text:
using KUparser, KUnet, HDF5, JLD, ArgParse, Compat, CUDArt
VERSION < v"0.4-" && eval(Expr(:using,:Dates))

function parse_commandline()
    s = ArgParseSettings()
    @add_arg_table s begin
        "datafiles"
        help = "JLD files for input: first one will be used for training"
        nargs = '+'
        required = true
        "--out"
        help = "JLD file for output trained network"
        default = ""
        "--nogpu"
        help = "Do not use gpu"
        action = :store_true
        "--parser"
        help = "Parsing algorithm to use: g(reedy)parser, b(eam)parser, or o(racle)parser for static training"
        default = "oparser"
        "--arctype"
        help = "Move set to use: ArcEager{R1,13}, ArcHybrid{R1,13}"
        default = "ArcEager13"
        "--feats"
        help = "Features to use from KUparser.Flist"
        default = "tacl13hybrid"
        "--hidden"
        help = "One or more hidden layer sizes"
        nargs = '+'
        arg_type = Int
        default = [20000]
        "--epochs"
        help = "Minimum number of epochs to train"
        arg_type = Int
        default = 100
        "--pepochs"
        help = "Number of epochs between parsing"
        arg_type = Int
        default = 1
        "--ncpu"
        help = "Number of workers for multithreaded parsing"
        arg_type = Int
        default = 12
        "--pbatch"
        help = "Minibatch size for parsing"
        arg_type = Int
        default = 2000
        "--tbatch"
        help = "Minibatch size for training"
        arg_type = Int
        default = 128
        "--nbeam"
        help = "Beam size for bparser"
        arg_type = Int
        default = 10
        "--adagrad"
        help = "If nonzero apply adagrad using arg as epsilon"
        arg_type = Float32
        nargs = '+'
        default = [1f-8]
        "--dropout"
        help = "Dropout probability"
        arg_type = Float32
        nargs = '+'
        default = [0.2f0, 0.7f0]
        "--l1reg"
        help = "L1 regularization parameter"
        arg_type = Float32
        nargs = '+'
        "--l2reg"
        help = "L2 regularization parameter"
        arg_type = Float32
        nargs = '+'
        "--learningRate"
        help = "Learning rate"
        arg_type = Float32
        nargs = '+'
        default = [2f-2]
        "--maxnorm"
        help = "If nonzero upper limit on weight matrix row norms"
        arg_type = Float32
        nargs = '+'
        "--momentum"
        help = "Momentum"
        arg_type = Float32
        nargs = '+'
        "--nesterov"
        help = "Apply nesterov's accelerated gradient"
        arg_type = Float32
        nargs = '+'
        "--seed"
        help = "Random number seed (-1 leaves the default seed)"
        arg_type = Int
        default = -1
    end
    args = parse_args(s)
    for (arg,val) in args
        print("$arg:$val ")
    end
    println("")
    return args
end

macro meminfo() :(gc(); run(`nvidia-smi`); run(`ps auxww`|>`grep julia`); run(`free`)) end

function main()
    args = parse_commandline()
    KUnet.gpu(!args["nogpu"])
    args["nogpu"] && blas_set_num_threads(20)
    args["seed"] >= 0 && (srand(args["seed"]); KUnet.gpuseed(args["seed"]))

    data = Corpus[]
    deprel = nothing
    ndeps = 0
    for f in args["datafiles"]
        @date d=load(f)
        push!(data, d["corpus"])
        if deprel == nothing
            deprel = d["deprel"]
            ndeps = length(deprel)
        else
            @assert deprel == d["deprel"]
        end
    end

    feats = eval(parse("Flist."*args["feats"]))
    pt = eval(parse(args["arctype"]))
    s1 = data[1][1]
    p1 = pt(wcnt(s1),length(deprel))
    xrows=KUparser.flen(p1, s1, feats)
    yrows=p1.nmove

    net=newnet(relu, [xrows; args["hidden"]; yrows]...)
    net[end].f=KUnet.logp
    for k in [fieldnames(UpdateParam); :dropout]
        haskey(args, string(k)) || continue
        v = args[string(k)]
        if isempty(v)
            continue
        elseif length(v)==1
            setparam!(net, k, v[1])
        else
            @assert length(v)==length(net) "$k should have 1 or $(length(net)) elements"
            for i=1:length(v)
                setparam!(net[i], k, v[i])
            end
        end
    end
    @show net

    # Initialize training set and model using oparse on first corpus
    @date (p,x,y) = oparse(pt, data[1], ndeps, args["ncpu"], feats)
    @date train(net, x, y; batch=args["tbatch"], loss=KUnet.logploss, shuffle=true)

    accuracy = Array(Float32, length(data))
    (bestscore,bestepoch,epoch)=(0,0,0)

    while true
        @show epoch += 1
        # @show map(size, (x, y))
        # @date train(net, x, y; batch=args["tbatch"], loss=KUnet.logploss, shuffle=true)
        # if epoch % args["pepochs"] == 0
        # @meminfo
        if (args["parser"] == "oparser")
            # We never change the training set with oparser, just report accuracy
            @date train(net, x, y; batch=args["tbatch"], loss=KUnet.logploss, shuffle=true)
            for i=1:length(data)
                @date p = gparse(pt, data[i], ndeps, feats, net, args["pbatch"], args["ncpu"])
                @show e = evalparse(p, data[i]); p=nothing; gc()
                accuracy[i] = e[1]  # e[1] is UAS including punct
            end
        elseif (args["parser"] == "gparser")
            # The first corpus gives us the new training set
            # p = x = y = nothing; gc()
            for s1 = 1:args["pbatch"]:length(data[1])
                @show s2 = min(length(data[1]), s1+args["pbatch"]-1)
                trn = sub(data[1], s1:s2)
                @date (p,x,y) = gparse(pt, trn, ndeps, feats, net, args["pbatch"], args["ncpu"]; xy=true)
                @show e = evalparse(p, trn); p=nothing; gc()
                @show accuracy[1] = ((s1-1)*accuracy[1] + (s2-s1+1)*e[1])/s2
                @show map(size, (x, y))
                @date train(net, x, y; batch=args["tbatch"], loss=KUnet.logploss, shuffle=true); x=y=nothing; gc()
            end
            for i=2:length(data)
                @date p = gparse(pt, data[i], ndeps, feats, net, args["pbatch"], args["ncpu"])
                @show e = evalparse(p, data[i]); p=nothing; gc()
                accuracy[i] = e[1]
            end
        elseif (args["parser"] == "bparser")
            # The first corpus gives us the new training set
            # p = x = y = nothing; gc()
            for s1 = 1:args["pbatch"]:length(data[1])
                @show s2 = min(length(data[1]), s1+args["pbatch"]-1)
                trn = sub(data[1], s1:s2)
                @date (p,x,y) = bparse(pt, trn, ndeps, feats, net, args["nbeam"], args["pbatch"], args["ncpu"]; xy=true)
                @show e = evalparse(p, trn); p=nothing; gc()
                @show accuracy[1] = ((s1-1)*accuracy[1] + (s2-s1+1)*e[1])/s2
                @show map(size, (x, y))
                @date train(net, x, y; batch=args["tbatch"], loss=KUnet.logploss, shuffle=true); x=y=nothing; gc()
            end
            for i=2:length(data)
                @date p = bparse(pt, data[i], ndeps, feats, net, args["nbeam"], args["pbatch"], args["ncpu"])
                @show e = evalparse(p, data[i]); p=nothing; gc()
                accuracy[i] = e[1]
            end
        else
            error("Unknown parser "*args["parser"])
        end
        println("DATA:\t$epoch\t"*join(accuracy, '\t')); flush(STDOUT)

        # We look at accuracy[2] (dev score) by default,
        # accuracy[1] (trn score) if there is no dev.

        score = (length(accuracy) > 1 ? accuracy[2] : accuracy[1])

        # Update best score and save best net

        if (score > bestscore)
            @show (bestscore,bestepoch)=(score,epoch)
            !isempty(args["out"]) && save(args["out"], net)
        end

        # Quit if we have the minimum number of epochs and have
        # not made progress in the last half.

        (epoch >= args["epochs"]) && (epoch >= 2*bestepoch) && break

        # end
    end # while true
end # main

main()

redpajama_set_name: RedPajamaGithub


text:
Hola,

Usted está recibiendo este correo electrónico porque usted está viendo el tema, "{TOPIC_TITLE}" en {SITENAME}. Este tema ha recibido una respuesta desde su última visita. Puede utilizar el siguiente enlace para ver las respuestas, no más notificaciones se enviarán hasta que visite el tema.

{U_TOPIC}

Si usted ya no desea ver este tema en el que pueden hacer clic en el "Dejar de ver este vínculo de un tema" que se encuentra en la parte inferior del tema anterior, o haciendo clic en el siguiente enlace:

{U_STOP_WATCHING_TOPIC}

{EMAIL_SIG}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Pleospora carpinicola Ellis & Everh.

### Remarks
null


text:
class RendermanPolyMeshSchemaHandler : public AbstractPolyMeshSchemaHandler
{

public:
	RendermanPolyMeshSchemaHandler();
	virtual ~RendermanPolyMeshSchemaHandler();
protected:
	virtual void EmitPolyMesh(Alembic::AbcGeom::IPolyMesh& pmesh,
							  Alembic::Abc::index_t        i_start_frame_number,
							  Alembic::Abc::index_t        i_requested_frame_number,
							  const std::string&           i_renderman_filename,
							  Alembic::Abc::uint8_t 	   i_motion_samples,
							  float          			   i_relative_shutter_open,
							  float          			   i_relative_shutter_close) const;
private:
	void build_polymesh_for_renderman_rib(const Alembic::AbcGeom::IPolyMeshSchema::Sample* i_previous_sample,
										  const Alembic::AbcGeom::IPolyMeshSchema::Sample* i_current_sample,
										  const Alembic::AbcGeom::IPolyMeshSchema::Sample* i_next_sample,
										  float											i_relative_shutter_open,
										  float											i_relative_shutter_close,
										  Alembic::Abc::uint8_t                            i_motion_sample_count,
										  RendermanMeshData&                               o_renderman_mesh) const;
};
// == Emacs ================
// -------------------------
// Local variables:
// tab-width: 4
// indent-tabs-mode: t
// c-basic-offset: 4
// end:
//
// == vi ===================
// -------------------------
// Format block
// ex:ts=4:sw=4:expandtab
// -------------------------


text:
<?php

namespace WebConstructionSet\Url;

class Tools {
	/**
	 * Получить полный URL к собственному (исполняемому) скрипту
	 * @return string URL
	 */
	public static function getMyUrl() {
		return (empty($_SERVER['HTTPS']) ? 'http' : 'https') . '://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
	}

	/**
	 * Получить URL к собственному (исполняемому) скрипту без параметров
	 * @return string URL
	 */
	public static function getMyUrlName() {
		return preg_replace('/\?.+/', '', Tools::getMyUrl());
	}

