text:
package de.gurkenlabs.litiengine.input;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.EventListener;

/** The {@code IKeyboard} interface is the engine's API for receiving keyboard input events. */
public interface IKeyboard {

  /**
   * Specifies whether the engine should consume key events with the ALT modifier.
   *
   *

   * This is useful to prevent unintended behavior of the default key processing.
   *
   * @param consume
   *          True if the events with the ALT modifier should be consumed.
   * @see KeyEvent#consume()
   * @see KeyEvent#isAltDown()
   */
  void consumeAlt(boolean consume);

  /**
   * Checks whether the key with the specified {@code keyCode} is currently being pressed.
   *
   * @param keyCode
   *          The keyCode to check for.
   * @return True if the key with the specified code is currently pressed.
   * @see #onKeyPressed(KeyPressedListener)
   * @see #onKeyPressed(int, KeyPressedListener)
   */
  boolean isPressed(int keyCode);

  /**
   * Checks whether the key with the specified {@code keyCode} was recently released.
   *
   * @param keyCode
   *          The keyCode to check for.
   * @return True if the key with the specified code was recently released.
   * @see #onKeyReleased(KeyReleasedListener)
   * @see #onKeyReleased(int, KeyReleasedListener)
   */
  boolean wasReleased(int keyCode);

  /**
   * Adds the specified key pressed listener to receive events when the key with the defined {@code
   * keyCode} has been pressed.
   *
   * @param keyCode
   *          The keyCode to capture the key pressed event for.
   * @param listener
   *          The listener to add.
   * @see KeyListener#keyPressed(KeyEvent)
   * @see KeyEvent#KEY_PRESSED
   */
  void onKeyPressed(int keyCode, KeyPressedListener listener);

  /**
   * Unregister the specified listener from key pressed events.
   *
   * @param keyCode
   *          The keyCode for which to remove the listener.
   * @param listener
   *          The listener to remove.
   */
  void removeKeyPressedListener(int keyCode, KeyPressedListener listener);

  /**
   * Adds the specified key released listener to receive events when the key with the defined {@code
   * keyCode} has been released.
   *
   * @param keyCode
   *          The keyCode to capture the key released event for.
   * @param listener
   *          The listener to add.
   * @see KeyListener#keyReleased(KeyEvent)
   * @see KeyEvent#KEY_RELEASED
   */
  void onKeyReleased(int keyCode, KeyReleasedListener listener);

  /**
   * Unregister the specified listener from key released events.
   *
   * @param keyCode
   *          The keyCode for which to remove the listener.
   * @param listener
   *          The listener to remove.
   */
  void removeKeyReleasedListener(int keyCode, KeyReleasedListener listener);

  /**
   * Adds the specified key typed listener to receive events when the key with the defined {@code
   * keyCode} has been typed.
   *
   * @param keyCode
   *          The keyCode to capture the key typed event for.
   * @param listener
   *          The listener to add.
   * @see KeyListener#keyTyped(KeyEvent)
   * @see KeyEvent#KEY_TYPED
   */
  void onKeyTyped(int keyCode, KeyTypedListener listener);

  /**
   * Unregister the specified listener from key typed events.
   *
   * @param keyCode
   *          The keyCode for which to remove the listener.
   * @param listener
   *          The listener to remove.
   */
  void removeKeyTypedListener(int keyCode, KeyTypedListener listener);

  /**
   * Adds the specified key pressed listener to receive events when any key has been pressed.
   *
   * @param listener
   *          The listener to add.
   * @see KeyListener#keyPressed(KeyEvent)
   * @see KeyEvent#KEY_PRESSED
   */
  void onKeyPressed(KeyPressedListener listener);

  /**
   * Unregister the specified listener from key pressed events.
   *
   * @param listener
   *          The listener to remove.
   */
  void removeKeyPressedListener(KeyPressedListener listener);

  /**
   * Adds the specified key released listener to receive events when any key has been released.
   *
   * @param listener
   *          The listener to add.
   * @see KeyListener#keyReleased(KeyEvent)
   * @see KeyEvent#KEY_RELEASED
   */
  void onKeyReleased(KeyReleasedListener listener);

  /**
   * Unregister the specified listener from key released events.
   *
   * @param listener
   *          The listener to remove.
   */
  void removeKeyReleasedListener(KeyReleasedListener listener);

  /**
   * Adds the specified key typed listener to receive events when any key has been typed.
   *
   * @param listener
   *          The listener to add.
   * @see KeyListener#keyTyped(KeyEvent)
   * @see KeyEvent#KEY_TYPED
   */
  void onKeyTyped(KeyTypedListener listener);

  /**
   * Unregister the specified listener from key typed events.
   *
   * @param listener
   *          The listener to remove.
   */
  void removeKeyTypedListener(KeyTypedListener listener);

  /**
   * Removes all registered event consumers from the Keyboard instance. This does not affect registered
   * {@code KeyListener} instances.
   *
   * @see #onKeyPressed(KeyPressedListener)
   * @see #onKeyPressed(int, KeyPressedListener)
   * @see #onKeyReleased(KeyReleasedListener)
   * @see #onKeyReleased(int, KeyReleasedListener)
   * @see #onKeyTyped(KeyTypedListener)
   * @see #onKeyTyped(int, KeyTypedListener)
   */
  void clearExplicitListeners();

  /**
   * Register for key events.
   *
   * @param listener
   *          The listener to add.
   */
  void addKeyListener(KeyListener listener);

  /**
   * Unregister the specified listener from key events.
   *
   * @param listener
   *          The listener to remove.
   */
  void removeKeyListener(KeyListener listener);

  /**
   * This listener interface receives pressed events for the keyboard.
   *
   * @see IKeyboard#onKeyPressed(KeyPressedListener)
   * @see IKeyboard#onKeyPressed(int, KeyPressedListener)
   * @see KeyListener#keyPressed(KeyEvent)
   */
  @FunctionalInterface
  interface KeyPressedListener extends EventListener {
    /**
     * Invoked when a key has been pressed. See the class description for {@link KeyEvent} for a definition of a key pressed
     * event.
     *
     * @param event
     *          The key event.
     */
    void keyPressed(KeyEvent event);
  }

  /**
   * This listener interface receives released events for the keyboard.
   *
   * @see IKeyboard#onKeyReleased(KeyReleasedListener)
   * @see IKeyboard#onKeyReleased(int, KeyReleasedListener)
   * @see KeyListener#keyReleased(KeyEvent)
   */
  @FunctionalInterface
  interface KeyReleasedListener extends EventListener {
    /**
     * Invoked when a key has been released. See the class description for {@link KeyEvent} for a definition of a key
     * released event.
     *
     * @param event
     *          The key event.
     */
    void keyReleased(KeyEvent event);
  }

  /**
   * This listener interface receives typed events for the keyboard.
   *
   * @see IKeyboard#onKeyTyped(KeyTypedListener)
   * @see IKeyboard#onKeyTyped(int, KeyTypedListener)
   * @see KeyListener#keyTyped(KeyEvent)
   */
  @FunctionalInterface
  interface KeyTypedListener extends EventListener {
    /**
     * Invoked when a key has been typed. See the class description for {@link KeyEvent} for a definition of a key typed
     * event.
     *
     * @param event
     *          The key event.
     */
    void keyTyped(KeyEvent event);
  }
}


text:
class HTTPRequest:
    # also callable as: asyncPut(self, url, postData, handler)
    def asyncPut(self, user, pwd, url, postData=None, handler=None,
                                        returnxml=0,
                                        content_type='text/plain charset=utf8'):
        if postData is None:
            return self.asyncPutImpl(None, None, user, pwd, url, returnxml,
                                      content_type)
        return self.asyncPutImpl(user, pwd, url, postData, handler,
                                    returnxml,
                                  content_type)

    # also callable as: asyncDelete(self, url, handler)
    def asyncDelete(self, user, pwd, url=None, handler=None, returnxml=0):
        if url is None:
            return self.asyncDeleteImpl(None, None, user, pwd, returnxml)
        return self.asyncDeleteImpl(user, pwd, url, handler, returnxml)

    # also callable as: asyncPost(self, url, postData, handler)
    def asyncPost(self, user, pwd, url, postData=None, handler=None,
                                        returnxml=0,
                                        content_type='text/plain charset=utf8'):
        if postData is None:
            return self.asyncPostImpl(None, None, user, pwd, url, returnxml,
                                      content_type)
        return self.asyncPostImpl(user, pwd, url, postData, handler,
                                    returnxml,
                                  content_type)

    # also callable as: asyncGet(self, url, handler)
    def asyncGet(self, user, pwd, url=None, handler=None, returnxml=0):
        if url is None:
            return self.asyncGetImpl(None, None, user, pwd, returnxml)
        return self.asyncGetImpl(user, pwd, url, handler, returnxml)

    def createXmlHTTPRequest(self):
        return self.doCreateXmlHTTPRequest()

    def doCreateXmlHTTPRequest(self):
        JS("""
        return new XMLHttpRequest();
        """)

    def asyncPutImpl(self, user, pwd, url, postData, handler,
                            returnxml, content_type):
        pdlen = str(len(postData))
        JS("""
        var xmlHttp = this.doCreateXmlHTTPRequest();
        try {
            xmlHttp.open("PUT", url, true);
            xmlHttp.setRequestHeader("Content-Type", content_type);
            xmlHttp.setRequestHeader("Content-Length", pdlen);
            xmlHttp.onreadystatechange = function() {
                if (xmlHttp.readyState == 4) {
                    delete xmlHttp.onreadystatechange;
                    var localHandler = handler;
                    var response;
                    var status = xmlHttp.status;
                    if (returnxml.valueOf())
                        response = xmlHttp.responseXML;
                    else
                        response = xmlHttp.responseText;
                    handler = null;
                    xmlHttp = null;
                    if(status == 200) {
                        localHandler.onCompletion(response);
                    } else {
                        localHandler.onError(response, status);
                    }
                }
            };
            xmlHttp.send(postData);
            return true;
        }
        catch (e) {
            delete xmlHttp.onreadystatechange;
            var localHandler = handler;
            handler = null;
            xmlHttp = null;
            localHandler.onError(String(e), "");
            return false;
        }
        """)

    def asyncDeleteImpl(self, user, pwd, url, handler, returnxml=0):
        JS("""
        var xmlHttp = this.doCreateXmlHTTPRequest();
        try {
            xmlHttp.open("DELETE", url, true);
            if (returnxml.valueOf())
                xmlHttp.setRequestHeader("Content-Type", "application/xml; charset=utf-8");
            else
                xmlHttp.setRequestHeader("Content-Type", "text/plain; charset=utf-8");
            xmlHttp.onreadystatechange = function() {
                if (xmlHttp.readyState == 4) {
                    delete xmlHttp.onreadystatechange;
                    var localHandler = handler;
                    var response;
                    var status = xmlHttp.status;
                    if (returnxml.valueOf())
                        response = xmlHttp.responseXML;
                    else
                        response = xmlHttp.responseText;
                    handler = null;
                    xmlHttp = null;
                    if(status == 200) {
                        localHandler.onCompletion(response);
                    } else {
                        localHandler.onError(response, status);
                    }
                }
            };
            xmlHttp.send('');
            return true;
        }
        catch (e) {
            delete xmlHttp.onreadystatechange;
            var localHandler = handler;
            handler = null;
            xmlHttp = null;
            localHandler.onError(String(e), "");
            return false;
        }
        """)

    def asyncPostImpl(self, user, pwd, url, postData, handler,
                            returnxml, content_type):
        pdlen = str(len(postData))
        JS("""
        var xmlHttp = this.doCreateXmlHTTPRequest();
        try {
            xmlHttp.open("POST", url, true);
            xmlHttp.setRequestHeader("Content-Type", content_type);
            xmlHttp.setRequestHeader("Content-Length", pdlen);
            xmlHttp.onreadystatechange = function() {
                if (xmlHttp.readyState == 4) {
                    delete xmlHttp.onreadystatechange;
                    var localHandler = handler;
                    var response;
                    var status = xmlHttp.status;
                    if (returnxml.valueOf())
                        response = xmlHttp.responseXML;
                    else
                        response = xmlHttp.responseText;
                    handler = null;
                    xmlHttp = null;
                    if(status == 200) {
                        localHandler.onCompletion(response);
                    } else {
                        localHandler.onError(response, status);
                    }
                }
            };
            xmlHttp.send(postData);
            return true;
        }
        catch (e) {
            delete xmlHttp.onreadystatechange;
            var localHandler = handler;
            handler = null;
            xmlHttp = null;
            localHandler.onError(String(e), "");
            return false;
        }
        """)

    def asyncGetImpl(self, user, pwd, url, handler, returnxml=0):
        JS("""
        var xmlHttp = this.doCreateXmlHTTPRequest();
        try {
            xmlHttp.open("GET", url, true);
            if (returnxml.valueOf())
                xmlHttp.setRequestHeader("Content-Type", "application/xml; charset=utf-8");
            else
                xmlHttp.setRequestHeader("Content-Type", "text/plain; charset=utf-8");
            xmlHttp.onreadystatechange = function() {
                if (xmlHttp.readyState == 4) {
                    delete xmlHttp.onreadystatechange;
                    var localHandler = handler;
                    var response;
                    var status = xmlHttp.status;
                    if (returnxml.valueOf())
                        response = xmlHttp.responseXML;
                    else
                        response = xmlHttp.responseText;
                    handler = null;
                    xmlHttp = null;
                    if(status == 200) {
                        localHandler.onCompletion(response);
                    } else {
                        localHandler.onError(response, status);
                    }
                }
            };
            xmlHttp.send('');
            return true;
        }
        catch (e) {
            delete xmlHttp.onreadystatechange;
            var localHandler = handler;
            handler = null;
            xmlHttp = null;
            localHandler.onError(String(e), "");
            return false;
        }
        """)

