text:
<?php

// ********** modify blog option 'wp_mobile_template' manually to specify a theme (ex. 'vip/cnnmobile')

// WordPress Mobile Edition
//
// Copyright (c) 2002-2008 Alex King
// http://alexking.org/projects/wordpress
//
// Released under the GPL license
// http://www.opensource.org/licenses/gpl-license.php
//
// **********************************************************************
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// *****************************************************************

/*
Plugin Name: WordPress Mobile Edition
Plugin URI: http://alexking.org/projects/wordpress
Description: Show a mobile view of the post/page if the visitor is on a known mobile device. Questions on configuration, etc.? Make sure to read the README.
Author: Alex King
Author URI: http://alexking.org
Version: 2.1a-WPCOM
*/

$_SERVER['REQUEST_URI'] = ( isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $_SERVER['SCRIPT_NAME'] . (( isset($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : '')));

function jetpack_check_mobile() {
	if ( ( defined('XMLRPC_REQUEST') && XMLRPC_REQUEST ) || ( defined('APP_REQUEST') && APP_REQUEST ) )
		return false;
	if ( !isset($_SERVER["HTTP_USER_AGENT"]) || (isset($_COOKIE['akm_mobile']) && $_COOKIE['akm_mobile'] == 'false') )
		return false;
	if ( jetpack_mobile_exclude() )
		return false;
	if ( 1 == get_option('wp_mobile_disable') )
		return false;
	if ( isset($_COOKIE['akm_mobile']) && $_COOKIE['akm_mobile'] == 'true' )
		return true;

	$is_mobile = jetpack_is_mobile();

	return apply_filters( 'jetpack_check_mobile', $is_mobile );
}

function jetpack_mobile_exclude() {
	$exclude = false;
	$pages_to_exclude = array(
		'wp-admin',
		'wp-comments-post.php',
		'wp-mail.php',
		'wp-login.php',
		'wp-activate.php',
	);
	foreach ( $pages_to_exclude as $exclude_page ) {
		if ( strstr( strtolower( $_SERVER['REQUEST_URI'] ), $exclude_page ) )
			$exclude = true;
	}

	if ( defined( 'DOING_AJAX' ) && true === DOING_AJAX )
		$exclude = false;

	if ( isset( $GLOBALS['wp_customize'] ) )
		return true;

	return $exclude;
}

function wp_mobile_get_main_template() {
	remove_action( 'option_template', 'jetpack_mobile_template' );
	$template = get_option( 'template' );
	add_action( 'option_template', 'jetpack_mobile_template' );
	return $template;
}

function wp_mobile_get_main_stylesheet() {
	remove_action( 'option_stylesheet', 'jetpack_mobile_stylesheet' );
	$stylesheet = get_option( 'stylesheet' );
	add_action( 'option_stylesheet', 'jetpack_mobile_stylesheet' );
	return $stylesheet;
}

function jetpack_mobile_stylesheet( $theme ) {
	return apply_filters( 'jetpack_mobile_stylesheet', 'pub/minileven', $theme );
}

function jetpack_mobile_template( $theme ) {
	return apply_filters( 'jetpack_mobile_template', 'pub/minileven', $theme );
}

function jetpack_mobile_available() {
	echo '
' . __( 'View Mobile Site', 'jetpack' ) . '
';
}

function jetpack_mobile_request_handler() {
	global $wpdb;
	if (isset($_GET['ak_action'])) {
		$url = parse_url( get_bloginfo( 'url' ) );
		$domain = $url['host'];
		if (!empty($url['path'])) {
			$path = $url['path'];
		}
		else {
			$path = '/';
		}
		$redirect = false;
		switch ($_GET['ak_action']) {
			case 'reject_mobile':
				setcookie(
					'akm_mobile'
					, 'false'
					, time() + 300000
					, $path
					, $domain
				);
				$redirect = true;

				do_action( 'mobile_reject_mobile' );
				break;
			case 'force_mobile':
			case 'accept_mobile':
				setcookie(
					'akm_mobile'
					, 'true'
					, time() + 300000
					, $path
					, $domain
				);
				$redirect = true;

				do_action( 'mobile_force_mobile' );
				break;
		}
		if ($redirect) {
			if ( isset( $_GET['redirect_to'] ) && $_GET['redirect_to'] ) {
				$go = urldecode( $_GET['redirect_to'] );
			} else if (!empty($_SERVER['HTTP_REFERER'])) {
				$go = $_SERVER['HTTP_REFERER'];
			}
			else {
				$go = remove_query_arg( array( 'ak_action' ) );
			}
			wp_safe_redirect( $go );
			exit;
		}
	}
}
add_action('init', 'jetpack_mobile_request_handler');

function jetpack_mobile_theme_setup() {
	if ( jetpack_check_mobile() ) {
		// Redirect to download page if user clicked mobile app promo link in mobile footer
		if ( isset( $_GET['app-download'] ) ) {
			do_action( 'mobile_app_promo_download', $_GET['app-download'] );

			switch ( $_GET['app-download'] ) {
				case 'android':
					header( 'Location: market://search?q=pname:org.wordpress.android' );
					exit;
				break;
				case 'ios':
					header( 'Location: http://itunes.apple.com/us/app/wordpress/id335703880?mt=8' );
					exit;
				break;
				case 'blackberry':
					header( 'Location: http://blackberry.wordpress.org/download/' );
					exit;
				break;
				case 'nokia':
					header( 'Location: http://nokia.wordpress.org/download/' );
					exit;
				break;
				case 'windowsphone':
					header( 'Location: http://social.zune.net/redirect?type=phoneApp&id=5f64ad85-f801-e011-9264-00237de2db9e' );
					exit;
				break;
			}
		}

		add_action('stylesheet', 'jetpack_mobile_stylesheet');
		add_action('template', 'jetpack_mobile_template');
		add_action('option_template', 'jetpack_mobile_template');
		add_action('option_stylesheet', 'jetpack_mobile_stylesheet');

		if ( class_exists( 'Jetpack_Custom_CSS' ) && method_exists( 'Jetpack_Custom_CSS', 'disable' ) && ! get_option( 'wp_mobile_custom_css' ) )
			add_action( 'init', array( 'Jetpack_Custom_CSS', 'disable' ), 11 );

		do_action( 'mobile_setup' );
	}
}

// Need a hook after plugins_loaded (since this code won't be loaded in Jetpack
// until then) but after init (because it has its own init hooks to add).
add_action( 'setup_theme', 'jetpack_mobile_theme_setup' );

if (isset($_COOKIE['akm_mobile']) && $_COOKIE['akm_mobile'] == 'false') {
	add_action('wp_footer', 'jetpack_mobile_available');
}

add_action( 'wp_footer', 'mobile_admin_bar', 20 );
function mobile_admin_bar() {
	global $wp_version;

	if ( jetpack_is_mobile() && 1 != version_compare( $wp_version, '3.5-beta3-22631' ) ) :
		// This fix was made unnecessary in http://core.trac.wordpress.org/changeset/22636
	?>

	<?php
	endif;
}

function jetpack_mobile_app_promo()  {
	?>

	<?php
}

add_action( 'wp_mobile_theme_footer', 'jetpack_mobile_app_promo' );

/**
 * Adds an option to allow your Custom CSS to also be applied to the Mobile Theme.
 * It's disabled by default, but this should allow people who know what they're
 * doing to customize the mobile theme.
 */
function jetpack_mobile_css_settings() {
	$mobile_css = get_option( 'wp_mobile_custom_css' );

	?>

		<?php esc_html_e( 'Mobile-compatible:', 'jetpack' ); ?>
		<?php echo $mobile_css ? __( 'Yes', 'jetpack' ) : __( 'No', 'jetpack' ); ?>
		<?php echo esc_html_e( 'Edit', 'jetpack' ); ?>

			<input type="hidden" name="mobile_css" id="mobile-css" value="<?php echo intval( $mobile_css ); ?>" />

				<input type="checkbox" id="mobile-css-visible" <?php checked( get_option( 'wp_mobile_custom_css' ) ); ?> />
				<?php esc_html_e( 'Include this CSS in the Mobile Theme', 'jetpack' ); ?>

				<?php esc_html_e( 'OK', 'jetpack' ); ?>
				<?php esc_html_e( 'Cancel', 'jetpack' ); ?>

	<?php
}

add_action( 'custom_css_submitbox_misc_actions', 'jetpack_mobile_css_settings' );

function jetpack_mobile_customizer_controls( $wp_customize ) {
	$wp_customize->add_setting( 'wp_mobile_custom_css' , array(
		'default' => true,
		'transport' => 'postMessage',
		'type' => 'option'
	) );

	$wp_customize->add_control( 'jetpack_mobile_css_control', array(
		'type' => 'checkbox',
		'label' => __( 'Include this CSS in the Mobile Theme', 'jetpack' ),
		'section' => 'jetpack_custom_css',
		'settings' => 'wp_mobile_custom_css',
	) );
}

add_action( 'jetpack_custom_css_customizer_controls', 'jetpack_mobile_customizer_controls' );

function jetpack_mobile_save_css_settings() {
	update_option( 'wp_mobile_custom_css', isset( $_POST['mobile_css'] ) && ! empty( $_POST['mobile_css'] ) );
}

add_action( 'safecss_save_pre', 'jetpack_mobile_save_css_settings' );


text:
import joinPaths from '../joinPaths';

describe('joinPaths', () => {
  it('joins paths', () => {
    expect(joinPaths('/', '')).toBe('/');
    expect(joinPaths('/', 'inbox')).toBe('/inbox');
    expect(joinPaths('/', '/inbox')).toBe('/inbox');
    expect(joinPaths('inbox', 'messages')).toBe('inbox/messages');
    expect(joinPaths('/inbox/messages/', '/1/')).toBe('/inbox/messages/1');
  });
});

redpajama_set_name: RedPajamaGithub


text:
from __future__ import unicode_literals

from django.db import models, migrations
import pg_fts.fields
from pg_fts.migrations import (
    CreateFTSIndexOperation,
    CreateFTSTriggerOperation
)

class Migration(migrations.Migration):

    dependencies = [
        ('localities', '0024_valuearchive'),
    ]

    operations = [
        migrations.CreateModel(
            name='LocalityIndex',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('rankA', models.TextField(null=True)),
                ('rankB', models.TextField(null=True)),
                ('rankC', models.TextField(null=True)),
                ('rankD', models.TextField(null=True)),
                ('fts_index', pg_fts.fields.TSVectorField(dictionary='english', default='', fields=((b'rankA', b'A'), (b'rankB', b'B'), (b'rankC', b'C'), (b'rankD', b'D')), serialize=False, editable=False, null=True)),
                ('locality', models.ForeignKey(to='localities.Locality')),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        CreateFTSIndexOperation(
            name='LocalityIndex',
            fts_vector='fts_index',
            index='gin'
        ),
        # create trigger to Article.fts_index
        CreateFTSTriggerOperation(
            name='LocalityIndex',
            fts_vector='fts_index'
        ),
    ]


text:
<?php

final class PassphraseCredentialPHIDType extends PhabricatorPHIDType {

  const TYPECONST = 'CDTL';

  public function getTypeName() {
    return pht('Credential');
  }

  public function newObject() {
    return new PassphraseCredential();
  }

  protected function buildQueryForObjects(
    PhabricatorObjectQuery $query,
    array $phids) {

    return id(new PassphraseCredentialQuery())
      ->withPHIDs($phids);
  }

  public function loadHandles(
    PhabricatorHandleQuery $query,
    array $handles,
    array $objects) {

    foreach ($handles as $phid => $handle) {
      $credential = $objects[$phid];
      $id = $credential->getID();
      $name = $credential->getName();

      $handle->setName("K{$id}");
      $handle->setFullName("K{$id} {$name}");
      $handle->setURI("/K{$id}");

      if ($credential->getIsDestroyed()) {
        $handle->setStatus(PhabricatorObjectHandleStatus::STATUS_CLOSED);
      }
    }
  }

  public function canLoadNamedObject($name) {
    return preg_match('/^K\d*[1-9]\d*$/i', $name);
  }

  public function loadNamedObjects(
    PhabricatorObjectQuery $query,
    array $names) {

    $id_map = array();
    foreach ($names as $name) {
      $id = (int)substr($name, 1);
      $id_map[$id][] = $name;
    }

    $objects = id(new PassphraseCredentialQuery())
      ->setViewer($query->getViewer())
      ->withIDs(array_keys($id_map))
      ->execute();

    $results = array();
    foreach ($objects as $id => $object) {
      foreach (idx($id_map, $id, array()) as $name) {
        $results[$name] = $object;
      }
    }

    return $results;
  }

}


text:
// Copyright (c) 2012 Ecma International.  All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms").   Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.

/*---
es5id: 11.8.2-4
description: >
    11.8.2 Greater-than Operator - Partial left to right order
    enforced when using Greater-than operator: toString > toString
includes: [runTestCase.js]
---*/

function testcase() {
        var accessed = false;
        var obj1 = {
            toString: function () {
                accessed = true;
                return 3;
            }
        };
        var obj2 = {
            toString: function () {
                if (accessed === true) {
                    return 4;
                } else {
                    return 2;
                }
            }
        };
        return !(obj1 > obj2);
    }
runTestCase(testcase);


text:
package org.wso2.carbon.device.mgt.core.app.mgt.oauth;

import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.transport.http.HttpTransportProperties;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException;

/**
 * Authenticate a given service client.
 */
public class ServiceAuthenticator {

    private String username;
    private String password;

    public ServiceAuthenticator(String username, String password) {
        this.username = username;
        this.password = password;
    }

    public void authenticate(ServiceClient client) throws ApplicationManagementException {
        Options option = client.getOptions();
        HttpTransportProperties.Authenticator auth = new HttpTransportProperties.Authenticator();
        auth.setUsername(username);
        auth.setPassword(password);
        auth.setPreemptiveAuthentication(true);
        option.setProperty(org.apache.axis2.transport.http.HTTPConstants.AUTHENTICATE, auth);
        option.setManageSession(true);
    }

}


text:
title: Inventário Patrimonial
lang: pt
featured: true
custom_css: grid-gallery
permalink: /portfolio/inventario-patrimonial/
preview_image: /images/portfolio/unijui.png
images:
  - path: /images/portfolio/inventario-screenshot-1.png
    id: 1
  - path: /images/portfolio/inventario-screenshot-2.png
    id: 2
  - path: /images/portfolio/inventario-screenshot-3.png
    id: 3
  - path: /images/portfolio/inventario-screenshot-4.png
    id: 4
  - path: /images/portfolio/inventario-screenshot-5.png
    id: 5
  - path: /images/portfolio/inventario-screenshot-6.png
    id: 6
  - path: /images/portfolio/inventario-screenshot-7.png
    id: 7
description: Aplicação desenvolvida para auxiliar os técnicos administrativos da UNIJUÍ durante os processos de inventário patrimonial da instituição.
---
Realizar o controle de bens patrimoniais de uma instituição de grande porte é uma tarefa difícil que pode ser muito trabalhosa quando não executada com as ferramentas corretas. O aplicativo em questão é parte de um projeto de informatização da Coordenadoria Patrimonial da UNIJUÍ e que tem como objetivo agilizar o processo de levantamento de informações sobre a localização dos pertences da universidade. Neste projeto integrei a equipe de desenvolvimento móvel da instituição por meio do Núcleo de Desenvolvimento de Sistemas, onde todo o trabalho foi coordenado pelo analista do setor.

#### O método antigo

Com uma relação impressa dos objetos presentes em cada espaço físico obtida a partir do sistema, o técnico visita as salas e realiza o cruzamento manual dos registros, verificando quais bens estão no lugar correto e quais foram movidos. Após a coleta de dados, é necessário realizar a inserção dos mesmos no sistema da universidade.

#### A solução apresentada

Para otimizar o processo de coleta de dados foi desenvolvida a aplicação em questão que tem as seguintes características:
- integração total ao sistema da universidade por meio de web services;
- controle de acesso de usuário a partir de formulário de login;
- carga de dados para utilização da aplicação offline;
- módulo de sincronização com suporte à notificações push para atualização de dados;
- suporte à leitura de código de barras utilizando a câmera do dispositivo.

Dessa forma, após fazer login no aplicativo, é mostrada a lista de prédios da instituição. Nesse momento é possível filtrar os prédios pelo campus ao qual pertencem ou por nome. Após selecionar um prédio, uma lista semelhante é exibida mostrando os espaços (salas) pertencentes a tal prédio. Selecionada a sala, são mostrados os bens ou leituras vinculados à mesma, permitindo ao usuário realizar as leituras de bens, indicando quais estão presentes no espaço em questão. A aplicação também oferece uma busca híbrida (local ou online) de objetos, permitindo ao usuário saber a localização correta de um dado objeto ou encontrar seu cadastro a partir de um código de barras.

A proposta utilizando o sistema móvel atingiu seu objetivo, diminuindo consideravelmente o tempo necessário para realizar a coleta de dados.

### Capturas de Tela

{% for image in page.images %}
<input type="checkbox" id="pic-{{ image.id }}"/>

{% endfor %}

	{% for image in page.images %}

	{% endfor %}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.spring.messaging.eventhubs.implementation.checkpoint;

import com.azure.messaging.eventhubs.models.EventBatchContext;

/**
 * Event batch checkpoint interface.
 */
interface EventBatchCheckpoint {

    /**
     * Checkpoint for the event batch context.
     * @param context the event batch context.
     */
    void checkpoint(EventBatchContext context);
}


text:
package com.twitter.finagle.ssl

import javax.net.ssl.{SSLContext, SSLEngine}
import org.scalatest.FunSuite

class SslConfigurationsTest extends FunSuite {

  private[this] def createTestEngine(): SSLEngine = {
    val sslContext = SSLContext.getInstance("TLSv1.2")
    sslContext.init(null, null, null)
    sslContext.createSSLEngine()
  }

  test("initializeSslContext succeeds for defaults") {
    val sslContext = SslConfigurations.initializeSslContext(
      KeyCredentials.Unspecified,
      TrustCredentials.Unspecified
    )
    assert(sslContext != null)
    assert(sslContext.getProtocol == "TLSv1.2")
  }

  test("configureCipherSuites succeeds with good suites") {
    val sslEngine = createTestEngine()
    val cipherSuites = CipherSuites.Enabled(Seq("TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256"))
    SslConfigurations.configureCipherSuites(sslEngine, cipherSuites)

    val enabled = sslEngine.getEnabledCipherSuites()
    assert(enabled.length == 1)
    assert(enabled(0) == "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256")
  }

  test("configureCipherSuites fails with bad suites") {
    val sslEngine = createTestEngine()
    val cipherSuites = CipherSuites.Enabled(Seq("TLS_ECDHE_ECDSA_WITH_AES_102_CBC_SHA496"))

    intercept[IllegalArgumentException] {
      SslConfigurations.configureCipherSuites(sslEngine, cipherSuites)
    }
  }

  test("configureProtocols succeeds with good protocols") {
    val sslEngine = createTestEngine()
    val protocols = Protocols.Enabled(Seq("TLSv1.2"))
    SslConfigurations.configureProtocols(sslEngine, protocols)

    val enabled = sslEngine.getEnabledProtocols()
    assert(enabled.length == 1)
    assert(enabled(0) == "TLSv1.2")
  }

  test("configureProtocols fails with bad protocols") {
    val sslEngine = createTestEngine()
    val protocols = Protocols.Enabled(Seq("TLSv2.0"))

    intercept[IllegalArgumentException] {
      SslConfigurations.configureProtocols(sslEngine, protocols)
    }
  }

  test("configureHostnameVerifier turns on endpoint identification when hostname is set") {
    val sslEngine = createTestEngine()
    val sslParametersBefore = sslEngine.getSSLParameters
    assert(sslParametersBefore.getEndpointIdentificationAlgorithm == null)

    SslConfigurations.configureHostnameVerification(sslEngine, Some("twitter.com"))
    val sslParametersAfter = sslEngine.getSSLParameters
    assert(sslParametersAfter.getEndpointIdentificationAlgorithm == "HTTPS")
  }

  test("configureHostnameVerifier leaves endpoint identification off when hostname is empty") {
    val sslEngine = createTestEngine()
    val sslParametersBefore = sslEngine.getSSLParameters
    assert(sslParametersBefore.getEndpointIdentificationAlgorithm == null)

    SslConfigurations.configureHostnameVerification(sslEngine, None)
    val sslParametersAfter = sslEngine.getSSLParameters
    assert(sslParametersAfter.getEndpointIdentificationAlgorithm == null)
  }

  test("checkKeyCredentialsNotSupported does nothing for Unspecified") {
    val keyCredentials = KeyCredentials.Unspecified
    SslConfigurations.checkKeyCredentialsNotSupported("TestFactory", keyCredentials)
  }

  test("checkKeyCredentialsNotSupported throws for CertAndKey") {
    val keyCredentials = KeyCredentials.CertAndKey(null, null)
    val ex = intercept[SslConfigurationException] {
      SslConfigurations.checkKeyCredentialsNotSupported("TestFactory", keyCredentials)
    }
    assert(
      "KeyCredentials.CertAndKey is not supported at this time for TestFactory" ==
        ex.cause.getMessage
    )
  }

  test("checkKeyCredentialsNotSupported throws for CertKeyAndChain") {
    val keyCredentials = KeyCredentials.CertKeyAndChain(null, null, null)
    val ex = intercept[SslConfigurationException] {
      SslConfigurations.checkKeyCredentialsNotSupported("TestFactory", keyCredentials)
    }
    assert(
      "KeyCredentials.CertKeyAndChain is not supported at this time for TestFactory" ==
        ex.cause.getMessage
    )
  }

  test("checkTrustCredentialsNotSupported does nothing for Unspecified") {
    val trustCredentials = TrustCredentials.Unspecified
    SslConfigurations.checkTrustCredentialsNotSupported("TestFactory", trustCredentials)
  }

  test("checkTrustCredentialsNotSupported throws for Insecure") {
    val trustCredentials = TrustCredentials.Insecure
    val ex = intercept[SslConfigurationException] {
      SslConfigurations.checkTrustCredentialsNotSupported("TestFactory", trustCredentials)
    }
    assert(
      "TrustCredentials.Insecure is not supported at this time for TestFactory" ==
        ex.cause.getMessage
    )
  }

  test("checkTrustCredentialsNotSupported throws for TrustManagerFactory") {
    val trustCredentials = TrustCredentials.TrustManagerFactory(null)
    val ex = intercept[SslConfigurationException] {
      SslConfigurations.checkTrustCredentialsNotSupported("TestFactory", trustCredentials)
    }
    assert(
      "TrustCredentials.TrustManagerFactory is not supported at this time for TestFactory" ==
        ex.cause.getMessage
    )
  }

  test("checkTrustCredentialsNotSupported throws for CertCollection") {
    val trustCredentials = TrustCredentials.CertCollection(null)
    val ex = intercept[SslConfigurationException] {
      SslConfigurations.checkTrustCredentialsNotSupported("TestFactory", trustCredentials)
    }
    assert(
      "TrustCredentials.CertCollection is not supported at this time for TestFactory" ==
        ex.cause.getMessage
    )
  }

  test("checkApplicationProtocolsNotSupported does nothing for Unspecified") {
    val appProtocols = ApplicationProtocols.Unspecified
    SslConfigurations.checkApplicationProtocolsNotSupported("TestFactory", appProtocols)
  }

  test("checkApplicationProtocolsNotSupported throws for Supported") {
    val appProtocols = ApplicationProtocols.Supported(Seq("h2"))
    val ex = intercept[SslConfigurationException] {
      SslConfigurations.checkApplicationProtocolsNotSupported("TestFactory", appProtocols)
    }
    assert(
      "ApplicationProtocols.Supported is not supported at this time for TestFactory" ==
        ex.cause.getMessage
    )
  }

  test("checkProtocolsNotSupported throws for Enabled") {
    val protocols = Protocols.Enabled(Seq("TLSv1.2"))
    val ex = intercept[SslConfigurationException] {
      SslConfigurations.checkProtocolsNotSupported("TestFactory", protocols)
    }
    assert(
      "Protocols.Enabled is not supported at this time for TestFactory" ==
        ex.cause.getMessage
    )
  }

  test("checkClientAuthNotSupported throws for Off") {
    val clientAuth = ClientAuth.Off
    val ex = intercept[SslConfigurationException] {
      SslConfigurations.checkClientAuthNotSupported("TestFactory", clientAuth)
    }
    assert(
      "ClientAuth.Off is not supported at this time for TestFactory" ==
        ex.cause.getMessage
    )
  }

  test("checkClientAuthNotSupported throws for Wanted") {
    val clientAuth = ClientAuth.Wanted
    val ex = intercept[SslConfigurationException] {
      SslConfigurations.checkClientAuthNotSupported("TestFactory", clientAuth)
    }
    assert(
      "ClientAuth.Wanted is not supported at this time for TestFactory" ==
        ex.cause.getMessage
    )
  }

  test("checkClientAuthNotSupported throws for Needed") {
    val clientAuth = ClientAuth.Needed
    val ex = intercept[SslConfigurationException] {
      SslConfigurations.checkClientAuthNotSupported("TestFactory", clientAuth)
    }
    assert(
      "ClientAuth.Needed is not supported at this time for TestFactory" ==
        ex.cause.getMessage
    )
  }

}


text:
//jshint strict: false
module.exports = function(config) {
  config.set({

    basePath: './app',

    files: [
      'bower_components/angular/angular.js',
      'bower_components/angular-route/angular-route.js',
      'bower_components/ngstorage/ngStorage.js',
      'bower_components/jquery/dist/jquery.js',
      'bower_components/bootstrap/dist/js/bootstrap.js',
      'bower_components/angular-sanitize/angular-sanitize.js',
      'bower_components/angular-emoji/lib/emoji.js',
      'bower_components/angular-mocks/angular-mocks.js',
      'components/**/*.js',
      'view*/**/*.js'
    ],

    autoWatch: true,

    frameworks: ['jasmine'],

    browsers: ['Chrome'],

    plugins: [
      'karma-chrome-launcher',
      'karma-firefox-launcher',
      'karma-jasmine',
      'karma-junit-reporter'
    ],

    junitReporter: {
      outputFile: 'test_out/unit.xml',
      suite: 'unit'
    }

  });
};


text:
import React from 'react';
export interface LocaleProviderProps {
    locale: {
        Pagination?: Object;
        DatePicker?: Object;
        TimePicker?: Object;
        Calendar?: Object;
        Table?: Object;
        Modal?: Object;
        Popconfirm?: Object;
        Transfer?: Object;
        Select?: Object;
    };
    children?: React.ReactElement<any>;
}
export default class LocaleProvider extends React.Component<LocaleProviderProps, any> {
    static propTypes: {
        locale: React.Requireable<any>;
    };
    static childContextTypes: {
        antLocale: React.Requireable<any>;
    };
    getChildContext(): {
        antLocale: {
            exist: boolean;
            Pagination?: Object | undefined;
            DatePicker?: Object | undefined;
            TimePicker?: Object | undefined;
            Calendar?: Object | undefined;
            Table?: Object | undefined;
            Modal?: Object | undefined;
            Popconfirm?: Object | undefined;
            Transfer?: Object | undefined;
            Select?: Object | undefined;
        };
    };
    componentWillMount(): void;
    componentDidUpdate(): void;
    componentWillUnMount(): void;
    render(): React.ReactElement<any>;
}


text:
package com.cloudera.cdk.data.filesystem;

import com.cloudera.cdk.data.spi.ReaderWriterState;
import com.cloudera.cdk.data.DatasetReaderException;
import com.cloudera.cdk.data.spi.AbstractDatasetReader;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import java.io.EOFException;
import java.io.IOException;
import org.apache.avro.Schema;
import org.apache.avro.generic.IndexedRecord;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import parquet.avro.AvroParquetReader;

class ParquetFileSystemDatasetReader<E extends IndexedRecord> extends AbstractDatasetReader<E> {

  private FileSystem fileSystem;
  private Path path;
  private Schema schema;

  private ReaderWriterState state;
  private AvroParquetReader<E> reader;

  private E next;

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

  public ParquetFileSystemDatasetReader(FileSystem fileSystem, Path path, Schema schema) {
    Preconditions.checkArgument(fileSystem != null, "FileSystem cannot be null");
    Preconditions.checkArgument(path != null, "Path cannot be null");
    Preconditions.checkArgument(schema != null, "Schema cannot be null");

    this.fileSystem = fileSystem;
    this.path = path;
    this.schema = schema;

    this.state = ReaderWriterState.NEW;
  }

  @Override
  public void open() {
    Preconditions.checkState(state.equals(ReaderWriterState.NEW),
      "A reader may not be opened more than once - current state:%s", state);

    logger.debug("Opening reader on path:{}", path);

    try {
      reader = new AvroParquetReader<E>(fileSystem.makeQualified(path));
    } catch (IOException e) {
      throw new DatasetReaderException("Unable to create reader path:" + path, e);
    }

    state = ReaderWriterState.OPEN;
  }

  @Override
  public boolean hasNext() {
    Preconditions.checkState(state.equals(ReaderWriterState.OPEN),
      "Attempt to read from a file in state:%s", state);
    if (next == null) {
      try {
        next = reader.read();
      } catch (EOFException e) {
        return false;
      } catch (IOException e) {
        throw new DatasetReaderException("Unable to read next record from: " + path, e);
      }
    }
    return next != null;
  }

  @Override
  public E next() {
    Preconditions.checkState(state.equals(ReaderWriterState.OPEN),
      "Attempt to read from a file in state:%s", state);

    E current = next;
    next = null;
    return current;
  }

  @Override
  public void close() {
    if (!state.equals(ReaderWriterState.OPEN)) {
      return;
    }

    logger.debug("Closing reader on path:{}", path);

    try {
      reader.close();
    } catch (IOException e) {
      throw new DatasetReaderException("Unable to close reader path:" + path, e);
    }

    state = ReaderWriterState.CLOSED;
  }

  @Override
  public boolean isOpen() {
    return state.equals(ReaderWriterState.OPEN);
  }

  @Override
  public String toString() {
    return Objects.toStringHelper(this)
      .add("fileSystem", fileSystem)
      .add("path", path)
      .add("schema", schema)
      .add("state", state)
      .add("reader", reader)
      .toString();
  }

}


text:
namespace extensions {

namespace {

base::LazyInstance<BrowserContextKeyedAPIFactory<UsbGuidMap>>::Leaky
    g_usb_guid_map_factory = LAZY_INSTANCE_INITIALIZER;

}  // namespace

// static
UsbGuidMap* UsbGuidMap::Get(content::BrowserContext* browser_context) {
  return BrowserContextKeyedAPIFactory<UsbGuidMap>::Get(browser_context);
}

// static
BrowserContextKeyedAPIFactory<UsbGuidMap>* UsbGuidMap::GetFactoryInstance() {
  return g_usb_guid_map_factory.Pointer();
}

int UsbGuidMap::GetIdFromGuid(const std::string& guid) {
  auto iter = guid_to_id_map_.find(guid);
  if (iter == guid_to_id_map_.end()) {
    auto result = guid_to_id_map_.insert(std::make_pair(guid, next_id_++));
    DCHECK(result.second);
    iter = result.first;
    id_to_guid_map_.insert(std::make_pair(iter->second, guid));
  }
  return iter->second;
}

bool UsbGuidMap::GetGuidFromId(int id, std::string* guid) {
  auto iter = id_to_guid_map_.find(id);
  if (iter == id_to_guid_map_.end())
    return false;
  *guid = iter->second;
  return true;
}

void UsbGuidMap::GetApiDevice(scoped_refptr<const device::UsbDevice> device_in,
                              extensions::api::usb::Device* device_out) {
  device_out->device = GetIdFromGuid(device_in->guid());
  device_out->vendor_id = device_in->vendor_id();
  device_out->product_id = device_in->product_id();
  device_out->product_name = base::UTF16ToUTF8(device_in->product_string());
  device_out->manufacturer_name =
      base::UTF16ToUTF8(device_in->manufacturer_string());
  device_out->serial_number = base::UTF16ToUTF8(device_in->serial_number());
}

UsbGuidMap::UsbGuidMap(content::BrowserContext* browser_context)
    : browser_context_(browser_context), observer_(this) {
  device::UsbService* service = device::DeviceClient::Get()->GetUsbService();
  DCHECK(service);
  observer_.Add(service);
}

UsbGuidMap::~UsbGuidMap() {
}

void UsbGuidMap::OnDeviceRemovedCleanup(
    scoped_refptr<device::UsbDevice> device) {
  auto iter = guid_to_id_map_.find(device->guid());
  if (iter != guid_to_id_map_.end()) {
    int id = iter->second;
    guid_to_id_map_.erase(iter);
    id_to_guid_map_.erase(id);
  }
}

}  // namespace extensions


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>bertrand: 52 s</title>
    <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
    <link href="../../../../../bootstrap.min.css" rel="stylesheet">
    <link href="../../../../../bootstrap-custom.css" rel="stylesheet">
    <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">

             Coq bench

clean / released

8.5.2~camlp4 / bertrand - 8.5.0

            « Up

              bertrand

                8.5.0
                52 s

 (2020-08-16 06:48:30 UTC)

Context

# Packages matching: installed
# Name              # Installed  # Synopsis
base-bigarray       base
base-num            base         Num library distributed with the OCaml compiler
base-threads        base
base-unix           base
camlp4              4.05+1       Camlp4 is a system for writing extensible parsers for programming languages
conf-findutils      1            Virtual package relying on findutils
coq                 8.5.2~camlp4 Formal proof management system.
num                 0            The Num library for arbitrary-precision integer and rational arithmetic
ocaml               4.05.0       The OCaml compiler (virtual package)
ocaml-base-compiler 4.05.0       Official 4.05.0 release
ocaml-config        1            OCaml Switch Configuration
ocamlbuild          0.14.0       OCamlbuild is a build system with builtin rules to easily build most OCaml projects.
# opam file:
opam-version: "2.0"
maintainer: "matej.kosik@inria.fr"
homepage: "https://github.com/coq-contribs/bertrand"
license: "LGPL 2"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/Bertrand"]
depends: [
  "ocaml"
  "coq" {>= "8.5" & < "8.6~"}
]
tags: [ "keyword:knuth's algorithm" "keyword:prime numbers" "keyword:bertrand's postulate" "category:Mathematics/Arithmetic and Number Theory/Number theory" "category:Computer Science/Decision Procedures and Certified Algorithms/Correctness proofs based on external tools" "category:Miscellaneous/Extracted Programs/Arithmetic" "date:2002" ]
authors: [ "Laurent Théry <>" ]
bug-reports: "https://github.com/coq-contribs/bertrand/issues"
dev-repo: "git+https://github.com/coq-contribs/bertrand.git"
synopsis: "Correctness of Knuth's algorithm for prime numbers"
description: """
A proof of correctness of the algorithm as described in
`The Art of Computer Programming: Fundamental Algorithms'
by Knuth, pages 147-149"""
flags: light-uninstall
url {
  src: "https://github.com/coq-contribs/bertrand/archive/v8.5.0.tar.gz"
  checksum: "md5=d7ed1b44196c96be0b55fc4fb3967d74"
}

Lint

Command

true

Return code

0

Dry install

Dry install with the current Coq version:

Command

opam install -y --show-action coq-bertrand.8.5.0 coq.8.5.2~camlp4

Return code

0

Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:

Command

true

Return code

0

Install dependencies

Command

opam list; echo; ulimit -Sv 4000000; timeout 2h opam install -y --deps-only coq-bertrand.8.5.0 coq.8.5.2~camlp4

Return code

0

Duration

4 s

Install

Command

opam list; echo; ulimit -Sv 16000000; timeout 2h opam install -y -v coq-bertrand.8.5.0 coq.8.5.2~camlp4

Return code

0

Duration

52 s

Installation size

Total: 3 M

474 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/Knuth_why.vo

160 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/Partition.vo

153 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/Knuth_why.glob

106 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/PrimeDirac.glob

98 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/Bertrand.glob

78 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/PrimeDirac.vo

74 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/Bertrand.vo

61 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/Binomial.glob

61 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/Misc.vo

56 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/Binomial.vo

54 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/Partition.glob

53 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/Gcd.vo

50 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/Div.vo

47 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/PowerDiv.vo

47 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/Divides.vo

47 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/PowerDiv.glob

44 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/Raux.vo

43 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/Misc.glob

42 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/Prime.vo

41 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/Summation.vo

41 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/Knuth_def.vo

40 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/Product.vo

39 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/Check128.vo

37 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/PowerBinomial.vo

34 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/Power.vo

33 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/why/WhyArrays.vo

32 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/Gcd.glob

32 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/Extraction.vo

30 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/DivDirac.vo

30 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/Summation.glob

30 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/Knuth_why.v

29 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/Div.glob

28 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/Product.glob

27 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/Divides.glob

24 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/Factorial_bis.vo

24 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/PowerBinomial.glob

21 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/PrimeDirac.v

17 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/Bertrand.v

17 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/Prime.glob

14 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/Partition.v

14 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/Knuth_def.glob

13 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/Raux.glob

13 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/Misc.v

13 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/Power.glob

12 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/Binomial.v

12 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/PowerDiv.v

11 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/Gcd.v

11 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/Check128.glob

9 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/Divides.v

9 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/Div.v

8 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/Prime.v

7 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/why/WhyArrays.glob

7 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/Summation.v

6 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/Product.v

6 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/PowerBinomial.v

5 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/DivDirac.glob

5 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/Knuth_def.v

5 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/Power.v

5 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/Check128.v

5 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/Raux.v

4 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/why/WhyArrays.v

3 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/sTactic.vo

3 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/DivDirac.v

2 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/sTactic.v

2 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/Factorial_bis.v

1 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/sTactic.glob

1 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/Extraction.v

1 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/Factorial_bis.glob

1 K ../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/Bertrand/Extraction.glob

Uninstall

Command

opam remove -y coq-bertrand.8.5.0

Return code

0

Missing removes

                none

Wrong removes

                none

          Sources are on GitHub. © Guillaume Claret.


text:
package com.teinvdlugt.android.brainfuckinterpreter;

import android.app.Activity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;

public class CellsAdapter extends RecyclerView.Adapter<CellsAdapter.ViewHolder> {
    private Activity context;
    private byte[] data;
    private int pointedCellPosition = 0;
    private Cell pointedCell;
    private LinearLayoutManager layoutManager;

    public CellsAdapter(Activity context, LinearLayoutManager layoutManager) {
        this.context = context;
        this.layoutManager = layoutManager;
        this.data = new byte[CellsLayout.MAX_CELL_AMOUNT];
    }

    public void incrementPointedCellValue() {
        data[pointedCellPosition]++;
        final int pointedCellPositionFinal = pointedCellPosition;
        context.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                notifyItemChanged(pointedCellPositionFinal);
            }
        });
    }

    public void decrementPointedCellValue() {
        data[pointedCellPosition]--;
        final int pointedCellPositionFinal = pointedCellPosition;
        context.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                notifyItemChanged(pointedCellPositionFinal);
            }
        });
    }

    public void setPointedCellValue(byte value) {
        data[pointedCellPosition] = value;
        final int pointedCellPositionFinal = pointedCellPosition;
        context.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                notifyItemChanged(pointedCellPositionFinal);
            }
        });
    }

    public byte getPointedCellValue() {
        return data[pointedCellPosition];
    }

    public void clearMemory() {
        this.data = new byte[CellsLayout.MAX_CELL_AMOUNT];
        pointedCellPosition = 0;
        context.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                layoutManager.scrollToPosition(0);
                notifyDataSetChanged();
            }
        });
    }

    public void movePointer(int position) {
        this.pointedCellPosition = position;

        context.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (pointedCell != null) pointedCell.setPointed(false);
                // TODO Try: if (layoutManager.findFirstVisibleItemPosition() <= position && layoutManager.findLastVisibleItemPosition() >= position) {
                notifyItemChanged(pointedCellPosition);
                // }
            }
        });
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new ViewHolder(new Cell(context));
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.cell.setText(Byte.toString(data[position]));
        if (position == pointedCellPosition) {
            holder.cell.setPointed(true);
            pointedCell = holder.cell;
        } else {
            holder.cell.setPointed(false);
        }
    }

    @Override
    public int getItemCount() {
        return data.length;
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        Cell cell;

        public ViewHolder(View itemView) {
            super(itemView);
            cell = (Cell) itemView;
        }
    }

}


