text:
#!/usr/local/bin/php
<?php // $Id: make.php 906 2007-08-04 22:33:21Z fred $
############################################################################
#    Copyright (C) 2006-2007 by the Framewerk Development Group            #
#    info@framewerk.org                                                    #
#                                                                          #
#    Permission is hereby granted, free of charge, to any person obtaining #
#    a copy of this software and associated documentation files (the       #
#    "Software"), to deal in the Software without restriction, including   #
#    without limitation the rights to use, copy, modify, merge, publish,   #
#    distribute, sublicense, and#or sell copies of the Software, and to    #
#    permit persons to whom the Software is furnished to do so, subject to #
#    the following conditions:                                             #
#                                                                          #
#    The above copyright notice and this permission notice shall be        #
#    included in all copies or substantial portions of the Software.       #
#                                                                          #
#    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       #
#    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    #
#    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.#
#    IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR     #
#    OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, #
#    ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR #
#    OTHER DEALINGS IN THE SOFTWARE.                                       #
############################################################################

  define('NEWLINE', "\n");
  define('VERSION', '1.1');

  // Gather our arguements into a nice little array ;-)
  $options            = array();
  $options['with']    = array();
  $options['without'] = array();

  unset($argv[0]);
  foreach( $argv as $arg )
  {
    if ( substr($arg, 0, 2) == '--' )
    {
      $arg = substr($arg, 2);
      if ( strpos($arg, '=') !== false )
      {
        $tmp = explode('=', $arg, 2);
        $options[$tmp[0]] = $tmp[1];
      } elseif ( strpos($arg, '-') !== false ) {
        $tmp = explode('-', $arg, 2);
        $options[$tmp[0]][$tmp[1]] = true;
      } else {
        $options[$arg] = true;
      }
    }
  }

  // Return help document
  if ( $options['help'] )
  {
    $message = <<<HELPMESSAGE
Usage: make.php <Application Name> [options]

Options:
--type=<type>         Set the type of Application
--theme=<name>        Name of theme to create default theme object files in
--ladder=<table>      Generate a basic 'Lazy Add Edit Remove' Object
--keyword=<keyword>   Keyword to add to site.xml document

--with-dom            Instance DOMDocument
--with-registry       Instance fRegistry for the Application settings

--without-js          Disable creation of default JavaScript Object File
--without-css         Disable creation of default CSS Object File
--without-dom         Disable DOMDocument Instance when using Application
                      type of "xml"
--without-xsl         Disable XSL output when using DOM in a regular
                      interface

--version             Print version information and exit
--help                Print help (this message) and exit

HELPMESSAGE;
    die($message);
  }

  // Return utilities version
  if ( $options['version'] )
  {
    die('Application Generator Version ' . VERSION . '.' . NEWLINE);
  }

  // Function for printing messages
  function msg($msg = '', $exit = false)
  {
    if ( $msg != '' )
    {
      print('[Framewerk] :: ' . $msg . NEWLINE);
    }
    if ( $exit )
    {
      exit();
    }
    return true;
  }

  // Make sure framewerk Applications directory exists
  if ( !file_exists('Applications') )
  {
    msg('(Fatal Error) -> Missing Framewerk Applications Directory.', true);
  }

  // Make sure framewerk configuration exists
  if ( !file_exists('Configuration/registry.xml') )
  {
    msg('(Fatal Error) -> Missing Framewerk "registry.xml" file.', true);
  }

  // Load configuration document
  if ( !$xml = simplexml_load_file('Configuration/registry.xml') )
  {
    msg('(Fatal Error) -> Invalid "registry.xml" file.', true);
  }

  // Make sure this is a valid Application name
  if ( !preg_match('/^[a-z][0-9a-z]+$/i', ($applicationName = $argv[1])) )
  {
    msg('(Fatal Error) -> Invalid Application name supplied.', true);
  }

  // Check if an Application with this name already exists
  if ( file_exists('Applications/' . $applicationName . '.inc') )
  {
    msg('(Fatal Error) -> There is already an Application existing with that name.', true);
  }

  // If no type was specified and a ladder exists, we'll assume this is going to be an admin application
  if ( !strlen($options['type']) && strlen($options['ladder']) )
  {
    $options['type'] = 'admin';
  }

  // Decide what type of Application this is and create some shortcuts
  $isXML = false;
  $isAdmin = false;
  $useXSL = false;

  switch( strtolower($options['type']) )
  {
    case 'admin':
      $isAdmin = true;
      $applicationType = 'fAdminApplication';
      break;
    case 'xml':
      $isXML = true;
      $applicationType = 'fXMLApplication';
      break;
    default:
      $applicationType = 'fApplication';
  }

  msg('Initialize Application of Type "' . $applicationType . '"');

  // Start of Application template
  $classTemplate = <<<TEMPLATE
<?php
/**
 * $applicationName
 *
 * This is some default Application description text.
 *
 * @author     My Name <myname@mydomain.com>
 * @link       http://www.mywebsite.com
 * @license    Unknown
 * @copyright  Unknown
 * @package    Engine
 * @subpackage Applications
 * @uses       $applicationType
 */

class $applicationName extends $applicationType
{
  /**
   * This function is executed when the Application is requested.
   *
   * @returns  (boolean)
   */
  public function execute()
  {

TEMPLATE;

  // Set page name template
  $classTemplate .= <<<TEMPLATE
    // Set page name
    \$this->pageName('$applicationName');

TEMPLATE;

  if ( $isAdmin )
  {
    // Set view permission template
    $classTemplate .= <<<TEMPLATE

    // Set the permission for viewing this Application
    \$this->requirePermission('Administrator');

TEMPLATE;
  }

  // Add a basic registry template
  if ( $options['with']['registry'] )
  {
    $classTemplate .= <<<TEMPLATE

    // Load registry settings for this Application
    // To access registry values,  simply use: \$appRegistry->valuesKey;
    \$appRegistry = new fRegistry('$applicationName');

TEMPLATE;
  }

  // Add CSS Application Object File
  if ( !$options['without']['css'] )
  {
    msg('Adding CSS Application Object File');

    $classTemplate .= <<<TEMPLATE

    // Add Application CSS File
    \$this->fTheme->addObjectCSSFile('$applicationName');

TEMPLATE;
  }

  // Add JavaScript Application Object File
  if ( !$options['without']['js'] )
  {
    msg('Adding JavaScript Application Object File');

    $classTemplate .= <<<TEMPLATE

    // Add Application JavaScript File
    \$this->fTheme->addObjectJSFile('$applicationName');

TEMPLATE;
  }

  if ( ($isXML && !$options['without']['dom']) || $options['with']['dom'] )
  {
    msg('Creating Basic DOM Structure');

    // Create basic DOM structure
    $classTemplate .= <<<TEMPLATE

    // Instance DOM document
    \$dom = new DOMDocument('1.0');
    \$dom->formatOutput = true;
    \$dom->preserveWhiteSpace = false;

    // Create root document node
    \$rootNode = \$dom->createElement('$applicationName');

    // Output XML

TEMPLATE;

    if ( $isXML || $options['without']['xsl'] )
    {
      $classTemplate .= '    $this->output($rootNode);' . NEWLINE;
    } else {
      $useXSL = true;
      $classTemplate .= '    $this->output($rootNode, true, \'' . $applicationName . '\');' . NEWLINE;
    }
  }

  // Admin related Application template code
  if ( $isAdmin )
  {
    // If a Lazy Add Edit Remove was specified generated some basic Ladder code
    if ( strlen($options['ladder']) )
    {
      msg('Adding Lazy Add Edit Remove Instance');

      //fixme: use Registry('tPDO') instead
      $pdo = new PDO($xml->PDO->dsn, $xml->PDO->username, (isset($xml->PDO->password) ? $xml->PDO->password : NULL));
      $query = $pdo->prepare('SELECT f.attname as field FROM pg_tables t JOIN pg_class c ON c.relname = t.tablename JOIN pg_attribute f ON c.oid = f.attrelid WHERE relkind = \'r\' and f.attnum > 0 AND t.schemaname = \'public\' AND t.tablename = :table;');
      $query->bindParam(':table', $options['ladder']);
      $query->execute();

      $classTemplate .= <<<TEMPLATE

    // Instance a copy of 'Lazy Add Edit Remove' for the table '{$options['ladder']}' and send the output
    // You can control and expand upon the Ladder Output by setting meta options on the fields.  Some basic
    // meta options are included as examples; however, no meta options are required for a Ladder to function.
    \$fLadder = new fLadder('{$options['ladder']}');
    \$fLadder->name = '$applicationName - {$options['ladder']}';

TEMPLATE;

      if ( $data = $query->fetchAll(PDO::FETCH_OBJ) )
      {
        foreach( $data as $field )
        {
          $classTemplate .= '    $fLadder->meta[\'' . $field->field . '\'][\'label\'] = \'' . ucfirst($field->field) . '\';' . NEWLINE;
        }
      }

      $classTemplate .= <<<TEMPLATE
    \$this->output(\$fLadder->buildOutput());

TEMPLATE;
    }
  }

  // End of Application
  $classTemplate .= <<<TEMPLATE

    return true;
  }
}
?>
TEMPLATE;

  // Try to write the Application, if it can't be written exit and don't create anything else
  if ( !file_put_contents('Applications/AddOns/' . $applicationName . '.inc', $classTemplate) )
  {
    msg('(Fatal Error) -> There was an error writing the Application Template,  check permissions and try again.', true);
  }

  // Figure out what theme should be used for creating JS/CSS empty templates
  if ( strlen($options['theme']) )
  {
    $theme = $options['theme'];
  } elseif ( $isAdmin ) {
    $theme = strval($xml->site->theme->administration);
  } else {
    $theme = strval($xml->site->theme->default);
  }

  // Strip slashes from keyword
  $options['keyword'] = trim($options['keyword'], '/');

  // If keyword is set try and add site.xml entry
  if ( strlen($options['keyword']) )
  {
    // Instance new DOMDocument
    $dom = new DOMDocument();
    $dom->preserveWhiteSpace = false;
    $dom->formatOutput = true;
    $dom->load('Configuration/site.xml');

    // Instance XPath
    $xpath = new DOMXPath($dom);
    $root = $xpath->query('/site')->item(0);

    if ( $isAdmin )
    {
      $adminURI = '/admin'; // @todo  automatically figure this out...
      $result = $xpath->evaluate('count(/site/key[@uri="' . $adminURI . '"]/key[@uri="/' . $options['keyword'] . '"])');
    } else {
      $result = $xpath->evaluate('count(/site/key[@uri="/' . $options['keyword'] . '"])');
    }
    if ( $result > 0 )
    {
      msg('The keyword you have specified already exists,  site.xml will not be created.');
    } else {
      msg('Adding site.xml keyword');

      // Create basic key element
      $key = $dom->createElement('key');
      $key->setAttribute('uri', '/' . $options['keyword']);
      $key->setAttribute('visible', '1');

      // If this is an Admin Application set default permission to 'Administrator'
      if ( $isAdmin )
      {
        $key->setAttribute('permission', 'Administrator');
      }

      // Set title and class key nodes
      $key->appendChild($dom->createElement('title', $applicationName));
      $key->appendChild($dom->createElement('class', $applicationName));

      // Decide where the key should be entered
      if ( $isAdmin )
      {
        // Append the new key as a child of the admin 'key' node
        $xpath->query('/site/key[@uri="'.$adminURI.'"]')->item(0)->appendChild($key);
      } else {
        // Insert the new key before the last 'key' node in the document.
        $last = $xpath->query('/site/key[last()]');
        $root->insertBefore($key, $last->item(0));
      }

      // Save site.xml
      if ( $dom->save('Configuration/site.xml') === false )
      {
        msg('Could not add specified keyword to "site.xml" document.  Check permissions.');
      }
    }
  }

  if ( !file_exists('Themes/' . $theme) )
  {
    msg('The theme "' . $theme . '" does not exist.');
  } else {
    if ( !$options['without']['js'] )
    {
      if ( !file_put_contents('Themes/' . $theme . '/JavaScript/' . $applicationName . '.js', '/* ' .  $applicationName . ' - JavaScript Object File */' . NEWLINE) === false )
      {
        msg('Unable to write JavaScript file.');
      }
    }
    if ( !$options['without']['css'] )
    {
      if ( file_put_contents('Themes/' . $theme . '/CSS/' . $applicationName . '.css', '/* ' .  $applicationName . ' - CSS Object File */' . NEWLINE) === false )
      {
        msg('Unable to write CSS file.');
      }
    }
    if ( $useXSL )
    {
      $template = <<<XSLTEMPLATE
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output encoding="ISO-8859-15" omit-xml-declaration="yes" method="xml" version="1.0" indent="yes" />

  <xsl:template match="$applicationName">
  </xsl:template>

</xsl:stylesheet>
XSLTEMPLATE;
      if ( file_put_contents('Applications/XSL/' . $applicationName . '.xsl', $template) === false )
      {
        msg('Unable to write XSL stylesheet.');
      }
    }
  }

  msg('Successfully created a new Application called "' . $applicationName . '".', true);


