text:
These WhizzML scripts will let the user run a **fully automated
Machine Learning pipeline** in BigML.

![BigML AutoML Steps](../res/steps.png)

From a train, holdout and test datasets, the following tasks will
be automatically done:

-  `Unsupervised Models Generation`: Creating the following
  **unsupervised models**: `Cluster`, `Anomaly Detector`, `Association
  Discovery` (with leverage and lift as search_strategy), `PCA` and
  `Topic Model` (for datasets that contain text fields).
-  `Feature Generation`: Using the unsupervised models created
  previously to append automatically generated new features to all the
  user given datasets.
- `Feature Selection`: Reducing, automatically, the number of fields
  of the datasets using the **Recursive Feature Eliminination**
  algorithm. This step is bypassed if the total number of fields is
  lower than 50 (or 30 if `shallow_search` is `True`)
-  `Model Selection` Using OptiML to find the best models and using
  the top 3 models to create a `Fusion` model to predict all the test
  dataset instances.
- `Fusion Evaluation`: Evaluating the Fusion using the data in the
   holdout dataset.
- `Fusion Prediction`: Scoring the input data provided
   in the test dataset (if set) using the final Fusion model.

The **inputs** for the script are:

* `train-dataset`: (dataset-id) Dataset ID from the train dataset
  (e.g. dataset/5d272205eba31d61920005cd). If no train dataset is
  provided, the script will expect an `automl-execution` and will use
  its models as starting point. Useful when we only want to perform
  scoring , using  a previous execution of AutoML.
* `holdout-dataset`: (dataset-id) Dataset ID from the holdout dataset
  (e.g. dataset/5d272205ea31d61920005cd). It will be used **only at
  the end of the workflow**, after the resulting Fusion model has been
  created, to evaluate it. If empty, some random rows from the
  `train-dataset` will be set aside and used as `holdout-dataset`. The
  parameter `holdout-rate` indicates the portion of the
  `train-dataset` that is sampled in the `holdout-dataset`
* `test-dataset`: (dataset-id) Dataset ID from the test dataset
  (e.g. dataset/7j272205eba31d61920005vf). AutoML will create a batch
  prediction with this dataset at the end of the workflow. It won't be
  used during previouse stages. If empty, no output-dataset
  is returned.
* `automl-exection`: (execution-id) Previous execution of this script, to
  reuse created executions and models,
  e.g. execution/5d272205eba31d61920005cd. Either `train-dataset` or
  `automl-execution` should be provided for the script to work. When
  both are provided, the `automl-execution` argument is discarded and
  new resources are generated from the training data.
* `shallow-search`: (boolean) If true, AutoML will perform a more
  shallow (but faster) search of the best features and models. A
  ramdomly sampled dataset will be used in some stages of the process,
  only one association discovery will be created (with lift metric),
  the objective number of features to obtain from the feature
  selection process will be fixed to 30 and the maximum training time
  of the OptiML will be more limited. Default value is `True`.
* `configuration-params`: (map) Execution configuration
  parameters. They will be overwritten if automl-execution is
  given. The following values must be provided:
  * `excluded-fields`: (list) List of fields that will be excluded
    from any dataset before any other process starts. e.g. ["bmi",
    "age"]. Empty by default.
  * `excluded-models`: (list) List of unsupervised models that won't
    be created nor reused during feature generation. e.g. ["anomaly",
    "cluster"]. Possible values are: association, cluster, anomaly, pca
    or topicmodel. Empty by default
  * `pca-variance-threshold`: (number) The PCA projection uses the
    minimum number of components such that the cumulative explained
    variance is greater than the given threshold. Values from 0 to 1. A
    value of 1 means all the components will be used. Default value is
    0.8.
  * `max-association-rules`: (integer) Maximum number of association
    rules that should be included in the extended datasets for each
    association discovery created. Default value is 10. Please, note
    that the final number of association rules in the extended
    datasets can be higher than this value if more than one
    association discovery is created.
  * `holdout-rate`: (number) The portion of the `train-dataset`
    that is sampled in the `holdout-dataset`. Values from 0 to 0.5.
    This is used only if a `holdout-dataset` is not provided by the
    user. If `holdout-rate` is 0, the `holdout-dataset` won't be
    created. 0.2 by default (20% of the rows).
  * `balance-objective`: (boolean) Whether to balance classes
    proportionally to their category counts or not (during the
    creation of models). False by default.
  * `models-configuration`:  (map) Configuration parameters for the models
    created by AutoML. They won't be used if `automl-execution` is
    given. The following keys are accepted: `cluster`, `anomaly`,
    `association`, `pca`, `topicmodel`, `optiml`.
    E.g. `{"cluster": {"critical_value": 4},
           "anomaly": {"forest_size": 256},
           "optiml": {"number_of_model_candidates": 64}}`

**WARNING** To avoid confusion, `configuration-params` are always
overwritten by the corresponding input in `automl-execution` if this
is given.

**WARNING** All the fields that appear as `non-preferred` in train,
holdout or test datasets will be considered `non-preferred` in all
the resources created by AutoML. It doesn't matter in which dataset
(train, holdout or test) they are set as non-preferred fields.

**WARNING** The AutoML script creates partial models and evaluations
both in the RFE and the OptiML selection processes. Those models and
evaluations are using samples of the training data and independent
validation datasets (extracted from the training data as totally
complementary splits to avoid leakage between the Feature Selection
and Model Selection steps). Therefore, only the final evaluation of
the Fusion model on the holdout data can be used as an estimate for
its performance.

The **outputs** for the script are:
* `output-dataset`: (dataset-id) Dataset with final predictions for the test dataset
* `output-evaluation`: (evaluation-id) Evaluation of the `Fusion`
  model using the `holdout-dataset`
* `output-fusion`: (fusion-id) Output fusion model
* `selected-fields`: (list) Selected important field names
* `unsupervised-models`: (list) List of unsupervised models created
  from train-dataset

## Usage
There are two different ways of using this script:

### From a train and a test dataset (and an optional holdout dataset)
In this case, the expected inputs for the script are the
`train-dataset` and the `test-dataset`, with no `automl-execution`
input.  The objective field used in the script will be the one
associated to the datasets used, so remember to choose them previously
in the training dataset (and holdout dataset when used).

The script will run the fully **automated Machine Learning pipeline**
and it will return, at the end of the process, the **output-dataset**
with the final predictions for the test dataset using a `Fusion` with
the best models from the created `OptiML`.

If a holdout dataset is given, the script will also return an
`evaluation` of the final `Fusion` model with the
`holdout-dataset`. If no `holdout-dataset` is given, but
`holdout-rate` is greater than 0, a subset of the original
`train-dataset` not used in any part of the process will be used to
generate this final `evaluation`.

### From a test dataset and a previous execution id (and an optional holdout dataset)
If we want to predict new data using the same models created by a
previously executed `automl` script, you can use the `automl-execution`
parameter (no `train-dataset` parameter needed) associated to that
previous execution and provide the test dataset ID in the
`test-dataset` parameter.

In this case, some steps of the process will be bypassed. The script
won't generate neither a new `OptiML`, unsupervised model nor a
**Recursive Feature Selection** execution.


text:
================================================================================
CustomFieldDefAddedEvent
================================================================================

.. describe:: Extends

    :py:class:`~pyvisdk.mo.custom_field_def_event.CustomFieldDefEvent`

.. class:: pyvisdk.do.custom_field_def_added_event.CustomFieldDefAddedEvent

