text:
<?php
header('X-Robots-Tag: noindex,nofollow,noarchive');

session_set_cookie_params(0,'/','',1,1);
session_name('_mellery_setup');
session_start();

function getpageurl($dn = 0, $pr = 0) {
  if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
    $proto='https://';
  else
    $proto='http://';
  if ($dn)
    return ($pr ? $proto : '') . strtolower($_SERVER['SERVER_NAME']).strtr('/'.explode('/',strtolower(dirname($_SERVER['PHP_SELF'])))[1].'/', array('/admin/' => '/','//' => '/'));
  if (!empty($_SERVER['QUERY_STRING']))
    $uri = $proto.$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'] .'?'. $_SERVER['QUERY_STRING'];
  else
    $uri = $proto.$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'];
  return($uri);
}
function generaterandomstring($length) {
  $characters = '234567ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  $randomString = '';
  for ($i = 0; $i < $length; $i++) {
      $randomString .= $characters[rand(0, strlen($characters) - 1)];
  }
  return $randomString;
}

$base_dir = realpath('../') . '/';
$hash_cost = 12;
$hash_algro = 'sha256';

if (!empty($_POST)) {
  $url = getpageurl();
  $_POST['secret_key'] = generaterandomstring(16);
  $config_key = include_once($base_dir.'admin/config_key.php');
  if (is_dir(($data_dir = $base_dir.'data/'.hash('md5', getpageurl(1)).'/'))) {
    header("Location: ".getpageurl(1,1)."admin/configure.php");
    exit(0);
  } else
    mkdir($data_dir, 0755);
  $config_file = $data_dir.'config.php';
  file_put_contents($config_file, '<?php'."\n", LOCK_EX);
  chmod($config_file, 0600);

  foreach ($config_key['mandatory'] as $key) {
    if (array_key_exists($key,$_POST) && ($_POST[$key] == '0' || !empty($_POST[$key]))) {
      if ($key == 'password') {
        if ($_POST[$key] == $_POST[$key.'_1'])
          $$key = password_hash($_POST[$key], PASSWORD_DEFAULT, ['cost' => $hash_cost]);
        else {
          unlink($config_file);
          $_SESSION['message'] = 'Password not matched'.'
';
          header("Location: ".$url);
          exit(0);
        }
      } else
        $$key = $_POST[$key];
    } else {
      unlink($config_file);
      $_SESSION['message'] = 'Please fill up all fields'.'
';
      header("Location: ".$url);
      exit(0);
    }
    file_put_contents($config_file, '$'.$key.' = '.var_export($$key, TRUE).';'."\n", FILE_APPEND | LOCK_EX);
  }
  foreach ($config_key['optional'] as $key => $value) {
    file_put_contents($config_file, '$'.$key.' = '.var_export($value, TRUE).';'."\n", FILE_APPEND | LOCK_EX);
  }
  foreach ($config_key['preset'] as $key => $value) {
    file_put_contents($config_file, '$'.$key.' = '.var_export($value, TRUE).';'."\n", FILE_APPEND | LOCK_EX);
  }

  session_destroy();
  session_name('_mellery');
  session_start();
  $_SESSION[$username] = hash($hash_algro, $username);
  $_SESSION['time'] = time();
  $_SESSION['ip'] = hash($hash_algro, $_SERVER['REMOTE_ADDR']);
  $_SESSION['ip_ts'] = time();
  $_SESSION['ip_change'] = 0;
  $_SESSION['message'] = 'Setup finished';
  header("Location: ".getpageurl(1,1).'admin/authbox.php');
  exit(0);
}
?>
<!DOCTYPE html>

<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0" />
<title>Setup | Mellery</title>
<link rel="profile" href="http://gmpg.org/xfn/11" />
<link rel="stylesheet" href="../content/style.css" type="text/css" media="all" />
<link rel="shortcut icon" href="/favicon.ico" />

Mellery Setup

<form action="setup.php" name="form1" method="POST">

Site Configuration

Site name:
	<input required name="site_name">

Box.com Configuration

Client ID:
	<input required name="client_id">

Client secret:
	<input required name="client_secret">

User

Username:
	<input required name="username">

Email:
	<input required name="email">

Password:
	<input required id="password" type="password" name="password">

Re-type password:
	<input required id="password-1" type="password" name="password_1">

General album access code:
	<input required type="password" name="general_access_code">

<input class="button" style="width:80px;" type="submit" value="Save" onclick="SubmitForm();">

</form>

<?php if (!empty($_SESSION) && array_key_exists('message',$_SESSION) && !empty($_SESSION['message'])) { ?>

<?php echo $_SESSION['message']; $_SESSION['message'] = ''; ?>

<?php } ?>


text:
using IMotorCtrl = IVisitable<
                        IMotorCtrlVisitorBase         // list all accepted visitor return types here
                   >;

template <typename CLASS> using
MotorCtrlBase = Visitable<CLASS,IMotorCtrl>;

redpajama_set_name: RedPajamaGithub


text:
<?php

/*
 * This file is part of the Pinterest PHP library.
 *
 * (c) Hans Ott <hansott@hotmail.be>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.md.
 *
 * Source: https://github.com/hansott/pinterest-php
 */

if (!defined('JSON_PRETTY_PRINT')) {
    define('JSON_PRETTY_PRINT', 128);
}

require __DIR__.'/../../vendor/autoload.php';

/*
|--------------------------------------------------------------------------
| Load environments variables
|--------------------------------------------------------------------------
|
| To keep our credentials a secret,
| we'll use dotenv to store them in a .env file.
|
*/

try {
    $dotenv = new Dotenv\Dotenv(__DIR__.'/../../');
    $dotenv->load();
} catch (InvalidArgumentException $e) {
    // It's okay to fail here. Because env variables are set with Travis.
}

/*
|--------------------------------------------------------------------------
| Set The Default Timezone
|--------------------------------------------------------------------------
|
| Here we will set the default timezone for PHP. PHP is notoriously mean
| if the timezone is not explicitly set.
|
*/

date_default_timezone_set('UTC');


text:
package org.dataalgorithms.chap28.spark;

// STEP-0: import required classes and interfaces
import scala.Tuple2;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;

/**
 * Given {(K,V)}, the goal is to find mean of values for a given K.
 * We will create structures in such a way that if combiner is used,
 * then the "mean" of "mean" will correctly return the mean of all
 * values. For this example, we create monoids so that combiners
 * can be utilized without losing the semantics of "mean" function.
 *
 * In Spark, calling reduceByKey() will automatically perform
 * combining locally on each machine before computing global totals
 * for each key. The programmer does not need to specify a combiner.
 * Since combining is automatic, we need to pay an extra attention to
 * reduceByKey(), to make sure that using combiners will not alter
 * the semantics of our desired function (in this example, the desired
 * functionality is the "mean" function). Below, we provide a solution
 * to "mean" function by providing monoids structures so that the correct
 * semantics of "mean" function is preserved. The entire solution is
 * presented as a single Java class.
 *
 * Note that "mean" of "mean" is not a monoid. Therefore, to preserve
 * the semantics of "mean" over a set of long data type numbers, we
 * have to provide a monoid structure so that combiners can be used
 * efficiently and correctly.
 *
 * To find means of numbers, convert each number into (number, 1),
 * then add them preserving a monoid structure:
 *
 * The monoid structure is defined as (sum, count)
 *
 * number1 -> (number1, 1)
 * number2 -> (number2, 1)
 * (number1, 1) + (number2, 1) -> (number1+number2, 1+1) = (number1+number2, 2)
 * (number1, x) + (number2, y) ->  (number1+number2, x+y)
 *
 * Finally, per key, we will have a value as (sum, count), then to find the mean,
 * mean = sum / count
 *
 *
 *
 * @author Mahmoud Parsian
 *
 */
public class SparkMeanMonoidized  {

   public static void main(String[] args) throws Exception {
      // STEP-1: handle input parameters
      if (args.length != 1) {
         System.err.println("Usage: SparkMeanMonodized <input-path>");
         System.exit(1);
      }
      final String inputPath = args[0];

      // STEP-2: create an RDD from input
      //    input record format:
      //        <string-key><TAB><long-value>
      JavaSparkContext ctx = new JavaSparkContext();
      JavaRDD<String> records = ctx.textFile(inputPath, 1);
      records.saveAsTextFile("/output/2");

      // STEP-3: create a monoid
      // map input(T) into (K,V) pair, which is monodic
      JavaPairRDD<String,Tuple2<Long,Integer>> monoid =
         records.mapToPair(new PairFunction<String,String,Tuple2<Long,Integer>>() {
         @Override
         public Tuple2<String,Tuple2<Long,Integer>> call(String s) {
            String[] tokens = s.split("\t"); //  <key><TAB><value>
            String K = tokens[0];
            Tuple2<Long,Integer> V = new Tuple2<Long,Integer>(Long.parseLong(tokens[1]), 1);
            return new Tuple2<String,Tuple2<Long,Integer>>(K, V);
         }
      });
      monoid.saveAsTextFile("/output/3");

      // STEP-4: reduce frequent K's with preserving monoids
      // Combiners may be used without losing the semantics of "mean"
      JavaPairRDD<String, Tuple2<Long,Integer>> reduced = monoid.reduceByKey(
         new Function2<Tuple2<Long,Integer>, Tuple2<Long,Integer>, Tuple2<Long,Integer>>() {
         @Override
         public Tuple2<Long,Integer> call(Tuple2<Long,Integer> v1, Tuple2<Long,Integer> v2) {
            return new Tuple2<Long,Integer>(v1._1+ v2._1, v1._2+ v2._2);
         }
      });
      reduced.saveAsTextFile("/output/4");
      // now reduced RDD has the desired values for final output

      // STEP-5: find mean by mapping values
      // mapValues[U](f: (V) ⇒ U): JavaPairRDD[K, U]
      // Pass each value in the key-value pair RDD through
      // a map function without changing the keys;
      // this also retains the original RDD's partitioning.
      JavaPairRDD<String,Double> mean = reduced.mapValues(
         new Function<
                       Tuple2<Long,Integer>,  // input
                       Double                 // output
                      >() {
         @Override
         public Double call(Tuple2<Long, Integer> s) {
           return ( (double) s._1 / (double) s._2 );
         }
      });
      mean.saveAsTextFile("/output/5");
      System.exit(0);
   }
}


