text:
package ariba.util.io;

import java.io.FilterReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.List;
import java.util.Map;

import ariba.util.core.Constants;
import ariba.util.core.Fmt;
import ariba.util.core.ListUtil;
import ariba.util.core.MapUtil;
import ariba.util.core.OrderedHashtable;

/**
    FilterInputStream subclass that can deserialize Maps,
    Lists, arrays, and Strings from an ASCII stream. The
    serialization format is very similar to the output of Map's
    and List's toString() methods, except strings with
    non-alphanumeric characters are quoted and special characters are
    escaped so that the output can be unambiguously deserialized.

    @see Serializer

    @aribaapi private
*/
public class Deserializer extends FilterReader
{
    private TokenGenerator tokenGenerator;

    /* static methods */

    /**
        Convenience method for creating a Deserializer taking its
        input from reader. This method only returns
        null on error instead of throwing an exception.
    */
    public static Object readObject (Reader reader)
    {
        Object object;
        Deserializer deserializer;

        try {
            deserializer = new Deserializer(reader);
            object = deserializer.readObject();
        }
        catch (IOException e) {
            object = null;
        }
        catch (DeserializationException e) {
            object = null;
        }
        return object;
    }

    private boolean useOrderedHashtable = false;

    /* constructors */

    /**
        Constructs a Deserializer that takes its input from reader.
    */
    public Deserializer (Reader reader)
    {
        super(reader);
        tokenGenerator = new TokenGenerator(reader);
    }

    public boolean useOrderedHashtable ()
    {
        return useOrderedHashtable;
    }

    public void setUseOrderedHashtable (boolean useOrderedHashtable)
    {
        this.useOrderedHashtable = useOrderedHashtable;
    }

    /**
        Convenience method for deserializing from the string
        serialization. Returns null on error.
    */
    public static Object deserializeObject (String serialization)
    {
        StringReader in;

        if (serialization == null) {
            return null;
        }

        in = new StringReader(serialization);
        return readObject(in);
    }

    /**
        Deserializes the next Dictionary, array, List, or String
        from the current reader.
    */
    public Object readObject ()
      throws IOException, DeserializationException
    {
        return readObjectInternal();
    }

    /**
        Deserializes the next object from the current reader.
        The result goes *into* the passed in object as opposed to
        creating a brand new instance.

        NOTE: Currently, this is only wired up for hashtables and lists.
        See readObjectInternal(Object instance) for the actual implementation.
    */
    public void readObject (Object instance)
      throws IOException, DeserializationException
    {
        readObjectInternal(instance);
    }

    private final void readObjectInternal (Object instance)
      throws IOException, DeserializationException
    {
        int token;

        if (!tokenGenerator.hasMoreTokens()) {
            return;
        }

        token = tokenGenerator.nextToken();
        switch (token) {
            case TokenGenerator.STRING_TOKEN:
            case TokenGenerator.ARRAY_BEGIN_TOKEN:
                return;
            case TokenGenerator.VECTOR_BEGIN_TOKEN:
                readIntoList((List)instance);
                return;
            case TokenGenerator.HASHTABLE_BEGIN_TOKEN:
                readIntoMap((Map)instance);
                return;
            default:
                syntaxError();
                return;
        }
    }

    private final Object readObjectInternal ()
      throws IOException, DeserializationException
    {
        int token;

        if (!tokenGenerator.hasMoreTokens()) {
            return null;
        }

        token = tokenGenerator.nextToken();
        switch (token) {
            case TokenGenerator.STRING_TOKEN:
                return stringForToken();
            case TokenGenerator.ARRAY_BEGIN_TOKEN:
                return readArray();
            case TokenGenerator.VECTOR_BEGIN_TOKEN:
                return readList();
            case TokenGenerator.HASHTABLE_BEGIN_TOKEN:
                return readMap();
            default:
                syntaxError();
                return null;
        }
    }

    private final void readKeyValuePair (Map result)
      throws IOException, DeserializationException
    {
        Object key;
        Object value;
        int token;
        int nextToken;

        key = readObjectInternal();
        if (key == null) {
            unterminatedExpression();
        }

        if (!tokenGenerator.hasMoreTokens()) {
            unterminatedExpression();
        }

        token = tokenGenerator.nextToken();
        if (token != TokenGenerator.HASHTABLE_KEY_VALUE_SEP_TOKEN) {
            syntaxError();
        }

        if (!tokenGenerator.hasMoreTokens()) {
            unterminatedExpression();
        }

        // This code is here and not in readObjectInternal() because we
        // only want to allow null in arrays and maps.  It should be a syntax error
        // for the null token to appear elsewhere.

        nextToken = tokenGenerator.peekNextToken();
        if (nextToken == TokenGenerator.NULL_VALUE_TOKEN) {
            tokenGenerator.nextToken();
            value = null;
        }
        else {
            value = readObjectInternal();
            if (value == null) {
                unterminatedExpression();
            }
        }
        result.put(key, value);

        if (!tokenGenerator.hasMoreTokens()) {
            unterminatedExpression();
        }

        token = tokenGenerator.peekNextToken();
        if (token == TokenGenerator.HASHTABLE_KEY_VALUE_END_TOKEN ||
            token == TokenGenerator.GENERIC_SEP_TOKEN)
            tokenGenerator.nextToken();
    }

    private final Map readMap ()
      throws IOException, DeserializationException
    {
        Map result = null;

        if (useOrderedHashtable()) {
            result = new OrderedHashtable();
        }
        else {
            result = MapUtil.map();
        }
        readIntoMap(result);
        return result;
    }

    private final void readIntoMap (Map target)
      throws IOException, DeserializationException
    {
        int token;

        while (true) {
            if (!tokenGenerator.hasMoreTokens()) {
                unterminatedExpression();
            }

            token = tokenGenerator.peekNextToken();
            if (token == TokenGenerator.HASHTABLE_END_TOKEN) {
                tokenGenerator.nextToken();
                return;
            }

            readKeyValuePair(target);
        }
    }

    private final List readList ()
      throws IOException, DeserializationException
    {
        List result = ListUtil.list();
        int token;
        boolean justAddedObject=false;
        Object object;

        while (true) {
            if (!tokenGenerator.hasMoreTokens()) {
                unterminatedExpression();
            }

            token = tokenGenerator.peekNextToken();
            if (token == TokenGenerator.VECTOR_END_TOKEN) {
                tokenGenerator.nextToken();
                return result;
            }

            if (token == TokenGenerator.GENERIC_SEP_TOKEN) {
                tokenGenerator.nextToken();
                if (justAddedObject) {
                    justAddedObject = false;
                }
                else {
                    syntaxError();
                }
            }
            else if (justAddedObject) {
                syntaxError();
            }

            object = readObjectInternal();
            if (object != null) {
                result.add(object);
                justAddedObject = true;
            }
        }
    }

    private final void readIntoList (List target)
      throws IOException, DeserializationException
    {
        List list = readList();
        target.addAll(list);
    }

    private final Object[] readArray ()
      throws IOException, DeserializationException
    {
        Object buf[] = new Object[16];
        int bufIndex = 0;
        Object obj;
        int nextToken;
        boolean justAddedObject=false;

        while (true) {
            if (!tokenGenerator.hasMoreTokens()) {
                unterminatedExpression();
            }

            nextToken = tokenGenerator.peekNextToken();
            if (nextToken == TokenGenerator.ARRAY_END_TOKEN) {
                tokenGenerator.nextToken();
                Object result[] = new Object[bufIndex];
                System.arraycopy(buf, 0, result, 0, bufIndex);
                return result;
            }
            else if (nextToken == TokenGenerator.GENERIC_SEP_TOKEN) {
                tokenGenerator.nextToken();
                if (justAddedObject) {
                    justAddedObject=false;
                }
                else {
                    syntaxError();
                }
            }
            else if (justAddedObject) {
                syntaxError();
            }

            // This code is here and not in readObjectInternal() because we
            // only want to allow null in arrays.  It should be a syntax error
            // for the null token to appear elsewhere.

            nextToken = tokenGenerator.peekNextToken();
            if (nextToken == TokenGenerator.NULL_VALUE_TOKEN) {
                tokenGenerator.nextToken();
                obj = null;
            }
            else {
                obj = readObjectInternal();
            }

            buf[bufIndex++] = obj;
            if (bufIndex == buf.length) {
                Object newBuf[] = new Object[buf.length * 2];
                System.arraycopy(buf, 0, newBuf, 0, buf.length);
                buf = newBuf;
            }
            justAddedObject = true;
        }
    }