text:
var request = require("superagent"),
  cheerio = require("cheerio"),
  url = "http://www.adp.com/worldwide.aspx",
  selector = "div#col-content tr span",
  fs = require("fs"),
  q = require("q"),
  MAGNITUDE = 0.1,
  BATCH_SIZE = 5,
  RATE_DELAY = 1000;

// Get geolocation
var geocoderProvider = 'google';
var httpAdapter = 'http';

var geocoder = require('node-geocoder')(geocoderProvider, httpAdapter);

var output = [];
var errors = [];

var countries, population = {}, A = Infinity, B = 0, a = 0.05, b = 0.2;

function GetMagnitude(x) {
  var entry;
  if (x.country && x.country.toLowerCase()) {
    var country = x.country.toLowerCase();
    entry = population[country];
    if (entry && entry.norm !== undefined && entry.norm !== null) {
      return entry.norm;
    } else {
      console.log("NO NORM FOR", JSON.stringify(x, null, 2));
      return a;
    }
  } else {
    console.log("UNKNOWN POPULATION FOR", JSON.stringify(x, null, 2));
    return a;
  }
}

function Go(countries, x) {
  var size = 0;
  if (x + BATCH_SIZE < countries.length) {
    size = x + BATCH_SIZE;
  } else {
    size = countries.length;
  }
  if (x < countries.length) {
    geocoder.batchGeocode(countries.slice(x, size), function(err, results) {
      var locations, l;
      //console.log(err, results);
      //console.log("RESULTS", results);
      console.log("BATCH", x / BATCH_SIZE);
      for (var r = 0; r < results.length; r++) {
        if (r.error) {
          errors.push(r.error);
        } else {
          locations = results[r].value;
          if (locations.length > 1) {
            var idx = 0;
            // tweak to get correct location for bahamas
            if (countries[r] === "bahamas") idx = 1;
            console.log("FOUND > 1 GEOCODE: ", countries[r], JSON.stringify(results[r].value.map(function (e) {
              return e.country;
            }), null, 2));
            l = locations[idx];
            output.push(l.latitude, l.longitude, GetMagnitude(l));
          } else {
            l = locations[0];
            output.push(l.latitude, l.longitude, GetMagnitude(l));
          }
        }
      }
      setTimeout(function() { Go(countries, x + BATCH_SIZE) }, RATE_DELAY);
    });
  } else {
    var series = [["ADP Countries", output]];
    console.log("SERIES", series);
    fs.writeFile (__dirname + "/src/www/assets/countries.json", JSON.stringify(series, null, 2));
  }

}

request
  .get(url)
  .end(function(err, res) {
    if (err) {
      console.log(err);
    } else {
      // Get ADP countries
      var $ = cheerio.load(res.text);
      countries = $(selector).map(function(i, c) {
        return { address: $(c).text().toLowerCase() };
      }).get();

      request.get("http://data.worldbank.org/indicator/SP.POP.TOTL")
        .end(function(err, res) {
          //console.log("GOT HERE!", res.text);
          var row, str, val, name;
          $ = cheerio.load(res.text);
          $("table.views-table tr").each(function(i, c) {
            row = $(c);
            str = row.find("td.views-field-wbapi-data-value-2013 span").text().replace(/\,/gi, "");
            val = str === "" ? 0 : parseInt(str);
            A = val < A && val != 0 ? val : A; // min
            B = val > B ? val : B; // max
            name = row.find("td.views-field-country-value a").text().toLowerCase();
            // cleanse data
            if (name.indexOf("bahamas") > -1) name = "the bahamas";
            if (name.indexOf("venezuela") > -1) name = "venezuela";
            if (name.indexOf("indonesia") > -1) name = "republic of indonesia";
            if (name.indexOf("hong kong") > -1) name = "hong kong";
            if (name.indexOf("macao") > -1) name = "macau";
            if (name.indexOf("macedonia") > -1) name = "macedonia (fyrom)";
            if (name.indexOf("egypt") > -1) name = "egypt";
            if (name.indexOf("slovak republic") > -1) name = "slovakia";
            if (name.indexOf("russian federation") > -1) name = "russia";
            if (name.indexOf("korea, dem. rep.") > -1) name = "south korea";

            population[name] = { abs: val };
          });
          population.jersey = { abs: 99500 };
          population.taiwan = { abs: 23370000 };
          population.guernsey = { abs: 65345 };
          Object.keys(population).forEach(function(k) {
            //console.log(k);
            //population[k].norm = a + ((population[k].abs - A) / (B - A)) * (b - a);
            population[k].norm = a + (Math.log(population[k].abs - A) / Math.log(B - A)) * (b - a);
            //population[k].norm = a + (Math.sqrt(population[k].abs - A) / Math.sqrt(B - A)) * (b - a);
          });
          //console.log("POPULATION", JSON.stringify(population, null, 2));

          Go(countries, 0);
        });

    }
  });

redpajama_set_name: RedPajamaGithub


text:
package openshift

import (
	"os"
	"runtime"
	"strings"

	"github.com/spf13/cobra"

	"github.com/openshift/origin/pkg/cmd/admin"
	"github.com/openshift/origin/pkg/cmd/cli"
	"github.com/openshift/origin/pkg/cmd/cli/cmd"
	"github.com/openshift/origin/pkg/cmd/experimental/buildchain"
	exipfailover "github.com/openshift/origin/pkg/cmd/experimental/ipfailover"
	"github.com/openshift/origin/pkg/cmd/experimental/tokens"
	"github.com/openshift/origin/pkg/cmd/flagtypes"
	"github.com/openshift/origin/pkg/cmd/infra/builder"
	"github.com/openshift/origin/pkg/cmd/infra/deployer"
	irouter "github.com/openshift/origin/pkg/cmd/infra/router"
	"github.com/openshift/origin/pkg/cmd/server/start"
	"github.com/openshift/origin/pkg/cmd/server/start/kubernetes"
	"github.com/openshift/origin/pkg/cmd/templates"
	cmdutil "github.com/openshift/origin/pkg/cmd/util"
	"github.com/openshift/origin/pkg/cmd/util/clientcmd"
	"github.com/openshift/origin/pkg/version"
)

const openshiftLong = `
OpenShift Application Platform

OpenShift helps you build, deploy, and manage your applications. To start an all-in-one server, run:

  $ openshift start &

OpenShift is built around Docker and the Kubernetes cluster container manager.  You must have
Docker installed on this machine to start your server.`

// CommandFor returns the appropriate command for this base name,
// or the global OpenShift command
func CommandFor(basename string) *cobra.Command {
	var cmd *cobra.Command

	out := os.Stdout

	// Make case-insensitive and strip executable suffix if present
	if runtime.GOOS == "windows" {
		basename = strings.ToLower(basename)
		basename = strings.TrimSuffix(basename, ".exe")
	}

	switch basename {
	case "openshift-router":
		cmd = irouter.NewCommandTemplateRouter(basename)
	case "openshift-deploy":
		cmd = deployer.NewCommandDeployer(basename)
	case "openshift-sti-build":
		cmd = builder.NewCommandSTIBuilder(basename)
	case "openshift-docker-build":
		cmd = builder.NewCommandDockerBuilder(basename)
	case "oc", "osc":
		cmd = cli.NewCommandCLI(basename, basename)
	case "oadm", "osadm":
		cmd = admin.NewCommandAdmin(basename, basename, out)
	case "kubectl":
		cmd = cli.NewCmdKubectl(basename, out)
	case "kube-apiserver":
		cmd = kubernetes.NewAPIServerCommand(basename, basename, out)
	case "kube-controller-manager":
		cmd = kubernetes.NewControllersCommand(basename, basename, out)
	case "kubelet":
		cmd = kubernetes.NewKubeletCommand(basename, basename, out)
	case "kube-proxy":
		cmd = kubernetes.NewProxyCommand(basename, basename, out)
	case "kube-scheduler":
		cmd = kubernetes.NewSchedulerCommand(basename, basename, out)
	case "kubernetes":
		cmd = kubernetes.NewCommand(basename, basename, out)
	case "origin":
		cmd = NewCommandOpenShift("origin")
	default:
		cmd = NewCommandOpenShift("openshift")
	}

	if cmd.UsageFunc() == nil {
		templates.ActsAsRootCommand(cmd)
	}
	flagtypes.GLog(cmd.PersistentFlags())

	return cmd
}

// NewCommandOpenShift creates the standard OpenShift command
func NewCommandOpenShift(name string) *cobra.Command {
	out := os.Stdout

	root := &cobra.Command{
		Use:   name,
		Short: "OpenShift helps you build, deploy, and manage your cloud applications",
		Long:  openshiftLong,
		Run:   cmdutil.DefaultSubCommandRun(out),
	}

	startAllInOne, _ := start.NewCommandStartAllInOne(name, out)
	root.AddCommand(startAllInOne)
	root.AddCommand(admin.NewCommandAdmin("admin", name+" admin", out))
	root.AddCommand(cli.NewCommandCLI("cli", name+" cli"))
	root.AddCommand(cli.NewCmdKubectl("kube", out))
	root.AddCommand(newExperimentalCommand("ex", name+" ex"))
	root.AddCommand(version.NewVersionCommand(name))

	// infra commands are those that are bundled with the binary but not displayed to end users
	// directly
	infra := &cobra.Command{
		Use: "infra", // Because this command exposes no description, it will not be shown in help
	}

	infra.AddCommand(
		irouter.NewCommandTemplateRouter("router"),
		deployer.NewCommandDeployer("deploy"),
		builder.NewCommandSTIBuilder("sti-build"),
		builder.NewCommandDockerBuilder("docker-build"),
	)
	root.AddCommand(infra)

	root.AddCommand(cmd.NewCmdOptions(out))

	// TODO: add groups
	templates.ActsAsRootCommand(root)

	return root
}

