text:
package app.logic.roomavatar;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.widget.ImageView;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import app.config.http.HttpConfig;
import app.yy.geju.R;

/**
 * Created by Administrator on 2017/3/15 0015.
 * author : YSF
 * 网络请求图片用的
 */

public class NetControl {

    private static final int TIME_OUT = 8000;
    private static Context mContext;
    private static File cacheDir;
    private ExecutorService exService;
    private OnNetCallBackListener   onNetCallBackListener ;
    private OnBitmapCallbackListener onBitmapCallbackListener ;

    public void setOnNetCallBackListener(OnNetCallBackListener onNetCallBackListener) {
        this.onNetCallBackListener = onNetCallBackListener;
    }

    public void setOnBitmapCallbackListener(OnBitmapCallbackListener onBitmapCallbackListener) {
        this.onBitmapCallbackListener = onBitmapCallbackListener;
    }

    /**
     * 构造方法
     */
    public NetControl( Context context ) {
        //初始化一个固定有4条线程的线程池
        exService = Executors.newFixedThreadPool(4);
        mContext = context;
        //获取应用缓存路径
        cacheDir = mContext.getCacheDir();
    }

    /**
     * 从网络中获取本地图片
     * @param path
     */
    public void getImageFromNet( final String path ) {
        //用线程池来执行任务
        exService.execute( new Runnable() {
            @Override
            public void run() {
                System.out.println(" Path = "+ path );
                if( path == null || TextUtils.isEmpty( path )){
                    Bitmap bitmap = BitmapFactory.decodeResource( mContext.getResources() , R.drawable.ic_launcher);
                    onNetCallBackListener.onNetCallback( bitmap );
                }else{
                    //从url中截取出图片的名字
                    String fileName = path.substring(path.lastIndexOf("/") + 1 );
                    System.out.println(" fileName = "+ fileName );
                    File file = new File(cacheDir, fileName);
                    //看看图片文件是否存在
                    if (file.exists()) {//存在则说明本地有此图片,直接从本地读取
                        Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
                        onNetCallBackListener.onNetCallback( bitmap );
                    } else {//本地无该图,联网获取
                        fromNet(path);
                    }
                }
            }
        });
    }

    /**
     * 网络获取图片
     * @param path
     */
    private void fromNet(String path) {
        Bitmap bitmap = null ;
        try {
            URL url = new URL( HttpConfig.getUrl( path ) );
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(TIME_OUT);
            conn.connect();
            int code = conn.getResponseCode();
            if ( code == HttpURLConnection.HTTP_OK ) {
                InputStream inputStream = conn.getInputStream();
                //把流解码成图片
                bitmap = BitmapFactory.decodeStream(inputStream);
                //回调结果
                //从url中截取出图片的名字
                String fileName = path.substring(path.lastIndexOf("/") + 1);
                File file = new File(cacheDir, fileName);
                FileOutputStream fos = new FileOutputStream(file);
                //把图片存到本地缓存中 第一个参数,图片格式  第二个参数 存储质量  第三个参数输出流
                bitmap.compress( Bitmap.CompressFormat.JPEG , 100 , fos );
                onNetCallBackListener.onNetCallback( bitmap );
            }
        } catch (Exception e) {
            e.printStackTrace();
            bitmap = BitmapFactory.decodeResource( mContext.getResources() , R.drawable.ic_launcher);
            onNetCallBackListener.onNetCallback( bitmap );
        }
    }

    /**
     * 网络回调接口
     */
    public interface OnNetCallBackListener {
        void onNetCallback(Bitmap bitmap);
    }

    /**
     * Bitmap 回调接口
     */
    public interface OnBitmapCallbackListener {
        void onBitmapCallback(String url, Bitmap bitmap, ImageView coverView);
    }

}


text:
export const hexToRgb = (hex, opacity) => {
	if (!hex) return;
	var rgb = [];

	hex = hex.substr(1); //去除前缀 # 号

	if (hex.length === 3) { // 处理 "#abc" 成 "#aabbcc"
		hex = hex.replace(/(.)/g, '$1$1');
	}

	hex.replace(/../g, function (color) {
		rgb.push(parseInt(color, 0x10)); //按16进制将字符串转换为数字
	});
	if (opacity) {
		return 'rgba(' + rgb.join(',') + ',' + opacity + ')';
	} else {
		return 'rgb(' + rgb.join(',') + ')';
	}
};

export const getUrlValue = (url, key) => {
	if (url && url.indexOf('?') >= 0) {
		url = url.split('?')[1];
		let params = url.split('&');
		if (params.length > 0) {
			for (let i = 0; i < params.length; i++) {
				if (params[i].split('=')[0] === key) {
					return params[i].split('=')[1];
				}
			}
		} else {
			console.log('invalid params');
			return false;
		}
	}
};

export const Fetch = (url, params) => {//params:method,body,headers
	params = params || {};
	params.headers = {
		'Accept': 'application/json, text/plain, */*',
		'Content-Type': 'application/json'
	};
	if (params.body) {
		params.body = JSON.stringify(params.body);
	}
	return fetch(url, params);
}

export const isParent = (obj, parentObj) => {
	while (obj != undefined && obj != null && obj.tagName.toUpperCase() != 'BODY') {
		if (obj == parentObj) {
			return true;
		}
		obj = obj.parentNode;
	}
	return false;
}

export const getRandomString = () => {
	var str = Math.random().toString();
	str = str.slice(2, str.length);
	return str;
};

export const isEqual = (o1, o2) => {
	var leftChain, rightChain;

	function compare2Objects(x, y) {
		var p;
		if (x === null && y === null || typeof x === 'undefined' && typeof y === 'undefined') {
			return true;
		}

		if (x === null && y !== null || y === null && x !== null ||
			typeof x === 'undefined' && typeof y !== 'undefined' ||
			typeof y === 'undefined' && typeof x !== 'undefined') {
			return false;
		}

		// remember that NaN === NaN returns false
		// and isNaN(undefined) returns true
		if (isNaN(x) && isNaN(y) && typeof x === 'number' && typeof y === 'number') {
			return true;
		}
		// Compare primitives and functions.
		// Check if both arguments link to the same object.
		// Especially useful on step when comparing prototypes
		if (x === y) {
			return true;
		}
		// Works in case when functions are created in constructor.
		// Comparing dates is a Common scenario. Another built-ins?
		// We can even handle functions passed across iframes
		if ((typeof x === 'function' && typeof y === 'function') ||
			(x instanceof Date && y instanceof Date) ||
			(x instanceof RegExp && y instanceof RegExp) ||
			(x instanceof String && y instanceof String) ||
			(x instanceof Number && y instanceof Number)) {
			return x.toString() === y.toString();
		}
		// check for infinitive linking loops
		if (leftChain.indexOf(x) > -1 || rightChain.indexOf(y) > -1) {
			return false;
		}
		// Quick checking of one object beeing a subset of another.
		// todo: cache the structure of arguments[0] for performance
		if (y !== null) {
			for (p in y) {
				if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) {
					return false;
				} else if (typeof y[p] !== typeof x[p]) {
					return false;
				}
			}
			for (p in x) {
				if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) {
					return false;
				} else if (typeof y[p] !== typeof x[p]) {
					return false;
				}
				switch (typeof (x[p])) {
					case 'object':
					case 'function':
						leftChain.push(x);
						rightChain.push(y);
						if (!compare2Objects(x[p], y[p])) {
							return false;
						}
						leftChain.pop();
						rightChain.pop();
						break;
					default:
						// remember that NaN === NaN returns false
						if (isNaN(x[p]) && isNaN(y[p]) && typeof x[p] === 'number' && typeof y[p] === 'number') {
							return true;
						}
						if (x[p] !== y[p]) {
							return false;
						}
						break;
				}
			}
		}

		return true;
	}

	leftChain = []; //todo: this can be cached
	rightChain = [];
	if (!compare2Objects(o1, o2)) {
		return false;
	}
	return true;
}

export const getSelectedValue = (jsonArray) => {
	let value = null;
	jsonArray.forEach((json) => {
		if (json.selected) {
			value = json.value;
		}
	})
	return value;
}
export const getFilterOption = (filterJson, repos) => {
	let filters = {};
	let repo = getSelectedValue(repos);

	let status = '';
	let assignee = '';
	let milestone = '';
	let label = [];

	let keys = Object.keys(filterJson);

	if (keys.length > 0) {
		keys.forEach((key) => {
			let value = filterJson[key];
			if (key === 'status') {
				value.forEach((val) => {
					if (val.selected) {
						status = val.value;
					}
				});
			}
			if (key === 'assignee') {
				value.forEach((val) => {
					if (val.selected) {
						assignee = val.title;
					}
				});
			}
			if (key === 'milestone') {
				value.forEach((val) => {
					if (val.selected) {
						milestone = val.value.title;
					}
				});
			}
			if (key === 'label') {
				value.forEach((val) => {
					if (val.selected) {
						label.push(val.value.name);
					}
				});
			}
		});
	}
	filters.repo = repo;
	filters.status = status;
	filters.assignee = assignee;
	filters.milestone = milestone;
	filters.label = label;
	return filters;
}

export const deepClone = (obj) => {
	if (typeof obj !== 'object') {
		return obj;
	}
	return JSON.parse(JSON.stringify(obj));
}

redpajama_set_name: RedPajamaGithub


text:
> A lightweight relational algebra operators library.

## Installation

