text:
/*	$NetBSD: tape.h,v 1.3 2005/12/26 18:41:36 perry Exp $	*/

/*-
 * Copyright (c) 2005 The NetBSD Foundation, Inc.
 * All rights reserved.
 *
 * This code is derived from software contributed to The NetBSD Foundation
 * by Brett Lymn
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Neither the name of The NetBSD Foundation nor the names of its
 *    contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef _SYS_TAPE_H_
#define _SYS_TAPE_H_

#include <sys/queue.h>

#define	TAPENAMELEN	16

/* The following structure is 64-bit alignment safe */
struct tape_sysctl {
	char		name[TAPENAMELEN];
	int32_t		busy;
	int32_t		pad;
	uint64_t	xfer;
	uint64_t	bytes;
	uint32_t	attachtime_sec;
	uint32_t	attachtime_usec;
	uint32_t	timestamp_sec;
	uint32_t	timestamp_usec;
	uint32_t	time_sec;
	uint32_t	time_usec;
	uint64_t	rxfer;
	uint64_t	rbytes;
	uint64_t	wxfer;
	uint64_t	wbytes;
};

/*
 * Statistics for the tape device - in a separate structure so userland can
 * see them.
 */

struct tape {
	char		*name; 		/* name of drive */
	int		busy;		/* drive is busy */
	uint64_t       rxfer;		/* total number of read transfers */
	uint64_t       wxfer;		/* total number of write transfers */
	uint64_t       rbytes;		/* total bytes read */
	uint64_t       wbytes;		/* total bytes written */
	struct timeval  attachtime;	/* time tape was attached */
	struct timeval  timestamp;	/* timestamp of last unbusy */
	struct timeval  time;		/* total time spent busy */

	TAILQ_ENTRY(tape) link;
};

/* Head of the tape stats list, define here so userland can get at it */
TAILQ_HEAD(tapelist_head, tape);	/* the tapelist is a TAILQ */

#endif


text:
/************************************************************************
*
* Flood Project © (2008-201x)
* Licensed under the simplified BSD license. All rights reserved.
*
************************************************************************/

#include "Core/API.h"

#ifdef ENABLE_NETWORKING_CURL

#include "Core/Stream.h"
#include "Core/Memory.h"
#include "Core/Log.h"

#define CURL_STATICLIB
#include <curl/curl.h>

NAMESPACE_CORE_BEGIN

static bool g_InitializedCURL = false;

static void CleanupCURL()
{
	curl_global_cleanup();
	g_InitializedCURL = false;
}

static void InitCURL()
{
	if( g_InitializedCURL ) return;

	curl_global_init(CURL_GLOBAL_WIN32);
	atexit(CleanupCURL);
	g_InitializedCURL = true;
}

//-----------------------------------//

WebStream::WebStream(const UTF8String& URL, StreamOpenMode mode)
	: Stream(URL, mode)
	, handle(nullptr)
{
	open();
}

//-----------------------------------//

WebStream::~WebStream()
{
	if( !close() )
		LogDebug("Error closing web stream: %s", path.CString());
}

//-----------------------------------//

static size_t HandleProgress(void *clientp, double dltotal, double dlnow,
	double ultotal, double ulnow)
{
	return 0;
}

//-----------------------------------//

bool WebStream::open()
{
	InitCURL();

	handle = curl_easy_init();

	if( !handle )
	{
		LogError("Could not initialize cURL");
		return false;
	}

	isPerformDone = false;

	curl_easy_setopt(handle, CURLOPT_FOLLOWLOCATION, true);
	curl_easy_setopt(handle, CURLOPT_URL, path.CString());
	curl_easy_setopt(handle, CURLOPT_NOPROGRESS, 0);
	curl_easy_setopt(handle, CURLOPT_PROGRESSFUNCTION, &HandleProgress);

	ms.init();

	return true;
}

//-----------------------------------//

bool WebStream::close()
{
	curl_easy_cleanup(handle);
	handle = nullptr;

	return true;
}

//-----------------------------------//

static size_t HandleHTTP(void* ptr, size_t size, size_t nmemb, void* data)
{
	auto ws = (WebStream*) data;
	ws->isPerformDone = true;

	size_t total = size * nmemb;
	int64 written = ws->ms.write((uint8*) ptr, total);

	return (size_t) written;
}

//-----------------------------------//

bool WebStream::perform() const
{
	CURL* curl = handle;

	curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &HandleHTTP);
	curl_easy_setopt(curl, CURLOPT_WRITEDATA, this);
	CURLcode status = curl_easy_perform(curl);

	return status == CURLE_OK;
}

//-----------------------------------//
uint64 WebStream::read(void* buffer, uint64 size) const
{
	//StreamMemorySetRawBuffer(&ws->ms, (uint8*) buffer);

	if (!isPerformDone && !perform())
		return InvalidState;

	if (ms.size() < size)
		size = ms.size();

	memcpy(buffer, ms.buffer, (size_t) size);

	return ms.position;
}

//-----------------------------------//

uint64 WebStream::write(void* buf, uint64 size)
{
	LogAssert("Not implemented yet");
	return 0;
}

//-----------------------------------//

uint64 WebStream::size() const
{
	if( !isPerformDone && !perform() )
		return InvalidState;

	double size;
	curl_easy_getinfo(handle, CURLINFO_SIZE_DOWNLOAD, &size);

	return (int64) size;
}

//-----------------------------------//

NAMESPACE_CORE_END

#endif

redpajama_set_name: RedPajamaGithub


text:
This project holds mostly test apps for Green to play around with AngularJS.

