text:
package org.apache.accumulo.core.clientImpl;

import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

import java.io.IOException;
import java.security.PrivilegedExceptionAction;
import java.util.Properties;

import org.apache.accumulo.core.client.security.tokens.AuthenticationToken;
import org.apache.accumulo.core.client.security.tokens.KerberosToken;
import org.apache.accumulo.core.conf.ClientProperty;
import org.apache.accumulo.core.rpc.SaslConnectionParams;
import org.apache.accumulo.core.rpc.SslConnectionParams;
import org.apache.accumulo.core.util.HostAndPort;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.CommonConfigurationKeysPublic;
import org.apache.hadoop.security.UserGroupInformation;
import org.easymock.EasyMock;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

public class ThriftTransportKeyTest {

  private static final String primary = "accumulo";

  @BeforeEach
  public void setup() {
    System.setProperty("java.security.krb5.realm", "accumulo");
    System.setProperty("java.security.krb5.kdc", "fake");
    Configuration conf = new Configuration(false);
    conf.set(CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHENTICATION, "kerberos");
    UserGroupInformation.setConfiguration(conf);
  }

  private static SaslConnectionParams createSaslParams(AuthenticationToken token) {
    Properties props = new Properties();
    props.setProperty(ClientProperty.SASL_KERBEROS_SERVER_PRIMARY.getKey(), primary);
    props.setProperty(ClientProperty.SASL_ENABLED.getKey(), "true");
    return new SaslConnectionParams(props, token);
  }

  @Test
  public void testSslAndSaslErrors() {
    ClientContext clientCtx = createMock(ClientContext.class);
    SslConnectionParams sslParams = createMock(SslConnectionParams.class);
    SaslConnectionParams saslParams = createMock(SaslConnectionParams.class);

    expect(clientCtx.getClientSslParams()).andReturn(sslParams).anyTimes();
    expect(clientCtx.getSaslParams()).andReturn(saslParams).anyTimes();

    // We don't care to verify the sslparam or saslparam mocks
    replay(clientCtx);

    try {
      assertThrows(RuntimeException.class,
          () -> new ThriftTransportKey(HostAndPort.fromParts("localhost", 9999), 120_000,
              clientCtx));
    } finally {
      verify(clientCtx);
    }
  }

  @Test
  public void testConnectionCaching() throws IOException, InterruptedException {
    UserGroupInformation user1 = UserGroupInformation.createUserForTesting("user1", new String[0]);
    final KerberosToken token = EasyMock.createMock(KerberosToken.class);

    // A first instance of the SASL cnxn params
    SaslConnectionParams saslParams1 =
        user1.doAs((PrivilegedExceptionAction<SaslConnectionParams>) () -> createSaslParams(token));

    // A second instance of what should be the same SaslConnectionParams
    SaslConnectionParams saslParams2 =
        user1.doAs((PrivilegedExceptionAction<SaslConnectionParams>) () -> createSaslParams(token));

    ThriftTransportKey ttk1 =
        new ThriftTransportKey(HostAndPort.fromParts("localhost", 9997), 1L, null, saslParams1),
        ttk2 =
            new ThriftTransportKey(HostAndPort.fromParts("localhost", 9997), 1L, null, saslParams2);

    // Should equals() and hashCode() to make sure we don't throw away thrift cnxns
    assertEquals(ttk1, ttk2);
    assertEquals(ttk1.hashCode(), ttk2.hashCode());
  }

  @Test
  public void testSaslPrincipalIsSignificant() throws IOException, InterruptedException {
    UserGroupInformation user1 = UserGroupInformation.createUserForTesting("user1", new String[0]);
    final KerberosToken token = EasyMock.createMock(KerberosToken.class);
    SaslConnectionParams saslParams1 =
        user1.doAs((PrivilegedExceptionAction<SaslConnectionParams>) () -> createSaslParams(token));

    UserGroupInformation user2 = UserGroupInformation.createUserForTesting("user2", new String[0]);
    SaslConnectionParams saslParams2 =
        user2.doAs((PrivilegedExceptionAction<SaslConnectionParams>) () -> createSaslParams(token));

    ThriftTransportKey ttk1 =
        new ThriftTransportKey(HostAndPort.fromParts("localhost", 9997), 1L, null, saslParams1),
        ttk2 =
            new ThriftTransportKey(HostAndPort.fromParts("localhost", 9997), 1L, null, saslParams2);

    assertNotEquals(ttk1, ttk2);
    assertNotEquals(ttk1.hashCode(), ttk2.hashCode());
  }

  @Test
  public void testSimpleEquivalence() {
    ClientContext clientCtx = createMock(ClientContext.class);

    expect(clientCtx.getClientSslParams()).andReturn(null).anyTimes();
    expect(clientCtx.getSaslParams()).andReturn(null).anyTimes();

    replay(clientCtx);

    ThriftTransportKey ttk =
        new ThriftTransportKey(HostAndPort.fromParts("localhost", 9999), 120_000, clientCtx);

    assertEquals(ttk, ttk, "Normal ThriftTransportKey doesn't equal itself");
  }
}


text:
class CEternitynodeSync;
extern CEternitynodeSync eternitynodeSync;

//
// CEternitynodeSync : Sync eternitynode assets in stages
//

class CEternitynodeSync
{
public:
    std::map<uint256, int> mapSeenSyncMNB;
    std::map<uint256, int> mapSeenSyncENW;
    std::map<uint256, int> mapSeenSyncEvolution;

    int64_t lastEternitynodeList;
    int64_t lastEternitynodeWinner;
    int64_t lastEvolutionItem;
    int64_t lastFailure;
    int nCountFailures;

    // sum of all counts
    int sumEternitynodeList;
    int sumEternitynodeWinner;
    int sumEvolutionItemProp;
    int sumEvolutionItemFin;
    // peers that reported counts
    int countEternitynodeList;
    int countEternitynodeWinner;
    int countEvolutionItemProp;
    int countEvolutionItemFin;

    // Count peers we've requested the list from
    int RequestedEternitynodeAssets;
    int RequestedEternitynodeAttempt;

    // Time when current eternitynode asset sync started
    int64_t nAssetSyncStarted;

    CEternitynodeSync();

    void AddedEternitynodeList(uint256 hash);
    void AddedEternitynodeWinner(uint256 hash);
    void AddedEvolutionItem(uint256 hash);
    void GetNextAsset();
    std::string GetSyncStatus();
    void ProcessMessage(CNode* pfrom, std::string& strCommand, CDataStream& vRecv);
    bool IsEvolutionFinEmpty();
    bool IsEvolutionPropEmpty();

    void Reset();
    void Process();
    bool IsSynced();
    bool IsBlockchainSynced();
    void ClearFulfilledRequest();
};

#endif

redpajama_set_name: RedPajamaGithub


text:
package org.hisp.dhis.common.comparator;

import java.util.Comparator;
import java.util.Locale;

/**
 * @author Lars Helge Overland
 */
public class LocaleNameComparator
    implements Comparator<Locale>
{
    public static final LocaleNameComparator INSTANCE = new LocaleNameComparator();

    @Override
    public int compare( Locale o1, Locale o2 )
    {
        return o1.getDisplayName().compareTo( o2.getDisplayName() );
    }
}


text:
<?php

class LoadImage extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('user_model');
        $this->load->model('Load_model');
        //$this->load->library('session');
        $this->user_model->isAvtoris();
        $this->load->library('image_lib');
        // $this->delWithout();
    }

    public function load() {
        //echo "load";
        //var_dump($this->input->post('template', true));die();
        if (isset($_FILES["files"]["tmp_name"])) {
            $allowedExts = array("gif", "jpeg", "jpg", "png", "blob");

            $temp = explode(".", $_FILES["files"]["name"]);

            $extension = end($temp);

            $finfo = finfo_open(FILEINFO_MIME_TYPE);
            $mime = finfo_file($finfo, $_FILES["files"]["tmp_name"]);

            if ((($mime == "image/gif") || ($mime == "image/jpeg") || ($mime == "image/pjpeg") || ($mime == "image/x-png") || ($mime == "image/png")) && in_array(strtolower($extension), $allowedExts)) {
                $filename = md5(uniqid(rand(), true));
                copy($_FILES["files"]["tmp_name"], BASE . '/files/images2/small/' . $filename . "1.jpg");
                $config = array(
                    'image_library' => 'imagemagick',
                    'library_path' => '/usr/bin/',
                    'source_image' => $_FILES["files"]["tmp_name"], //path to the uploaded image
                    'new_image' => BASE . '/files/images2/big/' . $filename . ".jpg",
                    'maintain_ratio' => true,
                    'create_thumb' => false,
                    'quality' => 95,
                    'width' => $this->input->post('max', true),
                );
                $mas['error'] = "";
                if ($this->input->post('onlismall', true) === "small") {
                    $this->image_lib->initialize($config);
                    $this->image_lib->resize();
                    $mas['error'] = $this->image_lib->display_errors();
                    $this->image_lib->clear();
                }

                $config['new_image'] = BASE . '/files/images2/small/' . $filename . ".jpg";
                $config['width'] = $this->input->post('min', true);

                $this->image_lib->initialize($config);
                $this->image_lib->resize();
                $mas['error'] .= $this->image_lib->display_errors();
                $this->image_lib->clear();
                $mas1 = array("Puth" => '/files/images2/', "Name" => $filename . ".jpg");
                $this->Load_model->insert($mas1);
                $mas['elem'] = $this->Load_model->getPhotos(array("name" => $filename . ".jpg", "count" => 1), $this->input->post('vid', true), $this->input->post('template', true));
                echo json_encode($mas);
            }
        }
    }

}


text:
require 'test_helper'

module Social
  class FacebookPostTest < ActiveSupport::TestCase
    # test "the truth" do
    #   assert true
    # end
  end
end


text:
require 'singleton'

