package com.yoshione.fingen;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import com.yoshione.fingen.adapter.AdapterSms;
import com.yoshione.fingen.dao.SmsDAO;
import com.yoshione.fingen.interfaces.IAbstractModel;
import com.yoshione.fingen.model.Events;
import com.yoshione.fingen.model.Sms;
import com.yoshione.fingen.model.Transaction;
import com.yoshione.fingen.utils.PrefUtils;
import com.yoshione.fingen.utils.RequestCodes;
import com.yoshione.fingen.widgets.ContextMenuRecyclerView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * A placeholder fragment containing a simple view.
 */
public class FragmentSmsList extends Fragment {
    @BindView(R.id.recycler_view)  ContextMenuRecyclerView mRecyclerView;
    private AdapterSms mAdapter;
//    private List<Sms> mSmsList;

    public FragmentSmsList() {
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        EventBus.getDefault().unregister(this);
        super.onStop();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_sms_list, container, false);
        ButterKnife.bind(this,view);

        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);

        SmsDAO mSmsDAO = SmsDAO.getInstance(getActivity());

        //adapter
        List<Sms> smses;
        try {
            smses = mSmsDAO.getAllSmss();
        } catch (Exception e) {
            smses = new ArrayList<>();
        }
        mAdapter = new AdapterSms(smses,getActivity());
        mAdapter.setSmsEventsListener(new AdapterSms.SmsEventsListener() {
            @Override
            public void OnSmsClick(View view1) {
                int position = mRecyclerView.getChildAdapterPosition(view1);
                Intent intent = new Intent(FragmentSmsList.this.getActivity(), ActivityEditTransaction.class);
                SmsDAO smsDAO = SmsDAO.getInstance(FragmentSmsList.this.getActivity());
                Sms sms;
                try {
                    sms = smsDAO.getAllSmss().get(position);
                } catch (Exception e) {
                    return;
                }
                intent.putExtra("sms", sms);
                intent.putExtra("transaction", new Transaction(PrefUtils.getDefDepID(getActivity())));
                FragmentSmsList.this.startActivityForResult(intent, RequestCodes.REQUEST_CODE_EDIT_TRANSACTION);
            }
        });

        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(mAdapter);
        registerForContextMenu(mRecyclerView);

        return view;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RequestCodes.REQUEST_CODE_EDIT_TRANSACTION & resultCode == Activity.RESULT_OK) {
            int smsListSize;
            try {
                smsListSize = SmsDAO.getInstance(getActivity()).getAllSmss().size();
            } catch (Exception e) {
                smsListSize = 0;
            }
            if (smsListSize == 0) {
                getActivity().finish();
            } else {
                fullUpdate();
            }
        } else {
            fullUpdate();
        }
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        // Inflate Menu from xml resource
        MenuInflater menuInflater = getActivity().getMenuInflater();
        menuInflater.inflate(R.menu.context_menu_sms_list, menu);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        ContextMenuRecyclerView.RecyclerContextMenuInfo info = (ContextMenuRecyclerView.RecyclerContextMenuInfo) item.getMenuInfo();
        SmsDAO smsDAO = SmsDAO.getInstance(getActivity());
        switch (item.getItemId()){
            case R.id.action_create_transaction:{
                Intent intent = new Intent(getActivity(), ActivityEditTransaction.class);
                intent.putExtra("sms", smsDAO.getSmsByID(info.id));
                startActivityForResult(intent, RequestCodes.REQUEST_CODE_EDIT_TRANSACTION);
                break;
            }
            case R.id.action_delete:{
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setTitle(R.string.ttl_confirm_action);
                builder.setMessage(R.string.ttl_delete_sms_confirmation);
                List<Sms> smses = new ArrayList<>();
                smses.add(smsDAO.getSmsByID(info.id));

                OnDeleteSmsDialogOkClickListener clickListener = new OnDeleteSmsDialogOkClickListener(smses);
                builder.setPositiveButton("OK", clickListener);
                builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });

                builder.show();
                break;
            }
            case R.id.action_delete_all:{
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setTitle(R.string.ttl_confirm_action);
                builder.setMessage(R.string.ttl_delete_all_sms_confirmation);
                List<Sms> smses;
                SmsDAO smsDAO1 = SmsDAO.getInstance(getActivity());
                try {
                    smses = smsDAO1.getAllSmss();
                } catch (Exception e) {
                    smses = new ArrayList<>();
                }

                OnDeleteSmsDialogOkClickListener clickListener = new OnDeleteSmsDialogOkClickListener(smses);
                // Set up the buttons
                builder.setPositiveButton("OK", clickListener);
                builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });

                builder.show();
                break;
            }
        }
        return true;
    }

    private class OnDeleteSmsDialogOkClickListener implements DialogInterface.OnClickListener{
        private final List<Sms> mSmsList;

        OnDeleteSmsDialogOkClickListener(List<Sms> smsList) {
            this.mSmsList = smsList;
        }

        @Override
        public void onClick(DialogInterface dialog, int which) {
            SmsDAO smsDAO = SmsDAO.getInstance(getActivity());

            for (Sms sms : mSmsList) {
                smsDAO.deleteModel(sms, true, getActivity());
            }

        }
    }

     @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
     public void onEvent(Events.EventOnModelChanged event) {
         if (event.getModelType() == IAbstractModel.MODEL_TYPE_SMS) {
             fullUpdate();
         }
    }

    private void fullUpdate(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                mRecyclerView.post(new Runnable() {
                    @Override
                    public void run() {
                        SmsDAO smsDAO = SmsDAO.getInstance(FragmentSmsList.this.getActivity());
                        List<Sms> smsList;
                        try {
                            smsList = smsDAO.getAllSmss();
                        } catch (Exception e) {
                            smsList = new ArrayList<>();
                        }
                        mAdapter.setSmsList(smsList);
                        mAdapter.notifyDataSetChanged();
                    }
                });
            }
        }).start();

    }
}


package org.zstack.sdk;

import java.util.HashMap;
import java.util.Map;
import org.zstack.sdk.*;

public class QueryConnectionAccessPointFromLocalAction extends QueryAction {

    private static final HashMap<String, Parameter> parameterMap = new HashMap<>();

    private static final HashMap<String, Parameter> nonAPIParameterMap = new HashMap<>();

    public static class Result {
        public ErrorCode error;
        public org.zstack.sdk.QueryConnectionAccessPointFromLocalResult value;

        public Result throwExceptionIfError() {
            if (error != null) {
                throw new ApiException(
                    String.format("error[code: %s, description: %s, details: %s]", error.code, error.description, error.details)
                );
            }

            return this;
        }
    }

    private Result makeResult(ApiResult res) {
        Result ret = new Result();
        if (res.error != null) {
            ret.error = res.error;
            return ret;
        }

        org.zstack.sdk.QueryConnectionAccessPointFromLocalResult value = res.getResult(org.zstack.sdk.QueryConnectionAccessPointFromLocalResult.class);
        ret.value = value == null ? new org.zstack.sdk.QueryConnectionAccessPointFromLocalResult() : value;

        return ret;
    }

    public Result call() {
        ApiResult res = ZSClient.call(this);
        return makeResult(res);
    }

    public void call(final Completion<Result> completion) {
        ZSClient.call(this, new InternalCompletion() {
            @Override
            public void complete(ApiResult res) {
                completion.complete(makeResult(res));
            }
        });
    }

    protected Map<String, Parameter> getParameterMap() {
        return parameterMap;
    }

    protected Map<String, Parameter> getNonAPIParameterMap() {
        return nonAPIParameterMap;
    }

    protected RestInfo getRestInfo() {
        RestInfo info = new RestInfo();
        info.httpMethod = "GET";
        info.path = "/hybrid/aliyun/access-point";
        info.needSession = true;
        info.needPoll = false;
        info.parameterName = "";
        return info;
    }

}


// Code generated by cmd/cgo -godefs; DO NOT EDIT.
// cgo -godefs defs_linux.go

package ipv6

const (
	sysIPV6_ADDRFORM       = 0x1
	sysIPV6_2292PKTINFO    = 0x2
	sysIPV6_2292HOPOPTS    = 0x3
	sysIPV6_2292DSTOPTS    = 0x4
	sysIPV6_2292RTHDR      = 0x5
	sysIPV6_2292PKTOPTIONS = 0x6
	sysIPV6_CHECKSUM       = 0x7
	sysIPV6_2292HOPLIMIT   = 0x8
	sysIPV6_NEXTHOP        = 0x9
	sysIPV6_FLOWINFO       = 0xb

	sysIPV6_UNICAST_HOPS        = 0x10
	sysIPV6_MULTICAST_IF        = 0x11
	sysIPV6_MULTICAST_HOPS      = 0x12
	sysIPV6_MULTICAST_LOOP      = 0x13
	sysIPV6_ADD_MEMBERSHIP      = 0x14
	sysIPV6_DROP_MEMBERSHIP     = 0x15
	sysMCAST_JOIN_GROUP         = 0x2a
	sysMCAST_LEAVE_GROUP        = 0x2d
	sysMCAST_JOIN_SOURCE_GROUP  = 0x2e
	sysMCAST_LEAVE_SOURCE_GROUP = 0x2f
	sysMCAST_BLOCK_SOURCE       = 0x2b
	sysMCAST_UNBLOCK_SOURCE     = 0x2c
	sysMCAST_MSFILTER           = 0x30
	sysIPV6_ROUTER_ALERT        = 0x16
	sysIPV6_MTU_DISCOVER        = 0x17
	sysIPV6_MTU                 = 0x18
	sysIPV6_RECVERR             = 0x19
	sysIPV6_V6ONLY              = 0x1a
	sysIPV6_JOIN_ANYCAST        = 0x1b
	sysIPV6_LEAVE_ANYCAST       = 0x1c

	sysIPV6_FLOWLABEL_MGR = 0x20
	sysIPV6_FLOWINFO_SEND = 0x21

	sysIPV6_IPSEC_POLICY = 0x22
	sysIPV6_XFRM_POLICY  = 0x23

	sysIPV6_RECVPKTINFO  = 0x31
	sysIPV6_PKTINFO      = 0x32
	sysIPV6_RECVHOPLIMIT = 0x33
	sysIPV6_HOPLIMIT     = 0x34
	sysIPV6_RECVHOPOPTS  = 0x35
	sysIPV6_HOPOPTS      = 0x36
	sysIPV6_RTHDRDSTOPTS = 0x37
	sysIPV6_RECVRTHDR    = 0x38
	sysIPV6_RTHDR        = 0x39
	sysIPV6_RECVDSTOPTS  = 0x3a
	sysIPV6_DSTOPTS      = 0x3b
	sysIPV6_RECVPATHMTU  = 0x3c
	sysIPV6_PATHMTU      = 0x3d
	sysIPV6_DONTFRAG     = 0x3e

	sysIPV6_RECVTCLASS = 0x42
	sysIPV6_TCLASS     = 0x43

	sysIPV6_ADDR_PREFERENCES = 0x48

	sysIPV6_PREFER_SRC_TMP            = 0x1
	sysIPV6_PREFER_SRC_PUBLIC         = 0x2
	sysIPV6_PREFER_SRC_PUBTMP_DEFAULT = 0x100
	sysIPV6_PREFER_SRC_COA            = 0x4
	sysIPV6_PREFER_SRC_HOME           = 0x400
	sysIPV6_PREFER_SRC_CGA            = 0x8
	sysIPV6_PREFER_SRC_NONCGA         = 0x800

	sysIPV6_MINHOPCOUNT = 0x49

	sysIPV6_ORIGDSTADDR     = 0x4a
	sysIPV6_RECVORIGDSTADDR = 0x4a
	sysIPV6_TRANSPARENT     = 0x4b
	sysIPV6_UNICAST_IF      = 0x4c

	sysICMPV6_FILTER = 0x1

	sysICMPV6_FILTER_BLOCK       = 0x1
	sysICMPV6_FILTER_PASS        = 0x2
	sysICMPV6_FILTER_BLOCKOTHERS = 0x3
	sysICMPV6_FILTER_PASSONLY    = 0x4

	sysSOL_SOCKET       = 0x1
	sysSO_ATTACH_FILTER = 0x1a

	sizeofKernelSockaddrStorage = 0x80
	sizeofSockaddrInet6         = 0x1c
	sizeofInet6Pktinfo          = 0x14
	sizeofIPv6Mtuinfo           = 0x20
	sizeofIPv6FlowlabelReq      = 0x20

	sizeofIPv6Mreq       = 0x14
	sizeofGroupReq       = 0x84
	sizeofGroupSourceReq = 0x104

	sizeofICMPv6Filter = 0x20

	sizeofSockFprog = 0x8
)

type kernelSockaddrStorage struct {
	Family  uint16
	X__data [126]int8
}

type sockaddrInet6 struct {
	Family   uint16
	Port     uint16
	Flowinfo uint32
	Addr     [16]byte /* in6_addr */
	Scope_id uint32
}

type inet6Pktinfo struct {
	Addr    [16]byte /* in6_addr */
	Ifindex int32
}

type ipv6Mtuinfo struct {
	Addr sockaddrInet6
	Mtu  uint32
}

type ipv6FlowlabelReq struct {
	Dst        [16]byte /* in6_addr */
	Label      uint32
	Action     uint8
	Share      uint8
	Flags      uint16
	Expires    uint16
	Linger     uint16
	X__flr_pad uint32
}

type ipv6Mreq struct {
	Multiaddr [16]byte /* in6_addr */
	Ifindex   int32
}

type groupReq struct {
	Interface uint32
	Group     kernelSockaddrStorage
}

type groupSourceReq struct {
	Interface uint32
	Group     kernelSockaddrStorage
	Source    kernelSockaddrStorage
}

type icmpv6Filter struct {
	Data [8]uint32
}

type sockFProg struct {
	Len       uint16
	Pad_cgo_0 [2]byte
	Filter    *sockFilter
}

type sockFilter struct {
	Code uint16
	Jt   uint8
	Jf   uint8
	K    uint32
}