redpajama_set_name: RedPajamaGithub


text:
package com.comcast.oscar.utilities;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class CheckSum {

	/**
	 * Method getMD5.
	 * @param bMessage ByteArray of the Message
	 * @return byte[] MD5 Hash of the Message
	 */
	public static byte[] getMD5(byte[] bMessage) {

		MessageDigest md = null;

		try {
			md = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}

		return md.digest(bMessage);
	}

	/**
	 *
	 * @param bTlvArray ByteArray of the Message
	 * @return SHA-1 Hash of the Message
	 */
	public static byte[] getSHA1(byte[] bTlvArray) {

		MessageDigest md = null;

	    try {
	    	md = MessageDigest.getInstance("SHA-1");
	    }
	    catch(NoSuchAlgorithmException e) {
	        e.printStackTrace();
	    }

	    return md.digest(bTlvArray);
	}

}


text:
@interface MeViewController : BaseViewController

@property (strong, nonatomic)  BaseTableView *tableview;
@property (assign) BOOL isSelf;
@property (strong, nonatomic) UserModel *user;
@property (assign) BOOL isPresentMode;
@property (assign, nonatomic) BOOL isRightItem;
@end


text:
void TriggerEditor::Draw(Canvas &c, const Rect &clip){
    c.clear(Colorf::dimgrey);

    const int space = 100;
    const int bar_width = 1;
    const Colorf bar_colors = Colorf(50,50,50,255);
    for(int i = 0;i < clip.bottom;i+=space)
        c.fill_rect(Rect(0,i,clip.right,i+bar_width),bar_colors);
    for(int i = 0;i < clip.right;i+=space)
        c.fill_rect(Rect(i,0,i+bar_width,clip.bottom),bar_colors);
}
bool TriggerEditor::on_input(const InputEvent &e){
    std::vector<int> selected;
    static int last_selected = -1;
    static bool grabbing = false;
    static bool action = false;
    static Vec2f scroll_last = Vec2f(0,0);
    static bool scrolling = false;

    if(e.id == InputCode::mouse_right && IsPressed(e) && !action){
        //! I know I could do a normal for loop, but I think this looks better
        int iter = 0;
        for(auto &elem : nodes){
            if(elem->PointInBound(Vec2f(e.mouse_pos)))
                selected.push_back(iter);
            if(!e.shift)
                elem->selected = false;
            iter++;
        }
        if(selected.size() == 1){
            nodes[selected[0]]->selected = true;
            last_selected = selected[0];
        }else if(selected.size() > 1){
            if(last_selected == -1){
                nodes[selected[0]]->selected = true;
                last_selected = selected[0];
            }else{
                //! if there arn't any further in the vector we need to cycle back
                bool are_any_ahead = false;
                for(unsigned int i = 0;i < selected.size();i++){
                    if(selected[i] > last_selected && !are_any_ahead){
                        nodes[selected[i]]->selected = true;
                        last_selected = selected[i];
                        are_any_ahead = true;
                    }
                }
                if(!are_any_ahead){
                    nodes[selected[0]]->selected = true;
                    last_selected = selected[0];
                }
            }
        }
    }

    if(e.id == InputCode::mouse_middle && IsPressed(e)){
        scroll_last = Vec2f(e.mouse_pos);
        scrolling = true;
    }
    if(e.id == InputCode::mouse_middle && e.type == InputEvent::Type::released){
        scroll_last = Vec2f(e.mouse_pos);
        scrolling = false;
    }
    if(scrolling){
        cam_position -= (Vec2f(e.mouse_pos)-scroll_last)*zoom;
        scroll_last = Vec2f(e.mouse_pos);
    }

    if(e.id == InputCode::mouse_left && IsPressed(e)){
        grabbing = false;
        action = false;
    }
    if(e.id == keycode_g && IsPressed(e)){
        for(auto &elem : nodes){
            if(elem->selected){
                elem->StartGrab(Vec2f(e.mouse_pos));
            }
        }
        grabbing = true;
        action = true;
    }
    if(grabbing){
        for(auto &elem : nodes){
            if(elem->selected){
                elem->Grabbing(Vec2f(e.mouse_pos));
            }
        }
    }

    //! zooming is a later feature
//    if(e.id == clan::mouse_wheel_down){
//        zoom *= 1.1;
//        if(zoom > 20) zoom = 20;
//    }
//    else if(e.id == clan::mouse_wheel_up){
//        zoom /= 1.1;
//        if(zoom < 1) zoom = 1;
//    }
}


text:
define(['marionette',
	'./feedbackTestTemplate.hbs',
	'rup.feedback','rup.button'], function(Marionette, FeedbackTestTemplate){

	var FeedbackTestView = Marionette.LayoutView.extend({
		template: FeedbackTestTemplate,
		create: fncCreate,
		destroy: fncDestroy,
		set: fncSet,
		setOptions: fncSetOptions,
		setType: fncSetType,
		setImageClass: fncSetImageClass,
		setHide: fncHide,
		setClose: fncClose,
		setShow: fncShow,
		_getOptions: fncGetOptions,
		ui:{
			feedback: '#feedback',
			btnCreate: '#boton_create',
			btnDestroy: '#boton_destroy',
			btnSet: '#boton_set',
			btnSetOptions: '#boton_setOptions',
			btnSetType: '#boton_setType',
			btnSetImageClass: '#boton_setImgClass',
			btnHide: '#boton_hide',
			btnClose: '#boton_close',
			btnShow: '#boton_show',
			selectType: '#feedback_type',
			selectGotoTop: '#feedback_gotoTop',
			selectBlock: '#feedback_block',
			selectCloseLink: '#feedback_closeLink',
			txtImageClass: '#feedback_imgClass',
			txtDelay: '#feedback_delay',
			txtFadeSpeed: '#feedback_fadeSpeed',
			buttons:'button.feedback-test-button'

		},
		events: {
			'click @ui.btnCreate': 'create',
			'click @ui.btnDestroy': 'destroy',
			'click @ui.btnSet': 'set',
			'click @ui.btnSetOptions': 'setOptions',
			'click @ui.btnSetType': 'setType',
			'click @ui.btnSetImageClass': 'setImageClass',
			'click @ui.btnHide': 'hide',
			'click @ui.btnClose': 'close',
			'click @ui.btnShow': 'show'
		}

	});

	function fncCreate(){
		this.ui.feedback.rup_feedback(this._getOptions());
		this.ui.btnCreate.attr('disabled',true);
		this.ui.btnDestroy.attr('disabled',false);
	}
	function fncDestroy(){
		this.ui.feedback.rup_feedback('destroy');
		this.ui.btnDestroy.attr('disabled',true);
		this.ui.btnCreate.attr('disabled',false);
	}
	function fncSet(){
		this.ui.feedback.rup_feedback('set','Este es un ejemplo de Feedback');
	}
	function fncSetOptions(){
		this.ui.feedback.rup_feedback('option',this._getOptions());
	}
	function fncSetType(){
		this.ui.feedback.rup_feedback('set',
			'Este es un ejemplo de cambio de tipo de Feedback',
			this.ui.selectType.val()==''?null:this.ui.selectType.val()
		);
	}
	function fncSetImageClass(){
		this.ui.feedback.rup_feedback('set',
			'Este es un ejemplo de cambio de tipo por imgClass del Feedback',
			null,
			this.ui.txtImageClass.val()
		);
	}
	function fncHide(){
		this.ui.feedback.rup_feedback('hide',
			this.ui.txtDelay.val()==''?null:this.ui.txtDelay.val(),
			this.ui.txtFadeSpeed.val()==''?null:this.ui.txtFadeSpeed.val()
		);
	}
	function fncClose(){
		this.ui.feedback.rup_feedback('close');
	}
	function fncShow(){
		this.ui.feedback.rup_feedback('show');
	}

	function fncGetOptions(){
		//Recuperar variables
		var my_type = this.ui.selectType.val()==''?null:this.ui.selectType.val(),
			my_imgClass = this.ui.txtImageClass.val()==''?null:this.ui.txtImageClass.val(),
			my_delay = this.ui.txtDelay.val()==''?null: this.ui.txtDelay.val(),
			my_fadeSpeed = this.ui.txtFadeSpeed.val()==''?null: this.ui.txtFadeSpeed.val(),
			my_gotoTop = eval(this.ui.selectGotoTop.val()),
			my_block = eval(this.ui.selectBlock.val()),
			my_closeLink = eval(this.ui.selectCloseLink.val()),
			//Parametros feedback
			properties = {
				type: my_type,
				imgClass: my_imgClass,
				delay: my_delay,
				fadeSpeed: my_fadeSpeed,
				gotoTop: my_gotoTop,
				block: my_block,
				closeLink: my_closeLink,
				message: 'Este es un ejemplo de Feedback con message cargado en el create()'
			};
		return properties;
	}

	return FeedbackTestView;
});


text: DONE_MESSAGE = "UnitTesting: Done.\n"


text:
.jqcandlestick-container {
  position: relative;
  cursor: none;
}
.jqcandlestick-canvas {
  position: absolute;
  display: block;
  height: 100%;
  width: 100%;
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Pleistophora chapmani T.B. Clark & T. Fukuda

### Remarks
null


text:
import React from 'react';
import { Route, DefaultRoute, NotFoundRoute } from 'react-router';

import App from './pages/app.jsx';
import HomeViz from './pages/viz/vizHome.jsx';
import DealsViz from './pages/viz/vizDeals.jsx';
import DataViz from './pages/viz/dataViz.jsx';
import InvestorsViz from './pages/viz/vizInvestors.jsx';
import SearchViz from './pages/viz/vizSearch.jsx';
import AnalysisViz from './pages/viz/vizAnalysis.jsx';
import SettingsViz from './pages/viz/vizSettings.jsx';
import LibraryViz from './pages/viz/vizLibrary.jsx';
import GlossaryViz from './pages/viz/vizGlossary.jsx';
import Info from './pages/info.jsx';
import NotFound from './pages/notFound.jsx';

//var routes = (
//    <Route name="app" handler={App} path="/">
//      <Route name="destination" path="destination/:someparam" handler={Destination} />
//    </Route>
//);

var routes = (
  <Route name="app" path="/" handler={ App }>
    <Route name="info" handler={ Info } />
    <Route name="dataViz" handler={ DataViz } />
    <Route name="home" handler={ HomeViz } />
    <Route name="deals" handler={ DealsViz } />
    <Route name="investors" handler={ InvestorsViz } />
    <Route name="search" handler={ SearchViz } />
    <Route name="analysis" handler={ AnalysisViz } />
    <Route name="settings" handler={ SettingsViz } />
    <Route name="library" handler={ LibraryViz } />
    <Route name="glossary" handler={ GlossaryViz } />
    <DefaultRoute handler={ HomeViz } />
    <NotFoundRoute handler={ NotFound } />
  </Route>
);

// sessionStorage.userName = "Tim";

export default routes;


text:
layout: post
title: "Updated  to Polymer 1.x"
date: 2016-06-01 12:00:00 -0500
comments: false
---

	The Polymer <code-explainer> element was really cool, but it was never updated to Polymer 1.0... until now!

	Check out the live demo and the source code on my GitHub.


text:
<?php

namespace Odysseus\FrontBundle\Form;

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

class RechercheType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('recherche', 'text', array('attr' => array('id' => 'recherche')) );
    }

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


