text:
describe( 'AppCtrl', function() {
  describe( 'isCurrentUrl', function() {
    var AppCtrl, $location, $scope;

    beforeEach( module( 'eink' ) );

    beforeEach( inject( function( $controller, _$location_, $rootScope ) {
      $location = _$location_;
      $scope = $rootScope.$new();
      AppCtrl = $controller( 'AppCtrl', { $location: $location, $scope: $scope });
    }));

    it( 'should pass a dummy test', inject( function() {
      expect( AppCtrl ).toBeTruthy();
    }));
  });
});


text:
function f = tone2freq(t)
% f = tone2freq(t)
%
% Converts a frequency from the 1/60 log2 tone
% domain into the frequency (Hz) domain

% Note: The lowest tone (0) is equal to 16 Hz.
f = 16 * 2.^(t ./ 60);

redpajama_set_name: RedPajamaGithub


text:
using CH.Testing.T2.Interface;

namespace CH.Testing.T2.Component
{
    internal sealed class ArgMappingByPosition : ISource<string>
    {
        private readonly IArgParser _argParser;
        private readonly int _pos;

        public ArgMappingByPosition(IArgParser argParser, int pos)
        {
            _argParser = argParser;
            _pos = pos;
        }

        string ISource<string>.Value
        {
            get { return _argParser.ByOrder(_pos); }
        }
    }
}


text:
package de.siebn.javaBug.android.TypeAdapters;

import android.content.res.Resources;

import de.siebn.javaBug.typeAdapter.TypeAdapters.AbstractTypeAdapter;

public class DpDimensionAdapter extends AbstractTypeAdapter<Integer> {
    public DpDimensionAdapter() {
        super(10, true);
    }

    @Override
    public String toString(Integer i) {
        return String.valueOf(i / Resources.getSystem().getDisplayMetrics().density);
    }

    @Override
    public Integer parse(Class<? extends Integer> clazz, String string) {
        return (int) Math.round((Double.parseDouble(string) * Resources.getSystem().getDisplayMetrics().density));
    }

    @Override
    public String getUnit() {
        return "dp";
    }
}


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePowersTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('da_powers', function(Blueprint $table)
		{
			$table->increments('id');
			$table->string('name')->unique();
			$table->integer('group');
			$table->foreign('group')->references('id')->on('da_power_groups');
			$table->timestamps();
		});
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		Schema::drop('da_powers');
	}

}


text:
for subj in sub-?? ; do  # for each subject
    cd ${subj}  # move into their subject directory
    subnum=`echo $subj | cut '-' -f1`  # derive the subject number
    echo processing subject $subnum  # provide an update to the user
    # read in center-of-mass coords from func data and copy to anat file
    read x y z<<<$(echo `3dCM func/*task-flanker_run-1_bold.nii.gz`)
    3dCM -set $x $y $z anat/*.nii.gz
    cd ..  # move out of subject directory
    done


text:
module.exports = (req, res) => {
  const areHelpersAvailable = typeof req.query !== 'undefined';

  res.end(`${areHelpersAvailable ? 'yes' : 'no'}:RANDOMNESS_PLACEHOLDER`);
};


text:
<?xml version="1.0"?>

<encoder xmlns="http://www.github/gregtampa/HBCTF-Battlegrounds/encoder"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://www.github/gregtampa/HBCTF-Battlegrounds/encoder">
  <name>Morse Code Encoder</name>
  <author>Thomas Shaw</author>
  <module_license>MIT</module_license>
  <description>Encodes a string into Morse code.</description>

  <type>morse_code_encoder</type>
  <type>ascii_reversible</type>
  <type>string_encoder</type>
  <platform>linux</platform>
  <platform>windows</platform>

  <reference>https://gist.github.com/mikedamage/105081</reference>

  <hint>Morse code decoders are available online e.g. https://morsecode.scphillips.com/translator.html</hint>

  <read_fact>strings_to_encode</read_fact>

  <default_input into="strings_to_encode">
    <generator type="flag_generator"/>
  </default_input>

  <output_type>encoded_strings</output_type>
</encoder>


text:
layout: post
title: "Disk capacity planning for Neo4J"
author: stelios
tags: [software, capacity planning, neo4j, utilities]
categories: [System Design, Architecture]
featured:
description: "Neo4J is a great graph database, able to store billions of nodes and relationships. This post provides an approach and ready-to-use Excel model to calculate how much space it will take on disk"
image: assets/images/capacity-planning/markus-spiske-5yEiCUynJ9w-unsplash.jpg
---

Neo4J is a [multi-featured][1] [graph][2] database, able to store [billions of items][3].
This brings up an interesting question: *how much space will it take on disk?*

## Background

A Neo4J database is composed of (or better, stores) the following discreet data items on disk
* nodes
* relationships
* properties string values are stored separately in 128 byte chunks
* Lucene indexes over properties
* other stuff: house-keeping files, logs,...

I will ignore the size of all other stuff and just focus on how the data itself affects disk consumption.

It is important to note than in a cluster setup **all nodes** contain a complete copy of the data.

## Overheads

Despite Neo's [great documentation][7], there is no central reference for the overheads and disk sizes.
This is understandable to a degree as this is something internal and not a published contract.
However, it is still a little bit annoying as one has to go in various [locations][4] to [find][5] bits and [pieces][6]

The following table gives an overview of the various items

        Item type	Size (in bytes)	Comments

        Node	15	Per node instance

        Relationship	34	Per relationship

        Property	41	Each property value, including strings

        String value	128	Strings take up whole blocks of 128b

        Indexed property	1/3 * AVG(X)	Each index entry is approximately 1/3 of the average property value size

## Example calculation

Let's give an example, to illustrate how the numbers above come into play.

Let's assume that we have a Neo4J database with the following 3 node instances (JSON representation)

1)

```javascript
{
	"labels": [ "User", "Employee" ],
    "properties":
    {
        "active":true,
        "emailAddress":"test.foo@baz.com",
        "employeeId":"1333",
        "employeeType":"Permanent",
        "firstName":"Test",
        "fullName":"Test Foo",
        "lastName":"Foo",
        "telephoneNumber": 1234,
        "usCitizen": true,
        "userName":"foo"
    },
	"indexedProperties": ["employeeId", "userName", "lastName"]
}
```

2)

```javascript
{
	"labels": [ "User", "Employee" ],
    "properties":
    {
        "active":true,
        "emailAddress":"bar@rbs.com",
        "employeeId":"1444",
        "employeeType":"Permanent",
        "firstName":"Bar",
        "fullName":"Bar Foo",
        "lastName":"Foo",
        "telephoneNumber": 4321,
        "usCitizen": false,
        "userName":"foo"
    },
	"indexedProperties": ["employeeId", "userName", "lastName"]
}
```

3)

```javascript
{
	"labels":["CostCentre"],
    "properties":
    {
        "active":true,
        "code":"id36123L2",
        "level":2,
        "name":"GALT FUND LLC"
    },
    "indexedProperties": ["code", "name"]
}
```

There are also 2 relationships with no properties attached to them

```
(1)-[MANAGER_OF]->(2)
(2)-[WORKS_FOR]->(3)
```

So for this tiny dataset we have

* 3 node instances
* 2 relationship instances
* 24 property "instances" (or better individual property values)
* ...16 of which are string values
* 8 index entries

        Item type	Multiplied	Result (in bytes)

        Node	3 * 15	45

        Relationship	2 * 34	68

        Property	24 * 41	984

        String value	16 * 128	2048 (all values are small so only one 120b chunk required)

        Indexed property	8 * 1.5	12 (average value length is ~4 bytes and Lucene calculations assume 1/3 of that per entry)

        Total		3157

So, the Neo4J database folder storing our model, will be around 3Kb on disk (provided we ignore logs and other housekeeping files)

## A calculation template

Let's consider the following example model to store in Neo4J.

![Example model][8]

To make things simple, we can choose to implement relational inheritance (in this case `User` with `Employee` and `Contact`) by simply collapsing and adding additional labels.
So an employee node will have 2 labels:`User` and `Employee`.

We should know (or at least guesstimate) the following

* how many and what type of properties each class will have
* how many instances of each class (or better, node type) we will have
* how many other nodes each one is connected to *on average*

Once we have this information, we can create an Excel similar to the following

![Neo4J Excel][9]

The right table captures how many nodes of each type we have along with the properties per node.

The left table calculates the number of relationships in total based on the averages.
So, for example, each `Country` has on average 50 `Employees` and each `Client` has 0.5 `Contacts` (because we know we have a lot of empty/unused `Client` entries).

These figures are then summed to calculate the final DB footprint.

You can download the Excel file from [this link][10] and use it as a basis for your own calculations.
The file contains a VB macro, which recalculates the totals, when you update any cell.

In case you need to add/remove lines to the tables because your model is bigger/smaller, you will need to edit this Macro.

![VB Macro][11]

There might be a more elegant way to create this Excel, but I never said I was an Excel guru ;-)
You comments and suggestions are welcome.

I hope you find it useful.

   [1]: http://neo4j.com/developer/cypher-query-language/
   [2]: http://neo4j.com/docs/stable/tutorial-traversal-java-api.html
   [3]: http://neo4j.com/docs/stable/capabilities-capacity.html
   [4]: http://neo4j.com/docs/stable/configuration-io-examples.html
   [5]: http://neo4j.com/docs/stable/configuration-caches.html
   [6]: https://lucidworks.com/blog/estimating-memory-and-storage-for-lucenesolr/
   [7]: http://neo4j.com/docs/stable/
   [8]: ../assets/images/capacity-planning/example_model.png
   [9]: ../assets/images/capacity-planning/capacity-planning-excel.png
   [10]: ../assets/resources/capacity-planning/example-neo4j-capacity-planning.xls
   [11]: ../assets/images/capacity-planning/vb_macro.png


text: alert("bbbbbbbbbbbbbbbbbb")


text:
package com.linkedin.pinot.tools;

import static com.linkedin.pinot.tools.Quickstart.printStatus;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Level;
import org.json.JSONException;

import com.google.common.collect.Lists;
import com.linkedin.pinot.common.data.Schema;
import com.linkedin.pinot.common.utils.KafkaStarterUtils;
import com.linkedin.pinot.common.utils.ZkStarter;
import com.linkedin.pinot.core.data.readers.FileFormat;
import com.linkedin.pinot.tools.Quickstart.color;
import com.linkedin.pinot.tools.admin.command.QuickstartRunner;
import com.linkedin.pinot.tools.streams.AirlineDataStream;

import kafka.server.KafkaServerStartable;

/**
 *
 *
 *
 */
public class HybridQuickstart {

  private File _offlineQuickStartDataDir;
  private File _realtimeQuickStartDataDir;
  KafkaServerStartable kafkaStarter;

