text:
package consul

import (
	"context"
	"testing"
	"time"

	"net/http"
	"net/http/httptest"
	"net/url"

	"github.com/go-kit/kit/log"
	"github.com/prometheus/common/model"
	"github.com/prometheus/prometheus/discovery/targetgroup"
	"github.com/prometheus/prometheus/util/testutil"
)

func TestConfiguredService(t *testing.T) {
	conf := &SDConfig{
		Services: []string{"configuredServiceName"}}
	consulDiscovery, err := NewDiscovery(conf, nil)

	if err != nil {
		t.Errorf("Unexpected error when initialising discovery %v", err)
	}
	if !consulDiscovery.shouldWatch("configuredServiceName", []string{""}) {
		t.Errorf("Expected service %s to be watched", "configuredServiceName")
	}
	if consulDiscovery.shouldWatch("nonConfiguredServiceName", []string{""}) {
		t.Errorf("Expected service %s to not be watched", "nonConfiguredServiceName")
	}
}

func TestConfiguredServiceWithTag(t *testing.T) {
	conf := &SDConfig{
		Services:   []string{"configuredServiceName"},
		ServiceTag: "http",
	}
	consulDiscovery, err := NewDiscovery(conf, nil)

	if err != nil {
		t.Errorf("Unexpected error when initialising discovery %v", err)
	}
	if consulDiscovery.shouldWatch("configuredServiceName", []string{""}) {
		t.Errorf("Expected service %s to not be watched without tag", "configuredServiceName")
	}
	if !consulDiscovery.shouldWatch("configuredServiceName", []string{"http"}) {
		t.Errorf("Expected service %s to be watched with tag %s", "configuredServiceName", "http")
	}
	if consulDiscovery.shouldWatch("nonConfiguredServiceName", []string{""}) {
		t.Errorf("Expected service %s to not be watched without tag", "nonConfiguredServiceName")
	}
	if consulDiscovery.shouldWatch("nonConfiguredServiceName", []string{"http"}) {
		t.Errorf("Expected service %s to not be watched with tag %s", "nonConfiguredServiceName", "http")
	}
}

func TestNonConfiguredService(t *testing.T) {
	conf := &SDConfig{}
	consulDiscovery, err := NewDiscovery(conf, nil)

	if err != nil {
		t.Errorf("Unexpected error when initialising discovery %v", err)
	}
	if !consulDiscovery.shouldWatch("nonConfiguredServiceName", []string{""}) {
		t.Errorf("Expected service %s to be watched", "nonConfiguredServiceName")
	}
}

const (
	AgentAnswer       = `{"Config": {"Datacenter": "test-dc"}}`
	ServiceTestAnswer = `[{
"ID": "b78c2e48-5ef3-1814-31b8-0d880f50471e",
"Node": "node1",
"Address": "1.1.1.1",
"Datacenter": "test-dc",
"NodeMeta": {"rack_name": "2304"},
"ServiceID": "test",
"ServiceName": "test",
"ServiceTags": ["tag1"],
"ServicePort": 3341,
"CreateIndex": 1,
"ModifyIndex": 1
}]`
	ServicesTestAnswer = `{"test": ["tag1"], "other": ["tag2"]}`
)

func newServer(t *testing.T) (*httptest.Server, *SDConfig) {
	// github.com/hashicorp/consul/testutil/ would be nice but it needs a local consul binary.
	stub := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		response := ""
		switch r.URL.String() {
		case "/v1/agent/self":
			response = AgentAnswer
		case "/v1/catalog/service/test?node-meta=rack_name%3A2304&stale=&tag=tag1&wait=30000ms":
			response = ServiceTestAnswer
		case "/v1/catalog/service/test?wait=30000ms":
			response = ServiceTestAnswer
		case "/v1/catalog/service/other?wait=30000ms":
			response = `[]`
		case "/v1/catalog/services?node-meta=rack_name%3A2304&stale=&wait=30000ms":
			response = ServicesTestAnswer
		case "/v1/catalog/services?wait=30000ms":
			response = ServicesTestAnswer
		case "/v1/catalog/services?index=1&node-meta=rack_name%3A2304&stale=&wait=30000ms":
			time.Sleep(5 * time.Second)
			response = ServicesTestAnswer
		case "/v1/catalog/services?index=1&wait=30000ms":
			time.Sleep(5 * time.Second)
			response = ServicesTestAnswer
		default:
			t.Errorf("Unhandeld consul call: %s", r.URL)
		}
		w.Header().Add("X-Consul-Index", "1")
		w.Write([]byte(response))
	}))
	stuburl, err := url.Parse(stub.URL)
	testutil.Ok(t, err)

	config := &SDConfig{
		Server:          stuburl.Host,
		Token:           "fake-token",
		RefreshInterval: model.Duration(1 * time.Second),
	}
	return stub, config
}

func newDiscovery(t *testing.T, config *SDConfig) *Discovery {
	logger := log.NewNopLogger()
	d, err := NewDiscovery(config, logger)
	testutil.Ok(t, err)
	return d
}

func checkOneTarget(t *testing.T, tg []*targetgroup.Group) {
	testutil.Equals(t, 1, len(tg))
	target := tg[0]
	testutil.Equals(t, "test-dc", string(target.Labels["__meta_consul_dc"]))
	testutil.Equals(t, target.Source, string(target.Labels["__meta_consul_service"]))
	if target.Source == "test" {
		// test service should have one node.
		testutil.Assert(t, len(target.Targets) > 0, "Test service should have one node")
	}
}

// Watch all the services in the catalog.
func TestAllServices(t *testing.T) {
	stub, config := newServer(t)
	defer stub.Close()

	d := newDiscovery(t, config)

	ctx, cancel := context.WithCancel(context.Background())
	ch := make(chan []*targetgroup.Group)
	go d.Run(ctx, ch)
	checkOneTarget(t, <-ch)
	checkOneTarget(t, <-ch)
	cancel()
}

// Watch only the test service.
func TestOneService(t *testing.T) {
	stub, config := newServer(t)
	defer stub.Close()

	config.Services = []string{"test"}
	d := newDiscovery(t, config)

	ctx, cancel := context.WithCancel(context.Background())
	ch := make(chan []*targetgroup.Group)
	go d.Run(ctx, ch)
	checkOneTarget(t, <-ch)
	cancel()
}

// Watch the test service with a specific tag and node-meta.
func TestAllOptions(t *testing.T) {
	stub, config := newServer(t)
	defer stub.Close()

	config.Services = []string{"test"}
	config.NodeMeta = map[string]string{"rack_name": "2304"}
	config.ServiceTag = "tag1"
	config.AllowStale = true
	config.Token = "fake-token"

	d := newDiscovery(t, config)

	ctx, cancel := context.WithCancel(context.Background())
	ch := make(chan []*targetgroup.Group)
	go d.Run(ctx, ch)
	checkOneTarget(t, <-ch)
	cancel()
}


text: /*# sourceMappingURL=brown.css.map */

redpajama_set_name: RedPajamaGithub


text:
import { Component, OnInit, OnDestroy, ComponentFactoryResolver, Injector } from '@angular/core';
import { Subject, combineLatest, iif, of, Observable, EMPTY } from 'rxjs';
import { tap, concatMap, filter, switchMap, delay, takeUntil, catchError } from 'rxjs/operators';
import { TranslateService } from '@ngx-translate/core';

import {
    NewUrlStateNotificationService,
    UrlRouteManagerService,
    WebAppSettingDataService,
    StoreHelperService,
    AnalyticsService,
    DynamicPopupService,
    TRACKED_EVENT_LIST,
    MessageQueueService,
    MESSAGE_TO,
} from 'app/shared/services';
import { ServerErrorPopupContainerComponent } from 'app/core/components/server-error-popup/server-error-popup-container.component';
import { InspectorPageService, ISourceForServerAndAgentList } from 'app/routes/inspector-page/inspector-page.service';
import { UrlPath, UrlPathId } from 'app/shared/models';
import { ServerAndAgentListDataService } from './server-and-agent-list-data.service';
import { isEmpty, isThatType } from 'app/core/utils/util';

@Component({
    selector: 'pp-server-and-agent-list-container',
    templateUrl: './server-and-agent-list-container.component.html',
    styleUrls: ['./server-and-agent-list-container.component.css'],
})
export class ServerAndAgentListContainerComponent implements OnInit, OnDestroy {
    private unsubscribe = new Subject<void>();

    filterStr: string;
    agentId: string;
    serverList: { [key: string]: IServerAndAgentData[] };
    filteredServerList: { [key: string]: IServerAndAgentData[] } = {};
    filteredServerKeyList: string[] = [];
    funcImagePath: Function;
    isEmpty: boolean;
    emptyText$: Observable<string>;
    errorMessage: string;

    constructor(
        private newUrlStateNotificationService: NewUrlStateNotificationService,
        private urlRouteManagerService: UrlRouteManagerService,
        private webAppSettingDataService: WebAppSettingDataService,
        private storeHelperService: StoreHelperService,
        private dynamicPopupService: DynamicPopupService,
        private analyticsService: AnalyticsService,
        private componentFactoryResolver: ComponentFactoryResolver,
        private injector: Injector,
        private inspectorPageService: InspectorPageService,
        private serverAndAgentListDataService: ServerAndAgentListDataService,
        private messageQueueService: MessageQueueService,
        private translateService: TranslateService,
    ) {}