# Page controller is the class the runs the majority of front end pages.
# If you are looking to create your own custom front end controller you should
# override ModuleAppController instead
class PageController < ModuleAppController

  skip_before_filter :validate_module

  skip_before_filter :handle_page,:only => [ :paragraph, :webalytics ]
  skip_after_filter :process_logging, :only =>  [ :paragraph, :webalytics ]

  before_filter :cache_force

  helper :paragraph

  def view #:nodoc:
    session[:cms_language] = params[:language] if Configuration.languages.include?(params[:language])
    index
  end

  def paragraph #:nodoc:

    revision = PageRevision.find(params[:page_revision],:conditions => ['revision_type IN ("real","old") AND revision_container_id=?',params[:site_node]])
    container = revision.revision_container
    para = revision.page_paragraphs.find(params[:paragraph])

    engine = SiteNodeEngine.new(container,:display => session[:cms_language], :path => [])

    begin
      @result = engine.run_paragraph(para,self,myself)
    rescue SiteNodeEngine::MissingPageException => e
      @result = nil
    end

    if @result
      render :text => webiva_post_process_paragraph(render_paragraph(container.is_a?(SiteNode) ? container : container.site_node, revision, @result, :ajax => true))
    else
      render :nothing => true, :status => 404
    end
  end

  def index #:nodoc:
      # Handled by module app controller before filter
      render :action => 'index'
  end

  def webalytics
    DomainLogVisitor.log_location(cookies,session,params[:loc])
    DomainLogSession.log_source(cookies, session)
    render :nothing => true
  end

  protected

  # Necessary to prevent repeated authenticity token errors
  def cache_force #:nodoc:
    response.headers["Cache-Control"] = "no-cache, no-store, max-age=0, must-revalidate"
    response.headers["Pragma"] = "no-cache"
    response.headers["Expires"] = "Fri, 01 Jan 1990 00:00:00 GMT"
  end

  public

  if RAILS_ENV == 'test'
    def set_test_renderer(rnd) #:nodoc:
      @test_renderer = rnd
    end

    def renderer_test #:nodoc:
      @test_renderer.send(@test_renderer.paragraph.display_type)
      output =  @test_renderer.output
      if output.is_a?(ParagraphRenderer::ParagraphOutput)
        render output.render_args
      else
        render :nothing => true
      end

    end

    skip_before_filter :handle_page,:only => :renderer_test

  end

end


text:
<?php

namespace Algolia\AlgoliaSearch\Response;

use Algolia\AlgoliaSearch\SearchClient;

final class MultipleIndexBatchIndexingResponse extends AbstractResponse
{
    /**
     * @var \Algolia\AlgoliaSearch\SearchClient
     */
    private $client;

    public function __construct(array $apiResponse, SearchClient $client)
    {
        $this->apiResponse = $apiResponse;
        $this->client = $client;
    }

    public function wait($requestOptions = [])
    {
        if (!isset($this->client)) {
            return $this;
        }

        foreach ($this->apiResponse['taskID'] as $indexName => $taskId) {
            $this->client->waitTask($indexName, $taskId, $requestOptions);
        }

        unset($this->client);

        return $this;
    }
}


text:
package de.iss.mv2.security;

import java.security.NoSuchAlgorithmException;
import java.security.Signature;

/**
 * A object to create a SHA256 with RSA {@link Signature}.
 * @author Marcel Singer
 *
 */
public class SHA256WithRSASignatureProvider implements SignatureProvider{

	/**
	 * Creates a new instance of {@link SHA256WithRSASignatureProvider}.
	 */
	public SHA256WithRSASignatureProvider() {

	}

	@Override
	public Signature createSignature() {
		try {
			return Signature.getInstance("SHA256withRSA");
		} catch (NoSuchAlgorithmException e) {
			return null;
		}
	}

}


text:
/**************************************************************************

   File: /home/john/git/smaccm/models/SmaccmPhaseIIIV2/components/Decrypt/src/smaccm_Decrypt.c
   Created on: 2016/06/16 12:29:24
   using Dulcimer AADL system build tool suite

   ***AUTOGENERATED CODE: DO NOT MODIFY***

  This C file contains the implementations of the AADL primitives
  used by user-level declarations for thread Decrypt.

  The user code runs in terms of "dispatchers", which cause
  dispatch user-level handlers to execute.  These handlers can
  communicate using the standard AADL primitives, which are mapped
  to C functions.

  The send/receive handlers are not thread safe in CAmkES; it is
  assumed that this is handled by the CAmkES sequentialized access
  to the dispatch handler.  There is only one dispatch interface
  for the component containing all of the dispatch points.

  They are thread safe for eChronos.

  The read/write handlers are thread safe because the writer comes
  through a dispatch interface but the reader is "local" on a dispatch
  interface and so contention may occur.

 **************************************************************************/
#include <smaccm_Decrypt.h>
#include <string.h>
#include <Decrypt.h>

///////////////////////////////////////////////////////////////////////////
//
// Local prototypes for AADL dispatchers
//
///////////////////////////////////////////////////////////////////////////
static void
smaccm_Decrypt_periodic_dispatcher_dispatcher(int64_t * periodic_dispatcher);
static void
smaccm_Decrypt_Decrypt_initializer_dispatcher(int64_t * Decrypt_initializer);
static void
smaccm_Decrypt_get_packet_dispatcher(SMACCM_DATA__UartPacket_i * get_packet);

/************************************************************************
 *
 * Static variables and queue management functions for port:
 * 	get_packet
 *
 ************************************************************************/

static SMACCM_DATA__UartPacket_i smaccm_queue_get_packet [1];
static bool smaccm_queue_full_get_packet  = false;
static uint32_t smaccm_queue_front_get_packet  = 0;
static uint32_t smaccm_queue_back_get_packet  = 0;

bool smaccm_queue_is_full_get_packet() {
	return (smaccm_queue_front_get_packet == smaccm_queue_back_get_packet) && (smaccm_queue_full_get_packet);
}

bool smaccm_queue_is_empty_get_packet() {
	return (smaccm_queue_front_get_packet == smaccm_queue_back_get_packet) && (!smaccm_queue_full_get_packet);
}

bool smaccm_queue_read_get_packet(SMACCM_DATA__UartPacket_i * get_packet) {
	if (smaccm_queue_is_empty_get_packet()) {
		return false;
	} else {
		memcpy(get_packet, &smaccm_queue_get_packet[smaccm_queue_back_get_packet], sizeof(SMACCM_DATA__UartPacket_i));

		smaccm_queue_back_get_packet = (smaccm_queue_back_get_packet + 1) % 1;
		smaccm_queue_full_get_packet = false ;
		return true;
	}
}

bool smaccm_queue_write_get_packet(const SMACCM_DATA__UartPacket_i * get_packet) {
	if (smaccm_queue_is_full_get_packet()) {
		return false;
	} else {
		memcpy(&smaccm_queue_get_packet[smaccm_queue_front_get_packet], get_packet, sizeof(SMACCM_DATA__UartPacket_i));

		smaccm_queue_front_get_packet = (smaccm_queue_front_get_packet + 1) % 1;
		if (smaccm_queue_back_get_packet == smaccm_queue_front_get_packet) {
			smaccm_queue_full_get_packet = true ;
		}
		return true;
	}
}

/************************************************************************
 *  get_packet_write_SMACCM_DATA__UartPacket_i:
 * Invoked by: remote interface.
 *
 * This is the function invoked by a remote RPC to write to an active-thread
 * input event data port.  It queues the input message into a circular buffer.
 *
 ************************************************************************/

bool get_packet_write_SMACCM_DATA__UartPacket_i(const SMACCM_DATA__UartPacket_i * arg) {
	bool result;
	smaccm_decrypt_get_packet_mut_lock();
	result = smaccm_queue_write_get_packet( arg);
	smaccm_decrypt_get_packet_mut_unlock();
	return result;
}

/************************************************************************
 *  Decrypt_read_get_packet:
 * Invoked from local active thread.
 *
 * This is the function invoked by the active thread to read from the
 * input event data queue circular buffer.
 *
 ************************************************************************/

bool Decrypt_read_get_packet(SMACCM_DATA__UartPacket_i * arg) {
	bool result;
	smaccm_decrypt_get_packet_mut_lock();
	result = smaccm_queue_read_get_packet(arg);
	smaccm_decrypt_get_packet_mut_unlock();
	return result;
}

static SMACCM_DATA__Array_U8_80 * smaccm_tmp_array_send_gidl;
static uint32_t * smaccm_tmp_used_send_gidl;
static uint32_t smaccm_max_tmp_array_send_gidl;

/************************************************************************
 * periodic_dispatcher Declarations
 *
 ************************************************************************/

static bool smaccm_occurred_periodic_dispatcher;
static int64_t smaccm_time_periodic_dispatcher;

/************************************************************************
 * Decrypt_periodic_dispatcher_write_int64_t
 * Invoked from remote periodic dispatch thread.
 *
 * This function records the current time and triggers the active thread
 * dispatch from a periodic event.
 *
 ************************************************************************/

bool Decrypt_periodic_dispatcher_write_int64_t(const int64_t * arg) {
	smaccm_occurred_periodic_dispatcher = true;
	smaccm_time_periodic_dispatcher = *arg;
	smaccm_dispatch_sem_post();

	return true;
}

/************************************************************************
 *  dispatch_dispatch_periodic_dispatcher:
 * Invoked by remote RPC (or, for active thread, local dispatcher).
 *
 * This is the function invoked by an active thread dispatcher to
 * call to a user-defined entrypoint function.  It sets up the dispatch
 * context for the user-defined entrypoint, then calls it.
 *
 ************************************************************************/

void dispatch_dispatch_periodic_dispatcher(
  const int64_t * in_arg ,
  smaccm_Decrypt_periodic_dispatcher_struct *out_arg) {
	smaccm_max_tmp_array_send_gidl = 0;

	component_entry( in_arg);

}

/************************************************************************
 *  dispatch_dispatch_Decrypt_initializer:
 * Invoked by remote RPC (or, for active thread, local dispatcher).
 *
 * This is the function invoked by an active thread dispatcher to
 * call to a user-defined entrypoint function.  It sets up the dispatch
 * context for the user-defined entrypoint, then calls it.
 *
 ************************************************************************/

void dispatch_dispatch_Decrypt_initializer(
  const int64_t * in_arg ,
  smaccm_Decrypt_Decrypt_initializer_struct *out_arg) {
	smaccm_max_tmp_array_send_gidl = 0;

	component_init( in_arg);

}

