text:
package parser

import (
	"sip/core"
	"sip/header"
	"strconv"
)

/** SIPParser for TimeStamp header.
 */
type TimeStampParser struct {
	HeaderParser
}

/** Creates a new instance of TimeStampParser
 * @param timeStamp the header to parse
 */
func NewTimeStampParser(timeStamp string) *TimeStampParser {
	this := &TimeStampParser{}
	this.HeaderParser.super(timeStamp)
	return this
}

/** Constructor
 * @param lexer the lexer to use to parse the header
 */
func NewTimeStampParserFromLexer(lexer core.Lexer) *TimeStampParser {
	this := &TimeStampParser{}
	this.HeaderParser.superFromLexer(lexer)
	return this
}

/** parse the String message
 * @return SIPHeader (TimeStamp object)
 * @throws SIPParseException if the message does not respect the spec.
 */
func (this *TimeStampParser) Parse() (sh header.Header, ParseException error) {
	timeStamp := header.NewTimeStamp()

	var ch byte
	var firstNumber, secondNumber int

	lexer := this.GetLexer()
	this.HeaderName(TokenTypes_TIMESTAMP)

	timeStamp.SetHeaderName(core.SIPHeaderNames_TIMESTAMP)
	lexer.SPorHT()

	if firstNumber, ParseException = lexer.Number(); ParseException != nil {
		return nil, ParseException
	}

	var ts float64
	if ch, _ = lexer.LookAheadK(0); ch == '.' {
		lexer.Match('.')

		if secondNumber, ParseException = lexer.Number(); ParseException != nil {
			return nil, ParseException
		}

		s := strconv.Itoa(firstNumber) + "." + strconv.Itoa(secondNumber)
		ts, _ = strconv.ParseFloat(s, 32)
	} else {
		ts = float64(firstNumber)
	}

	timeStamp.SetTimeStamp(float32(ts))

	lexer.SPorHT()
	if ch, _ = lexer.LookAheadK(0); ch != '\n' {
		if firstNumber, ParseException = lexer.Number(); ParseException != nil {
			return nil, ParseException
		}

		if ch, _ = lexer.LookAheadK(0); ch == '.' {
			lexer.Match('.')
			if secondNumber, ParseException = lexer.Number(); ParseException != nil {
				return nil, ParseException
			}

			s := strconv.Itoa(firstNumber) + "." + strconv.Itoa(secondNumber)
			ts, _ = strconv.ParseFloat(s, 32)
		} else {
			ts = float64(firstNumber)
		}

		timeStamp.SetDelay(float32(ts))
	}

	return timeStamp, nil
}


text:
var program = require('commander');
var AWS = require('aws-sdk');
var databases = require('./lib/databases');
var stacks = require('./lib/stacks');

AWS.config.update({region: 'us-east-1'});

program
  .parse(process.argv);

var name = program.args[0];
if (!name) {
  program.help();
  process.exit(1);
}

var deleteVersion = program.args[1];
if (!deleteVersion) {
  program.help();
  process.exit(1);
}

if (!program.args[2] || !program.args[3]) {
  console.error('Supply user and pass');
  process.exit(1);
}

stacks.get(AWS, name, function(err, stack) {
  if (err) {
    console.error(err);
    process.exit(1);
  }

  databases.list(AWS, name, function(err, results) {
    if (err) {
      console.error(err);
      process.exit(1);
    }

    var version = results.filter(function(version) {
      return (version.AppVersion === deleteVersion);
    })[0];

    if (!version) {
      console.error('Failed to find version with id', deleteVersion);
      process.exit(1);
    }

    databases.provision(AWS, version, program.args[2], program.args[3], function(err) {
      if (err) {
        console.error(err);
        process.exit(1);
      }
    });
  });
});

redpajama_set_name: RedPajamaGithub


text:
package org.apache.wicket.util.resource;

import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;

import org.apache.wicket.IClusterable;
import org.apache.wicket.util.lang.Bytes;
import org.apache.wicket.util.watch.IModifiable;

/**
 * Interface to a streamed resource. The resource stream can be retrieved by calling
 * getInputStream(), but the resource should later be closed by calling close() on the
 * IResourceStream (as opposed to calling close on the InputStream returned by getInputStream()).
 *

 * Once a resource has been closed with a call to close(), it is normally possible to call
 * getInputStream() again to retrieve a new input stream on the same resource.
 *

 * Implementations of this interface are typically unsafe for use from multiple threads.
 *
 * @author Jonathan Locke
 */
public interface IResourceStream extends IModifiable, IClusterable, Closeable
{
	/**
	 * Gets the mime type of this resource
	 *
	 * @return The mime type of this resource, such as "image/jpeg" or "text/html". Return null to
	 *         let ResourceStreamRequestHandler handle the Content-Type automatically
	 */
	String getContentType();

	/**
	 * Gets the size of this resource
	 *
	 * @return The size of this resource in the number of bytes, or null if unknown
	 */
	Bytes length();

	/**
	 * Gets the resource stream. You should not directly close this stream. Instead call the close()
	 * method on IResourceStream.
	 *
	 * @see IResourceStream#close()
	 * @return Returns the inputStream.
	 * @throws ResourceStreamNotFoundException
	 */
	InputStream getInputStream() throws ResourceStreamNotFoundException;

	/**
	 * Closes the resource. Normally, this includes closing any underlying input stream returned by
	 * getInputStream().
	 *
	 * @throws IOException
	 */
	void close() throws IOException;

	/**
	 * @return The Locale where this stream did resolve to
	 */
	Locale getLocale();

	/**
	 * This method shouldn't be used from the outside. It is used by the Loaders to set the resolved
	 * locale.
	 *
	 * @param locale
	 *            The Locale where this stream did resolve to.
	 */
	void setLocale(Locale locale);

	/**
	 * @return The Style where this stream did resolve to
	 */
	String getStyle();

	/**
	 * This method shouldn't be used from the outside. It is used by the Loaders to set the resolved
	 * Style.
	 *
	 * @param style
	 *            The style where this stream did resolve to.
	 */
	void setStyle(String style);

	/**
	 * @return The Variation where this stream did resolve to
	 */
	String getVariation();

	/**
	 * This method shouldn't be used from the outside. It is used by the Loaders to set the resolved
	 * variation.
	 *
	 * @param variation
	 *            The Variation where this stream did resolve to.
	 */
	void setVariation(String variation);
}


text:
package blended.samples.jms.internal

import java.util.concurrent.atomic.AtomicLong

import blended.camel.utils.BlendedCamelContextFactory
import blended.container.context.api.ContainerIdentifierService
import blended.domino.TypesafeConfigWatching
import blended.util.logging.Logger
import domino.DominoActivator
import javax.jms.ConnectionFactory
import org.apache.camel.{ Exchange, Processor }
import org.apache.camel.builder.RouteBuilder
import org.apache.camel.component.jms.JmsComponent

object JmsSampleActivator {
  val msgCounter : AtomicLong = new AtomicLong()
}

class JmsSampleActivator extends DominoActivator with TypesafeConfigWatching {
  import JmsSampleActivator.msgCounter

  private[this] val log = Logger[JmsSampleActivator]

  whenBundleActive {
    whenTypesafeConfigAvailable { (cfg, idSvc) =>
      val jmsSampleCfg = JmsSampleConfig(cfg)

      whenAdvancedServicePresent[ConnectionFactory]("(provider=activemq)"){ cf =>
        whenServicePresent[ContainerIdentifierService] { idSvc =>
          val ctxt = BlendedCamelContextFactory.createContext(name = "JmsSampleContext", withJmx = true, idSvc = idSvc)
          ctxt.addComponent("activemq", JmsComponent.jmsComponent(cf))

          ctxt.addRoutes(new RouteBuilder() {
            override def configure(): Unit = {

              if (jmsSampleCfg.producerInterval > 0) {
                log.info(s"Creating producer with interval [${jmsSampleCfg.producerInterval}]ms for destination [${jmsSampleCfg.destination}]")
                from(s"timer:sample?period=${jmsSampleCfg.producerInterval}")
                  .routeId("sampleProducer")
                  .process(new Processor() {
                    override def process(exchange: Exchange): Unit = {
                      exchange.setOut(exchange.getIn())
                      exchange.getOut().setHeader("SampleCounter", msgCounter.getAndIncrement().toString())
                    }
                  })
                  .to(s"activemq:${jmsSampleCfg.destination}")
              }

              jmsSampleCfg.consumeSelector.foreach { sel =>
                log.info(s"Creating consumer for destination [${jmsSampleCfg.destination}] with selector [$sel]")

                var endpoint = "activemq:" + jmsSampleCfg.destination

                if (sel.trim().length() > 0) endpoint = endpoint + "?selector=" + sel

                from(endpoint)
                  .routeId("sampleConsumer")
                  .to("log:jmsSample?showHeaders=true&maxChars=500")
              }
            }
          })

          ctxt.start()

          onStop {
            log.debug("Stopping Camel Context")
            ctxt.stop()
          }
        }
      }
    }
  }
}


text:
<?php

namespace Phlexible\Bundle\ElementtypeBundle\Field;

/**
 * Textarea field
 *
 * @author Stephan Wentz <sw@brainbits.net>
 */
class TextareaField extends TextField
{
    /**
     * {@inheritdoc}
     */
    public function getIcon()
    {
        return 'p-elementtype-field_textarea-icon';
    }
}


text:
package org.dspace.content.crosswalk;

/**
 * Superclass for more-specific crosswalk exceptions.
 * Use this class in declarations and catchers to simplify code
 * and allow for new exception types to be added.
 *
 * @author Larry Stone
 * @version $Revision$
 */
public class CrosswalkException extends Exception
{
    public CrosswalkException()
    {
        super();
    }

    public CrosswalkException(String s, Throwable t)
    {
        super(s, t);
    }

    public CrosswalkException(String s)
    {
        super(s);
    }

    public CrosswalkException(Throwable t)
    {
        super(t);
    }
}


text:
class GURL;

namespace WebKit {
class WebSocketStreamHandle;
}

namespace webkit_glue {

class WebSocketStreamHandleDelegate {
 public:
  WebSocketStreamHandleDelegate() {}
  virtual ~WebSocketStreamHandleDelegate() {}

  virtual void WillOpenStream(WebKit::WebSocketStreamHandle* handle,
                              const GURL& url) {}
  virtual void WillSendData(WebKit::WebSocketStreamHandle* handle,
                            const char* data, int len) {}

  virtual void DidOpenStream(WebKit::WebSocketStreamHandle* handle,
                             int max_amount_send_allowed) {}
  virtual void DidSendData(WebKit::WebSocketStreamHandle* handle,
                           int amount_sent) {}
  virtual void DidReceiveData(WebKit::WebSocketStreamHandle* handle,
                              const char* data, int len) {}
  virtual void DidClose(WebKit::WebSocketStreamHandle*) {}
};

}  // namespace webkit_glue

#endif  // WEBKIT_GLUE_WEBSOCKETSTREAMHANDLE_DELEGATE_H_


text:
package com.yaneri.se.config;

import org.springframework.beans.factory.xml.NamespaceHandlerSupport;

public class SeNamespaceHandler extends NamespaceHandlerSupport {

	public void init() {
		registerBeanDefinitionParser("transaction", new TransactionBeanDefinitionParser());
		registerBeanDefinitionParser("action", new ActionBeanDefinitionParser());
	}

}


text:
import {Component, OnInit} from '@angular/core';
import {MultipleAdditionModel} from '../multiple-addition.model';
import {Lendable} from '../../interfaces/server/lendable.interface';