func newExperimentalCommand(name, fullName string) *cobra.Command {
	out := os.Stdout

	experimental := &cobra.Command{
		Use:   name,
		Short: "Experimental commands under active development",
		Long:  "The commands grouped here are under development and may change without notice.",
		Run: func(c *cobra.Command, args []string) {
			c.SetOutput(out)
			c.Help()
		},
	}

	f := clientcmd.New(experimental.PersistentFlags())

	experimental.AddCommand(tokens.NewCmdTokens(tokens.TokenRecommendedCommandName, fullName+" "+tokens.TokenRecommendedCommandName, f, out))
	experimental.AddCommand(exipfailover.NewCmdIPFailoverConfig(f, fullName, "ipfailover", out))
	experimental.AddCommand(buildchain.NewCmdBuildChain(f, fullName, "build-chain"))
	experimental.AddCommand(cmd.NewCmdOptions(out))
	return experimental
}


text:
title:  "Comparison of performance: Python NumPy and Numba, MATLAB, and Fortran"
date:   2017-09-27 19:11:00
description: The time it takes to perform an array operation is compared in Python NumPy, Python NumPy with Numba accleration, MATLAB, and Fortran. The arrays are large, with one million to one billion elements. Numba is a great choice for parallel acceleration of Python and NumPy.
keywords: [Python parallel processing, NumPy vs MATLAB vs Fortran, Python vs Fortan, Python vs MATLAB, Numba NumPy acceleration, Python NumPy faster]
---

TL;DR; Python Numba acceleration is really fast.

Like faster than *Fortan fast*.

**Edit February 6, 2018**:
Some notes. In Python ```X += Y; X += Y``` is faster than ```X = X + Y + Y``` which is faster than ```X = X + 2*Y```. However, in MATLAB on my machines ```X = X + 2*Y``` is slightly faster than ```X = X + Y + Y```. The Fortran code I run could be marginally improved (<=2% on my machines) by compiling ```X = X + Y + Y``` instead of ```X = X + 2*Y```. The code for the Numba, MATLAB, and Fortran benchmark is the same ```X = X + 2*Y```. Benchmarking code is really hard to do, but this quick study was a pleasant introduction to Numba.

*Edit September 28, 2017: I've updated the benchmark to include runs with gfortran -O2.*

