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

        <meta http-equiv="X-UA-Compatible" content="IE=edge">

        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
        <meta name="generator" content="Doxygen 1.8.9.1"/>

        <title>Traffic Assignment frameworK (TAsK): ShortestPath.h Source File</title>

        <link href="search/search.css" rel="stylesheet" type="text/css"/>

        <link href="doxygen.css" rel="stylesheet" type="text/css" />
        <link href="customdoxygen.css" rel="stylesheet" type="text/css"/>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">

                    Traffic Assignment frameworK (TAsK)

Main Page

Related Pages

Namespaces

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

File List

ShortestPath.h

    1 #ifndef SHORTEST_PATH

    2 #define SHORTEST_PATH

    3

    4 #include "StarLink.h"

    5

    6 #include <iostream>

    7

   11 class ShortestPath {

   12

   13     public:

   14         virtual ~ShortestPath(){};

   15

   19         virtual void calculate(int originIndex) =0;

   20

   25         virtual void calculate(int originIndex, int destIndex, int odPairIndex) {

   26             calculate(originIndex);

   27         };

   28

   30         virtual FPType getCost(int destIndex) const =0;

   31

   36         virtual StarLink* getInComeLink(int destIndex) const =0;

   37

   40         void printPath(int destIndex) const {

   41             StarLink *link = getInComeLink(destIndex);

   42             int nextDest = -1;

   43             std::string str;

   44             while (link != NULL) {

   45                 str = link->toString() + " " + str;

   46                 nextDest = link->getNodeFromIndex();

   47                 link = getInComeLink(nextDest);

   48             }

   49             std::cout << str << std::endl;

   50         };

   51

   52     protected:

   53         ShortestPath(){};

   54

   55 };

   56

   57 #endif

StarLink

This class is a basic element of StarNetwork. It represents a link of the graph.

Definition: StarLink.h:8

StarLink::getNodeFromIndex

int getNodeFromIndex() const

Definition: StarLink.cpp:44

ShortestPath::getCost

virtual FPType getCost(int destIndex) const  =0

ShortestPath::printPath

void printPath(int destIndex) const

Definition: ShortestPath.h:40

ShortestPath::getInComeLink

virtual StarLink * getInComeLink(int destIndex) const  =0

ShortestPath

This is an abstract class that defines the interface for single-objective shortest-path algorithms...

Definition: ShortestPath.h:11

StarLink::toString

std::string toString() const

Definition: StarLink.cpp:76

ShortestPath::calculate

virtual void calculate(int originIndex)=0

ShortestPath::calculate

virtual void calculate(int originIndex, int destIndex, int odPairIndex)

Definition: ShortestPath.h:25

<address class="footer">
Generated on Tue Mar 10 2015 15:45:14 for Traffic Assignment frameworK (TAsK) by

 1.8.9.1
</address>


text:
/**
 * Created by rharik on 10/21/14.
 */
'use strict';

var curl = require('curlrequest'),
    uuid = require('node-uuid'),
    is = require('is'),
    contentESMediaType= 'application/vnd.eventstore.events+json',
    acceptESMediaType = 'application/vnd.eventstore.atom+json',
    server = 'http://127.0.0.1:2113/streams/',
    username = 'admin',
    password = 'changeit';

module.exports = makeAuthorizedRequest;

function makeAuthorizedRequest(optsOrStream, cb) {
    var opts = is.string(optsOrStream) ? { stream: optsOrStream } : optsOrStream,
        uri = opts.stream.indexOf('http') === 0 ? opts.stream : server + opts.stream,
        options = {
            url: uri,
            headers: {
                'Accept': acceptESMediaType,
                 'Content-Type': contentESMediaType,
                'Authorization': 'Basic '+ new Buffer(username+':'+password).toString('base64')
                //, 'ES-LongPoll': 10
            },
            method:opts.method
        };

    if(opts.body ) {
        options.data = JSON.stringify([opts.body]);
    }
    curl.request(options, function(err, stdout, meta){
        if(err){
            console.log(err);
            cb(err);
        }else{
//            console.log('%s %s', meta.cmd, meta.args.join(' '));
            cb(stdout);
        }
    });
}

redpajama_set_name: RedPajamaGithub


text:
// This will check if the node version you are running is the required
// Node version, if it isn't it will throw the following error to inform
// you.
if (process.version.slice(1).split(".")[0] < 8) throw new Error("Node 8.0.0 or higher is required. Update Node on your system.");

// Load up the discord.js library
const Discord = require("discord.js");
// We also load the rest of the things we need in this file:
const { promisify } = require("util");
const readdir = promisify(require("fs").readdir);
const Enmap = require("enmap");
const EnmapLevel = require("enmap-level");

class GuideBot extends Discord.Client {
  constructor(options) {
    super(options);

    // Here we load the config.js file that contains our token and our prefix values.
    this.config = require("./config.js");
    // client.config.token contains the bot's token
    // client.config.prefix contains the message prefix

    // Aliases and commands are put in collections where they can be read from,
    // catalogued, listed, etc.
    this.commands = new Enmap();
    this.aliases = new Enmap();

    // Now we integrate the use of Evie's awesome Enhanced Map module, which
    // essentially saves a collection to disk. This is great for per-server configs,
    // and makes things extremely easy for this purpose.
    this.settings = new Enmap({provider: new EnmapLevel({name: "settings"})});
  }

  /*
  PERMISSION LEVEL FUNCTION

  This is a very basic permission system for commands which uses "levels"
  "spaces" are intentionally left black so you can add them if you want.
  NEVER GIVE ANYONE BUT OWNER THE LEVEL 10! By default this can run any
  command including the VERY DANGEROUS `eval` command!

  */
  permlevel(message) {
    let permlvl = 0;

    const permOrder = client.config.permLevels.slice(0).sort((p, c) => p.level < c.level ? 1 : -1);

    while (permOrder.length) {
      const currentLevel = permOrder.shift();
      if (message.guild && currentLevel.guildOnly) continue;
      if (currentLevel.check(message)) {
        permlvl = currentLevel.level;
        break;
      }
    }
    return permlvl;
  }

  /*
  LOGGING FUNCTION

  Logs to console. Future patches may include time+colors
  */
  log(type, msg, title) {
    if (!title) title = "Log";
    console.log(`[${type}] [${title}]${msg}`);
  }

  loadCommand(commandName) {
    try {
      const props = new (require(`./commands/${commandName}`))(client);
      client.log("log", `Loading Command: ${props.help.name}. 👌`);
      if (props.init) {
        props.init(client);
      }
      client.commands.set(props.help.name, props);
      props.conf.aliases.forEach(alias => {
        client.aliases.set(alias, props.help.name);
      });
      return false;
    } catch (e) {
      return `Unable to load command ${commandName}: ${e}`;
    }
  }

  async unloadCommand(commandName) {
    let command;
    if (client.commands.has(commandName)) {
      command = client.commands.get(commandName);
    } else if (client.aliases.has(commandName)) {
      command = client.commands.get(client.aliases.get(commandName));
    }
    if (!command) return `The command \`${commandName}\` doesn"t seem to exist, nor is it an alias. Try again!`;

    if (command.shutdown) {
      await command.shutdown(client);
    }
    delete require.cache[require.resolve(`./commands/${commandName}.js`)];
    return false;
  }
}

// This is your client. Some people call it `bot`, some people call it `self`,
// some might call it `cootchie`. Either way, when you see `client.something`,
// or `bot.something`, this is what we're refering to. Your client.
const client = new GuideBot();
console.log(client.config.permLevels.map(p=>`${p.level} : ${p.name}`));

// Let's start by getting some useful functions that we'll use throughout
// the bot, like logs and elevation features.
require("./modules/functions.js")(client);

// We're doing real fancy node 8 async/await stuff here, and to do that
// we need to wrap stuff in an anonymous function. It's annoying but it works.

const init = async () => {

  // Here we load **commands** into memory, as a collection, so they're accessible
  // here and everywhere else.
  const cmdFiles = await readdir("./commands/");
  client.log("log", `Loading a total of ${cmdFiles.length} commands.`);
  cmdFiles.forEach(f => {
    if (!f.endsWith(".js")) return;
    const response = client.loadCommand(f);
    if (response) console.log(response);
  });

  // Then we load events, which will include our message and ready event.
  const evtFiles = await readdir("./events/");
  client.log("log", `Loading a total of ${evtFiles.length} events.`);
  evtFiles.forEach(file => {
    const eventName = file.split(".")[0];
    const event = new (require(`./events/${file}`))(client);
    // This line is awesome by the way. Just sayin'.
    client.on(eventName, (...args) => event.run(...args));
    delete require.cache[require.resolve(`./events/${file}`)];
  });

  client.levelCache = {};
  for (let i = 0; i < client.config.permLevels.length; i++) {
    const thisLevel = client.config.permLevels[i];
    client.levelCache[thisLevel.name] = thisLevel.level;
  }

  // Here we login the client.
  client.login(client.config.token);

// End top-level async/await function.
};

init();


text:
package kubernetes

type Pods struct {
	Kind       string `json:"kind"`
	APIVersion string `json:"apiVersion"`
	Items      []Item `json:"items"`
}

type Item struct {
	Metadata Metadata `json:"metadata"`
}

type Metadata struct {
	Name      string            `json:"name"`
	Namespace string            `json:"namespace"`
	Labels    map[string]string `json:"labels"`
}


text:
package alien4cloud.component.repository.exception;

/**
 * Exception thrown when trying to override a node type that is defined in an other CSAR
 *
 */
public class ToscaTypeAlreadyDefinedInOtherCSAR extends RepositoryFunctionalException {

    private static final long serialVersionUID = -7825281720911419035L;

    public ToscaTypeAlreadyDefinedInOtherCSAR(String message) {
        super(message);
    }

}


text:
PUB=../../../intellij/dart-sdk/bin/pub

git branch -D gh-pages
git checkout -b gh-pages
$PUB build
git add -A build
git commit -m "Build pages `date`"
git checkout master
echo "Built examples on gh-pages branch"


text:
/*
    This is a simple debounce/throttle function that uses `requestAnimationFrame`
    for timing instead of setTimeout or equivalent, as such it's better suited
    for updates that involve a repaint, which tbh is probably most things
*/

export default fn => {
  let rafID

  /*
      Create a debounced wrapper
  */

  let debounced = (a) => {
    // console.log( performance.now() - t)
    fn(a)
    cancelAnimationFrame(rafID)
    rafID = null
  }

  /*
      Return a function that only executes when rafID has fired
  */

  return e => {
    if (!rafID) {
      if (e && e.persist) e.persist()
      requestAnimationFrame(_ => {
        rafID = requestAnimationFrame(debounced.bind(this, e))
      })
    }
  }
}


text:
%run_training_localModel is the launching script for the training of the local model

% SETUP THESE PATHS TO RUN THE CODE
dataPath = 'data/HollywoodHeads';
resultPath = 'results/HollywoodHeads';
pretrainedNetworkPath = 'models';

%% add all the required paths
filePath = fileparts( mfilename('fullpath') );
run( fullfile( fileparts( filePath ), 'setup.m' ) );

