text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Grasshopper.Kernel;
using Rhino.Geometry;

namespace RhinoNestForGrasshopper.Nesting
{
    class RhinoNestClass:Grasshopper.Kernel.IGH_Param
    {
        public Rhino.Geometry.GeometryBase Geometry{ get; set; }
        public int Copies {get;set;}
        public int Rotation { get; set; }
        public int Priority { get; set; }
        public GH_ParamAccess Access
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }
        public void AddSource(IGH_Param source, int index)
        {
            throw new NotImplementedException();
        }

        public void AddSource(IGH_Param source)
        {
            throw new NotImplementedException();
        }

        public bool AddVolatileData(Grasshopper.Kernel.Data.GH_Path path, int index, object data)
        {
            throw new NotImplementedException();
        }

        public bool AddVolatileDataList(Grasshopper.Kernel.Data.GH_Path path, System.Collections.IEnumerable list)
        {
            throw new NotImplementedException();
        }

        public bool AddVolatileDataTree(Grasshopper.Kernel.Data.IGH_Structure tree)
        {
            throw new NotImplementedException();
        }

        public void ClearProxySources()
        {
            throw new NotImplementedException();
        }

        public void CreateProxySources()
        {
            throw new NotImplementedException();
        }

        public GH_DataMapping DataMapping
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public GH_ParamData DataType
        {
            get { throw new NotImplementedException(); }
        }

        public bool HasProxySources
        {
            get { throw new NotImplementedException(); }
        }

        public GH_ParamKind Kind
        {
            get { throw new NotImplementedException(); }
        }

        public bool Optional
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public int ProxySourceCount
        {
            get { throw new NotImplementedException(); }
        }

        public IList<IGH_Param> Recipients
        {
            get { throw new NotImplementedException(); }
        }

        public bool RelinkProxySources(GH_Document document)
        {
            throw new NotImplementedException();
        }

        public void RemoveAllSources()
        {
            throw new NotImplementedException();
        }

        public void RemoveEffects()
        {
            throw new NotImplementedException();
        }

        public void RemoveSource(Guid source_id)
        {
            throw new NotImplementedException();
        }

        public void RemoveSource(IGH_Param source)
        {
            throw new NotImplementedException();
        }

        public void ReplaceSource(Guid old_source_id, IGH_Param new_source)
        {
            throw new NotImplementedException();
        }

        public void ReplaceSource(IGH_Param old_source, IGH_Param new_source)
        {
            throw new NotImplementedException();
        }

        public bool Reverse
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public bool Simplify
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public int SourceCount
        {
            get { throw new NotImplementedException(); }
        }

        public IList<IGH_Param> Sources
        {
            get { throw new NotImplementedException(); }
        }

        public GH_StateTagList StateTags
        {
            get { throw new NotImplementedException(); }
        }

        public Type Type
        {
            get { throw new NotImplementedException(); }
        }

        public string TypeName
        {
            get { throw new NotImplementedException(); }
        }

        public Grasshopper.Kernel.Data.IGH_Structure VolatileData
        {
            get { throw new NotImplementedException(); }
        }

        public int VolatileDataCount
        {
            get { throw new NotImplementedException(); }
        }

        public GH_ParamWireDisplay WireDisplay
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public void AddRuntimeMessage(GH_RuntimeMessageLevel Type, string Message)
        {
            throw new NotImplementedException();
        }

        public void ClearData()
        {
            throw new NotImplementedException();
        }

        public void ClearRuntimeMessages()
        {
            throw new NotImplementedException();
        }

        public void CollectData()
        {
            throw new NotImplementedException();
        }

        public void ComputeData()
        {
            throw new NotImplementedException();
        }

        public bool DependsOn(IGH_ActiveObject PotentialSource)
        {
            throw new NotImplementedException();
        }

        public bool IsDataProvider
        {
            get { throw new NotImplementedException(); }
        }

        public bool Locked
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public bool MutableNickName
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public GH_SolutionPhase Phase
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public TimeSpan ProcessorTime
        {
            get { throw new NotImplementedException(); }
        }

        public void RegisterRemoteIDs(GH_GuidTable id_list)
        {
            throw new NotImplementedException();
        }

        public GH_RuntimeMessageLevel RuntimeMessageLevel
        {
            get { throw new NotImplementedException(); }
        }

        public IList<string> RuntimeMessages(GH_RuntimeMessageLevel level)
        {
            throw new NotImplementedException();
        }

        public bool SDKCompliancy(int exeVersion, int exeServiceRelease)
        {
            throw new NotImplementedException();
        }

        public void AddedToDocument(GH_Document document)
        {
            throw new NotImplementedException();
        }

        public bool AppendMenuItems(System.Windows.Forms.ToolStripDropDown menu)
        {
            throw new NotImplementedException();
        }

        public IGH_Attributes Attributes
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public event IGH_DocumentObject.AttributesChangedEventHandler AttributesChanged;

        public Guid ComponentGuid
        {
            get { throw new NotImplementedException(); }
        }

        public void CreateAttributes()
        {
            throw new NotImplementedException();
        }

        public event IGH_DocumentObject.DisplayExpiredEventHandler DisplayExpired;

        public void DocumentContextChanged(GH_Document document, GH_DocumentContext context)
        {
            throw new NotImplementedException();
        }

        public void ExpirePreview(bool redraw)
        {
            throw new NotImplementedException();
        }

        public void ExpireSolution(bool recompute)
        {
            throw new NotImplementedException();
        }

        public GH_Exposure Exposure
        {
            get { throw new NotImplementedException(); }
        }

        public GH_IconDisplayMode IconDisplayMode
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public System.Drawing.Bitmap Icon_24x24
        {
            get { throw new NotImplementedException(); }
        }

        public System.Drawing.Bitmap Icon_24x24_Locked
        {
            get { throw new NotImplementedException(); }
        }

        public void IsolateObject()
        {
            throw new NotImplementedException();
        }

        public void MovedBetweenDocuments(GH_Document oldDocument, GH_Document newDocument)
        {
            throw new NotImplementedException();
        }

        public event IGH_DocumentObject.ObjectChangedEventHandler ObjectChanged;

        public bool Obsolete
        {
            get { throw new NotImplementedException(); }
        }

        public void OnAttributesChanged()
        {
            throw new NotImplementedException();
        }

        public void OnDisplayExpired(bool redraw)
        {
            throw new NotImplementedException();
        }

        public void OnObjectChanged(GH_ObjectChangedEventArgs e)
        {
            throw new NotImplementedException();
        }

        public void OnObjectChanged(string customEvent, object tag)
        {
            throw new NotImplementedException();
        }

        public void OnObjectChanged(GH_ObjectEventType eventType, object tag)
        {
            throw new NotImplementedException();
        }

        public void OnObjectChanged(string customEvent)
        {
            throw new NotImplementedException();
        }

        public void OnObjectChanged(GH_ObjectEventType eventType)
        {
            throw new NotImplementedException();
        }

        public GH_Document OnPingDocument()
        {
            throw new NotImplementedException();
        }

        public void OnPreviewExpired(bool redraw)
        {
            throw new NotImplementedException();
        }

        public void OnSolutionExpired(bool recompute)
        {
            throw new NotImplementedException();
        }

        public event IGH_DocumentObject.PingDocumentEventHandler PingDocument;

        public event IGH_DocumentObject.PreviewExpiredEventHandler PreviewExpired;

        public void RecordUndoEvent(Grasshopper.Kernel.Undo.GH_UndoRecord record)
        {
            throw new NotImplementedException();
        }

        public Guid RecordUndoEvent(string name, Grasshopper.Kernel.Undo.IGH_UndoAction action)
        {
            throw new NotImplementedException();
        }

        public Guid RecordUndoEvent(string name)
        {
            throw new NotImplementedException();
        }

        public void RemovedFromDocument(GH_Document document)
        {
            throw new NotImplementedException();
        }

        public event IGH_DocumentObject.SolutionExpiredEventHandler SolutionExpired;

        public void TriggerAutoSave(GH_AutoSaveTrigger trigger, Guid id)
        {
            throw new NotImplementedException();
        }

        public void TriggerAutoSave(Guid id)
        {
            throw new NotImplementedException();
        }

        public void TriggerAutoSave(GH_AutoSaveTrigger trigger)
        {
            throw new NotImplementedException();
        }

        public void TriggerAutoSave()
        {
            throw new NotImplementedException();
        }

        public string Category
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public string Description
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public bool HasCategory
        {
            get { throw new NotImplementedException(); }
        }

        public bool HasSubCategory
        {
            get { throw new NotImplementedException(); }
        }

        public string InstanceDescription
        {
            get { throw new NotImplementedException(); }
        }

        public Guid InstanceGuid
        {
            get { throw new NotImplementedException(); }
        }

        public IEnumerable<string> Keywords
        {
            get { throw new NotImplementedException(); }
        }

        public string Name
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public void NewInstanceGuid(Guid UUID)
        {
            throw new NotImplementedException();
        }

        public void NewInstanceGuid()
        {
            throw new NotImplementedException();
        }

        public string NickName
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public string SubCategory
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public bool Read(GH_IO.Serialization.GH_IReader reader)
        {
            throw new NotImplementedException();
        }

        public bool Write(GH_IO.Serialization.GH_IWriter writer)
        {
            throw new NotImplementedException();
        }
    }
}


text:
<?php

declare(strict_types=1);

namespace IssetBV\PushNotification\Type\Android;

use IssetBV\PushNotification\Core\Connection\ConnectionException;
use IssetBV\PushNotification\Core\Connection\ConnectionHandlerException;
use IssetBV\PushNotification\Core\Message\Message;
use IssetBV\PushNotification\Core\Message\MessageEnvelope;
use IssetBV\PushNotification\Core\Message\MessageEnvelopeQueue;
use IssetBV\PushNotification\Core\NotifierAbstract;
use IssetBV\PushNotification\Type\Android\Message\AndroidMessage;
use IssetBV\PushNotification\Type\Android\Message\AndroidMessageEnvelope;

/**
 * Class AndroidNotifier.
 */
class AndroidNotifier extends NotifierAbstract
{
    /**
     * @param Message $message
     *
     * @return bool
     */
    public function handles(Message $message): bool
    {
        return $message instanceof AndroidMessage;
    }

    /**
     * @param Message $message
     * @param string $connectionName
     *
     * @throws ConnectionHandlerException
     * @throws ConnectionException
     *
     * @return MessageEnvelope
     */
    protected function sendMessage(Message $message, string $connectionName = null): MessageEnvelope
    {
        /* @var AndroidMessage $message */
        $connection = $this->getConnectionHandler()->getConnection($connectionName);
        /* @var AndroidConnection $connection */
        $messageEnvelope = $this->createMessageEnvelope($message);
        /* @var AndroidMessageEnvelope $messageEnvelope */
        $this->sendMessageEnvelope($connection, $messageEnvelope);

        return $messageEnvelope;
    }

    /**
     * @param Message $message
     *
     * @return MessageEnvelope
     */
    protected function createMessageEnvelope(Message $message): MessageEnvelope
    {
        /* @var AndroidMessage $message */
        return new AndroidMessageEnvelope($message);
    }