text:
#include "mongo/base/initializer_context.h"

namespace mongo {

    InitializerContext::InitializerContext(const ArgumentVector& args,
                                           const EnvironmentMap& env,
                                           const ConfigurationVariableManager* configVariables)
        : _args(args), _env(env), _configVariables(configVariables) {}

}  // namespace mongo


text:
package org.everit.osgi.dev.maven.configuration;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Parameter;
import org.everit.osgi.dev.dist.util.configuration.MergeUtil;
import org.everit.osgi.dev.dist.util.configuration.schema.UseByType;

/**
 * The configuration of the launched OSGi Container.
 */
public class LaunchConfig extends AbstractLaunchConfig {

  /**
   * The overrides applied on this launch configuration.
   */
  @Parameter
  private LaunchConfigOverride[] overrides;

  public LaunchConfig() {
    super();
  }

  LaunchConfig(final Map<String, String> programArguments, final Map<String, String> vmArguments,
      final LaunchConfigOverride[] overrides) {
    super(programArguments, vmArguments);
    this.overrides = overrides;
  }

  private void checkForDuplicateOverrides(final LaunchConfigOverride[] launchConfigOverrides)
      throws MojoExecutionException {

    if (launchConfigOverrides == null) {
      return;
    }

    Set<UseByType> useBys = new HashSet<>();
    for (LaunchConfigOverride launchConfigOverride : launchConfigOverrides) {
      UseByType useBy = launchConfigOverride.useBy;
      if (useBys.contains(useBy)) {
        throw new MojoExecutionException("[" + useBy + "] defined twice in the configuration");
      }
      useBys.add(useBy);
    }
  }