### Preface
So this post was inspired by a HN comment by [CS207](https://news.ycombinator.com/item?id=15123559) about NumPy performance. The post demonstrates a *trick* that you can use to increase NumPy's peformance with integer arrays. Unfortunately the performance gain greatly diminishes when working with double precision floats (though it is still always faster on average). The demo and conversation that follows was interesting, and I got my first taste of [Numba](https://numba.pydata.org/) (high performance Python acceleration libarary -- which has a seamless integration with NumPy).

### Introudction
I'm going to benchmark adding big arrays together in NumPy, Numba, MATLAB, and Fortran. It'll be interesting to see what Numba's acceleration has to offer since the majoriy of my numerical work is done with NumPy. Many of my colleges still use MATLAB (hopefully my class on Python and this post may convince them to seriously consider Python as an alternative.) Now everyone already knows that Python and MATLAB are *slow* languages, but NumPy and MATLAB are optimized for array calculations which is what Fortran is all about. And Fortran is *fast*, so a fair comparison of array operations in Numpy and MATALAB should also consider Fortran.

### The Benchmark
The benchmark is going to solve the following equation

$$
X = X + 2.0 Y
$$

where \\( X, Y  \\) are double precision floating point arrays with a lot of elements. I'm going to benchmark this problem for arrays between 1,000,000 and and 1,000,000,000 elements (the most I can fit into my RAM). So essentially I'm going to run functionally equivalent code in Python (either NumPy or NumPy + Numba), MATLAB, and Fortran on two different machines. Machine 1: AMD FX-8370 Eight-Core @ 4.0 GHz with 32 GB DDR3 RAM. Machine 2: ThinkPad 13 [i5-6300U](https://ark.intel.com/products/88190/Intel-Core-i5-6300U-Processor-3M-Cache-up-to-3_00-GHz) with 32 GB DDR4 RAM. I'm not going to touch GPU acceleration in this benchmark, but I think it will be worthwhile to do so sometime.

The benchmark will run \\( X = X + 2.0 Y  \\) 10 times, and return the average run time for 1 dimensional array sizes of 1,000,000, 10,000,000, 100,000,000, and 1,000,000,000 elements. The sample code for one run in each language is provided below.

NumPy code:
```python
import numpy as np
import time as time

n = np.array( int(1e9))# number of data points

X = np.ones(n, dtype=np.float)
Y = np.ones(n, dtype=np.float)
t0 = time.time()
X += Y; X += Y
t1 = time.time()
run_time = t1 - t0
```

NumPy + Numba single threaded code (inspired by [jzwinck](https://news.ycombinator.com/item?id=15123846)):
```python
import numpy as np
import numba
import time as time

@numba.vectorize(["float64(float64,float64)"],
    nopython=True,target='cpu')
def add2_par(x, y):
    return x + 2 * y
n = np.array( int(1e9))# number of data points

X = np.ones(n, dtype=np.float)
Y = np.ones(n, dtype=np.float)
t0 = time.time()
add2_par(X, Y, out=X)
t1 = time.time()
run_time = t1 - t0
```

NumPy + Numba parallel code:
```python
import numpy as np
import numba
import time as time

@numba.vectorize(["float64(float64,float64)"],
    nopython=True,target='parallel')
def add2_par(x, y):
    return x + 2 * y
n = np.array( int(1e9))# number of data points

X = np.ones(n, dtype=np.float)
Y = np.ones(n, dtype=np.float)
t0 = time.time()
add2_par(X, Y, out=X)
t1 = time.time()
run_time = t1 - t0
```

MATLAB Code:
```matlab
clear; clc;
% --- single threaded run ---
X = ones(1e9,1);
Y = ones(1e9,1);
t = cputime;
X = X + 2.0*Y;
e = cputime-t;
```

Fortran code:
```fortran
    program main
c compile with GNU Fortran as
c gfortran -mcmodel=medium demo.f
c
c -mcmodel=medium is only needed for one billion elements
c
c to execture program run ./a.out
    implicit none
    real*8, dimension(1000000000) :: X
    real*8, dimension(1000000000) :: Y
    double precision t1, t2
    X(:) = 1
    Y(:) = 1
    call cpu_time ( t1 )
    X = X + 2*Y
    call cpu_time ( t2 )
    write ( *, '(a)' ) 'run time  in seconds: '
    write ( *, * ) t2-t1
    stop
    end
```

Application versions:

| Program  |     Version    |
|----------|:-------------:|
| Python   | 2.7.13        |
| NumPy    | 1.13.1        |
| Numba    | 0.35.0        |
| MATLAB   | R2015a        |
| GNU Fortran | 4.8.5      |

[Python folder](https://github.com/cjekel/cjekel.github.io/tree/master/assets/2017-09-27/Python) and execution:
```bash
> python numpy_bench.py
> python numba_bench_single.py
> python numba_bench_par.py
```

[MATLAB folder](https://github.com/cjekel/cjekel.github.io/tree/master/assets/2017-09-27/Matlab) and execution:
```bash
> matlab -nodesktop -nodisplay -r "run speedTest.m"
```

[Fortran folder](https://github.com/cjekel/cjekel.github.io/tree/master/assets/2017-09-27/Fortran) and execution:
```bash
> gfortran -mcmodel=medium speed1e9.f
> ./a.out
> gfortran speed1e8.f
> ./a.out
> gfortran speed1e7.f
> ./a.out
> gfortran speed1e6.f
> ./a.out
> gfortran -O2 -mcmodel=medium speed1e9.f
> ./a.out
> gfortran -O2 speed1e8.f
> ./a.out
> gfortran -O2 speed1e7.f
> ./a.out
> gfortran -O2 speed1e6.f
> ./a.out
```

### Results

On both of my machines a single threaded Numba run was on average faster than compiled Fortran code (without the -O2 optimization level). With the -O2 optimization level it appears the that Fortan is faster than numba single threaded, but by a very narrow margin. Below you'll see the mean run times in seconds between gfortran -O2 and the single threaded Python Numba.

| CPU | array elements | gfortran -O2 (s)|  Python Numba single (s)  |
|----------:|:-------------:|:-------------:|:-------------:|
| AMD FX-8370 |     1,000,000 | 0.00225 | 0.00202 |
| AMD FX-8370 |    10,000,000 | 0.01952 | 0.01946 |
| AMD FX-8370 |   100,000,000 | 0.19258 | 0.18895|
| AMD FX-8370 | 1,000,000,000 | 1.90781 | 1.91261|
| i5-6300u    |     1,000,000 | 0.00128 | 0.00098 |
| i5-6300u    |    10,000,000 | 0.00996 | 0.01041 |
| i5-6300u    |   100,000,000 | 0.10023 | 0.10142 |
| i5-6300u    | 1,000,000,000 | 0.94956 | 1.03110  |

 I wasn't expecting this -- and I'm not sure how this black magic called Numba works... I need to do some more research into what Numba is actually doing with the [JIT](https://en.wikipedia.org/wiki/Just-in-time_compilation) compilation. The speed ranks from Slowest to Fastest on the AMD-FX870: MATLAB, NumPy, gfortran, Numba single thread, gfortran -O2, Numba parallel. With the i5-6300U there is less discrepancy between MATLAB times and NumPy times (they are basically the same).

I was also surprised to see with the i5-6300u that NumPy and Fortran ran at nearlly the same speed. For the 1,000,000,000 element arrays, the Fortran code (without the O2 flag) was only 3.7% faster than the NumPy code.

The parallel Numba code really shines with the 8-cores of the AMD-FX870, which was about 4 times faster than MATLAB, and 3 times faster than Numpy. However the parallel Numba code was only about two times faster than Numpy with the i5-6300u, but this makes sences since this is only a two core (4 threads) processor.

The figures bellow show the benchmarks results of the average run times on a log-log scale. Another figure shows how much slower the implementation was when compared to the Numba parallel run average.

![Machine 1 time results]({{ "/" | relative_url  }}assets/2017-09-27/Machine1_res.png)

![Machine 1 times slower]({{ "/" | relative_url  }}assets/2017-09-27/Machine1_per.png)

![Machine 2 time results]({{ "/" | relative_url  }}assets/2017-09-27/Machine2_res.png)

![Machine 2 times slower]({{ "/" | relative_url  }}assets/2017-09-27/Machine2_per.png)

### Discusion about memory usage
You can't perform this benchmark without mentioning that this Python example is a Memory HOG wen compared to Fortran and MATLAB. Python will peak at 24 GB of RAM to do the math with the 1,000,000,000 element arrays, regardless of if you use Numba or pure NumPy. This is horribly inefficient -- since Python is only storing 16 GB of data in RAM after and before the operation. MATLAB and Fortran solve this problem with a peak memory usage of 16 GB of RAM. This is 33% more RAM required to perform the array operation with Python than MATLAB or Fortran. (Peak RAM usage was estimated using GNU time /usr/bin/time -v)

### Conclusion

Wow Numba is Fast. I would have never expected to see a Python NumPy Numba array combination as fast as compiled Fortran code. The cost is obviously that it takes time to port your already existing Python NumPy code to Numba. Numba's parallel acceleration worked really well on this problem, and with the 8 core AMD-FX870 Numba parallel ran 4 times faster than MATLAB code.

Is there anything I missed? I'm looking forward to playing with Numba GPU acceleration in the future. You can take a look at the code I used to run the benchmark [here](https://github.com/cjekel/cjekel.github.io/tree/master/assets/2017-09-27).

It's worthwhile to note that I did not do this benchmark with  [ATLAS](https://math-atlas.sourceforge.net/), and that using ATLAS may seriously speed up the Fortran execution of this problem (and likely speed up the Numpy and Numba execution as well).


text:
/**
 * Autogenerated by Thrift Compiler (0.9.3)
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
package org.apache.hadoop.hive.metastore.api;

import org.apache.thrift.scheme.IScheme;
import org.apache.thrift.scheme.SchemeFactory;
import org.apache.thrift.scheme.StandardScheme;

import org.apache.thrift.scheme.TupleScheme;
import org.apache.thrift.protocol.TTupleProtocol;
import org.apache.thrift.protocol.TProtocolException;
import org.apache.thrift.EncodingUtils;
import org.apache.thrift.TException;
import org.apache.thrift.async.AsyncMethodCallback;
import org.apache.thrift.server.AbstractNonblockingServer.*;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.EnumMap;
import java.util.Set;
import java.util.HashSet;
import java.util.EnumSet;
import java.util.Collections;
import java.util.BitSet;
import java.nio.ByteBuffer;
import java.util.Arrays;
import javax.annotation.Generated;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"})
@Generated(value = "Autogenerated by Thrift Compiler (0.9.3)")
@org.apache.hadoop.classification.InterfaceAudience.Public @org.apache.hadoop.classification.InterfaceStability.Stable public class GetFieldsResponse implements org.apache.thrift.TBase<GetFieldsResponse, GetFieldsResponse._Fields>, java.io.Serializable, Cloneable, Comparable<GetFieldsResponse> {
  private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("GetFieldsResponse");

  private static final org.apache.thrift.protocol.TField FIELDS_FIELD_DESC = new org.apache.thrift.protocol.TField("fields", org.apache.thrift.protocol.TType.LIST, (short)1);

  private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
  static {
    schemes.put(StandardScheme.class, new GetFieldsResponseStandardSchemeFactory());
    schemes.put(TupleScheme.class, new GetFieldsResponseTupleSchemeFactory());
  }

  private List<FieldSchema> fields; // required

  /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
  public enum _Fields implements org.apache.thrift.TFieldIdEnum {
    FIELDS((short)1, "fields");

    private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();

    static {
      for (_Fields field : EnumSet.allOf(_Fields.class)) {
        byName.put(field.getFieldName(), field);
      }
    }

    /**
     * Find the _Fields constant that matches fieldId, or null if its not found.
     */
    public static _Fields findByThriftId(int fieldId) {
      switch(fieldId) {
        case 1: // FIELDS
          return FIELDS;
        default:
          return null;
      }
    }

    /**
     * Find the _Fields constant that matches fieldId, throwing an exception
     * if it is not found.
     */
    public static _Fields findByThriftIdOrThrow(int fieldId) {
      _Fields fields = findByThriftId(fieldId);
      if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
      return fields;
    }

    /**
     * Find the _Fields constant that matches name, or null if its not found.
     */
    public static _Fields findByName(String name) {
      return byName.get(name);
    }

    private final short _thriftId;
    private final String _fieldName;

    _Fields(short thriftId, String fieldName) {
      _thriftId = thriftId;
      _fieldName = fieldName;
    }

    public short getThriftFieldId() {
      return _thriftId;
    }

    public String getFieldName() {
      return _fieldName;
    }
  }

  // isset id assignments
  public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
  static {
    Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
    tmpMap.put(_Fields.FIELDS, new org.apache.thrift.meta_data.FieldMetaData("fields", org.apache.thrift.TFieldRequirementType.REQUIRED,
        new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST,
            new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, FieldSchema.class))));
    metaDataMap = Collections.unmodifiableMap(tmpMap);
    org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(GetFieldsResponse.class, metaDataMap);
  }

  public GetFieldsResponse() {
  }

  public GetFieldsResponse(
    List<FieldSchema> fields)
  {
    this();
    this.fields = fields;
  }

  /**
   * Performs a deep copy on <i>other</i>.
   */
  public GetFieldsResponse(GetFieldsResponse other) {
    if (other.isSetFields()) {
      List<FieldSchema> __this__fields = new ArrayList<FieldSchema>(other.fields.size());
      for (FieldSchema other_element : other.fields) {
        __this__fields.add(new FieldSchema(other_element));
      }
      this.fields = __this__fields;
    }
  }

  public GetFieldsResponse deepCopy() {
    return new GetFieldsResponse(this);
  }

  @Override
  public void clear() {
    this.fields = null;
  }

  public int getFieldsSize() {
    return (this.fields == null) ? 0 : this.fields.size();
  }

  public java.util.Iterator<FieldSchema> getFieldsIterator() {
    return (this.fields == null) ? null : this.fields.iterator();
  }

  public void addToFields(FieldSchema elem) {
    if (this.fields == null) {
      this.fields = new ArrayList<FieldSchema>();
    }
    this.fields.add(elem);
  }

  public List<FieldSchema> getFields() {
    return this.fields;
  }

  public void setFields(List<FieldSchema> fields) {
    this.fields = fields;
  }

  public void unsetFields() {
    this.fields = null;
  }

  /** Returns true if field fields is set (has been assigned a value) and false otherwise */
  public boolean isSetFields() {
    return this.fields != null;
  }

  public void setFieldsIsSet(boolean value) {
    if (!value) {
      this.fields = null;
    }
  }

  public void setFieldValue(_Fields field, Object value) {
    switch (field) {
    case FIELDS:
      if (value == null) {
        unsetFields();
      } else {
        setFields((List<FieldSchema>)value);
      }
      break;

    }
  }

  public Object getFieldValue(_Fields field) {
    switch (field) {
    case FIELDS:
      return getFields();

    }
    throw new IllegalStateException();
  }

  /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
  public boolean isSet(_Fields field) {
    if (field == null) {
      throw new IllegalArgumentException();
    }

    switch (field) {
    case FIELDS:
      return isSetFields();
    }
    throw new IllegalStateException();
  }

  @Override
  public boolean equals(Object that) {
    if (that == null)
      return false;
    if (that instanceof GetFieldsResponse)
      return this.equals((GetFieldsResponse)that);
    return false;
  }

  public boolean equals(GetFieldsResponse that) {
    if (that == null)
      return false;

    boolean this_present_fields = true && this.isSetFields();
    boolean that_present_fields = true && that.isSetFields();
    if (this_present_fields || that_present_fields) {
      if (!(this_present_fields && that_present_fields))
        return false;
      if (!this.fields.equals(that.fields))
        return false;
    }

    return true;
  }

  @Override
  public int hashCode() {
    List<Object> list = new ArrayList<Object>();

    boolean present_fields = true && (isSetFields());
    list.add(present_fields);
    if (present_fields)
      list.add(fields);

    return list.hashCode();
  }

  @Override
  public int compareTo(GetFieldsResponse other) {
    if (!getClass().equals(other.getClass())) {
      return getClass().getName().compareTo(other.getClass().getName());
    }

    int lastComparison = 0;

    lastComparison = Boolean.valueOf(isSetFields()).compareTo(other.isSetFields());
    if (lastComparison != 0) {
      return lastComparison;
    }
    if (isSetFields()) {
      lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.fields, other.fields);
      if (lastComparison != 0) {
        return lastComparison;
      }
    }
    return 0;
  }

  public _Fields fieldForId(int fieldId) {
    return _Fields.findByThriftId(fieldId);
  }

  public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
    schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
  }

  public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
    schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder("GetFieldsResponse(");
    boolean first = true;

    sb.append("fields:");
    if (this.fields == null) {
      sb.append("null");
    } else {
      sb.append(this.fields);
    }
    first = false;
    sb.append(")");
    return sb.toString();
  }

  public void validate() throws org.apache.thrift.TException {
    // check for required fields
    if (!isSetFields()) {
      throw new org.apache.thrift.protocol.TProtocolException("Required field 'fields' is unset! Struct:" + toString());
    }

    // check for sub-struct validity
  }

  private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
    try {
      write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
    } catch (org.apache.thrift.TException te) {
      throw new java.io.IOException(te);
    }
  }

  private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
    try {
      read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
    } catch (org.apache.thrift.TException te) {
      throw new java.io.IOException(te);
    }
  }

  private static class GetFieldsResponseStandardSchemeFactory implements SchemeFactory {
    public GetFieldsResponseStandardScheme getScheme() {
      return new GetFieldsResponseStandardScheme();
    }
  }

  private static class GetFieldsResponseStandardScheme extends StandardScheme<GetFieldsResponse> {

    public void read(org.apache.thrift.protocol.TProtocol iprot, GetFieldsResponse struct) throws org.apache.thrift.TException {
      org.apache.thrift.protocol.TField schemeField;
      iprot.readStructBegin();
      while (true)
      {
        schemeField = iprot.readFieldBegin();
        if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
          break;
        }
        switch (schemeField.id) {
          case 1: // FIELDS
            if (schemeField.type == org.apache.thrift.protocol.TType.LIST) {
              {
                org.apache.thrift.protocol.TList _list1208 = iprot.readListBegin();
                struct.fields = new ArrayList<FieldSchema>(_list1208.size);
                FieldSchema _elem1209;
                for (int _i1210 = 0; _i1210 < _list1208.size; ++_i1210)
                {
                  _elem1209 = new FieldSchema();
                  _elem1209.read(iprot);
                  struct.fields.add(_elem1209);
                }
                iprot.readListEnd();
              }
              struct.setFieldsIsSet(true);
            } else {
              org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
            }
            break;
          default:
            org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
        }
        iprot.readFieldEnd();
      }
      iprot.readStructEnd();
      struct.validate();
    }

    public void write(org.apache.thrift.protocol.TProtocol oprot, GetFieldsResponse struct) throws org.apache.thrift.TException {
      struct.validate();

      oprot.writeStructBegin(STRUCT_DESC);
      if (struct.fields != null) {
        oprot.writeFieldBegin(FIELDS_FIELD_DESC);
        {
          oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, struct.fields.size()));
          for (FieldSchema _iter1211 : struct.fields)
          {
            _iter1211.write(oprot);
          }
          oprot.writeListEnd();
        }
        oprot.writeFieldEnd();
      }
      oprot.writeFieldStop();
      oprot.writeStructEnd();
    }

  }

  private static class GetFieldsResponseTupleSchemeFactory implements SchemeFactory {
    public GetFieldsResponseTupleScheme getScheme() {
      return new GetFieldsResponseTupleScheme();
    }
  }

  private static class GetFieldsResponseTupleScheme extends TupleScheme<GetFieldsResponse> {

    @Override
    public void write(org.apache.thrift.protocol.TProtocol prot, GetFieldsResponse struct) throws org.apache.thrift.TException {
      TTupleProtocol oprot = (TTupleProtocol) prot;
      {
        oprot.writeI32(struct.fields.size());
        for (FieldSchema _iter1212 : struct.fields)
        {
          _iter1212.write(oprot);
        }
      }
    }

    @Override
    public void read(org.apache.thrift.protocol.TProtocol prot, GetFieldsResponse struct) throws org.apache.thrift.TException {
      TTupleProtocol iprot = (TTupleProtocol) prot;
      {
        org.apache.thrift.protocol.TList _list1213 = new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, iprot.readI32());
        struct.fields = new ArrayList<FieldSchema>(_list1213.size);
        FieldSchema _elem1214;
        for (int _i1215 = 0; _i1215 < _list1213.size; ++_i1215)
        {
          _elem1214 = new FieldSchema();
          _elem1214.read(iprot);
          struct.fields.add(_elem1214);
        }
      }
      struct.setFieldsIsSet(true);
    }
  }

}


text:
<?php