import { LokiEventEmitter } from "./event_emitter";
import { UniqueIndex } from "./unique_index";
import { ResultSet } from "./result_set";
import { DynamicView } from "./dynamic_view";
import { IRangedIndex } from "./ranged_indexes";
import { CloneMethod } from "./clone";
import { Doc, Dict } from "../../common/types";
import { FullTextSearch } from "../../full-text-search/src/full_text_search";
import { Analyzer } from "../../full-text-search/src/analyzer/analyzer";
/**
 * Collection class that handles documents of same type
 * @extends LokiEventEmitter
 * @param <TData> - the data type
 * @param <TNested> - nested properties of data type
 */
export declare class Collection<TData extends object = object, TNested extends object = object, T extends TData & TNested = TData & TNested> extends LokiEventEmitter {
    name: string;
    _data: Doc<T>[];
    private _idIndex;
    _rangedIndexes: {
        [P in keyof T]?: Collection.RangedIndexMeta;
    };
    _lokimap: {
        [$loki: number]: Doc<T>;
    };
    _unindexedSortComparator: string;
    _defaultLokiOperatorPackage: string;
    /**
     * Unique constraints contain duplicate object references, so they are not persisted.
     * We will keep track of properties which have unique constraints applied here, and regenerate on load.
     */
    _constraints: {
        unique: {
            [P in keyof T]?: UniqueIndex;
        };
    };
    /**
     * Transforms will be used to store frequently used query chains as a series of steps which itself can be stored along
     * with the database.
     */
    _transforms: Dict<Collection.Transform<T>[]>;
    /**
     * In autosave scenarios we will use collection level dirty flags to determine whether save is needed.
     * currently, if any collection is dirty we will autosave the whole database if autosave is configured.
     * Defaulting to true since this is called from addCollection and adding a collection should trigger save.
     */
    _dirty: boolean;
    private _cached;
    /**
     * Is collection transactional.
     */
    private _transactional;
    /**
     * Options to clone objects when inserting them.
     */
    _cloneObjects: boolean;
    /**
     * Default clone method (if enabled) is parse-stringify.
     */
    _cloneMethod: CloneMethod;
    /**
     * If set to true we will not maintain a meta property for a document.
     */
    private _disableMeta;
    /**
     * Disable track changes.
     */
    private _disableChangesApi;
    /**
     * Disable delta update object style on changes.
     */
    _disableDeltaChangesApi: boolean;
    /**
     * By default, if you insert a document with a Date value for an indexed property, we will convert that value to number.
     */
    private _serializableIndexes;
    /**
     * Name of path of used nested properties.
     */
    private _nestedProperties;
    /**
     * Option to activate a cleaner daemon - clears "aged" documents at set intervals.
     */
    _ttl: Collection.TTL;
    private _maxId;
    private _dynamicViews;
    /**
     * Changes are tracked by collection and aggregated by the db.
     */
    private _changes;
    /**
     * stages: a map of uniquely identified 'stages', which hold copies of objects to be
     * manipulated without affecting the data in the original collection
     */
    private _stages;
    private _commitLog;
    _fullTextSearch: FullTextSearch;
    /**
     * @param {string} name - collection name
     * @param {(object)} [options={}] - a configuration object
     * @param {string[]} [options.unique=[]] - array of property names to define unique constraints for
     * @param {string[]} [options.exact=[]] - array of property names to define exact constraints for
     * @param {RangedIndexOptions} [options.rangedIndexes] - configuration object for ranged indexes
     * @param {boolean} [options.asyncListeners=false] - whether listeners are invoked asynchronously
     * @param {boolean} [options.disableMeta=false] - set to true to disable meta property on documents
     * @param {boolean} [options.disableChangesApi=true] - set to false to enable Changes API
     * @param {boolean} [options.disableDeltaChangesApi=true] - set to false to enable Delta Changes API (requires Changes API, forces cloning)
     * @param {boolean} [options.clone=false] - specify whether inserts and queries clone to/from user
     * @param {boolean} [options.serializableIndexes=true] - converts date values on binary indexed property values are serializable
     * @param {string} [options.cloneMethod="deep"] - the clone method
     * @param {number} [options.transactional=false] - ?
     * @param {number} [options.ttl=] - age of document (in ms.) before document is considered aged/stale.
     * @param {number} [options.ttlInterval=] - time interval for clearing out 'aged' documents; not set by default
     * @param {string} [options.unindexedSortComparator="js"] "js", "abstract", "abstract-date", "loki" or other registered comparator name
     * @param {string} [options.defaultLokiOperatorPackage="js"] "js", "loki", "comparator" (or user defined) query ops package
     * @param {FullTextSearch.FieldOptions} [options.fullTextSearch=] - the full-text search options
     * @see {@link Loki#addCollection} for normal creation of collections
     */
    constructor(name: string, options?: Collection.Options<TData, TNested>);
    toJSON(): Collection.Serialized;
    static fromJSONObject(obj: Collection.Serialized, options?: Collection.DeserializeOptions): Collection<any, object, any>;
    /**
     * Adds a named collection transform to the collection
     * @param {string} name - name to associate with transform
     * @param {array} transform - an array of transformation 'step' objects to save into the collection
     */
    addTransform(name: string, transform: Collection.Transform<T>[]): void;
    /**
     * Retrieves a named transform from the collection.
     * @param {string} name - name of the transform to lookup.
     */
    getTransform(name: string): Collection.Transform<T>[];
    /**
     * Updates a named collection transform to the collection
     * @param {string} name - name to associate with transform
     * @param {object} transform - a transformation object to save into collection
     */
    setTransform(name: string, transform: Collection.Transform<T>[]): void;
    /**
     * Removes a named collection transform from the collection
     * @param {string} name - name of collection transform to remove
     */
    removeTransform(name: string): void;
    private setTTL(age, interval);
    /**
     * Create a row filter that covers all documents in the collection.
     */
    _prepareFullDocIndex(): number[];
    /**
     * Ensure rangedIndex of a field.
     * @param field
     * @param indexTypeName
     * @param comparatorName
     */
    ensureIndex(field: string, indexTypeName?: string, comparatorName?: string): void;
    /**
     * Ensure rangedIndex of a field.
     * @param field Property to create an index on (need to look into contraining on keyof T)
     * @param indexTypeName Name of IndexType factory within (global?) hashmap to create IRangedIndex from
     * @param comparatorName Name of Comparator within (global?) hashmap
     */
    ensureRangedIndex(field: string, indexTypeName?: string, comparatorName?: string): void;
    ensureUniqueIndex(field: keyof T): UniqueIndex;
    /**
     * Quickly determine number of documents in collection (or query)
     * @param {object} query - (optional) query object to count results of
     * @returns {number} number of documents in the collection
     */
    count(query?: ResultSet.Query<Doc<T>>): number;
    /**
     * Rebuild idIndex
     */
    private _ensureId();
    /**
     * Add a dynamic view to the collection
     * @param {string} name - name of dynamic view to add
     * @param {object} options - (optional) options to configure dynamic view with
     * @param {boolean} [options.persistent=false] - indicates if view is to main internal results array in 'resultdata'
     * @param {string} [options.sortPriority=SortPriority.PASSIVE] - the sort priority
     * @param {number} options.minRebuildInterval - minimum rebuild interval (need clarification to docs here)
     * @returns {DynamicView} reference to the dynamic view added
     **/
    addDynamicView(name: string, options?: DynamicView.Options): DynamicView<T>;
    /**
     * Remove a dynamic view from the collection
     * @param {string} name - name of dynamic view to remove
     **/
    removeDynamicView(name: string): void;
    /**
     * Look up dynamic view reference from within the collection
     * @param {string} name - name of dynamic view to retrieve reference of
     * @returns {DynamicView} A reference to the dynamic view with that name
     **/
    getDynamicView(name: string): DynamicView<T>;
    /**
     * Applies a 'mongo-like' find query object and passes all results to an update function.
     * @param {object} filterObject - the 'mongo-like' query object
     * @param {function} updateFunction - the update function
     */
    findAndUpdate(filterObject: ResultSet.Query<Doc<T>>, updateFunction: (obj: Doc<T>) => any): void;
    /**
     * Applies a 'mongo-like' find query object removes all documents which match that filter.
     * @param {object} filterObject - 'mongo-like' query object
     */
    findAndRemove(filterObject: ResultSet.Query<Doc<T>>): void;
    /**
     * Adds object(s) to collection, ensure object(s) have meta properties, clone it if necessary, etc.
     * @param {(object|array)} doc - the document (or array of documents) to be inserted
     * @returns {(object|array)} document or documents inserted
     */
    insert(doc: TData): Doc<T>;
    insert(doc: TData[]): Doc<T>[];
    /**
     * Adds a single object, ensures it has meta properties, clone it if necessary, etc.
     * @param {object} doc - the document to be inserted
     * @param {boolean} bulkInsert - quiet pre-insert and insert event emits
     * @returns {object} document or 'undefined' if there was a problem inserting it
     */
    insertOne(doc: TData, bulkInsert?: boolean): Doc<T>;
    /**
     * Refers nested properties of an object to the root of it.
     * @param {T} data - the object
     * @returns {T & TNested} the object with nested properties
     * @hidden
     */
    _defineNestedProperties<U extends TData>(data: U): U & TNested;
    /**
     * Empties the collection.
     * @param {boolean} [removeIndices=false] - remove indices
     */
    clear({removeIndices: removeIndices}?: {
        removeIndices?: boolean;
    }): void;
    /**
     * Updates an object and notifies collection that the document has changed.
     * @param {object} doc - document to update within the collection
     */
    update(doc: Doc<T> | Doc<T>[]): void;
    /**
     * Add object to collection
     */
    private _add(obj);
    /**
     * Applies a filter function and passes all results to an update function.
     * @param {function} filterFunction - the filter function
     * @param {function} updateFunction - the update function
     */
    updateWhere(filterFunction: (obj: Doc<T>) => boolean, updateFunction: (obj: Doc<T>) => Doc<T>): void;
    /**
     * Remove all documents matching supplied filter function.
     * @param {function} filterFunction - the filter function
     */
    removeWhere(filterFunction: (obj: Doc<T>) => boolean): void;
    removeDataOnly(): void;
    /**
     * Remove a document from the collection
     * @param {number|object} doc - document to remove from collection
     */
    remove(doc: number | Doc<T> | Doc<T>[]): void;
    /**
     * Returns all changes.
     * @returns {Collection.Change[]}
     */
    getChanges(): Collection.Change[];
    /**
     * Enables/disables changes api.
     * @param {boolean} disableChangesApi
     * @param {boolean} disableDeltaChangesApi
     */
    setChangesApi(disableChangesApi: boolean, disableDeltaChangesApi?: boolean): void;
    /**
     * Clears all the changes.
     */
    flushChanges(): void;
    private _getObjectDelta(oldObject, newObject);
    /**
     * Compare changed object (which is a forced clone) with existing object and return the delta
     */
    private _getChangeDelta(obj, old);
    /**
     * Creates a clone of the current status of an object and associates operation and collection name,
     * so the parent db can aggregate and generate a changes object for the entire db
     */
    private _createChange(name, op, obj, old?);
    private _createInsertChange(obj);
    private _createUpdateChange(obj, old);
    private _insertMetaWithChange(obj);
    private _updateMetaWithChange(obj, old);
    private _insertMeta(obj);
    private _updateMeta(obj);
    /**
     * Get by Id - faster than other methods because of the searching algorithm
     * @param {int} id - $loki id of document you want to retrieve
     * @param {boolean} returnPosition - if 'true' we will return [object, position]
     * @returns {(object|array|null)} Object reference if document was found, null if not,
     *     or an array if 'returnPosition' was passed.
     */
    get(id: number): Doc<T>;
    get(id: number, returnPosition: boolean): Doc<T> | [Doc<T>, number];
    /**
     * Retrieve doc by Unique index
     * @param {string} field - name of uniquely indexed property to use when doing lookup
     * @param {any} value - unique value to search for
     * @returns {object} document matching the value passed
     */
    by(field: keyof T, value: any): Doc<T>;
    /**
     * Find one object by index property, by property equal to value
     * @param {object} query - query object used to perform search with
     * @returns {(object|null)} First matching document, or null if none
     */
    findOne(query: ResultSet.Query<Doc<T>>): Doc<T>;
    /**
     * Chain method, used for beginning a series of chained find() and/or view() operations
     * on a collection.
     *
     * @param {array} transform - Ordered array of transform step objects similar to chain
     * @param {object} parameters - Object containing properties representing parameters to substitute
     * @returns {ResultSet} (this) ResultSet, or data array if any map or join functions where called
     */
    chain(transform?: string | Collection.Transform<T>[], parameters?: object): ResultSet<T>;
    /**
     * Find method, api is similar to mongodb.
     * for more complex queries use [chain()]{@link Collection#chain} or [where()]{@link Collection#where}.
     * @example {@tutorial Query Examples}
     * @param {object} query - 'mongo-like' query object
     * @returns {array} Array of matching documents
     */
    find(query?: ResultSet.Query<Doc<T>>): Doc<T>[];
    /**
     * Find object by unindexed field by property equal to value,
     * simply iterates and returns the first element matching the query
     */
    findOneUnindexed(prop: string, value: any): Doc<T>;
    /**
     * Transaction methods
     */
    /**
     * start the transation
     */
    startTransaction(): void;
    /**
     * Commit the transaction.
     */
    commit(): void;
    /**
     * Rollback the transaction.
     */
    rollback(): void;
    /**
     * Query the collection by supplying a javascript filter function.
     * @example
     * let results = coll.where(function(obj) {
       *   return obj.legs === 8;
       * });
     * @param {function} fun - filter function to run against all collection docs
     * @returns {array} all documents which pass your filter function
     */
    where(fun: (obj: Doc<T>) => boolean): Doc<T>[];
    /**
     * Map Reduce operation
     * @param {function} mapFunction - function to use as map function
     * @param {function} reduceFunction - function to use as reduce function
     * @returns {data} The result of your mapReduce operation
     */
    mapReduce<U1, U2>(mapFunction: (value: Doc<T>, index: number, array: Doc<T>[]) => U1, reduceFunction: (array: U1[]) => U2): U2;
    /**
     * Join two collections on specified properties
     * @param {array} joinData - array of documents to 'join' to this collection
     * @param {string} leftJoinProp - property name in collection
     * @param {string} rightJoinProp - property name in joinData
     * @param {function} mapFun - (Optional) map function to use
     * @param dataOptions - options to data() before input to your map function
     * @param [dataOptions.removeMeta] - allows removing meta before calling mapFun
     * @param [dataOptions.forceClones] - forcing the return of cloned objects to your map object
     * @param [dataOptions.forceCloneMethod] - allows overriding the default or collection specified cloning method
     * @returns {ResultSet} Result of the mapping operation
     */
    eqJoin(joinData: Collection<any> | ResultSet<any> | any[], leftJoinProp: string | ((obj: any) => string), rightJoinProp: string | ((obj: any) => string), mapFun?: (left: any, right: any) => any, dataOptions?: ResultSet.DataOptions): ResultSet<any>;
    /**
     * (Staging API) create a stage and/or retrieve it
     */
    getStage(name: string): any;
    /**
     * a collection of objects recording the changes applied through a commmitStage
     */
    /**
     * (Staging API) create a copy of an object and insert it into a stage
     */
    stage<F extends TData>(stageName: string, obj: Doc<F>): F;
    /**
     * (Staging API) re-attach all objects to the original collection, so indexes and views can be rebuilt
     * then create a message to be inserted in the commitlog
     * @param {string} stageName - name of stage
     * @param {string} message
     */
    commitStage(stageName: string, message: string): void;
    /**
     * Returns all values of a field.
     * @param {string} field - the field name
     * @return {any}: the array of values
     */
    extract(field: keyof T): any[];
    /**
     * Finds the minimum value of a field.
     * @param {string} field - the field name
     * @return {number} the minimum value
     */
    min(field: keyof T): number;
    /**
     * Finds the maximum value of a field.
     * @param {string} field - the field name
     * @return {number} the maximum value
     */
    max(field: keyof T): number;
    /**
     * Finds the minimum value and its index of a field.
     * @param {string} field - the field name
     * @return {object} - index and value
     */
    minRecord(field: keyof T): {
        index: number;
        value: number;
    };
    /**
     * Finds the maximum value and its index of a field.
     * @param {string} field - the field name
     * @return {object} - index and value
     */
    maxRecord(field: keyof T): {
        index: number;
        value: number;
    };
    /**
     * Returns all values of a field as numbers (if possible).
     * @param {string} field - the field name
     * @return {number[]} - the number array
     */
    extractNumerical(field: keyof T): number[];
    /**
     * Calculates the average numerical value of a field
     * @param {string} field - the field name
     * @returns {number} average of property in all docs in the collection
     */
    avg(field: keyof T): number;
    /**
     * Calculate the standard deviation of a field.
     * @param {string} field - the field name
     * @return {number} the standard deviation
     */
    stdDev(field: keyof T): number;
    /**
     * Calculates the mode of a field.
     * @param {string} field - the field name
     * @return {number} the mode
     */
    mode(field: keyof T): number;
    /**
     * Calculates the median of a field.
     * @param {string} field - the field name
     * @return {number} the median
     */
    median(field: keyof T): number;
}
export declare namespace Collection {
    interface Options<TData extends object, TNested extends object = {}, T extends object = TData & TNested> {
        unique?: (keyof T)[];
        unindexedSortComparator?: string;
        defaultLokiOperatorPackage?: string;
        rangedIndexes?: RangedIndexOptions;
        serializableIndexes?: boolean;
        asyncListeners?: boolean;
        disableMeta?: boolean;
        disableChangesApi?: boolean;
        disableDeltaChangesApi?: boolean;
        clone?: boolean;
        serializableIndices?: boolean;
        cloneMethod?: CloneMethod;
        transactional?: boolean;
        ttl?: number;
        ttlInterval?: number;
        nestedProperties?: (keyof TNested | {
            name: keyof TNested;
            path: string[];
        })[];
        fullTextSearch?: FullTextSearch.FieldOptions[];
    }
    interface RangedIndexOptions {
        [prop: string]: RangedIndexMeta;
    }
    interface DeserializeOptions {
        retainDirtyFlags?: boolean;
        fullTextSearch?: Dict<Analyzer>;
        [collName: string]: any | {
            proto?: any;
            inflate?: (src: object, dest?: object) => void;
        };
    }
    interface BinaryIndex {
        dirty: boolean;
        values: any;
    }
    interface RangedIndexMeta {
        index?: IRangedIndex<any>;
        indexTypeName?: string;
        comparatorName?: string;
    }
    interface Change {
        name: string;
        operation: string;
        obj: any;
    }
    interface Serialized {
        name: string;
        unindexedSortComparator: string;
        defaultLokiOperatorPackage: string;
        _dynamicViews: DynamicView[];
        _nestedProperties: {
            name: string;
            path: string[];
        }[];
        uniqueNames: string[];
        transforms: Dict<Transform[]>;
        rangedIndexes: RangedIndexOptions;
        _data: Doc<any>[];
        idIndex: number[];
        maxId: number;
        _dirty: boolean;
        transactional: boolean;
        asyncListeners: boolean;
        disableMeta: boolean;
        disableChangesApi: boolean;
        disableDeltaChangesApi: boolean;
        cloneObjects: boolean;
        cloneMethod: CloneMethod;
        changes: any;
        _fullTextSearch: FullTextSearch;
    }
    interface CheckIndexOptions {
        randomSampling?: boolean;
        randomSamplingFactor?: number;
        repair?: boolean;
    }
    type Transform<T extends object = object> = {
        type: "find";
        value: ResultSet.Query<Doc<T>> | string;
    } | {
        type: "where";
        value: ((obj: Doc<T>) => boolean) | string;
    } | {
        type: "simplesort";
        property: keyof T;
        options?: boolean | ResultSet.SimpleSortOptions;
    } | {
        type: "compoundsort";
        value: (keyof T | [keyof T, boolean])[];
    } | {
        type: "sort";
        value: (a: Doc<T>, b: Doc<T>) => number;
    } | {
        type: "sortByScoring";
        desc?: boolean;
    } | {
        type: "limit";
        value: number;
    } | {
        type: "offset";
        value: number;
    } | {
        type: "map";
        value: (obj: Doc<T>, index: number, array: Doc<T>[]) => any;
        dataOptions?: ResultSet.DataOptions;
    } | {
        type: "eqJoin";
        joinData: Collection<any> | ResultSet<any>;
        leftJoinKey: string | ((obj: any) => string);
        rightJoinKey: string | ((obj: any) => string);
        mapFun?: (left: any, right: any) => any;
        dataOptions?: ResultSet.DataOptions;
    } | {
        type: "mapReduce";
        mapFunction: (item: Doc<T>, index: number, array: Doc<T>[]) => any;
        reduceFunction: (array: any[]) => any;
    } | {
        type: "update";
        value: (obj: Doc<T>) => any;
    } | {
        type: "remove";
    };
    interface TTL {
        age: number;
        ttlInterval: number;
        daemon: any;
    }
}


