text:
const rp = require('request-promise');
const moment = require('moment');

let pageAfterBase;

var domains = [];
var funcs = [{
    func: "getAllRedditDomainsFromDate",
    description: "Get all domains from JSON using date",
    execute: function(date, subreddit, pageAfter, callback) {
        let req;
        pageAfterBase = pageAfter;

        req = 'https://www.reddit.com/r/' + subreddit + '.json?after=' + pageAfter;

        rp(req)
            .then(function(body) {
                var jsonParsed = JSON.parse(body);
                var limit = Object.keys(jsonParsed.data.children).length;
                newPageAfter = jsonParsed.data.after;
                // var todayDate = Date.now() / 1000 | 0;
                for (var i = 0; i < limit; i++) {
                    var postDate = jsonParsed.data.children[i].data.created_utc.toString();
                    postDate = postDate.substring(0, 10);
                    postDate = new moment(new moment.unix(postDate));
                    if (postDate.isAfter(date) && postDate.isValid()) {
                        var idPost = jsonParsed.data.children[i].data.id;
                        var domain = jsonParsed.data.children[i].data.domain;
                        //var timestamp = jsonParsed.data.children[i].data.created;
                        //var dateTime = postDate.getDate() + "/" + postDate.getMonth() + "/" + postDate.getFullYear();
                        console.log(domain, " - Date : ", postDate.format("DD MMM YYYY hh:mm a"));
                        domains.push(idPost + " - " + "Page : " + pageAfterBase + " - " + domain + " - " + postDate.format("DD MMM YYYY hh:mm a"));
                    }
                }
                return domains;
            }).then((dom) => {
                //console.log(dom);
                return callback(dom, newPageAfter, false);
            })
            .catch(function(err) {
                return callback(false, false, err);
            });
    }
}];

module.exports = funcs;

redpajama_set_name: RedPajamaGithub


text:
<blueprint>

    <sensor watch="activeCount,completedCount,filter" run="render" />
    <sensor node="clearCompletedBtn" on="click" pipe="cmd_ClearCompleted" />

</blueprint>

<display>

        1
         item left

All

Active

Completed

    <button id="clearCompletedBtn" class="id_clear-completed" ></button>

</display>


text:
#include "netif/ppp/ppp_opts.h"
#if PPP_SUPPORT && ECP_SUPPORT  /* don't build if not configured for use in lwipopts.h */

#ifndef ECP_H
#define ECP_H

#ifdef __cplusplus
extern "C" {
#endif

typedef struct ecp_options {
    bool required;		/* Is ECP required? */
    unsigned enctype;		/* Encryption type */
} ecp_options;

extern fsm ecp_fsm[];
extern ecp_options ecp_wantoptions[];
extern ecp_options ecp_gotoptions[];
extern ecp_options ecp_allowoptions[];
extern ecp_options ecp_hisoptions[];

extern const struct protent ecp_protent;

#ifdef __cplusplus
}
#endif

#endif /* ECP_H */
#endif /* PPP_SUPPORT && ECP_SUPPORT */


text:
import { useState } from "react";

// If key is null/undefined, hook behaves exactly like useState
export const useLocalStorage = (key: string, initialValue: any) => {
  const initialString = JSON.stringify(initialValue);

  const [storedValue, setStoredValue] = useState(() => {
    if (key) {
      const item = window.localStorage.getItem(key);
      return item ? JSON.parse(item) : initialValue;
    } else {
      return initialValue;
    }
  });

  const setValue = (value: any) => {
    // Allow value to be a function so we have same API as useState
    const valueToStore = value instanceof Function ? value(storedValue) : value;

    // Save state
    setStoredValue(valueToStore);

    if (key) {
      const stringToStore = JSON.stringify(valueToStore);
      if (stringToStore === initialString) {
        window.localStorage.removeItem(key);
      } else {
        window.localStorage.setItem(key, stringToStore);
      }
    }
  };

  return [storedValue, setValue] as const;
};


text:
#ifndef GRPC_CORE_SUPPORT_THD_INTERNAL_H
#define GRPC_CORE_SUPPORT_THD_INTERNAL_H

/* Internal interfaces between modules within the gpr support library.  */

#endif /* GRPC_CORE_SUPPORT_THD_INTERNAL_H */


text:
package com.xandrev.mbandroid.gui;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;

import com.xandrev.mbandroid.R;

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

public class NotificationSettings extends Activity {

    private static final String TAG = "NotificationSettings";
    private com.xandrev.mbandroid.settings.notifications.NotificationSettings settings;
    private Button btnCheckAll;
    private Button btnUncheckAll;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        settings = com.xandrev.mbandroid.settings.notifications.NotificationSettings.getInstance(this);
        setContentView(R.layout.activity_notification_settings);
        getActionBar().setDisplayHomeAsUpEnabled(true);

        btnCheckAll = (Button) findViewById(R.id.btnCheckAll);
        btnUncheckAll = (Button) findViewById(R.id.btnUncheckAll);

        final ListView lv = (ListView) findViewById(R.id.listView);
        final List<String> your_array_list =settings.getApplicationNames();
        final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, your_array_list );
        Log.i(TAG, "Recovering application list: " + your_array_list.size());
        lv.setAdapter(arrayAdapter);
        lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

        final CheckBox cbox = (CheckBox) findViewById(R.id.checkBox);

        List list = settings.getEnabledApps();
        if(list != null) {
            Log.i(TAG,"Recovering enabled application list: "+list.size());
            for (int i = 0; i < arrayAdapter.getCount(); i++) {
                String value = arrayAdapter.getItem(i);
                lv.setItemChecked(i,settings.isEnabledApplication(value));
            }
        }else{
            for (int i = 0; i < arrayAdapter.getCount(); i++) {
                lv.setItemChecked(i, true);
            }
        }

        btnCheckAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (int i = 0; i < arrayAdapter.getCount(); i++) {
                    lv.setItemChecked(i, true);
                }
            }
        });

        btnUncheckAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (int i = 0; i < arrayAdapter.getCount(); i++) {
                    lv.setItemChecked(i, false);
                }
            }
        });

        cbox.setChecked(settings.getEnabledTile());

        findViewById(R.id.saveBtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SparseBooleanArray checkedItems = lv.getCheckedItemPositions();
                Log.i(TAG, "Recovering checked items..");
                List<String> newEnabledAppList = new ArrayList<String>();
                if(checkedItems != null){
                    Log.i(TAG,"Total of checked items: "+checkedItems.size());
                    for(int i=0;i<checkedItems.size();i++){
                        int idx = checkedItems.keyAt(i);
                        if(checkedItems.get(idx)){
                            Log.i(TAG, "Added new value: "+lv.getItemAtPosition(idx));
                            newEnabledAppList.add((String)lv.getItemAtPosition(idx));
                        }
                    }
                }
                settings.setEnabledApps(newEnabledAppList);
                settings.setEnabledTile(cbox.isChecked());

            }
        });
    }

}


text:
namespace sf
{
class Socket;

////////////////////////////////////////////////////////////
/// \brief Multiplexer that allows to read from multiple sockets
///
////////////////////////////////////////////////////////////
class SFML_NETWORK_API SocketSelector
{
public:

    ////////////////////////////////////////////////////////////
    /// \brief Default constructor
    ///
    ////////////////////////////////////////////////////////////
    SocketSelector();

    ////////////////////////////////////////////////////////////
    /// \brief Copy constructor
    ///
    /// \param copy Instance to copy
    ///
    ////////////////////////////////////////////////////////////
    SocketSelector(const SocketSelector& copy);

    ////////////////////////////////////////////////////////////
    /// \brief Destructor
    ///
    ////////////////////////////////////////////////////////////
    ~SocketSelector();

    ////////////////////////////////////////////////////////////
    /// \brief Add a new socket to the selector
    ///
    /// This function keeps a weak reference to the socket,
    /// so you have to make sure that the socket is not destroyed
    /// while it is stored in the selector.
    /// This function does nothing if the socket is not valid.
    ///
    /// \param socket Reference to the socket to add
    ///
    /// \see remove, clear
    ///
    ////////////////////////////////////////////////////////////
    void add(Socket& socket);

    ////////////////////////////////////////////////////////////
    /// \brief Remove a socket from the selector
    ///
    /// This function doesn't destroy the socket, it simply
    /// removes the reference that the selector has to it.
    ///
    /// \param socket Reference to the socket to remove
    ///
    /// \see add, clear
    ///
    ////////////////////////////////////////////////////////////
    void remove(Socket& socket);

    ////////////////////////////////////////////////////////////
    /// \brief Remove all the sockets stored in the selector
    ///
    /// This function doesn't destroy any instance, it simply
    /// removes all the references that the selector has to
    /// external sockets.
    ///
    /// \see add, remove
    ///
    ////////////////////////////////////////////////////////////
    void clear();

    ////////////////////////////////////////////////////////////
    /// \brief Wait until one or more sockets are ready to receive
    ///
    /// This function returns as soon as at least one socket has
    /// some data available to be received. To know which sockets are
    /// ready, use the isReady function.
    /// If you use a timeout and no socket is ready before the timeout
    /// is over, the function returns false.
    ///
    /// \param timeout Maximum time to wait, (use Time::Zero for infinity)
    ///
    /// \return True if there are sockets ready, false otherwise
    ///
    /// \see isReady
    ///
    ////////////////////////////////////////////////////////////
    bool wait(Time timeout = Time::Zero);

    ////////////////////////////////////////////////////////////
    /// \brief Test a socket to know if it is ready to receive data
    ///
    /// This function must be used after a call to Wait, to know
    /// which sockets are ready to receive data. If a socket is
    /// ready, a call to receive will never block because we know
    /// that there is data available to read.
    /// Note that if this function returns true for a TcpListener,
    /// this means that it is ready to accept a new connection.
    ///
    /// \param socket Socket to test
    ///
    /// \return True if the socket is ready to read, false otherwise
    ///
    /// \see isReady
    ///
    ////////////////////////////////////////////////////////////
    bool isReady(Socket& socket) const;

    ////////////////////////////////////////////////////////////
    /// \brief Overload of assignment operator
    ///
    /// \param right Instance to assign
    ///
    /// \return Reference to self
    ///
    ////////////////////////////////////////////////////////////
    SocketSelector& operator =(const SocketSelector& right);

private:

    struct SocketSelectorImpl;

    ////////////////////////////////////////////////////////////
    // Member data
    ////////////////////////////////////////////////////////////
    SocketSelectorImpl* m_impl; ///< Opaque pointer to the implementation (which requires OS-specific types)
};

} // namespace sf

#endif // SFML_SOCKETSELECTOR_HPP