@Component({
  selector: 'addition-summary-step',
  templateUrl: './summary-step.component.html',
  styleUrls: ['./summary-step.component.scss']
})
export class SummaryStepComponent implements OnInit {
  constructor(public model: MultipleAdditionModel<Lendable>) { }

  ngOnInit() {
  }

  public reset(): void {
    this.model.reset();
  }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
<link type="text/css" rel="stylesheet" href="../js9.css">
<title>Creating a JS9 Web Page</title>

Creating a JS9 Web Page

Adding JS9 to Your Web Page

The sample js9basics.html file shows how to add JS9 to a web page by
assigning JS9 CSS classes to "div" elements.  The js9multi.html web
page goes further by showing how multiple instances of JS9 can be
added using unique IDs.

To start, a few JavaScript and CSS files must be loaded into the web
page.  Ordinarily this is done in the page's header, which typically
will look something like this:

  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=Edge;chrome=1" >
  <meta name="viewport" content="width=device-width, initial-scale=1" >
  <link type="image/x-icon" rel="shortcut icon" href="./favicon.ico">
  <link type="text/css" rel="stylesheet" href="js9support.css">
  <link type="text/css" rel="stylesheet" href="js9.css">
  <script type="text/javascript" src="js9prefs.js"></script>
  <script type="text/javascript" src="js9support.min.js"></script>
  <script type="text/javascript" src="js9.min.js"></script>
  <script type="text/javascript" src="js9plugins.js"></script>
  </head>

The js9prefs.js file (and deprecated js9Prefs.json file) is optional.
It contains a JS9Prefs object that holds various default settings for
JS9, e.g. default colormap and scale for image display.  Feel free to
edit this file to set up your own site-specific parameters. See
JS9 Site Preferences for a
description of the available parameters.

Order is important: The js9prefs.js file must be loaded first. The
js9support.min.js must be loaded before you load js9.min.js. You must
load the plugin files after you load js9.min.js.  You can simply copy
the order of files as specified in the JS9 demo files.

You can, of course, arrange to have your web server gzip the javascript
files, using browser-based capabilities to ungzip them automatically. The
JS9 web site serves pre-compressed content, as described in the

Apache Module mod_deflate page.

The text file js9support.txt is a list of the files contained
in js9support.css, js9support.js, js9support.min,js, and js9plugins.js.

The js9support.min.js file contains a number of required third-party
software modules, including jQuery, fabric.js (2D graphics), flot (for
plotting), dhtmlwindow (for light windows), etc. It is separated from
js9.min.js to optimize file caching. Although JS9 will not run
properly without these third-party modules, you are free to load them
manually, i.e., without loading js9support.min.js itself. A manual
load is useful in cases where you want a different version of one of
the third-party modules (e.g., js9support.min.js loads jQuery 1.12.2,
but you need to utilize jQuery 1.11.3). In such a case, we still
recommend creating a single file to hold third-party modules, in order
to minimize load latency.

JS9 will run without the js9plugins.js file, but with much
restricted functionality.  In particular, core plugins such as
blending, blinking, colorbar, data cube, magnifier, panner, etc. are
loaded from this file, as are analysis plugins such as encircled
energy, radial projection, region statistics, and 3D plot.  Note that
the regions and mouse/touch core plugins are always loaded from within
js9.min.js itself, since they are essential to almost all JS9
functionality.

All of these Javascript plugin files are contained in the plugins
subdirectory, so you can load them individually, e.g.:

  <script type="text/javascript" src="js9prefs.js"></script>
  <script type="text/javascript" src="js9support.min.js"></script>
  <script type="text/javascript" src="js9.min.js"></script>
  <script type="text/javascript" src="plugins/core/menubar.js"></script>
  <script type="text/javascript" src="plugins/core/info.js"></script>

will load only the menubar and info display plugins.

During startup, JS9 will asynchronously load the js9worker.js
file in order to create a worker process. It also will load either
the astroem.js file or the astroemw.js
and astroemw.wasm files, depending on whether
WebAssembly is supported on your browser.

The main JS9 display as well as JS9 plugins are placed on a web page
by assigning JS9 classes to ordinary "div" elements. The two important
JS9 classes are:

JS9: this class will display the main JS9 image window

JS9Menubar: this class will display the JS9 menubar

Thus, for example, to place a menubar on top of a JS9 display, use:

  <div class="JS9Menubar">
  <div class="JS9">

Among the many JS9 plugins that you can add to your webpage are:

Archives & Catalogs: access to external archives and catalogs

Bin/Filter/Section: support for extracting sections from images

Blending: blend images using standard composite techniques

Blinking: blink two or more images

Colormaps: create colormaps

Console: display a console window for executing commands

Contours: create contour maps

Data Cube: process 3D FITS data cubes

Extensions: view FITS extensions

Info: display position, value, and other information as mouse moves

Keyboard Actions: configure keyboard actions

Magnifier: display a magnifier window centered on the mouse position

Mouse/Touch: configure mouse/touch actions

Panner: display a panner window of the whole image

Pixel Table: display a pixel value table centered on the mouse position

Preferences: configure JS9 preferences

Any of these can be added to a web page by specifying a div element with the
appropriate class:

    <div class="JS9Menubar"></div>
    <div class="JS9Toolbar"></div>
    <div class="JS9"></div>
    <div style="margin-top: 2px;">
    <div class="JS9Colorbar"></div>

NB: all of these plugins can also be displayed at any time as light
windows, using the appropriate View menu options. Light windows
can moved around on the page and dismissed when no longer needed. Also
note that if a plugin is declared statically in a page, it will not be
made available in the View menu.

Placement of JS9 div elements should follow standard web page rules
and constraints.  This means that div elements can be placed in any
order to create different graphical views. For example, the
js9basics.html page places the menubar above the image display, in
keeping with the traditional layout of DS9. The entire JS9 construct
is placed in a data cell of a table, next to a data cell containing
data URLs.

The JS9 display has a default width and height of 512x512. You can
change this by adding data-width and data-height
attributes to the div. For example, to create a display of size 256x256, use:

  <div class="JS9" data-width="256px" data-height="256px">

The data-width and data-height attributes can be applied
to the other JS9 divs (which can be especially useful for the menubar).
Thus, for example, if you shorten the width of the Js9 display, you might
also want to shorten the width of the menubar:

  <div class="JS9Menubar" data-width="256px" data-height="48px">

Multiple instances of JS9 (including the main JS9 display element
and secondary plugins elements) can be added to a single web page. This
is done by specifying multiple sets of JS9 elements. Each main JS9 display
element should have a unique HTML id associated with it:

   <div class="JS9" id="JS9"></div>
   <div class="JS9" id="myJS9"></div>

To connect a JS9 plugin element to a given JS9 display element, you
can either use an HTML id that obeys certain rules, or you can
use an HTML data attribute data-js9id, as described below.

To connect a JS9 display to one or more JS9 plugins using an
HTML id attribute, the plugin ids should be specified as follows:

 start with a unique ID name, e.g. "myJS9" that matches the main JS9 id

 follow with an optional dash or underscore

 finish with the type of JS9 plugin, e.g. "Menubar", "Panner", "Magnifier" "Info", "3dPlot", "RegionStats", etc.

For example:

    <div class="JS9Menubar" id="myJS9Menubar"></div>
    <div class="JS9" id="myJS9"></div>
    <div class="JS9Colorbar" id="myJS9Colorbar"></div>
    <div class="ImExamRegionStats" id="myJS9RegionStats"></div>

Note that the type of plugin is the simple name of the plugin, without the class prefix, e.g., "RegionStats" instead of "ImExamRegionStats". (Esoteric note: for
non-JS9 class plugins, you can prefix the class to avoid name collisions.)

To connect a JS9 display to one or more JS9 plugins using a
HTML data attribute js9id, specify the id of the main
JS9 display element as its value:

    <div class="JS9Menubar" data-js9id="myJS9"></div>
    <div class="JS9" id="myJS9"></div>
    <div style="margin-top: 2px;">
    <div class="JS9Colorbar" data-js9id="myJS9"></div>

These two connection methods are equivalent. However, the js9id
data attribute method also allows you to specify the single-character
token * as a target value for many plugins. In this case, the
display associated with the plugin is dynamically selected by clicking
the mouse in a JS9 display window. In this way, a single plugin can serve
several displays.

The plugins that support dynamic selection are:

 Blend

 Blink

 Colorbar

 Info

 Magnifier

 Menubar

 Panner

 Separate

 EncEnergy

 RadialProj

 Histogram

 RegionStats

 XProj

 YProj

 3dPlot

Note that ids are not required at all if there is only one JS9 instance on
the web page:

    <div class="JS9Menubar"></div>
    <div class="JS9Toolbar"></div>
    <div class="JS9"></div>
    <div style="margin-top: 2px;">
    <div class="JS9Colorbar"></div>

However, if your site needs to communicate with clients using
the js9 script for external communication, you can
differentiate between clients loading the same JS9-enabled web page by
supplying a unique ID when the JS9 page is served.

 A full example of how to define multiple instances of JS9 with ids
is found, for example, in the js9multi.html file. Two DS9 instances
are defined, having IDs of "JS9" (the default) and "myJS9". When
"myJS9" is the display ID, "myJS9Menubar" specifies the associated
menubar and "myJS9Console" specifies the associated console.

The js9.css file contains CSS directives for various parts of
JS9. These can be modified (or overwritten) as needed, subject to
ordinary CSS rules. In general, we recommend overwriting CSS rules by
loading a site-specific CSS file after the js9.css file. This makes
updating much easier.

One CSS directive worth noting is the JS9Button class, which
defines the look and feel of the buttons found on the Menubar, inside
plugins, etc.  The JS9Button class currently is set to
the JS9ClassicButton class, which mimics Mac OSX buttons in
shape and color. An alternative is the JS9FlatButton class
displays a flat blue button that highlights when the mouse hovers and
darkens when clicked. A lightblue background is often used with
this class of button. JS9 also defines a JS9BorderButton which
has a blue colored border and a white background.  The JS9 Menubar
supports two data properties to make it easier to change the button
and background:

buttonClass: the class of button to use ("JS9ClassicButton", "JS9FlatButton", "JS9BorderButton" ... or your own class)

backgroundColor: color of background (default: "lightblue")

The JS9 Size Demo displays different button styles.

Normally, JS9 will initialize itself automatically once the page is
loaded and ready: internally, jQuery $(document).ready() calls
JS9.init(). If you need to delay JS9 initialization (e.g., you
are using a platform that fires $(document).ready() before the
platform is really ready), you can set data-js9init to "false"
on any JS9 div. In this case, you must call the init routine manually:

  JS9.init();

Until you do this, no JS9 div elements will be visible.

When JS9 is fully loaded and ready (including connection to the JS9
helper, if necessary), it fires the JS9:ready event. You can
use this event to perform your own initialization:

  $(document).on("JS9:ready", function(){
      myinit();
  });

Menubar Styles
 The default menubar has a style in which all
of the major menus are shown at the top-level of the menubar. This is
the classic style. JS9 also supports a mac style
menubar, in which the File, Edit and View menus
are placed on the left side of the menubar and the Help menu on
the right.  The other main menus are displayed as sub-menus within
the View menu. The mac style can be specified in two
ways: you can set the JS9globalOpts.menubarStyle property to "mac" in
your js9prefs.js file to set the default menubar style for all menus
in the page. Alternatively you can supply a data-style="mac"
attribute to the Menubar div element:

  <div class="JS9Menubar" data-style="mac">

This will set the menubar style for this element only.

Supermenus: One Menubar to Rule Them All
 By default, each
menubar controls one JS9 display. You can, however, create a menubar
that controls multiple displays, so that a given menu selection is
applied to each display (or to a specifically selected image). This is
done by creating a menubar div with two special characteristics:

 the id of the menubar starts with SUPERMENU_ (it can end with anything, or nothing)

 an HTML5 data attribute called data-displays lists the JS9 displays to control or "*" for all displays

For example, to control two JS9 displays:

  <div class="JS9Menubar" id="SUPERMENU_" data-displays="JS9,myJS9"></div>

As shown, the data-displays attribute is a comma-separated list
of JS9 display ids to control with this super-menu.

A super-menu acts like an ordinary menu, except that it will control
all of the JS9 displays in the list. Thus, you can change multiple
colormaps at once, run analysis on all displays, etc.

You also can click on an individual display to make it the selected
display for the supermenu. The selected display will be
highlighted, and the supermenu will target its actions at this display
alone, rather than at all of the displays. Click again in a selected
display (or clicking in another display) to unselect it. In this way,
a single supermenu can be used to control several displays
individually (akin to how the top-level Apple menu functions with
regard to applications).

A supermenu displays an additional Super menu button on the
left side of the menubar. This button contains a list of all displays
controlled by the supermenu, with the selected display starred. You
can choose a new selected display from this menu, or choose "all
displays" to unselect.

Of course, you also can define a menubar for each display in order to
control them individually. Since the actions of an ordinary menu and a
super-menu can be mixed for a given JS9 display, the displays will not
always be perfectly synchronized. In such a case, the super-menu's
selected values will be tied to the first display in the
data-displays list.  For example, if the first display listed
is at zoom 2 and the second is at zoom 4, the Zoom menu will show
a current zoom value of 2.

Adding Server-side Analysis Tasks to Your Web Page

Server-side JS9 analysis tasks can be executed using
the Analysis menu, but they also can be executed directly from
the web page using HTML elements (buttons, forms, etc.) To do this, a
web page author simply creates the web interface and calls
either JS9.RunAnalysis() (for buttons, menus, etc.)
or JS9.SubmitAnalysis() (for forms). These are described
in the Local Tasks web page.

Adding Local Analysis Tasks to Your Web Page

JS9 also supports the ability to perform local analysis, i.e.,
analysis tasks defined and executed right on your web page, rather
than being executed by a back-end server.  This is accomplished by
offering access to the image data and region information via
a public JS9 API. See the
Local Tasks for more information.

Adding JS9 Display Windows Dynamically

JS9 display windows can be created dynamically using the JS9 Public API call
JS9.LoadWindow(). You can create a light window to hold a new
JS9 display on the same page or you can create an entirely separate
pop-up window. See the
JS9 Public API for more information.

Adding Data Files to a Web Page

Data file links are added to a web page by supplying URLs that call
the JS9.Load() routine.
You also can load images automatically when the web page loads using the
JS9.Preload() routine.
See:
Adding Data Files To a Web Page for more
information.

Last updated: June 5, 2019


text:
package com.alibaba.otter.canal.instance.core;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.otter.canal.common.AbstractCanalLifeCycle;
import com.alibaba.otter.canal.common.alarm.CanalAlarmHandler;
import com.alibaba.otter.canal.filter.aviater.AviaterRegexFilter;
import com.alibaba.otter.canal.meta.CanalMetaManager;
import com.alibaba.otter.canal.parse.CanalEventParser;
import com.alibaba.otter.canal.parse.ha.CanalHAController;
import com.alibaba.otter.canal.parse.ha.HeartBeatHAController;
import com.alibaba.otter.canal.parse.inbound.AbstractEventParser;
import com.alibaba.otter.canal.parse.inbound.group.GroupEventParser;
import com.alibaba.otter.canal.parse.inbound.mysql.MysqlEventParser;
import com.alibaba.otter.canal.parse.index.CanalLogPositionManager;
import com.alibaba.otter.canal.protocol.CanalEntry;
import com.alibaba.otter.canal.protocol.ClientIdentity;
import com.alibaba.otter.canal.sink.CanalEventSink;
import com.alibaba.otter.canal.store.CanalEventStore;
import com.alibaba.otter.canal.store.model.Event;

/**
 * Created with Intellig IDEA. Author: yinxiu Date: 2016-01-07 Time: 22:26
 */
public class AbstractCanalInstance extends AbstractCanalLifeCycle implements CanalInstance {

    private static final Logger                      logger = LoggerFactory.getLogger(AbstractCanalInstance.class);

    protected Long                                   canalId;                                                      // 和manager交互唯一标示
    protected String                                 destination;                                                  // 队列名字
    protected CanalEventStore<Event>                 eventStore;                                                   // 有序队列

    protected CanalEventParser                       eventParser;                                                  // 解析对应的数据信息
    protected CanalEventSink<List<CanalEntry.Entry>> eventSink;                                                    // 链接parse和store的桥接器
    protected CanalMetaManager                       metaManager;                                                  // 消费信息管理器
    protected CanalAlarmHandler                      alarmHandler;                                                 // alarm报警机制

    @Override
    public boolean subscribeChange(ClientIdentity identity) {
        if (StringUtils.isNotEmpty(identity.getFilter())) {
            logger.info("subscribe filter change to " + identity.getFilter());
            AviaterRegexFilter aviaterFilter = new AviaterRegexFilter(identity.getFilter());

            boolean isGroup = (eventParser instanceof GroupEventParser);
            if (isGroup) {
                // 处理group的模式
                List<CanalEventParser> eventParsers = ((GroupEventParser) eventParser).getEventParsers();
                for (CanalEventParser singleEventParser : eventParsers) {// 需要遍历启动
                    ((AbstractEventParser) singleEventParser).setEventFilter(aviaterFilter);
                }
            } else {
                ((AbstractEventParser) eventParser).setEventFilter(aviaterFilter);
            }

        }

        // filter的处理规则
        // a. parser处理数据过滤处理
        // b. sink处理数据的路由&分发,一份parse数据经过sink后可以分发为多份,每份的数据可以根据自己的过滤规则不同而有不同的数据
        // 后续内存版的一对多分发,可以考虑
        return true;
    }

    @Override
    public void start() {
        super.start();
        if (!metaManager.isStart()) {
            metaManager.start();
        }

        if (!alarmHandler.isStart()) {
            alarmHandler.start();
        }

        if (!eventStore.isStart()) {
            eventStore.start();
        }

        if (!eventSink.isStart()) {
            eventSink.start();
        }

        if (!eventParser.isStart()) {
            beforeStartEventParser(eventParser);
            eventParser.start();
            afterStartEventParser(eventParser);
        }
        logger.info("start successful....");
    }

    @Override
    public void stop() {
        super.stop();
        logger.info("stop CannalInstance for {}-{} ", new Object[] { canalId, destination });

        if (eventParser.isStart()) {
            beforeStopEventParser(eventParser);
            eventParser.stop();
            afterStopEventParser(eventParser);
        }

        if (eventSink.isStart()) {
            eventSink.stop();
        }

        if (eventStore.isStart()) {
            eventStore.stop();
        }

        if (metaManager.isStart()) {
            metaManager.stop();
        }

        if (alarmHandler.isStart()) {
            alarmHandler.stop();
        }

        logger.info("stop successful....");
    }

    protected void beforeStartEventParser(CanalEventParser eventParser) {

        boolean isGroup = (eventParser instanceof GroupEventParser);
        if (isGroup) {
            // 处理group的模式
            List<CanalEventParser> eventParsers = ((GroupEventParser) eventParser).getEventParsers();
            for (CanalEventParser singleEventParser : eventParsers) {// 需要遍历启动
                startEventParserInternal(singleEventParser, true);
            }
        } else {
            startEventParserInternal(eventParser, false);
        }
    }

    // around event parser, default impl
    protected void afterStartEventParser(CanalEventParser eventParser) {
        // 读取一下历史订阅的filter信息
        List<ClientIdentity> clientIdentitys = metaManager.listAllSubscribeInfo(destination);
        for (ClientIdentity clientIdentity : clientIdentitys) {
            subscribeChange(clientIdentity);
        }
    }

    // around event parser
    protected void beforeStopEventParser(CanalEventParser eventParser) {
        // noop
    }

    protected void afterStopEventParser(CanalEventParser eventParser) {

        boolean isGroup = (eventParser instanceof GroupEventParser);
        if (isGroup) {
            // 处理group的模式
            List<CanalEventParser> eventParsers = ((GroupEventParser) eventParser).getEventParsers();
            for (CanalEventParser singleEventParser : eventParsers) {// 需要遍历启动
                stopEventParserInternal(singleEventParser);
            }
        } else {
            stopEventParserInternal(eventParser);
        }
    }

    /**
     * 初始化单个eventParser,不需要考虑group
     */
    protected void startEventParserInternal(CanalEventParser eventParser, boolean isGroup) {
        if (eventParser instanceof AbstractEventParser) {
            AbstractEventParser abstractEventParser = (AbstractEventParser) eventParser;
            // 首先启动log position管理器
            CanalLogPositionManager logPositionManager = abstractEventParser.getLogPositionManager();
            if (!logPositionManager.isStart()) {
                logPositionManager.start();
            }
        }

        if (eventParser instanceof MysqlEventParser) {
            MysqlEventParser mysqlEventParser = (MysqlEventParser) eventParser;
            CanalHAController haController = mysqlEventParser.getHaController();

            if (haController instanceof HeartBeatHAController) {
                ((HeartBeatHAController) haController).setCanalHASwitchable(mysqlEventParser);
            }

            if (!haController.isStart()) {
                haController.start();
            }

        }
    }

    protected void stopEventParserInternal(CanalEventParser eventParser) {
        if (eventParser instanceof AbstractEventParser) {
            AbstractEventParser abstractEventParser = (AbstractEventParser) eventParser;
            // 首先启动log position管理器
            CanalLogPositionManager logPositionManager = abstractEventParser.getLogPositionManager();
            if (logPositionManager.isStart()) {
                logPositionManager.stop();
            }
        }

        if (eventParser instanceof MysqlEventParser) {
            MysqlEventParser mysqlEventParser = (MysqlEventParser) eventParser;
            CanalHAController haController = mysqlEventParser.getHaController();
            if (haController.isStart()) {
                haController.stop();
            }
        }
    }

    // ==================getter==================================
    @Override
    public String getDestination() {
        return destination;
    }

    @Override
    public CanalEventParser getEventParser() {
        return eventParser;
    }

    @Override
    public CanalEventSink getEventSink() {
        return eventSink;
    }

    @Override
    public CanalEventStore getEventStore() {
        return eventStore;
    }

    @Override
    public CanalMetaManager getMetaManager() {
        return metaManager;
    }