%% set data files
% network initialization
pretrainedNetwork = fullfile( pretrainedNetworkPath, 'imagenet-torch-oquab.mat'); networkInputSize = [224, 224]; initNetworkName = 'oquabTorch'; addDropout = false;
%CAUTION: the MatConvNet pretrained networks do not have dropout layers! be careful when turning this option on!
%pretrainedNetwork = fullfile( pretrainedNetworkPath, 'imagenet-caffe-alex.mat'); networkInputSize = [227, 227]; initNetworkName = 'alexCaffe'; addDropout = true;
%pretrainedNetwork = fullfile( pretrainedNetworkPath, 'imagenet-vgg-s.mat'); networkInputSize = [227, 227]; initNetworkName = 'vggS'; addDropout = true;
%pretrainedNetwork = fullfile( pretrainedNetworkPath, 'imagenet-vgg-verydeep-16.mat'); networkInputSize = [227, 227]; initNetworkName = 'vggVeryDeep16'; addDropout = true;

% get the mean vector on the training set
meanVector = [57, 52, 47];

%% preparation
% parameters
opts_cnn = struct;
opts_cnn.dataPath = dataPath;
opts_cnn.dataset.trainingSetFile = fullfile('Splits', 'train.txt');
opts_cnn.dataset.validationSetFile = fullfile('Splits', 'val.txt');
opts_cnn.dataset.testSetFile = fullfile('Splits', 'test.txt');
opts_cnn.dataset.groundTruthLocalPrefix = 'Annotations';
opts_cnn.dataset.imageLocalPrefix = 'JPEGImages';
opts_cnn.dataset.candidateLocalPrefix = 'Candidates';

opts_cnn.expDir =  resultPath;
opts_cnn.maxGpuImagesEvaluation = 3000;
opts_cnn.scoreMode = 'afterSoftMax'; % 'beforeSoftMax' or 'afterSoftMax' or 'scoreDifference';

opts_cnn.train.numValidationPerEpoch = 8;
opts_cnn.train.numEpochs = 3;
opts_cnn.train.learningRate =  [ 0.001 0.0001 0.00001 ];
opts_cnn.train.batchSize = 1;
opts_cnn.train.backPropDepth = +inf;
opts_cnn.train.weightDecay = 0.0005;

opts_cnn.getBatch.numPatchesPerImage = 64;
opts_cnn.getBatch.maxPositives = 32;
opts_cnn.getBatch.iouPositiveThreshold = 0.6;
opts_cnn.getBatch.iouNegativeThreshold = 0.5;
opts_cnn.getBatch.jitterStd = 1;
opts_cnn.getBatch.cropPad = [18, 18, 18, 18];

opts_cnn.evaluation.iouThreshold = 0.5;
opts_cnn.evaluation.useDifficultImages = false;

opts_cnn.train.expDir = fullfile( opts_cnn.expDir, 'local', 'models');

% get the mean image for normalization
meanImage = single( repmat( reshape( meanVector, [1 1 3] ), networkInputSize ) );

% network initialization
extraLayers = [];
opts_cnn.networkInitialization = @() cnn_initNet_localModel( pretrainedNetwork, 2, meanImage, extraLayers, addDropout );

%% run training
cnn_localModel( opts_cnn );


text:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

    <item>
        <shape>
            <solid android:color="@color/BlueDarkanddev" />
        </shape>
    </item>
    <item
        android:drawable="@drawable/gradient_background"
        android:left="10dp">
    </item>

</layer-list>


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width initial-scale=1" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge">

  <title>blog2</title>
  <meta name="description" content="Personal Projects">
  <meta name="author" content="Chris Holmes">
  <meta name="HandheldFriendly" content="True">
  <meta name="MobileOptimized" content="320">
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

  <meta name="twitter:card" content="summary">
  <meta name="twitter:title" content="Chris Holmes">
  <meta name="twitter:description" content="Personal Projects">

  <meta property="og:type" content="article">
  <meta property="og:title" content="Chris Holmes">
  <meta property="og:description" content="Personal Projects">

  <link rel="apple-touch-icon" sizes="57x57" href="/christopherholmes.github.io/images/favicons/apple-touch-icon-57x57.png">
  <link rel="apple-touch-icon" sizes="60x60" href="/christopherholmes.github.io/images/favicons/apple-touch-icon-60x60.png">
  <link rel="apple-touch-icon" sizes="72x72" href="/christopherholmes.github.io/images/favicons/apple-touch-icon-72x72.png">
  <link rel="apple-touch-icon" sizes="76x76" href="/christopherholmes.github.io/images/favicons/apple-touch-icon-76x76.png">
  <link rel="apple-touch-icon" sizes="114x114" href="/christopherholmes.github.io/images/favicons/apple-touch-icon-114x114.png">
  <link rel="apple-touch-icon" sizes="120x120" href="/christopherholmes.github.io/images/favicons/apple-touch-icon-120x120.png">
  <link rel="apple-touch-icon" sizes="144x144" href="/christopherholmes.github.io/images/favicons/apple-touch-icon-144x144.png">
  <link rel="apple-touch-icon" sizes="152x152" href="/christopherholmes.github.io/images/favicons/apple-touch-icon-152x152.png">
  <link rel="apple-touch-icon" sizes="180x180" href="/christopherholmes.github.io/images/favicons/apple-touch-icon-180x180.png">
  <link rel="icon" type="image/png" href="/christopherholmes.github.io/images/favicons/favicon-32x32.png" sizes="32x32">
  <link rel="icon" type="image/png" href="/christopherholmes.github.io/images/favicons/favicon-194x194.png" sizes="194x194">
  <link rel="icon" type="image/png" href="/christopherholmes.github.io/images/favicons/favicon-96x96.png" sizes="96x96">
  <link rel="icon" type="image/png" href="/christopherholmes.github.io/images/favicons/android-chrome-192x192.png" sizes="192x192">
  <link rel="icon" type="image/png" href="/christopherholmes.github.io/images/favicons/favicon-16x16.png" sizes="16x16">
  <link rel="manifest" href="/christopherholmes.github.io/images/favicons/manifest.json">
  <link rel="shortcut icon" href="/christopherholmes.github.io/images/favicons/favicon.ico">
  <meta name="msapplication-TileColor" content="#ffc40d">
  <meta name="msapplication-TileImage" content="/christopherholmes.github.io/images/favicons/mstile-144x144.png">
  <meta name="theme-color" content="#ffffff">

  <link rel="stylesheet" href="/christopherholmes.github.io/css/main.css">
  <link rel="canonical" href="http://christopherholmes.github.io/christopherholmes.github.io//blog2/">
  <link rel="alternate" type="application/rss+xml" title="Chris Holmes" href="/christopherholmes.github.io/feed.xml">

Chris Holmes

Personal Projects

Blog

Project_365

                  GitHub

                  Email

                RSS

Project 365 Day 7

#Project 365
#    7/365

…

<time datetime="7 Jan 2017" class="post-list__meta--date date">7 Jan 2017</time> • on featured

Project 365 Day 6

#Project 365
#    6/365

…

<time datetime="6 Jan 2017" class="post-list__meta--date date">6 Jan 2017</time> • on featured

Project 365 Day 5

#Project 365
#    5/365

…

<time datetime="5 Jan 2017" class="post-list__meta--date date">5 Jan 2017</time> • on featured

Project 365 Day 4

#Project 365
#    4/365

…

<time datetime="4 Jan 2017" class="post-list__meta--date date">4 Jan 2017</time> • on featured

Project 365 Day 3

#Project 365
#    3/365

…

<time datetime="3 Jan 2017" class="post-list__meta--date date">3 Jan 2017</time> • on featured

Project 365 Day 2

#Project 365
#    2/365

…

<time datetime="2 Jan 2017" class="post-list__meta--date date">2 Jan 2017</time> • on featured

Project 365 Day 1

#Project 365
#    1/365

…

<time datetime="1 Jan 2017" class="post-list__meta--date date">1 Jan 2017</time> • on featured

  © 2017 Chris Holmes. All rights reserved.


text:
package com.badlogic.sol.command;

import com.badlogic.sol.Command;
import com.badlogic.sol.Entity;
import com.badlogic.sol.Game;

public class SetZ implements Command {
	String name;
	int z;

	public SetZ(String name, int z) {
		this.name = name;
		this.z = z;
	}

	@Override
	public void update (float delta) {
		Game.ctx.getEntity(name, Entity.class).z = z;
	}

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

	@Override
	public Command copy () {
		return this;
	}
}


text:
namespace rocksdb {

class SanityTest {
 public:
  explicit SanityTest(const std::string& path)
      : env_(Env::Default()), path_(path) {
    env_->CreateDirIfMissing(path);
  }
  virtual ~SanityTest() {}

  virtual std::string Name() const = 0;
  virtual Options GetOptions() const = 0;

  Status Create() {
    Options options = GetOptions();
    options.create_if_missing = true;
    std::string dbname = path_ + Name();
    DestroyDB(dbname, options);
    DB* db;
    Status s = DB::Open(options, dbname, &db);
    std::unique_ptr<DB> db_guard(db);
    if (!s.ok()) {
      return s;
    }
    for (int i = 0; i < 1000000; ++i) {
      std::string k = "key" + std::to_string(i);
      std::string v = "value" + std::to_string(i);
      s = db->Put(WriteOptions(), Slice(k), Slice(v));
      if (!s.ok()) {
        return s;
      }
    }
    return Status::OK();
  }
  Status Verify() {
    DB* db;
    std::string dbname = path_ + Name();
    Status s = DB::Open(GetOptions(), dbname, &db);
    std::unique_ptr<DB> db_guard(db);
    if (!s.ok()) {
      return s;
    }
    for (int i = 0; i < 1000000; ++i) {
      std::string k = "key" + std::to_string(i);
      std::string v = "value" + std::to_string(i);
      std::string result;
      s = db->Get(ReadOptions(), Slice(k), &result);
      if (!s.ok()) {
        return s;
      }
      if (result != v) {
        return Status::Corruption("Unexpected value for key " + k);
      }
    }
    return Status::OK();
  }

 private:
  Env* env_;
  std::string const path_;
};

class SanityTestBasic : public SanityTest {
 public:
  explicit SanityTestBasic(const std::string& path) : SanityTest(path) {}
  virtual Options GetOptions() const {
    Options options;
    options.create_if_missing = true;
    return options;
  }
  virtual std::string Name() const { return "Basic"; }
};

class SanityTestSpecialComparator : public SanityTest {
 public:
  explicit SanityTestSpecialComparator(const std::string& path)
      : SanityTest(path) {
    options_.comparator = new NewComparator();
  }
  ~SanityTestSpecialComparator() { delete options_.comparator; }
  virtual Options GetOptions() const { return options_; }
  virtual std::string Name() const { return "SpecialComparator"; }

 private:
  class NewComparator : public Comparator {
   public:
    virtual const char* Name() const { return "rocksdb.NewComparator"; }
    virtual int Compare(const Slice& a, const Slice& b) const {
      return BytewiseComparator()->Compare(a, b);
    }
    virtual void FindShortestSeparator(std::string* s, const Slice& l) const {
      BytewiseComparator()->FindShortestSeparator(s, l);
    }
    virtual void FindShortSuccessor(std::string* key) const {
      BytewiseComparator()->FindShortSuccessor(key);
    }
  };
  Options options_;
};

class SanityTestZlibCompression : public SanityTest {
 public:
  explicit SanityTestZlibCompression(const std::string& path)
      : SanityTest(path) {
    options_.compression = kZlibCompression;
  }
  virtual Options GetOptions() const { return options_; }
  virtual std::string Name() const { return "ZlibCompression"; }

