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

  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>Get request method name</title>

http_request_method_exists

http_request_method_register

HTTP Functions

PHP Manual

http_request_method_name

(PECL pecl_http >= 0.10.0)

http_request_method_name — Get request method name

Description

   string http_request_method_name
    ( int $method
   )

   Get the literal string representation of a standard or registered request method.

Parameters

method

       request method ID

Return Values

   Returns the request method name as string on success or FALSE on failure.

http_request_method_exists

http_request_method_register

HTTP Functions

PHP Manual

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace PHPSQLParser\builders;
use PHPSQLParser\exceptions\UnableToCreateSQLException;
use PHPSQLParser\utils\ExpressionType;

require_once dirname(__FILE__) . '/../utils/ExpressionType.php';
require_once dirname(__FILE__) . '/../exceptions/UnableToCreateSQLException.php';
require_once dirname(__FILE__) . '/ConstantBuilder.php';
require_once dirname(__FILE__) . '/ReservedBuilder.php';
require_once dirname(__FILE__) . '/OperatorBuilder.php';
require_once dirname(__FILE__) . '/Builder.php';

/**
 * This class implements the builder for the index lock of CREATE INDEX statement.
 * You can overwrite all functions to achieve another handling.
 *
 * @author  André Rothe <andre.rothe@phosco.info>
 * @license http://www.debian.org/misc/bsd.license  BSD License (3 Clause)
 *
 */
class IndexLockBuilder implements Builder {

    protected function buildReserved($parsed) {
        $builder = new ReservedBuilder();
        return $builder->build($parsed);
    }

    protected function buildConstant($parsed) {
        $builder = new ConstantBuilder();
        return $builder->build($parsed);
    }

    protected function buildOperator($parsed) {
        $builder = new OperatorBuilder();
        return $builder->build($parsed);
    }

    public function build(array $parsed) {
        if ($parsed['expr_type'] !== ExpressionType::INDEX_LOCK) {
            return "";
        }
        $sql = "";
        foreach ($parsed['sub_tree'] as $k => $v) {
            $len = strlen($sql);
            $sql .= $this->buildReserved($v);
            $sql .= $this->buildConstant($v);
            $sql .= $this->buildOperator($v);

            if ($len == strlen($sql)) {
                throw new UnableToCreateSQLException('CREATE INDEX lock subtree', $k, $v, 'expr_type');
            }

            $sql .= ' ';
        }
        return substr($sql, 0, -1);
    }
}
?>


text:
package org.jgentleframework.context.injecting.autodetect;

import java.util.List;
import java.util.Map;

import org.jgentleframework.context.injecting.Provider;
import org.jgentleframework.context.injecting.scope.ScopeController;
import org.jgentleframework.context.services.ServiceHandler;
import org.jgentleframework.core.handling.DefinitionManager;

/**
 * This abstract class represents the detector in the chain.
 *
 * @author LE QUOC CHUNG - mailto: <a
 *         href="mailto:skydunkpro@yahoo.com">skydunkpro@yahoo.com</a>
 * @date Mar 5, 2008
 * @see ExtensionPointsDetector
 * @see FirstDetector
 */
public abstract class AbstractDetector implements Detector {
	/** The provider. */
	protected Provider	provider			= null;

	/** The definition manager. */
	DefinitionManager	definitionManager	= null;

	/** The service handler. */
	ServiceHandler		serviceHandler		= null;

	/** The scope controller. */
	ScopeController		scopeController		= null;

	/** The next detector of this detector in the chain. */
	Detector			detectModule		= null;

	/**
	 * The Constructor.
	 *
	 * @param provider
	 *            the provider
	 */
	public AbstractDetector(Provider provider) {

		this.provider = provider;
		definitionManager = this.provider.getDefinitionManager();
		this.serviceHandler = this.provider.getServiceHandler();
		this.scopeController = this.provider.getScopeController();
	}

	/*
	 * (non-Javadoc)
	 * @see
	 * org.jgentleframework.context.injecting.autodetect.Detector#getProvider()
	 */
	public Provider getProvider() {

		return this.provider;
	}

	/*
	 * (non-Javadoc)
	 * @see
	 * org.jgentleframework.context.injecting.autodetect.Detector#getNextDetector
	 * ()
	 */
	public Detector getNextDetector() {

		return detectModule;
	}

	/*
	 * (non-Javadoc)
	 * @see
	 * org.jgentleframework.context.injecting.autodetect.Detector#handling(java
	 * .util.List)
	 */
	public abstract void handling(List<Map<String, Object>> OLArray);

	/*
	 * (non-Javadoc)
	 * @see
	 * org.jgentleframework.context.injecting.autodetect.Detector#setProvider
	 * (org.jgentleframework.context.injecting.Provider)
	 */
	public void setProvider(Provider provider) {

		this.provider = provider;
	}

	/*
	 * (non-Javadoc)
	 * @see
	 * org.jgentleframework.context.injecting.autodetect.Detector#setNextDetector
	 * (org.jgentleframework.context.injecting.autodetect.AbstractDetector)
	 */
	@Override
	public void setNextDetector(Detector detectModule) {

		this.detectModule = detectModule;
	}
}


text:
using FluentFTP.Client.BaseClient;
using System.Threading;
using System.Threading.Tasks;

namespace FluentFTP.Proxy.AsyncProxy {
	/// <summary> A FTP client with a user@host proxy identification. </summary>
	public class AsyncFtpClientUserAtHostProxy : AsyncFtpClientProxy {
		/// <summary> A FTP client with a user@host proxy identification. </summary>
		/// <param name="proxy">Proxy information</param>
		public AsyncFtpClientUserAtHostProxy(FtpProxyProfile proxy)
			: base(proxy) {
			ConnectionType = "User@Host";
		}

		/// <summary>
		/// Creates a new instance of this class. Useful in FTP proxy classes.
		/// </summary>
		protected override BaseFtpClient Create() {
			return new AsyncFtpClientUserAtHostProxy(Proxy);
		}

		/// <summary> Redefine the first dialog: auth with proxy information </summary>
		protected override async Task HandshakeAsync(CancellationToken token = default) {

			// Proxy authentication eventually needed.
			if (Proxy.ProxyCredentials != null) {
				await Authenticate(Proxy.ProxyCredentials.UserName, Proxy.ProxyCredentials.Password, Proxy.ProxyCredentials.Domain, token);
			}

			// Connection USER@Host means to change user name to add host.
			Credentials.UserName = Credentials.UserName + "@" + Host + ":" + Port;
		}
	}
}


text:
namespace Awesomium {
	class DllExport WebCore
	{
	public:
		static WebCore*Initialize(const WebConfig&config);
		static void Shutdown();
		static WebCore*instance();
		virtual WebSession* CreateWebSession(const WebString& path, const WebPreferences& prefs);
		virtual WebView* CreateWebView(int width, int height, WebSession* session = 0, int type = 0);
		virtual void set_surface_factory(SurfaceFactory* factory);
		virtual SurfaceFactory* surface_factory() const;
		virtual void set_resource_interceptor(ResourceInterceptor* interceptor);
		virtual ResourceInterceptor* resource_interceptor() const;
		virtual void Update();
		virtual void Log(const WebString& message, int severity, const WebString& file, int line);
		virtual const char* version_string() const;

		static unsigned int used_memory();
		static unsigned int allocated();
		static void release_memory();

		virtual ~WebCore();

		static WebCore* instance_;
		static ResourceInterceptor*resc;
		static SurfaceFactory*surf;
		static WebView*view;
		static WebSession*sess;
	};

}


text:
using System.Collections.Generic;

namespace Beyova.JPush.V3
{
    /// <summary>
    /// Class Audience
    /// </summary>
    public class Audience : Dictionary<PushTypeV3, List<string>>
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="Audience"/> class.
        /// </summary>
        public Audience()
            : base()
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Audience"/> class.
        /// </summary>
        /// <param name="dictionary">The dictionary.</param>
        public Audience(Dictionary<PushTypeV3, List<string>> dictionary)
            : base(dictionary)
        {
        }

        /// <summary>
        /// Adds the item.
        /// </summary>
        /// <param name="pushType">Type of the push.</param>
        /// <param name="item">The item.</param>
        public void AddItem(PushTypeV3 pushType, string item)
        {
            if (!string.IsNullOrWhiteSpace(item))
            {
                if (!this.ContainsKey(pushType))
                {
                    this.Add(pushType, new List<string>());
                }

                if (!this[pushType].Contains(item))
                {
                    this[pushType].Add(item);
                }
            }
        }
    }
}


text:
package com.evolveum.midpoint.repo.sql.data.common.enums;

import com.evolveum.midpoint.repo.sql.query.definition.JaxbType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.SynchronizationSituationType;

/**
 * @author lazyman
 */
@JaxbType(type = SynchronizationSituationType.class)
public enum RSynchronizationSituation implements SchemaEnum<SynchronizationSituationType> {

    DELETED(SynchronizationSituationType.DELETED),
    UNMATCHED(SynchronizationSituationType.UNMATCHED),
    DISPUTED(SynchronizationSituationType.DISPUTED),
    LINKED(SynchronizationSituationType.LINKED),
    UNLINKED(SynchronizationSituationType.UNLINKED);

    private SynchronizationSituationType syncType;

    private RSynchronizationSituation(SynchronizationSituationType syncType) {
        this.syncType = syncType;
    }

    @Override
    public SynchronizationSituationType getSchemaValue() {
        return syncType;
    }
}


text:
./dirs.sh
sudo mv ~/.bashrc .bashrc_bak
sudo cp bashrc ~/.bashrc

sudo apt-get -y update && sudo apt-get -y upgrade && sudo apt-get -y update

./java.sh
./simple.sh
./zsh.sh
./spotify.sh
./sublime.sh
./IJ.sh
./git.sh


text:
import { JSONObject } from 'tiny-types';

import { Duration } from '../model/Duration';
import { ErrorSerialiser } from './ErrorSerialiser';
import { RuntimeError } from './RuntimeError';

/**
 * Thrown to indicate that an {@apilink Interaction}, a {@apilink Task} or a test scenario
 * took longer to execute than the expected timeout.
 *
 * @group Errors
 */
export class TimeoutExpiredError extends RuntimeError {

    static fromJSON(serialised: JSONObject): TimeoutExpiredError {
        const error = new TimeoutExpiredError(
            serialised.message as string,
            Duration.fromJSON(serialised.timeout as { milliseconds: number }),
            ErrorSerialiser.deserialise(serialised.cause as string | undefined),
        );

        error.stack = serialised.stack as string;

        return error;
    }

    /**
     * @param message
     *  Human-readable description of the error
     *
     * @param timeout
     *  The maximum amount of time an operation was expected to take
     *
     * @param [cause]
     *  The root cause of this {@apilink RuntimeError}, if any
     */
    constructor(
        message: string,
        public readonly timeout: Duration,
        cause?: Error
    ) {
        super(TimeoutExpiredError, message, cause);
    }
}


text: Proxy for Raspberry Pi Camera


text:
package jenkins

import (
	"bytes"
	"fmt"
	"strconv"
	"sync"

	"github.com/sirupsen/logrus"

	"k8s.io/test-infra/prow/config"
	"k8s.io/test-infra/prow/github"
	"k8s.io/test-infra/prow/kube"
	"k8s.io/test-infra/prow/pjutil"
	reportlib "k8s.io/test-infra/prow/report"
)

const (
	testInfra = "https://github.com/kubernetes/test-infra/issues"
)

type kubeClient interface {
	CreateProwJob(kube.ProwJob) (kube.ProwJob, error)
	ListProwJobs(string) ([]kube.ProwJob, error)
	ReplaceProwJob(string, kube.ProwJob) (kube.ProwJob, error)
}