	/**
	 * Полчить URL к каталогу, где лежит выполняемый скрипт
	 * @return string URL
	 */
	public static function getMyUrlPath() {
		$path = preg_replace('~/[^/]+$~', '/', Tools::getMyUrlName());
		if (!preg_match('~/$~', $path))
			$path .= '/';
		return $path;
	}

	/**
	 * Получить URL к скрипту, который лежит рядом
	 * @param string $scriptName
	 * @return string URL
	 */
	public static function getNeighbourUrl($scriptName) {
		return Tools::getMyUrlPath() . $scriptName;
	}

	/**
	 * Извлечь схему и имя сервера http://server.name
	 * @param string $url
	 * @return string|NULL URL
	 */
	public static function makeServerUrl($url) {
		while (preg_match('~//\S+/~', $url))
			$url = dirname($url);
		if (preg_match('~//\S+~', $url))
			return $url;
		return null;
	}

	/**
	 * Нормализация url (убирает /../ /./ //)
	 * @param string $url
	 * @return string URL
	 */
	public static function normalize($url) {
		$prefix = '';
		if (preg_match('~^\s*((\S+:)?//)~', $url, $matches)) {
			$prefix = $matches[1];
			$url = preg_replace('~^\s*((\S+:)?//)~', '', $url);
		} else if (preg_match('~^\s*(/)~', $url, $matches)) {
			$prefix = $matches[1];
			$url = preg_replace('~^\s*(/)~', '', $url);
		}
		$segments = explode('/', $url);
		$path = [];
		foreach($segments as $segment) {
			if ($segment == '')
				continue;
			if ($segment == '.')
				continue;
			if ($segment == '..')
				array_pop($path);
			else
				array_push($path, $segment);
		}
		$url = $prefix . implode('/', $path);
		return $url;
	}

	/**
	 * Добавить параметры к url
	 * Вставляет разделитель "?" или "&", кодирует значения
	 * @param string $url
	 * @param [string => string] $params
	 * @return string URL
	 */
	public static function addParams($url, $params) {
		if (strpos($url, '?') === false)
			return $url . '?' . http_build_query($params);
		else
			return $url . '&' . http_build_query($params);
	}
}