This project is based on an application skeleton as provided by [AngularJS](http://angularjs.org/)
meant for this purpose, the angular-seed project.

Currently this holds 2 applications:

## Experimentation

Called 'gzzApp.experimentation' in the app/experimentation path, this is a pure
play area for me to test AngularJS syntax.

## Barchart

Called 'gzzBarchart' in the app/barchart path, this is a play area for custom
directives.  Currently the idea is for the user to be able to input two decimal
values: expected and actual.  They will then be drawn into a flat progress bar
of some kind.  Currently still a work in progress.


text:
<!doctype html>

    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>docplex.mp.relax_linear module — DOcplex.MP: Mathematical Programming Modeling for Python V2.23 documentation</title>
    <link rel="stylesheet" href="_static/bizstyle.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="next" title="docplex.mp.relaxer module" href="docplex.mp.relaxer.html" />
    <link rel="prev" title="docplex.mp.quad module" href="docplex.mp.quad.html" />
    <meta name="viewport" content="width=device-width,initial-scale=1.0">

Navigation

          index

          modules |

          next |

          previous |

DOcplex.MP: Mathematical Programming Modeling for Python V2.23 documentation »

docplex.mp reference manual »

Previous topic

docplex.mp.quad module

Next topic

docplex.mp.relaxer module

Quick search

    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

docplex.mp.relax_linear module¶

class docplex.mp.relax_linear.LinearRelaxer[source]¶

Bases: object

This class returns a linear relaxation for a MIP model.

linear_relaxation(mdl, return_partial=False, **kwargs)[source]¶

Returns a continuous relaxation of the model.

Variable types are set to continuous (note that semi-xxx variables have their LB set to zero)

Some constructs are not relaxable, for example, piecewise-linear expressions, SOS sets,
logical constraints…
When a model contains at least one of these non-relaxable constructs, a message is printed
and this method returns None.

By default, model parameters are not copied. If you want to copy them, pass the
keyword argument copy_parameters=True

<col class="field-name" />
<col class="field-body" />

Parameters:

mdl – the initial model

return_partial – if True, returns the partially relaxed model anyway, default is False,
if an unrelaxable item is encountered, None is returned

Returns:
a new model with continuous relaxation, if possible, else None.

Navigation

          index

          modules |

          next |

          previous |

DOcplex.MP: Mathematical Programming Modeling for Python V2.23 documentation »

docplex.mp reference manual »

        © Copyright 2016-2021, IBM®.


text:
package kr.lul.kobalttown.document.web.controller;

import kr.lul.common.util.TimeProvider;
import kr.lul.kobalttown.account.domain.Account;
import kr.lul.kobalttown.account.dto.AccountSimpleDto;
import kr.lul.kobalttown.account.test.AccountTestTool;
import kr.lul.kobalttown.document.domain.Note;
import kr.lul.kobalttown.document.dto.AbstractNoteDto;
import kr.lul.kobalttown.document.dto.NoteDetailDto;
import kr.lul.kobalttown.document.test.NoteTestTool;
import kr.lul.kobalttown.document.web.DocumentWebTestConfiguration;
import kr.lul.kobalttown.document.web.controller.request.CreateNoteReq;
import kr.lul.kobalttown.page.note.NoteMvc.C;
import kr.lul.kobalttown.page.note.NoteMvc.M;
import kr.lul.kobalttown.page.note.NoteMvc.V;
import kr.lul.support.spring.security.userdetails.User;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.ui.ExtendedModelMap;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.MapBindingResult;

import java.time.Instant;
import java.util.HashMap;
import java.util.List;

import static java.util.concurrent.ThreadLocalRandom.current;
import static org.apache.commons.lang3.RandomStringUtils.random;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.slf4j.LoggerFactory.getLogger;

/**
 * @author justburrow
 * @since 2020/03/08
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = DocumentWebTestConfiguration.class)
public class NoteControllerTest {
  protected static final Logger log = getLogger(NoteControllerTest.class);

  @Autowired
  private NoteController controller;

  @Autowired
  private NoteTestTool tool;
  @Autowired
  private AccountTestTool accountTestTool;
  @Autowired
  private TimeProvider timeProvider;

  private Instant before;

  @Before
  public void setUp() throws Exception {
    this.before = this.timeProvider.now();
    log.info("SETUP - before={}", this.before);
  }

  @Test
  public void test_createForm_with_null_user() throws Exception {
    assertThatThrownBy(() -> this.controller.createForm(null, new ExtendedModelMap()))
        .isInstanceOf(IllegalArgumentException.class)
        .hasMessage("user is null.");
  }

  @Test
  public void test_createForm_with_null_model() throws Exception {
    // GIVEN
    final User user = new User(1L, "testuser", "password", List.of(new SimpleGrantedAuthority("ROLE_USER")));

    // WHEN & THEN
    assertThatThrownBy(() -> this.controller.createForm(user, null))
        .isInstanceOf(IllegalArgumentException.class)
        .hasMessage("model is null.");
  }

  @Test
  public void test_createForm() throws Exception {
    // GIVEN
    final Account account = this.accountTestTool.account();
    log.info("GIVEN - account={}", account);
    final User user = new User(account.getId(), account.getNickname(), "password",
        List.of(new SimpleGrantedAuthority("ROLE_USER")));
    log.info("GIVEN - user={}", user);
    final Model model = new ExtendedModelMap();
    log.info("GIVEN - model={}", model);

    // WHEN
    final String viewname = this.controller.createForm(user, model);
    log.info("WHEN - viewname={}", viewname);

    // THEN
    assertThat(viewname)
        .isNotNull()
        .isEqualTo(V.CREATE);
    assertThat(model.asMap())
        .hasSize(1)
        .containsKey(M.CREATE_REQ);
  }

  @Test
  public void test_create_with_null_user() throws Exception {
    assertThatThrownBy(
        () -> this.controller.create(null,
            new CreateNoteReq(), new MapBindingResult(new HashMap<>(), M.CREATE_REQ),
            new ExtendedModelMap()))
        .isInstanceOf(IllegalArgumentException.class)
        .hasMessage("user is null.");
  }

  @Test
  public void test_create_with_null_req() throws Exception {
    assertThatThrownBy(
        () -> this.controller.create(new User(1L, "testuser", "password", List.of(new SimpleGrantedAuthority("ROLE_USER"))),
            null, new MapBindingResult(new HashMap<>(), M.CREATE_REQ),
            new ExtendedModelMap()))
        .isInstanceOf(IllegalArgumentException.class)
        .hasMessage("req is null.");
  }

  @Test
  public void test_create_with_null_binding() throws Exception {
    assertThatThrownBy(
        () -> this.controller.create(new User(1L, "testuser", "password", List.of(new SimpleGrantedAuthority("ROLE_USER"))),
            new CreateNoteReq("test body"), null,
            new ExtendedModelMap()))
        .isInstanceOf(IllegalArgumentException.class)
        .hasMessage("binding is null.");
  }

  @Test
  public void test_create_with_null_model() throws Exception {
    assertThatThrownBy(
        () -> this.controller.create(new User(1L, "testuser", "password", List.of(new SimpleGrantedAuthority("ROLE_USER"))),
            new CreateNoteReq("test body"), new MapBindingResult(new HashMap<>(), M.CREATE_REQ),
            null))
        .isInstanceOf(IllegalArgumentException.class)
        .hasMessage("model is null.");
  }

  @Test
  public void test_create() throws Exception {
    // GIVEN
    final Account account = this.accountTestTool.account();
    log.info("GIVEN - account={}", account);
    final User user = new User(account.getId(), account.getNickname(), "password",
        List.of(new SimpleGrantedAuthority("ROLE_USER")));
    log.info("GIVEN - user={}", user);
    final String body = "test note #" + random(current().nextInt(10, 20));
    log.info("GIVEN - body={}", body);

    final CreateNoteReq req = new CreateNoteReq(body);
    log.info("GIVEN - req={}", req);
    final BindingResult binding = new MapBindingResult(new HashMap<>(), M.CREATE_REQ);
    log.info("GIVEN - binding={}", binding);
    final Model model = new ExtendedModelMap();
    log.info("GIVEN - model={}", model);

    // WHEN
    final String viewname = this.controller.create(user, req, binding, model);
    log.info("WHEN - viewname={}", viewname);

    // THEN
    assertThat(viewname)
        .isNotNull()
        .startsWith("redirect:" + C.GROUP);
    assertThat(binding)
        .extracting(BindingResult::hasErrors)
        .isEqualTo(false);
    assertThat(model.asMap())
        .isEmpty();
  }

  @Test
  public void test_detail() throws Exception {
    // GIVEN
    final Note note = this.tool.note();
    final Account author = note.getAuthor();
    log.info("GIVEN - note={}", note);

    final Account account = this.accountTestTool.account();
    log.info("GIVEN - account={}", account);
    final User user = new User(account.getId(), account.getNickname(), "password",
        List.of(new SimpleGrantedAuthority("ROLE_USER")));
    log.info("GIVEN - user={}", user);
    final Model model = new ExtendedModelMap();

    // WHEN
    final String template = this.controller.detail(user, note.getId(), model);
    log.info("WHEN - template={}", template);

    // THEN
    assertThat(template)
        .isNotNull()
        .isEqualTo(V.DETAIL);
    assertThat(model.asMap())
        .isNotEmpty();
    assertThat((NoteDetailDto) model.getAttribute(M.NOTE))
        .isNotNull()
        .extracting(NoteDetailDto::getId, NoteDetailDto::getVersion, AbstractNoteDto::getAuthor, AbstractNoteDto::getBody,
            NoteDetailDto::getCreatedAt, NoteDetailDto::getUpdatedAt)
        .containsSequence(note.getId(), 0, new AccountSimpleDto(author.getId(), author.getNickname()), note.getBody(),
            this.timeProvider.zonedDateTime(note.getCreatedAt()), this.timeProvider.zonedDateTime(note.getUpdatedAt()));
  }
}


text:
import { LOGIN } from '../constants';
import { handleActions } from 'redux-actions';
const initialState = {};
export default handleActions({
  [LOGIN]: (state, action) => ({ ...state, val: action.payload }),
}, initialState);


text:
require "rails_helper"

module Renalware
  module LowClearance
    describe Profile, type: :model do
      it_behaves_like "an Accountable model"
      it :aggregate_failures do
        is_expected.to validate_presence_of(:patient)
        is_expected.to belong_to(:patient).touch(true)
        is_expected.to belong_to(:referrer)
        is_expected.to belong_to(:dialysis_plan)
        is_expected.to respond_to(:document)
        is_expected.to be_versioned
        is_expected.to have_db_index(:document)
        is_expected.to have_db_index(:patient_id)
      end
    end
  end
end


text:
import psycopg2

top_stories = (    # psql query to return the top stories
    """
    SELECT title, views
    FROM articles
    INNER JOIN
        (SELECT path, count(path) AS views
                       FROM log
                       GROUP BY log.path) AS log
    ON log.path = '/article/' || articles.slug
    ORDER BY views desc limit 3;
    """
)

def get_top_stories():
    """Return results for get_top_stories query."""
    db = psycopg2.connect("dbname=news")
    c = db.cursor()
    c.execute(top_stories)
    story_rows = c.fetchall()
    print("The 3 Most Popular Stories Are:")
    for title, views in story_rows:
        print("\"{}\" -- {} views".format(title, views))
    db.close

top_authors = (    # psql query to return the top authors
    """
    SELECT titlename.name, count(path) AS views
    FROM log,
        (SELECT name, slug
                       FROM authors
                       JOIN articles
                       ON authors.id = articles.author) AS titlename
    WHERE log.path = '/article/' ||titlename.slug
    GROUP BY titlename.name
    ORDER BY views desc;
    """
)

def get_top_authors():
    """Return results from get_top_authors query."""
    db = psycopg2.connect("dbname=news")
    c = db.cursor()
    c.execute(top_authors)
    author_rows = c.fetchall()
    print("The Most Popular Authors Are:")
    for name, views in author_rows:
        print("\"{}\" -- {} views".format(name, views))
    db.close()

most_errors = (    # psql query to return the days with most errors
    """
    SELECT date, percent_errors
    FROM (SELECT errors.day AS date, (cast(errors.total_errors AS float)
            / cast(views.total_views AS float) * 100) AS percent_errors
            FROM errors
            JOIN views
            ON errors.day = views.day) AS most_errors
    GROUP BY most_errors.date, most_errors.percent_errors
    HAVING SUM(percent_errors) >= 1.0
    ORDER BY percent_errors desc;
    """
)

def get_days_errors_over_1_percent():
    """Return the results for the get_days_errors_over_1_percent query."""
    db = psycopg2.connect("dbname=news")
    c = db.cursor()
    c.execute(most_errors)
    errors_rows = c.fetchall()
    print("The Day with the Most Errors Was:")
    for row in errors_rows:
        print('{0:%B %d, %Y} -- {1:.2f}% errors'.format(row[0], row[1]))
    db.close()

if __name__ == '__main__':  # Ensures each function runs only when called upon
    get_top_stories()
    print("")
    get_top_authors()
    print("")
    get_days_errors_over_1_percent()
    print("")


text:
package org.apache.myfaces.config.annotation;

import javax.naming.NamingException;
import javax.naming.Context;
import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;
import org.apache.myfaces.shared.util.ClassUtils;

// TODO @Resources
public class ResourceAnnotationLifecycleProvider extends NoInjectionAnnotationLifecycleProvider
{
    /**
     * Cache the Method instances per ClassLoader using the Class-Name.
     * NOTE that we do it this way, because the only other valid way in order to support a shared
     * classloader scenario would be to use a WeakHashMap<Class<?>, Method[]>, but this
     * creates a cyclic reference between the key and the value of the WeakHashMap which will
     * most certainly cause a memory leak! Furthermore we can manually cleanup the Map when
     * the webapp is undeployed just by removing the Map for the current ClassLoader.
     */
    private volatile static WeakHashMap<ClassLoader, Map<Class,Field[]> > declaredFieldBeans =
            new WeakHashMap<ClassLoader, Map<Class, Field[]>>();

    protected Context context;
    private static final String JAVA_COMP_ENV = "java:comp/env/";

    public ResourceAnnotationLifecycleProvider(Context context)
    {
        this.context = context;
    }

    private static Map<Class,Field[]> getDeclaredFieldBeansMap()
    {
        ClassLoader cl = ClassUtils.getContextClassLoader();

        Map<Class,Field[]> metadata = (Map<Class,Field[]>)
                declaredFieldBeans.get(cl);

        if (metadata == null)
        {
            // Ensure thread-safe put over _metadata, and only create one map
            // per classloader to hold metadata.
            synchronized (declaredFieldBeans)
            {
                metadata = createDeclaredFieldBeansMap(cl, metadata);
            }
        }

        return metadata;
    }

    private static Map<Class,Field[]> createDeclaredFieldBeansMap(
            ClassLoader cl, Map<Class,Field[]> metadata)
    {
        metadata = (Map<Class,Field[]>) declaredFieldBeans.get(cl);
        if (metadata == null)
        {
            metadata = new HashMap<Class,Field[]>();
            declaredFieldBeans.put(cl, metadata);
        }
        return metadata;
    }

    /**
     * Inject resources in specified instance.
     */
    @Override
    protected void processAnnotations(Object instance)
            throws IllegalAccessException, InvocationTargetException, NamingException
    {

        if (context == null)
        {
            // No resource injection
            return;
        }

        checkAnnotation(instance.getClass(), instance);

        /*
         * May be only check non private fields and methods
         * for @Resource (JSR 250), if used all superclasses MUST be examined
         * to discover all uses of this annotation.
         */

        Class superclass = instance.getClass().getSuperclass();
        while (superclass != null && (!superclass.equals(Object.class)))
        {
            checkAnnotation(superclass, instance);
            superclass = superclass.getSuperclass();
        }
    }

    Field[] getDeclaredFieldBeans(Class clazz)
    {
        Map<Class,Field[]> declaredFieldBeansMap = getDeclaredFieldBeansMap();
        Field[] fields = declaredFieldBeansMap.get(clazz);
        if (fields == null)
        {
            fields = clazz.getDeclaredFields();
            synchronized(declaredFieldBeansMap)
            {
                declaredFieldBeansMap.put(clazz, fields);
            }
        }
        return fields;
    }

    private void checkAnnotation(Class<?> clazz, Object instance)
            throws NamingException, IllegalAccessException, InvocationTargetException
    {
        // Initialize fields annotations
        Field[] fields = getDeclaredFieldBeans(clazz);
        for (int i = 0; i < fields.length; i++)
        {
            Field field = fields[i];
            checkFieldAnnotation(field, instance);
        }

        // Initialize methods annotations
        Method[] methods = getDeclaredMethods(clazz);
        for (int i = 0; i < methods.length; i++)
        {
            Method method = methods[i];
            checkMethodAnnotation(method, instance);
        }
    }

    protected void checkMethodAnnotation(Method method, Object instance)
            throws NamingException, IllegalAccessException, InvocationTargetException
    {
        if (method.isAnnotationPresent(Resource.class))
        {
            Resource annotation = method.getAnnotation(Resource.class);
            lookupMethodResource(context, instance, method, annotation.name());
        }
    }

    protected void checkFieldAnnotation(Field field, Object instance)
            throws NamingException, IllegalAccessException
    {
        if (field.isAnnotationPresent(Resource.class))
        {
            Resource annotation = field.getAnnotation(Resource.class);
            lookupFieldResource(context, instance, field, annotation.name());
        }
    }

    /**
     * Inject resources in specified field.
     */
    protected static void lookupFieldResource(javax.naming.Context context,
            Object instance, Field field, String name)
            throws NamingException, IllegalAccessException
    {

        Object lookedupResource;

        if ((name != null) && (name.length() > 0))
        {
            // TODO local or global JNDI
            lookedupResource = context.lookup(JAVA_COMP_ENV + name);
        }
        else
        {
            // TODO local or global JNDI
            lookedupResource = context.lookup(JAVA_COMP_ENV + instance.getClass().getName() + "/" + field.getName());
        }

        boolean accessibility = field.isAccessible();
        field.setAccessible(true);
        field.set(instance, lookedupResource);
        field.setAccessible(accessibility);
    }

    /**
     * Inject resources in specified method.
     */
    protected static void lookupMethodResource(javax.naming.Context context,
            Object instance, Method method, String name)
            throws NamingException, IllegalAccessException, InvocationTargetException
    {

        if (!method.getName().startsWith("set")
                || method.getParameterTypes().length != 1
                || !method.getReturnType().getName().equals("void"))
        {
            throw new IllegalArgumentException("Invalid method resource injection annotation");
        }

        Object lookedupResource;

        if ((name != null) && (name.length() > 0))
        {
            // TODO local or global JNDI
            lookedupResource = context.lookup(JAVA_COMP_ENV + name);
        }
        else
        {
            // TODO local or global JNDI
            lookedupResource =
                    context.lookup(JAVA_COMP_ENV + instance.getClass().getName() + "/" + getFieldName(method));
        }

        boolean accessibility = method.isAccessible();
        method.setAccessible(true);
        method.invoke(instance, lookedupResource);
        method.setAccessible(accessibility);
    }

    /**
     * Returns the field name for the given Method.
     * E.g. setName() will be "name".
     *
     * @param setter the setter method
     * @return the field name of the given setter method
     */
    protected static String getFieldName(Method setter)
    {
        StringBuilder name = new StringBuilder(setter.getName());

        // remove 'set'
        name.delete(0, 3);

        // lowercase first char
        name.setCharAt(0, Character.toLowerCase(name.charAt(0)));

        return name.toString();
    }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;

namespace AllYourTextsUi.Commands
{
    public class CopyConversationTextFormattedCommand
    {
        public static RoutedUICommand CopyConversationTextFormatted { get; private set; }

        static CopyConversationTextFormattedCommand()
        {
            InputGestureCollection gestures = new InputGestureCollection();
            gestures.Add(new KeyGesture(Key.C, ModifierKeys.Control | ModifierKeys.Shift));

            CopyConversationTextFormatted = new RoutedUICommand("Copy Formatted", "Copy Formatted", typeof(CopyConversationTextFormattedCommand), gestures);
        }
    }
}


text:
package ca.ualberta.cs.oneclick_cookbook;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;

/**
 * Class that allows the user to sign up for our service. Talks with remote
 * server to create user.
 *
 * @author Kenneth Armstrong
 *
 */
public class SignUpActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_sign_up);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.sign_up, menu);
		return true;
	}

	/**
	 * Commits the signup of the user, based on the info they have entered.
	 */
	public void onSignUp() {
		EditText u = (EditText) findViewById(R.id.tSignUpUsername);
		EditText p = (EditText) findViewById(R.id.tSignUpPassword);
		EditText s = (EditText) findViewById(R.id.tSignUpScreenName);
		EditText e = (EditText) findViewById(R.id.tSignUpEmail);
		EditText m = (EditText) findViewById(R.id.tSignUpMobile);

		// Extract the strings from the text boxes
		String username = u.getText().toString();
		String password = p.getText().toString();
		String screenName = s.getText().toString();
		String email = e.getText().toString();
		String mobile = m.getText().toString();

		User user;
		if (!email.equals("")) {
			// If they entered an email, use that
			user = new User(username, password, screenName, email);
		} else {
			// If they didn't enter an email, check for a mobile number
			// Make sure that a valid number was entered
			Integer mobileNumber;
			try {
				mobileNumber = new Integer(mobile);
			} catch (NumberFormatException et) {
				// They didin't enter a valid number
				return;
			}
			user = new User(username, password, screenName, mobileNumber);
		}

		// Check to make sure that valid info was entered
		if (user.isValidInfo() != Constants.GOOD) {
			// Should probably add some message here
			return;
		}

		// TODO Add the networking stuff here

		// End the activity... Possible rather start the main screen
		finish();

	}

	/**
	 * Handles and directs the clicks for this activity.
	 *
	 * @param v
	 *            The view of te button that was clicked.
	 */
	public void clickHandler(View v) {
		switch (v.getId()) {
		case R.id.bSignUp:
			onSignUp();
			break;
		}
	}

}