redpajama_set_name: RedPajamaGithub


text:
package com.haulmont.cuba.web.gui.components;

import com.haulmont.chile.core.model.MetaPropertyPath;
import com.haulmont.cuba.core.entity.Entity;
import com.haulmont.cuba.core.global.UserSessionSource;
import com.haulmont.cuba.gui.components.CaptionMode;
import com.haulmont.cuba.gui.components.OptionsStyleProvider;
import com.haulmont.cuba.gui.components.SecuredActionsHolder;
import com.haulmont.cuba.gui.components.SuggestionPickerField;
import com.haulmont.cuba.gui.executors.BackgroundTask;
import com.haulmont.cuba.gui.executors.BackgroundTaskHandler;
import com.haulmont.cuba.gui.executors.BackgroundWorker;
import com.haulmont.cuba.gui.executors.TaskLifeCycle;
import com.haulmont.cuba.web.gui.components.converters.StringToEntityConverter;
import com.haulmont.cuba.web.widgets.CubaPickerField;
import com.haulmont.cuba.web.widgets.CubaSuggestionPickerField;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.inject.Inject;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;

public class WebSuggestionPickerField<V extends Entity> extends WebPickerField<V>
        implements SuggestionPickerField<V>, SecuredActionsHolder {

    private static final Logger log = LoggerFactory.getLogger(WebSuggestionPickerField.class);

    /* Beans */
    protected BackgroundWorker backgroundWorker;

    protected BackgroundTaskHandler<List<V>> handler;

    protected SearchExecutor<V> searchExecutor;

    protected EnterActionHandler enterActionHandler;
    protected ArrowDownActionHandler arrowDownActionHandler;

    protected OptionsStyleProvider optionsStyleProvider;

    protected StringToEntityConverter entityConverter = new StringToEntityConverter();
    protected Locale locale;

    public WebSuggestionPickerField() {
    }

    @Override
    protected CubaPickerField<V> createComponent() {
        return new CubaSuggestionPickerField<>();
    }

    @Override
    public CubaSuggestionPickerField<V> getComponent() {
        //noinspection unchecked
        return (CubaSuggestionPickerField<V>) super.getComponent();
    }

    @Inject
    public void setBackgroundWorker(BackgroundWorker backgroundWorker) {
        this.backgroundWorker = backgroundWorker;
    }

    @Override
    protected void initComponent(CubaPickerField<V> component) {
        getComponent().setTextViewConverter(this::convertToTextView);

        getComponent().setSearchExecutor(query -> {
            cancelSearch();
            searchSuggestions(query);
        });

        getComponent().setCancelSearchHandler(this::cancelSearch);
    }

    @Inject
    public void setUserSessionSource(UserSessionSource userSessionSource) {
        this.locale = userSessionSource.getLocale();
    }

    protected String convertToTextView(V value) {
        if (value == null) {
            return "";
        }

        if (captionMode == CaptionMode.ITEM) {
            return entityConverter.convertToPresentation(value, String.class, locale);
        }

        if (captionProperty != null && !"".equals(captionProperty)) {
            MetaPropertyPath propertyPath = value.getMetaClass().getPropertyPath(captionProperty);
            if (propertyPath == null) {
                throw new IllegalArgumentException(String.format("Can't find property for given caption property: %s", captionProperty));
            }

            return metadataTools.format(value.getValueEx(captionProperty), propertyPath.getMetaProperty());
        }

        log.warn("Using StringToEntityConverter to get entity text presentation. Caption property is not defined " +
                "while caption mode is \"PROPERTY\"");

        return entityConverter.convertToPresentation(value, String.class, locale);
    }

    protected void cancelSearch() {
        if (handler != null) {
            log.debug("Cancel previous search");

            handler.cancel();
            handler = null;
        }
    }

    protected void searchSuggestions(final String query) {
        BackgroundTask<Long, List<V>> task = getSearchSuggestionsTask(query);
        if (task != null) {
            handler = backgroundWorker.handle(task);
            handler.execute();
        }
    }

    protected BackgroundTask<Long, List<V>> getSearchSuggestionsTask(final String query) {
        if (this.searchExecutor == null)
            return null;

        final SearchExecutor<V> currentSearchExecutor = this.searchExecutor;

        Map<String, Object> params;
        if (currentSearchExecutor instanceof ParametrizedSearchExecutor) {
            params = ((ParametrizedSearchExecutor<?>) currentSearchExecutor).getParams();
        } else {
            params = Collections.emptyMap();
        }

        return new BackgroundTask<Long, List<V>>(0) {
            @Override
            public List<V> run(TaskLifeCycle<Long> taskLifeCycle) throws Exception {
                List<V> result;
                try {
                    result = asyncSearch(currentSearchExecutor, query, params);
                } catch (RuntimeException e) {
                    log.error("Error in async search thread", e);

                    result = Collections.emptyList();
                }

                return result;
            }

            @Override
            public void done(List<V> result) {
                log.debug("Search results for '{}'", query);
                handleSearchResult(result);
            }

            @Override
            public void canceled() {
            }

            @Override
            public boolean handleException(Exception ex) {
                log.error("Error in async search thread", ex);
                return true;
            }
        };
    }

    protected List<V> asyncSearch(SearchExecutor<V> searchExecutor, String searchString,
                                  Map<String, Object> params) throws Exception {
        if (Thread.currentThread().isInterrupted()) {
            throw new InterruptedException();
        }

        log.debug("Search '{}'", searchString);

        List<V> searchResultItems;
        if (searchExecutor instanceof ParametrizedSearchExecutor) {
            //noinspection unchecked
            ParametrizedSearchExecutor<V> pSearchExecutor = (ParametrizedSearchExecutor<V>) searchExecutor;
            searchResultItems = pSearchExecutor.search(searchString, params);
        } else {
            searchResultItems = searchExecutor.search(searchString, Collections.emptyMap());
        }

        return searchResultItems;
    }

    protected void handleSearchResult(List<V> results) {
        showSuggestions(results);
    }

    @Override
    public void addFieldListener(FieldListener listener) {
        throw new UnsupportedOperationException();
    }

    @Override
    public void setFieldEditable(boolean editable) {
        throw new UnsupportedOperationException();
    }

    @Override
    public int getAsyncSearchDelayMs() {
        return getComponent().getAsyncSearchDelayMs();
    }

    @Override
    public void setAsyncSearchDelayMs(int asyncSearchDelayMs) {
        getComponent().setAsyncSearchDelayMs(asyncSearchDelayMs);
    }

    @Override
    public SearchExecutor getSearchExecutor() {
        return searchExecutor;
    }

    @Override
    public void setSearchExecutor(SearchExecutor searchExecutor) {
        this.searchExecutor = searchExecutor;
    }

    @Override
    public EnterActionHandler getEnterActionHandler() {
        return enterActionHandler;
    }

    @Override
    public void setEnterActionHandler(EnterActionHandler enterActionHandler) {
        this.enterActionHandler = enterActionHandler;
        getComponent().setEnterActionHandler(enterActionHandler::onEnterKeyPressed);
    }

    @Override
    public ArrowDownActionHandler getArrowDownActionHandler() {
        return arrowDownActionHandler;
    }

    @Override
    public void setArrowDownActionHandler(ArrowDownActionHandler arrowDownActionHandler) {
        this.arrowDownActionHandler = arrowDownActionHandler;
        getComponent().setArrowDownActionHandler(arrowDownActionHandler::onArrowDownKeyPressed);
    }

    @Override
    public int getMinSearchStringLength() {
        return getComponent().getMinSearchStringLength();
    }

    @Override
    public void setMinSearchStringLength(int minSearchStringLength) {
        getComponent().setMinSearchStringLength(minSearchStringLength);
    }

    @Override
    public int getSuggestionsLimit() {
        return getComponent().getSuggestionsLimit();
    }

    @Override
    public void setSuggestionsLimit(int suggestionsLimit) {
        getComponent().setSuggestionsLimit(suggestionsLimit);
    }

    @Override
    public void showSuggestions(List<V> suggestions) {
        getComponent().showSuggestions(suggestions);
    }

    @Override
    public void setPopupWidth(String popupWidth) {
        getComponent().setPopupWidth(popupWidth);
    }

    @Override
    public String getPopupWidth() {
        return getComponent().getPopupWidth();
    }

    @Override
    public String getInputPrompt() {
        return getComponent().getInputPrompt();
    }

    @Override
    public void setInputPrompt(String inputPrompt) {
        getComponent().setInputPrompt(inputPrompt);
    }

    @Override
    public void setOptionsStyleProvider(OptionsStyleProvider optionsStyleProvider) {
        this.optionsStyleProvider = optionsStyleProvider;

        if (optionsStyleProvider != null) {
            getComponent().setOptionsStyleProvider(item ->
                    optionsStyleProvider.getItemStyleName(this, item));
        } else {
            getComponent().setOptionsStyleProvider(null);
        }
    }

    @Override
    public OptionsStyleProvider getOptionsStyleProvider() {
        return optionsStyleProvider;
    }

    @Override
    public void setStyleName(String name) {
        super.setStyleName(name);

        getComponent().setPopupStyleName(name);
    }

    @Override
    public void addStyleName(String styleName) {
        super.addStyleName(styleName);

        getComponent().addPopupStyleName(styleName);
    }

    @Override
    public void removeStyleName(String styleName) {
        super.removeStyleName(styleName);

        getComponent().removePopupStyleName(styleName);
    }

    @Override
    public void commit() {
        throw new UnsupportedOperationException();
    }

    @Override
    public void discard() {
        throw new UnsupportedOperationException();
    }

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

    @Override
    public void setBuffered(boolean buffered) {
        throw new UnsupportedOperationException("Buffered mode isn't supported");
    }

    @Override
    public boolean isModified() {
        throw new UnsupportedOperationException();
    }
}


