text:
# fs-jetpack [![codecov](https://codecov.io/gh/szwacz/fs-jetpack/branch/master/graph/badge.svg)](https://codecov.io/gh/szwacz/fs-jetpack)

API for your everyday file system manipulations, much more convenient than [fs](http://nodejs.org/api/fs.html) or [fs-extra](https://github.com/jprichardson/node-fs-extra). You will especially appreciate it as a scripting/tooling library and for your build pipelines.

# Table of Contents

[Key Concepts](#key-concepts)
[Getting Started](#getting-started)

**API:**
[append](#appendpath-data-options)
[copy](#copyfrom-to-options)
[createReadStream](#createreadstreampath-options)
[createWriteStream](#createwritestreampath-options)
[cwd](#cwdpath)
[dir](#dirpath-criteria)
[exists](#existspath)
[file](#filepath-criteria)
[find](#findpath-searchoptions)
[inspect](#inspectpath-options)
[inspectTree](#inspecttreepath-options)
[list](#listpath)
[move](#movefrom-to-options)
[path](#pathparts)
[read](#readpath-returnas)
[remove](#removepath)
[rename](#renamepath-newname-options)
[symlink](#symlinksymlinkvalue-path)
[tmpDir](#tmpdiroptions)
[write](#writepath-data-options)

# Key Concepts

### Why not use more than one CWD?

You can create many fs-jetpack objects with different internal working directories (which are independent from `process.cwd()`) and work on directories in a little more object-oriented manner.

```js
const src = jetpack.cwd("path/to/source");
const dest = jetpack.cwd("/some/different/path/to/destination");
src.copy("foo.txt", dest.path("bar.txt"));
```

### JSON is a first class citizen

You can write JavaScript object directly to disk and it will be transformed into JSON automatically.

```js
const obj = { greet: "Hello World!" };
jetpack.write("file.json", obj);
```

Then you can get your object back just by telling `read` method that it's a JSON.

```js
const obj = jetpack.read("file.json", "json");
```

### Automatic handling of ENOENT errors

Everyone who has a lot to do with file system probably is sick of seeing error _"ENOENT, no such file or directory"_. Fs-jetpack tries to recover from this.

- For write/creation operations, if any of parent directories doesn't exist jetpack will just create them as well (like `mkdir -p` works).
- For read/inspect operations, if file or directory doesn't exist `undefined` is returned instead of throwing.

### Sync & async harmony

API has the same set of synchronous and asynchronous methods. All async methods are promise based (no callbacks).

Commonly used naming convention in node.js world has been flipped in this API, so no `method()` (async) and `methodSync()` naming. Here the convention is `methodAsync()` and `method()` (sync). I know this looks wrong to you, but bear with me. Thanks to that, you always know how fs-jetpack method behaves, just by looking at the name: **If you don't see the word "Async", this method returns value immediately, if you do, promise is returned.** Standard node.js naming can't give you this clarity.

```js
// Synchronous call
const data = jetpack.read('file.txt');
console.log(data);

// Asynchronous call
const data = await jetpack.readAsync('file.txt');
console.log(data);
```

## All API methods cooperate nicely with each other

Let's say you want to create folder structure as demonstrated in comment below. Piece of cake!

```js
// .
// |- greets
//    |- greet.txt
//    |- greet.json
// |- greets-i18n
//    |- polish.txt

jetpack
  .dir("greets")
  .file("greet.txt", { content: "Hello world!" })
  .file("greet.json", { content: { greet: "Hello world!" } })
  .cwd("..")
  .dir("greets-i18n")
  .file("polish.txt", { content: "Witaj świecie!" });
```

Need to copy whole directory of files, but first perform some transformations on each file?

```js
const src = jetpack.cwd("path/to/source/folder");
const dst = jetpack.cwd("path/to/destination");

src.find({ matching: "*" }).forEach((path) => {
  const content = src.read(path);
  const transformedContent = transformTheFileHoweverYouWant(content);
  dst.write(path, transformedContent);
});
```

Need to delete all temporary and log files inside `my_folder` tree?

```js
jetpack.find("my_folder", { matching: ["*.tmp", "*.log"] }).forEach(jetpack.remove);
```

Need to perform temporary data transformations?

```js
const dir = jetpack.tmpDir();
dir.write("data.txt", myData);
// Perform some operations on the data and when you're done
// and don't need the folder any longer just call...
dir.remove();
```

# Getting Started

## Installation

```
npm install fs-jetpack
```

Import to your code:

```javascript
const jetpack = require("fs-jetpack");
```

## Usage with TypeScript

Starting from v2.1.0 fs-jetpack is TypeScript compatible. But for backwards compatibility purposes all types and interfaces are reachable through special path `fs-jetpack/types`.

```typescript
// Import fs-jetpack into TypeScript code (the jetpack typings will be loaded as well).
import * as jetpack from "fs-jetpack";

// Import one of jetpack's interfaces to cast it on a variable declaration.
import { InspectResult } from "fs-jetpack/types";
let result: InspectResult = jetpack.inspect("foo");
```

## Upgrading to New Version

This API is considered stable and all breaking changes to it are done as completely last resort. It also uses "better safe than sorry" approach to bumping major version number. So in 99.9% of cases you can upgrade to latest version with no worries, because all major version bumps so far, were due to edge case behaviour changes.

# API

## append(path, data, [options])

asynchronous: **appendAsync(path, data, [options])**

Appends given data to the end of file. If file or any parent directory doesn't exist it will be created.

**arguments:**
`path` the path to file.
`data` data to append (can be `String` or `Buffer`).
`options` (optional) `Object` with possible fields:

- `mode` if the file doesn't exist yet, will be created with given mode. Value could be number (eg. `0o700`) or string (eg. `'700'`).

**returns:**
Nothing.

## copy(from, to, [options])

asynchronous: **copyAsync(from, to, [options])**

Copies given file or directory (with everything inside).

**arguments:**
`from` path to location you want to copy.
`to` path to destination location, where the copy should be placed.
`options` (optional) additional options for customization. Is an `Object` with possible fields:

- `overwrite` (default: `false`) Whether to overwrite destination path when it already exists. Can be `Boolean` or `Function`. If `false`, an error will be thrown if it already exists. If `true`, the overwrite will be performed (for directories, this overwrite consists of a recursive merge - i.e. only files that already exist in the destination directory will be overwritten). If a function was provided, every time there is a file conflict while copying the function will be invoked with [inspect](#inspectpath-options) objects of both: source and destination file and overwrites the file only if `true` has been returned from the function (see example below). In async mode, the overwrite function can also return a promise, so you can perform multi step processes to determine if file should be overwritten or not (see example below).
- `matching` if defined will actually copy **only** items matching any of specified glob patterns and omit everything else ([all possible globs are described further in this readme](#matching-patterns)).
- `ignoreCase` (default `false`) whether or not case should be ignored when processing glob patterns passed through the `matching` option.

**returns:**
Nothing.

**examples:**

```javascript
// Copies a file (and replaces it if one already exists in 'foo' directory)
jetpack.copy("file.txt", "foo/file.txt", { overwrite: true });

// Copies files from folder foo_1 to foo_final, but overwrites in
// foo_final only files which are newer in foo_1.
jetpack.copy("foo_1", "foo_final", {
  overwrite: (srcInspectData, destInspectData) => {
    return srcInspectData.modifyTime > destInspectData.modifyTime;
  }
});

// Asynchronously copies files from folder foo_1 to foo_final,
// but overwrites only files containing "John Doe" string.
jetpack.copyAsync("foo_1", "foo_final", {
  overwrite: (srcInspectData, destInspectData) => {
    return jetpack.readAsync(srcInspectData.absolutePath).then(data => {
      return data.includes("John Doe");
    });
  }
});

// Copies only '.md' files from 'foo' (and subdirectories of 'foo') to 'bar'.
jetpack.copy("foo", "bar", { matching: "*.md" });
// Copies only '.md' and '.txt' files from 'foo' (and subdirectories of 'foo') to 'bar'.
jetpack.copy("foo", "bar", { matching: ["*.md", "*.txt"] });

// You can filter previous matches by defining negated pattern further in the order:
// Copies only '.md' files from 'foo' (and subdirectories of 'foo') to 'bar'
// but will skip file '!top-secret.md'.
jetpack.copy("foo", "bar", { matching: ["*.md", "!top-secret.md"] });
// Copies only '.md' files from 'foo' (and subdirectories of 'foo') to 'bar'
// but will skip all files in 'foo/top-secret' directory.
jetpack.copy("foo", "bar", { matching: ["*.md", "!top-secret/**/*"] });

// All patterns are anchored to directory you want to copy, not to CWD.
// So in this example directory 'dir1/dir2/images' will be copied
// to 'copied-dir2/images'
jetpack.copy("dir1/dir2", "copied-dir2", {
  matching: "images/**"
});
```

## createReadStream(path, [options])

Just an alias to vanilla [fs.createReadStream](http://nodejs.org/api/fs.html#fs_fs_createreadstream_path_options).

## createWriteStream(path, [options])

Just an alias to vanilla [fs.createWriteStream](http://nodejs.org/api/fs.html#fs_fs_createwritestream_path_options).

## cwd([path...])

Returns Current Working Directory (CWD) for this instance of jetpack, or creates new jetpack object with given path as its internal CWD.

**Note:** fs-jetpack never changes value of `process.cwd()`, the CWD we are talking about here is internal value inside every jetpack instance.

**arguments:**
`path...` (optional) path (or many path parts) to become new CWD. Could be absolute, or relative. If relative path given new CWD will be resolved basing on current CWD of this jetpack instance.

**returns:**
If `path` not specified, returns CWD path of this jetpack object. For main instance of fs-jetpack it is always `process.cwd()`.
If `path` specified, returns new jetpack object (totally the same thing as main jetpack). The new object resolves paths according to its internal CWD, not the global one (`process.cwd()`).

**examples:**

```javascript
// Let's assume that process.cwd() outputs...
console.log(process.cwd()); // '/one/two/three'
// jetpack.cwd() will always return the same value as process.cwd()
console.log(jetpack.cwd()); // '/one/two/three'

// Now let's create new CWD context...
const jetParent = jetpack.cwd("..");
console.log(jetParent.cwd()); // '/one/two'
// ...and use this new context.
jetParent.dir("four"); // we just created directory '/one/two/four'

// One CWD context can be used to create next CWD context.
const jetParentParent = jetParent.cwd("..");
console.log(jetParentParent.cwd()); // '/one'

// When many parameters specified they are treated as parts of path to resolve
const sillyCwd = jetpack.cwd("a", "b", "c");
console.log(sillyCwd.cwd()); // '/one/two/three/a/b/c'
```

## dir(path, [criteria])

asynchronous: **dirAsync(path, [criteria])**

Ensures that directory on given path exists and meets given criteria. If any criterium is not met it will be after this call. If any parent directory in `path` doesn't exist it will be created (like `mkdir -p`).

If the given path already exists but is not a directory, an error will be thrown.

**arguments:**
`path` path to directory to examine.
`criteria` (optional) criteria to be met by the directory. Is an `Object` with possible fields:

- `empty` (default: `false`) whether directory should be empty (no other files or directories inside). If set to `true` and directory contains any files or subdirectories all of them will be deleted.
- `mode` ensures directory has specified mode. If not set and directory already exists, current mode will be preserved. Value could be number (eg. `0o700`) or string (eg. `'700'`).

**returns:**
New CWD context with directory specified in `path` as CWD (see docs of `cwd()` method for explanation).

**examples:**

```javascript
// Creates directory if doesn't exist
jetpack.dir("new-dir");

// Makes sure directory mode is 0700 and that it's empty
jetpack.dir("empty-dir", { empty: true, mode: "700" });

// Because dir returns new CWD context pointing to just
// created directory you can create dir chains.
jetpack
  .dir("main-dir") // creates 'main-dir'
  .dir("sub-dir"); // creates 'main-dir/sub-dir'
```

## exists(path)

asynchronous: **existsAsync(path)**

Checks whether something exists on given `path`. This method returns values more specific than `true/false` to protect from errors like "I was expecting directory, but it was a file".

**returns:**

- `false` if path doesn't exist.
- `"dir"` if path is a directory.
- `"file"` if path is a file.
- `"other"` if none of the above.

## file(path, [criteria])

asynchronous: **fileAsync(path, [criteria])**

Ensures that file exists and meets given criteria. If any criterium is not met it will be after this call. If any parent directory in `path` doesn't exist it will be created (like `mkdir -p`).

**arguments:**
`path` path to file to examine.
`criteria` (optional) criteria to be met by the file. Is an `Object` with possible fields:

- `content` sets file content. Can be `String`, `Buffer`, `Object` or `Array`. If `Object` or `Array` given to this parameter data will be written as JSON.
- `jsonIndent` (defaults to 2) if writing JSON data this tells how many spaces should one indentation have.
- `mode` ensures file has specified mode. If not set and file already exists, current mode will be preserved. Value could be number (eg. `0o700`) or string (eg. `'700'`).

**returns:**
Jetpack object you called this method on (self).

**examples:**

```javascript
// Creates file if doesn't exist
jetpack.file("something.txt");

// Creates file with mode '777' and content 'Hello World!'
jetpack.file("hello.txt", { mode: "777", content: "Hello World!" });
```

## find([path], searchOptions)

asynchronous: **findAsync([path], searchOptions)**

Finds in directory specified by `path` all files fulfilling `searchOptions`. Returned paths are relative to current CWD of jetpack instance.

**arguments:**
`path` (optional, defaults to `'.'`) path to start search in (all subdirectories will be searched).
`searchOptions` is an `Object` with possible fields:

- `matching` (default `"*"`) glob patterns of files you want to find ([all possible globs are described further in this readme](#matching-patterns)).
- `filter` (default `undefined`) function that is called on each matched path with [inspect object](#inspectpath-options) of that path as an argument. Return `true` or `false` to indicate whether given path should stay on list or should be filtered out (see example below).
- `files` (default `true`) whether or not should search for files.
- `directories` (default `false`) whether or not should search for directories.
- `recursive` (default `true`) whether the whole directory tree should be searched recursively, or only one-level of given directory (excluding it's subdirectories).
- `ignoreCase` (`false` otherwise) whether or not case should be ignored when processing glob patterns passed through the `matching` option.

**returns:**
`Array` of found paths.

**examples:**

```javascript
// Finds all files inside 'foo' directory and its subdirectories
jetpack.find("foo");

// Finds all files which has 2015 in the name
jetpack.find("my-work", { matching: "*2015*" });

// Finds all '.txt' files inside 'foo/bar' directory and its subdirectories
jetpack.find("foo", { matching: "bar/**/*.txt" });
// Finds all '.txt' files inside 'foo/bar' directory WITHOUT subdirectories
jetpack.find("foo", { matching: "bar/*.txt" });

// Finds all '.txt' files that were modified after 2019-01-01
const borderDate = new Date("2019-01-01")
jetpack.find("foo", {
  matching: "*.txt",
  filter: (inspectObj) => {
    return inspectObj.modifyTime > borderDate
  }
});

// Finds all '.js' files inside 'my-project' but excluding those in 'vendor' subtree.
jetpack.find("my-project", { matching: ["*.js", "!vendor/**/*"] });

// Looks for all directories named 'foo' (and will omit all files named 'foo').
jetpack.find("my-work", { matching: ["foo"], files: false, directories: true });

// Finds all '.txt' files inside 'foo' directory WITHOUT subdirectories
jetpack.find("foo", { matching: "./*.txt" });
// This line does the same as the above, but has better performance
// (skips looking in subdirectories)
jetpack.find("foo", { matching: "*.txt", recursive: false });

// Path parameter might be omitted and CWD is used as path in that case.
const myStuffDir = jetpack.cwd("my-stuff");
myStuffDir.find({ matching: ["*.md"] });

// You can chain find() with different jetpack methods for more power.
// For example lets delete all `.tmp` files inside `foo` directory
jetpack
  .find("foo", {
    matching: "*.tmp"
  })
  .forEach(jetpack.remove);
```

## inspect(path, [options])

asynchronous: **inspectAsync(path, [options])**

Inspects given path (replacement for `fs.stat`). Returned object by default contains only very basic, not platform-dependent properties (so you have something e.g. your unit tests can rely on), you can enable more properties through options object.

**arguments:**
`path` path to inspect.
`options` (optional). Possible values:

- `checksum` if specified will return checksum of inspected file. Possible values are strings `'md5'`, `'sha1'`, `'sha256'` or `'sha512'`. If given path is a directory this field is ignored.
- `mode` (default `false`) if set to `true` will add file mode (unix file permissions) value.
- `times` (default `false`) if set to `true` will add atime, mtime and ctime fields (here called `accessTime`, `modifyTime`, `changeTime` and `birthTime`).
- `absolutePath` (default `false`) if set to `true` will add absolute path to this resource.
- `symlinks` (default `'report'`) if a given path is a symlink by default `inspect` will report that symlink (not follow it). You can flip this behaviour by setting this option to `'follow'`.

**returns:**
`undefined` if given path doens't exist.
Otherwise `Object` of structure:

```javascript
{
  name: "my_dir",
  type: "file", // possible values: "file", "dir", "symlink"
  size: 123, // size in bytes, this is returned only for files
  // if checksum option was specified:
  md5: '900150983cd24fb0d6963f7d28e17f72',
  // if mode option was set to true:
  mode: 33204,
  // if times option was set to true:
  accessTime: [object Date],
  modifyTime: [object Date],
  changeTime: [object Date],
  birthTime: [object Date]
}
```

## inspectTree(path, [options])

asynchronous: **inspectTreeAsync(path, [options])**

Calls [inspect](#inspectpath-options) recursively on given path so it creates tree of all directories and sub-directories inside it.

**arguments:**
`path` the starting path to inspect.
`options` (optional). Possible values:

- `checksum` if specified will also calculate checksum of every item in the tree. Possible values are strings `'md5'`, `'sha1'`, `'sha256'` or `'sha512'`. Checksums for directories are calculated as checksum of all children' checksums plus their filenames (see example below).
- `times` (default `false`) if set to `true` will add atime, mtime and ctime fields (here called `accessTime`, `modifyTime` and `changeTime`) to each tree node.
- `relativePath` if set to `true` every tree node will have relative path anchored to root inspected folder.
- `symlinks` (default `'report'`) if a given path is a symlink by default `inspectTree` will report that symlink (not follow it). You can flip this behaviour by setting this option to `'follow'`.

**returns:**
`undefined` if given path doesn't exist.
Otherwise tree of inspect objects like:

```javascript
{
    name: 'my_dir',
    type: 'dir',
    size: 123, // this is combined size of all items in this directory
    relativePath: '.',
    md5: '11c68d9ad988ff4d98768193ab66a646',
    // checksum of this directory was calculated as:
    // md5(child[0].name + child[0].md5 + child[1].name + child[1].md5)
    children: [
        {
            name: 'empty',
            type: 'dir',
            size: 0,
            relativePath: './dir',
            md5: 'd41d8cd98f00b204e9800998ecf8427e',
            children: []
        },{
            name: 'file.txt',
            type: 'file',
            size: 123,
            relativePath: './file.txt',
            md5: '900150983cd24fb0d6963f7d28e17f72'
        }
    ]
}
```

## list([path])

asynchronous: **listAsync(path)**

Lists the contents of directory. Equivalent of `fs.readdir`.

**arguments:**
`path` (optional) path to directory you would like to list. If not specified defaults to CWD.

**returns:**
Array of file names inside given path, or `undefined` if given path doesn't exist.

## move(from, to, [options])

asynchronous: **moveAsync(from, to, [options])**

Moves given path to new location.

**arguments:**
`from` path to directory or file you want to move.
`to` path where the thing should be moved.
`options` (optional) additional options for customization. Is an `Object` with possible fields:

- `overwrite` (default: `false`) Whether to overwrite destination path when it already exists. If `true`, the overwrite will be performed.

**returns:**
Nothing.

## path(parts...)

Returns path resolved to internal CWD of this jetpack object.

**arguments:**
`parts` strings to join and resolve as path (as many as you like).

**returns:**
Resolved path as string.

**examples:**

```javascript
jetpack.cwd(); // if it returns '/one/two'
jetpack.path(); // this will return the same '/one/two'
jetpack.path("three"); // this will return '/one/two/three'
jetpack.path("..", "four"); // this will return '/one/four'
```

## read(path, [returnAs])

asynchronous: **readAsync(path, [returnAs])**

Reads content of file.

**arguments:**
`path` path to file.
`returnAs` (optional) how the content of file should be returned. Is a string with possible values:

- `'utf8'` (default) content will be returned as UTF-8 String.
- `'buffer'` content will be returned as a Buffer.
- `'json'` content will be returned as parsed JSON object.
- `'jsonWithDates'` content will be returned as parsed JSON object, and date strings in [ISO format](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString) will be automatically turned into Date objects.

**returns:**
File content in specified format, or `undefined` if file doesn't exist.

## remove([path])

asynchronous: **removeAsync([path])**

Deletes given path, no matter what it is (file, directory or non-empty directory). If path already doesn't exist terminates gracefully without throwing, so you can use it as 'ensure path doesn't exist'.

**arguments:**
`path` (optional) path to file or directory you want to remove. If not specified the remove action will be performed on current working directory (CWD).

**returns:**
Nothing.

**examples:**

```javascript
// Deletes file
jetpack.remove("my_work/notes.txt");

// Deletes directory "important_stuff" and everything inside
jetpack.remove("my_work/important_stuff");

// Remove can be called with no parameters and will default to CWD then.
// In this example folder 'my_work' will cease to exist.
const myStuffDir = jetpack.cwd("my_stuff");
myStuffDir.remove();
```

## rename(path, newName, [options])

asynchronous: **renameAsync(path, newName, [options])**

Renames given file or directory.

**arguments:**
`path` path to thing you want to change name of.
`newName` new name for this thing (not full path, just a name).
`options` (optional) additional options for customization. Is an `Object` with possible fields:

- `overwrite` (default: `false`) Whether to overwrite destination path when it already exists. If `true`, the overwrite will be performed.

**returns:**
Nothing.

**examples:**

```javascript
// The file "my_work/important.md" will be renamed to "my_work/very_important.md"
jetpack.rename("my_work/important.txt", "very_important.md");
```

## symlink(symlinkValue, path)

asynchronous: **symlinkAsync(symlinkValue, path)**

Creates symbolic link.

**arguments:**
`symlinkValue` path where symbolic link should point.
`path` path where symbolic link should be put.

**returns:**
Nothing.

## tmpDir([options])

asynchronous: **tmpDirAsync([options])**

Creates temporary directory with random, unique name.

**arguments:**
`options` (optional) `Object` with possible fields:

- `prefix` prefix to be added to created random directory name. Defaults to none.
- `basePath` the path where temporary directory should be created. Defaults to [https://nodejs.org/api/os.html#os_os_tmpdir](os.tmpdir).

**returns:**
New CWD context with temporary directory specified in `path` as CWD (see docs of `cwd()` method for explanation).

**examples:**

```javascript
// Creates temporary directory, e.g. /tmp/90ed0f0f4a0ba3b1433c5b51ad8fc76b
// You can interact with this directory by returned CWD context.
const dirContext = jetpack.tmpDir();

// Creates temporary directory with a prefix, e.g. /tmp/foo_90ed0f0f4a0ba3b1433c5b51ad8fc76b
jetpack.tmpDir({ prefix: "foo_" });

// Creates temporary directory on given path, e.g. /some/other/path/90ed0f0f4a0ba3b1433c5b51ad8fc76b
jetpack.tmpDir({ basePath: "/some/other/path" });

// Creates temporary directory on jetpack.cwd() path
jetpack.tmpDir({ basePath: "." });

// The method returns new jetpack context, so you can easily clean your
// temp files after you're done.
const dir = jetpack.tmpDir();
dir.write("foo.txt", data);
// ...and when you're done using the dir...
dir.remove();
```

## write(path, data, [options])

asynchronous: **writeAsync(path, data, [options])**

Writes data to file. If any parent directory in `path` doesn't exist it will be created (like `mkdir -p`).

**arguments:**
`path` path to file.
`data` data to be written. This could be `String`, `Buffer`, `Object` or `Array` (if last two used, the data will be outputted into file as JSON).
`options` (optional) `Object` with possible fields:

- `mode` file will be created with given mode. Value could be number (eg. `0o700`) or string (eg. `'700'`).
- `atomic` (default `false`) if set to `true` the file will be written using strategy which is much more resistant to data loss. The trick is very simple, [read this to get the concept](http://stackoverflow.com/questions/17047994/transactionally-writing-files-in-node-js).
- `jsonIndent` (defaults to 2) if writing JSON data this tells how many spaces should one indentation have.

**returns:**
Nothing.

# Matching patterns

API methods [copy](#copyfrom-to-options) and [find](#findpath-searchoptions) have `matching` option. Those are all the possible tokens to use there:

- `*` - Matches 0 or more characters in a single path portion.
- `?` - Matches 1 character.
- `!` - Used as the first character in pattern will invert the matching logic (match everything what **is not** matched by tokens further in this pattern).
- `[...]` - Matches a range of characters, similar to a RegExp range. If the first character of the range is `!` or `^` then it matches any character not in the range.
- `@(pattern|pat*|pat?ern)` - Matches exactly one of the patterns provided.
- `+(pattern|pat*|pat?ern)` - Matches one or more occurrences of the patterns provided.
- `?(pattern|pat*|pat?ern)` - Matches zero or one occurrence of the patterns provided.
- `*(pattern|pat*|pat?ern)` - Matches zero or more occurrences of the patterns provided.
- `!(pattern|pat*|pat?ern)` - Matches anything that does not match any of the patterns provided.
- `**` - If a "globstar" is alone in a path portion, then it matches zero or more directories and subdirectories.

_(explanation borrowed from [glob](https://github.com/isaacs/node-glob) which is using [the same matching library](https://github.com/isaacs/minimatch) as this project)_


text:
package com.p1.mobile.p1android.ui.phone;

import android.support.v4.app.FragmentActivity;

import com.flurry.android.FlurryAgent;
import com.p1.mobile.p1android.BuildConfig;
import com.p1.mobile.p1android.P1Application;

public abstract class FlurryFragmentActivity extends FragmentActivity {
    @Override
    protected void onStart() {
        super.onStart();
        if (!BuildConfig.DEBUG) {
            FlurryAgent.onStartSession(this, P1Application.FLURRY_API_KEY);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (!BuildConfig.DEBUG) {
            FlurryAgent.onEndSession(this);
        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Proc. Acad. nat. Sci. Philad. , 1893 45: 128 (1893)

#### Original name
Asterina graminicola Ellis & Everh.

### Remarks
null


text:
describe Crashbreak::BasicSerializer do
  subject { described_class.new }

  let(:example_request) { double(:request) }
  let(:example_exception) { double(:exception) }
  let(:example_controller) { double(:controller) }

  before(:each) do
    RequestStore.store[:request] = example_request
    RequestStore.store[:exception] = example_exception
    RequestStore.store[:controller] = example_controller
  end

  it 'returns request' do
    expect(subject.send(:request)).to eq(example_request)
  end

  it 'returns exception' do
    expect(subject.send(:exception)).to eq(example_exception)
  end

  it 'returns controller' do
    expect(subject.send(:controller)).to eq(example_controller)
  end
end


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Immutable;
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Implementation.LanguageClient;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Editor.Xaml;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServer;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.LanguageServer.Client;
using Microsoft.VisualStudio.LanguageServer.Protocol;
using Microsoft.VisualStudio.LanguageServices.Xaml.LanguageServer;
using Microsoft.VisualStudio.Utilities;

namespace Microsoft.VisualStudio.LanguageServices.Xaml
{
    /// <summary>
    /// Experimental XAML Language Server Client used everywhere when
    /// <see cref="XamlOptions.EnableLspIntelliSenseFeatureFlag"/> is turned on.
    /// </summary>
    [ContentType(ContentTypeNames.XamlContentType)]
    [Export(typeof(ILanguageClient))]
    internal class XamlInProcLanguageClient : AbstractInProcLanguageClient
    {
        [ImportingConstructor]
        [Obsolete(MefConstruction.ImportingConstructorMessage, true)]
        public XamlInProcLanguageClient(
            XamlLspServiceProvider lspServiceProvider,
            IGlobalOptionService globalOptions,
            IAsynchronousOperationListenerProvider listenerProvider,
            ILspLoggerFactory lspLoggerFactory,
            IThreadingContext threadingContext)
            : base(lspServiceProvider, globalOptions, listenerProvider, lspLoggerFactory, threadingContext)
        {
        }

        protected override ImmutableArray<string> SupportedLanguages => ImmutableArray.Create(StringConstants.XamlLanguageName);

        public override ServerCapabilities GetCapabilities(ClientCapabilities clientCapabilities)
        {
            var isLspExperimentEnabled = IsXamlLspIntelliSenseEnabled();

            return isLspExperimentEnabled ? XamlCapabilities.Current : XamlCapabilities.None;
        }

        /// <summary>
        /// Failures are only catastrophic when this server is providing intellisense features.
        /// </summary>
        public override bool ShowNotificationOnInitializeFailed => IsXamlLspIntelliSenseEnabled();

        public override WellKnownLspServerKinds ServerKind => WellKnownLspServerKinds.XamlLspServer;

        private bool IsXamlLspIntelliSenseEnabled()
            => GlobalOptions.GetOption(XamlOptions.EnableLspIntelliSenseFeatureFlag);
    }
}


text:
package org.apache.carbondata.spark.testsuite.sortcolumns

import org.scalatest.BeforeAndAfterAll
import org.apache.carbondata.core.constants.CarbonCommonConstants
import org.apache.carbondata.core.util.CarbonProperties
import org.apache.carbondata.spark.exception.MalformedCarbonCommandException
import org.apache.spark.sql.test.util.QueryTest

class TestSortColumns extends QueryTest with BeforeAndAfterAll {

  override def beforeAll {
    dropTable

    sql("CREATE TABLE origintable1 (empno int, empname String, designation String, doj Timestamp, workgroupcategory int, workgroupcategoryname String, deptno int, deptname String, projectcode int, projectjoindate Timestamp, projectenddate Timestamp,attendance int,utilization int,salary int) STORED BY 'org.apache.carbondata.format'")
    sql(s"""LOAD DATA local inpath '$resourcesPath/data.csv' INTO TABLE origintable1 OPTIONS('DELIMITER'= ',', 'QUOTECHAR'= '\"')""")
  }

  test("create table with no dictionary sort_columns") {
    sql("CREATE TABLE sorttable1 (empno int, empname String, designation String, doj Timestamp, workgroupcategory int, workgroupcategoryname String, deptno int, deptname String, projectcode int, projectjoindate Timestamp, projectenddate Timestamp,attendance int,utilization int,salary int) STORED BY 'org.apache.carbondata.format' tblproperties('sort_columns'='empno')")
    sql(s"""LOAD DATA local inpath '$resourcesPath/data.csv' INTO TABLE sorttable1 OPTIONS('DELIMITER'= ',', 'QUOTECHAR'= '\"')""")
    checkAnswer(sql("select empno from sorttable1"), sql("select empno from sorttable1 order by empno"))
  }

  test("create table with no dictionary sort_columns with dictionary exclude") {
    sql(
      "CREATE TABLE sorttable1a (empno String, empname String, designation String, doj Timestamp," +
      " workgroupcategory int, workgroupcategoryname String, deptno int, deptname String, " +
      "projectcode int, projectjoindate Timestamp, projectenddate Timestamp,attendance int," +
      "utilization int,salary int) STORED BY 'org.apache.carbondata.format' tblproperties" +
      "('dictionary_exclude'='empno','sort_columns'='empno')")
    sql(
      s"""LOAD DATA local inpath '$resourcesPath/data.csv' INTO TABLE sorttable1a OPTIONS
         |('DELIMITER'= ',', 'QUOTECHAR'= '\"','SORT_SCOPE'='BATCH_SORT',
         |'batch_sort_size_inmb'='64')""".stripMargin)
    checkAnswer(sql("select empname from sorttable1a"),
      sql("select empname from origintable1 order by empname"))
  }

  test(
    "create table with no dictionary sort_columns where NumberOfNoDictSortColumns < " +
    "NoDictionaryCount")
  {
    sql(
      "CREATE TABLE sorttable1b (empno String, empname String, designation String, doj Timestamp," +
      " workgroupcategory int, workgroupcategoryname String, deptno int, deptname String, " +
      "projectcode int, projectjoindate Timestamp, projectenddate Timestamp,attendance int," +
      "utilization int,salary int) STORED BY 'org.apache.carbondata.format' tblproperties" +
      "('dictionary_exclude'='empno,empname,workgroupcategoryname','sort_columns'='empno,empname')")
    sql(
      s"""LOAD DATA local inpath '$resourcesPath/data.csv' INTO TABLE sorttable1b OPTIONS
          |('DELIMITER'= ',', 'QUOTECHAR'= '\"','SORT_SCOPE'='BATCH_SORT',
          |'batch_sort_size_inmb'='64')""".stripMargin)
    checkAnswer(sql("select empname from sorttable1b"),
      sql("select empname from origintable1 order by empname"))
  }

  test("create table with dictionary sort_columns") {
    sql("CREATE TABLE sorttable2 (empno int, empname String, designation String, doj Timestamp, workgroupcategory int, workgroupcategoryname String, deptno int, deptname String, projectcode int, projectjoindate Timestamp, projectenddate Timestamp,attendance int,utilization int,salary int) STORED BY 'org.apache.carbondata.format' tblproperties('sort_columns'='empname', 'dictionary_include'='empname')")
    sql(s"""LOAD DATA local inpath '$resourcesPath/data.csv' INTO TABLE sorttable2 OPTIONS('DELIMITER'= ',', 'QUOTECHAR'= '\"')""")
    checkAnswer(sql("select empname from sorttable2"),sql("select empname from origintable1"))
  }

  test("create table with direct-dictioanry sort_columns") {
    sql("CREATE TABLE sorttable3 (empno int, empname String, designation String, doj Timestamp, workgroupcategory int, workgroupcategoryname String, deptno int, deptname String, projectcode int, projectjoindate Timestamp, projectenddate Timestamp,attendance int,utilization int,salary int) STORED BY 'org.apache.carbondata.format' tblproperties('sort_columns'='doj')")
    sql(s"""LOAD DATA local inpath '$resourcesPath/data.csv' INTO TABLE sorttable3 OPTIONS('DELIMITER'= ',', 'QUOTECHAR'= '\"')""")
    checkAnswer(sql("select doj from sorttable3"), sql("select doj from sorttable3 order by doj"))
  }

  test("create table with multi-sort_columns and data loading with offheap safe") {
    try {
      setLoadingProperties("true", "false", "false")
      sql("CREATE TABLE sorttable4_offheap_safe (empno int, empname String, designation String, doj Timestamp, workgroupcategory int, workgroupcategoryname String, deptno int, deptname String, projectcode int, projectjoindate Timestamp, projectenddate Timestamp,attendance int,utilization int,salary int) STORED BY 'org.apache.carbondata.format' tblproperties('sort_columns'='workgroupcategory, empname')")
      sql(s"""LOAD DATA local inpath '$resourcesPath/data.csv' INTO TABLE sorttable4_offheap_safe OPTIONS('DELIMITER'= ',', 'QUOTECHAR'= '\"')""")
      checkAnswer(sql("select workgroupcategory, empname from sorttable4_offheap_safe"), sql("select workgroupcategory, empname from origintable1 order by workgroupcategory"))
    } finally {
      defaultLoadingProperties
    }
  }

  test("create table with multi-sort_columns and data loading with offheap and unsafe sort") {
    try {
      setLoadingProperties("true", "true", "false")
      sql(
        "CREATE TABLE sorttable4_offheap_unsafe (empno int, empname String, designation String, doj Timestamp, workgroupcategory int, workgroupcategoryname String, deptno int, deptname String, projectcode int, projectjoindate Timestamp, projectenddate Timestamp,attendance int,utilization int,salary int) STORED BY 'org.apache.carbondata.format' tblproperties('sort_columns'='workgroupcategory, empname')")
      sql(s"""LOAD DATA local inpath '$resourcesPath/data.csv' INTO TABLE sorttable4_offheap_unsafe OPTIONS('DELIMITER'= ',', 'QUOTECHAR'= '\"')""")
      checkAnswer(sql("select workgroupcategory, empname from sorttable4_offheap_unsafe"),
        sql("select workgroupcategory, empname from origintable1 order by workgroupcategory"))
    } finally {
      defaultLoadingProperties
    }
  }

  test("create table with multi-sort_columns and data loading with offheap and inmemory sort") {
    try {
      setLoadingProperties("true", "false", "true")
      sql(
        "CREATE TABLE sorttable4_offheap_inmemory (empno int, empname String, designation String, doj Timestamp, workgroupcategory int, workgroupcategoryname String, deptno int, deptname String, projectcode int, projectjoindate Timestamp, projectenddate Timestamp,attendance int,utilization int,salary int) STORED BY 'org.apache.carbondata.format' tblproperties('sort_columns'='workgroupcategory, empname')")
      sql(s"""LOAD DATA local inpath '$resourcesPath/data.csv' INTO TABLE sorttable4_offheap_inmemory OPTIONS('DELIMITER'= ',', 'QUOTECHAR'= '\"')""")
      checkAnswer(sql("select workgroupcategory, empname from sorttable4_offheap_inmemory"),
        sql("select workgroupcategory, empname from origintable1 order by workgroupcategory"))
    } finally {
      defaultLoadingProperties
    }
  }

  test("create table with multi-sort_columns and data loading with heap") {
    try {
      setLoadingProperties("false", "false", "false")
      sql(
        "CREATE TABLE sorttable4_heap_safe (empno int, empname String, designation String, doj Timestamp, workgroupcategory int, workgroupcategoryname String, deptno int, deptname String, projectcode int, projectjoindate Timestamp, projectenddate Timestamp,attendance int,utilization int,salary int) STORED BY 'org.apache.carbondata.format' tblproperties('sort_columns'='workgroupcategory, empname')")
      sql(s"""LOAD DATA local inpath '$resourcesPath/data.csv' INTO TABLE sorttable4_heap_safe OPTIONS('DELIMITER'= ',', 'QUOTECHAR'= '\"')""")
      checkAnswer(sql("select workgroupcategory, empname from sorttable4_heap_safe"),
        sql("select workgroupcategory, empname from origintable1 order by workgroupcategory"))
    } finally {
      defaultLoadingProperties
    }
  }

  test("create table with multi-sort_columns and data loading with heap and unsafe sort") {
    try {
      setLoadingProperties("false", "true", "false")
      sql(
        "CREATE TABLE sorttable4_heap_unsafe (empno int, empname String, designation String, doj Timestamp, workgroupcategory int, workgroupcategoryname String, deptno int, deptname String, projectcode int, projectjoindate Timestamp, projectenddate Timestamp,attendance int,utilization int,salary int) STORED BY 'org.apache.carbondata.format' tblproperties('sort_columns'='workgroupcategory, empname')")
      sql(s"""LOAD DATA local inpath '$resourcesPath/data.csv' INTO TABLE sorttable4_heap_unsafe OPTIONS('DELIMITER'= ',', 'QUOTECHAR'= '\"')""")
      checkAnswer(sql("select workgroupcategory, empname from sorttable4_heap_unsafe"),
        sql("select workgroupcategory, empname from origintable1 order by workgroupcategory"))
    } finally {
      defaultLoadingProperties
    }
  }

  test("create table with multi-sort_columns and data loading with heap and inmemory sort") {
    try {
      setLoadingProperties("false", "false", "true")
      sql(
        "CREATE TABLE sorttable4_heap_inmemory (empno int, empname String, designation String, doj Timestamp, workgroupcategory int, workgroupcategoryname String, deptno int, deptname String, projectcode int, projectjoindate Timestamp, projectenddate Timestamp,attendance int,utilization int,salary int) STORED BY 'org.apache.carbondata.format' tblproperties('sort_columns'='workgroupcategory, empname')")
      sql(s"""LOAD DATA local inpath '$resourcesPath/data.csv' INTO TABLE sorttable4_heap_inmemory OPTIONS('DELIMITER'= ',', 'QUOTECHAR'= '\"')""")
      checkAnswer(sql("select workgroupcategory, empname from sorttable4_heap_inmemory"),
        sql("select workgroupcategory, empname from origintable1 order by workgroupcategory"))
    } finally {
      defaultLoadingProperties
    }
  }

  test("compaction on sort_columns table") {
    sql("CREATE TABLE origintable2 (empno int, empname String, designation String, doj Timestamp, workgroupcategory int, workgroupcategoryname String, deptno int, deptname String, projectcode int, projectjoindate Timestamp, projectenddate Timestamp,attendance int,utilization int,salary int) STORED BY 'org.apache.carbondata.format'")
    sql(s"""LOAD DATA local inpath '$resourcesPath/data.csv' INTO TABLE origintable2 OPTIONS('DELIMITER'= ',', 'QUOTECHAR'= '\"')""")
    sql(s"""LOAD DATA local inpath '$resourcesPath/data.csv' INTO TABLE origintable2 OPTIONS('DELIMITER'= ',', 'QUOTECHAR'= '\"')""")
    sql(s"""LOAD DATA local inpath '$resourcesPath/data.csv' INTO TABLE origintable2 OPTIONS('DELIMITER'= ',', 'QUOTECHAR'= '\"')""")
    sql(s"""LOAD DATA local inpath '$resourcesPath/data.csv' INTO TABLE origintable2 OPTIONS('DELIMITER'= ',', 'QUOTECHAR'= '\"')""")
    sql("alter table origintable2 compact 'minor'")

    sql("CREATE TABLE sorttable5 (empno int, empname String, designation String, doj Timestamp, workgroupcategory int, workgroupcategoryname String, deptno int, deptname String, projectcode int, projectjoindate Timestamp, projectenddate Timestamp,attendance int,utilization int,salary int) STORED BY 'org.apache.carbondata.format' tblproperties('sort_columns'='empno')")
    sql(s"""LOAD DATA local inpath '$resourcesPath/data.csv' INTO TABLE sorttable5 OPTIONS('DELIMITER'= ',', 'QUOTECHAR'= '\"')""")
    sql(s"""LOAD DATA local inpath '$resourcesPath/data.csv' INTO TABLE sorttable5 OPTIONS('DELIMITER'= ',', 'QUOTECHAR'= '\"')""")
    sql(s"""LOAD DATA local inpath '$resourcesPath/data.csv' INTO TABLE sorttable5 OPTIONS('DELIMITER'= ',', 'QUOTECHAR'= '\"')""")
    sql(s"""LOAD DATA local inpath '$resourcesPath/data.csv' INTO TABLE sorttable5 OPTIONS('DELIMITER'= ',', 'QUOTECHAR'= '\"')""")
    sql("alter table sorttable5 compact 'minor'")

    checkAnswer(sql("select empno from sorttable5"), sql("select empno from origintable2 order by empno"))
  }

  test("filter on sort_columns include no-dictionary, direct-dictionary and dictioanry") {
    sql("CREATE TABLE sorttable6 (empno int, empname String, designation String, doj Timestamp, workgroupcategory int, workgroupcategoryname String, deptno int, deptname String, projectcode int, projectjoindate Timestamp, projectenddate Timestamp,attendance int,utilization int,salary int) STORED BY 'org.apache.carbondata.format' tblproperties('sort_columns'='workgroupcategory, doj, empname', 'dictionary_include'='empname')")
    sql(s"""LOAD DATA local inpath '$resourcesPath/data.csv' INTO TABLE sorttable6 OPTIONS('DELIMITER'= ',', 'QUOTECHAR'= '\"')""")
    // no dictionary
    checkAnswer(sql("select * from sorttable6 where workgroupcategory = 1"), sql("select * from origintable1 where workgroupcategory = 1 order by doj"))
    // direct dictionary
    checkAnswer(sql("select * from sorttable6 where doj = '2007-01-17 00:00:00'"), sql("select * from origintable1 where doj = '2007-01-17 00:00:00'"))
    // dictionary
    checkAnswer(sql("select * from sorttable6 where empname = 'madhan'"), sql("select * from origintable1 where empname = 'madhan'"))
  }

  test("unsorted table creation, query data loading with heap and safe sort config") {
    try {
      setLoadingProperties("false", "false", "false")
      sql("CREATE TABLE unsortedtable_heap_safe (empno int, empname String, designation String, doj Timestamp, workgroupcategory int, workgroupcategoryname String, deptno int, deptname String, projectcode int, projectjoindate Timestamp, projectenddate Timestamp,attendance int,utilization int,salary int) STORED BY 'org.apache.carbondata.format' tblproperties('sort_columns'='')")
      sql(s"""LOAD DATA local inpath '$resourcesPath/data.csv' INTO TABLE unsortedtable_heap_safe OPTIONS('DELIMITER'= ',', 'QUOTECHAR'= '\"')""")
      checkAnswer(sql("select * from unsortedtable_heap_safe where empno = 11"), sql("select * from origintable1 where empno = 11"))
      checkAnswer(sql("select * from unsortedtable_heap_safe order by empno"), sql("select * from origintable1 order by empno"))
    } finally {
      defaultLoadingProperties
    }
  }

  test("unsorted table creation, query and data loading with heap and unsafe sort config") {
    try {
      setLoadingProperties("false", "true", "false")
      sql("CREATE TABLE unsortedtable_heap_unsafe (empno int, empname String, designation String, doj Timestamp, workgroupcategory int, workgroupcategoryname String, deptno int, deptname String, projectcode int, projectjoindate Timestamp, projectenddate Timestamp,attendance int,utilization int,salary int) STORED BY 'org.apache.carbondata.format' tblproperties('sort_columns'='')")
      sql(s"""LOAD DATA local inpath '$resourcesPath/data.csv' INTO TABLE unsortedtable_heap_unsafe OPTIONS('DELIMITER'= ',', 'QUOTECHAR'= '\"')""")
      checkAnswer(sql("select * from unsortedtable_heap_unsafe where empno = 11"), sql("select * from origintable1 where empno = 11"))
      checkAnswer(sql("select * from unsortedtable_heap_unsafe order by empno"), sql("select * from origintable1 order by empno"))
    } finally {
      defaultLoadingProperties
    }
  }

  test("unsorted table creation, query and loading with heap and inmemory sort config") {
    try {
      setLoadingProperties("false", "false", "true")
      sql("CREATE TABLE unsortedtable_heap_inmemory (empno int, empname String, designation String, doj Timestamp, workgroupcategory int, workgroupcategoryname String, deptno int, deptname String, projectcode int, projectjoindate Timestamp, projectenddate Timestamp,attendance int,utilization int,salary int) STORED BY 'org.apache.carbondata.format' tblproperties('sort_columns'='')")
      sql(s"""LOAD DATA local inpath '$resourcesPath/data.csv' INTO TABLE unsortedtable_heap_inmemory OPTIONS('DELIMITER'= ',', 'QUOTECHAR'= '\"')""")
      checkAnswer(sql("select * from unsortedtable_heap_inmemory where empno = 11"), sql("select * from origintable1 where empno = 11"))
      checkAnswer(sql("select * from unsortedtable_heap_inmemory order by empno"), sql("select * from origintable1 order by empno"))
    } finally {
      defaultLoadingProperties
    }
  }

  test("unsorted table creation, query and data loading with offheap and safe sort config") {
    try {
      setLoadingProperties("true", "false", "false")
      sql("CREATE TABLE unsortedtable_offheap_safe (empno int, empname String, designation String, doj Timestamp, workgroupcategory int, workgroupcategoryname String, deptno int, deptname String, projectcode int, projectjoindate Timestamp, projectenddate Timestamp,attendance int,utilization int,salary int) STORED BY 'org.apache.carbondata.format' tblproperties('sort_columns'='')")
      sql(s"""LOAD DATA local inpath '$resourcesPath/data.csv' INTO TABLE unsortedtable_offheap_safe OPTIONS('DELIMITER'= ',', 'QUOTECHAR'= '\"')""")
      checkAnswer(sql("select * from unsortedtable_offheap_safe where empno = 11"), sql("select * from origintable1 where empno = 11"))
      checkAnswer(sql("select * from unsortedtable_offheap_safe order by empno"), sql("select * from origintable1 order by empno"))
    } finally {
      defaultLoadingProperties
    }
  }

  test("unsorted table creation, query and data loading with offheap and unsafe sort config") {
    try {
      setLoadingProperties("true", "true", "false")
      sql("CREATE TABLE unsortedtable_offheap_unsafe (empno int, empname String, designation String, doj Timestamp, workgroupcategory int, workgroupcategoryname String, deptno int, deptname String, projectcode int, projectjoindate Timestamp, projectenddate Timestamp,attendance int,utilization int,salary int) STORED BY 'org.apache.carbondata.format' tblproperties('sort_columns'='')")
      sql(s"""LOAD DATA local inpath '$resourcesPath/data.csv' INTO TABLE unsortedtable_offheap_unsafe OPTIONS('DELIMITER'= ',', 'QUOTECHAR'= '\"')""")
      checkAnswer(sql("select * from unsortedtable_offheap_unsafe where empno = 11"), sql("select * from origintable1 where empno = 11"))
      checkAnswer(sql("select * from unsortedtable_offheap_unsafe order by empno"), sql("select * from origintable1 order by empno"))
    } finally {
      defaultLoadingProperties
    }
  }

  test("unsorted table creation, query and data loading with offheap and inmemory sort config") {
    try {
      setLoadingProperties("true", "false", "true")
      sql("CREATE TABLE unsortedtable_offheap_inmemory (empno int, empname String, designation String, doj Timestamp, workgroupcategory int, workgroupcategoryname String, deptno int, deptname String, projectcode int, projectjoindate Timestamp, projectenddate Timestamp,attendance int,utilization int,salary int) STORED BY 'org.apache.carbondata.format' tblproperties('sort_columns'='')")
      sql(s"""LOAD DATA local inpath '$resourcesPath/data.csv' INTO TABLE unsortedtable_offheap_inmemory OPTIONS('DELIMITER'= ',', 'QUOTECHAR'= '\"')""")
      checkAnswer(sql("select * from unsortedtable_offheap_inmemory where empno = 11"), sql("select * from origintable1 where empno = 11"))
      checkAnswer(sql("select * from unsortedtable_offheap_inmemory where empno < 15 order by empno"), sql("select * from origintable1 where empno < 15 order by empno"))
      checkAnswer(sql("select * from unsortedtable_offheap_inmemory where empno <= 15 order by empno"), sql("select * from origintable1 where empno <= 15 order by empno"))
      checkAnswer(sql("select * from unsortedtable_offheap_inmemory where empno > 15 order by empno"), sql("select * from origintable1 where empno > 15 order by empno"))
      checkAnswer(sql("select * from unsortedtable_offheap_inmemory where empno >= 15 order by empno"), sql("select * from origintable1 where empno >= 15 order by empno"))
      checkAnswer(sql("select * from unsortedtable_offheap_inmemory where empno <> 15 order by empno"), sql("select * from origintable1 where empno <> 15 order by empno"))
      checkAnswer(sql("select * from unsortedtable_offheap_inmemory where empno in (15, 16, 17) order by empno"), sql("select * from origintable1 where empno in (15, 16, 17) order by empno"))
      checkAnswer(sql("select * from unsortedtable_offheap_inmemory where empno is null"), sql("select * from origintable1 where empno is null order by empno"))
      checkAnswer(sql("select * from unsortedtable_offheap_inmemory where empno is not null"), sql("select * from origintable1 where empno is not null order by empno"))
      checkAnswer(sql("select * from unsortedtable_offheap_inmemory order by empno"), sql("select * from origintable1 order by empno"))
    } finally {
      defaultLoadingProperties
    }
  }

  test("create table with invalid values for numeric data type columns specified as sort_columns") {
    // load hive data
    sql("CREATE TABLE test_sort_col_hive (id INT, name STRING, age INT) row format delimited fields terminated by ','")
    sql(s"LOAD DATA local inpath '$resourcesPath/numeric_column_invalid_values.csv' INTO TABLE test_sort_col_hive")
    // load carbon data
    sql("CREATE TABLE test_sort_col (id INT, name STRING, age INT) STORED BY 'org.apache.carbondata.format' TBLPROPERTIES('SORT_COLUMNS'='id,age')")
    sql(s"LOAD DATA local inpath '$resourcesPath/numeric_column_invalid_values.csv' INTO TABLE test_sort_col OPTIONS('FILEHEADER'='id,name,age')")
    // compare hive and carbon data
    checkAnswer(sql("select * from test_sort_col_hive"), sql("select * from test_sort_col"))
  }

  test("describe formatted for sort_columns") {
    sql("CREATE TABLE sorttableDesc (empno int, empname String, designation String, doj Timestamp, workgroupcategory int, workgroupcategoryname String, deptno int, deptname String, projectcode int, projectjoindate Timestamp, projectenddate Timestamp,attendance int,utilization int,salary int) STORED BY 'org.apache.carbondata.format' tblproperties('sort_columns'='empno,empname')")
    checkExistence(sql("describe formatted sorttableDesc"),true,"SORT_COLUMNS")
    checkExistence(sql("describe formatted sorttableDesc"),true,"empno,empname")
  }

  test("duplicate columns in sort_columns") {
    val exceptionCaught = intercept[MalformedCarbonCommandException]{
      sql("CREATE TABLE sorttable1 (empno int, empname String, designation String, doj Timestamp, workgroupcategory int, workgroupcategoryname String, deptno int, deptname String, projectcode int, projectjoindate Timestamp, projectenddate Timestamp,attendance int,utilization int,salary int) STORED BY 'org.apache.carbondata.format' tblproperties('sort_columns'='empno,empname,empno')")
    }
  assert(exceptionCaught.getMessage.equals("SORT_COLUMNS Either having duplicate columns : empno or it contains illegal argumnet."))
  }

  override def afterAll = {
    dropTable
  }

  def dropTable = {
    sql("drop table if exists origintable1")
    sql("drop table if exists origintable2")
    sql("drop table if exists sorttable1")
    sql("drop table if exists sorttableDesc")
    sql("drop table if exists sorttable1a")
    sql("drop table if exists sorttable2")
    sql("drop table if exists sorttable3")
    sql("drop table if exists sorttable4_offheap_safe")
    sql("drop table if exists sorttable4_offheap_unsafe")
    sql("drop table if exists sorttable4_offheap_inmemory")
    sql("drop table if exists sorttable4_heap_safe")
    sql("drop table if exists sorttable4_heap_unsafe")
    sql("drop table if exists sorttable4_heap_inmemory")
    sql("drop table if exists sorttable5")
    sql("drop table if exists sorttable6")
    sql("drop table if exists unsortedtable_offheap_safe")
    sql("drop table if exists unsortedtable_offheap_unsafe")
    sql("drop table if exists unsortedtable_offheap_inmemory")
    sql("drop table if exists unsortedtable_heap_safe")
    sql("drop table if exists unsortedtable_heap_unsafe")
    sql("drop table if exists unsortedtable_heap_inmemory")
    sql("drop table if exists test_sort_col")
    sql("drop table if exists test_sort_col_hive")
  }

  def setLoadingProperties(offheap: String, unsafe: String, useBatch: String): Unit = {
    CarbonProperties.getInstance().addProperty(CarbonCommonConstants.ENABLE_OFFHEAP_SORT, offheap)
    if (useBatch.equalsIgnoreCase("true")) {
      CarbonProperties.getInstance().addProperty(CarbonCommonConstants.ENABLE_UNSAFE_SORT, "BATCH_SORT")
    }
    CarbonProperties.getInstance().addProperty(CarbonCommonConstants.LOAD_SORT_SCOPE, useBatch)
  }

  def defaultLoadingProperties = {
    CarbonProperties.getInstance().addProperty(CarbonCommonConstants.ENABLE_OFFHEAP_SORT, CarbonCommonConstants.ENABLE_OFFHEAP_SORT_DEFAULT)
    CarbonProperties.getInstance().addProperty(CarbonCommonConstants.ENABLE_UNSAFE_SORT, CarbonCommonConstants.ENABLE_UNSAFE_SORT_DEFAULT)
    CarbonProperties.getInstance().addProperty(CarbonCommonConstants.LOAD_SORT_SCOPE, CarbonCommonConstants.LOAD_SORT_SCOPE_DEFAULT)
  }
}


text:
/*
 * Main application entry point
 */
/* @if NODE_ENV='test' **
var allTestFiles = [];
var TEST_REGEXP = /(spec|test)\.js$/i;

// Get a list of all the test files to include
Object.keys(window.__karma__.files).forEach(function(file) {
  if (TEST_REGEXP.test(file)) {
    // Normalize paths to RequireJS module names.
    // If you require sub-dependencies of test files to be loaded as-is (requiring file extension)
    // then do not normalize the paths
    var normalizedTestModule = file.replace(/^\/base\/content\/js\/|\.js$/g, '');
    allTestFiles.push(normalizedTestModule);
  }
});
/* @endif */

require.config({
    /* @if NODE_ENV='test' **
    baseUrl: '/base/content/js',
    deps: allTestFiles,
    callback: window.__karma__.start,
    /* @endif */
    shim: {
        'bootstrap/affix':      { deps: ['jquery'], exports: '$.fn.affix' },
        'bootstrap/alert':      { deps: ['jquery'], exports: '$.fn.alert' },
        'bootstrap/button':     { deps: ['jquery'], exports: '$.fn.button' },
        'bootstrap/carousel':   { deps: ['jquery'], exports: '$.fn.carousel' },
        'bootstrap/collapse':   { deps: ['jquery'], exports: '$.fn.collapse' },
        'bootstrap/dropdown':   { deps: ['jquery'], exports: '$.fn.dropdown' },
        'bootstrap/modal':      { deps: ['jquery'], exports: '$.fn.modal' },
        'bootstrap/popover':    { deps: ['jquery', 'bootstrap/tooltip'], exports: '$.fn.popover' },
        'bootstrap/scrollspy':  { deps: ['jquery'], exports: '$.fn.scrollspy' },
        'bootstrap/tab':        { deps: ['jquery'], exports: '$.fn.tab'        },
        'bootstrap/tooltip':    { deps: ['jquery'], exports: '$.fn.tooltip' },
        'bootstrap/transition': { deps: ['jquery'], exports: '$.fn.transition' },
        'angular' : {exports: 'angular'},
        /* @if NODE_ENV='test' **
        'angular-mocks' : { deps: ['angular'] },
        /* @endif */
        'angular-route' : { deps: ['angular'] }
    },
    paths: {
        /* path to folder where individual bootstrap files have been saved. (affix.js, alert.js, etc) */
        'bootstrap': 'libs/bootstrap',
        'jquery': 'libs/jquery.min',
        'angular-route': 'libs/angular-route.min',
        'angular': 'libs/angular.min',
        /* @if NODE_ENV='test' **
        'angular-mocks': 'libs/angular-mocks',
        /* @endif */
        lib: 'libs',
        app: 'app'
    },
});

requirejs(['app/main'], function(app){
});


text:
#ifndef STK_SINGWAVE_H
#define STK_SINGWAVE_H

#include "FileLoop.h"
#include "Modulate.h"
#include "Envelope.h"

namespace stk {

/***************************************************/
/*! \class SingWave
    \brief STK "singing" looped soundfile class.

    This class loops a specified soundfile and modulates it both
    periodically and randomly to produce a pitched musical sound, like
    a simple voice or violin.  In general, it is not be used alone
    because of "munchkinification" effects from pitch shifting.
    Within STK, it is used as an excitation source for other
    instruments.

    by Perry R. Cook and Gary P. Scavone, 1995--2014.
*/
/***************************************************/

class SingWave : public Generator
{
 public:
  //! Class constructor taking filename argument.
  /*!
    An StkError will be thrown if the file is not found, its format
    is unknown, or a read error occurs.  If the soundfile has no
    header, the second argument should be \e true and the file data
    will be assumed to consist of 16-bit signed integers in big-endian
    byte order at a sample rate of 22050 Hz.
  */
  SingWave( std::string fileName, bool raw = false );

  //! Class destructor.
  ~SingWave( void );

  //! Reset file to beginning.
  void reset( void ) { wave_.reset(); lastFrame_[0] = 0.0; };

  //! Normalize the file to a maximum of +-1.0.
  void normalize( void ) { wave_.normalize(); };

  //! Normalize the file to a maximum of \e +- peak.
  void normalize( StkFloat peak ) { wave_.normalize( peak ); };

  //! Set looping parameters for a particular frequency.
  void setFrequency( StkFloat frequency );

  //! Set the vibrato frequency in Hz.
  void setVibratoRate( StkFloat rate ) { modulator_.setVibratoRate( rate ); };

  //! Set the vibrato gain.
  void setVibratoGain( StkFloat gain ) { modulator_.setVibratoGain( gain ); };

  //! Set the random-ness amount.
  void setRandomGain( StkFloat gain ) { modulator_.setRandomGain( gain ); };

  //! Set the sweep rate.
  void setSweepRate( StkFloat rate ) { sweepRate_ = rate; };

  //! Set the gain rate.
  void setGainRate( StkFloat rate ) { envelope_.setRate( rate ); };

  //! Set the gain target value.
  void setGainTarget( StkFloat target ) { envelope_.setTarget( target ); };

  //! Start a note.
  void noteOn( void ) { envelope_.keyOn(); };

  //! Stop a note.
  void noteOff( void ) { envelope_.keyOff(); };

  //! Return the last computed output value.
  StkFloat lastOut( void ) const { return lastFrame_[0]; };

  //! Compute and return one output sample.
  StkFloat tick( void );

  //! Fill a channel of the StkFrames object with computed outputs.
  /*!
    The \c channel argument must be less than the number of
    channels in the StkFrames argument (the first channel is specified
    by 0).  However, range checking is only performed if _STK_DEBUG_
    is defined during compilation, in which case an out-of-range value
    will trigger an StkError exception.
  */
  StkFrames& tick( StkFrames& frames, unsigned int channel = 0 );

 protected:

  FileLoop wave_;
  Modulate modulator_;
  Envelope envelope_;
  Envelope pitchEnvelope_;
  StkFloat rate_;
  StkFloat sweepRate_;

};

inline StkFloat SingWave :: tick( void )
{
  // Set the wave rate.
  StkFloat newRate = pitchEnvelope_.tick();
  newRate += newRate * modulator_.tick();
  wave_.setRate( newRate );

  lastFrame_[0] = wave_.tick();
  lastFrame_[0] *= envelope_.tick();

  return lastFrame_[0];
}

inline StkFrames& SingWave :: tick( StkFrames& frames, unsigned int channel )
{
#if defined(_STK_DEBUG_)
  if ( channel >= frames.channels() ) {
    oStream_ << "SingWave::tick(): channel and StkFrames arguments are incompatible!";
    handleError( StkError::FUNCTION_ARGUMENT );
  }
#endif

  StkFloat *samples = &frames[channel];
  unsigned int hop = frames.channels();
  for ( unsigned int i=0; i<frames.frames(); i++, samples += hop )
    *samples = SingWave::tick();

  return frames;
}

} // stk namespace

#endif


text:
<?php
namespace qtil {
    trait Chain {
        use Factory;

        /**
         * Creates link object with built-in factory
         * @param string $name
         * @param array $arguments
         * @return mixed
         */
        public function link($name, array $arguments) {
            $suffix = defined('static::LINK_SUFFIX')
                    ? static::LINK_SUFFIX
                    : '';

            $qualifiedName = Chain\Registry::getQualifiedName($this,$name,$suffix);

            if(empty($qualifiedName)) {
                throw new \BadMethodCallException(get_class($this).'->'.$name);
            }

            $link = $this->make($qualifiedName,$arguments);

            if(isset($link)) {
                $linkProperty = Chain\Registry::getLinkProperty($this);
                $this->{$linkProperty}[] = $link;

                return $link;
            } else {
                return null;
            }
        }

        /**
         * Check if chain link is possible given name
         * @param string $name
         * @return boolean
         */
        public function canLink($name) {
            $suffix = defined('static::LINK_SUFFIX')
                    ? static::LINK_SUFFIX
                    : '';

            $qualifiedName = Chain\Registry::getQualifiedName($this,$name,$suffix);

            if(class_exists($qualifiedName)) {
                return true;
            }

            return false;
        }

        /**
         * Checks if link with given name already exists in chain
         * @param string $name
         * @return boolean
         */
        public function hasLink($name) {
            $suffix = defined('static::LINK_SUFFIX')
                    ? static::LINK_SUFFIX
                    : '';

            $qualifiedName = Chain\Registry::getQualifiedName($this,$name,$suffix);

            $linkProperty = Chain\Registry::getLinkProperty($this);
            $links = $this->{$linkProperty};
            foreach($links as $link) {
                $linkClass = get_class($link);
                if($linkClass === $qualifiedName) {
                    return true;
                }
            }

            return false;
        }

        /**
         * Retrieves all links with given name
         * An array of names may be provided
         * @param type $names
         * @return type
         */
        public function getLink($names) {
            if(!ArrayUtil::isIterable($names)) {
                $names = [$names];
            }

            $linkProperty = Chain\Registry::getLinkProperty($this);
            $links = $this->{$linkProperty};

            $returnLinks = [];
            foreach($names as $name) {
                $suffix = defined('static::LINK_SUFFIX')
                    ? static::LINK_SUFFIX
                    : '';

                $qualifiedName = Chain\Registry::getQualifiedName($this,$name,$suffix);
                foreach($links as $link) {
                    if($link instanceof $qualifiedName) {
                        $returnLinks[] = $link;
                    }
                }
            }

            return $returnLinks;
        }

        /**
         * Helper method to add registry namespace definition
         * @param string $namespace
         */
        public function registerNamespace($namespace) {
            Chain\Registry::addNamespace($this, $namespace);
            return $this;
        }

        /**
         * Helper method to remove registry namespace definition
         * @param string $namespace
         */
        public function unregisterNamespace($namespace) {
            Chain\Registry::removeNamespace($this, $namespace);
            return $this;
        }

        /**
         * Retrieves all links in chain
         * @return array
         */
        public function getLinks() {
            $linkProperty = Chain\Registry::getLinkProperty($this);
            return $this->{$linkProperty};
        }

        /**
         * Call magic for chain link creation
         * @param string $name
         * @param array $arguments
         * @return self
         */
        public function __call($name, array $arguments) {
            $this->link($name, $arguments);

            return $this;
        }
    }
}


text:
using System;

namespace Obelisk.Agi.Commands
{
    /// <summary>
    /// Represents a command for setting a variable by name.
    /// </summary>
    public class SetVariableCommand : ObeliskCommand
    {
        /// <summary>
        /// Gets or sets the name of the variable.
        /// </summary>
        public string Name
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the value of the variable.
        /// </summary>
        public string Value
        {
            get;
            set;
        }

        /// <summary>
        /// Initialises a new instance of the SetVariableCommand class.
        /// </summary>
        public SetVariableCommand(string name, string value)
        {
            Name = name;
            Value = value;
        }

        /// <summary>
        /// Compiles the command.
        /// </summary>
        public override string Compile()
        {
            return String.Format("SET VARIABLE {0} {1}", EscapeAndQuote(Name), EscapeAndQuote(Value));
        }
    }
}


text:
package org.lamport.tla.toolbox;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import org.lamport.tla.toolbox.tool.tlc.ui.test.ModelCheckerTest;
import org.lamport.tla.toolbox.ui.handler.CloneModelTest;
import org.lamport.tla.toolbox.ui.handler.RenameSpecHandlerTest;

@RunWith(Suite.class)
@SuiteClasses({
    ModelCheckerTest.class,
    CloneModelTest.class,
    RenameSpecHandlerTest.class
})

public class SmokeTests {}


text:
<?php
require('index.php');


text:
using Rtps.Structure.Types;
namespace rtps.messages.elements
{
    public class KeyHashPrefix : GuidPrefix
    {
        public byte[] value; //[12];

        public KeyHashPrefix(byte[] value)
            : base(value)
        {
            this.value = value;
        }

    }
}


text:
(function() {
  'use strict';

  angular.module('app.resources')
    .factory('AwsData', AwsDataFactory);

  /** @ngInject */
  function AwsDataFactory($resource) {
    var base = '/api/v1/aws/providers/:id/:action';
    var AwsData = $resource(base, {action: '@action', id: '@id'});

    AwsData.ec2Flavors = ec2Flavors;
    AwsData.rdsEngines = rdsEngines;
    AwsData.rdsVersions = rdsVersions;
    AwsData.rdsFlavors = rdsFlavors;
    AwsData.ec2Images = ec2Images;
    AwsData.vpcs = vpcs;
    AwsData.subnets = subnets;
    AwsData.zones = zones;
    AwsData.keyNames = keyNames;
    AwsData.securityGroups = securityGroups;
    AwsData.deprovision = deprovision;

    return AwsData;

    function ec2Flavors(id) {
      return AwsData.query({id: id, action: 'ec2_flavors'}).$promise;
    }

    function rdsEngines(id) {
      return AwsData.query({id: id, action: 'rds_engines'}).$promise;
    }

    function rdsVersions(id, engine) {
      return AwsData.query({id: id, action: 'rds_versions', engine: engine}).$promise;
    }

    function rdsFlavors(id, engine, version) {
      return AwsData.query({id: id, action: 'rds_flavors', engine: engine, version: version}).$promise;
    }

    function ec2Images(id) {
      return AwsData.query({id: id, action: 'ec2_images'}).$promise;
    }

    function vpcs(id) {
      return AwsData.query({id: id, action: 'vpcs'}).$promise;
    }

    function subnets(id, vpc_id) {
      return AwsData.query({id: id, action: 'subnets', vpc_id: vpc_id}).$promise;
    }

    function zones(id) {
      return AwsData.query({id: id, action: 'availability_zones'}).$promise;
    }

    function keyNames(id) {
      return AwsData.query({id: id, action: 'key_names'}).$promise;
    }

    function securityGroups(id) {
      return AwsData.query({id: id, action: 'security_groups'}).$promise;
    }

    function deprovision(id, service_id) {
      return AwsData.query({id: id, action: 'deprovision', service_id: service_id}).$promise;
    }
  }
})();


text:
import numpy as np
import csv

def safeChange(ROOT, R, vis, eps, PotentialUpdated, recomputefractionsafe, errorplotinfo, errorworst, errorbest):
    C1Base = R.flatten()
    with open("%s/C1Base.txt" % ROOT, 'wb') as csvfile:
        writer = csv.writer(csvfile)
        for val in C1Base:
            writer.writerow([val])

    with open("%s/C1vis.txt" % ROOT, 'wb') as csvfile:
        writer = csv.writer(csvfile)
        for val in vis:
            writer.writerow([val])

    #safe eps
    with open("%s/C1eps.txt" % ROOT, 'wb') as csvfile:
        writer = csv.writer(csvfile)
        for val in eps:
            writer.writerow([val])

    #safe PotentialUpdated
    with open("%s/C1PotentialUpdated.txt" % ROOT, 'wb') as csvfile:
        writer = csv.writer(csvfile)
        for val in [PotentialUpdated]:
            writer.writerow([val])

    #safe
    with open("%s/C1recomputefractionsafe.txt" % ROOT, 'wb') as csvfile:
        writer = csv.writer(csvfile)
        for val in recomputefractionsafe:
            writer.writerow([val])

    #safe
    with open("%s/C1errorplotinfo.txt" % ROOT, 'wb') as csvfile:
        writer = csv.writer(csvfile)
        for val in errorplotinfo:
            writer.writerow([val])

    #safe
    with open("%s/C1errorworst.txt" % ROOT, 'wb') as csvfile:
        writer = csv.writer(csvfile)
        for val in errorworst:
            writer.writerow([val])

    #safe
    with open("%s/C1errorbest.txt" % ROOT, 'wb') as csvfile:
        writer = csv.writer(csvfile)
        for val in errorbest:
            writer.writerow([val])

def safeVanish(ROOT, R, vis, eps, PotentialUpdated, recomputefractionsafe, errorplotinfo, errorworst, errorbest):
    VBase = R.flatten()
    with open("%s/VBase.txt" % ROOT, 'wb') as csvfile:
        writer = csv.writer(csvfile)
        for val in VBase:
            writer.writerow([val])

    #safe vis
    with open("%s/Vvis.txt" % ROOT, 'wb') as csvfile:
        writer = csv.writer(csvfile)
        for val in vis:
            writer.writerow([val])

    #safe eps
    with open("%s/Veps.txt" % ROOT, 'wb') as csvfile:
        writer = csv.writer(csvfile)
        for val in eps:
            writer.writerow([val])

    #safe PotentialUpdated
    with open("%s/VPotentialUpdated.txt" % ROOT, 'wb') as csvfile:
        writer = csv.writer(csvfile)
        for val in [PotentialUpdated]:
            writer.writerow([val])

    #safe
    with open("%s/Vrecomputefractionsafe.txt" % ROOT, 'wb') as csvfile:
        writer = csv.writer(csvfile)
        for val in recomputefractionsafe:
            writer.writerow([val])

    #safe
    with open("%s/Verrorplotinfo.txt" % ROOT, 'wb') as csvfile:
        writer = csv.writer(csvfile)
        for val in errorplotinfo:
            writer.writerow([val])

    #safe
    with open("%s/Verrorworst.txt" % ROOT, 'wb') as csvfile:
        writer = csv.writer(csvfile)
        for val in errorworst:
            writer.writerow([val])

    #safe
    with open("%s/Verrorbest.txt" % ROOT, 'wb') as csvfile:
        writer = csv.writer(csvfile)
        for val in errorbest:
            writer.writerow([val])

def safeShift(ROOT, R, vis, eps, PotentialUpdated, recomputefractionsafe, errorplotinfo, errorworst, errorbest):
    M1Base = R.flatten()
    with open("%s/M1Base.txt" % ROOT, 'wb') as csvfile:
        writer = csv.writer(csvfile)
        for val in M1Base:
            writer.writerow([val])

    with open("%s/M1vis.txt" % ROOT, 'wb') as csvfile:
        writer = csv.writer(csvfile)
        for val in vis:
            writer.writerow([val])

    #safe eps
    with open("%s/M1eps.txt" % ROOT, 'wb') as csvfile:
        writer = csv.writer(csvfile)
        for val in eps:
            writer.writerow([val])

    #safe PotentialUpdated
    with open("%s/M1PotentialUpdated.txt" % ROOT, 'wb') as csvfile:
        writer = csv.writer(csvfile)
        for val in [PotentialUpdated]:
            writer.writerow([val])

    #safe
    with open("%s/M1recomputefractionsafe.txt" % ROOT, 'wb') as csvfile:
        writer = csv.writer(csvfile)
        for val in recomputefractionsafe:
            writer.writerow([val])

    #safe
    with open("%s/M1errorplotinfo.txt" % ROOT, 'wb') as csvfile:
        writer = csv.writer(csvfile)
        for val in errorplotinfo:
            writer.writerow([val])

    #safe
    with open("%s/M1errorworst.txt" % ROOT, 'wb') as csvfile:
        writer = csv.writer(csvfile)
        for val in errorworst:
            writer.writerow([val])

    #safe
    with open("%s/M1errorbest.txt" % ROOT, 'wb') as csvfile:
        writer = csv.writer(csvfile)
        for val in errorbest:
            writer.writerow([val])

def RegainChange(ROOT):
    C1Base = []
    f = open('%s/C1Base.txt' % ROOT, 'rb')
    reader = csv.reader(f)
    for row in reader:
        C1Base.append(float(row[0]))
    f.close()

    C1eps = []
    f = open('%s/C1eps.txt' % ROOT, 'rb')
    reader = csv.reader(f)
    for row in reader:
        C1eps.append(float(row[0]))
    f.close()

    C1errorbest = []
    f = open('%s/C1errorbest.txt' % ROOT, 'rb')
    reader = csv.reader(f)
    for row in reader:
        C1errorbest.append(float(row[0]))
    f.close()

    C1errorplotinfo = []
    f = open('%s/C1errorplotinfo.txt' % ROOT, 'rb')
    reader = csv.reader(f)
    for row in reader:
        C1errorplotinfo.append(float(row[0]))
    f.close()

    C1errorworst = []
    f = open('%s/C1errorworst.txt' % ROOT, 'rb')
    reader = csv.reader(f)
    for row in reader:
        C1errorworst.append(float(row[0]))
    f.close()

    C1vis = []
    f = open('%s/C1vis.txt' % ROOT, 'rb')
    reader = csv.reader(f)
    for row in reader:
        C1vis.append(float(row[0]))
    f.close()

    C1recomputefractionsafe = []
    f = open('%s/C1recomputefractionsafe.txt' % ROOT, 'rb')
    reader = csv.reader(f)
    for row in reader:
        C1recomputefractionsafe.append(float(row[0]))
    f.close()

    return C1Base, C1eps, C1errorbest, C1errorplotinfo, C1errorworst, C1vis, C1recomputefractionsafe

def RegainVanish(ROOT):
    VBase = []
    f = open('%s/VBase.txt' % ROOT, 'rb')
    reader = csv.reader(f)
    for row in reader:
        VBase.append(float(row[0]))
    f.close()

    Veps = []
    f = open('%s/Veps.txt' % ROOT, 'rb')
    reader = csv.reader(f)
    for row in reader:
        Veps.append(float(row[0]))
    f.close()

    Verrorbest = []
    f = open('%s/Verrorbest.txt' % ROOT, 'rb')
    reader = csv.reader(f)
    for row in reader:
        Verrorbest.append(float(row[0]))
    f.close()

    Verrorplotinfo = []
    f = open('%s/Verrorplotinfo.txt' % ROOT, 'rb')
    reader = csv.reader(f)
    for row in reader:
        Verrorplotinfo.append(float(row[0]))
    f.close()

    Verrorworst = []
    f = open('%s/Verrorworst.txt' % ROOT, 'rb')
    reader = csv.reader(f)
    for row in reader:
        Verrorworst.append(float(row[0]))
    f.close()

    Vvis = []
    f = open('%s/Vvis.txt' % ROOT, 'rb')
    reader = csv.reader(f)
    for rovw in reader:
        Vvis.append(float(row[0]))
    f.close()

    Vrecomputefractionsafe = []
    f = open('%s/Vrecomputefractionsafe.txt' % ROOT, 'rb')
    reader = csv.reader(f)
    for row in reader:
        Vrecomputefractionsafe.append(float(row[0]))
    f.close()

    return VBase, Veps, Verrorbest, Verrorplotinfo, Verrorworst, Vvis, Vrecomputefractionsafe

def RegainShift(ROOT):
    M1Base = []
    f = open('%s/M1Base.txt' % ROOT, 'rb')
    reader = csv.reader(f)
    for row in reader:
        M1Base.append(float(row[0]))
    f.close()

    M1eps = []
    f = open('%s/M1eps.txt' % ROOT, 'rb')
    reader = csv.reader(f)
    for row in reader:
        M1eps.append(float(row[0]))
    f.close()

    M1errorbest = []
    f = open('%s/M1errorbest.txt' % ROOT, 'rb')
    reader = csv.reader(f)
    for row in reader:
        M1errorbest.append(float(row[0]))
    f.close()

    M1errorplotinfo = []
    f = open('%s/M1errorplotinfo.txt' % ROOT, 'rb')
    reader = csv.reader(f)
    for row in reader:
        M1errorplotinfo.append(float(row[0]))
    f.close()

    M1errorworst = []
    f = open('%s/M1errorworst.txt' % ROOT, 'rb')
    reader = csv.reader(f)
    for row in reader:
        M1errorworst.append(float(row[0]))
    f.close()

    M1vis = []
    f = open('%s/M1vis.txt' % ROOT, 'rb')
    reader = csv.reader(f)
    for row in reader:
        M1vis.append(float(row[0]))
    f.close()

    M1recomputefractionsafe = []
    f = open('%s/M1recomputefractionsafe.txt' % ROOT, 'rb')
    reader = csv.reader(f)
    for row in reader:
        M1recomputefractionsafe.append(float(row[0]))
    f.close()

    return M1Base, M1eps, M1errorbest, M1errorplotinfo, M1errorworst, M1vis, M1recomputefractionsafe

def safer(ROOT, mum, a, plottingx, plottingy, plottingz, plotting2x, plotting2y, plotting2z, plotting3x, plotting3y, plotting3z, ems, Matrix):
    with open("%s/mum.txt" % ROOT, 'wb') as csvfile:
        writer = csv.writer(csvfile)
        for val in mum:
            writer.writerow([val])

    with open("%s/a.txt" % ROOT, 'wb') as csvfile:
        writer = csv.writer(csvfile)
        for val in a:
            writer.writerow([val])

    with open("%s/Matrix.txt" % ROOT, 'wb') as csvfile:
        writer = csv.writer(csvfile)
        for val in Matrix:
            writer.writerow([val])

    with open("%s/ems.txt" % ROOT, 'wb') as csvfile:
        writer = csv.writer(csvfile)
        for val in ems:
            writer.writerow([val])

    with open("%s/plottingx.txt" % ROOT, 'wb') as csvfile:
        writer = csv.writer(csvfile)
        for val in plottingx:
            writer.writerow([val])

    with open("%s/plottingy.txt" % ROOT, 'wb') as csvfile:
        writer = csv.writer(csvfile)
        for val in plottingy:
            writer.writerow([val])

    with open("%s/plottingz.txt" % ROOT, 'wb') as csvfile:
        writer = csv.writer(csvfile)
        for val in plottingz:
            writer.writerow([val])

    with open("%s/plotting2x.txt" % ROOT, 'wb') as csvfile:
        writer = csv.writer(csvfile)
        for val in plotting2x:
            writer.writerow([val])

    with open("%s/plotting2y.txt" % ROOT, 'wb') as csvfile:
        writer = csv.writer(csvfile)
        for val in plotting2y:
            writer.writerow([val])

    with open("%s/plotting2z.txt" % ROOT, 'wb') as csvfile:
        writer = csv.writer(csvfile)
        for val in plotting2z:
            writer.writerow([val])

    with open("%s/plotting3x.txt" % ROOT, 'wb') as csvfile:
        writer = csv.writer(csvfile)
        for val in plotting3x:
            writer.writerow([val])

    with open("%s/plotting3y.txt" % ROOT, 'wb') as csvfile:
        writer = csv.writer(csvfile)
        for val in plotting3y:
            writer.writerow([val])

    with open("%s/plotting3z.txt" % ROOT, 'wb') as csvfile:
        writer = csv.writer(csvfile)
        for val in plotting3z:
            writer.writerow([val])

def regainer(ROOT):
    mum = []
    f = open('%s/mum.txt' % ROOT, 'rb')
    reader = csv.reader(f)
    for row in reader:
        mum.append(float(row[0]))
    f.close()

    a = []
    f = open('%s/a.txt' % ROOT, 'rb')
    reader = csv.reader(f)
    for row in reader:
        a.append(float(row[0]))
    f.close()

    ABase = []
    f = open('%s/Matrix.txt' % ROOT, 'rb')
    reader = csv.reader(f)
    for row in reader:
        ABase.append(float(row[0]))
    f.close()

    ems = []
    f = open('%s/ems.txt' % ROOT, 'rb')
    reader = csv.reader(f)
    for row in reader:
        ems.append(float(row[0]))
    f.close()

    plottingx = []
    f = open('%s/plottingx.txt' % ROOT, 'rb')
    reader = csv.reader(f)
    for row in reader:
        plottingx.append(float(row[0]))
    f.close()

    plottingy = []
    f = open('%s/plottingy.txt' % ROOT, 'rb')
    reader = csv.reader(f)
    for row in reader:
        plottingy.append(float(row[0]))
    f.close()

    plottingz = []
    f = open('%s/plottingz.txt' % ROOT, 'rb')
    reader = csv.reader(f)
    for row in reader:
        plottingz.append(float(row[0]))
    f.close()

    plotting2x = []
    f = open('%s/plotting2x.txt' % ROOT, 'rb')
    reader = csv.reader(f)
    for row in reader:
        plotting2x.append(float(row[0]))
    f.close()

    plotting2y = []
    f = open('%s/plotting2y.txt' % ROOT, 'rb')
    reader = csv.reader(f)
    for row in reader:
        plotting2y.append(float(row[0]))
    f.close()

    plotting2z = []
    f = open('%s/plotting2z.txt' % ROOT, 'rb')
    reader = csv.reader(f)
    for row in reader:
        plotting2z.append(float(row[0]))
    f.close()

    plotting3x = []
    f = open('%s/plotting3x.txt' % ROOT, 'rb')
    reader = csv.reader(f)
    for row in reader:
        plotting3x.append(float(row[0]))
    f.close()

    plotting3y = []
    f = open('%s/plotting3y.txt' % ROOT, 'rb')
    reader = csv.reader(f)
    for row in reader:
        plotting3y.append(float(row[0]))
    f.close()

    plotting3z = []
    f = open('%s/plotting3z.txt' % ROOT, 'rb')
    reader = csv.reader(f)
    for row in reader:
        plotting3z.append(float(row[0]))
    f.close()

    return mum, a, ABase, ems, plottingx, plottingy, plottingz, plotting2x, plotting2y, plotting2z, plotting3x, plotting3y, plotting3z


text:
const {
  GraphQLList,
  GraphQLString,
  GraphQLNonNull,
} = require('graphql');
const { MongoWrapper: mw } = require('../../../util/MongoWrapper');
const { ObjectId } = require('mongodb');
const { Validator } = require('../../../util/Validator');
const { PieceType } = require('../../model/Piece/type');
const { PieceModel } = require('../../model/Piece/Model');
const Io = require('../../../socketeer/Io');

export const deletePiece = {
  type: new GraphQLList(PieceType),
  description: 'mutation(delete) piece description',
  args: {
    id: {
      type: new GraphQLNonNull(GraphQLString),
      description: 'piece\'s pieceId to be removed',
    },
  },
  /**
   * @return {Promise}
   */
  resolve: async (...args) => {
    const [, {
      id,
    }] = args;
    Validator.test([
      ['piece.id', id, { exist: true }],
    ])
    await mw.open();

    /* existence check */
    const piecesExist: { roomId: string }[] = await PieceModel.find({
      _id: new ObjectId(id)
    });
    if (piecesExist.length === 0) {
      throw new Error('対象となるコマが存在しません');
    }

    const roomId = piecesExist[0].roomId;
    await PieceModel.deleteOne({
      _id: new ObjectId(id)
    })

    const pieceResult = await PieceModel.find().where({ roomId }).exec();
    const pieces = pieceResult.map((p) => ({
      id: p._id.toString(),
      characterId: p.characterId,
      roomId: p.roomId,
      type: p.type,
      height: p.height,
      width: p.width,
      x: p.x,
      y: p.y,
    }))

    Io.roomEmit(roomId, 'pieceInfoSync', pieces);
    return pieces;
  }
};


text:
package com.pineone.icbms.sda.itf.template.dao;

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

import org.springframework.stereotype.Repository;

import com.pineone.icbms.sda.itf.template.dto.TemplateDTO;
import com.pineone.icbms.sda.sch.comm.dao.AbstractDAO;

/**
 * 템플릿용 DAO
 */
@Repository("templateDAO")
public class TemplateDAO extends AbstractDAO {

	/**
	 *
	 * @param commandMap
	 * @return List<TemplateDTO>
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public List<TemplateDTO> selectList(Map<String, Object> commandMap) throws Exception {
		return (List<TemplateDTO>)selectList("itf.template.selectList", commandMap);
	}

	/**
	 * 단건 조회
	 * @param commandMap
	 * @return TemplateDTO
	 * @throws Exception
	 */
	public TemplateDTO selectOne(Map<String, Object> commandMap) throws Exception{
		return (TemplateDTO)selectOne("itf.template.selectOne", commandMap);
	}

	/**
	 * ID체크
	 * @param tmid
	 * @return int
	 * @throws Exception
	 */
	public int checkId(String tmid) throws Exception {
		return Integer.parseInt(selectOne("itf.template.checkId", tmid).toString());
	}

}


text:
/**
 * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
 */
package net.sourceforge.pmd.lang.vm.rule;

import net.sourceforge.pmd.Rule;
import net.sourceforge.pmd.RuleContext;
import net.sourceforge.pmd.RuleViolation;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.rule.AbstractRuleViolationFactory;
import net.sourceforge.pmd.lang.rule.ParametricRuleViolation;
import net.sourceforge.pmd.lang.rule.RuleViolationFactory;
import net.sourceforge.pmd.lang.vm.ast.AbstractVmNode;

public final class VmRuleViolationFactory extends AbstractRuleViolationFactory {

    public static final RuleViolationFactory INSTANCE = new VmRuleViolationFactory();

    private VmRuleViolationFactory() {
    }

    @Override
    protected RuleViolation createRuleViolation(final Rule rule, final RuleContext ruleContext, final Node node,
            final String message) {
        return new ParametricRuleViolation<AbstractVmNode>(rule, ruleContext, (AbstractVmNode) node, message);
    }

    @Override
    protected RuleViolation createRuleViolation(final Rule rule, final RuleContext ruleContext, final Node node,
            final String message, final int beginLine, final int endLine) {
        final ParametricRuleViolation<AbstractVmNode> violation = new ParametricRuleViolation<AbstractVmNode>(rule,
                ruleContext, (AbstractVmNode) node, message);
        violation.setLines(beginLine, endLine);
        return violation;
    }
}


text:
package com.proyecto.enrique.osporthello.Activities;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.loopj.android.http.JsonHttpResponseHandler;
import com.proyecto.enrique.osporthello.Adapters.UsersAdapter;
import com.proyecto.enrique.osporthello.AnalyzeJSON;
import com.proyecto.enrique.osporthello.ApiClient;
import com.proyecto.enrique.osporthello.AsyncTask.NameAndImageTask;
import com.proyecto.enrique.osporthello.Fragments.ShowFriendsFragment;
import com.proyecto.enrique.osporthello.Interfaces.UserInfoInterface;
import com.proyecto.enrique.osporthello.Models.User;
import com.proyecto.enrique.osporthello.R;

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

import java.util.ArrayList;

import cz.msebera.android.httpclient.Header;

/**
 * Autor: Enrique Ramos
 * Fecha última actualización: 12/06/2016
 * Descripción: Activity donde se muestran  la lista de Seguidores del usuario, donde el usuario puede
 * iniciar conversaciones en el Chat y Seguir/Dejar de seguir.
 */

public class FollowersActivity extends AppCompatActivity implements UsersAdapter.FriendsChanges, UserInfoInterface {

    private Context context;
    private ProgressBar progressBar;
    private RecyclerView recycler;
    private RecyclerView.Adapter adapter;
    private RecyclerView.LayoutManager lManager;
    private SwipeRefreshLayout swipeRefreshLayout;

    private static UsersAdapter.FriendsChanges myInterface;
    private static UserInfoInterface infoInterface;
    private ArrayList<User> followingList = null;
    private ArrayList<User> followersList = null;
    private static final String SESSION_FILE = "my_session";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_followers);
        swipeRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.updateList);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        //
        this.context = this;
        this.myInterface = this;
        this.infoInterface = this;
        progressBar = (ProgressBar)findViewById(R.id.progressFollowers);
        progressBar.setVisibility(View.GONE);

        // To show back arrow
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        // Obtain Recycler
        recycler = (RecyclerView) findViewById(R.id.recyclerViewFriends);
        recycler.setHasFixedSize(true);

        // LinearLayout administrator
        lManager = new LinearLayoutManager(this);
        recycler.setLayoutManager(lManager);

        if(savedInstanceState == null) {
            progressBar.setVisibility(View.VISIBLE);
            getMyFollowers();
        }
        else{
            followersList = (ArrayList<User>) savedInstanceState.getSerializable("followersList");
            followingList = (ArrayList<User>)savedInstanceState.getSerializable("followingList");
            if(followersList == null || followingList == null){
                progressBar.setVisibility(View.VISIBLE);
                getMyFollowers();
                return;
            }
            adapter = new UsersAdapter(context, myInterface, infoInterface, followersList, followingList);
            recycler.setAdapter(adapter);
            progressBar.setVisibility(View.GONE);
        }

        swipeRefreshLayout.setColorSchemeResources(R.color.accentColor, R.color.primaryColor);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getMyFollowers();
            }
        });
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putSerializable("followersList", followersList);
        outState.putSerializable("followingList", followingList);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            // Respond to the action bar's Up/Home button
            case android.R.id.home:
                setResult(RESULT_OK);
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        setResult(RESULT_OK);
    }

    /**
     * Obtains my followers list
     * @return
     */
    private void getMyFollowers() {
        SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(SESSION_FILE, 0);
        User user = new User(sharedPreferences.getString("email", null),
                sharedPreferences.getString("firstname", null),
                sharedPreferences.getString("lastname", null), null,
                sharedPreferences.getString("apikey", null),
                sharedPreferences.getString("age", null),
                sharedPreferences.getString("city", null),
                sharedPreferences.getString("weight", null),
                sharedPreferences.getString("height", null));

        ApiClient.getUsersByName("api/friends/followers" + "/" + user.getEmail(), new JsonHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject response) {
                progressBar.setVisibility(View.GONE);
                Toast.makeText(context, R.string.connection_error,Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                progressBar.setVisibility(View.GONE);
                Toast.makeText(context, R.string.connection_error,Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) {
                super.onFailure(statusCode, headers, throwable, errorResponse);
                progressBar.setVisibility(View.GONE);
                Toast.makeText(context, R.string.connection_error,Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                try {
                    if (response.getString("code").equals("true")) {
                        followersList = AnalyzeJSON.analyzeAllUsers(response);
                        followingList = AnalyzeJSON.analyzeMyFriends(response);
                        // Instance adapter
                        adapter = new UsersAdapter(context, myInterface, infoInterface, followersList, followingList);
                        recycler.setAdapter(adapter);

                        if(followersList != null){
                            for (int i = 0; i < followersList.size(); i++) {
                                new NameAndImageTask(followersList.get(i).getEmail(), null, null, i, infoInterface).execute();
                            }
                        }
                    }
                    progressBar.setVisibility(View.GONE);
                } catch (JSONException e) {
                    e.printStackTrace();
                    progressBar.setVisibility(View.GONE);
                    Toast.makeText(context, R.string.connection_error,Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
                try {
                    swipeRefreshLayout.setRefreshing(false);
                } catch (Exception e) {
                    //
                }
            }
        });
    }

    @Override
    public void onFriendsChanges(String friendEmail, boolean added) {
        ShowFriendsFragment.FRIENDS_CHANGE = true;
        if(added){
            followingList.add(new User(friendEmail, null, null, null, null));
        }
        else {
            for (int i = 0; i < followingList.size(); i++) {
                User user = followingList.get(i);
                if(user.getEmail().equals(friendEmail))
                    followingList.remove(i);
            }
        }
    }

    @Override
    public void onInfoUserChanges(User userInfo, int index) {
        if(followersList == null || followersList.size() <= index)
            return;
        followersList.get(index).setFirstname(userInfo.getFirstname());
        followersList.get(index).setLastname(userInfo.getLastname());
        followersList.get(index).setImage(userInfo.getImage());
        if(recycler != null && recycler.getAdapter() != null)
            recycler.getAdapter().notifyItemChanged(index);
    }
}