    private final String stringForToken () throws DeserializationException
    {
        char str[] = tokenGenerator.charsForLastToken();

        if (str == null || str.length == 0) {
            internalInconsistency("empty string");
        }

        if (str[0] == '"') {
            char ch;
            char charBuf[] = new char[32];
            int charBufIndex = 0;
            int i;
            int c;

            for (i = 1, c = str.length-1; i < c; i++) {
                ch = str[i];
                if (ch == '\\') {
                    char nextChar = 0;
                    if (++i < c) {
                        nextChar = str[i];
                    }
                    else {
                        malformedString();
                    }

                    switch (nextChar) {
                      case '"': {
                          nextChar = '\"';
                          break;
                      }
                      case 't': {
                          nextChar = '\t';
                          break;
                      }
                      case 'n': {
                          nextChar = '\n';
                          break;
                      }
                      case 'r': {
                          nextChar = '\r';
                          break;
                      }
                      case '\\': {
                          nextChar = '\\';
                          break;
                      }
                      case 'u': {
                          char one   = 0;
                          char two   = 0;
                          char three = 0;
                          char four  = 0;

                          if (++i < c) {
                              one = str[i];
                          }
                          else {
                              malformedString();
                          }

                          if (++i < c) {
                              two = str[i];
                          }
                          else {
                              malformedString();
                          }

                          if (++i < c) {
                              three = str[i];
                          }
                          else {
                              malformedString();
                          }

                          if (++i < c) {
                              four = str[i];
                          }
                          else {
                              malformedString();
                          }

                          if (isHexa(one)   &&
                              isHexa(two)   &&
                              isHexa(three) &&
                              isHexa(four))
                          {
                              nextChar = (char)
                                  ((asciiToFourBits(one)   << 12) |
                                   (asciiToFourBits(two)   <<  8) |
                                   (asciiToFourBits(three) <<  4) |
                                   (asciiToFourBits(four)  <<  0));
                              break;
                          }
                          else {
                              malformedString();
                          }
                          break;
                      }

                      default: {
                          char up     = 0;
                          char middle = 0;
                          char low    = 0;

                          up = nextChar;
                          if (++i < c) {
                              middle = str[i];
                          }
                          else {
                              i--;
                          }

                          if (++i < c) {
                              low = str[i];
                          }
                          else {
                              i--;
                          }

                          if (up >= '0' && up <= '7' &&
                              middle >= '0' && middle <= '7' &&
                              low >= '0' && low <= '7') {
                              nextChar = (char)(((up - '0') << 6) |
                                                ((middle - '0') << 3) |
                                                (low - '0'));
                              break;
                          }
                          else {
                              malformedString();
                          }

                          break;
                      }
                    }

                    charBuf[charBufIndex++] = nextChar;
                    if (charBufIndex == charBuf.length) {
                        char newCharBuf[]  = new char[charBuf.length * 2];
                        System.arraycopy(charBuf, 0, newCharBuf, 0,
                                         charBuf.length);
                        charBuf = newCharBuf;
                    }
                }
                else {
                    charBuf[charBufIndex++] = ch;
                    if (charBufIndex == charBuf.length) {
                        char newCharBuf[]  = new char[charBuf.length * 2];
                        System.arraycopy(charBuf, 0, newCharBuf, 0,
                                         charBuf.length);
                        charBuf = newCharBuf;
                    }
                }
            }

            return new String(charBuf, 0, charBufIndex);
        }
        else {
            return new String(str);
        }
    }

    private final boolean isHexa (char c)
    {
        return ((c >= '0' && c <= '9') ||
                (c >= 'a' && c <= 'f') ||
                (c >= 'A' && c <= 'F'));
    }

    private final byte asciiToFourBits (char c)
    {
        if (c >= '0' && c <= '9') {
            return (byte)(c - '0');
        }
        if (c >= 'a' && c <= 'f') {
            return (byte)(c - 'a'+0xa);
        }
        /* We assume that char c makes sense... Caller should test it */
        return (byte)(c - 'A'+0xa);
    }

    private void malformedString () throws DeserializationException
    {
        int line = tokenGenerator.lineForLastToken();

        throw new DeserializationException(
            Fmt.S("%s%s:%s",
                  "Malformed string at line ",
                  Constants.getInteger(line),
                  new String(tokenGenerator.charsForLastToken())),
            line);
    }

    private void syntaxError () throws DeserializationException
    {
        int line = tokenGenerator.lineForLastToken();
        String lineStr = "[not available]";
        try {
            lineStr = String.valueOf(tokenGenerator.charsForLastToken());
        }
        catch (Throwable th) {
            // suppress it in case there is bad data and token string cannot be obtained
        }
        throw new DeserializationException(Fmt.S("Syntax error at line %s. Current token: \"%s\"", line,
            lineStr), line);
    }

    private void internalInconsistency (String type) throws
      DeserializationException {
        int line = tokenGenerator.lineForLastToken();

        throw new DeserializationException(
            Fmt.S("%s%s %s",
                  "Internal inconsistency exception. Please report this problem. ",
                  type, Constants.getInteger(line)), line);
    }

    private void unterminatedExpression () throws DeserializationException
    {
        int line = tokenGenerator.lineForLastToken();

        throw new DeserializationException(
            Fmt.S("Unterminated expression at line %s", line),
            line);
    }
}


text:
<link rel="import" href="../../bower_components/polymer/polymer.html">

<dom-module id="shokka-module-header">
  <template>

    <paper-material elevation="1">

[[title]]

[[desc]]

    </paper-material>
  </template>

</dom-module>

redpajama_set_name: RedPajamaGithub


text:
package org.jgroups.tests;

import org.jgroups.Global;
import org.jgroups.util.AgeOutCache;
import org.jgroups.util.TimeScheduler;
import org.jgroups.util.Util;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

/**
 * Test cases for AgeOutCache
 *
 * @author Bela Ban
 */
@Test(groups = Global.FUNCTIONAL,singleThreaded=true)
public class AgeOutCacheTest {

    @DataProvider(name="timerCreator")
    protected Object[][] timerCreator() {
        return Util.createTimer();
    }

    @Test(dataProvider="timerCreator")
    public void testExpiration(TimeScheduler timer) {
        AgeOutCache<Integer> cache=new AgeOutCache<Integer>(timer, 2000L,
                                                            new AgeOutCache.Handler<Integer>() {
                                                                public void expired(Integer key) {
                                                                    System.out.println(key + " expired");
                                                                }
                                                            });
        for(int i = 1; i <= 5; i++)
            cache.add(i);
        int size=cache.size();
        System.out.println("cache:\n" + cache);
        assert size == 5 : "size is " + size;

        for(int i=0; i < 30; i++) {
            if(cache.size() == 0)
                break;
            Util.sleep(1000);
        }
        System.out.println("cache:\n" + cache);
        size=cache.size();
        assert size == 0 : "size is " + size;
        timer.stop();
    }

    @Test(dataProvider="timerCreator")
    public void testRemoveAndExpiration(TimeScheduler timer) {
        AgeOutCache<Integer> cache = new AgeOutCache<Integer>(timer, 2000L);
        for (int i = 1; i <= 5; i++)
            cache.add(i);
        System.out.println("cache:\n" + cache);
        cache.remove(3);
        cache.remove(5);
        cache.remove(6); // not existent

        boolean correct_size=false;
        for(int i=0; i < 20; i++) {
            if(cache.size() == 3) {
                correct_size=true;
                break;
            }
            Util.sleep(500);
        }

        if(!correct_size) {
            System.out.println("cache:\n" + cache);
            assert cache.size() == 3 : "cache size should be 3 but is " + cache.size();
        }

        for(int i=0; i < 10; i++) {
            if(cache.size() == 0)
                break;
            Util.sleep(1000);
        }

        assert cache.size() == 0;
        timer.stop();
    }

    @Test(dataProvider="timerCreator")
    public void testContains(TimeScheduler timer) {
        AgeOutCache<Integer> cache = new AgeOutCache<Integer>(timer, 5000L);
        for (int i = 1; i <= 5; i++)
            cache.add(i);
        System.out.println("cache:\n" + cache);
        assert cache.contains(3);
        cache.remove(3);
        System.out.println("cache:\n" + cache);
        assert !cache.contains(3);
        cache.clear();
        assert cache.size() == 0;
        assert !cache.contains(4);
        timer.stop();
    }

    @Test(dataProvider="timerCreator")
    public void testGradualExpiration(TimeScheduler timer) {
        AgeOutCache<Integer> cache = new AgeOutCache<Integer>(timer, 5000L,
                                                              new AgeOutCache.Handler<Integer>() {
                                                                  public void expired(Integer key) {
                                                                      System.out.println(key + " expired");
                                                                  }
                                                              });
        for (int i = 1; i <= 10; i++) {
            cache.add(i);
            System.out.print(".");
            Util.sleep(1000);
        }
        System.out.println("\ncache:\n" + cache);
        int size = cache.size();
        assert size < 10 && size > 0 : " size was " + size + ", but should have been < 10 or > 0";
        timer.stop();
    }
}


text:
class Ore
	attr_accessor :size

	def initialize(size = 1)
		@size = size
	end
end


