text:
package com.taoswork.tallycheck.datasolution.mongo.core.entityservice;

import com.taoswork.tallycheck.authority.provider.AllPassAuthorityProvider;
import com.taoswork.tallycheck.dataservice.PersistableResult;
import com.taoswork.tallycheck.dataservice.SecurityAccessor;
import com.taoswork.tallycheck.dataservice.exception.ServiceException;
import com.taoswork.tallycheck.dataservice.operator.Operator;
import com.taoswork.tallycheck.dataservice.query.CriteriaQueryResult;
import com.taoswork.tallycheck.dataservice.query.CriteriaTransferObject;
import com.taoswork.tallycheck.dataservice.query.PropertyFilterCriteria;
import com.taoswork.tallycheck.datasolution.DatasourceDefinition;
import com.taoswork.tallycheck.datasolution.IDataSolution;
import com.taoswork.tallycheck.datasolution.config.IDatasourceConfiguration;
import com.taoswork.tallycheck.datasolution.mongo.servicemockup.TallyMockupMongoDataSolution;
import com.taoswork.tallycheck.datasolution.mongo.servicemockup.datasource.TallyMockupMongoDatasourceConfiguration;
import com.taoswork.tallycheck.datasolution.service.EasyEntityService;
import com.taoswork.tallycheck.datasolution.service.EntityMetaAccess;
import com.taoswork.tallycheck.datasolution.service.IEntityService;
import com.taoswork.tallycheck.descriptor.dataio.in.Entity;
import com.taoswork.tallycheck.descriptor.dataio.in.translator.EntityTranslator;
import com.taoswork.tallycheck.descriptor.dataio.in.translator.TranslateException;
import com.taoswork.tallycheck.general.solution.time.MethodTimeCounter;
import com.taoswork.tallycheck.testmaterial.mongo.domain.zoo.ZooKeeper;
import com.taoswork.tallycheck.testmaterial.mongo.domain.zoo.impl.ZooKeeperImpl;
import org.bson.types.ObjectId;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashSet;
import java.util.Set;

/**
 * Created by Gao Yuan on 2015/11/10.
 */
public class MongoEntityServicePerformanceTest {
    private static final Logger LOGGER = LoggerFactory.getLogger(MongoEntityServicePerformanceTest.class);

    private IDataSolution dataSolution = null;
    private EntityTranslator translator = null;
    private EntityMetaAccess metaAccess = null;
    private SecurityAccessor accessor = new SecurityAccessor();
    private Operator operator = new Operator();

    @Before
    public void setup() {
        dataSolution = new TallyMockupMongoDataSolution();
        dataSolution.setAuthorityProvider(new AllPassAuthorityProvider());

        metaAccess = dataSolution.getService(EntityMetaAccess.COMPONENT_NAME);
        translator = new EntityTranslator();
    }

    @After
    public void teardown() {
        TallyMockupMongoDatasourceConfiguration.DatasourceDefinition mdbDef = dataSolution.getService(DatasourceDefinition.DATA_SOURCE_DEFINITION);
        mdbDef.dropDatabase();
        dataSolution = null;
        metaAccess = null;
        translator = null;
    }

    @Test
    public void testCRUDQ() throws ServiceException {
        int loopCount = 20;
        int inLoopAttempt = 20;
        EasyEntityService easyEntityService = new EasyEntityService(dataSolution);
        IEntityService entityService = dataSolution.getService(IEntityService.COMPONENT_NAME);

        Set<ObjectId> ids = new HashSet<ObjectId>();
        final int total;
        try {
            int created = 0;
            MethodTimeCounter methodTimeCounter = new MethodTimeCounter(LOGGER, "CREATE");
            for (int l = 0; l < loopCount; ++l) {
                String nameAAA = entityPrefix(l);
                for (int i = 0; i < inLoopAttempt; ++i) {
                    Entity adminEntity = new Entity();
                    adminEntity
                            .setType(ZooKeeperImpl.class)
                            .setProperty("name", nameAAA + i);
                    ZooKeeper adminP = (ZooKeeper)translator.translate(metaAccess, adminEntity, null);
                    PersistableResult<ZooKeeper> adminRes = entityService.create(operator, accessor, adminP);
                    ZooKeeper admin = adminRes.getValue();
                    ids.add(admin.getId());
                    created++;
                }
            }
            Assert.assertEquals(loopCount * inLoopAttempt, ids.size());
            Assert.assertEquals(loopCount * inLoopAttempt, created);
            total = created;
            methodTimeCounter.noticePerActionCostOnExit(created);
        } catch (TranslateException e) {
            throw new ServiceException(e);
        }
        {
            int query = 0;
            MethodTimeCounter methodTimeCounter = new MethodTimeCounter(LOGGER, "QUERY SINGLE");
            for (ObjectId id : ids) {
                CriteriaTransferObject cto = new CriteriaTransferObject();
                cto.addFilterCriteria(new PropertyFilterCriteria("id", "" + id));
                CriteriaQueryResult<ZooKeeper> zooKeepers = easyEntityService.query(accessor, ZooKeeper.class, cto);
                query++;
            }
            methodTimeCounter.noticePerActionCostOnExit(query);
        }
        {
            int query = 0;
            MethodTimeCounter methodTimeCounter = new MethodTimeCounter(LOGGER, "QUERY MULTIPLE");
            for (int l = 0; l < loopCount; ++l) {
                String nameAAA = entityPrefix(l);
                for (int i = 0; i < inLoopAttempt; ++i) {
                    CriteriaTransferObject cto = new CriteriaTransferObject();
                    cto.addFilterCriteria(new PropertyFilterCriteria("name", nameAAA));
                    CriteriaQueryResult<ZooKeeper> zooKeepers = easyEntityService.query(accessor, ZooKeeper.class, cto);
                    query++;
                }
            }
            methodTimeCounter.noticePerActionCostOnExit(query);
        }
        {
            int read = 0;
            MethodTimeCounter methodTimeCounter = new MethodTimeCounter(LOGGER, "READ");
            for (ObjectId id : ids) {
                PersistableResult<ZooKeeper> adminFromDbRes = easyEntityService.read(operator, accessor, ZooKeeper.class, (id));
                Assert.assertEquals(id, adminFromDbRes.getValue().getId());
                read++;
            }
            methodTimeCounter.noticePerActionCostOnExit(read);
        }
        {
            int updated = 0;
            MethodTimeCounter methodTimeCounter = new MethodTimeCounter(LOGGER, "UPDATE");
            for (ObjectId id : ids) {
                PersistableResult<ZooKeeper> adminFromDbRes = easyEntityService.read(operator, accessor, ZooKeeper.class, (id));
                ZooKeeper admin = adminFromDbRes.getValue();
                String oldEmail = admin.getEmail();
                String newEmail = admin.getName() + "@xxx.com";
                admin.setEmail(newEmail);
                PersistableResult<ZooKeeper> freshAdminFrom = entityService.update(operator, accessor, admin);
                Assert.assertEquals(newEmail, freshAdminFrom.getValue().getEmail());
                updated++;
            }
            methodTimeCounter.noticePerActionCostOnExit(updated);
        }
        {
            int deleted = 0;
            MethodTimeCounter methodTimeCounter = new MethodTimeCounter(LOGGER, "DELETE");
            for (ObjectId id : ids) {
                PersistableResult<ZooKeeper> adminFromDbRes = easyEntityService.read(operator, accessor, ZooKeeper.class, (id));
                ZooKeeperImpl zk = new ZooKeeperImpl();
                zk.setId(id);
                boolean delOk = easyEntityService.delete(operator, accessor, zk);
                Assert.assertTrue(delOk);
                deleted++;
            }
            methodTimeCounter.noticePerActionCostOnExit(deleted);
        }

    }

    public String entityPrefix(int i) {
        return "name" + i + "_";
    }

}


text:
package prompting

import (
	"errors"
	"fmt"
)

// streamPrompter implements Prompter on top of a Prompting_HostServer stream.
type streamPrompter struct {
	// allowPrompts indicates whether or not the client allows prompts.
	allowPrompts bool
	// stream is the underlying Prompting_HostServer stream.
	stream Prompting_HostServer
	// errored indicates whether or not the stream has encountered an error.
	errored bool
}

// sendReceive performs a send/receive cycle by sending a HostResponse and
// receiving a HostRequest.
func (p *streamPrompter) sendReceive(response *HostResponse) (*HostRequest, error) {
	// Send the request.
	if err := p.stream.Send(response); err != nil {
		return nil, fmt.Errorf("unable to send response: %w", err)
	}

	// Determine the expected request mode.
	mode := hostRequestModeMessageResponse
	if response.IsPrompt {
		mode = hostRequestModePromptResponse
	}

	// Receive the response.
	if request, err := p.stream.Recv(); err != nil {
		return nil, fmt.Errorf("unable to receive request: %w", err)
	} else if err = request.ensureValid(mode); err != nil {
		return nil, fmt.Errorf("invalid request received: %w", err)
	} else {
		return request, nil
	}
}

// Message implements the Message method of Prompter.
func (p *streamPrompter) Message(message string) error {
	// Check if a previous transmission error has occurred.
	if p.errored {
		return errors.New("prompter encountered previous error")
	}

	// Otherwise perform the messaging operation.
	if _, err := p.sendReceive(&HostResponse{Message: message}); err != nil {
		p.errored = true
		return err
	}

	// Success.
	return nil
}

// Prompt implements the Prompt method of Prompter.
func (p *streamPrompter) Prompt(prompt string) (string, error) {
	// Check if a previous transmission error has occurred.
	if p.errored {
		return "", errors.New("prompter encountered previous error")
	}

	// Check whether or not prompts are supported by this client.
	if !p.allowPrompts {
		return "", errors.New("prompter only supports messaging")
	}

	// Perform the exchange.
	response, err := p.sendReceive(&HostResponse{IsPrompt: true, Message: prompt})
	if err != nil {
		p.errored = true
		return "", err
	}

	// Success.
	return response.Response, nil
}

redpajama_set_name: RedPajamaGithub


text:
<?php
  require_once('cursos/functions.php');
  if (isset($_GET['id']) and isset($_GET['idCurso'])){
    deleteParticipant($_GET['id'],$_GET['idCurso']);
  } else {
    die("ERRO: ID não definido.");
  }
?>


text:
* tmux
  1. # cp tmux.conf.default ~/.tmux.conf
* vim
  1. # git clone https://github.com/gmarik/Vundle.vim.git ~/.vim/bundle/Vundle.vim
  2. # cp vimrc.default ~/.vimrc
  3. Launch **vim** and **:PluginInstall**