  /**
   * Merges the this {@link LaunchConfig} to the {@link LaunchConfig} of the
   * environment and returns a new {@link LaunchConfig}.
   */
  public LaunchConfig createLaunchConfigForEnvironment(final LaunchConfig environmentLaunchConfig)
      throws MojoExecutionException {

    LaunchConfig rval = new LaunchConfig();

    mergeDefaults(rval, environmentLaunchConfig);

    checkForDuplicateOverrides(
        overrides);
    checkForDuplicateOverrides(
        environmentLaunchConfig == null ? null : environmentLaunchConfig.overrides);

    Set<UseByType> processedUseBys = new HashSet<>();
    List<LaunchConfigOverride> rvalOverrides = new ArrayList<>();

    if (overrides != null) {
      for (LaunchConfigOverride o1 : overrides) {

        UseByType useBy = o1.useBy;

        LaunchConfigOverride o2 = null;
        if (environmentLaunchConfig != null) {
          o2 = getPairOfUseBy(useBy, environmentLaunchConfig.overrides);
        }

        LaunchConfigOverride mergedLaunchConfigOverride =
            createMergedLaunchConfigOverride(o1, environmentLaunchConfig, o2, useBy);

        rvalOverrides.add(mergedLaunchConfigOverride);

        processedUseBys.add(useBy);
      }
    }

    if ((environmentLaunchConfig != null) && (environmentLaunchConfig.overrides != null)) {

      for (LaunchConfigOverride o2 : environmentLaunchConfig.overrides) {

        UseByType useBy = o2.useBy;

        if (!processedUseBys.contains(useBy)) {

          LaunchConfigOverride mergedLaunchConfigOverride =
              createMergedLaunchConfigOverride(null, environmentLaunchConfig, o2, useBy);

          rvalOverrides.add(mergedLaunchConfigOverride);

        }
      }
    }

    rval.overrides = rvalOverrides.toArray(new LaunchConfigOverride[] {});

    return rval;
  }