/************************************************************************
 *  dispatch_dispatch_get_packet:
 * Invoked by remote RPC (or, for active thread, local dispatcher).
 *
 * This is the function invoked by an active thread dispatcher to
 * call to a user-defined entrypoint function.  It sets up the dispatch
 * context for the user-defined entrypoint, then calls it.
 *
 ************************************************************************/

void dispatch_dispatch_get_packet(
  const SMACCM_DATA__UartPacket_i * in_arg ,
  smaccm_Decrypt_get_packet_struct *out_arg) {
	smaccm_max_tmp_array_send_gidl = 0;

}

/************************************************************************
 * Decrypt_write_send_gidl
 * Invoked from local active or passive thread.
 *
 * This is the comm function invoked by a user-level thread to send a message
 * to another thread.  It enqueues the request to be sent when the user thread
 * completes execution.
 *
 ************************************************************************/

bool Decrypt_write_send_gidl(const SMACCM_DATA__Array_U8_80 send_gidl) {
	if (smaccm_max_tmp_array_send_gidl > 0 &&
		 *smaccm_tmp_used_send_gidl < smaccm_max_tmp_array_send_gidl) {
		memcpy(smaccm_tmp_array_send_gidl[*smaccm_tmp_used_send_gidl], send_gidl, sizeof(SMACCM_DATA__Array_U8_80));

		(*smaccm_tmp_used_send_gidl)++;
		return true;
	} else {
		return false;
	}
}

/************************************************************************
 *
smaccm_Decrypt_periodic_dispatcher_dispatcher
 * Invoked from local active thread.
 *
 * This is the dispatcher function invoked to respond to an incoming thread
 * stimulus: an ISR, a periodic dispatch, or a queued event.
 *
 ******************************************************************************/
static smaccm_Decrypt_periodic_dispatcher_struct smaccm_Decrypt_periodic_dispatcher_arg;

void
smaccm_Decrypt_periodic_dispatcher_dispatcher(int64_t * periodic_dispatcher) {

	// make the call:
	dispatch_dispatch_periodic_dispatcher( periodic_dispatcher,
  &smaccm_Decrypt_periodic_dispatcher_arg
		);

}
/************************************************************************
 *
smaccm_Decrypt_Decrypt_initializer_dispatcher
 * Invoked from local active thread.
 *
 * This is the dispatcher function invoked to respond to an incoming thread
 * stimulus: an ISR, a periodic dispatch, or a queued event.
 *
 ******************************************************************************/
static smaccm_Decrypt_Decrypt_initializer_struct smaccm_Decrypt_Decrypt_initializer_arg;

void
smaccm_Decrypt_Decrypt_initializer_dispatcher(int64_t * Decrypt_initializer) {

	// make the call:
	dispatch_dispatch_Decrypt_initializer( Decrypt_initializer,
  &smaccm_Decrypt_Decrypt_initializer_arg
		);

}
/************************************************************************
 *
smaccm_Decrypt_get_packet_dispatcher
 * Invoked from local active thread.
 *
 * This is the dispatcher function invoked to respond to an incoming thread
 * stimulus: an ISR, a periodic dispatch, or a queued event.
 *
 ******************************************************************************/
static smaccm_Decrypt_get_packet_struct smaccm_Decrypt_get_packet_arg;

void
smaccm_Decrypt_get_packet_dispatcher(SMACCM_DATA__UartPacket_i * get_packet) {

	// make the call:
	dispatch_dispatch_get_packet( get_packet,
  &smaccm_Decrypt_get_packet_arg
		);

}

/************************************************************************
 * run
 * Main active thread function.
 *
 ************************************************************************/

int run() {
	// port initialization routines (if any)...

	// thread initialization routines (if any)...
	  int64_t dummy_time = 0;

	  smaccm_Decrypt_Decrypt_initializer_dispatcher(&dummy_time);
	// register interrupt handlers (if any)...

	// initial lock to await dispatch input.
	smaccm_dispatch_sem_wait();

	for(;;) {
		smaccm_dispatch_sem_wait();

		// drain the queues
		if (smaccm_occurred_periodic_dispatcher) {
			smaccm_occurred_periodic_dispatcher = false;

			smaccm_Decrypt_periodic_dispatcher_dispatcher(&smaccm_time_periodic_dispatcher);
		}

		while (!smaccm_queue_is_empty_get_packet()) {
			SMACCM_DATA__UartPacket_i get_packet ;
			smaccm_queue_read_get_packet(&get_packet);

			smaccm_Decrypt_get_packet_dispatcher(&get_packet);
		}

	}
	// won't ever get here, but form must be followed
	return 0;
}

/**************************************************************************
  End of autogenerated file: /home/john/git/smaccm/models/SmaccmPhaseIIIV2/components/Decrypt/src/smaccm_Decrypt.c
 **************************************************************************/


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE369_Divide_by_Zero__int_connect_socket_divide_72a.cpp
Label Definition File: CWE369_Divide_by_Zero__int.label.xml
Template File: sources-sinks-72a.tmpl.cpp
*/
/*
 * @description
 * CWE: 369 Divide by Zero
 * BadSource: connect_socket Read data using a connect socket (client side)
 * GoodSource: Non-zero
 * Sinks: divide
 *    GoodSink: Check for zero before dividing
 *    BadSink : Divide a constant by data
 * Flow Variant: 72 Data flow: data passed in a vector from one function to another in different source files
 *
 * */

#include "std_testcase.h"
#include <vector>

#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#include <direct.h>
#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */
#define CLOSE_SOCKET closesocket
#else /* NOT _WIN32 */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define CLOSE_SOCKET close
#define SOCKET int
#endif

#define TCP_PORT 27015
#define IP_ADDRESS "127.0.0.1"
#define CHAR_ARRAY_SIZE (3 * sizeof(data) + 2)

using namespace std;

namespace CWE369_Divide_by_Zero__int_connect_socket_divide_72
{

#ifndef OMITBAD

/* bad function declaration */
void badSink(vector<int> dataVector);

void bad()
{
    int data;
    vector<int> dataVector;
    /* Initialize data */
    data = -1;
    {
#ifdef _WIN32
        WSADATA wsaData;
        int wsaDataInit = 0;
#endif
        int recvResult;
        struct sockaddr_in service;
        SOCKET connectSocket = INVALID_SOCKET;
        char inputBuffer[CHAR_ARRAY_SIZE];
        do
        {
#ifdef _WIN32
            if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
            {
                break;
            }
            wsaDataInit = 1;
#endif
            /* POTENTIAL FLAW: Read data using a connect socket */
            connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
            if (connectSocket == INVALID_SOCKET)
            {
                break;
            }
            memset(&service, 0, sizeof(service));
            service.sin_family = AF_INET;
            service.sin_addr.s_addr = inet_addr(IP_ADDRESS);
            service.sin_port = htons(TCP_PORT);
            if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
            {
                break;
            }
            /* Abort on error or the connection was closed, make sure to recv one
             * less char than is in the recv_buf in order to append a terminator */
            recvResult = recv(connectSocket, inputBuffer, CHAR_ARRAY_SIZE - 1, 0);
            if (recvResult == SOCKET_ERROR || recvResult == 0)
            {
                break;
            }
            /* NUL-terminate the string */
            inputBuffer[recvResult] = '\0';
            /* Convert to int */
            data = atoi(inputBuffer);
        }
        while (0);
        if (connectSocket != INVALID_SOCKET)
        {
            CLOSE_SOCKET(connectSocket);
        }
#ifdef _WIN32
        if (wsaDataInit)
        {
            WSACleanup();
        }
#endif
    }
    /* Put data in a vector */
    dataVector.insert(dataVector.end(), 1, data);
    dataVector.insert(dataVector.end(), 1, data);
    dataVector.insert(dataVector.end(), 1, data);
    badSink(dataVector);
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink(vector<int> dataVector);

static void goodG2B()
{
    int data;
    vector<int> dataVector;
    /* Initialize data */
    data = -1;
    /* FIX: Use a value not equal to zero */
    data = 7;
    /* Put data in a vector */
    dataVector.insert(dataVector.end(), 1, data);
    dataVector.insert(dataVector.end(), 1, data);
    dataVector.insert(dataVector.end(), 1, data);
    goodG2BSink(dataVector);
}

/* goodB2G uses the BadSource with the GoodSink */
void goodB2GSink(vector<int> dataVector);

static void goodB2G()
{
    int data;
    vector<int> dataVector;
    /* Initialize data */
    data = -1;
    {
#ifdef _WIN32
        WSADATA wsaData;
        int wsaDataInit = 0;
#endif
        int recvResult;
        struct sockaddr_in service;
        SOCKET connectSocket = INVALID_SOCKET;
        char inputBuffer[CHAR_ARRAY_SIZE];
        do
        {
#ifdef _WIN32
            if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
            {
                break;
            }
            wsaDataInit = 1;
#endif
            /* POTENTIAL FLAW: Read data using a connect socket */
            connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
            if (connectSocket == INVALID_SOCKET)
            {
                break;
            }
            memset(&service, 0, sizeof(service));
            service.sin_family = AF_INET;
            service.sin_addr.s_addr = inet_addr(IP_ADDRESS);
            service.sin_port = htons(TCP_PORT);
            if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
            {
                break;
            }
            /* Abort on error or the connection was closed, make sure to recv one
             * less char than is in the recv_buf in order to append a terminator */
            recvResult = recv(connectSocket, inputBuffer, CHAR_ARRAY_SIZE - 1, 0);
            if (recvResult == SOCKET_ERROR || recvResult == 0)
            {
                break;
            }
            /* NUL-terminate the string */
            inputBuffer[recvResult] = '\0';
            /* Convert to int */
            data = atoi(inputBuffer);
        }
        while (0);
        if (connectSocket != INVALID_SOCKET)
        {
            CLOSE_SOCKET(connectSocket);
        }
#ifdef _WIN32
        if (wsaDataInit)
        {
            WSACleanup();
        }
#endif
    }
    dataVector.insert(dataVector.end(), 1, data);
    dataVector.insert(dataVector.end(), 1, data);
    dataVector.insert(dataVector.end(), 1, data);
    goodB2GSink(dataVector);
}

void good()
{
    goodG2B();
    goodB2G();
}

#endif /* OMITGOOD */

} /* close namespace */

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

#ifdef INCLUDEMAIN

using namespace CWE369_Divide_by_Zero__int_connect_socket_divide_72; /* so that we can use good and bad easily */

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

#endif


text:
package eu.scape_project.watch.interfaces.eventhandling;

/**
 * A simple scout change event that has a source and a message.
 *
 * @author Petar Petrov <me@petarpetrov.org>
 *
 */
public class ScoutChangeEvent {

