text:
package ru.skynet.jvfsftpd.util;

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

import javax.security.auth.login.AppConfigurationEntry;
import javax.security.auth.login.Configuration;

public class DeligateConfiguration extends Configuration
{
	private final Configuration config;
	private final Map<String, AppConfigurationEntry[]> addon;

	public DeligateConfiguration(Configuration config, String domain, AppConfigurationEntry[] appConfigurationEntries)
	{
		this.config=config;
		this.addon=new HashMap<String, AppConfigurationEntry[]>();
		this.addon.put(domain, appConfigurationEntries);
	}
	public DeligateConfiguration(Configuration config, Map<String, AppConfigurationEntry[]> addon)
	{
		this.config=config;
		this.addon=addon;
	}
	@Override
	public AppConfigurationEntry[] getAppConfigurationEntry(String name)
	{
		AppConfigurationEntry[] ret = addon.get(name);
		if(ret==null && config!=null)
		{
			ret = config.getAppConfigurationEntry(name);
		}
		return ret!=null?ret:addon.get("other");
	}

	@Override
	public void refresh()
	{
		if(config!=null) config.refresh();
	}

}

redpajama_set_name: RedPajamaGithub


text:
package com.haulmont.cuba.core.sys.jpql;

import com.haulmont.bali.util.Preconditions;
import com.haulmont.cuba.core.sys.jpql.model.JpqlEntityModel;
import com.haulmont.cuba.core.sys.jpql.model.VirtualJpqlEntityModel;
import com.haulmont.cuba.core.sys.jpql.tree.QueryNode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class QueryVariableContext {
    private Map<String, JpqlEntityModel> entityVariableName2entity = new HashMap<>();
    private QueryNode node;
    private List<QueryVariableContext> children = new ArrayList<>();
    private JpqlEntityModel entity;
    private boolean propagateVariablesUpstairs = true;
    private QueryVariableContext parent = null;

    public QueryVariableContext(DomainModel model, QueryNode node) {
        Preconditions.checkNotNullArgument(model);
        Preconditions.checkNotNullArgument(node);

        this.node = node;
        this.entity = new VirtualJpqlEntityModel();
    }

    public boolean isPropagateVariablesUpstairs() {
        return propagateVariablesUpstairs;
    }

    public void setPropagateVariablesUp(boolean propagateVariablesUpstairs) {
        this.propagateVariablesUpstairs = propagateVariablesUpstairs;
    }

    public JpqlEntityModel getEntityByVariableName(String entityVariableName) {
        JpqlEntityModel result = entityVariableName2entity.get(entityVariableName);
        if (result != null) {
            return result;
        }

        return parent == null ? null : parent.getEntityByVariableName(entityVariableName);
    }

    public JpqlEntityModel getEntityByVariableNameHierarchically(String entityVariableName) {
        JpqlEntityModel result = entityVariableName2entity.get(entityVariableName);
        if (result != null) {
            return result;
        }
        if (children != null) {
            for (QueryVariableContext child : children) {
                JpqlEntityModel childModel = child.getEntityByVariableNameHierarchically(entityVariableName);
                if (childModel != null) {
                    return childModel;
                }
            }
        }
        return null;
    }

    /**
     * Internal method to register entity variables found in query
     *
     * @param variableName - found entity variable name
     * @param entity entity model
     */
    public void addEntityVariable(String variableName, JpqlEntityModel entity) {
        if (variableName == null) {
            throw new JPA2RecognitionException("No entity variable name passed");
        }
        if (entity == null) {
            throw new JPA2RecognitionException("No entity passed");
        }
        if (entityVariableName2entity.containsKey(variableName))
            throw new JPA2RecognitionException(
                    String.format("The identification variable '%s' cannot be declared more than once", variableName));

        entityVariableName2entity.put(variableName, entity);
    }

    public QueryVariableContext getContextByCaretPosition(int caretPosition) {
        if (!node.contains(caretPosition)) {
            return null;
        }

        for (QueryVariableContext child : children) {
            QueryVariableContext childResult = child.getContextByCaretPosition(caretPosition);
            if (childResult != null)
                return childResult;
        }
        return this;

    }

    public void addChild(QueryVariableContext child) {
        if (child == null) {
            throw new NullPointerException("No child passed");
        }
        if (child.getParent() != null) {
            throw new IllegalArgumentException("Child has parent already");
        }
        child.setParent(this);
        children.add(child);
    }

    public JpqlEntityModel getEntity() {
        return entity;
    }

    public void setEntity(JpqlEntityModel entity) {
        this.entity = entity;
    }

    private QueryVariableContext getParent() {
        return parent;
    }

    private void setParent(QueryVariableContext parent) {
        this.parent = parent;
    }

    public String getVariableNameByEntity(String entityName) {
        if (entityName == null)
            throw new NullPointerException("No entity name passed");

        for (Map.Entry<String, JpqlEntityModel> entry : entityVariableName2entity.entrySet()) {
            if (entityName.equals(entry.getValue().getName())) {
                return entry.getKey();
            }
        }

        return parent == null ? null : parent.getVariableNameByEntity(entityName);
    }
}


text:
require 'ffaker/internet'

module FFaker
  module InternetSE
    include Internet

    extend ModuleUtils
    extend self

    BYTE = [*'0'..'255'].freeze
    HOSTS = %w(gmail.com yahoo.com hotmail.com spray.se passagen.se).freeze
    DOMAIN_SUFFIXES = %w(se nu com).freeze
    DISPOSABLE_HOSTS = %w(mailinator.com suremail.info spamherelots.com binkmail.com safetymail.info).freeze
    SLUG_DELIMITERS = %w(- _ .).freeze

    def email(name = nil)
      "#{user_name(name)}@#{domain_name}"
    end

    # Returns an email address of an online disposable email service
    # (like tempinbox.com). you can really send an email to these
    # addresses an access it by going to the service web pages.
    def disposable_email(name = nil)
      "#{user_name(name)}@#{DISPOSABLE_HOSTS.sample}"
    end

    def free_email(name = nil)
      "#{user_name(name)}@#{HOSTS.sample}"
    end

    # Used to fake login names were dot is not allowed
    def login_user_name
      user_name.tr('.', '')
    end

    # Mostly used for email creation
    def user_name(name = nil)
      return user_name_from_name(name) if name
      user_name_random
    end

    def user_name_random
      variant = rand(2)
      case variant
      when 0 then user_name_variant_short
      when 1 then user_name_variant_long
      else        user_name_variant_short
      end
    end

    def user_name_variant_long
      array_parts = [NameSE.first_name, NameSE.last_name]
      array_parts.map! { |word| word.gsub(/\W/, '') }
      join_to_user_name(array_parts)
    end

    def user_name_variant_short
      array_parts = [NameSE.first_name]
      array_parts.map! { |word| word.gsub(/\W/, '') }
      join_to_user_name(array_parts)
    end

    def user_name_from_name(name)
      array_parts = name.scan(/\w+/).shuffle
      join_to_user_name(array_parts)
    end

    def join_to_user_name(array_parts)
      join_char = %w(. _).sample
      array_parts.map(&:downcase).join(join_char)
    end

    def domain_name
      "#{domain_word}.#{domain_suffix}"
    end

    def domain_word
      company_name_single_word.tap do |dw|
        dw.gsub!(/\W/, '')
        dw.downcase!
      end
    end

    def company_name_single_word
      CompanySE.name.split(' ').first
    end

    def domain_suffix
      DOMAIN_SUFFIXES.sample
    end

    def uri(protocol)
      "#{protocol}://#{domain_name}"
    end

    def http_url
      uri('http')
    end

    def ip_v4_address
      (1..4).map { BYTE.sample }.join('.')
    end

    def slug(words = nil, glue = nil)
      glue ||= SLUG_DELIMITERS.sample

      (words || FFaker::Lorem.words(2).join(' ')).gsub(' ', glue).downcase
    end
  end
end


text:
/* $Id: Keep.java 985537 2010-08-14 17:17:00Z jeremias $ */

package org.apache.fop.layoutmgr;

import org.apache.fop.fo.Constants;
import org.apache.fop.fo.properties.KeepProperty;
import org.apache.fop.fo.properties.Property;

/**
 * Object representing a keep constraint, corresponding
 * to the XSL-FO keep properties.
 */
public final class Keep {

    /** The integer value for "auto" keep strength. */
    private static final int STRENGTH_AUTO = Integer.MIN_VALUE;

    /** The integer value for "always" keep strength. */
    private static final int STRENGTH_ALWAYS = Integer.MAX_VALUE;

    /** keep auto */
    public static final Keep KEEP_AUTO = new Keep(STRENGTH_AUTO, Constants.EN_AUTO);

    /** keep always */
    public static final Keep KEEP_ALWAYS = new Keep(STRENGTH_ALWAYS, Constants.EN_LINE);

    private int strength;

    private int context;

    private Keep(int strength, int context) {
        this.strength = strength;
        this.context = context;
    }

    private static int getKeepStrength(Property keep) {
        if (keep.isAuto()) {
            return STRENGTH_AUTO;
        } else if (keep.getEnum() == Constants.EN_ALWAYS) {
            return STRENGTH_ALWAYS;
        } else {
            return keep.getNumber().intValue();
        }
    }

    /**
     * Obtain a Keep instance corresponding to the given {@link KeepProperty}
     *
     * @param keepProperty  the {@link KeepProperty}
     * @return  a new instance corresponding to the given property
     */
    public static Keep getKeep(KeepProperty keepProperty) {
        Keep keep = new Keep(STRENGTH_AUTO, Constants.EN_AUTO);
        keep.update(keepProperty.getWithinPage(),   Constants.EN_PAGE);
        keep.update(keepProperty.getWithinColumn(), Constants.EN_COLUMN);
        keep.update(keepProperty.getWithinLine(),   Constants.EN_LINE);
        return keep;
    }

    private void update(Property keep, int context) {
        if (!keep.isAuto()) {
            this.strength = getKeepStrength(keep);
            this.context = context;
        }
    }

    /** @return {@code true} if the keep property was specified as "auto" */
    public boolean isAuto() {
        return strength == STRENGTH_AUTO;
    }

    /**
     * Returns the context of this keep.
     *
     * @return one of {@link Constants#EN_LINE}, {@link Constants#EN_COLUMN} or
     * {@link Constants#EN_PAGE}
     */
    public int getContext() {
        return context;
    }

    /** @return the penalty value corresponding to the strength of this Keep */
    public int getPenalty() {
        if (strength == STRENGTH_AUTO) {
            return 0;
        } else if (strength == STRENGTH_ALWAYS) {
            return KnuthElement.INFINITE;
        } else {
            return KnuthElement.INFINITE - 1;
        }
    }

    private static int getKeepContextPriority(int context) {
        switch (context) {
        case Constants.EN_LINE:   return 0;
        case Constants.EN_COLUMN: return 1;
        case Constants.EN_PAGE:   return 2;
        case Constants.EN_AUTO:   return 3;
        default: throw new IllegalArgumentException();
        }
    }

    /**
     * Compare this Keep instance to another one, and return the
     * stronger one if the context is the same
     *
     * @param other     the instance to compare to
     * @return  the winning Keep instance
     */
    public Keep compare(Keep other) {

        /* check strength "always" first, regardless of priority */
        if (this.strength == STRENGTH_ALWAYS
                && this.strength > other.strength) {
            return this;
        } else if (other.strength == STRENGTH_ALWAYS
                && other.strength > this.strength) {
            return other;
        }

        int pThis = getKeepContextPriority(this.context);
        int pOther = getKeepContextPriority(other.context);

        /* equal priority: strongest wins */
        if (pThis == pOther) {
            return (strength >= other.strength) ? this : other;
        }

        /* different priority: lowest priority wins */
        return (pThis < pOther) ? this : other;
    }

