text:
import os
import mimetypes

from tweepy2.binder import bind_api
from tweepy2.error import TweepError
from tweepy2.parsers import ModelParser
from tweepy2.utils import list_to_csv

class API(object):
    """Twitter API"""

    def __init__(self, auth_handler=None,
            host='api.twitter.com', search_host='search.twitter.com',
             cache=None, secure=True, api_root='/1.1', search_root='',
            retry_count=0, retry_delay=0, retry_errors=None,
            parser=None):
        self.auth = auth_handler
        self.host = host
        self.search_host = search_host
        self.api_root = api_root
        self.search_root = search_root
        self.cache = cache
        self.secure = secure
        self.retry_count = retry_count
        self.retry_delay = retry_delay
        self.retry_errors = retry_errors
        self.parser = parser or ModelParser()

    """ statuses/home_timeline """
    home_timeline = bind_api(
        path = '/statuses/home_timeline.json',
        payload_type = 'status', payload_list = True,
        allowed_param = ['since_id', 'max_id', 'count', 'page'],
        require_auth = True
    )

    """ statuses/user_timeline """
    user_timeline = bind_api(
        path = '/statuses/user_timeline.json',
        payload_type = 'status', payload_list = True,
        allowed_param = ['id', 'user_id', 'screen_name', 'since_id',
                          'max_id', 'count', 'page', 'include_rts']
    )

    """ statuses/mentions """
    mentions_timeline = bind_api(
        path = '/statuses/mentions_timeline.json',
        payload_type = 'status', payload_list = True,
        allowed_param = ['since_id', 'max_id', 'count'],
        require_auth = True
    )

    """/statuses/:id/retweeted_by.format"""
    retweeted_by = bind_api(
        path = '/statuses/{id}/retweeted_by.json',
        payload_type = 'status', payload_list = True,
        allowed_param = ['id', 'count', 'page'],
        require_auth = True
    )

    """/related_results/show/:id.format"""
    related_results = bind_api(
        path = '/related_results/show/{id}.json',
        payload_type = 'relation', payload_list = True,
        allowed_param = ['id'],
        require_auth = False
    )

    """/statuses/:id/retweeted_by/ids.format"""
    retweeted_by_ids = bind_api(
        path = '/statuses/{id}/retweeted_by/ids.json',
        payload_type = 'ids',
        allowed_param = ['id', 'count', 'page'],
        require_auth = True
    )

    """ statuses/retweets_of_me """
    retweets_of_me = bind_api(
        path = '/statuses/retweets_of_me.json',
        payload_type = 'status', payload_list = True,
        allowed_param = ['since_id', 'max_id', 'count', 'page'],
        require_auth = True
    )

    """ statuses/show """
    get_status = bind_api(
        path = '/statuses/show.json',
        payload_type = 'status',
        allowed_param = ['id']
    )

    """ statuses/update """
    update_status = bind_api(
        path = '/statuses/update.json',
        method = 'POST',
        payload_type = 'status',
        allowed_param = ['status', 'in_reply_to_status_id', 'lat', 'long', 'source', 'place_id'],
        require_auth = True
    )

    """ statuses/destroy """
    destroy_status = bind_api(
        path = '/statuses/destroy/{id}.json',
        method = 'POST',
        payload_type = 'status',
        allowed_param = ['id'],
        require_auth = True
    )

    """ statuses/retweet """
    retweet = bind_api(
        path = '/statuses/retweet/{id}.json',
        method = 'POST',
        payload_type = 'status',
        allowed_param = ['id'],
        require_auth = True
    )

    """ statuses/retweets """
    retweets = bind_api(
        path = '/statuses/retweets/{id}.json',
        payload_type = 'status', payload_list = True,
        allowed_param = ['id', 'count'],
        require_auth = True
    )

    """ users/show """
    get_user = bind_api(
        path = '/users/show.json',
        payload_type = 'user',
        allowed_param = ['id', 'user_id', 'screen_name']
    )

    """ Perform bulk look up of users from user ID or screenname """
    def lookup_users(self, user_ids=None, screen_names=None):
        return self._lookup_users(list_to_csv(user_ids), list_to_csv(screen_names))

    _lookup_users = bind_api(
        path = '/users/lookup.json',
        payload_type = 'user', payload_list = True,
        allowed_param = ['user_id', 'screen_name'],
    )

    """ Get the authenticated user """
    def me(self):
        return self.get_user(screen_name=self.auth.get_username())

    """ users/search """
    search_users = bind_api(
        path = '/users/search.json',
        payload_type = 'user', payload_list = True,
        require_auth = True,
        allowed_param = ['q', 'per_page', 'page']
    )

    """ users/suggestions/:slug """
    suggested_users = bind_api(
        path = '/users/suggestions/{slug}.json',
        payload_type = 'user', payload_list = True,
        require_auth = True,
        allowed_param = ['slug', 'lang']
    )

    """ users/suggestions """
    suggested_categories = bind_api(
        path = '/users/suggestions.json',
        payload_type = 'category', payload_list = True,
        allowed_param = ['lang'],
        require_auth = True
    )

    """ users/suggestions/:slug/members """
    suggested_users_tweets = bind_api(
        path = '/users/suggestions/{slug}/members.json',
        payload_type = 'status', payload_list = True,
        allowed_param = ['slug'],
        require_auth = True
    )

    """ direct_messages """
    direct_messages = bind_api(
        path = '/direct_messages.json',
        payload_type = 'direct_message', payload_list = True,
        allowed_param = ['since_id', 'max_id', 'count', 'page'],
        require_auth = True
    )

    """ direct_messages/show """
    get_direct_message = bind_api(
        path = '/direct_messages/show/{id}.json',
        payload_type = 'direct_message',
        allowed_param = ['id'],
        require_auth = True
    )

    """ direct_messages/sent """
    sent_direct_messages = bind_api(
        path = '/direct_messages/sent.json',
        payload_type = 'direct_message', payload_list = True,
        allowed_param = ['since_id', 'max_id', 'count', 'page'],
        require_auth = True
    )

    """ direct_messages/new """
    send_direct_message = bind_api(
        path = '/direct_messages/new.json',
        method = 'POST',
        payload_type = 'direct_message',
        allowed_param = ['user', 'screen_name', 'user_id', 'text'],
        require_auth = True
    )

    """ direct_messages/destroy """
    destroy_direct_message = bind_api(
        path = '/direct_messages/destroy.json',
        method = 'DELETE',
        payload_type = 'direct_message',
        allowed_param = ['id'],
        require_auth = True
    )

    """ friendships/create """
    create_friendship = bind_api(
        path = '/friendships/create.json',
        method = 'POST',
        payload_type = 'user',
        allowed_param = ['id', 'user_id', 'screen_name', 'follow'],
        require_auth = True
    )

    """ friendships/destroy """
    destroy_friendship = bind_api(
        path = '/friendships/destroy.json',
        method = 'DELETE',
        payload_type = 'user',
        allowed_param = ['id', 'user_id', 'screen_name'],
        require_auth = True
    )

    """ friendships/exists """
    exists_friendship = bind_api(
        path = '/friendships/exists.json',
        payload_type = 'json',
        allowed_param = ['user_a', 'user_b']
    )

    """ friendships/show """
    show_friendship = bind_api(
        path = '/friendships/show.json',
        payload_type = 'friendship',
        allowed_param = ['source_id', 'source_screen_name',
                          'target_id', 'target_screen_name']
    )

    """ Perform bulk look up of friendships from user ID or screenname """
    def lookup_friendships(self, user_ids=None, screen_names=None):
	    return self._lookup_friendships(list_to_csv(user_ids), list_to_csv(screen_names))

    _lookup_friendships = bind_api(
        path = '/friendships/lookup.json',
        payload_type = 'relationship', payload_list = True,
        allowed_param = ['user_id', 'screen_name'],
        require_auth = True
    )

    """ friends/ids """
    friends_ids = bind_api(
        path = '/friends/ids.json',
        payload_type = 'ids',
        allowed_param = ['id', 'user_id', 'screen_name', 'cursor']
    )

    """ friendships/incoming """
    friendships_incoming = bind_api(
        path = '/friendships/incoming.json',
        payload_type = 'ids',
        allowed_param = ['cursor']
    )

    """ friendships/outgoing"""
    friendships_outgoing = bind_api(
        path = '/friendships/outgoing.json',
        payload_type = 'ids',
        allowed_param = ['cursor']
    )

    """ followers/ids """
    followers_ids = bind_api(
        path = '/followers/ids.json',
        payload_type = 'ids',
        allowed_param = ['id', 'user_id', 'screen_name', 'cursor']
    )

    """ account/verify_credentials """
    def verify_credentials(self, **kargs):
        try:
            return bind_api(
                path = '/account/verify_credentials.json',
                payload_type = 'user',
                require_auth = True,
                allowed_param = ['include_entities', 'skip_status'],
            )(self, **kargs)
        except TweepError, e:
            if e.response and e.response.status == 401:
                return False
            raise

    """ account/rate_limit_status """
    rate_limit_status = bind_api(
        path = '/application/rate_limit_status.json',
        payload_type = 'json',
        allowed_param = ['resources'],
        use_cache = False
    )

    """ account/update_delivery_device """
    set_delivery_device = bind_api(
        path = '/account/update_delivery_device.json',
        method = 'POST',
        allowed_param = ['device'],
        payload_type = 'user',
        require_auth = True
    )

    """ account/update_profile_colors """
    update_profile_colors = bind_api(
        path = '/account/update_profile_colors.json',
        method = 'POST',
        payload_type = 'user',
        allowed_param = ['profile_background_color', 'profile_text_color',
                          'profile_link_color', 'profile_sidebar_fill_color',
                          'profile_sidebar_border_color'],
        require_auth = True
    )

    """ account/update_profile_image """
    def update_profile_image(self, filename):
        headers, post_data = API._pack_image(filename, 700)
        return bind_api(
            path = '/account/update_profile_image.json',
            method = 'POST',
            payload_type = 'user',
            require_auth = True
        )(self, post_data=post_data, headers=headers)

    """ account/update_profile_background_image """
    def update_profile_background_image(self, filename, *args, **kargs):
        headers, post_data = API._pack_image(filename, 800)
        bind_api(
            path = '/account/update_profile_background_image.json',
            method = 'POST',
            payload_type = 'user',
            allowed_param = ['tile'],
            require_auth = True
        )(self, post_data=post_data, headers=headers)

    """ account/update_profile """
    update_profile = bind_api(
        path = '/account/update_profile.json',
        method = 'POST',
        payload_type = 'user',
        allowed_param = ['name', 'url', 'location', 'description'],
        require_auth = True
    )

    """ favorites """
    favorites = bind_api(
        path = '/favorites/list.json',
        payload_type = 'status', payload_list = True,
        allowed_param = ['screen_name', 'user_id', 'max_id', 'count', 'since_id', 'max_id']
    )

    """ favorites/create """
    create_favorite = bind_api(
        path = '/favorites/create.json',
        method = 'POST',
        payload_type = 'status',
        allowed_param = ['id'],
        require_auth = True
    )

    """ favorites/destroy """
    destroy_favorite = bind_api(
        path = '/favorites/destroy.json',
        method = 'POST',
        payload_type = 'status',
        allowed_param = ['id'],
        require_auth = True
    )

    """ blocks/create """
    create_block = bind_api(
        path = '/blocks/create.json',
        method = 'POST',
        payload_type = 'user',
        allowed_param = ['id', 'user_id', 'screen_name'],
        require_auth = True
    )

    """ blocks/destroy """
    destroy_block = bind_api(
        path = '/blocks/destroy.json',
        method = 'DELETE',
        payload_type = 'user',
        allowed_param = ['id', 'user_id', 'screen_name'],
        require_auth = True
    )

    """ blocks/blocking """
    blocks = bind_api(
        path = '/blocks/list.json',
        payload_type = 'user', payload_list = True,
        allowed_param = ['page'],
        require_auth = True
    )

    """ blocks/blocking/ids """
    blocks_ids = bind_api(
        path = '/blocks/ids.json',
        payload_type = 'json',
        require_auth = True
    )

    """ report_spam """
    report_spam = bind_api(
        path = '/report_spam.json',
        method = 'POST',
        payload_type = 'user',
        allowed_param = ['id', 'user_id', 'screen_name'],
        require_auth = True
    )

    """ saved_searches """
    saved_searches = bind_api(
        path = '/saved_searches/list.json',
        payload_type = 'saved_search', payload_list = True,
        require_auth = True
    )

    """ saved_searches/show """
    get_saved_search = bind_api(
        path = '/saved_searches/show/{id}.json',
        payload_type = 'saved_search',
        allowed_param = ['id'],
        require_auth = True
    )

    """ saved_searches/create """
    create_saved_search = bind_api(
        path = '/saved_searches/create.json',
        method = 'POST',
        payload_type = 'saved_search',
        allowed_param = ['query'],
        require_auth = True
    )

    """ saved_searches/destroy """
    destroy_saved_search = bind_api(
        path = '/saved_searches/destroy/{id}.json',
        method = 'POST',
        payload_type = 'saved_search',
        allowed_param = ['id'],
        require_auth = True
    )

    """ help/test """
    def test(self):
        try:
            bind_api(
                path = '/help/test.json',
            )(self)
        except TweepError:
            return False
        return True

    create_list = bind_api(
        path = '/lists/create.json',
        method = 'POST',
        payload_type = 'list',
        allowed_param = ['name', 'mode', 'description'],
        require_auth = True
    )

    destroy_list = bind_api(
        path = '/lists/destroy.json',
        method = 'POST',
        payload_type = 'list',
        allowed_param = ['owner_screen_name', 'owner_id', 'list_id', 'slug'],
        require_auth = True
    )

    update_list = bind_api(
        path = '/lists/update.json',
        method = 'POST',
        payload_type = 'list',
        allowed_param = ['list_id', 'slug', 'name', 'mode', 'description', 'owner_screen_name', 'owner_id'],
        require_auth = True
    )

    lists_all = bind_api(
        path = '/lists/list.json',
        payload_type = 'list', payload_list = True,
        allowed_param = ['screen_name', 'user_id'],
        require_auth = True
    )

    lists_memberships = bind_api(
        path = '/lists/memberships.json',
        payload_type = 'list', payload_list = True,
        allowed_param = ['screen_name', 'user_id', 'filter_to_owned_lists', 'cursor'],
        require_auth = True
    )

    lists_subscriptions = bind_api(
        path = '/lists/subscriptions.json',
        payload_type = 'list', payload_list = True,
        allowed_param = ['screen_name', 'user_id', 'cursor'],
        require_auth = True
    )

    list_timeline = bind_api(
        path = '/lists/statuses.json',
        payload_type = 'status', payload_list = True,
        allowed_param = ['owner_screen_name', 'slug', 'owner_id', 'list_id', 'since_id', 'max_id', 'count']
    )

    get_list = bind_api(
        path = '/lists/show.json',
        payload_type = 'list',
        allowed_param = ['owner_screen_name', 'owner_id', 'slug', 'list_id']
    )

    add_list_member = bind_api(
        path = '/lists/members/create.json',
        method = 'POST',
        payload_type = 'list',
        allowed_param = ['screen_name', 'user_id', 'owner_screen_name', 'owner_id', 'slug', 'list_id'],
        require_auth = True
    )

    remove_list_member = bind_api(
        path = '/lists/members/destroy.json',
        method = 'POST',
        payload_type = 'list',
        allowed_param = ['screen_name', 'user_id', 'owner_screen_name', 'owner_id', 'slug', 'list_id'],
        require_auth = True
    )

    list_members = bind_api(
        path = '/lists/members.json',
        payload_type = 'user', payload_list = True,
        allowed_param = ['owner_screen_name', 'slug', 'list_id', 'owner_id', 'cursor']
    )

    show_list_member = bind_api(
        path = '/lists/members/show.json',
        payload_type = 'user',
        allowed_param = ['list_id', 'slug', 'user_id', 'screen_name', 'owner_screen_name', 'owner_id']
    )

    subscribe_list = bind_api(
        path = '/lists/subscribers/create.json',
        method = 'POST',
        payload_type = 'list',
        allowed_param = ['owner_screen_name', 'slug', 'owner_id', 'list_id'],
        require_auth = True
    )

    unsubscribe_list = bind_api(
        path = '/lists/subscribers/destroy.json',
        method = 'POST',
        payload_type = 'list',
        allowed_param = ['owner_screen_name', 'slug', 'owner_id', 'list_id'],
        require_auth = True
    )

    list_subscribers = bind_api(
        path = '/lists/subscribers.json',
        payload_type = 'user', payload_list = True,
        allowed_param = ['owner_screen_name', 'slug', 'owner_id', 'list_id', 'cursor']
    )

    show_list_subscriber = bind_api(
        path = '/lists/subscribers/show.json',
        payload_type = 'user',
        allowed_param = ['owner_screen_name', 'slug', 'screen_name', 'owner_id', 'list_id', 'user_id']
    )

    """ trends/available """
    trends_available = bind_api(
        path = '/trends/available.json',
        payload_type = 'json'
    )

    trends_place = bind_api(
        path = '/trends/place.json',
        payload_type = 'json',
        allowed_param = ['id', 'exclude']
    )

    trends_closest = bind_api(
        path = '/trends/closest.json',
        payload_type = 'json',
        allowed_param = ['lat', 'long']
    )

    """ search """
    new_search = bind_api(
        path = '/search/tweets.json',
        payload_type = 'search_result', payload_list = True,
        allowed_param = ['q', 'lang', 'locale', 'rpp', 'page', 'since_id', 'geocode', 'show_user', 'max_id', 'since', 'until', 'result_type']
    )

    """ search """
    search = bind_api(
        search_api = True,
        path = '/search.json',
        payload_type = 'search_result', payload_list = True,
        allowed_param = ['q', 'lang', 'locale', 'rpp', 'page', 'since_id', 'geocode', 'show_user', 'max_id', 'since', 'until', 'result_type']
    )
    search.pagination_mode = 'page'

    """ trends/daily """
    trends_daily = bind_api(
        path = '/trends/daily.json',
        payload_type = 'json',
        allowed_param = ['date', 'exclude']
    )

    """ trends/weekly """
    trends_weekly = bind_api(
        path = '/trends/weekly.json',
        payload_type = 'json',
        allowed_param = ['date', 'exclude']
    )

    """ geo/reverse_geocode """
    reverse_geocode = bind_api(
        path = '/geo/reverse_geocode.json',
        payload_type = 'place', payload_list = True,
        allowed_param = ['lat', 'long', 'accuracy', 'granularity', 'max_results']
    )

    """ geo/id """
    geo_id = bind_api(
        path = '/geo/id/{id}.json',
        payload_type = 'place',
        allowed_param = ['id']
    )

    """ geo/search """
    geo_search = bind_api(
        path = '/geo/search.json',
        payload_type = 'place', payload_list = True,
        allowed_param = ['lat', 'long', 'query', 'ip', 'granularity', 'accuracy', 'max_results', 'contained_within']
    )

    """ geo/similar_places """
    geo_similar_places = bind_api(
        path = '/geo/similar_places.json',
        payload_type = 'place', payload_list = True,
        allowed_param = ['lat', 'long', 'name', 'contained_within']
    )

    """ Internal use only """
    @staticmethod
    def _pack_image(filename, max_size):
        """Pack image from file into multipart-formdata post body"""
        # image must be less than 700kb in size
        try:
            if os.path.getsize(filename) > (max_size * 1024):
                raise TweepError('File is too big, must be less than 700kb.')
        except os.error:
            raise TweepError('Unable to access file')

        # image must be gif, jpeg, or png
        file_type = mimetypes.guess_type(filename)
        if file_type is None:
            raise TweepError('Could not determine file type')
        file_type = file_type[0]
        if file_type not in ['image/gif', 'image/jpeg', 'image/png']:
            raise TweepError('Invalid file type for image: %s' % file_type)

        # build the mulitpart-formdata body
        fp = open(filename, 'rb')
        BOUNDARY = 'Tw3ePy'
        body = []
        body.append('--' + BOUNDARY)
        body.append('Content-Disposition: form-data; name="image"; filename="%s"' % filename)
        body.append('Content-Type: %s' % file_type)
        body.append('')
        body.append(fp.read())
        body.append('--' + BOUNDARY + '--')
        body.append('')
        fp.close()
        body = '\r\n'.join(body)

        # build headers
        headers = {
            'Content-Type': 'multipart/form-data; boundary=Tw3ePy',
            'Content-Length': str(len(body))
        }

        return headers, body


