text:
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

async function main(name = 'projects/my-project/secrets/my-secret/versions/1') {
  // [START secretmanager_access_secret_version]
  /**
   * TODO(developer): Uncomment these variables before running the sample.
   */
  // const name = 'projects/my-project/secrets/my-secret/versions/5';
  // const name = 'projects/my-project/secrets/my-secret/versions/latest';

  // Imports the Secret Manager library
  const {SecretManagerServiceClient} = require('@google-cloud/secret-manager');

  // Instantiates a client
  const client = new SecretManagerServiceClient();

  async function accessSecretVersion() {
    const [version] = await client.accessSecretVersion({
      name: name,
    });

    // Extract the payload as a string.
    const payload = version.payload.data.toString();

    // WARNING: Do not print the secret in a production environment - this
    // snippet is showing how to access the secret material.
    console.info(`Payload: ${payload}`);
  }

  accessSecretVersion();
  // [END secretmanager_access_secret_version]
}

const args = process.argv.slice(2);
main(...args).catch(console.error);


text:
//
//  GTLPlusAclentryResource.h
//

// ----------------------------------------------------------------------------
// NOTE: This file is generated from Google APIs Discovery Service.
// Service:
//   Google+ API (plus/v1)
// Description:
//   The Google+ API enables developers to build on top of the Google+ platform.
// Documentation:
//   https://developers.google.com/+/api/
// Classes:
//   GTLPlusAclentryResource (0 custom class methods, 3 custom properties)

#if GTL_BUILT_AS_FRAMEWORK
  #import "GTL/GTLObject.h"
#else
  #import "GTLObject.h"
#endif

// ----------------------------------------------------------------------------
//
//   GTLPlusAclentryResource
//

@interface GTLPlusAclentryResource : GTLObject

// A descriptive name for this entry. Suitable for display.
@property (nonatomic, copy) NSString *displayName;

// The ID of the entry. For entries of type "person" or "circle", this is the ID
// of the resource. For other types, this property is not set.
// identifier property maps to 'id' in JSON (to avoid Objective C's 'id').
@property (nonatomic, copy) NSString *identifier;

// The type of entry describing to whom access is granted. Possible values are:
// - "person" - Access to an individual.
// - "circle" - Access to members of a circle.
// - "myCircles" - Access to members of all the person's circles.
// - "extendedCircles" - Access to members of all the person's circles, plus all
// of the people in their circles.
// - "domain" - Access to members of the person's Google Apps domain.
// - "public" - Access to anyone on the web.
@property (nonatomic, copy) NSString *type;

@end

redpajama_set_name: RedPajamaGithub


text:
using System;
namespace System.Windows.Input
{
    /// <summary>
    ///    The raw actions being reported from the mouse.
    /// </summary>
    /// <remarks>
    ///     Note that multiple actions can be reported at once.
    /// </remarks>
    [Flags]
    internal enum RawMouseActions
    {
        /// <summary>
        ///     No mouse actions.
        /// </summary>
        None = 0x0,

        /// <summary>
        ///     The mouse attributes have changed.  The application needs to
        ///     query the mouse attributes.
        /// </summary>
        AttributesChanged = 0x1,

        /// <summary>
        ///     The mouse became active in the application.  The application
        ///     may need to refresh its mouse state.
        /// </summary>
        Activate = 0x2,

        /// <summary>
        ///     The mouse became inactive in the application.  The application
        ///     may need to clear its mouse state.
        /// </summary>
        Deactivate = 0x4,

        /// <summary>
        ///     The mouse moved, and the position is reported relative to
        ///     the last reported position.
        /// </summary>
        RelativeMove = 0x8,

        /// <summary>
        ///     The mouse moved, and the position is reported in absolute
        ///     coordinates.
        /// </summary>
        AbsoluteMove = 0x10,

        /// <summary>
        ///     The mouse moved, and the position is reported in coordinates
        ///     relative to the virtual desktop.
        /// </summary>
        VirtualDesktopMove = 0x20,

        /// <summary>
        ///     The first button was pressed.
        /// </summary>
        Button1Press = 0x40,

        /// <summary>
        ///     The first button was released.
        /// </summary>
        Button1Release = 0x80,

        /// <summary>
        ///     The second button was pressed.
        /// </summary>
        Button2Press = 0x100,

        /// <summary>
        ///     The second button was released.
        /// </summary>
        Button2Release = 0x200,

        /// <summary>
        ///     The third button was pressed.
        /// </summary>
        Button3Press = 0x400,

        /// <summary>
        ///     The third button was released.
        /// </summary>
        Button3Release = 0x800,

        /// <summary>
        ///     The fourth button was pressed.
        /// </summary>
        Button4Press = 0x1000,

        /// <summary>
        ///     The fourth button was released.
        /// </summary>
        Button4Release = 0x2000,

        /// <summary>
        ///     The fifth button was pressed.
        /// </summary>
        Button5Press = 0x4000,

        /// <summary>
        ///     The fifth button was released.
        /// </summary>
        Button5Release = 0x8000,

        /// <summary>
        ///     The vertical wheel was roteated.
        /// </summary>
        VerticalWheelRotate = 0x10000,

        /// <summary>
        ///     The horizontal wheel was roteated.
        /// </summary>
        HorizontalWheelRotate = 0x20000,

        /// <summary>
        ///     The mouse cursor was queried.
        /// </summary>
        QueryCursor = 0x40000,

        /// <summary>
        ///     The mouse capture was lost.
        /// </summary>
        CancelCapture = 0x80000

        // update the IsValid method in RawMouseInputReport when this enum is changed
    }
}


text:
var App = (function () {
	'use strict';

	App.formMultiselect = function( ){

	//Bootstrap multiselect init
 	$('#example1').multiselect();

    $('#example2').multiselect();

    $('#example3').multiselect({
        buttonClass: 'btn btn-link'
    });

    $('#example4').multiselect({
        buttonClass: 'btn btn-default btn-sm'
    });

    $('#example6').multiselect();

    $('#example9').multiselect({
        onChange:function(element, checked){
            alert('Change event invoked!');
            console.log(element);
        }
    });

    for (var i = 1; i <= 100; i++) {
        $('#example11').append('<option value="' + i + '">Options ' + i + '</option>');
    }
    $('#example11').multiselect({
        maxHeight: 150
    })

    $('#example13').multiselect();

    $('#example14').multiselect({
        buttonWidth: '500px',
        buttonText: function(options) {
            if (options.length === 0) {
                return 'None selected';
            }
            else {
                var selected = '';
                options.each(function() {
                    selected += $(this).text() + ', ';
                });
                return selected.substr(0, selected.length -2) + ' ';
            }
        }
    });

    $('#example16').multiselect({
        onChange: function(option, checked) {
                  if (checked === false) {
                      $('#example16').multiselect('select', option.val());
                  }
        }
    });

    $('#example19').multiselect();

    $('#example20').multiselect({
        selectedClass: null
    });

    $('#example23').multiselect();

    $('#example24').multiselect();

    $('#example25').multiselect({
    	dropRight: true,
    	buttonWidth: '300px'
    });

    $('#example27').multiselect({
    	includeSelectAllOption: true
    });

    $('#example28').multiselect({
    	enableFiltering: true,
        maxHeight: 150
    });

    $('#example32').multiselect();

    $('#example39').multiselect({
      includeSelectAllOption: true,
    	enableCaseInsensitiveFiltering: true
    });

    $('#example41').multiselect({
    	includeSelectAllOption: true
    });

    //Multiselect init

    $('#my-select').multiSelect()
    $('#pre-selected-options').multiSelect();
    $('#callbacks').multiSelect({
      afterSelect: function(values){
        alert("Select value: "+values);
      },
      afterDeselect: function(values){
        alert("Deselect value: "+values);
      }
    });
    $('#optgroup').multiSelect({ selectableOptgroup: true });
    $('#disabled-attribute').multiSelect();
    $('#custom-headers').multiSelect({
      selectableHeader: "
Selectable items
",
      selectionHeader: "
Selection items
",
    });
    $('#searchable').multiSelect({
      selectableHeader: "<input type='text' class='form-control search-input' autocomplete='off' placeholder='Search'>",
      selectionHeader: "<input type='text' class='form-control search-input' autocomplete='off' placeholder='Search'>",
      afterInit: function(ms){
        var that = this,
            $selectableSearch = that.$selectableUl.prev(),
            $selectionSearch = that.$selectionUl.prev(),
            selectableSearchString = '#'+that.$container.attr('id')+' .ms-elem-selectable:not(.ms-selected)',
            selectionSearchString = '#'+that.$container.attr('id')+' .ms-elem-selection.ms-selected';

        that.qs1 = $selectableSearch.quicksearch(selectableSearchString)
        .on('keydown', function(e){
          if (e.which === 40){
            that.$selectableUl.focus();
            return false;
          }
        });

        that.qs2 = $selectionSearch.quicksearch(selectionSearchString)
        .on('keydown', function(e){
          if (e.which == 40){
            that.$selectionUl.focus();
            return false;
          }
        });
      },
      afterSelect: function(){
        this.qs1.cache();
        this.qs2.cache();
      },
      afterDeselect: function(){
        this.qs1.cache();
        this.qs2.cache();
      }
    });
	};

  return App;
})(App || {});