text:
body {background-color:#F4FA58;}
p {font-family: sans-serif color: #0000FF}
#awesomeText {font-family: 'Times New Roman', Serif;}
.blue {color:#0000FF}
.red {color:#FF0000}
.black {color:#00000}
.center {text-align: center}


text:
'use strict';

const Token = require('./token');
const Tag = require('./tag');

class Num extends Token {
  constructor(value) {
    super(Tag.NUM);
    this.value = value;
  }

  toString() {
    return '' + this.value;
  }
}

module.exports = Num;


text:
The existing calico networking plugin for mesos already provides coarse grained security policy whereby tasks can
be grouped and isolated from tasks in other groups, e.g. so that your test apps can not modify your production data
stores! (see the video of the Calico presentation/demo on the Thursday of MesosCon Dublin 2015).

Our hack was extending this to allow more fine grained controls, with which you can open up/close specific IPs and
ports to individual tasks within those groups.

## Team

- @neiljerram
- @emmagordon
- @lxpollitt
- @patclaffey

## Source

All source material is in https://github.com/projectcalico/calico-mesos/tree/njhack

## Documentation

Documentation does not exist yet - sorry! See the video of the hackathon presentations for a demo of the UI.

## License

This material is licensed under the terms of the [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0)


text:
import numpy as np

array = np.random.rand(100)
array[5] = np.nan

# Returns inccorrect result
print(np.max(array))
# nan

# Returns correct result
print(np.nanmax(array))
# 0.992949280963


text:
<?php

/**
 * KSMVC version 0.1.0
 * https://github.com/gidcs/ksmvc
 * Lim Kok Suan <admin@gidcs.net>
 */

namespace Core\Commands;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class ControllerMakeCommand extends Command
{
  protected function configure()
  {
    $this
      ->setName('make:controller')
      ->setDescription('Create a new controller class.')
      ->addArgument(
        'name',
        InputArgument::REQUIRED,
        'What is your controller name?'
      )
      ->addOption(
        'blank',
        null,
        InputOption::VALUE_NONE,
        'If set, the new controller class will be blank.'
      );
  }

  protected function getErrorString($error_header='',$error_msg=[]){
      $maxlen = max(array_map('strlen', $error_msg));
      $maxlen = max($maxlen,strlen($error_header));
      $text = '<error>'."\n";
      $text .= '  '.str_repeat(' ', $maxlen)."  \n";
      $text .= '  '.$error_header.str_repeat(' ', $maxlen-strlen($error_header))."  \n";
      foreach($error_msg as $msg){
        $text .= '  '.$msg.str_repeat(' ', $maxlen-strlen($msg))."  \n";
      }
      $text .= '  '.str_repeat(' ', $maxlen)."  ";
      $text .= '</error>';
      return $text;
  }

  protected function copy_controller_file($source, $dest, $name, $view_dir_name){
    $file = file_get_contents($source);
    $file = str_replace("DummyClass", $name, $file);
    $file = str_replace("Dummy", $view_dir_name, $file);
    return file_put_contents($dest, $file, LOCK_EX);
  }

  protected function copy_view_file($source, $dest){
    $file = file_get_contents($source);
    return file_put_contents($dest, $file, LOCK_EX);
  }

  protected function execute(InputInterface $input, OutputInterface $output)
  {
    //for view files creation
    $view_dir_name = lcfirst($input->getArgument('name'));
    $view_dir = './app/views/'.$view_dir_name;

    //for controller file creation
    $name = ucfirst($input->getArgument('name')).'Controller';
    $source = './core/Commands/stub/controller.stub';
    if ($input->getOption('blank')) {
      $source .= '.plain';
    }
    $dest = './app/controllers/'.$name.'.php';
    if(file_exists($dest)){
      $header = '[InvalidArgumentException]';
      $msg[] = 'The controller class "'.$name.'" already exists';
      $text=$this->getErrorString($header,$msg);
      $output->writeln($text);
    }
    else{
      //generate controller file
      if(!file_exists($source)){
        $header = '[MissingFileException]';
        $msg[] = 'Failed to write file to app/controllers/'.$name.'.php';
        $text=$this->getErrorString($header,$msg);
        $output->writeln($text);
      }
      else if (!$this->copy_controller_file($source,$dest,$name,$view_dir_name)){
        $header = '[CopyFailedException]';
        $msg[] = 'Failed to write file to app/controllers/'.$name.'.php  ';
        $text=$this->getErrorString($header,$msg);
        $output->writeln($text);
      }
      else{
        $text = '<info>created</info> app/controllers/'.$name.'.php';
        $output->writeln($text);
        //generate view files
        if ($input->getOption('blank')) {
          //no view files needed
        }
        else{
          //create directory
          if(!mkdir($view_dir, 0755)){
            $header = '[MkdirFailedException]';
            $msg[] = 'Failed to create directory app/views/'.$view_dir_name;
            $text=$this->getErrorString($header,$msg);
            $output->writeln($text);
          }
          else{
            $text = '<info>directory created</info> app/views/'.$view_dir_name;
            $output->writeln($text);
            //copy view file
            $views = ['index', 'create', 'show', 'edit'];
            $source = './core/Commands/stub/view.stub';
            foreach($views as $v){
              $dest = $view_dir.'/'.$v.'.pug';
              if(!$this->copy_view_file($source,$dest)){
                $header = '[CopyFailedException]';
                $msg[] = 'Failed to write file to app/views/'.$view_dir_name.'/'.$v.'.php  ';
                $text=$this->getErrorString($header,$msg);
                $output->writeln($text);
              }
              else{
                $text = '<info>created</info> app/views/'.$view_dir_name.'/'.$v.'.php';
                $output->writeln($text);
              }
            }
          }
        }
      }
    }
  }
}


text:
package com.twotoasters.sectioncursoradaptersample.adapter;

import android.content.Context;
import android.database.Cursor;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ViewSwitcher;

import com.squareup.picasso.Picasso;
import com.twotoasters.sectioncursoradapter.SectionCursorAdapter;
import com.twotoasters.sectioncursoradaptersample.R;
import com.twotoasters.sectioncursoradaptersample.database.ToasterModel;
import com.twotoasters.sectioncursoradaptersample.transformation.SquareTransformation;

public class ToastersAdapter extends SectionCursorAdapter {

    private final SquareTransformation mToasterTrans;
    private final SquareTransformation mHumanTrans;

    public ToastersAdapter(Context context, Cursor cursor) {
        super(context, cursor, 0);

        mToasterTrans = new SquareTransformation(true);
        mHumanTrans = new SquareTransformation(false);
    }

    @Override
    protected Object getSectionFromCursor(Cursor cursor) {
        final ToasterModel toaster = new ToasterModel();
        toaster.loadFromCursor(cursor);
        return toaster.shortJob;
    }

    @Override
    protected View newSectionView(Context context, Object item, ViewGroup parent) {
        return getLayoutInflater().inflate(R.layout.item_section, parent, false);
    }

    @Override
    protected void bindSectionView(View convertView, Context context, int position, Object item) {
        ((TextView) convertView).setText((String) item);
    }

    @Override
    protected View newItemView(Context context, Cursor cursor, ViewGroup parent) {
        View convertView = getLayoutInflater().inflate(R.layout.item_toaster, parent, false);
        ViewHolder holder = new ViewHolder(convertView);
        convertView.setTag(holder);

        return convertView;
    }

    @Override
    protected void bindItemView(View convertView, Context context, Cursor cursor) {
        final ToasterModel toaster = new ToasterModel();
        toaster.loadFromCursor(cursor);

        final ViewHolder holder = (ViewHolder) convertView.getTag();
        holder.txtName.setText(toaster.name);
        holder.txtJob.setText(toaster.jobDescription);

        Picasso.with(context).load(toaster.imageUrl)
                .error(R.drawable.toaster_backup).transform(mToasterTrans)
                .into(holder.imgToaster);
        Picasso.with(context).load(toaster.imageUrl)
                .error(R.drawable.toaster_backup).transform(mHumanTrans)
                .into(holder.imgHuman);
        // Reseting the view our switcher is showing.
        switchWithoutAnimation(holder.switcher);
        holder.switcher.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                ((ViewSwitcher) v).showNext();
            }
        });
    }

    private void switchWithoutAnimation(ViewSwitcher switcher) {
        if (switcher.getDisplayedChild() != 0) {
            Animation in = switcher.getInAnimation();
            Animation out = switcher.getOutAnimation();

            switcher.setInAnimation(null);
            switcher.setOutAnimation(null);

            switcher.setDisplayedChild(0);
            switcher.setInAnimation(in);
            switcher.setOutAnimation(out);
        };
    }

    private static class ViewHolder {
        TextView txtName;
        TextView txtJob;
        ImageView imgToaster;
        ImageView imgHuman;
        ViewSwitcher switcher;

        private ViewHolder(View convertView) {
            txtName = (TextView) convertView.findViewById(R.id.txtName);
            txtJob = (TextView) convertView.findViewById(R.id.txtJob);
            imgToaster = (ImageView) convertView.findViewById(R.id.imgToaster);
            imgHuman = (ImageView) convertView.findViewById(R.id.imgHuman);
            switcher = (ViewSwitcher) convertView.findViewById(R.id.switcherImg);
        }
    }

    @Override
    protected int getMaxIndexerLength() {
        return 1;
    }
}


text:
package com.greenpepper.extensions.guice;

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

import com.google.inject.Singleton;

@Singleton
public class PhoneBook
{

	private List<PhoneBookEntry> entries = new ArrayList<PhoneBookEntry>();

	public void add(PhoneBookEntry entry)
	{
		entries.add(entry);
	}

	public List<PhoneBookEntry> getEntries()
	{
		return entries;
	}

	public String findNumber(String firstName, String lastName)
	{
		PhoneBookEntry entry = findEntry(firstName, lastName);

		return entry == null ? null : entry.getNumber();
	}

	public void updateNumber(String firstName, String lastName, String number)
	{
		PhoneBookEntry entry = findEntry(firstName, lastName);

		if (entry == null)
		{
			throw new IllegalArgumentException("Entry not found");
		}

		entry.setNumber(number);
	}

	private PhoneBookEntry findEntry(String firstName, String lastName)
	{
		for (PhoneBookEntry entry : entries)
		{
			if (entry.getFirstName().equalsIgnoreCase(firstName)
				&& entry.getLastName().equalsIgnoreCase(lastName))
			{
				return entry;
			}
		}

		return null;
	}
}


text:
require 'httparty'
require 'hashie'
require 'git'

begin
  require 'pry'
rescue Gem::LoadError
end

require 'apigee_cli/configuration'
require 'apigee_cli/base'
require 'apigee_cli/version'

require 'apigee_cli/config_set'
require 'apigee_cli/resource_file'

module ApigeeCli
end


text:
package com.nr.viewnote.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.List;

/**
 * Convenient database adapter class
 */
public class DbAdapter {
    private final Context mContext;
    private InnerDbHelper mDbHelper;
    private SQLiteDatabase mDb;
    private static DbAdapter mSelf;
    private static boolean isOpened;

    /**
     * Singleton getInstance method
     * @param context current context
     * @return singleton database adapter object
     */
    public static synchronized DbAdapter getInstance(Context context){
        if(mSelf == null){
            mSelf = new DbAdapter(context);
        }
        if(!isOpened){
            mSelf.open();
        }
        return mSelf;
    }

    /**
     * Constructor
     * @param context context to be initialized with
     */
    private DbAdapter(Context context) {
        mContext = context;
    }

    /**
     * Opens a connection
     * @return database adapter
     */
    private DbAdapter open(){
        mDbHelper = new InnerDbHelper(mContext);
        mDb = mDbHelper.getWritableDatabase();
        isOpened = true;
        return this;
    }

    /**
     * Closes the current connection
     */
    public synchronized void close(){
        mDbHelper.close();
        isOpened = false;
    }

    /**
     * Adds a new entry to database with empty text by default
     * @param image image data
     */
    public synchronized long addEntry(byte[] image, byte[] thumb){
        return addEntry(image, thumb, "");
    }

    /**
     * Adds a new entry to database
     * @param image image data
     * @param thumb thumb data
     * @param text text data
     */
    public synchronized long addEntry(byte[] image, byte[] thumb, String text){
        ContentValues cv = new ContentValues();
        cv.put(DbConst.COLUMN_PICTURE, image);
        cv.put(DbConst.COLUMN_THUMBNAIL, thumb);
        cv.put(DbConst.COLUMN_TEXT, text);
        cv.put(DbConst.COLUMN_DATE, System.currentTimeMillis());
        return mDb.insert(DbConst.TABLE_NOTES, null, cv);
    }

    /**
     * Removes a single entity
     * @param entity entity to remove
     */
    public synchronized long removeEntry(NoteEntity entity){
        return mDb.delete(DbConst.TABLE_NOTES,
                String.format(DbConst.EQUALS_EXPRESSION, DbConst.COLUMN_ID),
                new String[]{Long.toString(entity.getId())});
    }

    /**
     * Remove collection of entities
     * @param entities collection of entities
     */
    public synchronized long removeEntries(Collection<NoteEntity> entities){
        StringBuilder ids = new StringBuilder("(");
        for(NoteEntity entity : entities){
            ids.append(entity.getId()).append(",");
        }
        ids.setLength(ids.length() - 1);
        ids.append(")");
        return mDb.delete(DbConst.TABLE_NOTES,
                String.format(DbConst.IN_EXPRESSION, DbConst.COLUMN_ID, ids.toString()), null);
    }

    /**
     * Updates current note text
     * @param entity note entity
     */
    public synchronized long updateEntryText(NoteEntity entity){
        ContentValues cv = new ContentValues();
        cv.put(DbConst.COLUMN_TEXT, entity.getText());
        return mDb.update(DbConst.TABLE_NOTES, cv,
                String.format(DbConst.EQUALS_EXPRESSION, DbConst.COLUMN_ID),
                new String[]{Long.toString(entity.getId())});
    }

    /**
     * Returns all data as list
     * It's a waste of resources to load all fields at once
     * so it's newer used but only in tests
     * @return list of note entities
     */
    public synchronized List<NoteEntity> getAllData(){
        Cursor cursor = getAllCursor();
        if(cursor == null){
            return new ArrayList<>(0);
        }
        List<NoteEntity> result = new ArrayList<>(cursor.getCount());
        if(cursor.getCount() == 0){
            return result;
        }
        do{
            result.add(extractEntityForNoteList(cursor));
        }while (cursor.moveToNext());
        return result;
    }

    /**
     * Return cursor with a complete set of data
     * It's a waste of resources to load all fields at once
     * so it's newer used but only in tests
     * @return cursor with data
     */
    public synchronized Cursor getAllCursor(){
        Cursor cursor = mDb.rawQuery(DbConst.Q_GET_ALL_DATA, null);
        if(cursor != null) {
            cursor.moveToFirst();
            return cursor;
        }
        return null;
    }

    /**
     * Returns cursor for viewing data in listview
     * @return cursor cursor with data
     */
    public synchronized Cursor getAllDataToShowInListCursor(){
        return mDb.query(
                false,
                DbConst.TABLE_NOTES,
                new String[]{
                        DbConst.COLUMN_ID, DbConst.COLUMN_THUMBNAIL,
                        DbConst.COLUMN_TEXT, DbConst.COLUMN_DATE},
                null, null, null, null, null, null);
    }

    /**
     * Filters data using message text as constraint
     * @param constraint message text
     * @return cursor with filtered data
     */
    public synchronized Cursor getFilteredData(String constraint){
        return mDb.query(
                false,
                DbConst.TABLE_NOTES,
                new String[]{
                        DbConst.COLUMN_ID, DbConst.COLUMN_THUMBNAIL,
                        DbConst.COLUMN_TEXT, DbConst.COLUMN_DATE},
                DbConst.COLUMN_TEXT + " LIKE ?",
                new String[]{"%" + constraint + "%"},
                null, null, null, null);
    }

    /**
     * Clears all data
     * @return query result
     */
    public synchronized long clearAll(){
        return mDb.delete(DbConst.TABLE_NOTES, null, null);
    }

    /**
     * Returns last entry to be edited.
     * Only id field is returned as it's assumed that image was already saved
     * on the previous step and now we are going to add a text note.
     * @return entry with only entry id loaded
     */
    public synchronized NoteEntity getLastEditedEntry(){
        Cursor cursor = mDb.rawQuery(DbConst.Q_SELECT_LAST_ENTRY, null);
        if(cursor == null || cursor.getCount() != 1){
            return null;
        }
        cursor.moveToFirst();
        return new NoteEntity(cursor.getInt(0));
    }

    /**
     * Extracts set of fields needed to make a detail view
     * @param id entity id
     * @return note entity with id, image and text fields filled
     */
    public synchronized NoteEntity getEntityToView(long id){
        Cursor cursor = mDb.rawQuery(DbConst.Q_SELECT_ENTRY_TO_VIEW + id, null);
        if(cursor == null || cursor.getCount() != 1){
            return null;
        }
        cursor.moveToFirst();
        NoteEntity result = new NoteEntity(id);
        result.setImage(cursor.getBlob(1));
        result.setText(cursor.getString(2));
        return result;
    }

    /**
     * Extracts set of fields to add item into listview
     * @param cursor cursor
     * @return note entity with id, thumb, text and date fields filled
     */
    public static NoteEntity extractEntityForNoteList(Cursor cursor) {
        Calendar calendar = Calendar.getInstance();
        if(cursor.getCount() > 0) {
            NoteEntity entity = new NoteEntity(cursor.getInt(0));
            entity.setThumb(cursor.getBlob(1));
            entity.setText(cursor.getString(2));
            calendar.setTimeInMillis(cursor.getLong(3));
            entity.setDate(calendar.getTime());
            return entity;
        }else{
            return null;
        }
    }
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Bulbophyllum schizopetalum L.O.Williams

### Remarks
null


text:
using namespace goetia::hashing;

int main() {
    std::string known_kmer = "TCACCTGTGTTGTGCTACTTGCGGCGC";
    uint64_t known_hash =  13194817695400542713;

    FwdRollingExtender from_k(27);
    FwdRollingExtender from_other(from_k);

    std::cout << "=== from k ===" << std::endl;
    std::cout << from_k.set_cursor(known_kmer) << std::endl << from_k.get() << std::endl;

    std::cout << "=== from other ===" << std::endl;
    std::cout << from_other.set_cursor(known_kmer) << std::endl << from_other.get() << std::endl;

    CanRollingExtender can_from_k(27);
    CanRollingExtender can_from_other(can_from_k);

    std::cout << "=== from k ===" << std::endl;
    std::cout << can_from_k.set_cursor(known_kmer) << std::endl << can_from_k.get() << std::endl;

    std::cout << "=== from other ===" << std::endl;
    std::cout << can_from_other.set_cursor(known_kmer) << std::endl << can_from_other.get() << std::endl;
}


text:
class AlertWorker
  include Sidekiq::Worker
  sidekiq_options retry: false

  def perform(user_id, disaster_id)
    user = User.find(user_id)
    disaster = Disaster.find(disaster_id)
    FirstaidMailer.alert_email(user, disaster).deliver_now
  end
end


text:
// API class

package org.yuimozilla.javascript;

/**
 * Class ImporterTopLevel
 *
 * This class defines a ScriptableObject that can be instantiated
 * as a top-level ("global") object to provide functionality similar
 * to Java's "import" statement.
 *

 * This class can be used to create a top-level scope using the following code:
 *

 *  Scriptable scope = new ImporterTopLevel(cx);
 *

 * Then JavaScript code will have access to the following methods:
 *

 *
importClass - will "import" a class by making its unqualified name
 *                   available as a property of the top-level scope
 *
importPackage - will "import" all the classes of the package by
 *                     searching for unqualified names as classes qualified
 *                     by the given package.
 *

 * The following code from the shell illustrates this use:
 *

 * js> importClass(java.io.File)
 * js> f = new File('help.txt')
 * help.txt
 * js> importPackage(java.util)
 * js> v = new Vector()
 * []
 *
 * @author Norris Boyd
 */
public class ImporterTopLevel extends IdScriptableObject
{
    static final long serialVersionUID = -9095380847465315412L;

    private static final Object IMPORTER_TAG = new Object();

    public ImporterTopLevel() { }

    public ImporterTopLevel(Context cx) {
        this(cx, false);
    }

    public ImporterTopLevel(Context cx, boolean sealed)
    {
        initStandardObjects(cx, sealed);
    }

    public String getClassName()
    {
        return (topScopeFlag) ? "global" : "JavaImporter";
    }

    public static void init(Context cx, Scriptable scope, boolean sealed)
    {
        ImporterTopLevel obj = new ImporterTopLevel();
        obj.exportAsJSClass(MAX_PROTOTYPE_ID, scope, sealed);
    }

    public void initStandardObjects(Context cx, boolean sealed)
    {
        // Assume that Context.initStandardObjects initialize JavaImporter
        // property lazily so the above init call is not yet called
        cx.initStandardObjects(this, sealed);
        topScopeFlag = true;
        // If seal is true then exportAsJSClass(cx, seal) would seal
        // this obj. Since this is scope as well, it would not allow
        // to add variables.
        IdFunctionObject ctor = exportAsJSClass(MAX_PROTOTYPE_ID, this, false);
        if (sealed) {
            ctor.sealObject();
        }
        // delete "constructor" defined by exportAsJSClass so "constructor"
        // name would refer to Object.constructor
        // and not to JavaImporter.prototype.constructor.
        delete("constructor");
    }

    public boolean has(String name, Scriptable start) {
        return super.has(name, start)
               || getPackageProperty(name, start) != NOT_FOUND;
    }

    public Object get(String name, Scriptable start) {
        Object result = super.get(name, start);
        if (result != NOT_FOUND)
            return result;
        result = getPackageProperty(name, start);
        return result;
    }

    private Object getPackageProperty(String name, Scriptable start) {
        Object result = NOT_FOUND;
        Object[] elements;
        synchronized (importedPackages) {
            elements = importedPackages.toArray();
        }
        for (int i=0; i < elements.length; i++) {
            NativeJavaPackage p = (NativeJavaPackage) elements[i];
            Object v = p.getPkgProperty(name, start, false);
            if (v != null && !(v instanceof NativeJavaPackage)) {
                if (result == NOT_FOUND) {
                    result = v;
                } else {
                    throw Context.reportRuntimeError2(
                        "msg.ambig.import", result.toString(), v.toString());
                }
            }
        }
        return result;
    }

    /**
     * @deprecated Kept only for compatibility.
     */
    public void importPackage(Context cx, Scriptable thisObj, Object[] args,
                              Function funObj)
    {
        js_importPackage(args);
    }

    private Object js_construct(Scriptable scope, Object[] args)
    {
        ImporterTopLevel result = new ImporterTopLevel();
        for (int i = 0; i != args.length; ++i) {
            Object arg = args[i];
            if (arg instanceof NativeJavaClass) {
                result.importClass((NativeJavaClass)arg);
            } else if (arg instanceof NativeJavaPackage) {
                result.importPackage((NativeJavaPackage)arg);
            } else {
                throw Context.reportRuntimeError1(
                    "msg.not.class.not.pkg", Context.toString(arg));
            }
        }
        // set explicitly prototype and scope
        // as otherwise in top scope mode BaseFunction.construct
        // would keep them set to null. It also allow to use
        // JavaImporter without new and still get properly
        // initialized object.
        result.setParentScope(scope);
        result.setPrototype(this);
        return result;
    }

    private Object js_importClass(Object[] args)
    {
        for (int i = 0; i != args.length; i++) {
            Object arg = args[i];
            if (!(arg instanceof NativeJavaClass)) {
                throw Context.reportRuntimeError1(
                    "msg.not.class", Context.toString(arg));
            }
            importClass((NativeJavaClass)arg);
        }
        return Undefined.instance;
    }

    private Object js_importPackage(Object[] args)
    {
        for (int i = 0; i != args.length; i++) {
            Object arg = args[i];
            if (!(arg instanceof NativeJavaPackage)) {
                throw Context.reportRuntimeError1(
                    "msg.not.pkg", Context.toString(arg));
            }
            importPackage((NativeJavaPackage)arg);
        }
        return Undefined.instance;
    }

    private void importPackage(NativeJavaPackage pkg)
    {
        if(pkg == null) {
            return;
        }
        synchronized (importedPackages) {
            for (int j = 0; j != importedPackages.size(); j++) {
                if (pkg.equals(importedPackages.get(j))) {
                    return;
                }
            }
            importedPackages.add(pkg);
        }
    }

    private void importClass(NativeJavaClass cl)
    {
        String s = cl.getClassObject().getName();
        String n = s.substring(s.lastIndexOf('.')+1);
        Object val = get(n, this);
        if (val != NOT_FOUND && val != cl) {
            throw Context.reportRuntimeError1("msg.prop.defined", n);
        }
        //defineProperty(n, cl, DONTENUM);
        put(n, this, cl);
    }

    protected void initPrototypeId(int id)
    {
        String s;
        int arity;
        switch (id) {
          case Id_constructor:   arity=0; s="constructor";   break;
          case Id_importClass:   arity=1; s="importClass";   break;
          case Id_importPackage: arity=1; s="importPackage"; break;
          default: throw new IllegalArgumentException(String.valueOf(id));
        }
        initPrototypeMethod(IMPORTER_TAG, id, s, arity);
    }

    public Object execIdCall(IdFunctionObject f, Context cx, Scriptable scope,
                             Scriptable thisObj, Object[] args)
    {
        if (!f.hasTag(IMPORTER_TAG)) {
            return super.execIdCall(f, cx, scope, thisObj, args);
        }
        int id = f.methodId();
        switch (id) {
          case Id_constructor:
            return js_construct(scope, args);

          case Id_importClass:
            return realThis(thisObj, f).js_importClass(args);

          case Id_importPackage:
            return realThis(thisObj, f).js_importPackage(args);
        }
        throw new IllegalArgumentException(String.valueOf(id));
    }

    private ImporterTopLevel realThis(Scriptable thisObj, IdFunctionObject f)
    {
        if (topScopeFlag) {
            // when used as top scope importPackage and importClass are global
            // function that ignore thisObj
            return this;
        }
        if (!(thisObj instanceof ImporterTopLevel))
            throw incompatibleCallError(f);
        return (ImporterTopLevel)thisObj;
    }

// #string_id_map#

    protected int findPrototypeId(String s)
    {
        int id;
// #generated# Last update: 2007-05-09 08:15:24 EDT
        L0: { id = 0; String X = null; int c;
            int s_length = s.length();
            if (s_length==11) {
                c=s.charAt(0);
                if (c=='c') { X="constructor";id=Id_constructor; }
                else if (c=='i') { X="importClass";id=Id_importClass; }
            }
            else if (s_length==13) { X="importPackage";id=Id_importPackage; }
            if (X!=null && X!=s && !X.equals(s)) id = 0;
            break L0;
        }
// #/generated#
        return id;
    }

    private static final int
        Id_constructor          = 1,
        Id_importClass          = 2,
        Id_importPackage        = 3,
        MAX_PROTOTYPE_ID        = 3;

// #/string_id_map#

    private ObjArray importedPackages = new ObjArray();
    private boolean topScopeFlag;
}


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>search_n</title>
<link rel="stylesheet" href="../../../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.75.2">
<link rel="home" href="../../../../index.html" title="Chapter 1. Range 2.0">
<link rel="up" href="../non_mutating.html" title="Non-mutating algorithms">
<link rel="prev" href="search.html" title="search">
<link rel="next" href="upper_bound.html" title="upper_bound">

Home
Libraries
People
FAQ
More

search_n

            Prototype

template<class ForwardRange, class Integer, class Value>
typename range_iterator<ForwardRange>::type
search_n(ForwardRange& rng, Integer n, const Value& value);

template<class ForwardRange, class Integer, class Value>
typename range_iterator<const ForwardRange>::type
search_n(const ForwardRange& rng, Integer n, const Value& value);

template<class ForwardRange, class Integer, class Value, class BinaryPredicate>
typename range_iterator<ForwardRange>::type
search_n(ForwardRange& rng, Integer n, const Value& value,
         BinaryPredicate binary_pred);

template<class ForwardRange, class Integer, class Value, class BinaryPredicate>
typename range_iterator<const ForwardRange>::type
search_n(const ForwardRange& rng, Integer n, const Value& value,
         BinaryPredicate binary_pred);

            Description

            search_n searches rng for a sequence of length n equal to value
            where equality is determined by operator== in the non-predicate case,
            and by a predicate when one is supplied.

            Definition

            Defined in the header file boost/range/algorithm/search_n.hpp

            Requirements

            For the non-predicate versions:

                ForwardRange is a
                model of the Forward
                Range Concept.

                ForwardRange's value
                type is a model of the EqualityComparableConcept.

                ForwardRanges value
                type can be compared for equality with Value.

                Integer is a model
                of the IntegerConcept.

            For the predicate versions:

                ForwardRange is a
                model of the Forward
                Range Concept.

                BinaryPredicate is
                a model of the BinaryPredicateConcept.

                ForwardRange's value
                type is convertible to BinaryPredicate's
                first argument type.

                Value is convertible
                to BinaryPredicate's
                second argument type.

                Integer is a model
                of the IntegerConcept.

            Complexity

            Average complexity is Linear. Worst-case complexity is quadratic.

Copyright © 2003-2010 Thorsten Ottosen,
      Neil Groves

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
namespace radio {

    class Line {

	public:
	    Line(const Vertex& start_, const Vertex& dir_)
		: start(start_), dir(dir_)
	    {}

	    static inline Line fromPoints(const Vertex& a, const Vertex& b) {
		return Line(b, b - a);
	    }

	    static inline Line fromPointsNormed(const Vertex& a, const Vertex& b) {
	        Line l(b, b - a);
	        l.normDir();
		return l;
	    }

	    inline void normDir(){
	        dir.norm();
	    }

	    inline float startX() const { return start.X(); }
	    inline float startY() const { return start.Y(); }
	    inline float startZ() const { return start.Z(); }

	    inline const Vertex& getStart() const { return start; }

	    inline float dirX() const { return dir.X(); }
	    inline float dirY() const { return dir.Y(); }
	    inline float dirZ() const { return dir.Z(); }

	    inline const Vertex getDir() const { return dir; }

	private:
	    Vertex start;
	    Vertex dir;

    };
}

#endif


text:
SELECT
	f.folder_id,
	f.name,
	project_id,
	p.folder_id,
	p.name,
	p.[description]
FROM
	[catalog].projects p
INNER JOIN
	[catalog].folders f ON p.folder_id = f.folder_id


text:
module.exports = {
  root: true,

  parserOptions: {
    ecmaVersion: '2021' // Allows for the parsing of modern ECMAScript features
  },

  env: {
    browser: true,
    'vue/setup-compiler-macros': true
  },

  extends: [
    // https://github.com/vuejs/eslint-plugin-vue#priority-a-essential-error-prevention
    // consider switching to `plugin:vue/strongly-recommended` or `plugin:vue/recommended` for stricter rules.
    'plugin:vue/vue3-essential',
    // https://github.com/standard/standard/blob/master/docs/RULES-en.md
    'standard'
  ],

  // required to lint *.vue files
  plugins: [
    'vue',
    'no-only-tests'
  ],

  globals: {
    cordova: 'readonly',
    __QUASAR_VERSION__: 'readonly',
    __QUASAR_SSR__: 'readonly',
    __QUASAR_SSR_SERVER__: 'readonly',
    __QUASAR_SSR_CLIENT__: 'readonly',
    __QUASAR_SSR_PWA__: 'readonly'
  },

  overrides: [
    {
      files: [ '**/*.spec.{js,ts}', 'test/cypress/**/*' ],
      extends: [
        // Add Cypress-specific lint rules, globals and Cypress plugin
        // See https://github.com/cypress-io/eslint-plugin-cypress#rules
        'plugin:cypress/recommended'
      ]
    }
  ],

  // add your custom rules here
  rules: {
    'brace-style': [ 2, 'stroustrup', { allowSingleLine: true } ],
    'prefer-const': 2,
    'prefer-promise-reject-errors': 'off',
    'multiline-ternary': 'off',
    'no-prototype-builtins': 'off',
    'no-case-declarations': 'off',
    'generator-star-spacing': 'off',
    'arrow-parens': 'off',
    'object-property-newline': 'off',
    'one-var': 'off',
    'no-void': 'off',
    'no-lone-blocks': 'error',
    'no-unused-expressions': 'error',
    'no-useless-concat': 'error',
    'no-useless-return': 'error',
    'no-unneeded-ternary': 'error',
    'no-confusing-arrow': [ 'error', { allowParens: true } ],
    'operator-linebreak': [ 'error', 'before' ],
    'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0,

    'array-bracket-spacing': [ 'error', 'always' ],
    'object-curly-spacing': [ 'error', 'always' ],
    'computed-property-spacing': [ 'error', 'always' ],
    'template-curly-spacing': [ 'error', 'always' ],

    'import/first': 0,
    'import/named': 2,
    'import/namespace': 2,
    'import/default': 2,
    'import/export': 2,
    'import/extensions': 0,
    'import/no-unresolved': 0,
    'import/no-extraneous-dependencies': 'off',

    'vue/max-attributes-per-line': 'off',
    'vue/valid-v-for': 'off',
    'vue/require-default-prop': 'off',
    'vue/require-prop-types': 'off',
    'vue/require-v-for-key': 'off',
    'vue/return-in-computed-property': 'off',
    'vue/require-render-return': 'off',
    'vue/singleline-html-element-content-newline': 'off',
    'vue/no-side-effects-in-computed-properties': 'off',
    'vue/array-bracket-spacing': 'off',
    'vue/object-curly-spacing': 'off',
    'vue/script-indent': 'off',
    'vue/no-v-model-argument': 'off',
    'vue/require-explicit-emits': 'off',
    'vue/multi-word-component-names': 'off',

    // Testing
    'cypress/no-unnecessary-waiting': 'off',
    'no-only-tests/no-only-tests': 'error'
  }
}


text:
/**
 * Products module actions
 */

var productsActionCreators = {};
var Dispatcher = require('rlux').Dispatcher;
var constants = require('../constants');
var service = require('../services');

productsActionCreators.loadProducts = function () {
  service.loadProducts().then(function (products) {
    Dispatcher.handleServerAction({
      type: constants.actions.productsLoaded,
      products: products.response
    });
  },function (reason) {
    Dispatcher.handleErrorAction({
      type: constants.actions.productLoadingFailed,
      reason: reason
    });
  });
};

module.exports = productsActionCreators;


text:
require 'singleton'

module Sycamore

  ##
  # The Nothing Tree singleton class.
  #
  # The Nothing Tree is an empty Sycamore Tree, and means "there are no nodes".
  #
  # It is immutable:
  # - {Tree::QUERY_METHODS Query method} calls will behave like a normal, empty Tree.
  # - {Tree::DESTRUCTIVE_COMMAND_METHODS Pure destructive command} calls, will be ignored, i.e. being no-ops.
  # - But all other {Tree::COMMAND_METHODS command} calls, will raise a {NothingMutation}.
  #
  # It is the only Tree object that will return +true+ on a {#nothing?} call.
  # But like {Absence}, it will return +true+ on {#absent?} and +false+ on {#existent?}.
  #
  class NothingTree < Tree
    include Singleton

    ########################################################################
    # Absence and Nothing predicates
    ########################################################################

    ##
    # (see Tree#nothing?)
    #
    def nothing?
      true
    end

    ##
    # (see Tree#absent?)
    #
    def absent?
      true
    end

    ########################################################################
    # CQS element access
    ########################################################################

    # TODO: YARD should be informed about this method definitions.
    command_methods.each do |command_method|
      define_method command_method do |*args|
        raise NothingMutation, 'attempt to change the Nothing tree'
      end
    end

    # TODO: YARD should be informed about this method definitions.
    pure_destructive_command_methods.each do |command_method|
      define_method(command_method) { |*args| self }
    end

    def child_of(node)
      self
    end

    def to_native_object(sleaf_child_as: nil, **args)
      sleaf_child_as
    end

    ##
    # A string representation of the Nothing tree.
    #
    # @return [String]
    #
    def to_s
      'Tree[Nothing]'
    end

    ##
    # A developer-friendly string representation of the Nothing tree.
    #
    # @return [String]
    #
    def inspect
      '#<Sycamore::Nothing>'
    end

    def freeze
      super
    end

    ########################################################################
    # Equality
    ########################################################################

    ##
    # Checks if the given object is an empty tree.
    #
    # @return [Boolean]
    #
    def ==(other)
      (other.is_a?(Tree) or other.is_a?(Absence)) and other.empty?
    end

    ########################################################################
    # Falsiness
    #
    # Sadly, in Ruby we can't do that match to reach this goal.
    #
    # see http://devblog.avdi.org/2011/05/30/null-objects-and-falsiness/
    ########################################################################

    ##
    # Try to emulate a falsey value, by negating to +true+.
    #
    # @return [Boolean] +true+
    #
    # @see http://devblog.avdi.org/2011/05/30/null-objects-and-falsiness/
    #
    def !
      true
    end

    # def nil?
    #   true
    # end

    ########################################################################
    # Some helpers
    #
    # Ideally these would be implemented with Refinements, but since they
    # aren't available anywhere (I'm looking at you, JRuby), we have to be
    # content with this.
    #
    ########################################################################

    def like?(object)
      object.nil? or object.equal? self
    end

    ##
    # @api private
    class NestedStringPresentation
      include Singleton

      def inspect
        'n/a'
      end
    end

    ##
    # @api private
    NestedString = NestedStringPresentation.instance.freeze

  end

  ############################################################################
  # The Nothing Tree Singleton object
  #
  Nothing = NothingTree.instance.freeze

end


text:
package powercrystals.minefactoryreloaded.api;

/**
 * @author PowerCrystals
 *
 * Determines what kind of action a given fertilizer can perform. Your IFactoryFertilizable instances should check this before
 * performing any action to maintain future compatibility.
 */
public enum FertilizerType
{
	/**
	 * The fertilizer will fertilize nothing.
	 */
	None,
	/**
	 * The fertilizer will fertilize grass.
	 */
	Grass,
	/**
	 * The fertilizer will grow a plant.
	 */
	GrowPlant,
	/**
	 * The fertilizer will grow magical crops.
	 */
	GrowMagicalCrop,
}


text:
package com.google.api.ads.adwords.jaxws.v201409.cm;

import java.util.List;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.ws.RequestWrapper;
import javax.xml.ws.ResponseWrapper;

/**
 *
 *       Use this service to manage media for your ads. For example:
 *

 *
Upload new images for location
 *       extensions.

 *
Get the IDs of videos you want to use in
 *       {@linkplain TemplateAd template ads}.

 *

 *
 *
 * This class was generated by the JAX-WS RI.
 * JAX-WS RI 2.2.4-b01
 * Generated source version: 2.1
 *
 */
@WebService(name = "MediaServiceInterface", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201409")
@XmlSeeAlso({
    ObjectFactory.class
})
public interface MediaServiceInterface {

    /**
     *
     *         Returns a list of media that meet the criteria specified by the selector.
     *
Note: {@code MediaService} will not return any
     *         {@link ImageAd} image files.

     *
     *         @param serviceSelector Selects which media objects to return.
     *         @return A list of {@code Media} objects.
     *
     *
     * @param serviceSelector
     * @return
     *     returns com.google.api.ads.adwords.jaxws.v201409.cm.MediaPage
     * @throws ApiException_Exception
     */
    @WebMethod
    @WebResult(name = "rval", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201409")
    @RequestWrapper(localName = "get", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201409", className = "com.google.api.ads.adwords.jaxws.v201409.cm.MediaServiceInterfaceget")
    @ResponseWrapper(localName = "getResponse", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201409", className = "com.google.api.ads.adwords.jaxws.v201409.cm.MediaServiceInterfacegetResponse")
    public MediaPage get(
        @WebParam(name = "serviceSelector", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201409")
        Selector serviceSelector)
        throws ApiException_Exception
    ;

    /**
     *
     *         Returns the list of {@link Media} objects that match the query.
     *
     *         @param query The SQL-like AWQL query string
     *         @returns A list of {@code Media} objects.
     *         @throws ApiException when the query is invalid or there are errors processing the request.
     *
     *
     * @param query
     * @return
     *     returns com.google.api.ads.adwords.jaxws.v201409.cm.MediaPage
     * @throws ApiException_Exception
     */
    @WebMethod
    @WebResult(name = "rval", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201409")
    @RequestWrapper(localName = "query", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201409", className = "com.google.api.ads.adwords.jaxws.v201409.cm.MediaServiceInterfacequery")
    @ResponseWrapper(localName = "queryResponse", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201409", className = "com.google.api.ads.adwords.jaxws.v201409.cm.MediaServiceInterfacequeryResponse")
    public MediaPage query(
        @WebParam(name = "query", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201409")
        String query)
        throws ApiException_Exception
    ;

    /**
     *
     *         Uploads new media. Currently, you can only upload {@link Image} files.
     *
     *         @param media A list of {@code Media} objects, each containing the data to
     *         be uploaded.
     *         @return A list of uploaded media in the same order as the argument list.
     *
     *
     * @param media
     * @return
     *     returns java.util.List<com.google.api.ads.adwords.jaxws.v201409.cm.Media>
     * @throws ApiException_Exception
     */
    @WebMethod
    @WebResult(name = "rval", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201409")
    @RequestWrapper(localName = "upload", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201409", className = "com.google.api.ads.adwords.jaxws.v201409.cm.MediaServiceInterfaceupload")
    @ResponseWrapper(localName = "uploadResponse", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201409", className = "com.google.api.ads.adwords.jaxws.v201409.cm.MediaServiceInterfaceuploadResponse")
    public List<Media> upload(
        @WebParam(name = "media", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201409")
        List<Media> media)
        throws ApiException_Exception
    ;

}


text:
package google

import (
	"time"

	"google.golang.org/api/dns/v1"

	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
)

type DnsChangeWaiter struct {
	Service     *dns.Service
	Change      *dns.Change
	Project     string
	ManagedZone string
}

func (w *DnsChangeWaiter) RefreshFunc() resource.StateRefreshFunc {
	return func() (interface{}, string, error) {
		var chg *dns.Change
		var err error

		chg, err = w.Service.Changes.Get(
			w.Project, w.ManagedZone, w.Change.Id).Do()

		if err != nil {
			return nil, "", err
		}

		return chg, chg.Status, nil
	}
}

func (w *DnsChangeWaiter) Conf() *resource.StateChangeConf {
	return &resource.StateChangeConf{
		Pending:    []string{"pending"},
		Target:     []string{"done"},
		Refresh:    w.RefreshFunc(),
		Timeout:    10 * time.Minute,
		MinTimeout: 2 * time.Second,
	}
}


text:
package org.apache.axis2.builder.unknowncontent;

import java.io.InputStream;

import javax.activation.DataHandler;

import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.impl.llom.OMSourcedElementImpl;
import org.apache.axis2.AxisFault;
import org.apache.axis2.builder.Builder;
import org.apache.axis2.context.MessageContext;

public class UnknownContentBuilder implements Builder {

	public OMElement processDocument(InputStream inputStream,
			String contentType, MessageContext messageContext) throws AxisFault {

		// using this to figure out whether the received is a MIME message
		if (messageContext.isDoingSwA()) {
			String rootPartContentID = messageContext.attachments
					.getSOAPPartContentID();
			DataHandler rootPartDataHandler = messageContext.attachments
					.getDataHandler(rootPartContentID);
			UnknownContentOMDataSource unknownContentDataSource = new UnknownContentOMDataSource(
					rootPartDataHandler);
			OMFactory factory = OMAbstractFactory.getOMFactory();
			messageContext.setDoingSwA(false);
			messageContext.setDoingMTOM(false);
			return new OMSourcedElementImpl(
					UnknownContentOMDataSource.unknownContentQName, factory,
					unknownContentDataSource);
		}
		InputStreamDataSource inStreamDataSource = new InputStreamDataSource(
				inputStream);
		inStreamDataSource.setType(contentType);
		DataHandler dataHandler = new DataHandler(inStreamDataSource);
		UnknownContentOMDataSource unknownContentDataSource = new UnknownContentOMDataSource(
				dataHandler);
		OMFactory factory = OMAbstractFactory.getOMFactory();
		return new OMSourcedElementImpl(
				UnknownContentOMDataSource.unknownContentQName, factory,
				unknownContentDataSource);
	}
}


text:
package com.javarush.task.task23.task2309.vo;

/**
 * Created by Sukora Stas.
 */
public class Server extends NamedItem {
}


text:
package io.quarkus.resteasy.test.security;

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.concurrent.atomic.AtomicInteger;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

import org.hamcrest.Matchers;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

import io.quarkus.security.AuthenticationFailedException;
import io.quarkus.security.test.utils.TestIdentityController;
import io.quarkus.security.test.utils.TestIdentityProvider;
import io.quarkus.test.QuarkusUnitTest;
import io.restassured.RestAssured;

public class HttpPolicyAuthFailureExceptionMapperTest {

    private static final String EXPECTED_RESPONSE = "expect response";

    /**
     * Number of times exception mappers was invoked.
     */
    private static final AtomicInteger EXCEPTION_MAPPER_INVOCATION_COUNT = new AtomicInteger(0);

    @RegisterExtension
    static QuarkusUnitTest runner = new QuarkusUnitTest()
            .withApplicationRoot((jar) -> jar
                    .addClasses(TestIdentityProvider.class, TestIdentityController.class)
                    .addAsResource(
                            new StringAsset("quarkus.http.auth.proactive=false\n" +
                                    "quarkus.http.auth.permission.basic.paths=/*\n" +
                                    "quarkus.http.auth.permission.basic.policy=authenticated\n"),
                            "application.properties"));

    @BeforeAll
    public static void setupUsers() {
        TestIdentityController.resetRoles()
                .add("user", "user", "user");
    }

    @Test
    public void testAuthFailedExceptionMapper() {
        RestAssured
                .given()
                .auth().basic("user", "unknown-pwd")
                .get("/")
                .then()
                .statusCode(401)
                .body(Matchers.equalTo(EXPECTED_RESPONSE));

        assertEquals(1, EXCEPTION_MAPPER_INVOCATION_COUNT.get(),
                "Exception mapper was invoked more than once during one request.");
    }

    @Provider
    public static class AuthFailedExceptionMapper implements ExceptionMapper<AuthenticationFailedException> {

        @Override
        public Response toResponse(AuthenticationFailedException exception) {
            EXCEPTION_MAPPER_INVOCATION_COUNT.incrementAndGet();
            return Response.status(401).entity(EXPECTED_RESPONSE).build();
        }
    }

    @Path("hello")
    public static final class HelloResource {

        @GET
        public String hello() {
            return "hello world";
        }
    }

}


text:
<?php

namespace Magento\Framework\Data\Argument\Interpreter;

use Magento\Framework\Data\Argument\InterpreterInterface;
use Magento\Framework\Stdlib\BooleanUtils;

/**
 * Interpreter of string data type that may optionally perform text translation
 */
class StringUtils implements InterpreterInterface
{
    /**
     * @var BooleanUtils
     */
    private $booleanUtils;

    /**
     * @param BooleanUtils $booleanUtils
     */
    public function __construct(BooleanUtils $booleanUtils)
    {
        $this->booleanUtils = $booleanUtils;
    }

    /**
     * {@inheritdoc}
     * @return string
     * @throws \InvalidArgumentException
     */
    public function evaluate(array $data)
    {
        if (isset($data['value'])) {
            $result = $data['value'];
            if (!is_string($result)) {
                throw new \InvalidArgumentException('String value is expected.');
            }
            $needTranslation = isset($data['translate']) ? $this->booleanUtils->toBoolean($data['translate']) : false;
            if ($needTranslation) {
                $result = (string)new \Magento\Framework\Phrase($result);
            }
        } else {
            $result = '';
        }
        return $result;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<parent>
		<artifactId>tiny-retry</artifactId>
		<groupId>com.github.tinyretry</groupId>
		<version>1.0-SNAPSHOT</version>
	</parent>
	<modelVersion>4.0.0</modelVersion>

	<artifactId>tinyretry-client</artifactId>

	<properties>
		<project.build.sourceEncoding>GBK</project.build.sourceEncoding>
		<log4j.version>2.1</log4j.version>
	</properties>

	<dependencies>

		<dependency>
			<groupId>com.github.commons</groupId>
			<artifactId>common-utils</artifactId>
			<version>1.0-SNAPSHOT</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>4.1.5.RELEASE</version>
		</dependency>

		<!-- common tools -->
		<dependency>
			<groupId>commons-lang</groupId>
			<artifactId>commons-lang</artifactId>
			<version>2.6</version>
		</dependency>
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.4</version>
		</dependency>
		<dependency>
			<groupId>opensymphony</groupId>
			<artifactId>quartz-all</artifactId>
			<version>1.6.3</version>
		</dependency>
		<dependency>
			<groupId>commons-beanutils</groupId>
			<artifactId>commons-beanutils</artifactId>
			<version>1.9.2</version>
		</dependency>
		<dependency>
			<groupId>commons-collections</groupId>
			<artifactId>commons-collections</artifactId>
			<version>3.2.1</version>
		</dependency>
		<!--for log -->
		<!-- log -->
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-api</artifactId>
			<version>${log4j.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-core</artifactId>
			<version>${log4j.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-slf4j-impl</artifactId>
			<version>${log4j.version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>1.7.10</version>
		</dependency>

		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.8.2</version>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.hamcrest</groupId>
					<artifactId>hamcrest-core</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.hamcrest</groupId>
			<artifactId>hamcrest-core</artifactId>
			<version>1.3.RC2</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.hamcrest</groupId>
			<artifactId>hamcrest-library</artifactId>
			<version>1.3.RC2</version>
			<scope>test</scope>
		</dependency>

	</dependencies>

	<build>

		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<encoding>GBK</encoding>
				</configuration>
			</plugin>
			<plugin>
                <artifactId>maven-source-plugin</artifactId>
                <version>2.1</version>
                <configuration>
                    <attach>true</attach>
                </configuration>
                <executions>
                    <execution>
                        <phase>compile</phase>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
		</plugins>

	</build>
</project>


text:
/**
 *
 */
package com.gupta.saransh.services;
import java.io.IOException;
import java.util.ArrayList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gupta.saransh.dal.SearchResponseDao;
import com.gupta.saransh.models.SearchResponse;
import com.gupta.saransh.models.SearchResponseWrapper;
import com.gupta.saransh.web.controllers.HomeController;
/**
 * Service class to query the AngelList API
 * @author Saransh
 *
 */
@Service
public class SearchAngelList {
	@Autowired
	RestTemplate restTemplate;

	@Autowired
	SearchResponseDao searchResponseDao;
	SearchResponseWrapper searchResponseWrapper = new SearchResponseWrapper();
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

	public void setSearchResponseDao(SearchResponseDao searchResponseDao) {
		this.searchResponseDao = searchResponseDao;
	}

	public SearchResponseWrapper searchUsers(String query,String type) throws JsonParseException, IOException{

		String url = 	"https://api.angel.co/1/search?query={query}&type={type}";
		ArrayList<SearchResponse> searchResponseList = new ArrayList<SearchResponse>();
		ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class,query,type);
		ObjectMapper mapper = new ObjectMapper();
		JsonFactory jsonFactory  = new JsonFactory();
		JsonParser jsonParser = jsonFactory.createParser(responseEntity.getBody());		jsonParser.nextToken();
		while(jsonParser.nextToken() == JsonToken.START_OBJECT){
			searchResponseList.add(mapper.readValues(jsonParser, SearchResponse.class).next());
		}
		searchResponseWrapper.setSearchResponseList(searchResponseList);
		searchResponseDao.saveToDB(searchResponseWrapper);
		logger.info(searchResponseDao.getUserList().toString());
		return searchResponseWrapper;
	}
}


text:
/**
 * Add custom settings to Jasmine.
 */

/*globals jasmine*/

jasmine.VERBOSE = true;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 15000;


text:
package org.multibit.viewsystem.swing.action;

import com.google.dogecoin.store.BlockStore;
import com.google.dogecoin.store.BlockStoreException;
import org.multibit.ApplicationInstanceManager;
import org.multibit.controller.Controller;
import org.multibit.controller.bitcoin.BitcoinController;
import org.multibit.controller.core.CoreController;
import org.multibit.file.BackupManager;
import org.multibit.file.FileHandler;
import org.multibit.file.WalletSaveException;
import org.multibit.message.Message;
import org.multibit.message.MessageManager;
import org.multibit.model.bitcoin.WalletData;
import org.multibit.model.core.CoreModel;
import org.multibit.store.WalletVersionException;
import org.multibit.viewsystem.swing.HealthCheckTimerTask;
import org.multibit.viewsystem.swing.MultiBitFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.List;

/**
 * Exit the application.
 */
public class ExitAction extends AbstractExitAction {

    private static final long serialVersionUID = 8784284740245520863L;

    private static final int MAXIMUM_TIME_TO_WAIT_FOR_HEALTH_CHECK_TASK = 10000; // ms
    private static final int TIME_TO_WAIT = 200; // ms

    private final MultiBitFrame mainFrame;
    private static final Logger log = LoggerFactory.getLogger(ExitAction.class);

    private CoreController coreController = null;
    private BitcoinController bitcoinController = null;

    /**
     * Creates a new {@link ExitAction}.
     */
    public ExitAction(Controller controller, MultiBitFrame mainFrame) {
        super(controller);
        this.mainFrame = mainFrame;
    }

    public void setCoreController(CoreController coreController) {
        if (null == coreController) {
            this.coreController = coreController;
        }
    }

    public void setBitcoinController(BitcoinController bitcoinController) {
        if (null == this.bitcoinController) {
            this.bitcoinController = bitcoinController;
        }
    }

    @Override
    public void actionPerformed(ActionEvent arg0) {
        String shuttingDownTitle = bitcoinController.getLocaliser().getString("multiBitFrame.title.shuttingDown");

        if (mainFrame != null) {
            mainFrame.setTitle(shuttingDownTitle);

            if (EventQueue.isDispatchThread()) {
                mainFrame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
            } else {
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        mainFrame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
                    }
                });
            }

            // If the HealthCheckTimerTask is running wait until it completes.
            HealthCheckTimerTask healthCheckTimerTask = mainFrame.getHealthCheckTimerTask();
            if (healthCheckTimerTask != null) {
                boolean breakout = false;
                int timeWaited = 0;

                while(healthCheckTimerTask.isRunning() && !breakout && timeWaited < MAXIMUM_TIME_TO_WAIT_FOR_HEALTH_CHECK_TASK) {
                    try {
                        log.debug("Waiting for healthCheckTimerTask to complete (waited so far = " + timeWaited + "). . .");
                        Thread.sleep(TIME_TO_WAIT);
                        timeWaited = timeWaited + TIME_TO_WAIT;
                    } catch (InterruptedException e) {
                        breakout = true;
                        e.printStackTrace();
                    }
                }
            }
        }

        if (bitcoinController != null && bitcoinController.getMultiBitService() != null) {
            // Stop the peer group so that blocks are notified to wallets correctly.
            if (bitcoinController.getMultiBitService().getPeerGroup() != null) {
                log.debug("Closing Bitcoin network connection...");
                bitcoinController.getMultiBitService().getPeerGroup().stopAndWait();
                log.debug("PeerGroup is now stopped.");
            }

            // Close down the blockstore.
            BlockStore blockStore = bitcoinController.getMultiBitService().getBlockStore();
            if (blockStore != null) {
                try {
                    log.debug("Closing blockStore. . .");
                    blockStore.close();
                    blockStore = null;
                    log.debug("BlockStore closed successfully.");
                } catch (NullPointerException npe) {
                    log.error("NullPointerException on blockstore close");
                } catch (BlockStoreException e) {
                    log.error("BlockStoreException on blockstore close. Message was '" + e.getMessage() + "'");
                }
            }
        }

        if (bitcoinController != null && mainFrame != null) {
            // Save the current window state so we can restore it on next start
            bitcoinController.getModel().setUserPreference(CoreModel.PREVIOUS_WINDOW_SIZE_H, String.valueOf(mainFrame.getHeight()));
            bitcoinController.getModel().setUserPreference(CoreModel.PREVIOUS_WINDOW_SIZE_W, String.valueOf(mainFrame.getWidth()));
            bitcoinController.getModel().setUserPreference(CoreModel.PREVIOUS_WINDOW_POS_X, String.valueOf(mainFrame.getX()));
            bitcoinController.getModel().setUserPreference(CoreModel.PREVIOUS_WINDOW_POS_Y, String.valueOf(mainFrame.getY()));
            bitcoinController.getModel().setUserPreference(CoreModel.PREVIOUS_WINDOW_MAX, String.valueOf(mainFrame.getExtendedState()));
            bitcoinController.getModel().setUserPreference(CoreModel.PREVIOUS_WINDOW_TRAY, String.valueOf(mainFrame.isInTray()));
        }

        if (bitcoinController != null) {
            // Save all the wallets and put their filenames in the user preferences.
            List<WalletData> perWalletModelDataList = bitcoinController.getModel().getPerWalletModelDataList();
            if (perWalletModelDataList != null) {
                for (WalletData loopPerWalletModelData : perWalletModelDataList) {
                    try {
                        String titleText = shuttingDownTitle;
                        if (mainFrame != null) {
                            if (loopPerWalletModelData != null) {
                                titleText = bitcoinController.getLocaliser().getString("multiBitFrame.title.saving",
                                        new String[] { loopPerWalletModelData.getWalletDescription() });
                            }
                            if (EventQueue.isDispatchThread()) {
                                mainFrame.setTitle(titleText);
                            } else {
                                final String finalTitleText = titleText;
                                SwingUtilities.invokeLater(new Runnable() {
                                    @Override
                                    public void run() {
                                        mainFrame.setTitle(finalTitleText);
                                    }
                                });
                            }
                        }
                        bitcoinController.getFileHandler().savePerWalletModelData(loopPerWalletModelData, false);
                    } catch (WalletSaveException wse) {
                        log.error(wse.getClass().getCanonicalName() + " " + wse.getMessage());
                        MessageManager.INSTANCE.addMessage(new Message(wse.getClass().getCanonicalName() + " " + wse.getMessage()));

                        // Save to backup.
                        try {
                            BackupManager.INSTANCE.backupPerWalletModelData(bitcoinController.getFileHandler(), loopPerWalletModelData);
                        } catch (WalletSaveException wse2) {
                            log.error(wse2.getClass().getCanonicalName() + " " + wse2.getMessage());
                            MessageManager.INSTANCE.addMessage(new Message(wse2.getClass().getCanonicalName() + " "
                                    + wse2.getMessage()));
                        }
                    } catch (WalletVersionException wve) {
                        log.error(wve.getClass().getCanonicalName() + " " + wve.getMessage());
                        MessageManager.INSTANCE.addMessage(new Message(wve.getClass().getCanonicalName() + " " + wve.getMessage()));
                    }
                }
            }

            // Write the user properties.
            log.debug("Saving user preferences ...");
            FileHandler.writeUserPreferences(bitcoinController);
        }

        log.debug("Shutting down Bitcoin URI checker ...");
        ApplicationInstanceManager.shutdownSocket();

        // Get rid of main display.
        if (mainFrame != null) {
            mainFrame.setVisible(false);
        }

        if (mainFrame != null) {
            mainFrame.dispose();
        }

        System.exit(0);
    }
}


text:
/*
Create a function that:
*   **Takes** a collection of books
    *   Each book has propeties `title` and `author`
        **  `author` is an object that has properties `firstName` and `lastName`
*   **finds** the most popular author (the author with biggest number of books)
*   **prints** the author to the console
*   **Use underscore.js for all operations**
*/

function solve(){
  return function (students) {
  };
}

module.exports = solve;


text:
..  Titling
    ##++::==~~--''``

User Story: JASMIN Analysis Package
===================================

As a scientist working for STFC I want my analytics processes to run where
they have access to JASMIN storage so I can apply my models to a particular
dataset.

Elaboration
~~~~~~~~~~~

* Predefined vCloud template contains standard JASMIN analysis package
* Ability to measure readiness of a node
* Ability to configure node with software, process configuration
* Alerting on conditions (ready, finished, error)

Tasks
~~~~~

* `Discoverable permissions`_
* Multiple authorization protocols
* Cross-domain identity mapping
* Hands-on JASMIN AP
* Hands-on example analytics code
* Explore deploy code
* Explore data access
* Explore process control and events
* Identify indicators

.. _discoverable permissions: http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/urldispatch.html#using-pyramid-security-with-url-dispatch


text:
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using MS.Core;

namespace System.Threading
{
    public static class __CompressedStack
    {
        public static IObservable<System.Threading.CompressedStack> Capture()
        {
            return ObservableExt.Factory(() => System.Threading.CompressedStack.Capture());
        }

        public static IObservable<System.Reactive.Unit> Run(
            IObservable<System.Threading.CompressedStack> compressedStack,
            IObservable<System.Threading.ContextCallback> callback, IObservable<System.Object> state)
        {
            return ObservableExt.ZipExecute(compressedStack, callback, state,
                (compressedStackLambda, callbackLambda, stateLambda) =>
                    System.Threading.CompressedStack.Run(compressedStackLambda, callbackLambda, stateLambda));
        }

        public static IObservable<System.Reactive.Unit> GetObjectData(
            this IObservable<System.Threading.CompressedStack> CompressedStackValue,
            IObservable<System.Runtime.Serialization.SerializationInfo> info,
            IObservable<System.Runtime.Serialization.StreamingContext> context)
        {
            return ObservableExt.ZipExecute(CompressedStackValue, info, context,
                (CompressedStackValueLambda, infoLambda, contextLambda) =>
                    CompressedStackValueLambda.GetObjectData(infoLambda, contextLambda));
        }

        public static IObservable<System.Threading.CompressedStack> GetCompressedStack()
        {
            return ObservableExt.Factory(() => System.Threading.CompressedStack.GetCompressedStack());
        }

        public static IObservable<System.Threading.CompressedStack> CreateCopy(
            this IObservable<System.Threading.CompressedStack> CompressedStackValue)
        {
            return Observable.Select(CompressedStackValue,
                (CompressedStackValueLambda) => CompressedStackValueLambda.CreateCopy());
        }
    }
}


text:
require 'offsite_payments/action_view_helper'
ActionView::Base.send(:include, OffsitePayments::ActionViewHelper)


text:
<?php

include "PGraphException.php";

/**
 * Exception thrown if a vertex doesn't exist.
 *
 * @category  PGraphNoVertexException
 * @package   PGraph
 * @author    Vilius Zaikauskas <zaikaus1@gmail.com>
 * @copyright 2013 Vilius Zaikauskas
 * @license   http://vzaikauskas.com/licenses/MIT.txt MIT
 * @version   Release: @package_version@
 * @link      http://pear.php.net/package/PGraph
 * @since     Class available since Release 1.0
 */
class PGraphNoVertexException extends PGraphException
{

    /**
     * Constructor to create the NoVertexException.
     *
     * @param mixed $args The arguments to be embedded into
     *                    the Exception message.
     */
    public function __construct($args)
    {
        parent::__construct($args, self::NO_VERTEX);
    }

}

/**
 * Exception thrown if an edge between
 * certain vertices doesn't exist.
 *
 * @category  PGraphNoEdgeException
 * @package   PGraph
 * @author    Vilius Zaikauskas <zaikaus1@gmail.com>
 * @copyright 2013 Vilius Zaikauskas
 * @license   http://vzaikauskas.com/licenses/MIT.txt MIT
 * @version   Release: @package_version@
 * @link      http://pear.php.net/package/PGraph
 * @since     Class available since Release 1.0
 */
class PGraphNoEdgeException extends PGraphException
{

    /**
     * Constructor to create the NoEdgeException.
     *
     * @param mixed $args The arguments to be embedded into
     *                    the Exception message.
     */
    public function __construct($args)
    {
        parent::__construct($args, self::NO_EDGE);
    }

}

/**
 * Exception thrown if an edge between two vertices
 * exists.
 *
 * @category  PGraphEdgeExistsException
 * @package   PGraph
 * @author    Vilius Zaikauskas <zaikaus1@gmail.com>
 * @copyright 2013 Vilius Zaikauskas
 * @license   http://vzaikauskas.com/licenses/MIT.txt MIT
 * @version   Release: @package_version@
 * @link      http://pear.php.net/package/PGraph
 * @since     Class available since Release 1.0
 */
class PGraphEdgeExistsException extends PGraphException
{

    /**
     * Constructor to create the EdgeExistsException.
     *
     * @param mixed $args The arguments to be embedded into
     *                    the Exception message.
     */
    public function __construct($args)
    {
        parent::__construct($args, self::EDGE_EXISTS);
    }

}

/**
 * Exception thrown if a vertex exists.
 *
 * @category  PGraphVertexExistsException
 * @package   PGraph
 * @author    Vilius Zaikauskas <zaikaus1@gmail.com>
 * @copyright 2013 Vilius Zaikauskas
 * @license   http://vzaikauskas.com/licenses/MIT.txt MIT
 * @version   Release: @package_version@
 * @link      http://pear.php.net/package/PGraph
 * @since     Class available since Release 1.0
 */
class PGraphVertexExistsException extends PGraphException
{
    /**
     * Constructor to create the VertexExistsException.
     *
     * @param mixed $args The arguments to be embedded into
     *                    the Exception message.
     */
    public function __construct($args)
    {
        parent::__construct($args, self::VERTEX_EXISTS);
    }
}

/**
 * Exception thrown if there is no path
 * betwee two vertices.
 *
 * @category  PGraphNoPathException
 * @package   PGraph
 * @author    Vilius Zaikauskas <zaikaus1@gmail.com>
 * @copyright 2013 Vilius Zaikauskas
 * @license   http://vzaikauskas.com/licenses/MIT.txt MIT
 * @version   Release: @package_version@
 * @link      http://pear.php.net/package/PGraph
 * @since     Class available since Release 1.0
 */
class PGraphNoPathException extends PGraphException
{

    /**
     * Constructor to create the NoPathException.
     *
     * @param mixed $args The arguments to be embedded into
     *                    the Exception message.
     */
    public function __construct($args)
    {
        parent::__construct($args, self::NO_PATH);
    }
}

/**
 * Exception thrown if the parameter passed has an invalid
 * type.
 *
 * @category  PGraphInvalidTypeException
 * @package   PGraph
 * @author    Vilius Zaikauskas <zaikaus1@gmail.com>
 * @copyright 2013 Vilius Zaikauskas
 * @license   http://vzaikauskas.com/licenses/MIT.txt MIT
 * @version   Release: @package_version@
 * @link      http://pear.php.net/package/PGraph
 * @since     Class available since Release 1.0
 */
class PGraphInvalidTypeException extends PGraphException
{
    /**
     * Constructor to create the InvalidTypeException.
     */
    public function __construct()
    {
        $emptyArr = array();
        parent::__construct($emptyArr, self::BAD_TYPE);
    }
}

/**
 * Exception thrown if a graph contains a negative cycle.
 *
 * @category  PGraphNegativeCycleException
 * @package   PGraph
 * @author    Vilius Zaikauskas <zaikaus1@gmail.com>
 * @copyright 2013 Vilius Zaikauskas
 * @license   http://vzaikauskas.com/licenses/MIT.txt MIT
 * @version   Release: @package_version@
 * @link      http://pear.php.net/package/PGraph
 * @since     Class available since Release 1.0
 */
class PGraphNegativeCycleException extends PGraphException
{
    /**
     * Constructor to create the NegativeCycleException.
     */
    public function __construct()
    {
        $emptyArr = array();
        parent::__construct($emptyArr, self::NEG_CYCLE);
    }
}


text:
package scala.runtime.java8;

@FunctionalInterface
public interface JFunction0$mcC$sp extends scala.Function0, java.io.Serializable {
    char apply$mcC$sp();

    default Object apply() { return scala.runtime.BoxesRunTime.boxToCharacter(apply$mcC$sp()); }
}


text:
"""
Authentication aware Docker remote REST API routes.
Docker remote API docs can be found here: https://docs.docker.com/reference/api/docker_remote_api_v1.21/
The API is not called directly but uses the docker library which is imported to this module as 'docker_client'.
"""
from flask import Blueprint, jsonify, request
from qsdocker import app, docker_client
from flask_jwt import jwt_required
import docker as docker_module

docker = Blueprint('docker',__name__, url_prefix=app.config['BASE_REST_API_ROUTE'])

def api_call(method,*args,**kwargs):
    """
    A wrapper to call docker client method and create proper responses in a success or failure (exception raised,...).
    :return: the Response object
    """
    try:
        api_method = getattr(docker_client,method)
        response = jsonify(data=api_method(*args, **kwargs), message="Success")
        response.status_code = 200
        return response
    except docker_module.exceptions.APIError as e:
        response = jsonify(data=[], message=e.strerror)
        response.status_code = e.response.status_code
        return response

@docker.route('/container/<string:action>', methods=['POST'])
@jwt_required()
def container(action):
    """
    A route for interacting with containers, action can be:
    :param action: start, stop, inspect
    """
    if action == 'start':
        mid = api_call('create_container', **request.json)['Id']
        # Pop or remove some elements from the request.json(??)
        return api_call('create_container', **request.json)
    elif action == 'stop':
        pass
    elif action == 'inspect':
        pass
    else:
        raise Exception("Unhandled exception: unknown action provided")

@docker.route('/images', methods=['GET'])
@jwt_required()
def images():
    """
    A flask route for the to get list of images from the docker remote API.
    """
    return api_call('images')

@docker.route('/image/inspect/<string:mid>', methods=['GET'])
@jwt_required()
def inspect(imd):
    """
     A flask route for the to get inspect data for an image from the docker remote API.
     :param imd: the image id to inspect.
    """
    return api_call('inspect_image', imd)


text:
#include "bench/Benchmark.h"
#include "include/core/SkBitmap.h"
#include "include/core/SkCanvas.h"
#include "include/core/SkImageFilter.h"
#include "include/core/SkSurface.h"
#include "include/effects/SkGradientShader.h"
#include "include/effects/SkImageFilters.h"

// Chains several matrix color filters image filter or several
// table filter image filters and draws a bitmap.
// This bench shows an improvement in performance and memory
// when collapsing matrices or tables is implemented since all
// the passes are collapsed in one.

class BaseImageFilterCollapseBench : public Benchmark {
public:
    BaseImageFilterCollapseBench() {}

protected:
    void doPreDraw(sk_sp<SkColorFilter> colorFilters[], int nFilters) {
        SkASSERT(!fImageFilter);

        // Create a chain of ImageFilters from colorFilters
        for(int i = nFilters; i --> 0;) {
            fImageFilter = SkImageFilters::ColorFilter(colorFilters[i], fImageFilter);
        }
    }

    void onDraw(int loops, SkCanvas* canvas) override {
        makeBitmap();

        for(int i = 0; i < loops; i++) {
            SkPaint paint;
            paint.setImageFilter(fImageFilter);
            canvas->drawImage(fImage, 0, 0, SkSamplingOptions(), &paint);
        }
    }

private:
    sk_sp<SkImageFilter> fImageFilter;
    sk_sp<SkImage> fImage;

    void makeBitmap() {
        int W = 400;
        int H = 400;
        auto surf = SkSurface::MakeRasterN32Premul(W, H);

        SkPaint paint;
        SkPoint pts[] = { {0, 0}, {SkIntToScalar(W), SkIntToScalar(H)} };
        SkColor colors[] = {
            SK_ColorBLACK, SK_ColorGREEN, SK_ColorCYAN,
            SK_ColorRED, 0, SK_ColorBLUE, SK_ColorWHITE
        };
        paint.setShader(SkGradientShader::MakeLinear(pts, colors, nullptr, std::size(colors),
                                                     SkTileMode::kClamp));
        surf->getCanvas()->drawPaint(paint);
        fImage = surf->makeImageSnapshot();       // shader->makeImage()
    }
};

class TableCollapseBench: public BaseImageFilterCollapseBench {
protected:
    const char* onGetName() override {
        return "image_filter_collapse_table";
    }

    void onDelayedSetup() override {
        for (int i = 0; i < 256; ++i) {
            int n = i >> 5;
            table1[i] = (n << 5) | (n << 2) | (n >> 1);

            table2[i] = i * i / 255;

            float fi = i / 255.0f;
            table3[i] = static_cast<uint8_t>(sqrtf(fi) * 255);
        }

        sk_sp<SkColorFilter> colorFilters[] = {
            SkColorFilters::Table(table1),
            SkColorFilters::Table(table2),
            SkColorFilters::Table(table3),
        };

        this->doPreDraw(colorFilters, std::size(colorFilters));
    }

private:
    uint8_t table1[256], table2[256], table3[256];
};

static sk_sp<SkColorFilter> make_brightness(float amount) {
    SkScalar matrix[20] = { 1, 0, 0, 0, amount,
                            0, 1, 0, 0, amount,
                            0, 0, 1, 0, amount,
                            0, 0, 0, 1, 0 };
    return SkColorFilters::Matrix(matrix);
}

static sk_sp<SkColorFilter> make_grayscale() {
    float matrix[20];
    memset(matrix, 0, 20 * sizeof(float));
    matrix[0] = matrix[5] = matrix[10] = 0.2126f;
    matrix[1] = matrix[6] = matrix[11] = 0.7152f;
    matrix[2] = matrix[7] = matrix[12] = 0.0722f;
    matrix[18] = 1.0f;
    return SkColorFilters::Matrix(matrix);
}

class MatrixCollapseBench: public BaseImageFilterCollapseBench {
protected:
    const char* onGetName() override {
        return "image_filter_collapse_matrix";
    }

    void onDelayedSetup() override {
        sk_sp<SkColorFilter> colorFilters[] = {
            make_brightness(0.1f),
            make_grayscale(),
            make_brightness(-0.1f),
        };

        this->doPreDraw(colorFilters, std::size(colorFilters));
    }
};

DEF_BENCH(return new TableCollapseBench;)
DEF_BENCH(return new MatrixCollapseBench;)