text:
const chai = require('chai');
const sinon = require('sinon');
const { v4: uuidv4 } = require('uuid');
const _ = require('lodash');

const sampleData = require('../../../sample-data');
const TestHelper = require('../../../test-helper');
const { BudgetError } = require('../../../../app/middleware/error-handler');

const assert = chai.assert;

describe('Unit:Controllers - BudgetCtrl.createBudget', function() {
  let controllers;
  let models;
  const testHelper = new TestHelper();

  let trackChangesSpy;

  let user1HouseholdUuid;
  let user1SubcategoryUuid;
  let user1Uuid;
  let user2Uuid;

  before('get app', async function() {
    this.timeout(30000);
    const app = await testHelper.getApp();
    controllers = app.get('controllers');
    models = app.get('models');
  });

  before('create sinon spies', function() {
    trackChangesSpy = sinon.spy(controllers.AuditCtrl, 'trackChanges');
  });

  after('restore sinon spies', function() {
    trackChangesSpy.restore();
  });

  after('cleanup', async function() {
    await testHelper.cleanup();
  });

  beforeEach('create user 1', async function() {
    const household = await models.Household.create({
      name: sampleData.users.user1.lastName,
    });
    user1HouseholdUuid = household.get('uuid');
    const user = await models.User.create({
      email: sampleData.users.user1.email,
      first_name: sampleData.users.user1.firstName,
      household_uuid: household.get('uuid'),
      last_name: sampleData.users.user1.lastName,
    });
    user1Uuid = user.get('uuid');
  });

  beforeEach('create user 1 subcategory', async function() {
    const category = await models.Category.create({
      household_uuid: user1HouseholdUuid,
      name: sampleData.categories.category1.name,
    });
    const subcategory = await models.Subcategory.create({
      category_uuid: category.get('uuid'),
      name: sampleData.categories.category2.name,
    });
    user1SubcategoryUuid = subcategory.get('uuid');
  });

  beforeEach('create user 2', async function() {
    const household = await models.Household.create({
      name: sampleData.users.user2.lastName,
    });
    const user = await models.User.create({
      email: sampleData.users.user2.email,
      first_name: sampleData.users.user2.firstName,
      household_uuid: household.get('uuid'),
      last_name: sampleData.users.user2.lastName,
    });
    user2Uuid = user.get('uuid');
  });

  afterEach('reset history for sinon spies', function() {
    trackChangesSpy.resetHistory();
  });

  afterEach('truncate tables', async function() {
    this.timeout(10000);
    await testHelper.truncateTables();
  });

  it('should reject with no subcategory UUID', async function() {
    try {
      const apiCall = await models.Audit.ApiCall.create({
        user_uuid: user1Uuid,
      });
      await controllers.BudgetCtrl.createBudget({
        amount: sampleData.budgets.budget1.amount_cents,
        auditApiCallUuid: apiCall.get('uuid'),
        month: sampleData.budgets.budget1.month,
        notes: sampleData.budgets.budget1.notes,
        subcategoryUuid: null,
        year: sampleData.budgets.budget1.year,
      });
      /* istanbul ignore next */
      throw new Error('Expected to reject not resolve.');
    } catch (err) {
      assert.isOk(err);
      assert.strictEqual(err.message, 'Category is required');
      assert.isTrue(err instanceof BudgetError);
    }
    assert.strictEqual(trackChangesSpy.callCount, 0);
  });

  it('should reject with no year', async function() {
    try {
      const apiCall = await models.Audit.ApiCall.create({
        user_uuid: user1Uuid,
      });
      await controllers.BudgetCtrl.createBudget({
        amount: sampleData.budgets.budget1.amount_cents,
        auditApiCallUuid: apiCall.get('uuid'),
        month: sampleData.budgets.budget1.month,
        notes: sampleData.budgets.budget1.notes,
        subcategoryUuid: user1SubcategoryUuid,
        year: null,
      });
      /* istanbul ignore next */
      throw new Error('Expected to reject not resolve.');
    } catch (err) {
      assert.isOk(err);
      assert.strictEqual(err.message, 'Year is required');
      assert.isTrue(err instanceof BudgetError);
    }
    assert.strictEqual(trackChangesSpy.callCount, 0);
  });

  it('should reject with an invalid year (type)', async function() {
    try {
      const apiCall = await models.Audit.ApiCall.create({
        user_uuid: user1Uuid,
      });
      await controllers.BudgetCtrl.createBudget({
        amount: sampleData.budgets.budget1.amount_cents,
        auditApiCallUuid: apiCall.get('uuid'),
        month: sampleData.budgets.budget1.month,
        notes: sampleData.budgets.budget1.notes,
        subcategoryUuid: user1SubcategoryUuid,
        year: 'invalid year',
      });
      /* istanbul ignore next */
      throw new Error('Expected to reject not resolve.');
    } catch (err) {
      assert.isOk(err);
      assert.strictEqual(err.message, 'Year is required');
      assert.isTrue(err instanceof BudgetError);
    }
    assert.strictEqual(trackChangesSpy.callCount, 0);
  });

  it('should reject with an invalid year (too small)', async function() {
    try {
      const apiCall = await models.Audit.ApiCall.create({
        user_uuid: user1Uuid,
      });
      await controllers.BudgetCtrl.createBudget({
        amount: sampleData.budgets.budget1.amount_cents,
        auditApiCallUuid: apiCall.get('uuid'),
        month: sampleData.budgets.budget1.month,
        notes: sampleData.budgets.budget1.notes,
        subcategoryUuid: user1SubcategoryUuid,
        year: 1999,
      });
      /* istanbul ignore next */
      throw new Error('Expected to reject not resolve.');
    } catch (err) {
      assert.isOk(err);
      assert.strictEqual(err.message, 'Invalid year');
      assert.isTrue(err instanceof BudgetError);
    }
    assert.strictEqual(trackChangesSpy.callCount, 0);
  });

  it('should reject with an invalid year (too large)', async function() {
    try {
      const apiCall = await models.Audit.ApiCall.create({
        user_uuid: user1Uuid,
      });
      await controllers.BudgetCtrl.createBudget({
        amount: sampleData.budgets.budget1.amount_cents,
        auditApiCallUuid: apiCall.get('uuid'),
        month: sampleData.budgets.budget1.month,
        notes: sampleData.budgets.budget1.notes,
        subcategoryUuid: user1SubcategoryUuid,
        year: 2051,
      });
      /* istanbul ignore next */
      throw new Error('Expected to reject not resolve.');
    } catch (err) {
      assert.isOk(err);
      assert.strictEqual(err.message, 'Invalid year');
      assert.isTrue(err instanceof BudgetError);
    }
    assert.strictEqual(trackChangesSpy.callCount, 0);
  });

  it('should reject with no month', async function() {
    try {
      const apiCall = await models.Audit.ApiCall.create({
        user_uuid: user1Uuid,
      });
      await controllers.BudgetCtrl.createBudget({
        amount: sampleData.budgets.budget1.amount_cents,
        auditApiCallUuid: apiCall.get('uuid'),
        month: null,
        notes: sampleData.budgets.budget1.notes,
        subcategoryUuid: user1SubcategoryUuid,
        year: sampleData.budgets.budget1.year,
      });
      /* istanbul ignore next */
      throw new Error('Expected to reject not resolve.');
    } catch (err) {
      assert.isOk(err);
      assert.strictEqual(err.message, 'Month is required');
      assert.isTrue(err instanceof BudgetError);
    }
    assert.strictEqual(trackChangesSpy.callCount, 0);
  });

  it('should reject with an invalid month (type)', async function() {
    try {
      const apiCall = await models.Audit.ApiCall.create({
        user_uuid: user1Uuid,
      });
      await controllers.BudgetCtrl.createBudget({
        amount: sampleData.budgets.budget1.amount_cents,
        auditApiCallUuid: apiCall.get('uuid'),
        month: 'invalid month',
        notes: sampleData.budgets.budget1.notes,
        subcategoryUuid: user1SubcategoryUuid,
        year: sampleData.budgets.budget1.year,
      });
      /* istanbul ignore next */
      throw new Error('Expected to reject not resolve.');
    } catch (err) {
      assert.isOk(err);
      assert.strictEqual(err.message, 'Month is required');
      assert.isTrue(err instanceof BudgetError);
    }
    assert.strictEqual(trackChangesSpy.callCount, 0);
  });

  it('should reject with an invalid month (too small)', async function() {
    try {
      const apiCall = await models.Audit.ApiCall.create({
        user_uuid: user1Uuid,
      });
      await controllers.BudgetCtrl.createBudget({
        amount: sampleData.budgets.budget1.amount_cents,
        auditApiCallUuid: apiCall.get('uuid'),
        month: -1,
        notes: sampleData.budgets.budget1.notes,
        subcategoryUuid: user1SubcategoryUuid,
        year: sampleData.budgets.budget1.year,
      });
      /* istanbul ignore next */
      throw new Error('Expected to reject not resolve.');
    } catch (err) {
      assert.isOk(err);
      assert.strictEqual(err.message, 'Invalid month');
      assert.isTrue(err instanceof BudgetError);
    }
    assert.strictEqual(trackChangesSpy.callCount, 0);
  });

  it('should reject with an invalid month (too large)', async function() {
    try {
      const apiCall = await models.Audit.ApiCall.create({
        user_uuid: user1Uuid,
      });
      await controllers.BudgetCtrl.createBudget({
        amount: sampleData.budgets.budget1.amount_cents,
        auditApiCallUuid: apiCall.get('uuid'),
        month: 12,
        notes: sampleData.budgets.budget1.notes,
        subcategoryUuid: user1SubcategoryUuid,
        year: sampleData.budgets.budget1.year,
      });
      /* istanbul ignore next */
      throw new Error('Expected to reject not resolve.');
    } catch (err) {
      assert.isOk(err);
      assert.strictEqual(err.message, 'Invalid month');
      assert.isTrue(err instanceof BudgetError);
    }
    assert.strictEqual(trackChangesSpy.callCount, 0);
  });

  it('should reject with no amount', async function() {
    try {
      const apiCall = await models.Audit.ApiCall.create({
        user_uuid: user1Uuid,
      });
      await controllers.BudgetCtrl.createBudget({
        amount: null,
        auditApiCallUuid: apiCall.get('uuid'),
        month: sampleData.budgets.budget1.month,
        notes: sampleData.budgets.budget1.notes,
        subcategoryUuid: user1SubcategoryUuid,
        year: sampleData.budgets.budget1.year,
      });
      /* istanbul ignore next */
      throw new Error('Expected to reject not resolve.');
    } catch (err) {
      assert.isOk(err);
      assert.strictEqual(err.message, 'Invalid budget');
      assert.isTrue(err instanceof BudgetError);
    }
    assert.strictEqual(trackChangesSpy.callCount, 0);
  });

  it('should reject with an invalid amount', async function() {
    try {
      const apiCall = await models.Audit.ApiCall.create({
        user_uuid: user1Uuid,
      });
      await controllers.BudgetCtrl.createBudget({
        amount: 'invalid amount',
        auditApiCallUuid: apiCall.get('uuid'),
        month: sampleData.budgets.budget1.month,
        notes: sampleData.budgets.budget1.notes,
        subcategoryUuid: user1SubcategoryUuid,
        year: sampleData.budgets.budget1.year,
      });
      /* istanbul ignore next */
      throw new Error('Expected to reject not resolve.');
    } catch (err) {
      assert.isOk(err);
      assert.strictEqual(err.message, 'Invalid budget');
      assert.isTrue(err instanceof BudgetError);
    }
    assert.strictEqual(trackChangesSpy.callCount, 0);
  });

  it('should reject with no notes', async function() {
    try {
      const apiCall = await models.Audit.ApiCall.create({
        user_uuid: user1Uuid,
      });
      await controllers.BudgetCtrl.createBudget({
        amount: sampleData.budgets.budget1.amount_cents,
        auditApiCallUuid: apiCall.get('uuid'),
        month: sampleData.budgets.budget1.month,
        notes: null,
        subcategoryUuid: user1SubcategoryUuid,
        year: sampleData.budgets.budget1.year,
      });
      /* istanbul ignore next */
      throw new Error('Expected to reject not resolve.');
    } catch (err) {
      assert.isOk(err);
      assert.strictEqual(err.message, 'Invalid notes');
      assert.isTrue(err instanceof BudgetError);
    }
  });

  it('should reject with invalid notes', async function() {
    try {
      const apiCall = await models.Audit.ApiCall.create({
        user_uuid: user1Uuid,
      });
      await controllers.BudgetCtrl.createBudget({
        amount: sampleData.budgets.budget1.amount_cents,
        auditApiCallUuid: apiCall.get('uuid'),
        month: sampleData.budgets.budget1.month,
        notes: 123,
        subcategoryUuid: user1SubcategoryUuid,
        year: sampleData.budgets.budget1.year,
      });
      /* istanbul ignore next */
      throw new Error('Expected to reject not resolve.');
    } catch (err) {
      assert.isOk(err);
      assert.strictEqual(err.message, 'Invalid notes');
      assert.isTrue(err instanceof BudgetError);
    }
  });

  it('should reject with no audit API call', async function() {
    try {
      await controllers.BudgetCtrl.createBudget({
        amount: sampleData.budgets.budget1.amount_cents,
        auditApiCallUuid: null,
        month: sampleData.budgets.budget1.month,
        notes: sampleData.budgets.budget1.notes,
        subcategoryUuid: user1SubcategoryUuid,
        year: sampleData.budgets.budget1.year,
      });
      /* istanbul ignore next */
      throw new Error('Expected to reject not resolve.');
    } catch (err) {
      assert.isOk(err);
      assert.strictEqual(err.message, 'Missing audit API call');
      assert.isTrue(err instanceof BudgetError);
    }
    assert.strictEqual(trackChangesSpy.callCount, 0);
  });

  it('should reject when the audit API call does not exist', async function() {
    try {
      await controllers.BudgetCtrl.createBudget({
        amount: sampleData.budgets.budget1.amount_cents,
        auditApiCallUuid: uuidv4(),
        month: sampleData.budgets.budget1.month,
        notes: sampleData.budgets.budget1.notes,
        subcategoryUuid: user1SubcategoryUuid,
        year: sampleData.budgets.budget1.year,
      });
      /* istanbul ignore next */
      throw new Error('Expected to reject not resolve.');
    } catch (err) {
      assert.isOk(err);
      assert.strictEqual(err.message, 'Missing audit API call');
      assert.isTrue(err instanceof BudgetError);
    }
    assert.strictEqual(trackChangesSpy.callCount, 0);
  });

  it('should reject when the user does not exist', async function() {
    try {
      await models.User.destroy({
        where: {
          uuid: user1Uuid,
        },
      });
      const apiCall = await models.Audit.ApiCall.create({
        user_uuid: user1Uuid,
      });
      await controllers.BudgetCtrl.createBudget({
        amount: sampleData.budgets.budget1.amount_cents,
        auditApiCallUuid: apiCall.get('uuid'),
        month: sampleData.budgets.budget1.month,
        notes: sampleData.budgets.budget1.notes,
        subcategoryUuid: user1SubcategoryUuid,
        year: sampleData.budgets.budget1.year,
      });
      /* istanbul ignore next */
      throw new Error('Expected to reject not resolve.');
    } catch (err) {
      assert.isOk(err);
      assert.strictEqual(err.message, 'Audit user does not exist');
      assert.isTrue(err instanceof BudgetError);
    }
    assert.strictEqual(trackChangesSpy.callCount, 0);
  });

  it('should reject when the subcategory does not exist', async function() {
    try {
      const apiCall = await models.Audit.ApiCall.create({
        user_uuid: user1Uuid,
      });
      await controllers.BudgetCtrl.createBudget({
        amount: sampleData.budgets.budget1.amount_cents,
        auditApiCallUuid: apiCall.get('uuid'),
        month: sampleData.budgets.budget1.month,
        notes: sampleData.budgets.budget1.notes,
        subcategoryUuid: uuidv4(),
        year: sampleData.budgets.budget1.year,
      });
      /* istanbul ignore next */
      throw new Error('Expected to reject not resolve.');
    } catch (err) {
      assert.isOk(err);
      assert.strictEqual(err.message, 'Category not found');
      assert.isTrue(err instanceof BudgetError);
    }
    assert.strictEqual(trackChangesSpy.callCount, 0);
  });

  it('should reject when the subcategory belongs to a different household', async function() {
    try {
      const apiCall = await models.Audit.ApiCall.create({
        user_uuid: user2Uuid,
      });
      await controllers.BudgetCtrl.createBudget({
        amount: sampleData.budgets.budget1.amount_cents,
        auditApiCallUuid: apiCall.get('uuid'),
        month: sampleData.budgets.budget1.month,
        notes: sampleData.budgets.budget1.notes,
        subcategoryUuid: user1SubcategoryUuid,
        year: sampleData.budgets.budget1.year,
      });
      /* istanbul ignore next */
      throw new Error('Expected to reject not resolve.');
    } catch (err) {
      assert.isOk(err);
      assert.strictEqual(err.message, 'Category not found');
      assert.isTrue(err instanceof BudgetError);
    }
    assert.strictEqual(trackChangesSpy.callCount, 0);
  });

  it('should resolve creating a budget', async function() {
    const apiCall = await models.Audit.ApiCall.create({
      user_uuid: user1Uuid,
    });
    const budgetUuid = await controllers.BudgetCtrl.createBudget({
      amount: sampleData.budgets.budget1.amount_cents,
      auditApiCallUuid: apiCall.get('uuid'),
      month: sampleData.budgets.budget1.month,
      notes: sampleData.budgets.budget1.notes,
      subcategoryUuid: user1SubcategoryUuid,
      year: sampleData.budgets.budget1.year,
    });

    assert.isOk(budgetUuid);

    // Verify the Budget instance.
    const budget = await models.Budget.findOne({
      attributes: [
        'amount_cents',
        'month',
        'notes',
        'subcategory_uuid',
        'uuid',
        'year',
      ],
      where: {
        uuid: budgetUuid,
      },
    });
    assert.isOk(budget);
    assert.strictEqual(budget.get('amount_cents'), sampleData.budgets.budget1.amount_cents);
    assert.strictEqual(budget.get('month'), sampleData.budgets.budget1.month);
    assert.strictEqual(budget.get('notes'), sampleData.budgets.budget1.notes);
    assert.strictEqual(budget.get('subcategory_uuid'), user1SubcategoryUuid);
    assert.strictEqual(budget.get('year'), sampleData.budgets.budget1.year);

    assert.strictEqual(trackChangesSpy.callCount, 1);
    const trackChangesParams = trackChangesSpy.getCall(0).args[0];
    assert.strictEqual(trackChangesParams.auditApiCallUuid, apiCall.get('uuid'));
    assert.isNotOk(trackChangesParams.changeList);
    assert.isNotOk(trackChangesParams.deleteList);
    assert.isOk(trackChangesParams.newList);
    const newBudget = _.find(trackChangesParams.newList, (newInstance) => {
      return newInstance instanceof models.Budget
        && newInstance.get('uuid') === budget.get('uuid');
    });
    assert.isOk(newBudget);
    assert.strictEqual(trackChangesParams.newList.length, 1);
    assert.isOk(trackChangesParams.transaction);
  });

  it('should reject creating a budget with a duplicate month, year and subcategory', async function() {
    const apiCall = await models.Audit.ApiCall.create({
      user_uuid: user1Uuid,
    });
    await controllers.BudgetCtrl.createBudget({
      amount: sampleData.budgets.budget1.amount_cents,
      auditApiCallUuid: apiCall.get('uuid'),
      month: sampleData.budgets.budget1.month,
      notes: sampleData.budgets.budget1.notes,
      subcategoryUuid: user1SubcategoryUuid,
      year: sampleData.budgets.budget1.year,
    });
    try {
      await controllers.BudgetCtrl.createBudget({
        amount: sampleData.budgets.budget2.amount_cents,
        auditApiCallUuid: apiCall.get('uuid'),
        month: sampleData.budgets.budget1.month,
        notes: sampleData.budgets.budget2.notes,
        subcategoryUuid: user1SubcategoryUuid,
        year: sampleData.budgets.budget1.year,
      });
      /* istanbul ignore next */
      throw new Error('Expected to reject not resolve.');
    } catch (err) {
      assert.isOk(err);
      assert.strictEqual(err.message, 'Duplicate budget');
      assert.isTrue(err instanceof BudgetError);
    }
  });

  it('should resolve creating a budget with empty notes', async function() {
    const apiCall = await models.Audit.ApiCall.create({
      user_uuid: user1Uuid,
    });
    const budgetUuid = await controllers.BudgetCtrl.createBudget({
      amount: sampleData.budgets.budget1.amount_cents,
      auditApiCallUuid: apiCall.get('uuid'),
      month: sampleData.budgets.budget1.month,
      notes: '',
      subcategoryUuid: user1SubcategoryUuid,
      year: sampleData.budgets.budget1.year,
    });

    assert.isOk(budgetUuid);

    // Verify the Budget instance.
    const budget = await models.Budget.findOne({
      attributes: [
        'amount_cents',
        'month',
        'notes',
        'subcategory_uuid',
        'uuid',
        'year',
      ],
      where: {
        uuid: budgetUuid,
      },
    });
    assert.isOk(budget);
    assert.strictEqual(budget.get('amount_cents'), sampleData.budgets.budget1.amount_cents);
    assert.strictEqual(budget.get('month'), sampleData.budgets.budget1.month);
    assert.strictEqual(budget.get('notes'), '');
    assert.strictEqual(budget.get('subcategory_uuid'), user1SubcategoryUuid);
    assert.strictEqual(budget.get('year'), sampleData.budgets.budget1.year);

    assert.strictEqual(trackChangesSpy.callCount, 1);
    const trackChangesParams = trackChangesSpy.getCall(0).args[0];
    assert.strictEqual(trackChangesParams.auditApiCallUuid, apiCall.get('uuid'));
    assert.isNotOk(trackChangesParams.changeList);
    assert.isNotOk(trackChangesParams.deleteList);
    assert.isOk(trackChangesParams.newList);
    const newBudget = _.find(trackChangesParams.newList, (newInstance) => {
      return newInstance instanceof models.Budget
        && newInstance.get('uuid') === budget.get('uuid');
    });
    assert.isOk(newBudget);
    assert.strictEqual(trackChangesParams.newList.length, 1);
    assert.isOk(trackChangesParams.transaction);
  });
});