text:
module SlideRule
  class DistanceCalculator
    attr_accessor :rules

    def initialize(rules)
      @rules = prepare_rules(rules)
    end

    # TODO: Figure this out. Very inefficient!
    # Probably should calculate using a suggestions algorythm
    def group(array)
      array.map do |item|
        {
          item: item,
          matches: (array - [item]).map do |item_cmp|
            {
              match: item_cmp,
              distance: calculate_distance(item, item_cmp)
            }
          end
        }
      end
    end

    def closest_match(obj, array, threshold = 1.0)
      matches(obj, array, threshold).sort_by { |match| match[:distance] }.first
    end

    def closest_matching_item(obj, array, threshold = 1.0)
      match = closest_match(obj, array, threshold)
      return nil if match.nil?

      match[:item]
    end

    def is_match?(obj_1, obj_2, threshold)
      distance = calculate_distance(obj_1, obj_2)
      distance < threshold
    end

    def matches(obj, array, threshold)
      array.map do |item|
        distance = calculate_distance(obj, item)
        next nil unless distance <= threshold
        {
          item: item,
          distance: distance
        }
      end.compact
    end

    # All distances represented as 0..1
    #  0 = perfect match
    #  1 = farthest distance
    # Calculate distances for all attributes, then apply weight, and average them out.
    # Rules format:
    # {
    #   :attribute_name => {
    #     :weight => 0.90,
    #     :calculator => :distance_calculator,
    #     :threshold => 30
    #   }
    # }
    def calculate_distance(i1, i2)
      calculate_weighted_distances(i1, i2).reduce(0.0) do |distance, obj|
        distance + (obj[:distance] * obj[:weight])
      end
    end

    private

    def calculate_weighted_distances(i1, i2)
      distances = @rules.map do |attribute, options|
        val1 = i1.send(attribute)
        val2 = i2.send(attribute)
        distance = options[:calculator].calculate(val1, val2, options)
        next { distance: distance.to_f, weight: options[:weight] } unless distance.nil?

        nil
      end
      normalize_weights_array(distances) if distances.compact!

      distances
    end

    def get_calculator(calculator)
      return calculator.new if calculator.is_a?(Class)

      klass_name = calculator.to_s.split('_').collect(&:capitalize).join.to_s
      klass = begin
        ::SlideRule::DistanceCalculators.const_get(klass_name)
      rescue ::NameError
        nil
      end

      fail ArgumentError, "Unable to find calculator #{klass_name}" if klass.nil?

      klass.new
    end

    # Ensures all weights add up to 1.0
    #
    def normalize_weights(rules)
      weight_total = rules.map { |_attr, rule| rule[:weight] }.reduce(0.0, &:+)
      rules.each do |_attr, rule|
        rule[:weight] = rule[:weight] / weight_total
      end
    end

    # Ensures all weights add up to 1.0 in array of hashes
    #
    def normalize_weights_array(rules)
      weight_total = rules.map { |rule| rule[:weight] }.reduce(0.0, &:+)
      rules.each do |rule|
        rule[:weight] = rule[:weight] / weight_total
      end
    end

    # Prepares a duplicate of given rules hash with normalized weights and calculator instances
    #
    def prepare_rules(rules)
      prepared_rules = rules.each_with_object({}) do |(attribute, rule), copy|
        rule = copy[attribute] = safe_dup(rule)

        if rule[:type]
          puts 'Rule key `:type` is deprecated. Use `:calculator` instead.'
          rule[:calculator] = rule[:type]
        end

        rule[:calculator] = get_calculator(rule[:calculator])

        copy
      end
      prepared_rules = normalize_weights(prepared_rules)

      prepared_rules
    end

    def safe_dup(obj)
      obj.dup
    rescue
      obj
    end
  end
end


text:
module Fog
  module XenServer
    class Compute
      class Real
        def custom_templates
          data = @connection.request(:parser => Fog::XenServer::Parsers::GetRecords.new, :method => "VM.get_all_records")
          data.keep_if { |vm| vm[:is_a_template] && vm[:other_config]["default_template"].nil? }
          servers.load(data)
        rescue Fog::XenServer::RequestFailed => e
          []
        end
      end
    end
  end
end


text:
from strato.racktest.hostundertest import plugins

class Ping:
    def __init__(self, host):
        self._host = host

    def once(self, host):
        self._host.ssh.run.script("ping -c 1 %s" % host.node.ipAddress())

plugins.register('ping', Ping)


text:
import R from 'ramda';
import allErrors from './allErrors';
import { addError } from './error';
import { IHaveValidation } from './IHaveValidation';
import { isStringWithError } from './isString';
import { toLowerCase } from './toLowerCase';

/**
 * returns true if an E-mail is valid.
 */
export const isValidEmail = R.test(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/); // tslint:disable-line:max-line-length

/**
 * Validates E-mail prop of an object.
 *  - Checks if It is a string.
 *  - toLowerCase.
 *  - Checks if It is a valid E-mail.
 */
