text:
<?php

namespace Bolt\Installer\Command;

use Bolt\Requirement\BoltRequirements;
use Bolt\Requirement\PhpIniRequirement;
use Bolt\Requirement\Requirement;
use Bolt\Requirement\RequirementCollection;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Formatter\OutputFormatterStyle;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Filesystem\Filesystem;

/**
 * Check installation command.
 *
 * @author Gawain Lynch <gawain.lynch@gmail.com>
 */
class CheckCommand extends BaseCommand
{
    /** @var Filesystem */
    protected $fs;
    /** @var string The project name */
    protected $projectName;
    /** @var string The project dir */
    protected $projectDir;

    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this
            ->setName('check')
            ->setDescription('Bolt Installer environment checks.')
            ->addArgument('directory', InputArgument::OPTIONAL, 'Directory (optional) where the project is located.')
        ;
    }

    /**
     * {@inheritdoc}
     */
    protected function initialize(InputInterface $input, OutputInterface $output)
    {
        $this->fs = new Filesystem();

        $style = new OutputFormatterStyle('black', 'yellow', []);
        $output->getFormatter()->setStyle('koala', $style);
        $directory = rtrim(trim($input->getArgument('directory')), DIRECTORY_SEPARATOR);
        $this->projectDir = $this->fs->isAbsolutePath($directory) ? $directory : getcwd() . DIRECTORY_SEPARATOR . $directory;
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $boltRequirements = new BoltRequirements($this->projectDir);
        $requirementsErrors = [];
        $recommendationsErrors = [];
        $problemFree = true;

        if ($boltRequirements->hasPhpIniConfigIssue()) {
            $this->notifyPhpIniConfigIssue($boltRequirements, $output);
        }

        /** @var Requirement $requirement */
        foreach ($boltRequirements->getRequirements() as $requirement) {
            if ($requirement->isFulfilled() || $requirement instanceof PhpIniRequirement) {
                continue;
            }
            $requirementsErrors[] = $requirement;
        }
        foreach ($boltRequirements->getRecommendations() as $requirement) {
            if ($requirement->isFulfilled() || $requirement instanceof PhpIniRequirement) {
                continue;
            }
            $recommendationsErrors[] = $requirement;
        }

        if (!empty($requirementsErrors)) {
            $problemFree = false;
            $this->notifyRequirements($requirementsErrors, $output);
        }

        if (!empty($recommendationsErrors)) {
            $problemFree = false;
            $this->notifyRecommendations($recommendationsErrors, $output);
        }

        if ($problemFree) {
            $this->notifyProblemFree($output);
        }
    }

    private function notifyProblemFree(OutputInterface $output)
    {
        $banner = <<<BANNER
 <bg=green;options=bold>

 Congratulations!

 Everything looks OK, you should be able to run Bolt on this host.
 </>

BANNER;
        $output->writeln(sprintf($banner));
    }

    /**
     * @param RequirementCollection $requirements
     * @param OutputInterface       $output
     */
    private function notifyPhpIniConfigIssue(RequirementCollection $requirements, OutputInterface $output)
    {
        $style = new OutputFormatterStyle('black', 'red', ['bold']);
        $output->getFormatter()->setStyle('banner_php', $style);
        $banner = <<<BANNER
 <banner_php>

 PHP Configuration problems found:
 </>
BANNER;
        $output->write(sprintf($banner));

        $message = '';
        foreach ($requirements as $requirement) {
            if ($requirement instanceof PhpIniRequirement) {
                $message .= $this->getErrorMessage($requirement);
            }
        }
        $output->writeln(sprintf('<koala>%s%s</koala>', PHP_EOL, $message));
    }

    /**
     * @param Requirement[]   $requirements
     * @param OutputInterface $output
     */
    private function notifyRequirements($requirements, OutputInterface $output)
    {
        $style = new OutputFormatterStyle('black', 'red', ['bold']);
        $output->getFormatter()->setStyle('banner_require', $style);
        $banner = <<<BANNER
 <banner_require>

 Requirement problems found:
 </>
BANNER;
        $output->write(sprintf($banner));

        $message = '';
        foreach ($requirements as $requirement) {
            $message .= $this->getErrorMessage($requirement);
        }
        $output->writeln(sprintf('<koala>%s%s</koala>', PHP_EOL, $message));
    }

    /**
     * @param Requirement[]   $requirements
     * @param OutputInterface $output
     */
    private function notifyRecommendations($requirements, OutputInterface $output)
    {
        $style = new OutputFormatterStyle('black', 'cyan', ['bold']);
        $output->getFormatter()->setStyle('banner_recommend', $style);
        $banner = <<<BANNER
 <banner_recommend>

 Recommended settings are not correct:
 </>
BANNER;
        $output->write(sprintf($banner));

        $message = '';
        foreach ($requirements as $requirement) {
            $message .= $this->getErrorMessage($requirement);
        }
        $output->writeln(sprintf('<koala>%s%s</koala>', PHP_EOL, $message));
    }

    /**
     * @param Requirement $requirement
     * @param int         $lineSize
     *
     * @return null|string
     */
    private function getErrorMessage(Requirement $requirement, $lineSize = 70)
    {
        if ($requirement->isFulfilled()) {
            return null;
        }

        $errorMessage = wordwrap($requirement->getTestMessage(), $lineSize - 3, PHP_EOL . '   ') . PHP_EOL;
        $errorMessage .= '   > ' . wordwrap($requirement->getHelpText(), $lineSize - 5, PHP_EOL . '   > ') . PHP_EOL;

        return $errorMessage;
    }
}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;
using GTA;
using GTA.Math;
using GTA.Native;
using Inferno.InfernoScripts.Event;
using Inferno.InfernoScripts.Event.Isono;
using UniRx;