  private QuickstartTableRequest prepareOfflineTableRequest() throws IOException {
    _offlineQuickStartDataDir = new File("quickStartData" + System.currentTimeMillis());

    if (!_offlineQuickStartDataDir.exists()) {
      _offlineQuickStartDataDir.mkdir();
    }

    _offlineQuickStartDataDir = new File("quickStartData" + System.currentTimeMillis());

    if (!_offlineQuickStartDataDir.exists()) {
      _offlineQuickStartDataDir.mkdir();
    }

    File schemaFile = new File(_offlineQuickStartDataDir + "/airlineStats.schema");
    File dataFile = new File(_offlineQuickStartDataDir + "/airline.avro");
    File tableCreationJsonFileName = new File(_offlineQuickStartDataDir + "/airlineStatsOffline_hybrid.json");

    FileUtils.copyURLToFile(Quickstart.class.getClassLoader().getResource("sample_data/airlineStats.schema"),
        schemaFile);
    FileUtils.copyURLToFile(Quickstart.class.getClassLoader().getResource("sample_data/airline.avro"), dataFile);

    FileUtils.copyURLToFile(
        Quickstart.class.getClassLoader().getResource("sample_data/airlineStatsOffline_hybrid.json"),
        tableCreationJsonFileName);

    String tableName = "airlineStats";
    return new QuickstartTableRequest(tableName, schemaFile, tableCreationJsonFileName, _offlineQuickStartDataDir,
        FileFormat.AVRO);
  }

  private QuickstartTableRequest prepareRealtimeTableRequest() throws IOException {
    _realtimeQuickStartDataDir = new File("quickStartData" + System.currentTimeMillis());
    String quickStartDataDirName = _realtimeQuickStartDataDir.getName();

    if (!_realtimeQuickStartDataDir.exists()) {
      _realtimeQuickStartDataDir.mkdir();
    }

    File schema = new File(quickStartDataDirName + "/airlineStats.schema");
    File tableCreate = new File(quickStartDataDirName + "/airlineStatsRealtime_hybrid.json");

    FileUtils.copyURLToFile(RealtimeQuickStart.class.getClassLoader().getResource("sample_data/airlineStats.schema"),
        schema);

    FileUtils.copyURLToFile(
        RealtimeQuickStart.class.getClassLoader().getResource("sample_data/airlineStatsRealtime_hybrid.json"),
        tableCreate);

    return new QuickstartTableRequest("airlineStats", schema, tableCreate);
  }

  private void startKafka() {
    ZkStarter.startLocalZkServer();

    kafkaStarter =
        KafkaStarterUtils.startServer(KafkaStarterUtils.DEFAULT_KAFKA_PORT, KafkaStarterUtils.DEFAULT_BROKER_ID,
            KafkaStarterUtils.DEFAULT_ZK_STR, KafkaStarterUtils.getDefaultKafkaConfiguration());

    KafkaStarterUtils.createTopic("airlineStatsEvents", KafkaStarterUtils.DEFAULT_ZK_STR);
  }

  public void execute() throws JSONException, Exception {

    QuickstartTableRequest offlineRequest = prepareOfflineTableRequest();
    QuickstartTableRequest realtimeTableRequest = prepareRealtimeTableRequest();

    File tempDir = new File("/tmp/" + System.currentTimeMillis());
    tempDir.mkdir();
    QuickstartRunner runner =
        new QuickstartRunner(Lists.newArrayList(offlineRequest, realtimeTableRequest), 2, 2, 1, tempDir, false);
    printStatus(color.YELLOW, "***** starting kafka  *****");
    startKafka();

    printStatus(color.YELLOW, "***** starting 2 servers, 2 brokers and 1 controller  *****");
    runner.startAll();
    printStatus(color.YELLOW, "***** creating a server tenant with name  airline  *****");
    runner.createServerTenantWith(1, 1, "airline");
    printStatus(color.YELLOW, "***** creating a broker tenant with name  airline_broker  *****");
    runner.createBrokerTenantWith(2, "airline_broker");

    printStatus(color.YELLOW, "***** adding airline schema  *****");
    runner.addSchema();
    printStatus(color.YELLOW, "***** adding airline offline and realtime table  *****");
    runner.addTable();
    printStatus(color.YELLOW, "***** adding airline offline segment  *****");
    runner.buildSegment();
    printStatus(color.YELLOW, "***** pushing airline offline segment to the controller  *****");
    runner.pushSegment();
    File dataFile = new File(_offlineQuickStartDataDir + "/airline.avro");
    File schemaFile = new File(_offlineQuickStartDataDir + "/airlineStats.schema");

    printStatus(color.YELLOW,
        "***** publishing data to kafka for airline realtime to start consuming event stream  *****");
    AirlineDataStream stream = new AirlineDataStream(Schema.fromFile(schemaFile), dataFile);
    stream.run();

    printStatus(color.YELLOW, "***** Pinot Hybrid with hybrid table setup is complete *****");
    printStatus(color.YELLOW, "*****    1. Sequence of operations *****");
    printStatus(color.YELLOW, "*****    2. Started 1 controller instances where tenant creation is enabled *****");
    printStatus(color.YELLOW, "*****    3. Started 2 servers and 2 brokers *****");
    printStatus(color.YELLOW, "*****    4. created a server tenant with 1 offline and 1 realtime instance *****");
    printStatus(color.YELLOW, "*****    5. Created a broker tenant with 2 instances *****");
    printStatus(color.YELLOW, "*****    6. Added a schema *****");
    printStatus(color.YELLOW, "*****    7. Created a offline and a realtime table with the tenant names created abover *****");
    printStatus(color.YELLOW, "*****    8. Created and published an offline segment *****");
    printStatus(color.YELLOW, "***** Also Started publishing a kafka stream for the realtime instance so start consuming *****");
    printStatus(color.YELLOW, "***** go to http://localhost:9000/query to run a few queries *****");

    Runtime.getRuntime().addShutdownHook(new Thread() {
      @Override
      public void run() {
        try {
          stream.shutdown();
          Thread.sleep(2000);
          printStatus(color.GREEN, "***** shutting down hybrid quick start *****");
          runner.stop();
          runner.clean();
          FileUtils.deleteDirectory(_offlineQuickStartDataDir);
          FileUtils.deleteDirectory(_realtimeQuickStartDataDir);
          KafkaStarterUtils.stopServer(kafkaStarter);
          ZkStarter.stopLocalZkServer();
        } catch (Exception e) {
        }
      }
    });
  }

  public static void main(String[] args) throws Exception {
    org.apache.log4j.Logger.getRootLogger().setLevel(Level.ERROR);
    HybridQuickstart st = new HybridQuickstart();
    st.execute();

    while (true) {

    }
  }
}


text:
<!doctype html>
File: /base1/test1.html
<script src="dest.js"></script>


text:
use std::ops::{Deref, DerefMut};
use std::collections::HashMap;

use roaring::RoaringBitmap;

use search::term::Term;
use search::token::Token;

#[derive(Debug, Clone, PartialEq)]
pub struct TermVector(HashMap<Term, RoaringBitmap>);

impl TermVector {
    pub fn new() -> TermVector {
        TermVector(HashMap::new())
    }
}

impl Deref for TermVector {
    type Target = HashMap<Term, RoaringBitmap>;

    fn deref(&self) -> &HashMap<Term, RoaringBitmap> {
        &self.0
    }
}

impl DerefMut for TermVector {
    fn deref_mut(&mut self) -> &mut HashMap<Term, RoaringBitmap> {
        &mut self.0
    }
}

impl Into<TermVector> for Vec<Token> {
    fn into(self) -> TermVector {
        let mut map = HashMap::new();

        for token in self {
            let positions = map.entry(token.term).or_insert_with(RoaringBitmap::new);
            positions.insert(token.position);
        }

         TermVector(map)
    }
}

impl Into<Vec<Token>> for TermVector {
    fn into(self) -> Vec<Token> {
        let mut vec = Vec::new();

        for (term, positions) in self.0 {
            for position in positions {
                vec.push(Token { term: term.clone(), position: position });
            }
        }

        vec.sort_by_key(|token| token.position);

        vec
    }
}


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

<title>Source code</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

