text:
package io.apiman.gateway.platforms.servlet.connectors.ssl;

import io.apiman.common.config.options.TLSOptions;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLSession;
import javax.net.ssl.X509TrustManager;

import org.apache.http.ssl.PrivateKeyDetails;
import org.apache.http.ssl.PrivateKeyStrategy;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.util.Args;

/**
 * Factory to produce {@link SSLSessionStrategy}.
 *
 * @author Marc Savy
 */
public class SSLSessionStrategyFactory {
    private SSLSessionStrategyFactory() {}
    private static final HostnameVerifier ALLOW_ANY = new AllowAnyVerifier();
    private static final TrustStrategy SELF_SIGNED = new TrustSelfSignedStrategy();
    private static String[] EMPTY = new String[]{};

    /**
     * Convenience function parses map of options to generate {@link SSLSessionStrategy}.
     *

     * Defaults are provided for all fields:
     *

     *

     *
trustStore - default: JSSERefGuide

     *
trustStorePassword - none

     *
allowedProtocols - {@link SSLParameters#getProtocols()}

     *
disallowedProtocols - {@link SSLParameters#getCipherSuites()}

     *
allowedCiphers - {@link SSLParameters#getCipherSuites()}

     *
disallowedCiphers - {@link SSLParameters#getCipherSuites()}

     *
allowAnyHost - false

     *
allowSelfSigned - false

     *

     *
     * @param optionsMap map of options
     * @return the SSL session strategy
     * @see #build(String, String, String, String, String[], String, String[], String[], boolean, boolean)
     * @throws NoSuchAlgorithmException if the selected algorithm is not available on the system
     * @throws KeyManagementException when particular cryptographic algorithm not available
     * @throws KeyStoreException problem with keystore
     * @throws CertificateException if there was a problem with the certificate
     * @throws IOException if the truststore could not be found or was invalid
     * @throws UnrecoverableKeyException a key in keystore cannot be recovered
     */
    public static SSLSessionStrategy buildStandard(TLSOptions optionsMap)
            throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException,
            UnrecoverableKeyException, CertificateException, IOException {
        String[] allowedProtocols = arrayDifference(optionsMap.getAllowedProtocols(),
                optionsMap.getDisallowedProtocols(),
                getDefaultProtocols());
        String[] allowedCiphers = arrayDifference(optionsMap.getAllowedCiphers(),
                optionsMap.getDisallowedCiphers(),
                getDefaultCipherSuites());

        return build(optionsMap.getTrustStore(),
                optionsMap.getTrustStorePassword(),
                null, null, null, null, // All keyStore related stuff
                allowedProtocols,
                allowedCiphers,
                optionsMap.isAllowAnyHost(),
                optionsMap.isTrustSelfSigned());
    }

    /**
     * Convenience function parses map of options to generate {@link SSLSessionStrategy}.
     *

     * Defaults are provided for some fields, others are options. ClientKeystore is required:
     *

     *

     *
trustStore - default: JSSERefGuide

     *
trustStorePassword - none

     *
keyStore - required

     *
keyStorePassword - none

     *
keyAliases - none

     *
keyPassword - none

     *
allowedProtocols - {@link SSLParameters#getProtocols()}

     *
disallowedProtocols - {@link SSLParameters#getCipherSuites()}

     *
allowedCiphers - {@link SSLParameters#getCipherSuites()}

     *
disallowedCiphers - {@link SSLParameters#getCipherSuites()}

     *
allowAnyHost - false

     *
allowSelfSigned - false

     *

     *
     * @param optionsMap map of options
     * @return the SSL session strategy
     * @see #build(String, String, String, String, String[], String, String[], String[], boolean, boolean)
     * @throws NoSuchAlgorithmException if the selected algorithm is not available on the system
     * @throws KeyManagementException when particular cryptographic algorithm not available
     * @throws KeyStoreException problem with keystore
     * @throws CertificateException if there was a problem with the certificate
     * @throws IOException if the truststore could not be found or was invalid
     * @throws UnrecoverableKeyException a key in keystore cannot be recovered
     */
    @SuppressWarnings("nls")
    public static SSLSessionStrategy buildMutual(TLSOptions optionsMap)
            throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException,
            IOException, UnrecoverableKeyException {
        Args.notNull(optionsMap.getKeyStore(), "KeyStore");
        Args.notEmpty(optionsMap.getKeyStore(), "KeyStore must not be empty");

        String[] allowedProtocols = arrayDifference(optionsMap.getAllowedProtocols(),
                optionsMap.getDisallowedProtocols(),
                getDefaultProtocols());
        String[] allowedCiphers = arrayDifference(optionsMap.getAllowedCiphers(),
                optionsMap.getDisallowedCiphers(),
                getDefaultCipherSuites());

        return build(optionsMap.getTrustStore(),
                optionsMap.getTrustStorePassword(),
                optionsMap.getKeyStore(),
                optionsMap.getKeyStorePassword(),
                optionsMap.getKeyAliases(),
                optionsMap.getKeyPassword(),
                allowedProtocols,
                allowedCiphers,
                optionsMap.isAllowAnyHost(),
                optionsMap.isTrustSelfSigned());
    }

    /**
     * Build an {@link SSLSessionStrategy}.
     *
     * @param trustStore the trust store
     * @param trustStorePassword the truststore password (if any)
     * @param keyStore the keystore
     * @param keyStorePassword the keystore password (if any)
     * @param keyAliases the key aliases that are candidates for use (if any)
     * @param keyPassword the key password (if any)
     * @param allowedProtocols the allowed transport protocols.
     *            Avoid specifying insecure protocols
     * @param allowedCiphers allowed crypto ciphersuites, <tt>null</tt> to use system defaults
     * @param trustSelfSigned true if self signed certificates can be trusted.
     *             Use with caution
     * @param allowAnyHostname true if any hostname can be connected to (i.e. does not need to match
     *            certificate hostname). Do not use in production
     * @return the connection socket factory
     * @throws NoSuchAlgorithmException if the selected algorithm is not available on the system
     * @throws KeyStoreException if there was a problem with the keystore
     * @throws CertificateException if there was a problem with the certificate
     * @throws IOException if the truststore could not be found or was invalid
     * @throws KeyManagementException if there is a problem with keys
     * @throws UnrecoverableKeyException if the key cannot be recovered
     */
    public static SSLSessionStrategy build(String trustStore,
            String trustStorePassword,
            String keyStore,
            String keyStorePassword,
            String[] keyAliases,
            String keyPassword,
            String[] allowedProtocols,
            String[] allowedCiphers,
            boolean allowAnyHostname,
            boolean trustSelfSigned)

    throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException,
            KeyManagementException, UnrecoverableKeyException {

        Args.notNull(allowedProtocols, "Allowed protocols"); //$NON-NLS-1$
        Args.notNull(allowedCiphers, "Allowed ciphers"); //$NON-NLS-1$

        TrustStrategy trustStrategy = trustSelfSigned ?  SELF_SIGNED : null;
        HostnameVerifier hostnameVerifier = allowAnyHostname ? ALLOW_ANY :
            SSLConnectionSocketFactory.getDefaultHostnameVerifier();
        PrivateKeyStrategy privateKeyStrategy = keyAliases == null ? null : new SelectByAlias(keyAliases);
        boolean clientAuth = keyStore == null ? false : true;

        SSLContextBuilder builder = SSLContexts.custom();

        if (trustStore != null) {
            loadTrustMaterial(builder,
                    new File(trustStore),
                    trustStorePassword.toCharArray(),
                    trustStrategy);
        }

        if (keyStore != null) {
            char[] ksp = keyStorePassword == null ? null : keyStorePassword.toCharArray();
            char[] kp = keyPassword == null ? null : keyPassword.toCharArray();
            loadKeyMaterial(builder, new File(keyStore), ksp, kp, privateKeyStrategy);
        }

        SSLContext sslContext = builder.build();
        return new SSLSessionStrategy(hostnameVerifier, new CipherSelectingSSLSocketFactory(
                sslContext.getSocketFactory(), allowedCiphers, allowedProtocols, clientAuth));
    }

    /**
     * Do not use in production
     *

     * Returns an SSLSessionStrategy that trusts any Certificate.
     *

     * Naturally, this is vulnerable to a raft of MIITM and forgery attacks, so users should exercise extreme
     * caution and only use it for development purposes.
     *
     * @return the ssl strategy
     */
    public static SSLSessionStrategy buildUnsafe() {
        System.err.println("ATTENTION: SSLSessionStrategy will trust *any* certificate." //$NON-NLS-1$
                + " This is extremely unsafe for production. Caveat utilitor!"); //$NON-NLS-1$

        try {
            SSLContext sslContext = SSLContext.getInstance("TLS"); //$NON-NLS-1$

            // This accepts anything.
            sslContext.init(null, new X509TrustManager[] { new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }
            } }, new SecureRandom());

