text:
package com.oloba.core.http;

import java.io.File;
import java.net.InetSocketAddress;
import java.util.List;

import org.apache.commons.lang3.Validate;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletHandler;
import org.eclipse.jetty.webapp.WebAppContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Lists;
import com.oloba.core.constant.EnvConf;

public class JettyServer {

    private Logger logger = LoggerFactory.getLogger(getClass());
    private int port = -1;
    private String contextPath = null;
    private ServletHandler servletHandler = null;
    private List<String> webappPaths = Lists.newArrayList();

    public JettyServer(){
        webappPaths.add("lib/webapp");
        webappPaths.add("src/main/webapp");
    }

    public void setPort(int port) {
        this.port = port;
    }

    public void setContextPath(String contextPath) {
        this.contextPath = contextPath;
    }

    /**
     * 用在修正idea下的当前目录
     */
    public void addWebappPath(String webappPath) {
        webappPaths.add(webappPath);
    }

    public void setServletHandler(ServletHandler servletHandler) {
        this.servletHandler = servletHandler;
    }

    public void start() {
        Validate.isTrue(port>0);

        String address = "0.0.0.0";
        InetSocketAddress inetAddress = new InetSocketAddress(address, port);
        Server server = new Server(inetAddress);
//        QueuedThreadPool threadPool = new QueuedThreadPool(1024, 32);
//        Server server = new Server(threadPool);
//        ServerConnector connector = new ServerConnector(server);
//        server.addConnector(connector);
//
//        connector.setPort(port);

        try {
		    if(contextPath != null) {
		    	WebAppContext webAppContext = new WebAppContext(getWebappPath(), contextPath);
		    	webAppContext.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false");
		    	webAppContext.setInitParameter("org.eclipse.jetty.servlet.Default.useFileMappedBuffer", "false");
//	            webAppContext.setTempDirectory(new File(webAppContext.getWar(), "jsptemp"));

		        server.setHandler(webAppContext);
		    } else if(servletHandler != null) {
		        server.setHandler(servletHandler);
		    } else {
		        Validate.isTrue(false);
		    }

            server.start();
		    logger.warn("Started JettyServer {{}} environment-prod:{}.",
		    		address+":"+port, EnvConf.isProd());
            server.join();
        } catch (Exception e) {
            logger.error("jetty start error", e);
            System.exit(-1);
        }
    }

    private String getWebappPath() {
        for(String webappPath: webappPaths) {
            if(new File(webappPath, "WEB-INF/web.xml").exists()) {
                logger.warn("find {}", webappPath);
                return webappPath;
            }
        }
        throw new IllegalStateException("not find any webappPath");
    }

}


text:
<?php

declare(strict_types=1);

namespace SebastianBergmann\ObjectReflector\TestFixture;

class ClassWithIntegerAttributeName
{
    public function __construct()
    {
        $i        = 1;
        $this->$i = 2;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.nem.monitor.launcher;

import java.io.*;
import java.util.*;
import java.util.logging.Logger;
import java.util.stream.Collectors;

/**
 * Helper class for launching external java processes.
 */
public class JavaProcessLauncher {
	private static final Logger LOGGER = Logger.getLogger(JavaProcessLauncher.class.getName());

	/**
	 * Launches a new java process.
	 *
	 * @param arguments The process arguments.
	 * @param workingDirectory The process working directory.
	 */
	public void launch(final List<String> arguments, final File workingDirectory) throws IOException {
		final List<String> argumentsWithExe = new ArrayList<>();
		argumentsWithExe.add("java");
		argumentsWithExe.addAll(arguments);

		LOGGER.info(String.format(
				"Launching '%s' in '%s'",
				argumentsWithExe.stream().collect(Collectors.joining(" ")),
				workingDirectory));

		final ProcessBuilder builder = new ProcessBuilder()
				.command(argumentsWithExe)
				.inheritIO()
				.directory(workingDirectory);
		builder.start();
	}
}


text:
<?php
/** Read files and return them as an array
*/

function read($path, $config = array()) {
	$path = str_replace('\\' , "/", $path);
	// Open file
	$file = file($path . ".config");

	// Read all lines
	foreach($file as $line_num => $line) {
		// Ignore command- and empty  lines
		if(substr($line, 0, 1) === "#" || strlen($line) <= 0)
			continue;

		// Read config items key=value
		$config_line = preg_split("/\s* *= *\s*/", $line, 2);

		// If not a valid item, skip
		if(count($config_line) !== 2)
			continue;

		// Add item to return value
		$config[rtrim($config_line[0])] = rtrim($config_line[1]);
	}

	return $config;

}


text:
package com.mobidevday.demo.activities;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import com.mobidevday.demo.AuthService;
import com.mobidevday.demo.R;
import com.mobidevday.demo.Settings;

public class Basic extends BaseActivity {

    private String mAction;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.basic);

        String title = getIntent().getStringExtra("title");
        mAction = getIntent().getStringExtra("action");

        TextView titleText = (TextView) findViewById(R.id.title);
        titleText.setText(title);

        Button mLogin = (Button) findViewById(R.id.login);
        mLogin.setOnClickListener(loginListener);

        mPersonList = (ListView) findViewById(R.id.results);

        if(mAction.equalsIgnoreCase("hmac-auth")){
            EditText passwordField = (EditText) findViewById(R.id.password);
            passwordField.setEnabled(false);
        }
    }

    private View.OnClickListener loginListener = new View.OnClickListener(){
            public void onClick(View v){
                //Hide the keyboard
                InputMethodManager inputManager = (InputMethodManager)
                                                  getSystemService(INPUT_METHOD_SERVICE);

                inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                                                     InputMethodManager.HIDE_NOT_ALWAYS);

                EditText userNameField = (EditText) findViewById(R.id.user_name);
                EditText passwordField = (EditText) findViewById(R.id.password);

                //Send credentials via intent
                Intent intent = new Intent(Basic.this, AuthService.class);
                intent.setAction(mAction);
                intent.putExtra("username", userNameField.getText().toString().trim());
                intent.putExtra("password", passwordField.getText().toString().trim());
                startService(intent);
            }
    };
}


text:
package com.navercorp.pinpoint.plugin.jdbc.oracle.parser;

import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

/**
 * @author emeroad
 */
public class OracleNetConnectionDescriptorParserTest {

    private Logger logger = LogManager.getLogger(this.getClass());

    @Test
    public void simple() {
        String rac = "jdbc:oracle:thin:@(DESCRIPTION=(LOAD_BALANCE=on)"
                                        + "(CONNECT_DATA=(SERVICE_NAME=service)))";

        OracleNetConnectionDescriptorParser parser = new OracleNetConnectionDescriptorParser(rac);
        KeyValue<?> keyValue = parser.parse();

        logger.info(keyValue.toString());

        Description des = new Description(keyValue);
        Assertions.assertEquals(des.getServiceName(), "service");
    }

    @Test
    public void emptyValue() {
        String rac = "jdbc:oracle:thin:@(DESCRIPTION=(LOAD_BALANCE=)"
                                        + "(CONNECT_DATA=(SERVICE_NAME=)))";

        OracleNetConnectionDescriptorParser parser = new OracleNetConnectionDescriptorParser(rac);
        KeyValue<?> keyValue = parser.parse();
        logger.info(keyValue.toString());

        Description des = new Description(keyValue);
        Assertions.assertEquals(des.getServiceName(), null);

    }

    @Test
    public void parse() {
        String rac = "jdbc:oracle:thin:@(DESCRIPTION=(LOAD_BALANCE=on)" +
                "(ADDRESS=(PROTOCOL=TCP)(HOST=1.2.3.4) (PORT=1521))" +
                "(ADDRESS=(PROTOCOL=TCP)(HOST=1.2.3.5) (PORT=1522))" +
                "(CONNECT_DATA=(SERVICE_NAME=service)))";

        OracleNetConnectionDescriptorParser parser = new OracleNetConnectionDescriptorParser(rac);
        KeyValue<?> keyValue = parser.parse();
        Description description = new Description(keyValue);

        Description value = new Description();
        value.setServiceName("service");
        value.addAddress("tcp", "1.2.3.4", "1521");
        value.addAddress("tcp", "1.2.3.5", "1522");
        Assertions.assertEquals(description, value);

    }

    @Test
    public void parse2() {
        String rac = "jdbc:oracle:thin:@(DESCRIPTION=(LOAD_BALANCE = off )" +
                "(ADDRESS  =  ( PROTOCOL = TCP)(HOST = 1.2.3.4 ) (PORT = 1521 ))" +
                "(ADDRESS = (PROTOCOL = TCP ) (HOST = 1.2.3.5) ( PORT = 1522 ))" +
                " ( CONNECT_DATA = ( SERVICE_NAME = service ) ) )";

        OracleNetConnectionDescriptorParser parser = new OracleNetConnectionDescriptorParser(rac);
        KeyValue<?> keyValue = parser.parse();
        Description description = new Description(keyValue);

        Description value = new Description();
        value.setServiceName("service");
        value.addAddress("tcp", "1.2.3.4", "1521");
        value.addAddress("tcp", "1.2.3.5", "1522");
        Assertions.assertEquals(description, value);

    }

    @Test
    public void parse3() {
        String rac = "jdbc:oracle:thin:@(DESCRIPTION=(LOAD_BALANCE = off )" +
                "(ADDRESS  =  ( PROTOCOL = TCP)(HOST = 1.2.3.4 ) (PORT = 1521 ))" +
                "(ADDRESS = (PROTOCOL = TCP ) (HOST = 1.2.3.5) ( PORT = 1522 ))" +
                "(ADDRESS = (PROTOCOL = TCP ) (HOST = 1.2.3.6) ( PORT = 1523 ))" +
                " ( CONNECT_DATA = ( SERVICE_NAME = service ) ) )";

        OracleNetConnectionDescriptorParser parser = new OracleNetConnectionDescriptorParser(rac);
        KeyValue<?> keyValue = parser.parse();
        Description description = new Description(keyValue);

        Description value = new Description();
        value.setServiceName("service");
        value.addAddress("tcp", "1.2.3.4", "1521");
        value.addAddress("tcp", "1.2.3.5", "1522");
        value.addAddress("tcp", "1.2.3.6", "1523");
        Assertions.assertEquals(description, value);

    }

    @Test
    public void parse4() {
        String rac = "jdbc:oracle:thin:@(DESCRIPTION=(LOAD_BALANCE = off )" +
                "(ADDRESS  =  ( PROTOCOL = TCP)(HOST = 1.2.3.4 ) (PORT = 1521 ))" +
                " ( CONNECT_DATA = ( SID = sid ) ) )";

        OracleNetConnectionDescriptorParser parser = new OracleNetConnectionDescriptorParser(rac);
        KeyValue<?> keyValue = parser.parse();
        Description description = new Description(keyValue);

        Description value = new Description();
        value.setSid("sid");
        value.addAddress("tcp", "1.2.3.4", "1521");
        Assertions.assertEquals(description, value);

    }

    @Test
    public void parse_description_list() {
        String url = "jdbc:oracle:thin:@(DESCRIPTION_LIST=" +
                "(LOAD_BALANCE=off)(FAILOVER=on)" +
                "(DESCRIPTION=" +
                    "(LOAD_BALANCE=on)" +
                    "(ADDRESS=(PROTOCOL=tcp)(HOST=1.2.3.4)(PORT=1521))" +
                    "(ADDRESS=(PROTOCOL=tcp)(HOST=1.2.3.5)(PORT=1521))" +
                    "(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=service_test)))" +
                 "(DESCRIPTION=" +
                    "(LOAD_BALANCE=on)" +
                    "(ADDRESS=(PROTOCOL=tcp)(HOST=2.3.4.5)(PORT=1521))" +
                    "(ADDRESS=(PROTOCOL=tcp)(HOST=2.3.4.6)(PORT=1521))" +
                    "(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=service_test))))";

        OracleNetConnectionDescriptorParser parser = new OracleNetConnectionDescriptorParser(url);
        KeyValue<?> keyValue = parser.parse();

        DescriptionList descriptionList = new DescriptionList(keyValue);
        Description desc1 = new Description();
        desc1.setServiceName("service_test");
        desc1.addAddress("tcp", "1.2.3.4", "1521");
        desc1.addAddress("tcp", "1.2.3.5", "1521");
        Assertions.assertEquals(desc1, descriptionList.getDescriptionList().get(0));

        Description desc2 = new Description();
        desc2.setServiceName("service_test");
        desc2.addAddress("tcp", "2.3.4.5", "1521");
        desc2.addAddress("tcp", "2.3.4.6", "1521");
        Assertions.assertEquals(desc2, descriptionList.getDescriptionList().get(1));

    }