001
016
017package com.palamida.util.collect;
018
019import static com.google.common.base.Preconditions.checkNotNull;
020import static com.google.common.base.Preconditions.checkState;
021import static com.palamida.util.collect.TreeSet.Color.BLACK;
022import static com.palamida.util.collect.TreeSet.Color.RED;
023
024import java.io.Serializable;
025import java.util.AbstractSet;
026import java.util.Collection;
027import java.util.Comparator;
028import java.util.ConcurrentModificationException;
029import java.util.Iterator;
030import java.util.NavigableSet;
031import java.util.NoSuchElementException;
032import java.util.PriorityQueue;
033import java.util.SortedSet;
034
035import com.google.common.collect.Iterables;
036import com.google.common.collect.MinMaxPriorityQueue;
037import com.google.common.collect.Ordering;
038
039/**
040 * <b>Note: This class should only be used for testing. It provides no practical
041 * benefit when compared to {@link java.util.TreeSet java.util.TreeSet} and
042 * lacks navigation methods defined in the {@link NavigableSet} interface.</b>
043 * <p>
044 * A {@code Set} implementation based on a modified <a
045 * href="http://en.wikipedia.org/wiki/Red-black_tree">Red-Black Tree</a>.
046 * Elements are sorted from <i>least</i> to <i>greatest</i> according to their
047 * <i>natural ordering</i>, or by an explicit {@link Comparator} provided at
048 * creation. Attempting to remove or insert {@code null} elements is prohibited.
049 * Querying for {@code null} elements is allowed. Inserting non-comparable
050 * elements will result in a {@code ClassCastException}.
051 * <p>
052 * The iterators obtained from the {@link #iterator()} method are
053 * <i>fail-fast</i>. Attempts to modify the elements in this list at any time
054 * after an iterator is created, in any way except through the iterator's own
055 * remove method, will result in a {@code ConcurrentModificationException}.
056 * <p>
057 * This set is not <i>thread-safe</i>. If multiple threads modify this set
058 * concurrently it must be synchronized externally.
059 * <p>
060 * This implementation uses a comparator (whether or not one is explicitly
061 * provided) to perform all element comparisons. Two elements which are deemed
062 * equal by the comparator's {@code compare(E, E)} method are, from the
063 * standpoint of this set, equal.
064 * <p>
065 * The underlying Red-Black Tree provides the following worst case running time
066 * (where <i>n</i> is the size of this set and <i>m</i> is the size of the
067 * specified collection which is iterable in linear time):
068 * <p>
069 * <table border="1" cellpadding="3" cellspacing="1" style="width:400px;">
070 *   <tr>
071 *     <th style="text-align:center;">Method</th>
072 *     <th style="text-align:center;">Running Time</th>
073 *   </tr>
074 *   <tr>
075 *     <td>
076 *       {@link #addAll(Collection) addAll(Collection)}<br/>
077 *       {@link #containsAll(Collection) containsAll(Collection)}<br/>
078 *       {@link #retainAll(Collection) retainAll(Collection)}<br/>
079 *       {@link #removeAll(Collection) removeAll(Collection)}
080 *     </td>
081 *     <td style="text-align:center;"><i>O(m log n)</i></td>
082 *   </tr>
083 *   <tr>
084 *     <td>
085 *       {@link #add(Object) add(E)}<br/>
086 *       {@link #contains(Object)}<br/>
087 *       {@link #remove(Object)}
088 *     </td>
089 *     <td style="text-align:center;"><i>O(log n)</i></td>
090 *   </tr>
091 *   <tr>
092 *     <td>
093 *       {@link #clear() clear()}<br/>
094 *       {@link #isEmpty() isEmpty()}<br/>
095 *       {@link #size()}<br/>
096 *       {@link Iterator#remove()}
097 *     </td>
098 *     <td style="text-align:center;"><i>O(1)</i></td>
099 *   </tr>
100 * </table>
101 *
102 * @author Zhenya Leonov
103 * @param <E>
104 *            the type of elements maintained by this list
105 * @see SkiplistSet
106 */
107final public class TreeSet<E> extends AbstractSet<E> implements SortedCollection<E>, Cloneable, Serializable {
108
109        private static final long serialVersionUID = 1L;
110        private transient int size = 0, modCount = 0;
111        private transient Node nil = new Node();
112        private transient Node min = nil, root = nil;
113        private final Comparator<? super E> comparator;
114
115        private TreeSet(final Comparator<? super E> comparator) {
116                this.comparator = comparator;
117        }
118
119        /**
120         * Creates a new {@code TreeSet} that orders its elements according to their
121         * <i>natural ordering</i>.
122         *
123         * @return a new {@code TreeSet} that orders its elements according to their
124         *         <i>natural ordering</i>
125         */
126        public static <E extends Comparable<? super E>> TreeSet<E> create() {
127                return new TreeSet<E>(Ordering.natural());
128        }
129
130        /**
131         * Creates a new {@code TreeSet} that uses the specified comparator to order
132         * its elements.
133         *
134         * @param comparator
135         *            the specified comparator
136         * @return a new {@code TreeSet} that uses the specified comparator to order
137         *         its elements
138         *
139         */
140        public static <E> TreeSet<E> create(final Comparator<? super E> comparator) {
141                checkNotNull(comparator);
142                return new TreeSet<E>(comparator);
143        }
144
145        /**
146         * Creates a new {@code TreeSet} containing the specified initial elements.
147         * If {@code elements} is an instance of {@link SortedSet},
148         * {@link PriorityQueue}, {@link MinMaxPriorityQueue}, or
149         * {@code SortedCollection}, this set will be ordered according to the same
150         * ordering. Otherwise, this set will be ordered according to the <i>natural
151         * ordering</i> of its elements.
152         *
153         * @param elements
154         *            the initial elements to be placed into the set
155         * @return a new {@code TreeSet} containing the specified initial elements
156         * @throws ClassCastException
157         *             if any of the initial elements cannot be compared to one
158         *             another according to this set's ordering
159         * @throws NullPointerException
160         *             if any of the initial elements or {@code elements} itself is
161         *             {@code null}
162         */
163        @SuppressWarnings({ "unchecked" })
164        public static <E extends Comparable<? super E>> TreeSet<E> create(final Iterable<? extends E> elements) {
165                checkNotNull(elements);
166                final Comparator<? super E> comparator;
167                if (elements instanceof SortedSet<?>)
168                        comparator = ((SortedSet<? super E>) elements).comparator();
169                else if (elements instanceof PriorityQueue<?>)
170                        comparator = ((PriorityQueue<? super E>) elements).comparator();
171                else if (elements instanceof SortedCollection<?>)
172                        comparator = ((SortedCollection<? super E>) elements).comparator();
173                else if (elements instanceof MinMaxPriorityQueue<?>)
174                        comparator = ((MinMaxPriorityQueue<? super E>) elements).comparator();
175                else
176                        comparator = (Comparator<? super E>) Ordering.natural();
177                final TreeSet<E> treeSet = TreeSet.create(comparator);
178                Iterables.addAll(treeSet, elements);
179                return treeSet;
180        }
181
182        /**
183         * Returns the comparator used to order the elements in this set. If one was
184         * not explicitly provided a <i>natural order</i> comparator is returned.
185         *
186         * @return the comparator used to order this set
187         */
188        @Override
189        public Comparator<? super E> comparator() {
190                return comparator;
191        }
192
193        /**
194         * Inserts the specified element into this set in sorted order.
195         */
196        @Override
197        public boolean add(E e) {
198                return insert(new Node(checkNotNull(e)));
199        }
200
201        @SuppressWarnings("unchecked")
202        @Override
203        public boolean contains(Object o) {
204                return o != null && search((E) o) != null;
205        }
206
207        @Override
208        public Iterator<E> iterator() {
209                return new Iterator<E>() {
210                        private Node next = min;
211                        private Node last = nil;
212                        private int expectedModCount = modCount;
213
214                        @Override
215                        public boolean hasNext() {
216                                return next != nil;
217                        }
218
219                        @Override
220                        public void remove() {
221                                checkForConcurrentModification();
222                                checkState(last != nil);
223                                if (last.left != nil && last.right != nil)
224                                        next = last;
225                                delete(last);
226                                expectedModCount = modCount;
227                                last = nil;
228                        }
229
230                        @Override
231                        public E next() {
232                                checkForConcurrentModification();
233                                if (next == nil)
234                                        throw new NoSuchElementException();
235                                last = next;
236                                next = successor(next);
237                                return last.element;
238                        }
239
240                        private void checkForConcurrentModification() {
241                                if (modCount != expectedModCount)
242                                        throw new ConcurrentModificationException();
243                        }
244                };
245        }
246
247        @SuppressWarnings("unchecked")
248        @Override
249        public boolean remove(Object o) {
250                final Node node = search((E) checkNotNull(o));
251                if (node == null)
252                        return false;
253                delete(node);
254                return true;
255        }
256
257        @Override
258        public int size() {
259                return size;
260        }
261
262        @Override
263        public void clear() {
264                modCount++;
265                root = min = nil;
266                size = 0;
267        }
268
269        /**
270         * Returns a shallow copy of this {@code TreeSet}. The elements themselves
271         * are not cloned.
272         *
273         * @return a shallow copy of this queue
274         */
275        @SuppressWarnings("unchecked")
276        @Override
277        public TreeSet<E> clone() {
278                TreeSet<E> clone;
279                try {
280                        clone = (TreeSet<E>) super.clone();
281                } catch (CloneNotSupportedException e) {
282                        throw new InternalError();
283                }
284                clone.modCount = clone.size = 0;
285                clone.root = clone.min = clone.min = clone.nil = new Node();
286                clone.addAll(this);
287                return clone;
288        }
289
290        private void writeObject(java.io.ObjectOutputStream oos) throws java.io.IOException {
291                oos.defaultWriteObject();
292                oos.writeInt(size);
293                for (E e : this)
294                        oos.writeObject(e);
295        }
296
297        @SuppressWarnings("unchecked")
298        private void readObject(java.io.ObjectInputStream ois) throws java.io.IOException, ClassNotFoundException {
299                ois.defaultReadObject();
300                root = min = nil = new Node();
301                int size = ois.readInt();
302                for (int i = 0; i < size; i++)
303                        add((E) ois.readObject());
304        }
305
306        // Red-Black-Tree
307
308        static enum Color {
309                BLACK, RED;
310        }
311
312        private class Node {
313                private E element = null;
314                private Node parent, left, right;
315                private Color color = BLACK;
316
317                private Node() {
318                        parent = right = left = this;
319                }
320
321                private Node(final E element) {
322                        this.element = element;
323                        parent = right = left = nil;
324                }
325        }
326
327        private Node search(final E e) {
328                Node n = root;
329                while (n != nil) {
330                        int cmp = comparator.compare(e, n.element);
331                        if (cmp == 0)
332                                return n;
333                        if (cmp < 0)
334                                n = n.left;
335                        else
336                                n = n.right;
337                }
338                return null;
339        }
340
341        /**
342         * Introduction to Algorithms (CLR) Second Edition
343         *
344         * <pre>
345         * RB-INSERT(T, z)
346         * y = nil[T]
347         * x = root[T]
348         * while x != nil[T]
349         *    do y = x
350         *       if key[z] < key[x]
351         *          then x = left[x]
352         *          else x = right[x]
353         * p[z] = y
354         * if y = nil[T]
355         *    then root[T] = z
356         *    else if key[z] < key[y]
357         *            then left[y] = z
358         *            else right[y] = z
359         * left[z] = nil[T]
360         * right[z] = nil[T]
361         * color[z] = RED
362         * RB-INSERT-FIXUP(T, z)
363         */
364        private boolean insert(Node z) {
365                size++;
366                modCount++;
367                Node x = root;
368                Node y = nil;
369                while (x != nil) {
370                        y = x;
371                        int cmp = comparator.compare(z.element, x.element);
372                        if (cmp == 0)
373                                return false;
374                        else if (cmp < 0)
375                                x = x.left;
376                        else
377                                x = x.right;
378                }
379                z.parent = y;
380                if (y == nil)
381                        root = z;
382                else if (comparator.compare(z.element, y.element) < 0)
383                        y.left = z;
384                else
385                        y.right = z;
386                fixAfterInsertion(z);
387                if (min == nil || comparator.compare(z.element, min.element) < 0)
388                        min = z;
389                return true;
390        }
391
392        /**
393         * Introduction to Algorithms (CLR) Second Edition
394         *
395         * <pre>
396         * RB-DELETE-FIXUP(T, z)
397         * if left[z] = nil[T] or right[z] = nil[T]
398         *    then y = z
399         *    else y = TREE-SUCCESSOR(z)
400         * if left[y] != nil[T]
401         *    then x = left[y]
402         *    else x = right[y]
403         * p[x] = p[y]
404         * if p[y] = nil[T]
405         *    then root[T] = x
406         *    else if y = left[p[y]]
407         *            then left[p[y]] = x
408         *            else right[p[y]] = x
409         * if y != z
410         *    then key[z] = key[y]
411         *         copy y's satellite data into z
412         * if color[y] = BLACK
413         *    then RB-DELETE-FIXUP(T, x)
414         * return y
415         */
416        private void delete(Node z) {
417                size--;
418                modCount++;
419                Node x, y;
420                if (min == z)
421                        min = successor(z);
422                if (z.left == nil || z.right == nil)
423                        y = z;
424                else
425                        y = successor(z);
426                if (y.left != nil)
427                        x = y.left;
428                else
429                        x = y.right;
430                x.parent = y.parent;
431                if (y.parent == nil)
432                        root = x;
433                else if (y == y.parent.left)
434                        y.parent.left = x;
435                else
436                        y.parent.right = x;
437                if (y != z)
438                        z.element = y.element;
439                if (y.color == Color.BLACK)
440                        fixAfterDeletion(x);
441        }
442
443        /**
444         * Introduction to Algorithms (CLR) Second Edition
445         *
446         * <pre>
447         * TREE-SUCCESSOR(x)
448         * if right[x] != NIL
449         *    then return TREE-MINIMUM(right[x])
450         * y = p[x]
451         * while y != NIL and x = right[y]
452         *    do x = y
453         *       y = p[y]
454         * return y
455         */
456        private Node successor(Node x) {
457                if (x == nil)
458                        return nil;
459                if (x.right != nil) {
460                        Node y = x.right;
461                        while (y.left != nil)
462                                y = y.left;
463                        return y;
464                }
465                Node y = x.parent;
466                while (y != nil && x == y.right) {
467                        x = y;
468                        y = y.parent;
469                }
470                return y;
471        }
472
473        /**
474         * Introduction to Algorithms (CLR) Second Edition
475         *
476         * <pre>
477         * LEFT-ROTATE(T, x)
478         * y = right[x]                                                 Set y.
479         * right[x] = left[y]                                   Turn y's left subtree into x's right subtree.
480         * if left[y] != nil[T]
481         *    then p[left[y]] = x
482         * p[y] = p[x]                                                  Link x's parent to y.
483         * if p[x] = nil[T]
484         *    then root[T] = y
485         *    else if x = left[p[x]]
486         *            then left[p[x]] = y
487         *            else right[p[x]] = y
488         * left[y] = x                                                  Put x on y's left.
489         * p[x] = y
490         */
491        private void leftRotate(final Node x) {
492                if (x != nil) {
493                        Node n = x.right;
494                        x.right = n.left;
495                        if (n.left != nil)
496                                n.left.parent = x;
497                        n.parent = x.parent;
498                        if (x.parent == nil)
499                                root = n;
500                        else if (x.parent.left == x)
501                                x.parent.left = n;
502                        else
503                                x.parent.right = n;
504                        n.left = x;
505                        x.parent = n;
506                }
507        }
508
509        private void rightRotate(final Node x) {
510                if (x != nil) {
511                        Node n = x.left;
512                        x.left = n.right;
513                        if (n.right != nil)
514                                n.right.parent = x;
515                        n.parent = x.parent;
516                        if (x.parent == nil)
517                                root = n;
518                        else if (x.parent.right == x)
519                                x.parent.right = n;
520                        else
521                                x.parent.left = n;
522                        n.right = x;
523                        x.parent = n;
524                }
525        }
526
527        /**
528         * Introduction to Algorithms (CLR) Second Edition
529         *
530         * <pre>
531         * RB-INSERT-FIXUP(T, z)
532         * while color[p[z]] = RED
533         *    do if p[z] = left[p[p[z]]]
534         *          then y = right[p[p[z]]]
535         *               if color[y] = RED
536         *                  then color[p[z]] = BLACK                                    Case 1
537         *                       color[y] = BLACK                                               Case 1
538         *                       color[p[p[z]]] = RED                                   Case 1
539         *                       z = p[p[z]]                                                    Case 1
540         *                  else if z = right[p[z]]
541         *                          then z = p[z]                                               Case 2
542         *                               LEFT-ROTATE(T, z)                              Case 2
543         *                       color[p[z]] = BLACK                                    Case 3
544         *                       color[p[p[z]]] = RED                                   Case 3
545         *                       RIGHT-ROTATE(T, p[p[z]])                               Case 3
546         *          else (same as then clause
547         *                        with right and left exchanged)
548         * color[root[T]] = BLACK
549         */
550        private void fixAfterInsertion(Node z) {
551                z.color = RED;
552                while (z.parent.color == RED) {
553                        if (z.parent == z.parent.parent.left) {
554                                Node y = z.parent.parent.right;
555                                if (y.color == RED) {
556                                        z.parent.color = BLACK;
557                                        y.color = BLACK;
558                                        z.parent.parent.color = RED;
559                                        z = z.parent.parent;
560                                } else {
561                                        if (z == z.parent.right) {
562                                                z = z.parent;
563                                                leftRotate(z);
564                                        }
565                                        z.parent.color = BLACK;
566                                        z.parent.parent.color = RED;
567                                        rightRotate(z.parent.parent);
568                                }
569                        } else {
570                                Node y = z.parent.parent.left;
571                                if (y.color == RED) {
572                                        z.parent.color = BLACK;
573                                        y.color = BLACK;
574                                        z.parent.parent.color = RED;
575                                        z = z.parent.parent;
576                                } else {
577                                        if (z == z.parent.left) {
578                                                z = z.parent;
579                                                rightRotate(z);
580                                        }
581                                        z.parent.color = BLACK;
582                                        z.parent.parent.color = RED;
583                                        leftRotate(z.parent.parent);
584                                }
585                        }
586                }
587                root.color = BLACK;
588        }
589
590        /**
591         * Introduction to Algorithms (CLR) Second Edition
592         *
593         * <pre>
594         * RB-DELETE-FIXUP(T, x)
595         * while x != root[T] and color[x] = BLACK
596         *    do if x = left[p[x]]
597         *          then w = right[p[x]]
598         *               if color[w] = RED
599         *                  then color[w] = BLACK                                                               Case 1
600         *                       color[p[x]] = RED                                                              Case 1
601         *                       LEFT-ROTATE(T, p[x])                                                   Case 1
602         *                       w = right[p[x]]                                                                Case 1
603         *               if color[left[w]] = BLACK and color[right[w]] = BLACK
604         *                  then color[w] = RED                                                                 Case 2
605         *                       x = p[x]                                                                               Case 2
606         *                  else if color[right[w]] = BLACK
607         *                          then color[left[w]] = BLACK                                 Case 3
608         *                               color[w] = RED                                                 Case 3
609         *                               RIGHT-ROTATE(T,w)                                              Case 3
610         *                               w = right[p[x]]                                                Case 3
611         *                       color[w] = color[p[x]]                                                 Case 4
612         *                       color[p[x]] = BLACK                                                    Case 4
613         *                       color[right[w]] = BLACK                                                Case 4
614         *                       LEFT-ROTATE(T, p[x])                                                   Case 4
615         *                       x = root[T]                                                                    Case 4
616         *          else (same as then clause with right and left exchanged)
617         * color[x] = BLACK
618         */
619        private void fixAfterDeletion(Node x) {
620                while (x != root && x.color == BLACK) {
621                        if (x == x.parent.left) {
622                                Node w = x.parent.right;
623                                if (w.color == RED) {
624                                        w.color = BLACK;
625                                        x.parent.color = RED;
626                                        leftRotate(x.parent);
627                                        w = x.parent.right;
628                                }
629                                if (w.left.color == BLACK && w.right.color == BLACK) {
630                                        w.color = RED;
631                                        x = x.parent;
632                                } else {
633                                        if (w.right.color == BLACK) {
634                                                w.left.color = BLACK;
635                                                w.color = RED;
636                                                rightRotate(w);
637                                                w = x.parent.right;
638                                        }
639                                        w.color = x.parent.color;
640                                        x.parent.color = BLACK;
641                                        w.right.color = BLACK;
642                                        leftRotate(x.parent);
643                                        x = root;
644                                }
645                        } else {
646                                Node w = x.parent.left;
647                                if (w.color == RED) {
648                                        w.color = BLACK;
649                                        x.parent.color = RED;
650                                        rightRotate(w.parent);
651                                        w = x.parent.left;
652                                }
653                                if (w.right.color == BLACK && w.left.color == BLACK) {
654                                        w.color = RED;
655                                        x = x.parent;
656                                } else {
657                                        if (w.left.color == BLACK) {
658                                                w.right.color = BLACK;
659                                                w.color = RED;
660                                                leftRotate(w);
661                                                w = x.parent.left;
662                                        }
663                                        w.color = x.parent.color;
664                                        w.parent.color = BLACK;
665                                        w.left.color = BLACK;
666                                        rightRotate(x.parent);
667                                        x = root;
668                                }
669                        }
670                }
671                x.color = BLACK;
672        }
673
674}