type jenkinsClient interface {
	Build(*kube.ProwJob) error
	ListBuilds(jobs []string) (map[string]JenkinsBuild, error)
	Abort(job string, build *JenkinsBuild) error
}

type githubClient interface {
	BotName() (string, error)
	CreateStatus(org, repo, ref string, s github.Status) error
	ListIssueComments(org, repo string, number int) ([]github.IssueComment, error)
	CreateComment(org, repo string, number int, comment string) error
	DeleteComment(org, repo string, ID int) error
	EditComment(org, repo string, ID int, comment string) error
	GetPullRequestChanges(org, repo string, number int) ([]github.PullRequestChange, error)
}

type configAgent interface {
	Config() *config.Config
}

type syncFn func(kube.ProwJob, chan<- kube.ProwJob, map[string]JenkinsBuild) error

// Controller manages ProwJobs.
type Controller struct {
	kc  kubeClient
	jc  jenkinsClient
	ghc githubClient
	log *logrus.Entry
	ca  configAgent
	// selector that will be applied on prowjobs.
	selector string

	lock sync.RWMutex
	// pendingJobs is a short-lived cache that helps in limiting
	// the maximum concurrency of jobs.
	pendingJobs map[string]int

	pjLock sync.RWMutex
	// shared across the controller and a goroutine that gathers metrics.
	pjs []kube.ProwJob
}

// NewController creates a new Controller from the provided clients.
func NewController(kc *kube.Client, jc *Client, ghc *github.Client, logger *logrus.Entry, ca *config.Agent, selector string) *Controller {
	if logger == nil {
		logger = logrus.NewEntry(logrus.StandardLogger())
	}
	return &Controller{
		kc:          kc,
		jc:          jc,
		ghc:         ghc,
		log:         logger,
		ca:          ca,
		selector:    selector,
		pendingJobs: make(map[string]int),
	}
}

func (c *Controller) config() config.Controller {
	operators := c.ca.Config().JenkinsOperators
	if len(operators) == 1 {
		return operators[0].Controller
	}
	configured := make([]string, 0, len(operators))
	for _, cfg := range operators {
		if cfg.LabelSelectorString == c.selector {
			return cfg.Controller
		}
		configured = append(configured, cfg.LabelSelectorString)
	}
	if len(c.selector) == 0 {
		c.log.Panicf("You need to specify a non-empty --label-selector (existing selectors: %v).", configured)
	} else {
		c.log.Panicf("No config exists for --label-selector=%s.", c.selector)
	}
	return config.Controller{}
}

// canExecuteConcurrently checks whether the provided ProwJob can
// be executed concurrently.
func (c *Controller) canExecuteConcurrently(pj *kube.ProwJob) bool {
	c.lock.Lock()
	defer c.lock.Unlock()

	if max := c.config().MaxConcurrency; max > 0 {
		var running int
		for _, num := range c.pendingJobs {
			running += num
		}
		if running >= max {
			c.log.WithFields(pjutil.ProwJobFields(pj)).Debugf("Not starting another job, already %d running.", running)
			return false
		}
	}

	if pj.Spec.MaxConcurrency == 0 {
		c.pendingJobs[pj.Spec.Job]++
		return true
	}

	numPending := c.pendingJobs[pj.Spec.Job]
	if numPending >= pj.Spec.MaxConcurrency {
		c.log.WithFields(pjutil.ProwJobFields(pj)).Debugf("Not starting another instance of %s, already %d running.", pj.Spec.Job, numPending)
		return false
	}
	c.pendingJobs[pj.Spec.Job]++
	return true
}

// incrementNumPendingJobs increments the amount of
// pending ProwJobs for the given job identifier
func (c *Controller) incrementNumPendingJobs(job string) {
	c.lock.Lock()
	defer c.lock.Unlock()
	c.pendingJobs[job]++
}

// Sync does one sync iteration.
func (c *Controller) Sync() error {
	pjs, err := c.kc.ListProwJobs(c.selector)
	if err != nil {
		return fmt.Errorf("error listing prow jobs: %v", err)
	}
	// Share what we have for gathering metrics.
	c.pjLock.Lock()
	c.pjs = pjs
	c.pjLock.Unlock()

	// TODO: Replace the following filtering with a field selector once CRDs support field selectors.
	// https://github.com/kubernetes/kubernetes/issues/53459
	var jenkinsJobs []kube.ProwJob
	for _, pj := range pjs {
		if pj.Spec.Agent == kube.JenkinsAgent {
			jenkinsJobs = append(jenkinsJobs, pj)
		}
	}
	pjs = jenkinsJobs
	jbs, err := c.jc.ListBuilds(getJenkinsJobs(pjs))
	if err != nil {
		return fmt.Errorf("error listing jenkins builds: %v", err)
	}

	var syncErrs []error
	if err := c.terminateDupes(pjs, jbs); err != nil {
		syncErrs = append(syncErrs, err)
	}

	pendingCh, triggeredCh := pjutil.PartitionActive(pjs)
	errCh := make(chan error, len(pjs))
	reportCh := make(chan kube.ProwJob, len(pjs))

	// Reinstantiate on every resync of the controller instead of trying
	// to keep this in sync with the state of the world.
	c.pendingJobs = make(map[string]int)
	// Sync pending jobs first so we can determine what is the maximum
	// number of new jobs we can trigger when syncing the non-pendings.
	maxSyncRoutines := c.config().MaxGoroutines
	c.log.Debugf("Handling %d pending prowjobs", len(pendingCh))
	syncProwJobs(c.log, c.syncPendingJob, maxSyncRoutines, pendingCh, reportCh, errCh, jbs)
	c.log.Debugf("Handling %d triggered prowjobs", len(triggeredCh))
	syncProwJobs(c.log, c.syncTriggeredJob, maxSyncRoutines, triggeredCh, reportCh, errCh, jbs)

	close(errCh)
	close(reportCh)

	for err := range errCh {
		syncErrs = append(syncErrs, err)
	}

	var reportErrs []error
	reportTemplate := c.config().ReportTemplate
	for report := range reportCh {
		if err := reportlib.Report(c.ghc, reportTemplate, report); err != nil {
			reportErrs = append(reportErrs, err)
		}
	}

	if len(syncErrs) == 0 && len(reportErrs) == 0 {
		return nil
	}
	return fmt.Errorf("errors syncing: %v, errors reporting: %v", syncErrs, reportErrs)
}

// SyncMetrics records metrics for the cached prowjobs.
func (c *Controller) SyncMetrics() {
	c.pjLock.RLock()
	defer c.pjLock.RUnlock()
	kube.GatherProwJobMetrics(c.pjs)
}

// getJenkinsJobs returns all the Jenkins jobs for all active
// prowjobs from the provided list. It handles deduplication.
func getJenkinsJobs(pjs []kube.ProwJob) []string {
	jenkinsJobs := make(map[string]struct{})
	for _, pj := range pjs {
		if pj.Complete() {
			continue
		}
		jenkinsJobs[pj.Spec.Job] = struct{}{}
	}
	var jobs []string
	for job := range jenkinsJobs {
		jobs = append(jobs, job)
	}
	return jobs
}

// terminateDupes aborts presubmits that have a newer version. It modifies pjs
// in-place when it aborts.
func (c *Controller) terminateDupes(pjs []kube.ProwJob, jbs map[string]JenkinsBuild) error {
	// "job org/repo#number" -> newest job
	dupes := make(map[string]int)
	for i, pj := range pjs {
		if pj.Complete() || pj.Spec.Type != kube.PresubmitJob {
			continue
		}
		n := fmt.Sprintf("%s %s/%s#%d", pj.Spec.Job, pj.Spec.Refs.Org, pj.Spec.Refs.Repo, pj.Spec.Refs.Pulls[0].Number)
		prev, ok := dupes[n]
		if !ok {
			dupes[n] = i
			continue
		}
		cancelIndex := i
		if (&pjs[prev].Status.StartTime).Before(&pj.Status.StartTime) {
			cancelIndex = prev
			dupes[n] = i
		}
		toCancel := pjs[cancelIndex]
		// Allow aborting presubmit jobs for commits that have been superseded by
		// newer commits in Github pull requests.
		if c.config().AllowCancellations {
			build, buildExists := jbs[toCancel.ObjectMeta.Name]
			// Avoid cancelling enqueued builds.
			if buildExists && build.IsEnqueued() {
				continue
			}
			// Otherwise, abort it.
			if buildExists {
				if err := c.jc.Abort(toCancel.Spec.Job, &build); err != nil {
					c.log.WithError(err).WithFields(pjutil.ProwJobFields(&toCancel)).Warn("Cannot cancel Jenkins build")
				}
			}
		}
		toCancel.SetComplete()
		prevState := toCancel.Status.State
		toCancel.Status.State = kube.AbortedState
		c.log.WithFields(pjutil.ProwJobFields(&toCancel)).
			WithField("from", prevState).
			WithField("to", toCancel.Status.State).Info("Transitioning states.")
		npj, err := c.kc.ReplaceProwJob(toCancel.ObjectMeta.Name, toCancel)
		if err != nil {
			return err
		}
		pjs[cancelIndex] = npj
	}
	return nil
}

func syncProwJobs(
	l *logrus.Entry,
	syncFn syncFn,
	maxSyncRoutines int,
	jobs <-chan kube.ProwJob,
	reports chan<- kube.ProwJob,
	syncErrors chan<- error,
	jbs map[string]JenkinsBuild,
) {
	goroutines := maxSyncRoutines
	if goroutines > len(jobs) {
		goroutines = len(jobs)
	}
	wg := &sync.WaitGroup{}
	wg.Add(goroutines)
	l.Debugf("Firing up %d goroutines", goroutines)
	for i := 0; i < goroutines; i++ {
		go func() {
			defer wg.Done()
			for pj := range jobs {
				if err := syncFn(pj, reports, jbs); err != nil {
					syncErrors <- err
				}
			}
		}()
	}
	wg.Wait()
}

func (c *Controller) syncPendingJob(pj kube.ProwJob, reports chan<- kube.ProwJob, jbs map[string]JenkinsBuild) error {
	// Record last known state so we can log state transitions.
	prevState := pj.Status.State

	jb, jbExists := jbs[pj.ObjectMeta.Name]
	if !jbExists {
		pj.SetComplete()
		pj.Status.State = kube.ErrorState
		pj.Status.URL = testInfra
		pj.Status.Description = "Error finding Jenkins job."
	} else {
		switch {
		case jb.IsEnqueued():
			// Still in queue.
			c.incrementNumPendingJobs(pj.Spec.Job)
			return nil

		case jb.IsRunning():
			// Build still going.
			c.incrementNumPendingJobs(pj.Spec.Job)
			if pj.Status.Description == "Jenkins job running." {
				return nil
			}
			pj.Status.Description = "Jenkins job running."

		case jb.IsSuccess():
			// Build is complete.
			pj.SetComplete()
			pj.Status.State = kube.SuccessState
			pj.Status.Description = "Jenkins job succeeded."
			for _, nj := range pj.Spec.RunAfterSuccess {
				child := pjutil.NewProwJob(nj, pj.ObjectMeta.Labels)
				if !c.RunAfterSuccessCanRun(&pj, &child, c.ca, c.ghc) {
					continue
				}
				if _, err := c.kc.CreateProwJob(pjutil.NewProwJob(nj, pj.ObjectMeta.Labels)); err != nil {
					return fmt.Errorf("error starting next prowjob: %v", err)
				}
			}

		case jb.IsFailure():
			pj.SetComplete()
			pj.Status.State = kube.FailureState
			pj.Status.Description = "Jenkins job failed."

		case jb.IsAborted():
			pj.SetComplete()
			pj.Status.State = kube.AbortedState
			pj.Status.Description = "Jenkins job aborted."
		}
		// Construct the status URL that will be used in reports.
		pj.Status.PodName = fmt.Sprintf("%s-%d", pj.Spec.Job, jb.Number)
		pj.Status.BuildID = strconv.Itoa(jb.Number)
		var b bytes.Buffer
		if err := c.config().JobURLTemplate.Execute(&b, &pj); err != nil {
			return fmt.Errorf("error executing URL template: %v", err)
		}
		pj.Status.URL = b.String()
	}
	// Report to Github.
	reports <- pj
	if prevState != pj.Status.State {
		c.log.WithFields(pjutil.ProwJobFields(&pj)).
			WithField("from", prevState).
			WithField("to", pj.Status.State).Info("Transitioning states.")
	}
	_, err := c.kc.ReplaceProwJob(pj.ObjectMeta.Name, pj)
	return err
}