  /**
   * The source of the message or the component/object that was observed and
   * changed in other words.
   */
  private Object source;

  /**
   * The actual message. This can be any kind of object ant it is in the
   * responsibility of the publisher and subscriber to agree on the content.
   */
  private Object message;

  public ScoutChangeEvent(final Object s, final Object m) {
    this.setSource(s);
    this.setMessage(m);
  }

  public Object getSource() {
    return source;
  }

  public void setSource(Object source) {
    this.source = source;
  }

  public Object getMessage() {
    return message;
  }

  public void setMessage(Object message) {
    this.message = message;
  }
}


text:
<?php

	/** an EPG entry */
	class VdrEpgEntry {

		/* attributes */
		private $id = -1;						// only used if retrieved via database
		private $channel;
		private $event;
		private $streams = array();
		private $title;
		private $descShort;
		private $descLong;
		private $genre;

		/** construction only via static methods! */
		private function __construct() {;}

		/** parse and create from epg.data strings */
		public static function getFromEpgDataStrings($channel, $event, $title, $descShort, $descLong, $genreHex, array $streams) {

			$entry = new VdrEpgEntry();

			$attr = explode(' ', $channel, 2);
			$entry->channel = new VdrChannel($attr[0], $attr[1]);

			$attr = explode(' ', $event, 5);
			$entry->event = new VdrEpgEvent($attr[0], $attr[1], $attr[1]+$attr[2], $attr[3], $attr[4]);

			$numStreams = count($streams);
			for ($i = 0; $i < $numStreams; ++$i) {
				$attr = explode(' ', $streams[$i], 4);
				$entry->streams[] = new VdrStream($attr[0], $attr[1], $attr[2], @$attr[3]);
			}

			$entry->title = $title;
			$entry->descShort = $descShort;
			$entry->descLong = str_replace('|', "\n", $descLong);
			$entry->genre = new VdrEpgGenre(hexdec($genreHex));

			return $entry;

		}

		/** directly create using the provided objects */
		public static function getFromDB($id, $title, $descShort, $descLong, $genreInt, $channel, $event, array $streams = null) {
			$entry = new VdrEpgEntry();
			$entry->id = $id;
			$entry->channel = $channel;
			$entry->event = $event;
			$entry->title = $title;
			$entry->descShort = $descShort;
			$entry->descLong = $descLong;
			$entry->genre = new VdrEpgGenre($genreInt);
			return $entry;
		}

		/** get the database-id of this entry (only used if retrieved from database! */
		public function getDbId() {return $this->id;}

		/** get the title */
		public function getTitle() {return $this->title;}

		/** get the short-desc */
		public function getDescShort() {return $this->descShort;}

		/** get the long-desc */
		public function getDescLong() {return $this->descLong;}

		/** get the channel */
		public function getChannel() {return $this->channel;}

		/** get the streams */
		public function getStreams() {return $this->streams;}

		/** get the event */
		public function getEvent() {return $this->event;}

		/** get the genre */
		public function getGenre() {return $this->genre;}

		/** check if this transmission has AC3 stream */
		public function hasAC3() {
			for ($i = 0; $i < count($this->streams); ++$i) {
				$stream = $this->streams[$i];
				$type = $stream->getStreamType();
				if (!$type || !$stream->isAudio()) {continue;}
				if ($type->getCodec() == Codec::AC3) {return true;}
			}
			return false;
		}

		/** check if this transmission has AC3 stream */
		public function isHD() {
			//if (++$this->cnt == 10) {die();}
			for ($i = 0; $i < count($this->streams); ++$i) {
				$stream = $this->streams[$i];
				$type = $stream->getStreamType();
				if (!$type || !$stream->isVideo()) {continue;}
				if ($type->getCodec() == Codec::MPEG2_HD) {return true;}
				if ($type->getCodec() == Codec::H264_HD) {return true;}
			}
			return false;
		}

		/** get an info-box for the given entry */
		public function getInfoBox($includeDesc = false) {

			$start = $this->getEvent()->getTsStart();
			$end = $this->getEvent()->getTsEnd();
			$duration = intval ($this->getEvent()->getDuration() / 60);

			$infoBox  = '';
			$infoBox .= HTML::getSafe($this->getTitle()) . '
';
			$infoBox .= MyDate::getHourMinute($start) . ' - ' . MyDate::getHourMinute($end) . ' (' . $duration . ' ' . LANG_DATE_MINUTES . ')';

			if ($end < time()) {
				// already over

			} else if ($start <= time()) {
				// currently running?
				$running = intval((time() - $start) / 60);
				$percent = 0;
				if ($duration) {
					$percent = intval($running * 100 / $duration);
				}
				$infoBox .= '
' . LANG_TIMELINE_RUNNING_SINCE . ': ' . $running . ' ' . LANG_DATE_MINUTES . ' (' . $percent . '%)';

			} else {
				// starting later
				$start = intval(($start - time()) / 60);
				$infoBox .= '
' . LANG_TIMELINE_STARTING_IN . ': ' . $start . ' ' . LANG_DATE_MINUTES;

			}

			// include long description of this show?
			if ($includeDesc) {
				$infoBox .= '
' . $this->getDescShort();
			}

			return $infoBox;

		}

	}

?>


text:
<?php

require_once BASE_PATH.'/modules/thumbnailcreator/models/base/ItemthumbnailModelBase.php';

/** Item thumbnail pdo model. */
class Thumbnailcreator_ItemthumbnailModel extends Thumbnailcreator_ItemthumbnailModelBase
{
    /**
     * Return an item thumbnail dao based on an itemId.
     *
     * @param int $itemId
     * @return false|Thumbnailcreator_ItemthumbnailDao
     */
    public function getByItemId($itemId)
    {
        $sql = $this->database->select()->where('item_id = ?', $itemId);
        $row = $this->database->fetchRow($sql);
        $dao = $this->initDao('Itemthumbnail', $row, 'thumbnailcreator');

        return $dao;
    }

    /**
     * Delete thumbnails on a given item. Called when item is about to be deleted.
     *
     * @param ItemDao $item
     */
    public function deleteByItem($item)
    {
        Zend_Registry::get('dbAdapter')->delete($this->_name, 'item_id = '.$item->getKey());
    }
}


text:
<!--
  ~ Copyright 2015 Mathew Kurian
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  ~
  ~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  ~
  ~ test_xml_activity.xml
  ~ @author Mathew Kurian
  ~
  ~ From TextJustify-Android Library v2.0
  ~ https://github.com/bluejamesbond/TextJustify-Android
  ~
  ~ Please report any issues
  ~ https://github.com/bluejamesbond/TextJustify-Android/issues
  ~
  ~ Date: 1/27/15 3:35 AM
  -->

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:orientation="vertical">

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <ProgressBar
            android:id="@+id/progressBarXml"
            style="?android:attr/progressBarStyleHorizontal"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_alignBottom="@+id/titlebar"
            android:max="100"
            android:progressDrawable="@drawable/progress__background"/>

        <TextView
            android:id="@+id/titlebar"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:padding="20dp"
            android:text="@string/titlebar"
            android:textColor="@android:color/white"
            android:textSize="20dp"
            android:textStyle="bold"/>
    </RelativeLayout>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                  android:layout_width="fill_parent"
                  android:layout_height="wrap_content"
                  android:background="#222222"
                  android:orientation="horizontal"
                  android:padding="7dp"
                  android:weightSum="100">

        <TextView
            android:id="@+id/debugButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="7dp"
            android:layout_weight="50"
            android:background="@drawable/simple_button__background"
            android:clickable="true"
            android:gravity="center"
            android:padding="10dp"
            android:text="@string/debug_button"
            android:textColor="#aaaaaa"
            android:textSize="13dp"
            android:textStyle="bold"/>

        <TextView
            android:id="@+id/cacheButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="7dp"
            android:layout_weight="50"
            android:background="@drawable/simple_button__background"
            android:clickable="true"
            android:gravity="center"
            android:padding="10dp"
            android:text="@string/cache_button"
            android:textColor="#aaaaaa"
            android:textSize="13dp"
            android:textStyle="bold"/>
    </LinearLayout>

    <com.bluejamesbond.text.DocumentView xmlns:ext="http://schemas.android.com/apk/res-auto"
                                         android:layout_width="fill_parent"
                                         android:layout_height="fill_parent"
                                         ext:documentView_antialias="true"
                                         ext:documentView_cacheConfig="auto_quality"
                                         ext:documentView_hyphen="-"
                                         ext:documentView_insetPadding="10dp"
                                         ext:documentView_insetPaddingBottom="10dp"
                                         ext:documentView_insetPaddingLeft="10dp"
                                         ext:documentView_insetPaddingRight="10dp"
                                         ext:documentView_insetPaddingTop="10dp"
                                         ext:documentView_lineHeightMultiplier="2.0"
                                         ext:documentView_maxLines="100"
                                         ext:documentView_offsetX="10dp"
                                         ext:documentView_offsetY="10dp"
                                         ext:documentView_progressBar="@id/progressBarXml"
                                         ext:documentView_reverse="false"
                                         ext:documentView_text="@string/xml_test_data"
                                         ext:documentView_textAlignment="justified"
                                         ext:documentView_textColor="@android:color/white"
                                         ext:documentView_textFormat="plain"
                                         ext:documentView_textSize="12sp"
                                         ext:documentView_textStyle="bold|strikeThru|underline"
                                         ext:documentView_textSubPixel="true"
                                         ext:documentView_textTypefacePath="fonts/helvetica.ttf"
                                         ext:documentView_wordSpacingMultiplier="5.0"/>

</LinearLayout>


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#FFFFFF" />
    <corners android:radius="@dimen/x10" />
    <stroke android:width="1dip" android:color="@color/WGAppBlueButtonColor"/>
</shape>


text:
package com.example;

import org.junit.Before;
import org.junit.Test;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

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

import static com.example.ApplicationReadyListener.Service;
import static com.example.ApplicationReadyListener.ServiceLink;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.refEq;
import static org.mockito.Mockito.same;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
import static org.springframework.http.HttpHeaders.ACCEPT;
import static org.springframework.http.HttpHeaders.AUTHORIZATION;
import static org.springframework.http.HttpHeaders.CONTENT_TYPE;
import static org.springframework.http.HttpMethod.GET;
import static org.springframework.http.HttpMethod.PATCH;
import static org.springframework.http.HttpMethod.POST;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.test.util.ReflectionTestUtils.setField;

public class ApplicationReadyListenerTest
{
    private Service service;
    private ApplicationReadyListener listener;

