text:
package Proc::Launcher::Manager;
use strict;
use warnings;

our $VERSION = '0.0.35'; # VERSION

use Mouse;

use Carp;
use File::Path;
use POSIX qw(:sys_wait_h);

use Proc::Launcher;
use Proc::Launcher::Supervisor;

=head1 NAME

Proc::Launcher::Manager - manage multiple Proc::Launcher objects

=head1 VERSION

version 0.0.35

=head1 SYNOPSIS

    use Proc::Launcher::Manager;

    my $shared_config = { x => 1, y => 2 };

    my $monitor = Proc::Launcher::Manager->new( app_name  => 'MyApp' );

    # a couple of different components
    $monitor->register( daemon_name  => 'component1',
                        start_method => sub { MyApp->start_component1( $config ) }
                   );
    $monitor->register( daemon_name  => 'component2',
                        start_method => sub { MyApp->start_component2( $config ) }
                   );

    # using class/method/context rather than a code ref
    $monitor->register( daemon_name  => 'webui',
                        class        => 'MyApp::WebUI',
                        start_method => 'start_webui',
                        context      => $config,
                   );

    # start all registered daemons.  processes that are already
    # running won't be restarted.
    $monitor->start();

    # stop all daemons
    $monitor->stop();
    sleep 1;
    $monitor->force_stop();

    # display all processes stdout/stderr from the log file that's
    # been generated since we started
    $monitor->read_log( sub { print "$_[0]\n" } );

    # get a specific daemon or perform actions on one
    my $webui = $monitor->daemon('webui');
    $monitor->daemon('webui')->start();

    # start the process supervisor.  this will start up an event loop
    # and won't exit until it is killed.  any processes not already
    # running will be started.  all processes will be monitored and
    # automatically restarted if they exit.
    $monitor->supervisor->start();

    # shut down/restart the supervisor
    $monitor->supervisor->stop();
    $monitor->supervisor->force_stop();
    $monitor->supervisor->restart();

=head1 DESCRIPTION

This library makes it easier to deal with multiple L<Proc::Launcher>
processes by providing methods to start and stop all daemons with a
single command.  Please see the documentation in L<Proc::Launcher> to
understand how this these libraries differ from other similar forking
and controller modules.

It also provides a supervisor() method which will fork a daemon that
will monitor the other daemons at regular intervals and restart any
that have stopped.  Note that only one supervisor can be running at
any given time for each pid_dir.

There is no tracking of inter-service dependencies nor predictable
ordering of service startup.  Instead, daemons should be designed to
wait for needed resources.  See L<Launcher::Cascade> if you need to
handle dependencies.

=cut

#_* Roles

with 'Proc::Launcher::Roles::Launchable';

#_* Attributes

has 'debug'      => ( is         => 'ro',
                      isa        => 'Bool',
                      default    => 0,
                  );

has 'pid_dir'    => ( is         => 'ro',
                      isa        => 'Str',
                      lazy       => 1,
                      default    => sub {
                          my $dir = join "/", $ENV{HOME}, "logs";
                          unless ( -d $dir ) {  mkpath( $dir ); }
                          return $dir;
                      },
                  );

has 'launchers'  => ( is         => 'rw',
                      isa        => 'HashRef[Proc::Launcher]',
                  );

has 'supervisor' => ( is         => 'rw',
                      lazy       => 1,
                      default    => sub {
                          my $self = shift;

                          return Proc::Launcher->new(
                              daemon_name  => 'supervisor',
                              pid_dir      => $self->pid_dir,
                              start_method => sub {
                                  Proc::Launcher::Supervisor->new( manager => $self )->monitor();
                              },
                          );
                      },
                  );

#_* Methods

=head1 METHODS

=over 8

=item register( %options )

Create a new L<Proc::Launcher> object with the specified options.  If
the specified daemon already exists, no changes will be made.

=cut

sub register {
    my ( $self, %options ) = @_;

    $options{pid_dir} = $self->pid_dir;

    my $daemon;
    unless ( $self->{daemons}->{ $options{daemon_name} } ) {
        $daemon = Proc::Launcher->new( %options );
    }

    # just capturing the position of the tail end of the log file
    $self->read_log( undef, $daemon );

    $self->{daemons}->{ $options{daemon_name} } = $daemon;
}

=item daemon( 'daemon_name' )

Return the L<Proc::Launcher> object for a specified daemon.

=cut

sub daemon {
    my ( $self, $daemon_name ) = @_;

    return $self->{daemons}->{ $daemon_name };
}

=item daemons()

Return a list of L<Proc::Launcher> objects.

=cut

sub daemons {
    my ( $self ) = @_;

    my @daemons;

    for my $daemon_name ( $self->daemons_names() ) {
        push @daemons, $self->{daemons}->{ $daemon_name };
    }

    return @daemons;
}

=item daemons_names()

Return a list of the names of all registered daemons.

=cut

sub daemons_names {
    my ( $self ) = @_;

    return ( sort keys %{ $self->{daemons} } );
}

=item is_running()

Return a list of the names of daemons that are currently running.

This will begin by calling rm_zombies() on one of daemon objects,
sleeping a second, and then calling rm_zombies() again.  So far the
test cases have always passed when using this strategy, and
inconsistently passed with any subset thereof.

While it seems that this is more complicated than shutting down a
single process, it's really just trying to be a bit more efficient.
When managing a single process, is_running might be called a few times
until the process exits.  Since we might be managing a lot of daemons,
this method is likely to be a bit more efficient and will hopefully
only need to be called once (after the daemons have been given
necessary time to shut down).

This may be reworked a bit in the future since calling sleep will halt
all processes in single-threaded cooperative multitasking frameworks.

=cut

sub is_running {
    my ( $self ) = @_;

    my @daemon_names = $self->daemons_names();

    unless ( scalar @daemon_names ) {
        print "is_running() called when no daemons registered\n";
        return;
    }

    # clean up deceased child processes before checking if processes
    # are running.
    $self->daemon($daemon_names[0])->rm_zombies();

    # # give any processes that have ceased a second to shut down
    sleep 1;

    # again clean up deceased child processes before checking if
    # processes are running.
    $self->daemon($daemon_names[0])->rm_zombies();

    my @running = ();

    for my $daemon_name ( @daemon_names ) {
        if ( $self->daemon($daemon_name)->is_running() ) {
            push @running, $daemon_name
        }
    }

    return @running;
}

=item start( $data )

Call the start() method on all registered daemons.  If the daemon is
already running it will not be restarted.

=cut

sub start {
    my ( $self, $data ) = @_;

    my $started;

    for my $daemon ( $self->daemons() ) {
        if ( $daemon->is_running() ) {
            print "daemon already running: ", $daemon->daemon_name, "\n";
        }
        else {
            print "starting daemon: ", $daemon->daemon_name, "\n";
            $daemon->start();
            $started++;
        }
    }

    return $started;
}

=item stop()

Call the stop() method on all daemons.

=cut

sub stop {
    my ( $self ) = @_;

    for my $daemon ( $self->daemons() ) {
        print "stopping daemon: ", $daemon->daemon_name, "\n";
        $daemon->stop();
    }

    return 1;
}

=item force_stop()

Call the force_stop method on all daemons.

=cut

sub force_stop {
    my ( $self ) = @_;

    for my $daemon ( $self->daemons() ) {
        print "forcefully stopping daemon: ", $daemon->daemon_name, "\n";
        $daemon->force_stop();
    }

    return 1;
}

=item disable()

Call the disable() method on all daemons.

=cut

sub disable {
    my ( $self ) = @_;

    for my $daemon ( $self->daemons() ) {
        print "disabling daemon: ", $daemon->daemon_name, "\n";
        $daemon->disable();
    }

    return 1;
}

=item enable()

Call the enable() method on all daemons.

=cut

sub enable {
    my ( $self ) = @_;

    for my $daemon ( $self->daemons() ) {
        print "enabling daemon: ", $daemon->daemon_name, "\n";
        $daemon->enable();
    }

    return 1;
}

=item read_log()

=cut

sub read_log {
    my ( $self, $output_callback, @daemons ) = @_;

    unless ( scalar @daemons ) { @daemons = $self->daemons() }

    for my $daemon ( @daemons ) {
        $daemon->read_log( $output_callback );
    }
}

=item tail( $output_callback, $timeout_secs )

Poll all daemons for output for the specified number of seconds.  Any
output received in that time will be sent to $output_callback.  Each
line of output will be prefixed with the daemon name.

=cut

sub tail {
    my ( $self, $output_callback, $timeout ) = @_;

    # create an array of Log::Tail objects to be passed to select()
    my @tails;

    # select() will return the paths associated with each daemon, so
    # we need to be able to look up the name of a daemon based on it's
    # log file path.
    my %daemons;
    for my $daemon ( $self->daemons() ) {
        push @tails, $daemon->file_tail;
        $daemons{ $daemon->log_file } = $daemon->daemon_name;
    }

    # calculate the time when we're done processing.
    my $end = time + $timeout;

    # display all new log output to stdout
    my $count;
    while ( 1 ) {

        my ($nfound,$timeleft,@pending)=
            File::Tail::select(undef,undef,undef,1,@tails);

        if ($nfound) {
            foreach (@pending) {
                my $daemon_name = $daemons{ $_->{input} } || $_->{input};
                my $text = $_->read;

                for my $line ( split /\n/, $text ) {
                    my $output = sprintf( "%-8s: %-1s", $daemon_name, $line );
                    $output_callback->( "$output\n" );
                }
            }
        }
        else {
            # if we spawned any child procs, reap any that died
            waitpid(-1, WNOHANG);
            sleep 1;
        }

        # if timeout was specified, quit when the timeout has passed.
        if ( $timeout ) {
            last if time > $end;
        }
    }

    return 1;
}

=back

=cut

no Mouse;

1;


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

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20dp"
        android:textStyle="bold"
        android:text="Subject"
        android:layout_margin="10dp"/>
    <TextView
        android:id="@+id/assunto"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:textSize="15dp"
        android:text="assunto..." />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20dp"
        android:layout_margin="10dp"
        android:textStyle="bold"
        android:text="Texto" />
    <TextView
        android:id="@+id/texto"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="15dp"
        android:layout_margin="10dp"
        android:text="algo..." />

</LinearLayout>

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;

namespace CollectionsOnline.WebSite.Models.Api
{
    public class SearchApiInputModel
    {
        public string Sort { get; set; }

        public DateTime? MinDateModified { get; set; }

        public DateTime? MaxDateModified { get; set; }

        public IList<string> Queries { get; set; }

        public IDictionary<string, string> Facets { get; set; }

        public IDictionary<string, string[]> MultiFacets { get; set; }

        public IDictionary<string, string> Terms { get; set; }

        public SearchApiInputModel()
        {
            Queries = new List<string>();
            Facets = new Dictionary<string, string>();
            MultiFacets = new Dictionary<string, string[]>();
            Terms = new Dictionary<string, string>();
        }
    }
}


text:
"""Unit tests for templated pipelines."""

from __future__ import absolute_import

import json
import tempfile
import unittest

import apache_beam as beam
from apache_beam.options.pipeline_options import PipelineOptions
from apache_beam.pipeline import Pipeline
from apache_beam.runners.dataflow.dataflow_runner import DataflowRunner

# Protect against environments where apitools library is not available.
# pylint: disable=wrong-import-order, wrong-import-position
try:
  from apache_beam.runners.dataflow.internal import apiclient
except ImportError:
  apiclient = None  # type: ignore
# pylint: enable=wrong-import-order, wrong-import-position