text:
{% extends "admin/expressions/base.html" %}
{% load helpers %}

{% block bc_inner %}
{{ block.super }}
› {{ title }}
{% endblock bc_inner %}

{% block content %}

Enter your expression below to see the graph.

    <form action="." method="post">

            {{ form }}

 	<input class="default" type="submit" name="_save" value="Render" />

    </form>

Last expression

{{ last_rendering }}

{% endblock content %}


text:
package com.kendelong.util.monitoring.graphite;

import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.Level;
import org.apache.log4j.spi.LoggingEvent;

/**
 * A log4j log appender that sends the log levels to the Graphite server. With this appender, you will get charts of how many log
 * messages are being written by category: one chart for ERROR, one for WARN, etc.
 *
 * Because this appender is instantiated by the
 * log4j framework, it can't be autowired.  In order to transfer the reference of the graphiteClient from the Spring
 * context to this appender, a second instance of the appender is created in applicationContext.xml just for the purpose
 * of harvesting the reference and transferring it to the static variable here.  It's a sucky hack, but I couldn't think
 * of any other way to get the reference to the GraphiteClient.
 *
 * Configuration in application context is like this:
 * <pre>
   {@code
	<bean class="com.kendelong.util.monitoring.graphite.GraphiteAppender">
		<property name="graphiteClient" ref="graphiteClient"/>
	</bean>
   }
   </pre>
 *
 * @author kdelong
 *
 */
public class GraphiteAppender extends AppenderSkeleton
{
	private volatile static GraphiteClient graphiteClient;

	@Override
	public void close()
	{
	}

	@Override
	public boolean requiresLayout()
	{
		return false;
	}

	@Override
	protected void append(LoggingEvent event)
	{
		Level level = event.getLevel();
		if(graphiteClient != null)
		{
			graphiteClient.increment("logs." + level.toString());
		}
	}

	public void setGraphiteClient(GraphiteClient gc)
	{
		graphiteClient = gc;
	}

}


text:
package org.activiti5.camel.exception.tools;

import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.JavaDelegate;

public class NoExceptionServiceMock implements JavaDelegate {

  static boolean isCalled = false;

  @Override
  public void execute(DelegateExecution execution) {
    isCalled = true;
  }

  public static void reset() {
    isCalled = false;
  }

  public static boolean isCalled() {
    return isCalled;
  }

}


text:
<?php

namespace Tests\AsyncSockets\Event;

use AsyncSockets\Event\Event;
use AsyncSockets\Event\EventType;
use AsyncSockets\Event\SocketExceptionEvent;
use AsyncSockets\Exception\SocketException;

/**
 * Class SocketExceptionEventTest
 */
class SocketExceptionEventTest extends EventTest
{
    /**
     * SocketException
     *
     * @var SocketException
     */
    protected $exception;

    /**
     * Event
     *
     * @var Event
     */
    protected $originalEvent;

    /** {@inheritdoc} */
    protected function getEventType()
    {
        return EventType::EXCEPTION;
    }

    /** {@inheritdoc} */
    protected function createEvent($type)
    {
        return new SocketExceptionEvent(
            $this->exception,
            $this->executor,
            $this->socket,
            $this->context,
            $this->originalEvent
        );
    }

    /** {@inheritdoc} */
    protected function setUp()
    {
        parent::setUp();
        $this->exception     = new SocketException('Test', 123);
        $this->originalEvent = new Event($this->executor, $this->socket, $this->context, EventType::CONNECTED);
    }

    /** {@inheritdoc} */
    public function testGetters()
    {
        $event = parent::testGetters();
        /** @var SocketExceptionEvent $event */
        self::assertSame($this->exception, $event->getException(), 'Incorrect exception object');

        return $event;
    }
}


text:
<?php
require_once __DIR__ . '/path/to/vendor/autoload.php';

use Twilio\Rest\Client;

$accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$authToken = 'your_auth_token';

$client = new Client($accountSid, $authToken);
$status = $client->sync
                 ->services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
                 ->syncLists('MyFirstList')
                 ->syncListPermissions('bob')
                 ->delete();

print_r($status);


text:
package org.wso2.am.integration.tests.token;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONObject;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Factory;
import org.testng.annotations.Test;
import org.wso2.am.integration.clients.store.api.v1.dto.ApplicationDTO;
import org.wso2.am.integration.clients.store.api.v1.dto.ApplicationKeyDTO;
import org.wso2.am.integration.clients.store.api.v1.dto.ApplicationKeyGenerateRequestDTO;
import org.wso2.am.integration.clients.store.api.v1.dto.SubscriptionDTO;
import org.wso2.am.integration.test.Constants;
import org.wso2.am.integration.test.utils.base.APIMIntegrationBaseTest;
import org.wso2.am.integration.test.utils.base.APIMIntegrationConstants;
import org.wso2.am.integration.test.utils.bean.APIRequest;
import org.wso2.am.integration.test.utils.token.TokenUtils;
import org.wso2.carbon.automation.engine.annotations.ExecutionEnvironment;
import org.wso2.carbon.automation.engine.annotations.SetEnvironment;
import org.wso2.carbon.automation.engine.context.TestUserMode;
import org.wso2.carbon.automation.test.utils.http.client.HttpRequestUtil;
import org.wso2.carbon.automation.test.utils.http.client.HttpResponse;

import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.ws.rs.core.Response;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;

@SetEnvironment(executionEnvironments = {ExecutionEnvironment.STANDALONE})
public class TokenAPITestCase extends APIMIntegrationBaseTest {

    private static final Log log = LogFactory.getLog(TokenAPITestCase.class);
    private String apiId;
    private String appId;
    private String oauthTokenTestAppId;
    private String gatewayUrl;
    private String consumerKey;
    private String consumerSecret;

    @Factory(dataProvider = "userModeDataProvider")
    public TokenAPITestCase(TestUserMode userMode) {
        this.userMode = userMode;
    }

