text:
package com.hae.pipe.stages;

import java.util.*;

import com.hae.pipe.*;

/**
 * ──STEM──word──┬──────────────┬──
 *               ├─APPEND───────┤
 *               └─FROM──number─┘
 */
public class Stem extends Stage {
	public int execute(String args) throws PipeException {
		signalOnError();
		try {
			commit(-1);

			boolean firstStage = (stageNum() == 1);
			boolean append = false;
			// note that the public API for the offset is 1-based, but
			// internally, we use 0-based offsets
			int     startOffset = 0;

			// make sure we have a stem name
			PipeArgs pa = new PipeArgs(args);
			String stemName = scanWord(pa);
			if ("".equals(stemName))
				return exitCommand(-231);

			String arg = scanWord(pa);
			if (Syntax.abbrev("APPEND", arg, 6)) {
				append = true;
				arg = scanWord(pa);
			}
			if (Syntax.abbrev("FROM", arg, 4)) {
				arg = scanWord(pa);
				if (Syntax.isNumber(arg)) {
					// convert to 0-based offset
					startOffset = Integer.parseInt(arg)-1;
					arg = scanWord(pa);
				}
				else {
					// invalid number
					return exitCommand(-58, arg);
				}
			}
			if (!"".equals(arg)) {
				// extra parameters
				return exitCommand(-112, arg);
			}

			// make sure APPEND and FROM aren't both passed
			if (append && startOffset != 0)
				return exitCommand(-14, "APPEND and FROM");

			commit(0);

			// if first in the pipe, then we read, otherwise
			// we are writing to the collection
			if (firstStage) {
				// first stage, so we output records
				Object collection = getParameter(stemName);
				if (collection == null) {
					// null input, so we don't need to output anything
					return 0;
				}
				else if (collection instanceof List) {
					// handle a java.io.List
					List<?> list = (List<?>)collection;
					for (int i = startOffset; i < list.size(); i++) {
						Object o = list.get(i);
						output(o == null ? "" : o.toString());
					}
				}
				else if (collection instanceof Object[]) {
					// handle an array
					Object[] list = (Object[])collection;
					for (int i = startOffset; i < list.length; i++) {
						Object o = list[i];
						output(o == null ? "" : o.toString());
					}
				}
				else {
					// unknown data type
					return exitCommand(-235, stemName+"("+collection.getClass().getName()+")");
				}
			}
			else {
				// we are writing to a stem...
				Object collection = getParameter(stemName);
				if (collection == null)
					collection = new ArrayList<String>();

				// note that although we can read from arrays of
				// objects, we only ever write to a List.
				if (collection instanceof List) {
					putParameter(stemName, collection);

					@SuppressWarnings("unchecked")
					List<String> list = (List<String>)collection;

					// now if we are supposed to start writing at an
					// offset that is greater than the number of current
					// records, then we fill the list until it has enough
					while (startOffset > list.size())
						list.add(null);

					// are we connected to an output stream?
					boolean shouldWrite = (streamState(OUTPUT, 0) == 0);

					int i = startOffset;
					String s = peekto();
					while (true) {
						// store into the list...
						if (i >= list.size())
							list.add(s);
						else
							list.set(i, s);

						// and write to output stream if possible
						if (shouldWrite)
							output(s);

						// consume the record and wait for the next one
						readto();
						s = peekto();
						i++;
					}
				}
				else {
					// unknown data type
					return exitCommand(-235, stemName+"("+collection.getClass().getName()+")");
				}
			}
		}
		catch(EOFException e) {
		}
		return 0;
	}
}


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

package org.apache.hadoop.fs.kfs;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URI;

import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.BlockLocation;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.util.Progressable;

/**
 * A FileSystem backed by KFS.
 *
 */
@InterfaceAudience.Public
@InterfaceStability.Stable
public class KosmosFileSystem extends FileSystem {

    private FileSystem localFs;
    private IFSImpl kfsImpl = null;
    private URI uri;
    private Path workingDir = new Path("/");

    public KosmosFileSystem() {

    }

    KosmosFileSystem(IFSImpl fsimpl) {
        this.kfsImpl = fsimpl;
    }

    @Override
    public URI getUri() {
	return uri;
    }

    @Override
    public void initialize(URI uri, Configuration conf) throws IOException {
      super.initialize(uri, conf);
      try {
        if (kfsImpl == null) {
          if (uri.getHost() == null) {
            kfsImpl = new KFSImpl(conf.get("fs.kfs.metaServerHost", ""),
                                  conf.getInt("fs.kfs.metaServerPort", -1),
                                  statistics);
          } else {
            kfsImpl = new KFSImpl(uri.getHost(), uri.getPort(), statistics);
          }
        }

        this.localFs = FileSystem.getLocal(conf);
        this.uri = URI.create(uri.getScheme() + "://" + uri.getAuthority());
        this.workingDir = new Path("/user", System.getProperty("user.name")
                                   ).makeQualified(this);
        setConf(conf);

      } catch (Exception e) {
        e.printStackTrace();
        System.out.println("Unable to initialize KFS");
        System.exit(-1);
      }
    }

    @Override
    public Path getWorkingDirectory() {
	return workingDir;
    }

    @Override
    public void setWorkingDirectory(Path dir) {
	workingDir = makeAbsolute(dir);
    }

    private Path makeAbsolute(Path path) {
	if (path.isAbsolute()) {
	    return path;
	}
	return new Path(workingDir, path);
    }

    @Override
    public boolean mkdirs(Path path, FsPermission permission
        ) throws IOException {
	Path absolute = makeAbsolute(path);
        String srep = absolute.toUri().getPath();

	int res;

	// System.out.println("Calling mkdirs on: " + srep);

	res = kfsImpl.mkdirs(srep);

	return res == 0;
    }

    @Override
    public boolean isDirectory(Path path) throws IOException {
	Path absolute = makeAbsolute(path);
        String srep = absolute.toUri().getPath();

	// System.out.println("Calling isdir on: " + srep);

        return kfsImpl.isDirectory(srep);
    }

    @Override
    public boolean isFile(Path path) throws IOException {
	Path absolute = makeAbsolute(path);
        String srep = absolute.toUri().getPath();
        return kfsImpl.isFile(srep);
    }

    @Override
    public FileStatus[] listStatus(Path path) throws IOException {
        Path absolute = makeAbsolute(path);
        String srep = absolute.toUri().getPath();

        if(!kfsImpl.exists(srep))
          throw new FileNotFoundException("File " + path + " does not exist.");

        if (kfsImpl.isFile(srep))
                return new FileStatus[] { getFileStatus(path) } ;

        return kfsImpl.readdirplus(absolute);
    }

    @Override
    public FileStatus getFileStatus(Path path) throws IOException {
	Path absolute = makeAbsolute(path);
        String srep = absolute.toUri().getPath();
        if (!kfsImpl.exists(srep)) {
          throw new FileNotFoundException("File " + path + " does not exist.");
        }
        if (kfsImpl.isDirectory(srep)) {
            // System.out.println("Status of path: " + path + " is dir");
            return new FileStatus(0, true, 1, 0, kfsImpl.getModificationTime(srep),
                                  path.makeQualified(this));
        } else {
            // System.out.println("Status of path: " + path + " is file");
            return new FileStatus(kfsImpl.filesize(srep), false,
                                  kfsImpl.getReplication(srep),
                                  getDefaultBlockSize(),
                                  kfsImpl.getModificationTime(srep),
                                  path.makeQualified(this));
        }
    }

    @Override
    public FSDataOutputStream append(Path f, int bufferSize,
        Progressable progress) throws IOException {
        Path parent = f.getParent();
        if (parent != null && !mkdirs(parent)) {
            throw new IOException("Mkdirs failed to create " + parent);
        }

        Path absolute = makeAbsolute(f);
        String srep = absolute.toUri().getPath();

        return kfsImpl.append(srep, bufferSize, progress);
    }

    @Override
    public FSDataOutputStream create(Path file, FsPermission permission,
                                     boolean overwrite, int bufferSize,
				     short replication, long blockSize, Progressable progress)
	throws IOException {

        if (exists(file)) {
            if (overwrite) {
                delete(file, true);
            } else {
                throw new IOException("File already exists: " + file);
            }
        }

	Path parent = file.getParent();
	if (parent != null && !mkdirs(parent)) {
	    throw new IOException("Mkdirs failed to create " + parent);
	}

        Path absolute = makeAbsolute(file);
        String srep = absolute.toUri().getPath();

        return kfsImpl.create(srep, replication, bufferSize, progress);
    }

    @Override
    public FSDataInputStream open(Path path, int bufferSize) throws IOException {
        if (!exists(path))
            throw new IOException("File does not exist: " + path);

        Path absolute = makeAbsolute(path);
        String srep = absolute.toUri().getPath();

        return kfsImpl.open(srep, bufferSize);
    }

    @Override
    public boolean rename(Path src, Path dst) throws IOException {
	Path absoluteS = makeAbsolute(src);
        String srepS = absoluteS.toUri().getPath();
	Path absoluteD = makeAbsolute(dst);
        String srepD = absoluteD.toUri().getPath();

        // System.out.println("Calling rename on: " + srepS + " -> " + srepD);

        return kfsImpl.rename(srepS, srepD) == 0;
    }

    // recursively delete the directory and its contents
    @Override
    public boolean delete(Path path, boolean recursive) throws IOException {
      Path absolute = makeAbsolute(path);
      String srep = absolute.toUri().getPath();
      if (kfsImpl.isFile(srep))
        return kfsImpl.remove(srep) == 0;

      FileStatus[] dirEntries = listStatus(absolute);
      if (!recursive && (dirEntries.length != 0)) {
        throw new IOException("Directory " + path.toString() +
        " is not empty.");
      }

      for (int i = 0; i < dirEntries.length; i++) {
        delete(new Path(absolute, dirEntries[i].getPath()), recursive);
      }
      return kfsImpl.rmdir(srep) == 0;
    }

    @Override
    public short getDefaultReplication() {
	return 3;
    }

    @Override
    public boolean setReplication(Path path, short replication)
	throws IOException {

	Path absolute = makeAbsolute(path);
        String srep = absolute.toUri().getPath();

        int res = kfsImpl.setReplication(srep, replication);
        return res >= 0;
    }

    // 64MB is the KFS block size

    @Override
    public long getDefaultBlockSize() {
	return 1 << 26;
    }

    @Deprecated
    public void lock(Path path, boolean shared) throws IOException {

    }

    @Deprecated
    public void release(Path path) throws IOException {

    }

    /**
     * Return null if the file doesn't exist; otherwise, get the
     * locations of the various chunks of the file file from KFS.
     */
    @Override
    public BlockLocation[] getFileBlockLocations(FileStatus file, long start,
        long len) throws IOException {

      if (file == null) {
        return null;
      }
      String srep = makeAbsolute(file.getPath()).toUri().getPath();
      String[][] hints = kfsImpl.getDataLocation(srep, start, len);
      if (hints == null) {
        return null;
      }
      BlockLocation[] result = new BlockLocation[hints.length];
      long blockSize = getDefaultBlockSize();
      long length = len;
      long blockStart = start;
      for(int i=0; i < result.length; ++i) {
        result[i] = new BlockLocation(null, hints[i], blockStart,
                                      length < blockSize ? length : blockSize);
        blockStart += blockSize;
        length -= blockSize;
      }
      return result;
    }

    @Override
    public void copyFromLocalFile(boolean delSrc, Path src, Path dst) throws IOException {
	FileUtil.copy(localFs, src, this, dst, delSrc, getConf());
    }

    @Override
    public void copyToLocalFile(boolean delSrc, Path src, Path dst) throws IOException {
	FileUtil.copy(this, src, localFs, dst, delSrc, getConf());
    }

    @Override
    public Path startLocalOutput(Path fsOutputFile, Path tmpLocalFile)
	throws IOException {
	return tmpLocalFile;
    }

    @Override
    public void completeLocalOutput(Path fsOutputFile, Path tmpLocalFile)
	throws IOException {
	moveFromLocalFile(tmpLocalFile, fsOutputFile);
    }
}

redpajama_set_name: RedPajamaGithub


text:
#ifndef DataTransferItemList_h
#define DataTransferItemList_h

#if ENABLE(DATA_TRANSFER_ITEMS)

#include "DataTransferItem.h"
#include <wtf/Forward.h>
#include <wtf/RefCounted.h>

namespace WebCore {

class File;

typedef int ExceptionCode;

class DataTransferItemList : public RefCounted<DataTransferItemList> {
public:
    virtual ~DataTransferItemList() { }