text:
package org.stagemonitor.core.metrics.annotations;

import net.bytebuddy.asm.Advice;
import net.bytebuddy.description.annotation.AnnotationDescription;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.description.method.ParameterDescription;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.implementation.bytecode.assign.Assigner;

import org.stagemonitor.core.metrics.aspects.SignatureUtils;

import java.lang.annotation.Annotation;

public abstract class MetricAnnotationSignatureDynamicValue<T extends Annotation> implements Advice.OffsetMapping.Factory<T> {

	public String getRequestName(MethodDescription instrumentedMethod) {
		final NamingParameters namingParameters = getNamingParameters(instrumentedMethod);
		return SignatureUtils.getSignature(instrumentedMethod.getDeclaringType().getTypeName(), instrumentedMethod.getName(),
				namingParameters.getNameFromAnnotation(), namingParameters.isAbsolute());
	}

	@Override
	public Advice.OffsetMapping make(ParameterDescription.InDefinedShape target, AnnotationDescription.Loadable<T> annotation, AdviceType adviceType) {
		return new Advice.OffsetMapping() {
			@Override
			public Target resolve(TypeDescription instrumentedType, MethodDescription instrumentedMethod, Assigner assigner, Advice.ArgumentHandler argumentHandler, Sort sort) {
				return Advice.OffsetMapping.Target.ForStackManipulation.of(getRequestName(instrumentedMethod));
			}
		};
	}

	protected abstract NamingParameters getNamingParameters(MethodDescription instrumentedMethod);

	protected static class NamingParameters {
		private String nameFromAnnotation;
		private boolean absolute;

		public NamingParameters(String nameFromAnnotation, boolean absolute) {
			this.nameFromAnnotation = nameFromAnnotation;
			this.absolute = absolute;
		}

		public String getNameFromAnnotation() {
			return nameFromAnnotation;
		}

		public boolean isAbsolute() {
			return absolute;
		}
	}
}


text:
require "google/cloud/asset/v1"

##
# Example demonstrating basic usage of
# Google::Cloud::Asset::V1::AssetService::Client#update_feed
#
def update_feed
  # Create a client object. The client can be reused for multiple calls.
  client = Google::Cloud::Asset::V1::AssetService::Client.new

  # Create a request. To set request fields, pass in keyword arguments.
  request = Google::Cloud::Asset::V1::UpdateFeedRequest.new

  # Call the update_feed method.
  result = client.update_feed request

  # The returned object is of type Google::Cloud::Asset::V1::Feed.
  p result
end
# [END cloudasset_v1_generated_AssetService_UpdateFeed_sync]


text:
#ifndef SQLPP_FIELD_H
#define SQLPP_FIELD_H

#include <sqlpp11/multi_column.h>

namespace sqlpp
{
	namespace vendor
	{
		template<typename NameType, typename ValueType>
			struct field_t
			{
				using _name_t = NameType;
				using _value_type = ValueType;
			};

		template<typename AliasProvider, typename FieldTuple>
			struct multi_field_t
			{
			};

		namespace detail
		{
			template<typename NamedExpr>
				struct make_field_t_impl
				{
					using type = field_t<typename NamedExpr::_name_t, typename NamedExpr::_value_type::_base_value_type>;
				};

			template<typename AliasProvider, typename... NamedExpr>
				struct make_field_t_impl<multi_column_t<AliasProvider, std::tuple<NamedExpr...>>>
				{
					using type = multi_field_t<AliasProvider, std::tuple<typename make_field_t_impl<NamedExpr>::type...>>;
				};
		}

		template<typename NamedExpr>
			using make_field_t = typename detail::make_field_t_impl<NamedExpr>::type;
	}

}

#endif


text:
//
//  UIViewController+OKCategory
//
//  Copyright © 2016年 OK Inc. All rights reserved.
//

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

typedef void (^OKBackButtonHandler)(UIViewController *vc);

@interface UIViewController (OKCategory)

/// UIViewController 是否可见
- (BOOL)ok_isVisible;

/**
 *  获取当前显示的ViewController
 */
+ (nullable UIViewController *)ok_fetchCurrentViewController;

/**
 *  视图层级
 *
 *  @return 视图层级字符串
 */
- (NSString *)ok_recursiveDescription;

- (void)ok_backButtonTouched:(OKBackButtonHandler)backButtonHandler;

- (void)ok_addChildViewController:(UIViewController *)controller atFrame:(CGRect)frame;
- (void)ok_addChildViewController:(UIViewController *)controller inView:(UIView *)view atFrame:(CGRect)frame;

- (void)ok_removeChildViewController:(UIViewController *)controller;

