text:
<?php
if (!defined('__TYPECHO_ROOT_DIR__')) exit;

/**
 * 全局选项组件
 *
 * @link typecho
 * @package Widget
 * @copyright Copyright (c) 2008 Typecho team (http://www.typecho.org)
 * @license GNU General Public License 2.0
 */
class Widget_Abstract_Options extends Widget_Abstract
{
    /**
     * 以checkbox选项判断是否某个值被启用
     *
     * @access protected
     * @param mixed $settings 选项集合
     * @param string $name 选项名称
     * @return integer
     */
    protected function isEnableByCheckbox($settings, $name)
    {
        return is_array($settings) && in_array($name, $settings) ? 1 : 0;
    }

    /**
     * 获取原始查询对象
     *
     * @access public
     * @return Typecho_Db_Query
     */
    public function select()
    {
        return $this->db->select()->from('table.options');
    }

    /**
     * 插入一条记录
     *
     * @access public
     * @param array $options 记录插入值
     * @return integer
     */
    public function insert(array $options)
    {
        return $this->db->query($this->db->insert('table.options')->rows($options));
    }

    /**
     * 更新记录
     *
     * @access public
     * @param array $options 记录更新值
     * @param Typecho_Db_Query $condition 更新条件
     * @return integer
     */
    public function update(array $options, Typecho_Db_Query $condition)
    {
        return $this->db->query($condition->update('table.options')->rows($options));
    }

    /**
     * 删除记录
     *
     * @access public
     * @param Typecho_Db_Query $condition 删除条件
     * @return integer
     */
    public function delete(Typecho_Db_Query $condition)
    {
        return $this->db->query($condition->delete('table.options'));
    }

    /**
     * 获取记录总数
     *
     * @access public
     * @param Typecho_Db_Query $condition 计算条件
     * @return integer
     */
    public function size(Typecho_Db_Query $condition)
    {
        return $this->db->fetchObject($condition->select(array('COUNT(name)' => 'num'))->from('table.options'))->num;
    }
}


text:
from __future__ import unicode_literals
import frappe, json
from frappe.model.document import Document

class Language(Document):
	pass

def export_languages_json():
	'''Export list of all languages'''
	languages = frappe.db.get_all('Language', fields=['name', 'language_name'])
	languages = [{'name': d.language_name, 'code': d.name} for d in languages]

	languages.sort(key = lambda a: a['code'])

	with open(frappe.get_app_path('frappe', 'geo', 'languages.json'), 'w') as f:
		f.write(frappe.as_json(languages))

def sync_languages():
	'''Sync frappe/geo/languages.json with Language'''
	with open(frappe.get_app_path('frappe', 'geo', 'languages.json'), 'r') as f:
		data = json.loads(f.read())

	for l in data:
		if not frappe.db.exists('Language', l['code']):
			frappe.get_doc({
				'doctype': 'Language',
				'language_code': l['code'],
				'language_name': l['name']
			}).insert()

def update_language_names():
	'''Update frappe/geo/languages.json names (for use via patch)'''
	with open(frappe.get_app_path('frappe', 'geo', 'languages.json'), 'r') as f:
		data = json.loads(f.read())

	for l in data:
		frappe.db.set_value('Language', l['code'], 'language_name', l['name'])

redpajama_set_name: RedPajamaGithub


text:
/*
 *
 * ExchangePage reducer
 *
 */

import {
  MARKET_INFO_RECEIVED,
  MARKET_CHANGED,
  MARKET_INFO_CHANGED
} from "containers/App/constants";
import {
  normalize,
  getPrimaryCurrency,
  getSecondaryCurrency
} from "utils/general";
import update from "react-addons-update";
import { pprint } from "../../utils/general";

const initialState = {
  marketInfo: null,
  marketInfoLoaded: false,
  to_currency: null
};

function transform(info) {
  var data = {};

  pprint(info);

  let pc = getPrimaryCurrency(info.pair);
  let sc = getSecondaryCurrency(info.pair);

  data[pc] = data[pc] || {};
  data[pc][sc] = data[pc][sc] || {};

  for (var key in info) {
    var value = info[key];

    if (key == "volume_24h") {
      value = normalize(value)
    } else if (key == "rate") {
      value = normalize(value)
    }

    data[pc][sc][key] = value;
  }
  return data;
}

function marketInfoReducer(state = initialState, action) {
  switch (action.type) {
    case MARKET_INFO_CHANGED:
    case MARKET_INFO_RECEIVED:
    {

      let info = transform(action.marketInfo);
      let newMarketInfo = state.marketInfo || {};

      for (let pc in info) {
        for (let sc in info[pc]) {
          if (newMarketInfo[pc]) {
            newMarketInfo = update(newMarketInfo,
              {
                [pc]: {
                  $merge: {
                    [sc]: info[pc][sc]
                  }
                }
              });
          } else {
            newMarketInfo = update(newMarketInfo,
              {
                [pc]: {
                  $set: {
                    [sc]: info[pc][sc]
                  }
                }
              });
          }

        }
      }

      return Object.assign({}, state,
        {
          marketInfoLoaded: true,
          marketInfo: newMarketInfo
        });
    }

    case MARKET_CHANGED:
      return Object.assign({}, state,
        {
          marketInfo: null,
          marketInfoLoaded: false,
          to_currency: action.to_currency
        });

    default:
      return state;
  }
}

export default marketInfoReducer;


text:
require 'pedant/rspec/cookbook_util'

describe "Cookbook Versions API endpoint, GET", :cookbooks, :cookbooks_version do

  shared_examples "versions cookbooks" do |api_version|
    let(:cookbook_url_base) { "cookbooks" }
    let(:api_version) { api_version }

    before do
      platform.server_api_version = api_version
    end

    after do
      platform.reset_server_api_version
    end

    let(:segment_type) do
      if api_version.to_i < 2
        "files"
      else
        "all_files"
      end
    end

    include Pedant::RSpec::CookbookUtil

    let(:request_method) { :GET }
    let(:request_url)    { named_cookbook_url }
    let(:requestor)      { admin_user }

    let(:non_existent_cookbook){ "fakecookbook" }
    let(:fake_version){ "1.0.0" }
    let(:latest_cookbook_version_url) { api_url("/#{cookbook_url_base}/#{cookbook_name}/_latest") }

    let(:fetch_cookbook_version_success_response) do
      {
        :status => 200,
        :body => retrieved_cookbook(cookbook_name, cookbook_version)
      }
    end
    let(:cookbook_version_not_found_exact_response) do
      {
        :status => 404,
        :body_exact => { "error" => ["Cannot find a cookbook named #{cookbook_name} with version #{cookbook_version}"] }
      }
    end

    context "with no cookbooks on the server" do
      let(:expected_response) { cookbook_version_not_found_exact_response }
      let(:cookbook_name) { non_existent_cookbook }
      let(:cookbook_version) { fake_version }

      should_respond_with 404
    end # with no cookbooks on the server

    context "with cookbooks on the server" do

      let(:cookbook_name) { existing_cookbook_name }
      let(:cookbook_version) { existing_cookbook_version }
      let(:existing_cookbook_name){ "the_art_of_french_cooking" }
      let(:existing_cookbook_version){ "1.0.0" }
      let(:latest){ "1.0.1" }

      before :each do
        make_cookbook(admin_user, existing_cookbook_name, existing_cookbook_version)
        # Erchef doesn't handle multipe versions yet
        make_cookbook(admin_user, existing_cookbook_name, latest)
      end

      after :each do
        delete_cookbook(admin_user, existing_cookbook_name, existing_cookbook_version)
        delete_cookbook(admin_user, existing_cookbook_name, latest)
      end

      context 'when fetching existing version of cookbook' do
        let(:expected_response) { fetch_cookbook_version_success_response }

        should_respond_with 200, 'and the cookbook version'
      end

      context 'when fetching non-existant version of cookbook' do
        let(:expected_response) { cookbook_version_not_found_exact_response }
        let(:cookbook_version) { '6.6.6' }

        should_respond_with 404
      end

      context 'as a non-admin user' do
        let(:expected_response) { fetch_cookbook_version_success_response }
        let(:requestor) { normal_user }

        should_respond_with 200, 'and the cookbook version'
      end

      context 'as a user outside the organization', :authorization do
        let(:expected_response) { unauthorized_access_credential_response }
        let(:requestor) { outside_user }

        should_respond_with 403
      end

      context "when requesting the 'latest' Cookbook version", :smoke do
        let(:expected_response) { fetch_cookbook_version_success_response }
        let(:request_url) { latest_cookbook_version_url }
        let(:cookbook_version) { latest }

        should_respond_with 200, 'and the latest cookbook version'
      end # when requesting the 'latest' cookbook version

      context "when requesting the 'latest' version of a non-existent cookbook" do
        let(:expected_response) { cookbook_version_not_found_exact_response }
        let(:cookbook_name) { non_existent_cookbook }
        let(:cookbook_version) { '_latest' }

        should_respond_with 404
      end # when requesting the 'latest' version of a non-existent cookbook
    end # with existing cookbook
  end

  describe "API v0" do
    it_behaves_like "versions cookbooks", 0
  end

  describe "API v2" do
    it_behaves_like "versions cookbooks", 2
  end