text:
package org.sakaiproject.metaobj.shared.model;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class InvalidUploadException extends OspException {
   protected final transient Log logger = LogFactory.getLog(getClass());

   private String fieldName;

   /**
    *
    */
   public InvalidUploadException(String fieldName) {
      this.fieldName = fieldName;
   }

   /**
    * @param cause
    */
   public InvalidUploadException(Throwable cause, String fieldName) {
      super(cause);
      this.fieldName = fieldName;
   }

   /**
    * @param message
    */
   public InvalidUploadException(String message, String fieldName) {
      super(message);
      this.fieldName = fieldName;
   }

   /**
    * @param message
    * @param cause
    */
   public InvalidUploadException(String message, Throwable cause, String fieldName) {
      super(message, cause);
      this.fieldName = fieldName;
   }

   public String getFieldName() {
      return fieldName;
   }

   public void setFieldName(String fieldName) {
      this.fieldName = fieldName;
   }
}


text:
using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.Xml;
using System.Xml.Serialization;

namespace BPMNET.Bpmn
{
    [GeneratedCode("xsd", "4.0.30319.1")]
    [Serializable()]
    [DebuggerStepThrough()]
    [DesignerCategory("code")]
    [XmlType(Namespace = "http://www.omg.org/spec/BPMN/20100524/MODEL")]
    [XmlRoot("exclusiveGateway", Namespace = "http://www.omg.org/spec/BPMN/20100524/MODEL", IsNullable = false)]
    public partial class tExclusiveGateway : tGateway
    {

        private string defaultField;

        [XmlAttribute(DataType = "IDREF")]
        public string @default
        {
            get
            {
                return defaultField;
            }
            set
            {
                defaultField = value;
            }
        }
    }
}


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Wave Recorder Private API: src/recorder/private/encoders/raw_encoder.h File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

Wave Recorder Private API

src

recorder

private

encoders

Data Structures |
Typedefs |
Functions

raw_encoder.h File Reference

#include <stdio.h>

Go to the source code of this file.

Data Structures

struct  	WaveRawEncoder

Typedefs

typedef struct WaveRawEncoder 	WaveRawEncoder

Functions

WaveError 	wave_raw_encoder_init (void *rawEncoder, const char *filePath, float fs, float numChannels)

WaveError 	wave_raw_encoder_write (void *rawEncoder, int numChannels, int numFrames, float *buffer, int *numBytesWritten)

WaveError 	wave_raw_encoder_stop (void *rawEncoder)

Typedef Documentation

◆ WaveRawEncoder

          typedef struct WaveRawEncoder  WaveRawEncoder

Writes raw PCM samples to disk.

<address class="footer">
Generated by

 1.8.13
</address>


text:
namespace SimpleMVC.App.BindingModels
{
    public class LoginUserBindingModel
    {
        public string Identifyer { get; set; }
        public string Password { get; set; }
    }
}


text:
extern mailbox_t mb_start, mb_done;
//extern cyg_handle_t mb_start_handle, mb_done_handle;

void* sort8k_entry( void *data )
{
#ifdef USE_ECOS
    void *ptr;
    unsigned int thread_number = ( unsigned int ) data;

    while ( 1 ) {
        // get pointer to next chunk of data
        ptr = cyg_mbox_get( mb_start_handle );
        // sort it
        bubblesort( ( unsigned int * ) ptr, N );
        // return
        cyg_mbox_put( mb_done_handle, ( void * ) 23 );                         // return any value
    }
#else
    void *ptr;
    //unsigned int tid = (unsigned int)hthread_self();
    //unsigned int thread_number = ( unsigned int ) data;

    while ( 1 ) {
        // get pointer to next chunk of data
        ptr = (void*)mailbox_read( &mb_start );
        // sort it
        bubblesort( ( unsigned int * ) ptr, N );
        // return
        mailbox_write( &mb_done, (void*)23 ); // return any value
    }
#endif
    return NULL;
}


text:
#if defined(MBED_CONF_RTOS_PRESENT)
#include "mbed.h"
#include "TCPSocket.h"
#include "greentea-client/test_env.h"
#include "unity/unity.h"
#include "utest.h"
#include "tcp_tests.h"

using namespace utest::v1;

void TCPSOCKET_SETSOCKOPT_KEEPALIVE_VALID()
{
    SKIP_IF_TCP_UNSUPPORTED();
    TCPSocket sock;
    TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock.open(NetworkInterface::get_default_instance()));
    int32_t seconds = 7200;

    int ret = sock.setsockopt(NSAPI_SOCKET, NSAPI_KEEPALIVE, &seconds, sizeof(int));

    if (ret == NSAPI_ERROR_UNSUPPORTED) {
        TEST_IGNORE_MESSAGE("NSAPI_KEEPALIVE option not supported");
        sock.close();
        return;
    }

    TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, ret);
    SocketAddress address;
    TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, NetworkInterface::get_default_instance()->gethostbyname(ECHO_SERVER_ADDR, &address));
    address.set_port(9);
    TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock.connect(address));
    // LWIP stack does not support getsockopt so the part below is commented out
    //    int32_t optval;
    //    unsigned int optlen;
    //    TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock.getsockopt(NSAPI_SOCKET, NSAPI_KEEPALIVE, &optval, &optlen));
    //    TEST_ASSERT_EQUAL(optlen, sizeof(seconds));
    //    TEST_ASSERT_EQUAL(optval, seconds);
    TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock.close());
}
#endif // defined(MBED_CONF_RTOS_PRESENT)


text:
package xworker.swt.xwidgets.clock;

import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Path;
import org.eclipse.swt.graphics.Transform;
import org.xmeta.ActionContext;
import org.xmeta.Thing;

public class AnalogClockDrawer extends AbstractDrawer implements ClockDrawer {
	public AnalogClockDrawer(Thing thing, ActionContext actionContext) {
		super(thing, actionContext);
	}