namespace Inferno.InfernoScripts.Parupunte
{
    internal class ParupunteCore : InfernoScript
    {

        /// <summary>
        /// パルプンテスクリプト一覧
        /// </summary>
        private Type[] _parupunteScritpts;

        private Dictionary<string, ParupunteConfigElement> _parupunteConfigs;

        /// <summary>
        /// デバッグ用
        /// </summary>
        private Type[] _debugParuputeScripts;

        /// <summary>
        /// いその用パルプンテ
        /// </summary>
        private Dictionary<string, Type> _isonoParupunteScripts;

        private Dictionary<string, Type> IsonoParupunteScripts
        {
            get
            {
                if (_isonoParupunteScripts != null) return _isonoParupunteScripts;
                _isonoParupunteScripts =
                    _parupunteScritpts
                        .Select(x => new { type = x, isono = x.GetCustomAttribute<ParupunteIsono>() })
                        .Where(x => !string.IsNullOrEmpty(x.isono?.Command))
                        .ToDictionary(x => x.isono.Command, x => x.type);
                return _isonoParupunteScripts;
            }
        }

        /// <summary>
        /// NoLongerNeededを遅延して設定する対象リスト
        /// </summary>
        private List<Entity> _autoReleaseEntitiesList = new List<Entity>();

        private UIContainer _mainTextUiContainer;
        private UIContainer _subTextUiContainer;
        private TimerUiTextManager timerText;
        private int _screenHeight;
        private int _screenWidth;
        private Vector2 _mainTextPositionScale = new Vector2(0.5f, 0.8f);
        private Vector2 _subTextPositionScale = new Vector2(0.0f, 0.0f);

        private readonly Stopwatch _stopWatch = Stopwatch.StartNew();

        private TimeSpan Time => _stopWatch.Elapsed;

        protected override void Setup()
        {
            IsActive = false;
            timerText = new TimerUiTextManager(this);

            #region ParunteScripts

            //RefrectionでParupunteScriptを継承しているクラスをすべて取得する
            _parupunteScritpts =
                Assembly.GetExecutingAssembly()
                    .GetTypes()
                    .Where(type => type.BaseType != null && type.BaseType == typeof(ParupunteScript))
                    .Where(x =>
                    {
                        var attribute = x.GetCustomAttribute<ParupunteDebug>();
                        return attribute == null || !attribute.IsIgnore;
                    })
                    .ToArray();

            _debugParuputeScripts = _parupunteScritpts.Where(x =>
            {
                var attribute = x.GetCustomAttribute<ParupunteDebug>();
                return attribute != null && attribute.IsDebug;
            }).ToArray();

            #endregion ParunteScripts

            #region Config

            SetConfigData(_parupunteScritpts);

            #endregion

            #region EventHook

            CreateInputKeywordAsObservable("rnt")
                .Where(_ => !IsActive)
                .Subscribe(_ => ParupunteStart(ChooseParupounteScript()));

            CreateInputKeywordAsObservable("snt")
                .Where(_ => IsActive)
                .Subscribe(_ => ParupunteStop());

            OnKeyDownAsObservable.Where(x => x.KeyCode == Keys.NumPad0)
                .ThrottleFirst(TimeSpan.FromSeconds(2f), InfernoScriptScheduler)
                .Subscribe(_ =>
                {
                    if (IsActive)
                    {
                        ParupunteStop();
                    }
                    else
                    {
                        ParupunteStart(ChooseParupounteScript());
                    }

                });

            //パルプンテが停止したタイミングで開放
            IsActiveAsObservable
                .Where(x => !x)
                .Subscribe(_ =>
                {
                    foreach (var entity in _autoReleaseEntitiesList.Where(entity => entity.IsSafeExist()))
                    {
                        entity.MarkAsNoLongerNeeded();
                    }
                    _autoReleaseEntitiesList.Clear();
                });

            var nextIsonoTime = Time;

            OnRecievedInfernoEvent
                .OfType<IEventMessage, IsonoMessage>()
                .Where(_ => (nextIsonoTime - Time).Ticks <= 0)
                .Retry()
                .Subscribe(c =>
                {
                    var r = IsonoMethod(c.Command);
                    if (r) nextIsonoTime = Time.Add(TimeSpan.FromSeconds(4));
                });

            #endregion EventHook

            #region Drawer

            var screenResolution = NativeFunctions.GetScreenResolution();
            _screenHeight = (int)screenResolution.Y;
            _screenWidth = (int)screenResolution.X;
            _mainTextUiContainer = new UIContainer(
                new Point(0, 0), new Size(_screenWidth, _screenHeight));
            _subTextUiContainer = new UIContainer(
                new Point(0, 0), new Size(_screenWidth, _screenHeight));

            //テキストが更新されたら詰め直す
            timerText.OnSetTextAsObservable.Subscribe(_ =>
            {
                _mainTextUiContainer.Items.Clear();
                _mainTextUiContainer.Items.Add(timerText.Text);
            });
            //テキストが時間切れしたら消す
            OnThinnedTickAsObservable.Select(_ => timerText.IsEnabled)
                .DistinctUntilChanged()
                .Where(x => !x)
                .Subscribe(_ => _mainTextUiContainer.Items.Clear());

            this.OnDrawingTickAsObservable
                .Where(_ => _mainTextUiContainer.Items.Any() || _subTextUiContainer.Items.Any())
                .Subscribe(_ =>
                {
                    _mainTextUiContainer.Draw();
                    _subTextUiContainer.Draw();
                });

            #endregion Drawer

        }

