text:
namespace ui {
namespace win {

namespace {

// Ensures that the Save As dialog is on-screen.
UINT_PTR CALLBACK SaveAsDialogHook(HWND dialog, UINT message,
                                   WPARAM wparam, LPARAM lparam) {
  static const UINT kPrivateMessage = 0x2F3F;
  switch (message) {
    case WM_INITDIALOG: {
      // Do nothing here. Just post a message to defer actual processing.
      ::PostMessage(dialog, kPrivateMessage, 0, 0);
      return TRUE;
    }
    case kPrivateMessage: {
      // The dialog box is the parent of the current handle.
      HWND real_dialog = ::GetParent(dialog);

      // Retrieve the final size.
      RECT dialog_rect;
      ::GetWindowRect(real_dialog, &dialog_rect);

      // Verify that the upper left corner is visible.
      POINT point = { dialog_rect.left, dialog_rect.top };
      HMONITOR monitor1 = ::MonitorFromPoint(point, MONITOR_DEFAULTTONULL);
      point.x = dialog_rect.right;
      point.y = dialog_rect.bottom;

      // Verify that the lower right corner is visible.
      HMONITOR monitor2 = ::MonitorFromPoint(point, MONITOR_DEFAULTTONULL);
      if (monitor1 && monitor2)
        return 0;

      // Some part of the dialog box is not visible, fix it by moving is to the
      // client rect position of the browser window.
      HWND parent_window = ::GetParent(real_dialog);
      if (!parent_window)
        return 0;
      WINDOWINFO parent_info;
      parent_info.cbSize = sizeof(WINDOWINFO);
      ::GetWindowInfo(parent_window, &parent_info);
      ::SetWindowPos(
          real_dialog,
          NULL,
          parent_info.rcClient.left,
          parent_info.rcClient.top,
          0,
          0,  // Size.
          SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOSIZE | SWP_NOZORDER);

      return 0;
    }
  }
  return 0;
}

}  // namespace

OpenFileName::OpenFileName(HWND parent_window, DWORD flags) {
  ::ZeroMemory(&openfilename_, sizeof(openfilename_));
  openfilename_.lStructSize = sizeof(openfilename_);

  // According to http://support.microsoft.com/?scid=kb;en-us;222003&x=8&y=12,
  // The lpstrFile Buffer MUST be NULL Terminated.
  filename_buffer_[0] = 0;
  openfilename_.lpstrFile = filename_buffer_;
  openfilename_.nMaxFile = arraysize(filename_buffer_);

  openfilename_.Flags = flags;
  openfilename_.hwndOwner = parent_window;
}

OpenFileName::~OpenFileName() {
}

void OpenFileName::SetFilters(
    const std::vector<base::Tuple<base::string16, base::string16>>& filters) {
  openfilename_.lpstrFilter = NULL;
  filter_buffer_.clear();
  if (filters.empty())
    return;
  for (const auto& filter : filters) {
    filter_buffer_.append(base::get<0>(filter));
    filter_buffer_.push_back(0);
    filter_buffer_.append(base::get<1>(filter));
    filter_buffer_.push_back(0);
  }
  filter_buffer_.push_back(0);
  openfilename_.lpstrFilter = filter_buffer_.c_str();
}

void OpenFileName::SetInitialSelection(const base::FilePath& initial_directory,
                                       const base::FilePath& initial_filename) {
  // First reset to the default case.
  // According to http://support.microsoft.com/?scid=kb;en-us;222003&x=8&y=12,
  // The lpstrFile Buffer MUST be NULL Terminated.
  filename_buffer_[0] = 0;
  openfilename_.lpstrFile = filename_buffer_;
  openfilename_.nMaxFile = arraysize(filename_buffer_);
  openfilename_.lpstrInitialDir = NULL;
  initial_directory_buffer_.clear();

  if (initial_directory.empty())
    return;

  initial_directory_buffer_ = initial_directory.value();
  openfilename_.lpstrInitialDir = initial_directory_buffer_.c_str();

  if (initial_filename.empty())
    return;

  // The filename is ignored if no initial directory is supplied.
  base::wcslcpy(filename_buffer_,
                initial_filename.value().c_str(),
                arraysize(filename_buffer_));
}

void OpenFileName::MaybeInstallWindowPositionHookForSaveAsOnXP() {
  if (base::win::GetVersion() >= base::win::VERSION_VISTA)
    return;

  openfilename_.Flags |= OFN_ENABLEHOOK;
  DCHECK(!openfilename_.lpfnHook);
  openfilename_.lpfnHook = &SaveAsDialogHook;
}

base::FilePath OpenFileName::GetSingleResult() {
  base::FilePath directory;
  std::vector<base::FilePath> filenames;
  GetResult(&directory, &filenames);
  if (filenames.size() != 1)
    return base::FilePath();
  return directory.Append(filenames[0]);
}

void OpenFileName::GetResult(base::FilePath* directory,
                             std::vector<base::FilePath>* filenames) {
  DCHECK(filenames->empty());
  const wchar_t* selection = openfilename_.lpstrFile;
  // The return value of |openfilename_.lpstrFile| is dependent on the
  // value of the Multi-Select flag within |openfilename_|. If the flag is
  // not set the return value will be a single null-terminated wide string.
  // If it is set it will be more than one null-terminated wide string, itself
  // terminated by an empty null-terminated wide string.
  if (openfilename_.Flags & OFN_ALLOWMULTISELECT) {
    while (*selection) {  // Empty string indicates end of list.
      filenames->push_back(base::FilePath(selection));
      // Skip over filename and null-terminator.
      selection += filenames->back().value().length() + 1;
    }
  } else {
    filenames->push_back(base::FilePath(selection));
  }
  if (filenames->size() == 1) {
    // When there is one file, it contains the path and filename.
    *directory = (*filenames)[0].DirName();
    (*filenames)[0] = (*filenames)[0].BaseName();
  } else if (filenames->size() > 1) {
    // Otherwise, the first string is the path, and the remainder are
    // filenames.
    *directory = (*filenames)[0];
    filenames->erase(filenames->begin());
  }
}

// static
void OpenFileName::SetResult(const base::FilePath& directory,
                             const std::vector<base::FilePath>& filenames,
                             OPENFILENAME* openfilename) {
  base::string16 filename_value;
  if (filenames.size() == 1) {
    filename_value = directory.Append(filenames[0]).value();
  } else {
    filename_value = directory.value();
    filename_value.push_back(0);
    for (std::vector<base::FilePath>::const_iterator it = filenames.begin();
         it != filenames.end();
         ++it) {
      filename_value.append(it->value());
      filename_value.push_back(0);
    }
  }
  if (filename_value.size() + 1 < openfilename->nMaxFile) {
    // Because the result has embedded nulls, we must memcpy.
    memcpy(openfilename->lpstrFile,
           filename_value.c_str(),
           (filename_value.size() + 1) * sizeof(filename_value[0]));
  } else if (openfilename->nMaxFile) {
    openfilename->lpstrFile[0] = 0;
  }
}

// static
std::vector<base::Tuple<base::string16, base::string16>>
OpenFileName::GetFilters(const OPENFILENAME* openfilename) {
  std::vector<base::Tuple<base::string16, base::string16>> filters;

  const base::char16* display_string = openfilename->lpstrFilter;
  if (!display_string)
    return filters;

  while (*display_string) {
    const base::char16* display_string_end = display_string;
    while (*display_string_end)
      ++display_string_end;
    const base::char16* pattern = display_string_end + 1;
    const base::char16* pattern_end = pattern;
    while (*pattern_end)
      ++pattern_end;
    filters.push_back(
        base::MakeTuple(base::string16(display_string, display_string_end),
                  base::string16(pattern, pattern_end)));
    display_string = pattern_end + 1;
  }

  return filters;
}

}  // namespace win
}  // namespace ui


text:
package org.apache.spark.sql.hive.thriftserver.sparklinedata.ui

import javax.servlet.http.HttpServletRequest
import org.apache.spark.sql.SPLLogging
import org.apache.spark.ui.{UIUtils, WebUIPage}
import org.sparklinedata.druid.metadata.{DruidQueryExecutionView, DruidQueryHistory}
import scala.xml.Node

private[ui] class DruidQueriesPage(parent: DruidQueriesTab) extends WebUIPage("") with SPLLogging {

  def render(request: HttpServletRequest): Seq[Node] = {
    val content = generateDruidStatsTable()
    UIUtils.headerSparkPage("Druid Query Details", content, parent, Some(5000))
  }

  private def generateDruidStatsTable(): Seq[Node] = {
    val numStatement = DruidQueryHistory.getHistory.size
    val table = if (numStatement > 0) {
      val headerRow = Seq("stageId", "partitionId", "taskAttemptId", "druidQueryServer",
        "druidSegIntervals", "startTime", "druidExecTime", "queryExecTime", "numRows",
        "druidQuery", "sql")
      val druidContent = DruidQueryHistory.getHistory
      def generateDataRow(info: DruidQueryExecutionView): Seq[Node] = {
        var interval = ""
        for(temp <- info.druidSegIntervals){
          interval += temp
        }
        val stageLink = "%s/stages/stage?id=%s&attempt=0"
          .format(UIUtils.prependBaseUri(parent.basePath), info.stageId)

           {info.stageId}

            {info.partitionId}

          {info.taskAttemptId}
          {info.druidQueryServer}
          {interval}
          {info.startTime}
          {info.druidExecTime}
          {info.queryExecTime}
          {info.numRows}
          {info.druidQuery}
          {info.sqlStmt.getOrElse("none")}

      }
      Some(UIUtils.listingTable(headerRow, generateDataRow,
        druidContent, false, None, Seq(null), false))
    } else {
      None
    }
    val content =

Druid Query Details
 ++

            {table.getOrElse("No queries have been executed yet.")}

    content
  }
}

redpajama_set_name: RedPajamaGithub


text:
@implementation DescribeWebView