////////////////////////////////////////////////////////////
/// \class sf::SocketSelector
/// \ingroup network
///
/// Socket selectors provide a way to wait until some data is
/// available on a set of sockets, instead of just one. This
/// is convenient when you have multiple sockets that may
/// possibly receive data, but you don't know which one will
/// be ready first. In particular, it avoids to use a thread
/// for each socket; with selectors, a single thread can handle
/// all the sockets.
///
/// All types of sockets can be used in a selector:
/// \li sf::TcpListener
/// \li sf::TcpSocket
/// \li sf::UdpSocket
///
/// A selector doesn't store its own copies of the sockets
/// (socket classes are not copyable anyway), it simply keeps
/// a reference to the original sockets that you pass to the
/// "add" function. Therefore, you can't use the selector as a
/// socket container, you must store them outside and make sure
/// that they are alive as long as they are used in the selector.
///
/// Using a selector is simple:
/// \li populate the selector with all the sockets that you want to observe
/// \li make it wait until there is data available on any of the sockets
/// \li test each socket to find out which ones are ready
///
/// Usage example:
/// \code
/// // Create a socket to listen to new connections
/// sf::TcpListener listener;
/// listener.listen(55001);
///
/// // Create a list to store the future clients
/// std::list<sf::TcpSocket*> clients;
///
/// // Create a selector
/// sf::SocketSelector selector;
///
/// // Add the listener to the selector
/// selector.add(listener);
///
/// // Endless loop that waits for new connections
/// while (running)
/// {
///     // Make the selector wait for data on any socket
///     if (selector.wait())
///     {
///         // Test the listener
///         if (selector.isReady(listener))
///         {
///             // The listener is ready: there is a pending connection
///             sf::TcpSocket* client = new sf::TcpSocket;
///             if (listener.accept(*client) == sf::Socket::Done)
///             {
///                 // Add the new client to the clients list
///                 clients.push_back(client);
///
///                 // Add the new client to the selector so that we will
///                 // be notified when he sends something
///                 selector.add(*client);
///             }
///             else
///             {
///                 // Error, we won't get a new connection, delete the socket
///                 delete client;
///             }
///         }
///         else
///         {
///             // The listener socket is not ready, test all other sockets (the clients)
///             for (std::list<sf::TcpSocket*>::iterator it = clients.begin(); it != clients.end(); ++it)
///             {
///                 sf::TcpSocket& client = **it;
///                 if (selector.isReady(client))
///                 {
///                     // The client has sent some data, we can receive it
///                     sf::Packet packet;
///                     if (client.receive(packet) == sf::Socket::Done)
///                     {
///                         ...
///                     }
///                 }
///             }
///         }
///     }
/// }
/// \endcode
///
/// \see sf::Socket
///
////////////////////////////////////////////////////////////


text:
<?php

namespace FJ;

use Exception;
use \phpseclib\Crypt\AES;

class FJ
{
    const FJ_DEFAULT_AES_MODE   = "ctr";
    const FJ_JSON_DETECT_ERRORS = false;

    public static function totime () { return date("Ymd_his"); }
    public static function todate () { return date("Ymd"); }

    /**
     * ****************************************************************
     * Base64url-encodes the input.
     *
     * @param $s string - Input (plain)
     *
     * @return string - base64url-encoding of input.
     * ****************************************************************
     */
    public static function b64url_encode ( $s )
    {
        if ( false === isset($s) || null === $s || 0 == strlen($s) )
        {
            return null;
        }

        /*
        * Do stuff!
        */
        $b64 = base64_encode($s);
        //$b64u = rtrim( strtr( $b64, '+/', '-_' ), '=' );
        $b64u = strtr($b64, '+/', '-_');

        return $b64u;
    }

    /**
     * ****************************************************************
     * Base64url-decodes the input.
     *
     * @param $s string - Input (base64url-encoded).
     *
     * @return string - base64url-decoding of input.
     * ****************************************************************
     */
    public static function b64url_decode ( $s )
    {
        if ( false === isset($s) || null === $s || 0 == strlen($s) )
        {
            return null;
        }

        //return base64_decode( str_pad( strtr( $s, '-_', '+/' ), strlen( $s ) % 4, '=', STR_PAD_RIGHT ) );
        return base64_decode(strtr($s, '-_', '+/'));
    }

    public static function stripNon7BitCleanASCII ( $string )
    {
        return preg_replace('/[\x00-\x1F\x7F-\xFF]/', '', $string);
    }

    public static function stripSpaces ( $string )
    {
        return preg_replace("/[^[:alnum:]]/", "", $string);
    }

    public static function stripLower ( $string )
    {
        return strtolower(self::stripSpaces($string));
    }

    public static function spacesToDashes ( $string )
    {
        return preg_replace("/[[:space:]]/", "-", $string);
    }

    /**
     * ****************************************************************
     * Creates a 2nd-level copy of an array.  The references are copied,
     * but the values themselves are unchanged.
     *
     * @param $ar
     *
     * @return array
     * ****************************************************************
     */
    public static function deepCopy ( $ar )
    {
        $copy = [];
        foreach ( $ar as $key => $value )
        {
            $copy[$key] = $value;
        }
        return $copy;
    }

    public static function hash ( $str, $substrLen = 0, $algo = "SHA256" )
    {
        $hash = hash($algo, $str);
        return (0 < $substrLen) ? substr($hash, 0, $substrLen) : $hash;
    }

    public static function hashFile ( $path, $substrLen = 0, $algo = "SHA256" )
    {
        $hash = hash_file($algo, $path);
        return (0 < $substrLen) ? substr($hash, 0, $substrLen) : $hash;
    }

    public static function encrypt ( $key, $iv, $plaintext )
    {
        $aes = new AES(self::FJ_DEFAULT_AES_MODE);
        $aes->setKey($key);
        $aes->setIV($iv);
        return $aes->encrypt($plaintext);
    }

    public static function decrypt ( $key, $iv, $ciphertext )
    {
        $aes = new AES(self::FJ_DEFAULT_AES_MODE);
        $aes->setKey($key);
        $aes->setIV($iv);
        return $aes->decrypt($ciphertext);
    }

    public static function in_array_sorted ( $needle, $haystack )
    {
        $top = count($haystack) - 1;
        $bot = 0;
        while ( $top >= $bot )
        {
            $p = ($top + $bot) >> 1;
            if ( $haystack[$p] < $needle ) $bot = $p + 1;
            elseif ( $haystack[$p] > $needle ) $top = $p - 1;
            else return true;
        }
        return false;
    }

    public static function endsWith ( $needle, $haystack, $len = false )
    {
        if ( false === $len ) $len = strlen($needle);
        if ( 0 == $len ) return true;

        return $needle === substr($haystack, -$len);
    }

    public static function startsWith ( $needle, $haystack, $len = false )
    {
        if ( false === $len ) $len = strlen($needle);
        return $needle === substr($haystack, 0, $len);
    }

    public static function stripExtension ( $filename )
    {
        $extWithPeriod = strrchr($filename, ".");
        $extlen        = strlen($extWithPeriod);
        $hasPeriod     = 0 < $extlen;
        $namelen       = strlen($filename) - $extlen;
        $name          = $hasPeriod ? substr($filename, 0, $namelen) : $filename;

        return $name;
    }

    public static function stripExtensionAndDir ( $filepath )
    {
        $basename = basename($filepath);
        return self::stripExtension($basename);
    }

    /**
     * https://stackoverflow.com/questions/2791998/convert-dashes-to-camelcase-in-php
     *
     * @param      $string
     * @param bool $startWithLower
     *
     * @return mixed|string
     */
    public static function dashesToCamelCase ( $string, $startWithLower = true )
    {
        $str = str_replace(' ', '', ucwords(str_replace('-', ' ', $string)));
        return $startWithLower ? lcfirst($str) : $str;
    }

    /**
     * Takes a string of the form 'abcxyz' and converts it to 'ab...yz'.
     *
     * @param string $string    - Input string.
     * @param int    $len       - Total length to clip to (including delimiter).
     * @param string $delimiter - Combining string to split front- and back-halves.
     *
     * @return string - Either a clipped string 'ab...yz' or the original string.
     */
    public static function clipString ( $string, $len, $delimiter = " )->( " )
    {
        $l = strlen($string);
        if ( $l < $len ) return $string;

//        clog("clipping!");

        $dlen = strlen($delimiter);

        $slen      = $len - $dlen;
        $half      = $slen / 2;
        $fh        = floor($half);
        $otherHalf = 0 === ($half - $fh) ? $fh : ($fh + 1);
        $end       = $l - $otherHalf;

//        clog("dlen", $dlen);
//        clog("slen", $slen);
//        clog("half", $half);
//        clog("fh", $fh);
//        clog("o-ha", $otherHalf);
//        clog("dlen", $dlen);
//        clog("end", $end);

        $front = substr($string, 0, $half);
        $back  = substr($string, $end);

//        clog("front", $front);
//        clog("back", $back);

        return $front . $delimiter . $back;
    }

    public static function jsEncode ( $obj )
    {
        $json = json_encode($obj);

        if ( self::FJ_JSON_DETECT_ERRORS ) self::detectJSONError($obj, $json, true);

        return $json;
    }

    public static function jsPrettyEncode ( $obj )
    {
        $json = json_encode($obj, JSON_PRETTY_PRINT);

        if ( self::FJ_JSON_DETECT_ERRORS ) self::detectJSONError($obj, $json, true);

        return $json;
    }

    public static function jsDecode ( $json, $useAssoc = true )
    {
        $string = json_decode($json, $useAssoc);

        if ( self::FJ_JSON_DETECT_ERRORS ) self::detectJSONError($json, $string, false);

        return $string;
    }

    private static function detectJSONError ( $input, $output, $isEncode = true )
    {
        $function = $isEncode ? "encoding" : "decoding";

        if ( false === $output )
            clog("JSON error $function [ $input ]");

        switch ( json_last_error() )
        {
            case JSON_ERROR_NONE:
                $jsonErrorMessage = null;
                break;
            case JSON_ERROR_DEPTH:
                $jsonErrorMessage = '- Maximum stack depth exceeded';
                break;
            case JSON_ERROR_STATE_MISMATCH:
                $jsonErrorMessage = '- Underflow or the modes mismatch';
                break;
            case JSON_ERROR_CTRL_CHAR:
                $jsonErrorMessage = '- Unexpected control character found';
                break;
            case JSON_ERROR_SYNTAX:
                $jsonErrorMessage = '- Syntax error, malformed JSON';
                break;
            case JSON_ERROR_UTF8:
                $jsonErrorMessage = '- Malformed UTF-8 characters, possibly incorrectly encoded';
                break;
            default:
                $jsonErrorMessage = '- Unknown error';
                break;
        }

        if ( null !== $jsonErrorMessage )
            clog("-----=====[ JSON encoding error $jsonErrorMessage ]=====-----");
    }