end


text:
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title></title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="apple-touch-icon" href="apple-touch-icon.png">

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

    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">

Home

About

Design

Element

Layout

Contact


text:
<?php

namespace app\controllers;
use app\models\customer\CustomerRecord;
use app\models\customer\PhoneRecord;
use app\models\Customer;
use app\models\Phone;
use yii\data\ArrayDataProvider;
use yii\web\Controller;
use yii\helpers\ArrayHelper ;

class CustomerController extends Controller
{
    public function actionIndex()
    {
        $records = $this->findRecordsByQuery() ;
        echo "
" ;
        print_r($records) ;
        echo "
" ;

        return $this->render('index', compact('records') ) ;
//        return $this->render('index', ['records' => $records]) ;
    }

    private function store(Customer $customer)
    {
        $customer_record = new CustomerRecord() ;
        $customer_record->name = $customer->name ;
        $customer_record->birth_date = $customer->birth_date->format('Y-m-d') ;
        $customer_record->notes = $customer->notes ;

        $customer_record->save() ;

        foreach($customer->phones as $phone)
        {
            $phone_record = new PhoneRecord() ;
            $phone_record->number = $phone->number ;
            $phone_record->customer_id = $customer_record->id ;
            $phone_record->save() ;
        }
    }

    private function makeCustomer(CustomerRecord $customer_record, PhoneRecord $phone_record)
    {
        $name = $customer_record->name ;
        $birth_date = new \DateTime($customer_record->birth_date) ;

        $customer = new Customer($name, $birth_date) ;
        $customer->notes = $customer_record->notes ;
        $customer->phones[] = new Phone($phone_record->number) ;

        return $customer ;
    }

    private function load(CustomerRecord $customer, PhoneRecord $phone, array $post)
    {
        return $customer->load($post)
            and $phone->load($post)
            and $customer->validate()
            and $phone->validate(['number']) ;

    }

    public function actionAdd()
    {
        $customer = new CustomerRecord() ;
        $phone = new PhoneRecord() ;

        if($this->load($customer, $phone, $_POST))
        {
            $this->store($this->makeCustomer($customer, $phone)) ;
            return $this->redirect(\Yii::$app->request->baseUrl . '/customer/') ;
        }
        // stateful magic: both $customer and $phone will be validated at this point

        return $this->render('add', compact('customer' , 'phone')) ;
    }

    private function findRecordsByQuery()
    {
        $number = \Yii::$app->request->get('phone_number') ;
        $records = $this->getRecordsByPhoneNumber($number) ;
        $dataProvider = $this->wrapIntoDataProvider($records) ;
        return $dataProvider ;
    }

    private function getRecordsByPhoneNumber($number)
    {
        $phone_record = PhoneRecord::findOne(['number' => $number]) ;
        if(!$phone_record)
            return [] ;

        $customer_record = CustomerRecord::findOne($phone_record->customer_id);
        if(!$customer_record)
            return [] ;

        return [$this->makeCustomer($customer_record, $phone_record)] ;
    }

    private function wrapIntoDataProvider($data)
    {
//        echo 'asdfwaegbawsegaweg' . '
';

        return new ArrayDataProvider([
            'allModels' => $data,
            'pagination' => false
        ]) ;

//        return ArrayHelper::map($data, 'name', 'birth_date') ;
    }

    public function actionQuery()
    {
        return $this->render('query');
    }

}


text:
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;

namespace FurryRun.Editor.Adorners
{
    public class MoveThumb : Thumb
    {
        private RotateTransform rotateTransform;
        private ContentControl designerItem;

        public MoveThumb()
        {
            DragStarted += new DragStartedEventHandler(this.MoveThumb_DragStarted);
            DragDelta += new DragDeltaEventHandler(this.MoveThumb_DragDelta);
        }

        private void MoveThumb_DragStarted(object sender, DragStartedEventArgs e)
        {
            this.designerItem = DataContext as ContentControl;

            if (this.designerItem != null)
            {
                this.rotateTransform = this.designerItem.RenderTransform as RotateTransform;
            }
        }

        private void MoveThumb_DragDelta(object sender, DragDeltaEventArgs e)
        {
            if (this.designerItem != null)
            {
                Point dragDelta = new Point(e.HorizontalChange, e.VerticalChange);

                if (this.rotateTransform != null)
                {
                    dragDelta = this.rotateTransform.Transform(dragDelta);
                }

                var left = this.designerItem.Margin.Left + dragDelta.X;
                var top = this.designerItem.Margin.Top + dragDelta.Y;
                this.designerItem.Margin = new Thickness(left, top, designerItem.Margin.Right, designerItem.Margin.Bottom);
                //Canvas.SetLeft(this.designerItem, Canvas.GetLeft(this.designerItem) + dragDelta.X);
                //Canvas.SetTop(this.designerItem, Canvas.GetTop(this.designerItem) + dragDelta.Y);
            }
        }
    }
}


text:
import sinon = require('sinon');
import should = require('should');
require('should-sinon');

import { throttledRetrier } from '../../src/utils/throttledRetrier';

describe('Throttled retrier', () => {
  it('Runs function only once in base success case', async () => {
    const stub = sinon.stub().resolves('BLAH');
    const f = throttledRetrier(stub, { disableErrorLogging: true });
    const v = await f();
    stub.calledOnce.should.be.True();
    v.should.be.eql('BLAH');
  });

  it('Runs function 5 times in base failure case', async () => {
    const stub = sinon.stub().rejects(new Error());
    const f = throttledRetrier(stub, {
      disableErrorLogging: true,
      sleepAmountFunction: attemptNumber => 10 * attemptNumber,
    });
    let error = null;
    let v = null;
    try {
      v = await f();
    } catch (e) {
      error = e;
    }
    stub.callCount.should.be.eql(5);
    should.not.exist(v);
    should.exist(error);
  });

  it('Function honors retry count', async () => {
    const stub = sinon.stub().rejects(new Error());
    const f = throttledRetrier(stub, {
      disableErrorLogging: true,
      maxNumberOfTries: 2,
      sleepAmountFunction: attemptNumber => 10 * attemptNumber,
    });
    let error = null;
    let v = null;
    try {
      v = await f();
    } catch (e) {
      error = e;
    }
    stub.callCount.should.be.eql(2);
    should.not.exist(v);
    should.exist(error);
  });

  it('Function rejects bad retry counts', async () => {
    const stub = sinon.stub().resolves('BLAH');
    const f = throttledRetrier(stub, {
      disableErrorLogging: true,
      maxNumberOfTries: -5,
    });
    let error = null;
    let v = null;
    try {
      v = await f();
    } catch (e) {
      error = e;
    }
    stub.callCount.should.be.eql(0);
    should.not.exist(v);
    should.exist(error);
  });

  it('Runs function until success', async () => {
    const stub = sinon.stub();
    stub.onCall(0).rejects(new Error());
    stub.onCall(1).resolves('BLAH2');
    const f = throttledRetrier(stub, {
      disableErrorLogging: true,
      sleepAmountFunction: attemptNumber => 10 * attemptNumber,
    });
    const v = await f();
    stub.calledTwice.should.be.True();
    v.should.be.eql('BLAH2');
  });

  it('Stops immediately on non-retryable error', async () => {
    const stub = sinon.stub();
    stub.onCall(0).rejects(new Error());
    stub.onCall(1).resolves('BLAH2');
    const f = throttledRetrier(stub, {
      disableErrorLogging: true,
      sleepAmountFunction: attemptNumber => 10 * attemptNumber,
      isErrorRetryableFunc: () => false,
    });
    let v;
    let error;
    try {
      v = await f();
    } catch (e) {
      error = e;
    }
    stub.calledOnce.should.be.True();
    should.exist(error);
    should.not.exist(v);
  });
});