text:
START_ATF_NAMESPACE
    typedef tagOLEUIGNRLPROPSW *POLEUIGNRLPROPSW;
END_ATF_NAMESPACE

redpajama_set_name: RedPajamaGithub


text:
import React from 'react';
import { compose, pure, setPropTypes } from 'recompose';
import PropTypes from 'prop-types';

import GradientOverlayImage from '@ui/GradientOverlayImage';
import ProgressiveImage from '@ui/ProgressiveImage';
import { getItemImages } from '@utils/content';

const enhance = compose(
  pure,
  setPropTypes({
    images: PropTypes.any, // eslint-disable-line
    thumbnail:  PropTypes.any, // eslint-disable-line
    imageOverlayColor: PropTypes.string,
  }),
);

const ImageHeader = enhance(({ images, thumbnail, imageOverlayColor }) => (
  <GradientOverlayImage
    ImageComponent={ProgressiveImage}
    // todo: calling getItemImages like this is kinda dirty
    source={getItemImages({ content: { images } })}
    thumbnail={thumbnail}
    overlayColor={imageOverlayColor}
  />
));

export default ImageHeader;


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WPFDemo
{
        /// <summary>
        /// MainWindow.xaml 的交互逻辑
        /// </summary>
        public partial class MainWindow : Window
        {
                public MainWindow()
                {
                        InitializeComponent();
                        AppDomain app = AppDomain.CurrentDomain;
                        app.UnhandledException += app_UnhandledException;
                        this.Closing += MainWindow_Closing;
                }

                void app_UnhandledException(object sender, UnhandledExceptionEventArgs e)
                {
                }

                void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
                {
                        MessageBox.Show("关闭");
                }

                private void btn_Click(object sender, RoutedEventArgs e)
                {
                        throw new Exception();
                }
        }
}