text:
package command

import (
	"flag"
	"fmt"
	"os"
	"strings"

	"github.com/hashicorp/terraform/terraform"
)

// GraphCommand is a Command implementation that takes a Terraform
// configuration and outputs the dependency tree in graphical form.
type GraphCommand struct {
	Meta
}

func (c *GraphCommand) Run(args []string) int {
	var moduleDepth int
	var verbose bool
	var drawCycles bool

	args = c.Meta.process(args, false)

	cmdFlags := flag.NewFlagSet("graph", flag.ContinueOnError)
	c.addModuleDepthFlag(cmdFlags, &moduleDepth)
	cmdFlags.BoolVar(&verbose, "verbose", false, "verbose")
	cmdFlags.BoolVar(&drawCycles, "draw-cycles", false, "draw-cycles")
	cmdFlags.Usage = func() { c.Ui.Error(c.Help()) }
	if err := cmdFlags.Parse(args); err != nil {
		return 1
	}

	var path string
	args = cmdFlags.Args()
	if len(args) > 1 {
		c.Ui.Error("The graph command expects one argument.\n")
		cmdFlags.Usage()
		return 1
	} else if len(args) == 1 {
		path = args[0]
	} else {
		var err error
		path, err = os.Getwd()
		if err != nil {
			c.Ui.Error(fmt.Sprintf("Error getting pwd: %s", err))
		}
	}

	ctx, _, err := c.Context(contextOpts{
		Path:      path,
		StatePath: "",
	})
	if err != nil {
		c.Ui.Error(fmt.Sprintf("Error loading Terraform: %s", err))
		return 1
	}

	// Skip validation during graph generation - we want to see the graph even if
	// it is invalid for some reason.
	g, err := ctx.Graph(&terraform.ContextGraphOpts{
		Verbose:  verbose,
		Validate: false,
	})
	if err != nil {
		c.Ui.Error(fmt.Sprintf("Error creating graph: %s", err))
		return 1
	}

	graphStr, err := terraform.GraphDot(g, &terraform.GraphDotOpts{
		DrawCycles: drawCycles,
		MaxDepth:   moduleDepth,
		Verbose:    verbose,
	})
	if err != nil {
		c.Ui.Error(fmt.Sprintf("Error converting graph: %s", err))
		return 1
	}

	c.Ui.Output(graphStr)

	return 0
}