text:
function Resource($http) {
  return function (path, methods) {
    var resource = {};

    if (methods.indexOf('index') !== -1) {
      resource.index = function (success, error) {
        var request = $http.get(path);
        if (success) request.success(success);
        if (error) request.error(error);
        return request;
      };
    }

    if (methods.indexOf('create') !== -1) {
      resource.create = function (data, success, error) {
        var request = $http.post(path, data);
        if (success) request.success(success);
        if (error) request.error(error);
        return request;
      };
    }

    return resource;
  };
}

function Notification(Resource) {
  return Resource('/notifications.json', ['index']);
}

function Message(Resource) {
  return Resource('/messages.json', ['index', 'create']);
}

function NotificationListCtrl($scope, Notification) {
  $scope.toggleNotifications = function () {
    if ($scope.notifications) {
      $scope.notifications = null;
    } else {
      Notification.index(function (notifications) {
          $scope.notifications = notifications;
      });
    }
  };
}

function MessageCtrl($scope, Message) {
  $scope.message = {};

  Message.index(function (messages) {
    $scope.messages = messages;
  });

  $scope.postMessage = function () {
    var data = angular.copy($scope.message);
    Message.create(data, function (message) {
      $scope.message = {};
      $scope.messages.unshift(message);
    });
  };
}

angular.module('sample', [])
    .service('Resource', Resource)
    .service('Notification', Notification)
    .service('Message', Message)
    .controller('NotificationListCtrl', NotificationListCtrl)
    .controller('MessageCtrl', MessageCtrl);


text:
.. _encryption:

Encryption
==========

Encrypting and decrypting
-------------------------

If you don't choose to encrypt your file when you run `jrnl` for the first time, you can encrypt your existing journal file or change its password using ::

    jrnl --encrypt

If it is already encrypted, you will first be asked for the current password. You can then enter a new password and your plain journal will replaced by the encrypted file. Conversely, ::

    jrnl --decrypt

will replace your encrypted journal file by a Journal in plain text. You can also specify a filename, ie. ``jrnl --decrypt plain_text_copy.txt``, to leave your original file untouched.

Storing passwords in your keychain
----------------------------------

Whenever you encrypt your journal, you are asked whether you want to store the encryption password in your keychain. If you do this, you won't have to enter your password every time you want to write or read your journal.

If you don't initially store the password in the keychain but decide to do so at a later point -- or maybe want to store it on one computer but not on another -- you can simply run ``jrnl --encrypt`` on an encrypted journal and use the same password again.

A note on security
------------------

While jrnl follows best practises, true security is an illusion. Specifically, jrnl will leave traces in your memory and your shell history -- it's meant to keep journals secure in transit, for example when storing it on an `untrusted <http://techcrunch.com/2014/04/09/condoleezza-rice-joins-dropboxs-board/>`_ services such as Dropbox. If you're concerned about security, disable history logging for journal in your ``.bashrc`` ::

    HISTIGNORE="jrnl *"

If you are using zsh instead of bash, you can get the same behaviour adding this to your ``zshrc`` ::

    setopt HIST_IGNORE_SPACE
    alias jrnl=" jrnl"

Manual decryption
-----------------

Should you ever want to decrypt your journal manually, you can do so with any program that supports the AES algorithm in CBC. The key used for encryption is the SHA-256-hash of your password, the IV (initialisation vector) is stored in the first 16 bytes of the encrypted file. The plain text is encoded in UTF-8 and padded according to PKCS#7 before being encrypted. So, to decrypt a journal file in python, run::

    import hashlib, Crypto.Cipher
    key = hashlib.sha256(my_password).digest()
    with open("my_journal.txt") as f:
        cipher = f.read()
        crypto = AES.new(key, AES.MODE_CBC, iv = cipher[:16])
        plain = crypto.decrypt(cipher[16:])
        plain = plain.strip(plain[-1])
        plain = plain.decode("utf-8")


text:
<?php

final class PhabricatorConfigEditor
  extends PhabricatorApplicationTransactionEditor {

  public function getTransactionTypes() {
    $types = parent::getTransactionTypes();

    $types[] = PhabricatorConfigTransaction::TYPE_EDIT;

    return $types;
  }

  protected function getCustomTransactionOldValue(
    PhabricatorLiskDAO $object,
    PhabricatorApplicationTransaction $xaction) {

    switch ($xaction->getTransactionType()) {
      case PhabricatorConfigTransaction::TYPE_EDIT:
        return array(
          'deleted' => (int)$object->getIsDeleted(),
          'value'   => $object->getValue(),
        );
    }
  }

  protected function getCustomTransactionNewValue(
    PhabricatorLiskDAO $object,
    PhabricatorApplicationTransaction $xaction) {

    switch ($xaction->getTransactionType()) {
      case PhabricatorConfigTransaction::TYPE_EDIT:
        return $xaction->getNewValue();
    }
  }

  protected function applyCustomInternalTransaction(
    PhabricatorLiskDAO $object,
    PhabricatorApplicationTransaction $xaction) {

    switch ($xaction->getTransactionType()) {
      case PhabricatorConfigTransaction::TYPE_EDIT:
        $v = $xaction->getNewValue();

        // If this is a defined configuration option (vs a straggler from an
        // old version of Phabricator or a configuration file misspelling)
        // submit it to the validation gauntlet.
        $key = $object->getConfigKey();
        $all_options = PhabricatorApplicationConfigOptions::loadAllOptions();
        $option = idx($all_options, $key);
        if ($option) {
          $option->getGroup()->validateOption(
            $option,
            $v['value']);
        }

        $object->setIsDeleted((int)$v['deleted']);
        $object->setValue($v['value']);
        break;
    }
  }

  protected function applyCustomExternalTransaction(
    PhabricatorLiskDAO $object,
    PhabricatorApplicationTransaction $xaction) {
    return;
  }

  protected function mergeTransactions(
    PhabricatorApplicationTransaction $u,
    PhabricatorApplicationTransaction $v) {

    $type = $u->getTransactionType();
    switch ($type) {
      case PhabricatorConfigTransaction::TYPE_EDIT:
        return $v;
    }

    return parent::mergeTransactions($u, $v);
  }

  protected function transactionHasEffect(
    PhabricatorLiskDAO $object,
    PhabricatorApplicationTransaction $xaction) {

    $old = $xaction->getOldValue();
    $new = $xaction->getNewValue();

    $type = $xaction->getTransactionType();
    switch ($type) {
      case PhabricatorConfigTransaction::TYPE_EDIT:
        // If an edit deletes an already-deleted entry, no-op it.
        if (idx($old, 'deleted') && idx($new, 'deleted')) {
          return false;
        }
        break;
    }

    return parent::transactionHasEffect($object, $xaction);
  }

  protected function didApplyTransactions(array $xactions) {
    // Force all the setup checks to run on the next page load.
    PhabricatorSetupCheck::deleteSetupCheckCache();
  }

  public static function storeNewValue(
   PhabricatorConfigEntry $config_entry, $value, AphrontRequest $request) {
    $xaction = id(new PhabricatorConfigTransaction())
              ->setTransactionType(PhabricatorConfigTransaction::TYPE_EDIT)
              ->setNewValue(
                array(
                   'deleted' => false,
                   'value' => $value
                ));

    $editor = id(new PhabricatorConfigEditor())
           ->setActor($request->getUser())
           ->setContinueOnNoEffect(true)
           ->setContentSourceFromRequest($request);

    $editor->applyTransactions($config_entry, array($xaction));
  }

}


text:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;

using DigitalPlatform.GUI;
using DigitalPlatform.Core;

namespace DigitalPlatform.Script
{
    /// <summary>
    /// 管理一个 Project 的对话框
    /// </summary>
    public class OneProjectDialog : System.Windows.Forms.Form
    {
        public string HostName = "";
        public ScriptManager scriptManager = null;
        bool m_bNew = false;

        public string strTempLocate = "";

        public string ResultProjectNamePath = "";
        public string ResultLocate = "";
        //public string[] ResultRefs = null;

        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.TextBox textBox_projectName;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Button button_Cancel;
        private System.Windows.Forms.Button button_OK;
        private System.Windows.Forms.Label label5;
        private DigitalPlatform.GUI.ListViewNF listView_files;
        private System.Windows.Forms.ColumnHeader columnHeader_fileName;
        private System.Windows.Forms.ColumnHeader columnHeader_comment;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.TextBox textBox_projectPathOfName;
        private System.Windows.Forms.TextBox textBox_projectLocate;
        private System.Windows.Forms.Button button_editFile;
        private System.Windows.Forms.Button button_newFile;
        private System.Windows.Forms.Button button_deleteFile;
        private System.Windows.Forms.Button button_changeProjectLocation;
        private System.Windows.Forms.Button button_changeProjectName;
        private System.Windows.Forms.CheckBox checkBox_displayTempFile;
        private Button button_openProjectFolder;
        private Button button_openInCode;
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.Container components = null;