func (c *Controller) syncTriggeredJob(pj kube.ProwJob, reports chan<- kube.ProwJob, jbs map[string]JenkinsBuild) error {
	// Record last known state so we can log state transitions.
	prevState := pj.Status.State

	if _, jbExists := jbs[pj.ObjectMeta.Name]; !jbExists {
		// Do not start more jobs than specified.
		if !c.canExecuteConcurrently(&pj) {
			return nil
		}
		// Start the Jenkins job.
		if err := c.jc.Build(&pj); err != nil {
			c.log.WithError(err).WithFields(pjutil.ProwJobFields(&pj)).Warn("Cannot start Jenkins build")
			pj.SetComplete()
			pj.Status.State = kube.ErrorState
			pj.Status.URL = testInfra
			pj.Status.Description = "Error starting Jenkins job."
		} else {
			pj.Status.State = kube.PendingState
			pj.Status.Description = "Jenkins job enqueued."
		}
	} else {
		// If a Jenkins build already exists for this job, advance the ProwJob to Pending and
		// it should be handled by syncPendingJob in the next sync.
		pj.Status.State = kube.PendingState
		pj.Status.Description = "Jenkins job enqueued."
	}
	// Report to Github.
	reports <- pj

	if prevState != pj.Status.State {
		c.log.WithFields(pjutil.ProwJobFields(&pj)).
			WithField("from", prevState).
			WithField("to", pj.Status.State).Info("Transitioning states.")
	}
	_, err := c.kc.ReplaceProwJob(pj.ObjectMeta.Name, pj)
	return err
}

// RunAfterSuccessCanRun returns whether a child job (specified as run_after_success in the
// prow config) can run once its parent job succeeds. The only case we will not run a child job
// is when it is a presubmit job and has a run_if_changed regural expression specified which does
// not match the changed filenames in the pull request the job was meant to run for.
// TODO: Collapse with plank, impossible to reuse as is due to the interfaces.
func (c *Controller) RunAfterSuccessCanRun(parent, child *kube.ProwJob, ca configAgent, ghc githubClient) bool {
	if parent.Spec.Type != kube.PresubmitJob {
		return true
	}

	// TODO: Make sure that parent and child have always the same org/repo.
	org := parent.Spec.Refs.Org
	repo := parent.Spec.Refs.Repo
	prNum := parent.Spec.Refs.Pulls[0].Number

	ps := ca.Config().GetPresubmit(org+"/"+repo, child.Spec.Job)
	if ps == nil {
		// The config has changed ever since we started the parent.
		// Not sure what is more correct here. Run the child for now.
		return true
	}
	if ps.RunIfChanged == "" {
		return true
	}
	changesFull, err := ghc.GetPullRequestChanges(org, repo, prNum)
	if err != nil {
		c.log.WithError(err).WithFields(pjutil.ProwJobFields(parent)).Warnf("Cannot get PR changes for #%d", prNum)
		return true
	}
	// We only care about the filenames here
	var changes []string
	for _, change := range changesFull {
		changes = append(changes, change.Filename)
	}
	return ps.RunsAgainstChanges(changes)
}


text:
package org.intellij.lang.xpath.xslt.associations;

import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.SimpleModificationTracker;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiFile;
import com.intellij.util.containers.ContainerUtil;

import java.util.List;
import java.util.Map;

public abstract class FileAssociationsManager extends SimpleModificationTracker {
    public static class Holder {
        public static final FileType[] XML_FILES = {StdFileTypes.XML, StdFileTypes.XHTML};
        public static final List<FileType> XML_FILES_LIST = ContainerUtil.immutableList(XML_FILES);
    }

    public abstract void removeAssociations(PsiFile file);

    public abstract void removeAssociation(PsiFile file, PsiFile assoc);

    public abstract void addAssociation(PsiFile file, PsiFile assoc);

    public abstract void addAssociation(PsiFile file, VirtualFile assoc);

    public abstract Map<VirtualFile, VirtualFile[]> getAssociations();

    public abstract PsiFile[] getAssociationsFor(PsiFile file);

    public abstract PsiFile[] getAssociationsFor(PsiFile file, FileType... fileTypes);

    public static FileAssociationsManager getInstance(Project project) {
        return project.getComponent(FileAssociationsManager.class);
    }
}


text:
namespace Zu.ChromeDevTools.Network
{
    using Newtonsoft.Json;
    using Newtonsoft.Json.Converters;
    using System.Runtime.Serialization;

    /// <summary>
    ///
    /// </summary>
    [JsonConverter(typeof(StringEnumConverter))]
    public enum CrossOriginEmbedderPolicyValue
    {
        [EnumMember(Value = "None")]
        None,
        [EnumMember(Value = "Credentialless")]
        Credentialless,
        [EnumMember(Value = "RequireCorp")]
        RequireCorp,
    }
}


text:
/**
 * @author J. Santos <jamillo@gmail.com>
 * @date August 26, 2016
 */

#include "floodfillstate.h"

mote::data::FloodFillState::FloodFillState()
	: _size(0), _sumX(0), _sumY(0), _bBox(std::numeric_limits<int>::max(), std::numeric_limits<int>::max(), 0, 0),
	  _sumRed(0), _sumGreen(0), _sumBlue(0)
{}

void mote::data::FloodFillState::addPoint(const unsigned int x, const unsigned int y, const mote::data::Pixel &pixel)
{
	if ((signed)x < this->_bBox.x)
	{
		if (this->bBox().x == std::numeric_limits<int>::max())
			this->_bBox.x = x;
		else
			this->_bBox.l(x);
	}

	if ((signed)y < this->_bBox.y)
	{
		if (this->bBox().y == std::numeric_limits<int>::max())
			this->_bBox.y = y;
		else
			this->_bBox.t(y);
	}

	if ((signed)x > this->_bBox.r())
		this->_bBox.r(x);

	if ((signed)y > this->_bBox.b())
		this->_bBox.b(y);

	this->_sumRed = this->_sumRed + pixel.r;
	this->_sumGreen = this->_sumGreen + pixel.g;
	this->_sumBlue = this->_sumBlue + pixel.b;

	++this->_size;
	this->_sumX = this->_sumX + x;
	this->_sumY = this->_sumY + y;
}

void mote::data::FloodFillState::addPoint(const cv::Point2f &p, const mote::data::Pixel &pixel)
{
	this->addPoint(p.x, p.y, pixel);
}

mote::data::Rect<int>& mote::data::FloodFillState::bBox()
{
	return this->_bBox;
}

std::size_t mote::data::FloodFillState::size() const
{
	return this->_size;
}

mote::data::FloodFillState &mote::data::FloodFillState::size(std::size_t size)
{
	this->_size = size;
	return *this;
}

unsigned int mote::data::FloodFillState::sumX() const
{
	return this->_sumX;
}

mote::data::FloodFillState &mote::data::FloodFillState::sumX(unsigned int sumX)
{
	this->_sumX = sumX;
	return *this;
}

unsigned int mote::data::FloodFillState::sumY() const
{
	return this->_sumY;
}

mote::data::FloodFillState &mote::data::FloodFillState::sumY(unsigned int sumY)
{
	this->_sumY = sumY;
	return *this;
}

int mote::data::FloodFillState::x() const
{
	int result = -1;
	if (this->_size > 0)
		result = this->_sumX / this->_size;
	return result;
}

int mote::data::FloodFillState::y() const
{
	int result = -1;
	if (this->_size > 0)
		result = this->_sumY / this->_size;
	return result;
}

mote::data::Pixel mote::data::FloodFillState::averageColour() const
{
	unsigned int red;
	unsigned int green;
	unsigned int blue;

	if (this->_size > 0)
	{
		red = this->_sumRed / this->_size;
		green = this->_sumGreen / this->_size;
		blue = this->_sumBlue / this->_size;
	}
	else
	{
		red = 0;
		green = 0;
		blue = 0;
	}

	return mote::data::Pixel(boost::algorithm::clamp(red, 0, 255), boost::algorithm::clamp(green, 0, 255),
		boost::algorithm::clamp(blue, 0, 255));
}

void mote::data::FloodFillState::clear()
{
	this->_size = this->_sumX = this->_sumY = 0;

	this->_bBox.x = this->_bBox.y = std::numeric_limits<int>::max();
	this->_bBox.width = this->_bBox.height = 0;

	this->_sumRed = this->_sumGreen = this->_sumBlue = 0;
}


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

package org.chromium.base;

import androidx.test.filters.SmallTest;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;

import org.chromium.base.test.BaseRobolectricTestRunner;
import org.chromium.base.test.util.Feature;

/**
 * Tests for {@link TraceEvent}.
 */
@RunWith(BaseRobolectricTestRunner.class)
public class TraceEventTest {
    @Test
    @SmallTest
    @Feature({"Android-AppBase"})
    public void testDisableEventNameFiltering() {
        TraceEvent.setEventNameFilteringEnabled(false);
        Assert.assertFalse(TraceEvent.eventNameFilteringEnabled());
    }

    @Test
    @SmallTest
    @Feature({"Android-AppBase"})
    public void testEnableEventNameFiltering() {
        TraceEvent.setEventNameFilteringEnabled(true);
        Assert.assertTrue(TraceEvent.eventNameFilteringEnabled());
    }

    @Test
    @SmallTest
    @Feature({"Android-AppBase"})
    public void testEventNameUnfiltered() {
        TraceEvent.setEventNameFilteringEnabled(false);
        Assert.assertFalse(TraceEvent.eventNameFilteringEnabled());

        // Input string format:
        // ">>>>> Finished to (TARGET) {HASH_CODE} TARGET_NAME: WHAT"
        String realEventName = ">>>>> Finished to (org.chromium.myClass.myMethod) "
                + "{HASH_CODE} org.chromium.myOtherClass.instance: message";

        // Output string format:
        // "{TraceEvent.BasicLooperMonitor.LOOPER_TASK_PREFIX} TARGET(TARGET_NAME)"
        String realEventNameExpected = TraceEvent.BasicLooperMonitor.LOOPER_TASK_PREFIX
                + "org.chromium.myClass.myMethod(org.chromium.myOtherClass.instance)";
        Assert.assertEquals(TraceEvent.BasicLooperMonitor.getTraceEventName(realEventName),
                realEventNameExpected);
    }