text:
import * as vs from 'vscode';

import { Model } from './model';
import { GitService } from './gitService';
import { CommandCenter } from './commands';
import { HistoryViewProvider } from './historyViewProvider';
import { ExplorerViewProvider } from './explorerViewProvider';
import { InfoViewProvider } from './infoViewProvider';
import { BlameViewProvider } from './blameViewProvider';

export function activate(context: vs.ExtensionContext) {
  let gitService = new GitService(context);
  let model = new Model(context, gitService);
  let historyViewProvider = new HistoryViewProvider(context, model, gitService);
  let infoViewProvider = new InfoViewProvider(context, model, gitService);
  new ExplorerViewProvider(context, model, gitService);
  new BlameViewProvider(context, model, gitService);
  new CommandCenter(context, model, gitService, historyViewProvider, infoViewProvider);
}

export function deactivate() {}


text:
import 'reflect-metadata';
import { StackServer } from './stack-server';
import { logger } from '@cdm-logger/server';

declare var module: __WebpackModuleApi.Module;

const service = new StackServer();
async function start() {
    await service.initialize();
    await service.start();
}

if (module.hot) {
    module.hot.status(event => {
        if (event === 'abort' || event === 'fail') {
            logger.error('HMR error status: ' + event);
            // Signal webpack.run.js to do full-reload of the back-end
            service.cleanup();
        }
        // adddintionally when event is idle due to external modules
        if (event === 'idle') {
            service.cleanup();
        }
    });
    module.hot.accept();
}

start();


text:
define(function () {

    function guid() {
        return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
    };

    return {
        guid: guid
    }
});


text:
/**
 *
 * @file common_magma.h
 *
 *  clMAGMA (version 1.1.0) --
 *  Univ. of Tennessee, Knoxville
 *  Univ. of California, Berkeley
 *  Univ. of Colorado, Denver
 *  @date January 2014
 *
 *
 **/

/***************************************************************************//**
 *  MAGMA facilities of interest to both src and magmablas directories
 **/
#ifndef _MAGMA_COMMON_H_
#define _MAGMA_COMMON_H_

#include <stdio.h>
#include <math.h>
#include <string.h>
#include <ctype.h>

#if defined( _WIN32 ) || defined( _WIN64 )

#  include "magmawinthread.h"
#  include <windows.h>
#  include <limits.h>
#  include <io.h>

#else

#  include <pthread.h>
#  include <unistd.h>
#  include <inttypes.h>

#endif

#include "magma.h"
#include "magma_lapack.h"
#include "operators.h"
#include "transpose.h"

/** ****************************************************************************
 * C99 standard defines __func__. Some older compilers use __FUNCTION__.
 * Note __func__ is not a macro, so ifndef __func__ doesn't work.
 */
#if __STDC_VERSION__ < 199901L
# if __GNUC__ >= 2 || _MSC_VER >= 1300
#  define __func__ __FUNCTION__
# else
#  define __func__ "<unknown>"
# endif
#endif

/** ****************************************************************************
 *  Determine if weak symbols are allowed
 */
#if defined(linux) || defined(__linux) || defined(__linux__)
#if defined(__GNUC_EXCL__) || defined(__GNUC__)
#define MAGMA_HAVE_WEAK    1
#endif
#endif

/***************************************************************************//**
 *  Global utilities
 **/
#ifndef max
#define max(a, b) ((a) > (b) ? (a) : (b))
#endif
#ifndef min
#define min(a, b) ((a) < (b) ? (a) : (b))
#endif
#ifndef roundup
#define roundup(a, b) (b <= 0) ? (a) : (((a) + (b)-1) & ~((b)-1))
#endif

/** ****************************************************************************
 *  Define magma_[sd]sqrt functions
 *    - sqrt alone cannot be catched by the generation script because of tsqrt
 */

#define magma_dsqrt sqrt
#define magma_ssqrt sqrt

/** ****************************************************************************
 *  Define macros for error checking
 */
void chk_helper( int err, const char* func, const char* file, int line );

// if debugging is enabled, assert that all functions return correctly
#ifndef NDEBUG
#  define chk( err ) chk_helper( err, __func__, __FILE__, __LINE__  )
#else
#  define chk( err ) (err)
#endif

#endif /* _MAGMA_COMMON_H_ */


text:
<?php

namespace Econda\RecEngine\Exception;

class InvalidArgumentException extends \InvalidArgumentException
{
}


text:
// Copyright (c) 2015 Flowgrammable.org
// All rights reserved

#include "../libmatch/basic_trie.cpp"

#include <iostream>
#include <vector>
#include <string>
#include <stdio.h>
#include <fstream>
#include <cstdint>
#include <sstream>
#include <iomanip>
#include <math.h>
#include <chrono>
#include <algorithm>
#include <functional>

using namespace std;
using  ns = chrono::nanoseconds;
using  ms = chrono::microseconds;
using get_time = chrono::steady_clock ;

struct Result {
  // define the result struct for merging algorithm
  int flag = -1; // show the different bit position
  int dif = 0; // the number bit of difference
};

// Matches integer type
Rule strTint(string rulestr)
{
  Rule rule;
  rule.mask = 0;
  rule.value = 0;
  // Find the position of ".", which spilit IP address to 4 parts
  size_t p1 = rulestr.find_first_of(" ");

  string substr1 = rulestr.substr(0,p1);
  string substr2 = rulestr.substr((p1 + 1));

  rule.value = stoull(substr1); // unsigned long long 64bit
  rule.mask = stoull(substr2);

  return rule;
}

/*
 * Check the mask part relation
 * whether is subset
 * the "1" bit position
*/