        public OneProjectDialog()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            //
            // TODO: Add any constructor code after InitializeComponent call
            //
        }

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(OneProjectDialog));
            this.label1 = new System.Windows.Forms.Label();
            this.textBox_projectName = new System.Windows.Forms.TextBox();
            this.label2 = new System.Windows.Forms.Label();
            this.button_Cancel = new System.Windows.Forms.Button();
            this.button_OK = new System.Windows.Forms.Button();
            this.textBox_projectPathOfName = new System.Windows.Forms.TextBox();
            this.label5 = new System.Windows.Forms.Label();
            this.listView_files = new DigitalPlatform.GUI.ListViewNF();
            this.columnHeader_fileName = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
            this.columnHeader_comment = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
            this.textBox_projectLocate = new System.Windows.Forms.TextBox();
            this.label3 = new System.Windows.Forms.Label();
            this.button_editFile = new System.Windows.Forms.Button();
            this.button_newFile = new System.Windows.Forms.Button();
            this.button_deleteFile = new System.Windows.Forms.Button();
            this.button_changeProjectLocation = new System.Windows.Forms.Button();
            this.button_changeProjectName = new System.Windows.Forms.Button();
            this.checkBox_displayTempFile = new System.Windows.Forms.CheckBox();
            this.button_openProjectFolder = new System.Windows.Forms.Button();
            this.button_openInCode = new System.Windows.Forms.Button();
            this.SuspendLayout();
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(7, 12);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(47, 12);
            this.label1.TabIndex = 0;
            this.label1.Text = "方案名:";
            //
            // textBox_projectName
            //
            this.textBox_projectName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));
            this.textBox_projectName.Location = new System.Drawing.Point(121, 9);
            this.textBox_projectName.Name = "textBox_projectName";
            this.textBox_projectName.ReadOnly = true;
            this.textBox_projectName.Size = new System.Drawing.Size(282, 21);
            this.textBox_projectName.TabIndex = 1;
            //
            // label2
            //
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(9, 124);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(59, 12);
            this.label2.TabIndex = 10;
            this.label2.Text = "构成文件:";
            //
            // button_Cancel
            //
            this.button_Cancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this.button_Cancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.button_Cancel.Location = new System.Drawing.Point(408, 322);
            this.button_Cancel.Name = "button_Cancel";
            this.button_Cancel.Size = new System.Drawing.Size(74, 22);
            this.button_Cancel.TabIndex = 17;
            this.button_Cancel.Text = "取消";
            this.button_Cancel.Click += new System.EventHandler(this.button_Cancel_Click);
            //
            // button_OK
            //
            this.button_OK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this.button_OK.DialogResult = System.Windows.Forms.DialogResult.OK;
            this.button_OK.Location = new System.Drawing.Point(328, 322);
            this.button_OK.Name = "button_OK";
            this.button_OK.Size = new System.Drawing.Size(75, 22);
            this.button_OK.TabIndex = 16;
            this.button_OK.Text = "确定";
            this.button_OK.Click += new System.EventHandler(this.button_OK_Click);
            //
            // textBox_projectPathOfName
            //
            this.textBox_projectPathOfName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));
            this.textBox_projectPathOfName.Location = new System.Drawing.Point(121, 33);
            this.textBox_projectPathOfName.Name = "textBox_projectPathOfName";
            this.textBox_projectPathOfName.ReadOnly = true;
            this.textBox_projectPathOfName.Size = new System.Drawing.Size(282, 21);
            this.textBox_projectPathOfName.TabIndex = 4;
            //
            // label5
            //
            this.label5.AutoSize = true;
            this.label5.Location = new System.Drawing.Point(7, 36);
            this.label5.Name = "label5";
            this.label5.Size = new System.Drawing.Size(95, 12);
            this.label5.TabIndex = 3;
            this.label5.Text = "方案名所在位置:";
            //
            // listView_files
            //
            this.listView_files.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
            | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));
            this.listView_files.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
            this.columnHeader_fileName,
            this.columnHeader_comment});
            this.listView_files.FullRowSelect = true;
            this.listView_files.HideSelection = false;
            this.listView_files.Location = new System.Drawing.Point(9, 138);
            this.listView_files.Name = "listView_files";
            this.listView_files.Size = new System.Drawing.Size(394, 179);
            this.listView_files.TabIndex = 11;
            this.listView_files.UseCompatibleStateImageBehavior = false;
            this.listView_files.View = System.Windows.Forms.View.Details;
            this.listView_files.SelectedIndexChanged += new System.EventHandler(this.listView_files_SelectedIndexChanged);
            this.listView_files.DoubleClick += new System.EventHandler(this.listView_files_DoubleClick);
            this.listView_files.MouseUp += new System.Windows.Forms.MouseEventHandler(this.listView_files_MouseUp);
            //
            // columnHeader_fileName
            //
            this.columnHeader_fileName.Text = "文件名";
            this.columnHeader_fileName.Width = 204;
            //
            // columnHeader_comment
            //
            this.columnHeader_comment.Text = "注释";
            this.columnHeader_comment.Width = 288;
            //
            // textBox_projectLocate
            //
            this.textBox_projectLocate.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));
            this.textBox_projectLocate.Location = new System.Drawing.Point(121, 58);
            this.textBox_projectLocate.Name = "textBox_projectLocate";
            this.textBox_projectLocate.ReadOnly = true;
            this.textBox_projectLocate.Size = new System.Drawing.Size(361, 21);
            this.textBox_projectLocate.TabIndex = 6;
            this.textBox_projectLocate.TextChanged += new System.EventHandler(this.textBox_projectLocate_TextChanged);
            //
            // label3
            //
            this.label3.AutoSize = true;
            this.label3.Location = new System.Drawing.Point(7, 60);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(83, 12);
            this.label3.TabIndex = 5;
            this.label3.Text = "方案文件目录:";
            //
            // button_editFile
            //
            this.button_editFile.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.button_editFile.Location = new System.Drawing.Point(408, 138);
            this.button_editFile.Name = "button_editFile";
            this.button_editFile.Size = new System.Drawing.Size(74, 21);
            this.button_editFile.TabIndex = 12;
            this.button_editFile.Text = "编辑(&E)";
            this.button_editFile.Click += new System.EventHandler(this.button_editFile_Click);
            //
            // button_newFile
            //
            this.button_newFile.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.button_newFile.Location = new System.Drawing.Point(408, 164);
            this.button_newFile.Name = "button_newFile";
            this.button_newFile.Size = new System.Drawing.Size(74, 22);
            this.button_newFile.TabIndex = 13;
            this.button_newFile.Text = "新增(&N)";
            this.button_newFile.Click += new System.EventHandler(this.button_newFile_Click);
            //
            // button_deleteFile
            //
            this.button_deleteFile.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.button_deleteFile.Location = new System.Drawing.Point(408, 205);
            this.button_deleteFile.Name = "button_deleteFile";
            this.button_deleteFile.Size = new System.Drawing.Size(74, 22);
            this.button_deleteFile.TabIndex = 14;
            this.button_deleteFile.Text = "删除(&D)";
            this.button_deleteFile.Click += new System.EventHandler(this.button_deleteFile_Click);
            //
            // button_changeProjectLocation
            //
            this.button_changeProjectLocation.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.button_changeProjectLocation.Location = new System.Drawing.Point(408, 82);
            this.button_changeProjectLocation.Name = "button_changeProjectLocation";
            this.button_changeProjectLocation.Size = new System.Drawing.Size(74, 21);
            this.button_changeProjectLocation.TabIndex = 9;
            this.button_changeProjectLocation.Text = "改名(&R)";
            this.button_changeProjectLocation.Click += new System.EventHandler(this.button_changeProjectLocation_Click);
            //
            // button_changeProjectName
            //
            this.button_changeProjectName.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.button_changeProjectName.Location = new System.Drawing.Point(408, 9);
            this.button_changeProjectName.Name = "button_changeProjectName";
            this.button_changeProjectName.Size = new System.Drawing.Size(74, 22);
            this.button_changeProjectName.TabIndex = 2;
            this.button_changeProjectName.Text = "改名(&R)";
            this.button_changeProjectName.Click += new System.EventHandler(this.button_changeProjectName_Click);
            //
            // checkBox_displayTempFile
            //
            this.checkBox_displayTempFile.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
            this.checkBox_displayTempFile.AutoSize = true;
            this.checkBox_displayTempFile.Location = new System.Drawing.Point(9, 328);
            this.checkBox_displayTempFile.Name = "checkBox_displayTempFile";
            this.checkBox_displayTempFile.Size = new System.Drawing.Size(114, 16);
            this.checkBox_displayTempFile.TabIndex = 15;
            this.checkBox_displayTempFile.Text = "显示临时文件(&T)";
            this.checkBox_displayTempFile.CheckedChanged += new System.EventHandler(this.checkBox_displayTempFile_CheckedChanged);
            //
            // button_openProjectFolder
            //
            this.button_openProjectFolder.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.button_openProjectFolder.Location = new System.Drawing.Point(270, 82);
            this.button_openProjectFolder.Name = "button_openProjectFolder";
            this.button_openProjectFolder.Size = new System.Drawing.Size(133, 21);
            this.button_openProjectFolder.TabIndex = 8;
            this.button_openProjectFolder.Text = "打开文件夹(&F)...";
            this.button_openProjectFolder.Click += new System.EventHandler(this.button_openProjectFolder_Click);
            //
            // button_openInCode
            //
            this.button_openInCode.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.button_openInCode.Location = new System.Drawing.Point(121, 82);
            this.button_openInCode.Name = "button_openInCode";
            this.button_openInCode.Size = new System.Drawing.Size(143, 21);
            this.button_openInCode.TabIndex = 7;
            this.button_openInCode.Text = "在 Code 中打开(&C)...";
            this.button_openInCode.Click += new System.EventHandler(this.button_openInCode_Click);
            //
            // OneProjectDialog
            //
            this.AcceptButton = this.button_OK;
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.CancelButton = this.button_Cancel;
            this.ClientSize = new System.Drawing.Size(492, 353);
            this.Controls.Add(this.button_openInCode);
            this.Controls.Add(this.button_openProjectFolder);
            this.Controls.Add(this.checkBox_displayTempFile);
            this.Controls.Add(this.button_changeProjectName);
            this.Controls.Add(this.button_changeProjectLocation);
            this.Controls.Add(this.button_deleteFile);
            this.Controls.Add(this.button_newFile);
            this.Controls.Add(this.button_editFile);
            this.Controls.Add(this.textBox_projectLocate);
            this.Controls.Add(this.textBox_projectPathOfName);
            this.Controls.Add(this.textBox_projectName);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.listView_files);
            this.Controls.Add(this.label5);
            this.Controls.Add(this.button_Cancel);
            this.Controls.Add(this.button_OK);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.Name = "OneProjectDialog";
            this.ShowInTaskbar = false;
            this.Text = "脚本代码管理";
            this.Closing += new System.ComponentModel.CancelEventHandler(this.ScriptDlg_Closing);
            this.Closed += new System.EventHandler(this.ScriptDlg_Closed);
            this.Load += new System.EventHandler(this.ScriptDlg_Load);
            this.ResumeLayout(false);
            this.PerformLayout();

        }
        #endregion

        private void ScriptDlg_Load(object sender, System.EventArgs e)
        {
            // textBox_scriptCode.Font = new Font("Courier New",9);
            listView_files_SelectedIndexChanged(null, null);

        }

        private void button_OK_Click(object sender, System.EventArgs e)
        {
            if (textBox_projectName.Text == "")
            {
                MessageBox.Show("尚未指定方案名");
                return;
            }

            // 方案名 + 路径
            ResultProjectNamePath = textBox_projectPathOfName.Text;

            if (ResultProjectNamePath != "")
                ResultProjectNamePath += "/";

            ResultProjectNamePath += textBox_projectName.Text;

            ResultLocate = textBox_projectLocate.Text;
            // 避免有用目录和文件被OnClosed()自动删除
            this.strTempLocate = "";

            /*
            // 源代码文件名
            ResultCodeFileName = textBox_codeFileName.Text;

            // refs
            string strTemp = textBox_refs.Text;
            strTemp = strTemp.Replace("\r\n", ",");	// 注意去掉空行?
            ResultRefs = strTemp.Split(new Char [] {','});

            // 避免有用文件被OnClosed()自动删除
            this.strTempCodeFileName = "";
            */

            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        private void button_Cancel_Click(object sender, System.EventArgs e)
        {
            this.Close();
            this.DialogResult = DialogResult.Cancel;
        }

        // 初始化参数
        public void Initial(string strProjectNamePath,
            string strLocate)
        {
            // 析出路径和名

            /*
            int nRet = strProjectNamePath.LastIndexOf("/");
            if (nRet == -1)
            {
                this.textBox_projectName.Text = strProjectNamePath;
                this.textBox_projectPathOfName.Text = "";
            }
            else
            {
                this.textBox_projectName.Text = strProjectNamePath.Substring(nRet+1);
                this.textBox_projectPathOfName.Text = strProjectNamePath.Substring(0,nRet);
            }
            */
            string strPath;
            string strName;
            ScriptManager.SplitProjectPathName(strProjectNamePath,
                out strPath,
                out strName);

            this.textBox_projectName.Text = strName;
            this.textBox_projectPathOfName.Text = strPath;

            // 文件目录
            textBox_projectLocate.Text = strLocate;

            LoadFileInfo();

            /*
            // refs
            //string[] aName = strList.Split(new Char [] {','});
            // 每行一个ref事项
            textBox_refs.Text = "";
            for(int i=0;i<refs.Length;i++)
            {
                if (textBox_refs.Text != "")
                    textBox_refs.Text += "\r\n";
                textBox_refs.Text += refs[i];
            }
            */

        }

        class FileInfoCompare : IComparer
        {

            // Calls CaseInsensitiveComparer.Compare with the parameters reversed.
            int IComparer.Compare(Object x, Object y)
            {
                return ((new CaseInsensitiveComparer()).Compare(((FileInfo)x).Name, ((FileInfo)y).Name));
            }

        }

        // 填充文件信息
        void LoadFileInfo()
        {

            listView_files.Items.Clear();

            DirectoryInfo di = null;

            try
            {
                di = new DirectoryInfo(textBox_projectLocate.Text);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ExceptionUtil.GetAutoText(ex));
                return;
            }

            FileInfo[] afi = null;
            try
            {
                afi = di.GetFiles();
            }
            catch (DirectoryNotFoundException ex)
            {
                MessageBox.Show(this, ex.Message);
                return;
            }

            Array.Sort(afi, new FileInfoCompare());

            for (int i = 0; i < afi.Length; i++)
            {
                string strName = afi[i].Name;

                if (strName.Length == 0)
                    continue;
                if (strName[0] == '~'
                    && checkBox_displayTempFile.Checked == false)
                    continue;	// 不显示 '~'打头的临时文件

                ListViewItem item =
                    new ListViewItem(strName,
                    0);

                item.SubItems.Add(GetComment(strName));

                listView_files.Items.Add(item);

            }

        }

        string GetComment(string strFileName)
        {
            string strResult = "";

            if (String.Compare(strFileName,
                "main.cs",
                true) == 0)
                strResult = "主程序";
            else if (String.Compare(strFileName,
                "marcfilter.fltx",
                true) == 0)
                strResult = "MARC记录过滤器";
            else if (String.Compare(strFileName,
                "references.xml",
                true) == 0)
                strResult = "references配置";
            else if (String.Compare(strFileName,
    "metadata.xml",
    true) == 0)
                strResult = "元数据";

            return strResult;
        }

        /*
        void LoadCode()
        {
            // 源代码本身
            try
            {
                StreamReader sr = new StreamReader(textBox_codeFileName.Text, true);
                textBox_scriptCode.Text = sr.ReadToEnd();
                sr.Close();
            }
            catch
            {
                textBox_scriptCode.Text = "";
            }
        }
        */

        // 为新建一个Script准备参数
        public void New(string strProjectPath,
            string strTempName,
            string strNewLocate)
        {
            m_bNew = true;

            this.textBox_projectName.Text = strTempName;
            this.textBox_projectPathOfName.Text = strProjectPath;

            this.strTempLocate = strNewLocate;

            textBox_projectLocate.Text = strNewLocate;

            if (strNewLocate != null)
                scriptManager.CreateDefault(strNewLocate, this.HostName);

            LoadFileInfo();
        }

        private void ScriptDlg_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {

            if (this.DialogResult != DialogResult.OK
                && m_bNew == true)
            {
                DialogResult msgResult = MessageBox.Show(this,
                    "确实要放弃保存新方案 '" + textBox_projectName.Text + "' ?",
                    "script",
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question,
                    MessageBoxDefaultButton.Button2);
                if (msgResult == DialogResult.No)
                {
                    e.Cancel = true;
                    return;
                }
            }
        }

        private void ScriptDlg_Closed(object sender, System.EventArgs e)
        {
            // 删除临时代码文件
            if (this.strTempLocate != "")
            {
                try
                {
                    Directory.Delete(this.strTempLocate, true);
                }
                catch
                {
                }
            }

        }

        private void listView_files_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            if (e.Button != MouseButtons.Right)
                return;

            ContextMenu contextMenu = new ContextMenu();
            MenuItem menuItem = null;

            bool bSelected = listView_files.SelectedItems.Count > 0;

            //
            menuItem = new MenuItem("编辑(&E)");
            menuItem.Click += new System.EventHandler(this.button_editFile_Click);
            if (bSelected == false)
            {
                menuItem.Enabled = false;
            }
            contextMenu.MenuItems.Add(menuItem);

            //
            menuItem = new MenuItem("新增(&N)");
            menuItem.Click += new System.EventHandler(this.button_newFile_Click);
            contextMenu.MenuItems.Add(menuItem);

            // ---
            menuItem = new MenuItem("-");
            contextMenu.MenuItems.Add(menuItem);

            //
            menuItem = new MenuItem("删除(&D)");
            menuItem.Click += new System.EventHandler(this.button_deleteFile_Click);
            if (bSelected == false)
            {
                menuItem.Enabled = false;
            }
            contextMenu.MenuItems.Add(menuItem);

            contextMenu.Show(listView_files, new Point(e.X, e.Y));

        }

        private void button_editFile_Click(object sender, System.EventArgs e)
        {
            foreach (ListViewItem item in listView_files.SelectedItems)
            {
                string strFileName = textBox_projectLocate.Text + "\\" + item.Text;

                System.Diagnostics.Process.Start("notepad.exe", strFileName);
            }
        }

        private void button_newFile_Click(object sender, System.EventArgs e)
        {
            FileNameDlg dlg = new FileNameDlg();
            GuiUtil.AutoSetDefaultFont(dlg);

            dlg.StartPosition = FormStartPosition.CenterScreen;
            dlg.ShowDialog(this);

            if (dlg.DialogResult != DialogResult.OK)
                return;

            // 看看文件名是否重复创建
            if (GetFileNameItemIndex(dlg.textBox_fileName.Text) != -1)
            {
                MessageBox.Show(this, "文件" + dlg.textBox_fileName.Text + "已经存在,不能重复创建...");
                return;
            }

            string strFileName = textBox_projectLocate.Text + "\\" + dlg.textBox_fileName.Text;

            if (String.Compare(dlg.textBox_fileName.Text,
                "main.cs", true) == 0)
            {
                // ScriptManager.CreateDefaultMainCsFile(strFileName);
                scriptManager.OnCreateDefaultContent(strFileName);
            }
            else if (String.Compare(dlg.textBox_fileName.Text,
                "marcfilter.fltx", true) == 0)
            {
                // ScriptManager.CreateDefaultMarcFilterFile(strFileName);
                scriptManager.OnCreateDefaultContent(strFileName);
            }
            else if (String.Compare(dlg.textBox_fileName.Text,
                "references.xml", true) == 0)
            {
                // TODO: 应修改为事件驱动
                ScriptManager.CreateDefaultReferenceXmlFile(strFileName);
            }
            else if (String.Compare(dlg.textBox_fileName.Text,
                "metadata.xml", true) == 0)
            {
                Debug.Assert(string.IsNullOrEmpty(this.HostName) == false, "");
                // TODO: 应修改为事件驱动
                ScriptManager.CreateDefaultMetadataXmlFile(strFileName, this.HostName);
            }
            else
            {
                using (StreamWriter sw = new StreamWriter(strFileName))
                {
                    sw.WriteLine("");
                }
            }

            // 装入listview
            LoadFileInfo();

            int nIndex = GetFileNameItemIndex(dlg.textBox_fileName.Text);
            if (nIndex != -1)
            {

                listView_files.SelectedItems.Clear();
                listView_files.Items[nIndex].Selected = true;
            }
        }

        int GetFileNameItemIndex(string strFileName)
        {
            for (int i = 0; i < listView_files.Items.Count; i++)
            {
                if (String.Compare(strFileName,
                    listView_files.Items[i].Text,
                    true) == 0)
                    return i;
            }

            return -1;
        }

        private void button_deleteFile_Click(object sender, System.EventArgs e)
        {
            if (listView_files.SelectedItems.Count == 0)
            {
                MessageBox.Show(this, "尚未选择要删除的文件...");
                return;
            }

            string strFileNames = ListViewUtil.GetItemNameList(listView_files.SelectedItems, "\r\n");

            /*
			foreach(ListViewItem item in listView_files.SelectedItems)
			{
				strFileNames += item.Text + "\r\n";
			}
             * */

            // 警告
            DialogResult msgResult = MessageBox.Show(this,
                "确实要删除下列文件?\r\n---\r\n" + strFileNames + "---",
                "script",
                MessageBoxButtons.YesNo,
                MessageBoxIcon.Question,
                MessageBoxDefaultButton.Button2);
            if (msgResult == DialogResult.No)
            {
                return;
            }

            // 删除实际文件
            foreach (ListViewItem item in listView_files.SelectedItems)
            {
                string strFileName = textBox_projectLocate.Text + "\\"
                    + item.Text;

                try
                {
                    File.Delete(strFileName);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, ExceptionUtil.GetAutoText(ex));
                }
            }

            // 删除listview中事项
            for (int i = listView_files.SelectedIndices.Count - 1; i >= 0; i--)
            {
                listView_files.Items.RemoveAt(listView_files.SelectedIndices[i]);
            }

        }

        private void listView_files_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            if (listView_files.SelectedItems.Count == 0)
            {
                button_editFile.Enabled = false;
                button_newFile.Enabled = true;
                button_deleteFile.Enabled = false;
            }
            else
            {
                button_editFile.Enabled = true;
                button_newFile.Enabled = true;
                button_deleteFile.Enabled = true;
            }

        }

        private void button_changeProjectLocation_Click(object sender, System.EventArgs e)
        {
            DirNameDlg dlg = new DirNameDlg();
            GuiUtil.AutoSetDefaultFont(dlg);

            DirectoryInfo di = new DirectoryInfo(textBox_projectLocate.Text);

            dlg.textBox_dirName.Text = di.Name;
            dlg.StartPosition = FormStartPosition.CenterScreen;
            dlg.ShowDialog(this);

            if (dlg.DialogResult != DialogResult.OK)
                return;

            // 改名
            string strNewLocation = di.Parent.FullName + "\\" + dlg.textBox_dirName.Text;

            if (di.Exists == true)
            {
                try
                {
                    Directory.Move(textBox_projectLocate.Text, strNewLocation);
                }
                catch (IOException ex)
                {
                    MessageBox.Show(this, ex.Message);
                    return;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, ExceptionUtil.GetAutoText(ex));
                    return;
                }
            }

            // 方案名 + 路径
            ResultProjectNamePath = textBox_projectPathOfName.Text;

            if (ResultProjectNamePath != "")
                ResultProjectNamePath += "/";

            ResultProjectNamePath += textBox_projectName.Text;

            string strError;

            Debug.Assert(scriptManager != null, "调用本对话框以前,scriptManager指针应初始化...");

            if (m_bNew == false)
            {
                int nRet = scriptManager.ChangeProjectData(
                    ResultProjectNamePath,
                    null,
                    strNewLocation,
                    out strError);
                if (nRet == -1)
                {
                    MessageBox.Show(this, strError);
                    return;
                }

                scriptManager.Save();
            }

            textBox_projectLocate.Text = strNewLocation;

            // 重新装载文件名?
            LoadFileInfo();

        }

        private void listView_files_DoubleClick(object sender, System.EventArgs e)
        {
            button_editFile_Click(null, null);

        }

        private void button_changeProjectName_Click(object sender, System.EventArgs e)
        {

            ProjectNameDlg dlg = new ProjectNameDlg();
            GuiUtil.AutoSetDefaultFont(dlg);

            dlg.textBox_projectName.Text = textBox_projectName.Text;
            dlg.StartPosition = FormStartPosition.CenterScreen;
            dlg.ShowDialog(this);

            if (dlg.DialogResult != DialogResult.OK)
                return;

            if (dlg.textBox_projectName.Text == textBox_projectName.Text)
                return;	// 没有必要修改

            if (m_bNew == true)
            {
                textBox_projectName.Text = dlg.textBox_projectName.Text;
                return;
            }

            // 方案名 + 路径
            ResultProjectNamePath = textBox_projectPathOfName.Text;

            if (ResultProjectNamePath != "")
                ResultProjectNamePath += "/";

            ResultProjectNamePath += textBox_projectName.Text;

            string strError;

            int nRet = scriptManager.ChangeProjectData(ResultProjectNamePath,
                dlg.textBox_projectName.Text,
                null,
                out strError);
            if (nRet == -1)
            {
                MessageBox.Show(this, strError);
            }
            else
            {
                // 兑现显示遗留给对话框退出以后再做
                // node.Text = dlg.textBox_projectName.Text;
                textBox_projectName.Text = dlg.textBox_projectName.Text;
                scriptManager.Save();
            }

        }

        private void checkBox_displayTempFile_CheckedChanged(object sender, System.EventArgs e)
        {
            LoadFileInfo();
        }

        private void button_openProjectFolder_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(this.textBox_projectLocate.Text) == true)
            {
                MessageBox.Show(this, "尚未指定方案目录");
                return;
            }

            try
            {
                System.Diagnostics.Process.Start(this.textBox_projectLocate.Text);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ExceptionUtil.GetAutoText(ex));
            }

        }

        private void textBox_projectLocate_TextChanged(object sender, EventArgs e)
        {
            if (this.textBox_projectLocate.Text == "")
            {
                this.button_openProjectFolder.Enabled = false;
                this.button_changeProjectLocation.Enabled = false;
                this.button_openInCode.Enabled = false;
            }
            else
            {
                this.button_openProjectFolder.Enabled = true;
                this.button_changeProjectLocation.Enabled = true;
                this.button_openInCode.Enabled = true;
            }
        }

        // 在 Visual Studio Code 中打开
        private void button_openInCode_Click(object sender, EventArgs e)
        {
            try
            {
                ProcessStartInfo startInfo = new ProcessStartInfo("code");
                startInfo.Arguments = ".";
                startInfo.WindowStyle = ProcessWindowStyle.Hidden;
                startInfo.CreateNoWindow = true;
                // startInfo.UseShellExecute = false;
                startInfo.WorkingDirectory = this.textBox_projectLocate.Text;
                Process p = Process.Start(startInfo);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "启动 Vusual Studio Code 时发生异常(可能是 Code 尚未安装):" + ex.Message);
            }
        }
    }
}