@unittest.skipIf(apiclient is None, 'GCP dependencies are not installed')
class TemplatingDataflowRunnerTest(unittest.TestCase):
  """TemplatingDataflow tests."""

  def test_full_completion(self):
    # Create dummy file and close it.  Note that we need to do this because
    # Windows does not allow NamedTemporaryFiles to be reopened elsewhere
    # before the temporary file is closed.
    dummy_file = tempfile.NamedTemporaryFile(delete=False)
    dummy_file_name = dummy_file.name
    dummy_file.close()

    dummy_dir = tempfile.mkdtemp()

    remote_runner = DataflowRunner()
    pipeline = Pipeline(remote_runner,
                        options=PipelineOptions([
                            '--dataflow_endpoint=ignored',
                            '--sdk_location=' + dummy_file_name,
                            '--job_name=test-job',
                            '--project=test-project',
                            '--staging_location=' + dummy_dir,
                            '--temp_location=/dev/null',
                            '--template_location=' + dummy_file_name,
                            '--no_auth']))

    pipeline | beam.Create([1, 2, 3]) | beam.Map(lambda x: x) # pylint: disable=expression-not-assigned
    pipeline.run().wait_until_finish()
    with open(dummy_file_name) as template_file:
      saved_job_dict = json.load(template_file)
      self.assertEqual(
          saved_job_dict['environment']['sdkPipelineOptions']
          ['options']['project'], 'test-project')
      self.assertEqual(
          saved_job_dict['environment']['sdkPipelineOptions']
          ['options']['job_name'], 'test-job')

  def test_bad_path(self):
    dummy_sdk_file = tempfile.NamedTemporaryFile()
    remote_runner = DataflowRunner()
    pipeline = Pipeline(remote_runner,
                        options=PipelineOptions([
                            '--dataflow_endpoint=ignored',
                            '--sdk_location=' + dummy_sdk_file.name,
                            '--job_name=test-job',
                            '--project=test-project',
                            '--staging_location=ignored',
                            '--temp_location=/dev/null',
                            '--template_location=/bad/path',
                            '--no_auth']))
    remote_runner.job = apiclient.Job(pipeline._options,
                                      pipeline.to_runner_api())

    with self.assertRaises(IOError):
      pipeline.run().wait_until_finish()

if __name__ == '__main__':
  unittest.main()


text:
#include "caffe2/core/context_gpu.h"
#include "caffe2/core/operator.h"
#include "ctc_op.h"

namespace caffe2 {

namespace detail {
template <>
ctcComputeInfo workspaceInfo<CUDAContext>(const CUDAContext& context) {
  ctcComputeInfo result;
  result.loc = CTC_GPU;
  result.stream = context.cuda_stream();
  return result;
}
}

REGISTER_CUDA_OPERATOR(CTC, CTCOp<float, CUDAContext>);
}


text:
/*
 * test
 * @bug 6377058
 * @summary SunJCE depends on sun.security.provider.SignatureImpl
 * behaviour, BC can't load into 1st slot.
 * @author Brad R. Wetmore
 */

import java.security.*;

public class MyProvider extends Provider {

    public MyProvider() {
        super("MyProvider", 1.0, "CertImpl");
        put("CertificateFactory.X.509", "MyCertificateFactory");
    }
}


text:
{% extends "users/emails/base.html" %}
{% block content %}

<multiline label="Description">
Hello,

You access to {{domain_url}} has been revoked.
</multiline>

{% endblock content %}


text:
package com.vertabelo.mobileorm.myplaces.orm.runtime.util.monitors;

import com.vertabelo.mobileorm.myplaces.orm.runtime.dao.DAO;
import com.vertabelo.mobileorm.myplaces.orm.runtime.query.Value;
import com.vertabelo.mobileorm.myplaces.orm.runtime.util.DAOMonitor;

import java.util.List;

/**
 * DAO monitor which does not log any information.
 */
public class EmptyDAOMonitor implements DAOMonitor {

    /**
     * Constructor.
     */
    public EmptyDAOMonitor() { }

    @Override
    public void delete(DAO<?> dao, String deleteStatement, List<Value> parameters) {
    }

    @Override
    public void insert(DAO<?> dao, String insertStatement, List<Value> parameters) {
    }

    @Override
    public void selectObjectList(DAO<?> dao, String queryString, List<Value> parameters) {
    }

    @Override
    public void update(DAO<?> dao, String updateStatement, List<Value> parameters) {
    }

}


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

<title>com.douglaswhitehead.model.digitaldata.event</title>
<meta name="date" content="2015-11-09">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package com.douglaswhitehead.model.digitaldata.event

Interface Summary

Interface
Description

Event

Event interface.

Event.Builder

Event.Builder inner interface.

EventInfo

EventInfo interface.

EventInfo.Builder

EventInfo.Builder inner interface.

Class Summary

Class
Description

EventImpl

Implementation of the Event interface.

EventImpl.Builder

Implementation of the Event.Builder interface.

EventInfoImpl

Implementation of the EventInfo interface.

EventInfoImpl.Builder

Implementation of the EventInfo.Builder interface.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes


text:
package com.gokuai.cloud.data;

/**
 * Created by qp on 2017/5/2.
 */
public class FileInfo {
    public int mountId;
    public long fileSize;
    public String fileHash;
    public String fullpath;
    public String filename;
    public String hash;
    public String uploadServer;

    public FileInfo() {

    }

    public FileInfo(long fileSize, String fileHash) {
        this.fileSize = fileSize;
        this.fileHash = fileHash;
    }
}


text:
import unittest
from fabric.api import local
from lib import base
from lib.gobgp import *
from lib.exabgp import *
import sys
import os
import time
import nose
from noseplugin import OptionParser, parser_option

class GoBGPTestBase(unittest.TestCase):

    wait_per_retry = 5
    retry_limit = 10

    @classmethod
    def setUpClass(cls):
        gobgp_ctn_image_name = parser_option.gobgp_image
        base.TEST_PREFIX = parser_option.test_prefix

        g1 = GoBGPContainer(name='g1', asn=65000, router_id='192.168.0.1',
                            ctn_image_name=gobgp_ctn_image_name,
                            log_level=parser_option.gobgp_log_level)

        rs_clients = [ExaBGPContainer(name='q{0}'.format(i+1), asn=65001+i,
                      router_id='192.168.0.{0}'.format(i+2))
                      for i in range(4)]
        ctns = [g1] + rs_clients
        q1 = rs_clients[0]
        q2 = rs_clients[1]
        q3 = rs_clients[2]
        q4 = rs_clients[3]

        # advertise a route from route-server-clients
        for idx, rs_client in enumerate(rs_clients):
            route = '10.0.{0}.0/24'.format(idx+1)
            rs_client.add_route(route)
            if idx < 2:
                route = '10.0.10.0/24'
            rs_client.add_route(route)

        initial_wait_time = max(ctn.run() for ctn in ctns)

        time.sleep(initial_wait_time)

        for i, rs_client in enumerate(rs_clients):
            g1.add_peer(rs_client, is_rs_client=True)
            as2 = False
            if i > 1:
                as2 = True
            rs_client.add_peer(g1, as2=as2)

        cls.gobgp = g1
        cls.quaggas = { x.name: x for x in rs_clients }

    # test each neighbor state is turned establish
    def test_01_neighbor_established(self):
        for q in self.quaggas.itervalues():
            self.gobgp.wait_for(expected_state=BGP_FSM_ESTABLISHED, peer=q)

    def test_02_check_gobgp_local_rib(self):
        for rs_client in self.quaggas.itervalues():
            done = False
            for _ in range(self.retry_limit):
                if done:
                    break
                local_rib = self.gobgp.get_local_rib(rs_client)
                local_rib = [p['prefix'] for p in local_rib]
                if len(local_rib) < len(self.quaggas)-1:
                    time.sleep(self.wait_per_retry)
                    continue

                self.assertTrue(len(local_rib) == 4)
                done = True

            if done:
                continue
            # should not reach here
            self.assertTrue(False)

    def test_03_stop_q2_and_check_neighbor_status(self):
        q2 = self.quaggas['q2']
        q2.remove()
        self.gobgp.wait_for(expected_state=BGP_FSM_IDLE, peer=q2)

if __name__ == '__main__':
    if os.geteuid() is not 0:
        print "you are not root."
        sys.exit(1)
    output = local("which docker 2>&1 > /dev/null ; echo $?", capture=True)
    if int(output) is not 0:
        print "docker not found"
        sys.exit(1)

    nose.main(argv=sys.argv, addplugins=[OptionParser()],
              defaultTest=sys.argv[0])


text:
/*
 * This file is subject to the terms of the GFX License. If a copy of
 * the license was not distributed with this file, you can obtain one at:
 *
 *              http://ugfx.org/license.html
 */

#ifndef _GOS_X_HEAP_H
#define _GOS_X_HEAP_H

#if GOS_NEED_X_HEAP || defined(__DOXYGEN__)

/*===========================================================================*/
/* Type definitions                                                          */
/*===========================================================================*/

#ifdef __cplusplus
extern "C" {
#endif

	#if GFX_OS_HEAP_SIZE != 0 || defined(__DOXYGEN__)
		/**
		 * @brief	Take a chunk of memory and add it to the available heap
		 * @note	Memory added must obviously not already be on the heap.
		 * @note	It is allowable to add multiple non-contiguous blocks of memory
		 * 			to the heap. If however it is contiguous with a previously added block
		 * 			it will get merged with the existing block in order to allow
		 * 			allocations that span the boundary.
		 * @pre		GFX_OS_HEAP_SIZE != 0 and an operating system that uses the
		 * 			internal ugfx heap allocator rather than its own allocator.
		 */
		void gfxAddHeapBlock(void *ptr, size_t sz);
	#endif

	void *gfxAlloc(size_t sz);
	void *gfxRealloc(void *ptr, size_t oldsz, size_t newsz);
	void gfxFree(void *ptr);

#ifdef __cplusplus
}
#endif

#endif /* GOS_NEED_X_HEAP */
#endif /* _GOS_X_HEAP_H */


text:
package info.ephyra.answerselection.filters;

import info.ephyra.io.MsgPrinter;
import info.ephyra.nlp.semantics.Predicate;
import info.ephyra.querygeneration.Query;
import info.ephyra.search.Result;
import info.ephyra.util.FileCache;
import info.ephyra.util.HTMLConverter;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashSet;

/**
 *
A filter that fetches web documents that contain the given search engine
 * snippets.

 *
 *
This class extends the class Filter.

 *
 * @author Nico Schlaefer
 * @version 2007-07-24
 */
public class WebDocumentFetcherFilter extends Filter {
	/** Forbidden document types. */
	private static final String FORBIDDEN_DOCS = "(DOC|PDF|PS)";

	/** Maximum number of documents to fetch. */
	private static final int MAX_DOCS = 200;
	/** Maximum number of documents fetched in parallel. */
	private static final int MAX_PENDING = 60;

	/** Enable caching of web documents. */
	private static final boolean CACHING = true;
	/** Cache directory where web documents are stored. */
	private static final String CACHE_DIR = "cache/docs";

	/** Documents fetched by the WebDocumentFetcher threads. */
	private ArrayList<Result> docs;
	/** Number of active WebDocumentFetcher threads. */
	private int pending;

	/**
	 * Delays the main thread until all documents have been fetched.
	 */
	private void waitForDocs() {
		synchronized (docs) {
			while (pending > 0)
				try {
					docs.wait();
				} catch (InterruptedException e) {}
		}
	}

	/**
	 * Delays a thread until there are less than MAX_PENDING pending fetchers.
	 */
	public void waitForPending() {
		synchronized (docs) {
			while (pending >= MAX_PENDING)
				try {
					docs.wait();
				} catch (InterruptedException e) {}
		}
	}

	/**
	 * Increments the number of pending fetchers by 1.
	 */
	public void incPending() {
		synchronized (docs) {
			pending++;
		}
	}