bool is_subset(Rule a, Rule b)
{
  vector<int> vec_a;
  vector<int> vec_b;
  // Get the "1" bit position for the mask part of two rules
  for (int i = 0; i < 64; i++) {
    if ((a.mask & (uint64_t(1) << i)) == 1) {
      vec_a.push_back(i);
    }
    if ((b.mask & (uint64_t(1) << i)) == 1) {
      vec_b.push_back(i);
    }
  }
  // Check the vec_a and vec_b is subset or not
  std::sort(vec_a.begin(),vec_a.end());
  std::sort(vec_b.begin(),vec_b.end());
  if (std::includes (vec_a.begin(), vec_a.end(), vec_b.begin(),vec_b.end())
      || std::includes (vec_b.begin(), vec_b.end(), vec_a.begin(),vec_a.end())) {
    return true;
  }
  else {
    return false;
  }
}

/*
 * Merge the rules between the first rule and second rule
 * depends on the bits of every column
 * if in each column, it has "1" and "0" or "*"
*/
Result is_mergeable(Rule firstrule, Rule secondrule)
{
  Result ret;
  Rule rule1;
  rule1.mask = firstrule.mask | secondrule.mask;
  //cout << "rule1.mask = " << rule1.mask << endl;
  if (rule1.mask == 0) {
    for (int q = 0; q < 64; q++) {
      if ((firstrule.value & (uint64_t(1) << q)) != (secondrule.value & (uint64_t(1) << q)) ) {
        ret.flag = q; // show the bit position
        ret.dif++;
      }
      else {
        continue;
      }
    }
  }
  else {
    for (int k = 0; k < 64; k++) {
      if ((rule1.mask & (uint64_t(1) << k)) == 0) {
        // check the value part, the hamming distance
        // Check the hamming distance between the value part in the "0" positions
        if ((firstrule.value & (uint64_t(1) << k)) != (secondrule.value & (uint64_t(1) << k)) ) {
          ret.flag = k; // show the bit position
          ret.dif++;
        }
        else {
          continue;
        }
      }
      else {
        continue;
      }
    }
  }
  return ret;
  // The condition for merging, hamming distance smaller than 1
}

vector<Rule> merge_rules(vector<Rule>& ruleList)
{
  // Copy into a new vector
  vector<Rule> new_rule_list(ruleList);
  Rule newRule7;
  for (int i = 0; i < new_rule_list.size() - 1; i++) {
    for (int j = i+1; j < new_rule_list.size(); j++) {
      // The condition for able to merging
      //if (new_rule_list.at(i).mask == new_rule_list.at(j).mask)
      //if (is_subset (new_rule_list.at(i), new_rule_list.at(j)))
      if (new_rule_list.at(i).mask == new_rule_list.at(j).mask) {
        Result ret2 = is_mergeable(new_rule_list.at(i), new_rule_list.at(j));
        //cout << "i =" << i << " " << "j =" << j << " " << "dif =" << ret2.dif << " " << "flag =" << ret2.flag << endl;
        if (ret2.dif == 0) {
          // the value part is the same on the "1" positions at mask part
          //cout << "Merge rules" << endl;
          newRule7.mask = (new_rule_list.at(i).mask | new_rule_list.at(j).mask);
          newRule7.value = new_rule_list.at(i).value & new_rule_list.at(j).value;
          //newRule7.priority = min( new_rule_list.at(i).priority, new_rule_list.at(j).priority );
          newRule7.priority = new_rule_list.size() - 1;
          //cout << "value = " << newRule7.value << " " << "mask = " << newRule7.mask << " " << "priority = " << newRule7.priority << endl;
          new_rule_list.erase(new_rule_list.begin() + i);
          new_rule_list.erase(new_rule_list.begin() + (j-1));
          // Insert the new merged rule into the beginning of the vector
          new_rule_list.push_back(newRule7);
          i = -1;
          break;
        }
        if (ret2.dif == 1) {
          //cout << "Merge rules" << endl;
          newRule7.mask = (new_rule_list.at(i).mask | new_rule_list.at(j).mask)
              + (uint64_t(1) << ret2.flag);
          newRule7.value = new_rule_list.at(i).value & new_rule_list.at(j).value;
          //newRule7.priority = min( new_rule_list.at(i).priority, new_rule_list.at(j).priority );
          newRule7.priority = new_rule_list.size() - 1;
          //cout << "value = " << newRule7.value << " " << "mask = " << newRule7.mask << " " << "priority = " << newRule7.priority << endl;
          new_rule_list.erase(new_rule_list.begin() + i);
          new_rule_list.erase(new_rule_list.begin() + (j-1));
          // Insert the new merged rule into the beginning of the vector
          new_rule_list.push_back(newRule7);
          i = -1;
          break;
        }
        else {
          continue;
        }
      }
      else {
        continue;
      }
    }
  }
  /*
  for (int k = 0; k < new_rule_list.size(); k++) {
    cout << "value part:" << new_rule_list.at(k).value << " " << "mask part:" <<
            new_rule_list.at(k).mask  << endl;
  }
  */
  return new_rule_list;
}

/*
 * Check whether the new rule is a prefix rule
 * if yes, do the LPM insertion
 * if not, do the expand rule function
*/
bool is_prefix(Rule& rule)
{
  // Store the wildcard postion into vector maskPosion
  vector<uint32_t> maskPosition;
  // Check the mask field from the lower bit
  for(int i = 0; i < 64; i++) {
    // if this: get the position whose bit is 1 (have wildcard)
    if((rule.mask >> i) & uint64_t(1) == 1) {
      maskPosition.push_back(i);
    }
  }
  uint32_t num = maskPosition.size(); // num is the number of wildcard
  if (rule.mask == (uint64_t(1) << num)-1) {
    return true;
  }
  else {
    return false;
  }
}

// Sorting the rules in an asscending order
bool wayToSort(Rule aa, Rule bb)
{
  return aa.mask < bb.mask;
}

/*
 * Sorting the prefix format rules into asscending order, denpending on the prefix length
 * using the std::sort function
*/
vector<Rule> sort_rules(vector<Rule>& ruleList)
{
  // Copy the rules in each group into a new vector
  // for backup
  //vector<Rule> newSortedRules(ruleList);
  // Sort the newSumColumn vector in descending order
  std::sort(ruleList.begin(), ruleList.end(), wayToSort);
  return ruleList;
}

/*
 * Generate the two dimensional array (generate delta array) from the pingRulesTable array
 * With all the bits in each rule, including "0" and "1"
 * Caculate the score--the sum of column
*/
vector<int> generate_delta(vector<Rule>& ruleList)
{
  vector<uint64_t> sumColumn;
  for (int j = 0; j < 64; j++) {
    uint32_t score = 0;
    for (int i = 0; i < ruleList.size(); i++) {
      score += ((((ruleList.at(i)).mask) >> j) & uint64_t(1));
    }
    sumColumn.push_back(score);
  }

  // Copy the sumColumn vector to a new vector
  vector<uint64_t> newSumColumn(sumColumn);
  /*
   * Checked the newSumColumn vector is the same with the sumColumn vector
  cout << newSumColumn.size() << endl;
  for (i = 0; i < newSumColumn.size(); i++) {
    cout << newSumColumn[i] << endl;
  }
  */

  // Sort the newSumColumn vector in descending order
  std::sort(newSumColumn.begin(), newSumColumn.end(), std::greater<uint64_t>());
  /*
   * Checked the descending order is correct or not
  for (i = 0; i < newSumColumn.size(); i++) {
    cout << newSumColumn[i] << endl;
  }
  */

  // Construct the delta(): the rearrangement operation {left shift, right shift, and no change}
  // the element in delta vector, can be negative, positive and "0"
  vector<int> delta;
  // checkpoint is the index/subscript of the newSumColumn has the same value with the sumColumn
  uint32_t checkpoint = 0;
  int gap = 0; // Gap is the difference between the original and new sumcolumn vectors
  for (int i = 0; i < sumColumn.size(); i++) {
    //cout << "mark1" << " " << sumColumn[i] << endl;
    for (int j = 0; j < newSumColumn.size(); j++) {
      //cout << newSumColumn[j] << endl;
      // Check the first equal element, if it is true, then return the checkpoint
      if (newSumColumn[j] != sumColumn[i]) {
        continue;
      }
      else if (newSumColumn[j] == sumColumn[i]) {
        checkpoint = j;
        newSumColumn[j] = 132; // make the matched column invalid
        break;
      }
      else {
        // Search all the 64 values, still didn't find the same value
        cout << "Error occurs" << endl;
      }
    }
    // Get the difference between the original vector data and the sorted vector data
    // Create the rearrangement operation
    gap = i - checkpoint;
    delta.push_back(gap);
  }
  return delta;
}

/*
 * Generate the new rule after the delta operations
 * if the element value of delta vector is negative, which means left shift
 * if the element value of delta vector is positive, which means right shift
 * if the element value of delta vector is "0", which means no change
*/
// Create a new pingRulesTable for the new rearrangement rules
//vector<Rule> newPingRulesTable; // for each bit of each rule
vector<Rule> rules_rearrange(vector<Rule>& oldRuleList, vector<int> delta_array)
{
  vector<Rule> sumRulesTable; // for a new rule

  for (int i = 0; i < oldRuleList.size(); i++) {
    Rule newRule;
    for (int j = 0; j < 64; j++) {
      Rule subRule;
      if (delta_array[j] < 0) {
        // if it is negative, do the left shift
        // from the lsb position, do the correct operations
        // Note: because here is 64 bit, if we just use 1 to do left shift, it will occur overflow
        // since "1" is 32bit by default
        subRule.value = ( (( (oldRuleList[i].value) & (uint64_t(1) << j) ) ) << (abs(delta_array[j])) );
        subRule.mask = ( (( (oldRuleList[i].mask) & (uint64_t(1) << j) ) ) << (abs(delta_array[j])) );
      }
      else if (delta_array[j] > 0) {
        // if it is positive, do the right shift
        subRule.value = ( (( (oldRuleList[i].value) & (uint64_t(1) << j) ) ) >> (abs(delta_array[j])) );
        subRule.mask = ( (( (oldRuleList[i].mask) & (uint64_t(1) << j) ) ) >> (abs(delta_array[j])) );
      }
      else if (delta_array[j] == 0) {
        // if it is "0", no change
        subRule.value = (( (oldRuleList[i].value) & (uint64_t(1) << j) ) );
        subRule.mask = (( (oldRuleList[i].mask) & (uint64_t(1) << j) ) );
      }
      newRule.value |= subRule.value;
      newRule.mask |= subRule.mask;
      //cout << j << " " << newRule.mask << endl;
      newRule.priority = oldRuleList[i].priority;
    }
    sumRulesTable.push_back(newRule);
  }
  return sumRulesTable;
}