- (void) beforeAll
{
    DTTraceLog();
	DTLog(@"DescribeWebView start");
	[super beforeAll];
	[[app.label.with text: @"Web"] flash].touch;
	[app wait: 1];
    [SpecsOutputData sendViewsMapWithName: NSStringFromClass([self class])];
}

- (void) afterAll
{
    DTTraceLog();
	[super afterAll];
	[[app.navigationItemButtonView flash] touch];
	DTLog(@"DescribeWebView finish");
}

- (void) itShouldSetValueToURL
{
    DTTraceLog();
	DTLog(@"BEGIN");
	UITextField* textField = app.textField;
    id viewController = [textField delegate];

    NSString* URL = [textField text];
    //NSLog(@"%@", URL);

    [textField setText: @"http://mail.ru"];
    [expectThat(textField.text) should: be(@"http://mail.ru")];

    [textField becomeFirstResponder];
	[[app view: @"UIKBKeyView"].all setUserInteractionEnabled: YES];
	[[app view: @"UIKBKeyView"] index: 0].touch;  // 5 - backspace
	[[app view: @"UIKBKeyView"] index: 0].touch;  // 5 - backspace

    [viewController textFieldShouldReturn: textField];

    //textField app.textField setText: 'http://www.mail.ru'

	[app wait: 5.0f];
	DTLog(@"END");
}

-(void) itShouldSetValue
{
    DTTraceLog();
	DTLog(@"BEGIN");
    // don't work!
    [app.webView setValue: @"UISpec"
         forElementWithId: @"gbqfq"];  // query
	[app wait: 0.5];
	DTLog(@"END");
}

-(void) itShouldClickButton
{
    DTTraceLog();
	DTLog(@"BEGIN");
	[app.webView clickElementWithId: @"b"];
	DTLog(@"END");
}

@end


text:
namespace chrono
{

/// Class to be used as a callback interface for some user defined
/// action to be taken each time a contact is added to the container.
/// It can be used to modify the friction value (as default it is the
/// average of the friction of the two bodies).
/// The user should implement an inherited class and
/// implement a custom ContactCallback() function.

class ChApi ChAddContactCallback
{
public:
			/// Callback, used to report contact points being added to the container.
			/// This must be implemented by a child class of ChAddContactCallback
	virtual void ContactCallback (const  collision::ChCollisionInfo& mcontactinfo, ///< get info about contact (cannot change it)
								  ChMaterialCouple&  material 			  		   ///< you can modify this!
								) = 0;
};

/// Class to be used as a callback interface for some user defined
/// action to be taken for each contact (already added to the container,
/// maybe with already computed forces).
/// The user should implement an inherited class and
/// implement a custom ReportContactCallback() function.

class ChApi ChReportContactCallback
{
public:
			/// Callback, used to report contact points already added to the container.
			/// This must be implemented by a child class of ChReportContactCallback.
			/// If returns false, the contact scanning will be stopped.
	virtual bool ReportContactCallback (
					const ChVector<>& pA,				///< get contact pA
					const ChVector<>& pB,				///< get contact pB
					const ChMatrix33<>& plane_coord,	///< get contact plane coordsystem (A column 'X' is contact normal)
					const double& distance,				///< get contact distance
					const float& mfriction,			  	///< get friction info
					const ChVector<>& react_forces,		///< get react.forces (if already computed). In coordsystem 'plane_coord'
					const ChVector<>& react_torques,	///< get react.torques, if rolling friction (if already computed).
					collision::ChCollisionModel* modA,	///< get model A (note: some containers may not support it and could be zero!)
					collision::ChCollisionModel* modB	///< get model B (note: some containers may not support it and could be zero!)
										) = 0;
};

///
/// Class representing a container of many contacts.
/// There might be implementations of this interface
/// in form of plain CPU linked lists of ChContact objects,
/// or highly optimized GPU buffers, etc. etc.
/// This is only the basic interface with the features that are in common.
///

class ChApi ChContactContainerBase : public ChPhysicsItem {

	CH_RTTI(ChContactContainerBase,ChPhysicsItem);

protected:
				//
	  			// DATA
				//

	ChAddContactCallback* add_contact_callback;
	ChReportContactCallback* report_contact_callback;
public:
				//
	  			// CONSTRUCTORS
				//

	ChContactContainerBase ()
				{
					add_contact_callback =0;
					report_contact_callback =0;
				};

	virtual ~ChContactContainerBase () {};

				//
	  			// FUNCTIONS
				//

					/// Tell the number of added contacts. To be implemented by child classes.
	virtual int  GetNcontacts  () = 0;

					/// Remove (delete) all contained contact data. To be implemented by child classes.
	virtual void RemoveAllContacts() = 0;

					/// The collision system will call BeginAddContact() before adding
					/// all contacts (for example with AddContact() or similar). By default
					/// it deletes all previous contacts. Custom more efficient implementations
					/// might reuse contacts if possible.
	virtual void BeginAddContact() { RemoveAllContacts(); }

					/// Add a contact between two models, storing it into this container.
					/// To be implemented by child classes.
					/// Some specialized child classes (ex. one that uses GPU buffers)
					/// could implement also other more efficient functions to add many contacts
					/// in a batch (so that, for example, a special GPU collision system can exploit it);
					/// yet most collision system might still fall back to this function if no other
					/// specialized add-functions are found.
	virtual void AddContact(const collision::ChCollisionInfo& mcontact) =0;

					/// The collision system will call EndAddContact() after adding
					/// all contacts (for example with AddContact() or similar). By default
					/// it does nothing.
	virtual void EndAddContact() {};

					/// Sets a callback to be used each time a contact point is
					/// added to the container. Note that not all child classes can
					/// support this function in all circumstances (example, the GPU container
					/// won't launch the callback for all its points because of performance optimization)
	void SetAddContactCallback(ChAddContactCallback* mcallback) {add_contact_callback = mcallback;}

					/// Scans all the contacts and for each contact exacutes the ReportContactCallback()
					/// function of the user object inherited from ChReportContactCallback.
					/// Child classes of ChContactContainerBase should try to implement this (although
					/// in some highly-optimized cases as in ChContactContainerGPU it could be impossible to
					/// report all contacts).
	virtual void ReportAllContacts(ChReportContactCallback* mcallback) =0;

};

//////////////////////////////////////////////////////
//////////////////////////////////////////////////////

} // END_OF_NAMESPACE____

#endif


text:
namespace RecordConstructorGenerator.Test
{
    class Sample
    {
    }
}


text:
package server.endpoint_6790700.client;

import java.net.ServerSocket;
import java.io.IOException;

/**
 * @author Jitendra Kotamraju
 */
public class Util {

    public static int getFreePort() {
        int port = -1;
        try {
               ServerSocket soc = new ServerSocket(0);
            port = soc.getLocalPort();
               soc.close();
        } catch (IOException e) {
        }
        return port;
    }

}


text:
package com.hourglassapps.cpi_ii.stem;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintWriter;
import java.io.Reader;

import com.hourglassapps.cpi_ii.stem.stempel.egothor.Compile;
import com.hourglassapps.util.Log;

public class MainGenStempelModel {
	private final static String TAG=MainGenStempelModel.class.getName();

	public static void main(String[] pArgs) throws IOException {
		if (pArgs.length < 1) {
			usage();
			return;
		}

		BufferedReader reader=null;
		try {
			if("-".equals(pArgs[0])) {
				reader=new BufferedReader(new InputStreamReader(System.in));
			} else {
				reader = new BufferedReader(new InputStreamReader(new FileInputStream(pArgs[0])));
			}

			PipedOutputStream outstream=new PipedOutputStream();

			if (pArgs.length < 3) {
				final Reader pipe=new InputStreamReader(new PipedInputStream(outstream));
				final String outFilename=pArgs[1];
				Thread compiler=new Thread(new Runnable() {

					@Override
					public void run() {
						try {
							Compile.compileFromReader(pipe, new String[]{ "latin", outFilename});
						} catch (IOException e) {
							Log.e(TAG, e);
						}
					}});
				compiler.start();
			} else {
				usage();
				return;
			}

			try(PrintWriter writer=new PrintWriter(outstream)) {
				String lemma, lastLemma, variant;
				lemma=reader.readLine();
				lastLemma=null;
				StringBuffer outLine = new StringBuffer();
				boolean first=true;
				while(lemma!=null) {
					variant=reader.readLine();
					assert(variant!=null);
					if(lemma.equals(lastLemma)) {
						outLine.append(' ').append(variant);
					} else {
						if(first) {
							first=false;
						} else {
							writer.println(outLine);
						}
						outLine.delete(0, outLine.length());
						outLine.append(lemma).append(' ').append(variant);
						lastLemma=lemma;
					}

					lemma=reader.readLine();
				}
				writer.println(outLine);
			}
		} finally {
			if(reader!=null) {
				reader.close();
			}
		}

	}

		private static void usage() {
			System.out.println("Args: -input <IN_FILE> -out <OUT_FILE>");
		}
}