export const isEmailWithError = R.curry((errorMsg: string, propName: string, obj: IHaveValidation) => {
    obj = isStringWithError(errorMsg, propName, obj);
    obj = toLowerCase(propName, obj);

    const propValue = R.prop<string>(propName, obj);

    return isValidEmail(propValue)
        ? obj
        : addError(obj, propName, errorMsg);
});

/**
 * Validates E-mail prop of an object.
 *  - Checks if It is a string.
 *  - toLowerCase.
 *  - Checks if It is a valid E-mail.
 */
export const isEmail = isEmailWithError(allErrors.INVALID_EMAIL);


text:
package org.activiti.engine.impl;

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

import org.activiti.engine.history.HistoricDetail;
import org.activiti.engine.history.NativeHistoricDetailQuery;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.impl.interceptor.CommandExecutor;

public class NativeHistoricDetailQueryImpl extends AbstractNativeQuery<NativeHistoricDetailQuery, HistoricDetail> implements NativeHistoricDetailQuery {

  private static final long serialVersionUID = 1L;

  public NativeHistoricDetailQueryImpl(CommandContext commandContext) {
    super(commandContext);
  }

  public NativeHistoricDetailQueryImpl(CommandExecutor commandExecutor) {
    super(commandExecutor);
  }

  // results ////////////////////////////////////////////////////////////////

  public List<HistoricDetail> executeList(CommandContext commandContext, Map<String, Object> parameterMap, int firstResult, int maxResults) {
    return commandContext.getHistoricDetailEntityManager().findHistoricDetailsByNativeQuery(parameterMap, firstResult, maxResults);
  }

  public long executeCount(CommandContext commandContext, Map<String, Object> parameterMap) {
    return commandContext.getHistoricDetailEntityManager().findHistoricDetailCountByNativeQuery(parameterMap);
  }

}


text:
'use strict';

module.exports = function(app) {
	var users = require('../../app/controllers/users');
	var queries = require('../../app/controllers/queries');
	var queryTask = require('../../app/tasks/queries');

	// Queries Routes
	app.route('/queries')
		.get(queries.list)
		.post(users.requiresLogin, queries.create);

	app.route('/queries/:queryId')
		.get(queries.read)
		.put(users.requiresLogin, queries.hasAuthorization, queries.update)
		.delete(users.requiresLogin, queries.hasAuthorization, queries.delete);

	// Finish by binding the Query middleware
	app.param('queryId', queries.queryByID);
};


text:
		<title>Example 2 - Simple Announcer</title>

			Please note: All examples will send data to each other as they'll be on the same domain. Consider only having one example open at a time!

Messages will show here when a new tab is opened:


text:
import datetime
timeToWakeUp = datetime.datetime(2100, 1, 1, hour=0, minute=0, second=0, microsecond=0)

import oscReceiver as receiver
import getTrainInfo as info

import params

isSleeping = 1
delayTime = 0

def setTime(time):
  global delayTime
  print receiver.getUrl()
  delayTime = info.getInfo(str(receiver.getUrl()))
  print "delayTime : " + str(delayTime)

  global timeToWakeUp
  timeToWakeUp = time
  global isSleeping
  isSleeping = 1

  print "set ; " + str(timeToWakeUp - datetime.timedelta(minutes=delayTime*15 + params.USERMARGIN))

def isTime():
  global timeToWakeUp
  global isSleeping
  global delayTime

  timeToCheck = timeToWakeUp - datetime.timedelta(minutes=(delayTime * 15 + params.USERMARGIN))
#  if delayTime > 0:
 #   timeToCheck = timeTowakeUp - detetaime.timedelta(minutes=delayTime*15)
  #  print "[DELAYED!] Estimated alerm time : " + str(timeToCheck)

  if timeToCheck < datetime.datetime.now():
    #print "time to wake up"
    if isSleeping == 1:
      isSleeping = 0
      return 1
    else:
      return 0
  else:
    return 0

def getDelayTime():
  global delayTime
  return delayTime+1

def updateDelayTime():
  global delayTime
  delayTime = info.getInfo(receiver.getUrl())
  if delayTime > 0:
    print "[DELAY]"

def update():
  global timeToWakeUp
  if timeToWakeUp != receiver.getTime():
    setTime(receiver.getTime())

def close():
  receiver.close()


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/color_blue">
    <LinearLayout
        android:id="@+id/my_linear"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <LinearLayout
            android:layout_marginTop="30dp"
            android:layout_marginLeft="20dp"
            android:layout_marginBottom="5dp"
            android:layout_width="wrap_content"
            android:layout_height="40dp"
            android:orientation="horizontal"
            android:gravity="center_vertical">
            <ImageView
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:src="@drawable/frag_my_img01"/>
            <TextView
                android:id="@+id/frag_my_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="李小姐"
                android:textColor="@color/color_white"
                android:textSize="20sp"
                />
        </LinearLayout>
        <LinearLayout
            android:layout_marginLeft="20dp"
            android:layout_width="wrap_content"
            android:layout_height="40dp"
            android:gravity="center_vertical"
            android:orientation="horizontal">
            <ImageView
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:src="@drawable/frag_my_img02"/>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/frag_my_phone"
                android:text="@string/num_phone"
                android:textColor="@color/color_white"
                android:textSize="20sp"
                />
        </LinearLayout>
        <View
            android:layout_gravity="center_horizontal"
            android:layout_width="250dp"
            android:layout_height="1dp"
            android:background="@color/color_white"
            android:layout_marginTop="20dp"
            />
            <LinearLayout
                android:layout_marginTop="10dp"
                android:layout_width="match_parent"
                android:layout_height="40dp"
                android:orientation="horizontal"
                android:gravity="center"

                >
                <TextView
                    android:layout_width="75dp"
                    android:layout_height="wrap_content"
                    android:text="@string/referral_code01"
                    android:textSize="18sp"
                    android:textColor="@color/color_white"/>
                <TextView
                    android:id="@+id/frag_my_code"
                    android:layout_width="45dp"
                    android:layout_height="wrap_content"
                    android:text="@string/referral_code"
                    android:textSize="18sp"
                    android:textColor="@color/color_white"/>
                <View
                    android:layout_width="1dp"
                    android:layout_height="match_parent"
                    android:background="@color/color_white"
                    android:layout_marginLeft="15dp"
                    android:layout_marginRight="15dp"/>
                <TextView
                    android:layout_width="20dp"
                    android:layout_height="wrap_content"
                    android:text="剩"
                    android:textColor="@color/color_white"
                    android:textSize="18sp"/>
                <TextView
                    android:layout_width="10dp"
                    android:layout_height="wrap_content"
                    android:text="2"
                    android:textColor="@color/color_white"
                    android:textSize="18sp"/>
                <TextView
                    android:layout_width="80dp"
                    android:layout_height="wrap_content"
                    android:text="张洗衣券"
                    android:textColor="@color/color_white"
                    android:textSize="18sp"/>

            </LinearLayout>

    </LinearLayout>

    <GridView
        android:layout_below="@id/my_linear"
        android:id="@+id/frag_my_grid"
        android:background="@color/color_white"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:numColumns="3"
        android:gravity="center"
        android:verticalSpacing="5dp"
        android:horizontalSpacing="5dp"
        android:layout_marginBottom="2dp"

        >
    </GridView>

</RelativeLayout>


text:
set -e

read -p "Enter the version to release: " releaseVersion
echo "Releasing stub-http version $releaseVersion"
RELEASE_VERSION=${releaseVersion} lein release
echo "Release $releaseVersion completed successfully"