namespace Andean\BackendBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class HotelHabitacionType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('hotel', null, array('required' => true))
            ->add('acomodacion', null, array('required' => true))
            ->add('precio')
        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Andean\HotelBundle\Entity\HotelHabitacion'
        ));
    }

    public function getName()
    {
        return 'andean_backendbundle_hotelhabitaciontype';
    }
}


text:
namespace Skeleton.Common.Extensions
{
    using System;

    public static class DoubleExtensions
    {
        public const double DefaultAccuracy = 1e-7;

        private static double GetUsedAccuracy(double? accuracy) => accuracy ?? DefaultAccuracy;

        public static bool Equal(this double first, double second, double? accuracy = null)
        {
            var usedAccuracy = GetUsedAccuracy(accuracy);
            return first <= second + usedAccuracy
                   && first + usedAccuracy >= second;
        }

        public static bool NotEqual(this double first, double second, double? accuracy = null)
        {
            var usedAccuracy = GetUsedAccuracy(accuracy);
            return first + usedAccuracy < second
                || first > second + usedAccuracy;
        }

        public static bool LessOrEqual(this double first, double second, double? accuracy = null)
        {
            return first <= second + GetUsedAccuracy(accuracy);
        }

        public static bool Less(this double first, double second, double? accuracy = null)
        {
            return first + GetUsedAccuracy(accuracy) < second;
        }

        public static bool GreaterOrEqual(this double first, double second, double? accuracy = null)
        {
            return first + GetUsedAccuracy(accuracy) >= second;
        }

        public static bool Greater(this double first, double second, double? accuracy = null)
        {
            return first > second + GetUsedAccuracy(accuracy);
        }
    }
}


text:
package org.pescuma.buildhealth.cli.commands.webserver;

import static org.pescuma.buildhealth.core.BuildHealth.ReportFlags.*;
import io.airlift.airline.Arguments;
import io.airlift.airline.Command;

import java.io.IOException;

import org.pescuma.buildhealth.cli.BuildHealthCliCommand;
import org.pescuma.buildhealth.core.Report;

@Command(name = "webserver", description = "Serve the results using a embeded webserver")
public class WebServerCommand extends BuildHealthCliCommand {

	@Arguments(title = "port", description = "The port to bind the webserver (default: 80190)", required = false)
	public int port = 8190;

	@Override
	public void execute() {
		Report report = buildHealth.generateReport(Full);

		BuildHealthWebServer server = new BuildHealthWebServer(report, null, port);

		try {
			server.start();
		} catch (IOException e) {
			System.err.println("Couldn't start server:");
			e.printStackTrace();
			System.exit(-1);
		}

		String url = "http://localhost:" + port;
		System.out.println("Web server started at " + url);
		System.out.println("Available urls:");
		System.out.println("  " + url + "/            => Browse the reports as a web site");
		System.out.println("  " + url + "/report.json => Report in JSON format");
		System.out.println("  " + url + "/report.xml  => Report in XML format");
		System.out.println();
		System.out.println("Hit Enter to stop...");

		try {
			System.in.read();
		} catch (Exception ignored) {
		}

		server.stop();
		System.out.println("Server stopped.\n");
	}

}


text:
{% extends 'common/templates/base_sidebar.html' %}
{% load nonce avatar vcard base %}
{% block title %}{{view.display_nick}}{% endblock %}

{% block content %}
{% if user_can_post %}
  {% include_extend 'common/templates/message_form.html' %}
    {% block message_title %}

          {% if not user_is_admin %}
          You are a member. Leave {{view.display_nick}}
          {% else %}
          Edit settings
          {% endif %}

        {{view.display_nick}}

    {% endblock %}
  {% endinclude_extend %}
{% else %}
  {% include 'form_error.html' %}

      {% with view as actor %}
        {% include 'common/templates/vcard_full.html' %}
      {% endwith %}
      {% if request.user %}

      + Join {{view.display_nick}}

      {% endif %}

{% endif %}

{{POST_NAME}}s in {{ view.display_nick }}

  {% include_extend 'common/templates/stream.html' %}
  {% block no_posts %}No one has posted to this channel yet.{% endblock %}
  {% endinclude_extend %}
  {% include 'common/templates/paging.html' %}

    {% if feeds %}
      {{feeds.0.title}}
    {% endif %}

{% endblock %}

{% block sidebar %}
{% include 'channel/templates/sidebar_profile.html' %}
{% include 'common/templates/sidebar_admins.html' %}

{% include 'common/templates/sidebar_members.html' %}

{% with view_streams as streams %}
  {% include 'common/templates/sidebar_streams.html' %}
{% endwith %}

{% endblock %}


text:
<!DOCTYPE html>

  <meta charset="UTF-8" />
  <title>Backbone.Analytics Test Suite</title>
  <link rel="stylesheet" href="vendor/qunit.css" type="text/css">

Backbone.Analytics Test Suite


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class pendaftaran extends CI_Controller {

	public function __construct()
	{
		parent::__construct();
		$this->load->model('daftar_model');
        $this->load->helper('url');
	}

	public function index()
	{
		$this->load->view('templates/header');
		$this->load->view('templates/nav');
		$this->load->view('pendaftaran');
		$this->load->view('templates/footer');
	}

	public function prosespendaftaran(){
		$namalengkap = $this->input->post('namalengkap');
		$telepon = $this->input->post('telepon');
		$alamat = $this->input->post('alamat');
		$nim = $this->input->post('nim');
		$email = $this->input->post('email');

		$data = array(
			'namalengkap' => $namalengkap,
			'telepon' => $telepon,
			'alamat' => $alamat,
			'nim' => $nim,
			'email' => $email
			);
		$this->daftar_model->input_data($data,'pendaftaran');
		redirect('Home');
	}
}


text:
export class AbstractPrepRule {
  public name: string;
  public isBuilder: boolean;
}

export class NestRule extends AbstractPrepRule {
  public col: string[];
  public newCol: string;
  public type: string;
}

export class HeaderRule extends AbstractPrepRule {
  public rownum: number;
}

export class DropRule extends AbstractPrepRule {
  public col: string[];
}

export class ExtractRule extends AbstractPrepRule {
  public col: string[];
  public pattern: string;
  public limit: number;
  public ignore?: string;
  public ignoreCase: boolean;
}

export class MoveRule extends AbstractPrepRule {
  public col: string[];
  public refColumn: string;
  public beforeAfter: string;
}

export class UnnestRule extends AbstractPrepRule {
  public col: string[];
  public element: string;
}

export class FlattenRule extends AbstractPrepRule {
  public col: string[];
}

export class SortRule extends AbstractPrepRule {
  public col: string[];
  public sortBy: string;
}

export class SetRule extends AbstractPrepRule {
  public col: string[];
  public expression: string;
  public condition?: string;
}

export class ReplaceRule extends AbstractPrepRule {
  public col: string[];
  public pattern: string;
  public newVal?: string;
  public ignore?: string;
  public matchOccurrence: boolean;
  public ignoreCase: boolean;
  public condition: string;
}

export class SetFormatRule extends AbstractPrepRule {
  public col: string[];
  public format: string;
}

export class SetTypeRule extends AbstractPrepRule {
  public col: string[] | string;
  public type: string;
  public format?: string;
}

export class SplitRule extends AbstractPrepRule {
  public col: string[];
  public pattern: string;
  public limit: number;
  public ignore?: string;
  public ignoreCase: boolean;
}

export class MergeRule extends AbstractPrepRule {
  public col: string[];
  public delimiter: string;
  public newCol: string;
}

export class KeepRule extends AbstractPrepRule {
  public condition: string;
}

export class DeriveRule extends AbstractPrepRule {
  public expression: string;
  public newCol: string;
}

export class DeleteRule extends AbstractPrepRule {
  public condition: string;
}

export class CountPatternRule extends AbstractPrepRule {
  public col: string[];
  public ignore?: string;
  public pattern: string;
  public ignoreCase: boolean;
}

export class AggregateRule extends AbstractPrepRule {
  public col: string[];
  public expression: string[];
}

export class PivotRule extends AbstractPrepRule {
  public col: string[];
  public expression: string[];
  public group: string[];
}

export class UnpivotRule extends AbstractPrepRule {
  public col: string[];
  public groupEvery: number;
}

export class WindowRule extends AbstractPrepRule {
  public groupBy?: string[];
  public expression: string[];
  public sortBy?: string[];
}

export class RenameRule extends AbstractPrepRule {
  public col: string[];
  public to: string[];
}


text:
<!DOCTYPE html>
<html>
<head>
<script src="../../../resources/js-test.js"></script>
<style id="style1">
.foo::-webkit-distributed(> div .bar::before) { display: block; }
</style>
</head>
<script>
description("Test for cssText of '::distributed()' rule.");
shouldBeEqualToString("document.getElementById('style1').sheet.cssRules.item(0).cssText", ".foo::-webkit-distributed(> div .bar::before) { display: block; }");
</script>
</html>


text:
layout: post
title: centos7 rc.local问题
category: 系统及服务
tags: [centos7,rc.local]
keywords: centos7,rc.local
description:
---

> 用正确的工具,做正确的事情

centos6及之前版本的OS,开机启动执行的脚本可以通过直接写到/etc/rc.d/rc.local文件中来实现,然而测试发现centos7 os 写到该文件中的脚本开机并没有被执行,在redhat官方bugzilla中找到了问题的原因-- [bugzilla链接](https://bugzilla.redhat.com/show_bug.cgi?id=1178488),重点信息:

	This is intentional, we want users to understatnd that rc.local does not and can't work in the same way as in rhel6.
	There is a explanatory comment in the rc.local.

	# THIS FILE IS ADDED FOR COMPATIBILITY PURPOSES
	#
	# It is highly advisable to create own systemd services or udev rules
	# to run scripts during boot instead of using this file.
	#
	# In contrast to previous versions due to parallel execution during boot
	# this script will NOT be run after all other services.
	#
	# Please note that you must run 'chmod +x /etc/rc.d/rc.local' to ensure
	# that this script will be executed during boot.

从官方回复看,rc.local中脚本开机时没有自动执行并不是系统bug,而是故意为之,新版本OS希望使用systemd services的方式来实现开机执行或者开机启动,看了 rc.local文件已经在弃用的路上了。

下面验证了通过systemd services来实现开机执行命令,首先是创建一个自己的systemd 服务,在
/usr/lib/systemd/system/ 目录创建服务配置文件bootstart.service:

	[Unit]
	Description=bootstart      //服务描述

	[Service]
	Type=forking               //服务后台执行
	ExecStart=/usr/local/bootstart/bin/bootstart.sh   //服务启动文件或者脚本
	PrivateTmp=true                                   //创建独立命名空间

	[Install]
	WantedBy=multi-user.target

其中/usr/local/bootstart/bin/bootstart.sh:

	#!/bin/bash

	echo "`date`:system start !!" >> /usr/local/bootstart/log/bootstart.log

然后设置服务开机启动:

		systemctl enable bootstart.service

重启系统查看日志文件,可以发现脚本中的命令被开机执行。

玩的开心 !!!


text:
function yoTypescript() {
    yo typescript;
}


text:
package com.dptest.behavioralpattern.chainofresponsibility;

public interface IChain {

	void setNext(IChain nextInChain);

	void process(int number);

}


text:
package echosign.api.clientv20.dto9;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for ArrayOfMergeField complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="ArrayOfMergeField">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="MergeField" type="{http://dto9.api.echosign}MergeField" maxOccurs="unbounded" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ArrayOfMergeField", propOrder = {
    "mergeField"
})
public class ArrayOfMergeField {

    @XmlElement(name = "MergeField", nillable = true)
    protected List<MergeField> mergeField;