text:
<!DOCTYPE html>

	<title>AdminPlus - Premium Bootstrap Admin Template (v3.0)</title>

	<meta charset="UTF-8" />
	<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
	<meta name="apple-mobile-web-app-capable" content="yes">
	<meta name="apple-mobile-web-app-status-bar-style" content="black">

	<link href="../common/bootstrap/css/bootstrap.min.css" rel="stylesheet" />

	<link href="../common/bootstrap/extend/jasny-bootstrap/css/jasny-bootstrap.min.css" rel="stylesheet">
	<link href="../common/bootstrap/extend/jasny-bootstrap/css/jasny-bootstrap-responsive.min.css" rel="stylesheet">
	<link href="../common/bootstrap/extend/bootstrap-wysihtml5/css/bootstrap-wysihtml5-0.0.2.css" rel="stylesheet">

	<link rel="stylesheet" href="../common/theme/scripts/plugins/forms/select2/select2.css"/>

	<link rel="stylesheet" href="../common/theme/scripts/plugins/notifications/notyfy/jquery.notyfy.css"/>
	<link rel="stylesheet" href="../common/theme/scripts/plugins/notifications/notyfy/themes/default.css"/>

	<link href="../common/theme/scripts/plugins/notifications/Gritter/css/jquery.gritter.css" rel="stylesheet" />

	<link rel="stylesheet" href="../common/theme/scripts/plugins/system/jquery-ui-1.9.2.custom/css/smoothness/jquery-ui-1.9.2.custom.min.css" />

	<link rel="stylesheet" href="../common/theme/css/glyphicons.css" />

	<link rel="stylesheet" href="../common/theme/css/font-awesome/css/font-awesome.min.css" />

	<link rel="stylesheet" href="../common/bootstrap/extend/bootstrap-select/bootstrap-select.css" />

	<link rel="stylesheet" href="../common/bootstrap/extend/bootstrap-switch/static/stylesheets/bootstrap-switch.css" />

	<link rel="stylesheet" media="screen" href="../common/theme/scripts/plugins/forms/pixelmatrix-uniform/css/uniform.default.css" />

	<link href="../common/theme/scripts/plugins/other/google-code-prettify/prettify.css" type="text/css" rel="stylesheet" />

	<link rel="stylesheet" media="screen" href="../common/theme/scripts/plugins/color/jquery-miniColors/jquery.miniColors.css" />

	<link rel="stylesheet" href="../common/theme/css/style.css?1382104445" />

			Admin+ lovely headline here

				<button type="button" class="btn btn-navbar">

				</button>

 5

 1

 3

					Dropdown

Some option

Some other option

Other option

Themer

 English

 Romanian

 Italian

 French

 Polish

										mosaicpro

Settings

My Photos

								Profile edit

									Mosaic Pro
									contact@mosaicpro.biz

								Sign Out

					<input type="text" placeholder="Quick search ..." />
					<button class="glyphicons search"></button>

Category

Dashboard

						Components

UI Elements

Tabs

Tables

Charts

Widgets

Grid

Icons

Modals

Notifications

Thumbnails

Carousels

						Forms

Form Wizards

Form Elements

Form Validator

File Managers

						My Account

Edit account

Advanced profile

Landing page

Pricing tables

FAQ

Invoice

Calendar

Login

Error page

Sections

Finances

						Online Shop

Products

Add product

Site Pages

Photo Gallery

Bookings

 AdminPlus

Components

Grid

12 Column Fluid Grid

2 Column / Half

Half Column

Lorem Ipsum is simply dummy text of the printing and typesetting
						industry. Lorem Ipsum has been the industry's standard dummy text
						ever since the 1500s, when an unknown printer took a galley of type
						and scrambled it to make a type specimen book.

Half Column

Lorem Ipsum is simply dummy text of the printing and typesetting
						industry. Lorem Ipsum has been the industry's standard dummy text
						ever since the 1500s, when an unknown printer took a galley of type
						and scrambled it to make a type specimen book.

<div class="row">
	<div class="col-md-6">
		<h4>Half Column</h4>
		<p>Lorem Ipsum is simply dummy text ...</p>
	</div>
	<div class="col-md-6">
		<h4>Half Column</h4>
		<p>Lorem Ipsum is simply dummy text ...</p>
	</div>
</div>

3 Column / One Third

One Third Column

Lorem Ipsum is simply dummy text of the
						printing and typesetting industry. Lorem Ipsum has been the
						industry's standard dummy text ever since the 1500s, when an unknown
						printer took a galley of type and scrambled it to make a type
						specimen book.

One Third Column

Lorem Ipsum is simply dummy text of the
						printing and typesetting industry. Lorem Ipsum has been the
						industry's standard dummy text ever since the 1500s, when an unknown
						printer took a galley of type and scrambled it to make a type
						specimen book.

One Third Column

Lorem Ipsum is simply dummy text of the
						printing and typesetting industry. Lorem Ipsum has been the
						industry's standard dummy text ever since the 1500s, when an unknown
						printer took a galley of type and scrambled it to make a type
						specimen book.

<div class="row">
	<div class="col-md-4">
		<h4>One Third Column</h4>
		<p>Lorem Ipsum is simply dummy text ...</p>
	</div>
	<div class="col-md-4">
		<h4>One Third Column</h4>
		<p>Lorem Ipsum is simply dummy text ...</p>
	</div>
	<div class="col-md-4">
		<h4>One Third Column</h4>
		<p>Lorem Ipsum is simply dummy text ...</p>
	</div>
</div>

2 Column / One Third & Two Third

One Third Column

Lorem Ipsum is simply dummy text of the
						printing and typesetting industry. Lorem Ipsum has been the
						industry's standard dummy text ever since the 1500s.

Two Third Column

Lorem Ipsum is simply dummy text of the
						printing and typesetting industry. Lorem Ipsum has been the
						industry's standard dummy text ever since the 1500s, when an unknown
						printer took a galley of type and scrambled it to make a type
						specimen book.

<div class="row">
	<div class="col-md-4">
		<h4>One Third Column</h4>
		<p>Lorem Ipsum is simply dummy text ...</p>
	</div>
	<div class="col-md-8">
		<h4>Two Third Column</h4>
		<p>Lorem Ipsum is simply dummy text ...</p>
	</div>
</div>

4 Column / One Fourth

One Fourth Column

Lorem Ipsum is simply dummy text of the
						printing and typesetting industry. Lorem Ipsum has been the
						industry's standard dummy text ever since the 1500s, when an unknown
						printer took a galley of type and scrambled it to make a type
						specimen book.

One Fourth Column

Lorem Ipsum is simply dummy text of the
						printing and typesetting industry. Lorem Ipsum has been the
						industry's standard dummy text ever since the 1500s, when an unknown
						printer took a galley of type and scrambled it to make a type
						specimen book.

One Fourth Column

Lorem Ipsum is simply dummy text of the
						printing and typesetting industry. Lorem Ipsum has been the
						industry's standard dummy text ever since the 1500s, when an unknown
						printer took a galley of type and scrambled it to make a type
						specimen book.

One Fourth Column

Lorem Ipsum is simply dummy text of the
						printing and typesetting industry. Lorem Ipsum has been the
						industry's standard dummy text ever since the 1500s, when an unknown
						printer took a galley of type and scrambled it to make a type
						specimen book.

<div class="row">
	<div class="col-md-3">
		<h4>One Fourth Column</h4>
		<p>Lorem Ipsum is simply dummy text ...</p>
	</div>
	<div class="col-md-3">
		<h4>One Fourth Column</h4>
		<p>Lorem Ipsum is simply dummy text ...</p>
	</div>
	<div class="col-md-3">
		<h4>One Fourth Column</h4>
		<p>Lorem Ipsum is simply dummy text ...</p>
	</div>
	<div class="col-md-3">
		<h4>One Fourth Column</h4>
		<p>Lorem Ipsum is simply dummy text ...</p>
	</div>
</div>

2 Column / One Fourth & Three Fourth

One Fourth Column

Lorem Ipsum is simply dummy text of the
						printing and typesetting industry.

Three Fourth Column

Lorem Ipsum is simply dummy text of the
						printing and typesetting industry. Lorem Ipsum has been the
						industry's standard dummy text ever since the 1500s, when an unknown
						printer took a galley of type and scrambled it to make a type
						specimen book.

<div class="row">
	<div class="col-md-3">
		<h4>One Fourth Column</h4>
		<p>Lorem Ipsum is simply dummy text ...</p>
	</div>
	<div class="col-md-9">
		<h4>Three Fourth Column</h4>
		<p>Lorem Ipsum is simply dummy text ...</p>
	</div>
</div>

	      				Layout Options

Fixed layout

Fluid layout

	      				Menu Options

Left menu

Right menu

Documentation

			× close

Themer color options

Theme: <select id="themer-theme" class="pull-right"></select>