        // Configファイルの設定を行う
        private void SetConfigData(Type[] parupunteScripts)
        {
            var configRepository = new ParupunteConfigRepository();

            // jsonから読み込んだConfig値
            var loadConfig = configRepository.LoadSettingFile();

            // デフォルト値
            var defaultConfig = parupunteScripts
                .Select(x => new { x.Name, Attribute = x.GetCustomAttribute<ParupunteConfigAttribute>() })
                .Where(x => x.Attribute != null)
                .ToDictionary(x => x.Name, x =>
                {
                    var a = x.Attribute;
                    return new ParupunteConfigElement(a.DefaultStartMessage, a.DefaultSubMessage, a.DefaultEndMessage);
                });

            // 合成したConfig値
            var mergedConfig = new Dictionary<string, ParupunteConfigElement>();

            // デフォルト値のConfを、読み込んだConf値で上書きする
            foreach (var kv in defaultConfig)
            {
                var value = kv.Value;
                if (loadConfig.ContainsKey(kv.Key))
                {
                    value = loadConfig[kv.Key];
                }
                mergedConfig[kv.Key] = value;
            }

            // 最終的なconfをファイルに書き出す
            configRepository.SaveSettings(mergedConfig);

            // 設定完了
            _parupunteConfigs = mergedConfig;
        }

        private bool IsonoMethod(string command)
        {
            var c = command;

            if (c.Contains("とまれ"))
            {
                //       ParupunteStop();
                //       return true;
            }

            if (IsActive) return false;

            if (c.Contains("ぱるぷんて"))
            {
                ParupunteStart(ChooseParupounteScript());
                return true;
            }

            var result = IsonoParupunteScripts.Keys.FirstOrDefault(x => command.Contains(x));
            if (string.IsNullOrEmpty(result) || !IsonoParupunteScripts.ContainsKey(result)) return false;
            ParupunteStart(IsonoParupunteScripts[result]);
            return true;
        }

        /// <summary>
        /// パルプンテの実行を開始する
        /// </summary>
        private void ParupunteStart(Type script)
        {
            if (IsActive)
            {
                return;
            }

            IsActive = true;

            var conf = _parupunteConfigs.ContainsKey(script.Name)
                ? _parupunteConfigs[script.Name]
                : ParupunteConfigElement.Default;

            //ThreadPool上で初期化(プチフリ回避)
            Observable.Start(() => Activator.CreateInstance(script, this, conf) as ParupunteScript, Scheduler.ThreadPool)
                .OnErrorRetry((Exception ex) =>
                {
                    LogWrite(ex.ToString());
                }, 3, TimeSpan.FromMilliseconds(300))
                .Subscribe(x => StartCoroutine(ParupunteCoreCoroutine(x)), ex =>
                {
                    //       LogWrite(ex.ToString());
                    IsActive = false;
                });
        }

        /// <summary>
        /// パルプンテを中断する
        /// </summary>
        private void ParupunteStop()
        {
            DrawText("Parupunte:Abort");
            IsActive = false;
        }

        /// <summary>
        /// パルプンテスクリプトから抽選する
        /// </summary>
        private Type ChooseParupounteScript()
        {
            if (_debugParuputeScripts.Any())
            {
                //デバッグ指定のやつがあるならそっち優先で取り出す
                return _debugParuputeScripts[Random.Next(0, _debugParuputeScripts.Length)];
            }
            return _parupunteScritpts[Random.Next(0, _parupunteScritpts.Length)];
        }

        /// <summary>
        /// パルプンテのメインコルーチン
        /// </summary>
        /// <returns></returns>
        private IEnumerable<object> ParupunteCoreCoroutine(ParupunteScript script)
        {
            yield return null;

            if (!IsActive) yield break;

            if (script == null)
            {
                IsActive = false;
                yield break;
            }

            try
            {
                script.OnSetUp();
                script.OnSetNames();
            }
            catch (Exception e)
            {
                LogWrite(e.ToString());
                script.OnFinishedCore();
                IsActive = false;
                yield break;
            }

            //名前を出してスタート
            StartCoroutine(ParupunteDrawCoroutine(GetPlayerName() + "はパルプンテを唱えた!", script.Name));
            yield return WaitForSeconds(2);

            try
            {
                script.OnStart();
            }
            catch (Exception e)
            {
                LogWrite(e.ToString());
                script.OnFinishedCore();
                IsActive = false;
                _subTextUiContainer.Items.Clear();
                yield break;
            }

            //サブタイトルを出す
            var subTitle = string.IsNullOrEmpty(script.SubName) ? script.Name : script.SubName;
            _subTextUiContainer.Items.Clear();
            _subTextUiContainer.Items.Add(CreateSubText(subTitle));

            while (script.IsActive && IsActive)
            {
                try
                {
                    //スクリプトのUpdateを実行
                    script.OnUpdateCore();
                }
                catch (Exception e)
                {
                    LogWrite(e.ToString());
                    script.OnFinishedCore();
                    IsActive = false;
                    _subTextUiContainer.Items.Clear();
                    yield break;
                }
                yield return null; //100ms待機
            }

            try
            {
                script.OnFinishedCore();
            }
            catch (Exception e)
            {
                LogWrite(e.ToString());
            }
            finally
            {
                IsActive = false;
                _subTextUiContainer.Items.Clear();
            }
        }

        /// <summary>
        /// 画面に名前とかを出す
        /// </summary>
        private IEnumerable<object> ParupunteDrawCoroutine(string callString, string scriptname)
        {
            //○はパルプンテを唱えた!の部分
            timerText.Set(CreateMainText(callString), 2.0f);

            //2秒画面に出す
            yield return WaitForSeconds(2);

            //効果名
            timerText.Set(CreateMainText(scriptname), 3.0f);

            //3秒画面に出す
            yield return WaitForSeconds(3);
        }