text:
FROM python:3-alpine3.7

# install dependencies
RUN apk add --no-cache openssl-dev \
                       build-base \
                       git \
    && git clone https://github.com/holgern/beem.git \
    && cd beem \
    && python setup.py build \
    && python setup.py install --user \
    && rm -r /beem \
    && apk del build-base \
               git

LABEL maintainer="Max Patternman (https://github.com/maxpatternman)" \
      source="https://github.com/holgern/beem"

redpajama_set_name: RedPajamaGithub


text:
'use strict';

var q = require('q');
var fs = require('fs');
var mkdirp = require('mkdirp');
var path = require('path');

module.exports = (function () {
	var readFile = q.denodeify(fs.readFile);
	var writeFile = q.denodeify(fs.writeFile);
	var makeDir = q.denodeify(mkdirp);
	var readDir = q.denodeify(fs.readdir);
	var stat = q.denodeify(fs.stat);

	function getFile(path) {
		return readFile(path, 'utf8');
	}

	function setFile(path, data) {
		return writeFile(path, data, 'utf8');
	}

	function fileExists(path) {
		var _d = q.defer();

		fs.exists(path, _d.resolve);

		return _d.promise;
	}

	function getJson(path) {
		return getFile(path).then(function (data) {
			return JSON.parse(data);
		});
	}

	function getFolderList(dir) {
		var _d = q.defer();

		readDir(dir).then(function (list) {
			list = list || [];
			var pending = list.length || 0,
				results = [];

			if (!pending) { _d.reject(new Error('Nothing to list: ' + dir)); }

			list.forEach(function(filePath) {
				var path = dir + '/' + filePath;
				stat(path).then(function(dstat) {
					if (dstat && dstat.isDirectory()) {
						results.push(filePath);
					}

					if (!--pending) { _d.resolve(results); }
				});
			});
		}, function () {
			_d.reject(new Error('Folder not found: ' + dir));
		});

		return _d.promise;
	}

	function fileListRecusive(dir) {
		var _d = q.defer(),
			results = [];

		readDir(dir)
			.then(function(list) {

				var pending = list.length;
				if (!pending) { _d.resolve(results); return; }

				list.forEach(function(file) {
					file = path.join(dir, file);
					stat(file)
						.then(function(stat) {
							if (stat && stat.isDirectory()) {
								fileListRecusive(file).then(function(res) {
									results = results.concat(res);
									if (!--pending) { _d.resolve(results); return; }
								});
							} else {
								// omit dotfiles
								if (!file.split('/').pop().match(/^\./)) {
									results.push(file);
								}

								if (!--pending) { _d.resolve(results); return; }
							}
						});
				});
			})
			.fail(_d.reject);

		return _d.promise;
	}

	return {
		readFile: getFile,
		writeFile: setFile,
		fileExists: fileExists,
		json: getJson,
		folderList: getFolderList,
		fileListRecusive: fileListRecusive,
		makeDir: makeDir
	};
})();


text:
<!DOCTYPE html>

    <title>Daily Digest #6 – jakartaDEV – Daily discoveries</title>

        <meta charset="utf-8" />
    <meta content='text/html; charset=utf-8' http-equiv='Content-Type'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <meta name='viewport' content='width=device-width, initial-scale=1, maximum-scale=1'>

    <meta name="description" content="
  Rilis PHP 7.1.0
  Rilis PHP 5.6.25
  PowerShell di Linux
