text:
package com.umeng.comm.ui.presenter.impl;

import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.TextUtils;

import com.umeng.comm.core.beans.CommConfig;
import com.umeng.comm.core.beans.FeedItem;
import com.umeng.comm.core.constants.Constants;
import com.umeng.comm.core.constants.ErrorCode;
import com.umeng.comm.core.listeners.Listeners.FetchListener;
import com.umeng.comm.core.listeners.Listeners.OnResultListener;
import com.umeng.comm.core.listeners.Listeners.SimpleFetchListener;
import com.umeng.comm.core.nets.responses.FeedsResponse;
import com.umeng.comm.core.nets.uitls.NetworkUtils;
import com.umeng.comm.ui.mvpview.MvpFeedView;
import com.umeng.comm.ui.utils.Filter;

/**
 * Feed列表相关的Presenter,该Presenter从网络、数据库中读取Feed,如果数据是从网络上获取的,那么需要将数据存储到数据库中。
 * 在获取数据后会通过MvpFeedView的{@link MvpFeedView#getBindDataSource()}
 * 函数获取到列表的数据集,然后对新获取的数据进行去重、排序,再将新获取到的数据添加到列表的数据集合中,最后调用
 * {@link MvpFeedView#notifyDataSetChanged()} 函数更新对应的列表视图。
 *
 * @author mrsimple
 */
public class FeedListPresenter extends BaseFeedPresenter {
    protected MvpFeedView mFeedView;
    protected String mNextPageUrl;
    private Filter<FeedItem> mFeedFilter;
    private boolean isRegisterLoginBroadcast = false;
    private boolean isAttached = false;
    private OnResultListener mOnResultListener; // feed更新时回调,用于提示

    /**
     * 是否需要清空数据库缓存的标志位
     */
    protected AtomicBoolean isNeedRemoveOldFeeds = new AtomicBoolean(true);

    public FeedListPresenter(MvpFeedView view) {
        this(view, false);
    }

    public FeedListPresenter(MvpFeedView view, boolean isRegisterLoginBroadcast) {
        mFeedView = view;
        this.isRegisterLoginBroadcast = isRegisterLoginBroadcast;
    }

    /**
     * 设置回调

     *
     * @param listener
     */
    public void setOnResultListener(OnResultListener listener) {
        this.mOnResultListener = listener;
    }

    @Override
    public void loadDataFromServer() {
        mCommunitySDK.fetchLastestFeeds(mRefreshListener);
    }

    /**
     * 下拉数据的Listener
     */
    protected FetchListener<FeedsResponse> mRefreshListener = new SimpleFetchListener<FeedsResponse>() {

        @Override
        public void onStart() {
            mFeedView.onRefreshStart();
        }

        // [注意]:mFeedView.onRefreshEnd方法不可提前统一调用,该方法会被判断是否显示空视图的逻辑
        @Override
        public void onComplete(FeedsResponse response) {
            // 根据response进行Toast
            if (NetworkUtils.handleResponseAll(response)) {
                mFeedView.onRefreshEnd();
                return;
            }

            final List<FeedItem> newFeedItems = response.result;
            // 对于下拉刷新,仅在下一个地址为空(首次刷新)时设置下一页地址
            if (TextUtils.isEmpty(mNextPageUrl) && isNeedRemoveOldFeeds.get()) {
                mNextPageUrl = response.nextPageUrl;
            }
            beforeDeliveryFeeds(response);
            // 更新数据
            int news = addFeedItemsToHeader(newFeedItems);
            if (mOnResultListener != null) {
                mOnResultListener.onResult(news);
            }
            // 保存加载的数据。如果该数据存在于DB中,则替换成最新的,否则Insert一条新纪录
            saveDataToDB(newFeedItems);
            mFeedView.onRefreshEnd();
        }
    };

    protected void beforeDeliveryFeeds(FeedsResponse response) {
        // 第一次从网络上下拉到数据,那么则清除从数据库中加载进来的数据,避免下一页地址出问题.
        clearFeedDBCache();
    }

    /**
     * 第一次从网上下拉到数据时清空数据库中的缓存,然后会调用{@see saveFeedsToDB}将新的数据存储到缓存中
     *
     * @param helper
     */
    private void clearFeedDBCache() {
        if (isNeedRemoveOldFeeds.get()) {
            // 清空原来的缓存数据
            // mFeedView.clearListView(); //
            // 此时暂时不清空Adapter数据,确保手机显示的数据是集为:cache+server端数据
            // 清空数据库中的缓存数据
            mDatabaseAPI.getFeedDBAPI().deleteAllFeedsFromDB();
            if (!TextUtils.isEmpty(CommConfig.getConfig().loginedUser.id)) {
                isNeedRemoveOldFeeds.set(false);
            }
        }
    }

    public void fetchNextPageData() {
        if (TextUtils.isEmpty(mNextPageUrl)) {
            mFeedView.onRefreshEnd();
            return;
        }

        mCommunitySDK.fetchNextPageData(mNextPageUrl,
                FeedsResponse.class, new SimpleFetchListener<FeedsResponse>() {

                    @Override
                    public void onComplete(FeedsResponse response) {
                        mFeedView.onRefreshEnd();
                        // 根据response进行Toast
                        if (NetworkUtils.handleResponseAll(response)) {
                            if (response.errCode == ErrorCode.NO_ERROR) { // 如果返回的数据是空,则需要置下一页地址为空
                                mNextPageUrl = "";
                            }
                            return;
                        }

                        mNextPageUrl = response.nextPageUrl;
                        // 去掉重复的feed
                        final List<FeedItem> feedItems = getNewFeedItems(response.result);
                        if (feedItems != null && feedItems.size() > 0) {
                            // 追加数据
                            appendFeedItems(feedItems,false);
                            saveDataToDB(feedItems);
                        }
                    }
                });
    }

    /**
     * 去重并更新adapter的数据,追加到后面。

     *
     * @param feedItems
     */
    protected List<FeedItem> appendFeedItems(List<FeedItem> feedItems,boolean fromDB) {
        List<FeedItem> newFeeds = null;
        synchronized (this) {
            newFeeds = getNewFeedItems(feedItems);
            if (newFeeds != null && newFeeds.size() > 0) {
                // 添加到listview中
                mFeedView.getBindDataSource().addAll(newFeeds);
                sortFeedItems(mFeedView.getBindDataSource());
                mFeedView.notifyDataSetChanged();
            }
        }
        return newFeeds;
    }

    /**
     * 过滤数据

     *
     * @return
     */
    protected List<FeedItem> filteFeeds(List<FeedItem> list) {
        List<FeedItem> destList = mFeedFilter != null ? mFeedFilter.doFilte(list) : list;
        // 移除status>=2的feed,具体值得的含义参考文档说明
        Iterator<FeedItem> iterator = destList.iterator();
        while (iterator.hasNext()) {
            FeedItem item = iterator.next();
            if (item.status >= FeedItem.STATUS_SPAM) {
                iterator.remove();
            }
        }
        return destList;
    }

    /**
     * 移除存在的feed,获取最新的feed

     *
     * @param feedItems 最新的feed(待被移除)
     * @return
     */
    private List<FeedItem> getNewFeedItems(List<FeedItem> feedItems) {
        // 去掉在本地已经存在的feeds[此时应该先从adapter中移除数据,确保加载下来的是最新的数据]
        // feedItems.removeAll(mFeedView.getAdapterDataSet());
        mFeedView.getBindDataSource().removeAll(feedItems);
        // 过滤数据
        return filteFeeds(feedItems);
    }

    /**
     * 去重并更新adapter的数据,将数据插到前边。

     *
     * @param feedItems
     */
    protected int addFeedItemsToHeader(List<FeedItem> feedItems) {
        feedItems = filteFeeds(feedItems);
        List<FeedItem> olds = mFeedView.getBindDataSource();
        int size = olds.size();
        olds.removeAll(feedItems);
        olds.addAll(0, feedItems);
        int news = olds.size() - size;
        sortFeedItems(olds);
        mFeedView.notifyDataSetChanged();
        return news;
    }

    public void sortFeedItems(List<FeedItem> items) {
        // 所有feed都按照feed的时间降序排列。【该代码避免用户首次登录时,推荐的feed时间较新,但是管理员的帖子较旧的情况】
        Collections.sort(items, mComparator);
    }

    /**
     * 获取所有的feed
     */
    @Override
    public void loadDataFromDB() {
        mDatabaseAPI.getFeedDBAPI().loadFeedsFromDB(mDbFetchListener);
    }

    /**
     * 获取某个用户的feed

     *
     * @param uid
     */
    // 注意这里不能重构
    public void loadFeedsFromDB(String uid) {
        mDatabaseAPI.getFeedDBAPI().loadFeedsFromDB(uid, mDbFetchListener);
    }

    @Override
    public void attach(Context context) {
        super.attach(context);
        if (isRegisterLoginBroadcast && !isAttached) {
            registerLoginSuccessBroadcast();
            isAttached = true;
        }
    }

    /**
     * 用于数据库的SimpleFetchListener
     */
    protected SimpleFetchListener<List<FeedItem>> mDbFetchListener =
            new SimpleFetchListener<List<FeedItem>>() {

                @Override
                public void onComplete(List<FeedItem> response) {
                    appendFeedItems(response,true);
                }
            };

    protected Comparator<FeedItem> mComparator = new Comparator<FeedItem>() {

        @Override
        public int compare(FeedItem lhs, FeedItem rhs) {
            int isTop = rhs.isTop - lhs.isTop;
            return isTop != 0 ? isTop : rhs.publishTime.compareTo(lhs.publishTime);
        }
    };

    /**
     * 注册登录成功时的广播

     */
    private void registerLoginSuccessBroadcast() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constants.ACTION_LOGIN_SUCCESS);
        // LocalBroadcastManager.getInstance(mContext).registerReceiver(mLoginReceiver,
        // filter);
        mContext.registerReceiver(mLoginReceiver, filter);
    }

    private BroadcastReceiver mLoginReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            fetchDataFromServerByLogin();
        }
    };

    /**
     * 从server加载数据。【注意:该接口仅仅在登录成功的时候调用,需要对此种情况有特殊的逻辑处理】

     */
    protected void fetchDataFromServerByLogin() {
        mCommunitySDK.fetchLastestFeeds(mLoginRefreshListener);
    }

    protected FetchListener<FeedsResponse> mLoginRefreshListener = new FetchListener<FeedsResponse>() {

        @Override
        public void onStart() {

        }

        @Override
        public void onComplete(FeedsResponse response) {
            // 首先清理未登录时存储的数据
            mDatabaseAPI.getFeedDBAPI().deleteAllFeedsFromDB();
            // 清理Adapter中的数据
            mFeedView.getBindDataSource().clear();
            if (NetworkUtils.handleResponseAll(response)) {
                mFeedView.onRefreshEnd();
                return;
            }
            // 更新下一页地址
            mNextPageUrl = response.nextPageUrl;
            if (!TextUtils.isEmpty(mNextPageUrl)) {
                isNeedRemoveOldFeeds.set(false);
            }
            beforeDeliveryFeeds(response);
            mFeedView.getBindDataSource().addAll(response.result);
            mFeedView.notifyDataSetChanged();
            // 保存加载的数据。如果该数据存在于DB中,则替换成最新的,否则Insert一条新纪录
            saveDataToDB(response.result);
            mFeedView.onRefreshEnd();
        }
    };

}


text:
<?xml version="1.0" encoding="UTF-8"?>