    /**
     * @param $length
     *
     * @return bool|string
     * @throws Exception
     */
    public static function randBytes ( $length )
    {
        // method 1. the fastest
        if ( function_exists('openssl_random_pseudo_bytes') )
        {
            return openssl_random_pseudo_bytes($length);
        }
        // method 2
        static $fp = true;
        if ( $fp === true )
        {
            // warning's will be output unles the error suppression operator is used. errors such as
            // "open_basedir restriction in effect", "Permission denied", "No such file or directory", etc.
            $fp = @fopen('/dev/urandom', 'rb');
        }
        if ( $fp !== true && $fp !== false )
        { // surprisingly faster than !is_bool() or is_resource()
            return fread($fp, $length);
        }
        // method 3. pretty much does the same thing as method 2 per the following url:
        // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/mcrypt/mcrypt.c#L1391
        // surprisingly slower than method 2. maybe that's because mcrypt_create_iv does a bunch of error checking that we're
        // not doing. regardless, this'll only be called if this PHP script couldn't open /dev/urandom due to open_basedir
        // restrictions or some such
        if ( function_exists('mcrypt_create_iv') )
        {
            return mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
        }

        // We've failed to get a good random number; throw exception.
        throw new Exception("Could not get high-quality random number (openssl, /dev/urandom, mcrypt all FAILED); aborting.");
    }

    /**
     * @param string     $method
     * @param string     $url
     * @param bool|array $data
     * @param bool|array $params
     *
     * @return string - raw (textual) HTTP response
     */
    public static function callAPI ( $method, $url, $data = false, $params = false )
    {
        $debug        = self::getParam("debug", $params);
        $debugVerbose = self::getParam("debugVerbose", $params);
        $user         = self::getParam("user", $params);
        $pass         = self::getParam("pass", $params);
        $debugProxy   = self::getParam("debugProxy", $params);
        $debugPort    = self::getParam("debugPort", $params);
        $debugHost    = self::getParam("debugHost", $params);

        $curl = curl_init();

        switch ( $method )
        {
            case "POST":
                curl_setopt($curl, CURLOPT_POST, 1);

                if ( false !== $data )
                {
                    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
                    if ( false !== $debugVerbose ) clog("POST data (as query string)", http_build_query($data));
                }
                break;

            case "PUT":
                curl_setopt($curl, CURLOPT_PUT, 1);
                break;

            default:
                if ( false !== $data )
                {
                    if ( false !== $debugVerbose ) clog("GET data (query string)", http_build_query($data));
                    $url = sprintf("%s?%s", $url, http_build_query($data));
                }
        }

        if ( false !== $pass && false !== $user )
        {
            // Optional Authentication:
            curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
            curl_setopt($curl, CURLOPT_USERPWD, "$user:$pass");
        }

        if ( false !== $debug ) clog("Hitting URL", $url);
        if ( false !== $debugVerbose ) curl_setopt($curl, CURLOPT_VERBOSE, true);

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

        if ( false !== $debugProxy )
        {
            //
            // Defaults set to Charles Debugging, locally.
            //
            $port = false === $debugPort ? 8888 : $debugPort;
            $host = false === $debugHost ? "localhost" : $debugHost;

            curl_setopt($curl, CURLOPT_PROXY, "http://$host:$port/");
        }

        $result = curl_exec($curl);

        curl_close($curl);

        return trim($result);
    }

    static function getParam ( $needle, $haystack )
    {
        if ( false === $haystack || !$haystack ) return false;
        return array_key_exists($needle, $haystack) ? $haystack[$needle] : false;
    }

    /**
     * Method: POST, PUT, GET etc
     * Data: array("param" => "value") ==> index.php?param=value
     *
     * @param      $method
     * @param      $url
     * @param bool $data
     * @param bool $debug - Only use if CharlesProxy is being used on localhost:8888
     *
     * @return string
     */
    public static function _callAPI ( $method, $url, $data = false, $debug = false )
    {
        $curl = curl_init();

        switch ( $method )
        {
            case "POST":
                curl_setopt($curl, CURLOPT_POST, 1);

                if ( false !== $data )
                {
                    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
                    if ( false !== $debug ) clog("POST data (as query string)", http_build_query($data));
                }
                break;

            case "PUT":
                curl_setopt($curl, CURLOPT_PUT, 1);
                break;

            default:
                if ( false !== $data )
                {
                    if ( false !== $debug ) clog("GET data (query string)", http_build_query($data));
                    $url = sprintf("%s?%s", $url, http_build_query($data));
                }
        }

//        // Optional Authentication:
//        curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
//        curl_setopt($curl, CURLOPT_USERPWD, "username:password");

        if ( false !== $debug ) clog("Hitting URL", $url);

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

        if ( false !== $debug )
        {
            curl_setopt($curl, CURLOPT_PROXY, 'http://localhost:8888/');
            curl_setopt($curl, CURLOPT_VERBOSE, true);
        }

        $result = curl_exec($curl);

        curl_close($curl);

        return trim($result);
    }

    private static function normalizeSimpleXML ( $obj, &$result )
    {
        $data = $obj;
        if ( is_object($data) )
        {
            $data = get_object_vars($data);
        }
        if ( is_array($data) )
        {
            foreach ( $data as $key => $value )
            {
                $res = null;
                self::normalizeSimpleXML($value, $res);
                if ( ($key == '@attributes') && ($key) )
                {
                    $result = $res;
                }
                else
                {
                    $result[$key] = $res;
                }
            }
        }
        else
        {
            $result = $data;
        }
    }

    /**
     * Converts XML to JSON (ignoring attributes).
     *
     * @param $xml
     *
     * @return false|string
     */
    public static function xmlDecodeComplex ( $xml )
    {
        self::normalizeSimpleXML(simplexml_load_string($xml), $result);

        return $result;

        //return json_encode($result);
    }

    public static function xmlDecode ( $xml )
    {
        $object = simplexml_load_string($xml);
        return @json_decode(@json_encode($object), 1);
    }
}


text:
<?php

namespace Blocktrail\SDK\Connection;

use Blocktrail\SDK\Blocktrail;
use Blocktrail\SDK\Throttler;
use GuzzleHttp\Client as Guzzle;
use GuzzleHttp\Handler\CurlHandler;
use GuzzleHttp\HandlerStack;
use HttpSignatures\Context;

class RestClient extends BaseRestClient
{
    /**
     * @var array
     */
    protected $options = [];

    /**
     * @var array
     */
    protected $curlOptions = [];

    /**
     * @var Guzzle
     */
    protected $guzzle;

    /**
     * @var Throttler
     */
    protected $throttler;

    /**
     * GuzzleRestClient constructor.
     * @param $apiEndpoint
     * @param $apiVersion
     * @param $apiKey
     * @param $apiSecret
     */
    public function __construct($apiEndpoint, $apiVersion, $apiKey, $apiSecret) {
        parent::__construct($apiEndpoint, $apiVersion, $apiKey, $apiSecret);
        $this->guzzle = $this->createGuzzleClient();
        if ($throttle = \getenv('BLOCKTRAIL_SDK_THROTTLE_BTCCOM')) {
            $throttle = (float)$throttle;
        } else {
            $throttle = 0.33;
        }

        $this->throttler = Throttler::getInstance($this->apiEndpoint, $throttle);
    }

    /**
     * @param array $options
     * @param array $curlOptions
     * @return Guzzle
     */
    protected function createGuzzleClient(array $options = [], array $curlOptions = []) {
        $options = $options + $this->options;
        $curlOptions = $curlOptions + $this->curlOptions;

        $context = new Context([
            'keys' => [$this->apiKey => $this->apiSecret],
            'algorithm' => 'hmac-sha256',
            'headers' => ['(request-target)', 'Content-MD5', 'Date'],
        ]);

        $curlHandler = new CurlHandler($curlOptions);
        $handler = HandlerStack::create($curlHandler);
//        $handler->push(GuzzleHttpSignatures::middlewareFromContext($context));

        return new Guzzle($options + array(
            'handler' => $handler,
            'base_uri' => $this->apiEndpoint,
            'headers' => array(
                'User-Agent' => Blocktrail::SDK_USER_AGENT . '/' . Blocktrail::SDK_VERSION,
            ),
            'http_errors' => false,
            'connect_timeout' => 3,
            'timeout' => 20.0, // tmp until we have a good matrix of all the requests and their expect min/max time
            'verify' => true,
            'proxy' => '',
            'debug' => false,
            'config' => array(),
            'auth' => '',
        ));
    }

    /**
     * @return Guzzle
     */
    public function getGuzzleClient() {
        return $this->guzzle;
    }

    /**
     * enable CURL debugging output
     *
     * @param   bool        $debug
     */
    public function setCurlDebugging($debug = true) {
        $this->options['debug'] = $debug;

        $this->guzzle = $this->createGuzzleClient();
    }

    /**
     * set cURL default option on Guzzle client
     * @param string    $key
     * @param bool      $value
     */
    public function setCurlDefaultOption($key, $value) {
        $this->curlOptions[$key] = $value;

        $this->guzzle = $this->createGuzzleClient();
    }

    /**
     * set the proxy config for Guzzle
     *
     * @param   $proxy
     */
    public function setProxy($proxy) {
        $this->options['proxy'] = $proxy;

        $this->guzzle = $this->createGuzzleClient();
    }

    /**
     * generic request executor
     *
     * @param   string          $method         GET, POST, PUT, DELETE
     * @param   string          $endpointUrl
     * @param   array           $queryString
     * @param   array|string    $body
     * @param   string          $auth           http-signatures to enable http-signature signing
     * @param   string          $contentMD5Mode body or url
     * @param   float           $timeout        timeout in seconds
     * @return Response
     */
    public function request($method, $endpointUrl, $queryString = null, $body = null, $auth = null, $contentMD5Mode = null, $timeout = null) {
        $request = $this->buildRequest($method, $endpointUrl, $queryString, $body, $auth, $contentMD5Mode, $timeout);
        $this->throttler->waitForThrottle();
        $response = $this->guzzle->send($request, ['auth' => $auth, 'timeout' => $timeout]);

        return $this->responseHandler($response);
    }
}


text:
var assert = require('assert'),
    retry = require('../lib/three-times');

function makefn(count) {
    var times = 0;
    return function (done) {
        if (++times === count) {
            done(null, times);
        } else {
            done(times);
        }
    }
}