text:
#ifndef _DEINSTREAM_H
#define _DEINSTREAM_H
/*!
 * \file
 * \brief Input stream abstraction.
 *//*--------------------------------------------------------------------*/

#include "deDefs.h"

#include "deIOStream.h"

DE_BEGIN_EXTERN_C

/* Input stream struct, implemented as a wrapper to io stream */
typedef struct deInStream_s
{
	deIOStream ioStream;
} deInStream;

DE_INLINE deStreamResult	deInStream_read		(deInStream* stream, void* buf, deInt32 bufSize, deInt32* numWritten);
DE_INLINE deStreamResult	deInStream_deinit	(deInStream* stream);
DE_INLINE const char*		deInStream_getError (deInStream* stream);
DE_INLINE deStreamStatus	deInStream_getStatus(deInStream* stream);

DE_INLINE deStreamResult deInStream_read (deInStream* stream, void* buf, deInt32 bufSize, deInt32* numWritten)
{
	return deIOStream_read(&(stream->ioStream), buf, bufSize, numWritten);
}

DE_INLINE deStreamResult deInStream_deinit (deInStream* stream)
{
	return deIOStream_deinit(&(stream->ioStream));
}

DE_INLINE const char* deInStream_getError (deInStream* stream)
{
	return deIOStream_getError(&(stream->ioStream));
}

DE_INLINE deStreamStatus deInStream_getStatus(deInStream* stream)
{
	return deIOStream_getStatus(&(stream->ioStream));
}

DE_END_EXTERN_C

#endif /* _DEINSTREAM_H */


text:
cask 'font-anaheim' do
  version :latest
  sha256 :no_check

  # github.com/google/fonts was verified as official when first introduced to the cask
  url 'https://github.com/google/fonts/raw/master/ofl/anaheim/Anaheim-Regular.ttf'
  name 'Anaheim'
  homepage 'http://www.google.com/fonts/specimen/Anaheim'

  font 'Anaheim-Regular.ttf'
end


text:
from pathlib import Path
import glob
import math

import torch
import torch.utils.data as data
import torchvision.transforms as transforms
from PIL import Image

DEFAULT_CROP_PCT = 0.875

class LeNormalize(object):
    # Normalize to [-1.0, 1.0]
    def __call__(self, tensor):
        for t in tensor:
            t.sub_(0.5).mul_(2.0)
        return tensor

def default_inception_transform(sz):
    tf = transforms.Compose([
        transforms.Scale(sz),
        transforms.CenterCrop(sz),
        transforms.ToTensor(),
        LeNormalize(),
    ])
    return tf

def default_transform(sz):
    tf = transforms.Compose([
        transforms.Scale(sz),
        transforms.CenterCrop(sz),
        transforms.ToTensor(),
    ])
    return tf

def default_transform_v2(sz):
    tf = transforms.Compose([
        transforms.Scale(256),
        transforms.CenterCrop(224),
        transforms.ToTensor(),
    ])
    return tf

def default_transform_v3(sz):
    normalize = transforms.Normalize(
        mean=[0.485, 0.456, 0.406],
        std=[0.229, 0.224, 0.225])

    tf = transforms.Compose([
        transforms.Scale(256),
        transforms.CenterCrop(224),
        transforms.ToTensor(),
        normalize,
    ])
    return tf

def transforms_eval(img_size=224, crop_pct=None):
    crop_pct = crop_pct or DEFAULT_CROP_PCT
    if crop_pct is None:
        if img_size == 224:
            scale_size = int(
                math.floor(img_size / DEFAULT_CROP_PCT)
            )
        else:
            scale_size = img_size
    else:
        scale_size = int(math.floor(img_size / crop_pct))

    normalize = transforms.Normalize(
        mean=[124 / 255, 117 / 255, 104 / 255],
        std=[1 / (.0167 * 255)] * 3)

    return transforms.Compose([
        transforms.Scale(scale_size, Image.BICUBIC),
        transforms.CenterCrop(img_size),
        transforms.ToTensor(),
        normalize])

class DataLoader(data.DataLoader):
    def get_filenames(self, idx, size):
        idx_st = idx * self.batch_size

        return [
            self.dataset.get_filename(file_idx)
            for file_idx in range(
                idx_st,
                idx_st + size)]

class Dataset(data.Dataset):
    def __init__(self, input_dir, transform=None):
        self.input_dir = input_dir
        self.transform = transform

        self.imgs = list(glob.glob(str(
            Path(input_dir) /
            Path("./*.png"))))

    def __getitem__(self, index):
        path = self.imgs[index]
        img = Image.open(path).convert('RGB')
        if self.transform is not None:
            img = self.transform(img)
        target = torch.zeros(1).long()
        return img, target

    def __len__(self):
        return len(self.imgs)

    def set_transform(self, transform):
        self.transform = transform

    def get_filename(self, idx):
        return Path(self.imgs[idx]).name


text:
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_controller_impl_win.h"

#include <sstream>
#include <string>
#include <tuple>
#include <utility>

#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/command_line.h"
#include "base/run_loop.h"
#include "base/task/post_task.h"
#include "base/test/multiprocess_test.h"
#include "base/threading/thread_task_runner_handle.h"
#include "build/build_config.h"
#include "chrome/browser/metrics/chrome_metrics_service_accessor.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/safe_browsing/chrome_cleaner/chrome_prompt_actions_win.h"
#include "chrome/browser/safe_browsing/chrome_cleaner/mock_chrome_cleaner_process_win.h"
#include "chrome/browser/safe_browsing/chrome_cleaner/reporter_runner_win.h"
#include "chrome/browser/safe_browsing/chrome_cleaner/srt_field_trial_win.h"
#include "chrome/test/base/testing_browser_process.h"
#include "chrome/test/base/testing_profile.h"
#include "chrome/test/base/testing_profile_manager.h"
#include "components/chrome_cleaner/public/constants/constants.h"
#include "components/chrome_cleaner/public/proto/chrome_prompt.pb.h"
#include "components/chrome_cleaner/test/test_name_helper.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/test/browser_task_environment.h"
#include "content/public/test/test_utils.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/multiprocess_func_list.h"