    /**
     * Gets the value of the mergeField property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the mergeField property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getMergeField().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link MergeField }
     *
     *
     */
    public List<MergeField> getMergeField() {
        if (mergeField == null) {
            mergeField = new ArrayList<MergeField>();
        }
        return this.mergeField;
    }

}


text:
<?php

use yii\db\Schema;
use yii\db\Migration;

class m151128_120537_create_files_table extends Migration
{
    public function safeUp()
    {
        $this->createTable('files', [
            'id'           => Schema::TYPE_PK,
            'name'         => Schema::TYPE_STRING . '(128) NOT NULL',
            'extension'    => Schema::TYPE_STRING . '(16) NOT NULL',
            'mime_type'    => Schema::TYPE_STRING . '(128) NOT NULL',
            'size'         => Schema::TYPE_INTEGER . ' NOT NULL',
            'real_name'    => Schema::TYPE_STRING . '(32) NOT NULL',
            'path'         => Schema::TYPE_STRING . '(32) NOT NULL DEFAULT ""',
            'created'      => Schema::TYPE_INTEGER . ' NOT NULL DEFAULT 0',
            'updated'      => Schema::TYPE_INTEGER . ' NOT NULL DEFAULT 0',
            'is_protected' => Schema::TYPE_BOOLEAN . ' NOT NULL',
        ]);

        $this->addColumn('articles', 'logo_image_file_id', Schema::TYPE_INTEGER . ' DEFAULT NULL');
        $this->addForeignKey('article_logo_image', 'articles', 'logo_image_file_id', 'files', 'id', 'SET NULL', 'CASCADE');
    }

    public function safeDown()
    {
        $this->dropForeignKey('article_logo_image', 'articles');
        $this->dropColumn('articles', 'logo_image_file_id');
        $this->dropTable('files');
    }
}


text:
using namespace std;

int main(void) {

    cout<<"scope begin"<<endl;
    {

        int x = 0;
        cout<<"constructing looping thread object"<<endl;
        sfh::looping_thread lt([&x](){cout<<++x<<endl;});

        cout<<"starting loop thread"<<endl;
        for (int i = 0; i < 4; ++i) {
            lt.start();
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
            lt.pause();
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
        }

        cout<<"stopping loop thread"<<endl;
        lt.stop();

    }
    cout<<"scope end"<<endl;

    return 0;
}


text:
namespace arangodb {
namespace transaction {

class Hints {
 public:
  typedef uint32_t ValueType;

  /// @brief individual hint flags that can be used for transactions
  enum class Hint : ValueType {
    NONE = 0,
    SINGLE_OPERATION = 1,
    LOCK_NEVER = 2,
    NO_USAGE_LOCK = 4,
    NO_DLD = 8,        // disable deadlock detection, unsupported in RocksDB
    NO_INDEXING = 16,  // use DisableIndexing for RocksDB
    INTERMEDIATE_COMMITS = 32,  // enable intermediate commits in rocksdb
    ALLOW_RANGE_DELETE = 64,    // enable range-delete in rocksdb
    FROM_TOPLEVEL_AQL = 128,    // transaction is only runnning one AQL query
    GLOBAL_MANAGED = 256,       // transaction with externally managed lifetime
    INDEX_CREATION = 512,  // transaction is for creating index on existing collection (many inserts, no removes, index will be deleted on any failure anyway)
    IS_FOLLOWER_TRX = 1024,  // transaction used to replicate something on a follower
    ALLOW_FAST_LOCK_ROUND_CLUSTER =
        2048,  // allow the coordinator to try a fast-lock path (parallel on all DBServers), and if that fails revert to slow-lock path
  };

  Hints() : _value(0) {}
  explicit Hints(Hint value) : _value(static_cast<ValueType>(value)) {}
  explicit Hints(ValueType value) : _value(value) {}

  inline bool has(ValueType value) const noexcept {
    return (_value & value) != 0;
  }

  inline bool has(Hint value) const noexcept {
    return has(static_cast<ValueType>(value));
  }

  inline void set(ValueType value) { _value |= value; }

  inline void set(Hint value) { set(static_cast<ValueType>(value)); }

  inline void unset(ValueType value) { _value &= ~value; }

  inline void unset(Hint value) { unset(static_cast<ValueType>(value)); }

  inline ValueType toInt() const { return static_cast<ValueType>(_value); }

 private:
  ValueType _value;
};

}  // namespace transaction
}  // namespace arangodb


text:
//
//  NSString+ZYLotter.h
//  ZYKit
//
//  Created by 何伟东 on 2016/11/22.
//  Copyright © 2016年 章鱼彩票. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface NSString (ZYLotter)

/**
 将某段字符串处理成带富文本属性的字符串

 @param partOfStr 需要将字符串中那些子串进行处理
 @param color 处理成的颜色
 @param font 处理成的字体
 @return <#return value description#>
 */
- (NSMutableAttributedString *)mutableAttributedStringWithPartStr:(NSString *)partOfStr changeToColor:(UIColor *)color font:(UIFont *)font;
- (NSMutableAttributedString *)mutableAttributedStringWithPartStrRange:(NSRange)range changeToColor:(UIColor *)color font:(UIFont *)font;

/**
 *  给字符串增加千位符
 *
 *  @param digitString <#digitString description#>
 *
 *  @return <#return value description#>
 */

+ (NSString *)separatedDigitStringWithStr:(NSString *)digitString;

@end


text:
import Vue from 'vue'
import utils from './utils'

const _setStatus = Symbol('_setStatus')
const _setCurrentTrain = Symbol('_setCurrentTrain')
const _isHasTicket = Symbol('_isHasTicket')
const _startSubmitOrder = Symbol('_startSubmitOrder')
const _submitOrder = Symbol('_submitOrder')
const _checkOrderInfo = Symbol('_checkOrderInfo')
const _getOrderQueueInfo = Symbol('_getOrderQueueInfo')
const _getOrderAwaitTime = Symbol('_getOrderAwaitTime')

const _startAutoSubmitOder = Symbol('_startAutoSubmitOder')
const _autoSubmitOrder = Symbol('_autoSubmitOrder')
const _getOrderQueueInfoAsync = Symbol('_getOrderQueueInfoAsync')

let timeout = 1

/**
 * 订单任务
 */
class OrderTask {
  /**
   * 开始任务
   */
  static start () {
    const taskItem = Vue.store.getters.taskData

    this.stop()

    this.startFunc = setInterval(async () => {
      this[_setStatus](`${timeout}秒后,开始查询...`)

      if (timeout <= 0) {
        this.stop() // 暂停计时器

        // 开始查询
        const {fromCityCode, toCityCode, trainDate, ticketType} = taskItem.queryInfo
        const formData = {
          queryUrl: Vue.store.getters.queryUrl,
          fromCity: fromCityCode,
          toCity: toCityCode,
          trainDate,
          ticketType
        }

        this[_setStatus]('正在查询...')

        const {data} = await Vue.api.base.getTicket(formData)

        // 更新列表车次数据
        Vue.eventBus.$emit('updateTicketData', data)

        let trainSeats = [] // 有票数的座位
        // 检查匹配车次是否符合预订条件
        let trainData = data.reduce((prev, current) => {
          if (taskItem.trains.indexOf(current.trainCode) > -1) {
            const arrPassenger = taskItem.passengers.passengerName.split(',')
            const seatItems = this[_isHasTicket](taskItem.seats, current.seatTypes, arrPassenger)
            const arrSeat = trainSeats.concat(seatItems)

            trainSeats = [...new Set(arrSeat)]

            if (trainSeats.length) {
              prev.push(current)
            }
          }

          return prev
        }, [])

        // 如果没有符合预订条件的车次,则继续启动任务
        if (!trainData.length) {
          this.start()

          return
        }

        // 开始准备提交订单
        this[_setStatus]('正在开始准备提交订单...')
        utils.notification.show('提示', {
          body: `【任务】正在执行提交订单`,
          tag: 'order'
        })
        this[_startSubmitOrder](trainData, trainSeats, taskItem)

        return
      }

      timeout = parseFloat(timeout - 0.1).toFixed(1)
    }, 100)
  }

  /**
   * 停止任务
   */
  static stop () {
    timeout = 1
    clearInterval(this.startFunc)
  }

  /**
   * 停止订单出票时间任务
   */
  static stopOrderAwaitFunc () {
    clearInterval(this.startOrderAwaitFunc)
  }

  /**
   * 设置任务状态
   * @param {*} text 状态内容
   */
  static [_setStatus] (text) {
    Vue.store.dispatch('setTaskDataStatus', text)
  }

  /**
   * 更新任务数据,当前预订车次信息
   * @param {*} train
   * @param {*} seatText
   */
  static [_setCurrentTrain] (train, seatText) {
    const {trainCode, fromCityName, toCityName, departureTime, arrivalTime, useTime} = train
    const currentTrain = {
      trainCode,
      fromCityName,
      toCityName,
      departureTime,
      arrivalTime,
      useTime,
      seatText
    }

    Vue.store.dispatch('setTaskCurrentTrain', currentTrain)
  }

  /**
   * 检查是否有票
   * @param {*} chkSeats 选择的座位
   * @param {*} seatTypes 车次的座位
   * @param {*} arrPassenger 乘客
   */
  static [_isHasTicket] (chkSeats, seatTypes, arrPassenger) {
    const passengerCount = arrPassenger.length

    let result = chkSeats.reduce((prevValue, currentValue) => {
      const trainSeat = seatTypes.find(t => t.seatTypeCode === currentValue)

      if (!trainSeat) return []

      const ticketRemark = trainSeat.seatTypeDetail
      let ticketCount = ticketRemark.match(/((.+))/)[1]

      ticketCount = Number(ticketCount)

      if ('有'.indexOf(ticketCount.toString()) > -1 || (!Number.isNaN(ticketCount) && ticketCount >= passengerCount)) {
        prevValue.push(currentValue)
      }

      return prevValue
    }, [])

    return result
  }