text:
using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

	public int score  ;

	public DisplayManager RefDisplayerManager;

	public float MassProperty {
		get {
			var parameter =  1/Mathf.InverseLerp( 0f , 10000f , score + 10 ) ;
			return parameter ;
		}
	}

	void Start() {
		if (RefDisplayerManager == null) {
			RefDisplayerManager = GetComponentInParent<DisplayManager> ();
		}
	}

	void OnTriggerEnter2D(Collider2D other) {
		if (other.gameObject.tag == "Food") {
			score += 1;
			Destroy (other.gameObject);
			RefDisplayerManager.CurrentScoreText.text = score.ToString() ;
		}
	}
}


text:
cask 'retroshare' do
  version '0.6.3,20170821-cebcc4b4'
  sha256 'ea908eb98f3af69486b4b950635dff9774c004488bdb950db27f8bac92bdf45a'

  # github.com/RetroShare/RetroShare was verified as official when first introduced to the cask
  url "https://github.com/RetroShare/RetroShare/releases/download/v#{version.before_comma}/Retroshare-#{version.before_comma}-OSX-#{version.after_comma}.dmg"
  appcast 'https://github.com/RetroShare/RetroShare/releases.atom',
          checkpoint: '336c2f3110552dfc7a2b18807ea2273cbfa837e2b4df1a26e295e055fc44b152'
  name 'RetroShare'
  homepage 'http://retroshare.sourceforge.net/'

  app 'retroshare.app'
end


text:
#ifndef HK_BASE_BSD_SOCKET_H
#define HK_BASE_BSD_SOCKET_H

#include <Common/Base/System/Io/Socket/hkSocket.h>

class hkBsdSocket : public hkSocket
{
	public:
		HK_DECLARE_CLASS_ALLOCATOR( HK_MEMORY_CLASS_BASE_CLASS );

#		if defined(HK_PLATFORM_X64)
			typedef unsigned __int64 socket_t;
#		elif defined(HK_PLATFORM_WIN32) || defined(HK_PLATFORM_XBOX) || defined(HK_PLATFORM_XBOX360)
			typedef unsigned socket_t;
#		else
			typedef int socket_t;
#		endif

		hkBsdSocket(socket_t s=socket_t(-1));

		virtual ~hkBsdSocket();

		virtual hkBool isOk() const;

		virtual void close();

		virtual int read( void* buf, int nbytes);

		virtual int write( const void* buf, int nbytes);

		// client

		virtual hkResult connect(const char* servername, int portNumber);

		virtual hkResult asyncSelect(void* notificationHandle, hkUint32 message, SOCKET_EVENTS events);

		virtual bool canRead();

		// server

		virtual hkResult listen(int port);

		virtual hkSocket* pollForNewClient();

		virtual void getAddress( hkStringBuf& hostOut, int& portOut ) const;

		// Switch between blocking/non-blocking modes if desired
		hkResult setBlocking(hkBool blocking);

	protected:

		hkResult createSocket();

		socket_t m_socket;
};

/// Initializes the network for BSD style sockets
void HK_CALL hkBsdNetworkInit();

/// Shuts down the network
void HK_CALL hkBsdNetworkQuit();

void HK_CALL hkBsdGetAddressString( hkStringBuf& );

#endif // HK_BASE_BSD_SOCKET_H

/*
 * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20140907)
 *
 * Confidential Information of Havok.  (C) Copyright 1999-2014
 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
 * Logo, and the Havok buzzsaw logo are trademarks of Havok.  Title, ownership
 * rights, and intellectual property rights in the Havok software remain in
 * Havok and/or its suppliers.
 *
 * Use of this software for evaluation purposes is subject to and indicates
 * acceptance of the End User licence Agreement for this product. A copy of
 * the license is included with this software and is also available at www.havok.com/tryhavok.
 *
 */


text:
/*
 This class packages the parameters for impression and conversion events sent to the backend.
 */

#import <Foundation/Foundation.h>

@class OPTLYProjectConfig, OPTLYDecisionEventTicket, OPTLYEventTicket;
@protocol OPTLYBucketer;

// --- Event URLs ----
NS_ASSUME_NONNULL_BEGIN
extern NSString * const OPTLYEventBuilderDecisionTicketEventURL;
extern NSString * const OPTLYEventBuilderEventTicketURL;
NS_ASSUME_NONNULL_END

@protocol OPTLYEventBuilder <NSObject>

/**
 * Create the parameters for an impression event.
 *
 * @param config The project config object.
 * @param userId The ID of the user.
 * @param experimentKey The experiment name.
 * @param variationId The variation ID.
 * @param attributes A map of attribute names to current user attribute values.
 * @return A map of parameters for an impression event. This value can be nil.
 *
 */
- (nullable OPTLYDecisionEventTicket *)buildDecisionEventTicket:(nonnull OPTLYProjectConfig *)config
                                                         userId:(nonnull NSString *)userId
                                                  experimentKey:(nonnull NSString *)experimentKey
                                                    variationId:(nonnull NSString *)variationId
                                                     attributes:(nullable NSDictionary<NSString *, NSString *> *)attributes;

/**
 * Create the parameters for a conversion event.
 *
 * @param config The project config object.
 * @param userId The ID of the user.
 * @param eventName The event name.
 * @param eventValue The event value (e.g., revenue amount).
 * @param attributes A map of attribute names to current user attribute values.
 * @return A map of parameters for a conversion event. This value can be nil.
 *
 */
- (nullable OPTLYEventTicket *)buildEventTicket:(nonnull OPTLYProjectConfig *)config
                                       bucketer:(nonnull id<OPTLYBucketer>)bucketer
                                         userId:(nonnull NSString *)userId
                                      eventName:(nonnull NSString *)eventName
                                     eventValue:(nullable NSNumber *)eventValue
                                     attributes:(nullable NSDictionary<NSString *, NSString *> *)attributes;
@end

@interface OPTLYEventBuilderDefault : NSObject<OPTLYEventBuilder>

@end


text:
@interface SRChannelsConfiguration : NSObject

+ (instancetype)defaultConfig;

@property (nonatomic, strong, readonly) UIColor *barBackgroundColor;

@property (nonatomic, strong, readonly) UIColor *channelNormalColor;
@property (nonatomic, strong, readonly) UIColor *channelSelectedColor;
@property (nonatomic, strong, readonly) UIFont  *channelFont;

@property (nonatomic, strong, readonly) UIColor *indicatorViewColor;
@property (nonatomic, assign, readonly) CGFloat  indicatorViewHeight;
@property (nonatomic, assign, readonly) CGFloat  indicatorViewExtraWidth;

@property (nonatomic, strong, readonly) UIColor *bottomLineViewColor;

@property (nonatomic, copy, readonly) SRChannelsConfiguration *(^backgroundColor)(UIColor *color);

@property (nonatomic, copy, readonly) SRChannelsConfiguration *(^titleNormalColor)(UIColor *color);
@property (nonatomic, copy, readonly) SRChannelsConfiguration *(^titleSelectedColor)(UIColor *color);
@property (nonatomic, copy, readonly) SRChannelsConfiguration *(^titleFont)(UIFont *font);

@property (nonatomic, copy, readonly) SRChannelsConfiguration *(^indicatorColor)(UIColor *color);
@property (nonatomic, copy, readonly) SRChannelsConfiguration *(^indicatorHeight)(CGFloat height);
@property (nonatomic, copy, readonly) SRChannelsConfiguration *(^indicatorExtraWidth)(CGFloat width);