* zsh
  1. Install [oh-my-zsh](https://github.com/robbyrussell/oh-my-zsh)

## Screenshot
![Alt text](screenshots/screenshot.png?raw=true "Optional Title")


text:
'use strict';
var LIVERELOAD_PORT = 35729;
var lrSnippet = require('connect-livereload')({ port: LIVERELOAD_PORT });
var mountFolder = function(connect, dir) {
    return connect.static(require('path').resolve(dir));
};

// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'

module.exports = function(grunt) {
    // load all grunt tasks
    require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);

    grunt.initConfig({
        watch: {
            options: {
                nospawn: true
            },
            livereload: {
                options: {
                    livereload: LIVERELOAD_PORT
                },
                files: [
                    'app/*.html',
                    'app/styles/scss/{,*/}*.scss',
                    'app/js/{,*/}*.js'
                ]
            },
            compass: {
                files: ['app/styles/scss/{,*/}*.scss'],
                tasks: ['compass:dev']
            }
        },

        connect: {
            options: {
                port: 9001,
                // change this to '0.0.0.0' to access the server from outside
                hostname: 'gfw-ekuatorial.local'
            },
            livereload: {
                options: {
                    middleware: function(connect) {
                        return [
                            mountFolder(connect, 'app'),
                            lrSnippet
                        ];
                    }
                }
            }
        },

        open: {
            server: {
                path: 'http://gfw-ekuatorial.local:<%= connect.options.port %>'
            }
        },

        compass: {
            dev: {
                options: {
                    sassDir: ['app/styles/scss'],
                    cssDir: ['app/styles/css'],
                    environment: 'development'
                }
            }
        }
    });

    grunt.registerTask('server', [
        'compass:dev',
        'connect:livereload',
        // 'open',
        'watch'
    ]);
};


text:
using System;
using System.Xml;
using System.Collections;
using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.ServiceModel.Activation;
using System.ServiceModel.Syndication;

namespace WCFRestService
{
	public class WCFRESTService : IWCFRESTService
	{
		/// <summary>
		/// Example on how to return an object via the service
		/// </summary>
		/// <returns>Your serializable object</returns>
		public ExampleObject ReturnExample()
		{
			ExampleObject returnValue = new ExampleObject ();
			returnValue.Name = "Adams";
			returnValue.MeaningfulNumber = 42;
			WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK;
			return returnValue;
		}

		/// <summary>
		/// Example on how to post a JSON object to the service
		/// </summary>
		/// <param name="inputObject">A Serializable Object (JSON)</param>
		public void PostExample(ExampleObject inputObject)
		{
			if(inputObject == null)
				WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.BadRequest;
			if (inputObject.MeaningfulNumber == 42) {
				WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.Redirect;
				WebOperationContext.Current.OutgoingResponse.Headers.Add ("Location", @"http://en.wikipedia.org/wiki/42_(number)#The_Hitchhiker.27s_Guide_to_the_Galaxy");
			} else {
				WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK;
			}
		}

		/// <summary>
		/// Example on how to return an RSS Feed
		/// </summary>
		/// <param name="input">Your input via the URL parameter</param>
		/// <returns>RSS Feed</returns>
		public SyndicationFeedFormatter ReturnFeed(string input)
		{
			SyndicationFeed queryFeed = new SyndicationFeed("WCF REST Example", "RSS Feed", new Uri("http://www.google.ca/"), "ExampleID", DateTime.UtcNow);

			List<SyndicationItem> resultItems = new List<SyndicationItem> ();

			SyndicationItem newResultItem = new SyndicationItem();
			newResultItem.Id = Guid.NewGuid().ToString();
			newResultItem.Title = new TextSyndicationContent("Canadian Bacon");
			newResultItem.BaseUri = new Uri("http://www.google.ca/");
			newResultItem.AttributeExtensions.Add(new XmlQualifiedName("DateTimeUTC"), DateTime.UtcNow.ToString());
			newResultItem.AttributeExtensions.Add(new XmlQualifiedName("ARandomString"), Guid.NewGuid().ToString());
			newResultItem.AttributeExtensions.Add(new XmlQualifiedName("YourInputValue"), input);
			resultItems.Add (newResultItem);

			queryFeed.AttributeExtensions.Add(new XmlQualifiedName("TotalResults"), resultItems.Count.ToString());
			queryFeed.Items = resultItems;
			return new Rss20FeedFormatter(queryFeed);
		}
	}
}


text:
<?php

namespace Portal\AppBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class PortalAppBundle extends Bundle
{
}


text:
<?php

namespace Ekyna\Component\Commerce\Payment\Event;

use Ekyna\Component\Commerce\Payment\Model\PaymentInterface;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\HttpFoundation\Response;

/**
 * Class PaymentEvent
 * @package Ekyna\Component\Commerce\Payment\Event
 * @author  Etienne Dauvergne <contact@ekyna.com>
 */
class PaymentEvent extends Event
{
    /**
     * @var PaymentInterface
     */
    private $payment;

    /**
     * @var Response
     */
    private $response;

    /**
     * Constructor.
     *
     * @param PaymentInterface $payment
     */
    public function __construct(PaymentInterface $payment)
    {
        $this->payment = $payment;
    }

    /**
     * Sets the payment.
     *
     * @param PaymentInterface $payment
     */
    public function setPayment(PaymentInterface $payment = null)
    {
        $this->payment = $payment;
    }

    /**
     * Returns the payment.
     *
     * @return PaymentInterface
     */
    public function getPayment()
    {
        return $this->payment;
    }

    /**
     * Sets the response.
     *
     * @param Response $response
     */
    public function setResponse(Response $response = null)
    {
        $this->response = $response;
    }

    /**
     * Returns whether or not the event has a response.
     *
     * @return bool
     */
    public function hasResponse()
    {
        return null !== $this->response;
    }

    /**
     * Returns the response.
     *
     * @return Response
     */
    public function getResponse()
    {
        return $this->response;
    }
}


text:
Pattern: Use of development PHP function

Issue: -

## Description

Restricts the use of various development functions.

## Further Reading