Microsoft merilis PowerShell di Linux, dan juga meng-_opensource_-kan PowerShell, lihat projectnya di GitHub.
  Free Coding School
Dengan banyaknya e-learning, dan orang menjadi menjauh dari sisi sosial, berkurangnya human interaction, menjadikan awal mula ide sekolah ini dan di sini juga digerakkan untuk saling belajar, saling melakukan code review dan lainnya.

    AWS Summit Series 2016 Video

  Running Jenkins on top of a Flocker Cluster using Docker and Ansible
Cara menggunakan Flocker untuk me-manage Docker dan data secara bersamaan.
  Advanced SQL in Rails - Part 1

    Understanding and Hardening Linux Containers

    Trello Android Schema Upgrades
Cara Trello untuk skema SQLite database tabel update di app Android Trello

    Testing Your Drupal Site with Behat

    ProxySQL
sekarang versi 1.2.1 General Availability.

    ARQ
Job queues and RPC in python with asyncio, redis and msgpack.

    Cleave.js
<input> formatting

  Slate.js
Javascript framework untuk rich text editor

" />
    <meta property="og:description" content="
  Rilis PHP 7.1.0
  Rilis PHP 5.6.25
  PowerShell di Linux
Microsoft merilis PowerShell di Linux, dan juga meng-_opensource_-kan PowerShell, lihat projectnya di GitHub.
  Free Coding School
Dengan banyaknya e-learning, dan orang menjadi menjauh dari sisi sosial, berkurangnya human interaction, menjadikan awal mula ide sekolah ini dan di sini juga digerakkan untuk saling belajar, saling melakukan code review dan lainnya.

    AWS Summit Series 2016 Video

  Running Jenkins on top of a Flocker Cluster using Docker and Ansible
Cara menggunakan Flocker untuk me-manage Docker dan data secara bersamaan.
  Advanced SQL in Rails - Part 1

    Understanding and Hardening Linux Containers

    Trello Android Schema Upgrades
Cara Trello untuk skema SQLite database tabel update di app Android Trello

    Testing Your Drupal Site with Behat

    ProxySQL
sekarang versi 1.2.1 General Availability.

    ARQ
Job queues and RPC in python with asyncio, redis and msgpack.

    Cleave.js
<input> formatting

  Slate.js
Javascript framework untuk rich text editor

" />

    <meta name="author" content="jakartaDEV" />

    <meta property="og:title" content="Daily Digest #6" />
    <meta property="twitter:title" content="Daily Digest #6" />

    <meta property="og:title" content="Daily discoveries dan newsletter mingguan untuk developer dan Open source enthusias"/>
    <meta property="og:locale" content="id_ID" />
    <meta property="og:type" content="website" />
    <meta property="og:url" content="http://jakartadev.org/" />
    <meta property="og:site_name" content="JakartaDEV: developement news, tech news dan open source" />
    <meta property="og:image" content="http://localhost:4000/images/logo.png" />
    <meta name="twitter:card" content="summary"/>
    <meta name="twitter:title" content="Daily discoveries dan newsletter mingguan untuk developer dan Open source enthusias"/>
    <meta name="twitter:site" content="@JakartaDev"/>
    <meta name="twitter:image" content="http://localhost:4000/images/logo.png"/>
    <meta name="twitter:creator" content="@JakartaDev"/>

    <link rel="canonical" href="http://jakartadev.org/" />
    <link rel="stylesheet" type="text/css" href="/style.css" />
    <link rel="alternate" type="application/rss+xml" title="jakartaDEV - Daily discoveries" href="/feed.xml" />

    <link href="https://fonts.googleapis.com/css?family=Saira+Condensed|Roboto|Lobster|Patua+One|Open+Sans|PT+Mono" rel="stylesheet">
    <link rel="apple-touch-icon-precomposed" sizes="144x144" href="http://localhost:4000/images/apple-touch-icon-precomposed.png">
    <link rel="icon" type="image/png" href="http://localhost:4000/images/favicon.png">

jakartaDEV

Daily discoveries

            Archives
            Newsletter
            About

      ← home

Daily Digest #6

Rilis PHP 7.1.0

Rilis PHP 5.6.25

PowerShell di Linux
Microsoft merilis PowerShell di Linux, dan juga meng-_opensource_-kan PowerShell, lihat projectnya di GitHub.

Free Coding School
Dengan banyaknya e-learning, dan orang menjadi menjauh dari sisi sosial, berkurangnya human interaction, menjadikan awal mula ide sekolah ini dan di sini juga digerakkan untuk saling belajar, saling melakukan code review dan lainnya.

AWS Summit Series 2016 Video

Running Jenkins on top of a Flocker Cluster using Docker and Ansible
Cara menggunakan Flocker untuk me-manage Docker dan data secara bersamaan.

Advanced SQL in Rails - Part 1

Understanding and Hardening Linux Containers

Trello Android Schema Upgrades
Cara Trello untuk skema SQLite database tabel update di app Android Trello

Testing Your Drupal Site with Behat

ProxySQL
sekarang versi 1.2.1 General Availability.

ARQ
Job queues and RPC in python with asyncio, redis and msgpack.

Cleave.js
<input> formatting

Slate.js
Javascript framework untuk rich text editor

      <form action="https://jakartadev.us12.list-manage.com/subscribe/post?u=a34ff9df1ffbc50651c66d478&id=d1f45e3af1" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" id="subscribe-newsletter" novalidate>

Subscribe Jakartadev newsletter.

          <input type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" style="width: 95%; padding: 1px 2px" placeholder="Your email address"  id="subscribe-field" required>

          <input type="submit" id="mc-embedded-subscribe" value="Subscribe">

    </form>

        Published on August 23, 2016

Curated by dedenf,
        check post hash and verify at keybase.

© Copyright 2018 -- jakartadev.org -- made with ♥ by @dedenf


text:
package tree.expressions;

import tree.DefaultTreeNode;
import tree.symbols.TSBandOp;

public class TAndExpression extends DefaultTreeNode {

	public TAndExpression(TAndExpression node) {
		super(node);
	}

	public TAndExpression(TEqualityExpression eexpr) {
		addChild(eexpr);
	}

	public TAndExpression(TAndExpression aexpr, TSBandOp band_op, TEqualityExpression eexpr) {
		addChild(aexpr);
		addChild(band_op);
		addChild(eexpr);
	}

	public static TAndExpression from(TUnaryExpression uexpr) {
		return new TAndExpression(TEqualityExpression.from(uexpr));
	}

	public static TAndExpression from(TCastExpression cexpr) {
		return new TAndExpression(TEqualityExpression.from(cexpr));
	}
}


text:
package org.voovan.dockerfly.HttpFilter;

import org.voovan.docker.command.Cmd;
import org.voovan.dockerfly.db.DataBaseUtils;
import org.voovan.dockerfly.model.User;
import org.voovan.http.server.HttpFilter;
import org.voovan.http.server.HttpRequest;
import org.voovan.http.server.HttpResponse;
import org.voovan.http.server.HttpSession;
import org.voovan.http.server.context.HttpFilterConfig;
import org.voovan.tools.ObjectPool;
import org.voovan.tools.TString;
import org.voovan.tools.json.JSON;
import org.voovan.tools.log.Logger;
import org.voovan.tools.reflect.TReflect;
import org.voovan.vestful.VestfulGlobal;
import org.voovan.vestful.dto.Error;

import java.lang.reflect.Method;
import java.util.List;

/**
 * 类文字命名
 *
 * @author: helyho
 * DockerFly Framework.
 * WebSite: https://github.com/helyho/DockerFly
 * Licence: Apache v2 License
 */
public class RoleFilter implements HttpFilter {

    /**
     * 尝试初始化数据库
     * @param request 请求对象
     * @param response 响应对象
     */
    public void tryInitDataBase(HttpRequest request, HttpResponse response){
        String requestPath = request.protocol().getPath();
        // 登录页面尝试初始化数据库
        if(requestPath.endsWith("login.html")){
            DataBaseUtils.initDataBase();
        }
    }

    /**
     * 检查静态页面是否登录
     * @param request 请求对象
     * @param response 响应对象
     */
    public void checkPageIsLogin(HttpRequest request, HttpResponse response) {
        String requestPath = request.protocol().getPath();
        User user = getUserFromSession(request);

        // 除登录页面,在没有登录时,全部转向到登录页面
        if ((requestPath.endsWith(".html") || requestPath.endsWith("/"))
                && !requestPath.endsWith("login.html") && user == null) {
            response.redirct("/login.html");
            DataBaseUtils.initDataBase();
        }

        if(requestPath.endsWith("logout.html")){
            HttpSession session = request.getSession();
            session.removeAttribute("User");
            response.redirct("/login.html");
        }
    }

    /**
     * 创建对象权限管理
     * @param request 请求对象
     * @param response 响应对象
     */
    public void onCreateObject(HttpRequest request, HttpResponse response){
        String requestPath = request.protocol().getPath();
        //DirectObject 创建对象方法捕获类名
        if(requestPath.endsWith("createObject")){
            String className = request.getParameter("className");
        }
    }

    /**
     * 用户管理操作(OperUser类的方法)控制
     * @param request 请求对象
     * @param response 响应对象
     */
    public void userOperation(HttpRequest request, HttpResponse response){
        ObjectPool objectPool = VestfulGlobal.getObjectPool();
        String objectId = request.getParameter("pooledObjectId");
        Object obj = objectPool.get(objectId);
        String className = obj.getClass().getName();
        String methodName = request.getParameter("methodName");
        List params = request.getParameterAsObject("params",List.class);
        User user = getUserFromSession(request);

        //检查修改用户属性的操作是否合法
        if(className.equals("org.voovan.dockerfly.DataOperate.OperUser")){
            switch (methodName){
                case "checkUser" :
                    return;
                //判断单用户操作是否合法
                case "modifyPassword" :;
                case "modifyHosts":;
                case "modifyDefaultHost":;
                case "getUser": {
                    if(user != null) {
                        //用户 ID 和参数中提供的 ID 不同的时候,且不是 Admin 类型的用户,返回错误
                        if (params != null && user.getUserId() != (Integer) params.get(0)) {
                            if (!user.getRole().equals("Admin")) {
                                error("NO_RIGHT", request, response);
                            }
                        }
                    } else {
                        disposeNotLogin(request, response);
                    }
                };

                //只有管理员用户可以执行的操作
                case "getUserList":;
                case "addUser":;
                case "delUser":{
                    if(user!=null) {
                        if (!user.getRole().equals("Admin")) {
                            error("NO_RIGHT", request, response);
                        }
                    } else {
                        disposeNotLogin(request, response);
                    }
                };
            }
        }
    }

    /**
     * JDocker方法操作控制
     * @param request 请求对象
     * @param response 响应对象
     */
    public void dockerOperation(HttpRequest request, HttpResponse response){
        ObjectPool objectPool = VestfulGlobal.getObjectPool();
        String objectId = request.getParameter("pooledObjectId");
        Object obj = objectPool.get(objectId);
        String className = obj.getClass().getName();
        String methodName = request.getParameter("methodName");
        User user = getUserFromSession(request);

        if(TString.regexMatch(className,"org\\.voovan\\.docker\\.command") > 0) {
            if (user != null) {
                //创建和查看 Docker 实体在 Label 中增加用户标志 (针对User用户类型进行处理)
                if (className.matches("org\\.voovan\\.docker\\.command\\..*?\\.Cmd[^(Image)].*?(Create|List)") &&
                        methodName.equals("send") &&
                        user.getRole().equals("User")) {
                    try {
                        Method method = TReflect.findMethod(obj.getClass(), "label", new Class[]{String.class, String.class});
                        if (method != null) {
                            TReflect.invokeMethod(obj, method, "org.voovan.dockerfly.label.UserId", String.valueOf(user.getUserId()));
                            TReflect.invokeMethod(obj, method, "org.voovan.dockerfly.label.UserName", user.getUserName());
                        }
                    } catch (ReflectiveOperationException e) {
                        e.printStackTrace();
                    }
                }
            } else {
                disposeNotLogin(request, response);
            }
        }
    }