@property (nonatomic, copy, readonly) SRChannelsConfiguration *(^bottomLineColor)(UIColor *color);

@end


text:
package org.elasticsearch.test;

import com.carrotsearch.randomizedtesting.annotations.*;
import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope.Scope;
import org.apache.lucene.analysis.BaseTokenStreamTestCase;
import org.apache.lucene.util.TimeUnits;
import org.elasticsearch.test.junit.listeners.ReproduceInfoPrinter;

@Listeners({
        ReproduceInfoPrinter.class
})
@ThreadLeakFilters(defaultFilters = true, filters = {ElasticsearchThreadFilter.class})
@ThreadLeakScope(Scope.NONE)
@TimeoutSuite(millis = TimeUnits.HOUR)
public abstract class ElasticsearchTokenStreamTestCase extends BaseTokenStreamTestCase {

}


text:
<!DOCTYPE HTML>

  <ons-page id="aboutPage">
    <ons-toolbar>

        <ons-toolbar-button onclick="fn.open()">
          <ons-icon icon="ion-navicon, material:md-menu"></ons-icon>
        </ons-toolbar-button>

    </ons-toolbar>

      <ons-speed-dial position="bottom left" direction="right">
        <ons-fab>
          <ons-icon icon="share-alt"></ons-icon>
        </ons-fab>
        <ons-speed-dial-item>
          <ons-icon icon="twitter"></ons-icon>
        </ons-speed-dial-item>
        <ons-speed-dial-item>
          <ons-icon icon="google-plus"></ons-icon>
        </ons-speed-dial-item>
        <ons-speed-dial-item>
          <ons-icon icon="facebook"></ons-icon>
        </ons-speed-dial-item>
  </ons-page>


text:
from mediadownloader import db