	/**
	 * Used by the WebDocumentFetcher threads to return the
	 * documents.
	 *
	 * @param doc document that contains a snippet
	 * @param cached flag indicating that the document was fetched from the
	 *               search engine cache
	 */
	public void addDoc(Result doc, boolean cached) {
		synchronized (docs) {
			if (doc != null) {
				docs.add(doc);

				// if caching is enabled and the document is not from the search
				// engine cache, write document to local cache
				if (CACHING && !cached) {
					FileCache cache = new FileCache(CACHE_DIR);
					cache.write(doc.getDocID(), new String[] {doc.getAnswer()});
				}
			}

			pending--;
			docs.notify();  // signal that the fetcher is done
		}
	}

	/**
	 * Fetches the top MAX_DOCS documents containing the given
	 * search engine snippets. The original snippets are dropped.
	 *
	 * @param results array of Result objects containing snippets
	 * @return array of Result objects containing entire documents
	 */
	public Result[] apply(Result[] results) {
		// documents containing the search engine snippets
		docs = new ArrayList<Result>();

		// start document fetchers
		HashSet<String> urls = new HashSet<String>();
		for (Result result : results) {
			// only apply this filter to results for the semantic parsing
			// approach
			Query query = result.getQuery();
			Predicate[] ps = query.getAnalyzedQuestion().getPredicates();
			if (!query.extractWith(FactoidsFromPredicatesFilter.ID) ||
					ps.length == 0 ||
					result.getScore() > Float.NEGATIVE_INFINITY)
				continue;

			// if result is not a web document then just make a copy
			if (!result.getDocID().contains(":")) {
				Result newResult = result.getCopy();
				newResult.setScore(0);
				docs.add(newResult);
				continue;
			}

			// fetch at most MAX_DOCS documents
			if (urls.size() >= MAX_DOCS) break;

			String url = result.getDocID();
			// no forbidden document type
			if (url.matches("(?i).*?" + FORBIDDEN_DOCS)) continue;
			// only HTTP connections
			try {
				URLConnection conn = (new URL(url)).openConnection();
				if (!(conn instanceof HttpURLConnection)) continue;
			} catch (IOException e) {
				continue;
			}
			// no duplicate document
			if (!urls.add(url)) continue;

			// if caching is enabled, try to read document from cache
			if (CACHING) {
				FileCache cache = new FileCache(CACHE_DIR);
				String[] entries = cache.read(url);

				if (entries != null) {
					StringBuilder sb = new StringBuilder();
					for (String entry : entries) {
						sb.append(entry);
						sb.append("\n");
					}
					String docText = sb.toString();

					Result doc = new Result(docText, result.getQuery(), url,
							result.getHitPos());
					doc.setScore(0);
					docs.add(doc);

					continue;
				}
			}

			(new WebDocumentFetcher()).start(this, result);
		}

		// wait until all fetchers are done
		waitForDocs();

		// keep old results
		Result[] newResults = docs.toArray(new Result[docs.size()]);
		Result[] allResults = new Result[results.length + newResults.length];
		for (int i = 0; i < results.length; i++)
			allResults[i] = results[i];
		for (int i = 0; i < newResults.length; i++)
			allResults[results.length + i] = newResults[i];

		return allResults;
	}
}

/**
 *
A thread that fetches a web document containing a given search engine
 * snippet.

 *
 *
This class extends the class Thread.

 *
 * @author Nico Schlaefer
 * @version 2007-05-15
 */
class WebDocumentFetcher extends Thread {
	/** Number of retries if the HTTP connection fails. */
	private static final int RETRIES = 2;

	/** The WebDocumentFetcherFilter that started this thread. */
	private WebDocumentFetcherFilter filter;
	/** The search engine snippet. */
	private Result snippet;

	/**
	 * Sets the calling filter and the snippet and starts the thread.
	 *
	 * @param filter the calling WebDocumentFetcherFilter
	 * @param snippet search engine snippet
	 */
	public void start(WebDocumentFetcherFilter filter, Result snippet) {
		this.filter = filter;
		this.snippet = snippet;

		// wait until there are less than MAX_PENDING pending fetchers
		filter.waitForPending();

		start();

		// one more pending fetcher
		filter.incPending();
	}

	/**
	 * Fetches the document text and returns it to the
	 * WebDocumentFetcherFilter.
	 */
	public void run() {
		// fetch document text, retry up to RETRIES times
		String docText = null;
		int retries = RETRIES;
		boolean cached = false;
		do {
			// fetch document and convert to plain text
			try {
				docText = HTMLConverter.url2text(snippet.getDocID());

				if (docText == null)
					MsgPrinter.printHttpError("Document " +
							snippet.getDocID() + " not available.");
			} catch (SocketTimeoutException e) {
				docText = null;
				MsgPrinter.printHttpError("Connection to " +
						snippet.getDocID() + " timed out.");
			}

			retries--;

			// retrieve cached document if original document unavailable
			if (docText == null && retries < 0 &&
					snippet.getCacheID() != null &&
					!snippet.getCacheID().equals(snippet.getDocID())) {
				MsgPrinter.printErrorMsg("\nCould not fetch original source, " +
						"trying cached source instead...");
				snippet.setDocID(snippet.getCacheID());
				retries = RETRIES;
				cached = true;
			}
		} while (docText == null && retries >= 0);

		// pass document to WebDocumentFetcherFilter
		if (docText != null) {
			Result doc = new Result(docText, snippet.getQuery(),
					snippet.getDocID(), snippet.getHitPos());
			doc.setScore(0);
			filter.addDoc(doc, cached);
		} else {
			MsgPrinter.printErrorMsg("\nCould not fetch document.");
			filter.addDoc(null, cached);
//			System.exit(1);
		}
	}
}


text:
var React = require('react');
var Avatar = require('components/common/Avatar');

var userPropType = require('types/userPropType');

require('./AgendaListQuestion.css');

var AgendaListQuestion = React.createClass({

  propTypes: {
    content: React.PropTypes.string.isRequired,
    user: userPropType.isRequired
  },

  render: function() {
    return (

        <Avatar user={this.props.user}/>

{this.props.content}

    );
  }

});

module.exports = AgendaListQuestion;


text:
package com.fuscus.seien.appli.data

import com.fuscus.seien.appli.output.CustomSerializer._
import com.fuscus.seien.domain.entity.Issue
import com.fuscus.seien.infra.vo.URI
import org.json4s._
import org.json4s.native.JsonMethods._
import org.specs2.specification.Scope

case class Test(name: String, uri: URI)
case class Test2(name: String, uri: String)
case class Child(name: String, age: Int, birthdate: Option[java.util.Date])
case class Address(street: String, city: String)
case class Person(name: String, address: Address, children: List[Child])

/**
 * Created by watawuwu on 15/08/08.
 */
trait TestContext extends Scope with DummyData {
  val dataPath = "test/com/fuscus/seien/appli/data/"

  implicit lazy val formats = (DefaultFormats + URISerializer + IssueIDSerializer) ++ org.json4s.ext.JodaTimeSerializers.all

  lazy val expectIssue: Issue = {
    parse(readFile("issue.json")).extract[Issue]
  }
}


text:
require("lua/gameplay/game")
require("lua/gameplay/boxes")
require("lua/gameplay/drops")
require("lua/gameplay/controls")
require("lua/gameplay/collision")
require("lua/gameplay/character")
require("lua/gameplay/background")

gameplay = {}

function gameplay.load()
	game.init()

	boxes.create(-128)
	drops.create(-128)

	char.init()

	background.init()
end

function gameplay.update(dt)
	controls.shortcutKeys()

	if game.mode == "playing" then
		boxes.drop(dt, 800)
		drops.drop(dt, 400)

		controls.setKeyBinds()
		controls.movement(dt, 600)
		controls.limit()

		collision.collideBox(44, 30, 60)
		collision.collideDrop(44, 30, 60)

		char.shield(dt)
	end

	background.scroll(dt, 400)

	controls.waver(2, 0.05)
end

function gameplay.draw()
	background.draw()

	if game.mode == "playing" then
		drops.drawAll()
	end
	char.draw(0.75)

	if game.mode == "playing" then
		boxes.drawAll()
	end
end


text:
<?php

namespace directapi\services\keywordsResearch\models;

use directapi\components\Model;

class DeduplicateRequestItem extends Model
{
    /**
     * @var int
     */
    public $Id;

    /**
     * @var string
     */
    public $Keyword;

    /**
     * @var int
     */
    public $Weight;
}


text:
class RemovedFundingsForInitiativesGrid
  include Datagrid

  scope do
    RemovedInitiativeFunding
  end

  column(:funding_id, :header => 'Funder') do |model|
    format(model.funder_id) do |value|
      funder = Funder.find(value)
      link_to funder.name, funder
    end
  end
  column(:date_given, :header => 'Date Given') do |model|
    format(model.date_given) { |value| value.strftime('%d/%m/%Y - %H:%M') }
  end
  column(:created_at, :header => 'Date Removed') do |model|
    format(model.created_at) { |value| value.strftime('%d/%m/%Y - %H:%M') }
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <artifactId>brooklyn-example-hello-world-sql-webapp</artifactId>
    <packaging>war</packaging>
    <name>hello-world-sql-webapp Maven Webapp</name>

    <parent>
        <groupId>io.brooklyn.example</groupId>
        <artifactId>brooklyn-examples-webapps-parent</artifactId>
        <version>0.7.0-SNAPSHOT</version> <!-- BROOKLYN_VERSION -->
        <relativePath>../pom.xml</relativePath>
    </parent>

    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql-connector-java.version}</version>
        </dependency>
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>${mongodb.version}</version>
        </dependency>
    </dependencies>

    <build>
        <finalName>brooklyn-example-hello-world-sql-webapp</finalName>
    </build>
</project>


text:
<?php

require_once 'Site/Methods.php';

function smarty_modifier_slug($title)
{
    return Site_Methods::slug($title);
}


text:
require 'geong/geocoder'
require 'logger'
require 'optparse'

module Geong
  class Server
    class Configuration
      DEFAULT_PORT = 9090
      DEFAULT_NUM_THREADS = 20
      DEFAULT_LOGGER = Logger.new(STDERR)
      DEFAULT_LOGGER.level = Logger::DEBUG

      attr_writer :logger, :port, :num_threads, :transport, :transport_factory, :protocol_factory, :server

      def configure(&block)
        self.instance_exec(self, &block)
        self
      end

      def processor
        handler = Geocoder::GeocoderHandler.new()
        Geocoder::GeocoderService::Processor.new(handler)
      end

      def port(port = nil)
        self.port = port if port
        get_port
      end

      def get_port
        @port ||= DEFAULT_PORT
      end

      def num_threads(num_threads = nil)
        self.num_threads = num_threads if num_threads
        get_num_threads
      end

      def get_num_threads
        @num_threads ||= DEFAULT_NUM_THREADS
      end

      def logger(logger = nil)
        self.logger = logger if logger
        get_logger
      end

      def get_logger
        @logger ||= DEFAULT_LOGGER
      end

      def transport(transport = nil)
        self.transport = transport if transport
        get_transport
      end

      def get_transport
        @transport ||= Thrift::ServerSocket.new(port)
      end

      def transport_factory(transport_factory = nil)
        self.transport_factory = transport_factory if transport_factory
        get_transport_factory ||= Thrift::FramedTransportFactory.new
      end

      def get_transport_factory
        @transport_factory
      end

      def protocol_factory(protocol_factory = nil)
        self.protocol_factory = protocol_factory if protocol_factory
        get_protocol_factory
      end

      def get_protocol_factory
        @protocol_factory
      end

      def server(server = nil)
        self.server =server if server
        get_server
      end

      def get_server
        return @server if @server
        @server ||= Thrift::NonblockingServer.new(processor, transport, transport_factory, protocol_factory, num_threads, logger)
      end
    end
  end
end


text:
package com.weghst.setaria.client.converter;

/**
 * @author Kevin Zou (kevinz@weghst.com)
 */
public class BooleanValueConverter extends AbstractValueConverter<Boolean> {