  private LaunchConfigOverride createMergedLaunchConfigOverride(final LaunchConfigOverride o1,
      final LaunchConfig d2, final LaunchConfigOverride o2, final UseByType useBy)
      throws MojoExecutionException {

    LaunchConfigOverride mergedLaunchConfigOverride = new LaunchConfigOverride();
    mergedLaunchConfigOverride.useBy = useBy;

    mergedLaunchConfigOverride.vmArguments = MergeUtil.mergeOverrides(
        getVmArgumentsIfAvailable(o1),
        getVmArgumentsIfAvailable(d2),
        getVmArgumentsIfAvailable(o2));
    mergedLaunchConfigOverride.programArguments = MergeUtil.mergeOverrides(
        getProgramArgumentsIfAvailable(o1),
        getProgramArgumentsIfAvailable(d2),
        getProgramArgumentsIfAvailable(o2));

    return mergedLaunchConfigOverride;
  }

  public LaunchConfigOverride[] getOverrides() {
    return overrides;
  }

  private LaunchConfigOverride getPairOfUseBy(final UseByType useBy,
      final LaunchConfigOverride[] environmentOverrides) {

    for (LaunchConfigOverride launchConfigOverride : environmentOverrides) {
      if (launchConfigOverride.useBy.equals(useBy)) {
        return launchConfigOverride;
      }
    }

    return null;
  }