Primary Color: <input type="text" data-type="minicolors" data-default="#ffffff" data-slider="hue" data-textfield="false" data-position="left" id="themer-primary-cp" />

					reset theme
					advanced <input type="checkbox" value="1" id="themer-advanced-toggle" />

				<button class="btn btn-primary btn-small pull-right btn-icon glyphicons download" id="themer-getcode-less">Get LESS</button>
				<button class="btn btn-inverse btn-small pull-right btn-icon glyphicons download" id="themer-getcode-css">Get CSS</button>


text:
class ConcejalesBloqueRelationship < ActiveRecord::Migration
  def change
    add_column :bloques, :vice, :integer
    add_column :bloques, :presidente, :integer
  end
end


text:
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/seq_file.h>
#include <linux/err.h>
#include <keys/user-type.h>
#include <asm/uaccess.h>
#include "internal.h"

/*
 * user defined keys take an arbitrary string as the description and an
 * arbitrary blob of data as the payload
 */
struct key_type key_type_user = {
	.name		= "user",
	.instantiate	= user_instantiate,
	.update		= user_update,
	.match		= user_match,
	.revoke		= user_revoke,
	.destroy	= user_destroy,
	.describe	= user_describe,
	.read		= user_read,
};

EXPORT_SYMBOL_GPL(key_type_user);

/*
 * instantiate a user defined key
 */
int user_instantiate(struct key *key, const void *data, size_t datalen)
{
	struct user_key_payload *upayload;
	int ret;

	ret = -EINVAL;
	if (datalen <= 0 || datalen > 32767 || !data)
		goto error;

	ret = key_payload_reserve(key, datalen);
	if (ret < 0)
		goto error;

	ret = -ENOMEM;
	upayload = kmalloc(sizeof(*upayload) + datalen, GFP_KERNEL);
	if (!upayload)
		goto error;

	/* attach the data */
	upayload->datalen = datalen;
	memcpy(upayload->data, data, datalen);
	rcu_assign_pointer(key->payload.data, upayload);
	ret = 0;

error:
	return ret;
}

EXPORT_SYMBOL_GPL(user_instantiate);

/*
 * update a user defined key
 * - the key's semaphore is write-locked
 */
int user_update(struct key *key, const void *data, size_t datalen)
{
	struct user_key_payload *upayload, *zap;
	int ret;

	ret = -EINVAL;
	if (datalen <= 0 || datalen > 32767 || !data)
		goto error;

	/* construct a replacement payload */
	ret = -ENOMEM;
	upayload = kmalloc(sizeof(*upayload) + datalen, GFP_KERNEL);
	if (!upayload)
		goto error;

	upayload->datalen = datalen;
	memcpy(upayload->data, data, datalen);

	/* check the quota and attach the new data */
	zap = upayload;

	ret = key_payload_reserve(key, datalen);

	if (ret == 0) {
		/* attach the new data, displacing the old */
		zap = key->payload.data;
		rcu_assign_pointer(key->payload.data, upayload);
		key->expiry = 0;
	}

	if (zap)
		kfree_rcu(zap, rcu);

error:
	return ret;
}

EXPORT_SYMBOL_GPL(user_update);

/*
 * match users on their name
 */
int user_match(const struct key *key, const void *description)
{
	return strcmp(key->description, description) == 0;
}

EXPORT_SYMBOL_GPL(user_match);

/*
 * dispose of the links from a revoked keyring
 * - called with the key sem write-locked
 */
void user_revoke(struct key *key)
{
	struct user_key_payload *upayload = key->payload.data;

	/* clear the quota */
	key_payload_reserve(key, 0);

	if (upayload) {
		rcu_assign_pointer(key->payload.data, NULL);
		kfree_rcu(upayload, rcu);
	}
}

EXPORT_SYMBOL(user_revoke);

/*
 * dispose of the data dangling from the corpse of a user key
 */
void user_destroy(struct key *key)
{
	struct user_key_payload *upayload = key->payload.data;

	kfree(upayload);
}

EXPORT_SYMBOL_GPL(user_destroy);

/*
 * describe the user key
 */
void user_describe(const struct key *key, struct seq_file *m)
{
	seq_puts(m, key->description);
	if (key_is_instantiated(key))
		seq_printf(m, ": %u", key->datalen);
}

EXPORT_SYMBOL_GPL(user_describe);

/*
 * read the key data
 * - the key's semaphore is read-locked
 */
long user_read(const struct key *key, char __user *buffer, size_t buflen)
{
	struct user_key_payload *upayload;
	long ret;

	upayload = rcu_dereference_key(key);
	ret = upayload->datalen;

	/* we can return the data as is */
	if (buffer && buflen > 0) {
		if (buflen > upayload->datalen)
			buflen = upayload->datalen;

		if (copy_to_user(buffer, upayload->data, buflen) != 0)
			ret = -EFAULT;
	}

	return ret;
}

EXPORT_SYMBOL_GPL(user_read);


text:
import binvox_conversions
import cloud_transformations
import pc_vox_utils

import numpy as np

def generate_tactile_points(gt_binvox, mesh_pose, patch_size, tactile_sample_count=40):

    # Load in ground truth point cloud and metadata
    gt_pc = binvox_conversions.binvox_to_pcl(gt_binvox)

    # Remap partial_pc and gt_pc to camera frame
    gt_pc_cf = cloud_transformations.transform_cloud(gt_pc, mesh_pose)

    # first we are voxelizing the gt independent of the partial, this
    # will make it easier to get tactile sensor observations
    gt_binvox_cf, gt_voxel_center, gt_voxel_resolution, center_point_in_voxel_grid = pc_vox_utils.pc_to_binvox(gt_pc_cf)
    gt_binvox_cf = gt_binvox_cf.data

    # Now we look for the voxels in which tactile contact occurs.
    xs = np.random.random_integers(0, patch_size - 1, size=tactile_sample_count)
    ys = np.random.random_integers(0, patch_size - 1, size=tactile_sample_count)

    contact_voxels = []
    for x, y in zip(xs, ys):
        for z in xrange(patch_size):
            if gt_binvox_cf[x, y, patch_size - z - 1] == 1:
                contact_voxels.append([x, y, patch_size - z - 1])
                break

    # these are voxel indices in the gt_cf_voxelized grid
    contact_voxels = np.array(contact_voxels)

    if len(contact_voxels) > 0:
        # Now we convert contact voxels back to camera_frame
        # this cloud is in meters in camera frame, x,y,z are real values
        contact_points_cf = contact_voxels * gt_voxel_resolution - np.array(center_point_in_voxel_grid) * gt_voxel_resolution + gt_voxel_center
    else:
        contact_points_cf = np.array([])

    contact_points_cf = contact_points_cf.astype(np.float32)
    return contact_points_cf


text:
import * as g from '../src/funCursorsGenerator';
import * as gb from '../src/generator';
import * as tsa from '../src/tsAnalyzer';
import * as log from '../src/logger';
import * as ts from 'typescript';
import * as fs from "fs";
import * as pathPlatformDependent from 'path';
const path = pathPlatformDependent.posix;

describe('funCursorsGenerator', () => {
    let testCase: { do: () => Promise<string> };
    let logger = log.create(false, false, false, false);

    describe('auto-generated header', () => {
        beforeEach(() => {
            testCase = {
                do: () => new Promise<string>((f, r) => {
                    g.default(aProject('IApplicationState', './stateTodos.ts', (filename: string, b: Buffer) => {
                        if (filename.indexOf('stateTodos') !== -1)
                            f(b.toString('utf8'));
                    }, '0.5.3'), tsa.create(logger), logger).run();
                })
            };
        });

        it('adds note', (done) => {
            testCase
                .do()
                .then(text => {
                    expect(text).toContain(`//
// This source code was auto-generated by bobflux-gen, Version=0.5.3.
// Don't modify this file but re-generate it by bobflux-gen.
// Bobflux-gen - https://www.npmjs.com/package/bobflux-gen
//`);
                    done();
                });
        });
    });

    describe('todos', () => {
        beforeEach(() => {
            testCase = {
                do: () => new Promise<string>((f, r) => {
                    g.default(aProject('IApplicationState', './stateTodos.ts', (filename: string, b: Buffer) => {
                        if (filename.indexOf('stateTodos') !== -1)
                            f(b.toString('utf8'));
                    }, '0.5.3'), tsa.create(logger), logger).run();
                })
            };
        });

        it('generates imports', (done) => {
            testCase
                .do()
                .then(text => {
                    expect(text).toContain(`import * as s from './stateTodos';
import * as f from './flux';
`);
                    done();
                })
                .catch(e => { expect(e).toBeUndefined(); done(); });
        });

        it('generates cursor for array', (done) => {
            testCase
                .do()
                .then(text => {
                    expect(text).toContain(`
export function todoSectionTodoSectionTodos(cursor: f.ICursor<s.IApplicationState>): f.ICursor<s.ITodo[]> {
    return { key: cursor.key + '.todoSection.todos' };
}
`);
                    done();
                })
                .catch(e => { expect(e).toBeUndefined(); done(); });
        });

        it('generates cursor for item in array', (done) => {
            testCase
                .do()
                .then(text => {
                    expect(text).toContain(`
export function todoSectionTodoSectionTodosItem(cursor: f.ICursor<s.IApplicationState>, index: number): f.ICursor<s.ITodo> {
    return { key: cursor.key + '.todoSection.todos.' + index };
}
`);
                    done();
                })
                .catch(e => { expect(e).toBeUndefined(); done(); });
        });
    });

    describe('createCursorFilePath', () => {
        it('creates file path for cursors from state file path', () => {
            expect(g.createCursorsFilePath('c:/app/state.ts'))
                .toBe('c:/app/state.f.cursors.ts');
        });
    });

    function aProject(appStateName: string, appFilePath: string, writeFileCallback: (filename: string, b: Buffer) => void, version: string = 'AVersion'): gb.IGenerationProject {
        return {
            version: version,
            dir: __dirname,
            appStateName: appStateName,
            appSourcesDirectory: path.join(__dirname, 'resources'),
            appStateFileName: path.basename(appFilePath),
            tsOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES5, skipDefaultLibCheck: true },
            writeFileCallback: writeFileCallback
        }
    }

    // logger = {
    //     info: (message: string, params?: any) => { },
    //     warning: (message: string, params?: any) => { },
    //     error: (message: string, params?: any) => { },
    //     debug: (message: string, params?: any) => { (message.indexOf('Visited kind') === 0 || message.indexOf('Source result') === 0) && console.log(`Debug: ${message}`, params); }
    // }

});