    @DataProvider
    public static Object[][] userModeDataProvider() {
        return new Object[][]{
                new Object[]{TestUserMode.SUPER_TENANT_ADMIN},
                new Object[] { TestUserMode.SUPER_TENANT_USER_STORE_USER },
                new Object[] { TestUserMode.SUPER_TENANT_EMAIL_USER },
                new Object[] { TestUserMode.TENANT_EMAIL_USER },
        };
    }

    @BeforeClass(alwaysRun = true)
    public void setEnvironment() throws Exception {
        super.init(userMode);

        String APIName = "TokenTestAPI";
        String APIContext = "tokenTestAPI";
        String tags = "youtube, token, media";
        String url = getGatewayURLHttp() + "jaxrs_basic/services/customers/customerservice";
        String description = "This is test API create by API manager integration test";
        String APIVersion = "1.0.0";

        APIRequest apiRequest = new APIRequest(APIName, APIContext, new URL(url), new URL(url));
        apiRequest.setTags(tags);
        apiRequest.setDescription(description);
        apiRequest.setVersion(APIVersion);
        apiRequest.setSandbox(url);
        apiRequest.setProvider(user.getUserName());
        HttpResponse serviceResponse = restAPIPublisher.addAPI(apiRequest);
        apiId = serviceResponse.getData();
        // Create Revision and Deploy to Gateway
        createAPIRevisionAndDeployUsingRest(apiId, restAPIPublisher);
        restAPIPublisher.changeAPILifeCycleStatus(apiId, Constants.PUBLISHED);
        waitForAPIDeploymentSync(apiRequest.getProvider(), apiRequest.getName(), apiRequest.getVersion(),
                APIMIntegrationConstants.IS_API_EXISTS);
        gatewayUrl = getAPIInvocationURLHttp("tokenTestAPI/1.0.0/customers/123");
    }

    @Test(groups = {"wso2.am"}, description = "Token API Test other")
    public void testTokenAPITestCase() throws Exception {

        // Create application
        ApplicationDTO applicationDTO = restAPIStore.addApplication("TokenTestAPI-Application",
                APIMIntegrationConstants.APPLICATION_TIER.UNLIMITED, "", "this-is-test");
        appId = applicationDTO.getApplicationId();

        SubscriptionDTO subscriptionDTO = restAPIStore.subscribeToAPI(apiId, appId,
                APIMIntegrationConstants.API_TIER.GOLD);
        Assert.assertEquals(true, subscriptionDTO.getThrottlingPolicy().equals("Gold"));

        //Generate sandbox Token and invoke with that
        ArrayList<String> grantTypes = new ArrayList<>();
        grantTypes.add(APIMIntegrationConstants.GRANT_TYPE.PASSWORD);
        grantTypes.add(APIMIntegrationConstants.GRANT_TYPE.CLIENT_CREDENTIAL);
        grantTypes.add(APIMIntegrationConstants.GRANT_TYPE.REFRESH_CODE);
        ApplicationKeyDTO applicationKeyDTO = restAPIStore.generateKeys(appId, "3600",
                null, ApplicationKeyGenerateRequestDTO.KeyTypeEnum.SANDBOX, null, grantTypes);
        String sandboxAccessToken = applicationKeyDTO.getToken().getAccessToken();
        Map<String, String> requestHeadersSandBox = new HashMap<String, String>();
        requestHeadersSandBox.put("Authorization", "Bearer " + sandboxAccessToken);
        requestHeadersSandBox.put("accept", "text/xml");
        HttpResponse youTubeResponseSandBox = HttpRequestUtil.doGet(gatewayUrl, requestHeadersSandBox);
        log.info("Response " + youTubeResponseSandBox);
        assertEquals(youTubeResponseSandBox.getResponseCode(), 200, "Response code mismatched");

        ApplicationKeyDTO productionApplicationKeyDTO = restAPIStore.generateKeys(appId,
                "3600", null, ApplicationKeyGenerateRequestDTO.KeyTypeEnum.PRODUCTION, null, grantTypes);
        String accessToken = productionApplicationKeyDTO.getToken().getAccessToken();
        consumerKey = productionApplicationKeyDTO.getConsumerKey();
        consumerSecret = productionApplicationKeyDTO.getConsumerSecret();
        //Obtain user access token
        Thread.sleep(2000);
        String requestBody = "grant_type=password&username=" + user.getUserName() + "&password=" +
                user.getPassword() + "&scope=PRODUCTION";
        URL tokenEndpointURL = new URL(keyManagerHTTPSURL + "oauth2/token");
        HttpResponse httpAccessTokenGenerationResponse = restAPIStore.generateUserAccessKey(consumerKey,
                consumerSecret, requestBody, tokenEndpointURL);
        JSONObject accessTokenGenerationResponse = new JSONObject(httpAccessTokenGenerationResponse.getData());
        String userAccessToken = accessTokenGenerationResponse.getString("access_token");
        Map<String, String> requestHeaders = new HashMap<String, String>();
        //Check User Access Token
        requestHeaders.put("Authorization", "Bearer " + userAccessToken);
        requestHeaders.put("accept", "text/xml");

        Thread.sleep(2000);
        HttpResponse youTubeResponse = HttpRequestUtil.doGet(gatewayUrl, requestHeaders);
        assertEquals(youTubeResponse.getResponseCode(), Response.Status.OK.getStatusCode(), "Response code mismatched");
        assertTrue(youTubeResponse.getData().contains("John"), "Response data mismatched");
        assertTrue(youTubeResponse.getData().contains("<name"), "Response data mismatched");
        assertTrue(youTubeResponse.getData().contains("<Customer>"), "Response data mismatched");

        //Check Application Access Token
        requestHeaders.clear();
        requestHeaders.put("Authorization", "Bearer " + accessToken);
        requestHeaders.put("accept", "text/xml");
        HttpResponse youTubeResponseWithApplicationToken = HttpRequestUtil.doGet(gatewayUrl, requestHeaders);
        assertEquals(youTubeResponseWithApplicationToken.getResponseCode(), Response.Status.OK.getStatusCode(),
                "Response code mismatched");
        assertTrue(youTubeResponseWithApplicationToken.getData().contains("John"), "Response data mismatched");
        assertTrue(youTubeResponseWithApplicationToken.getData().contains("<name>"), "Response data mismatched");
        assertTrue(youTubeResponseWithApplicationToken.getData().contains("<Customer>"), "Response data mismatched");
        //Invoke Https end point
        HttpResponse youTubeResponseWithApplicationTokenHttps = HttpRequestUtil
                .doGet(gatewayUrl, requestHeaders);
        log.info("Response " + youTubeResponseWithApplicationTokenHttps);
        assertEquals(youTubeResponseWithApplicationTokenHttps.getResponseCode(), 200, "Response code mismatched");

        HttpResponse errorResponse = null;
        errorResponse = HttpRequestUtil.doGet(gatewayUrl, requestHeaders);
        log.info("Error response " + errorResponse);

        requestHeaders.clear();
        requestHeaders.put("Authorization", "Bearer " + "this-is-incorrect-token");
        requestHeaders.put("accept", "text/xml");
        errorResponse = HttpRequestUtil.doGet(gatewayUrl, requestHeaders);
        assertEquals(errorResponse.getResponseCode(), 401, "Response code mismatched while token API test case");
        //TODO handle this in automation core level
        try {
            errorResponse = HttpRequestUtil.doGet(getAPIInvocationURLHttp("tokenTestAPI/1.0.0/most_popular"),
                    requestHeaders);
            log.info("Error Response " + errorResponse);
        } catch (Exception e) {
            //handle error
        }
        assertEquals(errorResponse.getResponseCode(), 401, "Response code mismatched while token API test case");
    }