    @Test
    @SmallTest
    @Feature({"Android-AppBase"})
    public void testEventNameFiltered() {
        TraceEvent.setEventNameFilteringEnabled(true);
        Assert.assertTrue(TraceEvent.eventNameFilteringEnabled());

        String realEventName = TraceEvent.BasicLooperMonitor.LOOPER_TASK_PREFIX
                + "org.chromium.myClass.myMethod(org.chromium.myOtherClass.instance)";
        Assert.assertEquals(TraceEvent.BasicLooperMonitor.getTraceEventName(realEventName),
                TraceEvent.BasicLooperMonitor.FILTERED_EVENT_NAME);
    }
}


text:
<?php

class Application_Model_DbTable_Foo extends Zend_Db_Table_Abstract
{

    protected $_name = 'user';
    protected $_primary = 'id';

    public function getListOfUser()
    {
         $db = Zend_Db_Table_Abstract::getDefaultAdapter();
        $select  = $db->select()
                      ->from($_name,array('*'))
                      ->where(1);
        $data = $db->query($select)->fetchAll();
        return $data;
    }
}


text:
/**
 * @author Phuluong
 * December 27, 2015
 */
/** Exports **/
module.exports = IO;
/** Imports **/
var fs = require("fs");
var Cookie = require(__dir + "/core/io/cookie/cookie");
/** Modules **/
var IOBuilder = require('./io-builder');
function IO(constructorProperties) {
    this.cookie = new Cookie();
    this.p = {
        type: "http",
        status: 200,
        headers: {},
        isToAll: false,
        toEvent: null,
        tos: [],
        toExpections: [],
        toCriterias: [],
        toExpectionCriterias: []
    };
    this.init = function() {
        for (var property in constructorProperties) {
            this[property] = constructorProperties[property];
        }
    }
    this.bindHttp = function (req, res) {
        this.type = "http";
        this.request = req;
        this.response = res;
        this.inputs = req.inputs;
        this.session = req.session;
        this.cookie.load({
            request: req,
            response: res
        });
    };
    this.bindSocketIO = function (data, session) {
        this.type = "socket.io";
        this.session = session;
        this.inputs = data;
    };
    /**
     * Return a JSON response
     * @param {jsonString | object} data
     */
    this.json = function (data) {
        var self = this;
        this.header("Content-Type", "application/json");
        this.header("Connection", "close");
        this.build();
        this.p.tos.forEach(function (session) {
            if (session.socket != null) {
                session.socket.emit(self.p.toEvent, data);
            }
        });
        if (this.type === "http") {
            this.response.end((!(typeof data === "string")) ? JSON.stringify(data) : data);
        }
    };
    /**
     * Return a custom response
     * @param {string} content
     */
    this.echo = function (content) {
        var self = this;
        this.header("Content-Type", "text/html; charset=UTF-8");
        this.header("Connection", "close");
        this.build();
        this.p.tos.forEach(function (session) {
            session.socket.emit(self.p.toEvent, content);
        });
        if (this.type === "http") {
            this.response.end(content);
        }
    };
    /**
     * Return a file response
     * @param {string} filePath
     * @param {array} headers
     */
    this.download = function (filePath) {
        this.header("Connection", "close");
        this.build();
        var file = fs.readFileSync(filePath);
        this.response.end(file, 'binary');
    };
    /**
     * Render a view response
     * @param {View} view
     * @param {object} data
     */
    this.render = function (view, data) {
        var self = this;
        this.header("Content-Type", "text/html; charset=UTF-8");
        this.header("Connection", "close");
        this.build();
        var content = this.viewEngine.render(view, data, {});
        this.p.tos.forEach(function (session) {
            session.socket.emit(self.p.toEvent, content);
        });
        if (this.type === "http") {
            this.response.end(content);
        }
    };
    /**
     * Create a new redirect response to a action
     * @param {String|Function} action
     */
    this.delegate = function (action) {
        if (typeof action === "function") {
            action(this);
        } else if (typeof action === "string") {
            this.autoLoader.getAction(action)(this);
        }
    };
    /**
     * Create a new redirect response to a url
     * @param {String|Function} url
     */
    this.redirect = function (url) {
        this.status(302).header("Location", url).echo("");

    };
    this.init();
}
IO.prototype = new IOBuilder();


text:
<!DOCTYPE html>

	<meta charset="utf-8" />
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
	<title>Command-Fu: The Linux Command Line > Permissions</title>
	<link href="slideshow.css" rel="stylesheet" />
	<link href="theme.css" rel="stylesheet" />
	<link href="talk.css" rel="stylesheet" />

		Command-Fu : The Linux Command Line

		Chapter 9 × Permissions

Chris Roche

History

Users & permissions are not a "recent innovation" of the *nix system

Pre-"personal" computers were monolithic with many terminals

Many users connected and using the system simultaneously (ex: ssh)

Needed a way to protect users and files from each other

Commands

id Display user identity

chmod Change file permissions

umask Set default permissions

su Run a shell as another user

sudo Execute a command as another user

chown Change file ownership

chgrp Change group ownership

passwd Change a user's password

id

$ id
uid=500(me) gid=500(me) groups=500(me)

uid - user id number (mapped to username in /etc/passwd)

/etc/passwd also contains "real" account name and home directory

/etc/passwd includes other "users" as well (like the superuser 0)

gid - primary group id of user (also in /etc/passwd)

groups - groups that the user belongs (in /etc/group)

On Mac: ~10 groups from the system

File Attributes

$ > foo.txt
$ ls -l foo.txt
-rw-rw-r-- 1 chris staff 0 2014-03-14 13:59 foo.txt

First character is the file type:

- : A regular file

d : A directory

l : A symbolic link (in which case the other 9 characters are erroneous)

c : Character Special File (Device that handles a data stream, ex: terminal or modem)

b : Block Special File (Device that handles block data, ex: hard or disc drive)

File Attributes

$ > foo.txt
$ ls -l foo.txt
-rw-rw-r-- 1 chris staff 0 2014-03-14 13:59 foo.txt

Next 9 characters are the permissions for user, group, and the world in blocks of 3 characters:

r : read access to the file (ex: $ cat foo.txt)

w : write access to the file (ex: $ echo "bar" > foo.txt)

x : execution access to the file (ex: $ ./foo.txt)

- : doesn't have that particular permission

Each block can be represented as:

3-digit binary # (- - - = 000 to rwx = 111)

1-digit octal # (- - - = 0 to rwx = 7)

chmod

Change the permissions on a file (owner or superuser only):

$ chmod 600 foo.txt
$ ls -l foo.txt
-rw------- 1 chris staff 0 2014-03-14 13:59 foo.txt

Can also set via the GUI if desired (on Mac: right+click/option+click > Get Info)

chmod

Can also use a symbolic notation:

$ chmod u+x,go=rx foo.txt
$ ls -l foo.txt
-rwxr-xr-x 1 chris staff 0 2014-03-14 13:59 foo.txt

Blocks: u = user, g = group, o = others (world), a = all (u + g + o)

+ : Add permission to the block

- : Remove permission from the block

= : Set the permissions on the block

comma delimited

umask

Change default permissions via bit mask:

$ umask
0002
$ > bar.txt
$ ls -l bar.txt
-rw-rw-r-- 1 chris staff 0 2014-03-14 13:59 bar.txt
$ rm -f bar.txt
$ umask 0000
$ > bar.txt
$ ls -l bar.txt
-rw-rw-rw- 1 chris staff 0 2014-03-14 13:59 bar.txt

umask

Turn off permissions at the specified positions:

original:   --- rw- rw- rw-
mask(0022): 000 000 010 010
result:     --- rw- r-- r--

The leading block? Special permissions:

setuid bit (u+s) - execute the file as the file owner. Many superuser files have this flag

setgid bit (g+s) - same but for group. If on dir, sets all new files inside to the dir's group(s)

sticky bit (+t)  - on directory, files can be modified by owner, superuser, or directory owner (such as /tmp)

su

Run a shell as a different user:

$ su -l zo
$ whoami
zo
$ su -
Password: #######
$ whoami
root
$ exit
$ whoami
zo

su

Can also run a command as another user:

$ whoami
chris
$ su -c "> bar.txt"
$ ls -l bar.txt
-rw-rw-r-- 1 root staff 0 2014-03-14 13:59 bar.txt

sudo

Execute a command as the superuser (or another user chosen by the admin)

$ whoami
chris
$ rm -rf /
Permission Denied
$ sudo rm -rf /
Password: ######
Game Over, Son!

Quickly sudo the previous command: sudo !!

chown

Change the ownership of a file:

$ sudo touch ~zo/foo.txt
$ sudo ls -l ~zo/foo.txt
-rw-rw-r-- 1 root root 0 2014-03-14 13:59 foo.txt
$ sudo chown zo: ~zo/foo.txt
$ sudo ls -l ~zo/foo.txt
-rw-rw-r-- 1 zo zo 0 2014-03-14 13:59 foo.txt

 zo - Only changes the file owner (zo root)

 zo:chris - Changes owner and group (zo chris)

 :zo - Only changes the file group (root zo)

 zo: - Changes both to the same thing (zo zo)

chgrp

Same as chown but can only change the group (kinda old Unix command)

passwd

Change a user's password:

$ passwd
(current) UNIX password: ######
New UNIX password: #######
BAD PASSWORD: is too similar to the old one
New UNIX password: ##
BAD PASSWORD: it is WAY too short
New UNIX password: $$$$$$$

sudo passwd zo
New UNIX password: ######

Example: Shared Music Library

### logged in as chris ###
#----- create music group and add users -----#
$ groupadd music
$ usermod -a -G music chris
$ usermod -a -G music zo

#----- create shared folder -----#
$ sudo mkdir /usr/local/share/Music
$ sudo ls -ld /usr/local/share/Music
drwxr-xr-x 2 root root 4096 2014-03-14 18:05 /usr/local/share/Music
$ sudo chown :music /usr/local/share/Music
$ sudo chmod 775 /usr/local/share/Music
drwxrwxr-x 2 root music 4096 2014-03-14 18:05 /usr/local/share/Music

Example: Shared Music Library, Cont.

#----- make all files added to folder accessible by music group -----#
$ sudo chmod g+s /usr/local/share/Music
$ ls -ld /usr/local/share/Music
drwxrwsr-x root music 4096 2014-03-14 18:05 /usr/local/share/Music

#----- test adding files/directories -----#
$ mkdir /usr/local/share/Music/One_Direction
$ > /usr/local/share/Music/Friday_Rebecca_Black.mp3
$ ls -l /usr/local/share/Music
drwxrwsr-x 2 chris music 4096 2014-03-14 20:24 One_Direction
-rw-rw-r-- 1 chris music 0 2014-03-14 20:22 Friday_Rebecca_Black.mp3

Thank you!

Get it at rodaine.com/the-linux-command-line-permissions-presentation


text:
package pr03.food;

public class Meat extends Food {

    public Meat(int quantity) {
        super(quantity);
    }
}


text:
steal(function(){
	console.log("loaded")
})


text:
var gulp         = require('gulp');
var browserSync  = require('browser-sync').create();
var sass         = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');
var sourcemaps   = require('gulp-sourcemaps');
var del          = require('del');
var runSequence  = require('run-sequence');
var minifyCss    = require('gulp-minify-css');
var imagemin     = require('gulp-imagemin');
var uglify       = require('gulp-uglify');
var jscs         = require('gulp-jscs');
var notify       = require('gulp-notify');
var plumber      = require('gulp-plumber');
var browserify   = require('browserify');
var source       = require('vinyl-source-stream');

var notifyError = function(err, lang) {
  console.log('------------------ error ------------------');
  console.log(err.toString());
  console.log('-------------------------------------------');
  notify.onError({
    title: lang + ' error',
    message: 'Check console',
    sound: 'Basso'
  })(err);
};