    ngOnInit() {
        this.initI18nText();
        this.funcImagePath = this.webAppSettingDataService.getImagePathMakeFunc();
        combineLatest(
            this.inspectorPageService.sourceForServerAndAgentList$.pipe(
                takeUntil(this.unsubscribe),
                filter((data: ISourceForServerAndAgentList) => !!data),
                switchMap((data: ISourceForServerAndAgentList) => {
                    return iif(() => data.emitAfter === 0,
                        of(data),
                        of(data).pipe(delay(data.emitAfter))
                    );
                }),
                tap(({agentId}: ISourceForServerAndAgentList) => {
                    this.agentId = agentId;
                }),
                concatMap(({range}: ISourceForServerAndAgentList) => {
                    const appName = (this.newUrlStateNotificationService.getPathValue(UrlPathId.APPLICATION) as IApplication).getApplicationName();
                    const requestStartAt = Date.now();

                    return this.serverAndAgentListDataService.getData(appName, range).pipe(
                        filter((res: {[key: string]: IServerAndAgentData[]} | IServerErrorShortFormat) => {
                            if (isThatType<IServerErrorShortFormat>(res, 'errorCode', 'errorMessage')) {
                                this.errorMessage = res.errorMessage;
                                this.messageQueueService.sendMessage({to: MESSAGE_TO.IS_ACCESS_DENYED, param: true});
                                return false;
                            } else {
                                this.errorMessage = '';
                                this.messageQueueService.sendMessage({to: MESSAGE_TO.IS_ACCESS_DENYED, param: false});
                                return true;
                            }
                        }),
                        filter((res: {[key: string]: IServerAndAgentData[]}) => {
                            if (this.agentId) {
                                const filteredList = this.filterServerList(res, this.agentId, ({ agentId }: IServerAndAgentData) => this.agentId.toLowerCase() === agentId.toLowerCase());
                                const isAgentIdValid = Object.keys(filteredList).length !== 0;

                                if (isAgentIdValid) {
                                    return true;
                                } else {
                                    const url = this.newUrlStateNotificationService.isRealTimeMode()
                                        ? [ UrlPath.INSPECTOR, UrlPathId.REAL_TIME, this.newUrlStateNotificationService.getPathValue(UrlPathId.APPLICATION).getUrlStr() ]
                                        : [
                                            UrlPath.INSPECTOR,
                                            this.newUrlStateNotificationService.getPathValue(UrlPathId.APPLICATION).getUrlStr(),
                                            this.newUrlStateNotificationService.getPathValue(UrlPathId.PERIOD).getValueWithTime(),
                                            this.newUrlStateNotificationService.getPathValue(UrlPathId.END_TIME).getEndTime()
                                        ];

                                    this.urlRouteManagerService.moveOnPage({ url });

                                    return false;
                                }
                            } else {
                                return true;
                            }
                        }),
                        tap(() => {
                            const responseArriveAt = Date.now();
                            const deltaT = responseArriveAt - requestStartAt;
                            const now = range[1] + deltaT;

                            this.messageQueueService.sendMessage({
                                to: MESSAGE_TO.INSPECTOR_PAGE_VALID,
                                param: {range, now}
                            });
                        }),
                        catchError((error: IServerErrorFormat) => {
                            this.dynamicPopupService.openPopup({
                                data: {
                                    title: 'Error',
                                    contents: error
                                },
                                component: ServerErrorPopupContainerComponent
                            }, {
                                resolver: this.componentFactoryResolver,
                                injector: this.injector
                            });

                            return EMPTY;
                        })
                    );
                }),
            ),
            this.storeHelperService.getServerAndAgentQuery<string>(this.unsubscribe)
        ).subscribe(([data, query]: [{[key: string]: IServerAndAgentData[]}, string]) => {
            this.filteredServerList = this.filterServerList(data, query, ({ agentId, agentName }: IServerAndAgentData) =>
                agentId.toLowerCase().includes(query.toLowerCase()) || ( agentName && agentName.toLowerCase().includes(query.toLowerCase()) )
            );
            this.filteredServerKeyList = Object.keys(this.filteredServerList).sort();
            this.isEmpty = isEmpty(this.filteredServerList);
        });
    }

    ngOnDestroy() {
        this.unsubscribe.next();
        this.unsubscribe.complete();
    }

    private initI18nText(): void {
        this.emptyText$ = this.translateService.get('COMMON.EMPTY_ON_SEARCH');
    }

    onSelectAgent(agentId: string) {
        const url = this.newUrlStateNotificationService.isRealTimeMode() ?
            [
                UrlPath.INSPECTOR,
                UrlPath.REAL_TIME,
                this.newUrlStateNotificationService.getPathValue(UrlPathId.APPLICATION).getUrlStr(),
                agentId
            ] :
            [
                UrlPath.INSPECTOR,
                this.newUrlStateNotificationService.getPathValue(UrlPathId.APPLICATION).getUrlStr(),
                this.newUrlStateNotificationService.getPathValue(UrlPathId.PERIOD).getValueWithTime(),
                this.newUrlStateNotificationService.getPathValue(UrlPathId.END_TIME).getEndTime(),
                agentId
            ];

        this.urlRouteManagerService.moveOnPage({ url });
        this.analyticsService.trackEvent(TRACKED_EVENT_LIST.GO_TO_AGENT_INSPECTOR);
    }

    private filterServerList(serverList: { [key: string]: IServerAndAgentData[] }, query: string, predi: any): { [key: string]: IServerAndAgentData[] } {
        return query === ''
            ? serverList
            : Object.keys(serverList).reduce((acc: { [key: string]: IServerAndAgentData[] }, key: string) => {
                const matchedList = serverList[key].filter(predi);

                return matchedList.length !== 0 ? { ...acc, [key]: matchedList } : acc;
            }, {} as { [key: string]: IServerAndAgentData[] });
    }
}


text:
import styled, { css } from 'styled-components';
import { string, bool } from 'prop-types';
import { getBaseLineHeight, calcLineHeight } from '../../theme/typography';
import {
  getHeadingSizingStyle,
  getHeadingColor,
  getHeadingCommonStyle,
} from './headingSelectors';

const propTypes = {
  color: string.isRequired,
  sizing: string.isRequired,
  marginBottom: bool.isRequired,
};

const StyledHeading = styled.h1`
  display: block;
  ${({ theme, color, sizing, marginBottom }) => {
    const baseLineHeight = getBaseLineHeight(theme);
    const sizingStyle = getHeadingSizingStyle(theme, sizing);
    return css`
      ${getHeadingCommonStyle(theme, sizing)}
      color: ${getHeadingColor(theme, color)};
      line-height: ${calcLineHeight(sizingStyle.fontSize, baseLineHeight)};
      margin-bottom: ${marginBottom ? `${baseLineHeight}rem` : '0'};
      ${sizingStyle}
    `;
  }}
`;

StyledHeading.propTypes = propTypes;

export default StyledHeading;


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

import java.io.Serializable;

import org.activiti.engine.ActivitiException;
import org.activiti.engine.ActivitiIllegalArgumentException;
import org.activiti.engine.ActivitiObjectNotFoundException;
import org.activiti.engine.impl.interceptor.Command;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.activiti.engine.task.Task;

/**
 * An abstract superclass for {@link Command} implementations that
 * want to verify the provided task is always active (ie. not suspended).
 *
 * @author Joram Barrez
 */
public abstract class NeedsActiveTaskCmd<T> implements Command<T>, Serializable {

  private static final long serialVersionUID = 1L;

  protected String taskId;

  public NeedsActiveTaskCmd(String taskId) {
    this.taskId = taskId;
  }

  public T execute(CommandContext commandContext) {

    if(taskId == null) {
      throw new ActivitiIllegalArgumentException("taskId is null");
    }

    TaskEntity task = commandContext
      .getTaskEntityManager()
      .findTaskById(taskId);

    if (task == null) {
      throw new ActivitiObjectNotFoundException("Cannot find task with id " + taskId, Task.class);
    }

    if (task.isSuspended()) {
      throw new ActivitiException(getSuspendedTaskException());
    }

    return execute(commandContext, task);
  }

  /**
   * Subclasses must implement in this method their normal command logic.
   * The provided task is ensured to be active.
   */
  protected abstract T execute(CommandContext commandContext, TaskEntity task);

  /**
   * Subclasses can override this method to provide a customized exception message
   * that will be thrown when the task is suspended.
   */
  protected String getSuspendedTaskException() {
    return "Cannot execute operation: task is suspended";
  }

}


text:
package se.uu.farmbio.vs

import org.apache.spark.{ SparkConf, SparkContext }

import org.apache.spark.mllib.classification.{ SVMWithSGD, SVMModel }

import org.apache.spark.mllib.optimization.{ LBFGS, HingeGradient, SquaredL2Updater }

import org.apache.spark.mllib.linalg.Vectors
import org.apache.spark.mllib.regression.LabeledPoint
import org.apache.spark.mllib.util.MLUtils
import org.apache.spark.rdd.RDD
import se.uu.it.cp.UnderlyingAlgorithm

// Define a MLlib SVM underlying algorithm
private object SVM {
  def trainingProcedure(
    input: RDD[LabeledPoint],
    maxNumItearations: Int,
    regParam: Double,
    numCorrections: Int,
    convergenceTol: Double) = {

    //Train SVM with LBFGS
    val numFeatures = input.take(1)(0).features.size
    val training = input.map(x => (x.label, MLUtils.appendBias(x.features))).cache()
    val initialWeightsWithIntercept = Vectors.dense(new Array[Double](numFeatures + 1))
    val (weightsWithIntercept, _) = LBFGS.runLBFGS(
      training,
      new HingeGradient(),
      new SquaredL2Updater(),
      numCorrections,
      convergenceTol,
      maxNumItearations,
      regParam,
      initialWeightsWithIntercept)

    //Create the model using the weights
    val model = new SVMModel(
      Vectors.dense(weightsWithIntercept.toArray.slice(0, weightsWithIntercept.size - 1)),
      weightsWithIntercept(weightsWithIntercept.size - 1))

    //Return raw score predictor
    model.clearThreshold()
    model

  }
}

private[vs] class MLlibSVM(val properTrainingSet: RDD[LabeledPoint], numIterations: Int)
    extends UnderlyingAlgorithm[LabeledPoint] {

  // First describe how to access Spark's LabeledPoint structure
  override def makeDataPoint(features: Seq[Double], label: Double) =
    new LabeledPoint(label, Vectors.dense(features.toArray))
  override def getDataPointFeatures(lp: LabeledPoint) = lp.features.toArray
  override def getDataPointLabel(lp: LabeledPoint) = lp.label

  val regParam: Double = 0.1
  val numCorrections: Int = 10
  val convergenceTol: Double = 1e-4
  val svmModel = SVM.trainingProcedure(properTrainingSet, numIterations, regParam, numCorrections, convergenceTol)

  // Define nonconformity measure as signed distance from the dividing hyperplane
  override def nonConformityMeasure(lp: LabeledPoint) = {
    if (lp.label == 1.0) {
      -svmModel.predict(lp.features)
    } else {
      svmModel.predict(lp.features)
    }
  }

}


text:
require 'delayed_job'
Delayed::Worker.max_attempts = 10
Delayed::Worker.max_run_time = 5.minutes
Delayed::Worker.destroy_failed_jobs = false
Delayed::Worker.logger = Logger.new(Rails.root.join('log/delayed_job.log'))

PRIORITIES = { push: 1, download: 2, web_hook: 3, stats: 4 }.freeze


text:
package main // import "github.com/GoogleCloudPlatform/appengine-sidecars-docker/api_proxy"

import (
	"log"
	"net/http"
)

func sbEnabledError(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusBadRequest)
	w.Write([]byte("App Engine APIs over the Service Bridge are disabled.\n" +
		"If they are required, enable them by setting the following to your app.yaml:\n" +
		"\n" +
		"beta_settings:\n" +
		"  enable_app_engine_apis: true\n"))
}

func makeHandler() http.Handler {
	mux := http.NewServeMux()
	mux.HandleFunc("/", sbEnabledError)
	return mux
}

func main() {
	handler := makeHandler()
	s := &http.Server{
		Addr:    ":10001",
		Handler: handler,
	}
	log.Fatal(s.ListenAndServe())
}