- (void)ok_dismissToRootViewControllerAnimated:(BOOL)flag;

@end

NS_ASSUME_NONNULL_END


text:
import React from 'react';
import { ScrollView } from 'react-native';
import styles from './styles';

const Slides = ({ children }) => (
  <ScrollView
    horizontal
    indicatorStyle='white'
    pagingEnabled
    style={styles.container}
  >
    {children}
  </ScrollView>
);

export { Slides };


text:
package carton

import (
	"strings"
	"time"

	"github.com/megamsys/vertice/carton/bind"
	"github.com/megamsys/vertice/db"
	"github.com/megamsys/vertice/provision"
	"github.com/megamsys/vertice/repository"
	"gopkg.in/yaml.v2"
)

const (
	DOMAIN        = "domain"
	PUBLICIPV4    = "publicipv4"
	PRIVATEIPV4   = "privateipv4"
	COMPBUCKET    = "components"
	IMAGE_VERSION = "version"
	ONECLICK      = "oneclick"
)

type Artifacts struct {
	Type         string         `json:"artifact_type"`
	Content      string         `json:"content"`
	Requirements bind.JsonPairs `json:"requirements"`
}

/* Repository represents a repository managed by the manager. */
type Repo struct {
	Rtype    string `json:"rtype"`
	Source   string `json:"source"`
	Oneclick string `json:"oneclick"`
	Rurl     string `json:"url"`
}

type Component struct {
	Id                string         `json:"id"`
	Name              string         `json:"name"`
	Tosca             string         `json:"tosca_type"`
	Inputs            bind.JsonPairs `json:"inputs"`
	Outputs           bind.JsonPairs `json:"outputs"`
	Envs              bind.JsonPairs `json:"envs"`
	Repo              Repo           `json:"repo"`
	Artifacts         *Artifacts     `json:"artifacts"`
	RelatedComponents []string       `json:"related_components"`
	Operations        []*Operations  `json:"operations"`
	Status            string         `json:"status"`
	CreatedAt         string         `json:"created_at"`
}

func (a *Component) String() string {
	if d, err := yaml.Marshal(a); err != nil {
		return err.Error()
	} else {
		return string(d)
	}
}

/**
**fetch the component json from riak and parse the json to struct
**/
func NewComponent(id string) (*Component, error) {
	c := &Component{Id: id}
	if err := db.Fetch(COMPBUCKET, id, c); err != nil {
		return nil, err
	}
	return c, nil
}

//make a box with the details for a provisioner.
func (c *Component) mkBox() (provision.Box, error) {
	bt := provision.Box{
		Id:         c.Id,
		Level:      provision.BoxSome,
		Name:       c.Name,
		DomainName: c.domain(),
		Envs:       c.envs(),
		Tosca:      c.Tosca,
		Commit:     "",
		Provider:   c.provider(),
		PublicIp:   c.publicIp(),
	}

	if &c.Repo != nil {
		bt.Repo = &repository.Repo{
			Type:     c.Repo.Rtype,
			Source:   c.Repo.Source,
			OneClick: c.withOneClick(),
			URL:      c.Repo.Rurl,
		}
		bt.Repo.Hook = BuildHook(c.Operations, repository.CIHOOK)
	}
	return bt, nil
}

func (c *Component) SetStatus(status provision.Status) error {
	LastStatusUpdate := time.Now().Local().Format(time.RFC822)
	m := make(map[string][]string, 2)
	m["lastsuccessstatusupdate"] = []string{LastStatusUpdate}
	m["status"] = []string{status.String()}
	c.Inputs.NukeAndSet(m) //just nuke the matching output key:

	c.Status = status.String()

	if err := db.Store(COMPBUCKET, c.Id, c); err != nil {
		return err
	}
	return nil
}

/*func (c *Component) UpdateOpsRun(opsRan upgrade.OperationsRan) error {
	mutatedOps := make([]*upgrade.Operation, 0, len(opsRan))

	for _, o := range opsRan {
		mutatedOps = append(mutatedOps, o.Raw)
	}
	c.Operations = mutatedOps

	if err := db.Store(COMPBUCKET, c.Id, c); err != nil {
		return err
	}
	return nil
}*/

func (c *Component) Delete(compid string) {
	_ = db.Delete(COMPBUCKET, compid)
}

func (c *Component) setDeployData(dd DeployData) error {
	/*c.Inputs = append(c.Inputs, bind.NewJsonPair("lastsuccessstatusupdate", ""))
	c.Inputs = append(c.Inputs, bind.NewJsonPair("status", ""))

	if err := db.Store(COMPBUCKET, c.Id, c); err != nil {
		return err
	}*/
	return nil

}

func (c *Component) domain() string {
	return c.Inputs.Match(DOMAIN)
}

func (c *Component) provider() string {
	return c.Inputs.Match(provision.PROVIDER)
}

func (c *Component) publicIp() string {
	return c.Outputs.Match(PUBLICIPV4)
}

func (c *Component) withOneClick() bool {
	return (len(strings.TrimSpace(c.Envs.Match(ONECLICK))) > 0)
}

//all the variables in the inputs shall be treated as ENV.
//we can use a filtered approach as well.
func (c *Component) envs() []bind.EnvVar {
	envs := make([]bind.EnvVar, 0, len(c.Envs))
	for _, i := range c.Envs {
		envs = append(envs, bind.EnvVar{Name: i.K, Value: i.V})
	}
	return envs
}


text:
require File.expand_path('../application', __FILE__)

# Initialize the Rails application.
Squash::Application.initialize!


text:
__author__    = "Ole Christian Weidner"
__copyright__ = "Copyright 2011-2012, Ole Christian Weidner"
__license__   = "MIT"

import bliss.saga as saga
import os
import unittest

###############################################################################
#
class ExceptionTests(unittest.TestCase):
    """
    Tests for the saga.Exception class
    """
    def setUp(self):
        pass

    def tearDown(self):
        pass

    ###########################################################################
    #
    def test_exception_properties(self):

        e1 = saga.Exception(saga.Error.NotImplemented, "Not Implemented!")

        try:
            e1.message = "set"
            self.fail("message should be read-only")

            e1.error = "set"
            self.fail("error should be read-only")

            e1.traceback = "set"
            self.fail("traceback should be read-only")

        except Exception, e:
            pass

        if e1.message != "Not Implemented!":
            self.fail("message contains the wrong string!")

        if e1.error != saga.Error.NotImplemented:
            self.fail("error contains the wrong type!")

        if e1.traceback != "(No Traceback)":
            self.fail("There shouldn't be a traceback!")

    ###########################################################################
    #
    def test_exception_string_rep(self):

        e1 = saga.Exception(saga.Error.NotImplemented, "Not Implemented")

        if str(e1) != "SAGA Exception (NotImplemented): Not Implemented":
            self.fail("Something's wrong with the string representation")

    ###########################################################################
    #
    def test_exception_string_rep(self):

        e1 = saga.Exception(saga.Error.NotImplemented, "Not Implemented")

        if unicode(e1) != unicode("SAGA Exception (NotImplemented): Not Implemented"):
            self.fail("Something's wrong with the string representation")

    ###########################################################################
    #
    def test_exception_traceback(self):

        try:
            saga.job.Service("notgonnawork!")
        except saga.Exception, e:
            if e.traceback == "(No Traceback)":
                self.fail("There should be a traceback!")
            else:
                pass


text:
require 'helper'

describe Plucky::OptionsHash do
  describe "#initialize_copy" do
    before do
      @original = described_class.new(:fields => {:name => true}, :sort => :name, :limit => 10)
      @cloned   = @original.clone
    end

    it "duplicates source hash" do
      @cloned.source.should_not equal(@original.source)
    end

    it "clones duplicable? values" do
      @cloned[:fields].should_not equal(@original[:fields])
      @cloned[:sort].should_not equal(@original[:sort])
    end
  end

  describe "#fields?" do
    it "returns true if fields have been selected" do
      described_class.new(:fields => :name).fields?.should be(true)
    end

    it "returns false if no fields have been selected" do
      described_class.new.fields?.should be(false)
    end
  end

  describe "#merge" do
    before do
      @o1 = described_class.new(:skip => 5, :sort => :name)
      @o2 = described_class.new(:limit => 10, :skip => 15)
      @merged = @o1.merge(@o2)
    end

    it "overrides options in first with options in second" do
      @merged.should == described_class.new(:limit => 10, :skip => 15, :sort => :name)
    end

    it "returns new instance and not change either of the merged" do
      @o1[:skip].should == 5
      @o2[:sort].should be_nil
      @merged.should_not equal(@o1)
      @merged.should_not equal(@o2)
    end
  end

  describe "#merge!" do
    before do
      @o1 = described_class.new(:skip => 5, :sort => :name)
      @o2 = described_class.new(:limit => 10, :skip => 15)
      @merged = @o1.merge!(@o2)
    end

    it "overrides options in first with options in second" do
      @merged.should == described_class.new(:limit => 10, :skip => 15, :sort => :name)
    end

    it "just updates the first" do
      @merged.should equal(@o1)
    end
  end
end


text:
namespace Atomiv.Template.Web.UI
{
    public class ApiClientOptions
    {
        public string Url { get; set; }
    }
}


text:
from flask import Blueprint, request, render_template, flash, g, session, redirect, url_for

# Importar clave / ayudantes de encriptacion
from werkzeug import check_password_hash, generate_password_hash

# Importar el objeto de base de datos desde el modulo principal de la aplicacion
from app import db

# Importar modulo de formulario
#from app.mod_curia.forms import LoginForm

# Importar modulo de usuario (i.e. User)
#from app.mod_curia.models import User

# Definir el blueprint: 'Curia', establecer el prefijo de la url: app.url/curia
mod_curia = Blueprint('curia', __name__, url_prefix='/curia')

# Establecer las rutas y metodos aceptados

### Rutas del menu principal

@mod_curia.route('/inicio/', methods=['GET', 'POST'])
def inicio():
    return render_template("curia/inicio.html")

@mod_curia.route('/obispos/', methods=['GET', 'POST'])
def obispos():
    return render_template("curia/obispos.html")

@mod_curia.route('/noticias/', methods=['GET', 'POST'])
def noticias():
    return render_template("curia/noticias.html")

@mod_curia.route('/contacto/', methods=['GET', 'POST'])
def contacto():
    return render_template("curia/contacto.html")

### Rutas del menu de arquidocesis

@mod_curia.route('/arquidiocesis/catedral/', methods=['GET', 'POST'])
def catedral():
    return render_template("/curia/arquidiocesis/catedral.html")

@mod_curia.route('/arquidiocesis/santuario-diocesano/', methods=['GET', 'POST'])
def santuario_dio():
    return render_template("/curia/arquidiocesis/santuario-diocesano.html")