<recipeml version="0.5">
  <recipe>
    <head>
      <title>Basic Bread Crumbs</title>
      <categories>
        <cat>Misc</cat>
        <cat>Lite</cat></categories>
      <yield>3</yield></head>
    <ingredients>
      <ing>
        <amt>
          <qty>6</qty>
          <unit>slices</unit></amt>
        <item>Wonder Light Reduced Calorie Fat-Free bread</item></ing>
      <ing>
        <amt>
          <qty/>
          <unit/></amt>
        <item>Butter Flavor Pam no stick cooking spray</item></ing></ingredients>
    <directions>
      <step>     Spray both sides of each bread slice with Pam and bake in a 250~ oven
  until toasted.  Turn slices over and toast until brown and dry. Crumb bread
  in food processor. Store in air-tight container in freezer and use as
  needed.   Makes 3 (1 cup) servings.

     Per Serving.  0g fat, 80 calories, 0% fat, 2.6g protein, 0.5g carb, 0mg
  sodium, 0 mg cholesterol.

     From.  The Lite Switch, June McLean Jeter.

  From Gemini's MASSIVE MealMaster collection at www.synapse.com/~gemini

</step></directions></recipe></recipeml>

redpajama_set_name: RedPajamaGithub


text:
<!doctype html>

    <meta charset="utf-8">
    <title>d3 block chart</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width">
    <link rel="shortcut icon" href="/favicon.ico">

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

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

D3 Block Chart

One Chart

      <button class="btn btn-default" type="submit" id="btn-add">Add</button>
      <button class="btn btn-default" type="submit" id="btn-remove">Remove</button>

Several Charts

by Pablo Navarro Castillo


text:
/**
 * Created by shuyi.wu on 2015/4/2.
 */
import MyScroll from './myScroll';
import {vendorPrefixJsStyle} from './util/vendorPrefix';

class MyEasyScroll {
    constructor(content, options) {
        this.content = content;
        this.container = content.parentNode;
        this.options = options || {};

        // create Scroller instance
        var that = this;
        this.scroller = new MyScroll(function (left, top, zoom) {
            that.render(left, top, zoom);
        }, options);

        this.render = (function () {
            var vendorPrefix = MyEasyScroll.vendorPrefix = vendorPrefixJsStyle;

            var helperElem = document.createElement('div');

            var perspectiveProperty = vendorPrefix + 'Perspective';
            var transformProperty = vendorPrefix + 'Transform';

            if (helperElem.style[perspectiveProperty] !== undefined) {

                return function (left, top, zoom) {
                    this.content.style[transformProperty] = 'translate3d(' + (-left) + 'px,' + (-top) + 'px,0) scale(' + zoom + ')';
                };

            } else if (helperElem.style[transformProperty] !== undefined) {

                return function (left, top, zoom) {
                    this.content.style[transformProperty] = 'translate(' + (-left) + 'px,' + (-top) + 'px) scale(' + zoom + ')';
                };

            } else {

                return function (left, top, zoom) {
                    this.content.style.marginLeft = left ? (-left / zoom) + 'px' : '';
                    this.content.style.marginTop = top ? (-top / zoom) + 'px' : '';
                    this.content.style.zoom = zoom || '';
                };
            }
        })();

        // bind events
        this.bindEvents();

        // the content element needs a correct transform origin for zooming
        this.content.style[MyEasyScroll.vendorPrefix + 'TransformOrigin'] = 'left top';

        // reflow for the first time
        this.reflow();
    }

    reflow() {

        // set the right scroller dimensions
        this.scroller.setDimensions(this.container.clientWidth, this.container.clientHeight, this.content.offsetWidth, this.content.offsetHeight);

        // refresh the position for zooming purposes
        var rect = this.container.getBoundingClientRect();
        this.scroller.setPosition(rect.left + this.container.clientLeft, rect.top + this.container.clientTop);

    }

    bindEvents() {

        var that = this;

        // reflow handling
        window.addEventListener('resize', function () {
            that.reflow();
        }, false);

        // touch devices bind touch events
        if ('ontouchstart' in window) {

            this.container.addEventListener('touchstart', function (e) {

                // Don't react if initial down happens on a form element
                if (e.touches[0] && e.touches[0].target && e.touches[0].target.tagName.match(/input|textarea|select/i)) {
                    return;
                }

                that.scroller.doTouchStart(e.touches, e.timeStamp);
                e.preventDefault();

            }, false);

            document.addEventListener('touchmove', function (e) {
                that.scroller.doTouchMove(e.touches, e.timeStamp, e.scale);
            }, false);

            document.addEventListener('touchend', function (e) {
                that.scroller.doTouchEnd(e.timeStamp);
            }, false);

            document.addEventListener('touchcancel', function (e) {
                that.scroller.doTouchEnd(e.timeStamp);
            }, false);

            // non-touch bind mouse events
        } else {

            var mousedown = false;

            this.container.addEventListener('mousedown', function (e) {

                if (e.target.tagName.match(/input|textarea|select/i)) {
                    return;
                }

                that.scroller.doTouchStart([{
                    pageX: e.pageX,
                    pageY: e.pageY
                }], e.timeStamp);

                mousedown = true;
                e.preventDefault();

            }, false);

            document.addEventListener('mousemove', function (e) {

                if (!mousedown) {
                    return;
                }

                that.scroller.doTouchMove([{
                    pageX: e.pageX,
                    pageY: e.pageY
                }], e.timeStamp);

                mousedown = true;

            }, false);

            document.addEventListener('mouseup', function (e) {

                if (!mousedown) {
                    return;
                }

                that.scroller.doTouchEnd(e.timeStamp);

                mousedown = false;

            }, false);

            this.container.addEventListener('mousewheel', function (e) {
                if (that.options.zooming) {
                    that.scroller.doMouseZoom(e.wheelDelta, e.timeStamp, e.pageX, e.pageY);
                    e.preventDefault();
                }
            }, false);

        }

    }
}

export default MyEasyScroll;
window.MyEasyScroll = MyEasyScroll;


text:
@class WebScriptObject, WebView, WebFrame;

@interface UIApplication (Apple)
- (void) applicationOpenURL:(NSURL *)url;
@end

@interface NSString (UIKit)
- (NSString *) stringByAddingPercentEscapes;
@end

@interface UIScroller : UIView
- (CGSize) contentSize;
- (void) setOffset:(CGPoint)offset;
@end

@interface UIWebDocumentView : UIView
- (WebView *) webView;
@end

@interface UIView (Apple)
- (UIScroller *) _scroller;
@end

@interface DOMCSSStyleSheet : NSObject
- (int) addRule:(NSString *)rule style:(NSString *)style index:(unsigned)index;
- (void) deleteRule:(unsigned)index;
@end

@interface DOMStyleSheetList : NSObject
- (DOMCSSStyleSheet *) item:(unsigned)index;
@end

@interface DOMDocument : NSObject
- (NSString *) selectedStylesheetSet;
- (void) setSelectedStylesheetSet:(NSString *)value;
- (DOMStyleSheetList *) styleSheets;
@end

@interface NSURL (Apple)
- (BOOL) isSpringboardHandledURL;
@end