/* List of defines generated by configure. Included with preprocessor flag,
 * -include, to avoid long list of -D defines on the compile command-line.
 * Do not edit.
 */

#ifndef js_confdefs_h
#define js_confdefs_h

// Expands to all the defines from configure.
#define CPP_THROW_NEW throw()
#define CROSS_COMPILE
#define EDITLINE 1
#define HAVE_64BIT_BUILD 1
#define HAVE_ALLOCA_H 1
#define HAVE_CPP_DYNAMIC_CAST_TO_VOID_PTR 1
#define HAVE_CPUID_H 1
#define HAVE_DIRENT_H 1
#define HAVE_GETC_UNLOCKED 1
#define HAVE_GETOPT_H 1
#define HAVE_GMTIME_R 1
#define HAVE_INTTYPES_H 1
#define HAVE_LANGINFO_CODESET 1
#define HAVE_LIBM 1
#define HAVE_LOCALECONV 1
#define HAVE_LOCALTIME_R 1
#define HAVE_NETINET_IN_H 1
#define HAVE_NL_TYPES_H 1
#define HAVE_POSIX_MEMALIGN 1
#define HAVE_PTHREAD_GETNAME_NP 1
#define HAVE_SSIZE_T 1
#define HAVE_STDINT_H 1
#define HAVE_STRNDUP 1
#define HAVE_SYS_MOUNT_H 1
#define HAVE_SYS_QUEUE_H 1
#define HAVE_SYS_STATVFS_H 1
#define HAVE_SYS_TYPES_H 1
#define HAVE_THREAD_TLS_KEYWORD 1
#define HAVE_TM_ZONE_TM_GMTOFF 1
#define HAVE_UNISTD_H 1
#define HAVE_VALLOC 1
#define HAVE_VA_COPY 1
#define HAVE_VA_LIST_AS_ARRAY 1
#define HAVE_VISIBILITY_ATTRIBUTE 1
#define HAVE_VISIBILITY_HIDDEN_ATTRIBUTE 1
#define HAVE___CXA_DEMANGLE 1
#define HAVE___SINCOS 1
#define JS_64BIT 1
#define JS_CODEGEN_X64 1
#define JS_DEFAULT_JITREPORT_GRANULARITY 3
#define JS_POSIX_NSPR 1
#define JS_PUNBOX64 1
#define JS_STANDALONE 1
#define MALLOC_H <malloc/malloc.h>
#define MALLOC_USABLE_SIZE_CONST_PTR const
#define MOZILLA_UAVERSION "60.0"
#define MOZILLA_VERSION "60.3.0"
#define MOZILLA_VERSION_U 60.3.0
#define MOZJS_MAJOR_VERSION 60
#define MOZJS_MINOR_VERSION 3
#define MOZ_BUILD_APP js
#define MOZ_DLL_SUFFIX ".dylib"
#define MOZ_MEMORY 1
#define MOZ_STATIC_JS 1
#define MOZ_UPDATE_CHANNEL default
#define NO_NSPR_10_SUPPORT 1
#define RELEASE_OR_BETA 1
#define STATIC_EXPORTABLE_JS_API 1
#define STDC_HEADERS 1
#define VA_COPY va_copy
#define XP_DARWIN 1
#define XP_MACOSX 1
#define XP_UNIX 1
#define X_DISPLAY_MISSING 1

#include "js/RequiredDefines.h"

#endif /* js_confdefs_h */


# TRANSLATORS: Name of Venus in Anutan culture
Venus	"Te Petuu Ao/Tiuriuri"	_("Te Petuu Ao/Tiuriuri")


<?php

namespace Oro\Bundle\PromotionBundle\Tests\Functional\Manager;

use Oro\Bundle\CustomerBundle\Tests\Functional\DataFixtures\LoadCustomerUserData;
use Oro\Bundle\PromotionBundle\Tests\Functional\DataFixtures\LoadCouponData;
use Oro\Bundle\PromotionBundle\Tests\Functional\DataFixtures\LoadCouponUsageData;
use Oro\Bundle\TestFrameworkBundle\Test\WebTestCase;

/**
 * @dbIsolationPerTest
 */
class CouponUsageManagerTest extends WebTestCase
{
    protected function setUp(): void
    {
        $this->initClient([], $this->generateBasicAuthHeader());
        $this->loadFixtures([
            LoadCouponUsageData::class
        ]);
    }

    public function testGetCouponUsageCount()
    {
        $coupon = $this->getReference(LoadCouponData::COUPON_WITH_PROMO_AND_VALID_FROM_AND_UNTIL);

        $manager = $this->getContainer()->get('oro_promotion.coupon_usage_manager');

        $this->assertEquals(3, $manager->getCouponUsageCount($coupon));
    }

    public function testGetCouponUsageCountByCustomerUser()
    {
        $coupon = $this->getReference(LoadCouponData::COUPON_WITH_PROMO_AND_VALID_FROM_AND_UNTIL);
        $customerUser = $this->getReference(LoadCustomerUserData::EMAIL);

        $manager = $this->getContainer()->get('oro_promotion.coupon_usage_manager');

        $this->assertEquals(2, $manager->getCouponUsageCountByCustomerUser($coupon, $customerUser));
    }

    public function testCreateCouponUsage()
    {
        $coupon = $this->getReference(LoadCouponData::COUPON_WITH_PROMO_AND_VALID_FROM_AND_UNTIL);
        $customerUser = $this->getReference(LoadCustomerUserData::ANONYMOUS_EMAIL);

        $manager = $this->getContainer()->get('oro_promotion.coupon_usage_manager');

        $this->assertEmpty($manager->getCouponUsageCountByCustomerUser($coupon, $customerUser));

        $manager->createCouponUsage($coupon, $customerUser, true);
        $manager->createCouponUsage($coupon, $customerUser, true);
        $manager->createCouponUsage($coupon, $customerUser, false);
        $this->assertEquals(2, $manager->getCouponUsageCountByCustomerUser($coupon, $customerUser));
    }
}