describe('events', function () {
    it('should succeed after executed three times', function (done) {
        retry(makefn(3)).on('error', function (err) {
            assert.fail();
        }).on('done', function (result) {
            assert.equal(3, result);
            done();
        });
    });
    it('should succeed after executed five times', function (done) {
        retry(makefn(5), 5).on('error', function (err) {
            assert.fail();
        }).on('done', function (result) {
            assert.equal(5, result);
            done();
        });
    });
    it('should fail after executed three times', function (done) {
        retry(makefn(5)).on('error', function (err) {
            assert.equal(3, err);
            done();
        }).on('done', function (result) {
            assert.fail();
        });
    });
});

describe("callbacks", function() {
    it('should succeed after executed once', function (done) {
        retry(makefn(1), function (err, result) {
            assert.equal(null, err);
            assert.equal(1, result);
            done();
        });
    });
    it('should succeed after executed twice', function (done) {
        retry(makefn(2), function (err, result) {
            assert.equal(null, err);
            assert.equal(2, result);
            done();
        });
    });
    it('should succedd after executed five times', function (done) {
        retry(makefn(5), function (err, result) {
            assert.equal(null, err);
            assert.equal(5, result);
            done();
        }, 5);
    });it('should give error after executed three times', function (done) {
        retry(makefn(999), function (err, result) {
            assert.equal(3, err)
            assert.equal(null, result);
            done();
        });
    });
    it('should give error after executed five times', function (done) {
        retry(makefn(999), function (err, result) {
            assert.equal(5, err);
            assert.equal(null, result);
            done();
        }, 5);
    });
});


text:
import React, { Component, PropTypes } from 'react';
import debounce from 'lodash/debounce';
import { t } from '../utils/Helpers';

class HResizer extends Component {
  constructor(props) {
    super(props);

    this.state = {
      dragging: false
    };

    this.stopPropagation = (e) => {
      e.stopPropagation();
    };

    this.handleMouseDown = (e) => {
      e.preventDefault();
      this.setState({dragging: true});

      $(document).off(`mousemove.${this.props.eventScope}`).on(`mousemove.${this.props.eventScope}`, debounce((event) => {
        const $resizer = $(this.refs.resizer);
        const offset = event.pageY - $resizer.offset().top - $resizer.height() / 2;
        let topHeight = this.props.topHeight + offset;
        let bottomHeight = this.props.bottomHeight - offset;
        if (bottomHeight < this.props.minBottomHeight) {
          bottomHeight = this.props.minBottomHeight;
          topHeight = this.props.topHeight + (this.props.bottomHeight - this.props.minBottomHeight);
        }

        if (bottomHeight > this.props.maxBottomHeight) {
          bottomHeight = this.props.maxBottomHeight;
          topHeight = this.props.topHeight + (this.props.bottomHeight - this.props.maxBottomHeight);
        }
        this.props.onResize(topHeight, bottomHeight);
      }, 10));
    };

    this.handleClick = (e) => {
      let topHeight;
      let bottomHeight;
      e.preventDefault();

      if (this.props.bottomOpened) {
        topHeight = this.props.topHeight + this.props.bottomHeight;
        bottomHeight = 0;
      } else {
        topHeight = this.props.preTopHeight;
        bottomHeight = this.props.preBottomHeight;
      }
      this.props.onResize(topHeight, bottomHeight);
    };
  }

  componentDidMount() {
    $(document).on(`mouseup.${this.props.eventScope}`, () => {
      if (this.state.dragging) {
        $(document).off(`mousemove.${this.props.eventScope}`);
        this.setState({dragging: false});
      }
    });
  }

  shouldComponentUpdate() {
    return false;
  }

  render() {
    return (

    );
  }
}

HResizer.propTypes = {
  tagName: PropTypes.string,
  minBottomHeight: PropTypes.number,
  maxBottomHeight: PropTypes.number,
  eventScope: PropTypes.string.isRequired,
  preTopHeight: PropTypes.number.isRequired,
  preBottomHeight: PropTypes.number.isRequired,
  topHeight: PropTypes.number.isRequired,
  bottomHeight: PropTypes.number.isRequired,
  bottomOpened: PropTypes.bool.isRequired,
  onResize: PropTypes.func.isRequired
};

HResizer.defaultProps = {
  tagName: '',
  minBottomHeight: 0,
  maxBottomHeight: 300
};

export default HResizer;


text:
"""
    Widget to display a 2D map of the detector
"""
import wx
import sys
from sas.sasgui.guiframe.utils import format_number
from sas.sasgui.guiframe.events import StatusEvent
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as Canvas
import matplotlib as mpl
from matplotlib import pylab
# FONT size
if sys.platform.count("win32") > 0:
    FONT_VARIANT = 0
else:
    FONT_VARIANT = 1

DEFAULT_CMAP = pylab.cm.get_cmap('jet')