text:
[![Build Status](https://travis-ci.org/stefanzweifel/imgubox.svg?branch=master)](https://travis-ci.org/stefanzweifel/imgubox)
[![Code Climate](https://codeclimate.com/github/stefanzweifel/imgubox/badges/gpa.svg)](https://codeclimate.com/github/stefanzweifel/imgubox)
[![Test Coverage](https://codeclimate.com/github/stefanzweifel/imgubox/badges/coverage.svg)](https://codeclimate.com/github/stefanzweifel/imgubox/coverage)

****
### This project is no longer maintained!
****

> Found a funny cat GIF or an awesome wallpaper album? ImguBox stores those files within your Dropbox automatically.

Read more about this project on [my blog](https://stefanzweifel.io/projects/imgubox/).

## Selfhosting

This application was built with the PHP Framework Laravel 5.2. To run imgubox on your own server you need at least PHP 5.5!

To run the application you need the following:

- PHP
- A database Server (mysql, sqlite, …)
- A registered [Imgur Application](https://api.imgur.com/oauth2/addclient)
- A registered [Dropbox Application](https://www.dropbox.com/developers)

### Installation

```
git clone https://github.com/stefanzweifel/imgubox.git && cd imgubox
cp .env.example .env
composer install
php artisan key:generate
```

### Configuration

After you've installed the PHP dependencies you have to update the `.env` file to your needs:

- Add Database Credentials,
- Add Client ID, Secret Key, Redirect URL for Imgur and Dropbox

You then need to migrate and seed your database. Run the following on your server:

```shell
php artisan migrate --seed
```

The Application should be ready to go. Open the site in your browser of choice and create an account. You should then be able to connect with your Imgur and Dropbox Account.

### Running the Application

The core of imgubox is a scheduled [command](https://github.com/stefanzweifel/imgubox/blob/master/app/Console/Commands/FetchUserFavs.php) which runs every 30 minutes. The command will then dispatches a [job](https://github.com/stefanzweifel/imgubox/blob/master/app/Jobs/FetchImages.php) to the queue for every user with an active Imgur and Dropbox token. The Job gets the latest favorited images of the given user and dispatches another [job](https://github.com/stefanzweifel/imgubox/blob/master/app/Jobs/StoreImgurImages.php) which will then store the passed Imgur Image in Dropbox.

Add the following line to your `crontab`. The `schedule:run`  runs Laravel's internal Scheduling class. Read more about it [here](https://laravel.com/docs/5.2/scheduling#defining-schedules).

```shell
* * * * * php /home/imgubox/artisan schedule:run 1>> /dev/null 2>&1
```

As described above, Laravel pushed Jobs onto the queue you have configured in the beginning. The Queue can be consumed by the `queue:work` command. You can add the following line to your `supervisord` configuration. Replace `$YOUR_QUEUE_CONNECTION` with whatever you have configured in [this file](https://github.com/stefanzweifel/imgubox/blob/master/config/queue.php#L19).

```shell
php /home/imgubox/artisan queue:work $YOUR_QUEUE_CONNECTION --queue=high,low --daemon  2>&1
```


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace Microsoft.DocAsCode.Tools.AzureMarkdownRewriterTool
{
    using System;
    using System.Collections.Generic;

    using Newtonsoft.Json;

    public class AzureVideoRawInformation
    {
        [JsonProperty("namePropertyName")]
        public string NamePropertyName { get; set; }

        [JsonProperty("displayNamePropertyName")]
        public string DisplayNamePropertyName { get; set; }

        [JsonProperty("collectionNamePropertyName")]
        public string CollectionNamePropertyName { get; set; }

        [JsonProperty("pollingInterval")]
        public int PollingInterval { get; set; }

        [JsonProperty("fastPollingInterval")]
        public int FastPollingInterval { get; set; }

        [JsonProperty("slowPollingInterval")]
        public int SlowPollingInterval { get; set; }

        [JsonProperty("isComplete")]
        public bool IsComplete { get; set; }

        [JsonProperty("partialErrors")]
        public string PartialErrors { get; set; }

        [JsonProperty("data")]
        public List<AzureVideoDataItem> Data { get; set; }
    }

    public class AzureVideoDataItem
    {
        [JsonProperty("id")]
        public int Id { get; set; }

        [JsonProperty("title")]
        public string Title { get; set; }

        [JsonProperty("submissionStatus")]
        public string SubmissionStatus { get; set; }

        [JsonProperty("published")]
        public DateTime Published { get; set; }

        [JsonProperty("acomUrl")]
        public string AcomUrl { get; set; }

        [JsonProperty("channel9PlayerUrl")]
        public string Channel9PlayerUrl { get; set; }

        [JsonProperty("owner")]
        public string Owner { get; set; }

        [JsonProperty("order")]
        public string Order { get; set; }

        [JsonProperty("channel9Url")]
        public string Channel9Url { get; set; }
    }
}


text:
layout: post
title: He is the MILF Master.
titleinfo: pornvd
desc: Watch He is the MILF Master.. Pornhub is the ultimate xxx porn and sex site.
---

He is the MILF Master.

Watch He is the MILF Master.. Pornhub is the ultimate xxx porn and sex site.


text:
redirect_from:
- /ucp/evaluation-install/
- /ucp/install-sandbox/
---


text:
Install graph dependencies:
`fbpx install graphs/clock.fbp`

`fbpx browserify graphs/clock.fbp > example/bundle.js`

Watch:
`fbpx browserify graphs/alert.fbp --watch -o example/bundle.js`

Watch and reload with fb-flo:

`fbpx browserify graphs/alert.fbp --watch --browser -o example/bundle.js`

Server index.html
`http-server example/`


text:
<stack>
  <description brief="faa">Fly Alcohol Assay</description>
  <author>Maintained by Peter Polidoro</author>
  <license>BSD</license>
  <review status="unreviewed" notes=""/>
  <url>https://bitbucket.org/peterpolidoro/faa</url>
  <depend stack="ros" />

</stack>


text:
@interface CandyMachine (Dispenser)

- (void) dispenseCandy;

@end


text:
* Run sqlite using, `/usr/bin/sqlite3 sessions.db`.  This creates a sessions.db file in the directory which you run.
*

## MySQL
# Creating DSN

#Windows
* Download mysql odbc driver from http://cdn.mysql.com/Downloads/Connector-ODBC/5.3/mysql-connector-odbc-5.3.4-winx64.msi
* Open ODBC DataSources
* Click User DSN Tab and click Add...
* Select the MySQL ODBC 5.3 Unicode Driver
* Click Finish.
** Give any Data Source Name: sessionAnalyticsDSN
** Give your mysql user name and password
** Select the database you want.

#OS X
* Download mysql odbc driver from https://dev.mysql.com/downloads/file.php?id=453045
* Follow instructions on: https://dev.mysql.com/doc/connector-odbc/en/connector-odbc-configuration-dsn-osx.html
* Good luck!

In case the above does not work, use an alternative unregistered Julia Packages.  On the Julia REPL, run the following in sequence
* `Pkg.clone("git@github.com:JuliaDB/DBI.jl.git")`
* `Pkg.clone("git@github.com:johnmyleswhite/MySQL.jl.git")`
* `using DBI`
* `using MySQL`
* `db = connect(MySQL5, "127.0.0.1", "root", "root", "test")`


text:
class Vimpager < Formula
  desc "Use ViM as PAGER"
  homepage "https://github.com/rkitover/vimpager"
  url "https://github.com/rkitover/vimpager/archive/2.06.tar.gz"
  sha256 "cc616d0840a6f2501704eea70de222ab662421f34b2da307e11fb62aa70bda5d"
  head "https://github.com/rkitover/vimpager.git"

  option "with-pandoc", "Use pandoc to build and install man pages"
  depends_on "pandoc" => [:build, :optional]

  def install
    system "make", "docs" if build.with? "pandoc"
    bin.install "vimcat"
    bin.install "vimpager"
    doc.install "README.md", "vimcat.md", "vimpager.md"
    man1.install "vimcat.1", "vimpager.1" if build.with? "pandoc"
  end

  def caveats; <<-EOS.undent
    To use vimpager as your default pager, add `export PAGER=vimpager` to your
    shell configuration.
    EOS
  end

  test do
    (testpath/"test.txt").write <<-EOS.undent
      This is test
    EOS

    assert_match(/This is test/, shell_output("#{bin}/vimcat test.txt"))
  end
end


text:
namespace System.IdentityModel.Tokens
{
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Globalization;
    using System.IdentityModel;
    using System.IdentityModel.Claims;
    using System.IdentityModel.Selectors;
    using System.Runtime.Serialization;
    using System.Xml.Serialization;
    using System.Xml;

    public class SamlAuthenticationStatement : SamlSubjectStatement
    {
        DateTime authenticationInstant = DateTime.UtcNow.ToUniversalTime();
        string authenticationMethod = XD.SamlDictionary.UnspecifiedAuthenticationMethod.Value;
        readonly ImmutableCollection<SamlAuthorityBinding> authorityBindings = new ImmutableCollection<SamlAuthorityBinding>();
        string dnsAddress;
        string ipAddress;
        bool isReadOnly = false;

        public SamlAuthenticationStatement()
        {
        }

        public SamlAuthenticationStatement(SamlSubject samlSubject,
            string authenticationMethod,
            DateTime authenticationInstant,
            string dnsAddress,
            string ipAddress,
            IEnumerable<SamlAuthorityBinding> authorityBindings)
            : base(samlSubject)
        {
            if (string.IsNullOrEmpty(authenticationMethod))
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("authenticationMethod", SR.GetString(SR.SAMLAuthenticationStatementMissingAuthenticationMethod));

            this.authenticationMethod = authenticationMethod;
            this.authenticationInstant = authenticationInstant.ToUniversalTime();
            this.dnsAddress = dnsAddress;
            this.ipAddress = ipAddress;

            if (authorityBindings != null)
            {
                foreach (SamlAuthorityBinding binding in authorityBindings)
                {
                    if (binding == null)
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SAMLEntityCannotBeNullOrEmpty, XD.SamlDictionary.Assertion.Value));

                    this.authorityBindings.Add(binding);
                }
            }

            CheckObjectValidity();
        }

        public DateTime AuthenticationInstant
        {
            get { return this.authenticationInstant; }
            set
            {
                if (isReadOnly)
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ObjectIsReadOnly)));

                this.authenticationInstant = value;
            }
        }

        public string AuthenticationMethod
        {
            get { return this.authenticationMethod; }
            set
            {
                if (isReadOnly)
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ObjectIsReadOnly)));

                if (string.IsNullOrEmpty(value))
                    this.authenticationMethod = XD.SamlDictionary.UnspecifiedAuthenticationMethod.Value;
                else
                    this.authenticationMethod = value;
            }
        }

        public static string ClaimType
        {
            get
            {
                return ClaimTypes.Authentication;
            }
        }

        public IList<SamlAuthorityBinding> AuthorityBindings
        {
            get { return this.authorityBindings; }
        }

        public string DnsAddress
        {
            get { return this.dnsAddress; }
            set
            {
                if (isReadOnly)
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ObjectIsReadOnly)));

                this.dnsAddress = value;
            }
        }

        public string IPAddress
        {
            get { return this.ipAddress; }
            set
            {
                if (isReadOnly)
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ObjectIsReadOnly)));

                this.ipAddress = value;
            }
        }

        public override bool IsReadOnly
        {
            get { return this.isReadOnly; }
        }

        public override void MakeReadOnly()
        {
            if (!this.isReadOnly)
            {
                foreach (SamlAuthorityBinding binding in this.authorityBindings)
                {
                    binding.MakeReadOnly();
                }

                this.authorityBindings.MakeReadOnly();

                this.isReadOnly = true;
            }
        }

        protected override void AddClaimsToList(IList<Claim> claims)
        {
            if (claims == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("claims");

            claims.Add(new Claim(ClaimTypes.Authentication, new SamlAuthenticationClaimResource(this.authenticationInstant, this.authenticationMethod, this.dnsAddress, this.ipAddress, this.authorityBindings), Rights.PossessProperty));
        }

        void CheckObjectValidity()
        {
            if (this.SamlSubject == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLSubjectStatementRequiresSubject)));

            // Authenticaton instant is required. We will throw an exception if it is not present while
            // deserializing a SAML Authentication statement. When creating a new Authentication statement
            // we set this value to UtcNow.

            if (string.IsNullOrEmpty(this.authenticationMethod))
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLAuthenticationStatementMissingAuthenticationMethod)));
        }

        public override void ReadXml(XmlDictionaryReader reader, SamlSerializer samlSerializer, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver outOfBandTokenResolver)
        {
            if (reader == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("reader"));

            if (samlSerializer == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("samlSerializer"));

#pragma warning suppress 56506 // samlSerializer.DictionaryManager is never null.
            SamlDictionary dictionary = samlSerializer.DictionaryManager.SamlDictionary;

            string authInstance = reader.GetAttribute(dictionary.AuthenticationInstant, null);
            if (string.IsNullOrEmpty(authInstance))
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLAuthenticationStatementMissingAuthenticationInstanceOnRead)));
            this.authenticationInstant = DateTime.ParseExact(
                authInstance, SamlConstants.AcceptedDateTimeFormats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None).ToUniversalTime();

            this.authenticationMethod = reader.GetAttribute(dictionary.AuthenticationMethod, null);
            if (string.IsNullOrEmpty(this.authenticationMethod))
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLAuthenticationStatementMissingAuthenticationMethodOnRead)));

            reader.MoveToContent();
            reader.Read();

            if (reader.IsStartElement(dictionary.Subject, dictionary.Namespace))
            {
                SamlSubject subject = new SamlSubject();
                subject.ReadXml(reader, samlSerializer, keyInfoSerializer, outOfBandTokenResolver);
                base.SamlSubject = subject;
            }
            else
            {
                // Subject is a required element for a Authentication Statement clause.
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLAuthenticationStatementMissingSubject)));
            }

            if (reader.IsStartElement(dictionary.SubjectLocality, dictionary.Namespace))
            {
                this.dnsAddress = reader.GetAttribute(dictionary.SubjectLocalityDNSAddress, null);
                this.ipAddress = reader.GetAttribute(dictionary.SubjectLocalityIPAddress, null);

                if (reader.IsEmptyElement)
                {
                    reader.MoveToContent();
                    reader.Read();
                }
                else
                {
                    reader.MoveToContent();
                    reader.Read();
                    reader.ReadEndElement();
                }
            }

            while (reader.IsStartElement())
            {
                if (reader.IsStartElement(dictionary.AuthorityBinding, dictionary.Namespace))
                {
                    SamlAuthorityBinding binding = new SamlAuthorityBinding();
                    binding.ReadXml(reader, samlSerializer, keyInfoSerializer, outOfBandTokenResolver);
                    this.authorityBindings.Add(binding);
                }
                else
                {
                    // We do not understand this element.
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLBadSchema, dictionary.AuthenticationStatement)));
                }
            }

            reader.MoveToContent();
            reader.ReadEndElement();
        }

        public override void WriteXml(XmlDictionaryWriter writer, SamlSerializer samlSerializer, SecurityTokenSerializer keyInfoSerializer)
        {
            CheckObjectValidity();

            if (writer == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("writer"));

            if (samlSerializer == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("samlSerializer"));

#pragma warning suppress 56506 // samlSerializer.DictionaryManager is never null.
            SamlDictionary dictionary = samlSerializer.DictionaryManager.SamlDictionary;

            writer.WriteStartElement(dictionary.PreferredPrefix.Value, dictionary.AuthenticationStatement, dictionary.Namespace);

            writer.WriteStartAttribute(dictionary.AuthenticationMethod, null);
            writer.WriteString(this.authenticationMethod);
            writer.WriteEndAttribute();
            writer.WriteStartAttribute(dictionary.AuthenticationInstant, null);
            writer.WriteString(this.authenticationInstant.ToString(SamlConstants.GeneratedDateTimeFormat, CultureInfo.InvariantCulture));
            writer.WriteEndAttribute();

            this.SamlSubject.WriteXml(writer, samlSerializer, keyInfoSerializer);

            if ((this.ipAddress != null) || (this.dnsAddress != null))
            {
                writer.WriteStartElement(dictionary.PreferredPrefix.Value, dictionary.SubjectLocality, dictionary.Namespace);

                if (this.ipAddress != null)
                {
                    writer.WriteStartAttribute(dictionary.SubjectLocalityIPAddress, null);
                    writer.WriteString(this.ipAddress);
                    writer.WriteEndAttribute();
                }

                if (this.dnsAddress != null)
                {
                    writer.WriteStartAttribute(dictionary.SubjectLocalityDNSAddress, null);
                    writer.WriteString(this.dnsAddress);
                    writer.WriteEndAttribute();
                }

                writer.WriteEndElement();
            }

            for (int i = 0; i < this.authorityBindings.Count; i++)
            {
                this.authorityBindings[i].WriteXml(writer, samlSerializer, keyInfoSerializer);
            }

            writer.WriteEndElement();
        }
    }
}