text:
package net.spy.memcached;

/**
 * A value with a CAS identifier.
 */
public class CASValue<T> {
  private final long cas;
  private final T value;

  /**
   * Construct a new CASValue with the given identifer and value.
   *
   * @param c the CAS identifier
   * @param v the value
   */
  public CASValue(long c, T v) {
    super();
    cas = c;
    value = v;
  }

  /**
   * Get the CAS identifier.
   */
  public long getCas() {
    return cas;
  }

  /**
   * Get the object value.
   */
  public T getValue() {
    return value;
  }

  @Override
  public String toString() {
    return "{CasValue " + cas + "/" + value + "}";
  }
}


text:
package com.yahoo.sketches;

import java.nio.charset.StandardCharsets;

import com.yahoo.memory.Memory;
import com.yahoo.memory.NativeMemory;
import com.yahoo.memory.UnsafeUtil;

/**
 * Methods of serializing and deserializing arrays of String.
 * This class serializes strings in UTF-8 format, which is more compact compared to
 * {@link ArrayOfUtf16StringsSerDe}. In an extreme case when all strings are in ASCII,
 * this method is 2 times more compact, but it takes more time to encode and decode
 * by a factor of 1.5 to 2.
 *
 * @author Alexander Saydakov
 */
public class ArrayOfStringsSerDe extends ArrayOfItemsSerDe<String> {