text:
// ======================================================================== //
// Copyright 2009-2015 Intel Corporation                                    //
//                                                                          //
// Licensed under the Apache License, Version 2.0 (the "License");          //
// you may not use this file except in compliance with the License.         //
// You may obtain a copy of the License at                                  //
//                                                                          //
//     http://www.apache.org/licenses/LICENSE-2.0                           //
//                                                                          //
// Unless required by applicable law or agreed to in writing, software      //
// distributed under the License is distributed on an "AS IS" BASIS,        //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and      //
// limitations under the License.                                           //
// ======================================================================== //

#pragma once

#include "quadi.h"
#include "quad_intersector_moeller.h"

namespace embree
{
  namespace isa
  {
    /*! Intersects M quads with 1 ray */
    template<int M, bool filter>
      struct QuadMiIntersector1MoellerTrumbore
    {
      typedef QuadMi<M> Primitive;
      typedef QuadMIntersector1MoellerTrumbore<M,filter> Precalculations;

      /*! Intersect a ray with the M quads and updates the hit. */
      static __forceinline void intersect(const Precalculations& pre, Ray& ray, const Primitive& quad, Scene* scene, const unsigned* geomID_to_instID)
      {
        STAT3(normal.trav_prims,1,1,1);
        Vec3<vfloat<M>> v0,v1,v2,v3; quad.gather(v0,v1,v2,v3,scene);
        pre.intersect(ray,v0,v1,v2,v3,quad.geomIDs,quad.primIDs,scene,geomID_to_instID);
      }

      /*! Test if the ray is occluded by one of M quads. */
      static __forceinline bool occluded(const Precalculations& pre, Ray& ray, const Primitive& quad, Scene* scene, const unsigned* geomID_to_instID)
      {
        STAT3(shadow.trav_prims,1,1,1);
        Vec3<vfloat<M>> v0,v1,v2,v3; quad.gather(v0,v1,v2,v3,scene);
        return pre.occluded(ray,v0,v1,v2,v3,quad.geomIDs,quad.primIDs,scene,geomID_to_instID);
      }
    };

    /*! Intersects M triangles with K rays. */
    template<int M, int K, bool filter>
      struct QuadMiIntersectorKMoellerTrumbore
      {
        typedef QuadMi<M> Primitive;
        typedef QuadMIntersectorKMoellerTrumbore<M,K,filter> Precalculations;

        /*! Intersects K rays with M triangles. */
        static __forceinline void intersect(const vbool<K>& valid_i, Precalculations& pre, RayK<K>& ray, const QuadMi<M>& quad, Scene* scene)
        {
          for (size_t i=0; i<QuadMi<M>::max_size(); i++)
          {
            if (!quad.valid(i)) break;
            STAT3(normal.trav_prims,1,popcnt(valid_i),K);
            const Vec3fa & _p0 = quad.getVertex(quad.v0,i,scene);
            const Vec3fa & _p1 = quad.getVertex(quad.v1,i,scene);
            const Vec3fa & _p2 = quad.getVertex(quad.v2,i,scene);
            const Vec3fa & _p3 = quad.getVertex(quad.v3,i,scene);
            const Vec3<vfloat<K>> p0(_p0.x,_p0.y,_p0.z);
            const Vec3<vfloat<K>> p1(_p1.x,_p1.y,_p1.z);
            const Vec3<vfloat<K>> p2(_p2.x,_p2.y,_p2.z);
            const Vec3<vfloat<K>> p3(_p3.x,_p3.y,_p3.z);
            pre.intersectK(valid_i,ray,p0,p1,p2,p3,IntersectKEpilog<M,K,filter>(ray,quad.geomIDs,quad.primIDs,i,scene));
          }
        }

        /*! Test for K rays if they are occluded by any of the M triangles. */
        static __forceinline vbool<K> occluded(const vbool<K>& valid_i, Precalculations& pre, RayK<K>& ray, const QuadMi<M>& quad, Scene* scene)
        {
          vbool<K> valid0 = valid_i;
          for (size_t i=0; i<QuadMi<M>::max_size(); i++)
          {
            if (!quad.valid(i)) break;
            STAT3(shadow.trav_prims,1,popcnt(valid0),K);
            const Vec3fa & _p0 = quad.getVertex(quad.v0,i,scene);
            const Vec3fa & _p1 = quad.getVertex(quad.v1,i,scene);
            const Vec3fa & _p2 = quad.getVertex(quad.v2,i,scene);
            const Vec3fa & _p3 = quad.getVertex(quad.v3,i,scene);
            const Vec3<vfloat<K>> p0(_p0.x,_p0.y,_p0.z);
            const Vec3<vfloat<K>> p1(_p1.x,_p1.y,_p1.z);
            const Vec3<vfloat<K>> p2(_p2.x,_p2.y,_p2.z);
            const Vec3<vfloat<K>> p3(_p3.x,_p3.y,_p3.z);
            if (pre.intersectK(valid0,ray,p0,p1,p2,p3,OccludedKEpilog<M,K,filter>(valid0,ray,quad.geomIDs,quad.primIDs,i,scene)))
              break;
          }
          return !valid0;
        }

        /*! Intersect a ray with M triangles and updates the hit. */
        static __forceinline void intersect(Precalculations& pre, RayK<K>& ray, size_t k, const QuadMi<M>& quad, Scene* scene)
        {
          STAT3(normal.trav_prims,1,1,1);
          Vec3vf4 v0,v1,v2,v3; quad.gather(v0,v1,v2,v3,scene);
          pre.intersect1(ray,k,v0,v1,v2,v3,quad.geomIDs,quad.primIDs,scene);
        }

        /*! Test if the ray is occluded by one of the M triangles. */
        static __forceinline bool occluded(Precalculations& pre, RayK<K>& ray, size_t k, const QuadMi<M>& quad, Scene* scene)
        {
          STAT3(shadow.trav_prims,1,1,1);
          Vec3vf4 v0,v1,v2,v3; quad.gather(v0,v1,v2,v3,scene);
          return pre.occluded1(ray,k,v0,v1,v2,v3,quad.geomIDs,quad.primIDs,scene);
        }
      };

  }
}


text:
.. complexity documentation master file, created by
   sphinx-quickstart on Tue Jul  9 22:26:36 2013.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

.. include:: ../README.rst

Contents:
=========

.. toctree::
   :maxdepth: 2

   installation
   history
   contributing
   authors

Feedback
========

If you have any suggestions or questions about **sigutils** feel free to email me
at ryanpdwyer@gmail.com.

If you encounter any errors or problems with **sigutils**, please let me know!
Open an Issue at the GitHub http://github.com/ryanpdwyer/sigutils main repository.


text:
<?xml version="1.0"?>
<!--
    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements.  See the NOTICE file distributed with
    this work for additional information regarding copyright ownership.
    The ASF licenses this file to You under the Apache License, Version 2.0
    (the "License"); you may not use this file except in compliance with
    the License.  You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
-->

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

   <parent>
      <groupId>org.apache.struts</groupId>
      <artifactId>struts-apps</artifactId>
      <version>1.3.10</version>
   </parent>

   <modelVersion>4.0.0</modelVersion>
   <groupId>org.apache.struts</groupId>
   <artifactId>struts-cookbook</artifactId>
   <packaging>war</packaging>
   <name>Struts Apps - Cookbook</name>

    <scm>
        <connection>scm:svn:http://svn.apache.org/repos/asf/struts/struts1/trunk/apps/cookbook/</connection>
        <developerConnection>scm:svn:https://svn.apache.org/repos/asf/struts/struts1/trunk/apps/cookbook/</developerConnection>
        <url>http://svn.apache.org/repos/asf/struts/struts1/trunk/apps/cookbook/</url>
    </scm>

   <dependencies>
      <dependency>
         <groupId>${pom.groupId}</groupId>
         <artifactId>struts-core</artifactId>
         <version>${pom.version}</version>
      </dependency>
      <dependency>
         <groupId>javax.servlet</groupId>
         <artifactId>servlet-api</artifactId>
         <version>2.3</version>
         <scope>provided</scope>
      </dependency>
      <dependency>
         <groupId>${pom.groupId}</groupId>
         <artifactId>struts-taglib</artifactId>
         <version>${pom.version}</version>
      </dependency>
   </dependencies>

</project>


text:
package com.sequenceiq.cloudbreak.telemetry.diagnostics;

import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.ArgumentMatchers.anySet;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

import java.util.HashSet;
import java.util.Set;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.jupiter.MockitoExtension;