text:
package ts.internal.client.protocol;

import java.util.List;

import ts.client.Event;

public interface IRequestEventable<T extends Event> {

	List<String> getKeys();

	boolean accept(T body);

	List<T> getEvents();
}


text:
/************************************************************
 * @file         DDWtach.h
 * @author       快刀<kuaidao@mogujie.com>
 * summery       watch实现监听service中tag的变化,通知给观察者s(废弃这块的封装,等到要做Core data的时候再来考虑)
 ************************************************************/

#import <Foundation/Foundation.h>

@protocol WatchHandle <NSObject>

@required
-(void)OnWatchHandle:(uint32)tagID;

@end

@interface DDWatch : NSObject
{
    NSString*                               _notifiName;
    NSMutableArray*                         _observerArray;
    id<WatchHandle>                         _delegate;
}

-(void)addWatch:(id<WatchHandle>)observer selector:(SEL)aSelector;
-(void)uiNotify:(uint32)tagID;

-(id) initWatch:(NSString*)nitifiName;

@end


text:
package org.apache.kafka.clients.admin;

import org.apache.kafka.common.TopicPartitionInfo;
import org.apache.kafka.common.acl.AclOperation;
import org.apache.kafka.common.utils.Utils;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * A detailed description of a single topic in the cluster.
 */
public class TopicDescription {
    private final String name;
    private final boolean internal;
    private final List<TopicPartitionInfo> partitions;
    private final Set<AclOperation> authorizedOperations;

    @Override
    public boolean equals(final Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        final TopicDescription that = (TopicDescription) o;
        return internal == that.internal &&
            Objects.equals(name, that.name) &&
            Objects.equals(partitions, that.partitions) &&
            Objects.equals(authorizedOperations, that.authorizedOperations);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, internal, partitions, authorizedOperations);
    }

    /**
     * Create an instance with the specified parameters.
     *
     * @param name The topic name
     * @param internal Whether the topic is internal to Kafka
     * @param partitions A list of partitions where the index represents the partition id and the element contains
     *                   leadership and replica information for that partition.
     */
    public TopicDescription(String name, boolean internal, List<TopicPartitionInfo> partitions) {
        this(name, internal, partitions, Collections.emptySet());
    }

    /**
     * Create an instance with the specified parameters.
     *
     * @param name The topic name
     * @param internal Whether the topic is internal to Kafka
     * @param partitions A list of partitions where the index represents the partition id and the element contains
     *                   leadership and replica information for that partition.
     * @param authorizedOperations authorized operations for this topic, or null if this is not known.
     */
    public TopicDescription(String name, boolean internal, List<TopicPartitionInfo> partitions,
                            Set<AclOperation> authorizedOperations) {
        this.name = name;
        this.internal = internal;
        this.partitions = partitions;
        this.authorizedOperations = authorizedOperations;
    }

    /**
     * The name of the topic.
     */
    public String name() {
        return name;
    }

    /**
     * Whether the topic is internal to Kafka. An example of an internal topic is the offsets and group management topic:
     * __consumer_offsets.
     */
    public boolean isInternal() {
        return internal;
    }

    /**
     * A list of partitions where the index represents the partition id and the element contains leadership and replica
     * information for that partition.
     */
    public List<TopicPartitionInfo> partitions() {
        return partitions;
    }

    /**
     * authorized operations for this topic, or null if this is not known.
     */
    public Set<AclOperation>  authorizedOperations() {
        return authorizedOperations;
    }

    @Override
    public String toString() {
        return "(name=" + name + ", internal=" + internal + ", partitions=" +
            Utils.join(partitions, ",") + ", authorizedOperations=" + authorizedOperations + ")";
    }
}


text: module.exports = require("npm:turf-point-grid@2.0.0/index");


text:
package org.jetbrains.plugins.groovy.mvc;

import org.jetbrains.plugins.groovy.config.GroovyAwareModuleBuilder;

/**
 * @author peter
 */
public class MvcModuleBuilder extends GroovyAwareModuleBuilder {
  private final MvcFramework myFramework;

  protected MvcModuleBuilder(MvcFramework framework) {
    super(framework.getFrameworkName(), framework.getDisplayName(),
          framework.getDisplayName() + " modules are used for creating <b>" + framework.getDisplayName() + "</b> applications.");
    myFramework = framework;
  }

  @Override
  protected MvcFramework getFramework() {
    return myFramework;
  }
}


text:
package com.alibaba.otter.canal.deployer;

import java.io.FileInputStream;
import java.util.Properties;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.otter.canal.common.utils.AddressUtils;
import com.alibaba.otter.canal.common.utils.NamedThreadFactory;
import com.alibaba.otter.canal.instance.manager.plain.PlainCanal;
import com.alibaba.otter.canal.instance.manager.plain.PlainCanalConfigClient;

/**
 * canal独立版本启动的入口类
 *
 * @author jianghang 2012-11-6 下午05:20:49
 * @version 1.0.0
 */
public class CanalLauncher {

    private static final String             CLASSPATH_URL_PREFIX = "classpath:";
    private static final Logger             logger               = LoggerFactory.getLogger(CanalLauncher.class);
    public static final CountDownLatch      runningLatch         = new CountDownLatch(1);
    private static ScheduledExecutorService executor             = Executors.newScheduledThreadPool(1,
                                                                     new NamedThreadFactory("canal-server-scan"));