	@Override
	public void drawClock(Date date, float x, float y, float width, float height,  GC gc) {
		// Hard code the padding at 10 pixels for now
		float padding = 10;

		// float radius
		double r = Math.min(width, height)/2-padding;

		// Center point.
		float cX = x + width / 2;
		float cY = y + height / 2;

		//Tick Styles
		int tickLen = 7;  // short tick
		int medTickLen = 14;  // at 5-minute intervals
		int longTickLen = 21; // at the quarters
		gc.setBackground(gc.getDevice().getSystemColor(SWT.COLOR_WHITE));
		gc.fillRectangle((int) x, (int) y, (int) width, (int) height);
		gc.setAntialias(SWT.ON);
		Color tickColor = new Color(gc.getDevice(), 0x00, 0x00, 0x00);
		Color hourAreaClolor = new Color(gc.getDevice(), 0xff, 0x51, 0x51);
		Color minuteAreaClolor = new Color(gc.getDevice(), 0x84, 0xc1, 0xff);
		Color secondAreaClolor = new Color(gc.getDevice(), 0x93, 0xff, 0x93);
		Font textFont = new Font(gc.getDevice(), new FontData("", 14, SWT.BOLD));
		Path secondHand = new Path(gc.getDevice());
		Path minuteHand = new Path(gc.getDevice());
		Path hourHand = new Path(gc.getDevice());
		Path ticksPath = new Path(gc.getDevice());
		Transform tr = new Transform(gc.getDevice());

		boolean showArea = this.isShowArea();
		boolean showSecond = this.isShowSecond();
		boolean showMinute = this.isShowMinute();
		boolean showHour = this.isShowHour();
		boolean showAmPm = this.isShowAmPm();

		try {
			//------------------------------显示表盘-----------------------------
			// Draw a tick for each "second" (1 through 60)
			for ( int i=1; i<= 60; i++){
			    // default tick length is short
			    int len = tickLen;
			    if ( i % 15 == 0 ){
			        // Longest tick on quarters (every 15 ticks)
			        len = longTickLen;
			    } else if ( i % 5 == 0 ){
			        // Medium ticks on the '5's (every 5 ticks)
			        len = medTickLen;
			    }

			    double di = (double)i; // tick num as double for easier math

			    // Get the angle from 12 O'Clock to this tick (radians)
			    double angleFrom12 = di/60.0*2.0*Math.PI;

			    // Get the angle from 3 O'Clock to this tick
			        // Note: 3 O'Clock corresponds with zero angle in unit circle
			        // Makes it easier to do the math.
			    double angleFrom3 = Math.PI/2.0-angleFrom12;

			    // Move to the outer edge of the circle at correct position
			    // for this tick.
			    ticksPath.moveTo(
			            (float)(cX+Math.cos(angleFrom3)*r),
			            (float)(cY-Math.sin(angleFrom3)*r)
			    );

			    // Draw line inward along radius for length of tick mark
			    ticksPath.lineTo(
			            (float)(cX+Math.cos(angleFrom3)*(r-len)),
			            (float)(cY-Math.sin(angleFrom3)*(r-len))
			    );
			}

			// Draw the full shape onto the graphics context.
			gc.setLineJoin(SWT.JOIN_ROUND);
			gc.setLineWidth(2);
			gc.setForeground(tickColor);
			gc.drawOval((int) ( cX - r), (int) (cY - r), (int) r * 2,(int)  r * 2);
			gc.drawPath(ticksPath);
			//gc.setLineCap(SWT.CAP);

			gc.setForeground(gc.getDevice().getSystemColor(SWT.COLOR_BLACK));
			gc.setFont(textFont);

			//----------------------------显示指针-------------------------
			gc.setBackground(gc.getDevice().getSystemColor(SWT.COLOR_BLACK));
			gc.fillArc((int) cX-8, (int) cY-8, 16, 16, 0, 360);
			// Calculate the angle of the second hand
			Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
			calendar.setTimeInMillis(date.getTime());

			//secondHand.moveTo((float)cX, (float)cY);
			//secondHand.moveTo(0, longTickLen / 2 );
			secondHand.moveTo(0, 0);
	        secondHand.lineTo((float)0, (float)(r-tickLen));

			//Shape translatedSecondHand = secondHand.createTransformedShape(Transform.makeTranslation(0f, 5, 0));

	        double second = (double)(calendar.get(Calendar.SECOND));
	        double secondAngle = second/60.0*360 - 180;//*Math.PI;

	        //显示秒针划过的区域
	        if(showArea && showSecond) {
		        gc.setBackground(secondAreaClolor);
		        float secondWidth = (float)((r-medTickLen));
		        gc.fillArc((int) (cX - secondWidth), (int) (cY - secondWidth),
		        		(int) (2 * secondWidth), (int) (2 * secondWidth), (int) (90), (int)-(secondAngle + 180));
	        }

	        double minute = (double)(calendar.get(Calendar.MINUTE)) +
	                (double)(calendar.get(Calendar.SECOND))/60.0;
	        double minuteAngle = minute/60.0*360 - 180;
	        //显示分针划过的区域
	        if(showArea && showMinute) {
	        	gc.setBackground(minuteAreaClolor);
		        float minuteWidth = (float)((r-medTickLen) * 0.9);
		        gc.fillArc((int) (cX - minuteWidth), (int) (cY - minuteWidth),
		        		(int) (2 * minuteWidth), (int) (2 * minuteWidth), (int) (90), (int) -(minuteAngle + 180));
	        }

	        double hour = (double)(calendar.get(Calendar.HOUR_OF_DAY)%12) +
	                (double)(calendar.get(Calendar.MINUTE))/60.0;
	        double angle = (hour/12.0)*360 - 180 ;

	        //显示时针划过的区域
	        if(showArea && showHour) {
		        gc.setBackground(hourAreaClolor);
		        float hourWidth = (float)((r-longTickLen)*0.75);
		        gc.fillArc((int) (cX - hourWidth), (int) (cY - hourWidth),
		        		(int) (2 * hourWidth), (int) (2 * hourWidth), (int) 90,  (int) -(angle + 180));
		    }

	        gc.setBackground(gc.getDevice().getSystemColor(SWT.COLOR_BLACK));

	        tr.translate(cX, cY);
	        if(showSecond) {
	        	tr.rotate((float) secondAngle);
	        	gc.setTransform(tr);
	        	gc.drawPath(secondHand);
	        	tr.rotate((float) -secondAngle);
	        }

	        if(showMinute) {
		        minuteHand.moveTo((float)0, (float)0);
		        minuteHand.lineTo((float)0+4, (float)0);
		        minuteHand.lineTo((float)0+1, (float)((r-medTickLen) * 0.9));
		        minuteHand.lineTo((float)0-1, (float)((r-medTickLen) * 0.9));
		        minuteHand.lineTo((float)0-4, (float)0);
		        minuteHand.close();

		        //Shape translatedMinuteHand = minuteHand.createTransformedShape(Transform.makeTranslation(0f, 5, 0));

		        tr.rotate((float)minuteAngle);
		        gc.setTransform(null);
		        gc.setTransform(tr);

		        //g.setColor(0x000000);
		        gc.fillPath(minuteHand);
		        tr.rotate((float) -minuteAngle);
	        }

	        if(showHour) {
		        hourHand.moveTo((float)0, (float)0);
		        hourHand.lineTo((float)0+6, (float)0);
		        hourHand.lineTo((float)0+2, (float)((r-longTickLen)*0.75));
		        hourHand.lineTo((float)0-2, (float)((r-longTickLen)*0.75));
		        hourHand.lineTo((float)0-6, (float)0);
		        hourHand.close();

		        tr.rotate((int) angle);
		        gc.setTransform(null);

		        gc.setTransform(tr);
		        gc.fillPath(hourHand);
	        }

	        gc.setTransform(null);

	        //-----------------------显示表盘上的数字---------------------
	        gc.setBackground(gc.getDevice().getSystemColor(SWT.COLOR_WHITE));
	        gc.setAlpha(255);
	        int charWidth = gc.getFontMetrics().getAverageCharWidth();
		    int charHeight = gc.getFontMetrics().getHeight();
	        for ( int i=1; i<=12; i++){
			    // Calculate the string width and height so we can center it properly
			    String numStr = ""+i;

			    double di = (double)i;  // number as double for easier math

			    // Calculate the position along the edge of the clock where the number should
			    // be drawn
			     // Get the angle from 12 O'Clock to this tick (radians)
			    double angleFrom12 = di/12.0*2.0*Math.PI;

			    // Get the angle from 3 O'Clock to this tick
			        // Note: 3 O'Clock corresponds with zero angle in unit circle
			        // Makes it easier to do the math.
			    double angleFrom3 = Math.PI/2.0-angleFrom12;

			    // Get diff between number position and clock center
			    int tx = (int)(Math.cos(angleFrom3)*(r-longTickLen - 10));
			    int ty = (int)(-Math.sin(angleFrom3)*(r-longTickLen -10));

					    // Translate the graphics context by delta between clock center and
			    // number position

			    // Draw number at clock center.
			    if(numStr.length() == 1) {
			    	gc.drawString(numStr, (int)(tx + cX -charWidth/2), (int)(cY + ty-charHeight/2), true);
			    }else {
			    	gc.drawString(numStr, (int)(tx + cX -charWidth), (int)(cY + ty-charHeight/2), true);
			    }

			    // Undo translation
			}

	        //-------------------------------画上午和下午------------------------------
	        if(showAmPm) {
	        	String amPm = null;
	        	if(Calendar.AM == calendar.get(Calendar.AM_PM)){
	        		amPm = "AM";
	        	}else {
	        		amPm = "PM";
	        	}

	        	gc.drawString(amPm, (int)(cX + r / 2 - charWidth), (int)(cY  -charHeight/2), true);
	        }

		}finally {
			tickColor.dispose();
			hourAreaClolor.dispose();
			minuteAreaClolor.dispose();
			secondAreaClolor.dispose();
			ticksPath.dispose();
			textFont.dispose();
			secondHand.dispose();
			minuteHand.dispose();
			hourHand.dispose();
			tr.dispose();
		}
	}

	public static AnalogClockDrawer create(ActionContext actionContext) {
		Thing self = actionContext.getObject("self");
		return new AnalogClockDrawer(self, actionContext);
	}
}


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

<TITLE>
DeviceType (Authorize.Net Java SDK)
</TITLE>

<META NAME="date" CONTENT="2011-07-18">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | ENUM CONSTANTS | FIELD | METHOD

DETAIL: ENUM CONSTANTS | FIELD | METHOD

net.authorize.aim.cardpresent

Enum DeviceType

java.lang.Object
  java.lang.Enum<DeviceType>
      net.authorize.aim.cardpresent.DeviceType

All Implemented Interfaces:
java.io.Serializable, java.lang.Comparable<DeviceType>

public enum DeviceType
extends java.lang.Enum<DeviceType>

DeviceType is used for Card Present transactions.

Enum Constant Summary

AIRPAY

DIAL_TERMINAL

ELECTRONIC_CASH_REGISTER

PERSONAL_COMPUTER_BASED_TERMINAL

SELF_SERVICE_TERMINAL

UNATTENDED

UNKNOWN

VIRTUAL_TERMINAL

WEBSITE

WIRELESS_POS

Method Summary

static DeviceType
findByValue(java.lang.String value)

          Lookup a DeviceType by it's value.

 java.lang.String
getValue()

          Return the DeviceType value.

static DeviceType
valueOf(java.lang.String name)

          Returns the enum constant of this type with the specified name.

static DeviceType[]
values()

          Returns an array containing the constants of this enum type, in
the order they are declared.

Methods inherited from class java.lang.Enum

clone, compareTo, equals, finalize, getDeclaringClass, hashCode, name, ordinal, toString, valueOf

Methods inherited from class java.lang.Object

getClass, notify, notifyAll, wait, wait, wait

Enum Constant Detail

UNKNOWN

public static final DeviceType UNKNOWN

UNATTENDED

public static final DeviceType UNATTENDED