    public static final String VALUE_TRUE = "true";
    public static final String VALUE_FALSE = "false";

    public static final String VALUE_ON = "on";
    public static final String VALUE_OFF = "off";

    public static final String VALUE_YES = "yes";
    public static final String VALUE_NO = "no";

    public static final String VALUE_1 = "1";
    public static final String VALUE_0 = "0";

    @Override
    protected Boolean doConvert(String value) {
        if (VALUE_TRUE.equalsIgnoreCase(value)
                || VALUE_ON.equalsIgnoreCase(value)
                || VALUE_YES.equalsIgnoreCase(value)
                || VALUE_1.equals(value)) {
            return true;
        } else if (VALUE_FALSE.equalsIgnoreCase(value)
                || VALUE_OFF.equalsIgnoreCase(value)
                || VALUE_NO.equalsIgnoreCase(value)
                || VALUE_0.equals(value)) {
            return false;
        } else {
            throw new IllegalArgumentException("非法的 boolean 属性值 [" + value + "]");
        }
    }
}


text:
<?php

namespace IPS\Data;

/* To prevent PHP errors (extending class does not exist) revealing path */
if ( !defined( '\IPS\SUITE_UNIQUE_KEY' ) )
{
	header( ( isset( $_SERVER['SERVER_PROTOCOL'] ) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0' ) . ' 403 Forbidden' );
	exit;
}

/**
 * Abstract Storage Class
 */
abstract class _Cache extends AbstractData
{
	/**
	 * @brief	Instance
	 */
	protected static $instance;

	/**
	 * @brief	Caches already retrieved this instance
	 */
	protected $cache	= array();

	/**
	 * @brief	Log
	 */
	public $log	= array();

	/**
	 * Get instance
	 *
	 * @return	\IPS\Data\Cache
	 */
	public static function i()
	{
		if( static::$instance === NULL )
		{
			$classname = 'IPS\Data\Cache\\' . \IPS\CACHE_METHOD;

			if ( $classname::supported() )
			{
				static::$instance = new $classname( json_decode( \IPS\CACHE_CONFIG, TRUE ) );
			}
			else
			{
				static::$instance = new \IPS\Data\Cache\None( array() );
			}
		}

		return static::$instance;
	}

	/**
	 * Store value using cache method if available or falling back to the database
	 *
	 * @param	string			$key		Key
	 * @param	mixed			$value		Value
	 * @param	\IPS\DateTime	$expire		Expiration if using database
	 * @param	bool			$fallback	Use database if no caching method is available?
	 * @return	void
	 */
	public function storeWithExpire( $key, $value, \IPS\DateTime $expire, $fallback=FALSE )
	{
		$value = array( 'value' => $value, 'expires' => $expire->getTimestamp() );

		if ( \IPS\CACHING_LOG )
		{
			$this->log[] = array( 'set', $key, version_compare( PHP_VERSION, '5.4.0' ) >= 0 ? json_encode( $value, JSON_PRETTY_PRINT ) : json_encode( $value ), var_export( debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS ), TRUE ) );
		}

		if ( $this->set( $key, json_encode( $value ), $expire ) )
		{
			$this->_data[ $key ] = $value;
			$this->_exists[ $key ] = $key;
		}
	}

	/**
	 * Get value using cache method if available or falling back to the database
	 *
	 * @param	string	$key	Key
	 * @param	bool	$fallback	Use database if no caching method is available?
	 * @return	mixed
	 * @throws	\OutOfRangeException
	 */
	public function getWithExpire( $key, $fallback=FALSE )
	{
		if ( !isset( $this->$key ) )
		{
			throw new \OutOfRangeException;
		}

		$data = $this->$key;
		if( count( $data ) and isset( $data['value'] ) and isset( $data['expires'] ) )
		{
			/* Is it expired? */
			if( $data['expires'] AND time() < $data['expires'] )
			{
				return $data['value'];
			}
			else
			{
				unset( $this->$key );
				throw new \OutOfRangeException;
			}
		}
		else
		{
			unset( $this->$key );
			throw new \OutOfRangeException;
		}
	}

	/**
	 * Clear All Caches
	 *
	 * @return	void
	 */
	public function clearAll()
	{
		/* cacheKeys stored md5 hashes of the correct value, and the cache
			is only used if the value it returns matches the hash, so clearing
			this out invalidates all caches, even if the caching engine
			does not allow us to actually clear them */
		\IPS\Data\Store::i()->cacheKeys = array();
	}
}


text:
require "spec_helper"

describe Docks::Languages::Slim do
  subject { Docks::Languages::Slim.instance }

  describe ".extensions" do
    let(:extensions) { [subject.class.extensions].flatten }

    it "includes .slim as an extension" do
      expect(extensions).to include "slim"
    end
  end

  describe "#helper_markup_for" do
    let(:mixed_arguments) { ["hello", 10, false, :goodbye, { bar: "baz", "baz" => :qux }] }
    let(:mixed_arguments_output) { "\"hello\", 10, false, :goodbye, bar: \"baz\",\n#{" " * 37}\"baz\" => :qux" }
    let(:argumentless_hash) { { "baz" => :qux } }
    let(:argumentless_hash_output) { "\"baz\" => :qux" }

    it "converts an array of arguments into the corresponding function" do
      expect(subject.helper_markup_for("foo", mixed_arguments)).to eq "== foo #{mixed_arguments_output}"
    end

    it "converts a hash with an arguments key into the corresponding function" do
      expect(subject.helper_markup_for("foo", arguments: mixed_arguments)).to eq "== foo #{mixed_arguments_output}"
    end

    it "converts a hash without an array key into a function with the hash as the only param" do
      expect(subject.helper_markup_for("foo", argumentless_hash)).to eq "== foo #{argumentless_hash_output}"
    end
  end
end


text:
<?php
//----------------------------------------------------------------------
// Copyright (c) 2012-2016 Raytheon BBN Technologies
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and/or hardware specification (the "Work") to
// deal in the Work without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Work, and to permit persons to whom the Work
// is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Work.
//
// THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS
// IN THE WORK.
//----------------------------------------------------------------------

// Standard format for responses from services: A dictionary of [code, value, output]

class RESPONSE_ARGUMENT {
  const CODE = 'code'; // Error code: no error if 0
  const VALUE = 'value'; // Result of call if no error
  const OUTPUT = 'output'; // Error info if error
}

// Canonical representation of message response
// Dictionary: [
//       code = (error code, 0 => no error),
//       value => (result if no error),
//       output => error info if error)]
//       ]
function generate_response($code, $value, $output)
{
  $result[RESPONSE_ARGUMENT::CODE] = $code;
  $result[RESPONSE_ARGUMENT::VALUE] = $value;
  $result[RESPONSE_ARGUMENT::OUTPUT] = $output;
  return $result;
}

class RESPONSE_ERROR {
  const NONE = 0;
  const DATABASE = 1;
  const AUTHENTICATION = 2;
  const AUTHORIZATION = 3;
  const ARGS = 4;
}

?>


text:
"""
   This sample shows how to update the
   large thumbnail of an item
   Python 2.x
   ArcREST 3.0.1
"""
import arcrest
from arcresthelper import securityhandlerhelper
from arcresthelper import common
def trace():
    """
        trace finds the line, the filename
        and error message and returns it
        to the user
    """
    import traceback, inspect
    tb = sys.exc_info()[2]
    tbinfo = traceback.format_tb(tb)[0]
    filename = inspect.getfile(inspect.currentframe())
    # script name + line number
    line = tbinfo.split(", ")[1]
    # Get Python syntax error
    #
    synerror = traceback.format_exc().splitlines()[-1]
    return line, filename, synerror

def main():
    proxy_port = None
    proxy_url = None

    securityinfo = {}
    securityinfo['security_type'] = 'Portal'#LDAP, NTLM, OAuth, Portal, PKI
    securityinfo['username'] = ""#<UserName>
    securityinfo['password'] = ""#<Password>
    securityinfo['org_url'] = "http://www.arcgis.com"
    securityinfo['proxy_url'] = proxy_url
    securityinfo['proxy_port'] = proxy_port
    securityinfo['referer_url'] = None
    securityinfo['token_url'] = None
    securityinfo['certificatefile'] = None
    securityinfo['keyfile'] = None
    securityinfo['client_id'] = None
    securityinfo['secret_id'] = None

    itemId = "" #Item ID
    pathToImage = r"" #Path to image

    try:
        shh = securityhandlerhelper.securityhandlerhelper(securityinfo=securityinfo)
        if shh.valid == False:
            print shh.message
        else:
            admin = arcrest.manageorg.Administration(securityHandler=shh.securityhandler)
            content = admin.content

            item = content.getItem(itemId)
            itemParams = arcrest.manageorg.ItemParameter()

            itemParams.largeThumbnail = pathToImage

            print item.userItem.updateItem(itemParameters=itemParams)
    except (common.ArcRestHelperError),e:
        print "error in function: %s" % e[0]['function']
        print "error on line: %s" % e[0]['line']
        print "error in file name: %s" % e[0]['filename']
        print "with error message: %s" % e[0]['synerror']
        if 'arcpyError' in e[0]:
            print "with arcpy message: %s" % e[0]['arcpyError']

    except:
        line, filename, synerror = trace()
        print "error on line: %s" % line
        print "error in file name: %s" % filename
        print "with error message: %s" % synerror

if __name__ == "__main__":
    main()


text:
package com.ppcxy.common.student.entity;

import com.ppcxy.common.entity.IdEntity;
import org.springframework.format.annotation.DateTimeFormat;

import javax.persistence.*;
import java.util.Date;

/**
 *
用户基本信息

 */
@Entity
@Table(name = "student_baseinfo")
@SequenceGenerator(name = "seq", sequenceName = "BaseInfo_SEQ")
public class BaseInfo extends IdEntity {

    private Student student;
    /**
     * 真实名称
     */
    private String realname;
    /**
     * 性别
     */
    private Sex sex;

    private Date birthday;

    private int age;

    @OneToOne()
    @JoinColumn(name = "student_id", unique = true, nullable = false, updatable = false)
    public Student getStudent() {
        return student;
    }

    public void setStudent(Student student) {
        this.student = student;
    }

    @Column(name = "realname", length = 100)
    public String getRealname() {
        return realname;
    }

    public void setRealname(String realname) {
        this.realname = realname;
    }

    @Column(name = "sex", length = 2)
    @Enumerated(EnumType.ORDINAL)
    public Sex getSex() {
        return sex;
    }

    public void setSex(Sex sex) {
        this.sex = sex;
    }

    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @Column(name = "birthday")
    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    @Column(name = "age")
    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}


text:
#pragma once
#include <aws/iotdeviceadvisor/IoTDeviceAdvisor_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/core/utils/DateTime.h>
#include <aws/iotdeviceadvisor/model/DeviceUnderTest.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace IoTDeviceAdvisor
{
namespace Model
{

  /**
   *
Information about the suite definition.

See Also:
   AWS
   * API Reference

   */
  class AWS_IOTDEVICEADVISOR_API SuiteDefinitionInformation
  {
  public:
    SuiteDefinitionInformation();
    SuiteDefinitionInformation(Aws::Utils::Json::JsonView jsonValue);
    SuiteDefinitionInformation& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
Suite definition ID of the test suite.

     */
    inline const Aws::String& GetSuiteDefinitionId() const{ return m_suiteDefinitionId; }

    /**
     *
Suite definition ID of the test suite.

     */
    inline bool SuiteDefinitionIdHasBeenSet() const { return m_suiteDefinitionIdHasBeenSet; }

    /**
     *
Suite definition ID of the test suite.

     */
    inline void SetSuiteDefinitionId(const Aws::String& value) { m_suiteDefinitionIdHasBeenSet = true; m_suiteDefinitionId = value; }

    /**
     *
Suite definition ID of the test suite.

     */
    inline void SetSuiteDefinitionId(Aws::String&& value) { m_suiteDefinitionIdHasBeenSet = true; m_suiteDefinitionId = std::move(value); }

    /**
     *
Suite definition ID of the test suite.

     */
    inline void SetSuiteDefinitionId(const char* value) { m_suiteDefinitionIdHasBeenSet = true; m_suiteDefinitionId.assign(value); }

    /**
     *
Suite definition ID of the test suite.

     */
    inline SuiteDefinitionInformation& WithSuiteDefinitionId(const Aws::String& value) { SetSuiteDefinitionId(value); return *this;}

    /**
     *
Suite definition ID of the test suite.

     */
    inline SuiteDefinitionInformation& WithSuiteDefinitionId(Aws::String&& value) { SetSuiteDefinitionId(std::move(value)); return *this;}

    /**
     *
Suite definition ID of the test suite.

     */
    inline SuiteDefinitionInformation& WithSuiteDefinitionId(const char* value) { SetSuiteDefinitionId(value); return *this;}

    /**
     *
Suite name of the test suite.

     */
    inline const Aws::String& GetSuiteDefinitionName() const{ return m_suiteDefinitionName; }

    /**
     *
Suite name of the test suite.

     */
    inline bool SuiteDefinitionNameHasBeenSet() const { return m_suiteDefinitionNameHasBeenSet; }

    /**
     *
Suite name of the test suite.

     */
    inline void SetSuiteDefinitionName(const Aws::String& value) { m_suiteDefinitionNameHasBeenSet = true; m_suiteDefinitionName = value; }

    /**
     *
Suite name of the test suite.

     */
    inline void SetSuiteDefinitionName(Aws::String&& value) { m_suiteDefinitionNameHasBeenSet = true; m_suiteDefinitionName = std::move(value); }

    /**
     *
Suite name of the test suite.

     */
    inline void SetSuiteDefinitionName(const char* value) { m_suiteDefinitionNameHasBeenSet = true; m_suiteDefinitionName.assign(value); }

    /**
     *
Suite name of the test suite.

     */
    inline SuiteDefinitionInformation& WithSuiteDefinitionName(const Aws::String& value) { SetSuiteDefinitionName(value); return *this;}

    /**
     *
Suite name of the test suite.

     */
    inline SuiteDefinitionInformation& WithSuiteDefinitionName(Aws::String&& value) { SetSuiteDefinitionName(std::move(value)); return *this;}

    /**
     *
Suite name of the test suite.

     */
    inline SuiteDefinitionInformation& WithSuiteDefinitionName(const char* value) { SetSuiteDefinitionName(value); return *this;}

    /**
     *
Specifies the devices that are under test for the test suite.

     */
    inline const Aws::Vector<DeviceUnderTest>& GetDefaultDevices() const{ return m_defaultDevices; }

    /**
     *
Specifies the devices that are under test for the test suite.

     */
    inline bool DefaultDevicesHasBeenSet() const { return m_defaultDevicesHasBeenSet; }

    /**
     *
Specifies the devices that are under test for the test suite.

     */
    inline void SetDefaultDevices(const Aws::Vector<DeviceUnderTest>& value) { m_defaultDevicesHasBeenSet = true; m_defaultDevices = value; }

    /**
     *
Specifies the devices that are under test for the test suite.

     */
    inline void SetDefaultDevices(Aws::Vector<DeviceUnderTest>&& value) { m_defaultDevicesHasBeenSet = true; m_defaultDevices = std::move(value); }

    /**
     *
Specifies the devices that are under test for the test suite.

     */
    inline SuiteDefinitionInformation& WithDefaultDevices(const Aws::Vector<DeviceUnderTest>& value) { SetDefaultDevices(value); return *this;}

    /**
     *
Specifies the devices that are under test for the test suite.

     */
    inline SuiteDefinitionInformation& WithDefaultDevices(Aws::Vector<DeviceUnderTest>&& value) { SetDefaultDevices(std::move(value)); return *this;}

    /**
     *
Specifies the devices that are under test for the test suite.

     */
    inline SuiteDefinitionInformation& AddDefaultDevices(const DeviceUnderTest& value) { m_defaultDevicesHasBeenSet = true; m_defaultDevices.push_back(value); return *this; }

    /**
     *
Specifies the devices that are under test for the test suite.

     */
    inline SuiteDefinitionInformation& AddDefaultDevices(DeviceUnderTest&& value) { m_defaultDevicesHasBeenSet = true; m_defaultDevices.push_back(std::move(value)); return *this; }

    /**
     *
Specifies if the test suite is intended for qualification.

     */
    inline bool GetIntendedForQualification() const{ return m_intendedForQualification; }

    /**
     *
Specifies if the test suite is intended for qualification.

     */
    inline bool IntendedForQualificationHasBeenSet() const { return m_intendedForQualificationHasBeenSet; }

    /**
     *
Specifies if the test suite is intended for qualification.

     */
    inline void SetIntendedForQualification(bool value) { m_intendedForQualificationHasBeenSet = true; m_intendedForQualification = value; }

    /**
     *
Specifies if the test suite is intended for qualification.

     */
    inline SuiteDefinitionInformation& WithIntendedForQualification(bool value) { SetIntendedForQualification(value); return *this;}

    /**
     *
Date (in Unix epoch time) when the test suite was created.

     */
    inline const Aws::Utils::DateTime& GetCreatedAt() const{ return m_createdAt; }

    /**
     *
Date (in Unix epoch time) when the test suite was created.

     */
    inline bool CreatedAtHasBeenSet() const { return m_createdAtHasBeenSet; }

    /**
     *
Date (in Unix epoch time) when the test suite was created.

     */
    inline void SetCreatedAt(const Aws::Utils::DateTime& value) { m_createdAtHasBeenSet = true; m_createdAt = value; }

    /**
     *
Date (in Unix epoch time) when the test suite was created.

     */
    inline void SetCreatedAt(Aws::Utils::DateTime&& value) { m_createdAtHasBeenSet = true; m_createdAt = std::move(value); }

    /**
     *
Date (in Unix epoch time) when the test suite was created.

     */
    inline SuiteDefinitionInformation& WithCreatedAt(const Aws::Utils::DateTime& value) { SetCreatedAt(value); return *this;}

    /**
     *
Date (in Unix epoch time) when the test suite was created.

     */
    inline SuiteDefinitionInformation& WithCreatedAt(Aws::Utils::DateTime&& value) { SetCreatedAt(std::move(value)); return *this;}

  private:

    Aws::String m_suiteDefinitionId;
    bool m_suiteDefinitionIdHasBeenSet;

    Aws::String m_suiteDefinitionName;
    bool m_suiteDefinitionNameHasBeenSet;

    Aws::Vector<DeviceUnderTest> m_defaultDevices;
    bool m_defaultDevicesHasBeenSet;

    bool m_intendedForQualification;
    bool m_intendedForQualificationHasBeenSet;

    Aws::Utils::DateTime m_createdAt;
    bool m_createdAtHasBeenSet;
  };

} // namespace Model
} // namespace IoTDeviceAdvisor
} // namespace Aws