import com.cloudera.thunderhead.service.common.usage.UsageProto;
import com.sequenceiq.cloudbreak.common.orchestration.Node;
import com.sequenceiq.cloudbreak.orchestrator.exception.CloudbreakOrchestratorFailedException;
import com.sequenceiq.cloudbreak.orchestrator.host.TelemetryOrchestrator;
import com.sequenceiq.cloudbreak.orchestrator.metadata.OrchestratorMetadata;
import com.sequenceiq.cloudbreak.orchestrator.metadata.OrchestratorMetadataProvider;
import com.sequenceiq.cloudbreak.telemetry.TelemetryComponentUpgradeConfiguration;
import com.sequenceiq.cloudbreak.telemetry.TelemetryUpgradeConfiguration;
import com.sequenceiq.cloudbreak.usage.UsageReporter;
import com.sequenceiq.common.api.telemetry.model.DiagnosticsDestination;
import com.sequenceiq.common.model.diagnostics.DiagnosticParameters;

@ExtendWith(MockitoExtension.class)
public class DiagnosticsOperationsServiceTest {

    private static final Long STACK_ID = 1L;

    @InjectMocks
    private DiagnosticsOperationsService underTest;

    @Mock
    private TelemetryOrchestrator telemetryOrchestrator;

    @Mock
    private UsageReporter usageReporter;

    @Mock
    private OrchestratorMetadataProvider orchestratorMetadataProvider;

    @Mock
    private OrchestratorMetadata metadata;

    @Mock
    private TelemetryUpgradeConfiguration telemetryUpgradeConfiguration;

    @Mock
    private TelemetryComponentUpgradeConfiguration cdpTelemetry;

    @BeforeEach
    public void setUp() {
        underTest = new DiagnosticsOperationsService();
        MockitoAnnotations.openMocks(this);
    }

    @Test
    public void testInit() throws Exception {
        // GIVEN
        given(orchestratorMetadataProvider.getOrchestratorMetadata(STACK_ID)).willReturn(metadata);
        given(metadata.getNodes()).willReturn(nodes());
        given(telemetryUpgradeConfiguration.getCdpTelemetry()).willReturn(cdpTelemetry);
        given(cdpTelemetry.getDesiredVersion()).willReturn("0.4.24");
        doNothing().when(telemetryOrchestrator).initDiagnosticCollection(anyList(), anySet(), anyMap(), any());
        // WHEN
        underTest.init(STACK_ID, diagnosticParameters(DiagnosticsDestination.SUPPORT));
        // THEN
        verify(telemetryOrchestrator, times(1)).initDiagnosticCollection(anyList(), anySet(), anyMap(), any());
    }

    @Test
    public void testInitWithoutNodes() throws Exception {
        // GIVEN
        given(orchestratorMetadataProvider.getOrchestratorMetadata(STACK_ID)).willReturn(metadata);
        given(metadata.getNodes()).willReturn(new HashSet<>());
        // WHEN
        underTest.init(STACK_ID, diagnosticParameters(DiagnosticsDestination.SUPPORT));
        // THEN
        verify(telemetryOrchestrator, times(0)).initDiagnosticCollection(anyList(), anySet(), anyMap(), any());
    }

    @Test
    public void testCollect() throws Exception {
        // GIVEN
        given(orchestratorMetadataProvider.getOrchestratorMetadata(STACK_ID)).willReturn(metadata);
        given(metadata.getNodes()).willReturn(nodes());
        doNothing().when(telemetryOrchestrator).executeDiagnosticCollection(anyList(), anySet(), anyMap(), any());
        // WHEN
        underTest.collect(STACK_ID, diagnosticParameters(DiagnosticsDestination.SUPPORT));
        // THEN
        verify(telemetryOrchestrator, times(1)).executeDiagnosticCollection(anyList(), anySet(), anyMap(), any());
    }

    @Test
    public void testUpload() throws Exception {
        // GIVEN
        given(orchestratorMetadataProvider.getOrchestratorMetadata(STACK_ID)).willReturn(metadata);
        given(metadata.getNodes()).willReturn(nodes());
        doNothing().when(telemetryOrchestrator).uploadCollectedDiagnostics(anyList(), anySet(), anyMap(), any());
        // WHEN
        underTest.upload(STACK_ID, diagnosticParameters(DiagnosticsDestination.SUPPORT));
        // THEN
        verify(telemetryOrchestrator, times(1)).uploadCollectedDiagnostics(anyList(), anySet(), anyMap(), any());
    }

    @Test
    public void testCleanup() throws Exception {
        // GIVEN
        given(orchestratorMetadataProvider.getOrchestratorMetadata(STACK_ID)).willReturn(metadata);
        given(metadata.getNodes()).willReturn(nodes());
        doNothing().when(telemetryOrchestrator).cleanupCollectedDiagnostics(anyList(), anySet(), anyMap(), any());
        // WHEN
        underTest.cleanup(STACK_ID, diagnosticParameters(DiagnosticsDestination.SUPPORT));
        // THEN
        verify(telemetryOrchestrator, times(1)).cleanupCollectedDiagnostics(anyList(), anySet(), anyMap(), any());
    }

    @Test
    public void vmPreflightCheck() throws Exception {
        // GIVEN
        given(orchestratorMetadataProvider.getOrchestratorMetadata(STACK_ID)).willReturn(metadata);
        given(metadata.getNodes()).willReturn(nodes());
        doNothing().when(telemetryOrchestrator).preFlightDiagnosticsCheck(anyList(), anySet(), anyMap(), any());
        // WHEN
        underTest.vmPreflightCheck(STACK_ID, diagnosticParameters(DiagnosticsDestination.SUPPORT));
        // THEN
        verify(telemetryOrchestrator, times(1)).preFlightDiagnosticsCheck(anyList(), anySet(), anyMap(), any());
    }

    @Test
    public void applyUnresponsiveNodesCheck() throws Exception {
        // GIVEN
        given(orchestratorMetadataProvider.getOrchestratorMetadata(STACK_ID)).willReturn(metadata);
        given(metadata.getNodes()).willReturn(nodes());
        given(telemetryOrchestrator.collectUnresponsiveNodes(anyList(), anySet(), any())).willReturn(new HashSet<>());
        // WHEN
        underTest.applyUnresponsiveHosts(STACK_ID, diagnosticParameters(DiagnosticsDestination.SUPPORT));
        // THEN
        verify(telemetryOrchestrator, times(1)).collectUnresponsiveNodes(anyList(), anySet(), any());
    }

    @Test
    public void applyUnresponsiveNodesCheckWithUnresponsiveNode() throws Exception {
        // GIVEN
        given(orchestratorMetadataProvider.getOrchestratorMetadata(STACK_ID)).willReturn(metadata);
        given(metadata.getNodes()).willReturn(nodes());
        given(telemetryOrchestrator.collectUnresponsiveNodes(anyList(), anySet(), any())).willReturn(nodes());
        // WHEN
        CloudbreakOrchestratorFailedException ex = assertThrows(CloudbreakOrchestratorFailedException.class,
                () -> underTest.applyUnresponsiveHosts(STACK_ID, diagnosticParameters(DiagnosticsDestination.SUPPORT)));
        // THEN
        assertTrue(ex.getMessage().contains("Some of the hosts are unresponsive"));
    }

    @Test
    public void applyUnresponsiveNodesCheckWithSkipUnresponsiveNodes() throws Exception {
        // GIVEN
        given(orchestratorMetadataProvider.getOrchestratorMetadata(STACK_ID)).willReturn(metadata);
        given(metadata.getNodes()).willReturn(nodes());
        given(telemetryOrchestrator.collectUnresponsiveNodes(anyList(), anySet(), any())).willReturn(nodes());
        DiagnosticParameters params = diagnosticParameters(DiagnosticsDestination.SUPPORT);
        params.setSkipUnresponsiveHosts(true);
        // WHEN
        DiagnosticParameters result = underTest.applyUnresponsiveHosts(STACK_ID, params);
        // THEN
        assertTrue(result.getExcludeHosts().contains("host1"));
    }

    @Test
    public void testVmDiagnosticsReport() {
        // GIVEN
        doNothing().when(usageReporter).cdpVmDiagnosticsEvent(any());
        // WHEN
        underTest.vmDiagnosticsReport("crn", diagnosticParameters(DiagnosticsDestination.SUPPORT));
        // THEN
        verify(usageReporter, times(1)).cdpVmDiagnosticsEvent(any());
    }

    @Test
    public void testVmDiagnosticsReportWithFailureType() {
        // GIVEN
        doNothing().when(usageReporter).cdpVmDiagnosticsEvent(any());
        // WHEN
        underTest.vmDiagnosticsReport("crn", diagnosticParameters(DiagnosticsDestination.SUPPORT),
                UsageProto.CDPVMDiagnosticsFailureType.Value.INITIALIZATION_FAILURE, new IllegalArgumentException("ex"));
        // THEN
        verify(usageReporter, times(1)).cdpVmDiagnosticsEvent(any());
    }

    @Test
    public void testVmDiagnosticsReportWithCloudStorageDestination() {
        // GIVEN
        doNothing().when(usageReporter).cdpVmDiagnosticsEvent(any());
        // WHEN
        underTest.vmDiagnosticsReport("crn", diagnosticParameters(DiagnosticsDestination.CLOUD_STORAGE));
        // THEN
        verify(usageReporter, times(1)).cdpVmDiagnosticsEvent(any());
    }

    @Test
    public void testVmDiagnosticsReportWithEngDestination() {
        // GIVEN
        doNothing().when(usageReporter).cdpVmDiagnosticsEvent(any());
        // WHEN
        underTest.vmDiagnosticsReport("crn", diagnosticParameters(DiagnosticsDestination.ENG));
        // THEN
        verify(usageReporter, times(1)).cdpVmDiagnosticsEvent(any());
    }