@interface UIWebView (Apple)
- (UIWebDocumentView *) _documentView;
- (void) setDataDetectorTypes:(NSInteger)types;
- (void) _setDrawInWebThread:(BOOL)draw;
- (UIScrollView *) _scrollView;
- (UIScroller *) _scroller;
- (void) webView:(WebView *)view addMessageToConsole:(NSDictionary *)message;
- (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame;
@end

@interface WebView : NSObject
@property (nonatomic, readonly) WebFrame *mainFrame;
+ (void)registerURLSchemeAsLocal:(id)arg1;
@end

@interface WebFrame : NSObject
@property (nonatomic, readonly) JSGlobalContextRef globalContext;
- (id)DOMDocument;
@end

@protocol CydgetWebViewDelegate <UIWebViewDelegate>
- (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame;
@end

#include <string>

struct State {
    unsigned state;
};

namespace JSC {
    class JSGlobalData;
    class UString;
}

namespace WebCore {
    class KURL;
}

namespace WebCore {
    struct String {
        void *impl_;
    };
}

namespace JSC {
    struct SourceCode {
        void *provider_;
        int start_;
        int end_;
        int line_;
    };
}

namespace JSC {
    union ScriptSourceCode {
        struct {
            JSC::SourceCode source_;
        } Old;
        struct {
            void *provider_;
            JSC::SourceCode source_;
        } New;
    };
}

class CFStringStruct {
private:
    CFStringRef value_;

public:
    CFStringStruct() :
    value_(NULL)
    {
    }

    CFStringStruct(const CFStringStruct &value) :
    value_((CFStringRef) CFRetain(value.value_))
    {
    }

    ~CFStringStruct() {
    }

    operator CFStringRef() const {
        return value_;
    }

    operator NSString *() const {
        return (__bridge NSString *) value_;
    }
};

namespace WebCore {
    class MediaQueryEvaluator;
    class CSSParserValueList;
}

namespace WebCore {
    struct MediaQueryExp {
        String feature_;
        void *value_;
        bool valid_;
        String cache_;
    };
}


text:
smalluuid
=========

.. image:: https://img.shields.io/pypi/v/smalluuid.svg
    :target: https://pypi.python.org/pypi/smalluuid/

.. image:: https://img.shields.io/pypi/dm/smalluuid.svg
    :target: https://pypi.python.org/pypi/smalluuid/

.. image:: https://img.shields.io/github/license/adamcharnock/smalluuid.svg
    :target: https://pypi.python.org/pypi/smalluuid/

.. image:: https://img.shields.io/travis/adamcharnock/smalluuid.svg
    :target: https://travis-ci.org/adamcharnock/smalluuid/

.. image:: https://coveralls.io/repos/adamcharnock/smalluuid/badge.svg
    :target: https://coveralls.io/r/adamcharnock/smalluuid/

Installation
------------

Installation using pip::

    pip install smalluuid

**Do you use Django?** See django-smalluuid_.

Basic Usage
-----------

A drop-in replacement for Python's UUID class which – by default –
represents UUIDs as 22 character base64-encoded values.

.. code-block:: python

    >>> from smalluuid import SmallUUID
    >>> uuid = SmallUUID()

    # Displays as short UUID by default
    >>> uuid
    SmallUUID('IBNApQOzTHGzdjkSt6t-Jg')
    >>> print(uuid)
    IBNApQOzTHGzdjkSt6t-Jg

    # Hex output still available
    >>> SmallUUID().hex
    '44a30f95b86f429f83c5669fed1998ab'
    >>> uuid.hex_grouped
    '201340a5-03b3-4c71-b376-3912b7ab7e26'

    # Will initialise from short UUID
    >>> SmallUUID('IBNApQOzTHGzdjkSt6t-Jg')
    SmallUUID('IBNApQOzTHGzdjkSt6t-Jg')

    # Will load as a hex value
    >>> SmallUUID(hex='201340a5-03b3-4c71-b376-3912b7ab7e26')
    SmallUUID('RKMPlbhvQp-DxWaf7RmYqw')

Notable differences from Python's UUID implementation:

* Short-form UUIDs accepted as first parameter to ``__init__``
* Instantiating without a value will assign a random value of the given version (default: 4)
  rather than raise an exception.
* Addition of ``hex_grouped`` property to provide access to grouped hex style UUIDs, formally
  provided by ``__str__``.

Typed UUID Usage
----------------

An extension of ``SmallUUID`` is available in the form of ``TypedSmallUUID``:

.. code-block:: python

    >>> from smalluuid import TypedSmallUUID

    # Takes a type during instantiation
    >>> uuid = TypedSmallUUID(type=42)
    >>> uuid
    TypedSmallUUID('qHHvXuUwT6y7t7dnsiksvg')

    # Type is stored within the UUID
    >>> uuid.type
    42

    # Type determined from provided UUID value
    >>> TypedSmallUUID('qHHvXuUwT6y7t7dnsiksvg').type
    42

The use case here is that of having UUIDs from which one can determine
both an object's ID and the object's type/table/model.

Credits
-------

This project borrowed a little code and inspiration from
shortuuid_.

``smalluuid`` is packaged using seed_.

.. _seed: https://github.com/adamcharnock/seed/
.. _shortuuid: https://github.com/stochastic-technologies/shortuuid
.. _django-smalluuid: https://github.com/adamcharnock/django-smalluuid


text:
import * as qvangular from "qvangular";
export =
    ["serverside", "standardSelectDialogService",
        function (serverside, standardSelectDialogService) {
            var dialogContentProvider = {
                getConnectionInfo: function () {
                    return qvangular.promise({
                        dbusage: false,
                        ownerusage: false,
                        dbseparator: ".",
                        ownerseparator: ".",
                        specialchars: '! "$&\"()*+,-/:;<>`{}~[]',
                        quotesuffix: '"',
                        quoteprefix: '"',
                        dbfirst: true,
                        keywords: []
                    });
                },
                getDatabases: function () {
                    return qvangular.promise({ qName: "" });
                },
                getOwners: function (qDatabaseName) {
                    return qvangular.promise([{ qName: "" }]);
                },
                getTables: function (qDatabaseName, qOwnerName) {
                    return qvangular.promise([]);
                },
                getFields: function (qDatabaseName, qOwnerName, qTableName) {
                    return qvangular.promise([]);
                },
                getPreview: function (qDatabaseName, qOwnerName, qTableName) {
                    return qvangular.promise([]);
                }
            };

            standardSelectDialogService.showStandardDialog(dialogContentProvider, {
                precedingLoadVisible: true,
                fieldsAreSelectable: true,
                allowFieldRename: true
            });
        }];


text:
class Submission < ActiveRecord::Base
  validates :problem, presence: true,
    uniqueness: { scope: :team_id,
      message: "already exists for this team"}
  belongs_to :team
  #attr_accessible :team, :problem

  def self.boards
    [
      {
        title:
          "e",
        description:
          "All problems ≤ 20",
        query:
          self.
          select('team_id, SUM(problem) AS total').
          group('team_id').
          order('total DESC').
          having('MAX(problem) <= 20')
      },
      {
        title:
          "i",
        description:
          "Some problems between 21 and 99",
        query:
          self.
          select('team_id, SUM(problem) AS total').
          group('team_id').
          order('total DESC').
          having('MAX(problem) BETWEEN 21 AND 99')
      },
      {
        title:
          "π",
        description:
            "Some problems ≥ 100",
        query:
          self.
          select('team_id, SUM(problem) AS total').
          group('team_id').
          order('total DESC').
          having('MAX(problem) >= 100')
          }
    ]
  end
end


text:
table {
  border-spacing: 0;
  border-collapse: collapse;
  position: relative;
  width: 100%;
}

table td, table th {
  padding:
    calc(var(--line-height) * 1 / 4)
    calc(var(--line-height) * 1 / 2);
}

table th {
  hyphens: none;
  white-space: nowrap;
  background-color: var(--color-ultralight);
  font-family: var(--font-header);
}

tbody code {
  background: none;
  padding: 0;
}

tbody tr:nth-of-type(2n) {
  background-color: var(--color-ultralight);
}

.table-wrapper {
  overflow: auto;
  box-shadow: 0 -1px 0 var(--color-light);
}


text:
using System;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Windows.Forms;

using Poderosa.Preferences;
using Poderosa.Terminal;
using Poderosa.Usability;
using Poderosa.Util;

namespace Poderosa.ExtendPaste {
    /// <summary>
    /// <ja>オプションパネルフォームクラス</ja>
    /// </summary>
    internal class ExtendPasteOptionPanel : UserControl {
        // メンバー変数
        private CheckBox _afterSpecifiedTimePasteCheck;
        private CheckBox _changeDialogSize;
        private CheckBox _showConfirmCheck;
        private ComboBox _useActionBox;
        private GroupBox _extendPasteOptionGroup;
        private Label _descriptionLabel;
        private Label _highlightKeywordLabel;
        private Label _useActionLabel;
        private NumericUpDown _pasteTimeBox;
        private TextBox _highlightKeywordBox;

        /// <summary>
        /// <ja>コンストラクタ</ja>
        /// </summary>
        public ExtendPasteOptionPanel() {
            InitializeComponent();
            FillText();
        }

        /// <summary>
        /// <ja>InitializeComponent</ja>
        /// </summary>
        private void InitializeComponent() {
            this._descriptionLabel = new System.Windows.Forms.Label();
            this._useActionLabel = new System.Windows.Forms.Label();
            this._useActionBox = new System.Windows.Forms.ComboBox();
            this._showConfirmCheck = new System.Windows.Forms.CheckBox();
            this._afterSpecifiedTimePasteCheck = new System.Windows.Forms.CheckBox();
            this._changeDialogSize = new System.Windows.Forms.CheckBox();
            this._extendPasteOptionGroup = new System.Windows.Forms.GroupBox();
            this._pasteTimeBox = new System.Windows.Forms.NumericUpDown();
            this._highlightKeywordBox = new System.Windows.Forms.TextBox();
            this._highlightKeywordLabel = new System.Windows.Forms.Label();
            this._extendPasteOptionGroup.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this._pasteTimeBox)).BeginInit();
            this.SuspendLayout();
            //
            // _descriptionLabel
            //
            this._descriptionLabel.Location = new System.Drawing.Point(11, 210);
            this._descriptionLabel.Name = "_descriptionLabel";
            this._descriptionLabel.Size = new System.Drawing.Size(419, 155);
            this._descriptionLabel.TabIndex = 0;
            this._descriptionLabel.Text = "_descriptionLabel";
            //
            // _useActionLabel
            //
            this._useActionLabel.AutoSize = true;
            this._useActionLabel.Location = new System.Drawing.Point(15, 24);
            this._useActionLabel.Name = "_useActionLabel";
            this._useActionLabel.Size = new System.Drawing.Size(87, 12);
            this._useActionLabel.TabIndex = 1;
            this._useActionLabel.Text = "_useActionLabel";
            //
            // _useActionBox
            //
            this._useActionBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this._useActionBox.FormattingEnabled = true;
            this._useActionBox.Location = new System.Drawing.Point(172, 21);
            this._useActionBox.Name = "_useActionBox";
            this._useActionBox.Size = new System.Drawing.Size(239, 20);
            this._useActionBox.TabIndex = 2;
            this._useActionBox.SelectedIndexChanged += new System.EventHandler(this._useActionBox_SelectedIndexChanged);
            //
            // _showConfirmCheck
            //
            this._showConfirmCheck.AutoSize = true;
            this._showConfirmCheck.Location = new System.Drawing.Point(17, 87);
            this._showConfirmCheck.Name = "_showConfirmCheck";
            this._showConfirmCheck.Size = new System.Drawing.Size(126, 16);
            this._showConfirmCheck.TabIndex = 6;
            this._showConfirmCheck.Text = "_showConfirmCheck";
            this._showConfirmCheck.UseVisualStyleBackColor = true;
            //
            // _afterSpecifiedTimePasteCheck
            //
            this._afterSpecifiedTimePasteCheck.AutoSize = true;
            this._afterSpecifiedTimePasteCheck.Location = new System.Drawing.Point(17, 118);
            this._afterSpecifiedTimePasteCheck.Name = "_afterSpecifiedTimePasteCheck";
            this._afterSpecifiedTimePasteCheck.Size = new System.Drawing.Size(185, 16);
            this._afterSpecifiedTimePasteCheck.TabIndex = 7;
            this._afterSpecifiedTimePasteCheck.Text = "_afterSpecifiedTimePasteCheck";
            this._afterSpecifiedTimePasteCheck.UseVisualStyleBackColor = true;
            this._afterSpecifiedTimePasteCheck.CheckedChanged += new System.EventHandler(this._afterSpecifiedTimePasteCheck_CheckedChanged);
            //
            // _changeDialogSize
            //
            this._changeDialogSize.AutoSize = true;
            this._changeDialogSize.Location = new System.Drawing.Point(17, 149);
            this._changeDialogSize.Name = "_changeDialogSize";
            this._changeDialogSize.Size = new System.Drawing.Size(117, 16);
            this._changeDialogSize.TabIndex = 8;
            this._changeDialogSize.Text = "_changeDialogSize";
            this._changeDialogSize.UseVisualStyleBackColor = true;
            //
            // _extendPasteOptionGroup
            //
            this._extendPasteOptionGroup.Controls.Add(this._pasteTimeBox);
            this._extendPasteOptionGroup.Controls.Add(this._highlightKeywordBox);
            this._extendPasteOptionGroup.Controls.Add(this._highlightKeywordLabel);
            this._extendPasteOptionGroup.Controls.Add(this._useActionLabel);
            this._extendPasteOptionGroup.Controls.Add(this._changeDialogSize);
            this._extendPasteOptionGroup.Controls.Add(this._useActionBox);
            this._extendPasteOptionGroup.Controls.Add(this._afterSpecifiedTimePasteCheck);
            this._extendPasteOptionGroup.Controls.Add(this._showConfirmCheck);
            this._extendPasteOptionGroup.Location = new System.Drawing.Point(13, 13);
            this._extendPasteOptionGroup.Name = "_extendPasteOptionGroup";
            this._extendPasteOptionGroup.Size = new System.Drawing.Size(417, 185);
            this._extendPasteOptionGroup.TabIndex = 0;
            this._extendPasteOptionGroup.TabStop = false;
            this._extendPasteOptionGroup.Text = "_extendPasteOptionGroup";
            //
            // _pasteTimeBox
            //
            this._pasteTimeBox.Location = new System.Drawing.Point(366, 118);
            this._pasteTimeBox.Maximum = new decimal(new int[] {
            60,
            0,
            0,
            0});
            this._pasteTimeBox.Name = "_pasteTimeBox";
            this._pasteTimeBox.Size = new System.Drawing.Size(45, 19);
            this._pasteTimeBox.TabIndex = 11;
            //
            // _highlightKeywordBox
            //
            this._highlightKeywordBox.Font = new System.Drawing.Font("MS ゴシック", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(128)));
            this._highlightKeywordBox.Location = new System.Drawing.Point(172, 54);
            this._highlightKeywordBox.Name = "_highlightKeywordBox";
            this._highlightKeywordBox.Size = new System.Drawing.Size(239, 19);
            this._highlightKeywordBox.TabIndex = 10;
            //
            // _highlightKeywordLabel
            //
            this._highlightKeywordLabel.AutoSize = true;
            this._highlightKeywordLabel.Location = new System.Drawing.Point(15, 57);
            this._highlightKeywordLabel.Name = "_highlightKeywordLabel";
            this._highlightKeywordLabel.Size = new System.Drawing.Size(122, 12);
            this._highlightKeywordLabel.TabIndex = 9;
            this._highlightKeywordLabel.Text = "_highlightKeywordLabel";
            //
            // ExtendPasteOptionPanel
            //
            this.BackColor = System.Drawing.SystemColors.Window;
            this.Controls.Add(this._extendPasteOptionGroup);
            this.Controls.Add(this._descriptionLabel);
            this.Name = "ExtendPasteOptionPanel";
            this.Size = new System.Drawing.Size(448, 380);
            this._extendPasteOptionGroup.ResumeLayout(false);
            this._extendPasteOptionGroup.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this._pasteTimeBox)).EndInit();
            this.ResumeLayout(false);

        }

        /// <summary>
        /// <ja>オブジェクトテキスト初期化</ja>
        /// </summary>
        private void FillText() {
            // テキスト
            this._extendPasteOptionGroup.Text = ExtendPastePlugin.Instance.Strings.GetString("Form.ExtendPasteOptionPanel._extendPasteOptionGroup");
            this._useActionLabel.Text = ExtendPastePlugin.Instance.Strings.GetString("Form.ExtendPasteOptionPanel._useActionLabel");
            this._highlightKeywordLabel.Text = ExtendPastePlugin.Instance.Strings.GetString("Form.ExtendPasteOptionPanel._highlightKeywordLabel");
            this._showConfirmCheck.Text = ExtendPastePlugin.Instance.Strings.GetString("Form.ExtendPasteOptionPanel._showConfirmCheck");
            this._afterSpecifiedTimePasteCheck.Text = ExtendPastePlugin.Instance.Strings.GetString("Form.ExtendPasteOptionPanel._afterSpecifiedTimePasteCheck");
            this._changeDialogSize.Text = ExtendPastePlugin.Instance.Strings.GetString("Form.ExtendPasteOptionPanel._changeDialogSize");
            this._descriptionLabel.Text = ExtendPastePlugin.Instance.Strings.GetString("Form.ExtendPasteOptionPanel._descriptionLabel");

            // コンボボックス
            this._useActionBox.Items.AddRange(EnumListItem<UseAction>.GetListItems());
        }

        /// <summary>
        /// <ja>オプション値をオブジェクトに反映(パネルを開く度に実行される)</ja>
        /// </summary>
        public void InitUI(IExtendPasteOptions options) {
            this._useActionBox.SelectedItem = options.UseAction;
            this._highlightKeywordBox.Text = options.HighlightKeyword;
            this._showConfirmCheck.Checked = options.ShowConfirmCheck;
            this._afterSpecifiedTimePasteCheck.Checked = options.AfterSpecifiedTimePaste;
            this._pasteTimeBox.Value = options.PasteTime;
            this._changeDialogSize.Checked = options.ChangeDialogSize;
        }

        /// <summary>
        /// <ja>コミット(パネルを切り替える度に実行される)</ja>
        /// </summary>
        public bool Commit(IExtendPasteOptions options) {
            StringResource sr = ExtendPastePlugin.Instance.Strings;
            bool successful = false;
            string itemName = null;

            try {
                options.UseAction = ((EnumListItem<UseAction>)_useActionBox.SelectedItem).Value;
                options.HighlightKeyword = _highlightKeywordBox.Text;
                options.ShowConfirmCheck = _showConfirmCheck.Checked;
                options.AfterSpecifiedTimePaste = _afterSpecifiedTimePasteCheck.Checked;
                options.ChangeDialogSize = _changeDialogSize.Checked;

                // 強調キーワード正規表現パターンチェック
                itemName = sr.GetString("Message.ExtendPasteOptionPanel.RegExpPettern");
                Regex RegExp = new Regex(options.HighlightKeyword, RegexOptions.Multiline);

                // ペースト秒数チェック
                itemName = sr.GetString("Message.ExtendPasteOptionPanel.AfterSpecifiedTimePaste");
                if ((_afterSpecifiedTimePasteCheck.Checked) && (_pasteTimeBox.Value > 0)) {
                    options.PasteTime = (int)_pasteTimeBox.Value;
                } else {
                    options.PasteTime = 0;
                    options.AfterSpecifiedTimePaste = false;
                }

                successful = true;
            } catch (InvalidOptionException ex) {
                GUtil.Warning(this, ex.Message);
            } catch (Exception) {
                GUtil.Warning(this, String.Format(sr.GetString("Message.ExtendPasteOptionPanel.InvalidItem"), itemName));
            }

            return successful;
        }

        /// <summary>
        /// <ja>使用アクションコンボボックス選択変更イベント</ja>
        /// </summary>
        private void _useActionBox_SelectedIndexChanged(object sender, EventArgs e) {
            bool value = (((EnumListItem<UseAction>)_useActionBox.SelectedItem).Value != UseAction.NotUse) ? true : false;
            _highlightKeywordBox.Enabled = value;
            _showConfirmCheck.Enabled = value;
            _afterSpecifiedTimePasteCheck.Enabled = value;
            _pasteTimeBox.Enabled = (value && _afterSpecifiedTimePasteCheck.Checked);
            _changeDialogSize.Enabled = value;
        }

        /// <summary>
        /// <ja>指定秒数後ペーストチェックボックス切替イベント</ja>
        /// </summary>
        private void _afterSpecifiedTimePasteCheck_CheckedChanged(object sender, EventArgs e) {
            if ((((EnumListItem<UseAction>)_useActionBox.SelectedItem).Value != UseAction.NotUse) && (_afterSpecifiedTimePasteCheck.Checked == true)) {
                _pasteTimeBox.Enabled = true;
            } else {
                _pasteTimeBox.Enabled = false;
            }
        }
    }

    /// <summary>
    /// <ja>オプションパネル定義クラス</ja>
    /// </summary>
    internal class ExtendPastePanelExtension : IOptionPanelExtension {
        // メンバー変数
        private ExtendPasteOptionPanel _panel;

        /// <summary>
        /// <ja>オプションパネル初期化</ja>
        /// </summary>
        public void InitiUI(IPreferenceFolder[] values) {
            if (_panel == null) _panel = new ExtendPasteOptionPanel();
            _panel.InitUI((IExtendPasteOptions)values[0].QueryAdapter(typeof(IExtendPasteOptions)));
        }

        /// <summary>
        /// <ja>コミット</ja>
        /// </summary>
        public bool Commit(IPreferenceFolder[] values) {
            return _panel.Commit((IExtendPasteOptions)values[0].QueryAdapter(typeof(IExtendPasteOptions)));
        }

        /// <summary>
        /// <ja>Dispose</ja>
        /// </summary>
        public void Dispose() {
            if (_panel != null) {
                _panel.Dispose();
                _panel = null;
            }
        }

        /// <summary>
        /// <ja>項目タイトル</ja>
        /// </summary>
        public string Caption {
            get { return ExtendPastePlugin.Instance.Strings.GetString("Form.ExtendPasteOptionPanel.Caption"); }
        }

        /// <summary>
        /// <ja>項目アイコン</ja>
        /// </summary>
        public Image Icon {
            get { return Properties.Resources.OptionDialogIcon; }
        }

        /// <summary>
        /// <ja>オプションパネル</ja>
        /// </summary>
        public Control ContentPanel {
            get { return _panel; }
        }

        /// <summary>
        /// <ja>識別子</ja>
        /// </summary>
        public string[] PreferenceFolderIDsToEdit {
            get { return new string[] { ExtendPastePlugin.PLUGIN_ID }; }
        }
    }
}