namespace safe_browsing {
namespace {

using ::testing::_;
using ::testing::Bool;
using ::testing::Combine;
using ::testing::DoAll;
using ::testing::InvokeWithoutArgs;
using ::testing::SaveArg;
using ::testing::StrictMock;
using ::testing::UnorderedElementsAreArray;
using ::testing::Values;
using ::testing::ValuesIn;
using CrashPoint = MockChromeCleanerProcess::CrashPoint;
using IdleReason = ChromeCleanerController::IdleReason;
using ItemsReporting = MockChromeCleanerProcess::ItemsReporting;
using PromptUserResponse = chrome_cleaner::PromptUserResponse;
using State = ChromeCleanerController::State;
using UserResponse = ChromeCleanerController::UserResponse;
using UwsFoundStatus = MockChromeCleanerProcess::UwsFoundStatus;

// Returns the PromptAcceptance value that ChromeCleanerController is supposed
// to send to the Chrome Cleaner process when ReplyWithUserResponse() is
// called with |user_response|.
PromptUserResponse::PromptAcceptance UserResponseToPromptAcceptance(
    UserResponse user_response) {
  switch (user_response) {
    case UserResponse::kAcceptedWithLogs:
      return PromptUserResponse::ACCEPTED_WITH_LOGS;
    case UserResponse::kAcceptedWithoutLogs:
      return PromptUserResponse::ACCEPTED_WITHOUT_LOGS;
    case UserResponse::kDenied:  // Fallthrough
    case UserResponse::kDismissed:
      return PromptUserResponse::DENIED;
  }

  NOTREACHED();
  return PromptUserResponse::UNSPECIFIED;
}

class MockChromeCleanerControllerObserver
    : public ChromeCleanerController::Observer {
 public:
  MOCK_METHOD1(OnIdle, void(ChromeCleanerController::IdleReason));
  MOCK_METHOD0(OnReporterRunning, void());
  MOCK_METHOD0(OnScanning, void());
  MOCK_METHOD2(OnInfected, void(bool, const ChromeCleanerScannerResults&));
  MOCK_METHOD2(OnCleaning, void(bool, const ChromeCleanerScannerResults&));
  MOCK_METHOD0(OnRebootRequired, void());
  MOCK_METHOD0(OnRebootFailed, void());
};

enum class MetricsStatus {
  kEnabled,
  kDisabled,
};

// Simple test fixture that passes an invalid process handle back to the
// ChromeCleanerRunner class and is intended for testing simple things like
// command line flags that Chrome sends to the Chrome Cleaner process.
//
// Parameters:
// - metrics_status (MetricsStatus): whether Chrome metrics reporting is
//   enabled.
class ChromeCleanerControllerSimpleTest
    : public testing::TestWithParam<MetricsStatus>,
      public ChromeCleanerRunnerTestDelegate,
      public ChromeCleanerControllerDelegate {
 public:
  ChromeCleanerControllerSimpleTest()
      : command_line_(base::CommandLine::NO_PROGRAM) {}

  ~ChromeCleanerControllerSimpleTest() override {}

  void SetUp() override {
    MetricsStatus metrics_status = GetParam();

    metrics_enabled_ = metrics_status == MetricsStatus::kEnabled;

    SetChromeCleanerRunnerTestDelegateForTesting(this);
    ChromeCleanerControllerImpl::ResetInstanceForTesting();
    ChromeCleanerControllerImpl::GetInstance()->SetDelegateForTesting(this);
  }

  void TearDown() override {
    ChromeCleanerControllerImpl::GetInstance()->SetDelegateForTesting(nullptr);
    SetChromeCleanerRunnerTestDelegateForTesting(nullptr);
    ChromeCleanerControllerImpl::ResetInstanceForTesting();
  }

  // ChromeCleanerControllerDelegate overrides.

  void FetchAndVerifyChromeCleaner(FetchedCallback fetched_callback) override {
    // In this fixture, we only test the cases when fetching the cleaner
    // executable succeeds.
    std::move(fetched_callback)
        .Run(base::FilePath(FILE_PATH_LITERAL("chrome_cleaner.exe")));
  }

  bool IsMetricsAndCrashReportingEnabled() override { return metrics_enabled_; }

  void TagForResetting(Profile* profile) override {
    // This function should never be called by these tests.
    FAIL();
  }

  void ResetTaggedProfiles(std::vector<Profile*> profiles,
                           base::OnceClosure continuation) override {
    // This function should never be called by these tests.
    FAIL();
  }

  void StartRebootPromptFlow(ChromeCleanerController* controller) override {
    FAIL();
  }

  // ChromeCleanerRunnerTestDelegate overrides.

  base::Process LaunchTestProcess(
      const base::CommandLine& command_line,
      const base::LaunchOptions& launch_options) override {
    command_line_ = command_line;
    // Return an invalid process.
    return base::Process();
  }

  void OnCleanerProcessDone(
      const ChromeCleanerRunner::ProcessStatus& process_status) override {}

 protected:
  // We need this because we need UI and IO threads during tests. The thread
  // bundle should be the first member of the class so that it will be destroyed
  // last.
  content::BrowserTaskEnvironment task_environment_;

  bool metrics_enabled_;
  base::CommandLine command_line_;

  StrictMock<MockChromeCleanerControllerObserver> mock_observer_;
};

SwReporterInvocation GetInvocationWithPromptTrigger() {
  return SwReporterInvocation(base::CommandLine(base::CommandLine::NO_PROGRAM))
      .WithSupportedBehaviours(SwReporterInvocation::BEHAVIOUR_TRIGGER_PROMPT);
}

TEST_P(ChromeCleanerControllerSimpleTest, FlagsPassedToCleanerProcess) {
  ChromeCleanerControllerImpl* controller =
      ChromeCleanerControllerImpl::GetInstance();
  ASSERT_TRUE(controller);

  EXPECT_CALL(mock_observer_, OnIdle(_)).Times(1);
  controller->AddObserver(&mock_observer_);
  EXPECT_EQ(controller->state(), State::kIdle);

  EXPECT_CALL(mock_observer_, OnScanning()).Times(1);
  controller->Scan(GetInvocationWithPromptTrigger());
  EXPECT_EQ(controller->state(), State::kScanning);

  base::RunLoop run_loop;
  // The run loop will quit when we get back to the kIdle state, which will
  // happen when launching the Chrome Cleaner process fails (due to the
  // definition of LaunchTestProcess() in the test fixture class).
  EXPECT_CALL(mock_observer_, OnIdle(IdleReason::kScanningFailed))
      .WillOnce(InvokeWithoutArgs([&run_loop]() { run_loop.QuitWhenIdle(); }));
  run_loop.Run();

  EXPECT_EQ(controller->state(), State::kIdle);
  EXPECT_EQ(metrics_enabled_,
            command_line_.HasSwitch(chrome_cleaner::kUmaUserSwitch));
  EXPECT_EQ(metrics_enabled_, command_line_.HasSwitch(
                                  chrome_cleaner::kEnableCrashReportingSwitch));

  controller->RemoveObserver(&mock_observer_);
}

INSTANTIATE_TEST_SUITE_P(All,
                         ChromeCleanerControllerSimpleTest,
                         Values(MetricsStatus::kDisabled,
                                MetricsStatus::kEnabled));

enum class CleanerProcessStatus {
  kFetchFailure,
  kFetchSuccessInvalidProcess,
  kFetchSuccessValidProcess,
};

typedef std::tuple<CleanerProcessStatus,
                   CrashPoint,
                   UwsFoundStatus,
                   ItemsReporting,
                   UserResponse>
    ChromeCleanerControllerTestParams;

// Test fixture that runs a mock Chrome Cleaner process in various
// configurations and mocks the user's response.
class ChromeCleanerControllerTest
    : public ::testing::TestWithParam<ChromeCleanerControllerTestParams>,
      public ChromeCleanerRunnerTestDelegate,
      public ChromeCleanerControllerDelegate {
 public:
  ChromeCleanerControllerTest() = default;
  ~ChromeCleanerControllerTest() override {}

  void SetUp() override {
    std::tie(process_status_, crash_point_, uws_found_status_,
             registry_keys_reporting_, user_response_) = GetParam();

    cleaner_process_options_.SetReportedResults(
        uws_found_status_ != UwsFoundStatus::kNoUwsFound,
        registry_keys_reporting_);
    cleaner_process_options_.set_reboot_required(
        uws_found_status_ == UwsFoundStatus::kUwsFoundRebootRequired);
    cleaner_process_options_.set_crash_point(crash_point_);
    cleaner_process_options_.set_expected_user_response(
        uws_found_status_ == UwsFoundStatus::kNoUwsFound
            ? PromptUserResponse::DENIED
            : UserResponseToPromptAcceptance(user_response_));

    ChromeCleanerControllerImpl::ResetInstanceForTesting();
    controller_ = ChromeCleanerControllerImpl::GetInstance();
    ASSERT_TRUE(controller_);

    SetChromeCleanerRunnerTestDelegateForTesting(this);
    controller_->SetDelegateForTesting(this);
  }

  void TearDown() override {
    controller_->SetDelegateForTesting(nullptr);
    SetChromeCleanerRunnerTestDelegateForTesting(nullptr);
    ChromeCleanerControllerImpl::ResetInstanceForTesting();
  }

  // ChromeCleanerControllerDelegate overrides.

  void FetchAndVerifyChromeCleaner(FetchedCallback fetched_callback) override {
    base::ThreadTaskRunnerHandle::Get()->PostTask(
        FROM_HERE,
        base::BindOnce(
            std::move(fetched_callback),
            process_status_ != CleanerProcessStatus::kFetchFailure
                ? base::FilePath(FILE_PATH_LITERAL("chrome_cleaner.exe"))
                : base::FilePath()));
  }

  bool IsMetricsAndCrashReportingEnabled() override {
    // Returning an arbitrary value since this is not being tested in this
    // fixture.
    return false;
  }

  void TagForResetting(Profile* profile) override {
    profiles_tagged_.push_back(profile);
  }

  void ResetTaggedProfiles(std::vector<Profile*> profiles,
                           base::OnceClosure continuation) override {
    for (Profile* profile : profiles)
      profiles_to_reset_if_tagged_.push_back(profile);
    std::move(continuation).Run();
  }

  void StartRebootPromptFlow(ChromeCleanerController* controller) override {
    reboot_flow_started_ = true;
  }

  // ChromeCleanerRunnerTestDelegate overrides.

  base::Process LaunchTestProcess(
      const base::CommandLine& command_line,
      const base::LaunchOptions& launch_options) override {
    if (process_status_ != CleanerProcessStatus::kFetchSuccessValidProcess)
      return base::Process();

    // Add switches and program name that the test process needs for the multi
    // process tests.
    base::CommandLine test_process_command_line =
        base::GetMultiProcessTestChildBaseCommandLine();
    test_process_command_line.AppendArguments(command_line,
                                              /*include_program=*/false);

    cleaner_process_options_.AddSwitchesToCommandLine(
        &test_process_command_line);

    base::Process process = base::SpawnMultiProcessTestChild(
        "MockChromeCleanerProcessMain", test_process_command_line,
        launch_options);

    EXPECT_TRUE(process.IsValid());
    return process;
  }

  void OnCleanerProcessDone(
      const ChromeCleanerRunner::ProcessStatus& process_status) override {
    cleaner_process_status_ = process_status;
  }

  ChromeCleanerController::State ExpectedFinalState() {
    if (process_status_ == CleanerProcessStatus::kFetchSuccessValidProcess &&
        crash_point_ == CrashPoint::kNone &&
        uws_found_status_ == UwsFoundStatus::kUwsFoundRebootRequired &&
        ExpectedPromptAccepted()) {
      return State::kRebootRequired;
    }
    return State::kIdle;
  }

  bool ExpectedOnIdleCalled() { return ExpectedFinalState() == State::kIdle; }

  bool ExpectedOnInfectedCalled() {
    return process_status_ == CleanerProcessStatus::kFetchSuccessValidProcess &&
           crash_point_ != CrashPoint::kOnStartup &&
           crash_point_ != CrashPoint::kAfterConnection &&
           uws_found_status_ != UwsFoundStatus::kNoUwsFound;
  }

  bool ExpectedOnCleaningCalled() {
    return ExpectedOnInfectedCalled() &&
           crash_point_ != CrashPoint::kAfterRequestSent &&
           ExpectedPromptAccepted();
  }

  bool ExpectedOnRebootRequiredCalled() {
    return ExpectedFinalState() == State::kRebootRequired;
  }

  bool ExpectedUwsFound() { return ExpectedOnInfectedCalled(); }

  bool ExpectedRegistryKeysReported() {
    return ExpectedOnInfectedCalled() &&
           registry_keys_reporting_ == ItemsReporting::kReported;
  }

  bool ExpectedPromptAccepted() {
    return user_response_ == UserResponse::kAcceptedWithLogs ||
           user_response_ == UserResponse::kAcceptedWithoutLogs;
  }

  bool ExpectedToTagProfile() {
    return process_status_ == CleanerProcessStatus::kFetchSuccessValidProcess &&
           (crash_point_ == CrashPoint::kNone ||
            crash_point_ == CrashPoint::kAfterResponseReceived) &&
           (uws_found_status_ == UwsFoundStatus::kUwsFoundNoRebootRequired ||
            uws_found_status_ == UwsFoundStatus::kUwsFoundRebootRequired) &&
           ExpectedPromptAccepted();
  }

  bool ExpectedToResetSettings() {
    return process_status_ == CleanerProcessStatus::kFetchSuccessValidProcess &&
           crash_point_ == CrashPoint::kNone &&
           uws_found_status_ == UwsFoundStatus::kUwsFoundNoRebootRequired &&
           ExpectedPromptAccepted();
  }

  ChromeCleanerController::IdleReason ExpectedIdleReason() {
    EXPECT_EQ(ExpectedFinalState(), State::kIdle);

    if (process_status_ == CleanerProcessStatus::kFetchFailure) {
      return IdleReason::kCleanerDownloadFailed;
    }

    if (process_status_ != CleanerProcessStatus::kFetchSuccessValidProcess ||
        crash_point_ == CrashPoint::kOnStartup ||
        crash_point_ == CrashPoint::kAfterConnection) {
      return IdleReason::kScanningFailed;
    }

    if (uws_found_status_ == UwsFoundStatus::kNoUwsFound)
      return IdleReason::kScanningFoundNothing;

    if (ExpectedOnInfectedCalled() &&
        (user_response_ == UserResponse::kDenied ||
         user_response_ == UserResponse::kDismissed)) {
      return IdleReason::kUserDeclinedCleanup;
    }

    if (ExpectedOnInfectedCalled() && ExpectedPromptAccepted() &&
        crash_point_ == CrashPoint::kAfterResponseReceived) {
      return IdleReason::kCleaningFailed;
    }

    return IdleReason::kCleaningSucceeded;
  }

  bool ExpectedRebootFlowStarted() {
    return process_status_ == CleanerProcessStatus::kFetchSuccessValidProcess &&
           crash_point_ == CrashPoint::kNone &&
           uws_found_status_ == UwsFoundStatus::kUwsFoundRebootRequired &&
           ExpectedPromptAccepted();
  }

 protected:
  content::BrowserTaskEnvironment task_environment_;

  CleanerProcessStatus process_status_;
  MockChromeCleanerProcess::CrashPoint crash_point_;
  UwsFoundStatus uws_found_status_;
  ItemsReporting registry_keys_reporting_;
  ChromeCleanerController::UserResponse user_response_;

  MockChromeCleanerProcess::Options cleaner_process_options_;

  StrictMock<MockChromeCleanerControllerObserver> mock_observer_;
  ChromeCleanerControllerImpl* controller_;
  ChromeCleanerRunner::ProcessStatus cleaner_process_status_;

  std::vector<Profile*> profiles_tagged_;
  std::vector<Profile*> profiles_to_reset_if_tagged_;

  bool reboot_flow_started_ = false;
};

MULTIPROCESS_TEST_MAIN(MockChromeCleanerProcessMain) {
  MockChromeCleanerProcess mock_cleaner_process;
  EXPECT_TRUE(mock_cleaner_process.InitWithCommandLine(
      *base::CommandLine::ForCurrentProcess()));
  if (::testing::Test::HasFailure())
    return MockChromeCleanerProcess::kInternalTestFailureExitCode;
  return mock_cleaner_process.Run();
}

TEST_P(ChromeCleanerControllerTest, WithMockCleanerProcess) {
  TestingProfileManager profile_manager(TestingBrowserProcess::GetGlobal());
  ASSERT_TRUE(profile_manager.SetUp());

  constexpr char kTestProfileName1[] = "Test 1";
  constexpr char kTestProfileName2[] = "Test 2";

  Profile* profile1 = profile_manager.CreateTestingProfile(kTestProfileName1);
  ASSERT_TRUE(profile1);
  Profile* profile2 = profile_manager.CreateTestingProfile(kTestProfileName2);
  ASSERT_TRUE(profile2);

  const int num_profiles =
      profile_manager.profile_manager()->GetNumberOfProfiles();
  ASSERT_EQ(2, num_profiles);

  EXPECT_CALL(mock_observer_, OnIdle(_)).Times(1);
  controller_->AddObserver(&mock_observer_);
  EXPECT_EQ(controller_->state(), State::kIdle);

  EXPECT_CALL(mock_observer_, OnScanning()).Times(1);
  controller_->Scan(GetInvocationWithPromptTrigger());
  EXPECT_EQ(controller_->state(), State::kScanning);

  base::RunLoop run_loop;

  ChromeCleanerScannerResults scanner_results_on_infected;
  ChromeCleanerScannerResults scanner_results_on_cleaning;

  if (ExpectedOnIdleCalled()) {
    EXPECT_CALL(mock_observer_, OnIdle(ExpectedIdleReason()))
        .WillOnce(
            InvokeWithoutArgs([&run_loop]() { run_loop.QuitWhenIdle(); }));
  } else {
    EXPECT_CALL(mock_observer_, OnIdle(_)).Times(0);
  }

  if (ExpectedOnInfectedCalled()) {
    EXPECT_CALL(mock_observer_, OnInfected(_, _))
        .WillOnce(DoAll(SaveArg<1>(&scanner_results_on_infected),
                        InvokeWithoutArgs([this, profile1]() {
                          controller_->ReplyWithUserResponse(profile1,
                                                             user_response_);
                        })));
  } else {
    EXPECT_CALL(mock_observer_, OnInfected(_, _)).Times(0);
  }

  if (ExpectedOnCleaningCalled()) {
    EXPECT_CALL(mock_observer_, OnCleaning(_, _))
        .WillOnce(SaveArg<1>(&scanner_results_on_cleaning));
  } else {
    EXPECT_CALL(mock_observer_, OnCleaning(_, _)).Times(0);
  }

  if (ExpectedOnRebootRequiredCalled()) {
    EXPECT_CALL(mock_observer_, OnRebootRequired())
        .WillOnce(
            InvokeWithoutArgs([&run_loop]() { run_loop.QuitWhenIdle(); }));
  } else {
    EXPECT_CALL(mock_observer_, OnRebootRequired()).Times(0);
  }

  // Assert here that we expect at least one of OnIdle or OnRebootRequired to be
  // called, since otherwise, the test is set up incorrectly and is expected to
  // never stop.
  ASSERT_TRUE(ExpectedOnIdleCalled() || ExpectedOnRebootRequiredCalled());
  run_loop.Run();
  // Also ensure that we wait until the mock cleaner process has finished and
  // that all tasks that posted by ChromeCleanerRunner have run.
  content::RunAllTasksUntilIdle();

  EXPECT_NE(cleaner_process_status_.exit_code,
            MockChromeCleanerProcess::kInternalTestFailureExitCode);
  EXPECT_EQ(controller_->state(), ExpectedFinalState());

  EXPECT_EQ(!scanner_results_on_infected.files_to_delete().empty(),
            ExpectedUwsFound());
  EXPECT_EQ(!scanner_results_on_cleaning.files_to_delete().empty(),
            ExpectedUwsFound() && ExpectedOnCleaningCalled());
  if (!scanner_results_on_cleaning.files_to_delete().empty()) {
    EXPECT_THAT(scanner_results_on_cleaning.files_to_delete(),
                UnorderedElementsAreArray(
                    scanner_results_on_infected.files_to_delete()));
  }

  EXPECT_EQ(!scanner_results_on_infected.registry_keys().empty(),
            ExpectedRegistryKeysReported());
  EXPECT_EQ(!scanner_results_on_cleaning.registry_keys().empty(),
            ExpectedRegistryKeysReported() && ExpectedOnCleaningCalled());
  if (!scanner_results_on_cleaning.registry_keys().empty()) {
    EXPECT_THAT(
        scanner_results_on_cleaning.registry_keys(),
        UnorderedElementsAreArray(scanner_results_on_infected.registry_keys()));
  }

  EXPECT_EQ(ExpectedRebootFlowStarted(), reboot_flow_started_);

  std::vector<Profile*> expected_tagged;
  if (ExpectedToTagProfile())
    expected_tagged.push_back(profile1);
  EXPECT_THAT(expected_tagged, UnorderedElementsAreArray(profiles_tagged_));

  std::vector<Profile*> expected_reset_if_tagged;
  if (ExpectedToResetSettings()) {
    expected_reset_if_tagged.push_back(profile1);
    expected_reset_if_tagged.push_back(profile2);
  }
  EXPECT_THAT(expected_reset_if_tagged,
              UnorderedElementsAreArray(profiles_to_reset_if_tagged_));

  controller_->RemoveObserver(&mock_observer_);
}

// Make all the test parameter types printable. Use short names because these
// are used in tests with very many parameters.
std::ostream& operator<<(std::ostream& out, CleanerProcessStatus status) {
  return out << "Proc" << static_cast<int>(status);
}

// This includes all crash points after kOnStartup, except kAfterRequestSent.
// That one's not used because if we induce a crash after the mock cleaner
// sends a request, there would be a race condition between the request being
// received and the connection being lost. So at that point, invoking the error
// handler and not invoking it are both expected behaviour.
constexpr CrashPoint kCrashPointsAfterStartup[] = {
    CrashPoint::kNone, CrashPoint::kAfterConnection,
    CrashPoint::kAfterResponseReceived};

// Tests where the process gets past the startup phase and finds UwS to clean.
INSTANTIATE_TEST_SUITE_P(
    CleanerFindsUwSAndRuns,
    ChromeCleanerControllerTest,
    Combine(Values(CleanerProcessStatus::kFetchSuccessValidProcess),
            ValuesIn(kCrashPointsAfterStartup),
            Values(UwsFoundStatus::kUwsFoundRebootRequired,
                   UwsFoundStatus::kUwsFoundNoRebootRequired),
            Values(ItemsReporting::kUnsupported,
                   ItemsReporting::kNotReported,
                   ItemsReporting::kReported),
            Values(UserResponse::kAcceptedWithLogs,
                   UserResponse::kAcceptedWithoutLogs)),
    chrome_cleaner::GetParamNameForTest());

// Tests where the process gets past the startup phase and finds UwS to clean,
// but is dismissed by the user.
INSTANTIATE_TEST_SUITE_P(
    CleanerIsDismissed,
    ChromeCleanerControllerTest,
    Combine(Values(CleanerProcessStatus::kFetchSuccessValidProcess),
            ValuesIn(kCrashPointsAfterStartup),
            Values(UwsFoundStatus::kUwsFoundRebootRequired),
            Values(ItemsReporting::kReported),
            Values(UserResponse::kDenied, UserResponse::kDismissed)),
    chrome_cleaner::GetParamNameForTest());

// Tests where the process gets past the startup phase but finds nothing to
// clean. Since we don't progress to any stage where the parameters after
// UwsFoundStatus are used, their values would not change the test behaviour,
// so we can save time by only testing one arbitrary value for each.
INSTANTIATE_TEST_SUITE_P(
    CleanerFindsNothing,
    ChromeCleanerControllerTest,
    Combine(Values(CleanerProcessStatus::kFetchSuccessValidProcess),
            ValuesIn(kCrashPointsAfterStartup),
            Values(UwsFoundStatus::kNoUwsFound),
            Values(ItemsReporting::kNotReported),
            Values(UserResponse::kDismissed)),
    chrome_cleaner::GetParamNameForTest());

// Tests where the process fails to download. This never gets far enough to
// collect results, so we can save time by not repeating the tests for every
// possible combination of results parameters.
INSTANTIATE_TEST_SUITE_P(
    CleanerFailsToDownload,
    ChromeCleanerControllerTest,
    Combine(Values(CleanerProcessStatus::kFetchFailure),
            Values(CrashPoint::kNone),
            Values(UwsFoundStatus::kNoUwsFound),
            Values(ItemsReporting::kUnsupported),
            Values(UserResponse::kAcceptedWithLogs)),
    chrome_cleaner::GetParamNameForTest());

// Tests where the process fails before starting a scan. This never gets far
// enough to collect results, so we can save time by not repeating the tests
// for every possible combination of results parameters.
INSTANTIATE_TEST_SUITE_P(
    CleanerFailsToStart,
    ChromeCleanerControllerTest,
    Combine(Values(CleanerProcessStatus::kFetchSuccessInvalidProcess,
                   CleanerProcessStatus::kFetchSuccessValidProcess),
            // If the process status is kFetchSuccessValidProcess, crash on
            // startup. Otherwise the process never starts so the crash point
            // doesn't matter.
            Values(CrashPoint::kOnStartup),
            Values(UwsFoundStatus::kNoUwsFound),
            Values(ItemsReporting::kUnsupported),
            Values(UserResponse::kAcceptedWithLogs)),
    chrome_cleaner::GetParamNameForTest());

// Tests for the interaction between reporter runs and all possible states.
// Signals from reporter execution may lead to state transitions only if there
// is no cleaner activity, so it's enough to check the state after a signal.
//
// Parameters:
//  - initial_state_: the state of the controller before receiving a signal from
//        the reporter.
using ChromeCleanerControllerReporterInteractionTestParams =
    ChromeCleanerController::State;

class ChromeCleanerControllerReporterInteractionTest
    : public testing::TestWithParam<
          ChromeCleanerControllerReporterInteractionTestParams>,
      public ChromeCleanerControllerDelegate {
 public:
  void SetUp() override {
    initial_state_ = GetParam();

    ChromeCleanerControllerImpl::ResetInstanceForTesting();
    controller_ = ChromeCleanerControllerImpl::GetInstance();
    ASSERT_TRUE(controller_);

    controller_->SetDelegateForTesting(this);

    controller_->SetStateForTesting(initial_state_);
    ASSERT_EQ(initial_state_, controller_->state());
  }

  void TearDown() override {
    controller_->SetDelegateForTesting(nullptr);
    ChromeCleanerControllerImpl::ResetInstanceForTesting();
  }

  void ExpectNoStateChangeOnReporterSequenceDone(
      SwReporterInvocationResult reporter_result) {
    controller_->OnReporterSequenceDone(reporter_result);
    EXPECT_EQ(initial_state_, controller_->state());
  }

  void MaybeExpectStateChangeToIdle(
      SwReporterInvocationResult reporter_result,
      ChromeCleanerController::IdleReason idle_reason) {
    controller_->OnReporterSequenceDone(reporter_result);
    if (initial_state_ == ChromeCleanerController::State::kReporterRunning) {
      EXPECT_EQ(ChromeCleanerController::State::kIdle, controller_->state());
      EXPECT_EQ(idle_reason, controller_->idle_reason());
    } else {
      EXPECT_EQ(initial_state_, controller_->state());
    }
  }

  // We need this because we need UI and IO threads during tests. The thread
  // bundle should be the first member of the class so that it will be destroyed
  // last.
  content::BrowserTaskEnvironment task_environment_;

  ChromeCleanerController::State initial_state_;

  ChromeCleanerControllerImpl* controller_ = nullptr;
  StrictMock<MockChromeCleanerControllerObserver> mock_observer_;
};

TEST_P(ChromeCleanerControllerReporterInteractionTest,
       OnReporterSequenceStarted) {
  controller_->OnReporterSequenceStarted();
  EXPECT_EQ(initial_state_ == ChromeCleanerController::State::kIdle
                ? ChromeCleanerController::State::kReporterRunning
                : initial_state_,
            controller_->state());
}

TEST_P(ChromeCleanerControllerReporterInteractionTest,
       OnReporterSequenceDone_NotScheduled) {
  ExpectNoStateChangeOnReporterSequenceDone(
      SwReporterInvocationResult::kNotScheduled);
}

TEST_P(ChromeCleanerControllerReporterInteractionTest,
       OnReporterSequenceDone_TimedOut) {
  MaybeExpectStateChangeToIdle(
      SwReporterInvocationResult::kTimedOut,
      ChromeCleanerController::IdleReason::kReporterFailed);
}

TEST_P(ChromeCleanerControllerReporterInteractionTest,
       OnReporterSequenceDone_ProcessFailedToLaunch) {
  MaybeExpectStateChangeToIdle(
      SwReporterInvocationResult::kProcessFailedToLaunch,
      ChromeCleanerController::IdleReason::kReporterFailed);
}

TEST_P(ChromeCleanerControllerReporterInteractionTest,
       OnReporterSequenceDone_GeneralFailure) {
  MaybeExpectStateChangeToIdle(
      SwReporterInvocationResult::kGeneralFailure,
      ChromeCleanerController::IdleReason::kReporterFailed);
}

TEST_P(ChromeCleanerControllerReporterInteractionTest,
       OnReporterSequenceDone_NothingFound) {
  MaybeExpectStateChangeToIdle(
      SwReporterInvocationResult::kNothingFound,
      ChromeCleanerController::IdleReason::kReporterFoundNothing);
}

TEST_P(ChromeCleanerControllerReporterInteractionTest,
       OnReporterSequenceDone_CleanupNotOffered) {
  MaybeExpectStateChangeToIdle(
      SwReporterInvocationResult::kCleanupNotOffered,
      ChromeCleanerController::IdleReason::kReporterFoundNothing);
}

TEST_P(ChromeCleanerControllerReporterInteractionTest,
       OnReporterSequenceDone_CleanupToBeOffered) {
  ExpectNoStateChangeOnReporterSequenceDone(
      SwReporterInvocationResult::kCleanupToBeOffered);
}

INSTANTIATE_TEST_SUITE_P(
    All,
    ChromeCleanerControllerReporterInteractionTest,
    Values(ChromeCleanerController::State::kIdle,
           ChromeCleanerController::State::kReporterRunning,
           ChromeCleanerController::State::kScanning,
           ChromeCleanerController::State::kInfected,
           ChromeCleanerController::State::kCleaning,
           ChromeCleanerController::State::kRebootRequired),
    chrome_cleaner::GetParamNameForTest());

}  // namespace
}  // namespace safe_browsing