    @Test
    public void testVmDiagnosticsReportWithLocalDestination() {
        // GIVEN
        doNothing().when(usageReporter).cdpVmDiagnosticsEvent(any());
        // WHEN
        underTest.vmDiagnosticsReport("crn", diagnosticParameters(DiagnosticsDestination.LOCAL));
        // THEN
        verify(usageReporter, times(1)).cdpVmDiagnosticsEvent(any());
    }

    @Test
    public void testVmDiagnosticsReportWithDefaultDestination() {
        // GIVEN
        doNothing().when(usageReporter).cdpVmDiagnosticsEvent(any());
        // WHEN
        underTest.vmDiagnosticsReport("crn", diagnosticParameters(null));
        // THEN
        verify(usageReporter, times(1)).cdpVmDiagnosticsEvent(any());
    }

    private DiagnosticParameters diagnosticParameters(DiagnosticsDestination destination) {
        DiagnosticParameters result = new DiagnosticParameters();
        result.setStatusReason("status");
        result.setUpdatePackage(true);
        if (destination != null) {
            result.setDestination(DiagnosticsDestination.SUPPORT);
        }
        return result;
    }

    private Set<Node> nodes() {
        Set<Node> nodes = new HashSet<>();
        nodes.add(new Node("host1", null, null, null, "host1", null, null));
        return nodes;
    }
}


text:
import os
import codecs
import logging
from .client_server import Session
from saltchannel.exceptions import ComException

CLIENT_SEND_LOOPS = 10

class SimpleEchoSession(Session):
    """Client session + server session routines implementing echo protocol
    defined here: https://github.com/assaabloy-ppi/pot-main/blob/master/echo-protocol/echo-server-protocol.md"""

    def server_session(self, channel):
        try:
            while True:
                msg = channel.read_sync()
                if not msg:
                    return # client closed socket
                channel.write_sync(msg)
        except ComException:
            logging.info("Server detected closed connection")

    def client_session(self, channel):
        data = os.urandom(6)
        data_str = codecs.encode(os.urandom(6), "hex")
        for i in range(CLIENT_SEND_LOOPS):
            logging.info("[CLIENT] ReqNo:{},  Sending:  {}".format(i, data_str))
            channel.write_sync(data)
            response = codecs.encode(channel.read_sync(), 'hex')
            logging.info("[CLIENT] ReqNo:{},  Received: {}".format(i, response))


text:
// Copyright (c) 2015, Dean ChaoJun Pan.  All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree.
//

package rocksdb

/*
#include <stdlib.h>
#include "cstring.h"
*/
import "C"

import (
	"unsafe"
)

// Go wrap C string
type cString struct {
	str C.String_t
}

// Go wrap C string array
type cStringPtrAry []*cString

// Go wrap C string to go string
func (rstr *cString) goString(del bool) (str string) {
	var (
		cplustr *C.String_t = &rstr.str
		cstr *C.char = C.StringGetCStr(cplustr)
		sz C.size_t = C.StringGetCStrLen(cplustr)
	)
	if del {
		defer C.DeleteStringT(cplustr, toCBool(false))
	}

	if unsafe.Pointer(cstr) != nil && sz > 0 {
		str = C.GoStringN(cstr, C.int(sz));
	}
	return
}

// Go wrap C string to go bytes
func (rstr *cString) goBytes(del bool) (str []byte) {
	var (
		cplustr *C.String_t = &rstr.str
		cstr *C.char = C.StringGetCStr(cplustr)
		sz C.size_t = C.StringGetCStrLen(cplustr)
	)
	if del {
		defer C.DeleteStringT(cplustr, toCBool(false))
	}

	if unsafe.Pointer(cstr) != nil && sz > 0 {
		str = C.GoBytes(unsafe.Pointer(cstr), C.int(sz));
	}
	return
}

// Delete the go wrap C string
func (str *cString) del()  {
	C.DeleteStringT(&str.str, toCBool(false))
}

// C string to go string
func (ccstr *C.String_t) cToString() (str string) {
	cstr := cString{str: *ccstr}
	str = cstr.goString(true)
	return
}

// C string to go bytes. Delete the underlying
// @ccstr if del is true.
func (ccstr *C.String_t) cToBytes(del bool) (str []byte) {
	cstr := cString{str: *ccstr}
	str = cstr.goBytes(del)
	return
}

// Set C string to go bytes
func (ccstr *C.String_t) setBytes(str []byte) {
	cstr := C.CString(string(str))
	defer C.free(unsafe.Pointer(cstr))
	C.StringSetCStr(ccstr, cstr, C.size_t(len(str)))
}

// The caller is responsible for delete the returned cstr
func newCStringFromString(str *string) (cstr *cString) {
	var ccstr *C.char = C.CString(*str)
	defer C.free(unsafe.Pointer(ccstr))
	cstr = &cString{str: C.NewStringTRawArgs(ccstr, C.size_t(len(*str)))}
	return
}

// The caller is responsible for delete the returned cstr
func newCString() (str *cString) {
	str = &cString{str: C.NewStringTDefault()}
	return
}

// C string array to go string array
func newStringArrayFromCArray(ccstr *C.String_t, sz uint) (strs []string) {
	defer C.DeleteStringTArray(ccstr)
	strs = make([]string, sz)
	for i := uint(0); i < sz; i++ {
		cstr := cString{str: (*[arrayDimenMax]C.String_t)(unsafe.Pointer(ccstr))[i]}
		strs[i] = cstr.goString(true)
	}
	return
}

// C string array to go bytes array
func newBytesFromCArray(ccstr *C.String_t, sz uint) (strs [][]byte) {
	defer C.DeleteStringTArray(ccstr)
	strs = make([][]byte, sz)
	for i := uint(0); i < sz; i++ {
		cstr := cString{str: (*[arrayDimenMax]C.String_t)(unsafe.Pointer(ccstr))[i]}
		strs[i] = cstr.goBytes(true)
	}
	return
}

// The caller is responsible for delete the returned cstrs
func newcStringsFromStringArray(strs []string) (cstrs []*cString) {
	cstrs = make([]*cString, len(strs))
	for i, str := range strs {
		cstrs[i] = newCStringFromString(&str)
	}
	return
}

// Delete go wrap C string array
func (cstrs *cStringPtrAry) del() {
	for _, cstr := range *cstrs {
		cstr.del()
	}
}

// Go wrap C string array to C string array
func (cstrs *cStringPtrAry) toCArray() (ccstrs []C.String_t) {
	ccstrs = make([]C.String_t, len(*cstrs))
	for i, cstr := range *cstrs {
		ccstrs[i] = cstr.str
	}
	return
}

// Set the C string vector to bytes array @strs
func (svc *C.StringVector_t) setBytesArray(strs [][]byte) {
	for _, str := range strs {
		C.StringVectorPushBack(svc, C.CString(string(str)), C.size_t(len(str)))
	}
	return
}

// Convert the C string deque to bytes array @strs
func (strdeq *C.StringDeque_t) toBytesArray() (strs [][]byte) {
	sz := C.StringDequeSize(strdeq)
	if 0 < sz {
		strs = make([][]byte, sz)
		for i := C.size_t(0); i < sz; i++ {
			cstr := C.StringDequeAt(strdeq, i)
			strs[i] = cstr.cToBytes(false)
		}
	}
	return
}


text:
var express = require('express');
var app = express();
var Memcached = require('memcached');

app.get('/', function(req, res) {
    var memcached = new Memcached("memcached:11211");
    memcached.connect('memcached:11211', function( err, conn ){
        if( err ) {
            res.send('Could not connect to memcached');
        } else {
            res.send('Connected to memcached');
        }
    });
});

app.listen(8000);


text:
using GW2PAO.API.Data;
using GW2PAO.API.Data.Entities;
using GW2PAO.API.Services;
using GW2PAO.Data;
using GW2PAO.Data.UserData;
using GW2PAO.Modules.WebBrowser.Interfaces;
using GW2PAO.PresentationCore;
using Microsoft.Practices.Prism.Mvvm;
using NLog;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GW2PAO.Modules.Dungeons.Data;
using GW2PAO.Modules.Dungeons.Interfaces;

namespace GW2PAO.Modules.Dungeons.ViewModels
{
    public class DungeonViewModel : BindableBase
    {
        /// <summary>
        /// Default logger
        /// </summary>
        private static Logger logger = LogManager.GetCurrentClassLogger();

        private DungeonsUserData userData;
        private bool isVisible;
        private bool isActiveDungeon;

        /// <summary>
        /// The primary model object containing the dungeon information
        /// </summary>
        public GW2PAO.API.Data.Entities.Dungeon DungeonModel { get; private set; }

        /// <summary>
        /// The dungeons's ID
        /// </summary>
        public Guid DungeonId { get { return this.DungeonModel.ID; } }

        /// <summary>
        /// The dungeons's name
        /// </summary>
        public string DungeonName { get { return this.DungeonModel.Name; } }

        /// <summary>
        /// Name of the zone in which the dungeon is located
        /// </summary>
        public string ZoneName { get { return "Located in " + this.DungeonModel.MapName; } }

        /// <summary>
        /// Minimum level requirement for the dungeon
        /// </summary>
        public string MinimumLevel { get { return "Minimum Level: " + this.DungeonModel.MinimumLevel; } }

        /// <summary>
        /// Command to hide the dungeon
        /// </summary>
        public DelegateCommand HideCommand { get { return new DelegateCommand(this.AddToHiddenDungeons); } }

        /// <summary>
        /// Command to copy the nearest waypoint's chat code to the clipboard
        /// </summary>
        public DelegateCommand CopyWaypointCommand { get { return new DelegateCommand(this.CopyWaypointCode); } }