  private Map<String, String> getProgramArgumentsIfAvailable(
      final AbstractLaunchConfig abstractLaunchConfig) {
    if (abstractLaunchConfig == null) {
      return null;
    }
    return abstractLaunchConfig.programArguments;
  }

  private Map<String, String> getVmArgumentsIfAvailable(
      final AbstractLaunchConfig abstractLaunchConfig) {
    if (abstractLaunchConfig == null) {
      return null;
    }
    return abstractLaunchConfig.vmArguments;
  }

  private void mergeDefaults(final LaunchConfig rval, final LaunchConfig environmentLaunchConfig)
      throws MojoExecutionException {

    rval.vmArguments = MergeUtil.mergeDefaults(
        vmArguments,
        environmentLaunchConfig == null ? null : environmentLaunchConfig.vmArguments);
    rval.programArguments = MergeUtil.mergeDefaults(
        programArguments,
        environmentLaunchConfig == null ? null : environmentLaunchConfig.programArguments);
  }

}


text:
import numpy as np

with open('data/labels.txt', 'w') as labels_file:
  classes = np.load('data/classes.npy')
  for klass in classes:
    labels_file.write(klass)
    labels_file.write('\n')


text:
package org.assertj.core.api.offsetdatetime;

import static java.time.OffsetDateTime.now;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.BDDAssertions.then;
import static org.assertj.core.api.BDDAssertions.thenIllegalArgumentException;
import static org.assertj.core.error.ShouldBeAfterOrEqualTo.shouldBeAfterOrEqualTo;
import static org.assertj.core.util.AssertionsUtil.expectAssertionError;
import static org.mockito.Mockito.verify;

import java.time.OffsetDateTime;
import java.time.format.DateTimeParseException;

import org.assertj.core.api.AbstractOffsetDateTimeAssertBaseTest;
import org.assertj.core.api.OffsetDateTimeAssert;
import org.assertj.core.api.ThrowableAssert.ThrowingCallable;
import org.junit.jupiter.api.Test;

/**
 * @author Paweł Stawicki
 * @author Joel Costigliola
 * @author Marcin Zajączkowski
 */
class OffsetDateTimeAssert_isAfterOrEqualTo_Test extends AbstractOffsetDateTimeAssertBaseTest {

  @Override
  protected OffsetDateTimeAssert invoke_api_method() {
    return assertions.isAfterOrEqualTo(REFERENCE)
                     .isAfterOrEqualTo(BEFORE.toString());
  }

  @Override
  protected void verify_internal_effects() {
    verify(comparables).assertIsAfterOrEqualTo(getInfo(assertions), getActual(assertions), REFERENCE);
    verify(comparables).assertIsAfterOrEqualTo(getInfo(assertions), getActual(assertions), BEFORE);
  }

  @Test
  void should_pass_if_actual_is_after_offsetDateTime_parameter_with_different_offset() {
    assertThat(AFTER_WITH_DIFFERENT_OFFSET).isAfterOrEqualTo(REFERENCE);
  }

  @Test
  void should_pass_if_actual_is_equal_to_offsetDateTime_parameter_with_different_offset() {
    assertThat(REFERENCE_WITH_DIFFERENT_OFFSET).isAfterOrEqualTo(REFERENCE);
  }

  @Test
  void should_fail_if_actual_is_before_offsetDateTime_parameter_with_different_offset() {
    // WHEN
    AssertionError assertionError = expectAssertionError(() -> assertThat(BEFORE_WITH_DIFFERENT_OFFSET).isAfterOrEqualTo(REFERENCE));
    // THEN
    String errorMessage = shouldBeAfterOrEqualTo(BEFORE_WITH_DIFFERENT_OFFSET, REFERENCE, COMPARISON_STRATEGY).create();
    then(assertionError).hasMessage(errorMessage);
  }

  @Test
  void should_fail_if_offsetDateTime_parameter_is_null() {
    // GIVEN
    OffsetDateTime otherOffsetDateTime = null;
    // WHEN
    ThrowingCallable code = () -> assertThat(now()).isAfterOrEqualTo(otherOffsetDateTime);
    // THEN
    thenIllegalArgumentException().isThrownBy(code)
                                  .withMessage("The OffsetDateTime to compare actual with should not be null");
  }

  @Test
  void should_fail_if_offsetDateTime_as_string_parameter_is_null() {
    // GIVEN
    String otherOffsetDateTimeAsString = null;
    // WHEN
    ThrowingCallable code = () -> assertThat(now()).isAfterOrEqualTo(otherOffsetDateTimeAsString);
    // THEN
    thenIllegalArgumentException().isThrownBy(code)
                                  .withMessage("The String representing the OffsetDateTime to compare actual with should not be null");
  }

  @Test
  void should_fail_if_given_string_parameter_cant_be_parsed() {
    assertThatThrownBy(() -> assertions.isAfterOrEqualTo("not an OffsetDateTime")).isInstanceOf(DateTimeParseException.class);
  }
}


text:
@interface OBADataSourceConfig_Tests : XCTestCase

@end

@implementation OBADataSourceConfig_Tests

- (void)testExample {
    NSURL *URL = [NSURL URLWithString:@"http://api.pugetsound.onebusaway.org"];
    OBADataSourceConfig *config = [[OBADataSourceConfig alloc] initWithURL:URL args:nil];
    NSURL *fooURL = [config constructURL:@"/foo.json" withArgs:nil];

    XCTAssertEqualObjects([NSURL URLWithString:@"http://api.pugetsound.onebusaway.org/foo.json"], fooURL);
}

- (void)testDefaultParameters {
    OBADataSourceConfig *googleMapsDataSourceConfig = [[OBADataSourceConfig alloc] initWithURL:[NSURL URLWithString:@"https://maps.googleapis.com"] args:@{@"sensor": @"true"}];

    NSURL *testURL = [googleMapsDataSourceConfig constructURL:@"/something-goes-here.json" withArgs:@{@"hello": @"world", @"foo": @"bar"}];

    BOOL nonDeterminismSucks = ([testURL.absoluteString isEqual:@"https://maps.googleapis.com/something-goes-here.json?sensor=true&foo=bar&hello=world"] ||
                                [testURL.absoluteString isEqual:@"https://maps.googleapis.com/something-goes-here.json?sensor=true&hello=world&foo=bar"]);

    XCTAssert(nonDeterminismSucks);
}

@end


text:
<!DOCTYPE html>

		<meta charset="utf-8" />

		<link href="asset/css/bootstrap.css" rel="stylesheet" />
		<link rel="stylesheet" href="asset/css/dexter.min.css" />
		<link rel="stylesheet" href="asset/css/font-awesome.min.css" />

		<link rel="stylesheet" href="asset/css/prettify.css" />

 Checker Code

					ICAST_IDIV_CAST_TO_DOUBLE

 Description

					Integral division result cast to double or float

 Severity

					Critical

 Detector / Bug Pattern

					IDivResultCastToDouble / ICAST

 More Information

This code casts the result of an integral division (e.g., int or long division)
operation to double or
float.
Doing division on integers truncates the result
to the integer value closest to zero.  The fact that the result
was cast to double suggests that this precision should have been retained.
What was probably meant was to cast one or both of the operands to
double before performing the division.  Here is an example:

 Bad Code

int x = 2;
int y = 5;

// Wrong: yields result 0.0
double value1 =  x / y;

 Good Code

int x = 2;
int y = 5;

// Right: yields result 0.4
double value2 =  x / (double) y;

 CWE ID

				CWE-586

 Code Review Asset

				N/A

 URLs

					STACKOVERFLOW SITE  :

					http://stackoverflow.com/questions/6949897/applying-casts-to-the-results-of-integer-and-floating-point-division-whats-goi


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

  <bean id="target" class="foo.bar.aop.Target"/>
  <bean id="target2" class="foo.bar.aop.Impl"/>
  <bean id="target3" class="foo.bar.aop.Subclass"/>
  <bean id="target4" class="foo.bar.aop.NotMatched"/>

  <aop:config proxy-target-class="true">
       <aop:aspect ref="aspect">
         <aop:declare-parents types-matching="foo.bar.aop.Target+" implement-interface="foo.bar.aop.MyMixin" default-impl="foo.bar.aop.MyMixinImpl"/>
         <aop:around pointcut="this(foo.bar.aop.MyMixin)" method="around"/>
       </aop:aspect>
     </aop:config>

  <bean id="aspect" class="foo.bar.aop.AspectBean"/>

</beans>


text:
module(..., lunit.testcase, package.seeall)

local common = dofile("common.lua")
local http = require("luanode.http")

function test()
local outstanding_reqs = 0
local test_req_body = "some stuff...\n"
local test_res_body = "other stuff!\n"
local sent_continue = false
local got_continue = false

function handler(self, req, res)
	assert_equal(sent_continue, true, "Full response sent before 100 Continue")
	common.debug("Server sending full response...")
	res:writeHead(200, {
		['Content-Type'] = 'text/plain',
		ABCD = "1"
	})
	res:finish(test_res_body)
end

local server = http.createServer(handler)
server:addListener("checkContinue", function(self, req, res)
	common.debug("Server got Expect: 100-continue...")
	res:writeContinue()
	sent_continue = true
	handler(self, req, res)
end)
server:listen(common.PORT)

server:addListener("listening", function()
	local client = http.createClient(common.PORT)
	req = client:request("POST", "/world", {
		Expect = "100-continue",
	})
	common.debug("Client sending request...")
	outstanding_reqs = outstanding_reqs + 1
	body = ""
	req:addListener('continue', function ()
		common.debug("Client got 100 Continue...")
		got_continue = true
		req:finish(test_req_body)
	end)
	req:addListener('response', function (self, res)
		assert_equal(got_continue, true, "Full response received before 100 Continue")
		assert_equal(200, res.statusCode, "Final status code was " .. res.statusCode .. ", not 200.")
		res:setEncoding("utf8")
		res:addListener('data', function (self, chunk) body = body .. chunk end)
		res:addListener('end', function ()
			common.debug("Got full response.")
			assert_equal(body, test_res_body, "Response body doesn't match.")
			assert_true(res.headers.abcd == "1", "Response headers missing.")
			outstanding_reqs = outstanding_reqs - 1
			if outstanding_reqs == 0 then
				server:close()
				process.exit()
			end
		end)
	end)
end)