func (c *GraphCommand) Help() string {
	helpText := `
Usage: terraform graph [options] [DIR]

  Outputs the visual dependency graph of Terraform resources according to
  configuration files in DIR (or the current directory if omitted).

  The graph is outputted in DOT format. The typical program that can
  read this format is GraphViz, but many web services are also available
  to read this format.

Options:

  -draw-cycles         Highlight any cycles in the graph with colored edges.
                       This helps when diagnosing cycle errors.

  -module-depth=n      The maximum depth to expand modules. By default this is
                       -1, which will expand resources within all modules.

  -verbose             Generate a verbose, "worst-case" graph, with all nodes
                       for potential operations in place.

  -no-color           If specified, output won't contain any color.

`
	return strings.TrimSpace(helpText)
}

func (c *GraphCommand) Synopsis() string {
	return "Create a visual graph of Terraform resources"
}


text:
"""
Visualize bitmaps in gdb.

(gdb) source <path to this file>
(gdb) sk_bitmap <symbol>

This should pop up a window with the bitmap displayed.
Right clicking should bring up a menu, allowing the
bitmap to be saved to a file.
"""

import gdb
from enum import Enum
try:
  from PIL import Image
except ImportError:
  import Image

class ColorType(Enum):
    unknown = 0
    alpha_8 = 1
    rgb_565 = 2
    argb_4444 = 3
    rgba_8888 = 4
    rgbx_8888 = 5
    bgra_8888 = 6
    rgba_1010102 = 7
    rgb_101010x = 8
    gray_8 = 9
    rgba_F16 = 10

class AlphaType(Enum):
    unknown = 0
    opaque = 1
    premul = 2
    unpremul = 3

class sk_bitmap(gdb.Command):
  """Displays the content of an SkBitmap image."""

  def __init__(self):
      super(sk_bitmap, self).__init__('sk_bitmap',
                                      gdb.COMMAND_SUPPORT,
                                      gdb.COMPLETE_FILENAME)

  def invoke(self, arg, from_tty):
    frame = gdb.selected_frame()
    val = frame.read_var(arg)
    if str(val.type.strip_typedefs()) == 'SkBitmap':
      pixmap = val['fPixmap']
      pixels = pixmap['fPixels']
      row_bytes = pixmap['fRowBytes']
      info = pixmap['fInfo']
      dimensions = info['fDimensions']
      width = dimensions['fWidth']
      height = dimensions['fHeight']
      color_type = info['fColorType']
      alpha_type = info['fAlphaType']

      process = gdb.selected_inferior()
      memory_data = process.read_memory(pixels, row_bytes * height)
      size = (width, height)
      image = None
      # See Unpack.c for the values understood after the "raw" parameter.
      if color_type == ColorType.bgra_8888.value:
        if alpha_type == AlphaType.unpremul.value:
          image = Image.frombytes("RGBA", size, memory_data,
                                  "raw", "BGRA", row_bytes, 1)
        elif alpha_type == AlphaType.premul.value:
          # RGBA instead of RGBa, because Image.show() doesn't work with RGBa.
          image = Image.frombytes("RGBA", size, memory_data,
                                  "raw", "BGRa", row_bytes, 1)

      if image:
        # Fails on premultiplied alpha, it cannot convert to RGB.
        image.show()
      else:
        print ("Need to add support for %s %s." % (
               str(ColorType(int(color_type))),
               str(AlphaType(int(alpha_type)))
        ))

sk_bitmap()


text:
<?php

class Controller extends Module {

    /**
     * This isn't used yet (obviously), but is here for future functionality.
     * All controllers should still extend this main class.
     */

}


text:
        {% include form-cadastro-lead.html formNameSuffix="sidebar" %}

        {% include form-cadastro-lead.html formNameSuffix="sidebar" %}


text:
class AddPodcastDataFields < ActiveRecord::Migration
  def change
    add_column :blog_app_posts, :duration, :string
    add_column :blog_app_posts, :file_size, :integer
  end
end


text:
[![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Build status][appveyor-image]][appveyor-url] [![Dependency status][david-dm-image]][david-dm-url] [![Dev Dependency status][david-dm-dev-image]][david-dm-dev-url]

[npm-url]:https://npmjs.org/package/cross-spawn-async
[downloads-image]:http://img.shields.io/npm/dm/cross-spawn-async.svg
[npm-image]:http://img.shields.io/npm/v/cross-spawn-async.svg
[travis-url]:https://travis-ci.org/IndigoUnited/node-cross-spawn-async
[travis-image]:http://img.shields.io/travis/IndigoUnited/node-cross-spawn-async/master.svg
[appveyor-url]:https://ci.appveyor.com/project/satazor/node-cross-spawn-async
[appveyor-image]:https://img.shields.io/appveyor/ci/satazor/node-cross-spawn-async.svg
[david-dm-url]:https://david-dm.org/IndigoUnited/node-cross-spawn-async
[david-dm-image]:https://img.shields.io/david/IndigoUnited/node-cross-spawn-async.svg
[david-dm-dev-url]:https://david-dm.org/IndigoUnited/node-cross-spawn-async#info=devDependencies
[david-dm-dev-image]:https://img.shields.io/david/dev/IndigoUnited/node-cross-spawn-async.svg

A cross platform solution to node's spawn.

## Installation

`$ npm install cross-spawn-async`

## Why

Node has issues when using spawn on Windows:

- It ignores [PATHEXT](https://github.com/joyent/node/issues/2318)
- It does not support [shebangs](http://pt.wikipedia.org/wiki/Shebang)
- It does not allow you to run `del` or `dir`
- It does not properly escape arguments with spaces or special characters

All these issues are handled correctly by `cross-spawn-async`.
There are some known modules, such as [win-spawn](https://github.com/ForbesLindesay/win-spawn), that try to solve this but they are either broken or provide faulty escaping of shell arguments.

## Usage

Exactly the same way as node's [`spawn`](https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options), so it's a drop in replacement.

```javascript
var spawn = require('cross-spawn-async');

var process = spawn('npm', ['list', '-g', '-depth', '0'], { stdio: 'inherit' });
```

## Tests

`$ npm test`

## License

Released under the [MIT License](http://www.opensource.org/licenses/mit-license.php).


text:
#include "common_tools.h"
#include "opengles.h"

typedef void (APIENTRY *glPatchParameteriOESPROC) (jint, jint);

EXTERN_C_ENTER

JNIEXPORT void JNICALL Java_org_lwjgl_opengles_OESTessellationShader_glPatchParameteriOES(JNIEnv *__env, jclass clazz, jint pname, jint value) {
    glPatchParameteriOESPROC glPatchParameteriOES = (glPatchParameteriOESPROC)tlsGetFunction(810);
    UNUSED_PARAM(clazz)
    glPatchParameteriOES(pname, value);
}

EXTERN_C_EXIT


text:
'use strict';

angular.module('myApp.forecast.forecast-directive', [])

.directive('forecast', ['forecastService', function(forecastService) {
    return {
        templateUrl: 'components/forecast/forecast.html',
        restrict: 'E',
        scope: {
            city: '@'
        },
        link: function(scope) {
            scope.iconUrl = 'http://openweathermap.org/img/w/';

            forecastService.getFeed(scope.city)
                .then(function(data) {
                    scope.city = data.city;
                    scope.feed = data.list;
                });
        }
    };
}]);


text:
package one.nio.async;

public interface ParallelTask {
    void execute(int taskNum, int taskCount) throws Exception;
}


text:
cask "virtualhere" do
  version "5.1.9"
  sha256 :no_check

  url "https://www.virtualhere.com/sites/default/files/usbclient/VirtualHere.dmg"
  name "VirtualHere"
  desc "Use USB devices remotely over a network"
  homepage "https://www.virtualhere.com/usb_client_software"

  livecheck do
    url :homepage
    strategy :page_match
    regex(/Version\s*(\d+(?:\.\d+)*)/i)
  end

  app "VirtualHere.app"
end


text:
require File.dirname(__FILE__) + '/spec_helper'

describe "Etl" do
  it "should use rubygems" do
    defined?(Gem).should eql('constant')
  end

  it "should use ActiveSupport" do
    defined?(ActiveSupport).should eql('constant')
  end

  it "should use OpenStruct" do
    defined?(OpenStruct).should eql('constant')
  end

end


text:
import { render } from '@testing-library/react';
import React from 'react';

import { ViewControlBar } from './view-control-bar';

describe('view control bar snapshot', () => {
  it('matches snapshot', () => {
    const viewControlBar = (
      <ViewControlBar label="A label">

Hello world

      </ViewControlBar>
    );

    const { container } = render(viewControlBar);
    expect(container.firstChild).toMatchSnapshot();
  });
});


text:
import os
from flask_restful import Resource, reqparse
import ckanapi

HOST = os.getenv('CKAN_HOST')
TOKEN = os.getenv('CKAN_API_TOKEN')

remote = ckanapi.RemoteCKAN(HOST, user_agent='ckanops/1.0', apikey=TOKEN)

class CreateOrganization(Resource):
    def post(self):
        parser = reqparse.RequestParser(bundle_errors=True)
        parser.add_argument('org_name', type=str, required=True)
        query = parser.parse_args()
        existing_orgs = remote.action.organization_list()
        #if query['org_name'] not in existing_orgs:
        try:
            remote.action.organization_create(name=query['org_name'])
            return {'Organization created': query['org_name']}
        except ckanapi.ValidationError as e:
            if str(e) == "{u'__type': u'Validation Error', u'name': [u'Group name already exists in database']}":
                return {'Validation Error': 'Organization already exists'}
            else:
                return {'Error': 'Something went wrong'}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.collectivehealth.lob</groupId>
	<artifactId>lob-java-rest</artifactId>
	<version>0.1.0</version>
	<packaging>jar</packaging>

	<name>lob-java-rest</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>com.google.code.gson</groupId>
			<artifactId>gson</artifactId>
			<version>2.3.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.3.6</version>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpmime</artifactId>
			<version>4.3.6</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.8.1</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.mockito</groupId>
			<artifactId>mockito-all</artifactId>
			<version>1.10.17</version>
			<scope>test</scope>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.2</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<version>2.11</version>
				<dependencies>
					<dependency>
						<groupId>org.apache.maven.surefire</groupId>
						<artifactId>surefire-junit47</artifactId>
						<version>2.12</version>
					</dependency>
				</dependencies>
				<configuration>
					<includes>
						<include>**/*.class</include>
					</includes>
					<excludedGroups>com.test.annotation.type.IntegrationTest</excludedGroups>
					<environmentVariables>
						<DEVELOPMENT_ENV>test</DEVELOPMENT_ENV>
						<THIS_ENV>dev</THIS_ENV>
					</environmentVariables>
					<systemProperties>
						<app.logdir>log/</app.logdir>
					</systemProperties>
				</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-failsafe-plugin</artifactId>
				<version>2.12</version>
				<dependencies>
					<dependency>
						<groupId>org.apache.maven.surefire</groupId>
						<artifactId>surefire-junit47</artifactId>
						<version>2.12</version>
					</dependency>
				</dependencies>
				<configuration>
					<groups>com.test.annotation.type.IntegrationTest</groups>
					<environmentVariables>
						<DEVELOPMENT_ENV>test</DEVELOPMENT_ENV>
						<THIS_ENV>dev</THIS_ENV>
					</environmentVariables>
					<systemProperties>
						<app.logdir>log/</app.logdir>
					</systemProperties>
				</configuration>
				<executions>
					<execution>
						<goals>
							<goal>integration-test</goal>
						</goals>
						<configuration>
							<includes>
								<include>**/*.class</include>
							</includes>
						</configuration>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>
	<!-- Collective Health internal maven repository -->
	<distributionManagement>
		<repository>
			<id>central</id>
			<name>Temporary Staging Repository</name>
			<url>https://artifactory.cchh.io/artifactory/internal/</url>
		</repository>
	</distributionManagement>

</project>


text:
module MinitestHandler
  # Helper methods to help extract code out of recipes
  module CookbookHelper
    # Load necessary tests onto the filesystem
    def load_tests
      require 'fileutils'

      seen_cookbooks = []
      seen_recipes.each do |recipe|
        # recipes is actually a list of cookbooks and recipes with :: as a
        # delimiter
        if recipe.include?('::')
          cookbook_name, recipe_name = recipe.split('::')
        else
          cookbook_name = recipe
          recipe_name = 'default'
        end
        seen_cookbooks << cookbook_name unless seen_cookbooks.include?(cookbook_name)

        unless matches_filter?(recipe_name, cookbook_name)
          ::Chef::Log.debug('Not copying test files for recipe' \
            " #{recipe_name} in cookbook #{cookbook_name} as it" \
            " does not match filter #{node[:minitest][:filter]}")
          next
        end

        # create the parent directory
        dir = Chef::Resource::Directory.new(
          "#{node[:minitest][:path]}/#{cookbook_name}", run_context)
        dir.recursive(true)
        dir.run_action(:create)

        support_files(cookbook_name).each do |support_file|
          copy_file(cookbook_name, support_file)
        end
        test_files(cookbook_name, recipe_name).each do |test_file|
          copy_file(cookbook_name, test_file)
        end
      end

      # Try to help the user out and let them know if they have
      # what appears to be a test file in a directory we don't support
      seen_cookbooks.each do |cookbook_name|
        warn_tests_in_wrong_dir(cookbook_name)
      end
    end

    def register_handler
      options = {
        path: "#{node[:minitest][:path]}/#{node[:minitest][:tests]}",
        verbose: node[:minitest][:verbose] }
      # The following options can be omited

      options[:filter] = node[:minitest][:filter] if node[:minitest].include? 'filter'
      options[:seed] = node[:minitest][:seed] if node[:minitest].include? 'seed'
      options[:ci_reports] = node[:minitest][:ci_reports] if node[:minitest].include? 'ci_reports'

      handler = MiniTest::Chef::Handler.new(options)

      Chef::Log.info('Enabling minitest-chef-handler as a report handler')
      Chef::Config.send('report_handlers').delete_if do |v|
        v.class.to_s.include? MiniTest::Chef::Handler.to_s
      end
      Chef::Config.send('report_handlers') << handler
    end

    private

    # Compare a cookbook and recipe combination against
    # node[:minitest][:filter]
    #
    # @returns [Boolean]
    def matches_filter?(recipe_name, cookbook_name)
      full_name = "recipe::#{cookbook_name}::#{recipe_name}"
      # If no filter is set, it will match all
      filter = node[:minitest][:filter] || '/./'
      if filter.class == String
        # We don't know what form the user might give
        # us the pattern in. They may including leading and
        # trailing slashes, or they might just give us a
        # string. Try to handle both variations
        if filter =~ %r{/(.*)/}
          filter = Regexp.new(Regexp.last_match[1])
        else
          filter = Regexp.new(filter)
        end
      end
      return true if full_name =~ filter
      false
    end

    # Collect a list of recipes that we care about
    #
    # @return [Array] of recipes that should be tested
    def seen_recipes
      recipe_list = []
      if node[:minitest][:recipes].empty?
        if Chef::VERSION < '11.0'
          seen_recipes = node.run_state[:seen_recipes]
          recipe_list = seen_recipes.keys.each { |i| i }
        else
          recipe_list = run_context.loaded_recipes
        end
        if recipe_list.empty? && Chef::Config[:solo]
          # If you have roles listed in your run list they are NOT expanded
          recipe_list = node.run_list.map { |item| item.name if item.type == :recipe }
        end
      else
        recipe_list = node[:minitest][:recipes].dup
      end
      recipe_list
    end

    # Given a test or support file in the form of a relative path
    # copy the files into the test directory
    #
    # @returns [Nil]
    def copy_file(cookbook_name, file_path)
      base_path = ::File.join(node[:minitest][:path], cookbook_name)
      full_path = ::File.join(base_path, file_path)

      # Historically there has not been a one-to-one parity between
      # the path in the cookbook and the path on the file system.
      # In order to preserve the legacy placemnts the following
      # gsubs will construct the path in which to place the files
      # in the minitest folder
      full_path.gsub!('/test/', '/')
      full_path.gsub!('/tests/minitest/', '/')
      dir_path = ::File.dirname(full_path)

      # Make sure the enclosing directory actually exists
      dir = ::Chef::Resource::Directory.new(dir_path, run_context)
      dir.recursive(true)
      dir.run_action(:create)

      test_file = ::Chef::Resource::CookbookFile.new(full_path, run_context)
      test_file.cookbook(cookbook_name)
      test_file.source(file_path)
      test_file.run_action(:create)

      nil
    end

    # Check for tests in wrong directorys
    def warn_tests_in_wrong_dir(cookbook_name)
      # As of version 1.2.0 a fix was implemented that would no longer copy files
      # that were in the wrong directory. Its possible this change might affect
      # users so let them know
      wrong_dir_files = []
      cookbook_file_names(cookbook_name).each do |cb_file|
        wrong_dir_files << cb_file if cb_file =~ /^[\w\d]+_test\.rb$/
      end
      wrong_dir_files.each do |wdf|
        # Cleanup for readibility only. When displaying the message
        # to the user ignore the actual disk location and just
        # show them what cookbook it is.
        Array(Chef::Config[:cookbook_path]).each do |cookbook_path|
          wdf.gsub!("#{cookbook_path}/#{cookbook_name}/", '')
        end
        ::Chef::Log.warn("A test file was detected at #{wdf} in the files directory" \
          " of the #{cookbook_name} cookbook. As of version 1.2.0 of the" \
          ' minitest-handler-cookbook storing test files in this location' \
          ' is not supported. If you would like these tests executed' \
          ' you should move them into files/default/test/')
      end
    end

    # Set of supporting files for a cookbook. This is generally
    # helper modules, however this might also include supporting
    # files of any type. IE if a user has a txt file or csv file
    # we don't want to leave it behind
    #
    # @return [Array]
    def support_files(cookbook_name)
      all_test_files(cookbook_name).reject do |test_file|
        test_file.nil? || test_file.end_with?('_test.rb')
      end
    end

    # Set of test files for a given recipe
    #
    # @return [Array] list of test files
    def test_files(cookbook_name, recipe_name)
      files = []
      all_test_files(cookbook_name).each do |test_file|
        next if test_file.nil?
        # See Github Issue #67 for more background on this
        test_file_name = ::File.split(test_file).last
        files << test_file if test_file_name == "#{recipe_name}_test.rb"
      end
      remove_nil_from_array(files)
    end

    # A list of all test files in a given cookbook
    #
    # @return [Array]
    def all_test_files(cookbook_name)
      files = []
      cookbook_file_names(cookbook_name).each do |file_name|
        # match test/ or tests/. Those are the two
        # supported locations
        files << file_name if file_name =~ /^tests?\//
      end
      remove_nil_from_array(files)
    end

    # Extract the list of *files* (in the files directory)
    # from a cookbook
    #
    # @return [Array] of file paths relative to the cookbook root
    def cookbook_file_paths(cookbook_name)
      ckbk = run_context.cookbook_collection[cookbook_name]
      files = []
      ckbk.manifest['files'].each do |file_info|
        files << file_info['path']
      end
      files
    end

    # Return a list of files in this cookbook
    #
    # @returns [Array] of file names relative to
    # the files directory in the cookbook
    def cookbook_file_names(cookbook_name)
      relative_file_names = []
      cb_files = cookbook_file_paths(cookbook_name)

      # Drop the cookbook directory and cookbook name
      # from the front of the path. Account for the fact
      # that we might have multiple directories in the
      # cookbook path so it might be a string, or an Array
      cb_files.each do |cb_file|
        # Without the .dup the gsub! below causes  Chef::Exceptions::FileNotFound
        # when the cookbook_file resource goes to place the file
        relative_file_name = cb_file.dup
        Array(Chef::Config[:cookbook_path]).each do |cb_path|
          # Ensure the full cookbook path is not part of relative name
          dir_prefix = Regexp.new('[A-Za-z]?:?' +
            ::File.join(cb_path, cookbook_name, '/'))
          relative_file_name.gsub!(dir_prefix, '')

          files_prefix = ::File.join('files', 'default', '/')
          relative_file_name.gsub!(files_prefix, '')
        end
        relative_file_names << relative_file_name
      end
      remove_nil_from_array(relative_file_names)
    end

    # Remove nil entries from an Array
    #
    # @return [Array]
    def remove_nil_from_array(list_to_clean)
      list_to_clean.reject { |entry| entry.nil? }
    end
  end
end


text:
sectionid: building-internal-apps
sectionclass: h2
title: Building Internal Apps
parent-id: how
number: 2010
---

We love building apps.
Follow these guidelines when you build them.
It helps your friends to be involved in your project
and to make them live.

*  A user should be able to onboard on his own
*  Should support multiple Organization
*  Should be API ready
*  Git Repo & Issue tracker


text:
using ApiScanner.Entities.Enums;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace ApiScanner.Entities.Models
{
    public class ApiModel
    {
        /// <summary>
        /// Id of api.
        /// </summary>
        [Key]
        public Guid ApiId { get; set; }

        /// <summary>
        /// Id of user who created the api.
        /// </summary>
        [Required]
        public Guid UserId { get; set; }

        /// <summary>
        /// Name of api.
        /// </summary>
        [MaxLength(50)]
        [Required]
        public string Name { get; set; }

        /// <summary>
        /// Absolute url of api.
        /// </summary>
        [MaxLength(500)]
        [Required]
        public string Url { get; set; }

        /// <summary>
        /// Http request method type.
        /// </summary>
        public HttpMethodType Method { get; set; }

        /// <summary>
        /// Headers of request.
        /// </summary>
        public string Headers { get; set; }

        /// <summary>
        /// Body of request.
        /// </summary>
        public string Body { get; set; }

        /// <summary>
        /// Interval to scan the api.
        /// </summary>
        public ApiInterval Interval { get; set; }

        /// <summary>
        /// Authorization type.
        /// </summary>
        public AuthorizationType Authorization { get; set; }

        /// <summary>
        /// Only scan if true.
        /// </summary>
        public bool Enabled { get; set; }

        /// <summary>
        /// Anyone can see if true.
        /// </summary>
        public bool PublicRead { get; set; }

        /// <summary>
        /// Anyone can modify if true.
        /// </summary>
        public bool PublicWrite { get; set; }

        /// <summary>
        /// User who created the api.
        /// </summary>
        public ApplicationUser User { get; set; }

        /// <summary>
        /// Conditions of api.
        /// </summary>
        public ICollection<ConditionModel> Conditions { get; set; }

        /// <summary>
        /// Locations of api.
        /// </summary>
        public ICollection<ApiLocationModel> ApiLocations { get; set; }

        /// <summary>
        /// Api logs.
        /// </summary>
        public ICollection<ApiLogModel> ApiLogs { get; set; }

        /// <summary>
        /// Api widgets.
        /// </summary>
        public ICollection<ApiWidgetModel> ApiWidgets { get; set; }
    }
}


text:
using System;

namespace LeanCloud.Storage.Internal {
  public interface IAVModule {
    void OnModuleRegistered();
    void OnParseInitialized();
  }
}


text:
package org.zaproxy.zap.extension.fuzz;

import java.awt.EventQueue;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javax.swing.SwingUtilities;
import org.zaproxy.zap.extension.httppanel.Message;
import org.zaproxy.zap.model.ScanController;
import org.zaproxy.zap.model.Target;
import org.zaproxy.zap.users.User;

/**
 * A main {@code ScanController} of fuzzer scans.
 *
 *
Allows to control all fuzzer scans of several message types, for example, HTTP and WebSockets.
 */
public class FuzzersController implements ScanController<Fuzzer<? extends Message>> {

    /**
     * The {@code Lock} for exclusive access to instance variables related to multiple fuzzers.
     *
     * @see #fuzzerIdCounter
     * @see #fuzzerIdsToFuzzerMap
     */
    private final Lock fuzzersLock;

    /**
     * The counter used to give an unique ID to fuzzers.
     *
     *
Note: All accesses (read/write) should be done while holding the {@code
     * Lock} {@code scansLock}.
     *
     * @see #fuzzersLock
     * @see #registerScan(FuzzerHandler, Fuzzer)
     */
    private int fuzzerIdCounter;

    /**
     * A map that contains all {@code Fuzzer}s created (and not yet removed) and corresponding
     * {@code FuzzerHandler}s. Used to control (i.e. pause/resume and stop) the multiple active
     * fuzzers and get its results. The instance variable is never {@code null}. The map key is the
     * ID of the fuzzer.
     *
     *
Note: All accesses (both write and read) should be done while holding the
     * {@code Lock} {@code fuzzersLock}.
     *
     * @see #fuzzersLock
     * @see #fuzzerIdCounter
     */
    private Map<Integer, FuzzerEntry<?, ?>> fuzzerIdsToFuzzerMap;

    private FuzzersStatusPanel fuzzersStatusPanel;

    public FuzzersController() {
        fuzzersLock = new ReentrantLock();
        fuzzerIdsToFuzzerMap = new HashMap<>();
    }

    private void acquireFuzzersLock() {
        fuzzersLock.lock();
    }

    private void releaseScanStateLock() {
        fuzzersLock.unlock();
    }

    /**
     * Throws {@code UnsupportedOperationException}, the fuzzers are started by 3rd party.
     *
     * @throws UnsupportedOperationException the fuzzers are started by 3rd party.
     * @see #registerScan(FuzzerHandler, Fuzzer)
     */
    @Override
    public int startScan(
            String displayName, Target target, User user, Object[] contextSpecificObjects) {
        throw new UnsupportedOperationException(
                "Fuzzer scans are started by concrete fuzzer implementations.");
    }

    public <M extends Message, F extends Fuzzer<M>, FH extends FuzzerHandler<M, F>>
            void registerScan(FH fuzzHandler, F fuzzer) {
        acquireFuzzersLock();
        try {
            fuzzer.setScanId(fuzzerIdCounter);
            Integer id = Integer.valueOf(fuzzerIdCounter);
            fuzzerIdsToFuzzerMap.put(id, new FuzzerEntry<>(fuzzHandler, fuzzer));
            fuzzerIdCounter++;
        } finally {
            releaseScanStateLock();
        }
    }

    public FuzzResultsContentPanel<?, ?> getFuzzResultsContentPanel(Fuzzer<?> fuzzer) {
        acquireFuzzersLock();
        try {
            return getScanContentPanelHelper(
                    fuzzerIdsToFuzzerMap.get(Integer.valueOf(fuzzer.getScanId())));
        } finally {
            releaseScanStateLock();
        }
    }

    private <M extends Message, F extends Fuzzer<M>>
            FuzzResultsContentPanel<?, ?> getScanContentPanelHelper(FuzzerEntry<M, F> entry) {
        if (entry == null) {
            return null;
        }

        FuzzResultsContentPanel<M, F> panel = entry.getResultsContentPanel();
        panel.showFuzzerResults(entry.getFuzzer());
        return panel;
    }

    @Override
    public List<Fuzzer<? extends Message>> getAllScans() {
        acquireFuzzersLock();
        try {
            List<Fuzzer<? extends Message>> fuzzers = new ArrayList<>();
            for (FuzzerEntry<?, ?> entry : fuzzerIdsToFuzzerMap.values()) {
                fuzzers.add(entry.getFuzzer());
            }
            return fuzzers;
        } finally {
            releaseScanStateLock();
        }
    }

    @Override
    public List<Fuzzer<? extends Message>> getActiveScans() {
        acquireFuzzersLock();
        try {
            List<Fuzzer<? extends Message>> fuzzers = new ArrayList<>();
            for (FuzzerEntry<?, ?> entry : fuzzerIdsToFuzzerMap.values()) {
                if (!entry.getFuzzer().isStopped()) {
                    fuzzers.add(entry.getFuzzer());
                }
            }
            return fuzzers;
        } finally {
            releaseScanStateLock();
        }
    }

    @Override
    public Fuzzer<? extends Message> getScan(int id) {
        acquireFuzzersLock();
        try {
            FuzzerEntry<?, ?> entry = fuzzerIdsToFuzzerMap.get(Integer.valueOf(id));
            if (entry != null) {
                return entry.getFuzzer();
            }
            return null;
        } finally {
            releaseScanStateLock();
        }
    }

    @Override
    public void stopScan(int id) {
        acquireFuzzersLock();
        try {
            FuzzerEntry<?, ?> entry = fuzzerIdsToFuzzerMap.get(Integer.valueOf(id));
            if (entry != null) {
                entry.getFuzzer().stopScan();
            }
        } finally {
            releaseScanStateLock();
        }
    }

    @Override
    public void stopAllScans() {
        acquireFuzzersLock();
        try {
            for (FuzzerEntry<?, ?> entry : fuzzerIdsToFuzzerMap.values()) {
                entry.getFuzzer().stopScan();
            }
        } finally {
            releaseScanStateLock();
        }
    }

    @Override
    public void pauseScan(int id) {
        acquireFuzzersLock();
        try {
            FuzzerEntry<?, ?> entry = fuzzerIdsToFuzzerMap.get(Integer.valueOf(id));
            if (entry != null) {
                entry.getFuzzer().pauseScan();
                updateScannerUI();
            }
        } finally {
            releaseScanStateLock();
        }
    }

    @Override
    public void pauseAllScans() {
        acquireFuzzersLock();
        try {
            for (FuzzerEntry<?, ?> entry : fuzzerIdsToFuzzerMap.values()) {
                entry.getFuzzer().pauseScan();
            }
            updateScannerUI();
        } finally {
            releaseScanStateLock();
        }
    }

    @Override
    public void resumeScan(int id) {
        acquireFuzzersLock();
        try {
            FuzzerEntry<?, ?> entry = fuzzerIdsToFuzzerMap.get(Integer.valueOf(id));
            if (entry != null) {
                entry.getFuzzer().resumeScan();
                updateScannerUI();
            }
        } finally {
            releaseScanStateLock();
        }
    }

    @Override
    public void resumeAllScans() {
        acquireFuzzersLock();
        try {
            for (FuzzerEntry<?, ?> entry : fuzzerIdsToFuzzerMap.values()) {
                entry.getFuzzer().resumeScan();
            }
            updateScannerUI();
        } finally {
            releaseScanStateLock();
        }
    }

    @Override
    public Fuzzer<? extends Message> removeScan(int id) {
        acquireFuzzersLock();
        try {
            FuzzerEntry<?, ?> entry = fuzzerIdsToFuzzerMap.remove(Integer.valueOf(id));
            if (entry != null) {
                entry.notifyScannerRemoved();
                return entry.getFuzzer();
            }
            return null;
        } finally {
            releaseScanStateLock();
        }
    }

    @Override
    public int removeAllScans() {
        acquireFuzzersLock();
        try {
            for (FuzzerEntry<?, ?> entry : fuzzerIdsToFuzzerMap.values()) {
                entry.getFuzzer().stopScan();
                entry.notifyScannerRemoved();
            }
            int count = fuzzerIdsToFuzzerMap.size();
            fuzzerIdsToFuzzerMap.clear();
            return count;
        } finally {
            releaseScanStateLock();
        }
    }

    public void removeAllScans(FuzzerHandler<?, ?> fuzzerHandler) {
        acquireFuzzersLock();
        try {
            for (Iterator<FuzzerEntry<?, ?>> it = fuzzerIdsToFuzzerMap.values().iterator();
                    it.hasNext(); ) {
                FuzzerEntry<?, ?> entry = it.next();
                if (entry.getFuzzerHandler() == fuzzerHandler) {
                    entry.getFuzzer().stopScan();
                    entry.notifyScannerRemoved();
                    it.remove();
                }
            }
        } finally {
            releaseScanStateLock();
        }
    }

    @Override
    public int removeFinishedScans() {
        acquireFuzzersLock();
        try {
            int count = 0;
            for (Iterator<FuzzerEntry<?, ?>> it = fuzzerIdsToFuzzerMap.values().iterator();
                    it.hasNext(); ) {
                FuzzerEntry<?, ?> entry = it.next();
                if (entry.getFuzzer().isStopped()) {
                    entry.notifyScannerRemoved();
                    it.remove();
                    count++;
                }
            }
            return count;
        } finally {
            releaseScanStateLock();
        }
    }

    @Override
    public Fuzzer<? extends Message> getLastScan() {
        throw new UnsupportedOperationException("State of last scan is not supported.");
    }

    public void setFuzzerScansPanel(FuzzersStatusPanel fuzzerScansPanel) {
        this.fuzzersStatusPanel = fuzzerScansPanel;
    }

    public <M extends Message, F extends Fuzzer<M>> List<F> getFuzzers(Class<F> fuzzerClass) {
        List<F> fuzzers = new ArrayList<>();
        acquireFuzzersLock();
        try {
            for (Iterator<FuzzerEntry<?, ?>> it = fuzzerIdsToFuzzerMap.values().iterator();
                    it.hasNext(); ) {
                Fuzzer<?> fuzzer = it.next().getFuzzer();
                if (fuzzerClass.equals(fuzzer.getClass())) {
                    fuzzers.add(fuzzerClass.cast(fuzzer));
                }
            }
        } finally {
            releaseScanStateLock();
        }
        return fuzzers;
    }

    private void updateScannerUI() {
        if (fuzzersStatusPanel == null) {
            return;
        }

        EventQueue.invokeLater(() -> fuzzersStatusPanel.updateScannerUI());
    }

    private static class FuzzerEntry<M extends Message, F extends Fuzzer<M>> {

        private final FuzzerHandler<M, F> fuzzerHandler;
        private final F fuzzer;

        public FuzzerEntry(FuzzerHandler<M, F> fuzzerHandler, F fuzzer) {
            this.fuzzer = fuzzer;
            this.fuzzerHandler = fuzzerHandler;
        }

        public FuzzResultsContentPanel<M, F> getResultsContentPanel() {
            return fuzzerHandler.getResultsContentPanel();
        }

        public FuzzerHandler<M, F> getFuzzerHandler() {
            return fuzzerHandler;
        }

        public F getFuzzer() {
            return fuzzer;
        }

        public void notifyScannerRemoved() {
            fuzzerHandler.scannerRemoved(fuzzer);
        }
    }

    void updateUiFuzzResultsContentPanels() {
        acquireFuzzersLock();
        try {
            fuzzerIdsToFuzzerMap.values().stream()
                    .map(FuzzerEntry::getResultsContentPanel)
                    .map(FuzzResultsContentPanel::getPanel)
                    .forEach(SwingUtilities::updateComponentTreeUI);
        } finally {
            releaseScanStateLock();
        }
    }
}


text:
require 'rails'
require 'active_support'
require 'action_pack'
require 'action_view'
require 'action_controller'
require 'action_dispatch'

# Thanks to Justin French for formtastic spec
module FoundationRailsSpecHelper
  include ActionPack
  include ActionView::Context if defined?(ActionView::Context)
  include ActionController::RecordIdentifier
  include ActionView::Helpers::FormHelper
  include ActionView::Helpers::FormTagHelper
  include ActionView::Helpers::FormOptionsHelper
  include ActionView::Helpers::UrlHelper
  include ActionView::Helpers::TagHelper
  include ActionView::Helpers::TextHelper
  include ActionView::Helpers::ActiveRecordHelper if defined?(ActionView::Helpers::ActiveRecordHelper)
  include ActionView::Helpers::ActiveModelHelper if defined?(ActionView::Helpers::ActiveModelHelper)
  include ActionView::Helpers::DateHelper
  include ActionView::Helpers::CaptureHelper
  include ActionView::Helpers::AssetTagHelper
  include ActiveSupport
  include ActionController::PolymorphicRoutes if defined?(ActionController::PolymorphicRoutes)

  def active_model_validator(kind, attributes, options = {})
    validator = mock("ActiveModel::Validations::#{kind.to_s.titlecase}Validator", :attributes => attributes, :options => options)
    validator.stub!(:kind).and_return(kind)
    validator
  end

  def active_model_presence_validator(attributes, options = {})
    active_model_validator(:presence, attributes, options)
  end

  def active_model_length_validator(attributes, options = {})
    active_model_validator(:length, attributes, options)
  end

  def active_model_inclusion_validator(attributes, options = {})
    active_model_validator(:inclusion, attributes, options)
  end

  def active_model_numericality_validator(attributes, options = {})
    active_model_validator(:numericality, attributes, options)
  end

  class ::Author
    extend ActiveModel::Naming if defined?(ActiveModel::Naming)
    include ActiveModel::Conversion if defined?(ActiveModel::Conversion)

    def to_label
    end

    def persisted?
    end
  end

  def mock_everything
    # Resource-oriented styles like form_for(@post) will expect a path method for the object,
    # so we're defining some here.
    def author_path(*args); "/authors/1"; end
    def authors_path(*args); "/authors"; end
    def new_author_path(*args); "/authors/new"; end

    @author = ::Author.new
    @author.stub!(:class).and_return(::Author)
    @author.stub!(:to_label).and_return('Fred Smith')
    @author.stub!(:login).and_return('fred_smith')
    @author.stub!(:email).and_return('fred@foo.com')
    @author.stub!(:url).and_return('http://example.com')
    @author.stub!(:some_number).and_return('42')
    @author.stub!(:phone).and_return('317 456 2564')
    @author.stub!(:password).and_return('secret')
    @author.stub!(:active).and_return(true)
    @author.stub!(:description).and_return('bla bla bla')
    @author.stub!(:avatar).and_return('avatar.png')
    @author.stub!(:birthdate).and_return(Date.parse("1969-06-18 20:30"))
    @author.stub!(:id).and_return(37)
    @author.stub!(:new_record?).and_return(false)
    @author.stub!(:errors).and_return(mock('errors', :[] => nil))
    @author.stub!(:to_key).and_return(nil)
    @author.stub!(:persisted?).and_return(nil)

    ::Author.stub!(:scoped).and_return(::Author)
    ::Author.stub!(:find).and_return([@author])
    ::Author.stub!(:all).and_return([@author])
    ::Author.stub!(:where).and_return([@author])
    ::Author.stub!(:human_attribute_name).and_return { |column_name| column_name.to_s.humanize }
    ::Author.stub!(:human_name).and_return('::Author')
    ::Author.stub!(:content_columns).and_return([mock('column', :name => 'login'), mock('column', :name => 'created_at')])
    ::Author.stub!(:to_key).and_return(nil)
    ::Author.stub!(:persisted?).and_return(nil)
  end

  def self.included(base)
    base.class_eval do
      attr_accessor :output_buffer

      def protect_against_forgery?
        false
      end

    end
  end
end


text:
package com.lubocluod.touchwebcms.dao;

import java.util.List;

import com.lubocluod.touchwebcms.entity.Role;

public interface RoleDao {
	public boolean add(Role r);
	public boolean delete(int id);
	public boolean update(Role r);
	public Role find(String username);
	public Role find(int id);
	public List<Role> findAll();
}


text:
require 'spec_helper'

describe Providers::Twitter do

  before do
    @provider = Providers::Twitter.new
    @request  = Rack::Request.new('HTTP_HOST' => 'foo.com', 'rack.url_scheme' => 'https')
  end

  describe "#redirect_uri" do
    it "returns the url where the user is redirected" do
      subject.redirect_uri(@request).should == 'https://foo.com/oauth/twitter/callback'
    end
  end

  describe "#find_or_create_user" do
    before do
      client, @token = mock, mock
      @token.should_receive(:token).and_return('aaa')
    end
    it "returns a user if present" do
      User.should_receive(:find_by_access_token).and_return('foo')
      @provider.find_or_create_user(@token, @request).should == 'foo'
    end

    it "creates the user if missing" do
      User.should_receive(:find_by_access_token).and_return(nil)
      @provider.should_receive(:create_user).and_return('OMG')
      @provider.find_or_create_user(@token, @request).should == "OMG"
    end
  end

  describe "#create_user" do

    it "creates the user" do
      token = mock(:token => "ZOMG", :params => { 'user_id' => 33 })
      token.stub_chain(:client, :site=)
      response = mock(:body => '{"screen_name":"foo","profile_image_url_https":"IMG"}')
      token.should_receive(:get).with('/1.1/users/show.json?user_id=33').and_return(response)
      lambda {
        @provider.create_user(token)
      }.should change(User, :count).by(1)
      user = User.last
      user.access_token.should == "ZOMG"
      user.provider.should == 'twitter'
    end

  end

end


text:
<?php

namespace Magento\Security\Test\Unit\Model\ResourceModel;

use Magento\Framework\TestFramework\Unit\Helper\ObjectManager;

/**
 * Test class for \Magento\Security\Model\ResourceModel\PasswordResetRequestEvent testing
 */
class PasswordResetRequestEventTest extends \PHPUnit_Framework_TestCase
{
    /** @var \Magento\Security\Model\ResourceModel\PasswordResetRequestEvent */
    protected $model;

    /** @var \Magento\Framework\Stdlib\DateTime */
    protected $dateTimeMock;

    /** @var \Magento\Framework\App\ResourceConnection */
    protected $resourceMock;

    /** @var \Magento\Framework\DB\Adapter\AdapterInterface */
    protected $dbAdapterMock;

    /**
     * Init mocks for tests
     * @return void
     */
    protected function setUp()
    {
        $objectManager = new ObjectManager($this);

        $this->dateTimeMock = $this->getMock(
            '\Magento\Framework\Stdlib\DateTime',
            [],
            [],
            '',
            false
        );

        $this->resourceMock = $this->getMock(
            '\Magento\Framework\App\ResourceConnection',
            [],
            [],
            '',
            false
        );

        $this->dbAdapterMock = $this->getMock(
            '\Magento\Framework\DB\Adapter\AdapterInterface',
            [],
            [],
            '',
            false
        );

        $this->model = $objectManager->getObject(
            '\Magento\Security\Model\ResourceModel\PasswordResetRequestEvent',
            [
                'resource' => $this->resourceMock,
                'dateTime' => $this->dateTimeMock
            ]
        );
    }

    /**
     * @return void
     */
    public function testDeleteRecordsOlderThen()
    {
        $timestamp = 12345;

        $this->resourceMock->expects($this->once())
            ->method('getConnection')
            ->willReturn($this->dbAdapterMock);

        $this->dbAdapterMock->expects($this->once())
            ->method('delete')
            ->with($this->model->getMainTable(), ['created_at < ?' => $this->dateTimeMock->formatDate($timestamp)])
            ->willReturnSelf();

        $this->assertEquals($this->model, $this->model->deleteRecordsOlderThen($timestamp));
    }
}