 private:
  Options options_;
};

class SanityTestPlainTableFactory : public SanityTest {
 public:
  explicit SanityTestPlainTableFactory(const std::string& path)
      : SanityTest(path) {
    options_.table_factory.reset(NewPlainTableFactory());
    options_.prefix_extractor.reset(NewFixedPrefixTransform(2));
    options_.allow_mmap_reads = true;
  }
  ~SanityTestPlainTableFactory() {}
  virtual Options GetOptions() const { return options_; }
  virtual std::string Name() const { return "PlainTable"; }

 private:
  Options options_;
};

namespace {
bool RunSanityTests(const std::string& command, const std::string& path) {
  std::vector<SanityTest*> sanity_tests = {
      new SanityTestBasic(path),
      new SanityTestSpecialComparator(path),
      new SanityTestZlibCompression(path),
      new SanityTestPlainTableFactory(path)};

  if (command == "create") {
    fprintf(stderr, "Creating...\n");
  } else {
    fprintf(stderr, "Verifying...\n");
  }
  for (auto sanity_test : sanity_tests) {
    Status s;
    fprintf(stderr, "%s -- ", sanity_test->Name().c_str());
    if (command == "create") {
      s = sanity_test->Create();
    } else {
      assert(command == "verify");
      s = sanity_test->Verify();
    }
    fprintf(stderr, "%s\n", s.ToString().c_str());
    if (!s.ok()) {
      fprintf(stderr, "FAIL\n");
      return false;
    }

    delete sanity_test;
  }
  return true;
}
}  // namespace

}  // namespace rocksdb

int main(int argc, char** argv) {
  std::string path, command;
  bool ok = (argc == 3);
  if (ok) {
    path = std::string(argv[1]);
    command = std::string(argv[2]);
    ok = (command == "create" || command == "verify");
  }
  if (!ok) {
    fprintf(stderr, "Usage: %s <path> [create|verify] \n", argv[0]);
    exit(1);
  }
  if (path.back() != '/') {
    path += "/";
  }

  bool sanity_ok = rocksdb::RunSanityTests(command, path);

  return sanity_ok ? 0 : 1;
}


text:
GAUDI_MULTIPLEXER_SHOW="${GAUDI_MULTIPLEXER_SHOW=true}"
GAUDI_MULTIPLEXER_PREFIX="${GAUDI_MULTIPLEXER_PREFIX="$GAUDI_PROMPT_DEFAULT_PREFIX"}"
GAUDI_MULTIPLEXER_SUFFIX="${GAUDI_MULTIPLEXER_SUFFIX="$GAUDI_PROMPT_DEFAULT_SUFFIX"}"
GAUDI_MULTIPLEXER_SYMBOL="\\uf878"
GAUDI_MULTIPLEXER_COLOR="${GAUDI_MULTIPLEXER_COLOR=""}"

# ------------------------------------------------------------------------------
# Section
# ------------------------------------------------------------------------------

# Show current Maven version
gaudi_multiplexer() {
  [[ $GAUDI_MULTIPLEXER_SHOW == false ]] && return

  # Check if tmux or scren are installed
  ! gaudi::exists tmux && ! gaudi::exists screen && return

  local multiplexers

  detached_tmux_sessions=$(tmux list-sessions 2> /dev/null | \grep -cv 'attached')
  detached_screen_sessions=$(screen -ls 2> /dev/null | \grep -c '[Dd]etach[^)]*)$')

  [[ $detached_tmux_sessions == 0 ]] && [[ $detached_screen_sessions == 0 ]] && return

  [[ $detached_tmux_sessions != 0 ]] && multiplexers=" T:$detached_tmux_sessions"
  [[ $detached_screen_sessions != 0 ]] && multiplexers="$multiplexers S:$detached_screen_sessions"

  gaudi::section \
    "$GAUDI_MULTIPLEXER_COLOR" \
    "$GAUDI_MULTIPLEXER_PREFIX" \
    "$GAUDI_MULTIPLEXER_SYMBOL" \
    "$multiplexers" \
    "$GAUDI_MULTIPLEXER_SUFFIX"
}


text:
#include <modules/globebrowsing/src/tileloadjob.h>

#include <modules/globebrowsing/src/rawtiledatareader.h>

namespace openspace::globebrowsing {

TileLoadJob::TileLoadJob(RawTileDataReader& rawTileDataReader, TileIndex tileIndex)
    : _rawTileDataReader(rawTileDataReader)
    , _chunkIndex(std::move(tileIndex))
{}

TileLoadJob::~TileLoadJob() {
    if (_hasTile) {
        _rawTile.imageData = nullptr;
    }
}

void TileLoadJob::execute() {
    _rawTile = _rawTileDataReader.readTileData(_chunkIndex);
    _hasTile = true;
}

RawTile TileLoadJob::product() {
    _hasTile = false;
    return std::move(_rawTile);
}

} // namespace openspace::globebrowsing


text: .extern gdt 32


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE reference PUBLIC "-//IXIA//DTD IXIA DITA Composite//EN" "../../system/dtd/ixia/IxiaDitabase.dtd">
<reference id="blackberry_ui_contextmenu_CONTEXT_ALL" xml:lang="en-us">
    <title><apiname>CONTEXT_ALL</apiname></title>
    <shortdesc>Constant denoting all contexts.</shortdesc>
    <refbody>

            <title>Synopsis:</title>

constant {String}

CONTEXT_ALL: "CONTEXT_ALL"

    </refbody>
</reference>


text:
.. _`Integrity`:

#########
Integrity
#########

*This chapter provides a brief description of how to deploy Vortex OpenSplice
on Integrity.*

***********************
Integrity and GHS Multi
***********************

The ``ospl_projgen`` tool is in the ``HDE/bin`` directory of the DDS
distribution. It is a convenience tool provided for the Integrity
platform in order to aid in the creation of GHS Multi projects for
running the DDS-supplied PingPong example, the Touchstone performance
suite, and the Chatter Tutorial. If desired, these generated projects
can be adapted to suit user requirements by using Multi and the
``ospl_xml2int`` tool, which is also described in this chapter.

************************
The ospl_projgen Command
************************

**Usage**

.. code-block:: bash

  ospl_projgen -h

  ospl_projgen [-s <flash\|ram>\|-d] [-n] [-v] [-t <target>]
               [-l <c\|c++>\|c++onc] [-u <URI>] -b <bsp name>
               [-m <board model>] -o <directory> [-f]

Arguments shown between square brackets *[ ]* are optional; other
arguments are mandatory. Arguments may be supplied in any order. All of
the arguments are described in detail below.

**Arguments**

``-h``
  List the command line arguments and give brief reminders of their
  functions.

``-s <flash | ram>``
  Use this argument if you wish to generate a project
  that will be statically linked with the kernel. The two options for this
  argument determine whether the resulting kernel image will be a
  flashable image or a loadable image. If both this argument and the ``-d``
  argument are omitted the default of a statically-linked ram-loadable
  image will be generated.

``-d``
  Use this argument to produce a project file that will yield a
  dynamic download image.

|caution|
  Arguments ``-s`` and ``-d`` are mutually exclusive.

``-n``
  Use this argument if you want to include the GHS network stack in
  your project.

``-v``
  Use this argument if you want to include filesystem support in
  your project.

``-t <target>``
  Use this argument to specify which address spaces to
  include in your project. Use ``-t list`` to show a list of available
  targets. (Targets available initially are examples supplied with
  Vortex OpenSplice and Integrity itself.)

``-l <c | c++ | c++onc>``
  Use this argument to specify the language for
  your project. The default is ``c++``.

``-u <URI>``
  Use this argument to identify which configuration file to
  use. You can omit this argument if you have the environment variable
  ``OSPL_URI`` set, or use it if you want to use a different configuration
  file from the one referred to by ``OSPL_URI``. The default is
  ``$OSPL_URI``. The ``xml2int`` tool uses this configuration file when
  generating the Integrate file for your project.

``-b <bsp name>``
  Use this argument to specify the BSP name of your
  target board. Use ``-b list`` to show a list of supported target boards.

``-m <board model>``
  Use this argument to specify the model number for
  the target board. Use ``-b <bsp name> -m list`` to show a list of
  supported model numbers. (There are no separate model numbers for
  *pcx86* boards.)

``-o <directory>``
  Use this argument to specify the output directory for
  the project files. The name you supply here will also be used as the
  name for the image file that will be downloaded/flashed onto the
  Integrity board.

``-f``
  Use this argument to force overwrite of the output directory.

When you run the tool, the output directory specified with the ``-o``
argument will be created. Go into this directory, run GHS Multi, and
load the generated project.

If the output directory already exists and the *-f* argument has been
omitted, *ospl_projgen* will exit without generating any code and will
notify you that it has stopped.

|caution|
  *NOTE:* The *NetworkInterfaceAddress* configuration parameter is
  **required** for Integrity nodes which have more than one ethernet
  interface, as it is not possible to determine which are
  broadcast/multicast enabled. (See sections *3.5.2.1* and *3.9.2.1*
  *Element NetworkInterfaceAddress* in the *Vortex Deployment Guide*.)

Using mmstat and shmdump diagnostic tools on Integrity
======================================================

When ``mmstat`` or ``shmdump`` targets are specified to ``ospl_projgen`` an
address space will be added to the generated project. There will also be
an appropriate ``mmstat.c`` or ``shmdump.c`` file generated into the
project. In order to configure these, the command line arguments can be
edited in the generated ``.c`` files. The ``mmstat`` tool can be controlled
*via* telnet on port ``2323`` (by default).

****************
PingPong Example
****************

.. note: xref to install-configure.rst

(Please refer to the :ref:`Examples` section for a description of this example
application.)

|cpp|

To generate a project for the C++ PingPong example, follow these steps:

**Step 1**

The ``I_INSTALL_DIR`` environment variable must be set to point to the
Integrity installation directory on the host machine before running
``ospl_projgen``. For example:

.. code-block:: bash

  export I_INSTALL_DIR=/usr/ghs/int509

**Step 2**

Navigate to the ``examples/dcps/standalone/C++/PingPong`` directory

**Step 3**

Run ``ospl_projgen`` with the following arguments:

.. code-block:: bash

  ospl_projgen -s ram -v -n -t pingpong -l c++ -b pcx86 -o projgen

**Step 4**

Go into the ``projgen`` directory, which contains ``default.gpj`` and a
``src`` directory. (``default.gpj`` is the default Multi project that will
build all the sub-projects found in the ``src`` directory, and the ``src``
directory contains all the sub-projects and generated files produced by
the tool.)

**Step 5**

Start Multi:

.. code-block:: bash

  multi default.gpj

You should see a screen similar to the screenshot
`Integrity: project defaults`_ below:

.. _`Integrity: project defaults`:

.. figure:: /images/Integrity-projectDefaults.png
   :height: 70mm
   :alt: Integrity: project defaults

   **Integrity: project defaults**

If no changes are required to the project, right-click on ``default.gpj``
and then click *Build* to build the project.

Upon successful completion of the build process, an image is generated
(in our case called ``projgen``) in the ``src`` directory and you are now
ready to either dynamically download the resulting image to the board or
to load the kernel image onto the board (depending on the arguments you
have specified) and run the PingPong example.

If ``ospl_projgen`` is run and the project built as described above, the
generated image will contain:

+ GHS Integrity OS (Kernel, Networking, and Filesystem support)
+ Vortex OpenSplice (including ``spliced`` and the services described in the
  ``ospl.xml`` file)
+ The PingPong example

Once the image has been downloaded to the board, the ``pong`` "Initial
task" should be started and then the ``ping`` AddressSpace can be started
in the same way, so that the example begins the data transfer.
Parameters are not required to be passed to the Integrity processes
because the ``ospl_projgen`` tool generates code with particular values
that simulate the passing of parameters.