class DetectorDialog(wx.Dialog):
    """
    Dialog box to let the user edit detector settings
    """

    def __init__(self, parent, id=1, base=None, dpi=None,
                 cmap=DEFAULT_CMAP, reset_zmin_ctl=None,
                 reset_zmax_ctl=None, *args, **kwds):
        """
        """
        kwds["style"] = wx.DEFAULT_DIALOG_STYLE
        wx.Dialog.__init__(self, parent, id=1, *args, **kwds)
        self.SetWindowVariant(variant=FONT_VARIANT)
        self.parent = base
        self.dpi = dpi
        self.cmap = cmap
        self.reset_zmin_ctl = reset_zmin_ctl
        self.reset_zmax_ctl = reset_zmax_ctl
        self.label_xnpts = wx.StaticText(self, -1, "Detector width in pixels")
        self.label_ynpts = wx.StaticText(self, -1, "Detector Height in pixels")
        self.label_qmax = wx.StaticText(self, -1, "Q max")
        self.label_zmin = wx.StaticText(self, -1,
                                        "Min amplitude for color map (optional)")
        self.label_zmax = wx.StaticText(self, -1,
                                        "Max amplitude for color map (optional)")
        self.label_beam = wx.StaticText(self, -1,
                                        "Beam stop radius in units of q")
        self.xnpts_ctl = wx.StaticText(self, -1, "")
        self.ynpts_ctl = wx.StaticText(self, -1, "")
        self.qmax_ctl = wx.StaticText(self, -1, "")
        self.beam_ctl = wx.StaticText(self, -1, "")
        self.zmin_ctl = wx.TextCtrl(self, -1, size=(60, 20))
        self.zmin_ctl.Bind(wx.EVT_SET_FOCUS, self.onSetFocus)
        self.zmax_ctl = wx.TextCtrl(self, -1, size=(60, 20))
        self.zmax_ctl.Bind(wx.EVT_SET_FOCUS, self.onSetFocus)
        self.static_line_3 = wx.StaticLine(self, -1)
        self.button_cancel = wx.Button(self, wx.ID_CANCEL, "Cancel")
        self.button_reset = wx.Button(self, wx.NewId(), "Reset")
        self.Bind(wx.EVT_BUTTON, self.resetValues, self.button_reset)
        self.button_ok = wx.Button(self, wx.ID_OK, "OK")
        self.Bind(wx.EVT_BUTTON, self.checkValues, self.button_ok)
        self.__set_properties()
        self.__do_layout()
        self.Fit()

    class Event(object):
        """
        """
        xnpts = 0
        ynpts = 0
        qpax = 0
        beam = 0
        zmin = 0
        zmax = 0
        cmap = None
        sym4 = False

    def onSetFocus(self, event):
        """
        Highlight the txtcrtl
        """
        # Get a handle to the TextCtrl
        widget = event.GetEventObject()
        # Select the whole control, after this event resolves
        wx.CallAfter(widget.SetSelection, -1, -1)

    def resetValues(self, event):
        """
        reset detector info
        """
        try:
            zmin = self.reset_zmin_ctl
            zmax = self.reset_zmax_ctl
            if zmin is None:
                zmin = ""
            if zmax is None:
                zmax = ""
            self.zmin_ctl.SetValue(str(zmin))
            self.zmax_ctl.SetValue(str(zmax))
            self.cmap = DEFAULT_CMAP
            self.cmap_selector.SetStringSelection("jet")
            self._on_select_cmap(event=None)
        except:
            msg = "error occurs while resetting Detector: %s" % sys.exc_value
            wx.PostEvent(self.parent, StatusEvent(status=msg))

    def checkValues(self, event):
        """
        Check the valitidity of zmin and zmax value
        zmax should be a float and zmin less than zmax
        """
        flag = True
        try:
            value = self.zmin_ctl.GetValue()
            self.zmin_ctl.SetBackgroundColour(wx.WHITE)
            self.zmin_ctl.Refresh()
        except:
            flag = False
            wx.PostEvent(self.parent, StatusEvent(status="Enter float value"))
            self.zmin_ctl.SetBackgroundColour("pink")
            self.zmin_ctl.Refresh()
        try:
            value = self.zmax_ctl.GetValue()
            if value and float(value) == 0.0:
                flag = False
                wx.PostEvent(self.parent,
                             StatusEvent(status="Enter number greater than zero"))
                self.zmax_ctl.SetBackgroundColour("pink")
                self.zmax_ctl.Refresh()
            else:
                self.zmax_ctl.SetBackgroundColour(wx.WHITE)
                self.zmax_ctl.Refresh()
        except:
            flag = False
            wx.PostEvent(self.parent, StatusEvent(status="Enter Integer value"))
            self.zmax_ctl.SetBackgroundColour("pink")
            self.zmax_ctl.Refresh()
        if flag:
            event.Skip(True)

    def setContent(self, xnpts, ynpts, qmax, beam,
                   zmin=None, zmax=None, sym=False):
        """
        received value and displayed them

        :param xnpts: the number of point of the x_bins of data
        :param ynpts: the number of point of the y_bins of data
        :param qmax: the maxmimum value of data pixel
        :param beam: the radius of the beam
        :param zmin:  the value to get the minimum color
        :param zmax:  the value to get the maximum color
        :param sym:

        """
        self.xnpts_ctl.SetLabel(str(format_number(xnpts)))
        self.ynpts_ctl.SetLabel(str(format_number(ynpts)))
        self.qmax_ctl.SetLabel(str(format_number(qmax)))
        self.beam_ctl.SetLabel(str(format_number(beam)))
        if zmin is not None:
            self.zmin_ctl.SetValue(str(format_number(zmin)))
        if zmax is not None:
            self.zmax_ctl.SetValue(str(format_number(zmax)))

    def getContent(self):
        """
        return event containing value to reset the detector of a given data
        """
        event = self.Event()
        t_min = self.zmin_ctl.GetValue()
        t_max = self.zmax_ctl.GetValue()
        v_min = None
        v_max = None
        if len(t_min.lstrip()) > 0:
            try:
                v_min = float(t_min)
            except:
                v_min = None
        if len(t_max.lstrip()) > 0:
            try:
                v_max = float(t_max)
            except:
                v_max = None
        event.zmin = v_min
        event.zmax = v_max
        event.cmap = self.cmap
        return event

    def __set_properties(self):
        """
        set proprieties of the dialog window
        """
        self.SetTitle("2D Color Map")
        self.SetSize((600, 595))

    def __do_layout(self):
        """
        fill the dialog window .
        """
        sizer_main = wx.BoxSizer(wx.VERTICAL)
        sizer_button = wx.BoxSizer(wx.HORIZONTAL)
        sizer_params = wx.GridBagSizer(5, 5)
        sizer_colormap = wx.BoxSizer(wx.VERTICAL)
        sizer_selection = wx.BoxSizer(wx.HORIZONTAL)

        iy = 0
        sizer_params.Add(self.label_xnpts, (iy, 0), (1, 1),
                         wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
        sizer_params.Add(self.xnpts_ctl, (iy, 1), (1, 1),
                         wx.EXPAND | wx.ADJUST_MINSIZE, 0)
        iy += 1
        sizer_params.Add(self.label_ynpts, (iy, 0), (1, 1),
                         wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
        sizer_params.Add(self.ynpts_ctl, (iy, 1), (1, 1),
                         wx.EXPAND | wx.ADJUST_MINSIZE, 0)
        iy += 1
        sizer_params.Add(self.label_qmax, (iy, 0), (1, 1),
                         wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
        sizer_params.Add(self.qmax_ctl, (iy, 1), (1, 1),
                         wx.EXPAND | wx.ADJUST_MINSIZE, 0)
        iy += 1
        sizer_params.Add(self.label_beam, (iy, 0), (1, 1),
                         wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
        sizer_params.Add(self.beam_ctl, (iy, 1), (1, 1),
                         wx.EXPAND | wx.ADJUST_MINSIZE, 0)
        iy += 1
        sizer_params.Add(self.label_zmin, (iy, 0), (1, 1),
                         wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
        sizer_params.Add(self.zmin_ctl, (iy, 1), (1, 1),
                         wx.EXPAND | wx.ADJUST_MINSIZE, 0)
        iy += 1
        sizer_params.Add(self.label_zmax, (iy, 0), (1, 1),
                         wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
        sizer_params.Add(self.zmax_ctl, (iy, 1), (1, 1),
                         wx.EXPAND | wx.ADJUST_MINSIZE, 0)
        iy += 1
        self.fig = mpl.figure.Figure(dpi=self.dpi, figsize=(4, 1))
        self.ax1 = self.fig.add_axes([0.05, 0.65, 0.9, 0.15])
        self.norm = mpl.colors.Normalize(vmin=0, vmax=100)
        self.cb1 = mpl.colorbar.ColorbarBase(self.ax1, cmap=self.cmap,
                                             norm=self.norm,
                                             orientation='horizontal')
        self.cb1.set_label('Detector Colors')
        self.canvas = Canvas(self, -1, self.fig)
        sizer_colormap.Add(self.canvas, 0, wx.LEFT | wx.EXPAND, 5)
        self.cmap_selector = wx.ComboBox(self, -1)
        self.cmap_selector.SetValue(str(self.cmap.name))
        maps = sorted(m for m in pylab.cm.datad if not m.endswith("_r"))

        for i, m in enumerate(maps):
            self.cmap_selector.Append(str(m), pylab.get_cmap(m))

        wx.EVT_COMBOBOX(self.cmap_selector, -1, self._on_select_cmap)
        sizer_selection.Add(wx.StaticText(self, -1, "Select Cmap: "), 0,
                            wx.LEFT | wx.ADJUST_MINSIZE, 5)
        sizer_selection.Add(self.cmap_selector, 0, wx.EXPAND | wx.ALL, 10)
        sizer_main.Add(sizer_params, 0, wx.EXPAND | wx.ALL, 5)
        sizer_main.Add(sizer_selection, 0, wx.EXPAND | wx.ALL, 5)
        note = "   Note: This is one time option. " + \
               "It will be reset on updating the image."
        note_txt = wx.StaticText(self, -1, note)
        sizer_main.Add(note_txt, 0, wx.EXPAND | wx.ALL, 5)
        sizer_main.Add(sizer_colormap, 1, wx.EXPAND | wx.ALL, 5)
        sizer_main.Add(self.static_line_3, 0, wx.EXPAND, 0)
        sizer_button.Add(self.button_reset, 0, wx.LEFT | wx.ADJUST_MINSIZE, 100)
        sizer_button.Add(self.button_ok, 0, wx.LEFT | wx.ADJUST_MINSIZE, 10)
        sizer_button.Add(self.button_cancel, 0,
                         wx.LEFT | wx.RIGHT | wx.ADJUST_MINSIZE, 10)
        sizer_main.Add(sizer_button, 0, wx.EXPAND | wx.BOTTOM | wx.TOP, 10)
        self.SetAutoLayout(True)
        self.SetSizer(sizer_main)
        self.Layout()
        self.Centre()
        # end wxGlade

    def _on_select_cmap(self, event):
        """
        display a new cmap
        """
        cmap_name = self.cmap_selector.GetCurrentSelection()
        current_cmap = self.cmap_selector.GetClientData(cmap_name)
        self.cmap = current_cmap
        self.cb1 = mpl.colorbar.ColorbarBase(self.ax1, cmap=self.cmap,
                                             norm=self.norm, orientation='horizontal')
        self.canvas.draw()


text:
#ifndef _IVW_MODULE_EIGENUTILS_DEFINE_H_
#define _IVW_MODULE_EIGENUTILS_DEFINE_H_

#ifdef INVIWO_ALL_DYN_LINK //DYNAMIC
// If we are building DLL files we must declare dllexport/dllimport
#ifdef IVW_MODULE_EIGENUTILS_EXPORTS
#ifdef _WIN32
#define IVW_MODULE_EIGENUTILS_API __declspec(dllexport)
#else //UNIX (GCC)
#define IVW_MODULE_EIGENUTILS_API __attribute__ ((visibility ("default")))
#endif
#else
#ifdef _WIN32
#define IVW_MODULE_EIGENUTILS_API __declspec(dllimport)
#else
#define IVW_MODULE_EIGENUTILS_API
#endif
#endif
#else //STATIC
#define IVW_MODULE_EIGENUTILS_API
#endif

#endif /* _IVW_MODULE_EIGENUTILS_DEFINE_H_ */


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

namespace Chronic.Handlers
{
    public class SRPAHandler : SRPHandler
    {
        public override Span Handle(IList<Token> tokens, Options options)
        {
			if (tokens.First().IsTaggedAs<SeparatorIn>())
				tokens.RemoveAt(0);

            int tokensToSkip = tokens.First().IsTaggedAs<Scalar>() ? 3 : 2;
            var anchorSpan = tokens.Skip(tokensToSkip).GetAnchor(options);
            return Handle(tokens, anchorSpan, options);
        }
    }
}


text:
Write a function that receives a string coded in UTF-8 and returns its first code point as a number.  The function should return nil if the string does not start with a valid UTF-8 sequence.
]]

function firstcodepoint(s)
  function seqlen(s)
    local start = string.byte(s, 1)

    if bit32.band(start, 0x80) == 0x00 then return 1 end
    if bit32.band(start, 0xE0) == 0xC0 then return 2 end
    if bit32.band(start, 0xF0) == 0xE0 then return 3 end
    if bit32.band(start, 0xF8) == 0xF0 then return 4 end
    if bit32.band(start, 0xFC) == 0xF8 then return 5 end
    if bit32.band(start, 0xFE) == 0xFC then return 6 end

    return 0
  end

  function valid(s)
    local len = seqlen(s)

    if len == 0 then return false end

    for i = 2, len do
      if bit32.band(string.byte(s, i), 0xC0) ~= 0x80 then
        return false
      end
    end

    return true
  end

  if not valid(s) then return false end

  local codepoint = bit32.extract(string.byte(s, 1), 0, 7 - seqlen(s))

  for i = 2, seqlen(s) do
    codepoint = bit32.lshift(codepoint, 6)
    codepoint = bit32.bor(codepoint, bit32.extract(string.byte(s, i), 0, 6))
  end

  return codepoint
end

assert("0x20AC" == string.format("0x%X", firstcodepoint("€")))
assert("0x24B62" == string.format("0x%X", firstcodepoint("𤭢")))

print("Everything works!")


text:
using ChameHOT.WebService.Helpers.Models;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Chame.WebService.Helper.Services
{
    public sealed class GraphicsRenderHelper
    {
        public static SizeF MeasureText(Graphics g, RenderItemModel renderItem, float ratio, SizeF size, RectangleF rect)
        {
            var rectR = new RectangleF(rect.Left, rect.Top + size.Height, rect.Width, rect.Height);
            var option = renderItem.TextOption;
            var margin = option.Margin;
            var fontStyle = option.FontWeight.Weight > 500 ? (option.FontSytle.ToDrawingType() | System.Drawing.FontStyle.Bold) : option.FontSytle.ToDrawingType();
            var font = new Font(option.FontFamilyName, option.FontSize / ratio, fontStyle, GraphicsUnit.Pixel);
            var format = new StringFormat()
            {
                Alignment = option.ParagraphAlignment.ToDrawingType(),
                LineAlignment = option.TextAlignment.ToDrawingType()
            };

            var sizeR = g.MeasureString(renderItem.Content, font, new SizeF(rectR.Width, rectR.Height), format);

            return new SizeF((float)(sizeR.Width + margin.Left + margin.Right), (float)(sizeR.Height + margin.Top + margin.Bottom));
        }

        public static void RenderText(Graphics g, RenderItemModel renderItem, float ratio, ref SizeF size, ref RectangleF rect)
        {
            rect = new RectangleF(rect.Left, rect.Top + size.Height, rect.Width, rect.Height);
            var option = renderItem.TextOption;
            var margin = option.Margin;
            var fontStyle = option.FontWeight.Weight > 500 ? (option.FontSytle.ToDrawingType() | System.Drawing.FontStyle.Bold) : option.FontSytle.ToDrawingType();
            var font = new Font(option.FontFamilyName, option.FontSize / ratio, fontStyle, GraphicsUnit.Pixel);
            var brush = new SolidBrush(System.Drawing.Color.FromArgb(option.Foreground.A, option.Foreground.R, option.Foreground.G, option.Foreground.B));
            var format = new StringFormat()
            {
                Alignment = option.ParagraphAlignment.ToDrawingType(),
                LineAlignment = option.TextAlignment.ToDrawingType()
            };

            size = g.MeasureString(renderItem.Content, font, new SizeF(rect.Width, rect.Height), format);

            // Check and change the text alignment
            var renderRect = new RectangleF((float)(rect.Left + margin.Left),
                                  (float)(rect.Top + margin.Top),
                                  (float)(rect.Width + margin.Left + margin.Right),
                                  (float)(rect.Height + margin.Top + margin.Bottom));
            switch (option.HorizontalAlignment)
            {
                case TextHorizontalAlignment.Right:
                    renderRect = new RectangleF((float)(rect.Left + margin.Left + rect.Width - size.Width),
                                                (float)(rect.Top + margin.Top),
                                                (float)(rect.Width + margin.Left + margin.Right),
                                                (float)(rect.Height + margin.Top + margin.Bottom));
                    break;
                case TextHorizontalAlignment.Center:
                    renderRect = new RectangleF((float)(rect.Left + margin.Left + (rect.Width - size.Width) / 2.0),
                                                (float)(rect.Top + margin.Top),
                                                (float)(rect.Width + margin.Left + margin.Right),
                                                (float)(rect.Height + margin.Top + margin.Bottom));
                    break;
            }

            g.DrawString(renderItem.Content, font, brush, renderRect, format);

            size = new SizeF((float)(size.Width + margin.Left + margin.Right), (float)(size.Height + margin.Top + margin.Bottom));
        }
    }
}


text: Node utility library for identifying and scanning hosts on a subnet


text:
package com.amazonaws.services.dlm.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.dlm.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * CrossRegionCopyRetainRuleMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class CrossRegionCopyRetainRuleMarshaller {

    private static final MarshallingInfo<Integer> INTERVAL_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("Interval").build();
    private static final MarshallingInfo<String> INTERVALUNIT_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("IntervalUnit").build();

    private static final CrossRegionCopyRetainRuleMarshaller instance = new CrossRegionCopyRetainRuleMarshaller();

    public static CrossRegionCopyRetainRuleMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(CrossRegionCopyRetainRule crossRegionCopyRetainRule, ProtocolMarshaller protocolMarshaller) {

        if (crossRegionCopyRetainRule == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(crossRegionCopyRetainRule.getInterval(), INTERVAL_BINDING);
            protocolMarshaller.marshall(crossRegionCopyRetainRule.getIntervalUnit(), INTERVALUNIT_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
@interface NNSymlinkTagDirectoryWriter : NNTagDirectoryWriter {

}

@end


text:
package org.jetbrains.plugins.groovy.refactoring.introduce.parameter;

import com.intellij.openapi.application.AccessToken;
import com.intellij.openapi.application.WriteAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Splitter;
import com.intellij.openapi.ui.ValidationInfo;
import com.intellij.openapi.ui.VerticalFlowLayout;
import com.intellij.openapi.util.Ref;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiField;
import com.intellij.psi.PsiType;
import com.intellij.psi.codeStyle.CodeStyleSettingsManager;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.refactoring.BaseRefactoringProcessor;
import com.intellij.refactoring.JavaRefactoringSettings;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.ui.NameSuggestionsField;
import com.intellij.ui.IdeBorderFactory;
import com.intellij.ui.components.JBRadioButton;
import com.intellij.util.ArrayUtil;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.GridBag;
import com.intellij.util.ui.UIUtil;
import gnu.trove.TIntArrayList;
import gnu.trove.TObjectIntHashMap;
import gnu.trove.TObjectIntProcedure;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.groovy.GroovyFileType;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrParametersOwner;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod;
import org.jetbrains.plugins.groovy.refactoring.GrRefactoringError;
import org.jetbrains.plugins.groovy.refactoring.GroovyNamesUtil;
import org.jetbrains.plugins.groovy.refactoring.GroovyRefactoringBundle;
import org.jetbrains.plugins.groovy.refactoring.HelpID;
import org.jetbrains.plugins.groovy.refactoring.extract.ExtractUtil;
import org.jetbrains.plugins.groovy.refactoring.extract.ParameterInfo;
import org.jetbrains.plugins.groovy.refactoring.extract.ParameterTablePanel;
import org.jetbrains.plugins.groovy.refactoring.extract.closure.ExtractClosureFromClosureProcessor;
import org.jetbrains.plugins.groovy.refactoring.extract.closure.ExtractClosureFromMethodProcessor;
import org.jetbrains.plugins.groovy.refactoring.extract.closure.ExtractClosureHelperImpl;
import org.jetbrains.plugins.groovy.refactoring.extract.closure.ExtractClosureProcessorBase;
import org.jetbrains.plugins.groovy.refactoring.introduce.StringPartInfo;
import org.jetbrains.plugins.groovy.refactoring.ui.GrMethodSignatureComponent;
import org.jetbrains.plugins.groovy.refactoring.ui.GrTypeComboBox;
import org.jetbrains.plugins.groovy.settings.GroovyApplicationSettings;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;

import static com.intellij.refactoring.IntroduceParameterRefactoring.*;

public class GrIntroduceParameterDialog extends DialogWrapper {
  private GrTypeComboBox myTypeComboBox;
  private NameSuggestionsField myNameSuggestionsField;
  private JCheckBox myDeclareFinalCheckBox;
  private JCheckBox myDelegateViaOverloadingMethodCheckBox;
  private JBRadioButton myDoNotReplaceRadioButton;
  private JBRadioButton myReplaceFieldsInaccessibleInRadioButton;
  private JBRadioButton myReplaceAllFieldsRadioButton;
  private JPanel myGetterPanel;
  private IntroduceParameterInfo myInfo;
  private TObjectIntHashMap<JCheckBox> toRemoveCBs;

  private GrMethodSignatureComponent mySignature;
  private ParameterTablePanel myTable;
  private JPanel mySignaturePanel;
  private JCheckBox myForceReturnCheckBox;
  private Project myProject;

  private final boolean myCanIntroduceSimpleParameter;

  public GrIntroduceParameterDialog(IntroduceParameterInfo info) {
    super(info.getProject(), true);
    myInfo = info;
    myProject = info.getProject();
    myCanIntroduceSimpleParameter = GroovyIntroduceParameterUtil.findExpr(myInfo) != null || GroovyIntroduceParameterUtil.findVar(myInfo) != null || findStringPart() != null;

    TObjectIntHashMap<GrParameter> parametersToRemove = GroovyIntroduceParameterUtil.findParametersToRemove(info);
    toRemoveCBs = new TObjectIntHashMap<JCheckBox>(parametersToRemove.size());
    for (Object p : parametersToRemove.keys()) {
      JCheckBox cb = new JCheckBox(GroovyRefactoringBundle.message("remove.parameter.0.no.longer.used", ((GrParameter)p).getName()));
      toRemoveCBs.put(cb, parametersToRemove.get((GrParameter)p));
      cb.setSelected(true);
    }

    init();
  }

  @Override
  protected void init() {
    super.init();

    JavaRefactoringSettings settings = JavaRefactoringSettings.getInstance();

    initReplaceFieldsWithGetters(settings);

    myDeclareFinalCheckBox.setSelected(hasFinalModifier());
    myDelegateViaOverloadingMethodCheckBox.setVisible(myInfo.getToSearchFor() != null);

    setTitle(RefactoringBundle.message("introduce.parameter.title"));

    myTable.init(myInfo);

    final GrParameter[] parameters = myInfo.getToReplaceIn().getParameters();
    toRemoveCBs.forEachEntry(new TObjectIntProcedure<JCheckBox>() {
      @Override
      public boolean execute(JCheckBox checkbox, int index) {
        checkbox.setSelected(true);

        final GrParameter param = parameters[index];
        final ParameterInfo pinfo = findParamByOldName(param.getName());
        if (pinfo != null) {
          pinfo.setPassAsParameter(false);
        }
        return true;
      }
    });

    updateSignature();

    if (myCanIntroduceSimpleParameter) {
      mySignaturePanel.setVisible(false);

      //action to hide signature panel if we have variants to introduce simple parameter
      myTypeComboBox.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
          mySignaturePanel.setVisible(myTypeComboBox.isClosureSelected());
          pack();
        }
      });
    }

    final PsiType closureReturnType = inferClosureReturnType();
    if (closureReturnType == PsiType.VOID) {
      myForceReturnCheckBox.setEnabled(false);
      myForceReturnCheckBox.setSelected(false);
    }
    else {
      myForceReturnCheckBox.setSelected(isForceReturn());
    }

    if (myInfo.getToReplaceIn() instanceof GrClosableBlock) {
      myDelegateViaOverloadingMethodCheckBox.setEnabled(false);
      myDelegateViaOverloadingMethodCheckBox.setToolTipText("Delegating is not allowed in closure context");
    }

    pack();
  }

  private static boolean isForceReturn() {
    return GroovyApplicationSettings.getInstance().FORCE_RETURN;
  }

  @Override
  protected JComponent createCenterPanel() {
    JPanel north = new JPanel();
    north.setLayout(new VerticalFlowLayout(VerticalFlowLayout.TOP, 0, 0, true, true));

    final JPanel namePanel = createNamePanel();
    namePanel.setAlignmentX(Component.LEFT_ALIGNMENT);
    north.add(namePanel);

    createCheckBoxes(north);

    myGetterPanel = createFieldPanel();
    myGetterPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
    north.add(myGetterPanel);

    final JPanel root = new JPanel(new BorderLayout());
    mySignaturePanel = createSignaturePanel();
    root.add(mySignaturePanel, BorderLayout.CENTER);
    root.add(north, BorderLayout.NORTH);

    return root;
  }

  private JPanel createSignaturePanel() {
    mySignature = new GrMethodSignatureComponent("", myProject);
    myTable = new ParameterTablePanel() {
      @Override
      protected void updateSignature() {
        GrIntroduceParameterDialog.this.updateSignature();
      }

      @Override
      protected void doEnterAction() {
        clickDefaultButton();
      }

      @Override
      protected void doCancelAction() {
        GrIntroduceParameterDialog.this.doCancelAction();
      }
    };

    mySignature.setBorder(IdeBorderFactory.createTitledBorder(GroovyRefactoringBundle.message("signature.preview.border.title"), false));

    Splitter splitter = new Splitter(true);

    splitter.setFirstComponent(myTable);
    splitter.setSecondComponent(mySignature);

    mySignature.setPreferredSize(new Dimension(500, 100));
    mySignature.setSize(new Dimension(500, 100));

    splitter.setShowDividerIcon(false);

    final JPanel panel = new JPanel(new BorderLayout());
    panel.add(splitter, BorderLayout.CENTER);
    myForceReturnCheckBox = new JCheckBox(UIUtil.replaceMnemonicAmpersand("Use e&xplicit return statement"));
    panel.add(myForceReturnCheckBox, BorderLayout.NORTH);

    return panel;
  }

  private JPanel createFieldPanel() {
    myDoNotReplaceRadioButton = new JBRadioButton(UIUtil.replaceMnemonicAmpersand("Do n&ot replace"));
    myReplaceFieldsInaccessibleInRadioButton = new JBRadioButton(UIUtil.replaceMnemonicAmpersand("Replace fields &inaccessible in usage context"));
    myReplaceAllFieldsRadioButton = new JBRadioButton(UIUtil.replaceMnemonicAmpersand("&Replace all fields"));

    myDoNotReplaceRadioButton.setFocusable(false);
    myReplaceFieldsInaccessibleInRadioButton.setFocusable(false);
    myReplaceAllFieldsRadioButton.setFocusable(false);

    final ButtonGroup group = new ButtonGroup();
    group.add(myDoNotReplaceRadioButton);
    group.add(myReplaceFieldsInaccessibleInRadioButton);
    group.add(myReplaceAllFieldsRadioButton);

    final JPanel panel = new JPanel();
    panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
    panel.add(myDoNotReplaceRadioButton);
    panel.add(myReplaceFieldsInaccessibleInRadioButton);
    panel.add(myReplaceAllFieldsRadioButton);

    panel.setBorder(IdeBorderFactory.createTitledBorder("Replace fields used in expression with their getters", true));
    return panel;
  }

  private JPanel createNamePanel() {
    final GridBag c = new GridBag().setDefaultAnchor(GridBagConstraints.WEST).setDefaultInsets(1, 1, 1, 1);
    final JPanel namePanel = new JPanel(new GridBagLayout());

    final JLabel typeLabel = new JLabel(UIUtil.replaceMnemonicAmpersand("&Type:"));
    c.nextLine().next().weightx(0).fillCellNone();
    namePanel.add(typeLabel, c);

    myTypeComboBox = createTypeComboBox(GroovyIntroduceParameterUtil.findVar(myInfo), GroovyIntroduceParameterUtil.findExpr(myInfo), findStringPart());
    c.next().weightx(1).fillCellHorizontally();
    namePanel.add(myTypeComboBox, c);
    typeLabel.setLabelFor(myTypeComboBox);

    final JLabel nameLabel = new JLabel(UIUtil.replaceMnemonicAmpersand("&Name:"));
    c.nextLine().next().weightx(0).fillCellNone();
    namePanel.add(nameLabel, c);

    myNameSuggestionsField = createNameField(GroovyIntroduceParameterUtil.findVar(myInfo));
    c.next().weightx(1).fillCellHorizontally();
    namePanel.add(myNameSuggestionsField, c);
    nameLabel.setLabelFor(myNameSuggestionsField);

    GrTypeComboBox.registerUpDownHint(myNameSuggestionsField, myTypeComboBox);

    return namePanel;
  }

  private void createCheckBoxes(JPanel panel) {
    myDeclareFinalCheckBox = new JCheckBox(UIUtil.replaceMnemonicAmpersand("Declare &final"));
    myDeclareFinalCheckBox.setFocusable(false);
    panel.add(myDeclareFinalCheckBox);

    myDelegateViaOverloadingMethodCheckBox = new JCheckBox(UIUtil.replaceMnemonicAmpersand("De&legate via overloading method"));
    myDelegateViaOverloadingMethodCheckBox.setFocusable(false);
    panel.add(myDelegateViaOverloadingMethodCheckBox);

    for (Object o : toRemoveCBs.keys()) {
      final JCheckBox cb = (JCheckBox)o;
      cb.setFocusable(false);
      panel.add(cb);
    }
  }

  private GrTypeComboBox createTypeComboBox(GrVariable var, GrExpression expr, StringPartInfo stringPartInfo) {
    GrTypeComboBox box;
    if (var != null) {
      box = GrTypeComboBox.createTypeComboBoxWithDefType(var.getDeclaredType(), var);
    }
    else if (expr != null) {
      box = GrTypeComboBox.createTypeComboBoxFromExpression(expr);
    }
    else if (stringPartInfo != null) {
      box = GrTypeComboBox.createTypeComboBoxFromExpression(stringPartInfo.getLiteral());
    }
    else {
      box = GrTypeComboBox.createEmptyTypeComboBox();
    }

    box.addClosureTypesFrom(inferClosureReturnType(), myInfo.getContext());
    if (expr == null && var == null && stringPartInfo == null) {
      box.setSelectedIndex(box.getItemCount() - 1);
    }
    return box;
  }

  @Nullable
  private PsiType inferClosureReturnType() {
    final ExtractClosureHelperImpl mockHelper =
      new ExtractClosureHelperImpl(myInfo, "__test___n_", false, new TIntArrayList(), false, 0, false, false);
    final PsiType returnType;
    final AccessToken token = WriteAction.start();
    try {
      returnType = ExtractClosureProcessorBase.generateClosure(mockHelper).getReturnType();
    }
    finally {
      token.finish();
    }
    return returnType;
  }

  private NameSuggestionsField createNameField(GrVariable var) {
    List<String> names = new ArrayList<String>();
    if (var != null) {
      names.add(var.getName());
    }
    ContainerUtil.addAll(names, suggestNames());

    return new NameSuggestionsField(ArrayUtil.toStringArray(names), myProject, GroovyFileType.GROOVY_FILE_TYPE);
  }

  private void initReplaceFieldsWithGetters(JavaRefactoringSettings settings) {
    final PsiField[] usedFields = GroovyIntroduceParameterUtil.findUsedFieldsWithGetters(myInfo.getStatements(), getContainingClass());
    myGetterPanel.setVisible(usedFields.length > 0);
    switch (settings.INTRODUCE_PARAMETER_REPLACE_FIELDS_WITH_GETTERS) {
      case REPLACE_FIELDS_WITH_GETTERS_ALL:
        myReplaceAllFieldsRadioButton.setSelected(true);
        break;
      case REPLACE_FIELDS_WITH_GETTERS_INACCESSIBLE:
        myReplaceFieldsInaccessibleInRadioButton.setSelected(true);
        break;
      case REPLACE_FIELDS_WITH_GETTERS_NONE:
        myDoNotReplaceRadioButton.setSelected(true);
        break;
    }
  }

  private void updateSignature() {
    StringBuilder b = new StringBuilder();
    b.append("{ ");
    String[] params = ExtractUtil.getParameterString(myInfo, false);
    for (int i = 0; i < params.length; i++) {
      if (i > 0) {
        b.append("  ");
      }
      b.append(params[i]);
      b.append('\n');
    }
    b.append(" ->\n}");
    mySignature.setSignature(b.toString());
  }

  @Override
  protected ValidationInfo doValidate() {
    final String text = getEnteredName();
    if (!GroovyNamesUtil.isIdentifier(text)) {
      return new ValidationInfo(GroovyRefactoringBundle.message("name.is.wrong", text), myNameSuggestionsField);
    }

    if (myTypeComboBox.isClosureSelected()) {
      final Ref<ValidationInfo> info = new Ref<ValidationInfo>();
      toRemoveCBs.forEachEntry(new TObjectIntProcedure<JCheckBox>() {
        @Override
        public boolean execute(JCheckBox checkbox, int index) {
          if (!checkbox.isSelected()) return true;

          final GrParameter param = myInfo.getToReplaceIn().getParameters()[index];
          final ParameterInfo pinfo = findParamByOldName(param.getName());
          if (pinfo == null || !pinfo.passAsParameter()) return true;

          final String message = GroovyRefactoringBundle
            .message("you.cannot.pass.as.parameter.0.because.you.remove.1.from.base.method", pinfo.getName(), param.getName());
          info.set(new ValidationInfo(message));
          return false;
        }
      });
      if (info.get() != null) {
        return info.get();
      }
    }

    return null;
  }

  @Nullable
  private ParameterInfo findParamByOldName(String name) {
    for (ParameterInfo info : myInfo.getParameterInfos()) {
      if (name.equals(info.getOldName())) return info;
    }
    return null;
  }

  @Nullable
  private PsiClass getContainingClass() {
    final GrParametersOwner toReplaceIn = myInfo.getToReplaceIn();
    if (toReplaceIn instanceof GrMethod) {
      return ((GrMethod)toReplaceIn).getContainingClass();
    }
    else {
      return PsiTreeUtil.getContextOfType(toReplaceIn, PsiClass.class);
    }
  }

  private boolean hasFinalModifier() {
    final Boolean createFinals = JavaRefactoringSettings.getInstance().INTRODUCE_PARAMETER_CREATE_FINALS;
    return createFinals == null ? CodeStyleSettingsManager.getSettings(myProject).GENERATE_FINAL_PARAMETERS : createFinals.booleanValue();
  }

  @Override
  public void doOKAction() {
    saveSettings();

    super.doOKAction();

    final GrParametersOwner toReplaceIn = myInfo.getToReplaceIn();

    final GrExpression expr = GroovyIntroduceParameterUtil.findExpr(myInfo);
    final GrVariable var = GroovyIntroduceParameterUtil.findVar(myInfo);
    final StringPartInfo stringPart = findStringPart();

    if (myTypeComboBox.isClosureSelected() || expr == null && var == null && stringPart == null) {
      GrIntroduceParameterSettings settings = new ExtractClosureHelperImpl(myInfo,
                                                                           getEnteredName(),
                                                                           myDeclareFinalCheckBox.isSelected(),
                                                                           getParametersToRemove(),
                                                                           myDelegateViaOverloadingMethodCheckBox.isSelected(),
                                                                           getReplaceFieldsWithGetter(),
                                                                           myForceReturnCheckBox.isSelected(),
                                                                           myTypeComboBox.getSelectedType() == null);
      if (toReplaceIn instanceof GrMethod) {
        invokeRefactoring(new ExtractClosureFromMethodProcessor(settings));
      }
      else {
        invokeRefactoring(new ExtractClosureFromClosureProcessor(settings));
      }
    }
    else {

      GrIntroduceParameterSettings settings = new GrIntroduceExpressionSettingsImpl(myInfo,
                                                                                getEnteredName(),
                                                                                myDeclareFinalCheckBox.isSelected(),
                                                                                getParametersToRemove(),
                                                                                myDelegateViaOverloadingMethodCheckBox.isSelected(),
                                                                                getReplaceFieldsWithGetter(),
                                                                                expr,
                                                                                var,
                                                                                myTypeComboBox.getSelectedType(),
                                                                                myForceReturnCheckBox.isSelected());
      if (toReplaceIn instanceof GrMethod) {
        invokeRefactoring(new GrIntroduceParameterProcessor(settings));
      }
      else {
        invokeRefactoring(new GrIntroduceClosureParameterProcessor(settings));
      }
    }
  }

  private String getEnteredName() {
    return myNameSuggestionsField.getEnteredName();
  }

  private void saveSettings() {
    final JavaRefactoringSettings settings = JavaRefactoringSettings.getInstance();
    settings.INTRODUCE_PARAMETER_CREATE_FINALS = myDeclareFinalCheckBox.isSelected();
    if (myGetterPanel.isVisible()) {
      settings.INTRODUCE_PARAMETER_REPLACE_FIELDS_WITH_GETTERS = getReplaceFieldsWithGetter();
    }
    if (myForceReturnCheckBox.isEnabled() && mySignaturePanel.isVisible()) {
      GroovyApplicationSettings.getInstance().FORCE_RETURN = myForceReturnCheckBox.isSelected();
    }
  }

  protected void invokeRefactoring(BaseRefactoringProcessor processor) {
    final Runnable prepareSuccessfulCallback = new Runnable() {
      public void run() {
        close(DialogWrapper.OK_EXIT_CODE);
      }
    };
    processor.setPrepareSuccessfulSwingThreadCallback(prepareSuccessfulCallback);
    processor.setPreviewUsages(false);
    processor.run();
  }

  @NotNull
  public LinkedHashSet<String> suggestNames() {
    GrVariable var = GroovyIntroduceParameterUtil.findVar(myInfo);
    GrExpression expr = GroovyIntroduceParameterUtil.findExpr(myInfo);
    StringPartInfo stringPart = findStringPart();

    return GroovyIntroduceParameterUtil.suggestNames(var, expr, stringPart, myInfo.getToReplaceIn(), myProject);
  }

  private int getReplaceFieldsWithGetter() {
    if (myDoNotReplaceRadioButton.isSelected()) return REPLACE_FIELDS_WITH_GETTERS_NONE;
    if (myReplaceFieldsInaccessibleInRadioButton.isSelected()) return REPLACE_FIELDS_WITH_GETTERS_INACCESSIBLE;
    if (myReplaceAllFieldsRadioButton.isSelected()) return REPLACE_FIELDS_WITH_GETTERS_ALL;
    throw new GrRefactoringError("no check box selected");
  }

  @Override
  public JComponent getPreferredFocusedComponent() {
    return myNameSuggestionsField;
  }

  @Override
  protected String getHelpId() {
    return HelpID.GROOVY_INTRODUCE_PARAMETER;
  }

  private TIntArrayList getParametersToRemove() {
    TIntArrayList list = new TIntArrayList();
    for (Object o : toRemoveCBs.keys()) {
      if (((JCheckBox)o).isSelected()) {
        list.add(toRemoveCBs.get((JCheckBox)o));
      }
    }
    return list;
  }

  private StringPartInfo findStringPart() {
    return myInfo.getStringPartInfo();
  }

}


text:
package pk.com.habsoft.robosim.filters.core.values;

import pk.com.habsoft.robosim.filters.core.Attribute;

/**
 * A discrete value subclass in which discrete values are stored as int values.
 * The int values correspond to the attributes categorical list of discrete
 * values, so the int values should always be >= 0 unless it is unset, which
 * is specified by a value of -1.
 *
 * @author James MacGlashan
 *
 */
public class DiscreteValue extends OOMDPValue implements Value {
    public static final int UNSET = -1;
    /**
     * The discrete value stored as an integer. If the attribute defines
     * categorical values with strings, this int value represents the index in
     * the list of categorical values. The default value of -1 indicates an
     * unset attribute value.
     */
    protected final int discVal;

    /**
     * Initializes this value to be an assignment for Attribute attribute.
     *
     * @param attribute
     */
    public DiscreteValue(Attribute attribute) {
        super(attribute);
        this.discVal = UNSET;
    }

    /**
     * Initializes this value as a copy from the source Value object v.
     *
     * @param v
     *            the source Value to make this object a copy of.
     */
    public DiscreteValue(DiscreteValue v) {
        super(v);
        DiscreteValue dv = v;
        this.discVal = dv.discVal;
    }

    public DiscreteValue(Attribute attribute, int discVal) {
        super(attribute);
        this.discVal = discVal;
    }

    @Override
    public boolean valueHasBeenSet() {
        return this.discVal != UNSET;
    }

    @Override
    public Value copy() {
        return new DiscreteValue(this);
    }

    @Override
    public Value setValue(int v) {
        return new DiscreteValue(this.attribute, v);
    }

    @Override
    public Value setValue(double v) {
        return new DiscreteValue(this.attribute, (int) v);
    }

    @Override
    public Value setValue(boolean v) {
        int intV = (v) ? 1 : 0;
        return new DiscreteValue(this.attribute, intV);
    }

    @Override
    public Value setValue(String v) {
        Integer intv = attribute.discValuesHash.get(v);
        if (intv == null) {
            throw new RuntimeException("String value " + v + " is not applicable for attribute " + this.attribute.name);
        }
        return new DiscreteValue(this.attribute, intv);
    }

    @Override
    public int getDiscVal() {
        if (this.discVal == -1) {
            throw new UnsetValueException();
        }
        return this.discVal;
    }

    @Override
    public StringBuilder buildStringVal(StringBuilder builder) {
        if (this.discVal == -1) {
            throw new UnsetValueException();
        }
        return builder.append(attribute.discValues.get(discVal));
    }

    @Override
    public double getNumericRepresentation() {
        if (this.discVal == -1) {
            throw new UnsetValueException();
        }
        return (double) this.discVal;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + discVal;
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }

        if (!(obj instanceof DiscreteValue)) {
            return false;
        }

        DiscreteValue op = (DiscreteValue) obj;
        if (!op.attribute.equals(attribute)) {
            return false;
        }

        return discVal == op.discVal;

    }

    @Override
    public boolean getBooleanValue() {
        return this.discVal != 0;
    }

}


text:
#include "net/instaweb/rewriter/public/strip_subresource_hints_filter.h"

#include "net/instaweb/rewriter/public/domain_lawyer.h"
#include "net/instaweb/rewriter/public/rewrite_driver.h"
#include "net/instaweb/rewriter/public/rewrite_options.h"
#include "pagespeed/kernel/base/scoped_ptr.h"
#include "pagespeed/kernel/base/string_util.h"
#include "pagespeed/kernel/html/html_element.h"
#include "pagespeed/kernel/html/html_name.h"
#include "pagespeed/kernel/http/google_url.h"

namespace net_instaweb {

StripSubresourceHintsFilter::StripSubresourceHintsFilter(RewriteDriver* driver)
    : driver_(driver),
      delete_element_(nullptr),
      remove_script_(false),
      remove_style_(false),
      remove_image_(false),
      remove_any_(false) {}

StripSubresourceHintsFilter::~StripSubresourceHintsFilter() {}

void StripSubresourceHintsFilter::StartDocument() {
  const RewriteOptions* options = driver_->options();
  remove_script_ = driver_->can_modify_urls() && !options->js_preserve_urls();
  remove_style_ = driver_->can_modify_urls() && !options->css_preserve_urls();
  remove_image_ = driver_->can_modify_urls() && !options->image_preserve_urls();
  remove_any_ = remove_script_ || remove_style_ || remove_image_;
  delete_element_ = nullptr;

  // TODO(jefftk): replace can_modify_urls() with can_modify_js_urls(),
  // can_modify_css_urls(), and can_modify_image_urls() so that if you, say,
  // disable all js-modifying filters then js hints won't be stripped.  Right
  // now to get this behavior you need to explicitly turn on PreserveJsUrls.
}

bool StripSubresourceHintsFilter::ShouldStrip(HtmlElement* element) {
  // Strip:
  //   <link rel=subresource href=...>       regardless
  //   <link rel=preload as=script href=...> unless preserve scripts
  //   <link rel=preload as=style href=...>  unless preserve styles
  //   <link rel=preload as=image href=...>  unless preserve images
  //
  // Don't strip other kinds of rel=preload hints, because we don't change
  // their urls, so existing ones are still valid.
  if (remove_any_ && !delete_element_ &&
      element->keyword() == HtmlName::kLink) {
    const char* rel_value = element->AttributeValue(HtmlName::kRel);
    if (rel_value != nullptr) {
      if (StringCaseEqual(rel_value, "subresource")) {
        return true;
      } else if (StringCaseEqual(rel_value, "preload")) {
        const char* as_value = element->AttributeValue(HtmlName::kAs);
        if (as_value != nullptr) {
          return ((remove_script_ && StringCaseEqual(as_value, "script")) ||
                  (remove_style_ && StringCaseEqual(as_value, "style")) ||
                  (remove_image_ && StringCaseEqual(as_value, "image")));
        }
      }
    }
  }
  return false;
}

void StripSubresourceHintsFilter::StartElement(HtmlElement* element) {
  if (ShouldStrip(element)) {
    const RewriteOptions* options = driver_->options();
    const char* resource_url = element->AttributeValue(HtmlName::kHref);
    if (!resource_url) {
      // There's either no href attr, or one that we can't decode (utf8 etc).
      // One way this could happen is if we have a url-encoded utf8 url in an
      // img tag and a utf8 encoded url in the subresource tag.  Delete the
      // link to be on the safe side.
      driver_->DeleteNode(element);
    } else {
      const GoogleUrl& base_url = driver_->decoded_base_url();
      GoogleUrl resolved_resource_url(base_url, resource_url);
      if (options->IsAllowed(resolved_resource_url.Spec()) &&
          options->domain_lawyer()->IsDomainAuthorized(base_url,
                                                       resolved_resource_url)) {
        driver_->DeleteNode(element);
      }
    }
  }
}

}  // namespace net_instaweb


text:
from oslo.config import cfg
import pecan

from fuel_plugin.ostf_adapter.storage import engine
from fuel_plugin.ostf_adapter.wsgi import access_control
from fuel_plugin.ostf_adapter.wsgi import hooks

CONF = cfg.CONF

def setup_config(custom_pecan_config):
    """Updates defaults values for pecan server
    by those supplied via command line arguments
    when ostf-server is started
    """
    config_to_use = {
        'server': {
            'host': CONF.adapter.server_host,
            'port': CONF.adapter.server_port
        },
        'dbpath': CONF.adapter.dbpath,
        'debug': CONF.debug,
        'debug_tests': CONF.debug_tests,
        'lock_dir': CONF.adapter.lock_dir,
        'nailgun': {
            'host': CONF.adapter.nailgun_host,
            'port': CONF.adapter.nailgun_port
        },
        'app': {
            'root': 'fuel_plugin.ostf_adapter.wsgi.root.RootController',
            'modules': ['fuel_plugin.ostf_adapter.wsgi']
        },
    }
    config_to_use.update(custom_pecan_config)
    pecan.conf.update(config_to_use)

def setup_app(config=None, session=None):
    setup_config(config or {})
    session = session or engine.get_session(pecan.conf.dbpath)
    app_hooks = [
        hooks.CustomTransactionalHook(session),
        hooks.AddTokenHook()
    ]
    app = pecan.make_app(
        pecan.conf.app.root,
        debug=pecan.conf.debug,
        force_canonical=True,
        hooks=app_hooks,
    )
    return access_control.setup(app)