    @Test(groups = {"wso2.am"}, description = "Test Refresh token functionality", dependsOnMethods = {
            "testTokenAPITestCase" })
    public void testRefreshTokenAPITestCase() throws Exception {

        //Obtain user access token
        String requestBody = "grant_type=password&username=" + user.getUserName() + "&password=" + user.getPassword()
                + "&scope=PRODUCTION";
        URL tokenEndpointURL = new URL(keyManagerHTTPSURL + "oauth2/token");

        JSONObject accessTokenGenerationResponse = new JSONObject(
                restAPIStore.generateUserAccessKey(consumerKey, consumerSecret, requestBody, tokenEndpointURL)
                        .getData());

        // get Access Token and Refresh Token
        String userAccessToken = accessTokenGenerationResponse.getString("access_token");
        String refreshToken = accessTokenGenerationResponse.getString("refresh_token");

        Map<String, String> requestHeaders = new HashMap<String, String>();
        //Check Access Token
        String tokenJti = TokenUtils.getJtiOfJwtToken(userAccessToken);
        requestHeaders.put("Authorization", "Bearer " + tokenJti);
        requestHeaders.put("accept", "text/xml");

        HttpResponse httpResponse = HttpRequestUtil.doGet(gatewayUrl, requestHeaders);

        assertEquals(httpResponse.getResponseCode(), Response.Status.OK.getStatusCode(), "Response code mismatched");
        assertTrue(httpResponse.getData().contains("John"), "Response data mismatched");
        assertTrue(httpResponse.getData().contains("<name>"), "Response data mismatched");
        assertTrue(httpResponse.getData().contains("<Customer>"), "Response data mismatched");

        //Get a new access token using refresh token
        String getAccessTokenFromRefreshTokenRequestBody = "grant_type=refresh_token&refresh_token=" + refreshToken;
        accessTokenGenerationResponse = new JSONObject(restAPIStore
                .generateUserAccessKey(consumerKey, consumerSecret, getAccessTokenFromRefreshTokenRequestBody,
                        tokenEndpointURL).getData());
        userAccessToken = accessTokenGenerationResponse.getString("access_token");

        requestHeaders = new HashMap<String, String>();
        //Check with new Access Token
        tokenJti = TokenUtils.getJtiOfJwtToken(userAccessToken);
        requestHeaders.put("Authorization", "Bearer " + tokenJti);
        requestHeaders.put("accept", "text/xml");
        httpResponse = HttpRequestUtil.doGet(gatewayUrl, requestHeaders);

        assertEquals(httpResponse.getResponseCode(), Response.Status.OK.getStatusCode(), "Response code mismatched");
        assertTrue(httpResponse.getData().contains("John"), "Response data mismatched");
        assertTrue(httpResponse.getData().contains("<name"), "Response data mismatched");
        assertTrue(httpResponse.getData().contains("<Customer>"), "Response data mismatched");
    }

    @Test(groups = { "wso2.am" }, description = "Oauth Token API Test other", dependsOnMethods = {
            "testRefreshTokenAPITestCase" })
    public void testOauthTokenAPITestCase() throws Exception {

        ApplicationDTO applicationDTO = restAPIStore.addApplicationWithTokenType("oauthTokenTestAPI-Application",
                APIMIntegrationConstants.APPLICATION_TIER.UNLIMITED, "", "this-is-test", "OAUTH");
        oauthTokenTestAppId = applicationDTO.getApplicationId();

        SubscriptionDTO subscriptionDTO = restAPIStore.subscribeToAPI(apiId,
                oauthTokenTestAppId, APIMIntegrationConstants.API_TIER.GOLD);
        Assert.assertEquals(true, subscriptionDTO.getThrottlingPolicy().equals("Gold"));
        //Generate sandbox Token and invoke with that
        ArrayList<String> grantTypes = new ArrayList<>();
        //get access token
        grantTypes.add(APIMIntegrationConstants.GRANT_TYPE.PASSWORD);
        grantTypes.add(APIMIntegrationConstants.GRANT_TYPE.CLIENT_CREDENTIAL);

        ApplicationKeyDTO applicationKeyDTO = restAPIStore.generateKeys(oauthTokenTestAppId,
                "3600", null, ApplicationKeyGenerateRequestDTO.KeyTypeEnum.SANDBOX, null, grantTypes);

        String sandboxAccessToken = applicationKeyDTO.getToken().getAccessToken();
        Map<String, String> requestHeadersSandBox = new HashMap<String, String>();
        String sandTokenJti = TokenUtils.getJtiOfJwtToken(sandboxAccessToken);
        requestHeadersSandBox.put("Authorization", "Bearer " + sandTokenJti);
        requestHeadersSandBox.put("accept", "text/xml");
        HttpResponse youTubeResponseSandBox = HttpRequestUtil.doGet(gatewayUrl, requestHeadersSandBox);
        log.info("Response " + youTubeResponseSandBox);
        assertEquals(youTubeResponseSandBox.getResponseCode(), 200, "Response code mismatched");

        ApplicationKeyDTO productionApplicationKeyDTO = restAPIStore.generateKeys(oauthTokenTestAppId,
                "3600", null, ApplicationKeyGenerateRequestDTO.KeyTypeEnum.PRODUCTION, null, grantTypes);
        String consumerKey = productionApplicationKeyDTO.getConsumerKey();
        String consumerSecret = productionApplicationKeyDTO.getConsumerSecret();
        //Obtain user access token
        Thread.sleep(2000);
        String requestBody = "grant_type=password&username=" + user.getUserName() + "&password=" + user.getPassword() +
                "&scope=PRODUCTION";
        URL tokenEndpointURL = new URL(keyManagerHTTPSURL + "oauth2/token");
        HttpResponse httpAccessTokenGenerationResponse = restAPIStore.generateUserAccessKey(consumerKey, consumerSecret,
                requestBody, tokenEndpointURL);
        JSONObject accessTokenGenerationResponse = new JSONObject(httpAccessTokenGenerationResponse.getData());
        String userAccessToken = accessTokenGenerationResponse.getString("access_token");
        Map<String, String> requestHeaders = new HashMap<String, String>();
        //Check User Access Token
        String accessTokenJti = TokenUtils.getJtiOfJwtToken(userAccessToken);
        requestHeaders.put("Authorization", "Bearer " + accessTokenJti);
        requestHeaders.put("accept", "text/xml");
        Thread.sleep(2000);

        HttpResponse youTubeResponse = HttpRequestUtil.doGet(gatewayUrl, requestHeaders);
        assertEquals(youTubeResponse.getResponseCode(), Response.Status.OK.getStatusCode(),
                "Response code mismatched");
        assertTrue(youTubeResponse.getData().contains("John"), "Response data mismatched");
        assertTrue(youTubeResponse.getData().contains("<name"), "Response data mismatched");
        assertTrue(youTubeResponse.getData().contains("<Customer>"), "Response data mismatched");
    }

    @AfterClass(alwaysRun = true)
    public void destroy() throws Exception {
        restAPIStore.deleteApplication(appId);
        restAPIStore.deleteApplication(oauthTokenTestAppId);
        undeployAndDeleteAPIRevisionsUsingRest(apiId, restAPIPublisher);
        restAPIPublisher.deleteAPI(apiId);
    }
}


text:
package com.albedinsky.android.fragment.annotation;

import com.albedinsky.android.fragment.manage.FragmentController;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Defines an annotation for determining set of Fragment ids that are provided by a specific
 * {@link FragmentController.FragmentFactory}.
 *
 *