    @Mock
    private RestTemplate mockRestTemplate;

    @Before
    public void setUp()
    {
        initMocks(this);

        service = Service.builder().
                autoRedeploy(true).
                linkedToService(ServiceLink.builder().
                        fromServiceUri("test").
                        name("lb").
                        toServiceUri("lb").
                        build()).
                linkedToService(ServiceLink.builder().
                        fromServiceUri("test").
                        name("web").
                        toServiceUri("other").
                        build()).
                build();

        Service otherService = Service.builder().
                autoRedeploy(false).
                targetNumberOfContainers(3).
                build();

        listener = new ApplicationReadyListener(mockRestTemplate);
        setSystemPropertyValuesOnListener();

        when(mockRestTemplate.exchange(
                eq("http://localhost/api/test"), same(GET), any(HttpEntity.class), same(Service.class))).
                thenReturn(ResponseEntity.ok(service));

        when(mockRestTemplate.exchange(
                eq("http://localhost/api/other"), same(GET), any(HttpEntity.class), same(Service.class))).
                thenReturn(ResponseEntity.ok(otherService));
    }

    @Test
    public void shouldAutomaticallyPerformBlueGreenRelease()
    {
        listener.onApplicationEvent(null);

        InOrder inOrder = inOrder(mockRestTemplate);

        verifyServiceConfigurationIsUpdated(
                inOrder, "http://localhost/api/test",
                Service.builder().
                        autoRedeploy(false).
                        linkedToServices(new ArrayList<>()).
                        targetNumberOfContainers(3).
                        build());

        verifyServiceIsScaled(inOrder, "http://localhost/api/test");

        verifyServiceConfigurationIsUpdated(
                inOrder, "http://localhost/api/lb",
                Service.builder().
                        linkedToService(ServiceLink.builder().
                                fromServiceUri("lb").
                                name("web").
                                toServiceUri("test").
                                build()).
                        targetNumberOfContainers(1).
                        build());

        verifyServiceConfigurationIsUpdated(
                inOrder, "http://localhost/api/other",
                Service.builder().
                        autoRedeploy(true).
                        linkedToService(ServiceLink.builder().
                                fromServiceUri("other").
                                name("lb").
                                toServiceUri("lb").
                                build()).
                        linkedToService(ServiceLink.builder().
                                fromServiceUri("other").
                                name("web").
                                toServiceUri("test").
                                build()).
                        targetNumberOfContainers(1).
                        build());

        verifyServiceIsScaled(inOrder, "http://localhost/api/other");
    }

    @Test
    public void shouldDoNothingIfRestHostPropertyIsNotInjected()
    {
        setField(listener, "restHost", null);
        listener.onApplicationEvent(null);
        verifyZeroInteractions(mockRestTemplate);
    }

    @Test
    public void shouldDoNothingIfServiceApiUrlPropertyIsNotInjected()
    {
        setField(listener, "serviceApiUri", null);
        listener.onApplicationEvent(null);
        verifyZeroInteractions(mockRestTemplate);
    }

    @Test
    public void shouldDoNothingIfAutoDeployIsNotEnabledOnService()
    {
        service.setAutoRedeploy(false);

        listener.onApplicationEvent(null);

        verify(mockRestTemplate).exchange(
                eq("http://localhost/api/test"), same(GET), any(HttpEntity.class), same(Service.class));
        verifyNoMoreInteractions(mockRestTemplate);
    }

    @Test(expected = IllegalStateException.class)
    public void shouldValidateThatServiceHasLinkToLoadBalancer()
    {
        List<ServiceLink> linkedToServices = new ArrayList<>();
        linkedToServices.add(service.getLinkedToServices().get(0));
        service.setLinkedToServices(linkedToServices);

        listener.onApplicationEvent(null);
    }

    @Test(expected = IllegalStateException.class)
    public void shouldValidateThatServiceHasLinkToOtherService()
    {
        List<ServiceLink> linkedToServices = new ArrayList<>();
        linkedToServices.add(service.getLinkedToServices().get(1));
        service.setLinkedToServices(linkedToServices);

        listener.onApplicationEvent(null);
    }

    private void setSystemPropertyValuesOnListener()
    {
        setField(listener, "restHost", "http://localhost/api/");
        setField(listener, "serviceApiUri", "test");
    }

    private void verifyServiceConfigurationIsUpdated(InOrder inOrder, String url, Service body)
    {
        HttpHeaders httpHeaders = constructExpectedHttpHeaders();
        HttpEntity<Service> entity = new HttpEntity<>(body, httpHeaders);
        inOrder.verify(mockRestTemplate, times(1)).exchange(
                eq(url), same(PATCH), refEq(entity), same(Void.class));
    }

    private void verifyServiceIsScaled(InOrder inOrder, String url)
    {
        HttpHeaders httpHeaders = constructExpectedHttpHeaders();
        HttpEntity<Void> entity = new HttpEntity<>(httpHeaders);
        inOrder.verify(mockRestTemplate, times(1)).exchange(
                eq(url + "/scale/"), same(POST), refEq(entity), same(Void.class));
    }

    private HttpHeaders constructExpectedHttpHeaders()
    {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set(AUTHORIZATION, "Basic c3R1bWFjc29sdXRpb25zOjhjZjVlZjcwLWY2MDctNDNkMi04NDkwLTFjNWUyZDBlY2I4ZQ==");
        httpHeaders.set(ACCEPT, APPLICATION_JSON_VALUE);
        httpHeaders.set(CONTENT_TYPE, APPLICATION_JSON_VALUE);
        return httpHeaders;
    }
}


text:
#include "child_process_io_handler.h"

#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>

#include <vector>

static bool ALLWAYS_PRINT = getenv("BUILD_SHELL_ALLWAYS_PRINT") != 0;

ChildProcessIoHandler::ChildProcessIoHandler(const std::string &phase, const std::string &projectName, int out_file)
    : m_out_file(out_file)
    , m_stdout_pipe{-1,-1}
    , m_stderr_pipe{-1,-1}
    , m_error(true)
    , m_print_stdout(false)
    , m_print_stderr(true)
    , m_roller_state(0)
    , m_rooler_active(false)
    , m_use_roller(isatty(STDOUT_FILENO))
    , m_phase(phase)
    , m_project_name(projectName)
{
    if (::pipe(m_stderr_pipe)) {
        fprintf(stderr, "Failed to open pipe for stderr redirection %s\n", strerror(errno));
        return;
    }

    if (::pipe(m_stdout_pipe)) {
        fprintf(stderr, "Failed to open pipe for stdout redirection %s\n", strerror(errno));
        return;
    }

    m_error = false;
}

ChildProcessIoHandler::~ChildProcessIoHandler()
{
    if (m_stderr_pipe[1] >= 0) {
        close(m_stderr_pipe[1]);
    }
    if (m_stdout_pipe[1] >= 0) {
        close(m_stdout_pipe[1]);
    }

    m_thread.join();
}

void ChildProcessIoHandler::setupMasterProcessState()
{
    close(m_stderr_pipe[1]);
    close(m_stdout_pipe[1]);

    m_thread = std::thread(&ChildProcessIoHandler::run,this);
}

void ChildProcessIoHandler::setupChildProcessState()
{
    close(m_stdout_pipe[0]);
    close(STDOUT_FILENO);
    if (dup2(m_stdout_pipe[1], STDOUT_FILENO) < 0) {
        const char *error_msg = "Failed to dup pipe onto STDOUT_FILENO\n";
        write(m_stderr_pipe[1], error_msg, sizeof error_msg);
    }

    close(m_stderr_pipe[0]);
    close(STDERR_FILENO);
    if (dup2(m_stderr_pipe[1], STDERR_FILENO) < 0) {
        const char *error_msg = "Failed to dup pipe onto STDERR_FILENO\n";
        write(m_stderr_pipe[1], error_msg, sizeof error_msg);
    }
}

void ChildProcessIoHandler::setPrintStdOut(bool print)
{
    m_print_stdout = print;
}

static bool flushToFile(int file, char *buffer, ssize_t size)
{
    if (file < 0)
        return true;

    ssize_t written = 0;
    while (written < size) {
        ssize_t w = write(file, buffer, size);
        if (w < 0) {
            return false;
        }
        written+=w;
    }
    return true;
}

static const char roller[] = { '|', '/', '-', '\\' };

bool ChildProcessIoHandler::handle_events(const pollfd &poll_data, int out_file, bool print, int *active_connections) const
{
    if (!poll_data.revents) {
        return false;
    }
    if (poll_data.revents & POLLHUP) {
        (*active_connections)--;
    }

    bool return_val = false;
    if (poll_data.revents & POLLIN) {
        char in_buffer[1024];
        ssize_t r = read(poll_data.fd, in_buffer, sizeof in_buffer);

        if (r == 0) {
            (*active_connections)--;
        } else {
            if (out_file >= 0) {
                if (!flushToFile(out_file, in_buffer, r))
                    fprintf(stderr, "Failed to write to out_file %s\n", strerror(errno));
            }
            if (ALLWAYS_PRINT || print || out_file < 0) {
                if (!flushToFile(STDOUT_FILENO, in_buffer, r))
                    fprintf(stderr, "Failed to write to stderr %s\n", strerror(errno));
                return_val = true;
            }
        }
    }
    return return_val;
}

void ChildProcessIoHandler::run()
{
    pollfd poll_data[2];
    poll_data[0].fd = m_stdout_pipe[0];
    poll_data[0].events = POLLHUP | POLLIN;
    poll_data[1].fd = m_stderr_pipe[0];
    poll_data[1].events = POLLHUP | POLLIN;

    int active_connections = 2;

    while (active_connections > 0) {
        int poll_return = poll(poll_data, 2, -1);
        if (poll_return < 0) {
            fprintf(stderr, "ChildProcessIoHandler poll failed %s\n", strerror(errno));
            continue;
        } else {
            if (m_rooler_active) {
                m_rooler_active = false;
                write(STDOUT_FILENO, "\r",1);
            }
            bool stderr_wrote_out = handle_events(poll_data[1], m_out_file, m_print_stderr, &active_connections);
            bool stdout_wrote_out = handle_events(poll_data[0], m_out_file, m_print_stdout, &active_connections);
            if (m_use_roller && !stderr_wrote_out && !stdout_wrote_out) {
                if (!m_roller_string.size()) {
                    m_roller_string = m_phase + ": " + m_project_name + " /";
                }
                m_rooler_active = true;
                m_roller_string[m_roller_string.size() - 1] = roller[(m_roller_state += 1) % (sizeof roller / sizeof roller[0])];
                write(STDOUT_FILENO, m_roller_string.c_str(), m_roller_string.size());
            }
        }
    }
    if (m_rooler_active) {
        m_rooler_active = false;
        std::string clear_string = std::string("\r") + std::string(m_roller_string.size(), ' ') + std::string("\r");
        write(STDOUT_FILENO, clear_string.c_str(), clear_string.size());
    }

}


text:
package org.apache.spark.ui.storage

import scala.collection.mutable

import org.apache.spark.annotation.DeveloperApi
import org.apache.spark.ui._
import org.apache.spark.scheduler._
import org.apache.spark.storage._

/** Web UI showing storage status of all RDD's in the given SparkContext. */
private[ui] class StorageTab(parent: SparkUI) extends SparkUITab(parent, "storage") {
  val listener = parent.storageListener

  attachPage(new StoragePage(this))
  attachPage(new RDDPage(this))
}

/**
 * :: DeveloperApi ::
 * A SparkListener that prepares information to be displayed on the BlockManagerUI.
 *
 * This class is thread-safe (unlike JobProgressListener)
 */
@DeveloperApi
class StorageListener(storageStatusListener: StorageStatusListener) extends BlockStatusListener {