* [WordPress.PHP.DevelopmentFunctions](https://github.com/WordPress/WordPress-Coding-Standards/tree/develop/WordPress/Sniffs/PHP/DevelopmentFunctionsSniff.php)


text:
#include <fpu_control.h>

/* Change floating point precision to double (64-bit) from
 * the extended (80-bit) Linux default. */

void setDoublePrecision() {
    fpu_control_t cw;

    _FPU_GETCW(cw);
    cw &= ~_FPU_EXTENDED;
    cw |= _FPU_DOUBLE;
    _FPU_SETCW(cw);
}

void initialisePlatform() {
    setDoublePrecision();
}


text:
@import "~font-awesome/css/font-awesome.css";
@import "~bootstrap/dist/css/bootstrap.css";
@import "~bootstrap/dist/css/bootstrap-theme.css";


text:
Some Examples of Our Work

                                Printed Brochure

                                Let us profile your business for a Chinese audience and get it in print. We utilize professional writing, design and printing resources to enable your brand to stand out.

                                Social Media Platforms

                                When it comes to navigating China's digital landscape, it pays to work with experts who make it their passion and living day in and day out. We have many examples of establishing and building brand presence on China's social media.

                                Chinese Customers

                                Is your business ready?
 While it is not realistic to expect all your customer facing staff to speak Mandarin, we have ways that can help ease communication and improve the customer experience.

                                Deploy Your Brand

                                Don't get hung up on the barriers towards accessing China. We have cost-effective solutions to place your brand on the Chinese internet.


text:
package demo.cookies;

import demo.TestBase;

/**
 *
 * @author pthomas3
 */
public class CookiesRunner extends TestBase {

}


text:
package de.tudarmstadt.ukp.clarin.webanno.tsv;

import static org.apache.commons.io.IOUtils.closeQuietly;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import org.apache.commons.io.IOUtils;
import org.apache.commons.io.LineIterator;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.uima.cas.CAS;
import org.apache.uima.collection.CollectionException;
import org.apache.uima.fit.descriptor.ConfigurationParameter;
import org.apache.uima.jcas.JCas;
import org.apache.uima.util.Level;

import de.tudarmstadt.ukp.dkpro.core.api.io.JCasResourceCollectionReader_ImplBase;
import de.tudarmstadt.ukp.dkpro.core.api.lexmorph.type.pos.POS;
import de.tudarmstadt.ukp.dkpro.core.api.metadata.type.DocumentMetaData;
import de.tudarmstadt.ukp.dkpro.core.api.ner.type.NamedEntity;
import de.tudarmstadt.ukp.dkpro.core.api.parameter.ComponentParameters;
import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Lemma;
import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Sentence;
import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Token;
import de.tudarmstadt.ukp.dkpro.core.api.syntax.type.dependency.Dependency;

/**
 * Reads a specific TSV File (9 TAB separated) annotation and change it to CAS object. Example of
 * Input Files:

 * 1 Heutzutage heutzutage ADV _ _ 2 ADV _ _

 * Columns are separated by a TAB character and sentences are separated by a blank new line see the
 * {@link WebannoTsvReader#setAnnotations}
 *
 * @author Seid Muhie Yimam
 *
 */
public class WebannoTsvReader
    extends JCasResourceCollectionReader_ImplBase
{

    private String  fileName;
    public void convertToCas(JCas aJCas, InputStream aIs, String aEncoding)
        throws IOException

    {
        StringBuilder text = new StringBuilder();
        Map<Integer, String> tokens = new HashMap<Integer, String>();
        Map<Integer, String> pos = new HashMap<Integer, String>();
        Map<Integer, String> lemma = new HashMap<Integer, String>();
        Map<Integer, String> namedEntity = new HashMap<Integer, String>();
        Map<Integer, String> dependencyFunction = new HashMap<Integer, String>();
        Map<Integer, Integer> dependencyDependent = new HashMap<Integer, Integer>();

        List<Integer> firstTokenInSentence = new ArrayList<Integer>();

        DocumentMetaData documentMetadata = DocumentMetaData.get(aJCas);
        fileName = documentMetadata.getDocumentTitle();
        setAnnotations(aIs, aEncoding, text, tokens, pos, lemma, namedEntity, dependencyFunction,
                dependencyDependent, firstTokenInSentence);

        aJCas.setDocumentText(text.toString());

        Map<String, Token> tokensStored = new HashMap<String, Token>();

        createToken(aJCas, text, tokens, pos, lemma, tokensStored);

        createNamedEntity(namedEntity, aJCas, tokens, tokensStored);

        createDependency(aJCas, tokens, dependencyFunction, dependencyDependent, tokensStored);

        createSentence(aJCas, firstTokenInSentence, tokensStored);
    }

    /**
     * Create {@link Token} in the {@link CAS}. If the lemma and pos columns are not empty it will
     * create {@link Lemma} and {@link POS} annotations
     */
    private void createToken(JCas aJCas, StringBuilder text, Map<Integer, String> tokens,
            Map<Integer, String> pos, Map<Integer, String> lemma, Map<String, Token> tokensStored)
    {
        int tokenBeginPosition = 0;
        int tokenEndPosition = 0;

        for (int i = 1; i <= tokens.size(); i++) {
            tokenBeginPosition = text.indexOf(tokens.get(i), tokenBeginPosition);
            Token outToken = new Token(aJCas, tokenBeginPosition, text.indexOf(tokens.get(i),
                    tokenBeginPosition) + tokens.get(i).length());
            tokenEndPosition = text.indexOf(tokens.get(i), tokenBeginPosition)
                    + tokens.get(i).length();
            tokenBeginPosition = tokenEndPosition;
            outToken.addToIndexes();

            // Add pos to CAS if exist
            if (!pos.get(i).equals("_")) {
                POS outPos = new POS(aJCas, outToken.getBegin(), outToken.getEnd());
                outPos.setPosValue(pos.get(i));
                outPos.addToIndexes();
                outToken.setPos(outPos);
            }

            // Add lemma if exist
            if (!lemma.get(i).equals("_")) {
                Lemma outLemma = new Lemma(aJCas, outToken.getBegin(), outToken.getEnd());
                outLemma.setValue(lemma.get(i));
                outLemma.addToIndexes();
                outToken.setLemma(outLemma);
            }
            tokensStored.put("t_" + i, outToken);
        }
    }

    /**
     * add dependency parsing to CAS
     */
    private void createDependency(JCas aJCas, Map<Integer, String> tokens,
            Map<Integer, String> dependencyFunction, Map<Integer, Integer> dependencyDependent,
            Map<String, Token> tokensStored)
    {
        for (int i = 1; i <= tokens.size(); i++) {
            if (dependencyFunction.get(i) != null) {
                Dependency outDependency = new Dependency(aJCas);
                outDependency.setDependencyType(dependencyFunction.get(i));

                // if span A has (start,end)= (20, 26) and B has (start,end)= (30, 36)
                // arc drawn from A to B, dependency will have (start, end) = (20, 36)
                // arc drawn from B to A, still dependency will have (start, end) = (20, 36)
                int begin = 0, end = 0;
                // if not ROOT
                if (dependencyDependent.get(i) != 0) {
                    begin = tokensStored.get("t_" + i).getBegin() > tokensStored.get(
                            "t_" + dependencyDependent.get(i)).getBegin() ? tokensStored.get(
                            "t_" + dependencyDependent.get(i)).getBegin() : tokensStored.get(
                            "t_" + i).getBegin();
                    end = tokensStored.get("t_" + i).getEnd() < tokensStored.get(
                            "t_" + dependencyDependent.get(i)).getEnd() ? tokensStored.get(
                            "t_" + dependencyDependent.get(i)).getEnd() : tokensStored
                            .get("t_" + i).getEnd();
                }
                else {
                    begin = tokensStored.get("t_" + i).getBegin();
                    end = tokensStored.get("t_" + i).getEnd();
                }

                outDependency.setBegin(begin);
                outDependency.setEnd(end);
                outDependency.setDependent(tokensStored.get("t_" + i));
                if (dependencyDependent.get(i) == 0) {
                    outDependency.setGovernor(tokensStored.get("t_" + i));
                }
                else {
                    outDependency.setGovernor(tokensStored.get("t_" + dependencyDependent.get(i)));
                }
                outDependency.addToIndexes();
            }
        }
    }

    /**
     * Add sentence layer to CAS
     */
    private void createSentence(JCas aJCas, List<Integer> firstTokenInSentence,
            Map<String, Token> tokensStored)
    {
        for (int i = 0; i < firstTokenInSentence.size(); i++) {
            Sentence outSentence = new Sentence(aJCas);
            // Only last sentence, and no the only sentence in the document (i!=0)
            if (i == firstTokenInSentence.size() - 1 && i != 0) {
                outSentence.setBegin(tokensStored.get("t_" + firstTokenInSentence.get(i)).getEnd());
                outSentence.setEnd(tokensStored.get("t_" + (tokensStored.size())).getEnd());
                outSentence.addToIndexes();
                break;
            }
            if (i == firstTokenInSentence.size() - 1 && i == 0) {
                outSentence.setBegin(tokensStored.get("t_" + firstTokenInSentence.get(i))
                        .getBegin());
                outSentence.setEnd(tokensStored.get("t_" + (tokensStored.size())).getEnd());
                outSentence.addToIndexes();
            }
            else if (i == 0) {
                outSentence.setBegin(tokensStored.get("t_" + firstTokenInSentence.get(i))
                        .getBegin());
                outSentence.setEnd(tokensStored.get("t_" + firstTokenInSentence.get(i + 1))
                        .getEnd());
                outSentence.addToIndexes();
            }
            else {
                outSentence
                        .setBegin(tokensStored.get("t_" + firstTokenInSentence.get(i)).getEnd() + 1);
                outSentence.setEnd(tokensStored.get("t_" + firstTokenInSentence.get(i + 1))
                        .getEnd());
                outSentence.addToIndexes();
            }
        }
    }

    /**
     * Iterate through all lines and get available annotations

     * First column is sentence number and a blank new line marks end of a sentence

     * The Second column is the token

     * The third column is the lemma annotation

     * The fourth column is the POS annotation

     * The fifth column is used for Named Entity annotations (Multiple annotations separeted by |
     * character)

     * The sixth column is the origin token number of dependency parsing

     * The seventh column is the function/type of the dependency parsing

     * eighth and ninth columns are undefined currently
     */
    private void setAnnotations(InputStream aIs, String aEncoding, StringBuilder text,
            Map<Integer, String> tokens, Map<Integer, String> pos, Map<Integer, String> lemma,
            Map<Integer, String> namedEntity, Map<Integer, String> dependencyFunction,
            Map<Integer, Integer> dependencyDependent, List<Integer> firstTokenInSentence)
        throws IOException
    {
        int tokenNumber = 0;
        boolean first = true;
        int base = 0;

        LineIterator lineIterator = IOUtils.lineIterator(aIs, aEncoding);
        boolean textFound = false;
        StringBuffer tmpText = new StringBuffer();
        while (lineIterator.hasNext()) {
            String line = lineIterator.next().trim();
            if (line.startsWith("#text=")) {
                text.append(line.substring(6) + "\n");
                textFound = true;
                continue;
            }
            if (line.startsWith("#")) {
                continue;// it is a comment line
            }
            int count = StringUtils.countMatches(line, "\t");
            if (line.isEmpty()) {
                continue;
            }
            if (count != 9) {// not a proper TSV file
                getUimaContext().getLogger().log(Level.INFO, "This is not a valid TSV File");
                throw new IOException(fileName + " This is not a valid TSV File");
            }
            StringTokenizer lineTk = new StringTokenizer(line, "\t");

            if (first) {
                tokenNumber = Integer.parseInt(line.substring(0, line.indexOf("\t")));
                firstTokenInSentence.add(tokenNumber);
                first = false;
            }
            else {
                int lineNumber = Integer.parseInt(line.substring(0, line.indexOf("\t")));
                if (lineNumber == 1) {
                    base = tokenNumber;
                    firstTokenInSentence.add(base);
                }
                tokenNumber = base + Integer.parseInt(line.substring(0, line.indexOf("\t")));
            }

            while (lineTk.hasMoreElements()) {
                lineTk.nextToken();
                String token = lineTk.nextToken();

                // for backward compatibility
                tmpText.append(token + " ");

                tokens.put(tokenNumber, token);
                lemma.put(tokenNumber, lineTk.nextToken());
                pos.put(tokenNumber, lineTk.nextToken());
                String ne = lineTk.nextToken();
                lineTk.nextToken();// make it compatible with prev WebAnno TSV reader
                namedEntity.put(tokenNumber, (ne.equals("_")||ne.equals("-")) ? "O" : ne);
                String dependentValue = lineTk.nextToken();
                if (NumberUtils.isDigits(dependentValue)) {
                    int dependent = Integer.parseInt(dependentValue);
                    dependencyDependent.put(tokenNumber, dependent == 0 ? 0 : base + dependent);
                    dependencyFunction.put(tokenNumber, lineTk.nextToken());
                }
                else {
                    lineTk.nextToken();
                }
                lineTk.nextToken();
                lineTk.nextToken();
            }
        }
        if (!textFound) {
            text.append(tmpText);
        }
    }

    public static final String PARAM_ENCODING = ComponentParameters.PARAM_SOURCE_ENCODING;
    @ConfigurationParameter(name = PARAM_ENCODING, mandatory = true, defaultValue = "UTF-8")
    private String encoding;

    @Override
    public void getNext(JCas aJCas)
        throws IOException, CollectionException
    {
        Resource res = nextFile();
        initCas(aJCas, res);
        InputStream is = null;
        try {
            is = res.getInputStream();
            convertToCas(aJCas, is, encoding);
        }
        finally {
            closeQuietly(is);
        }

    }

    /**
     * Creates Named Entities from CoNLL BIO format to CAS format
     */
    private void createNamedEntity(Map<Integer, String> aNamedEntityMap, JCas aJCas,
            Map<Integer, String> aTokensMap, Map<String, Token> aJcasTokens)
    {

        Map<Integer, NamedEntity> indexedNeAnnos = new LinkedHashMap<Integer, NamedEntity>();

        for (int i = 1; i <= aTokensMap.size(); i++) {
            if (aNamedEntityMap.get(i).equals("O")) {
                continue;
            }
            int index = 1;// to maintain multiple span ne annotation in the same index
            for (String ne : aNamedEntityMap.get(i).split("\\|")) {

                if (ne.equals("O")) {// for annotations such as B_LOC|O|I_PER and the like
                    index++;
                }
                else if (ne.startsWith("B_") || ne.startsWith("B-")) {
                    NamedEntity outNamedEntity = new NamedEntity(aJCas, aJcasTokens.get("t_" + i)
                            .getBegin(), aJcasTokens.get("t_" + i).getEnd());
                    outNamedEntity.setValue(ne.substring(2));
                    outNamedEntity.addToIndexes();
                    indexedNeAnnos.put(index, outNamedEntity);
                    index++;
                }
                else if (ne.startsWith("I_")||ne.startsWith("I-")) {
                    NamedEntity outNamedEntity = indexedNeAnnos.get(index);
                    outNamedEntity.setEnd(aJcasTokens.get("t_" + i).getEnd());
                    outNamedEntity.addToIndexes();
                    index++;
                }
                else {// NE is not in IOB format. store one NE per token. No way to detect multiple
                      // token NE
                    NamedEntity outNamedEntity = new NamedEntity(aJCas, aJcasTokens.get("t_" + i)
                            .getBegin(), aJcasTokens.get("t_" + i).getEnd());
                    outNamedEntity.setValue(ne);
                    outNamedEntity.addToIndexes();
                    indexedNeAnnos.put(index, outNamedEntity);
                    index++;
                }
            }
        }
    }
}


text:
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/nearby_sharing/nearby_connections_manager_impl.h"

#include "base/callback_helpers.h"
#include "base/containers/contains.h"
#include "base/files/file_util.h"
#include "base/metrics/histogram_functions.h"
#include "base/strings/string_number_conversions.h"
#include "base/unguessable_token.h"
#include "chrome/browser/nearby_sharing/common/nearby_share_features.h"
#include "chrome/browser/nearby_sharing/constants.h"
#include "chrome/browser/nearby_sharing/logging/logging.h"
#include "chrome/browser/nearby_sharing/public/cpp/nearby_connections_manager.h"
#include "chromeos/ash/services/nearby/public/mojom/nearby_connections_types.mojom.h"
#include "crypto/random.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "net/base/network_change_notifier.h"

namespace {

const char kFastAdvertisementServiceUuid[] =
    "0000fef3-0000-1000-8000-00805f9b34fb";
const location::nearby::connections::mojom::Strategy kStrategy =
    location::nearby::connections::mojom::Strategy::kP2pPointToPoint;

bool ShouldUseInternet(DataUsage data_usage, PowerLevel power_level) {
  // We won't use internet if the user requested we don't.
  if (data_usage == DataUsage::kOffline)
    return false;

  // We won't use internet in a low power mode.
  if (power_level == PowerLevel::kLowPower)
    return false;

  net::NetworkChangeNotifier::ConnectionType connection_type =
      net::NetworkChangeNotifier::GetConnectionType();

  // Verify that this network has an internet connection.
  if (connection_type == net::NetworkChangeNotifier::CONNECTION_NONE) {
    NS_LOG(VERBOSE) << __func__ << ": No internet connection.";
    return false;
  }

  // If the user wants to limit Wi-Fi, then don't use it on metered networks.
  if (data_usage == DataUsage::kWifiOnly &&
      net::NetworkChangeNotifier::GetConnectionCost() ==
          net::NetworkChangeNotifier::CONNECTION_COST_METERED) {
    NS_LOG(VERBOSE) << __func__ << ": Do not use internet with " << data_usage
                    << " and a metered connection.";
    return false;
  }

  // We're online, the user hasn't disabled Wi-Fi, let's use it!
  return true;
}

bool ShouldEnableWebRtc(DataUsage data_usage, PowerLevel power_level) {
  return base::FeatureList::IsEnabled(features::kNearbySharingWebRtc) &&
         ShouldUseInternet(data_usage, power_level);
}

bool ShouldEnableWifiLan(DataUsage data_usage, PowerLevel power_level) {
  if (!base::FeatureList::IsEnabled(features::kNearbySharingWifiLan))
    return false;

  // WifiLan only works if both devices are using the same router. We can't
  // guarantee this, but at least check that we are using Wi-Fi or ethernet.
  // TODO(https://crbug.com/1261238): Test if WifiLan can work if both devices
  // are connected to the router without an internet connection. If so, return
  // true if connection_type == net::NetworkChangeNotifier::CONNECTION_NONE.
  net::NetworkChangeNotifier::ConnectionType connection_type =
      net::NetworkChangeNotifier::GetConnectionType();
  bool is_connection_wifi_or_ethernet =
      connection_type == net::NetworkChangeNotifier::CONNECTION_WIFI ||
      connection_type == net::NetworkChangeNotifier::CONNECTION_ETHERNET;

  return ShouldUseInternet(data_usage, power_level) &&
         is_connection_wifi_or_ethernet;
}

std::string MediumSelectionToString(
    const location::nearby::connections::mojom::MediumSelection& mediums) {
  std::stringstream ss;
  ss << "{";
  if (mediums.bluetooth)
    ss << "bluetooth ";
  if (mediums.ble)
    ss << "ble ";
  if (mediums.web_rtc)
    ss << "webrtc ";
  if (mediums.wifi_lan)
    ss << "wifilan ";
  ss << "}";

  return ss.str();
}

}  // namespace

NearbyConnectionsManagerImpl::NearbyConnectionsManagerImpl(
    ash::nearby::NearbyProcessManager* process_manager,
    const std::string& service_id)
    : process_manager_(process_manager), service_id_(service_id) {
  DCHECK(process_manager_);
}

NearbyConnectionsManagerImpl::~NearbyConnectionsManagerImpl() {
  ClearIncomingPayloads();
}

void NearbyConnectionsManagerImpl::Shutdown() {
  Reset();
}

void NearbyConnectionsManagerImpl::StartAdvertising(
    std::vector<uint8_t> endpoint_info,
    IncomingConnectionListener* listener,
    PowerLevel power_level,
    DataUsage data_usage,
    ConnectionsCallback callback) {
  DCHECK(listener);
  DCHECK(!incoming_connection_listener_);

  location::nearby::connections::mojom::NearbyConnections* nearby_connections =
      GetNearbyConnections();
  if (!nearby_connections) {
    std::move(callback).Run(ConnectionsStatus::kError);
    return;
  }

  bool is_high_power = power_level == PowerLevel::kHighPower;
  bool use_ble = !is_high_power;
  auto allowed_mediums = MediumSelection::New(
      /*bluetooth=*/is_high_power, /*ble=*/use_ble,
      // Using kHighPower here rather than power_level to signal that power
      // level isn't a factor when deciding whether or not to allow WebRTC
      // upgrades from this advertisement.
      ShouldEnableWebRtc(data_usage, PowerLevel::kHighPower),
      /*wifi_lan=*/
      ShouldEnableWifiLan(data_usage, PowerLevel::kHighPower) &&
          kIsWifiLanAdvertisingSupported);
  NS_LOG(VERBOSE) << __func__ << ": "
                  << "is_high_power=" << (is_high_power ? "yes" : "no")
                  << ", data_usage=" << data_usage << ", allowed_mediums="
                  << MediumSelectionToString(*allowed_mediums);

  mojo::PendingRemote<ConnectionLifecycleListener> lifecycle_listener;
  connection_lifecycle_listeners_.Add(
      this, lifecycle_listener.InitWithNewPipeAndPassReceiver());

  // Only auto-upgrade bandwidth if advertising at high-visibility.
  // This acts as a privacy safeguard when advertising in the background.
  // Bandwidth upgrades may expose stable identifiers, and so they're
  // only safe to expose after we've verified the sender's identity.
  // Once we have verified their identity, we will manually trigger
  // a bandwidth upgrade. This isn't a concern in the foreground
  // because high-visibility already leaks the device name.
  bool auto_upgrade_bandwidth = is_high_power;

  incoming_connection_listener_ = listener;
  nearby_connections->StartAdvertising(
      service_id_, endpoint_info,
      AdvertisingOptions::New(
          kStrategy, std::move(allowed_mediums), auto_upgrade_bandwidth,
          /*enforce_topology_constraints=*/true,
          /*enable_bluetooth_listening=*/use_ble,
          /*enable_webrtc_listening=*/
          ShouldEnableWebRtc(data_usage, power_level),
          /*fast_advertisement_service_uuid=*/
          device::BluetoothUUID(kFastAdvertisementServiceUuid)),
      std::move(lifecycle_listener), std::move(callback));
}

void NearbyConnectionsManagerImpl::StopAdvertising(
    ConnectionsCallback callback) {
  incoming_connection_listener_ = nullptr;

  // TODO(https://crbug.com/1177088): Determine if we should attempt to bind to
  // process.
  if (!process_reference_)
    return;

  process_reference_->GetNearbyConnections()->StopAdvertising(
      service_id_, std::move(callback));
}

void NearbyConnectionsManagerImpl::StartDiscovery(
    DiscoveryListener* listener,
    DataUsage data_usage,
    ConnectionsCallback callback) {
  DCHECK(listener);
  DCHECK(!discovery_listener_);

  location::nearby::connections::mojom::NearbyConnections* nearby_connections =
      GetNearbyConnections();
  if (!nearby_connections) {
    std::move(callback).Run(ConnectionsStatus::kError);
    return;
  }

  auto allowed_mediums = MediumSelection::New(
      /*bluetooth=*/true,
      /*ble=*/true,
      /*webrtc=*/ShouldEnableWebRtc(data_usage, PowerLevel::kHighPower),
      /*wifi_lan=*/
      ShouldEnableWifiLan(data_usage, PowerLevel::kHighPower) &&
          kIsWifiLanDiscoverySupported);
  NS_LOG(VERBOSE) << __func__ << ": "
                  << "data_usage=" << data_usage << ", allowed_mediums="
                  << MediumSelectionToString(*allowed_mediums);

  discovery_listener_ = listener;
  nearby_connections->StartDiscovery(
      service_id_,
      DiscoveryOptions::New(
          kStrategy, std::move(allowed_mediums),
          device::BluetoothUUID(kFastAdvertisementServiceUuid),
          /*is_out_of_band_connection=*/false),
      endpoint_discovery_listener_.BindNewPipeAndPassRemote(),
      std::move(callback));
}

void NearbyConnectionsManagerImpl::StopDiscovery() {
  discovered_endpoints_.clear();
  discovery_listener_ = nullptr;
  endpoint_discovery_listener_.reset();

  // TODO(https://crbug.com/1177088): Determine if we should attempt to bind to
  // process.
  if (!process_reference_)
    return;

  process_reference_->GetNearbyConnections()->StopDiscovery(
      service_id_, base::BindOnce([](ConnectionsStatus status) {
        NS_LOG(VERBOSE) << __func__
                        << ": Stop discovery attempted over Nearby "
                           "Connections with result: "
                        << ConnectionsStatusToString(status);
      }));
}

void NearbyConnectionsManagerImpl::Connect(
    std::vector<uint8_t> endpoint_info,
    const std::string& endpoint_id,
    absl::optional<std::vector<uint8_t>> bluetooth_mac_address,
    DataUsage data_usage,
    NearbyConnectionCallback callback) {
  // TODO(https://crbug.com/1177088): Determine if we should attempt to bind to
  // process.
  if (!process_reference_) {
    std::move(callback).Run(nullptr);
    return;
  }

  if (bluetooth_mac_address && bluetooth_mac_address->size() != 6)
    bluetooth_mac_address.reset();

  auto allowed_mediums = MediumSelection::New(
      /*bluetooth=*/true,
      /*ble=*/false, ShouldEnableWebRtc(data_usage, PowerLevel::kHighPower),
      /*wifi_lan=*/ShouldEnableWifiLan(data_usage, PowerLevel::kHighPower));
  NS_LOG(VERBOSE) << __func__ << ": "
                  << "data_usage=" << data_usage << ", allowed_mediums="
                  << MediumSelectionToString(*allowed_mediums);

  mojo::PendingRemote<ConnectionLifecycleListener> lifecycle_listener;
  connection_lifecycle_listeners_.Add(
      this, lifecycle_listener.InitWithNewPipeAndPassReceiver());

  auto result =
      pending_outgoing_connections_.emplace(endpoint_id, std::move(callback));
  DCHECK(result.second);

  auto timeout_timer = std::make_unique<base::OneShotTimer>();
  timeout_timer->Start(
      FROM_HERE, kInitiateNearbyConnectionTimeout,
      base::BindOnce(&NearbyConnectionsManagerImpl::OnConnectionTimedOut,
                     weak_ptr_factory_.GetWeakPtr(), endpoint_id));
  connect_timeout_timers_.emplace(endpoint_id, std::move(timeout_timer));

  process_reference_->GetNearbyConnections()->RequestConnection(
      service_id_, endpoint_info, endpoint_id,
      ConnectionOptions::New(std::move(allowed_mediums),
                             std::move(bluetooth_mac_address),
                             /*keep_alive_interval_millis=*/absl::nullopt,
                             /*keep_alive_timeout_millis=*/absl::nullopt),
      std::move(lifecycle_listener),
      base::BindOnce(&NearbyConnectionsManagerImpl::OnConnectionRequested,
                     weak_ptr_factory_.GetWeakPtr(), endpoint_id));
}

void NearbyConnectionsManagerImpl::OnConnectionTimedOut(
    const std::string& endpoint_id) {
  NS_LOG(ERROR) << "Failed to connect to the remote shareTarget: Timed out.";
  Disconnect(endpoint_id);
}

void NearbyConnectionsManagerImpl::OnConnectionRequested(
    const std::string& endpoint_id,
    ConnectionsStatus status) {
  auto it = pending_outgoing_connections_.find(endpoint_id);
  if (it == pending_outgoing_connections_.end())
    return;

  if (status != ConnectionsStatus::kSuccess) {
    NS_LOG(ERROR) << "Failed to connect to the remote shareTarget: "
                  << ConnectionsStatusToString(status);
    Disconnect(endpoint_id);
    return;
  }

  // TODO(crbug/1111458): Support TransferManager.
}

void NearbyConnectionsManagerImpl::Disconnect(const std::string& endpoint_id) {
  // TODO(https://crbug.com/1177088): Determine if we should attempt to bind to
  // process.
  if (!process_reference_)
    return;

  process_reference_->GetNearbyConnections()->DisconnectFromEndpoint(
      service_id_, endpoint_id,
      base::BindOnce(
          [](const std::string& endpoint_id, ConnectionsStatus status) {
            NS_LOG(VERBOSE)
                << __func__ << ": Disconnecting from endpoint " << endpoint_id
                << " attempted over Nearby Connections with result: "
                << ConnectionsStatusToString(status);
          },
          endpoint_id));

  OnDisconnected(endpoint_id);
  NS_LOG(INFO) << "Disconnected from " << endpoint_id;
}

void NearbyConnectionsManagerImpl::Send(
    const std::string& endpoint_id,
    PayloadPtr payload,
    base::WeakPtr<PayloadStatusListener> listener) {
  // TODO(https://crbug.com/1177088): Determine if we should attempt to bind to
  // process.
  if (!process_reference_)
    return;

  if (listener)
    RegisterPayloadStatusListener(payload->id, listener);

  process_reference_->GetNearbyConnections()->SendPayload(
      service_id_, {endpoint_id}, std::move(payload),
      base::BindOnce(
          [](const std::string& endpoint_id, ConnectionsStatus status) {
            NS_LOG(VERBOSE)
                << __func__ << ": Sending payload to endpoint " << endpoint_id
                << " attempted over Nearby Connections with result: "
                << ConnectionsStatusToString(status);
          },
          endpoint_id));
}

void NearbyConnectionsManagerImpl::RegisterPayloadStatusListener(
    int64_t payload_id,
    base::WeakPtr<PayloadStatusListener> listener) {
  payload_status_listeners_.insert_or_assign(payload_id, listener);
}

void NearbyConnectionsManagerImpl::RegisterPayloadPath(
    int64_t payload_id,
    const base::FilePath& file_path,
    ConnectionsCallback callback) {
  if (!process_reference_)
    return;

  DCHECK(!file_path.empty());

  file_handler_.CreateFile(
      file_path, base::BindOnce(&NearbyConnectionsManagerImpl::OnFileCreated,
                                weak_ptr_factory_.GetWeakPtr(), payload_id,
                                std::move(callback)));
}

void NearbyConnectionsManagerImpl::OnFileCreated(
    int64_t payload_id,
    ConnectionsCallback callback,
    NearbyFileHandler::CreateFileResult result) {
  // TODO(https://crbug.com/1177088): Determine if we should attempt to bind to
  // process.
  if (!process_reference_)
    return;

  process_reference_->GetNearbyConnections()->RegisterPayloadFile(
      service_id_, payload_id, std::move(result.input_file),
      std::move(result.output_file), std::move(callback));
}

NearbyConnectionsManagerImpl::Payload*
NearbyConnectionsManagerImpl::GetIncomingPayload(int64_t payload_id) {
  auto it = incoming_payloads_.find(payload_id);
  if (it == incoming_payloads_.end())
    return nullptr;

  return it->second.get();
}

void NearbyConnectionsManagerImpl::Cancel(int64_t payload_id) {
  // TODO(https://crbug.com/1177088): Determine if we should attempt to bind to
  // process.
  if (!process_reference_)
    return;

  auto it = payload_status_listeners_.find(payload_id);
  if (it != payload_status_listeners_.end()) {
    base::WeakPtr<PayloadStatusListener> listener = it->second;
    payload_status_listeners_.erase(payload_id);

    // Note: The listener might be invalidated, for example, if it is shared
    // with another payload in the same transfer.
    if (listener) {
      listener->OnStatusUpdate(
          PayloadTransferUpdate::New(payload_id, PayloadStatus::kCanceled,
                                     /*total_bytes=*/0,
                                     /*bytes_transferred=*/0),
          /*upgraded_medium=*/absl::nullopt);
    }
  }

  process_reference_->GetNearbyConnections()->CancelPayload(
      service_id_, payload_id,
      base::BindOnce(
          [](int64_t payload_id, ConnectionsStatus status) {
            NS_LOG(VERBOSE)
                << __func__ << ": Cancelling payload to id " << payload_id
                << " attempted over Nearby Connections with result: "
                << ConnectionsStatusToString(status);
          },
          payload_id));
  NS_LOG(INFO) << "Cancelling payload: " << payload_id;
}

void NearbyConnectionsManagerImpl::ClearIncomingPayloads() {
  std::vector<PayloadPtr> payloads;
  for (auto& it : incoming_payloads_) {
    payloads.push_back(std::move(it.second));
    payload_status_listeners_.erase(it.first);
  }

  file_handler_.ReleaseFilePayloads(std::move(payloads));
  incoming_payloads_.clear();
}

absl::optional<std::vector<uint8_t>>
NearbyConnectionsManagerImpl::GetRawAuthenticationToken(
    const std::string& endpoint_id) {
  auto it = connection_info_map_.find(endpoint_id);
  if (it == connection_info_map_.end())
    return absl::nullopt;

  return it->second->raw_authentication_token;
}

void NearbyConnectionsManagerImpl::UpgradeBandwidth(
    const std::string& endpoint_id) {
  // TODO(https://crbug.com/1177088): Determine if we should attempt to bind to
  // process.
  if (!process_reference_)
    return;

  // The only bandwidth upgrade mediums at this point are WebRTC and WifiLan.
  if (!base::FeatureList::IsEnabled(features::kNearbySharingWebRtc) &&
      !base::FeatureList::IsEnabled(features::kNearbySharingWifiLan)) {
    return;
  }

  requested_bwu_endpoint_ids_.emplace(endpoint_id);
  process_reference_->GetNearbyConnections()->InitiateBandwidthUpgrade(
      service_id_, endpoint_id,
      base::BindOnce(
          [](const std::string& endpoint_id, ConnectionsStatus status) {
            NS_LOG(VERBOSE)
                << __func__ << ": Bandwidth upgrade attempted to endpoint "
                << endpoint_id << "over Nearby Connections with result: "
                << ConnectionsStatusToString(status);
            base::UmaHistogramBoolean(
                "Nearby.Share.Medium.InitiateBandwidthUpgradeResult",
                status == ConnectionsStatus::kSuccess);
          },
          endpoint_id));
}

void NearbyConnectionsManagerImpl::OnNearbyProcessStopped(
    ash::nearby::NearbyProcessManager::NearbyProcessShutdownReason) {
  NS_LOG(VERBOSE) << __func__;
  Reset();
}

void NearbyConnectionsManagerImpl::OnEndpointFound(
    const std::string& endpoint_id,
    DiscoveredEndpointInfoPtr info) {
  if (!discovery_listener_) {
    NS_LOG(INFO) << "Ignoring discovered endpoint "
                 << base::HexEncode(info->endpoint_info.data(),
                                    info->endpoint_info.size())
                 << " because we're no longer "
                    "in discovery mode";
    return;
  }

  auto result = discovered_endpoints_.insert(endpoint_id);
  if (!result.second) {
    NS_LOG(INFO) << "Ignoring discovered endpoint "
                 << base::HexEncode(info->endpoint_info.data(),
                                    info->endpoint_info.size())
                 << " because we've already "
                    "reported this endpoint";
    return;
  }

  discovery_listener_->OnEndpointDiscovered(endpoint_id, info->endpoint_info);
  NS_LOG(INFO) << "Discovered "
               << base::HexEncode(info->endpoint_info.data(),
                                  info->endpoint_info.size())
               << " over Nearby Connections";
}

void NearbyConnectionsManagerImpl::OnEndpointLost(
    const std::string& endpoint_id) {
  if (!discovered_endpoints_.erase(endpoint_id)) {
    NS_LOG(INFO) << "Ignoring lost endpoint " << endpoint_id
                 << " because we haven't reported this endpoint";
    return;
  }

  if (!discovery_listener_) {
    NS_LOG(INFO) << "Ignoring lost endpoint " << endpoint_id
                 << " because we're no longer in discovery mode";
    return;
  }

  discovery_listener_->OnEndpointLost(endpoint_id);
  NS_LOG(INFO) << "Endpoint " << endpoint_id << " lost over Nearby Connections";
}

void NearbyConnectionsManagerImpl::OnConnectionInitiated(
    const std::string& endpoint_id,
    ConnectionInfoPtr info) {
  // TODO(https://crbug.com/1177088): Determine if we should attempt to bind to
  // process.
  if (!process_reference_)
    return;

  auto result = connection_info_map_.emplace(endpoint_id, std::move(info));
  DCHECK(result.second);

  mojo::PendingRemote<PayloadListener> payload_listener;
  payload_listeners_.Add(this,
                         payload_listener.InitWithNewPipeAndPassReceiver());

  process_reference_->GetNearbyConnections()->AcceptConnection(
      service_id_, endpoint_id, std::move(payload_listener),
      base::BindOnce(
          [](const std::string& endpoint_id, ConnectionsStatus status) {
            NS_LOG(VERBOSE)
                << __func__ << ": Accept connection attempted to endpoint "
                << endpoint_id << " over Nearby Connections with result: "
                << ConnectionsStatusToString(status);
          },
          endpoint_id));
}

void NearbyConnectionsManagerImpl::OnConnectionAccepted(
    const std::string& endpoint_id) {
  auto it = connection_info_map_.find(endpoint_id);
  if (it == connection_info_map_.end())
    return;

  if (it->second->is_incoming_connection) {
    if (!incoming_connection_listener_) {
      // Not in advertising mode.
      Disconnect(endpoint_id);
      return;
    }

    auto result = connections_.emplace(
        endpoint_id, std::make_unique<NearbyConnectionImpl>(this, endpoint_id));
    DCHECK(result.second);
    incoming_connection_listener_->OnIncomingConnection(
        endpoint_id, it->second->endpoint_info, result.first->second.get());
  } else {
    auto pending_it = pending_outgoing_connections_.find(endpoint_id);
    if (pending_it == pending_outgoing_connections_.end()) {
      Disconnect(endpoint_id);
      return;
    }

    auto result = connections_.emplace(
        endpoint_id, std::make_unique<NearbyConnectionImpl>(this, endpoint_id));
    DCHECK(result.second);
    std::move(pending_it->second).Run(result.first->second.get());
    pending_outgoing_connections_.erase(pending_it);
    connect_timeout_timers_.erase(endpoint_id);
  }
}

void NearbyConnectionsManagerImpl::OnConnectionRejected(
    const std::string& endpoint_id,
    Status status) {
  connection_info_map_.erase(endpoint_id);

  auto it = pending_outgoing_connections_.find(endpoint_id);
  if (it != pending_outgoing_connections_.end()) {
    std::move(it->second).Run(nullptr);
    pending_outgoing_connections_.erase(it);
    connect_timeout_timers_.erase(endpoint_id);
  }

  // TODO(crbug/1111458): Support TransferManager.
}

void NearbyConnectionsManagerImpl::OnDisconnected(
    const std::string& endpoint_id) {
  connection_info_map_.erase(endpoint_id);

  auto it = pending_outgoing_connections_.find(endpoint_id);
  if (it != pending_outgoing_connections_.end()) {
    std::move(it->second).Run(nullptr);
    pending_outgoing_connections_.erase(it);
    connect_timeout_timers_.erase(endpoint_id);
  }

  connections_.erase(endpoint_id);

  if (base::Contains(requested_bwu_endpoint_ids_, endpoint_id)) {
    base::UmaHistogramBoolean(
        "Nearby.Share.Medium.RequestedBandwidthUpgradeResult",
        base::Contains(current_upgraded_mediums_, endpoint_id));
  }
  requested_bwu_endpoint_ids_.erase(endpoint_id);
  current_upgraded_mediums_.erase(endpoint_id);

  // TODO(crbug/1111458): Support TransferManager.
}

void NearbyConnectionsManagerImpl::OnBandwidthChanged(
    const std::string& endpoint_id,
    Medium medium) {
  NS_LOG(VERBOSE) << __func__ << ": Changed to medium=" << medium
                  << "; endpoint_id=" << endpoint_id;
  base::UmaHistogramEnumeration("Nearby.Share.Medium.ChangedToMedium", medium);
  current_upgraded_mediums_.insert_or_assign(endpoint_id, medium);
  // TODO(crbug/1111458): Support TransferManager.
}

void NearbyConnectionsManagerImpl::OnPayloadReceived(
    const std::string& endpoint_id,
    PayloadPtr payload) {
  auto result = incoming_payloads_.emplace(payload->id, std::move(payload));
  DCHECK(result.second);
}

void NearbyConnectionsManagerImpl::OnPayloadTransferUpdate(
    const std::string& endpoint_id,
    PayloadTransferUpdatePtr update) {
  // TODO(https://crbug.com/1177088): Determine if we should attempt to bind to
  // process.
  if (!process_reference_)
    return;

  // If this is a payload we've registered for, then forward its status to the
  // PayloadStatusListener if it still exists. We don't need to do anything more
  // with the payload.
  auto listener_it = payload_status_listeners_.find(update->payload_id);
  if (listener_it != payload_status_listeners_.end()) {
    base::WeakPtr<PayloadStatusListener> listener = listener_it->second;
    switch (update->status) {
      case PayloadStatus::kInProgress:
        break;
      case PayloadStatus::kSuccess:
      case PayloadStatus::kCanceled:
      case PayloadStatus::kFailure:
        payload_status_listeners_.erase(update->payload_id);
        break;
    }
    // Note: The listener might be invalidated, for example, if it is shared
    // with another payload in the same transfer.
    if (listener) {
      listener->OnStatusUpdate(std::move(update),
                               GetUpgradedMedium(endpoint_id));
    }
    return;
  }

  // If this is an incoming payload that we have not registered for, then we'll
  // treat it as a control frame (eg. IntroductionFrame) and forward it to the
  // associated NearbyConnection.
  auto payload_it = incoming_payloads_.find(update->payload_id);
  if (payload_it == incoming_payloads_.end())
    return;

  if (!payload_it->second->content->is_bytes()) {
    NS_LOG(WARNING) << "Received unknown payload of file type. Cancelling.";
    process_reference_->GetNearbyConnections()->CancelPayload(
        service_id_, payload_it->first, base::DoNothing());
    return;
  }

  if (update->status != PayloadStatus::kSuccess)
    return;

  auto connections_it = connections_.find(endpoint_id);
  if (connections_it == connections_.end())
    return;

  NS_LOG(INFO) << "Writing incoming byte message to NearbyConnection.";
  connections_it->second->WriteMessage(
      payload_it->second->content->get_bytes()->bytes);
}

location::nearby::connections::mojom::NearbyConnections*
NearbyConnectionsManagerImpl::GetNearbyConnections() {
  if (!process_reference_) {
    process_reference_ = process_manager_->GetNearbyProcessReference(
        base::BindOnce(&NearbyConnectionsManagerImpl::OnNearbyProcessStopped,
                       base::Unretained(this)));

    if (!process_reference_) {
      NS_LOG(WARNING) << __func__
                      << "Failed to get a reference to the nearby process.";
      return nullptr;
    }
  }

  location::nearby::connections::mojom::NearbyConnections* nearby_connections =
      process_reference_->GetNearbyConnections().get();

  if (!nearby_connections)
    NS_LOG(WARNING)
        << __func__
        << "Failed to get a nearby connections from process reference.";

  return nearby_connections;
}

void NearbyConnectionsManagerImpl::Reset() {
  if (process_reference_) {
    process_reference_->GetNearbyConnections()->StopAllEndpoints(
        service_id_, base::BindOnce([](ConnectionsStatus status) {
          NS_LOG(VERBOSE) << __func__
                          << ": Stop all endpoints attempted over Nearby "
                             "Connections with result: "
                          << ConnectionsStatusToString(status);
        }));
  }
  process_reference_.reset();
  discovered_endpoints_.clear();
  payload_status_listeners_.clear();
  ClearIncomingPayloads();
  connections_.clear();
  connection_info_map_.clear();
  discovery_listener_ = nullptr;
  incoming_connection_listener_ = nullptr;
  endpoint_discovery_listener_.reset();
  connect_timeout_timers_.clear();
  requested_bwu_endpoint_ids_.clear();
  current_upgraded_mediums_.clear();

  for (auto& entry : pending_outgoing_connections_)
    std::move(entry.second).Run(/*connection=*/nullptr);

  pending_outgoing_connections_.clear();
}

absl::optional<location::nearby::connections::mojom::Medium>
NearbyConnectionsManagerImpl::GetUpgradedMedium(
    const std::string& endpoint_id) const {
  const auto it = current_upgraded_mediums_.find(endpoint_id);
  if (it == current_upgraded_mediums_.end())
    return absl::nullopt;

  return it->second;
}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.17.1: http://docutils.sourceforge.net/" />

    <title>signature — MetPy 1.1</title>

  <link href="../../_static/css/theme.css" rel="stylesheet" />
  <link href="../../_static/css/index.f6b7ca918bee2f46fd9abac01cfb07d5.css" rel="stylesheet" />

  <link rel="stylesheet"
    href="../../_static/vendor/fontawesome/5.13.0/css/all.min.css">
  <link rel="preload" as="font" type="font/woff2" crossorigin
    href="../../_static/vendor/fontawesome/5.13.0/webfonts/fa-solid-900.woff2">
  <link rel="preload" as="font" type="font/woff2" crossorigin
    href="../../_static/vendor/fontawesome/5.13.0/webfonts/fa-brands-400.woff2">

    <link rel="stylesheet" type="text/css" href="../../_static/pygments.css" />
    <link rel="stylesheet" type="text/css" href="../../_static/basic.css" />
    <link rel="stylesheet" type="text/css" href="../../_static/plot_directive.css" />
    <link rel="stylesheet" type="text/css" href="../../_static/gallery.css" />
    <link rel="stylesheet" type="text/css" href="../../_static/gallery-binder.css" />
    <link rel="stylesheet" type="text/css" href="../../_static/gallery-dataframe.css" />
    <link rel="stylesheet" type="text/css" href="../../_static/gallery-rendered-html.css" />
    <link rel="stylesheet" type="text/css" href="../../_static/theme-unidata.css" />

  <link rel="preload" as="script" href="../../_static/js/index.1e043a052b0af929e4d8.js">

    <link rel="shortcut icon" href="../../_static/metpy_32x32.ico"/>
    <link rel="index" title="Index" href="../../genindex.html" />
    <link rel="search" title="Search" href="../../search.html" />
    <link rel="next" title="Parameter" href="metpy.units.Parameter.html" />
    <link rel="prev" title="pandas_dataframe_to_unit_arrays" href="metpy.units.pandas_dataframe_to_unit_arrays.html" />

    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="docsearch:language" content="en" />
    <link rel="canonical" href="https://unidata.github.io/MetPy/latest/api/generated/metpy.units.signature.html" />

    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbar-menu" aria-controls="navbar-menu" aria-expanded="false" aria-label="Toggle navigation">

    </button>

            Version 1.1

            User Guide

            Reference Guide

            Developer's Guide

            Example Gallery

            Support

            Release Notes

      <form class="bd-search d-flex align-items-center" action="../../search.html" method="get">

  <input type="search" class="form-control" name="q" id="search-input" placeholder="Search the docs ..." aria-label="Search the docs ..." autocomplete="off" >
</form>

   constants

   units

     check_units

     concatenate

     masked_array

     pandas_dataframe_to_unit_arrays

     signature

     Parameter

     DimensionalityError

     UndefinedUnitError

   metpy.io

   calc

   metpy.plots

   ctables

   interpolate

   xarray

   References

signature¶

metpy.units.signature(obj, *, follow_wrapped=True)[source]¶

Get a signature object for the passed callable.

    pandas_dataframe_to_unit_arrays
    Parameter

          © Copyright 2008–2021, MetPy Developers.Development is supported by Unidata and the National Science Foundation..

        Last updated on Aug 09, 2021 at 17:24:01.

        Created using Sphinx 4.1.2.


text:
require 'json'
require 'xcov/version'
require 'xcov/manager'
require 'xcov/options'
require 'xcov/ignore_handler'
require 'xcov/error_handler'
require 'xcov/coveralls_handler'
require 'xcov/slack_poster'
require 'xcov/model/base'
require 'xcov/model/report'
require 'xcov/model/target'
require 'xcov/model/source'
require 'xcov/model/function'
require 'xcov/model/line'
require 'xcov/model/range'
require 'xcov/project_extensions'
require 'fastlane_core'

module Xcov
  class << self

    attr_accessor :config
    attr_accessor :ignore_handler
    attr_accessor :project

    def project=(value)
      @project = value
      @project.select_scheme
    end

  end

  Helper = FastlaneCore::Helper
  UI = FastlaneCore::UI

end


text:
@interface StringValidator : Validator

@property (nonatomic) int minLength;
@property (nonatomic) int maxLength;
@property (nonatomic) NSMutableArray<NSString *> *restrictedChars;

@end


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\Schema;

class AddLeagueRelationToTeams extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('teams', function (Blueprint $table) {
            $table->integer('leagueId')->unsigned();

            $table->foreign('leagueId')->references('id')->on('leagues')
                ->onDelete('restrict')
                ->onUpdate('restrict');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('teams', function (Blueprint $table) {
            $table->dropUnique('teams_leagueid_foreign');

            $table->dropColumn('leagueId');
        });
    }
}


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;">
<meta charset="utf-8">
<title>Phing API Documentation » \GitPushTask</title>
<meta name="author" content="Mike van Riel">
<meta name="description" content="">
<link href="../css/template.css" rel="stylesheet" media="all">
<link rel="shortcut icon" href="../img/favicon.ico">
<link rel="apple-touch-icon" href="../img/apple-touch-icon.png">
<link rel="apple-touch-icon" sizes="72x72" href="../img/apple-touch-icon-72x72.png">
<link rel="apple-touch-icon" sizes="114x114" href="../img/apple-touch-icon-114x114.png">

Phing API Documentation

                                    API Documentation

Packages

 Default

 JSMin

 Parallel

 Phing

 phing

                                    Charts

 Class hierarchy diagram

                                    Reports

 Errors
                2573

 Markers

todo
                15

fixme
                8

 Deprecated elements
                11

Back to top

                            Javascript is disabled; several features are only available
                            if Javascript is enabled.

<button class="btn public active" title="Show public elements">Public</button><button class="btn protected" title="Show protected elements">Protected</button><button class="btn private" title="Show private elements">Private</button><button class="btn inherited active" title="Show inherited elements">Inherited</button>

<button class="btn details" title="Show descriptions and method names"></button><button class="btn simple" title="Show only method names"></button>

 Methods

getAll()

getAll()

getDelete()

getDelete()

Returns the textual description of the task
getDescription()

getDestination()

getDestination()

getForce()

getForce()

Get path to git executable
getGitPath()

Returns the location within the buildfile this task occurs.
getLocation()

getMirror()

getMirror()

Returns the owning target of this task.
getOwningTarget()

Returns a reference to current project
getProject()

getQuiet()

getQuiet()

getRefspec()

getRefspec()

Get repository directory
getRepository()

Returns the wrapper object for runtime configuration
getRuntimeConfigurableWrapper()

getTags()

getTags()

Returns the name of task, used only for log messages
getTaskName()

Returns the name of the task under which it was invoked,
usually the XML tagname
getTaskType()

Initialize Task.
init()

isAllRemotes()

isAllRemotes()

isDelete()

isDelete()

isForce()

isForce()

isMirror()

isMirror()

isQuiet()

isQuiet()

isTags()

isTags()

Provides a project level log event to the task.
log()

The main entry point for the task
main()

Configure this task if it hasn't been done already.
maybeConfigure()

Perfrom this task
perform()

setAll()

setAll()

setDelete()

setDelete()

Sets a textual description of the task
setDescription()

setDestination()

setDestination()

setForce()

setForce()

Set path to git executable
setGitPath()

Sets the location within the buildfile this task occurs.
setLocation()

setMirror()

setMirror()

Sets the owning target this task belongs to.
setOwningTarget()

References the project to the current component.
setProject()

setQuiet()

setQuiet()

setRefspec()

setRefspec()

Set repository directory
setRepository()

Sets the wrapper object this task should use for runtime
 configurable elements.
setRuntimeConfigurableWrapper()

setTags()

setTags()

Sets the name of this task for log messages
setTaskName()

Sets the type of the task.
setTaskType()

» Protected

getGitClient()

getGitClient()

Returns a name
getRegisterSlot()

 Properties

» Protected

$description

$location

$project

$target

$taskName

$taskType

$wrapper

» Private

$allRemotes

$delete

$destination

$force

$gitClient

$gitPath

$mirror

$quiet

$refspec

$repository

$tags

\

global

\GitPushTask

Wrapper aroung git-push

Use Project#createTask to register a new Task.

author
Victor Farazdagi

version
$Id: a01e7e9f6cc92e419e82b4e99e4a45de6a61eba8 $

package
phing.tasks.ext.git

see
\global\VersionControl_Git

since
2.4.3

link
http://www.kernel.org/pub/software/scm/git/docs/git-push.html

copyright
2001,2002 THYRELL. All rights reserved

 Methods

getAll()

getAll()

getDelete()

getDelete()

Returns the textual description of the task

getDescription() : string

Inherited

inherited_from
\Task::getDescription()

inherited_from
\GitBaseTask::getDescription()

Returns

stringThe text description of the task

getDestination()

getDestination()

getForce()

getForce()

Get path to git executable

getGitPath() : string

Inherited

inherited_from
\GitBaseTask::getGitPath()

Returns

string

Returns the location within the buildfile this task occurs.

getLocation() : \Location

Inherited

Used
by BuildException to give detailed error messages.

inherited_from
\Task::getLocation()

inherited_from
\GitBaseTask::getLocation()

Returns

\LocationThe location object describing the position of this
                 task within the buildfile.

getMirror()

getMirror()

Returns the owning target of this task.

getOwningTarget() : \Target

Inherited

inherited_from
\Task::getOwningTarget()

inherited_from
\GitBaseTask::getOwningTarget()

Returns

\TargetThe target object that owns this task

Returns a reference to current project

getProject() : \Project

Inherited

inherited_from
\ProjectComponent::getProject()

inherited_from
\Task::getProject()

inherited_from
\GitBaseTask::getProject()

Returns

\ProjectReference to current porject object

getQuiet()

getQuiet()

getRefspec()

getRefspec()

Get repository directory

getRepository() : string

Inherited

inherited_from
\GitBaseTask::getRepository()

Returns

string

Returns the wrapper object for runtime configuration

getRuntimeConfigurableWrapper() : \RuntimeConfigurable

Inherited

inherited_from
\Task::getRuntimeConfigurableWrapper()

inherited_from
\GitBaseTask::getRuntimeConfigurableWrapper()

Returns

\RuntimeConfigurableThe wrapper object used by this task

getTags()

getTags()

Returns the name of task, used only for log messages

getTaskName() : string

Inherited

inherited_from
\Task::getTaskName()

inherited_from
\GitBaseTask::getTaskName()

Returns

stringName of this task

Returns the name of the task under which it was invoked,
usually the XML tagname

getTaskType() : string

Inherited

inherited_from
\Task::getTaskType()

inherited_from
\GitBaseTask::getTaskType()

Returns

stringThe type of this task (XML Tag)

Initialize Task.

init()

Inherited

Check and include necessary libraries.

inherited_from
\GitBaseTask::init()

Exceptions

\BuildException

isAllRemotes()

isAllRemotes()

isDelete()

isDelete()

isForce()

isForce()

isMirror()

isMirror()

isQuiet()

isQuiet()

isTags()

isTags()

Provides a project level log event to the task.

log(string $msg, integer $level)

Inherited

see
\global\BuildEvent

see
\global\BuildListener

inherited_from
\Task::log()

inherited_from
\GitBaseTask::log()

Parameters

$msg

string
The message to log

$level

integer
The priority of the message

The main entry point for the task

main()

This method may be
 called more than once, if the task is invoked more than once. For
 example, if target1 and target2 both depend on target3, then running
 phing target1 target2 will run all tasks in target3 twice.

Should throw a BuildException if someting goes wrong with the build

This is abstract here. Must be overloaded by real tasks.

Configure this task if it hasn't been done already.

maybeConfigure()

Inherited

inherited_from
\Task::maybeConfigure()

inherited_from
\GitBaseTask::maybeConfigure()

Perfrom this task

perform()

Inherited

inherited_from
\Task::perform()

inherited_from
\GitBaseTask::perform()

setAll()

setAll($flag)

Parameters

$flag

setDelete()

setDelete($flag)

Parameters

$flag

Sets a textual description of the task

setDescription(string $desc)

Inherited

inherited_from
\Task::setDescription()

inherited_from
\GitBaseTask::setDescription()

Parameters

$desc

string
The text describing the task

setDestination()

setDestination($destination)

Parameters

$destination

setForce()

setForce($flag)

Parameters

$flag

Set path to git executable

setGitPath(string $gitPath) : \GitBaseTask

Inherited

inherited_from
\GitBaseTask::setGitPath()

Parameters

$gitPath

string
New path to git repository

Returns

\GitBaseTask

Sets the location within the buildfile this task occurs.

setLocation(\Location $location)

Inherited

Called by
the parser to set location information.

inherited_from
\Task::setLocation()

inherited_from
\GitBaseTask::setLocation()

Parameters

$location

\Location
The location object describing the position of this task within the buildfile.

setMirror()

setMirror($flag)

Parameters

$flag

Sets the owning target this task belongs to.

setOwningTarget(\Target $target)

Inherited

inherited_from
\Task::setOwningTarget()

inherited_from
\GitBaseTask::setOwningTarget()

Parameters

$target

\Target
Reference to owning target

References the project to the current component.

setProject(\Project $project)

Inherited

inherited_from
\ProjectComponent::setProject()

inherited_from
\Task::setProject()

inherited_from
\GitBaseTask::setProject()

Parameters

$project

\Project
The reference to the current project

setQuiet()

setQuiet($flag)

Parameters

$flag

setRefspec()

setRefspec($spec)

Parameters

$spec

Set repository directory

setRepository(string $repository) : \GitBaseTask

Inherited

inherited_from
\GitBaseTask::setRepository()

Parameters

$repository

string
Repo directory

Returns

\GitBaseTask

Sets the wrapper object this task should use for runtime
 configurable elements.

setRuntimeConfigurableWrapper(\RuntimeConfigurable $wrapper)

Inherited

inherited_from
\Task::setRuntimeConfigurableWrapper()

inherited_from
\GitBaseTask::setRuntimeConfigurableWrapper()

Parameters

$wrapper

\RuntimeConfigurable
The wrapper object this task should use

setTags()

setTags($flag)

Parameters

$flag

Sets the name of this task for log messages

setTaskName(string $name) : string

Inherited

inherited_from
\Task::setTaskName()

inherited_from
\GitBaseTask::setTaskName()

Parameters

$name

string

Returns

stringA string representing the name of this task for log

Sets the type of the task.

setTaskType(string $name)

Inherited

Usually this is the name of the XML tag

inherited_from
\Task::setTaskType()

inherited_from
\GitBaseTask::setTaskType()

Parameters

$name

string
The type of this task (XML Tag)

getGitClient()

getGitClient($reset, $repository)

Inherited

inherited_from
\GitBaseTask::getGitClient()

Parameters

$reset

$repository

Returns a name

getRegisterSlot(string $slotName)

Inherited

inherited_from
\Task::getRegisterSlot()

inherited_from
\GitBaseTask::getRegisterSlot()

Parameters

$slotName

string

 Properties

$description : string

Inherited

inherited_from
\Task::$$description

inherited_from
\GitBaseTask::$$description

$location : \Location

Inherited

inherited_from
\Task::$$location

inherited_from
\GitBaseTask::$$location

$project : \Project

Inherited

inherited_from
\ProjectComponent::$$project

inherited_from
\Task::$$project

inherited_from
\GitBaseTask::$$project

$target : \Target

Inherited

inherited_from
\Task::$$target

inherited_from
\GitBaseTask::$$target

$taskName : string

Inherited

inherited_from
\Task::$$taskName

inherited_from
\GitBaseTask::$$taskName

$taskType : string

Inherited

inherited_from
\Task::$$taskType

inherited_from
\GitBaseTask::$$taskType

$wrapper : \RuntimeConfigurable

Inherited

inherited_from
\Task::$$wrapper

inherited_from
\GitBaseTask::$$wrapper

$allRemotes : boolean

$delete : string

$destination : string

$force : boolean

$gitClient : \VersionControl_Git

Inherited

inherited_from
\GitBaseTask::$$gitClient

$gitPath : string

Inherited

inherited_from
\GitBaseTask::$$gitPath

$mirror : boolean

$quiet : boolean

$refspec : string

$repository : string

Inherited

inherited_from
\GitBaseTask::$$repository

$tags : boolean

            Template is built using Twitter Bootstrap 2 and icons provided by Glyphicons.

            Documentation is powered by phpDocumentor 2.0.0a11 and

            generated on 2012-11-20T07:50:19+01:00.


text:
'use strict'
//Import modules
const express         =  require( 'express' )
const fs 		      =  require( 'fs' )
const app             =  express( )
const bodyParser      =  require('body-parser')
const sequelize       =  require('sequelize')
const session         =  require('express-session')
const bcrypt          =  require('bcrypt-nodejs')
const nodesass        =  require('node-sass')
const passport        =  require('passport')
const Strategy        =  require('passport-facebook').Strategy
const LocalStrategy   =  require('passport-local').Strategy
const cookieParser    =  require('cookie-parser')

app.use (express.static(__dirname + '/static'))
app.use(bodyParser.urlencoded({
  extended: true
}));

app.use(cookieParser())
app.use(session({
	secret: 'oh wow very secret much security',
	resave: true,
	saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());

app.set('views', './views')
app.set('view engine', 'pug')

nodesass.render({
	file: __dirname + '/static/sass/materialize.scss',
	outFile: __dirname + '/static/css/materialize.css'
}, (error, result) => {
	if(!error) {
		fs.writeFile(__dirname + '/static/css/materialize.css', result.css.toString('utf8'), (err) =>{
			if(!err){
				console.log("file written to disk")
			}
		})
	}
})

nodesass.render({
	file: __dirname + '/static/sass/style.scss',
	outFile: __dirname + '/static/css/style.css'
}, (error, result) => {
	if(!error) {
		fs.writeFile(__dirname + '/static/css/style.css', result.css.toString('utf8'), (err) =>{
			if(!err){
				console.log("style written to disk")
			}
		})
	}
	else if (error) {
			throw error
		}
})

//Setting Routes
let homeRouter 		  = require( __dirname + '/routes/home' )
let profile 		  = require( __dirname + '/routes/profile' )
let calculationRouter = require( __dirname+'/routes/calculation' )
let routes            = require(__dirname + '/routes/routes' )

app.use('/', homeRouter )

app.use('/', profile )
app.use('/', calculationRouter )
app.use('/', routes)

//Set port
app.listen(3000, function () {
	console.log('Yep Running')
})


text:
<?php

namespace SOSVelo\Bundle\TemplateBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use Symfony\Component\HttpFoundation\Request;

class TemplateController extends Controller
{
    /**
     * @Apidoc()
     * @Route("/home")
     * @Template()
     */
    public function indexAction(Request $request)
    {

        $id = 'thread_id';
        $thread = $this->container->get('fos_comment.manager.thread')->findThreadById($id);
        if (null === $thread) {
            $thread = $this->container->get('fos_comment.manager.thread')->createThread();
            $thread->setId($id);
            $thread->setPermalink($request->getUri());

            // Add the thread
            $this->container->get('fos_comment.manager.thread')->saveThread($thread);
        }
        $comments = $this->container->get('fos_comment.manager.comment')->findCommentTreeByThread($thread);

        return $this->render('SOSVeloTemplateBundle:Template:index.html.twig',
            array(
                'comments' => $comments,
                'thread' => $thread,
            )
    );
    }

    /**
     * @Apidoc()
     * @Route("/contact")
     * @Template()
     */
    public function contactAction()
    {
        return $this->render('SOSVeloTemplateBundle:Template:contact.html.twig');
    }

    /**
     * @Apidoc()
     * @Route("/generic")
     * @Template()
     */
    public function genericAction()
    {
        return $this->render('SOSVeloTemplateBundle:Template:generic.html.twig');
    }

}


text:
FOUNDATION_EXPORT double FirebaseFacebookAuthUIVersionNumber;

//! Project version string for FirebaseFacebookAuthUI.
FOUNDATION_EXPORT const unsigned char FirebaseFacebookAuthUIVersionString[];

#import "FUIFacebookAuth.h"


text:
{% extends "layout.html" %}

		{% block content %}
Flask-weather-app

Get weather information for any city in the world
{% endblock %}


text:
'use strict';
var React = require('react');
var _ = require('lodash');
var Immutable = require('immutable');
var Highlight = require('react-highlight');

var Tabs = require('react-simpletabs');
var DataComponent = require('./data');
var OptionsComponent = require('./options');
var VizComponent = require('./viz');

var capitalize = function(s) {
    return s && s[0].toUpperCase() + s.slice(1);
};

var styles = {
};

var parseData = function(d) {
    if(_.isArray(d)) {
        d = Immutable.List(d);
    } else if(_.isObject(d)) {
        d = Immutable.Map(d);
    }
    return d;
}

var Editor = React.createClass({

    getDefaultProps: function() {
        return {
            datasets: window.lightning.editor.datasets || [],
            images: window.lightning.editor.sampleImages || [],
            moduleName: window.lightning.editor.moduleName || '',
            initialOptions: window.lightning.editor.sampleOptions || {},
            codeExamples: window.lightning.editor.codeExamples || {},
        };
    },

    getInitialState: function() {
        return {
            data: parseData(this.props.datasets.length ? this.props.datasets[0].data : []),
            options: parseData(this.props.initialOptions),
            selectedTab: 1
        };
    },

    handleDataChange: function(data) {
        this.setState({
            data: parseData(data)
        });
    },

    handleOptionsChange: function(options) {
        this.setState({
            options: parseData(options)
        });
    },

    tabSelected: function(i) {
        this.setState({
            selectedTab: i
        });
    },

    // renderCodeExample: function(example, language) {
    //     return (
    //         <Tabs.Panel title={language}>

    //         </Tabs.Panel>
    //     );
    // },

    // renderCodeExamples: function() {
    //     if(_.keys(this.props.codeExamples).length) {
    //         return _.map(this.props.codeExamples, this.renderCodeExample, this);
    //     }
    //     return '';
    // },

    getTabComponents: function() {
        var components = {
            'Data': <DataComponent datasets={this.props.datasets} initialSelectedData={this.state.data} onChange={this.handleDataChange} />,
            'Options': <OptionsComponent initialOptions={this.state.options} onChange={this.handleOptionsChange} />,
        };

        _.each(this.props.codeExamples, function(example, language) {
            components[capitalize(language) + ' Example'] = <Highlight className={language}>{example}</Highlight>
        });

        return components;
    },

    renderTabComponents: function() {
        var components = this.getTabComponents();
        var tabComponents = [];
        _.each(components, function(val, title) {
            tabComponents.push(<Tabs.Panel title={title} key={title}>{val}</Tabs.Panel>)
        });
        return tabComponents;
    },

    render: function() {
        return (

                            <VizComponent data={this.state.data} options={this.state.options} moduleName={this.props.moduleName} images={this.props.images} />

                                <Tabs onAfterChange={this.tabSelected} tabActive={this.state.selectedTab} className={'tab-container'}>
                                    {this.renderTabComponents()}
                                </Tabs>

        );
    },
});

module.exports = Editor;