Usage

 *

 *
{@link com.albedinsky.android.fragment.manage.BaseFragmentFactory BaseFragmentFactory}

 *

 *
 * @author Martin Albedinsky
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface FactoryFragments {

	/**
	 * An array with Fragment ids to be provided by FragmentFactory.
	 *
	 * @see FragmentController.FragmentFactory#isFragmentProvided(int)
	 */
	int[] value();
}


text:
<?php

class AccountModel extends Model {

	public function getAllUsernames() {

		return $this->dbc->query(" SELECT Username FROM accounts");

	}

}


text:
package main

import (
	"fmt"
	"os"
	"time"

	"github.com/bom-d-van/xmppclient"
)

func main() {
	conn, err := xmppclient.Dial(
		"localhost:5222",
		//"yeerkunth-theplant@localhost",
		"y40@localhost",
		"localhost",
		//"BPwOQnLGnJ",
		"nopassword",
		"", //let server generate the resource
		&xmppclient.Config{
			Log: os.Stderr,
			//Log: logutils.ToWriter(logger),
			// InLog:  logutils.ToWriter(in),
			// OutLog: logutils.ToWriter(out),
		},
	)

	if err != nil {
		panic(err)
	}

	// conn.Presence = make(chan *xmppclient.ClientPresence)
	// conn.Message = make(chan *xmppclient.ClientMessage)
	//conn.Send("enn.raven-theplant@localhost", "I came from the darkness")
	//conn.Send("y40@localhost", "I came from the darkness")

	//conn.JoinMUC("49qniykfbt9@conference.localhost", "y")
	//conn.SendGroupChatMessage("49qniykfbt9@conference.localhost", "I came from the darkness")

	//conn.SendMediatedMucInvitation("enn.raven-theplant@localhost", "49qniykfbt9@conference.localhost", "noreason")
	//conn.JoinMUC("bullshit@conference.localhost", "y")
	//conn.SendMediatedMucInvitation("enn.raven-theplant@localhost", "bullshit@conference.localhost", "noreason")
	//conn.SendDirectMucInvitation("enn.raven-theplant@localhost", "bullshit@conference.localhost", "noreason")

	conn.Handler = &xmppclient.BasicHandler{}
	go conn.Listen()
	conn.SignalPresence("online")
	conn.RetrieveRoster()
	time.Sleep(time.Second * 1)
	fmt.Println("done")

	//conn.Send("jiangnan34-theplant@localhost", "it's my message.")
	// conn.DiscoverRooms()
	// for {
	// 	msg := <-conn.Message
	// 	log.Printf("--> %+v\n", msg.Body)
	// }
}


text:
// Copyright (c) Petabridge <https://petabridge.com/>. All rights reserved.
// Licensed under the Apache 2.0 license. See LICENSE file in the project root for full license information.
// See ThirdPartyNotices.txt for references to third party code used inside Helios.

using System;

namespace Helios.Eventing
{
    /// <summary>
    ///     An interface for notifying classes inside a single process about
    ///     available events.
    ///     Truth be told - this class can be used over sockets and inter-process communication; it's
    ///     a configuration detail.
    /// </summary>
    /// <typeparam name="TTopic">The type used to identify the topic</typeparam>
    /// <typeparam name="TSubscriber">The type used to identify the subscriber</typeparam>
    public interface IEventBroker<TTopic, TSubscriber>
    {
        event EventHandler<EventSubscriptionEventArgs<TTopic, TSubscriber>> SubscriptionAdded;
        event EventHandler<EventSubscriptionEventArgs<TTopic, TSubscriber>> SubscriptionRemoved;

        void Subscribe(TTopic id, TSubscriber subscriber, ITopicSubscription normalTopicSubscription);

        void Unsubscribe(TTopic id, TSubscriber subscriber);

        /// <summary>
        ///     Fire the event with the topic specified by the identifier
        ///     with its associated sender and parameters
        /// </summary>
        /// <param name="id">The id of the event to fire</param>
        /// <param name="sender">The object responsible for firing the event</param>
        /// <param name="e">The arguments for this event</param>
        void InvokeEvent(TTopic id, object sender, EventArgs e);
    }
}


text:
<?php

namespace R\Hive\Commands;

use Symfony\Component\Console\Input\InputOption;

class MakeMutatorCommand extends HiveGeneratorCommand
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'hive:mutator';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create a new Hive data mutator class.';

    /**
     * The type of class being generated.
     *
     * @var string
     */
    protected $type = 'Mutator';

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function fire()
    {
        parent::fire();
    }

    /**
     * Get the stub file for the generator.
     *
     * @return string
     */
    protected function getStub()
    {
        if ($this->option('request')) {
            return __DIR__.'/stubs/mutator-request.stub';
        } elseif ($this->option('clean')) {
            return __DIR__.'/stubs/mutator-clean.stub';
        } else {
            return __DIR__.'/stubs/mutator.stub';
        }
    }

    /**
     * Get the default namespace for the class.
     *
     * @param string $rootNamespace
     *
     * @return string
     */
    protected function getDefaultNamespace($rootNamespace)
    {
        return $rootNamespace.'\Lib\Data';
    }

    /**
     * Get the console command options.
     *
     * @return array
     */
    protected function getOptions()
    {
        return [
            ['request', 'r', InputOption::VALUE_NONE, 'Create a Laravel request mutator.'],
            ['clean', 'c', InputOption::VALUE_NONE, 'Create a clean mutator.'],
        ];
    }
}


text:
package oauth2

import (
	"strings"

	"github.com/hellofresh/janus/pkg/jwt"
	log "github.com/sirupsen/logrus"
)

const (
	// JWT provides a way to check the `exp` field on the JWT and make sure the token is still valid. This is
	// probably the most versatile way to check for tokens, since it doesn't require any storage or extra calls in
	// each request.
	JWT ManagerType = iota
	// Introspection strategy makes sure to validate the provided token on every request against the authentication provider.
	Introspection
)

var typesMap = map[string]ManagerType{
	"jwt":           JWT,
	"introspection": Introspection,
}

// ParseType takes a string type and returns the Manager type constant.
func ParseType(lvl string) (ManagerType, error) {
	m, ok := typesMap[strings.ToLower(lvl)]
	if !ok {
		var m ManagerType
		return m, ErrUnknownStrategy
	}
	return m, nil
}

// ManagerType type
type ManagerType uint8

// Manager holds the methods to handle tokens
type Manager interface {
	IsKeyAuthorized(accessToken string) bool
}

// ManagerFactory is used for creating a new manager
type ManagerFactory struct {
	oAuthServer *OAuth
}

// NewManagerFactory creates a new instance of ManagerFactory
func NewManagerFactory(oAuthServer *OAuth) *ManagerFactory {
	return &ManagerFactory{oAuthServer}
}

// Build creates a manager based on the type
func (f *ManagerFactory) Build(t ManagerType) (Manager, error) {
	// FIXME: make it nicer with BiMap - GetByType, GetByName
	typesMapReversed := make(map[ManagerType]string, len(typesMap))
	for k, v := range typesMap {
		typesMapReversed[v] = k
	}

	log.WithField("name", typesMapReversed[t]).
		Debug("Building token strategy")

	switch t {
	case JWT:
		signingMethods, err := f.oAuthServer.TokenStrategy.GetJWTSigningMethods()
		if nil != err {
			return nil, err
		}

		return NewJWTManager(jwt.NewParser(jwt.NewParserConfig(signingMethods...))), nil
	case Introspection:
		settings, err := f.oAuthServer.TokenStrategy.GetIntrospectionSettings()
		if nil != err {
			return nil, err
		}

		manager, err := NewIntrospectionManager(f.oAuthServer.Endpoints.Introspect.UpstreamURL, settings)
		if err != nil {
			return nil, err
		}

		return manager, nil
	}

	return nil, ErrUnknownManager
}