|info|
  This also applies to the Chat Tutorial (see :ref:`Examples`), if
  ``ospl_projgen`` is run with the ``-t chat`` argument.

.. note: xref to install-configure.rst above

***********************************
Changing the ospl_projgen Arguments
***********************************

If changes are subsequently required to the arguments that were
originally specified to the ``ospl_projgen`` tool, there are two choices:

a) Re-run the tool and amend the arguments accordingly

*or*

b) Make your changes through the Multi tool.

The first method guarantees that your project files will be produced
correctly and build without needing manual changes to the project files.
To use this method, simply follow the procedure described above but
supply different arguments.

The second method is perhaps a more flexible approach, but as well as
making some changes using Multi you will have to make other changes by
hand in order for the project to build correctly.

The following section describes the second method.

Changing the generated Vortex OpenSplice project using *Multi*
===========================================================

You can make changes to any of the settings you specified with
``ospl_projgen`` by following these steps:

**Step 1**

Right-click on the highlighted ``ospl.xml`` file (as shown above) and
click *Set Options...*.

**Step 2**

Select the *All Options* tab and expand the *Advanced* section.

**Step 3**

Select *Advanced Vortex OpenSplice XML To Int Convertor Options*. In the
right-hand pane you will see the options that you have set with the
``ospl_projgen`` tool with their values, similar to
`Integrity: changing project options in Multi`_ below.

.. _`Integrity: changing project options in Multi`:

.. figure:: /images/Integrity-projectOptionsMulti.png
   :height: 70mm
   :alt: Integrity: changing project options in Multi

   **Integrity: changing project options in Multi**

Right-click on the parameter that you want to change. For example, if
you don't need filesystem support to be included in the kernel image,
right-click on *Include filesystem support* and set the option to ``Off``.

The arguments for ``xml2int`` in the bottom pane are updated to reflect
any changes that you make. If you switch off filesystem support, the
``-v`` argument is removed from the arguments. (The ``xml2int`` tool is used
to generate the ``ospl.int`` Integrate file that will be used during the
Integrate phase of the project. For more information on ``xml2int``
please see section `The ospl_xml2int command`_.)

|caution|
  Note that if you do remove filesystem support from the kernel image you
  should also remove all references to the ``ivfs`` library, and make
  appropriate changes to the ``ospl_log.c`` file as well. See section
  `Amending Vortex OpenSplice Configuration with Multi`_ for information
  about ``ospl_log.c``.

Similarly you can change any other option and the changes are applied
instantly.

When the changes are complete, rebuild the project by right-clicking on
*default.gpj* and then click *Build* to build the project.

The ospl_xml2int Tool
=====================

The ``ospl_xml2int`` tool is used to inspect your Vortex OpenSplice
configuration file (``ospl.xml``) and generate an appropriate Integrate
file (``ospl.int``). For more information on Integrate files please
consult the Integrity manual.

The ospl_xml2int command
========================

**Usage**

.. code-block:: bash

  ospl_xml2int -h

  ospl_xml2int [-s|-d] [-v] [-n] [-t <target>] [-u <URI>]
               [-o <file>]

Arguments shown between square brackets *[ ]* are optional; other
arguments are mandatory. Arguments may be supplied in any order. All of
the arguments are described in detail below.

**Arguments**

``-h``
  List the command line arguments and give brief reminders of their
  functions.

``-s``
  Generate for static linkage with kernel.

``-d``
  Use this argument to generate an Integrate file that will yield
  a dynamic download image. If both this argument and the ``-s`` argument are
  omitted the default of a statically-linked image will be generated.

|caution|
  The arguments ``-s`` and ``-d`` are mutually exclusive.

``-v``
  Include filesystem support.

``-n``
  Include network support.

``-t <target>``
  Available targets:
     | ``chat`` include chat tutorial
     | ``pingpong`` include PingPong example
     | ``touchstone`` include Touchstone
     | ``mmstat`` include mmstat
     | ``shmdump`` include shmdump

  Multiple ``-t`` arguments may be given. This enables you to use
  ``mmstat`` and/or ``shmdump`` (see
  `Using mmstat and shmdump diagnostic tools on Integrity`_)
  in conjunction with one of the examples.

``-u <URI>``
  Identifies the configuration file to use (default:
  ``${OSPL_URI}``).

``-o <file>``
  Name of the generated Integrate file.

Applications linking with Vortex OpenSplice must comply with the following
requirements:

+ The ``First`` and ``Length`` parameters must match those of ``spliced``
  address space (these are generated from ``ospl.xml``).

+ The address space entry for your application in the Integrate file must
  include entries as shown in the example below.

Have a look at the ``ospl.int`` for the PingPong example if in doubt as to
what the format should be. (Make sure that you have built the project
first or else the file will be empty.)

Example ``ospl.int`` contents:

.. code-block:: bash

  AddressSpace
    .
    .
    .
    Object 10
           Link                  ResourceStore
           Name                  ResCon
           OtherObjectName       DDS_Connection
    EndObject

    Object 11
           Link                  ResourceStore
           Name                  ConnectionLockLink
           OtherObjectName       DDS_ConnectionLock
    EndObject

    Object 12
           MemoryRegion          your_app_name_database
           MapTo                 splice_database
           First 0x20000000
           Length 33554432
           Execute true
           Read true
           Write true
    EndObject
    .
    .
    .
  EndAddressSpace

..

|caution|
  *Note:* If you make any changes to the ``ospl.int`` file generated by the
  project and then you make any changes to the ``ospl.xml`` file and rebuild
  the project, the changes to the ``ospl.int`` file will be overwritten.

Make sure that you also edit the ``global_table.c`` and ``mounttable.c``
files to match your setup. These files can be found under
``src/projgen/kernel.gpj/kernel_kernel.gpj`` and
``src/projgen.gpj/kernel.gpj/ivfs_server.gpj`` as shown in
`Integrity: changing global_table.c and mounttable.c`_ below:

.. _`Integrity: changing global_table.c and mounttable.c`:

.. figure:: /images/Integrity-changeMounttable.png
   :height: 70mm
   :alt: Integrity: changing global_table.c and mounttable.c

   **Integrity: changing global_table.c and mounttable.c**

Once you have made all of the required changes to ``ospl.int``, you must
rebuild the whole project. Your changes will be picked up by Vortex OpenSplice
automatically.

**************************************************
Critical Warning about *Object 10* and *Object 11*
**************************************************

|caution|  |caution|
  We have used ``Object 10`` and ``Object 11`` in various address spaces to
  declare a semaphore and a connection object, but they may already be in
  use on your system.

  You *can* change these numbers in the ``ospl.int`` file, but if you do then
  you **must** change **all** of the address spaces where ``Object 10`` and
  ``Object 11`` are defined (except those for ``ResourceStore`` as noted
  below). The value replacing ``10`` must be the same for every address
  space, and likewise for the value replacing ``11``. You **must** change
  **all** references in order for Vortex OpenSplice to work correctly.

  *The only exception is the* ``ResourceStore`` *address space.*
  ``Object 10`` *and* ``Object 11`` *are unique to the Vortex OpenSplice*
  *ResourceStore and they* **MUST NOT** *be altered.*
  *If you do change them, Vortex OpenSplice*  **WILL NOT WORK!**
|caution| |caution|

*****************************************************
Amending Vortex OpenSplice Configuration with *Multi*
*****************************************************

You can make changes to the Vortex OpenSplice configuration from Multi by
editing the files under the project
``src/projgen.gpj/opensplice_configuration.gpj/libospl_cfg.gpj``. See
`Integrity: changing Vortex OpenSplice configuration in Multi`_ below:

.. _`Integrity: changing Vortex OpenSplice configuration in Multi`:

.. figure:: /images/Integrity-DDSconfigMulti.png
   :height: 70mm
   :alt: Integrity: changing Vortex OpenSplice configuration in Multi

   **Integrity: changing Vortex OpenSplice configuration in Multi**

|caution|
  There are five files here but you may *only* change ``ospl.xml`` and
  ``ospl_log.c``. The others must **NOT** be altered!

``ospl.xml``
  This is your Vortex OpenSplice configuration file. (See
  :ref:`Configuration` for more information about the options an Vortex OpenSplice
  configuration file may have.)

``ospl_log.c``
  This file determines where the log entries (errors,
  warnings and informational messages) from Vortex OpenSplice go. The way the
  default file is generated by ``ospl_projgen`` depends on whether you have
  specified filesystem support or not. (See comments within the file for
  more information.)

.. |caution| image:: ./images/icon-caution.*
            :height: 6mm
.. |info|   image:: ./images/icon-info.*
            :height: 6mm
.. |windows| image:: ./images/icon-windows.*
            :height: 6mm
.. |unix| image:: ./images/icon-unix.*
            :height: 6mm
.. |linux| image:: ./images/icon-linux.*
            :height: 6mm
.. |c| image:: ./images/icon-c.*
            :height: 6mm
.. |cpp| image:: ./images/icon-cpp.*
            :height: 6mm
.. |csharp| image:: ./images/icon-csharp.*
            :height: 6mm
.. |java| image:: ./images/icon-java.*
            :height: 6mm


text:
using System;
using Fluid;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using OrchardCore.Admin;
using OrchardCore.ContentFields.Controllers;
using OrchardCore.ContentFields.Drivers;
using OrchardCore.ContentFields.Fields;
using OrchardCore.ContentFields.Indexing;
using OrchardCore.ContentFields.Indexing.SQL;
using OrchardCore.ContentFields.Services;
using OrchardCore.ContentFields.Settings;
using OrchardCore.ContentFields.ViewModels;
using OrchardCore.ContentManagement;
using OrchardCore.ContentManagement.Display.ContentDisplay;
using OrchardCore.ContentTypes.Editors;
using OrchardCore.Data;
using OrchardCore.Data.Migration;
using OrchardCore.Indexing;
using OrchardCore.Modules;
using OrchardCore.Mvc.Core.Utilities;

namespace OrchardCore.ContentFields
{
    public class Startup : StartupBase
    {
        private readonly AdminOptions _adminOptions;
        static Startup()
        {
            // Registering both field types and shape types are necessary as they can
            // be accessed from inner properties.

            TemplateContext.GlobalMemberAccessStrategy.Register<BooleanField>();
            TemplateContext.GlobalMemberAccessStrategy.Register<DisplayBooleanFieldViewModel>();
            TemplateContext.GlobalMemberAccessStrategy.Register<HtmlField>();
            TemplateContext.GlobalMemberAccessStrategy.Register<DisplayHtmlFieldViewModel>();
            TemplateContext.GlobalMemberAccessStrategy.Register<LinkField>();
            TemplateContext.GlobalMemberAccessStrategy.Register<DisplayLinkFieldViewModel>();
            TemplateContext.GlobalMemberAccessStrategy.Register<NumericField>();
            TemplateContext.GlobalMemberAccessStrategy.Register<DisplayNumericFieldViewModel>();
            TemplateContext.GlobalMemberAccessStrategy.Register<TextField>();
            TemplateContext.GlobalMemberAccessStrategy.Register<DisplayTextFieldViewModel>();
            TemplateContext.GlobalMemberAccessStrategy.Register<DateTimeField>();
            TemplateContext.GlobalMemberAccessStrategy.Register<DisplayDateTimeFieldViewModel>();
            TemplateContext.GlobalMemberAccessStrategy.Register<DateField>();
            TemplateContext.GlobalMemberAccessStrategy.Register<DisplayDateFieldViewModel>();
            TemplateContext.GlobalMemberAccessStrategy.Register<TimeField>();
            TemplateContext.GlobalMemberAccessStrategy.Register<DisplayTimeFieldViewModel>();
        }