<?xml version="1.0" encoding="gb2312"?>
<VisualStudioProject
	ProjectType="Visual C++"
	Version="8.00"
	Name="麻将模板"
	ProjectGUID="{F2D70F30-23FC-4973-A798-AED329359B33}"
	Keyword="MFCProj"
	>
	<Platforms>
		<Platform
			Name="Win32"
		/>
	</Platforms>
	<ToolFiles>
	</ToolFiles>
	<Configurations>
		<Configuration
			Name="Debug|Win32"
			OutputDirectory="Debug"
			IntermediateDirectory="Debug"
			ConfigurationType="1"
			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
			UseOfMFC="2"
			CharacterSet="2"
			>
			<Tool
				Name="VCPreBuildEventTool"
			/>
			<Tool
				Name="VCCustomBuildTool"
			/>
			<Tool
				Name="VCXMLDataGeneratorTool"
			/>
			<Tool
				Name="VCWebServiceProxyGeneratorTool"
			/>
			<Tool
				Name="VCMIDLTool"
				PreprocessorDefinitions="_DEBUG"
				MkTypLibCompatible="false"
			/>
			<Tool
				Name="VCCLCompilerTool"
				Optimization="0"
				PreprocessorDefinitions="WIN32;_WINDOWS;_DEBUG"
				MinimalRebuild="true"
				BasicRuntimeChecks="3"
				RuntimeLibrary="3"
				TreatWChar_tAsBuiltInType="true"
				UsePrecompiledHeader="2"
				WarningLevel="3"
				Detect64BitPortabilityProblems="true"
				DebugInformationFormat="4"
			/>
			<Tool
				Name="VCManagedResourceCompilerTool"
			/>
			<Tool
				Name="VCResourceCompilerTool"
				PreprocessorDefinitions="_DEBUG"
				Culture="2052"
				AdditionalIncludeDirectories="$(IntDir)"
			/>
			<Tool
				Name="VCPreLinkEventTool"
			/>
			<Tool
				Name="VCLinkerTool"
				AdditionalDependencies="../../开发库/Lib/GameFrameD.lib ../../开发库/Lib/SkinControlsD.lib"
				OutputFile="../../运行/Debug/Sparrow.exe"
				LinkIncremental="2"
				GenerateDebugInformation="true"
				SubSystem="2"
				TargetMachine="1"
			/>
			<Tool
				Name="VCALinkTool"
			/>
			<Tool
				Name="VCManifestTool"
			/>
			<Tool
				Name="VCXDCMakeTool"
			/>
			<Tool
				Name="VCBscMakeTool"
			/>
			<Tool
				Name="VCFxCopTool"
			/>
			<Tool
				Name="VCAppVerifierTool"
			/>
			<Tool
				Name="VCWebDeploymentTool"
			/>
			<Tool
				Name="VCPostBuildEventTool"
				CommandLine="mkdir ..\..\发布组件\客户端组件\Debug
copy /y ..\..\运行\Debug\$(TargetFileName) ..\..\发布组件\客户端组件\Debug\$(TargetFileName)
"
			/>
		</Configuration>
		<Configuration
			Name="Release|Win32"
			OutputDirectory="Release"
			IntermediateDirectory="Release"
			ConfigurationType="1"
			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
			UseOfMFC="2"
			CharacterSet="2"
			>
			<Tool
				Name="VCPreBuildEventTool"
			/>
			<Tool
				Name="VCCustomBuildTool"
			/>
			<Tool
				Name="VCXMLDataGeneratorTool"
			/>
			<Tool
				Name="VCWebServiceProxyGeneratorTool"
			/>
			<Tool
				Name="VCMIDLTool"
				PreprocessorDefinitions="NDEBUG"
				MkTypLibCompatible="false"
			/>
			<Tool
				Name="VCCLCompilerTool"
				PreprocessorDefinitions="WIN32;_WINDOWS;NDEBUG"
				MinimalRebuild="false"
				RuntimeLibrary="2"
				TreatWChar_tAsBuiltInType="true"
				UsePrecompiledHeader="2"
				WarningLevel="3"
				Detect64BitPortabilityProblems="true"
				DebugInformationFormat="3"
			/>
			<Tool
				Name="VCManagedResourceCompilerTool"
			/>
			<Tool
				Name="VCResourceCompilerTool"
				PreprocessorDefinitions="NDEBUG"
				Culture="2052"
				AdditionalIncludeDirectories="$(IntDir)"
			/>
			<Tool
				Name="VCPreLinkEventTool"
			/>
			<Tool
				Name="VCLinkerTool"
				AdditionalDependencies="../../开发库/Lib/GameFrame.lib ../../开发库/Lib/SkinControls.lib Winmm.lib"
				OutputFile="../../运行/Release/GD_Mj.exe"
				LinkIncremental="1"
				GenerateDebugInformation="true"
				SubSystem="2"
				OptimizeReferences="2"
				EnableCOMDATFolding="2"
				TargetMachine="1"
			/>
			<Tool
				Name="VCALinkTool"
			/>
			<Tool
				Name="VCManifestTool"
			/>
			<Tool
				Name="VCXDCMakeTool"
			/>
			<Tool
				Name="VCBscMakeTool"
			/>
			<Tool
				Name="VCFxCopTool"
			/>
			<Tool
				Name="VCAppVerifierTool"
			/>
			<Tool
				Name="VCWebDeploymentTool"
			/>
			<Tool
				Name="VCPostBuildEventTool"
				CommandLine="mkdir ..\..\发布组件\客户端组件\Release
copy /y ..\..\运行\Release\$(TargetFileName) ..\..\发布组件\客户端组件\Release\$(TargetFileName)
"
			/>
		</Configuration>
	</Configurations>
	<References>
	</References>
	<Files>
		<Filter
			Name="源文件"
			Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx"
			UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
			>
			<File
				RelativePath=".\ClientKernelSink.cpp"
				>
			</File>
			<File
				RelativePath=".\GameClient.cpp"
				>
			</File>
			<File
				RelativePath=".\GameClientDlg.cpp"
				>
				<FileConfiguration
					Name="Debug|Win32"
					>
					<Tool
						Name="VCCLCompilerTool"
						DisableSpecificWarnings="4244"
					/>
				</FileConfiguration>
			</File>
			<File
				RelativePath=".\GameClientView.cpp"
				>
			</File>
			<File
				RelativePath=".\GameLogic.cpp"
				>
			</File>
			<File
				RelativePath=".\GameOption.cpp"
				>
			</File>
			<File
				RelativePath=".\GameParrentDlg.cpp"
				>
			</File>
			<File
				RelativePath=".\GameParrentView.cpp"
				>
			</File>
			<File
				RelativePath=".\GlobalOption.cpp"
				>
			</File>
			<File
				RelativePath=".\ScoreView.cpp"
				>
			</File>
			<File
				RelativePath=".\Stdafx.cpp"
				>
				<FileConfiguration
					Name="Debug|Win32"
					>
					<Tool
						Name="VCCLCompilerTool"
						UsePrecompiledHeader="1"
					/>
				</FileConfiguration>
				<FileConfiguration
					Name="Release|Win32"
					>
					<Tool
						Name="VCCLCompilerTool"
						UsePrecompiledHeader="1"
					/>
				</FileConfiguration>
			</File>
			<File
				RelativePath=".\TimerControl.cpp"
				>
			</File>
			<File
				RelativePath=".\TranscendLog.cpp"
				>
			</File>
		</Filter>
		<Filter
			Name="头文件"
			Filter="h;hpp;hxx;hm;inl;inc;xsd"
			UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
			>
			<File
				RelativePath=".\CClientKernelSink.h"
				>
			</File>
			<File
				RelativePath=".\ClientKernelSink.h"
				>
			</File>
			<File
				RelativePath="..\消息定义\CMD_Sparrow.h"
				>
			</File>
			<File
				RelativePath=".\GameClient.h"
				>
			</File>
			<File
				RelativePath=".\GameClientDlg.h"
				>
			</File>
			<File
				RelativePath=".\GameClientView.h"
				>
			</File>
			<File
				RelativePath=".\GameLogic.h"
				>
			</File>
			<File
				RelativePath=".\GameOption.h"
				>
			</File>
			<File
				RelativePath=".\GameParrentDlg.h"
				>
			</File>
			<File
				RelativePath=".\GameParrentView.h"
				>
			</File>
			<File
				RelativePath=".\GlobalOption.h"
				>
			</File>
			<File
				RelativePath=".\Resource.h"
				>
			</File>
			<File
				RelativePath=".\ScoreView.h"
				>
			</File>
			<File
				RelativePath=".\Stdafx.h"
				>
			</File>
			<File
				RelativePath=".\Struct.h"
				>
			</File>
			<File
				RelativePath=".\TimerControl.h"
				>
			</File>
			<File
				RelativePath=".\TranscendLog.h"
				>
			</File>
		</Filter>
		<Filter
			Name="资源文件"
			Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx"
			UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"
			>
			<File
				RelativePath=".\Res\ACTION_BACK.bmp"
				>
			</File>
			<File
				RelativePath=".\Res\ACTION_EXPLAIN.bmp"
				>
			</File>
			<File
				RelativePath=".\Res\BACK_GROUND.bmp"
				>
			</File>
			<File
				RelativePath=".\Res\BT_CHIHU.bmp"
				>
			</File>
			<File
				RelativePath=".\Res\BT_GIVEUP.bmp"
				>
			</File>
			<File
				RelativePath=".\Res\BT_HAI_DI.bmp"
				>
			</File>
			<File
				RelativePath=".\Res\BT_NO_HAI_DI.bmp"
				>
			</File>
			<File
				RelativePath=".\Res\BT_START.bmp"
				>
			</File>
			<File
				RelativePath=".\Res\CARD_BACK_H.bmp"
				>
			</File>
			<File
				RelativePath=".\Res\CARD_BACK_V.bmp"
				>
			</File>
			<File
				RelativePath=".\Res\CARD_CUR.cur"
				>
			</File>
			<File
				RelativePath=".\Res\CARD_HEAP_DOUBLE_H.bmp"
				>
			</File>
			<File
				RelativePath=".\Res\CARD_HEAP_DOUBLE_V.bmp"
				>
			</File>
			<File
				RelativePath=".\Res\CARD_HEAP_SINGLE_H.bmp"
				>
			</File>
			<File
				RelativePath=".\Res\CARD_HEAP_SINGLE_V.bmp"
				>
			</File>
			<File
				RelativePath=".\Res\CARD_TABLE_BOTTOM.bmp"
				>
			</File>
			<File
				RelativePath=".\Res\CARD_TABLE_LEFT.bmp"
				>
			</File>
			<File
				RelativePath=".\Res\CARD_TABLE_RIGHT.bmp"
				>
			</File>
			<File
				RelativePath=".\Res\CARD_TABLE_TOP.bmp"
				>
			</File>
			<File
				RelativePath=".\Res\CARD_USER_BOTTOM.bmp"
				>
			</File>
			<File
				RelativePath=".\Res\CARD_USER_LEFT.bmp"
				>
			</File>
			<File
				RelativePath=".\Res\CARD_USER_RIGHT.bmp"
				>
			</File>
			<File
				RelativePath=".\Res\CARD_USER_TOP.bmp"
				>
			</File>
			<File
				RelativePath=".\Res\CONTROL_BOTTOM.bmp"
				>
			</File>
			<File
				RelativePath=".\Res\CONTROL_MID.bmp"
				>
			</File>
			<File
				RelativePath=".\Res\CONTROL_TOP.bmp"
				>
			</File>
			<File
				RelativePath=".\Res\GAME_LOGO.bmp"
				>
			</File>
			<File
				RelativePath=".\Res\GAME_SCORE.bmp"
				>
			</File>
			<File
				RelativePath=".\Res\GameClient.ico"
				>
			</File>
			<File
				RelativePath=".\GameClient.rc"
				>
			</File>
			<File
				RelativePath=".\res\GameClient.rc2"
				>
			</File>
			<File
				RelativePath=".\Res\HUANG_ZHUANG.bmp"
				>
			</File>
			<File
				RelativePath=".\Res\OUT_CARD_TIP.bmp"
				>
			</File>
			<File
				RelativePath=".\Res\USER_ACTION.bmp"
				>
			</File>
			<File
				RelativePath=".\Res\USER_FLAG.bmp"
				>
			</File>
			<File
				RelativePath=".\Res\VIEW_BACK.bmp"
				>
			</File>
			<File
				RelativePath=".\Res\VIEW_BACK_CENTER.bmp"
				>
			</File>
			<File
				RelativePath=".\Res\VIEW_BORDER.bmp"
				>
			</File>
			<File
				RelativePath=".\Res\WAIT_TIP.bmp"
				>
			</File>
		</Filter>
		<File
			RelativePath=".\Res\A_chi_hu.wav"
			>
		</File>
		<File
			RelativePath=".\Res\A_FILL.wav"
			>
		</File>
		<File
			RelativePath=".\Res\A_gang.wav"
			>
		</File>
		<File
			RelativePath=".\Res\A_peng.wav"
			>
		</File>
		<File
			RelativePath=".\Res\A_shang.wav"
			>
		</File>
		<File
			RelativePath=".\Res\A_ting.wav"
			>
		</File>
		<File
			RelativePath=".\Res\Game_end.wav"
			>
		</File>
		<File
			RelativePath=".\Res\GAME_LOST.wav"
			>
		</File>
		<File
			RelativePath=".\Res\Game_start.wav"
			>
		</File>
		<File
			RelativePath=".\Res\Game_warn.wav"
			>
		</File>
		<File
			RelativePath=".\Res\GAME_WIN.wav"
			>
		</File>
		<File
			RelativePath=".\Res\OUT_CARD.wav"
			>
		</File>
		<File
			RelativePath=".\Res\S_1.wav"
			>
		</File>
		<File
			RelativePath=".\Res\S_2.wav"
			>
		</File>
		<File
			RelativePath=".\Res\S_3.wav"
			>
		</File>
		<File
			RelativePath=".\Res\S_4.wav"
			>
		</File>
		<File
			RelativePath=".\Res\S_5.wav"
			>
		</File>
		<File
			RelativePath=".\Res\S_6.wav"
			>
		</File>
		<File
			RelativePath=".\Res\S_7.wav"
			>
		</File>
		<File
			RelativePath=".\Res\S_8.wav"
			>
		</File>
		<File
			RelativePath=".\Res\S_9.wav"
			>
		</File>
		<File
			RelativePath=".\Res\T_1.wav"
			>
		</File>
		<File
			RelativePath=".\Res\T_2.wav"
			>
		</File>
		<File
			RelativePath=".\Res\T_3.wav"
			>
		</File>
		<File
			RelativePath=".\Res\T_4.wav"
			>
		</File>
		<File
			RelativePath=".\Res\T_5.wav"
			>
		</File>
		<File
			RelativePath=".\Res\T_6.wav"
			>
		</File>
		<File
			RelativePath=".\Res\T_7.wav"
			>
		</File>
		<File
			RelativePath=".\Res\T_8.wav"
			>
		</File>
		<File
			RelativePath=".\Res\T_9.wav"
			>
		</File>
		<File
			RelativePath=".\Res\W_1.wav"
			>
		</File>
		<File
			RelativePath=".\Res\W_2.wav"
			>
		</File>
		<File
			RelativePath=".\Res\W_3.wav"
			>
		</File>
		<File
			RelativePath=".\Res\W_4.wav"
			>
		</File>
		<File
			RelativePath=".\Res\W_5.wav"
			>
		</File>
		<File
			RelativePath=".\Res\W_6.wav"
			>
		</File>
		<File
			RelativePath=".\Res\W_7.wav"
			>
		</File>
		<File
			RelativePath=".\Res\W_8.wav"
			>
		</File>
		<File
			RelativePath=".\Res\W_9.wav"
			>
		</File>
	</Files>
	<Globals>
		<Global
			Name="RESOURCE_FILE"
			Value="GameClient.rc"
		/>
	</Globals>