    /**
     * 处理为登录操作
     * @param request 请求对象
     * @param response 响应对象
     */
    public void disposeNotLogin(HttpRequest request, HttpResponse response){
        ObjectPool objectPool = VestfulGlobal.getObjectPool();
        String objectId = request.getParameter("pooledObjectId");
        Object obj = objectPool.get(objectId);
        if(obj instanceof Cmd){
            ((Cmd)obj).close();
        }
        objectPool.remove(objectId);
        error("NOT_LOGIN", request, response);
    }

    /**
     * 方法调用权限控制
     * @param request 请求对象
     * @param response 响应对象
     */
    public void onInvoke(HttpRequest request, HttpResponse response){
        String requestPath = request.protocol().getPath();

        //DirectObject 调用对象方法权限判断
        if(requestPath.endsWith("invoke")){
            userOperation(request, response);
            dockerOperation(request, response);
        }

    }

    @Override
    public Object onRequest(HttpFilterConfig filterConfig, HttpRequest request,
                            HttpResponse response, Object prevFilterResult)  {
        HttpSession session = request.getSession();
        User user = getUserFromSession(request);
        String requestPath = request.protocol().getPath();

        // 登录页面尝试初始化数据库
        tryInitDataBase(request, response);

        //检查是否登录
        //除登录页面,在没有登录时,全部转向到登录页面
        checkPageIsLogin(request, response);

        //DirectObject 创建对象方法捕获类名
        onCreateObject(request, response);

        onInvoke(request, response);

        return null;
    }

    @Override
    public Object onResponse(HttpFilterConfig filterConfig, HttpRequest request, HttpResponse response, Object prevFilterResult) {

        User user = getUserFromSession(request);
        String requestPath = request.protocol().getPath();

        HttpSession session = request.getSession();
        //DirectObject 调用对象方法
        if(requestPath.endsWith("invoke")){

            String methodName = request.getParameter("methodName");

            if(methodName.equals("checkUser")){
                String body = response.body().getBodyString();
                if(!body.equals("null")){
                    user = JSON.toObject(body, User.class);
                    session.setAttribute("User", user);
                    Logger.simple("User ["+user.getUserName()+"] logined.");
                }
            }
        }

        return null;
    }

    /**
     * 从会话对象获取用户对象
     * @param request 请求对象
     * @return 用户对象
     */
    public static User getUserFromSession(HttpRequest request){
        HttpSession session = request.getSession();
        User user = null;
        if(session.containAttribute("User")) {
            user = (User)session.getAttribute("User");
        }
        return user;
    }

    /**
     * 构造错误信息
     * @param type 错误类型,此类型需要和前端 js 匹配
     * @param request 请求对象
     * @param response 响应对象
     */
    public static void error(String type, HttpRequest request,HttpResponse response){
        String result = Error.newInstance(request.protocol().getPath(), type, "You didn't hava right.").toString();
        response.protocol().setStatus(506);
        response.body().write(result);
    }
}


text:
#ifndef __c5_MON_sl_replacement_h__
#define __c5_MON_sl_replacement_h__

/* Include files */
#include "sf_runtime/sfc_sf.h"
#include "sf_runtime/sfc_mex.h"
#include "rtwtypes.h"
#include "multiword_types.h"

/* Type Definitions */
#ifndef typedef_SFc5_MON_sl_replacementInstanceStruct
#define typedef_SFc5_MON_sl_replacementInstanceStruct

typedef struct {
  SimStruct *S;
  ChartInfoStruct chartInfo;
  uint32_T chartNumber;
  uint32_T instanceNumber;
  int32_T c5_sfEvent;
  boolean_T c5_doneDoubleBufferReInit;
  uint8_T c5_is_active_c5_MON_sl_replacement;
  uint8_T c5_doSetSimStateSideEffects;
  const mxArray *c5_setSimStateSideEffectsInfo;
  boolean_T *c5_p;
  int32_T *c5_c;
  int32_T *c5_pre_c;
} SFc5_MON_sl_replacementInstanceStruct;

#endif                                 /*typedef_SFc5_MON_sl_replacementInstanceStruct*/

/* Named Constants */

/* Variable Declarations */
extern struct SfDebugInstanceStruct *sfGlobalDebugInstanceStruct;

/* Variable Definitions */

/* Function Declarations */
extern const mxArray *sf_c5_MON_sl_replacement_get_eml_resolved_functions_info
  (void);

/* Function Definitions */
extern void sf_c5_MON_sl_replacement_get_check_sum(mxArray *plhs[]);
extern void c5_MON_sl_replacement_method_dispatcher(SimStruct *S, int_T method,
  void *data);

#endif


text:
#import <XCTest/XCTest.h>

#import <IGListKit/IGListKit.h>

#import "IGListTestSection.h"
#import "IGListTestAdapterDataSource.h"

@interface IGReloadDataUpdaterTests : XCTestCase

@property (nonatomic, strong) IGListCollectionView *collectionView;
@property (nonatomic, strong) IGListAdapter *adapter;
@property (nonatomic, strong) IGListTestAdapterDataSource *dataSource;
@property (nonatomic, strong) UICollectionViewFlowLayout *layout;
@property (nonatomic, strong) UIWindow *window;

@end

@implementation IGReloadDataUpdaterTests