        /// <summary>
        /// テキストを表示する(ParupunteScript用)
        /// </summary>
        public void DrawParupunteText(string text, float duration)
        {
            timerText.Set(CreateMainText(text), duration);
        }

        private UIText CreateMainText(string text)
        {
            return new UIText(text,
                new Point((int)(_screenWidth * _mainTextPositionScale.X), (int)(_screenHeight * _mainTextPositionScale.Y)),
                0.8f, Color.White, 0, true, false, true);
        }

        private UIText CreateSubText(string text)
        {
            return new UIText(text,
                new Point((int)(_screenWidth * _subTextPositionScale.X),
                (int)(_screenHeight * _subTextPositionScale.Y)),
                0.4f, Color.White, 0, false, false, true);
        }

        private string GetPlayerName()
        {
            var hash = (PedHash)PlayerPed.Model.Hash;
            switch (hash)
            {
                case PedHash.Trevor:
                    return Game.GetGXTEntry("BLIP_TREV");

                case PedHash.Michael:
                    return Game.GetGXTEntry("BLIP_MICHAEL");

                case PedHash.Franklin:
                    return Game.GetGXTEntry("BLIP_FRANKLIN");

                default:
                    return hash.ToString();
            }
        }

        /// <summary>
        /// コルーチンの実行をCoreに委託する
        /// </summary>
        public uint RegisterCoroutine(IEnumerable<object> coroutine)
        {
            return StartCoroutine(coroutine);
        }

        /// <summary>
        /// コルーチンの実行を終了する
        /// </summary>
        /// <param scriptname="id"></param>
        public void UnregisterCoroutine(uint id)
        {
            StopCoroutine(id);
        }

        /// <summary>
        /// WaitForSeconsの結果を返す
        /// </summary>
        public IEnumerable CreateWaitForSeconds(float seconds)
        {
            return WaitForSeconds(seconds);
        }

        public IEnumerable CreateRadomWait()
        {
            return RandomWait();
        }

        public void AddProgressBar(ReduceCounter reduceCounter)
        {
            var prgoressbarData = new ProgressBarData(reduceCounter,
                new Point(0, 15),
                Color.FromArgb(200, 0, 127, 255),
                Color.FromArgb(128, 0, 0, 0),
                DrawType.RightToLeft, 100, 10, 2);
            RegisterProgressBar(prgoressbarData);
            RegisterCounter(reduceCounter);
        }

        /// <summary>
        /// パルプンテが終了した時に自動的に開放してくれる
        /// </summary>
        public void AutoReleaseOnParupunteEnd(Entity entity)
        {
            if (entity.IsSafeExist()) _autoReleaseEntitiesList.Add(entity);
            //中断時にも対応させる
            base.AutoReleaseOnGameEnd(entity);
        }