        public Startup(IOptions<AdminOptions> adminOptions)
        {
            _adminOptions = adminOptions.Value;
        }

        public override void ConfigureServices(IServiceCollection services)
        {
            // Boolean Field
            services.AddContentField<BooleanField>()
                .UseDisplayDriver<BooleanFieldDisplayDriver>();
            services.AddScoped<IContentPartFieldDefinitionDisplayDriver, BooleanFieldSettingsDriver>();
            services.AddScoped<IContentFieldIndexHandler, BooleanFieldIndexHandler>();

            // Text Field
            services.AddContentField<TextField>()
                .UseDisplayDriver<TextFieldDisplayDriver>();
            services.AddScoped<IContentPartFieldDefinitionDisplayDriver, TextFieldSettingsDriver>();
            services.AddScoped<IContentFieldIndexHandler, TextFieldIndexHandler>();
            services.AddScoped<IContentPartFieldDefinitionDisplayDriver, TextFieldPredefinedListEditorSettingsDriver>();
            services.AddScoped<IContentPartFieldDefinitionDisplayDriver, TextFieldHeaderDisplaySettingsDriver>();

            // Html Field
            services.AddContentField<HtmlField>()
                .UseDisplayDriver<HtmlFieldDisplayDriver>();
            services.AddScoped<IContentPartFieldDefinitionDisplayDriver, HtmlFieldSettingsDriver>();
            services.AddScoped<IContentPartFieldDefinitionDisplayDriver, HtmlFieldTrumbowygEditorSettingsDriver>();
            services.AddScoped<IContentFieldIndexHandler, HtmlFieldIndexHandler>();

            // Link Field
            services.AddContentField<LinkField>()
                .UseDisplayDriver<LinkFieldDisplayDriver>();
            services.AddScoped<IContentPartFieldDefinitionDisplayDriver, LinkFieldSettingsDriver>();
            services.AddScoped<IContentFieldIndexHandler, LinkFieldIndexHandler>();

            // Numeric Field
            services.AddContentField<NumericField>()
                .UseDisplayDriver<NumericFieldDisplayDriver>();
            services.AddScoped<IContentPartFieldDefinitionDisplayDriver, NumericFieldSettingsDriver>();
            services.AddScoped<IContentFieldIndexHandler, NumericFieldIndexHandler>();

            // DateTime Field
            services.AddContentField<DateTimeField>()
                .UseDisplayDriver<DateTimeFieldDisplayDriver>();
            services.AddScoped<IContentPartFieldDefinitionDisplayDriver, DateTimeFieldSettingsDriver>();
            services.AddScoped<IContentFieldIndexHandler, DateTimeFieldIndexHandler>();

            // Date Field
            services.AddContentField<DateField>()
                .UseDisplayDriver<DateFieldDisplayDriver>();
            services.AddScoped<IContentPartFieldDefinitionDisplayDriver, DateFieldSettingsDriver>();
            services.AddScoped<IContentFieldIndexHandler, DateFieldIndexHandler>();

            // Time Field
            services.AddContentField<TimeField>()
                .UseDisplayDriver<TimeFieldDisplayDriver>();
            services.AddScoped<IContentPartFieldDefinitionDisplayDriver, TimeFieldSettingsDriver>();
            services.AddScoped<IContentFieldIndexHandler, TimeFieldIndexHandler>();

            // Video field
            services.AddContentField<YoutubeField>()
                .UseDisplayDriver<YoutubeFieldDisplayDriver>();
            services.AddScoped<IContentPartFieldDefinitionDisplayDriver, YoutubeFieldSettingsDriver>();
            services.AddScoped<IContentFieldIndexHandler, YoutubeFieldIndexHandler>();

            // Content picker field
            services.AddContentField<ContentPickerField>()
                .UseDisplayDriver<ContentPickerFieldDisplayDriver>();
            services.AddScoped<IContentPartFieldDefinitionDisplayDriver, ContentPickerFieldSettingsDriver>();
            services.AddScoped<IContentFieldIndexHandler, ContentPickerFieldIndexHandler>();
            services.AddScoped<IContentPickerResultProvider, DefaultContentPickerResultProvider>();

            // Migration, can be removed in a future release.
            services.AddScoped<IDataMigration, Migrations>();
        }

        public override void Configure(IApplicationBuilder builder, IEndpointRouteBuilder routes, IServiceProvider serviceProvider)
        {
            routes.MapAreaControllerRoute(
                name: "ContentPicker",
                areaName: "OrchardCore.ContentFields",
                pattern: _adminOptions.AdminUrlPrefix + "/ContentFields/SearchContentItems",
                defaults: new { controller = typeof(ContentPickerAdminController).ControllerName(), action = nameof(ContentPickerAdminController.SearchContentItems) }
            );
        }
    }

    [RequireFeatures("OrchardCore.ContentLocalization")]
    public class LocalizationSetContentPickerStartup : StartupBase
    {
        private readonly AdminOptions _adminOptions;

        public LocalizationSetContentPickerStartup(IOptions<AdminOptions> adminOptions)
        {
            _adminOptions = adminOptions.Value;
        }

        public override void ConfigureServices(IServiceCollection services)
        {
            services.AddContentField<LocalizationSetContentPickerField>()
                .UseDisplayDriver<LocalizationSetContentPickerFieldDisplayDriver>();
            services.AddScoped<IContentPartFieldDefinitionDisplayDriver, LocalizationSetContentPickerFieldSettingsDriver>();
            services.AddScoped<IContentFieldIndexHandler, LocalizationSetContentPickerFieldIndexHandler>();
        }

        public override void Configure(IApplicationBuilder builder, IEndpointRouteBuilder routes, IServiceProvider serviceProvider)
        {
            routes.MapAreaControllerRoute(
                name: "SearchLocalizationSets",
                areaName: "OrchardCore.ContentFields",
                pattern: _adminOptions.AdminUrlPrefix + "/ContentFields/SearchLocalizationSets",
                defaults: new { controller = typeof(LocalizationSetContentPickerAdminController).ControllerName(), action = nameof(LocalizationSetContentPickerAdminController.SearchLocalizationSets) }
            );
        }
    }