text:
package es.deusto.deustotech.utils;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;

class GraphicsActivity extends Activity {
    // set to true to test Picture
    private static final boolean TEST_PICTURE = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void setContentView(View view) {
        if (TEST_PICTURE) {
            ViewGroup vg = new PictureLayout(this);
            vg.addView(view);
            view = vg;
        }

        super.setContentView(view);
    }
}


text:
from collections import namedtuple as _namedtuple

VERSION_INFO = _namedtuple('version_info', ('major', 'minor', 'patch'))(0, 1, 0)
VERSION = "%d.%d.%d" % VERSION_INFO


text:
var NobleDevice = require('./lib/noble-device');

NobleDevice.Util = require('./lib/util');
NobleDevice.DeviceInformationService = require('./lib/device-information-service');
NobleDevice.BatteryService = require('./lib/battery-service');

module.exports = NobleDevice;


text:
# Sending Email

Sending email is very simple in ActFramework. What you need to do is:

1. Use `Mailer` annotation to tag your class that contains send mail methods
1. Extend your class to `Mailer.Util` class or add a static import statement:

    `import static act.mail.Mailer.Util.*`

## Creating mailer class and methods

```java
package com.mycom.myprj;

import act.conf.AppConfig;
import act.job.Every;
import act.mail.Mailer;
import org.osgl.logging.*;
import org.osgl.util.E;
import org.osgl.util.S;

import javax.inject.Inject;

/**
 * This class demonstrate how to write an email sender
 * in act framework.
 */
@Mailer
public class PostOffice extends Mailer.Util {

    public void sendWelcome(Contact who) {
        to(who.getEmail());
        subject("Welcome letter");
        send(who);
    }

    public void sendBye(Contact who) {
        to(who.getEmail());
        send(who);
    }

}
```

## Creating mailer templates

Now that you have the mailer created, you can create the template corresponding to the mailer methods:

1. `src/main/resources/rythm/com/mycom/myprj/PostOffice/sendWelcome.html`:

```html
<html>
<head></head>
<body>
@args com.mycom.myprj.Contact who
<h1>Welcome @who.getFirstName()!</h1>
<p>Blah Blah</p>
</body>
</html>
```

1. `src/main/resources/rythm/com/mycom/myprj/PostOffice/sendBye.html`:

```html
<html>
<head></head>
<body>
@args com.mycom.myprj.Contact who
<h1>Good bye @who.getFirstName()!</h1>
</body>
</html>
```

## Calling mailer methods

You can call the mailer method directly from any where, like the following controller code:

```java
public class MyController {

    @Inject
    private PostOffice postOffice;

    @PostAction("/contact")
    public void createContact(Contact contact) {
        contactDao.save(contact);
        postOffice.sendWelcome(contact);
    }

    @PutAction("/contact/{contactId}/signOff")
    public void signOff(String contactId) {
        Contact contact = contactDao.findById(contactId);
        contact.signOff();
        contactDao.save(contact);
        postOffice.sendBye(contact);
    }
}
```

## Calling mailer method asynchronously

Usually executing mailer method involves IPC to external services (e.g. your SMTP server), which could be time consuming. So you would prefer to execute mailer method asynchrously and return back immediately. You can use ActFramework's event dispatching mechanism to achieve that.

1. Mark your mailer methods to be an event handler

    ```java
    @On(value = "contact-created", async = true)
    public void sendWelcome(Contact who) {
        to(who.getEmail());
        subject("Welcome letter");
        send(who);
    }

    @On(value = "contact-signed-off", async = true)
    public void sendBye(Contact who) {
        to(who.getEmail());
        send(who);
    }
    ```

1. Trigger event instead of calling mailer method directly:

    ```java
    public class MyController {

        @Inject
        EventBus eventBus;

        @PostAction("/contact")
        public void createContact(Contact contact) {
            contactDao.save(contact);
            eventBus.trigger("contact-created", contact);
        }

        @PutAction("/contact/{contactId}/signOff")
        public void signOff(String contactId) {
            Contact contact = contactDao.findById(contactId);
            contact.signOff();
            contactDao.save(contact);
            eventBus.trigger("contact-signed-off", contact);
        }
    }
    ```

    [Back to index](index.md)