text:
import * as consts from './constants'
import { registerUser, createUser } from '../../logic/Firebase/user.setters'

export const saveField = payload => dispatch => dispatch({ type: consts.SAVE_FIELD, payload })

export const loaderStart = () => ({ type: consts.LOADER_START })

export const registerStart = payload => dispatch => {
    dispatch(loaderStart())
    dispatch(registerProcess(payload))
}

export const registerProcess = payload => dispatch => {
    registerUser(payload)
        .then(user => dispatch(registerUserInfo(user, payload)))
        .catch(error => dispatch(registerFailed(error)))
}

export const registerUserInfo = (user, payload) => dispatch => {
    const { firstname, lastname, email } = payload
    createUser(user.uid, { firstname, lastname, email })
        .then(() => dispatch(registerSuccess(payload)))
        .catch(error => dispatch(registerFailed(error)))
}

export const registerSuccess = payload => dispatch =>
    dispatch({ type: consts.REGISTER_SUCCESS, payload })

export const registerFailed = payload => dispatch =>
    dispatch({ type: consts.REGISTER_FAILED, payload })

export const resetScene = () => dispatch =>
    dispatch({ type: consts.RESET_SCENE })


text:
import re
import sys

declare_line_pattern = '^( *)def +(\w+) *\((.*)'
doc_para_pattern = '^( *)(\w.*):(.*)'
doc_sec_pattern = '^( *)Parameters'
doc_sep_pattern = '^( *)-+'
doc_end_pattern = '^( *)\"\"\"'

record_warning = False

def check_file(path):
    line_no = 0
    in_params_sec = False
    in_dec_sec = False
    finished_func = False
    sep_no = 0
    func_dent = 0

    func = ''
    func_line = 0
    param_str = ''

    params_dec = {}
    params_doc = {}

    with open(path,'r') as src:
        for line in src:
            line_no += 1

            if in_dec_sec:
                if ':' in line:
                    in_dec_sec = False
                params_dec.update(get_params_dec(line))

            match_dec = re.match(declare_line_pattern,line)
            if match_dec:
                record_inconsistency(params_dec,params_doc,func_line,path,func)
                param_str = match_dec.group(3)
                if not ':' in param_str:
                    in_dec_sec = True
                func = match_dec.group(2)
                func_line = line_no
                func_dent = len(match_dec.group(1))
                param_str = match_dec.group(3)
                in_params_sec = False
                sep_no = 0
                params_dec = get_params_dec(param_str)
                params_doc = {}

            if not in_params_sec:
                match_sec = re.match(doc_sec_pattern,line)
                if match_sec:
                    in_params_sec = True
                    sep_no = 0
            else:
                match_params = re.match(doc_para_pattern,line)
                if match_params and len(match_params.group(1)) == func_dent + 4:
                    params_doc.update(get_params_doc(line))
                match_sep = re.match(doc_sep_pattern,line)
                if match_sep:
                    sep_no += 1
                    if sep_no > 1:
                        in_params_sec = False
                match_end = re.match(doc_end_pattern,line)
                if match_end:
                    in_params_sec = False
    record_inconsistency(params_dec,params_doc,func_line,path,func)

def get_params_dec(param_str):
    if not param_str:
        return {}

    param_str = param_str.replace(' ','')
    param_str = param_str.replace(')','')
    param_str = param_str.replace(':','')
    params = param_str.split(',')
    ret = {}

    opt_pattern = '(.*)=(.*)'
    for param in params:
        match = re.match(opt_pattern,param)
        if match:
            ret[match.group(1)] = True
        else:
            ret[param] = False
    return ret

def get_params_doc(param_str):
    param_str = param_str.replace(' ','')
    param_pattern = '(.*):(.*)'

    optional = False
    ret = {}

    match = re.match(param_pattern,param_str)
    if match:
        params = match.group(1)
        description = match.group(2)
        if description.find('optional')!=-1:
            optional = True
        for param in params.split(','):
            ret[param] = optional
    return ret

def record_inconsistency(dec,doc,line,filename,funcname):
    dec_set = set(dec)
    doc_set = set(doc)

    if dec_set == doc_set:
        return

    ignore = ['self','args','kwargs']
    dec_set = dec_set - set(ignore)

    undoced = dec_set - doc_set
    if undoced and record_warning:
        warn_str = 'Warning: Undocumented params'
        warn_str += ' in '+str(filename)+':'+str(line)
        warn_str += ':'+str(funcname)+':'
        for param in undoced:
            warn_str += str(param)+' '
        print warn_str

    deprecated = doc_set - dec_set
    if deprecated:
        err_str = 'Error: Deprecated params'
        err_str += ' in '+str(filename)+':'+str(line)
        err_str += ':'+str(funcname)+':'
        for param in deprecated:
            err_str += str(param)+' '
        print err_str

if __name__ == "__main__":
    check_file(sys.argv[1])


text:
var definitions, on_action, utils;

on_action = function(action) {
  return action.handler = (function(handler) {
    return async function({config}) {
      var result;
      result = (await this.call({
        $raw_output: true,
        $handler: handler
      }));
      if (!Array.isArray(result)) {
        result = [result];
      }
      if (!config.strict) {
        result = result.map(function(res) {
          switch (typeof res) {
            case 'undefined':
              return false;
            case 'boolean':
              return !!res;
            case 'number':
              return !!res;
            case 'string':
              return !!res.length;
            case 'object':
              if (Buffer.isBuffer(res)) {
                return !!res.length;
              } else if (res === null) {
                return false;
              } else {
                return !!Object.keys(res).length;
              }
              break;
            case 'function':
              throw utils.error('NIKITA_ASSERT_INVALID_OUTPUT', ['assertion does not accept functions']);
          }
        });
      }
      result = !result.some(function(res) {
        if (!config.not) {
          return res !== true;
        } else {
          return res === true;
        }
      });
      if (result !== true) {
        throw utils.error('NIKITA_ASSERT_UNTRUE', ['assertion did not validate,', `got ${JSON.stringify(result)}`]);
      }
    };
  })(action.handler);
};

// ## Schema definitions
definitions = {
  config: {
    type: 'object',
    properties: {
      'not': {
        type: 'boolean',
        default: false,
        description: `Negates the validation.`
      },
      'strict': {
        type: 'boolean',
        default: false,
        description: `Cancel the casting of output into a boolean value.`
      }
    }
  }
};

// ## Exports
module.exports = {
  hooks: {
    on_action: on_action
  },
  metadata: {
    definitions: definitions
  }
};

// ## Dependencies
utils = require('../utils');


text:
{% extends 'dash/base.html' %}

{% block sub_title %}
  Remove content
{% endblock sub_title %}

{% block sub_heading %}
  Remove content
{% endblock sub_heading %}

{% block content %}

              Title
              {{ object.title }}

            {% if object.style %}

                Style
                {{ object.style }}

            {% endif %}

        {% if object.is_pending_edited or object.is_pending_pushed %}

            This content is published on the live site.
            Clicking the 'Remove' button will remove it from your web site.

        {% endif %}

          {% include '_form.html' with legend='Are you sure you want to remove this content?' submit='Remove' %}

{% endblock content %}


text:
#include <unistd.h>

int link( const char* oldpath, const char* newpath ) {
    /* TODO */

    printf( "TODO: link() not yet implemented!\n" );

    return 0;
}