var AUTOPREFIXER_BROWSERS = [
  'ie >= 9',
  'ie_mob >= 10',
  'ff >= 30',
  'chrome >= 34',
  'safari >= 7',
  'opera >= 23',
  'ios >= 7',
  'android >= 4.4',
  'bb >= 10'
];

// Compile sass into CSS & auto-inject into browsers
gulp.task('sass', function() {
  return gulp.src('app/sass/*.scss')
    .pipe(plumber(function() {
      this.emit('end');
    }))
    .pipe(sass({
      errLogToConsole: true
    }))
    .on('error', function(err) {
      notifyError(err, 'SASS')
    })
    .pipe(sourcemaps.init())
    .pipe(autoprefixer({
      browsers: AUTOPREFIXER_BROWSERS
    }))
    .pipe(sourcemaps.write())
    .pipe(gulp.dest('app/'))
    .pipe(browserSync.stream())
    .pipe(plumber.stop());
});
gulp.task('sass-dist', function() {
  return gulp.src('app/sass/*.scss')
    .pipe(sass({
      errLogToConsole: false
    }))
    .on('error', function(err) {
      notifyError(err, 'SASS')
    })
    .pipe(autoprefixer({
      browsers: AUTOPREFIXER_BROWSERS
    }))
    .pipe(minifyCss())
    .pipe(gulp.dest('app/'))
    .pipe(browserSync.stream());
});

// Static Server + watching scss/html files
gulp.task('serve', ['sass', 'lint', 'scripts'], function() {
  browserSync.init({
    server: './app',
    open: false,
    ghostMode: false
  });
  gulp.watch('app/sass{,/**}', ['sass']);
  gulp.watch('app/*.html').on('change', browserSync.reload);
  gulp.watch(['app/js{,/**}', './gulpfile.js'], ['lint', 'scripts']);
  gulp.watch(['app/js/main.min.js'])
    .on('change', browserSync.reload);
});

gulp.task('lint', function() {
  return gulp.src(['app/js/*.js', '!app/js/main.min.js', './gulpfile.js'])
    .pipe(plumber())
    .pipe(jscs())
    .on('error', function(err) {
      notifyError(err, 'JS Style')
    })
    .pipe(plumber.stop());
});

gulp.task('scripts', function() {
  return browserify('./app/js/main.js', {debug: true})
    .bundle()
    .on('error', function(err) {
      notifyError(err, 'JS')
    })
    .pipe(source('main.min.js'))
    .pipe(gulp.dest('app/js'));
});

gulp.task('clean-dist', function(cb) {
  del('dist', cb);
});
gulp.task('copy-to-dist', function() {
  return gulp.src([
      'app/**/*', '!app/sass{,/**}', '!app/img{,/**}', '!app/js{,/**}'
    ],
    {base: './app'})
    .pipe(gulp.dest('dist'));
});
gulp.task('copy-images', function() {
  return gulp.src(['app/img/**/*'], {base: './app'})
    .pipe(imagemin())
    .pipe(gulp.dest('dist/'));
});
gulp.task('copy-js', function() {
  return gulp.src(['app/js/main.min.js'], {base: './app'})
    .pipe(uglify())
    .pipe(gulp.dest('dist/'));
});

gulp.task('default', ['serve']);
gulp.task('dist', function(callback) {
  runSequence(
    'lint', 'scripts', 'clean-dist', 'sass-dist',
    'copy-to-dist', 'copy-images', 'copy-js'
  );
});


text:
// Karma configuration
// Generated on Thu Feb 20 2014 16:57:54 GMT+0100 (CET)