  /**
   * 开始提交订单
   * @param {*} trainData 车次
   * @param {*} trainSeats 座位
   * @param {*} taskItem 任务项
   */
  static async [_startSubmitOrder] (trainData, trainSeats, taskItem) {
    const queryInfo = taskItem.queryInfo
    const passengers = taskItem.passengers
    const chooseSeats = taskItem.chooseSeats
    let isStop = false // 是否终止提交(当未登录)
    let title = '提示'
    let content = '哎呀!!!被挤下线了,请重新登录'

    for (let train of trainData) {
      if (isStop) return

      for (let seatCode of trainSeats) {
        const seatText = Vue.api.base.getSeatTypeInfo(seatCode)

        // 提交订单
        this[_setStatus](`正在预订【${train.trainCode}】车次的【${seatText}】...`)
        this[_setCurrentTrain](train, seatText)

        const orderResult = await this[_submitOrder](train.secret, queryInfo)

        if (orderResult.code !== 200) {
          this[_setStatus](`【${train.trainCode}】车次的【${seatText}】预订失败`)
          Vue.alert(orderResult.message)

          continue
        }

        const orderResultData = orderResult.data

        // 检查订单
        this[_setStatus](`【${train.trainCode}】车次的【${seatText}】正在检查订单信息...`)
        const checkResult = await this[_checkOrderInfo](passengers, orderResultData.orderToken, '', seatCode)

        if (checkResult.code !== 200) {
          this[_setStatus](`【${train.trainCode}】车次的【${seatText}无法提交订单`)
          Vue.alert(checkResult.message)

          if (checkResult.message.indexOf('登录') > -1) {
            this[_setStatus]('您的登录状态已失效,请重新登录')
            Vue.eventBus.$emit('openDialog', 'loginModal')
            utils.notification.show(title, {
              body: content,
              tag: 'order'
            })

            isStop = true
            return
          }
          continue
        }

        const awaitTime = parseInt(checkResult.captchaCodeTime)

        // 是否要验证码
        if (checkResult.isCaptchaCode) {
          // 将确认提交订单的数据存储到store
          const orderData = {
            train,
            seatCode,
            passengers,
            key: orderResultData.orderKey,
            token: orderResultData.orderToken,
            awaitTime,
            chooseSeats
          }

          Vue.store.dispatch('setConfirmOrderData', orderData)
          content = `正在预订【${train.trainCode}】车次【${seatText}】,请选择验证码`
          this[_setStatus](`正在预订【${train.trainCode}】车次【${seatText}】,等待选择验证码...`)
          Vue.eventBus.$emit('openDialog', 'captchCodeModal')
          utils.notification.show(title, {
            body: content,
            tag: 'order'
          })

          isStop = true
          return
        }

        // 获取订单排队信息
        this[_setStatus](`【${train.trainCode}】车次的【${seatText}】正在排队...`)
        const queueResult = await this[_getOrderQueueInfo](train, queryInfo.trainDate, seatCode, orderResultData.orderToken)

        if (queueResult.code !== 200) {
          this[_setStatus](`队伍太长,【${train.trainCode}】车次的【${seatText}】没能挤进去`)
          Vue.alert(queueResult.message)

          if (queueResult.message.indexOf('登录') > -1) {
            this[_setStatus]('您的登录状态已失效,请重新登录')
            Vue.eventBus.$emit('openDialog', 'loginModal')
            utils.notification.show(title, {
              body: content,
              tag: 'order'
            })

            isStop = true
            return
          }
          continue
        }

        // 确认提交订单(不需要验证码)
        const confirmResult = await this.confirmOrderQueue(train, passengers, orderResultData.orderKey, orderResultData.orderToken, seatCode, '', awaitTime, chooseSeats)

        if (confirmResult.code < 1) {
          if (confirmResult.code === 0) {
            isStop = true
            return
          }
          continue
        }
      }
    }
  }

  /**
   * 提交订单
   * @param {*} trainSecret 车次凭证
   * @param {*} queryInfo 查询信息
   */
  static [_submitOrder] (trainSecret, queryInfo) {
    const currentDate = new Date()
    const formData = {
      secretStr: decodeURIComponent(trainSecret),
      train_date: queryInfo.trainDate,
      back_train_date: `${currentDate.getFullYear()}-${(currentDate.getMonth() + 1)}-${currentDate.getDate()}`,
      query_from_station_name: queryInfo.fromCityName,
      query_to_station_name: queryInfo.toCityName,
      ticketType: queryInfo.ticketType
    }

    return Vue.api.order.submitOrder(formData)
  }

  /**
   * 检查订单
   * @param {*} passengers 乘客
   * @param {*} token 订单token
   * @param {*} captchCode 验证码
   */
  static [_checkOrderInfo] (passengers, token, captchCode, seatCode) {
    const formData = {
      passengerTicketStr: passengers.passengerTickets.replace(/(seatcode)/gi, seatCode),
      oldPassengerStr: passengers.oldPassengers,
      REPEAT_SUBMIT_TOKEN: token,
      randCode: captchCode
    }

    return Vue.api.order.checkOrderInfo(formData)
  }

  /**
   * 获取提交订单队列信息
   * @param {*} train 车次
   * @param {*} trainDate 乘车日期
   * @param {*} seatCode 座位code
   * @param {*} token token
   */
  static [_getOrderQueueInfo] (train, trainDate, seatCode, token) {
    const currentDate = new Date()
    const arrDate = trainDate.split('-')

    currentDate.setFullYear(arrDate[0], arrDate[1] - 1, arrDate[2])

    const formData = {
      train_date: currentDate.toString(),
      train_no: train.trainNo,
      stationTrainCode: train.trainCode,
      seatType: seatCode,
      fromStationTelecode: train.fromCityCode,
      toStationTelecode: train.toCityCode,
      leftTicket: train.ypInfo,
      train_location: train.locationCode,
      REPEAT_SUBMIT_TOKEN: token
    }
    const seatText = Vue.api.base.getSeatTypeInfo(seatCode)

    return Vue.api.order.getOrderQueueInfo(formData, seatText)
  }

  /**
   * 确认提交订单
   * @param {*} train 车次
   * @param {*} passengers 乘客
   * @param {*} key key
   * @param {*} token token
   * @param {*} seatCode 座位code
   * @param {*} captchCode 验证码
   * @param {*} awaitTime 提交订单的等待时间
   * @param {*} chooseSeats 选择的座位
   */
  static async confirmOrderQueue (train, passengers, key, token, seatCode, captchCode, awaitTime, chooseSeats) {
    const seatText = Vue.api.base.getSeatTypeInfo(seatCode)
    const formData = {
      passengerTicketStr: passengers.passengerTickets.replace(/(seatcode)/gi, seatCode),
      oldPassengerStr: passengers.oldPassengers,
      randCode: captchCode,
      key_check_isChange: key,
      leftTicketStr: train.ypInfo,
      train_location: train.locationCode,
      choose_seats: chooseSeats, // 选座
      seatDetailType: '', // 选铺
      REPEAT_SUBMIT_TOKEN: token
    }

    this[_setStatus](`正在确认提交【${train.trainCode}】车次【${seatText}】...`)
    // 由于12306提交订单的安全周期问题,需要等待一定时间
    await utils.sleep(awaitTime)

    let res = await Vue.api.order.confirmOrderQueue(formData)
    let data = {}

    if (res.code !== 200) {
      this[_setStatus](`【${train.trainCode}】车次【${seatText}】预订失败...`)
      Vue.alert(res.message)

      if (res.message.indexOf('登录') > -1) {
        this[_setStatus]('您的登录状态已失效,请重新登录')
        Vue.eventBus.$emit('openDialog', 'loginModal')
        utils.notification.show('提示', {
          body: '哎呀!!!被挤下线了,请重新登录',
          tag: 'order'
        })

        data.code = 0
        return data
      }

      data.code = -1
      return data
    }

    this[_setStatus](`【${train.trainCode}】车次【${seatText}】等待出票...`)
    // 获取订单出票时间
    return this[_getOrderAwaitTime](train, seatText)
  }

  /**
   * 获取订单出票时间
   * @param {*} train 车次
   * @param {*} seatText 座位
   */
  static [_getOrderAwaitTime] (train, seatText) {
    return new Promise((resolve, reject) => {
      let data = {}
      let title = '提示'
      let content = '哎呀!!!被挤下线了,请重新登录'

      this.stopOrderAwaitFunc()

      this.startOrderAwaitFunc = setInterval(async () => {
        const res = await Vue.api.order.getOrderAwaitTime()

        if (res.code !== 200) {
          Vue.alert(res.message)

          if (res.message.indexOf('登录') > -1) {
            this.stopOrderAwaitFunc()

            this[_setStatus]('您的登录状态已失效,请重新登录')
            Vue.eventBus.$emit('openDialog', 'loginModal')
            utils.notification.show(title, {
              body: content,
              tag: 'order'
            })

            data.code = 0
            reject(data)
          }

          if (res.message.indexOf('出票超时') > -1) {
            this.stopOrderAwaitFunc()

            this[_setStatus](`【${train.trainCode}】车次【${seatText}出票失败...`)
            utils.notification.show(title, {
              body: `【${train.trainCode}】出票失败!原因:${res.message}`,
              tag: 'order'
            })

            data.code = -2
            reject(data)
          }

          data.code = -1
          reject(data)
        }

        // 出票成功
        if (res.orderId) {
          const orderNo = res.orderId

          title = 'WOW,恭喜您抢到票了~'
          content = `您的订单号:【${orderNo}】,请在30分钟内完成支付`

          this.stopOrderAwaitFunc()
          utils.speech.textToSpeech(`${title}您的订单号:【${orderNo.replace(/\s*/g, '|')}】,请在30分钟内完成支付`)
          this[_setStatus](`【${train.trainCode}】车次【${seatText}】出票成功...`)
          Vue.swal({
            title: title,
            text: content,
            icon: 'success',
            button: '我知道了'
          })
          utils.notification.show(title, {
            body: content
          })

          data.code = 1
          data.orderId = orderNo
          resolve(data)
        }
      }, 1000)
    })
  }

  /**
   * 开始提交订单(自动提交)
   * @param {*} trainData 车次
   * @param {*} trainSeats 座位
   * @param {*} taskItem 任务项
   */
  static async [_startAutoSubmitOder] (trainData, trainSeats, taskItem) {
    const queryInfo = taskItem.queryInfo
    const passengers = taskItem.passengers
    let isStop = false // 是否终止提交(当未登录)
    let title = '提示'
    let content = '哎呀!!!被挤下线了,请重新登录'

    for (let train of trainData) {
      if (isStop) return

      for (let seatCode of trainSeats) {
        const seatText = Vue.api.base.getSeatTypeInfo(seatCode)

        // 提交订单
        this[_setStatus](`正在预订【${train.trainCode}】车次的【${seatText}】...`)
        const orderResult = await this[_autoSubmitOrder](train.secret, queryInfo, passengers, seatCode)

        if (orderResult.code !== 200) {
          this[_setStatus](`【${train.trainCode}】车次的【${seatText}】预订失败`)
          Vue.alert(orderResult.message)

          if (orderResult.message.indexOf('登录') > -1) {
            this[_setStatus]('您的登录状态已失效,请重新登录')
            Vue.eventBus.$emit('openDialog', 'loginModal')
            utils.notification.show(title, {
              body: content,
              tag: 'order'
            })

            isStop = true
            return
          }
          continue
        }

        // 获取订单排队信息
        this[_setStatus](`【${train.trainCode}】车次的【${seatText}】正在排队...`)
        const queueResult = await this[_getOrderQueueInfoAsync](train, queryInfo.trainDate, seatCode)

        if (queueResult.code !== 200) {
          this[_setStatus](`队伍太长,【${train.trainCode}】车次的【${seatText}】没能挤进去`)
          Vue.alert(queueResult.message)

          if (queueResult.message.indexOf('登录') > -1) {
            this[_setStatus]('您的登录状态已失效,请重新登录')
            Vue.eventBus.$emit('openDialog', 'loginModal')
            utils.notification.show(title, {
              body: content,
              tag: 'order'
            })

            isStop = true
            return
          }
          continue
        }

        const key = orderResult.ticketData[1]
        const awaitTime = parseInt(orderResult.captchaCodeTime)

        // 是否要验证码
        if (orderResult.isCaptchaCode) {
          // 将确认提交订单的数据存储到store
          const orderData = {
            train,
            seatCode,
            passengers,
            key,
            awaitTime
          }

          Vue.store.dispatch('setConfirmOrderData', orderData)
          content = `正在预订【${train.trainCode}】车次【${seatText}】,请选择验证码`
          this[_setStatus](`正在预订【${train.trainCode}】车次【${seatText}】,等待选择验证码...`)
          Vue.eventBus.$emit('openDialog', 'captchCodeModal')
          utils.notification.show(title, {
            body: content,
            tag: 'order'
          })

          isStop = true
          return
        }

        // 确认提交订单(不需要验证码)
        const confirmResult = await this.confirmOrderQueueAsync(train, seatCode, passengers, key, '', awaitTime)

        if (confirmResult.code < 1) {
          if (confirmResult.code === 0) {
            isStop = true
            return
          }
          continue
        }
      }
    }
  }