</VisualStudioProject>


<!-- Just need to instantiate the controller, and it will take care of showing the modal dialog -->
<span ng-controller="ActivitiMessageDefinitionsCtrl">
</span>


/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.ignite.internal.processors.rest.client.message;

import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

/**
 * @deprecated Use {@link GridClientClusterStateRequest} instead.
 */
@Deprecated
public class GridClientStateRequest extends GridClientAbstractMessage {
    /** */
    private static final long serialVersionUID = 0L;

    /** Active. */
    private boolean active;

    /** Request current state. */
    private boolean reqCurrentState;

    /**
     *
     */
    public boolean active() {
        return active;
    }

    /**
     *
     */
    public void active(boolean active) {
        this.active = active;
    }

    /**
     *
     */
    public void requestCurrentState() {
        this.reqCurrentState = true;
    }

    /**
     *
     */
    public boolean isReqCurrentState() {
        return reqCurrentState;
    }

    /** {@inheritDoc} */
    @Override public void writeExternal(ObjectOutput out) throws IOException {
        super.writeExternal(out);

        out.writeBoolean(active);
        out.writeBoolean(reqCurrentState);
    }

    /** {@inheritDoc} */
    @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        super.readExternal(in);

        active = in.readBoolean();
        reqCurrentState = in.readBoolean();
    }
}


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

#define SAD_WINDOW_SIZE 11

/* NO_OF_DISPARITIES must be greater than '0' and less than the image width */
#define NO_OF_DISPARITIES 32

/* NO_OF_DISPARITIES must not be lesser than PARALLEL_UNITS and NO_OF_DISPARITIES/PARALLEL_UNITS must be a
 * non-fractional number */
#define PARALLEL_UNITS 32

#define XF_USE_URAM false


#include "stdafx.h"
#include "SkinMenu.h"

CSkinMenu::CSkinMenu(HMENU hMenu/* = NULL*/)
{
	m_hMenu = hMenu;

	m_lpBgImgL = m_lpBgImgR = NULL;
	m_lpSelectedImg = NULL;
	m_lpSepartorImg = NULL;
	m_lpArrowImg = NULL;
	m_lpCheckImg = NULL;

	m_clrText = RGB(0, 0 , 0);
	m_clrSelText = RGB(255, 255, 255);
	m_clrGrayedText = RGB(131, 136, 140);

	m_nLMargin = 28;

	NONCLIENTMETRICS ncm = {0};
	ncm.cbSize = sizeof(ncm);

	::SystemParametersInfo(SPI_GETNONCLIENTMETRICS, 0, (PVOID)&ncm, FALSE);

	m_hFont = ::CreateFontIndirect(&ncm.lfMenuFont);
}

CSkinMenu::~CSkinMenu(void)
{
	if (m_hFont != NULL)
	{
		::DeleteObject(m_hFont);
		m_hFont = NULL;
	}
}

BOOL CSkinMenu::SetBgPic(LPCTSTR lpszLeftBg, LPCTSTR lpszRightBg)
{
	CSkinManager::GetInstance()->ReleaseImage(m_lpBgImgL);
	CSkinManager::GetInstance()->ReleaseImage(m_lpBgImgR);

	m_lpBgImgL = CSkinManager::GetInstance()->GetImage(lpszLeftBg);
	m_lpBgImgR = CSkinManager::GetInstance()->GetImage(lpszRightBg);

	if (NULL == m_lpBgImgL || NULL == m_lpBgImgR)
		return FALSE;
	else
		return TRUE;
}

BOOL CSkinMenu::SetSelectedPic(LPCTSTR lpszFileName)
{
	CSkinManager::GetInstance()->ReleaseImage(m_lpSelectedImg);

	m_lpSelectedImg = CSkinManager::GetInstance()->GetImage(lpszFileName);

	if (NULL == m_lpSelectedImg)
		return FALSE;
	else
		return TRUE;
}

BOOL CSkinMenu::SetSepartorPic(LPCTSTR lpszFileName)
{
	CSkinManager::GetInstance()->ReleaseImage(m_lpSepartorImg);

	m_lpSepartorImg = CSkinManager::GetInstance()->GetImage(lpszFileName);

	if (NULL == m_lpSepartorImg)
		return FALSE;
	else
		return TRUE;
}

BOOL CSkinMenu::SetArrowPic(LPCTSTR lpszFileName)
{
	CSkinManager::GetInstance()->ReleaseImage(m_lpArrowImg);

	m_lpArrowImg = CSkinManager::GetInstance()->GetImage(lpszFileName);

	if (NULL == m_lpArrowImg)
		return FALSE;
	else
		return TRUE;
}

BOOL CSkinMenu::SetCheckPic(LPCTSTR lpszFileName)
{
	CSkinManager::GetInstance()->ReleaseImage(m_lpCheckImg);

	m_lpCheckImg = CSkinManager::GetInstance()->GetImage(lpszFileName);

	if (NULL == m_lpCheckImg)
		return FALSE;
	else
		return TRUE;
}

BOOL CSkinMenu::SetIcon(UINT nItem, BOOL bByPosition, LPCTSTR lpszIconN, LPCTSTR lpszIconH)
{
	SKIN_MENU_ITEM_INFO* lpSkinMenuItemInfo;

	lpSkinMenuItemInfo = GetMenuItemInfo(nItem, bByPosition);
	if (lpSkinMenuItemInfo != NULL && SKIN_MENU_MAGIC == lpSkinMenuItemInfo->nMagic)
	{
		CSkinManager::GetInstance()->ReleaseImage(lpSkinMenuItemInfo->lpIconImgN);
		CSkinManager::GetInstance()->ReleaseImage(lpSkinMenuItemInfo->lpIconImgH);

		lpSkinMenuItemInfo->lpIconImgN = CSkinManager::GetInstance()->GetImage(lpszIconN);
		lpSkinMenuItemInfo->lpIconImgH = CSkinManager::GetInstance()->GetImage(lpszIconH);

		if (lpSkinMenuItemInfo->lpIconImgN != NULL && lpSkinMenuItemInfo->lpIconImgH != NULL)
			return TRUE;
	}

	return FALSE;
}

// 设置普通菜单文本颜色
void CSkinMenu::SetTextColor(COLORREF clrText)
{
	m_clrText = clrText;
}

// 设置选中菜单文本颜色
void CSkinMenu::SetSelTextColor(COLORREF clrSelText)
{
	m_clrSelText = clrSelText;
}

// 设置灰化菜单文本颜色
void CSkinMenu::SetGrayedTextColor(COLORREF clrGrayedText)
{
	m_clrGrayedText = clrGrayedText;
}

BOOL CSkinMenu::CreateMenu()
{
	if (m_hMenu != NULL)
	{
		EnableOwnerDraw(m_hMenu, FALSE);
		::DestroyMenu(m_hMenu);
		m_hMenu = NULL;
	}

	m_hMenu = ::CreateMenu();
	if (!m_hMenu)
		return FALSE;
	else
		return TRUE;
}

BOOL CSkinMenu::CreatePopupMenu()
{
	if (m_hMenu != NULL)
	{
		EnableOwnerDraw(m_hMenu, FALSE);
		::DestroyMenu(m_hMenu);
		m_hMenu = NULL;
	}

	m_hMenu = ::CreatePopupMenu();
	if (!m_hMenu)
		return FALSE;
	else
		return TRUE;
}

BOOL CSkinMenu::LoadMenu(LPCWSTR lpszResourceName)
{
	HMENU hMenu;
	BOOL bRet;

	if (m_hMenu != NULL)
	{
		EnableOwnerDraw(m_hMenu, FALSE);
		::DestroyMenu(m_hMenu);
		m_hMenu = NULL;
	}

	hMenu = ::LoadMenu(ModuleHelper::GetResourceInstance(), lpszResourceName);
	if (!hMenu)
		return FALSE;

	bRet = EnableOwnerDraw(hMenu, TRUE);
	if (!bRet)
	{
		return FALSE;
	}
	else
	{
		m_hMenu = hMenu;
		return TRUE;
	}
}

BOOL CSkinMenu::LoadMenu(UINT nIDResource)
{
	return LoadMenu(MAKEINTRESOURCE(nIDResource));
}

BOOL CSkinMenu::DestroyMenu()
{
	if (m_hMenu != NULL)
	{
		EnableOwnerDraw(m_hMenu, FALSE);
		::DestroyMenu(m_hMenu);
		m_hMenu = NULL;
	}

	CSkinManager::GetInstance()->ReleaseImage(m_lpBgImgL);
	CSkinManager::GetInstance()->ReleaseImage(m_lpBgImgR);
	CSkinManager::GetInstance()->ReleaseImage(m_lpSelectedImg);
	CSkinManager::GetInstance()->ReleaseImage(m_lpSepartorImg);
	CSkinManager::GetInstance()->ReleaseImage(m_lpArrowImg);
	CSkinManager::GetInstance()->ReleaseImage(m_lpCheckImg);

	return TRUE;
}

void CSkinMenu::OnInitMenuPopup(HMENU hMenuPopup, UINT nIndex, BOOL bSysMenu)
{
	EnableOwnerDraw(hMenuPopup, TRUE);
}

void CSkinMenu::OnMeasureItem(int nIDCtl, LPMEASUREITEMSTRUCT lpMeasureItemStruct)
{
	LPMEASUREITEMSTRUCT lpms;
	SKIN_MENU_ITEM_INFO* lpSkinMenuItemInfo;
	RECT rcText = {0};
	SIZE sz;

	lpms = lpMeasureItemStruct;
	if (!lpms || lpms->CtlType != ODT_MENU)
		return;

	lpSkinMenuItemInfo = (SKIN_MENU_ITEM_INFO*)lpms->itemData;
	if (NULL == lpSkinMenuItemInfo || lpSkinMenuItemInfo->nMagic != SKIN_MENU_MAGIC)
		return;

	if (lpSkinMenuItemInfo->nType & MFT_SEPARATOR)		// 分隔符
	{
		lpms->itemWidth = 0;
		if (m_lpSepartorImg != NULL && !m_lpSepartorImg->IsNull())
			lpms->itemHeight = m_lpSepartorImg->GetHeight();
		else
			lpms->itemHeight = 3;
	}
	else
	{
		sz = GetTextExtent(lpSkinMenuItemInfo->szText);

		lpms->itemWidth = m_nLMargin + 8 + sz.cx + 8;	// 左边栏宽度+菜单文本左边8像素+菜单文本宽度+菜单文本右边8像素
		lpms->itemHeight = 5 + sz.cy + 5;				// 菜单文本上边5像素+菜单文本高度+菜单文本下边5像素

		if (lpSkinMenuItemInfo->hSubMenu != NULL)		// 如果是子菜单
		{
			if (m_lpArrowImg != NULL && !m_lpArrowImg->IsNull())
				lpms->itemWidth += m_lpArrowImg->GetWidth() + 8;	// 原来的宽度 + 箭头图标宽度 + 箭头图标右边8像素
			else
				lpms->itemWidth += 5 + 8;
		}
	}
}

void CSkinMenu::OnDrawItem(int nIDCtl, LPDRAWITEMSTRUCT lpDrawItemStruct)
{
	LPDRAWITEMSTRUCT lpds;
	SKIN_MENU_ITEM_INFO* lpSkinMenuItemInfo;
	HDC hDC;
	CRect rcItem;
	BOOL bGrayed, bDisabled, bSelected, bChecked;
	BOOL bIsSeparator;
	CImageEx* lpIconImgN,* lpIconImgH;
	HDC hMemDC;
	HBITMAP hMemBmp, hOldBmp;

	lpds = lpDrawItemStruct;
	if (NULL == lpds || lpds->CtlType != ODT_MENU)
		return;

	lpSkinMenuItemInfo = (SKIN_MENU_ITEM_INFO*)lpds->itemData;
	if (NULL == lpSkinMenuItemInfo || lpSkinMenuItemInfo->nMagic != SKIN_MENU_MAGIC)
		return;

	hDC = lpds->hDC;
	rcItem = lpds->rcItem;

	bGrayed = lpds->itemState & ODS_GRAYED;
	bDisabled = lpds->itemState & ODS_DISABLED;
	bSelected = lpds->itemState & ODS_SELECTED;
	//bChecked  = lpds->itemState & ODS_CHECKED;
	bChecked  = lpSkinMenuItemInfo->nState & ODS_CHECKED;

	bIsSeparator = lpSkinMenuItemInfo->nType & MFT_SEPARATOR;

	lpIconImgN = lpSkinMenuItemInfo->lpIconImgN;
	lpIconImgH = lpSkinMenuItemInfo->lpIconImgH;

	rcItem.OffsetRect(-rcItem.left, -rcItem.top);

	hMemDC = ::CreateCompatibleDC(hDC);
	hMemBmp = ::CreateCompatibleBitmap(hDC, rcItem.Width(), rcItem.Height());
	hOldBmp = (HBITMAP)::SelectObject(hMemDC, hMemBmp);

	DrawBg(hMemDC, rcItem);					// 绘制背景

	if (bIsSeparator)						// 绘制分隔符
	{
		DrawSepartor(hMemDC, rcItem);
	}
	else
	{
		if (bSelected && !bGrayed)
			DrawSelRect(hMemDC, rcItem);	// 绘制选中区域

		if (bChecked)						// 绘制Check状态
		{
			DrawCheckState(hMemDC, rcItem);
		}
		else
		{
			if (bSelected)
				DrawIcon(hMemDC, rcItem, lpIconImgH);	// 绘制选中图标
			else
				DrawIcon(hMemDC, rcItem, lpIconImgN);	// 绘制非选中图标
		}

		DrawText(hMemDC, rcItem, bGrayed, bSelected,
			(BOOL)lpSkinMenuItemInfo->hSubMenu, lpSkinMenuItemInfo->szText);	// 绘制菜单文本

		if (lpSkinMenuItemInfo->hSubMenu != NULL)	// 绘制子菜单的右三角箭头
			DrawArrow(hMemDC, rcItem);
	}

	rcItem = lpds->rcItem;

	::BitBlt(hDC, rcItem.left, rcItem.top, rcItem.Width(), rcItem.Height(), hMemDC, 0, 0, SRCCOPY);

	if (lpSkinMenuItemInfo->hSubMenu != NULL)	// 不让系统绘制弹出式菜单箭头
		::ExcludeClipRect(hDC, rcItem.left, rcItem.top, rcItem.right, rcItem.bottom);

	::SelectObject(hMemDC, hOldBmp);
	::DeleteObject(hMemBmp);
	::DeleteDC(hMemDC);
}