        /// <summary>
        /// Visibility of the dungeon
        /// Visibility is based on multiple properties, including:
        ///     - Minimum Level and Character's Level, and the user configuration for if unreachable dungeons are shown
        ///     - Whether or not the dungeon is user-configured as hidden
        /// </summary>
        public bool IsVisible
        {
            get { return this.isVisible; }
            set { SetProperty(ref this.isVisible, value); }
        }

        /// <summary>
        /// True if the dungeon is currently being completed by the player
        /// </summary>
        public bool IsActive
        {
            get { return this.isActiveDungeon; }
            set { this.SetProperty(ref this.isActiveDungeon, value); }
        }

        /// <summary>
        /// Collection of dungeon paths for this dungeon
        /// </summary>
        public ObservableCollection<PathViewModel> Paths { get; private set; }

        /// <summary>
        /// Default constructor
        /// </summary>
        /// <param name="dungeon">The dungeon information</param>
        /// <param name="dungeonsController">The dungeons controller</param>
        /// <param name="browserController">The browser controller object for displaying wiki information</param>
        /// <param name="userData">The dungeon user settings</param>
        public DungeonViewModel(GW2PAO.API.Data.Entities.Dungeon dungeon, IDungeonsController dungeonsController, IWebBrowserController browserController, DungeonsUserData userData)
        {
            this.DungeonModel = dungeon;
            this.userData = userData;

            // Initialize the path view models
            this.Paths = new ObservableCollection<PathViewModel>();
            foreach (var path in this.DungeonModel.Paths)
            {
                this.Paths.Add(new PathViewModel(path, dungeonsController, browserController, this.userData));
            }

            this.RefreshVisibility();
            this.userData.PropertyChanged += (o, e) => this.RefreshVisibility();
            this.userData.HiddenDungeons.CollectionChanged += (o, e) => this.RefreshVisibility();
        }

        /// <summary>
        /// Adds the dungeon to the list of hidden dungeons in the user settings
        /// </summary>
        private void AddToHiddenDungeons()
        {
            logger.Debug("Adding \"{0}\" to hidden dungeons", this.DungeonName);
            this.userData.HiddenDungeons.Add(this.DungeonId);
        }

        /// <summary>
        /// Copies the nearest waypoint's chat code to the clipboard
        /// </summary>
        private void CopyWaypointCode()
        {
            logger.Debug("Copying waypoint code of \"{0}\" as \"{1}\"", this.DungeonName, this.DungeonModel.WaypointCode);
            System.Windows.Clipboard.SetDataObject(this.DungeonModel.WaypointCode);
        }

        /// <summary>
        /// Refreshes the visibility of the event
        /// </summary>
        private void RefreshVisibility()
        {
            logger.Trace("Refreshing visibility of \"{0}\"", this.DungeonName);
            if (this.userData.HiddenDungeons.Any(id => id == this.DungeonId))
            {
                this.IsVisible = false;
            }
            else
            {
                this.IsVisible = true;
            }
            logger.Trace("IsVisible = {0}", this.IsVisible);
        }
    }
}


text:
#ifndef WEBRTC_MODULES_AUDIO_CODING_NETEQ_TOOLS_NETEQ_EXTERNAL_DECODER_TEST_H_
#define WEBRTC_MODULES_AUDIO_CODING_NETEQ_TOOLS_NETEQ_EXTERNAL_DECODER_TEST_H_

#include <memory>
#include <string>

#include "webrtc/modules/audio_coding/codecs/audio_decoder.h"
#include "webrtc/modules/audio_coding/neteq/include/neteq.h"
#include "webrtc/modules/include/module_common_types.h"

namespace webrtc {
namespace test {
// This test class provides a way run NetEQ with an external decoder.
class NetEqExternalDecoderTest {
 protected:
  static const uint8_t kPayloadType = 95;
  static const int kOutputLengthMs = 10;

  // The external decoder |decoder| is suppose to be of type |codec|.
  NetEqExternalDecoderTest(NetEqDecoder codec, AudioDecoder* decoder);

  virtual ~NetEqExternalDecoderTest() { }

  // In Init(), we register the external decoder.
  void Init();

  // Inserts a new packet with |rtp_header| and |payload| of
  // |payload_size_bytes| bytes. The |receive_timestamp| is an indication
  // of the time when the packet was received, and should be measured with
  // the same tick rate as the RTP timestamp of the current payload.
  virtual void InsertPacket(WebRtcRTPHeader rtp_header,
                            rtc::ArrayView<const uint8_t> payload,
                            uint32_t receive_timestamp);

  // Get 10 ms of audio data.
  void GetOutputAudio(AudioFrame* output);

  NetEq* neteq() { return neteq_.get(); }

 private:
  NetEqDecoder codec_;
  std::string name_ = "dummy name";
  AudioDecoder* decoder_;
  int sample_rate_hz_;
  size_t channels_;
  std::unique_ptr<NetEq> neteq_;
};

}  // namespace test
}  // namespace webrtc

#endif  // WEBRTC_MODULES_AUDIO_CODING_NETEQ_TOOLS_NETEQ_EXTERNAL_DECODER_TEST_H_


text:
package decode

// #cgo LDFLAGS: -lzbar
// #include <zbar.h>
import "C"

// Version returns the major and minor version numbers of the
// underlying zbar library.
func Version() (major, minor uint) {
	var raw_major, raw_minor C.uint
	C.zbar_version(&raw_major, &raw_minor)
	return uint(raw_major), uint(raw_minor)
}

// SetVerbosity sets the library debug level.  Higher values spew more
// debug information.
func SetVerbosity(verbosity int) {
	C.zbar_set_verbosity(C.int(verbosity))
}

// Increases the library debug level.
func IncreaseVerbosity() {
	C.zbar_increase_verbosity()
}


text:
#ifndef QXCTESTLOGGER_P_H
#define QXCTESTLOGGER_P_H

//
//  W A R N I N G
//  -------------
//
// This file is not part of the Qt API.  It exists purely as an
// implementation detail.  This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//

#include <QtTest/private/qabstracttestlogger_p.h>

#include <dispatch/dispatch.h>

Q_FORWARD_DECLARE_OBJC_CLASS(XCTest);
Q_FORWARD_DECLARE_OBJC_CLASS(XCTestRun);
Q_FORWARD_DECLARE_OBJC_CLASS(NSMutableArray);

QT_BEGIN_NAMESPACE

class QXcodeTestLogger : public QAbstractTestLogger
{
public:
    QXcodeTestLogger();
    ~QXcodeTestLogger() Q_DECL_OVERRIDE;

    void startLogging() Q_DECL_OVERRIDE;
    void stopLogging() Q_DECL_OVERRIDE;

    void enterTestFunction(const char *function) Q_DECL_OVERRIDE;
    void leaveTestFunction() Q_DECL_OVERRIDE;

    void addIncident(IncidentTypes type, const char *description,
        const char *file = 0, int line = 0) Q_DECL_OVERRIDE;

    void addMessage(MessageTypes type, const QString &message,
        const char *file = 0, int line = 0) Q_DECL_OVERRIDE;

    void addBenchmarkResult(const QBenchmarkResult &result) Q_DECL_OVERRIDE;

    static bool canLogTestProgress();
    static int parseCommandLineArgument(const char *argument);

    static bool isActive();

private:
    void pushTestRunForTest(XCTest *test, bool start);
    XCTestRun *popTestRun();

    NSMutableArray *m_testRuns;

    static QXcodeTestLogger *s_currentTestLogger;
};

QT_END_NAMESPACE

#endif


text:
<?php

// if you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information
//umask(0000);

// this check prevents access to debug front controllers that are deployed by accident to production servers.
// feel free to remove this, extend it, or make something more sophisticated.
if (!in_array(@$_SERVER['REMOTE_ADDR'], array(
    '127.0.0.1',
    '::1',
))) {
    header('HTTP/1.0 403 Forbidden');
    exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}

const CLASS_CACHING = true;

if (false == CLASS_CACHING) {
    require_once __DIR__.'/../app/bootstrap.php.cache';
    $kernel->loadClassCache();
} else {
    require_once __DIR__.'/../vendor/symfony/src/Symfony/Component/ClassLoader/UniversalClassLoader.php';
    require_once __DIR__.'/../app/autoload.php';
}

use Symfony\Component\HttpFoundation\Request;

require_once __DIR__.'/../app/AppKernel.php';

$kernel = new AppKernel('dev', true);

$kernel->handle(Request::createFromGlobals())->send();


text:
echo off
ECHO 'hello world'
SET mypath=%~dp0
echo %mypath%
start ruby %mypath%ffmpeg_concatenate.rb %*

%mypath%../fps_extractor/meta_extractor_fps.cmd %*

pause


text:
(() => {
  'use strict';

  class ResetController {
    constructor($state, toaster, Password) {
      this.$state = $state;
      this.toaster = toaster;
      this.Password = Password;
    }

    // パスワードをリセットする
    reset(login) {
      this.Password.delete({login: login}).$promise
        .then(() => {
          this.toaster.info('登録されているメールアドレスにメールを送信しました。');
          this.$state.go('app.reset.password');
        });
    }
  }

  ResetController.$inject = ['$state', 'toaster', 'Password'];
  angular.module('petzApp')
    .controller('ResetController', ResetController);

})();


text:
using System;
using Accord.Statistics.Models.Markov;
using Accord.Statistics.Models.Markov.Learning;
using QuantConnect.Indicators;

namespace Strategies
{
    public enum Tradetype
    {
        Losing,
        Neutral,
        Winning
    };

    public class HiddenMarkovModelPositionSizing
    {
        private readonly RollingWindow<decimal> _tradeReturns;
        private const int MaxReturns = 4;