text:
namespace MPACK
{
	namespace Physics
	{
		class Body;
		class CollisionInfo;
	}
}

namespace MPACK
{
	namespace Physics
	{
		typedef void (*CollisionCallbackFunc)(void*,Body*,Body*,CollisionInfo*);

		struct CollisionCallbackStruct
		{
			CollisionCallbackStruct(CollisionCallbackFunc function, void *param1)
				:	function(function), param1(param1)
			{
			}

			CollisionCallbackFunc function;
			void *param1;

			bool operator== (const CollisionCallbackStruct &other)
			{
				if(function!=other.function)
					return false;
				if(param1!=other.param1)
					return false;
				return true;
			}
		};
	}
}

#endif


text:
<!doctype html>

  <meta charset="utf-8">
  <title>Forecast Player</title>
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
  <link href='http://fonts.googleapis.com/css?family=Lato:300,400' rel='stylesheet' type='text/css'>
  <link rel="stylesheet" href="style.css">

            {{ track.user.username }}

            {{ track.title }}

          {{ Playlist.currentTrack.user.username }}
          {{ Playlist.currentTrack.title }}

        {{ timeElapsed | timeInMinutes }}
        {{ Playlist.currentTrack.durationInMinutes() }}

      <audio></audio>


text:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Extract localisations from a pixel of the binned image
%
% INPUT:
%   molecules binDat
%   x,y coordinate of pixel in binDat binned image space
%
% OUTPUT:
%   raw localisations using hash table
%
% Lowe, A.R. 2010-2014
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function [localisations] = get_localisations(binDat, x, y)

% use the hash to return the localisations data
hash = uint32(x+(y-1)*size(binDat.image,2));

% check that the key exists
if isKey(binDat.hashtable, hash)
    rows = binDat.hashtable(hash);
    [localisations] = binDat.localisations(rows,:);
    return
else
    % disp('Warning... no localisations found in bin');
    localisations = [];
end

return


text:
package gov.nih.nci.calims2.domain.workflow.enumeration;

import java.util.Locale;

import gov.nih.nci.calims2.util.enumeration.I18nEnumeration;
/**
 * @author connollym@moxieinformatics.com
 *
 */

public enum ProtocolStatus  implements I18nEnumeration {

/**
* DEFAULT status name.
*/
DEFAULT;

  /**
   * {@inheritDoc}
   */
  public String getLocalizedValue(Locale locale) {
    return I18nEnumerationHelper.getLocalizedValue(gov.nih.nci.calims2.domain.workflow.l10n.ProtocolStatusBundle.class, locale, this);
  }

  /**
   * {@inheritDoc}
   */
  public String getName() {

    return name();
  }
}


text:
namespace Microsoft.Protocols.TestSuites.MS_OXCPERM
{
    /// <summary>
    /// This is an 8-bit structure used as both TableFlags and ModifyFlags structure.
    /// </summary>
    public class RequestBufferFlags
    {
        /// <summary>
        /// isReservedBitsSet property
        /// </summary>
        private bool isReservedBitsSet = false;

        /// <summary>
        /// isReplaceRowsFlagSet Property
        /// </summary>
        private bool isReplaceRowsFlagSet = false;

        /// <summary>
        /// isIncludeFreeBusyFlagSet property
        /// </summary>
        private bool isIncludeFreeBusyFlagSet = false;

        /// <summary>
        /// bufferFlags property
        /// </summary>
        private byte bufferFlags = 0x00;

        /// <summary>
        /// Gets or sets a value indicating whether to set the ReservedBits or not,
        /// if true, all reserved bits will be set as 1;
        /// if false, all reserved bits will be set as 0.
        /// </summary>
        public bool IsReservedBitsSet
        {
            get
            {
                return this.isReservedBitsSet;
            }

            set
            {
                this.isReservedBitsSet = value;
            }
        }

        /// <summary>
        /// Gets or sets a value indicating whether to set the ReplaceRows flag or not,
        /// if true, ReplaceRows flag will be set as 1;
        /// if false, ReplaceRows flag will be set as 0.
        /// </summary>
        public bool IsReplaceRowsFlagSet
        {
            get { return this.isReplaceRowsFlagSet; }
            set { this.isReplaceRowsFlagSet = value; }
        }

        /// <summary>
        /// Gets or sets a value indicating whether to set the IncludeFreeBusy flag or not,
        /// if true, IncludeFreeBusy flag will be set as 1;
        /// if false, IncludeFreeBusy flag will be set as 0;
        /// </summary>
        public bool IsIncludeFreeBusyFlagSet
        {
            get { return this.isIncludeFreeBusyFlagSet; }
            set { this.isIncludeFreeBusyFlagSet = value; }
        }

        /// <summary>
        /// Gets 8-bits structure property
        /// </summary>
        public byte BufferFlags
        {
            get
            {
                this.bufferFlags = 0x00;
                if (this.isIncludeFreeBusyFlagSet)
                {
                    this.bufferFlags |= 0x02;
                }

                if (this.isReplaceRowsFlagSet)
                {
                    this.bufferFlags |= 0x01;
                }

                if (this.isReservedBitsSet)
                {
                    this.bufferFlags |= 0xFC;
                }

                return this.bufferFlags;
            }
        }
    }
}


text:
package org.joinfaces.security.taglib;

import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;

/**
 * Spring security configuration for tests
 */
@Configuration
@ConditionalOnWebApplication
@EnableWebSecurity
public class SecurityConfiguration {
}


text:
Type.registerNamespace('dnn.controls');

dnn.extend(dnn.controls, {
    initMultiStateBox: function (ctl)
    {
	    if (ctl)
	    {
		    var ts = new dnn.controls.DNNMultiStateBox(ctl);
		    ts.initialize();
		    return ts;
	    }
    }
});

//------- Constructor -------//
dnn.controls.DNNMultiStateBox = function(o)
{
	dnn.controls.DNNMultiStateBox.initializeBase(this, [o]);

	//--- Appearance Properties ---//
	this.css = this.getProp('css', '');

    this.enabled = (this.getProp('enabled', '1') == '1');
	this.imgPath = this.getProp('imgpath', 'images/');
	this.states = this.getProp('states', '[]');
	this.states = Sys.Serialization.JavaScriptSerializer.deserialize(this.states);
	this.stateIndex = []

	for (var i=0; i<this.states.length; i++)
	    this.stateIndex[this.states[i].Key] = i;

	this.js = this.getProp('js', '');

    this._img = document.createElement('img');
    //this._img.style.position = 'absolute';
    this.container.parentNode.insertBefore(this._img, this.container);
    this.container.checked = true;
    //this.container.style.display = 'none';
    this.container.style.position = 'absolute';
    this.container.style.top = '-999px';
    this._label = dnn.dom.getByTagName('label', this.container.parentNode);
    if (this._label)
    {
        for (var i=0; i<this._label.length; i++)
        {
            if (this._label[i].htmlFor == this.container.id)
            {
                this._label = this._label[i];
                break;
            }
        }
    }
    else
        this._img.tabIndex = 0;

    this.set_Value(this.get_Value());

    this.addHandlers(this.container, {'click': this.click}, this);
    this.addHandlers(this._img, {'click': this.click, 'keypress': this.keypress}, this);

}