text:
package ru.job4j.map;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class SimpleHashMap<K, V> implements Iterable<V> {
    private Entry<K, V>[] table;
    private int INITIAL_CAPACITY = 16;
    private int size;
    final private double loadFactor = 0.75;

    public SimpleHashMap() {
        table = new Entry[INITIAL_CAPACITY];
    }

    public V get(K key) {
        int hash = hash(key.hashCode());
        int index = hash % table.length;

        for (Entry<K, V> entry = table[index]; entry != null; entry = entry.next) {
            if (hash == entry.hash && (key == entry.key || (key.equals(entry.key)))) {
                return entry.value;
            }
        }
        return null;
    }

    private int hash(int hash) {
        if (hash < 0) {
            hash *= -1;
        }
        return hash;
    }

    private void resize() {
        Entry[] oldTable = table;
        table = new Entry[table.length * 2];

        for (int i = 0; i < oldTable.length; i++) {
            if (oldTable[i] != null) {
                int hash = hash(oldTable[i].key.hashCode());
                int index = hash % (table.length);
                table[index] = oldTable[i];
            }
        }
    }

    V put(K key, V value) {
        if ((table.length * loadFactor) == size) {
            resize();
        }

        int hash = hash(key.hashCode());
        int index = hash % table.length;

        for (Entry<K, V> entry = table[index]; entry != null; entry = entry.next) {
            if (hash == entry.hash && (key == entry.key || (key.equals(entry.key)))) {
                V oldValue = entry.value;
                entry.value = value;
                return oldValue;
            }
        }

        Entry<K, V> entry = new Entry(hash, key, value, table[index]);
        table[index] = entry;
        size++;
        return null;
    }

    void remove(Object key) throws UnsupportedOperationException {
        int hash = hash(key.hashCode());
        int index = hash % table.length;

        table[index] = null;
    }

    boolean containsKey(K key) {
        int hash = key.hashCode();
        if (hash < 0) {
            hash *= -1;
        }
        int index = hash % table.length;
        if (table[index] != null) {
            return table[index].key == key;
        }
        return false;
    }

    static class Entry<K, V> {
        private final int hash;
        private final K key;
        private V value;
        private Entry<K, V> next;

        Entry(int hash, K key, V value, Entry<K, V> next) {
            this.hash = hash;
            this.key = key;
            this.value = value;
            this.next = next;
        }

        public K getKey() {
            return key;
        }
    }

    @Override
    public Iterator<V> iterator() {
        return new Iterator<V>() {
            Entry<K, V>[] t = table;
            int size = t.length;

            @Override
            public boolean hasNext() {
                boolean result = false;
                for (int i = 0; i < t.length; i++) {
                    if (t[i] != null) {
                        result = true;
                        break;
                    }
                }
                return result;
            }

            @Override
            public V next() {
                if (!hasNext())
                    throw new NoSuchElementException();
                V result = null;
                for (int i = 0; i < t.length; i++) {
                    if (t[i] != null) {
                        int hash = hash(t[i].key.hashCode());
                        int index = hash % table.length;
                        result = t[i].value;
                        t[index] = null;
                        break;
                    }
                }
                return result;
            }
        };
    }

    public int hashCode() {
        int hash = (int) (Math.random() * 64000);
        return hash % size;
    }
}


text:
from generateData import *
from gmm3 import *

X0train = generateDataCat('data/train.txt',0)
X1train = generateDataCat('data/train.txt',1)

# training
k0 = 4
k1 = 4
gmm0 = GMM(k0,X0train)
# train GMM0
gmm0.gmm(X0train,k0)

gmm1 = GMM(k1,X1train)
gmm1.gmm(X1train,k1)

X0dev = generateDataCat('data/dev.txt',0)
X1dev = generateDataCat('data/dev.txt',1)
Xdev = generateData('data/dev.txt')
ansDev = generateAns('data/dev.txt')

redev = generateResult(gmm0,gmm1,Xdev)
devacc = evaluate(redev,ansDev)
print 'Accuarcy on Dev dataset: ', devacc

# generate test result
Xtest = generateData('data/test.txt')
retest = generateResult(gmm0,gmm1,Xtest)
row, col = np.shape(Xtest)
print "row, col", row, " ",col
outf = open('result/result0.txt','w')

for i in range(row):
	line = ""
	for j in range(col):
		line += str(np.array(Xtest)[i][j])
		line += " "
	line += " "
	line += str(retest[i]+1)
	line += '\n'
	outf.write(line)

outf.close()

"""
test for change-case in atom
hello/word
"""


text:
package domino.test

import java.io.File

import scala.collection.JavaConverters.mapAsJavaMapConverter

import org.osgi.framework.BundleActivator

import de.kalpatec.pojosr.framework.PojoSR
import de.kalpatec.pojosr.framework.launch.PojoServiceRegistry

object PojoSrTestHelper {

  val OnlyOnePojoSrAtATime = new Object()

}

trait PojoSrTestHelper {

  import PojoSrTestHelper._

  def withPojoServiceRegistry[T](f: PojoServiceRegistry => T) = OnlyOnePojoSrAtATime.synchronized {
    val dir = File.createTempFile("pojosr-", "")
    dir.delete()
    dir.mkdirs()
    try {
      System.setProperty("org.osgi.framework.storage", dir.getAbsolutePath())
      val registry = new PojoSR(Map("felix.cm.dir" -> dir.getAbsolutePath()).asJava)
      f(registry)
    } finally {
      System.clearProperty("org.osgi.framework.storage")
      deleteRecursive(dir)
    }
  }

  def deleteRecursive(files: File*): Unit = files.map { file =>
    if (file.isDirectory) deleteRecursive(file.listFiles: _*)
    file.delete match {
      case false if file.exists =>
        throw new RuntimeException(s"Could not delete ${if (file.isDirectory) "dir" else "file"}: ${file}")
      case _ =>
    }
  }

  def withStartedBundle(activator: BundleActivator): Unit =
    withPojoServiceRegistry { sr =>
      withStartedBundle(sr)(activator)
    }

  def withStartedBundle(sr: PojoServiceRegistry)(activator: BundleActivator): Unit = {
    activator.start(sr.getBundleContext())
    activator.stop(sr.getBundleContext())
  }

}


text:
'use strict';

const PluginSocket = require.main.require('./src/socket.io/plugins');
const AdminSocket = require.main.require('./src/socket.io/admin');

const sockets = require('./sockets');
const settings = require('./settings');
const hashing = require('./hashing');
const routes = require('./routes');
// var services = require('./services');

let SmoothShorts = {
  admin: {},
  purgePost: hashing.purgePost,
  purgeTopic: hashing.purgeTopic,
  shortenPost: hashing.shortenPost,
  shortenTopic: hashing.shortenTopic
};

SmoothShorts.init = function(app, cb) {
  settings.load(function(err) {
    if (err) {
      return cb(err);
    }
    routes.initRoutes(app.router, app.middleware);
    openSockets();
    return cb(null, app);
  });
};

SmoothShorts.prepareHotSwap = routes.prepareHotSwap;

SmoothShorts.admin.addMenuItem = function(custom_header, cb) {
  custom_header.plugins.push({
    route: '/plugins/smoothshorts',
    icon: 'fa-location-arrow',
    name: 'SmoothShorts'
  });
  cb(null, custom_header);
};

function openSockets() {
  PluginSocket.SmoothShorts = sockets.plugin;
  AdminSocket.plugins.SmoothShorts = sockets.admin;
}

module.exports = SmoothShorts;


text:
package com.ystore.web.server;

import org.apache.velocity.tools.config.DefaultKey;
import org.apache.velocity.tools.config.ValidScope;
import org.apache.velocity.tools.view.ViewContext;

@DefaultKey("params")
@ValidScope("request")
public class ParameterTool extends org.apache.velocity.tools.view.ParameterTool {
    public void init(Object obj) {
        if (obj instanceof ViewContext) {
            setRequest(((ViewContext)obj).getRequest());
        }
    }
}


text:
/**
 * @constructor
 * @implements {WebInspector.DebuggerSourceMapping}
 * @param {!WebInspector.DebuggerModel} debuggerModel
 * @param {!WebInspector.Workspace} workspace
 * @param {!WebInspector.NetworkMapping} networkMapping
 * @param {!WebInspector.DebuggerWorkspaceBinding} debuggerWorkspaceBinding
 */
WebInspector.ResourceScriptMapping = function(debuggerModel, workspace, networkMapping, debuggerWorkspaceBinding)
{
    this._target = debuggerModel.target();
    this._debuggerModel = debuggerModel;
    this._workspace = workspace;
    this._workspace.addEventListener(WebInspector.Workspace.Events.UISourceCodeAdded, this._uiSourceCodeAdded, this);
    this._workspace.addEventListener(WebInspector.Workspace.Events.UISourceCodeRemoved, this._uiSourceCodeRemoved, this);
    this._networkMapping = networkMapping;
    this._debuggerWorkspaceBinding = debuggerWorkspaceBinding;
    /** @type {!Set.<string>} */
    this._boundURLs = new Set();

    /** @type {!Map.<!WebInspector.UISourceCode, !WebInspector.ResourceScriptFile>} */
    this._uiSourceCodeToScriptFile = new Map();

    debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.GlobalObjectCleared, this._debuggerReset, this);
}