    /** {@inheritDoc} */
    public String toString() {
        return (strength == STRENGTH_AUTO) ? "auto"
                : (strength == STRENGTH_ALWAYS) ? "always"
                        : Integer.toString(strength);
    }
}


text:
Settings Provider implements a simple binding from .properties files to Java objects.
It support tracking file content changes with automatic thread-safe substitution of new data in runtime.

## Description
Data object is declared with interface with getters. During data parsing

By default mapping of values from .properties file works as follows: camel-hump property name (for example `myFieldName`) associated with
dot-separated property name (`my.field.name`). Accessing to data could be declared as getter (`getMyFieldName()`) as well as
method named by field name (`myFieldName()`)

Default mapping could be overriding by `@PropertyName` annotation.

## Examples

#### Simple usage:
1. A .properties file with data (**user.properties**)
![user.properties](docs/user-properties.png)
1. Declare interface for mapping data from .properties file **UserSettings.java**
![UserSettings.java](docs/UserInterface-java.png)
1. Load settings from Java code. Settings could be loaded from resource, file or by URL **SimpleExample.java**
![SimpleExample.java](docs/SimpleExample-java.png)
2. Output:
```
Loaded settings: UserSettings [password (password) = "MyPassword"; email (email) = "anon@example.org"; username (username) = "Anonymous"]
```

#### Optional fields
By default all the properties are defined as mandatory. This means if there is no mapping from data object interface
field to property whole object could not be constructed. There are two ways to deal with it:
1. Add `@Optional` annotation to a field - this will allow to return `null` value. (not applicable to primitives)
2. Add `@DefaultValue` annotation to a field - if mapping is not found a value from annotation will be used.

Here is an example to show both variants.

1. Data object interface (**HostSettings.java**):
![HostSettings.java](docs/HostSettings-java.png)
2. Properties files for test:
**all-set.properties**
![all-set.properties](docs/all-set-properties.png)
**default-port.properties**
![default-port.properties](docs/default-port-properties.png)
**optional-host.properties**
![optional-host.properties](docs/optional-host-properties.png)
3. Demonstration class **OptionalExample.java**
![OptionalExample.java](docs/OptionalExample-java.png)
4. Outputs:
```
All set: HostSettings [targetPort (target.port) = "443"; targetHost (target.host) = "localhost"]
Default port: HostSettings [targetPort (target.port) = "80"; targetHost (target.host) = "localhost"]
Optional host: HostSettings [targetPort (target.port) = "443"; targetHost (target.host) = "null"]
localhost:443
```

#### More examples
... will be shown later ...


text:
package com.intellij.ide.actions.searcheverywhere;

import com.intellij.execution.Executor;
import com.intellij.execution.ExecutorRegistry;
import com.intellij.execution.RunnerAndConfigurationSettings;
import com.intellij.execution.actions.ChooseRunConfigurationPopup;
import com.intellij.execution.configurations.RunConfiguration;
import com.intellij.execution.executors.DefaultRunExecutor;
import com.intellij.execution.runners.ProgramRunner;
import com.intellij.ide.DataManager;
import com.intellij.ide.IdeBundle;
import com.intellij.openapi.keymap.KeymapUtil;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.wm.ToolWindowId;
import com.intellij.psi.codeStyle.MinusculeMatcher;
import com.intellij.psi.codeStyle.NameUtil;
import com.intellij.ui.SimpleColoredComponent;
import com.intellij.ui.SimpleTextAttributes;
import com.intellij.ui.scale.JBUIScale;
import com.intellij.util.ObjectUtils;
import com.intellij.util.Processor;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import org.intellij.lang.annotations.MagicConstant;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.*;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;

public class RunConfigurationsSEContributor implements SearchEverywhereContributor<ChooseRunConfigurationPopup.ItemWrapper> {

  private final SearchEverywhereCommandInfo RUN_COMMAND =
    new SearchEverywhereCommandInfo("run", IdeBundle.message("searcheverywhere.runconfigurations.command.run.description"), this);
  private final SearchEverywhereCommandInfo DEBUG_COMMAND =
    new SearchEverywhereCommandInfo("debug", IdeBundle.message("searcheverywhere.runconfigurations.command.debug.description"), this);

  private final static int RUN_MODE = 0;
  private final static int DEBUG_MODE = 1;

  private final Project myProject;
  private final Component myContextComponent;
  private final Supplier<String> myCommandSupplier;

  public RunConfigurationsSEContributor(Project project, Component component, Supplier<String> commandSupplier) {
    myProject = project;
    myContextComponent = component;
    myCommandSupplier = commandSupplier;
  }

  @NotNull
  @Override
  public String getSearchProviderId() {
    return getClass().getSimpleName();
  }

  @NotNull
  @Override
  public String getGroupName() {
    return IdeBundle.message("searcheverywhere.run.configs.tab.name");
  }

  @Override
  public int getSortWeight() {
    return 350;
  }

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

  @Override
  public boolean processSelectedItem(@NotNull ChooseRunConfigurationPopup.ItemWrapper selected, int modifiers, @NotNull String searchText) {
    RunnerAndConfigurationSettings settings = ObjectUtils.tryCast(selected.getValue(), RunnerAndConfigurationSettings.class);
    if (settings != null) {
      int mode = getMode(searchText, modifiers);
      Executor executor = findExecutor(settings, mode);
      if (executor != null) {
        DataManager dataManager = DataManager.getInstance();
        selected.perform(myProject, executor, dataManager.getDataContext(myContextComponent));
      }
    }

    return true;
  }

  @Nullable
  @Override
  public Object getDataForItem(@NotNull ChooseRunConfigurationPopup.ItemWrapper element, @NotNull String dataId) {
    return null;
  }

  @NotNull
  @Override
  public ListCellRenderer<? super ChooseRunConfigurationPopup.ItemWrapper> getElementsRenderer() {
    return renderer;
  }

  @NotNull
  @Override
  public List<SearchEverywhereCommandInfo> getSupportedCommands() {
    return Arrays.asList(RUN_COMMAND, DEBUG_COMMAND);
  }

  @Override
  public void fetchElements(@NotNull String pattern,
                            @NotNull ProgressIndicator progressIndicator,
                            @NotNull Processor<? super ChooseRunConfigurationPopup.ItemWrapper> consumer) {

    if (StringUtil.isEmptyOrSpaces(pattern)) return;

    pattern = filterString(pattern);
    MinusculeMatcher matcher = NameUtil.buildMatcher(pattern).build();
    for (ChooseRunConfigurationPopup.ItemWrapper wrapper : ChooseRunConfigurationPopup.createFlatSettingsList(myProject)) {
      if (matcher.matches(wrapper.getText()) && !consumer.process(wrapper)) {
        return;
      }
    }
  }

  @MagicConstant(intValues = {RUN_MODE, DEBUG_MODE})
  private int getMode(String searchText, int modifiers) {
    if (isCommand(searchText, DEBUG_COMMAND)) {
      return DEBUG_MODE;
    }
    else if (isCommand(searchText, RUN_COMMAND)) {
      return RUN_MODE;
    }
    else {
      return (modifiers & InputEvent.SHIFT_MASK) == 0 ? DEBUG_MODE : RUN_MODE;
    }
  }

  private static Optional<String> extractFirstWord(String input) {
    if (!StringUtil.isEmptyOrSpaces(input) && input.contains(" ")) {
      return Optional.of(input.split(" ")[0]);
    }

    return Optional.empty();
  }

  private String filterString(String input) {
    return extractFirstWord(input)
      .filter(firstWord -> RUN_COMMAND.getCommandWithPrefix().startsWith(firstWord) ||
                           DEBUG_COMMAND.getCommandWithPrefix().startsWith(firstWord))
      .map(firstWord -> input.substring(firstWord.length() + 1))
      .orElse(input);
  }

  private static boolean isCommand(String input, SearchEverywhereCommandInfo command) {
    if (input == null) {
      return false;
    }

    return extractFirstWord(input)
      .map(firstWord -> command.getCommandWithPrefix().startsWith(firstWord))
      .orElse(false);
  }

  private final Renderer renderer = new Renderer();

  private class Renderer extends JPanel implements ListCellRenderer<ChooseRunConfigurationPopup.ItemWrapper> {

    private final SimpleColoredComponent runConfigInfo = new SimpleColoredComponent();
    private final SimpleColoredComponent executorInfo = new SimpleColoredComponent();

    private Renderer() {
      super(new BorderLayout());
      add(runConfigInfo, BorderLayout.CENTER);
      add(executorInfo, BorderLayout.EAST);
      setBorder(JBUI.Borders.empty(1, UIUtil.isUnderWin10LookAndFeel() ? 0 : JBUIScale.scale(UIUtil.getListCellHPadding())));
    }

    @Override
    public Component getListCellRendererComponent(JList<? extends ChooseRunConfigurationPopup.ItemWrapper> list,
                                                  ChooseRunConfigurationPopup.ItemWrapper wrapper,
                                                  int index,
                                                  boolean isSelected,
                                                  boolean cellHasFocus) {
      runConfigInfo.clear();
      executorInfo.clear();

      setBackground(UIUtil.getListBackground(isSelected, true));
      setFont(list.getFont());
      Color foreground = isSelected ? list.getSelectionForeground() : list.getForeground();
      runConfigInfo.append(wrapper.getText(), new SimpleTextAttributes(SimpleTextAttributes.STYLE_PLAIN, foreground));
      runConfigInfo.setIcon(wrapper.getIcon());

      fillExecutorInfo(wrapper, list, isSelected);

      return this;
    }

    private void fillExecutorInfo(ChooseRunConfigurationPopup.ItemWrapper wrapper, JList<?> list, boolean selected) {

      SimpleTextAttributes commandAttributes = selected
                                               ? new SimpleTextAttributes(SimpleTextAttributes.STYLE_PLAIN, list.getSelectionForeground())
                                               : SimpleTextAttributes.GRAYED_ATTRIBUTES;
      SimpleTextAttributes shortcutAttributes = selected
                                                ? new SimpleTextAttributes(SimpleTextAttributes.STYLE_PLAIN, list.getSelectionForeground())
                                                : SimpleTextAttributes.GRAY_ATTRIBUTES;

      String input = myCommandSupplier.get();
      if (isCommand(input, RUN_COMMAND)) {
        fillWithMode(wrapper, RUN_MODE, commandAttributes);
        return;
      }
      if (isCommand(input, DEBUG_COMMAND)) {
        fillWithMode(wrapper, DEBUG_MODE, commandAttributes);
        return;
      }

      Executor debugExecutor = ExecutorRegistry.getInstance().getExecutorById(ToolWindowId.DEBUG);
      Executor runExecutor = DefaultRunExecutor.getRunExecutorInstance();

      KeyStroke enterStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
      KeyStroke shiftEnterStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.SHIFT_DOWN_MASK);
      if (debugExecutor != null) {
        executorInfo.append(debugExecutor.getId(), commandAttributes);
        executorInfo.append("(" + KeymapUtil.getKeystrokeText(enterStroke) + ")", shortcutAttributes);
        if (runExecutor != null) {
          executorInfo.append(" / " + runExecutor.getId(), commandAttributes);
          executorInfo.append("(" + KeymapUtil.getKeystrokeText(shiftEnterStroke) + ")", shortcutAttributes);
        }
      }
      else {
        if (runExecutor != null) {
          executorInfo.append(runExecutor.getId(), commandAttributes);
          executorInfo.append("(" + KeymapUtil.getKeystrokeText(enterStroke) + ")", shortcutAttributes);
        }
      }
    }

