text:
Interes::Interes(string jsonInteres){
    JsonObject datos(jsonInteres);

    this->categoria = datos.getString("category");
    this->valor = datos.getString("value");
    Logger::Instance()->log(INFO, "Se crea interes "+ categoria + ": " + valor);
}

Interes::~Interes()
{
    //dtor
}

JsonObject Interes::toJsonObject(){
    JsonObject datos;
    datos.agregarClaveValor("category", this->categoria);
    datos.agregarClaveValor("value", this->valor);
    return datos;
}

string Interes::getCategoria(){
    return this->categoria;
}

string Interes::getValor(){
    return this->valor;
}

bool Interes::comparar(Interes& interes){
    return ((this->categoria == interes.getCategoria()) && (this->valor == interes.getValor()));

}


text:
using Pickaxe.Runtime.Dom;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Pickaxe.Runtime
{
    public class SelectDownloadPage : LazyDownloadPage
    {
        public SelectDownloadPage(ThreadedDownloadTable<DownloadPage> parent) : base(parent)
        {
        }

        public override bool CssWhere(ref DownloadPage page, string selector)
        {
            CssSelector = selector;
            page = this;
            return true;
        }

        protected override void ApplyCssSelector(IEnumerable<HtmlElement> nodes)
        {
            if(nodes.Count() > 0)
                Inner.nodes = new DownloadedNodes(nodes.First().QuerySelectorAll(CssSelector));

            CssSelector = null;
        }

        public override void Clear()
        {
            Inner.Clear();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

-->
<view xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../../lib/internal/Magento/Framework/Config/etc/view.xsd">
    <vars module="One">
        <var name="one">Value One</var>
    </vars>
    <vars module="Two">
        <var name="one">Value One</var>
    </vars>
</view>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Peziza cenangioides Ellis

### Remarks
null


text:
"""Functionality for creating and working with NTOR keys.

For a description of the NTOR handshake protocol, as well as its requisite
keys, see §5.1.4 of `tor-spec.txt`_, as well as the NTOR handshake proposal_.

.. _tor-spec.txt: https://gitweb.torproject.org/torspec.git/tree/tor-spec.txt
.. _proposal: https://gitweb.torproject.org/torspec.git/tree/proposals/216-ntor-handshake.txt
"""

from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals

import binascii
import logging
import warnings

# Get rid of the `UserWarning: reimporting '_cffi__x6e273d72xa4719796' might
# overwrite older definitions` warnings when importing nacl:
warnings.simplefilter('ignore', UserWarning, append=True)

nacl = None

try:
    import nacl
    import nacl.public
except (ImportError, NameError, IOError) as error:
    logging.warn("Could not import pyNaCl: https://github.com/pyca/pynacl. "\
                 "NTOR key generation will be disabled.")

class NTORKeyCreationError(Exception):
    """Raised when there was an error creating an NTOR key."""

class NTORPublicKeyError(Exception):
    """Raised when there is an error deriving the public Curve25519 key."""

def createNTORSecretKey():
    """Create a base64-encoded Curve25519 Salsa20-Poly1305 key.

    See §5.1.4 of `tor-spec.txt`_, as well as
    torspec.git/proposals/216-ntor-handshake.txt (specifically the
    "Integrating with the rest of Tor" section towards the end). For a full
    description of the Curve25519 keypair, see "Curve25519: new Diffie-Hellman
    speed records" by D.J. Bernstein.

    .. important:: The subkey used in the NTOR handshake protocol should be
        generated via HKDF-SHA256 as defined in :rfc:`5869`.

    .. _tor-spec.txt: https://gitweb.torproject.org/torspec.git/tree/tor-spec.txt

    :raises: NTORKeyCreationError, if pynacl is not available or not
       installed, or if there was any other error while creating the key (such
       as an error due to having a different Python NaCl wrapper installed).

    :returns: The base64-encoded value of **NTORKey**, if available. The
       trailing newline of the base64 value is stripped (though not the
       padding, despite what proposals/216-ntor-handshake.txt
       says). Otherwise, returns None.
    """
    if nacl is None:
        raise NTORKeyCreationError("NTOR key creation requires pynacl.")
    else:
        try:
            #: The OR's private NTOR onion key.
            ntorSK = nacl.public.PrivateKey.generate()
        except Exception as error:
            raise NTORKeyCreationError("Error creating NTOR key: %s" % error)
        else:
            return ntorSK

def getNTORPublicKey(ntorSecretKey=None, base64=True):
    """Get the public key from the secret portion of a Curve25519 keypair.

    The **base64** version of the public Curve25519 key return from this
    function is suitable for use in a ``@type [bridge-]server-descriptor``.

    .. todo:: Remember to tell nickm to fix the description in his proposal
        about the ntor-onion-key padding removal.

    :type ntorSecretKey: ``nacl.public.PrivateKey``
    :param ntorSecretKey: A key created with :func:`createNTORSecretKey`. If
                          not given, a new one will be created automatically.
    :param bool base64: If ``True``, return the base64-encoded NTOR public key
                        (with trailing newline removed).
    :raises: :exc:`NTORPublicKeyError` if there was an error retrieving the
             public key.
    :rtype: str or ``nacl.public.PublicKey`` or ``None``
    :returns: The base64-encoded string version of the public portion of a
              Curve25519 keypair, if **base64** is ``True``, otherwise,
              returns the ``nacl.public.PublicKey``. Returns ``None``, if no
              **ntorSecretKey** was given and one could not be created.
    """
    if not ntorSecretKey:
        try:
            ntorSecretKey = createNTORSecretKey()
        except NTORKeyCreationError as error:
            logging.debug(error)

    if ntorSecretKey:
        try:
            #: The OR's public NTOR key; this goes into its
            #: ``@type [bridge]-server-descriptor``.
            ntorPublicKey = ntorSecretKey.public_key
            if base64:
                ntorPublicKey = binascii.b2a_base64(
                    bytearray(str(ntorPublicKey))).rstrip('\n').rstrip('==')
        except Exception as error:
            raise NTORPublicKeyError("Error retrieving the NTOR public key: %s"
                                     % error)
        else:
            return ntorPublicKey


text:
package code;

import java.awt.FileDialog;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import javax.swing.JFrame;
import javax.swing.UIManager;

import code.base.Board_024;
import code.base.Player_024_047;
import code.base.Scrabble_024_047;
import code.base.TileRack_024;
import code.base.Inventory_024;
import code.client.BoardFrame_047;
import code.client.PlayerFrame_047;

/**
 * @author tylerdie (Tyler Dietrich)
 * @author ceelman (Chris Elman)
 * @author jaeheunk (Jason(jaeheunk) Kim)
 * @author mjszymko (Michael Szymkowski)
 * @author shokoors (Shokoor Syed)
 * @date 2015-MARCH-7
 * The SaveGame class is responsible for saving the current state of the game in a text file.
 */
@SuppressWarnings("unused")
public class SaveString {
	/**
	 * @author tylerdie (Tyler Dietrich)
	 * @author ceelman (Chris Elman)
	 * @author jaeheunk (Jason(jaeheunk) Kim)
	 * @author mjszymko (Michael Szymkowski)
	 * @author shokoors (Shokoor Syed)
	 * @date 2015-MARCH-7
	 * Instance variable that holds reference to the Board class
	 */
	private Board_024 _b;
	/**
	 * @author tylerdie (Tyler Dietrich)
	 * @author ceelman (Chris Elman)
	 * @author jaeheunk (Jason(jaeheunk) Kim)
	 * @author mjszymko (Michael Szymkowski)
	 * @author shokoors (Shokoor Syed)
	 * @date 2015-MARCH-7
	 * Instance variable that holds reference to the BoardFrame class
	 */
	private BoardFrame_047 _bf;
	/**
	 * @author tylerdie (Tyler Dietrich)
	 * @author ceelman (Chris Elman)
	 * @author jaeheunk (Jason(jaeheunk) Kim)
	 * @author mjszymko (Michael Szymkowski)
	 * @author shokoors (Shokoor Syed)
	 * @date 2015-MARCH-7
	 * Instance variable that holds reference to the TileRack class
	 */
	private TileRack_024 _tr;
	/**
	 * @author tylerdie (Tyler Dietrich)
	 * @author ceelman (Chris Elman)
	 * @author jaeheunk (Jason(jaeheunk) Kim)
	 * @author mjszymko (Michael Szymkowski)
	 * @author shokoors (Shokoor Syed)
	 ** @date 2015-MARCH-7
	 * Instance variable that holds reference to the Scrabble class
	 */
	private Scrabble_024_047 _scrabble;
	/**
	 * @author tylerdie (Tyler Dietrich)
	 * @author ceelman (Chris Elman)
	 * @author jaeheunk (Jason(jaeheunk) Kim)
	 * @author mjszymko (Michael Szymkowski)
	 * @author shokoors (Shokoor Syed)
	 * @date 2015-MARCH-7
	 * Instance variable that holds reference to a specidif file to write to
	 */
	private String _fileToWriteTo;

	//public static void main(String[] args) throws IOException{
		//SaveGame t = new SaveGame();
		//t.writeNewFile();

	//}

	private String _bw;
	/**
	 * @author tylerdie (Tyler Dietrich)
	 * @author ceelman (Chris Elman)
	 * @author jaeheunk (Jason(jaeheunk) Kim)
	 * @author mjszymko (Michael Szymkowski)
	 * @author shokoors (Shokoor Syed)
	 * @date 2015-MARCH-7
	 * Constructor for the SaveGame class
	 * @param Reference to the Board class
	 * @param Reference to the BoardFrame class
	 * @param Reference to the Scrabble class
	 * @throws Throws IOException
	 */

	public SaveString(Board_024 b, BoardFrame_047 bf, Scrabble_024_047 s) throws IOException{
		_b = b;
		_bf = bf;

			_scrabble = s;
			/*JFrame jf = new JFrame();
			FileDialog chooser = new FileDialog(jf,"Save your file",FileDialog.SAVE);
			//FileDialog chooser = new FileDialog(j,"Save your file",FileDialog.LOAD);
			chooser.setDirectory("C:\\");chooser.setFile("*.txt");chooser.setVisible(true);
			String filename = chooser.getFile();
			String path = chooser.getDirectory();
			System.out.println(path);
			String filetoWrite = path + filename;
			_fileToWriteTo = filetoWrite;

			File file = new File(_fileToWriteTo);
			FileWriter fw = new FileWriter(file.getAbsoluteFile());
			*/
			//String bw = new String();

			String boardsize = "20 20";
			addToString(boardsize);
			addToString("\n");

			String content = "/part2/res/words.txt";
			addToString(content);
			addToString("\n");

			for(int i = 0; i <_scrabble.getNumofPlayers(); i = i + 1 ){
				Player_024_047 p = _scrabble.returnPlayer(i);

				addToString("[" + p.getName() + "," +p.getColor() + "," + p.getScore());
				addToString(",");
				addToString("[");
				for(int j = 0; j <12; j = j+1){
					addToString(Character.toString(p.getTileRack().getTile(j).getChar()));
				}
				addToString("]");
				addToString("]");
				if(i < _scrabble.getNumofPlayers()-1){
					addToString(";");
				}
			}

			addToString("\n");

			int turn = _scrabble.getGame().getCurrentTurn();
			addToString(Integer.toString(turn));
			addToString("\n");

			for(int i = 0; i < _scrabble.getInv().getSize(); i = i + 1 ){
				addToString("[" + _scrabble.getInv().getTile(i).getChar() + "]");
			}
			addToString("\n");

			for(int i = 0; i<20; i = i + 1){
				for(int j = 0; j<20; j = j +1){
					if(_scrabble.getBoard().getTile(i, j) == null){
						addToString("-");
					}
					else{
						_scrabble.getBoard().getTile(i, j).getChar();
						_scrabble.getBoard().getTile(i,j).getColor();
						addToString("[" + _scrabble.getBoard().getTile(i, j).getChar() +  ", " + _scrabble.getBoard().getTile(i, j).getColor() + "]");
					}

				}
			}
			//bw.close();
			System.out.println(_bw);

		}

	/**
	 * @author tylerdie (Tyler Dietrich)
	 * @author ceelman (Chris Elman)
	 * @author jaeheunk (Jason(jaeheunk) Kim)
	 * @author mjszymko (Michael Szymkowski)
	 * @author shokoors (Shokoor Syed)
	 ** @date 2015-MARCH-7
	 * Method that writes to a file
	 */
	public void writeNewFile() throws IOException{

	}

	public void addToString(String newString){
		_bw = _bw + newString;
	}

	public String returnGameInfo(){
		return _bw;
	}

}


text:
package vpp2009

import (
	"context"
	"net"
	"os"
	"strings"
	"time"

	govppapi "git.fd.io/govpp.git/api"
	"github.com/pkg/errors"

	vpp_dhcp "go.ligato.io/vpp-agent/v3/plugins/vpp/binapi/vpp2009/dhcp"
	vpp_ifs "go.ligato.io/vpp-agent/v3/plugins/vpp/binapi/vpp2009/interface"
	"go.ligato.io/vpp-agent/v3/plugins/vpp/binapi/vpp2009/interface_types"
	"go.ligato.io/vpp-agent/v3/plugins/vpp/ifplugin/vppcalls"
)

var (
	// EventDeliverTimeout defines maximum time to deliver event upstream.
	EventDeliverTimeout = time.Second
	// NotifChanBufferSize defines size of notification channel buffer.
	NotifChanBufferSize = 10
)

func (h *InterfaceVppHandler) WatchInterfaceEvents(ctx context.Context, eventsCh chan<- *vppcalls.InterfaceEvent) error {
	notifChan := make(chan govppapi.Message, NotifChanBufferSize)

	// subscribe to SwInterfaceEvent notifications
	sub, err := h.callsChannel.SubscribeNotification(notifChan, &vpp_ifs.SwInterfaceEvent{})
	if err != nil {
		return errors.Errorf("subscribing to VPP notification (sw_interface_event) failed: %v", err)
	}
	unsub := func() {
		if err := sub.Unsubscribe(); err != nil {
			h.log.Warnf("unsubscribing VPP notification (sw_interface_event) failed: %v", err)
		}
	}

	go func() {
		h.log.Debugf("start watching interface events")
		defer h.log.Debugf("done watching interface events (%v)", ctx.Err())

		for {
			select {
			case e, open := <-notifChan:
				if !open {
					h.log.Debugf("interface events channel was closed")
					unsub()
					return
				}

				ifEvent, ok := e.(*vpp_ifs.SwInterfaceEvent)
				if !ok {
					h.log.Debugf("unexpected notification type: %#v", ifEvent)
					continue
				}

				// try to send event
				select {
				case eventsCh <- toInterfaceEvent(ifEvent):
					// sent ok
				case <-ctx.Done():
					unsub()
					return
				default:
					// channel full send event in goroutine for later processing
					go func() {
						select {
						case eventsCh <- toInterfaceEvent(ifEvent):
							// sent ok
						case <-time.After(EventDeliverTimeout):
							h.log.Warnf("unable to deliver interface event, dropping it: %+v", ifEvent)
						}
					}()
				}
			case <-ctx.Done():
				unsub()
				return
			}
		}
	}()

	// enable interface events from VPP
	if _, err := h.interfaces.WantInterfaceEvents(ctx, &vpp_ifs.WantInterfaceEvents{
		PID:           uint32(os.Getpid()),
		EnableDisable: 1,
	}); err != nil {
		if errors.Is(err, govppapi.VPPApiError(govppapi.INVALID_REGISTRATION)) {
			h.log.Warnf("already subscribed to interface events: %v", err)
			return nil
		}
		return errors.Errorf("failed to watch interface events: %v", err)
	}

	return nil
}

func (h *InterfaceVppHandler) WatchDHCPLeases(ctx context.Context, leasesCh chan<- *vppcalls.Lease) error {
	notifChan := make(chan govppapi.Message, NotifChanBufferSize)

	// subscribe for receiving DHCPComplEvent notifications
	sub, err := h.callsChannel.SubscribeNotification(notifChan, &vpp_dhcp.DHCPComplEvent{})
	if err != nil {
		return errors.Errorf("subscribing to VPP notification (dhcp_compl_event) failed: %v", err)
	}
	unsub := func() {
		if err := sub.Unsubscribe(); err != nil {
			h.log.Warnf("unsubscribing VPP notification (dhcp_compl_event) failed: %v", err)
		}
	}

	go func() {
		h.log.Debugf("start watching DHCP leases")
		defer h.log.Debugf("done watching DHCP lease (%v)", ctx.Err())

		for {
			select {
			case e, open := <-notifChan:
				if !open {
					h.log.Debugf("interface notification channel was closed")
					unsub()
					return
				}

				dhcpEvent, ok := e.(*vpp_dhcp.DHCPComplEvent)
				if !ok {
					h.log.Debugf("unexpected notification type: %#v", dhcpEvent)
					continue
				}

				// try to send event
				select {
				case leasesCh <- toDHCPLease(dhcpEvent):
					// sent ok
				case <-ctx.Done():
					unsub()
					return
				default:
					// channel full send event in goroutine for later processing
					go func() {
						select {
						case leasesCh <- toDHCPLease(dhcpEvent):
							// sent ok
						case <-time.After(EventDeliverTimeout):
							h.log.Warnf("unable to deliver DHCP lease event, dropping it: %+v", dhcpEvent)
						}
					}()
				}
			case <-ctx.Done():
				unsub()
				return
			}
		}
	}()

	return nil
}

func toInterfaceEvent(ifEvent *vpp_ifs.SwInterfaceEvent) *vppcalls.InterfaceEvent {
	event := &vppcalls.InterfaceEvent{
		SwIfIndex: uint32(ifEvent.SwIfIndex),
		Deleted:   ifEvent.Deleted,
	}
	if ifEvent.Flags&interface_types.IF_STATUS_API_FLAG_ADMIN_UP == interface_types.IF_STATUS_API_FLAG_ADMIN_UP {
		event.AdminState = 1
	}
	if ifEvent.Flags&interface_types.IF_STATUS_API_FLAG_LINK_UP == interface_types.IF_STATUS_API_FLAG_LINK_UP {
		event.LinkState = 1
	}
	return event
}

func toDHCPLease(dhcpEvent *vpp_dhcp.DHCPComplEvent) *vppcalls.Lease {
	lease := dhcpEvent.Lease
	return &vppcalls.Lease{
		SwIfIndex:     uint32(lease.SwIfIndex),
		State:         uint8(lease.State),
		Hostname:      strings.TrimRight(lease.Hostname, "\x00"),
		IsIPv6:        lease.IsIPv6,
		HostAddress:   dhcpAddressToString(lease.HostAddress, uint32(lease.MaskWidth), lease.IsIPv6),
		RouterAddress: dhcpAddressToString(lease.RouterAddress, uint32(lease.MaskWidth), lease.IsIPv6),
		HostMac:       net.HardwareAddr(lease.HostMac[:]).String(),
	}
}


text:
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.plugins.newui;

import com.intellij.icons.AllIcons;
import com.intellij.ide.BrowserUtil;
import com.intellij.ide.IdeBundle;
import com.intellij.ide.plugins.IdeaPluginDescriptor;
import com.intellij.ide.plugins.PluginManagerConfigurable;
import com.intellij.openapi.application.IdeUrlTrackingParametersProvider;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.util.NlsSafe;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.ui.LicensingFacade;
import com.intellij.ui.components.ActionLink;
import com.intellij.ui.components.panels.NonOpaquePanel;
import com.intellij.util.ArrayUtil;
import com.intellij.util.text.DateFormatUtil;
import com.intellij.util.ui.EmptyIcon;
import com.intellij.util.ui.JBUI;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.*;
import java.util.Date;
import java.util.function.Supplier;

/**
 * @author Alexander Lobas
 */
public class LicensePanel extends NonOpaquePanel {
  private final JLabel mySubMessage = new JLabel();
  private final JPanel myPanel = new NonOpaquePanel(new HorizontalLayout(JBUI.scale(5)));
  private final JLabel myMessage = new JLabel();
  private final ActionLink myLink = new ActionLink();

  public LicensePanel(boolean tiny) {
    setLayout(new BorderLayout());

    add(tiny ? PluginManagerConfigurable.setTinyFont(mySubMessage) : mySubMessage, BorderLayout.NORTH);
    add(myPanel);

    myPanel.add(tiny ? PluginManagerConfigurable.setTinyFont(myMessage) : myMessage);
    myPanel.add(tiny ? PluginManagerConfigurable.setTinyFont(myLink) : myLink);

    hideElements();
  }

  public boolean isNotification() {
    return myMessage.getIcon() != null || myMessage.isForegroundSet();
  }

  @Nullable
  @NlsSafe
  public String getMessage() {
    String text = myMessage.getText();
    if (mySubMessage.isVisible()) {
      return mySubMessage.getText() + "\n" + text;
    }
    if (StringUtil.endsWithChar(text, '.')) {
      return text.substring(0, text.length() - 1);
    }
    return text;
  }

  public void setText(@NotNull @Nls String text, boolean warning, boolean errorColor) {
    int separator = text.indexOf('\n');

    if (separator == -1) {
      myMessage.setText(text);
      myMessage.setIcon(warning ? AllIcons.General.Warning : null);
    }
    else {
      mySubMessage.setText(text.substring(0, separator));
      mySubMessage.setIcon(warning ? AllIcons.General.Warning : null);
      mySubMessage.setVisible(true);

      myMessage.setText(text.substring(separator + 1));
      myMessage.setIcon(warning ? EmptyIcon.ICON_16 : null);
    }

    myMessage.setForeground(errorColor ? DialogWrapper.ERROR_FOREGROUND_COLOR : null);
    myMessage.setVisible(true);

    myPanel.setVisible(true);
  }

  public void setTextFromStamp(@NotNull String stamp, @Nullable Date expirationDate) {
    long days = expirationDate == null ? 0 : DateFormatUtil.getDifferenceInDays(new Date(), expirationDate);

    if (stamp.startsWith("eval:")) {
      if (days <= 0) {
        setText(IdeBundle.message("trial.expired"), false, true);
      }
      else {
        setText(IdeBundle.message("plugins.configurable.trial.expires.in.0.days", days), days < 11, false);
      }
    }
    else if (expirationDate == null) {
      setText(IdeBundle.message("plugins.configurable.license.is.active"), false, false);
    }
    else if (days > 30) {
      setText(IdeBundle
                .message("plugins.configurable.license.is.active.until.0", PluginManagerConfigurable.DATE_FORMAT.format(expirationDate)), false, false);
    }
    else if (days <= 0) {
      setText(IdeBundle.message("plugins.configurable.license.expired"), false, true);
    }
    else {
      setText(IdeBundle.message("plugins.configurable.license.expires.in.0.days", days), days < 11, false);
    }
  }

  public void setLink(@NotNull @Nls String text, @NotNull Runnable action, boolean external) {
    myLink.setText(text);
    if (external) {
      myLink.setExternalLinkIcon();
    }
    else {
      myLink.setIcon(null);
    }
    myLink.addActionListener(e -> action.run());
    myLink.setVisible(true);

    myPanel.setVisible(true);
  }

  public void updateLink(@NotNull @Nls String text, boolean async) {
    myLink.setText(text);
    if (async) {
      myPanel.doLayout();
    }
  }

  public void hideWithChildren() {
    hideElements();
    setVisible(false);
  }

  private void hideElements() {
    mySubMessage.setVisible(false);
    myMessage.setVisible(false);
    myLink.setVisible(false);
    myPanel.setVisible(false);
  }

  public void showBuyPlugin(@NotNull Supplier<? extends IdeaPluginDescriptor> getPlugin) {
    IdeaPluginDescriptor plugin = getPlugin.get();

    setLink(IdeBundle.message("plugins.configurable.buy.the.plugin"), () ->
      BrowserUtil.browse(IdeUrlTrackingParametersProvider.getInstance().augmentUrl("https://plugins.jetbrains.com/purchase-link/" + plugin.getProductCode())), true);

    PluginPriceService.getPrice(plugin, price -> updateLink(IdeBundle.message("plugins.configurable.buy.the.plugin.from.0", price), false), price -> {
      if (plugin == getPlugin.get()) {
        updateLink(IdeBundle.message("plugins.configurable.buy.the.plugin.from.0", price), true);
      }
    });
  }

  public static boolean isEA2Product(@Nullable String productCodeOrPluginId) {
    return productCodeOrPluginId != null &&
      LicensingFacade.getInstance() != null &&
      ArrayUtil.contains(productCodeOrPluginId, "DPN", "DC", "DPA", "PDB", "PWS", "PGO", "PPS", "PPC", "PRB", "PSW", "Pythonid");
  }
}


text:
"""Script for retracting pending retractions that are more than 48 hours old."""

import datetime
import logging

from modularodm import Q

from framework.auth import Auth
from framework.celery_tasks import app as celery_app
from framework.transactions.context import TokuTransaction

from website.app import init_app
from website import models, settings
from website.project.model import NodeLog

from scripts import utils as scripts_utils

logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)

def main(dry_run=True):
    pending_retractions = models.Retraction.find(Q('state', 'eq', models.Retraction.UNAPPROVED))
    for retraction in pending_retractions:
        if should_be_retracted(retraction):
            if dry_run:
                logger.warn('Dry run mode')
            try:
                parent_registration = models.Node.find_one(Q('retraction', 'eq', retraction))
            except Exception as err:
                logger.error('Could not find registration associated with retraction {}'.format(retraction))
                logger.error('Skipping...'.format(retraction))
                continue

            logger.warn(
                'Retraction {0} approved. Retracting registration {1}'
                .format(retraction._id, parent_registration._id)
            )
            if not dry_run:
                with TokuTransaction():
                    retraction.state = models.Retraction.APPROVED
                    try:
                        parent_registration.registered_from.add_log(
                            action=NodeLog.RETRACTION_APPROVED,
                            params={
                                'node': parent_registration._id,
                                'retraction_id': parent_registration.retraction._id,
                            },
                            auth=Auth(parent_registration.retraction.initiated_by),
                        )
                        retraction.save()
                        parent_registration.update_search()
                        for node in parent_registration.get_descendants_recursive():
                            node.update_search()
                    except Exception as err:
                        logger.error(
                            'Unexpected error raised when retracting '
                            'registration {}. Continuing...'.format(parent_registration))
                        logger.exception(err)

def should_be_retracted(retraction):
    """Returns true if retraction was initiated more than 48 hours prior"""
    return (datetime.datetime.utcnow() - retraction.initiation_date) >= settings.RETRACTION_PENDING_TIME

@celery_app.task(name='scripts.retract_registrations')
def run_main(dry_run=True):
    init_app(routes=False)
    if not dry_run:
        scripts_utils.add_file_logger(logger, __file__)
    main(dry_run=dry_run)


text:
describe TfpMetaprogramming::MetaClass::Macros do
  let(:myMacro) { TfpMetaprogramming::MetaClass::Macros }
  let(:myWolf) { TfpMetaprogramming::MetaClass::Macros::LoneWolf.new }
  let(:loneClass) { TfpMetaprogramming::MetaClass::Macros::LoneWolf }
  describe 'force_wolf_to_contemplate_solipsism' do
    context 'before called' do
      describe 'LoneWolf' do
        it 'does not respond to :contemplate_solipsism' do
          expect(loneClass).not_to respond_to(:contemplate_solipsism)
        end
      end
    end
    context 'after called' do
      before(:each) do
        myMacro.force_wolf_to_contemplate_solipsism
      end
      describe 'LoneWolf' do
        it 'responds to singleton method #force_wolf_to_contemplate_solipsism' do
          expect(loneClass).to respond_to(:contemplate_solipsism)
        end
      end
    end

  end
end


text:
package com.android.python;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Vector;

import org.apache.log4j.Logger;
import org.eclipse.swt.widgets.Display;
import org.openqa.selenium.WebElement;
import org.python.core.ArgParser;
import org.python.core.ClassDictInit;
import org.python.core.PyFunction;
import org.python.core.PyInteger;
import org.python.core.PyObject;
import org.python.core.PyString;
import org.python.core.PyTuple;
import org.python.util.PythonInterpreter;

import com.android.log.Log;
import com.android.robot.AndroidRobot;
import com.android.selendroid.LaunchSelendroid;
import com.android.selendroid.UiSelendroidClient;
import com.android.ui.data.Element;
import com.android.ui.data.UIElement;
import com.android.ui.data.UIPool;
import com.android.uiautomator.UiAutomatorClient;
import com.android.util.AdbUtil;
import com.android.util.ApkInfo;
import com.android.util.ApkUtil;
import com.android.util.DisplayUtil;
import com.android.util.ImageUtil;
import com.android.util.PropertiesUtil;
import com.android.util.StringUtil;
import com.google.common.base.Preconditions;

public class AndroidDriver extends PyObject implements ClassDictInit{
	private UiAutomatorClient  uiAutomatorClient = null;
	private UiSelendroidClient uiSelendroidClient = null;
	private static LaunchSelendroid launcher = null;
	private boolean isPass = true;
	private String taskName = "";
	private String sn = "";
	private String scriptName = "";
	private String scriptPath = "";
	private String act_name = "";
	private String apk_version = "";
	private String pkg_name = "";
	//script support s_width*s_height
	private int s_width = 1;
	private int s_height = 1;

	//device width*height
	private int d_width = 1;
	private int d_height = 1;
	private HashMap<String, UiWatcher> mWatchers = new HashMap<String, UiWatcher>();
	private boolean mInWatcherContext = false;
	private String window = "NATIVE_APP";//WEBVIEW_0
	private String apkPath = "";
	private int picCounter = 0;
	private String projectPath = "";

	public static void classDictInit(PyObject dict){
		JythonUtils.convertDocAnnotationsForClass(AndroidDriver.class, dict);
	}

	public AndroidDriver(String apkPath, String sn, boolean isSelendroid, String project){
		this.sn = sn;
		this.picCounter = 0;
		this.apkPath = apkPath;
		this.projectPath = project;
		System.out.println("project:" + this.projectPath);
		this.uiAutomatorClient  = new UiAutomatorClient(this.sn);
		if(isSelendroid)
			this.uiSelendroidClient = new UiSelendroidClient(apkPath, this.sn, 4444);
	}

	public void setTaskName(String taskName){
		this.taskName = taskName;
	}

	public void setScriptName(String scriptName){
		this.scriptName = scriptName;
	}

	public void setScriptPath(String scriptPath){
		this.scriptPath = scriptPath;
	}

	public boolean isPass() {
		return isPass;
	}

	public void setPass(boolean isPass) {
		this.isPass = isPass;
	}

	public String getSN(){
		return this.sn;
	}

	public boolean connect() throws InterruptedException{
		boolean isLaunched = false;
		if(this.uiAutomatorClient != null)
			isLaunched = this.uiAutomatorClient.connect();
		Logger.getLogger(this.getClass()).info("[" + sn + "] 连接UiAutomatorHarbout" + isLaunched);
		return isLaunched;
	}

	public static synchronized boolean launchSelendroidStandalone(String app, int port) throws Exception {
		if(null == launcher) {
			launcher = new LaunchSelendroid(app, port);
			Thread thread = new Thread(launcher);
			thread.start();
			thread.join(30000);
			launcher.getMessage();
		}

		return true;
	}

	public static boolean stopSelendroidStandalone() {
		if(null != launcher)
			launcher.stopSelendroid();
		return true;
	}

	public void runBeforeInstall(){
		mInWatcherContext = true;
		executePython(this.projectPath + "/Library/Install.py", "watcher");
		mInWatcherContext = false;
	}

	public boolean setup(final String serial,boolean isSelendroid) throws Exception {
		if(!this.apkPath.trim().equals("")) {
			ApkInfo apkInfo = new ApkUtil().getApkInfo(this.apkPath);
			this.act_name = apkInfo.getActivityName();
			this.pkg_name = apkInfo.getPackageName();
			this.apk_version = apkInfo.getVersionName();

			String isForceInstall = PropertiesUtil.getValue("./system.properties", "isForceInstall");

			if(!isForceInstall.trim().toLowerCase().equals("true")) {
				return true;
			}

			Thread preinstall = new Thread(new Runnable(){
				@Override
				public void run() {
					runBeforeInstall();
				}});
			preinstall.start();

			boolean bRet = false;
			if(isSelendroid)
				bRet = this.uiSelendroidClient.
					setup(serial, this.pkg_name, this.act_name, this.apk_version);
			else
				bRet = install();

			if(null != preinstall)
				preinstall.stop();
			return bRet;
		}
		return true;
	}

	public boolean unInstall(String pkg) throws Exception{
		String uninstall_cmd = "adb -s " + sn + " uninstall " + pkg;
		String result = new AdbUtil().send(uninstall_cmd, 60000);
		Logger.getLogger(AndroidDriver.class).info("[" + sn +"] uninstall result:" + pkg + " " + result);
		return result.trim().endsWith("Success");
	}

	public boolean install() throws Exception{
		boolean ret = true;
		ApkInfo apkInfo = new ApkUtil().getApkInfo(this.apkPath);
		String getAppVersionCode = "cmd /c adb -s " + sn + " shell dumpsys package " + apkInfo.getPackageName() + " | findstr versionCode";
		String d_versionCode = AdbUtil.send(getAppVersionCode, 5000);

		String getAppVersionName = "cmd /c adb -s " + sn + " shell dumpsys package " + apkInfo.getPackageName() + " | findstr versionName";
		String d_versionName = AdbUtil.send(getAppVersionName, 5000);

		unInstall(apkInfo.getPackageName());

//		System.out.println("d_versionCode:" + d_versionCode + " getVersion:" + apkInfo.getVersionCode());
//
//		System.out.println("d_versionName:" + d_versionName + " getVersionName:" + apkInfo.getVersionName());

//		if(d_versionName.trim().endsWith(apkInfo.getVersionName())) {
//			System.out.println("安装[" + this.apkPath + "] ret=App已经安装");
//			System.out.println("安装[" + this.apkPath + "] ret=App正在卸载");
//			return true;
//		}

		String adbShell = "adb -s " + sn + " install -r " + this.apkPath;
		String result = AdbUtil.send(adbShell, 60000);
		//ret = result.trim().endsWith("Success");
		ret = result.trim().contains("Success");
		Logger.getLogger(AndroidDriver.class).info("[" + sn +"] 安装[" + this.apkPath + "] ret=" + ret);
//		Log.getLoger(sn).logInfo.addRunLog("安装[" + this.apkPath + "]成功");
//		this.setInfo(DisplayUtil.Show.Info, "安装[" + filePath + "]成功", sn);
		return ret;
	}

	public boolean disconnect() throws Exception {
		boolean bRet = true;
		if(this.uiAutomatorClient != null){
			bRet = this.uiAutomatorClient.disconnect();
			this.uiAutomatorClient = null;
		}

		if(this.uiSelendroidClient != null) {
			this.uiSelendroidClient.quit();
			this.uiSelendroidClient = null;
		}

		return bRet;
	}

	public void refreshProgressData(){
		Element element = new Element();
		element.setElement(UIElement.TASK_PROGRESS_BAR);
		element.setSN(sn);
		element.setTaskName(taskName);
		element.setScriptName(scriptName);
		UIPool.offer(element);
	}

	@MonkeyRunnerExported(doc="getSerialNumber", args={"void"}, argDocs={""}, returns = "Serial ")
	public String getSerialNumber(PyObject[] args, String[] kws) throws UnsupportedEncodingException {
		return this.sn;
	}

	@MonkeyRunnerExported(doc="switchToWindow", args={"void"}, argDocs={""}, returns = "Serial ")
	public void switchToWindow(PyObject[] args, String[] kws) throws UnsupportedEncodingException {
		ArgParser ap = JythonUtils.createArgParser(args, kws);
		Preconditions.checkNotNull(ap);

		window = ap.getString(0);
		this.uiSelendroidClient.switchTo(window);
	}

	@MonkeyRunnerExported(doc="getPageSource", args={"void"}, argDocs={""}, returns = "Serial ")
	public String getPageSource(PyObject[] args, String[] kws) {
		this.refreshProgressData();
		this.setInfo(DisplayUtil.Show.Info, "getPageSource", sn);
		Logger.getLogger(AndroidDriver.class).info(this.uiSelendroidClient.getPageSource());
		return this.uiSelendroidClient.getPageSource();
	}

	@MonkeyRunnerExported(doc="register watcher", args={}, argDocs={}, returns = "void")
	public void registerWatcher(PyObject[] args, String[] kws){
		ArgParser ap = JythonUtils.createArgParser(args, kws);
		Preconditions.checkNotNull(ap);
		String name = "";
		String path = "";
		String func = "";

		name = ap.getString(0);
		path = ap.getString(1);
		func = ap.getString(2);

		this.refreshProgressData();
		Logger.getLogger(AndroidDriver.class).info("[" +sn + "]registerWatcher[" + name + "]");
		Log.getLoger(sn).logInfo.addRunLog("registerWatcher[" + name + "]");
		this.setInfo(DisplayUtil.Show.Info, "registerWatcher[" + name + "]", sn);

		UiWatcher watcher = new UiWatcher(name,path,func);
		mWatchers.put(name, watcher);
	}

	@MonkeyRunnerExported(doc="remove watcher", args={}, argDocs={}, returns = "void")
	public void removeWatcher(PyObject[] args, String[] kws){
		ArgParser ap = JythonUtils.createArgParser(args, kws);
		Preconditions.checkNotNull(ap);
		String name = ap.getString(0);
		this.refreshProgressData();
		Logger.getLogger(AndroidDriver.class).info("[" +sn + "removeWatcher[" + name + "]");
		Log.getLoger(sn).logInfo.addRunLog("removeWatcher[" + name + "]");
		this.setInfo(DisplayUtil.Show.Info, "removeWatcher[" + name + "]", sn);

		if(mWatchers.containsKey(name))
			mWatchers.remove(name);
	}

	@MonkeyRunnerExported(doc="trigger watcher", args={}, argDocs={}, returns = "void")
	public void triggerWatchers(PyObject[] args, String[] kws){
		this.refreshProgressData();
		Logger.getLogger(AndroidDriver.class).info("[" +sn + "triggerWatchers");
		Log.getLoger(sn).logInfo.addRunLog("triggerWatchers");
		this.setInfo(DisplayUtil.Show.Info, "triggerWatchers", sn);
		//runWatchers();
		runWatcher();
	}

	private PyObject executePython(String filePath){
		PythonInterpreter interpreter = new PythonInterpreter();
		Vector<AndroidDriver> drivers = new Vector();
		drivers.add(this);
		interpreter.set("device", drivers);
		interpreter.execfile(filePath);
		PyObject ret = interpreter.eval("True");
		return ret;
	}

	private PyObject executePython(String filePath, String function){
		PythonInterpreter interpreter = new PythonInterpreter();
		Vector<AndroidDriver> drivers = new Vector();
		drivers.add(this);
		interpreter.set("device", drivers);
		interpreter.execfile(filePath);
		System.out.println(filePath + "  " + function);
		PyFunction pyfunction = interpreter.get(function, PyFunction.class);
		PyObject pyobj = pyfunction.__call__();
		return pyobj;
	}

	private PyObject executePython(String filePath, String function, PyObject params){
		PythonInterpreter interpreter = new PythonInterpreter();
		Vector<AndroidDriver> drivers = new Vector();
		drivers.add(this);
		interpreter.set("device", drivers);
		interpreter.execfile(filePath);
		PyFunction pyfunction = interpreter.get(function, PyFunction.class);
		PyObject pyobj = pyfunction.__call__(params.__getitem__(0));
		return pyobj;
	}

	public void runWatchers(){
		if(true == mInWatcherContext)
			return;

		Iterator iterator = mWatchers.keySet().iterator();
		while(iterator.hasNext()) {
			mInWatcherContext = true;
			UiWatcher watcher = mWatchers.get(iterator.next());
			executePython(watcher.getWatcherPath(), watcher.getWatcherFunc());
		}

		mInWatcherContext = false;
	}

	public void runWatcher(){
		System.out.println("run watcher");
		mInWatcherContext = true;
		executePython(this.projectPath + "/Library/Watcher.py", "watcher");
		mInWatcherContext = false;
	}

	@MonkeyRunnerExported(doc="reboot device", args={}, argDocs={}, returns = "boolean")
	public boolean reboot(PyObject[] args, String[] kws) throws Exception{
		ArgParser ap = JythonUtils.createArgParser(args, kws);
		Preconditions.checkNotNull(ap);
		boolean ret = true;
		System.out.println("reboot");

		this.refreshProgressData();

		Thread.sleep(5000);
		return ret;
	}

	@MonkeyRunnerExported(doc="exec command", args={}, argDocs={}, returns = "boolean")
	public boolean exec(PyObject[] args, String[] kws) throws Exception{
		boolean ret = true;
		ArgParser ap = JythonUtils.createArgParser(args, kws);
		Preconditions.checkNotNull(ap);
		String cmd = ap.getString(0);

		PythonInterpreter interpreter = new PythonInterpreter();
		Vector<AndroidDriver> drivers = new Vector();
		drivers.add(this);
		interpreter.set("device", drivers);
		interpreter.exec(cmd);
		return ret;
	}

	@MonkeyRunnerExported(doc="reboot device", args={}, argDocs={}, returns = "boolean")
	public boolean sleep(PyObject[] args, String[] kws) throws Exception{
		boolean ret = true;
		try{
			ArgParser ap = JythonUtils.createArgParser(args, kws);
			Preconditions.checkNotNull(ap);

			this.refreshProgressData();
			int milli = ap.getInt(0);
			this.setInfo(DisplayUtil.Show.Info, "休眠"+milli+"毫秒", sn);

			Thread.sleep(milli);
		}catch(Exception ex){

		}
		return ret;
	}

	@MonkeyRunnerExported(doc="install app", args={"app path"}, argDocs={}, returns = "boolean")
	public boolean install(PyObject[] args, String[] kws) throws Exception{
		boolean ret = true;
		ArgParser ap = JythonUtils.createArgParser(args, kws);
		Preconditions.checkNotNull(ap);
		String filePath = new String(ap.getString(0).getBytes("ISO-8859-1"), "UTF-8");

		this.refreshProgressData();

		ApkInfo apkInfo = new ApkUtil().getApkInfo(filePath);
		String getAppVersionCode = "cmd /c adb -s " + sn + " shell dumpsys package " + apkInfo.getPackageName() + " | findstr versionCode";
		String d_versionCode = new AdbUtil().send(getAppVersionCode, 5000);

		String getAppVersionName = "cmd /c adb -s " + sn + " shell dumpsys package " + apkInfo.getPackageName() + " | findstr versionName";
		String d_versionName = new AdbUtil().send(getAppVersionName, 5000);

		System.out.println("d_versionCode:" + d_versionCode + " " + d_versionName);

		if(d_versionCode.trim().endsWith(apkInfo.getVersionCode())
				&& d_versionName.trim().endsWith(apkInfo.getVersionName())) {
			Log.getLoger(sn).logInfo.addRunLog("安装[" + filePath + "] ret=App已经安装");
			this.setInfo(DisplayUtil.Show.Info, "安装[" + filePath + "] ret=App已经安装", sn);
			return true;
		}

		String adbShell = "adb -s " + sn + " install -r " + filePath;
		String result = new AdbUtil().send(adbShell, 60000);
		ret = result.trim().endsWith("Success");
		Log.getLoger(sn).logInfo.addRunLog("安装[" + filePath + "]成功");
		this.setInfo(DisplayUtil.Show.Info, "安装[" + filePath + "]成功", sn);
		return ret;
	}

	@MonkeyRunnerExported(doc="start app", args={"app path"}, argDocs={}, returns = "boolean")
	public boolean startActivity(PyObject[] args, String[] kws) throws Exception{
		boolean ret = true;
		ArgParser ap = JythonUtils.createArgParser(args, kws);
		//Preconditions.checkNotNull(ap);
		String activityName = new String(ap.getString(0).getBytes("ISO-8859-1"), "UTF-8");

		this.refreshProgressData();

		String shell = "adb -s " + sn + " shell am start " + activityName;
		String response = AdbUtil.send(shell, 30000);

		Thread.sleep(3000);

		Logger.getLogger(this.getClass()).info("[" + sn + "]启动" + activityName + " " + response);
		Log.getLoger(sn).logInfo.addRunLog("启动[" + activityName + "]成功");
		this.setInfo(DisplayUtil.Show.Info, "启动[" + activityName + "]成功", sn);
		return ret;
	}

	@MonkeyRunnerExported(doc="start app", args={"app path"}, argDocs={}, returns = "String")
	public String getActivityName(PyObject[] args, String[] kws) throws Exception{
		ArgParser ap = JythonUtils.createArgParser(args, kws);
		Logger.getLogger(AndroidDriver.class).info("[" + sn + "]"+ this.pkg_name + "/" +this.act_name);
		return this.pkg_name + "/" +this.act_name;
	}

	@MonkeyRunnerExported(doc="start URL", args={"URL"}, argDocs={"URL link for App"}, returns = "boolean")
	public boolean startURL(PyObject[] args, String[] kws) throws Exception{
		boolean ret = true;
		ArgParser ap = JythonUtils.createArgParser(args, kws);
		Preconditions.checkNotNull(ap);
		String url = new String(ap.getString(0).getBytes("ISO-8859-1"), "UTF-8");

		this.refreshProgressData();
		String shell = "adb -s " + sn + " shell \"am start -W -a 'android.intent.action.VIEW' -d '" + url + "'\"";

		String result = new AdbUtil().send(shell, 30000);
		Thread.sleep(5000);
		Logger.getLogger(AndroidDriver.class).info("[" + sn + "]" + "启动[" + url + "]成功");
		Log.getLoger(sn).logInfo.addRunLog("启动[" + url + "]成功");
		this.setInfo(DisplayUtil.Show.Info, "启动[" + url + "]成功", sn);
		return ret;
	}

	@MonkeyRunnerExported(doc="set script supports screen size", args={"x", "y"}, argDocs={"x coordinate in pixels", "y coordinate in pixels"}, returns = "no")
	public void script(PyObject[] args, String[] kws) throws Exception{
		ArgParser ap = JythonUtils.createArgParser(args, kws);
		Preconditions.checkNotNull(ap);
		this.s_width = ap.getInt(0);
		this.s_height = ap.getInt(1);

		this.d_width = this.uiAutomatorClient.getDisplayWidth();
		this.d_height = this.uiAutomatorClient.getDisplayHeight();

		Log.getLoger(sn).logInfo.addRunLog("设置脚本分辨率" + this.s_width + "*" + this.s_height);
		this.setInfo(DisplayUtil.Show.Info, "设置脚本分辨率" + this.s_width + "*" + this.s_height, sn);
	}

	@MonkeyRunnerExported(doc="click id", args={"x", "y"}, argDocs={"x coordinate in pixels", "y coordinate in pixels"}, returns = "boolean")
	public boolean clickById(PyObject[] args, String[] kws) throws Exception {
		ArgParser ap = JythonUtils.createArgParser(args, kws);
		Preconditions.checkNotNull(ap);
		String id = ap.getString(0);
		int instance = ap.getInt(1);

		boolean bRet = this.uiAutomatorClient.clickById(id, instance);
		Logger.getLogger(AndroidDriver.class).info("[" + sn + "]" + "clickById[" + id + "," + instance + "] ret=" + bRet);
		Log.getLoger(sn).logInfo.addRunLog("clickById[" + id + "," + instance + "] ret=" + bRet);
		this.setInfo(DisplayUtil.Show.Info, "clickById[" + id + "," + instance + "] ret=" + bRet, sn);
		return bRet;
	}

	@MonkeyRunnerExported(doc="click class", args={"x", "y"}, argDocs={"x coordinate in pixels", "y coordinate in pixels"}, returns = "boolean")
	public boolean clickByClass(PyObject[] args, String[] kws) throws Exception {
		ArgParser ap = JythonUtils.createArgParser(args, kws);
		Preconditions.checkNotNull(ap);
		String object = ap.getString(0);
		int instance = ap.getInt(1);
		boolean bRet = this.uiAutomatorClient.clickByClass(object, instance);

		Logger.getLogger(AndroidDriver.class).info("[" + sn + "]" + "clickByClass[" + object + "," + instance + "] ret=" + bRet);
		Log.getLoger(sn).logInfo.addRunLog("clickByClass[" + object + "," + instance + "] ret=" + bRet);
		this.setInfo(DisplayUtil.Show.Info, "clickByClass[" + object + "," + instance + "] ret=" + bRet, sn);

		return bRet;
	}

	@MonkeyRunnerExported(doc="click screen", args={"x", "y"}, argDocs={"x coordinate in pixels", "y coordinate in pixels"}, returns = "boolean")
	public boolean click(PyObject[] args, String[] kws) throws Exception {
		ArgParser ap = JythonUtils.createArgParser(args, kws);
		Preconditions.checkNotNull(ap);
		int x = 0;
		int y = 0;
		String text = "";
		int instance = 0;

		PyObject  obj = ap.getPyObject(0); //get first
		if(obj instanceof PyString){
			text = new String(obj.asString().getBytes("ISO-8859-1"), "UTF-8");
			if(args.length == 2)
				instance = ap.getInt(1);
		}else {
			x = ap.getInt(0)*this.d_width/this.s_width;
			y = ap.getInt(1)*this.d_height/this.s_height;
		}

		boolean ret = false;
		this.refreshProgressData();
		if(!text.equals("")){
			text = new String(ap.getString(0).getBytes("ISO-8859-1"), "UTF-8");

			if(this.window.equals("NATIVE_APP"))
				ret = this.uiAutomatorClient.click(text,instance);
			else if(this.window.equals("WEBVIEW_0")) {
				this.uiSelendroidClient.findElement("//input[@value='" + text+"']").click();
				ret = true;
			}
			if(null != Log.getLoger(sn))
				Log.getLoger(sn).logInfo.addRunLog("click[" + text + "] 返回="+ret);
			this.setInfo(DisplayUtil.Show.Info, "click[" + text + "] 返回="+ret, sn);
			int count = 2;
			while(false == ret && (mWatchers.size() > 0)) {
				System.out.println("run watchers");
				runWatcher();
				ret = this.uiAutomatorClient.click(text,instance);
				if(null != Log.getLoger(sn))
					Log.getLoger(sn).logInfo.addRunLog("click[" + text + "] 返回="+ret + " Count="+count);
				this.setInfo(DisplayUtil.Show.Info, "click[" + text + "] 返回="+ret + " Count="+count, sn);
				if(count-- < 0)
					break;
			}

			if(ret == false && !mInWatcherContext)
				throw new Exception(Errors.TOUCH_TEXT_FAIL);
			else
				return ret;
		}else{
			ret = this.uiAutomatorClient.click(x, y);
			if(null != Log.getLoger(sn))
				Log.getLoger(sn).logInfo.addRunLog("click[" + x +"," + y + "] 返回="+ret);
			this.setInfo(DisplayUtil.Show.Info, "click[" + x +"," + y + "] 返回=" + ret, sn);

			return ret;
		}
	}

	@MonkeyRunnerExported(doc="click screen", args={"x", "y"}, argDocs={"x coordinate in pixels", "y coordinate in pixels"}, returns = "boolean")
	public boolean longClick(PyObject[] args, String[] kws) throws Exception {
		ArgParser ap = JythonUtils.createArgParser(args, kws);
		Preconditions.checkNotNull(ap);
		int x = 0;
		int y = 0;
		String text = "";

		boolean ret = false;
		this.refreshProgressData();
		if(args.length == 1){
			text = new String(ap.getString(0).getBytes("ISO-8859-1"), "UTF-8");
			ret = this.uiAutomatorClient.longClick(text);

			Log.getLoger(sn).logInfo.addRunLog("longClick[" + text + "] 返回="+ret);
			this.setInfo(DisplayUtil.Show.Info, "longClick[" + text + "] 返回="+ret, sn);
			int count = 2;
			while(false == ret && (mWatchers.size() > 0)) {
				System.out.println("run watchers");
				runWatcher();
				ret = this.uiAutomatorClient.longClick(text);
				Log.getLoger(sn).logInfo.addRunLog("longClick[" + text + "] 返回="+ret + " Count="+count);
				this.setInfo(DisplayUtil.Show.Info, "longClick[" + text + "] 返回="+ret + " Count="+count, sn);
				if(count-- < 0)
					break;
			}

			if(ret)
				return true;
			else
				throw new Exception(Errors.TOUCH_TEXT_FAIL);

		}else if(args.length == 2){
			x = ap.getInt(0)*this.d_width/this.s_width;
			y = ap.getInt(1)*this.d_height/this.s_height;
			ret = this.uiAutomatorClient.longClick(x, y);
			Log.getLoger(sn).logInfo.addRunLog("longClick[" + x +"," + y + "] 返回="+ret);
			this.setInfo(DisplayUtil.Show.Info, "longClick[" + x +"," + y + "] 返回=" + ret, sn);

			return ret;
			//System.out.println("click= x=" + x + " y="+y + " d_width=" + this.d_width + " s_width="+this.s_width + " d_height=" + d_height + " s_height=" + s_height);
		}
		return ret;

	}

	@MonkeyRunnerExported(doc="click screen", args={"x", "y"}, argDocs={"x coordinate in pixels", "y coordinate in pixels"}, returns = "boolean")
	public boolean scrollToBeginning(PyObject[] args, String[] kws) throws Exception {
		ArgParser ap = JythonUtils.createArgParser(args, kws);
		Preconditions.checkNotNull(ap);
		boolean ret = false;
		this.refreshProgressData();
		int maxSwipes = ap.getInt(0);

		ret = this.uiAutomatorClient.scrollToBeginning(maxSwipes);
		Log.getLoger(sn).logInfo.addRunLog("scrollToBeginning[" + maxSwipes + "] 返回="+ret);
		this.setInfo(DisplayUtil.Show.Info, "scrollToBeginning[" + maxSwipes + "] 返回=" + ret, sn);
		return ret;
	}

	@MonkeyRunnerExported(doc="click screen", args={"x", "y"}, argDocs={"x coordinate in pixels", "y coordinate in pixels"}, returns = "boolean")
	public boolean scrollToEnd(PyObject[] args, String[] kws) throws Exception {
		ArgParser ap = JythonUtils.createArgParser(args, kws);
		Preconditions.checkNotNull(ap);
		boolean ret = false;
		this.refreshProgressData();
		int maxSwipes = ap.getInt(0);

		ret = this.uiAutomatorClient.scrollToEnd(maxSwipes);
		Log.getLoger(sn).logInfo.addRunLog("scrollToEnd[" + maxSwipes + "] 返回="+ret);
		this.setInfo(DisplayUtil.Show.Info, "scrollToEnd[" + maxSwipes + "] 返回=" + ret, sn);
		return ret;
	}

	@MonkeyRunnerExported(doc="click screen", args={"x", "y"}, argDocs={"x coordinate in pixels", "y coordinate in pixels"}, returns = "boolean")
	public boolean clickAndWaitForNewWindow(PyObject[] args, String[] kws) throws Exception {
		ArgParser ap = JythonUtils.createArgParser(args, kws);
		Preconditions.checkNotNull(ap);
		boolean ret = false;

		this.refreshProgressData();
		String text = new String(ap.getString(0).getBytes("ISO-8859-1"), "UTF-8");
		long timeout = ap.getInt(1);
		ret = this.uiAutomatorClient.clickAndWaitForNewWindow(text, timeout);

		Log.getLoger(sn).logInfo.addRunLog("clickAndWaitForNewWindow[" + text + "] 返回="+ret);
		this.setInfo(DisplayUtil.Show.Info, "clickAndWaitForNewWindow[" + text + "] 返回="+ret, sn);
		int count = 2;
		while(false == ret && (mWatchers.size() > 0)) {
			System.out.println("run watchers");
			runWatcher();
			ret = this.uiAutomatorClient.clickAndWaitForNewWindow(text, timeout);
			Log.getLoger(sn).logInfo.addRunLog("clickAndWaitForNewWindow[" + text + "] 返回="+ret + " Count="+count);
			this.setInfo(DisplayUtil.Show.Info, "clickAndWaitForNewWindow[" + text + "] 返回="+ret + " Count="+count, sn);
			if(count-- < 0)
				break;
		}

		if(ret)
			return true;
		else
			throw new Exception(Errors.TOUCH_TEXT_FAIL);
	}

	@MonkeyRunnerExported(doc="search text in UI", args={"text"}, argDocs={"Text"}, returns = "boolean")
	public boolean textContains(PyObject[] args, String[] kws) throws UnsupportedEncodingException {
		ArgParser ap = JythonUtils.createArgParser(args, kws);
		Preconditions.checkNotNull(ap);
		String text = new String(ap.getString(0).getBytes("ISO-8859-1"), "UTF-8");
		this.refreshProgressData();
		boolean bRet = false;
		int count = 2;
		bRet = this.uiAutomatorClient.textContains(text);
//		while(false == bRet && (mWatchers.size() > 0)) {
//			System.out.println("run watchers");
//			runWatchers();
//			bRet = this.uiAutomatorClient.textContains(text);
//			if(count-- < 0)
//				break;
//		}

		if(null != Log.getLoger(sn))
			Log.getLoger(sn).logInfo.addRunLog("textContains[" + text + "] 返回="+bRet);
		this.setInfo(DisplayUtil.Show.Info, "textContains[" + text + "] 返回="+bRet, sn);
		return bRet;
	}

	@MonkeyRunnerExported(doc="search text in UI", args={"text"}, argDocs={"Text"}, returns = "boolean")
	public boolean findElementByXpath(PyObject[] args, String[] kws) throws UnsupportedEncodingException {
		ArgParser ap = JythonUtils.createArgParser(args, kws);
		Preconditions.checkNotNull(ap);
		String xpath = new String(ap.getString(0).getBytes("ISO-8859-1"), "UTF-8");
		this.refreshProgressData();
		WebElement bRet = null;
		int count = 2;
//		this.uiSelendroidClient.switchTo("WEBVIEW_0");

		bRet = this.uiSelendroidClient.findElement(xpath);
//		while(null == bRet && (mWatchers.size() > 0)) {
//			System.out.println("run watchers");
//			runWatchers();
//			bRet = this.uiSelendroidClient.findElement(xpath);
//			if(count-- < 0)
//				break;
//		}

//		this.uiSelendroidClient.switchTo("NATIVE_APP");

		Log.getLoger(sn).logInfo.addRunLog("findElementByXpath[" + xpath + "] 返回="+true);
		this.setInfo(DisplayUtil.Show.Info, "findElementByXpath[" + xpath + "] 返回="+true, sn);

		return (bRet != null)?true:false;
	}

	@MonkeyRunnerExported(doc="search text in UI", args={"text"}, argDocs={"Text"}, returns = "boolean")
	public boolean findElementById(PyObject[] args, String[] kws) throws UnsupportedEncodingException {
		ArgParser ap = JythonUtils.createArgParser(args, kws);
		Preconditions.checkNotNull(ap);
		String id = new String(ap.getString(0).getBytes("ISO-8859-1"), "UTF-8");
		this.refreshProgressData();
		boolean bRet = false;
		int count = 2;
		bRet = this.uiAutomatorClient.findElementById(id);
//		while(false == bRet && (mWatchers.size() > 0)) {
//			System.out.println("run watchers");
//			runWatchers();
//			bRet = this.uiAutomatorClient.findElementById(id);
//			if(count-- < 0)
//				break;
//		}

		Log.getLoger(sn).logInfo.addRunLog("findElementById[" + id + "] 返回="+bRet);
		this.setInfo(DisplayUtil.Show.Info, "findElementById[" + id + "] 返回="+bRet, sn);
		return bRet;
	}

	@MonkeyRunnerExported(doc="set text to TextView", args={"Object","instance","text"}, argDocs={"TextView Object", "index in UI", "Text"}, returns = "boolean")
	public boolean setTextByClass(PyObject[] args, String[] kws) throws UnsupportedEncodingException {
		ArgParser ap = JythonUtils.createArgParser(args, kws);
		Preconditions.checkNotNull(ap);
		boolean bRet = false;
		String object = ap.getString(0);
		int instance = ap.getInt(1);
		String text = new String(ap.getString(2).getBytes("ISO-8859-1"), "UTF-8");

		this.refreshProgressData();

		if(this.uiAutomatorClient.setTextByClass(object, instance, text)){
			Logger.getLogger(AndroidDriver.class).info("[" + sn + "]" + "setTextByClass[" + object + ", " +instance + ", "+ text + "] 返回="+true);
			Log.getLoger(sn).logInfo.addRunLog("setTextByClass[" + object + ", " +instance + ", "+ text + "] 返回="+true);
			this.setInfo(DisplayUtil.Show.Info, "setTextByClass[" + object + ", " +instance + ", "+ text + "] 返回="+true, sn);
			return true;
		}else{
			//if failed, run watcher
			int count = 2;
			while(bRet == false) {
				Logger.getLogger(AndroidDriver.class).info("[" + sn + "]" + "run watcher");
				runWatcher();
				bRet = this.uiAutomatorClient.setTextByClass(object, instance, text);
				Log.getLoger(sn).logInfo.addRunLog("setTextByClass[" + object + ", " +instance + ", "+ text + "] 返回="+bRet);
				this.setInfo(DisplayUtil.Show.Info, "setTextByClass[" + object + ", " +instance + ", "+ text + "] 返回="+bRet, sn);
				if(count-- < 0)
					break;
			}
		}

		return bRet;
	}

	@MonkeyRunnerExported(doc="set text to TextView", args={"Object","instance","text"}, argDocs={"TextView Object", "index in UI", "Text"}, returns = "boolean")
	public boolean setTextByXpath(PyObject[] args, String[] kws) throws UnsupportedEncodingException {
		ArgParser ap = JythonUtils.createArgParser(args, kws);
		Preconditions.checkNotNull(ap);
		boolean bRet = false;
		String xpath = ap.getString(0);
		String text = new String(ap.getString(1).getBytes("ISO-8859-1"), "UTF-8");

		this.refreshProgressData();

//		this.uiSelendroidClient.switchTo("WEBVIEW_0");

		if(this.uiSelendroidClient.sendKeys(xpath, text)) {
			Log.getLoger(sn).logInfo.addRunLog("setTextByXpath[" + xpath + ", " + text + "] 返回="+true);
			this.setInfo(DisplayUtil.Show.Info, "setTextByXpath[" + xpath + ", " + text + "] 返回="+true, sn);
			bRet = true;
		}else{
			//if failed, run watcher
			int count = 2;
			while(bRet == false) {
				System.out.println("run watchers");
				runWatcher();
				bRet = this.uiSelendroidClient.sendKeys(xpath, text);
				Log.getLoger(sn).logInfo.addRunLog("setTextByXpath[" + xpath + ", " +text + "] 返回="+bRet);
				this.setInfo(DisplayUtil.Show.Info, "setTextByXpath[" + xpath + ", " +text + "] 返回="+bRet, sn);
				if(count-- < 0)
					break;
			}
		}

//		this.uiSelendroidClient.switchTo("NATIVE_APP");

		return bRet;
	}

	@MonkeyRunnerExported(doc="set text to TextView", args={"Object","instance","text"}, argDocs={"TextView Object", "index in UI", "Text"}, returns = "boolean")
	public boolean setTextById(PyObject[] args, String[] kws) throws UnsupportedEncodingException {
		System.out.println(window);
		ArgParser ap = JythonUtils.createArgParser(args, kws);
		Preconditions.checkNotNull(ap);
		String id = ap.getString(0);
		int instance = ap.getInt(1);
		String text = new String(ap.getString(2).getBytes("ISO-8859-1"), "UTF-8");

		this.refreshProgressData();

		if(this.window.equals("NATIVE_APP")) {
			if(this.uiAutomatorClient.setTextById(id, instance, text)){
				Log.getLoger(sn).logInfo.addRunLog("setTextById[" + id + ", " +instance + ", "+ text + "] 返回="+true);
				this.setInfo(DisplayUtil.Show.Info, "setTextById[" + id + ", " +instance + ", "+ text + "] 返回="+true, sn);
				return true;
			}
		}else if(this.window.equals("WEBVIEW_0")) {
			if(this.uiSelendroidClient.sendKeys("//input[@id='" + id+"']", text)) {
				Log.getLoger(sn).logInfo.addRunLog("setTextById[" + id + ", " +instance + ", "+ text + "] 返回="+true);
				this.setInfo(DisplayUtil.Show.Info, "setTextById[" + id + ", " +instance + ", "+ text + "] 返回="+true, sn);
				return true;
			}
		}

		Log.getLoger(sn).logInfo.addRunLog("setTextById[" + id + ", " +instance + ", "+ text + "] 返回="+false);
		this.setInfo(DisplayUtil.Show.Info, "setTextById[" + id + ", " +instance + ", "+ text + "] 返回="+false, sn);
		return false;
	}

	@MonkeyRunnerExported(doc="takeSnapshot", args={"path", "fileName"}, argDocs={"releative path", "png name"}, returns = "String")
	public String takeSnapshot(PyObject[] args, String[] kws) throws Exception {
		ArgParser ap = JythonUtils.createArgParser(args, kws);
		Preconditions.checkNotNull(ap);

		String path = "";
		String fileName = "";
		if(args.length == 1) {
			path = Log.getLoger(sn).getPath();
			fileName = new String(ap.getString(0).getBytes("ISO-8859-1"), "UTF-8");
		}else if(args.length == 2) {
			path = new String(ap.getString(0).getBytes("ISO-8859-1"), "UTF-8");
			fileName = new String(ap.getString(1).getBytes("ISO-8859-1"), "UTF-8");
		}

		this.refreshProgressData();
		this.picCounter +=1;
		String counter = String.format("%04d", this.picCounter);
		String ret = "";

		for(int i=0;i<5;i++) {
			ret = this.uiAutomatorClient.takeSnapshot(path, counter + "_" +fileName);
			File file = new File(path + "/" + counter + "_" +fileName);
			if(file.exists()) {
				break;
			}
			Log.getLoger(sn).logInfo.addRunLog("takeSnapshot[" + path +", "+ fileName + "] 返回="+false);
		}
		Log.getLoger(sn).logInfo.addRunLog("takeSnapshot[" + path +", "+ fileName + "] 返回="+ret);
		this.setInfo(DisplayUtil.Show.Info, "takeSnapshot[" + path +", "+ fileName + "] 返回="+ret, sn);
		return ret;
	}

	@MonkeyRunnerExported(doc="get script compatible screen", args={"x", "y"}, argDocs={"x coordinate in pixels", "y coordinate in pixels"}, returns = "no")
	public boolean swipe(PyObject[] args, String[] kws) {
		ArgParser ap = JythonUtils.createArgParser(args, kws);
		Preconditions.checkNotNull(ap);

		int startX = ap.getInt(0)*this.d_width/this.s_width;  //
		int startY = ap.getInt(1)*this.d_height/this.s_height;
		int endX = ap.getInt(2)*this.d_width/this.s_width;
		int endY = ap.getInt(3)*this.d_height/this.s_height;

		this.refreshProgressData();
		boolean ret = this.uiAutomatorClient.swipe(startX, startY, endX, endY, 20);
		Log.getLoger(sn).logInfo.addRunLog("swipe[" + startX +", "+ startY + ", " + endX +"," + endY+ "] 返回="+ret);
		this.setInfo(DisplayUtil.Show.Info, "swipe[" + startX +", "+ startY + ", " + endX +"," + endY+ "] 返回="+ret, sn);
		return ret;
	}

	@MonkeyRunnerExported(doc="get script compatible screen", args={"x", "y"}, argDocs={"x coordinate in pixels", "y coordinate in pixels"}, returns = "no")
	public boolean pressBack(PyObject[] args, String[] kws) {
		ArgParser ap = JythonUtils.createArgParser(args, kws);
		Preconditions.checkNotNull(ap);

		this.refreshProgressData();
		boolean ret = this.uiAutomatorClient.pressBack();
		Log.getLoger(sn).logInfo.addRunLog("pressBack() 返回="+ret);
		this.setInfo(DisplayUtil.Show.Info, "pressBack() 返回="+ret, sn);
		return ret;
	}

	@MonkeyRunnerExported(doc="get script compatible screen", args={"x", "y"}, argDocs={"x coordinate in pixels", "y coordinate in pixels"}, returns = "no")
	public boolean pressDPadCenter(PyObject[] args, String[] kws) {
		ArgParser ap = JythonUtils.createArgParser(args, kws);
		Preconditions.checkNotNull(ap);

		this.refreshProgressData();
		return this.uiAutomatorClient.pressDPadCenter();
	}

	@MonkeyRunnerExported(doc="get script compatible screen", args={"x", "y"}, argDocs={"x coordinate in pixels", "y coordinate in pixels"}, returns = "no")
	public boolean pressDPadDown(PyObject[] args, String[] kws) {
		ArgParser ap = JythonUtils.createArgParser(args, kws);
		Preconditions.checkNotNull(ap);

		this.refreshProgressData();
		return this.uiAutomatorClient.pressDPadDown();
	}

	@MonkeyRunnerExported(doc="get script compatible screen", args={"x", "y"}, argDocs={"x coordinate in pixels", "y coordinate in pixels"}, returns = "no")
	public boolean pressDPadLeft(PyObject[] args, String[] kws) {
		ArgParser ap = JythonUtils.createArgParser(args, kws);
		Preconditions.checkNotNull(ap);

		this.refreshProgressData();
		return this.uiAutomatorClient.pressDPadLeft();
	}

	@MonkeyRunnerExported(doc="get script compatible screen", args={"x", "y"}, argDocs={"x coordinate in pixels", "y coordinate in pixels"}, returns = "no")
	public boolean pressDPadRight(PyObject[] args, String[] kws) {
		ArgParser ap = JythonUtils.createArgParser(args, kws);
		Preconditions.checkNotNull(ap);

		this.refreshProgressData();
		return this.uiAutomatorClient.pressDPadRight();
	}

	@MonkeyRunnerExported(doc="get script compatible screen", args={"x", "y"}, argDocs={"x coordinate in pixels", "y coordinate in pixels"}, returns = "no")
	public boolean pressDPadUp(PyObject[] args, String[] kws) {
		ArgParser ap = JythonUtils.createArgParser(args, kws);
		Preconditions.checkNotNull(ap);

		this.refreshProgressData();
		return this.uiAutomatorClient.pressDPadUp();
	}

	@MonkeyRunnerExported(doc="get script compatible screen", args={"x", "y"}, argDocs={"x coordinate in pixels", "y coordinate in pixels"}, returns = "no")
	public boolean pressDelete(PyObject[] args, String[] kws) {
		ArgParser ap = JythonUtils.createArgParser(args, kws);
		Preconditions.checkNotNull(ap);

		this.refreshProgressData();
		return this.uiAutomatorClient.pressDelete();
	}

	@MonkeyRunnerExported(doc="get script compatible screen", args={"x", "y"}, argDocs={"x coordinate in pixels", "y coordinate in pixels"}, returns = "no")
	public boolean pressEnter(PyObject[] args, String[] kws) {
		ArgParser ap = JythonUtils.createArgParser(args, kws);
		Preconditions.checkNotNull(ap);

		this.refreshProgressData();
		return this.uiAutomatorClient.pressEnter();
	}

	@MonkeyRunnerExported(doc="get script compatible screen", args={"x", "y"}, argDocs={"x coordinate in pixels", "y coordinate in pixels"}, returns = "no")
	public boolean pressHome(PyObject[] args, String[] kws) {
		ArgParser ap = JythonUtils.createArgParser(args, kws);
		Preconditions.checkNotNull(ap);

		this.refreshProgressData();
		return this.uiAutomatorClient.pressHome();
	}

	@MonkeyRunnerExported(doc="get script compatible screen", args={"x", "y"}, argDocs={"x coordinate in pixels", "y coordinate in pixels"}, returns = "no")
	public boolean pressMenu(PyObject[] args, String[] kws) {
		ArgParser ap = JythonUtils.createArgParser(args, kws);
		Preconditions.checkNotNull(ap);

		this.refreshProgressData();
		return this.uiAutomatorClient.pressMenu();
	}

	@MonkeyRunnerExported(doc="get script compatible screen", args={"x", "y"}, argDocs={"x coordinate in pixels", "y coordinate in pixels"}, returns = "no")
	public boolean pressKeyCode(PyObject[] args, String[] kws) {
		ArgParser ap = JythonUtils.createArgParser(args, kws);
		Preconditions.checkNotNull(ap);
		int keyCode = ap.getInt(0);
		int metaState = ap.getInt(1);

		this.refreshProgressData();
		return this.uiAutomatorClient.pressKeyCode(keyCode, metaState);
	}

	@MonkeyRunnerExported(doc="get script compatible screen", args={"x", "y"}, argDocs={"x coordinate in pixels", "y coordinate in pixels"}, returns = "no")
	public boolean pressKeyWords(PyObject[] args, String[] kws) {
		ArgParser ap = JythonUtils.createArgParser(args, kws);
		Preconditions.checkNotNull(ap);
		String str = ap.getString(0);

		Log.getLoger(sn).logInfo.addRunLog("pressKeyWords(" + str + ")");
		this.setInfo(DisplayUtil.Show.Info, "pressKeyWords(" + str + ")", sn);

		this.refreshProgressData();
		return this.uiAutomatorClient.pressKeyWords(str);
	}

	@MonkeyRunnerExported(doc="get script compatible screen", args={"x", "y"}, argDocs={"x coordinate in pixels", "y coordinate in pixels"}, returns = "no")
	public boolean logInfo(PyObject[] args, String[] kws) throws UnsupportedEncodingException {
		ArgParser ap = JythonUtils.createArgParser(args, kws);
		Preconditions.checkNotNull(ap);
		String log = new String(ap.getString(0).getBytes("ISO-8859-1"), "UTF-8");

		this.refreshProgressData();
		Log.getLoger(sn).logInfo.addRunLog(log);
		return true;
	}

	@MonkeyRunnerExported(doc="compare src to dest", args={"src", "rate"}, argDocs={"src - source picture", "dest - dest picture"}, returns = "boolean")
	public boolean compare(PyObject[] args, String[] kws) throws UnsupportedEncodingException {
		ArgParser ap = JythonUtils.createArgParser(args, kws);
		Preconditions.checkNotNull(ap);
		String filePath = new String(ap.getString(0).getBytes("ISO-8859-1"), "UTF-8").replace("\\", "/");
		int rate = ap.getInt(1);

		this.refreshProgressData();
		try {
			String screen = this.uiAutomatorClient.takeSnapshot("./temp/", "screen.png");

			String trimFilePath = StringUtil.trim(filePath);
			String project = trimFilePath.substring(0, trimFilePath.indexOf("/"));
			Area area = AreaLoader.load("./workspace/" + project + "/screen_area.xml",trimFilePath);

			return new ImageUtil(filePath, screen, rate).compare(area.getX(), area.getY(), area.getWidth(), area.getHeight());
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	@MonkeyRunnerExported(doc="findAndClickByScrollable", args={"text"}, argDocs={"src - source picture", "dest - dest picture"}, returns = "boolean")
	public boolean findAndClickByScrollable(PyObject[] args, String[] kws) throws UnsupportedEncodingException {
		ArgParser ap = JythonUtils.createArgParser(args, kws);
		Preconditions.checkNotNull(ap);
		String text = new String(ap.getString(0).getBytes("ISO-8859-1"), "UTF-8");

		this.refreshProgressData();
		try {
			return this.uiAutomatorClient.findAndClickByScrollable(text);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	@MonkeyRunnerExported(doc="invokeMethod", args={"text"}, argDocs={"src - source picture", "dest - dest picture"}, returns = "boolean")
	public PyObject invokeMethod(PyObject[] args, String[] kws) throws UnsupportedEncodingException {
		ArgParser ap = JythonUtils.createArgParser(args, kws);
		Preconditions.checkNotNull(ap);
		String path = "";
		String method = "";
		PyTuple obj = null;
		PyObject ret = null;

		if(args.length == 1) {
			path = new String(ap.getString(0).getBytes("ISO-8859-1"), "UTF-8");
			ret = executePython(path);
			return ret;
		}else if(args.length == 2){
			path = new String(ap.getString(0).getBytes("ISO-8859-1"), "UTF-8");
			method = ap.getString(1);
			ret = executePython(path, method);
			return ret;
		}else if(args.length == 3){
			path = new String(ap.getString(0).getBytes("ISO-8859-1"), "UTF-8");
			method = ap.getString(1);
			obj = (PyTuple)ap.getList(2);

			ret = executePython(path, method, obj);//obj.__getitem__(0).__getitem__(0)
			return ret;
		}
		return ret;
	}

	private void setInfo(final DisplayUtil.Show show,final String key,final String sn){
		Display.getDefault().asyncExec(new Runnable(){
			public void run()
			{
				AndroidRobot.showLog(show,key,sn);
			}
		});
	}
}

class Install implements Runnable{
	private UiSelendroidClient uiSelendroidClient = null;
	private String serial = "";
	private String pkgName = "";
	private String actName = "";
	private String version = "";
	private String exception = "";
	public Install(UiSelendroidClient uiSelendroidClient, String serial, String pkgName, String actName, String version) {
		this.uiSelendroidClient = uiSelendroidClient;
		this.serial = serial;
		this.pkgName = pkgName;
		this.actName = actName;
		this.version = version;
	}

	public void getMessage() throws Exception {
		if(!exception.trim().equals("")) {
			throw new Exception(this.exception);
		}
	}

	@Override
	public void run() {
		try {
			this.uiSelendroidClient.setup(serial, pkgName, actName, version);
		} catch (Exception e) {
			exception = e.getMessage();
		}
	}

}


text:
package torin.dmitry.fruitslots.framework.impl;

import android.view.View;

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

import torin.dmitry.fruitslots.framework.*;
import torin.dmitry.fruitslots.framework.Input.KeyEvent;

/**
 * Created by Torin Dmitry on 29.05.2017.
 */

public class KeyboardHandler implements View.OnKeyListener {
    private boolean[] pressedKeys = new boolean[128];
    private Pool<KeyEvent> keyEventPool;
    private List<KeyEvent> keyEventsBuffer = new ArrayList<KeyEvent>();
    private List<KeyEvent> keyEvents = new ArrayList<KeyEvent>();

    public KeyboardHandler(View v) {
        Pool.PoolObjectFactory<Input.KeyEvent> factory = new Pool.PoolObjectFactory<Input.KeyEvent>() {
            @Override
            public Input.KeyEvent createObject() {
                return new Input.KeyEvent();
            }
        };
        keyEventPool = new Pool<KeyEvent>(factory, 100);
        v.setOnKeyListener(this);
        v.setFocusableInTouchMode(true);
        v.requestFocus();
    }

    @Override
    public boolean onKey(View v, int keyCode, android.view.KeyEvent event) {
        if (event.getAction() == android.view.KeyEvent.ACTION_MULTIPLE)
            return false;
        synchronized (this) {
            KeyEvent keyEvent = keyEventPool.newObject();
            keyEvent.keyCode = keyCode;
            keyEvent.keyChar = (char) event.getUnicodeChar();
            if (event.getAction() == android.view.KeyEvent.ACTION_DOWN) {
                keyEvent.type = KeyEvent.KEY_DOWN;
                if (keyCode > 0 && keyCode < 127)
                    pressedKeys[keyCode] = true;
            }
            if (event.getAction() == android.view.KeyEvent.ACTION_UP) {
                keyEvent.type = KeyEvent.KEY_UP;
                if (keyCode > 0 && keyCode <= 127)
                    pressedKeys[keyCode] = false;
            }
            keyEventsBuffer.add(keyEvent);
        }
        return false;
    }

    public boolean isKeyPressed(int keyCode) {
        if (keyCode < 0 || keyCode > 127)
            return false;
        return pressedKeys[keyCode];
    }

    public List<KeyEvent> getKeyEvents() {
        synchronized (this) {
            int len = keyEvents.size();
            for (int i = 0; i < len; i++) {
                keyEventPool.free(keyEvents.get(i));
            }
            keyEvents.clear();
            keyEvents.addAll(keyEventsBuffer);
            keyEventsBuffer.clear();
            return keyEvents;
        }
    }

}


text:
import weakref
import logging
import threading
import traceback
import collections

finlock = threading.RLock()
logger  = logging.getLogger(__name__)

from synapse.common import *

class EventBus:
    '''
    A synapse EventBus provides an easy way manage callbacks.
    '''
    def __init__(self):
        self.isfini = False
        self.finlock = finlock
        self.finievt = threading.Event()

        self._syn_funcs = collections.defaultdict(list)
        self._syn_weaks = collections.defaultdict(weakref.WeakSet)

        self._syn_links = []
        self._syn_weak_links = weakref.WeakSet()

        self._syn_queues = {}

        self._fini_funcs = []
        self._fini_weaks = weakref.WeakSet()

    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        self.fini()

    def link(self, func, weak=False):
        '''
        Add a callback function to receive *all* events.

        Example:

            bus1 = EventBus()
            bus2 = EventBus()

            bus1.link( bus2.dist )

            # all events on bus1 are also propigated on bus2

        '''
        if not callable(func):
            raise Exception('link() func not callable: %r' % (func,))

        if weak:
            return self._syn_weak_links.add(func)

        self._syn_links.append(func)

    def unlink(self, func):
        '''
        Remove a callback function previously added with link()

        Example:

            bus.unlink( callback )

        '''
        self._syn_weak_links.discard(func)
        if func in self._syn_links:
            self._syn_links.remove(func)

    def on(self, name, func, weak=False):
        '''
        Add a callback func to the SynCallBacker.

        Example:

            def baz(event):
                x = event[1].get('x')
                y = event[1].get('y')
                return x + y

            d.on('woot',baz)

            d.fire('foo', x=10, y=20)

        Notes:

            * Use weak=True to hold a weak reference to the func.

        '''
        if not callable(func):
            raise Exception('on() func not callable: %r' % (func,))

        if weak:
            self._syn_weaks[name].add(func)
            return

        self._syn_funcs[name].append(func)

    def off(self, name, func):
        '''
        Remove a previously registered event handler function.

        Example:

            bus.off( 'foo', onFooFunc )

        '''
        funcs = self._syn_funcs.get(name)
        if funcs != None:

            if func in funcs:
                funcs.remove(func)

            if not funcs:
                self._syn_funcs.pop(name,None)

        weaks = self._syn_weaks.get(name)
        if weaks != None:

            if func in weaks:
                weaks.remove(func)

            if not weaks:
                self._syn_weaks.pop(name,None)

    def fire(self, evtname, **info):
        '''
        Fire the given event name on the EventBus.
        Returns a list of the return values of each callback.

        Example:

            for ret in d.fire('woot',foo='asdf'):
                print('got: %r' % (ret,))

        '''
        event = (evtname,info)
        self.dist(event)
        return event

    def dist(self, event):
        '''
        Distribute an existing event tuple.
        '''
        ret = []
        name = event[0]
        funcs = self._syn_funcs.get(name)
        if funcs != None:
            for func in funcs:
                try:
                    ret.append( func( event ) )
                except Exception as e:
                    logger.exception(e)

        weaks = self._syn_weaks.get(name)
        if weaks != None:
            for func in weaks:
                try:
                    ret.append( func( event ) )
                except Exception as e:
                    logger.exception(e)

        for func in self._syn_links:
            try:
                ret.append( func(event) )
            except Exception as e:
                logger.exception(e)

        for func in self._syn_weak_links:
            try:
                ret.append( func(event) )
            except Exception as e:
                logger.exception(e)

        return ret

    def fini(self):
        '''
        Fire the 'fini' handlers and set self.isfini.

        Example:

            d.fini()

        '''
        with finlock:

            if self.isfini:
                return

            self.isfini = True

        for func in self._fini_funcs:
            try:
                func()
            except Exception as e:
                traceback.print_exc()

        for func in self._fini_weaks:
            try:
                func()
            except Exception as e:
                traceback.print_exc()

        self.finievt.set()

    def onfini(self, func, weak=False):
        '''
        Register a handler to fire when this EventBus shuts down.
        '''
        if weak:
            return self._fini_weaks.add(func)
        self._fini_funcs.append(func)

    def waitfini(self, timeout=None):
        '''
        Wait for the event bus to fini()

        Example:

            bus.waitfini(timeout=30)

        '''
        return self.finievt.wait(timeout=timeout)

    def main(self):
        '''
        Helper function to block until shutdown ( and handle ctrl-c etc ).

        Example:

            dmon.main()
            # we have now fini()d

        '''
        try:
            self.waitfini()
        except KeyboardInterrupt as e:
            print('ctrl-c caught: shutting down')
            self.fini()

    def distall(self, events):
        '''
        Distribute multiple events on the event bus.
        '''
        [self.dist(evt) for evt in events]

    @firethread
    def consume(self, gtor):
        '''
        Feed the event bus from a generator.

        Example:

            bus.consume( getAllEvents() )

        '''
        for e in gtor:
            if e == None:
                break

            self.dist(e)

    def waiter(self, count, *names):
        '''
        Construct and return a new Waiter for events on this bus.

        Example:

            # wait up to 3 seconds for 10 foo:bar events...

            waiter = bus.waiter(10,'foo:bar')

            # .. fire thread that will cause foo:bar events

            events = waiter.wait(timeout=3)

            if events == None:
                # handle the timout case...

            for event in events:
                # parse the events if you need...

        NOTE: use with caution... it's easy to accidentally construct
              race conditions with this mechanism ;)

        '''
        return Waiter(self, count, *names)

class Waiter:
    '''
    A helper to wait for a given number of events on an EventBus.
    '''
    def __init__(self, bus, count, *names):
        self.bus = bus
        self.names = names
        self.count = count
        self.event = threading.Event()

        self.events = []

        for name in names:
            bus.on(name, self._onWaitEvent)

        if not names:
            bus.link(self._onWaitEvent)

    def _onWaitEvent(self, mesg):
        self.events.append(mesg)
        if len(self.events) >= self.count:
            self.event.set()

    def wait(self, timeout=None):
        '''
        Wait for the required number of events and return them
        or None on timeout.

        Example:

            evnts = waiter.wait(timeout=30)

            if evnts == None:
                handleTimedOut()
                return

            for evnt in evnts:
                doStuff(evnt)

        '''
        try:

            self.event.wait(timeout=timeout)
            if not self.event.is_set():
                return None

            return self.events

        finally:
            self.fini()

    def fini(self):

        for name in self.names:
            self.bus.off(name,self._onWaitEvent)

        if not self.names:
            self.bus.unlink(self._onWaitEvent)


text:
package fm.serializer.protobuf

import java.io.{BufferedInputStream, ByteArrayInputStream, ByteArrayOutputStream, InputStream}
import fm.serializer.{Deserializer, Serializer}

final class TestProtobufStream extends TestProtobufStreamBase(0)
final class TestProtobufStream1 extends TestProtobufStreamBase(1)
final class TestProtobufStream2 extends TestProtobufStreamBase(2)
final class TestProtobufStream3 extends TestProtobufStreamBase(3)
final class TestProtobufStream4 extends TestProtobufStreamBase(4)
final class TestProtobufStream5 extends TestProtobufStreamBase(5)
final class TestProtobufStream6 extends TestProtobufStreamBase(6)
final class TestProtobufStream7 extends TestProtobufStreamBase(7)
final class TestProtobufStream8 extends TestProtobufStreamBase(8)
final class TestProtobufStream9 extends TestProtobufStreamBase(9)
//final class TestProtobufStream10 extends TestProtobufStreamBase(10)
//final class TestProtobufStream11 extends TestProtobufStreamBase(11)
//final class TestProtobufStream12 extends TestProtobufStreamBase(12)
//final class TestProtobufStream13 extends TestProtobufStreamBase(13)
//final class TestProtobufStream14 extends TestProtobufStreamBase(14)
//final class TestProtobufStream15 extends TestProtobufStreamBase(15)
//final class TestProtobufStream16 extends TestProtobufStreamBase(16)
//final class TestProtobufStream17 extends TestProtobufStreamBase(17)
//final class TestProtobufStream18 extends TestProtobufStreamBase(18)
//final class TestProtobufStream19 extends TestProtobufStreamBase(19)
//final class TestProtobufStream20 extends TestProtobufStreamBase(20)
//final class TestProtobufStream16 extends TestProtobufStreamBase(16)
//final class TestProtobufStream32 extends TestProtobufStreamBase(32)
//final class TestProtobufStream64 extends TestProtobufStreamBase(64)
//final class TestProtobufStream128 extends TestProtobufStreamBase(128)
//final class TestProtobufStream1024 extends TestProtobufStreamBase(1024)
//final class TestProtobufStream4096 extends TestProtobufStreamBase(4096)
final class TestProtobufStream8192 extends TestProtobufStreamBase(8192) // This is the default BufferedInputStream size

/**
 * This tests ProtobufInputStreamInput
 */
sealed abstract class TestProtobufStreamBase(bufferSize: Int) extends fm.serializer.TestSerializer[Array[Byte]]  {
  def serialize[T](v: T)(implicit ser: Serializer[T]): Array[Byte] = {
    val os = new ByteArrayOutputStream()
    Protobuf.toOutputStream[T](os, v)
    os.toByteArray()
  }

  def deserialize[T](bytes: Array[Byte])(implicit deser: Deserializer[T]): T = {
    val is = new ByteArrayInputStream(bytes)
    Protobuf.fromInputStream[T](is)
  }

  def makeInput(bytes: Array[Byte]): ProtobufInputStreamInput = {
    val is: InputStream = if (bufferSize > 0) new BufferedInputStream(new ByteArrayInputStream(bytes), bufferSize) else new ByteArrayInputStream(bytes)
    new ProtobufInputStreamInput(is, ProtobufOptions.default)
  }
}


text:
<?php

$dictionary['Contact']['fields']['SecurityGroups'] = array (
  	'name' => 'SecurityGroups',
    'type' => 'link',
	'relationship' => 'securitygroups_contacts',
	'module'=>'SecurityGroups',
	'bean_name'=>'SecurityGroup',
    'source'=>'non-db',
	'vname'=>'LBL_SECURITYGROUPS',
);

?>


text:
> An Elixir wrapper around the Imgur API

## Installation
Add `imgur` to your deps in `mix.exs`

```elixir
def deps do
  [{:imgur, "~> 0.1.0"}]
end
```

## Usage
```elixir
client = Imgur.Client.new(client_id: "myclientid")
{:ok, image} = Imgur.Image.get(client, "someimageid")
```

## Maintainer
[Jordan Adams](http://github.com/jordanadams)

## Contribute
PRs are welcome.

If you have any problems or questions, please [create an issue](https://github.com/JordanAdams/imgur-elixir/issues/new).

## License
[MIT © Jordan Adams](https://github.com/JordanAdams/imgur-elixir/blob/master/LICENSE)


text:
Start-Transcript

# Install
Install-Module "ExchangeOnlineManagement"
Install-Module -Name "MicrosoftTeams"

# Import
Import-Module "ExchangeOnlineManagement"
Import-Module -Name "MicrosoftTeams"

# Connect
Connect-ExchangeOnline
Connect-MicrosoftTeams

# Default
$AllTeamsInOrg = (Get-Team).GroupID
$TeamList = @()

# Loop
Write-Output "This may take a little bit of time... Please sit back, relax and enjoy some GIFs inside of Teams!"
Foreach ($Team in $AllTeamsInOrg) {
    # Parse Inputs
    $TeamGUID           = $Team.ToString()
    $TeamGroup          = Get-UnifiedGroup -identity $Team.ToString()
    $TeamName           = (Get-Team | ? { $_.GroupID -eq $Team }).DisplayName
    $TeamOwner          = (Get-TeamUser -GroupId $Team | ? { $_.Role -eq 'Owner' }).User
    $TeamUserCount      = ((Get-TeamUser -GroupId $Team).UserID).Count
    $TeamCreationDate   = Get-unifiedGroup -identity $team.ToString() | Select -expandproperty WhenCreatedUTC
    $TeamGuest          = (Get-UnifiedGroupLinks -LinkType Members -identity $Team | ? { $_.Name -match "#EXT#" }).Name

    # Zero Guests
    if ($TeamGuest -eq $null) {
        $TeamGuest = "No Guests in Team"
    }

    # Append for CSV
    $TeamList = $TeamList + [PSCustomObject]@{
        TeamName = $TeamName;
        TeamObjectID = $TeamGUID;
        TeamCreationDate = $TeamCreationDate;
        TeamOwners = $TeamOwner -join ', ';
        TeamMemberCount = $TeamUserCount;
        TeamSite = $TeamGroup.SharePointSiteURL;
        AccessType = $TeamGroup.AccessType;
        TeamGuests = $TeamGuest -join ','
    }
}

# Write CSV
$TempFolder = "c:\temp"
New-Item -ItemType "Directory" -Path $TempFolder -ErrorAction "SilentlyContinue" | Out-Null
$TeamList | Export-Csv "$TempFolder\TeamsDatav2.csv" -NoTypeInformation

# Transcript
Stop-Transcript


text:
/*
 * create a cordova/android project
 *
 * USAGE
 *  ./create [path package activity]
 */

function read(filename) {
    var fso=WScript.CreateObject("Scripting.FileSystemObject");
    var f=fso.OpenTextFile(filename, 1, true);
    var s=f.ReadAll();
    f.Close();
    return s;
}
function write(filename, contents) {
    var fso=WScript.CreateObject("Scripting.FileSystemObject");
    var f=fso.OpenTextFile(filename, 2, true);
    f.Write(contents);
    f.Close();
}
function replaceInFile(filename, regexp, replacement) {
    write(filename, read(filename).replace(regexp, replacement));
}
function exec(s) {
    var o=shell.Exec(s);
}

var args = WScript.Arguments, PROJECT_PATH="example",
    PACKAGE="org.apache.cordova.example", ACTIVITY="cordovaExample",
    shell=WScript.CreateObject("WScript.Shell");

if (args.Count() == 3) {
    WScript.Echo('Found expected arguments');
    PROJECT_PATH=args(0);
    PACKAGE=args(1);
    ACTIVITY=args(2);
}

var PACKAGE_AS_PATH=PACKAGE.replace(/\./g, '\\');
var ACTIVITY_PATH=PROJECT_PATH+'\\src\\'+PACKAGE_AS_PATH+'\\'+ACTIVITY+'.java';
var MANIFEST_PATH=PROJECT_PATH+'\\AndroidManifest.xml';
var TARGET=shell.Exec('android.bat list targets').StdOut.ReadAll().match(/id:\s([0-9]).*/)[1];
var VERSION=read('VERSION').replace(/\r\n/,'').replace(/\n/,'');

// clobber any existing example

/*
if [ $# -eq 0 ]
then
    rm -rf $PROJECT_PATH
fi
*/

// create the project
exec('android.bat create project --target '+TARGET+' --path '+PROJECT_PATH+' --package '+PACKAGE+' --activity '+ACTIVITY);

// update the cordova framework project to a target that exists on this machine
exec('android.bat update project --target '+TARGET+' --path framework');

// compile cordova.js and cordova.jar
// if you see an error about "Unable to resolve target" then you may need to
// update your android tools or install an additional Android platform version
exec('ant.bat -f framework\\build.xml jar');

// copy in the project template
exec('cmd /c xcopy bin\\templates\\project '+PROJECT_PATH+' /S /Y');

// copy in cordova.js
exec('cmd /c copy framework\\assets\\www\\cordova-'+VERSION+'.js '+PROJECT_PATH+'\\assets\\www\\cordova-'+VERSION+'.js /Y');

// copy in cordova.jar
exec('cmd /c copy framework\\cordova-'+VERSION+'.jar '+PROJECT_PATH+'\\libs\\cordova-'+VERSION+'.jar /Y');

// copy in default activity
exec('cmd /c copy bin\\templates\\Activity.java '+ACTIVITY_PATH+' /Y');

// interpolate the activity name and package
replaceInFile(ACTIVITY_PATH, /__ACTIVITY__/, ACTIVITY);
replaceInFile(ACTIVITY_PATH, /__ID__/, PACKAGE);

replaceInFile(MANIFEST_PATH, /__ACTIVITY__/, ACTIVITY);
replaceInFile(MANIFEST_PATH, /__PACKAGE__/, PACKAGE);

/*
# leave the id for launching
touch $PROJECT_PATH/package-activity
echo $PACKAGE/$PACKAGE.$ACTIVITY >  $PROJECT_PATH/package-activity
*/


text:
<?php
return [

    /*
     * Translations and languages will be stored in the database, if you want
     * to have custom table names for these models, you sure can.
     */
    'tables' => [
        'translations' => 'translations',
        'groups' => 'groups',
        'namespaces' => 'namespaces',
        'languages' => 'languages'
    ],

    /**
     * Exclude specific groups from Laravel Translation Manager.
     * This is useful if, for example, you want to avoid editing the official Laravel language files.
     *
     * @type array
     *
     *  array(
     *      'pagination',
     *      'reminders',
     *      'validation',
     *  )
     */
    'exclude_groups' => array(),

    /*
     * Translations will be fetched by these loaders, make sure they implement
     * the Thomasvvugt\LaraLang\TranslationLoaders\TranslationLoader-interface.
     */
    'translation_loaders' => [
        Thomasvvugt\LaraLang\TranslationLoaders\DatabaseLoader::class,
    ],

    /*
     * Translation line, and their languages are stored in these models. You
     * are free to edit these and make your own. Do make sure that you extend
     * these models.
     */
    'models' => [
    	'translation' => Thomasvvugt\LaraLang\Translation::class,
      'group' => Thomasvvugt\LaraLang\Group::class,
      'namespace' => Thomasvvugt\LaraLang\Namespc::class,
    	'language' => Thomasvvugt\LaraLang\Language::class
    ]
];


text:
import logging
import time

from baseservice import BaseService, handler, register

LOBBY_CHAT_ID = 0

class ChatService(BaseService):

    # TODO: Add FIFO policy to the dict to limit the msg in memory

    def __init__(self):
        BaseService.__init__(self, 'ChatService')
        # init
        self.chat_room_list = []
        self.chat_room = {}
        self.chat_root_content = {}
        # next cid
        self.next_cid = LOBBY_CHAT_ID
        # init lobby
        self.make_new_chat_room()
        self.load_handlers()

    def make_new_chat_room(self, uid=None):
        cid = self.next_cid
        self.next_cid += 1
        self.chat_room_list.append(cid)
        self.chat_room[cid] = [] if uid is None else [uid]
        self.chat_root_content[cid] = []

    def load_handlers(self):
        @register(self)
        @handler
        def join_chat_room(uid, cid):
            if cid in self.chat_room_list:
                self.chat_room[cid].append(uid)
                return {'code': 200, 'uid': uid, 'cid': cid}
            else:
                return {'code': 404}
        self.add_handler(join_chat_room)

        @register(self)
        @handler
        def send_msg(uid, username, cid, msg):
            if cid not in self.chat_root_content:
                return {'code': 404, 'msg': 'cannot send msg. Room not exists or User not in the room'}
            if uid not in self.chat_room[cid]:
                return {'code': 404, 'msg': 'cannot send msg. Room not exists or User not in the room'}
            if len(msg) >= 100:
                return {'code': 404, 'msg': 'msg is too long(less 100 characters)'}
            self.chat_root_content[cid].append(
                {'time': time.strftime("%Y-%m-%d %H:%M"), 'username': username, 'msg': msg})
            return {'code': 200, 'msg': ''}

        @register(self)
        @handler
        def get_msg(cid, uid):
            if cid not in self.chat_root_content:
                return {'code': 404, 'msg': 'cannot send msg. Room not exists or User not in the room'}
            if uid not in self.chat_room[cid]:
                return {'code': 404, 'msg': 'uid %d not in the room cid: %d'.format(uid, cid)}
            content_list = self.chat_root_content[cid]
            # size = min(len(content_list), 20)  # avoid size exceed
            msgs = content_list  # self.chat_root_content[cid][-size:]
            return {'code': 200, 'cid': cid, 'data': msgs, 'token': str(hash(str(msgs)))}

        @register(self)
        @handler
        def get_room_msg_list_hash(cid):
            if cid not in self.chat_root_content:
                return {'code': 404, 'msg': 'cannot send msg. Room not exists or User not in the room'}
            return {'code': 200, 'token': hash(str(self.chat_root_content[cid]))}