module.exports = function(config) {
  config.set({

    // base path, that will be used to resolve files and exclude
    basePath: '',

    // frameworks to use
    frameworks: ['mocha', 'chai', 'effroi'],

    // list of files / patterns to load in the browser
    files: [
        'node_modules/bosonic/dist/*.js',
        'node_modules/bosonic-test-tools/src/*.js',
        'dist/*.js',
        'test/**/*.js'
    ],

    // list of files to exclude
    exclude: [

    ],

    // test results reporter to use
    // possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
    reporters: ['progress'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera (has to be installed with `npm install karma-opera-launcher`)
    // - Safari (only Mac; has to be installed with `npm install karma-safari-launcher`)
    // - PhantomJS
    // - IE (only Windows; has to be installed with `npm install karma-ie-launcher`)
    browsers: ['Chrome', 'Firefox'],

    // If browser does not capture in given timeout [ms], kill it
    captureTimeout: 60000,

    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: false
  });
};


text:
@interface GrowlControlDisableInNetworkScriptCommand : NSScriptCommand

@end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Hosagoudar, Abraham & Goos, Mycotaxon 66: 112 (1998)

#### Original name
Meliola dorsteniae Hosag. & T.K. Abraham

### Remarks
null


text:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using Xunit;
using Xunit.Extensions;

namespace NuGet.Test.Integration.NuGetCommandLine
{
    public class NuGetInstallCommandTest
    {
        [Fact]
        public void InstallCommand_PackageSaveModeNuspec()
        {
            var tempPath = Path.GetTempPath();
            var source = Path.Combine(tempPath, Guid.NewGuid().ToString());
            var outputDirectory = Path.Combine(tempPath, Guid.NewGuid().ToString());

            try
            {
                // Arrange
                Util.CreateDirectory(source);
                Util.CreateDirectory(outputDirectory);

                var packageFileName = PackageCreater.CreatePackage(
                    "testPackage1", "1.1.0", source);

                // Act
                string[] args = new string[] {
                    "install", "testPackage1",
                    "-OutputDirectory", outputDirectory,
                    "-Source", source,
                    "-PackageSaveMode", "nuspec" };
                int r = Program.Main(args);

                // Assert
                Assert.Equal(0, r);

                var nuspecFile = Path.Combine(
                    outputDirectory,
                    @"testPackage1.1.1.0\testPackage1.1.1.0.nuspec");

                Assert.True(File.Exists(nuspecFile));
                var nupkgFiles = Directory.GetFiles(outputDirectory, "*.nupkg", SearchOption.AllDirectories);
                Assert.Equal(0, nupkgFiles.Length);
            }
            finally
            {
                // Cleanup
                Util.DeleteDirectory(outputDirectory);
                Util.DeleteDirectory(source);
            }
        }

        [Fact]
        public void InstallCommand_PackageSaveModeNupkg()
        {
            var tempPath = Path.GetTempPath();
            var source = Path.Combine(tempPath, Guid.NewGuid().ToString());
            var outputDirectory = Path.Combine(tempPath, Guid.NewGuid().ToString());

            try
            {
                // Arrange
                Util.CreateDirectory(source);
                Util.CreateDirectory(outputDirectory);

                var packageFileName = PackageCreater.CreatePackage(
                    "testPackage1", "1.1.0", source);

                // Act
                string[] args = new string[] {
                    "install", "testPackage1",
                    "-OutputDirectory", outputDirectory,
                    "-Source", source,
                    "-PackageSaveMode", "nupkg" };
                int r = Program.Main(args);

                // Assert
                Assert.Equal(0, r);

                var nupkgFile = Path.Combine(
                    outputDirectory,
                    @"testPackage1.1.1.0\testPackage1.1.1.0.nupkg");

                Assert.True(File.Exists(nupkgFile));
                var nuspecFiles = Directory.GetFiles(outputDirectory, "*.nuspec", SearchOption.AllDirectories);
                Assert.Equal(0, nuspecFiles.Length);
            }
            finally
            {
                // Cleanup
                Util.DeleteDirectory(outputDirectory);
                Util.DeleteDirectory(source);
            }
        }

        [Fact]
        public void InstallCommand_PackageSaveModeNuspecNupkg()
        {
            var tempPath = Path.GetTempPath();
            var source = Path.Combine(tempPath, Guid.NewGuid().ToString());
            var outputDirectory = Path.Combine(tempPath, Guid.NewGuid().ToString());

            try
            {
                // Arrange
                Util.CreateDirectory(source);
                Util.CreateDirectory(outputDirectory);

                var packageFileName = PackageCreater.CreatePackage(
                    "testPackage1", "1.1.0", source);

                // Act
                string[] args = new string[] {
                    "install", "testPackage1",
                    "-OutputDirectory", outputDirectory,
                    "-Source", source,
                    "-PackageSaveMode", "nupkg;nuspec" };
                int r = Program.Main(args);

                // Assert
                Assert.Equal(0, r);

                var nupkgFile = Path.Combine(
                    outputDirectory,
                    @"testPackage1.1.1.0\testPackage1.1.1.0.nupkg");
                var nuspecFile = Path.ChangeExtension(nupkgFile, "nuspec");

                Assert.True(File.Exists(nupkgFile));
                Assert.True(File.Exists(nuspecFile));
            }
            finally
            {
                // Cleanup
                Util.DeleteDirectory(outputDirectory);
                Util.DeleteDirectory(source);
            }
        }

        // Test that after a package is installed with -PackageSaveMode nuspec, nuget.exe
        // can detect that the package is already installed when trying to install the same
        // package.
        [Fact]
        public void InstallCommand_PackageSaveModeNuspecReinstall()
        {
            var tempPath = Path.GetTempPath();
            var source = Path.Combine(tempPath, Guid.NewGuid().ToString());
            var outputDirectory = Path.Combine(tempPath, Guid.NewGuid().ToString());

            try
            {
                // Arrange
                Util.CreateDirectory(source);
                Util.CreateDirectory(outputDirectory);

                var packageFileName = PackageCreater.CreatePackage(
                    "testPackage1", "1.1.0", source);

                string[] args = new string[] {
                    "install", "testPackage1",
                    "-OutputDirectory", outputDirectory,
                    "-Source", source,
                    "-PackageSaveMode", "nuspec" };
                int r = Program.Main(args);
                Assert.Equal(0, r);

                // Act
                MemoryStream memoryStream = new MemoryStream();
                TextWriter writer = new StreamWriter(memoryStream);
                Console.SetOut(writer);
                r = Program.Main(args);
                writer.Close();
                var output = Encoding.Default.GetString(memoryStream.ToArray());

                // Assert
                var expectedOutput = "'testPackage1 1.1.0' already installed." +
                    Environment.NewLine;
                Assert.Equal(expectedOutput, output);
            }
            finally
            {
                // Cleanup
                Util.DeleteDirectory(outputDirectory);
                Util.DeleteDirectory(source);
            }
        }

        // Test that PackageSaveMode specified in nuget.config file is used.
        [Fact]
        public void InstallCommand_PackageSaveModeInConfigFile()
        {
            var tempPath = Path.GetTempPath();
            var source = Path.Combine(tempPath, Guid.NewGuid().ToString());
            var outputDirectory = Path.Combine(tempPath, Guid.NewGuid().ToString());

            try
            {
                // Arrange
                Util.CreateDirectory(source);
                Util.CreateDirectory(outputDirectory);

                var packageFileName = Util.CreateTestPackage(
                    "testPackage1", "1.1.0", source);

                var configFile = Path.Combine(source, "nuget.config");
                Util.CreateFile(Path.GetDirectoryName(configFile), Path.GetFileName(configFile), "<configuration/>");
                string[] args = new string[] {
                    "config", "-Set", "PackageSaveMode=nuspec",
                    "-ConfigFile", configFile };
                int r = Program.Main(args);
                Assert.Equal(0, r);

                // Act
                args = new string[] {
                    "install", "testPackage1",
                    "-OutputDirectory", outputDirectory,
                    "-Source", source,
                    "-ConfigFile", configFile };
                r = Program.Main(args);

                // Assert
                Assert.Equal(0, r);

                var nuspecFile = Path.Combine(
                    outputDirectory,
                    @"testPackage1.1.1.0\testPackage1.1.1.0.nuspec");

                Assert.True(File.Exists(nuspecFile));
                var nupkgFiles = Directory.GetFiles(outputDirectory, "*.nupkg", SearchOption.AllDirectories);
                Assert.Equal(0, nupkgFiles.Length);
            }
            finally
            {
                // Cleanup
                Util.DeleteDirectory(outputDirectory);
                Util.DeleteDirectory(source);
			}
		}

        // Tests that when package restore is enabled and -RequireConsent is specified,
        // the opt out message is displayed.
        [Theory]
        [InlineData("packages.config")]
        [InlineData("packages.proj1.config")]
        public void InstallCommand_OptOutMessage(string configFileName)
        {
            // Arrange
            var tempPath = Path.GetTempPath();
            var workingPath = Path.Combine(tempPath, Guid.NewGuid().ToString());
            var repositoryPath = Path.Combine(workingPath, Guid.NewGuid().ToString());
            var proj1Directory = Path.Combine(workingPath, "proj1");
            var currentDirectory = Directory.GetCurrentDirectory();
            var targetDir = ConfigurationManager.AppSettings["TargetDir"];
            var nugetexe = Path.Combine(targetDir, "nuget.exe");

            try
            {
                Util.CreateDirectory(workingPath);
                Util.CreateDirectory(repositoryPath);
                Util.CreateDirectory(proj1Directory);

                Util.CreateTestPackage("packageA", "1.1.0", repositoryPath);
                Util.CreateTestPackage("packageB", "2.2.0", repositoryPath);

                Util.CreateFile(workingPath, "my.config",
                    @"
<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
  <packageRestore>
    <add key=""enabled"" value=""True"" />
  </packageRestore>
</configuration>");

                Util.CreateFile(proj1Directory, "proj1.csproj",
                    @"<Project ToolsVersion='4.0' DefaultTargets='Build'
    xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
  <PropertyGroup>
    <OutputType>Library</OutputType>
    <OutputPath>out</OutputPath>
    <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
  </PropertyGroup>
  <ItemGroup>
    <None Include='packages.config' />
  </ItemGroup>
</Project>");
                Util.CreateFile(proj1Directory, configFileName,
@"<packages>
  <package id=""packageA"" version=""1.1.0"" targetFramework=""net45"" />
</packages>");
                // Act
                var r = CommandRunner.Run(
                    nugetexe,
                    proj1Directory,
                    "install " + configFileName + " -Source " + repositoryPath + @" -ConfigFile ..\my.config -RequireConsent -Verbosity detailed",
                    waitForExit: true);

                // Assert
                Assert.Equal(0, r.Item1);
                string optOutMessage = String.Format(
                    CultureInfo.CurrentCulture,
                    NuGetResources.RestoreCommandPackageRestoreOptOutMessage,
                    NuGet.Resources.NuGetResources.PackageRestoreConsentCheckBoxText.Replace("&", ""));
                Assert.Contains(optOutMessage, r.Item2);
            }
            finally
            {
                Directory.SetCurrentDirectory(currentDirectory);
                Util.DeleteDirectory(workingPath);
            }
        }

        // Tests that when package restore is enabled, but -RequireConsent is not specified,
        // the opt out message is not displayed.
        [Theory]
        [InlineData("packages.config")]
        [InlineData("packages.proj1.config")]
        public void InstallCommand_NoOptOutMessage(string configFileName)
        {
            // Arrange
            var tempPath = Path.GetTempPath();
            var workingPath = Path.Combine(tempPath, Guid.NewGuid().ToString());
            var repositoryPath = Path.Combine(workingPath, Guid.NewGuid().ToString());
            var proj1Directory = Path.Combine(workingPath, "proj1");
            var currentDirectory = Directory.GetCurrentDirectory();
            var targetDir = ConfigurationManager.AppSettings["TargetDir"];
            var nugetexe = Path.Combine(targetDir, "nuget.exe");

            try
            {
                Util.CreateDirectory(workingPath);
                Util.CreateDirectory(repositoryPath);
                Util.CreateDirectory(proj1Directory);

                Util.CreateTestPackage("packageA", "1.1.0", repositoryPath);
                Util.CreateTestPackage("packageB", "2.2.0", repositoryPath);

                Util.CreateFile(workingPath, "my.config",
                    @"
<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
  <packageRestore>
    <add key=""enabled"" value=""True"" />
  </packageRestore>
</configuration>");

                Util.CreateFile(proj1Directory, "proj1.csproj",
                    @"<Project ToolsVersion='4.0' DefaultTargets='Build'
    xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
  <PropertyGroup>
    <OutputType>Library</OutputType>
    <OutputPath>out</OutputPath>
    <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
  </PropertyGroup>
  <ItemGroup>
    <None Include='packages.config' />
  </ItemGroup>
</Project>");
                Util.CreateFile(proj1Directory, configFileName,
@"<packages>
  <package id=""packageA"" version=""1.1.0"" targetFramework=""net45"" />
</packages>");
                // Act
                var r = CommandRunner.Run(
                    nugetexe,
                    proj1Directory,
                    "install " + configFileName + " -Source " + repositoryPath + @" -ConfigFile ..\my.config",
                    waitForExit: true);

                // Assert
                Assert.Equal(0, r.Item1);
                string optOutMessage = String.Format(
                    CultureInfo.CurrentCulture,
                    NuGetResources.RestoreCommandPackageRestoreOptOutMessage,
                    NuGet.Resources.NuGetResources.PackageRestoreConsentCheckBoxText.Replace("&", ""));
                Assert.DoesNotContain(optOutMessage, r.Item2);
            }
            finally
            {
                Directory.SetCurrentDirectory(currentDirectory);
                Util.DeleteDirectory(workingPath);
            }
        }

        // Tests that when no version is specified, nuget will query the server to get
        // the latest version number first.
        [Fact]
        public void InstallCommand_GetLastestReleaseVersion()
        {
            var targetDir = ConfigurationManager.AppSettings["TargetDir"];
            var nugetexe = Path.Combine(targetDir, "nuget.exe");
            var tempPath = Path.GetTempPath();
            var packageDirectory = Path.Combine(tempPath, Guid.NewGuid().ToString());
            var workingDirectory = Path.Combine(tempPath, Guid.NewGuid().ToString());
            var mockServerEndPoint = "http://localhost:1234/";

            try
            {
                // Arrange
                Util.CreateDirectory(packageDirectory);
                Util.CreateDirectory(workingDirectory);
                var packageFileName = Util.CreateTestPackage("testPackage1", "1.1.0", packageDirectory);
                var package = new ZipPackage(packageFileName);
                MachineCache.Default.RemovePackage(package);

                var server = new MockServer(mockServerEndPoint);
                string findPackagesByIdRequest = string.Empty;
                bool packageDownloadIsCalled = false;

                server.Get.Add("/nuget/FindPackagesById()", r =>
                    new Action<HttpListenerResponse>(response =>
                    {
                        findPackagesByIdRequest = r.Url.ToString();
                        response.ContentType = "application/atom+xml;type=feed;charset=utf-8";
                        string feed = server.ToODataFeed(new[] { package }, "FindPackagesById");
                        MockServer.SetResponseContent(response,  feed);
                    }));

                server.Get.Add("/nuget/Packages(Id='testPackage1',Version='1.1.0')", r =>
                    new Action<HttpListenerResponse>(response =>
                    {
                        response.ContentType = "application/atom+xml;type=entry;charset=utf-8";
                        var p1 = server.ToOData(package);
                        MockServer.SetResponseContent(response, p1);
                    }));

                server.Get.Add("/package/testPackage1", r =>
                    new Action<HttpListenerResponse>(response =>
                    {
                        packageDownloadIsCalled = true;
                        response.ContentType = "application/zip";
                        using (var stream = package.GetStream())
                        {
                            var content = stream.ReadAllBytes();
                            MockServer.SetResponseContent(response, content);
                        }
                    }));

                server.Get.Add("/nuget", r => "OK");

                server.Start();

                // Act
                var args = "install testPackage1 -Source " + mockServerEndPoint + "nuget";
                var r1 = CommandRunner.Run(
                    nugetexe,
                    workingDirectory,
                    args,
                    waitForExit: true);
                server.Stop();

                // Assert
                Assert.Equal(0, r1.Item1);
                Assert.Contains("$filter=IsLatestVersion", findPackagesByIdRequest);
                Assert.True(packageDownloadIsCalled);
            }
            finally
            {
                // Cleanup
                Util.DeleteDirectory(packageDirectory);
                Util.DeleteDirectory(workingDirectory);
            }
        }

        // Tests that when no version is specified, and -Prerelease is specified,
        // nuget will query the server to get the latest prerelease version number first.
        [Fact]
        public void InstallCommand_GetLastestPrereleaseVersion()
        {
            var targetDir = ConfigurationManager.AppSettings["TargetDir"];
            var nugetexe = Path.Combine(targetDir, "nuget.exe");
            var tempPath = Path.GetTempPath();
            var packageDirectory = Path.Combine(tempPath, Guid.NewGuid().ToString());
            var workingDirectory = Path.Combine(tempPath, Guid.NewGuid().ToString());
            var mockServerEndPoint = "http://localhost:1234/";

            try
            {
                // Arrange
                Util.CreateDirectory(packageDirectory);
                Util.CreateDirectory(workingDirectory);
                var packageFileName = Util.CreateTestPackage("testPackage1", "1.1.0", packageDirectory);
                var package = new ZipPackage(packageFileName);
                MachineCache.Default.RemovePackage(package);

                var server = new MockServer(mockServerEndPoint);
                string findPackagesByIdRequest = string.Empty;
                bool packageDownloadIsCalled = false;

                server.Get.Add("/nuget/FindPackagesById()", r =>
                    new Action<HttpListenerResponse>(response =>
                    {
                        findPackagesByIdRequest = r.Url.ToString();
                        response.ContentType = "application/atom+xml;type=feed;charset=utf-8";
                        string feed = server.ToODataFeed(new[] { package }, "FindPackagesById");
                        MockServer.SetResponseContent(response, feed);
                    }));

                server.Get.Add("/nuget/Packages(Id='testPackage1',Version='1.1.0')", r =>
                    new Action<HttpListenerResponse>(response =>
                    {
                        response.ContentType = "application/atom+xml;type=entry;charset=utf-8";
                        var p1 = server.ToOData(package);
                        MockServer.SetResponseContent(response, p1);
                    }));

                server.Get.Add("/package/testPackage1", r =>
                    new Action<HttpListenerResponse>(response =>
                    {
                        packageDownloadIsCalled = true;
                        response.ContentType = "application/zip";
                        using (var stream = package.GetStream())
                        {
                            var content = stream.ReadAllBytes();
                            MockServer.SetResponseContent(response, content);
                        }
                    }));

                server.Get.Add("/nuget", r => "OK");

                server.Start();

                // Act
                var args = "install testPackage1 -Prerelease -Source " + mockServerEndPoint + "nuget";
                var r1 = CommandRunner.Run(
                    nugetexe,
                    workingDirectory,
                    args,
                    waitForExit: true);
                server.Stop();

                // Assert
                Assert.Equal(0, r1.Item1);
                Assert.Contains("$filter=IsAbsoluteLatestVersion", findPackagesByIdRequest);
                Assert.True(packageDownloadIsCalled);
            }
            finally
            {
                // Cleanup
                Util.DeleteDirectory(packageDirectory);
                Util.DeleteDirectory(workingDirectory);
            }
        }

        // Tests that when -Version is specified, nuget will use request
        // Packages(Id='id',Version='version') to get the specified version
        [Fact]
        public void InstallCommand_WithVersionSpecified()
        {
            var targetDir = ConfigurationManager.AppSettings["TargetDir"];
            var nugetexe = Path.Combine(targetDir, "nuget.exe");
            var tempPath = Path.GetTempPath();
            var workingDirectory = Path.Combine(tempPath, Guid.NewGuid().ToString());
            var packageDirectory = Path.Combine(tempPath, Guid.NewGuid().ToString());
            var mockServerEndPoint = "http://localhost:1234/";

            try
            {
                // Arrange
                Util.CreateDirectory(packageDirectory);
                Util.CreateDirectory(workingDirectory);
                var packageFileName = Util.CreateTestPackage("testPackage1", "1.1.0", packageDirectory);
                var package = new ZipPackage(packageFileName);
                MachineCache.Default.RemovePackage(package);

                var server = new MockServer(mockServerEndPoint);
                bool getPackageByVersionIsCalled = false;
                bool packageDownloadIsCalled = false;

                server.Get.Add("/nuget/Packages(Id='testPackage1',Version='1.1.0')", r =>
                    new Action<HttpListenerResponse>(response =>
                    {
                        getPackageByVersionIsCalled = true;
                        response.ContentType = "application/atom+xml;type=entry;charset=utf-8";
                        var p1 = server.ToOData(package);
                        MockServer.SetResponseContent(response, p1);
                    }));

                server.Get.Add("/package/testPackage1", r =>
                    new Action<HttpListenerResponse>(response =>
                    {
                        packageDownloadIsCalled = true;
                        response.ContentType = "application/zip";
                        using (var stream = package.GetStream())
                        {
                            var content = stream.ReadAllBytes();
                            MockServer.SetResponseContent(response, content);
                        }
                    }));

                server.Get.Add("/nuget", r => "OK");

                server.Start();

                // Act
                var args = "install testPackage1 -Version 1.1.0 -Source " + mockServerEndPoint + "nuget";
                var r1 = CommandRunner.Run(
                    nugetexe,
                    workingDirectory,
                    args,
                    waitForExit: true);
                server.Stop();

                // Assert
                Assert.Equal(0, r1.Item1);
                Assert.True(getPackageByVersionIsCalled);
                Assert.True(packageDownloadIsCalled);
            }
            finally
            {
                // Cleanup
                Util.DeleteDirectory(packageDirectory);
                Util.DeleteDirectory(workingDirectory);
            }
        }

        // Tests that when -Version is specified, if the specified version cannot be found,
        // nuget will retry with new version numbers by appending 0's to the specified version.
        [Fact]
        public void InstallCommand_WillTryNewVersionsByAppendingZeros()
        {
            var targetDir = ConfigurationManager.AppSettings["TargetDir"];
            var nugetexe = Path.Combine(targetDir, "nuget.exe");
            var tempPath = Path.GetTempPath();
            var workingDirectory = Path.Combine(tempPath, Guid.NewGuid().ToString());
            var mockServerEndPoint = "http://localhost:1234/";

            try
            {
                // Arrange
                Util.CreateDirectory(workingDirectory);

                // deleting testPackage1 from machine cache
                var packages = MachineCache.Default.FindPackagesById("testPackage1");
                foreach (var p in packages)
                {
                    MachineCache.Default.RemovePackage(p);
                }

                var server = new MockServer(mockServerEndPoint);
                List<string> requests = new List<string>();
                server.Get.Add("/nuget/Packages", r =>
                    {
                        requests.Add(r.Url.ToString());
                        return HttpStatusCode.NotFound;
                    });
                server.Get.Add("/nuget", r => "OK");

                server.Start();

                // Act
                var args = "install testPackage1 -Version 1.1 -Source " + mockServerEndPoint + "nuget";
                var r1 = CommandRunner.Run(
                    nugetexe,
                    workingDirectory,
                    args,
                    waitForExit: true);
                server.Stop();

                // Assert
                Assert.Equal(1, r1.Item1);

                Assert.Equal(3, requests.Count);
                Assert.True(requests[0].EndsWith("Packages(Id='testPackage1',Version='1.1')"));
                Assert.True(requests[1].EndsWith("Packages(Id='testPackage1',Version='1.1.0')"));
                Assert.True(requests[2].EndsWith("Packages(Id='testPackage1',Version='1.1.0.0')"));
            }
            finally
            {
                // Cleanup
                Util.DeleteDirectory(workingDirectory);
            }
        }

        // Tests that nuget will NOT download package from http source if the package on the server
        // has the same hash value as the cached version.
        [Fact]
        public void InstallCommand_WillUseCachedFile()
        {
            var targetDir = ConfigurationManager.AppSettings["TargetDir"];
            var nugetexe = Path.Combine(targetDir, "nuget.exe");
            var tempPath = Path.GetTempPath();
            var packageDirectory = Path.Combine(tempPath, Guid.NewGuid().ToString());
            var workingDirectory = Path.Combine(tempPath, Guid.NewGuid().ToString());
            var mockServerEndPoint = "http://localhost:1234/";

            try
            {
                // Arrange
                Util.CreateDirectory(packageDirectory);
                Util.CreateDirectory(workingDirectory);
                var packageFileName = Util.CreateTestPackage("testPackage1", "1.1.0", packageDirectory);
                var package = new ZipPackage(packageFileName);
                MachineCache.Default.RemovePackage(package);

                // add the package to machine cache
                MachineCache.Default.AddPackage(package);

                var server = new MockServer(mockServerEndPoint);
                string findPackagesByIdRequest = string.Empty;
                bool packageDownloadIsCalled = false;

                server.Get.Add("/nuget/FindPackagesById()", r =>
                    new Action<HttpListenerResponse>(response =>
                    {
                        findPackagesByIdRequest = r.Url.ToString();
                        response.ContentType = "application/atom+xml;type=feed;charset=utf-8";
                        string feed = server.ToODataFeed(new[] { package }, "FindPackagesById");
                        MockServer.SetResponseContent(response, feed);
                    }));

                server.Get.Add("/nuget/Packages(Id='testPackage1',Version='1.1.0')", r =>
                    new Action<HttpListenerResponse>(response =>
                    {
                        response.ContentType = "application/atom+xml;type=entry;charset=utf-8";
                        var p1 = server.ToOData(package);
                        MockServer.SetResponseContent(response, p1);
                    }));

                server.Get.Add("/package/testPackage1", r =>
                    new Action<HttpListenerResponse>(response =>
                    {
                        packageDownloadIsCalled = true;
                        response.ContentType = "application/zip";
                        using (var stream = package.GetStream())
                        {
                            var content = stream.ReadAllBytes();
                            MockServer.SetResponseContent(response, content);
                        }
                    }));

                server.Get.Add("/nuget", r => "OK");

                server.Start();

                // Act
                var args = "install testPackage1 -Source " + mockServerEndPoint + "nuget";
                var r1 = CommandRunner.Run(
                    nugetexe,
                    workingDirectory,
                    args,
                    waitForExit: true);
                server.Stop();

                // Assert
                Assert.Equal(0, r1.Item1);
                Assert.Contains("$filter=IsLatestVersion", findPackagesByIdRequest);

                // verifies that package is NOT downloaded from server since nuget uses
                // the file in machine cache.
                Assert.False(packageDownloadIsCalled);
            }
            finally
            {
                // Cleanup
                Util.DeleteDirectory(packageDirectory);
                Util.DeleteDirectory(workingDirectory);
            }
        }

        // Tests that nuget will download package from http source if the package on the server
        // has a different hash value from the cached version.
        [Fact]
        public void InstallCommand_DownloadPackageWhenHashChanges()
        {
            var targetDir = ConfigurationManager.AppSettings["TargetDir"];
            var nugetexe = Path.Combine(targetDir, "nuget.exe");
            var tempPath = Path.GetTempPath();
            var packageDirectory = Path.Combine(tempPath, Guid.NewGuid().ToString());
            var workingDirectory = Path.Combine(tempPath, Guid.NewGuid().ToString());
            var mockServerEndPoint = "http://localhost:1234/";

            try
            {
                // Arrange
                Util.CreateDirectory(packageDirectory);
                Util.CreateDirectory(workingDirectory);
                var packageFileName = Util.CreateTestPackage("testPackage1", "1.1.0", packageDirectory);
                var package = new ZipPackage(packageFileName);
                MachineCache.Default.RemovePackage(package);

                // add the package to machine cache
                MachineCache.Default.AddPackage(package);

                // create a new package. Now this package has different hash value from the package in
                // the machine cache.
                packageFileName = Util.CreateTestPackage("testPackage1", "1.1.0", packageDirectory);
                package = new ZipPackage(packageFileName);

                var server = new MockServer(mockServerEndPoint);
                string findPackagesByIdRequest = string.Empty;
                bool packageDownloadIsCalled = false;

                server.Get.Add("/nuget/FindPackagesById()", r =>
                    new Action<HttpListenerResponse>(response =>
                    {
                        findPackagesByIdRequest = r.Url.ToString();
                        response.ContentType = "application/atom+xml;type=feed;charset=utf-8";
                        string feed = server.ToODataFeed(new[] { package }, "FindPackagesById");
                        MockServer.SetResponseContent(response, feed);
                    }));

                server.Get.Add("/nuget/Packages(Id='testPackage1',Version='1.1.0')", r =>
                    new Action<HttpListenerResponse>(response =>
                    {
                        response.ContentType = "application/atom+xml;type=entry;charset=utf-8";
                        var p1 = server.ToOData(package);
                        MockServer.SetResponseContent(response, p1);
                    }));

                server.Get.Add("/package/testPackage1", r =>
                    new Action<HttpListenerResponse>(response =>
                    {
                        packageDownloadIsCalled = true;
                        response.ContentType = "application/zip";
                        using (var stream = package.GetStream())
                        {
                            var content = stream.ReadAllBytes();
                            MockServer.SetResponseContent(response, content);
                        }
                    }));

                server.Get.Add("/nuget", r => "OK");

                server.Start();

                // Act
                var args = "install testPackage1 -Source " + mockServerEndPoint + "nuget";
                var r1 = CommandRunner.Run(
                    nugetexe,
                    workingDirectory,
                    args,
                    waitForExit: true);
                server.Stop();

                // Assert
                Assert.Equal(0, r1.Item1);
                Assert.Contains("$filter=IsLatestVersion", findPackagesByIdRequest);

                // verifies that package is downloaded from server since the cached version has
                // a different hash from the package on the server.
                Assert.True(packageDownloadIsCalled);
            }
            finally
            {
                // Cleanup
                Util.DeleteDirectory(packageDirectory);
                Util.DeleteDirectory(workingDirectory);
            }
        }

        // Tests that when both the normal package and the symbol package exist in a local repository,
        // nuget install should pick the normal package.
        [Fact]
        public void InstallCommand_PreferNonSymbolPackage()
        {
            var tempPath = Path.GetTempPath();
            var source = Path.Combine(tempPath, Guid.NewGuid().ToString());
            var outputDirectory = Path.Combine(tempPath, Guid.NewGuid().ToString());

            try
            {
                // Arrange
                Util.CreateDirectory(source);
                Util.CreateDirectory(outputDirectory);

                var packageFileName = PackageCreater.CreatePackage(
                    "testPackage1", "1.1.0", source);
                var symbolPackageFileName = PackageCreater.CreateSymbolPackage(
                    "testPackage1", "1.1.0", source);

                // Act
                string[] args = new string[] {
                    "install", "testPackage1",
                    "-OutputDirectory", outputDirectory,
                    "-Source", source };
                int r = Program.Main(args);

                // Assert
                Assert.Equal(0, r);
                var testTxtFile = Path.Combine(
                    outputDirectory,
                    @"testPackage1.1.1.0\content\test1.txt");
                Assert.True(File.Exists(testTxtFile));

                var symbolTxtFile = Path.Combine(
                    outputDirectory,
                    @"testPackage1.1.1.0\symbol.txt");
                Assert.False(File.Exists(symbolTxtFile));
            }
            finally
            {
                // Cleanup
                Util.DeleteDirectory(outputDirectory);
                Util.DeleteDirectory(source);
            }
        }
    }
}


text:
class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """

        flag = [-1 for x in xrange(256)] # for 265 acii characters
        start = 0
        maxlen = 0
        for i in xrange(len(s)):
        	print flag[ord('a'):ord('d')+1], s[i] , i, start, maxlen

    		# check if this character has appeared in current substr
        	if flag[ord(s[i])] >= start:
        		# if repeated, compare existing longest substr with current substr
        		maxlen = max(maxlen, i - start)
        		# update starting positon of next substr
        		start = flag[ord(s[i])] + 1
        	# update the lastest position of this character
        	flag[ord(s[i])] = i

        maxlen = max(maxlen, len(s)-start)

        return maxlen

if __name__ == '__main__':
	s = "falsoiuelakhflkadhfih2983ryaliufhawp983yrp91#&(*#&hfieh(P(@*U(R*iu"
	print Solution().lengthOfLongestSubstring(s)


text:
<?php
namespace Boekkooi\Tactician\AMQP\Middleware;

use Boekkooi\Tactician\AMQP\Message;
use Boekkooi\Tactician\AMQP\Publisher\MessageCapturer;
use League\Tactician\Middleware;

/**
 * A middleware that will publish any message and store it in memory
 */
class MessageCapturingMiddleware implements Middleware
{
    /**
     * @var MessageCapturer
     */
    private $capturer;

    /**
     * @param MessageCapturer $capturer
     */
    public function __construct(MessageCapturer $capturer)
    {
        $this->capturer = $capturer;
    }

    /**
     * {@inheritdoc}
     */
    public function execute($command, callable $next)
    {
        if (!$command instanceof Message) {
            return $next($command);
        }

        $this->capturer->publish($command);

        return null;
    }
}


text:
@interface BaseNavController ()

@end

@implementation BaseNavController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(BOOL)shouldAutorotate
{
    return [[self.viewControllers lastObject] shouldAutorotate];
}

-(NSUInteger)supportedInterfaceOrientations
{
    return [[self.viewControllers lastObject] supportedInterfaceOrientations];
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return [[self.viewControllers lastObject] preferredInterfaceOrientationForPresentation];
}

@end


text:
namespace realm {

class SyncUser;
class SyncLoggerFactory;

class Adapter {
public:
    Adapter(std::function<void(std::string)> realm_changed, std::function<bool(const std::string&)> should_watch_realm_predicate,
            std::string local_root_dir, SyncConfig sync_config_template);

    enum class InstructionType {
        Insert,
        Delete,
        Set,
        Clear,
        ListSet,
        ListInsert,
        ListErase,
        ListClear,
        AddType,
        AddProperties,
    };

    static std::string instruction_type_string(InstructionType type) {
        switch (type) {
            case InstructionType::Insert:           return "INSERT";
            case InstructionType::Delete:           return "DELETE";
            case InstructionType::Set:              return "SET";
            case InstructionType::Clear:            return "CLEAR";
            case InstructionType::ListSet:          return "LIST_SET";
            case InstructionType::ListInsert:       return "LIST_INSERT";
            case InstructionType::ListErase:        return "LIST_ERASE";
            case InstructionType::ListClear:        return "LIST_CLEAR";
            case InstructionType::AddType:          return "ADD_TYPE";
            case InstructionType::AddProperties:    return "ADD_PROPERTIES";
        }
        REALM_COMPILER_HINT_UNREACHABLE();
    }

    util::Optional<util::AppendBuffer<char>> current(std::string realm_path);
    void advance(std::string realm_path);

    Realm::Config get_config(std::string path, util::Optional<Schema> schema = util::none);

    void close() { m_impl.reset(); }

private:
    class Impl;
    std::shared_ptr<Impl> m_impl;
};

} // namespace realm

#endif // REALM_SYNC_ADAPTER_HPP


text:
version: 0.9.0
title: Sigile
---

Tworzenie i praca z sigilami.

{% include toc.html %}

## Czym są sigile

Elixir posiada specjalną składnię pozwalającą na pracę z literałami. Sigil, bo o nim mowa,  rozpoczyna się znakiem tyldy `~`, a po nim następuje pojedyncza litera. Biblioteka standardowa Elixira dostarcza predefiniowane sigile, ale można też stworzyć własne, gdy potrzebujemy w jakiś sposób rozszerzyć możliwości języka.

Lista dostępnych sigili to:

  - `~C` Tworzy listę znaków **bez uwzględnienia** interpolacji i interpretacji znaków specjalnych.
  - `~c` Tworzy listę znaków **z uwzględnieniem** interpolacji i interpretacji znaków specjalnych.
  - `~R` Tworzy wyrażenie regularne **bez uwzględnienia** interpolacji i interpretacji znaków specjalnych.
  - `~r` Tworzy wyrażenie regularne **z uwzględnieniem** interpolacji i interpretacji znaków specjalnych.
  - `~S` Tworzy ciąg znaków **bez uwzględnienia** interpolacji i interpretacji znaków specjalnych.
  - `~s` Tworzy ciąg znaków **z uwzględnieniem** interpolacji i interpretacji znaków specjalnych.
  - `~W` Tworzy listę słów **bez uwzględnienia** interpolacji i interpretacji znaków specjalnych.
  - `~w` Tworzy listę słów **z uwzględnieniem** interpolacji i interpretacji znaków specjalnych.
  - `~N` Tworzy strukturę `NaiveDateTime`.

Listę możemy utworzyć korzystając ze znaków:

  - `<...>` Nawisy ostrokątne
  - `{...}` Nawiasy klamrowe
  - `[...]` Nawiasy kwadratowe
  - `(...)` Nawiasy okrągłe
  - `|...|` Para kresek pionowych
  - `/.../` Para ukośników prawych (ang. slash)
  - `"..."` Cudzysłów
  - `'...'` Cudzysłów pojedynczy

### Listy znaków

Za pomocą sigili `~c` i `~C` możemy utworzyć listę znaków. Na przykład:

```elixir
iex> ~c/2 + 7 = #{2 + 7}/
'2 + 7 = 9'

iex> ~C/2 + 7 = #{2 + 7}/
'2 + 7 = \#{2 + 7}'
```

Jak widać sigil `~c`, pisany małą literą, przeprowadza obliczenia, w przeciwieństwie do `~C`, pisany wielką literą. Konwencja wyliczania wartości, bądź nie, z pomocą użycia odpowiedniej małej albo wielkiej litery jest taka sama dla wszystkich sigili.

### Wyrażenia regularne

Sigile `~r` i `~R` służą do tworzenia wyrażeń regularnych. Można też w tym celu użyć funkcji `Regex`:

```elixir
iex> re = ~r/elixir/
~r/elixir/

iex> "Elixir" =~ re
false

iex> "elixir" =~ re
true
```

Jak widzimy pierwszy test nie powiódł się, ponieważ `Elixir` nie pasuje do wyrażenia, gdyż to uwzględnia wielkość liter. Ponieważ Elixir wspiera wyrażenia regularne kompatybilne z Perlem (PCRE - Perl Compatible Regular Expressions), możemy dodać `i` na końcu sigila by dopasowanie nie brało pod uwagę wielkości liter.

```elixir
iex> re = ~r/elixir/i
~r/elixir/i

iex> "Elixir" =~ re
true

iex> "elixir" =~ re
true
```

Elixir posiada też moduł [Regex](https://hexdocs.pm/elixir/Regex.html), którego API jest oparte o
bibliotekę do obsługi wyrażeń  regularnych z Erlanga. Zaimplementujmy funkcję `Regex.split/2` z użyciem sigila:

```elixir
iex> string = "100_000_000"
"100_000_000"

iex> Regex.split(~r/_/, string)
["100", "000", "000"]
```

Jak widać, ciąg znaków  `"100_000_000"` został podzielony za pomocą `~r/_/`. Funkcja `Regex.split` zwróciła listę.

### Ciągi znaków

Sigile `~s` i `~S` są używane do pracy z ciągami znaków:

```elixir
iex> ~s/the cat in the hat on the mat/
"the cat in the hat on the mat"

iex> ~S/the cat in the hat on the mat/
"the cat in the hat on the mat"
```
Jaka jest między nimi różnica? Taka sama jak w przypadku list znaków, które już omawialiśmy. Sigil pisany wielką literą wykona się na ciągu już zinterpretowanym, w którym wykonano też sekwencje ucieczki. Przyjrzyjmy się temu na kolejnym przykładzie:

```elixir
iex> ~s/welcome to elixir #{String.downcase "school"}/
"welcome to elixir school"

iex> ~S/welcome to elixir #{String.downcase "school"}/
"welcome to elixir \#{String.downcase \"school\"}"
```

### Listy słów

Sigile służące do tworzenia listy słów, `~w` i `~W`, są czasami bardzo przydatne. Mogą oszczędzić nam mnóstwo czasu, klepania w klawiaturę oraz zredukować złożoność naszego kodu. Na prostym przykładzie:

```elixir
iex> ~w/i love elixir school/
["i", "love", "elixir", "school"]

iex> ~W/i love elixir school/
["i", "love", "elixir", "school"]
```

Widać tu, że ciąg znaków został podzielony na słowa. Oczywiście pomiędzy tymi dwoma wywołaniami nie ma różnicy, bo znowuż leży ona w interpolacji ciągu i użyciu znaków ucieczki, tak ja na poniższym przykładzie:

```elixir
iex> ~w/i love #{'e'}lixir school/
["i", "love", "elixir", "school"]

iex> ~W/i love #{'e'}lixir school/
["i", "love", "\#{'e'}lixir", "school"]
```

### Struktura `NaiveDateTime`

Struktura [NaiveDateTime](https://hexdocs.pm/elixir/NaiveDateTime.html) jest uproszczeniem `DateTime`, które nie posiada informacji o strefie czasowej.

W większości wypadków nie powinniśmy tworzyć tej struktury w bezpośredni sposób, ale wyjątek stanowi tu użycie jej w dopasowaniach wzorców:

```elixir
iex> NaiveDateTime.from_iso8601("2015-01-23 23:50:07") == {:ok, ~N[2015-01-23 23:50:07]}
```

## Tworzenie sigili

Jednym z założeń Elixira jest możliwość łatwego rozszerzania języka. Zatem nie jest żadną niespodzianką możliwość tworzenia własnych sigili w łatwy sposób. Nasz przykładowy sigil będzie zmieniać ciąg znaków na wielkie litery. Oczywiście Elixir ma odpowiednią funkcję w standardowym API (`String.upcase/1`). Nasze rozwiązanie będzie z niego korzystać.

```elixir

iex> defmodule MySigils do
...>   def sigil_u(string, []), do: String.upcase(string)
...> end

iex> import MySigils
nil

iex> ~u/elixir school/
ELIXIR SCHOOL
```

Najpierw zdefiniowaliśmy moduł `MySigils`, a w nim funkcję `sigil_u`. Nie ma sigila `~u` wśród istniejących, a zatem możemy taki utworzyć. Zapis `_u` oznacza, że w nasz sigil będzie zapisywany jako `u` poprzedzone tyldą. Funkcja musi przyjmować dwa parametry, dane i listę.