WebInspector.ResourceScriptMapping.prototype = {
    /**
     * @override
     * @param {!WebInspector.DebuggerModel.Location} rawLocation
     * @return {?WebInspector.UILocation}
     */
    rawLocationToUILocation: function(rawLocation)
    {
        var debuggerModelLocation = /** @type {!WebInspector.DebuggerModel.Location} */ (rawLocation);
        var script = debuggerModelLocation.script();
        var uiSourceCode = this._workspaceUISourceCodeForScript(script);
        if (!uiSourceCode)
            return null;
        var scriptFile = this.scriptFile(uiSourceCode);
        if (scriptFile && ((scriptFile.hasDivergedFromVM() && !scriptFile.isMergingToVM()) || scriptFile.isDivergingFromVM()))
            return null;
        var lineNumber = debuggerModelLocation.lineNumber - (script.isInlineScriptWithSourceURL() ? script.lineOffset : 0);
        var columnNumber = debuggerModelLocation.columnNumber || 0;
        if (script.isInlineScriptWithSourceURL() && !lineNumber && columnNumber)
            columnNumber -= script.columnOffset;
        return uiSourceCode.uiLocation(lineNumber, columnNumber);
    },

    /**
     * @override
     * @param {!WebInspector.UISourceCode} uiSourceCode
     * @param {number} lineNumber
     * @param {number} columnNumber
     * @return {?WebInspector.DebuggerModel.Location}
     */
    uiLocationToRawLocation: function(uiSourceCode, lineNumber, columnNumber)
    {
        var scripts = this._scriptsForUISourceCode(uiSourceCode);
        console.assert(scripts.length);
        var script = scripts[0];
        if (script.isInlineScriptWithSourceURL())
            return this._debuggerModel.createRawLocation(script, lineNumber + script.lineOffset, lineNumber ? columnNumber : columnNumber + script.columnOffset);
        return this._debuggerModel.createRawLocation(script, lineNumber, columnNumber);
    },

    /**
     * @param {!WebInspector.Script} script
     */
    addScript: function(script)
    {
        if (script.isAnonymousScript())
            return;
        this._debuggerWorkspaceBinding.pushSourceMapping(script, this);

        var uiSourceCode = this._workspaceUISourceCodeForScript(script);
        if (!uiSourceCode)
            return;

        this._bindUISourceCodeToScripts(uiSourceCode, [script]);
    },

    /**
     * @override
     * @return {boolean}
     */
    isIdentity: function()
    {
        return true;
    },

    /**
     * @override
     * @param {!WebInspector.UISourceCode} uiSourceCode
     * @param {number} lineNumber
     * @return {boolean}
     */
    uiLineHasMapping: function(uiSourceCode, lineNumber)
    {
        return true;
    },

    /**
     * @param {!WebInspector.UISourceCode} uiSourceCode
     * @return {?WebInspector.ResourceScriptFile}
     */
    scriptFile: function(uiSourceCode)
    {
        return this._uiSourceCodeToScriptFile.get(uiSourceCode) || null;
    },

    /**
     * @param {!WebInspector.UISourceCode} uiSourceCode
     * @param {?WebInspector.ResourceScriptFile} scriptFile
     */
    _setScriptFile: function(uiSourceCode, scriptFile)
    {
        if (scriptFile)
            this._uiSourceCodeToScriptFile.set(uiSourceCode, scriptFile);
        else
            this._uiSourceCodeToScriptFile.remove(uiSourceCode);
    },

    /**
     * @param {!WebInspector.Event} event
     */
    _uiSourceCodeAdded: function(event)
    {
        var uiSourceCode = /** @type {!WebInspector.UISourceCode} */ (event.data);
        if (!this._networkMapping.networkURL(uiSourceCode))
            return;
        if (uiSourceCode.project().isServiceProject())
            return;

        var scripts = this._scriptsForUISourceCode(uiSourceCode);
        if (!scripts.length)
            return;

        this._bindUISourceCodeToScripts(uiSourceCode, scripts);
    },

    /**
     * @param {!WebInspector.Event} event
     */
    _uiSourceCodeRemoved: function(event)
    {
        var uiSourceCode = /** @type {!WebInspector.UISourceCode} */ (event.data);
        if (!this._networkMapping.networkURL(uiSourceCode))
            return;
        if (uiSourceCode.project().isServiceProject())
            return;

        this._unbindUISourceCode(uiSourceCode);
    },

    /**
     * @param {!WebInspector.UISourceCode} uiSourceCode
     */
    _hasMergedToVM: function(uiSourceCode)
    {
        var scripts = this._scriptsForUISourceCode(uiSourceCode);
        if (!scripts.length)
            return;
        for (var i = 0; i < scripts.length; ++i)
            this._debuggerWorkspaceBinding.updateLocations(scripts[i]);
    },

    /**
     * @param {!WebInspector.UISourceCode} uiSourceCode
     */
    _hasDivergedFromVM: function(uiSourceCode)
    {
        var scripts = this._scriptsForUISourceCode(uiSourceCode);
        if (!scripts.length)
            return;
        for (var i = 0; i < scripts.length; ++i)
            this._debuggerWorkspaceBinding.updateLocations(scripts[i]);
    },

    /**
     * @param {!WebInspector.Script} script
     * @return {?WebInspector.UISourceCode}
     */
    _workspaceUISourceCodeForScript: function(script)
    {
        if (script.isAnonymousScript())
            return null;
        return this._networkMapping.uiSourceCodeForURL(script.sourceURL);
    },

    /**
     * @param {!WebInspector.UISourceCode} uiSourceCode
     * @return {!Array.<!WebInspector.Script>}
     */
    _scriptsForUISourceCode: function(uiSourceCode)
    {
        if (!this._networkMapping.networkURL(uiSourceCode))
            return [];
        return this._debuggerModel.scriptsForSourceURL(this._networkMapping.networkURL(uiSourceCode));
    },

    /**
     * @param {!WebInspector.UISourceCode} uiSourceCode
     * @param {!Array.<!WebInspector.Script>} scripts
     */
    _bindUISourceCodeToScripts: function(uiSourceCode, scripts)
    {
        console.assert(scripts.length);
        var scriptFile = new WebInspector.ResourceScriptFile(this, uiSourceCode, scripts);
        this._setScriptFile(uiSourceCode, scriptFile);
        for (var i = 0; i < scripts.length; ++i)
            this._debuggerWorkspaceBinding.updateLocations(scripts[i]);
        this._debuggerWorkspaceBinding.setSourceMapping(this._target, uiSourceCode, this);
        this._boundURLs.add(this._networkMapping.networkURL(uiSourceCode));
    },

    /**
     * @param {!WebInspector.UISourceCode} uiSourceCode
     */
    _unbindUISourceCode: function(uiSourceCode)
    {
        var scriptFile = this.scriptFile(uiSourceCode);
        if (scriptFile) {
            scriptFile.dispose();
            this._setScriptFile(uiSourceCode, null);
        }
        this._debuggerWorkspaceBinding.setSourceMapping(this._target, uiSourceCode, null);
    },

    _debuggerReset: function()
    {
        var boundURLs = this._boundURLs.valuesArray();
        for (var i = 0; i < boundURLs.length; ++i)
        {
            var uiSourceCode = this._networkMapping.uiSourceCodeForURL(boundURLs[i]);
            if (!uiSourceCode)
                continue;
            this._unbindUISourceCode(uiSourceCode);
        }
        this._boundURLs.clear();
    },

    dispose: function()
    {
        this._debuggerReset();
        this._workspace.removeEventListener(WebInspector.Workspace.Events.UISourceCodeAdded, this._uiSourceCodeAdded, this);
        this._workspace.removeEventListener(WebInspector.Workspace.Events.UISourceCodeRemoved, this._uiSourceCodeRemoved, this);
    }

}

/**
 * @constructor
 * @extends {WebInspector.Object}
 * @param {!WebInspector.ResourceScriptMapping} resourceScriptMapping
 * @param {!WebInspector.UISourceCode} uiSourceCode
 * @param {!Array.<!WebInspector.Script>} scripts
 */
WebInspector.ResourceScriptFile = function(resourceScriptMapping, uiSourceCode, scripts)
{
    console.assert(scripts.length);

    this._resourceScriptMapping = resourceScriptMapping;
    this._uiSourceCode = uiSourceCode;

    if (this._uiSourceCode.contentType() === WebInspector.resourceTypes.Script)
        this._script = scripts[0];

    this._uiSourceCode.addEventListener(WebInspector.UISourceCode.Events.WorkingCopyChanged, this._workingCopyChanged, this);
    this._update();
}

WebInspector.ResourceScriptFile.Events = {
    DidMergeToVM: "DidMergeToVM",
    DidDivergeFromVM: "DidDivergeFromVM",
}

WebInspector.ResourceScriptFile.prototype = {
    /**
     * @param {function(?string,!DebuggerAgent.SetScriptSourceError=,!WebInspector.Script=)=} callback
     */
    commitLiveEdit: function(callback)
    {
        var target = this._resourceScriptMapping._target;
        /**
         * @param {?string} error
         * @param {!DebuggerAgent.SetScriptSourceError=} errorData
         * @this {WebInspector.ResourceScriptFile}
         */
        function innerCallback(error, errorData)
        {
            if (!error)
                this._scriptSource = source;
            this._update();
            if (callback)
                callback(error, errorData, this._script);
        }
        if (!this._script)
            return;
        var source = this._uiSourceCode.workingCopy();
        target.debuggerModel.setScriptSource(this._script.scriptId, source, innerCallback.bind(this));
    },

    /**
     * @return {boolean}
     */
    _isDiverged: function()
    {
        if (this._uiSourceCode.isDirty())
            return true;
        if (!this._script)
            return false;
        if (typeof this._scriptSource === "undefined")
            return false;
        if (!this._uiSourceCode.workingCopy().startsWith(this._scriptSource))
            return true;
        var suffix = this._uiSourceCode.workingCopy().substr(this._scriptSource.length);
        return !!suffix.length && !suffix.match(WebInspector.Script.sourceURLRegex);
    },

    /**
     * @param {!WebInspector.Event} event
     */
    _workingCopyChanged: function(event)
    {
        this._update();
    },

    _update: function()
    {
        if (this._isDiverged() && !this._hasDivergedFromVM)
            this._divergeFromVM();
        else if (!this._isDiverged() && this._hasDivergedFromVM)
            this._mergeToVM();
    },

    _divergeFromVM: function()
    {
        this._isDivergingFromVM = true;
        this._resourceScriptMapping._hasDivergedFromVM(this._uiSourceCode);
        delete this._isDivergingFromVM;
        this._hasDivergedFromVM = true;
        this.dispatchEventToListeners(WebInspector.ResourceScriptFile.Events.DidDivergeFromVM, this._uiSourceCode);
    },

    _mergeToVM: function()
    {
        delete this._hasDivergedFromVM;
        this._isMergingToVM = true;
        this._resourceScriptMapping._hasMergedToVM(this._uiSourceCode);
        delete this._isMergingToVM;
        this.dispatchEventToListeners(WebInspector.ResourceScriptFile.Events.DidMergeToVM, this._uiSourceCode);
    },

    /**
     * @return {boolean}
     */
    hasDivergedFromVM: function()
    {
        return this._hasDivergedFromVM;
    },

    /**
     * @return {boolean}
     */
    isDivergingFromVM: function()
    {
        return this._isDivergingFromVM;
    },

    /**
     * @return {boolean}
     */
    isMergingToVM: function()
    {
        return this._isMergingToVM;
    },

    checkMapping: function()
    {
        if (!this._script)
            return;
        if (typeof this._scriptSource !== "undefined")
            return;
        this._script.requestContent(callback.bind(this));

        /**
         * @param {?string} source
         * @this {WebInspector.ResourceScriptFile}
         */
        function callback(source)
        {
            this._scriptSource = source;
            this._update();
        }
    },

    /**
     * @return {?WebInspector.Target}
     */
    target: function()
    {
        if (!this._script)
            return null;
        return this._script.target();
    },

    dispose: function()
    {
        this._uiSourceCode.removeEventListener(WebInspector.UISourceCode.Events.WorkingCopyChanged, this._workingCopyChanged, this);
    },

    /**
     * @param {string} sourceMapURL
     */
    addSourceMapURL: function(sourceMapURL)
    {
        if (!this._script)
            return;
        this._script.addSourceMapURL(sourceMapURL);
    },

    __proto__: WebInspector.Object.prototype
}


