text:
@interface UIImage (LNVToolbox)

+ (instancetype)lnv_imageWithColor:(UIColor *)color size:(CGSize)size;

+ (instancetype)lnv_roundImageWithFillColor:(UIColor *)fillColor strokeColor:(UIColor *)strokeColor size:(CGSize)size;

- (instancetype)lnv_roundedImageWithSize:(CGSize)size cornerRadius:(CGFloat)cornerRadius;

- (instancetype)lnv_resizedImageWithSize:(CGSize)size;
- (instancetype)lnv_resizedImageWithSize:(CGSize)size scale:(CGFloat)scale;

@end

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.

using System.Reflection;

namespace System.Web.Mvc
{
    internal sealed class ActionMethodDispatcherCache : ReaderWriterCache<MethodInfo, ActionMethodDispatcher>
    {
        public ActionMethodDispatcherCache()
        {
        }

        public ActionMethodDispatcher GetDispatcher(MethodInfo methodInfo)
        {
            // Frequently called, so ensure delegate remains static
            return FetchOrCreateItem(methodInfo, (MethodInfo methodInfoInner) => new ActionMethodDispatcher(methodInfoInner), methodInfo);
        }
    }
}


text:
<?php

class Main extends CI_Controller {

	public function __construct() {
		parent::__construct();
	}

	public function index(){
		$data = array(
			'murid' =>$this->e_murid->get_all(),
			'guru' =>$this->e_dataGuru->get_all()
			);
		$this->load->view('header');
		$this->load->view('content/menu', $data);
	}

	public function logout(){
		session_destroy();
		redirect('c_loginmurid','refresh');
	}
}
 ?>


text:
package com.orientechnologies.orient.server.distributed;

import com.orientechnologies.orient.core.exception.ODatabaseException;
import org.junit.Assert;
import org.junit.Test;

/** Distributed test on drop database. */
public class DistributedDbDropIT extends AbstractServerClusterTxTest {
  static final int SERVERS = 3;
  int serverStarted = 0;

  @Test
  public void test() throws Exception {
    count = 10;
    init(SERVERS);
    prepare(false);
    execute();
  }

  @Override
  protected void onAfterExecution() throws Exception {
    ServerRun s = serverInstance.get(0);

    banner("DROPPING DATABASE ON SERVER " + s.getServerId());
    s.getServerInstance().dropDatabase(getDatabaseName());

    for (int i = 1; i < serverInstance.size(); ++i) {
      try {
        serverInstance.get(i).getServerInstance().openDatabase(getDatabaseName());
        Assert.fail("The database was not deleted on server " + i);
      } catch (ODatabaseException e) {
        Assert.assertTrue(e.getCause().getMessage().contains("it does not exist"));
      }
    }
  }

  protected String getDatabaseURL(final ServerRun server) {
    return "plocal:" + server.getDatabasePath(getDatabaseName());
  }

  @Override
  public String getDatabaseName() {
    return "distributed-dropdb";
  }
}


text:
package org.assertj.core.util;

import static org.assertj.core.api.Assertions.*;

import org.junit.Test;

/**
 * Tests for <code>{@link Arrays#isNullOrEmpty(Object[])}</code>.
 *
 * @author Alex Ruiz
 */
public class Arrays_isNullOrEmpty_Test {
  @Test
  public void should_return_true_if_array_is_empty() {
    assertThat(Arrays.isNullOrEmpty(new String[0])).isTrue();
  }

  @Test
  public void should_return_true_if_array_is_null() {
    assertThat(Arrays.isNullOrEmpty(null)).isTrue();
  }

  @Test
  public void should_return_false_if_array_has_elements() {
    assertThat(Arrays.isNullOrEmpty(new String[] { "Tuzi" })).isFalse();
  }
}


text:
package uk.gov.gds.ier.test

import org.scalatest._
import matchers._
import scala.util.Try

trait CustomMatchers {

  class MapComparisonMatcher[A,B](expectedMap: Map[A,B]) extends Matcher[Map[A,B]] {
    def apply(leftMap: Map[A,B]) = {
      val keysNotInLeft = expectedMap.keySet.filterNot(key => leftMap.keySet.contains(key))
      val keysNotInExpected = leftMap.keys.toSet.filterNot(key => expectedMap.keySet.contains(key))
      val keysInBoth = (leftMap.keySet ++ expectedMap.keySet) -- (keysNotInLeft ++ keysNotInExpected)

      val messagesAfterNotInLeft = keysNotInLeft.foldLeft(List.empty[String]){ (messages, key) =>
        messages ++ List(s"\n$key was expected but not found in map")
      }
      val messagesAfterNotInExpected = keysNotInExpected.foldLeft(messagesAfterNotInLeft){ (messages, key) =>
        messages ++ List(s"\n$key was unexpected and found in map")
      }
      val errorMessages = keysInBoth.foldLeft(messagesAfterNotInExpected){ (messages, key) =>
        Try {
          val expected = expectedMap(key)
          val left = leftMap(key)
          if (expected == left) {
            messages
          } else {
            messages ++ List(s"\n($key -> $left) did not equal ($key -> $expected)")
          }
        }.getOrElse(messages)
      }

      MatchResult(
        errorMessages.isEmpty,
        s"${errorMessages.mkString(",")}",
        s"Map $leftMap matched $expectedMap"
      )
    }
  }

  def matchMap[A,B](expectedMap:Map[A,B]) = new MapComparisonMatcher(expectedMap)

}

// Make them easy to import with:
// import CustomMatchers._
object CustomMatchers extends CustomMatchers


text:
package org.cqframework.cql.cql2elm.model;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Bryn on 12/22/2016.
 */
public class InstantiationResult {
    public InstantiationResult(GenericOperator genericOperator, Operator operator, int conversionScore) {
        if (genericOperator == null) {
            throw new IllegalArgumentException("genericOperator is required");
        }

        this.genericOperator = genericOperator;
        this.operator = operator;
        this.conversionScore = conversionScore;
    }

    private GenericOperator genericOperator;
    public GenericOperator getGenericOperator() {
        return genericOperator;
    }

    private Operator operator;
    public Operator getOperator() {
        return operator;
    }

    private int conversionScore;
    public int getConversionScore() {
        return conversionScore;
    }
}


text:
Thermoman 360 - Smart home thermal imaging solution for effecient use of energy.
------

# The event