text:
'use strict';

angular.module('restHackApp')
.controller('DeleteGameCtrl', function ($scope, User, Auth) {
  $scope.errors = {};

  $scope.deleteGame = function(form) {
    $scope.submitted = true;
    if(form.$valid) {
      //
    }
  };
});


text:
package com.nereuschen.eda.core.impl;

import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import com.nereuschen.eda.channel.MessageChannel;
import com.nereuschen.eda.channel.PollableChannel;
import com.nereuschen.eda.core.AsyncMessagingOperations;
import com.nereuschen.eda.core.MessagePostProcessor;
import com.nereuschen.eda.message.Message;
import com.nereuschen.eda.util.Assert;

/**
 * @author Mark Fisher
 * @author Nereus Chen (nereus.chen@gmail.com)
 * @since 2.0
 */
public class AsyncMessagingTemplate extends MessagingTemplate implements
		AsyncMessagingOperations {

	private volatile ExecutorService executor = Executors.newFixedThreadPool(2);

	public void setExecutor(Executor executor) {
		Assert.notNull(executor, "executor must not be null");
		this.executor = (ExecutorService) executor;
	}

	public Future<?> asyncSend(final Message<?> message) {
		return this.executor.submit(new Runnable() {
			public void run() {
				send(message);
			}
		});
	}

	public Future<?> asyncSend(final MessageChannel channel,
			final Message<?> message) {
		return this.executor.submit(new Runnable() {
			public void run() {
				send(channel, message);
			}
		});
	}

	public Future<?> asyncConvertAndSend(final Object object) {
		return this.executor.submit(new Runnable() {
			public void run() {
				convertAndSend(object);
			}
		});
	}

	public Future<?> asyncConvertAndSend(final MessageChannel channel,
			final Object object) {
		return this.executor.submit(new Runnable() {
			public void run() {
				convertAndSend(channel, object);
			}
		});
	}

	public Future<Message<?>> asyncReceive() {
		return this.executor.submit(new Callable<Message<?>>() {
			public Message<?> call() throws Exception {
				return receive();
			}
		});
	}

	public Future<Message<?>> asyncReceive(final PollableChannel channel) {
		return this.executor.submit(new Callable<Message<?>>() {
			public Message<?> call() throws Exception {
				return receive(channel);
			}
		});
	}

	@SuppressWarnings("unchecked")
	public <R> Future<R> asyncReceiveAndConvert() {
		return this.executor.submit(new Callable<R>() {
			public R call() throws Exception {
				return (R) receiveAndConvert();
			}
		});
	}

	@SuppressWarnings("unchecked")
	public <R> Future<R> asyncReceiveAndConvert(final PollableChannel channel) {
		return this.executor.submit(new Callable<R>() {
			public R call() throws Exception {
				return (R) receiveAndConvert(channel);
			}
		});
	}

	public Future<Message<?>> asyncSendAndReceive(
			final Message<?> requestMessage) {
		return this.executor.submit(new Callable<Message<?>>() {
			public Message<?> call() throws Exception {
				return sendAndReceive(requestMessage);
			}
		});
	}

	public Future<Message<?>> asyncSendAndReceive(final MessageChannel channel,
			final Message<?> requestMessage) {
		return this.executor.submit(new Callable<Message<?>>() {
			public Message<?> call() throws Exception {
				return sendAndReceive(channel, requestMessage);
			}
		});
	}

	@SuppressWarnings("unchecked")
	public <R> Future<R> asyncConvertSendAndReceive(final Object request) {
		return this.executor.submit(new Callable<R>() {
			public R call() throws Exception {
				return (R) convertSendAndReceive(request);
			}
		});
	}

	@SuppressWarnings("unchecked")
	public <R> Future<R> asyncConvertSendAndReceive(
			final MessageChannel channel, final Object request) {
		return this.executor.submit(new Callable<R>() {
			public R call() throws Exception {
				return (R) convertSendAndReceive(channel, request);
			}
		});
	}

	@SuppressWarnings("unchecked")
	public <R> Future<R> asyncConvertSendAndReceive(final Object request,
			final MessagePostProcessor requestPostProcessor) {
		return this.executor.submit(new Callable<R>() {
			public R call() throws Exception {
				return (R) convertSendAndReceive(request, requestPostProcessor);
			}
		});
	}

	@SuppressWarnings("unchecked")
	public <R> Future<R> asyncConvertSendAndReceive(
			final MessageChannel channel, final Object request,
			final MessagePostProcessor requestPostProcessor) {
		return this.executor.submit(new Callable<R>() {
			public R call() throws Exception {
				return (R) convertSendAndReceive(channel, request,
						requestPostProcessor);
			}
		});
	}
}