    /**
     * @param string $connectionName
     * @param MessageEnvelopeQueue $queue
     *
     * @throws ConnectionHandlerException
     * @throws ConnectionException
     */
    protected function flushQueueItem(string $connectionName = null, MessageEnvelopeQueue $queue)
    {
        if ($queue->isEmpty()) {
            return;
        }
        $connection = $this->getConnectionHandler()->getConnection($connectionName);
        /* @var AndroidConnection $connection */
        foreach ($queue->getQueue() as $messageEnvelope) {
            /* @var AndroidMessageEnvelope $messageEnvelope */
            $this->sendMessageEnvelope($connection, $messageEnvelope);
        }
        $queue->clear();
    }

    /**
     * @param AndroidConnection $connection
     * @param AndroidMessageEnvelope $messageEnvelope
     */
    private function sendMessageEnvelope(AndroidConnection $connection, AndroidMessageEnvelope $messageEnvelope)
    {
        $response = $connection->sendAndReceive($messageEnvelope->getMessage());
        $messageEnvelope->setResponse($response);
        if ($response->isSuccess()) {
            $messageEnvelope->setState(MessageEnvelope::SUCCESS);
        } else {
            $messageEnvelope->setState(MessageEnvelope::FAILED);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.lingju.assistant.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.lingju.assistant.AppConfig;
import com.lingju.assistant.R;
import com.lingju.assistant.entity.ZipCodeMap;
import com.lingju.assistant.service.AssistantService;
import com.lingju.assistant.view.CommonDialog;
import com.lingju.common.log.Log;
import com.lingju.model.Item;
import com.lingju.model.SubItem;
import com.lingju.model.Zipcode;
import com.lingju.model.dao.AccountItemDao;
import com.lingju.model.dao.CallAndSmsDao;
import com.lingju.util.ScreenUtil;
import com.tencent.stat.StatConfig;
import com.tencent.stat.StatService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class StartUpActivity extends Activity implements ActivityCompat.OnRequestPermissionsResultCallback {
    private String TAG = "StartUpActivity";
    //Class target=LoginActivity.class;
    /**
     * 收入标记
     **/
    private final static int ITEM_INCOME = 0;
    /**
     * 支出标记
     **/
    private final static int ITEM_EXPENSE = 1;
    private WaitTask mWaitTask;
    private ImageView mImg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AppConfig.ShowGuide = true;
        ScreenUtil.getInstance().init(this);
        try {
            //if (isStoragePermissionGranted()) {
            // init();
            //}
            StartUpActivityPermissionsDispatcher.initWithCheck(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.i(TAG, "onCreate>>" + Boolean.toString(AppConfig.MainProgressInited));
    }

    @Override
    protected void onDestroy() {
        Log.i(TAG, "StartUpActivity onDestroy()");
        if (mWaitTask != null) {
            mWaitTask.cancel(true);
        }
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.i(TAG, "StartUpActivity onResume()>>>");
        mWaitTask = new WaitTask();
        mWaitTask.execute();
        //部分初始化工作
        ((AppConfig) getApplication()).onMainProgressCreate();
        if (!AppConfig.MainServiceStarted) {
            startService(new Intent(this, AssistantService.class));
        }
        if (AppConfig.NewInstallFirstOpen) {
            Log.i("LingJu", "init data >>>>>");
            initZipCode();
            initAccountProject();
            //读取应用列表(只能在主线程中实现)
            getPackageManager().getInstalledPackages(0);
        }
    }

    /**
     * 需要申请权限的方法
     **/
    @NeedsPermission({Manifest.permission.CALL_PHONE,   //拨号
            Manifest.permission.PROCESS_OUTGOING_CALLS,
            Manifest.permission.RECORD_AUDIO,   //录音
            Manifest.permission.ACCESS_COARSE_LOCATION,     //定位
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.READ_CONTACTS,      //读取联系人
            Manifest.permission.READ_CALL_LOG,      //读取通话记录
            Manifest.permission.READ_SMS,       //读取短信
            Manifest.permission.SEND_SMS,       //发送短信
            "android.permission.WRITE_SMS",     //写短信
            Manifest.permission.BLUETOOTH,      //蓝牙
            Manifest.permission.BLUETOOTH_ADMIN})
    public void init() {
        // 因此,MTA的初始化工作需要在本onCreate中进行
        // 在startStatService之前调用StatConfig配置类接口,使得MTA配置及时生效
        initMTAConfig(false);
        String appkey = "Aqc1104472246";
        // 初始化并启动MTA
        // 第三方SDK必须按以下代码初始化MTA,其中appkey为规定的格式或MTA分配的代码。
        // 其它普通的app可自行选择是否调用
        try {
            // 第三个参数必须为:com.tencent.stat.common.StatConstants.VERSION
            StatService.startStatService(getApplicationContext(), appkey,
                    com.tencent.stat.common.StatConstants.VERSION);
        } catch (Exception e) {
            // MTA初始化失败
            e.printStackTrace();
        }
        setContentView(R.layout.activity_startup);
        Log.i(TAG, "StartUpActivity setContentView>>>>>>");
        //设置模拟状态栏的高度
        View statusBar = findViewById(R.id.status_bar);
        ViewGroup.LayoutParams layoutParams = statusBar.getLayoutParams();
        layoutParams.height = ScreenUtil.getStatusBarHeight(this);
        statusBar.setLayoutParams(layoutParams);
        /*mImg = (ImageView) findViewById(R.id.start_up_img);
        Animation loadAnimation = AnimationUtils.loadAnimation(this, R.anim.start_up_loading);
        String as[] = getResources().getStringArray(R.array.start_up_tips);
        if (as != null && as.length > 0) {
            ((TextView) findViewById(R.id.start_upt_tips)).setText(as[new Random(System.currentTimeMillis()).nextInt(as.length)]);
        }
        mImg.startAnimation(loadAnimation);*/

    }

    /*//挂断电话
    private void endCall() {
        try {
            Log.i("LingJu", "StartUpActivity endCall()");
            //通过反射拿到android.os.ServiceManager里面的getService这个方法的对象
            Method method = Class.forName("android.os.ServiceManager").getMethod("getService", String.class);
            //通过反射调用这个getService方法,然后拿到IBinder对象,然后就可以进行aidl啦
            IBinder iBinder = (IBinder) method.invoke(null, TELEPHONY_SERVICE);
            ITelephony telephony = ITelephony.Stub.asInterface(iBinder);
            telephony.endCall();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/

    /**
     * 向用户解释为什么需要这个权限的方法
     **/
    @OnShowRationale({Manifest.permission.CALL_PHONE,   //拨号
            Manifest.permission.PROCESS_OUTGOING_CALLS,
            Manifest.permission.RECORD_AUDIO,   //录音
            Manifest.permission.ACCESS_COARSE_LOCATION,     //定位
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.READ_CONTACTS,      //读取联系人
            Manifest.permission.READ_CALL_LOG,      //读取通话记录
            Manifest.permission.READ_SMS,       //读取短信
            Manifest.permission.SEND_SMS,       //发送短信
            "android.permission.WRITE_SMS",     //写短信
            Manifest.permission.BLUETOOTH,      //蓝牙
            Manifest.permission.BLUETOOTH_ADMIN})
    public void showRationaleForPermission(final PermissionRequest request) {
        Log.i("LingJu", "StartUpActivity showRationaleForPermission()");
        new CommonDialog(this, "申请权限", "应用还需要以下权限才能正常运行", "知道了")
                .setOnConfirmListener(new CommonDialog.OnConfirmListener() {
                    @Override
                    public void onConfirm() {
                        request.proceed();
                    }
                })
                .show();
    }

    /**
     * 申请权限被拒后调用
     **/
    @OnPermissionDenied({Manifest.permission.CALL_PHONE,   //拨号
            Manifest.permission.PROCESS_OUTGOING_CALLS,
            Manifest.permission.RECORD_AUDIO,   //录音
            Manifest.permission.ACCESS_COARSE_LOCATION,     //定位
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.READ_CONTACTS,      //读取联系人
            Manifest.permission.READ_CALL_LOG,      //读取通话记录
            Manifest.permission.READ_SMS,       //读取短信
            Manifest.permission.SEND_SMS,       //发送短信
            "android.permission.WRITE_SMS",     //写短信
            Manifest.permission.BLUETOOTH,      //蓝牙
            Manifest.permission.BLUETOOTH_ADMIN})
    public void showRecordDenied() {
        Toast.makeText(StartUpActivity.this, "有权限被拒绝将影响程序正常运行, 请自行到应用权限管理页面设置!", Toast.LENGTH_LONG).show();
    }

    private void initMTAConfig(boolean config) {
        //设置最大缓存未发送消息个数(默认1024)
        StatConfig.setMaxStoreEventCount(1024);

        //缓存消息的数量超过阈值时,最早的消息会被丢弃。
        StatConfig.setMaxBatchReportCount(30);

        //(仅在发送策略为PERIOD时有效)设置间隔时间(默认为24*60,即1天)
        StatConfig.setSendPeriodMinutes(1440);

        //开启SDK LogCat开关(默认false)
        StatConfig.setDebugEnable(config);
        StatConfig.initNativeCrashReport(getApplicationContext(), AppConfig.DefaultDir);
    }

    /**
     * 初始化区号
     **/
    private void initZipCode() {
        Observable.create(new ObservableOnSubscribe<Object>() {
            @Override
            public void subscribe(ObservableEmitter<Object> e) throws Exception {
                Set<Map.Entry<String, String>> entries = ZipCodeMap.MAP.entrySet();
                List<Zipcode> zipCodeList = new ArrayList<>();
                for (Map.Entry<String, String> entry : entries) {
                    Zipcode zipCode = new Zipcode();
                    zipCode.setCity(entry.getKey());
                    zipCode.setCode(entry.getValue());
                    zipCodeList.add(zipCode);
                }
                CallAndSmsDao.getInstance(StartUpActivity.this).insertZipCodes(zipCodeList);
            }
        })
                .delay(1500, TimeUnit.MILLISECONDS)
                .observeOn(Schedulers.io())
                .subscribeOn(Schedulers.io())
                .subscribe();
    }

    /**
     * 首次打开应用时,初始化账单项目数据
     **/
    private void initAccountProject() {
        Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> emitter) throws Exception {
                 /* 插入账单item */
                String[] expenses = getResources().getStringArray(R.array.expense_items);
                String[] incomes = getResources().getStringArray(R.array.income_items);
                        /* 支出类 */
                for (String expense : expenses) {
                    Item item = new Item();
                    item.setItem(expense);
                    item.setExpense(ITEM_EXPENSE);
                    AccountItemDao.getInstance().inserItem(item);
                }
                        /* 收入类 */
                for (String income : incomes) {
                    Item item = new Item();
                    item.setItem(income);
                    item.setExpense(ITEM_INCOME);
                    AccountItemDao.getInstance().inserItem(item);
                }
                Log.i("LingJu", "loaded item...");
                emitter.onNext(0);
            }
        })
                .delay(1500, TimeUnit.MILLISECONDS)
                .observeOn(Schedulers.io())
                .subscribeOn(Schedulers.io())
                .subscribe(new Consumer<Integer>() {
                    @Override
                    public void accept(Integer integer) throws Exception {
                         /* 插入账单子类item */
                        String[] subItems = getResources().getStringArray(R.array.sub_items);
                        for (String subItem1 : subItems) {
                            SubItem subItem = new SubItem();
                            String[] subArr = subItem1.split("\\|");
                            subItem.setItemid(Long.valueOf(subArr[0]));
                            subItem.setName(subArr[1]);
                            AccountItemDao.getInstance().insertSubItem(subItem);
                        }
                        Log.i("LingJu", "loaded subItem...");
                    }
                });

    }
/*
    public  boolean isStoragePermissionGranted() {
		if (Build.VERSION.SDK_INT >= 23) {
			if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
					== PackageManager.PERMISSION_GRANTED) {
				Log.i(TAG,"Permission is granted");
				return AssistantApplication.granted=true;
			} else {
				Log.i(TAG,"Permission is revoked");
				ActivityCompat.requestPermissions(this, new String[]{
						Manifest.permission.WRITE_EXTERNAL_STORAGE,
						Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS,
						Manifest.permission.RECEIVE_BOOT_COMPLETED,
						Manifest.permission.READ_CONTACTS,
						Manifest.permission.WAKE_LOCK,
						Manifest.permission.VIBRATE,
						Manifest.permission.RECORD_AUDIO,
						Manifest.permission.INTERNET,
						Manifest.permission.CHANGE_NETWORK_STATE,
						Manifest.permission.WRITE_SETTINGS,
						Manifest.permission.MODIFY_AUDIO_SETTINGS,
						Manifest.permission.READ_CALL_LOG,
						Manifest.permission.CALL_PHONE,
						Manifest.permission.SEND_SMS,
						Manifest.permission.CALL_PHONE,
						Manifest.permission.RECEIVE_SMS,
						Manifest.permission.READ_SMS,
						Manifest.permission.GET_TASKS,
						Manifest.permission.BLUETOOTH,
						Manifest.permission.BLUETOOTH_ADMIN,
						Manifest.permission.ACCESS_COARSE_LOCATION,
						Manifest.permission.ACCESS_FINE_LOCATION,
						Manifest.permission.ACCESS_WIFI_STATE,
						Manifest.permission.ACCESS_NETWORK_STATE,
						Manifest.permission.CHANGE_WIFI_STATE,
						Manifest.permission.INTERNET,
						Manifest.permission.READ_LOGS,
						Manifest.permission.READ_PHONE_STATE}, 1);
				return AssistantApplication.granted=false;
			}
		}
		else { //permission is automatically granted on sdk<23 upon installation
			Log.v(TAG,"Permission is granted");
			return AssistantApplication.granted=true;
		}
	}

	@TargetApi(Build.VERSION_CODES.M)
	@Override
	public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);
		Log.i(TAG,"permissions>>"+permissions.length+",grantResults>>>>>>>>>>>>>>>>"+grantResults);
		if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
			Log.v(TAG,"Permission: "+permissions[0]+ "was "+grantResults[0]);
			AssistantApplication.granted=true;
			if(checkSystemWritePermission()){
				init();
			}
		}
	}

	@TargetApi(Build.VERSION_CODES.M)
	protected boolean checkSystemWritePermission() {
		boolean retVal = true;
		try {
			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
				retVal = Settings.System.canWrite(this);
				Log.d(TAG, "Can Write Settings: " + retVal);
				if (!retVal) {
					openAndroidPermissionsMenu();
				}
			}
		}catch (Exception e){
			e.printStackTrace();
		}
		return retVal;
	}

	protected void openAndroidPermissionsMenu() {
		Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
		intent.setData(Uri.parse("package:" + getPackageName()));
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivityForResult(intent,110);
	}*/

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        StartUpActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 110) {
            init();
            // StartUpActivityPermissionsDispatcher.initWithCheck(this);
        }
    }

    class WaitTask extends AsyncTask<Void, Void, Boolean> {

        @Override
        protected Boolean doInBackground(Void... params) {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                //打断睡眠中的线程
                Thread.currentThread().interrupt();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            startActivity(new Intent(StartUpActivity.this, MainActivity.class));
            finish();
            overridePendingTransition(R.anim.startup_act_in, R.anim.startup_act_out);
        }

    }
}