![Endesa Energy Challenge](https://raw.githubusercontent.com/fauria/thermoman-360/master/assets/hackathon-banner.jpg)

This project was developed during the first [Endesa Energy Challenges Hackathon](http://www.endesaenergychallenges.com/hackathon/), held in the Official College of Madrid Architects ([COAM](http://www.coam.org/), in Madrid, Spain between October 9th and 11th 2015.

The event was sponsored by [Endesa](http://www.endesaenergychallenges.com/) and runned by [Opinno](http://www.opinno.com/). Mentors from both organizations were present during the whole event, helping teams to structure and develop their ideas.

# The idea

![Idea draft](https://raw.githubusercontent.com/fauria/thermoman-360/master/assets/idea.jpg)

Our project was defined as *"An application that locates inefficiencies and energy loss within the home through the use of a thermographic sensor that detects differences in temperature"*

The goal was to develop a low cost thermographic camera that allowed the monitoring of rooms, learning about its users habits and detecting waste.

This data, cross-referenced with external inputs, would generate recommendations to achive the most efficient use of energy.

# The team

![Thermoman 360 team members](https://raw.githubusercontent.com/fauria/thermoman-360/master/assets/winners.jpg)

Meet the team:

- Fernando Álvarez-Uría, Software Engineer. <fauria@gmail.com>. Twitter: [@fauria](https://twitter.com/fauria)
- Nuño Valencia, Industrial Engineer. <info@nunovalencia.info> Twitter: [@NuoValencia](https://twitter.com/NuoValencia)
- Andrea Jiménez, Business Analyst <andreaj.567@gmail.com>. Twitter: [@eatgreekspeakfr](https://twitter.com /eatgreekspeakfr)
- Diego Lasaosa, Architect. <diegolasaosa@certicalia.com> Twitter: [@diegolasaosa](https://twitter.com/diegolasaosa)

The teams were already pre-assigned before the event, although we hadn't met before.

At the entrance, the organisation handed each participant a hackathon kit, containing among other goodies one piece from a puzzle.

The hackathon members teamed up by matching their puzzle pieces during a networking session.

Each one had a superhero assigned, and ours was Ironman, thus the name of the project.

# Hardware

![Thermoman Rig](https://raw.githubusercontent.com/fauria/thermoman-360/master/assets/hardware.jpg)

For this project, we relied on the following parts:

- [Raspberry Pi](https://www.raspberrypi.org/) model B, with GPIO header break out.
- [Raspberry Pi Camera Module](https://www.raspberrypi.org/products/camera-module/).
- [Arduino Uno board](https://www.arduino.cc/en/main/arduinoBoardUno).
- [Grove Base Shield](http://www.seeedstudio.com/depot/Base-Shield-V2-p-1378.html)
- Melexis MLX 90614 digital thermopile with 10° Field of View (FOV). Based on this project, an [infrared thermometer Grove module](http://www.seeed.cc/project_detail.html?id=1157) was later produced.
- Pan-tilt head, composed by two servos.
- Protoboards

The thermographic camera consisted on a piece of foam with both the camera and the sensor attached in a 90° angle arrangement.

This way, alternating the vertical servo between 0° and 90° allowd the usage of both the camera and the sensor.

# Software

![Thermoman actual picture](https://raw.githubusercontent.com/fauria/thermoman-360/master/assets/thermoman-action.gif)

We developed an Arduino sketch that performed a scan using the pan-tilt head.

Knowing the field of view of the sensor was 10° on both axis, and the camera FOV 53.50° and 41.41° on X and Y respectively, we coud estimate a matrix of sensor readings.

This approach was not very pricese, but enough for a proof of concept.

The Raspberry Pi runned a Node.js application, communicating with Arduino via USB serial terminal. Events were used to coordinate the different actions.

A web interface displayed the results, using an HTML5 canvas for the readings.

# Future improvements

The prototype was just a proof of concept.

A potential commercial application should be efficient, able to perform readings in 360° and easly integrable in a home among many others.

# The prototype

![Fully functional prototype](https://raw.githubusercontent.com/fauria/thermoman-360/master/assets/prototype.gif)

For the assembly of the prototype we used a protoboard as a base, with the pant-tilt head, sensor foam setup and Raspberry Pi attached.

To perform a thermal image, the following steps were taken from the Node.js application on the Raspberry Pi:

1. Send a ```snap```command to Arduino to move the vertical servo to 90° and the horizontal servo to 180°. The camera should be looking forward.
2. [Take a picture](https://www.raspberrypi.org/documentation/usage/camera/raspicam/raspistill.md)
3. Send a ```reset``` command to Arduino to put both servos on ```0,0``` coordinates.
4. Send a ```scan``` command to Arduino. Now the servos start moving in increments, performing a sendor reading on each step. A JSON encoded string is sent back to the Raspberry Pi.
5. Send a ``neutral``` command to Arduino. This sets both servos on 90°.
6. Parse the JSON string sent from Arduino and display the image taken with a canvas overly showing the temperatures.

# The pitch

![Thermoman 360 team in front of the jury](https://raw.githubusercontent.com/fauria/thermoman-360/master/assets/pitch.jpg)

The jury was formed by:

**Juan Garrigosa** (Head of Innovation at Endesa), **Sandra Alfonso** (Head of Digital Market Transformation at Endesa), **Jorge Sánchez-Mayoral** (Digital Channel Director & Customer Experience at Endesa), **Enrique Dans** (Professor at IE Business School), **Antonio Fontanini** (Cex Advisor and Chief Optimistic Officer at Opinno), **Alberto Levy** (Innovation Evangelist) and **Javier Noguerol** (Senior researcher at Future Doers).

The pitch consisted on a five minutes talk, and altought the prototype could not be used live, the results were shown on the presentation.

# Awards

![Endesa Hackathon Winners](https://raw.githubusercontent.com/fauria/thermoman-360/master/assets/winners-all.jpg)

We won the first prize, awarded with 6.000€ for the team and four wooden table lamps, one for each member.

# Afterwork

![Endesa Hackathon Winners](https://raw.githubusercontent.com/fauria/thermoman-360/master/assets/exit-madrid.jpg)

After the prize-giving, the hackathon participants were taken to a special afterwork, held in [Exit Madrid](http://exit-game.es/?lang=en). It consisted on a *escape room* game, were we had to solver serveral puzzles inside a locked room before a certain deadline.

We had a great time there, working again together, but this time on a very different problem.

# Coverage

> November 30th, 2015

### Video: [Endesa Hackathon: Así se desarrolló el primer Hackathon de los #Energychallenges](https://www.youtube.com/watch?v=NXju4aeZCJc)

> November 25th, 2015

### Article: [Jóvenes competirán en un concurso para diseñar soluciones energéticas](http://www.elconfidencial.com/empresas/2015-11-25/jovenes-competiran-en-un-proyecto-para-disenar-soluciones-energeticas_1106238/)

> November 30th, 2015

### Article: [Una aplicación para saber por dónde se escapa el calor en casa gana el primer Hackathon Endesa](http://www.eleconomista.es/economia/noticias/7185653/11/15/Una-aplicacion-para-saber-por-donde-se-escapa-el-calor-en-casa-gana-el-primer-Hackathon-Endesa.html)

> November 30th, 2015

### TV: [Una aplicación para saber por dónde se escapa el calor en casa gana el primer Hackathon Endesa](http://www.telecinco.es/informativos/aplicacion-escapa-primer-Hackathon-Endesa_0_2092125256.html)

> November 30th, 2015

### Article: [Una app para saber por dónde se escapa el calor en casa gana el primer Hackathon Endesa](http://www.republica.com/2015/11/30/una-app-para-saber-por-donde-se-escapa-el-calor-en-casa-gana-el-primer-hackathon-endesa/)

> November 30th, 2015

### Article: [Una aplicación para saber por dónde se escapa el calor en casa gana el primer Hackathon Endesa](http://www.expansion.com/agencia/europa_press/2015/11/30/20151130142608.html)

> November 30th, 2015

### Article: [Una app para saber por dónde se escapa el calor en casa gana el primer Hackathon Endesa](http://www.endesa.com/es/saladeprensa/noticias/Entrega-premios-primer-Hackathon-Endesa)

> December 1st, 2015

### Article: [¿Por dónde se escapa el calor en casa? Endesa entrega los premios de su primer Hackathon](http://www.innovaspain.com/detalle_noticia.php?id=7559)

---


text:
layout: page
title: Dart Charm Limited Dinner
date: 2016-05-24
author: Jacqueline Daniel
tags: weekly links, java
status: published
summary: Aliquam bibendum ultrices elit in.
banner: images/banner/people.jpg
booking:
  startDate: 02/21/2016
  endDate: 02/23/2016
  ctyhocn: KNBHXHX
  groupCode: DCLD
published: true
---
Aliquam scelerisque mauris nisl, sit amet aliquam est malesuada eget. Vestibulum in arcu ligula. Sed non odio nec libero scelerisque vulputate in eu mauris. Vivamus leo mi, elementum eu urna a, semper rutrum lorem. Morbi a pellentesque enim, eu venenatis dui. Nulla facilisi. Maecenas laoreet congue condimentum. Maecenas finibus ante vestibulum nulla ullamcorper accumsan. Cras ac pharetra elit. Donec in dapibus nisi, ac sagittis massa. Donec sit amet pulvinar augue. Nunc a tincidunt tellus. Nunc arcu quam, euismod et neque sed, efficitur consectetur nulla.

1 Morbi dictum quam a arcu sollicitudin, non consectetur tellus venenatis
1 Nullam sollicitudin quam pulvinar laoreet cursus
1 Ut dapibus felis a velit dictum, a mattis nulla sodales
1 Suspendisse ac elit et purus porta mollis non et leo
1 Fusce aliquet diam accumsan imperdiet faucibus
1 Ut sodales nisl et lorem facilisis, non egestas sapien semper.

Etiam sed sapien nec erat finibus molestie sit amet sed justo. Morbi pellentesque pharetra facilisis. Duis sit amet tellus nec velit consectetur vehicula eget ac sapien. Proin facilisis urna vitae felis lacinia pellentesque. Aenean laoreet dui eu egestas tempus. Maecenas faucibus vehicula sem, vel venenatis enim lacinia nec. Praesent nec sodales risus. Duis sit amet neque consequat, iaculis nulla eget, semper nisi.
Aliquam dui nunc, finibus in auctor non, fermentum eget sapien. Donec mi enim, porttitor eu sem a, rhoncus ultricies dui. Aliquam tempor mattis odio, eget vulputate nulla fermentum in. Nunc vel diam feugiat, condimentum magna sed, bibendum arcu. Mauris et semper enim, a facilisis massa. Duis quis nulla odio. Fusce placerat ligula nec lorem condimentum, aliquet aliquam quam rhoncus.


text:
package hudson.util;

import hudson.util.CyclicGraphDetector.CycleDetectedException;
import junit.framework.TestCase;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;

/**
 * @author Kohsuke Kawaguchi
 */
public class CyclicGraphDetectorTest extends TestCase {
    private class Edge {
        String src,dst;

        private Edge(String src, String dst) {
            this.src = src;
            this.dst = dst;
        }
    }

    private class Graph extends ArrayList<Edge> {
        Graph e(String src, String dst) {
            add(new Edge(src,dst));
            return this;
        }

        Set<String> nodes() {
            Set<String> nodes = new LinkedHashSet<String>();
            for (Edge e : this) {
                nodes.add(e.src);
                nodes.add(e.dst);
            }
            return nodes;
        }

        Set<String> edges(String from) {
            Set<String> edges = new LinkedHashSet<String>();
            for (Edge e : this) {
                if (e.src.equals(from))
                    edges.add(e.dst);
            }
            return edges;
        }

        /**
         * Performs a cycle check.
         */
        void check() throws Exception {
            new CyclicGraphDetector<String>() {
                protected Set<String> getEdges(String s) {
                    return edges(s);
                }
            }.run(nodes());
        }

        void mustContainCycle(String... members) throws Exception {
            try {
                check();
                fail("Cycle expected");
            } catch (CycleDetectedException e) {
                String msg = "Expected cycle of " + Arrays.asList(members) + " but found " + e.cycle;
                for (String s : members)
                    assertTrue(msg, e.cycle.contains(s));
            }
        }
    }

    public void testCycle() throws Exception {
        new Graph().e("A","B").e("B","C").e("C","A").mustContainCycle("A","B","C");
    }

    public void testCycle2() throws Exception {
        new Graph().e("A","B").e("B","C").e("C","C").mustContainCycle("C");
    }

    public void testCycle3() throws Exception {
        new Graph().e("A","B").e("B","C").e("C","D").e("B","E").e("E","D").e("E","A").mustContainCycle("A","B","E");
    }

}


text:
(async function() {
  TestRunner.addResult(`Tests search in Summary view of detailed heap snapshots.\n`);
  await TestRunner.loadTestModule('heap_profiler_test_runner');
  await TestRunner.showPanel('heap_profiler');

  var instanceCount = 25;
  function createHeapSnapshot() {
    return HeapProfilerTestRunner.createHeapSnapshot(instanceCount);
  }

  HeapProfilerTestRunner.runHeapSnapshotTestSuite([function testSearch(next) {
    HeapProfilerTestRunner.takeAndOpenSnapshot(createHeapSnapshot, step1a);
    function addSearchResultSniffer(step) {
      function jumpToSearchResult() {
        step(HeapProfilerTestRunner.currentProfileView().searchResults.length);
      }
      TestRunner.addSniffer(HeapProfilerTestRunner.currentProfileView(), 'jumpToSearchResult', jumpToSearchResult);
    }

    function addNodeSelectedSniffer(callback) {
      TestRunner.addSniffer(HeapProfilerTestRunner.currentProfileView(), 'selectRevealedNode', callback);
    }

    function step1a() {
      HeapProfilerTestRunner.switchToView('Summary', step1b);
    }

    function step1b() {
      var row = HeapProfilerTestRunner.findRow('Window');
      TestRunner.assertEquals(true, !!row, '"Window" class row');
      HeapProfilerTestRunner.expandRow(row, step1c);
    }

    function step1c(row) {
      TestRunner.assertEquals(1, row.children.length, 'single Window object');
      var windowRow = row.children[0];
      TestRunner.assertEquals(true, !!windowRow, '"Window" instance row');
      HeapProfilerTestRunner.expandRow(windowRow, step2);
    }

    function step2() {
      addSearchResultSniffer(step3);
      HeapProfilerTestRunner.currentProfileView().performSearch({query: 'window', caseSensitive: false});
    }

    function step3(resultCount) {
      TestRunner.assertEquals(1, resultCount, 'Search for existing node');
      addSearchResultSniffer(step4);
      HeapProfilerTestRunner.currentProfileView().performSearch({query: 'foo', caseSensitive: false});
    }

    function step4(resultCount) {
      TestRunner.assertEquals(0, resultCount, 'Search for not-existing node');
      addNodeSelectedSniffer(step5);
      HeapProfilerTestRunner.currentProfileView().performSearch({query: '@999', caseSensitive: false});
    }

    function step5(node) {
      TestRunner.assertEquals(false, !!node, 'Search for not-existing node by id');
      addNodeSelectedSniffer(step6);
      HeapProfilerTestRunner.currentProfileView().performSearch({query: '@83', caseSensitive: false});
    }

    function step6(node) {
      TestRunner.assertEquals(true, !!node, 'Search for existing node by id');
      next();
    }
  }]);
})();


text:
* Added \nspl\a\lazy which contains lazy versions of function from \nspl\a where it made sense
* Added array function chaining with the \nspl\a\with function
* Added \nspl\a\in which works both on arrays and traversable objects
* Added \nspl\a\values which works both on arrays and traversable objects
* Added \nspl\a\keys which works both on arrays and traversable objects
* Added \nspl\a\dropKeys which works both on arrays and traversable objects
* Added \nspl\a\diff which works both on arrays and traversable objects
* Added \nspl\a\intersect which works both on arrays and traversable objects
* Added \nspl\a\cartesianProduct which works both on arrays and traversable objects
* Added \nspl\rnd\randomString
* Added \nspl\f\throttled higher order function
* Added \nspl\op\instanceOf_ function

## 1.2 / 2017-01-05

* Made ```\nspl\args``` PHP 7 compatible

## 1.1.1 / 2016-06-13

* Fixed ```Set::toArray()``` behaviour for empty sets. Thanks [Thomas Denoréaz](https://github.com/ThmX)

## 1.1 / 2016-05-19

* Improved performance
* Introduced new simpler and more flexible [\nspl\args](https://github.com/ihor/Nspl#nsplargs) API
* Added [Set](https://github.com/ihor/Nspl#set) data structure to ```\nspl\ds```
* Added the following functions to ```\nspl\a```
    * [partition](https://github.com/ihor/Nspl#partitionpredicate-sequence)
    * [span](https://github.com/ihor/Nspl#spanpredicate-sequence)
    * [flatMap](https://github.com/ihor/Nspl#flatmapfunction-sequence)
    * [zipWith](https://github.com/ihor/Nspl#zipwithfunction-sequence1-sequence2)
    * [filterNot](https://github.com/ihor/Nspl#filternotpredicate-sequence)
    * [second](https://github.com/ihor/Nspl#secondsequence)
    * [takeKeys](https://github.com/ihor/Nspl#takekeyssequence-array-keys)
    * [takeWhile](https://github.com/ihor/Nspl#takewhilepredicate-sequence)
    * [dropWhile](https://github.com/ihor/Nspl#dropwhilepredicate-sequence)
* Added the [id](https://github.com/ihor/Nspl#idvalue) function to ```\nspl\f```
* Moved [map](https://github.com/ihor/Nspl#mapfunction-sequence), [reduce](https://github.com/ihor/Nspl#reducefunction-sequence-initial--0) and [filter](https://github.com/ihor/Nspl#filterpredicate-sequence) from ```\nspl\f``` to ```\nspl\a```
* Moved [getType](https://github.com/ihor/Nspl#gettypevar) from ```\nspl\ds``` to ```\nspl```
* Renamed the following ```\nspl\a``` functions
    * ```moveElement``` to [reorder](https://github.com/ihor/Nspl#reorderarray-list-from-to)
    * ```extend``` to [merge](https://github.com/ihor/Nspl#mergesequence1-sequence2)
    * ```getByKey``` to [value](https://github.com/ihor/Nspl#valuearray-key-default--null)
* Fixed issue #1: [Strict mode warning](https://github.com/ihor/Nspl/issues/1)
* Fixed issue #4: [Strict error](https://github.com/ihor/Nspl/issues/4)
* Updated [documentation](https://github.com/ihor/Nspl#non-standard-php-library-nspl) and [examples](https://github.com/ihor/Nspl/tree/master/examples)

## 1.0.1 / 2016-01-24

* Fixed incompatibility issues with PHP 5.4 in ```\nspl\args``` and ```\nspl\rnd```
* Added argument validations to all NSPL modules

## 1.0 / 2016-01-17

* First release


text:
Issues and pull requests are welcome.

Please **be nice** and read the following before contributing.

- Use [feross/standard](https://github.com/feross/standard) code style
- Test before submitting pull requests - `npm test`

## Component style

- Follow code style based on src components
- All components should use the Base component as the root, unless it is an extension of another component
- Component props should be extracted using destructuring, and other props should be passed to the root Base component
- Components should pass `baseStyle` to the Base component and `style` should be reserved for the end user
- All functionality in a component should be tested
- All components should have propTypes set for all custom props
- All components and propTypes should be documented to allow for react-docgen parsing
- All components must be stateless functional components
- Delegate client-size JS to higher-order container components
- Prefer not to use external dependencies

## Component className

- The root className should match the component name
- Stateful classNames should be camelCased - e.g. `isInvalid`
- Child element and modifier classNames should be separated with an underscore - e.g. `Heading_alt`
- End-user should not be able to set className on a component


text:
package pubsub;

import javax.jms.*;
import javax.naming.InitialContext;

public class MyReceiver {
    public static void main(String[] args) {
        try {
            //1) Create and start connection
            InitialContext ctx=new InitialContext();
            TopicConnectionFactory f=(TopicConnectionFactory)ctx.lookup("myTopicConnectionFactory");
            TopicConnection con=f.createTopicConnection();
            con.start();
            //2) create topic session
            TopicSession ses=con.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
            //3) get the Topic object
            Topic t=(Topic)ctx.lookup("myTopic");
            //4)create TopicSubscriber
            TopicSubscriber receiver=ses.createSubscriber(t);

            //5) create listener object
            MyListener listener=new MyListener();

            //6) register the listener object with subscriber
            receiver.setMessageListener(listener);

            System.out.println("Subscriber1 is ready, waiting for messages...");
            System.out.println("press Ctrl+c to shutdown...");
            while(true){
                Thread.sleep(1000);
            }
        }catch(Exception e){System.out.println(e);}
    }

}


text:
#ifndef ARGS_TRANSLATOR_HPP
#define	ARGS_TRANSLATOR_HPP

// Basic defs
#include "xtranslator.hpp"

// Really specific hacks injected into ASIs to make them work properly
#include "hacks/RyosukeSetModule.hpp"       // For ryosuke plugins
#include "hacks/FindCleoScripts.hpp"        // To load *.cs scripts

// Calling convenitions
#include "translator_cdecl.hpp"             // Argument translator for cdecl funcs
#include "translator_stdcall.hpp"           // Argument translator for stdcall funcs

// Additions
#include "xtranslator_path.hpp"             // Path translators

#endif


text:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

    <PreferenceCategory android:title="@string/pref_category_general">
        <CheckBoxPreference
            android:defaultValue="true"
            android:key="@string/pref_key_notification"
            android:summary="@string/pref_notifications_summary"
            android:title="@string/pref_notifications"/>

        <CheckBoxPreference
            android:defaultValue="true"
            android:key="@string/pref_key_remember_encoding"
            android:summary="@string/pref_remember_encoding_summary"
            android:title="@string/pref_remember_encoding"/>

        <ListPreference
            android:defaultValue="@string/pref_default_encoding_default_value"
            android:entries="@array/defaultEncoding"
            android:entryValues="@array/defaultEncodingValues"
            android:key="@string/pref_key_default_encoding"
            android:summary="@string/pref_default_encoding_summary"
            android:title="@string/pref_default_encoding"/>
    </PreferenceCategory>

    <PreferenceCategory android:title="@string/pref_category_display">
        <com.markzhai.lyrichere.colorpicker.ColorPickerPreference
            alphaSlider="true"
            android:defaultValue="@android:color/holo_red_light"
            android:key="@string/pref_key_highlight_color"
            android:summary="@string/pref_color1_summary"
            android:title="@string/pref_color1_title"/>
        <com.markzhai.lyrichere.colorpicker.ColorPickerPreference
            alphaSlider="true"
            android:defaultValue="@android:color/white"
            android:key="@string/pref_key_normal_color"
            android:summary="@string/pref_color2_summary"
            android:title="@string/pref_color2_title"/>
        <com.markzhai.lyrichere.colorpicker.ColorPickerPreference
            alphaSlider="true"
            android:defaultValue="@android:color/black"
            android:key="@string/pref_key_background_color"
            android:title="@string/pref_color3_title"/>
    </PreferenceCategory>
</PreferenceScreen>


text:
package io.quarkus.arc.test.injection.assignability.generics;

import javax.enterprise.context.ApplicationScoped;

@ApplicationScoped
public class Car extends Vehicle<PetrolEngine> {
}


text: Proyectamos tu futuro


text:
Apache Quarks

(now incubating)

Join the community accelerating analytics at the edge:

http://quarks.incubator.apache.org/


text:
begin
  require 'sequel'
  puts "sequel #{Sequel::VERSION} gem found, running Sequel specs \e[32m#{'✔'}\e[0m"
rescue LoadError
  puts "sequel gem not found, not running Sequel specs \e[31m#{'✖'}\e[0m"
end


text:
<?xml version="1.0"?>
<!--
   Copyright 2004, 2005 The Apache Software Foundation

   Licensed 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.
-->

<module id="gaderian.tests.contains" version="1.0.0">
    <service-point id="uniqueService" interface="gaderian.test.IUniqueService">
        <create-instance class="gaderian.test.UniqueServiceImpl"/>
    </service-point>
    <service-point id="multipleServiceOne" interface="gaderian.test.IMultipleService">
        <create-instance class="gaderian.test.MultipleServiceImpl"/>
    </service-point>
    <service-point id="multipleServiceTwo" interface="gaderian.test.IMultipleService">
        <create-instance class="gaderian.test.MultipleServiceImpl"/>
    </service-point>
	<configuration-point id="Simple" schema-id="Datum"/>
		<schema id="Datum">
			<element name="datum">
			  <attribute name="key" required="true"/>
			  <attribute name="value" required="true"/>
				<rules>
					<create-object class="gaderian.test.config.impl.Datum"/>
					<read-attribute property="key" attribute="key"/>
					<read-attribute property="value" attribute="value"/>
					<invoke-parent method="addElement"/>
				</rules>
			</element>
		</schema>
	<contribution configuration-id="Simple">
	    <datum key="key1" value="value1"/>
		<datum key="key2" value="value2"/>
	</contribution>
</module>


text:
import os

class KeyPass(object):

  POSTGRES = '~/.pgpass'
  MONGO = '~/.mongopass'
  MYSQL = '~/.mysqlpass'

  def getDatabasePassword(self, passfile, host='*', port='*', database="*", username='*'):
    return self.getPassword(passfile, host, port, database, username)

  def getPassword(self, passfile, *args):
    with open(os.path.expanduser(passfile)) as passfile:
      for entry in passfile:
          entry = entry.strip().split(':')
          if self._matches(entry[0:len(args)], map(str, args)):
              return entry[-1]

  def _matches(self, entryPrefix, args):
    assert len(entryPrefix) == len(args)
    return all([(property == '*' or arg  == '*' or property == arg) for property, arg in zip(entryPrefix, args)])


text:
package f5

import (
	"encoding/json"
	"strings"
)

type LBServerSsl struct {
	Name                         string   `json:"name"`
	Partition                    string   `json:"partition"`
	FullPath                     string   `json:"fullPath"`
	Generation                   int      `json:"generation"`
	UntrustedCertResponseControl string   `json:"untrustedCertResponseControl"`
	UncleanShutdown              string   `json:"uncleanShutdown"`
	StrictResume                 string   `json:"strictResume"`
	SslSignHash                  string   `json:"sslSignHash"`
	SslForwardProxyBypass        string   `json:"sslForwardProxyBypass"`
	SslForwardProxy              string   `json:"sslForwardProxy"`
	SniRequire                   string   `json:"sniRequire"`
	SniDefault                   string   `json:"sniDefault"`
	ExpireCertResponseControl    string   `json:"expireCertResponseControl"`
	DefaultsFrom                 string   `json:"defaultsFrom"`
	Ciphers                      string   `json:"ciphers"`
	Chain                        string   `json:"chain"`
	Cert                         string   `json:"cert"`
	Key                          string   `json:"key"`
	CacheTimeout                 int      `json:"cacheTimeout"`
	CacheSize                    int      `json:"cacheSize"`
	AuthenticateDepth            int      `json:"authenticateDepth"`
	AlertTimeout                 string   `json:"alertTimeout"`
	SelfLink                     string   `json:"selfLink"`
	Authenticate                 string   `json:"authenticate"`
	GenericAlert                 string   `json:"genericAlert"`
	HandshakeTimeout             string   `json:"handshakeTimeout"`
	ModSslMethods                string   `json:"modSslMethods"`
	Mode                         string   `json:"mode"`
	TmOptions                    []string `json:"tmOptions"`
	PeerCertMode                 string   `json:"peerCertMode"`
	ProxySsl                     string   `json:"proxySsl"`
	ProxySslPassthrough          string   `json:"proxySslPassthrough"`
	RenegotiatePeriod            string   `json:"renegotiatePeriod"`
	RenegotiateSize              string   `json:"renegotiateSize"`
	Renegotiation                string   `json:"renegotiation"`
	RetainCertificate            string   `json:"retainCertificate"`
	SecureRenegotiation          string   `json:"secureRenegotiation"`
	SessionMirroring             string   `json:"sessionMirroring"`
	SessionTicket                string   `json:"sessionTicket"`
}

type LBServerSsls struct {
	Items []LBServerSsl `json:"items"`
}

func (f *Device) ShowServerSsls() (error, *LBServerSsls) {

	u := f.Proto + "://" + f.Hostname + "/mgmt/tm/ltm/profile/server-ssl"
	res := LBServerSsls{}

	err, _ := f.sendRequest(u, GET, nil, &res)
	if err != nil {
		return err, nil
	} else {
		return nil, &res
	}

}

func (f *Device) ShowServerSsl(sname string) (error, *LBServerSsl) {

	server := strings.Replace(sname, "/", "~", -1)
	u := f.Proto + "://" + f.Hostname + "/mgmt/tm/ltm/profile/server-ssl/" + server
	res := LBServerSsl{}

	err, _ := f.sendRequest(u, GET, nil, &res)
	if err != nil {
		return err, nil
	} else {
		return nil, &res
	}

}

func (f *Device) AddServerSsl(body *json.RawMessage) (error, *LBServerSsl) {

	u := f.Proto + "://" + f.Hostname + "/mgmt/tm/ltm/profile/server-ssl"
	res := LBServerSsl{}

	// post the request
	err, _ := f.sendRequest(u, POST, &body, &res)
	if err != nil {
		return err, nil
	} else {
		return nil, &res
	}

}

func (f *Device) UpdateServerSsl(sname string, body *json.RawMessage) (error, *LBServerSsl) {

	server := strings.Replace(sname, "/", "~", -1)
	u := f.Proto + "://" + f.Hostname + "/mgmt/tm/ltm/profile/server-ssl/" + server
	res := LBServerSsl{}

	// put the request
	err, _ := f.sendRequest(u, PUT, &body, &res)
	if err != nil {
		return err, nil
	} else {
		return nil, &res
	}

}

func (f *Device) DeleteServerSsl(sname string) (error, *Response) {

	server := strings.Replace(sname, "/", "~", -1)
	u := f.Proto + "://" + f.Hostname + "/mgmt/tm/ltm/profile/server-ssl/" + server
	res := json.RawMessage{}

	err, resp := f.sendRequest(u, DELETE, nil, &res)
	if err != nil {
		return err, nil
	} else {
		return nil, resp
	}

}


text:
<?php

namespace Application\Migrations;

use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;

/**
 * Auto-generated Migration: Please modify to your needs!
 */
class Version20140304180306 extends AbstractMigration
{
    public function up(Schema $schema)
    {
        // this up() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != "mysql", "Migration can only be executed safely on 'mysql'.");

        $this->addSql("CREATE TABLE Groupe (id INT AUTO_INCREMENT NOT NULL, nom VARCHAR(255) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB");
        $this->addSql("CREATE TABLE users_group (groupe_id INT NOT NULL, user_id INT NOT NULL, INDEX IDX_8AB7E08C7A45358C (groupe_id), INDEX IDX_8AB7E08CA76ED395 (user_id), PRIMARY KEY(groupe_id, user_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB");
        $this->addSql("ALTER TABLE users_group ADD CONSTRAINT FK_8AB7E08C7A45358C FOREIGN KEY (groupe_id) REFERENCES Groupe (id)");
        $this->addSql("ALTER TABLE users_group ADD CONSTRAINT FK_8AB7E08CA76ED395 FOREIGN KEY (user_id) REFERENCES fos_user (id)");
    }

    public function down(Schema $schema)
    {
        // this down() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != "mysql", "Migration can only be executed safely on 'mysql'.");

        $this->addSql("ALTER TABLE users_group DROP FOREIGN KEY FK_8AB7E08C7A45358C");
        $this->addSql("DROP TABLE Groupe");
        $this->addSql("DROP TABLE users_group");
    }
}


text:
FROM golang:1.10

# install sqlite3 for option "-console"
RUN apt-get update && apt-get install -y sqlite3

WORKDIR /go/src/app
COPY . .

RUN go get -d -v ./...
RUN go install -v ./...

WORKDIR /tmp

ENTRYPOINT ["textql"]


text:
module Genome
  module Importers
    module TdgClinicalTrial

      def self.source_info
        {
          base_url:          'https://clinicaltrials.gov/ct2/results?Search=Search&term=',
          site_url:          'http://www.ncbi.nlm.nih.gov/pubmed/24016212',
          citation:          "The druggable genome: Evaluation of drug targets in clinical trials suggests major shifts in molecular class and indication. Rask-Andersen M, Masuram S, Schioth HB. Annu Rev Pharmacol Toxicol. 2014;54:9-26. doi: 10.1146/annurev-pharmtox-011613-135943. PMID: 24016212",
          source_db_version:  'Jan-2014',
          source_type_id:    DataModel::SourceType.INTERACTION,
          source_db_name:    'TdgClinicalTrial',
          full_name:         'The Druggable Genome: Evaluation of Drug Targets in Clinical Trials Suggests Major Shifts in Molecular Class and Indication (Rask-Andersen, Masuram, Schioth 2014)',
          license: 'Supplementary table from Annual Reviews copyright publication',
          license_link: 'https://www.annualreviews.org/doi/10.1146/annurev-pharmtox-011613-135943?url_ver=Z39.88-2003&rfr_id=ori%3Arid%3Acrossref.org&rfr_dat=cr_pub++0pubmed',
        }
      end

      def self.run(tsv_path)
        blank_filter = ->(x) { x.blank? || x == "''" || x == '""' }
        upcase = ->(x) {x.upcase}
        downcase = ->(x) {x.downcase}
        TSVImporter.import tsv_path, TdgClinicalTrialRow, source_info do
          interaction known_action_type: 'unknown' do
            gene :uniprot_id, nomenclature: 'Uniprot Accession' do
              name :gene_symbol, nomenclature: 'Gene Symbol', unless: blank_filter
              attribute :target_main_class, name: 'Target Class', unless: blank_filter
              attributes :target_subclass, name: 'Target Subclass', unless: blank_filter
            end

            drug :drug_name, nomenclature: 'Drug Name', primary_name: :drug_name, transform: upcase do
              attributes :indication, name: 'Drug Indications', unless: blank_filter
              attribute :drug_class, name: 'Drug Class', unless: blank_filter
              attribute :fda_approval, name: 'FDA Approval', unless: blank_filter
            end

            attribute :trial_name, name: 'Trial Name', unless: blank_filter
            attribute :target_novelty, name: 'Novel drug target', unless: blank_filter
          end
        end.save!
        s = DataModel::Source.where(source_db_name: source_info['source_db_name'])
        s.interaction_claims.each do |ic|
          Genome::OnlineUpdater.new.create_interaction_claim_link(ic, s.citation, "https://www.annualreviews.org/doi/10.1146/annurev-pharmtox-011613-135943")
        end
      end
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<project>

	<meta title="HaxeGame" package="br.art.multisolution.haxegame" version="0.0.0" company="Multisolution" />
	<app main="Main" path="Export" file="HaxeGame" />

	<source path="Source" />

	<haxelib name="openfl" />
	<haxelib name="actuate" />
	<haxelib name="nape" />

	<assets path="Assets" rename="assets" />
	<assets path="Assets/fonts" rename="fonts" />

	<library path="Assets/library.swf" preload="true" />

	<window
		width="360" height="640"
		orientation="portrait"
		background="#FFFFFF"
		fps="60"
		hardware="true"
		fullscreen="true"
		resizable="true"
		borderless="true"
		vsync="true"
	/>

	<window resizable="false" if="mobile" />

</project>


text:
require 'minitest_helper'

describe Inquirer::Prompts::Confirm do
  before :each do
    Inquirer::IOHelper.output = ""
  end

  [
    Inquirer::Prompts::Confirm.method(:ask),
    Ask.method(:confirm)
  ].each do |meth|

    it "should return true for y and Y and enter when default" do
      Inquirer::IOHelper.keys = "y"
      meth.call("Are you sure?").must_equal true
      Inquirer::IOHelper.keys = "Y"
      meth.call("Are you sure?").must_equal true
      Inquirer::IOHelper.keys = "\r"
      meth.call("Are you sure?", default: true).must_equal true
    end

    it "should return false for n and N and enter when default" do
      Inquirer::IOHelper.keys = "n"
      meth.call("Are you sure?").must_equal false
      Inquirer::IOHelper.keys = "N"
      meth.call("Are you sure?").must_equal false
      Inquirer::IOHelper.keys = "\r"
      meth.call("Are you sure?", default: false).must_equal false
    end

    it "should return true if not default given" do
      Inquirer::IOHelper.keys = "\r"
      meth.call("Are you sure?").must_equal true
    end

    it "accepts and renders response correctly" do
      Inquirer::IOHelper.keys = "n"
      meth.call("Are you sure?")
      Inquirer::IOHelper.output.must_equal "Are you sure?: \e[36mNo\e[0m\n"

      Inquirer::IOHelper.keys = "N"
      meth.call("Are you sure?")
      Inquirer::IOHelper.output.must_equal "Are you sure?: \e[36mNo\e[0m\n"

      Inquirer::IOHelper.keys = "y"
      meth.call("Are you sure?")
      Inquirer::IOHelper.output.must_equal "Are you sure?: \e[36mYes\e[0m\n"

      Inquirer::IOHelper.keys = "y"
      meth.call("Are you sure?")
      Inquirer::IOHelper.output.must_equal "Are you sure?: \e[36mYes\e[0m\n"
    end

    it "should return default value if given and there is no input" do
      Inquirer::IOHelper.keys = "\r"
      meth.call("Are you sure?", default: "I'm default").must_equal "I'm default"
    end

  end
end


text:
import logger from '../../utils/logger'
import getCacheKey from './cacheKey'

const getCache = (key, options = {}) => async (ctx, next) => {
  const cacheKey = getCacheKey(ctx)(key, options)
  const result = await ctx.cache.get(cacheKey)
  logger.info(`[REQUEST-CACHE:GET][${cacheKey}]`)
  if (result) {
    try {
      ctx.body = {
        success: true,
        result: JSON.parse(result),
      }
      return
    } catch (e) {
      logger.debug(e)
    }
  }
  ctx.query.cacheKeys = [cacheKey]
  ctx.query.shouldCache = true
  await next()
}

const setCache = (options = {}) => async (ctx) => {
  const { cacheKeys, shouldCache } = ctx.query
  const { result } = ctx.body
  const expire = options.expire || 86400 * 3 // three days

  if (cacheKeys && cacheKeys.length && result && shouldCache) {
    for (let i = 0; i < cacheKeys.length; i += 1) {
      const cacheKey = cacheKeys[i]
      logger.info(`[REQUEST-CACHE:SET][${cacheKey}]`)
      await ctx.cache.set(cacheKey, JSON.stringify(result), 'EX', expire)
    }
  }
}

const removeCache = (keys = []) => async (ctx) => {
  const targetKeys = ctx.query.deleteKeys || keys
  for (let i = 0; i < targetKeys.length; i += 1) {
    logger.info(`[REQUEST-CACHE:DEL][${targetKeys[i]}]`)
    await ctx.cache.expire(targetKeys[i], 0)
  }
}

export default {
  get: getCache,
  set: setCache,
  del: removeCache
}


text:
package org.egzi.springconfigurator.context.manager.standalone;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class StandaloneContext {

    @Bean
    public Object  aloneBean() {
        return new Object();
    }
}


text:
using System;
using System.Collections.Generic;
using System.Text;

using PacketDotNet;
using SharpPcap;

namespace ConnStealing
{
    public abstract class WrapperBase
    {
        public string Msg;
    }

    public class PacketWrapper : WrapperBase
    {
        private IpPacket ipPacket;
        private RawCapture rawCapture;
        private TcpPacket tcpPacket;

        public int Count { get; protected set; }
        public string SrcIp { get { return ipPacket.SourceAddress.ToString(); } }
        public ushort SrcPort { get { return tcpPacket.SourcePort; } }
        public string DestIp { get { return ipPacket.DestinationAddress.ToString(); } }
        public ushort DestPort { get { return tcpPacket.DestinationPort; } }
        public string Protocol { get { return ipPacket.Protocol.ToString(); } }
        public string Length { get { return String.Format("{0}({1})", Msg.Length, tcpPacket.PayloadData.Length); } }
        public string Time
        {
            get
            {
                DateTime time = rawCapture.Timeval.Date;
                return String.Format("{0}:{1}:{2},{3}", time.Hour, time.Minute, time.Second, time.Millisecond);
            }
        }

        public PacketWrapper(TcpRecon tcpRecon)
        {
            Count = ++CaptureForm.packetCount;
            ipPacket = tcpRecon.IpPacket;
            rawCapture = tcpRecon.RawCapture;
            tcpPacket = tcpRecon.TcpPacket;
            Msg = tcpRecon.Msg.ToString();
        }
    }

    public class PacketWrapper2 : WrapperBase
    {
        public RawCapture rawPacket;
        public IpPacket ipPacket;
        public TcpPacket tcpPacket;

        public int Count { get; protected set; }
        public ushort MyPort { get; private set; }
        public string Destination { get; private set; }
        public string Flags { get; private set; }
        public uint Sequence { get; private set; }
        public uint Acknowledgment { get; private set; }
        public int Len { get; private set; }
        public ulong Time { get; private set; }

        public PacketWrapper2(RawCapture rawCapture)
        {
            rawPacket = rawCapture;
            Packet packet = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data);
            ipPacket = IpPacket.GetEncapsulated(packet);
            tcpPacket = TcpPacket.GetEncapsulated(packet);

            Count = ++CaptureForm.packetCount;
            if (ipPacket.SourceAddress.Equals(CaptureForm.MyIp))
            {
                MyPort = tcpPacket.SourcePort;
                Destination = "sent";
            }
            else
            {
                MyPort = tcpPacket.DestinationPort;
                Destination = "received";
            }

            Flags = "[";
            if (tcpPacket.Syn) Flags += "SYN";
            else if (tcpPacket.Psh) Flags += "PSH";
            else if (tcpPacket.Fin) Flags += "FIN";
            if (tcpPacket.Ack)
            {
                if (Flags.Length > 1) Flags += ",";
                Flags += "ACK";
            }
            Flags += "]";

            Sequence = tcpPacket.SequenceNumber;
            Acknowledgment = tcpPacket.AcknowledgmentNumber;
            Len = tcpPacket.PayloadData.Length;
            Time = rawCapture.Timeval.MicroSeconds;
            Msg = Encoding.ASCII.GetString(tcpPacket.PayloadData);
        }
    }
}


text:
var express = require("express");
var alexa = require("alexa-app");
const request = require('request');
const config = require('./config');

const YelpClient = require('./yelp/client');
let appYelpClient = new YelpClient(config, request);

var PORT = process.env.port || 8080;
var app = express();

// ALWAYS setup the alexa app and attach it to express before anything else.
var alexaApp = new alexa.app("test");

alexaApp.express({
    expressApp: app,

    // verifies requests come from amazon alexa. Must be enabled for production.
    // You can disable this if you're running a dev environment and want to POST
    // things to test behavior. enabled by default.
    checkCert: false,

    // sets up a GET route when set to true. This is handy for testing in
    // development, but not recommended for production. disabled by default
    debug: true
});

// now POST calls to /test in express will be handled by the app.request() function

// from here on you can setup any other express routes or middlewares as normal
app.set("view engine", "ejs");

alexaApp.launch(function (request, response) {
    response.say("You launched the app!");
});

alexaApp.dictionary = {
    "names": ["bob", "tejas", "oskar"],
    foods: ['pizza', 'pasta', 'burgers', 'sushi', 'sandwiches', 'soup', 'asian']
};

alexaApp.intent("foodIntent", {
        "slots": {
            "FOOD": "LITERAL",
            "LOCATION": "LOCATION" //this needs to be defined in the amazon dev portal
        },
        "utterances": [
            "i want to eat {foods|FOOD} in {-|LOCATION}",
            "best place for {foods|FOOD} in {-|LOCATION}"
        ]
    },
    function (request, response) {
        let session = request.getSession(),
            place = request.slot("LOCATION"),
            food = request.slot("FOOD"),
            restaurantLocation = [];

        if (!food) {
            return response.say('You must specify a valid food type!');
        }

        if (!place) {
            return response.say('Cannot determine location');
        }

        var normalizeGermanChars = (value)=> {
            value = value.replace(/ä/g, 'ae');
            value = value.replace(/ö/g, 'oe');
            value = value.replace(/ü/g, 'ue');
            value = value.replace(/ß/g, 'ss');
            value = value.replace(/&/g, 'and');
            return value;
        };

        return appYelpClient.search(food, place).then((resp)=> {
            let restaurants = resp.businesses.reduce((names, item, index)=> {
                if (!names) {
                    names = [];
                }

                let locationIndex = (index + 1),
                    restaurantName = normalizeGermanChars(item.name);

                restaurantLocation[locationIndex] = `${item.location.address1} ${item.location.city}`;
                return names.concat(`${locationIndex}. ${restaurantName}`);
            }, []).join(',');

            if (!restaurants.length) {
                throw Error('Could not get a proper response!');
            }

            restaurantLocation.forEach((item, index)=> {
                session.set('restaurant-' + index, item);
            });

            response.say(`top restaurants in ${place} are ${restaurants}`);
            response.shouldEndSession(false);
        }).catch((err)=> {
            console.error(err);
            response.say('Could not determine top restaurants!');
        });
    }
);

alexaApp.intent("addressFoodIntent", {
        "slots": {
            "NR": "AMAZON.NUMBER"
        },
        "utterances": [
            "address of {-|NR}", "where is number {-|NR}"
        ]
    },
    function (request, response) {
        let session = request.getSession(),
            restaurantNr = request.slot("NR"),
            restaurantAddress = session.get('restaurant-' + restaurantNr);

        if (restaurantNr === undefined || restaurantNr === null) {
            response.say(`You must give a 1 to 5 restaurant!`);
            response.card({
                type: "Simple",
                content: `Cannot determine location of ${restaurantNr}`
            });
            response.shouldEndSession(false);
            return;
        }

        if (!session.get('restaurant-1')) {
            return response.say('You must require top place first!');
        }

        if (restaurantNr > 5) {
            response.say(`Only using top 5 recomandations!`);
            response.shouldEndSession(false);
            return;
        }

        if (restaurantAddress) {
            response.say(
                `Address of ${restaurantNr} is ${restaurantAddress}.
                Please rate from 1 to 5 your experience.`
            );
            return;
        }

        response.say('Could not determine the location of the restaurant');
        response.card({
            type: "Simple",
            content: `Cannot determine location of ${restaurantNr}`
        });
    }
);

alexaApp.intent("ratingIntent", {
        "slots": {
            "NR": "AMAZON.NUMBER"
        },
        "utterances": [
            "{-|NR} out of five", "rating {-|NR}"
        ]
    },
    function (request, response) {
        let rating = request.slot("NR");

        if (!rating) {
            response.say('Invalid rating, please rate us again.');
            response.card({
                type: "Simple",
                content: `Cannot determine rating of ${rating}`
            });
            return;
        }

        if (rating <= 5 && rating >= 1) {
            return response.say('Thank you for rating us!')
        }

        return response.say('Invalid rating!');
    }
);

app.listen(PORT);
console.log("Listening on port " + PORT + ", try http://localhost:" + PORT + "/test");


text:
!function( $ ){

  "use strict"

  /* DROPDOWN PLUGIN DEFINITION
   * ========================== */

  $.fn.dropdown = function ( selector ) {
    return this.each(function () {
      $(this).delegate(selector || d, 'click', function (e) {
        var li = $(this).parent('li')
          , isActive = li.hasClass('open')

        clearMenus()
        !isActive && li.toggleClass('open')
        return false
      })
    })
  }

  /* APPLY TO STANDARD DROPDOWN ELEMENTS
   * =================================== */

  var d = 'a.menu, .dropdown-toggle'

  function clearMenus() {
    $(d).parent('li').removeClass('open')
  }

  $(function () {
    $('html').bind("click", clearMenus)
  })

}(window.jQuery || window.ender);


text:
package v1alpha1

import (
	"context"

	"github.com/tektoncd/pipeline/pkg/apis/config"
	"knative.dev/pkg/apis"
)

var _ apis.Defaultable = (*Run)(nil)

// SetDefaults implements apis.Defaultable
func (r *Run) SetDefaults(ctx context.Context) {
	ctx = apis.WithinParent(ctx, r.ObjectMeta)
	r.Spec.SetDefaults(apis.WithinSpec(ctx))
}

// SetDefaults implements apis.Defaultable
func (rs *RunSpec) SetDefaults(ctx context.Context) {
	cfg := config.FromContextOrDefaults(ctx)
	defaultSA := cfg.Defaults.DefaultServiceAccount
	if rs.ServiceAccountName == "" && defaultSA != "" {
		rs.ServiceAccountName = defaultSA
	}
	defaultPodTemplate := cfg.Defaults.DefaultPodTemplate
	if rs.PodTemplate == nil {
		rs.PodTemplate = defaultPodTemplate
	}
}


text:
"use strict";
var util = require('util');

var errors = require('./errors');
var types = require('./types');
var utils = require('./utils');
var requests = require('./requests');
var retry = require('./policies/retry');

/**
 * Handles a request to Cassandra, dealing with host fail-over and retries on error
 * @param {?Client} client Client instance used to retrieve and set the keyspace. It can be null.
 * @param {Object} options
 * @constructor
 */
function RequestHandler(client, options) {
  this.client = client;
  this.loadBalancingPolicy = options.policies.loadBalancing;
  this.retryPolicy = options.policies.retry;
  this.logEmitter = options.logEmitter;
  this.retryCount = 0;
  //current request being executed.
  this.request = null;
  //the options for the request.
  this.requestOptions = null;
  //The host selected by the load balancing policy to execute the request
  /** @type {Host} */
  this.host = null;
  /** @type {Connection} */
  this.connection = null;
  /** @type {Function} */
  this.retryHandler = null;
  this.stackContainer = {};
  this.triedHosts = {};
}

/**
 * Gets a connection from the next host according to the load balancing policy
 * @param {QueryOptions} queryOptions
 * @param {function} callback
 */
RequestHandler.prototype.getNextConnection = function (queryOptions, callback) {
  var self = this;
  var keyspace;
  if (this.client) {
    keyspace = this.client.keyspace;
  }
  if (this.hostIterator) {
    return self.iterateThroughHosts(this.hostIterator, callback);
  }
  this.loadBalancingPolicy.newQueryPlan(keyspace, queryOptions, function (err, iterator) {
    if (err) return callback(err);
    self.hostIterator = iterator;
    self.iterateThroughHosts(self.hostIterator, callback);
  });
};

/**
 * Uses the iterator to try to acquire a connection from a host
 * @param {{next: function}} iterator
 * @param {Function} callback callback(err, connection, host) to use
 */
RequestHandler.prototype.iterateThroughHosts = function (iterator, callback) {
  var host;
  var connection = null;
  var self = this;
  utils.whilst(
    function condition() {
      //while there isn't a valid connection
      if (connection) {
        return false;
      }
      var item = iterator.next();
      host = item.value;
      return (!item.done);
    },
    function whileIterator(next) {
      if (!host.isUp()) {
        self.triedHosts[host.address] = 'Host considered as DOWN';
        return next();
      }
      //the distance relative to the client, using the load balancing policy
      var distance = self.loadBalancingPolicy.getDistance(host);
      host.setDistance(distance);
      if (distance === types.distance.ignored) {
        //If its marked as ignore by the load balancing policy, move on.
        return next();
      }
      var c;
      utils.series([
        function borrowingConnection(next) {
          host.borrowConnection(function (err, pooledConnection) {
            c = pooledConnection;
            next(err);
          });
        },
        function changingKeyspace(next) {
          if (!self.client) {
            //There isn't a client, so there isn't an active keyspace
            return next();
          }
          //Try to change, if the connection is on the same connection it wont change it.
          c.changeKeyspace(self.client.keyspace, next);
        }
      ], function (err) {
        if (err) {
          //Cannot get a connection
          //Its a bad host
          self.triedHosts[host.address] = err;
          host.setDown();
        }
        else {
          self.host = host;
          connection = c;
        }
        next();
      });
    },
    function whilstEnded(err) {
      if (err) {
        return callback(err);
      }
      if (!connection) {
        return callback(new errors.NoHostAvailableError(self.triedHosts));
      }
      callback(null, connection, host);
    });
};

RequestHandler.prototype.log = utils.log;

/**
 * Gets an available connection and sends the request
 * @param request
 * @param {QueryOptions} options
 * @param {Function} callback
 */
RequestHandler.prototype.send = function (request, options, callback) {
  if (this.request === null) {
    //Set the first time
    if (options && options.captureStackTrace) {
      //noinspection JSUnresolvedFunction
      Error.captureStackTrace(this.stackContainer);
    }
    if (options && options.retry) {
      this.retryPolicy = options.retry;
    }
  }
  this.request = request;
  this.requestOptions = options;
  var self = this;
  this.getNextConnection(options, function (err, c) {
    if (err) {
      //No connection available
      return callback(err);
    }
    self.connection = c;
    self.sendOnConnection(request, options, callback);
  });
};

/**
 * Sends a request to the current connection, adapting the result and retrying, if necessary.
 * @param request
 * @param {QueryOptions} options
 * @param {Function} callback
 */
RequestHandler.prototype.sendOnConnection = function (request, options, callback) {
  var self = this;
  this.connection.sendStream(request, options, function readCallback(err, response) {
    if (err) {
      //Something bad happened, maybe retry or do something about it
      return self.handleError(err, callback);
    }
    //it looks good, lets ensure this host is marked as UP
    self.host.setUp();
    response = response || utils.emptyObject;
    var result = new types.ResultSet(response, self.host.address, self.triedHosts, self.request.consistency);
    if (result.info.warnings) {
      //log the warnings
      result.info.warnings.forEach(function (message, i, warnings) {
        self.log('warning', util.format(
          'Received warning (%d of %d) "%s" for query "%s"',
          i + 1,
          warnings.length,
          message,
          self.request.query));
      });
    }
    if (response.schemaChange) {
      self.client.waitForSchemaAgreement(self.connection, function (err) {
        if (err) {
          //we issue a warning but we continue with the normal flow
          self.log('warning', 'There was an error while waiting for the schema agreement between nodes', err);
        }
        callback(null, result);
      });
      return;
    }
    if (response.keyspaceSet) {
      self.client.keyspace = response.keyspaceSet;
    }
    callback(null, result);
  });
};

/**
 * Executed once there is a request timeout
 * @param {Error} err
 * @param {Function} callback
 */
RequestHandler.prototype.onTimeout = function (err, callback) {
  this.log('warning', err.message);
  this.host.checkHealth(this.connection);
  //Always retry on next host for PREPARE requests and when specified by user
  var executeOnNextHost =
    (this.requestOptions && this.requestOptions.retryOnTimeout) ||
    this.request instanceof requests.PrepareRequest;
  if (executeOnNextHost) {
    return this.send(this.request, this.requestOptions, callback);
  }
  callback(err);
};

/**
 * Sets the keyspace in any connection that is already opened.
 * @param {Function} callback
 */
RequestHandler.prototype.setKeyspace = function (callback) {
  var connection;
  var hosts = this.client.hosts.values();
  for (var i = 0; i < hosts.length; i++) {
    this.host = hosts[i];
    connection = this.host.getActiveConnection();
    if (connection) {
      break;
    }
  }
  if (!connection) {
    return callback(new errors.DriverInternalError('No active connection found'));
  }
  connection.changeKeyspace(this.client.keyspace, callback);
};

/**
 * Sends multiple prepare requests on the next connection available
 * @param {Array.<string>} queries
 * @param {Array.<function>} callbacksArray
 * @param {QueryOptions} options
 * @param {function} callback
 */
RequestHandler.prototype.prepareMultiple = function (queries, callbacksArray, options, callback) {
  //noinspection JSUnresolvedFunction
  Error.captureStackTrace(this.stackContainer);
  var self = this;
  this.retryHandler = function () {
    //Use a custom retryHandler
    self.prepareMultiple(queries, callbacksArray, options, callback);
  };
  this.getNextConnection(options, function (err, c) {
    if (err) {
      //No connection available, no point on retrying
      return callback(err);
    }
    self.connection = c;
    self.prepareOnConnection(queries, callbacksArray, callback);
  });
};

/**
 * Serially prepares multiple queries on the current connection and handles retry if necessary
 * @param {Array.<string>} queries
 * @param {Array.<function>} callbacksArray
 * @param {function} callback
 */
RequestHandler.prototype.prepareOnConnection = function (queries, callbacksArray, callback) {
  var self = this;
  var index = 0;
  utils.eachSeries(queries, function (query, next) {
    self.connection.prepareOnce(query, function (err, response) {
      if (callbacksArray) {
        callbacksArray[index++](err, response);
      }
      next(err);
    });
  }, function (err) {
    if (err) {
      return self.handleError(err, callback);
    }
    callback();
  });
};

/**
 * Checks if the exception is either a Cassandra response error or a socket exception to retry or failover if necessary.
 * @param {Error} err
 * @param {Function} callback
 */
RequestHandler.prototype.handleError = function (err, callback) {
  //Add the error to the tried hosts
  this.triedHosts[this.host.address] = err;
  err['coordinator'] = this.host.address;
  var decisionInfo = { decision: retry.RetryPolicy.retryDecision.rethrow };
  //noinspection JSUnresolvedVariable
  if (err && err.isServerUnhealthy) {
    this.host.setDown();
    return this.retry(callback);
  }
  if (err instanceof errors.OperationTimedOutError) {
    return this.onTimeout(err, callback);
  }
  if (err instanceof errors.ResponseError) {
    var requestInfo = {
      request: this.request,
      handler: this,
      nbRetry: this.retryCount
    };
    switch (err.code) {
      case types.responseErrorCodes.unprepared:
        //noinspection JSUnresolvedVariable
        return this.prepareAndRetry(err.queryId, callback);
      case types.responseErrorCodes.overloaded:
      case types.responseErrorCodes.isBootstrapping:
      case types.responseErrorCodes.truncateError:
        //always retry
        return this.retry(callback);
      case types.responseErrorCodes.unavailableException:
        //noinspection JSUnresolvedVariable
        decisionInfo = this.retryPolicy.onUnavailable(requestInfo, err.consistencies, err.required, err.alive);
        break;
      case types.responseErrorCodes.readTimeout:
        //noinspection JSUnresolvedVariable
        decisionInfo = this.retryPolicy.onReadTimeout(requestInfo, err.consistencies, err.received, err.blockFor, err.isDataPresent);
        break;
      case types.responseErrorCodes.writeTimeout:
        //noinspection JSUnresolvedVariable
        decisionInfo = this.retryPolicy.onWriteTimeout(requestInfo, err.consistencies, err.received, err.blockFor, err.writeType);
        break;
    }
  }
  if (decisionInfo && decisionInfo.decision === retry.RetryPolicy.retryDecision.retry) {
    return this.retry(callback);
  }
  if (this.requestOptions && this.requestOptions.captureStackTrace) {
    //Fill error information and return it
    utils.fixStack(this.stackContainer.stack, err);
  }
  if (this.request instanceof requests.QueryRequest || this.request instanceof requests.ExecuteRequest) {
    err['query'] = this.request.query;
  }
  callback(err);
};

RequestHandler.prototype.retry = function (callback) {
  this.retryCount++;
  this.log('info', 'Retrying request');
  if (this.retryHandler) {
    return this.retryHandler(callback);
  }
  this.send(this.request, this.requestOptions, callback);
};

/**
 * Prepares the query and retries on the SAME host
 * @param {Buffer} queryId
 * @param {Function} callback
 */
RequestHandler.prototype.prepareAndRetry = function (queryId, callback) {
  this.log('info', util.format('Query 0x%s not prepared on host %s, preparing and retrying', queryId.toString('hex'), this.host.address));
  var self = this;
  function retryRequest (err) {
    if (err) {
      //Could not be prepared or retried, just send the error to caller
      return callback(err)
    }
    self.sendOnConnection(self.request, self.requestOptions, callback);
  }
  if (this.request instanceof requests.ExecuteRequest) {
    //Its a single Execute of a prepared statement
    this.prepareOnConnection([this.request.query], [function (err, response) {
      if (err) return; //let the error be handle at general callback level
      if (!Buffer.isBuffer(response.id) ||
        response.id.length !== self.request.queryId.length ||
        response.id.toString('hex') !== self.request.queryId.toString('hex')
      ) {
        self.log('warning', util.format('Unexpected difference between query ids for query "%s" (%s !== %s)',
          self.request.query,
          response.id.toString('hex'),
          self.request.queryId.toString('hex')));
        self.request.queryId = response.id;
      }
    }], retryRequest);
    return;
  }
  if (this.request instanceof requests.BatchRequest) {
    //Its a BATCH of prepared statements
    //We need to prepare all the different queries in the batch in the current host
    var queries = {};
    this.request.queries.forEach(function (item) {
      //Unique queries
      queries[item.query] = item.info;
    });
    var queryStrings = Object.keys(queries);
    var singleCallbacks = new Array(queryStrings.length);
    queryStrings.forEach(function (query, i) {
      var info = queries[query];
      singleCallbacks[i] = function singlePrepareCallback(err, response) {
        if (err) return; //let the error be handle at general callback level
        if (!Buffer.isBuffer(response.id) ||
          response.id.length !== info.queryId.length ||
          response.id.toString('hex') !== info.queryId.toString('hex')
        ) {
          self.log('warning', util.format('Unexpected difference between query ids for query "%s" (%s !== %s)',
            info.query,
            response.id.toString('hex'),
            info.queryId.toString('hex')));
          info.queryId = response.id;
        }
      }
    });
    this.prepareOnConnection(queryStrings, singleCallbacks, retryRequest);
    return;
  }
  return callback(new errors.DriverInternalError('Obtained unprepared from wrong request'));
};

module.exports = RequestHandler;


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

    <title>Assert-Equal :: Blade :: PowerShell Testing Module</title>
	<link href="styles.css" type="text/css" rel="stylesheet" />

Topics

about_Blade

Commands

Assert-Contains

Assert-ContainsLike

Assert-ContainsNotLike

Assert-DirectoryDoesNotExist

Assert-DirectoryExists

Assert-DoesNotContain

Assert-Empty

Assert-Equal

Assert-Error

Assert-False

Assert-FileContains

Assert-FileDoesNotExist

Assert-FileExists

Assert-GreaterThan

Assert-Is

Assert-LastProcessFailed

Assert-LastProcessSucceeded

Assert-LessThan

Assert-Like

Assert-Match

Assert-NodeDoesNotExist

Assert-NodeExists

Assert-NoError

Assert-NotEmpty

Assert-NotEqual

Assert-NotNull

Assert-Null

Assert-True

New-AssertionException

New-TempDirectory

New-TempDirectoryTree

Test-NodeExists

Scripts

blade.ps1

Import-Blade.ps1

Assert-Equal

Asserts that two objects are equal.

Syntax

Assert-Equal [[-Expected] <Object>] [[-Actual] <Object>] [[-Message] <String>] [-CaseSensitive] [<CommonParameters>]

Description

Uses PowerShell's -eq operator to test if two objects are equal.  To perform a case-sensitive comparison with the -ceq operator, use the -CaseSensitive switch.

 Parameters

				Name
                Type
				Description
				Required?
				Pipeline Input
				Default Value

				Expected
				Object
				The expected value.

				false
				false

				Actual
				Object
				The actual value.

				false
				false

				Message
				String
				A message to show when the assertion fails.

				false
				false

				CaseSensitive
				SwitchParameter
				Performs a case-sensitive equality comparison.

				false
				false
                False

EXAMPLE 1

Assert-Equal 'foo' 'FOO'

Demonstrates that the equality is case-insensitive.

EXAMPLE 2

Assert-Equal 'foo' 'FOO' -CaseSensitive

Demonstrates that the equality is case-insensitive.

EXAMPLE 3

Assert-Equal 'foo' 'bar' 'The bar didn''t foo!'

Demonstrates how to include your own message when the assertion fails.


text:
/**
 * ArrayOfParameterBagItem.java
 *
 * This file was auto-generated from WSDL
 * by the Apache Axis 1.2 May 03, 2005 (02:20:24 EDT) WSDL2Java emitter.
 */

package com.avalara.avatax.services.tax;

import com.avalara.avatax.services.base.Utility;

import java.util.ArrayList;

/**
 * Copyright (c) 2005, Avalara.  All rights reserved.
 */
public class ArrayOfParameterBagItem  implements java.io.Serializable {
    private com.avalara.avatax.services.tax.ParameterBagItem[] parameterBagItem;

    /**
     * Initializes a new instance of the class with an empty array of {@link ParameterBagItem} objects.
     */
    public ArrayOfParameterBagItem() {
        parameterBagItem = new ParameterBagItem[0];
    }

    /**
     * Initializes a new instance of the classand and its internal array
     * of {@link ParameterBagItem} objects.
     * @param parameterBagItem
     */
    public ArrayOfParameterBagItem(
            com.avalara.avatax.services.tax.ParameterBagItem[] parameterBagItem) {
        this.parameterBagItem = parameterBagItem;
    }

    /**
     * Retrieves the raw array of {@link ParameterBagItem} objects encapsulated in
     * this object.
     *
     * @return parameterBagItem warning this may be null, depending on how the object
     * was initialized.
     */
    public com.avalara.avatax.services.tax.ParameterBagItem[] getParameterBagItem() {
        return parameterBagItem;
    }

    /**
     * Allows one to programatically set the raw array of {@link ParameterBagItem} objects
     * encapsulated by this object.
     *
     * @param parameterBagItem
     */
    public void setParameterBagItem(com.avalara.avatax.services.tax.ParameterBagItem[] parameterBagItem) {
        if (parameterBagItem != null)
        {
            this.parameterBagItem = parameterBagItem;
        }
        else
        {
            this.parameterBagItem = new ParameterBagItem[0];
        }
    }

    /**
     * Retrieves the ith {@link ParameterBagItem} object (counting from 0) from the array
     * of ParameterBagItems encapsulated in this object. Should only be used if its known
     * that {@link #getParameterBagItem} returns a non-null value and that i < number of ParameterBagItems
     * actually in that array.
     *
     * @param i integer from 0 to (number of ParameterBagItems -1)
     *
     * @return ParameterBagItem
     */
    public com.avalara.avatax.services.tax.ParameterBagItem getParameterBagItem(int i) {
        return this.parameterBagItem[i];
    }

    /**
     * Allows one to replace the ith {@link ParameterBagItem} object (counting from 0) within the array
     * of ParameterBagItems encapsulated in this object. Should only be used if its known
     * that {@link #getParameterBagItem} returns a non-null value and that i < number of ParameterBagItems
     * actually in that array.
     *
     * @param i integer from 0 to (number of ParameterBagItems -1)
     * @param _value ParameterBagItem object to place in the indicated position of the
     * ParameterBagItem array
     */
    public void setParameterBagItem(int i, com.avalara.avatax.services.tax.ParameterBagItem _value) {
        this.parameterBagItem[i] = _value;
    }

    private java.lang.Object __equalsCalc = null;

    /**
     * Determines whether the specified Object is equal to the current Object.
     * Note: In current implementation all Java Strings members of the two
     * objects must be exactly alike, including in case, for equal to return true.
     * @param obj
     * @return true or false, indicating if the two objects are equal.
     */
    public synchronized boolean equals(java.lang.Object obj) {
        if (!(obj instanceof ArrayOfParameterBagItem)) return false;
        ArrayOfParameterBagItem other = (ArrayOfParameterBagItem) obj;
        if (obj == null) return false;
        if (this == obj) return true;
        if (__equalsCalc != null) {
            return (__equalsCalc == obj);
        }
        __equalsCalc = obj;
        boolean _equals;
        _equals = true &&
                ((this.parameterBagItem==null && other.getParameterBagItem()==null) ||
                        (this.parameterBagItem!=null &&
                                java.util.Arrays.equals(this.parameterBagItem, other.getParameterBagItem())));
        __equalsCalc = null;
        return _equals;
    }

    private boolean __hashCodeCalc = false;

    /**
     *  Serves as a hash function for a particular type,
     * suitable for use in hashing algorithms and data
     * structures like a hash table.
     * @return  hash code for this GetTaxRequest object
     * @see java.lang.Object#hashCode
     */
    public synchronized int hashCode() {
        if (__hashCodeCalc) {
            return 0;
        }
        __hashCodeCalc = true;
        int _hashCode = 1;
        if (getParameterBagItem() != null) {
            for (int i=0;
                 i<java.lang.reflect.Array.getLength(getParameterBagItem());
                 i++) {
                java.lang.Object obj = java.lang.reflect.Array.get(getParameterBagItem(), i);
                if (obj != null &&
                        !obj.getClass().isArray()) {
                    _hashCode += obj.hashCode();
                }
            }
        }
        __hashCodeCalc = false;
        return _hashCode;
    }

    // Type metadata
    private static org.apache.axis.description.TypeDesc typeDesc =
            new org.apache.axis.description.TypeDesc(ArrayOfParameterBagItem.class, true);

    static {
        typeDesc.setXmlType(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "ArrayOfParameterBagItem"));
        org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("parameterBagItem");
        elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "ParameterBagItem"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "ParameterBagItem"));
        elemField.setMinOccurs(0);
        elemField.setNillable(true);
        elemField.setMaxOccursUnbounded(true);
        typeDesc.addFieldDesc(elemField);
    }

    /**
     * Return Axis type metadata object; this method is used internally by the adapter
     * and not intended to be used by external implementation code.
     *
     * @return Type Description
     */
    public static org.apache.axis.description.TypeDesc getTypeDesc() {
        return typeDesc;
    }

    /**
     * Get Axis Custom Serializer; this method is used internally by the adapter
     * and not intended to be used by external implementation code.
     *
     * @param mechType
     * @param _javaType
     * @param _xmlType
     * @return Serializer
     */
    public static org.apache.axis.encoding.Serializer getSerializer(
            java.lang.String mechType,
            java.lang.Class _javaType,
            javax.xml.namespace.QName _xmlType) {
        return
                new  org.apache.axis.encoding.ser.BeanSerializer(
                        _javaType, _xmlType, typeDesc);
    }

    /**
     * Get Axis Custom Deserializer; this method is used internally by the adapter
     * and not intended to be used by external implementation code.
     *
     * @param mechType
     * @param _javaType
     * @param _xmlType
     * @return Deserializer
     */
    public static org.apache.axis.encoding.Deserializer getDeserializer(
            java.lang.String mechType,
            java.lang.Class _javaType,
            javax.xml.namespace.QName _xmlType) {
        return
                new  com.avalara.avatax.services.base.ser.BeanDeserializer(
                        _javaType, _xmlType, typeDesc);
    }

    // BEGIN Extensions

    /**
     * Initializes a new instance of the class and and its internal array size.
     * of {@link ParameterBagItem} objects.
     * @param size
     */
    public ArrayOfParameterBagItem(int size)
    {
        this.parameterBagItem = new ParameterBagItem[size];
    }

    /**
     * Gets the size of the array.
     * @return size
     */
    public int size()
    {
        if (parameterBagItem == null)
        {
            return 0;
        }
        else
        {
            return parameterBagItem.length;
        }
    }

    /**
     * Adds an item to the array, resizing it as needed.
     * @param address
     * @return Array position of the added item.
     */
    public int add(ParameterBagItem address)
    {
        int pos = 0;
        if (parameterBagItem == null)
        {
            parameterBagItem = new ParameterBagItem[1];
        }
        else
        {
            while (pos < parameterBagItem.length && parameterBagItem[pos] != null)
            {
                ++pos;
            }
            if (pos == parameterBagItem.length)
            {
                parameterBagItem = (ParameterBagItem[])Utility.resizeArray(parameterBagItem, pos+1);
            }
        }
        parameterBagItem[pos] = address;

        return pos;
    }

    /**
     * Retrieves the {@link address} object identified by name from the array
     * of ParameterBagItems encapsulated in this object.
     *
     * @param name
     *
     * @return ParameterBagItem if found, else null
     */
    public com.avalara.avatax.services.tax.ParameterBagItem getParameterBagItem(String name)
    {
        ParameterBagItem result = null;
        if (parameterBagItem != null)
        {
            for (int ii = 0; ii < parameterBagItem.length && result == null; ii++)
            {
                if (name.equals(parameterBagItem[ii].getName()))
                {
                    result = parameterBagItem[ii];
                }
            }
        }

        return result;
    }
    // END Extensions
}


text:
subst.py PyArray_FromDimsAndData PyArray_SimpleNewFromData *.c

# these are needed for the Numeric version of gridloop.c:
subst.py PyArray_DOUBLE NPY_DOUBLE *.c
subst.py IND DIND *.c
subst.py PyArray_FromDims PyArray_SimpleNew *.c
subst.py Numeric numpy *.c

# other typical manual adjustments (not necessary in gridloop.c):
# cast data to void* in PyArray_SimpleNewFromData
# rewrite PyArray_ContiguousFromObject (-> PyArray_FROM_OTF)

# compile and link:
# numpy=`python -c 'import numpy; print numpy.get_include()'`
# gcc ... -I$numpy
# setup.py: include_dirs=[..., numpy.get_include()]

# these are not required, but macros are recommended so we can do
# some very gridloop.c-specific substitutions:
subst.py 'a->nd' 'PyArray_NDIM(a)' *.c
subst.py 'xcoor->nd' 'PyArray_NDIM(xcoor)' *.c
subst.py 'ycoor->nd' 'PyArray_NDIM(ycoor)' *.c
subst.py 'a->dimensions\[0\]' 'PyArray_DIM(a,0)' *.c
subst.py 'a->dimensions\[1\]' 'PyArray_DIM(a,1)' *.c
subst.py 'xcoor->dimensions\[0\]' 'PyArray_DIM(xcoor,0)' *.c
subst.py 'ycoor->dimensions\[0\]' 'PyArray_DIM(ycoor,0)' *.c
subst.py 'a->descr->type_num' 'PyArray_TYPE(a)' *.c
subst.py 'xcoor->descr->type_num' 'PyArray_TYPE(xcoor)' *.c
subst.py 'ycoor->descr->type_num' 'PyArray_TYPE(ycoor)' *.c
subst.py '\(a->data \+ i\*a->strides\[0\] \+ j\*a->strides\[1\]\)' ' PyArray_GETPTR2(a, i, j)' *.c
subst.py '\(xcoor->data \+ i\*xcoor->strides\[0\]\)' ' PyArray_GETPTR1(xcoor, i)' *.c
subst.py '\(ycoor->data \+ j\*ycoor->strides\[0\]\)' ' PyArray_GETPTR1(ycoor, j)' *.c


text:
package com.metech.firefly.ui.module;

import com.metech.firefly.AppModule;
import com.metech.firefly.ui.activity.Aboutus.AboutUsFragment;
import com.metech.firefly.ui.presenter.AboutUsPresenter;
import com.squareup.otto.Bus;

import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;

@Module(
        injects = AboutUsFragment.class,
        addsTo = AppModule.class,
        complete = false
)
public class AboutUsModule {

    private final AboutUsPresenter.AboutUsView aboutUsView;

    public AboutUsModule(AboutUsPresenter.AboutUsView aboutUsView) {
        this.aboutUsView = aboutUsView;
    }

    @Provides
    @Singleton
    AboutUsPresenter provideAboutUsPresenter(Bus bus) {
        return new AboutUsPresenter(aboutUsView, bus);
    }
}


text:
import { forwardRef } from "react";

import { FontIcon, FontIconProps } from "@react-md/icon";

export const SettingsPowerFontIcon = forwardRef<HTMLElement, FontIconProps>(
  function SettingsPowerFontIcon(props, ref) {
    return (
      <FontIcon {...props} ref={ref}>
        settings_power
      </FontIcon>
    );
  }
);


text:
'use strict';

var traverse = module.exports = function (schema, opts, cb) {
  // Legacy support for v0.3.1 and earlier.
  if (typeof opts == 'function') {
    cb = opts;
    opts = {};
  }

  cb = opts.cb || cb;
  var pre = (typeof cb == 'function') ? cb : cb.pre || function() {};
  var post = cb.post || function() {};

  _traverse(opts, pre, post, schema, '', schema);
};

traverse.keywords = {
  additionalItems: true,
  items: true,
  contains: true,
  additionalProperties: true,
  propertyNames: true,
  not: true
};

traverse.arrayKeywords = {
  items: true,
  allOf: true,
  anyOf: true,
  oneOf: true
};

traverse.propsKeywords = {
  definitions: true,
  properties: true,
  patternProperties: true,
  dependencies: true
};

traverse.skipKeywords = {
  default: true,
  enum: true,
  const: true,
  required: true,
  maximum: true,
  minimum: true,
  exclusiveMaximum: true,
  exclusiveMinimum: true,
  multipleOf: true,
  maxLength: true,
  minLength: true,
  pattern: true,
  format: true,
  maxItems: true,
  minItems: true,
  uniqueItems: true,
  maxProperties: true,
  minProperties: true
};

function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
  if (schema && typeof schema == 'object' && !Array.isArray(schema)) {
    pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
    for (var key in schema) {
      var sch = schema[key];
      if (Array.isArray(sch)) {
        if (key in traverse.arrayKeywords) {
          for (var i=0; i<sch.length; i++)
            _traverse(opts, pre, post, sch[i], jsonPtr + '/' + key + '/' + i, rootSchema, jsonPtr, key, schema, i);
        }
      } else if (key in traverse.propsKeywords) {
        if (sch && typeof sch == 'object') {
          for (var prop in sch)
            _traverse(opts, pre, post, sch[prop], jsonPtr + '/' + key + '/' + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop);
        }
      } else if (key in traverse.keywords || (opts.allKeys && !(key in traverse.skipKeywords))) {
        _traverse(opts, pre, post, sch, jsonPtr + '/' + key, rootSchema, jsonPtr, key, schema);
      }
    }
    post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
  }
}

function escapeJsonPtr(str) {
  return str.replace(/~/g, '~0').replace(/\//g, '~1');
}


text:
To run: `./run.sh`

## Cryptol Specifications

From: https://github.com/GaloisInc/cryptol/tree/master/examples/contrib

## C Implementations

### simon-X-Y.c

From: https://github.com/kmarquet/bloc

License: [GPL v2](https://github.com/kmarquet/bloc/blob/master/LICENSE)

Modifications:

* made Encrypt and Decrypt directly calls KeyExpand

* removed dependencies to external libs

### speck.c

From: https://code.google.com/archive/p/speck-cipher/source/default/source

License: GPL v3 (see source file)

Modifications:

* made encrypt and decrypt directly calls speck_expandkey.

* added 128/128 test vector

## Java Implementations

From: https://github.com/timw/bc-java/tree/feature/simon-speck/core/src/main/java/org/bouncycastle/crypto/engines

License: [MIT](https://github.com/timw/bc-java/blob/feature/simon-speck/LICENSE.html)

Modifications:

* Removed Bouncy Castle dependency

* Added static encrypt and decrypt helper methods

* Added a main method with test vectors

### SimonEngine.java

TODO [#126](https://github.com/GaloisInc/saw-script/issues/126)

### SpeckEngine.java

TODO [#126](https://github.com/GaloisInc/saw-script/issues/126)

## Issues & Workarounds

* Bitcode parsing error [#122](https://github.com/GaloisInc/saw-script/issues/122)

  Workaround: Downgrade XCode Command Line Tools from 7.3 to 7.2
              (http://stackoverflow.com/questions/36250949/revert-apple-clang-version-for-nvcc)

  - Log in to: https://developer.apple.com/downloads/

  - Download and install: http://adcdownload.apple.com/Developer_Tools/Command_Line_Tools_OS_X_10.11_for_Xcode_7.2/Command_Line_Tools_OS_X_10.11_for_Xcode_7.2.dmg

  - Run the following command to switch to the old version:

    ```sudo xcode-select --switch /Library/Developer/CommandLineTools```

    to restore:

    ```sudo xcode-select --switch /Applications/XCode.app```

  - Run the following command to quickly check clang version:

    ```clang --version```

* Verifying speck.c decrypt using z3 takes too long (interestingly, verifying encrypt using z3 is fine)

  Workaround: Use abc or yices

* Others are filed in [issues](https://github.com/GaloisInc/saw-script/issues/)


text:
from collections import defaultdict
import copy

# Other imports.
from simple_rl.planning import Planner
from simple_rl.planning import ValueIteration
from simple_rl.tasks import GridWorldMDP
from simple_rl.planning.BoundedRTDPClass import BoundedRTDP

class MonotoneLowerBound(Planner):
    def __init__(self, mdp, name='MonotoneUpperBound'):
        relaxed_mdp = MonotoneLowerBound._construct_deterministic_relaxation_mdp(mdp)

        Planner.__init__(self, relaxed_mdp, name)
        self.vi = ValueIteration(relaxed_mdp)
        self.states = self.vi.get_states()
        self.vi._compute_matrix_from_trans_func()
        self.vi.run_vi()
        self.lower_values = self._construct_lower_values()

    @staticmethod
    def _construct_deterministic_relaxation_mdp(mdp):
        relaxed_mdp = copy.deepcopy(mdp)
        relaxed_mdp.set_slip_prob(0.0)
        return relaxed_mdp

    def _construct_lower_values(self):
        values = defaultdict()
        for state in self.states:
            values[state] = self.vi.get_value(state)
        return values

class MonotoneUpperBound(Planner):
    def __init__(self, mdp, name='MonotoneUpperBound'):
        Planner.__init__(self, mdp, name)
        self.vi = ValueIteration(mdp)
        self.states = self.vi.get_states()
        self.upper_values = self._construct_upper_values()

    def _construct_upper_values(self):
        values = defaultdict()
        for state in self.states:
            values[state] = 1. / (1. - self.gamma)
        return values

def main():
    test_mdp = GridWorldMDP(width=6, height=6, goal_locs=[(6, 6)], slip_prob=0.2)
    lower_value_function = MonotoneLowerBound(test_mdp).lower_values
    upper_value_function = MonotoneUpperBound(test_mdp).upper_values
    bounded_rtdp = BoundedRTDP(test_mdp, lower_values_init=lower_value_function, upper_values_init=upper_value_function)
    test_policy = bounded_rtdp.plan()
    print('Derived policy:\n{}'.format(test_policy))

if __name__ == '__main__':
    main()


text:
<!DOCTYPE html>

<title>TO COMPLETE</title>
<meta charset="UTF-8">
<meta name="description" content="TO COMPLETE">
<meta name="keywords" content="">
<meta name="robots" content="index, follow">
<link rel="canonical" href="http://www.DOMAIN.TLD/" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

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

				</button>
				Site Name

Link

Link

Example page header Subtext for header

H2

In mattis ex sed ultrices hendrerit. Proin consequat ex in bibendum congue. Fusce et justo nec sem placerat sollicitudin nec in risus. Cras blandit odio vel augue aliquam aliquet. Proin malesuada suscipit libero et mattis. Nam pharetra, dui non sagittis placerat, ante massa suscipit turpis, non molestie urna urna vitae ex. Praesent vulputate luctus dui sed fermentum. Praesent id ex neque.

Page 1

In mattis ex sed ultrices hendrerit. Proin consequat ex in bibendum congue. Fusce et justo nec sem placerat sollicitudin nec in risus. Cras blandit odio vel augue aliquam aliquet. Proin malesuada suscipit libero et mattis.

Button

Page 2

In mattis ex sed ultrices hendrerit. Proin consequat ex in bibendum congue. Fusce et justo nec sem placerat sollicitudin nec in risus. Cras blandit odio vel augue aliquam aliquet. Proin malesuada suscipit libero et mattis.

Button

Page 3

In mattis ex sed ultrices hendrerit. Proin consequat ex in bibendum congue. Fusce et justo nec sem placerat sollicitudin nec in risus. Cras blandit odio vel augue aliquam aliquet. Proin malesuada suscipit libero et mattis.

Button

Legal mentions