CSkinMenu& CSkinMenu::operator =(HMENU hMenu)
{
	Attach(hMenu);
	return*this;
}

BOOL CSkinMenu::Attach(HMENU hMenu)
{
	BOOL bRet;

	if (m_hMenu != NULL)
	{
		EnableOwnerDraw(m_hMenu, FALSE);
		::DestroyMenu(m_hMenu);
		m_hMenu = NULL;
	}

	bRet = EnableOwnerDraw(hMenu, TRUE);
	if (!bRet)
	{
		return FALSE;
	}
	else
	{
		m_hMenu = hMenu;
		return TRUE;
	}
}

HMENU CSkinMenu::Detach()
{
	HMENU hMenu = m_hMenu;

	if (m_hMenu != NULL)
	{
		EnableOwnerDraw(m_hMenu, FALSE);
		m_hMenu = NULL;
	}

	return hMenu;
}

BOOL CSkinMenu::DeleteMenu(UINT nPosition, UINT nFlags)
{
	BOOL bByPosition;
	SKIN_MENU_ITEM_INFO* lpSkinMenuItemInfo;

	bByPosition = nFlags & MF_BYPOSITION;
	lpSkinMenuItemInfo = GetMenuItemInfo(nPosition, bByPosition);
	if (lpSkinMenuItemInfo != NULL && SKIN_MENU_MAGIC == lpSkinMenuItemInfo->nMagic)
	{
		if (lpSkinMenuItemInfo->hSubMenu != NULL)
		{
			CSkinMenu SubMenu(lpSkinMenuItemInfo->hSubMenu);
			SubMenu.DeleteMenu(nPosition, nFlags);
		}

		CSkinManager::GetInstance()->ReleaseImage(lpSkinMenuItemInfo->lpIconImgN);
		CSkinManager::GetInstance()->ReleaseImage(lpSkinMenuItemInfo->lpIconImgH);

		delete lpSkinMenuItemInfo;

		SetMenuItemInfo(nPosition, nFlags, NULL);
	}

	return ::DeleteMenu(m_hMenu, nPosition, nFlags);
}

BOOL CSkinMenu::TrackPopupMenu(UINT nFlags, int x, int y, HWND hWnd, LPCRECT lpRect/* = 0*/)
{
	return ::TrackPopupMenu(m_hMenu, nFlags, x, y, 0, hWnd, lpRect);
}

BOOL CSkinMenu::TrackPopupMenuEx(UINT fuFlags, int x, int y, HWND hWnd, LPTPMPARAMS lptpm)
{
	return ::TrackPopupMenuEx(m_hMenu, fuFlags, x, y, hWnd, lptpm);
}

BOOL CSkinMenu::AppendMenu(UINT nFlags, UINT_PTR nIDNewItem/* = 0*/,
						   LPCTSTR lpszNewItem/* = NULL*/)
{
	SKIN_MENU_ITEM_INFO* lpSkinMenuItemInfo;
	int nCount;
	BOOL bRet;

	nFlags |= MF_OWNERDRAW;
	bRet = ::AppendMenu(m_hMenu, nFlags, nIDNewItem, lpszNewItem);
	if (bRet)
	{
		lpSkinMenuItemInfo = new SKIN_MENU_ITEM_INFO;
		if (lpSkinMenuItemInfo != NULL)
		{
			memset(lpSkinMenuItemInfo, 0, sizeof(SKIN_MENU_ITEM_INFO));

			lpSkinMenuItemInfo->nMagic = SKIN_MENU_MAGIC;

			if (nFlags & MF_POPUP)				// 弹出菜单
			{
				lpSkinMenuItemInfo->hSubMenu = (HMENU)nIDNewItem;
				if (lpszNewItem != NULL && _tcslen(lpszNewItem) > 0)
				{
					_tcsncpy(lpSkinMenuItemInfo->szText, lpszNewItem,
						sizeof(lpSkinMenuItemInfo->szText) / sizeof(TCHAR));
				}
				bRet = EnableOwnerDraw(lpSkinMenuItemInfo->hSubMenu, TRUE);
			}
			else
			{
				if (nFlags & MF_SEPARATOR)		// 分隔符
				{
					lpSkinMenuItemInfo->nID = 0;
					lpSkinMenuItemInfo->nType = MFT_SEPARATOR;
				}
				else							// 菜单项
				{
					lpSkinMenuItemInfo->nID = nIDNewItem;
					if (lpszNewItem != NULL && _tcslen(lpszNewItem) > 0)
					{
						_tcsncpy(lpSkinMenuItemInfo->szText, lpszNewItem,
							sizeof(lpSkinMenuItemInfo->szText) / sizeof(TCHAR));
					}
				}
			}

			nCount = ::GetMenuItemCount(m_hMenu);
			bRet = SetMenuItemInfo(nCount - 1, TRUE, lpSkinMenuItemInfo);
		}
	}

	return bRet;
}

UINT CSkinMenu::CheckMenuItem(UINT nIDCheckItem, UINT nCheck)
{
	BOOL bByPosition;
	SKIN_MENU_ITEM_INFO* lpSkinMenuItemInfo;
	UINT nRet = MF_UNCHECKED;

	bByPosition = nCheck & MF_BYPOSITION ? TRUE : FALSE;
	lpSkinMenuItemInfo = GetMenuItemInfo(nIDCheckItem, bByPosition);
	if (lpSkinMenuItemInfo != NULL && SKIN_MENU_MAGIC == lpSkinMenuItemInfo->nMagic)
	{
		if (nCheck & MF_CHECKED)
		{
			lpSkinMenuItemInfo->nState |= MF_CHECKED;
			nRet = MF_CHECKED;
		}
		else
		{
			lpSkinMenuItemInfo->nState &= ~MF_CHECKED;
			nRet = MF_UNCHECKED;
		}
	}

	return nRet;
	//return ::CheckMenuItem(m_hMenu, nIDCheckItem, nCheck);
}

UINT CSkinMenu::EnableMenuItem(UINT nIDEnableItem, UINT nEnable)
{
	BOOL bByPosition;
	SKIN_MENU_ITEM_INFO* lpSkinMenuItemInfo;

	bByPosition = nEnable & MF_BYPOSITION ? TRUE : FALSE;
	lpSkinMenuItemInfo = GetMenuItemInfo(nIDEnableItem, bByPosition);
	if (lpSkinMenuItemInfo != NULL && SKIN_MENU_MAGIC == lpSkinMenuItemInfo->nMagic)
	{
		if (nEnable & MF_DISABLED)
		{
			lpSkinMenuItemInfo->nState |= MF_DISABLED;
			lpSkinMenuItemInfo->nState &= ~MF_ENABLED;
		}
		else if (nEnable & MF_GRAYED)
		{
			lpSkinMenuItemInfo->nState |= MF_GRAYED;
			lpSkinMenuItemInfo->nState &= ~MF_ENABLED;
		}
		else
		{
			lpSkinMenuItemInfo->nState |= MF_ENABLED;
			lpSkinMenuItemInfo->nState &= ~MF_DISABLED;
			lpSkinMenuItemInfo->nState &= ~MF_GRAYED;
		}
	}

	return ::EnableMenuItem(m_hMenu, nIDEnableItem, nEnable);
}

UINT CSkinMenu::GetMenuItemCount() const
{
	return ::GetMenuItemCount(m_hMenu);
}

UINT CSkinMenu::GetMenuItemID(int nPos) const
{
	return ::GetMenuItemID(m_hMenu, nPos);
}

UINT CSkinMenu::GetMenuState(UINT nID, UINT nFlags)
{
	BOOL bByPosition;
	SKIN_MENU_ITEM_INFO* lpSkinMenuItemInfo;
	UINT nRet = 0;

	bByPosition = nFlags & MF_BYPOSITION ? TRUE : FALSE;
	lpSkinMenuItemInfo = GetMenuItemInfo(nID, bByPosition);
	if (lpSkinMenuItemInfo != NULL && SKIN_MENU_MAGIC == lpSkinMenuItemInfo->nMagic)
	{
		nRet = lpSkinMenuItemInfo->nState;
	}

	return nRet;
}

int CSkinMenu::GetMenuString(UINT nIDItem, LPTSTR lpString, int nMaxCount, UINT nFlags)
{
	BOOL bByPosition;
	SKIN_MENU_ITEM_INFO* lpSkinMenuItemInfo;
	int nRet = 0;

	bByPosition = nFlags & MF_BYPOSITION ? TRUE : FALSE;
	lpSkinMenuItemInfo = GetMenuItemInfo(nIDItem, bByPosition);
	if (lpSkinMenuItemInfo != NULL && SKIN_MENU_MAGIC == lpSkinMenuItemInfo->nMagic)
	{
		_tcsncpy(lpString, lpSkinMenuItemInfo->szText, nMaxCount);
		nRet = _tcslen(lpString);
	}

	return nRet;
	//return ::GetMenuString(m_hMenu, nIDItem, lpString, nMaxCount, nFlags);
}

CSkinMenu CSkinMenu::GetSubMenu(int nPos) const
{
	return CSkinMenu(::GetSubMenu(m_hMenu, nPos));
}

BOOL CSkinMenu::InsertMenu(UINT nPosition, UINT nFlags,
						   UINT_PTR nIDNewItem/* = 0*/, LPCTSTR lpszNewItem/* = NULL*/)
{
	BOOL bByPosition;
	SKIN_MENU_ITEM_INFO* lpSkinMenuItemInfo;
	BOOL bRet;

	bByPosition = nFlags & MF_BYPOSITION ? TRUE : FALSE;

	nFlags |= MF_OWNERDRAW;
	bRet = ::InsertMenu(m_hMenu, nPosition, nFlags, nIDNewItem, lpszNewItem);
	if (bRet)
	{
		lpSkinMenuItemInfo = new SKIN_MENU_ITEM_INFO;
		if (lpSkinMenuItemInfo != NULL)
		{
			memset(lpSkinMenuItemInfo, 0, sizeof(SKIN_MENU_ITEM_INFO));

			lpSkinMenuItemInfo->nMagic = SKIN_MENU_MAGIC;
			if (nFlags & MF_POPUP)				// 弹出菜单
			{
				lpSkinMenuItemInfo->hSubMenu = (HMENU)nIDNewItem;
				if (lpszNewItem != NULL && _tcslen(lpszNewItem) > 0)
				{
					_tcsncpy(lpSkinMenuItemInfo->szText, lpszNewItem,
						sizeof(lpSkinMenuItemInfo->szText) / sizeof(TCHAR));
				}

				bRet = EnableOwnerDraw(lpSkinMenuItemInfo->hSubMenu, TRUE);
			}
			else
			{
				if (nFlags & MF_SEPARATOR)		// 分隔符
				{
					lpSkinMenuItemInfo->nID = 0;
					lpSkinMenuItemInfo->nType = MFT_SEPARATOR;
				}
				else if (nFlags & MF_STRING)	// 菜单项
				{
					lpSkinMenuItemInfo->nID = nIDNewItem;
					if (lpszNewItem != NULL && _tcslen(lpszNewItem) > 0)
					{
						_tcsncpy(lpSkinMenuItemInfo->szText, lpszNewItem,
							sizeof(lpSkinMenuItemInfo->szText) / sizeof(TCHAR));
					}
				}
			}

			bRet = SetMenuItemInfo(nPosition, bByPosition, lpSkinMenuItemInfo);
		}
	}

	return bRet;
}

BOOL CSkinMenu::ModifyMenu(UINT nPosition, UINT nFlags,
						   UINT_PTR nIDNewItem/* = 0*/, LPCTSTR lpszNewItem/* = NULL*/)
{
	BOOL bByPosition;
	SKIN_MENU_ITEM_INFO* lpSkinMenuItemInfo;
	BOOL bRet = FALSE;

	bByPosition = nFlags & MF_BYPOSITION ? TRUE : FALSE;
	lpSkinMenuItemInfo = GetMenuItemInfo(nPosition, bByPosition);
	if (lpSkinMenuItemInfo != NULL && SKIN_MENU_MAGIC == lpSkinMenuItemInfo->nMagic)
	{
		//SetMenuItemInfo(nPosition, bByPosition, NULL);

		nFlags |= MF_OWNERDRAW;
		bRet = ::ModifyMenu(m_hMenu, nPosition, nFlags, nIDNewItem, lpszNewItem);
		if (bRet)
		{
			if (nFlags & MF_SEPARATOR)		// 分隔符
			{
				lpSkinMenuItemInfo->nID = 0;
				lpSkinMenuItemInfo->nType = MFT_SEPARATOR;
			}
			else							// 菜单项
			{
				lpSkinMenuItemInfo->nID = nIDNewItem;
				if (lpszNewItem != NULL && _tcslen(lpszNewItem) > 0)
				{
					_tcsncpy(lpSkinMenuItemInfo->szText, lpszNewItem,
						sizeof(lpSkinMenuItemInfo->szText) / sizeof(TCHAR));
				}
			}

			bRet = SetMenuItemInfo(nPosition, bByPosition, lpSkinMenuItemInfo);
		}
	}

	return bRet;
}