text:
Management and API to communicate with the event server [ThunderPush](https://github.com/thunderpush/thunderpush).

## Installation

Add this line to your application's Gemfile:
```ruby
gem 'thunderpush', github: 'welingtonsampaio/thunderpush-gem'
```

And then execute:

    $ bundle install

## Configuration

The mode of use was based on the API Http service.

### Rails
Create a initializer file in `config/initializers/thunderpush.rb`
```ruby
ThunderPush.default_client.config do |config|
	config.hostname= 'localhost'
	config.port= 7171
	config.authenticate 'key', 'secret'

	# or inline configuration

	config.url= 'http://key:secret@localhost:7171'
end
```

### Parameters
- **scheme** - `String`
 - Defines the type of request, with the options `http` or `https`
  ```ruby
  config.scheme = 'https'
  ```
- **hostname** - `String`
 - Binds server to custom address where will be executed the request. Default `127.0.0.1`
  ```ruby
  config.hostname = 'hostname'
  ```
- **port** - `Integer`
 - Binds server to custom port where will be executed the request. Default `5678`
  ```ruby
  config.port = 80
  ```
- **publickey** - `String` required
 - Client key to connection authentication
  ```ruby
  config.publickey = 'key'
  ```
- **privatekey** - `String` required
 - Server Api Key to connection authentication
  ```ruby
  config.privatekey = 'long-hash-key'
  ```
- **encrypted** - `Boolean`
 - Sets whether the request should be encrypted using SSL. If set to true modifies the scheme for `https` and the door
 to `443`, if you need to change the default setting after you configure it. E.g.:
  ```ruby
  config.encrypted = true # scheme=>'https' and port=>443
  config.port = 10001 # changed port after encrypted request
  ```

### Methods
- **authenticate** -> `key:String`, `secret:String`
 - Adds the publickey and privatekey in only one method.
 ```ruby
 config.authenticate 'key', 'long-hash-key'
 ```
- **url=** -> `uri:String`
 - Parser URI to configuration inline method. E.g.:
 ```ruby
 config.url = 'https://key:long-hash-key@localhost:10001'
 # returns:
 #   scheme => 'https'
 #   hostname => 'localhost'
 #   port => 10001
 #   publickey => 'key'
 #   privatekey => 'long-hash-key'
 ```

## Usage

The use of the API was divided into three modules. They are: _client_, _channel_ and _user_. Each is responsible for
certain tasks. Below I am listing the usage of each module.

### Clients (ThunderPush::Client)

Client is the library that performs the call to the server events. It is possible to have more than one instance with
different settings for each, or use the default_client implemented within the module. For using the standard object use
the following syntax:
```ruby
ThunderPush.default_client
```

To create a new instance, use the following command:
```ruby
client = ThunderPush::Client.new { :publickey => 'key', :privatekey => 'long-hash-key' }
```

Some methods commonly used in client delegated to the main module, these methods use the standard instance of the Client. E.g.:
```ruby
ThunderPush.trigger 'my-channel', 'my-event', {foo: 'bar'}
```
The methods that are in the delegate are: `trigger`, `trigger_async`, `post`, `post_async`, `get` and `get_async`

#### Trigger (ThunderPush::Client)

Performs the event requests. The event requests are identical to a POST request to a channel, with the difference of the
structure to the event. Need a channel and event for the execution to be triggered.

**Options:**

- **channel** - `String` - Channel name that will receive the event
- **event_name** - `String` - Event name to be triggered
- **data** - `Hash` - Content to be sent to the event

**Publishing events**

```ruby
ThunderPush.trigger 'my-channel', 'my-event', {foo: 'bar'}
ThunderPush.trigger_async 'my-channel', 'my-event', {foo: 'bar'} # not waiting server response
```

#### Generic requests to the ThunderPush HTTP API (ThunderPush::Client)

Using the GET and POST methods can run on ThunderPush HTTP API directly and create their own forms of request. Below show how to run and the content of each request.

**Post** and **PostAsync**:

Options: `path:String` e `body:String`. Path, contains the relative path to version api ThunderPush, eg: `/key/channels/channel-name/`. Body, contains the contents of the request to be sent, it must contain the `json` format, eg: `'{"foo":"bar"}'`.

Tip: encode a hash in string!

```ruby
ThunderPush.post "/key/channels/my-channel/", {foo: "bar"}.to_json
ThunderPush.post_async "/key/channels/my-channel/", {foo: "bar"}.to_json

# POST http://127.0.0.1:5678/api/1.0.0/key/channels/channel-name/
# BODY {"foo":"bar"}
```

**Get** and **GetAsync**:

Options: `path:String` e `params:Hash`. Path, contains the relative path to version api ThunderPush, eg: `/key/users/[user_id]/`. Body, contains the contents of the request to be sent, it must contain the `json` format, eg: `{foo: "bar"}`.

Tip: encode a hash in string!

```ruby
ThunderPush.get "/key/users/[user_id]/", {foo: "bar"}
ThunderPush.get_async "/key/users/[user_id]/", {foo: "bar"}

# GET http://127.0.0.1:5678/api/1.0.0/key/users/[user_id]/?foo=bar
```

### Channels

`TODO: not implemented`

### Users

`TODO: not implemented`

## Contributing

1. Fork it ( https://github.com/welingtonsampaio/thunderpush-gem/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request


text:
const common = require('./webpack.common.js');
const merge = require('webpack-merge');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');

module.exports = merge(common, {
  devtool: 'source-map',
  plugins: [new UglifyJSPlugin({sourceMap: true})]
});


text:
FactoryGirl.define do
  factory :load_balancer_pool do
    sequence(:name)    { |n| "load_balancer_pool_#{seq_padded_for_sorting(n)}" }
    sequence(:ems_ref) { |n| "ems_ref_#{seq_padded_for_sorting(n)}" }
  end

  factory :load_balancer_pool_amazon,
          :class  => "ManageIQ::Providers::Amazon::NetworkManager::LoadBalancerPool",
          :parent => :load_balancer_pool
end


text:
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// TODO(vtl): I currently potentially overflow in doing index calculations.
// E.g., |start_index_| and |current_num_bytes_| fit into a |uint32_t|, but
// their sum may not. This is bad and poses a security risk. (We're currently
// saved by the limit on capacity -- the maximum size of the buffer, checked in
// |DataPipe::ValidateOptions()|, is currently sufficiently small.)

#include "third_party/mojo/src/mojo/edk/system/local_data_pipe_impl.h"

#include <string.h>

#include <algorithm>

#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "third_party/mojo/src/mojo/edk/system/channel.h"
#include "third_party/mojo/src/mojo/edk/system/configuration.h"
#include "third_party/mojo/src/mojo/edk/system/data_pipe.h"
#include "third_party/mojo/src/mojo/edk/system/message_in_transit.h"
#include "third_party/mojo/src/mojo/edk/system/message_in_transit_queue.h"
#include "third_party/mojo/src/mojo/edk/system/remote_consumer_data_pipe_impl.h"
#include "third_party/mojo/src/mojo/edk/system/remote_producer_data_pipe_impl.h"

namespace mojo {
namespace system {

// Assert some things about some things defined in data_pipe_impl.h (don't make
// the assertions there, to avoid including message_in_transit.h).
static_assert(MOJO_ALIGNOF(SerializedDataPipeConsumerDispatcher) ==
                  MessageInTransit::kMessageAlignment,
              "Wrong alignment");
static_assert(sizeof(SerializedDataPipeConsumerDispatcher) %
                      MessageInTransit::kMessageAlignment ==
                  0,
              "Wrong size");

LocalDataPipeImpl::LocalDataPipeImpl()
    : start_index_(0), current_num_bytes_(0) {
  // Note: |buffer_| is lazily allocated, since a common case will be that one
  // of the handles is immediately passed off to another process.
}

LocalDataPipeImpl::~LocalDataPipeImpl() {
}

void LocalDataPipeImpl::ProducerClose() {
  // If the consumer is still open and we still have data, we have to keep the
  // buffer around. Currently, we won't free it even if it empties later. (We
  // could do this -- requiring a check on every read -- but that seems to be
  // optimizing for the uncommon case.)
  if (!consumer_open() || !current_num_bytes_) {
    // Note: There can only be a two-phase *read* (by the consumer) if we still
    // have data.
    DCHECK(!consumer_in_two_phase_read());
    DestroyBuffer();
  }
}

MojoResult LocalDataPipeImpl::ProducerWriteData(
    UserPointer<const void> elements,
    UserPointer<uint32_t> num_bytes,
    uint32_t max_num_bytes_to_write,
    uint32_t min_num_bytes_to_write) {
  DCHECK_EQ(max_num_bytes_to_write % element_num_bytes(), 0u);
  DCHECK_EQ(min_num_bytes_to_write % element_num_bytes(), 0u);
  DCHECK_GT(max_num_bytes_to_write, 0u);
  DCHECK_GE(max_num_bytes_to_write, min_num_bytes_to_write);
  DCHECK(consumer_open());

  if (min_num_bytes_to_write > capacity_num_bytes() - current_num_bytes_) {
    // Don't return "should wait" since you can't wait for a specified amount
    // of data.
    return MOJO_RESULT_OUT_OF_RANGE;
  }

  size_t num_bytes_to_write =
      std::min(static_cast<size_t>(max_num_bytes_to_write),
               capacity_num_bytes() - current_num_bytes_);
  if (num_bytes_to_write == 0)
    return MOJO_RESULT_SHOULD_WAIT;

  // The amount we can write in our first copy.
  size_t num_bytes_to_write_first =
      std::min(num_bytes_to_write, GetMaxNumBytesToWrite());
  // Do the first (and possibly only) copy.
  size_t first_write_index =
      (start_index_ + current_num_bytes_) % capacity_num_bytes();
  EnsureBuffer();
  elements.GetArray(buffer_.get() + first_write_index,
                    num_bytes_to_write_first);

  if (num_bytes_to_write_first < num_bytes_to_write) {
    // The "second write index" is zero.
    elements.At(num_bytes_to_write_first)
        .GetArray(buffer_.get(), num_bytes_to_write - num_bytes_to_write_first);
  }

  current_num_bytes_ += num_bytes_to_write;
  DCHECK_LE(current_num_bytes_, capacity_num_bytes());
  num_bytes.Put(static_cast<uint32_t>(num_bytes_to_write));
  return MOJO_RESULT_OK;
}

MojoResult LocalDataPipeImpl::ProducerBeginWriteData(
    UserPointer<void*> buffer,
    UserPointer<uint32_t> buffer_num_bytes,
    uint32_t min_num_bytes_to_write) {
  DCHECK(consumer_open());

  // The index we need to start writing at.
  size_t write_index =
      (start_index_ + current_num_bytes_) % capacity_num_bytes();

  size_t max_num_bytes_to_write = GetMaxNumBytesToWrite();
  if (min_num_bytes_to_write > max_num_bytes_to_write) {
    // Don't return "should wait" since you can't wait for a specified amount
    // of data.
    return MOJO_RESULT_OUT_OF_RANGE;
  }

  // Don't go into a two-phase write if there's no room.
  if (max_num_bytes_to_write == 0)
    return MOJO_RESULT_SHOULD_WAIT;

  EnsureBuffer();
  buffer.Put(buffer_.get() + write_index);
  buffer_num_bytes.Put(static_cast<uint32_t>(max_num_bytes_to_write));
  set_producer_two_phase_max_num_bytes_written(
      static_cast<uint32_t>(max_num_bytes_to_write));
  return MOJO_RESULT_OK;
}

MojoResult LocalDataPipeImpl::ProducerEndWriteData(uint32_t num_bytes_written) {
  DCHECK_LE(num_bytes_written, producer_two_phase_max_num_bytes_written());
  DCHECK_EQ(num_bytes_written % element_num_bytes(), 0u);
  current_num_bytes_ += num_bytes_written;
  DCHECK_LE(current_num_bytes_, capacity_num_bytes());
  set_producer_two_phase_max_num_bytes_written(0);
  return MOJO_RESULT_OK;
}

HandleSignalsState LocalDataPipeImpl::ProducerGetHandleSignalsState() const {
  HandleSignalsState rv;
  if (consumer_open()) {
    if (current_num_bytes_ < capacity_num_bytes() &&
        !producer_in_two_phase_write())
      rv.satisfied_signals |= MOJO_HANDLE_SIGNAL_WRITABLE;
    rv.satisfiable_signals |= MOJO_HANDLE_SIGNAL_WRITABLE;
  } else {
    rv.satisfied_signals |= MOJO_HANDLE_SIGNAL_PEER_CLOSED;
  }
  rv.satisfiable_signals |= MOJO_HANDLE_SIGNAL_PEER_CLOSED;
  return rv;
}

void LocalDataPipeImpl::ProducerStartSerialize(Channel* channel,
                                               size_t* max_size,
                                               size_t* max_platform_handles) {
  *max_size = sizeof(SerializedDataPipeProducerDispatcher) +
              channel->GetSerializedEndpointSize();
  *max_platform_handles = 0;
}

bool LocalDataPipeImpl::ProducerEndSerialize(
    Channel* channel,
    void* destination,
    size_t* actual_size,
    embedder::PlatformHandleVector* platform_handles) {
  SerializedDataPipeProducerDispatcher* s =
      static_cast<SerializedDataPipeProducerDispatcher*>(destination);
  s->validated_options = validated_options();
  void* destination_for_endpoint = static_cast<char*>(destination) +
                                   sizeof(SerializedDataPipeProducerDispatcher);

  if (!consumer_open()) {
    // Case 1: The consumer is closed.
    s->consumer_num_bytes = static_cast<size_t>(-1);
    *actual_size = sizeof(SerializedDataPipeProducerDispatcher);
    return true;
  }

  // Case 2: The consumer isn't closed. We'll replace ourselves with a
  // |RemoteProducerDataPipeImpl|.

  s->consumer_num_bytes = current_num_bytes_;
  // Note: We don't use |port|.
  scoped_refptr<ChannelEndpoint> channel_endpoint =
      channel->SerializeEndpointWithLocalPeer(destination_for_endpoint, nullptr,
                                              owner(), 0);
  // Note: Keep |*this| alive until the end of this method, to make things
  // slightly easier on ourselves.
  scoped_ptr<DataPipeImpl> self(owner()->ReplaceImplNoLock(make_scoped_ptr(
      new RemoteProducerDataPipeImpl(channel_endpoint.get(), buffer_.Pass(),
                                     start_index_, current_num_bytes_))));

  *actual_size = sizeof(SerializedDataPipeProducerDispatcher) +
                 channel->GetSerializedEndpointSize();
  return true;
}

void LocalDataPipeImpl::ConsumerClose() {
  // If the producer is around and in a two-phase write, we have to keep the
  // buffer around. (We then don't free it until the producer is closed. This
  // could be rectified, but again seems like optimizing for the uncommon case.)
  if (!producer_open() || !producer_in_two_phase_write())
    DestroyBuffer();
  current_num_bytes_ = 0;
}

MojoResult LocalDataPipeImpl::ConsumerReadData(UserPointer<void> elements,
                                               UserPointer<uint32_t> num_bytes,
                                               uint32_t max_num_bytes_to_read,
                                               uint32_t min_num_bytes_to_read,
                                               bool peek) {
  DCHECK_EQ(max_num_bytes_to_read % element_num_bytes(), 0u);
  DCHECK_EQ(min_num_bytes_to_read % element_num_bytes(), 0u);
  DCHECK_GT(max_num_bytes_to_read, 0u);

  if (min_num_bytes_to_read > current_num_bytes_) {
    // Don't return "should wait" since you can't wait for a specified amount of
    // data.
    return producer_open() ? MOJO_RESULT_OUT_OF_RANGE
                           : MOJO_RESULT_FAILED_PRECONDITION;
  }

  size_t num_bytes_to_read =
      std::min(static_cast<size_t>(max_num_bytes_to_read), current_num_bytes_);
  if (num_bytes_to_read == 0) {
    return producer_open() ? MOJO_RESULT_SHOULD_WAIT
                           : MOJO_RESULT_FAILED_PRECONDITION;
  }

  // The amount we can read in our first copy.
  size_t num_bytes_to_read_first =
      std::min(num_bytes_to_read, GetMaxNumBytesToRead());
  elements.PutArray(buffer_.get() + start_index_, num_bytes_to_read_first);

  if (num_bytes_to_read_first < num_bytes_to_read) {
    // The "second read index" is zero.
    elements.At(num_bytes_to_read_first)
        .PutArray(buffer_.get(), num_bytes_to_read - num_bytes_to_read_first);
  }

  if (!peek)
    MarkDataAsConsumed(num_bytes_to_read);
  num_bytes.Put(static_cast<uint32_t>(num_bytes_to_read));
  return MOJO_RESULT_OK;
}

MojoResult LocalDataPipeImpl::ConsumerDiscardData(
    UserPointer<uint32_t> num_bytes,
    uint32_t max_num_bytes_to_discard,
    uint32_t min_num_bytes_to_discard) {
  DCHECK_EQ(max_num_bytes_to_discard % element_num_bytes(), 0u);
  DCHECK_EQ(min_num_bytes_to_discard % element_num_bytes(), 0u);
  DCHECK_GT(max_num_bytes_to_discard, 0u);

  if (min_num_bytes_to_discard > current_num_bytes_) {
    // Don't return "should wait" since you can't wait for a specified amount of
    // data.
    return producer_open() ? MOJO_RESULT_OUT_OF_RANGE
                           : MOJO_RESULT_FAILED_PRECONDITION;
  }

  // Be consistent with other operations; error if no data available.
  if (current_num_bytes_ == 0) {
    return producer_open() ? MOJO_RESULT_SHOULD_WAIT
                           : MOJO_RESULT_FAILED_PRECONDITION;
  }

  size_t num_bytes_to_discard = std::min(
      static_cast<size_t>(max_num_bytes_to_discard), current_num_bytes_);
  MarkDataAsConsumed(num_bytes_to_discard);
  num_bytes.Put(static_cast<uint32_t>(num_bytes_to_discard));
  return MOJO_RESULT_OK;
}

MojoResult LocalDataPipeImpl::ConsumerQueryData(
    UserPointer<uint32_t> num_bytes) {
  // Note: This cast is safe, since the capacity fits into a |uint32_t|.
  num_bytes.Put(static_cast<uint32_t>(current_num_bytes_));
  return MOJO_RESULT_OK;
}

MojoResult LocalDataPipeImpl::ConsumerBeginReadData(
    UserPointer<const void*> buffer,
    UserPointer<uint32_t> buffer_num_bytes,
    uint32_t min_num_bytes_to_read) {
  size_t max_num_bytes_to_read = GetMaxNumBytesToRead();
  if (min_num_bytes_to_read > max_num_bytes_to_read) {
    // Don't return "should wait" since you can't wait for a specified amount of
    // data.
    return producer_open() ? MOJO_RESULT_OUT_OF_RANGE
                           : MOJO_RESULT_FAILED_PRECONDITION;
  }

  // Don't go into a two-phase read if there's no data.
  if (max_num_bytes_to_read == 0) {
    return producer_open() ? MOJO_RESULT_SHOULD_WAIT
                           : MOJO_RESULT_FAILED_PRECONDITION;
  }

  buffer.Put(buffer_.get() + start_index_);
  buffer_num_bytes.Put(static_cast<uint32_t>(max_num_bytes_to_read));
  set_consumer_two_phase_max_num_bytes_read(
      static_cast<uint32_t>(max_num_bytes_to_read));
  return MOJO_RESULT_OK;
}

MojoResult LocalDataPipeImpl::ConsumerEndReadData(uint32_t num_bytes_read) {
  DCHECK_LE(num_bytes_read, consumer_two_phase_max_num_bytes_read());
  DCHECK_EQ(num_bytes_read % element_num_bytes(), 0u);
  DCHECK_LE(start_index_ + num_bytes_read, capacity_num_bytes());
  MarkDataAsConsumed(num_bytes_read);
  set_consumer_two_phase_max_num_bytes_read(0);
  return MOJO_RESULT_OK;
}

HandleSignalsState LocalDataPipeImpl::ConsumerGetHandleSignalsState() const {
  HandleSignalsState rv;
  if (current_num_bytes_ > 0) {
    if (!consumer_in_two_phase_read())
      rv.satisfied_signals |= MOJO_HANDLE_SIGNAL_READABLE;
    rv.satisfiable_signals |= MOJO_HANDLE_SIGNAL_READABLE;
  } else if (producer_open()) {
    rv.satisfiable_signals |= MOJO_HANDLE_SIGNAL_READABLE;
  }
  if (!producer_open())
    rv.satisfied_signals |= MOJO_HANDLE_SIGNAL_PEER_CLOSED;
  rv.satisfiable_signals |= MOJO_HANDLE_SIGNAL_PEER_CLOSED;
  return rv;
}

void LocalDataPipeImpl::ConsumerStartSerialize(Channel* channel,
                                               size_t* max_size,
                                               size_t* max_platform_handles) {
  *max_size = sizeof(SerializedDataPipeConsumerDispatcher) +
              channel->GetSerializedEndpointSize();
  *max_platform_handles = 0;
}

bool LocalDataPipeImpl::ConsumerEndSerialize(
    Channel* channel,
    void* destination,
    size_t* actual_size,
    embedder::PlatformHandleVector* platform_handles) {
  SerializedDataPipeConsumerDispatcher* s =
      static_cast<SerializedDataPipeConsumerDispatcher*>(destination);
  s->validated_options = validated_options();
  void* destination_for_endpoint = static_cast<char*>(destination) +
                                   sizeof(SerializedDataPipeConsumerDispatcher);

  size_t old_num_bytes = current_num_bytes_;
  MessageInTransitQueue message_queue;
  ConvertDataToMessages(buffer_.get(), &start_index_, &current_num_bytes_,
                        &message_queue);
  start_index_ = 0;
  current_num_bytes_ = 0;

  if (!producer_open()) {
    // Case 1: The producer is closed.
    channel->SerializeEndpointWithClosedPeer(destination_for_endpoint,
                                             &message_queue);
    *actual_size = sizeof(SerializedDataPipeConsumerDispatcher) +
                   channel->GetSerializedEndpointSize();
    return true;
  }

  // Case 2: The producer isn't closed. We'll replace ourselves with a
  // |RemoteConsumerDataPipeImpl|.

  // Note: We don't use |port|.
  scoped_refptr<ChannelEndpoint> channel_endpoint =
      channel->SerializeEndpointWithLocalPeer(destination_for_endpoint,
                                              &message_queue, owner(), 0);
  // Note: Keep |*this| alive until the end of this method, to make things
  // slightly easier on ourselves.
  scoped_ptr<DataPipeImpl> self(owner()->ReplaceImplNoLock(make_scoped_ptr(
      new RemoteConsumerDataPipeImpl(channel_endpoint.get(), old_num_bytes))));

  *actual_size = sizeof(SerializedDataPipeConsumerDispatcher) +
                 channel->GetSerializedEndpointSize();
  return true;
}

bool LocalDataPipeImpl::OnReadMessage(unsigned /*port*/,
                                      MessageInTransit* /*message*/) {
  NOTREACHED();
  return false;
}

void LocalDataPipeImpl::OnDetachFromChannel(unsigned /*port*/) {
  NOTREACHED();
}

void LocalDataPipeImpl::EnsureBuffer() {
  DCHECK(producer_open());
  if (buffer_)
    return;
  buffer_.reset(static_cast<char*>(
      base::AlignedAlloc(capacity_num_bytes(),
                         GetConfiguration().data_pipe_buffer_alignment_bytes)));
}

void LocalDataPipeImpl::DestroyBuffer() {
#ifndef NDEBUG
  // Scribble on the buffer to help detect use-after-frees. (This also helps the
  // unit test detect certain bugs without needing ASAN or similar.)
  if (buffer_)
    memset(buffer_.get(), 0xcd, capacity_num_bytes());
#endif
  buffer_.reset();
}

size_t LocalDataPipeImpl::GetMaxNumBytesToWrite() {
  size_t next_index = start_index_ + current_num_bytes_;
  if (next_index >= capacity_num_bytes()) {
    next_index %= capacity_num_bytes();
    DCHECK_GE(start_index_, next_index);
    DCHECK_EQ(start_index_ - next_index,
              capacity_num_bytes() - current_num_bytes_);
    return start_index_ - next_index;
  }
  return capacity_num_bytes() - next_index;
}

size_t LocalDataPipeImpl::GetMaxNumBytesToRead() {
  if (start_index_ + current_num_bytes_ > capacity_num_bytes())
    return capacity_num_bytes() - start_index_;
  return current_num_bytes_;
}

void LocalDataPipeImpl::MarkDataAsConsumed(size_t num_bytes) {
  DCHECK_LE(num_bytes, current_num_bytes_);
  start_index_ += num_bytes;
  start_index_ %= capacity_num_bytes();
  current_num_bytes_ -= num_bytes;
}

}  // namespace system
}  // namespace mojo


text:
// ==========================================================================
//  Squidex Headless CMS
// ==========================================================================
//  Copyright (c) Squidex UG (haftungsbeschraenkt)
//  All rights reserved. Licensed under the MIT license.
// ==========================================================================

using Squidex.Infrastructure;

namespace Squidex.Domain.Apps.Core.Rules.EnrichedEvents;

public sealed class EnrichedSchemaEvent : EnrichedSchemaEventBase, IEnrichedEntityEvent
{
    [FieldDescription(nameof(FieldDescriptions.EventType))]
    public EnrichedSchemaEventType Type { get; set; }

    public DomainId Id
    {
        get => SchemaId.Id;
    }

    public override long Partition
    {
        get => SchemaId?.GetHashCode() ?? 0;
    }
}


text:
package jp.mixi.triaina.commons.test.utils;

import android.net.Uri;
import jp.mixi.triaina.commons.utils.UriUtils;
import junit.framework.TestCase;

public class UriUtilsTest extends TestCase {

	public void testCompareDomain() {
		Uri uri = Uri.parse("http://aaa.example.com");
		assertEquals(true, UriUtils.compareDomain(uri, "example.com"));
		assertEquals(true, UriUtils.compareDomain(uri, "aaa.example.com"));

		uri = Uri.parse("http://example.com");
		assertEquals(false, UriUtils.compareDomain(uri, "aaa.example.com"));
		assertEquals(false, UriUtils.compareDomain(uri, "exampl.com"));

		uri = Uri.parse("http://fake-example.com");
		assertEquals(false, UriUtils.compareDomain(uri, "example.com"));
	}

}


text:
layout: tag
tag: git
permalink: /tag/git/
---


text: Template from https://github.com/BlackrockDigital/startbootstrap-freelancer


text:
import {Utils} from "./utils"
import {DataStore} from "./stores/data"

export class SCQuery {
    constructor (collName) {
        if (typeof collName !== 'string') {
            throw new Error('Collection name must be a type of string');
        }
        this._collection = collName;
        this._fields = [];
        this._filter = {};
        this._sort = {};
        this._limit = 100;
        this._skip = 0;
    }

    _addFilter(field, condition, values) {
        if (!Utils.isObject(this._filter[field])) {
            this._filter[field] = {};
        }

        if (typeof condition === 'object') {
            this._filter[field] = condition;
            return this;
        }

        this._filter[field][condition] = values;
        return this;
    }

    find(options = {}) {
        //TODO: Следует возвращать массив SC.Object вместо сырых данных
        return DataStore.getInstance().find(this.toJson(), options);
    }

    // Не следует использовать для больших коллекций
    findAll(options = {}) {
        let result = [];
        return Utils.promiseWhile(
            (res) => {
                if (!res) {
                    return true;
                }

                if (!res.result.length) {
                    return false;
                }

                result = result.concat(res.result);
                this.skip(this._skip + this._limit);

                return true;
            },
            () => {
                return DataStore.getInstance().find(this.toJson(), options);
            })
            .then(res => result)
    }
    count(options = {}) {
        return DataStore.getInstance().count(this.toJson(), options);
    }
    update(object, options = {}) {
        return DataStore.getInstance().update(this.toJson(), object.toJson(), options);
    }
    remove(options = {}) {
        return DataStore.getInstance().remove(this.toJson(), options);
    }

    reset() {
        this._filter = {};
        this.fields = [];

        return this;
    }

    equalTo(field, value) {
        this._filter[field] = value;
        return this;
    }
    notEqualTo(field, value) {
        return this._addFilter(field, "$ne", value);
    }

    containedIn(field,value) {
        if (!Utils.isArray(value)) {
            throw new Error('Value must be of type: Array');
        }

        return this._addFilter(field, '$in', value);
    }
    containsAll(field, value) {
        if (!Utils.isArray(value)) {
            throw new Error('Value must be of type: Array');
        }

        return this._addFilter(field, '$all', value);
    }
    notContainedIn(field, value) {
        if (!Utils.isArray(value)) {
            throw new Error('Value must be of type: Array');
        }

        return this._addFilter(field, '$nin', value);
    }

    greaterThan(field, value) {
        return this._addFilter(field, '$gt', value);
    }
    greaterThanOrEqualTo(field, value) {
        return this._addFilter(field, '$gte', value);
    }
    lessThan(field, value) {
        return this._addFilter(field, '$lt', value);
    }
    lessThanOrEqualTo(field, value) {
        return this._addFilter(field, '$lte', value);
    }

    exists(field) {
        return this._addFilter(field, '$exists', true);
    }
    doesNotExist(field) {
        return this._addFilter(field, '$exists', false);
    }

    contains(field,value, opts) {
        if (opts) {
            return this._addFilter(field, {$regex: value, $options: opts});
        }

        return this._addFilter(field, '$regex', value);
    }

    startsWith(field, value, opts) {
        if (typeof value !== 'string') {
            throw new Error("Value must be a string");
        }

        if (opts) {
            return this._addFilter(field, {$regex: '^' + value, $options: opts});
        }

        return this._addFilter(field, '$regex', '^' + value);
    }

    endsWith(field, value, opts) {
        if (typeof value !== 'string') {
            throw new Error("Value must be a string");
        }

        if (opts) {
            return this._addFilter(field, {$regex: value + '$', $options: opts});
        }

        return this._addFilter(field, '$regex', value + '$');
    }

    limit(limit) {
        if (!Utils.isNumber(limit) || limit < 0) {
            throw new Error("Limit must be a positive number");
        }

        this._limit = limit;

        return this;
    }
    skip(skip) {
        if (!Utils.isNumber(skip) || skip < 0 ) {
            throw new Error("Skip must be a positive number");
        }

        this._skip = skip;

        return this;
    }
    page(page) {
        if (!Utils.isNumber(page) || page < 0 ) {
            throw new Error("Page must be a positive number");
        }

        this._skip = (page - 1) * this._limit;

        return this;
    }

    ascending(field) {
        this._sort[field] = 1;

        return this;
    }
    descending(field) {
        this._sort[field] = -1;

        return this;
    }

    or(query) {
        if (!(query instanceof SCQuery)) {
            throw new Error('Invalid type of Query');
        }

        if (!this._filter['$or']) {
            this._filter['$or'] = [];
        }

        this._filter['$or'].push(query.toJson().query);

        return this;

    }
    and(query) {
        if (!(query instanceof SCQuery)) {
            throw new Error('Invalid type of Query');
        }

        if (!this._filter['$and']) {
            this._filter['$and'] = [];
        }

        this._filter['$and'].push(query.toJson().query);

        return this;
    }

    select() {
        this._fields = [];
        let ln = arguments.length;

        for (let i = 0; i < ln; i++) {
            this._fields.push(arguments[i]);
        }

        return this;
    }

    raw(filter) {
        if (!Utils.isObject(filter)) {
            throw new Error('Filter must be a object');
        }
        this._filter = filter;

        return this;
    }

    toJson() {
        const json = {
            coll: this._collection,
            limit: this._limit,
            skip: this._skip,
            query: this._filter,
            sort: this._sort,
            fields: this._fields
        };

        return json;
    }
}


text:
require_relative 'items/test_dir_item'
require_relative 'items/test_file_item'
require_relative 'items/test_run'


text:
import cffi
# monkey patch cffi to return itself on cdef

def return_self(func):
    def wrapper(self, *args):
        func(self, *args)
        return self
    return wrapper

cffi.FFI.cdef = return_self(cffi.FFI.cdef)

ffi = cffi.FFI()
ffi.cdef("""
//implemented
void *mmap(void *addr, size_t len, int prot, int flags, int fd, size_t offset);
int munmap(void *, size_t);

//unimplemented
int mlockall(int);
int munlockall(void);

int mlock(const void *, size_t);
int msync(void *, size_t, int);

int munlock(const void *, size_t);

int madvise(void *, size_t, int);
""")

_libc = ffi.dlopen(None)


text:
<?php

namespace CachetHQ\Cachet\Repositories\Metric;

use CachetHQ\Cachet\Models\Metric;
use Illuminate\Support\Facades\DB;

/**
 * This is the sqlite repository class.
 *
 * @author James Brooks <james@alt-three.com>
 */
class SqliteRepository extends AbstractMetricRepository implements MetricInterface
{
    /**
     * Returns metrics since given minutes.
     *
     * @param \CachetHQ\Cachet\Models\Metric $metric
     * @param int                            $minutes
     *
     * @return \Illuminate\Support\Collection
     */
    public function getPointsSinceMinutes(Metric $metric, $minutes)
    {
        $queryType = $this->getQueryType($metric);
        $points = DB::select("SELECT strftime('%Y-%m-%d %H:%M', {$this->getMetricPointsTable()}.`created_at`) AS `key`, {$queryType} ".
            "FROM {$this->getMetricsTable()} ".
            "INNER JOIN {$this->getMetricPointsTable()} ON {$this->getMetricsTable()}.id = {$this->getMetricPointsTable()}.metric_id ".
            "WHERE {$this->getMetricsTable()}.id = :metricId ".
            "AND {$this->getMetricPointsTable()}.`created_at` >= datetime('now', 'localtime', '-{$minutes} minutes') ".
            "AND {$this->getMetricPointsTable()}.`created_at` <= datetime('now', 'localtime') ".
            "GROUP BY strftime('%H', {$this->getMetricPointsTable()}.`created_at`), strftime('%M', {$this->getMetricPointsTable()}.`created_at`) ".
            "ORDER BY {$this->getMetricPointsTable()}.`created_at`", [
                'metricId' => $metric->id,
            ]);

        return $this->mapResults($metric, $points);
    }

    /**
     * Returns metrics since given hour.
     *
     * @param \CachetHQ\Cachet\Models\Metric $metric
     * @param int                            $hour
     *
     * @return \Illuminate\Support\Collection
     */
    public function getPointsSinceHour(Metric $metric, $hour)
    {
        $queryType = $this->getQueryType($metric);
        $points = DB::select("SELECT strftime('%Y-%m-%d %H:00', {$this->getMetricPointsTable()}.`created_at`) AS `key`, {$queryType} ".
            "FROM {$this->getMetricsTable()} INNER JOIN {$this->getMetricPointsTable()} ON {$this->getMetricsTable()}.id = {$this->getMetricPointsTable()}.metric_id ".
            "WHERE {$this->getMetricsTable()}.id = :metricId ".
            "AND {$this->getMetricPointsTable()}.`created_at` >= datetime('now', 'localtime', '-{$hour} hours') ".
            "AND {$this->getMetricPointsTable()}.`created_at` <= datetime('now', 'localtime') ".
            "GROUP BY strftime('%H', {$this->getMetricPointsTable()}.`created_at`) ORDER BY {$this->getMetricPointsTable()}.`created_at`", [
                'metricId' => $metric->id,
            ]);

        return $this->mapResults($metric, $points);
    }

    /**
     * Returns metrics since given day.
     *
     * @param \CachetHQ\Cachet\Models\Metric $metric
     * @param int                            $day
     *
     * @return \Illuminate\Support\Collection
     */
    public function getPointsSinceDay(Metric $metric, $day)
    {
        $queryType = $this->getQueryType($metric);
        $points = DB::select("SELECT strftime('%Y-%m-%d', {$this->getMetricPointsTable()}.`created_at`) AS `key`, {$queryType} ".
            "FROM {$this->getMetricsTable()} INNER JOIN {$this->getMetricPointsTable()} ON {$this->getMetricsTable()}.id = {$this->getMetricPointsTable()}.metric_id ".
            "WHERE {$this->getMetricsTable()}.id = :metricId ".
            "AND {$this->getMetricPointsTable()}.`created_at` >= datetime('now', 'localtime', '-{$day} days') ".
            "AND {$this->getMetricPointsTable()}.`created_at` <= datetime('now', 'localtime') ".
            "GROUP BY DATE({$this->getMetricPointsTable()}.`created_at`) ".
            "ORDER BY {$this->getMetricPointsTable()}.`created_at`", [
                'metricId' => $metric->id,
            ]);

        return $this->mapResults($metric, $points);
    }
}


text:
#ifndef CDBCONN_H
#define CDBCONN_H

#include "gp-libpq-fe.h"               /* prerequisite for libpq-int.h */
#include "gp-libpq-int.h"              /* PQExpBufferData */

/* --------------------------------------------------------------------------------------------------
 * Structure for segment database definition and working values
 */
typedef struct SegmentDatabaseDescriptor
{
	/* segment_database_info
	 *
	 * Points to the SegmentDatabaseInfo structure describing the
	 * parameters for this segment database.  Information in this structure is
	 * obtained from the Greenplum administrative schema tables.
	 */
	struct Segment		*segment;

    /* conn
	 *
	 * A non-NULL value points to the PGconn block of a successfully
	 * established connection to the segment database.
	 */
	PGconn				   *conn;

	/*
	 * Error info saved when connection cannot be established.
	 */
    int                     errcode;        /* ERRCODE_xxx (sqlstate encoded as
                                             * an int) of first error, or 0.
                                             */
	PQExpBufferData         error_message;  /* message text; '\n' at end */

    /*
     * Connection info saved at most recent PQconnectdb.
     *
     * NB: Use malloc/free, not palloc/pfree, for the items below.
     */
    int4		            motionListener; /* interconnect listener port */
    int4					backendPid;
    char                   *whoami;         /* QE identifier for msgs */
} SegmentDatabaseDescriptor;

/* Initialize a segment descriptor in storage provided by the caller. */
void
cdbconn_initSegmentDescriptor(SegmentDatabaseDescriptor *segdbDesc,
                              struct Segment *segment);

/* Free all memory owned by a segment descriptor. */
void
cdbconn_termSegmentDescriptor(SegmentDatabaseDescriptor *segdbDesc);

/* Connect to a QE as a client via libpq. */
bool                            /* returns true if connected */
cdbconn_doConnect(SegmentDatabaseDescriptor    *segdbDesc,
                  const char                   *options);

/* Set the slice index for error messages related to this QE. */
bool
cdbconn_setSliceIndex(SegmentDatabaseDescriptor    *segdbDesc,
                      int                           sliceIndex);

#endif   /* CDBCONN_H */


text:
package gov.nih.nci.system.server.mgmt;

import java.util.Hashtable;

/**
 * This class acts as a session storage object for the user. It stores the
 * User id and the last time the session was accessed time. It also provides
 * capabilities to add and remove user related attributes.
 *
 * @author Ekagra Software Technologies Ltd.
 */
public class UserSession extends Hashtable
{

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;
	private long lastAccessedTime;

	/**
	 * Contructs the {@link UserSession} object for the given id. It also
	 * stores the current time in milliseconds as the time when this object was
	 * accessed last.
	 *
	 * @param userId The login id of the user for which the session is instantiated
	 */
	public UserSession(String userId)
	{
		super();
		super.put("userId", userId);
		this.setLastAccessedTime(System.currentTimeMillis());
	}

	/**
	 * Sets the time (in milliseconds) as the time when this object was accessed last
	 *
	 * @param time The time when this object was last accessed. It should be in milliseconds.
	 */
	public synchronized void setLastAccessedTime(long time)
	{
		this.lastAccessedTime = time;
	}

	/**
	 * This method returns the time in milliseconds when this ojbect was last accessed
	 *
	 * @return Returns the time in milliseconds when this object was last accessed
	 */
	public long getLastAccessedTime()
	{
		return lastAccessedTime;
	}

	/**
	 * This methods accepts a name-value pair and stores the same in the {@link UserSession}
	 * hastable object.
	 *
	 * @param key The name of the object to be stored
	 * @param value The actual object which is to be stored
	 */
	public void setAttribute(String key, Object value)
	{
		this.setLastAccessedTime(System.currentTimeMillis());
		super.put(key, value);
	}

	/**
	 * This method retrieves the stored attribute value with the passed name as the key from
	 * the {@link UserSession} object
	 *
	 * @param key Name of the attribute which is to be retrieves from the UserSession object
	 * @return The object retrieved for the passed key from the UserSession object
	 */
	public Object getAttribute(String key)
	{
		this.setLastAccessedTime(System.currentTimeMillis());
		return super.get(key);
	}

	/**
	 * This method removes the stored attribute value with the passed name as the key from
	 * the {@link UserSession} object
	 *
	 * @param key Name of the attribute which is to be removed from the UserSession object
	 */
	public void removeAttribute(String key)
	{
		this.setLastAccessedTime(System.currentTimeMillis());
		super.remove(key);
	}

	/**
	 * This method returns the user id which is associated with this
	 * {@link UserSession} object
	 * @return The user id associated with this UserSession
	 */
	public String getUserId()
	{
		return (String) this.getAttribute("userId");
	}

}


text:
using Blog_GreenFluffyBites.Extensions;
using Blog_GreenFluffyBites.Models;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web.Mvc;

namespace Blog_GreenFluffyBites.Controllers.Admin
{
    public class CategoryController : Controller
    {
        //
        // GET: Category
        public ActionResult Index()
        {
            return RedirectToAction("List");
        }

        //
        //GET: Category/List
        public ActionResult List()
        {
            using (var database = new BlogDBContext())
            {
                var categories = database.Categories
                    .ToList();
                return View(categories);
            }
        }

        //
        //GET: Category/Create
        public ActionResult Create()
        {
            return View();
        }
        //
        // POST: Category/Create
        [HttpPost]
        [Authorize]
        public ActionResult Create(Category category)
        {
            if (ModelState.IsValid)
            {
                using (var database = new BlogDBContext())
                {
                    database.Categories.Add(category);
                    database.SaveChanges();

                    return RedirectToAction("Index");
                }
            }

            this.AddNotification("You have created the Category!", NotificationType.SUCCESS);

            return View(category);
        }

        //
        // GET: Category/Edit
        [Authorize]
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            using (var database = new BlogDBContext())
            {

                var category = database.Categories
                    .FirstOrDefault(c => c.Id == id);
                if (category == null)
                {
                    return HttpNotFound();
                }

                this.AddNotification("You are about to edit the Category!", NotificationType.WARNING);

                return View(category);
            }
        }

        //
        // POST: Category/Edit
        [HttpPost]
        public ActionResult Edit(Category category)
        {

            if (ModelState.IsValid)
            {
                using (var database = new BlogDBContext())
                {

                    database.Entry(category).State = EntityState.Modified;
                    database.SaveChanges();

                    this.AddNotification("You have edited the Category!", NotificationType.SUCCESS);

                    return RedirectToAction("Index");
                }
            }

            return View(category);
        }

        //
        // GET: Category/Delete
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            using (var database = new BlogDBContext())
            {
                var category = database.Categories
                  .FirstOrDefault(c => c.Id == id);
                if (category == null)
                {
                    return HttpNotFound();
                }

                this.AddNotification("You are about to delete the Category!", NotificationType.WARNING);

                return View(category);
            }
        }

        //
        // POST: Category/Delete
        [HttpPost]
        [ActionName("Delete")]
        public ActionResult DeleteConfirmed(int? id)
        {

            using (var database = new BlogDBContext())
            {

                var category = database.Categories
                   .FirstOrDefault(c => c.Id == id);

                var categoryArticles = category.Articles.ToList();

                foreach (var article in categoryArticles)
                {
                    database.Articles.Remove(article);
                }

                database.Categories.Remove(category);
                database.SaveChanges();

                this.AddNotification("You have deleted the Category!", NotificationType.SUCCESS);

                return RedirectToAction("Index");
            }
        }
    }
}