text:
package org.apache.wink.server.internal.registry;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import javax.ws.rs.Consumes;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.apache.wink.common.DynamicResource;
import org.apache.wink.common.RuntimeContext;
import org.apache.wink.common.internal.i18n.Messages;
import org.apache.wink.common.internal.lifecycle.LifecycleManagersRegistry;
import org.apache.wink.common.internal.lifecycle.ObjectFactory;
import org.apache.wink.common.internal.registry.Injectable;
import org.apache.wink.common.internal.registry.Injectable.ParamType;
import org.apache.wink.common.internal.registry.metadata.ClassMetadata;
import org.apache.wink.common.internal.registry.metadata.MethodMetadata;
import org.apache.wink.common.internal.registry.metadata.ResourceMetadataCollector;
import org.apache.wink.common.internal.uritemplate.UriTemplateProcessor;
import org.apache.wink.server.internal.ServerCustomProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ResourceRecordFactory {

    private static final Logger                 logger =
                                                           LoggerFactory
                                                               .getLogger(ResourceRecordFactory.class);

    private final LifecycleManagersRegistry     lifecycleManagerRegistry;
    private final Map<Class<?>, ResourceRecord> cacheByClass;

    private Lock                                readersLock;
    private Lock                                writersLock;

    final private boolean                       isStrictConsumesProduces;

    public ResourceRecordFactory(LifecycleManagersRegistry lifecycleManagerRegistry) {
        this(lifecycleManagerRegistry, new Properties());
    }

    public ResourceRecordFactory(LifecycleManagersRegistry lifecycleManagerRegistry,
                                 Properties customProperties) {
        if (lifecycleManagerRegistry == null) {
            throw new NullPointerException("lifecycleManagerRegistry"); //$NON-NLS-1$
        }
        this.lifecycleManagerRegistry = lifecycleManagerRegistry;
        this.cacheByClass = new HashMap<Class<?>, ResourceRecord>();
        ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
        readersLock = readWriteLock.readLock();
        writersLock = readWriteLock.writeLock();

        if (customProperties == null) {
            customProperties = new Properties();
        }

        String value =
            customProperties
                .getProperty(ServerCustomProperties.STRICT_INTERPRET_CONSUMES_PRODUCES_SPEC_CUSTOM_PROPERTY
                                 .getPropertyName(),
                             ServerCustomProperties.STRICT_INTERPRET_CONSUMES_PRODUCES_SPEC_CUSTOM_PROPERTY
                                 .getDefaultValue());
        isStrictConsumesProduces = Boolean.valueOf(value);
    }

    /**
     * Gets a resource record from a cache of records for the specified resource
     * class. If there is no record in the cache, then a new record is created
     *
     * @param cls the resource class to get the record for
     * @return ResourceRecord for the resource class
     */
    public ResourceRecord getResourceRecord(Class<?> cls) {
        readersLock.lock();
        try {
            ResourceRecord record = cacheByClass.get(cls);
            if (record == null) {
                ObjectFactory<?> of = lifecycleManagerRegistry.getObjectFactory(cls);
                readersLock.unlock();
                try {
                    record = createStaticResourceRecord(cls, of);
                } finally {
                    readersLock.lock();
                }
            }
            return record;
        } finally {
            readersLock.unlock();
        }
    }

    /**
     * Gets a root resource record from a cache of records for the specified
     * resource instance. This is a shortcut for {@code
     * getResourceRecord(instance, true)}
     *
     * @param instance the resource instance to get the record for
     * @return ResourceRecord for the resource instance
     */
    public ResourceRecord getResourceRecord(Object instance) {
        return getResourceRecord(instance, true);
    }

    /**
     * Gets a resource record from a cache of records for the specified resource
     * instance. If there is no record in the cache, or if the instance is a
     * dynamic resource, then a new record is created
     *
     * @param instance the resource instance to get the record for
     * @param isRootResource specifies whether the instance is a root resource
     *            (true) or sub-resource (false)
     * @return ResourceRecord for the resource instance
     */
    public ResourceRecord getResourceRecord(Object instance, boolean isRootResource) {
        Class<? extends Object> cls = instance.getClass();
        ResourceRecord record = null;
        readersLock.lock();
        try {
            // if this is a root resource
            if (isRootResource) {
                if (ResourceMetadataCollector.isStaticResource(cls)) {
                    // if this is a static resource, and use cache
                    record = cacheByClass.get(cls);
                    if (record == null) {
                        ObjectFactory<?> of = lifecycleManagerRegistry.getObjectFactory(instance);
                        readersLock.unlock();
                        try {
                            record = createStaticResourceRecord(cls, of);
                        } finally {
                            readersLock.lock();
                        }
                    }
                } else if (ResourceMetadataCollector.isDynamicResource(cls)) {
                    // if this is a dynamic resource, don't use cache
                    ObjectFactory<?> of = lifecycleManagerRegistry.getObjectFactory(instance);
                    readersLock.unlock();
                    try {
                        record = createDynamicResourceRecord((DynamicResource)instance, of);
                    } finally {
                        readersLock.lock();
                    }
                } else {
                    throw new IllegalArgumentException(Messages
                        .getMessage("rootResourceInstanceIsAnInvalidResource", instance.getClass() //$NON-NLS-1$
                            .getCanonicalName()));
                }
            } else {
                // if this is a sub-resource, don't use cache, and don't use the
                // life-cycle manager
                ObjectFactory<?> of = new InstanceObjectFactory<Object>(instance);
                readersLock.unlock();
                try {
                    record = createSubResourceRecord(instance, of);
                } finally {
                    readersLock.lock();
                }
            }
            return record;
        } finally {
            readersLock.unlock();
        }
    }

    private ResourceRecord createStaticResourceRecord(Class<? extends Object> cls,
                                                      ObjectFactory<?> of) {
        ClassMetadata metadata = createMetadata(cls);
        UriTemplateProcessor processor = createUriTemplateProcessor(metadata);
        ResourceRecord record = new ResourceRecord(metadata, of, processor);
        writersLock.lock();
        try {
            // double check so as not to put the same resource twice
            if (cacheByClass.get(cls) == null) {
                cacheByClass.put(cls, record);
            }
        } finally {
            writersLock.unlock();
        }
        return record;
    }

    private ResourceRecord createDynamicResourceRecord(DynamicResource instance, ObjectFactory<?> of) {
        Class<? extends Object> cls = instance.getClass();
        ClassMetadata metadata = createMetadata(cls);
        metadata = fixInstanceMetadata(metadata, instance);
        UriTemplateProcessor processor = createUriTemplateProcessor(metadata);
        return new ResourceRecord(metadata, of, processor);
    }

    private ResourceRecord createSubResourceRecord(Object instance, ObjectFactory<?> of) {
        Class<? extends Object> cls = instance.getClass();
        ClassMetadata metadata = createMetadata(cls);
        return new ResourceRecord(metadata, of, null);
    }

    private ClassMetadata createMetadata(Class<? extends Object> cls) {
        ClassMetadata md = ResourceMetadataCollector.collectMetadata(cls);
        md = fixConsumesAndProduces(md);
        return md;
    }

    private UriTemplateProcessor createUriTemplateProcessor(ClassMetadata metadata) {
        // create the resource path using the parents paths
        StringBuilder path = new StringBuilder();
        // Recursively append parent paths
        appendPathWithParent(metadata, path);
        // create the processor
        return UriTemplateProcessor.newNormalizedInstance(path.toString());
    }

    private void appendPathWithParent(ClassMetadata metadata, StringBuilder pathStr) {
        ResourceRecord parentRecord = getParent(metadata);
        if (parentRecord != null) {
            ClassMetadata parentMetadata = parentRecord.getMetadata();
            appendPathWithParent(parentMetadata, pathStr);
        }
        String path = UriTemplateProcessor.normalizeUri(metadata.getPath());
        if (!path.endsWith("/")) { //$NON-NLS-1$
            pathStr.append("/"); //$NON-NLS-1$
        }
        pathStr.append(path);
    }

    private ResourceRecord getParent(ClassMetadata metadata) {
        Class<?> parent = metadata.getParent();
        Object parentInstance = metadata.getParentInstance();
        ResourceRecord parentRecord = null;
        if (parent != null) {
            parentRecord = getResourceRecord(parent);
        } else if (parentInstance != null) {
            parentRecord = getResourceRecord(parentInstance);
        }
        return parentRecord;
    }

    /**
     * Fixed the metadata to reflect the information stored on the instance of
     * the dynamic resource.
     *
     * @param classMetadata
     * @param instance
     * @return
     */
    private ClassMetadata fixInstanceMetadata(ClassMetadata classMetadata,
                                              DynamicResource dynamicResource) {
        String path = dynamicResource.getPath();
        if (path != null) {
            classMetadata.addPath(path);
            if (logger.isTraceEnabled()) {
                logger.trace("Adding dispatched path from instance: {}", path); //$NON-NLS-1$
            }
        }

        Object parent = dynamicResource.getParent();
        if (parent != null) {
            classMetadata.getParentInstances().add(parent);
            if (logger.isTraceEnabled()) {
                logger.trace("Adding parent beans from instance: {}", parent); //$NON-NLS-1$
            }
        }

        String workspaceTitle = dynamicResource.getWorkspaceTitle();
        if (workspaceTitle != null) {
            classMetadata.setWorkspaceName(workspaceTitle);
        }

        String collectionTitle = dynamicResource.getCollectionTitle();
        if (collectionTitle != null) {
            classMetadata.setCollectionTitle(collectionTitle);
        }
        return classMetadata;
    }

    /**
     * This method will go through each method and "fix" the method metadata to
     * "ignore" inherited {@link Consumes} and {@link Produces} annotations when
     * appropriate. For Produces, if the return type is void, then ignore the
     * Produces annotation. For Consumes, if there are no entity parameters,
     * ignore the Consumes annotation.
     *
     * @param classMetadata
     * @return
     */
    ClassMetadata fixConsumesAndProduces(ClassMetadata classMetadata) {
        logger.trace("fixConsumesAndProduces({}) entry", classMetadata);
        if (isStrictConsumesProduces) {
            logger
                .trace("fixConsumesAndProduces() exit returning because custom property {} is set to true.",
                       ServerCustomProperties.STRICT_INTERPRET_CONSUMES_PRODUCES_SPEC_CUSTOM_PROPERTY
                           .getPropertyName());
            return classMetadata;
        }

        Set<MediaType> produces = classMetadata.getProduces();
        Set<MediaType> consumes = classMetadata.getConsumes();

        Set<MethodMetadata> allMethodMetadata = new HashSet<MethodMetadata>();
        allMethodMetadata.addAll(classMetadata.getResourceMethods());
        allMethodMetadata.addAll(classMetadata.getSubResourceMethods());

        /*
         * Ignore subresource locators because a) they have to return a non-void
         * and b) they aren't allowed to have an entity parameter.
         */

        /* fix the produces */
        for (MethodMetadata methodMetadata : allMethodMetadata) {
            Method method = methodMetadata.getReflectionMethod();
            if (Void.TYPE.equals(method.getReturnType())) {
                if (produces.size() > 0 && methodMetadata.getProduces().equals(produces)) {
                    /*
                     * let's assume this was inherited now. weird case would be
                     * they repeated the annotation values in both the class and
                     * method.
                     */
                    methodMetadata.addProduces(MediaType.WILDCARD_TYPE);
                    logger
                        .trace("Method has a @Produces value but also a void return type so adding a */* to allow any response: {} ",
                               methodMetadata);
                }
            }
        }

        /* fix the consumes */
        for (MethodMetadata methodMetadata : allMethodMetadata) {
            if (consumes.size() > 0 && methodMetadata.getConsumes().equals(consumes)) {
                List<Injectable> params = methodMetadata.getFormalParameters();
                boolean isEntityParamFound = false;
                for (Injectable p : params) {
                    if (ParamType.ENTITY.equals(p.getParamType())) {
                        isEntityParamFound = true;
                    }
                }
                /*
                 * let's assume this was inherited now. weird case would be they
                 * repeated the annotation values in both the class and method.
                 */
                if (!isEntityParamFound) {
                    methodMetadata.addConsumes(MediaType.WILDCARD_TYPE);
                    logger
                        .trace("Method has a @Consumes value but no entity parameter so adding a */* to allow any request: {} ",
                               methodMetadata);
                }
            }
        }

        logger.trace("fixConsumesAndProduces() exit returning {}", classMetadata);
        return classMetadata;
    }

    private static class InstanceObjectFactory<T> implements ObjectFactory<T> {

        private final T object;

        public InstanceObjectFactory(T object) {
            this.object = object;
        }

        public T getInstance(RuntimeContext context) {
            return object;
        }

        @SuppressWarnings("unchecked")
        public Class<T> getInstanceClass() {
            return (Class<T>)object.getClass();
        }

        @Override
        public String toString() {
            return String.format("InstanceObjectFactory: %s", getInstanceClass()); //$NON-NLS-1$
        }

        public void releaseInstance(T instance, RuntimeContext context) {
            /* do nothing */
        }

        public void releaseAll(RuntimeContext context) {
            /* do nothing */
        }
    }

}