BOOL CSkinMenu::RemoveMenu(UINT nPosition, UINT nFlags)
{
	BOOL bByPosition;
	SKIN_MENU_ITEM_INFO* lpSkinMenuItemInfo;
	MENUITEMINFO stMenuItemInfo = {0};
	WCHAR cText[256] = {0};

	bByPosition = nFlags & MF_BYPOSITION ? TRUE : FALSE;
	lpSkinMenuItemInfo = GetMenuItemInfo(nPosition, bByPosition);
	if (lpSkinMenuItemInfo != NULL && SKIN_MENU_MAGIC == lpSkinMenuItemInfo->nMagic)
	{
		if (lpSkinMenuItemInfo->hSubMenu != NULL)
		{
			CSkinMenu SubMenu(lpSkinMenuItemInfo->hSubMenu);
			SubMenu.RemoveMenu(nPosition, nFlags);
		}

		CSkinManager::GetInstance()->ReleaseImage(lpSkinMenuItemInfo->lpIconImgN);
		CSkinManager::GetInstance()->ReleaseImage(lpSkinMenuItemInfo->lpIconImgH);

		delete lpSkinMenuItemInfo;

		SetMenuItemInfo(nPosition, bByPosition, NULL);
	}

	return ::RemoveMenu(m_hMenu, nPosition, nFlags);
}

BOOL CSkinMenu::CheckMenuRadioItem(UINT nIDFirst, UINT nIDLast, UINT nIDItem, UINT nFlags)
{
	BOOL bByPosition;
	SKIN_MENU_ITEM_INFO* lpSkinMenuItemInfo;

	bByPosition = nFlags & MF_BYPOSITION ? TRUE : FALSE;
	for (UINT i = nIDFirst; i <= nIDLast; i++)
	{
		lpSkinMenuItemInfo = GetMenuItemInfo(i, bByPosition);
		if (lpSkinMenuItemInfo != NULL && SKIN_MENU_MAGIC == lpSkinMenuItemInfo->nMagic)
		{
			if (i == nIDItem)
				lpSkinMenuItemInfo->nState |= MF_CHECKED;
			else
				lpSkinMenuItemInfo->nState &= ~MF_CHECKED;
		}
	}

	return ::CheckMenuRadioItem(m_hMenu, nIDFirst, nIDLast, nIDItem, nFlags);
}

BOOL CSkinMenu::IsMenu()
{
	return ::IsMenu(m_hMenu);
}

SKIN_MENU_ITEM_INFO* CSkinMenu::GetMenuItemInfo(UINT nItem, BOOL bByPosition)
{
	MENUITEMINFO stMenuItemInfo = {0};
	BOOL bRet;

	stMenuItemInfo.cbSize = sizeof(MENUITEMINFO);
	stMenuItemInfo.fMask = MIIM_DATA;
	bRet = ::GetMenuItemInfo(m_hMenu, nItem, bByPosition, &stMenuItemInfo);
	if (bRet)
		return (SKIN_MENU_ITEM_INFO*)stMenuItemInfo.dwItemData;
	else
		return NULL;
}

BOOL CSkinMenu::SetMenuItemInfo(UINT nItem, BOOL bByPosition, SKIN_MENU_ITEM_INFO* lpItemInfo)
{
	MENUITEMINFO stMenuItemInfo = {0};

	stMenuItemInfo.cbSize = sizeof(MENUITEMINFO);
	stMenuItemInfo.fMask = MIIM_DATA;
	stMenuItemInfo.dwItemData = (DWORD)lpItemInfo;

	return ::SetMenuItemInfo(m_hMenu, nItem, bByPosition, &stMenuItemInfo);
}

BOOL CSkinMenu::EnableOwnerDraw(HMENU hMenu, BOOL bEnable)
{
	MENUITEMINFO stMenuItemInfo;
	SKIN_MENU_ITEM_INFO* lpSkinMenuItemInfo;
	TCHAR szText[256] = {0};
	int nMenuItemCount;
	BOOL bRet;

	nMenuItemCount = ::GetMenuItemCount(hMenu);
	for (int i = 0; i < nMenuItemCount; i++)
	{
		memset(&stMenuItemInfo, 0, sizeof(stMenuItemInfo));
		stMenuItemInfo.cbSize = sizeof(MENUITEMINFO);
		stMenuItemInfo.fMask = MIIM_SUBMENU | MIIM_DATA | MIIM_ID | MIIM_TYPE | MIIM_STATE;
		stMenuItemInfo.dwTypeData = szText;
		stMenuItemInfo.cch = sizeof(szText) / sizeof(TCHAR);
		bRet = ::GetMenuItemInfo(hMenu, i, TRUE, &stMenuItemInfo);

		if (bEnable)
		{
			if (stMenuItemInfo.hSubMenu != NULL)
				EnableOwnerDraw(stMenuItemInfo.hSubMenu, bEnable);

			if (!(stMenuItemInfo.fType & MFT_OWNERDRAW))	// 未起用菜单自绘
			{
				lpSkinMenuItemInfo = (SKIN_MENU_ITEM_INFO*)stMenuItemInfo.dwItemData;
				if (lpSkinMenuItemInfo != NULL && SKIN_MENU_MAGIC == lpSkinMenuItemInfo->nMagic)
				{
					CSkinManager::GetInstance()->ReleaseImage(lpSkinMenuItemInfo->lpIconImgN);
					CSkinManager::GetInstance()->ReleaseImage(lpSkinMenuItemInfo->lpIconImgH);

					lpSkinMenuItemInfo->nMagic = NULL;

					delete lpSkinMenuItemInfo;
				}

				lpSkinMenuItemInfo = new SKIN_MENU_ITEM_INFO;
				if (lpSkinMenuItemInfo != NULL)
				{
					lpSkinMenuItemInfo->nMagic = SKIN_MENU_MAGIC;
					lpSkinMenuItemInfo->nID = stMenuItemInfo.wID;
					lpSkinMenuItemInfo->nState = stMenuItemInfo.fState;
					lpSkinMenuItemInfo->nType = stMenuItemInfo.fType;
					if (stMenuItemInfo.dwTypeData != NULL && _tcslen(stMenuItemInfo.dwTypeData) > 0)
					{
						_tcsncpy(lpSkinMenuItemInfo->szText, stMenuItemInfo.dwTypeData,
							sizeof(lpSkinMenuItemInfo->szText) / sizeof(TCHAR));
					}
					lpSkinMenuItemInfo->hSubMenu = stMenuItemInfo.hSubMenu;
					lpSkinMenuItemInfo->lpIconImgN = NULL;
					lpSkinMenuItemInfo->lpIconImgH = NULL;

					stMenuItemInfo.fMask = MIIM_TYPE | MIIM_DATA;
					stMenuItemInfo.fType |= MFT_OWNERDRAW;
					stMenuItemInfo.dwItemData = (DWORD)lpSkinMenuItemInfo;
					bRet = ::SetMenuItemInfo(hMenu, i, TRUE, &stMenuItemInfo);
				}
			}
		}
		else
		{
			if (stMenuItemInfo.hSubMenu != NULL)
				EnableOwnerDraw(stMenuItemInfo.hSubMenu, bEnable);

			lpSkinMenuItemInfo = (SKIN_MENU_ITEM_INFO*)stMenuItemInfo.dwItemData;
			if (lpSkinMenuItemInfo != NULL && SKIN_MENU_MAGIC == lpSkinMenuItemInfo->nMagic)
			{
				CSkinManager::GetInstance()->ReleaseImage(lpSkinMenuItemInfo->lpIconImgN);
				CSkinManager::GetInstance()->ReleaseImage(lpSkinMenuItemInfo->lpIconImgH);

				delete lpSkinMenuItemInfo;

				stMenuItemInfo.fMask = MIIM_DATA;
				stMenuItemInfo.dwItemData = NULL;
				bRet = ::SetMenuItemInfo(hMenu, i, TRUE, &stMenuItemInfo);
			}
		}
	}

	return TRUE;
}

SIZE CSkinMenu::GetTextExtent(LPCTSTR lpszText)
{
	HDC hDC;
	RECT rcText = {0};
	SIZE sz = {0};
	HFONT hOldFont;

	if (NULL == lpszText || _tcslen(lpszText) <= 0)
		return sz;

	hDC = ::GetDC(NULL);
	hOldFont = (HFONT)::SelectObject(hDC, m_hFont);
	::DrawText(hDC, lpszText, _tcslen(lpszText), &rcText, DT_SINGLELINE | DT_CALCRECT);
	::SelectObject(hDC, hOldFont);
	::ReleaseDC(NULL, hDC);

	sz.cx = rcText.right - rcText.left;
	sz.cy = rcText.bottom - rcText.top;

	return sz;
}

// 绘制菜单顶背景
void CSkinMenu::DrawBg(HDC hDC, CRect& rect)
{
	if (m_lpBgImgL != NULL && !m_lpBgImgL->IsNull())
	{
		CRect rcLeft(rect);
		rcLeft.right = rcLeft.left + m_nLMargin;
		m_lpBgImgL->Draw(hDC, rcLeft);
	}

	if (m_lpBgImgR != NULL && !m_lpBgImgR->IsNull())
	{
		CRect rcRight(rect);
		rcRight.left += m_nLMargin;
		m_lpBgImgR->Draw(hDC, rcRight);
	}
}

// 绘制分隔符
void CSkinMenu::DrawSepartor(HDC hDC, CRect& rect)
{
	if (m_lpSepartorImg != NULL && !m_lpSepartorImg->IsNull())
	{
		CRect rcSepartor(rect);
		rcSepartor.left += m_nLMargin;
		m_lpSepartorImg->Draw(hDC, rcSepartor);
	}
}

// 填充选中区域
void CSkinMenu::DrawSelRect(HDC hDC, CRect& rect)
{
	if (m_lpSelectedImg != NULL && !m_lpSelectedImg->IsNull())
		m_lpSelectedImg->Draw(hDC, rect);
}

// 绘制菜单图标
void CSkinMenu::DrawIcon(HDC hDC, CRect& rect, CImageEx* lpIconImg)
{
	if (lpIconImg != NULL && !lpIconImg->IsNull())
	{
		int cxIcon = lpIconImg->GetWidth();
		int cyIcon = lpIconImg->GetHeight();

		CRect rcLeft(rect);
		rcLeft.right = rcLeft.left + m_nLMargin;

		int x = (rcLeft.Width() - cxIcon + 1) / 2;
		int y = (rcLeft.Height() - cyIcon + 1) / 2;

		CRect rcIcon(x, y, x+cxIcon, y+cyIcon);
		lpIconImg->Draw(hDC, rcIcon);
	}
}

// 绘制Check状态
void CSkinMenu::DrawCheckState(HDC hDC, CRect& rect)
{
	DrawIcon(hDC, rect, m_lpCheckImg);
}

// 绘制菜单文本
void CSkinMenu::DrawText(HDC hDC, CRect& rect, BOOL bGrayed,
						 BOOL bSelected, BOOL bIsSubMenu, LPCTSTR lpText)
{
	int nMode;
	COLORREF clrColor;

	CRect rcText(rect);
	rcText.left = m_nLMargin + 8;
	rcText.right -= 8;

	if (bIsSubMenu)
	{
		if (m_lpArrowImg != NULL && !m_lpArrowImg->IsNull())
			rcText.right = rcText.right - m_lpArrowImg->GetWidth() - 8;
		else
			rcText.right = rcText.right - 5 - 8;
	}

	nMode = ::SetBkMode(hDC, TRANSPARENT);

	if (bGrayed)
	{
		clrColor = m_clrGrayedText;
	}
	else
	{
		if (bSelected)
			clrColor = m_clrSelText;
		else
			clrColor = m_clrText;
	}

	::SetTextColor(hDC, clrColor);
	HFONT hOldFont = (HFONT)::SelectObject(hDC, m_hFont);
	::DrawText(hDC, lpText, _tcslen(lpText), &rcText, DT_LEFT | DT_SINGLELINE | DT_VCENTER);
	::SelectObject(hDC, hOldFont);

	::SetBkMode(hDC, nMode);
}

// 绘制弹出式菜单箭头
void CSkinMenu::DrawArrow(HDC hDC, CRect& rect)
{
	if (m_lpArrowImg != NULL && !m_lpArrowImg->IsNull())
	{
		int cxArrow = m_lpArrowImg->GetWidth();
		int cyArrow = m_lpArrowImg->GetHeight();

		int x = rect.right - 8 - cxArrow;
		int y = (rect.Height() - cyArrow + 1) / 2;

		CRect rcArrow(x, y, x+cxArrow, y+cyArrow);

		m_lpArrowImg->Draw(hDC, rcArrow);
	}
}


//
//     Generated by class-dump 3.5 (64 bit) (Debug version compiled Jun  9 2015 22:53:21).
//
//     class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2014 by Steve Nygard.
//

#import "TToolbarItem.h"

@interface TQuickLookToolbarItem : TToolbarItem
{
}

- (void)flagsDidChange:(id)arg1;
- (void)flagsMayHaveChanged:(id)arg1;
- (void)setImageFromFlags:(unsigned long long)arg1;
- (void)dealloc;
- (id)initWithItemIdentifier:(id)arg1 entry:(const struct ToolbarItemInfo *)arg2 controller:(id)arg3 propertyList:(id)arg4 willBeInsertedIntoToolbar:(_Bool)arg5;

@end


import {html} from 'lit-element';
import {signIn} from '../../fb';
import {BaseStateElement} from '../BaseStateElement';
import './_styles.scss';

/* eslint-disable require-jsdoc */
class SigninButton extends BaseStateElement {
  static get properties() {
    return {
      checkingSignedInState: {type: Boolean},
      isSignedIn: {type: Boolean},
    };
  }