text:
from flask_frozen import Freezer
from wowchi import app, unminified_js

app.config['ROLLBAR_ENV'] = 'production'
app.config['FREEZER_DESTINATION'] = '../../gh-pages'
app.config['FREEZER_DESTINATION_IGNORE'] = ['.git*', 'CNAME']
unminified_js._set_filters('rjsmin')
freezer = Freezer(app)

if __name__ == '__main__':
    freezer.freeze()


text:
package org.apache.pinot.common.config.tuner;

import org.apache.pinot.spi.config.table.IndexingConfig;
import org.apache.pinot.spi.config.table.TableConfig;
import org.apache.pinot.spi.config.table.TunerConfig;
import org.apache.pinot.spi.config.table.tuner.TableConfigTuner;
import org.apache.pinot.spi.config.table.tuner.Tuner;
import org.apache.pinot.spi.data.Schema;

/**
 * Used to auto-tune the table indexing config. It takes the original table
 * config, table schema and adds the following to indexing config:
 * - Inverted indices for all dimensions
 * - No dictionary index for all metrics
 */
@Tuner(name = "realtimeAutoIndexTuner")
public class RealTimeAutoIndexTuner implements TableConfigTuner {
  private Schema _schema;

  @Override
  public void init(TunerConfig props, Schema schema) {
    _schema = schema;
  }

