text:
market-pricing
=====

[![Greenkeeper badge](https://badges.greenkeeper.io/DrPaulBrewer/market-pricing.svg)](https://greenkeeper.io/)
[![Build Status](https://travis-ci.org/DrPaulBrewer/market-pricing.svg?branch=master)](https://travis-ci.org/DrPaulBrewer/market-pricing)
[![Coverage Status](https://coveralls.io/repos/github/DrPaulBrewer/market-pricing/badge.svg?branch=master)](https://coveralls.io/github/DrPaulBrewer/market-pricing?branch=master)

#### Copyright 2016 Paul Brewer, Economic & Financial Technology Consulting LLC <drpaulbrewer@eaftc.com>

#### Open Source License: The MIT License

npm Javascript package of algorithms for finding competitive equilibrium prices from demand and supply functions or sorted order queues.

Intended application:

A building block for
   * teaching and research simulations with robot traders
   * market experiments or demonstrations with human subjects
   * policy studies
   * developing new kinds of market rules or order types
   * other types of exchange markets, e.g. resource tokens, prediction, etc.

## Installation

    npm install market-pricing --save

## Usage

    var marketPricing = require('market-pricing');

### Data Requirements

Most functions require economically pre-sorted arrays of buy and sell orders.
That is, buy orders should be sorted price descending, highest price first.
Sell orders should be sorted price ascending, with the lowest price first.

Each order may be an Array of arbitrary length with as many other fields as necessary for a given application.  Objects might also work, but are untested in this version.

`cross`, `demandFromQueue`, and `supplyFromQueue` require the array indexes for "buy price", "buy quantity", "sell price", and "sell quantity".

The `sequential()` function also requires a timestamp or ordernumber
index so that it can tell which buy or sell orders occurred before other orders.

Example:

    // set up price-sorted buy (descending) and sell (ascending) order lists
    // bob wants 1 at price of 300, fred wants 1 at price of 250
    var buyerList = [['bob',1,300],['fred',1,250]];
    // sue will sell 1 at price of 200, alice will sell 1 at price of 280
    var sellerList = [['sue',1,200],['alice',1,280]];

### Functionality

#### Walrasian Tantonnement

Walrasian Tatonnement is a price-search procedure often attributed to
Walras, whereby the price is raised if there is excess demand, and lowered if
there is excess supply, until a price is found where the demand and supply equal.

The price where demand and supply equal is called the competitive equilibrium.

    var priceRange = marketPricing.walrasianCEPriceRange(
       pLow /* lower limit of price search, number */,
       pHigh /* upper limit of price search,  number */,
       pTol /* tolerance of price search, number, >=1 forces integer result */,
       qDemand /* function(p){...} returning quantity demanded for price p */,
       qSupply /* function(p){...} returning quantity supplied for price p */
    );

Starting with the `buyerList` and `sellerList` in the example above, we can use the helper functions `demandFromQueue` and `supplyFromQueue` to setup demand and supply functions for calculating the CE as follows:

    var qDFunc = marketPricing.demandFromQueue(
        buyerList,
        2 /* index for price in each item of buyerList ArrayOfArray */,
        1 /* index for quantity in each item of buyerList ArrayOfArray */);

    var qSFunc = marketPricing.supplyFromQueue(
        sellerList,
        2 /* index for price in each sellerList item */,
        1 /* index for quantity in each sellerList item */);

 You might then notice that `qDFunc(0)` returns 2 because both Bob and Fred would
buy 1 unit, for a total of 2 units,  if the price were zero. Similarly, `qSFunc(0)` returns 0 because neither seller will sell for a price of zero.

Now to search for a Walrasian Competitive Equilibirum Price Range between prices of 0 and 500, with a tolerance of 1 price unit, execute:

     marketPricing.walrasianCEPriceRange(0,500,1,qDFunc,qSFunc)
     --> [ 251, 279 ]

This indicates a competitive equilibrium price range of `251<=P<=279`.

Let's check the example to see if this makes sense.  At price P in `251<=P<=279`,
Bob wants to buy one because he was willing to pay 300, and Fred will buy zero because he was willing to pay 250 only and `P>250`, Sue sells one because she would sell for
a price of 200 or more, and Alice will not sell because she wanted a price of 280.
Therefore for the prices P in `251<=P<=279` there is one unit of demand and one unit
of supply and the market is in competitive equilibrium.

Notice how the prices of the excluded buyer and seller help set the limits of the range.  If the price were 250, Fred would buy, but there is no 2nd unit of supply at that price to sell to Fred.  If the price were 280, Alice would sell but there is no 2nd unit of demand at that price, no buyer to buy from Alice.

#### Marshallian Competitive Equilibrium

A **different** technique which yields reasonably consistent results is attributed to
to Marshall and involves finding the intersection of supply and demand curves on
a two dimensional chart, with axes of price and quantity.

In the case of integer quantities, the supply and demand curves become step functions and
the intersection can either be a point (exact price and quantity), a
horizontal segment (exact Price and a range of quantities), or a vertical segment
(exact quantity and a range or prices).

The helper function

     marketPricing.marshallianCEPriceRange(inframarginalBuyPrice,
                                           inframarginalSellPrice,
                                           extrmarginalBuyPrice,
                                           extramarginalSupplyPrice)

checks the input against each other for validity, and throws an error if, e.g. the extramarginal unit could trade or
the prices are in the wrong sort order.

Valid usage always returns a two element array representing the lower and upper bounds of the price range.

The lower bound is given by the larger of `inframarginalSellPrice` and `extraMarginalBuyPrice`.

The upper bound is given bu the smaller of `inframarginalBuyPrice` and `extraMarginalSellPrice`.

If one or both of the extramarginal prices do not exist, the usage is still valid, and the undefined value is simply ignored in the formula.

#### Call Markets: Crossing Order Queues to obtain CE price and trades

The `marketPricing.crossSingleUnitDemandAndSupply(buyPrices, sellPrices)` function, on success, returns an object `{p: [p0,p1] or number, q: [q0,q1] or number}` representing
the competitive equilibrium price or price range p, and competitive equilibrium quantity or quantity range q, treating the sorted numeric input arrays `buyPrices` and `sellPrices`
as single units of demand or supply at the given prices.

The `marketPricing.cross(buyQueue,sellQueue,bpCol,bqCol,spCol,sqCol)` function, on success, returns a 4 element array: [price, totalQuantity, buyQuantityArray, sellQuantityArray]
where the buyQuantityArray and sellQuantityArrays provide the quantities traded from individual orders in buyQueue and sellQueue.

`cross` assumes that `buyQueue` is sorted with the highest price buy order as buyQueue[0], with subsequent buy orders equal or lower in price,
and assumes that `sellQueue` is sorted with the lowest price sell order as sellQueue[0], with subsequent sell orders equal or higher in price.

`cross` does NOT sort the `buyQueue` and `sellQueue` because sorting can be costly if the queues are large.  This also allows a developer flexibility in when and how
often the queues are sorted, provided they are always in sort order when cross or other market-pricing routines are called.

`cross` operates by walking the Marhsllian path matching orders from the buyQueue and sellQueue until the inframarginal and extramarginal prices are identified. It then
feeds these prices to `marshallianCEPriceRange` to obtain the price range, and calculates the midpoint price from this range.

The set of trades identified in the buyQuantityArray and sellQuantityArray can be considered optimal in the sense that the sum of the surplus between the ordered prices and achieved price
over the set of all traders are maximized.

Note that even if all prices are integers, the midpoint could be between integers. Caution is advised rounding up or down to an integer price.  It is probably OK to do so only when prices are always integers, and the quantities returned in the buyQuantityArray and sellQuantityArray are used as the traded quantities.

`cross` checks for validity, throwing an error if any of the *Col variables
are undefined.  The *Col variables are for specifying the format of your order data, specifically, the column number or property name for buy price (bpC0l),
the buy quantity column name or number (bqCol), the sell price column name or number (spCol), and the sell quantity column name or number (sqCol).

simple example:

    // bob wants 1 at price of 300, fred wants 1 at price of 250
    var buyerList = [['bob',1,300],['fred',1,250]];
    // sue will sell 1 at price of 200, alice will sell 1 at price of 280
    var sellerList = [['sue',1,200],['alice',1,280]];
    marketPricing.cross(buyerList,sellerList,2,1,2,1);
    -->  [ 265, 1, [ 1 ], [ 1 ] ]

The result means that the price is 265, total quantity traded is 1, trading 1 unit from bob's order buy, and 1 unit from sue's sell order.

Note that the price of 265 was obtained from the midpoint of the Marshllian price range calculation, but also matches the midpoint of the earlier Walrasian method.

#### Sequential Markets: Finding the trades from a single order

The `marketPricing.sequential(buyQueue,sellQueue,tCol,bpCol,bqCol,spCol,sqCol)` is used to check for prices and traded quantities after each single order.

A valid return is either undefined, indicating no trade, or

    ['b' or 's',[prices],totalQuantity,buyQuantityArray,sellQuantityArray]

where 'b' or 's' indicates that the last order is a buy or a sell, the [prices] array is an array of the price from each matched order, and the buyQuantityArray
and sellQuantityArray indicate the amount traded from each order as explained above for `cross()`.

The new order should be placed in the proper sorted queue before calling.  The tCol indicates the time column.  Any kind of ascending column, like an order number,
can be used as the time column.

Internally in `sequential()`, the `cross()` function is used to find the quantities traded.

The price from `cross` is discarded, and prices are determined from the orders themeselves.  The pricing rule is that the price of the earlier order determines the trade price.
This means, for instance, that a large buy order will be filled at various prices corresponding to first the lowest price sell order, then the next higher, etc., until the buy order is filled
or there are no more sell order with a price less than that of the buy order.

`sequential()` is intended as a building block for a sequential trading engine, but is not the complete engine.  After each trade, adjustments to the queues are required
before calling `sequential()` again with a new order.

In our previous example with Bob, Fred, Alice, and Sue, the prices and trades would depend on the time order.

Scenario A:

1. No buy orders. Alice places sell order for 1 unit @ 280.  `sequential()` would return `undefined` (no trade).
2. Bob places a buy order for 1 unit @ 300.  Now `sequential()` would return [[280],1,[1],[1]], indicating a trade at the earlier price of 280.
3. Clearing out the traded orders from the buy and sell queues manually would result in empty buy and sell queues.
4. next Fred places a buy order for 1 unit @ 250.  There are no sell orders yet.
5. Sue places a sell order for 1 unit @ 200.  `sequential()` would return [[250],1,[1],[1]]), indicating a trade at the earlier price of 250.

Scenario A results in 2 trades, 1 trade @ 280 and 1 trade @ 250.

Scenario B:
1. No buy orders. Sue places sell order 1 unit @ 200.
2. Bob places a buy order for 1 unit @ 300.  Now `sequential()` would return [[200],1,[1],[1]] indicating a trade at the earlier price of 200.
3. Clearing out the traded orders from the buy and sell queues manually would result in empty buy and sell queues.
4. next Alice places a sell order for 1 unit @280.  no trades.
5. next Fred places a buy order for 1 unit @250.  `sequential()` would return undefined, as Fred's buy price is less than Alice's sell price.

With the same orders as Scenario A, but in a different sequence, scenario B results in only 1 trade @ 200.


text:
'use strict';

var React = require('react');

var ContentPage = React.createClass({

  propTypes: {
    body: React.PropTypes.string.isRequired
  },

  render() {
    var { className, title, body, other } = this.props;

    /* jshint ignore:start */
    return <div className={'ContentPage ' + className}
      dangerouslySetInnerHTML={{__html: body}} />;
    /* jshint ignore:end */
  }

});

module.exports = ContentPage;

redpajama_set_name: RedPajamaGithub


text:
package it.reply.orchestrator.controller;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import it.reply.orchestrator.config.specific.WebAppConfigurationAwareIT;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.restdocs.JUnitRestDocumentation;
import org.springframework.restdocs.mockmvc.MockMvcRestDocumentation;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

public class MiscControllerIT extends WebAppConfigurationAwareIT {

  @Autowired
  protected WebApplicationContext wac;

  private MockMvc mockMvc;

  @Rule
  public JUnitRestDocumentation restDocumentation =
      new JUnitRestDocumentation("target/generated-snippets");

  @Before
  public void before() {
    this.mockMvc = MockMvcBuilders
        .webAppContextSetup(this.wac)
        .apply(MockMvcRestDocumentation.documentationConfiguration(this.restDocumentation))
        .build();
  }

  @Test
  public void getRoot() throws Exception {
    mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk());
  }

  @Test
  public void getInfo() throws Exception {
    mockMvc.perform(get("/info").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk());
  }

}


text:
const webpack = require('webpack')
const NodePolyfillPlugin = require('node-polyfill-webpack-plugin')

module.exports = {
  entry: './index.js',
  output: {
    filename: 'build/[name].js',
    path: __dirname
  },
  resolve: {
    fallback: {
      fs: false,
      child_process: false,
      worker_threads: false,
      net: false,
      tls: false,
      ws: false
    }
  },
  devServer: { static: { directory: __dirname }, open: true },
  plugins: [
    new NodePolyfillPlugin(),
    new webpack.ProvidePlugin({
      process: require.resolve('process/browser')
    })
  ]
}


text:
<web-app version="2.4"
	xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

	<display-name>Spring MVC Application</display-name>

    <servlet>
		<servlet-name>mvc-dispatcher</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>mvc-dispatcher</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

   <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/applicationContext.xml
        </param-value>
    </context-param>

    <context-param>
        <param-name>defaultHtmlEscape</param-name>
        <param-value>true</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
</web-app>


text:
package in.beacandid.app.beacandid.ui.discover;

public class ShareLatestListExtract {
    /*
private void shareImage() {
            AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(itemView.getContext());
            LayoutInflater inflater = (LayoutInflater) itemView.getContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE );
            View dialogView = inflater.inflate(R.layout.custom_dialog_share_image, null);
            dialogBuilder.setView(dialogView);

            AlertDialog b = dialogBuilder.create();
            DisplayMetrics displayMetrics = new DisplayMetrics();
            ((WindowManager)itemView.getContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(displayMetrics);
            int height = displayMetrics.heightPixels;
            int width = displayMetrics.widthPixels;
            b.getWindow().setLayout(width, 110);
            b.show();

            ImageView facebook = (ImageView) dialogView.findViewById(R.id.facebook);
            ImageView twitter = (ImageView) dialogView.findViewById(R.id.twitter);
            ImageView linkIn = (ImageView) dialogView.findViewById(R.id.linkIn);
            ImageView Instagram = (ImageView) dialogView.findViewById(R.id.instagram);
            ImageView pinist = (ImageView) dialogView.findViewById(R.id.pinest);
            ImageView tumber = (ImageView) dialogView.findViewById(R.id.tumber);
            ImageView more = (ImageView) dialogView.findViewById(R.id.more);

            facebook.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (ActivityUtils.deleteAudioFile(itemView.getContext())){
                        createDirectoryAndSaveFile(itemView.getContext(), bmp, "HelloAndroid", "com.facebook.katana");
                    }

                    b.cancel();
                }
            });

            twitter.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (ActivityUtils.deleteAudioFile(itemView.getContext())){
                        createDirectoryAndSaveFile(itemView.getContext(),bmp, "HelloAndroid", "com.twitter.android");
                    }

                    b.cancel();
                }
            });

            linkIn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (ActivityUtils.deleteAudioFile(itemView.getContext())){
                        createDirectoryAndSaveFile(itemView.getContext(),bmp, "HelloAndroid", "com.linkedin.android");
                    }

                    b.cancel();
                }
            });

            Instagram.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (ActivityUtils.deleteAudioFile(itemView.getContext())){
                        createDirectoryAndSaveFile(itemView.getContext(),bmp, "HelloAndroid", "com.instagram.android");
                    }

                    b.cancel();
                }
            });

            pinist.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (ActivityUtils.deleteAudioFile(itemView.getContext())){
                        createDirectoryAndSaveFile(itemView.getContext(),bmp, "HelloAndroid", "com.pinterest");
                    }

                    b.cancel();
                }
            });
            tumber.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (ActivityUtils.deleteAudioFile(itemView.getContext())){
                        createDirectoryAndSaveFile(itemView.getContext(),bmp, "HelloAndroid", "com.tumblr");
                    }

                    b.cancel();
                }
            });
            more.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    v.getContext().startActivity(Intent.createChooser(sharedIntentMaker(), "Choose an app"));

                    b.cancel();
                }
            });
        }

        private Intent sharedIntentMaker() {
            String sharebody = String.valueOf(dataItem.getUser_name_random() + " " + "said:"
                    + " " + dataItem.getTextStatus() + " " + "inside Voiceme Android App. " +
                    "You can download from www.beacandid.com/candid?Post=" + dataItem.getIdPosts() + "");
            Intent shareIntent = new Intent();
            shareIntent.setAction(Intent.ACTION_SEND);
            shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
            shareIntent.setType("text/plain");
            shareIntent.putExtra(Intent.EXTRA_TEXT, sharebody);
            return shareIntent;
        }
 */

/*
 private Bitmap drawTextToBitmap(Context mContext, String text) {

            int textLength = text.length();
            int MAX_CHARCTER_IN_LINE = 60; //Text character count in one line

            DisplayMetrics displayMetrics = new DisplayMetrics();
            ((WindowManager) itemView.getContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(displayMetrics);
            //int height = displayMetrics.heightPixels;
            int width = displayMetrics.widthPixels;

            float text_x = width-40; //Image width taken in consideration
            float text_y = 500; //Image height taken in consideration
            double THRESHOLD_DIP = 30.0;

            final float scale = mContext.getResources().getDisplayMetrics().density;

            int mThreshold = (int) (THRESHOLD_DIP * scale + 0.5f);

            String[] splited = text.split("\\s+");
            double longest = 0;
            for (String s : splited) {
                if (s.length() > longest) {
                    longest = s.length();
                }
            }
            if (longest > MAX_STRING_LENGTH) {
                double ratio = (double) MAX_STRING_LENGTH / longest;
                mThreshold = (int) ((THRESHOLD_DIP * ((float) ratio)) * scale + 0.5f);
            }

            int noOfLines = Math.abs(textLength/MAX_CHARCTER_IN_LINE);
            for (int i=0; i<noOfLines; i++) {
                if(text_y > 130)
                    text_y -= 30;
            }

            //Bitmap bitmap = Bitmap.createBitmap(1024, 1024, Bitmap.Config.ARGB_8888);
            BitmapFactory.Options options = new BitmapFactory.Options();
            Bitmap bitmap = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.image);
            android.graphics.Bitmap.Config bitmapConfig = bitmap.getConfig();
            if (bitmapConfig == null) {
                bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
            }
            bitmap = bitmap.copy(bitmapConfig, true);

            Canvas canvas = new Canvas(bitmap);

            TextPaint mTextPaint = new TextPaint();
            mTextPaint.setColor(Color.WHITE);
            mTextPaint.setTextAlign(Paint.Align.CENTER);
            mTextPaint.setTextSize(mThreshold);
            StaticLayout mTextLayout = new StaticLayout(text, mTextPaint, canvas.getWidth()-40, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);

            canvas.save();

            canvas.translate(text_x, text_y);
            mTextLayout.draw(canvas);
            canvas.restore();

            return bitmap;
        }

        private void createDirectoryAndSaveFile(Context context, Bitmap imageToSave, String fileName, String PackageApp) {

            File direct = new File(Environment.getExternalStorageDirectory() + "/DirName");

            if (!direct.exists()) {
                File wallpaperDirectory = new File("/sdcard/DirName/");
                wallpaperDirectory.mkdirs();
            }

            File file = new File(new File("/sdcard/DirName/"), fileName + ".jpg");
            if (file.exists()) {
                file.delete();
            }
            try {
                FileOutputStream out = new FileOutputStream(file);
                imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
                out.flush();
                out.close();
                Uri uri = Uri.parse("file://" + file.getAbsolutePath());
                Intent share = new Intent(Intent.ACTION_SEND);
                share.setPackage(PackageApp);
                share.putExtra(Intent.EXTRA_STREAM, uri);
                share.setType("image/png");
                share.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                context.startActivity(Intent.createChooser(share, "Share image File"));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
 */

/*
private Bitmap drawTextToBitmap(Context mContext, String text) {

            int textLength = text.length();
            int MAX_CHARCTER_IN_LINE = 60; //Text character count in one line

            DisplayMetrics displayMetrics = new DisplayMetrics();
            ((WindowManager) itemView.getContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(displayMetrics);
            //int height = displayMetrics.heightPixels;
            int width = displayMetrics.widthPixels;

            float text_x = width-40; //Image width taken in consideration
            float text_y = 500; //Image height taken in consideration
            double THRESHOLD_DIP = 30.0;

            final float scale = mContext.getResources().getDisplayMetrics().density;

            int mThreshold = (int) (THRESHOLD_DIP * scale + 0.5f);

            String[] splited = text.split("\\s+");
            double longest = 0;
            for (String s : splited) {
                if (s.length() > longest) {
                    longest = s.length();
                }
            }
            if (longest > MAX_STRING_LENGTH) {
                double ratio = (double) MAX_STRING_LENGTH / longest;
                mThreshold = (int) ((THRESHOLD_DIP * ((float) ratio)) * scale + 0.5f);
            }

            int noOfLines = Math.abs(textLength/MAX_CHARCTER_IN_LINE);
            for (int i=0; i<noOfLines; i++) {
                if(text_y > 130)
                    text_y -= 30;
            }

            //Bitmap bitmap = Bitmap.createBitmap(1024, 1024, Bitmap.Config.ARGB_8888);
            BitmapFactory.Options options = new BitmapFactory.Options();
            Bitmap bitmap = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.image);
            android.graphics.Bitmap.Config bitmapConfig = bitmap.getConfig();
            if (bitmapConfig == null) {
                bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
            }
            bitmap = bitmap.copy(bitmapConfig, true);

            Canvas canvas = new Canvas(bitmap);

            TextPaint mTextPaint = new TextPaint();
            mTextPaint.setColor(Color.WHITE);
            mTextPaint.setTextAlign(Paint.Align.CENTER);
            mTextPaint.setTextSize(mThreshold);
            StaticLayout mTextLayout = new StaticLayout(text, mTextPaint, canvas.getWidth()-40, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);

            canvas.save();

            canvas.translate(text_x, text_y);
            mTextLayout.draw(canvas);
            canvas.restore();

            return bitmap;
        }

        private void createDirectoryAndSaveFile(Context context, Bitmap imageToSave, String fileName, String PackageApp) {

            File direct = new File(Environment.getExternalStorageDirectory() + "/DirName");

            if (!direct.exists()) {
                File wallpaperDirectory = new File("/sdcard/DirName/");
                wallpaperDirectory.mkdirs();
            }

            File file = new File(new File("/sdcard/DirName/"), fileName + ".jpg");
            if (file.exists()) {
                file.delete();
            }
            try {
                FileOutputStream out = new FileOutputStream(file);
                imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
                out.flush();
                out.close();
                Uri uri = Uri.parse("file://" + file.getAbsolutePath());
                Intent share = new Intent(Intent.ACTION_SEND);
                share.setPackage(PackageApp);
                share.putExtra(Intent.EXTRA_STREAM, uri);
                share.setType("image/png");
                share.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                context.startActivity(Intent.createChooser(share, "Share image File"));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
 */

/*
private void shareImage() {
            AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(itemView.getContext());
            LayoutInflater inflater = (LayoutInflater) itemView.getContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE );
            View dialogView = inflater.inflate(R.layout.custom_dialog_share_image, null);
            dialogBuilder.setView(dialogView);

            AlertDialog b = dialogBuilder.create();
            DisplayMetrics displayMetrics = new DisplayMetrics();
            ((WindowManager)itemView.getContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(displayMetrics);
            int height = displayMetrics.heightPixels;
            int width = displayMetrics.widthPixels;
            b.getWindow().setLayout(width, 110);
            b.show();

            ImageView facebook = (ImageView) dialogView.findViewById(R.id.facebook);
            ImageView twitter = (ImageView) dialogView.findViewById(R.id.twitter);
            ImageView linkIn = (ImageView) dialogView.findViewById(R.id.linkIn);
            ImageView Instagram = (ImageView) dialogView.findViewById(R.id.instagram);
            ImageView pinist = (ImageView) dialogView.findViewById(R.id.pinest);
            ImageView tumber = (ImageView) dialogView.findViewById(R.id.tumber);
            ImageView more = (ImageView) dialogView.findViewById(R.id.more);

            facebook.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (ActivityUtils.deleteAudioFile(itemView.getContext())){
                        createDirectoryAndSaveFile(itemView.getContext(), bmp, "HelloAndroid", "com.facebook.katana");
                    }

                    b.cancel();
                }
            });

            twitter.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (ActivityUtils.deleteAudioFile(itemView.getContext())){
                        createDirectoryAndSaveFile(itemView.getContext(),bmp, "HelloAndroid", "com.twitter.android");
                    }

                    b.cancel();
                }
            });

            linkIn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (ActivityUtils.deleteAudioFile(itemView.getContext())){
                        createDirectoryAndSaveFile(itemView.getContext(),bmp, "HelloAndroid", "com.linkedin.android");
                    }

                    b.cancel();
                }
            });

            Instagram.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (ActivityUtils.deleteAudioFile(itemView.getContext())){
                        createDirectoryAndSaveFile(itemView.getContext(),bmp, "HelloAndroid", "com.instagram.android");
                    }

                    b.cancel();
                }
            });

            pinist.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (ActivityUtils.deleteAudioFile(itemView.getContext())){
                        createDirectoryAndSaveFile(itemView.getContext(),bmp, "HelloAndroid", "com.pinterest");
                    }

                    b.cancel();
                }
            });
            tumber.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (ActivityUtils.deleteAudioFile(itemView.getContext())){
                        createDirectoryAndSaveFile(itemView.getContext(),bmp, "HelloAndroid", "com.tumblr");
                    }

                    b.cancel();
                }
            });
            more.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    v.getContext().startActivity(Intent.createChooser(sharedIntentMaker(), "Choose an app"));

                    b.cancel();
                }
            });
        }

        private Intent sharedIntentMaker() {
            String sharebody = String.valueOf(dataItem.getUser_name_random() + " " + "said:"
                    + " " + dataItem.getTextStatus() + " " + "inside Voiceme Android App. " +
                    "You can download from www.beacandid.com/candid?Post=" + dataItem.getIdPosts() + "");
            Intent shareIntent = new Intent();
            shareIntent.setAction(Intent.ACTION_SEND);
            shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
            shareIntent.setType("text/plain");
            shareIntent.putExtra(Intent.EXTRA_TEXT, sharebody);
            return shareIntent;
        }
 */
}


text:
<?php

require_once 'PhpDocumentor/phpDocumentor/Errors.inc';

/**
 * Phing subclass of the ErrorTracker class provided with PhpDocumentor to work around limitations in PhpDocumentor API.
 *
 * This class is necessary because PhpDocumentor does directly output errors and
 * warnings occured during testing for undocumented elements to stdout.
 * This class is injected globally to force PhpDocumentor to use phing's logging
 * mechanism.
 *
 * Obviously this is far from ideal, but there's also no solution given the inflexibility of the
 * PhpDocumentor design.
 *
 * @author Timo A. Hummel <privat@timohummel.com> @author felicitus
 * @version $Id: 73c919ab2044bf6582f52bd7ccb0184019d52f53 $
 * @package phing.tasks.ext.phpdoc
 */
class PhingPhpDocumentorErrorTracker extends ErrorTracker {

	/*
	 * @var object	Reference to the task we're called with
	 */
	private $task;

	/**
	 * Outputs a warning. This is an almost 1:1 copy from PhpDocumentor,
	 * we're just processing the warning text and send it to phing's logger.
	 *
	 * @param $num integer	Number of parameters
	 * @return nothing
	 */
	function addWarning ($num) {
        $a = array('', '', '', '');
        if (func_num_args()>1) {
            for ($i=1;$i<func_num_args();$i++) {
                $a[$i - 1] = func_get_arg($i);
            }
        }

       $message = sprintf($GLOBALS['phpDocumentor_warning_descrip'][$num], $a[0], $a[1], $a[2], $a[3]);
       $this->task->log($message, Project::MSG_WARN);

	}

	/**
	 * Outputs an error. This is an almost 1:1 copy from PhpDocumentor,
	 * we're just processing the error text and send it to phing's logger.
	 *
	 * @param $num integer	Number of parameters
	 * @return nothing
	 */

	function addError ($num) {
        $a = array('', '', '', '');
        if (func_num_args()>1) {
            for ($i=1;$i<func_num_args();$i++) {
                $a[$i - 1] = func_get_arg($i);
            }
        }

       $message = sprintf($GLOBALS['phpDocumentor_error_descrip'][$num], $a[0], $a[1], $a[2], $a[3]);
       $this->task->log($message, Project::MSG_ERR);

	}

	/**
	 * Sets the task we're working with. This is necessary since we need to be
	 * able to call the method "log".
	 *
	 * @param object $task	The task we're working with
	 * @return nothing
	 */
	public function setTask ($task) {
		$this->task = $task;
	}

}


text:
<!DOCTYPE html>

    <title>Passive mixed content example</title>

        Passive mixed content!

        View page over: HTTP - HTTPS

        Several examples of passive mixed content. When viewed over HTTPS most browsers do not block this content but instead display warnings in the JavaScript console.

      <audio src="http://googlesamples.github.io/web-fundamentals/samples/discovery-and-distribution/avoid-mixed-content/symphony-5-beethoven.mp3" type="audio/mp3" controls></audio>

      <video src="http://developers.google.com/web/fundamentals/media/video/video/chrome.webm" type="video/webm" controls></video>


text:
<?php

namespace Flarum\Database;

use Flarum\Extension\Extension;
use Illuminate\Filesystem\Filesystem;

class MigrationCreator
{
    /**
     * The filesystem instance.
     *
     * @var Filesystem
     */
    protected $files;

    /**
     * @var string
     */
    protected $publicPath;

    /**
     * Create a new migrator instance.
     *
     * @param Filesystem $files
     * @param string $publicPath
     */
    public function __construct(Filesystem $files, $publicPath)
    {
        $this->files = $files;
        $this->publicPath = $publicPath;
    }

    /**
     * Create a new migration for the given extension.
     *
     * @param string $name
     * @param Extension $extension
     * @param string $table
     * @param bool $create
     * @return string
     */
    public function create($name, $extension = null, $table = null, $create = false)
    {
        $migrationPath = $this->getMigrationPath($extension);

        $path = $this->getPath($name, $migrationPath);

        $stub = $this->getStub($table, $create);

        $this->files->put($path, $this->populateStub($stub, $table));

        return $path;
    }

    /**
     * Get the migration stub file.
     *
     * @param string $table
     * @param bool $create
     * @return string
     */
    protected function getStub($table, $create)
    {
        if (is_null($table)) {
            return $this->files->get($this->getStubPath().'/blank.stub');
        }

        // We also have stubs for creating new tables and modifying existing tables
        // to save the developer some typing when they are creating a new tables
        // or modifying existing tables. We'll grab the appropriate stub here.
        $stub = $create ? 'create.stub' : 'update.stub';

        return $this->files->get($this->getStubPath()."/{$stub}");
    }

    /**
     * Populate the place-holders in the migration stub.
     *
     * @param string $stub
     * @param string $table
     * @return string
     */
    protected function populateStub($stub, $table)
    {
        $replacements = [
            '{{table}}' => $table
        ];

        return str_replace(array_keys($replacements), array_values($replacements), $stub);
    }

    /**
     * Get the full path name to the migration directory.
     *
     * @param string $extension
     * @return string
     */
    protected function getMigrationPath($extension)
    {
        $parent = $extension ? public_path().'/extensions/'.$extension : __DIR__.'/../..';

        return $parent.'/migrations';
    }

    /**
     * Get the full path name to the migration.
     *
     * @param string $name
     * @param string $path
     * @return string
     */
    protected function getPath($name, $path)
    {
        return $path.'/'.$this->getDatePrefix().'_'.$name.'.php';
    }

    /**
     * Get the date prefix for the migration.
     *
     * @return string
     */
    protected function getDatePrefix()
    {
        return date('Y_m_d_His');
    }

    /**
     * Get the path to the stubs.
     *
     * @return string
     */
    protected function getStubPath()
    {
        return __DIR__.'/../../stubs/migrations';
    }
}


text:
var combinedReducers = require('./reducers');

module.exports = combinedReducers;


text:
package encryptedcookiespb

import (
	protoreflect "google.golang.org/protobuf/reflect/protoreflect"
	protoimpl "google.golang.org/protobuf/runtime/protoimpl"
	reflect "reflect"
	sync "sync"
)

const (
	// Verify that this generated code is sufficiently up-to-date.
	_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
	// Verify that runtime/protoimpl is sufficiently up-to-date.
	_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)

// SessionCookie is a clear-text representation of a session cookie.
//
// It contains the session ID and the per-session keyset used to encrypt the
// sensitive part of the session stored in the Private proto.
type SessionCookie struct {
	state         protoimpl.MessageState
	sizeCache     protoimpl.SizeCache
	unknownFields protoimpl.UnknownFields

	SessionId []byte `protobuf:"bytes,1,opt,name=session_id,json=sessionId,proto3" json:"session_id,omitempty"`
	Keyset    []byte `protobuf:"bytes,2,opt,name=keyset,proto3" json:"keyset,omitempty"` // serialized google.crypto.tink.Keyset with AEAD keys
}

func (x *SessionCookie) Reset() {
	*x = SessionCookie{}
	if protoimpl.UnsafeEnabled {
		mi := &file_go_chromium_org_luci_server_encryptedcookies_internal_encryptedcookiespb_cookie_proto_msgTypes[0]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}

func (x *SessionCookie) String() string {
	return protoimpl.X.MessageStringOf(x)
}

func (*SessionCookie) ProtoMessage() {}

func (x *SessionCookie) ProtoReflect() protoreflect.Message {
	mi := &file_go_chromium_org_luci_server_encryptedcookies_internal_encryptedcookiespb_cookie_proto_msgTypes[0]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}

// Deprecated: Use SessionCookie.ProtoReflect.Descriptor instead.
func (*SessionCookie) Descriptor() ([]byte, []int) {
	return file_go_chromium_org_luci_server_encryptedcookies_internal_encryptedcookiespb_cookie_proto_rawDescGZIP(), []int{0}
}

func (x *SessionCookie) GetSessionId() []byte {
	if x != nil {
		return x.SessionId
	}
	return nil
}

func (x *SessionCookie) GetKeyset() []byte {
	if x != nil {
		return x.Keyset
	}
	return nil
}

var File_go_chromium_org_luci_server_encryptedcookies_internal_encryptedcookiespb_cookie_proto protoreflect.FileDescriptor

var file_go_chromium_org_luci_server_encryptedcookies_internal_encryptedcookiespb_cookie_proto_rawDesc = []byte{
	0x0a, 0x55, 0x67, 0x6f, 0x2e, 0x63, 0x68, 0x72, 0x6f, 0x6d, 0x69, 0x75, 0x6d, 0x2e, 0x6f, 0x72,
	0x67, 0x2f, 0x6c, 0x75, 0x63, 0x69, 0x2f, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x2f, 0x65, 0x6e,
	0x63, 0x72, 0x79, 0x70, 0x74, 0x65, 0x64, 0x63, 0x6f, 0x6f, 0x6b, 0x69, 0x65, 0x73, 0x2f, 0x69,
	0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x2f, 0x65, 0x6e, 0x63, 0x72, 0x79, 0x70, 0x74, 0x65,
	0x64, 0x63, 0x6f, 0x6f, 0x6b, 0x69, 0x65, 0x73, 0x70, 0x62, 0x2f, 0x63, 0x6f, 0x6f, 0x6b, 0x69,
	0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x1c, 0x6c, 0x75, 0x63, 0x69, 0x2e, 0x73, 0x65,
	0x72, 0x76, 0x65, 0x72, 0x2e, 0x65, 0x6e, 0x63, 0x72, 0x79, 0x70, 0x74, 0x65, 0x64, 0x63, 0x6f,
	0x6f, 0x6b, 0x69, 0x65, 0x73, 0x22, 0x46, 0x0a, 0x0d, 0x53, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e,
	0x43, 0x6f, 0x6f, 0x6b, 0x69, 0x65, 0x12, 0x1d, 0x0a, 0x0a, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f,
	0x6e, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x09, 0x73, 0x65, 0x73, 0x73,
	0x69, 0x6f, 0x6e, 0x49, 0x64, 0x12, 0x16, 0x0a, 0x06, 0x6b, 0x65, 0x79, 0x73, 0x65, 0x74, 0x18,
	0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x06, 0x6b, 0x65, 0x79, 0x73, 0x65, 0x74, 0x42, 0x4a, 0x5a,
	0x48, 0x67, 0x6f, 0x2e, 0x63, 0x68, 0x72, 0x6f, 0x6d, 0x69, 0x75, 0x6d, 0x2e, 0x6f, 0x72, 0x67,
	0x2f, 0x6c, 0x75, 0x63, 0x69, 0x2f, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x2f, 0x65, 0x6e, 0x63,
	0x72, 0x79, 0x70, 0x74, 0x65, 0x64, 0x63, 0x6f, 0x6f, 0x6b, 0x69, 0x65, 0x73, 0x2f, 0x69, 0x6e,
	0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x2f, 0x65, 0x6e, 0x63, 0x72, 0x79, 0x70, 0x74, 0x65, 0x64,
	0x63, 0x6f, 0x6f, 0x6b, 0x69, 0x65, 0x73, 0x70, 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f,
	0x33,
}

var (
	file_go_chromium_org_luci_server_encryptedcookies_internal_encryptedcookiespb_cookie_proto_rawDescOnce sync.Once
	file_go_chromium_org_luci_server_encryptedcookies_internal_encryptedcookiespb_cookie_proto_rawDescData = file_go_chromium_org_luci_server_encryptedcookies_internal_encryptedcookiespb_cookie_proto_rawDesc
)

func file_go_chromium_org_luci_server_encryptedcookies_internal_encryptedcookiespb_cookie_proto_rawDescGZIP() []byte {
	file_go_chromium_org_luci_server_encryptedcookies_internal_encryptedcookiespb_cookie_proto_rawDescOnce.Do(func() {
		file_go_chromium_org_luci_server_encryptedcookies_internal_encryptedcookiespb_cookie_proto_rawDescData = protoimpl.X.CompressGZIP(file_go_chromium_org_luci_server_encryptedcookies_internal_encryptedcookiespb_cookie_proto_rawDescData)
	})
	return file_go_chromium_org_luci_server_encryptedcookies_internal_encryptedcookiespb_cookie_proto_rawDescData
}

var file_go_chromium_org_luci_server_encryptedcookies_internal_encryptedcookiespb_cookie_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
var file_go_chromium_org_luci_server_encryptedcookies_internal_encryptedcookiespb_cookie_proto_goTypes = []interface{}{
	(*SessionCookie)(nil), // 0: luci.server.encryptedcookies.SessionCookie
}
var file_go_chromium_org_luci_server_encryptedcookies_internal_encryptedcookiespb_cookie_proto_depIdxs = []int32{
	0, // [0:0] is the sub-list for method output_type
	0, // [0:0] is the sub-list for method input_type
	0, // [0:0] is the sub-list for extension type_name
	0, // [0:0] is the sub-list for extension extendee
	0, // [0:0] is the sub-list for field type_name
}

func init() {
	file_go_chromium_org_luci_server_encryptedcookies_internal_encryptedcookiespb_cookie_proto_init()
}
func file_go_chromium_org_luci_server_encryptedcookies_internal_encryptedcookiespb_cookie_proto_init() {
	if File_go_chromium_org_luci_server_encryptedcookies_internal_encryptedcookiespb_cookie_proto != nil {
		return
	}
	if !protoimpl.UnsafeEnabled {
		file_go_chromium_org_luci_server_encryptedcookies_internal_encryptedcookiespb_cookie_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
			switch v := v.(*SessionCookie); i {
			case 0:
				return &v.state
			case 1:
				return &v.sizeCache
			case 2:
				return &v.unknownFields
			default:
				return nil
			}
		}
	}
	type x struct{}
	out := protoimpl.TypeBuilder{
		File: protoimpl.DescBuilder{
			GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
			RawDescriptor: file_go_chromium_org_luci_server_encryptedcookies_internal_encryptedcookiespb_cookie_proto_rawDesc,
			NumEnums:      0,
			NumMessages:   1,
			NumExtensions: 0,
			NumServices:   0,
		},
		GoTypes:           file_go_chromium_org_luci_server_encryptedcookies_internal_encryptedcookiespb_cookie_proto_goTypes,
		DependencyIndexes: file_go_chromium_org_luci_server_encryptedcookies_internal_encryptedcookiespb_cookie_proto_depIdxs,
		MessageInfos:      file_go_chromium_org_luci_server_encryptedcookies_internal_encryptedcookiespb_cookie_proto_msgTypes,
	}.Build()
	File_go_chromium_org_luci_server_encryptedcookies_internal_encryptedcookiespb_cookie_proto = out.File
	file_go_chromium_org_luci_server_encryptedcookies_internal_encryptedcookiespb_cookie_proto_rawDesc = nil
	file_go_chromium_org_luci_server_encryptedcookies_internal_encryptedcookiespb_cookie_proto_goTypes = nil
	file_go_chromium_org_luci_server_encryptedcookies_internal_encryptedcookiespb_cookie_proto_depIdxs = nil
}


text:
angular.module('job')
  .controller('ConfirmIconController', [
    '$scope', '$modal', '$modalInstance', 'object',
    function ($scope, $modal, $modalInstance, object) {
      $scope.image = object.image;
      $scope.type = object.type;

      $scope.replaceUrl = function (url) {
        return url.replace('url("', '').replace('")', '');
      };

      $scope.ok = function () {
        $modalInstance.close();
      };

      $scope.close = function () {
        $modalInstance.dismiss();
      };
    }]);


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

		<title>iWader</title>
		<meta http-equiv="content-type" content="application/xhtml+xml; charset=UTF-8" />
		<link rel="stylesheet" href="/static/style.css" type="text/css" media="all" />

				iWader

Insert Slogan Here

			<form id="quick-search" action="#" method="get">

					Search:
					<input class="tbox" id="query" type="text" name="query" value="Search..." onclick="this.value='';" onblur="this.value='Search...';" title="Start typing what you want to search for" />
					<input class="btn" alt="Search" type="image" name="searchsubmit" title="Search" src="/static/img/search.png" />

			</form>

<?php require(ABSPATH . TEMPLATES_PATH . 'Default/resources/nav.php'); ?>


text:
import { Component, OnInit, Input } from '@angular/core';
import { Villain } from '../shared'

@Component({
  selector: 'vil-villain-edit',
  templateUrl: './villain-edit.component.html',
  styleUrls: ['./villain-edit.component.css']
})
export class VillainEditComponent implements OnInit {

  @Input()
  villain: Villain;

  constructor() { }

  ngOnInit() {
  }

}


text:
package org.apache.beam.sdk.io.gcp.datastore;

import java.io.IOException;
import java.io.Serializable;
import org.apache.beam.sdk.metrics.Counter;
import org.apache.beam.sdk.metrics.Metrics;
import org.apache.beam.sdk.options.ValueProvider;
import org.apache.beam.sdk.options.ValueProvider.StaticValueProvider;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.Sum;
import org.apache.beam.sdk.transforms.display.DisplayData;
import org.apache.beam.sdk.util.BackOff;
import org.apache.beam.sdk.util.FluentBackoff;
import org.apache.beam.sdk.util.MovingFunction;
import org.apache.beam.sdk.util.Sleeper;
import org.apache.beam.sdk.values.PCollectionView;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.annotations.VisibleForTesting;
import org.joda.time.Duration;
import org.joda.time.Instant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * An implementation of a client-side throttler that enforces a gradual ramp-up, broadly in line
 * with Datastore best practices. See also
 * https://cloud.google.com/datastore/docs/best-practices#ramping_up_traffic.
 */
public class RampupThrottlingFn<T> extends DoFn<T, T> implements Serializable {

  private static final Logger LOG = LoggerFactory.getLogger(RampupThrottlingFn.class);
  private static final double BASE_BUDGET = 500.0;
  private static final Duration RAMP_UP_INTERVAL = Duration.standardMinutes(5);
  private static final FluentBackoff fluentBackoff = FluentBackoff.DEFAULT;

  private final ValueProvider<Integer> numWorkers;
  private final PCollectionView<Instant> firstInstantSideInput;

  @VisibleForTesting
  Counter throttlingMsecs = Metrics.counter(RampupThrottlingFn.class, "throttling-msecs");

  // Initialized on every setup.
  private transient MovingFunction successfulOps;

  @VisibleForTesting transient Sleeper sleeper;

  public RampupThrottlingFn(
      ValueProvider<Integer> numWorkers, PCollectionView<Instant> firstInstantSideInput) {
    this.numWorkers = numWorkers;
    this.sleeper = Sleeper.DEFAULT;
    this.successfulOps =
        new MovingFunction(
            Duration.standardSeconds(1).getMillis(),
            Duration.standardSeconds(1).getMillis(),
            1 /* numSignificantBuckets */,
            1 /* numSignificantSamples */,
            Sum.ofLongs());
    this.firstInstantSideInput = firstInstantSideInput;
  }

  public RampupThrottlingFn(int numWorkers, PCollectionView<Instant> timestampSideInput) {
    this(StaticValueProvider.of(numWorkers), timestampSideInput);
  }

  // 500 / numWorkers * 1.5^max(0, (x-5)/5), or "+50% every 5 minutes"
  private int calcMaxOpsBudget(Instant first, Instant instant, int hintNumWorkers) {
    double rampUpIntervalMinutes = (double) RAMP_UP_INTERVAL.getStandardMinutes();
    Duration durationSinceFirst = new Duration(first, instant);

    double calculatedGrowth =
        (durationSinceFirst.getStandardMinutes() - rampUpIntervalMinutes) / rampUpIntervalMinutes;
    double growth = Math.max(0, calculatedGrowth);
    double maxOpsBudget = BASE_BUDGET / hintNumWorkers * Math.pow(1.5, growth);
    return (int) Math.min(Integer.MAX_VALUE, Math.max(1, maxOpsBudget));
  }

  @Setup
  public void setup() {
    this.sleeper = Sleeper.DEFAULT;
    this.successfulOps =
        new MovingFunction(
            Duration.standardSeconds(1).getMillis(),
            Duration.standardSeconds(1).getMillis(),
            1 /* numSignificantBuckets */,
            1 /* numSignificantSamples */,
            Sum.ofLongs());
  }

  /** Emit only as many elements as the exponentially increasing budget allows. */
  @ProcessElement
  public void processElement(ProcessContext c) throws IOException, InterruptedException {
    Instant firstInstant = c.sideInput(firstInstantSideInput);

    T element = c.element();
    BackOff backoff = fluentBackoff.backoff();
    while (true) {
      Instant instant = Instant.now();
      int maxOpsBudget = calcMaxOpsBudget(firstInstant, instant, this.numWorkers.get());
      long currentOpCount = successfulOps.get(instant.getMillis());
      long availableOps = maxOpsBudget - currentOpCount;

      if (maxOpsBudget >= Integer.MAX_VALUE || availableOps > 0) {
        c.output(element);
        successfulOps.add(instant.getMillis(), 1);
        return;
      }

      long backoffMillis = backoff.nextBackOffMillis();
      LOG.info("Delaying by {}ms to conform to gradual ramp-up.", backoffMillis);
      throttlingMsecs.inc(backoffMillis);
      sleeper.sleep(backoffMillis);
    }
  }

  @Override
  public void populateDisplayData(DisplayData.Builder builder) {
    builder.add(
        DisplayData.item("hintNumWorkers", numWorkers)
            .withLabel("Number of workers for ramp-up throttling algorithm"));
  }
}


text:
package io.vertx.ext.hawkular.impl;

import io.vertx.core.net.SocketAddress;
import io.vertx.core.net.impl.SocketAddressImpl;
import io.vertx.core.spi.metrics.DatagramSocketMetrics;

import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.LongAdder;

import static java.util.stream.Collectors.*;

/**
 * Implementation of {@link DatagramSocketMetrics} which relays data to {@link DatagramSocketMetricsSupplier}.
 *
 * @author Thomas Segismont
 */
public class DatagramSocketMetricsImpl implements DatagramSocketMetrics {
  private final ConcurrentMap<SocketAddress, LongAdder> bytesReceived = new ConcurrentHashMap<>(0);
  private final ConcurrentMap<SocketAddress, LongAdder> bytesSent = new ConcurrentHashMap<>(0);
  private final LongAdder errors = new LongAdder();
  private final DatagramSocketMetricsSupplier datagramSocketMetricsSupplier;

  private volatile SocketAddress localAddress;

  public DatagramSocketMetricsImpl(DatagramSocketMetricsSupplier datagramSocketMetricsSupplier) {
    this.datagramSocketMetricsSupplier = datagramSocketMetricsSupplier;
    datagramSocketMetricsSupplier.register(this);
  }

  @Override
  public void listening(String localName, SocketAddress localAddress) {
    this.localAddress = new SocketAddressImpl(localAddress.port(), localName);
  }

  @Override
  public void bytesRead(Void socketMetric, SocketAddress remoteAddress, long numberOfBytes) {
    LongAdder counter = bytesReceived.get(localAddress);
    if (counter == null) {
      counter = bytesReceived.computeIfAbsent(localAddress, address -> new LongAdder());
    }
    counter.add(numberOfBytes);
  }

  @Override
  public void bytesWritten(Void socketMetric, SocketAddress remoteAddress, long numberOfBytes) {
    LongAdder counter = bytesSent.get(remoteAddress);
    if (counter == null) {
      counter = bytesSent.computeIfAbsent(remoteAddress, address -> new LongAdder());
    }
    counter.add(numberOfBytes);
  }

  @Override
  public void exceptionOccurred(Void socketMetric, SocketAddress remoteAddress, Throwable t) {
    errors.increment();
  }

  /**
   * @return bytes received per remote {@link SocketAddress}
   */
  public Map<SocketAddress, Long> getBytesReceived() {
    return bytesReceived.entrySet().stream().collect(toMap(Entry::getKey, e -> e.getValue().sum()));
  }

  /**
   * @return bytes sent per remote {@link SocketAddress}
   */
  public Map<SocketAddress, Long> getBytesSent() {
    return bytesSent.entrySet().stream().collect(toMap(Entry::getKey, e -> e.getValue().sum()));
  }

  public long getErrorCount() {
    return errors.sum();
  }

  @Override
  public boolean isEnabled() {
    return true;
  }

  @Override
  public void close() {
    datagramSocketMetricsSupplier.unregister(this);
  }
}


text:
require 'spec_helper'

describe DataMapper::Property::Integer do
  before :all do
    @name          = :age
    @type          = described_class
    @load_as       = Integer
    @dump_as       = Integer
    @value         = 1
    @other_value   = 2
    @invalid_value = '1'
  end

  it_should_behave_like 'A public Property'

  describe '.options' do
    subject { described_class.options }

    it { should be_kind_of(Hash) }

    it { should eql(:load_as => @load_as, :dump_as => @load_as) }
  end
end


text:
package almhirt.eventlog

import akka.actor._
import scalaz.syntax.validation._
import almhirt.common._
import almhirt.almvalidation.kit._
import play.api.libs.iteratee.Enumerator
import almhirt.aggregates.{ AggregateRootId, AggregateRootVersion }

object AggregateRootEventLog {
  trait AggregateRootEventLogMessage
  trait AggregateRootEventLogQueryManyMessage extends AggregateRootEventLogMessage { def traverse: TraverseWindow }
  trait AggregateRootEventLogResponse

  sealed trait VersionRangeStartMarker
  final case class FromVersion(version: AggregateRootVersion) extends VersionRangeStartMarker
  final case object FromStart extends VersionRangeStartMarker

  object VersionRangeStartMarker {
    def fromLongOption(v: Option[Long]): VersionRangeStartMarker =
      v match {
        case Some(v) if v >= 0 ⇒ FromVersion(AggregateRootVersion(v))
        case _ ⇒ FromStart
      }

    def parseStringOption(v: Option[String]): AlmValidation[VersionRangeStartMarker] = {
      v match {
        case None ⇒ FromStart.success
        case Some(v) ⇒
          if (v.trim().isEmpty())
            FromStart.success
          else
            v.toLongAlm.map(v ⇒ fromLongOption(Some(v)))
      }
    }
  }

  sealed trait VersionRangeEndMarker
  final case class ToVersion(version: AggregateRootVersion) extends VersionRangeEndMarker
  final case object ToEnd extends VersionRangeEndMarker

  object VersionRangeEndMarker {
    def fromLongOption(v: Option[Long]): VersionRangeEndMarker =
      v match {
        case Some(v) if v >= 0 && v < Int.MaxValue ⇒ ToVersion(AggregateRootVersion(v))
        case Some(v) if v == Int.MaxValue ⇒ ToEnd
        case Some(v) if v < 0 ⇒ ToVersion(AggregateRootVersion(0L))
        case None ⇒ ToEnd
      }

    def parseStringOption(v: Option[String]): AlmValidation[VersionRangeEndMarker] = {
      v match {
        case None ⇒ ToEnd.success
        case Some(v) ⇒
          if (v.trim().isEmpty())
            ToEnd.success
          else
            v.toLongAlm.map(v ⇒ fromLongOption(Some(v)))
      }
    }
  }

  final case class CommitAggregateRootEvent(event: AggregateRootEvent) extends AggregateRootEventLogMessage
  sealed trait CommitAggregateRootEventResponse extends AggregateRootEventLogResponse
  final case class AggregateRootEventCommitted(id: EventId) extends CommitAggregateRootEventResponse
  final case class AggregateRootEventNotCommitted(id: EventId, problem: Problem) extends CommitAggregateRootEventResponse

  final case class GetAllAggregateRootEvents(traverse: TraverseWindow) extends AggregateRootEventLogQueryManyMessage
  final case class GetAggregateRootEventsFor(aggId: AggregateRootId, start: VersionRangeStartMarker, end: VersionRangeEndMarker, traverse: TraverseWindow) extends AggregateRootEventLogQueryManyMessage
  object GetAllAggregateRootEventsFor {
    def apply(aggId: AggregateRootId, traverse: TraverseWindow): GetAggregateRootEventsFor =
      GetAggregateRootEventsFor(aggId, FromStart, ToEnd, traverse)
    def apply(aggId: AggregateRootId): GetAggregateRootEventsFor =
      GetAggregateRootEventsFor(aggId, FromStart, ToEnd, skip.none.takeAll)
  }
  object GetAggregateRootEventsFrom {
    def apply(aggId: AggregateRootId, from: AggregateRootVersion, traverse: TraverseWindow): GetAggregateRootEventsFor =
      GetAggregateRootEventsFor(aggId, FromVersion(from), ToEnd, traverse)
    def apply(aggId: AggregateRootId, from: AggregateRootVersion): GetAggregateRootEventsFor =
      GetAggregateRootEventsFor(aggId, FromVersion(from), ToEnd, skip.none.takeAll)
  }
  sealed trait GetManyAggregateRootEventsResponse extends AggregateRootEventLogResponse
  final case class FetchedAggregateRootEvents(enumerator: Enumerator[AggregateRootEvent]) extends GetManyAggregateRootEventsResponse
  final case class GetAggregateRootEventsFailed(problem: Problem) extends GetManyAggregateRootEventsResponse

  final case class GetAggregateRootEvent(eventId: EventId) extends AggregateRootEventLogMessage
  sealed trait GetAggregateRootEventResponse extends AggregateRootEventLogResponse
  final case class FetchedAggregateRootEvent(eventId: EventId, event: Option[AggregateRootEvent]) extends GetAggregateRootEventResponse
  final case class GetAggregateRootEventFailed(eventId: EventId, problem: Problem) extends GetAggregateRootEventResponse

  val actorname = "aggregate-event-log"
  def path(root: RootActorPath) = almhirt.context.ContextActorPaths.eventLogs(root) / actorname
}


text:
<?php

namespace App\Commands;

use Symfony\Component\Console\Command\Command;

class RootCommand extends Command
{
    /**
     * @return \Doctrine\DBAL\Connection
     */
    public function database()
    {
        $db = $this->getApplication()->getService('db');

        return $db;
    }
}


text:
import assert from 'assert';
import React from 'react';

import translate from './translate';

describe('translate HOC', () => {
    it('should conserve base component default props', () => {
        const Component = () => <div />;
        Component.defaultProps = { foo: 'bar' };

        const TranslatedComponent = translate(Component);
        assert.deepEqual(TranslatedComponent.defaultProps, { foo: 'bar' });
    });
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MetroRadiance.Controls
{
	public interface ITabItem
	{
		string Name { get; }
		int? Badge { get; }
		bool IsSelected { get; set; }
	}
}


text:
using System;
using System.Runtime.InteropServices;

// ReSharper disable once CheckNamespace
namespace Xamarin.OpenCV
{

    internal sealed partial class NativeMethods
    {

        #region Fields

#if Android
    const string NativeLibrary = "libOpenCVWrapper.so";
#else
        const string NativeLibrary = "__Internal";
#endif

        [DllImport(NativeLibrary)]
        public static extern IntPtr opencv_get_version();

        [DllImport(NativeLibrary)]
        public static extern IntPtr opencv_getBuildInformation();

        [DllImport(NativeLibrary)]
        public static extern IntPtr string_c_str(IntPtr str);

        [DllImport(NativeLibrary)]
        public static extern void string_delete(IntPtr str);

        #endregion

    }

}


text:
/**
 * ArrayParameter.hpp -
 * @author: Jonathan Beard
 * @version: Thu Jan 23 12:01:22 2014
 */
#ifndef _ARRAYPARAMETER_HPP_
#define _ARRAYPARAMETER_HPP_  1

#include "Parameter.hpp"
namespace Node {
class ArrayParameter : public Parameter {
public:
   ArrayParameter();
   virtual ~ArrayParameter() = default;
};
}
#endif /* END _ARRAYPARAMETER_HPP_ */


text:
'use strict';

function LearnCtrl() {

}

module.exports = LearnCtrl;


text:
using System;

namespace Platform.Support
{
#if PORTABLE

    namespace Core
    {
#endif

    public static partial class Math
    {
        public const float RadianPI = 57.29578f; // 180.0 / Math.PI
        public const float DegreePI = 0.01745329f; // Math.PI / 180.0
        public const float TwoPI = 6.28319f; // Math.PI * 2

        private static readonly object randomLock = new object();
        private static readonly Random random = new Random();

        public static int Random(int max)
        {
            lock (randomLock)
                return random.Next(max + 1);
        }

        public static int Random(int min, int max)
        {
            lock (randomLock)
                return random.Next(min, max + 1);
        }

        public static float RadianToDegree(float radian)
        {
            return radian * RadianPI;
        }

        public static float DegreeToRadian(float degree)
        {
            return degree * DegreePI;
        }

        public static Vector2 RadianToVector2(float radian)
        {
            return new Vector2((float)System.Math.Cos(radian), (float)System.Math.Sin(radian));
        }

        public static Vector2 RadianToVector2(float radian, float length)
        {
            return RadianToVector2(radian) * length;
        }

        public static Vector2 DegreeToVector2(float degree)
        {
            return RadianToVector2(DegreeToRadian(degree));
        }

        public static Vector2 DegreeToVector2(float degree, float length)
        {
            return RadianToVector2(DegreeToRadian(degree), length);
        }

        public static float Vector2ToRadian(Vector2 direction)
        {
            return (float)System.Math.Atan2(direction.Y, direction.X);
        }

        public static float Vector2ToDegree(Vector2 direction)
        {
            return RadianToDegree(Vector2ToRadian(direction));
        }

        public static float LookAtRadian(Vector2 pos1, Vector2 pos2)
        {
            return (float)System.Math.Atan2(pos2.Y - pos1.Y, pos2.X - pos1.X);
        }

        public static Vector2 LookAtVector2(Vector2 pos1, Vector2 pos2)
        {
            return RadianToVector2(LookAtRadian(pos1, pos2));
        }

        public static float LookAtDegree(Vector2 pos1, Vector2 pos2)
        {
            return RadianToDegree(LookAtRadian(pos1, pos2));
        }

        public static float Distance(Vector2 pos1, Vector2 pos2)
        {
            return (float)System.Math.Sqrt(System.Math.Pow(pos2.X - pos1.X, 2) + System.Math.Pow(pos2.Y - pos1.Y, 2));
        }

        public static float Lerp(float value1, float value2, float amount)
        {
            return value1 + (value2 - value1) * amount;
        }

        public struct Vector2
        {
            private float x, y;

            public float X
            {
                get
                {
                    return x;
                }
                set
                {
                    x = value;
                }
            }

            public float Y
            {
                get
                {
                    return y;
                }
                set
                {
                    y = value;
                }
            }

            public static readonly Vector2 Empty = new Vector2();

            public Vector2(float x, float y)
            {
                this.x = x;
                this.y = y;
            }

            public override bool Equals(object obj)
            {
#if NETFX_40 || NETFX_45
                if (obj is Vector2)
                {
                    Vector2 v = (Vector2)obj;
                    return v.x == x && v.y == y;
                }
#else
                if (obj is Vector2 v)
                    return v.x == x && v.y == y;
#endif

                return false;
            }

            public override int GetHashCode()
            {
                return base.GetHashCode();
            }

            public override string ToString()
            {
                return String.Format("X={0}, Y={1}", x, y);
            }

            public static bool operator ==(Vector2 u, Vector2 v)
            {
                return u.x == v.x && u.y == v.y;
            }

            public static bool operator !=(Vector2 u, Vector2 v)
            {
                return !(u == v);
            }

            public static Vector2 operator +(Vector2 u, Vector2 v)
            {
                return new Vector2(u.x + v.x, u.y + v.y);
            }

            public static Vector2 operator -(Vector2 u, Vector2 v)
            {
                return new Vector2(u.x - v.x, u.y - v.y);
            }

            public static Vector2 operator *(Vector2 u, float a)
            {
                return new Vector2(a * u.x, a * u.y);
            }

            public static Vector2 operator /(Vector2 u, float a)
            {
                return new Vector2(u.x / a, u.y / a);
            }

            public static Vector2 operator -(Vector2 u)
            {
                return new Vector2(-u.x, -u.y);
            }

            //#if (!PORTABLE)

            //            public static explicit operator System.Drawing.Point(Vector2 u)
            //            {
            //                return new System.Drawing.Point((int)System.Math.Round(u.x), (int)System.Math.Round(u.y));
            //            }

            //            public static implicit operator Vector2(System.Drawing.Point p)
            //            {
            //                return new Vector2(p.X, p.Y);
            //            }

            //#endif
        }
    }

#if PORTABLE
    }

#endif
}


text:
/*jslint node: true */
/*global module, require*/
'use strict';

module.exports = function removeListener(listener) {
  var index = this.listeners.indexOf(listener);
  if (index > -1) {
    this.listeners.splice(index, 1);
  }
};


text:
package com.dataart.steps;

import org.junit.Assert;

import com.dataart.model.User;
import com.dataart.pages.RegistrationPage;
import com.dataart.utils.Vars;

import net.thucydides.core.annotations.Step;
import net.thucydides.core.pages.Pages;
import net.thucydides.core.steps.ScenarioSteps;
import net.thucydides.junit.annotations.Qualifier;

public class UserRegistrationSteps extends ScenarioSteps {

	public UserRegistrationSteps(Pages pages) {
		super(pages);

	}

	RegistrationPage registrationPage;

	public String firstName;
	public String middleName;
	public String lastName;
	public String email;
	public String password;
	public String passwordRepeat;
	public String role;
	public String school;

	@Qualifier
	public String getQualifier() {
		return firstName;
	}

	@Step
	public void is_on_the_registration_page() {

		registrationPage.open();
	}

	@Step
	public void enter_all_correct_credentials() {
		registrationPage.enterCredentials();
	}

	@Step
	public void click_Sign_up() {

		registrationPage.clickSignUp();
	}

	@Step
	public void user_should_see_the_E_mail_confirmation_message(String message) {
		Assert.assertEquals(registrationPage.getConfirmationMessage(), message);

	}

	@Step
	public void user_should_see_the_warrning_messages_about_blank_fields(
			int numbers) {
		Assert.assertEquals(numbers,registrationPage.getNumberOfWarrnings());

	}

	@Step
	public void user_should_see_the_Resend_email_button() {
		waitABit(1000);
		Assert.assertTrue(registrationPage.isResendButtonExist());
	}

	@Step
	public void enter_all_correct_credentials_form_file_source() {
		registrationPage.enterCredentialsFromCSV(firstName, middleName,
				lastName, email, password, passwordRepeat, role, school);
	}

	@Step
	public void enter_not_unique_credentials() {
		registrationPage.enterNotUniqueCredentials();
	}

	@Step
	public void user_should_see_DBerror_message(String message) {
		Assert.assertEquals(registrationPage.getErrorDBMessage(), message);

	}

	@Step
	public void user_enter_all_correct_credentials(String role) {
		registrationPage.userEnterAllCorrectCredentials(role);
	}

	@Step
	public void user_check_his_emailbox_and_click_on_the_confirmation_link(
			String email, String password) {
		registrationPage.checkGmailAndGetLink(email, password);
	}

	@Step
	public void user_should_see_the_verified_Email_confirmation_message(
			String message) {
		Assert.assertEquals(registrationPage.getEmailVirifiedMessage(), message);
	}

	@Step
	public void user_click_on_go_to_login_page_link() {
		registrationPage.clickOnLoginLink();
	}

	@Step
	public void user_click_on_Resend_email_button() {
		Assert.assertTrue(registrationPage.clickResndButton());
	}
	@Step
	public void user_click_on_the_button_for_import_from_baylor_website(){
		registrationPage.clickOnBaylorButton();
	}

	@Step
	public void user_should_be_on_the_registration_page(){
		registrationPage.shouldBeDisplayed();
	}
	@Step
	public void user_should_see_that_all_fields_are_filled(String data){
		Assert.assertEquals(data,registrationPage.getEmailFromField());
	}

}


text:
package org.synyx.minos.core.web.event;

import org.springframework.beans.factory.annotation.Required;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

/**
 * Base event handler. Invokes callback method {@code AbstractEventHandler#prepareEvent(Event, EventContext)} before
 * triggering a controller with its full lifecycle.
 *

 *
 * Subclasses should be annotated with {@code ModuleDependent} as the
 * implementation is typesafe and thus would refer possibly not available
 * classes from other modules.
 *
 * @author Oliver Gierke - gierke@synyx.de
 */
public abstract class AbstractEventHandler<T extends Event> implements EventHandler<T> {

    private Class<T> supportedEvent;

    private Controller controller;

    /**
     * Sets the event class, the handler is intrested in.
     *
     * @param event the event to set
     */
    @Required
    public void setSupportedEvent(Class<T> event) {

        this.supportedEvent = event;
    }

    /**
     * Sets the controller, the handler will execute.
     *
     * @param controller the controller to set
     */
    @Required
    public void setController(Controller controller) {

        this.controller = controller;
    }

    public void handleEvent(T event, EventContext context) throws Exception {

        // Prepare duplicate execution
        if (context.alreadyVisited(controller)) {
            return;
        }

        prepareEvent(event, context);

        ModelAndView mav = controller.handleRequest(context.getRequest(), context.getResponse());

        context.getModelAndView().addAllObjects(mav.getModelMap());
    }

    /**
     * Callback method to prepare execution of the controller. Override this method to prepare the request according to
     * the event that was thrown and the controller to be executed.
     *
     * @param event
     * @param context
     */
    protected void prepareEvent(T event, EventContext context) {

        return;
    }

    public boolean supports(Class<? extends T> eventClass) {

        return eventClass.isAssignableFrom(supportedEvent);
    }

    @Override
    public String toString() {

        return "SimpleEventHandler: triggering " + controller.toString() + " on events of type "
            + supportedEvent.getName();
    }
}


text:
. test_subs.sh

. scc_setup.sh

# set up
determine_offsets
if [ $? -ne 0 ]; then
    echo Test failed to initialize
    exit $?
fi

# Dump all registers
pos_test scc_test -Lr

# Verify that a register can be written and does change
start_test Changing SCM_LENGTH register to 4
scc_test -W${SCM_LENGTH}:4
length_value=`scc_test -S+Q -R${SCM_LENGTH}`
if [  -z $length_value ]; then
    record_failure Reading result of changed SCM_LENGTH failed.
else
    if [ $length_value -eq 4 ]; then
	record_success Verified result of changed SCM_LENGTH.
    else
	record_failure Read of SCM_LENGTH return $length_value.
    fi
fi

# Verify it can changed to something else
start_test Changing SCM_LENGTH register to 8
scc_test -W${SCM_LENGTH}:8
length_value=`scc_test -S+Q -R${SCM_LENGTH}`
if [  -z $length_value ]; then
    record_failure Reading result of changed SCM_LENGTH failed.
else
    if [ $length_value -eq 8 ]; then
	record_success Verified result of changed SCM_LENGTH.
    else
	record_failure Read of SCM_LENGTH return $length_value.
    fi
fi

# This will invoke the Software Alarm and put the SMN into FAIL mode
pos_test scc_test -La

# Read all 'safe' registers when SCC has gone to alarm/FAILED state
pos_test scc_test -Ls

echo
echo
echo "The rest of tests should have errors (but pass)"

# Test SCM Length and SMN Sequence Start
neg_test scc_test -R${SCM_LENGTH}
neg_test scc_test -R${SMN_SEQUENCE_START}

# Let the world know how things went
print_test_results


text:
interface EmailFields {
  from?: () => string;
  subject?: (user: Meteor.User) => string;
  text?: (user: Meteor.User, url: string) => string;
  html?: (user: Meteor.User, url: string) => string;
}

interface Header {
  [id: string]: string;
}

interface EmailTemplates {
  from: string;
  siteName: string;
  headers?: Header;
  resetPassword: EmailFields;
  enrollAccount: EmailFields;
  verifyEmail: EmailFields;
}

declare module Accounts {
  var emailTemplates: EmailTemplates;
  function addEmail(userId: string, newEmail: string, verified?: boolean): void;
  function removeEmail(userId: string, email: string): void;

  function onCreateUser(func: Function): void;
  function findUserByEmail(email: string): Object;
  function findUserByUsername(username: string): Object;

  function sendEnrollmentEmail(userId: string, email?: string): void;
  function sendResetPasswordEmail(userId: string, email?: string): void;
  function sendVerificationEmail(userId: string, email?: string): void;

  function setUsername(userId: string, newUsername: string): void;
  function setPassword(userId: string, newPassword: string, options?: {
    logout?: Object;
  }): void;

  function validateNewUser(func: Function): boolean;
  function validateLoginAttempt(func: Function): { stop: () => void };

  interface IValidateLoginAttemptCbOpts {
    type: string;
    allowed: boolean;
    error: Meteor.Error;
    user: Meteor.User;
    connection: Meteor.Connection;
    methodName: string;
    methodArguments: any[];
  }
}


text:
const { __ } = require('../lib/locale')

module.exports = function error (state, emitter) {
  state.error = state.error || null

  emitter.on('error', err => {
    err = err.error || err

    if (process.env.NODE_ENV === 'development') {
      // eslint-disable-next-line no-console
      console.error(err.stack)
    }

    state.error = {
      message: __(err.message),
      status: err.status,
      stack: err.stack
    }

    emitter.emit('render')
  })

  emitter.on(state.events.NAVIGATE, () => {
    state.error = null
  })

  emitter.on('error:dismiss', () => {
    state.error = null
    emitter.emit('render')
  })
}


text:
package org.encog.ml.ea.score.parallel;

import java.util.List;

import org.encog.ml.CalculateScore;
import org.encog.ml.MLMethod;
import org.encog.ml.ea.exception.EARuntimeError;
import org.encog.ml.ea.genome.Genome;
import org.encog.ml.ea.score.AdjustScore;
import org.encog.ml.ea.train.basic.BasicEA;

/**
 * An individual threadable task for the parallel score calculation.
 *
 */
public class ParallelScoreTask implements Runnable {

	/**
	 * The genome to calculate the score for.
	 */
	private final Genome genome;

	/**
	 * The score function.
	 */
	private final CalculateScore scoreFunction;

	/**
	 * The score adjusters.
	 */
	private final List<AdjustScore> adjusters;

	/**
	 * The owners.
	 */
	private final ParallelScore owner;

	/**
	 * Construct the parallel task.
	 * @param genome The genome.
	 * @param theOwner The owner.
	 */
	public ParallelScoreTask(Genome genome, ParallelScore theOwner) {
		super();
		this.owner = theOwner;
		this.genome = genome;
		this.scoreFunction = theOwner.getScoreFunction();
		this.adjusters = theOwner.getAdjusters();
	}

	/**
	 * Perform the task.
	 */
	@Override
	public void run() {
		MLMethod phenotype = this.owner.getCodec().decode(this.genome);
		if (phenotype != null) {
			double score;
			try {
				score = this.scoreFunction.calculateScore(phenotype);
			} catch(EARuntimeError e) {
				score = Double.NaN;
			}
			genome.setScore(score);
			genome.setAdjustedScore(score);
			BasicEA.calculateScoreAdjustment(genome, adjusters);
		} else {

		}
	}

}


text:
title: "NSCharacterSet on NSHipster"
date: 2012-09-18 00:00
---

I really enjoyed [this week's NSHipster](http://nshipster.com/nscharacterset/?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+NSHipster+%28NSHipster%29). It discusses the uses, and misuses, of `NSCharacterSet` as well as a few other obscure-ish string-related classes.

If you don't already follow [NSHipster](http://nshipster.com), you really should. In the worst case, you already knew about the topic being discussed (but _you would_ already have heard of that, wouldn't you?) and best case, you learn something super useful.

> And if not being wrong isn't the most important thing about being an NSHipster, then I don't want to be right!<!-- more -->


text:
;(function(window, document, _) {
    _.fn('on', function(key, fn) {
        if (!fn) { fn = key; key = ''; }// shift args when needed
        var s = this,
            bound,
            id = _.id(this._area);
        if (window.addEventListener) {
            window.addEventListener("storage", bound = function(e) {
                var k = s._out(e.key);
                if (k && (!key || k === key)) {// must match key if listener has one
                    var eid = _.id(e.storageArea);
                    if (!eid || id === eid) {// must match area, if event has a known one
                        return fn.call(s, _.event(k, s, e));
                    }
                }
            }, false);
        } else {
            document.attachEvent("onstorage", bound = function() {
                return fn.call(s, window.event);
            });
        }
        fn['_'+key+'listener'] = bound;
        return s;
    });
    _.fn('off', function(key, fn) {
        if (!fn) { fn = key; key = ''; }// shift args when needed
        var bound = fn['_'+key+'listener'];
        if (window.removeEventListener) {
            window.removeEventListener("storage", bound);
        } else {
            document.detachEvent("onstorage", bound);
        }
        return this;
    });
    _.event = function(k, s, e) {
        var event = {
            key: k,
            namespace: s.namespace(),
            newValue: _.parse(e.newValue),
            oldValue: _.parse(e.oldValue),
            url: e.url || e.uri,
            storageArea: e.storageArea,
            source: e.source,
            timeStamp: e.timeStamp,
            originalEvent: e
        };
        if (_.cache) {
            var min = _.expires(e.newValue || e.oldValue);
            if (min) {
                event.expires = _.when(min);
            }
        }
        return event;
    };
    _.id = function(area) {
        for (var id in _.areas) {
            if (area === _.areas[id]) {
                return id;
            }
        }
    };
})(window, document, window.store._);


text:
<?xml version="1.0"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">

<struts-config>
	<action-mappings>
                <action path="/login/stork" type="com.liferay.portlet.login.action.STORKAction">
                        <forward name="portlet.login.login" path="portlet.login.login" />
                        <forward name="portlet.login.stork.country" path="portlet.login.stork.country" />
                        <forward name="portlet.login.stork.peps" path="portlet.login.stork.peps" />
                        <forward name="portlet.login.stork.error" path="portlet.login.stork.error" />
                        <forward name="portlet.login.stork.notAuth" path="portlet.login.stork.notAuth" />
                </action>
	</action-mappings>
</struts-config>


text:
var app        = require('express');
var router     = app.Router();
var jsonParser = require('body-parser').json();
var calc       = require('../../libs/calc');

router.post('/', jsonParser, function (req, res) {
  var data     = req.body,
      numNodes = data.nodeWeights ? data.nodeWeights.length : 0,
      result   = [];

  for(var i = 0; i < numNodes; i++) {
    for(var j = 0; j < numNodes; j++) if (i !== j ) {
      var neighboursI = calc.getNeighbours(data.links, i),
          neighboursJ = calc.getNeighbours(data.links, j),
          weightsI    = calc.getWeights(neighboursI, data.linkWeights),
          weightsJ    = calc.getWeights(neighboursJ, data.linkWeights),
          score       = calc.calcPower(weightsI) * calc.calcPower(weightsJ);

      result.push({source: i, target: j, score: score});
    }
  }

  res.status(200).json(result);
});

module.exports = router;


text:
package com.intellij.refactoring.move.moveMembers;

import com.intellij.psi.PsiMember;
import com.intellij.psi.PsiModifier;
import org.jetbrains.annotations.Nullable;

import java.util.Collection;

public class MockMoveMembersOptions implements MoveMembersOptions {
  private final PsiMember[] mySelectedMembers;
  private final String myTargetClassName;
  private String myMemberVisibility = PsiModifier.PUBLIC;

  public MockMoveMembersOptions(String targetClassName, PsiMember[] selectedMembers) {
    mySelectedMembers = selectedMembers;
    myTargetClassName = targetClassName;
  }

  public MockMoveMembersOptions(String targetClassName, Collection<PsiMember> memberSet) {
    this(targetClassName, memberSet.toArray(PsiMember.EMPTY_ARRAY));
  }

  @Override
  public String getMemberVisibility() {
    return myMemberVisibility;
  }

  @Override
  public boolean makeEnumConstant() {
    return true;
  }

  public void setMemberVisibility(@Nullable String visibility) {
    myMemberVisibility = visibility;
  }

  @Override
  public PsiMember[] getSelectedMembers() {
    return mySelectedMembers;
  }

  @Override
  public String getTargetClassName() {
    return myTargetClassName;
  }
}


text:
package com.danielesegato.adme.db.serializer;

import android.content.ContentValues;
import android.database.Cursor;

import com.danielesegato.adme.config.ADMEFieldConfig;
import com.danielesegato.adme.config.SQLiteType;

/**
 * Persist a primitive integer in SQLite database.
 */
public class IntADMESerializer extends BaseADMESerializer {
    private static IntADMESerializer singleton = new IntADMESerializer();

    public static IntADMESerializer getSingleton() {
        return singleton;
    }

    @Override
    public SQLiteType getSQLiteType() {
        return SQLiteType.INTEGER;
    }

    @Override
    public Object sqlToJava(Cursor cursor, int columnPos, ADMEFieldConfig fieldConfig) {
        return cursor.getInt(columnPos);
    }

    @Override
    public String stringToSqlRaw(String val, ADMEFieldConfig fieldConfig) {
        return Integer.toString(Integer.parseInt(val));
    }

    @Override
    public void storeInContentValues(String key, ContentValues values, Object fieldValue, ADMEFieldConfig fieldConfig) throws IllegalArgumentException {
        if (fieldValue == null || !(fieldValue instanceof Integer)) {
            throw new IllegalArgumentException(String.format(
                    String.format("Field value for entity %s field %s can't be considered a primitive int for key %s: %s",
                            fieldConfig.getADMEEntityConfig().getEntityName(),
                            fieldConfig.getColumnName(),
                            key,
                            fieldValue)
            ));
        }
        values.put(key, (Integer) fieldValue);
    }
}