    public static void main(String[] args) {
        try {
            logger.info("## set default uncaught exception handler");
            setGlobalUncaughtExceptionHandler();

            // 支持rocketmq client 配置日志路径
            System.setProperty("rocketmq.client.logUseSlf4j","true");

            logger.info("## load canal configurations");
            String conf = System.getProperty("canal.conf", "classpath:canal.properties");
            Properties properties = new Properties();
            if (conf.startsWith(CLASSPATH_URL_PREFIX)) {
                conf = StringUtils.substringAfter(conf, CLASSPATH_URL_PREFIX);
                properties.load(CanalLauncher.class.getClassLoader().getResourceAsStream(conf));
            } else {
                properties.load(new FileInputStream(conf));
            }

            final CanalStarter canalStater = new CanalStarter(properties);
            String managerAddress = CanalController.getProperty(properties, CanalConstants.CANAL_ADMIN_MANAGER);
            if (StringUtils.isNotEmpty(managerAddress)) {
                String user = CanalController.getProperty(properties, CanalConstants.CANAL_ADMIN_USER);
                String passwd = CanalController.getProperty(properties, CanalConstants.CANAL_ADMIN_PASSWD);
                String adminPort = CanalController.getProperty(properties, CanalConstants.CANAL_ADMIN_PORT, "11110");
                boolean autoRegister = BooleanUtils.toBoolean(CanalController.getProperty(properties,
                    CanalConstants.CANAL_ADMIN_AUTO_REGISTER));
                String autoCluster = CanalController.getProperty(properties, CanalConstants.CANAL_ADMIN_AUTO_CLUSTER);
                String name = CanalController.getProperty(properties, CanalConstants.CANAL_ADMIN_REGISTER_NAME);
                if (StringUtils.isEmpty(name)) {
                    name = AddressUtils.getHostName();
                }

                String registerIp = CanalController.getProperty(properties, CanalConstants.CANAL_REGISTER_IP);
                if (StringUtils.isEmpty(registerIp)) {
                    registerIp = AddressUtils.getHostIp();
                }
                final PlainCanalConfigClient configClient = new PlainCanalConfigClient(managerAddress,
                    user,
                    passwd,
                    registerIp,
                    Integer.parseInt(adminPort),
                    autoRegister,
                    autoCluster,
                    name);
                PlainCanal canalConfig = configClient.findServer(null);
                if (canalConfig == null) {
                    throw new IllegalArgumentException("managerAddress:" + managerAddress
                                                       + " can't not found config for [" + registerIp + ":" + adminPort
                                                       + "]");
                }
                Properties managerProperties = canalConfig.getProperties();
                // merge local
                managerProperties.putAll(properties);
                int scanIntervalInSecond = Integer.valueOf(CanalController.getProperty(managerProperties,
                    CanalConstants.CANAL_AUTO_SCAN_INTERVAL,
                    "5"));
                executor.scheduleWithFixedDelay(new Runnable() {

                    private PlainCanal lastCanalConfig;

                    public void run() {
                        try {
                            if (lastCanalConfig == null) {
                                lastCanalConfig = configClient.findServer(null);
                            } else {
                                PlainCanal newCanalConfig = configClient.findServer(lastCanalConfig.getMd5());
                                if (newCanalConfig != null) {
                                    // 远程配置canal.properties修改重新加载整个应用
                                    canalStater.stop();
                                    Properties managerProperties = newCanalConfig.getProperties();
                                    // merge local
                                    managerProperties.putAll(properties);
                                    canalStater.setProperties(managerProperties);
                                    canalStater.start();

                                    lastCanalConfig = newCanalConfig;
                                }
                            }

                        } catch (Throwable e) {
                            logger.error("scan failed", e);
                        }
                    }

                }, 0, scanIntervalInSecond, TimeUnit.SECONDS);
                canalStater.setProperties(managerProperties);
            } else {
                canalStater.setProperties(properties);
            }

            canalStater.start();
            runningLatch.await();
            executor.shutdownNow();
        } catch (Throwable e) {
            logger.error("## Something goes wrong when starting up the canal Server:", e);
        }
    }

    private static void setGlobalUncaughtExceptionHandler() {
        Thread.setDefaultUncaughtExceptionHandler((t, e) -> logger.error("UnCaughtException", e));
    }

}


text:
package com.darksci.pardot.api.request.customfield;

import com.darksci.pardot.api.request.BaseRequest;
import com.darksci.pardot.api.response.customfield.CustomField;

/**
 * For creating new Custom Fields using Pardot's API.
 */
public class CustomFieldCreateRequest extends BaseRequest<CustomFieldCreateRequest> {
    @Override
    public String getApiEndpoint() {
        return "customField/do/create";
    }

    /**
     * Define the campaign you want to create in pardot.
     * @param customField The customField you want to create in pardot.
     * @return CustomFieldCreateRequest builder.
     */
    public CustomFieldCreateRequest withCustomField(final CustomField customField) {
        setParam("name", customField.getName());
        // Api is inconsistent here, type in READ/QUERY is returned as a String,
        // During CREATE it wants the constant integer value.
        setParam("type", customField.getTypeId());
        setParam("field_id", customField.getFieldId());
        setParam("crm_id", customField.getCrmId());
        setBooleanParam("is_record_multiple_responses", customField.isRecordMultipleResponses());
        setBooleanParam("is_use_values", customField.isUseValues());
        return this;
    }

    /**
     * This field is not accessible via READ or QUERY, but is allowed to be set
     * over the CREATE api end point.  Optional to set.
     * @param isRequired should the field be required.
     * @return CustomFieldCreateRequest builder.
     */
    public CustomFieldCreateRequest withFieldIsRequired(final boolean isRequired) {
        return setBooleanParam("is_required", true);
    }

    /**
     * This field is not accessible via READ or QUERY, but is allowed to be set
     * over the CREATE api end point.  Optional to set.
     * @return CustomFieldCreateRequest builder.
     */
    public CustomFieldCreateRequest withFieldIsRequired() {
        return withFieldIsRequired(true);
    }

    /**
     * This field is not accessible via READ or QUERY, but is allowed to be set
     * over the CREATE api end point.  Optional to set.
     * @return CustomFieldCreateRequest builder.
     */
    public CustomFieldCreateRequest withFieldIsNotRequired() {
        return withFieldIsRequired(false);
    }
}


text:
MacKey is an iOS app which can be used to unlock Mac using SSH connection.

## Prerequisites
1. This app will only work when iOS device and Mac are within the same WiFi network.
2. On Mac, `Remote Login` needs to be enabled in `System Preferences` -> `Sharing`.

## Recommended way to lock screen on Mac
1. Open `System Preferences` -> `Security & Privacy`. Check `Require password immediately after sleep or screen saver begins`.
2. Use one of the following methods to turn off the screen.

  A. Close the lid.

  B. Hold down the Command+Option+Eject keys together.

  C. Hold down the Command+Option+Power keys together.

  D. Open `Automator` app. Choose `Application`. Type `Script` in the search box. Double click `Run Shell Script`.
  Replace `cat` with `pmset displaysleepnow`. Use `Command+S` to save the app as an application.
  Then drag the saved applicaiton to Dock. Click on the new application in Dock will make the display sleep.

## Security
1. Host address, user name and password are saved in iOS keychain.
2. Every unlock action is protected by a related touch ID authentication if `Require Touch ID` option is enabled.
3. Communications between this app and Mac are protected by SSH connection using NMSSH framework.
4. It is recommended to delete all the hosts manually before deleting this app.

## [Privacy Policy](https://github.com/happylance/MacKey/blob/master/Privacy-Policy.md)


text:
package org.kannel.protocol.gateway.jms;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;
import javax.jms.*;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class SimpleService implements MessageListener {

  public static final String prop_ContentFile = "simpleService.contentFile";

  private String defaultMessage = "Contenido no encontrado.";
  private Properties properties = null;
  private Properties contenido = null;
  private SimpleQueueReceiverThread sqrThread = null;
  private long stress = 0;
  private long stressTime = 0;

  /*/////////////////////////////////////////////////////
  // JMS Related attributes
  private Context jndiContext = null;
  private TopicConnectionFactory queueConnectionFactory = null;
  private TopicConnection queueConnection = null;
  private TopicSession queueSession = null;
  private Topic inBoundTopic = null;
  private Topic outBoundTopic = null;
  private TopicPublisher outBoundPublisher = null;
  private TopicSubscriber inBoundSubscriber = null;
  private ObjectMessage outOMessage = null;
  private ObjectMessage inOMessage = null;
  /////////////////////////////////////////////////////*/

  /////////////////////////////////////////////////////
  // JMS Related attributes
  private Context jndiContext = null;
  private QueueConnectionFactory queueConnectionFactory = null;
  private QueueConnection queueConnection = null;
  private QueueSession queueSession = null;
  private Queue inBoundTopic = null;
  private Queue outBoundTopic = null;
  private QueueSender outBoundPublisher = null;
  private QueueReceiver inBoundSubscriber = null;
  private ObjectMessage outOMessage = null;
  private ObjectMessage inOMessage = null;
  /////////////////////////////////////////////////////

  public SimpleService(Properties props) throws NamingException, JMSException {
    this.properties = props;

    try {
      this.contenido = new Properties();
      this.contenido.load(
          new FileInputStream(new File(this.properties.getProperty(prop_ContentFile))));

      this.contenido.list(System.out);

    } catch (IOException e) {
      System.out.println("Error cargando contenido...");
      this.contenido = null;
    }

    // Set up all the JMS connection stuff
    if (this.properties != null) {
      jndiContext = new InitialContext(this.properties);
    } else {
      jndiContext = new InitialContext();
    }

    queueConnectionFactory =
        (QueueConnectionFactory)
            jndiContext.lookup(
                this.properties.getProperty(SimpleJMSTransport.prop_ConnectionFactoryName));

    inBoundTopic =
        (Queue)
            jndiContext.lookup(
                this.properties.getProperty(SimpleJMSTransport.prop_OutBoundTopicName));
    outBoundTopic =
        (Queue)
            jndiContext.lookup(
                this.properties.getProperty(SimpleJMSTransport.prop_InBoundTopicName));

    queueConnection = queueConnectionFactory.createQueueConnection();
    // queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
    queueSession = queueConnection.createQueueSession(true, Session.AUTO_ACKNOWLEDGE);

    outBoundPublisher = queueSession.createSender(outBoundTopic);
    inBoundSubscriber = queueSession.createReceiver(inBoundTopic);

    inBoundSubscriber.setMessageListener(this);
    // sqrThread = new SimpleQueueReceiverThread(this, inBoundSubscriber);
    queueConnection.start();
    // sqrThread.start();

  }

  public void start() {

    System.out.println("Para terminar presiona *  ENTER");
    InputStreamReader inputStreamReader = new InputStreamReader(System.in);
    char last = '\0';
    while (!(last == '*')) {
      try {
        last = (char) inputStreamReader.read();
      } catch (IOException e) {
        System.out.println("I/O Error");
      }
    }
  }

  public void onMessage(Message parMessage) {
    System.out.print(".");
    inOMessage = null;
    outOMessage = null;
    SimpleMessage mesg = null;
    String swap = null;
    try {
      if (parMessage instanceof ObjectMessage) {
        inOMessage = (ObjectMessage) parMessage;
        // Mensaje listo para traducir y enviar a Kannel
        mesg = (SimpleMessage) inOMessage.getObject();

        swap = mesg.getMsgData().trim().toUpperCase();
        System.out.println("Contenido recibido: " + swap);
        if (this.contenido != null) {
          swap = this.contenido.getProperty(swap);

          if (swap != null) {
            System.out.println("Enviando contenido: " + swap);
            outOMessage = queueSession.createObjectMessage();
            outOMessage.setObject(
                new SimpleMessage(mesg.getReceiver(), mesg.getSender(), "", swap));
            // System.out.println("llego1");
            outBoundPublisher.send(outOMessage);
            queueSession.commit();
            // System.out.println("llego");
          }
        }

        /*outOMessage = queueSession.createObjectMessage();
        outOMessage.setObject(mesg);
        outBoundPublisher.send(outOMessage);
        stress++;
        if (stress <= 1){
        	stressTime = System.currentTimeMillis();
        }
        if((stress % 1000) == 0){
        	System.out
        		.println("tiempo: " + (System.currentTimeMillis()-stressTime) + " millis.");
        	stress = 0;
        	stressTime = System.currentTimeMillis();
        }*/

      } else {
        System.out.println("Otro tipo de mensaje recibido:");
        System.out.println(parMessage.getClass().getName());
      }

    } catch (JMSException e) {
      System.out.println("JMSException");
    } catch (Throwable tjms) {
      System.out.println("Otra excepcion: " + tjms);
    }
  }

  public static void main(String arg[]) throws Exception {
    System.out.println("Starting SimpleService");
    Properties props = new Properties();
    props.load(
        new FileInputStream(
            new File(
                new String(
                    System.getProperty("user.dir")
                        + System.getProperty("file.separator")
                        + "kjGateway.cfg"))));

    SimpleService serv = new SimpleService(props);
    serv.start();
  }
}