    virtual size_t length() const = 0;
    virtual PassRefPtr<DataTransferItem> item(unsigned long index) = 0;
    virtual void deleteItem(unsigned long index, ExceptionCode&) = 0;
    virtual void clear() = 0;
    virtual void add(const String& data, const String& type, ExceptionCode&) = 0;
    virtual void add(PassRefPtr<File>) = 0;
};

} // namespace WebCore

#endif // ENABLE(DATA_TRANSFER_ITEMS)

#endif // DataTransferItemList_h


text:
namespace brickred::codec {

class Sha256 {
public:
    Sha256();
    ~Sha256();
    void reset();

    void update(const char *buffer, size_t size);
    void digest(char hash[32]);
    std::string digest();

private:
    BRICKRED_NONCOPYABLE(Sha256)

    uint32_t hash_[8];
    uint8_t work_block_[64];
    uint64_t message_size_;
};

std::string sha256(const std::string &str);
std::string sha256(const char *buffer, size_t size);
std::string sha256Binary(const std::string &str);
std::string sha256Binary(const char *buffer, size_t size);

} // namespace brickred::codec

#endif


text:
/// <reference path='_all.ts' />

module angularShift.shiftEntries {

    /**
     * The interface for the shift entries we are getting from the api.
     */
    export interface ShiftEntryInterface {
        id : number;
        shift: angularShift.shifts.ShiftInterface;
        angelType : angularShift.neededAngels.AngelType;
        UID : number;
        Comment: string;
        freeload_comment:string;
        freeloaded: number;
    };
};


text:
<!--
Copyright 2016 Goldman Sachs.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
-->
<FlatFileParserConfig
       delimiter="|"
       inflatedObject="com.gs.fw.para.domain.transaction.implementation.RivukifEpEfojuxugikoLufe"
       columns="60"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:noNamespaceSchemaLocation="../../xsd/parserconfig.xsd">
   <Header required="true" identifier="NASAVU:" simpleFormat="NASAVU:[hojakinipo]*FUZASINADU:[hojakinipo][yyyy/WE/dd]"/>
   <Trailer required="true" identifier="KABANAS:" simpleFormat="KABANAS:[hojakinipo][count]*"/>

   <Mapping attribute="fijifiSovoli" position = "2"        />
   <Mapping attribute="suyewejexOcis" position = "6"        />
   <Mapping attribute="zefewaWitatu" position = "16"        />
   <Mapping attribute="raxokaCeyubupa" position = "19"      />
   <Mapping attribute="sepuneNimaj" position = "20"         />
   <Mapping attribute="description" position="21"           />
   <Mapping attribute="tavibexakIxez" position = "22"       />
   <Mapping attribute="vosufecEzag" position = "23"         />
   <Mapping attribute="koxiqoneTudomuJo" position = "27"    />

   <FixedValue attribute="josonica" value="0.0"/>
   <FixedValue attribute="qiyuXexayasas" value="[~]"/>

</FlatFileParserConfig>


text:
import isObject from 'lodash/isObject';

/**
 * Track an event to analytics providers (e.g. Google Analytics, Mixpanel).
 *
 * @param {string} event_category Typically the object interacted with, e.g. 'Clipboard'
 * @param {string} event_action The type of interaction, e.g. 'Add item'
 * @param {object} event_data (Optional) Properties to include about the
 *     event, e.g. {title: 'Sparks Fly'}
 */
export function track(event_category, event_action, event_data) {
  var event_data_string = '';
  if (isObject(event_data)) {
    event_data_string = JSON.stringify(event_data);
  }

  if (window.DEBUG) {
    // eslint-disable-next-line no-console
    console.log(
      `Sample analytics event:"${event_category}: ${event_action}"`,
      `\n${event_data_string}`
    );
    return;
  }

  // eslint-disable-next-line no-console
  console.log(
    `Tracking analytics event "${event_category}: ${event_action}"`,
    ` ${event_data_string}`
  );

  window.gtag &&
    window.gtag('event', event_action, {
      ...event_data,
      event_category: event_category,
      event_label: event_data_string,
    });

  // TODO(davidhu): Uncomment this in the next PR that adds Mixpanel tracking
  //window.mixpanel && mixpanel.track(`${event_category}: ${event_action}`, event_data);
}

export default track;


text:
<?xml version="1.0" encoding="utf-8"?>
<databaseChangeLog
    xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">

    <include file="classpath:config/liquibase/changelog/00000000000000_initial_schema.xml" relativeToChangelogFile="false"/>
    <include file="classpath:config/liquibase/changelog/20150627193612_added_entity_Author.xml" relativeToChangelogFile="false"/>
    <include file="classpath:config/liquibase/changelog/20150627201451_added_entity_Book.xml" relativeToChangelogFile="false"/>
    <!-- JHipster will add liquibase changelogs here -->
</databaseChangeLog>


text:
import time
import threading
import usb.core
import usb.util
import array
import cairocffi
import rgbtools
import cProfile

_FRAMES_PER_SECOND = 60.0

class DisplayParameters:
  DISPLAY_WIDTH = 960
  DISPLAY_HEIGHT = 160

  BUFFER_WIDTH = 1024
  BUFFER_HEIGHT = 160

class DisplayRenderer(threading.Thread):
  '''
  DisplayRenderer is an abstract superclass implementing logic to
  push frames (rendered with Cairo) to the Push 2's display.  To use,
  override the paint(context) method, instantiate an instance, and call
  start().

  Since this spawns a background thread to do the actual work of
  interacting with the Push, subclasses will want to make sure to use
  the appropriate synchronization mechanisms when working with data
  inside paint that may be used from other threads.
  '''

  _MAGIC_HEADER = array.array('B', [ 0xFF, 0xCC, 0xAA, 0x88,
                                     0x00, 0x00, 0x00, 0x00,
                                     0x00, 0x00, 0x00, 0x00,
                                     0x00, 0x00, 0x00, 0x00 ]);

  _PUSH_VID = 0x2982
  _PUSH_PID = 0x1967

  def __init__(self, group=None, target=None, name=None, args=(), kwargs={}):
    threading.Thread.__init__(self, group=group, target=target, name=name, args=args, kwargs=kwargs)
    self.cancelled = threading.Event()

  def paint(self, context):
    raise NotImplementedError("Subclasses must implement paint")

  def cancel(self):
    self.cancelled.set()

  def is_cancelled(self):
    return self.cancelled.is_set()

  def run(self):
    dev = usb.core.find(idVendor=DisplayRenderer._PUSH_VID, idProduct=DisplayRenderer._PUSH_PID)

    if dev is None:
      raise ValueError("Device not found")

    dev.set_configuration()

    surface = cairocffi.ImageSurface(cairocffi.FORMAT_RGB16_565, DisplayParameters.BUFFER_WIDTH, DisplayParameters.BUFFER_HEIGHT)
    context = cairocffi.Context(surface)
    while not self.is_cancelled():
      start = time.clock()

      with context:
        self.paint(context)

      surface.flush()

      data = surface.get_data()
      convertedBgr = rgbtools.rgb565ToBgr565(data)
      shapedBgr = rgbtools.shaping(convertedBgr)

      end = time.clock()

      dev.write(1, DisplayRenderer._MAGIC_HEADER)
      dev.write(1, shapedBgr)

      frameTime = end - start

      if(frameTime < (1.0 / _FRAMES_PER_SECOND)):
        time.sleep((1.0 / _FRAMES_PER_SECOND) - frameTime)
      else:
        time.sleep(1.0 / _FRAMES_PER_SECOND)

class ProfiledDisplayRenderer(DisplayRenderer):
    # Overrides threading.Thread.run()
    def run(self):
        profiler = cProfile.Profile()
        try:
            return profiler.runcall(DisplayRenderer.run, self)
        finally:
            profiler.dump_stats('myprofile-%d.profile' % (self.ident,))


text:
title: jet steps
menus:
  pro/jet:
    title: jet steps
    weight: 9
categories:
  - CLI
tags:
  - jet
  - usage
  - cli
  - pro
  - steps
---

## Description
Run your CodeShip Pro pipeline steps.

## Usage

```
jet steps [flags]
```

## Flags
{% include jet_flag_table.html flags=site.data.jet.flags.steps %}

## Extended description
Executing the `jet steps` command will build the services defined in the [codeship-services.yml]({{ site.baseurl }}{% link _pro/builds-and-configuration/services.md %}) file, and execute the steps in the [codeship-steps.yml]({{ site.baseurl }}{% link _pro/builds-and-configuration/steps.md %}) file.