    @Test
     public void parseEofError() {
        String rac = "jdbc:oracle:thin:@(DESCRIPTION=(LOAD_BALANCE = off )" +
                "(ADDRESS  =  ( PROTOCOL = TCP)(HOST = 1.2.3.4 ) (PORT = 1521 ))" +
//                " ( CONNECT_DATA = ( SID = sid ) ) )";
                " ( CONNECT_DATA = ( SID = sid ) ) ";

        OracleNetConnectionDescriptorParser parser = new OracleNetConnectionDescriptorParser(rac);
        try {
            KeyValue<?> keyValue = parser.parse();
            Assertions.fail();
        } catch (OracleConnectionStringException e) {
            logger.info("Expected error", e);
        }

    }

    @Test
    public void parseSyntaxError() {
        String rac = "jdbc:oracle:thin:@(DESCRIPTION=(LOAD_BALANCE = off )" +
                "(ADDRESS  =  ( PROTOCOL = TCP) HOST = 1.2.3.4 ) (PORT = 1521 ))" +
                " ( CONNECT_DATA = ( SID = sid ) ) )";

        OracleNetConnectionDescriptorParser parser = new OracleNetConnectionDescriptorParser(rac);
        try {
            KeyValue<?> keyValue = parser.parse();
            Assertions.fail();
        } catch (OracleConnectionStringException e) {
            logger.info("Expected error", e);
        }
    }

    @Test
    public void parseSyntaxError2() {
        String rac = "jdbc:oracle:thin:@(DESCRIPTION=(LOAD_BALANCE = off )" +
                "(ADDRESS  =  ( PROTOCOL = TCP) (HOST = 1.2.3.4 ) ( = 1521 ))" +
                " ( CONNECT_DATA = ( SID = sid ) ) )";
        // removed port

        OracleNetConnectionDescriptorParser parser = new OracleNetConnectionDescriptorParser(rac);
        try {
            KeyValue<?> keyValue = parser.parse();
            Assertions.fail();
        } catch (OracleConnectionStringException e) {
            logger.info("Expected error", e);
        }
    }

}


text:
package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"os"
	"strings"

	"go.pedge.io/pkg/exec"
	"go.pedge.io/tools/common"
)

func main() {
	if err := do(); err != nil {
		fmt.Fprintf(os.Stderr, "%s\n", err.Error())
		os.Exit(1)
	}
	os.Exit(0)
}

func do() error {
	if len(os.Args) < 2 {
		return fmt.Errorf("usage: go-external-deps pkg [output-file-path]")
	}
	pkg := os.Args[1]
	outputFilePath := ""
	if len(os.Args) > 2 {
		outputFilePath = os.Args[2]
	}
	if strings.HasPrefix(pkg, ".") || strings.HasSuffix(pkg, "/") || strings.HasSuffix(pkg, ".") {
		return fmt.Errorf("just use actual package name, not . at the beginning or / or /... at the end")
	}
	buffer := bytes.NewBuffer(nil)
	if err := pkgexec.RunStdout(buffer, "go", "list", "-f", "{{join .Deps \"\\n\"}}", fmt.Sprintf("%s/...", pkg)); err != nil {
		return err
	}
	lines, err := common.GetUniqueSortedLines(buffer)
	if err != nil {
		return err
	}
	var noVendorLines []string
	for _, line := range lines {
		if !strings.Contains("line", fmt.Sprintf("%s/vendor/", pkg)) {
			noVendorLines = append(noVendorLines, line)
		}
	}
	args := []string{"go", "list", "-f", "{{if not .Standard}}{{.ImportPath}}{{end}}"}
	args = append(args, noVendorLines...)
	buffer = bytes.NewBuffer(nil)
	if err = pkgexec.RunStdout(buffer, args...); err != nil {
		return err
	}
	lines, err = common.GetUniqueSortedLines(buffer)
	if err != nil {
		return err
	}
	var filteredLines []string
	for _, line := range lines {
		if !strings.HasPrefix(line, pkg) {
			filteredLines = append(filteredLines, line)
		}
	}
	output := strings.Join(filteredLines, "\n")
	if outputFilePath == "" {
		fmt.Println(output)
		return nil
	}
	existing, err := ioutil.ReadFile(outputFilePath)
	if err != nil {
		if os.IsNotExist(err) {
			fmt.Fprintf(os.Stderr, "file %s does not exist, creating...\n", outputFilePath)
			return write(output, outputFilePath)
		}
		return err
	}
	if output != string(existing) {
		fmt.Fprintf(os.Stderr, "found diff for file %s, updating...\n", outputFilePath)
		return write(output, outputFilePath)
	}
	return nil
}

func write(data string, outputFilePath string) (retErr error) {
	file, err := os.Create(outputFilePath)
	if err != nil {
		return err
	}
	defer func() {
		if err := file.Close(); err != nil && retErr == nil {
			retErr = err
		}
	}()
	_, err = file.Write([]byte(data))
	return err
}


text:
package sagan.blog.support;

import sagan.blog.Post;
import sagan.blog.PostCategory;
import sagan.blog.PostFormat;
import sagan.team.MemberProfile;
import sagan.team.support.TeamRepository;
import saganx.AbstractIntegrationTests;

import java.security.Principal;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static sagan.support.SecurityRequestPostProcessors.*;

public class CreateBlogPostTests extends AbstractIntegrationTests {

    @Autowired
    private WebApplicationContext wac;

    private MockMvc mockMvc;

    @Autowired
    private PostRepository postRepository;

    @Autowired
    private TeamRepository teamRepository;

    private Principal principal;

    @Before
    public void setup() {
        MemberProfile profile = new MemberProfile();
        profile.setUsername("author");
        profile.setName("Mr Author");
        profile = teamRepository.save(profile);

        final Long profileId = profile.getId();

        principal = profileId::toString;
        mockMvc = MockMvcBuilders.webAppContextSetup(wac)
                .addFilters(springSecurityFilterChain)
                .defaultRequest(get("/").with(csrf()).with(user(profileId).roles("USER"))).build();
        postRepository.deleteAll();
    }

    @After
    public void tearDown() throws Exception {
        postRepository.deleteAll();
    }

    @Test
    public void getNewBlogPage() throws Exception {
        mockMvc.perform(get("/admin/blog/new"))
                .andExpect(status().isOk())
                .andExpect(content().contentTypeCompatibleWith("text/html"))
                .andExpect(content().string(containsString("Add New Post")));
    }

    @Test
    public void redirectToEditPostAfterCreation() throws Exception {
        MockHttpServletRequestBuilder createPostRequest = getCreatePostRequest();
        createPostRequest.param("title", "Post Title");
        createPostRequest.param("content", "My Content");
        createPostRequest.param("category", PostCategory.NEWS_AND_EVENTS.name());
        createPostRequest.param("format", PostFormat.MARKDOWN.name());
        createPostRequest.param("draft", "false");
        createPostRequest.param("publishAt", "2013-07-01 13:15");

        mockMvc.perform(createPostRequest)
                .andExpect(status().isFound())
                .andExpect(result -> {
                    String redirectedUrl = result.getResponse().getRedirectedUrl();
                    assertTrue("Expected redirect to /blog/2013/07/01/post-title, got: " + redirectedUrl,
                            redirectedUrl.matches("^/blog/2013/07/01/post-title/edit"));
                });
    }

    @Test
    public void createdPostValuesArePersisted() throws Exception {
        MockHttpServletRequestBuilder createPostRequest = getCreatePostRequest();
        createPostRequest.param("title", "Post Title");
        createPostRequest.param("content", "My Content");
        createPostRequest.param("category", PostCategory.ENGINEERING.name());
        createPostRequest.param("format", PostFormat.MARKDOWN.name());
        createPostRequest.param("broadcast", "true");

        mockMvc.perform(createPostRequest);

        Post post = postRepository.findAll().get(0);

        assertThat(post.getTitle(), is("Post Title"));
        assertThat(post.getRawContent(), is("My Content"));
        assertThat(post.getCategory(), is(PostCategory.ENGINEERING));
        assertThat(post.isBroadcast(), is(true));
    }

    private MockHttpServletRequestBuilder getCreatePostRequest() {
        return post("/admin/blog").principal(principal);
    }

    @Test
    public void invalidPostsShowsErrors() throws Exception {
        MockHttpServletRequestBuilder createPostRequest = getCreatePostRequest();
        mockMvc.perform(createPostRequest).andExpect(status().isOk());
    }

}


text:
node.gitlab
===========

nodejs library of gitlab API.


text:
/*
  @author Sam Heutmaker [samheutmaker@gmail.com]
*/

import React, {PropTypes, Component} from 'react'
import ControlRoom from './../components/ControlRoom'
import CenteredConfirm from './../components/CenteredConfirm'
import Btn from './../components/Btn'
import Loader from './../components/Loader'
import Msg from './../components/Msg'
import NPECheck from './../util/NPECheck'
import ConvertTimeUTC from './../util/ConvertTimeUTC'
import CopyToClipboard from './../util/CopyToClipboard'