@mod_curia.route('/carquidiocesis/seminario-diocesano/', methods=['GET', 'POST'])
def seminario_diocesano():
    return render_template("/curia/arquidiocesis/seminarios-diocesanos.html")

@mod_curia.route('/arquidiocesis/vicario-pastoral/', methods=['GET', 'POST'])
def vicario_pastoral():
    return render_template("/curia/arquidiocesis/vicario-pastoral.html")

### Rutas del menu de curia arzobispal

@mod_curia.route('/curia-arzobispal/consejo-gobierno/', methods=['GET', 'POST'])
def consejo_gobierno():
    return render_template("/curia/curia-arzobispal/consejo-gob.html")

@mod_curia.route('/curia-arzobispal/colegio-consultores/', methods=['GET', 'POST'])
def colegio_consultores():
    return render_template("/curia/curia-arzobispal/colegio-consul.html")

@mod_curia.route('/curia-arzobispal/consejo-pastoral/', methods=['GET', 'POST'])
def consejo_pastoral():
    return render_template("/curia/curia-arzobispal/consejo-pas.html")

@mod_curia.route('/curia-arzobispal/tribunal-ecle/', methods=['GET', 'POST'])
def tribunal_ecle():
    return render_template("/curia/curia-arzobispal/tribunal-ecle.html")

@mod_curia.route('/curia-arzobispal/consejo-presbiteral/', methods=['GET', 'POST'])
def consejo_presbiteral():
    return render_template("/curia/curia-arzobispal/consejo-presbiteral.html")

### Parte de parroquias del menu parroquias

@mod_curia.route('/parroquias/zona-central/', methods=['GET', 'POST'])
def zona_c():
    return render_template("curia/parroquias/zona-central.html")

@mod_curia.route('/parroquias/zona-oriental/', methods=['GET', 'POST'])
def zona_or():
    return render_template("curia/parroquias/zona-oriental.html")

@mod_curia.route('/parroquias/zona-occidental/', methods=['GET', 'POST'])
def zona_oc():
    return render_template("curia/parroquias/zona-occidental.html")

@mod_curia.route('/parroquias/masaya/', methods=['GET', 'POST'])
def masaya():
    return render_template("/curia/parroquias/masaya.html")

@mod_curia.route('/parroquias/carazo/', methods=['GET', 'POST'])
def carazo():
    return render_template("curia/parroquias/carazo.html")


text: extern int ExtensionA;


text:
<?php
namespace chervand\yii2\oauth2\server\components\AuthorizationValidators;

class BearerTokenValidator extends \League\OAuth2\Server\AuthorizationValidators\BearerTokenValidator
{
}


text:
class Goal;
class MissionSite;

class Mission
{
public:
	Mission(MissionSite& mission_site);

	const std::string& getId() const { return id_; }
	void addGoal(Goal& goal);
	const std::vector<Goal*>& getGoals() const { return goals_; }
	void getStrageticPoints(std::vector<glm::vec3>& points) const;
private:
	static int global_mission_id_;
	std::string id_;
	MissionSite* mission_site_;

	std::vector<Goal*> goals_;
};

#endif


text:
package org.clinical3po.backendservices.rule.compiler;

import java.util.HashMap;
import java.util.Map;

import org.clinical3po.backendservices.rule.Rule;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

/**
 * Test case for CharSequenceCompiler
 *
 * @author w.ding
 */
public class CharSequenceCompilerTest extends TestCase {

	public CharSequenceCompilerTest(String name) {
		super(name);
	}

	public static Test suite() {
		TestSuite suite = new TestSuite();
		suite.addTestSuite(CharSequenceCompilerTest.class);
		return suite;
	}

	public void setUp() throws Exception {
		super.setUp();
	}

	public void tearDown() throws Exception {
		super.tearDown();
	}

	public void testF1() throws Exception {
		boolean result = true;
        assertTrue(result);
	}

}


text:
<?php
session_start();
include_once 'connect/conn.php';

if(isset($_SESSION['user'])!="")
{
	header("Location: dashboard/");
}

if(isset($_POST['btn-login']))
{
	$user = $_POST['user'];
	$upass = $_POST['pass'];
	$res= $pdo->query("SELECT * FROM user_admin WHERE username='$user'");
	$row= $res->fetch(PDO::FETCH_ASSOC);

	if($row['password']==$upass)
	{
		$_SESSION['user'] = $row['id_admin'];
		header("Location: dashboard/");
	}
	else
	{
		?>

        <?php
	}

}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

	<title>Admin Panel - SINO</title>
	<link rel="stylesheet" type="text/css" href="assets/css/custom.css" />
	<link rel="stylesheet" type="text/css" href="assets/css/bootstrap.css" />
	<link href='https://fonts.googleapis.com/css?family=Montserrat' rel='stylesheet' type='text/css'/>
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css"/>
	<link rel="icon" type="image/x-icon" href="assets/images/favicon.png"/>
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">

		<form class="form-inline space-top" action="index.php" method="post" name="postform">

						<input class="form-control" type="text" name="user" placeholder="Username" required>

						<input class="form-control" type="password" name="pass" placeholder="Password" type="password" required>

			<button class="btn btn-primary space-top" button type="submit" style="width:100%" name="btn-login">Login</button>
		</form>

		2015. Dibuat oleh IT Club SMAN 1 Cibadak


text:
@interface FSHistoryViewController : FSBaseViewController

@end


text:
package org.phenoscape.obd.query;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public abstract class GeneFaceter extends Faceter {

    private static final List<String> rootEntities = new ArrayList<String>();
    static {
        rootEntities.add("GO:0008150"); // biological process
        rootEntities.add("GO:0005575"); // cellular component
        rootEntities.add("GO:0003674"); // molecular function
    }

    public GeneFaceter(PhenoscapeDataStore dataStore, int minimum, int maximum) {
        super(dataStore, minimum, maximum);
    }

    @Override
    protected List<String> getChildren(String focalTermUID) throws SQLException {
        if (focalTermUID == null) {
            return rootEntities;
        } else {
            return this.getDataStore().getGeneFacetChildrenUIDs(focalTermUID);
        }
    }

}


text:
<?php

require_once __DIR__ . "/../../src/Kafka/Kafka.php";

$partitioner = new \Kafka\Partitioner();

//test random partitioning
$result = array();
for ($i=0; $i<10; $i++) {
    $result[$partitioner->partition(null, 10)] = true;
}
assert(count($result)>1);

//test module partitioning
assert($partitioner->partition(0, 1) === 0 );
assert($partitioner->partition(1, 1) === 0 );
assert($partitioner->partition(2, 1) === 0 );
assert($partitioner->partition(0, 2) === 0 );
assert($partitioner->partition(1, 2) === 1 );
assert($partitioner->partition(2, 2) === 0 );
assert($partitioner->partition(0, 3) === 0 );
assert($partitioner->partition(1, 3) === 1 );
assert($partitioner->partition(2, 3) === 2 );
assert($partitioner->partition(3, 3) === 0 );
assert($partitioner->partition(4, 3) === 1 );

//test default partitioner non-integer key exceptions
try {
    $partitioner->partition("StringKey", 10);
    throw new Exception("Expected \Kafka\Exception with invalid partitioner key type.");
} catch (\Kafka\Exception $e) {
    assert($e->getMessage() === "Default Kafka Partitioner only accepts integer keys" );
}

//test uuid partitioner uniformity of distribution
class TestUuidPartitioner extends \Kafka\Partitioner
{
    public function partition($uuid, $numPartitions)
    {
        $hex = str_replace("-", "", $uuid);
        return abs(crc32($hex)) % $numPartitions;
    }
}
$uuids = gzopen(__DIR__ . "/../uuid10000.csv.gz", "r");
$parts = array(0,0,0);
$partitioner = new TestUuidPartitioner();
while ($uuid = gzgets($uuids)) {
    if ($uuid = trim($uuid)) {
        $i = $partitioner->partition($uuid, count($parts));
        $parts[$i] ++;
    }
}
gzclose($uuids);

assert($parts === array(3228, 3330, 3442) || $parts === array(3321, 3237, 3442)); //32bit && 64bit
$sum = array_sum($parts);
$avg = $sum / count($parts);
$var = array_reduce($parts, function(&$variance, $item) use ($avg) { return $variance += pow($avg -  $item, 2); }) / count($parts);
$std = sqrt($var);
$err = round(100 * $std / $sum, 1);
//echo " AVG = $avg, STD = $std, ERR = % $err ";
assert($sum === 10000);
assert($err <= 1);


text:
package com.test.yahoo.weather;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class ItemDto {

	private int id;

	private String name;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}


text:
class SubmissionsJob < ActiveJob::Base
  queue_as MarkusConfigurator.markus_job_collect_submissions_queue_name

  before_enqueue do |_job|
    job_messenger = JobMessenger.create(job_id: job_id, status: :queued)
    PopulateCache.populate_for_job(job_messenger, job_id)
  end

  def perform(groupings, options = {})
    return if groupings.empty?

    m_logger = MarkusLogger.instance
    assignment = groupings.first.assignment

    begin
      job_messenger = JobMessenger.where(job_id: job_id).first
      unless job_messenger.nil?
        job_messenger.update(status: :running)
        PopulateCache.populate_for_job(job_messenger, job_id)
      end

      m_logger.log('Submission collection process established database' +
                   ' connection successfully')

      groupings.each do |grouping|
        m_logger.log("Now collecting: #{assignment.short_identifier} for grouping: " +
                     "#{grouping.id}")
        if options[:revision_number].nil?
          time = assignment.submission_rule.calculate_collection_time.localtime
          new_submission = Submission.create_by_timestamp(grouping, time)
        else
          new_submission = Submission.create_by_revision_number(grouping, options[:revision_number])
        end

        if assignment.submission_rule.is_a? GracePeriodSubmissionRule
          # Return any grace credits previously deducted for this grouping.
          assignment.submission_rule.remove_deductions(grouping)
        end

        if options[:apply_late_penalty].nil? || options[:apply_late_penalty]
          new_submission = assignment.submission_rule.apply_submission_rule(
            new_submission)
        end

        unless grouping.error_collecting
          grouping.is_collected = true
        end

        grouping.save
      end
      m_logger.log('Submission collection process done')
    rescue => e
      Rails.logger.error e.message
      unless job_messenger.nil?
        job_messenger.update(status: :failed, message: e.message)
        PopulateCache.populate_for_job(job_messenger, job_id)
      end
      raise e
    end
    unless job_messenger.nil?
      job_messenger.update(status: :succeeded)
      PopulateCache.populate_for_job(job_messenger, job_id)
    end
  end
end


text:
<?php

namespace WebModule\Pragmatik\Crud\Server\Ascp\ModeHandler\AutoAdmin\RowActionHandler;

use Bee\Component\Log\SuperLogger\SuperLogger;