  @Override
  public TableConfig apply(TableConfig initialConfig) {
    IndexingConfig initialIndexingConfig = initialConfig.getIndexingConfig();
    initialIndexingConfig.setInvertedIndexColumns(_schema.getDimensionNames());
    initialIndexingConfig.setNoDictionaryColumns(_schema.getMetricNames());
    return initialConfig;
  }
}


text:
import ng from 'angular';

import ConfirmationComponent from './confirmation.component';
import ConfirmationService from './confirmation.service';
import ConfirmationController from './confirmation.controller';

export default ng.module('myApp.confirmation.component', [])
  .service('confirmationService', ConfirmationService)
  .controller('ConfirmationController', ConfirmationController)
  .component('confirmation', ConfirmationComponent)
  .name;


text:
<!DOCTYPE html>

    <title>Light Blue Documentation</title>
    <link href="css/documentation.css" rel="stylesheet">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">
    <meta charset="utf-8">

             Dashboard

             Statistics

Stats

Charts

Realtime

             Forms

Account

Article

Elements

Validation

Wizard

             UI

Buttons

Dialogs

Icons

Tabs

Accordion

             Components

Calendar

Maps

Gallery

Fileupload

             Tables

Static

Dynamic

            Grid

             Special

Search

Login

404

Documentation