dnn.controls.DNNMultiStateBox.prototype =
{
get_Value: function() {return this.container.value;},
set_Value: function(value)
{
    var index = this.stateIndex[value];
    var state = this.states[index];

    if (this.enabled)
        this._img.src = this.imgPath + state.ImageUrl;
    else
        this._img.src = this.imgPath + state.DisabledImageUrl;
    this._img.alt = state.ToolTip;
    if (this._label)
        this._label.innerHTML = state.Text;

    this.container.value = state.Key;
},

//--- Event Handlers ---//
click: function(sender, args)
{
    if (this.enabled)
    {
        var index = this.stateIndex[this.get_Value()] + 1;
        if (index > this.states.length - 1)
            index = 0;
        this.set_Value(this.states[index].Key);
    }
    this.container.checked = true;
},

keypress: function(sender, args)
{
debugger;
},

// Methods
dispose: function()
{
    dnn.controls.DNNMultiStateBox.callBaseMethod(this, 'dispose');
}

}

dnn.controls.DNNMultiStateBox.registerClass('dnn.controls.DNNMultiStateBox', dnn.controls.control);


text:
%% problemcolor
\providecommand{\problemcolor}{\color{black!50}}
%% problemcopy environment
\newenvironment{problemcopy}{%
  \problemcolor
  \setlength{\parindent}{0cm}
  \setlength{\parskip}{1em}
}{%
  \vspace{1.5em}
}


text:
import tensorflow as tf

def compute_loss(logits, labels):
    labels = tf.squeeze(tf.cast(labels, tf.int32))

    cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=labels)
    cross_entropy_loss= tf.reduce_mean(cross_entropy)
    reg_loss = tf.reduce_mean(tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES))

    return cross_entropy_loss + reg_loss, cross_entropy_loss, reg_loss

def compute_accuracy(logits, labels):
    labels = tf.squeeze(tf.cast(labels, tf.int32))
    batch_predictions = tf.cast(tf.argmax(logits, 1), tf.int32)
    predicted_correctly = tf.equal(batch_predictions, labels)
    accuracy = tf.reduce_mean(tf.cast(predicted_correctly, tf.float32))
    return accuracy

def get_learning_rate(global_step, initial_value, decay_steps, decay_rate):
    learning_rate = tf.train.exponential_decay(initial_value, global_step, decay_steps, decay_rate, staircase=True)
    return learning_rate

def train(total_loss, learning_rate, global_step):
    optimizer = tf.train.AdamOptimizer(learning_rate)
    train_op = optimizer.minimize(total_loss, global_step)
    return train_op

def average_gradients(gradients):
    average_grads = []
    for grad_and_vars in zip(*gradients):
        grads = []
        for g, _ in grad_and_vars:
            grads.append(tf.expand_dims(g, 0))

        grad = tf.concat(grads, 0)
        grad = tf.reduce_mean(grad, 0)

        v = grad_and_vars[0][1]
        grad_and_var = (grad, v)
        average_grads.append(grad_and_var)
    return average_grads


text:
package org.antlr.v4.runtime;

import org.antlr.v4.runtime.atn.ATN;
import org.antlr.v4.runtime.atn.ATNType;
import org.antlr.v4.runtime.atn.LexerATNSimulator;
import org.antlr.v4.runtime.atn.PredictionContextCache;
import org.antlr.v4.runtime.dfa.DFA;

import java.util.ArrayList;
import java.util.Collection;

public class LexerInterpreter extends Lexer {
	protected final String grammarFileName;
	protected final ATN atn;

	@Deprecated
	protected final String[] tokenNames;
	protected final String[] ruleNames;
	protected final String[] channelNames;
	protected final String[] modeNames;

	private final Vocabulary vocabulary;

	protected final DFA[] _decisionToDFA;
	protected final PredictionContextCache _sharedContextCache =
		new PredictionContextCache();

	@Deprecated
	public LexerInterpreter(String grammarFileName, Collection<String> tokenNames, Collection<String> ruleNames, Collection<String> modeNames, ATN atn, CharStream input) {
		this(grammarFileName, VocabularyImpl.fromTokenNames(tokenNames.toArray(new String[0])), ruleNames, new ArrayList<String>(), modeNames, atn, input);
	}

	@Deprecated
	public LexerInterpreter(String grammarFileName, Vocabulary vocabulary, Collection<String> ruleNames, Collection<String> modeNames, ATN atn, CharStream input) {
		this(grammarFileName, vocabulary, ruleNames, new ArrayList<String>(), modeNames, atn, input);
	}

	public LexerInterpreter(String grammarFileName, Vocabulary vocabulary, Collection<String> ruleNames, Collection<String> channelNames, Collection<String> modeNames, ATN atn, CharStream input) {
		super(input);

		if (atn.grammarType != ATNType.LEXER) {
			throw new IllegalArgumentException("The ATN must be a lexer ATN.");
		}

		this.grammarFileName = grammarFileName;
		this.atn = atn;
		this.tokenNames = new String[atn.maxTokenType];
		for (int i = 0; i < tokenNames.length; i++) {
			tokenNames[i] = vocabulary.getDisplayName(i);
		}

		this.ruleNames = ruleNames.toArray(new String[0]);
		this.channelNames = channelNames.toArray(new String[0]);
		this.modeNames = modeNames.toArray(new String[0]);
		this.vocabulary = vocabulary;

		this._decisionToDFA = new DFA[atn.getNumberOfDecisions()];
		for (int i = 0; i < _decisionToDFA.length; i++) {
			_decisionToDFA[i] = new DFA(atn.getDecisionState(i), i);
		}
		this._interp = new LexerATNSimulator(this,atn,_decisionToDFA,_sharedContextCache);
	}

	@Override
	public ATN getATN() {
		return atn;
	}

	@Override
	public String getGrammarFileName() {
		return grammarFileName;
	}

	@Override
	@Deprecated
	public String[] getTokenNames() {
		return tokenNames;
	}

	@Override
	public String[] getRuleNames() {
		return ruleNames;
	}

	@Override
	public String[] getChannelNames() {
		return channelNames;
	}

	@Override
	public String[] getModeNames() {
		return modeNames;
	}

	@Override
	public Vocabulary getVocabulary() {
		if (vocabulary != null) {
			return vocabulary;
		}

		return super.getVocabulary();
	}
}


text:
<?php

namespace Tmdb;

/**
 * Class SessionToken
 * @package Tmdb
 */
class SessionToken
{
    /**
     * @var string
     */
    private $sessionToken = null;

    /**
     * @var \DateTime
     */
    private $expiresAt;

    /**
     * @var bool
     */
    private $success;

    /**
     * Token bag
     *
     * @param $session_token
     */
    public function __construct($session_token = null)
    {
        $this->sessionToken = $session_token;
    }

    /**
     * @param  null  $sessionToken
     * @return $this
     */
    public function setToken($sessionToken)
    {
        $this->sessionToken = $sessionToken;

        return $this;
    }

    /**
     * @return null
     */
    public function getToken()
    {
        return $this->sessionToken;
    }

    /**
     * @param  \DateTime $expiresAt
     * @return $this
     */
    public function setExpiresAt($expiresAt)
    {
        if (!$expiresAt instanceof \DateTime) {
            $expiresAt = new \DateTime($expiresAt);
        }

        $this->expiresAt = $expiresAt;

        return $this;
    }

    /**
     * @return \DateTime
     */
    public function getExpiresAt()
    {
        return $this->expiresAt;
    }

    /**
     * @param  mixed $success
     * @return $this
     */
    public function setSuccess($success)
    {
        $this->success = $success;

        return $this;
    }

    /**
     * @return mixed
     */
    public function getSuccess()
    {
        return $this->success;
    }
}


text:
+++
date = "2016-11-06T13:00:25+05:30"
title = "Soumettre un article"
+++

Si vous avez écrit, trouvé ou traduit un article qui pourrait aider la communauté francophone dans son exploration de Steem, n'hésitez pas à le soumettre via le formulaire ci-dessous.