/**
 * BaseRowActionHandler
 * @author Lingtalfi
 * 2015-02-10
 *
 */
abstract class BaseRowActionHandler implements RowActionHandlerInterface
{

    protected function missingParam($key, array &$errors)
    {
        $errors[] = sprintf("Missing param: %s", $key);
    }

    protected function log($id, $msg, array &$errors=null)
    {
        $cName = get_called_class();
        $p = explode('\\', $cName);
        $cName = array_pop($p);
        $cName = str_replace('RowActionHandler', '', $cName);

        $errors[] = "An error has occurred, please check the application logs";
        SuperLogger::getInst()->log("Pragmatik.Crud.Server.ModeHandler.AutoAdmin.RowActionHandler." . $cName . '.' . $id, $msg);
    }

}


text:
This module has been tested with
linux: CENTOS7 (3.10.0-229.11.1.el7.x86_64)

Note: actor framework version should be the same at both sides (bro and osquery side)

```singlequerysubscription.bro ``` and ```multiplequerysubscription.bro``` are the sample script files
which are in https://github.com/sami2316/osquery directory.

-------------------------------------------------------
###Step 1: Follow Osquery Extension Guidelines###
-------------------------------------------------------
We have developed osquery extension which will enable bro users to subscribe to
(single or group) SQL queries remotely and then get the queries updates till the
broker connection is alive. Once the SQL queries are received form bro then
extension will send an initial dump if the inidump flag is set to true;
otherwise, it will only monitor updates of events and send them to bro.

Broker is a communication library which is used as a communication module
between osquery extension and bro IDS.

####1.1 Files Structure:####
#####1.1.1 Following files have been added into the osquery directory:#####
*	```osquery/osquery/main/BrokerQueryManager.cpp```
*	```osquery/osquery/main/BrokerQueryManager.h```
*	```osquery/osquery/main/BrokerConnectionManager.cpp```
*	```osquery/osquery/main/BrokerConnectionManager.h```
*	```osquery/osquery/main/BrokerQueryManagerPlugin.cpp```
*	```osquery/osquery/main/BrokerQueryManagerPlugin.h```
*	```osquery/osquery/main/utility.cpp```
*	```osquery/osquery/main/utility.h```
*	```osquery/osquery/main/bro_osquery.cpp```

#####1.1.2 Following files have been updated into the osquery directory:#####
*	osquery/osquery/CMakeLists.txt

####1.2 Installation Steps: ####
*	```Install actor framework from github```
*	```git clone --recursive https://github.com/bro/broker```
*	```cd broker && ./configure && make && make install```
*	```git clone https://github.com/sami2316/osquery```
*	```cd osquery && make deps```
*	```make```
*	```make install```

####1.3 Application usage guide:####
*	copy ```broker.ini``` in ```/var/osquery/```
*	``` cp -rf osquery/build/centos7/osquery/BrokerQueryManagerExtension.ext /usr/lib/osquery/extensions/ ```
*	create ```/etc/Osquery/extensions.load``` with following content
	``` /usr/lib/osquery/extensions/BrokerQueryManagerExtension.ext ```
*	```osqueryd --extensions_autoload=/etc/osquery/extensions.load ```

-------------------------------------------------
###Step 2: Follow Bro Extension Guideline###
-------------------------------------------------

We have added osquery query subscription module with a broker functionality in
bro IDS. This module is about subscribing SQL queries from bro (master) to
osquery hosts and then receiving updates of subscribed events.
Default subscription behavior is for update events only but you can request an
initial dump by setting inidump
flag to true during the subscription process.

This module enables following modes of connections and monitoring:
*  A master to a single remote host monitoring with a single query subscription
*  A master to a single remote host monitoring with multiple queries subscription
*  A master to a remote group of hosts monitoring with a single query subscription
*  A master to a remote group of hosts monitoring with multiple queries subscription

####2.1 Files Structure:####
#####2.1.1 Following files have been added into the bro directory:#####
*	```bro/src/broker/QueryManager.h```
*	```bro/src/broker/QueryManager.cpp```
*	```bro/src/broker/querying .bif```

#####2.1.2 Following files have been updated into the bro directory:#####
*	```bro/scripts/base/framework/broker/main.bro```
*	```bro/src/broker/Manager.h```
*	```bro/src/main.cc```
*	```bro/src/broker/CMakeLists.txt```

####2.2 Installation steps:####
*	install actor-framework from github
*	```git clone --recursive https://github.com/sami2316/bro```
*	```./configure```
*	```make```
*	```make install```

Note: actor framework version should be the same at both sides (bro and
       osquery side)

----------------------------------------------
###Step 3: Start Using Monitoring Application###
----------------------------------------------

####3.1 Scenario 1: A master to a single remote host monitoring with a single query subscription####

First you need to run osqueryd on both hosts. Then at bro side write the
following script to subscribe to a single query. An example script, extracted
from singlequerysubscription.bro, to monitor usb_devices is given below:

```
module osquery;

const broker_port: port = 9999/tcp &redef;
redef exit_only_after_terminate = T;
redef osquery::endpoint_name = "Printer";

global added_usb_devices: event(host: string, usb_address: count, vendor: string, model: string);

event bro_init()
{
	##enable broker communication
	osquery::enable();
	##subscribe to events
	osquery::subscribe_to_events("/bro/event/");
	##connect with the osquery host at IP
	osquery::connect("192.168.1.90",broker_port, 2sec);
}

##if the connection is established then connection_extablished event will be trigered.
event BrokerComm::outgoing_connection_established(peer_address: string, peer_port: port, peer_name: string)
{
	print "BrokerComm::outgoing_connection_establisted", 	peer_address, peer_port, peer_name;

        ##if we are interested in inserted usb_devices then write event name as "added_usb_devices"
	osquery::subscribe("osquery::added_usb_devices","SELECT usb_address,vendor,model FROM usb_devices");
	##if you want an initial dump for the requrest query then set inidumpflag to True
	##osquery::subscribe("osquery::added_usb_devices","SELECT usb_address,vendor,model FROM usb_devices",T);

}

event BrokerComm::incoming_connection_broken(peer_name: string)
{
	print "BrokerComm::incoming_connection_broken", peer_name;
	terminate();
}

event added_usb_devices(host: string, usb_address: count, vendor: string, model: string)
{
	print "New Usb Device Added";
 	print fmt("Host = %s Usb_address = %d Vendor = %s Model = %s",host, usb_address, vendor, model);
}
```

Please refer to singlequerysubscription.bro to write scripts to monitor other events.

####3.2 Scenario 2: A master to a single remote host monitoring with multiple queries subscription####
An example script for multiple queries subscription, extracted from multiplequerysubscription.bro,
to monitor multiple OS events is given below:

```
module osquery;

const broker_port: port = 9999/tcp &redef;
redef exit_only_after_terminate = T;
redef osquery::endpoint_name = "Printer";

global added_acpi_tables: event(host: string, name: string, size: count, md5: string);
global added_usb_devices: event(host: string, usb_address: count, vendor: string, model: string);
global added_users: event(host: string, username: string, uid: count, gid: count);

global query: table[string] of string;

event bro_init()
{
	##enable broker communication
	osquery::enable();
	##subscribe to events
	osquery::subscribe_to_events("/bro/event/");
	##connect with the osquery host at IP
	osquery::connect("192.168.1.90",broker_port, 2sec);

        query["osquery::added_acpi_tables"] = "SELECT name,size,md5 FROM acpi_tables";
	query["osquery::added_usb_devices"] =  "SELECT usb_address,vendor,model FROM usb_devices";
	query["osquery::added_users"] =  "SELECT username,uid,gid FROM users";
}

##if the connection is established then connection_extablished event will be trigered.
event BrokerComm::outgoing_connection_established(peer_address: string, peer_port: port, peer_name: string)
{
	print "BrokerComm::outgoing_connection_establisted", peer_address, peer_port, peer_name;
	osquery::groupsubscribe("/bro/event/",query);
	##if you want an initial dump for the requrest query then set inidumpflag to True
	##osquery::groupsubscribe("/bro/event/",query,T);
}

event BrokerComm::incoming_connection_broken(peer_name: string)
{
	print "BrokerComm::incoming_connection_broken", peer_name;
	terminate();
}

event added_acpi_tables(host: string, name: string, size: count, md5: 	string)
{
	print "New acpi_table Entry";
	print fmt("Host = %s Table_name = %s size = %d md5 = %s",host, 	name, size, md5);
}
event added_usb_devices(host: string, usb_address: count, vendor: string, model: string)
{
	print "New Usb Device Added";
 	print fmt("Host = %s Usb_address = %d Vendor = %s Model = %s",host, usb_address, vendor, model);
}
event added_users(host: string, username: string, uid: count, gid: count)
{
	print "New User Added";
 	print fmt("Host = %s UserName = %s UID = %d GID = %d",host, username, uid, gid);
}
```
Please refer to multiplequerysubscription.bro to have a look at the scripts written to monitor other
events.

####3.3 Scenario 3: A master to a remote group of hosts monitoring with a single query subscription####
Make sure the broker.ini at each osquery host in a group has the same broker_topic. In our example, we are using
"broker_topic=/bro/event/group1"
An example script for a group of connections and single query subscription,
to monitor usb_devices is given below:
```
module osquery;

const broker_port: port = 9999/tcp &redef;
redef exit_only_after_terminate = T;
redef osquery::endpoint_name = "Printer";

global added_usb_devices: event(host: string, usb_address: count, vendor: string, model: string);

global gconn: table[string] of string;

event bro_init()
{
	##enable broker communication
	osquery::enable();
	##subscribe to events
	osquery::subscribe_to_events("/bro/event/");
	##connect with a group of osquery host at IPs
	gconn["192.168.1.187"] = "9999";

	gconn["192.168.1.211"] = "9999";

	gconn["192.168.1.33"] = "9999";

 	osquery::groupconnect(gconn, 2sec);
}

##if the connection is established then connection_extablished event will be trigered.
event BrokerComm::outgoing_connection_established(peer_address: string, peer_port: port, peer_name: string)
{
	print "BrokerComm::outgoing_connection_establisted", 	peer_address,
        peer_port, peer_name;

	##if we are interested in inserted usb_devices then write event name as "added_usb_devices"
	osquery::subscribe("osquery::added_usb_devices","SELECT usb_address,vendor,model FROM
	usb_devices","/bro/event/group1");
}

event BrokerComm::incoming_connection_broken(peer_name: string)
{
	print "BrokerComm::incoming_connection_broken", peer_name;
	terminate();
}

event added_usb_devices(host: string, usb_address: count, vendor: string, model: string)
{
	print "New Usb Device Added";
 	print fmt("Host = %s Usb_address = %d Vendor = %s Model = %s",host, usb_address, vendor, model);
}
```
For multiple groups, you need to change the broker.ini at each osquery host to make it a part of specific group. For example, if there are three hosts and we wana make three groups, simply update broker.ini on each host with different
broker_topic "/bro/event/group1", "/bro/event/group2", "/bro/event/group3" respectively.
Then subscribe different queries on each host in BrokerComm::outgoing_connection_established event body.