        public new void AutoReleaseOnGameEnd(Entity entity)
        {
            base.AutoReleaseOnGameEnd(entity);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Immortal\Support\Facades;

/**
 * @see \Immortal\View\Compilers\BladeCompiler
 */
class Blade extends Facade
{
    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor()
    {
        return static::$app['view']->getEngineResolver()->resolve('blade')->getCompiler();
    }
}


text:
using System;
using System.Runtime.InteropServices;
using starshipxac.Shell.Interop;

namespace starshipxac.Windows.Shell.Controls.Interop
{
    [ComImport]
    [Guid(ShellIID.IContextMenu2)]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    internal interface IContextMenu2 : IContextMenu
    {
        [PreserveSig]
        HRESULT HandleMenuMsg(
            UInt32 uMsg,
            IntPtr wParam,
            IntPtr lParam);
    }
}


text:
package org.kie.internal.task.api.model;

import org.kie.api.task.model.OrganizationalEntity;

public interface InternalOrganizationalEntity extends OrganizationalEntity {

    void setId(String id);

}


text:
using FluentValidation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TestCase.Repository.Locking.Contracts;
using TestCase.Service.Validation;

namespace TestCase.Service.Locking.Lock.DeleteLockPermission
{
    /// <summary>
    /// Delete lock permission command validator.
    /// </summary>
    /// <seealso cref="TestCase.Service.Validation.BaseModelValidator{TestCase.Service.Locking.Lock.DeleteLockPermission.DeleteLockPermissionCommand}" />
    public class DeleteLockPermissionCommandValidator : BaseModelValidator<DeleteLockPermissionCommand>
    {
        private readonly ILockRepository lockRepository;

        /// <summary>
        /// Initializes a new instance of the <see cref="DeleteLockPermissionCommandValidator"/> class.
        /// </summary>
        public DeleteLockPermissionCommandValidator(ILockRepository lockRepository)
        {
            RuleFor(model => model.LockPermissionId)
                .NotEmpty().WithMessage("LockPermissionId is required.");
            RuleFor(model => model.LockId)
                .NotEmpty().WithMessage("LockId is required.");
            this.lockRepository = lockRepository;
        }

        /// <summary>
        /// Asynchronously validates the model.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <returns></returns>
        public override async Task ValidateAsync(DeleteLockPermissionCommand model)
        {
            await base.ValidateAsync(model);

            var existingPolicy = await this.lockRepository.GetLockPermissionAsync(model.LockPermissionId);
            if (existingPolicy == null)
            {
                throw new ValidationException("LockPermission doesn't exist");
            }
        }
    }
}


text:
<!doctype html>

    <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Northmount Developments Ltd for Consulting, Enterprise Architecture and Open Source Software.">

    <title>northmount.org</title>

<link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.6.0/pure-min.css">

    <link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.6.0/grids-responsive-min.css">

<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css">

        <link rel="stylesheet" href="css/layouts/marketing.css">

        northmount.org

Home

Services

Latest

Blog

                    February 2014 News

25/02/2014  - The first thing to point out is that myJarvis is a highly complex project and is at the very early stages of development at this point. To give you some understanding of the current position, a POC has been produced for the AI communications pieceand some rudimentary note take capabilities. The next stage being to provide a better UI experience and to build in a multi-threaded approach to the java 1.7.0.51 built program so far.  With a view to produce a video to generate some more interest in this project.

25/02/2014 - Jango is a much smaller project initially than myJarvis all though I have high hopes that this will provide a very usefull tool for industry. I hope to produce a jar file over the next week or so that can be downloaded and can be used to produce realtime test data into the MongdoDB

Archives

Find out more.

                <form class="pure-form pure-form-stacked">
                    <fieldset>

                    </fieldset>
                </form>

Connect

                Owner and Principle Consultant Philip Tyler, connect via Twitter, LinkedIn or Email as below.

                "An IT visionary highly experienced in delivering Strategy across multiple sectors, focused on large scale Business Transformation, Change Management and Enterprise Architecture."

                Providing consultancy for a variety of sectors over the last 20+ years including Retail, Banking and Finance, Government, Travel, Utilities, Telecommunications. These included a number of high profile clients BP, Shell, DERA, Barclays, Cisco, Scottish Water, Wetherspoons, Burberry, BAA, Easyjet.... and more.

                Enterprise Data Architect, Technical Architect and Big Data Consultant using TOGAF, Agile, MongoDB, Horton Works, Cloudera, Informatica, Talend, CA Erwin and others...

        Proudly powered by Linux.


text:
package com.guangzhou.gov.net.tools;

import java.util.HashMap;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;

import android.content.Context;

/**
 * 上层封装的Http工具类
 *
 * @ClassName: HttpTool
 * @author chenjianping
 * @date 2014-11-9
 *
 */
public class HttpTool {

    /**
     * 通过get方法访问一个http地址,获取其返回的字符串内容
     *
     * @param context
     * @param contentUrl http地址
     * @return 返回获取到的字符串,可能为null
     */
    public static final String getString(Context context, String contentUrl)
    {
        String data = null;
        HttpGet get = HttpHelper.get(contentUrl);
        if (get != null) {
            HttpResponse resp = HttpHelper.processHttpRequest(context, get);
            if (resp != null) {
                StatusLine statusLine = resp.getStatusLine();
                int code = statusLine.getStatusCode();
                if (code == HttpStatus.SC_OK) {
                    data = HttpHelper.parserHttpResponseToString(resp);
                }
            }
        }
        HttpHelper.abortRequest(get);
        return data;
    }

    /**
     * 通过post方法访问一个http地址,获取其返回的字符串内容
     *
     * @param context
     * @param httpUrl http地址
     * @param values post的数据
     * @return 返回获取到的字符串,可能为null
     */
    public static final String getPostString(Context context, String httpUrl, HashMap<String, String> values)
    {
        String data = null;
        HttpPost post = HttpHelper.post(httpUrl, values);
        if (post != null) {
            HttpResponse resp = HttpHelper.processHttpRequest(context, post);
            if (resp != null) {
                StatusLine statusLine = resp.getStatusLine();
                int code = statusLine.getStatusCode();
                if (code == HttpStatus.SC_OK) {
                    data = HttpHelper.parserHttpResponseToString(resp);
                }
            }
        }
        HttpHelper.abortRequest(post);
        return data;
    }

    /**
     * 通过post方法访问一个http地址,获取其返回的http状态码和字符串内容
     *
     * @param context
     * @param returnData byte数组缓存,获取到的数据将存放到该缓存中
     * @param httpUrl http地址
     * @param postData post的数据
     */
    public static final String postString(Context context, String httpUrl, String postData)
    {
        String data = null;
        HttpPost post = HttpHelper.post(httpUrl, postData);
        if (post != null) {
            HttpResponse resp = HttpHelper.processHttpRequest(context, post);
            if (resp != null) {
                StatusLine statusLine = resp.getStatusLine();
                int code = statusLine.getStatusCode();
                if (code == HttpStatus.SC_OK) {
                    data = HttpHelper.parserHttpResponseToString(resp);
                }
            }
        }
        HttpHelper.abortRequest(post);
        return data;
    }

    /**
     * 上传文件到服务端。
     *
     * @param httpUrl
     * @param values
     * @return
     * @throws UploadException
     */
    public static final String postStream(Context context, String httpUrl, HashMap<String, Object> values)
    {
        String returnStr = null;
        HttpPost post = HttpHelper.postStream(httpUrl, values);

        HttpResponse response = HttpHelper.processHttpRequest(context, post);
        StatusLine statusLine = response.getStatusLine();
        int code = statusLine.getStatusCode();
        if (code == HttpStatus.SC_OK) {
            returnStr = HttpHelper.parserHttpResponseToString(response);
        }
        HttpHelper.abortRequest(post);
        return returnStr;
    }

}


text:
"""
glashammer.utils.lazysettings
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Lazy descriptor.

:copyright: 2009, The Glashammer Authors
:license: MIT
"""

class LazySettings(object):
    """A lazy settings store that is filled on application setup. Works as a
    descriptor."""

    def __init__(self, application=None):
        """Accepts an application. Can be bound later with bind()."""
        self.application = application

    def bind(self, application):
        self.application = application

    def __getitem__(self, name):
        try:
            value = self.application.cfg[name]
        except AttributeError:
            raise RuntimeError("Application setup did not complete.")
        except KeyError:
            raise RuntimeError("Configuration was not set up properly. Key %r"
                               " not found!" % name)

        return value


text:
@interface NSDictionary (MRLayoutItemReadable)

@end

@interface NSMutableDictionary (MRLayoutItemWriteable)

@end


text:
/**
 * angular2-google-maps - Angular 2 components for Google Maps
 * @version v0.15.0
 * @link https://github.com/SebastianM/angular2-google-maps#readme
 * @license MIT
 */
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require('@angular/core');
var Observable_1 = require('rxjs/Observable');
var maps_api_loader_1 = require('./maps-api-loader/maps-api-loader');
/**
 * Wrapper class that handles the communication with the Google Maps Javascript
 * API v3
 */
var GoogleMapsAPIWrapper = (function () {
    function GoogleMapsAPIWrapper(_loader, _zone) {
        var _this = this;
        this._loader = _loader;
        this._zone = _zone;
        this._map =
            new Promise(function (resolve) { _this._mapResolver = resolve; });
    }
    GoogleMapsAPIWrapper.prototype.createMap = function (el, mapOptions) {
        var _this = this;
        return this._loader.load().then(function () {
            var map = new google.maps.Map(el, mapOptions);
            _this._mapResolver(map);
            return;
        });
    };
    GoogleMapsAPIWrapper.prototype.setMapOptions = function (options) {
        this._map.then(function (m) { m.setOptions(options); });
    };
    /**
     * Creates a google map marker with the map context
     */
    GoogleMapsAPIWrapper.prototype.createMarker = function (options) {
        if (options === void 0) { options = {}; }
        return this._map.then(function (map) {
            options.map = map;
            return new google.maps.Marker(options);
        });
    };
    GoogleMapsAPIWrapper.prototype.createInfoWindow = function (options) {
        return this._map.then(function () { return new google.maps.InfoWindow(options); });
    };
    /**
     * Creates a google.map.Circle for the current map.
     */
    GoogleMapsAPIWrapper.prototype.createCircle = function (options) {
        return this._map.then(function (map) {
            options.map = map;
            return new google.maps.Circle(options);
        });
    };
    GoogleMapsAPIWrapper.prototype.createPolyline = function (options) {
        return this.getNativeMap().then(function (map) {
            var line = new google.maps.Polyline(options);
            line.setMap(map);
            return line;
        });
    };
    GoogleMapsAPIWrapper.prototype.subscribeToMapEvent = function (eventName) {
        var _this = this;
        return Observable_1.Observable.create(function (observer) {
            _this._map.then(function (m) {
                m.addListener(eventName, function (arg) { _this._zone.run(function () { return observer.next(arg); }); });
            });
        });
    };
    GoogleMapsAPIWrapper.prototype.setCenter = function (latLng) {
        return this._map.then(function (map) { return map.setCenter(latLng); });
    };
    GoogleMapsAPIWrapper.prototype.getZoom = function () { return this._map.then(function (map) { return map.getZoom(); }); };
    GoogleMapsAPIWrapper.prototype.getBounds = function () {
        return this._map.then(function (map) { return map.getBounds(); });
    };
    GoogleMapsAPIWrapper.prototype.setZoom = function (zoom) {
        return this._map.then(function (map) { return map.setZoom(zoom); });
    };
    GoogleMapsAPIWrapper.prototype.getCenter = function () {
        return this._map.then(function (map) { return map.getCenter(); });
    };
    GoogleMapsAPIWrapper.prototype.panTo = function (latLng) {
        return this._map.then(function (map) { return map.panTo(latLng); });
    };
    GoogleMapsAPIWrapper.prototype.fitBounds = function (latLng) {
        return this._map.then(function (map) { return map.fitBounds(latLng); });
    };
    GoogleMapsAPIWrapper.prototype.panToBounds = function (latLng) {
        return this._map.then(function (map) { return map.panToBounds(latLng); });
    };
    /**
     * Returns the native Google Maps Map instance. Be careful when using this instance directly.
     */
    GoogleMapsAPIWrapper.prototype.getNativeMap = function () { return this._map; };
    /**
     * Triggers the given event name on the map instance.
     */
    GoogleMapsAPIWrapper.prototype.triggerMapEvent = function (eventName) {
        return this._map.then(function (m) { return google.maps.event.trigger(m, eventName); });
    };
    GoogleMapsAPIWrapper = __decorate([
        core_1.Injectable(),
        __metadata('design:paramtypes', [maps_api_loader_1.MapsAPILoader, core_1.NgZone])
    ], GoogleMapsAPIWrapper);
    return GoogleMapsAPIWrapper;
}());
exports.GoogleMapsAPIWrapper = GoogleMapsAPIWrapper;

//# sourceMappingURL=google-maps-api-wrapper.js.map


text:
var assert = require('assert');
const parser = require('../src/index');

// NOTICE:
// reference link: http://www.ecma-international.org/ecma-262/7.0/index.html#sec-automatic-semicolon-insertion

describe('automatic semicolon insertion', function() {
  describe('rules of automatic semicolon insertion', function() {
    it(`{ 1 2 } 3`, function(done) {
      try {
        const ast = parser.parse('{ 1 2 } 3');
        assert.equal(true, false);
      } catch(ex) {
        assert.equal(true, ex instanceof Error);
      }
      done();
    });

    it(`{ 1\n2 } 3\n => { 1\n;2 ;} 3;`, function(done) {
      const ast = parser.parse('{ 1\n2 } 3\n');

      assert.equal('BlockStatement', ast.body[0].type);
      assert.equal('ExpressionStatement', ast.body[0].body[0].type);
      assert.equal('Literal', ast.body[0].body[0].expression.type);
      assert.equal(1, ast.body[0].body[0].expression.value);
      assert.equal(2, ast.body[0].body[1].expression.value);
      assert.equal('ExpressionStatement', ast.body[1].type);
      assert.equal(3, ast.body[1].expression.value);

      assert.equal(2, ast.body[0].body[0].range[0]);
      assert.equal(3, ast.body[0].body[0].range[1]);

      assert.equal(2, ast.body[0].body[0].expression.range[0]);
      assert.equal(3, ast.body[0].body[0].expression.range[1]);

      assert.equal(4, ast.body[0].body[1].range[0]);
      assert.equal(5, ast.body[0].body[1].range[1]);

      assert.equal(4, ast.body[0].body[1].expression.range[0]);
      assert.equal(5, ast.body[0].body[1].expression.range[1]);

      assert.equal(8, ast.body[1].expression.range[0]);
      assert.equal(9, ast.body[1].expression.range[1]);
      assert.equal(8, ast.body[1].range[0]);
      assert.equal(9, ast.body[1].range[1]);
      done();
    });

    it(`for (a; b\n)`, function(done) {
      try {
        const ast = parser.parse('for (a; b\n)\n');
        assert.equal(true, false);
      } catch(ex) {
        assert.equal(true, ex instanceof Error);
      }
      done();
    });

    it(`for (a; b\n);`, function(done) {
      try {
        const ast = parser.parse('for (a; b\n);\n');
        assert.equal(true, false);
      } catch(ex) {
        assert.equal(true, true);
        // assert.equal(`semicolon can't become one of the two semicolons in the header of a for statement`, ex.message);
      }
      done();
    });

    it('no LineTerminator here', function(done) {
      const ast = parser.parse('function foo() {\n  return\n  a + b\n}');
      assert.equal('FunctionDeclaration', ast.body[0].type);

      assert.equal(0, ast.body[0].range[0]);
      assert.equal(35, ast.body[0].range[1]);

      assert.equal('foo', ast.body[0].id.name);
      assert.equal(9, ast.body[0].id.range[0]);
      assert.equal(12, ast.body[0].id.range[1]);

      assert.equal(0, ast.body[0].params.length);
      assert.equal(2, ast.body[0].body.length);

      assert.equal(19, ast.body[0].body[0].range[0]);
      assert.equal(25, ast.body[0].body[0].range[1]);
      assert.equal('ReturnStatement', ast.body[0].body[0].type);
      assert.equal(null, ast.body[0].body[0].params);

      assert.equal(28, ast.body[0].body[1].range[0]);
      assert.equal(33, ast.body[0].body[1].range[1]);
      assert.equal('ExpressionStatement', ast.body[0].body[1].type);
      assert.equal('AdditiveExpression', ast.body[0].body[1].expression.type);
      assert.equal(28, ast.body[0].body[1].expression.range[0]);
      assert.equal(33, ast.body[0].body[1].expression.range[1]);
      assert.equal('+', ast.body[0].body[1].expression.operator);
      assert.equal(28, ast.body[0].body[1].expression.left.range[0]);
      assert.equal(29, ast.body[0].body[1].expression.left.range[1]);
      assert.equal('a', ast.body[0].body[1].expression.left.name);

      assert.equal(32, ast.body[0].body[1].expression.right.range[0]);
      assert.equal(33, ast.body[0].body[1].expression.right.range[1]);
      assert.equal('b', ast.body[0].body[1].expression.right.name);
      done();
    });

    it('LineTerminator occurs between identifier and ++.', function(done) {
      const ast = parser.parse('a = b\n++c\n');
      assert.equal('ExpressionStatement', ast.body[0].type);
      assert.equal(0, ast.body[0].range[0]);
      assert.equal(5, ast.body[0].range[1]);
      assert.equal(0, ast.body[0].expression.range[0]);
      assert.equal(5, ast.body[0].expression.range[1]);

      assert.equal('a', ast.body[0].expression.left.name);
      assert.equal(0, ast.body[0].expression.left.range[0]);
      assert.equal(1, ast.body[0].expression.left.range[1]);

      assert.equal('b', ast.body[0].expression.right.name);
      assert.equal(4, ast.body[0].expression.right.range[0]);
      assert.equal(5, ast.body[0].expression.right.range[1]);

      assert.equal('=', ast.body[0].expression.operator);

      assert.equal('ExpressionStatement', ast.body[1].type);
      assert.equal(6, ast.body[1].range[0]);
      assert.equal(9, ast.body[1].range[1]);
      assert.equal(true, ast.body[1].expression.prefix);

      assert.equal(6, ast.body[1].expression.range[0]);
      assert.equal(9, ast.body[1].expression.range[1]);

      assert.equal(8, ast.body[1].expression.operand.range[0]);
      assert.equal(9, ast.body[1].expression.operand.range[1]);

      assert.equal('++', ast.body[1].expression.operator);
      assert.equal('UpdateExpression', ast.body[1].expression.type);
      assert.equal('c', ast.body[1].expression.operand.name);

      done();
    });

    it('an automatically inserted semicolon would then be parsed as an empty statement.', function(done) {
      try {
        const ast = parser.parse('if (a > b)\nelse c = d\n');
        assert.equal(true, false);
      } catch (ex) {
        assert.equal(true, ex instanceof Error);
      }
      done();
    });

    it(`a = b + c\n(d + e).print()`, function(done) {
      const ast = parser.parse('a = b + c\n(d + e).print()\n\na\n');
      assert.equal('ExpressionStatement', ast.body[0].type);

      assert.equal(0, ast.body[0].range[0]);
      assert.equal(25, ast.body[0].range[1]);

      assert.equal('AssignmentExpression', ast.body[0].expression.type);
      assert.equal(0, ast.body[0].expression.range[0]);
      assert.equal(25, ast.body[0].expression.range[1]);

      assert.equal(0, ast.body[0].expression.left.range[0]);
      assert.equal(1, ast.body[0].expression.left.range[1]);
      assert.equal('Identifier', ast.body[0].expression.left.type);
      assert.equal('a', ast.body[0].expression.left.name);

      assert.equal(4, ast.body[0].expression.right.range[0]);
      assert.equal(25, ast.body[0].expression.right.range[1]);
      assert.equal('AdditiveExpression', ast.body[0].expression.right.type);
      assert.equal('+', ast.body[0].expression.right.operator);

      assert.equal(4, ast.body[0].expression.right.left.range[0]);
      assert.equal(5, ast.body[0].expression.right.left.range[1]);
      assert.equal('b', ast.body[0].expression.right.left.name);

      assert.equal(8, ast.body[0].expression.right.right.range[0]);
      assert.equal(25, ast.body[0].expression.right.right.range[1]);
      assert.equal('CallExpression', ast.body[0].expression.right.right.type);

      assert.equal('MemberExpression', ast.body[0].expression.right.right.callee.type);

      assert.equal(8, ast.body[0].expression.right.right.callee.range[0]);
      assert.equal(23, ast.body[0].expression.right.right.callee.range[1]);
      assert.equal('CallExpression', ast.body[0].expression.right.right.callee.element.type);

      assert.equal(8, ast.body[0].expression.right.right.callee.element.callee.range[0]);
      assert.equal(9, ast.body[0].expression.right.right.callee.element.callee.range[1]);
      assert.equal('c', ast.body[0].expression.right.right.callee.element.callee.name);

      assert.equal(1, ast.body[0].expression.right.right.callee.element.params.length);
      assert.equal(11, ast.body[0].expression.right.right.callee.element.params[0].range[0]);
      assert.equal(16, ast.body[0].expression.right.right.callee.element.params[0].range[1]);
      assert.equal('AdditiveExpression', ast.body[0].expression.right.right.callee.element.params[0].type);
      assert.equal('+', ast.body[0].expression.right.right.callee.element.params[0].operator);

      assert.equal(11, ast.body[0].expression.right.right.callee.element.params[0].left.range[0]);
      assert.equal(12, ast.body[0].expression.right.right.callee.element.params[0].left.range[1]);
      assert.equal('d', ast.body[0].expression.right.right.callee.element.params[0].left.name);

      assert.equal(15, ast.body[0].expression.right.right.callee.element.params[0].right.range[0]);
      assert.equal(16, ast.body[0].expression.right.right.callee.element.params[0].right.range[1]);
      assert.equal('e', ast.body[0].expression.right.right.callee.element.params[0].right.name);

      assert.equal(18, ast.body[0].expression.right.right.callee.property.range[0]);
      assert.equal(23, ast.body[0].expression.right.right.callee.property.range[1]);
      assert.equal('Identifier', ast.body[0].expression.right.right.callee.property.type);
      assert.equal('print', ast.body[0].expression.right.right.callee.property.name);
      done();
    });

    it('LineTerminator occurs between identifier and ++ with comments', function(done) {
      const ast = parser.parse('a = b\n/*some comment 1*/\n/*some comment 2*/++c\n');
      assert.equal('ExpressionStatement', ast.body[0].type);
      assert.equal('AssignmentExpression', ast.body[0].expression.type);

      assert.equal('=', ast.body[0].expression.operator);
      assert.equal('a', ast.body[0].expression.left.name);
      assert.equal('b', ast.body[0].expression.right.name);

      assert.equal('UpdateExpression', ast.body[1].expression.type);
      assert.equal('++', ast.body[1].expression.operator);
      assert.equal('c', ast.body[1].expression.operand.name);
      assert.equal(2, ast.body[1].leadingComments.length);

      assert.equal('some comment 1', ast.body[1].leadingComments[0].value);
      assert.equal('some comment 2', ast.body[1].leadingComments[1].value);

      done();
    });

  });
});


text:
git config --global alias.d 'diff --color'
git config --global alias.a 'add -u'

git config --global alias.co checkout
git config --global alias.ci commit
git config --global alias.ca 'commit --amend'
git config --global alias.br branch
git config --global alias.st status
git config --global alias.hs 'log --pretty=format:"%h %ad | %s%d [%an]" --graph --date=short'
git config --global alias.hist 'log --pretty=format:"%h %ad | %s%d [%an]" --graph --date=short'
git config --global alias.type 'cat-file -t'
git config --global alias.dump 'cat-file -p'

git config --global alias.unstage 'reset HEAD --'
git config --global alias.last 'log -1 HEAD'

# pretty well format of git history
git config --global alias.g 'log --oneline --graph --all --decorate'
git config --global alias.graph 'log --oneline --graph --all --decorate'
# more graph, provide more information
git config --global alias.mg 'log --graph --all --decorate'

# editor: use vim
git config --global core.editor vim

# turn off SSL verification
# this can workaround "server certificate verification failed" problem
# git config --global http.sslVerify false


text:
<?php

$Writeyourreviews = Writeyourreviews::model()->findAll(array('condition'=>'status = 1',
							'order' => 'created DESC',
							'limit' => 5
						));

?>
<?php if ( isset($Writeyourreviews) && count($Writeyourreviews)>0 ) { ?>

<img alt="Recent Reviews" src="<?php echo $layout_asset; ?>/images/articles-reviews-icon.png"> <?php echo t('Recent Reviews'); ?>

      <?php foreach ( $Writeyourreviews as $Writeyourreviews) { ?>
      <a href="<?php echo Yii::app()->createUrl('reviews')?>">

<?php echo Temples::GetName($Writeyourreviews->parent); ?>

      <?php } ?>

<?php } ?>