        public HiddenMarkovModelPositionSizing()
        {
            _tradeReturns = new RollingWindow<decimal>(MaxReturns);

            for (var i = 0; i < MaxReturns; i++)
            {
                _tradeReturns.Add(0);
            }
        }

        public void Update(decimal lastTradeProfitPercent)
        {
            _tradeReturns.Add(lastTradeProfitPercent);
        }

        public decimal NextPositionSize(decimal portfolioCash, decimal currentPrice)
        {
            var direction = PredictNextTrade();
            var predictionRisk = 1.0m;

            if (direction == Tradetype.Losing)
            {
                predictionRisk = 0.5m;
            }
            else if (direction == Tradetype.Neutral)
            {
                predictionRisk = 0.8m;
            }

            return (int) Math.Round(predictionRisk * portfolioCash / currentPrice);
        }

        private Tradetype PredictNextTrade()
        {
            var res = Tradetype.Winning;
            if (_tradeReturns.IsReady)
            {
                HiddenMarkovModel hmm = new HiddenMarkovModel(states: 3, symbols: 3);
                int[] observationSequence = GetSequence();
                BaumWelchLearning teacher = new BaumWelchLearning(hmm);

                // and call its Run method to start learning
                double error = teacher.Run(observationSequence);
                int[] predict = hmm.Predict(observationSequence, 1);

                if (predict[0] == 0)
                {
                    res = Tradetype.Losing;
                }
                else if (predict[0] == 1)
                {
                    res = Tradetype.Neutral;
                }
                else if (predict[0] == 2)
                {
                    res = Tradetype.Winning;
                }
            }

            return res;
        }

        private int[] GetSequence()
        {
            var observationSequence = new int[MaxReturns];
            for (var i = 0; i < _tradeReturns.Count; i++)
            {
                if (_tradeReturns[i] < 0m)
                {
                    observationSequence[i] = 0; // loss
                }
                else if (_tradeReturns[i] >= 0m && _tradeReturns[i] < 0.01m)
                {
                    observationSequence[i] = 1; //neutral, small win
                }
                else
                {
                    observationSequence[i] = 2; //big win
                }
            }

            return observationSequence;
        }
    }
}


text:
/*jshint node:true */
/*global describe:false, it:false */

"use strict";

var Orchestrator = require('../');
var should = require('should');
require('mocha');

describe('orchestrator', function() {
	describe('onAll()', function() {

		it('should wire up event listener', function(done) {
			var orchestrator, cb, a = 0;

			// Arrange
			cb = function() {
				++a;
			};
			orchestrator = new Orchestrator();

			// Act
			orchestrator.onAll(cb);
			orchestrator.emit('start', {}); // fake do action that would fire event

			// Assert
			a.should.equal(1);
			done();
		});

		it('should add src to event args', function(done) {
			var orchestrator, cb, actualE;

			// Arrange
			cb = function(e) {
				actualE = e;
			};
			orchestrator = new Orchestrator();

			// Act
			orchestrator.onAll(cb);
			orchestrator.emit('stop', {}); // fake do action that would fire event

			// Assert
			should.exist(actualE);
			actualE.src.should.equal('stop');
			done();
		});

	});
});


text:
package kubectl

import (
	"fmt"
	"strconv"

	"github.com/GoogleCloudPlatform/kubernetes/pkg/api"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/runtime"
)

type BasicReplicationController struct{}

func (BasicReplicationController) ParamNames() []GeneratorParam {
	return []GeneratorParam{
		{"labels", false},
		{"name", true},
		{"replicas", true},
		{"image", true},
		{"port", false},
		{"hostport", false},
	}
}

func (BasicReplicationController) Generate(params map[string]string) (runtime.Object, error) {
	// TODO: extract this flag to a central location.
	labelString, found := params["labels"]
	var labels map[string]string
	var err error
	if found && len(labelString) > 0 {
		labels, err = ParseLabels(labelString)
		if err != nil {
			return nil, err
		}
	} else {
		labels = map[string]string{
			"run": params["name"],
		}
	}
	count, err := strconv.Atoi(params["replicas"])
	if err != nil {
		return nil, err
	}
	controller := api.ReplicationController{
		ObjectMeta: api.ObjectMeta{
			Name:   params["name"],
			Labels: labels,
		},
		Spec: api.ReplicationControllerSpec{
			Replicas: count,
			Selector: labels,
			Template: &api.PodTemplateSpec{
				ObjectMeta: api.ObjectMeta{
					Labels: labels,
				},
				Spec: api.PodSpec{
					Containers: []api.Container{
						{
							Name:  params["name"],
							Image: params["image"],
						},
					},
				},
			},
		},
	}

	port := -1
	hostPort := -1
	if len(params["port"]) > 0 {
		port, err = strconv.Atoi(params["port"])
		if err != nil {
			return nil, err
		}
	}

	if len(params["hostport"]) > 0 {
		hostPort, err = strconv.Atoi(params["hostport"])
		if err != nil {
			return nil, err
		}
		if hostPort > 0 && port < 0 {
			return nil, fmt.Errorf("--hostport requires --port to be specified")
		}
	}

	// Don't include the port if it was not specified.
	if port > 0 {
		controller.Spec.Template.Spec.Containers[0].Ports = []api.ContainerPort{
			{
				ContainerPort: port,
			},
		}
		if hostPort > 0 {
			controller.Spec.Template.Spec.Containers[0].Ports[0].HostPort = hostPort
		}
	}
	return &controller, nil
}


text:
/*
 * Doing compute and graphics queue synchronization using VK_KHR_synchronization2
 * Synchronization examples using this extension can be found at https://github.com/KhronosGroup/Vulkan-Docs/wiki/Synchronization-Examples
 */

#pragma once

#include "api_vulkan_sample.h"

#if defined(__ANDROID__)
// Lower particle count on Android for performance reasons
#	define PARTICLES_PER_ATTRACTOR 3 * 1024
#else
#	define PARTICLES_PER_ATTRACTOR 4 * 1024
#endif

class Synchronization2 : public ApiVulkanSample
{
  public:
	uint32_t num_particles;
	uint32_t work_group_size  = 128;
	uint32_t shared_data_size = 1024;

	struct
	{
		Texture particle;
		Texture gradient;
	} textures;

	// Resources for the graphics part of the example
	struct
	{
		std::unique_ptr<vkb::core::Buffer> uniform_buffer;               // Contains scene matrices
		VkDescriptorSetLayout              descriptor_set_layout;        // Particle system rendering shader binding layout
		VkDescriptorSet                    descriptor_set;               // Particle system rendering shader bindings
		VkPipelineLayout                   pipeline_layout;              // Layout of the graphics pipeline
		VkPipeline                         pipeline;                     // Particle rendering pipeline
		VkSemaphore                        semaphore;                    // Execution dependency between compute & graphic submission
		uint32_t                           queue_family_index;
		struct
		{
			glm::mat4 projection;
			glm::mat4 view;
			glm::vec2 screenDim;
		} ubo;
	} graphics;

	// Resources for the compute part of the example
	struct
	{
		std::unique_ptr<vkb::core::Buffer> storage_buffer;               // (Shader) storage buffer object containing the particles
		std::unique_ptr<vkb::core::Buffer> uniform_buffer;               // Uniform buffer object containing particle system parameters
		VkQueue                            queue;                        // Separate queue for compute commands (queue family may differ from the one used for graphics)
		VkCommandPool                      command_pool;                 // Use a separate command pool (queue family may differ from the one used for graphics)
		VkCommandBuffer                    command_buffer;               // Command buffer storing the dispatch commands and barriers
		VkSemaphore                        semaphore;                    // Execution dependency between compute & graphic submission
		VkDescriptorSetLayout              descriptor_set_layout;        // Compute shader binding layout
		VkDescriptorSet                    descriptor_set;               // Compute shader bindings
		VkPipelineLayout                   pipeline_layout;              // Layout of the compute pipeline
		VkPipeline                         pipeline_calculate;           // Compute pipeline for N-Body velocity calculation (1st pass)
		VkPipeline                         pipeline_integrate;           // Compute pipeline for euler integration (2nd pass)
		VkPipeline                         blur;
		VkPipelineLayout                   pipeline_layout_blur;
		VkDescriptorSetLayout              descriptor_set_layout_blur;
		VkDescriptorSet                    descriptor_set_blur;
		uint32_t                           queue_family_index;
		struct ComputeUBO
		{                              // Compute shader uniform block object
			float   delta_time;        //		Frame delta time
			int32_t particle_count;
		} ubo;
	} compute;

	// SSBO particle declaration
	struct Particle
	{
		glm::vec4 pos;        // xyz = position, w = mass
		glm::vec4 vel;        // xyz = velocity, w = gradient texture position
	};

	Synchronization2();
	~Synchronization2();
	virtual void request_gpu_features(vkb::PhysicalDevice &gpu) override;
	void         load_assets();
	void         build_command_buffers() override;
	void         build_compute_command_buffer();
	void         prepare_storage_buffers();
	void         setup_descriptor_pool();
	void         setup_descriptor_set_layout();
	void         setup_descriptor_set();
	void         prepare_pipelines();
	void         prepare_graphics();
	void         prepare_compute();
	void         prepare_uniform_buffers();
	void         update_compute_uniform_buffers(float delta_time);
	void         update_graphics_uniform_buffers();
	void         draw();
	bool         prepare(vkb::Platform &platform) override;
	virtual void render(float delta_time) override;
	virtual bool resize(const uint32_t width, const uint32_t height) override;
};

std::unique_ptr<vkb::Application> create_synchronization_2();


text: Go scripts for parsing Complete Genomics files