SELF_SERVICE_TERMINAL

public static final DeviceType SELF_SERVICE_TERMINAL

ELECTRONIC_CASH_REGISTER

public static final DeviceType ELECTRONIC_CASH_REGISTER

PERSONAL_COMPUTER_BASED_TERMINAL

public static final DeviceType PERSONAL_COMPUTER_BASED_TERMINAL

AIRPAY

public static final DeviceType AIRPAY

WIRELESS_POS

public static final DeviceType WIRELESS_POS

WEBSITE

public static final DeviceType WEBSITE

DIAL_TERMINAL

public static final DeviceType DIAL_TERMINAL

VIRTUAL_TERMINAL

public static final DeviceType VIRTUAL_TERMINAL

Method Detail

values

public static DeviceType[] values()

Returns an array containing the constants of this enum type, in
the order they are declared.  This method may be used to iterate
over the constants as follows:

for (DeviceType c : DeviceType.values())
    System.out.println(c);

Returns:
an array containing the constants of this enum type, in
the order they are declared

valueOf

public static DeviceType valueOf(java.lang.String name)

Returns the enum constant of this type with the specified name.
The string must match exactly an identifier used to declare an
enum constant in this type.  (Extraneous whitespace characters are
not permitted.)

Parameters:
name - the name of the enum constant to be returned.

Returns:
the enum constant with the specified name

Throws:

java.lang.IllegalArgumentException - if this enum type has no constant
with the specified name

java.lang.NullPointerException - if the argument is null

getValue

public java.lang.String getValue()

Return the DeviceType value.

Returns:
the value

findByValue

public static DeviceType findByValue(java.lang.String value)

Lookup a DeviceType by it's value.

Parameters:
value -

Returns:
Returns a DeviceType if a value match is found.

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | ENUM CONSTANTS | FIELD | METHOD

DETAIL: ENUM CONSTANTS | FIELD | METHOD


text:
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

package org.apache.impala.testutil;

import org.apache.impala.authorization.AuthorizationConfig;
import org.apache.impala.catalog.Catalog;
import org.apache.impala.common.ImpalaException;
import org.apache.impala.service.BackendConfig;
import org.apache.impala.service.CatalogOpExecutor;
import org.apache.impala.service.Frontend;
import org.apache.impala.thrift.TBackendGflags;
import org.apache.impala.thrift.TCatalogUpdateResult;
import org.apache.impala.thrift.TCopyTestCaseReq;
import org.apache.impala.thrift.TDdlExecResponse;
import org.apache.impala.thrift.TQueryCtx;
import org.apache.impala.thrift.TQueryOptions;

/**
 * A util class that loads a given testcase file into an in-memory Catalog
 * and runs EXPLAIN on the testcase query statement. The catalog is backed by a
 * transient HMS instanced based on derby DB.
 *
 * Runs in a standalone mode without having to start the Impala cluster.
 * Expects the testcase path as the only argument.
 * Ex: ...PlannerTestCaseLoader hdfs:///tmp/impala-testcase-data-9642a6f6...
 *
 * Full command example using maven-exec plugin (for an Impala DEV environment):
 *
 * mvn install exec:java -Dexec.classpathScope="test" \
 *    -Dexec.mainClass="org.apache.impala.testutil.PlannerTestCaseLoader" \
 *    -Dexec.args="/tmp/impala-testcase-data-9642a6f6-6a0b-48b2-a61f-f7ce55b92fee"
 *
 * Running through Maven is just for convenience. Can also be invoked directly using the
 * Java binary by setting appropriate classpath.
 *
 */
public class PlannerTestCaseLoader implements AutoCloseable {

  private final CatalogOpExecutor catalogOpExecutor_;
  private final ImpaladTestCatalog catalog_;
  private final Frontend frontend_;

  public PlannerTestCaseLoader() throws ImpalaException {
    AuthorizationConfig config = AuthorizationConfig.createAuthDisabledConfig();
    catalog_ = new ImpaladTestCatalog(
        CatalogServiceTestCatalog.createTransientTestCatalog());
    frontend_ = new Frontend(config, catalog_);
    catalogOpExecutor_ = new CatalogOpExecutor(catalog_.getSrcCatalog());
  }

  public Catalog getSrcCatalog() { return catalog_.getSrcCatalog(); }

  /**
   * Loads the testcase from a given path and returns the EXPLAIN string for the
   * testcase query statement.
   */
  public String loadTestCase(String testCasePath) throws Exception {
    String stmt = catalogOpExecutor_.copyTestCaseData(new TCopyTestCaseReq(testCasePath),
        new TDdlExecResponse(new TCatalogUpdateResult()));
    TQueryCtx queryCtx = TestUtils.createQueryContext(
        new TQueryOptions().setPlanner_testcase_mode(true));
    queryCtx.client_request.setStmt(stmt);
    return frontend_.getExplainString(queryCtx);
  }

  @Override
  public void close() {
    getSrcCatalog().close();
  }

  public static void main(String[] args) throws Exception {
    if (args.length != 1) {
      throw new IllegalArgumentException(String.format("Incorrect number of args. " +
          "Expected 1 argument, found %d. Valid usage: PlannerTestCaseLoader " +
          "<testcase path>", args.length));
    }
    try (PlannerTestCaseLoader testCaseLoader = new PlannerTestCaseLoader()) {
      System.out.println(testCaseLoader.loadTestCase(args[0]));
    }
    System.exit(0);
  }
}


text:
"""
S-objects (or selector-objects) can be used to select some nodes of an AST
depending on various constraints. Three common types of selections involve:

  1. Selecting based on the type of the node.
  2. Selecting based on the attributes of the node.
  3. Selecting based on some custom criteria, i.e, whether a function f,
     returns True for the given node.

The S-Object for each of the cases can be instantiated as follows:

  >>> import redhawk.common.selector as S
  >>> s1 = S(node_type = 'DefineFunction')
  >>> s2 = S(name = 'foobar')
  >>> s3 = S(function = lambda x: len(x.GetChildren()) > 3)

Selector-objects are evaluted by calling it with a tree or list of trees. (The
__call__ method of the S-objects have been overriden).

  >>> # Get trees t1, t2, t3
  >>> s1(t1) # Select nodes in t1 which have are of type DefineFunction
  >>> s2([t1, t2, t3]) # Select nodes where an attribute name has attribute foobar.

Evaluating an s-object returns a (possibly empty) iterator to the selected
nodes.

Selector-objects objects can be combined. We chose styles similar to the CSS3
combinators (http://www.w3.org/TR/css3-selectors/#combinators):

  1. s1.And(s2) returns a NEW s-object that selects a node only if BOTH s1,
    and s2 select the node.

  2. s1.Or(s2) returns a NEW new s-object that selects a node if EITHER s1 or s2
     select the node.

  3. s1.HasChild(s2) returns a NEW s-object that selects a node, n, only if
        * s1 selects the node
        * s2 selects a child of the node.

  4. s1.HasDescendant(s2) returns a NEW s-object that selects a node, n, only if
        * s1 selects the node
        * s2 selects some descendant of the node.

  5. s1.HasParent(s2) returns a NEW s-object that selects a node, n, only if
        * s1 selects the node, n
        * s2 selects the parent of the node, n.parent.

  6. s1.HasAncestor(s2) returns a NEW s-object that selects a node, n, only if
        * s1 selects the node, n
        * s2 selects some ancestor of the node, n.

Example:

Find all private functions (those that start with __), of all classes
that inherits from some particular class, 'Foo'

  >>> import selector as S
  >>> private_function = S.S(node_type = 'DefineFunction',
                             function = lambda x: x.name.name[:2] == '__')
  >>> inherited_classes = S.S(node_type = 'DefineClass',
                              function = lambda x: 'Foo' in x.inherits)
  >>> required_functions = private_function.HasParent(inherited_classes)
  >>> required_functions(tree)

(Note that the HasDescendant selector is a little inefficient right now. This
should be fixed in the future).

(See _selector.py for implementation details).
"""

from . import _selector