process:loop()
end


text:
[CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
param(
    $module = "dbatools"
)
# Which process should we be looking for?
if ($psedition -eq 'Core') {
    $process = "pwsh"
} else {
    $process = "powershell"
}
if (($PSVersionTable.PSVersion.Major -le 5) -or ($PSVersionTable.PSVersion.Major -gt 6 -and $PSVersionTable.OS -contains "Windows")) {
    $isElevated = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)

    $ise = Get-Process powershell_ise -ErrorAction SilentlyContinue
    if ($ise) {
        return "PowerShell ISE found in use. Please close this program before using this script."
    }
} else {
    $isElevated = $null;
    $ise = $null;
}
$installedVersion = Get-InstalledModule $module -AllVersions | Select-Object Version, InstalledLocation
Write-Output "The currently installed version(s) of $module is/are: "
$installedVersion.Version

$results =
foreach ($v in $installedVersion) {
    if ($v.InstalledLocation -match "C:\\Users") {
        Add-Member -Force -InputObject $v -MemberType NoteProperty -Name IsUserScope -value $true
    } else {
        if (-not $isElevated) {
            Write-Output "$module version $v.Version cannot be removed without elevated session."
        }
        Add-Member -Force -InputObject $v -MemberType NoteProperty -Name IsUserScope -value $false
    }
    $v
}

$newestVersion = Find-Module $module | Select-Object Version
Write-Output "`nThe latest version of $module in the PSGallery is: $($newestVersion.Version)"
if ($installedVersion.Count -gt 1) {
    $olderVersions = @($installedVersion | Where-Object { [version]$_.Version -lt [version]$newestVersion.Version })
}

if ( ($olderVersions.Count -gt 0) -and $newestVersion.Version -in $installedVersion.Version ) {
    Write-Output "Latest version of $module found on $env:COMPUTERNAME."
    Write-Output "Older versions of $module also found. These will be uninstalled now."
    if ($isElevated) {
        $processes = Get-Process $process -IncludeUserName -ErrorAction SilentlyContinue | Where-Object Id -NE $pid
    } else {
        $processes = Get-Process $process -ErrorAction SilentlyContinue | Where-Object Id -NE $PID
    }
    if ($processes.Count -gt 0) {
        if ($Pscmdlet.ShouldProcess("$env:COMPUTERNAME", "Killing $($processes.Count) processes of powershell running")) {
            Write-Output "Death to the following process(es): $(($processes.Id) -join ",")"
            $processes | Stop-Process -ErrorVariable dangit -ErrorAction SilentlyContinue -Force
            if ($dangit) {
                Write-Warning "Not able to kill following processes: $((Get-Process $process | Where-Object Id -NE $pid).Id -join ",")"
            }
        }
    }
    if ($Pscmdlet.ShouldProcess("$env:COMPUTERNAME", "Removing old versions of $module.")) {
        foreach ($v in $olderVersions.Version) {
            Uninstall-Module $module -RequiredVersion $v -ErrorVariable dangit -ErrorAction SilentlyContinue -Force
            if ($dangit) {
                if ($dangit.Exception -like "*Administrator rights*") {
                    Write-Warning "Elevated session is required to uninstall $module version: $v"
                } else {
                    Write-Warning "Unable to remove $module version [$v] due to: `n`t$($dangit.Exception)"
                }
            }
        }
    }
    Write-Output "The End"
} elseif ( ($olderVersions.Count -gt 0) -and $newestVersion.Version -notin $installedVersion.Version ) {
    Write-Output "Update of $module is available"
    Write-Output "Older versions of $module found. These will be uninstalled now."
    if ($isElevated) {
        $processes = Get-Process $process -ErrorAction SilentlyContinue -IncludeUserName | Where-Object Id -NE $pid
    } else {
        $processes = Get-Process $process -ErrorAction SilentlyContinue | Where-Object Id -NE $PID
    }
    if ($processes.Count -gt 0) {
        if ($Pscmdlet.ShouldProcess("$env:COMPUTERNAME", "Killing $($processes.Count) processes of powershell running")) {
            Write-Output "Death to the following process(es): $(($processes.Id) -join ",")"
            $processes | Stop-Process -ErrorVariable dangit -ErrorAction SilentlyContinue -Force
            if ($dangit) {
                Write-Warning "Not able to kill following processes: $((Get-Process $process | Where-Object Id -NE $pid).Id -join ",")"
            }
        }
    }
    if ($Pscmdlet.ShouldProcess("$env:COMPUTERNAME", "Removing old versions of $module.")) {
        foreach ($v in $olderVersions.Version) {
            Uninstall-Module $module -RequiredVersion $v -ErrorVariable dangit -ErrorAction SilentlyContinue -Force
            if ($dangit) {
                if ($dangit.Exception -like "*Administrator rights*") {
                    Write-Warning "Elevated session is required to uninstall $module version: $v"
                } else {
                    Write-Warning "Unable to remove $module version [$v] due to: `n`t$($dangit.Exception)"
                }
            }
        }
    }
    Write-Output "Continuing to install latest release of $module"
    Install-Module $module -Force
    Write-Output "The End"
} else {
    Write-Output "No update/actions required."
}


text:
'use strict'

import maze from './maze'
import createMazeDisplay from './createMazeDisplay'
import mouse from './mouse'
import sockception from 'sockception'

let startNewGame = (edges, pos, onUpdate) => {
    // Clear current document
    while (document.body.firstChild) {
        document.body.removeChild(document.body.firstChild)
    }

    let mz = maze.grid(edges)
    let mazeDisplay = createMazeDisplay(mz)

    document.body.appendChild(
        mazeDisplay.element
    )

    let mouseCellPos = mazeDisplay.getPos(pos.row, pos.col)

    let cheeseCellPos = mazeDisplay.getPos(mz.size.rows - 1, mz.size.cols - 1)
    let cheeseElement = document.createElement('img')
    cheeseElement.src = 'assets/cheese.gif'
    cheeseElement.style.position = 'absolute'
    cheeseElement.style.left = cheeseCellPos.x - 16 + 'px'
    cheeseElement.style.top = cheeseCellPos.y - 16 + 'px'
    document.body.appendChild(cheeseElement)

    let mazeMouse = new mouse(mouseCellPos.x, mouseCellPos.y)
    document.body.appendChild(mazeMouse.element)

    onUpdate((update) => {
        let mouseCellPos = mazeDisplay.getPos(update.pos.row, update.pos.col)

        mazeMouse.move(mouseCellPos.x, mouseCellPos.y, 500).then(() => {
            console.log(update.stepCount + ' / ' + update.stepMax)
        })
    })
}

window.addEventListener('load', () => {
    let sock = sockception.connect('ws://' + window.location.hostname + ':56657')

    sock.route('connected').receiveOne(() => {
        let updateHandler = () => {}

        sock.route('getStarts').send().receiveMany((res) => {
            startNewGame(
                res.value,
                {row: 0, col: 0},
                handler => updateHandler = handler
            )
        })

        sock.route('getUpdates').send().receiveMany(res => updateHandler(res.value))

        sock.route('getStops').receiveMany((res) => {
            setTimeout(console.log(res.value), 500)
        })

        sock.route('getCurrent').send().receiveOne((res) => {
            if (res.value === null) {
                sock.route('start').send()
            } else {
                startNewGame(
                    res.value.edges,
                    res.value.update.pos,
                    handler => updateHandler = handler
                )
            }
        })
    })
})


text:
package com.xiledsystems.AlternateJavaBridgelib.components.altbridge.util;

import android.os.Build;

/**
 * Support for discovering which version of the Android SDK is on the phone.
 *
 * For more information about Android API levels see
 * http://developer.android.com/guide/appendix/api-levels.html.
 *
 */
public class SdkLevel {
  public static final int LEVEL_CUPCAKE = 3;           // a.k.a. 1.5
  public static final int LEVEL_DONUT = 4;             // a.k.a. 1.6
  public static final int LEVEL_ECLAIR = 5;            // a.k.a. 2.0
  public static final int LEVEL_ECLAIR_0_1 = 6;        // a.k.a. 2.0.1
  public static final int LEVEL_ECLAIR_MR1 = 7;        // a.k.a. 2.1
  public static final int LEVEL_FROYO = 8;             // a.k.a. 2.2
  public static final int LEVEL_GINGERBREAD = 9;       // a.k.a. 2.3
  public static final int LEVEL_GINGERBREAD_MR1 = 10;  // a.k.a. 2.3.3
  public static final int LEVEL_HONEYCOMB = 11;        // a.k.a. 3.0
  public static final int LEVEL_HONEYCOMB_MR2 = 13;	   // a.k.a  3.2
  public static final int LEVEL_ICE_CREAM_SANDWICH = 14; // a.k.a 4.0.1
  public static final int LEVEL_ICE_CREAM_SANDWICH_MR1 = 15; // a.k.a 4.0.3

  private SdkLevel() {
  }

  /**
   * Returns the API level of the SDK on the phone
   */
  public static int getLevel() {
    // Determine the SDK version in a way that is compatible with API level 3.
    return Integer.parseInt(Build.VERSION.SDK);
  }
}


text:
define(function(){

	/**
	 * Commons#identity(elem) -> ?
	 * Returns elem without any modification.
	 */
	function identity(elem)
	{
		return elem;
	}

	/**
	 * Commons#extend(destination, source, override=false)
	 * Copies all the elements of source to destination. If override is set to true,
	 * it will override destination elements.
	 */
	function extend(destination, source, override)
	{
		for(var element in source)
			destination[element] = (!override) ? destination[element] || source[element] : source[element];
	}

	return {
		id: identity,
		extend: extend
	};
});


text:
<?php

require dirname(__DIR__) . '/../vendor/autoload.php';

use OpenCloud\OpenStack;

// 1. Instantiate an OpenStack client.
$client = new OpenStack('{authUrl}', array(
    'username' => '{username}',
    'password' => '{password}',
));

// 2. Obtain an Orchestration service object from the client.
$orchestrationService = $client->orchestrationService(null, '{region}');

// 3. Get build info.
/** @var $resourceType OpenCloud\Orchestration\Resource\BuildInfo **/
$buildInfo = $orchestrationService->getBuildInfo();


text:
var fs = require("fs");
var path = require("path");
var config = require("config.js");
var logger = require("logger.js")();

module.exports = function testcase(name, id, file){

	this.name = name;
	this.id = id;
	this.file = file;
	this.train = [];
	this.test = [];

	this.loadMaster = function(){
		if(!testcase.prototype.fileList){
			try{
				var data = fs.readFileSync(path.join(config.testcase_dir,"master.json"));
				testcase.prototype.fileList = JSON.parse(data);
			}catch(err){
				//create new fileList
				testcase.prototype.fileList = [];
				logger.error(err);
			}
		}
	};

	this.saveMaster = function(){
		if(testcase.prototype.fileList){
			try{
				fs.writeFileSync(path.join(config.testcase_dir,"master.json"), JSON.stringify(testcase.prototype.fileList));
			}catch(err){
				logger.error(err);
			}
		}
	};

	this.getFileList = function(){
		if(testcase.prototype.fileList){
			return testcase.prototype.fileList;
		}else throw "No file list was found.";
	};

	this.load = function(file, callback){
		fs.readFile(path.join(config.testcase_dir,file), (err, data) => {
			if(err) callback(err);
			Object.assign(this,JSON.parse(data));
			callback();
		});
	};

	this.save = function(callback){
		testcase.prototype.fileList.push({
			name : this.name,
			id : this.id,
			file : this.file
		});
		fs.writeFile(path.join(config.testcase_dir,this.file), JSON.stringify(this), callback);
	};

};