text:
<?php
	class CustomersController extends \BaseController{

		public function index()
		{
			$customers = Customer::all();

			foreach ($customers as $key => $customer) {
				$customers[$key]->birthday = date("d/m/Y", strtotime($customers[$key]->birthday));
			}

			return View::make('customers.index')->with('customers', $customers);
		}

		/**
	     * Show the form for creating a new resource.
	     *
	     * @return Response
	     */
		public function create()
	    {
	        return View::make('customers.edit');
	    }

		/**
	     * Store a newly created resource in storage.
	     *
	     * @return Response
	     */
	    public function store()
	    {
	        // Inser the data on base.
	        try
	        {
	            DB::beginTransaction();

	            $customer = new Customer;

	            $customer->name     = Input::get('name');
	            $customer->address  = Input::get('address');
	            $customer->phone    = Input::get('phone');
	            $customer->rg       = Input::get('rg');
	            $customer->cpf      = Input::get('cpf');
	            $customer->birthday = date("Y-m-d", strtotime(Input::get('birthday')));

	            $customer->save();

	            DB::commit();

	            // redirect
	            return Redirect::to('customers')->with('flash_notice', 'Cliente criado com sucesso!');
	        }
	        catch (Exception $e)
	        {
	            DB::rollback();

	            return Redirect::route('customers.create')->with('flash_error', 'Ocorreu um erro ao criar o cliente.')->withInput();
	        }
	    }

	    /**
	     * Show the form for editing the specified resource.
	     *
	     * @param  int  $id
	     * @return Response
	     */
	    public function edit($id)
	    {
	        //
	        $data = array();

	        $customer = Customer::findOrFail($id);

	        $data['customer'] = $customer;

	        $data['customer']->birthday = date("d/m/Y", strtotime($data['customer']->birthday));

	        return View::make('customers.edit')->with('data', $data);
	    }

	        /**
	     * Store a newly created resource in storage.
	     *
	     * @return Response
	     */
	    public function update($id)
	    {
	        // Inser the data on base.
	        try
	        {
	            DB::beginTransaction();

	            $customer = Customer::findOrFail($id);

	            $customer->name         = Input::get('name');
	            $customer->address         = Input::get('address');
	            $customer->phone         = Input::get('phone');
	            $customer->rg         = Input::get('rg');
	            $customer->cpf         = Input::get('cpf');
	            $customer->birthday         = date("Y-m-d", strtotime(Input::get('birthday')));

	            $customer->save();

	            DB::commit();

	            // redirect
	            return Redirect::to('customers')->with('flash_notice', 'Cliente atualizado com sucesso!');
	        }
	        catch (Exception $e)
	        {
	            DB::rollback();

	            return Redirect::route('customers.create')->with('flash_error', 'Ocorreu um erro ao atualizar o cliente.')->withInput();
	        }
	    }

	    /**
	     * Remove the specified resource from storage.
	     *
	     * @param  int  $id
	     * @return Response
	     */
	    public function destroy($id)
	    {
	        //
	        try
	        {

	            DB::beginTransaction();
	            // delete
	            $customer = Customer::find($id);
	            $customer->delete();

	            DB::commit();

	            // redirect
	            return Redirect::to('customers')->with('flash_notice', 'Cliente deletado com sucesso!');
	        }
	        catch (Exception $e)
	        {
	            DB::rollback();

	            return Redirect::to('customers')->with('flash_error', 'Erro ao tentar deletar o cliente!');
	        }
	    }

	}
?>


text:
#pragma once

#include <map>
#include <string>
using namespace std;

/*
 * A false start from the Ukkonen's algorithm
 * The standard compressed trie force a node at the end
 * of a string inserted, so this essentially fall back to
 * a uncompressed trie
 */
class SuffixTree2
{
public:
    SuffixTree2();
    ~SuffixTree2();
    void  Add(const string key);
    string Show() const;
private:
    class SuffixTree2Edge;

    class SuffixTree2Node
    {
    public:
        SuffixTree2Node();
        ~SuffixTree2Node();
        map<char, SuffixTree2Edge*> m_children;
    };

    class SuffixTree2Edge
    {
    public:
        SuffixTree2Edge();
        ~SuffixTree2Edge();
        string m_edgeLabel;
        SuffixTree2Node* m_child;
    };

    SuffixTree2Node* m_root;
};


text:
# LiteNetLib 1.0 indev

Lite reliable UDP library for .NET Standard 2.0 (Mono, .NET Core, .NET Framework)