  private[ui] val _rddInfoMap = mutable.Map[Int, RDDInfo]() // exposed for testing

  def storageStatusList: Seq[StorageStatus] = storageStatusListener.storageStatusList

  /** Filter RDD info to include only those with cached partitions */
  def rddInfoList: Seq[RDDInfo] = synchronized {
    _rddInfoMap.values.filter(_.numCachedPartitions > 0).toSeq
  }

  /** Update the storage info of the RDDs whose blocks are among the given updated blocks */
  private def updateRDDInfo(updatedBlocks: Seq[(BlockId, BlockStatus)]): Unit = {
    val rddIdsToUpdate = updatedBlocks.flatMap { case (bid, _) => bid.asRDDId.map(_.rddId) }.toSet
    val rddInfosToUpdate = _rddInfoMap.values.toSeq.filter { s => rddIdsToUpdate.contains(s.id) }
    StorageUtils.updateRddInfo(rddInfosToUpdate, storageStatusList)
  }

  override def onStageSubmitted(stageSubmitted: SparkListenerStageSubmitted): Unit = synchronized {
    val rddInfos = stageSubmitted.stageInfo.rddInfos
    rddInfos.foreach { info => _rddInfoMap.getOrElseUpdate(info.id, info) }
  }

  override def onStageCompleted(stageCompleted: SparkListenerStageCompleted): Unit = synchronized {
    // Remove all partitions that are no longer cached in current completed stage
    val completedRddIds = stageCompleted.stageInfo.rddInfos.map(r => r.id).toSet
    _rddInfoMap.retain { case (id, info) =>
      !completedRddIds.contains(id) || info.numCachedPartitions > 0
    }
  }

  override def onUnpersistRDD(unpersistRDD: SparkListenerUnpersistRDD): Unit = synchronized {
    _rddInfoMap.remove(unpersistRDD.rddId)
  }

  override def onBlockUpdated(blockUpdated: SparkListenerBlockUpdated): Unit = {
    super.onBlockUpdated(blockUpdated)
    val blockId = blockUpdated.blockUpdatedInfo.blockId
    val storageLevel = blockUpdated.blockUpdatedInfo.storageLevel
    val memSize = blockUpdated.blockUpdatedInfo.memSize
    val diskSize = blockUpdated.blockUpdatedInfo.diskSize
    val externalSize = blockUpdated.blockUpdatedInfo.externalBlockStoreSize
    val blockStatus = BlockStatus(storageLevel, memSize, diskSize, externalSize)
    updateRDDInfo(Seq((blockId, blockStatus)))
  }
}


text:
require 'test_helper'

class UsersControllerTest < ActionDispatch::IntegrationTest

  test "should get new" do
    get register_path
    assert_response :success
  end
end


text:
gitdojo
=======

Jan 2014 Dojo team 5

Source repo: https://github.com/citation-style-language/styles


text:
You can configure the key event notification function on CTS so that SMN can send messages to notify you of some key operations. This function is triggered by CTS, but notifications need to be sent by SMN. This function is used in the following scenarios:

-   Real-time perception and confirmation of high-risk operations \(such as VM restart and security configuration changes\), cost-sensitive operations \(such as creating and deleting high-price resources\), and service-sensitive operations \(such as network configuration changes\)
-   Perception and confirmation of unauthorized operations such as login of a user with high permissions or operations of a user without required permissions
-   Interconnecting with your own audit system: All audit logs are synchronized to your audit system in real time to analyze the interface invoking success rate, unauthorized operations, security, and costs.

## Instructions

-   Key event notifications are sent to related subscribers using the SMN service. Therefore, before using CTS, you need to know how to create topics and add subscriptions on the SMN console.
-   Currently, you can create 100 custom notifications on CTS and specify the key operations, users, and topics for each notification.
-   You can configure key event notifications for a maximum of 50 users in 10 user groups. For each notification, you can select multiple users in one user group.
-   You can select a maximum of 1000 key operations of 100 cloud services for each notification.
-   The customized key event notification function is the upgrade version of the previous notification function. More configuration items and more powerful functions are provided. The old version will be brought offline recently.

## Procedure

1.  Log in to the management console.
2.  Click  ![](figures/icon-region-0.png)  in the upper left corner to select the desired region and project.
3.  Click  **Service List**  and choose  **Management & Deployment \> Cloud Trace Service**.
4.  In the navigation pane on the left, choose  **Key Event Notifications**.

    The  **Key Event Notifications**  page is displayed.

5.  Click  **Create Key Event Notification**. On the displayed page, specify required parameters.
6.  Enter a key event notification name.

    **Notification Name**: Identifies key event notifications. This parameter is mandatory. The value contains a maximum of 64 characters, and only letters, digits, and underscores \(\_\) are allowed.

7.  Configure key operations.

    You can select  **Typical**,  **All**, or  **Custom**  based on actual requirements:

    -   **Typical**: This scenario is suitable for routine audit of enterprises. Currently, CTS can enable text notifications pertaining to key operations such as creating and deleting some core resources of ECS, VPC, EVS, or KMS, and logging in to IAM.

        >![](/images/icon-note.gif) **NOTE:**
        >Because IAM is a global service, the  **Login**  function is only provided for the central region of the current site. After this function is enabled, SMN deployed in the central region will send notifications upon the login of any region.

    -   **All**: This scenario applies when CTS is interconnected with your own audit system. Notifications will be sent through SMN for all operations performed on interconnected cloud services. When  **All**  is selected, you cannot modify any settings, and CTS sends notifications for all traces sent from interconnected services by default. You are advised to use the SMN topic for which HTTPS is selected.
    -   **Custom**: This scenario is suitable for enterprises that require awareness and confirmation of high-risk, cost-sensitive, service-sensitive, and unauthorized operations. You can also interconnect CTS with your own audit system for log analysis. CTS enables you to configure key operations that can trigger notifications and add a maximum of 1000 key operations of 100 services. For details, see section "Supported Operations and Operation Lists" in the  _Cloud Trace Service User Guide_.

8.  Configure users.

    You can specify the users to whom SMN messages will be sent when they perform key operations.

    -   If you do not specify any users, CTS notifies all users when key operations are initiated.
    -   If you specify users, you can select whether to send SMN messages to subscribers. You can configure key event notifications for a maximum of 50 users in 10 user groups. For each notification, you can select multiple users in one user group.

9.  Configure an SMN topic.
    -   You can select an existing topic or create a one on the SMN console.
    -   If you do not want to send notifications, no further action is required.


text:
namespace Question2AnswerMigrater.Executor.OldForumModels
{
    using System;
    using System.Collections.Generic;

    public partial class qa_uservotes
    {
        public long postid { get; set; }
        public long userid { get; set; }
        public sbyte vote { get; set; }
        public sbyte flag { get; set; }

        public virtual qa_posts qa_posts { get; set; }
        public virtual qa_users qa_users { get; set; }
    }
}


text:
import http = require('http');

class Application {
    Start(port:number, callback:any): void {
        var server = http.createServer(function (request, response) {
            console.log(request.url);
            response.writeHead(200, {'Content-Type': 'text/plain'});
            response.write('<b>Hello NodeTS!</b>');
            response.end();
        })
        server.listen(port,callback);
    }
}

export = Application;


text:
require 'features/support/page_models/application_page'

module PageModels

  def self.landing_page
    Ideas.new
  end

  class Ideas < ApplicationPage
    set_url "/ideas"

    class Idea < SitePrism::Section
      element :vote_count  , ".votes"
      element :upvote_image, ".upvote img"
      element :title       , "h3.title"
      element :description , ".description"
      element :project     , ".project"
    end