text:
{% load i18n %}
{% for activity in activities %}
{% include 'activitysingle.html' %}
{% endfor %}
{% if activities|length >= page_size %}

⟱

{% endif %}
{% if activities|length == 0 %}

{% trans 'No results.' %}

{% endif %}


text:
Bienvenue dans Paperwork !

Ici se trouvera l'aide. N'hésitez pas à contribuer au projet.

Pour simplifié la rédaction de cette page. Le langage [Markdown](http://fr.wikipedia.org/wiki/Markdown) a été intégré et peut être géré selon les exemples suivants :

* Liens d'aide : Pour faire un lien vers d'autres pages d'aide, il suffit d'utiliser simplement : `[C'est un lien](@help.folder.anotherfolder.file)`
* Images d'aide : Pour afficher les images qui sont stockés dans le répertoire public/images/help/-folder, utiliser ceci : `![mon image](@image.ay-caramba.png "Ay caramba!")`


text:
import pyglet
import pytmx.util_pyglet
from pyglet.window import key

# Not pretty to include these here also but it's messy to pass around such
# constants
SCREEN_HEIGHT = 480
SCREEN_WIDTH = 640
TILE_SIZE = 16

def create_batch_from_tileset(tiled_map, layer_name):
    """ Function for creating a Sprite batch (pyglet.graphics.Batch) from tileset's
    certain layer. Returns the batch and a list containing the sprites."""
    sprite_list = []
    sprite_batch = pyglet.graphics.Batch()
    for tile in tiled_map.get_layer_by_name(layer_name).tiles():
        sprite_list.append(pyglet.sprite.Sprite(tile[2],
                                                tile[0] * TILE_SIZE,
                                                SCREEN_HEIGHT -
                                                tile[1] * TILE_SIZE -
                                                TILE_SIZE,
                                                batch=sprite_batch))
    return sprite_batch, sprite_list

def check_keys(keys):
    movedir = "NONE"
    jump_pressed = False
    run_pressed = False

    if keys[key.LEFT]:
        movedir = "LEFT"
    elif keys[key.RIGHT]:
        movedir = "RIGHT"
    else:
        movedir = "NONE"

    if keys[key.UP]:
        jump_pressed = True
    else:
        jump_pressed = False

    if keys[key.LSHIFT]:
        run_pressed = True

    return (movedir, jump_pressed, run_pressed)

def check_collision(player_object, collisionmap, movedir):
    """ Function for checking player collision. Checks player's rectangle's
    different sides' coordinates depending on move direction."""
    test_x_left = player_object.collision_box.x + player_object.speed_x
    test_x_right = player_object.collision_box.right + player_object.speed_x
    test_y_top = player_object.collision_box.y + player_object.collision_box.height
    test_y_bottom = player_object.collision_box.y

    # Check if player is jumping
    if movedir == "UP":
        test_y_top += player_object.speed_y
        test_y_bottom += player_object.speed_y

    # Generate coordinates that are checked from collisionmap
    x_coord_left = test_x_left / collisionmap.tilewidth
    x_coord_right = test_x_right / collisionmap.tilewidth
    y_coord_top = (collisionmap.height * collisionmap.tileheight -
        test_y_top) / collisionmap.tileheight
    y_coord_bottom = (collisionmap.height * collisionmap.tileheight -
        test_y_bottom) / collisionmap.tileheight

    # Corner checks
    top_right = collisionmap.get_tile_gid(x_coord_right, y_coord_top, 1)
    top_left = collisionmap.get_tile_gid(x_coord_left, y_coord_top, 1)
    bottom_right = collisionmap.get_tile_gid(x_coord_right, y_coord_bottom, 1)
    bottom_left = collisionmap.get_tile_gid(x_coord_left, y_coord_bottom, 1)

    # If there's anything but 0 in GIDs' of those tiles, return True because collision happened
    if top_right == 0 and top_left == 0 and bottom_right == 0 and bottom_left == 0:
        return False
    else:
        return True


text:
@interface BitmessageKit2 : NavInfoNode

@end


text:
package workers

import (
	"testing"
)

func TestDockerImage(t *testing.T) {
	if testing.Short() {
		t.Skip("Skipping docker tests in short mode")
	} else {
		t.Parallel()
		losers := []parameters{[]string{"failme"}, []string{""}}
		testInputs(t, dockerImage, []parameters{}, losers)
	}
}

func TestDockerImageRegexp(t *testing.T) {
	if testing.Short() {
		t.Skip("Skipping docker tests in short mode")
	} else {
		t.Parallel()
		losers := []parameters{[]string{"failme"}, []string{"regexp"}}
		testInputs(t, dockerImageRegexp, []parameters{}, losers)
	}
}

func TestDockerRunning(t *testing.T) {
	if testing.Short() {
		t.Skip("Skipping docker tests in short mode")
	} else {
		t.Parallel()
		losers := []parameters{[]string{"failme"}, []string{""}}
		testInputs(t, dockerRunning, []parameters{}, losers)
	}
}

func TestDockerRunningAPI(t *testing.T) {
	if testing.Short() {
		t.Skip("Skipping docker tests in short mode")
	} else {
		t.Parallel()
		path := "/var/run/docker.sock"
		losers := []parameters{[]string{path, "failme"}, []string{path, ""}}
		testInputs(t, dockerRunningAPI, []parameters{}, losers)
	}
}

func TestDockerRunningRegexp(t *testing.T) {
	if testing.Short() {
		t.Skip("Skipping docker tests in short mode")
	} else {
		t.Parallel()
		losers := []parameters{[]string{"failme"}, []string{""}}
		testInputs(t, dockerRunningRegexp, []parameters{}, losers)
	}
}


text:
<!DOCTYPE HTML>

    <title>Offline Application Cache - API_status_IDLE</title>


text:
package org.restexpress.plugin.content.resolver;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import org.junit.Test;

/**
 * Test class for {@link ResolverTest}.
 *
 * @author Jerome Guibert
 *
 */
public class ResolverTest {

    public ResolverTest() {
    }

    @Test
    public void checkResolverWithoutExcludedPart() {
        final Resolver resolver = new Resolver("", null);

        assertTrue(resolver.match("/root"));
        assertFalse(resolver.match("boot"));
        assertEquals("/root/", resolver.resolve("/root/"));
        assertEquals("/Root/", resolver.resolve("/Root/"));
        assertEquals("/root/a", resolver.resolve("/root/a"));
        assertEquals("/rOot/a", resolver.resolve("/rOot/a"));
        assertEquals("/rOot/a/b/c/d", resolver.resolve("/rOot/a/b/c/d"));
    }

    @Test
    public void checkResolverWithExcludedPart() {
        final Resolver resolver = new Resolver("/root", new String[] { "/root/b" });
        assertTrue(resolver.match("/root"));
        assertFalse(resolver.match("boot"));

        assertTrue(resolver.match("/root/a"));
        assertEquals("/a", resolver.resolve("/root/a"));
        assertFalse(resolver.match("/root/b"));
        assertFalse(resolver.match("/root/b/a"));

    }
}


text:
export * from './src/link';
export * from './src/normalized-resource';
export * from './src/relations';
export * from './src/resource';
export * from './src/dsl/embedded-from';
export * from './src/dsl/from';
export * from './src/dsl/links-from';

export * from './src/parser/parser';
export * from './src/uri/uri';


text:
from .base import DoubanApiBase, DEFAULT_START, DEFAULT_COUNT

class Doumail(DoubanApiBase):

    def __repr__(self):
        return '<DoubanAPI Doumail>'

    def get(self, id):
        return self._get('/v2/doumail/%s'%id)

    def inbox(self, start=DEFAULT_START, count=DEFAULT_COUNT):
        return self._get('/v2/doumail/inbox', start=start, count=count)

    def outbox(self, start=DEFAULT_START, count=DEFAULT_COUNT):
        return self._get('/v2/doumail/outbox', start=start, count=count)

    def unread(self, start=DEFAULT_START, count=DEFAULT_COUNT):
        return self._get('/v2/doumail/inbox/unread', start=start, count=count)

    def read(self, id):
        return self._put('/v2/doumail/%s'%id, key='key')

    def reads(self, ids):
        if isinstance(ids, (list, tuple)):
            ids = ','.join(ids)
        return self._put('/v2/doumail/read', ids=ids)

    def delete(self, id):
        return self._delete('/v2/doumail/%s'%id)

    def deletes(self, ids):
        if isinstance(ids, (tuple, list)):
            ids = ','.join(ids)
        return self._post('/v2/doumail/delete', ids=ids)

    def new(self, title, content, receiver_id, captcha_token=None, captcha_string=None):
        return self._post('/v2/doumails', title=title, content=content, receiver_id=receiver_id,
                captcha_toke=captcha_token, captcha_string=captcha_string)


text:
import {AuthorizedResource} from './authorizedResource';
import {Resource, IResource} from './resource';
import {Request, Response} from 'express';
import SubResource = require('./subResource');

class AuthorizedSubResource extends AuthorizedResource {
  constructor(subResDef: ISubResource) {
    var resDef = {
      name: null,
      model: null
    };
    for (var prop in subResDef) {
      if (subResDef.hasOwnProperty(prop)) {
        resDef[prop] = subResDef[prop];
      }
    }
    super(resDef);
  }

  createModel(resDef: IResource) {
    // sub resource model is already created
    return resDef.parentResource.model;
  }

  getAll(req: Request, res: Response) {
    this.isAuthorized(req, this.permissions.getAll)
      .then(() => SubResource.prototype.getAll.call(this, req, res),
        (err: Error) => this.sendUnauthorized(err, res));
  }

  getById(req: Request, res: Response) {
    this.isAuthorized(req, this.permissions.getById)
      .then(() => SubResource.prototype.getById.call(this, req, res),
        (err: Error) => this.sendUnauthorized(err, res));
  }

  create(req: Request, res: Response) {
    this.isAuthorized(req, this.permissions.create)
      .then(() => SubResource.prototype.create.call(this, req, res),
        (err: Error) => this.sendUnauthorized(err, res));
  }

  update(req: Request, res: Response) {
    this.isAuthorized(req, this.permissions.update)
      .then(() => SubResource.prototype.update.call(this, req, res),
        (err: Error) => this.sendUnauthorized(err, res));
  }

  del(req: Request, res: Response) {
    this.isAuthorized(req, this.permissions.del)
      .then(() => SubResource.prototype.del.call(this, req, res),
        (err: Error) => this.sendUnauthorized(err, res));
  }

  createProjectionQuery(req: Request) {
    return SubResource.prototype.createProjectionQuery.call(this, req);
  }

  createPullQuery(req: Request) {
    return SubResource.prototype.createPullQuery.call(this, req);
  }

  createFindQuery(req: Request) {
    return SubResource.prototype.createFindQuery.call(this, req);
  }

  createSubUpdateQuery(req: Request) {
    return SubResource.prototype.createSubUpdateQuery.call(this, req);
  }
}

interface ISubResource {
  name: string;
  plural?: string;
  parentResource: Resource;
  populate?: string;
}

export = AuthorizedSubResource;


text:
"""Tests for preprocess hook."""

import unittest
from grow.extensions.hooks import preprocess_hook

class PreprocessHookTestCase(unittest.TestCase):
    """Test the preprocess hook."""

    def test_something(self):
        """?"""
        pass


text:
namespace SofiaToday.Web.ViewModels.Articles
{
    using System.Collections.Generic;
    using Comments;

    public class ArticlePageViewModel
    {
        public ArticleViewModel Article { get; set; }

        public CreateCommentInputModel CommentInputModel { get; set; }

        public IEnumerable<CommentViewModel> Comments { get; set; }
    }
}


text:
/** @defgroup gpio_defines GPIO Defines

@brief <b>Defined Constants and Types for the LPC17xx General Purpose I/O</b>

@ingroup LPC17xx_defines

@version 1.0.0

@author @htmlonly © @endhtmlonly 2009 Uwe Hermann <uwe@hermann-uwe.de>

@date 10 March 2013

LGPL License Terms @ref lgpl_license
 */
/*
 * This file is part of the libopencm3 project.
 *
 * Copyright (C) 2010 Uwe Hermann <uwe@hermann-uwe.de>
 *
 * This library is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this library.  If not, see <http://www.gnu.org/licenses/>.
 */

#ifndef LPC17XX_GPIO_H
#define LPC17XX_GPIO_H

/**@{*/

#include <libopencm3/cm3/common.h>
#include <libopencm3/lpc17xx/memorymap.h>

/* --- Convenience macros -------------------------------------------------- */

/* GPIO port base addresses (for convenience) */
#define GPIO0				GPIO_PIO0_BASE
#define GPIO1				GPIO_PIO1_BASE
#define GPIO2				GPIO_PIO2_BASE
#define GPIO3				GPIO_PIO3_BASE
#define GPIO4				GPIO_PIO4_BASE

/* GPIO number definitions (for convenience) */
#define GPIOPIN0                        (1 << 0)
#define GPIOPIN1                        (1 << 1)
#define GPIOPIN2                        (1 << 2)
#define GPIOPIN3                        (1 << 3)
#define GPIOPIN4                        (1 << 4)
#define GPIOPIN5                        (1 << 5)
#define GPIOPIN6                        (1 << 6)
#define GPIOPIN7                        (1 << 7)
#define GPIOPIN8                        (1 << 8)
#define GPIOPIN9                        (1 << 9)
#define GPIOPIN10                       (1 << 10)
#define GPIOPIN11                       (1 << 11)
#define GPIOPIN12                       (1 << 12)
#define GPIOPIN13                       (1 << 13)
#define GPIOPIN14                       (1 << 14)
#define GPIOPIN15                       (1 << 15)
#define GPIOPIN16                       (1 << 16)
#define GPIOPIN17                       (1 << 17)
#define GPIOPIN18                       (1 << 18)
#define GPIOPIN19                       (1 << 19)
#define GPIOPIN20                       (1 << 20)
#define GPIOPIN21                       (1 << 21)
#define GPIOPIN22                       (1 << 22)
#define GPIOPIN23                       (1 << 23)
#define GPIOPIN24                       (1 << 24)
#define GPIOPIN25                       (1 << 25)
#define GPIOPIN26                       (1 << 26)
#define GPIOPIN27                       (1 << 27)
#define GPIOPIN28                       (1 << 28)
#define GPIOPIN29                       (1 << 29)
#define GPIOPIN30                       (1 << 30)
#define GPIOPIN31                       (1 << 31)

/* --- GPIO registers ------------------------------------------------------ */

/* GPIO data direction register (GPIOn_DIR) */
#define GPIO_DIR(port)			MMIO32(port + 0x00)
#define GPIO0_DIR			GPIO_DIR(GPIO0)
#define GPIO1_DIR			GPIO_DIR(GPIO1)
#define GPIO2_DIR			GPIO_DIR(GPIO2)
#define GPIO3_DIR			GPIO_DIR(GPIO3)
#define GPIO4_DIR			GPIO_DIR(GPIO4)

/* GPIO fast mask register (GPIOn_DIR) */
#define GPIO_MASK(port)			MMIO32(port + 0x10)
#define GPIO0_MASK			GPIO_MASK(GPIO0)
#define GPIO1_MASK			GPIO_MASK(GPIO1)
#define GPIO2_MASK			GPIO_MASK(GPIO2)
#define GPIO3_MASK			GPIO_MASK(GPIO3)
#define GPIO4_MASK			GPIO_MASK(GPIO4)

/* GPIO port pin value register (GPIOn_PIN) */
#define GPIO_PIN(port)			MMIO32(port + 0x14)
#define GPIO0_PIN			GPIO_PIN(GPIO0)
#define GPIO1_PIN			GPIO_PIN(GPIO1)
#define GPIO2_PIN			GPIO_PIN(GPIO2)
#define GPIO3_PIN			GPIO_PIN(GPIO3)
#define GPIO4_PIN			GPIO_PIN(GPIO4)

/* GPIO port output set register (GPIOn_SET) */
#define GPIO_SET(port)			MMIO32(port + 0x18)
#define GPIO0_SET			GPIO_SET(GPIO0)
#define GPIO1_SET			GPIO_SET(GPIO1)
#define GPIO2_SET			GPIO_SET(GPIO2)
#define GPIO3_SET			GPIO_SET(GPIO3)
#define GPIO4_SET			GPIO_SET(GPIO4)

/* GPIO port output clear register (GPIOn_CLR) */
#define GPIO_CLR(port)			MMIO32(port + 0x1C)
#define GPIO0_CLR			GPIO_CLR(GPIO0)
#define GPIO1_CLR			GPIO_CLR(GPIO1)
#define GPIO2_CLR			GPIO_CLR(GPIO2)
#define GPIO3_CLR			GPIO_CLR(GPIO3)
#define GPIO4_CLR			GPIO_CLR(GPIO4)

/* GPIO interrupt register map */
/* Interrupt enable rising edge */
#define GPIO0_IER                       MMIO32(GPIOINTERRUPT_BASE + 0x90)
#define GPIO2_IER                       MMIO32(GPIOINTERRUPT_BASE + 0xB0)

/* Interrupt enable falling edge */
#define GPIO0_IEF                       MMIO32(GPIOINTERRUPT_BASE + 0x94)
#define GPIO2_IEF                       MMIO32(GPIOINTERRUPT_BASE + 0xB4)

/* Interrupt status rising edge */
#define GPIO0_ISR                       MMIO32(GPIOINTERRUPT_BASE + 0x84)
#define GPIO2_ISR                       MMIO32(GPIOINTERRUPT_BASE + 0xA4)

/* Interrupt status falling edge */
#define GPIO0_ISF                       MMIO32(GPIOINTERRUPT_BASE + 0x88)
#define GPIO2_ISF                       MMIO32(GPIOINTERRUPT_BASE + 0xA8)

/* Interrupt clear */
#define GPIO0_IC                        MMIO32(GPIOINTERRUPT_BASE + 0x8C)
#define GPIO1_IC                        MMIO32(GPIOINTERRUPT_BASE + 0xAC)

/* Overall interrupt status */
#define GPIO_IS                         MMIO32(GPIOINTERRUPT_BASE + 0x80)

BEGIN_DECLS

void gpio_set(uint32_t gpioport, uint32_t gpios);
void gpio_clear(uint32_t gpioport, uint32_t gpios);

END_DECLS

/**@}*/

#endif


text:
using Akka.TestKit.Xunit2;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Neo.Consensus;
using Neo.IO;
using Neo.Network.P2P.Payloads;
using Neo.SmartContract.Native;
using Neo.Wallets;
using System;
using System.Linq;

namespace Neo.UnitTests.Consensus
{

    [TestClass]
    public class UT_ConsensusContext : TestKit
    {
        ConsensusContext _context;
        KeyPair[] _validatorKeys;

        [TestInitialize]
        public void TestSetup()
        {
            TestBlockchain.InitializeMockNeoSystem();

            var rand = new Random();
            var mockWallet = new Mock<Wallet>();
            mockWallet.Setup(p => p.GetAccount(It.IsAny<UInt160>())).Returns<UInt160>(p => new TestWalletAccount(p));

            // Create dummy validators

            _validatorKeys = new KeyPair[7];
            for (int x = 0; x < _validatorKeys.Length; x++)
            {
                var pk = new byte[32];
                rand.NextBytes(pk);

                _validatorKeys[x] = new KeyPair(pk);
            }

            _context = new ConsensusContext(mockWallet.Object, TestBlockchain.Store)
            {
                Validators = _validatorKeys.Select(u => u.PublicKey).ToArray()
            };
            _context.Reset(0);
        }

        [TestCleanup]
        public void Cleanup()
        {
            Shutdown();
        }

        [TestMethod]
        public void TestMaxBlockSize_Good()
        {
            // Only one tx, is included

            var tx1 = CreateTransactionWithSize(200);
            _context.EnsureMaxBlockSize(new Transaction[] { tx1 });
            EnsureContext(_context, tx1);

            // All txs included

            var max = (int)NativeContract.Policy.GetMaxTransactionsPerBlock(_context.Snapshot);
            var txs = new Transaction[max];

            for (int x = 0; x < max; x++) txs[x] = CreateTransactionWithSize(100);

            _context.EnsureMaxBlockSize(txs);
            EnsureContext(_context, txs);
        }

        [TestMethod]
        public void TestMaxBlockSize_Exceed()
        {
            // Two tx, the last one exceed the size rule, only the first will be included

            var tx1 = CreateTransactionWithSize(200);
            var tx2 = CreateTransactionWithSize(256 * 1024);
            _context.EnsureMaxBlockSize(new Transaction[] { tx1, tx2 });
            EnsureContext(_context, tx1);

            // Exceed txs number, just MaxTransactionsPerBlock included

            var max = (int)NativeContract.Policy.GetMaxTransactionsPerBlock(_context.Snapshot);
            var txs = new Transaction[max + 1];

            for (int x = 0; x < max; x++) txs[x] = CreateTransactionWithSize(100);

            _context.EnsureMaxBlockSize(txs);
            EnsureContext(_context, txs.Take(max).ToArray());
        }

        private Transaction CreateTransactionWithSize(int v)
        {
            var r = new Random();
            var tx = new Transaction()
            {
                Cosigners = new Cosigner[0],
                Attributes = new TransactionAttribute[0],
                NetworkFee = 0,
                Nonce = (uint)Environment.TickCount,
                Script = new byte[0],
                Sender = UInt160.Zero,
                SystemFee = 0,
                ValidUntilBlock = (uint)r.Next(),
                Version = 0,
                Witnesses = new Witness[0],
            };

            // Could be higher (few bytes) if varSize grows
            tx.Script = new byte[v - tx.Size];
            return tx;
        }

        private Block SignBlock(ConsensusContext context)
        {
            context.Block.MerkleRoot = null;

            // Fake commits

            for (int x = 0; x < _validatorKeys.Length; x++)
            {
                _context.MyIndex = x;

                var com = _context.MakeCommit();
                _context.CommitPayloads[_context.MyIndex] = com;
            }

            return context.CreateBlock();
        }

        private void EnsureContext(ConsensusContext context, params Transaction[] expected)
        {
            // Check all tx

            Assert.AreEqual(expected.Length, context.Transactions.Count);
            Assert.IsTrue(expected.All(tx => context.Transactions.ContainsKey(tx.Hash)));

            Assert.AreEqual(expected.Length, context.TransactionHashes.Length);
            Assert.IsTrue(expected.All(tx => context.TransactionHashes.Count(t => t == tx.Hash) == 1));

            // Ensure length

            var block = SignBlock(context);

            Assert.AreEqual(context.GetExpectedBlockSize(), block.Size);
            Assert.IsTrue(block.Size < NativeContract.Policy.GetMaxBlockSize(context.Snapshot));
        }
    }
}


text:
<?xml version="1.0"?>
<!--

-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <update handle="sales_order_creditmemo_renderers"/>
    <update handle="customer_account"/>
    <update handle="sales_order_item_price"/>
    <update handle="sales_order_info_links"/>
    <body>
        <referenceContainer name="page.main.title">
            <block class="Magento\Sales\Block\Order\Info" name="order.status" template="order/order_status.phtml"/>
            <block class="Magento\Sales\Block\Order\Info" name="order.date" template="order/order_date.phtml"/>
            <container name="order.actions.container" htmlTag="div" htmlClass="actions-toolbar order-actions-toolbar">
                <block class="Magento\Sales\Block\Order\Info\Buttons" as="buttons" name="sales.order.info.buttons" cacheable="false"/>
            </container>
        </referenceContainer>
        <referenceContainer name="content">
            <block class="Magento\Sales\Block\Order\Creditmemo" name="sales.order.creditmemo" cacheable="false" after="sales.order.info.links">
                <block class="Magento\Sales\Block\Order\Creditmemo\Items" name="creditmemo_items" template="order/creditmemo/items.phtml">
                    <block class="Magento\Framework\View\Element\RendererList" name="sales.order.creditmemo.renderers" as="renderer.list"/>
                    <block class="Magento\Sales\Block\Order\Creditmemo\Totals" name="creditmemo_totals" template="order/totals.phtml">
                        <arguments>
                            <argument name="label_properties" xsi:type="string">colspan="6" class="mark"</argument>
                            <argument name="value_properties" xsi:type="string">class="amount"</argument>
                        </arguments>
                        <block class="Magento\Tax\Block\Sales\Order\Tax" name="tax" template="order/tax.phtml"/>
                    </block>
                    <block class="Magento\Sales\Block\Order\Comments" name="creditmemo_comments" template="order/comments.phtml"/>
                </block>
            </block>
        </referenceContainer>
        <referenceContainer name="sales.order.info.buttons">
            <block class="Magento\Sales\Block\Order\Info\Buttons\Rss" as="buttons.rss" name="sales.order.info.buttons.rss" cacheable="false"/>
        </referenceContainer>
        <block class="Magento\Framework\View\Element\Template" name="additional.product.info" template="Magento_Theme::template.phtml"/>
    </body>
</page>


text:
package org.olat.presentation.framework.extensions.action;

import org.olat.presentation.framework.core.UserRequest;

/**
 * Description:

 * Should be used for GenericActionExtensions in combination with a GenericMainController which decides if the controller defined in the ActionExtension will be shown in
 * menu, resp. if the toolController may be used. Implement the two methods and provide name of your implementation in olat_extensions.xml. See docu in
 * GenericActionExtension.
 *

 * Initial Date: 07.07.2009

 *
 * @author Roman Haag, roman.haag@frentix.com, frentix GmbH
 */
public interface ActionExtensionSecurityCallback {

    /**
     * Defines when its allowed to launch the configured controller. ActionController is mostly shown in column 3 (middle column)
     *
     * @return true if allowed (default), else false
     */
    public boolean isAllowedToLaunchActionController(UserRequest ureq);

}


text:
#include "AboutTipster.h"
#include "MainWindow.h"

#include <Application.h>
#include <Catalog.h>
#include <ControlLook.h>
#include <Dragger.h>
#include <GroupLayout.h>
#include <GroupLayoutBuilder.h>
#include <LayoutBuilder.h>
#include <Menu.h>
#include <MenuBar.h>
#include <MenuItem.h>
#include <TranslationUtils.h>

#include <private/interface/AboutWindow.h>

#include <stdio.h>

enum
{
	SHOW_ABOUT = 'swat',
	NEXT_TIP = 'nxtp',
	PREVIOUS_TIP = 'pvtp',
	DELAY = 'dely',
	MSG_QUIT = 'quit'
};

#undef B_TRANSLATION_CONTEXT
#define B_TRANSLATION_CONTEXT "MainWindow"

MainWindow::MainWindow()
	:
	BWindow(BRect(100, 100, 740, 190), B_TRANSLATE_SYSTEM_NAME("Tipster"),
		B_TITLED_WINDOW, B_ASYNCHRONOUS_CONTROLS | B_NOT_V_RESIZABLE
		| B_AUTO_UPDATE_SIZE_LIMITS)
{
	BuildLayout();
}

void
MainWindow::BuildLayout()
{
	BMenuBar* fMenuBar = new BMenuBar("menubar");

	BMenu* fTipsterMenu = new BMenu(B_TRANSLATE_SYSTEM_NAME("Tipster"));
	BMenu* fTipMenu = new BMenu(B_TRANSLATE("Tip"));

	fDelaySubMenu = new BMenu(B_TRANSLATE("Delay"));

	fTipsterMenu->AddItem(new BMenuItem(B_TRANSLATE("About"),
		new BMessage(SHOW_ABOUT)));
	fTipsterMenu->AddItem(new BMenuItem(B_TRANSLATE("Quit"),
		new BMessage(MSG_QUIT)));

	fTipMenu->AddItem(new BMenuItem(B_TRANSLATE("Previous tip"),
		new BMessage(PREVIOUS_TIP)));
	fTipMenu->AddItem(new BMenuItem(B_TRANSLATE("Next tip"),
		new BMessage(NEXT_TIP)));

	fTipMenu->AddItem(fDelaySubMenu);

	fMenuBar->AddItem(fTipsterMenu);
	fMenuBar->AddItem(fTipMenu);

	fTipsterView = new Tipster();

	BLayoutBuilder::Group<>(this, B_VERTICAL, 0)
		.Add(fMenuBar)
		.Add(fTipsterView)
		.AddGlue();

	// After the creation of Tipster because we need the delay
	// time saved in the settings

	AddDelaySubMenuItem(30000000, B_TRANSLATE("30 seconds"));
	AddDelaySubMenuItem(60000000, B_TRANSLATE("1 minute"));
	AddDelaySubMenuItem(120000000, B_TRANSLATE("2 minutes"));
	AddDelaySubMenuItem(300000000, B_TRANSLATE("5 minutes"));

	fDelaySubMenu->SetRadioMode(true);
}

void
MainWindow::AddDelaySubMenuItem(bigtime_t delay, const char *label)
{
	BMenuItem* menuItem;
	BMessage* delayMessage = new BMessage(DELAY);
	delayMessage->AddInt64("delay", delay);
	fDelaySubMenu->AddItem(menuItem = new BMenuItem(label, delayMessage));
	menuItem->SetMarked(delay == fTipsterView->Delay());
}

bool
MainWindow::QuitRequested()
{
	be_app->PostMessage(B_QUIT_REQUESTED);
	return true;
}

#undef B_TRANSLATION_CONTEXT
#define B_TRANSLATION_CONTEXT "About"

void
MainWindow::MessageReceived(BMessage* message)
{
	switch(message->what)
	{
		case SHOW_ABOUT:
		{
			BAboutWindow* about = new AboutTipster();
			about->Show();
			break;
		}
		case NEXT_TIP:
		{
			fTipsterView->UpdateTip();
			break;
		}
		case PREVIOUS_TIP:
		{
			fTipsterView->DisplayPreviousTip();
			break;
		}
		case DELAY:
		{
			int64 delay = 60000000;
			message->FindInt64("delay", &delay);

			fTipsterView->SetDelay(delay);
			break;
		}
		case MSG_QUIT:
		{
			be_app->PostMessage(B_QUIT_REQUESTED);
			break;
		}
		default:
			BWindow::MessageReceived(message);
			break;
	}
}


text:
package org.sakaiproject.tool.assessment.ui.listener.author;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.faces.event.AbortProcessingException;
import javax.faces.event.ActionEvent;
import javax.faces.event.ActionListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.sakaiproject.event.cover.EventTrackingService;
import org.sakaiproject.tool.assessment.facade.AgentFacade;
import org.sakaiproject.tool.assessment.facade.AssessmentFacade;
import org.sakaiproject.tool.assessment.facade.ItemFacade;
import org.sakaiproject.tool.assessment.facade.SectionFacade;
import org.sakaiproject.tool.assessment.services.ItemService;
import org.sakaiproject.tool.assessment.services.QuestionPoolService;
import org.sakaiproject.tool.assessment.services.assessment.AssessmentService;
import org.sakaiproject.tool.assessment.ui.bean.author.AssessmentBean;
import org.sakaiproject.tool.assessment.ui.bean.author.ItemAuthorBean;
import org.sakaiproject.tool.assessment.ui.bean.authz.AuthorizationBean;
import org.sakaiproject.tool.assessment.ui.bean.questionpool.QuestionPoolBean;
import org.sakaiproject.tool.assessment.ui.listener.util.ContextUtil;

public class ItemRemoveListener implements ActionListener
{
	private static final Logger log = LoggerFactory.getLogger(ItemModifyListener.class);
	private static final String PERM_SAM_ASSESSMENT_REVISE = "sam.assessment.revise";
	private static final String PERM_SAM_ASSESSMENT_ITEM_DELETE = "sam.assessment.item.delete";

	public void processAction(ActionEvent ae) throws AbortProcessingException
	{
		ItemAuthorBean item = (ItemAuthorBean) ContextUtil.lookupBean("itemauthor");
		ItemService delegate = new ItemService();
		if(item.getItemToDelete() == null) {
			return;
		}
		String deleteId = String.valueOf(item.getItemToDelete().getItemId());
		ItemFacade itemf = delegate.getItem(deleteId);
		// save the currSection before itemf.setSection(null), used to reorder question sequences
		SectionFacade  currSection = (SectionFacade) itemf.getSection();
		Integer  currSeq = itemf.getSequence();
		QuestionPoolService qpdelegate = new QuestionPoolService();
		if (qpdelegate.getPoolIdsByItem(deleteId) ==  null || qpdelegate.getPoolIdsByItem(deleteId).isEmpty()) {
			// if no reference to this item at all, ie, this item is created in assessment but not assigned to any pool
			AuthorizationBean authzBean = (AuthorizationBean) ContextUtil.lookupBean("authorization");
			AssessmentService assessdelegate = new AssessmentService();
			AssessmentFacade af = assessdelegate.getBasicInfoOfAnAssessmentFromSectionId(currSection.getSectionId());
			if (!authzBean.isUserAllowedToEditAssessment(af.getAssessmentBaseId().toString(), af.getCreatedBy(), false)) {
				throw new IllegalArgumentException("User does not have permission to delete item in assessment: " + af.getAssessmentBaseId());
			}
			delegate.deleteItem(Long.valueOf(deleteId), AgentFacade.getAgentString());
		}
		else {
			if (currSection == null) {
				// if this item is created from question pool
				QuestionPoolBean  qpoolbean= (QuestionPoolBean) ContextUtil.lookupBean("questionpool");
				ItemFacade itemfacade= delegate.getItem(deleteId);
				ArrayList<ItemFacade> items = new ArrayList<>();
				items.add(itemfacade);
				qpoolbean.setItemsToDelete(items);
				qpoolbean.removeQuestionsFromPool();
				return;
			}
			else {
				// if some pools still reference to this item, ie, this item is
				// created in assessment but also assigned a a pool
				// then just set section = null
				itemf.setSection(null);
				delegate.saveItem(itemf);
			}
		}
		//An item has been deleted
		EventTrackingService.post(EventTrackingService.newEvent(PERM_SAM_ASSESSMENT_ITEM_DELETE, "/sam/" +AgentFacade.getCurrentSiteId() + "/removed itemId=" + deleteId, true));
		AssessmentService assessdelegate = new AssessmentService();

		// reorder item numbers
		SectionFacade sectfacade = assessdelegate.getSection(currSection.getSectionId().toString());
		Set<ItemFacade> itemset = sectfacade.getItemFacadeSet();
		// should be size-1 now.
		for (ItemFacade itemfacade : itemset) {
			Integer itemfacadeseq = itemfacade.getSequence();
			if (itemfacadeseq.compareTo(currSeq) > 0 ){
				itemfacade.setSequence( Integer.valueOf(itemfacadeseq.intValue()-1) );
				delegate.saveItem(itemfacade);
			}
		}
		// this will ensure that in case the same bean is re-POST, it won't be in scope
		item.setItemToDelete(null);
		//  go to editAssessment.jsp, need to first reset assessmentBean
		AssessmentBean assessmentBean = (AssessmentBean) ContextUtil.lookupBean(
				"assessmentBean");
		AssessmentFacade assessment = assessdelegate.getAssessment(assessmentBean.getAssessmentId());
		assessmentBean.setAssessment(assessment);
		assessdelegate.updateAssessmentLastModifiedInfo(assessment);
		//Assessment has been revised
		EventTrackingService.post(EventTrackingService.newEvent(PERM_SAM_ASSESSMENT_REVISE, "/sam/" +AgentFacade.getCurrentSiteId() + "/removed itemId=" + deleteId + "from assessmentId=" + assessmentBean.getAssessmentId(), true));
	}

}


text:
package sqlalertstore

import (
	"context"
	"encoding/json"
	"sort"
	"time"

	"github.com/jackc/pgx/v4/pgxpool"
	"go.skia.org/infra/go/skerr"
	"go.skia.org/infra/perf/go/alerts"
)

// statement is an SQL statement identifier.
type statement int

const (
	// The identifiers for all the SQL statements used.
	insertAlert statement = iota
	updateAlert
	deleteAlert
	listActiveAlerts
	listAllAlerts
)

// statements holds all the raw SQL statements used.
var statements = map[statement]string{
	insertAlert: `
		INSERT INTO
			Alerts (alert, last_modified)
		VALUES
			($1, $2)
		RETURNING
			id
		`,
	updateAlert: `
		UPSERT INTO
			Alerts (id, alert, config_state, last_modified)
		VALUES
			($1, $2, $3, $4)
		`,
	deleteAlert: `
		UPDATE
		  	Alerts
		SET
			config_state=1, -- alerts.DELETED
			last_modified=$1
		WHERE
			id=$2
		`,
	listActiveAlerts: `
		SELECT
			id, alert
		FROM
			ALERTS
		WHERE
			config_state=0 -- alerts.ACTIVE
		`,
	listAllAlerts: `
		SELECT
			id, alert
		FROM
			ALERTS
		`,
}

// SQLAlertStore implements the alerts.Store interface.
type SQLAlertStore struct {
	// db is the database interface.
	db *pgxpool.Pool
}

// New returns a new *SQLAlertStore.
//
// We presume all migrations have been run against db before this function is
// called.
func New(db *pgxpool.Pool) (*SQLAlertStore, error) {

	return &SQLAlertStore{
		db: db,
	}, nil
}

// Save implements the alerts.Store interface.
func (s *SQLAlertStore) Save(ctx context.Context, cfg *alerts.Alert) error {
	b, err := json.Marshal(cfg)
	if err != nil {
		return skerr.Wrapf(err, "Failed to serialize Alert for saving with ID=%s", cfg.IDAsString)
	}
	now := time.Now().Unix()

	if cfg.IDAsString == alerts.BadAlertIDAsAsString {
		newID := alerts.BadAlertID
		// Not a valid ID, so this should be an insert, not an update.
		if err := s.db.QueryRow(ctx, statements[insertAlert], string(b), now).Scan(&newID); err != nil {
			return skerr.Wrapf(err, "Failed to insert alert")
		}
		cfg.SetIDFromInt64(newID)
	} else {
		if _, err := s.db.Exec(ctx, statements[updateAlert], cfg.IDAsStringToInt(), string(b), cfg.StateToInt(), now); err != nil {
			return skerr.Wrapf(err, "Failed to update Alert with ID=%s", cfg.IDAsString)
		}
	}

	return nil
}

// Delete implements the alerts.Store interface.
func (s *SQLAlertStore) Delete(ctx context.Context, id int) error {
	now := time.Now().Unix()
	if _, err := s.db.Exec(ctx, statements[deleteAlert], now, id); err != nil {
		return skerr.Wrapf(err, "Failed to mark Alert as deleted with ID=%d", id)
	}
	return nil
}

type sortableAlertSlice []*alerts.Alert

func (p sortableAlertSlice) Len() int { return len(p) }
func (p sortableAlertSlice) Less(i, j int) bool {
	if p[i].DisplayName == p[j].DisplayName {
		return p[i].IDAsString < p[j].IDAsString
	}
	return p[i].DisplayName < p[j].DisplayName
}
func (p sortableAlertSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }

// List implements the alerts.Store interface.
func (s *SQLAlertStore) List(ctx context.Context, includeDeleted bool) ([]*alerts.Alert, error) {
	stmt := listActiveAlerts
	if includeDeleted {
		stmt = listAllAlerts
	}
	rows, err := s.db.Query(ctx, statements[stmt])
	if err != nil {
		return nil, err
	}
	ret := []*alerts.Alert{}
	for rows.Next() {
		var id int64
		var serializedAlert string
		if err := rows.Scan(&id, &serializedAlert); err != nil {
			return nil, err
		}
		a := &alerts.Alert{}
		if err := json.Unmarshal([]byte(serializedAlert), a); err != nil {
			return nil, skerr.Wrapf(err, "Failed to deserialize JSON Alert.")
		}
		a.SetIDFromInt64(id)
		ret = append(ret, a)
	}
	sort.Sort(sortableAlertSlice(ret))
	return ret, nil
}