    @Override
    public CanalAlarmHandler getAlarmHandler() {
        return alarmHandler;
    }
}


text:
package org.apache.skywalking.oap.server.storage.plugin.elasticsearch;

import java.io.ByteArrayInputStream;
import java.util.Properties;
import java.util.function.Function;
import lombok.extern.slf4j.Slf4j;
import org.apache.skywalking.oap.server.library.util.StringUtil;
import org.apache.skywalking.oap.server.core.CoreModule;
import org.apache.skywalking.oap.server.core.storage.IBatchDAO;
import org.apache.skywalking.oap.server.core.storage.IHistoryDeleteDAO;
import org.apache.skywalking.oap.server.core.storage.StorageBuilderFactory;
import org.apache.skywalking.oap.server.core.storage.StorageDAO;
import org.apache.skywalking.oap.server.core.storage.StorageModule;
import org.apache.skywalking.oap.server.core.storage.cache.INetworkAddressAliasDAO;
import org.apache.skywalking.oap.server.core.storage.management.UITemplateManagementDAO;
import org.apache.skywalking.oap.server.core.storage.model.ModelCreator;
import org.apache.skywalking.oap.server.core.storage.profile.IProfileTaskLogQueryDAO;
import org.apache.skywalking.oap.server.core.storage.profile.IProfileTaskQueryDAO;
import org.apache.skywalking.oap.server.core.storage.profile.IProfileThreadSnapshotQueryDAO;
import org.apache.skywalking.oap.server.core.storage.query.IAggregationQueryDAO;
import org.apache.skywalking.oap.server.core.storage.query.IAlarmQueryDAO;
import org.apache.skywalking.oap.server.core.storage.query.IBrowserLogQueryDAO;
import org.apache.skywalking.oap.server.core.storage.query.IEventQueryDAO;
import org.apache.skywalking.oap.server.core.storage.query.ILogQueryDAO;
import org.apache.skywalking.oap.server.core.storage.query.IMetadataQueryDAO;
import org.apache.skywalking.oap.server.core.storage.query.IMetricsQueryDAO;
import org.apache.skywalking.oap.server.core.storage.query.ITopNRecordsQueryDAO;
import org.apache.skywalking.oap.server.core.storage.query.ITopologyQueryDAO;
import org.apache.skywalking.oap.server.core.storage.query.ITraceQueryDAO;
import org.apache.skywalking.oap.server.library.client.elasticsearch.ElasticSearchClient;
import org.apache.skywalking.oap.server.library.module.ModuleConfig;
import org.apache.skywalking.oap.server.library.module.ModuleDefine;
import org.apache.skywalking.oap.server.library.module.ModuleProvider;
import org.apache.skywalking.oap.server.library.module.ModuleStartException;
import org.apache.skywalking.oap.server.library.module.ServiceNotProvidedException;
import org.apache.skywalking.oap.server.library.util.MultipleFilesChangeMonitor;
import org.apache.skywalking.oap.server.storage.plugin.elasticsearch.base.BatchProcessEsDAO;
import org.apache.skywalking.oap.server.storage.plugin.elasticsearch.base.HistoryDeleteEsDAO;
import org.apache.skywalking.oap.server.storage.plugin.elasticsearch.base.StorageEsDAO;
import org.apache.skywalking.oap.server.storage.plugin.elasticsearch.base.StorageEsInstaller;
import org.apache.skywalking.oap.server.storage.plugin.elasticsearch.base.TimeSeriesUtils;
import org.apache.skywalking.oap.server.storage.plugin.elasticsearch.cache.NetworkAddressAliasEsDAO;
import org.apache.skywalking.oap.server.storage.plugin.elasticsearch.query.AggregationQueryEsDAO;
import org.apache.skywalking.oap.server.storage.plugin.elasticsearch.query.AlarmQueryEsDAO;
import org.apache.skywalking.oap.server.storage.plugin.elasticsearch.query.BrowserLogQueryEsDAO;
import org.apache.skywalking.oap.server.storage.plugin.elasticsearch.query.ESEventQueryDAO;
import org.apache.skywalking.oap.server.storage.plugin.elasticsearch.query.LogQueryEsDAO;
import org.apache.skywalking.oap.server.storage.plugin.elasticsearch.query.MetadataQueryEsDAO;
import org.apache.skywalking.oap.server.storage.plugin.elasticsearch.query.MetricsQueryEsDAO;
import org.apache.skywalking.oap.server.storage.plugin.elasticsearch.query.ProfileTaskLogEsDAO;
import org.apache.skywalking.oap.server.storage.plugin.elasticsearch.query.ProfileTaskQueryEsDAO;
import org.apache.skywalking.oap.server.storage.plugin.elasticsearch.query.ProfileThreadSnapshotQueryEsDAO;
import org.apache.skywalking.oap.server.storage.plugin.elasticsearch.query.TopNRecordsQueryEsDAO;
import org.apache.skywalking.oap.server.storage.plugin.elasticsearch.query.TopologyQueryEsDAO;
import org.apache.skywalking.oap.server.storage.plugin.elasticsearch.query.TraceQueryEsDAO;
import org.apache.skywalking.oap.server.storage.plugin.elasticsearch.query.UITemplateManagementEsDAO;
import org.apache.skywalking.oap.server.telemetry.TelemetryModule;
import org.apache.skywalking.oap.server.telemetry.api.HealthCheckMetrics;
import org.apache.skywalking.oap.server.telemetry.api.MetricsCreator;
import org.apache.skywalking.oap.server.telemetry.api.MetricsTag;

/**
 * The storage provider for ElasticSearch 6.
 */
@Slf4j
public class StorageModuleElasticsearchProvider extends ModuleProvider {

    protected final StorageModuleElasticsearchConfig config;
    protected ElasticSearchClient elasticSearchClient;

    public StorageModuleElasticsearchProvider() {
        super();
        this.config = new StorageModuleElasticsearchConfig();
    }

    @Override
    public String name() {
        return "elasticsearch";
    }

    @Override
    public Class<? extends ModuleDefine> module() {
        return StorageModule.class;
    }

    @Override
    public ModuleConfig createConfigBeanIfAbsent() {
        return config;
    }

    @Override
    public void prepare() throws ServiceNotProvidedException {
        this.registerServiceImplementation(StorageBuilderFactory.class, new StorageBuilderFactory.Default());

        if (StringUtil.isEmpty(config.getNamespace())) {
            config.setNamespace("sw");
        } else {
            config.setNamespace(config.getNamespace().toLowerCase());
        }
        if (config.getDayStep() > 1) {
            TimeSeriesUtils.setDAY_STEP(config.getDayStep());
            TimeSeriesUtils.setSUPER_DATASET_DAY_STEP(config.getDayStep());
        }
        if (config.getSuperDatasetDayStep() > 0) {
            TimeSeriesUtils.setSUPER_DATASET_DAY_STEP(config.getSuperDatasetDayStep());
        }

        if (!StringUtil.isEmpty(config.getSecretsManagementFile())) {
            MultipleFilesChangeMonitor monitor = new MultipleFilesChangeMonitor(
                10, readableContents -> {
                final byte[] secretsFileContent = readableContents.get(0);
                if (secretsFileContent == null) {
                    return;
                }
                Properties secrets = new Properties();
                secrets.load(new ByteArrayInputStream(secretsFileContent));
                config.setUser(secrets.getProperty("user", null));
                config.setPassword(secrets.getProperty("password", null));
                config.setTrustStorePass(secrets.getProperty("trustStorePass", null));

                if (elasticSearchClient == null) {
                    // In the startup process, we just need to change the username/password
                } else {
                    // The client has connected, updates the config and connects again.
                    elasticSearchClient.setUser(config.getUser());
                    elasticSearchClient.setPassword(config.getPassword());
                    elasticSearchClient.setTrustStorePass(config.getTrustStorePass());
                    elasticSearchClient.connect();
                }
            }, config.getSecretsManagementFile(), config.getTrustStorePass());
            /*
             * By leveraging the sync update check feature when startup.
             */
            monitor.start();
        }

        elasticSearchClient = new ElasticSearchClient(
            config.getClusterNodes(), config.getProtocol(), config.getTrustStorePath(), config
            .getTrustStorePass(), config.getUser(), config.getPassword(),
            indexNameConverter(config.getNamespace()), config.getConnectTimeout(),
            config.getSocketTimeout(), config.getNumHttpClientThread()
        );
        this.registerServiceImplementation(
            IBatchDAO.class,
            new BatchProcessEsDAO(elasticSearchClient, config.getBulkActions(), config
                .getFlushInterval(), config.getConcurrentRequests())
        );
        this.registerServiceImplementation(StorageDAO.class, new StorageEsDAO(elasticSearchClient));
        this.registerServiceImplementation(
            IHistoryDeleteDAO.class, new HistoryDeleteEsDAO(elasticSearchClient));
        this.registerServiceImplementation(
            INetworkAddressAliasDAO.class, new NetworkAddressAliasEsDAO(elasticSearchClient, config
                .getResultWindowMaxSize()));
        this.registerServiceImplementation(ITopologyQueryDAO.class, new TopologyQueryEsDAO(elasticSearchClient));
        this.registerServiceImplementation(IMetricsQueryDAO.class, new MetricsQueryEsDAO(elasticSearchClient));
        this.registerServiceImplementation(
            ITraceQueryDAO.class, new TraceQueryEsDAO(elasticSearchClient, config.getSegmentQueryMaxSize()));
        this.registerServiceImplementation(IBrowserLogQueryDAO.class, new BrowserLogQueryEsDAO(elasticSearchClient));
        this.registerServiceImplementation(
            IMetadataQueryDAO.class, new MetadataQueryEsDAO(elasticSearchClient, config.getMetadataQueryMaxSize()));
        this.registerServiceImplementation(IAggregationQueryDAO.class, new AggregationQueryEsDAO(elasticSearchClient));
        this.registerServiceImplementation(IAlarmQueryDAO.class, new AlarmQueryEsDAO(elasticSearchClient));
        this.registerServiceImplementation(ITopNRecordsQueryDAO.class, new TopNRecordsQueryEsDAO(elasticSearchClient));
        this.registerServiceImplementation(ILogQueryDAO.class, new LogQueryEsDAO(elasticSearchClient));
        this.registerServiceImplementation(
            IProfileTaskQueryDAO.class, new ProfileTaskQueryEsDAO(elasticSearchClient, config
                .getProfileTaskQueryMaxSize()));
        this.registerServiceImplementation(
            IProfileTaskLogQueryDAO.class, new ProfileTaskLogEsDAO(elasticSearchClient, config
                .getProfileTaskQueryMaxSize()));
        this.registerServiceImplementation(
            IProfileThreadSnapshotQueryDAO.class, new ProfileThreadSnapshotQueryEsDAO(elasticSearchClient, config
                .getProfileTaskQueryMaxSize()));
        this.registerServiceImplementation(
            UITemplateManagementDAO.class, new UITemplateManagementEsDAO(elasticSearchClient));

        this.registerServiceImplementation(IEventQueryDAO.class, new ESEventQueryDAO(elasticSearchClient));
    }

    @Override
    public void start() throws ModuleStartException {
        MetricsCreator metricCreator = getManager().find(TelemetryModule.NAME)
                                                   .provider()
                                                   .getService(MetricsCreator.class);
        HealthCheckMetrics healthChecker = metricCreator.createHealthCheckerGauge(
            "storage_elasticsearch", MetricsTag.EMPTY_KEY, MetricsTag.EMPTY_VALUE);
        elasticSearchClient.registerChecker(healthChecker);
        try {
            elasticSearchClient.connect();
            StorageEsInstaller installer = new StorageEsInstaller(elasticSearchClient, getManager(), config);

            getManager().find(CoreModule.NAME).provider().getService(ModelCreator.class).addModelListener(installer);
        } catch (Exception e) {
            throw new ModuleStartException(e.getMessage(), e);
        }
    }

    @Override
    public void notifyAfterCompleted() {
    }

    @Override
    public String[] requiredModules() {
        return new String[] {CoreModule.NAME};
    }

    public static Function<String, String> indexNameConverter(String namespace) {
        return indexName -> {
            if (StringUtil.isNotEmpty(namespace)) {
                return namespace + "_" + indexName;
            }
            return indexName;
        };
    }
}


text:
package net.zerobuilder.examples.derive4j;

import org.junit.Test;

import java.util.Optional;
import java.util.function.Function;

import static net.zerobuilder.examples.derive4j.RequestBuilders.putBuilder;
import static net.zerobuilder.examples.derive4j.Requests.getBody;
import static net.zerobuilder.examples.derive4j.Requests.getPath;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

public class RequestTest {