  /**
   * 自动提交订单
   * @param {*} trainSecret 车次凭证
   * @param {*} queryInfo 查询信息
   * @param {*} passengers 乘客信息
   * @param {*} seatCode 座位代码
   */
  static [_autoSubmitOrder] (trainSecret, queryInfo, passengers, seatCode) {
    const orderData = {
      secretStr: decodeURIComponent(trainSecret),
      train_date: queryInfo.trainDate,
      query_from_station_name: queryInfo.fromCityName,
      query_to_station_name: queryInfo.toCityName,
      passengerTicketStr: passengers.passengerTickets.replace(/(seatcode)/gi, seatCode),
      oldPassengerStr: passengers.oldPassengers,
      ticketType: queryInfo.ticketType
    }

    return Vue.api.order.autoSubmitOrder(orderData)
  }

  /**
   * 订单排队信息(自动提交)
   * @param {*} train 车次
   * @param {*} trainDate 乘车日期
   * @param {*} seatCode 座位代码
   */
  static [_getOrderQueueInfoAsync] (train, trainDate, seatCode) {
    const currentDate = new Date()
    const arrDate = trainDate.split('-')

    currentDate.setFullYear(arrDate[0], arrDate[1] - 1, arrDate[2])

    const queueData = {
      train_date: currentDate.toString(),
      train_no: train.trainNo,
      stationTrainCode: train.trainCode,
      seatType: seatCode,
      fromStationTelecode: train.fromCityCode,
      toStationTelecode: train.toCityCode,
      leftTicket: train.ypInfo
      // ticketType: queryInfo.ticketType
    }

    return Vue.api.order.getOrderQueueInfoAsync(queueData)
  }

  /**
   * 确认提交订单(自动提交)
   * @param {*} train 车次
   * @param {*} seatCode 座位代码
   * @param {*} passengers 乘客
   * @param {*} key key
   * @param {*} captchCode 验证码
   * @param {*} awaitTime 提交订单的等待时间
   */
  static async confirmOrderQueueAsync (train, seatCode, passengers, key, captchCode, awaitTime) {
    const seatText = Vue.api.base.getSeatTypeInfo(seatCode)
    const passengerTicket = passengers.passengerTickets.replace(/(seatcode)/gi, seatCode)
    const formData = {
      passengerTicketStr: passengerTicket,
      oldPassengerStr: passengers.oldPassengers,
      randCode: captchCode,
      purpose_codes: '',
      key_check_isChange: key,
      leftTicketStr: train.ypInfo,
      train_location: train.locationCode,
      choose_seats: '',
      seatDetailType: ''
    }

    this[_setStatus](`正在确认提交【${train.trainCode}】车次【${seatText}】...`)
    // 由于12306提交订单的安全周期问题,需要等待一定时间
    await this.sleep(awaitTime)

    let res = await Vue.api.order.confirmOrderQueueAsync(formData)
    let data = {}

    if (res.code !== 200) {
      this[_setStatus](`【${train.trainCode}】车次【${seatText}】预订失败...`)
      Vue.alert(res.message)

      if (res.message.indexOf('登录') > -1) {
        this[_setStatus]('您的登录状态已失效,请重新登录')
        Vue.eventBus.$emit('openDialog', 'loginModal')
        utils.notification.show('提示', {
          body: '哎呀!!!被挤下线了,请重新登录',
          tag: 'order'
        })

        data.code = 0
        return data
      }

      data.code = -1
      return data
    }

    this[_setStatus](`【${train.trainCode}】车次【${seatText}】等待出票...`)
    // 获取订单出票时间
    return this[_getOrderAwaitTime](train, seatText)
  }
}

export default OrderTask


text:
echo "Starting build node configuration..."

echo "Installing expect: apt-get install expect"
sudo apt-get install expect

echo "Moving new settings.xml to MAVEN_HOME"

cp settings.xml $HOME/.m2/settings.xml

echo "------------------------------------------------------------------------"
echo "The new mvn settings are"
echo "------------------------------------------------------------------------"
cat $HOME/.m2/settings.xml
echo
echo "------------------------------------------------------------------------"

echo "New Maven configuration... DONE"

echo "Configuring git"
git config --global user.email $GIT_USER_EMAIL
git config --global user.name $GIT_USER_NAME
echo "Git configuration... DONE"


text:
package de.serviceflow.nutshell.cl.test1;

public class Expected {

	private final int result;

	public Expected(int result) {
		this.result = result;
	}

	public final int getResult() {
		return result;
	}
}


text:
/**
 * @author alteredq / http://alteredqualia.com/
 */

THREE.SavePass = function ( renderTarget ) {

	if ( THREE.CopyShader === undefined )
		console.error( "THREE.SavePass relies on THREE.CopyShader" );

	var shader = THREE.CopyShader;

	this.textureID = "tDiffuse";

	this.uniforms = THREE.UniformsUtils.clone( shader.uniforms );

	this.material = new THREE.ShaderMaterial( {

		uniforms: this.uniforms,
		vertexShader: shader.vertexShader,
		fragmentShader: shader.fragmentShader

	} );

	this.renderTarget = renderTarget;

	if ( this.renderTarget === undefined ) {

		this.renderTargetParameters = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBFormat, stencilBuffer: false };
		this.renderTarget = new THREE.WebGLRenderTarget( window.innerWidth, window.innerHeight, this.renderTargetParameters );

	}

	this.enabled = true;
	this.needsSwap = false;
	this.clear = false;

};

THREE.SavePass.prototype = {

	render: function ( renderer, writeBuffer, readBuffer, delta ) {

		if ( this.uniforms[ this.textureID ] ) {

			this.uniforms[ this.textureID ].value = readBuffer;

		}

		THREE.EffectComposer.quad.material = this.material;

		renderer.render( THREE.EffectComposer.scene, THREE.EffectComposer.camera, this.renderTarget, this.clear );

	}

};


text:
<?php

class ChargeIO_TransactionList extends ChargeIO_List {
	protected function parseResult($offset) {
		$transAttrs = $this->attributes['results'][$offset];
		try {
			return ChargeIO_Transaction::parse($transAttrs, $this->connection);
		}
		catch(Exception $ex) {
			throw new ChargeIO_Error('Unexpected transaction type ' . $transAttrs['type'] . ' at offset ' . $offset);
		}
	}
}


text:
@implementation PasswordlessLoginAPI
+ (instancetype)passwordlessInstance{
    static dispatch_once_t onceToken;
    static PasswordlessLoginAPI *instance;

    dispatch_once(&onceToken, ^{
        instance = [[PasswordlessLoginAPI alloc] init];
    });

    return instance;
}

-(void)passwordlessLoginWithEmail:(NSString *)email passwordlesslogintemplate:(NSString *)passwordlesslogintemplate verificationurl:(NSString *)verificationurl completionHandler:(LRAPIResponseHandler)completion {
    NSString *passwordlesslogin_template = passwordlesslogintemplate ? passwordlesslogintemplate: @"";
    [[LoginRadiusREST apiInstance] sendGET:@"identity/v2/auth/login/passwordlesslogin/email"
                               queryParams:@{
                                             @"apikey": [LoginRadiusSDK apiKey],
                                             @"email": email,
                                             @"passwordlesslogintemplate": passwordlesslogin_template,
                                             @"verificationurl":[LoginRadiusSDK verificationUrl]
                                             }
                         completionHandler:completion];
}

-(void)passwordlessLoginWithUserName:(NSString *)username passwordlesslogintemplate:(NSString *)passwordlesslogintemplate verificationurl:(NSString *)verificationurl completionHandler:(LRAPIResponseHandler)completion{
    NSString *passwordlesslogin_template = passwordlesslogintemplate ? passwordlesslogintemplate: @"";
    [[LoginRadiusREST apiInstance] sendGET:@"identity/v2/auth/login/passwordlesslogin/email"
                               queryParams:@{
                                             @"apikey": [LoginRadiusSDK apiKey],
                                             @"username": username,
                                             @"passwordlesslogintemplate": passwordlesslogin_template,
                                             @"verificationurl":[LoginRadiusSDK verificationUrl]
                                             }
                         completionHandler:completion];

}

-(void)passwordlessLoginVerificationWithVerificationToken:(NSString *)verificationtoken welcomeemailtemplate:(NSString *)welcomeemailtemplate completionHandler:(LRAPIResponseHandler)completion {
    NSString *welcomeemail_template = welcomeemailtemplate ? welcomeemailtemplate: @"";
    [[LoginRadiusREST apiInstance] sendGET:@"identity/v2/auth/login/passwordlesslogin/email/verify"
                               queryParams:@{
                                             @"apikey": [LoginRadiusSDK apiKey],
                                             @"verificationtoken": verificationtoken,
                                             @"welcomeemailtemplate": welcomeemail_template
                                             }
                         completionHandler:completion];

}

-(void)passwordlessLoginSendOtpWithPhone:(NSString *)phone smstemplate:(NSString *)smstemplate completionHandler:(LRAPIResponseHandler)completion{
    NSString *sms_template = smstemplate ? smstemplate: @"";
    [[LoginRadiusREST apiInstance] sendGET:@"identity/v2/auth/login/passwordlesslogin/otp"
                               queryParams:@{
                                             @"apikey": [LoginRadiusSDK apiKey],
                                             @"phone": phone,
                                             @"smstemplate": sms_template
                                             }
                         completionHandler:completion];

}

-(void)passwordlessPhoneLoginWithPayload:(NSDictionary *)payload smstemplate:(NSString *)smstemplate completionHandler:(LRAPIResponseHandler)completion{
    NSString *sms_template = smstemplate ? smstemplate: @"";
    [[LoginRadiusREST apiInstance] sendPUT:@"identity/v2/auth/login/passwordlesslogin/otp/verify"
                               queryParams:@{
                                             @"apikey": [LoginRadiusSDK apiKey],
                                             @"smstemplate": sms_template
                                             }
                                      body:payload
                         completionHandler:completion];
}

@end


text:
#import "MSGraphServiceCalendar.h"
#import "MSGraphServiceFetchers.h"

/** Implementation for MSGraphServiceCalendarCollectionOperations
 *
 */
@implementation MSGraphServiceCalendarCollectionOperations

@end


text:
'use strict';

/* jshint -W098 */
angular.module('cooperativa').controller('Cooperativa.Caja.EditarController',
	function ($scope, $state, caja, SGDialog) {

		$scope.view = {
			caja: caja
		};

		$scope.desactivar = function () {

			SGDialog.confirm('Desactivar', 'Estas seguro de querer eliminar permanentemente la caja?', function () {
				alert('Metdo no implementado');
			});

		};

	});


text:
/**
 *
 */
package picasso.parser.unaryFunctions;

import java.util.Stack;

import picasso.parser.SemanticAnalyzer;
import picasso.parser.binaryFunctions.BinaryFunctionAnalyzer;
import picasso.parser.language.ExpressionTreeNode;
import picasso.parser.language.expressions.binaryFunctions.ImageClip;
import picasso.parser.language.expressions.binaryFunctions.ImageWrap;
import picasso.parser.tokens.Token;
import picasso.parser.tokens.operations.StringToken;
import picasso.parser.language.expressions.Image;

/**
 * @author sharmas
 *
 */
public class ImageClipAnalyzer extends BinaryFunctionAnalyzer {

	/**
	 *
	 */
	@Override
	public ExpressionTreeNode generateExpressionTree(Stack<Token> tokens) {
		super.generateExpressionTree(tokens);

		StringToken st = (StringToken) tokens.pop();

		String fileName = st.input();

		return new ImageClip(fileName, left, right);
	}

}