    class IdeasList < SitePrism::Section
      element  :ideas_title, "h1", text: "Ideas"
      sections :idea_items, Idea, "ul li.idea"

      def ideas
        idea_items.map do |idea|
          {
            title: idea.title.text,
            description: idea.description.text,
            project: idea.project.text
          }
        end
      end
    end

    section  :idea_list, IdeasList, "#ideas"

    def change_idea(old_idea, new_idea)
      within("#idea-#{old_idea.id}") do
        click_button 'Edit'
        fill_in 'idea_title', with: new_idea.title
        fill_in 'idea_description', with: new_idea.description
        click_on 'Save'
      end

      find("#idea-#{old_idea.id} .idea-content") # block until finished
    end

  end
end


text:
class FixReferenceColumnNames < ActiveRecord::Migration
  def change
    rename_column :areas, :referrences, :references
    rename_column :features, :referrences, :references
    rename_column :routes, :referrences, :references
  end
end


text:
package edu.uci.ics.fuzzyjoin.hadoop.ridrecordpairs;

import java.io.IOException;
import java.util.Iterator;

import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.MapReduceBase;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reducer;
import org.apache.hadoop.mapred.Reporter;

public class ReduceOne extends MapReduceBase implements
        Reducer<Object, Text, Text, NullWritable> {

    final private NullWritable nullWritable = NullWritable.get();

    public void reduce(Object unused, Iterator<Text> inputValues,
            OutputCollector<Text, NullWritable> collector, Reporter reporter)
            throws IOException {
        collector.collect(inputValues.next(), nullWritable);

    }
}


text:
ossimLasPointRecord2::ossimLasPointRecord2Data::ossimLasPointRecord2Data()
   :
   m_x(0),
   m_y(0),
   m_z(0),
   m_intensity(0),
   m_bitFlags(0),
   m_classification(0),
   m_scanAngleRank(0),
   m_userData(0),
   m_pointSourceId(0),
   m_red(0),
   m_green(0),
   m_blue(0)
{
}

ossimLasPointRecord2::ossimLasPointRecord2Data::ossimLasPointRecord2Data(
   const ossimLasPointRecord2::ossimLasPointRecord2Data& obj)
   :
   m_x(obj.m_x),
   m_y(obj.m_y),
   m_z(obj.m_z),
   m_intensity(obj.m_intensity),
   m_bitFlags(obj.m_bitFlags),
   m_classification(obj.m_classification),
   m_scanAngleRank(obj.m_scanAngleRank),
   m_userData(obj.m_userData),
   m_pointSourceId(obj.m_pointSourceId),
   m_red(obj.m_red),
   m_green(obj.m_green),
   m_blue(obj.m_blue)
{
}

const ossimLasPointRecord2::ossimLasPointRecord2Data&
ossimLasPointRecord2::ossimLasPointRecord2Data::operator=(
   const ossimLasPointRecord2::ossimLasPointRecord2Data& obj)
{
   if ( this != &obj )
   {
      m_x              = obj.m_x;
      m_y              = obj.m_y;
      m_z              = obj.m_z;
      m_intensity      = obj.m_intensity;
      m_bitFlags       = obj.m_bitFlags;
      m_classification = obj.m_classification;
      m_scanAngleRank  = obj.m_scanAngleRank;
      m_userData       = obj.m_userData;
      m_pointSourceId  = obj.m_pointSourceId;
      m_red            = obj.m_red;
      m_green          = obj.m_green;
      m_blue           = obj.m_blue;
   }
   return *this;
}

ossimLasPointRecord2::ossimLasPointRecord2()
   :
   m_record()
{
}

ossimLasPointRecord2::ossimLasPointRecord2(const ossimLasPointRecord2& obj)
   :
   m_record(obj.m_record)
{
}

const ossimLasPointRecord2& ossimLasPointRecord2::operator=(const ossimLasPointRecord2& copy_this)
{
   if (this != &copy_this)
   {
      m_record = copy_this.m_record;
   }
   return *this;
}

ossimLasPointRecord2::~ossimLasPointRecord2()
{
}

void ossimLasPointRecord2::readStream(std::istream& in)
{
   in.read((char*)&m_record, 26); // sizeof reports 28 due to actual space used for STRUCT //sizeof(ossimLasPointRecord2Data));

   if ( ossim::byteOrder() == OSSIM_BIG_ENDIAN )
   {
      swap();
   }
}

void ossimLasPointRecord2::writeStream(std::ostream& out)
{
   if ( ossim::byteOrder() == OSSIM_BIG_ENDIAN )
   {
      // Write little endian per spec:
      swap();
   }

   out.write((char*)&m_record, 26); // sizeof reports 28 due to actual space used for STRUCT //sizeof(ossimLasPointRecord2Data));

   if ( ossim::byteOrder() == OSSIM_BIG_ENDIAN )
   {
      // Swap back to native byte order if needed:
      swap();
   }
}

ossim_int32 ossimLasPointRecord2::getX() const
{
   return m_record.m_x;
}

ossim_int32 ossimLasPointRecord2::getY() const
{
   return m_record.m_y;
}

ossim_int32 ossimLasPointRecord2::getZ() const
{
   return m_record.m_z;
}

ossim_uint16 ossimLasPointRecord2::getRed() const
{
   return m_record.m_red;
}

ossim_uint16 ossimLasPointRecord2::getGreen() const
{
   return m_record.m_green;
}

ossim_uint16 ossimLasPointRecord2::getBlue() const
{
   return m_record.m_blue;
}

ossim_uint16 ossimLasPointRecord2::getIntensity() const
{
   return m_record.m_intensity;
}

ossim_uint8 ossimLasPointRecord2::getReturnNumber() const
{
   return (m_record.m_bitFlags.m_returnNumber);
}

ossim_uint8 ossimLasPointRecord2::getNumberOfReturns() const
{
   return (m_record.m_bitFlags.m_numberOfReturns);
}

ossim_uint8 ossimLasPointRecord2::getEdgeFlag() const
{
   return (m_record.m_bitFlags.m_edgeOfFlightLine);
}

std::ostream& ossimLasPointRecord2::print(std::ostream& out) const
{
   // Capture the original flags.
   std::ios_base::fmtflags f = out.flags();

   out << std::setiosflags(std::ios_base::fixed) << std::setprecision(8);

   out << "x:                 " << m_record.m_x
       << "\ny:                 " << m_record.m_y
       << "\nz:                 " << m_record.m_z
       << "\nintensity:         " << m_record.m_intensity
       << "\nreturn:            " << int(getReturnNumber())
       << "\nnumber_of_returns: " << int(getNumberOfReturns())
       << "\nedge:              " << (getEdgeFlag()?"true":"false")
       << "\nscan_direction:    " << int(m_record.m_bitFlags.m_scanDirection)
       << "\nclassification:    " << m_record.m_classification
       << "\nscan_angle_rank:   " << int(m_record.m_scanAngleRank)
       << "\nuser_data:         " << m_record.m_userData
       << "\npoint_source_id:   " << m_record.m_pointSourceId
       << "\nred:               " << m_record.m_red
       << "\ngreen:             " << m_record.m_green
       << "\nblue:              " << m_record.m_blue
       << std::endl;

   // Reset flags.
   out.setf(f);
   return out;
}

void ossimLasPointRecord2::swap()
{
   ossimEndian endian;
   endian.swap(m_record.m_x);
   endian.swap(m_record.m_y);
   endian.swap(m_record.m_z);
   endian.swap(m_record.m_intensity);
   endian.swap(m_record.m_pointSourceId);
   endian.swap(m_record.m_red);
   endian.swap(m_record.m_green);
   endian.swap(m_record.m_blue);
}


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:compat="http://schemas.android.com/apk/res-auto" >