```
event BrokerComm::outgoing_connection_established(peer_address: string, peer_port: port, peer_name: string)
{
	print "BrokerComm::outgoing_connection_establisted", 	peer_address,
        peer_port, peer_name;

	osquery::subscribe("osquery::added_usb_devices","SELECT usb_address,vendor,model FROM
	usb_devices","/bro/event/group1");
	osquery::subscribe("osquery::added_users","SELECT username,uid,gid FROM users", "/bro/event/group2");
	osquery::subscribe("osquery::added_acpi_tables","SELECT name,size,md5 FROM acpi_tables", "/bro/event/group3");
}
```

####3.4 Scenario 4: A master to a remote group of hosts monitoring with multiple queries subscription####
Make sure the broker.ini at each osquery host in a group has the same broker_topic. In our example, we are using
"broker_topic=/bro/event/group1"
An example script for a group of connection and multiple queries subscription,
to monitor multiple OS events is given below:

```
module osquery;

const broker_port: port = 9999/tcp &redef;
redef exit_only_after_terminate = T;
redef osquery::endpoint_name = "Printer";

global added_acpi_tables: event(host: string, name: string, size: count, md5: string);
global added_usb_devices: event(host: string, usb_address: count, vendor: string, model: string);
global added_users: event(host: string, username: string, uid: count, gid: count);

global query: table[string] of string;
global gconn: table[string] of string;

event bro_init()
{
	##enable broker communication
	osquery::enable();
	##subscribe to events
	osquery::subscribe_to_events("/bro/event/");
	##connect with a group of osquery host at IPs
	gconn["192.168.1.187"] = "9999";

	gconn["192.168.1.211"] = "9999";

	gconn["192.168.1.33"] = "9999";

 	osquery::groupconnect(gconn, 2sec);

	query["osquery::added_acpi_tables"] = "SELECT name,size,md5 FROM acpi_tables";
	query["osquery::added_usb_devices"] =  "SELECT usb_address,vendor,model FROM usb_devices";
	query["osquery::added_users"] =  "SELECT username,uid,gid FROM users";
}

##if the connection is established then connection_extablished event will be trigered.
event BrokerComm::outgoing_connection_established(peer_address: string, peer_port: port, peer_name: string)
{
	print "BrokerComm::outgoing_connection_establisted", 	peer_address, peer_port, peer_name;
	osquery::groupsubscribe("/bro/event/group1",query);

}

event BrokerComm::incoming_connection_broken(peer_name: string)
{
	print "BrokerComm::incoming_connection_broken", peer_name;
	terminate();
}

event added_acpi_tables(host: string, name: string, size: count, md5: 	string)
{
	print "New acpi_table Entry";
	print fmt("Host = %s Table_name = %s size = %d md5 = %s",host, 	name, size, md5);
}
event added_usb_devices(host: string, usb_address: count, vendor: string, model: string)
{
	print "New Usb Device Added";
 	print fmt("Host = %s Usb_address = %d Vendor = %s Model = %s",host, usb_address, vendor, model);
}
event added_users(host: string, username: string, uid: count, gid: count)
{
	print "New User Added";
 	print fmt("Host = %s UserName = %s UID = %d GID = %d",host, username, uid, gid);
}
```

For multiple groups, you need to change the broker.ini at each osquery host to make it a part of specific group. For example, if there are three hosts and we wana make three groups, simply update broker.ini on each host with different
broker_topic "/bro/event/group1", "/bro/event/group2", "/bro/event/group3" respectively.
And also define three different query tables e.g. query1, query2, query3, respectively.
Then subscribe different group of queries on each group in BrokerComm::outgoing_connection_established event body.
```
event BrokerComm::outgoing_connection_established(peer_address: string, peer_port: port, peer_name: string)
{
	print "BrokerComm::outgoing_connection_establisted", 	peer_address, peer_port, peer_name;
	osquery::groupsubscribe("/bro/event/group1",query1);
	osquery::groupsubscribe("/bro/event/group2",query2);
	osquery::groupsubscribe("/bro/event/group3",query3);
```


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

package com.google.devtools.build.lib.actions;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.devtools.build.lib.actions.cache.MetadataHandler;
import com.google.devtools.build.lib.actions.extra.ExtraActionInfo;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.collect.CollectionUtils;
import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder;
import com.google.devtools.build.lib.collect.nestedset.Order;
import com.google.devtools.build.lib.concurrent.ThreadSafety.Immutable;
import com.google.devtools.build.lib.concurrent.ThreadSafety.ThreadSafe;
import com.google.devtools.build.lib.events.Event;
import com.google.devtools.build.lib.events.EventHandler;
import com.google.devtools.build.lib.skylarkinterface.SkylarkCallable;
import com.google.devtools.build.lib.skylarkinterface.SkylarkModule;
import com.google.devtools.build.lib.skylarkinterface.SkylarkModuleCategory;
import com.google.devtools.build.lib.skylarkinterface.SkylarkValue;
import com.google.devtools.build.lib.syntax.Printer;
import com.google.devtools.build.lib.syntax.SkylarkDict;
import com.google.devtools.build.lib.syntax.SkylarkList;
import com.google.devtools.build.lib.syntax.SkylarkNestedSet;
import com.google.devtools.build.lib.util.Preconditions;
import com.google.devtools.build.lib.vfs.FileSystemUtils;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.PathFragment;
import com.google.devtools.build.lib.vfs.Symlinks;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import javax.annotation.Nullable;

/**
 * Abstract implementation of Action which implements basic functionality: the inputs, outputs, and
 * toString method. Both input and output sets are immutable. Subclasses must be generally
 * immutable - see the documentation on {@link Action}.
 */
@Immutable @ThreadSafe
@SkylarkModule(
    name = "Action",
    category = SkylarkModuleCategory.BUILTIN,
    doc = "An action created on a ctx object. You can retrieve these "
        + "using the Actions provider. Some fields are only "
        + "applicable for certain kinds of actions. Fields that are inapplicable are set to "
        + "None."
)
public abstract class AbstractAction implements Action, SkylarkValue {

  /**
   * An arbitrary default resource set. Currently 250MB of memory, 50% CPU and 0% of total I/O.
   */
  public static final ResourceSet DEFAULT_RESOURCE_SET =
      ResourceSet.createWithRamCpuIo(250, 0.5, 0);

  /**
   * The owner/inputs/outputs attributes below should never be directly accessed even within
   * AbstractAction itself. The appropriate getter methods should be used instead. This has to be
   * done due to the fact that the getter methods can be overridden in subclasses.
   */
  private final ActionOwner owner;

  /**
   * Tools are a subset of inputs and used by the WorkerSpawnStrategy to determine whether a
   * compiler has changed since the last time it was used. This should include all artifacts that
   * the tool does not dynamically reload / check on each unit of work - e.g. its own binary, the
   * JDK for Java binaries, shared libraries, ... but not a configuration file, if it reloads that
   * when it has changed.
   *
   *
If the "tools" set does not contain exactly the right set of artifacts, the following can
   * happen: If an artifact that should be included is missing, the tool might not be restarted when
   * it should, and builds can become incorrect (example: The compiler binary is not part of this
   * set, then the compiler gets upgraded, but the worker strategy still reuses the old version).
   * If an artifact that should *not* be included is accidentally part of this set, the worker
   * process will be restarted more often that is necessary - e.g. if a file that is unique to each
   * unit of work, e.g. the source code that a compiler should compile for a compile action, is
   * part of this set, then the worker will never be reused and will be restarted for each unit of
   * work.
   */
  private final Iterable<Artifact> tools;

  // The variable inputs is non-final only so that actions that discover their inputs can modify it.
  private Iterable<Artifact> inputs;
  private final Iterable<String> clientEnvironmentVariables;
  private final RunfilesSupplier runfilesSupplier;
  private final ImmutableSet<Artifact> outputs;

  private String cachedKey;

  /**
   * Construct an abstract action with the specified inputs and outputs;
   */
  protected AbstractAction(ActionOwner owner,
                           Iterable<Artifact> inputs,
                           Iterable<Artifact> outputs) {
    this(owner, ImmutableList.<Artifact>of(), inputs, EmptyRunfilesSupplier.INSTANCE, outputs);
  }

  /**
   * Construct an abstract action with the specified tools, inputs and outputs;
   */
  protected AbstractAction(
      ActionOwner owner,
      Iterable<Artifact> tools,
      Iterable<Artifact> inputs,
      Iterable<Artifact> outputs) {
    this(owner, tools, inputs, EmptyRunfilesSupplier.INSTANCE, outputs);
  }

  protected AbstractAction(
      ActionOwner owner,
      Iterable<Artifact> inputs,
      RunfilesSupplier runfilesSupplier,
      Iterable<Artifact> outputs) {
    this(owner, ImmutableList.<Artifact>of(), inputs, runfilesSupplier, outputs);
  }

  protected AbstractAction(
      ActionOwner owner,
      Iterable<Artifact> tools,
      Iterable<Artifact> inputs,
      RunfilesSupplier runfilesSupplier,
      Iterable<Artifact> outputs) {
    this(owner, tools, inputs, ImmutableList.<String>of(), runfilesSupplier, outputs);
  }

  protected AbstractAction(
      ActionOwner owner,
      Iterable<Artifact> tools,
      Iterable<Artifact> inputs,
      Iterable<String> clientEnvironmentVariables,
      RunfilesSupplier runfilesSupplier,
      Iterable<Artifact> outputs) {
    Preconditions.checkNotNull(owner);
    // TODO(bazel-team): Use RuleContext.actionOwner here instead
    this.owner = owner;
    this.tools = CollectionUtils.makeImmutable(tools);
    this.inputs = CollectionUtils.makeImmutable(inputs);
    this.clientEnvironmentVariables = clientEnvironmentVariables;
    this.outputs = ImmutableSet.copyOf(outputs);
    this.runfilesSupplier = Preconditions.checkNotNull(runfilesSupplier,
        "runfilesSupplier may not be null");
    Preconditions.checkArgument(!this.outputs.isEmpty(), "action outputs may not be empty");
  }

  @Override
  public final ActionOwner getOwner() {
    return owner;
  }

  @Override
  public boolean inputsKnown() {
    return true;
  }

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

  @Override
  public Iterable<Artifact> discoverInputs(ActionExecutionContext actionExecutionContext)
      throws ActionExecutionException, InterruptedException {
    throw new IllegalStateException("discoverInputs cannot be called for " + this.prettyPrint()
        + " since it does not discover inputs");
  }