            return new SSLSessionStrategy(ALLOW_ANY, sslContext.getSocketFactory());

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static String[] getDefaultCipherSuites() {
        try {
            return SSLContext.getDefault().getDefaultSSLParameters().getCipherSuites();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    private static String[] getDefaultProtocols() {
        try {
            return SSLContext.getDefault().getDefaultSSLParameters().getProtocols();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * List A - List B
     *
     * @param allowed allowed items
     * @param disallowed disallowed items
     * @return allowed items minus disallowed items
     */
    private static String[] arrayDifference(String[] allowed, String[] disallowed, String[] defaultItems) {
        List<String> allowL = new ArrayList<>(Arrays.asList(optionalVar(allowed, defaultItems)));
        List<String> disallowL = new ArrayList<>(Arrays.asList(optionalVar(disallowed, EMPTY)));
        allowL.removeAll(disallowL);
        return allowL.toArray(new String[allowL.size()]);
    }

    private static String[] optionalVar(String[] arr, String[] defaultArr) {
        if (arr == null || arr.length==0) {
            return defaultArr;
        }
        return arr;
    }

    /**
     * Allows any hostname.
     *
     * @author Marc Savy <msavy@redhat.com>
     */
    private static final class AllowAnyVerifier implements HostnameVerifier {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }

    private static final class SelectByAlias implements PrivateKeyStrategy {
        private Set<String> keyAliases = new HashSet<>();

        public SelectByAlias(String[] keyAliases) {
            for (String k : keyAliases) {
                this.keyAliases.add(k);
            }
        }

        @Override
        public String chooseAlias(Map<String, PrivateKeyDetails> aliases, Socket socket) {
            for (String k : aliases.keySet()) {
              if (keyAliases.contains(k)) {
                  return k;
              }
            }
            return null;
        }
    }

    // This code is adapted from
    // apache/httpcore/blob/4.4.x/httpcore/src/main/java/org/apache/http/ssl/SSLContextBuilder.java
    // for compatibility purposes.
    private static SSLContextBuilder loadTrustMaterial(SSLContextBuilder builder, final File file,
            final char[] tsp, final TrustStrategy trustStrategy)
                    throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {
        Args.notNull(file, "Truststore file"); //$NON-NLS-1$
        final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        final FileInputStream instream = new FileInputStream(file);
        try {
            trustStore.load(instream, tsp);
        } finally {
            instream.close();
        }
        return builder.loadTrustMaterial(trustStore, trustStrategy);
    }

    // This code is adapted from
    // apache/httpcore/blob/4.4.x/httpcore/src/main/java/org/apache/http/ssl/SSLContextBuilder.java
    // for compatibility purposes.
    private static SSLContextBuilder loadKeyMaterial(SSLContextBuilder builder, File file, char[] ksp,
            char[] kp, PrivateKeyStrategy privateKeyStrategy) throws NoSuchAlgorithmException,
                    KeyStoreException, UnrecoverableKeyException, CertificateException, IOException {
        Args.notNull(file, "Keystore file"); //$NON-NLS-1$
        final KeyStore identityStore = KeyStore.getInstance(KeyStore.getDefaultType());
        final FileInputStream instream = new FileInputStream(file);
        try {
            identityStore.load(instream, ksp);
        } finally {
            instream.close();
        }
        return builder.loadKeyMaterial(identityStore, kp, privateKeyStrategy);
    }

}


text:
PHP Library (+Laravel) - Teeworlds Servers Info
This package, allows you to gather information from Teeworlds Servers as well as from TeeWorlds Master Servers.
## Requirements

- PHP ^7.0

## Composer

Require this package with composer using the following command:
```
composer require savander/twservers
```
To install this package on only development systems, add the `--dev` flag to your composer command:
```
composer require --dev savander/twservers
```

#### for Laravel
##### Laravel 5.5+
Laravel 5.5 introduced package autodiscover. It means, that you don't need to aliases and providers to your app by your own.

##### For Laravel 5.4~
After updating composer, add the service provider to the `providers` array in `config/app.php`
```php
Savander\TwServers\TwServersServiceProvider::class,
```

Also, add the Facade to the `aliases` array in `config/app.php`
```php
'TwServers' => Savander\TwServers\Facades\TwServers::class,
```

## Usage (examples based on Laravel Facade)

### Teeworlds Servers
Gathering information from server/servers can consume some time.

You can **add one or few servers** to object by passing `array`
```php
$servers = TwServers::addServers([
        new ServerResolver('192.168.0.1', 8303),
        new ServerResolver('192.168.0.2', 8305)
    ]
);
```
or `ServerResolver` class directly to function. (You don't have to pass `port`, by default it is `8303`)
```php
$servers = TwServers::addServer(
        new ServerResolver('192.168.0.1')
);

```

To list every server you added, use `getServers()` function

```php
  $servers->getServers();

```
It will return list of servers you passed to object, with data from server.

You can automatically get Players from servers by using `getPlayers()` function.
You can pass `ServerResolverInterface` object, or string like `ip:port` to get data from already added server.
```php
$servers = TwServers::getPlayers(
        new ServerResolver('192.168.0.1')
);

# Array of Player objects
$players = $server->getPlayers();

```

To get specific server from already added, use function `getServer(string $string)`
```php

# Index as a combination of ip and port => ip:port or
#                                          ip (only if standard port 8303)
$server = $servers->getServer('192.168.0.1')
```

`ServerResolver` has some function, which you can use, check `ServerResolverInterface`:
[**ServerResolverInterface.php**](https://github.com/savander/TwServersInfo-php/blob/master/src/Server/ServerResolverInterface.php)

If server has players, ServerResolver stores PlayerInterface, which has some function as well:
[**PlayerInterface**](https://github.com/savander/TwServersInfo-php/blob/master/src/Player/PlayerInterface.php)

### Teeworlds Master Servers
Gathering information from master servers can consume some time.

You can **add one or few servers** to object by passing `array`
```php
$servers = TwServers::addMasterServers([
       new MasterServerResolver('master1.teeworlds.com', 8300),
       new MasterServerResolver('master2.teeworlds.com', 8300),
       new MasterServerResolver('master3.teeworlds.com'),
       new MasterServerResolver('master4.teeworlds.com')
    ]
);
```
or `MasterServerResolver` class directly to function. (You don't have to pass `port`, by default it is `8300`)
```php
$servers = TwServers::addMasterServer(
        new MasterServerResolver('master2.teeworlds.com')
);

```

To list every server you added, use `getMasterServers()` function

```php
  $servers->getMasterServers();

```
It will return list of servers you passed to object, with data from masterserver.

To get specific masterserver from already added, use function `getMasterServer(string $string)`
```php

# Index as a combination of ip and port => ip:port or
#                                          ip (only if standard port 8300)
$server = $servers->getMasterServer('master2.teeworlds.com')
```

`MasterServerResolver` has some function, which you can use, check `MasterServerResolverInterface`:
[**MasterServerResolverInterface.php**](https://github.com/savander/TwServersInfo-php/blob/master/src/MasterServer/MasterServerResolverInterface.php)

___
**Feel free to add your own version based on those interfaces.**

redpajama_set_name: RedPajamaGithub


text:
namespace DiscogsClient.Data.Result
{
    public class DiscogsFormat
    {
        public string[] descriptions { get; set; }
        public string name { get; set; }
        public string qty { get; set; }
        public string text { get; set; }
    }
}


text:
      Benchmarked against goal:

      Not applicable


text:
from __future__ import unicode_literals

from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('sest', '0011_auto_20170202_1607'),
    ]

    operations = [
        migrations.RenameField(
            model_name='conditionandreaction',
            old_name='value',
            new_name='_value',
        ),
        migrations.RenameField(
            model_name='conditionandreaction',
            old_name='value_optional',
            new_name='_value_optional',
        ),
    ]


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package unifavip.estruturadados;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;

/**
 *
 * @author douglasfrari
 */
public class VetorTest {

    private static final int TOTAL = 200000;

    public VetorTest() {
    }

    @BeforeClass
    public static void setUpClass() {
    }

    @AfterClass
    public static void tearDownClass() {
    }

    @Before
    public void setUp() {
    }

    @After
    public void tearDown() {
    }

    /**
     * Test of adicionaAluno method, of class Vetor.
     */
    @Test
    public void testAdicionaAluno_Aluno() {
        System.out.println("adicionaAluno");
        Aluno aluno = new Aluno("Test");
        Vetor instance = new Vetor();
        instance.adicionaAluno(aluno);
        // TODO review the generated test code and remove the default call to fail.

        assertTrue(instance.tamanho() == 1);
    }

    @Test
    public void testAdicionarAlunoNulo() {
        System.out.println("testAdicionarAlunoNulo");
        Aluno aluno = null;
        Vetor instance = new Vetor();
        String ESPERADO = "Objeto Inválido!";
        try {
            instance.adicionaAluno(aluno);
        } catch (IllegalArgumentException e) {
            assertTrue(e.getMessage().equals(ESPERADO));
        }
   }

    /**
     * Test of adicionaAluno method, of class Vetor.
     */
    @Test
    public void testAdicionaAluno_int_Aluno() {
        System.out.println("adicionaAluno");
        int posicao = 99;
        Aluno aluno = new Aluno("Aluno");
        Vetor instance = new Vetor();
        instance.adicionaAluno(posicao, aluno);

        assertTrue(instance.tamanho() == 1);

    }

    /**
     * Test of pegaAluno method, of class Vetor.
     */
    @Test
    public void testPegaAluno() {
        System.out.println("pegaAluno");
        int posicao = 0;
        Vetor instance = new Vetor();
        Aluno expResult = new Aluno("Batman");
        instance.adicionaAluno(expResult);

        Aluno result = instance.pegaAluno(posicao);

        assertEquals(expResult, result);
        assertTrue(expResult.equals(result));
    }

    /**
     * Test of remove method, of class Vetor.
     */
    @Test
    public void testRemove() {
        System.out.println("remove");
        int posicao = 0;
        Vetor instance = new Vetor();

        Aluno aluno = new Aluno("Ryu");
        instance.adicionaAluno(aluno);

        instance.remove(posicao);

        assertTrue(instance.tamanho() == 0);
    }

    /**
     * Test of contem method, of class Vetor.
     */
    @Test
    public void testContem() {
        System.out.println("contem");
        Aluno aluno = new Aluno("Xuxa");
        Vetor instance = new Vetor();
        instance.adicionaAluno(aluno);

        boolean expResult = true;
        boolean result = instance.contem(aluno);
        assertEquals(expResult, result);
    }

    /**
     * Test of tamanho method, of class Vetor.
     */
    @Test
    public void testTamanho() {
        System.out.println("tamanho");
        Vetor instance = new Vetor();
        int expResult = 0;
        int result = instance.tamanho();
        assertEquals(expResult, result);

    }

    /**
     * Test of listaTodos method, of class Vetor.
     */
    @Test
    public void testListaTodos() {
        System.out.println("listaTodos");
        Vetor instance = new Vetor();
        String expResult = "[]";
        String result = instance.listaTodos();
        assertEquals(expResult, result);

    }

    /**
     * Test of toString method, of class Vetor.
     */
    @Test
    public void testToString() {
        System.out.println("toString");
        Vetor instance = new Vetor();
        String expResult = "[]";
        String result = instance.toString();

        assertEquals(expResult, result);

    }

    @Test
    public void testAdicionarVariosAlunos() {
        // TOTAL como constante (ver acima)

        long tempoInicial = System.currentTimeMillis();
        Vetor nossoVetor = new Vetor();

        for (int i = 0; i < TOTAL; i++) {
            Aluno aluno = new Aluno("Aluno "+(i+1));
            nossoVetor.adicionaAluno(aluno);
        }

        long tempoFinal = System.currentTimeMillis();

        float diferenca = (float) ((tempoFinal-tempoInicial) / 1000) %60;

        System.out.println("Adicionando "+TOTAL+" Alunos no Vetor: tempo: "+diferenca
                +" segundos");
        int totalAtual = nossoVetor.tamanho();

        assertTrue(TOTAL == totalAtual);

    }

    @Test
    public void testAdicionarVariosAlunosEmPosicaoInicio() {
        // TOTAL como constante (ver acima)

        String texto = "Adicionando "+TOTAL+" Alunos no INICIO";
        long tempoInicial = System.currentTimeMillis();
        Vetor nossoVetor = new Vetor();

        for (int i = 0; i < TOTAL; i++) {
            Aluno aluno = new Aluno("Aluno "+(i+1));
            nossoVetor.adicionaAluno(0,aluno);
        }

        long tempoFinal = System.currentTimeMillis();

        imprimirTempo(texto, (tempoFinal-tempoInicial));

        int totalAtual = nossoVetor.tamanho();

        assertTrue(TOTAL == totalAtual);

    }

     @Test
    public void testAdicionarVariosAlunosEmPosicaoMEIO() {
        // TOTAL como constante (ver acima)

        String texto = "Adicionando "+TOTAL+" Alunos no MEIO";
        long tempoInicial = System.currentTimeMillis();
        Vetor nossoVetor = new Vetor();

        for (int i = 0; i < TOTAL; i++) {
            Aluno aluno = new Aluno("Aluno "+(i+1));
            nossoVetor.adicionaAluno(nossoVetor.tamanho()/2,aluno);
        }

        long tempoFinal = System.currentTimeMillis();

        imprimirTempo(texto, (tempoFinal-tempoInicial));

        int totalAtual = nossoVetor.tamanho();

        assertTrue(TOTAL == totalAtual);

    }

     @Test
    public void testAdicionarVariosAlunosEmPosicaoFIM() {
        // TOTAL como constante (ver acima)

        String texto = "Adicionando "+TOTAL+" Alunos no FINAL";
        long tempoInicial = System.currentTimeMillis();
        Vetor nossoVetor = new Vetor();

        for (int i = 0; i < TOTAL; i++) {
            Aluno aluno = new Aluno("Aluno "+(i+1));
            nossoVetor.adicionaAluno(nossoVetor.tamanho(),aluno);
        }

        long tempoFinal = System.currentTimeMillis();

        imprimirTempo(texto, (tempoFinal-tempoInicial));

        int totalAtual = nossoVetor.tamanho();

        assertTrue(TOTAL == totalAtual);

    }

    private void imprimirTempo(String texto, long tempo) {

        float diferenca = (float) (tempo / 1000) % 60;
        System.out.println(texto+" -> tempo: "+diferenca+ " segundos");
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <ImageView
        android:id="@+id/icon"
        android:layout_width="45dp"
        android:layout_height="45dp"
        />

    <LinearLayout
        android:id="@+id/fileinfo_linear"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:paddingLeft="11dp"
        >
        <TextView
            android:id="@+id/filename_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />

        <TextView
            android:id="@+id/filesize_date_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#ADADAD"
            />
    </LinearLayout>

</LinearLayout>


text:
Different time string at 0004.test_mem_w_prediction.sh
-------------------------------------------------------
Reported by Heiko when run on i386 and x86 platforms with different locales, en_US.utf8 and POSIX, respectively.


text:
using System.Threading;
using System.Threading.Tasks;

namespace TIKSN.Shell
{
    public interface IShellCommand
    {
        Task ExecuteAsync(CancellationToken cancellationToken);
    }
}


text:
using System.Collections.Generic;
using GitVersion.Configuration.Init.Wizard;
using GitVersion.Logging;
using GitVersion.Model.Configuration;

namespace GitVersion.Configuration.Init.SetConfig
{
    public class ConfigureBranch : ConfigInitWizardStep
    {
        private string name;
        private BranchConfig branchConfig;

        public ConfigureBranch(IConsole console, IFileSystem fileSystem, ILog log, IConfigInitStepFactory stepFactory) : base(console, fileSystem, log, stepFactory)
        {
        }

        public ConfigureBranch WithData(string name, BranchConfig branchConfig)
        {
            this.branchConfig = branchConfig;
            this.name = name;
            return this;
        }

        protected override StepResult HandleResult(string result, Queue<ConfigInitWizardStep> steps, Config config, string workingDirectory)
        {
            switch (result)
            {
                case "0":
                    steps.Enqueue(StepFactory.CreateStep<ConfigureBranches>());
                    return StepResult.Ok();
                case "1":
                    steps.Enqueue(StepFactory.CreateStep<SetBranchTag>().WithData(name, branchConfig));
                    return StepResult.Ok();
                case "2":
                    steps.Enqueue(StepFactory.CreateStep<SetBranchIncrementMode>().WithData(name, branchConfig));
                    return StepResult.Ok();
            }

            return StepResult.InvalidResponseSelected();
        }

        protected override string GetPrompt(Config config, string workingDirectory)
        {
            return $@"What would you like to change for '{name}':

0) Go Back
1) Branch Pre-release tag (Current: {branchConfig.Tag})
2) Branch Increment mode (per commit/after tag) (Current: {branchConfig.VersioningMode})";
        }

        protected override string DefaultResult => "0";
    }
}


text:
<slider>

{ titulo }

{descricao}

</slider>


text:
package server

import (
	"net/url"
	"reflect"
	"strconv"
	"time"

	"github.com/intervention-engine/fhir/models"
	"github.com/intervention-engine/fhir/search"
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
)

// NewMongoDataAccessLayer returns an implementation of DataAccessLayer that is backed by a Mongo database
func NewMongoDataAccessLayer(db *mgo.Database) DataAccessLayer {
	return &mongoDataAccessLayer{Database: db}
}

type mongoDataAccessLayer struct {
	Database *mgo.Database
}

func (dal *mongoDataAccessLayer) Get(id, resourceType string) (result interface{}, err error) {
	bsonID, err := convertIDToBsonID(id)
	if err != nil {
		return nil, convertMongoErr(err)
	}

	collection := dal.Database.C(models.PluralizeLowerResourceName(resourceType))
	result = models.NewStructForResourceName(resourceType)
	if err = collection.FindId(bsonID.Hex()).One(result); err != nil {
		return nil, convertMongoErr(err)
	}

	return
}

func (dal *mongoDataAccessLayer) Post(resource interface{}) (id string, err error) {
	id = bson.NewObjectId().Hex()
	err = convertMongoErr(dal.PostWithID(id, resource))
	return
}

func (dal *mongoDataAccessLayer) PostWithID(id string, resource interface{}) error {
	bsonID, err := convertIDToBsonID(id)
	if err != nil {
		return convertMongoErr(err)
	}

	reflect.ValueOf(resource).Elem().FieldByName("Id").SetString(bsonID.Hex())
	resourceType := reflect.TypeOf(resource).Elem().Name()
	collection := dal.Database.C(models.PluralizeLowerResourceName(resourceType))
	updateLastUpdatedDate(resource)
	return convertMongoErr(collection.Insert(resource))
}

func (dal *mongoDataAccessLayer) Put(id string, resource interface{}) (createdNew bool, err error) {
	bsonID, err := convertIDToBsonID(id)
	if err != nil {
		return false, convertMongoErr(err)
	}

	resourceType := reflect.TypeOf(resource).Elem().Name()
	collection := dal.Database.C(models.PluralizeLowerResourceName(resourceType))
	reflect.ValueOf(resource).Elem().FieldByName("Id").SetString(bsonID.Hex())
	updateLastUpdatedDate(resource)
	info, err := collection.UpsertId(bsonID.Hex(), resource)
	if err == nil {
		createdNew = (info.Updated == 0)
	}
	return createdNew, convertMongoErr(err)
}

func (dal *mongoDataAccessLayer) ConditionalPut(query search.Query, resource interface{}) (id string, createdNew bool, err error) {
	if IDs, err := dal.FindIDs(query); err == nil {
		switch len(IDs) {
		case 0:
			id = bson.NewObjectId().Hex()
		case 1:
			id = IDs[0]
		default:
			return "", false, ErrMultipleMatches
		}
	} else {
		return "", false, err
	}

	createdNew, err = dal.Put(id, resource)
	return id, createdNew, err
}

func (dal *mongoDataAccessLayer) Delete(id, resourceType string) error {
	bsonID, err := convertIDToBsonID(id)
	if err != nil {
		return convertMongoErr(err)
	}

	collection := dal.Database.C(models.PluralizeLowerResourceName(resourceType))
	return convertMongoErr(collection.RemoveId(bsonID.Hex()))
}

func (dal *mongoDataAccessLayer) ConditionalDelete(query search.Query) (count int, err error) {
	searcher := search.NewMongoSearcher(dal.Database)
	queryObject := searcher.CreateQueryObject(query)

	collection := dal.Database.C(models.PluralizeLowerResourceName(query.Resource))
	info, err := collection.RemoveAll(queryObject)
	if info != nil {
		count = info.Removed
	}
	return count, convertMongoErr(err)
}

func (dal *mongoDataAccessLayer) Search(baseURL url.URL, searchQuery search.Query) (*models.Bundle, error) {
	searcher := search.NewMongoSearcher(dal.Database)

	var result interface{}
	var err error
	usesIncludes := len(searchQuery.Options().Include) > 0
	usesRevIncludes := len(searchQuery.Options().RevInclude) > 0
	// Only use (slower) pipeline if it is needed
	if usesIncludes || usesRevIncludes {
		result = models.NewSlicePlusForResourceName(searchQuery.Resource, 0, 0)
		err = searcher.CreatePipeline(searchQuery).All(result)
	} else {
		result = models.NewSliceForResourceName(searchQuery.Resource, 0, 0)
		err = searcher.CreateQuery(searchQuery).All(result)
	}
	if err != nil {
		return nil, convertMongoErr(err)
	}

	includesMap := make(map[string]interface{})
	var entryList []models.BundleEntryComponent
	resultVal := reflect.ValueOf(result).Elem()
	for i := 0; i < resultVal.Len(); i++ {
		var entry models.BundleEntryComponent
		entry.Resource = resultVal.Index(i).Addr().Interface()
		entry.Search = &models.BundleEntrySearchComponent{Mode: "match"}
		entryList = append(entryList, entry)

		if usesIncludes || usesRevIncludes {
			rpi, ok := entry.Resource.(ResourcePlusRelatedResources)
			if ok {
				for k, v := range rpi.GetIncludedAndRevIncludedResources() {
					includesMap[k] = v
				}
			}
		}
	}

	for _, v := range includesMap {
		var entry models.BundleEntryComponent
		entry.Resource = v
		entry.Search = &models.BundleEntrySearchComponent{Mode: "include"}
		entryList = append(entryList, entry)
	}

	var bundle models.Bundle
	bundle.Id = bson.NewObjectId().Hex()
	bundle.Type = "searchset"
	bundle.Entry = entryList

	options := searchQuery.Options()

	// Need to get the true total (not just how many were returned in this response)
	var total uint32
	if resultVal.Len() == options.Count || resultVal.Len() == 0 {
		// Need to get total count from the server, since there may be more or the offset was too high
		intTotal, err := searcher.CreateQueryWithoutOptions(searchQuery).Count()
		if err != nil {
			return nil, convertMongoErr(err)
		}
		total = uint32(intTotal)
	} else {
		// We can figure out the total by adding the offset and # results returned
		total = uint32(options.Offset + resultVal.Len())
	}
	bundle.Total = &total

	// Add links for paging
	bundle.Link = generatePagingLinks(baseURL, searchQuery, total)

	return &bundle, nil
}

func (dal *mongoDataAccessLayer) FindIDs(searchQuery search.Query) (IDs []string, err error) {
	// First create a new query with the unsupported query options filtered out
	oldParams := searchQuery.URLQueryParameters(false)
	newParams := search.URLQueryParameters{}
	for _, param := range oldParams.All() {
		switch param.Key {
		case search.ContainedParam, search.ContainedTypeParam, search.ElementsParam, search.IncludeParam,
			search.RevIncludeParam, search.SummaryParam:
			continue
		default:
			newParams.Add(param.Key, param.Value)
		}
	}
	newQuery := search.Query{Resource: searchQuery.Resource, Query: newParams.Encode()}

	// Now search on that query, unmarshaling to a temporary struct and converting results to []string
	searcher := search.NewMongoSearcher(dal.Database)
	mgoQuery := searcher.CreateQuery(newQuery).Select(bson.M{"_id": 1})
	results := []struct {
		ID string `bson:"_id"`
	}{}
	if err := mgoQuery.All(&results); err != nil {
		return nil, err
	}
	IDs = make([]string, len(results))
	for i := range results {
		IDs[i] = results[i].ID
	}

	return IDs, nil
}

// ResourcePlusRelatedResources is an interface to capture those structs that implement the functions for
// getting included and rev-included resources
type ResourcePlusRelatedResources interface {
	GetIncludedAndRevIncludedResources() map[string]interface{}
	GetIncludedResources() map[string]interface{}
	GetRevIncludedResources() map[string]interface{}
}

func generatePagingLinks(baseURL url.URL, query search.Query, total uint32) []models.BundleLinkComponent {
	links := make([]models.BundleLinkComponent, 0, 5)
	params := query.URLQueryParameters(true)
	offset := 0
	if pOffset := params.Get(search.OffsetParam); pOffset != "" {
		offset, _ = strconv.Atoi(pOffset)
		if offset < 0 {
			offset = 0
		}
	}
	count := search.NewQueryOptions().Count
	if pCount := params.Get(search.CountParam); pCount != "" {
		count, _ = strconv.Atoi(pCount)
		if count < 1 {
			count = search.NewQueryOptions().Count
		}
	}

	// Self link
	links = append(links, newLink("self", baseURL, params, offset, count))

	// First link
	links = append(links, newLink("first", baseURL, params, 0, count))

	// Previous link
	if offset > 0 {
		prevOffset := offset - count
		// Handle case where paging is uneven (e.g., count=10&offset=5)
		if prevOffset < 0 {
			prevOffset = 0
		}
		prevCount := offset - prevOffset
		links = append(links, newLink("previous", baseURL, params, prevOffset, prevCount))
	}

	// Next Link
	if total > uint32(offset+count) {
		nextOffset := offset + count
		links = append(links, newLink("next", baseURL, params, nextOffset, count))
	}

	// Last Link
	remainder := (int(total) - offset) % count
	if int(total) < offset {
		remainder = 0
	}
	newOffset := int(total) - remainder
	if remainder == 0 && int(total) > count {
		newOffset = int(total) - count
	}
	links = append(links, newLink("last", baseURL, params, newOffset, count))

	return links
}

func newLink(relation string, baseURL url.URL, params search.URLQueryParameters, offset int, count int) models.BundleLinkComponent {
	params.Set(search.OffsetParam, strconv.Itoa(offset))
	params.Set(search.CountParam, strconv.Itoa(count))
	baseURL.RawQuery = params.Encode()
	return models.BundleLinkComponent{Relation: relation, Url: baseURL.String()}
}

func convertIDToBsonID(id string) (bson.ObjectId, error) {
	if bson.IsObjectIdHex(id) {
		return bson.ObjectIdHex(id), nil
	}
	return bson.ObjectId(""), models.NewOperationOutcome("fatal", "exception", "Id must be a valid BSON ObjectId")
}

func updateLastUpdatedDate(resource interface{}) {
	m := reflect.ValueOf(resource).Elem().FieldByName("Meta")
	if m.IsNil() {
		newMeta := &models.Meta{}
		m.Set(reflect.ValueOf(newMeta))
	}
	now := &models.FHIRDateTime{Time: time.Now(), Precision: models.Timestamp}
	m.Elem().FieldByName("LastUpdated").Set(reflect.ValueOf(now))
}

func convertMongoErr(err error) error {
	switch err {
	default:
		return err
	case mgo.ErrNotFound:
		return ErrNotFound
	}
}


text:
var department = function(){
	var baseUrl =  contextPath + '/organization/';
	var dialog = null;    //对话框
	var departmentName = null;   //部门名称
	var departmentSN = null;    //部门编号
	var description = null;//部门描述
	var org = null;
	/*
	 *新增部门
	 */
	$.ajaxSetup({cache:false});

	var addDepartment = function(id, organizationType, $element){
		$.get(contextPath + '/pages/organisation/department-template.jsp').done(function(data){
			init(data,  id , 'addDepartment', organizationType, $element);
		});
	};
	/*
	 *新增子公司
	 */
	var addCompany = function(id, $element){
		$.get( contextPath + '/pages/organisation/department-template.jsp').done(function(data){
			init(data, id , 'addCompany', null, $element);
		});
	};
	/*
	 * 修改公司信息
	 */
	var updateCompany = function(id, $element){
		$.get( contextPath + '/pages/organisation/department-template.jsp').done(function(data){
			init(data,  id , 'updateCompany', null, $element);
			setData(id);
		});
	};
	/*
	 * 修改部门信息
	 */
	var updateDepartment = function(id, $element){
		$.get( contextPath + '/pages/organisation/department-template.jsp').done(function(data){
			init(data,  id , 'updateDepartment', null, $element);
			setData(id);
		});
	};
	/*
	 删除方法
	 */
	var del = function(org, type, $element){
        delete org.title;
		var url = 'terminate-department.koala';
		if(type == 'Company'){
			url = 'terminate-company.koala';
		}
		$.post(baseUrl + url, org).done(function(data){
			if(data.success){
				$('#departmentDetail').message({
					type: 'success',
					content: '撤销成功'
				});
				var departmentTree = $('#departmentTree');
                if($element.hasClass('tree-item')){
                    departmentTree.tree('removeChildren', $element);
                }else{
                    departmentTree.tree('removeChildren', $element.parent());
                }
                departmentTree.find('.tree-folder-header:first').click();
			}else{
				$('body').message({
					type: 'error',
					content: data.errorMessage
				});
			}
		}).fail(function(data){
			$('body').message({
				type: 'error',
				content: '撤销失败'
			});
		});
	};
	/**
	 * 初始化
	 */
	var init = function(data, id, type, organizationType, $element){
		dialog = $(data);
		var title = '';
		switch(type){
			case 'addDepartment':
				title = '创建下级部门';
				break;
			case 'addCompany':
				title = '创建子公司';
				break;
			case 'updateCompany':
				title = '修改机构信息';
				break;
			case 'updateDepartment':
				title = '修改机构信息';
				break;
		}
		dialog.find('.modal-header').find('.modal-title').html(title);
		departmentSN = dialog.find('#sn');
		departmentName = dialog.find('#name');
		description = dialog.find('#description');
		dialog.find('#save').on('click',function(){
			$(this).attr('disabled', 'disabled');
			save(id, type, organizationType);
		}).end().modal({
			keyboard: false
		}).on({
			'hidden.bs.modal': function(){
				$(this).remove();
			},
			'complete': function(event, data){
				var type = data.type;
				$('#departmentDetail').message({
					type: 'success',
					content: '保存成功'
				});
                if(type == 'updateCompany' || type == 'updateDepartment'){
                	 $.get(contextPath + '/organization/get.koala?id='+id).done(function(data){
                        var org = data;
                        $element.data(org);
                        if(!$element.hasClass('tree-item')){
                        	$element.find('.tree-folder-name:first').html(org.name).click();
                        }else{
                        	$element.find('.tree-item-name').html(org.name).click();
                        }
                     });
                }else{
                    $('#departmentTree').off().empty().data('koala.tree', null)
                    getTree(data.id);
                }
				$(this).modal('hide');
			}
		});
	};
	/*
	 *设置值
	 */
	var setData = function(id){
		$.get(baseUrl+'get.koala?id='+id).done(function(data){
			org = data;
			departmentSN.val(org.sn);
			departmentName.val(org.name);
			description.val(org.description);
		});
	};
	/*
	 *   保存数据 id存在则为修改 否则为新增
	 */
	var save = function(id, type, organizationType){
		if(!validate()){
			dialog.find('#save').removeAttr('disabled');
			return false;
		}
		var url = '';
		switch(type){
			case 'addDepartment':
				url =  baseUrl + 'create-department.koala?parentId='+id+'&parentType='+organizationType;
				break;
			case 'addCompany':
				url =  baseUrl + 'create-company.koala?parentId='+id;
				break;
			case 'updateCompany':
				url =  baseUrl + 'update-company.koala';
				break;
			case 'updateDepartment':
				url =  baseUrl + 'update-department.koala';
				break;
		}
		var data = getAllData(id, type);
		$.post(url, data).done(function(data){
			if(data.success){
				dialog.trigger('complete', {type:type, id: data.id});
			}else{
				dialog.find('.modal-content').message({
					type: 'error',
					content: data.errorMessage
				});
				refreshToken(dialog.find('input[name="koala.token"]'));
			}
			dialog.find('#save').removeAttr('disabled');
		}).fail(function(data){
			dialog.find('.modal-content').message({
				type: 'error',
				content: '保存失败!'
			});
			dialog.find('#save').removeAttr('disabled');
			refreshToken(dialog.find('input[name="koala.token"]'));
		});
	};
	/*
	 *获取表单数据
	 */
	var getAllData = function(id, type){
		if(type == 'addDepartment'){
			var department = {};
			department.sn = departmentSN.val();
			department.name = departmentName.val();
			department.description = description.val();
			department['koala.token'] = dialog.find('input[name="koala.token"]').val();
			return department;
		}else if(type == 'addCompany'){
			var company = {};
			company.sn = departmentSN.val();
			company.name = departmentName.val();
			company.description = description.val();
			company['koala.token'] = dialog.find('input[name="koala.token"]').val();
			return company;
	   }else {
			org.sn = departmentSN.val();
			org.name = departmentName.val();
			org.description = description.val();
			org['koala.token'] = dialog.find('input[name="koala.token"]').val();
			return org;
		}
	};
	/**
	 * 表单验证 通过返回true  失败返回false
	 */
	var validate = function(){
		if(!Validation.notNull(dialog, departmentSN, departmentSN.val(), '请填写机构编号!')){
			return false;
		}
		if(!Validation.serialNmuber(dialog, departmentSN, departmentSN.val(), '请填写正确的机构编号!')){
			return false;
		}
		if(!Validation.notNull(dialog, departmentName, departmentName.val(), '请填写机构名称!')){
			return false;
		}
		return true;
	};
	/**
	 * 显示提示信息
	 */
	var showErrorMessage = function($element, content){
		$element.popover({
			content: content,
			trigger: 'manual',
			container: dialog
		}).popover('show').on({
			'blur': function(){
				$element.popover('destroy');
				$element.parent().removeClass('has-error');
			},
			'keydown': function(){
				$element.popover('destroy');
				$element.parent().removeClass('has-error');
			}
		}).focus().parent().addClass('has-error');
	};
	/**
	 * 检查变量是否不为空  true:不空   false:空
	 */
	var checkNotNull = function(item){
		//不能为空和空格
		if(item==null || item=="" || item.replace(/(^\s*)|(\s*$)/g, "")=="" ){
			return false;
		}else{
			return true;
		}
	};
	/**
	 * 生成部门树
	 */
	var getTree = function(id){
		$('#departmentTree').loader({
			opacity: 0
		});
        $.get(baseUrl + 'org-tree.koala').done(function(data){
        	$('#departmentTree').loader('hide');
            var zNodes = new Array();
            $.each(data, function(){
                var zNode = {};
                if(this.organizationType == 'Company'){
                    zNode.type = 'parent';
                }else{
                    zNode.icon = 'glyphicon glyphicon-list-alt'
                }
                this.title = this.name;
                zNode.menu = this;
                if(this.children && this.children.length > 0){
                    zNode.children = getChildrenData(new Array(), this.children);
                }
                zNodes.push(zNode);
            });
            var dataSourceTree = {
                data: zNodes,
                delay: 400
            };
            $('#departmentTree').off().data('koala.tree', null).tree({
                dataSource: dataSourceTree,
                loadingHTML: '
Loading...
',
                multiSelect: false,
                cacheItems: true
            }).on({
                'contextmenu': function(e){
                    return false;
                },
                'rightClick': function(e, originalEvent){
                    createRightMenu(originalEvent);
                },
                'selectParent': function(event, data){
                    showDepartmentDetail(data.data.id);
                },
                'selectChildren': function(event, data){
                    showDepartmentDetail(data.id);
                },
                'addCompany': function(event, data){
                    var $element = $(data);
                    var data = $element.data();
                    addCompany(data.id, $element);
                },
                'addDepartment': function(event, data){
                    var $element = $(data);
                    var data = $element.data();
                    addDepartment(data.id, data.organizationType, $element);
                },
                'update': function(event, data){
                    var $element = $(data);
                    var data = $element.data();
                    if(data.organizationType == 'Company'){
                        updateCompany(data.id, $element);
                    }else{
                        updateDepartment(data.id, $element);
                    }
                },
                'delete': function(event, data){
                    var $element = $(data);
                    var data = $element.data();
                    $(this).confirm({
                        content: '确定要撤销该机构吗?',
                        callBack: function(){
                            var type = data.organizationType;
                            delete data.children;
                            delete data.organizationType;
                            department().del(data, type, $element);
                        }
                    });
                }
            });
        	if(id){
        		var $element = $('#departmentTree').find('#'+id).click();
        		if($element.hasClass('tree-folder')){
        			$element.find('.tree-folder-header:first').click();
        		}
        		$element.parents().filter('.tree-folder-content').each(function(){
        			var $this = $(this);
					$this.show()
						 .prev('.tree-folder-header')
						 .find('.glyphicon-folder-close')
						 .removeClass('glyphicon-folder-close')
						 .addClass('glyphicon-folder-open');
        		});
        	}else{
                if ($('#departmentTree').find('.tree-folder-header:first').length != 0) {
                    $('#departmentTree').find('.tree-folder-header:first').click();
                } else {
                    $('#departmentTree').find('.tree-item:first').click();
                }

        	}
        });
	};
    var createRightMenu = function(ev){
        var $element = $(ev.currentTarget);
        var menuData = null;
        menuData = [
            {title:'创建分公司', action: 'addCompany'},
            {title:'创建下级部门', action: 'addDepartment'},
            {title:'修改机构信息', action: 'update'},
            {title:'撤销', action: 'delete'}
        ];
        if($element.data('organizationType') == 'Company'){
            menuData = [
                {title:'创建分公司', action: 'addCompany'},
                {title:'创建下级部门', action: 'addDepartment'},
                {title:'修改机构信息', action: 'update'},
                {title:'撤销', action: 'delete'}
            ];
        }else{
            menuData = [
                {title:'创建下级部门', action: 'addDepartment'},
                {title:'修改机构信息', action: 'update'},
                {title:'撤销', action: 'delete'}
            ];
        }
        $('#departmentTree').tree('createRightMenu', {event:ev, element: $element, data:menuData});
    };

    var getChildrenData = function(nodes, items){
        $.each(items, function(){
            var zNode = {};
            if(this.organizationType == 'Company'){
                zNode.type = 'parent';
            }else{
                zNode.icon = 'glyphicon glyphicon-list-alt'
            }
            this.title = this.name;
            zNode.menu = this;
            if(this.children && this.children.length > 0){
                zNode.children = getChildrenData(new Array(), this.children);
            }
            nodes.push(zNode);
        });
        return nodes;
    };

	var showDepartmentDetail =  function(id){
		$.get(contextPath + '/organization/get.koala?id='+id).done(function(data){
			var org = data;
			var departmentDetail = $('.right-content');
			departmentDetail.find('[data-role="id"]').val(org.id);
			departmentDetail.find('[data-role="number"]').text(org.sn);
			departmentDetail.find('[data-role="name"]').text(org.name == null ? '':org.name);
			departmentDetail.find('[data-role="description"]').text(org.description == null ? '':org.description);
			departmentDetail.find('[data-role="principalName"]').text(org.principalName == null ? '':org.principalName);
			departmentDetail.find('[data-role="organizationType"]').val(org.organizationType);
			if(org.organizationType == 'Company'){
				$('#addCompany').show();
				$('#updateCompany').show();
				$('#updateDepartment').hide();
			}else{
				$('#addCompany').hide();
				$('#updateCompany').hide();
				$('#updateDepartment').show();
			}
		}).fail(function(data){
			$('body').message({
				type: 'error',
				content: '无法获取该部门信息'
			});
		});
	};

	var showEmployeeList = function(id){
		$.get( contextPath + '/pages/organisation/department-employee-list.jsp').done(function(data){
			var employeeListDialog = $(data);
			employeeListDialog.find('#deleteRelation').on('click',function(){
				var grid = employeeListDialog.find('#employeeList');
				deleteEmployeeRelation(employeeListDialog, id, grid.data('koala.grid').selectedRows() , grid);
			}).end().modal({
					keyboard: false
				}).on({
					'shown.bs.modal': function(){
						loadEmployeeList(employeeListDialog,id);
					},
					'hidden.bs.modal': function(){
						/*====解除员工后关闭弹出框重新加载该公司信息=======*/
						if(id){
		            		var $element = $('#departmentTree').find('#'+id).click();
		            		if($element.hasClass('tree-folder')){
		            			$element.find('.tree-folder-header:first').click();
		            		}
		            		$element.parents().filter('.tree-folder-content').each(function(){
		            			var $this = $(this);
								$this.show()
									 .prev('.tree-folder-header')
									 .find('.glyphicon-folder-close')
									 .removeClass('glyphicon-folder-close')
									 .addClass('glyphicon-folder-open');
		            		});
		            	}else{
		            		$('#departmentTree').find('.tree-folder-header:first').click();
		            	}
						/*==============================================	*/
						$(this).remove();
					}
				});

                //兼容IE8 IE9
                if(window.ActiveXObject){
                   if(parseInt(navigator.userAgent.toLowerCase().match(/msie ([\d.]+)/)[1]) < 10){
                       employeeListDialog.trigger('shown.bs.modal');
                   }
                }
		});
	};
	var loadEmployeeList = function(employeeListDialog, id){
		var cols = [
			{ title:'编号', name:'sn' , width: '150px'},
			{ title:'姓名', name:'name', width: '150px'},
			{ title:'性别', name:'gender' , width: '100px',
				render: function(item, name, index){
					if(item[name] == 'FEMALE'){
						return '女';
					}else{
						return '男';
					}
				}
			},
			{ title:'岗位', name:'postName' , width: 'auto'}
		];
		var buttons = [{content: '

 显示下属机构员工
', action: 'queryAllChildren'}];
		var  departmentEmployeeGrid = employeeListDialog.find('#employeeList');
		departmentEmployeeGrid.grid({
			identity: 'id',
			columns: cols,
			buttons: buttons,
			querys: [{title: '姓名', value: 'name'}],
			url:  contextPath + '/employee/pagingquery-by-org.koala?organizationId='+id
		});
		departmentEmployeeGrid.find('#queryAllChildren').on('click', function(){
			var $span = $(this).find('span');
			departmentEmployeeGrid.data('koala.grid').search({queryAllChildren: !$span.hasClass('checked')});
			$span.toggleClass('checked');
			if ($span.hasClass('checked')) {
				employeeListDialog.find('#deleteRelation').hide();
			} else {
				employeeListDialog.find('#deleteRelation').show();
			}
		});
	};
	var deleteEmployeeRelation = function(employeeListDialog, id, items, grid){
		if(items.length == 0){
			employeeListDialog.find('.modal-content').message({
				type: 'warning',
				content: '请选择要解除关系的员工'
			});
			return;
		}
		grid.confirm({
            backdrop: false,
			content: '确定要与所选员工解除关系吗?',
			callBack: function(){
				$.ajax({
					headers: {
						'Accept': 'application/json',
						'Content-Type': 'application/json'
					},
					'type': "Post",
					'url':  contextPath + '/organization/terminate-eo-relations.koala?organizationId=' + id,
					'data': JSON.stringify(items),
					'dataType': 'json'
				}).done(function(data){
					if(data.success){
						$('body').message({
							type: 'success',
							content: '解除关系成功'
						});
						grid.grid('refresh');
					}else{
						employeeListDialog.find('.modal-content').message({
							type: 'error',
							content: data.errorMessage
						});
					}
				});
			}
		});
	};
	return {
		addDepartment: addDepartment,
		addCompany: addCompany,
		updateDepartment: updateDepartment,
		updateCompany: updateCompany,
		del: del,
		getTree: getTree,
		showEmployeeList:showEmployeeList
	};
};


text:
<?php

class ForumUser extends ForumAppModel {

    /**
     * Force the model to act like the User model.
     *
     * @type string
     */
    public $name = USER_MODEL;
    public $alias = USER_MODEL;

    /**
     * No prefix on users table.
     *
     * @type string
     */
    public $tablePrefix = null;

    /**
     * Disable admin.
     *
     * @type bool
     */
    public $admin = false;

    /**
     * Get the newest signup.
     *
     * @return array
     */
    public function getNewestUser() {
        return $this->find('first', array(
            'order' => array('User.created' => 'DESC'),
            'limit' => 1,
            'cache' => __METHOD__
        ));
    }

    /**
     * Increase the post count.
     *
     * @param int $user_id
     * @return bool
     */
    public function increasePosts($user_id) {
        $field = Configure::read('User.fieldMap.totalPosts');

        if (!$this->hasField($field)) {
            return false;
        }

        return $this->updateAll(
            array('User.' . $field => 'User.' . $field . ' + 1'),
            array('User.id' => $user_id)
        );
    }

    /**
     * Increase the topic count.
     *
     * @param int $user_id
     * @return bool
     */
    public function increaseTopics($user_id) {
        $field = Configure::read('User.fieldMap.totalTopics');

        if (!$this->hasField($field)) {
            return false;
        }

        return $this->updateAll(
            array('User.' . $field => 'User.' . $field . ' + 1'),
            array('User.id' => $user_id)
        );
    }

    /**
     * Get who's online within the past x minutes.
     *
     * @return array
     */
    public function whosOnline() {
        $minutes = Configure::read('Forum.settings.whosOnlineInterval');
        $currentLogin = Configure::read('User.fieldMap.currentLogin');

        if (!$currentLogin) {
            return null;
        }

        return $this->find('all', array(
            'conditions' => array('User.' . $currentLogin . ' >' => date('Y-m-d H:i:s', strtotime($minutes))),
            'cache' => array(__METHOD__, $minutes),
            'cacheExpires' => '+15 minutes'
        ));
    }

}


text:
:: Copyright 2015 Google Inc. All rights reserved.
::
:: Licensed 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.

set buildtype=Release
if "%1"=="-b" set buildtype=%2

..\%buildtype%\flatc.exe --cpp --java --csharp --dart --go --binary --lobster --lua --python --js --ts --php --rust --grpc --gen-mutable --reflect-names --gen-object-api --gen-compare --no-includes --cpp-ptr-type flatbuffers::unique_ptr  --no-fb-import -I include_test monster_test.fbs monsterdata_test.json || goto FAIL
..\%buildtype%\flatc.exe --cpp --java --csharp --dart --go --binary --lobster --lua --python --js --ts --php --rust --gen-mutable --reflect-names --no-fb-import --cpp-ptr-type flatbuffers::unique_ptr  -o namespace_test namespace_test/namespace_test1.fbs namespace_test/namespace_test2.fbs || goto FAIL
..\%buildtype%\flatc.exe --cpp --java --csharp --js --ts --php --gen-mutable --reflect-names --gen-object-api --gen-compare --cpp-ptr-type flatbuffers::unique_ptr -o union_vector ./union_vector/union_vector.fbs || goto FAIL
..\%buildtype%\flatc.exe -b --schema --bfbs-comments --bfbs-builtins -I include_test monster_test.fbs || goto FAIL
..\%buildtype%\flatc.exe -b --schema --bfbs-comments --bfbs-builtins -I include_test arrays_test.fbs || goto FAIL
..\%buildtype%\flatc.exe --jsonschema --schema -I include_test monster_test.fbs || goto FAIL
..\%buildtype%\flatc.exe --cpp --java --csharp --python --gen-mutable --reflect-names --gen-object-api --gen-compare --no-includes --scoped-enums --jsonschema --cpp-ptr-type flatbuffers::unique_ptr arrays_test.fbs || goto FAIL
..\%buildtype%\flatc.exe --cpp --gen-mutable --gen-object-api --reflect-names --cpp-ptr-type flatbuffers::unique_ptr native_type_test.fbs || goto FAIL

IF NOT "%MONSTER_EXTRA%"=="skip" (
  @echo Generate MosterExtra
  ..\%buildtype%\flatc.exe --cpp --java --csharp --python --gen-mutable --reflect-names --gen-object-api --gen-compare --no-includes monster_extra.fbs monsterdata_extra.json || goto FAIL
) else (
  @echo monster_extra.fbs skipped (the strtod function from MSVC2013 or older doesn't support NaN/Inf arguments)
)

cd ../samples
..\%buildtype%\flatc.exe --cpp --lobster --gen-mutable --reflect-names --gen-object-api --gen-compare --cpp-ptr-type flatbuffers::unique_ptr monster.fbs || goto FAIL
..\%buildtype%\flatc.exe -b --schema --bfbs-comments --bfbs-builtins monster.fbs || goto FAIL
cd ../reflection
call generate_code.bat %1 %2 || goto FAIL

set EXITCODE=0
goto SUCCESS
:FAIL
set EXITCODE=1
:SUCCESS
cd ../tests
EXIT /B %EXITCODE%


text:
""" Entities """

import json

class JSONSerializable():
    """ Class to simplify the JSON serialization """

    def __json_dict__(self):
        """ Method to remove _ (underscore) from beggining of the attribute name """
        simple_dict = self.__dict__.copy()

        for key in simple_dict.keys():
            if key.startswith('_'):
                new_key = key[1:]
                simple_dict[new_key] = simple_dict[key]
                del simple_dict[key]

        return simple_dict

    def to_json(self):
        """ Generates JSON representation"""
        return json.dumps(self.__json_dict__(), sort_keys=True,
                          cls=ComplexEncoder, ensure_ascii=False)

class BusLineItem(JSONSerializable):
    """ This class represents a bus line """

    def __init__(self, code, name):
        """ __init__  """
        self._code = code
        self._name = name

    @property
    def code(self):
        """ getter method """
        return self._code

    @code.setter
    def code(self, value):
        """ setter method """
        self._code = value

    @property
    def name(self):
        """ getter method """
        return self._name

    @name.setter
    def name(self, value):
        """ setter method """
        self._name = value

    def __repr__(self):
        """ Representation to this class """
        return self.__str__()

    def __str__(self):
        """ to string method """
        return self.to_json()

class BusLine(JSONSerializable):
    """ This is a bus line which has a schedule """

    def __init__(self, name, code):
        """ __init__ """
        self._name = name
        self._code = code
        self._schedules = []

    def add_schedule(self, schedule):
        """ method to add a new schedule to the bus """
        self._schedules.append(schedule)

    @property
    def schedules(self):
        """ schedules getter """
        return self._schedules

    @property
    def name(self):
        """ name getter """
        return self._name

    @property
    def code(self):
        """ code getter """
        return self._code

    def __str__(self):
        """ to string method """

        string = 'BusLine: {} - {}\n'.format(self._code, self._name)
        for sch in self._schedules:
            string += 'Direction: {}, Schedule Type: {}\n'.format(sch.direction, sch.schedule_day)

            for deperture in sch.timetable:
                string += '{}\n'.format(deperture)

        return string

class Schedule(JSONSerializable):
    """ Class that represents a full bus's schedule"""
    def __init__(self, schedule_day, direction, departures):
        """ __init__ """
        self._schedule_day = schedule_day
        self._direction = direction
        self._timetable = [] if departures is None else departures

    def add_departure_time(self, time):
        """ method to add a new time to depertures list"""
        self._timetable.append(time)

    @property
    def schedule_day(self):
        """ schedule_day getter """
        return self._schedule_day

    @property
    def direction(self):
        """ direction getter """
        return self._direction

    @property
    def timetable(self):
        """ timetable getter"""
        return self._timetable

    def  __str__(self):
        """ to string method """
        return self.to_json()

class ComplexEncoder(json.JSONEncoder):
    """ Helper class to enable JSON convertion """
    def default(self, o):
        """ This is the default method"""
        if hasattr(o, '__json_dict__'):
            return o.__json_dict__()

        return json.JSONEncoder.default(self, o)


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

<title>org.gradle.api.file (Gradle API 2.3)</title>
<meta name="keywords" content="org.gradle.api.file package">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" title="Style">
<link href="../../../../groovy.ico" type="image/x-icon" rel="shortcut icon">
<link href="../../../../groovy.ico" type="image/x-icon" rel="icon">

Overview

Package

Class

Deprecated

Index

Help

Frames

No Frames

Package org.gradle.api.file

 Classes for working with files.

Interface Summary

                        Interface
                        Description

                                    ConfigurableFileCollection

                                    ConfigurableFileTree

                                    ContentFilterable

                            Represents some binary resource whose content can be filtered.

                                    CopyProcessingSpec

                            Specifies the destination of a copy.

                                    CopySourceSpec

                            Specifies sources for a file copy.

                                    CopySpec

                            A set of specifications for copying files.

                                    DeleteAction

                            Deletes files and directories.

                                    DirectoryTree

                                    FileCollection

                                    FileCopyDetails

                                    FileTree

                                    FileTreeElement

                            Information about a file in a FileTree.

                                    FileVisitDetails

                            Provides access to details about a file or directory being visited by a FileVisitor.

                                    FileVisitor

                                    SourceDirectorySet

Class Summary

                        Class
                        Description

                                    EmptyFileVisitor

                            The EmptyFileVisitor can be extends by implementations that only require to implement one of the 2 visit methods
 (dir or file).

                                    RelativePath

Enum Summary

                        Enum
                        Description

                                    DuplicatesStrategy

                            Strategies for dealing with the potential creation of duplicate files for or archive entries.

                                    FileCollection.AntType

                            Ant types which a FileCollection can be mapped to.

Exception Summary

                        Exception
                        Description

                                    DuplicateFileCopyingException

                            Thrown when more than one file with the same relative path name is to be copied
 and the DuplicatesStrategy is set to DuplicatesStrategy.FAIL

                                    UnableToDeleteFileException

                            Thrown by Gradle when it is unable to delete a file.

Overview

Package

Class

Deprecated

Index

Help

Frames

No Frames

Gradle API 2.3


text:
mkdir -p build
g++ -S hello_world.cpp -o build/hello_world.s


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Interface com.thinkaurelius.titan.diskstorage.WriteBuffer (Titan 1.0.0 API)</title>
<meta name="date" content="2015-09-19">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Interface
com.thinkaurelius.titan.diskstorage.WriteBuffer

Packages that use WriteBuffer

Package
Description

com.thinkaurelius.titan.core.attribute

com.thinkaurelius.titan.diskstorage

com.thinkaurelius.titan.diskstorage.util

com.thinkaurelius.titan.graphdb.database.idhandling

com.thinkaurelius.titan.graphdb.database.serialize

com.thinkaurelius.titan.graphdb.database.serialize.attribute

Uses of WriteBuffer in com.thinkaurelius.titan.core.attribute

Methods in com.thinkaurelius.titan.core.attribute with parameters of type WriteBuffer

Modifier and Type
Method and Description

void
Geoshape.GeoshapeSerializer.write(WriteBuffer buffer,
     Geoshape attribute)

void
AttributeSerializer.write(WriteBuffer buffer,
     V attribute)

Writes the attribute value to the given WriteBuffer.

Uses of WriteBuffer in com.thinkaurelius.titan.diskstorage

Methods in com.thinkaurelius.titan.diskstorage that return WriteBuffer

Modifier and Type
Method and Description

WriteBuffer
WriteBuffer.putBoolean(boolean val)

WriteBuffer
WriteBuffer.putByte(byte val)

WriteBuffer
WriteBuffer.putBytes(byte[] val)

WriteBuffer
WriteBuffer.putBytes(StaticBuffer val)

WriteBuffer
WriteBuffer.putChar(char val)

WriteBuffer
WriteBuffer.putDouble(double val)

WriteBuffer
WriteBuffer.putFloat(float val)

WriteBuffer
WriteBuffer.putInt(int val)

WriteBuffer
WriteBuffer.putLong(long val)

WriteBuffer
WriteBuffer.putShort(short val)

Uses of WriteBuffer in com.thinkaurelius.titan.diskstorage.util

Classes in com.thinkaurelius.titan.diskstorage.util that implement WriteBuffer

Modifier and Type
Class and Description

class
WriteByteBuffer

Methods in com.thinkaurelius.titan.diskstorage.util that return WriteBuffer

Modifier and Type
Method and Description

static WriteBuffer
WriteBufferUtil.put(WriteBuffer out,
   byte[] bytes)

static WriteBuffer
WriteBufferUtil.put(WriteBuffer out,
   StaticBuffer in)

WriteBuffer
WriteByteBuffer.putBoolean(boolean val)

WriteBuffer
WriteByteBuffer.putByte(byte val)

WriteBuffer
WriteByteBuffer.putBytes(byte[] val)

WriteBuffer
WriteByteBuffer.putBytes(StaticBuffer val)

WriteBuffer
WriteByteBuffer.putChar(char val)

WriteBuffer
WriteByteBuffer.putDouble(double val)

WriteBuffer
WriteByteBuffer.putFloat(float val)

WriteBuffer
WriteByteBuffer.putInt(int val)

WriteBuffer
WriteByteBuffer.putLong(long val)

WriteBuffer
WriteByteBuffer.putShort(short val)

Methods in com.thinkaurelius.titan.diskstorage.util with parameters of type WriteBuffer

Modifier and Type
Method and Description

static WriteBuffer
WriteBufferUtil.put(WriteBuffer out,
   byte[] bytes)

static WriteBuffer
WriteBufferUtil.put(WriteBuffer out,
   StaticBuffer in)

Uses of WriteBuffer in com.thinkaurelius.titan.graphdb.database.idhandling

Methods in com.thinkaurelius.titan.graphdb.database.idhandling with parameters of type WriteBuffer

Modifier and Type
Method and Description

static void
VariableLong.write(WriteBuffer out,
     long value)

static void
VariableLong.writeBackward(WriteBuffer out,
             long value)

static void
IDHandler.writeInlineRelationType(WriteBuffer out,
                       long relationTypeId)

static void
VariableLong.writePositive(WriteBuffer out,
             long value)

static void
VariableLong.writePositiveBackward(WriteBuffer out,
                     long value)

static void
VariableLong.writePositiveWithPrefix(WriteBuffer out,
                       long value,
                       long prefix,
                       int prefixBitLen)

static void
IDHandler.writeRelationType(WriteBuffer out,
                 long relationTypeId,
                 IDHandler.DirectionID dirID,
                 boolean invisible)

The edge type is written as follows: [ Invisible & System (2 bit) | Relation-Type-ID (1 bit) | Relation-Type-Count (variable) | Direction-ID (1 bit)]
 Would only need 1 bit to store relation-type-id, but using two so we can upper bound.

Uses of WriteBuffer in com.thinkaurelius.titan.graphdb.database.serialize

Subinterfaces of WriteBuffer in com.thinkaurelius.titan.graphdb.database.serialize

Modifier and Type
Interface and Description

interface
DataOutput

Methods in com.thinkaurelius.titan.graphdb.database.serialize with parameters of type WriteBuffer

Modifier and Type
Method and Description

void
NoSerializer.write(WriteBuffer buffer,
     V attribute)

void
OrderPreservingSerializer.writeByteOrder(WriteBuffer buffer,
              V attribute)

Writes the attribute value to the given WriteBuffer such that the byte order of the result is equal to the
 natural order of the attribute.

Uses of WriteBuffer in com.thinkaurelius.titan.graphdb.database.serialize.attribute

Methods in com.thinkaurelius.titan.graphdb.database.serialize.attribute with parameters of type WriteBuffer

Modifier and Type
Method and Description

void
BooleanSerializer.write(WriteBuffer out,
     Boolean attribute)

void
BooleanArraySerializer.write(WriteBuffer buffer,
     boolean[] attribute)

void
ByteSerializer.write(WriteBuffer out,
     Byte object)

void
ByteArraySerializer.write(WriteBuffer buffer,
     byte[] attribute)

void
CharArraySerializer.write(WriteBuffer buffer,
     char[] attribute)

void
CharacterSerializer.write(WriteBuffer out,
     Character attribute)

void
DateSerializer.write(WriteBuffer out,
     Date attribute)

void
DoubleSerializer.write(WriteBuffer buffer,
     Double attribute)

void
DoubleArraySerializer.write(WriteBuffer buffer,
     double[] attribute)

void
DurationSerializer.write(WriteBuffer buffer,
     java.time.Duration attribute)

void
EnumSerializer.write(WriteBuffer out,
     E object)

void
FloatSerializer.write(WriteBuffer buffer,
     Float attribute)

void
FloatArraySerializer.write(WriteBuffer buffer,
     float[] attribute)

void
InstantSerializer.write(WriteBuffer buffer,
     java.time.Instant attribute)

void
IntArraySerializer.write(WriteBuffer buffer,
     int[] attribute)

void
IntegerSerializer.write(WriteBuffer out,
     Integer attribute)

void
LongSerializer.write(WriteBuffer out,
     Long attribute)

void
LongArraySerializer.write(WriteBuffer buffer,
     long[] attribute)

void
ObjectSerializer.write(WriteBuffer buffer,
     Object attribute)

void
ParameterSerializer.write(WriteBuffer buffer,
     Parameter attribute)

void
ParameterArraySerializer.write(WriteBuffer buffer,
     Parameter[] attribute)

void
ShortSerializer.write(WriteBuffer out,
     Short object)

void
ShortArraySerializer.write(WriteBuffer buffer,
     short[] attribute)

void
StandardTransactionIdSerializer.write(WriteBuffer buffer,
     StandardTransactionId attribute)

void
StringSerializer.write(WriteBuffer buffer,
     String attribute)

void
StringArraySerializer.write(WriteBuffer buffer,
     String[] attribute)

void
TypeDefinitionDescriptionSerializer.write(WriteBuffer buffer,
     TypeDefinitionDescription attribute)

void
UUIDSerializer.write(WriteBuffer buffer,
     UUID attribute)

void
BooleanSerializer.writeByteOrder(WriteBuffer buffer,
              Boolean attribute)

void
ByteSerializer.writeByteOrder(WriteBuffer buffer,
              Byte attribute)

void
CharacterSerializer.writeByteOrder(WriteBuffer buffer,
              Character attribute)

void
DateSerializer.writeByteOrder(WriteBuffer buffer,
              Date attribute)

void
DoubleSerializer.writeByteOrder(WriteBuffer buffer,
              Double attribute)

void
EnumSerializer.writeByteOrder(WriteBuffer buffer,
              E attribute)

void
FloatSerializer.writeByteOrder(WriteBuffer buffer,
              Float attribute)

void
IntegerSerializer.writeByteOrder(WriteBuffer out,
              Integer attribute)

void
LongSerializer.writeByteOrder(WriteBuffer out,
              Long attribute)

void
ShortSerializer.writeByteOrder(WriteBuffer buffer,
              Short attribute)

void
StringSerializer.writeByteOrder(WriteBuffer buffer,
              String attribute)

protected void
ArraySerializer.writeLength(WriteBuffer buffer,
           Object array)

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2012–2015. All rights reserved.


text:
package com.amazonaws.services.simpleemailv2.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.simpleemailv2.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * GetCustomVerificationEmailTemplateRequestMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class GetCustomVerificationEmailTemplateRequestMarshaller {

    private static final MarshallingInfo<String> TEMPLATENAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PATH)
            .marshallLocationName("TemplateName").build();

    private static final GetCustomVerificationEmailTemplateRequestMarshaller instance = new GetCustomVerificationEmailTemplateRequestMarshaller();

    public static GetCustomVerificationEmailTemplateRequestMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(GetCustomVerificationEmailTemplateRequest getCustomVerificationEmailTemplateRequest, ProtocolMarshaller protocolMarshaller) {

        if (getCustomVerificationEmailTemplateRequest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(getCustomVerificationEmailTemplateRequest.getTemplateName(), TEMPLATENAME_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
package org.cyclops.integrateddynamics.core.evaluate.operator;

import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import org.cyclops.integrateddynamics.Reference;
import org.cyclops.integrateddynamics.api.evaluate.EvaluationException;
import org.cyclops.integrateddynamics.api.evaluate.variable.IValue;
import org.cyclops.integrateddynamics.api.evaluate.variable.IValueCastRegistry;
import org.cyclops.integrateddynamics.api.evaluate.variable.IValueType;
import org.cyclops.integrateddynamics.api.logicprogrammer.IConfigRenderPattern;
import org.cyclops.integrateddynamics.core.helper.L10NValues;

import java.util.List;

/**
 * Base class for cast operators.
 * @author rubensworks
 */
public class CastOperator<T1 extends IValueType<V1>, T2 extends IValueType<V2>, V1 extends IValue, V2 extends IValue> extends OperatorBase {

    private final T1 from;
    private final T2 to;
    private final IValueCastRegistry.IMapping<T1, T2, V1, V2> mapping;

    public CastOperator(final T1 from, final T2 to, final IValueCastRegistry.IMapping<T1, T2, V1, V2> mapping) {
        super("()", from.getTranslationKey() + "$" + to.getTranslationKey(), constructInputVariables(1, from), to, new IFunction() {
            @Override
            public IValue evaluate(SafeVariablesGetter variables) throws EvaluationException {
                IValue value = variables.getValue(0);
                if(value.getType() != from) {
                    throw new EvaluationException(Component.translatable(
                            L10NValues.OPERATOR_ERROR_CAST_UNEXPECTED, Component.translatable(value.getType().getTranslationKey()), Component.translatable(from.getTranslationKey()), Component.translatable(to.getTranslationKey())));
                }
                return mapping.cast((V1) value);
            }
        }, IConfigRenderPattern.PREFIX_1);
        this.from = from;
        this.to = to;
        this.mapping = mapping;
    }

    @Override
    public ResourceLocation getUniqueName() {
        return new ResourceLocation(Reference.MOD_ID, "operator." + getModId() + ".cast"
                + from.getUniqueName().toString().replaceAll(":", "_") + "__"
                + to.getUniqueName().toString().replaceAll(":", "_"));
    }

    @Override
    public String getUnlocalizedType() {
        return "cast";
    }

    @Override
    protected String getUnlocalizedPrefix() {
        return "operator." + getModId() + "." + getUnlocalizedType();
    }

    @Override
    public void loadTooltip(List<Component> lines, boolean appendOptionalInfo) {
        lines.add(Component.translatable("operator.integrateddynamics.cast.tooltip",
                Component.translatable(from.getTranslationKey()),
                Component.translatable(to.getTranslationKey())));
        super.loadTooltip(lines, appendOptionalInfo);
    }

}


text:
'''
  Monitor a given webpage and notify the website maintainer if the page fails to load 3 times in one minute.
'''

api_url = 'http://restyourdroid.com/f/ae4564ss'  #  change to the url of your android device
url_to_monitor = 'http://restyourdroid.com' # change to the page you want to monitor
target_text = 'Download the app now!' # some text that should appear in the page

import logging
import time
import urllib2

logging.basicConfig(format="%(asctime)s: %(message)s", level=logging.INFO)
failures = 0

while True:
    try:
        response = urllib2.urlopen(url_to_monitor)
        html = response.read()
        if target_text not in html:
            logging.info('Did not find target text in page.')
            failures += 1
        else:
            logging.info('Everything looks ok.')
            if failures>0:
                failures -= 1
    except Exception as exp:
        logging.exception('Received exception while fetching %s' % url_to_monitor)
        failures += 1

    if failures>=3:
        logging.info('3 failures in last minute, notifying maintainer...')
        urllib2.urlopen("%s/notify" % api_url, "title=Server down!&text=3 failures in last minute. Please check %s" % url_to_monitor).read()
        failures = 0
        time.sleep(300)  # don't send a notification for 5 minutes
    else:
        time.sleep(20)  # check url again in 20 seconds


text:
test -d digits && cd digits

if ! test -d ../source; then
  echo >&2 "Please run me in the digits/ directory"
  exit 1
fi

function create () {
	out="$1";
	shift;
	echo "Creating $out.ogg..."
	flac -s -d --endian little --sign signed --force-raw-format -c "$@" |
	oggenc -Q --downmix --resample 22050 -r - -o $out.ogg
}

create blob ../source/blob.flac
for d in {0..9}; do
	create english_$d ../source/english_$d.flac
done


text:
package org.wso2.test.http.netty.proxy.sql;

import io.netty.channel.ChannelHandlerContext;
import org.wso2.test.http.netty.proxy.DelayingProxyFrontendHandler;
import org.wso2.test.http.netty.proxy.config.ProxyConfigEntry;

import java.util.concurrent.ScheduledExecutorService;

public class SqlFrontendHandler extends DelayingProxyFrontendHandler {

    public SqlFrontendHandler(ProxyConfigEntry proxyConfigEntry, ScheduledExecutorService scheduledExecutorService) {
        super(proxyConfigEntry, scheduledExecutorService);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        //Match query with the available regex, then apply delay if regex matched. log the matched regex id.
        System.out.println(msg);
        super.channelRead(ctx, msg);
    }
}


text:
#ifndef _ONYX_ACPI_H
#define _ONYX_ACPI_H

#include <stdint.h>

#include <onyx/dev.h>

#include <acpica/acpi.h>

struct acpi_processor
{
    ACPI_HANDLE object;
#ifdef __x86_64__
    uint32_t apic_id;
#endif
};

struct acpi_device : public device
{
    ACPI_HANDLE object;
    ACPI_DEVICE_INFO *info;
    ACPI_RESOURCE *resources;

    acpi_device(const char *name, struct bus *b, device *parent, ACPI_HANDLE obj,
                ACPI_DEVICE_INFO *info, ACPI_RESOURCE *rsrc)
        : device{name, b, parent}, object{obj}, info{info}, resources{rsrc}
    {
    }
};

struct acpi_dev_id
{
    const char *devid;
};

#define ACPI_PIC_PIC     0
#define ACPI_PIC_IOAPIC  1
#define ACPI_PIC_IOSAPIC 1

#define ACPI_POWER_STATE_D0 0
#define ACPI_POWER_STATE_D1 1
#define ACPI_POWER_STATE_D2 2
#define ACPI_POWER_STATE_D3 3

uintptr_t acpi_get_rsdp(void);

int acpi_initialize(void);

uint32_t acpi_shutdown(void);

uint32_t acpi_execute_pic(int value);

int acpi_get_irq_routing_tables();

struct acpi_processor *acpi_enumerate_cpus(void);

struct acpi_device *acpi_get_device(const char *id);

unsigned int acpi_suspend(void);

void acpi_bus_register_driver(struct driver *driver);

ACPI_RESOURCE *acpi_get_resource(struct acpi_device *device, uint32_t type, unsigned int index);

extern struct clocksource acpi_timer_source;

namespace acpi
{

using find_root_pci_bus_t = int (*)(uint16_t seg, uint8_t nbus, ACPI_HANDLE bus);
int find_root_pci_buses(find_root_pci_bus_t callback);
int route_irqs(bus *bus);
bool is_enabled();

#ifndef CONFIG_ACPI
inline bool is_enabled()
{
    return false;
}
#endif

} // namespace acpi

#endif


text:
package org.onosproject.vtnrsc.cli.floatingip;

import java.util.Set;

import org.apache.karaf.shell.commands.Command;
import org.apache.karaf.shell.commands.Option;
import org.onosproject.cli.AbstractShellCommand;
import org.onosproject.vtnrsc.FloatingIp;
import org.onosproject.vtnrsc.FloatingIpId;
import org.onosproject.vtnrsc.floatingip.FloatingIpService;

import com.google.common.collect.Sets;

/**
 * Supports for remove a floating IP.
 */
@Command(scope = "onos", name = "floatingip-remove", description = "Supports for removing a floating IP")
public class FloatingIpRemoveCommand extends AbstractShellCommand {
    @Option(name = "-I", aliases = "--id", description = "The floating IP identifier",
            required = false, multiValued = false)
    String id = null;

    @Option(name = "-i", aliases = "--fixedIp", description = "The fixed IP of floating IP",
            required = false, multiValued = false)
    String fixedIp = null;

    @Option(name = "-l", aliases = "--floatingIp", description = "The floating IP of floating IP",
            required = false, multiValued = false)
    String floatingIp = null;

    @Override
    protected void execute() {
        FloatingIpService service = get(FloatingIpService.class);
        if (id == null && fixedIp == null && floatingIp == null) {
            print(null, "one of id, fixedIp, floatingIp should not be null");
        }
        try {
            Set<FloatingIpId> floatingIpSet = Sets.newHashSet();
            if (id != null) {
                floatingIpSet.add(FloatingIpId.of(id));
                service.removeFloatingIps(floatingIpSet);
            } else {
                Iterable<FloatingIp> floatingIps = service.getFloatingIps();
                if (floatingIps == null) {
                    return;
                }
                if (fixedIp != null) {
                    for (FloatingIp floatingIp : floatingIps) {
                        if (floatingIp.fixedIp().toString().equals(fixedIp)) {
                            floatingIpSet.add(floatingIp.id());
                            service.removeFloatingIps(floatingIpSet);
                            return;
                        }
                    }
                    print(null, "The fixedIp is not existed");
                    return;
                }
                if (floatingIp != null) {
                    for (FloatingIp floatingIpObj : floatingIps) {
                        if (floatingIpObj.fixedIp().toString()
                                .equals(floatingIp)) {
                            floatingIpSet.add(floatingIpObj.id());
                            service.removeFloatingIps(floatingIpSet);
                            return;
                        }
                    }
                    print(null, "The floatingIp is not existed");
                    return;
                }
            }
        } catch (Exception e) {
            print(null, e.getMessage());
        }
    }
}


text:
package com.googlecode.iqapps.IQTimeSheet.test;

import android.app.Instrumentation;
import android.content.Context;
import android.test.ActivityInstrumentationTestCase2;
import android.test.FlakyTest;
import android.test.suitebuilder.annotation.Suppress;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ListView;

import com.googlecode.iqapps.TimeHelpers;
import com.googlecode.iqapps.IQTimeSheet.AddTaskHandler;
import com.googlecode.iqapps.IQTimeSheet.MenuItems;
import com.googlecode.iqapps.IQTimeSheet.TimeSheetActivity;
import com.googlecode.iqapps.testtools.Helpers;
import com.jayway.android.robotium.solo.Solo;

// @Suppress //#$##
public class EditTaskHandlerTest extends
		ActivityInstrumentationTestCase2<TimeSheetActivity> {
	private static final String EXAMPLE_TASK_ENTRY = "Example task entry";
	private static final String CHILD_TASK_1_65 = "Child Task 1 - 65%";
	private static final String CHILD_TASK_2_35 = "Child Task 2 - 35%";

	private static final int SLEEPTIME = 99;

	final String renamedTaskText = "Renamed Task";

	private Solo solo;
	private TimeSheetActivity mActivity;
	private Context mCtx;
	private Instrumentation mInstr;

	public EditTaskHandlerTest() {
		super(TimeSheetActivity.class);
	}

	@Override
	protected void setUp() throws Exception {
		super.setUp();
		mInstr = getInstrumentation();
		mCtx = mInstr.getTargetContext();
		solo = new Solo(mInstr, getActivity());
	}

	/**
	 * Make sure the application is ready for us to test it.
	 */
	public void test00Preconditions() {
		mActivity = getActivity();
		assertNotNull(mActivity);

		ListView mView = (ListView) solo
				.getView(com.googlecode.iqapps.IQTimeSheet.R.id.tasklistfragment);
		assertNotNull(mView);
	}

	/**
	 * Make sure the application is ready for us to test it.
	 */
	public void test01BackupDB() {
		mActivity = getActivity();
		assertNotNull(mActivity);

		Helpers.backup(solo, mInstr, mActivity);
	}

	/**
	 * Make sure the application is ready for us to test it.
	 */
	public void test02EraseDB() {
		// TODO: This should be more kind to existing data. Perhaps backing it
		// up and replacing it once we're done testing...

		// Delete the databases associated with the project.
		String[] databases = mCtx.databaseList();
		for (String database : databases) {
			// assertTrue("dbList: " + databases[db], false);
			mCtx.deleteDatabase(database);
		}
	}

	public void test03ForEmptyDatabase() {
		mActivity = getActivity();
		assertNotNull(mActivity);

		assertTrue(solo.searchText(EXAMPLE_TASK_ENTRY));
	}

	@FlakyTest(tolerance = 3)
	public void test10CreateSplitTasks() {
		createSplitTask(CHILD_TASK_1_65, EXAMPLE_TASK_ENTRY, 65);
		createSplitTask(CHILD_TASK_2_35, EXAMPLE_TASK_ENTRY, 35);
	}

	public void test20StartStopTask() {
		mActivity = getActivity();
		assertNotNull(mActivity);

		// Press the task to start recording time.
		solo.clickOnText(EXAMPLE_TASK_ENTRY);
		solo.sleep(SLEEPTIME);
		// Press the task to stop recording time.
		solo.clickOnText(EXAMPLE_TASK_ENTRY);
	}

	public void test30EditTask() {
		mActivity = getActivity();
		assertNotNull(mActivity);

		int whatHour = TimeHelpers.millisToHour(TimeHelpers.millisNow());

		// Bring up the edit day activity.
		mInstr.sendKeyDownUpSync(KeyEvent.KEYCODE_MENU);
		solo.sleep(SLEEPTIME);
		int menuItemID = mActivity.getOptionsMenu()
				.getItem(MenuItems.EDITDAY_ENTRIES.ordinal()).getItemId();
		assertTrue(mInstr.invokeMenuActionSync(mActivity, menuItemID, 0));
		assertTrue(solo.waitForActivity("EditDayEntriesHandler", 1500));

		// Select the first item in the list, which was just created.
		assertTrue(solo.waitForText(EXAMPLE_TASK_ENTRY, 1, SLEEPTIME * 5));
		solo.clickOnText(EXAMPLE_TASK_ENTRY);

		// Find the end time button and select it.
		// If it's not midnight or the following hour, change start time
		if (whatHour != 0) {
			solo.clickOnButton(2);
		} else {
			solo.clickOnButton(3);
		}
		solo.sleep(SLEEPTIME);

		// Change the time to one hour prior.
		// If it's midnight or the following hour, increase instead
		if (whatHour == 0) {
			View increment = solo.getView(
					com.googlecode.iqapps.IQTimeSheet.R.id.increment, 0);
			solo.clickOnView(increment);
		} else {
			View decrement = solo.getView(
					com.googlecode.iqapps.IQTimeSheet.R.id.decrement, 0);
			solo.clickOnView(decrement);
		}

		// Accept this change.
		solo.clickOnButton(mActivity
				.getString(com.googlecode.iqapps.IQTimeSheet.R.string.accept));
		solo.sleep(SLEEPTIME);

		// Accept the edit
		solo.clickOnButton(mActivity
				.getString(com.googlecode.iqapps.IQTimeSheet.R.string.accept));
		solo.sleep(SLEEPTIME);
	}

	public void test40EditTaskCancel() {
		mActivity = getActivity();
		assertNotNull(mActivity);

		// Bring up the edit day activity.
		int menuItemID = mActivity.getOptionsMenu()
				.getItem(MenuItems.EDITDAY_ENTRIES.ordinal()).getItemId();
		assertTrue(mInstr.invokeMenuActionSync(mActivity, menuItemID, 0));
		assertTrue(solo.waitForActivity("EditDayEntriesHandler", 1500));

		// Select the first item in the list, which was just created.
		solo.clickOnText(EXAMPLE_TASK_ENTRY);

		// Select the cancel button.
		solo.clickOnButton(solo
				.getString(com.googlecode.iqapps.IQTimeSheet.R.string.cancel));
		solo.sleep(SLEEPTIME);
	}

	public void test50Report() {
		mActivity = getActivity();
		assertNotNull(mActivity);

		// Bring up the report activity.
		solo.scrollToSide(Solo.LEFT);
		solo.scrollToSide(Solo.LEFT);
		solo.scrollToSide(Solo.RIGHT);
		// assertTrue(solo.waitForFragmentByTag("DayReport", 1500));

		// Locate the larger percentage task
		// The percentage of time accumulated can vary a little due to rounding
		// when the snap time is one minute. Account for that variance here.
		assertTrue(solo.searchText("0.65") || solo.searchText("0.66"));
		solo.sleep(SLEEPTIME);

		// Locate the smaller percentage task
		// The percentage of time accumulated can vary a little due to rounding
		// when the snap time is one minute. Account for that variance here.
		assertTrue(solo.searchText("0.35") || solo.searchText("0.36"));
		solo.sleep(SLEEPTIME);

		// Locate the footer
		// The total time accumulated can vary a little due to rounding when the
		// snap time is one minute. Account for that variance here.
		assertTrue(solo.searchText("1.00") || solo.searchText("1.01")
				|| solo.searchText("1.02"));
		solo.sleep(SLEEPTIME);
	}

	public void test60EditTaskDelete() {
		mActivity = getActivity();
		assertNotNull(mActivity);

		// Bring up the edit day activity.
		mInstr.sendKeyDownUpSync(KeyEvent.KEYCODE_MENU);
		solo.sleep(SLEEPTIME);
		int menuItemID = mActivity.getOptionsMenu()
				.getItem(MenuItems.EDITDAY_ENTRIES.ordinal()).getItemId();
		assertTrue(mInstr.invokeMenuActionSync(mActivity, menuItemID, 0));
		assertTrue(solo.waitForActivity("EditDayEntriesHandler", 1500));

		// Select the first item in the list, which was just created.
		solo.clickOnText(EXAMPLE_TASK_ENTRY);

		// Select the delete button.
		solo.clickOnButton(mActivity
				.getString(com.googlecode.iqapps.IQTimeSheet.R.string.delete));
		solo.sleep(SLEEPTIME);

		// Answer the dialog.
		solo.clickOnText("Yes");
		solo.sleep(SLEEPTIME);
	}

	/**
	 * Restore the database after we're done messing with it.
	 */
	public void testzzzRestoreDB() {
		mActivity = getActivity();
		assertNotNull(mActivity);

		Helpers.restore(solo, mInstr, mActivity);
	}

	@Override
	protected void tearDown() throws Exception {
		solo.finishOpenedActivities();
	}

	private void createSplitTask(String name, String parent, int percentage) {
		mActivity = getActivity();
		assertNotNull(mActivity);

		// Bring up the new task activity.
		mInstr.sendKeyDownUpSync(KeyEvent.KEYCODE_MENU);
		solo.sleep(SLEEPTIME);
		int menuItemID = mActivity.getOptionsMenu()
				.getItem(MenuItems.NEW_TASK.ordinal()).getItemId();
		assertTrue(mInstr.invokeMenuActionSync(mActivity, menuItemID, 0));
		assertTrue(solo.waitForActivity(AddTaskHandler.class, 1500));
		// solo.sleep(SLEEPTIME);

		// Enter the name of the new task
		solo.clearEditText(0);
		solo.enterText(0, name);
		solo.sleep(SLEEPTIME);

		// Check the split task check box.
		solo.clickOnCheckBox(0);
		solo.sleep(SLEEPTIME * 2);

		// Choose the first child task from the list.
		solo.pressSpinnerItem(0, 0);
		solo.sleep(SLEEPTIME);

		// Set the percentage desired.
		solo.setProgressBar(0, percentage);
		solo.sleep(SLEEPTIME);

		// Verify the percentage is reflected in the text field.
		assertTrue(solo.searchEditText(String.valueOf(percentage)));

		// Click on Accept button
		final String acceptButton = mActivity
				.getString(com.googlecode.iqapps.IQTimeSheet.R.string.accept);
		solo.clickOnButton(acceptButton);
		solo.sleep(SLEEPTIME);
	}
}