    private void fillWithMode(ChooseRunConfigurationPopup.ItemWrapper wrapper, @MagicConstant(intValues = {RUN_MODE, DEBUG_MODE}) int mode,
                              SimpleTextAttributes attributes) {
      Optional.ofNullable(ObjectUtils.tryCast(wrapper.getValue(), RunnerAndConfigurationSettings.class))
        .map(settings -> findExecutor(settings, mode))
        .ifPresent(executor -> {
          executorInfo.append(executor.getId(), attributes);
          executorInfo.setIcon(executor.getToolWindowIcon());
        });
    }
  }

  @Nullable
  private static Executor findExecutor(@NotNull RunnerAndConfigurationSettings settings,
                                       @MagicConstant(intValues = {RUN_MODE, DEBUG_MODE}) int mode) {
    Executor runExecutor = DefaultRunExecutor.getRunExecutorInstance();
    Executor debugExecutor = ExecutorRegistry.getInstance().getExecutorById(ToolWindowId.DEBUG);

    Executor executor = mode == RUN_MODE ? runExecutor : debugExecutor;
    if (executor == null) {
      return null;
    }

    RunConfiguration runConf = settings.getConfiguration();
    if (ProgramRunner.getRunner(executor.getId(), runConf) == null) {
      executor = runExecutor == executor ? debugExecutor : runExecutor;
    }

    return executor;
  }
}


text:
"""
Tests for util/random.py

Functions
---------
probvec
sample_without_replacement

"""
import numbers
import numpy as np
from numpy.testing import (assert_array_equal, assert_allclose, assert_raises,
                           assert_)
from quantecon.random import probvec, sample_without_replacement, draw

# probvec #

class TestProbvec:
    def setup_method(self):
        self.m, self.k = 2, 3  # m vectors of dimension k
        seed = 1234

        self.out_parallel = probvec(self.m, self.k, random_state=seed)
        self.out_cpu = \
            probvec(self.m, self.k, random_state=seed, parallel=False)

    def test_shape(self):
        for out in [self.out_parallel, self.out_cpu]:
            assert_(out.shape == (self.m, self.k))

    def test_parallel_cpu(self):
        assert_array_equal(self.out_parallel, self.out_cpu)

# sample_without_replacement #

def test_sample_without_replacement_shape():
    assert_array_equal(sample_without_replacement(2, 0).shape, (0,))

    n, k, m = 5, 3, 4
    assert_array_equal(
        sample_without_replacement(n, k).shape,
        (k,)
    )
    assert_array_equal(
        sample_without_replacement(n, k, num_trials=m).shape,
        (m, k)
    )

def test_sample_without_replacement_uniqueness():
    n = 10
    a = sample_without_replacement(n, n)
    b = np.unique(a)
    assert_(len(b) == n)

def test_sample_without_replacement_value_error():
    # n <= 0
    assert_raises(ValueError, sample_without_replacement, 0, 2)
    assert_raises(ValueError, sample_without_replacement, -1, -1)

    # k > n
    assert_raises(ValueError, sample_without_replacement, 2, 3)

# draw #

class TestDraw:
    def setup_method(self):
        self.pmf = np.array([0.4, 0.1, 0.5])
        self.cdf = np.cumsum(self.pmf)
        self.n = len(self.pmf)

    def test_return_types(self):
        out = draw(self.cdf)
        assert_(isinstance(out, numbers.Integral))

        size = 10
        out = draw(self.cdf, size)
        assert_(out.shape == (size,))

    def test_return_values(self):
        out = draw(self.cdf)
        assert_(out in range(self.n))

        size = 10
        out = draw(self.cdf, size)
        assert_(np.isin(out, range(self.n)).all())

    def test_lln(self):
        size = 1000000
        out = draw(self.cdf, size)
        hist, bin_edges = np.histogram(out, bins=self.n, density=True)
        pmf_computed = hist * np.diff(bin_edges)
        atol = 1e-2
        assert_allclose(pmf_computed, self.pmf, atol=atol)


text:
>

## Installation

```sh
$ npm install --save event-manager
```

## Usage

```js
var eventManager = require('event-manager');

eventManager('Rainbow');
```
## License

MIT © [Darius Brückers]()

[npm-image]: https://badge.fury.io/js/event-manager.svg
[npm-url]: https://npmjs.org/package/event-manager
[travis-image]: https://travis-ci.org//event-manager.svg?branch=master
[travis-url]: https://travis-ci.org//event-manager
[daviddm-image]: https://david-dm.org//event-manager.svg?theme=shields.io
[daviddm-url]: https://david-dm.org//event-manager


text:
OTTO WG Minutes 4/6/16
STATUS: Final

## Voting Members Attending:
 - Mike Schwartz
 - Keith Hazelton
 - Yuriy Zabrovarnyy
 - Judith Bush

## Discussion of OpenID Connect Federation Standard

Roland and Rebecka have put forward a draft federation standard for OpenID Connect:
 https://github.com/rohe/pyoidc/blob/master/oidc_fed/oidcfed.txt

Keith is going to reach out to Roland and Rebecka to encourage them to bring that to the
OTTO WG. It's a subset of what we're trying to accomplish, but it could be synergistic
with our overall mission.

Mike has submitted some suggested revisions to the abstract, and will continue to review the
spec this week for a more detailed presentation at next week's OTTO meeting.

## Discussion of Linked Data Format

Janusz suggested we should define and formalize OTTO ontology using owl/rdfs. "Using OWL we will be
able to create very strict schema (classes, properties, etc) which it will be very good for validators."

I think we agree, but what about Turtle N3 format? Last week, Jeff was using Turtle.
Yuriy switched to it this week because its more concise than the JSON-LD format:
    Turtle (Terse RDF Triple Language) is a syntax and grammar for RDF serialization written
    by David Beckett and Tim Berners-Lee in 2008, created as an alternative syntax to RDF/XML.
    It allows RDF graphs to be written out ('serialized') in a compact and natural text form
    that easier for humans to read than RDF/XML.