text:
# sitedeploy-core
[![Build Status](https://secure.travis-ci.org/sitedeploy/core.png?branch=master)](http://travis-ci.org/sitedeploy/core)  [![Npm module](https://badge.fury.io/js/core.png)](https://npmjs.org/package/core) [![Code Climate](https://codeclimate.com/github/sitedeploy/core.png)](https://codeclimate.com/github/sitedeploy/core)

sitedeploy core libraries

## Getting Started
Install the module with: `npm install sitedeploy-core --save`

```javascript
var sm = require('sitedeploy-core');

//create a sitedeploy folder descriptor:
var folder = sm.createDescriptor('static/css');
console.dir(folder)

/*

{
    "etag": 12,
    "content": {
        "vendor": {
            "jquery": {
                "jquery.js": "0d4c0e15"
            }
        },
        "file1.css": "49d8d999",
        "file2.css": "07ee315f"
    }
}
*/

```

The sitedeploy folder descriptor file is used for multiple purposes. First
it is used by the connect middleware to check when to serve a new version
of a folder to the client.

Descriptor could be cached in memory, but old version could be saved
to disk, to compare different versions and build a patch release.

## Contributing
In lieu of a formal styleguide, take care to maintain the existing coding style.
Add unit tests for any new or changed functionality.

## License
Copyright (c) 2014 Andrea Parodi
Licensed under the MIT license.


text:
/******************************************************************************
 * 版权所有 刘大磊 2013-07-01												      *
 *	作者:刘大磊								                                      *
 * 电话:13336390671                                                          *
 * email:ldlqdsd@126.com						                          *
 *****************************************************************************/

package com.delmar.base.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.delmar.base.dao.EventTypeModeDao;
import com.delmar.base.model.EventTypeMode;
import com.delmar.base.service.EventTypeModeService;
import com.delmar.core.dao.CoreDao;
import com.delmar.core.service.impl.CoreServiceImpl;

/**
 * @author 刘大磊 22015-03-25 15:22:29
 */
@Service("eventTypeModeService")
public class EventTypeModeServiceImpl extends CoreServiceImpl<EventTypeMode> implements
		EventTypeModeService {
	@Autowired
	private EventTypeModeDao eventTypeModeDao;
	/* (non-Javadoc)
	 * @see CoreService.CoreServiceImpl#getCoreDao()
	 */
	@Override
	protected CoreDao<EventTypeMode> getCoreDao() {
		return eventTypeModeDao;
	}
	public void deleteEventTypeModeList(Integer[] ids)
	{
		if(ids!=null)
		for(Integer id:ids)
		{
			eventTypeModeDao.deleteByPrimaryKey(id);
		}
	}

}


text:
namespace instrument {
namespace transforms {

using block_graph::Displacement;
using block_graph::Operand;

const char SecurityCookieCheckHookTransform::kTransformName[] =
    "SecurityCookieCheckHookTransform";

const char SecurityCookieCheckHookTransform::kReportGsFailure[] =
    "__report_gsfailure";

const char SecurityCookieCheckHookTransform::kSyzygyReportGsFailure[] =
    "__syzygy_report_gsfailure";

const uint32_t SecurityCookieCheckHookTransform::kInvalidUserAddress =
    0xdeadbeef;

bool SecurityCookieCheckHookTransform::TransformBlockGraph(
    const TransformPolicyInterface* policy,
    BlockGraph* block_graph,
    BlockGraph::Block* header_block) {
  BlockGraph::Block* report_gsfailure = nullptr;
  BlockGraph::BlockMap& blocks = block_graph->blocks_mutable();
  for (auto& block : blocks) {
    std::string name(block.second.name());
    if (name == kReportGsFailure) {
      report_gsfailure = &block.second;
      break;
    }
  }

  if (report_gsfailure == nullptr) {
    LOG(ERROR) << "Could not find " << kReportGsFailure << ".";
    return false;
  }

  if (report_gsfailure->referrers().size() != 1) {
    // We bail out if we don't have a single referrer as the only
    // expected referrer is supposed to be __security_cookie_check.
    // If there is more than one, we would rather bail out than take
    // a chance at modifying the behavior of the PE image.
    LOG(ERROR) << "Only a single referrer to " << kReportGsFailure
               << " is expected.";
    return false;
  }

  LOG(INFO) << "Found a " << kReportGsFailure
            << " implementation, hooking it now.";
  BlockGraph::Section* section_text = block_graph->FindOrAddSection(
      pe::kCodeSectionName, pe::kCodeCharacteristics);

  // All of the below is needed to build the instrumentation via the assembler.
  BasicBlockSubGraph bbsg;
  BasicBlockSubGraph::BlockDescription* block_desc = bbsg.AddBlockDescription(
      kSyzygyReportGsFailure, nullptr, BlockGraph::CODE_BLOCK,
      section_text->id(), 1, 0);

  BasicCodeBlock* bb = bbsg.AddBasicCodeBlock(kSyzygyReportGsFailure);
  block_desc->basic_block_order.push_back(bb);
  BasicBlockAssembler assm(bb->instructions().begin(), &bb->instructions());
  assm.mov(Operand(Displacement(kInvalidUserAddress)), assm::eax);

  // Condense into a block.
  BlockBuilder block_builder(block_graph);
  if (!block_builder.Merge(&bbsg)) {
    LOG(ERROR) << "Failed to build " << kSyzygyReportGsFailure << " block.";
    return false;
  }

  DCHECK_EQ(1u, block_builder.new_blocks().size());

  // Transfer the referrers to the new block, and delete the old one.
  BlockGraph::Block* syzygy_report_gsfailure =
      block_builder.new_blocks().front();
  report_gsfailure->TransferReferrers(
      0, syzygy_report_gsfailure,
      BlockGraph::Block::kTransferInternalReferences);

  report_gsfailure->RemoveAllReferences();
  if (!block_graph->RemoveBlock(report_gsfailure)) {
    LOG(ERROR) << "Removing " << kReportGsFailure << " failed.";
    return false;
  }

  return true;
}

}  // namespace transforms
}  // namespace instrument


text:
"""
This file is part of the web2py Web Framework
Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>
License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
"""

import os
import sys
import socket
import platform
from storage import Storage

global_settings = Storage()
settings = global_settings  # legacy compatibility

if not hasattr(os, 'mkdir'):
    global_settings.db_sessions = True

if global_settings.db_sessions is not True:
    global_settings.db_sessions = set()

global_settings.gluon_parent = \
    os.environ.get('web2py_path', os.getcwd())

global_settings.applications_parent = global_settings.gluon_parent

global_settings.app_folders = set()

global_settings.debugging = False

global_settings.is_pypy = \
    hasattr(platform, 'python_implementation') and \
    platform.python_implementation() == 'PyPy'

global_settings.is_jython = \
    'java' in sys.platform.lower() or \
    hasattr(sys, 'JYTHON_JAR') or \
    str(sys.copyright).find('Jython') > 0


text:
package org.codecover.instrumentation.java.measurement;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * This class is used to get to know the path of the coverage log file and to
 * add additional files to the instrumentation target.

 *

 * The process of getting the target for the coverage log file goes the
 * following. If the path of the coverage log file is found on a level, it is
 * returned. If it is not found, the lower level is asked.
 *

 *
{@link System#getProperty(String)} is asked for "{@link CoverageLogPath#PROPERTY_PATH_VARIABLE}"

 *
{@link System#getenv(String)} is asked for "{@link CoverageLogPath#ENVIRONMENT_PATH_VARIABLE}"

 *
the {@link #getDefaultPath()} method is asked for it

 * </lo>
 *
 * @author Christoph Müller
 *
 * @version 1.0 ($Id: CoverageLogPath.java 8 2008-03-27 19:46:02Z ahija $)
 */
public class CoverageLogPath {

    private static final String DEFAULT_TARGET_FILE_NAME = "coverage-log";

    private static final String DEFAULT_TARGET_FILE_EXTENSION = "clf";

    /**
     * The default path of the coverage log file.
     */
    private static final String DEFAULT_TARGET_FILE = DEFAULT_TARGET_FILE_NAME +
        "." + DEFAULT_TARGET_FILE_EXTENSION;

    /**
     * The format for the suffix of the coverage-log:

     *

     * yyyy-MM-dd-HH-mm-ss-SSS
     *
     * @see SimpleDateFormat
     */
    public static final DateFormat COVERAGE_LOG_DATE_SUFFIX = new SimpleDateFormat(
    "yyyy-MM-dd-HH-mm-ss-SSS");

    /**
     * The name of the property, used to get the path of the coverage log file: {@value} .
     * @see System#getProperty(String)
     */
    public static final String PROPERTY_PATH_VARIABLE = "org.codecover.coverage-log-file";

    /**
     * The name of the property, used to allow overwriting of the coverage log: {@value} .
 To allow overwriting, the property must be set and its value must not be false or no.
     * @see System#getProperty(String)
     */
    public static final String PROPERTY_OVERWRITE_VARIABLE = "org.codecover.coverage-log-overwrite";

    /**
     * The name of the environment variable, used to get the path of the coverage log file:  {@value} .
     * @see System#getenv(String)
     */
    public static final String ENVIRONMENT_PATH_VARIABLE = "org.codecover.coverage-log-file";

    /**
     * This is the pattern, which is used to get a coverage log file name and make it unique:  {@link #getAlternativeFile(File)} .

 The pattern looks like:  {@value}

     * @see #getAlternativeFile(File)  for usage information
     */
    public static final String ALTERNATIVE_FILE_PATTERN_STRING = ".*\\((\\d{1,18}+)\\)";

    private static final Pattern ALTERNATIVE_FILE_PATTERN = Pattern.compile(ALTERNATIVE_FILE_PATTERN_STRING);

    private static final Object LOCK = new Object();

    /**
     * Stores the path of the coverage log file after {@link #getCoverageLogFile(String)}  has decided its target.
     */
    private static File usedPath = null;

    /**
     * Change this return value to a relative or absolute path, where ever the
     * coverage log file should be written to.
     *
     * @return the path to the coverage log file
     */
    private static String getDefaultPath() {
        return DEFAULT_TARGET_FILE_NAME + "-" +
               COVERAGE_LOG_DATE_SUFFIX.format(new Date()) + "." +
               DEFAULT_TARGET_FILE_EXTENSION;
    }

    /**
     * Gets the path, where the Coverage Log file will be created.
     *
     * @param preferredPath The preferred path of the clf, if now property is
     * set.
     *
     * @return The path of the Coverage Log File.
     * @see CoverageLogPath
     * @see CoverageResultLogFile#getInstance()
     */
    public static File getCoverageLogFile(String preferredPath) {
        // just one Thread can create the path of the coverage log file
        synchronized (LOCK) {
            if (usedPath != null) {
                return usedPath;
            }

            String clfPath = null;

            // try the PROPERTY_PATH_VARIABLE
            try {
                clfPath = System.getProperty(PROPERTY_PATH_VARIABLE);
            } catch (Throwable t) {
                // access was not allowed
            }

            // try the ENVIRONMENT_PATH_VARIABLE
            if (clfPath == null) {
                try {
                    clfPath = System.getenv(ENVIRONMENT_PATH_VARIABLE);
                } catch (Throwable t) {
                    // access was not allowed
                }
            }

            // try the preferredPath
            if (clfPath == null) {
                clfPath = preferredPath;
            }

            // user the #getDefaultPath
            if (clfPath == null) {
                clfPath = getDefaultPath();
            }

            File clfFile = new File(clfPath);
            if (clfFile.isDirectory()) {
                clfPath = clfPath + File.separatorChar
                + DEFAULT_TARGET_FILE;
                clfFile = new File(clfPath);
            }

            clfFile = clfFile.getAbsoluteFile();

            try {
                String overwriteProp = System.getProperty(PROPERTY_OVERWRITE_VARIABLE);
                if (overwriteProp == null ||
                        overwriteProp.equals("false") ||
                        overwriteProp.equals("no")) {
                    clfFile = getAlternativeFile(clfFile).getAbsoluteFile();
                }
            } catch (Throwable t) {
                // access was not allowed
            }

            // store the decision in used Path
            usedPath = clfFile;
            return clfFile;
        }
    }

    /**
     * Ensures, that a file with the given name does not exist. This is done by
     * adding (1), (2) and so on.

     *

     * Detailed description:

     * We use a {@link Pattern} for this job: {link #ALTERNATIVE_FILE_PATTERN_STRING}.

     * At the beginning of the file name any character is allowed by the pattern.
     * Then there might be a number in brackets: (12). This number
     * has at least one, at most 18 digits. So it can be casted into a {@link Long}.

     * If the pattern does not match, we
     * can add a (1) to the name of the file, to get an alternative
     * file name.

     * If the pattern matches, we can get the number of the capturing group 1,
     * 12, cast it into a {@link Long} and increment it. Perhaps
     * this file name is not used.
     *
     * @param clfFile The file to use as start.
     *
     * @return The file, based on clfFile, that does not exists yet.
     *
     * @see #ALTERNATIVE_FILE_PATTERN_STRING
     */
    public static File getAlternativeFile(File clfFile) {
        while (clfFile.exists()) {
            String parentPath = clfFile.getParentFile().getAbsolutePath();
            String fileName = clfFile.getName();
            String extension = getExtension(clfFile);
            if (extension.length() > 0) {
                // remove the extension and the dot from the file name
                fileName = fileName.substring(0,
                        fileName.length() - extension.length() - 1);
                extension = '.' + extension;
            }

            // matches the pattern?
            Matcher matcher = ALTERNATIVE_FILE_PATTERN.matcher(fileName);
            if (matcher.matches()) {
                // first get the number
                String numberAsString = fileName.substring(matcher.start(1),
                        matcher.end(1));
                // then truncate the file name until the opening (
                fileName = fileName.substring(0, matcher.start(1));
                long number = Long.parseLong(numberAsString);
                fileName += Long.toString(number + 1) + ')';
            } else {
                // we can add a (1)
                fileName += "(1)";
            }

            clfFile = new File(parentPath + File.separatorChar + fileName +
                    extension);
        }
        return clfFile;
    }

    /**
     * Gets the extension of a file.

     *

     * An extension is defined as the String after the last dot. The extensions
     * is always returned in lower case. If there is no dot, the extensions is
     * defined as "".
     *
     *

     *      getExtension(Main.java) == "java"
     *      getExtension(Main.java.in) == "in"
     *      getExtension(Main) == ""
     *

     *
     * Copied from ExtensionFileFilter#getExtension(File) that this
     * class needs not to be shipped as source file too.
     *
     * @param file
     *            The given file.
     * @return The extension of the file.
     *
     */
    public static String getExtension(File file) {
        if (file == null) {
            return "";
        }
        // file != null

        String name = file.getName();
        // name != null

        String extensions = "";
        int i = name.lastIndexOf('.');
        if (i >= 0 && i < name.length() - 1) {
            extensions = name.substring(i + 1).toLowerCase();
        }
        return extensions;
    }
}


text:
package org.guvnor.ala.wildfly.marshalling;

import org.guvnor.ala.marshalling.impl.JSONBaseMarshaller;
import org.guvnor.ala.wildfly.model.WildflyRuntime;

/**
 * WildflyRuntime marshaller implementation.
 */
public class WildflyRuntimeMarshaller
        extends JSONBaseMarshaller<WildflyRuntime> {

    public WildflyRuntimeMarshaller() {
        super(WildflyRuntime.class);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/ColorPrimary">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="64dp"
        android:layout_marginRight="8dp"
        android:gravity="center_vertical"
        android:text="Name"
        android:textColor="@color/white"
        android:paddingTop="32sp">
        </TextView>
    <EditText
        android:id="@+id/editTextName"
        style="@style/EditTextStyle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="64dp"
        android:layout_marginRight="8dp"
        android:gravity="center_vertical"
        android:hint="@string/name"
        android:textColor="@color/black"
        android:textColorHint="@color/abc_primary_text_disable_only_material_dark"
        />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="64dp"
        android:layout_marginRight="8dp"
        android:gravity="center_vertical"
        android:text="Description"
        android:textColor="@color/white">
    </TextView>
    <EditText
        android:id="@+id/editTextDescription"
        style="@style/EditTextStyle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="64dp"
        android:layout_marginRight="8dp"
        android:gravity="center_vertical"
        android:hint="@string/name"
        android:textColor="@color/black"
        android:textColorHint="@color/abc_primary_text_disable_only_material_dark"
        />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="64dp"
        android:layout_marginRight="8dp"
        android:gravity="center_vertical"
        android:text="Location"
        android:textColor="@color/white">
    </TextView>
    <EditText
        android:id="@+id/editTextLocation"
        style="@style/EditTextStyle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="64dp"
        android:layout_marginRight="8dp"
        android:gravity="center_vertical"
        android:hint="@string/name"
        android:textColor="@color/black"
        android:textColorHint="@color/abc_primary_text_disable_only_material_dark"
        />

</LinearLayout>


text:
import os
import shutil
from optparse import make_option

from django.core.exceptions import ImproperlyConfigured
from django.core.management.base import BaseCommand

from goog import utils

class Command(BaseCommand):
    help = "Download Closure library and compiler."
    option_list = BaseCommand.option_list + (
        make_option('--force',
            action='store_true',
            dest='force',
            default=False,
            help='Download files even if they exist locally.'),
        )

    def handle(self, *args, **options):
        force = options.get('force', False)
        download = True
        try:
            lib_path = utils.get_closure_path(interactive=False)
            print 'Closure library found at %s' % lib_path
            if force:
                print 'Removing as requested.'
                shutil.rmtree(lib_path)
            else:
                download = False
        except ImproperlyConfigured:
            pass
        if download:
            utils.get_closure_path(interactive=True)
        download = True
        try:
            jar_path = utils.get_compiler_jar(interactive=False)
            print 'Closure compiler found at %s' % jar_path
            if force:
                print 'Removing as requested.'
                shutil.rmtree(os.path.split(jar_path)[0])
            else:
                download = False
        except ImproperlyConfigured:
            pass
        if download:
            utils.get_compiler_jar(interactive=True)


text:
package br.gov.servicos.editor.usuarios.token;

import org.springframework.stereotype.Component;

import java.math.BigInteger;
import java.security.SecureRandom;

@Component
public class GeradorToken {
    private final SecureRandom secureRandom = new SecureRandom();

    public String gerar() {
        return new BigInteger(130, secureRandom).toString(32);
    }
}


text:
@class DSANode, DSATextSearchResult, DSMQuery, NSArray, NSString, NSURL;

@interface IDEDocSearchResult : NSObject
{
    DSANode *_searchResultNode;
    DSATextSearchResult *_textResult;
    DSMQuery *_searchQuery;
    NSURL *_overrideURL;
}

+ (id)searchResultForTextResult:(id)arg1 overrideURL:(id)arg2 fromQuery:(id)arg3;
+ (id)searchResultForTextResult:(id)arg1 fromQuery:(id)arg2;
+ (id)searchResultForNode:(id)arg1 fromQuery:(id)arg2;
@property(copy) NSURL *overrideURL; // @synthesize overrideURL=_overrideURL;
@property(retain) DSMQuery *searchQuery; // @synthesize searchQuery=_searchQuery;
@property(retain) DSATextSearchResult *textResult; // @synthesize textResult=_textResult;
@property(retain) DSANode *searchResultNode; // @synthesize searchResultNode=_searchResultNode;
- (void).cxx_destruct;
- (id)childItems;
- (id)description;
@property(readonly, copy) NSURL *URL;
@property(readonly, copy) NSString *displayName;
@property(readonly, copy) NSArray *children;

@end


text:
"""
    netvisor.schemas.sales_payments.list
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    :copyright: (c) 2013-2016 by Fast Monkeys Oy.
    :license: MIT, see LICENSE for more details.
"""
from marshmallow import Schema, fields, post_load

from ..fields import Decimal, FinnishDate, List

class BankStatusErrorDescriptionSchema(Schema):
    code = fields.String(load_from='@code')
    description = fields.String(load_from='#text')

class SalesPaymentSchema(Schema):
    netvisor_key = fields.Integer()
    name = fields.String()
    date = FinnishDate()
    sum = Decimal()
    foreign_currency_amount = Decimal(allow_none=True)
    reference_number = fields.String()
    invoice_number = fields.Integer()
    bank_status = fields.String()
    bank_status_error_description = fields.Nested(
        BankStatusErrorDescriptionSchema
    )

class SalesPaymentListSchema(Schema):
    sales_payments = List(
        fields.Nested(SalesPaymentSchema),
        load_from='sales_payment'
    )

    @post_load
    def preprocess_sales_payment_list(self, input_data):
        return input_data['sales_payments'] if input_data else []


text:
/**
 * Created by ar on 11/24/15.
 */
var db=require("../config/MysqlInit");

var auxDescription={};

auxDescription.create=function(sctIdRecord,callback){

    db.getDB(function (err,connection)
    {

        if (err) throw err;
        connection.query('INSERT INTO auxDescription SET ?', sctIdRecord, function(error, result)
        {
            connection.release();
            if(error)
            {
                callback (error,null);
            }
            else
            {

                callback(null, sctIdRecord);
            }
        });
    });
};

auxDescription.availableCount=function(query,callback){

    db.getDB(function (err,connection)
    {
        if (err) throw err;

        var sql;
        sql = "SELECT count(*) as count FROM auxDescription where modified_at is null and namespace=" + connection.escape(query.namespace);
        connection.query(sql, function(error, rows)
        {
            connection.release();
            if(error)
            {
                callback(error, null);
            }
            else
            {
                if (rows && rows.length>0) {
                    callback(null, rows[0].count);
                }else{
                    callback(null, 0);
                }
            }
        });
    });
};
module.exports=auxDescription;