# Shorthand use of the selector API.
class S:
  def __init__(self
              ,selector_function = None
              ,node_type = None
              ,function = None
              ,attr_matcher = None
              ,match_only_common_attributes = True
              ,**attrs):
    """ Create a selector object that selects based on the criteria passed.

    * node_type takes a string, or a class, and checks if the node type matches.
    * function takes a boolean function, and selects if function(node) is true.
    * attrs is used to match the attributes of the node at hand.

    If match_only_common_attributes is True, we match only the common attributes
    passed in, and it is considered a failure only when some attribute does not
    match, or there are no common attributes. If false, we match all attributes,
    and the absence of an attribute would mean failure.

    In case a function, f, is passed and match_only_common_attributes is True,
    we simply do not match a node when an AttributeError is thrown when f is
    applied on the node. If match_only_common_attributes is False, we raise the
    AttributeError, and the program is expected to handle it (or comes to a
    grinding halt!)

    If `attr_matcher` is passed, a call to attr_matcher(node_attribute,
    argument) is used to check for equality between the attribute value passed
    in, and the attribute value in the node.

    If more than one criteria is passed, all the criteria have to be satisfied for
    a node to be selected.

    (A Selector function as described in the _selector module can also be
    passed. For more help, see the Selector function in the _selector module)."""

    if selector_function:
      self.selector = selector_function
    else:
      self.selector = _selector.Selector(
                         node_type = node_type
                        ,function = function
                        ,attr_matcher = attr_matcher
                        ,match_only_common_attributes = match_only_common_attributes,
                        **attrs)
    return

  def __lshift__(self, selector):
    """ A << B is A.HasAncestor(B)"""
    return self.HasAncestor(selector)

  def __rshift__(self, selector):
    """ A >> B is A.HasDescendant(B) """
    return self.HasDescendant(selector)

  def __call__(self, tree):
    """ Calls _selector.RunSelector on a tree (or list of trees) with the
    given selector."""
    return _selector.RunSelector(self.selector, tree)

  def Apply(self, trees):
    """ This applies the selector on a LIST of `trees`. This method returns an
    For each resulting node, n, a pair is returned:

      (n, tree in `trees` from which n was selected)

    This method, thus returns an iterator to a pair of trees.

    Example: Suppose t1 contains two nodes, n1, n2 that match some selector,
    s. And t2 contains three nodes, m1, m2, m3, that match the selector, s.

    Then s.Apply([t1, t2]) returns an *iterator* to the *set*:

      (n1, t1), (n2, t1), (m1, t2), (m2, t2), (m2, t3)

    The order of nodes is NOT guaranteed."""

    assert(type(trees) is list)
    for t in trees:
      for n in self(t):
        yield (n, t)

  def And(self, s):
    """ Returns a NEW selector that requires the current s-object be valid,
    and the `s` s-object also to be valid.

    See the And function in the module for more help."""
    return S(_selector.And(self.selector, s.selector))

  def Or(self, s):
    """ Returns a NEW selector that requires the current s-object be valid,
    or the `s` s-object to be valid.

    See the Or function in the module for more help."""
    return S(_selector.Or(self.selector, s.selector))

  def HasChild(self, s):
    """ Returns a NEW selector that requires the current s-object be valid,
    and `s` s-object to be valid on one of its children.

    See the HasChild function in the module for more help."""
    return S(_selector.HasChild(self.selector, s.selector))

  def HasDescendant(self, s):
    """ Returns a NEW selector that requires the current s-object be valid,
    and the `s` s-object to be valid on one of its parents.

    See the HasDescendant function in the module for more help."""
    return S(_selector.HasDescendant(self.selector, s.selector))

  def HasParent(self, s):
    """ Returns a NEW selector that requires the current s-object be valid,
    and the `s` s-object to be valid on one of its parents.

    See the HasParent function in the module for more help."""
    return S(_selector.HasParent(self.selector, s.selector))

  def HasAncestor(self, s):
    """ Returns a NEW selector that requires the current s-object be valid,
    and the `s` s-object to be valid on one of its ancestors.

    See the HasAncestor function in the module for more help."""
    return S(_selector.HasAncestor(self.selector, s.selector))


text:
from PIL import Image
from six import moves, string_types

TRANSFORM_AXIS = {
    Image.EXTENT: (0, 1, 0, 1),
    Image.AFFINE: (None, None, 0, None, None, 1),
    Image.QUAD: (0, 1, 0, 1, 0, 1, 0, 1),
    Image.PERSPECTIVE: (None, None, None, None, None, None, None, None),
    # Image.MESH: ???
}

class Transform(list):

    def __init__(self, spec, image_size=None):

        super(Transform, self).__init__(spec)

        self.flag = getattr(Image, self[0].upper())
        try:
            axis = (None, 0, 1) + TRANSFORM_AXIS[self.flag]
        except KeyError:
            raise ValueError('unknown transform %r' % self[0])

        if len(self) != len(axis):
            raise ValueError('expected %d transform values; got %d' % (len(axis), len(self)))

        for i in moves.range(1, len(self)):
            v = self[i]
            if isinstance(v, string_types):
                if v[-1:] in ('%', 'p'): # Percentages.
                    if axis[i] is None:
                        raise ValueError('unknown dimension for %s value %d' % (self[0], i))
                    if image_size is None:
                        raise ValueError('no image size with relative transform')
                    self[i] = image_size[axis[i]] * float(v[:-1]) / 100
                else:
                    self[i] = float(v)

        # Finalize the size.
        if not self[1] or not self[2]:
            if not image_size:
                ValueError('no image size or transform size')
        self[1] = int(self[1] or image_size[0])
        self[2] = int(self[2] or image_size[1])

    @property
    def size(self):
        return self[1], self[2]

    def apply(self, image):
        return image.transform(
            (int(self[1] or image.size[0]), int(self[2] or image.size[1])),
            self.flag,
            self[3:],
            Image.BILINEAR,
        )


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE427_Uncontrolled_Search_Path_Element__char_console_51a.c
Label Definition File: CWE427_Uncontrolled_Search_Path_Element.label.xml
Template File: sources-sink-51a.tmpl.c
*/
/*
 * @description
 * CWE: 427 Uncontrolled Search Path Element
 * BadSource: console Read input from the console
 * GoodSource: Use a hardcoded path
 * Sink:
 *    BadSink : Set the environment variable
 * Flow Variant: 51 Data flow: data passed as an argument from one function to another in different source files
 *
 * */

#include "std_testcase.h"

#include <wchar.h>
#ifdef _WIN32
#define NEW_PATH "%SystemRoot%\\system32"
#define PUTENV _putenv
#else
#define NEW_PATH "/bin"
#define PUTENV putenv
#endif

#ifndef OMITBAD

/* bad function declaration */
void CWE427_Uncontrolled_Search_Path_Element__char_console_51b_badSink(char * data);

void CWE427_Uncontrolled_Search_Path_Element__char_console_51_bad()
{
    char * data;
    char dataBuffer[250] = "PATH=";
    data = dataBuffer;
    {
        /* Read input from the console */
        size_t dataLen = strlen(data);
        /* if there is room in data, read into it from the console */
        if (250-dataLen > 1)
        {
            /* POTENTIAL FLAW: Read data from the console */
            if (fgets(data+dataLen, (int)(250-dataLen), stdin) != NULL)
            {
                /* The next few lines remove the carriage return from the string that is
                 * inserted by fgets() */
                dataLen = strlen(data);
                if (dataLen > 0 && data[dataLen-1] == '\n')
                {
                    data[dataLen-1] = '\0';
                }
            }
            else
            {
                printLine("fgets() failed");
                /* Restore NUL terminator if fgets fails */
                data[dataLen] = '\0';
            }
        }
    }
    CWE427_Uncontrolled_Search_Path_Element__char_console_51b_badSink(data);
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* good function declarations */
void CWE427_Uncontrolled_Search_Path_Element__char_console_51b_goodG2BSink(char * data);

/* goodG2B uses the GoodSource with the BadSink */
static void goodG2B()
{
    char * data;
    char dataBuffer[250] = "PATH=";
    data = dataBuffer;
    /* FIX: Set the path as the "system" path */
    strcat(data, NEW_PATH);
    CWE427_Uncontrolled_Search_Path_Element__char_console_51b_goodG2BSink(data);
}

void CWE427_Uncontrolled_Search_Path_Element__char_console_51_good()
{
    goodG2B();
}

#endif /* OMITGOOD */

/* Below is the main(). It is only used when building this testcase on
 * its own for testing or for building a binary to use in testing binary
 * analysis tools. It is not used when compiling all the testcases as one
 * application, which is how source code analysis tools are tested.
 */

#ifdef INCLUDEMAIN

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    CWE427_Uncontrolled_Search_Path_Element__char_console_51_good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    CWE427_Uncontrolled_Search_Path_Element__char_console_51_bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
using System;

namespace Platform.Xml.Serialization
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface | AttributeTargets.Field | AttributeTargets.Property, Inherited = true, AllowMultiple = true)]
	public abstract class XmlApproachAttribute
		: XmlSerializationAttribute
	{
		public virtual string Name { get; set; }
		public virtual bool SerializeUnattribted { get; set; }
		public virtual bool MakeNameLowercase { get; set; }
		public virtual bool UseNameFromAttributedType { get; set; }
		public virtual string Namespace { get; set; }
		public virtual Type Type { get; set; }
		public virtual Type SerializerType { get; set; }
		public virtual bool SerializeIfNull { get; set; }

		protected XmlApproachAttribute()
		{
			Namespace = "";
			MakeNameLowercase = false;
			Name = "";
		}

		protected XmlApproachAttribute(Type type)
			: this("", type)
		{
		}

		protected XmlApproachAttribute(string name)
		{
			Namespace = "";
			MakeNameLowercase = false;
			Name = name;
		}

		protected XmlApproachAttribute(string name, Type type)
		{
			Namespace = "";
			MakeNameLowercase = false;
			Type = type;
			Name = name;
		}

		protected XmlApproachAttribute(string ns, string name, Type type)
		{
			MakeNameLowercase = false;
			Type = type;
			Name = name;
			Namespace = ns;
		}
	}
}