Here is a [Rough guide to Turtle Guide]
(https://semanticpublishing.wordpress.com/2013/03/01/lld2-rough-guide-to-turtle/)

## Discussion of OpenID_Relying Party

We started to discuss schema for OpenID Connect Relying Parties:

```N3
    @prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
    @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
    @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
    @prefix schema: <http://schema.org/> .
    @prefix otto: <http://kantarainitiative.org/otto/schema/> .

    # Ontology

    otto:OpenID_Relying_Party a rdfs:Class .

    otto:redirect_uris a rdf:Property ;
     rdfs:range xsd:anyURI;
     .

    otto:jwks_uri a rdf:Property ;
     rdfs:range xsd:anyURI;
     .

    otto:sector_identifier_uri a rdf:Property ;
     rdfs:range xsd:anyURI;
     .

    otto:initiate_login_uri a rdf:Property ;
     rdfs:range xsd:anyURI;
     .

    otto:logout_uri a rdf:Property ;
     rdfs:range xsd:anyURI;
     .

    otto:entity_category a rdf:Property ;
     rdfs:range xsd:anyURI;
     .
```

The question is what would the federation operator publish about OpenID Connect relying parties.
Mike proposed that the URI's are interesting, because even though an RP can register these with
the OP, trust can be enhanced by the federation publishing (and sign) this information.

There is also precedent in SAML federations for asserting a category for the relying party,
such as "Research and Scholarship" in the higher education federations.

Mike was concerned that unlike in SAML federations where "entityID" uniquely identifies
an SP, OpenID Connect has no equivalent single identifier. The closest thing is "redirect_uris".
Perhaps we need to introduce the equivalent of an "entityID"?

## Deliverables for next week

Yuriy is going to look at exporting our schema to a website like http://schema.org
Jeff mentioned last week that there was a script to accomplish this.

Mike is going to work on a first draft of moving some of the content to rfc-xml format
so we have something that looks like a spec by IIW.

## Next Meeting - Weds 4/13/2016 9am PT

Screen Sharing: [https://global.gotomeeting.com/join/162399285](https://global.gotomeeting.com/join/162399285)

 - Audio: Skype: +99051000000481
 - North America Toll: +1 (805) 309-2350
 - Alternate Toll: +1 (714) 551-9842
 - International Toll: http://www.turbobridge.com/international.html

 - Conference ID: 613-2898

    Command Menu: 0 Plays menu of Keypad Commands *3 Promote to Host (if non-host) *5 Raise your hand
    *6 Mute yourself (toggle on/off) *# Private roll call of participants *\ Mute music-on-hold (toggle on/off)

    TurboPhone (beta): https://www.turbobridge.com/join.html Works with Internet Explorer on Windows only

    SIP Access (using IP phone or soft phone) sip:bridge@turbobridge.com
    SIP URL details: https://www.turbobridge.com/help/Index.html?context=180


text:
require "fog/core"

module Fog
  module Tutum
    extend Fog::Provider

    module Errors
      class ServiceError < Fog::Errors::Error; end
      class SecurityError < ServiceError; end
      class NotFound < ServiceError; end
      class Execution < ServiceError; end
    end

    service(:compute, "Compute")
  end
end


text:
package org.workcraft.plugins.son.tools;

import org.workcraft.gui.graph.tools.Decoration;

public interface PlaceNodeDecoration extends Decoration {
    boolean hasToken();

    boolean hasFault();
}


text:
"""
Operation compression, both in-memory and in-database.
"""

import warnings

from dbsync.lang import *
from dbsync.utils import get_pk, query_model
from dbsync import core
from dbsync.models import Version, Operation
from dbsync.logs import get_logger

logger = get_logger(__name__)

def _assert_operation_sequence(seq, session=None):
    """
    Asserts the correctness of a sequence of operations over a single
    tracked object.

    The sequence is given in a sorted state, from newest operation to
    oldest.
    """
    message = "The sequence of operations for the given object "\
        "<row_id: {0}, content_type_id: {1}, model: {2}> is inconsistent. "\
        "This might indicate external interference with the synchronization "\
        "model or, most commonly, the reuse of old primary keys by the "\
        "database engine. To function properly, the database engine must use "\
        "unique primary keys through the history of the table "\
        "(e.g. using AUTO INCREMENT). Operations from old to new: {3}".\
        format(seq[0].row_id,
               seq[0].content_type_id,
               seq[0].tracked_model,
               list(reversed(map(attr('command'), seq))))

    if not all(op.command == 'u' for op in seq[1:-1]):
        warnings.warn(message)
        logger.error(
            u"Can't have anything but updates between beginning "
            u"and end of operation sequence. %s",
            seq)

    if len(seq) > 1:
        if seq[-1].command == 'd':
            warnings.warn(message)
            logger.error(
                u"Can't have anything after a delete operation in sequence. %s",
                seq)

        if seq[0].command == 'i':
            warnings.warn(message)
            logger.error(
                u"Can't have anything before an insert in operation sequence. %s",
                seq)

@core.session_committing
def compress(session=None):
    """
    Compresses unversioned operations in the database.

    For each row in the operations table, this deletes unnecesary
    operations that would otherwise bloat the message.

    This procedure is called internally before the 'push' request
    happens, and before the local 'merge' happens.
    """
    unversioned = session.query(Operation).\
        filter(Operation.version_id == None).order_by(Operation.order.desc())
    seqs = group_by(lambda op: (op.row_id, op.content_type_id), unversioned)

    # Check errors on sequences
    for seq in seqs.itervalues():
        _assert_operation_sequence(seq, session)

    for seq in ifilter(lambda seq: len(seq) > 1, seqs.itervalues()):
        if seq[-1].command == 'i':
            if all(op.command == 'u' for op in seq[:-1]):
                # updates are superfluous
                map(session.delete, seq[:-1])
            elif seq[0].command == 'd':
                # it's as if the object never existed
                map(session.delete, seq)
        elif seq[-1].command == 'u':
            if all(op.command == 'u' for op in seq[:-1]):
                # leave a single update
                map(session.delete, seq[1:])
            elif seq[0].command == 'd':
                # leave the delete statement
                map(session.delete, seq[1:])
    session.flush()

    # repair inconsistencies
    for operation in session.query(Operation).\
            filter(Operation.version_id == None).\
            order_by(Operation.order.desc()).all():
        session.flush()
        model = operation.tracked_model
        if not model:
            logger.error(
                "operation linked to content type "
                "not tracked: %s" % operation.content_type_id)
            continue
        if operation.command in ('i', 'u'):
            if query_model(session, model, only_pk=True).\
                    filter_by(**{get_pk(model): operation.row_id}).count() == 0:
                logger.warning(
                    "deleting operation %s for model %s "
                    "for absence of backing object" % (operation, model.__name__))
                session.delete(operation)
                continue
        if operation.command == 'u':
            subsequent = session.query(Operation).\
                filter(Operation.content_type_id == operation.content_type_id,
                       Operation.version_id == None,
                       Operation.row_id == operation.row_id,
                       Operation.order > operation.order).all()
            if any(op.command == 'i' for op in subsequent) and \
                    all(op.command != 'd' for op in subsequent):
                logger.warning(
                    "deleting update operation %s for model %s "
                    "for preceding an insert operation" %\
                        (operation, model.__name__))
                session.delete(operation)
                continue
        if session.query(Operation).\
                filter(Operation.content_type_id == operation.content_type_id,
                       Operation.command == operation.command,
                       Operation.version_id == None,
                       Operation.row_id == operation.row_id,
                       Operation.order != operation.order).count() > 0:
            logger.warning(
                "deleting operation %s for model %s "
                "for being redundant after compression" %\
                    (operation, model.__name__))
            session.delete(operation)
            continue
    return session.query(Operation).\
        filter(Operation.version_id == None).\
        order_by(Operation.order.asc()).all()

def compressed_operations(operations):
    """
    Compresses a set of operations so as to avoid redundant
    ones. Returns the compressed set sorted by operation order. This
    procedure doesn't perform database operations.
    """
    seqs = group_by(lambda op: (op.row_id, op.content_type_id),
                    sorted(operations, key=attr('order')))
    compressed = []
    for seq in seqs.itervalues():
        if len(seq) == 1:
            compressed.append(seq[0])
        elif seq[0].command == 'i':
            if seq[-1].command == 'd':
                pass
            else:
                compressed.append(seq[0])
        elif seq[0].command == 'u':
            if seq[-1].command == 'd':
                compressed.append(seq[-1])
            else:
                compressed.append(seq[0])
        else: # seq[0].command == 'd':
            if seq[-1].command == 'd':
                compressed.append(seq[0])
            elif seq[-1].command == 'u':
                compressed.append(seq[-1])
            else: # seq[-1].command == 'i':
                op = seq[-1]
                compressed.append(
                    Operation(order=op.order,
                              content_type_id=op.content_type_id,
                              row_id=op.row_id,
                              version_id=op.version_id,
                              command='u'))
    compressed.sort(key=attr('order'))
    return compressed

@core.session_committing
def unsynched_objects(session=None):
    """
    Returns a list of triads (class, id, operation) that represents
    the unsynchronized objects in the tracked database.

    The first element of each triad is the class for the
    unsynchronized object.

    The second element is the primary key *value* of the object.

    The third element is a character in ``('i', 'u', 'd')`` that
    represents the operation that altered the objects state (insert,
    update or delete). If it's a delete, the object won't be present
    in the tracked database.

    Because of compatibility issues, this procedure will only return
    triads for classes marked for both push and pull handling.
    """
    ops = compress(session=session)
    def getclass(op):
        class_ = op.tracked_model
        if class_ is None: return None
        if class_ not in core.pulled_models or class_ not in core.pushed_models:
            return None
        return class_
    triads = [
        (c, op.row_id, op.command)
        for c, op in ((getclass(op), op) for op in ops)
        if c is not None]
    return triads

@core.session_committing
def trim(session=None):
    "Trims the internal synchronization tables, to free space."
    last_id = core.get_latest_version_id(session=session)
    session.query(Operation).filter(Operation.version_id != None).delete()
    session.query(Version).filter(Version.version_id != last_id).delete()


text:
import {PullRequestListTrigger} from "../logic/triggers";
var TriggerMixin = require("../logic/triggers").TriggerMixin([
    PullRequestListTrigger
]);
var React = require("react");
var Link = require("react-router").Link;
var PrSearcher = require("../components/pr-searcher");
var GprHeader = require("../components/gpr-header");

// Values of _renderPRs's display param
const displayOwner = "displayOwner";

module.exports = React.createClass({displayName: 'ListPage',
    mixins: [TriggerMixin],

    componentDidMount: function() {
        if (!this.props.sessionStore.getAccessToken()) {
            this.props.history.pushState(null, "/");
        }
    },

    propTypes: {
        controller: React.PropTypes.any.isRequired,
        listController: React.PropTypes.any,
        sessionStore: React.PropTypes.any
    },

    render: function() {
        var prList = this.getTrigger(PullRequestListTrigger);
        if (!prList || Object.keys(prList).length === 0) {
            this.props.listController.getOpenPullRequests();
            return (

                <GprHeader showBackLink={false} />
                Loading...

);
        }
        if (prList.error) {
            return (

                <GprHeader showBackLink={false} />
                Error: {prList.error}

);
        }

        var assigned = [].concat(
            this._renderPRs(
                "Awaiting your review:",
                prList.assignedPulls.assignedNeedsAction,
                displayOwner
            ),
            this._renderPRs(
                "Others last commented:",
                prList.assignedPulls.assignedOthersInvolved,
                displayOwner
            ),
            this._renderPRs(
                "Awaiting their action:",
                prList.assignedPulls.assignedNoAction,
                displayOwner
            )
        );
        if (assigned.length === 0) {
            assigned = "None";
        }

        var owned = [].concat(
            this._renderPRs("Awaiting your response:", prList.myPulls.awaitingAction),
            this._renderPRs("Reviewed (but not LGTM):", prList.myPulls.reviewed),
            this._renderPRs("LGTM:", prList.myPulls.lgtmed),
            this._renderPRs("Unassigned:", prList.myPulls.unassigned),
            this._renderPRs("Awaiting review:", prList.myPulls.awaitingReview)
        );
        if (owned.length === 0) {
            owned = "None";
        }

        return (

            <GprHeader showBackLink={false} />

Assigned to you:

            {assigned}

Owned by you:

            {owned}
            <PrSearcher controller={this.props.controller} history={this.props.history} />

        );
    },

    _renderPRs: function(heading, pulls, display) {
        if (!pulls.length) {
            return [];
        }
        return [
            (<h2 key={`h2-${heading}`}>{heading}
),
            (<ul key={`ul-${heading}`}>{pulls.map(function(pr) {
            var keySuffix = "pr-" + pr.getRepo() + "/" + pr.getId();
            var who = (display === displayOwner) ? pr.getOwner() : pr.getAssignee();
            if (who) {
                who = who.getUserLinkJsx("user-" + keySuffix);
            }
            else {
                who = "";
            }
            var repoUrl = "https://github.com/" + pr.getRepo();
            return (
                <li key={`li-${keySuffix}`}>
                    <Link to={`/repos/${pr.getRepo()}/${pr.getId()}`} key={`link-${keySuffix}`}>
                    {pr.getTitle()}
                    </Link> - <a href={repoUrl} target="_blank" key={`a-${keySuffix}`}>
                    {pr.getRepo()}
                     <a href={`${repoUrl}/pull/${pr.getId()}`} key={`a2-${keySuffix}`}>
                    #{pr.getId()}
                     {who}

            );
        })}
)];
    }
});


text:
<Title>Boost Graph Library: King Ordering</Title>

<TT>king_ordering</TT>

Graphs:
undirected

Properties:
color, degree

Complexity:
time: O(m2log(m)|E|) where m = max { degree(v) | v in V }

  (1)
  template <class IncidenceGraph, class OutputIterator,
            class ColorMap, class DegreeMap, class VertexIndexMap>
  OutputIterator
  king_ordering(const IncidenceGraph& g,
                typename graph_traits<Graph>::vertex_descriptor s,
                OutputIterator inverse_permutation,
                ColorMap color, DegreeMap degree, VertexIndexMap index_map);

  (2)
  template <class IncidenceGraph, class OutputIterator>
  OutputIterator
  king_ordering(const IncidenceGraph& g, OutputIterator inverse_permutation);

  template <class IncidenceGraph, class OutputItrator, class VertexIndexMap>
  OutputIterator
  king_ordering(const IncidenceGraph& g, OutputIterator inverse_permutation,
                VertexIndexMap index_map);

  template <class VertexListGraph, class OutputIterator,
            class ColorMap, class DegreeMap, class VertexIndexMap>
  OutputIterator
  king_ordering(const VertexListGraph& G, OutputIterator inverse_permutation,
                ColorMap color, DegreeMap degree, VertexIndexMap index_map);

  (3)
  template <class IncidenceGraph, class OutputIterator,
            class ColorMap, class DegreeMap, class VertexIndexMap>
  OutputIterator
  king_ordering(const IncidenceGraph& g,
    		std::deque< typename
		graph_traits<Graph>::vertex_descriptor > vertex_queue,
                OutputIterator permutation,
                ColorMap color, DegreeMap degree, VertexIndexMap index_map);

The goal of the King ordering
algorithm [62]is to reduce the bandwidth of a graph by reordering the
indices assigned to each vertex.  The King ordering algorithm
works by a local minimization of the i-th bandwidths. The vertices are
basically assigned a breadth-first search order, except that at each
step, the adjacent vertices are placed in the queue in order of
increasing pseudo-degree, where pseudo-degree is defined as the number of
outgoing edges with white endpoints (vertices yet to be examined).

Version 1 of the algorithm lets the user choose the ``starting
vertex'', version 2 finds a good starting vertex using the
pseudo-peripheral pair heuristic (among each component), while version 3
contains the starting nodes for each vertex in the deque.  The choice of the ``starting
vertex'' can have a significant effect on the quality of the ordering.

The output of the algorithm are the vertices in the new ordering.
Storing the output into a vector gives you the
permutation from the new ordering to the old ordering.

  inv_perm[new_index[u]] == u

Often times, it is the opposite permutation that you want, the
permutation from the old index to the new index. This can easily be
computed in the following way.

  for (size_type i = 0; i != inv_perm.size(); ++i)
    perm[old_index[inv_perm[i]]] = i;

Parameters

For version 1:

 <tt>IncidenceGraph& g</tt>  (IN)

  An undirected graph. The graph's type must be a model of IncidenceGraph.

  Python: The parameter is named <tt>graph</tt>.

 <tt>vertex_descriptor s</tt> &nbsp(IN)

  The starting vertex.

  Python: Unsupported parameter.

 <tt>OutputIterator permutation</tt> &nbsp(OUT)

  The new vertex ordering. The vertices are written to the output
  iterator in their new order.

  Python: This parameter is unused in Python. The new vertex
  ordering is returned as a Python <tt>list</tt>.

 <tt>ColorMap color_map</tt> &nbsp(WORK)

  Used internally to keep track of the progress of the algorithm
  (to avoid visiting the same vertex twice).

  Python: Unsupported parameter.

 <tt>DegreeMap degree_map</tt> &nbsp(IN)

  This must map vertices to their degree.

  Python: Unsupported parameter.

For version 2:

 <tt>VertexListGraph& g</tt>  (IN)

  An undirected graph. The graph's type must be a model of VertexListGraph.

  Python: The name of this parameter is <tt>graph</tt>.

 <tt>
  OutputIterator permutation</tt> &nbsp(OUT)

  The new vertex ordering. The vertices are written to the
  output iterator in their new order.

  Python: This parameter is unused in Python. The new vertex
  ordering is returned as a Python <tt>list</tt>.

 <tt>ColorMap color_map</tt> &nbsp(WORK)

  Used internally to keep track of the progress of the algorithm
  (to avoid visiting the same vertex twice).

  Python: Unsupported parameter.

 <tt>DegreeMap degree_map</tt> &nbsp(IN)

  This must map vertices to their degree.

  Python: Unsupported parameter.

For version 3:

 <tt>IncidenceGraph& g</tt>  (IN)

  An undirected graph. The graph's type must be a model of IncidenceGraph.

  Python: The parameter is named <tt>graph</tt>.

 <tt> std::deque< typename graph_traits<Graph>::vertex_descriptor > vertex_queue </tt> &nbsp(IN)

  The deque containing the starting vertices for each component.

  Python: This parameter is unused in Python. The new vertex
  ordering is returned as a Python <tt>list</tt>.

 <tt>OutputIterator permutation</tt> &nbsp(OUT)

  The new vertex ordering. The vertices are written to the output
  iterator in their new order.

  Python: This parameter is unused in Python. The new vertex
  ordering is returned as a Python <tt>list</tt>.

 <tt>ColorMap color_map</tt> &nbsp(WORK)

  Used internally to keep track of the progress of the algorithm
  (to avoid visiting the same vertex twice).

  Python: Unsupported parameter.

 <tt>DegreeMap degree_map</tt> &nbsp(IN)

  This must map vertices to their degree.

  Python: Unsupported parameter.

Example

See <tt>example/king_ordering.cpp</tt>.

See Also

bandwidth</tt>,
and <tt>degree_property_map</tt> in <tt>boost/graph/properties.hpp</tt>.

Copyright © 2000-2001
Jeremy Siek, Indiana University (jsiek@osl.iu.edu)


text:
body {
    /*padding-top: 50px;*/
    padding-bottom: 20px;
}

/* Set padding to keep content from hitting the edges */
.body-content {
    padding-left: 15px;
    padding-right: 15px;
}

/* Override the default bootstrap behavior where horizontal description lists
   will truncate terms that are too long to fit in the left column
*/
.dl-horizontal dt {
    white-space: normal;
}

/* Set width on the form input elements since they're 100% wide by default */
input,
select,
textarea {
    max-width: 280px;
}

body {
    margin: 0px;
}
.suiteBar {
    position: fixed;
    background-color: black;
    width: 100%;
    height: 50px;
    color: white;
    text-align: center;
    line-height: 40px;
}

a {
    text-decoration: none !important;
}

a:hover {
    color: #333 !important;
}


text:
FESTITIME
=========

Festitime is a Student project for an ecommerce website.
The particularity of this website is to be specific to Festivals.
We really think Festival is a particular type of buisness and that really specific features can be developed for it.

------------
Components :
------------

#### Symfony2

    We are using Symfony2 with FOSRestBundle for the API side.

#### MongoDB

    We are using MongoDB with DoctrineMongoDBBundle

#### Angular.js

    We are using Angular.js for the front side intelligence, rendering and filters.

#### Grunt

    We are using Grunt for compiling LESS files.

#### LESS

    We are using LESS for the stylesheets.

#### API Blueprint

    We are using Api Blueprint for generating documentation about our API and in for the continuous amelioration of the project.

---------
Install :
---------

#### Composer

To start you need to install the composer dependencies :

    $ composer install

#### NPM

##### API Blueprint - Protagonist

Before install of basic npm dependencies you need to have **ruby** and **g++** install for the install of protagonist.
**Protagonist** is the Node.js wrapper for Snow Crash library (which is the **API Blueprint Parser**)

So, if one of the previous package is missing run the following command :
+ For Debian :

    `$ sudo apt-get install rubygems`

+ For Ubuntu :

    `$ sudo aptitude install rubygems`

##### Install Dependencies

You also need to install the npm dependencies :

    $ npm install

#### Grunt
You will need Grunt, so if you don't already have grunt-cli install, run the following command :

    $ npm install -g grunt-cli

#### Bower
you will also need bower dependencies:

    $ bower install

If bower isn't already installed you need to run :

    $ npm install -g bower

#### VHOST
#####basic configuration :
First run the following command :

    $ sudo nano /etc/apache2/sites-available/festitime.dev

It will open an editor in your terminal, put the following content inside and save it :

        <VirtualHost *:80>
                SetEnv FESTITIME_ENV dev
                ServerAdmin webmaster@localhost
                ServerName festitime.dev
                ServerAlias www.festitime.dev

                DocumentRoot /var/www/festitime/web
                <Directory /var/www/festitime/web>
                        Options Indexes FollowSymLinks MultiViews
                        AllowOverride All
                        Order allow,deny
                        allow from all
                </Directory>

                ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/

                ErrorLog ${APACHE_LOG_DIR}/error.log

                # Possible values include: debug, info, notice, warn, error, crit,
                # alert, emerg.
                LogLevel warn

                CustomLog ${APACHE_LOG_DIR}/access.log combined
        </VirtualHost>

Once the file saved run the following commands :

    $ sudo a2ensite festitime.dev
    $ sudo service apache2 reload

You need to register the host (if you're using vagrant you will also need to put it in windows hosts) :

    $ sudo nano /etc/hosts

Put it the following content :

    127.0.0.1       festitime.dev

#####Environment configuration :

You also need to add the aliases for piloting the environment :
first run the command

    $ sudo nano ~/.bashrc

then go at the end of the file and put it the following lines :

    alias ftdev='sudo sed -i "s/FESTITIME_ENV prod/FESTITIME_ENV dev/g" /etc/apache2/sites-available/festitime.dev && sudo service apache2 restart'
    alias ftprod='sudo sed -i "s/FESTITIME_ENV dev/FESTITIME_ENV prod/g" /etc/apache2/sites-available/festitime.dev && sudo service apache2 restart'

#### MongoDB
##### Basic Install

You need to add this apt-key

    $ sudo apt-key adv --keyserver keyserver.ubuntu.com --recv 7F0CEB10
    $ echo 'deb http://downloads-distro.mongodb.org/repo/debian-sysvinit dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list

Then update and upgrade apt-get :

    $ sudo apt-get update
    $ sudo apt-get upgrade

Now you can install MongoDB :

    $ sudo apt-get install mongodb-org
    $ sudo /etc/init.d/mongod restart

Now we are gonna install MongoDB PHP extension :

    $ sudo pecl install mongo
    $ echo "extension=mongo.so" >> /etc/php5/cli/php.ini
    $ echo "extension=mongo.so" >> /etc/php5/cgi/php.ini
    $ echo "extension=mongo.so" >> /etc/php5/apache2/php.ini
    $ sudo /etc/init.d/mongod restart

##### Install festitime DB :

    $ mongo
    $ show dbs
    $ use festitime
    $ exit

-----
USAGE
-----

#### Grunt

Grunt is here to compile less and javascript files.
You're supposed to run

    $ grunt watch

You have to run it in a second terminal, because it will watch you're files during you modify it. And when you make a change in a less or javascript file, grunt will compile it again.

Grunt watch will do some tasks:

1. preprocessing less files into one unique css file : **/assets/dist/css/styles.css**
2. minify styles.css into **/assets/dist/css/styles.min.css**
3. concat javascript files into **/assets/dist/js/built.js**
4. minify and uglify built.js into **/assets/dist/js/built.min.js**
5. clear symfony2 cache for the appropriate environment (in case you forget to clear it)

Grunt also provide a task for building the API.md file (blueprint document)

    $ grunt blueprint2json

This will parse **API.md** and create a **blueprint.json** file in */web/assets/blueprint*

------------


text:
'use strict'
var path = require('path')
var rimraf = require('rimraf')
var fs = require('graceful-fs')
var mkdirp = require('mkdirp')
var asyncMap = require('slide').asyncMap
var andIgnoreErrors = require('../and-ignore-errors.js')

module.exports = function (top, buildpath, pkg, log, next) {
  log.silly('finalize', pkg.path)

  var delpath = path.join(path.dirname(pkg.path), '.' + path.basename(pkg.path) + '.DELETE')

  mkdirp(path.resolve(pkg.path, '..'), whenParentExists)

  function whenParentExists (mkdirEr) {
    if (mkdirEr) return next(mkdirEr)
    // We stat first, because we can't rely on ENOTEMPTY from Windows.
    // Windows, by contrast, gives the generic EPERM of a folder already exists.
    fs.lstat(pkg.path, destStated)
  }

  function destStated (doesNotExist) {
    if (doesNotExist) {
      fs.rename(buildpath, pkg.path, whenMoved)
    } else {
      moveAway()
    }
  }

  function whenMoved (renameEr) {
    if (!renameEr) return next()
    if (renameEr.code !== 'ENOTEMPTY') return next(renameEr)
    moveAway()
  }

  function moveAway () {
    fs.rename(pkg.path, delpath, whenOldMovedAway)
  }

  function whenOldMovedAway (renameEr) {
    if (renameEr) return next(renameEr)
    fs.rename(buildpath, pkg.path, whenConflictMoved)
  }

  function whenConflictMoved (renameEr) {
    // if we got an error we'll try to put back the original module back,
    // succeed or fail though we want the original error that caused this
    if (renameEr) return fs.rename(delpath, pkg.path, function () { next(renameEr) })
    fs.readdir(path.join(delpath, 'node_modules'), makeTarget)
  }

  function makeTarget (readdirEr, files) {
    if (readdirEr) return cleanup()
    if (!files.length) return cleanup()
    mkdirp(path.join(pkg.path, 'node_modules'), function (mkdirEr) { moveModules(mkdirEr, files) })
  }

  function moveModules (mkdirEr, files) {
    if (mkdirEr) return next(mkdirEr)
    asyncMap(files, function (file, done) {
      var from = path.join(delpath, 'node_modules', file)
      var to = path.join(pkg.path, 'node_modules', file)
      // we ignore errors here, because they can legitimately happen, for instance,
      // bundled modules will be in both node_modules folders
      fs.rename(from, to, andIgnoreErrors(done))
    }, cleanup)
  }

  function cleanup () {
    rimraf(delpath, afterCleanup)
  }

  function afterCleanup (rimrafEr) {
    if (rimrafEr) log.warn('finalize', rimrafEr)
    next()
  }
}

module.exports.rollback = function (buildpath, pkg, next) {
  var top = path.resolve(buildpath, '..')
  rimraf(pkg.path, function () {
    removeEmptyParents(pkg.path)
  })
  function removeEmptyParents (pkgdir) {
    if (path.relative(top, pkgdir)[0] === '.') return next()
    fs.rmdir(pkgdir, function (er) {
      // FIXME: Make sure windows does what we want here
      if (er && er.code !== 'ENOENT') return next()
      removeEmptyParents(path.resolve(pkgdir, '..'))
    })
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Notes.Client.Helpers
{
    public class Constants
    {
        public static readonly string ClientAddress = "https://cloudservicenotesservice.azurewebsites.net";
    }
}


text:
/**
* @file CUOTerrainInfo.h
*
*/

#ifndef _INC_CUOTERRAININFO_H
#define _INC_CUOTERRAININFO_H

#include "CUOTerrainTypeRec.h"
#include "uofiles_types.h"

struct CUOTerrainInfo : public CUOTerrainTypeRec_HS
{
    CUOTerrainInfo( TERRAIN_TYPE id );
};

#endif //_INC_CUOTERRAININFO_H


text:
package net.herit.iot.db.mongo;

import java.util.Arrays;
import java.util.Collections;
import java.util.Map;

import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoClientURI;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.WriteConcern;
import com.mongodb.client.MongoDatabase;

import java.util.logging.Level;
import java.util.logging.Logger;

import org.bson.Document;

public class MongoPool {
	private final static MongoPool INSTANCE = new MongoPool();

	private MongoClient mongoClient = null;
//	private String serverAddr;
//	private int serverPort;
	private String databaseName;
//	private String userName;
//	private String userPasswd;

	private MongoPool() {}

	public static MongoPool getInstance() {
		return INSTANCE;
	}

	public boolean initialize(String serverAddr, int serverPort, String databaseName,
								String userName, String userPasswd) {
		if(serverAddr == null) serverAddr = "localhost";

		if(serverPort <= 0 || databaseName == null) {
			System.out.println("Database Server port or database name invalid..");
			return false;
		}

//		this.serverAddr = serverAddr;
//		this.serverPort = serverPort;
		this.databaseName = databaseName;
//		this.userName = userName;
//		this.userPasswd = userPasswd;

		if(userName != null || userPasswd != null) {
			//MongoCredential credential = MongoCredential.createCredential(userName, databaseName, userPasswd.toCharArray());		// blocked in 2017-11-10
			MongoCredential credential = MongoCredential.createScramSha1Credential(userName, databaseName, userPasswd.toCharArray());		// added in 2017-11-10 to support Mongodb authentication
			mongoClient = new MongoClient(new ServerAddress(serverAddr, serverPort), Arrays.asList(credential));

		} else {
		//	mongoClient = new MongoClient(serverAddr, serverPort);
			MongoClientOptions options = new MongoClientOptions.Builder()
			.threadsAllowedToBlockForConnectionMultiplier(20)
			.maxConnectionIdleTime(60000)
			.connectionsPerHost(512)
		//	.minConnectionsPerHost(64)
			.build();
		//	.socketTimeout(180000)
		//	.socketKeepAlive(true)
			//.writeConcern(WriteConcern.SAFE)
			//.connectTimeout(1000).build();

			mongoClient = new MongoClient(serverAddr + ":" + serverPort, options);

			//MongoClientURI  uri = new MongoClientURI("mongodb://" + serverAddr + ":" + serverPort + "/?minPoolSize=100&maxPoolSize=200");
			//mongoClient = new MongoClient(uri);
		}

		Logger mongoLogger = Logger.getLogger( "com.mongodb" );
		mongoLogger.setLevel(Level.SEVERE);
		//mongoLogger.setLevel(Level.INFO);

		return true;
	}

	public MongoDatabase getDatabase() {
		return mongoClient.getDatabase(databaseName);
	}

	public int getCurrConnection() {
		MongoDatabase db = mongoClient.getDatabase("admin");
		Document serverStatus = db.runCommand(new Document("serverStatus", 1));
		Map connMap = (Map)serverStatus.get("connections");

		return (Integer)connMap.get("current");
	}

}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package World2D.Objects;

import Physics2D.Vector2;
import World2D.Camera;
import java.awt.Graphics2D;
import java.util.Date;

/**
 *
 * @author bowen
 */
public interface DisplayObject {

    public void renderTransform(Graphics2D g2, Camera camera); //part of the rendering requiring affine transforms
    public void renderNoTransform(Graphics2D g2, Camera camera); //part of the rendering without transforms (per pixel)

    //public void setPos(double x, double y);
    public void registerUpdate(Date date);

    public boolean isVisible(double scale);

    public void hide();
    public void show();

    public double getX();
    public double getY();

    public double getSx(Camera camera);
    public double getSy(Camera camera);
    public double getSr(Camera camera);

    public static double getSx(double x, double offsetX, Camera camera) {
        return ((x + (offsetX - camera.getxPos())) * camera.getScale() + camera.getxScrOffset());
    }

    public static double getSy(double y, double offsetY, Camera camera) {
        return ((y + (offsetY + camera.getyPos())) * -camera.getScale() + camera.getyScrOffset());
    }

    public static double getSr(double radius, Camera camera) {
        double rOut = (Math.log10(radius)-6)*3;
        double rIn = radius*camera.getScale();
        double r = (rIn > rOut) ? rIn : rOut;
        return r;
    }

}


text:
The c++ example agent has the following dependencies:

      Armadillo     >= 4.200.0
      Boost (system, thread)
      CMake         >= 2.8.5

## Installation

First, checkout the repository and change into the unpacked c++ client directory:

      git clone https://github.com/zoq/gym_tcp_api.git
      cd gym_tcp_api/cpp/

Then, make a build directory. The directory can have any name, not just 'build', but 'build' is sufficient.

      $ mkdir build
      $ cd build

The next step is to run CMake to configure the project. Running CMake is the equivalent to running ./configure with autotools

      $ cmake ../

Once CMake is configured, building the the example agent is as simple as typing 'make'.

      $ make

In a separate terminal, you can then run the example agent:

      $ ./example


text:
package edu.cmu.cs.stage3.alice.scenegraph.renderer.directx7renderer;

class OrthographicCameraProxy extends edu.cmu.cs.stage3.alice.scenegraph.renderer.nativerenderer.OrthographicCameraProxy {
    //from ElementProxy
    protected native void createNativeInstance();
    protected native void releaseNativeInstance();
    //from ComponentProxy
    protected native void onAbsoluteTransformationChange( javax.vecmath.Matrix4d m );
    protected native void addToScene( edu.cmu.cs.stage3.alice.scenegraph.renderer.nativerenderer.SceneProxy scene );
    protected native void removeFromScene( edu.cmu.cs.stage3.alice.scenegraph.renderer.nativerenderer.SceneProxy scene );
    //from CameraProxy
    protected native void onNearClippingPlaneDistanceChange( double value );
    protected native void onFarClippingPlaneDistanceChange( double value );
    protected native void onBackgroundChange( edu.cmu.cs.stage3.alice.scenegraph.renderer.nativerenderer.BackgroundProxy value );
    //from OrthographicCameraProxy
	protected native void onPlaneChange( double left, double top, double right, double bottom );
}


text:
use crate::descriptor_set::DescriptorSetWithOffsets;

/// A collection of descriptor set objects.
pub unsafe trait DescriptorSetsCollection {
    fn into_vec(self) -> Vec<DescriptorSetWithOffsets>;
}

unsafe impl DescriptorSetsCollection for () {
    #[inline]
    fn into_vec(self) -> Vec<DescriptorSetWithOffsets> {
        vec![]
    }
}

unsafe impl<T> DescriptorSetsCollection for T
where
    T: Into<DescriptorSetWithOffsets>,
{
    fn into_vec(self) -> Vec<DescriptorSetWithOffsets> {
        vec![self.into()]
    }
}

unsafe impl<T> DescriptorSetsCollection for Vec<T>
where
    T: Into<DescriptorSetWithOffsets>,
{
    fn into_vec(self) -> Vec<DescriptorSetWithOffsets> {
        self.into_iter().map(|x| x.into()).collect()
    }
}

macro_rules! impl_collection {
    ($first:ident $(, $others:ident)+) => (
        unsafe impl<$first$(, $others)+> DescriptorSetsCollection for ($first, $($others),+)
            where $first: Into<DescriptorSetWithOffsets>
                  $(, $others: Into<DescriptorSetWithOffsets>)*
        {
            #[inline]
            #[allow(non_snake_case)]
            fn into_vec(self) -> Vec<DescriptorSetWithOffsets> {
                let ($first, $($others,)*) = self;
                vec![$first.into() $(, $others.into())+]
            }
        }

        impl_collection!($($others),+);
    );

    ($i:ident) => ();
}

impl_collection!(Z, Y, X, W, V, U, T, S, R, Q, P, O, N, M, L, K, J, I, H, G, F, E, D, C, B, A);


text:
<?php

//// FORMS ////
use API\REST\V1\ACL\Company\Client\Form\ClientFormGET;
use API\REST\V1\ACL\Company\Clientfile\Form\ClientfileForm;
use API\REST\V1\ACL\Company\Clientfile\Form\ClientfileFormGET;
use API\REST\V1\ACL\Company\Clientfile\Form\ClientfileFormToShowUpdate;
use API\REST\V1\ACL\Company\Clientfile\Form\ClientfileFormPostPut;

//// FILTERS ////
use API\REST\V1\ACL\Company\Clientfile\Filter\ClientfileFilterPostPut;

//// SHARED ////
use API\REST\V1\Shared\Functions\HttpRequest;
use API\REST\V1\Shared\Functions\ArrayResponse;

/**
 * Skeleton subclass for representing a row from the 'clientfile' table.
 *
 *
 *
 * You should add additional methods to this class to meet the
 * application requirements.  This class will only be generated as
 * long as it does not already exist in the output directory.
 *
 * @package    propel.generator.api
 */
class Clientfile extends BaseClientfile
{

    /**
     * @param $idResource
     * @param $idCompany
     * @return bool
     */
    public function isIdValidResource($idResource,$idCompany){
        return ClientQuery::create()
            ->filterByIdclient($idResource)
            ->filterByIdcompany($idCompany)
            ->exists();
    }

    /**
     * @param $idResource
     * @param $idResourceChild
     * @return bool
     */
    public function isIdValidResurceChild($idResourceChild, $idCompany){
        return ClientfileQuery::create()
            ->filterByIdclientfile($idResourceChild)
            ->useClientQuery()
                ->filterByIdcompany($idCompany)
            ->endUse()
            ->exists();
    }

    /////////// Start create ///////////
    /**
     * @param $dataArray
     * @param $idCompany
     * @param $userLevel
     * @param null $data
     * @return array
     */
    public function saveResouce($dataArray,$idCompany,$userLevel, $data=null){

        // Agregamos por defecto la fecha del server en la columna clientfile_uploaddate
        $dataArray['clientfile_uploaddate'] = date("Y-m-d H:i:s");

        foreach ($dataArray as $dataKey => $dataValue){
            $this->setByName($dataKey,$dataValue,  BasePeer::TYPE_FIELDNAME);
        }
        $this->save();

        //Las columnas permitidas de nuestros foreign keys
        $allowedClientfileColumns = array();

        $client = null;
        //Validamos los foreign Keys a los que va tener acceso el usuario para instanciar nuestros formularios
        if(array_key_exists("idclient", $dataArray)){

            //Instanciamos nuestro objeto Client
            $client = $this->getClient();

            //Instanciamos nuestro formulario clientGET para obtener los datos que el usuario de acuerdo a su nivel va tener accesso
            $clientForm   = ClientFormGET::init($userLevel);

            foreach ($clientForm->getElements() as $element){
                if($element->getOption('value_options')!=null){
                    $allowedClientfileColumns[$element->getAttribute('name')] = array('label' => $element->getOption('label') ,'value_options' => $element->getOption('value_options'));
                }else{
                    $allowedClientfileColumns[$element->getAttribute('name')] = $element->getOption('label');
                }
            }
        }
        //Mandamos a llamar a nuestra funcion create para darle el formato a nuestra respuesta pasandole los siguientes parametros
        //1. El objeto branch "this"
        //2. Los elementos que van a ir como _embebed para removerlos(en este caso idcompany),
        //3. Las columnas permitidas e los foreignKeys
        //4. el objeto company que va ir como __embebed = "client"
        $bodyResponse = $this->createBodyResponse($this,array('idclient'),array('client' => $allowedClientfileColumns),array($client));
        $this->save();
        return array('status_code' => 201, 'details' => $bodyResponse);

    }

    /**
     * @param $clientfile
     * @param array $voidElements
     * @param array $allowedColumns
     * @param array $halResources
     * @return array
     */
    public function createBodyResponse($clientfile, array $voidElements = null, array $allowedColumns,array $halResources=null){

        //Guardamos en un arrglo los datos de nuestro recurso
        $clientfileArray = $clientfile->toArray(\BasePeer::TYPE_FIELDNAME);

        //Verificamos si hay elementos que hay que remover
        if($voidElements!=null){
            foreach ($voidElements as $element){
                unset($clientfileArray[$element]);
            }
        }

        //Comnezamos a darle formato a nuestra respuesta.

        //Los links
        $body = array(
            "_links" => array(
                "self" => array(
                    "href" =>URL_API.'/v'.API_VERSION.'/'.MODULE.'/client/'.ID_RESOURCE.'/file/'.$clientfile->getPrimaryKey()
                ),
            ),
        );

        //Los datos del recurso
        foreach ($clientfileArray as $clientfileKey => $clientfileValue){
            $body[$clientfileKey] = $clientfileValue; // Los datos del recurso
        }

        //Verificamos si hay elementos recursos _embebed
        if($halResources!=null){
            foreach ($halResources as $halResource){
                if($halResource!=null){
                    if(!isset($body[strtolower(get_class($halResource))])){
                        $body[strtolower(get_class($halResource))] = array(
                            "_links" => array(
                                "self" => array(
                                    "href" =>URL_API.'/v'.API_VERSION.'/'.MODULE.'/'.strtolower(get_class($halResource)).'/'.$halResource->getPrimaryKey()
                                ),
                            ),
                        );
                        $halResourceArray = $halResource->toArray(\BasePeer::TYPE_FIELDNAME);
                        $halResourceName = strtolower(get_class($halResource));

                        //Los datos del recurso __embedded
                        if(isset($allowedColumns[$halResourceName])){
                            foreach($allowedColumns[$halResourceName] as $column => $value){
                                $body[$halResourceName][$column] = $halResourceArray[$column];
                            }
                        }
                    }else{
                        $body[strtolower(get_class($halResource))] = array(
                            "_links" => array(
                                "self" => array(
                                    "href" =>URL_API.'/v'.API_VERSION.'/'.MODULE.'/'.strtolower(get_class($halResource)).'/'.$halResource->getPrimaryKey()
                                ),
                            ),
                        );
                        if(isset($allowedColumns[$halResourceName])){
                            foreach($allowedColumns[$halResourceName] as $column){
                                $body[$halResourceName][$column] = $halResourceArray[$column];
                            }
                        }
                    }
                }
            }
        }

        $body[strtolower(get_class($halResource))] = array(
            'idclient' => $body['client']['idclient'],
            'client_firstname' => $body['client']['client_firstname'],
            'client_lastname' => $body['client']['client_lastname'],
        );

        // Retornamos nuestra respuesta
        return $body;
    }
    /////////// End create ///////////

    /////////// Start get ///////////
    /**
     *
     * @param type $id
     * @param array $allowedColumns
     * @return type
     */

    public function getEntity($id){
        $entity = ClientfileQuery::create()->findPk($id);
        return $entity;
    }

    /**
     *
     * @param type $entity
     * @param array $allowedColumns
     * @return array
     */

    public function getEntityResponse($entity,$userLevel){
        //Obtenemos nuestra entidad clientfile en forma de arreglo
        $entityArray = $entity->toArray(BasePeer::TYPE_FIELDNAME);

        $response = array();

        //El ACL
        //Instanciamos nuestros formularios para obtener las columnas que el usuario va poder tener acceso
        $clientfileForm = ClientfileFormGET::init($userLevel);
        $clientForm = ClientFormGET::init($userLevel);

        foreach($clientfileForm->getElements() as $element){
            if($element->getOption('value_options')!=null){
                $response["ACL"][$element->getAttribute('name')] = array('label' => $element->getOption('label') ,'value_options' => $element->getOption('value_options'));
            }else{
                if($element->getAttribute('name')!="idclient"){
                    $response["ACL"][$element->getAttribute('name')] = $element->getOption('label');
                }
            }
        }
        $response["ACL"]["client"]=array(
            "idclient" =>  $clientForm->get("idclient")->getOption('label'),
            "client_firstname" =>  $clientForm->get("client_firstname")->getOption('label'),
            "client_lastname" =>  $clientForm->get("client_lastname")->getOption('label'),
        );

        //Los Links
        $response['_links'] = array(
            "self" => array(
                "href" =>  URL_API."/v".API_VERSION."/".MODULE."/client/".ID_RESOURCE.'/file/'.$entity->getIdclientfile(),
            ),
        );

        foreach($clientfileForm->getElements() as $element){
            if($element->getOption('value_options')!=null){
                $response[$element->getAttribute('name')] = $entityArray[$element->getAttribute('name')];
            }else{
                if($element->getAttribute('name')!="idclient"){
                    $response[$element->getAttribute('name')] = $entityArray[$element->getAttribute('name')];
                }
            }
        }
        $client = $entity->getClient();
        $response["client"] = array(
            "_links" => array(
                "self" => array(
                    "href" =>  URL_API."/v".API_VERSION."/".MODULE."/client/".$client->getIdclient(),
                ),
            ),
            "idclient" => $client->getIdclient(),
            "client_firstname" => $client->getClientFirstName(),
            "client_lastname" => $client->getClientLastName()
        );

        return $response;
    }
    /////////// End get ///////////

    ///// Start getList /////
    /**
     * @param $idCompany
     * @param $page
     * @param $limit
     * @param $filters
     * @param $order
     * @param $dir
     * @return array
     */
    public function getCollection($idCompany, $page, $limit, $filters, $order, $dir){
        $clientfileQuery = new ClientfileQuery();

        //Los Filtros
        if($filters!=null){
            foreach($filters as $filter){
                $params = $clientfileQuery->getParams();
                if(isset($filter['in'])){
                    if(!empty($params)){
                        foreach($params as $param){
                            if($filter['attribute'] == $param['column']){
                                $flag = true;
                            }else{
                                $flag=false;
                            }
                        }
                        if($flag){
                            $clientfileQuery->addOr('clientfile'.$filter['attribute'], $filter['in'], \Criteria::IN);
                        }else{
                            $clientfileQuery->addAnd('clientfile.'.$filter['attribute'], $filter['in'], \Criteria::IN);
                        }
                    }else{
                        $clientfileQuery->filterBy(BasePeer::translateFieldname('clientfile', $filter['attribute'], BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_PHPNAME), $filter['in'], \Criteria::IN);
                    }
                }
                if(isset($filter['neq'])){
                    if(!empty($params)){
                        foreach($params as $param){
                            if($filter['attribute'] = $param['column']){
                                $clientfileQuery->addOr('clientfile.'.$filter['attribute'], $filter['neq'], \Criteria::NOT_EQUAL);
                            }
                        }
                    }else{
                        $clientfileQuery->filterBy(BasePeer::translateFieldname('clientfile', $filter['attribute'], BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_PHPNAME), $filter['neq'], \Criteria::NOT_EQUAL);
                    }
                }
                if(isset($filter['gt'])){
                    $clientfileQuery->filterBy(BasePeer::translateFieldname('clientfile', $filter['attribute'], BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_PHPNAME), $filter['gt'], \Criteria::GREATER_THAN);
                }
                if(isset($filter['lt'])){
                    $clientfileQuery->filterBy(BasePeer::translateFieldname('clientfile', $filter['attribute'], BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_PHPNAME), $filter['lt'], \Criteria::LESS_THAN);
                }
                if(isset($filter['from']) && isset($filter['to'])){
                    $clientfileQuery->filterBy(BasePeer::translateFieldname('clientfile', $filter['attribute'], BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_PHPNAME), $filter['from'], \Criteria::GREATER_EQUAL)
                        ->add(BasePeer::translateFieldname('clientfile', $filter['attribute'], BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_PHPNAME), $filter['to'], \Criteria::LESS_EQUAL);
                }
                if(isset($filter['like'])){
                    $clientfileQuery->filterBy(BasePeer::translateFieldname('clientfile', $filter['attribute'], BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_PHPNAME), $filter['like'], \Criteria::LIKE);
                }
            }
        }
        //Order y Dir
        if($order !=null || $dir !=null){
            $clientfileQuery->orderBy($order, $dir);
        }

        // Obtenemos el filtrado por medio del idcompany del recurso.
        $result =  $clientfileQuery->useClientQuery()->filterByIdcompany($idCompany)->filterByIdclient(ID_RESOURCE)->endUse()->paginate($page,$limit);

        $links = array(
            'self' => array('href' => URL_API.'/v'.API_VERSION.'/'.MODULE.'/client/'.ID_RESOURCE.'/file?page='.$result->getPage()),
            'prev' => array('href' => URL_API.'/v'.API_VERSION.'/'.MODULE.'/client/'.ID_RESOURCE.'/file?page='.$result->getPreviousPage()),
            'next' => array('href' => URL_API.'/v'.API_VERSION.'/'.MODULE.'/client/'.ID_RESOURCE.'/file?page='.$result->getNextPage()),
            'first' => array('href' => URL_API.'/v'.API_VERSION.'/'.MODULE.'/client/'.ID_RESOURCE.'/file'),
            'last' => array('href' => URL_API.'/v'.API_VERSION.'/'.MODULE.'/client/'.ID_RESOURCE.'/file?page='.$result->getLastPage()),
        );

        if($result->getPreviousPage() == 1){
            unset($links['prev']);
        }
        if($result->isLastPage()){
            unset($links['next']);
        }

        $resume = array(
            'currentPage' => $result->getPage(),
            'itemsPerPage' => $result->getMaxPerPage(),
            'totalItems' => $result->count(),
            'lastPage' => $result->getLastPage(),
        );

        $data = $result->getResults()->toArray(null,false,BasePeer::TYPE_FIELDNAME);

        $resultArray = array(
            'links' => $links,
            'resume' => $resume,
            'data' => $data
        );

        //Retornamos nuestro resultado
        return $resultArray;

    }

    /**
     * @param $getCollection
     * @param $userLevel
     * @return array
     */
    public function getCollectionResponse($getCollection, $userLevel){
        // Instanciamos el Formulario GET de nuestro recurso department
        $clientfileFormGET = ClientfileFormGET::init($userLevel);
        $clientFormGET = ClientFormGET::init($userLevel);
        $clientfileArray = array();
        $clientQuery = ClientQuery::create()->findPk(ID_RESOURCE)->toArray(BasePeer::TYPE_FIELDNAME);

        foreach ($getCollection['data'] as $item){

            $clientfileQuery = ClientfileQuery::create()->filterByIdclientfile($item['idclientfile'])->findOne();
            $file = $clientfileQuery->toArray(BasePeer::TYPE_FIELDNAME);

            $row = array(
                "_links" => array(
                    'self' => array('href' => URL_API.'/'.MODULE.'/client/'.$file['idclient'].'/file/'.$file['idclientfile']),
                ),
            );

            foreach($clientfileFormGET->getElements() as $key=>$value){
                $row[$key] = $file[$key];
            }

            array_push($clientfileArray, $row);
        }

        // Start ACL //
        //Guardamos en un arreglo las columnas y los atributos a los que el usuario tiene permiso
        $acl = array();
        foreach ($clientfileFormGET->getElements() as $element){
            if($element->getOption('value_options')!=null){
                $acl[$element->getAttribute('name')] = array('viewName' => $element->getOption('label') ,'value_options' => $element->getOption('value_options'));
            }else{
                $acl[$element->getAttribute('name')] = $element->getOption('label');
            }
        }
        // End ACL //
        unset($acl['idclient']);
        $response = array(
            '_links' => $getCollection['links'],
            'ACL' => $acl,
            'resume' => $getCollection['resume'],
            'client' => array(
                '_links' => array(
                    'self' => array('href' => URL_API.'/'.MODULE.'/client/'.$clientQuery['idclient']),
                ),
                'idclient' => $clientQuery['idclient'],
                'client_firstname' => $clientQuery['client_firstname'],
                'client_lastname' => $clientQuery['client_lastname'],
            ),
            'files' => $clientfileArray,
        );
        switch(TYPE_RESPONSE){
            case "xml" :{
                $response['files'] = array(
                    'file' => $clientfileArray
                );
                break;
            }
        }

        return $response;

    }
    ///// End getList /////

    /////////// Start update ///////////
    public function updateResource($data, $idCompany, $userLevel, $request, $response){

        $idclientfile = $data['idclientfile'];
        //Instanciamos nuestra clientfileQuery
        $clientfileQuery = ClientfileQuery::create();

        //Verificamos que el idclientfile que se quiere modificar exista y que pretenece a la compañia
        if($clientfileQuery->create()->filterByIdclientfile($idclientfile)->useClientQuery()->filterByIdCompany($idCompany)->endUse()->exists()){

            //Instanciamos nuestra clientfileQuery
            $clientfilePKQuery = $clientfileQuery->findPk($idclientfile);
            $clientfileFormToShowUpdate = ClientfileFormToShowUpdate::init($userLevel);

            $clientfileDataArray = $clientfilePKQuery->toArray(BasePeer::TYPE_FIELDNAME);

            // La funcion resourceData retorna un array de los datos que son enviados por el body
            $clientfileArray = HttpRequest::resourceUpdateData($data, $request, $response, 'Clientfile');

            // Actualizamos clientfile_uploaddate con la fecha del server actual.
            $clientfileArray['clientfile_uploaddate'] = date("Y-m-d H:i:s");

            // Instanciamos el formulario clientfileForm()
            $clientfileForm = new ClientfileForm();
            // Insertamos los valores que tiene el registro por defecto a nuestro clientfileArray
            foreach($clientfilePKQuery as $key => $value){
                foreach($clientfileForm->getElements() as $keys => $values){
                    // Validamos que solo se inserten las columnas de nuestro formulario
                    if($key == $keys){
                        if(!is_null($value) && is_null($clientfileArray[$keys])){
                            $clientfileArray[$key] = $value;
                        }
                    }
                }
            }

            //Remplzamos los datos de la clientfile por lo que se van a modificar
            foreach ($clientfileArray as $key => $value){
                $clientfilePKQuery->setByName($key, $value, BasePeer::TYPE_FIELDNAME);
            }

            // Instanciamos nuestro formulario ClientfileFormPostPut
            $clientfileFormPostPut = ClientfileFormPostPut::init($userLevel);
            //Le ponemos los datos a nuestro formulario
            $clientfileFormPostPut->setData($clientfileArray);

            // Instanciamos nuestro filtro ClientfileFilterPostPut
            $clientfileFilterPostPut = new ClientfileFilterPostPut();

            //Le ponemos el filtro a nuestro formulario
            $clientfileFormPostPut->setInputFilter($clientfileFilterPostPut->getInputFilter($userLevel));
            //Si los valores son validos
            if($clientfileFormPostPut->isValid()){

                //Si hay valores por modificar
                if($clientfilePKQuery->isModified()){

                    $clientfilePKQuery->save();

                    //Le damos formato a nuestra respuesta
                    $bodyResponse = array(
                        "_links" => array(
                            'self' => URL_API.'/v'.API_VERSION.'/'.MODULE.'/client/'.ID_RESOURCE.'/file/'.$clientfilePKQuery->getIdclientfile(),
                        ),
                    );

                    foreach ($clientfilePKQuery->toArray(BasePeer::TYPE_FIELDNAME) as $key => $value){
                        $bodyResponse[$key] = $value;
                    }

                    //Eliminamos los campos que hacen referencia a otras tablas
                    unset($bodyResponse['idclient']);

                    //Agregamos el campo embedded a nuestro arreglo
                    $objectClient = $clientfilePKQuery->getClient()->toArray(BasePeer::TYPE_FIELDNAME);

                    //Instanciamos nuestro formulario clientGET para obtener los datos que el usuario de acuerdo a su nivel va tener accesso
                    $clientForm = ClientFormGET::init($userLevel);

                    $clientArray = array();
                    foreach ($clientForm->getElements() as $key=>$value){
                        $clientArray[$key] = $objectClient[$key];
                    }
                    $bodyResponse['client'] = array(
                        '_links' => array(
                            'self' => array('href' => URL_API.'/'.MODULE.'/client/'.$clientfilePKQuery->getIdclient()),
                        ),
                    );

                    //Agregamos los datod de company a nuestro arreglo $row['_embedded']['client']
                    foreach ($clientArray as $key=>$value){
                        $bodyResponse['client'][$key] = $value;
                    }

                    $bodyResponse['client'] = array(
                        'idclient' => $bodyResponse['client']['idclient'],
                        'client_firstname' => $bodyResponse['client']['client_firstname'],
                        'client_lastname' => $bodyResponse['client']['client_lastname'],
                    );

                    return array('status_code' => 200, 'details' => $bodyResponse);

                }else{
                    $messageArray = array();
                    foreach ($clientfileFormToShowUpdate->getElements() as $key => $value){
                        //Obtenemos el nombre de la columna
                        $message = $key;
                        array_push($messageArray, $message);
                    }
                    $bodyResponse = 'No changes were found';
                    return array('status_code' => 304, 'details' => $bodyResponse, 'columns_to_do_changes' => $messageArray);
                }
            }else{
                //Identificamos cual fue la columna que dio problemas y la enviamos como mensaje
                $messageArray = array();
                foreach ($clientfileFormPostPut->getMessages() as $key => $value){
                    foreach($value as $val){
                        //Obtenemos el valor de la columna con error
                        $message = $key.' '.$val;
                        array_push($messageArray, $message);
                    }
                }
                return array('status_code' => 409, 'details' => $messageArray);
            }
        }else{

            $bodyResponse = 'Invalid idclientfile';
            return array('status_code' => 409, 'details' => $bodyResponse);
        }
    }
    /////////// End update ///////////

    /////////// Start delete ///////////
    /**
     * @param $id
     * @param $userLevel
     * @return bool
     */
    public function deleteEntity($id,$userLevel) {

        //Reglas de negocio
        if($userLevel>=4){
            ClientfileQuery::create()->filterByIdclientfile($id)->delete();
            return true;
        }
        return false;

    }
    /////////// End delete ///////////
}


text:
package com.amar.hello2.service.push;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.amar.hello2.ServiceActivity_;

import cn.jpush.android.api.JPushInterface;

/**
 * 自定义接收器
 * 如果不定义这个 Receiver,则:
 * 1) 默认用户会打开主界面
 * 2) 接收不到自定义消息
 */
public class MyReceiver extends BroadcastReceiver
{
    private static final String TAG = "JPush";

    @Override
    public void onReceive( Context context,Intent intent )
    {
        Bundle bundle = intent.getExtras();
        Log.d( TAG,"[MyReceiver] onReceive - " + intent.getAction() + ", extras: " + printBundle( bundle ) );

        if ( JPushInterface.ACTION_REGISTRATION_ID.equals( intent.getAction() ) )
        {
            String regId = bundle.getString( JPushInterface.EXTRA_REGISTRATION_ID );
            Log.d( TAG,"[MyReceiver] 接收Registration Id : " + regId );
            // send the Registration Id to your server...

        }
        else if ( JPushInterface.ACTION_MESSAGE_RECEIVED.equals( intent.getAction() ) )
        {
            Log.d( TAG,"[MyReceiver] 接收到推送下来的自定义消息: " + bundle.getString( JPushInterface.EXTRA_MESSAGE ) );
            processCustomMessage( context,bundle );
        }
        else if ( JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals( intent.getAction() ) )
        {
            Log.d( TAG,"[MyReceiver] 接收到推送下来的通知" );
            int notifactionId = bundle.getInt( JPushInterface.EXTRA_NOTIFICATION_ID );
            processCustomMessage( context,bundle );
            Log.d( TAG,"[MyReceiver] 接收到推送下来的通知的ID: " + notifactionId );
        }
        else if ( JPushInterface.ACTION_NOTIFICATION_OPENED.equals( intent.getAction() ) )
        {
            Log.d( TAG,"[MyReceiver] 用户点击打开了通知" );

            // 打开自定义的Activity
            Intent i = new Intent( context,ServiceActivity_.class );
            i.putExtras( bundle );
            // i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            i.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
            context.startActivity( i );

        }
        else if ( JPushInterface.ACTION_RICHPUSH_CALLBACK.equals( intent.getAction() ) )
        {
            Log.d( TAG,"[MyReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString( JPushInterface.EXTRA_EXTRA ) );
            // 在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码,比如打开新的Activity, 打开一个网页等..

        }
        else if ( JPushInterface.ACTION_CONNECTION_CHANGE.equals( intent.getAction() ) )
        {
            boolean connected = intent.getBooleanExtra( JPushInterface.EXTRA_CONNECTION_CHANGE,false );
            Log.w( TAG,"[MyReceiver]" + intent.getAction() + " connected state change to " + connected );
        }
        else
        {
            Log.d( TAG,"[MyReceiver] Unhandled intent - " + intent.getAction() );
        }
    }

    // 打印所有的 intent extra 数据
    private static String printBundle( Bundle bundle )
    {
        StringBuilder sb = new StringBuilder();
        for ( String key : bundle.keySet() )
        {
            if ( key.equals( JPushInterface.EXTRA_NOTIFICATION_ID ) )
            {
                sb.append( "\nkey:" + key + ", value:" + bundle.getInt( key ) );
            }
            else if ( key.equals( JPushInterface.EXTRA_CONNECTION_CHANGE ) )
            {
                sb.append( "\nkey:" + key + ", value:" + bundle.getBoolean( key ) );
            }
            else
            {
                sb.append( "\nkey:" + key + ", value:" + bundle.getString( key ) );
            }
        }
        return sb.toString();
    }

    // send msg to MainActivity
    private void processCustomMessage( Context context,Bundle bundle )
    {
        if ( ServiceActivity_.isForeground )
        {
            String alert = bundle.getString( JPushInterface.EXTRA_ALERT );
            //String message = bundle.getString( JPushInterface.EXTRA_MESSAGE );
            String extras = bundle.getString( JPushInterface.EXTRA_EXTRA );
            Intent msgIntent = new Intent( ServiceActivity_.MESSAGE_RECEIVED_ACTION );
            msgIntent.putExtra( ServiceActivity_.KEY_MESSAGE,alert );
            if ( !ExampleUtil.isEmpty( extras ) )
            {
                try
                {
                    JSONObject extraJson = new JSONObject( extras );
                    if ( null != extraJson && extraJson.length() > 0 )
                    {
                        msgIntent.putExtra( ServiceActivity_.KEY_EXTRAS,extras );
                    }
                }
                catch ( JSONException e )
                {

                }
            }
            context.sendBroadcast( msgIntent );
        }
    }
}