text:
<?php
namespace Blogger\BlogBundle\Service;

use Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface;

class Sha256Salted implements PasswordEncoderInterface
{
    public function encodePassword($raw, $salt)
    {
        return hash('sha256', $salt . $raw); // Custom function for encrypt
    }

    public function isPasswordValid($encoded, $raw, $salt)
    {
        return $encoded === $this->encodePassword($raw, $salt);
    }

    public static function encodePasswordStatic($raw, $salt)
    {
        return hash('sha256', $salt . $raw); // Custom function for encrypt
    }
}


text:
import { Component } from "@angular/core";

@Component({
    selector: "book-app",
    templateUrl: "./app/components/app/app.component.html"
})
export class AppComponent { }


text:
using namespace thewizardplusplus::wizard_basic_2::compiler::translator;
using namespace thewizardplusplus::wizard_basic_2::compiler::translator::
	exceptions;
using namespace boost;

ArrayAccessExpression::ArrayAccessExpression(const Variable::Pointer& variable,
	const Expression::Pointer& index_expression)
:
	Expression(ValueType::NUMBER),
	variable(variable),
	index_expression(index_expression)
{
	ValueType::Types variable_type = ValueType::UNKNOWN_TYPE;
	if (typeid(*variable) == typeid(NumberVariable)) {
		variable_type = ValueType::NUMBER;
	} else if (typeid(*variable) == typeid(ArrayVariable) || typeid(*variable)
		== typeid(StringVariable))
	{
		variable_type = ValueType::ARRAY;
	}

	if (variable_type != ValueType::ARRAY || index_expression->getType() !=
		ValueType::NUMBER)
	{
		throw IllegalArrayAccessOperationException(variable_type,
			index_expression->getType());
	}
}

std::string ArrayAccessExpression::getCppCode(void) const {
	return (format("%1%[%2%]") % variable->getName() % index_expression->
		getCppCode()).str();
}


text:
using System;
using System.Text;

namespace Elmah.AzureTableStorage
{
    /// <summary>
    ///     Includes methods to encode or decode values for Azure key fields.
    /// </summary>
    /// <remarks>
    ///     Original source - http://msdn.microsoft.com/en-us/library/ff803362.aspx
    ///
    ///     Azure places some restrictions on the characters that you can use in partition and row keys.
    ///
    ///     The following information is copied from: http://msdn.microsoft.com/en-us/library/dd179338.aspx
    ///
    ///     The following characters are not allowed in values for the PartitionKey and RowKey properties:
    ///
    ///     The forward slash (/) character
    ///     The backslash (\) character
    ///     The number sign (#) character
    ///     The question mark (?) character
    ///     Control characters from U+0000 to U+001F, including:
    ///     The horizontal tab (\t) character
    ///     The linefeed (\n) character
    ///     The carriage return (\r) character
    ///     Control characters from U+007F to U+009F
    /// </remarks>
    internal class AzureHelper
    {
        internal static string EncodeAzureKey(string key)
        {
            return string.IsNullOrEmpty(key) ? null : Convert.ToBase64String(Encoding.UTF8.GetBytes(key)).Replace("/", "_");
        }

        internal static string DecodeAzureKey(string encodedKey)
        {
            return string.IsNullOrEmpty(encodedKey) ? null : Encoding.UTF8.GetString(Convert.FromBase64String(encodedKey)).Replace("_", "/");
        }
    }
}


text:
/* LCM type definition class file
 * This file was automatically generated by lcm-gen
 * DO NOT MODIFY BY HAND!!!!
 */

using System;
using System.Collections.Generic;
using System.IO;
using LCM.LCM;

namespace forseti2
{
    public sealed class piemos_override : LCM.LCM.LCMEncodable
    {
        public forseti2.header header;
        public int team;
        public bool override;

        public piemos_override()
        {
        }

        public static readonly ulong LCM_FINGERPRINT;
        public static readonly ulong LCM_FINGERPRINT_BASE = 0x05ced4af13b32459L;

        static piemos_override()
        {
            LCM_FINGERPRINT = _hashRecursive(new List<String>());
        }

        public static ulong _hashRecursive(List<String> classes)
        {
            if (classes.Contains("forseti2.piemos_override"))
                return 0L;

            classes.Add("forseti2.piemos_override");
            ulong hash = LCM_FINGERPRINT_BASE
                 + forseti2.header._hashRecursive(classes)
                ;
            classes.RemoveAt(classes.Count - 1);
            return (hash<<1) + ((hash>>63)&1);
        }

        public void Encode(LCMDataOutputStream outs)
        {
            outs.Write((long) LCM_FINGERPRINT);
            _encodeRecursive(outs);
        }

        public void _encodeRecursive(LCMDataOutputStream outs)
        {
            this.header._encodeRecursive(outs);

            outs.Write(this.team);

            outs.Write(this.override);

        }

        public piemos_override(byte[] data) : this(new LCMDataInputStream(data))
        {
        }

        public piemos_override(LCMDataInputStream ins)
        {
            if ((ulong) ins.ReadInt64() != LCM_FINGERPRINT)
                throw new System.IO.IOException("LCM Decode error: bad fingerprint");

            _decodeRecursive(ins);
        }

        public static forseti2.piemos_override _decodeRecursiveFactory(LCMDataInputStream ins)
        {
            forseti2.piemos_override o = new forseti2.piemos_override();
            o._decodeRecursive(ins);
            return o;
        }

        public void _decodeRecursive(LCMDataInputStream ins)
        {
            this.header = forseti2.header._decodeRecursiveFactory(ins);

            this.team = ins.ReadInt32();

            this.override = ins.ReadBoolean();

        }

        public forseti2.piemos_override Copy()
        {
            forseti2.piemos_override outobj = new forseti2.piemos_override();
            outobj.header = this.header.Copy();

            outobj.team = this.team;

            outobj.override = this.override;

            return outobj;
        }
    }
}


text:
'use strict'

import React from 'react'
import {connect} from 'react-redux'
import { pushPath } from 'redux-simple-router'
import {reduxForm} from 'redux-form'
import _ from 'lodash'
import RadioGroup from 'react-radio-group'
import CheckboxGroup from 'react-checkbox-group'

import {getSettings, upsertSettings} from '../../../modules/settings/actions/index'

const fields = [
  'requireNumeric', 'requireLowercase', 'requireUppercase',
  'google', 'twitter', 'github', 'publicRegister', 'concordaPublicRegister',
  'emailTemplateFolder'
]