Install the Haskell Tool [Stack](https://docs.haskellstack.org/en/stable/README/).

From the shell prompt:
```sh
git clone https://github.com/janthelme/relation-tool.git
cd relation-tool
stack build
```
Executable examples are available in the [relation-toolbox-examples repo](https://github.com/JAnthelme/relation-tool-examples). You can either read their [source code](https://github.com/JAnthelme/relation-tool-examples/tree/master/app) or follow the README to run them locally.

## Documentation
Check the [Haddock documentation](https://janthelme.github.io/relation-tool/).

## Basics
For the proper definition of most concepts, see C.J. Date, "*An Introduction to Database Systems*" Eighth Edition, chapter 7 ('*Relational Algebra*').

Loosely speaking a relation is a collection of tuples, or "rows", of elements and each of its "column" is associated to an attribute, i.e. a column name (*label*) and a column type. "Collection" is in the sense of **unordered set**; neither tuples nor attributes ("columns") are ordered and duplicate rows or columns are not allowed.

Relations are of type `Relvar`. Relation elements are of type `Elem`:
```haskell
data Elem =
          -- basic types
          | B Bool | C Char | S String | T Text | I Int | J Integer | D Double | DD Day | DT UTCTime | BS ByteString
          -- others
          | A [Elem]              -- ^ array of Elems
          | T2 (Elem, Elem)       -- ^ pair of Elems
          | T3 (Elem, Elem, Elem) -- ^ triplet of Elems
          | R Relvar              -- ^ relation
          | DW (Down Elem)        -- ^ convenient for ordering Elems in descending order
          | Nil
          deriving (Eq, Ord, Typeable)
```
Motivation for this representation (non-exhaustive list): **Pros**: Simpler code. Easy to extend. **Cons**: Boilerplate code. Users need to update the code in order to add new Elem types.

Note that `R Relvar` is included in `Elem` and in this way relations can contain relations.

`Attributes` and `Row` types are defined in terms of labelled sets `LSet`, a type synonym for `Set (String, a)`. The use of `Set` garantees that duplicates are excluded.
```haskell
type Attributes = LSet TypeRep
```
```haskell
type Row = LSet Elem
```
Relations type:
```haskell
data Relvar = Relvar { attributes :: Attributes   -- ^ Set of the relation's attributes.
                     , rdata      :: Set.Set Row  -- ^ Set of the relation's tuples (i.e. rows).
                     }
                     deriving (Show, Typeable)
```

Unlike relations, tables are for representation; rows and columns are ordered and duplicate rows and columns are allowed. Table type:
```haskell
data Table = Table { header :: [String], tdata :: [[Elem]]} deriving (Show, Eq, Ord)
```

## Getting Started
### Elem
Lists of Elem, `[Elem]`, represent heterogeneous lists. They are necessary to define tuples and relations. To create such a list:
```haskell
mylist = [S "foo", D 3.14159, A [J 123, DD $ fromGregorian 2016 8 19], T2 (I 456, B True)]
```
... or using the `toElem` function:
```haskell
mylist = [toElem ("foo" :: String), toElem (3.14159 :: Double)
         , toElem [toElem (123 :: Integer), toElem $ fromGregorian 2016 8 19]
         , toElem (toElem (456 :: Int), toElem True)]
myotherlist = map toElem ["foo" :: String, "bar", "baz"] ++ map toElem [1..10::Int]
```
To embed a relation , `myrel`, in such a list:
```haskell
mylist = [S "foo", I 123, R myrel]
```
### Relvar
Relation initialization with the `relvar` function:
```haskell
myrel = relvar ["foo", "bar"] [typeOf (undefined::String), typeOf (undefined::Double)]
        [[S "abc", D 3.145159]
        ,[S "xyz", D 2.718281]
        ]
```
Since Haskell does not provide `TypeRep` literals, and because typing `typeOf (undefined::String)` is tedious, some predefined `TypeRep` ["constants"](https://janthelme.github.io/relation-tool/relation-tool-0.1.0.0/Relvar.html#g:10) are available. Relations can then be created that way:
```haskell
myrel = relvar ["foo", "bar"] [tyS, tyD]
        [[S "abc", D 3.145159]
        ,[S "xyz", D 2.718281]
        ]
```
Unicode characters are represented via `(T Text)` `Elem`s:
```haskell
relchinese = relvar ["Hanzi", "Piyin"] [tyT, tyT]
            [[T "中", S "zhōng"]
            ,[T "國", S "guō"]
            ]
```
### Relation representation
Use `show` to print a relation to stdout without formatting:
```sh
*> myrel
Relvar {attributes = fromList [("bar",Double),("foo",[Char])], rdata = fromList [fromList [("bar",2.718281),("foo","xyz")],fromList [("bar",3.145159),("foo","abc")]]}
```
... or use the [view functions](https://janthelme.github.io/relation-tool/relation-tool-0.1.0.0/Relvar-Pretty.html#g:2) to have it in a tabular format:
```sh
*> viewAll myrel
bar       |foo
----------+----------
2.718281  |xyz
----------+----------
3.145159  |abc

```
... or create a table and print it:
```haskell
mytable = table myrel (Just ["foo","bar"]) Nothing Nothing
```
```sh
*> viewAll mytable
foo       |bar
----------+----------
xyz       |2.718281
----------+----------
abc       |3.145159
```
(here we just reordered the columns. Check-out the [`table`](https://janthelme.github.io/relation-tool/relation-tool-0.1.0.0/Relvar.html#g:8) function for more options).
### Relation operators
Given the following relation:
```sh
*> viewAll r_class
ANIMAL    |CLASS
----------+----------
crocodile |reptiles
----------+----------
dolphin   |mammals
----------+----------
flamingo  |birds
----------+----------
hippo     |mammals
----------+----------
horse     |mammals
----------+----------
kangaroo  |mammals
----------+----------
lion      |mammals
----------+----------
ostrich   |birds
----------+----------
pelican   |birds
----------+----------
platypus  |-nil-
----------+----------
turtle    |reptiles
```
... we can project on the "CLASS" column:
```haskell
r_project = project r_class ["CLASS"]
```
```
*> viewAll r_project
CLASS
----------
-nil-
----------
birds
----------
mammals
----------
reptiles
```
... we can restrict on the "mammals" class:
```haskell
f_mamm = (== "mammals") :: String -> Bool
r_restrict = restrict r_class (liftBoolFun f_mamm) ["CLASS"]
```
```sh
*> viewAll r_restrict
ANIMAL    |CLASS
----------+----------
dolphin   |mammals
----------+----------
hippo     |mammals
----------+----------
horse     |mammals
----------+----------
kangaroo  |mammals
----------+----------
lion      |mammals
```
(check the explanation on `liftBoolFun` [here](https://janthelme.github.io/relation-tool/relation-tool-0.1.0.0/Algebra-Function.html) -FIXME).

Given the additional relation:
```sh
*> viewAll r_habitat
ANIMAL    |HABITAT
----------+----------
crocodile |land
----------+----------
crocodile |water
----------+----------
dolphin   |water
----------+----------
flamingo  |air
----------+----------
hippo     |land
----------+----------
hippo     |water
----------+----------
horse     |land
----------+----------
kangaroo  |land
----------+----------
lion      |land
----------+----------
ostrich   |land
----------+----------
pelican   |air
----------+----------
pelican   |water
----------+----------
platypus  |water
----------+----------
turtle    |water
```
... we can join the relations together:
```haskell
r_join = r_class `join` r_habitat
```
```sh
*> viewAll r_join
ANIMAL    |CLASS     |HABITAT
----------+----------+----------
crocodile |reptiles  |land
----------+----------+----------
crocodile |reptiles  |water
----------+----------+----------
dolphin   |mammals   |water
----------+----------+----------
flamingo  |birds     |air
----------+----------+----------
hippo     |mammals   |land
----------+----------+----------
hippo     |mammals   |water
----------+----------+----------
horse     |mammals   |land
----------+----------+----------
kangaroo  |mammals   |land
----------+----------+----------
lion      |mammals   |land
----------+----------+----------
ostrich   |birds     |land
----------+----------+----------
pelican   |birds     |air
----------+----------+----------
pelican   |birds     |water
----------+----------+----------
platypus  |-nil-     |water
----------+----------+----------
turtle    |reptiles  |water
```
... and restrict further:
```haskell
f_mamm_h2o x y = (x == ("mammals")) && (y == ("water"))
r_restrict2 = restrict r_join (liftBoolFun2 f_mamm_h2o) ["CLASS", "HABITAT"]
```
```sh
*> viewAll r_restrict2
ANIMAL    |CLASS     |HABITAT
----------+----------+----------
dolphin   |mammals   |water
----------+----------+----------
hippo     |mammals   |water
```
(check the explanation on `liftBoolFun2` [here](https://janthelme.github.io/relation-tool/relation-tool-0.1.0.0/Algebra-Function.html) -FIXME).

Finally if we join a third relation:
```sh
*> viewAll r_zoo
A#        |ANIMAL
----------+----------
0         |platypus
----------+----------
1         |ostrich
----------+----------
2         |crocodile
----------+----------
2         |dolphin
----------+----------
3         |horse
----------+----------
5         |hippo
----------+----------
7         |kangaroo
----------+----------
10        |lion
----------+----------
13        |flamingo
----------+----------
22        |pelican
----------+----------
123       |turtle
```
```haskell
r_joinall = r_join `join` r_zoo
```
... we can summarize and get the class x habitat pairs living at the zoo:
```haskell
r_summary = summarize r_joinall (project r_joinall ["CLASS", "HABITAT"]) [Count] ["A#"] ["ZOOTOTAL"]
```
```sh
*> viewAll r_summary
CLASS     |HABITAT   |ZOOTOTAL
----------+----------+----------
-nil-     |water     |1
----------+----------+----------
birds     |air       |2
----------+----------+----------
birds     |land      |1
----------+----------+----------
birds     |water     |1
----------+----------+----------
mammals   |land      |4
----------+----------+----------
mammals   |water     |2
----------+----------+----------
reptiles  |land      |1
----------+----------+----------
reptiles  |water     |2
```

Check [Basics.hs](https://github.com/JAnthelme/relation-tool-examples/blob/master/app/Basics.hs) and call `main` to run the examples above. Read the Haddock documentation for [all other operators](https://janthelme.github.io/relation-tool/relation-tool-0.1.0.0/Algebra.html).

## CSV imports

Given the filepath, a delimiter, the column names (*labels*) and their types, inport a csv file into a Relvar:
```haskell
import qualified Relvar.CSV as CSV (CSVSettings(..), toRelation)
-- ...
main :: IO ()
main = do
    r <- CSV.toRelation "./olympics2016_medalists.csv" ';' ["MEDALIST","COUNTRY","ISTEAM"] [tyS, tyS, tyB]
    viewAll r
```

See [CSV.hs](https://github.com/JAnthelme/relation-tool-examples/blob/master/app/CSV.hs) for more details.

## Other examples
See C.J Date's book examples [here](https://github.com/JAnthelme/relation-tool-examples/blob/master/app/CJDate.hs).

## Test
See [Spec.hs](https://github.com/JAnthelme/relation-tool/blob/master/test/Spec.hs). With Stack, run `stack build --test` from the command shell.

## Built With

* [Stack](https://docs.haskellstack.org/en/stable/README/)

Github: https://github.com/JAnthelme/relation-toolbox


text:
KANJI_BLOCKS = [
    'CJK Unified Ideographs',
    'CJK Unified Ideographs Extension A',
    'CJK Unified Ideographs Extension B',
]

def block(ch):
  '''
  Return the Unicode block name for ch, or None if ch has no block.

  >>> block(u'a')
  'Basic Latin'
  >>> block(unichr(0x0b80))
  'Tamil'
  >>> block(unichr(0xe0080))

  '''

  assert isinstance(ch, str) and len(ch) == 1, repr(ch)
  cp = ord(ch)
  for start, end, name in _blocks:
    if start <= cp <= end:
      return name

def _initBlocks(text):
  global _blocks
  _blocks = []
  import re
  pattern = re.compile(r'([0-9A-F]+)\.\.([0-9A-F]+);\ (\S.*\S)')
  for line in text.splitlines():
    m = pattern.match(line)
    if m:
      start, end, name = m.groups()
      _blocks.append((int(start, 16), int(end, 16), name))

# retrieved from http://unicode.org/Public/UNIDATA/Blocks.txt
_initBlocks('''
# Blocks-5.1.0.txt
# Date: 2008-03-20, 17:41:00 PDT [KW]
#
# Unicode Character Database
# Copyright (c) 1991-2008 Unicode, Inc.
# For terms of use, see http://www.unicode.org/terms_of_use.html
# For documentation, see UCD.html
#
# Note:   The casing of block names is not normative.
#         For example, "Basic Latin" and "BASIC LATIN" are equivalent.
#
# Format:
# Start Code..End Code; Block Name

# ================================================

# Note:   When comparing block names, casing, whitespace, hyphens,
#         and underbars are ignored.
#         For example, "Latin Extended-A" and "latin extended a" are equivalent.
#         For more information on the comparison of property values,
#            see UCD.html.
#
#  All code points not explicitly listed for Block
#  have the value No_Block.

# Property: Block
#
# @missing: 0000..10FFFF; No_Block

0000..007F; Basic Latin
0080..00FF; Latin-1 Supplement
0100..017F; Latin Extended-A
0180..024F; Latin Extended-B
0250..02AF; IPA Extensions
02B0..02FF; Spacing Modifier Letters
0300..036F; Combining Diacritical Marks
0370..03FF; Greek and Coptic
0400..04FF; Cyrillic
0500..052F; Cyrillic Supplement
0530..058F; Armenian
0590..05FF; Hebrew
0600..06FF; Arabic
0700..074F; Syriac
0750..077F; Arabic Supplement
0780..07BF; Thaana
07C0..07FF; NKo
0900..097F; Devanagari
0980..09FF; Bengali
0A00..0A7F; Gurmukhi
0A80..0AFF; Gujarati
0B00..0B7F; Oriya
0B80..0BFF; Tamil
0C00..0C7F; Telugu
0C80..0CFF; Kannada
0D00..0D7F; Malayalam
0D80..0DFF; Sinhala
0E00..0E7F; Thai
0E80..0EFF; Lao
0F00..0FFF; Tibetan
1000..109F; Myanmar
10A0..10FF; Georgian
1100..11FF; Hangul Jamo
1200..137F; Ethiopic
1380..139F; Ethiopic Supplement
13A0..13FF; Cherokee
1400..167F; Unified Canadian Aboriginal Syllabics
1680..169F; Ogham
16A0..16FF; Runic
1700..171F; Tagalog
1720..173F; Hanunoo
1740..175F; Buhid
1760..177F; Tagbanwa
1780..17FF; Khmer
1800..18AF; Mongolian
1900..194F; Limbu
1950..197F; Tai Le
1980..19DF; New Tai Lue
19E0..19FF; Khmer Symbols
1A00..1A1F; Buginese
1B00..1B7F; Balinese
1B80..1BBF; Sundanese
1C00..1C4F; Lepcha
1C50..1C7F; Ol Chiki
1D00..1D7F; Phonetic Extensions
1D80..1DBF; Phonetic Extensions Supplement
1DC0..1DFF; Combining Diacritical Marks Supplement
1E00..1EFF; Latin Extended Additional
1F00..1FFF; Greek Extended
2000..206F; General Punctuation
2070..209F; Superscripts and Subscripts
20A0..20CF; Currency Symbols
20D0..20FF; Combining Diacritical Marks for Symbols
2100..214F; Letterlike Symbols
2150..218F; Number Forms
2190..21FF; Arrows
2200..22FF; Mathematical Operators
2300..23FF; Miscellaneous Technical
2400..243F; Control Pictures
2440..245F; Optical Character Recognition
2460..24FF; Enclosed Alphanumerics
2500..257F; Box Drawing
2580..259F; Block Elements
25A0..25FF; Geometric Shapes
2600..26FF; Miscellaneous Symbols
2700..27BF; Dingbats
27C0..27EF; Miscellaneous Mathematical Symbols-A
27F0..27FF; Supplemental Arrows-A
2800..28FF; Braille Patterns
2900..297F; Supplemental Arrows-B
2980..29FF; Miscellaneous Mathematical Symbols-B
2A00..2AFF; Supplemental Mathematical Operators
2B00..2BFF; Miscellaneous Symbols and Arrows
2C00..2C5F; Glagolitic
2C60..2C7F; Latin Extended-C
2C80..2CFF; Coptic
2D00..2D2F; Georgian Supplement
2D30..2D7F; Tifinagh
2D80..2DDF; Ethiopic Extended
2DE0..2DFF; Cyrillic Extended-A
2E00..2E7F; Supplemental Punctuation
2E80..2EFF; CJK Radicals Supplement
2F00..2FDF; Kangxi Radicals
2FF0..2FFF; Ideographic Description Characters
3000..303F; CJK Symbols and Punctuation
3040..309F; Hiragana
30A0..30FF; Katakana
3100..312F; Bopomofo
3130..318F; Hangul Compatibility Jamo
3190..319F; Kanbun
31A0..31BF; Bopomofo Extended
31C0..31EF; CJK Strokes
31F0..31FF; Katakana Phonetic Extensions
3200..32FF; Enclosed CJK Letters and Months
3300..33FF; CJK Compatibility
3400..4DBF; CJK Unified Ideographs Extension A
4DC0..4DFF; Yijing Hexagram Symbols
4E00..9FFF; CJK Unified Ideographs
A000..A48F; Yi Syllables
A490..A4CF; Yi Radicals
A500..A63F; Vai
A640..A69F; Cyrillic Extended-B
A700..A71F; Modifier Tone Letters
A720..A7FF; Latin Extended-D
A800..A82F; Syloti Nagri
A840..A87F; Phags-pa
A880..A8DF; Saurashtra
A900..A92F; Kayah Li
A930..A95F; Rejang
AA00..AA5F; Cham
AC00..D7AF; Hangul Syllables
D800..DB7F; High Surrogates
DB80..DBFF; High Private Use Surrogates
DC00..DFFF; Low Surrogates
E000..F8FF; Private Use Area
F900..FAFF; CJK Compatibility Ideographs
FB00..FB4F; Alphabetic Presentation Forms
FB50..FDFF; Arabic Presentation Forms-A
FE00..FE0F; Variation Selectors
FE10..FE1F; Vertical Forms
FE20..FE2F; Combining Half Marks
FE30..FE4F; CJK Compatibility Forms
FE50..FE6F; Small Form Variants
FE70..FEFF; Arabic Presentation Forms-B
FF00..FFEF; Halfwidth and Fullwidth Forms
FFF0..FFFF; Specials
10000..1007F; Linear B Syllabary
10080..100FF; Linear B Ideograms
10100..1013F; Aegean Numbers
10140..1018F; Ancient Greek Numbers
10190..101CF; Ancient Symbols
101D0..101FF; Phaistos Disc
10280..1029F; Lycian
102A0..102DF; Carian
10300..1032F; Old Italic
10330..1034F; Gothic
10380..1039F; Ugaritic
103A0..103DF; Old Persian
10400..1044F; Deseret
10450..1047F; Shavian
10480..104AF; Osmanya
10800..1083F; Cypriot Syllabary
10900..1091F; Phoenician
10920..1093F; Lydian
10A00..10A5F; Kharoshthi
12000..123FF; Cuneiform
12400..1247F; Cuneiform Numbers and Punctuation
1D000..1D0FF; Byzantine Musical Symbols
1D100..1D1FF; Musical Symbols
1D200..1D24F; Ancient Greek Musical Notation
1D300..1D35F; Tai Xuan Jing Symbols
1D360..1D37F; Counting Rod Numerals
1D400..1D7FF; Mathematical Alphanumeric Symbols
1F000..1F02F; Mahjong Tiles
1F030..1F09F; Domino Tiles
20000..2A6DF; CJK Unified Ideographs Extension B
2F800..2FA1F; CJK Compatibility Ideographs Supplement
E0000..E007F; Tags
E0100..E01EF; Variation Selectors Supplement
F0000..FFFFF; Supplementary Private Use Area-A
100000..10FFFF; Supplementary Private Use Area-B

# EOF
''')


text:
<?php $this->load->view('admin/sidebar') ?>

Edit <?= $pageTitle ?>

 <a href="<?= base_url() ?>"> HOME

 <a href="<?= base_url() ?>form-master"><?= $pageTitle ?>

 Edit <?= $pageTitle ?>

            <?php $this->load->view('admin/msg') ?>

            <?= form_open_multipart(base_url() . 'edit-form-master/' . $pageID, array('id' => 'edit-form-master', 'role' => 'form', 'data-parsley-validate' => '')); ?>
            <?php if (isset($pages) && $pages->num_rows() > 0) {
                $v = $pages->row();
                ?>

                    <input name="pageID" id="pageID" type="hidden" value="<?= $pageID ?>">

Form Details

                                    Form/Menu Name *
                                    <input type="text" name="menuCaption" id="menuCaption" class="form-control" required="" data-parsley-id="8057" value="<?= $v->menuCaption ?>">

                                    Parent Category *
                                    <select name="parentID" class="form-control mb-10" data-parsley-trigger="change" required="" data-parsley-id="3888">
                                        <option value="">Select option...</option>
                                        <option value="1" <?php
                                                if ($v->parentID == 1) {
                                                    echo 'selected';
                                                }
                                                ?>>Master</option>
                                        <option value="2" <?php
                                        if ($v->parentID == 2) {
                                            echo 'selected';
                                        }
                                        ?>>Setup</option>
                                        <option value="3" <?php
                                        if ($v->parentID == 3) {
                                            echo 'selected';
                                        }
                                        ?>>Operations</option>
                                        <option value="4" <?php
                                        if ($v->parentID == 4) {
                                            echo 'selected';
                                        }
                                        ?>>Report</option>
                                    </select>

                                    URL *
                                    <input type="text" name="url" id="url" value="<?= $v->url ?>" class="form-control checkfield" data-tb="pages" data-col="url" required="" data-parsley-id="8057" placeholder="add-form-master">

                                    Icon
                                    <input type="text" name="icon" id="icon" value="<?= $v->icon ?>" class="form-control" data-parsley-id="1328" placeholder="fa fa-plus">

                                    Tooltip
                                    <input type="text" name="tooltip" id="tooltip" value="<?= $v->tooltip ?>" class="form-control" data-parsley-id="1328">

    <?php if (isset($pagealt) && $pagealt->num_rows() > 0) {
        $v1 = $pagealt->row();
        ?>

Page Alter Details

                                        Is Self Edit Allowed

                                                <input type="checkbox" name="isSelfEditAllowed" class="onoffswitch-checkbox" id="isSelfEditAllowed"  <?php
        if ($v1->isSelfEditAllowed == 1) {
            echo 'checked';
        }
        ?> value="1">

                                        Is Self Approval Allowed

                                                <input type="checkbox" name="isSelfApprovalAllowed" class="onoffswitch-checkbox" id="isSelfApprovalAllowed" <?php
                                        if ($v1->isSelfApprovalAllowed == 1) {
                                            echo 'checked';
                                        }
        ?> value="1">

                                        Is Create Approve Required

                                                <input type="checkbox" name="iscreateApproveRequired" class="onoffswitch-checkbox" id="iscreateApproveRequired" value="1" <?php
                                               if ($v1->iscreateApproveRequired == 1) {
                                                   echo 'checked';
                                               }
                                               ?>>

                                        Is Modify Approve Required

                                                <input type="checkbox" name="ismodifyApproveRequired" class="onoffswitch-checkbox" id="ismodifyApproveRequired" <?php
                                               if ($v1->ismodifyApproveRequired == 1) {
                                                   echo 'checked';
                                               }
                                               ?> value="1">

                                        Is Reporting User Approve Allowed

                                                <input type="checkbox" name="isReportingUserApproveAllowed" class="onoffswitch-checkbox" id="isReportingUserApproveAllowed" <?php
                                                if ($v1->isReportingUserApproveAllowed == 1) {
                                                    echo 'checked';
                                                }
                                                ?> value="1">

                                        Default Approver Role

                                            <select name="defaultApproverRoleID" class="form-control mb-10" data-parsley-trigger="change" >
                                                <option value="">Select option...</option>
        <?php
        if (isset($role) && $role->num_rows() > 0) {
            foreach ($role->result() AS $rol) {
                ?>
                                                        <option value="<?= $rol->roleID ?>" <?php if ($v1->defaultApproverRoleID == $rol->roleID) {
                    echo 'selected';
                } ?>><?= $rol->roleName ?></option>
                <?php
            }
        }
        ?>
                                            </select>

<?php } ?>

                             <a  href="<?= base_url() ?>form-master" tabindex="0" class="btn btn-warning"> Go Back

                            <input type="submit" class="btn bg-greensea" id="formSubmit" value="Update" >
                            Submit
                            <input type="submit" class="btn btn-default" id="new_button" onclick="form_submit('edit-form-master')" value="Submit" style="display:none" >

<?php } ?>
<?php echo form_close(); ?>

<?php $this->load->view('admin/footer') ?>


text:
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
		<property name="hibernate.c3p0.min_size">5</property>
		<property name="hibernate.c3p0.max_size">20</property>
		<property name="hibernate.c3p0.timeout">1800</property>
		<property name="hibernate.c3p0.max_statements">50</property>

		<property name="hibernate.c3p0.preferredTestQuery">select 1;</property>
		<property name="hibernate.c3p0.testConnectionOnCheckout">true</property>
	</session-factory>
</hibernate-configuration>


text:
#ifndef _INC_RBIND_
#define _INC_RBIND_

#include "stdio.h"
#include "math.h"
#include "assert.h"

#include "libEmu/emulator.h"
#include "libEmu/estimator-fns.h"
#include "libEmu/emulate-fns.h"
#include "libEmu/regression.h"
#include "libEmu/estimate_threaded.h"

#include "useful.h"

#include "optstruct.h"
#include "modelstruct.h"
#include "resultstruct.h"

#include "../defaults.h"

/**
 * this file contains #defines set by cmake
 * currently we only export VERSION_NUMBER but there
 * could be other nice things we can set here, like if we want to
 * include the R headers or not...
 */
#include "../buildConfig.h"

/**
 * \author C.Coleman-Smith cec24@phy.duke.edu
 * \file rbind.h
 * \brief defines an interface between libEmu and R
 *
 *
 */

/**
 * we'll alloc an instance of this to hold the various data structures
 * needed by setupEmulateMC, callEmulateMC
 * allowing many rapid samples to be generated (hopefully)
 */
struct emulateMCData{
	optstruct* options;
	modelstruct* model;
	gsl_matrix* cov_matrix;
	gsl_matrix* cov_matrix_inverse;
	gsl_vector* beta_vector;
	gsl_matrix* h_matrix;
};

struct emulateMCData emuMCData;

struct emulateMCData *emuMCDataMulti;

/**
 * functions with names: call<whatever> are to be called from the external process (R etc)
 *
 * these are: callEstimate, callEmulateAtList, callEmulateAtPt, callEvalLhoodList
 */

void callEstimate(double* xmodel_in, int* nparams_in, double* training_in, int *nmodelpts, int *nthetas_in, double* final_thetas,
									int* use_fixed_nugget, double* fixed_nugget_in,
									int* cov_fn_index_in, int* regression_order_in);

void callEmulateAtList(double *xmodel_in, int *nparams_in, double* points_in, int *nemupoints, double* training_in,
											 int *nmodelpts, double* thetas_in, int *nthetas_in, double* final_emulated_y,
											 double* final_emulated_variance, int* cov_fn_index_in, int* regression_order_in);

void callEmulateAtPt(double* xmodel_in, int* nparams_in, double* point_in, double* training_in,
										 int* nmodelpts, double* thetas_in, int* nthetas_in, double* final_emulated_y,
										 double* final_emulated_variance, int* cov_fn_index_in, int*regression_order_in);

void callEvalLhoodList(double *xmodel_in, int *nparams_in, double *pointList_in,
											 int *nevalPoints_in, double *training_in, int *nmodelPoints_in,
											 int *nthetas_in, double *answer, int*cov_fn_index_in, int* regression_order_in);

void callInfo(void);

/**
 * functions for quick calls for getting samples of the posterior density
 * you need to call setupEmulateMC first
 */
void setupEmulateMC(double* xmodel_in, int* nparams_in, double* training_in,
										 int* nmodelpts, double* thetas_in, int* nthetas_in,
										int *cov_fn_index_in, int*regression_order_in);

void callEmulateMC(double* point_in, double* mean_out, double* var_out);
void freeEmulateMC(void);

void setupEmulateMCHelper(struct emulateMCData* emuMCData, double* xmodel_in,
													int* nparams_in,  double* training_in,
										 int* nmodelpts, double* thetas_in, int* nthetas_in,
													int *cov_fn_index_in, int*regression_order_in);

void setupEmulateMCMulti(double* xmodel_in, int* nparams_in,
												 double* training_in, int* nydims_in,
												 int* nmodelpts_in, double* thetas_in, int* nthetas_in,
												 int *cov_fn_index_in, int*regression_order_in);

void callEmulateMCMulti(double* point_in, int* nydims_in, double* final_mean, double* final_var);

void freeEmulateMCMulti(int *nydims_in);

/**
 * these are INTERNAL routines, not to be called from outside
 */

void set_ptrs_model(modelstruct *model, optstruct *opt);

#ifdef APPLE

/* some r header information
 * currently things are working in linux so we'll only
 * do this linking in apple builds
 */
#include "Rdefines.h"
#include "R_ext/Rdynload.h"
/**
 * some boilerlate for registering things with R
 *
 * i'm not sure if adding this or switching to an "is.loaded" then load
 * setup in testMac made things work, stupid heisenbugs
 *
 * currently this is just turned on in the CMAKELISTS file
 *
 */

R_NativePrimitiveArgType callEstArgs[10] = {REALSXP, INTSXP, REALSXP, INTSXP, INTSXP, REALSXP,
																						INTSXP, REALSXP, INTSXP, INTSXP};

R_NativePrimitiveArgType callEmuAtListArgs[12] = {REALSXP, INTSXP, REALSXP, INTSXP, REALSXP,
																									INTSXP, REALSXP, INTSXP, REALSXP,
																									REALSXP, INTSXP, INTSXP};

R_NativePrimitiveArgType callEmuAtPtArgs[11] = {REALSXP, INTSXP, REALSXP, REALSXP, INTSXP,
																								REALSXP, INTSXP, REALSXP, REALSXP, INTSXP, INTSXP};

R_NativePrimitiveArgType callEvalListArgs[10] = {REALSXP, INTSXP, REALSXP, INTSXP, REALSXP, INTSXP,
																						 INTSXP, REALSXP, INTSXP, INTSXP};

R_NativePrimitiveArgType setupEmulateMCArgs[8] = {REALSXP, INTSXP, REALSXP,
																									INTSXP, REALSXP, INTSXP,
																									INTSXP, INTSXP};

R_NativePrimitiveArgType callEmulateMCArgs[3] = {REALSXP, REALSXP, REALSXP};

// multidim
R_NativePrimitiveArgType setupEmulateMCMultiArgs[9] = {REALSXP, INTSXP, REALSXP,
																											 INTSXP, INTSXP, REALSXP, INTSXP,
																											 INTSXP, INTSXP};

R_NativePrimitiveArgType callEmulateMCMultiArgs[4] = {REALSXP, INTSXP, REALSXP, REALSXP};

R_NativePrimitiveArgType freeEmulateMCMultiArgs[1] = {INTSXP};

void R_init_libRBIND(DllInfo *dll){

	R_CMethodDef cMethods[] = {
		{"callEstimate", (DL_FUNC)&callEstimate, 10, callEstArgs},
		{"callEmulateAtList", (DL_FUNC)&callEmulateAtList, 12, callEmuAtListArgs},
		{"callEmulateAtPt", (DL_FUNC)&callEmulateAtPt, 11, callEmuAtPtArgs},
		{"callEvalLhoodList", (DL_FUNC)&callEvalLhoodList, 10, callEvalListArgs},
		{"setupEmulateMC", (DL_FUNC)&setupEmulateMC, 8, setupEmulateMCArgs},
		{"callEmulateMC", (DL_FUNC)&callEmulateMC, 3, callEmulateMCArgs},
		{"freeEmulateMC", (DL_FUNC)&freeEmulateMC, 0, NULL},
		{"setupEmulateMCMulti", (DL_FUNC)&setupEmulateMCMulti, 9, setupEmulateMCMultiArgs},
		{"callEmulateMC", (DL_FUNC)&callEmulateMCMulti, 4, callEmulateMCMultiArgs},
		{"freeEmulateMC", (DL_FUNC)&freeEmulateMCMulti, 1, freeEmulateMCMultiArgs},
		{NULL, NULL, 0}
	};

	R_registerRoutines(dll, cMethods, NULL, NULL, NULL);
}

#endif

void fill_sample_scales(modelstruct* the_model, optstruct* options);

/**
 * conversion from R arrays to C
 * we're switching from row major (R) to column major (C)
 * with the added wrinkles that R indexs from 1 AND the 2d structures are
 * interleaved (matrix)
 */

void convertDoubleToMatrix(gsl_matrix* the_matrix, double* input, int ny, int nx);
void convertDoubleToVector(gsl_vector* the_vec, double* input, int nx);
void testConvert(double* matrix, int *nx_in, int *ny_in);

#endif


text:
package com.amazonaws.services.apigateway.model;

public class CreateModelInput {

    private String name;

    private String description;

    private String schema;

    private String contentType;

    /**
     * Returns the value of the name property for this object.
     *
     * @return The value of the name property for this object.
     */
    public String getName() {
        return name;
    }

    /**
     * Sets the value of the name property for this object.
     *
     * @param name The new value for the name property for this object.
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * Sets the value of the name property for this object.
     *
     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param name The new value for the name property for this object.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public CreateModelInput withName(String name) {
        this.name = name;
        return this;
    }

    /**
     * Returns the value of the description property for this object.
     *
     * @return The value of the description property for this object.
     */
    public String getDescription() {
        return description;
    }

    /**
     * Sets the value of the description property for this object.
     *
     * @param description The new value for the description property for this object.
     */
    public void setDescription(String description) {
        this.description = description;
    }

    /**
     * Sets the value of the description property for this object.
     *
     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param description The new value for the description property for this object.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public CreateModelInput withDescription(String description) {
        this.description = description;
        return this;
    }

    /**
     * Returns the value of the schema property for this object.
     *
     * @return The value of the schema property for this object.
     */
    public String getSchema() {
        return schema;
    }

    /**
     * Sets the value of the schema property for this object.
     *
     * @param schema The new value for the schema property for this object.
     */
    public void setSchema(String schema) {
        this.schema = schema;
    }

    /**
     * Sets the value of the schema property for this object.
     *
     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param schema The new value for the schema property for this object.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public CreateModelInput withSchema(String schema) {
        this.schema = schema;
        return this;
    }

    /**
     * Returns the value of the contentType property for this object.
     *
     * @return The value of the contentType property for this object.
     */
    public String getContentType() {
        return contentType;
    }

    /**
     * Sets the value of the contentType property for this object.
     *
     * @param contentType The new value for the contentType property for this object.
     */
    public void setContentType(String contentType) {
        this.contentType = contentType;
    }

    /**
     * Sets the value of the contentType property for this object.
     *
     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param contentType The new value for the contentType property for this object.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public CreateModelInput withContentType(String contentType) {
        this.contentType = contentType;
        return this;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getName() != null) sb.append("name: " + getName() + ",");
        if (getDescription() != null) sb.append("description: " + getDescription() + ",");
        if (getSchema() != null) sb.append("schema: " + getSchema() + ",");
        if (getContentType() != null) sb.append("contentType: " + getContentType() + ",");
        sb.append("}");
        return sb.toString();
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;
        hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode());
        hashCode = prime * hashCode + ((getDescription() == null) ? 0 : getDescription().hashCode());
        hashCode = prime * hashCode + ((getSchema() == null) ? 0 : getSchema().hashCode());
        hashCode = prime * hashCode + ((getContentType() == null) ? 0 : getContentType().hashCode());
        return hashCode;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null) return false;

        if (obj instanceof CreateModelInput == false) return false;
        CreateModelInput other = (CreateModelInput)obj;

        if (other.getName() == null ^ this.getName() == null) return false;
        if (other.getName() != null && other.getName().equals(this.getName()) == false) return false;
        if (other.getDescription() == null ^ this.getDescription() == null) return false;
        if (other.getDescription() != null && other.getDescription().equals(this.getDescription()) == false) return false;
        if (other.getSchema() == null ^ this.getSchema() == null) return false;
        if (other.getSchema() != null && other.getSchema().equals(this.getSchema()) == false) return false;
        if (other.getContentType() == null ^ this.getContentType() == null) return false;
        if (other.getContentType() != null && other.getContentType().equals(this.getContentType()) == false) return false;
        return true;
    }

}


text:
<!DOCTYPE html>
<script src="./profile.js" type="module"></script>


text:
/// <reference path="../../robotParts/Motor.ts" />

class TrikServoMotor extends Motor {
    static parentType = Motor;
    static name = "servo";
    static friendlyName = "Servo Motor";
}


text:
<!doctype html>

    <meta charset="utf-8">
    <title>SparkWaves</title>
    <base href="/">
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width">
    <link href='https://fonts.googleapis.com/css?family=Open+Sans:300,400,200,700' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">

    <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css" />

    <link rel="stylesheet" href="styles/style.css">

                  <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                  </button>

                     SparkWaves

                      View lessons

          About
          ·
          With  from Kenya


text:
<?xml version='1.0' encoding='utf-8'?>
<Context>
    <Resource name="jndi/datasource"
              auth="Container"
              type="javax.sql.DataSource"
              username="root"
              password="root"
              driverClassName="com.mysql.jdbc.Driver"
              url="jdbc:mysql://127.0.0.1:3306/ssh"
              maxActive="8"
              maxldle="4"/>
</Context>


text:
require 'mhl/version'
require 'mhl/genetic_algorithm_solver'
require 'mhl/particle_swarm_optimization_solver'
require 'mhl/quantum_particle_swarm_optimization_solver'
require 'mhl/multiswarm_qpso_solver'


text:
namespace Envoy {
namespace Extensions {
namespace Common {
namespace Wasm {
namespace Null {

// The NullVm wraps a C++ WASM plugin which has been compiled with the WASM API
// and linked directly into the Envoy process. This is useful for development
// in that it permits the debugger to set breakpoints in both Envoy and the plugin.
struct NullVm : public WasmVmBase {
  NullVm(const Stats::ScopeSharedPtr& scope) : WasmVmBase(scope, WasmRuntimeNames::get().Null) {}
  NullVm(const NullVm& other)
      : WasmVmBase(other.scope_, WasmRuntimeNames::get().Null), plugin_name_(other.plugin_name_) {}

  // WasmVm
  absl::string_view runtime() override { return WasmRuntimeNames::get().Null; }
  Cloneable cloneable() override { return Cloneable::InstantiatedModule; };
  WasmVmPtr clone() override;
  bool load(const std::string& code, bool allow_precompiled) override;
  void link(absl::string_view debug_name) override;
  uint64_t getMemorySize() override;
  absl::optional<absl::string_view> getMemory(uint64_t pointer, uint64_t size) override;
  bool setMemory(uint64_t pointer, uint64_t size, const void* data) override;
  bool setWord(uint64_t pointer, Word data) override;
  bool getWord(uint64_t pointer, Word* data) override;
  absl::string_view getCustomSection(absl::string_view name) override;
  absl::string_view getPrecompiledSectionName() override;

#define _FORWARD_GET_FUNCTION(_T)                                                                  \
  void getFunction(absl::string_view function_name, _T* f) override {                              \
    plugin_->getFunction(function_name, f);                                                        \
  }
  FOR_ALL_WASM_VM_EXPORTS(_FORWARD_GET_FUNCTION)
#undef _FORWARD_GET_FUNCTION

  // These are not needed for NullVm which invokes the handlers directly.
#define _REGISTER_CALLBACK(_T)                                                                     \
  void registerCallback(absl::string_view, absl::string_view, _T,                                  \
                        typename ConvertFunctionTypeWordToUint32<_T>::type) override{};
  FOR_ALL_WASM_VM_IMPORTS(_REGISTER_CALLBACK)
#undef _REGISTER_CALLBACK

  std::string plugin_name_;
  std::unique_ptr<NullVmPlugin> plugin_;
};

} // namespace Null
} // namespace Wasm
} // namespace Common
} // namespace Extensions
} // namespace Envoy


text:
<?php

defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'test');

// fcgi doesn't have STDIN and STDOUT defined by default
defined('STDIN') or define('STDIN', fopen('php://stdin', 'r'));
defined('STDOUT') or define('STDOUT', fopen('php://stdout', 'w'));

defined('YII_APP_BASE_PATH') or define('YII_APP_BASE_PATH', dirname(dirname(dirname(__DIR__))));

require_once(YII_APP_BASE_PATH . '/vendor/autoload.php');
require_once(YII_APP_BASE_PATH . '/vendor/yiisoft/yii2/Yii.php');
require_once(YII_APP_BASE_PATH . '/common/config/bootstrap.php');

Yii::setAlias('@tests', dirname(dirname(__DIR__)));


text:
using System.IO;
using System;
using System.Threading.Tasks;

namespace FFImageLoading.Helpers.Gif
{
    internal static class GifHelper
    {
		public static int GetValidFrameDelay(int ms)
		{
			// https://bugzilla.mozilla.org/show_bug.cgi?id=139677
			// https://nullsleep.tumblr.com/post/16524517190/animated-gif-minimum-frame-delay-browser
			if (ms < 20)
				return 100;

			return ms;
		}

        public static async Task<bool> CheckIfAnimatedAsync(Stream st)
        {
            try
            {
				using (var parser = new GifHeaderParser(st))
				{
					return await parser.IsAnimatedAsync().ConfigureAwait(false);
				}
            }
            finally
            {
                st.Position = 0;
            }
        }
    }
}


text:
When /^I add comment:(.*)$/ do |comment|
  fill_in "comment[content]", :with => comment
  click_button '发送'
end


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>cf-pass</groupId>
  <artifactId>cf-pass</artifactId>
  <name>cf-pass</name>
  <description>Library to generate passes</description>
  <version>1.1.0</version>
  <packaging>bundle</packaging>
  <properties>
    <maven.build.timestamp.format>yyyy-MM-dd HH:mm:ss</maven.build.timestamp.format>
    <ext.release.date>${maven.build.timestamp}</ext.release.date>
  </properties>
  <dependencies>
    <dependency>
      <groupId>org.bouncycastle</groupId>
      <artifactId>bcpkix-jdk15on</artifactId>
      <version>1.66</version>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.0</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.felix</groupId>
        <artifactId>maven-bundle-plugin</artifactId>
        <extensions>true</extensions>
      </plugin>
      <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <version>3.1.1</version>
        <executions>
          <execution>
            <id>build-extension</id>
            <phase>package</phase>
            <goals>
              <goal>single</goal>
            </goals>
            <configuration>
              <finalName>cf-pass</finalName>
              <descriptors>
                <descriptor>src/assembly/lucee4.xml</descriptor>
                <descriptor>src/assembly/lucee5.xml</descriptor>
              </descriptors>
            </configuration>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>com.coderplus.maven.plugins</groupId>
        <artifactId>copy-rename-maven-plugin</artifactId>
        <version>1.0.1</version>
        <executions>
          <execution>
            <id>rename-file</id>
            <phase>package</phase>
            <goals>
              <goal>rename</goal>
            </goals>
            <configuration>
              <sourceFile>${project.build.directory}/cf-pass-lucee5-ext.zip</sourceFile>
              <destinationFile>${project.build.directory}/cf-pass-lucee5-ext.lex</destinationFile>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>


text:
path: "/docs/logging/helium-logger"
title: HeliumLogger
---

#HeliumLogger

[Helium Logger](https://github.com/Kitura/HeliumLogger) is a lightweight Swift logging framework which supports logging to standard output.

In this guide we are going to show you how to add Helium Logger to a Kitura server, log messages using the logger and set the level of logging that should be displayed.

> If you don't have a Kitura server, follow our [Create a server](../getting-started/create-server-cli) guide.

---

##Step 1: Add HeliumLogger to the project

If you created your server using the CLI or the macOS app, your project will have HeliumLogger by default. In this case, we can skip to step 3.

Otherwise, we need to [add HeliumLogger to our dependencies](https://github.com/Kitura/HeliumLogger#add-dependencies).

We then need to import `LoggerAPI` and `HeliumLogger` inside our project.

Open your `main.swift` file:

```
open Sources/MyKituraApp/main.swift
```

At the top of the file, add `LoggerAPI` and `HeliumLogger` to our import statements:

```swift
import LoggerAPI
import HeliumLogger
```

> LoggerAPI is a logger protocol that provides a common logging interface for different kinds of loggers. HeliumLogger has LoggerAPI included as a dependency, so we do not need to add this to our `Package.swift` file.

---

##Step 2: Add logging code to the server

To use the default settings for HeliumLogger we just need to call the `use()` method in HeliumLogger.

Inside your `main.swift` add:

```swift
HeliumLogger.use()
```

We are going to use our new logger to log errors thrown by our server.

Inside the catch block, log the thrown error:

```swift
Log.error(error.localizedDescription)
```

Your `main.swift` should look like this:

```swift
import Foundation
import Kitura
import LoggerAPI
import HeliumLogger
import Application

HeliumLogger.use()
do {
    let app = try App()
    try app.run()
} catch let error {
    Log.error(error.localizedDescription)
}
```

Now if you start your server you should see some logging output. This should look something like:

```
[xxx] [VERBOSE] [Kitura.swift:118 run()] Starting Kitura framework...
[xxx] [VERBOSE] [Kitura.swift:135 start()] Starting an HTTP Server on port 8080...
[xxx] [INFO] [HTTPServer.swift:195 listen(on:)] Listening on port 8080
[xxx] [VERBOSE] [HTTPServer.swift:196 listen(on:)] Options for port 8080: maxPendingConnections: 100, allowPortReuse: false
```

---

##Step 3: Set logging level

HeliumLogger can be customized to change the level of logging.

This means you can decide how much information you'd like to be logged, based on importance.

If you'd like to customize the level of logging you can simply pass the level to the `use()` method.

Inside your `main.swift` file, set the logging level:

```swift
HeliumLogger.use(.debug)
```

There are several logging levels:

1. entry
2. exit
3. debug
4. verbose (default)
5. info
6. warning
7. error

Verbose is set by default. Setting a particular logging level also includes all levels below that.

For example, if you set a logging level of `verbose`:

```swift
HeliumLogger.use(.verbose)
```

You will get logging for; `verbose`, `info`, `warning` and `error`.

Similarly if you set a logging level of `warning`:

```swift
HeliumLogger.use(.warning)
```

You will get logging for `warning` and `error`.

---

##Step 4: Add logging to your application

Once you have your Logger configured, you can use it within your application.

Open your `Application.swift` file:

```
open Sources/Application/Application.swift
```

Ensure LoggerAPI is imported:

```swift
import LoggerAPI
```

Add a log message to the App's `init()` function:

```swift
Log.info("Hello World")
```

Restart your server and look through the logs. You should see your message:

```
[2019-03-13T16:23:08.078Z] [INFO] [Application.swift:22 init()] Hello World
```

Your log message is printed along with the time it occurred, the log level and the location in your code.

##Next steps

[Routing](../routing/what-is-routing): Learn about routing and the two types Kitura supports.


text:
package org.openoffice.extensions.util.datamodel;

import org.openoffice.extensions.util.datamodel.properties.OpenOfficeOrgProperty;
import org.openoffice.extensions.util.datamodel.properties.UnknownOpenOfficeOrgLanguageIDException;
import org.openoffice.extensions.util.datamodel.properties.UnknownOpenOfficeOrgPropertyException;

/**
 *
 * @author sg128468
 */
public class PropertyContainer implements OpenOfficeOrgPropertyContainer {

    // CAUTION! PROPERTY_CONTAINER_CONTEXTS and PROPERTY_CONTAINER_CONTEXT_REPRESENTATIONS
    // must always have the same length! Adapt
    // org.openoffice.extensions.projecttemplates.addon.datamodel.Command c'tor
    // when something changes here.
    public static final String[] PROPERTY_CONTAINER_CONTEXTS = new String[] {
        "Bibilography",
        "Chart",
        "Database",
        "Draw",
        "Formula",
        "Presentation",
        "Spreadsheet",
        "Writer",
        "Global",
    }; // NOI18N

    public static final String[] PROPERTY_CONTAINER_CONTEXT_REPRESENTATIONS = new String[] {
        "com.sun.star.frame.Bibliography",
        "com.sun.star.chart.ChartDocument",
        "com.sun.star.sdb.OfficeDatabaseDocument",
        "com.sun.star.drawing.DrawingDocument",
        "com.sun.star.formula.FormulaProperties",
        "com.sun.star.presentation.PresentationDocument",
        "com.sun.star.sheet.SpreadsheetDocument",
        "com.sun.star.text.TextDocument",
        "com.sun.star.text.GlobalDocument",
    }; // NOI18N

    // typical properties index
    public int PROPERTY_DisplayName;
    public int PROPERTY_Description;
    public int PROPERTY_Type;
    public int PROPERTY_Name;
    public int PROPERTY_Category;
    public int PROPERTY_CompatibilityName;
    public int PROPERTY_Exceptions;
    public int PROPERTY_Icon_Hires_Big;
    public int PROPERTY_Icon_Hires_Small;
    public int PROPERTY_Icon_Lowres_Big;
    public int PROPERTY_Icon_Lowres_Small;
    public int PROPERTY_Package;
    public int PROPERTY_ParentException;
    public int PROPERTY_Interface;
    public int PROPERTY_Parent;
    public int[] PROPERTY_Context = new int[PROPERTY_CONTAINER_CONTEXTS.length];

    // typical properties name
    public static final String PROPERTY_CONTAINER_DISPLAY_NAME = "DisplayName"; // NOI18N
    public static final String PROPERTY_CONTAINER_DESCRIPTION = "Description"; // NOI18N
    public static final String PROPERTY_CONTAINER_EXCEPTIONS = "Exceptions"; // NOI18N
    public static final String PROPERTY_CONTAINER_NAME = "Name"; // NOI18N
    public static final String PROPERTY_CONTAINER_CATEGORY = "Category"; // NOI18N
    public static final String PROPERTY_CONTAINER_ICON_HIRES_BIG = "Icon, High Contrast, 26x26"; // NOI18N
    public static final String PROPERTY_CONTAINER_ICON_HIRES_SMALL = "Icon, High Contrast, 16x16"; // NOI18N
    public static final String PROPERTY_CONTAINER_ICON_LOWRES_BIG = "Icon, Low Contrast, 26x26"; // NOI18N
    public static final String PROPERTY_CONTAINER_ICON_LOWRES_SMALL = "Icon, Low Contrast, 16x16"; // NOI18N
    public static final String PROPERTY_CONTAINER_COMPATIBILITY_NAME = "CompatibilityName"; // NOI18N
    public static final String PROPERTY_CONTAINER_PACKAGE = "Package"; // NOI18N
    public static final String PROPERTY_CONTAINER_PARENT_EXCPTION = "ParentException"; // NOI18N
    public static final String PROPERTY_CONTAINER_TYPE = "Type"; // NOI18N
    public static final String PROPERTY_CONTAINER_INTERFACE = "Interface"; // NOI18N
    public static final String PROPERTY_CONTAINER_PARENT = "Parent"; // NOI18N

    // category display name is not used for now
//    public int PROPERTY_CategoryDisplayName;
//    private static final String CATEGORY_DISPLAY_NAME = "CategoryDisplayName"; // NOI18N

    protected OpenOfficeOrgProperty[] properties;

    public PropertyContainer(String[] names) {
        properties = new OpenOfficeOrgProperty[names.length];
        for (int i=0; i<names.length; i++) {
            if (names[i].equals(PROPERTY_CONTAINER_DISPLAY_NAME))
                PROPERTY_DisplayName = i;
            else if (names[i].equals(PROPERTY_CONTAINER_DESCRIPTION))
                PROPERTY_Description = i;
            else if (names[i].equals(PROPERTY_CONTAINER_EXCEPTIONS))
                PROPERTY_Exceptions = i;
            else if (names[i].equals(PROPERTY_CONTAINER_NAME))
                PROPERTY_Name = i;
            else if (names[i].equals(PROPERTY_CONTAINER_CATEGORY))
                PROPERTY_Category = i;
            else if (names[i].equals(PROPERTY_CONTAINER_ICON_HIRES_BIG))
                PROPERTY_Icon_Hires_Big = i;
            else if (names[i].equals(PROPERTY_CONTAINER_ICON_HIRES_SMALL))
                PROPERTY_Icon_Hires_Small = i;
            else if (names[i].equals(PROPERTY_CONTAINER_ICON_LOWRES_BIG))
                PROPERTY_Icon_Lowres_Big = i;
            else if (names[i].equals(PROPERTY_CONTAINER_ICON_LOWRES_SMALL))
                PROPERTY_Icon_Lowres_Small = i;
            else if (names[i].equals(PROPERTY_CONTAINER_COMPATIBILITY_NAME))
                PROPERTY_CompatibilityName = i;
            else if (names[i].equals(PROPERTY_CONTAINER_PACKAGE))
                PROPERTY_Package = i;
            else if (names[i].equals(PROPERTY_CONTAINER_PARENT_EXCPTION))
                PROPERTY_ParentException = i;
            else if (names[i].equals(PROPERTY_CONTAINER_TYPE))
                PROPERTY_Type = i;
            else if (names[i].equals(PROPERTY_CONTAINER_INTERFACE))
                PROPERTY_Interface = i;
            else if (names[i].equals(PROPERTY_CONTAINER_PARENT))
                PROPERTY_Parent = i;
            else {
                for (int j = 0; j < PROPERTY_CONTAINER_CONTEXTS.length; j++) {
                    if (names[i].equals(PROPERTY_CONTAINER_CONTEXTS[j]))
                        PROPERTY_Context[j] = i;
                }
            }
        }
    }

    public String getLocalizedProperty(String propertyName, int languageID)
        throws UnknownOpenOfficeOrgPropertyException, UnknownOpenOfficeOrgLanguageIDException {
        for (int i=0; i<properties.length; i++) {
            if (properties[i] != null && properties[i].isLocalized() && propertyName.equals(properties[i].getPropertyName())) {
                return properties[i].getValueForLanguage(languageID);
            }
        }
        throw new UnknownOpenOfficeOrgPropertyException("Cannot get property " + propertyName); // NOI18N
    }

    public void setLocalizedProperty(String propertyName, int languageID, String value)
        throws UnknownOpenOfficeOrgLanguageIDException {
        for (int i=0; i<properties.length; i++) {
            if (properties[i] != null && properties[i].isLocalized() && propertyName.equals(properties[i].getPropertyName())) {
                properties[i].setValueForLanguage(languageID, value);
            }
        }
    }

    public String getSimpleProperty(String propertyName)
            throws UnknownOpenOfficeOrgPropertyException {
        for (int i=0; i<properties.length; i++) {
            if (properties[i] != null && !properties[i].isLocalized() && propertyName.equals(properties[i].getPropertyName())) {
                try {
                    return properties[i].getValueForLanguage(-1);
                } catch (UnknownOpenOfficeOrgLanguageIDException ex) {
                    // will never be thrown
                }
            }
        }
        throw new UnknownOpenOfficeOrgPropertyException("Unknown: " + propertyName);// NOI18N
    }

    public void setSimpleProperty(String propertyName, String value)
            throws UnknownOpenOfficeOrgPropertyException {
        for (int i=0; i<properties.length; i++) {
            if (properties[i] != null && !properties[i].isLocalized() && propertyName.equals(properties[i].getPropertyName())) {
                try {
                    properties[i].setValueForLanguage(-1, value);
                    return; // evil construct, but function is short anyway
                }
                catch (UnknownOpenOfficeOrgLanguageIDException e) {
                    // will never be thrown
                }
            }
        }
        throw new UnknownOpenOfficeOrgPropertyException("Cannot set property " + propertyName); // NOI18N
    }

    public boolean isPropertyLocalized(String propertyName)
            throws UnknownOpenOfficeOrgPropertyException {
        for (int i=0; i<properties.length; i++) {
            if (properties[i] != null && propertyName.equals(properties[i].getPropertyName())) {
                return properties[i].isLocalized();
            }
        }
        throw new UnknownOpenOfficeOrgPropertyException("No property with name " + propertyName); // NOI18N
    }

    /**
     * some default text is set for a new language on all localized properties
     * existing text is not overwritten
     */
    public void setLanguageWithDefaultText(int languageID, String text)
            throws UnknownOpenOfficeOrgLanguageIDException {
        for (int i=0; i<properties.length; i++) {
            if (properties[i] != null && properties[i].isLocalized()) {
//                if (properties[i].getValueForLanguage(languageID) == null)
                    properties[i].setValueForLanguage(languageID, text);
            }
        }
    }

    public void removeLanguageAndText(int languageID)
            throws UnknownOpenOfficeOrgLanguageIDException {
        for (int i=0; i<properties.length; i++) {
            if (properties[i] != null && properties[i].isLocalized()) {
                properties[i].removeValueForLanguage(languageID);
            }
        }
    }

    public String[] getAllPropertyNames() {
        String[] propNames = new String[properties.length];
        for (int i=0; i<properties.length; i++) {
            if (properties[i] != null)
                propNames[i] = properties[i].getPropertyName();
        }
        return propNames;
    }

    public OpenOfficeOrgProperty getProperty(String propertyName)
            throws UnknownOpenOfficeOrgPropertyException {
        for (int i=0; i<properties.length; i++) {
            if (properties[i] != null && propertyName.equals(properties[i].getPropertyName())) {
                return properties[i];
            }
        }
        throw new UnknownOpenOfficeOrgPropertyException("Cannot get property " + propertyName); // NOI18N
    }

    public void setProperty(String propertyName, OpenOfficeOrgProperty value)
            throws UnknownOpenOfficeOrgPropertyException {
        for (int i=0; i<properties.length; i++) {
            if (properties[i] != null && propertyName.equals(properties[i].getPropertyName())) {
                properties[i] = value;
            }
        }
        throw new UnknownOpenOfficeOrgPropertyException("Cannot set property " + propertyName); // NOI18N
    }

    public OpenOfficeOrgProperty getProperty(int propertyIndex) {
        return properties[propertyIndex];
    }

    public void setProperty(int propertyIndex, OpenOfficeOrgProperty property) {
        properties[propertyIndex] = property;
    }
}


text:
import { ObjectID } from 'mongodb';
import { db } from '../../lib/mongo';
import utils from '../../lib/utils';
import parse from '../../lib/parse';
import webhooks from '../../lib/webhooks';
import CustomerGroupsService from './customerGroups';

class CustomersService {
	constructor() {}

	getFilter(params = {}) {
		// tag
		// gender
		// date_created_to
		// date_created_from
		// total_spent_to
		// total_spent_from
		// orders_count_to
		// orders_count_from

		let filter = {};
		const id = parse.getObjectIDIfValid(params.id);
		const group_id = parse.getObjectIDIfValid(params.group_id);

		if (id) {
			filter._id = new ObjectID(id);
		}

		if (group_id) {
			filter.group_id = group_id;
		}

		if (params.email) {
			filter.email = params.email.toLowerCase();
		}

		if (params.search) {
			filter['$or'] = [
				{ email: new RegExp(params.search, 'i') },
				{ mobile: new RegExp(params.search, 'i') },
				{ $text: { $search: params.search } }
			];
		}

		return filter;
	}

	getCustomers(params = {}) {
		let filter = this.getFilter(params);
		const limit = parse.getNumberIfPositive(params.limit) || 1000;
		const offset = parse.getNumberIfPositive(params.offset) || 0;

		return Promise.all([
			CustomerGroupsService.getGroups(),
			db
				.collection('customers')
				.find(filter)
				.sort({ date_created: -1 })
				.skip(offset)
				.limit(limit)
				.toArray(),
			db.collection('customers').countDocuments(filter)
		]).then(([customerGroups, customers, customersCount]) => {
			const items = customers.map(customer =>
				this.changeProperties(customer, customerGroups)
			);
			const result = {
				total_count: customersCount,
				has_more: offset + items.length < customersCount,
				data: items
			};
			return result;
		});
	}

	getSingleCustomer(id) {
		if (!ObjectID.isValid(id)) {
			return Promise.reject('Invalid identifier');
		}
		return this.getCustomers({ id: id }).then(
			items => (items.data.length > 0 ? items.data[0] : {})
		);
	}

	async addCustomer(data) {
		const customer = this.getValidDocumentForInsert(data);

		// is email unique
		if (customer.email && customer.email.length > 0) {
			const customerCount = await db
				.collection('customers')
				.count({ email: customer.email });
			if (customerCount > 0) {
				return Promise.reject('Customer email must be unique');
			}
		}

		const insertResponse = await db
			.collection('customers')
			.insertMany([customer]);
		const newCustomerId = insertResponse.ops[0]._id.toString();
		const newCustomer = await this.getSingleCustomer(newCustomerId);
		await webhooks.trigger({
			event: webhooks.events.CUSTOMER_CREATED,
			payload: newCustomer
		});
		return newCustomer;
	}

	async updateCustomer(id, data) {
		if (!ObjectID.isValid(id)) {
			return Promise.reject('Invalid identifier');
		}
		const customerObjectID = new ObjectID(id);
		const customer = this.getValidDocumentForUpdate(id, data);

		// is email unique
		if (customer.email && customer.email.length > 0) {
			const customerCount = await db.collection('customers').count({
				_id: {
					$ne: customerObjectID
				},
				email: customer.email
			});

			if (customerCount > 0) {
				return Promise.reject('Customer email must be unique');
			}
		}

		await db.collection('customers').updateOne(
			{
				_id: customerObjectID
			},
			{
				$set: customer
			}
		);

		const updatedCustomer = await this.getSingleCustomer(id);
		await webhooks.trigger({
			event: webhooks.events.CUSTOMER_UPDATED,
			payload: updatedCustomer
		});
		return updatedCustomer;
	}

	updateCustomerStatistics(customerId, totalSpent, ordersCount) {
		if (!ObjectID.isValid(customerId)) {
			return Promise.reject('Invalid identifier');
		}
		const customerObjectID = new ObjectID(customerId);
		const customerData = {
			total_spent: totalSpent,
			orders_count: ordersCount
		};

		return db
			.collection('customers')
			.updateOne({ _id: customerObjectID }, { $set: customerData });
	}

	async deleteCustomer(customerId) {
		if (!ObjectID.isValid(customerId)) {
			return Promise.reject('Invalid identifier');
		}
		const customerObjectID = new ObjectID(customerId);
		const customer = await this.getSingleCustomer(customerId);
		const deleteResponse = await db
			.collection('customers')
			.deleteOne({ _id: customerObjectID });
		await webhooks.trigger({
			event: webhooks.events.CUSTOMER_DELETED,
			payload: customer
		});
		return deleteResponse.deletedCount > 0;
	}

	getValidDocumentForInsert(data) {
		let customer = {
			date_created: new Date(),
			date_updated: null,
			total_spent: 0,
			orders_count: 0
		};

		customer.note = parse.getString(data.note);
		customer.email = parse.getString(data.email).toLowerCase();
		customer.mobile = parse.getString(data.mobile).toLowerCase();
		customer.full_name = parse.getString(data.full_name);
		customer.gender = parse.getString(data.gender).toLowerCase();
		customer.group_id = parse.getObjectIDIfValid(data.group_id);
		customer.tags = parse.getArrayIfValid(data.tags) || [];
		customer.social_accounts =
			parse.getArrayIfValid(data.social_accounts) || [];
		customer.birthdate = parse.getDateIfValid(data.birthdate);
		customer.addresses = this.validateAddresses(data.addresses);
		customer.browser = parse.getBrowser(data.browser);

		return customer;
	}

	validateAddresses(addresses) {
		if (addresses && addresses.length > 0) {
			let validAddresses = addresses.map(addressItem =>
				parse.getCustomerAddress(addressItem)
			);
			return validAddresses;
		} else {
			return [];
		}
	}

	getValidDocumentForUpdate(id, data) {
		if (Object.keys(data).length === 0) {
			return new Error('Required fields are missing');
		}

		let customer = {
			date_updated: new Date()
		};

		if (data.note !== undefined) {
			customer.note = parse.getString(data.note);
		}

		if (data.email !== undefined) {
			customer.email = parse.getString(data.email).toLowerCase();
		}

		if (data.mobile !== undefined) {
			customer.mobile = parse.getString(data.mobile).toLowerCase();
		}

		if (data.full_name !== undefined) {
			customer.full_name = parse.getString(data.full_name);
		}

		if (data.gender !== undefined) {
			customer.gender = parse.getString(data.gender);
		}

		if (data.group_id !== undefined) {
			customer.group_id = parse.getObjectIDIfValid(data.group_id);
		}

		if (data.tags !== undefined) {
			customer.tags = parse.getArrayIfValid(data.tags) || [];
		}

		if (data.social_accounts !== undefined) {
			customer.social_accounts =
				parse.getArrayIfValid(data.social_accounts) || [];
		}

		if (data.birthdate !== undefined) {
			customer.birthdate = parse.getDateIfValid(data.birthdate);
		}

		if (data.addresses !== undefined) {
			customer.addresses = this.validateAddresses(data.addresses);
		}

		if (data.browser !== undefined) {
			customer.browser = parse.getBrowser(data.browser);
		}

		return customer;
	}

	changeProperties(customer, customerGroups) {
		if (customer) {
			customer.id = customer._id.toString();
			delete customer._id;

			const customerGroup = customer.group_id
				? customerGroups.find(
						group => group.id === customer.group_id.toString()
				  )
				: null;

			customer.group_name =
				customerGroup && customerGroup.name ? customerGroup.name : '';

			if (customer.addresses && customer.addresses.length === 1) {
				customer.billing = customer.shipping = customer.addresses[0];
			} else if (customer.addresses && customer.addresses.length > 1) {
				let default_billing = customer.addresses.find(
					address => address.default_billing
				);
				let default_shipping = customer.addresses.find(
					address => address.default_shipping
				);
				customer.billing = default_billing
					? default_billing
					: customer.addresses[0];
				customer.shipping = default_shipping
					? default_shipping
					: customer.addresses[0];
			} else {
				customer.billing = {};
				customer.shipping = {};
			}
		}

		return customer;
	}

	addAddress(customer_id, address) {
		if (!ObjectID.isValid(customer_id)) {
			return Promise.reject('Invalid identifier');
		}
		let customerObjectID = new ObjectID(customer_id);
		const validAddress = parse.getCustomerAddress(address);

		return db.collection('customers').updateOne(
			{
				_id: customerObjectID
			},
			{
				$push: {
					addresses: validAddress
				}
			}
		);
	}

	createObjectToUpdateAddressFields(address) {
		let fields = {};

		if (address.address1 !== undefined) {
			fields['addresses.$.address1'] = parse.getString(address.address1);
		}

		if (address.address2 !== undefined) {
			fields['addresses.$.address2'] = parse.getString(address.address2);
		}

		if (address.city !== undefined) {
			fields['addresses.$.city'] = parse.getString(address.city);
		}

		if (address.country !== undefined) {
			fields['addresses.$.country'] = parse
				.getString(address.country)
				.toUpperCase();
		}

		if (address.state !== undefined) {
			fields['addresses.$.state'] = parse.getString(address.state);
		}

		if (address.phone !== undefined) {
			fields['addresses.$.phone'] = parse.getString(address.phone);
		}

		if (address.postal_code !== undefined) {
			fields['addresses.$.postal_code'] = parse.getString(address.postal_code);
		}

		if (address.full_name !== undefined) {
			fields['addresses.$.full_name'] = parse.getString(address.full_name);
		}

		if (address.company !== undefined) {
			fields['addresses.$.company'] = parse.getString(address.company);
		}

		if (address.tax_number !== undefined) {
			fields['addresses.$.tax_number'] = parse.getString(address.tax_number);
		}

		if (address.coordinates !== undefined) {
			fields['addresses.$.coordinates'] = address.coordinates;
		}

		if (address.details !== undefined) {
			fields['addresses.$.details'] = address.details;
		}

		if (address.default_billing !== undefined) {
			fields['addresses.$.default_billing'] = parse.getBooleanIfValid(
				address.default_billing,
				false
			);
		}

		if (address.default_shipping !== undefined) {
			fields['addresses.$.default_shipping'] = parse.getBooleanIfValid(
				address.default_shipping,
				false
			);
		}

		return fields;
	}

	updateAddress(customer_id, address_id, data) {
		if (!ObjectID.isValid(customer_id) || !ObjectID.isValid(address_id)) {
			return Promise.reject('Invalid identifier');
		}
		let customerObjectID = new ObjectID(customer_id);
		let addressObjectID = new ObjectID(address_id);
		const addressFields = this.createObjectToUpdateAddressFields(data);

		return db.collection('customers').updateOne(
			{
				_id: customerObjectID,
				'addresses.id': addressObjectID
			},
			{ $set: addressFields }
		);
	}

	deleteAddress(customer_id, address_id) {
		if (!ObjectID.isValid(customer_id) || !ObjectID.isValid(address_id)) {
			return Promise.reject('Invalid identifier');
		}
		let customerObjectID = new ObjectID(customer_id);
		let addressObjectID = new ObjectID(address_id);

		return db.collection('customers').updateOne(
			{
				_id: customerObjectID
			},
			{
				$pull: {
					addresses: {
						id: addressObjectID
					}
				}
			}
		);
	}

	setDefaultBilling(customer_id, address_id) {
		if (!ObjectID.isValid(customer_id) || !ObjectID.isValid(address_id)) {
			return Promise.reject('Invalid identifier');
		}
		let customerObjectID = new ObjectID(customer_id);
		let addressObjectID = new ObjectID(address_id);

		return db
			.collection('customers')
			.updateOne(
				{
					_id: customerObjectID,
					'addresses.default_billing': true
				},
				{
					$set: {
						'addresses.$.default_billing': false
					}
				}
			)
			.then(res => {
				return db.collection('customers').updateOne(
					{
						_id: customerObjectID,
						'addresses.id': addressObjectID
					},
					{
						$set: {
							'addresses.$.default_billing': true
						}
					}
				);
			});
	}

	setDefaultShipping(customer_id, address_id) {
		if (!ObjectID.isValid(customer_id) || !ObjectID.isValid(address_id)) {
			return Promise.reject('Invalid identifier');
		}
		let customerObjectID = new ObjectID(customer_id);
		let addressObjectID = new ObjectID(address_id);

		return db
			.collection('customers')
			.updateOne(
				{
					_id: customerObjectID,
					'addresses.default_shipping': true
				},
				{
					$set: {
						'addresses.$.default_shipping': false
					}
				}
			)
			.then(res => {
				return db.collection('customers').updateOne(
					{
						_id: customerObjectID,
						'addresses.id': addressObjectID
					},
					{
						$set: {
							'addresses.$.default_shipping': true
						}
					}
				);
			});
	}
}

export default new CustomersService();


text:
class PostOfficeInput;
class PostOfficeOutput;
class SynchConsoleInput;
class SynchConsoleOutput;
class SynchDisk;

class Kernel {
    public:
        char jobName[1000][100];
        int initTime[1000];
        int listCounter;
        int totalList;
        Kernel(int argc, char **argv);
        // Interpret command line arguments
        ~Kernel();		        // deallocate the kernel

        void Initialize(); 		// initialize the kernel -- separated
        // from constructor because
        // refers to "kernel" as a global
        void ExecAll();
        int Exec(char* name);
        void ThreadSelfTest();	// self test of threads and synchronization

        void ConsoleTest();         // interactive console self test
        void NetworkTest();         // interactive 2-machine network test
        void PrintInt(int number);
        void Nice(int priority);
        Thread* getThread(int threadID){return t[threadID];}
        // These are public for notational convenience; really,
        // they're global variables used everywhere.

        Thread *currentThread;	// the thread holding the CPU
        Scheduler *scheduler;	// the ready list
        Interrupt *interrupt;	// interrupt status
        Statistics *stats;		// performance metrics
        Alarm *alarm;		// the software alarm clock
        Machine *machine;           // the simulated CPU
        SynchConsoleInput *synchConsoleIn;
        SynchConsoleOutput *synchConsoleOut;
        SynchDisk *synchDisk;
        FileSystem *fileSystem;
        PostOfficeInput *postOfficeIn;
        PostOfficeOutput *postOfficeOut;

        int hostName;               // machine identifier

    private:

        Thread* t[1000];
        char*   execfile[1000];
        int priority[1000];
        int execfileNum;
        int threadNum;
        bool randomSlice;		// enable pseudo-random time slicing
        bool debugUserProg;         // single step user program
        double reliability;         // likelihood messages are dropped
        char *consoleIn;            // file to read console input from
        char *consoleOut;           // file to send console output to
#ifndef FILESYS_STUB
        bool formatFlag;          // format the disk if this is true
#endif
};

#endif // KERNEL_H


text:
import {
  DEFAULT_EMISSIONS_SELECTIONS,
  GHG_CALCULATION_OPTIONS
} from 'data/constants';
import { useSlug } from 'utils/utils';

export const getGhgEmissionDefaults = (source, meta) => {
  const sourceName = source.name || source.label;
  const defaults = DEFAULT_EMISSIONS_SELECTIONS[sourceName];
  if (!defaults) return {};

  const sectorDefaults = defaults.sector;
  return {
    gas: (meta.gas.find(g => g.label === defaults.gas) || {}).value,
    sector: (meta.sector.find(s => s.label === sectorDefaults) || {}).value,
    location: defaults.location
  };
};

export const getGhgEmissionDefaultSlugs = (source, meta) => {
  const sourceName = source.name || source.label;
  const defaults = DEFAULT_EMISSIONS_SELECTIONS[sourceName];
  if (!defaults) {
    console.warn(
      'Remember to add the defaults for a new sournce on DEFAULT_EMISSIONS_SELECTIONS'
    );
    return {};
  }
  const gas = meta.gas.find(g => g.label === defaults.gas);
  const sector = meta.sector.find(s => s.label === defaults.sector);
  return {
    gas: gas && useSlug(gas.label),
    sector: sector && useSlug(sector.label),
    location: defaults.location
  };
};

export const calculatedRatio = (selected, calculationData, x) => {
  if (!calculationData || !calculationData[x]) return 1;
  if (selected === GHG_CALCULATION_OPTIONS.PER_GDP.value) {
    // GDP is in dollars and we want to display it in million dollars
    return calculationData[x][0].gdp / 1000000;
  }
  if (selected === GHG_CALCULATION_OPTIONS.PER_CAPITA.value) {
    return calculationData[x][0].population;
  }
  return 1;
};

export const toPlural = model => {
  const plurals = {
    sector: 'sectors',
    gas: 'gases'
  };
  return plurals[model] || model;
};

export const replaceSubscript = text => {
  const super_sub_script_dict = {
    '\u2070': '0',
    '\u00B9': '1',
    '\u00B2': '2',
    '\u00B3': '3',
    '\u2074': '4',
    '\u2075': '5',
    '\u2076': '6',
    '\u2077': '7',
    '\u2078': '8',
    '\u2079': '9',
    '\u2080': '0',
    '\u2081': '1',
    '\u2082': '2',
    '\u2083': '3',
    '\u2084': '4',
    '\u2085': '5',
    '\u2086': '6',
    '\u2087': '7',
    '\u2088': '8',
    '\u2089': '9'
  };
  const regex = /[\u00B9\u00B2\u00B3\u2070\u2074-\u2089]/g;
  return text.replace(regex, x => super_sub_script_dict[x]);
};


text:
require 'logger'
require_relative 'query'

class Pocket
  attr_accessor :consumer_key
  attr_accessor :redirect_url
  attr_accessor :access_token
  attr_accessor :logger

  def initialize(file_with_key = 'consumer.key', redirect_url = 'example1.com')
    @consumer_key = File.open(file_with_key) {|f| f.readline}
    @redirect_url = redirect_url
    @logger = Logger.new(STDOUT)
    @logger.level = Logger::INFO
  end

  def login
    key = send_post_request('https://getpocket.com/v3/oauth/request', {consumer_key: @consumer_key, redirect_uri: @redirect_url})[:code]
    @logger.info('Received oath key')
    `sensible-browser "https://getpocket.com/auth/authorize?request_token=#{key}&redirect_uri=#{@redirect_url}"`
    sleep 5
    @access_token = send_post_request("https://getpocket.com/v3/oauth/authorize", {consumer_key: @consumer_key, code: key})[:access_token]
    @logger.info('Received access token')
  end

  def add_url(url)
    send_post_request("https://getpocket.com/v3/add", {url: url, consumer_key: @consumer_key, access_token: @access_token})
    @logger.info("Added url: #{url}")
  end
end


text:
@(comment: gitbucket.core.model.CommitComment,
  hasWritePermission: Boolean,
  repository: gitbucket.core.service.RepositoryService.RepositoryInfo,
  latestCommitId: Option[String] = None)(implicit context: gitbucket.core.controller.Context)
@import gitbucket.core.view.helpers

      @helpers.avatar(comment.commentedUserName, 20)
      @helpers.user(comment.commentedUserName, styleClass="username strong")

          commented on
          @if(comment.issueId.isDefined){
            #@comment.issueId
          }
          @comment.fileName.map { fileName =>
            @fileName in
          }
          @comment.commitId.substring(0, 7)
          @gitbucket.core.helper.html.datetimeago(comment.registeredDate)

        @if(hasWritePermission || context.loginAccount.map(_.userName == comment.commentedUserName).getOrElse(false)){

        }

      @helpers.markdown(
        markdown = comment.content,
        repository = repository,
        enableWikiLink = false,
        enableRefsLink = true,
        enableLineBreaks = true,
        enableTaskList = false,
        hasWritePermission = hasWritePermission
      )