  @Override
  public byte[] serializeToByteArray(final String[] items) {
    int length = 0;
    final byte[][] itemsBytes = new byte[items.length][];
    for (int i = 0; i < items.length; i++) {
      itemsBytes[i] = items[i].getBytes(StandardCharsets.UTF_8);
      length += itemsBytes[i].length + Integer.BYTES;
    }
    final byte[] bytes = new byte[length];
    final Memory mem = new NativeMemory(bytes);
    long offsetBytes = 0;
    for (int i = 0; i < items.length; i++) {
      mem.putInt(offsetBytes, itemsBytes[i].length);
      offsetBytes += Integer.BYTES;
      mem.putByteArray(offsetBytes, itemsBytes[i], 0, itemsBytes[i].length);
      offsetBytes += itemsBytes[i].length;
    }
    return bytes;
  }

  @Override
  public String[] deserializeFromMemory(final Memory mem, final int numItems) {
    final String[] array = new String[numItems];
    long offsetBytes = 0;
    for (int i = 0; i < numItems; i++) {
      UnsafeUtil.checkBounds(offsetBytes, Integer.BYTES, mem.getCapacity());
      final int strLength = mem.getInt(offsetBytes);
      offsetBytes += Integer.BYTES;
      final byte[] bytes = new byte[strLength];
      UnsafeUtil.checkBounds(offsetBytes, strLength, mem.getCapacity());
      mem.getByteArray(offsetBytes, bytes, 0, strLength);
      offsetBytes += strLength;
      array[i] = new String(bytes, StandardCharsets.UTF_8);
    }
    return array;
  }

}