/*
 * Rearrange each key in the keyTable according to the delta vector
 * because the rules are being reordered by the delta vector
*/

uint64_t keys_rearrange(uint64_t key, vector<int> delta_array)
{
  // Calculate the key rearrangement configure time basing on the delta vector

  uint64_t newKey = 0; // new key after reordering
  for (int j = 0; j < 64; j++) {
    uint64_t subKey = 0; // subKey is the single bit value of each key
    if (delta_array[j] < 0) {
      subKey = ( (( key & (uint64_t(1) << j) ) ) << (abs(delta_array[j])) );
    }
    else if (delta_array[j] > 0) {
      // if it is positive, do the right shift
      subKey = ( (( key & (uint64_t(1) << j) ) ) >> (abs(delta_array[j])) );
    }
    else if (delta_array[j] == 0) {
      // if it is "0", no change
      subKey = (( key & (uint64_t(1) << j) ) );
    }
    newKey |= subKey;
  }
  return newKey;
  //cout << newKey << endl;
}

int main(int argc, char* argv[])
{
  ifstream file (argv[1]);
  // Read the rules from txt file
  vector<Rule> pingRulesTable;
  int i = 0;
  if (file.is_open()) {
    while (!file.eof()) {
      // Read lines as long as the file is
      string line;
      getline(file,line);
      if(!line.empty()) {
        Rule rule = strTint(line);
        // Add the priority feature when generating rules
        // Priority is in-order of generating
        rule.priority = ++i;
        // Push the input file into ruleArray
        pingRulesTable.push_back(rule);
      }
    }
  }
  file.close();

  cout << "Original total size = " << pingRulesTable.size() << endl;
  //vector<Rule> pingRulesTable = merge_rules(oldpingRulesTable);
  //cout << "Merged total size = " << pingRulesTable.size() << endl;
  /*
  for (int k = 0; k < pingRulesTable.size(); k++) {
    cout << pingRulesTable[k].value << " " << pingRulesTable[k].mask << endl;
  }
  */
  // Read in keys from file:
  ifstream file1 (argv[2]);
  vector<uint64_t> keyTable;
  if (file1.is_open()) {
    while (!file1.eof()) {
      // Read lines as long as the file is
      string packet;
      getline(file1,packet);
      if(!packet.empty()) {
        uint64_t key = stoull(packet);
        // Push the input file into ruleArray
        keyTable.push_back(key);
      }
    }
  }
  file1.close();
  //cout << keyTable.size() << endl;

  /*
   * Grouping algorithm
   * Use the is_cross_pattern function to check the grouping number
   * Avoid the expanding number is too large
   * how to improve the grouping algorithm??
   * add the threshold, to adjust the grouping seperation
  */

  // For the grouped rule table
  vector<uint32_t> groupVector;
  vector<Rule> newList;

  // avoid the bad allocation memory

  uint32_t list_count = 0;
  for ( int i = 0; i < pingRulesTable.size(); i++ ) {
    if (i < (pingRulesTable.size()-1)) {
      newList.push_back(pingRulesTable[i]);
      vector<int> new_generated_delta = generate_delta(newList);
      // Create the rearranged rule set
      vector<Rule> new_table_list = rules_rearrange(
            newList, new_generated_delta );
      for ( int k = 0; k < new_table_list.size(); k++ ) {
        Trie trie1; // for caculating the trie1.new_num
        // for guarantee avoding the bad memory alloc
        if (trie1.get_new_num( new_table_list.at (k))  < 13) {
          continue;
        }
        else if (new_table_list.size() == 1) {
          groupVector.push_back(list_count);
          list_count += 1;
          newList.clear();
          break;
        }
        else if ((new_table_list.size() > 1)) {
          if (k == 0) {
            groupVector.push_back(list_count);
            i = list_count;
            list_count += 1;
            newList.clear();
            break;
          }
          else {
            groupVector.push_back(i-1);
            // clear the newList vector, becasue this is a seperated group
            list_count += k;
            newList.clear();
            i = i -1;
            break;
          }
        }
      }
    }
    else {
      groupVector.push_back(i);
    }
  }

  cout << "Num of groups is:" << " " << groupVector.size() << endl;

  /* Create all the subgroups
   * The big array is called bigArray
  */
  vector< vector<Rule> > bigArray;
  // Create a new sub group by copying the related rules

  for (int m = 0; m < groupVector.size(); m++) {
    bigArray.push_back(vector<Rule> ());
  }

  for (int j = 0; j < groupVector.size(); j++) {
    if (j == 0) {
      for (int i = 0; i < (groupVector[j] + 1); i++) {
        bigArray[j].push_back(pingRulesTable.at(i));
      }
      continue;
    }
    else {
      for (int k = (groupVector[j-1] + 1); k < (groupVector[j] + 1); k++) {
        bigArray[j].push_back(pingRulesTable.at(k));

      }
      continue;
    }
  }

  // Start to build the newRules in each group
  /*
   * We get the new rearrangement rules table here, named sumRulesTabel
   * Next, we will do the rules insertion
   * Here, we just insert prefix rules, follow the LPM insertion function
   * So we need to check whether each new rules is prefix rule
   * If it is, then do the insertion
   * if not, do the expansion algorithm to make it is prefix rule
  */

  int expandRule_num = 0;
  int insertRule_num = 0;
  uint64_t checksum = 0; // show the sum of matching priority
  uint64_t match = 0; // how many keys are being matched in these new rules
  uint64_t sum_trie_expand_count = 0;
  uint64_t sum_trie_count = 0;
  uint64_t sum_trie_node_count = 0;
  auto sum_rule_rearrange_time = 0;
  auto sum_rule_insertion_time = 0;
  auto sum_key_rearrange_time = 0;
  auto sum_key_search_time = 0;
  //get time1
  //auto start = get_time::now(); // use auto keyword to minimize typing strokes :)

  // Start to search each key here
  for (int j = 0; j < groupVector.size(); j++) {
    // Initilize a trie
    // Each group is a seperate trie

    Trie trie;
    auto start1 = get_time::now();
    //vector<Rule> newnewTable = merge_rules(bigArray[j]);
    vector<int> delta_need = generate_delta(bigArray[j]);
    vector<Rule> newSumRuleTable = rules_rearrange(bigArray[j], delta_need);
    // Sorting the rules in each group into asscending order
    // prepare for the merging next
    vector<Rule> newnewTable = merge_rules(newSumRuleTable);
    //vector<Rule> newSortedTable = sort_rules(newSumRuleTable);
    /*
    for (int i = 0; i < newSortedTable.size(); i++) {
      cout << "group ID:" << j << " " << newSortedTable.at(i).mask << " " << "sorted mask" << endl;
    }
    */

    auto end1 = get_time::now();
    auto diff1 = end1 - start1;
    sum_rule_rearrange_time += chrono::duration_cast<ms>(diff1).count();

    //Checked the num of groups: new rules
    /*
    if (j == 758) {
      for (int k = 0; k < newSumRuleTable.size(); k++) {
        cout << newSumRuleTable[k].value << " " << newSumRuleTable[k].mask
             << " " << newSumRuleTable[k].priority << endl;
      }
    }
    */
    //cout << "original table size = " << bigArray[j].size() << endl;
    //cout << "new table size = " << newnewTable.size() << endl;
    // Doing the rule insertion
    auto start2 = get_time::now();
    for (int k = 0; k < newnewTable.size(); k++) {
      if ( is_prefix(newnewTable.at(k)) ) {
        trie.insert_prefix_rule_priority(newnewTable.at(k));
        insertRule_num ++;
      }
      else {
        // becasue we control the number of expanding wildcard
        // so don't need to delete rules manually
        trie.expand_rule(newnewTable.at(k));
        expandRule_num ++;
      }
    }
    auto end2 = get_time::now();
    auto diff2 = end2 - start2;
    sum_rule_insertion_time += chrono::duration_cast<ms>(diff2).count();
    // Finished the rearranged rule insertion for each subtrie
    // Doing the rule searching
    char output[][32] = {"Not present in rulesTable", "Present in rulesTable"};
    // Search the rules
    //cout << "j is:" << j << "test again" << endl;

    for (int i = 0; i < keyTable.size(); i++) {
      // Check each key
      auto start3 = get_time::now();
      uint64_t newGenKey = keys_rearrange(keyTable[i], delta_need);
      auto end3 = get_time::now();
      auto diff3 = end3 - start3;
      sum_key_rearrange_time += chrono::duration_cast<ms>(diff3).count();
      auto start4 = get_time::now();
      uint64_t priority = trie.LPM1_search_rule(newGenKey);
      auto end4 = get_time::now();
      auto diff4 = end4 - start4;
      sum_key_search_time += chrono::duration_cast<ms>(diff4).count();
      match += (priority != 0); // when priority == 0, which means no matching
      if (priority == 0) {
        // not matching
        // Go to check the next keys through this current group of rules
        //cout << "not matching " << endl;
        continue;
      }
      else {
        checksum += priority;
        // Delete the matched keys from the keyTable
        // Avoid the duplication searching
        // Delete the element keyTable[i]
        keyTable.erase(keyTable.begin() + i);
        // Make sure the index is correct
        // Because we delete one key, so need to decrease index too
        //cout << "matching" << endl;
        i = i - 1;
        continue;
      }
    }
    sum_trie_expand_count += trie.expand_count;
    sum_trie_count += trie.count;
    sum_trie_node_count += trie.node_count;
    trie.delete_trie();
    //cout << "Group ID:" << j << match << " " << checksum << endl;
  }

  //get time2
  //auto end = get_time::now();
  //auto diff = end - start;

  cout << "Total rules rearrange configure time is:" << sum_rule_rearrange_time << " ms " << endl;
  cout << "Total rules insertion configure time is:" << sum_rule_insertion_time << " ms " << endl;
  cout << "Total keys rearrange configure time is:" << sum_key_rearrange_time << " ms " << endl;
  cout << "Total keys search time is:" << sum_key_search_time << " ms " << endl;
  cout << "Total expanded count is:" << " " << sum_trie_expand_count << endl;
  cout << "Expand rule num is:" << " " << expandRule_num << endl;
  cout << "Insert rule num is:" << " " << insertRule_num << endl;
  cout << "Total insert rule num is:" << " " << sum_trie_count << endl;
  cout << "Total insert trie_node count is:" << " " << sum_trie_node_count << endl;
  cout << "Checksum: " << checksum << endl;
  cout << "Total matches: " << match << endl;
  cout << "==================================================" << endl;

  return 0;
}