  private final Function<Request, String> type = Requests.cases()
      .GET("GET")
      .DELETE("DELETE")
      .PUT("PUT")
      .POST("POST");

  @Test
  public void put() throws Exception {
    Request body = putBuilder()
        .path("/put")
        .body("body");
    assertThat(getPath(body), is("/put"));
    assertThat(getBody(body), is(Optional.of("body")));
    assertThat(type.apply(body), is("PUT"));
  }

  @Test
  public void post() throws Exception {
    Request body = RequestBuilders.postBuilder()
        .path("/post")
        .body("body");
    assertThat(getPath(body), is("/post"));
    assertThat(getBody(body), is(Optional.of("body")));
    assertThat(type.apply(body), is("POST"));
  }

  @Test
  public void get() throws Exception {
    Request body = RequestBuilders.getBuilder()
        .path("/get");
    assertThat(getPath(body), is("/get"));
    assertThat(getBody(body), is(Optional.empty()));
    assertThat(type.apply(body), is("GET"));
  }

  @Test
  public void delete() throws Exception {
    Request body = RequestBuilders.deleteBuilder()
        .path("/delete");
    assertThat(getPath(body), is("/delete"));
    assertThat(getBody(body), is(Optional.empty()));
    assertThat(type.apply(body), is("DELETE"));
  }

  @Test
  public void refs() {
    Request request = putBuilder()
        .path("/external/path")
        .body(getBody(putBuilder()
            .path("/internal/path")
            .body("body"))
            .orElse(""));
    assertThat(getPath(request), is("/external/path"));
  }
}


text:
Overview
--------

The sentinels module is a small utility providing the Sentinel class, along with useful instances.

What are Sentinels?
-------------------

Sentinels are objects with special meanings. They can be thought of as singletons, but they service the need of having 'special' values in your code, that have special meanings (see example below).

Why Do I Need Sentinels?
------------------------

Let's take *NOTHING* for example. This sentinel is automatically provided with the sentinels import::

  >>> from sentinels import NOTHING

Let's say you're writing a wrapper around a Python dictionary, which supports a special kind of method, *get_default_or_raise*. This method behaves like *get*, but when it does not receive a default and the key does not exist, it raises a *KeyError*. How would you implement such a thing? The naive method is this::

  >>> class MyDict(dict):
  ...     def get_default_or_raise(self, key, default=None):
  ...         if key not in self and default is None:
  ...             raise KeyError(key)
  ...         return self.get(key, default)

Or even this::

  >>> class MyDict(dict):
  ...     def get_default_or_raise(self, key, default=None):
  ...         returned = self.get(key, default)
  ...         if returned is None:
  ...             raise KeyError(key)
  ...         return returned

But the problem with the above two pieces of code is the same -- when writing a general utility class, we don't know how it will be used later on. More importantly, **None might be a perfectly valid dictionary value!**

This is where NOTHING comes in handy::

  >>> class MyDict(dict):
  ...     def get_default_or_raise(self, key, default=NOTHING):
  ...         returned = self.get(key, default)
  ...         if returned is NOTHING:
  ...             raise KeyError(key)
  ...         return returned

And Tada!

Semantics
---------

Sentinels are always equal to themselves::

  >>> NOTHING == NOTHING
  True

But never to another object::

  >>> from sentinels import Sentinel
  >>> NOTHING == 2
  False
  >>> NOTHING == "NOTHING"
  False

Copying sentinels returns the same object::

  >>> import copy
  >>> copy.deepcopy(NOTHING) is NOTHING
  True

And of course also pickling/unpickling::