- (void)setUp {
    [super setUp];

    // minimum line spacing, item size, and minimum interim spacing are all set in IGListTestSection
    self.window = [[UIWindow alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];

    self.layout = [[UICollectionViewFlowLayout alloc] init];
    self.collectionView = [[IGListCollectionView alloc] initWithFrame:self.window.bounds collectionViewLayout:self.layout];

    [self.window addSubview:self.collectionView];

    // syncronous reloads so we dont have to do expectations or other nonsense
    IGListReloadDataUpdater *updater = [[IGListReloadDataUpdater alloc] init];

    self.dataSource = [[IGListTestAdapterDataSource alloc] init];
    self.adapter = [[IGListAdapter alloc] initWithUpdater:updater
                                           viewController:nil
                                         workingRangeSize:0];
    self.adapter.collectionView = self.collectionView;
    self.adapter.dataSource = self.dataSource;
}

- (void)test_whenCompletionBlockExists_thatBlockExecuted {
    __block BOOL executed = NO;
    self.dataSource.objects = @[@0, @1, @2];
    [self.adapter reloadDataWithCompletion:^(BOOL finished) {
        executed = YES;
    }];
    XCTAssertTrue(executed);
}

- (void)test_whenInsertingIntoContext_thatCollectionViewUpdated {
    self.dataSource.objects = @[@2];
    [self.adapter reloadDataWithCompletion:nil];
    XCTAssertEqual([self.collectionView numberOfItemsInSection:0], 2);
    IGListTestSection *section = [self.adapter sectionControllerForObject:@2];
    section.items = 3;
    [section.collectionContext insertInSectionController:section atIndexes:[NSIndexSet indexSetWithIndex:0]];
    XCTAssertEqual([self.collectionView numberOfItemsInSection:0], 3);
}

- (void)test_whenDeletingFromContext_thatCollectionViewUpdated {
    self.dataSource.objects = @[@2];
    [self.adapter reloadDataWithCompletion:nil];
    XCTAssertEqual([self.collectionView numberOfItemsInSection:0], 2);
    IGListTestSection *section = [self.adapter sectionControllerForObject:@2];
    section.items = 1;
    [section.collectionContext deleteInSectionController:section atIndexes:[NSIndexSet indexSetWithIndex:0]];
    XCTAssertEqual([self.collectionView numberOfItemsInSection:0], 1);
}

- (void)test_whenReloadingInContext_thatCollectionViewUpdated {
    self.dataSource.objects = @[@2];
    [self.adapter reloadDataWithCompletion:nil];
    XCTAssertEqual([self.collectionView numberOfItemsInSection:0], 2);
    IGListTestSection *section = [self.adapter sectionControllerForObject:@2];
    [section.collectionContext reloadInSectionController:section atIndexes:[NSIndexSet indexSetWithIndex:0]];
    XCTAssertEqual([self.collectionView numberOfItemsInSection:0], 2);
}

- (void)test_whenPerformingUpdate_thatCompletionExecuted {
    __block BOOL executed = NO;
    self.dataSource.objects = @[@0, @1, @2];
    [self.adapter performUpdatesAnimated:NO completion:^(BOOL finished) {
        executed = YES;
    }];
    XCTAssertTrue(executed);
}

@end


text:
<?php

class M_propiedad extends CI_Model {

      public function __construct(){

      	$this->load->database();

      }

       public function get_propiedad($slug = FALSE) {

      	if($slug === FALSE){
      		$query = $this->db->get('propiedades');
      		return $query->result_array();
      	}

      	$query = $this->db->get_where('propiedades', array('slug' => $slug));
      	return $query->row_array();

      }

}


text:
<?php

namespace Phramework\ValidateFiller;

use Phramework\Validate\ArrayValidator;
use Phramework\Validate\BaseValidator;

/**
 * @license https://www.apache.org/licenses/LICENSE-2.0 Apache-2.0
 * @since  0.2.0
 * @author Xenofon Spafaridis <nohponex@gmail.com>
 */
class ArrayValidatorFiller implements IValidatorFillerArrayValidatorFiller
{
    /**
     * @var IFillerRepository
     */
    protected $fillerRepository;

    /**
     * @param IFillerRepository $repository
     * @return IValidatorFillerWithFillerRepository
     * @return $this
     */
    public function withIFillerRepository(
        IFillerRepository $repository
    ) : IValidatorFillerWithFillerRepository {
        $copy = clone $this;

        $copy->fillerRepository = $repository;

        return $copy;
    }

    /**
     * @param ArrayValidator $validator
     * @throws \DomainException
     * @return array
     */
    public function fill(BaseValidator $validator)
    {
        $minItems = $validator->minItems;
        $maxItems = $validator->maxItems ?? PHP_INT_MAX;

        $numberOfItems = random_int($minItems, $maxItems);

        $items = [];

        $validatorAllowedItems = $validator->items;

        if ($validatorAllowedItems === null) {
            throw new \DomainException(
                'Not implemented to work without specific items'
            );
        }

        for ($i = 0; $i<$numberOfItems; ++$i) {
            //todo deal with infinite loop
            $item = $this
                ->fillerRepository
                ->fill(
                    $validator->items
                );

            //todo refactor
            while ($validator->uniqueItems && in_array($item, $items, true)) {
                $item = $this
                    ->fillerRepository
                    ->fill(
                        $validator->items
                    );
            }

            $items[] = $item;
        }

        return $items;
    }
}


text:
__author__="EIXXIE"

from sqlalchemy import create_engine,func
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from flask import json
from config import SQLALCHEMY_DATABASE_URI
#from config import SQLALCHEMY_MIGRATE_REPO
from mos import db

engine = create_engine(SQLALCHEMY_DATABASE_URI, convert_unicode=True)

db_session = scoped_session(sessionmaker(autocommit=False,
                                         autoflush=False,
                                         bind=engine))
Base = declarative_base()
Base.query = db_session.query_property()

def init_db():
    Base.metadata.create_all(bind=engine)

def aviable_groups_for_user(userid):
    groups=[]
    conn = engine.connect()
    sql = 'select groups.id as groupid,groupname FROM groups CROSS JOIN uig where groups.id = uig.group_id and uig.user_id = \'' + \
            str(userid) + '\' ' + 'order by groupname'
    print(sql)
    rs = conn.execute(sql)
    for r in rs:
        print(r)
        groups.append(r)
        #groups.append([r.groupid,r.groupname])
        return groups

def get_record_nums():
    user_all_nums = db_session.query(User).count()
    user_active_nums = db_session.query(User).filter(User.is_active=='1').count()
    group_all_nums = db_session.query(Group).count()
    group_active_nums = db_session.query(Group).filter(Group.is_active=='1').count()
    repo_all_nums = db_session.query(Repo).count()
    repo_active_nums = db_session.query(Repo).filter(Repo.is_active=='1').count()
    authitem_all_nums = db_session.query(AuthItem).count()
    datas={'user_all_nums':user_all_nums, 'user_active_nums':user_active_nums,\
           'group_all_nums':group_all_nums,'group_active_nums':group_active_nums,\
           'repo_all_nums':repo_all_nums,'repo_active_nums':repo_active_nums,\
           'authitem_all_nums':authitem_all_nums}
    return datas

def SetData(type,para):
    conn = engine.connect()
    if type=='authitem':
        sql = 'select repos.id FROM auth_items CROSS JOIN repos where repos.reponame = \'' + para[0] +'\' '
        print(sql)
        rs = conn.execute(sql)
        for r in rs:
            repo_id = r[0]
        sql = 'insert into auth_items(\'repo_id\',\'authitem\') values(\'' + str(repo_id) +'\',' +'\'' + para[1] + '\')'
        print(sql)
        rs = conn.execute(sql)

#获得包含用户名和密码的用户数据
def get_user_passwd(reponame):
    users=[]
    conn = engine.connect()
    if reponame=='irepresentalltherepos':
        sql = 'select username,password from users'
    else:
        sql = 'select username,password from users cross join auth_users,repos,auth_items where auth_users.user_id=users.id and auth_users.authitem_id = auth_items.id and auth_items.repo_id = repos.id and repos.reponame = \'' + reponame +'\' order by reponame,authitem,username,authtype'
    rs = conn.execute(sql)
    for r in rs:
        users.append({'username':r.username,'password':r.password})
    #print(users)
    return users

#获取特定格式的数据
def GetData(type,para):
    conn = engine.connect()
    #单项配置项数据
    if type == 'authitemid':
        authitem=[]
        sql = 'select auth_items.id as id,reponame,authitem FROM auth_items CROSS JOIN repos where auth_items.repo_id = repos.id \
        and repos.reponame = \'' + para[0] +'\' and auth_items.authitem = \'' + para[1] + '\' order by reponame,authitem'
        #print(sql)
        rs = conn.execute(sql)
        for r in rs:
            #print(r)
            authitem.append(r)
            return r[0]
    elif type == 'authiteminfo':
        authitem=[]
        sql = 'select reponame,authitem FROM auth_items CROSS JOIN repos where auth_items.repo_id = repos.id \
        and auth_items.id = \'' + para[0] + '\' order by reponame'
        #print(sql)
        rs = conn.execute(sql)
        for r in rs:
            #print(r)
            authitem.append(r)
            return authitem
    elif type == 'authitems':
        authitems=[]
        if para=='all':
            sql = 'select auth_items.id as id,reponame,authitem FROM auth_items CROSS JOIN repos where auth_items.repo_id = repos.id order by reponame,authitem'
        else:
            sql = 'select auth_items.id as id,reponame,authitem FROM auth_items CROSS JOIN repos where auth_items.repo_id = repos.id and \
            repos.reponame like \'%' + para + '%\' order by reponame,authitem'
        #print(sql)
        rs = conn.execute(sql)
        for r in rs:
            #print(r)
            authitems.append(r)
        #print(authitems)
        return authitems
    elif type == 'users-json':
        users=[]
        if para=='all':
            sql = 'select id,fullname,username FROM users order by username'
        else:
            pass
        #print(sql)
        rs = conn.execute(sql)
        for r in rs:
            #print(r)
            users.append({'id':r.id,'name':r.fullname + ' (' + r.username + ' )'})
        json_users = json.dumps(users)
        #print(users)
        #print(json_users)
        return json_users
    elif type == 'groups-json':
            groups=[]
            if para=='all':
                sql = 'select id,groupname FROM groups order by groupname'
            else:
                pass
            rs = conn.execute(sql)
            for r in rs:
                #print(r)
                groups.append({'id':r.id,'name':r.groupname})
            json_groups = json.dumps(groups)
            #print(groups)
            #print(json_groups)
            return json_groups
    elif type == 'repos-json':
            repos=[]
            if para=='all':
                sql = 'select id,reponame FROM repos order by reponame'
            else:
                pass
            rs = conn.execute(sql)
            for r in rs:
                #print(r)
                repos.append({'id':r.id,'name':r.reponame})
            json_repos = json.dumps(repos)
            #print(repos)
            #print(json_repos)
            return json_repos
    elif type == 'repos':
            repos=[]
            if para=='all':
                sql = 'select id,reponame FROM repos order by reponame'
            else:
                pass
            rs = conn.execute(sql)
            for r in rs:
                #print(r)
                repos.append(r.reponame)
            return repos

#获取配置库相关的组包含用户的信息
def get_user_groups(reponame):
    user_groups=[]
    conn = engine.connect()
    if reponame=='irepresentalltherepos':
        sql = 'select groupname,username from auth_groups cross join uig,groups,users,repos,auth_items where auth_groups.group_id=groups.id and auth_groups.authitem_id = auth_items.id and auth_items.repo_id = repos.id and uig.user_id = users.id and uig.group_id = groups.id order by reponame,username'
    else:
        sql = 'select groupname,username from auth_groups cross join uig,groups,users,repos,auth_items where auth_groups.group_id=groups.id and auth_groups.authitem_id = auth_items.id and auth_items.repo_id = repos.id and uig.user_id = users.id and uig.group_id = groups.id and repos.reponame = \'' + reponame +'\' order by reponame,username'
    rs = conn.execute(sql)
    groups = set([])
    for r in rs:
        groups.add(r.groupname)
    names = locals()
    for group in groups:
        names['%s' % group] = {'groupname':group,'users':''}
        names['users_%s' % group] = ''
        rs = conn.execute(sql)
        for r in rs:
            if r.groupname == group:
                names['users_%s' % group]=names['users_%s' % group]+','+r.username
        names['%s' % group]['users']=list(set((names['users_%s' % group].lstrip(',')).split(',')))
        names['%s' % group]['users'] = ','.join(names['%s' % group]['users'])
        user_groups.append(names['%s' % group])
    return user_groups

#获取用户及组的权限认证信息
def get_auths(type,reponame):
    auths=[]
    conn = engine.connect()
    if type=='user':
        if reponame=='irepresentalltherepos':
            sql = 'select reponame,authitem,username,authtype from auth_users cross join users,repos,auth_items where auth_users.user_id=users.id and auth_users.authitem_id = auth_items.id and auth_items.repo_id = repos.id order by reponame,authitem,username,authtype'
        else:
            sql = 'select reponame,authitem,username,authtype from auth_users cross join users,repos,auth_items where auth_users.user_id=users.id and auth_users.authitem_id = auth_items.id and auth_items.repo_id = repos.id and repos.reponame = \'' + reponame +'\' order by reponame,authitem,username,authtype'
        rs = conn.execute(sql)
        for r in rs:
            #print(r)
            auths.append({'reponame':r.reponame,'authitem':r.authitem,'username':r.username,'authtype':r.authtype})
    elif type=='group':
        if reponame=='irepresentalltherepos':
            sql = 'select reponame,authitem,groupname,authtype from auth_groups cross join groups,repos,auth_items where auth_groups.group_id=groups.id and auth_groups.authitem_id = auth_items.id and auth_items.repo_id = repos.id order by reponame,authitem,groupname,authtype'
        else:
            sql = 'select reponame,authitem,groupname,authtype from auth_groups cross join groups,repos,auth_items where auth_groups.group_id=groups.id and auth_groups.authitem_id = auth_items.id and auth_items.repo_id = repos.id and repos.reponame = \'' + reponame +'\' order by reponame,authitem,groupname,authtype'
        rs = conn.execute(sql)
        for r in rs:
            #print(r)
            auths.append({'reponame':r.reponame,'authitem':r.authitem,'groupname':r.groupname,'authtype':r.authtype})
    return auths

def get_groups():
    conn = engine.connect()
    sql = 'select id,groupname from groups order by groupname'
    rs = conn.execute(sql)

#检查配置项是否已经存在
def is_data_exist(type,para):
    conn = engine.connect()
    if type == 'authitem':
        authitem=[]
        sql = 'select repo_id,authitem FROM auth_items where auth_items.repo_id = \'' + para[0] \
            +'\' and auth_items.authitem = \'' + para[1] + '\' order by repo_id'
        #print(sql)
        rs = conn.execute(sql)
        for r in rs:
            #print(r)
            authitem.append(r)
        if len(authitem)==0:
            return False
        else:
            return True
    else:
        return '参数错误'

class DBMaster(object):
    def __repr__(self):
        return "<{}>".format(self.__class__.__name__)

    def save(self):
        db_session.add(self)
        #try:
        db_session.commit()
        #except:
            #db_session.rollback()
        return self

    def delete(self):
        db_session.delete(self)
        db_session.commit()
        return self


text:
#include "biopsy/pssm.h"
#include "biopsy/custom_pssm.h"
#include "biopsy/sequence.h"

#include <bio/biobase_db.h>
#include <bio/sequence.h>
#include <bio/cache.h>
#include <bio/singleton.h>
#include <bio/serialisable.h>
#include <bio/environment.h>

using namespace boost;
using namespace std;

namespace biopsy {

pssm_parameters::pssm_parameters()
    : pseudo_counts( 0.25 )
    , likelihoods_size( 100 )
    , calculate_likelihoods_map_size( 10000 )
    , binding_background_odds_prior( 2e-5 )
    , use_cumulative_dists( true )
    , use_p_value( false )
    , use_score( false )
    , avg_phylo_bayes( true )
    , max_chain_num_boxes_limit( 50000 )
    , min_related_evidence_fraction( .5 )
{
}

nucleo_dist::nucleo_dist(
    double a,
    double c,
    double g,
    double t )
{
    _values[ 0 ] = a;
    _values[ 1 ] = c;
    _values[ 2 ] = g;
    _values[ 3 ] = t;
}

nucleo_dist::vec  operator + (const nucleo_dist::vec & v,double pseudo_count)
{
    nucleo_dist::vec retVal;

    BOOST_FOREACH(const nucleo_dist & c, v)
    {
        nucleo_dist dist(
            c.get(0) + pseudo_count,
            c.get(1) + pseudo_count,
            c.get(2) + pseudo_count,
            c.get(3) + pseudo_count);
        retVal.push_back(dist);
    }
    return retVal;
}

/** argument is 0 for a, 1 for c, ... */
double
nucleo_dist::get( unsigned nucleo ) const
{
    return _values[ nucleo ];
}

void
nucleo_dist::set( unsigned nucleo, double value )
{
    _values[ nucleo ] = value;
}

double
nucleo_dist::get_total( ) const
{
    return std::accumulate( _values.begin(), _values.end(), 0.0 );
}

/** argument is 0 for a, 1 for c, ... */
double
nucleo_dist::get_freq( unsigned nucleo ) const
{
    return get( nucleo ) / get_total();
}

bool
nucleo_dist::operator==( const nucleo_dist & rhs ) const
{
    return
        _values == rhs._values;
}

nucleo_dist
uniform_nucleo_dist()
{
    return nucleo_dist( 0.25, 0.25, 0.25, 0.25 );
}

nucleo_dist
get_dist_for_iupac( char s )
{
    USING_BIO_NS;
    IupacCode i( s );
    return
        nucleo_dist(
            i.get_num( 'a' ),
            i.get_num( 'c' ),
            i.get_num( 'g' ),
            i.get_num( 't' ) );
}

pssm_ptr
create_pssm(
    const nucleo_dist::vec & dists )
{
    //from http://nar.oxfordjournals.org/cgi/reprint/31/13/3576

    //first calculate the information vector and the min and max scores possible
    std::vector< double > infos;
    std::vector< double > min_freqs;
    double min_score = 0.0;
    double max_score = 0.0;
    BOOST_FOREACH( const nucleo_dist & dist, dists )
    {
        double info = 0.0;
        double min_freq = 1.0;
        double max_freq = 0.0;
        for( unsigned i = 0; 4 != i; ++i )
        {
            const double fib = dist.get_freq( i );
            if( 0.0 > fib || fib > 1.0 ) {
                throw std::logic_error( BIOPSY_MAKE_STRING( "pssm_create(): Frequency is not in [0,1]: "<<fib ) );
            }
            min_freq = std::min( fib, min_freq );
            max_freq = std::max( fib, max_freq );
            if( 0.0 != fib )
            {
                info += fib * std::log( 4.0 * fib );
            }
        }
        //std::cout << info << "\n";
        min_score += min_freq * info;
        max_score += max_freq * info;
        if( info < 0. ) {
            throw std::logic_error( BIOPSY_MAKE_STRING( "pssm_create(): info < 0.0: "<<info ) );
        }
        infos.push_back( info );
        if( min_freq < 0. ) {
            throw std::logic_error( BIOPSY_MAKE_STRING( "pssm_create(): min_freq < 0.0: "<<info ) );
        }
        min_freqs.push_back( min_freq );
    }

    if( max_score == min_score ) {
        throw std::logic_error( BIOPSY_MAKE_STRING( "pssm_create(): max score == min score: "<<min_score ) );
    }
    if( max_score < min_score ) {
        throw std::logic_error( BIOPSY_MAKE_STRING( "pssm_create(): max score < min score: "<<max_score<<" < "<<min_score ) );
    }
    const double range = 1.0 / ( max_score - min_score );
    if( BIOPSY_ISNAN( range ) ) {
        throw std::logic_error( "pssm_create(): Range is too small to calculate" );
    }

    //now calculate the scores for each position
    pssm_ptr result( new pssm );
    for( unsigned pos = 0; dists.size() != pos; ++pos )
    {
        const nucleo_dist scores(
            infos[ pos ] * ( std::max( 0.0, dists[ pos ].get_freq( 0 ) - min_freqs[ pos ] ) ) * range,
            infos[ pos ] * ( std::max( 0.0, dists[ pos ].get_freq( 1 ) - min_freqs[ pos ] ) ) * range,
            infos[ pos ] * ( std::max( 0.0, dists[ pos ].get_freq( 2 ) - min_freqs[ pos ] ) ) * range,
            infos[ pos ] * ( std::max( 0.0, dists[ pos ].get_freq( 3 ) - min_freqs[ pos ] ) ) * range );
        for( unsigned b = 0; 4 != b; ++b ) {
            if( scores.get( b ) < 0.0 ) {
                throw std::logic_error( BIOPSY_MAKE_STRING( "pssm_create(): Have a negative score in PSSM: "<<scores.get( b ) ) );
            }
        }
        result->push_back( scores );
    }

    return result;
}

inline
unsigned
get_nucleo_index( const sequence::value_type & c )
{
    switch( c )
    {
    case 'a':
    case 'A':
        return 0;
    case 'c':
    case 'C':
        return 1;
    case 'g':
    case 'G':
        return 2;
    case 't':
    case 'T':
        return 3;
    }

    throw std::logic_error( BIOPSY_MAKE_STRING( "Not a nucleotide: \"" << c << "\"" ) );
}

double
score(
    const pssm & pssm,
    sequence::const_iterator s_begin )
{
    double score = 0.0;
    for( unsigned pos = 0; pssm.size() != pos; ++pos, ++s_begin )
    {
        score += ( pssm [ pos ] ).get( get_nucleo_index( *s_begin ) );
    }

    return score;
}

double
score_complement(
    const pssm & pssm,
    sequence::const_iterator s_begin )
{
    double score = 0.0;
    const unsigned size = pssm.size();
    for( unsigned pos = 0; size != pos; ++pos, ++s_begin )
    {
        score += ( pssm [ size - pos - 1 ] ).get( get_nucleo_index( nucleo_complement()( *s_begin ) ) );
    }

    return score;
}

double
score_pssm(
    pssm_ptr pssm,
    const sequence & s )
{
    if( pssm->size() > s.size() )
    {
        throw std::logic_error( "Pssm too large for sequence" );
    }

    return score( *pssm, s.begin() );
}

double
get_odds_ratio(
    double p_score_under_binding,
    double p_score_under_background )
{
    return pssm_parameters::singleton().binding_background_odds_prior * p_score_under_binding / p_score_under_background;
}

double
get_odds_ratio(
    double score,
    likelihoods_ptr _binding_dist,
    likelihoods_ptr _background_dist )
{
    const double p_score_under_binding = get_likelihood( _binding_dist, score );
    const double p_score_under_background = get_likelihood( _background_dist, score );

    return get_odds_ratio( p_score_under_binding, p_score_under_background );
}

double
get_p_binding(
    double odds_ratio )
{
    return odds_ratio / ( 1.0 + odds_ratio );
}

double
get_odds_ratio_from_p_binding(
    double p_binding )
{
    return p_binding / ( 1.0 - p_binding );
}

namespace detail {

enum pssm_type {
    PSSM_TRANSFAC,
    PSSM_CUSTOM,
    PSSM_UNKNOWN_TYPE
};

pssm_type get_pssm_type( const std::string & id );

struct PssmFromName
    : std::unary_function< std::string, pssm_info >
{
    const static regex transfac_re; /**< Regex to match TRANSFAC PSSM names. */
    const static regex custom_re; /**< Regex to match custom PSSM names. */
    pssm_info operator()( const std::string & name ) const
    {
        std::cout << "Creating pssm info for: " << name << "\n";

        nucleo_dist::vec counts;
        int n_sites = 0;

        switch( get_pssm_type( name ) )
        {
        case PSSM_TRANSFAC:
            {
                //look in transfac
                USING_BIO_NS;
                const TableLink link = parse_table_link_accession_number( name );

                switch( link.table_id )
                {
                case SITE_DATA:
                    {
                        Site::map_t::const_iterator s = BiobaseDb::singleton().get_sites().find( link );
                        if( BiobaseDb::singleton().get_sites().end() == s )
                        {
                            throw std::logic_error( BIOPSY_MAKE_STRING( "Could not find TRANSFAC PSSM id: " << name ) );
                        }
                        //std::cout << s->second->sequence << "\n";
                        BOOST_FOREACH( char c, s->second->sequence )
                        {
                            const nucleo_dist count = get_dist_for_iupac( c );
                            counts.push_back( count );
                        }
                        //    These are consensus sequences, so assume they are derived from
                        //    12 sites
                        n_sites = 12;
                    }
                    break;

                case MATRIX_DATA:
                    {
                        Matrix::map_t::const_iterator m = BiobaseDb::singleton().get_matrices().find( link );
                        if( BiobaseDb::singleton().get_matrices().end() == m )
                        {
                            throw std::logic_error( BIOPSY_MAKE_STRING( "Could not find TRANSFAC PSSM id: " << name ) );
                        }
                        BOOST_FOREACH( const PssmEntry & e, m->second->pssm )
                        {
                            const nucleo_dist count(
                                e.get_count( 'a' ),
                                e.get_count( 'c' ),
                                e.get_count( 'g' ),
                                e.get_count( 't' ) );
                            counts.push_back( count );
                        }
                        n_sites =  m->second->number_of_sites;
                    }
                    break;

                default:
                    throw std::logic_error( BIOPSY_MAKE_STRING( "Could not parse TRANSFAC PSSM id: " << name ) );
                }
            }
            break;

        case PSSM_CUSTOM:
            {
                //it looks like the name of a custom PSSM
                custom_pssm::ptr pssm = parse_custom_pssm_file( custom_pssm_filename( name ) ); //the name should be the PSSM id
                counts = pssm->counts;
                n_sites = 0;
            }
            break;

        default:
            throw std::logic_error( BIOPSY_MAKE_STRING( "Unknown PSSM name: " << name ) );
        }

        //add pseudo-counts
        double max_count = 0;
        double min_count = 999;
        double multiplier = 1;

        //    For distributions where the sum adds up to 1, divide the pseudo count by 100;
        //    Have to check for total less than 1.02 because of rounding errors in the TRANSFAC data
        //    where it is only given to 2 sig fig
        double total = 0;
        BOOST_FOREACH( nucleo_dist & c, counts )
        {
            double count = c.get_total();
            total += count;
            max_count  = max(max_count,count);
            min_count  = min(min_count,count);
        }

        if (n_sites) {
            double average_count = total/counts.size();
            //    IF the reported number of sites is out of kilter with the raw count
            //    data then adjust the pseudo count.
            if ((n_sites > (1.2 * max_count)) || (n_sites < (0.8 * min_count))) {
                multiplier = average_count/n_sites;
            }
        } else {
            if (max_count <= min_count * 1.05) {
                n_sites = max_count;
            } else if (max_count <= min_count + 1) {
                n_sites = max_count;
            }

            //Look to see if the data is non integer implying that we have the equivalent of data from
            //lots of sites.  If so adjust the pseudo count on the assumption that it is for 100
            //sites

            for (int i = 0; (i < int(counts.size())) && (multiplier == 1); i++ ) {

                const nucleo_dist & c = counts[i];
                for (int j = 0;j < 4;j++) {

                    double frac = fmod(c.get(j),1.0);
                    if ((frac > 0.1) && (frac < 0.9)) {
                        multiplier = 1.0f/ANALOGUE_SITE_EQUIVALENT;
                        n_sites = ANALOGUE_SITE_EQUIVALENT;
                        break;
                    }
                }
            }
        }

        double pseudo_count = pssm_parameters::singleton().pseudo_counts * multiplier;
        nucleo_dist::vec dists( counts + pseudo_count );
        pssm_ptr _pssm = create_pssm( dists );

        return pssm_info(
            counts,
            pseudo_count,
            n_sites,
            _pssm,
            calculate_likelihoods_under_pssm( _pssm, dists ),
            calculate_likelihoods_under_background( _pssm )
        );
    }
};

pssm_type
get_pssm_type( const std::string & id ) {
    if( regex_match( id, PssmFromName::transfac_re ) ) return PSSM_TRANSFAC;
    if( regex_match( id, PssmFromName::custom_re ) ) return PSSM_CUSTOM;
    return PSSM_UNKNOWN_TYPE;
}

const regex PssmFromName::transfac_re( "[MR][0-9][0-9][0-9][0-9][0-9]" );
const regex PssmFromName::custom_re( "([A-Z]+)-([0-9]+)" );

boost::filesystem::path
get_pssm_cache_serialised_file()
{
    using namespace boost::filesystem;
    return
        path( BIO_NS::BioEnvironment::singleton().get_serialised_dir() )
        / path( "pssm_cache.txt" );
}

/**
 * Our cache of PSSM information
 */
struct pssm_cache
    : BIO_NS::Cache< PssmFromName >
    , BIO_NS::Singleton< pssm_cache >
{
    void init_singleton()
    {
        BIO_NS::try_to_deserialise< false >( this->elements, get_pssm_cache_serialised_file() );

        //    We don't persist the dists because they are derivable from the counts
        BOOST_FOREACH(map_t::value_type & t,elements)
        {
            t.second._dists = t.second._counts + t.second._pseudo_count;
        }
    }

    void serialise() const
    {
        BIO_NS::serialise< false >( this->elements, get_pssm_cache_serialised_file() );
    }
};

} //namespace detail

likelihoods_ptr
calculate_likelihoods_under_pssm( pssm_ptr _pssm, const nucleo_dist::vec & dists ) {
    likelihoods_ptr under_pssm( new likelihoods( pssm_parameters::singleton().likelihoods_size ) );
    calculate_pssm_likelihoods( *_pssm, dists, *under_pssm, pssm_parameters::singleton().calculate_likelihoods_map_size, false );
    //std::cout << "Under pssm:\n";
    //BOOST_FOREACH( double p, *under_pssm )
    //{
    //    std::cout << p << "\n";
    //}
    return under_pssm;
}

likelihoods_ptr
calculate_likelihoods_under_background( pssm_ptr _pssm ) {
    likelihoods_ptr under_background( new likelihoods( pssm_parameters::singleton().likelihoods_size ) );
    const nucleo_dist::vec background_dist =
        boost::assign::list_of( uniform_nucleo_dist() ).repeat( _pssm->size() - 1, uniform_nucleo_dist() );
    calculate_pssm_likelihoods( *_pssm, background_dist, *under_background, pssm_parameters::singleton().calculate_likelihoods_map_size, false );
    //std::cout << "Under background:\n";
    //BOOST_FOREACH( double p, *under_background )
    //{
    //    std::cout << p << "\n";
    //}
    return under_background;
}

bool is_transfac_pssm( const std::string & pssm_name )
{
    return detail::PSSM_TRANSFAC == detail::get_pssm_type( pssm_name );
}

bool
add_pssm_to_cache( const std::string & name, const pssm_info & pssm ) {
    return detail::pssm_cache::singleton().insert( name, pssm );
}

void
save_pssm_cache_state( )
{
    detail::pssm_cache::singleton().serialise();
}

void
clear_pssm_cache( )
{
    detail::pssm_cache::singleton().clear();
}

const pssm_info &
get_pssm(
    const std::string & name )
{
    return detail::pssm_cache::singleton()( name );
}

std::string get_pssm_name( const std::string & id )
{
    using namespace detail;
    switch( get_pssm_type( id ) )
    {
    case PSSM_TRANSFAC: return BIO_NS::parse_table_link_accession_number( id ).get_name();
    case PSSM_CUSTOM: return get_custom_pssm( id )->name;
    default: throw std::logic_error( BIOPSY_MAKE_STRING( "Do not know about PSSM with id: " << id ) );
    }
}

std::string get_pssm_url( const std::string & id )
{
    using namespace detail;
    switch( get_pssm_type( id ) )
    {
    case PSSM_TRANSFAC: return BIO_NS::parse_table_link_accession_number( id ).get_url();
    case PSSM_CUSTOM: return get_custom_pssm( id )->url;
    default: throw std::logic_error( BIOPSY_MAKE_STRING( "Do not know about PSSM with id: " << id ) );
    }
}

typedef std::vector< double > likelihoods;

unsigned get_likelihood_index( unsigned size, double score )
{
    if (size == 0)
    {
        throw std::logic_error( "size == 0" );
    }

    if (0.0 > score)
    {
        throw std::logic_error( BIOPSY_MAKE_STRING( "Score < 0: " << score ) );
    }

    if (score * 2 * size > 2 * size + 1)
    {
        throw std::logic_error( BIOPSY_MAKE_STRING( "Score > 1 and a bit: " << score ) );
    }

    unsigned idx = ( unsigned )(score * size);
    if( size == idx ) //cater for a perfect match
    {
        --idx;
    }
    BOOST_ASSERT( 0 <= idx && idx < size );

    return idx;
}

double get_likelihood( likelihoods_ptr likelihoods, double score )
{
    const unsigned index = get_likelihood_index( likelihoods->size(), score );
    return ( *likelihoods )[ index ];
}

likelihoods_ptr
accumulate_likelihoods( likelihoods_ptr ls )
{
    const unsigned size = ls->size();
    likelihoods_ptr result( new likelihoods( size ) );
    double cum = 0.0;
    for( unsigned i = 0; size != i; ++i )
    {
        const unsigned idx = size - 1 - i;
        cum += ( *ls )[ idx ];
        ( *result )[ idx ] = cum;
    }
    return result;
}

double
normalise_likelihoods( likelihoods & result )
{
    const double sum = std::accumulate( result.begin(), result.end(), 0.0 );
    if( 0 >= sum )
    {
        throw std::logic_error( BIOPSY_MAKE_STRING( "Cannot normalise likelihood vector with sum < 0: " << sum ) );
    }

    BOOST_FOREACH( double & p, result )
    {
        p /= sum;
    }

    return sum;
}

void
calculate_pssm_likelihoods(
    const pssm & pssm,
    const nucleo_dist::vec & distribution,
    likelihoods & result,
    const size_t max_map_size,
    bool verbose )
{
    using namespace boost::numeric;

    /** Maps scores to probabilities. */
    typedef std::map< double, double > prob_map;
    typedef boost::scoped_ptr< prob_map > prob_map_ptr;

    if( pssm.size() != distribution.size() )
    {
        BOOST_FOREACH( const nucleo_dist & d, distribution )
        {
            std::cout << d.get( 0 ) << "," << d.get( 1 ) << "," << d.get( 2 ) << "," << d.get( 3 ) << "\n";
        }

        throw
            std::invalid_argument(
                BIOPSY_MAKE_STRING(
                    "pssm and distribution are different sizes: "
                    << pssm.size() << " != " << distribution.size() ) );
    }

    if( result.empty() )
    {
        throw std::invalid_argument( "result vector is empty" );
    }

    prob_map_ptr probs1( new prob_map );
    prob_map_ptr probs2( new prob_map );
    prob_map * last_probs = probs1.get(); //these alternate
    prob_map * new_probs = probs2.get();
    (*last_probs)[0.0] = std::log(1.0); //initialise with score of 0 has likelihood 1.0 at the start of the algorithm

    //for each row
    for( unsigned base = 0; pssm.size() != base; ++base )
    {
        new_probs->clear(); //start afresh

        //go to the next nucleotide if no observations
        if ( 0 == distribution[ base ].get_total() )
        {
            continue;
        }

        //if we have too many scores we need to quantise them
        while (last_probs->size() > max_map_size)
        {
            if( verbose )
            {
                std::cout << "Reducing map size from " <<  last_probs->size();
            }

            const double min_score = last_probs->begin()->first;
            const double max_score = last_probs->rbegin()->first;
            const double quantum = (max_score - min_score) / max_map_size;

            //for each pair of consecutive scores
            for( prob_map::iterator p1 = last_probs->begin(); last_probs->end() != p1; )
            {
                //get the next score
                prob_map::iterator p2 = p1;
                ++p2;
                if( last_probs->end() == p2 )
                {
                    break;
                }

                const double score1 = p1->first;
                const double score2 = p2->first;
                BOOST_ASSERT(score2 > score1); //problem if in wrong order...

                //are the two scores close?
                if( score2 - score1 < quantum )
                {
                    //we remove them both and insert a replacement for the average score that is as likely
                    //as both together
                    prob_map::iterator to_erase1 = p1;
                    prob_map::iterator to_erase2 = p2;

                    //insert the new value
                    const double prob1 = std::exp( p1->second );
                    const double prob2 = std::exp( p2->second );
                    const double prob_sum = prob1 + prob2;
#ifndef NDEBUG
                    const double relative_prob1 = prob1 / prob_sum;
#endif
                    const double relative_prob2 = prob2 / prob_sum;
                    const double avg_score = score1 + ( score2 - score1 ) * relative_prob2; //had to be careful here with floating point underflow
                    BOOST_ASSERT( score1 <= avg_score );
                    BOOST_ASSERT( avg_score <= score2 );

                    //move on before we insert the new value and erase the old
                    p1 = p2; ++p1;

                    //erase the old values
                    last_probs->erase(to_erase1);
                    last_probs->erase(to_erase2);

                    //insert the new value
                    const double log_prob_sum = std::log( prob_sum );
                    std::pair< prob_map::iterator, bool > insert_result =
                        last_probs->insert( prob_map::value_type( avg_score, log_prob_sum ) );

                    //did it actually insert?
                    if( ! insert_result.second )
                    {
                        //no - so update the existing element
                        insert_result.first->second =
                            std::log( std::exp( insert_result.first->second ) + std::exp( log_prob_sum ) );
                    }
                }
                else
                {
                    //move on
                    p1 = p2;
                }
            }

            if (verbose)
            {
                std::cout << " to " <<  last_probs->size() << std::endl;
            }

        } //while map is too large

        //for each nucleotide
        for( unsigned i = 0; 4 != i; ++i )
        {
            //likelihood in the pssm for this nucleotide in this position? Use a psuedo count of 1
            const double prob_this_nucleo = distribution[ base ].get_freq( i );

            //if none, cannot contribute to the total probabilities
            if( 0.0 == prob_this_nucleo )
            {
                continue;
            }
            //BOOST_ASSERT(0 != entry->get_count(*n)); - this was only true before pseudo counts used

            const double log_prob_this_nucleo = std::log( prob_this_nucleo );
            const double score_this_nucleo = pssm[ base ].get( i );

            //for each score we have already achieved
            for( prob_map::const_iterator p = last_probs->begin(); last_probs->end() != p; ++p )
            {
                const double new_score = p->first + score_this_nucleo;
                const double new_log_likelihood = p->second + log_prob_this_nucleo;

                //update the new probability map

                //first try to insert
                std::pair< prob_map::iterator, bool > insert_result =
                    new_probs->insert( prob_map::value_type( new_score, new_log_likelihood ) );

                //did it actually insert?
                if( ! insert_result.second )
                {
                    //no - so update the existing element
                    insert_result.first->second =
                        std::log( std::exp( insert_result.first->second ) + std::exp( new_log_likelihood ) );
                }
            }

        } //for each nucleotide

        if( verbose )
        {
            //for debugging
            double total_prob = 0.0;
            for( prob_map::const_iterator p = new_probs->begin(); new_probs->end() != p; ++p )
            {
                total_prob += std::exp( p->second );
            }
            std::cout
                << "Base " << base << " has prob map size " << new_probs->size()
                << " and total probability: " << total_prob
                << std::endl;

        }

        std::swap( new_probs, last_probs );

    } //for each row

    //initialise the result vector
    std::fill( result.begin(), result.end(), 0.0 );

    //for each score in the last_probs map, place in the likelihoods vector
    for( prob_map::const_iterator p = last_probs->begin(); last_probs->end() != p; ++p )
    {
        //normalise the score
        BOOST_ASSERT( in( p->first, interval< double >( -0.0001, 1.0001 ) ) );
        const double score = std::min( 1.0, std::max( 0.0, p->first ) );

        //what is the probability
        const double log_likelihood = p->second;
        const double prob = std::exp( log_likelihood );

        result[ get_likelihood_index( result.size(), score ) ] += prob;
    }

    normalise_likelihoods( result );
}

double
get_p_binding_using_p_value(
    double score,
    likelihoods_ptr likelihoods )
{
    const unsigned idx = get_likelihood_index( likelihoods->size(), score );
    const double likelihood_under_background = ( *likelihoods )[ idx ];
    const double likelihood_under_binding = 1.0 / double( likelihoods->size() );
    return
        get_p_binding(
            get_odds_ratio(
                likelihood_under_binding,
                likelihood_under_background ) );
}

double
get_p_binding_from_score(
    const pssm_info & p,
    double score )
{
    const pssm_parameters & params = pssm_parameters::singleton();
    const bool use_cumulative_dists = params.use_cumulative_dists;
    if( params.use_p_value )
    {
        return
            get_p_binding_using_p_value(
                score,
                p.get_dist( false, use_cumulative_dists ) );
    }
    else
    {
        return
            get_p_binding(
                get_odds_ratio(
                    score,
                    p.get_dist( true, use_cumulative_dists ),
                    p.get_dist( false, use_cumulative_dists ) ) );
    }
}

const pssm_info::matrix_t &
pssm_info::get_log_likelihoods() const {

    // check whether we have calculated them
    if( ! _log_likelihoods ) {
        _log_likelihoods.reset( new matrix_t( boost::extents[ boost::size( _dists ) ][ 4 ] ) );
        for( size_t i = 0; _dists.size() != i; ++i ) {
            for( size_t b = 0; 4 != b; ++b ) {
                ( *_log_likelihoods )[ i ][ b ] = std::log( _dists[ i ].get_freq( b ) );
            }
        }
    }

    return *_log_likelihoods;
}

double
get_p_binding_on_sequence(
    const pssm_info & p,
    sequence::const_iterator s_begin )
{
    return get_p_binding_from_score(
        p,
        score( *( p._pssm ), s_begin ) );
}

/**
Scores a pssm on the reverse complement of the sequence and adjusts for distributions.
*/
double
get_p_binding_on_reverse_complement(
    const pssm_info & p,
    sequence::const_iterator s_begin )
{
    return
        get_p_binding_from_score(
            p,
            score_complement( *( p._pssm ), s_begin ) );
}

pssm_info::pssm_info(
    const nucleo_dist::vec & counts,
    double pseudo_count,
    int number_of_sites,
    pssm_ptr p,
    likelihoods_ptr binding_dist,
    likelihoods_ptr background_dist )
    : _counts( counts )
    , _dists( counts + pseudo_count )
    , _pseudo_count( pseudo_count )
    , _number_of_sites( number_of_sites )
    , _pssm( p )
    , _binding_dist( binding_dist )
    , _background_dist( background_dist )
{
}

likelihoods_ptr
pssm_info::get_dist( bool binding, bool cumulative ) const
{
    if( cumulative )
    {
        if( binding )
        {
            if( ! _cumulative_binding_dist )
            {
                _cumulative_binding_dist = accumulate_likelihoods( get_dist( binding, false ) );
            }
            return _cumulative_binding_dist;
        }
        else
        {
            if( ! _cumulative_background_dist )
            {
                _cumulative_background_dist = accumulate_likelihoods( get_dist( binding, false ) );
            }
            return _cumulative_background_dist;
        }
    }
    else
    {
        if( binding )
        {
            if( ! _binding_dist )
            {
                throw std::logic_error( "Do not have binding distribution." );
            }
            return _binding_dist;
        }
        else
        {
            if( ! _background_dist )
            {
                throw std::logic_error( "Do not have background distribution." );
            }
            return _background_dist;
        }
    }
}

/** Convert a biopsy pssm to a bio pssm. */
BIO_NS::Pssm make_transfac_pssm( const pssm & _pssm )
{
    BIO_NS::Pssm result;
    BOOST_FOREACH( const nucleo_dist & dist, _pssm )
        result.push_back( BIO_NS::PssmEntry( (BIO_NS::float_t)(10*dist.get(0)),(BIO_NS::float_t)(10*dist.get(1)),
         (BIO_NS::float_t)(10*dist.get(2)), (BIO_NS::float_t)(10*dist.get(3))) );
    return result;
}

} //namespace biopsy


text:
/*global OdysseyEventHandler*/
goog.require('Odyssey.Events.EventHandler');
goog.provide('Odyssey.Events.EventDispatcher');
Odyssey.Events.EventDispatcher = (function () {
    "use strict";
    /**
     * @constructor
     */
    function OdysseyEventDispatcher() {
        this.events = {};
    }
    OdysseyEventDispatcher.prototype.toJSON = function () {
        // Do not serialize this object, as it is a container for functions.
        return;
    };
    OdysseyEventDispatcher.prototype.parent = null;
    OdysseyEventDispatcher.prototype.getParentEventHandler = function () {
        return this.parent;
    };
    OdysseyEventDispatcher.prototype.setParentEventHandler = function (parent) {
        this.parent = parent;
    };
    OdysseyEventDispatcher.prototype.getEventHandler = function (type) {
        if (!this.events.hasOwnProperty(type)) {
            this.events[type] = new Odyssey.Events.EventHandler(type);
        }
        return this.events[type];
    };

    OdysseyEventDispatcher.prototype.dispatch = function (ctx, e) {
        var handler = this.getEventHandler(e.type), parent;
        handler.fire(ctx, e);
        if (!e.propagationStopped) {
            // Bubble up to the parent.
            parent = this.getParentEventHandler();
            if (parent !== null) {
                parent.dispatch(ctx, e);
            }
        }
    };

    OdysseyEventDispatcher.prototype.addListener = function (type, fn) {
        var handler = this.getEventHandler(type);
        handler.addListener(fn);
    };

    OdysseyEventDispatcher.prototype.removeListener = function (type, fn) {
        var handler = this.getEventHandler(type);
        handler.removeListener(fn);
    };

    return OdysseyEventDispatcher;
}());


text:
using MaintenanceTracker.Domain;
using NUnit.Framework;
using System.Linq;
using System.Collections.Generic;
using MaintenanceTracker.Domain.Model;
using MaintenanceTracker.Tests.Domain.Context;

namespace MaintenanceTracker.Tests.Web
{
    [TestFixture]
    public class VehicleControllerTests
    {
        private IMaintenanceTrackerContext _context;

        public VehicleControllerTests()
        {
            _context = new MockContext();
            _context.Users.Add(new User
            {
                Id = 1,
                Username = "test"
            });

            var make = new Make
            {
                Id = 1,
                Name = "make"
            };

            var model = new Model
            {
                Id = 1,
                Name = "model",
                Make = make
            };

            var user = new User
            {
                Id = 1,
                Email = "Test"
            };

            make.Models = new List<Model> {model};

            _context.Models.Add(model);
            _context.Makes.Add(make);

            _context.Vehicles.Add(new Vehicle
            {
                Id = 1,
                Year = "2015",
                Kilometers = 100,
                Model = model,
                User = user
            });
            _context.Vehicles.Add(new Vehicle
            {
                Id = 2,
                Year = "2014",
                Kilometers = 1000,
                Model = model,
                User = user
            });

            user.Vehicles = new List<Vehicle>();
            user.Vehicles.Add(_context.Vehicles.First());
            user.Vehicles.Add(_context.Vehicles.Last());
        }

        [Test]
        public void Get_Returns_Vehicles_For_User_Only()
        {
        }

        [Test]
        public void Gets_All_Vehicles()
        {

        }

        [Test]
        public void Gets_Individual_Vehicle()
        {

        }

        [Test]
        public void Creates_New_Vehicle()
        {

        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="Encoding">
    <file url="file://$PROJECT_DIR$/app/src/main/java/joseangelpardo/volleyandroidstudyjam/MySocialMediaSingleton.java" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$/app/src/main/java/joseangelpardo/volleyandroidstudyjam/PostAdapter.java" charset="UTF-8" />
  </component>
</project>


text:
require 'rubygems'
require 'csv-mapper'
require 'active_record'
require 'sqlite3'
include CsvMapper

ActiveRecord::Base.establish_connection(
    :adapter => "sqlite3",
    :database => "ptc_datamapper.sqlite3"
)

ActiveRecord::Schema.define do
    create_table :people do |t|
        t.column :input_id, :string
        t.column :first_name, :string
        t.column :last_name, :string
        t.column :address, :string
        t.column :city, :string
        t.column :state, :string
        t.column :zip, :string
        t.column :email, :string
        t.column :birth_month, :string
        t.column :birth_day, :string
        t.column :birth_year, :string
        t.column :ptc, :string
        t.column :date_created, :string
    end
end

class Mapper
    def import_data(importfile)
        @importfile = importfile
        @persons = import_from_file
    end

    def export_data(exportfile)
        @exportfile = exportfile
        export_to_file
    end

    def import_from_file
        results = import(@importfile) do
            map_to Person
#           after_row lambda{|row, person| person.save}

            start_at_row 0
            [input_id, first_name, last_name, address, city, state, zip, email, birth_month, birth_day, birth_year, ptc, date_created]
        end
        results
    end

    def get_cr_row
        'CR|6|9999000024542||9289560|CLEARBNS|||7020||||||20120530||1325|||||||||'
    end

    def format_row(data)
        row = ''
        data.each {|r| row = row.to_s + "#{r}|"}
        row = row[0..-2]
    end

    def print_result
        @persons.each do |p|
            puts format_row(p.ptc_data)
        end
    end

    def export_to_file
        File.open(@exportfile,'w') do |export|
            export.puts get_cr_row
            @persons.each do |p|
                export.puts format_row(p.na_data)
                export.puts format_row(p.ptc_data) if p.ptc
            end
        end
    end
end

class Person < ActiveRecord::Base
    def ptc_data
        value_array = ['PTC', 6, self.input_id, '1325', '', '', 'Y','Y', '', self.date_created]
    end

    def na_data
        value_array = ['NA', 6, self.input_id, '', '', '', '', '', self.first_name, '', self.last_name, '', self.address, '', '', self.city, self.state, self.zip, '', '', '', '', '', '', '', '', self.email, '', '', '', '', self.date_created.gsub!(' ','|') ]
    end
end

importfile = ARGV[0]
exportfile = ARGV[1]
start_time = Time.now.to_f * 1000
mapper = Mapper.new
mapper.import_data(importfile)
mapper.export_data(exportfile)
end_time = Time.now.to_f * 1000
puts 'File save successfully!'
puts 'Time used:' << (end_time - start_time).to_s << 'ms'


text:
    <input type="radio" name="useNewDeck" value="deckSelectionType.EXISTING" autocomplete="off"
           (change)="onDeckSelectTypeChange(deckSelectionType.EXISTING)"> Existing

    <input type="radio" name="useNewDeck" value="deckSelectionType.IMPORT" autocomplete="off"
           (change)="onDeckSelectTypeChange(deckSelectionType.IMPORT)"> Import

    <input type="radio" name="useNewDeck" value="deckSelectionType.NEW" autocomplete="off"
           (change)="onDeckSelectTypeChange(deckSelectionType.NEW)"> New

    <agot-existing-deck-selector [playerId]="playerId" [existingDeck]="existingDeck"
                                 (selectDeck)="onExistingDeckUpdate($event)"></agot-existing-deck-selector>

      <button type="button" (click)="onExistingDeckSelect()" class="btn btn-success" [disabled]="!existingDeck">
        {{ creating ? 'Add Player' : 'Update' }}
      </button>

    <agot-deck-import-form (updateDeck)="onImportedDeckSelect($event)" [creating]="creating"></agot-deck-import-form>

    <agot-deck-edit-form (updateDeck)="onNewDeckSelect($event)"
                         [deck]="editDeck" [creating]="creating"></agot-deck-edit-form>

  ThronesDB version
  <input type="number" class="form-control" [(ngModel)]="deckVersion" inputmode="numeric">


text:
using MediaBrowser.Controller.Plugins;

namespace MediaBrowser.Plugins.SoundCloud
{
    public class EntryPoint : IServerEntryPoint
    {
        public void Run()
        {
            var username = Plugin.Instance.Configuration.Username;
            var password = Plugin.Instance.Configuration.PwData;

            if (!string.IsNullOrWhiteSpace(username) && !string.IsNullOrWhiteSpace(password))
            {
                Plugin.Instance.SoundCloudClient.Authenticate();
            }
        }

        public void Dispose()
        {
        }
    }
}


text:
@import url(http://fonts.googleapis.com/css?family=Nova+Square);
@import url(http://fonts.googleapis.com/css?family=Lato:300);
body{
  font-family: 'Lato', sans-serif;
}
.container{
  border: solid 10px #98ba3f;
  padding: 4px;
  margin: 3px;
  border-radius: 8px;
  background-color: #ff9;
  display: inline-block;
  width: 200px;
  vertical-align: top;
}

::-webkit-input-placeholder { color:#fff; }
::-moz-placeholder { color:#fff; }
:-ms-input-placeholder { color:#fff; }
input:-moz-placeholder { color:#fff; }

.container p{
  margin: 6px;
}
h1{
  font-family: 'Nova Square', cursive;
}
.container h1{
  font-family: 'Nova Square', cursive;
  margin: 6px;
  border-bottom: 10px solid #98ba3f;
}
.input {
  background-color: #98ba3f;
  border: 0px;
  border-radius: 8px;
  padding: 3px;
  margin: 3px;
  font-family: Arial;
  font-size: 16px;
  text-decoration: none;
  color: #ffffff;
  font-family: 'Lato', sans-serif;
}
.button{
  border: solid 1px #98ba3f;
  height: 16px;
  border-radius: 5px;
  margin: 6px;
  padding: 3px;
  text-align: center;
  float: left;
  font-family: Arial;
  font-size: 16px;
  text-decoration: none;
  color: #ffffff;
  background-color: #98ba3f;
}

.button:hover {
  background-color: #245191;
    font-family: 'Lato', sans-serif;
}

strong{
  font-family: 'Nova Square', cursive;
  font-size: 20px;
}
.row{
}

.status{
  display: block;
}