The `jet steps` command skips [push steps]({{ site.baseurl }}{% link _pro/builds-and-configuration/steps.md %}#push-steps) and [branch/tag specific steps]({{ site.baseurl }}{% link _pro/builds-and-configuration/steps.md %}#limiting-steps-to-specific-branches-or-tags) unless the appropriate flags are passed to the command.

Docker will use existing images when running `jet` locally. This may lead to builds passing locally, and failing remotely on CodeShip. This is due to the remote environment starting without any prior images. We recommend removing any locally saved Docker images prior to running `jet steps` for a more consistent result to the remote server.

## Examples

### Steps with Push

```shell
$ jet steps --push
(step: tests)
...
(step: tests) success ✔
(step: push_service)
...
```

Using the `--push` flag will execute any [push steps]({{ site.baseurl }}{% link _pro/builds-and-configuration/steps.md %}#push-steps) in the [codeship-steps.yml]({{ site.baseurl }}{% link _pro/builds-and-configuration/steps.md %}) file. If the step is also a [branch/tag specific step]({{ site.baseurl }}{% link _pro/builds-and-configuration/steps.md %}#limiting-steps-to-specific-branches-or-tags), use `--tag` in conjunction with `--push`.

### Specify Branch or Tag
It is often necessary to test [branch/tag specific steps]({{ site.baseurl }}{% link _pro/builds-and-configuration/steps.md %}#limiting-steps-to-specific-branches-or-tags).  To do this, use the `--tag` flag to specify a branch or tag name.

```shell
$ jet steps --tag master

$ jet steps --tag staging
```

### Using CI Flags

A remote build has access to [default environment variables]({{ site.baseurl }}{% link _pro/builds-and-configuration/environment-variables.md%}#default-environment-variables) populated from the SCM. You can pass similar data to test the behavior. A normal practice is to use the `commit-id` in a container tag, for example.

```shell
$ jet steps --ci-commit-id 1234ABCD --ci-branch master --ci-committer-name "Jane Doe" --ci-commit-message "A random message from the committer"
```


text:
package org.pepstock.charba.client.utils.toast.enums;

import org.pepstock.charba.client.commons.Key;

/**
 * The align option defines the position of the toast actions.
 *
 * @author Andrea "Stock" Stocchero
 *
 */
public enum Align implements Key
{
	/**
	 * The actions are centered on the toast.
	 */
	CENTER("center"),
	/**
	 * The actions are positioned to the right of the toast.
	 */
	RIGHT("right"),
	/**
	 * Is the default: the actions are positioned to the left of the toast.
	 */
	LEFT("left");

	// name value of property
	private final String value;

	/**
	 * Creates with the property value to use in the native object.
	 *
	 * @param value value of property name
	 */
	private Align(String value) {
		this.value = value;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see org.pepstock.charba.client.commons.Key#value()
	 */
	@Override
	public String value() {
		return value;
	}

}


text:
import java.util.Deque;
import java.util.LinkedList;
import java.util.Scanner;

/**
 * @author Oleg Cherednik
 * @since 01.11.2017
 */
public class Solution {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int Q = scan.nextInt();
        scan.nextLine();

        StringBuilder buf = new StringBuilder();
        Deque<String> stack = new LinkedList<>();

        for (int i = 0; i < Q; i++) {
            int t = scan.nextInt();

            if (t == 1) {
                buf.append(scan.next());
                stack.push(buf.toString());
            } else if (t == 2) {
                buf.setLength(buf.length() - scan.nextInt());
                stack.push(buf.toString());
            } else if (t == 3)
                System.out.println(buf.toString().charAt(scan.nextInt() - 1));
            else if (t == 4) {
                stack.pop();
                buf.setLength(0);
                buf.append(stack.isEmpty() ? "" : stack.element());
            }
        }

        scan.close();
    }
}


text:
package org.apache.etch.bindings.java.msg;

import java.util.Set;

import org.apache.etch.bindings.java.msg.Validator.Level;

/**
 * Interface which defines the value factory which helps
 * the idl compiler serialize and deserialize messages,
 * convert values, etc.
 */
public interface ValueFactory
{
	//////////
	// Type //
	//////////

	/**
	 * Translates a type id into the appropriate Type object. If the type does
	 * not exist, and if dynamic typing is enabled, adds it to the dynamic types.
	 * @param id a type id.
	 * @return id translated into the appropriate Type.
	 */
	public Type getType( Integer id );

	/**
	 * Translates a type name into the appropriate Type object. If the type does
	 * not exist, and if dynamic typing is enabled, adds it to the dynamic types.
	 * @param name a type name.
	 * @return name translated into the appropriate Type.
	 */
	public Type getType( String name );

	/**
	 * Adds the type if it doesn't already exist. Use this to dynamically add
	 * types to a ValueFactory. The type is per instance of the ValueFactory,
	 * not global. Not available if dynamic typing is locked.
	 * @param type
	 */
	public void addType( Type type );

	/**
	 * Locks the dynamic typing so that no new types may be created by addType
	 * or getType.
	 */
	public void lockDynamicTypes();

	/**
	 * Unlocks the dynamic typing so that new types may be created by addType
	 * or getType.
	 */
	public void unlockDynamicTypes();

	/**
	 * @return a collection of all the types.
	 */
	public Set<Type> getTypes();

	/////////////////////
	// STRING ENCODING //
	/////////////////////

	/**
	 * @return the encoding to use for strings.
	 */
	public String getStringEncoding();

	////////////////
	// MESSAGE ID //
	////////////////

	/**
	 * @param msg the message whose well-known message-id field is to be
	 * returned.
	 * @return the value of the well-known message-id field. This is a
	 * unique identifier for this message on a particular transport
	 * during a particular session. If there is no well-known message-id
	 * field defined, or if the message-id field has not been set, then
	 * return null.
	 */
	public Long getMessageId( Message msg );

	/**
	 * Sets the value of the well-known message-id field. This is a
	 * unique identifier for this message on a particular transport
	 * during a particular session. If there is no well-known message-id
	 * field defined then nothing is done. If msgid is null, then the
	 * field is cleared.
	 * @param msg the message whose well-known message-id field is to
	 * be set.
	 * @param msgid the value of the well-known message-id field.
	 */
	public void setMessageId( Message msg, Long msgid );

	/**
	 * @return well-known message field for message id.
	 */
	public Field get_mf__messageId();

	/////////////////
	// IN REPLY TO //
	/////////////////

	/**
	 * @param msg the message whose well-known in-reply-to field is to
	 * be returned.
	 * @return the value of the in-reply-to field, or null if there is
	 * none or if there is no such field defined.
	 */
	public Long getInReplyTo( Message msg );

	/**
	 * @param msg the message whose well-known in-reply-to field is to
	 * be set.
	 * @param msgid the value of the well-known in-reply-to field. If
	 * there is no well-known in-reply-to field defined then nothing
	 * is done. If msgid is null, then the field is cleared.
	 */
	public void setInReplyTo( Message msg, Long msgid );

	/**
	 * @return well-known message field for in reply to.
	 */
	public Field get_mf__inReplyTo();

	//////////////////////
	// VALUE CONVERSION //
	//////////////////////

	/**
	 * Converts a value to a struct value representation to be exported
	 * to a tagged data output.
	 * @param value a custom type defined by a service, or a well-known
	 * standard type (e.g., date).
	 * @return a struct value representing the value.
	 * @throws UnsupportedOperationException if the type cannot be exported.
	 */
	public StructValue exportCustomValue( Object value )
		throws UnsupportedOperationException;

	/**
	 * Converts a struct value imported from a tagged data input to
	 * a normal type.
	 * @param struct a struct value representation of a custom type, or a
	 * well known standard type.
	 * @return a custom type, or a well known standard type.
	 * @throws UnsupportedOperationException if the type cannot be imported.
	 */
	public Object importCustomValue( StructValue struct )
		throws UnsupportedOperationException;

	/**
	 * @param c the class of a custom value.
	 * @return the struct type of a custom value class.
	 * @throws UnsupportedOperationException
	 * @see #exportCustomValue(Object)
	 */
	public Type getCustomStructType( Class<?> c )
		throws UnsupportedOperationException;

	/**
	 * @return well-known message type for exception thrown by one-way
	 * message.
	 */
	public Type get_mt__exception();

	/**
	 * @return the validation level of field StructValue.put and TaggedDataOutput.
	 */
	public Level getLevel();

	/**
	 * Sets the validation level of field StructValue.put and TaggedDataOutput.
	 * @param level
	 * @return the old value
	 */
	public Level setLevel( Level level );
}


text:
class CreateSwattrComments < ActiveRecord::Migration
  def change
    create_table :swattr_comments do |t|
      t.integer :author_id
      t.integer :issue_id
      t.text :body
      t.datetime :deleted_at

      t.timestamps null: false
    end

    add_index :swattr_comments, :deleted_at
  end
end


text:
package ca.uhn.fhir.model.api;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(value= {ElementType.FIELD})
public @interface CodeableConceptElement {

	Class<? extends ICodeEnum> type();

}


text:
package org.codehaus.groovy.classgen.asm;

import org.codehaus.groovy.ast.ClassHelper;
import org.codehaus.groovy.ast.ClassNode;
import org.codehaus.groovy.runtime.BytecodeInterface8;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;

import static org.codehaus.groovy.syntax.Types.*;
import static org.objectweb.asm.Opcodes.*;

public class BinaryIntExpressionHelper extends BinaryExpressionWriter {

    private static final MethodCaller intArrayGet = MethodCaller.newStatic(BytecodeInterface8.class, "intArrayGet");
    private static final MethodCaller intArraySet = MethodCaller.newStatic(BytecodeInterface8.class, "intArraySet");

    private static final int[] stdCompareCodes = {
        IF_ICMPEQ,      // COMPARE_NOT_EQUAL            120
        IF_ICMPNE,      // COMPARE_IDENTICAL            121
        IF_ICMPEQ,      // COMPARE_NOT_IDENTICAL        122
        IF_ICMPNE,      // COMPARE_EQUAL                123
        IF_ICMPGE,      // COMPARE_LESS_THAN            124
        IF_ICMPGT,      // COMPARE_LESS_THAN_EQUAL      125
        IF_ICMPLE,      // COMPARE_GREATER_THAN         126
        IF_ICMPLT,      // COMPARE_GREATER_THAN_EQUAL   127
    };

    private static final int[] stdOperations = {
        IADD,           //  PLUS        200
        ISUB,           //  MINUS       201
        IMUL,           //  MULTIPLY    202
        IDIV,           //  DIV         203
        IDIV,           //  INTDIV      204
        IREM,           //  MOD         203
    };

    private static final int[] bitOp = {
        IOR,            //  BITWISE_OR / PIPE   340
        IAND,           //  BITWISE_AND         341
        IXOR,           //  BIWISE_XOR          342
    };

    /* unhandled types from from org.codehaus.groovy.syntax.Types
    public static final int LOGICAL_OR                  = 162;   // ||
    public static final int LOGICAL_AND                 = 164;   // &&

    public static final int DIVIDE                      = 203;   // /
    public static final int STAR_STAR                   = 206;   // **
    public static final int POWER                       = STAR_STAR;   //

    public static final int PLUS_EQUAL                  = 210;   // +=
    public static final int MINUS_EQUAL                 = 211;   // -=
    public static final int MULTIPLY_EQUAL              = 212;   // *=
    public static final int DIVIDE_EQUAL                = 213;   // /=
    public static final int INTDIV_EQUAL                = 214;   // \=
    public static final int MOD_EQUAL                   = 215;   // %=
    public static final int POWER_EQUAL                 = 216;   // **=

    public static final int PLUS_PLUS                   = 250;   // ++
    public static final int PREFIX_PLUS_PLUS            = 251;   // ++
    public static final int POSTFIX_PLUS_PLUS           = 252;   // ++
    public static final int PREFIX_PLUS                 = 253;   // +

    public static final int MINUS_MINUS                 = 260;   // --
    public static final int PREFIX_MINUS_MINUS          = 261;   // --
    public static final int POSTFIX_MINUS_MINUS         = 262;   // --
    public static final int PREFIX_MINUS                = 263;   // - (negation)
*/
    private static final int[] shiftOp = {
        ISHL,           // LEFT_SHIFT               280
        ISHR,           // RIGHT_SHIFT              281
        IUSHR           // RIGHT_SHIFT_UNSIGNED     282
    };

/*
    public static final int LEFT_SHIFT_EQUAL            = 285;   // <<=
    public static final int RIGHT_SHIFT_EQUAL           = 286;   // >>=
    public static final int RIGHT_SHIFT_UNSIGNED_EQUAL  = 287;   // >>>=

    public static final int BITWISE_OR_EQUAL            = 350;   // |=
    public static final int BITWISE_AND_EQUAL           = 351;   // &=
    public static final int BITWISE_XOR_EQUAL           = 352;   // ^=
    public static final int BITWISE_NEGATION            = REGEX_PATTERN;    // ~
    */

    private WriterController controller;
    public BinaryIntExpressionHelper(WriterController wc) {
        super(wc);
        controller = wc;
    }

    /**
     * writes a std compare. This involves the tokens IF_ICMPEQ, IF_ICMPNE,
     * IF_ICMPEQ, IF_ICMPNE, IF_ICMPGE, IF_ICMPGT, IF_ICMPLE and IF_ICMPLT
     * @param type the token type
     * @return true if a successful std compare write
     */
    protected boolean writeStdCompare(int type, boolean simulate) {
        type = type-COMPARE_NOT_EQUAL;
        // look if really compare
        if (type<0||type>7) return false;

        if (!simulate) {
            MethodVisitor mv = controller.getMethodVisitor();
            OperandStack operandStack = controller.getOperandStack();
            // operands are on the stack already
            int bytecode = stdCompareCodes[type];
            Label l1 = new Label();
            mv.visitJumpInsn(bytecode,l1);
            mv.visitInsn(ICONST_1);
            Label l2 = new Label();;
            mv.visitJumpInsn(GOTO, l2);
            mv.visitLabel(l1);
            mv.visitInsn(ICONST_0);
            mv.visitLabel(l2);
            operandStack.replace(ClassHelper.boolean_TYPE, 2);
        }
        return true;
    }

    /**
     * writes the spaceship operator, type should be COMPARE_TO
     * @param type the token type
     * @return true if a successful spaceship operator write
     */
    protected boolean writeSpaceship(int type, boolean simulate) {
        if (type != COMPARE_TO) return false;
        /*
           we will actually do

          (x < y) ? -1 : ((x == y) ? 0 : 1)
          which is the essence of what the call with Integers would do
          this compiles to something along

              <x>
              <y>
              IF_ICMPGE L1
              ICONST_M1
              GOTO L2
          L1
              <x>
              <y>
              IF_ICMPNE L3
              ICONST_0
              GOTO L2
          L3
              ICONST_1
          L2

          since the operators are already on the stack and we don't want
          to load them again, we will instead duplicate them. This will
          require some pop actions in the branches!

              DUP2          (operands: IIII)
              IF_ICMPGE L1  (operands: II)
              ICONST_M1     (operands: III)
              GOTO L2
          L1
              -----         (operands: II)
              IF_ICMPNE L3  (operands: -)
              ICONST_0      (operands: I)
              GOTO L2
          L3
              - jump from L1 branch to here (operands: -)
              ICONST_1      (operands: I)
          L2
          - if jump from GOTO L2 we have III, but need only I
          - if from L3 branch we get only I

          this means we have to pop of II before loading -1

        */
        if (!simulate) {
            MethodVisitor mv = controller.getMethodVisitor();
            // duplicate int arguments
            mv.visitInsn(DUP2);

            Label l1 = new Label();
            mv.visitJumpInsn(IF_ICMPGE,l1);
            // no jump, so -1, need to pop off surplus II
            mv.visitInsn(POP2);
            mv.visitInsn(ICONST_M1);
            Label l2 = new Label();;
            mv.visitJumpInsn(GOTO, l2);

            mv.visitLabel(l1);
            Label l3 = new Label();
            mv.visitJumpInsn(IF_ICMPNE,l3);
            mv.visitInsn(ICONST_0);
            mv.visitJumpInsn(GOTO,l2);

            mv.visitLabel(l3);
            mv.visitInsn(ICONST_1);

            controller.getOperandStack().replace(ClassHelper.int_TYPE, 2);
        }
        return true;
    }

    protected void doubleTwoOperands(MethodVisitor mv) {
        mv.visitInsn(DUP2);
    }

    protected MethodCaller getArrayGetCaller() {
        return intArrayGet;
    }

    protected MethodCaller getArraySetCaller() {
        return intArraySet;
    }

    protected int getBitwiseOperationBytecode(int type) {
        return bitOp[type];
    }

    protected int getCompareCode() {
        return -1;
    }

    protected ClassNode getNormalOpResultType() {
        return ClassHelper.int_TYPE;
    }

    protected int getShiftOperationBytecode(int type) {
        return shiftOp[type];
    }

    protected int getStandardOperationBytecode(int type) {
        return stdOperations[type];
    }

    protected void removeTwoOperands(MethodVisitor mv) {
        mv.visitInsn(POP2);
    }

    protected void writeMinusMinus(MethodVisitor mv) {
        mv.visitInsn(ICONST_1);
        mv.visitInsn(ISUB);
    }

    protected void writePlusPlus(MethodVisitor mv) {
        mv.visitInsn(ICONST_1);
        mv.visitInsn(IADD);
    }

    protected ClassNode getDevisionOpResultType() {
        return ClassHelper.int_TYPE;
    }

    @Override
    protected boolean supportsDivision() {
        return true;
    }
}


text:
class CreatePages < ActiveRecord::Migration
  def change
    create_table :pages do |t|
      t.string :slug
      t.string :title
      t.text :content
      t.text :data, limit: 16777215
      t.timestamps
    end

    add_index :pages, :slug, unique: true
  end
end


text:
import {Injectable} from '@angular/core';
import {Http, Headers} from '@angular/http';
import 'rxjs/add/operator/map';
import { Store,ActionReducer, Action,Reducer } from '@ngrx/store';
import {Observable} from 'rxjs/Observable';

const CATEGORY: string = 'DJ';

export interface DJState {
  term?: string;
  results?: Array<any>;
  toggle?: boolean;             // eventid
  mainLoading?: boolean;        // loading
  modalLoading?: boolean;       // modalloading
  modalPlaylist?: boolean;      // playlistModal
  downloadLoading?: boolean;    // downloadloading
  playlistAdd?: boolean;
}
const initialState: DJState = {
  results: [],
  toggle: false,
  mainLoading: false,
  modalLoading: false,
  modalPlaylist: false,
  downloadLoading: false,
  playlistAdd : false
};

interface DJ_ACTIONS {
  TOGGLE_CHK: string;
  MAIN_LOADING: string;
  MODAL_LOADING: string;
  MODAL_Playlist: string;
  DOWNLOAD_LOADING: string;
  PLAYLIST_ADD    : string;

}

export const DJ_ACTIONS: DJ_ACTIONS = {
  TOGGLE_CHK: `[${CATEGORY}] TOGGLE_CHK`,
  MAIN_LOADING: `[${CATEGORY}] MAIN_LOADING`,
  MODAL_LOADING: `[${CATEGORY}] MODAL_LOADING`,
  MODAL_Playlist: `[${CATEGORY}] MODAL_Playlist`,
  DOWNLOAD_LOADING: `[${CATEGORY}] DOWNLOAD_LOADING`,
  PLAYLIST_ADD: `[${CATEGORY}] PLAYLIST_ADD`
};

export const DJReducer: ActionReducer<DJState> = (state: DJState = initialState, action: Action) => {
  let changeState = () => {
    return Object.assign({}, state, action.payload);
  };
  switch (action.type) {
    // 마지막에 작업
    case DJ_ACTIONS.TOGGLE_CHK:
      action.payload.toggle = true;
      return changeState();
    case DJ_ACTIONS.MODAL_LOADING:
     if (typeof action.payload === 'undefined') {
         action.payload = { modalLoading: true};
      }else{
          action.payload = { modalLoading: false};
      }
      return changeState();
    case DJ_ACTIONS.MAIN_LOADING:
     if (typeof action.payload === 'undefined') {
         action.payload = { mainLoading: true , modalPlaylist : true};
      }else{
        action.payload = { mainLoading: false };
      }
      return changeState();
      case DJ_ACTIONS.PLAYLIST_ADD:
     if (typeof action.payload === 'undefined') {
         action.payload = { playlistAdd: false};
      }else{
          action.payload = { playlistAdd: true};
      }
      return changeState();
    default:
      return state;
  };
};

@Injectable()
export class DJService{
    constructor(private _http:Http,private store: Store<any>){
    }
     searchDJ(params){
        var headers = new Headers();
        headers.append('Content-Type', 'application/json');
        return this._http.post('http://localhost:4100/searchDJ', params, {headers: headers})
            .map(res => res.json());
    }
    searchPlaylist(params){
        var headers = new Headers();
        headers.append('Content-Type', 'application/X-www-form-urlencoded');
        return this._http.post('http://localhost:4100/searchPlaylist', params, {headers: headers})
            .map(res => res.json());
    }

}
// http://localhost:4100/
// https://moonedm.herokuapp.com/


text:
#include <stdio.h>

/* Lines with length >= to this will be printed */
#define MIN_LINE_LENGTH 80
#define INITIAL_BUFFER_SIZE 1024
#define BUFFER_GROW_FACTOR 2

int get_array_size(char array[])
{
    return sizeof(array) / sizeof(char);
}

char* expand_array(char array[])
{
    static char new_array[sizeof(array) / sizeof(char) * BUFFER_GROW_FACTOR];

    for (int i = 0; i < get_array_size(array); ++i)
    {
        new_array[i] = array[i];
    }

    return new_array;
}

int get_line(char line[])
{
    int line_length = 0;
    char current_char = EOF;

    while ((current_char = getchar()) != '\n')
    {
        if (get_array_size(line) < line_length)
        {
            line = expand_array(line);
        }

        line[line_length++] = current_char;
    }

    line[line_length] = '\0';

    return line_length;
}

int main()
{
    int current_line_length = 0;
    char current_line[INITIAL_BUFFER_SIZE];

    while ((current_line_length = get_line(current_line)) > 0)
    {
        if (current_line_length >= MIN_LINE_LENGTH)
        {
            printf("%-4d %s\n", current_line_length, current_line);
        }
    }

    return 0;
}


text:
angular.module('EventServiceFactory', [])

.factory("EventService", function($http,$ionicLoading,$q,$window,UrlPath){

  var service = {};

  var getEventPath = UrlPath.getEventPath();
  var getEventDetailPath = UrlPath.getEventDetailPath();

  service.getMainInfo = function(num,start_id,order){
    return $http.post(getEventPath,{num:num,start_id:start_id,order:order});
  };

  service.getDetailInfo = function(event_id){
  	// return $http.get('data/eventdetail.json');
  	return $http
    .post(getEventDetailPath,{event_id:event_id});
  };
  return service;
})


text:
<?php
if(!defined('IN_MANAGER_MODE') || IN_MANAGER_MODE != 'true') exit();

if (!$modx->hasPermission('save_document')) {
	$e->setError(3);
	$e->dumpError();
}

global $form_v;
$modx->loadExtension('DocAPI');
$form_v = $modx->doc->fix_tv_nest('ta,introtext,pagetitle,longtitle,menutitle,description,alias,link_attributes',$_POST);
$form_v = $modx->doc->initValue($form_v);
$form_v = $modx->doc->setValue($form_v);

// preprocess POST values
$id = $form_v['id'];
if(!preg_match('@^[0-9]*$@',$id) || ($_POST['mode'] == '27' && empty($id)))
{
	$e->setError(2);
	$e->dumpError();
}

if($_POST['mode'] == '27') $actionToTake = 'edit';
else                       $actionToTake = 'new';

$document_groups = getDocGroups();

checkDocPermission($id,$document_groups);

$modx->loadExtension('REVISION');

$modx->manager->saveFormValues();

switch ($actionToTake) {
	case 'new' :
		$return_url = 'index.php?a=' . $_GET['a'];

		// invoke OnBeforeDocFormSave event
		$modx->invokeEvent('OnBeforeDocFormSave', array('mode'=>'new'));

		$temp_id = $modx->doc->getNewDocID();
		$values = getInputValues($temp_id,'new');
		$values = $modx->db->escape($values);
		$newid = $modx->db->insert($values,'[+prefix+]site_content');
		if(!$newid) {
			$msg = 'An error occured while attempting to save the new document: ' . $modx->db->getLastError();
			$modx->webAlertAndQuit($msg, $return_url);
		}

		if(!empty($form_v['template'])) {
			$tmplvars = get_tmplvars($newid);
			insert_tmplvars($newid,$tmplvars);
		}

		setDocPermissionsNew($document_groups,$newid);

		updateParentStatus();
		if(isset($modx->config['show_meta'])) saveMETAKeywords($newid);

		// invoke OnDocFormSave event
		$modx->invokeEvent('OnDocFormSave', array('mode'=>'new','id'=>$newid));

		if($modx->config['use_udperms']==='1') {
			$modx->manager->setWebDocsAsPrivate($newid);
			$modx->manager->setMgrDocsAsPrivate($newid);
		}

		if($form_v['syncsite'] == 1) $modx->clearCache();
		goNextAction($newid);
		exit;
		break;
	case 'edit' :
		$return_url = "index.php?a=27&id={$id}";
		$db_v = getExistsValues($id, $return_url);

		checkStartDoc($id,$return_url);
		$form_v['parent']   = checkParentID($id,$return_url);

		$form_v['isfolder'] = checkFolderStatus($id);

		// set publishedon and publishedby
		$form_v['published']   = checkPublished($db_v);
		$form_v['pub_date']    = checkPub_date($db_v);
		$form_v['unpub_date']  = checkUnpub_date($db_v);
		$form_v['publishedon'] = checkPublishedon($db_v);
		$form_v['publishedby'] = checkPublishedby($db_v);

		// invoke OnBeforeDocFormSave event
		$modx->invokeEvent('OnBeforeDocFormSave', array('mode'=>'upd','id'=>$id));

		$values = getInputValues($id,'edit');
		$values = $modx->db->escape($values);
		$rs = $modx->db->update($values,'[+prefix+]site_content',"id='{$id}'");
		if (!$rs) {
			$msg = "An error occured while attempting to save the edited document. The generated SQL is: <i> {$sql} </i>.";
			$modx->webAlertAndQuit($msg, $return_url);
		}

		if(!empty($form_v['template'])) {
			$tmplvars = get_tmplvars($id);
			update_tmplvars($id,$tmplvars);
		}

		setDocPermissionsEdit($document_groups,$id);

		updateParentStatus();

		// finished moving the document, now check to see if the old_parent should no longer be a folder
		if($db_v['parent']!=='0') folder2doc($db_v['parent']);

		if(isset($modx->config['show_meta'])) saveMETAKeywords($id);

		// invoke OnDocFormSave event
		$modx->invokeEvent('OnDocFormSave', array('mode'=>'upd','id'=>$id));

		if($modx->config['use_udperms']==='1') {
			$modx->manager->setWebDocsAsPrivate($id);
			$modx->manager->setMgrDocsAsPrivate($id);
		}

		if ($form_v['syncsite'] === '1') {
			if($form_v['published']===$db_v['published']&&$form_v['alias']===$db_v['alias']&&$form_v['parent']===$db_v['parent'])
				$clearcache['target'] = 'pagecache';
			else
				$clearcache['target'] = 'pagecache,sitecache';
			$modx->clearCache($clearcache);
		}
		goNextAction($id);
		exit;
		break;
	default :
		header("Location: index.php?a=7");
		exit;
}

// -- Save META Keywords --
function saveMETAKeywords($id) {
	global $modx;
	$keywords = $_POST['keywords'];
	$metatags = $_POST['metatags'];

	if(!$keywords&&!$metatags) return;
	if(!isset($modx->config['show_meta']) || $modx->config['show_meta']==0)
		return;
	if (!$modx->hasPermission('edit_doc_metatags'))
		return;

	// keywords - remove old keywords first
	$modx->db->delete('[+prefix+]keyword_xref', "content_id='{$id}'");
	foreach($keywords as $keyword) {
		$flds = array (
			'content_id' => $id,
			'keyword_id' => $keyword
		);
		$flds = $modx->db->escape($flds);
		$modx->db->insert($flds, '[+prefix+]keyword_xref');
	}
	// meta tags - remove old tags first
	$modx->db->delete('[+prefix+]site_content_metatags', "content_id='{$id}'");
	foreach($metatag as $metatag) {
		$flds = array (
			'content_id' => $id,
			'metatag_id' => $metatag
		);
		$flds = $modx->db->escape($flds);
		$modx->db->insert($flds, '[+prefix+]site_content_metatags');
	}
	$flds = array (
		'haskeywords' => (count($keywords) ? 1 : 0),
		'hasmetatags' => (count($metatags) ? 1 : 0)
	);
	$flds = $modx->db->escape($flds);
	$modx->db->update($flds, '[+prefix+]site_content', "id='{$id}'");
}

function get_tmplvars($id)
{
	global $modx,$form_v;

	$template = $form_v['template'];

	if(empty($template)) return array();

	// get document groups for current user
	if ($_SESSION['mgrDocgroups'])
	{
		$docgrp = implode(',', $_SESSION['mgrDocgroups']);
	}

	$from[] = '[+prefix+]site_tmplvars AS tv';
	$from[] = 'INNER JOIN [+prefix+]site_tmplvar_templates AS tvtpl ON tvtpl.tmplvarid = tv.id';
	$from[] = 'LEFT JOIN [+prefix+]site_tmplvar_contentvalues AS tvc ON tvc.tmplvarid=tv.id';
	if($id) $from[] = "AND tvc.contentid = '{$id}'";
	$from[] = 'LEFT JOIN [+prefix+]site_tmplvar_access tva ON tva.tmplvarid=tv.id';
	$tva_docgrp = ($docgrp) ? "OR tva.documentgroup IN ({$docgrp})" : '';
	$where = "tvtpl.templateid = '{$template}' AND (1='{$_SESSION['mgrRole']}' OR ISNULL(tva.documentgroup) {$tva_docgrp})";
	$orderby = 'tv.rank';
	$from = join(' ', $from);
	$rs = $modx->db->select('DISTINCT tv.*',$from,$where,$orderby);

	$tmplvars = array ();
	while ($row = $modx->db->getRow($rs)):
		$tmplvar = '';
		$tvid = "tv{$row['id']}";

		if(!isset($form_v[$tvid]) && $row['type']!=='checkbox' && $row['type']!=='listbox-multiple')
			continue;

		if($row['type']==='url') {
			if($form_v["{$tvid}_prefix"] !== '--') {
				$value = str_replace(array ('feed://','ftp://','http://','https://','mailto:'), '', $form_v[$tvid]);
				$value = $form_v["{$tvid}_prefix"] . $value;
			}
			else $value = $form_v[$tvid];
		}
		elseif($row['type']==='file')    $value = $form_v[$tvid];
		else {
			if(is_array($form_v[$tvid])) {
				// handles checkboxes & multiple selects elements
				$value = implode('||', $form_v[$tvid]);
			}
			elseif(isset($form_v[$tvid])) $value = $form_v[$tvid];
			else                          $value = '';
		}
		// save value if it was modified
		if(substr($row['default_text'], 0, 6) === '@@EVAL') {
	     	$eval_str = trim(substr($row['default_text'], 7));
	    	$row['default_text'] = eval($eval_str);
	    }
		if (strlen($value) > 0 && $value != $row['default_text'])
		{
			$tmplvars[$row['id']] = $value;
		}
		else $tmplvars[$row['id']] = false; // Mark the variable for deletion
	endwhile;
	return $tmplvars;
}

function get_alias($id,$alias,$parent,$pagetitle)
{
	global $modx;
	// friendly url alias checks
	if ($modx->config['friendly_urls'])
	{
		if(!$parent) $parent = '0';
		if ($alias && !$modx->config['allow_duplicate_alias'])
		{ // check for duplicate alias name if not allowed
			$alias = _check_duplicate_alias($id,$alias,$parent);
		}
		elseif (!$alias && $modx->config['automatic_alias'] != '0')
		{ // auto assign alias
			switch($modx->config['automatic_alias'])
			{
				case '1':
					$alias = $modx->manager->get_alias_from_title($id,$pagetitle);
					break;
				case '2':
					$alias = $modx->manager->get_alias_num_in_folder($id,$parent);
					break;
			}

		}
	}
	return $alias;
}

function _check_duplicate_alias($id,$alias,$parent)
{
	global $modx,$_lang;

	if ($modx->config['use_alias_path']==1)
	{ // only check for duplicates on the same level if alias_path is on
		$rs = $modx->db->select('id','[+prefix+]site_content',"id<>'{$id}' AND alias='{$alias}' AND parent={$parent} LIMIT 1");
		$docid = $modx->db->getValue($rs);
		if($docid < 1)
		{
			$rs = $modx->db->select('id','[+prefix+]site_content',"id='{$alias}' AND alias='' AND parent='{$parent}'");
			$docid = $modx->db->getValue($rs);
		}
	}
	else
	{
		$rs = $modx->db->select('id','[+prefix+]site_content',"id<>'{$id}' AND alias='{$alias}' LIMIT 1");
		$docid = $modx->db->getValue($rs);
		if($docid < 1)
		{
			$rs = $modx->db->select('id','[+prefix+]site_content',"id='{$alias}' AND alias=''");
			$docid = $modx->db->getValue($rs);
		}
	}
	if ($docid > 0)
	{
		$modx->manager->saveFormValues($_POST['mode']);

		$url = 'index.php?a=' . $_POST['mode'];
		if ($_POST['mode'] == '27') $url .= "&id={$id}";
		elseif($_REQUEST['pid'])    $url .= '&pid=' . $_REQUEST['pid'];

		if($_REQUEST['stay']) $url .= '&stay=' . $_REQUEST['stay'];

		$modx->webAlertAndQuit(sprintf($_lang["duplicate_alias_found"], $docid, $alias), $url);
	}
	return $alias;
}

function checkDocPermission($id,$document_groups=array()) {
	global $modx,$form_v,$_lang,$e;
	// ensure that user has not made this document inaccessible to themselves
	if($_SESSION['mgrRole'] != 1 && is_array($document_groups) && !empty($document_groups))
	{
		$document_group_list = implode(',', array_filter(explode(',',$document_group_list), 'is_numeric'));
		if(!empty($document_group_list))
		{
			$from='[+prefix+]membergroup_access mga, [+prefix+]member_groups mg';
			$mgrInternalKey = $_SESSION['mgrInternalKey'];
			$where = "mga.membergroup = mg.user_group AND mga.documentgroup IN({$document_group_list}) AND mg.member='{$mgrInternalKey}'";
			$count = $modx->db->getValue($modx->db->select('COUNT(mg.id)',$from,$where));
			if($count == 0)
			{
				if ($actionToTake == 'new') $url = 'index.php?a=4';
				else                        $url = "index.php?a=27&id={$id}";

				$modx->manager->saveFormValues();
				$modx->webAlertAndQuit(sprintf($_lang["resource_permissions_error"]), $url);
			}
		}
	}

	// get the document, but only if it already exists
	if ($_POST['mode'] === '27')
	{
		$rs = $modx->db->select('parent', '[+prefix+]site_content', "id='{$id}'");
		$total = $modx->db->getRecordCount($rs);
		if ($total > 1)
		{
			$e->setError(6);
			$e->dumpError();
		} elseif ($total < 1) {
			$e->setError(7);
			$e->dumpError();
		}
		if ($modx->config['use_udperms'] !== 1) return;
		$existingDocument = $modx->db->getRow($rs);

		// check to see if the user is allowed to save the document in the place he wants to save it in
		if ($existingDocument['parent'] == $form_v['parent']) return;

		if (!$modx->checkPermissions($form_v['parent'])) {
			if ($actionToTake == 'new') $url = "index.php?a=4";
			else                        $url = "index.php?a=27&id={$id}";
			$modx->manager->saveFormValues();
			$modx->webAlertAndQuit(sprintf($_lang['access_permission_parent_denied'], $id, $form_v['alias']), $url);
		}
	}
}

function getInputValues($id=0,$mode='new') {
	global $form_v;

	$db_v_names = explode(',', 'content,pagetitle,longtitle,type,description,alias,link_attributes,isfolder,richtext,published,pub_date,unpub_date,parent,template,menuindex,searchable,cacheable,editedby,editedon,publishedon,publishedby,contentType,content_dispo,donthit,menutitle,hidemenu,introtext,createdby,createdon');
	if($id) $fields['id'] = $id;
	foreach($db_v_names as $key) {
		if(!isset($form_v[$key])) $form_v[$key] = '';
		$fields[$key] = $form_v[$key];
	}
	if($mode==='edit') {
		unset($fields['createdby']);
		unset($fields['createdon']);
	}
	return $fields;
}

function checkStartDoc($id,$return_url) {
	global $modx,$form_v;

	if ($id == $modx->config['site_start']) {
		$published  = $form_v['published'];
		$pub_date   = $form_v['pub_date'];
		$unpub_date = $form_v['unpub_date'];
		if($published == 0) {
			$modx->webAlertAndQuit('Document is linked to site_start variable and cannot be unpublished!',$return_url);
		} elseif (($pub_date > $_SERVER['REQUEST_TIME'] || $unpub_date != "0")) {
			$modx->webAlertAndQuit('Document is linked to site_start variable and cannot have publish or unpublish dates set!',$return_url);
		}
	}
}

function checkParentID($id,$return_url) {
	global $modx,$form_v;

	if ($form_v['parent'] == $id) {
		$modx->webAlertAndQuit("Document can not be it's own parent!",$url);
	}
	else return $form_v['parent'];
}

function checkFolderStatus($id) {
	global $modx,$form_v;

	$isfolder = $form_v['isfolder'];
	// check to see document is a folder
	$rs = $modx->db->select('COUNT(id) AS count', '[+prefix+]site_content', "parent='{$id}'");
	if ($rs) {
		$row = $modx->db->getRow($rs);
		if ($row['count'] > 0) $isfolder = '1';
	} else {
		$modx->webAlertAndQuit("An error occured while attempting to find the document's children.",$url);
	}
	return $isfolder;
}

// keep original publish state, if change is not permitted
function getPublishPermission($field_name,$db_v) {
	global $modx,$form_v;
	if (!$modx->hasPermission('publish_document'))
		return $db_v[$field_name];
	else return $form_v[$field_name];
}

function checkPublished($db_v) {
	return getPublishPermission('published',$db_v);
}

function checkPub_date($db_v) {
	return getPublishPermission('pub_date',$db_v);
}

function checkUnpub_date($db_v) {
	return getPublishPermission('unpub_date',$db_v);
}

function checkPublishedon($db_v) {
	global $modx,$form_v;

	if(!$modx->hasPermission('publish_document'))
		return $db_v['publishedon'];
	else
	{
		// if it was changed from unpublished to published
		if(!empty($form_v['pub_date']) && $form_v['pub_date']<=$_SERVER['REQUEST_TIME'] && $form_v['published'])
			$publishedon = $form_v['pub_date'];
		elseif (0<$db_v['publishedon'] && $form_v['published'])
			$publishedon = $db_v['publishedon'];
		elseif(!$form_v['published'])
			$publishedon = 0;
		else
			$publishedon = $_SERVER['REQUEST_TIME'];
		return $publishedon;
	}
}

function checkPublishedby($db_v) {
	global $modx,$form_v;

	if(!$modx->hasPermission('publish_document'))
		return $db_v['publishedon'];
	else
	{
		// if it was changed from unpublished to published
		if(!empty($form_v['pub_date']) && $form_v['pub_date']<=$_SERVER['REQUEST_TIME'] && $form_v['published'])
			$publishedby = $db_v['publishedby'];
		elseif (0<$db_v['publishedon'] && $form_v['published'])
			$publishedby = $db_v['publishedby'];
		elseif(!$form_v['published'])
			$publishedby = 0;
		else
			$publishedby = $modx->getLoginUserID();
		return $publishedby;
	}
}

function getExistsValues($id, $return_url) {
	global $modx;
	$rs = $modx->db->select('*', '[+prefix+]site_content', "id='{$id}'");
	$row = $modx->db->getRow($rs);
	if (!$row) {
		$msg =  "An error occured while attempting to find the document's current parent.";
		$modx->webAlertAndQuit($msg, $return_url);
	}
	return $row;
}

function insert_tmplvars($docid,$tmplvars) {
	global $modx;
	if(empty($tmplvars)) return;
	$tvChanges = array();
	$tv['contentid'] = $docid;
	foreach ($tmplvars as $tmplvarid=>$value) {
		if ($value!==false) {
			$tv['tmplvarid'] = $tmplvarid;
			$tv['value']     = $value;
			$tvChanges[] = $tv;
		}
	}
	if(!empty($tvChanges)) {
		foreach ($tvChanges as $tv) {
			$tv = $modx->db->escape($tv);
			$rs = $modx->db->insert($tv, '[+prefix+]site_tmplvar_contentvalues');
		}
	}
}

function update_tmplvars($docid,$tmplvars) {
	global $modx;
	if(empty($tmplvars)) return;
	$tvChanges   = array();
	$tvAdded     = array();
	$tvDeletions = array();
	$rs = $modx->db->select('id, tmplvarid', '[+prefix+]site_tmplvar_contentvalues', "contentid='{$docid}'");
	$tvIds = array ();
	while ($row = $modx->db->getRow($rs))
	{
		$tvIds[$row['tmplvarid']] = $row['id'];
	}
	$tv['contentid'] = $docid;
	foreach ($tmplvars as $tmplvarid=>$value)
	{
		if ($value===false) {
			if (isset($tvIds[$tmplvarid])) $tvDeletions[] = $tvIds[$tmplvarid];
		} else {
			$tv['tmplvarid'] = $tmplvarid;
			$tv['value']     = $value;
			if (isset($tvIds[$tmplvarid])) {
				$tvChanges[] = $tv;
			} else {
				$tvAdded[] = $tv;
			}
		}
	}

	if (!empty($tvDeletions)) {
		$where = 'id IN('.implode(',', $tvDeletions).')';
		$rs = $modx->db->delete('[+prefix+]site_tmplvar_contentvalues', $where);
	}
	if (!empty($tvAdded)) {
		foreach ($tvAdded as $tv) {
			$tv = $modx->db->escape($tv);
			$rs = $modx->db->insert($tv, '[+prefix+]site_tmplvar_contentvalues');
		}
	}

	if (!empty($tvChanges)) {
		foreach ($tvChanges as $tv) {
			$tv = $modx->db->escape($tv);
			$tvid = $tv['tmplvarid'];
			$rs = $modx->db->update($tv, '[+prefix+]site_tmplvar_contentvalues', "tmplvarid='{$tvid}' AND contentid='{$docid}'");
		}
	}
}

// document access permissions
function setDocPermissionsNew($document_groups,$newid) {
	global $modx,$form_v;
	$parent = $form_v['parent'];
	$tbl_document_groups = $modx->getFullTableName('document_groups');

	$docgrp_save_attempt = false;
	if ($modx->config['use_udperms'] == 1 && is_array($document_groups))
	{
		$new_groups = array();
		foreach ($document_groups as $value_pair)
		{
			// first, split the pair (this is a new document, so ignore the second value
			$group = intval(substr($value_pair,0,strpos($value_pair,',')));
			// @see manager/actions/mutate_content.dynamic.php @ line 1138 (permissions list)
			$new_groups[] = "({$group},{$newid})";
		}
		$saved = true;
		if (!empty($new_groups))
		{
			$sql = 'INSERT INTO '.$tbl_document_groups.' (document_group, document) VALUES '. implode(',', $new_groups);
			$saved = $modx->db->query($sql) ? $saved : false;
			$docgrp_save_attempt = true;
		}
	}
	else
	{
		$isManager = $modx->hasPermission('access_permissions');
		$isWeb     = $modx->hasPermission('web_access_permissions');
		if($modx->config['use_udperms']==1 && !($isManager || $isWeb) && $parent != 0) {
			// inherit document access permissions
			$sql = "INSERT INTO {$tbl_document_groups} (document_group, document) SELECT document_group, {$newid} FROM {$tbl_document_groups} WHERE document='{$parent}'";
			$saved = $modx->db->query($sql);
			$docgrp_save_attempt = true;
		}
	}
	if ($docgrp_save_attempt && !$saved) {
		$msg = 'An error occured while attempting to add the document to a document_group.';
		$modx->webAlertAndQuit($msg);
	}
}

// update parent folder status
function updateParentStatus() {
	global $modx,$form_v;
	$parent = $form_v['parent'];
	if ($parent != 0) {
		$rs = $modx->db->update('isfolder=1', '[+prefix+]site_content', "id='{$parent}'");
		if (!$rs) {
			$msg = "An error occured while attempting to change the document's parent to a folder.";
			$modx->webAlertAndQuit($msg);
		}
	}
}

// redirect/stay options
function goNextAction($id) {
	global $form_v;

	$parent = $form_v['parent'];
	switch($form_v['stay']) {
		case '1':
			$header = 'Location: index.php?';
			if($form_v['type']==='document')
				$header .= 'a=4';
			elseif($form_v['type']==='reference')
				$header .= 'a=72';
			$header .= "&pid={$parent}&r=1&stay=1";
			break;
		case '2':
			$header = "Location: index.php?a=27&id={$id}&r=1&stay=2";
			break;
		default:
			if($parent!=='0')
				$header = "Location: index.php?a=120&id={$parent}&r=1";
			else
				$header = "Location: index.php?a=3&id={$id}&r=1";
	}
	header($header);
	exit;
}

function setDocPermissionsEdit($document_groups,$id) {
	global $modx;

	if ($modx->config['use_udperms'] != 1 || !is_array($document_groups))
		return;

	$new_groups = array();
	// process the new input
	foreach ($document_groups as $value_pair)
	{ // @see manager/actions/mutate_content.dynamic.php @ line 1138 (permissions list)
		list($group, $link_id) = explode(',', $value_pair);
		$new_groups[$group] = $link_id;
	}

	// grab the current set of permissions on this document the user can access
	$isManager = intval($modx->hasPermission('access_permissions'));
	$isWeb     = intval($modx->hasPermission('web_access_permissions'));
	$fields = 'groups.id, groups.document_group';
	$from   = '[+prefix+]document_groups AS groups LEFT JOIN [+prefix+]documentgroup_names AS dgn ON dgn.id = groups.document_group';
	$where  = "((1={$isManager} AND dgn.private_memgroup) OR (1={$isWeb} AND dgn.private_webgroup)) AND groups.document = '{$id}'";
	$rs = $modx->db->select($fields,$from,$where);
	$old_groups = array();
	while ($row = $modx->db->getRow($rs)) {
		$old_groups[$row['document_group']] = $row['id'];
	}
	// update the permissions in the database
	$insertions = $deletions = array();
	foreach ($new_groups as $group => $link_id)
	{
		$group = intval($group);
		if (array_key_exists($group, $old_groups))
		{
			unset($old_groups[$group]);
			continue;
		}
		elseif ($link_id == 'new')
		{
			$insertions[] = "({$group},{$id})";
		}
	}
	$saved = true;
	if (!empty($insertions))
	{
		$tbl_document_groups = $modx->getFullTableName('document_groups');
		$sql_insert = 'INSERT INTO '.$tbl_document_groups.' (document_group, document) VALUES '.implode(',', $insertions);
		$saved = $modx->db->query($sql_insert) ? $saved : false;
	}
	if (!empty($old_groups))
	{
		$where = 'id IN (' . implode(',', $old_groups) . ')';
		$saved = $modx->db->delete('[+prefix+]document_groups',$where) ? $saved : false;
	}
	// necessary to remove all permissions as document is public
	if ((isset($_POST['chkalldocs']) && $_POST['chkalldocs'] == 'on'))
	{
		$saved = $modx->db->delete('[+prefix+]document_groups',"document='{$id}'") ? $saved : false;
	}
	if (!$saved)
	{
		$msg = 'An error occured while saving document groups.';
		$modx->webAlertAndQuit($msg);
	}
}

function folder2doc($parent) {
	global $modx;
	$rs = $modx->db->select('COUNT(id)', '[+prefix+]site_content', "parent={$parent}");
	if (!$rs)
		echo "An error occured while attempting to find the old parents' children.";
	$row = $modx->db->getRow($rs);
	if ($row['COUNT(id)'] == 0) {
		$rs = $modx->db->update('isfolder = 0', '[+prefix+]site_content', "id='{$parent}'");
		if (!$rs)
			echo "An error occured while attempting to change the old parent to a regular document.";
	}
}

function getDocGroups()
{
	if(isset($_POST['chkalldocs']) && $_POST['chkalldocs'] === 'on')
		$rs = array();
	elseif(!isset($_POST['docgroups']))
		$rs = array();
	else
		$rs = $_POST['docgroups'];
	return $rs;
}


text:
package com.djn.perfect.ssmnormal.common.test.pattern.factory.method;

public class BMW320 extends BMW {
	public BMW320(){
		   System.out.println("制造-->BMW320");
	}

}


text:
class Element
  attr_accessor :prev
  attr_accessor :next
  attr_reader :datum

  def initialize(datum, next_element=nil, prev=nil)
    @datum = datum
    @next = next_element || self
    @prev = prev || self
  end

end

class Deque
  def initialize
    @front = nil
  end

  def push(value)
    if @front.nil?
      @front = Element.new(value)
    else
      back = @front.prev
      n = Element.new(value, @front, back)
      back.next = n
      @front.prev = n
    end
  end

  def unshift(value)
    push(value)
    @front = @front.prev
  end

  def pop
    @front = @front.prev
    shift
  end

  def shift
    value = @front.datum
    front = @front.next
    back = @front.prev
    if front.equal?(@front)
      @front = nil
    else
      front.prev = back
      back.next = front
      @front = front
    end
    value
  end
end


text:
============
django-hvad
============

This project is yet another attempt at making model translations suck less in
Django.

Documentation for django-hvad can be found at http://django-hvad.readthedocs.org/.

This project provides the same functionality as django-nani, but it as opposed
to django-nani, this project does not affect the default queries, which means
that everything will continue to work as it was before.

You have to activate the translated fields, by calling a specific method on the manager.

.. warning:: django-hvad is still in beta, please use it with
             caution and report any bug(s) you might encounter.

**Feel free to join us at #django-hvad on irc.freenode.net for a chat**

.. image:: https://secure.travis-ci.org/KristianOellegaard/django-hvad.png?branch=master

Example
-------

             Normal.objects.all()

Returns all objects, but without any translated fields attached - this query is
just the default django queryset and can therefore be used as usual.

             Normal.objects.language().all()

Returns all objects as translated instances, but only the ones that are translated
into the currect language. You can also specify which language to get, using e.g.

             Normal.objects.language("en").all()

Features
--------

* Simple API
* Predictable
* Reliable
* Fast (few and simple queries)
* High level (no custom SQL Compiler or other scary things)

Thanks to
---------

Jonas Obrist (https://github.com/ojii) for making django-nani and for helping me with this project.


text:
import proto  # type: ignore

__protobuf__ = proto.module(
    package="google.cloud.aiplatform.v1",
    manifest={
        "DeployedIndexRef",
    },
)

class DeployedIndexRef(proto.Message):
    r"""Points to a DeployedIndex.

    Attributes:
        index_endpoint (str):
            Immutable. A resource name of the
            IndexEndpoint.
        deployed_index_id (str):
            Immutable. The ID of the DeployedIndex in the
            above IndexEndpoint.
    """

    index_endpoint = proto.Field(
        proto.STRING,
        number=1,
    )
    deployed_index_id = proto.Field(
        proto.STRING,
        number=2,
    )

__all__ = tuple(sorted(__protobuf__.manifest))


text:
class Search < ActiveRecord::Base
  validates :console, presence: true;
  validates :game_name, presence: true;

  has_many :results
end


text:
@implementation FKFlickrPhotosetsGetPhotos

- (BOOL) needsLogin {
    return NO;
}

- (BOOL) needsSigning {
    return NO;
}

- (FKPermission) requiredPerms {
    return -1;
}

- (NSString *) name {
    return @"flickr.photosets.getPhotos";
}

- (BOOL) isValid:(NSError **)error {
    BOOL valid = YES;
	NSMutableString *errorDescription = [[NSMutableString alloc] initWithString:@"You are missing required params: "];
	if(!self.photoset_id) {
		valid = NO;
		[errorDescription appendString:@"'photoset_id', "];
	}

	if(error != NULL) {
		if(!valid) {
			NSDictionary *userInfo = @{NSLocalizedDescriptionKey: errorDescription};
			*error = [NSError errorWithDomain:FKFlickrKitErrorDomain code:FKErrorInvalidArgs userInfo:userInfo];
		}
	}
    return valid;
}

- (NSDictionary *) args {
    NSMutableDictionary *args = [NSMutableDictionary dictionary];
	if(self.photoset_id) {
		[args setValue:self.photoset_id forKey:@"photoset_id"];
	}
	if(self.extras) {
		[args setValue:self.extras forKey:@"extras"];
	}
	if(self.privacy_filter) {
		[args setValue:self.privacy_filter forKey:@"privacy_filter"];
	}
	if(self.per_page) {
		[args setValue:self.per_page forKey:@"per_page"];
	}
	if(self.page) {
		[args setValue:self.page forKey:@"page"];
	}
	if(self.media) {
		[args setValue:self.media forKey:@"media"];
	}

    return [args copy];
}

- (NSString *) descriptionForError:(NSInteger)error {
    switch(error) {
		case FKFlickrPhotosetsGetPhotosError_PhotosetNotFound:
			return @"Photoset not found";
		case FKFlickrPhotosetsGetPhotosError_InvalidAPIKey:
			return @"Invalid API Key";
		case FKFlickrPhotosetsGetPhotosError_ServiceCurrentlyUnavailable:
			return @"Service currently unavailable";
		case FKFlickrPhotosetsGetPhotosError_WriteOperationFailed:
			return @"Write operation failed";
		case FKFlickrPhotosetsGetPhotosError_FormatXXXNotFound:
			return @"Format \"xxx\" not found";
		case FKFlickrPhotosetsGetPhotosError_MethodXXXNotFound:
			return @"Method \"xxx\" not found";
		case FKFlickrPhotosetsGetPhotosError_InvalidSOAPEnvelope:
			return @"Invalid SOAP envelope";
		case FKFlickrPhotosetsGetPhotosError_InvalidXMLRPCMethodCall:
			return @"Invalid XML-RPC Method Call";
		case FKFlickrPhotosetsGetPhotosError_BadURLFound:
			return @"Bad URL found";

		default:
			return @"Unknown error code";
    }
}

@end


text:
using System;

namespace elbgb_test
{
    [Flags]
    public enum TestStatus
    {
        None,
        Inconclusive = 1,
        Failing = 2,
        Passing = 4,
        All = Inconclusive | Passing | Failing,
    }
}


text:
var JsonDB	  	= require('node-json-db'),
	mv		  	= require('mv');

module.exports = class DB{
	constructor(options){
		var _this = this;
		this.options = Object.assign({}, {
			db_name: 'db',
			readable: false, //save in human readable format
			on_load: function(db_root){
				return db_root;
			},
			on_empty: function(){
				try {
					b.log.info('Default ' + options.db_name + ' loaded!');
					return require(__botdir + '/db/default/./default_' + options.db_name + '.json');
				} catch (e) {
					b.log.warn('No default ' + options.db_name);
					return {};
				}
			},
			after_load: function()
			{

			}

		}, options);

		if(!_this.options.db_name_new) _this.options.db_name_new = _this.options.db_name;

		var old_path = __botdir + '/' + this.options.db_name + '.json';
		var new_path = __botdir + '/db/' + this.options.db_name_new + '.json';

		if (!fs.existsSync(new_path) && fs.existsSync(old_path)){
			mv(old_path, new_path, function(err) {
				if(err) {
					b.log.error('Reverting to old path', err);
					new_path = old_path;
				} else {
					b.log.debug('Moved', old_path, 'to', new_path);
				}

				_this.jdb = new JsonDB(new_path, true, _this.options.readable);
				_this.clean_db();
			});
		} else {
			_this.jdb = new JsonDB(new_path, true, _this.options.readable);
			_this.clean_db();
		}

	}

	clean_db(){
		var _this = this;
		this.get_data('/', function(db_root){
			function filter_empty(data){
				for(var key in data){

					if(typeof(data) === 'object' && !Array.isArray(data))
					{
						var new_key = _this.fix_key(key);
						if(new_key !== key)
						{
							data[new_key] = data[key];
							delete data[key];
							key = new_key;
						}
					}

					if(typeof(data[key]) === 'object' && data[key] !== null && data[key] !== undefined){
						if(Array.isArray(data[key])){
							if(data[key].length === 0){
								delete data[key];
							} else {
								filter_empty(data[key]);
							}
						} else {
							if(Object.keys(data[key]).length === 0){
								delete data[key];
							} else {
								filter_empty(data[key]);
							}
						}
					}
				}
				return data;
			}

			if(db_root === null ||
				(typeof db_root === 'object' && Array.isArray(db_root) === false && (Object.keys(db_root)).length === 0) ||
				(typeof db_root === 'object' && Array.isArray(db_root) === true && db_root.length === 0)
			){
				db_root = _this.options.on_empty();
			}

			db_root = _this.options.on_load(db_root);

			_this.update('/', filter_empty(db_root), true, function(){
				b.log.info('Engaged the quantum ' + _this.options.db_name_new + ' database');
				_this.options.after_load();
			});
		});
	}

	//jsondb doesn't accept non-JS compliant variable first chars (a-zA-Z$_)
	//reverse swaps & -> # etc
	fix_key(key, reverse){
		var _this = this;
		if(reverse){
			if(key.match(/^\$/)){
				//b.log.warn(_this.options.db_name, '$key matched', key);
				key = key.replace(/^\$/, '#');
				return key;
			} else if (key.match(/^__\$__/)){
				//b.log.warn(_this.options.db_name, 'wrong first char key matched', key);
				key = key.replace(/^__\$__/, '');
				return key;
			}
		} else {
			if(key.match(/^\#/)){
				//b.log.warn(_this.options.db_name, '#key matched', key);
				key = key.replace(/^\#/, '$');
				return key;
			} else if (key.match(/^[^a-zA-Z$_]/)){
				//b.log.warn(_this.options.db_name, 'wrong first char key matched', key);
				key = '__$__' + key;
				return key;
			}
		}

		return key;
	}
	fix_path(path){
		var _this = this;
		if (path.match(/\/[^a-zA-Z$_]/gm)){
			//b.log.warn(_this.options.db_name, 'incorrect keys in path', path);
			var path = path.split('/').map(function(key){
				return _this.fix_key(key);
			}).join('/');
		}
		return path;
	}

	//case_insensitive tries to pull the parent node, do regex search, and return that instead
	//case_insensitive = path value to search for insensitive
	get_data(path, callback, case_insensitive){
		var _this = this;
		path = _this.fix_path(path);
		case_insensitive = case_insensitive === undefined ? false : case_insensitive;

		try {
			function filter_keys(data){
				for(var key in data){
					if(typeof(data) === 'object' && !Array.isArray(data))
					{
						var new_key = _this.fix_key(key, true);
						if(new_key !== key)
						{
							data[new_key] = data[key];
							delete data[key];
							key = new_key;
						}
					}

					if(typeof(data[key]) === 'object' && data[key] !== null && data[key] !== undefined){
						if(Array.isArray(data[key])){
							if(data[key].length > 0){
								data[key] = filter_keys(data[key]);
							}
						} else {
							if(Object.keys(data[key]).length > 0){
								data[key] = filter_keys(data[key]);
							}
						}
					}
				}

				return data;
			}

			function get_some_data(pth){
				var data = JSON.parse(JSON.stringify(_this.jdb.getData(pth)));
				data = filter_keys(data);
				callback(data);
			}

			if(case_insensitive !== false){
				var path_arr = path.split('/');
				path_arr = path_arr.filter(function(x){
					return x !== '';
				});

				var p1 = path_arr.slice(0, path_arr.indexOf(case_insensitive));
				var p2 = path_arr.slice(path_arr.indexOf(case_insensitive) + 1);

				_this.merge_case(p1.join('/'), case_insensitive, function(rtn){
					if(!rtn.err){
						get_some_data(rtn + (p2.length > 0 ? '/' + p2.join('/') : ''));
					} else {
						get_some_data(path);
					}
				});
			}
			else
			{
				get_some_data(path);
			}
		} catch(e) {
			if(e.message.match(/Can't Load Database/) !== null){ //fail here, cuz something is W R O N G
				b.log.error('db.get_data', e.stack);
				process.exit(1);
			} else {
				if(e.message.match(/Can't find dataPath/) === null){
					//b.log.warn('db.get_data', e.message);
					b.log.warn('db.get_data', e.stack);
				}
				callback(null);
			}
		}
	}

	//merges objects in a case insensitive way
	//base_path = base data path to search
	//key = search key case insensitve
	merge_case(base_path, key_search, callback){
		var _this = this;
		base_path = _this.fix_path(base_path);
		key_search = _this.fix_key(key_search);

		try {
			var key_search_regex = '^' + key_search.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + '$';
			var case_insensitive_regex = new RegExp(key_search_regex, 'i');

			var base_path_arr = base_path.split('/');
			base_path_arr = base_path_arr.filter(function(x){
				return x !== '';
			});

			base_path = '/' + base_path_arr.join('/');

			var get_data = _this.jdb.getData(base_path);
			var get_data_arr = [];
			var get_paths = [];

			for(var key in get_data){
				if(key.match(case_insensitive_regex)){
					get_paths.push(base_path + (base_path === '/' ? '' : '/') + key);
					get_data_arr.push(get_data[key]);
				}
			}

			if(get_paths.length > 0){
				var save_path = get_paths.shift();
				if(get_paths.length === 0){
					callback(save_path);
				} else {
					for(var i = 0; i < get_paths.length; i++){
						_this.jdb.delete(get_paths[i]);
						b.log.debug('delete dup path', get_paths[i]);
					}
					var merge_data = merge.all(get_data_arr);
					_this.jdb.push(save_path, merge_data, true);

					b.log.debug('save merged', save_path, merge_data);
					callback(save_path);
				}
			} else {
				b.log.warn('merge_case: no data found at ' + base_path + '/' + key_search_regex);
				callback({err: 'no data found at ' + base_path + '/' + key_search_regex})
			}
		} catch(e) {
			if(e.message.match(/Can't find dataPath/) === null){
				b.log.warn('merge_case', e.stack);
			}
			callback({err: e.message})
		}
	}

	//case_insensitive tries to pull the parent node, do regex search, and return that instead
	//case_insensitive = path value to search for insensitive
	update(path, data, overwrite, callback, case_insensitive){
		var _this = this;
		path = _this.fix_path(path);
		case_insensitive = case_insensitive === undefined ? false : case_insensitive;

		try {
			function update_some_data(pth, dat, clbk){
				if(dat === '' || dat === undefined || dat === null){
					_this.jdb.delete(pth);
					if(callback) clbk('remove');
				} else {
					_this.jdb.push(pth, dat, overwrite);
					if(callback) clbk('add');
				}
			}

			var get_paths = [];

			if(case_insensitive !== false){

				var path_arr = path.split('/');
				path_arr = path_arr.filter(function(x){
					return x !== '';
				});

				var p1 = path_arr.slice(0, path_arr.indexOf(case_insensitive));
				var p2 = path_arr.slice(path_arr.indexOf(case_insensitive) + 1);

				_this.merge_case(p1.join('/'), case_insensitive, function(rtn){
					if(!rtn.err){
						update_some_data(rtn + (p2.length > 0 ? '/' + p2.join('/') : ''), data, callback);
					} else {
						update_some_data(path, data, callback);
					}
				});
			}
			else
			{
				update_some_data(path, data, callback);
			}
		} catch(e) {
			b.log.error('db.update', path, e.stack);
		}
	}

	delete(path, callback, case_insensitive){
		var _this = this;
		path = _this.fix_path(path);

		try{
			if(typeof(case_insensitive) === 'string'){

				var path_arr = path.split('/');
				path_arr = path_arr.filter(function(x){
					return x !== '';
				});

				var p1 = path_arr.slice(0, path_arr.indexOf(case_insensitive));
				var p2 = path_arr.slice(path_arr.indexOf(case_insensitive) + 1);

				_this.merge_case(p1.length === 0 ? '/' : p1.join('/'), case_insensitive, function(rtn){
					if(!rtn.err){
						var data = _this.jdb.delete(rtn + (p2.length > 0 ? '/' + p2.join('/') : ''));
						if(callback) callback(true);
					} else {
					   var data = _this.jdb.delete(path);
						if(callback) callback(true);
					}
				});
			}
			else
			{
				var data = _this.jdb.delete(path);
				if(callback) callback(true);
			}
		}catch(e){
			b.log.error('db.delete', e.stack)
			if(callback) callback(false);
		}
	}

	//path to array to manage in db, ie: /bugs, /username/tags
	//args are the args from the command
	//id is required by -delete and -edit
	manage_arr(USER, path, args, options, callback){
		var _this = this;
		path = _this.fix_path(path);

		options = Object.assign({}, {
			case_insensitive: false,
			format: function(item){ return item; }
		}, options);

		function loop_thru(){
			b.log.debug('loop_thru');
			_this.get_data(path, function(d){

				if(d === null || d.length < 1){
					b.log.warn('nothing to loop thru in ' + path);
					callback({err: 'No data to ' + args.flag}, 3);
					return;
				}

				var matched = false;
				var matched_arr = [];

				for(var i = 0; i < d.length; i++){
					var str = USER.t.warn('[' + (i + 1) + '] ') + options.format(d[i]);

				   if(args.id !== undefined && (i + 1) === args.id){
						if(args.flag === '-delete'){
							_this.delete(path + '[' + i + ']', function(deleted){
								if(deleted){
									matched = true;
									callback({succ: 'Deleted: '  + options.format(d[i])}, 3);
									return;
								}
							})
						} else if(args.flag === '-edit'){
							d[i] = options.format(args.new_val);
							_this.update(path, d, true, function(act){
								matched = true;
								callback({succ: 'Updated ' + str + ' -> ' + args.new_val}, 3);
								return;
							});
						}
					} else if (args.id === undefined) {
						matched = true;
						matched_arr.push(str);
					}
				}

				if (matched === false) {
					callback({err: 'No value by that id found'}, 2);
					return;
				} else if(matched === true && matched_arr.length > 0) {
					callback(matched_arr, 3);
					return;
				}
			}, options.case_insensitive);
		}

		if(args.flag !== '-add'){
			loop_thru();
		} else {
			_this.update(path, [args.new_val], false, function(act){
				callback({succ: 'Added: ' + args.new_val});
			});
		}
	};

	//rand = true, send back a random value if no id or search term set
	//rand = false, send back the last item in the array
	search_arr(USER, path, args, rand, callback, case_insensitive){
		var _this = this;
		path = _this.fix_path(path);

		_this.get_data(path, function(data){
			if(data && data.length > 0){
				if(args.id !== undefined){
					if(data[args.id] === undefined){
						callback({err: 'No item with that id found!'}, 0);
					} else {
						callback(data[args.id], 1);
					}
				} else if(args.query !== undefined){
					var search_vals = {};
					var count_found = 0;
					var msg_found = [];
					for(var i = 0; i < data.length; i++){
						if(data[i].toLowerCase().indexOf(args.query.toLowerCase().trim()) > -1){
							count_found++;
							search_vals[i] = data[i];
							msg_found.push(USER.t.warn('[' + i + '] ') + data[i]);
						}
					}

					if(count_found === 0){
						callback({err: 'No values with that search term found!'}, 0);
					} else if (count_found === 1) {
						for(var idd in search_vals){
							callback(data[idd], 1);
						}
					} else {
						callback(msg_found, count_found);
					}
				} else {
					if(rand){
						callback(x.rand_arr(data), 1);
					} else {
						callback(data.slice(-1), 1);
					}
				}
			} else {
				callback({err: 'no values have been set yet!'}, 0);
			}
		}, case_insensitive);
	}
}


text:
<!DOCTYPE html>

    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <meta name="description" content="DeviceAtlas Java Cloud Client API Examples"/>
    <meta name="author" content="Afilias Technologies Ltd "/>
    <title>DeviceAtlas Java Cloud Client API Examples | Redirection</title>
    <link type="text/css" rel="stylesheet" th:href="@{/css/bootstrap.min.css}" href="../../css/bootstrap.min.css" />
    <link type="text/css" rel="stylesheet" th:href="@{/css/jumbotron-narrow.css}" href="../../css/jumbotron-narrow.css" />
    <link type="text/css" rel="stylesheet" th:href="@{/css/deviceatlas.css}" href="../../css/deviceatlas.css" />

Redirection Example

You have been redirected to this page because you are using a highend mobile device with a browser that is able to show HTML and CSS.

How it works

            If we have different web sites and each one is created to give the best
            content and user experience to a specific device type. Users will enter our
            main web-site URL in their browsers, the source code which gets this first
            request will use DeviceAtlas CloudApi to detect the device type, then based
            on the conclusions, the user will be redirected to the web-site which provides
            the best experience for her/his device.

            In this example four directories will mimic four different websites that give
            specific service to "desktop browsers", "mobile device" and "tablet pcs".

The web examples are based on a MVC model where files are placed inside /Examples/ExampleWebApp,
                having controllers in /src/main/java/com/deviceatlas/cloud/example/web
                and views in /src/main/resources.

All requests first go to the ControllerWebApp controller object. Here it is used DeviceAtlas to detect device type and decides which template should be used to wrap around the contents.

View of this page is templates/redirection/mobile_highend.html


text:
import _ from 'lodash';
import mongodb from 'mongodb';
import MongoDatabase from '../../../../server/database/MongoDatabase';
import Client from '../../../../server/models/Client';

const TEST_DATABASE_URL = 'mongodb://localhost:27017/testdb';

describe('MongoDatabase', function() {
  'use strict';

  describe('#ensureConnection', function() {
    it('connects to the database', function(done) {
      var database = new MongoDatabase(TEST_DATABASE_URL);
      database.ensureConnection()
        .then(function(db) {
          expect(db).to.not.be.undefined;
          expect(db.collection).to.not.be.undefined;
          done();
        })
        .catch(function(err) {
          done(err);
        });
    });

    it('does not connect twice on multiple calls', function(done) {
      var database = new MongoDatabase(TEST_DATABASE_URL);
      var firstDb;

      database.ensureConnection()
        .then(function(db) {
          firstDb = db;
          return database.ensureConnection();
        })
        .then(function(db) {
          expect(db).to.be.equal(firstDb);
          done();
        })
        .catch(function(err) {
          done(err);
        });
    });
  });

  describe('CRUD operations', function() {
    beforeEach(function(done) {
      this.clientRfc = 'ABC1123456ABA';
      this.clientData = {
        nombre: 'John Doe',
        rfc: this.clientRfc
      };

      this.database = new MongoDatabase(TEST_DATABASE_URL);
      this.database.ensureConnection()
        .then(_.bind(function(db) {
          this.db = db;

          // Insert mock data
          db.collection('clientes')
            .insert(this.clientData, _.bind(function(err, result) {
              this.clientId = String(result[0]._id);
              done();
            }, this));
        }, this))
        .catch(done);
    });

    afterEach(function(done) {
      this.db.collection('clientes').drop(function(err) {
        if (err) {
          if (err.errmsg === 'ns not found') {
            this.db.close();
            this.database.db.close();
            this.database.close();
            done();
          } else {
            done(err);
          }
        }
        done();
      });
    });

    describe('getting zip codes', function() {
      beforeEach(function(done) {
        this.db.collection('codigospostales').insert({
          _id: '10000',
          estado: 'SIN',
          colonia: 'Centro',
          ciudad: 'Culiacán'
        }, function(err) {
          if (err) {
            done(err);
          } else {
            done();
          }
        });
      });

      afterEach(function(done) {
        this.db.collection('codigospostales').drop(function(err) {
          if (err) {
            if (err.errmsg === 'ns not found') {
              this.db.close();
              this.database.db.close();
              this.database.close();
              done();
            } else {
              done(err);
            }
          }
          done();
        });
      });

      describe('#storeZipCode', function() {
        it('saves a zip code', function(done) {
          this.database.storeZipCode('8000', {
            estado: 'SIN',
            ciudad: 'Culiacán',
            colonia: 'Centro'
          }).then(function() {
            done();
          });
        });
      });

      describe('#getAddressByZipCode', function() {
        it('gets an address', function(done) {
          this.database.getAddressByZipCode('10000')
            .then(function(address) {
              expect(address).to.not.be.null;
              expect(address).to.have.property('estado', 'SIN');
              expect(address).to.have.property('ciudad', 'Culiacán');
              expect(address).to.have.property('colonia', 'Centro');
              done();
            })
            .catch(done);
        });
      });
    });

    describe('#storeClient', function() {
      it('inserts a client in the database', function(done) {
        var _this = this;
        var client = new Client({ 'nombre': 'John Doe' });

        this.database.storeClient(client)
          .then(function(clientFound) {
            expect(clientFound).to.not.be.null;
            client = clientFound;

            expect(client).to.have.property('id').that.is.a('string');

            _this.db.collection('clientes').findOne({
              _id: mongodb.ObjectID(client.id)
            }, function(err, result) {
              if (err) {
                done(err);
              } else {
                expect(String(result._id)).to.be.equal(client.id);
                expect(result.nombre).to.be.equal(client.nombre);
                done();
              }
            });
          })
          .catch(done);
      });
    });

    describe('#findClientById', function() {
      it('get a client by id', function(done) {
        this.database.findClientById(this.clientId)
          .then(_.bind(function(client) {
            expect(client).to.not.be.undefined;
            expect(client).to.be.an.instanceOf(Client);
            expect(client).to.have.property('id', this.id);
            expect(client).to.have.property('nombre', this.clientData.nombre);
            done();
          }, this))
          .catch(done);
      });
    });

    describe('#findClientByRFC', function() {
      it('get a client by rfc', function(done) {
        this.database.findClientByRFC(this.clientRfc)
          .then(_.bind(function(client) {
            expect(client).to.not.be.undefined;
            expect(client).to.be.an.instanceOf(Client);
            expect(client).to.have.property('id', this.id);
            expect(client).to.have.property('nombre', this.clientData.nombre);
            expect(client).to.have.property('rfc', this.clientRfc);
            done();
          }, this))
          .catch(done);
      });
    });

    describe('#deleteClient', function() {
      it('delete a client', function(done) {
        var client = new Client(_.extend(this.clientData, {
          id: this.clientId
        }));

        this.database.deleteClient(client)
          .then(_.bind(function() {
            this.db.collection('clientes').findOne({
              _id: mongodb.ObjectID(client.id)
            }, function(err, result) {
              if (err) {
                done(err);
              } else {
                expect(result).to.be.null;
                done();
              }
            });
          }, this))
          .catch(done);
      });
    });
  });

  describe('#getClients', function() {
    beforeEach(function(done) {
      var clientData = [];

      for (let i = 0; i<100; i++) {
        let rfc = 'ABC' + _.padLeft(i, 6, '0') + 'ABA';
        let numeroCliente = _.padLeft(i, 4, '0');

        clientData.push({
          nombre: 'John',
          apellidoPaterno: 'Doe',
          rfc: rfc,
          numeroCliente: numeroCliente,
          numeroCuenta: '120-001-' + numeroCliente,
          codigoPostal: '80280'
        });
      }

      this.database = new MongoDatabase(TEST_DATABASE_URL);
      this.database.ensureConnection()
        .then(_.bind(function(db) {
          this.db = db;

          // Insert mock data
          db.collection('clientes')
            .insert(clientData, _.bind(function(err) {
              if (err) {
                done(err);
              } else {
                done();
              }
            }, this));
        }, this))
        .catch(done);
    });

    afterEach(function(done) {
      this.db.collection('clientes').drop(function(err) {
        if (err) {
          if (err.errmsg === 'ns not found') {
            this.db.close();
            this.database.db.close();
            this.database.close();
            done();
          } else {
            done(err);
          }
        }
        done();
      });
    });

    it('get limited list of clients', function(done) {
      this.database.getClients()
        .then(_.bind(function(result) {
          expect(result.items).to.not.be.empty;
          expect(result.items).to.have.a.lengthOf(10);
          result.items.forEach(function(client) {
            expect(client).to.be.an.instanceOf(Client);
          });
          done();
        }, this))
        .catch(done);
    });

    it('skips the result as needed', function(done) {
      this.database.getClients({ skip: 10 })
        .then(_.bind(function(result) {
          expect(result.items).to.not.be.empty;
          // We are in the 10th element so rfc should contain a 10
          expect(result.items[0].rfc).to.be.equal('ABC000010ABA');
          done();
        }, this))
        .catch(done);
    });

    it('filter clients by rfc', function(done) {
      this.database.getClients({ rfc: 'ABC000010ABA' })
        .then(_.bind(function(result) {
          expect(result.items).to.not.be.empty;
          expect(result.items).to.have.a.lengthOf(1);
          expect(result.items[0].rfc).to.be.equal('ABC000010ABA');
          done();
        }, this))
        .catch(done);
    });

    it('filter clients by rfc in case insensitive', function(done) {
      this.database.getClients({ rfc: 'ABC000010aba' })
        .then(_.bind(function(result) {
          expect(result.items).to.not.be.empty;
          expect(result.items).to.have.a.lengthOf(1);
          expect(result.items[0].rfc).to.be.equal('ABC000010ABA');
          done();
        }, this))
        .catch(done);
    });

  });
});