  >>> import pickle
  >>> NOTHING is pickle.loads(pickle.dumps(NOTHING))
  True


text:
extern "C" {
#include "bspatch/bspatch.h"
}

// Resource compiled assets (cmds)
#ifdef DEPTHAI_RESOURCE_COMPILED_BINARIES
    #include "cmrc/cmrc.hpp"
CMRC_DECLARE(depthai);
#endif

namespace dai {

static std::vector<std::uint8_t> createPrebootHeader(const std::vector<uint8_t>& payload, uint32_t magic1, uint32_t magic2);

constexpr static auto CMRC_DEPTHAI_DEVICE_TAR_XZ = "depthai-device-fwp-" DEPTHAI_DEVICE_VERSION ".tar.xz";

// Main FW
constexpr static auto DEPTHAI_CMD_OPENVINO_2022_1_PATH = "depthai-device-openvino-2022.1-" DEPTHAI_DEVICE_VERSION ".cmd";
constexpr static auto MAIN_FW_PATH = DEPTHAI_CMD_OPENVINO_2022_1_PATH;
constexpr static auto& MAIN_FW_VERSION = OpenVINO::DEFAULT_VERSION;

// Patches from Main FW
constexpr static auto DEPTHAI_CMD_OPENVINO_2020_3_PATCH_PATH = "depthai-device-openvino-2020.3-" DEPTHAI_DEVICE_VERSION ".patch";
constexpr static auto DEPTHAI_CMD_OPENVINO_2020_4_PATCH_PATH = "depthai-device-openvino-2020.4-" DEPTHAI_DEVICE_VERSION ".patch";
constexpr static auto DEPTHAI_CMD_OPENVINO_2021_1_PATCH_PATH = "depthai-device-openvino-2021.1-" DEPTHAI_DEVICE_VERSION ".patch";
constexpr static auto DEPTHAI_CMD_OPENVINO_2021_2_PATCH_PATH = "depthai-device-openvino-2021.2-" DEPTHAI_DEVICE_VERSION ".patch";
constexpr static auto DEPTHAI_CMD_OPENVINO_2021_3_PATCH_PATH = "depthai-device-openvino-2021.3-" DEPTHAI_DEVICE_VERSION ".patch";

// Creates std::array without explicitly needing to state the size
template <typename V, typename... T>
static constexpr auto array_of(T&&... t) -> std::array<V, sizeof...(T)> {
    return {{std::forward<T>(t)...}};
}

constexpr static auto RESOURCE_LIST_DEVICE = array_of<const char*>(DEPTHAI_CMD_OPENVINO_2022_1_PATH,
                                                                   DEPTHAI_CMD_OPENVINO_2020_3_PATCH_PATH,
                                                                   DEPTHAI_CMD_OPENVINO_2020_4_PATCH_PATH,
                                                                   DEPTHAI_CMD_OPENVINO_2021_1_PATCH_PATH,
                                                                   DEPTHAI_CMD_OPENVINO_2021_2_PATCH_PATH,
                                                                   DEPTHAI_CMD_OPENVINO_2021_3_PATCH_PATH);

std::vector<std::uint8_t> Resources::getDeviceFirmware(Device::Config config, dai::Path pathToMvcmd) const {
    // Wait until lazy load is complete
    {
        std::unique_lock<std::mutex> lock(mtxDevice);
        cvDevice.wait(lock, [this]() { return readyDevice; });
    }

    std::vector<std::uint8_t> finalFwBinary;

    // Get OpenVINO version
    auto& version = config.version;

    // Check if pathToMvcmd variable is set
    dai::Path finalFwBinaryPath;
    if(!pathToMvcmd.empty()) {
        finalFwBinaryPath = pathToMvcmd;
    }
    // Override if env variable DEPTHAI_DEVICE_BINARY is set
    dai::Path fwBinaryPath = utility::getEnv("DEPTHAI_DEVICE_BINARY");
    if(!fwBinaryPath.empty()) {
        finalFwBinaryPath = fwBinaryPath;
    }
    // Return binary from file if any of above paths are present
    if(!finalFwBinaryPath.empty()) {
        // Load binary file at path
        std::ifstream stream(finalFwBinaryPath, std::ios::binary);
        if(!stream.is_open()) {
            // Throw an error
            // TODO(themarpe) - Unify exceptions into meaningful groups
            throw std::runtime_error(
                fmt::format("File at path {}{} doesn't exist.", finalFwBinaryPath, !fwBinaryPath.empty() ? " pointed to by DEPTHAI_DEVICE_BINARY" : ""));
        }
        spdlog::warn("Overriding firmware: {}", finalFwBinaryPath);
        // Read the file and return its contents
        finalFwBinary = std::vector<std::uint8_t>(std::istreambuf_iterator<char>(stream), {});
    } else {
// Binaries are resource compiled
#ifdef DEPTHAI_RESOURCE_COMPILED_BINARIES

        std::unordered_set<OpenVINO::Version> deprecatedVersions(
            {OpenVINO::VERSION_2020_4, OpenVINO::VERSION_2021_1, OpenVINO::VERSION_2021_2, OpenVINO::VERSION_2021_3});

        if(deprecatedVersions.count(version)) {
            spdlog::warn("OpenVINO {} is deprecated!", OpenVINO::getVersionName(version));
        }

        // Main FW
        std::vector<std::uint8_t> depthaiBinary;
        // Patch from main to specified
        std::vector<std::uint8_t> depthaiPatch;

        switch(version) {
            case OpenVINO::VERSION_2020_3:
                depthaiPatch = resourceMapDevice.at(DEPTHAI_CMD_OPENVINO_2020_3_PATCH_PATH);
                break;

            case OpenVINO::VERSION_2020_4:
                depthaiPatch = resourceMapDevice.at(DEPTHAI_CMD_OPENVINO_2020_4_PATCH_PATH);
                break;

            case OpenVINO::VERSION_2021_1:
                depthaiPatch = resourceMapDevice.at(DEPTHAI_CMD_OPENVINO_2021_1_PATCH_PATH);
                break;

            case OpenVINO::VERSION_2021_2:
                depthaiPatch = resourceMapDevice.at(DEPTHAI_CMD_OPENVINO_2021_2_PATCH_PATH);
                break;

            case OpenVINO::VERSION_2021_3:
                depthaiPatch = resourceMapDevice.at(DEPTHAI_CMD_OPENVINO_2021_3_PATCH_PATH);
                break;

            case OpenVINO::VERSION_2021_4:
            case MAIN_FW_VERSION:
                depthaiBinary = resourceMapDevice.at(MAIN_FW_PATH);
                break;
        }

        // is patching required?
        if(!depthaiPatch.empty()) {
            spdlog::debug("Patching OpenVINO FW version from {} to {}", OpenVINO::getVersionName(MAIN_FW_VERSION), OpenVINO::getVersionName(version));

            // Load full binary for patch
            depthaiBinary = resourceMapDevice.at(MAIN_FW_PATH);

            // Get new size
            int64_t patchedSize = bspatch_mem_get_newsize(depthaiPatch.data(), depthaiPatch.size());

            // Reserve space for patched binary
            std::vector<std::uint8_t> tmpDepthaiBinary{};
            tmpDepthaiBinary.resize(patchedSize);

            // Patch
            int error = bspatch_mem(depthaiBinary.data(), depthaiBinary.size(), depthaiPatch.data(), depthaiPatch.size(), tmpDepthaiBinary.data());

            // if patch not successful
            if(error > 0) {
                throw std::runtime_error(fmt::format(
                    "Error while patching OpenVINO FW version from {} to {}", OpenVINO::getVersionName(MAIN_FW_VERSION), OpenVINO::getVersionName(version)));
            }

            // Change depthaiBinary to tmpDepthaiBinary
            depthaiBinary = std::move(tmpDepthaiBinary);
        }

        finalFwBinary = std::move(depthaiBinary);

#else
        // Binaries from default path (TODO)

#endif
    }

    // Prepend preboot config
    // Serialize preboot
    auto prebootPayload = utility::serialize(config.board);
    auto prebootHeader = createPrebootHeader(prebootPayload, BOARD_CONFIG_MAGIC1, BOARD_CONFIG_MAGIC2);
    finalFwBinary.insert(finalFwBinary.begin(), prebootHeader.begin(), prebootHeader.end());

    // Return created firmware
    return finalFwBinary;
}

constexpr static auto CMRC_DEPTHAI_BOOTLOADER_TAR_XZ = "depthai-bootloader-fwp-" DEPTHAI_BOOTLOADER_VERSION ".tar.xz";
constexpr static auto DEVICE_BOOTLOADER_USB_PATH = "depthai-bootloader-usb.cmd";
constexpr static auto DEVICE_BOOTLOADER_ETH_PATH = "depthai-bootloader-eth.cmd";

constexpr static std::array<const char*, 2> RESOURCE_LIST_BOOTLOADER = {
    DEVICE_BOOTLOADER_USB_PATH,
    DEVICE_BOOTLOADER_ETH_PATH,
};

std::vector<std::uint8_t> Resources::getBootloaderFirmware(dai::bootloader::Type type) const {
    // Wait until lazy load is complete
    {
        std::unique_lock<std::mutex> lock(mtxBootloader);
        cvDevice.wait(lock, [this]() { return readyBootloader; });
    }

    // Check if env variable DEPTHAI_BOOTLOADER_BINARY_USB/_ETH is set
    std::string blEnvVar;
    if(type == dai::bootloader::Type::USB) {
        blEnvVar = "DEPTHAI_BOOTLOADER_BINARY_USB";
    } else if(type == dai::bootloader::Type::NETWORK) {
        blEnvVar = "DEPTHAI_BOOTLOADER_BINARY_ETH";
    }
    dai::Path blBinaryPath = utility::getEnv(blEnvVar);
    if(!blBinaryPath.empty()) {
        // Load binary file at path
        std::ifstream stream(blBinaryPath, std::ios::binary);
        if(!stream.is_open()) {
            // Throw an error
            // TODO(themarpe) - Unify exceptions into meaningful groups
            throw std::runtime_error(fmt::format("File at path {} pointed to by {} doesn't exist.", blBinaryPath, blEnvVar));
        }
        spdlog::warn("Overriding bootloader {}: {}", blEnvVar, blBinaryPath);
        // Read the file and return its content
        return std::vector<std::uint8_t>(std::istreambuf_iterator<char>(stream), {});
    }

    switch(type) {
        case dai::bootloader::Type::AUTO:
            throw std::invalid_argument("DeviceBootloader::Type::AUTO not allowed, when getting bootloader firmware.");
            break;

        case dai::bootloader::Type::USB:
            return resourceMapBootloader.at(DEVICE_BOOTLOADER_USB_PATH);
            break;

        case dai::bootloader::Type::NETWORK:
            return resourceMapBootloader.at(DEVICE_BOOTLOADER_ETH_PATH);
            break;

        default:
            throw std::invalid_argument("Invalid Bootloader Type specified.");
            break;
    }
}

Resources& Resources::getInstance() {
    static Resources instance;  // Guaranteed to be destroyed, instantiated on first use.
    return instance;
}

template <typename CV, typename BOOL, typename MTX, typename PATH, typename LIST, typename MAP>
std::function<void()> getLazyTarXzFunction(MTX& mtx, CV& cv, BOOL& ready, PATH cmrcPath, LIST& resourceList, MAP& resourceMap) {
    return [&mtx, &cv, &ready, cmrcPath, &resourceList, &resourceMap] {
        using namespace std::chrono;

        // Get binaries from internal sources
        auto fs = cmrc::depthai::get_filesystem();
        auto tarXz = fs.open(cmrcPath);

        auto t1 = steady_clock::now();

        // Load tar.xz archive from memory
        struct archive* a = archive_read_new();
        archive_read_support_filter_xz(a);
        archive_read_support_format_tar(a);
        int r = archive_read_open_memory(a, tarXz.begin(), tarXz.size());
        assert(r == ARCHIVE_OK);

        auto t2 = steady_clock::now();

        struct archive_entry* entry;
        while(archive_read_next_header(a, &entry) == ARCHIVE_OK) {
            // Check whether filename matches to one of required resources
            for(const auto& cpath : resourceList) {
                std::string resPath(cpath);
                if(resPath == std::string(archive_entry_pathname(entry))) {
                    // Create an emtpy entry
                    resourceMap[resPath] = std::vector<std::uint8_t>();

                    // Read size, 16KiB
                    std::size_t readSize = 16 * 1024;
                    if(archive_entry_size_is_set(entry)) {
                        // if size is specified, use that for read size
                        readSize = archive_entry_size(entry);
                    }

                    // Record number of bytes actually read
                    long long finalSize = 0;

                    while(true) {
                        // Current size, as a offset to write next data to
                        auto currentSize = resourceMap[resPath].size();

                        // Resize to accomodate for extra data
                        resourceMap[resPath].resize(currentSize + readSize);
                        long long size = archive_read_data(a, &resourceMap[resPath][currentSize], readSize);

                        // Assert that no errors occurred
                        assert(size >= 0);

                        // Append number of bytes actually read to finalSize
                        finalSize += size;

                        // All bytes were read
                        if(size == 0) {
                            break;
                        }
                    }

                    // Resize vector to actual read size
                    resourceMap[resPath].resize(finalSize);

                    // Entry found - go to next required resource
                    break;
                }
            }
        }
        r = archive_read_free(a);  // Note 3
        assert(r == ARCHIVE_OK);
        // Ignore 'r' variable when in Release build
        (void)r;

        // Check that all resources were read
        for(const auto& cpath : resourceList) {
            std::string resPath(cpath);
            assert(resourceMap.count(resPath) > 0);
        }

        auto t3 = steady_clock::now();

        // Debug - logs loading times
        spdlog::debug(
            "Resources - Archive '{}' open: {}, archive read: {}", cmrcPath, duration_cast<milliseconds>(t2 - t1), duration_cast<milliseconds>(t3 - t2));

        // Notify that that preload is finished
        {
            std::unique_lock<std::mutex> l(mtx);
            ready = true;
        }
        cv.notify_all();
    };
}

Resources::Resources() {
    // Preinit libarchive
    struct archive* a = archive_read_new();
    auto r = archive_read_free(a);
    assert(r == ARCHIVE_OK);
    // Ignore 'r' variable when in Release build
    (void)r;

    // Device resources
    // Create a thread which lazy-loads firmware resources package
    lazyThreadDevice = std::thread(getLazyTarXzFunction(mtxDevice, cvDevice, readyDevice, CMRC_DEPTHAI_DEVICE_TAR_XZ, RESOURCE_LIST_DEVICE, resourceMapDevice));

    // Bootloader resources
    // Create a thread which lazy-loads firmware resources package
    lazyThreadBootloader = std::thread(
        getLazyTarXzFunction(mtxBootloader, cvBootloader, readyBootloader, CMRC_DEPTHAI_BOOTLOADER_TAR_XZ, RESOURCE_LIST_BOOTLOADER, resourceMapBootloader));
}

Resources::~Resources() {
    // join the lazy threads
    if(lazyThreadDevice.joinable()) lazyThreadDevice.join();
    if(lazyThreadBootloader.joinable()) lazyThreadBootloader.join();
}

// Get device firmware
std::vector<std::uint8_t> Resources::getDeviceFirmware(bool usb2Mode, OpenVINO::Version version) const {
    Device::Config cfg;
    if(usb2Mode) {
        cfg.board.usb.maxSpeed = UsbSpeed::HIGH;
    } else {
        cfg.board.usb.maxSpeed = Device::DEFAULT_USB_SPEED;
    }
    cfg.version = version;

    return getDeviceFirmware(cfg);
}

std::vector<std::uint8_t> createPrebootHeader(const std::vector<uint8_t>& payload, uint32_t magic1, uint32_t magic2) {
    // clang-format off
    const std::uint8_t HEADER[] = {77, 65, 50, 120,
                                   // WD Protection
                                   // TODO(themarpe) - expose timings
                                   0x9A, 0xA8, 0x00, 0x32, 0x20, 0xAD, 0xDE, 0xD0, 0xF1,
                                   0x9A, 0x9C, 0x00, 0x32, 0x20, 0xFF, 0xFF, 0xFF, 0xFF,
                                   0x9A, 0xA8, 0x00, 0x32, 0x20, 0xAD, 0xDE, 0xD0, 0xF1,
                                   0x9A, 0xA4, 0x00, 0x32, 0x20, 0x01, 0x00, 0x00, 0x00,
                                   0x8A,
                                   static_cast<uint8_t>((magic1 >> 0) & 0xFF),
                                   static_cast<uint8_t>((magic1 >> 8) & 0xFF),
                                   static_cast<uint8_t>((magic1 >> 16) & 0xFF),
                                   static_cast<uint8_t>((magic1 >> 24) & 0xFF)};
    // clang-format on

    // Store the constructed board information
    std::vector<std::uint8_t> prebootHeader;

    // Store initial header
    prebootHeader.insert(prebootHeader.begin(), std::begin(HEADER), std::end(HEADER));

    // Calculate size
    std::size_t totalPayloadSize = payload.size() + sizeof(magic2) + sizeof(uint32_t) + sizeof(uint32_t);
    std::size_t toAddBytes = 0;
    if(totalPayloadSize % 4 != 0) {
        toAddBytes = 4 - (totalPayloadSize % 4);
    }
    std::size_t totalSize = totalPayloadSize + toAddBytes;
    std::size_t totalSizeWord = totalSize / 4;

    // Write size in words in little endian
    prebootHeader.push_back((totalSizeWord >> 0) & 0xFF);
    prebootHeader.push_back((totalSizeWord >> 8) & 0xFF);

    // Compute payload checksum
    auto checksum = utility::checksum(payload.data(), payload.size());

    // Write checksum & payload size as uint32_t LE
    for(const auto& field : {magic2, checksum, static_cast<uint32_t>(payload.size())}) {
        for(int i = 0; i < 4; i++) {
            prebootHeader.push_back((field >> (i * 8)) & 0xFF);
        }
    }

    // Copy payload
    prebootHeader.insert(prebootHeader.end(), payload.begin(), payload.end());
    // Add missing bytes
    for(std::size_t i = 0; i < toAddBytes; i++) {
        prebootHeader.push_back(0x00);
    }

    return prebootHeader;
}

}  // namespace dai


text:
package gardener_test

import (
	"code.cloudfoundry.org/garden"
	"code.cloudfoundry.org/guardian/gardener"
	"code.cloudfoundry.org/lager/lagertest"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("NoopVolumizer", func() {
	var volumizer gardener.NoopVolumizer

	var logger *lagertest.TestLogger

	BeforeEach(func() {
		volumizer = gardener.NoopVolumizer{}

		logger = lagertest.NewTestLogger("test")
	})

	Describe("Create", func() {
		It("returns ErrGraphDisabled", func() {
			_, err := volumizer.Create(logger, "some-handle", gardener.RootfsSpec{})
			Expect(err).To(Equal(gardener.ErrGraphDisabled))
		})
	})

	Describe("Destroy", func() {
		It("succeeds, as destroying is idempotent and may be actually called redundantly", func() {
			Expect(volumizer.Destroy(logger, "some-handle")).To(BeNil())
		})
	})

	Describe("Metrics", func() {
		It("successfully returns an empty set of metrics", func() {
			Expect(volumizer.Metrics(logger, "some-handle", false)).To(Equal(garden.ContainerDiskStat{}))
		})
	})

	Describe("GC", func() {
		It("succeeds", func() {
			Expect(volumizer.GC(logger)).To(BeNil())
		})
	})
})


text:
module ApplicationHelper
  include Rails.application.routes.url_helpers
def full_title(page_title)
  base_title = "VatOnWheels"
  if page_title.empty?
    base_title
  else
    "#{base_title} | #{page_title}"
  end
end
def root_detector()
  if current_page?(root_url)
    return true
  else
    return false
  end
end

  def link_to_remove_fields(name, f)
    f.hidden_field(:_destroy) + link_to_function(image_tag('button_cancel_256.png'), "remove_fields(this)")
  end

  def link_to_add_fields(name, f, association)
    new_object = f.object.class.reflect_on_association(association).klass.new
    fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder|
      render("shared/"+association.to_s.singularize + "_fields", :f => builder)
    end
    link_to_function(name, ("add_fields(this,\"#{association}\",\"#{escape_javascript(fields)}\")"), class: "btn btn-info")
  end

end


text:
CREATE TABLE IF NOT EXISTS scd_cells_operations (
    cell_id INT64 NOT NULL,
    cell_level INT CHECK (
        cell_level BETWEEN 0
        and 30
    ),
    operation_id UUID NOT NULL REFERENCES scd_operations (id) ON DELETE CASCADE,
    PRIMARY KEY (cell_id, operation_id),
    INDEX cell_id_idx (cell_id),
    INDEX operation_id_idx (operation_id)
);

-- Restore cells data in scd_cells_operations
BEGIN;

INSERT INTO
    scd_cells_operations (cell_id, operation_id)
SELECT
    DISTINCT unnest(cells) as cell_id,
    id
from
    scd_operations;

COMMIT;

-- Restore Table scd_cells_subscriptions
CREATE TABLE IF NOT EXISTS scd_cells_subscriptions (
    cell_id INT64 NOT NULL,
    cell_level INT CHECK (
        cell_level BETWEEN 0
        and 30
    ),
    subscription_id UUID NOT NULL REFERENCES scd_subscriptions (id) ON DELETE CASCADE,
    PRIMARY KEY (cell_id, subscription_id),
    INDEX cell_id_idx (cell_id),
    INDEX subscription_id_idx (subscription_id)
);

-- Restore cells data in scd_cells_subscriptions
BEGIN;

INSERT INTO
    scd_cells_subscriptions (cell_id, subscription_id)
SELECT
    DISTINCT unnest(cells) as cell_id,
    id
from
    scd_subscriptions;

COMMIT;

-- Remove inverted index for scd_subscriptions
DROP INDEX IF EXISTS scd_subscriptions@cell_idx;

ALTER TABLE
    scd_subscriptions DROP IF EXISTS cells;

-- Remove inverted index for scd_operations
DROP INDEX IF EXISTS scd_operations@cell_idx;

ALTER TABLE
    scd_operations DROP IF EXISTS cells;

UPDATE
    schema_versions
set
    schema_version = 'v2.0.0'
WHERE
    onerow_enforcer = TRUE;


text:
#ifndef LEAPPROCESS_H_
#define LEAPPROCESS_H_

#include "RecognitionModule/StaticRec.h"
#include "RecognitionModule/FingerDiff.h"

#include "includes.h"
#include "RecognizedGesture.h"

using namespace Leap;

class LeapListener;

class LeapProcess {
public:

	void (*f)();
	pthread_mutex_t mutexDyn, mutexStat, finished;
	pthread_t dynamicProcess, staticProcess;
	Controller controller;

	LeapProcess(RecognizedGestureListener *rg, bool enableStatic, bool enableDynamic);
	void start();
	void stop();
	void loadFrame(GestureFrame *frame);
	void loadFrameClone(GestureFrame frame);
	void *staticThread(void);
	void *dynamicThread(void);
	static void *runStatic(void *c);
	static void *runDynamic(void *c);
	TestingStaticRecConf *staticConf;

private:
	RecognizedGestureListener *rg;
	Controller lm;
	GestureFrame *dataFrame;
	GestureFrame g;
	bool enableStatic, enableDynamic;
};

#endif /* LEAPPROCESS_H_ */


text:
from .. import types, functions
from ... import utils

class InlineResult:
    """
    Custom class that encapsulates a bot inline result providing
    an abstraction to easily access some commonly needed features
    (such as clicking a result to select it).

    Attributes:

        result (:tl:`BotInlineResult`):
            The original :tl:`BotInlineResult` object.
    """
    # tdlib types are the following (InlineQueriesManager::answer_inline_query @ 1a4a834):
    # gif, article, audio, contact, file, geo, photo, sticker, venue, video, voice
    #
    # However, those documented in https://core.telegram.org/bots/api#inline-mode are different.
    ARTICLE = 'article'
    PHOTO = 'photo'
    GIF = 'gif'
    VIDEO = 'video'
    VIDEO_GIF = 'mpeg4_gif'
    AUDIO = 'audio'
    DOCUMENT = 'document'
    LOCATION = 'location'
    VENUE = 'venue'
    CONTACT = 'contact'
    GAME = 'game'

    def __init__(self, client, original, query_id=None, *, entity=None):
        self._client = client
        self.result = original
        self._query_id = query_id
        self._entity = entity

    @property
    def type(self):
        """
        The always-present type of this result. It will be one of:
        ``'article'``, ``'photo'``, ``'gif'``, ``'mpeg4_gif'``, ``'video'``,
        ``'audio'``, ``'voice'``, ``'document'``, ``'location'``, ``'venue'``,
        ``'contact'``, ``'game'``.

        You can access all of these constants through `InlineResult`,
        such as `InlineResult.ARTICLE`, `InlineResult.VIDEO_GIF`, etc.
        """
        return self.result.type

    @property
    def message(self):
        """
        The always-present :tl:`BotInlineMessage` that
        will be sent if `click` is called on this result.
        """
        return self.result.send_message

    @property
    def title(self):
        """
        The title for this inline result. It may be `None`.
        """
        return self.result.title

    @property
    def description(self):
        """
        The description for this inline result. It may be `None`.
        """
        return self.result.description

    @property
    def url(self):
        """
        The URL present in this inline results. If you want to "click"
        this URL to open it in your browser, you should use Python's
        `webbrowser.open(url)` for such task.
        """
        if isinstance(self.result, types.BotInlineResult):
            return self.result.url

    @property
    def photo(self):
        """
        Returns either the :tl:`WebDocument` thumbnail for
        normal results or the :tl:`Photo` for media results.
        """
        if isinstance(self.result, types.BotInlineResult):
            return self.result.thumb
        elif isinstance(self.result, types.BotInlineMediaResult):
            return self.result.photo

    @property
    def document(self):
        """
        Returns either the :tl:`WebDocument` content for
        normal results or the :tl:`Document` for media results.
        """
        if isinstance(self.result, types.BotInlineResult):
            return self.result.content
        elif isinstance(self.result, types.BotInlineMediaResult):
            return self.result.document

    async def click(self, entity=None, reply_to=None, comment_to=None,
                    silent=False, clear_draft=False, hide_via=False,
                    background=None):
        """
        Clicks this result and sends the associated `message`.

        Args:
            entity (`entity`):
                The entity to which the message of this result should be sent.

            reply_to (`int` | `Message <telethon.tl.custom.message.Message>`, optional):
                If present, the sent message will reply to this ID or message.

            comment_to (`int` | `Message <telethon.tl.custom.message.Message>`, optional):
                Similar to ``reply_to``, but replies in the linked group of a
                broadcast channel instead (effectively leaving a "comment to"
                the specified message).

            silent (`bool`, optional):
                Whether the message should notify people with sound or not.
                Defaults to `False` (send with a notification sound unless
                the person has the chat muted). Set it to `True` to alter
                this behaviour.

            clear_draft (`bool`, optional):
                Whether the draft should be removed after sending the
                message from this result or not. Defaults to `False`.

            hide_via (`bool`, optional):
                Whether the "via @bot" should be hidden or not.
                Only works with certain bots (like @bing or @gif).

            background (`bool`, optional):
                Whether the message should be send in background.

        """
        if entity:
            entity = await self._client.get_input_entity(entity)
        elif self._entity:
            entity = self._entity
        else:
            raise ValueError('You must provide the entity where the result should be sent to')

        if comment_to:
            entity, reply_id = await self._client._get_comment_data(entity, comment_to)
        else:
            reply_id = None if reply_to is None else utils.get_message_id(reply_to)

        req = functions.messages.SendInlineBotResultRequest(
            peer=entity,
            query_id=self._query_id,
            id=self.result.id,
            silent=silent,
            background=background,
            clear_draft=clear_draft,
            hide_via=hide_via,
            reply_to_msg_id=reply_id
        )
        return self._client._get_response_message(
            req, await self._client(req), entity)

    async def download_media(self, *args, **kwargs):
        """
        Downloads the media in this result (if there is a document, the
        document will be downloaded; otherwise, the photo will if present).

        This is a wrapper around `client.download_media
        <telethon.client.downloads.DownloadMethods.download_media>`.
        """
        if self.document or self.photo:
            return await self._client.download_media(
                self.document or self.photo, *args, **kwargs)


text:
sappari
=======

Sappari aims to be a fast and easy-to-use web CMS.


text:
@ParametersAreNonnullByDefault
package org.zalando.problem.spring.webflux.advice;

import javax.annotation.ParametersAreNonnullByDefault;


text:
.. _biclustering:

============
Biclustering
============

Biclustering can be performed with the module
:mod:`sklearn.cluster.bicluster`. Biclustering algorithms simultaneously
cluster rows and columns of a data matrix. These clusters of rows and
columns are known as biclusters. Each determines a submatrix of the
original data matrix with some desired properties.

For instance, given a matrix of shape ``(10, 10)``, one possible bicluster
with three rows and two columns induces a submatrix of shape ``(3, 2)``::

    >>> import numpy as np
    >>> data = np.arange(100).reshape(10, 10)
    >>> rows = np.array([0, 2, 3])[:, np.newaxis]
    >>> columns = np.array([1, 2])
    >>> data[rows, columns]
    array([[ 1,  2],
           [21, 22],
           [31, 32]])

For visualization purposes, given a bicluster, the rows and columns of
the data matrix may be rearranged to make the bicluster contiguous.

Algorithms differ in how they define biclusters. Some of the
common types include:

* constant values, constant rows, or constant columns
* unusually high or low values
* submatrices with low variance
* correlated rows or columns

Algorithms also differ in how rows and columns may be assigned to
biclusters, which leads to different bicluster structures. Block
diagonal or checkerboard structures occur when rows and columns are
divided into partitions.

If each row and each column belongs to exactly one bicluster, then
rearranging the rows and columns of the data matrix reveals the
biclusters on the diagonal. Here is an example of this structure
where biclusters have higher average values than the other rows and
columns:

.. figure:: ../auto_examples/bicluster/images/plot_spectral_coclustering_003.png
   :target: ../auto_examples/bicluster/images/plot_spectral_coclustering_003.png
   :align: center
   :scale: 50

   An example of biclusters formed by partitioning rows and columns.

In the checkerboard case, each row belongs to all column clusters, and
each column belongs to all row clusters. Here is an example of this
structure where the variance of the values within each bicluster is
small:

.. figure:: ../auto_examples/bicluster/images/plot_spectral_biclustering_003.png
   :target: ../auto_examples/bicluster/images/plot_spectral_biclustering_003.png
   :align: center
   :scale: 50

   An example of checkerboard biclusters.

After fitting a model, row and column cluster membership can be found
in the ``rows_`` and ``columns_`` attributes. ``rows_[i]`` is a binary vector
with nonzero entries corresponding to rows that belong to bicluster
``i``. Similarly, ``columns_[i]`` indicates which columns belong to
bicluster ``i``.

Some models also have ``row_labels_`` and ``column_labels_`` attributes.
These models partition the rows and columns, such as in the block
diagonal and checkerboard bicluster structures.

.. note::

    Biclustering has many other names in different fields including
    co-clustering, two-mode clustering, two-way clustering, block
    clustering, coupled two-way clustering, etc. The names of some
    algorithms, such as the Spectral Co-Clustering algorithm, reflect
    these alternate names.

.. currentmodule:: sklearn.cluster.bicluster

.. _spectral_coclustering:

Spectral Co-Clustering
======================

The :class:`SpectralCoclustering` algorithm finds biclusters with
values higher than those in the corresponding other rows and columns.
Each row and each column belongs to exactly one bicluster, so
rearranging the rows and columns to make partitions contiguous reveals
these high values along the diagonal:

.. note::

    The algorithm treats the input data matrix as a bipartite graph: the
    rows and columns of the matrix correspond to the two sets of vertices,
    and each entry corresponds to an edge between a row and a column. The
    algorithm approximates the normalized cut of this graph to find heavy
    subgraphs.

Mathematical formulation
------------------------

An approximate solution to the optimal normalized cut may be found via
the generalized eigenvalue decomposition of the Laplacian of the
graph. Usually this would mean working directly with the Laplacian
matrix. If the original data matrix :math:`A` has shape :math:`m
\times n`, the Laplacian matrix for the corresponding bipartite graph
has shape :math:`(m + n) \times (m + n)`. However, in this case it is
possible to work directly with :math:`A`, which is smaller and more
efficient.

The input matrix :math:`A` is preprocessed as follows:

.. math::
    A_n = R^{-1/2} A C^{-1/2}

Where :math:`R` is the diagonal matrix with entry :math:`i` equal to
:math:`\sum_{j} A_{ij}` and :math:`C` is the diagonal matrix with
entry :math:`j` equal to :math:`\sum_{i} A_{ij}`.

The singular value decomposition, :math:`A_n = U \Sigma V^\top`,
provides the partitions of the rows and columns of :math:`A`. A subset
of the left singular vectors gives the row partitions, and a subset
of the right singular vectors gives the column partitions.

The :math:`\ell = \lceil \log_2 k \rceil` singular vectors, starting
from the second, provide the desired partitioning information. They
are used to form the matrix :math:`Z`:

.. math::
    Z = \begin{bmatrix} R^{-1/2} U \\\\
                        C^{-1/2} V
          \end{bmatrix}

where the columns of :math:`U` are :math:`u_2, \dots, u_{\ell +
1}`, and similarly for :math:`V`.

Then the rows of :math:`Z` are clustered using :ref:`k-means
<k_means>`. The first ``n_rows`` labels provide the row partitioning,
and the remaining ``n_columns`` labels provide the column partitioning.

.. topic:: Examples:

 * :ref:`example_bicluster_plot_spectral_coclustering.py`: A simple example
   showing how to generate a data matrix with biclusters and apply
   this method to it.

 * :ref:`example_bicluster_bicluster_newsgroups.py`: An example of finding
   biclusters in the twenty newsgroup dataset.

.. topic:: References:

 * Dhillon, Inderjit S, 2001. `Co-clustering documents and words using
   bipartite spectral graph partitioning
   <http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.140.3011>`__.

.. _spectral_biclustering:

Spectral Biclustering
=====================

The :class:`SpectralBiclustering` algorithm assumes that the input
data matrix has a hidden checkerboard structure. The rows and columns
of a matrix with this structure may be partitioned so that the entries
of any bicluster in the Cartesian product of row clusters and column
clusters are approximately constant. For instance, if there are two
row partitions and three column partitions, each row will belong to
three biclusters, and each column will belong to two biclusters.

The algorithm partitions the rows and columns of a matrix so that a
corresponding blockwise-constant checkerboard matrix provides a good
approximation to the original matrix.

Mathematical formulation
------------------------

The input matrix :math:`A` is first normalized to make the
checkerboard pattern more obvious. There are three possible methods:

1. *Independent row and column normalization*, as in Spectral
   Co-Clustering. This method makes the rows sum to a constant and the
   columns sum to a different constant.

2. **Bistochastization**: repeated row and column normalization until
   convergence. This method makes both rows and columns sum to the
   same constant.

3. **Log normalization**: the log of the data matrix is computed: :math:`L =
   \log A`. Then the column mean :math:`\overline{L_{i \cdot}}`, row mean
   :math:`\overline{L_{\cdot j}}`, and overall mean :math:`\overline{L_{\cdot
   \cdot}}` of :math:`L` are computed. The final matrix is computed
   according to the formula

.. math::
    K_{ij} = L_{ij} - \overline{L_{i \cdot}} - \overline{L_{\cdot
    j}} + \overline{L_{\cdot \cdot}}

After normalizing, the first few singular vectors are computed, just
as in the Spectral Co-Clustering algorithm.

If log normalization was used, all the singular vectors are
meaningful. However, if independent normalization or bistochastization
were used, the first singular vectors, :math:`u_1` and :math:`v_1`.
are discarded. From now on, the "first" singular vectors refers to
:math:`u_2 \dots u_{p+1}` and :math:`v_2 \dots v_{p+1}` except in the
case of log normalization.

Given these singular vectors, they are ranked according to which can
be best approximated by a piecewise-constant vector. The
approximations for each vector are found using one-dimensional k-means
and scored using the Euclidean distance. Some subset of the best left
and right singular vector are selected. Next, the data is projected to
this best subset of singular vectors and clustered.

For instance, if :math:`p` singular vectors were calculated, the
:math:`q` best are found as described, where :math:`q<p`. Let
:math:`U` be the matrix with columns the :math:`q` best left singular
vectors, and similarly :math:`V` for the right. To partition the rows,
the rows of :math:`A` are projected to a :math:`q` dimensional space:
:math:`A * V`. Treating the :math:`m` rows of this :math:`m \times q`
matrix as samples and clustering using k-means yields the row labels.
Similarly, projecting the columns to :math:`A^{\top} * U` and
clustering this :math:`n \times q` matrix yields the column labels.

.. topic:: Examples:

 * :ref:`example_bicluster_plot_spectral_biclustering.py`: a simple example
   showing how to generate a checkerboard matrix and bicluster it.

.. topic:: References:

 * Kluger, Yuval, et. al., 2003. `Spectral biclustering of microarray
   data: coclustering genes and conditions
   <http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.135.1608>`__.

.. _biclustering_evaluation:

.. currentmodule:: sklearn.metrics

Biclustering evaluation
=======================

There are two ways of evaluating a biclustering result: internal and
external. Internal measures, such as cluster stability, rely only on
the data and the result themselves. Currently there are no internal
bicluster measures in scikit-learn. External measures refer to an
external source of information, such as the true solution. When
working with real data the true solution is usually unknown, but
biclustering artificial data may be useful for evaluating algorithms
precisely because the true solution is known.

To compare a set of found biclusters to the set of true biclusters,
two similarity measures are needed: a similarity measure for
individual biclusters, and a way to combine these individual
similarities into an overall score.

To compare individual biclusters, several measures have been used. For
now, only the Jaccard index is implemented:

.. math::
    J(A, B) = \frac{|A \cap B|}{|A| + |B| - |A \cap B|}

where :math:`A` and :math:`B` are biclusters, :math:`|A \cap B|` is
the number of elements in their intersection. The Jaccard index
achieves its minimum of 0 when the biclusters to not overlap at all
and its maximum of 1 when they are identical.

Several methods have been developed to compare two sets of biclusters.
For now, only :func:`consensus_score` (Hochreiter et. al., 2010) is
available:

1. Compute bicluster similarities for pairs of biclusters, one in each
   set, using the Jaccard index or a similar measure.

2. Assign biclusters from one set to another in a one-to-one fashion
   to maximize the sum of their similarities. This step is performed
   using the Hungarian algorithm.

3. The final sum of similarities is divided by the size of the larger
   set.

The minimum consensus score, 0, occurs when all pairs of biclusters
are totally dissimilar. The maximum score, 1, occurs when both sets
are identical.

.. topic:: References:

 * Hochreiter, Bodenhofer, et. al., 2010. `FABIA: factor analysis
   for bicluster acquisition
   <https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2881408/>`__.


text:
package ru.apetrov.Query;

import org.junit.Test;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

/**
 * Created by Andrey on 31.10.2017.
 */
public class QueryFiltersTest {

    /**
     * запрос с фильтром равно.
     */
    @Test
    public void testEquallyFilter() {
        QueryFilters queryFilters = new QueryFilters("*", "user");
        Filter filter = queryFilters.select(0);
        String result = filter.execute("id", "5");
        String expected = "SELECT * FROM user AS u WHERE u.id = 5;";
        assertThat(expected, is(result));
    }

    /**
     * запрос с фильтром больше.
     */
    @Test
    public void testLargerFilter() {
        QueryFilters queryFilters1 = new QueryFilters("*", "user");
        Filter filter = queryFilters1.select(1);
        String result = filter.execute("id", "5");
        String expected = "SELECT * FROM user AS u WHERE u.id > 5;";
        assertThat(expected, is(result));
    }

    /**
     * запрос с фильтром меньше.
     */
    @Test
    public void testSmallerFilter() {
        QueryFilters queryFilters2 = new QueryFilters("*", "user");
        Filter filter = queryFilters2.select(2);
        String result = filter.execute("id", "5");
        String expected = "SELECT * FROM user AS u WHERE u.id < 5;";
        assertThat(expected, is(result));
    }

    /**
     * запрос с фильтром содержит.
     */
    @Test
    public void testContainsFilter() {
        QueryFilters queryFilters3 = new QueryFilters("*", "user");
        Filter filter = queryFilters3.select(3);
        String result = filter.execute("id", "DIT");
        String expected = "SELECT * FROM user AS u WHERE u.id LIKE '%DIT%';";
        assertThat(expected, is(result));
    }

}


text:
typedef void wxWindow;
#define wxYES                   CClientUIInterface::BTN_YES
#define wxOK                    CClientUIInterface::BTN_OK
#define wxNO                    CClientUIInterface::BTN_NO
#define wxYES_NO                (wxYES|wxNO)
#define wxCANCEL                CClientUIInterface::BTN_CANCEL
#define wxAPPLY                 CClientUIInterface::BTN_APPLY
#define wxCLOSE                 CClientUIInterface::BTN_CLOSE
#define wxOK_DEFAULT            0
#define wxYES_DEFAULT           0
#define wxNO_DEFAULT            0
#define wxCANCEL_DEFAULT        0
#define wxICON_EXCLAMATION      0
#define wxICON_HAND             CClientUIInterface::MSG_ERROR
#define wxICON_WARNING          wxICON_EXCLAMATION
#define wxICON_ERROR            wxICON_HAND
#define wxICON_QUESTION         0
#define wxICON_INFORMATION      CClientUIInterface::ICON_INFORMATION
#define wxICON_STOP             wxICON_HAND
#define wxICON_ASTERISK         wxICON_INFORMATION
#define wxICON_MASK             CClientUIInterface::ICON_MASK
#define wxFORWARD               0
#define wxBACKWARD              0
#define wxRESET                 0
#define wxHELP                  0
#define wxMORE                  0
#define wxSETUP                 0

inline int MyMessageBox(const std::string& message, const std::string& caption="Message", int style=wxOK, wxWindow* parent=NULL, int x=-1, int y=-1)
{
    return uiInterface.ThreadSafeMessageBox(message, caption, style);
}

#define wxMessageBox MyMessageBox

inline void CalledSetStatusBar(const std::string& strText, int nField)
{
}

inline void UIThreadCall(boost::function0<void> fn)
{
}

inline void CreateMainWindow()
{
}

inline void SetStartOnSystemStartup(bool dummy)
{
}

#endif
#endif