text:
<?php namespace Raahul\LarryFour\Command;

use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;

use \Raahul\LarryFour\Writer;
use \Raahul\LarryFour\MigrationList;
use \Raahul\LarryFour\Generator\MigrationGenerator;
use \Raahul\LarryFour\DbParser;
use \Raahul\SchemaExtractor\SchemaExtractor;
use \Illuminate\Support\Facades\DB;

class GenerateFromDb extends Command {

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'larry:fromdb';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generate migration files from the active database';

    /**
     * Instance of the Larry Writer class
     *
     * @var \Raahul\LarryFour\Writer
     */
    protected $larryWriter;

    /**
     * Instance of the migration generator
     * @var \Raahul\LarryFour\Generator\MigrationGenerator
     */
    protected $migrationGenerator;

    /**
     * Instance of the database parser
     * @var \Raahul\LarryFour\DbParser
     */
    protected $dbParser;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();

        // Initialize the migration generator
        $this->migrationGenerator = new MigrationGenerator();

        // Initial the paths to the model and migration folder, and then the
        // writer class
        $modelPath = app_path() . '/models/';
        $migrationPath = app_path() . '/database/migrations/';

        $this->larryWriter = new Writer($modelPath, $migrationPath);

        // Initialize the database parser
        // TODO: Use DB::getDriverName() instead of hardcoded database driver name
        // PostgreSQL isn't support by SchemaExtractor package. So we force it to use 'mysql' driver.
        $this->dbParser = new DbParser(new MigrationList(), new SchemaExtractor(), 'mysql');
    }

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function fire()
    {
        // Verify whether we're running on a supported driver
        $this->verifyDriver();

        // Get all tables to be processed
        $tables = $this->getAllTablesToBeProcessed();

        // Print it for confirmation
        $this->info("Migrations for the following tables will be created:");
        $this->info(implode("\n", $tables));
        $confirm = $this->confirm('Do you wish to continue? [yes|no]', false);

        if (!$confirm) die();

        // Now, let's start processing
        $tablesData = array();
        foreach ($tables as $table)
        {
            if( DB::getDriverName() === 'mysql' ) {
                $tablesData[ $table ] = DB::select("DESCRIBE `$table`");
            } else if( DB::getDriverName() === 'pgsql' ) {
                // PostgreSQL port of MySQL DESCRIBE statement
                $tablesData[ $table ] = DB::select(
                    "SELECT a.oid, c.column_name AS \"Field\", COALESCE(c.column_default, 'NULL') AS \"Default\", c.is_nullable AS \"Null\",
                        CASE
                          WHEN c.udt_name = 'bool' THEN 'boolean'
                          WHEN c.udt_name = 'int2' THEN 'smallint' || COALESCE(NULLIF('('|| COALESCE(c.character_maximum_length::varchar, '') || ')', '()'), '')
                          WHEN c.udt_name = 'int4' THEN 'int'
                          WHEN c.udt_name = 'int8' THEN 'bigint'
                          WHEN c.udt_name LIKE 'float_' THEN 'float'
                          WHEN c.udt_name = 'timetz' THEN 'time'
                          WHEN c.udt_name = 'timestamptz' THEN 'timestamp'
                          WHEN c.udt_name ~ '_?bytea' THEN 'blob' || COALESCE(NULLIF('('|| COALESCE(c.character_maximum_length::varchar, '') || ')', '()'), '')
                          WHEN c.udt_name = 'numeric' THEN 'decimal' || COALESCE(NULLIF('('|| COALESCE(c.numeric_precision::varchar, '') || ',' || COALESCE(c.numeric_scale::varchar, '') || ')', '(,)'), '')
                          WHEN p.consrc LIKE '%ARRAY[%]%' THEN 'enum' || '(' || regexp_replace(regexp_replace(p.consrc, '.+ARRAY\[([^\[\]]+)\].+', '\\1'), '::[a-z0-9 ]+', '', 'g') || ')'
                        ELSE c.udt_name || COALESCE(NULLIF('(' || COALESCE(c.character_maximum_length::varchar, '') ||')', '()'), '')
                        END AS \"Type\",
                        CASE
                          WHEN c.column_default LIKE 'nextval(%)' THEN 'auto_increment'
                        END AS \"Extra\",
                        CASE
                          WHEN p.contype = 'p' THEN 'PRI'
                          WHEN p.contype = 'u' AND p.conkey::text LIKE '{_,%}' THEN 'MUL'
                          WHEN p.contype = 'u' THEN 'UNI'
                        END AS \"Key\"
                        FROM INFORMATION_SCHEMA.COLUMNS c
                        INNER JOIN (SELECT attrelid AS oid, attname FROM pg_attribute
                          WHERE attrelid = ( SELECT oid FROM pg_class WHERE relname = '$table') ) a ON a.attname = c.column_name
                          LEFT JOIN pg_constraint p ON p.conrelid = a.oid AND c.dtd_identifier::integer = ANY (p.conkey )
                        WHERE c.table_name = '$table'"
                );
            }
        }

        // Get migrations
        $migrationList = $this->dbParser->parse($tablesData);

        // Generate migrations
        $this->generateMigrations($migrationList->all());
    }

    /**
     * This command has to be overriden in individual commands to either generate
     * models or migrations or both
     *
     * @param  array $parsed An array of ModelList and MigrationList
     * @return void
     */
    protected function runCommand($parsed)
    {
        throw new \Exception("The runCommand function has to be overriden.");
    }

    /**
     * Verify if the database that we're using is supported by Larry
     */
    protected function verifyDriver()
    {
        $driver = DB::getDriverName();
        $supported = array('mysql', 'pgsql');
        if ( !in_array($driver, $supported)  )
        {
            $this->error("You are using an unsupported database driver. Only the following drivers are supported for now: " . implode(", ", $supported));
        }
    }

    /**
     * Get an array of tables that will have to be processed in the end
     * @return array List of table names
     */
    protected function getAllTablesToBeProcessed()
    {
        // Get all the tables from the database
        $allTables = $this->getAllTables($this->getDbName());

        // Get --only tables if any
        $onlyTables = $this->getOnlyTables();

        // Get --except tables if any
        $exceptTables = $this->getExceptTables();

        // If the --only parameter is present, do some error checking on whether
        // those tables exist
        if ($onlyTables)
        {
            foreach ($onlyTables as $t)
            {
                if (!in_array($t, $allTables))
                {
                    $this->error("\nTable {$t} is not present in your database.\n");
                    die();
                }
            }

            return $onlyTables;
        }

        // If the --except paramter is present, remove those tables from the allTables
        // array and return
        // We also remove the laravel `migrations` table
        else if ($exceptTables)
        {
            return array_filter($allTables, function($element) use($exceptTables) {
                if ( (in_array($element, $exceptTables))
                    or ($element == 'migrations') )
                {
                    return false;
                }

                return true;
            });
        }

        // In the normal case, we only remove laravel's migration table
        else
        {
            return array_filter($allTables, function($element) {
                if ( $element == 'migrations' )
                {
                    return false;
                }

                return true;
            });
        }
    }

    /**
     * Get the name of the selected database
     * @return string Database name
     */
    protected function getDbName()
    {
        if( DB::getDriverName() === 'mysql' ) {
            $select = DB::select('SELECT database() as dbname');
        } else if( DB::getDriverName() === 'pgsql' ) {
            $select = DB::select('SELECT current_database() as dbname');
        }

        return $select[0]->dbname;
    }

    /**
     * Get all the tables present in the database
     * @param  string $dbname The name of the database
     * @return array          An array of table names present
     */
    protected function getAllTables($dbname)
    {
        $tables = array();
        if( DB::getDriverName() === 'mysql' ) {
            $tableRows = DB::select('SHOW tables');
            $column = "Tables_in_{$dbname}";

            foreach ($tableRows as $row)
            {
                $tables[] = $row->$column;
            }
        } else if( DB::getDriverName() === 'pgsql' ) {
            $tableRows = DB::select(
                "SELECT table_name FROM information_schema.tables
                  WHERE table_type = 'BASE TABLE'
                  AND table_schema = 'public'
                  ORDER BY table_type, table_name"
            );
            foreach ($tableRows as $row)
            {
                $tables[] = $row->table_name;
            }
        }
        return $tables;
    }

    /**
     * Get the tables marked by the --only parameters, if any
     * @return array An array of table names marked by --only parameter
     */
    protected function getOnlyTables()
    {
        $onlyTables = explode(",", $this->option('only'));
        return array_filter( array_map('trim', $onlyTables) );
    }

    /**
     * Get the tables marked by the --except parameters, if any
     * @return array An array of table names marked by --except parameter
     */
    protected function getExceptTables()
    {
        $exceptTables = explode(",", $this->option('except'));
        return array_filter( array_map('trim', $exceptTables) );
    }

    /**
     * Generates all the migrations, given a list of migrations
     * @param  array $migrations An array of migration objects
     */
    protected function generateMigrations($migrations)
    {
        foreach ($migrations as $migration)
        {
            $filename = date('Y_m_d_His') . '_create_' . $migration->tableName . '_table.php';
            $this->larryWriter->writeMigration(
                $this->migrationGenerator->generate($migration),
                $filename
            );
            $this->info("Wrote migration: {$filename}");
        }
    }

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments()
    {
        return array();
    }

    /**
     * Get the console command options.
     *
     * @return array
     */
    protected function getOptions()
    {
        return array(
            array('only', '', InputOption::VALUE_REQUIRED, 'Tables that should be processed, while rest excluded'),
            array('except', '', InputOption::VALUE_REQUIRED, 'Tables that should excluded'),
        );
    }

}


text:
all:
	mkdir -p bin
	$(CC) -std=c99 -Wall -o bin/opensnap src/opensnap.c -lX11 `pkg-config gtk+-3.0 --cflags` `pkg-config gtk+-3.0 --libs`
install:
	install bin/opensnap /usr/bin/
	install -dm0755 /etc/opensnap
	for file in `ls sample_configs/` ; do \
		install -m0644 "sample_configs/$$file" "/etc/opensnap/$$file" ; \
	done
uninstall:
	rm -ri /etc/opensnap/
	rm -i /usr/bin/opensnap
clean:
	rm bin/opensnap


text:
using System;
using System.Runtime.InteropServices;
using OpenLiveWriter.Interop.Windows;

namespace OpenLiveWriter.Interop.Com.ActiveDocuments
{
    /// <summary>
    ///
    /// </summary>
    [ComImport]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    [Guid("00000113-0000-0000-C000-000000000046")]
    public interface IOleInPlaceObject
    {
        void GetWindow(
            [Out] out IntPtr phwnd);

        void ContextSensitiveHelp(
            [In, MarshalAs(UnmanagedType.Bool)] bool fEnterMode);

        void InPlaceDeactivate();

        void UIDeactivate();

        void SetObjectRects(
            [In] ref RECT lprcPosRect,
            [In] ref RECT lprcClipRect);

        [PreserveSig]
        int ReactivateAndUndo();
    }
}