text:
package net.drailing.kunai.local;

import java.net.UnknownHostException;

import net.drailing.kunai.local.ui.UI;

public class Main {

	public static void main(String[] args) {

		if(args.length == 2){

			try {
				KunaiSocket socket = new KunaiSocket(Integer.valueOf(args[1]));
				socket.start();

				KunaiWebServer webserver = new KunaiWebServer(Integer.valueOf(args[0]), Integer.valueOf(args[1]));
				webserver.startServer();

			} catch (NumberFormatException e) {
				e.printStackTrace();
			} catch (UnknownHostException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
				System.exit(0);
			}

		}else{
			new UI();
		}

	}

}


text:
//
//  BaseNavigationController.m
//  Project114
//
//  Created by fosung_002 on 16/8/31.
//  Copyright © 2016年 fosung_002. All rights reserved.
//

#import "BaseNavigationController.h"

@interface BaseNavigationController ()

@end

@implementation BaseNavigationController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    UIColor * color = [UIColor blackColor];

    UIFont *ff=[UIFont systemFontOfSize:17];
    //    UITextAttributeFont
    NSDictionary * dict=[[NSDictionary alloc] initWithObjectsAndKeys:color,UITextAttributeTextColor,ff,UITextAttributeFont, nil];
    //    NSDictionary * dict=[NSDictionary dictionaryWithObject:color forKey:UITextAttributeTextColor];

    self.navigationBar.titleTextAttributes = dict;
    [self.navigationBar setBackgroundImage:[UIImage imageNamed:@"navar"] forBarMetrics:UIBarMetricsDefault];
    //  [self.navigationBar setBackgroundColor:[UIColor whiteColor]];

    //设置导航条样式
    [self.navigationController.navigationBar setBarStyle:UIBarStyleDefault];

    //    [self.navigationBar setBarStyle:UIBarStyleBlack];
    [self.navigationBar setTintColor:[UIColor whiteColor]];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
<?php
/**
 * Add post metabox
 */
add_action('add_meta_boxes', 'aym_portfolio_metaboxes');
function aym_portfolio_metaboxes(){
    global $post;
    if( !$post || empty($post->post_type) || 'portfolio' != $post->post_type){
        return;
    }
    //Add required styles & scripts
    add_action('admin_enqueue_scripts', 'aym_portfolio_metabox_scripst');

    // Add photos metabox grid
    add_meta_box('aym-portfolio-info', 'Projects Information', 'aym_portfolio_mbhtml', 'portfolio', 'normal', 'high');
}

function aym_portfolio_metabox_scripst(){
    $screen = get_current_screen();
    // Enqueue styles and scripts only pages
    if('post' == $screen->base && 'portfolio' == $screen->post_type){
        if(function_exists( 'wp_enqueue_media' )){
            wp_enqueue_media();
        }else{
            wp_enqueue_style('thickbox');
            wp_enqueue_script('media-upload');
            wp_enqueue_script('thickbox');
        }

        wp_enqueue_style( 'aympmb-style', AYM_PORTFOLIO_URI . '/css/admin-metabox-style.css', array(), 1.0 );
        wp_enqueue_script( 'aympmb-scripts', AYM_PORTFOLIO_URI . '/js/admin-metaboxe-script.js', array( 'jquery', 'jquery-ui-sortable' ), RWMB_VER, true );
    }

}

/**
 * Out put the metaboxes html
 */
function aym_portfolio_mbhtml($post){
    $website = get_post_meta($post->ID, 'aymp_website', true);
    $client_name = get_post_meta($post->ID, 'aymp_client_name', true);
    $screenshots = get_post_meta($post->ID, 'aymp_screenshots', true);
    $screenshots = !empty($screenshots)? (array)$screenshots:array();
?>

    <?php wp_nonce_field('aymp-save-portfolio', 'nonce-aymp-portfolio'); ?>

Website

            <input type="text" id="aymp-website" name="aymp_website" value="<?php echo $website; ?>" placeholder="Website Url"/>

Add website url to the project.

Clients Name

            <input type="text" id="aymp-clients-name" name="aymp_client_name" value="<?php echo $client_name; ?>" placeholder="Clients Name"/>

Add Clients name for whom the project was done.

Screenshots

            <input type="hidden" class="aymp-gallery" name="aymp_field_name" value="aymp_screenshots"/>
            Add Photo

                    <?php foreach($screenshots as $atid){
                        $src  = wp_get_attachment_image_src( $atid, 'thumbnail' );
			$src  = $src[0];
			$link = get_edit_post_link( $atid );
                    ?>
                    <li id="aympscid-<?php echo $atid; ?>" class="aymp-single-img">
                        <img alt="" src="<?php echo $src;?>"/>

                            <a title="Edit this screenshot" class="aymp-edit-image" href="<?php echo $link; ?>" target="_blank">Edit |
                            Remove

                        <input type="hidden" name="aymp_screenshots[]" value="<?php echo $atid;?>"/>

                    <?php }?>

Add photos of the project. You can reorder the photos by dragging them.

<?php
}

/* Save Post Meta */
add_action( 'save_post', 'aymp_save_proejct_info' );
function aymp_save_proejct_info($post_id){
// Get proper post type. @link http://www.deluxeblogtips.com/forums/viewtopic.php?id=161
    $post_type = null;
    $post = get_post( $post_id );

    if ( $post )
            $post_type = $post->post_type;
    elseif ( isset( $_POST['post_type'] ) && post_type_exists( $_POST['post_type'] ) )
            $post_type = $_POST['post_type'];

    $post_type_object = get_post_type_object( $post_type );
    // Check whether:
    // - the post is autosaved
    // - the post is a revision
    // - current post type is supported
    // - user has proper capability
    if (
            ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
            || ( ! isset( $_POST['post_ID'] ) || $post_id != $_POST['post_ID'] )
            || ( 'portfolio' !=  $post_type )
            || ( ! current_user_can( $post_type_object->cap->edit_post, $post_id ) )
    ){
            return $post_id;
    }
    // Check Nonce for home page grid
    if (  empty( $_POST['nonce-aymp-portfolio'] ) || !wp_verify_nonce( $_POST['nonce-aymp-portfolio'], 'aymp-save-portfolio' ) ){
        return $post_id;
    }

    //Save the projects info
    if(!empty($_POST['aymp_website'])){
        update_post_meta($post_id, 'aymp_website', $_POST['aymp_website']);
    }else{
        delete_post_meta($post_id, 'aymp_website');
    }

    if(!empty($_POST['aymp_client_name'])){
        update_post_meta($post_id, 'aymp_client_name', $_POST['aymp_client_name']);
    }else{
        delete_post_meta($post_id, 'aymp_client_name');
    }

    if(!empty($_POST['aymp_screenshots'])){
        update_post_meta($post_id, 'aymp_screenshots', $_POST['aymp_screenshots']);
    }else{
        delete_post_meta($post_id, 'aymp_screenshots');
    }

}


text:
package com.headius.invokebinder.transform;

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.Arrays;

/**
 * An argument-filtering transform.
 *
 * Equivalent call: MethodHandles.filterArguments(MethodHandle, int, MethodHandle...).
 */
public class Filter extends Transform {
    private final int index;
    private final MethodHandle[] functions;

    public static final String FILTER_FUNCTIONS_JAVA = "<filter functions>";

    public Filter(int index, MethodHandle... functions) {
        this.index = index;
        this.functions = functions;
    }

    public MethodHandle up(MethodHandle target) {
        return MethodHandles.filterArguments(target, index, functions);
    }

    public MethodType down(MethodType type) {
        for (int i = 0; i < functions.length; i++) {
            type = type.changeParameterType(index + i, functions[i].type().returnType());
        }
        return type;
    }

    public String toString() {
        return "fold args from " + index + " with " + Arrays.toString(functions);
    }

    public String toJava(MethodType incoming) {
        return "handle = MethodHandles.filterArguments(handle, " + index + ", " + FILTER_FUNCTIONS_JAVA + ");";
    }
}


text:
package net.glowstone.generator.populators.nether;

import net.glowstone.generator.objects.OreType;
import net.glowstone.generator.objects.OreVein;
import org.bukkit.Chunk;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.generator.BlockPopulator;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;

/**
 * Populates the world with ores.
 */
public class OrePopulator extends BlockPopulator {

    private final Map<OreType, Integer> ores = new LinkedHashMap<>();

    public OrePopulator() {
        ores.put(new OreType(Material.QUARTZ_ORE, 10, 118, 13, Material.NETHERRACK), 16);
    }