export default class APITokens extends Component{
	constructor(props) {
		super(props);
		this.state = {};
	}
	componentDidMount() {
		this.context.actions.listAuthTokens();
	}
	createAuthToken(){
		this.context.actions.createAuthToken()
		.then(this.context.actions.listAuthTokens);
	}
	setAuthTokenStatus(tokenString, status){
		this.context.actions.setAuthTokenStatus(tokenString, status)
		.then(this.context.actions.listAuthTokens);
	}
	deleteAuthToken(){
		this.context.actions.deleteAuthToken()
		.then(this.context.actions.listAuthTokens);
	}
	renderHeader(){
		return (

			 		API Tokens

			 		Owner

			 		Created

			 		Status

			 	 this.createAuthToken()}>
			 		{this.renderCreateTokenText()}

		);
	}
	renderCreateTokenText(){
		if(NPECheck(this.props, 'settings/tokens/createTokenXHR', false)) {
			return (

			);
		}

		return '+ Create Token';
	}
	renderContent(){
		let errorMsg = NPECheck(this.props, 'settings/tokens/tokenPageError', false);
		if(errorMsg) {
			return this.renderError(errorMsg);
		}

		let tokens = NPECheck(this.props, 'settings/tokens/allTokens', []);
		return (

				{tokens.sort((firstEvent, secondEvent) => (firstEvent.created > secondEvent.created) ? -1 : 1 ).map((token, i) => {
					let statusClassName = (token.status == 'ACTIVE') ? 'Active' : 'Inactive';
					 let dateCreated = new Date(token.created);
					 let dateCreatedUTC = ConvertTimeUTC(dateCreated);

					return (

								{this.renderTokenString(token.token)}
								{token.username}
								{dateCreatedUTC}
								{token.status}
								{this.renderIcons(token)}

							{this.renderDeleteToken(token)}

					);
				})}

		);
	}
	renderIcons(token){
		let statusToolTip = 'Deactivate Token';
		let newStatus = 'INACTIVE';
		let statusIcon = 'icon icon-dis-inactive';
		let contents = [];

		if(token.status == 'INACTIVE') {
			statusToolTip = 'Activate Token';
			newStatus = 'ACTIVE';
			statusIcon = 'icon icon-dis-active';
		}

		let infoIconDOM = (
			  {}} data-tip="A token must be INACTIVE to be deleted" data-for="ToolTipTop"/>
		);

		let deleteIconDOM = (
			 this.context.actions.toggleTokenForDelete(token.token)} data-tip="Delete Token" data-for="ToolTipTop"/>
		);

		let statusIconDOM = (
			 this.setAuthTokenStatus(token.token, newStatus)} data-tip={statusToolTip} data-for="ToolTipTop"/>
		);

		contents.push(statusIconDOM);
		contents.push((token.status == 'INACTIVE') ? deleteIconDOM : infoIconDOM );

		return (

				{contents}

		);
	}
	renderTokenString(tokenString){
		let displayToken = '••••••••••••••••••••';
		let verb = 'Show';
		let isActive = NPECheck(this.props, 'settings/tokens/showingTokens').includes(tokenString);

		if(isActive) {
			verb = 'Hide';
			displayToken  = tokenString;
		}

		return (

					{tokenString}
					{displayToken}

					 |
					  this.context.actions.toggleShowingToken(tokenString)}>{verb}
					  CopyToClipboard(document.getElementById(tokenString))}>Copy

		);

	}
	renderDeleteToken(token){
		if( NPECheck(this.props, 'settings/tokens/selectedTokenForStatusUpdate', null) == token.token
			|| NPECheck(this.props, 'settings/tokens/selectedTokenForDelete', null) ==  token.token) {

			let errorMsg = NPECheck(this.props, 'settings/tokens/tokenItemError', null);
			if(errorMsg) return this.renderError(errorMsg);

			if( NPECheck(this.props, 'settings/tokens/statusXHR', false)
			    || NPECheck(this.props, 'settings/tokens/deleteTokenXHR', false)) {
				return (
					<Loader />
				);
			}

			return (
				<CenteredConfirm message="Are you sure you want to delete this token? This is permanent"
							     confirmButtonText="Delete"
							     confirmButtonStyle={{}}
							     onConfirm={() => this.deleteAuthToken()}
							     onCancel={() => this.context.actions.toggleTokenForDelete() }/>
			);
		}
	}
	renderError(errorMsg){
		return (
			<Msg text={errorMsg}
				 close={() => this.context.actions.clearTokenItemError()}
				 style={{padding: '1rem 0'}}/>
		);
	}
	renderPageContent(){
		let isLoading = NPECheck(this.props, 'settings/tokens/tokensXHR', false);
		if(isLoading) {
			return (

					<Loader />

			);
		}

		let tokens = NPECheck(this.props, 'settings/tokens/allTokens', []);
		if(!tokens.length) {
			return (

No API Tokens found.

					<Btn className="LargeBlueButton"
						 text="Create Token"
						 onClick={() => this.createAuthToken()}/>

			);
		}

		return (
			<ControlRoom renderHeaderContent={() => this.renderHeader()}
						 renderBodyContent={() => this.renderContent()} />
		);
	}
	render(){
		return (

				{this.renderPageContent()}

		);
	}
}

APITokens.childContextTypes = {
    actions: React.PropTypes.object
};

APITokens.contextTypes = {
    actions: React.PropTypes.object
};