text:
/**
 * Represents information about a LOL champion
 */
package lolwrapper;

/**
 * @author Cameron
 *
 */
public class Champion {

	private boolean active;
	private int attackRank;
	private boolean botEnabled;
	private boolean botMmEnabled;
	private int defenseRank;
	private int difficultyRank;
	private boolean freeToPlay;
	private long id;
	private int magicRank;
	private String name;
	private boolean rankPlayEnabled;

	public String getName()
	{
		return name;
	}

	public boolean isActive() {
		return active;
	}

	public void setActive(boolean active) {
		this.active = active;
	}

	public int getAttackRank() {
		return attackRank;
	}

	public void setAttackRank(int attackRank) {
		this.attackRank = attackRank;
	}

	public boolean isBotEnabled() {
		return botEnabled;
	}

	public void setBotEnabled(boolean botEnabled) {
		this.botEnabled = botEnabled;
	}

	public boolean isBotMmEnabled() {
		return botMmEnabled;
	}

	public void setBotMmEnabled(boolean botMmEnabled) {
		this.botMmEnabled = botMmEnabled;
	}

	public int getDefenseRank() {
		return defenseRank;
	}

	public void setDefenseRank(int defenseRank) {
		this.defenseRank = defenseRank;
	}

	public int getDifficultyRank() {
		return difficultyRank;
	}

	public void setDifficultyRank(int difficultyRank) {
		this.difficultyRank = difficultyRank;
	}

	public boolean isFreeToPlay() {
		return freeToPlay;
	}

	public void setFreeToPlay(boolean freeToPlay) {
		this.freeToPlay = freeToPlay;
	}

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public int getMagicRank() {
		return magicRank;
	}

	public void setMagicRank(int magicRank) {
		this.magicRank = magicRank;
	}

	public boolean isRankPlayEnabled() {
		return rankPlayEnabled;
	}

	public void setRankPlayEnabled(boolean rankPlayEnabled) {
		this.rankPlayEnabled = rankPlayEnabled;
	}

	public void setName(String name) {
		this.name = name;
	}

}


text:
package org.slipchansky.lingualeo.data;

import java.util.Date;
import java.util.List;

public class WordInfo {

	public String word;
	public Integer training_count;
	public Date created_at;
	public Date last_updated_at;
	public String sound_url;

	public List<String> translations;

	public WordInfo(String word, Integer training_count, Date created_at,
			Date last_updated_at, String sound_url, List<String> translations) {
		super();
		this.word = word;
		this.training_count = training_count;
		this.created_at = created_at;
		this.last_updated_at = last_updated_at;
		this.sound_url = sound_url;
		this.translations = translations;
	}

	@Override
	public String toString() {
		return "WordInfo [word=" + word + ", translations=" + translations
				+ "]";
	}

}


text:
package org.woltage.irssiconnectbot;

import org.woltage.irssiconnectbot.util.HelpTopicView;

import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ViewFlipper;

/**
 * Show a series of wizard-like steps to the user, which might include an EULA,
 * program credits, and helpful hints.
 *
 * @author jsharkey
 */
public class WizardActivity extends Activity {
	protected ViewFlipper flipper = null;
	private Button next, prev;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_wizard);

		this.flipper = (ViewFlipper) findViewById(R.id.wizard_flipper);

		// inflate the layout for EULA step
		LayoutInflater inflater = LayoutInflater.from(this);
		this.flipper.addView(inflater.inflate(R.layout.wiz_eula, this.flipper, false));

		// Add a view for each help topic we want the user to see.
		String[] topics = getResources().getStringArray(R.array.list_wizard_topics);
		for (String topic : topics) {
			flipper.addView(new HelpTopicView(this).setTopic(topic));
		}

		next = (Button)this.findViewById(R.id.action_next);
		next.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if(isLastDisplayed()) {
					// user walked past end of wizard, so return okay
					WizardActivity.this.setResult(Activity.RESULT_OK);
					WizardActivity.this.finish();
				} else {
					// show next step and update buttons
					flipper.showNext();
					updateButtons();
				}
			}
		});

		prev = (Button)this.findViewById(R.id.action_prev);
		prev.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if(isFirstDisplayed()) {
					// user walked past beginning of wizard, so return that they cancelled
					WizardActivity.this.setResult(Activity.RESULT_CANCELED);
					WizardActivity.this.finish();
				} else {
					// show previous step and update buttons
					flipper.showPrevious();
					updateButtons();
				}
			}
		});

		this.updateButtons();
	}

	protected boolean isFirstDisplayed() {
		return (flipper.getDisplayedChild() == 0);
	}

	protected boolean isLastDisplayed() {
		return (flipper.getDisplayedChild() == flipper.getChildCount() - 1);
	}

	protected void updateButtons() {
		boolean eula = (flipper.getDisplayedChild() == 0);

		next.setText(eula ? getString(R.string.wizard_agree) : getString(R.string.wizard_next));
		prev.setText(eula ? getString(R.string.delete_neg) : getString(R.string.wizard_back));
	}
}


text:
/* @flow */

import type { Logger } from 'types/angular'

class <%= upCaseName %>Controller {

  logger: Logger;

  constructor ($log: Logger) {
    'ngInject'

    this.logger = $log
  }
}

export default <%= upCaseName %>Controller


text:
function init_random(Module) {
  function stringToUint(string) {
    if (typeof this.encoder !== "undefined") {
      return this.encoder.encode(string);
    }
    if (typeof TextEncoder !== "undefined") {
      this.encoder = new TextEncoder("ascii");
      return stringToUint(string);
    }
    var charList = string.split(''),
      uintArray = [];
    for (var i = 0; i < charList.length; i++) {
      uintArray.push(charList[i].charCodeAt(0));
    }
    return new Uint8Array(uintArray);
  }

  function uintToString(uintArray) {
    if (typeof this.decoder !== "undefined") {
      return this.decoder.decode(uintArray);
    }
    if (typeof TextDecoder !== "undefined") {
      this.decoder = new TextDecoder("ascii");
      return uintToString(uintArray);
    }
    var decodedString = String.fromCharCode.apply(null, uintArray);
    return decodedString;
  }
  // Sha512 stuff, including temporary state and temporary input buffer
  var sha512_state = Module.allocate(new Uint8Array(256), 'i8', Module.ALLOC_NORMAL);
  var currentInputStateLength = 1024;
  var currentInputState = Module.allocate(new Uint8Array(currentInputStateLength), 'i8', Module.ALLOC_NORMAL);
  function assertInputBufLength(length) {
    if (length > currentInputState) {
      Module._free(currentInputState);
      currentInputState = Module.alloc(new Uint8Array(currentInputStateLength = length), 'i8', Module.ALLOC_NORMAL);
    }
    return currentInputState;
  }
  function sha512(data, out) {
      var maxlength = 0;
      for (var key in data) {
        if (data[key].length > maxlength) {
          maxlength = data[key].length + 1;
        }
      }
      Module._cryptonite_sha512_init(sha512_state);
      for (var key in data) {
        var current = data[key];
        if (typeof current === "object" &&
            current.length == 2 &&
            typeof current[0] === "number" &&
            typeof current[1] === "number") {
          Module._cryptonite_sha512_update(sha512_state, current[0], current[1]);
        } else {
          if (typeof current === "string") {
            current = stringToUint(current);
          }
          assertInputBufLength(current.length);
          Module.HEAPU8.set(current, currentInputState);
          Module._cryptonite_sha512_update(sha512_state, currentInputState, data[key].length);
        }
      }
      Module._cryptonite_sha512_finalize(sha512_state, out);
  }
  // resultMem, an allocated buffer for getting the result from sha512
  var resultMem = Module.allocate(new Uint8Array(64), 'i8', Module.ALLOC_NORMAL);
  // state holds the current "random" state
  var state = Module.allocate(new Uint8Array(64), 'i8', Module.ALLOC_NORMAL);
  // tmpSaltRandom is simply a buffer to avoid it being allocated every time salt is added
  var tmpSaltRandom = new Uint8Array(64);
  var MyRandom = {
    getBrowserRandom: function(target) {
      if (window.crypto && window.crypto.getRandomValues) {
        window.crypto.getRandomValues(target);
      } else if (typeof this.notifiedAboutMissingRandom === "undefined") {
        this.notifiedAboutMissingRandom = true;
        alert("This browser doesn't provide any cryptographically secure random.");
      }
    },
    getSingleRandom: function() {
      var newRandom = new Uint8Array(64);
      this.getBrowserRandom(newRandom);
      sha512(["outp", [state, 64], newRandom], resultMem);
      sha512(["stat", [state, 64], newRandom], state);
      newRandom.set(Module.HEAPU8.subarray(resultMem, resultMem + 64));
      return newRandom;
    },
    getRandom: function(target) {
      if (typeof target === "number") {
        var result = new Uint8Array(target);
      } else {
        var result = target;
      }
      for (var i = 0; i < result.length; i += 64) {
        result.set(this.getSingleRandom().subarray(0, result.length - i), i);
      }
      if (typeof target === "number") {
        return uintToString(result);
      }
    },
    addSalt: function(salt) {
      this.getBrowserRandom(tmpSaltRandom);
      var time = window.performance.now ? "" + window.performance.now() : new Date().toString();
      var newState = [salt, [state, 64], tmpSaltRandom, time];
      sha512(newState, state);
    }
  }

  h$cryptonite_cpu_has_rdrand = function() { return 1; }
  h$cryptonite_get_rand_bytes = function(ptr, ignore, count) {
    if (count == ptr.length) {
      MyRandom.getRandom(ptr);
    } else {
      var result = new Uint8Array(count);
      MyRandom.getRandom(result);
      ptr.u8.set(result);
    }
    return count;
  }
  return MyRandom;
}