    @Override
    public void populate(World world, Random random, Chunk chunk) {
        final int cx = (chunk.getX() << 4);
        final int cz = (chunk.getZ() << 4);

        for (Entry<OreType, Integer> entry : ores.entrySet()) {

            final OreType oreType = entry.getKey();
            for (int n = 0; n < entry.getValue(); n++) {

                int sourceX = cx + random.nextInt(16);
                int sourceZ = cz + random.nextInt(16);
                int sourceY = oreType.getMinY() == oreType.getMaxY() ?
                        random.nextInt(oreType.getMinY()) + random.nextInt(oreType.getMinY()) :
                            random.nextInt(oreType.getMaxY() - oreType.getMinY()) + oreType.getMinY();

                new OreVein(oreType).generate(world, random, sourceX, sourceY, sourceZ);
            }
        }
    }
}


text:
using System.Windows;

namespace DemoWPFServer
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }
}


text:
require 'shellwords'
require 'chef/knife'
require 'chef/knife/kvm_base'

class Chef
  class Knife
    class KvmVmDelete < Knife
      include Chef::Knife::KvmBase

      banner "knife kvm vm delete NAME"

      option :hostname,
        :short => "-h hostname",
        :long => "--hostname",
        :description => "Host Name or IP"

      option :username,
        :short => "-u USERNAME",
        :long => "--username",
        :description => "Login Username"

      option :password,
        :short => "-p PASSWORD",
        :long => "--password",
        :description => "Login Password"

      #
      # Run the plugin
      #
      def run
        read_and_validate_params
        delete_vm
      end

      #
      # Reads the input parameters and validates them.
      # Will exit if it encounters an error
      #
      def read_and_validate_params
        if @name_args.length < 1
          show_usage
          exit 1
        end

        if config[:hostname].nil? ||
            config[:username].nil? ||
            config[:password].nil?
          show_usage
          exit 1
        end
      end

      private

      def delete_vm
        ui.info "Destroying machine"
        command = "virsh --connect qemu:///system destroy #{@name_args[0]}"
        result = run_remote_command(command)

        ui.info "Nuking machine"
        command = "virsh --connect qemu:///system undefine #{@name_args[0]} --remove-all-storage"
        result = run_remote_command(command)
      end
    end
  end
end


text:
<manifest package="com.github.chenglei1986.statusbar">
</manifest>


text:
if [ -z "$1" ] || [ -z "$2" ]; then
  >&2 echo "This script requires 2 positional parameters:"
  >&2 echo -e "\t1. ARN of key administrator"
  >&2 echo -e "\t2. ARN of key user"
  >&2 echo "Usage:"
  >&2 echo -e "\t$0 arn:aws:iam::000000000007:user/lukaszbudnik arn:aws:iam::000000000007:user/lukaszbudnik-test"
  exit 1
fi

region="eu-central-1"
stack_name="lukasz-test-key-2"
admin_arn=$1
user_arn=$2

aws cloudformation create-stack --stack-name $stack_name \
  --region $region \
  --capabilities CAPABILITY_IAM \
  --template-body file://kms.template.yml \
  --parameters \
    ParameterKey=AdminArn,ParameterValue=$admin_arn \
    ParameterKey=UserArn,ParameterValue=$user_arn

echo "Waiting for AWS CloudFormation to create the stack."
sleep 10

aws cloudformation wait stack-create-complete --region $region \
  --stack-name $stack_name

# race conditions, make sure describe-stacks will return correct response
sleep 10

output=$(aws cloudformation describe-stacks --region $region \
  --stack-name $stack_name)

# get key arn (there is only 1 output in stack)
key_arn=$(echo $output | jq -r '.Stacks[0].Outputs[0].OutputValue')

echo "Key created: $key_arn"

# generate data key

data_key_response=$(aws kms generate-data-key --key-id $key_arn --key-spec AES_256 --region $region)

echo "Data key generated:"
echo "$data_key_response"

data_key=$(echo $data_key_response | jq -r '.Plaintext')
encrypted_data_key=$(echo $data_key_response | jq -r '.CiphertextBlob')

echo "This file will be encrypted with a data key generated by KMS using key $key_arn" > plain.txt

echo "Original file:"
cat plain.txt

# data key is encoded in base64, convert it to raw bytes and pass to openssl stdin
base64 -D <<< $data_key | openssl enc -aes-256-ecb -pass stdin -in plain.txt -out encrypted.bin

# encryption done
# remove all traces of the raw data key - all was done in memory - key not persisted anywhere
unset data_key_response
unset data_key

# decryption

# decrypt encrypted data key with KMS