[![Made in Ukraine](https://img.shields.io/badge/made_in-ukraine-ffd700.svg?labelColor=0057b7)](https://stand-with-ukraine.pp.ua)

[!["Buy Me A Coffee"](https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png)](https://www.buymeacoffee.com/revx)

`BTC:bc1qn3lwhafsp7ka0r5lew0v7r3qnpj62atqju809n`

`LTC:LTQqo9yjGVWrXahAByqvx9Jo5TaotjDKXJ`

`ETH:0x78664986894932bD399B1539D9F65155D0BF55bd`

**Discord chat**: [![Discord](https://img.shields.io/discord/501682175930925058.svg)](https://discord.gg/FATFPdy)

[OLD BRANCH (and examples) for 0.9.x](https://github.com/RevenantX/LiteNetLib/tree/0.9)

[Little Game Example on Unity](https://github.com/RevenantX/NetGameExample)

[Documentation](https://revenantx.github.io/LiteNetLib/index.html)

## Build

### [NuGet](https://www.nuget.org/packages/LiteNetLib/) [![NuGet](https://img.shields.io/nuget/v/LiteNetLib?color=blue)](https://www.nuget.org/packages/LiteNetLib/) [![NuGet](https://img.shields.io/nuget/vpre/LiteNetLib)](https://www.nuget.org/packages/LiteNetLib/#versions-body-tab) [![NuGet](https://img.shields.io/nuget/dt/LiteNetLib)](https://www.nuget.org/packages/LiteNetLib/)

### [Release builds](https://github.com/RevenantX/LiteNetLib/releases) [![GitHub (pre-)release](https://img.shields.io/github/release/RevenantX/LiteNetLib/all.svg)](https://github.com/RevenantX/LiteNetLib/releases)

### [DLL build from master](https://ci.appveyor.com/project/RevenantX/litenetlib/branch/master/artifacts) [![](https://ci.appveyor.com/api/projects/status/354501wnvxs8kuh3/branch/master?svg=true)](https://ci.appveyor.com/project/RevenantX/litenetlib/branch/master)
( Warning! Master branch can be unstable! )

## Features

* Lightweight
  * Small CPU and RAM usage
  * Small packet size overhead ( 1 byte for unreliable, 4 bytes for reliable packets )
* Simple connection handling
* Peer to peer connections
* Helper classes for sending and reading messages
* Multiple data channels
* Different send mechanics
  * Reliable with order
  * Reliable without order
  * Reliable sequenced (realiable only last packet)
  * Ordered but unreliable with duplication prevention
  * Simple UDP packets without order and reliability
* Fast packet serializer [(Usage manual)](https://revenantx.github.io/LiteNetLib/articles/netserializerusage.html)
* Automatic small packets merging
* Automatic fragmentation of reliable packets
* Automatic MTU detection
* Optional CRC32C checksums
* UDP NAT hole punching
* NTP time requests
* Packet loss and latency simulation
* IPv6 support (dual mode)
* Connection statisitcs
* Multicasting (for discovering hosts in local network)
* Unity support
* Supported platforms:
  * Windows/Mac/Linux (.NET Framework, Mono, .NET Core, .NET Standard)
  * Lumin OS (Magic Leap)
  * Monogame
  * Godot
  * Unity 2018.3 (Desktop platforms, Android, iOS, Switch)

## Unity notes!!!
* Minimal supported Unity is 2018.3. For older Unity versions use [0.9.x library](https://github.com/RevenantX/LiteNetLib/tree/0.9) versions
* Always use library sources instead of precompiled DLL files ( because there are platform specific #ifdefs and workarounds for unity bugs )

## Usage samples

### Client
```csharp
EventBasedNetListener listener = new EventBasedNetListener();
NetManager client = new NetManager(listener);
client.Start();
client.Connect("localhost" /* host ip or name */, 9050 /* port */, "SomeConnectionKey" /* text key or NetDataWriter */);
listener.NetworkReceiveEvent += (fromPeer, dataReader, deliveryMethod) =>
{
    Console.WriteLine("We got: {0}", dataReader.GetString(100 /* max length of string */));
    dataReader.Recycle();
};

while (!Console.KeyAvailable)
{
    client.PollEvents();
    Thread.Sleep(15);
}

client.Stop();
```
### Server
```csharp
EventBasedNetListener listener = new EventBasedNetListener();
NetManager server = new NetManager(listener);
server.Start(9050 /* port */);

listener.ConnectionRequestEvent += request =>
{
    if(server.ConnectedPeersCount < 10 /* max connections */)
        request.AcceptIfKey("SomeConnectionKey");
    else
        request.Reject();
};

listener.PeerConnectedEvent += peer =>
{
    Console.WriteLine("We got connection: {0}", peer.EndPoint); // Show peer ip
    NetDataWriter writer = new NetDataWriter();                 // Create writer class
    writer.Put("Hello client!");                                // Put some string
    peer.Send(writer, DeliveryMethod.ReliableOrdered);             // Send with reliability
};

while (!Console.KeyAvailable)
{
    server.PollEvents();
    Thread.Sleep(15);
}
server.Stop();
```


text:
(function($){
  $(function(){

    var window_width = $(window).width();

    $('.button-collapse').sideNav({'edge': 'left'});

  });
})(jQuery);


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Profile</title>

    <link href="bootstrapcss/bootstrap-glyphicons.css" rel="stylesheet">
    <link rel="stylesheet" href="bootstrapcss/bootstrap.min.css">

    <link rel="stylesheet" href="cssFiles/index.css">
    <link rel="stylesheet" href="cssFiles/profile.css">

            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#mynavbar" aria-expanded="false" aria-controls="navbar">
                Toggle navigation

            </button>

 <button type="button" class="btn btn-default btn-lg" id="editPreferences" onclick="editPreferences()" style="width:100%;background-color: #31b0d5;border-color: #31b0d5;">Edit Preferences</button>

<button type="button"  class="btn btn-default btn-lg" onclick="getEventLikes()" style="width:100%;background-color: #31b0d5;"> Liked Events</button>

<button type="button" class="btn btn-default btn-lg" id="logoutButton" onclick="logout()" style="width:100%;background-color: #31b0d5;"> Logout</button>

        Welcome to WHAM!

                What's Happening

                Around Me?

                Location
                    <input type="text" class="form-control" placeholder="Boston, MA" id="loc">

                Category
                    <input type="text" class="form-control" placeholder="Music, Arts, etc." id="cat">

            <button class="btn btn-default btn-sm" id="search" onclick="search()">
                Search Events
            </button>

        Discover Events, Like and Away you go.

            <button id="moreResults" class="btn btn-block btn-success" onclick="moreResults()">MORE EVENTS</button>

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Set Your Preferences

Music

Food & Drink

Parties

Yoga

Meetups

Sports

Movies

Farmer's Market

Festivals

                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button onclick="getListPref()" type="button" class="btn btn-primary">Save changes</button>

Events you liked previously

                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>


text:
import BaseBlockNode from './BaseBlockNode';
import {Context} from '../compiler/context';
import ContextBuilder from '../contextBuilder';
import ObjectDeclarationHLIR from '../hlirNodes/ObjectDeclarationHLIR';
import * as symbols from '../symbols';

const BUILDER = Symbol();

export default class ObjectDeclarationNode extends BaseBlockNode {
    constructor(
                name,
                objConstructor,
                members,
                methods,
                attributes,
                operators,
                start,
                end
            ) {
        super(start, end);

        this.name = name;
        this.attributes = attributes;
        this.members = members;
        this.objConstructor = objConstructor;
        this.methods = methods;
        this.operators = operators;
    }

    get id() {
        return 20;
    }

    pack(bitstr) {
        super.pack(bitstr);
        this.packStr(bitstr, this.name);
        bitstr.writebits(!!this.objConstructor, 1);
        this.packBlock(bitstr, 'attributes');
        if (this.objConstructor) this.objConstructor.pack(bitstr);
        this.packBlock(bitstr, 'members');
        this.packBlock(bitstr, 'methods');
        this.packBlock(bitstr, 'operators');
    }

    traverse(cb) {
        this.params.forEach(p => cb(p, 'params'));
        this.body.forEach(s => cb(s, 'body'));
    }

    toString() {
        return 'object ' + this.name +
            (this.attributes.length ? '<' + this.attributes.map(a => a.toString()).join(', ') + '>' : '') +
            ' {\n' +
            (this.objConstructor ? this.objConstructor.toString() : '') +
            this.members.map(m => m.toString()).join('') +
            this.methods.map(m => m.toString()).join('') +
            this.operators.map(o => o.toString()).join('') +
            '}\n';
    }

    [symbols.FMAKEHLIR](builder) {
        builder.peekCtx().registerPrototype(this.name, this);
        return [];
    }

    [symbols.FCONSTRUCT](rootCtx, attributes) {
        if (attributes.length !== this.attributes.length) {
            let passedAttrs = '<' + attributes.map(a => a.toString()).join(', ') + '>';
            let currentAttrs = '<' + this.attributes.join(', ') + '>';
            throw this.TypeError(
                'Expected ' + this.attributes.length + ' attribute(s) (' + currentAttrs + ') ' +
                'but got ' + attributes.length + ' attribute(s) (' + passedAttrs + ') for ' +
                this.name
            );
        }

        var mappedAttributes = new Map();
        this.attributes.forEach((a, i) => {
            mappedAttributes.set(a.name, attributes[i]);
        });

        var node = new ObjectDeclarationHLIR(this.name, mappedAttributes);

        var builder = new ContextBuilder(rootCtx.env, rootCtx.privileged);
        builder.pushCtx(rootCtx);

        var ctx = new Context(rootCtx.env, node, rootCtx, rootCtx.privileged);
        builder.pushCtx(ctx);

        mappedAttributes.forEach((type, name) => {
            ctx.typeDefs.set(name, type);
        });

        node[symbols.ASSIGNED_NAME] = rootCtx.env.namer();
        node[symbols.CONTEXT] = ctx;
        node[symbols.IS_CONSTRUCTED] = true;
        node[BUILDER] = builder;

        node.setMembers(
            this.members.map(m => m[symbols.FMAKEHLIR](builder))
        );

        return node;
    }

    bindContents(node) {
        if (!(node instanceof ObjectDeclarationHLIR)) {
            throw new Error('Attempting to bind to invalid HLIR node');
        }
        var builder = node[BUILDER];
        if (!(builder instanceof ContextBuilder)) {
            throw new Error('Attempting to bind object declaration methods with invalid context builder');
        }

        delete node[BUILDER];

        const constructionTasks = new Set();

        if (this.objConstructor) {
            let hlir = this.objConstructor[symbols.FMAKEHLIR](builder);
            node.setConstructor(hlir);
            constructionTasks.add(() => this.objConstructor[symbols.FCONSTRUCT](builder, hlir));
        }
        node.setMethods(
            this.methods.map(m => {
                var hlir = m[symbols.FMAKEHLIR](builder);
                constructionTasks.add(() => m[symbols.FCONSTRUCT](builder, hlir));
                return hlir;
            })
        );
        node.setOperatorStatements(
            this.operators.map(o => {
                var hlir = o[symbols.FMAKEHLIR](builder);
                constructionTasks.add(() => o[symbols.FCONSTRUCT](builder, hlir));
                return hlir;
            })
        );

        return constructionTasks;
    }

};


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="AppTheme" parent="@android:style/Theme.Holo">
    </style>
    <style name="CrashTheme" parent="@android:style/Theme.Holo.NoActionBar">
        <item name="android:windowBackground">@color/primaryDark</item>
    </style>
</resources>


text:
package com.cloud.hypervisor.kvm.resource;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.naming.ConfigurationException;

import com.cloud.utils.StringUtils;
import com.cloud.utils.net.NetUtils;
import com.cloud.utils.script.OutputInterpreter;
import com.google.common.base.Strings;
import org.apache.log4j.Logger;
import org.libvirt.LibvirtException;

import com.cloud.agent.api.to.NicTO;
import com.cloud.exception.InternalErrorException;
import com.cloud.network.Networks;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.script.Script;

public class BridgeVifDriver extends VifDriverBase {

    private static final Logger s_logger = Logger.getLogger(BridgeVifDriver.class);
    private int _timeout;

    private final Object _vnetBridgeMonitor = new Object();
    private String _modifyVlanPath;
    private String _modifyVxlanPath;
    private String _controlCidr = NetUtils.getLinkLocalCIDR();
    private Long libvirtVersion;

    @Override
    public void configure(Map<String, Object> params) throws ConfigurationException {

        super.configure(params);

        getPifs();

        // Set the domr scripts directory
        params.put("domr.scripts.dir", "scripts/network/domr/kvm");

        String networkScriptsDir = (String)params.get("network.scripts.dir");
        if (networkScriptsDir == null) {
            networkScriptsDir = "scripts/vm/network/vnet";
        }

        String controlCidr = (String)params.get("control.cidr");
        if (StringUtils.isNotBlank(controlCidr)) {
            _controlCidr = controlCidr;
        }

        String value = (String)params.get("scripts.timeout");
        _timeout = NumbersUtil.parseInt(value, 30 * 60) * 1000;

        _modifyVlanPath = Script.findScript(networkScriptsDir, "modifyvlan.sh");
        if (_modifyVlanPath == null) {
            throw new ConfigurationException("Unable to find modifyvlan.sh");
        }
        _modifyVxlanPath = Script.findScript(networkScriptsDir, "modifyvxlan.sh");
        if (_modifyVxlanPath == null) {
            throw new ConfigurationException("Unable to find modifyvxlan.sh");
        }

        libvirtVersion = (Long) params.get("libvirtVersion");
        if (libvirtVersion == null) {
            libvirtVersion = 0L;
        }
    }

    public void getPifs() {
        final File dir = new File("/sys/devices/virtual/net");
        final File[] netdevs = dir.listFiles();
        final List<String> bridges = new ArrayList<String>();
        for (File netdev : netdevs) {
            final File isbridge = new File(netdev.getAbsolutePath() + "/bridge");
            final String netdevName = netdev.getName();
            s_logger.debug("looking in file " + netdev.getAbsolutePath() + "/bridge");
            if (isbridge.exists()) {
                s_logger.debug("Found bridge " + netdevName);
                bridges.add(netdevName);
            }
        }

        String guestBridgeName = _libvirtComputingResource.getGuestBridgeName();
        String publicBridgeName = _libvirtComputingResource.getPublicBridgeName();

        for (final String bridge : bridges) {
            s_logger.debug("looking for pif for bridge " + bridge);
            final String pif = getPif(bridge);
            if (_libvirtComputingResource.isPublicBridge(bridge)) {
                _pifs.put("public", pif);
            }
            if (guestBridgeName != null && bridge.equals(guestBridgeName)) {
                _pifs.put("private", pif);
            }
            _pifs.put(bridge, pif);
        }

        // guest(private) creates bridges on a pif, if private bridge not found try pif direct
        // This addresses the unnecessary requirement of someone to create an unused bridge just for traffic label
        if (_pifs.get("private") == null) {
            s_logger.debug("guest(private) traffic label '" + guestBridgeName + "' not found as bridge, looking for physical interface");
            final File dev = new File("/sys/class/net/" + guestBridgeName);
            if (dev.exists()) {
                s_logger.debug("guest(private) traffic label '" + guestBridgeName + "' found as a physical device");
                _pifs.put("private", guestBridgeName);
            }
        }

        // public creates bridges on a pif, if private bridge not found try pif direct
        // This addresses the unnecessary requirement of someone to create an unused bridge just for traffic label
        if (_pifs.get("public") == null) {
            s_logger.debug("public traffic label '" + publicBridgeName+ "' not found as bridge, looking for physical interface");
            final File dev = new File("/sys/class/net/" + publicBridgeName);
            if (dev.exists()) {
                s_logger.debug("public traffic label '" + publicBridgeName + "' found as a physical device");
                _pifs.put("public", publicBridgeName);
            }
        }

        s_logger.debug("done looking for pifs, no more bridges");
    }

    private String getPif(final String bridge) {
        String pif = matchPifFileInDirectory(bridge);
        final File vlanfile = new File("/proc/net/vlan/" + pif);

        if (vlanfile.isFile()) {
            pif = Script.runSimpleBashScript("grep ^Device\\: /proc/net/vlan/" + pif + " | awk {'print $2'}");
        }

        return pif;
    }

    private String matchPifFileInDirectory(final String bridgeName) {
        final File brif = new File("/sys/devices/virtual/net/" + bridgeName + "/brif");

        if (!brif.isDirectory()) {
            final File pif = new File("/sys/class/net/" + bridgeName);
            if (pif.isDirectory()) {
                // if bridgeName already refers to a pif, return it as-is
                return bridgeName;
            }
            s_logger.debug("failing to get physical interface from bridge " + bridgeName + ", does " + brif.getAbsolutePath() + "exist?");
            return "";
        }

        final File[] interfaces = brif.listFiles();

        for (File anInterface : interfaces) {
            final String fname = anInterface.getName();
            s_logger.debug("matchPifFileInDirectory: file name '" + fname + "'");
            if (LibvirtComputingResource.isInterface(fname)) {
                return fname;
            }
        }

        s_logger.debug("failing to get physical interface from bridge " + bridgeName + ", did not find an eth*, bond*, team*, vlan*, em*, p*p*, ens*, eno*, enp*, or enx* in " + brif.getAbsolutePath());
        return "";
    }

    protected boolean isBroadcastTypeVlanOrVxlan(final NicTO nic) {
        return nic != null && (nic.getBroadcastType() == Networks.BroadcastDomainType.Vlan
                || nic.getBroadcastType() == Networks.BroadcastDomainType.Vxlan);
    }

    protected boolean isValidProtocolAndVnetId(final String vNetId, final String protocol) {
        return vNetId != null && protocol != null && !vNetId.equalsIgnoreCase("untagged");
    }

    @Override
    public LibvirtVMDef.InterfaceDef plug(NicTO nic, String guestOsType, String nicAdapter, Map<String, String> extraConfig) throws InternalErrorException, LibvirtException {

        if (s_logger.isDebugEnabled()) {
            s_logger.debug("nic=" + nic);
            if (nicAdapter != null && !nicAdapter.isEmpty()) {
                s_logger.debug("custom nic adapter=" + nicAdapter);
            }
        }

        LibvirtVMDef.InterfaceDef intf = new LibvirtVMDef.InterfaceDef();

        String vNetId = null;
        String protocol = null;
        if (isBroadcastTypeVlanOrVxlan(nic)) {
            vNetId = Networks.BroadcastDomainType.getValue(nic.getBroadcastUri());
            protocol = Networks.BroadcastDomainType.getSchemeValue(nic.getBroadcastUri()).scheme();
        } else if (nic.getBroadcastType() == Networks.BroadcastDomainType.Lswitch) {
            throw new InternalErrorException("Nicira NVP Logicalswitches are not supported by the BridgeVifDriver");
        }
        String trafficLabel = nic.getName();
        Integer networkRateKBps = 0;
        if (libvirtVersion > ((10 * 1000 + 10))) {
            networkRateKBps = (nic.getNetworkRateMbps() != null && nic.getNetworkRateMbps().intValue() != -1) ? nic.getNetworkRateMbps().intValue() * 128 : 0;
        }

        if (nic.getType() == Networks.TrafficType.Guest) {
            if (isBroadcastTypeVlanOrVxlan(nic) && isValidProtocolAndVnetId(vNetId, protocol)) {
                    if (trafficLabel != null && !trafficLabel.isEmpty()) {
                        s_logger.debug("creating a vNet dev and bridge for guest traffic per traffic label " + trafficLabel);
                        String brName = createVnetBr(vNetId, trafficLabel, protocol);
                        intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps);
                    } else {
                        String brName = createVnetBr(vNetId, "private", protocol);
                        intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps);
                    }
            } else {
                String brname = "";
                if (trafficLabel != null && !trafficLabel.isEmpty()) {
                    brname = trafficLabel;
                } else {
                    brname = _bridges.get("guest");
                }
                intf.defBridgeNet(brname, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps);
            }
        } else if (nic.getType() == Networks.TrafficType.Control) {
            /* Make sure the network is still there */
            createControlNetwork();
            intf.defBridgeNet(_bridges.get("linklocal"), null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter));
        } else if (nic.getType() == Networks.TrafficType.Public) {
            if (isBroadcastTypeVlanOrVxlan(nic) && isValidProtocolAndVnetId(vNetId, protocol)) {
                if (trafficLabel != null && !trafficLabel.isEmpty()) {
                    s_logger.debug("creating a vNet dev and bridge for public traffic per traffic label " + trafficLabel);
                    String brName = createVnetBr(vNetId, trafficLabel, protocol);
                    intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps);
                } else {
                    String brName = createVnetBr(vNetId, "public", protocol);
                    intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps);
                }
            } else {
                intf.defBridgeNet(_bridges.get("public"), null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps);
            }
        } else if (nic.getType() == Networks.TrafficType.Management) {
            intf.defBridgeNet(_bridges.get("private"), null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter));
        } else if (nic.getType() == Networks.TrafficType.Storage) {
            String storageBrName = nic.getName() == null ? _bridges.get("private") : nic.getName();
            intf.defBridgeNet(storageBrName, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter));
        }
        if (nic.getPxeDisable()) {
            intf.setPxeDisable(true);
        }

        return intf;
    }

    @Override
    public void unplug(LibvirtVMDef.InterfaceDef iface) {
        deleteVnetBr(iface.getBrName());
    }

    @Override
    public void attach(LibvirtVMDef.InterfaceDef iface) {
        Script.runSimpleBashScript("ip link set " + iface.getDevName() + " master " +  iface.getBrName());
    }

    @Override
    public void detach(LibvirtVMDef.InterfaceDef iface) {
        Script.runSimpleBashScript("test -d /sys/class/net/" + iface.getBrName() + "/brif/" + iface.getDevName() + " && ip link set " + iface.getDevName() + " nomaster");
    }

    private String generateVnetBrName(String pifName, String vnetId) {
        return "br" + pifName + "-" + vnetId;
    }

    private String generateVxnetBrName(String pifName, String vnetId) {
        return "brvx-" + vnetId;
    }

    private String createVnetBr(String vNetId, String pifKey, String protocol) throws InternalErrorException {
        String nic = _pifs.get(pifKey);
        if (nic == null) {
            // if not found in bridge map, maybe traffic label refers to pif already?
            File pif = new File("/sys/class/net/" + pifKey);
            if (pif.isDirectory()) {
                nic = pifKey;
            }
        }
        String brName = "";
        if (protocol.equals(Networks.BroadcastDomainType.Vxlan.scheme())) {
            brName = generateVxnetBrName(nic, vNetId);
        } else {
            brName = generateVnetBrName(nic, vNetId);
        }
        createVnet(vNetId, nic, brName, protocol);
        return brName;
    }

    private void createVnet(String vnetId, String pif, String brName, String protocol) throws InternalErrorException {
        synchronized (_vnetBridgeMonitor) {
            String script = _modifyVlanPath;
            if (protocol.equals(Networks.BroadcastDomainType.Vxlan.scheme())) {
                script = _modifyVxlanPath;
            }
            final Script command = new Script(script, _timeout, s_logger);
            command.add("-v", vnetId);
            command.add("-p", pif);
            command.add("-b", brName);
            command.add("-o", "add");

            final String result = command.execute();
            if (result != null) {
                throw new InternalErrorException("Failed to create vnet " + vnetId + ": " + result);
            }
        }
    }

    private void deleteVnetBr(String brName) {
        synchronized (_vnetBridgeMonitor) {
            String cmdout = Script.runSimpleBashScript("ls /sys/class/net/" + brName);
            if (cmdout == null)
                // Bridge does not exist
                return;
            cmdout = Script.runSimpleBashScript("ls /sys/class/net/" + brName + "/brif | tr '\n' ' '");
            if (cmdout != null && cmdout.contains("vnet")) {
                // Active VM remains on that bridge
                return;
            }

            Pattern oldStyleBrNameRegex = Pattern.compile("^cloudVirBr(\\d+)$");
            Pattern brNameRegex = Pattern.compile("^br(\\S+)-(\\d+)$");
            Matcher oldStyleBrNameMatcher = oldStyleBrNameRegex.matcher(brName);
            Matcher brNameMatcher = brNameRegex.matcher(brName);

            String pName = null;
            String vNetId = null;
            if (oldStyleBrNameMatcher.find()) {
                // Actually modifyvlan.sh doesn't require pif name when deleting its bridge so far.
                pName = "undefined";
                vNetId = oldStyleBrNameMatcher.group(1);
            } else if (brNameMatcher.find()) {
                if (brNameMatcher.group(1) != null || !brNameMatcher.group(1).isEmpty()) {
                    pName = brNameMatcher.group(1);
                } else {
                    pName = "undefined";
                }
                vNetId = brNameMatcher.group(2);
            }

            if (vNetId == null || vNetId.isEmpty()) {
                s_logger.debug("unable to get a vNet ID from name " + brName);
                return;
            }

            String scriptPath = null;
            if (cmdout != null && cmdout.contains("vxlan")) {
                scriptPath = _modifyVxlanPath;
            } else {
                scriptPath = _modifyVlanPath;
            }

            final Script command = new Script(scriptPath, _timeout, s_logger);
            command.add("-o", "delete");
            command.add("-v", vNetId);
            command.add("-p", pName);
            command.add("-b", brName);

            final String result = command.execute();
            if (result != null) {
                s_logger.debug("Delete bridge " + brName + " failed: " + result);
            }
        }
    }

    private void deleteExistingLinkLocalRouteTable(String linkLocalBr) {
        Script command = new Script("/bin/bash", _timeout);
        command.add("-c");
        command.add("ip route | grep " + _controlCidr);
        OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser();
        String result = command.execute(parser);
        boolean foundLinkLocalBr = false;
        if (result == null && parser.getLines() != null) {
            String[] lines = parser.getLines().split("\\n");
            for (String line : lines) {
                String[] tokens = line.split(" ");
                if (tokens != null && tokens.length < 2) {
                    continue;
                }
                final String device = tokens[2];
                if (!Strings.isNullOrEmpty(device) && !device.equalsIgnoreCase(linkLocalBr)) {
                    Script.runSimpleBashScript("ip route del " + _controlCidr + " dev " + tokens[2]);
                } else {
                    foundLinkLocalBr = true;
                }
            }
        }

        if (!foundLinkLocalBr) {
            Script.runSimpleBashScript("ip address add " + NetUtils.getLinkLocalAddressFromCIDR(_controlCidr) + " dev " + linkLocalBr);
            Script.runSimpleBashScript("ip route add " + _controlCidr + " dev " + linkLocalBr + " src " + NetUtils.getLinkLocalGateway(_controlCidr));
        }
    }

    private void createControlNetwork() {
        createControlNetwork(_bridges.get("linklocal"));
    }

    @Override
    public void createControlNetwork(String privBrName)  {
        deleteExistingLinkLocalRouteTable(privBrName);
        if (!isExistingBridge(privBrName)) {
            Script.runSimpleBashScript("ip link add name " + privBrName + " type bridge");
            Script.runSimpleBashScript("ip link set " + privBrName + " up");
            Script.runSimpleBashScript("ip address add " + NetUtils.getLinkLocalAddressFromCIDR(_controlCidr) + " dev " + privBrName);
        }
    }

    @Override
    public boolean isExistingBridge(String bridgeName) {
        File f = new File("/sys/devices/virtual/net/" + bridgeName + "/bridge");
        if (f.exists()) {
            return true;
        } else {
            return false;
        }
    }
}


text:
export const Factory = {
    createTx (type) {
        const selectedAccount = Session.get("selectedAccount");
        let account = undefined;
        if (selectedAccount) {
            account = selectedAccount;
        } else {
            account = MoneyAccounts.findOne()._id;
            Session.set("selectedAccount", account);
        }
        return {
            amount: undefined,
            account: account,
            createdAt: new Date(),
            type: type,
            description: "",
            tags: []
        };
    }
};


text:
/*
 * This javascript file supports the robot_control.html page.
 * It was pulled out of the html page itself when the page
 * was mustache-templated. For some reason, the mustache
 * engine kind of whacks things up. It's better to separate
 * the javascript anyway IMHO.
 */
var wsUri = "wss://giskard:8081/";

function addRobotOption(robot, selected) {
  var options = getCurrentRobotOptions();
  options.push(robot);
  return formatOptions(options, selected);
}

function removeRobotOption(robot, selected) {
  var options = getCurrentRobotOptions();
  var indexOfRobot = options.indexOf(robot);
  options.splice(indexOfRobot, 1);
  return formatOptions(options, selected);
}

function formatOptions(options, selected) {
  var optionHtml = "";
  for (var i=0; i<options.length; i++) {
    optionHtml += "<option value='" + options[i] + "'";
    if (options[i] === selected) {
      optionHtml += " selected";
    }
    optionHtml += ">" + options[i] + "</option>";
  }
  return optionHtml;
}

function getCurrentRobotOptions() {
  var options = $('#robot_id option');

  var values = $.map(options ,function(option) {
      return option.value;
    });
  return values;
}

/**
 * Issue the robot a command
 */
function issueCommand(command) {
  var robotId = $( "#robot_id" ).val()
  var re = /is not registered/;
  if ( robotId ) {
    $.ajax({url: "/robot/commands/"+command+"?robot="+robotId, success:function(result) {
        if (result.match(re)) {
          alert(result);
        } else {
          $("#div_result").html(result);
        }
    }});
  } else {
    alert("Must specify a robot id")
  }
}

function handleKeypress(event) {
  event.preventDefault();
  switch (event.which) {
    case 32: // Space
      case 83: // S
      case 115: // s
        command = 'stop';
        $("#currentCommand").val(command);
        break;
      case 70: // F
      case 102: // f
        if ($("#currentCommand").val() === 'forward') {
          command = 'speed_up';
        } else {
          command = 'forward';
          $("#currentCommand").val(command);
        }
        break;
      case 66: // B
      case 98: // b
        if ($("#currentCommand").val() === 'backward') {
          command = 'speed_up';
        } else {
          command = 'backward';
          $("#currentCommand").val(command);
        }
        break;
      case 82: // R
      case 114: // r
        if ($("#currentCommand").val() === 'rotate_cw') {
          command = 'speed_up';
        } else {
          command = 'rotate_cw';
          $("#currentCommand").val(command);
        }
        break;
      case 76: // L
      case 108: // l
        if ($("#currentCommand").val() === 'rotate_ccw') {
          command = 'speed_up';
        } else {
          command = 'rotate_ccw';
          $("#currentCommand").val(command);
        }
        break;
      case 68: // D
      case 100: // d
        command = 'slow_down';
        $("#currentCommand").val(command);
        break;
    }
    $("#theCommand").empty().append("
Current Command: " + $("#currentCommand").val() + "
Sent command: " + command);
    issueCommand(command);
}

var ws = $.websocket(wsUri, {
  open: function(e) {
    $("#output").append("CONNECTED");
  },
  close: function(e) {
    $("#robot_id").val("");
    $("#output").append("DISCONNECTED")
  },
  events: {
    register: function(e) {
      var selected = $("#robot_id").val();
      var robot_name = e.data.name;
      var optionHtml = addRobotOption(robot_name, selected);
      $("#robot_id").empty().append(optionHtml);
      $("#output").append('
REGISTER: ' + e.data.name + "
")
    },
    unregister: function(e) {
      var selected = $("#robot_id").val();
      var robot_name = e.data.name;
      var optionHtml = removeRobotOption(robot_name, selected)
      $("#robot_id").empty().append(optionHtml);
      $("#output").append('
UNREGISTER: ' + e.data.name + "
")
    }
  }
});

/**
 * Register the click-events to send the commands.
 */
$( document ).ready(function() {

  $(document).keypress(handleKeypress);

  // Handle the slow-down button
  $("#slow_down" ).click(function(event) { issueCommand("slow_down") });
  // Handle the forward button
  $("#forward" ).click(function(event) { issueCommand("forward") });
  // Handle the speed up button
  $("#speed_up" ).click(function(event) { issueCommand("speed_up") });
  // Handle the rotate_ccw up button
  $("#rotate_ccw" ).click(function(event) { issueCommand("rotate_ccw") });
  // Handle the stop button
  $("#stop" ).click(function(event) { issueCommand("stop") });
  // Handle the rotate_cw button
  $("#rotate_cw" ).click(function(event) { issueCommand("rotate_cw") });
  // Handle the backward button
  $("#backward" ).click(function(event) { issueCommand("backward") });
});


text:
package com.intel.hadoop.graphbuilder.util;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.mapreduce.Mapper;

public class PassThruMapperIntegerKey<VALUEIN, KEYOUT, VALUEOUT>
        extends Mapper<IntWritable, VALUEIN, KEYOUT, VALUEOUT> {
}


text:
class AddResolutionColumnsToIssue < ActiveRecord::Migration
  def change

    unless ActiveRecord::Base.connection.table_exists? 'issue_status_types'
      create_table :issue_status_types, :force => true do |t|
        t.string  :name,        :limit => 32,   :null => false
        t.string  :description, :limit => 254,  :null => false
        t.boolean  "active"
      end
    end

    unless column_exists? :issues, :issue_status_type_id
      add_column    :issues, :issue_status_type_id, :integer, :after => :comments, :default => 1
    end
    unless column_exists? :issues, :resolution_comments
      add_column    :issues, :resolution_comments, :text, :after => :issue_status_type_id
    end

    unless Rails.env.test?
      reversible do |change|
        change.up do
          Rake::Task['transam_core_data:update_issue_report_with_new_custom_sql'].invoke
        end
      end
    end

  end
end


text:
use super::SelectionContext;
use super::{Obligation, ObligationCause};
use super::project;
use super::util;

use middle::subst::{Subst, TypeSpace};
use middle::ty::{self, Ty};
use middle::infer::InferCtxt;
use std::collections::HashSet;
use std::rc::Rc;
use syntax::ast;
use syntax::codemap::DUMMY_SP;
use util::ppaux::Repr;

pub fn impl_can_satisfy(infcx: &InferCtxt,
                        impl1_def_id: ast::DefId,
                        impl2_def_id: ast::DefId)
                        -> bool
{
    debug!("impl_can_satisfy(\
           impl1_def_id={}, \
           impl2_def_id={})",
           impl1_def_id.repr(infcx.tcx),
           impl2_def_id.repr(infcx.tcx));

    let param_env = ty::empty_parameter_environment(infcx.tcx);
    let mut selcx = SelectionContext::intercrate(infcx, &param_env);
    let cause = ObligationCause::dummy();

    // `impl1` provides an implementation of `Foo<X,Y> for Z`.
    let impl1_substs =
        util::fresh_substs_for_impl(infcx, DUMMY_SP, impl1_def_id);
    let impl1_trait_ref =
        (*ty::impl_trait_ref(infcx.tcx, impl1_def_id).unwrap()).subst(infcx.tcx, &impl1_substs);
    let impl1_trait_ref =
        project::normalize(&mut selcx, cause.clone(), &impl1_trait_ref);

    // Determine whether `impl2` can provide an implementation for those
    // same types.
    let obligation = Obligation::new(cause,
                                     ty::Binder(ty::TraitPredicate {
                                         trait_ref: Rc::new(impl1_trait_ref.value),
                                     }));
    debug!("impl_can_satisfy(obligation={})", obligation.repr(infcx.tcx));
    selcx.evaluate_impl(impl2_def_id, &obligation) &&
        impl1_trait_ref.obligations.iter().all(
            |o| selcx.evaluate_obligation(o))
}

pub enum OrphanCheckErr<'tcx> {
    NoLocalInputType,
    UncoveredTy(Ty<'tcx>),
}

/// Checks the coherence orphan rules. `impl_def_id` should be the
/// def-id of a trait impl. To pass, either the trait must be local, or else
/// two conditions must be satisfied:
///
/// 1. All type parameters in `Self` must be "covered" by some local type constructor.
/// 2. Some local type must appear in `Self`.
pub fn orphan_check<'tcx>(tcx: &ty::ctxt<'tcx>,
                          impl_def_id: ast::DefId)
                          -> Result<(), OrphanCheckErr<'tcx>>
{
    debug!("impl_is_local({})", impl_def_id.repr(tcx));

    // We only except this routine to be invoked on implementations
    // of a trait, not inherent implementations.
    let trait_ref = ty::impl_trait_ref(tcx, impl_def_id).unwrap();
    debug!("trait_ref={}", trait_ref.repr(tcx));

    // If the *trait* is local to the crate, ok.
    if trait_ref.def_id.krate == ast::LOCAL_CRATE {
        debug!("trait {} is local to current crate",
               trait_ref.def_id.repr(tcx));
        return Ok(());
    }

    // First, create an ordered iterator over all the type parameters to the trait, with the self
    // type appearing first.
    let input_tys = Some(trait_ref.self_ty());
    let input_tys = input_tys.iter().chain(trait_ref.substs.types.get_slice(TypeSpace).iter());
    let mut input_tys = input_tys;

    // Find the first input type that either references a type parameter OR
    // some local type.
    match input_tys.find(|&&input_ty| references_local_or_type_parameter(tcx, input_ty)) {
        Some(&input_ty) => {
            // Within this first type, check that all type parameters are covered by a local
            // type constructor. Note that if there is no local type constructor, then any
            // type parameter at all will be an error.
            let covered_params = type_parameters_covered_by_ty(tcx, input_ty);
            let all_params = type_parameters_reachable_from_ty(input_ty);
            for &param in all_params.difference(&covered_params) {
                return Err(OrphanCheckErr::UncoveredTy(param));
            }
        }
        None => {
            return Err(OrphanCheckErr::NoLocalInputType);
        }
    }

    return Ok(());
}

fn ty_is_local_constructor<'tcx>(tcx: &ty::ctxt<'tcx>, ty: Ty<'tcx>) -> bool {
    debug!("ty_is_local_constructor({})", ty.repr(tcx));

    match ty.sty {
        ty::ty_bool |
        ty::ty_char |
        ty::ty_int(..) |
        ty::ty_uint(..) |
        ty::ty_float(..) |
        ty::ty_str(..) |
        ty::ty_bare_fn(..) |
        ty::ty_vec(..) |
        ty::ty_ptr(..) |
        ty::ty_rptr(..) |
        ty::ty_tup(..) |
        ty::ty_param(..) |
        ty::ty_projection(..) => {
            false
        }

        ty::ty_enum(def_id, _) |
        ty::ty_struct(def_id, _) => {
            def_id.krate == ast::LOCAL_CRATE
        }

        ty::ty_uniq(_) => { // treat ~T like Box<T>
            let krate = tcx.lang_items.owned_box().map(|d| d.krate);
            krate == Some(ast::LOCAL_CRATE)
        }

        ty::ty_trait(ref tt) => {
            tt.principal_def_id().krate == ast::LOCAL_CRATE
        }

        ty::ty_closure(..) |
        ty::ty_infer(..) |
        ty::ty_open(..) |
        ty::ty_err => {
            tcx.sess.bug(
                &format!("ty_is_local invoked on unexpected type: {}",
                        ty.repr(tcx))[])
        }
    }
}

fn type_parameters_covered_by_ty<'tcx>(tcx: &ty::ctxt<'tcx>,
                                       ty: Ty<'tcx>)
                                       -> HashSet<Ty<'tcx>>
{
    if ty_is_local_constructor(tcx, ty) {
        type_parameters_reachable_from_ty(ty)
    } else {
        ty.walk_children().flat_map(|t| type_parameters_covered_by_ty(tcx, t).into_iter()).collect()
    }
}

/// All type parameters reachable from `ty`
fn type_parameters_reachable_from_ty<'tcx>(ty: Ty<'tcx>) -> HashSet<Ty<'tcx>> {
    ty.walk().filter(|&t| is_type_parameter(t)).collect()
}

fn references_local_or_type_parameter<'tcx>(tcx: &ty::ctxt<'tcx>, ty: Ty<'tcx>) -> bool {
    ty.walk().any(|ty| is_type_parameter(ty) || ty_is_local_constructor(tcx, ty))
}

fn is_type_parameter<'tcx>(ty: Ty<'tcx>) -> bool {
    match ty.sty {
        // FIXME(#20590) straighten story about projection types
        ty::ty_projection(..) | ty::ty_param(..) => true,
        _ => false,
    }
}


text:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using GalaSoft.MvvmLight.Command;
using Microsoft.Win32;
using WinHAB.Core.Configuration;
using WinHAB.Core.Fx;
using WinHAB.Core.Fx.Mvvm;
using WinHAB.Desktop.Configuration;
using WinHAB.Desktop.Fx.IO;
using WinHAB.Desktop.Fx.Windows;
using WinHAB.Desktop.Localization;

namespace WinHAB.Desktop.ViewModels.Settings
{
  public class SettingsUserResourcesViewModel : ViewModel, ITitledViewModel
  {
    private readonly INavigationService _navigation;
    private readonly DesktopConfiguration _config;

    public SettingsUserResourcesViewModel(INavigationService navigation, DesktopConfiguration config)
    {
      _navigation = navigation;
      _config = config;

      Title = Strings.TitleUserResources;
      ResourceFile = config.Constants.UserResourcesFile;

      AddIconCommand = new RelayCommand(AddIcon);
      EditIconCommand = new RelayCommand<UserResourcesData.UserResourcesIcon>(EditIcon);
      DeleteIconCommand = new RelayCommand<string>(DeleteIcon);

      OpenCommand = new AsyncRelayCommand(Open);
      SaveAsCommand = new AsyncRelayCommand(SaveAs);
      OpenDefaultCommand = new AsyncRelayCommand(OpenDefault);
    }

    private string _Title;
    public string Title { get { return _Title; } set { _Title = value; RaisePropertyChanged(() => Title); } }

    private string _ResourceFile;
    public string ResourceFile { get { return _ResourceFile; } set { _ResourceFile = value; RaisePropertyChanged(()=>ResourceFile); }}

    private UserResources _UserResources;
    public UserResources UserResources { get { return _UserResources; } set { _UserResources = value; RaisePropertyChanged(() => UserResources); } }

    public RelayCommand AddIconCommand { get; set; }
    public RelayCommand<UserResourcesData.UserResourcesIcon> EditIconCommand { get; set; }
    public RelayCommand<string> DeleteIconCommand { get; set; }
    public AsyncRelayCommand SaveAsCommand { get; set; }
    public AsyncRelayCommand OpenCommand { get; set; }
    public AsyncRelayCommand OpenDefaultCommand { get; set; }

    public override async Task InitializeAsync(object parameter)
    {
      await LoadUserResources(ResourceFile);
    }

    // TODO: Make load/save safely
    private async Task LoadUserResources(string fileName)
    {
      UserResources = new UserResources();
      try
      {
        var f = new FileInfo(fileName);
        if (f.Exists)
        {
          var fileContent = await f.ReadAllTextAsync(Encoding.UTF8);
          UserResources = new UserResources();
          UserResources.LoadFromString(fileContent);
        }
      }
      catch
      {
      }
    }

    private async Task SaveUserResources(string fileName = null)
    {
      if (fileName.IsNullOrWhitespace()) fileName = ResourceFile;
      await new FileInfo(fileName).WriteAllTextAsync(UserResources.Data.ToString(), FileMode.Create, Encoding.UTF8);
    }

    private async void AddIcon()
    {
      string[] keys = null;
      if (UserResources.Data.Icons != null)
        keys = UserResources.Data.Icons.Select(x => x.Key).ToArray();
      var vm = await _navigation.NavigateAsync<SettingsIconsAddIconDialogModel>(new SettingsIconsAddIconDialogModel.SettingsIconsAddIconDialogModelParameter(keys, null, null));

      if (await vm.DialogResult())
      {
        if (UserResources.Data.Icons != null)
          UserResources.Data.Icons.Add(new UserResourcesData.UserResourcesIcon(vm.Key, vm.PathData));
        await SaveUserResources();
      }
    }

    private async void EditIcon(UserResourcesData.UserResourcesIcon icon)
    {
      if (icon == null) return;

      string[] keys = null;
      if (UserResources.Data.Icons != null)
        keys = UserResources.Data.Icons.Select(x => x.Key).ToArray();

      var vm = await _navigation.NavigateAsync<SettingsIconsAddIconDialogModel>(new SettingsIconsAddIconDialogModel.SettingsIconsAddIconDialogModelParameter(keys, icon.Key, icon.PathData));
      if (await vm.DialogResult())
      {
        icon.Key = vm.Key;
        icon.PathData = vm.PathData;
        await SaveUserResources();
      }

    }

    private async void DeleteIcon(string key)
    {
      if (key.IsNullOrWhitespace()) return;

      if (await _navigation.ShowQuestionAsync(Strings.TitleEditIconDialog, string.Format(Strings.MessageQuestionDeleteIconFormat, key)))
      {
        if (UserResources.Data.Icons == null) return;
        var icon = UserResources.Data.Icons.FirstOrDefault(x => x.Key == key);
        if (icon != null)
          UserResources.Data.Icons.Remove(icon);
        await SaveUserResources();
      }
    }

    private async Task OpenDefault()
    {
      ResourceFile = _config.Constants.UserResourcesFile;
      await LoadUserResources(ResourceFile);
    }

    // TODO: Replace SaveFileDialog with INavigationService
    private async Task Open()
    {
      var od = new OpenFileDialog();
      od.CheckFileExists = true;
      od.CheckPathExists = true;
      od.DefaultExt = "*.json";
      od.Multiselect = false;
      od.Filter = "WinHAB Configuration Files (*.json)|*.json";

      var res = od.ShowDialog();
      if (res.HasValue && res.Value)
      {
        await LoadUserResources(od.FileName);
        ResourceFile = od.FileName;
      }
    }

    // TODO: Replace SaveFileDialog with INavigationService
    private async Task SaveAs()
    {
      var sd = new SaveFileDialog();
      sd.AddExtension = true;
      sd.CheckPathExists = true;
      sd.FileName = "WinHAB.Resources.json";
      sd.DefaultExt = "*.json";
      sd.Filter = "WinHAB Configuration Files (*.json)|*.json";
      sd.OverwritePrompt = true;
      var res = sd.ShowDialog();
      if (res.HasValue && res.Value)
      {
        await SaveUserResources(sd.FileName);
        ResourceFile = sd.FileName;
      }

    }

  }
}


text:
from __future__ import division
import pydoc

def run():
  pydoc.cli()

if (__name__ == "__main__"):
  run()


text:
{% if post.url %}
  {% assign path = post.path %}
{% else %}
  {% assign path = page.path %}
{% endif %}

 Edit this page


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>AdministratorsController</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" href="../css/reset.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../css/main.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../css/github.css" type="text/css" media="screen" />

            Class
            AdministratorsController

                <

                    AdministrativeInterfaceController

app/controllers/administrators_controller.rb

Methods

C

                create

D

                destroy

E

                edit

I

                index

N

                new

U

                update

Instance Public methods

              create()

            Link

POST /administrators

                Source:
                show

# File app/controllers/administrators_controller.rb, line 19
def create
  @administrator = Administrator.new(administrator_params.merge(data_center: current_user.data_center))

  if @administrator.save
    redirect_to administrators_path, notice: I18n.t('activerecord.notices.models.administrator.success.create')
  else
    render :new
  end
end

              destroy()

            Link

DELETE /administrators/1

                Source:
                show

# File app/controllers/administrators_controller.rb, line 39
def destroy
  @administrator.destroy
  redirect_to administrators_url, notice: I18n.t('activerecord.notices.models.administrator.success.destroy')
end

              edit()

            Link

GET /administrators/1/edit

                Source:
                show

# File app/controllers/administrators_controller.rb, line 15
def edit
end

              index()

            Link

GET /administrators

                Source:
                show

# File app/controllers/administrators_controller.rb, line 5
def index
  @administrators = Administrator.find_by_data_center(current_user.data_center).all
end

              new()

            Link

GET /administrators/new

                Source:
                show

# File app/controllers/administrators_controller.rb, line 10
def new
  @administrator = Administrator.new(data_center: current_user.data_center)
end

              update()

            Link

PATCH/PUT /administrators/1

                Source:
                show

# File app/controllers/administrators_controller.rb, line 30
def update
  if @administrator.update(administrator_params)
    redirect_to administrators_path, notice: I18n.t('activerecord.notices.models.administrator.success.update')
  else
    render :edit
  end
end


text:
const through = require('through2');

module.exports = function injectMetadata(metadata) {

  return through.obj(function(file, encoding, cb) {

    // copy global metadata and override with file's local metadata
    file.data = Object.assign({}, metadata.fields, file.frontMatter);
    cb(null, file);
  });
}


text:
"""SCons.Tool.PharLapCommon

This module contains common code used by all Tools for the
Phar Lap ETS tool chain.  Right now, this is linkloc and
386asm.

"""

#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#

__revision__ = "src/engine/SCons/Tool/PharLapCommon.py 4043 2009/02/23 09:06:45 scons"

import os
import os.path
import SCons.Errors
import SCons.Util
import re
import string

def getPharLapPath():
    """Reads the registry to find the installed path of the Phar Lap ETS
    development kit.

    Raises UserError if no installed version of Phar Lap can
    be found."""

    if not SCons.Util.can_read_reg:
        raise SCons.Errors.InternalError, "No Windows registry module was found"
    try:
        k=SCons.Util.RegOpenKeyEx(SCons.Util.HKEY_LOCAL_MACHINE,
                                  'SOFTWARE\\Pharlap\\ETS')
        val, type = SCons.Util.RegQueryValueEx(k, 'BaseDir')

        # The following is a hack...there is (not surprisingly)
        # an odd issue in the Phar Lap plug in that inserts
        # a bunch of junk data after the phar lap path in the
        # registry.  We must trim it.
        idx=val.find('\0')
        if idx >= 0:
            val = val[:idx]

        return os.path.normpath(val)
    except SCons.Util.RegError:
        raise SCons.Errors.UserError, "Cannot find Phar Lap ETS path in the registry.  Is it installed properly?"

REGEX_ETS_VER = re.compile(r'#define\s+ETS_VER\s+([0-9]+)')

def getPharLapVersion():
    """Returns the version of the installed ETS Tool Suite as a
    decimal number.  This version comes from the ETS_VER #define in
    the embkern.h header.  For example, '#define ETS_VER 1010' (which
    is what Phar Lap 10.1 defines) would cause this method to return
    1010. Phar Lap 9.1 does not have such a #define, but this method
    will return 910 as a default.

    Raises UserError if no installed version of Phar Lap can
    be found."""

    include_path = os.path.join(getPharLapPath(), os.path.normpath("include/embkern.h"))
    if not os.path.exists(include_path):
        raise SCons.Errors.UserError, "Cannot find embkern.h in ETS include directory.\nIs Phar Lap ETS installed properly?"
    mo = REGEX_ETS_VER.search(open(include_path, 'r').read())
    if mo:
        return int(mo.group(1))
    # Default return for Phar Lap 9.1
    return 910

def addPathIfNotExists(env_dict, key, path, sep=os.pathsep):
    """This function will take 'key' out of the dictionary
    'env_dict', then add the path 'path' to that key if it is not
    already there.  This treats the value of env_dict[key] as if it
    has a similar format to the PATH variable...a list of paths
    separated by tokens.  The 'path' will get added to the list if it
    is not already there."""
    try:
        is_list = 1
        paths = env_dict[key]
        if not SCons.Util.is_List(env_dict[key]):
            paths = string.split(paths, sep)
            is_list = 0
        if not os.path.normcase(path) in map(os.path.normcase, paths):
            paths = [ path ] + paths
        if is_list:
            env_dict[key] = paths
        else:
            env_dict[key] = string.join(paths, sep)
    except KeyError:
        env_dict[key] = path

def addPharLapPaths(env):
    """This function adds the path to the Phar Lap binaries, includes,
    and libraries, if they are not already there."""
    ph_path = getPharLapPath()

    try:
        env_dict = env['ENV']
    except KeyError:
        env_dict = {}
        env['ENV'] = env_dict
    addPathIfNotExists(env_dict, 'PATH',
                       os.path.join(ph_path, 'bin'))
    addPathIfNotExists(env_dict, 'INCLUDE',
                       os.path.join(ph_path, 'include'))
    addPathIfNotExists(env_dict, 'LIB',
                       os.path.join(ph_path, 'lib'))
    addPathIfNotExists(env_dict, 'LIB',
                       os.path.join(ph_path, os.path.normpath('lib/vclib')))

    env['PHARLAP_PATH'] = getPharLapPath()
    env['PHARLAP_VERSION'] = str(getPharLapVersion())

# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:


text:
external help file: Microsoft.Azure.Commands.Network.dll-Help.xml
Module Name: AzureRM.Network
online version: https://docs.microsoft.com/en-us/powershell/module/azurerm.network/remove-azurermapplicationgatewaytrustedrootcertificate
schema: 2.0.0
---

# Remove-AzureRmApplicationGatewayTrustedRootCertificate

## SYNOPSIS
Removes a Trusted Root Certificate from an application gateway.

## SYNTAX

```
Remove-AzureRmApplicationGatewayTrustedRootCertificate -Name <String>
 -ApplicationGateway <PSApplicationGateway> [-DefaultProfile <IAzureContextContainer>] [-WhatIf] [-Confirm]
 [<CommonParameters>]
```

## DESCRIPTION
The **Remove-AzureRmApplicationGatewayTrustedRootCertificate** cmdlet removes a Trusted Root Certificate from an existing Application Gateway.

## EXAMPLES

### Example 1
```powershell
PS C:\> $gw = Get-AzureRmApplicationGateway -Name $appgwName -ResourceGroupName $resgpName
PS C:\> $gw = Remove-AzureRmApplicationGatewayTrustedRootCertificate -ApplicationGateway $gw -Name "myRootCA"
PS C:\> $gw = Set-AzureRmApplicationGateway -ApplicationGateway $gw
```

The first command gets an application gateway and stores it in the $gw variable.
The second command removes the trusted root certificate named myRootCA from the application gateway stored in $gw.
The third command updates the application gateway on Azure.

## PARAMETERS

### -ApplicationGateway
The applicationGateway

```yaml
Type: Microsoft.Azure.Commands.Network.Models.PSApplicationGateway
Parameter Sets: (All)
Aliases:

Required: True
Position: Named
Default value: None
Accept pipeline input: True (ByValue)
Accept wildcard characters: False
```

### -DefaultProfile
The credentials, account, tenant, and subscription used for communication with Azure.

```yaml
Type: Microsoft.Azure.Commands.Common.Authentication.Abstractions.IAzureContextContainer
Parameter Sets: (All)
Aliases: AzureRmContext, AzureCredential

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -Name
The name of the TrustedRoot certificate

```yaml
Type: System.String
Parameter Sets: (All)
Aliases:

Required: True
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -Confirm
Prompts you for confirmation before running the cmdlet.

```yaml
Type: System.Management.Automation.SwitchParameter
Parameter Sets: (All)
Aliases: cf

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -WhatIf
Shows what would happen if the cmdlet runs.
The cmdlet is not run.

```yaml
Type: System.Management.Automation.SwitchParameter
Parameter Sets: (All)
Aliases: wi

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216).

## INPUTS

### Microsoft.Azure.Commands.Network.Models.PSApplicationGateway

## OUTPUTS

### Microsoft.Azure.Commands.Network.Models.PSApplicationGateway

## NOTES

## RELATED LINKS


text:
"use strict";

angular.module("Wallr").controller("ImageQueueCtrl", ["ImageQueueStore",
    function (imageQueueStore) {
        Object.defineProperty(this, "imageIds", {
            get: function() {
                return imageQueueStore.imageIds;
            }
        });

        this.getUrlForImage = function(imageId) {
            return "/image/" + imageId.sourceId + "/" + imageId.localId;
        }
    }
]);