  @Nullable
  @Override
  public Iterable<Artifact> getInputsWhenSkippingInputDiscovery() {
    return null;
  }

  @Nullable
  @Override
  public Iterable<Artifact> resolveInputsFromCache(
      ArtifactResolver artifactResolver,
      PackageRootResolver resolver,
      Collection<PathFragment> inputPaths)
      throws PackageRootResolutionException, InterruptedException {
    throw new IllegalStateException(
        "Method must be overridden for actions that may have unknown inputs.");
  }

  @Override
  public void updateInputs(Iterable<Artifact> inputs) {
    throw new IllegalStateException(
        "Method must be overridden for actions that may have unknown inputs.");
  }

  @Override
  public Iterable<Artifact> getTools() {
    return tools;
  }

  /**
   * Should only be overridden by actions that need to optionally insert inputs. Actions that
   * discover their inputs should use {@link #setInputs} to set the new iterable of inputs when they
   * know it.
   */
  @Override
  public Iterable<Artifact> getInputs() {
    return inputs;
  }

  @Override
  public Iterable<String> getClientEnvironmentVariables() {
    return clientEnvironmentVariables;
  }

  @Override
  public RunfilesSupplier getRunfilesSupplier() {
    return runfilesSupplier;
  }

  /**
   * Set the inputs of the action. May only be used by an action that {@link #discoversInputs()}.
   * The iterable passed in is automatically made immutable.
   */
  protected void setInputs(Iterable<Artifact> inputs) {
    Preconditions.checkState(discoversInputs(), this);
    this.inputs = CollectionUtils.makeImmutable(inputs);
  }

  @Override
  public ImmutableSet<Artifact> getOutputs() {
    return outputs;
  }

  @Override
  public Artifact getPrimaryInput() {
    // The default behavior is to return the first input artifact.
    // Call through the method, not the field, because it may be overridden.
    return Iterables.getFirst(getInputs(), null);
  }

  @Override
  public Artifact getPrimaryOutput() {
    // Default behavior is to return the first output artifact.
    // Use the method rather than field in case of overriding in subclasses.
    return Iterables.getFirst(getOutputs(), null);
  }

  @Override
  public Iterable<Artifact> getMandatoryInputs() {
    return getInputs();
  }

  @Override
  public String toString() {
    return prettyPrint() + " (" + getMnemonic() + "[" + ImmutableList.copyOf(getInputs())
        + (inputsKnown() ? " -> " : ", unknown inputs -> ")
        + getOutputs() + "]" + ")";
  }

  @Override
  public abstract String getMnemonic();

  /**
   * See the javadoc for {@link com.google.devtools.build.lib.actions.Action} and
   * {@link com.google.devtools.build.lib.actions.ActionExecutionMetadata#getKey()} for the contract
   * for {@link #computeKey()}.
   */
  protected abstract String computeKey();

  @Override
  public final synchronized String getKey() {
    if (cachedKey == null) {
      cachedKey = computeKey();
    }
    return cachedKey;
  }

  @Override
  public String describeKey() {
    return null;
  }

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

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

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

  @Override
  public final String getProgressMessage() {
    String message = getRawProgressMessage();
    if (message == null) {
      return null;
    }
    String additionalInfo = getOwner().getAdditionalProgressInfo();
    return additionalInfo == null ? message : message + " [" + additionalInfo + "]";
  }

  /**
   * Returns a progress message string that is specific for this action. This is
   * then annotated with additional information, currently the string '[for host]'
   * for actions in the host configurations.
   *
   *
A return value of null indicates no message should be reported.
   */
  protected String getRawProgressMessage() {
    // A cheesy default implementation.  Subclasses are invited to do something
    // more meaningful.
    return defaultProgressMessage();
  }

  private String defaultProgressMessage() {
    return getMnemonic() + " " + getPrimaryOutput().prettyPrint();
  }

  @Override
  public String prettyPrint() {
    return "action '" + describe() + "'";
  }

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

  @Override
  public void write(Appendable buffer, char quotationMark) {
    Printer.append(buffer, prettyPrint()); // TODO(bazel-team): implement a readable representation
  }

  /**
   * Deletes all of the action's output files, if they exist. If any of the
   * Artifacts refers to a directory recursively removes the contents of the
   * directory.
   *
   * @param execRoot the exec root in which this action is executed
   */
  protected void deleteOutputs(Path execRoot) throws IOException {
    for (Artifact output : getOutputs()) {
      deleteOutput(output);
    }
  }

  /**
   * Helper method to remove an Artifact. If the Artifact refers to a directory
   * recursively removes the contents of the directory.
   */
  protected void deleteOutput(Artifact output) throws IOException {
    Path path = output.getPath();
    try {
      // Optimize for the common case: output artifacts are files.
      path.delete();
    } catch (IOException e) {
      // Handle a couple of scenarios where the output can still be deleted, but make sure we're not
      // deleting random files on the filesystem.
      if (output.getRoot() == null) {
        throw e;
      }
      String outputRootDir = output.getRoot().getPath().getPathString();
      if (!path.getPathString().startsWith(outputRootDir)) {
        throw e;
      }

      Path parentDir = path.getParentDirectory();
      if (!parentDir.isWritable() && parentDir.getPathString().startsWith(outputRootDir)) {
        // Retry deleting after making the parent writable.
        parentDir.setWritable(true);
        deleteOutput(output);
      } else if (path.isDirectory(Symlinks.NOFOLLOW)) {
        FileSystemUtils.deleteTree(path);
      } else {
        throw e;
      }
    }
  }

  /**
   * If the action might read directories as inputs in a way that is unsound wrt dependency
   * checking, this method must be called.
   */
  protected void checkInputsForDirectories(EventHandler eventHandler,
                                           MetadataHandler metadataHandler) {
    // Report "directory dependency checking" warning only for non-generated directories (generated
    // ones will be reported earlier).
    for (Artifact input : getMandatoryInputs()) {
      // Assume that if the file did not exist, we would not have gotten here.
      if (input.isSourceArtifact() && !metadataHandler.isRegularFile(input)) {
        eventHandler.handle(Event.warn(getOwner().getLocation(), "input '"
            + input.prettyPrint() + "' to " + getOwner().getLabel()
            + " is a directory; dependency checking of directories is unsound"));
      }
    }
  }

  @Override
  public MiddlemanType getActionType() {
    return MiddlemanType.NORMAL;
  }

  /**
   * If the action might create directories as outputs this method must be called.
   */
  protected void checkOutputsForDirectories(EventHandler eventHandler) {
    for (Artifact output : getOutputs()) {
      Path path = output.getPath();
      String ownerString = Label.print(getOwner().getLabel());
      if (path.isDirectory()) {
        eventHandler.handle(
            Event.warn(
                getOwner().getLocation(),
                "output '" + output.prettyPrint() + "' of " + ownerString
                    + " is a directory; dependency checking of directories is unsound")
                .withTag(ownerString));
      }
    }
  }

  @Override
  public void prepare(Path execRoot) throws IOException {
    deleteOutputs(execRoot);
  }

  @Override
  public String describe() {
    String progressMessage = getProgressMessage();
    return progressMessage != null ? progressMessage : defaultProgressMessage();
  }

  @Override
  public boolean shouldReportPathPrefixConflict(ActionAnalysisMetadata action) {
    return this != action;
  }

  @Override
  public boolean extraActionCanAttach() {
    return true;
  }

  @Override
  public ExtraActionInfo.Builder getExtraActionInfo() {
    ActionOwner owner = getOwner();
    ExtraActionInfo.Builder result =
        ExtraActionInfo.newBuilder()
            .setOwner(owner.getLabel().toString())
            .setId(getKey())
            .setMnemonic(getMnemonic());
    if (owner.getAspectName() != null) {
      result.setAspectName(owner.getAspectName());
    }
    if (owner.getAspectParameters() != null) {
      for (Map.Entry<String, Collection<String>> entry :
          owner.getAspectParameters().getAttributes().asMap().entrySet()) {
        result.putAspectParameters(
            entry.getKey(),
            ExtraActionInfo.StringList.newBuilder().addAllValue(entry.getValue()).build());
      }
    }
    return result;
  }

  @Override
  public ImmutableSet<Artifact> getMandatoryOutputs() {
    return ImmutableSet.of();
  }

  /**
   * Returns input files that need to be present to allow extra_action rules to shadow this action
   * correctly when run remotely. This is at least the normal inputs of the action, but may include
   * other files as well. For example C(++) compilation may perform include file header scanning.
   * This needs to be mirrored by the extra_action rule. Called by
   * {@link com.google.devtools.build.lib.rules.extra.ExtraAction} at execution time.
   *
   *
As this method is called from the ExtraAction, make sure it is ok to call
   * this method from a different thread than the one this action is executed on.
   *
   * @param actionExecutionContext Services in the scope of the action, like the Out/Err streams.
   * @throws ActionExecutionException only when code called from this method
   *     throws that exception.
   * @throws InterruptedException if interrupted
   */
  public Iterable<Artifact> getInputFilesForExtraAction(
      ActionExecutionContext actionExecutionContext)
      throws ActionExecutionException, InterruptedException {
    return getInputs();
  }

  @SkylarkCallable(
      name = "inputs",
      doc = "A set of the input files of this action.",
      structField = true)
  public SkylarkNestedSet getSkylarkInputs() {
    return SkylarkNestedSet.of(Artifact.class, NestedSetBuilder.wrap(
        Order.STABLE_ORDER, getInputs()));
  }

  @SkylarkCallable(
      name = "outputs",
      doc = "A set of the output files of this action.",
      structField = true)
  public SkylarkNestedSet getSkylarkOutputs() {
    return SkylarkNestedSet.of(Artifact.class, NestedSetBuilder.wrap(
        Order.STABLE_ORDER, getOutputs()));
  }

  @SkylarkCallable(
      name = "argv",
      doc = "For actions created by ctx.action(), an immutable "
          + "list of the arguments for the command line to be executed. Note that when using the "
          + "shell (i.e., when executable is not set), "
          + "the first two arguments will be the shell path and \"-c\".",
      structField = true,
      allowReturnNones = true)
  public SkylarkList<String> getSkylarkArgv() {
    return null;
  }

  @SkylarkCallable(
      name = "content",
      doc = "For actions created by ctx.file_action() or "
          + "ctx.template_action(), the contents of the "
          + "file to be written.",
      structField = true,
      allowReturnNones = true)
  public String getSkylarkContent() throws IOException {
    return null;
  }

  @SkylarkCallable(
      name = "substitutions",
      doc = "For actions created by "
          + "ctx.template_action(), an immutable dict holding the substitution mapping.",
      structField = true,
      allowReturnNones = true)
  public SkylarkDict<String, String> getSkylarkSubstitutions() {
    return null;
  }
}


text:
@interface SYFTextBoxController : UIViewController

@end