class File(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    type = db.Column(db.String(20), unique=False)
    filename = db.Column(db.String(256), unique=False)
    date_added = db.Column(db.DateTime, unique=False)

    def __init__(self, type, filename, date_added):
        self.type = type
        self.filename = filename
        self.date_added = date_added

    def __repr__(self):
        return '<File %s (%s)>' % self.filename


text:
<?php

namespace TestSuite;
use Opl\Autoloader\Exception\TranslationException;
use Opl\Autoloader\Exception\FileNotFoundException;
use Opl\Autoloader\Exception\FileFormatException;
use RuntimeException;

/**
 * @covers Opl\Autoloader\Exception\TranslationException
 * @covers Opl\Autoloader\Exception\FileNotFoundException
 * @covers Opl\Autoloader\Exception\FileFormatException
 */
class ExceptionTest extends \PHPUnit_Framework_TestCase
{
	public function testTranslationException()
	{
		$exception = new TranslationException('Foo');
		$this->assertEquals('Foo', $exception->getMessage());
		$this->assertTrue($exception instanceof RuntimeException);
	} // end testTranslationException();

	public function testFileNotFoundException()
	{
		$exception = new FileNotFoundException('Foo');
		$this->assertEquals('Foo', $exception->getMessage());
		$this->assertTrue($exception instanceof RuntimeException);
	} // end testFileNotFoundException();

	public function testFileFormatException()
	{
		$exception = new FileFormatException('Foo');
		$this->assertEquals('Foo', $exception->getMessage());
		$this->assertTrue($exception instanceof RuntimeException);
	} // end testFileFormatException();
} // end ExceptionTest;


text:
<?php

namespace CachetHQ\Cachet\Http\Routes\Dashboard;

use Illuminate\Contracts\Routing\Registrar;

/**
 * This is the dashboard setting routes class.
 *
 * @author James Brooks <james@alt-three.com>
 * @author Connor S. Parks <connor@connorvg.tv>
 */
class SettingRoutes
{
    /**
     * Defines if these routes are for the browser.
     *
     * @var bool
     */
    public static $browser = true;

    /**
     * Define the dashboard setting routes.
     *
     * @param \Illuminate\Contracts\Routing\Registrar $router
     *
     * @return void
     */
    public function map(Registrar $router)
    {
        $router->group([
            'middleware' => ['auth'],
            'namespace'  => 'Dashboard',
            'prefix'     => 'dashboard/settings',
        ], function (Registrar $router) {
            $router->get('setup', [
                'as'   => 'get:dashboard.settings.setup',
                'uses' => 'SettingsController@showSetupView',
            ]);
            $router->get('analytics', [
                'as'   => 'get:dashboard.settings.analytics',
                'uses' => 'SettingsController@showAnalyticsView',
            ]);
            $router->get('localization', [
                'as'   => 'get:dashboard.settings.localization',
                'uses' => 'SettingsController@showLocalizationView',
            ]);
            $router->get('security', [
                'as'   => 'get:dashboard.settings.security',
                'uses' => 'SettingsController@showSecurityView',
            ]);
            $router->get('theme', [
                'as'   => 'get:dashboard.settings.theme',
                'uses' => 'SettingsController@showThemeView',
            ]);
            $router->get('stylesheet', [
                'as'   => 'get:dashboard.settings.stylesheet',
                'uses' => 'SettingsController@showStylesheetView',
            ]);
            $router->get('customization', [
                'as'   => 'get:dashboard.settings.customization',
                'uses' => 'SettingsController@showCustomizationView',
            ]);
            $router->get('credits', [
                'as'   => 'get:dashboard.settings.credits',
                'uses' => 'SettingsController@showCreditsView',
            ]);
            $router->get('log', [
                'as'   => 'get:dashboard.settings.log',
                'uses' => 'SettingsController@showLogView',
            ]);
            $router->get('mail', [
                'as'   => 'get:dashboard.settings.mail',
                'uses' => 'SettingsController@showMailView',
            ]);
            $router->post('mail', [
                'as'   => 'post:dashboard.settings.mail',
                'uses' => 'SettingsController@postMail',
            ]);
            $router->post('mail/test', [
                'as'   => 'post:dashboard.settings.mail.test',
                'uses' => 'SettingsController@testMail',
            ]);

            $router->post('/', [
                'as'   => 'post:dashboard.settings',
                'uses' => 'SettingsController@postSettings',
            ]);
        });
    }
}


text:
/**
 *
 */
package ATS.DAO.QUERYBUILDER;

import ATS.ENTITY.Project;

/**
 * @author doquanghuy
 *
 */
public class ProjectQueryBuilder {
	private final static String GET_ALL_PROJECTS="SELECT o FROM Project o WHERE o.userId = \"%s\"";
	private final static String GET_PROJECTS_BY_STATE="SELECT o FROM Project o WHERE o.userId = \"%s\" AND o.projectState = %d";

	public static String getAllProjects(String userId)
	{
		return String.format(GET_ALL_PROJECTS, userId);
	}

	public static String getProjectsByState(String userId,int state)
	{
		String query="";
		switch (state) {
			//State project active
			case Project.STATE_ACTIVE:
			//State project delete
			case Project.STATE_DELETED:
				query = String.format(GET_PROJECTS_BY_STATE, userId, state);
				break;
			//Default State project active
			default:
				query = getAllProjects(userId);
				break;
			}
		return query;
	}

}


text:
package com.itheima.oschina.bean;

import com.thoughtworks.xstream.annotations.XStreamAlias;

/**
 * 软件实体类
 *
 * @author FireAnt(http://my.oschina.net/LittleDY)
 * @created 2014年10月23日 下午3:03:25
 *
 */
@SuppressWarnings("serial")
@XStreamAlias("software")
public class Software extends Entity {

	@XStreamAlias("title")
	private String title;

	@XStreamAlias("author")
	private String author;

	@XStreamAlias("authorid")
	private int authorId;

	@XStreamAlias("recommended")
	private int recommended;

	@XStreamAlias("extensiontitle")
	private String extensionTitle;

	@XStreamAlias("license")
	private String license;

	@XStreamAlias("body")
	private String body;

	@XStreamAlias("homepage")
	private String homepage;

	@XStreamAlias("document")
	private String document;

	@XStreamAlias("download")
	private String download;

	@XStreamAlias("logo")
	private String logo;

	@XStreamAlias("language")
	private String language;

	@XStreamAlias("os")
	private String os;

	@XStreamAlias("recordtime")
	private String recordtime;

	@XStreamAlias("url")
	private String url;

	@XStreamAlias("favorite")
	private int favorite;

	@XStreamAlias("tweetCount")
	private int tweetCount;

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getAuthor() {
		return author;
	}

	public void setAuthor(String author) {
		this.author = author;
	}

	public int getAuthorId() {
		return authorId;
	}

	public void setAuthorId(int authorId) {
		this.authorId = authorId;
	}

	public int getRecommended() {
		return recommended;
	}

	public void setRecommended(int recommended) {
		this.recommended = recommended;
	}

	public String getExtensionTitle() {
		return extensionTitle;
	}

	public void setExtensionTitle(String extensionTitle) {
		this.extensionTitle = extensionTitle;
	}

	public String getLicense() {
		return license;
	}

	public void setLicense(String license) {
		this.license = license;
	}

	public String getBody() {
		return body;
	}

	public void setBody(String body) {
		this.body = body;
	}

	public String getHomepage() {
		return homepage;
	}

	public void setHomepage(String homepage) {
		this.homepage = homepage;
	}

	public String getDocument() {
		return document;
	}

	public void setDocument(String document) {
		this.document = document;
	}

	public String getDownload() {
		return download;
	}

	public void setDownload(String download) {
		this.download = download;
	}

	public String getLogo() {
		return logo;
	}

	public void setLogo(String logo) {
		this.logo = logo;
	}

	public String getLanguage() {
		return language;
	}

	public void setLanguage(String language) {
		this.language = language;
	}

	public String getOs() {
		return os;
	}

	public void setOs(String os) {
		this.os = os;
	}

	public String getRecordtime() {
		return recordtime;
	}

	public void setRecordtime(String recordtime) {
		this.recordtime = recordtime;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public int getFavorite() {
		return favorite;
	}

	public void setFavorite(int favorite) {
		this.favorite = favorite;
	}

	public int getTweetCount() {
		return tweetCount;
	}

	public void setTweetCount(int tweetCount) {
		this.tweetCount = tweetCount;
	}
}


text:
package test.component;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import aQute.bnd.osgi.Builder;
import aQute.bnd.osgi.Constants;
import aQute.bnd.osgi.Jar;
import aQute.bnd.osgi.PermissionGenerator;
import aQute.bnd.osgi.Resource;
import aQute.bnd.test.BndTestCase;

public class PermissionGeneratorTest extends BndTestCase {
	private static Set<String> getPermissionsGeneratedFor(String permissionFile) throws Exception {
		Builder b = new Builder();
		b.setProperty(Constants.DSANNOTATIONS, "test.component.*_basic");
		b.setProperty("Private-Package", "test.component");
		b.setProperty("Export-Package", "test.api");

		File tmpFile = File.createTempFile("bndtest", "permissions.perm");
		FileWriter fileWriter = new FileWriter(tmpFile);
		fileWriter.write(permissionFile);
		fileWriter.close();
		b.setProperty("-includeresource", "{OSGI-INF/permissions.perm=" + tmpFile.getAbsolutePath() + "}");

		b.addClasspath(new File("bin"));

		Jar jar = b.build();
		assertOk(b);

		Resource resource = jar.getResource("OSGI-INF/permissions.perm");
		BufferedReader r = new BufferedReader(new InputStreamReader(resource.openInputStream()));

		Set<String> permissions = new TreeSet<String>();
		String line = null;
		while ((line = r.readLine()) != null) {
			if (!line.isEmpty()) {
				assertTrue("Found duplicate permission: " + line, permissions.add(line));
				System.err.println("Permission read: " + line);
			}
		}

		tmpFile.delete();

		return permissions;
	}

	private static Set<String> filterAndSubtract(Set<String> input, String regex) {
		Set<String> result = new TreeSet<>();
		Pattern pattern = Pattern.compile(regex);
		for (Iterator<String> it = input.iterator(); it.hasNext();) {
			String string = it.next();
			Matcher matcher = pattern.matcher(string);
			if (matcher.matches()) {
				it.remove();
				result.add(matcher.group(1));
			}
		}
		return result;
	}

	private static void assertNotingLeft(Set<String> permissions) {
		assertEquals("No other permissions expected", Collections.emptySet(), permissions);
	}

	private static void assertPackageAvailable(Set<String> permissions) {
		Set<String> importedPackages = filterAndSubtract(permissions,
				"^\\(org.osgi.framework.PackagePermission \"([^\"]+)\" \"import\"\\)$");
		Set<String> exportedPackages = filterAndSubtract(permissions,
				"^\\(org.osgi.framework.PackagePermission \"([^\"]+)\" \"export\"\\)$");

		/* @formatter:off */
		assertEquals("Imported packages",
			     new TreeSet<>(Arrays.asList("aQute.bnd.annotation.metatype",
			                                 "aQute.bnd.differ",
			                                 "aQute.bnd.header",
			                                 "aQute.bnd.osgi",
			                                 "aQute.bnd.service.diff",
			                                 "aQute.bnd.test",
			                                 "aQute.lib.io",
			                                 "aQute.service.reporter",
			                                 "javax.xml.namespace",
			                                 "javax.xml.parsers",
			                                 "javax.xml.xpath",
			                                 "junit.framework",
			                                 "org.osgi.framework",
			                                 "org.osgi.service.component",
			                                 "org.osgi.service.event",
			                                 "org.osgi.service.log",
			                                 "org.w3c.dom",
			                                 "org.xml.sax")),
			     importedPackages);
		assertEquals("Exported packages",
			     new TreeSet<>(Arrays.asList("test.api")),
			     exportedPackages);
		/* @formatter:on */
	}

	private static void assertServicesAvailable(Set<String> permissions) {
		Set<String> registeredServices = filterAndSubtract(permissions,
				"^\\(org.osgi.framework.ServicePermission \"([^\"]+)\" \"register\"\\)$");
		Set<String> requiredServices = filterAndSubtract(permissions,
				"^\\(org.osgi.framework.ServicePermission \"([^\"]+)\" \"get\"\\)$");

		/* @formatter:off */
		assertEquals("Registered services",
				new TreeSet<>(Arrays.asList("java.lang.Runnable",
						"java.io.Serializable",
						"java.lang.Object")),
						registeredServices);
		assertEquals("Required services",
				new TreeSet<>(Arrays.asList("org.osgi.service.log.LogService")),
						requiredServices);
		/* @formatter:on */
	}

	private static void assertCapabilitiesAvailable(Set<String> permissions) {
		Set<String> requiredCapabilities = filterAndSubtract(permissions,
				"^\\(org.osgi.framework.CapabilityPermission \"([^\"]+)\" \"require\"\\)$");
		Set<String> providedCapabilities = filterAndSubtract(permissions,
				"^\\(org.osgi.framework.CapabilityPermission \"([^\"]+)\" \"provide\"\\)$");

		/* @formatter:off */
		assertEquals("Provided capabilities",
				new TreeSet<>(Arrays.asList("osgi.service")),
				providedCapabilities);
		assertEquals("Required capabilities",
				new TreeSet<>(Arrays.asList("osgi.extender",
						"osgi.service")),
						requiredCapabilities);
		/* @formatter:on */
	}

	private static void assertAdminAvailable(Set<String> permissions) {
		Set<String> adminCapabilities = filterAndSubtract(permissions, "^\\((org.osgi.framework.AdminPermission)\\)$");
		assertEquals("Admin capabilities", 1, adminCapabilities.size());
	}

	public static void testJustPackages() throws Exception {
		Set<String> permissions = getPermissionsGeneratedFor("${permissions;packages}");
		assertPackageAvailable(permissions);
		assertNotingLeft(permissions);
	}

	public static void testJustServices() throws Exception {
		Set<String> permissions = getPermissionsGeneratedFor("${permissions;services}");
		assertServicesAvailable(permissions);
		assertNotingLeft(permissions);
	}

	public static void testJustCapabilities() throws Exception {
		Set<String> permissions = getPermissionsGeneratedFor("${permissions;capabilities}");
		assertCapabilitiesAvailable(permissions);
		assertNotingLeft(permissions);
	}

	public static void testJustAdmin() throws Exception {
		Set<String> permissions = getPermissionsGeneratedFor("${permissions;admin}");
		assertAdminAvailable(permissions);
		assertNotingLeft(permissions);
	}

	public static void testConcatenatedPermissionsNoAdmin() throws Exception {
		Set<String> permissions = getPermissionsGeneratedFor(
				"${permissions;packages}${permissions;services}${permissions;capabilities}");
		assertPackageAvailable(permissions);
		assertServicesAvailable(permissions);
		assertCapabilitiesAvailable(permissions);
		assertNotingLeft(permissions);
	}

	public static void testInlinePermissionsNoAdmin() throws Exception {
		Set<String> permissions = getPermissionsGeneratedFor("${permissions;packages;services;capabilities}");
		assertPackageAvailable(permissions);
		assertServicesAvailable(permissions);
		assertCapabilitiesAvailable(permissions);
		assertNotingLeft(permissions);
	}

	public static void testInlinePermissions() throws Exception {
		Set<String> permissions = getPermissionsGeneratedFor("${permissions;packages;services;capabilities;admin}");
		assertPackageAvailable(permissions);
		assertServicesAvailable(permissions);
		assertCapabilitiesAvailable(permissions);
		assertAdminAvailable(permissions);
		assertNotingLeft(permissions);
	}

	public static void testCustomCapabilityParsing() throws Exception {
		Builder b = new Builder();
		b.setProperty("Require-Capability", "osgi.service;filter:=\"(objectClass=*)\"");
		Set<String> services = PermissionGenerator.getReferencedServices(b);
		assertEquals(Collections.singleton("*"), services);

		b.setProperty("Require-Capability", "osgi.service;filter:=\"(!(objectClass=*))\"");
		services = PermissionGenerator.getReferencedServices(b);
		assertEquals(Collections.emptySet(), services);

		b.setProperty("Require-Capability", "osgi.service;filter:=\"(!(objectClass=test.Helper))\"");
		services = PermissionGenerator.getReferencedServices(b);
		assertEquals(Collections.emptySet(), services);

		b.setProperty("Require-Capability", "osgi.service;filter:=\"(objectClass=test.*)\"");
		services = PermissionGenerator.getReferencedServices(b);
		assertEquals(Collections.singleton("test.*"), services);

		b.setProperty("Require-Capability", "osgi.service;filter:=\"(|(objectClass=test.*)(objectClass=test2.*))\"");
		services = PermissionGenerator.getReferencedServices(b);
		assertEquals(new HashSet<String>(Arrays.asList("test.*", "test2.*")), services);

		b.setProperty("Require-Capability", "osgi.service;filter:=\"(|(objectClass=test.*)(!(objectClass=test2.*)))\"");
		services = PermissionGenerator.getReferencedServices(b);
		assertEquals(Collections.singleton("test.*"), services);

		// In the following cases, there is no way to determine the permissions
		// needed, so nothing is generated. In these cases it is up to the user
		// to generate the permission
		b.setProperty("Require-Capability", "osgi.service;filter:=\"(objectClass=test2.*Helper)\"");
		services = PermissionGenerator.getReferencedServices(b);
		assertEquals(Collections.emptySet(), services);

		b.setProperty("Require-Capability", "osgi.service;filter:=\"(objectClass=test*.*)\"");
		services = PermissionGenerator.getReferencedServices(b);
		assertEquals(Collections.emptySet(), services);

		b.setProperty("Require-Capability", "osgi.service;filter:=\"(other=prop)\"");
		services = PermissionGenerator.getReferencedServices(b);
		assertEquals(Collections.emptySet(), services);

		b.setProperty("Require-Capability", "osgi.service;filter:=\"(&(objectClass=test.*)(objectClass=*Helper))\"");
		services = PermissionGenerator.getReferencedServices(b);
		assertEquals(Collections.emptySet(), services);

		b.setProperty("Require-Capability", "osgi.service;filter:=\"(!(&(objectClass=test.*)(objectClass=*Helper)))\"");
		services = PermissionGenerator.getReferencedServices(b);
		assertEquals(Collections.emptySet(), services);
	}
}


text:
package org.springframework.boot.autoconfigure.cache;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.cache.CacheManager;
import org.springframework.cache.support.NoOpCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;

/**
 * No-op cache configuration used to disable caching via configuration.
 *
 * @author Stephane Nicoll
 * @since 1.3.0
 */
@Configuration
@ConditionalOnMissingBean(CacheManager.class)
@Conditional(CacheCondition.class)
class NoOpCacheConfiguration {

	@Bean
	public NoOpCacheManager cacheManager() {
		return new NoOpCacheManager();
	}

}


text:
var express = require('express'),
    app = express(),
    port = 80;

app.configure(function() {
    app.use(express.static(__dirname));
});

console.log("vagrant-nodejs-express server listening...");

app.listen(port);


text:
.PHONY: default
default: all

files=generale.tex tournevis.tex perceuse.tex fer_a_souder.tex colle.tex scie_sauteuse.tex contact.tex

.PHONY: brochure
brochure: brochure_bricolage.pdf
.PHONY: poster
poster: poster_bricolage.pdf

.PHONY: all
all: brochure poster

.PHONY: force
force: clean-all $(output)

%.pdf: %.tex $(files)
	@echo "Compile the LaTeX" > /dev/stderr
	pdflatex $<
	@echo "Compile the LaTeX" > /dev/stderr
	pdflatex $<

#Add dependency to the sty
poster_bricolage.pdf: template_poster.sty

.PHONY: clean
clean:
	rm -f *.aux *.blg *.log *.out *.ps

.PHONY: clean-all
clean-all: clean
	rm -f *.pdf

.PHONY: help
help:
	@echo "Possible targets:"
	@echo "     all (default)"
	@echo "     force"
	@echo "     brochure"
	@echo "     poster"
	@echo "     clean"
	@echo "     clean-all"