Dynamic Tables

                        Backgrid.js is a set of components for building semantic and easily stylable data grid widgets.

It has been chosen because it offers really simple, intuitive programming interface that makes easy things easy, but hard things possible when dealing with tabular data.

Backgrind provides editing, adding and sorting data on client side. I recommend to read more about it -
                        Backgrid website. Files:

lib/backbone/backbone-pageable.js
lib/backgrid/backgrid.js
lib/backgrid/backgrid-paginator.js

DataTables

                        DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool, based upon the foundations of progressive enhancement, which will add advanced interaction controls to any HTML table.

Files:

lib/jquery.dataTables.min.js


text:
class StrBlobPtr;
class ConstStrBlobPtr;

#include <vector>
#include <string>
#include <initializer_list>
#include <memory>
#include <iostream>

class StrBlob {
  friend class StrBlobPtr;
  friend class ConstStrBlobPtr;
  friend bool operator==(const StrBlob &, const StrBlob &);
  friend bool operator!=(const StrBlob &, const StrBlob &);
  friend bool operator<(const StrBlob &, const StrBlob &);
  friend bool operator>(const StrBlob &, const StrBlob &);
  friend bool operator<=(const StrBlob &, const StrBlob &);
  friend bool operator>=(const StrBlob &, const StrBlob &);
public:
  typedef std::vector<std::string>::size_type size_type;