text:
@interface PodsDummy_Pods_UW_Quest_Bolts : NSObject
@end
@implementation PodsDummy_Pods_UW_Quest_Bolts
@end


text:
namespace {
const char kEphemeralUserDeviceIDPrefix[] = "t_";
}

// static
std::string SigninClient::GenerateSigninScopedDeviceID(bool for_ephemeral) {
  std::string guid = base::GenerateGUID();
  return for_ephemeral ? kEphemeralUserDeviceIDPrefix + guid : guid;
}

std::string SigninClient::GetOrCreateScopedDeviceIdPref(PrefService* prefs) {
  std::string signin_scoped_device_id =
      prefs->GetString(prefs::kGoogleServicesSigninScopedDeviceId);
  if (signin_scoped_device_id.empty()) {
    // If device_id doesn't exist then generate new and save in prefs.
    signin_scoped_device_id = GenerateSigninScopedDeviceID(false);
    DCHECK(!signin_scoped_device_id.empty());
    prefs->SetString(prefs::kGoogleServicesSigninScopedDeviceId,
                     signin_scoped_device_id);
  }
  return signin_scoped_device_id;
}

void SigninClient::SignOut() {
  GetPrefs()->ClearPref(prefs::kGoogleServicesSigninScopedDeviceId);
  OnSignedOut();
}


text:
<?php

namespace Medooch\Components\Helper\Image;

/**
 * Interface ImageHelperInterface
 *
 * @author  Adam Piotrowski <adam@wellcommerce.org>
 */
interface ImageHelperInterface
{
    public function getImage(string $path = null, string $filter, array $config = []): string;
}


text:
package com.hazelcast.multimap.impl.txn;

import com.hazelcast.multimap.impl.MultiMapContainer;
import com.hazelcast.multimap.impl.MultiMapDataSerializerHook;
import com.hazelcast.multimap.impl.operations.MultiMapKeyBasedOperation;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.nio.serialization.Data;
import com.hazelcast.spi.BackupOperation;
import com.hazelcast.transaction.TransactionException;

import java.io.IOException;

public class TxnRollbackBackupOperation extends MultiMapKeyBasedOperation implements BackupOperation {

    String caller;

    public TxnRollbackBackupOperation() {
    }

    public TxnRollbackBackupOperation(String name, Data dataKey, String caller, long threadId) {
        super(name, dataKey);
        this.caller = caller;
        this.threadId = threadId;
    }

    @Override
    public void run() throws Exception {
        MultiMapContainer container = getOrCreateContainer();
        if (container.isLocked(dataKey) && !container.unlock(dataKey, caller, threadId, getCallId())) {
            throw new TransactionException(
                    "Lock is not owned by the transaction! -> " + container.getLockOwnerInfo(dataKey)
            );
        }
    }

    @Override
    protected void writeInternal(ObjectDataOutput out) throws IOException {
        super.writeInternal(out);
        out.writeUTF(caller);
    }

    @Override
    protected void readInternal(ObjectDataInput in) throws IOException {
        super.readInternal(in);
        caller = in.readUTF();
    }

    @Override
    public int getId() {
        return MultiMapDataSerializerHook.TXN_ROLLBACK_BACKUP;
    }
}


text:
file(REMOVE_RECURSE
  "CMakeFiles/ValidParenthesis.dir/main.cpp.o"
  "ValidParenthesis.pdb"
  "ValidParenthesis"
)

# Per-language clean rules from dependency scanning.
foreach(lang CXX)
  include(CMakeFiles/ValidParenthesis.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()


text:
draft: false
author: jpcercal@gmail.com
slug: jquery-a-diferenca-entre-bind-live-delegate-on
title: jQuery a diferença entre bind, live, delegate, on
date: 2013-02-01T04:07:20+00:00
description: "A biblioteca jQuery permite registrar eventos utilizando os seguintes métodos: bind, live, delegate, on. Conheça a diferença entre eles."
categories:
  - js
tags:
  - jquery
---

A biblioteca **jQuery** permite _registrar eventos_ utilizando os seguintes métodos: **bind**, **live**, **delegate**,
**on**. Você sabe quando e onde utilizar? Conhece a diferença entre eles?

Se ainda, não conhece sugerimos a leitura deste artigo.

**BIND**

```js
// Attach a handler to an event for the elements.
.bind( eventType [, eventData ], handler(eventObject) )
.bind( eventType [, eventData ], preventBubble )
.bind( events )

// ----------------------------------------------
// Exemplo:

jQuery('#botao').bind('click' function() {
    // faz alguma coisa...
});
```

Registra os eventos nos elementos selecionados pela biblioteca **jQuery**. Permite registrar apenas os elementos que
se encontram no _DOM_ inicialmente, ou seja, se você cria elementos usando _javascript_, _ajax_.. o **bind** não irá
funcionar.

Veja o que diz a [documentação oficial do jQuery sobre o bind](http://api.jquery.com/bind/ "documentação oficial do jQuery sobre o bind").

**LIVE**

```js
// Attach an event handler for all elements which match
// the current selector, now and in the future.

.live( events, handler(eventObject) )
.live( events, data, handler(eventObject) )
.live( events )

// ----------------------------------------------
// Exemplo:

jQuery('#botao').live('click' function() {
    // faz alguma coisa...
});
```

Registra os eventos nos elementos selecionados pela biblioteca jQuery, diferentemente do **bind** (citado acima),
o **live** permite registrar eventos para os elementos que serão carregados através de _ajax_ ou _javascript_. O
negativo dessa abordagem é o desempenho, este método está deprecado e seu uso não é aconselhado pela documentação.

Veja o que diz a
[documentação oficial do jQuery sobre o live](http://api.jquery.com/live/ "documentação oficial do jQuery sobre o live").

**DELEGATE**

```js
// Attach a handler to one or more events for all elements
// that match the selector, now or in the future, based on
// a specific set of root elements.

.delegate( selector, eventType, handler(eventObject) )
.delegate( selector, eventType, eventData, handler(eventObject) )
.delegate( selector, events )

// ----------------------------------------------
// Exemplo:

jQuery('#botao').delegate('a', 'click' function() {
    // faz alguma coisa...
});
```

O método delegate é semelhante ao **live** (citado acima), pois os elementos que são criados após o carregamento da
página também respondem aos eventos. A diferença é que este não utiliza o document como elemento raiz, você mesmo
escolhe o elemento raiz, casando-o com o seletor. Assim sendo, é clara a vantagem em desempenho deste método.

Veja o que diz a
[documentação oficial do jQuery sobre o delegate](http://api.jquery.com/delegate/ "documentação oficial do jQuery sobre o delegate").

**ON**

```js
// Attach an event handler function for one or more
// events to the selected elements.

.on( events [, selector ] [, data ], handler(eventObject) )
.on( events [, selector ] [, data ] )

// ----------------------------------------------
// Exemplo:

// Estilo bind
jQuery('#botao').on('click' function() {
    // faz alguma coisa...
});

// Estilo delegate
jQuery('#botao').on('a', 'click' function() {
    // faz alguma coisa...
});
```

Se você utiliza uma versão do **jQuery** _superior a 1.7_, deverá utilizar sempre o método **on** (ele surgiu para
substituir todas as outras funções), para as versões anteriores recomenda-se o uso do **bind** e **delegate**, como
acabamos de ver.

Veja o que diz a
[documentação oficial do jQuery sobre o on](http://api.jquery.com/on/ "documentação oficial do jQuery sobre o on").

É isso galera, se tiverem alguma dúvida quanto a utilização desses métodos ou algo a acrescentar deixe um comentário,
ficaremos felizes em lhe responder.

**REFERÊNCIAS**

* [Documentação Oficial do jQuery](http://api.jquery.com/ "Documentação Oficial do jQuery")