text:
package svchost

import (
	"strings"
)

// A labelIter allows iterating over domain name labels.
//
// This type is copied from golang.org/x/net/idna, where it is used
// to segment hostnames into their separate labels for analysis. We use
// it for the same purpose here, in ForComparison.
type labelIter struct {
	orig     string
	slice    []string
	curStart int
	curEnd   int
	i        int
}

func (l *labelIter) done() bool {
	return l.curStart >= len(l.orig)
}

func (l *labelIter) label() string {
	if l.slice != nil {
		return l.slice[l.i]
	}
	p := strings.IndexByte(l.orig[l.curStart:], '.')
	l.curEnd = l.curStart + p
	if p == -1 {
		l.curEnd = len(l.orig)
	}
	return l.orig[l.curStart:l.curEnd]
}

// next sets the value to the next label. It skips the last label if it is empty.
func (l *labelIter) next() {
	l.i++
	if l.slice != nil {
		if l.i >= len(l.slice) || l.i == len(l.slice)-1 && l.slice[l.i] == "" {
			l.curStart = len(l.orig)
		}
	} else {
		l.curStart = l.curEnd + 1
		if l.curStart == len(l.orig)-1 && l.orig[l.curStart] == '.' {
			l.curStart = len(l.orig)
		}
	}
}


text:
all: clean install test

install:
	@npm install

test:
	@NODE_ENV=test node_modules/.bin/hydro

test-ci: test

clean:
	@rm -rf node_modules

.PHONY: test


text:
@interface UserCollectionCell : UICollectionViewCell

@property (readonly) UIImageView * userImage;

@end


text:
namespace OpenApoc
{

void TileObjectScenery::draw(Renderer &r, TileTransform &transform, Vec2<float> screenPosition,
                             TileViewMode mode)
{
	std::ignore = transform;
	// Mode isn't used as TileView::tileToScreenCoords already transforms according to the mode
	auto scenery = this->scenery.lock();
	if (!scenery)
	{
		LogError("Called with no owning scenery object");
		return;
	}
	// FIXME: If damaged use damaged tile sprites?
	auto &type = scenery->type;
	sp<Image> sprite;
	sp<Image> overlaySprite;
	Vec2<float> transformedScreenPos = screenPosition;
	switch (mode)
	{
		case TileViewMode::Isometric:
			sprite = type->sprite;
			overlaySprite = type->overlaySprite;
			transformedScreenPos -= type->imageOffset;
			break;
		case TileViewMode::Strategy:
			sprite = type->strategySprite;
			// All strategy sprites so far are 8x8 so offset by 4 to draw from the center
			// FIXME: Not true for large sprites (2x2 UFOs?)
			transformedScreenPos -= Vec2<float>{4, 4};
			break;
		default:
			LogError("Unsupported view mode");
	}
	if (sprite)
		r.draw(sprite, transformedScreenPos);
	// FIXME: Should be drawn at 'later' Z than scenery (IE on top of any vehicles on tile?)
	if (overlaySprite)
		r.draw(overlaySprite, transformedScreenPos);
}

TileObjectScenery::~TileObjectScenery() = default;

TileObjectScenery::TileObjectScenery(TileMap &map, sp<Scenery> scenery)
    : TileObject(map, Type::Scenery, Vec3<float>{1, 1, 1}), scenery(scenery)
{
}

sp<Scenery> TileObjectScenery::getOwner()
{
	auto s = this->scenery.lock();
	if (!s)
	{
		LogError("Owning scenery object disappeared");
	}
	return s;
}

sp<VoxelMap> TileObjectScenery::getVoxelMap() { return this->getOwner()->type->voxelMap; }

Vec3<float> TileObjectScenery::getPosition() const
{
	auto s = this->scenery.lock();
	if (!s)
	{
		LogError("Called with no owning scenery object");
		return {0, 0, 0};
	}
	return s->getPosition();
}

} // namespace OpenApoc


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
        http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-4.3.xsd
		http://www.springframework.org/schema/task
		http://www.springframework.org/schema/task/spring-task-4.3.xsd">

	<context:component-scan base-package="org.finance">
		<!--context:exclude-filter type="regex" expression="elf.server.ems.*" /-->
	</context:component-scan>
</beans>


text:
import Ember from 'ember';
import helpers from 'ember-google-map/core/helpers';
import GoogleMapCoreView from './core';
import MarkerView from './marker';

var observer = Ember.observer;
var run = Ember.run;
var on = Ember.on;
var scheduleOnce = Ember.run.scheduleOnce;
var computed = Ember.computed;
var alias = computed.alias;
var oneWay = computed.oneWay;

/**
 * @class GoogleMapInfoWindowView
 * @extends GoogleMapCoreView
 */
export default GoogleMapCoreView.extend({
  classNames: ['google-info-window'],

  googleFQCN: 'google.maps.InfoWindow',

  // will be either the marker using us, or the component if this is a detached info-window
  templateName: computed.any('controller.templateName', 'parentView.infoWindowTemplateName'),

  googleProperties: {
    zIndex:    {event: 'zindex_changed', cast: helpers.cast.integer},
    map:       {readOnly: true},
    'lat,lng': {
      name:       'position',
      event:      'position_changed',
      toGoogle:   helpers._latLngToGoogle,
      fromGoogle: helpers._latLngFromGoogle
    }
  },

  isMarkerInfoWindow: computed('parentView', {
    get() {
      return (this.get('parentView') instanceof MarkerView);
    }
  }),

  _coreGoogleEvents: ['closeclick'],

  // aliased from controller so that if they are not defined they use the values from the controller
  zIndex: alias('controller.zIndex'),
  lat:    alias('controller.lat'),
  lng:    alias('controller.lng'),
  anchor: oneWay('parentView.infoWindowAnchor'),

  visible: computed('parentView.isInfoWindowVisible', 'controller.isVisible', {
    get() {
      var value, isMarkerIW = this.get('isMarkerInfoWindow');
      if (isMarkerIW) {
        value = this.get('parentView.isInfoWindowVisible');
      }
      else {
        value = this.getWithDefault('controller.isVisible', true);
        run(this, 'set', 'controller.isVisible', value);
      }
      return value;
    },
    set(key, value) {
      var isMarkerIW = this.get('isMarkerInfoWindow');
      value = Boolean(value);
      if (isMarkerIW) {
        this.set('parentView.isInfoWindowVisible', value);
      }
      else {
        this.set('controller.isVisible', value);
      }
      return value;
    }
  }),

  initGoogleObject: on('didInsertElement', function () {
    scheduleOnce('afterRender', this, '_initGoogleInfoWindow');
  }),

  handleInfoWindowVisibility: observer('visible', function () {
    if (this._changingVisible) {
      return;
    }
    var iw = this.get('googleObject');
    if (iw) {
      if (this.get('visible')) {
        iw.open(this.get('map'), this.get('anchor') || undefined);
      }
      else {
        iw.close();
      }
    }
  }),

  _initGoogleInfoWindow: function () {
    // force the creation of the marker
    if (helpers.hasGoogleLib() && !this.get('googleObject')) {
      this.createGoogleObject({content: this._backupViewElement()});
      this.handleInfoWindowVisibility();
    }
  },

  destroyGoogleObject: on('willDestroyElement', function () {
    var infoWindow = this.get('googleObject');
    if (infoWindow) {
      this._changingVisible = true;
      infoWindow.close();
      // detach from the map
      infoWindow.setMap(null);
      // free the content node
      this._restoreViewElement();
      this.set('googleObject', null);
      this._changingVisible = false;
    }
  }),

  _backupViewElement: function () {
    var element = this.get('element');
    if (!this._placeholderElement) {
      this._placeholderElement = document.createElement(element.nodeName);
      element.parentNode.replaceChild(this._placeholderElement, element);
    }
    return element;
  },

  _restoreViewElement: function () {
    var element = this.get('element');
    if (this._placeholderElement) {
      this._placeholderElement.parentNode.replaceChild(element, this._placeholderElement);
      this._placeholderElement = null;
    }
    return element;
  },

  _handleCoreEvent: function (name) {
    if (name === 'closeclick') {
      this._changingVisible = true;
      this.set('visible', false);
      this._changingVisible = false;
    }
  }
});