  StrBlob();
  StrBlob(std::initializer_list<std::string> il);

  StrBlob(const StrBlob &);
  StrBlob &operator=(const StrBlob &);

  size_type size() const { return data->size(); }
  bool empty() const { return data->empty(); }

  void push_back(const std::string &s);
  void push_back(std::string &&s);
  void pop_back();

  std::string &front();
  const std::string &front() const;
  std::string &back();
  const std::string &back() const;

  StrBlobPtr begin();
  StrBlobPtr end();

  ConstStrBlobPtr cbegin() const;
  ConstStrBlobPtr cend() const;

private:
  std::shared_ptr<std::vector<std::string>> data;

  void check(size_type pos, const std::string &msg) const;
};

bool operator==(const StrBlob &, const StrBlob &);
bool operator!=(const StrBlob &, const StrBlob &);
bool operator<(const StrBlob &, const StrBlob &);
bool operator>(const StrBlob &, const StrBlob &);
bool operator<=(const StrBlob &, const StrBlob &);
bool operator>=(const StrBlob &, const StrBlob &);

inline void StrBlob::push_back(const std::string &s) {
  data->push_back(s);
}

inline void StrBlob::push_back(std::string &&s) {
  std::cout << "StrBlob::push_back(std::string &&s)" << std::endl;
  data->push_back(std::move(s));
}

#endif


text:
@interface SRServerSentEventsTransport ()

- (void)openConnection:(id <SRConnectionInterface>)connection data:(NSString *)data initializeCallback:(void (^)(void))initializeCallback errorCallback:(void (^)(SRErrorByReferenceBlock))errorCallback;

@end

@implementation SRServerSentEventsTransport

static NSString * const kTransportName = @"serverSentEvents";

- (instancetype)init {
    if(self = [self initWithHttpClient:[[SRDefaultHttpClient alloc] init]]) {
    }
    return self;
}

- (instancetype)initWithHttpClient:(id<SRHttpClient>)httpClient {
    if (self = [super initWithHttpClient:httpClient transport:kTransportName]) {
        _connectionTimeout = @5;
        _reconnectDelay = @2;
    }
    return self;
}

- (void)onStart:(id <SRConnectionInterface>)connection data:(NSString *)data initializeCallback:(void (^)(void))initializeCallback errorCallback:(void (^)(SRErrorByReferenceBlock))errorCallback {
    [self openConnection:connection data:data initializeCallback:initializeCallback errorCallback:errorCallback];
}

- (void)reconnect:(id <SRConnectionInterface>)connection data:(NSString *)data {
    SRLogServerSentEvents(@"reconnecting");

    //Wait for a bit before reconnecting
    [[NSBlockOperation blockOperationWithBlock:^{
        if (connection.state != disconnected && [SRConnection ensureReconnecting:connection]) {
            //Now attempt a reconnect
            [self openConnection:connection data:data initializeCallback:nil errorCallback:nil];
        }
    }] performSelector:@selector(start) withObject:nil afterDelay:[_reconnectDelay integerValue]];
}