    [Feature("OrchardCore.ContentFields.Indexing.SQL")]
    [RequireFeatures("OrchardCore.ContentFields")]
    public class IndexingStartup : StartupBase
    {
        public override void ConfigureServices(IServiceCollection services)
        {
            services.AddScoped<IDataMigration, Indexing.SQL.Migrations>();
            services.AddScoped<IScopedIndexProvider, TextFieldIndexProvider>();
            services.AddScoped<IScopedIndexProvider, BooleanFieldIndexProvider>();
            services.AddScoped<IScopedIndexProvider, NumericFieldIndexProvider>();
            services.AddScoped<IScopedIndexProvider, DateTimeFieldIndexProvider>();
            services.AddScoped<IScopedIndexProvider, DateFieldIndexProvider>();
            services.AddScoped<IScopedIndexProvider, ContentPickerFieldIndexProvider>();
            services.AddScoped<IScopedIndexProvider, TimeFieldIndexProvider>();
            services.AddScoped<IScopedIndexProvider, LinkFieldIndexProvider>();
            services.AddScoped<IScopedIndexProvider, HtmlFieldIndexProvider>();
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="ca.ualberta.papaya">

    <permission
        android:name="example.gps.permission.MAPS_RECEIVE"
        android:protectionLevel="signature"></permission>
    <!-- Copied from Google Maps Library/AndroidManifest.xml. -->

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="AIzaSyAlEikmGE6jKVjUHExlBmlUrkeiFMjTzEQ" />
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <activity
            android:name=".ThingListActivity"
            android:theme="@style/AppTheme.NoActionBar">
            <!--
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            -->
        </activity>
        <activity
            android:name=".ThingDetailActivity"
            android:parentActivityName=".ThingListActivity"
            android:theme="@style/AppTheme.NoActionBar">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="ca.ualberta.papaya.ThingListActivity" />
        </activity>
        <activity
            android:name=".BidProfileActivity"
            android:parentActivityName=".ThingListActivity"
            android:theme="@style/AppTheme.NoActionBar">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="ca.ualberta.papaya.ThingListActivity" />
        </activity>
        <activity
            android:name=".EditUserProfileActivity"
            android:parentActivityName=".ThingListActivity"
            android:theme="@style/AppTheme.NoActionBar">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="ca.ualberta.papaya.ThingListActivity" />
        </activity>
        <activity
            android:name=".UserProfileActivity"
            android:parentActivityName=".ThingListActivity"
            android:theme="@style/AppTheme.NoActionBar">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="ca.ualberta.papaya.ThingListActivity" />
        </activity>
        <activity
            android:name=".AddThingActivity"
            android:parentActivityName=".ThingListActivity"
            android:theme="@style/AppTheme.NoActionBar">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="ca.ualberta.papaya.ThingListActivity" />
        </activity>
        <activity
            android:name=".ThingSearchActivity"
            android:parentActivityName=".ThingListActivity"
            android:theme="@style/AppTheme.NoActionBar">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="ca.ualberta.papaya.ThingListActivity" />
        </activity>
        <activity
            android:name=".EditThingActivity"
            android:parentActivityName=".ThingListActivity"
            android:theme="@style/AppTheme.NoActionBar">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="ca.ualberta.papaya.ThingListActivity" />
        </activity>
        <activity
            android:name=".ThingSearchDetailActivity"
            android:parentActivityName=".ThingListActivity"
            android:theme="@style/AppTheme.NoActionBar">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="ca.ualberta.papaya.ThingSearchActivity" />
        </activity>
        <activity
            android:name=".AddPictureActivity"
            android:parentActivityName=".ThingListActivity"
            android:theme="@style/AppTheme.NoActionBar">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="ca.ualberta.papaya.ThingSearchActivity" />
        </activity>
        <activity
            android:name=".ViewPictureActivity"
            android:parentActivityName=".ThingListActivity"
            android:theme="@style/AppTheme.NoActionBar">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="ca.ualberta.papaya.ThingSearchActivity" />
        </activity>
        <activity
            android:name=".ThingBidsActivity"
            android:parentActivityName=".ThingListActivity"
            android:theme="@style/AppTheme.NoActionBar">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="ca.ualberta.papaya.ThingListActivity" />
        </activity>
        <activity
            android:name=".ThingBorrowingActivity"
            android:parentActivityName=".ThingListActivity"
            android:theme="@style/AppTheme.NoActionBar">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="ca.ualberta.papaya.ThingListActivity" />
        </activity>
        <activity
            android:name=".AllInfoActivity"
            android:parentActivityName=".ThingListActivity"
            android:theme="@style/AppTheme.NoActionBar">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="ca.ualberta.papaya.ThingListActivity" />
        </activity>
        <activity
            android:name=".LogInActivity"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity
            android:name=".DisplayLocationActivity"
            android:theme="@style/AppTheme.NoActionBar">
            <!--
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            -->
        </activity>

        <activity
            android:name=".SetLocationActivity"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <!-- ATTENTION: This was auto-generated to add Google Play services to your project for
             App Indexing.  See https://g.co/AppIndexing/AndroidStudio for more information. -->
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

    </application>

</manifest>


text:
from google.cloud import spanner_v1

async def sample_commit():
    # Create a client
    client = spanner_v1.SpannerAsyncClient()

    # Initialize request argument(s)
    request = spanner_v1.CommitRequest(
        transaction_id=b'transaction_id_blob',
        session="session_value",
    )

    # Make the request
    response = await client.commit(request=request)

    # Handle the response
    print(response)

# [END spanner_v1_generated_Spanner_Commit_async]


text: define({popupLabel:"Wy\u015bwietl lub ukryj kolumny"});


text:
import sys
import getopt

import os

from .structural_similarity import *
from model import *
from time import time
from util import *

# Read arguments from command line
def __main__(argv):
    s_file = ''
    t_file = ''
    operation = "compare_database"

    try:
        opts, args = getopt.getopt(argv, "D:A:B:s:t:o:", ["database=", "database_b=","database_b=","sfile=", "tfile=", "outputfile="])
    except getopt.GetoptError:
        print('model -s <stfile> -t <tfile> -o <outputfile>')
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print('model -s <stfile> -t <tfile> -o <outputfile>')
            sys.exit()
        elif opt in ("-s", "--sfile"):
            s_file = arg
            operation = "compare_pair"
        elif opt in ("-t", "--tfile"):
            t_file = arg
            operation = "compare_pair"
        elif opt in ("-D", "--database"):
            database_name = arg
            operation = "compare_database"
        elif opt in ("-A", "--database_a"):
            database_name_a = arg
            operation = "compare_two_databases"
        elif opt in ("-B", "--database_b"):
            database_name_b = arg
            operation = "compare_two_databases"
        elif opt in ("-o", "--outputfile"):
            output_file = arg

    output_file = open(output_file, "w")

    if operation == "compare_database":
        output_string = compare_database(database_name)
    elif operation == "compare_two_databases":
        output_string = compare_two_databases(database_name_a, database_name_b)
    else:
        output_string = compare_pair(s_file, t_file)

    output_file.write(output_string)
    output_file.close()

def compare_two_databases(database_name_a, database_name_b):
    file_names_a = util.list_dir(database_name_a + "/pickled/", "*.pkl")
    file_names_b = util.list_dir(database_name_b + "/pickled/", "*.pkl")

    documents_a = []
    documents_b = []

    # Read the database
    for file_name in file_names_a:
        documents_a.append(document_from_pkl(file_name))

    for file_name in file_names_b:
        documents_b.append(document_from_pkl(file_name))

    header_string = 'Distances in database' + database_name_a + " X " + database_name_b + ':\n'
    output_string = ''

    start_time = time()

    for rank in range(0, len(documents_a)):
        for j in range(0, len(documents_b)):
            # Get the words
            s_document = documents_a.__getitem__(rank)
            t_document = documents_b.__getitem__(j)

            simil = align_words(s_document, t_document);

            # results accumulation
            output_string += '[' + file_names_a.__getitem__(rank) + '][' + file_names_b.__getitem__(j) + ']=' + "%0.4f" % simil + '\n'

    end_time = time()
    spent_time = (end_time - start_time)

    time_string = "Spend time: %0.4f s\n" % spent_time

    output_string = header_string + time_string + output_string
    return output_string

def compare_database(database_name):

    # List files in database
    file_names = list_dir(database_name + "/pickled/", "*.pkl")

    documents = []

    # Read the database
    for file_name in file_names:
       documents.append(document_from_pkl(file_name))

    header_string = 'Distances in database' + database_name + ':\n'
    output_string = ''

    start_time = time()

    for rank in range(0, len(documents)):
        for j in range(rank+1, len(documents)):
            # Get the words

            # Call function
            simil = list_of_paragraphs(documents[rank], documents[j], granule_alignment_funcion=bag_of_words, threshold=0.8)

            # results accumulation
            output_string += '[' + file_names.__getitem__(rank) + '][' + file_names.__getitem__(j) + ']=' + "%0.4f" % simil + '\n'

    end_time = time()
    spent_time = (end_time - start_time)

    time_string = "Spend time: %0.4f s\n" % spent_time

    output_string = header_string + time_string + output_string
    return output_string

def compare_pair(s_file, t_file):

    # Define the values of comparasion
    s_document = document_from_pkl(s_file)
    t_document = document_from_pkl(t_file)

    # Get the paragraphs
    s_paragraphs = s_document.get_paragraphs()
    t_paragraphs = t_document.get_paragraphs()

    header_string = 'Distance(' + s_file + ', ' + t_file + '):\n'
    output_string = ''

    start_time = time()

    for rank in range(0, len(s_paragraphs)):
        for j in range(rank+1, len(t_paragraphs)):
            # Get the paragraphs
            s_paragraphsi = s_paragraphs.__getitem__(rank)
            t_paragraphsi = t_paragraphs.__getitem__(j)

            s_words = s_paragraphsi.get_words()
            t_words = t_paragraphsi.get_words()

            s_len = len(s_words)
            t_len = len(t_words)

            # Call function
            distance = str(parallel_levenshtein(s_words.to_hash_list(), t_words.to_hash_list()))

            simil = similarity(s_len, t_len, distance)

            #  results accumulation
            output_string += '[' + str(rank) + '][' + str(j) + ']=' + "%0.4f" % simil + '\n'

    end_time = time()
    spent_time = (end_time - start_time)

    time_string = "Spend time: %0.4f s\n" % spent_time

    output_string = header_string + time_string + output_string
    return output_string

if __name__ == "__main__":
    __main__(sys.argv[1:])


text:
var Fluxible = require('../../../../lib/Fluxible');
var Component = require('./components/Application.jsx');

module.exports = new Fluxible({
    component: Component
});


text:
<?php

declare(strict_types=1);

namespace Sonata\Exporter\Writer;

/**
 * Generates a GSA feed.
 *
 * @author Rémi Marseille <marseille@ekino.com>
 */
final class GsaFeedWriter implements WriterInterface
{
    public const LIMIT_SIZE = 31_457_280;

    private int $bufferPart;

    /**
     * @var resource|null
     *
     * @phpstan-var resource|null
     * @psalm-var resource|closed-resource|null
     */
    private $buffer;

    private int $bufferSize;

    /**
     * @param \SplFileInfo $folder     The folder to store the generated feed(s)
     * @param string       $dtd        A DTD URL (something like http://gsa.example.com/gsafeed.dtd)
     * @param string       $datasource A datasouce
     * @param string       $feedtype   A feedtype (full|incremental|metadata-and-url)
     */
    public function __construct(
        private \SplFileInfo $folder,
        private string $dtd,
        private string $datasource,
        private string $feedtype
    ) {
        $this->bufferPart = 0;
        $this->bufferSize = 0;
    }

    public function open(): void
    {
        $this->generateNewPart();
    }

    public function write(array $data): void
    {
        $line = sprintf(
            "        <record url=\"%s\" mimetype=\"%s\" action=\"%s\"/>\n",
            $data['url'],
            $data['mime_type'],
            $data['action']
        );

        // + 18 corresponding to the length of the closing tags
        if (($this->bufferSize + \strlen($line) + 18) > self::LIMIT_SIZE) {
            $this->generateNewPart();
        }

        $this->bufferSize += fwrite($this->getBuffer(), $line);
    }

    public function close(): void
    {
        if (null !== $this->buffer) {
            $this->closeFeed();
        }
    }

    /**
     * Generates a new file.
     *
     * @throws \RuntimeException
     */
    private function generateNewPart(): void
    {
        if (null !== $this->buffer) {
            $this->closeFeed();
        }

        $this->bufferSize = 0;
        ++$this->bufferPart;

        if (!$this->folder->isWritable()) {
            throw new \RuntimeException(sprintf('Unable to write to folder: %s', (string) $this->folder));
        }

        $filename = sprintf('%s/feed_%05d.xml', (string) $this->folder, $this->bufferPart);
        $buffer = fopen($filename, 'w');
        if (false === $buffer) {
            throw new \Exception(sprintf('Cannot open file %s.', $filename));
        }
        $this->buffer = $buffer;

        $this->bufferSize += fwrite(
            $this->buffer,
            <<<XML
                <?xml version="1.0" encoding="UTF-8"?>
                <!DOCTYPE gsafeed PUBLIC "-//Google//DTD GSA Feeds//EN" "$this->dtd">
                <gsafeed>
                    <header>
                        <datasource>$this->datasource</datasource>
                        <feedtype>$this->feedtype</feedtype>
                    </header>

                    <group>

                XML
        );
    }

    /**
     * @psalm-suppress InvalidPassByReference
     *
     * @see https://github.com/vimeo/psalm/issues/7505
     */
    private function closeFeed(): void
    {
        fwrite(
            $this->getBuffer(),
            <<<'EOF'
                    </group>
                </gsafeed>
                EOF
        );

        fclose($this->getBuffer());
    }

    /**
     * @return resource
     */
    private function getBuffer()
    {
        if (!\is_resource($this->buffer)) {
            throw new \LogicException('You MUST open the file first');
        }

        return $this->buffer;
    }
}


text:
/*
 *  eXist Open Source Native XML Database
 *  Copyright (C) 2001-04 The eXist Team
 *
 *  http://exist-db.org
 *
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public License
 *  as published by the Free Software Foundation; either version 2
 *  of the License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 *  $Id$
 */
package org.exist.storage.index;

import java.nio.ByteBuffer;

import org.exist.storage.DBBroker;
import org.exist.storage.journal.LogException;
import org.exist.storage.txn.Txn;

/**
 * @author wolf
 *
 */
public class OverflowStoreLoggable extends AbstractBFileLoggable {

	protected long pageNum;
	protected long prevPage;
    protected byte[] data;
    protected int startOffset;
	protected int size;

	/**
     *
     *
     * @param page
     * @param prevPage
     * @param chunk
     * @param startOffset
     * @param chunkSize
     * @param fileId
     * @param transaction
     */
	public OverflowStoreLoggable(byte fileId, Txn transaction, long page, long prevPage,
			byte[] chunk, int startOffset, int chunkSize) {
		super(BFile.LOG_OVERFLOW_STORE, fileId, transaction);
		this.pageNum = page;
        this.data = chunk;
		this.size = chunkSize;
		this.prevPage = prevPage;
        this.startOffset = startOffset;
	}

	/**
	 * @param broker
	 * @param transactionId
	 */
	public OverflowStoreLoggable(DBBroker broker, long transactionId) {
		super(broker, transactionId);
	}

	public void write(ByteBuffer out) {
        super.write(out);
        out.putInt((int) pageNum);
		out.putInt((int) prevPage);
        out.putInt(size);
        out.put(data, startOffset, size);
    }

	public void read(ByteBuffer in) {
		super.read(in);
		pageNum = in.getInt();
		prevPage = in.getInt();
		size = in.getInt();
		data = new byte[size];
		in.get(data);
	}

	public int getLogSize() {
		return super.getLogSize() + 12 + size;
	}

    public void redo() throws LogException {
        getIndexFile().redoStoreOverflow(this);
    }

	public String dump() {
		return super.dump() + " - stored overflow page " + pageNum;
	}
}


text:
var fs = require('fs'),
    path = require('path');

exports.app = app;
exports.lib = lib;
exports.ext = ext;
exports.run = run;

/// --- Methods

var run = require;

// A shortcut for adding `lib' and `ext' subfolders, then running a
// main program.
function app(base, main) {
  lib(path.join(base, 'lib'));
  ext(path.join(base, 'ext'));
  return main ? run(path.join(base, main)) : exports;
}

// Local libraries
function lib(folder) {
  if (exists(folder))
    require.paths.unshift(folder);
  return exports;
}

// Third-party libraries
function ext(folder) {
  if (!exists(folder))
    return exports;

  // Some programmers refer to third-party libraries in a fully-qualified manner.
  require.paths.unshift(folder);

  fs.readdirSync(folder).forEach(function(name) {
    var base = path.join(folder, name),
        linked = false;

    // Pure-JS packages have a `lib' folder with LIBRARY.js files in it.
    // Packages with C++ bindings will have a `build/default' folder
    // with LIBRARY.node files in it after running node-waf.
    [path.join(base, '/build/default'), path.join(base, '/lib')]
      .forEach(function(folder) {
        if (exists(folder)) {
          require.paths.unshift(folder);
          linked = true;
        }
      });

    // If neither `lib' or `build' were found, fallback to linking the
    // folder itself.
    if (!linked)
      require.paths.unshift(base);
  });
  return exports;
}

/// --- Aux

function exists(filename) {
  try {
    fs.statSync(filename);
    return true;
  } catch (x) {
    return false;
  }
}


text:
require 'test_helper'

class BarsControllerTest < ActionController::TestCase
  setup do
    @bar = bars(:one)
  end

  test "should get index" do
    get :index
    assert_response :success
    assert_not_nil assigns(:bars)
  end

  test "should get new" do
    get :new
    assert_response :success
  end

  test "should create bar" do
    assert_difference('Bar.count') do
      post :create, bar: { idf: @bar.idf, name: @bar.name }
    end

    assert_redirected_to bar_path(assigns(:bar))
  end

  test "should show bar" do
    get :show, id: @bar
    assert_response :success
  end

  test "should get edit" do
    get :edit, id: @bar
    assert_response :success
  end

  test "should update bar" do
    patch :update, id: @bar, bar: { idf: @bar.idf, name: @bar.name }
    assert_redirected_to bar_path(assigns(:bar))
  end

  test "should destroy bar" do
    assert_difference('Bar.count', -1) do
      delete :destroy, id: @bar
    end

    assert_redirected_to bars_path
  end
end


text:
#include <cppdevtk/base/deadlock_exception.hpp>

namespace cppdevtk {
namespace base {

}	// namespace base
}	// namespace cppdevtk


text:
layout: post
title: Amortised MAP Inference for Image Super-resolution
author: C.K. Sønderby, J. Caballero, L. Theis, W Shi, F. Huszár
year: 2017
key: 2016.3
journal: ICLR (Oral presentation)
link: https://openreview.net/forum?id=S1RP6GLle
bibtex: /media/publications/AmortizedMAP/bibtex.txt
pdf: https://openreview.net/pdf?id=S1RP6GLle
image: /media/publications/AmortizedMAP/image.jpg
type: paper
blog: http://www.inference.vc/instance-noise-a-trick-for-stabilising-gan-training/
---


text:
//
//  PeopleFavorites.h
//  People
//
//  Created by Bruno Koga on 7/20/13.
//  Copyright (c) 2013 CI&T. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface PeopleFavorites : NSObject

/*
 All these methods grabs the current user and set/get favorites for it.
 */
+ (NSArray *)allFavoriteColaboradores;
+ (void)addFavoriteWithLogin:(NSString *)login;
+ (void)removeFavoriteWithLogin:(NSString *)login;

@end


text:
This openresty config and lua script show an example of a simple HTTP load balancer using lua-resty-upstream and lua-resty-http.

## init_by_lua

In `init_by_lua` we've pulled in all 3 upstream modules, socket, http and api.

Then we create a new socket upstream instance and define 2 pools, `primary` and `dr`, each with 2 hosts.
Set the IPs and ports to whatever is appropriate for your environment.
The pools have some keepalive and timeout settings configured

Instances are created for both the API and http upstream modules.

Repeat for the SSL enable origin servers.

## init_worker_by_lua

We call `init_background_thread()` here on both http upstream instances to start the background workers.

This worker will restore dead hosts after the defined timeout period and perform background checks on hosts.

## lua-load-balancer

In our main server block, listening on port 80 and on port 443 for ssl, we pass everything to `load-balancer.lua` in `content_by_lua`.

In `load-balancer.lua` we check the scheme variable and select the right upstream instance.
`httpc` can then be used as if it was an instance of lua-resty-http.
The only real difference is the second return value from `request()` is a table.

We first get the request body iterator and return a 411 error if the client is attempting to send a chunked request.
This is not yet supported by the ngx_lua `ngx.req.socket` api.

Then we make an http request with all the parameters of the current request.
If the request errors then the `conn_info` table will contain the error message in `err` and the recommended response status code in `status`.
This will be `504 Gateway Timeout` if no tcp connection could be made at all, or `502 Bad Gateway` if the upstream host returned a bad status code.

You don't *have* to use these status codes, you can do whatever you like at this point.

If we successfully made a request to one of the hosts then we strip out hop-by-hop headers and add the rest of the upstream response headers to the current request's response headers.
Then we read the response body, if available, from the upstream host in chunks and flush back to the client.

We call `set_keepalive()` to let the pool configuration and http response determine whether to close the socket or put it into the connection pool.

Lastly we call `process_failed_hosts()` on the socket upstream module to save any failed hosts back to the dictionary.
This function triggers an immediate callback to run once the request has finished and so this doesn't affect the response time for the client.

## api

On port 8080 theres a very simple HTTP API, requesting `/pools` will return the current json encoded pool definition.
Calling `/down_host/primary/1` will mark the first host in the primary pool as offline and immediately stop any further requests being made to it.
Likewise `/up_host/primary/1` will bring it back up.


text:
import base64
import gzip
import io
import os

from oslo_log import log as oslo_logging

from cloudbaseinit import conf as cloudbaseinit_conf
from cloudbaseinit import exception
from cloudbaseinit.metadata.services import base
from cloudbaseinit.osutils import factory as osutils_factory
from cloudbaseinit.utils import serialization

CONF = cloudbaseinit_conf.CONF
LOG = oslo_logging.getLogger(__name__)

class VMwareGuestInfoService(base.BaseMetadataService):
    def __init__(self):
        super(VMwareGuestInfoService, self).__init__()
        self._rpc_tool_path = None
        self._osutils = osutils_factory.get_os_utils()
        self._meta_data = {}
        self._user_data = None

    @staticmethod
    def _decode_data(raw_data, is_base64, is_gzip):
        """Decode raw_data from base64 / ungzip"""
        if not raw_data:
            return

        if is_base64:
            raw_data = base64.b64decode(raw_data)

        if is_gzip:
            with gzip.GzipFile(fileobj=io.BytesIO(raw_data), mode='rb') as dt:
                raw_data = dt.read()

        return raw_data

    def _get_guestinfo_value(self, key):
        rpc_command = 'info-get guestinfo.%s' % key
        data, stderr, exit_code = self._osutils.execute_process([
            self._rpc_tool_path,
            rpc_command
        ])
        if exit_code:
            LOG.debug(
                'Failed to execute "%(rpctool_path)s \'%(rpc_command)s\'" '
                'with exit code: %(exit_code)s\nstdout: '
                '%(stdout)s\nstderr: %(stderr)s' % {
                    'rpctool_path': self._rpc_tool_path,
                    'rpc_command': rpc_command, 'exit_code': exit_code,
                    'stdout': data, 'stderr': stderr})
            return

        return data

    def _get_guest_data(self, key):
        is_base64 = False
        is_gzip = False
        encoding_plain_text = 'plaintext'
        raw_data = self._get_guestinfo_value(key)
        raw_encoding = self._get_guestinfo_value("%s.encoding" % key)

        if not raw_encoding or not raw_encoding.strip():
            raw_encoding = encoding_plain_text

        encoding = raw_encoding.strip()
        if isinstance(encoding, bytes):
            encoding = encoding.decode("utf-8")

        if encoding in ('gzip+base64', 'gz+b64'):
            is_gzip = True
            is_base64 = True
        elif encoding in ('base64', 'b64'):
            is_base64 = True
        elif encoding != encoding_plain_text:
            raise exception.CloudbaseInitException(
                "Encoding %s not supported" % encoding)

        LOG.debug("Decoding key %s: encoding %s", key, encoding)
        return self._decode_data(raw_data, is_base64, is_gzip)

    def load(self):
        super(VMwareGuestInfoService, self).load()

        if not CONF.vmwareguestinfo.vmware_rpctool_path:
            LOG.info("rpctool_path is empty. "
                     "Please provide a value for VMware rpctool path.")
            return False

        self._rpc_tool_path = os.path.abspath(
            os.path.expandvars(CONF.vmwareguestinfo.vmware_rpctool_path))

        if not os.path.exists(self._rpc_tool_path):
            LOG.info("%s does not exist. "
                     "Please provide a valid value for VMware rpctool path."
                     % self._rpc_tool_path)
            return False

        self._meta_data = serialization.parse_json_yaml(
            self._get_guest_data('metadata'))
        if not isinstance(self._meta_data, dict):
            LOG.warning("Instance metadata is not a dictionary.")
            self._meta_data = {}

        self._user_data = self._get_guest_data('userdata')

        if self._meta_data or self._user_data:
            return True

    def _get_data(self, path):
        pass

    def get_instance_id(self):
        return self._meta_data.get('instance-id')

    def get_user_data(self):
        return self._user_data

    def get_host_name(self):
        return self._meta_data.get('local-hostname')

    def get_public_keys(self):
        public_keys = []
        public_keys_data = self._meta_data.get('public-keys-data')

        if public_keys_data:
            public_keys = public_keys_data.splitlines()

        return list(set((key.strip() for key in public_keys)))

    def get_admin_username(self):
        return self._meta_data.get('admin-username')

    def get_admin_password(self):
        return self._meta_data.get('admin-password')


text:
import tryFn from './tryFn';
import promised from './promised';

export default promised(function times(n, iteratee, ...args) {
    return Promise.all(
        new Array(n)
            .fill()
            .map((item, index) => tryFn(iteratee, index, ...args))
    );
});


text:
define(function() {
    var fileName = null,
        encoding = false,
        readyCallback,
        frameNum = null;

    function start() {
        encoding = true;
        frameNum = 0;
    }

    function complete() {
        encoding = false;
    }

    function addFrame(canvas) {
        var header = 'data:image/xxx;base64,',
            fs = nodeRequire("fs"),
            dataURL = canvas.toDataURL();
            body = dataURL.substr(header.length),
            buffer = new Buffer(body, "base64"),
            frameName = getFrameName();

        fs.writeFile(frameName, buffer, "base64", function(err) {
            if(err) {
                alert("error: " + err);
            }
        });
        frameNum++;
    }

    function getFrameName() {
        var frameNumStr = "" + frameNum;
        while(frameNumStr.length < 4) {
            frameNumStr = "0" + frameNumStr;
        }
        return fileName + "_" + frameNumStr + ".png";
    }

    function chooseFileLocation(callback) {
        readyCallback = callback;
        var remote = nodeRequire("remote"),
            dialog = remote.require("dialog"),
            type = "png",
            options = {
                filters: [
                    {
                        name: type,
                        extensions: [type]
                    }
                ]
            };

        dialog.showSaveDialog(options, onFileChosen);

    }

    function onFileChosen(value) {
        if(value === undefined) return;
        fileName = value;
        if(fileName.substr(fileName.length - 4) === ".png") {
            fileName = fileName.substring(0, value.length - 4);
        }
        if(readyCallback) {
            readyCallback();
        }
    }

    function isEncoding() {
        return encoding;
    }

    return {
        start: start,
        complete: complete,
        isEncoding: isEncoding,
        addFrame: addFrame,
        chooseFileLocation: chooseFileLocation
    }

});


text:
import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';

import Form from '../Form';
import { approveTask } from '../../../actions/MarkerActions';
import { findOfferer, showUserModal } from '../../../actions/ModalActions';

class ApproveForm extends Form {
  constructor(props) {
    super(props);

    this.handleSubmitForm = this.handleSubmitForm.bind(this);
    this.handleSeeProfile = this.handleSeeProfile.bind(this);
  }

  handleSeeProfile(e) {
    e.preventDefault();
    e.stopPropagation();
    this.props.findOfferer(this.props.clickedMarker.exec_id);
    this.props.showUserModal();
  }

  handleSubmitForm() {
    const date = Date.now();
    this.props.approveTask(
      date,
      this.props.clickedMarker._id
    );
  }

  render() {
    const { clickedMarker, handleCloseModal } = this.props;
    return (
      <form>

Offer details:

          Title: {clickedMarker.title}

          Offered by: {clickedMarker.author}

          Description: {clickedMarker.text}

          Data: {this.formatDate(clickedMarker.modified)}

Accept details:

          Acceptor: {clickedMarker.executor} <button className='frofile-a' onClick={this.handleSeeProfile}>See Profile...</button>

          Phone: {clickedMarker.exec_phone}

          Description: {clickedMarker.exec_text}

          <input className="button" type="button" value="Approve" onClick={this.handleSubmitForm} />
          <input className="button" type="reset" value="Cansel" onClick={handleCloseModal} />

      </form>
    );
  }
}

function mapStateToProps(state) {
  return {
    clickCoords: state.map.clickCoords,
  };
}

function mapDispatchToProps(dispatch) {
  return {
    approveTask: bindActionCreators(approveTask, dispatch),
    findOfferer: bindActionCreators(findOfferer, dispatch),
    showUserModal: bindActionCreators(showUserModal, dispatch),
  };
}

ApproveForm.propTypes = {
  clickCoords: PropTypes.array.isRequired,
  approveTask: PropTypes.func.isRequired,
  findOfferer: PropTypes.func.isRequired,
  showUserModal: PropTypes.func.isRequired,
};

export default connect(mapStateToProps, mapDispatchToProps)(ApproveForm);


text:
/* ###
 * IP: GHIDRA
 *
 * 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.
 */
package ghidra.app.util.pdb.pdbapplicator;

import java.util.*;

import ghidra.app.util.bin.format.pdb2.pdbreader.*;
import ghidra.app.util.bin.format.pdb2.pdbreader.symbol.AbstractMsSymbol;
import ghidra.app.util.bin.format.pdb2.pdbreader.symbol.AbstractPublicMsSymbol;
import ghidra.app.util.pdb.pdbapplicator.SymbolGroup.AbstractMsSymbolIterator;
import ghidra.program.model.address.Address;
import ghidra.program.model.data.DataTypeManager;
import ghidra.program.model.listing.Program;
import ghidra.program.model.mem.Memory;
import ghidra.program.model.mem.MemoryAccessException;
import ghidra.util.Msg;
import ghidra.util.exception.CancelledException;
import ghidra.util.task.TaskMonitor;

/**
 * Manages virtual base table lookup for PDB classes.
 */
public class PdbVbtManager extends VbtManager {

	private Map<String, Address> addressByMangledName;
	private Memory memory;

	private static Memory getMemory(DefaultPdbApplicator applicator) throws PdbException {
		Program program = applicator.getProgram();
		if (program == null) {
			throw new PdbException("Program null for VbtManager");
		}
		return program.getMemory();
	}

	// TODO: Research whether we ever find VBT symbols put into the program by the "loader."
	//  If we find some this way, then need to modify PdbVbtManager to also look
	//  through the loader symbol for them.
	private static Map<String, Address> findVirtualBaseTableSymbols(DefaultPdbApplicator applicator)
			throws CancelledException {

		TaskMonitor monitor = applicator.getMonitor();
		Map<String, Address> myAddressByMangledName = new HashMap<>();

		AbstractPdb pdb = applicator.getPdb();
		PdbDebugInfo debugInfo = pdb.getDebugInfo();
		if (debugInfo == null) {
			return myAddressByMangledName;
		}

		SymbolGroup symbolGroup = applicator.getSymbolGroup();
		if (symbolGroup == null) {
			return myAddressByMangledName;
		}

		PublicSymbolInformation publicSymbolInformation = debugInfo.getPublicSymbolInformation();
		List<Long> offsets = publicSymbolInformation.getModifiedHashRecordSymbolOffsets();
		monitor.setMessage("PDB: Searching for virtual base table symbols...");
		monitor.initialize(offsets.size());

		AbstractMsSymbolIterator iter = symbolGroup.iterator();
		for (long offset : offsets) {
			monitor.checkCanceled();
			iter.initGetByOffset(offset);
			if (!iter.hasNext()) {
				break;
			}
			AbstractMsSymbol symbol = iter.peek();
			if (symbol instanceof AbstractPublicMsSymbol) {
				AbstractPublicMsSymbol pubSymbol = (AbstractPublicMsSymbol) symbol;
				String name = pubSymbol.getName();
				if (name.startsWith("??_8")) {
					Address address = applicator.getAddress(pubSymbol);
					if (!applicator.isInvalidAddress(address, name)) {
						myAddressByMangledName.put(name, address);
					}
				}
			}
			monitor.incrementProgress(1);
		}
		return myAddressByMangledName;
	}

	/**
	 * Virtual Base Table Lookup Manager
	 * @param applicator {@link DefaultPdbApplicator} for which this class is working.
	 * @throws PdbException If Program is null;
	 * @throws CancelledException upon user cancellation
	 */
	PdbVbtManager(DefaultPdbApplicator applicator) throws PdbException, CancelledException {
		this(applicator.getDataTypeManager(), getMemory(applicator),
			findVirtualBaseTableSymbols(applicator));
	}

	PdbVbtManager(DataTypeManager dataTypeManager, Memory memory,
			Map<String, Address> addressByMangledName) {
		super(dataTypeManager);
		this.memory = memory;
		this.addressByMangledName = addressByMangledName;
	}

//	/**
//	 * Builds the tables
//	 * @throws PdbException If Program is null;
//	 * @throws CancelledException upon user cancellation.
//	 */
//	void CreateVirtualBaseTables() throws PdbException, CancelledException {
//		createVirtualBaseTables();
//	}
//
	PdbVirtualBaseTable createVirtualBaseTableByName(String mangledName, int entrySize) {
		Address address = addressByMangledName.get(mangledName);
		if (address == null) {
			return null;
			//throw new PdbException("Cannot find address for table name: " + mangledName);
		}
		return createVirtualBaseTable(address, entrySize);
	}

	PdbVirtualBaseTable createVirtualBaseTable(Address address, int entrySize) {

		VirtualBaseTable vbt = vbtByAddress.get(address);
		if (vbt != null) {
			String message =
				"PDB: warning virtual base table already exists for address: " + address;
			PdbLog.message(message);
			Msg.info(this, message);
		}
		else {
			vbt = new PdbVirtualBaseTable(memory, address, entrySize);
			vbtByAddress.put(address, vbt);
		}
		if (!(vbt instanceof PdbVirtualBaseTable)) {
			// investigate this
		}
		return (PdbVirtualBaseTable) vbt;
	}

	/**
	 * Returns offset for vbtable (mangled name) and ordinal
	 * @param vbtMangledName mangled name of vbtable
	 * @param ordinal index into table
	 * @param size size of a vbt entry offset value
	 * @return the offset
	 * @throws PdbException if no address exists for mangled name
	 */
	long getOffset(String vbtMangledName, int ordinal, int size) throws PdbException {
		Address address = addressByMangledName.get(vbtMangledName);
		if (address == null) {
			throw new PdbException(
				"Virtual Base Table does not exist for symbol: " + vbtMangledName);
		}
		return getOffset(address, ordinal, size);
	}

	/**
	 * Returns the offset from the virtual base table entry
	 * @param address Address of virtual base table
	 * @param ordinal index into table
	 * @param size size of a vbt entry offset value
	 * @return the offset
	 * @throws PdbException if no table exists for address or no entry exists for ordinal
	 */
	long getOffset(Address address, int ordinal, int size) throws PdbException {
		VirtualBaseTable table = vbtByAddress.get(address);
		if (table == null) {
			throw new PdbException("Virtual Base Table does not exist for address: " + address);
		}
		if (!(table instanceof PdbVirtualBaseTable)) {
			throw new PdbException("Not a PDB Virtual Base Table for address: " + address);
		}
		VirtualBaseTableEntry entry =
			((PdbVirtualBaseTable) table).getOrParseEntryByOrdinal(ordinal);
		return entry.getOffset();
	}

	private void createVirtualBaseTables() {
		for (Map.Entry<String, Address> entry : addressByMangledName.entrySet()) {
			Address address = entry.getValue();
			createVirtualBaseTable(address);
		}
	}

	static VirtualBaseTableEntry parseVbtEntryFromMemory(Memory memory, Address address,
			int ordinal, int size) throws PdbException {
		if (size != 4 && size != 8) {
			throw new IllegalArgumentException("Invalid size (" + size + "): must be 4 or 8.");
		}
		Address readAddress = address.add(ordinal * size);
		long offset;
		try {
			offset = (size == 4) ? (long) memory.getInt(readAddress) : memory.getLong(readAddress);
		}
		catch (MemoryAccessException e) {
			throw new PdbException(
				"MemoryAccessException while trying to parse virtual base table entry at address: " +
					readAddress);
		}
		return new VirtualBaseTableEntry(offset);
	}

	static class PdbVirtualBaseTable extends VirtualBaseTable {
		private Memory memory;
		private Address address;
		private int entrySize;

		PdbVirtualBaseTable(Memory memory, Address address, int entrySize) {
			super();
			this.memory = memory;
			this.address = address;
			this.entrySize = entrySize;
		}

		@Override
		VirtualBaseTableEntry getEntry(int ordinal) throws PdbException {
			return getOrParseEntryByOrdinal(ordinal);
			//return entryByOrdinal.get(ordinal);
		}

		VirtualBaseTableEntry getOrParseEntryByOrdinal(int ordinal) throws PdbException {
			VirtualBaseTableEntry entry = entryByOrdinal.get(ordinal);
			if (entry == null) {
				entry = parseVbtEntryFromMemory(memory, address, ordinal, entrySize);
				addEntry(ordinal, entry);
			}
			return entry;
		}
	}
}


text:
@import Foundation;

typedef NS_ENUM(NSInteger, KRMLPInertialMethods)
{
    KRMLPInertialFixedRate = 0, // Fixed inertial rate, 固定慣性項
    KRMLPInertialQuickProp,
    KRMLPInertialRProp
};

@class KRMLPNet;

@interface KRMLPInertia : NSObject

@property (nonatomic, assign) KRMLPInertialMethods inertialMethod;
@property (nonatomic, assign) double inertialRate; // (Kecman, 2001) suggested this inertial rate between 0.5 ~ 0.7.

+ (instancetype)sharedInertia;
- (instancetype)initWithMethod:(KRMLPInertialMethods)method;
- (instancetype)init;

- (double)deltaWeightAtIndex:(NSInteger)weightIndex net:(KRMLPNet *)net mappedOutput:(double)mappedOutput learningRate:(double)learningRate;

@end


text:
/* eslint-env mocha, browser*/
/* global proclaim, it */

describe('console', function () {

	it('info()', function () {
		proclaim.doesNotThrow(function () {
			console.info();
		});
	});

});