text:
import sys
from genAmplicons import misc

try:
    from genAmplicons import editdist
    editdist_loaded = True
except ImportError:
    sys.stderr.write("Warning: editdist library not loaded, Insertion/Deletion detection in barcodes and primers will not be performed\n")
    editdist_loaded = False

try:
    from genAmplicons import trim
    trim_loaded = True
except ImportError:
    sys.stderr.write("Warning: trim library not loaded, trimming using python\n")
    trim_loaded = False

def barcodeDist(b_1, b_2):
    # ------------------- calculate distance between two barcode sequences ------------------------------
    """
    gets edit distnace between two equal-length barcode strings
    """
    if editdist_loaded:
        return editdist.hamming_distance(b_1, b_2)
    elif len(b_1) == len(b_2) and len(b_1) > 0:
        return sum(map(lambda x: x[0] != x[1], zip(b_1, b_2)))
    else:
        sys.stderr.write("ERROR:[barcodeDist] lengths of barcodes and index read do not match!\n")
        sys.stderr.write("Target: %s" % b_1)
        sys.stderr.write("Index read: %s" % b_2)
        raise Exception

def primerDist(primer_l, read, dedup_float, max_diff, end_match):
    # ------------------- calculate distance between primer sequence and first part of read ------------------------------
    """
    gets edit distance between primer and read sequence
    """
    pr = None
    prMismatch = max_diff+1
    prStartPosition = 0
    prEndPosition = 0

    if editdist_loaded:
        pr_i, prMismatch, prStartPosition, prEndPosition = editdist.bounded_distance_list(primer_l, read, dedup_float, max_diff, end_match)

    else:
        for i, key in enumerate(primer_l):
            read = read[0:len(key)]
            if end_match == 0:
                dist = sum(map(lambda x: x[0] != x[1], zip(read, key)))
            else:
                dist = sum(map(lambda x: x[0] != x[1], zip(read[:-end_match], key[:-end_match])))
                for i in range(len(key)-end_match, len(key)):
                    if read[i] != key[i]:
                        dist += 100
            if dist < prMismatch:
                pr_i = i
                prMismatch = dist
                prEndPosition = len(key)

    if prMismatch > max_diff:
        pr = None
        prStartPosition = 0
        prEndPosition = 0
    else:
        pr = primer_l[pr_i]

    return (pr, prMismatch, prStartPosition, prEndPosition)

class FourSequenceReadSet:
    # ---------------- Class for 4 read sequence data with double barcode set ----------------
    """
    Class to hold one Illumina four read (double barocodes) set, only one read names is used for all sequence reads
    Class processes a read by defining the barcode pair and primer pair [optional] and project [optional]. Finally
    class returns a paired read set for output
    """

    def __init__(self, name, read_1, qual_1, read_2, qual_2, bc_1, bc_2):
        """
        Initialize a FourSequenceReadSet with a name, two read sequences
        and cooresponding quality sequence and two barcode sequences. A read
        is initially defined as 'not' a good read and requires processing before
        being labeled as a good read.
        """
        self.barcode = [None, 0, 0]  # when filled, a vector of length 3 [barcodePairID, editdist1, editdist2]
        self.primer = [None, None, 0, 0, None, 0, 0]  # when filled, a vector of length 7 [primerPairID,primerID1,editdist1,readendpos1, primerID2,editdist2,readendpos2]
        self.sample = None
        self.project = None
        self.name = name
        self.read_1 = read_1
        self.qual_1 = qual_1
        self.read_2 = read_2
        self.qual_2 = qual_2
        self.bc_1 = bc_1
        self.bc_2 = bc_2
        self.trim_left = len(read_1)
        self.trim_right = len(read_2)
        self.goodRead = False

    def assignBarcode(self, bcTable, max_diff):
        """
        Given a barcodeTable object and the maximum number of allowed difference (mismatch, insertion, deletions)
        assign a barcode pair ID from the reads barcodes.
        """
        # Barcode One Matching
        bc1 = None
        bc1Mismatch = max_diff+1
        for key in bcTable.getP7():
            bcdist = barcodeDist(key, self.bc_1)
            if bcdist < bc1Mismatch:
                bc1 = key
                bc1Mismatch = bcdist
        # Barcode Two Matching
        bc2 = None
        bc2Mismatch = max_diff+1
        for key in bcTable.getP5():
            bcdist = barcodeDist(key, self.bc_2)
            if bcdist < bc2Mismatch:
                bc2 = key
                bc2Mismatch = bcdist
        # Barcode Pair Matching
        self.barcode = [bcTable.getMatch(bc1, bc2), bc1Mismatch, bc2Mismatch]
        self.goodRead = self.barcode[0] is not None
        self.sample = self.barcode[0]
        return 0

    def assignPrimer(self, prTable, max_diff, endmatch):
        """
        Given a primerTable object, the maximum number of allowed difference (mismatch, insertion, deletions) and the
        required number of end match bases (final endmatch bases must match) assign a primer pair ID from the read
        sequences.
        """
        # Barcode One Matching
        pr1 = None
        pr1Mismatch = max_diff+1
        pr1Position = 0
        for key in prTable.getP5sequences():
            prdist = primerDist(key, self.read_1, max_diff, endmatch)
            if prdist[0] < pr1Mismatch:
                pr1 = key
                pr1Mismatch = prdist[0]
                pr1Position = prdist[1]
        # Barcode Two Matching
        pr2 = None
        pr2Mismatch = max_diff+1
        pr2Position = 0
        for key in prTable.getP7sequences():
            prdist = primerDist(key, self.read_2, max_diff, endmatch)
            if prdist[0] < pr2Mismatch:
                pr2 = key
                pr2Mismatch = prdist[0]
                pr2Position = prdist[1]
        # Barcode Pair Matching
        combined_pr = prTable.getMatch(pr1, pr2)
        self.goodRead = self.goodRead and combined_pr[0] is not None and pr1Mismatch <= max_diff and pr2Mismatch <= max_diff
        self.primer = [combined_pr[0], combined_pr[1], pr2Mismatch, pr1Position, combined_pr[2], pr2Mismatch, pr2Position]
        return 0

    def assignRead(self, sTable):
        """
        Given a samplesTable object, assign a sample ID and project ID using the reads barcode and primer designation
        """
        self.project = sTable.getProjectID(self.barcode[0], self.primer[0])
        self.sample = sTable.getSampleID(self.barcode[0], self.primer[0])
        self.goodRead = self.project is not None
        return 0

    def trimRead(self, minQ, minL):
        """
        Trim the read by a minQ score
        """
        if (trim_loaded):
            trim_points = trim.trim(self.qual_1, self.qual_2, minQ)
            self.trim_left = trim_points["left_trim"]
            self.trim_right = trim_points["right_trim"]
            if ((self.trim_left-self.primer[3]) < minL or (self.trim_right-self.primer[6]) < minL):
                self.goodRead = False

    def getBarcode(self):
        """
        Return the reads barcode pair ID
        """
        return self.barcode[0]

    def getPrimer(self):
        """
        Return the reads primer pair ID
        """
        return self.primer[0]

    def getSampleID(self):
        """
        Return the reads sample ID
        """
        return self.sample

    def getProject(self):
        """
        Return the reads project ID
        """
        return self.project

    def getFastq(self, kprimer):
        """
        Create four line string ('\n' separator included) for the read pair, returning a length 2 vector (one for each read)
        """
        if self.primer[0] is not None and kprimer is False:
            read1_name = "%s 1:N:0:%s:%s %s|%s|%s|%s %s|%s|%s" % (self.name, self.sample, self.primer[0], self.bc_1, self.barcode[1], self.bc_2, self.barcode[2], self.primer[1], self.primer[2], self.primer[3])
            read2_name = "%s 2:N:0:%s:%s %s|%s|%s|%s %s|%s|%s" % (self.name, self.sample, self.primer[0], self.bc_1, self.barcode[1], self.bc_2, self.barcode[2], self.primer[4], self.primer[5], self.primer[6])
            r1 = '\n'.join([read1_name, self.read_1[self.primer[3]:self.trim_left], '+', self.qual_1[self.primer[3]:self.trim_left]])
            r2 = '\n'.join([read2_name, self.read_2[self.primer[6]:self.trim_right], '+', self.qual_2[self.primer[6]:self.trim_right]])
        else:
            read1_name = "%s 1:N:0:%s %s|%s|%s|%s" % (self.name, self.sample, self.bc_1, self.barcode[1], self.bc_2, self.barcode[2])
            read2_name = "%s 2:N:0:%s %s|%s|%s|%s" % (self.name, self.sample, self.bc_1, self.barcode[1], self.bc_2, self.barcode[2])
            r1 = '\n'.join([read1_name, self.read_1[0:self.trim_left], '+', self.qual_1[0:self.trim_left]])
            r2 = '\n'.join([read2_name, self.read_2[0:self.trim_right], '+', self.qual_2[0:self.trim_right]])
        return [r1, r2]