export let Settings = React.createClass({
  propTypes: {
    fields: React.PropTypes.object.isRequired,
    handleSubmit: React.PropTypes.func.isRequired
  },

  componentDidMount () {
    const {route, dispatch} = this.props
    dispatch(getSettings())
  },

  getInitialState () {
    return {
    }
  },

  componentWillReceiveProps: function (nextProps) {
    if (nextProps.settings) {
      this.setState({
        google: this.state.google || nextProps.settings.authType ? nextProps.settings.authType.google : "0",
        github: this.state.github || nextProps.settings.authType ? nextProps.settings.authType.github : "0",
        twitter: this.state.twitter || nextProps.settings.authType ? nextProps.settings.authType.twitter : "0",

        publicRegister: this.state.publicRegister || nextProps.settings.publicRegister || "0",
        concordaPublicRegister: this.state.concordaPublicRegister || nextProps.settings.concordaPublicRegister || "0",

        emailTemplateFolder: this.state.emailTemplateFolder || nextProps.settings.emailTemplateFolder,

        //user policy
        activateAccount: this.state.activateAccount || nextProps.settings.userPolicy ? nextProps.settings.userPolicy.activateAccount : "0",
        forceChangePassword: this.state.forceChangePassword || nextProps.settings.userPolicy ? nextProps.settings.userPolicy.forceChangePassword : "0",
        maximumSessionNumber: this.state.maximumSessionNumber || nextProps.settings.userPolicy ? nextProps.settings.userPolicy.maximumSessionNumber : "0",
        //password policy
        requireLowercase: this.state.requireLowerCase || nextProps.settings.passwordPolicy ? nextProps.settings.passwordPolicy.requireLowercase : "0",
        requireUppercase: this.state.requireUpperCase || nextProps.settings.passwordPolicy ? nextProps.settings.passwordPolicy.requireUppercase : "0",
        requireNumeric: this.requireNumeric || nextProps.settings.passwordPolicy ? nextProps.settings.passwordPolicy.requireNumeric : "0",
        minLength: this.state.minLength || nextProps.settings.passwordPolicy ? nextProps.settings.passwordPolicy.minLength : 6,

        forceResetPasswordAfterFailedCount: this.state.forceResetPasswordAfterFailedCount || nextProps.settings.passwordPolicy ? nextProps.settings.passwordPolicy.forceResetPasswordAfterFailedCount : "0",
        forceChangePasswordAfterInterval: this.state.forceChangePasswordAfterInterval || nextProps.settings.passwordPolicy ? nextProps.settings.passwordPolicy.forceChangePasswordAfterInterval : "0"
      })
    }
  },

  handleSubmit (data) {
    const {dispatch} = this.props

    let settings = {
      authType: {
        google: this.state.google || "0",
        github: this.state.github || "0",
        twitter: this.state.twitter || "0"
      },
      concordaPublicRegister: this.state.concordaPublicRegister || "0",
      publicRegister: this.state.publicRegister || "0",
      emailTemplateFolder: data.emailTemplateFolder,
      passwordPolicy: {
        requireLowercase: this.state.requireLowercase || "0",
        requireNumeric: this.state.requireNumeric || "0",
        requireUppercase: this.state.requireUppercase || "0",
        forceResetPasswordAfterFailedCount: this.state.forceResetPasswordAfterFailedCount || "0",
        forceChangePasswordAfterInterval: this.state.forceChangePasswordAfterInterval || "0",
        minLength: this.state.minLength || 6
      },
      userPolicy: {
        activateAccount: this.state.activateAccount || "0",
        forceChangePassword: this.state.forceChangePassword || "0",
        maximumSessionNumber: this.state.maximumSessionNumber || "0"
      }
    }

    dispatch(upsertSettings(settings))
  },

  handleRequireLowercaseChange (value) {
    this.setState({requireLowercase: value})
  },

  handleRequireUppercaseChange (value) {
    this.setState({requireUppercase: value})
  },

  handleRequireNumericChange (value) {
    this.setState({requireNumeric: value})
  },

  handleRegisterTypeChange (value) {
    this.setState({publicRegister: value})
  },

  handleConcordaRegisterTypeChange (value) {
    this.setState({concordaPublicRegister: value})
  },

  handleGoogleChange (value) {
    this.setState({google: value})
  },

  handleTwitterChange (value) {
    this.setState({twitter: value})
  },

  handleActivateAccount (value) {
    this.setState({activateAccount: value})
  },

  handleForceChangePassword (value) {
    this.setState({forceChangePassword: value})
  },

  handleGithubChange (value) {
    this.setState({github: value})
  },

  updateMinLength (event) {
    this.setState({ minLength: event.target.value })
  },

  updateForceResetPasswordAfterFailedCount (event) {
    this.setState({ forceResetPasswordAfterFailedCount: event.target.value })
  },

  updateMaximumSessionNumber (event) {
    this.setState({ maximumSessionNumber: event.target.value })
  },

updateForceChangePasswordAfterInterval (event) {
    this.setState({ forceChangePasswordAfterInterval: event.target.value })
  },

  render () {
    const {
      fields: {emailTemplateFolder},
      settings,
      handleSubmit } = this.props

    return (

Settings

        {(() => {
          if (settings) {

            return (
              <form className="login-form col-xs-8 txt-left form-full-width form-panel"
                    onSubmit={handleSubmit(this.handleSubmit)}>

                    Authentication

                        Concorda public user registration:

                        <RadioGroup name="concordaPublicRegister" selectedValue={this.state.concordaPublicRegister}
                                    onChange={this.handleConcordaRegisterTypeChange}>
                          {Radio => (

                              <Radio value="1"/>Yes
                              <Radio value="0"/>No

                          )}
                        </RadioGroup>

                        Public user registration:

                        <RadioGroup name="publicRegister" selectedValue={this.state.publicRegister}
                                    onChange={this.handleRegisterTypeChange}>
                          {Radio => (

                              <Radio value="1"/>Yes
                              <Radio value="0"/>No

                          )}
                        </RadioGroup>

                        Google authentication:

                        <RadioGroup name="google" selectedValue={this.state.google || "0"}
                                    onChange={this.handleGoogleChange}>
                          {Radio => (

                              <Radio value="1"/>Yes
                              <Radio value="0"/>No

                          )}
                        </RadioGroup>

                        Github authentication:

                        <RadioGroup name="github" selectedValue={this.state.github || "0"}
                                    onChange={this.handleGithubChange}>
                          {Radio => (

                              <Radio value="1"/>Yes
                              <Radio value="0"/>No

                          )}
                        </RadioGroup>

                        Twitter authentication:

                        <RadioGroup name="twitter" selectedValue={this.state.twitter || "0"}
                                    onChange={this.handleTwitterChange}>
                          {Radio => (

                              <Radio value="1"/>Yes
                              <Radio value="0"/>No

                          )}
                        </RadioGroup>

                    Password Policy

                        Password require lowercase character:

                        <RadioGroup name="requireLowercase"
                                    selectedValue={this.state.requireLowercase || "1"}
                                    onChange={this.handleRequireLowercaseChange}>
                          {Radio => (

                              <Radio value="1"/>Yes
                              <Radio value="0"/>No

                          )}
                        </RadioGroup>

                        Password require uppercase character:

                        <RadioGroup name="requireUppercase"
                                    selectedValue={this.state.requireUppercase || "0"}
                                    onChange={this.handleRequireUppercaseChange}>
                          {Radio => (

                              <Radio value="1"/>Yes
                              <Radio value="0"/>No

                          )}
                        </RadioGroup>

                        Password require numeric:

                        <RadioGroup name="requireNumeric"
                                    selectedValue={this.state.requireNumeric || "0"}
                                    onChange={this.handleRequireNumericChange}>
                          {Radio => (

                              <Radio value="1"/>Yes
                              <Radio value="0"/>No

                          )}
                        </RadioGroup>

                        Password minimum length:

                        <input defaultValue={this.state.minLength} placeholder="Password minimum length" onChange={this.updateMinLength} className="input-large"/>

                        characters

                        Force password reset after

                        <input defaultValue={this.state.forceResetPasswordAfterFailedCount} placeholder="# failures" onChange={this.updateForceResetPasswordAfterFailedCount} className="input-large"/>

                        failed logins (0 to disable)

                        Force password reset after

                        <input defaultValue={this.state.forceChangePasswordAfterInterval} placeholder="# days" onChange={this.updateForceChangePasswordAfterInterval} className="input-large"/>

                        number of days (0 to disable)

                    User Policy

                        Maximum allowed active user sessions

                        <input defaultValue={this.state.maximumSessionNumber} placeholder="# active sessions" onChange={this.updateMaximumSessionNumber} className="input-large"/>

                        (0 for unlimited)

                        User should activate account by email:

                        <RadioGroup name="activateAccount"
                                    selectedValue={this.state.activateAccount || "0"}
                                    onChange={this.handleActivateAccount}>
                          {Radio => (

                              <Radio value="1"/>Yes
                              <Radio value="0"/>No

                          )}
                        </RadioGroup>

                        Force user to change password on first login:

                        <RadioGroup name="forceChangePassword"
                                    selectedValue={this.state.forceChangePassword || "0"}
                                    onChange={this.handleForceChangePassword}>
                          {Radio => (

                              <Radio value="1"/>Yes
                              <Radio value="0"/>No

                          )}
                        </RadioGroup>

                    Other

                        Email templates folder:

                        <input placeholder="Email template folder" className="input-large" {...emailTemplateFolder}/>

                    <button type="submit" className="btn btn-large submit">Submit</button>

              </form>
            )
          }
        })()}

    )
  }
})

Settings = reduxForm(
  {
    form: 'settings',
    fields: fields
  },
  state => ({
    initialValues: state.settings.data ? state.settings.data : null
  }))(Settings)

export default connect((state) => {
  return {
    settings: state.settings.data ? state.settings.data : null
  }
})(Settings)


text:
package main

import (
	"flag"
	"fmt"

	env "istio.io/istio/tests/integration_old/example/environment/mixerEnvoyEnv"
	"istio.io/istio/tests/integration_old/framework"
)

func main() {
	flag.Parse()

	testEM := framework.NewTestEnvManager(env.NewMixerEnvoyEnv(""), "")
	if err := testEM.StartUp(); err != nil {
		fmt.Printf("Failed to start the environment: %s\n", err)
	} else {
		fmt.Println("Environment is running")
		for {
			var input string
			fmt.Println("Entry 'exit' to stop the environment, don't use 'ctrl+C'")
			fmt.Scanln(&input)
			if input == "exit" {
				break
			}
		}
	}

	testEM.TearDown()
}


text:
using namespace plugin;

BOOL APIENTRY DllMain(HMODULE hModule,
	DWORD  ul_reason_for_call,
	LPVOID lpReserved
)
{
	if (ul_reason_for_call == DLL_PROCESS_ATTACH)
	{
		Events::initRwEvent += gtasajs::Init;
		Events::initGameEvent += gtasajs::Start;
		Events::reInitGameEvent += gtasajs::Restart;
		Events::gameProcessEvent += gtasajs::Main;
		Events::shutdownRwEvent += gtasajs::Close;
	}
	return TRUE;
}


text:
from django.db import models
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _

import uuid
import os

from sorl.thumbnail import ImageField
from tinymce import models as tinymce_models

try:
    from PIL import Image, ImageOps
except ImportError:
    import Image
    import ImageOps

STATE_CHOICES = (
    ('AC', u'Acre'),
    ('AL', u'Alagoas'),
    ('AP', u'Amapá'),
    ('AM', u'Amazonas'),
    ('BA', u'Bahia'),
    ('CE', u'Ceará'),
    ('DF', u'Distrito Federal'),
    ('ES', u'Espírito Santo'),
    ('GO', u'Goiás'),
    ('MA', u'Maranhão'),
    ('MT', u'Mato Grosso'),
    ('MS', u'Mato Grosso do Sul'),
    ('MG', u'Minas Gerais'),
    ('PA', u'Pará'),
    ('PB', u'Paraíba'),
    ('PR', u'Paraná'),
    ('PE', u'Pernambuco'),
    ('PI', u'Piauí'),
    ('RJ', u'Rio de Janeiro'),
    ('RN', u'Rio Grande do Norte'),
    ('RS', u'Rio Grande do Sul'),
    ('RO', u'Rondônia'),
    ('RR', u'Roraima'),
    ('SC', u'Santa Catarina'),
    ('SP', u'São Paulo'),
    ('SE', u'Sergipe'),
    ('TO', u'Tocantins'),
)

BANNER_CHOICES = (
    (1, _(u'Super Banner (Home)')),
    (2, _(u'Banner Secundário (Home)')),
    (3, _(u'Popup Banner')),
)

AREA_CHOICES = (
    (1, _(u'Prefeitura')),
    (2, _(u'Imprensa')),
    (3, _(u'Secretarias')),
    # (3, _(u'Transparência')),
)

class Social(models.Model):
    name = models.CharField(_(u'Nome'), max_length=50,
                            help_text='Ex: Facebook')
    link = models.URLField(_(u'Link'),
                           help_text='Ex: http://www.facebook.com/usuario')

    def __unicode__(self):
        return unicode(self.name)

    class Meta:
        verbose_name = _(u'Mídia Social')
        verbose_name_plural = _(u'Mídias Sociais')
        ordering = ['name']