- (void)openConnection:(id <SRConnectionInterface>)connection data:(NSString *)data initializeCallback:(void (^)(void))initializeCallback errorCallback:(void (^)(SRErrorByReferenceBlock))errorCallback
{
    // If we're reconnecting add /connect to the url
    BOOL _reconnecting = initializeCallback == nil;
    SRThreadSafeInvoker *callbackInvoker = [[SRThreadSafeInvoker alloc] init];

    NSString *url = [(_reconnecting ? connection.url : [connection.url stringByAppendingString:@"connect"]) stringByAppendingFormat:@"%@",[self receiveQueryString:connection data:data]];
    __block id <SRRequest> request = nil;
    __block SREventSourceStreamReader *eventSource;
    __block id requestDisposer;

    [self.httpClient get:url requestPreparer:^(id<SRRequest> req) {
        request = req;
        [connection prepareRequest:request];

        [request setAccept:@"text/event-stream"];
    } completionHandler:^(id<SRResponse> response) {
        BOOL isFaulted = (response.error ||
                          [response.string isEqualToString:@""] ||
                          [response.string isEqualToString:@"null"]);

        if (isFaulted) {
            NSError *exception = response.error;
            if(![SRExceptionHelper isRequestAborted:exception]) {
                if (errorCallback != nil) {
                    SRLogServerSentEvents(@"isFaulted will report to errorCallback");

                    [callbackInvoker invoke:^(callback cb, NSError *ex) {
                        SRErrorByReferenceBlock errorBlock = ^(NSError ** error) {
                            if(error) {
                                *error = ex;
                            }
                        };
                        cb(errorBlock);
                    }
                    withCallback:errorCallback
                    withObject:exception];
                } else if(_reconnecting) {
                    // Only raise the error event if we failed to reconnect
                    [connection didReceiveError:exception];

                    [self reconnect:connection data:data];
                }
            }
            [[NSNotificationCenter defaultCenter] removeObserver:requestDisposer];
            requestDisposer = nil;
        } else {
            eventSource = [[SREventSourceStreamReader alloc] initWithStream:response.stream];
            __weak __typeof(&*self)weakSelf = self;
            __weak __typeof(&*connection)weakConnection = connection;
            __weak __typeof(&*response)weakResponse = response;
            __weak __typeof(&*data)weakData = data;
            __weak __typeof(&*callbackInvoker)weakCallbackInvoker = callbackInvoker;

            typedef void (^SRInitializedCallback)(void);
            __block SRInitializedCallback weakInitializedCallback = initializeCallback;
            __block BOOL retry = YES;

            __block id esCancellationRegistration = [[NSNotificationCenter defaultCenter] addObserverForName:SRConnectionDidDisconnect object:connection queue:[NSOperationQueue currentQueue] usingBlock:^(NSNotification *note) {
                retry = false;
                [eventSource close];
            }];

            eventSource.opened = ^() {
                __strong __typeof(&*weakConnection)strongConnection = weakConnection;
                __strong __typeof(&*weakCallbackInvoker)strongCallbackInvoker = weakCallbackInvoker;

                SRLogServerSentEvents(@"did initialize");

                if (!_reconnecting) {
                    if (weakInitializedCallback != nil) {
                        [strongCallbackInvoker invoke:weakInitializedCallback];
                        weakInitializedCallback = nil;
                    }
                } else if([strongConnection changeState:reconnecting toState:connected]) {
                    // Raise the reconnect event if the connection comes back up
                    [strongConnection didReconnect];
                }
            };

            eventSource.message = ^(SRSseEvent * sseEvent) {
                __strong __typeof(&*weakSelf)strongSelf = weakSelf;
                __strong __typeof(&*weakConnection)strongConnection = weakConnection;

                if(sseEvent.eventType == Data) {
                    if([sseEvent.data caseInsensitiveCompare:@"initialized"] == NSOrderedSame) {
                        return;
                    }

                    BOOL timedOut = NO;
                    BOOL disconnect = NO;
                    [strongSelf processResponse:strongConnection response:sseEvent.data timedOut:&timedOut disconnected:&disconnect];

                    if(disconnect) {
                        SRLogServerSentEvents(@"disconnect received should disconnect");

                        retry = NO;
                        [connection disconnect];
                    }
                }
            };

            eventSource.closed = ^(NSError *exception) {
                __strong __typeof(&*weakSelf)strongSelf = weakSelf;
                __strong __typeof(&*weakConnection)strongConnection = weakConnection;
                __strong __typeof(&*weakData)strongData = weakData;

                SRLogServerSentEvents(@"did close");
                BOOL isRequestAborted = NO;

                if (exception != nil) {
                    // Check if the request is aborted
                    isRequestAborted = [SRExceptionHelper isRequestAborted:exception];

                    if (!isRequestAborted) {
                        // Don't raise exceptions if the request was aborted (connection was stopped).
                        [strongConnection didReceiveError:exception];
                    }
                }

                // Skip reconnect attempt for aborted requests
                if (!isRequestAborted && retry)
                {
                    [strongSelf reconnect:strongConnection data:strongData];
                }
            };

            eventSource.disabled = ^() {
                __strong __typeof(&*weakResponse)strongResponse = weakResponse;
                [[NSNotificationCenter defaultCenter] removeObserver:requestDisposer];
                [[NSNotificationCenter defaultCenter] removeObserver:esCancellationRegistration];
                requestDisposer = nil;
                esCancellationRegistration = nil;
                [strongResponse close];
            };

            [eventSource start];
        }
    }];

    requestDisposer = [[NSNotificationCenter defaultCenter] addObserverForName:SRConnectionDidDisconnect object:connection queue:[NSOperationQueue currentQueue] usingBlock:^(NSNotification *note) {
        if (request != nil) {
            // This will no-op if the request is already finished.
            [request abort];
        }

        if (errorCallback != nil) {
            NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
            userInfo[NSLocalizedFailureReasonErrorKey] = NSInternalInconsistencyException;
            userInfo[NSLocalizedDescriptionKey] = NSLocalizedString(@"The connection was stopped before it could be started.",@"The connection was stopped before it could be started.");
            NSError *error = [NSError errorWithDomain:[NSString stringWithFormat:NSLocalizedString(@"com.SignalR-ObjC.%@",@""),NSStringFromClass([self class])]
                                                 code:NSURLErrorCancelled
                                             userInfo:userInfo];

            [callbackInvoker invoke:^(callback cb, NSError *ex) {
                SRErrorByReferenceBlock errorBlock = ^(NSError ** error){
                    if(error){
                        *error = ex;
                    }
                };
                cb(errorBlock);
            }
                       withCallback:errorCallback
                         withObject:error];
        }

    }];

    if (errorCallback != nil) {
        [[NSBlockOperation blockOperationWithBlock:^{
            [callbackInvoker invoke:^(callback cb, id <SRConnectionInterface> conn) {
                [connection disconnect];

                SRErrorByReferenceBlock errorBlock = ^(NSError ** error) {
                    if(error) {
                        NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
                        userInfo[NSLocalizedFailureReasonErrorKey] = NSInternalInconsistencyException;
                        userInfo[NSLocalizedDescriptionKey] = [NSString stringWithFormat:NSLocalizedString(@"Transport took longer than %d to connect",@""),_connectionTimeout];
                        *error = [NSError errorWithDomain:[NSString stringWithFormat:NSLocalizedString(@"com.SignalR-ObjC.%@",@""),NSStringFromClass([self class])]
                                                     code:NSURLErrorTimedOut
                                                 userInfo:userInfo];
                    }
                };
                cb(errorBlock);
                SRLogServerSentEvents(@"did call errorCallBack with timeout error");
            }
            withCallback:errorCallback
            withObject:connection];
        }] performSelector:@selector(start) withObject:nil afterDelay:[_connectionTimeout integerValue]];
    }
}

@end


text:
"use strict";
var BasePage_1 = require('../shared/BasePage');
var Page = (function (_super) {
    __extends(Page, _super);
    function Page() {
        _super.apply(this, arguments);
    }
    Page.prototype.mainContentLoaded = function () {
    };
    return Page;
}(BasePage_1.BasePage));
module.exports = new Page();
//# sourceMappingURL=slider.js.map


text:
/*global window,angular*/

/* App Module */
var playFilmApp = angular.module('playFilmApp', [
    'ngRoute',

    'filmControllers',
    'filmServices'
]).run(function ($rootScope) {
    'use strict';
    $rootScope.search = function () {
        window.location = "#/results";
    };
});

playFilmApp.config(['$routeProvider',
    function ($routeProvider) {
        'use strict';
        $routeProvider.
            when('/highlight', {
                templateUrl: 'assets/partials/film-highlight.html',
                controller: 'FilmHighlightCtrl'
            }).
            when('/films', {
                templateUrl: 'assets/partials/film-list.html',
                controller: 'FilmListCtrl'
            }).
            when('/results', {
                templateUrl: 'assets/partials/film-list.html',
                controller: 'SearchCtrl'
            }).
            when('/films/:filmId', {
                templateUrl: 'assets/partials/film-detail.html',
                controller: 'FilmDetailCtrl'
            }).
            when('/cart', {
                templateUrl: 'assets/partials/cart.html',
                controller: 'CartCtrl'
            }).
            otherwise({
                redirectTo: '/highlight'
            });
    }]);


text:
// Generated by xsd compiler for android/java
// DO NOT CHANGE!
package ebay.apis.eblbasecomponents;

import java.io.Serializable;
import com.leansoft.nano.annotation.*;

/**
 *
 * Applicable to sites that support the Detailed Seller Ratings feature.
 * The ItemRatingDetailsType contains detailed seller ratings for an order line item in one area. When buyers leave an overall Feedback rating (positive, neutral, or negative) for a seller, they also can leave ratings in four areas: item as described, communication, shipping time, and charges for shipping and handling. Users retrieve detailed ratings as averages of the ratings left by buyers.
 *
 */
public class ItemRatingDetailsType implements Serializable {

    private static final long serialVersionUID = -1L;

	@Element(name = "RatingDetail")
	private FeedbackRatingDetailCodeType ratingDetail;

	@Element(name = "Rating")
	private Integer rating;

	/**
     * public getter
     *
     *
     * The area of a specific detailed seller rating for an order line item.
     * When buyers leave an overall Feedback rating (positive, neutral, or negative)
     * for a seller, they also can leave ratings in four areas: item as described,
     * communication, shipping time, and charges for shipping and handling.
     *
     *
     * @returns ebay.apis.eblbasecomponents.FeedbackRatingDetailCodeType
	 */
	public FeedbackRatingDetailCodeType getRatingDetail() {
	    return this.ratingDetail;
	}

	/**
	 * public setter
	 *
     *
     * The area of a specific detailed seller rating for an order line item.
     * When buyers leave an overall Feedback rating (positive, neutral, or negative)
     * for a seller, they also can leave ratings in four areas: item as described,
     * communication, shipping time, and charges for shipping and handling.
     *
     *
     * @param ebay.apis.eblbasecomponents.FeedbackRatingDetailCodeType
	 */
	public void setRatingDetail(FeedbackRatingDetailCodeType ratingDetail) {
	    this.ratingDetail = ratingDetail;
	}
	/**
     * public getter
     *
     *
     * A detailed seller rating for an order line item applied to the area
     * in the corresponding RatingDetail field. Valid input values are
     * numerical integers 1 though 5.
     *
     *
     * @returns java.lang.Integer
	 */
	public Integer getRating() {
	    return this.rating;
	}

	/**
	 * public setter
	 *
     *
     * A detailed seller rating for an order line item applied to the area
     * in the corresponding RatingDetail field. Valid input values are
     * numerical integers 1 though 5.
     *
     *
     * @param java.lang.Integer
	 */
	public void setRating(Integer rating) {
	    this.rating = rating;
	}

}