    <item
        android:id="@+id/action_logout"
        android:orderInCategory="99"
        android:title="@string/action_logout"
        compat:showAsAction="never"/>

</menu>


text:
var passport = require('passport');
var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
var debug = require('debug')('improvingu');

module.exports = function( app, config ) {
    var google = config.google || {};
    var baseUrl = process.env.BASE_URL || config.baseUrl;
    if (!baseUrl) {
        throw new Error("Please configure a base URL in config/config/js as baseUrl: \"http://localhost:8080\", or environment variable BASE_URL");
    }

    var clientId = process.env.GOOGLE_CLIENT_ID || google.clientId;
    var clientSecret = process.env.GOOGLE_CLIENT_SECRET || google.clientSecret;
    if (!clientId || !clientSecret) {
        throw new Error("Please configure Google client ID and secret in config/config.js as google { clientId: \"\", clientSecret: \"\" }, or environment variables GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET.");
    }

    passport.use(new GoogleStrategy({
            clientID: clientId,
            clientSecret: clientSecret,
            callbackURL: baseUrl + "/login/callback"
        },
        function(accessToken, refreshToken, profile, done) {
            debug("Logged in: " + JSON.stringify(profile));
            done(null, {
                provider: profile.provider,
                id: profile.id,
                profile: {
                    displayName: profile.displayName
                }
            });
        }
    ));

    passport.serializeUser(function(user, done) {
        done(null, JSON.stringify(user));
    });

    passport.deserializeUser(function(str, done) {
        done(null, JSON.parse(str));
    });

    var doPassportInitialize = passport.initialize();
    var doPassportSession = passport.session();
    app.use(doPassportInitialize);
    app.use(doPassportSession);

    var authenticate = passport.authenticate('google', {
        failureRedirect: '/public/login.html',
        scope: 'openid profile'
    });
    function authenticationCallback(req, res) {
        var redirect_to = req.session.redirect_to ? req.session.redirect_to : '/';
        delete req.session.redirect_to;
        res.redirect( redirect_to );
    }
    app.get('/login', authenticate);
    app.get('/login/callback', authenticate, authenticationCallback);

    return {
        initialize: doPassportInitialize,
        session: doPassportSession,
        require: function requireAuth(req, res, next) {
            if (req.isAuthenticated()) {
               return next();
            }
            req.session.redirect_to = req.originalUrl;
            return res.redirect('/public/login.html');
        }
    }
};


text:
<?php

class Twig_Tests_Grammar_BodyTest extends PHPUnit_Framework_TestCase
{
    public function testMagicToString()
    {
        $grammar = new Twig_Extensions_Grammar_Body('foo');
        $this->assertEquals('<foo:body>', (string) $grammar);
    }
}


text:
(npm install & bower install) && rm -rf app/bower_components/mdv
git clone --recursive https://github.com/Polymer/mdv app/bower_components/mdv
echo 'Edit config.js and run `grunt server` afterwards'


text:
<?php

namespace yii\adminUi\assetsBundle;

use yii\web\AssetBundle;

/**
 * Asset bundle for the Twitter bootstrap css files.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class AdminUiJVectorMapAsset extends AssetBundle
{
    public $sourcePath = '@vendor/adminUi/assets/';
    public $css = [
        'css/jvectormap/jquery-jvectormap-1.2.2.css',
    ];

    public $js  = [
            'js/plugins/jvectormap/jquery-jvectormap-1.2.2.min.js',
            'js/plugins/jvectormap/jquery-jvectormap-world-mill-en.js',
    ];
}


text:
var e1entry = 1
     var area1 = 'GlowBear Indevelopment Edition
 A simple JavaScript based web terminal that supports commands and stuff
 Use help command for command listing'
     var dowrite = 'hi'
     document.getElementById('echo1').innerHTML = area1;

     function setcp(p) { // set the currently running process
      cprocess = p
      document.getElementById('gbtitle').innerHTML = 'GlowBear [' + cprocess + ']';
      document.title = 'GlowBear [' + cprocess + ']';
     }
     document.getElementById('echo1').innerHTML = 'ECHO1';
     function validecho1() { // validate commands
          e1entry = document.getElementById('echo1form').value;
          area1 = area1 + '
 >' + e1entry;
          if(e1entry == 'help'){
             setcp('help')
area1 = area1 + '
 ' + 'GlowBear Help
 Commands:
 write {insert string message here} (Prints the message to the console)
 repo (Takes you to the GitHub repository)
 process (Writes the currently running process)';
document.getElementById('echo1').innerHTML = area1;
          }else{
             if (e1entry.substring(0, 6) == "write ") {
              setcp('write')
              dowrite = e1entry.substring(6)
              area1 = area1 + '
 ' + dowrite;
             }else{
              if (e1entry == "repo") {
              window.location.assign('https://github.com/codatronic/GlowBear')
              }else{
                   if (e1entry == 'process') {
                        area1 = area1 + '
 ' + cprocess;
                   }else{
                                     setcp('notvalid')
                                     area1 = area1 + '
 ' + e1entry + ' is not a valid GlowBear command';
                   }
                   }
             }
          }
          document.getElementById('echo1').innerHTML = area1;
     }
     function blink1() {
      blinkback = area1
      area1 = area1 + '
 ' + '>';
      setTimeout('blink2()', '1000')
      document.getElementById('echo1').innerHTML = area1;
     }
     function blink2() {
      area1 = blinkback;
      document.getElementById('echo1').innerHTML = area1;
     }


text:
from . import Framework
import github

class ConditionalRequestUpdate(Framework.TestCase):
    def setUp(self):
        Framework.TestCase.setUp(self)
        self.repo = self.g.get_repo("akfish/PyGithub", lazy=False)

    def testDidNotUpdate(self):
        self.assertFalse(self.repo.update(), msg="The repo is not changed. But update() != False")

    def testDidUpdate(self):
        self.assertTrue(self.repo.update(), msg="The repo should be changed by now. But update() != True")

    def testUpdateObjectWithoutEtag(self):
        r = self.g.get_repo("jacquev6/PyGithub", lazy=False)
        self.assertTrue(r.update())


text:
package organizations

import (
	"fmt"
	"io"
	"strconv"
	"time"
)

type CreateOrganizationRequest struct {
	Name string `json:"name"`
}

type Organization struct {
	ID        string               `json:"id"`
	CreatedAt time.Time            `json:"created_at"`
	UpdatedAt time.Time            `json:"updated_at"`
	DeletedAt *time.Time           `json:"deleted_at"`
	Name      string               `json:"name"`
	Members   []OrganizationMember `json:"members"`
}

type OrganizationMember struct {
	ID        string           `json:"id"`
	UserID    string           `json:"user_id"`
	Username  string           `json:"username"`
	Email     string           `json:"email"`
	RoleID    string           `json:"role_id"`
	Role      OrganizationRole `json:"role"`
	CreatedAt time.Time        `json:"created_at"`
	JoinedAt  *time.Time       `json:"joined_at"`
	DeletedAt *time.Time       `json:"deleted_at"`
}

type OrganizationMemberUpdate struct {
	UserID    string     `json:"user_id"`
	RoleID    *string    `json:"role_id"`
	DeletedAt *time.Time `json:"deleted_at"`
}

type UpdateOrganizationMembersInput struct {
	OrgID   string                     `json:"org_id"`
	Members []OrganizationMemberUpdate `json:"members"`
}

type UserOrganizationRole struct {
	RoleID       string           `json:"role_id"`
	Role         OrganizationRole `json:"role"`
	Description  string           `json:"description"`
	Organization Organization     `json:"organization"`
}

type OrganizationRole string

const (
	OrganizationRoleOwner   OrganizationRole = "Owner"
	OrganizationRoleManager OrganizationRole = "Manager"
	OrganizationRoleMember  OrganizationRole = "Member"
)

var AllOrganizationRole = []OrganizationRole{
	OrganizationRoleOwner,
	OrganizationRoleManager,
	OrganizationRoleMember,
}

func (e OrganizationRole) IsValid() bool {
	switch e {
	case OrganizationRoleOwner, OrganizationRoleManager, OrganizationRoleMember:
		return true
	}
	return false
}

func (e OrganizationRole) String() string {
	return string(e)
}

func (e *OrganizationRole) UnmarshalGQL(v interface{}) error {
	str, ok := v.(string)
	if !ok {
		return fmt.Errorf("enums must be strings")
	}

	*e = OrganizationRole(str)
	if !e.IsValid() {
		return fmt.Errorf("%s is not a valid OrganizationRole", str)
	}
	return nil
}

func (e OrganizationRole) MarshalGQL(w io.Writer) {
	fmt.Fprint(w, strconv.Quote(e.String()))
}

type Permission string

const (
	// Grants all permissions over all objects in the system.
	// Reserved for System Admin role. Cannot be granted to or inherited by other roles.
	PermissionAllPermissions Permission = "ALL_PERMISSIONS"
	// Grants the ability to modify an organization's settings, including billing information.
	PermissionOrganizationModify Permission = "ORGANIZATION_MODIFY"
	// Grants the ability to view basic information about an organization, including its name,
	// the date and time it was created, etc.
	PermissionOrganizationView Permission = "ORGANIZATION_VIEW"
	// Grants the ability to invite users to an organization.
	PermissionOrganizationUserCreate Permission = "ORGANIZATION_USER_CREATE"
	// Grants the ability to change the roles of existing users within an organization.
	PermissionOrganizationUserModify Permission = "ORGANIZATION_USER_MODIFY"
	// Grants the ability to remove users from an organization.
	PermissionOrganizationUserRemove Permission = "ORGANIZATION_USER_REMOVE"
	// Grants the ability to view a list of all the organization's members.
	PermissionOrganizationUserView Permission = "ORGANIZATION_USER_VIEW"
	// Grants the ability to create a new software list and add it to an organization's software inventory.
	PermissionOrganizationSoftwareListCreate Permission = "ORGANIZATION_SOFTWARE_LIST_CREATE"
	// Grants the ability to modify an organization's existing software lists,
	// including adding, modifying, and removing components from individual software lists.
	PermissionOrganizationSoftwareListModify Permission = "ORGANIZATION_SOFTWARE_LIST_MODIFY"
	// Grants the ability to view an organization's software lists and any components they contain.
	// This also includes the ability to export an SBOM for the software lists and view risk scoring data.
	PermissionOrganizationSoftwareListView Permission = "ORGANIZATION_SOFTWARE_LIST_VIEW"
	// Grants the ability to remove software lists from an organization's software inventory.
	PermissionOrganizationSoftwareListRemove Permission = "ORGANIZATION_SOFTWARE_LIST_REMOVE"
)

var AllPermission = []Permission{
	PermissionAllPermissions,
	PermissionOrganizationModify,
	PermissionOrganizationView,
	PermissionOrganizationUserCreate,
	PermissionOrganizationUserModify,
	PermissionOrganizationUserRemove,
	PermissionOrganizationUserView,
	PermissionOrganizationSoftwareListCreate,
	PermissionOrganizationSoftwareListModify,
	PermissionOrganizationSoftwareListView,
	PermissionOrganizationSoftwareListRemove,
}

func (e Permission) IsValid() bool {
	switch e {
	case PermissionAllPermissions, PermissionOrganizationModify, PermissionOrganizationView, PermissionOrganizationUserCreate, PermissionOrganizationUserModify, PermissionOrganizationUserRemove, PermissionOrganizationUserView, PermissionOrganizationSoftwareListCreate, PermissionOrganizationSoftwareListModify, PermissionOrganizationSoftwareListView, PermissionOrganizationSoftwareListRemove:
		return true
	}
	return false
}

func (e Permission) String() string {
	return string(e)
}

func (e *Permission) UnmarshalGQL(v interface{}) error {
	str, ok := v.(string)
	if !ok {
		return fmt.Errorf("enums must be strings")
	}

	*e = Permission(str)
	if !e.IsValid() {
		return fmt.Errorf("%s is not a valid Permission", str)
	}
	return nil
}

func (e Permission) MarshalGQL(w io.Writer) {
	fmt.Fprint(w, strconv.Quote(e.String()))
}


text:
package org.jhaws.common.documents;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;

import org.jhaws.common.io.FilePath;

public class OfficeXlsFileTextExtracter implements FileTextExtracter {
    @Override
    public List<String> accepts() {
        return Arrays.asList("xls");
    }

    @Override
    public void extract(InputStream inputFile, FilePath target) throws IOException {
        throw new UnsupportedOperationException();
    }
}


text:
php-xml-webform
===============

A PHP Web Form that collects input and e-mails it as an XML attachment.
More Information

Stand alone Example | WordPress Example