text:
package resource

import (
	"errors"
	"net/http"
	"sort"
	"strconv"

	"github.com/manyminds/api2go"
	"github.com/manyminds/api2go/examples/model"
	"github.com/manyminds/api2go/examples/storage"
)

// UserResource for api2go routes
type UserResource struct {
	ChocStorage *storage.ChocolateStorage
	UserStorage *storage.UserStorage
}

// FindAll to satisfy api2go data source interface
func (s UserResource) FindAll(r api2go.Request) (api2go.Responder, error) {
	var result []model.User
	users := s.UserStorage.GetAll()

	for _, user := range users {
		// get all sweets for the user
		user.Chocolates = []*model.Chocolate{}
		for _, chocolateID := range user.ChocolatesIDs {
			choc, err := s.ChocStorage.GetOne(chocolateID)
			if err != nil {
				return &Response{}, err
			}
			user.Chocolates = append(user.Chocolates, &choc)
		}
		result = append(result, *user)
	}

	return &Response{Res: result}, nil
}

// PaginatedFindAll can be used to load users in chunks
func (s UserResource) PaginatedFindAll(r api2go.Request) (uint, api2go.Responder, error) {
	var (
		result                      []model.User
		number, size, offset, limit string
		keys                        []int
	)
	users := s.UserStorage.GetAll()

	for k := range users {
		i, err := strconv.ParseInt(k, 10, 64)
		if err != nil {
			return 0, &Response{}, err
		}

		keys = append(keys, int(i))
	}
	sort.Ints(keys)

	numberQuery, ok := r.QueryParams["page[number]"]
	if ok {
		number = numberQuery[0]
	}
	sizeQuery, ok := r.QueryParams["page[size]"]
	if ok {
		size = sizeQuery[0]
	}
	offsetQuery, ok := r.QueryParams["page[offset]"]
	if ok {
		offset = offsetQuery[0]
	}
	limitQuery, ok := r.QueryParams["page[limit]"]
	if ok {
		limit = limitQuery[0]
	}

	if size != "" {
		sizeI, err := strconv.ParseUint(size, 10, 64)
		if err != nil {
			return 0, &Response{}, err
		}

		numberI, err := strconv.ParseUint(number, 10, 64)
		if err != nil {
			return 0, &Response{}, err
		}

		start := sizeI * (numberI - 1)
		for i := start; i < start+sizeI; i++ {
			if i >= uint64(len(users)) {
				break
			}
			result = append(result, *users[strconv.FormatInt(int64(keys[i]), 10)])
		}
	} else {
		limitI, err := strconv.ParseUint(limit, 10, 64)
		if err != nil {
			return 0, &Response{}, err
		}

		offsetI, err := strconv.ParseUint(offset, 10, 64)
		if err != nil {
			return 0, &Response{}, err
		}

		for i := offsetI; i < offsetI+limitI; i++ {
			if i >= uint64(len(users)) {
				break
			}
			result = append(result, *users[strconv.FormatInt(int64(keys[i]), 10)])
		}
	}

	return uint(len(users)), &Response{Res: result}, nil
}

// FindOne to satisfy `api2go.DataSource` interface
// this method should return the user with the given ID, otherwise an error
func (s UserResource) FindOne(ID string, r api2go.Request) (api2go.Responder, error) {
	user, err := s.UserStorage.GetOne(ID)
	if err != nil {
		return &Response{}, api2go.NewHTTPError(err, err.Error(), http.StatusNotFound)
	}

	user.Chocolates = []*model.Chocolate{}
	for _, chocolateID := range user.ChocolatesIDs {
		choc, err := s.ChocStorage.GetOne(chocolateID)
		if err != nil {
			return &Response{}, err
		}
		user.Chocolates = append(user.Chocolates, &choc)
	}
	return &Response{Res: user}, nil
}

// Create method to satisfy `api2go.DataSource` interface
func (s UserResource) Create(obj interface{}, r api2go.Request) (api2go.Responder, error) {
	user, ok := obj.(model.User)
	if !ok {
		return &Response{}, api2go.NewHTTPError(errors.New("Invalid instance given"), "Invalid instance given", http.StatusBadRequest)
	}

	id := s.UserStorage.Insert(user)
	user.ID = id

	return &Response{Res: user, Code: http.StatusCreated}, nil
}

// Delete to satisfy `api2go.DataSource` interface
func (s UserResource) Delete(id string, r api2go.Request) (api2go.Responder, error) {
	err := s.UserStorage.Delete(id)
	return &Response{Code: http.StatusNoContent}, err
}

//Update stores all changes on the user
func (s UserResource) Update(obj interface{}, r api2go.Request) (api2go.Responder, error) {
	user, ok := obj.(model.User)
	if !ok {
		return &Response{}, api2go.NewHTTPError(errors.New("Invalid instance given"), "Invalid instance given", http.StatusBadRequest)
	}

	err := s.UserStorage.Update(user)
	return &Response{Res: user, Code: http.StatusNoContent}, err
}


text:
import getFileNameAndExtension from './getFileNameAndExtension.js'
import mimeTypes from './mimeTypes.js'

export default function getFileType (file) {
  if (file.type) return file.type

  const fileExtension = file.name ? getFileNameAndExtension(file.name).extension?.toLowerCase() : null
  if (fileExtension && fileExtension in mimeTypes) {
    // else, see if we can map extension to a mime type
    return mimeTypes[fileExtension]
  }
  // if all fails, fall back to a generic byte stream type
  return 'application/octet-stream'
}


text:
    					{{node.name}}

				 <localize key="general_add">Add</localize>

   <umb-overlay
      ng-if="memberGroupPicker.show"
      model="memberGroupPicker"
      position="right"
      view="memberGroupPicker.view">
   </umb-overlay>


text:
<?php

namespace Oro\Bundle\EmailBundle\EventListener;

use Symfony\Component\Security\Core\User\UserInterface;

use Oro\Bundle\EmailBundle\Entity\Email;
use Oro\Bundle\EmailBundle\Entity\EmailRecipient;
use Oro\Bundle\OrganizationBundle\Entity\OrganizationAwareInterface;
use Oro\Bundle\SearchBundle\Event\PrepareEntityMapEvent;

class SearchListener
{
    const EMAIL_CLASS_NAME = 'Oro\Bundle\EmailBundle\Entity\Email';
    const EMPTY_ORGANIZATION_ID = 0;

    /**
     * @param PrepareEntityMapEvent $event
     */
    public function prepareEntityMapEvent(PrepareEntityMapEvent $event)
    {
        $data      = $event->getData();
        $className = $event->getClassName();
        if ($className === self::EMAIL_CLASS_NAME) {
            /** @var $entity Email */
            $entity          = $event->getEntity();
            $organizationsId = [];
            $recipients      = $entity->getRecipients();
            /** @var  $recipient EmailRecipient */
            foreach ($recipients as $recipient) {
                $owner = $recipient->getEmailAddress()->getOwner();
                if ($owner instanceof UserInterface && $owner instanceof OrganizationAwareInterface) {
                    $organizationsId[] = $owner->getOrganization()->getId();
                }
            }
            if (!isset($data['integer'])) {
                $data['integer'] = [];
            }
            if (!empty($organizationsId)) {
                $data['integer']['organization'] = array_unique($organizationsId);
            } else {
                $data['integer']['organization'] = self::EMPTY_ORGANIZATION_ID;
            }
        }

        $event->setData($data);
    }
}