base64 -D <<< $encrypted_data_key > encrypted_data_key
data_key_response=$(aws kms decrypt --region $region --ciphertext-blob fileb://encrypted_data_key)

echo "Decrypted data key:"
echo "$data_key_response"

data_key=$(echo $data_key_response | jq -r '.Plaintext')

# using the data_key decrypt the file
base64 -D <<< $data_key | openssl enc -d -aes-256-ecb -pass stdin -in encrypted.bin -out plain_decrypted.txt

# verify that everything is fine
echo "Decrypted file:"
cat plain_decrypted.txt

# clean up

echo "Cleaning up local files and the stack"
rm plain*
rm encrypted*

aws cloudformation delete-stack --stack-name $stack_name --region $region


text:
<?php
namespace Isign\Tests\Integration;

use Isign\ResultInterface;
use Isign\Sign;

class MobileSignTest extends TestCase
{
    public function testSign()
    {
        /** @var Isign\Sign\MobileResult $result */
        $result = $this->client->get(new Sign\Mobile(
            'pdf',
            PHONE,
            CODE,
            $this->getDocumentParams()
        ));

        $this->assertSame(ResultInterface::STATUS_OK, $result->getStatus());
        $this->assertNotEmpty($result->getControlCode());
        $this->assertNotEmpty($result->getToken());

        return $result;
    }

    /**
     * @depends testSign
     * @params Sign\MobileResult $result
     */
    public function testSignStatusWaiting(Sign\MobileResult $result)
    {
        /** @var Sign\MobileStatusResult $statusResult */
        $statusResult = $this->client->get(
            new Sign\MobileStatus($result->getToken())
        );

        $this->assertSame(ResultInterface::STATUS_WAITING, $statusResult->getStatus());

        return $result;
    }

    /**
     * @depends testSignStatusWaiting
     * @params Sign\MobileResult $result
     */
    public function testSignStatusOk(Sign\MobileResult $result)
    {
        sleep(TIMEOUT);

        /** @var Isign\Login\MobileStatusResult $result */
        $statusResult = $this->client->get(
            new Sign\MobileStatus($result->getToken())
        );
        $this->assertSame(ResultInterface::STATUS_OK, $statusResult->getStatus());
        $this->assertSame('Signature1', $statusResult->getSignatureId());
        $this->assertNotEmpty($statusResult->getFile());
    }

    /**
     * Test parameters validation on client side
     * @expectedException Isign\Exception\QueryValidator
     * @expectedExceptionMessage Query parameters validation failed
     */
    public function testInvalidParamsHandling()
    {
        /** @var Isign\Sign\MobileResult $result */
        $result = $this->client->get(new Sign\Mobile(
            'pdf',
            '37260000007',
            CODE,
            $this->getDocumentParams()
        ));
    }

    /**
     * Test parameters validation on API by sending invalid personal code
     * @expectedException Isign\Exception\InvalidData
     * @expectedExceptionMessage Data validation failed
     */
    public function testBadRequest()
    {
        /** @var Isign\Sign\MobileResult $result */
        $result = $this->client->get(new Sign\Mobile(
            'pdf',
            PHONE,
            '41001091072',
            $this->getDocumentParams()
        ));
    }

    private function getDocumentParams()
    {
        return [
            'contact' => 'Ponas Testuotojas',
            'reason' => 'Dokumento asirašymas',
            'location' => 'Vilnius',
            'files' => [
                __DIR__.'/../data/document.pdf',
            ]
        ];
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="application_name">Qiitanium DEV</string>
</resources>


text:
package pl.java.scalatech.jms;

import javax.jms.Message;
import javax.jms.MessageListener;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author przodownik
 *         Module name : jmsSpringKata
 *         Creating time : 10:22:23 PM
 */
@Transactional
@Slf4j
public class QueueReceiver implements MessageListener {

    @Autowired
    private Counter counter;

    @Override
    public void onMessage(Message message) {
        log.info("+++   MDB  ----->  receive a message : {}", message);
        counter.getCountMessage().getAndIncrement();
    }

}


text:
Jlink Python Programming GUI Tool
===============

## 1 Introduction
We use Python+Pyside make a GUI programming tool. By calling JLinkARM.Dll, it can access the device via C2 and SWD interface. The EFM8 and EFM32 which are C8051 and ARM cortex M0/M3/M4 core are in the latest Segger JLinkARM.dll support list. It can download hex file, and also binary file with offset setting.

## 2 Preparation
### 2.1 Install Python 2.7 32-bit
The reason for 32-bit python is because many dll file is 32-bit version.

Goto https://www.python.org/downloads/release/python-2712/ and install the python 2.7 32-bit.

And also install enum package

```
$pip install enum
```

### 2.2 Install Pyside
Goto https://info.qt.io/download-qt-for-application-development, install QT creator.

using following command to convert .ui file into .py file.
$ pyside-uic mainwindow.ui -o mainwindow.py

### 2.3 Pyside API
All Pyside API can be found in http://pyside.github.io/docs/pyside/ It is very good place for Pyside brand new developer.

![PySide Doc][PySide_doc]

### 2.4 Install Pycharm
Goto http://www.jetbrains.com/pycharm/download/, download community version.

![PyCharm][PyCharm]

It is an awesome Python development IDE.

### 2.5 Get JlinkARM.Dll
The JLinkARM.dll is the key file to access EFM8 and EFM32 through on board segger Jlink controller in Silicon Labs STK board.

Goto https://www.segger.com/downloads/jlink/, download latest J-link Software and Documentation Pack.

![Segger jlink download][Segger_jlink_download]

After installation, the JLinkARM.dll can be found in following path:
C:\Program Files (x86)\SEGGER\JLink_V618c\JLinkARM.dll

## 3 Guide on Coding
Now we need to know elements that the programming tool required. It requires a GUI frame mainwindow.py for what the tools looks like; JlinkARM.dll for communication with device; main control routine programmer.py; jlink.py take response on communication between main control routine and JLinkARM.dll.

### 3.1 GUI frame
Here is the final view of the programmer tool

![Programmer view][Programmer]

It is convenient to make a GUI frame using PySide.
The GUI contains Window Title, Menu, Status Bar and Central Widget.

#### 3.1.1 Window Title
Define Window Title and Fixed size.

```python
self.setWindowTitle("PyProgrammer")
self.setFixedSize(640, 260)
```

#### 3.1.2 Menu
Create Help Menu and About dialog.

```python
def createMenu(self):
    self.aboutAct = QtGui.QAction("&About", self,
            statusTip="Show the PyProgrammer's About box",
            triggered=self.about)
    self.helpMenu = self.menuBar().addMenu("&Help")
    self.helpMenu.addAction(self.aboutAct)

def about(self):
    QtGui.QMessageBox.about(self, "About PyProgrammer",
            "Copyright Silicon Laboratories, Inc 2018. All rights reserved.\n\n\r"
            "PyProgrammer v1.0 is based on Qt Pyside and SEGGER JlinkARM.\n\n\r"
            "The PyProgrammer example demonstrates how to write a "
            "modern GUI flash programmer applications using Qt Pyside.\n\n\r"
            "This program uses third party libraries covered by the LGPL.\n\r"
            "See the file LGPL.txt for details.")
```

#### 3.1.3 Status Bar
Create Status Bar.

```python
def createStatusBar(self):
    self.statusBar().showMessage("Ready")
```

#### 3.1.4 Central Widget
The main layout of Central Widget includes two main groups - "Connection" and "Flash MCU". The "Flash MCU" includes two subgroups - "Browse" and "Flash".

__Main Group Layout__

```python
mainLayout = QtGui.QVBoxLayout(self.centralWidget)
mainLayout.addWidget(self.createConnectGroup())
mainLayout.addWidget(self.createFlashMCUGroup())
self.setLayout(mainLayout)
```

__Sub Group Layout__

```python
    def createFlashMCUGroup(self):
        groupBox = QtGui.QGroupBox("Flash MCU
        ",self.centralWidget)

        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.createBrowseGroup())
        layout.addWidget(self.createFlashGroup())

        groupBox.setLayout(layout)
        return groupBox
```

### 3.2 Main Control
The purpose of the tool is to select a image file, connect to device, flash the image into device, response on any event that pop up with the operation.

#### 3.2.1 Push Button Events
The Pyside provides interface to connect button press event to dedicate function.
The tool has four buttons -  Browse, Connect, Erase and Flash.

```python
self.browseButton.pressed.connect(self.browse_file)
self.connectButton.pressed.connect(self.connect_mcu)
self.flashButton.pressed.connect(self.flash_mcu)
self.eraseButton.pressed.connect(self.erase_mcu)

def browse_file(self):
	...
	return

def connect_mcu(self):
	...
	return

def flash_mcu(self):
	...
	return

def erase_mcu(self):
    ...
    return
```

According above code, the four button pressed event was connected to the dedicate functions. Once user click on the button, it will call the connected function.

#### 3.2.2 File Browser
The QtGui provides QFileDialog.getOpenFileName to browse the image file. User can define the window name, file default location, file extension. etc

```python
def browse_file(self):
    file_name, file_filter = QtGui.QFileDialog.getOpenFileName(
        self, 'Open Download file', "./hex_bin",
        'Intel Hex Files(*.hex);;Binary Files(*.bin);;All Files (*)')
    if file_name:
        self.pathLineEdit.setText(file_name)
    # Set start address editable with bin file only.
    split_name = file_name.split(".")
    if split_name[-1].lower() == "hex":
        self.startAddrLineEdit.setText("00000000")
        self.startAddrLineEdit.setReadOnly(True)
    if split_name[-1].lower() == "bin":
        self.startAddrLineEdit.setReadOnly(False)
    return
```

The above codes open a file dialog, looking for hex, bin and all files.

![Browse file][Browse_file]

Once choose a file, the full path file name displayed in pathLineEdit component.

#### 3.2.3 Adapter and Debug IF list
The Combox is used here for a list of adapter and debug interface.
Adding item into Combox as follows:

```python
# Adding debug interface into Debug IF Combox
self.debugIFCombo.addItems("SWD C2".split())

# Adding new adapter into Adapter Combox list
self.jlinkDeviceCombo.addItem(unicode(adapter.SerialNumber))
```

We set two type of debug interface into combox, use choose which interface to connect to the device. For EFM8, it is C2 interface; for EFM32, it is SWD interface.
Other common usage of Combox as follows:

```python
# Get current selected Combox item.
serial_number = self.debugIFCombo.currentText()

# Checking if any adapter exist by count Combox items.
if self.jlinkDeviceCombo.count() == 0:
    return

# Clear all Combox items.
self.jlinkDeviceCombo.clear()

# Set current Combo index
self.jlinkDeviceCombo.setCurrentIndex(index)
```

#### 3.2.4 Part Number and Status Display
The Label and Status Bar components made for the purpose.

```python
# Show message on status bar
msg = "Please connect to device."
self.statusBar().showMessage(msg)

# Show detect part number on device Label
self.deviceLabel.setText(self._jlink._part_number)
```

#### 3.2.5 Flash Offset Format and Reset MCU Check Box
The QtGui provides CheckBox component can be used as reset MCU check box. And LineEdit has function setInputMask to limit hex number input only.

```python
# Checking if user check to option
if self.resetMCUCheckBox.checkState():
	self._jlink.reset(False)

# Make hex number input only and with initial value 00000000.
self.startAddrLineEdit.setInputMask(">HHHHHHHH; ")
self.startAddrLineEdit.setText("00000000")

```

#### 3.2.6 Scan Adapter Automatic
The dynamic scan adapter is basic requirement of a programmer tool. Using Python QTimer can achieve the purpose.

```python
def scan_adapter(self):
    num_adapters, adapter_list = self._jlink.get_usb_adapter_list()
    ...
    return

def init_timer(self):
    self.timer = QtCore.QTimer(self)
    self.timer.timeout.connect(self.scan_adapter)
    self.timer.start(1000)
```

### 3.3 JLink function
In order to communicate with STK on board Segger JLink controller, the Python script needs to talk with JLinkARM.DLL, and the JLinkARM.DLL pass the command to the STK JLink controller.

The Jlink.py act as interpret layer between JLinkARM.DLL and Main Control routine.
There are several useful interface functions used in this programmer tool.

```python
# Loading JLinkARM.DLL
self._jlink = jlink.JLinkDll()

# Connect jLink device with serial_number, debug interface ifc
result = self._jlink.connect(long(serial_number), None, ifc)

# Close JLink connection
self._jlink.close()

# Erase device and download file into device
self._jlink.erase_chip()
self._jlink.download(file_name, offset)

# Reset the device
self._jlink.reset(False)

# Get attached USB adapter list
num_adapters, adapter_list = self._jlink.get_usb_adapter_list()

```

[Segger_jlink_download]:img/segger-jlink-download.png
[PyCharm]:img/pycharm.png
[PySide_doc]:img/pyside-doc.png
[Programmer]:img/programmer.png
[Browse_file]:img/browse-file.png


text:
import React, {Component, PropTypes} from 'react';
import { Table, Button } from 'react-bootstrap';
import * as _ from 'lodash';
import type from 'type-of';

class Fields extends Component{

  static propTypes = {
    fields: PropTypes.object,
    sourceObject: PropTypes.object,
  };

  render(){
    const { fields, sourceObject } = this.props;
    let keys = [];

    for(let field in fields) {
      keys.push(field);
    };

    let matchedIndentedKeys = [];

    let fieldsOutput = _.map(keys, (key) => {
      // Indent the fields that are nested fields
      let padding = 0;
      let splitKey = key.split('.');
      for(let i = 0; i < (splitKey.length -1)*2; i++) {
        padding += 10;
      }
      let specificField;
      // Get the last part separated by the period
      // FOr example, get 'id' from 'user.test.id'
      specificField = splitKey[splitKey.length - 1].replace('[]','');
      let indentedKey = {specificField};

      let typeOutput;
      // For arrays, we'll need to parse the key a little differently since it has the
      // [] syntax in the key.
      if(key.endsWith('[]')) {
        typeOutput = type(fields[key]) + '[]';
      } else {
        typeOutput = type(fields[key]);
      }

      // Now we need to generate the descriptions using the source object to
      // do so. It's not clean but works... so far. lol.
      let description = '';
      let source;
      let count = 1;
      let required;
      for(let i of key.split('.')){
        if(description === '') {
          source = sourceObject;
        } else {
          source = description;
        }

        if(count === key.split('.').length) {
          i = i.replace('[]', []);
          if(source && source[i]){
            if(source[i].optional) {
              required = <Button bsSize="xsmall">optional</Button>;
            }

            if(source[i].description) {
              description = source[i].description;
            } else {
              description = '';
            }

            // Override the inferred type if one is specified
            if(source[i].type) {
              typeOutput = source[i].type;
            }
          }
        } else {
          let subject;

          if(_.endsWith(i, '[]')) {
            subject = source[i.replace('[]', '')];
          } else {
            subject = source[i];
          }

          if(subject) {
            if(_.isFunction(subject.example)) {
              description = subject.example();
            } else {
              description = subject.example;
            }

            if(_.endsWith(i, '[]')) {
              description = description[0];
            }
          }
        }
        count++;
      }

      let descriptionOutput;
      if(description) {
        descriptionOutput = (

        );
      }

      // We use this to make sure array items don't appear twice in the fields.
      // We convert x[].0.name and x[].1.name to x[].x.name to make sure that they
      // are treated as the same item
      let match = key.replace(/\[\]\.\d*\./g,'[].x.');
      if(_.includes(matchedIndentedKeys, match) === false) {
        matchedIndentedKeys.push(match);
        return (

            {indentedKey}
            {typeOutput} {required}
            {descriptionOutput}

        );
      } else {

        return null;
      }
    });

    return (

            Field
            Type
            Description

          {fieldsOutput}

    );
  }
};
export default Fields;