class Enterprise(models.Model):
    name = models.CharField(_(u'Nome'), max_length=100)
    description = models.CharField(_(u'Descrição'), max_length=100,
                                   blank=True, null=True)
    cnpj = models.CharField(_(u'CNPJ'), max_length=20,
                            help_text='99.999.999/9999-99')
    address = models.CharField(_(u'Endereço'), max_length=200)
    number = models.CharField(_(u'Número'), max_length=10)
    complement = models.CharField(_(u'Complemento'), max_length=100,
                                  blank=True, null=True)
    cep = models.CharField(_(u'CEP'), max_length=9, help_text='99999-999',
                           blank=True, null=True)
    district = models.CharField(_(u'Bairro'), max_length=100)
    city = models.CharField(_(u'Cidade'), max_length=100)
    state = models.CharField(_(u'UF'), max_length=2, choices=STATE_CHOICES)
    country = models.CharField(_(u'País'), max_length=50)
    phone1 = models.CharField(_(u'Fone 1'), max_length=20,
                              help_text='(99) 9999-9999')
    phone2 = models.CharField(_(u'Fone 2'), max_length=20,
                              help_text='(99) 9999-9999', blank=True,
                              null=True)
    phone3 = models.CharField(_(u'Fone 3 (Fax)'), max_length=20,
                              help_text='(99) 9999-9999', blank=True,
                              null=True)
    email = models.EmailField(_(u'Email'))
    site = models.URLField(_(u'Site'))
    socials = models.ManyToManyField('Social',
                                     verbose_name=_(u'Mídias Sociais'))

    def __unicode__(self):
        return unicode(self.name)

    class Meta:
        verbose_name = _(u'Empresa')
        verbose_name_plural = _(u'Empresa')

class Category(models.Model):
    area = models.IntegerField(_(u'Área'), choices=AREA_CHOICES, default=1)
    name = models.CharField(_(u'Nome da Categoria'), max_length=200)
    slug = models.SlugField(_(u'Link no Site'), max_length=200,
                            unique=True)
    acronym = models.CharField(_(u'Sigla'), max_length=50, blank=True,
                               null=True)
    order = models.IntegerField(_(u'Ordem do Menu'), default=0,
                                help_text='Caso o valor seja zero o menu \
                                ficará em ordem alfabética.')

    # def save(self, *args, **kwargs):
    #     self.slug = slugify(self.name)
    #     super(Category, self).save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse('blog:category_list', kwargs={'pk': self.pk})

    def get_absolute_url_prefeitura(self):
        return reverse('prefeitura', kwargs={'slug': self.slug})

    def get_absolute_url_imprensa(self):
        return reverse('imprensa', kwargs={'slug': self.slug})

    def get_absolute_url_secretaria(self):
        return reverse('secretaria', kwargs={'slug': self.slug})

    # def get_absolute_url_transparencia(self):
    #     return reverse('transparencia', kwargs={'slug': self.slug})

    def save(self, *args, **kwargs):
        super(Category, self).save(*args, **kwargs)
        c = Content.objects.filter(category=self.pk)
        if not c:
            Content.objects.get_or_create(
                category_id=self.pk, body='Aguardando conteúdo...')

    def __unicode__(self):
        return unicode(self.name)

    class Meta:
        verbose_name = _(u'Categoria')
        verbose_name_plural = _(u'Categorias')
        ordering = ['order', 'name']

class Content(models.Model):
    category = models.ForeignKey('Category', verbose_name=_(u'Página'),
                                 default=1, unique=True)
    body = tinymce_models.HTMLField(_(u'Conteúdo da Página'))

    def admin_body(self):
        if self.body:
            return self.body[:150]
    admin_body.allow_tags = True
    admin_body.short_description = 'Conteúdo da Página'

    def __unicode__(self):
        return unicode(self.pk)

    class Meta:
        verbose_name = _(u'Página')
        verbose_name_plural = _(u'Páginas')
        ordering = ['category']

class Link(models.Model):
    name = models.CharField(_(u'Nome'), max_length=100)
    link = models.URLField(_(u'Link do Site'))
    image = ImageField(_(u'Logo'), upload_to='link')

    def admin_image(self):
        return '' % self.image.url
    admin_image.allow_tags = True
    admin_image.short_description = 'Logo do Link'

    def save(self, *args, **kwargs):
        if not self.id and not self.image:
            return

        super(Link, self).save(*args, **kwargs)

        image = Image.open(self.image)

        def scale_dimensions(width, height, longest_side):
            if width > height:
                if width > longest_side:
                    ratio = longest_side*1./width
                    return (int(width*ratio), int(height*ratio))
                elif height > longest_side:
                    ratio = longest_side*1./height
                    return (int(width*ratio), int(height*ratio))
            return (width, height)

        (width, height) = image.size
        (width, height) = scale_dimensions(width, height, longest_side=120)

        size = (width, height)
        """ redimensiona esticando """
        # image = image.resize(size, Image.ANTIALIAS)
        """ redimensiona proporcionalmente """
        image.thumbnail(size, Image.ANTIALIAS)
        """ redimensiona cortando para encaixar no tamanho """
        # image = ImageOps.fit(image, size, Image.ANTIALIAS)
        image.save(self.image.path, 'JPEG', quality=99)

    def __unicode__(self):
        return unicode(self.name)

    class Meta:
        verbose_name = _(u'Link Útil')
        verbose_name_plural = _(u'Links Úteis')
        ordering = ['name']

class Program(models.Model):
    name = models.CharField(_(u'Nome'), max_length=100)
    link = models.URLField(_(u'Link do Site'))
    image = ImageField(_(u'Logo'), upload_to='program',
                       help_text=_(u'O nome do arquivo não pode conter \
                                   espaços em branco e/ou acentuação.'))

    def admin_image(self):
        return '' % self.image.url
    admin_image.allow_tags = True
    admin_image.short_description = 'Logo do Programa'

    def save(self, *args, **kwargs):
        if not self.id and not self.image:
            return

        super(Program, self).save(*args, **kwargs)

        image = Image.open(self.image)

        def scale_dimensions(width, height, longest_side):
            if width > height:
                if width > longest_side:
                    ratio = longest_side*1./width
                    return (int(width*ratio), int(height*ratio))
                elif height > longest_side:
                    ratio = longest_side*1./height
                    return (int(width*ratio), int(height*ratio))
            return (width, height)

        (width, height) = image.size
        (width, height) = scale_dimensions(width, height, longest_side=120)

        size = (width, height)
        """ redimensiona esticando """
        # image = image.resize(size, Image.ANTIALIAS)
        """ redimensiona proporcionalmente """
        image.thumbnail(size, Image.ANTIALIAS)
        """ redimensiona cortando para encaixar no tamanho """
        # image = ImageOps.fit(image, size, Image.ANTIALIAS)
        image.save(self.image.path, 'JPEG', quality=99)

    def __unicode__(self):
        return unicode(self.name)

    class Meta:
        verbose_name = _(u'Programa')
        verbose_name_plural = _(u'Programas')
        ordering = ['name']

class BannerManager(models.Manager):
    def get_queryset(self):
        return super(BannerManager,
                     self).get_queryset().all()

class BannerPublishedManager(models.Manager):
    def get_queryset(self):
        return super(BannerPublishedManager,
                     self).get_queryset().filter(publish=True)

class Banner(models.Model):
    def get_file_path(instance, filename):
        ext = filename.split('.')[-1]
        filename = "%s.%s" % (uuid.uuid4(), ext)
        return os.path.join('banner', filename)

    type = models.IntegerField(_(u'Banner'), choices=BANNER_CHOICES, default=1)
    image = ImageField(_(u'Banner'), upload_to=get_file_path)
    title = models.CharField(_(u'Título do banner'), max_length=100)
    link = models.URLField(_(u'Link do banner'), blank=True, null=True)
    publish = models.BooleanField(_(u'Visível no site?'), default=True)

    objects = BannerManager()
    published = BannerPublishedManager()

    def admin_image(self):
        return '' % self.image.url
    admin_image.allow_tags = True
    admin_image.short_description = 'Imagem'

    def save(self, *args, **kwargs):
        if not self.id and not self.image:
            return

        super(Banner, self).save(*args, **kwargs)

        image = Image.open(self.image)

        def scale_dimensions(width, height, longest_side):
            if width > height:
                if width > longest_side:
                    ratio = longest_side*1./width
                    return (int(width*ratio), int(height*ratio))
                elif height > longest_side:
                    ratio = longest_side*1./height
                    return (int(width*ratio), int(height*ratio))
            return (width, height)

        if self.type == 2:
            side = 520
        else:
            side = 940

        (width, height) = image.size
        (width, height) = scale_dimensions(width, height, longest_side=side)

        size = (width, height)
        """ redimensiona esticando """
        # image = image.resize(size, Image.ANTIALIAS)
        """ redimensiona proporcionalmente """
        image.thumbnail(size, Image.ANTIALIAS)
        """ redimensiona cortando para encaixar no tamanho """
        # image = ImageOps.fit(image, size, Image.ANTIALIAS)
        image.save(self.image.path, 'JPEG', quality=99)

    def __unicode__(self):
        return unicode(self.title)

    class Meta:
        verbose_name = _(u'Banner')
        verbose_name_plural = _(u'Banners')

class Timeline(models.Model):
    def get_file_path(instance, filename):
        ext = filename.split('.')[-1]
        filename = "%s.%s" % (uuid.uuid4(), ext)
        return os.path.join('timeline', filename)

    title = models.CharField(_(u'Título'), max_length=50)
    description = models.TextField(_(u'Descrição'),
                                   help_text='Uma breve história')
    image = ImageField(_(u'Imagem'), upload_to=get_file_path,
                       blank=True, null=True)
    period = models.CharField(_(u'Ano'), max_length=4, unique=True)

    def admin_image(self):
        if self.image:
            return '' % self.image.url
        else:
            return 'Sem imagem'
    admin_image.allow_tags = True
    admin_image.short_description = 'Imagem'

    def save(self, *args, **kwargs):
        if not self.id and not self.image:
            return

        super(Timeline, self).save(*args, **kwargs)

        image = Image.open(self.image)

        def scale_dimensions(width, height, longest_side):
            if width > height:
                if width > longest_side:
                    ratio = longest_side*1./width
                    return (int(width*ratio), int(height*ratio))
                elif height > longest_side:
                    ratio = longest_side*1./height
                    return (int(width*ratio), int(height*ratio))
            return (width, height)

        side = 800

        (width, height) = image.size
        (width, height) = scale_dimensions(width, height, longest_side=side)

        size = (width, height)
        """ redimensiona esticando """
        # image = image.resize(size, Image.ANTIALIAS)
        """ redimensiona proporcionalmente """
        image.thumbnail(size, Image.ANTIALIAS)
        """ redimensiona cortando para encaixar no tamanho """
        # image = ImageOps.fit(image, size, Image.ANTIALIAS)
        image.save(self.image.path, 'JPEG', quality=99)

    def __unicode__(self):
        return "%s (%s)" % (unicode(self.title), self.period)

    class Meta:
        verbose_name = _(u'Linha do Tempo')
        verbose_name_plural = _(u'Linha do Tempo')
        ordering = ['-period']