text:
Site is built on top of [WordPress](https://wordpress.org) with the help of the following tools and themes:

* [Bedrock](https://roots.io/bedrock/)
* [Vagrant](http://www.vagrantup.com/)
* [roots-wp-salt](https://roots.io/salts.html)
* [wp-cli-dotenv](https://github.com/aaemnnosttv/wp-cli-dotenv-command)
* [DailyTheme](http://www.robertbrodziak.com/daily)


text:
package org.emerjoin.hi.web.events;

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

/**
 * @author Mário Júnior
 */
public class TemplateLoadEvent extends HiEvent {

    private Map<String,Object> values = new HashMap<>();

    public void set(String key, Object value){
        if(key==null||key.isEmpty())
            throw new IllegalArgumentException("Key instance must not be null nor empty");
        if(value==null)
            throw new IllegalArgumentException("Value instance must not be null");
        values.put(key,value);

    }

    public void set(Map<String,Object> map){
        if(map==null)
            throw new IllegalArgumentException("Map instance must not be null");
        values.putAll(map);

    }

    public  Map<String,Object> getValues(){

        return this.values;

    }

}


text:
#ifndef LADSPA_INCLUDED
#define LADSPA_INCLUDED
#define LADSPA_VERSION "1.1"
#define LADSPA_VERSION_MAJOR 1
#define LADSPA_VERSION_MINOR 1
#ifdef __cplusplus
extern "C" {
#endif
typedef float LADSPA_Data;
typedef int LADSPA_Properties;
#define LADSPA_PROPERTY_REALTIME        0x1
#define LADSPA_PROPERTY_INPLACE_BROKEN  0x2
#define LADSPA_PROPERTY_HARD_RT_CAPABLE 0x4
#define LADSPA_IS_REALTIME(x)        ((x) & LADSPA_PROPERTY_REALTIME)
#define LADSPA_IS_INPLACE_BROKEN(x)  ((x) & LADSPA_PROPERTY_INPLACE_BROKEN)
#define LADSPA_IS_HARD_RT_CAPABLE(x) ((x) & LADSPA_PROPERTY_HARD_RT_CAPABLE)
typedef int LADSPA_PortDescriptor;
#define LADSPA_PORT_INPUT   0x1
#define LADSPA_PORT_OUTPUT  0x2
#define LADSPA_PORT_CONTROL 0x4
#define LADSPA_PORT_AUDIO   0x8
#define LADSPA_IS_PORT_INPUT(x)   ((x) & LADSPA_PORT_INPUT)
#define LADSPA_IS_PORT_OUTPUT(x)  ((x) & LADSPA_PORT_OUTPUT)
#define LADSPA_IS_PORT_CONTROL(x) ((x) & LADSPA_PORT_CONTROL)
#define LADSPA_IS_PORT_AUDIO(x)   ((x) & LADSPA_PORT_AUDIO)
typedef int LADSPA_PortRangeHintDescriptor;
#define LADSPA_HINT_BOUNDED_BELOW   0x1
#define LADSPA_HINT_BOUNDED_ABOVE   0x2
#define LADSPA_HINT_TOGGLED         0x4
#define LADSPA_HINT_SAMPLE_RATE     0x8
#define LADSPA_HINT_LOGARITHMIC     0x10
#define LADSPA_HINT_INTEGER         0x20
#define LADSPA_HINT_DEFAULT_MASK    0x3C0
#define LADSPA_HINT_DEFAULT_NONE    0x0
#define LADSPA_HINT_DEFAULT_MINIMUM 0x40
#define LADSPA_HINT_DEFAULT_LOW     0x80
#define LADSPA_HINT_DEFAULT_MIDDLE  0xC0
#define LADSPA_HINT_DEFAULT_HIGH    0x100
#define LADSPA_HINT_DEFAULT_MAXIMUM 0x140
#define LADSPA_HINT_DEFAULT_0       0x200
#define LADSPA_HINT_DEFAULT_1       0x240
#define LADSPA_HINT_DEFAULT_100     0x280
#define LADSPA_HINT_DEFAULT_440     0x2C0
#define LADSPA_IS_HINT_BOUNDED_BELOW(x)   ((x) & LADSPA_HINT_BOUNDED_BELOW)
#define LADSPA_IS_HINT_BOUNDED_ABOVE(x)   ((x) & LADSPA_HINT_BOUNDED_ABOVE)
#define LADSPA_IS_HINT_TOGGLED(x)         ((x) & LADSPA_HINT_TOGGLED)
#define LADSPA_IS_HINT_SAMPLE_RATE(x)     ((x) & LADSPA_HINT_SAMPLE_RATE)
#define LADSPA_IS_HINT_LOGARITHMIC(x)     ((x) & LADSPA_HINT_LOGARITHMIC)
#define LADSPA_IS_HINT_INTEGER(x)         ((x) & LADSPA_HINT_INTEGER)
#define LADSPA_IS_HINT_HAS_DEFAULT(x)     ((x) & LADSPA_HINT_DEFAULT_MASK)
#define LADSPA_IS_HINT_DEFAULT_MINIMUM(x) \
    (((x) & LADSPA_HINT_DEFAULT_MASK) == LADSPA_HINT_DEFAULT_MINIMUM)
#define LADSPA_IS_HINT_DEFAULT_LOW(x) \
    (((x) & LADSPA_HINT_DEFAULT_MASK) == LADSPA_HINT_DEFAULT_LOW)
#define LADSPA_IS_HINT_DEFAULT_MIDDLE(x) \
    (((x) & LADSPA_HINT_DEFAULT_MASK) == LADSPA_HINT_DEFAULT_MIDDLE)
#define LADSPA_IS_HINT_DEFAULT_HIGH(x) \
    (((x) & LADSPA_HINT_DEFAULT_MASK) == LADSPA_HINT_DEFAULT_HIGH)
#define LADSPA_IS_HINT_DEFAULT_MAXIMUM(x) \
    (((x) & LADSPA_HINT_DEFAULT_MASK) == LADSPA_HINT_DEFAULT_MAXIMUM)
#define LADSPA_IS_HINT_DEFAULT_0(x) \
    (((x) & LADSPA_HINT_DEFAULT_MASK) == LADSPA_HINT_DEFAULT_0)
#define LADSPA_IS_HINT_DEFAULT_1(x) \
    (((x) & LADSPA_HINT_DEFAULT_MASK) == LADSPA_HINT_DEFAULT_1)
#define LADSPA_IS_HINT_DEFAULT_100(x) \
    (((x) & LADSPA_HINT_DEFAULT_MASK) == LADSPA_HINT_DEFAULT_100)
#define LADSPA_IS_HINT_DEFAULT_440(x) \
    (((x) & LADSPA_HINT_DEFAULT_MASK) == LADSPA_HINT_DEFAULT_440)
typedef struct _LADSPA_PortRangeHint {
	LADSPA_PortRangeHintDescriptor HintDescriptor;
	LADSPA_Data LowerBound;
	LADSPA_Data UpperBound;
} LADSPA_PortRangeHint;
typedef void * LADSPA_Handle;
typedef struct _LADSPA_Descriptor {
	unsigned long UniqueID;
	const char * Label;
	LADSPA_Properties Properties;
	const char * Name;
	const char * Maker;
	const char * Copyright;
	unsigned long PortCount;
	const LADSPA_PortDescriptor * PortDescriptors;
	const char * const * PortNames;
	const LADSPA_PortRangeHint * PortRangeHints;
	void * ImplementationData;
	LADSPA_Handle (*instantiate)(
	    const struct _LADSPA_Descriptor * Descriptor,
	    unsigned long SampleRate
	);
	void (*connect_port)(
	    LADSPA_Handle Instance,
	    unsigned long Port,
	    LADSPA_Data * DataLocation
	);
	void (*activate)(LADSPA_Handle Instance);
	void (*run)(LADSPA_Handle Instance, unsigned long SampleCount);
	void (*run_adding)(LADSPA_Handle Instance, unsigned long SampleCount);
	void (*set_run_adding_gain)(LADSPA_Handle Instance, LADSPA_Data Gain);
	void (*deactivate)(LADSPA_Handle Instance);
	void (*cleanup)(LADSPA_Handle Instance);
} LADSPA_Descriptor;
#if WIN32 || _WIN32
// weird clang bug workaround
#if (__clang__ != 1) || (_X86_ != 1) || _MSC_VER
__declspec(dllexport)
#endif
#endif
const LADSPA_Descriptor * ladspa_descriptor(unsigned long Index);
typedef const LADSPA_Descriptor *
    (*LADSPA_Descriptor_Function)(unsigned long Index);
#ifdef __cplusplus
}
#endif
#endif


text:
package goryachev.common.io;
import goryachev.common.util.CKit;

// Format:
//   long signature;
//   segments[]
//   {
//       byte id;
//       <data>
//   }
public abstract class PrimitiveHandler
{
	public abstract Object read(PrimitiveInputStream in) throws Exception;

	public abstract void write(Object x, PrimitiveOutputStream out) throws Exception;

	//

	private byte id;

	public PrimitiveHandler(byte id)
	{
		this.id = id;
	}

	public byte getID()
	{
		return id;
	}

	public boolean isPrimitive()
	{
		return true;
	}

	// do not remove - used in string handler, see readShortString()
	protected void storeWithID(Object x, PrimitiveOutputStream out) throws Exception
	{
		out.writeRawByte(getID());
		write(x, out);
	}

	public void readContainer(PrimitiveInputStream in, DContainer c) throws Exception
	{
		Object x = read(in);
		c.add(x);
	}

	protected static String readString(PrimitiveInputStream in, int sz) throws Exception
	{
		byte[] b = new byte[sz];
		in.readRawBytes(b);
		return new String(b, CKit.CHARSET_UTF8);
	}
}


text:
#pragma once

#include "rae/core/Types.hpp"
#include "rae/entity/Table.hpp"

#include "rae/entity/Hierarchy.hpp"
#include "rae/scene/Transform.hpp"
#include "rae/core/ISystem.hpp"
#include "rae/visual/Box.hpp"

namespace rae
{

struct Changed
{
};

// The primary hierarchy is done with Parent and Children components. Primary hierarchy usually means that
// the parent transforms are propagated to the children. The localTransform is the childs transform in relation
// to its parent. In UI the Children are usually part of the Parents Layout.
using Parent = Id;
using Children = Array<Id>;

// A secondary hierarchy, which usually contains things like KeyLines, which are not part of the UI layout, but
// the transforms can still be propagated, and the localTransform is in relation to its parent. We just might
// skip the layouting part, so that the KeyLine itself can affect the layout, but not be affected by it.
using Owner = Id;
using Owned = Array<Id>;

struct Sphere
{
};

class TransformSystem : public ISystem
{
public:
	TransformSystem();

	UpdateStatus update() override;

	void syncLocalAndWorldTransforms();

	bool hasAnyTransformChanged() const;

	// Process the while hierarchy including the parentId itself.
	void processHierarchy(Id parentId, std::function<void(Id)> process);
	// Process the hierarchy. If process returns false, we don't process it's children,
	// but still continue to process it's siblings and their children.
	void processHierarchySkippable(Id parentId, std::function<bool(Id)> process);
	// Process only direct children, so doesn't include the parentId.
	void processChildren(Id parentId, std::function<void(Id)> process);
	// Process the siblings of the given entity (they have the same parent). Also process entity itself.
	void processSiblingsInclusive(Id id, std::function<void(Id)> process);
	// Process the siblings of the given entity (they have the same parent). Don't process the entity.
	void processSiblingsExclusive(Id id, std::function<void(Id)> process);

	void addTransform(Id id, const Transform& transform);

	bool hasLocalTransform(Id id) const;
	const Transform& getLocalTransform(Id id) const;

	void setLocalPosition(Id id, const vec3& position);
	const vec3& getLocalPosition(Id id);
	void setLocalRotation(Id id, const qua& rotation);
	const qua& getLocalRotation(Id id);
	void setLocalScale(Id id, const vec3& scale);
	const vec3& getLocalScale(Id id);

	bool hasWorldTransform(Id id) const;
	const Transform& getWorldTransform(Id id) const;

	void setWorldPosition(Id id, const vec3& position);
	const vec3& getWorldPosition(Id id);
	void setWorldRotation(Id id, const qua& rotation);
	const qua& getWorldRotation(Id id);
	void setWorldScale(Id id, const vec3& scale);
	const vec3& getWorldScale(Id id);

	int transformCount() const { return m_localTransforms.size(); }
	const Table<Transform>& localTransforms() const { return m_localTransforms; }
	const Table<Transform>& worldTransforms() const { return m_worldTransforms; }

	// Get only the toplevel ids. So if there's parent child relationships, then only return the parents.
	Array<Id> entitiesForTransform(const Array<Id>& ids) const;

	void translate(Id id, const vec3& delta);
	void translate(const Array<Id>& ids, const vec3& delta);

	void rotate(Id id, const qua& delta);
	void rotate(const Array<Id>& ids, const qua& delta);
	void rotateAround(const Array<Id>& ids, const qua& delta, const vec3& pivot);

	void addChild(Id parent, Id child); // Does not fix existing hierarchy
	void setParent(Id child, Id parent); // Does not fix existing hierarchy

	//void addParent(Id id);
	bool hasParent(Id id) const;
	Id getParent(Id id) const;

	//void addChildren(Id id);
	bool hasChildren(Id id) const;
	const Array<Id>& getChildren(Id id) const;
	void moveToTop(Id parentId, Id childIdToMove);
	void moveToTopInParent(Id childIdToMove);
	void moveToBottom(Id parentId, Id childIdToMove);
	void moveToBottomInParent(Id childIdToMove);

	// Pivot is defined in normalized coordinates -1 to 1 (in relation to own size)
	// and it will affect how the origin of the current entity will be interpreted.
	bool hasPivot(Id id) const;
	void addPivot(Id id, const Pivot& pivot);
	void setPivot(Id id, const Pivot& pivot);
	const Pivot& getPivot(Id id) const;

	// RAE_TODO add functions to get full 2D transform
	/*
	struct Transform2D
	{
		Transform
		Pivot
		Box
	}?
	*/
	const Table<Box>& boxes() const { return m_boxes; }
	bool hasBox(Id id) const;
	void addBox(Id id, const Box& box);
	void setBox(Id id, const Box& box);
	const Box& getBox(Id id) const;
	Box& modifyBox(Id id);

	const Table<Sphere>& spheres() const { return m_spheres; }
	bool hasSphere(Id id) const;
	void addSphere(Id id);
	const Sphere& getSphere(Id id) const;

	Box getAABBWorldSpace(Id id) const;

	String toString(Id id) const;

private:

	Transform& modifyLocalTransform(Id id);
	Transform& modifyWorldTransform(Id id);

	// Local transforms. Relative to parents.
	Table<Transform>	m_localTransforms;
	// World transform. The final coordinates to draw and hittest with.
	Table<Transform>	m_worldTransforms;
	bool				m_anyTransformUpdated = true;

	Table<Parent>		m_parents;
	Table<Changed>		m_parentChanged; // These are most likely not used properly. Also see Changed tag inside Table class.

	Table<Children>		m_childrens;
	Table<Changed>		m_childrenChanged;

	Table<Owner>		m_owners;
	Table<Owned>		m_owneds;

	// Pivot defines the relation between the localTransform.position and the Box.
	// By default if no Pivot is set, you get the default pivot which is vec(0,0,0).
	// The pivot is relational to the Box size, and its typical values run from
	// (-1,-1,-1) to (1,1,1), which mark the opposite corners of the Box. Y-up or Y-down in 3D or 2D
	// of course affect which corner is which. TopLeft2D corner is defined in Types.cpp as vec(-1,-1,0).
	Table<Pivot>		m_pivots;

	Table<Box>			m_boxes;
	// This is just an additional component to recognize spheres for RayTracer. They can also have a Box component.
	Table<Sphere>		m_spheres;
};

}


text:
#ifndef ALIANALYSISTASKSEXICZERO2XIPIFROMAODTRACKS_H
#define ALIANALYSISTASKSEXICZERO2XIPIFROMAODTRACKS_H

/* $Id$ */

//*************************************************************************
//
//Modified by Jianhui Zhu, zjh@mail.ccnu.edu.cn
//
//*************************************************************************

#include "TROOT.h"
#include "TSystem.h"

#include "AliAnalysisTaskSE.h"
#include "AliAODEvent.h"
#include "AliPID.h"
#include <AliAODRecoCascadeHF.h>
#include "AliRDHFCutsXicZerotoXiPifromAODtracks.h"

/// \class AliAnalysisTaskSEXicZero2XiPifromAODtracks

class THnSparse;
class TH1F;
class TH2F;
class TClonesArray;
class AliAODPidHF;
class AliESDtrackCuts;
class AliESDVertex;
class AliAODMCParticle;

class AliAnalysisTaskSEXicZero2XiPifromAODtracks : public AliAnalysisTaskSE
{
 public:
  AliAnalysisTaskSEXicZero2XiPifromAODtracks();
  AliAnalysisTaskSEXicZero2XiPifromAODtracks(const Char_t* name, AliRDHFCutsXicZerotoXiPifromAODtracks* cuts, Bool_t writeVariableTree=kTRUE, Bool_t anaOmegacZero=kFALSE);
  virtual ~AliAnalysisTaskSEXicZero2XiPifromAODtracks();

  /// Implementation of interface methods
  virtual void UserCreateOutputObjects();
  virtual void Init();
  virtual void LocalInit() {Init();}
  virtual void UserExec(Option_t *option);
  virtual void Terminate(Option_t *option);

  void FillROOTObjects(AliAODRecoCascadeHF *xicobj,  AliAODcascade *casc, AliAODTrack *part1, AliAODMCParticle *mcpart, AliAODMCParticle *mcdaughter1, AliAODMCParticle *mcdaughterxi, Int_t mcnused, Bool_t isXiC);
  void MakeAnalysis(AliAODEvent *aod, TClonesArray *mcArray);

  /// set MC usage
  void SetMC(Bool_t theMCon) {fUseMCInfo = theMCon;}
  Bool_t GetMC() const {return fUseMCInfo;}
   void SetFillSignalOnly(Bool_t signalOnly) {fFillSignalOnly = signalOnly;}
  Bool_t GetFillSignalOnly() const {return fFillSignalOnly;}
  void SetFillBkgOnly(Bool_t bkgOnly) {fFillBkgOnly = bkgOnly;}
  Bool_t GetFillBkgOnly() const {return fFillBkgOnly;}

  void SetReconstructPrimVert(Bool_t a) { fReconstructPrimVert=a; }
  void SelectCascade( const AliVEvent *event,Int_t nCascades,Int_t &nSeleCasc, Bool_t *seleCascFlags);
  void SelectTrack( const AliVEvent *event, Int_t trkEntries, Int_t &nSeleTrks,Bool_t *seleFlags);

  AliAODRecoCascadeHF* MakeCascadeHF(AliAODcascade *casc, AliAODTrack *trk, AliAODEvent *aod, AliAODVertex *vert);
  AliAODVertex* ReconstructSecondaryVertex(AliAODcascade *casc, AliAODTrack *trk, AliAODEvent *aod);

 private:

  AliAnalysisTaskSEXicZero2XiPifromAODtracks(const AliAnalysisTaskSEXicZero2XiPifromAODtracks &source);
  AliAnalysisTaskSEXicZero2XiPifromAODtracks& operator=(const AliAnalysisTaskSEXicZero2XiPifromAODtracks& source);

  //Da modificare
  void DefineTreeVariables();
  void DefineGeneralHistograms();

  //Da modificare
  //  void DefineAnalysisHistograms();

  AliAODVertex *CallPrimaryVertex(AliAODcascade *casc, AliAODTrack *trk, AliAODEvent *evt);
  AliAODVertex* PrimaryVertex(const TObjArray *trkArray,AliVEvent *event);

  Int_t MatchtoMC(AliAODRecoCascadeHF *exobj, Int_t pdgabs, Int_t pdgabscasc, Int_t *pdgDg,Int_t *pdgDgcasc,Int_t *pdgDgv0, TClonesArray *mcArray);
  Int_t MatchToMCCascade(AliAODcascade *theCascade, Int_t pdgabscasc, Int_t *pdgDgcasc, Int_t *pdgDgv0, TClonesArray *mcArray);
  Int_t MatchToMCXicZero(Int_t pdgabs,TClonesArray *mcArray, Int_t dgLabels[10],Int_t ndg,Int_t ndgCk, const Int_t *pdgDg);

  Bool_t fUseMCInfo;          /// Use MC info
  Bool_t fFillSignalOnly;     /// Fill only the signal in MC
  Bool_t fFillBkgOnly;        /// Fill only the bkg in MC
  Bool_t fAnaOmegacZero;      /// flag to decide analysis OmegacZero
  TList *fOutput;             //!<! User output slot 1 // general histos
  TList *fOutputAll;          //!<! User output slot 3 // Analysis histos
  TList *fListCuts;           //!<! User output slot 2 // Cuts
  TH1F *fCEvents;             /// Histogram to check selected events
  TH1F *fHTrigger;            /// Histograms to check trigger
  TH1F *fHCentrality;         /// histogram to check centrality
  AliRDHFCutsXicZerotoXiPifromAODtracks *fAnalCuts;      /// Cuts - sent to output slot 2
  Bool_t fIsEventSelected;           /// flag for event selected
  Bool_t    fWriteVariableTree;       /// flag to decide whether to write the candidate variables on a tree variables
  TTree    *fVariablesTree;           //!<! tree of the candidate variables after track selection on output slot 4
  Bool_t fReconstructPrimVert;            /// Reconstruct primary vertex excluding candidate tracks
  Bool_t fIsMB;            /// Is MB event
  Bool_t fIsSemi;          /// is semi-central trigger event
  Bool_t fIsCent;          /// is central trigger event
  Bool_t fIsINT7;          /// is int7 trigger event
  Bool_t fIsEMC7;          /// is emc7 trigger event
  Float_t *fCandidateVariables;     //!<! variables to be written to the tree
  AliAODVertex *fVtx1;              /// primary vertex
  AliESDVertex *fV1;                /// primary vertex
  Double_t fBzkG;                   /// magnetic field value [kG]
  Float_t  fCentrality;             /// centrality
  Float_t  fTriggerCheck;           /// Trigger information

  //--------------------- My histograms ------------------
  THnSparse*  fHistoXicMass;        //!<! xic mass spectra

  TH1F*  fHistoDcaPiCasc;                    //!<! DCA between pi and cascade

  TH1F*  fHistoXiMass;                       //!<! mass of xi
  TH1F*  fHistoCascDcaXiDaughters;           //!<! DCA of xi daughgers
  TH1F*  fHistoCascDcaV0Daughters;           //!<! DCA of v0 daughters
  TH1F*  fHistoCascDcaV0ToPrimVertex;        //!<! DCA of v0 to primary vertex
  TH1F*  fHistoCascDcaPosToPrimVertex;       //!<! DCA of positive track to primary vertex
  TH1F*  fHistoCascDcaNegToPrimVertex;       //!<! DCA of negative track to primary vertex
  TH1F*  fHistoCascDcaBachToPrimVertex;      //!<! DCA of bachelor track to primary vertex
  TH1F*  fHistoCascCosPAXiPrim;              //!<! Cosine pointing angle of Xi to primary vertex
  TH1F*  fHistoXiPt;                         //!<! Xi pt

  TH1F*  fHistoPiPt;                         //!<! Pion pT
  TH1F*  fHistoPid0;                         //!<! pion d0
  TH1F*  fHistonSigmaTPCpi;                  //!<! nSigma of TPC pion
  TH1F*  fHistonSigmaTOFpi;                  //!<! nSigma of TOF pion
  TH1F*  fHistoProbPion;                     //!<! Probability to be pion

  TH1F*  fHSelectedCascadePerEv;           //!<! Cascades per event
  TH1F*  fHSelectedTracksPerEv;            //!<! Tracks per event

  TH2F*  fHistoXiMassvsPtRef;                    //!<! Reference Xi mass spectra
  TH2F*  fHistoXiMassvsPtRef2;                    //!<! Reference Xi mass spectra
  TH2F*  fHistoXiMassvsPtRef3;                    //!<! Reference Xi mass spectra
  TH2F*  fHistoXiMassvsPtRef4;                    //!<! Reference Xi mass spectra
  TH2F*  fHistoXiMassvsPtRef5;                    //!<! Reference Xi mass spectra
  TH2F*  fHistoXiMassvsPtRef6;                    //!<! Reference Xi mass spectra
  TH1F*  fHistoPiPtRef;                      //!<! Reference pi spectra

  /// \cond CLASSIMP
  ClassDef(AliAnalysisTaskSEXicZero2XiPifromAODtracks,2); /// class for XicZero->Xipi
  /// \endcond
};
#endif


text:
/*
 * This file is available under and governed by the GNU General Public
 * License version 2 only, as published by the Free Software Foundation.
 * However, the following notice accompanied the original version of this
 * file:
 *
 * Written by Doug Lea with assistance from members of JCP JSR-166
 * Expert Group and released to the public domain, as explained at
 * http://creativecommons.org/publicdomain/zero/1.0/
 */

package java.util.concurrent.atomic;

import java.util.function.LongBinaryOperator;
import java.util.function.LongUnaryOperator;

/**
 * A {@code long} value that may be updated atomically.  See the
 * {@link java.util.concurrent.atomic} package specification for
 * description of the properties of atomic variables. An
 * {@code AtomicLong} is used in applications such as atomically
 * incremented sequence numbers, and cannot be used as a replacement
 * for a {@link java.lang.Long}. However, this class does extend
 * {@code Number} to allow uniform access by tools and utilities that
 * deal with numerically-based classes.
 *
 * @since 1.5
 * @author Doug Lea
 */
public class AtomicLong extends Number implements java.io.Serializable {
    private static final long serialVersionUID = 1927816293512124184L;

    /* J2ObjC removed.
    private static final sun.misc.Unsafe U = sun.misc.Unsafe.getUnsafe();
    private static final long VALUE;
    */

    /**
     * Records whether the underlying JVM supports lockless
     * compareAndSwap for longs. While the Unsafe.compareAndSwapLong
     * method works in either case, some constructions should be
     * handled at Java level to avoid locking user-visible locks.
     */
    static final boolean VM_SUPPORTS_LONG_CAS = VMSupportsCS8();

    /**
     * Returns whether underlying JVM supports lockless CompareAndSet
     * for longs. Called only once and cached in VM_SUPPORTS_LONG_CAS.
     */
    private static native boolean VMSupportsCS8() /*-[
      return sizeof(jlong) == sizeof(volatile_jlong);
    ]-*/;

    /* J2ObjC removed.
    static {
        try {
            VALUE = U.objectFieldOffset
                (AtomicLong.class.getDeclaredField("value"));
        } catch (ReflectiveOperationException e) {
            throw new Error(e);
        }
    }
    */

    private volatile long value;

    /**
     * Creates a new AtomicLong with the given initial value.
     *
     * @param initialValue the initial value
     */
    public AtomicLong(long initialValue) {
        value = initialValue;
    }

    /**
     * Creates a new AtomicLong with initial value {@code 0}.
     */
    public AtomicLong() {
    }

    /**
     * Gets the current value.
     *
     * @return the current value
     */
    public final long get() {
        return value;
    }

    /**
     * Sets to the given value.
     *
     * @param newValue the new value
     */
    public final native void set(long newValue) /*-[
      __c11_atomic_store(&self->value_, newValue, __ATOMIC_SEQ_CST);
    ]-*/;

    /**
     * Eventually sets to the given value.
     *
     * @param newValue the new value
     * @since 1.6
     */
    public final native void lazySet(long newValue) /*-[
      __c11_atomic_store(&self->value_, newValue, __ATOMIC_RELEASE);
    ]-*/;

    /**
     * Atomically sets to the given value and returns the old value.
     *
     * @param newValue the new value
     * @return the previous value
     */
    public final native long getAndSet(long newValue) /*-[
      return __c11_atomic_exchange(&self->value_, newValue, __ATOMIC_SEQ_CST);
    ]-*/;

    /**
     * Atomically sets the value to the given updated value
     * if the current value {@code ==} the expected value.
     *
     * @param expect the expected value
     * @param update the new value
     * @return {@code true} if successful. False return indicates that
     * the actual value was not equal to the expected value.
     */
    public final native boolean compareAndSet(long expect, long update) /*-[
      return __c11_atomic_compare_exchange_strong(
          &self->value_, &expect, update, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST);
    ]-*/;

    /**
     * Atomically sets the value to the given updated value
     * if the current value {@code ==} the expected value.
     *
     *
May fail
     * spuriously and does not provide ordering guarantees, so is
     * only rarely an appropriate alternative to {@code compareAndSet}.
     *
     * @param expect the expected value
     * @param update the new value
     * @return {@code true} if successful
     */
    public final native boolean weakCompareAndSet(long expect, long update) /*-[
      return __c11_atomic_compare_exchange_weak(
          &self->value_, &expect, update, __ATOMIC_RELAXED, __ATOMIC_RELAXED);
    ]-*/;

    /**
     * Atomically increments by one the current value.
     *
     * @return the previous value
     */
    public final long getAndIncrement() {
      return getAndAdd(1);
    }

    /**
     * Atomically decrements by one the current value.
     *
     * @return the previous value
     */
    public final long getAndDecrement() {
      return getAndAdd(-1);
    }

    /**
     * Atomically adds the given value to the current value.
     *
     * @param delta the value to add
     * @return the previous value
     */
    public final native long getAndAdd(long delta) /*-[
      return __c11_atomic_fetch_add(&self->value_, delta, __ATOMIC_SEQ_CST);
    ]-*/;

    /**
     * Atomically increments by one the current value.
     *
     * @return the updated value
     */
    public final long incrementAndGet() {
      return addAndGet(1);
    }

    /**
     * Atomically decrements by one the current value.
     *
     * @return the updated value
     */
    public final long decrementAndGet() {
      return addAndGet(-1);
    }

    /**
     * Atomically adds the given value to the current value.
     *
     * @param delta the value to add
     * @return the updated value
     */
    public final native long addAndGet(long delta) /*-[
      return __c11_atomic_fetch_add(&self->value_, delta, __ATOMIC_SEQ_CST) + delta;
    ]-*/;

    /**
     * Atomically updates the current value with the results of
     * applying the given function, returning the previous value. The
     * function should be side-effect-free, since it may be re-applied
     * when attempted updates fail due to contention among threads.
     *
     * @param updateFunction a side-effect-free function
     * @return the previous value
     * @since 1.8
     */
    public final long getAndUpdate(LongUnaryOperator updateFunction) {
        long prev, next;
        do {
            prev = get();
            next = updateFunction.applyAsLong(prev);
        } while (!compareAndSet(prev, next));
        return prev;
    }

    /**
     * Atomically updates the current value with the results of
     * applying the given function, returning the updated value. The
     * function should be side-effect-free, since it may be re-applied
     * when attempted updates fail due to contention among threads.
     *
     * @param updateFunction a side-effect-free function
     * @return the updated value
     * @since 1.8
     */
    public final long updateAndGet(LongUnaryOperator updateFunction) {
        long prev, next;
        do {
            prev = get();
            next = updateFunction.applyAsLong(prev);
        } while (!compareAndSet(prev, next));
        return next;
    }

    /**
     * Atomically updates the current value with the results of
     * applying the given function to the current and given values,
     * returning the previous value. The function should be
     * side-effect-free, since it may be re-applied when attempted
     * updates fail due to contention among threads.  The function
     * is applied with the current value as its first argument,
     * and the given update as the second argument.
     *
     * @param x the update value
     * @param accumulatorFunction a side-effect-free function of two arguments
     * @return the previous value
     * @since 1.8
     */
    public final long getAndAccumulate(long x,
                                       LongBinaryOperator accumulatorFunction) {
        long prev, next;
        do {
            prev = get();
            next = accumulatorFunction.applyAsLong(prev, x);
        } while (!compareAndSet(prev, next));
        return prev;
    }

    /**
     * Atomically updates the current value with the results of
     * applying the given function to the current and given values,
     * returning the updated value. The function should be
     * side-effect-free, since it may be re-applied when attempted
     * updates fail due to contention among threads.  The function
     * is applied with the current value as its first argument,
     * and the given update as the second argument.
     *
     * @param x the update value
     * @param accumulatorFunction a side-effect-free function of two arguments
     * @return the updated value
     * @since 1.8
     */
    public final long accumulateAndGet(long x,
                                       LongBinaryOperator accumulatorFunction) {
        long prev, next;
        do {
            prev = get();
            next = accumulatorFunction.applyAsLong(prev, x);
        } while (!compareAndSet(prev, next));
        return next;
    }

    /**
     * Returns the String representation of the current value.
     * @return the String representation of the current value
     */
    public String toString() {
        return Long.toString(get());
    }

    /**
     * Returns the value of this {@code AtomicLong} as an {@code int}
     * after a narrowing primitive conversion.
     * @jls 5.1.3 Narrowing Primitive Conversions
     */
    public int intValue() {
        return (int)get();
    }

    /**
     * Returns the value of this {@code AtomicLong} as a {@code long}.
     * Equivalent to {@link #get()}.
     */
    public long longValue() {
        return get();
    }

    /**
     * Returns the value of this {@code AtomicLong} as a {@code float}
     * after a widening primitive conversion.
     * @jls 5.1.2 Widening Primitive Conversions
     */
    public float floatValue() {
        return (float)get();
    }

    /**
     * Returns the value of this {@code AtomicLong} as a {@code double}
     * after a widening primitive conversion.
     * @jls 5.1.2 Widening Primitive Conversions
     */
    public double doubleValue() {
        return (double)get();
    }

    /*
     * These ObjC methods are needed to support subclassing of NSNumber.
     * objCType is used by descriptionWithLocale:.
     * getValue: is used by copyWithZone:.
     */
    /*-[
    - (const char *)objCType {
      return "q";
    }

    - (void)getValue:(void *)buffer {
      *((long long int *) buffer) = value_;
    }
    ]-*/

}


text:
using System.Collections.Generic;

namespace HaloOnline.Server.Model.GameStatistics
{
    public class UserChallenges
    {
        public int Version { get; set; }
        public List<Challenge> Challenges { get; set; }
    }
}


text:
import os
try:
    from PIL import Image as PILImage
except ImportError:
    try:
        import Image as PILImage
    except ImportError:
        raise ImportError("The Python Imaging Library was not found.")

import logging
logger = logging.getLogger(__name__)

from django.db import models
from django.utils import six
from django.utils.translation import ugettext_lazy as _

from filer import settings as filer_settings
from filer.models.filemodels import File
from filer.utils.filer_easy_thumbnails import FilerThumbnailer
from filer.utils.pil_exif import get_exif_for_file

class BaseImage(File):
    SIDEBAR_IMAGE_WIDTH = 210
    DEFAULT_THUMBNAILS = {
        'admin_clipboard_icon': {'size': (32, 32), 'crop': True,
                                 'upscale': True},
        'admin_sidebar_preview': {'size': (SIDEBAR_IMAGE_WIDTH, 10000)},
        'admin_directory_listing_icon': {'size': (48, 48),
                                         'crop': True, 'upscale': True},
        'admin_tiny_icon': {'size': (32, 32), 'crop': True, 'upscale': True},
    }
    file_type = 'Image'
    _icon = "image"

    _height = models.IntegerField(null=True, blank=True)
    _width = models.IntegerField(null=True, blank=True)

    default_alt_text = models.CharField(_('default alt text'), max_length=255, blank=True, null=True)
    default_caption = models.CharField(_('default caption'), max_length=255, blank=True, null=True)

    subject_location = models.CharField(_('subject location'), max_length=64, null=True, blank=True,
                                        default=None)

    @classmethod
    def matches_file_type(cls, iname, ifile, request):
        # This was originally in admin/clipboardadmin.py  it was inside of a try
        # except, I have moved it here outside of a try except because I can't
        # figure out just what kind of exception this could generate... all it was
        # doing for me was obscuring errors...
        # --Dave Butler <croepha@gmail.com>
        iext = os.path.splitext(iname)[1].lower()
        return iext in ['.jpg', '.jpeg', '.png', '.gif']

    def save(self, *args, **kwargs):
        self.has_all_mandatory_data = self._check_validity()
        try:
            # do this more efficient somehow?
            self.file.seek(0)
            self._width, self._height = PILImage.open(self.file).size
        except Exception:
            # probably the image is missing. nevermind.
            pass
        super(BaseImage, self).save(*args, **kwargs)

    def _check_validity(self):
        if not self.name:
            return False
        return True

    def sidebar_image_ratio(self):
        if self.width:
            return float(self.width) / float(self.SIDEBAR_IMAGE_WIDTH)
        else:
            return 1.0

    def _get_exif(self):
        if hasattr(self, '_exif_cache'):
            return self._exif_cache
        else:
            if self.file:
                self._exif_cache = get_exif_for_file(self.file)
            else:
                self._exif_cache = {}
        return self._exif_cache
    exif = property(_get_exif)

    def has_edit_permission(self, request):
        return self.has_generic_permission(request, 'edit')

    def has_read_permission(self, request):
        return self.has_generic_permission(request, 'read')

    def has_add_children_permission(self, request):
        return self.has_generic_permission(request, 'add_children')

    def has_generic_permission(self, request, permission_type):
        """
        Return true if the current user has permission on this
        image. Return the string 'ALL' if the user has all rights.
        """
        user = request.user
        if not user.is_authenticated():
            return False
        elif user.is_superuser:
            return True
        elif user == self.owner:
            return True
        elif self.folder:
            return self.folder.has_generic_permission(request, permission_type)
        else:
            return False

    @property
    def label(self):
        if self.name in ['', None]:
            return self.original_filename or 'unnamed file'
        else:
            return self.name

    @property
    def width(self):
        return self._width or 0

    @property
    def height(self):
        return self._height or 0

    def _generate_thumbnails(self, required_thumbnails):
        _thumbnails = {}
        for name, opts in six.iteritems(required_thumbnails):
            try:
                opts.update({'subject_location': self.subject_location})
                thumb = self.file.get_thumbnail(opts)
                _thumbnails[name] = thumb.url
            except Exception as e:
                # catch exception and manage it. We can re-raise it for debugging
                # purposes and/or just logging it, provided user configured
                # proper logging configuration
                if filer_settings.FILER_ENABLE_LOGGING:
                    logger.error('Error while generating thumbnail: %s',e)
                if filer_settings.FILER_DEBUG:
                    raise
        return _thumbnails

    @property
    def icons(self):
        required_thumbnails = dict(
            (size, {'size': (int(size), int(size)),
                    'crop': True,
                    'upscale': True,
                    'subject_location': self.subject_location})
            for size in filer_settings.FILER_ADMIN_ICON_SIZES)
        return self._generate_thumbnails(required_thumbnails)

    @property
    def thumbnails(self):
        return self._generate_thumbnails(BaseImage.DEFAULT_THUMBNAILS)

    @property
    def easy_thumbnails_thumbnailer(self):
        tn = FilerThumbnailer(
            file=self.file, name=self.file.name,
            source_storage=self.file.source_storage,
            thumbnail_storage=self.file.thumbnail_storage,
            thumbnail_basedir=self.file.thumbnail_basedir)
        return tn

    class Meta:
        app_label = 'filer'
        verbose_name = _('image')
        verbose_name_plural = _('images')
        abstract = True


text:
<!--

[comment]: # Licensed to the Apache Software Foundation (ASF) under one
[comment]: # or more contributor license agreements.  See the NOTICE file
[comment]: # distributed with this work for additional information
[comment]: # regarding copyright ownership.  The ASF licenses this file
[comment]: # to you under the Apache License, Version 2.0 (the
[comment]: # "License"); you may not use this file except in compliance
[comment]: # with the License.  You may obtain a copy of the License at
[comment]: #
[comment]: #   http://www.apache.org/licenses/LICENSE-2.0
[comment]: #
[comment]: # Unless required by applicable law or agreed to in writing,
[comment]: # software distributed under the License is distributed on an
[comment]: # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
[comment]: # KIND, either express or implied.  See the License for the
[comment]: # specific language governing permissions and limitations
[comment]: # under the License.

-->

# Rya Vagrant Example Documentation

The Rya Vagrant Example project allows users to quickly get up and running on Rya using a Virtual Machine.  Specifically, this project uses Vagrant to create a VM, install Rya on Accumulo, and configure the RDF4J Workbench Web Application to use Rya.

## Setting up the VM

### Installing Vagrant

The Rya Example Box VM requires Vagrant to install, configure, and run the VM.  Vagrant is freely available for many host operating systems.  More information about Vagrant (including installers) are available at <https://www.vagrantup.com/>

The Rya Example Box was developed using Vagrant 1.7.4 and Oracle Virtual Box 5.0.6.

If a user would rather not use Vagrant, expert users should be able to read through the [Rya-Example-Box Vagrantfile] and understand the operations that the Vagrantfile is performing to configure the VM for Rya.  These operations should be applicable to other Linux machines and VMs.

### Starting up the VM

Once Vagrant is installed, starting up the Rya-Example-Box is fairly straightforward.

1. Create a custom directory for the Rya Example Box (e.g., for windows users `c:\users\<user>\ryavagrant` or for Mac/Linux users `/home/<user>/ryavagrant`)

1. Download the [Rya-Example-Box Vagrantfile] to the custom directory.  Note that it must be named `Vagrantfile` with no extension.

1. Open a DOS prompt (Windows) or Terminal (Mac/Linux), change to the custom directory, and issue the command `vagrant up`.  Note that it may take up to 30 minutes to download, install, and configure Rya and all of the components.

### Verification

By default, the VM should be assigned the IP address of `192.168.33.10`.  This value is defined in the Vagrantfile and it is configurable.  All of the procedures in this in this document assume that the hostname `rya-example-box` resolves to the VM's IP address `192.168.33.10`.  The easiest way to do this is to add the entry `192.168.33.10 rya-example-box` to your machine's host file (e.g., for windows users modify `C:\Windows\System32\drivers\etc\hosts` or for Mac/Linux users modify `/etc/hosts`)

1. **Verify the Tomcat instance**:  Open a browser to <http://rya-example-box:8080/>.  You should see a webpage that says "It works!  If you're seeing this page via a web browser, it means you've setup Tomcat successfully. Congratulations!

1. **Verify the deployed RDF4J Server service**: Open your browser to <http://rya-example-box:8080/rdf4j-server/protocol> and you should see a `6` (this is the RDF4J Protocol Version).

1. **Verify the deployed RDF4J Workbench**: Open your browser to <http://rya-example-box:8080/rdf4j-workbench>

1. **Verify the deployed Rya Web**: Open your browser to <http://rya-example-box:8080/web.rya/sparqlQuery.jsp>

1. **Ssh into into the VM**: SSH from your host machine to `rya-example-box` with user/pass of vagrant/vagrant.

1. **Test the Accumulo shell**: After ssh'ing into the VM, run the command: `/home/vagrant/accumulo-1.6.5/bin/accumulo shell -u root -p root`

### Common Errors on the VM

Most of the time, the Vagrant script works perfectly and passes all of the verification.  However, below are a list of the common issues that we've seen and how to mitigate those issues

#### URLs for dependencies no longer valid

As dependencies such as Hadoop and Accumulo are updated, URLs for downloads of old versions can be come stale.
If this happens, the vagrant provisioning script should fail.  Scrolling back through the output should reveal
an error message indicating which download did not work.  To fix, try updating the version number specified in
the Vagrantfile.

#### Rya libraries are not installed
Run these two commands and see if you have any Rya files in the two lib directories:

```
    ls /var/lib/tomcat7/webapps/rdf4j-server/WEB-INF/lib/rya*
    ls /var/lib/tomcat7/webapps/rdf4j-workbench/WEB-INF/lib/rya*
```

If these files do note exists, open the vagrant file and look for the line `echo "Downloading Rya"`. Try working through those commands manually on your Vagrant VM.

#### RDF4J Workbench transformations are not installed

RDF4J Workbench requires a set of "transformations" for listing Rya in the RDF4J Workbench Repository list. The transforms are in this directory: /var/lib/tomcat7/webapps/rdf4j-workbench/transformations/

1. Verify that this file exists: create-RyaAccumuloSail.xsl
1. Verify that create.xsl has been updated for rya.  (run: "cat create.xsl | grep Rya" and make sure there's some stuff there.)

If these files do note exists, open the vagrant file and look for the line `echo "Downloading Rya"`. Try working through those commands manually on your Vagrant VM.

#### Other useful commands

Below is a list of other useful commands on the VMs

#####*Log into the VM*

1. Go to the folder containing "vagrantfile", run:
        `cd extras/vagrantExample/src/main/vagrant/`
2. Login -- no password required, uses crypto keys, run:
        `vagrant ssh`
Alternatively:
1. Log into the vm (run: `ssh vagrant@rya-example-box` with pass: `vagrant`)

#####*Running as Root*

Most start and stop scripts require running as root with variables, like %HADOOP_PREFIX% assigned.

1. Run thecommand as root preserving environment variables, run:
        `sudo -E thecommand theParameters`
The `-E` preserves environment variables from the current session.

Alternatively:

2. Switch to root (run: `su` with pass: `vagrant`)
2. Load the environment variables.  (run: `source .accumulo_rc.sh`)
2. Enter thecommand with parameters after the "#" prompt.
2. Exit when done (run: `exit` )

#####*Restart Tomcat*

1. Login into the VM, see above.
2. Restart tomcat, run:
        `sudo -E service tomcat7 restart`

#####*Restart Accumulo*

1. Login into the VM, see above.
2. Stop Accumulo (run: `sudo -E /home/vagrant/accumulo-1.6.5/bin/stop-all.sh`)
 * If `stop-all` doesn't complete, hit `ctrl-c` once and you should see `Initiating forced shutdown in 15 seconds`.  Wait 15 seconds.
1. Start Accumulo (run: `sudo -E /home/vagrant/accumulo-1.6.5/bin/start-all.sh`)

#####*Test and Restart Zookeeper*

1. Log into the vm, see above.
2. Ping Zookeeper, run:
        `echo ruok | (nc 127.0.0.1 2181 ; echo)`
  * If Zookeeper is okay, you should immediately see the response
        `imok`
  * Otherwise, restart Zookeeper, run:
        `sudo -E /home/vagrant/zookeeper-3.4.5-cdh4.5.0/bin/zkServer.sh start`

##### *Rya Process list*

List the processes specific to rya.

From the VM, run:
    `ryaps`
Output should look like this:
```
org.apache.zookeeper.server.quorum.QuorumPeerMain
org.apache.accumulo.start.Main monitor
org.apache.accumulo.start.Main tserver
org.apache.accumulo.start.Main master
org.apache.accumulo.start.Main gc
org.apache.accumulo.start.Main tracer
org.apache.catalina.startup.Bootstrap
```

##### *Re-provision, reseting the configuration*

If you are having issues, or modified the vagrantfile and want to put everything back as specified, then use the provision command. This will overwrite most settings.  It will not download nor unpack the libraries, unless you first remove there corresponding folders from the VM's vagrant home folder.

1. Go to the folder containing "vagrantfile", on the host machine, (not the VM),   run:
        `cd extras/vagrantExample/src/main/vagrant/`
2. Run the provision command:
        `vagrant provision`
To get the full factory-reset, do some of the following before you re-provision:

###### Logs

From within the VM, run:
    `sudo rm -r  zookeeper-3.4.5-cdh4.5.0/logs`
    `sudo rm -r accumulo-1.6.5/logs/`

###### Delete all data in Rya and Accumulo!
If you run into the issue where it repeatedly prints: `Waiting for accumulo to be initialized`
This will allow Accumulo to start up.  Remove the data, then reprovision as above.
From within the VM, run:
    `sudo rm -r /data`
    `sudo rm -r /var/zookeeper/`

## Interacting with Rya on the VM

### Connecting to Rya via RDF4J Workbench

The first step to using Rya via the RDF4J Workbench is to create a repository using the Rya Accumulo Store connector.

1. Open your browser to the [RDF4J Workbench](http://rya-example-box:8080/rdf4j-workbench)
2. Click on `New Repository`
3. Choose "Type" of `Rya Accumulo Store`, a Repository "ID" (e.g., `RyaAccumulo`), and a Repository "Title" (e.g., `Rya Accumulo`).  Click on `Next` when complete.
4. Enter the Rya Accumulo Store connection parameters.  The default parameters will connect to the Rya Example Box Acccumulo deployment (i.e., Accumulo User: `root`, Accumulo Password: `root`, Accumulo Instance: `dev`, Zookeepers: `localhost`, is Mock?: `false`).  Click on `Create` when complete.

### Uploading Data via RDF4J Workbench

Once we've created a Rya repository, we can load data into Rya via the RDF4J Workbench.

1.  Open your browser to the [RDF4J Workbench](http://rya-example-box:8080/rdf4j-workbench)
1. Verify that RDF4J Workbench is connected to Rya.  The RDF4j Workbench screen should have `Current Selections: Repository:	Rya Accumulo ( RyaAccumulo )` at the top of the page.
2. Click on `Add` on the left side of the page.
3. This page allows a user to add data either through a local file (uploaded through the browser), cut-and-pasted RDF, or a file located on the web.  For this example, let's choose a file on the web.  Set "Data Format" to `RDF/XML` and "Location of the RDF data you wish to upload" to `http://telegraphis.net/data/currencies/currencies.rdf`.  All other fields should remain empty.  Click on `Upload` when complete.

### Querying Data via RDF4J Workbench

Once we've created a Rya repository and uploaded data, we can query Rya via the RDF4J Workbench.

1. Open your browser to the [RDF4J Workbench](http://rya-example-box:8080/rdf4j-workbench)
1. Verify that RDF4J Workbench is connected to Rya.  The RDF4J Workbench screen should have `Current Selections: Repository:	Rya Accumulo ( RyaAccumulo )` at the top of the page.
1. Click on `Query` on the left side of the page.
1. Use the example SPARQL query below to query for Currencies with a Short Name of "dollar"

    ```
    PREFIX money:<http://telegraphis.net/ontology/money/money#>

    select ?name where {
       ?x a money:Currency .
       ?x money:shortName "dollar" .
       ?x money:name ?name .
    }
    ```

### Using the RDF4J REST Service

More information about the RDF4J REST HTTP Protocol is availible in the [RDF4J 2.3.1 Docs]
(http://docs.rdf4j.org/rest-api/)

### Using Rya Java Client
TODO

### Using Rya Web Client

The Rya Web Client provides a user a web gui to query Rya.  Once data has been loaded into Rya, we can run the same query as before

1. Open your browser to the [Rya Web](http://rya-example-box:8080/web.rya/sparqlQuery.jsp) page.
1. Use the example SPARQL query below to query for Currencies with a Short Name of "dollar"

    ```
    PREFIX money:<http://telegraphis.net/ontology/money/money#>

    select ?name where {
       ?x a money:Currency .
       ?x money:shortName "dollar" .
       ?x money:name ?name .
    }
    ```
1. You should see an XML document with the results.

## Developing Rya on the VM
TODO

### Enabling Secondary Indexing
TODO

### Resizing the VMs Disk space
Instructions for resizing a Vagrant/VirtualBox image can be found [here](http://www.midwesternmac.com/blogs/jeff-geerling/resizing-virtualbox-disk-image)

[Rya-Example-Box Vagrantfile]: Vagrantfile


text:
import { createStore, applyMiddleware } from 'redux';
import { browserHistory } from 'react-router';
import { routerMiddleware } from 'react-router-redux';
import thunkMiddleware from 'redux-thunk';
import rootReducer from '../reducers';

const routerMW = routerMiddleware(browserHistory);

function configureStore (initialState) {
  return createStore(
    rootReducer,
    initialState,
    applyMiddleware(
      routerMW,
      thunkMiddleware
    )
  );
}

export default configureStore;


text:
// <copyright file="ClientAddressInfo.cs" company="Automate The Planet Ltd.">
// Copyright 2021 Automate The Planet Ltd.
// 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.
// </copyright>
// <author>Anton Angelov</author>
// <site>http://automatetheplanet.com/</site>

using System;
using System.Linq;

namespace AdvancedStrategyDesignPattern.Data
{
    public class ClientAddressInfo
    {
        public string FullName { get; set; }

        public string Country { get; set; }

        public string Address1 { get; set; }

        public string City { get; set; }

        public string Phone { get; set; }

        public string Zip { get; set; }

        public string Email { get; set; }

        public string State { get; set; }
    }
}


text:
At the beginning of a Signum Framework application the `Starter` class calls the `Start` methods of the different modules used in the applications.

This different `Start` methods tipically:

* Include some necessary tables in the database using `SchemaBuilder.Include` method
* Maybe include some indexes.
* Register some queries in QueryLogic.Queries.
* Register some expressions in QueryLogic.Expression.
* Register some operations in OperationLogic using Graph<T>, tipically save and optionally delete.

There are of course a lot of other stuff, like registering processes, permission, ResetLazy, etc... but this actions are the bread and butter of most of the `Start` methods.

Example:

```C#
public static void Start(SchemaBuilder sb)
{
    if(sb.NotIncluded(MethodInfo.GetCurrentMethod()))
	{
		sb.Include<ProjectEntity>();

		sb.AddUniqueIndex((ProjectEntity p) => new { p.Name, p.Year });

		QueryLogic.Queries.Register(typeof(ProjectEntity), ()=>
			from p in Database.Query<ProjectEntity>()
			select new
			{
				Entity = p,
				p.Id,
				p.Name
			});

		QueryLogic.Expression.Register((ClientEntity c) => c.Projects())

		new Graph<ProjectEntity>.Execute(ProjectOperation.Save)
		{
		    CanBeNew = true,
			CanBeModified = true,
			Execute = (p, _) => {}
		}.Register();

		new Graph<ProjectEntity>.Delete(ProjectOperation.Delete)
		{
			Delete = (p, _) => { p.Delete() }
		}.Register();
	}
}
```

With this in mind, the generic method `SchemaBuilder.Include` has been expanded to return a `FluentInclude<T>` instance:

```C#
public class FluentInclude<T> where T : Entity
{
    public SchemaBuilder SchemaBuilder { get; private set; }
    public Table Table { get; private set; }
}
```

This class contains methods and extension methods that allow you to register stuff with fewer code.

It doesn't try to cover all the cases, only the common ones, that's why `FluentInclude` can be seen as dead-end road.

Other the other side it helps in removing the syntactic noise and leting you concentrate in the interesting stuff, and promotes keeping all the information for a particular entity together.

Example:

```C#
public static void Start(SchemaBuilder sb)
{
    if(sb.NotIncluded(MethodInfo.GetCurrentMethod()))
	{
		sb.Include<ProjectEntity>()
			.WithUniqueIndex(p => new { p.Name, p.Year })
			.WithSave(ProjectOpepration.Save)
			.WithDelete(ProjectOpepration.Delete)
			.WithQuery(p => new
			{
				Entity = p,
				p.Id,
				p.Name
			});
	}
}
```

## Available Methods

### WithIndex / WithUniqueIndex

Register an index in the Included entity, tipically a unique index on multiple columns or with a where condition.

```C#
public FluentInclude<T> WithUniqueIndex(Expression<Func<T, object>> fields, Expression<Func<T, bool>> where = null)
public FluentInclude<T> WithIndex(Expression<Func<T, object>> fields)
```

Internally calls `SchemaBuilder.AddUniqueIndex`.

### WithQuery

Extension method that registers a simple query in QueryLogic.Queeries using `typeof(T)` as `queryName`, with no filters, joins or column customizations, and just using the provided `simpleQuerySelector` as the `selector` of the only `Select` operator.

```C#
public static FluentInclude<T> WithQuery<T, Q>(this FluentInclude<T> fi, Expression<Func<T, Q>> simpleQuerySelector) where T : Entity
```

Internally calls `QueryLogic.Queries.Register`.

### WithExpresssionFrom

Register expressions from another type (`F`) that returns an `IQueryable<T>`, optionally providing a custom niceName, or `null` to keep the method name non-localizable.

```C#
public static FluentInclude<T> WithExpressionFrom<T, F>(this FluentInclude<T> fi, Expression<Func<F, IQueryable<T>>> lambdaToMethodOrProperty) where T : Entity
public static FluentInclude<T> WithExpressionFrom<T, F>(this FluentInclude<T> fi, Expression<Func<F, IQueryable<T>>> lambdaToMethodOrProperty, Func<string> niceName) where T : Entity

```

> Note: Given `ProjectEntity` with a property of type `ClientEntity`, where is the right place to register `client.Projects()` expression to navigate the property backwards?.
> Signum Framework encourages you to register it on `ProjectLogic` to keep `ClientLogic` clean of dependencies and more reusable, that's why `WithExpressionFrom`takes an
> Expression from `F` (a `ClientEntity`) to `IQueryable<T>` (a query of `ProjectEntity`).

Internally calls QueryLogic.Queries.Register;

### WithSave / WithDelete

Register trivial implementations of `Save` (CanBeNew = true, CanBeModified = true with no body) and Delete (just `e.Delete()` in the body).

```C#
public static FluentInclude<T> WithSave<T>(this FluentInclude<T> fi, ExecuteSymbol<T> saveOperation) where T : Entity
public static FluentInclude<T> WithDelete<T>(this FluentInclude<T> fi, DeleteSymbol<T> delete) where T : Entity
```

Internally instantiates a `Graph<T>.Execute`/`Graph<T>.Delete` and calls the extension method `OperationLogic.Register`.

### Others...

Most of this methods are implemented using extension methods. If you feel the need to remove some code duplication for registering
behaviour on a particular entity type, it's a good idea to create your own implementation:

```C#
public static WithMyCustomBehaviour(this FluentInclude<T> fi, ...)
```


text:
// vim: et sw=4 sts=4 tabstop=4
/*
 * 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.issc.ui;

import com.issc.Bluebit;
import com.issc.R;
import com.issc.util.Log;
import com.issc.util.Util;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class ActivityFileChooser extends ListActivity {

    private final static String PATH = "/sdcard/issc/";
    private final static String sFile = "_file";
    private final static String sName = "_file_name";
    private final static String sSize = "_file_size";

    private SimpleAdapter mAdapter;
    private ArrayList<Map<String, Object>> mEntries;
    private Button   mBtnChoose;
    private TextView mEmptyMsg;
    private TextView mFilename;
    private File mChosen;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file_chooser);

        mBtnChoose = (Button) findViewById(R.id.btn_choose);
        mEmptyMsg  = (TextView) findViewById(R.id.empty_msg);
        mFilename  = (TextView) findViewById(R.id.filename);

        String[] from = {sName, sSize};
        int[] to = {R.id.row_title, R.id.row_description};
        mEntries = new ArrayList<Map<String, Object>>();
        mAdapter = new SimpleAdapter(
                    this,
                    mEntries,
                    R.layout.row_normal,
                    from,
                    to);
        setListAdapter(mAdapter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        if (extras == null || !extras.containsKey(Bluebit.CHOOSE_PATH)) {
            fail("Please specify a directory to choose");
        } else {
            listFiles(extras.getString(Bluebit.CHOOSE_PATH));
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onListItemClick(ListView l, View v, int pos, long id) {
        mBtnChoose.setClickable(true);
        mChosen = (File)mEntries.get(pos).get(sFile);
        mFilename.setText(mChosen.getName());
    }

    public void onClickChoose(View v) {
        if (mChosen != null) {
            Intent intent = new Intent();
            intent.setData(Uri.fromFile(mChosen));
            this.setResult(Activity.RESULT_OK, intent);
            this.finish();
        }
    }

    private void fail(CharSequence msg) {
        mEntries.clear();
        mBtnChoose.setClickable(false);
        mEmptyMsg.setText(msg);
    }

    private void listFiles(String path) {
        File dir = new File(path);

        if (!dir.exists()) {
            if (!dir.mkdir()) {
                fail("Cannot make: " + path);
                return;
            }
        }

        if (!dir.canRead()) {
            fail("Cannot read: " + path);
            return;
        }

        if (!dir.isDirectory()) {
            fail("Not directory: " + path);
            return;
        }

        File[] files = dir.listFiles();

        for (int i = 0; i < files.length; i++) {
            if (files[i].isDirectory()) {
                continue;
            }
            final Map<String, Object> entry = new HashMap<String, Object>();
            entry.put(sFile, files[i]);
            entry.put(sName, files[i].getName());
            entry.put(sSize, files[i].length() + " bytes");
            mEntries.add(entry);
        }

        mAdapter.notifyDataSetChanged();

        if (mEntries.size() == 0) {
            fail("There is not any file under: " + path);
            return;
        } else {
            mBtnChoose.setEnabled(true);
        }
    }
}


text:
"""Copyright 2022 Google LLC

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

"""Performs word similarity evaluations over a set of embeddings."""
from __future__ import print_function

from absl import app
from absl import flags

import numpy as np
import csv
import pickle
import nltk
from nltk.corpus import words
from random import sample
import os

FLAGS = flags.FLAGS

flags.DEFINE_string(
    'sorted_tuple_file', '',
    'Pkl file containing pairs of (match_count, word) sorted in order of ascending frequency.'
)

def main(_):
  sorted_tuple_file = FLAGS.sorted_tuple_file
  data_dir = '/usr/local/google/home/agoldie/data/sorted_by_freq'
  #'/usr/local/google/home/agoldie/data/glove/all_sorted_count_to_word_tuples.pkl'
  with open(sorted_tuple_file, 'rb') as f:
    sorted_tuples = pickle.load(f)
  print(len(sorted_tuples))
  vocab_size = 5000
  stride = 5000
  for start_index in range(0, len(sorted_tuples) - vocab_size, stride):
    sample_vocab = [p[1] for p in sorted_tuples[start_index:start_index + vocab_size]]
    output_vocab_file = os.path.join(data_dir, 'start' + str(start_index) + '-vocab' + str(vocab_size) + '-stride' + str(stride) + '.pkl')
    print(output_vocab_file)
    with open(output_vocab_file, 'wb') as f:
      pickle.dump(sample_vocab, f)

if __name__ == '__main__':
  app.run(main)


text:
namespace SilverScreen.Domain.Customers
{
    public sealed class CustomerId : AbstractIdentity<string>
    {
        public override string Id { get; protected set; }

        public CustomerId(string id)
        {
            Id = id;
        }
    }
}


text: A basic chat demonstration using Socket.IO and Vue.js


text:
package turksem.util

import scala.collection.mutable
import scala.math.Numeric

/** Convenience class for scoring things with numbers. Mutable.
  * Basically copied from Counter. Generalizes it, so phase out Counter if possible.
  *
  * Could definitely replace with a better implementation later on,
  * maybe just use something from a library.
  * Not writing scaladoc because it's pretty self-explanatory...
  */
class Scorer[A, N] private (private[this] val map: mutable.Map[A, N])(implicit N: Numeric[N]) {
  @inline def apply(a: A): N = get(a)
  def get(a: A): N = map.get(a).getOrElse(N.zero)
  def increment(a: A): Unit = add(a, N.one)
  def add(a: A, n: N): Unit = map.put(a, N.plus(get(a), n))

  def addAll(other: Iterator[(A, N)]): Unit =
    other.foreach(Function.tupled(add))

  def iterator: Iterator[(A, N)] = map.iterator
  def keyIterator: Iterator[A] = map.keys.iterator

  def isEmpty: Boolean = map.isEmpty
  def nonEmpty: Boolean = map.nonEmpty

  def size: Int = map.size
  def max: N = if(map.isEmpty) N.zero else map.values.max
  def min: N = if(map.isEmpty) N.zero else map.values.min
  def sum: N = map.values.sum
  def mean: Double = N.toDouble(sum) / size.toDouble
  def median: Double = {
    if(map.isEmpty) {
      0.0
    } else {
      val sorted = iterator.map(_._2).toVector.sorted
      if(sorted.size % 2 == 0) {
        N.toDouble(N.plus(sorted(sorted.size / 2 - 1), sorted(sorted.size / 2))) / 2.0
      } else {
        N.toDouble(sorted(sorted.size / 2))
      }
    }
  }

  def sizeIf(p: A => Boolean): Int = map.keys.filter(p).size
  def sumIf(p: A => Boolean): N = map.filter(x => p(x._1)).map(_._2).sum
}

object Scorer {
  def apply[A, N : Numeric](): Scorer[A, N] = {
    new Scorer(mutable.Map.empty[A, N])
  }

  def apply[A, N : Numeric](items: TraversableOnce[A]): Scorer[A, N] = {
    val map = mutable.Map.empty[A, N]
    val counter = new Scorer(map)
    items.foreach(i => counter.increment(i))
    counter
  }
}


text:
package dotty.tools.dotc

import config.CompilerCommand
import core.Contexts.{Context, ContextBase}
import util.DotClass
import reporting._
import scala.util.control.NonFatal

abstract class Driver extends DotClass {

  val prompt = "\ndotc> "

  protected def newCompiler(): Compiler

  protected def emptyReporter: Reporter = new StoreReporter

  protected def doCompile(compiler: Compiler, fileNames: List[String])(implicit ctx: Context): Reporter =
    if (fileNames.nonEmpty)
      try {
        val run = compiler.newRun
        run.compile(fileNames)
        run.printSummary()
      }
      catch {
        case ex: FatalError  =>
          ctx.error(ex.getMessage) // signals that we should fail compilation.
          ctx.typerState.reporter
      }
    else emptyReporter

  protected def initCtx = (new ContextBase).initialCtx

  protected def sourcesRequired = true

  def setup(args: Array[String], rootCtx: Context): (List[String], Context) = {
    val summary = CompilerCommand.distill(args)(rootCtx)
    implicit val ctx: Context = initCtx.fresh.setSettings(summary.sstate)
    val fileNames = CompilerCommand.checkUsage(summary, sourcesRequired)
    (fileNames, ctx)
  }

  def process(args: Array[String], rootCtx: Context): Reporter = {
    val (fileNames, ctx) = setup(args, rootCtx)
    doCompile(newCompiler(), fileNames)(ctx)
  }

  def main(args: Array[String]): Unit =
    sys.exit(if (process(args, initCtx).hasErrors) 1 else 0)
}

class FatalError(msg: String) extends Exception


text:
var gyp = require('./gyp')
var util = require('./util')

function runGyp (opts, version, cb) {
  var log = opts.log
  if (!opts.preinstall) return run()

  log.verbose('executing preinstall')
  util.spawn(opts.preinstall, function (err) {
    if (err) return cb(err)
    run()
  })

  function run () {
    var args = ['node', 'index.js']
    if (opts.backend === 'node-ninja') {
      args.push('configure')
      args.push('build')
      args.push('--builddir=build/' + version)
    } else {
      args.push('rebuild')
    }
    args.push('--target=' + version)
    args.push('--target_arch=' + opts.arch)
    if (opts.debug) args.push('--debug')

    gyp({
      gyp: opts.gyp,
      backend: opts.backend,
      log: opts.log,
      args: args,
      version: version,
      filter: function (command) {
        if (command.name === 'configure') {
          return configurePreGyp(command, opts)
        }
      }
    }, cb)
  }
}

function configurePreGyp (command, opts) {
  var binary = opts.pkg.binary
  if (binary && binary.module_name) {
    command.args.push('-Dmodule_name=' + binary.module_name)
  }
  if (binary && binary.module_path) {
    command.args.push('-Dmodule_path=' + binary.module_path)
  }
}

module.exports = runGyp