  render() {
    if (this.isSignedIn) {
      // lit-element ignores "" (prior to 2.2.2), so return an empty template.
      return html``;
    }

    // We don't set "disabled" attribute on the <button> based on this, because
    // it causes a visual transition. Just disable the action while checking.
    const action = this.checkingSignedInState ? null : signIn;

    return html`
      <button
        @click=${action}
        class="w-button w-button--secondary lh-signin-button gc-analytics-event"
        data-category="web.dev"
        data-label="measure, big sign-in"
        data-action="click"
      >
        <svg
          class="w-mr--sm"
          xmlns="http://www.w3.org/2000/svg"
          xmlns:xlink="http://www.w3.org/1999/xlink"
          viewBox="0 0 48 48"
          width="24"
          heigh="24"
        >
          <defs>
            <path
              id="a"
              d="M44.5 20H24v8.5h11.8C34.7 33.9 30.1 37 24 37c-7.2 0-13-5.8-13-13s5.8-13 13-13c3.1 0 5.9 1.1 8.1 2.9l6.4-6.4C34.6 4.1 29.6 2 24 2 11.8 2 2 11.8 2 24s9.8 22 22 22c11 0 21-8 21-22 0-1.3-.2-2.7-.5-4z"
            />
          </defs>
          <clipPath id="b"><use xlink:href="#a" overflow="visible" /></clipPath>
          <path clip-path="url(#b)" fill="#FBBC05" d="M0 37V11l17 13z" />
          <path
            clip-path="url(#b)"
            fill="#EA4335"
            d="M0 11l17 13 7-6.1L48 14V0H0z"
          />
          <path
            clip-path="url(#b)"
            fill="#34A853"
            d="M0 37l30-23 7.9 1L48 0v48H0z"
          />
          <path
            clip-path="url(#b)"
            fill="#4285F4"
            d="M48 48L17 24l-4-3 35-10z"
          />
        </svg>
        Sign in with Google
      </button>
    `;
  }

  onStateChanged({checkingSignedInState, isSignedIn}) {
    this.checkingSignedInState = checkingSignedInState;
    this.isSignedIn = isSignedIn;
  }
}

customElements.define('web-signin-button', SigninButton);


/*
 * Copyright 2013 Frank Breedijk
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
steal('funcunit').then(function(){

module("Seccubus.Notification.Table", {
	setup: function(){
		S.open("//seccubus/notification/table/table.html");
	}
});

test("Text Test", function(){
	equals(S("h1").text(), "Seccubus.Notification.Table Demo","demo text");
});

});


from ebdata.blobs.scrapers import IncrementalCrawler
import re

class ChicagoCityPressReleaseCrawler(IncrementalCrawler):
    schema = 'city-press-releases'
    seed_url = 'http://egov.cityofchicago.org/'
    date_headline_re = re.compile(r'(?s)E-mail: .*?
\s*(?P<article_date>.*?)\s*	\s*
\s*
\s*(?P<article_headline>.*?)	')
    date_format = '%A, %B %d, %Y'
    max_blanks = 60

    def public_url(self, id_value):
        return 'http://egov.cityofchicago.org/city/webportal/portalContentItemAction.do?contenTypeName=COC_EDITORIAL&topChannelName=HomePage&contentOID=%s' % id_value

    def retrieval_url(self, id_value):
        return 'http://egov.cityofchicago.org/city/webportal/jsp/content/showNewsItem.jsp?print=true&contenTypeName=1006&contentOID=%s' % id_value

    def id_for_url(self, url):
        return url.split('contentOID=')[1]

if __name__ == "__main__":
    from ebdata.retrieval import log_debug
    ChicagoCityPressReleaseCrawler().update()


ecc-jsbn
========

ECC package based on [jsbn](https://github.com/andyperlitch/jsbn) from [Tom Wu](http://www-cs-students.stanford.edu/~tjw/).

This is a subset of the same interface as the [node compiled module](https://github.com/quartzjer/ecc), but works in the browser too.

Also uses point compression now from [https://github.com/kaielvin](https://github.com/kaielvin/jsbn-ec-point-compression).


#!/usr/bin/env python
# Copyright (c) 2002-2005 ActiveState Corp.
# See LICENSE.txt for license details.
# Author:
#   Trent Mick (TrentM@ActiveState.com)
# Home:
#   http://trentm.com/projects/which/

r"""Find the full path to commands.

which(command, path=None, verbose=0, exts=None)
    Return the full path to the first match of the given command on the
    path.

whichall(command, path=None, verbose=0, exts=None)
    Return a list of full paths to all matches of the given command on
    the path.

whichgen(command, path=None, verbose=0, exts=None)
    Return a generator which will yield full paths to all matches of the
    given command on the path.

By default the PATH environment variable is searched (as well as, on
Windows, the AppPaths key in the registry), but a specific 'path' list
to search may be specified as well.  On Windows, the PATHEXT environment
variable is applied as appropriate.

If "verbose" is true then a tuple of the form
    (<fullpath>, <matched-where-description>)
is returned for each match. The latter element is a textual description
of where the match was found. For example:
    from PATH element 0
    from HKLM\SOFTWARE\...\perl.exe
"""

_cmdlnUsage = """
    Show the full path of commands.

    Usage:
        which [<options>...] [<command-name>...]

    Options:
        -h, --help      Print this help and exit.
        -V, --version   Print the version info and exit.

        -a, --all       Print *all* matching paths.
        -v, --verbose   Print out how matches were located and
                        show near misses on stderr.
        -q, --quiet     Just print out matches. I.e., do not print out
                        near misses.

        -p <altpath>, --path=<altpath>
                        An alternative path (list of directories) may
                        be specified for searching.
        -e <exts>, --exts=<exts>
                        Specify a list of extensions to consider instead
                        of the usual list (';'-separate list, Windows
                        only).

    Show the full path to the program that would be run for each given
    command name, if any. Which, like GNU's which, returns the number of
    failed arguments, or -1 when no <command-name> was given.

    Near misses include duplicates, non-regular files and (on Un*x)
    files without executable access.
"""

__revision__ = "$Id: which.py 430 2005-08-20 03:11:58Z trentm $"
__version_info__ = (1, 1, 0)
__version__ = '.'.join(map(str, __version_info__))

import os
import sys
import getopt
import stat

#---- exceptions

class WhichError(Exception):
    pass

#---- internal support stuff

def _getRegisteredExecutable(exeName):
    """Windows allow application paths to be registered in the registry."""
    registered = None
    if sys.platform.startswith('win'):
        if os.path.splitext(exeName)[1].lower() != '.exe':
            exeName += '.exe'
        if sys.version_info[0] < 3:
            import _winreg as winreg
        else:
            import winreg
        try:
            key = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\" +\
                  exeName
            value = winreg.QueryValue(winreg.HKEY_LOCAL_MACHINE, key)
            registered = (value, "from HKLM\\"+key)
        except winreg.error:
            pass
        if registered and not os.path.exists(registered[0]):
            registered = None
    return registered

def _samefile(fname1, fname2):
    if sys.platform.startswith('win'):
        return ( os.path.normpath(os.path.normcase(fname1)) ==\
            os.path.normpath(os.path.normcase(fname2)) )
    else:
        return os.path.samefile(fname1, fname2)

def _cull(potential, matches, verbose=0):
    """Cull inappropriate matches. Possible reasons:
        - a duplicate of a previous match
        - not a disk file
        - not executable (non-Windows)
    If 'potential' is approved it is returned and added to 'matches'.
    Otherwise, None is returned.
    """
    for match in matches:  # don't yield duplicates
        if _samefile(potential[0], match[0]):
            if verbose:
                sys.stderr.write("duplicate: %s (%s)\n" % potential)
            return None
    else:
        if not stat.S_ISREG(os.stat(potential[0]).st_mode):
            if verbose:
                sys.stderr.write("not a regular file: %s (%s)\n" % potential)
        elif not os.access(potential[0], os.X_OK):
            if verbose:
                sys.stderr.write("no executable access: %s (%s)\n"\
                                 % potential)
        else:
            matches.append(potential)
            return potential

#---- module API

def whichgen(command, path=None, verbose=0, exts=None):
    """Return a generator of full paths to the given command.

    "command" is a the name of the executable to search for.
    "path" is an optional alternate path list to search. The default it
        to use the PATH environment variable.
    "verbose", if true, will cause a 2-tuple to be returned for each
        match. The second element is a textual description of where the
        match was found.
    "exts" optionally allows one to specify a list of extensions to use
        instead of the standard list for this system. This can
        effectively be used as an optimization to, for example, avoid
        stat's of "foo.vbs" when searching for "foo" and you know it is
        not a VisualBasic script but ".vbs" is on PATHEXT. This option
        is only supported on Windows.

    This method returns a generator which yields either full paths to
    the given command or, if verbose, tuples of the form (<path to
    command>, <where path found>).
    """
    matches = []
    if path is None:
        usingGivenPath = 0
        path = os.environ.get("PATH", "").split(os.pathsep)
        if sys.platform.startswith("win"):
            path.insert(0, os.curdir)  # implied by Windows shell
    else:
        usingGivenPath = 1

    # Windows has the concept of a list of extensions (PATHEXT env var).
    if sys.platform.startswith("win"):
        if exts is None:
            exts = os.environ.get("PATHEXT", "").split(os.pathsep)
            # If '.exe' is not in exts then obviously this is Win9x and
            # or a bogus PATHEXT, then use a reasonable default.
            for ext in exts:
                if ext.lower() == ".exe":
                    break
            else:
                exts = ['.COM', '.EXE', '.BAT']
        elif not isinstance(exts, list):
            raise TypeError("'exts' argument must be a list or None")
    else:
        if exts is not None:
            raise WhichError("'exts' argument is not supported on "\
                             "platform '%s'" % sys.platform)
        exts = []

    # File name cannot have path separators because PATH lookup does not
    # work that way.
    if os.sep in command or os.altsep and os.altsep in command:
        pass
    else:
        for i in range(len(path)):
            dirName = path[i]
            # On windows the dirName *could* be quoted, drop the quotes
            if sys.platform.startswith("win") and len(dirName) >= 2\
               and dirName[0] == '"' and dirName[-1] == '"':
                dirName = dirName[1:-1]
            for ext in ['']+exts:
                absName = os.path.abspath(
                    os.path.normpath(os.path.join(dirName, command+ext)))
                if os.path.isfile(absName):
                    if usingGivenPath:
                        fromWhere = "from given path element %d" % i
                    elif not sys.platform.startswith("win"):
                        fromWhere = "from PATH element %d" % i
                    elif i == 0:
                        fromWhere = "from current directory"
                    else:
                        fromWhere = "from PATH element %d" % (i-1)
                    match = _cull((absName, fromWhere), matches, verbose)
                    if match:
                        if verbose:
                            yield match
                        else:
                            yield match[0]
        match = _getRegisteredExecutable(command)
        if match is not None:
            match = _cull(match, matches, verbose)
            if match:
                if verbose:
                    yield match
                else:
                    yield match[0]

def which(command, path=None, verbose=0, exts=None):
    """Return the full path to the first match of the given command on
    the path.

    "command" is a the name of the executable to search for.
    "path" is an optional alternate path list to search. The default it
        to use the PATH environment variable.
    "verbose", if true, will cause a 2-tuple to be returned. The second
        element is a textual description of where the match was found.
    "exts" optionally allows one to specify a list of extensions to use
        instead of the standard list for this system. This can
        effectively be used as an optimization to, for example, avoid
        stat's of "foo.vbs" when searching for "foo" and you know it is
        not a VisualBasic script but ".vbs" is on PATHEXT. This option
        is only supported on Windows.

    If no match is found for the command, a WhichError is raised.
    """
    try:
        if sys.version_info[0] < 3:
            match = whichgen(command, path, verbose, exts).next()
        else:
            match = next(whichgen(command, path, verbose, exts))
    except StopIteration:
        raise WhichError("Could not find '%s' on the path." % command)
    return match

def whichall(command, path=None, verbose=0, exts=None):
    """Return a list of full paths to all matches of the given command
    on the path.

    "command" is a the name of the executable to search for.
    "path" is an optional alternate path list to search. The default it
        to use the PATH environment variable.
    "verbose", if true, will cause a 2-tuple to be returned for each
        match. The second element is a textual description of where the
        match was found.
    "exts" optionally allows one to specify a list of extensions to use
        instead of the standard list for this system. This can
        effectively be used as an optimization to, for example, avoid
        stat's of "foo.vbs" when searching for "foo" and you know it is
        not a VisualBasic script but ".vbs" is on PATHEXT. This option
        is only supported on Windows.
    """
    return list( whichgen(command, path, verbose, exts) )

#---- mainline

def main(argv):
    all = 0
    verbose = 0
    altpath = None
    exts = None
    try:
        optlist, args = getopt.getopt(argv[1:], 'haVvqp:e:',
            ['help', 'all', 'version', 'verbose', 'quiet', 'path=', 'exts='])
    except getopt.GetoptError:
        sys.stderr.write("which: error: %s. Your invocation was: %s\n"\
                         % (sys.exc_info(), argv))
        sys.stderr.write("Try 'which --help'.\n")
        return 1
    for opt, optarg in optlist:
        if opt in ('-h', '--help'):
            print(_cmdlnUsage)
            return 0
        elif opt in ('-V', '--version'):
            print("which %s" % __version__)
            return 0
        elif opt in ('-a', '--all'):
            all = 1
        elif opt in ('-v', '--verbose'):
            verbose = 1
        elif opt in ('-q', '--quiet'):
            verbose = 0
        elif opt in ('-p', '--path'):
            if optarg:
                altpath = optarg.split(os.pathsep)
            else:
                altpath = []
        elif opt in ('-e', '--exts'):
            if optarg:
                exts = optarg.split(os.pathsep)
            else:
                exts = []

    if len(args) == 0:
        return -1

    failures = 0
    for arg in args:
        #print("debug: search for %r" % arg)
        nmatches = 0
        for match in whichgen(arg, path=altpath, verbose=verbose, exts=exts):
            if verbose:
                print("%s (%s)" % match)
            else:
                print(match)
            nmatches += 1
            if not all:
                break
        if not nmatches:
            failures += 1
    return failures

if __name__ == "__main__":
    sys.exit( main(sys.argv) )