# ---------------- Class for 2 read sequence data processed with dbcAmplicons preprocess ----------------
class TwoSequenceReadSet:
    """
    Class to hold one Illumina two read set, assumed to have already been preprocessed with Barcodes and Primers already
    identified. Class processes a read by defining sample and project ids. Finally class returns a paired read set for output.
    """
    def __init__(self, name_1, read_1, qual_1, name_2, read_2, qual_2):
        """
        Initialize a TwoSequenceReadSet with names, two read sequences and cooresponding quality sequence.
        Barcode and primer sequence is inferred by their placement in the read names.
        A read is initially defined as 'not' a good read and requires processing before being labeled as a good read.
        """
        try:
            split_name = name_1.split(" ")
            self.name = split_name[0]
            self.barcode = split_name[1].split(":")[3]
            self.sample = self.barcode
            # dbcAmplicons processed, Primer and Barcode Identified
            if (len(split_name) == 4):
                self.primer_string1 = split_name[3]
                self.primer_string2 = name_2.split(" ")[3]
                self.primer = split_name[1].split(":")[4]
                self.barcode_string = split_name[2]
            # dbcAmplicons processed, Barcode only Identified
            elif (len(split_name) == 3):
                self.primer_string1 = None
                self.primer_string2 = None
                self.primer = None
                self.barcode_string = split_name[2]
            # Casava processed, check for barcode in the second string
            else:
                self.primer_string1 = None
                self.primer_string2 = None
                self.primer = None
                self.barcode_string = None
            self.read_1 = read_1
            self.qual_1 = qual_1
            self.read_2 = read_2
            self.qual_2 = qual_2
            self.trim_left = len(read_1)
            self.trim_right = len(read_2)
            self.goodRead = False
        except IndexError:
            sys.stderr.write('ERROR:[TwoSequenceReadSet] Read names are not formatted in the expected manner\n')
            raise
        except:
            sys.stderr.write('ERROR:[TwoSequenceReadSet] Unknown error occured initiating read\n')
            raise

    def assignBarcode(self, bcTable, max_diff):
        """
        Given a barcodeTable object and the maximum number of allowed difference (mismatch, insertion, deletions)
        assign a barcode pair ID from the reads barcodes.
        """

        # HARD CODED
        bc_1 = self.read_2[0:8]

        # Barcode One Matching
        bc1 = None
        bc1Mismatch = max_diff+1
        for key in bcTable.getP7():
            bcdist = barcodeDist(key, bc_1)
            if bcdist < bc1Mismatch:
                bc1 = key
                bc1Mismatch = bcdist
        # Barcode Two Matching
        bc2 = None
        bc2Mismatch = max_diff+1
        # for key in bcTable.getP5():
        #     bcdist = barcodeDist(key, self.bc_2)
        #     if bcdist < bc2Mismatch:
        #         bc2 = key
        #         bc2Mismatch = bcdist
        # Barcode Pair Matching
        self.barcode = [bcTable.getMatch(bc1, bc2), bc_1, bc1Mismatch, bc2Mismatch]
        self.goodRead = self.barcode[0] is not None
        self.sample = self.barcode[0]
        if self.goodRead:
            self.read_2 = self.read_2[8:]
            self.qual_2 = self.qual_2[8:]

        return 0

    def checkLinker(self, sequence, dedup_float, max_diff, endmatch):

        # Primer One Matching
        linker, linkerMismatch, linkerStartPosition, linkerEndPosition = primerDist([sequence], self.read_2, dedup_float, max_diff, endmatch)

        self.MI1 = self.read_2[0:linkerStartPosition]

        self.linker = [linker, linkerMismatch, linkerStartPosition, linkerEndPosition]
        self.goodRead = self.goodRead and linker is not None
        if self.goodRead:
            self.read_2 = self.read_2[linkerEndPosition:]
            self.qual_2 = self.qual_2[linkerEndPosition:]
            return 1
        else:
            return 0

    def assignPrimer(self, prTable, dedup_float, max_diff, endmatch):
        """
        Given a primerTable object, the maximum number of allowed difference (mismatch, insertion, deletions) and the
        required number of end match bases (final endmatch bases must match) assign a primer pair ID from the read
        sequences.
        """
        # Primer One Matching
        pr1, pr1Mismatch, pr1StartPosition, pr1EndPosition = primerDist(prTable.getP5sequences(), self.read_1, 0, max_diff, endmatch)

        # Primer One Matching
        pr2, pr2Mismatch, pr2StartPosition, pr2EndPosition = primerDist(prTable.getP7sequences(), self.read_2, 4, max_diff, endmatch)

        self.MI2 = self.read_2[0:pr2StartPosition]
        # Barcode Pair Matching
        combined_pr = prTable.getMatch(pr1, pr2)
        self.primer = [combined_pr[0], combined_pr[1], pr1Mismatch, pr1StartPosition, pr1EndPosition, combined_pr[2], pr2Mismatch, pr2StartPosition, pr2EndPosition]
        self.goodRead = self.goodRead and combined_pr[0] is not None
        if self.goodRead:
            return 1
        else:
            return 0

    def assignRead(self, sTable):
        """
        Given a samplesTable object, assign a sample ID and project ID using the reads barcode and primer designation
        """
        self.project = sTable.getProjectID(self.barcode[0], self.primer[0])
        self.sample = sTable.getSampleID(self.barcode[0], self.primer[0])
        self.goodRead = self.project is not None
        return 0

    def getBarcode(self):
        """
        Return the reads barcode pair ID
        """
        return self.barcode[0]

    def getLinker(self):
        """
        Return the reads barcode pair ID
        """
        return self.linker[0]

    def getPrimer(self):
        """
        Return the reads primer pair ID
        """
        return self.primer[0]

    def getSampleID(self):
        """
        Return the reads sample ID
        """
        return self.sample

    def getProject(self):
        """
        Return the reads project ID
        """
        return self.project

    def trimRead(self, minQ, minL):
        """
        Trim the read by a minQ score
        """
        if (trim_loaded):
            trim_points = trim.trim(self.qual_1, self.qual_2, minQ)
            self.trim_left = trim_points["left_trim"]
            self.trim_right = trim_points["right_trim"]
            if (self.trim_left < minL or self.trim_right < minL):
                self.goodRead = False

    def getFastqSRA(self):
        """
        Create four line string ('\n' separator included) for the read pair, returning a length 2 vector (one for each read)
        """
        read1_name = "%s 1:N:0:" % (self.name)
        read2_name = "%s 2:N:0:" % (self.name)
        r1 = '\n'.join([read1_name, self.read_1[0:self.trim_left], '+', self.qual_1[0:self.trim_left]])
        r2 = '\n'.join([read2_name, self.read_2[0:self.trim_right], '+', self.qual_2[0:self.trim_right]])
        return [r1, r2]

    def getFastq(self):
        """
        Create four line string ('\n' separator included) for the read pair, returning a length 2 vector (one for each read)
        """
        if self.primer is not None:
            read1_name = "%s 1:N:0:%s:%s %s %s" % (self.name, self.sample, self.primer, self.barcode_string, self.primer_string1)
            read2_name = "%s 2:N:0:%s:%s %s %s" % (self.name, self.sample, self.primer, self.barcode_string, self.primer_string2)
        else:
            read1_name = "%s 1:N:0:%s %s" % (self.name, self.sample, self.barcode_string)
            read2_name = "%s 2:N:0:%s %s" % (self.name, self.sample, self.barcode_string)
        r1 = '\n'.join([read1_name, self.read_1[0:self.trim_left], '+', self.qual_1[0:self.trim_left]])
        r2 = '\n'.join([read2_name, self.read_2[0:self.trim_right], '+', self.qual_2[0:self.trim_right]])
        return [r1, r2]

    def getFastq2(self, kprimer):
        """
        Create four line string ('\n' separator included) for the read pair, returning a length 2 vector (one for each read)
        """
        if self.primer[0] is not None and kprimer is False:
            read1_name = "%s*%s|%s*%s|%s|%s*%s|%s|%s|%s*%s|%s 1:N:0:None" % (self.name, self.sample, self.primer[0], self.barcode[0], self.barcode[1], self.barcode[2], self.primer[1], self.primer[2], self.primer[5], self.primer[6], self.MI1, self.MI2)
            read2_name = "%s*%s|%s*%s|%s|%s*%s|%s|%s|%s*%s|%s 2:N:0:None" % (self.name, self.sample, self.primer[0], self.barcode[0], self.barcode[1], self.barcode[2], self.primer[1], self.primer[2], self.primer[5], self.primer[6], self.MI1, self.MI2)
            r1 = '\n'.join([read1_name, self.read_1[self.primer[4]:self.trim_left], '+', self.qual_1[self.primer[4]:self.trim_left]])
            r2 = '\n'.join([read2_name, self.read_2[self.primer[8]:self.trim_right], '+', self.qual_2[self.primer[8]:self.trim_right]])
        else:
            read1_name = "%s*%s*%s|%s|%s|%s*%s|%s 1:N:0:None" % (self.name, self.sample, self.barcode[0], self.barcode[1], self.barcode[2], self.MI1, self.MI2)
            read2_name = "%s*%s*%s|%s|%s|%s*%s|%s 2:N:0:None" % (self.name, self.sample, self.barcode[0], self.barcode[1], self.barcode[2], self.MI1, self.MI2)
            r1 = '\n'.join([read1_name, self.read_1[0:self.trim_left], '+', self.qual_1[0:self.trim_left]])
            r2 = '\n'.join([read2_name, self.read_2[0:self.trim_right], '+', self.qual_2[0:self.trim_right]])
        return [r1, r2]

    def getFourReads(self, bc1_length=8, bc2_length=8):
        """
        Create four line string ('\n' separator included) for the read set, returning a length 4 vector (one for each read)
        """
        try:
            if self.barcode_string is not None:
                bc1 = self.barcode_string.split('|')[0]
                bc2 = self.barcode_string.split('|')[2]
            elif len(self.barcode) is (bc1_length+bc2_length):
                bc1 = self.barcode[:bc1_length]
                bc2 = self.barcode[bc1_length:]
            else:
                raise Exception("string in the barcode is not %s characters" % str(bc1_length+bc2_length))
            r1 = '\n'.join([self.name + ' 1:Y:0:', self.read_1[0:self.trim_left], '+', self.qual_1[0:self.trim_left]])
            r2 = '\n'.join([self.name + ' 2:Y:0:', bc1, '+', 'C' * len(bc1)])  # Give barcodes and arbitary quality of Cs
            r3 = '\n'.join([self.name + ' 3:Y:0:', bc2, '+', 'C' * len(bc2)])
            r4 = '\n'.join([self.name + ' 4:Y:0:', self.read_2[0:self.trim_right], '+', self.qual_2[0:self.trim_right]])
            return [r1, r2, r3, r4]
        except IndexError:
            sys.stderr.write('ERROR:[TwoSequenceReadSet] unable to exract barocode sequence from the read names\n')
            raise
        except:
            sys.stderr.write('ERROR:[TwoSequenceReadSet] Unknown error occured generating four read set\n')
            raise

    def getFasta(self):
        """
        Create two line string ('\n' separator included) for the read pair, returning a length 1 vector (one read)
        """
        name = '>' + self.name[1:]
        if self.primer is not None:
            read1_name = "%s 1:N:0:%s:%s:%i" % (name, self.sample, self.primer, len(self.read_1))
            read2_name = "%s 2:N:0:%s:%s:%i" % (name, self.sample, self.primer, len(self.read_2))
        else:
            read1_name = "%s 1:N:0:%s:%i" % (name, self.sample, len(self.read_1))
            read2_name = "%s 2:N:0:%s:%i" % (name, self.sample, len(self.read_2))
        r1 = '\n'.join([read1_name, self.read_1[0:self.trim_left]])
        r2 = '\n'.join([read2_name, self.read_2[0:self.trim_right]])
        return [r1, r2]

    def getJoinedFasta(self):
        """
        Create two line string ('\n' separator included) for the read pair, concatenating the two reads into a single returning length 1 vector (one read)
        """
        name = '>' + self.name[1:]
        joined_seq = self.read_1[0:self.trim_left] + misc.reverseComplement(self.read_2[0:self.trim_right])
        if self.primer is not None:
            read1_name = "%s|%s:%s:PAIR" % (name, self.sample, self.primer)
        else:
            read1_name = "%s|%s:PAIR" % (name, self.sample)
        r1 = '\n'.join([read1_name, joined_seq])
        return [r1]

# ---------------- Class for 2 read sequence data processed with dbcAmplicons preprocess ----------------
class OneSequenceReadSet:
    """
    Class to hold a one Illumina read set, assumes the paired reads produced by dbcAmplicons preprocess have been merged
    """
    def __init__(self, name_1, read_1, qual_1):
        """
        Initialize a OneSequenceReadSet with name, one read sequences and cooresponding quality sequence.
        A read is initially defined as 'not' a good read and requires processing before being labeled as a good read.
        """
        self.goodRead = False
        self.primer = None
        # parse the read name for the sample and primer ids
        try:
            split_name = name_1.split(" ")
            self.name = split_name[0]
            self.sample = split_name[1].split(":")[3]
            if (len(split_name) == 4):
                self.primer = split_name[1].split(":")[4]
        except IndexError:
            sys.stderr.write('ERROR:[OneSequenceReadSet] Read names are not formatted in the expected manner\n')
            raise
        except:
            sys.stderr.write('ERROR:[OneSequenceReadSet] Unknown error occured initiating read\n')
            raise
        self.read_1 = read_1
        self.qual_1 = qual_1

    def getFastqSRA(self):
        """
        Create four line string ('\n' separator included) for the read pair, returning a length 2 vector (one for each read)
        """
        read1_name = "%s 1:N:0:" % (self.name)
        r1 = '\n'.join([read1_name, self.read_1, '+', self.qual_1])
        return [r1]

    def getFastq(self):
        """
        Create four line string ('\n' separator included) for the read, returning a length 1 vector (one read)
        """
        if self.primer is not None:
            read1_name = "%s 1:N:0:%s:%s" % (self.name, self.sample, self.primer)
        else:
            read1_name = "%s 1:N:0:%s" % (self.name, self.sample)
        r1 = '\n'.join([read1_name, self.read_1, '+', self.qual_1])
        return [r1]

    def getFasta(self):
        """
        Create two line string ('\n' separator included) for the read, returning a length 1 vector (one read)
        """
        name = '>' + self.name[1:]
        if self.primer is not None:
            read1_name = "%s|%s:%s:%i" % (name, self.sample, self.primer, len(self.read_1))
        else:
            read1_name = "%s|%s:%i" % (name, self.sample, len(self.read_1))
        r1 = '\n'.join([read1_name, self.read_1])
        return [r1]