text:
[TBD: The philosophy of concentrating on recognizing, not memorizing]

* [TBD: Dash]
* [TBD: A few notes about Stack Overflow]
* [TBD: man pages]

## Network testing

* Httpie
* Curl
* whois
* dig
* traceroute
* ping

## Git and GitHub

### How Git Works

**The #1, most important thing to know about git is how it works.**

Git is a linked list of commits. Here's a simple linked list:

![Linked list](http://goose.ycp.edu/~dhovemey/fall2011/cs201/lecture/figures/sll.png)

> If this makes perfect sense to you, then you can skip this section. Otherwise, keep reading; **do not** go on until you understand what this means.

[TBD: show git commits as linked list in various forms]

As Philip Nilsson writes, [learning to expertly use Git means learning how to manipulate that data structure](http://www.jayway.com/2013/03/03/git-is-a-purely-functional-data-structure/).

### Essential Git Tools

* An up-to-date Git via Homebrew (Mac) or aptitude (Ubuntu)
* [lol and lola aliases](http://blog.kfish.org/2010/04/git-lola.html)
* gitsh
* Git Desktop

## A Good Text Editor

### The VIM and Emacs Story

[TBD]

### The Super-Editors: Atom, Sublime Text, and Brackets

### Atom

**Recommended Packages**
* file-icons
* git-projects
* terminal-plus
* highlight-selected


text:
package model.persisted

import play.api.libs.json.Format
import play.api.libs.json._
import play.api.libs.functional.syntax._

case class ReferenceData[T](options: List[T], default: T, aggregate: T) {
  val allValues: Set[T] = (aggregate :: options).toSet
}

object ReferenceData {

  // default formatter does not work for generic types, has to define fields manually...
  implicit def referenceDataFormat[T : Format]: Format[ReferenceData[T]] =
    ((__ \ "options").format[List[T]] ~
      (__ \ "default").format[T] ~
      (__ \ "aggregate").format[T]
      )(ReferenceData.apply, unlift(ReferenceData.unapply))
}

redpajama_set_name: RedPajamaGithub


text:
		<iframe id="frame_preview" name="frame_preview" style="<?php echo $iframeStyle?>">

	<form id="form_preview_slide" name="form_preview_slide" action="" target="frame_preview" method="post">
		<input type="hidden" name="client_action" value="preview_slide">
		<input type="hidden" name="data" value="" id="preview_slide_data">
		<input type="hidden" id="preview_slide_nonce" name="nonce" value="">
	</form>


text:
<?php

namespace yii2tech\tests\unit\install;

use yii\validators\RequiredValidator;
use yii2tech\install\LocalFilePlaceholder;

/**
 * Test case for the extension "yii2tech\install\LocalFilePlaceholder".
 * @see LocalFilePlaceholder
 */
class LocalFilePlaceholderTest extends TestCase
{
    /**
     * Creates test model.
     * @return LocalFilePlaceholder model instance.
     */
    protected function createTestModel()
    {
        $model = new LocalFilePlaceholder('', []);
        return $model;
    }

    // Tests :

    public function testLabel()
    {
        $model = $this->createTestModel();

        $name = 'TestPlaceholderName';
        $model->name = $name;

        $this->assertEquals($name, $model->getAttributeLabel('value'), 'Wrong value label!');
    }

    public function testSetupRules()
    {
        $model = $this->createTestModel();
        $model->default = 'test default';

        $validationRules = [
            ['required'],
        ];
        $model->setRules($validationRules);
        $validators = $model->getValidators();

        $this->assertEquals(count($validationRules), $validators->count(), 'Unable to set validation rules!');

        $validator = $validators->offsetGet(0);
        $this->assertTrue($validator instanceof RequiredValidator, 'Wrong validator created!');
    }

    /**
     * @depends testSetupRules
     */
    public function testAutoRequiredRule()
    {
        $model = $this->createTestModel();
        $model->default = null;

        $validators = $model->getValidators();

        $this->assertEquals(1, $validators->count(), 'Unable to automatically add validator!');

        $validator = $validators->offsetGet(0);
        $this->assertTrue($validator instanceof RequiredValidator, 'Wrong validator created!');
    }

    /**
     * Data provider for {@link testGetActualValue}
     * @return array test data
     */
    public function dataProviderGetActualValue()
    {
        return [
            [
                'string',
                'test_value',
                'test_value',
            ],
            [
                'boolean',
                '1',
                'true',
            ],
            [
                'boolean',
                '0',
                'false',
            ],
            [
                'boolean',
                'true',
                'true',
            ],
            [
                'boolean',
                'false',
                'false',
            ],
        ];
    }

    /**
     * @dataProvider dataProviderGetActualValue
     *
     * @param string $type
     * @param mixed $value
     * @param mixed $expectedActualValue
     */
    public function testGetActualValue($type, $value, $expectedActualValue)
    {
        $model = $this->createTestModel();

        $model->type = $type;
        $model->value = $value;

        $this->assertEquals($expectedActualValue, $model->getActualValue());
    }

    /**
     * @depends testGetActualValue
     */
    public function testGetDefaultValue()
    {
        $model = $this->createTestModel();

        $defaultValue = 'test_default_value';
        $model->default = $defaultValue;

        $this->assertEquals($defaultValue, $model->getActualValue(), 'Unable to get default value!');

        $model->default = null;
        $this->expectException('\yii\base\Exception');
        $model->getActualValue();
    }
}


text:
package com.olddriver.ui;

import android.app.Application;

import com.olddriver.data.AVService;
import com.orhanobut.logger.LogLevel;
import com.orhanobut.logger.Logger;

/**
 * @author Danny
 * @ClassName: XXXX
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @date
 */
public class App extends Application {
    public static final String DETAIL_ID = "detailId";
    @Override
    public void onCreate() {
        super.onCreate();
        Logger.init("OD");
        AVService.AVInit(this);
    }
}


text:
<?php

namespace Gomoob\FacebookMessenger\Model\Message;

use Gomoob\FacebookMessenger\Exception\FacebookMessengerException;
use Gomoob\FacebookMessenger\Model\VideoAttachmentMessageInterface;
use Gomoob\FacebookMessenger\Model\Attachment\VideoAttachment;

/**
 * Class which represents a a Facebook Messenger video attachment message.
 *
 * @author Baptiste GAILLARD (baptiste.gaillard@gomoob.com)
 * @see https://developers.facebook.com/docs/messenger-platform/send-api-reference/video-attachment
 */
class VideoAttachmentMessage extends AbstractAttachmentMessage implements VideoAttachmentMessageInterface
{
    /**
     * Utility function used to create a new instance of the <tt>VideoAttachmentMessage</tt> class.
     *
     * @return \Gomoob\FacebookMessenger\Model\Message\VideoAttachmentMessage the new created instance.
     */
    public static function create()
    {
        return new VideoAttachmentMessage();
    }

    /**
     * {@inheritDoc}
     */
    protected function doCheckAttachmentType(/* AttachmentInterface */ $attachment)
    {
        // The attachment must be an 'VideoAttachment'
        if (!($attachment instanceof VideoAttachment)) {
            throw new FacebookMessengerException(
                'The \'attachment\' associated to a video attachment message must be intance of class ' .
                '\'VideoAttachment\' !'
            );
        }
    }
}


text:
@RouteConfig('/server')
@Component({
  selector: 'server',
  template: `

        <md-button class="start-stop" ng-show="!vm.server.isRunning" ng-click="vm.startServer()">Start Server</md-button>
        <md-button class="start-stop md-primary" ng-show="vm.server.isRunning" ng-click="vm.stopServer()">Stop Server</md-button>
        <md-button class="start-stop" ng-click="vm.showInstallFolder()">
          <md-tooltip md-direction="bottom">Access your server config files and back them up before updating HEAT server</md-tooltip>
          Install Dir
        </md-button>
        <md-button class="start-stop" ng-click="vm.showUserDataFolder()">
          <md-tooltip md-direction="bottom">Access your user profile</md-tooltip>
          User Dir
        </md-button>

        <md-button ng-click="vm.editFailoverConfig()">
          <md-tooltip md-direction="bottom">Edit failover config</md-tooltip>
          Failover Config
        </md-button>

        <md-switch ng-model="vm.connectedToLocalhost" aria-label="Choose API connection" ng-change="vm.connectToLocalhostChanged()">
          <md-tooltip md-direction="top">
            Connect client API to remotehost or to your local machine
          </md-tooltip>
          Client API connected to {{ vm.connectedToLocalhost ? 'localhost' : vm.remotehostDisplay }}
        </md-switch>

          Remaining :
          {{vm.miningRemaining}}
          Deadline :
          {{vm.miningDeadline}}
          Hittime :
          {{vm.miningHittime}}

        <md-button ng-show="vm.user.unlocked&&!vm.isMining" ng-disabled="!vm.server.isReady" class="start-stop" ng-click="vm.startMining()">Start Mining</md-button>
        <md-button ng-show="vm.user.unlocked&&vm.isMining" ng-disabled="!vm.server.isReady" class="start-stop md-primary" ng-click="vm.stopMining()">Stop Mining</md-button>
        Sign in to start mining

        <md-virtual-repeat-container md-top-index="vm.topIndex" flex layout-fill layout="column"
            virtual-repeat-flex-helper id="server-console-container">

            {{item.message}}

              {{item.timestamp}} {{item.severity}} {{item.message}}

        </md-virtual-repeat-container>

  `
})
@Inject('$scope','server','heat','user','settings','$mdToast')
class ServerComponent {
  private ROW_HEIGHT = 12; // must match the `server .console pre { height: 12px }` style rule above

  private console: any;
  private onOutput: IEventListenerFunction;
  private calculatedTopIndex = 0;
  private topIndex = 0;
  private consoleRowCount = 0;
  private isMining = false;
  private miningRemaining: any = '*';
  private miningDeadline: any = '*';
  private miningHittime: any = '*';
  private hostLocal: string;
  private hostRemote: string;
  private portLocal: string;
  private portRemote: string;
  private connectedToLocalhost: boolean;
  private remotehostDisplay: string;

  /* 2017-01-27 23:22:30 INFO: Pushed block 13300804393767116009 with height 2925 */
  //private msgRegExp = /^([\d-]+\s[\d:]+)\s(\w+):\s(.*)/;

  /* 2017-04-01 19:00:17 [pool-5-thread-3] INFO c.heatledger.BlockchainProcessorImpl - Pushed block 4762652772805132303 at height 659 received 2017-03-18 06:27:42 from 37.139.25.98 */
  private msgRegExp = /^([\d-]+\s[\d:]+)\s(.+)\s-\s(.*)/;

  constructor(private $scope:angular.IScope,
              public server: ServerService,
              private heat: HeatService,
              private user: UserService,
              private settings: SettingsService,
              private $mdToast: angular.material.IToastService) {

    if (user.unlocked) {
      heat.subscriber.blockPushed({generator:user.account}, ()=>{this.updateMiningInfo()});
      heat.subscriber.blockPopped({generator:user.account}, ()=>{this.updateMiningInfo()});
    }
    else {
      let listener = () => { this.updateMiningInfo() };
      user.on(UserService.EVENT_UNLOCKED, listener);
      $scope.$on('$destroy',()=>user.removeListener(UserService.EVENT_UNLOCKED, listener));
    }

    this.hostLocal  = this.settings.get(SettingsService.HEAT_HOST_LOCAL);
    this.hostRemote = this.settings.get(SettingsService.HEAT_HOST_REMOTE);
    this.portLocal  = this.settings.get(SettingsService.HEAT_PORT_LOCAL);
    this.portRemote = this.settings.get(SettingsService.HEAT_PORT_REMOTE);
    this.connectedToLocalhost = this.isConnectedToLocalhost();

    //failover will choose this host by priority
    SettingsService.forceServerPriority(
      this.isConnectedToLocalhost() ? this.hostLocal : this.hostRemote,
      this.isConnectedToLocalhost() ? this.portLocal : this.portRemote
    );

    this.onOutput = () => {
      $scope.$evalAsync(()=> {
        this.calculatedTopIndex = this.determineTopIndex();
        if (!(this.topIndex < (this.calculatedTopIndex-5)) || this.consoleRowCount < this.getLength()) {
          this.topIndex = this.calculatedTopIndex;
        }
      })
    };
    server.addListener('output',this.onOutput);
    $scope.$on('$destroy',()=>{
      server.removeListener('output',this.onOutput);
    });
    this.updateMiningInfo();
    window.setTimeout(()=>{
      this.topIndex = this.determineTopIndex();
      this.onOutput();
    },3000);

    this.remotehostDisplay = this.hostRemote.replace('https://','');
  }

  showInstallFolder() {
    require('electron').shell.showItemInFolder(this.server.getAppDir('.'))
  }

  showUserDataFolder() {
    this.server.getUserDataDirFromMainProcess().then(
      userDataDir => {
        var path = require('path');
        let dir = path.join(userDataDir);
        require('electron').shell.showItemInFolder(path.resolve(dir))
      }
    )
  }

  editFailoverConfig() {
    // @ts-ignore
    const fs = require('fs');
    let filePath = 'failover-config.json';
    fs.readFile(filePath, (err, data) => {
      if (err) {
        console.log("Cannot load 'failover-config.json': " + err);
        throw err;
      }
      dialogs.textEditor("Failover Config", data, (editedData) => {
        fs.writeFile(filePath, editedData, (err) => {
          if (err) throw err;
          this.settings.applyFailoverConfig();
        });
      });
    });
  }

  /* md-virtual-repeat */
  getItemAtIndex(index) {
    return this.render(this.server.buffer[index]);
  }

  /* md-virtual-repeat */
  getLength() {
    return this.server.buffer.length;
  }

  connectToLocalhostChanged() {
    this.toggleConnectToLocalhost();
  }

  isConnectedToLocalhost(): boolean {
    return this.settings.get(SettingsService.HEAT_HOST) == this.hostLocal &&
           this.settings.get(SettingsService.HEAT_PORT) == this.portLocal;
  }

  toggleConnectToLocalhost() {
    var host = this.isConnectedToLocalhost() ? this.hostRemote : this.hostLocal;
    var port = this.isConnectedToLocalhost() ? this.portRemote : this.portLocal;
    this.settings.put(SettingsService.HEAT_HOST, host);
    this.settings.put(SettingsService.HEAT_PORT, port);
    SettingsService.forceServerPriority(host, port);  //failover will choose this host by priority
  }

  startServer() {
    this.server.startServer()
    this.$mdToast.show(this.$mdToast.simple().textContent("In some cases you need to Start the server A SECOND TIME!\n"+
      "Wheter that's the case is indicated at the end of the log output (the colored text with black background).").hideDelay(10000));
  }

  stopServer() {
    this.server.stopServer()
  }

  determineRowCount() {
    var el = document.getElementById('server-console-container');
    return Math.round(el.clientHeight / this.ROW_HEIGHT);
  }

  determineTopIndex() {
    this.consoleRowCount = this.determineRowCount();
    return Math.max(0, this.getLength()-this.consoleRowCount+2);
  }

  /* msg is a string object from server service buffer. when asked for again we return the same instance */
  render(msg) {
    if (angular.isUndefined(msg))
      return msg;
    if (angular.isUndefined(msg.rendered)) {
      var match = this.msgRegExp.exec(msg);
      msg.rendered = match ? { timestamp: match[1], severity: match[2], message: match[3] } : { message: msg };
    }
    return msg.rendered;
  }

  startMining() {
    this.heat.api.startMining(this.user.secretPhrase).then((info) => {
      this.updateMiningInfo();
    });
  }

  stopMining() {
    this.heat.api.stopMining(this.user.secretPhrase).then((info) => {
      this.updateMiningInfo();
    });
  }

  updateMiningInfo() {
    if (this.user.unlocked) {
      this.heat.api.getMiningInfo(this.user.secretPhrase).then((info)=> {
        this.$scope.$evalAsync(() => {
          if (info[0]) {
            this.isMining = true;
            this.miningRemaining = info[0].remaining;
            this.miningDeadline = info[0].deadline;
            this.miningHittime = info[0].hitTime;
          }
          else {
            this.isMining = false;
          }
        })
      }, () => {
        this.$scope.$evalAsync(() => {
          this.isMining = false;
        });
      });
    }
  }
}


text:
package template

import (
	"fmt"
	"html/template"
	"io"
)

// FuncMap is a convenience type that mirrors the FuncMap type in html/template
type FuncMap template.FuncMap

// HTML is another convenience type that mirrors the HTML type in html/template
// (http://golang.org/src/html/template/content.go?h=HTML#L120)
type HTML template.HTML

// AssetFunc is the function that go-bindata generates to look up a file
// by name
type AssetFunc func(string) ([]byte, error)

// Must is a helper that wraps a call to a function returning
// (*Template, error) and panics if the error is non-nil. It is intended for
// use in variable initializations such as
//	var t = template.Must(template.New("name").Parse("templates/my.tmpl"))
func Must(t *Template, err error) *Template {
	if err != nil {
		panic(fmt.Sprintf("template error: %s", err))
	}
	if t == nil {
		panic(fmt.Sprintf("template was nil"))
	}
	return t
}

// Template is a wrapper around a Template (from html/template). It reads
// template file contents from a function instead of the filesystem.
type Template struct {
	AssetFunc AssetFunc
	tmpl      *template.Template
}

// New creates a new Template with the given name. It stores
// the given Asset() function for use later.
// Example usage:
//  tmpl := template.New("mytmpl", Asset) //Asset is the function that go-bindata generated for you
//
func New(name string, fn AssetFunc) *Template {
	return &Template{fn, template.New(name)}
}

// Name gets the name that was passed in the New function
func (t *Template) Name() string {
	return t.tmpl.Name()
}

// Funcs is a proxy to the underlying template's Funcs function
func (t *Template) Funcs(funcMap FuncMap) *Template {
	return t.replaceTmpl(t.tmpl.Funcs(template.FuncMap(funcMap)))
}

//Delims is a proxy to the underlying template's Delims function
func (t *Template) Delims(left, right string) *Template {
	return t.replaceTmpl(t.tmpl.Delims(left, right))
}

// Parse looks up the filename in the underlying Asset store,
// then calls the underlying template's Parse function with the result.
// returns an error if the file wasn't found or the Parse call failed
func (t *Template) Parse(filename string) (*Template, error) {
	tmplBytes, err := t.file(filename)
	if err != nil {
		return nil, err
	}
	newTmpl, err := t.tmpl.Parse(string(tmplBytes))
	if err != nil {
		return nil, err
	}
	return t.replaceTmpl(newTmpl), nil
}

// ParseFiles looks up all of the filenames in the underlying Asset store,
// concatenates the file contents together, then calls the underlying template's
// Parse function with the result. returns an error if any of the files
// don't exist or the underlying Parse call failed.
func (t *Template) ParseFiles(filenames ...string) (*Template, error) {
	fileBytes := []byte{}
	for _, filename := range filenames {
		tmplBytes, err := t.file(filename)
		if err != nil {
			return nil, err
		}
		fileBytes = append(fileBytes, tmplBytes...)
	}
	newTmpl, err := t.tmpl.Parse(string(fileBytes))
	if err != nil {
		return nil, err
	}
	return t.replaceTmpl(newTmpl), nil
}

// Execute is a proxy to the underlying template's Execute function
func (t *Template) Execute(w io.Writer, data interface{}) error {
	return t.tmpl.Execute(w, data)
}

// ExecuteTemplate is a proxy to the underlying template's ExecuteTemplate function
func (t *Template) ExecuteTemplate(w io.Writer, name string, data interface{}) error {
	return t.tmpl.ExecuteTemplate(w, name, data)
}

// replaceTmpl is a convenience function to replace t.tmpl with the given tmpl
func (t *Template) replaceTmpl(tmpl *template.Template) *Template {
	t.tmpl = tmpl
	return t
}

// file is a convenience function to look up fileName using t.AssetFunc, then
// return the contents or an error if the file doesn't exist
func (t *Template) file(fileName string) ([]byte, error) {
	tmplBytes, err := t.AssetFunc(fileName)
	if err != nil {
		return nil, err
	}
	return tmplBytes, nil
}


text:
describe HipchatSearcher::SearchProxy::Simple do
  def searcher(pattern, result, options={})
    described_class.new(pattern, result, options)
  end

  describe '#before?' do
    context 'when no "date" option' do
      subject { searcher("hoge", double(:result)).before?("2014-07-13") }

      it { should be_falsy }
    end

    context 'when argument is nil' do
      subject { searcher("hoge", double(:result)).before?(nil) }

      it { should be_falsy }
    end

    context 'when option date is later than argument date' do
      subject { searcher("hoge", double(:result), date: "2014-07-13").before?("2014-07-10") }

      it { should be_truthy }
    end

    context 'when option date is equal to argument date ' do
      subject { searcher("hoge", double(:result), date: "2014-07-13").before?("2014-07-13") }

      it { should be_falsy }
    end

    context 'when option date is newer than argument date ' do
      subject { searcher("hoge", double(:result), date: "2014-07-13").before?("2014-07-20") }

      it { should be_falsy }
    end
  end

  describe '#items' do
    subject { searcher(pattern, result).items }

    let(:pattern) { 'hoge' }
    let(:result) do
      response = File.read(File.join('spec', 'data', 'item-list.json'))
      HipchatSearcher::Result.new(response)
    end

    it { should be_instance_of Array }

    it 'should return array with Hashie::Mash objects' do
      subject.first.should be_instance_of ::Hashie::Mash
      subject.last.should  be_instance_of ::Hashie::Mash
    end
  end

  describe '#search' do
    context 'when matches pattern in messages' do
      subject { searcher(pattern, result).search }

      let(:pattern)  { 'yare' }
      let(:result) do
        response = File.read(File.join('spec', 'data', 'item-list.json'))
        HipchatSearcher::Result.new(response).tap do |r|
          r.room = "Joestars"
        end
      end
      let(:search_result) do
        "\e[4;39;49mJoestars\e[0m" + "\n" + \
        "  Date: 2014-05-30T01:38:16.741565+00:00" + "\n" + \
        "  @jotaro: \e[0;31;49myare\e[0m\e[0;31;49myare\e[0m daze" + "\n" + \
        "\n"
      end

      it 'should print roomname & search result' do
        expect do
          subject
        end.to output(search_result).to_stdout
      end
    end

    context 'when matches pattern in many messages' do
      subject { searcher(pattern, result).search }

      let(:pattern)  { 'ze' }
      let(:result) do
        response = File.read(File.join('spec', 'data', 'item-list.json'))
        HipchatSearcher::Result.new(response).tap do |r|
          r.room = "Joestars"
        end
      end
      let(:search_result) do
        "\e[4;39;49mJoestars\e[0m" + "\n" + \
        "  Date: 2014-06-09T11:29:10.209014+00:00" + "\n" + \
        "  @polnareff: a... arinomama ima okotta koto wo hanasu \e[0;31;49mze\e[0m" + "\n" + \
        "\n" + \
        "  Date: 2014-05-30T01:38:16.741565+00:00" + "\n" + \
        "  @jotaro: yareyare da\e[0;31;49mze\e[0m" + "\n" \
        "\n"
      end

      it 'should print roomname & search result' do
        expect do
          subject
        end.to output(search_result).to_stdout
      end
    end

    context 'when you specify option date and include item date no later than this date' do
      subject { searcher(pattern, result, date: '2014-06-10').search }

      let(:pattern) { 'ze' }
      let(:result) do
        response = File.read(File.join('spec', 'data', 'item-list-with-overlap.json'))
        HipchatSearcher::Result.new(response).tap do |r|
          r.room = "Joestars"
        end
      end

      let(:search_result) do
        "\e[4;39;49mJoestars\e[0m" + "\n" + \
        "  Date: 2014-06-11T19:20:47.726182+00:00" + "\n" + \
        "  @lggy: inu zuki no kodomo ha migoroshiniha dekine-\e[0;31;49mze\e[0m" + "\n" + \
        "\n"
      end

      it 'should print the matched message since option date' do
        expect do
          subject
        end.to output(search_result).to_stdout
      end
    end

    context "when don't match pattern in messages" do
      subject { searcher(pattern, result).search }

      let(:pattern) { 'abcd' }
      let(:result) do
        response = File.read(File.join('spec', 'data', 'item-list.json'))
        HipchatSearcher::Result.new(response)
      end

      it { should be_nil }

      it 'should no output to stdout' do
        expect do
          subject
        end.to output('').to_stdout
      end
    end

    context "when pattern can't convert regexp" do
      subject { searcher(pattern, result).search }

      let(:pattern) { nil }
      let(:result) do
        response = File.read(File.join('spec', 'data', 'item-list.json'))
        HipchatSearcher::Result.new(response)
      end

      it 'should raise exception' do
        expect do
          subject
        end.to raise_error
      end
    end
  end

  describe '#puts_search_result' do
    def extended_items(path, pattern)
      hash  = JSON.parse(File.read(path))
      items = ::Hashie::Mash.new(hash).items
      items.map do |itm|
        itm.extend(HipchatSearcher::ItemExtention).tap do |i|
          i.pattern = Regexp.new(pattern)
        end
      end
    end

    context 'when only person in room' do
      subject { searcher(pattern, result).puts_search_result(item) }

      let(:pattern) { 'yare' }
      let(:result)  { double(:result, room: 'Joestars') }
      let(:item) do
        path = File.join('spec', 'data', 'item-list.json')
        extended_items(path, pattern).first
      end

      let(:search_result) do
        "\e[4;39;49mJoestars\e[0m" + "\n" + \
        "  Date: 2014-05-30T01:38:16.741565+00:00" + "\n" + \
        "  @jotaro: \e[0;31;49myare\e[0m\e[0;31;49myare\e[0m daze" + "\n" + \
        "\n"
      end

      it 'should print message of search result' do
        expect do
          subject
        end.to output(search_result).to_stdout
      end
    end

    context 'when person and bot in room' do
      subject { searcher(pattern, result).puts_search_result(item) }

      let(:pattern) { 'mgi166' }
      let(:result)  { double(:result, room: 'Joestars') }
      let(:item) do
        path = File.join('spec', 'data', 'item-list-with-bot.json')
        extended_items(path, pattern).first
      end

      let(:search_result) do
        "\e[4;39;49mJoestars\e[0m" + "\n" + \
        '  Date: 2014-06-17T08:14:48.305590+00:00' + "\n" + \
        "  @GitHub: \e[0;31;49mmgi166\e[0m commented on pull request 118 ..." + "\n\n"
      end

      it 'should print message of search result' do
        expect do
          subject
        end.to output(search_result).to_stdout
      end
    end

    context "when user options specified but the user don't speak this message" do
      subject { searcher(pattern, result, user: 'jotaro').puts_search_result(item) }

      let(:pattern) { 'ze' }
      let(:result)  { double(:result, room: 'Joestars') }
      let(:item) do
        path = File.join('spec', 'data', 'item-list.json')
        extended_items(path, pattern).last
      end

      it 'should not print message' do
        expect do
          subject
        end.to output('').to_stdout
      end
    end

    context "when user options specified and the user speak this message" do
      subject { searcher(pattern, result, user: 'jotaro').puts_search_result(item) }

      let(:pattern) { 'ze' }
      let(:result)  { double(:result, room: 'Joestars') }
      let(:item) do
        path = File.join('spec', 'data', 'item-list.json')
        extended_items(path, pattern).first
      end

      let(:search_result) do
        "\e[4;39;49mJoestars\e[0m" + "\n" + \
        "  Date: 2014-05-30T01:38:16.741565+00:00" + "\n" + \
        "  @jotaro: yareyare da\e[0;31;49mze\e[0m" + "\n" \
        "\n"
      end

      it 'should print message for specified user' do
        expect do
          subject
        end.to output(search_result).to_stdout
      end
    end

  end
end


text:
namespace EntLibExtensions.Infrastructure.Unity5
{
    using System;

    using EntLibExtensions.Infrastructure;
    using EntLibExtensions.Infrastructure.WinService;

    using global::Unity;

    /// <summary>
    /// The application extensions.
    /// </summary>
    public static class ApplicationExtensions
    {
        /// <summary>
        /// The run workers host service.
        /// </summary>
        /// <param name="application">
        /// The application.
        /// </param>
        /// <param name="optionsBootstrap">
        /// The options bootstrap.
        /// </param>
        /// <param name="bootstrapContainer">
        /// The bootstrap container.
        /// </param>
        public static void RunWorkersHostService(
            this Application application,
            Func<string[], WinServiceOptions> optionsBootstrap,
            Func<string[], IUnityContainer> bootstrapContainer)
        {
            application.RunWorkersHostService(
                optionsBootstrap,
                strings =>
                    {
                        IUnityContainer container = bootstrapContainer(strings);
                        return new UnityWorkerActionFactory(container);
                    });
        }
    }
}


text:
package es.ucm.fdi.sscheck.spark.demo

import org.junit.runner.RunWith
import org.specs2.runner.JUnitRunner
import org.specs2.ScalaCheck
import org.specs2.Specification
import org.specs2.matcher.ResultMatchers
import org.scalacheck.Arbitrary.arbitrary

import org.apache.spark.rdd.RDD
import org.apache.spark.streaming.Duration
import org.apache.spark.streaming.dstream.DStream

import es.ucm.fdi.sscheck.spark.streaming.SharedStreamingContextBeforeAfterEach
import es.ucm.fdi.sscheck.prop.tl.{Formula,DStreamTLProperty}
import es.ucm.fdi.sscheck.prop.tl.Formula._
import es.ucm.fdi.sscheck.gen.{PDStreamGen,BatchGen}

@RunWith(classOf[JUnitRunner])
class StreamingFormulaDemo1
  extends Specification
  with DStreamTLProperty
  with ResultMatchers
  with ScalaCheck {

  // Spark configuration
  override def sparkMaster : String = "local[*]"
  override def batchDuration = Duration(150)
  override def defaultParallelism = 4

  def is =
    sequential ^ s2"""
    Simple demo Specs2 example for ScalaCheck properties with temporal
    formulas on Spark Streaming programs
      - where a simple property for DStream.count is a success ${countForallAlwaysProp(_.count)}
      - where a faulty implementation of the DStream.count is detected ${countForallAlwaysProp(faultyCount) must beFailing}
    """

  def faultyCount(ds : DStream[Double]) : DStream[Long] =
    ds.count.transform(_.map(_ - 1))

  def countForallAlwaysProp(testSubject : DStream[Double] => DStream[Long]) = {
    type U = (RDD[Double], RDD[Long])
    val (inBatch, transBatch) = ((_ : U)._1, (_ : U)._2)
    val numBatches = 10
    val formula : Formula[U] = always { (u : U) =>
      transBatch(u).count === 1 and
      inBatch(u).count === transBatch(u).first
    } during numBatches

    val gen = BatchGen.always(BatchGen.ofNtoM(10, 50, arbitrary[Double]), numBatches)

    forAllDStream(
      gen)(
      testSubject)(
      formula)
  }.set(minTestsOk = 10).verbose

}


text:
package com.hpe.application.automation.tools.nv.model;

import java.util.HashMap;
import java.util.Map;

public class NvDataHolder {
    private static NvDataHolder instance;
    private Map<String,NvContext> dataMap;

    private NvDataHolder() {
        dataMap = new HashMap<>();
    }

    public static synchronized NvDataHolder getInstance() {
        if(null == instance) {
             instance = new NvDataHolder();
        }

        return instance;
    }

    public NvContext get(String key) {
        return dataMap.get(key);
    }

    public void put(String key, NvContext context) {
        dataMap.put(key, context);
    }

    public void clear(String key) {
        dataMap.remove(key);
    }
}


text:
require 'spec_helper'

describe SynvertTools do
  describe '.matching_code' do
    it 'matches with highlight code' do
      code = "post = FactoryGirl.create :post"
      rules = "type: 'send', receiver: 'FactoryGirl', message: 'create'"
      matching_code = "post = FactoryGirl.create :post"
      expect(SynvertTools.matching_code(code, rules)).to eq [:match, matching_code]
    end

    it 'does not match' do
      code = "post = FactoryGirl.create :post"
      rules = "type: 'send', receiver: 'FactoryGirl', message: 'build'"
      matching_code = "post = FactoryGirl.create :post"
      expect(SynvertTools.matching_code(code, rules)).to eq [:unmatch, matching_code]
    end
  end

  describe '.to_ast_node' do
    it 'converts code to ast node' do
      code = "post = FactoryGirl.create :post"
      node = Parser::CurrentRuby.parse(code)
      expect(SynvertTools.to_ast_node(code)).to eq node
    end
  end

  describe '.convert_code' do
    it 'converts code by snippet' do
      code = "it 'test post' do\n  post = FactoryGirl.create(:post)\nend"
      snippet =<<-EOC
within_files '*.rb' do
  with_node type: 'send', receiver: 'FactoryGirl', message: 'create' do
    replace_with 'create({{arguments}})'
  end
end
EOC
      result = "it 'test post' do\n  post = create(:post)\nend"
      expect(SynvertTools.convert_code(code, snippet)).to eq result
    end
  end
end


text:
/***************************************************************************
 *
 * $Id: StSigmaMinus.cc,v 1.1 1999/05/14 18:48:23 ullrich Exp $
 *
 * Author: Thomas Ullrich, May 99 (based on Geant4 code, see below)
 ***************************************************************************
 *
 * The design of the StParticleDefinition class and all concrete
 * classes derived from it is largely based on the design of the
 * G4ParticleDefinition class from Geant4 (RD44).
 * Although the code is in large parts different (modified or rewritten)
 * and adapted to the STAR framework the basic idea stays the same.
 *
 ***************************************************************************
 *
 * $Log: StSigmaMinus.cc,v $
 * Revision 1.1  1999/05/14 18:48:23  ullrich
 * Initial Revision
 *
 **************************************************************************/
#include "StSigmaMinus.hh"
#include "PhysicalConstants.h"

StSigmaMinus::StSigmaMinus(const string  &  aName,
			   double           mass,
			   double           width,
			   double           charge,
			   int              iSpin,
			   int              iParity,
			   int              iConjugation,
			   int              iIsospin,
			   int              iIsospinZ,
			   int              gParity,
			   const string  &  pType,
			   int              lepton,
			   int              baryon,
			   int              encoding,
			   bool             stable,
			   double           lifetime)
    : StBaryon(aName, mass, width, charge, iSpin, iParity,
	       iConjugation, iIsospin, iIsospinZ, gParity,
	       pType, lepton, baryon, encoding, stable,
	       lifetime) {/* noop */}

// ......................................................................
// ...                 static member definitions                      ...
// ......................................................................
//
//    Arguments for constructor are as follows
//               name             mass          width         charge
//             2*spin           parity  C-conjugation
//          2*Isospin       2*Isospin3       G-parity
//               type    lepton number  baryon number   PDG encoding
//             stable         lifetime
//
StSigmaMinus StSigmaMinus::mSigmaMinus(
             "sigma-",     1.19744*GeV,       0.0*MeV,    -1*eplus,
		    1,              +1,             0,
		    2,              -2,             0,
	     "baryon",               0,            +1,        3112,
		false,       0.1479*nanosecond
);


text:
using System;
using System.Drawing;
using System.Windows.Forms;

namespace SIL.Windows.Forms.Widgets.BetterGrid
{
	/// ----------------------------------------------------------------------------------------
	internal class CalendarEditingControl : DateTimePicker, IDataGridViewEditingControl
	{
		private DataGridView _parentGrid;

		/// ------------------------------------------------------------------------------------
		public CalendarEditingControl()
		{
			Format = DateTimePickerFormat.Short;
		}

		#region Private properties
		/// ------------------------------------------------------------------------------------
		private DataGridView Grid
		{
			get
			{
				if (_parentGrid == null)
				{
					Control parent = Parent;
					while (parent != null && !(parent is DataGridView))
						parent = parent.Parent;
					_parentGrid = parent as DataGridView;
				}
				return _parentGrid;
			}
		}

		/// ------------------------------------------------------------------------------------
		private Color GridForeColor
		{
			get
			{
				return (Grid != null) ? Grid.ForeColor : Color.Black;
			}
		}

		/// ------------------------------------------------------------------------------------
		private Color GridBackColor
		{
			get
			{
				return (Grid != null) ? Grid.BackColor : Color.White;
			}
		}
		#endregion

		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Notify the DataGridView that the contents of the cell have changed.
		/// </summary>
		/// ------------------------------------------------------------------------------------
		protected override void OnValueChanged(EventArgs eventargs)
		{
			EditingControlValueChanged = true;
			EditingControlDataGridView.NotifyCurrentCellDirty(true);
			base.OnValueChanged(eventargs);
		}

		#region IDataGridViewEditingControl implementations

		public int EditingControlRowIndex { get; set; }
		public bool EditingControlValueChanged { get; set; }
		public DataGridView EditingControlDataGridView { get; set; }

		/// ------------------------------------------------------------------------------------
		public Cursor EditingPanelCursor
		{
			get { return base.Cursor; }
		}

		/// ------------------------------------------------------------------------------------
		public object EditingControlFormattedValue
		{
			get { return Value.ToShortDateString(); }
			set
			{
				if (value is string && ((string)value).Trim() != string.Empty)
					Value = DateTime.Parse((string)value);
			}
		}

		/// ------------------------------------------------------------------------------------
		public object GetEditingControlFormattedValue(DataGridViewDataErrorContexts context)
		{
			return EditingControlFormattedValue;
		}

		/// ------------------------------------------------------------------------------------
		public void ApplyCellStyleToEditingControl(DataGridViewCellStyle dataGridViewCellStyle)
		{
			Font = dataGridViewCellStyle.Font;
			if (!Application.RenderWithVisualStyles)
			{
				var foreColor = dataGridViewCellStyle.ForeColor;
				if (foreColor.IsEmpty)
					foreColor = GridForeColor;
				var backColor = dataGridViewCellStyle.BackColor;
				if (backColor.IsEmpty)
					backColor = GridBackColor;
				if (!foreColor.IsEmpty && foreColor != backColor)
					CalendarForeColor = foreColor;
				if (!backColor.IsEmpty && backColor != CalendarForeColor)
					CalendarMonthBackground = backColor;
			}
		}

		/// ------------------------------------------------------------------------------------
		public bool EditingControlWantsInputKey(Keys key, bool dataGridViewWantsInputKey)
		{
			// Let the DateTimePicker handle the keys listed.
			switch (key & Keys.KeyCode)
			{
				case Keys.Left:
				case Keys.Up:
				case Keys.Down:
				case Keys.Right:
				case Keys.Home:
				case Keys.End:
				case Keys.PageDown:
				case Keys.PageUp:
					return true;
				default:
					return !dataGridViewWantsInputKey;
			}
		}

		/// ------------------------------------------------------------------------------------
		public void PrepareEditingControlForEdit(bool selectAll)
		{
			// No preparation needs to be done.
		}

		/// ------------------------------------------------------------------------------------
		public bool RepositionEditingControlOnValueChange
		{
			get { return false; }
		}

		#endregion
	}
}


text:
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.idea;

import com.intellij.diagnostic.Activity;
import com.intellij.diagnostic.StartUpMeasurer;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.application.ex.ApplicationInfoEx;
import com.intellij.openapi.util.SystemInfoRt;
import com.intellij.openapi.wm.impl.FrameBoundsConverter;
import com.intellij.openapi.wm.impl.IdeFrameImpl;
import com.intellij.ui.Splash;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SeekableByteChannel;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;

public final class SplashManager {
  private static volatile JFrame PROJECT_FRAME;
  static Splash SPLASH_WINDOW;

  public static @NotNull Runnable scheduleShow(@NotNull ApplicationInfoEx appInfo) {
    Activity frameActivity = StartUpMeasurer.startActivity("splash as project frame initialization");
    try {
      Runnable task = createFrameIfPossible();
      if (task != null) {
        return task;
      }
    }
    catch (Throwable e) {
      //noinspection UseOfSystemOutOrSystemErr
      System.out.println(e.getMessage());
    }
    finally {
      frameActivity.end();
    }

    // must be out of activity measurement
    assert SPLASH_WINDOW == null;
    Activity activity = StartUpMeasurer.startActivity("splash initialization");
    SPLASH_WINDOW = new Splash(appInfo);
    Activity queueActivity = activity.startChild("splash initialization (in queue)");
    return () -> {
      queueActivity.end();
      Splash splash = SPLASH_WINDOW;
      // can be cancelled if app was started very fast
      if (splash != null) {
        splash.initAndShow(true);
      }
      activity.end();
    };
  }

  private static @Nullable Runnable createFrameIfPossible() throws IOException {
    Path infoFile = Paths.get(PathManager.getSystemPath(), "lastProjectFrameInfo");
    ByteBuffer buffer;
    try (SeekableByteChannel channel = Files.newByteChannel(infoFile)) {
      buffer = ByteBuffer.allocate((int)channel.size());
      do {
        channel.read(buffer);
      }
      while (buffer.hasRemaining());

      buffer.flip();
      if (buffer.getShort() != 0) {
        return null;
      }
    }
    catch (NoSuchFileException ignore) {
      return null;
    }

    Rectangle savedBounds = new Rectangle(buffer.getInt(), buffer.getInt(), buffer.getInt(), buffer.getInt());
    //noinspection UseJBColor
    Color backgroundColor = new Color(buffer.getInt(), /* hasAlpha = */ true);
    @SuppressWarnings("unused")
    boolean isFullScreen = buffer.get() == 1;
    int extendedState = buffer.getInt();
    return () -> {
      PROJECT_FRAME = doShowFrame(savedBounds, backgroundColor, extendedState);
    };
  }

  private static @NotNull IdeFrameImpl doShowFrame(Rectangle savedBounds, Color backgroundColor, int extendedState) {
    IdeFrameImpl frame = new IdeFrameImpl();
    frame.setAutoRequestFocus(false);
    frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);

    frame.setBounds(FrameBoundsConverter.convertFromDeviceSpaceAndFitToScreen(savedBounds));
    frame.setExtendedState(extendedState);

    frame.setMinimumSize(new Dimension(340, (int)frame.getMinimumSize().getHeight()));
    frame.setBackground(backgroundColor);
    frame.getContentPane().setBackground(backgroundColor);
    if (SystemInfoRt.isMac) {
      frame.setIconImage(null);
    }

    StartUpMeasurer.addInstantEvent("frame shown");
    Activity activity = StartUpMeasurer.startActivity("frame set visible");
    frame.setVisible(true);
    activity.end();
    return frame;
  }

  public static void executeWithHiddenSplash(@NotNull Window window, @NotNull Runnable runnable) {
    if (SPLASH_WINDOW == null) {
      if (PROJECT_FRAME != null) {
        // just destroy frame
        hide();
      }
      runnable.run();
      return;
    }

    WindowListener listener = new WindowAdapter() {
      @Override
      public void windowOpened(WindowEvent e) {
        setVisible(false);
      }
    };
    window.addWindowListener(listener);

    runnable.run();

    setVisible(true);
    window.removeWindowListener(listener);
  }

  private static void setVisible(boolean value) {
    Splash splash = SPLASH_WINDOW;
    if (splash != null) {
      splash.setVisible(value);
      if (value) {
        splash.paint(splash.getGraphics());
      }
    }
  }

  public static @Nullable JFrame getAndUnsetProjectFrame() {
    JFrame frame = PROJECT_FRAME;
    PROJECT_FRAME = null;
    return frame;
  }

  public static void hideBeforeShow(@NotNull Window window) {
    if (SPLASH_WINDOW != null || PROJECT_FRAME != null) {
      window.addWindowListener(new WindowAdapter() {
        @Override
        public void windowOpened(WindowEvent e) {
          hide();
          window.removeWindowListener(this);
        }
      });
    }
  }

  public static void hide() {
    Window window = SPLASH_WINDOW;
    if (window == null) {
      window = PROJECT_FRAME;
      if (window == null) {
        return;
      }
      else {
        PROJECT_FRAME = null;
      }
    }
    else {
      SPLASH_WINDOW = null;
    }

    StartUpMeasurer.addInstantEvent("splash hidden");
    window.setVisible(false);
    window.dispose();
  }
}


text:
Wecome to my AngularJS based Ganeti Frontend

Foo


text:
<?php

namespace Skaphandrus\AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Knp\DoctrineBehaviors\Model as ORMBehaviors;

/**
 * SkEmailNotificationTimeI18n
 */
class SkEmailNotificationTimeTranslation
{
     use ORMBehaviors\Translatable\Translation;

    /**
     * @var string
     */
    private $name;

    /**
     * Set name
     *
     * @param string $name
     *
     * @return SkEmailNotificationTimeI18n
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

}


text:
package model;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class JsonNumberLong {

    @JsonProperty("$numberLong")
    private Long $numberLong;

    public JsonNumberLong(long $numberLong) {
        this.$numberLong = $numberLong;
    }

    public JsonNumberLong(int $numberLong) {
        this.$numberLong = Long.valueOf($numberLong);
    }

    public Long get$numberLong() {
        return $numberLong;
    }

    public void set$numberLong(Long $numberLong) {
        this.$numberLong = $numberLong;
    }
}


text:
package org.apache.olingo.fit.proxy.staticservice.odatawcfservice.types;

// CHECKSTYLE:OFF (Maven checkstyle)
import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind;

// CHECKSTYLE:ON (Maven checkstyle)

@org.apache.olingo.ext.proxy.api.annotations.Namespace("Microsoft.Test.OData.Services.ODataWCFService")
@org.apache.olingo.ext.proxy.api.annotations.EnumType(name = "Color",
    underlyingType = EdmPrimitiveTypeKind.Int32,
    isFlags = false)
public enum Color {
  Red(1),
  Green(2),
  Blue(4);

  private java.lang.Integer value;

  public java.lang.Integer getValue() {
    return value;
  }

  private Color(final java.lang.Integer value) {
    this.value = value;
  }
}


text:
<?php

defined("_VALID_ACCESS") || die('Direct access forbidden');

class Utils_CurrencyFieldCommon extends ModuleCommon {
	public static function format($val, $currency=null) {
		if (!isset($currency) || !$currency) {
			$val = self::get_values($val);
			$currency = $val[1];
			if(!$currency) return '';
			$val = $val[0];
		}
		$params = self::$cache[$currency];
		$dec_delimiter = $params['decimal_sign'];
		if(!$dec_delimiter) trigger_error(print_r(self::$cache,true));
		$thou_delimiter = $params['thousand_sign'];
		$dec_digits = $params['decimals'];
		$currency = $params['symbol'];
		$pos_before = $params['pos_before'];

		if (!$val) $val = '0';
		$val = str_replace(array('.',','),$dec_delimiter,$val);
		if (!strrchr($val,$dec_delimiter)) $val .= $dec_delimiter;
		$cur = explode($dec_delimiter, $val);
		if (!isset($cur[1])) $cur[1] = '';
		$cur[1] = str_pad($cur[1], $dec_digits, '0');
		$val = $cur[0].'.'.$cur[1];
		$ret = number_format($val, $dec_digits, $dec_delimiter, $thou_delimiter);
		if ($pos_before) $ret = $currency.' '.$ret;
		else $ret = $ret.' '.$currency;
		return $ret;
	}

    public static function is_empty($p) {
        return strpos($p,'__') === 0;
    }

	public static function get_values($p) {
		if (!is_array($p)) $p = explode('__', $p);
                if(!is_numeric($p[0]) && $p[0]!='') return false;
		if (!isset($p[1])) $p[1] = Base_User_SettingsCommon::get('Utils_CurrencyField', 'default_currency');
        $p[0] = str_replace(array(',', self::get_decimal_point($p[1])), '.', $p[0]);
		return $p;
	}

	public static function format_default($v, $c=null) {
        $values = ($c === null ? self::get_values($v) : self::get_values(array($v, $c)));
        $c = $values[1];
        $v = round($values[0], self::get_precission($c));
		return $v.'__'.$c;
	}

	public static function user_settings() {
		$currency_options = DB::GetAssoc('SELECT id, code FROM utils_currency WHERE active=1');
		$def = self::get_default_currency();
		return array(__('Regional Settings')=>array(
				array('name'=>'currency_header', 'label'=>__('Currency'), 'type'=>'header'),
				array('name'=>'default_currency','label'=>__('Default currency'),'type'=>'select','values'=>$currency_options,'default'=>$def['id']),
					));
	}

	public static function get_decimal_point($arg = null) {
        self::load_cache();
		if($arg===null) $arg = Base_User_SettingsCommon::get('Utils_CurrencyField','default_currency');
		if (!isset(self::$cache[$arg])) return null;
		return self::$cache[$arg]['decimal_sign'];
	}

	public static function get_thousand_point($arg) {
        self::load_cache();
		if (!isset(self::$cache[$arg])) return null;
		return self::$cache[$arg]['thousand_sign'];
	}

	public static function get_id_by_code($code) {
		static $cache;
		if(!isset($cache)) $cache = array();
		if(!isset($cache[$code]))
			$cache[$code] = DB::GetOne('SELECT id FROM utils_currency WHERE code=%s', array($code));
		return $cache[$code];
	}

	public static function get_code($arg) {
        self::load_cache();
		if (!isset(self::$cache[$arg])) return null;
		return self::$cache[$arg]['code'];
	}

	public static function get_precission($arg) {
        self::load_cache();
		if (!isset(self::$cache[$arg])) return null;
		return self::$cache[$arg]['decimals'];
	}

	public static function get_currencies() {
		static $cache=null;
		if ($cache===null) $cache = DB::GetAssoc('SELECT id, code FROM utils_currency WHERE active=1');
		return $cache;
	}

	public static function get_all_currencies() {
		static $cache=null;
		if ($cache===null) $cache = DB::GetAssoc('SELECT id, code FROM utils_currency');
		return $cache;
	}

	public static function get_default_currency() {
		static $cache=null;
		if ($cache===null) $cache = DB::GetRow('SELECT * FROM utils_currency WHERE default_currency=1');
		return $cache;
	}

	public static function admin_caption() {
		return array('label'=>__('Currencies'), 'section'=>__('Regional Settings'));
	}

	public static function get_symbol($arg) {
        self::load_cache();
		if (!isset(self::$cache[$arg])) return null;
		return self::$cache[$arg]['symbol'];
	}
	public static function get_symbol_position($arg) {
        self::load_cache();
		if (!isset(self::$cache[$arg])) return null;
		return self::$cache[$arg]['pos_before'];
	}

    /**
     * Parse currency using existing currencies set in the system.
     *
     * @param $string Currency string to parse
     *
     * @return array|null null on failure and array(value, currency_id) on success - like get_values returns.
     */
    public static function parse_currency($string) {
        $string = html_entity_decode($string);
        $string = preg_replace('/[\pZ\pC\s]/u', '', $string); // remove whitespaces, including unicode nbsp
        $currencies = Utils_CurrencyFieldCommon::get_currencies();
        foreach (array_keys($currencies) as $cur_id) {
            $symbol = Utils_CurrencyFieldCommon::get_symbol($cur_id);
            $symbol_pos_before = Utils_CurrencyFieldCommon::get_symbol_position($cur_id);
            // check for symbol
            if ($symbol_pos_before) {
                if (strpos($string, $symbol) === 0) {
                    $string = substr($string, strlen($symbol));
                } else continue;
            } else {
                $pos_of_sym = strlen($string) - strlen($symbol);
                if (strrpos($string, $symbol) == $pos_of_sym) {
                    $string = substr($string, 0, $pos_of_sym);
                } else continue;
            }
            // separate by decimal point
            $exp = explode(Utils_CurrencyFieldCommon::get_decimal_point($cur_id), $string);
            if (count($exp) > 2)
                continue;
            $fraction = count($exp) == 2 ? $exp[1] : '0';
            $int = $exp[0];
            if (!preg_match('/^\d+$/', $fraction))
                continue;
            $th_point = Utils_CurrencyFieldCommon::get_thousand_point($cur_id);
            if (strlen($th_point)) {
                $thparts = explode($th_point, $int);
                if (count($thparts) > 1) {
                    for ($i = 1; $i < count($thparts); $i++)
                        if (strlen($thparts[$i]) != 3)
                            continue 2;
                }
                $int = str_replace($th_point, '', $int);
            }
            if (preg_match('/^\-?\d+$/', $int)) {
                return array($int . '.' . $fraction, $cur_id);
            }
        }
        return null;
    }

    private static $cache;
    public static function load_cache() {
        if(!isset(self::$cache))
            self::$cache = DB::GetAssoc('SELECT id,pos_before,symbol,decimals,code,thousand_sign,decimal_sign FROM utils_currency');
    }
    public static function load_js() {
        self::load_cache();
        load_js('modules/Utils/CurrencyField/currency.js');
        $currencies = Utils_CurrencyFieldCommon::get_all_currencies();
        $js = 'Utils_CurrencyField.currencies=new Array();';
        foreach ($currencies as $k => $v) {
            $symbol = Utils_CurrencyFieldCommon::get_symbol($k);
            $position = Utils_CurrencyFieldCommon::get_symbol_position($k);
            $curr_format = '-?([0-9]*)\\'.Utils_CurrencyFieldCommon::get_decimal_point($k).'?[0-9]{0,'.Utils_CurrencyFieldCommon::get_precission($k).'}';
            $js .= 'Utils_CurrencyField.currencies[' . $k . ']={' . '"decp":"' . Utils_CurrencyFieldCommon::get_decimal_point($k) . '",' . '"thop":"' . Utils_CurrencyFieldCommon::get_thousand_point($k) . '",' . '"symbol_before":"' . ($position ? $symbol : '') . '",' . '"symbol_after":"' . (!$position ? $symbol : '') . '",' . '"dec_digits":' . Utils_CurrencyFieldCommon::get_precission($k) . ',' .
                '"regex":'.json_encode($curr_format).'};';
        }
        eval_js_once($js);
    }
}

$GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']['currency'] = array('modules/Utils/CurrencyField/currency.php','HTML_QuickForm_currency');
on_init(array('Utils_CurrencyFieldCommon','load_js'));
?>


text:
def user_can_edit?
  @user.id == session[:user_id]
end


text:
import 'isomorphic-fetch'
import reduxApi from 'redux-api'
import adapterFetch from 'lib/adapters/fetch'
// import adapterFetch from "redux-api/lib/adapters/fetch"
import config from 'config'
import { addBaseApiUrl } from 'decorators/Api'
import { webcamsTransformer } from 'store/webcams'

/**
 * Realtime API endpoints
 */
export default reduxApi(addBaseApiUrl(
  {
    /**
     * Retrieves all conferences
     */
    webcams: {
      url: 'webcam/',
      options: config.api.headers,
      reducerName: 'webcams',
      transformer: webcamsTransformer
    }
  }
))
.use('fetch', adapterFetch(fetch))


text:
<?php
/**
*
*/
class Product
{
	// general

	private $name = "unidentified";
	private $code="unidentified";
	private $amount =  0.0;
	private $unitAmount = "unidentified";
    private $netWeight = 0.0;//
	private $unitWeight = "unidentified";

	// finance
	private $currency = "unidentified";
	private $cost = 0.0;
	private $price = 0.0;//
	private $profit = 0.0;
    private $sale = 0.0;

	// feature
	private $hierarchy = "unidentified";// ระดับชั้น
	private $certificate = "unidentified";
	private $expire = "unidentified";//
    private $authorization = "unidentified";// ผู้มีอำนาจรับผิดชอบ

	// logistic
    private $orderLeadTime = 0; // ระยะเวลาสั่งซื้อ(หน่วยเป็น ชม) ระยะเวลาการสั่งของ
    private $unitOrderLeadTime = "unidentified";
	private $minimumPacking =  0.0;
	private $unitMinimumPacking = "unidentified";
	private $minimumOrder = 0;
	private $paymentTerm = "unidentified"; // เงื่อนไขการชำระ ex cash 30 วัน,cheque 3 วัน
													// FACTORY=ราคาหน้าโรงงานผลิต
													// FOB=ราคาถึงท่าเรือของผู้ขาย
													// CIF=ราคาถึงท่าเรือของผู้ซื้อ
													// DDU=ราคาถึงผู้ซื้อไม่รวมภาษี
													// DDP=ราคาถึงผู้ซื้อรวมภาษี
	private $allocation = "unidentified";// การจัดสรร

	/* All set method */
	// general

	public function setName($name) {
		$this->name = $name;
	}

	public function setCode($code) {
		$this->code = $code;
	}

	public function setAmount($amount) {
		$this->amount = $amount;
	}

	public function setUnitAmount($unitAmount) {
		$this->unitAmount = $unitAmount;
	}

	public function setNetWeight($netWeight) {
		$this->netWeight = $netWeight;
	}

	public function setUnitNetWeight($unitWeight) {
		$this->unitWeight = $unitWeight;
	}

	// finance
	public function setCurrency($currency) {
		$this->currency = $currency;
	}

	public function setCost($cost) {
		$this->cost = $cost;
	}

	public function setPrice($price) {
		$this->price = $price;
	}

	public function setSale($sale) {
		$this->sale = $sale;
	}

	// feature
	public function setHierarchy($hierarchy) {
		$this->hierarchy = $hierarchy;
	}

	public function setCertificate($certificate) {
		$this->certificate = $certificate;
	}

	public function setExpire($expire) {
		$this->expire = $expire;
	}

	public function setAuthorization($authorization) {
		$this->authorization = $authorization;
	}

	// logistic
	public function setOrderLeadTime($orderLeadTime) {
		$this->orderLeadTime = $orderLeadTime;
	}

	public function setUnitOrderLeadTime($unitOrderLeadTime) {
		$this->unitOrderLeadTime = $unitOrderLeadTime;
	}

	public function setMinimumPacking($minimumPacking) {
		$this->minimumPacking = $minimumPacking;
	}

	public function setUnitMinimumPacking($unitMinimumPacking) {
		$this->unitMinimumPacking = $unitMinimumPacking;
	}

	public function setMinimumOrder($minimumOrder) {
		$this->minimumOrder = $minimumOrder;
	}

	public function setPaymentTerm($paymentTerm) {
		$this->paymentTerm = $paymentTerm;
	}

	public function setAllocation($allocation) {
		$this->allocation = $allocation;
	}

	/* All get method */
	// general

	public function getName() {
		return $this->name;
	}

	public function getCode() {
		return $this->code;
	}

	public function getAmount() {
		return $this->amount;
	}

	public function getUnitAmount() {
		return $this->unitAmount;
	}

	public function getNetWeight() {
		return $this->netWeight;
	}

	public function getUnitWeight() {
		return $this->unitWeight;
	}

	// finance
	public function getCurrency() {
		return $this->currency;
	}

	public function getCost() {
		return $this->cost;
	}

	public function getPrice() {
		return $this->price;
	}

	public function getProfit() {
		$this->profit = $this->price - $this->cost;
		return $this->profit;
	}

	public function getSale() {
		return $this->sale;
	}

	// feature
	public function getHierarchy() {
		return $this->hierarchy;
	}

	public function getCertificate() {
		return $this->certificate;
	}

	public function getExpire() {
		return $this->expire;
	}

	public function getAuthorization() {
		return $this->authorization;
	}

	// logistic
	public function getOrderLeadTime() {
		return $this->orderLeadTime;
	}

	public function getUnitOrderLeadTime() {
		return $this->unitOrderLeadTime;
	}

	public function getMinimumPacking() {
		return $this->minimumPacking;
	}

	public function getUnitMinimumPacking() {
		return $this->unitMinimumPacking;
	}

	public function getMinimumOrder() {
		return $this->minimumOrder;
	}

	public function getParmentTerm() {
		return $this->paymentTerm;
	}

	public function getAllocation() {
		return $this->allocation;
	}

	// operation function

	public function sell($amount) {
		$this->sale=($this->sale)+($this->getProfit())*$amount;
		$this->amount=($this->amount)-$amount;
	}
	public function printAll() {

		print "
";
		print "Name : ";
		print $this->getName();
		print "
";

		print "Code : ";
		print $this->getCode();
		print "
";

		print "Amount : ";
		print $this->getAmount();
		print "
";

		print "Unit amount : ";
		print $this->getUnitAmount();
		print "
";

		print "NetWeight : ";
		print $this->getNetWeight();
		print "
";

		print "Unit NetWeight : ";
		print $this->getUnitWeight();
		print "
";

		print "Currency : ";
		print $this->getCurrency();
		print "
";

		print "Cost : ";
		print $this->getCost();
		print "
";

		print "Price : ";
		print $this->getPrice();
		print "
";

		print "Profit : ";
		print $this->getProfit();
		print "
";

		print "Sale : ";
		print $this->getSale();
		print "
";

		print "Hierarchy : ";
		print $this->getHierarchy();
		print "
";

		print "Certificate : ";
		print $this->getCertificate();
		print "
";

		print "Expire : ";
		print $this->getExpire();
		print "
";

		print "Authorization : ";
		print $this->getAuthorization();
		print "
";

		print "Order lead time : ";
		print $this->getOrderLeadTime();
		print "
";

		print "Unit order lead time : ";
		print $this->getUnitOrderLeadTime();
		print "
";

		print "Minimum Packing : ";
		print $this->getMinimumPacking();
		print "
";

		print "Unit minimum packing : ";
		print $this->getUnitMinimumPacking();
		print "
";

		print "Minimum order : ";
		print $this->getMinimumOrder();
		print "
";

		print "Payment term : ";
		print $this->getParmentTerm();
		print "
";

		print "Allocation : ";
		print $this->getAuthorization();
		print "

";
	}
}
?>


text:
package org.cobbzilla.sendgrid;

import lombok.NoArgsConstructor;
import org.apache.http.entity.ContentType;
import org.cobbzilla.util.string.StringUtil;
import org.cobbzilla.wizard.client.ApiClientBase;
import org.cobbzilla.util.http.ApiConnectionInfo;
import org.cobbzilla.wizard.util.RestResponse;

import java.util.Map;

@NoArgsConstructor
public class SendGridApiClient extends ApiClientBase {

    public SendGridApiClient (String baseUri) {
        super(new ApiConnectionInfo(baseUri));
    }

    public RestResponse post(String path, Map<String, String> params) throws Exception {
        return super.post(path, StringUtil.urlParameterize(params), ContentType.APPLICATION_FORM_URLENCODED);
    }

}


text:
namespace blink {

class Document;
class HTMLAnchorElement;
class IntersectionObserver;
class IntersectionObserverEntry;
class AnchorElementMetrics;

// AnchorElementMetricsSender is responsible to send anchor element metrics to
// the browser process for a given document.
//
// The high level approach is:
// 1) When HTMLAnchorElements are inserted into the DOM,
//    AnchorElementMetricsSender::AddAnchorElement is called and a reference to
//    the element is stored. We also add the element to the intersection
//    observer that watches for elements entering the viewport. The first time
//    this happens, the sender is created, which registers itself for lifecycle
//    callbacks.
// 2) If any elements enter the viewport, the intersection observer will call
//    AnchorElementMetricsSender::UpdateVisibleAnchors. Elements are collected
//    in entered_viewport_messages_ and will be reported after the next layout.
// 3) On the next layout, AnchorElementMetricsSender::DidFinishLifecycleUpdate
//    is called, and it goes over the collected anchor elements. Elements that
//    are visible are reported to the browser via ReportNewAnchorElements. The
//    anchor elements collected in AnchorElementMetricsSender are all dropped.
//    In particular, this drops elements that are not visible. They will never
//    be reported even if they become visible later, unless the are reinserted
//    into the DOM. This is not ideal, but simpler, keeps resource usage low,
//    and seems to work well enough on the sites I've looked at. Also, elements
//    that entered the viewport will be reported using
//    ReportAnchorElementsEnteredViewport.
class CORE_EXPORT AnchorElementMetricsSender final
    : public GarbageCollected<AnchorElementMetricsSender>,
      public LocalFrameView::LifecycleNotificationObserver,
      public Supplement<Document> {
 public:
  static const char kSupplementName[];

  explicit AnchorElementMetricsSender(Document&);
  AnchorElementMetricsSender(const AnchorElementMetricsSender&) = delete;
  AnchorElementMetricsSender& operator=(const AnchorElementMetricsSender&) =
      delete;
  virtual ~AnchorElementMetricsSender();

  // LocalFrameView::LifecycleNotificationObserver
  void WillStartLifecycleUpdate(const LocalFrameView&) override {}
  void DidFinishLifecycleUpdate(
      const LocalFrameView& local_frame_view) override;

  // Returns the anchor element metrics sender of the root document of
  // |Document|. Constructs new one if it does not exist.
  static AnchorElementMetricsSender* From(Document&);

  // Returns true if |document| should have associated
  // AnchorElementMetricsSender.
  static bool HasAnchorElementMetricsSender(Document& document);

  // Report the link click to the browser process, so long as the anchor
  // is an HTTP(S) link.
  void MaybeReportClickedMetricsOnClick(
      const HTMLAnchorElement& anchor_element);

  // Adds an anchor element to |anchor_elements_|.
  void AddAnchorElement(HTMLAnchorElement& element);

  HeapMojoRemote<mojom::blink::AnchorElementMetricsHost>* MetricsHost();

  // Creates AnchorElementMetrics from anchor element if possible. Then records
  // the metrics, and sends them to the browser process.
  void UpdateVisibleAnchors(
      const HeapVector<Member<IntersectionObserverEntry>>& entries);

  void Trace(Visitor*) const override;

 private:
  // Associates |metrics_host_| with the IPC interface if not already, so it can
  // be used to send messages. Returns true if associated, false otherwise.
  bool AssociateInterface();

  // Creates an AnchorElementEnteredViewportPtr for the given element and
  // enqueue it so that it gets reported after the next layout.
  void EnqueueEnteredViewport(const HTMLAnchorElement& element);

  // Use WeakMember to make sure we don't leak memory on long-lived pages.
  HeapHashSet<WeakMember<HTMLAnchorElement>> anchor_elements_to_report_;

  HeapMojoRemote<mojom::blink::AnchorElementMetricsHost> metrics_host_;

  Member<IntersectionObserver> intersection_observer_;

  WTF::Vector<mojom::blink::AnchorElementEnteredViewportPtr>
      entered_viewport_messages_;
  WTF::Vector<mojom::blink::AnchorElementClickPtr> clicked_messages_;
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_CORE_HTML_ANCHOR_ELEMENT_METRICS_SENDER_H_


text:
from config import CONFIG_FILE
from ifcb.util import get_config
import re

CONFIG_SCHEMA = [
('stitch', 'bool'),
('use_memcached', 'bool'),
('memcached_servers', 'list'),
('url_base', 'str'),
('data_ttl', 'int'),
('data_namespace', 'str'),
('feed', 'str'),
('fs_roots', 'list'),
('mod_roots', 'list'),
('blob_roots', 'list'),
('psql_connect', 'str')
]

# read a config file and massage some value types
def config(name):
    c = get_config(CONFIG_FILE,name)
    for key,val_type in CONFIG_SCHEMA:
        try:
            if val_type == 'list':
                c[key] = re.split(r'\s*,\s*',c[key])
            elif val_type == 'bool':
                c[key] = c[key] == 'True'
            elif val_type == 'int':
                c[key] = int(c[key])
        except KeyError:
            pass
    return c


text:
			// Replace the <textarea id="editor"> with an CKEditor
			// instance, using the "bbcode" plugin, shaping some of the
			// editor configuration to fit BBCode environment.
			CKEDITOR.replace( 'editor1',
				{
					//extraPlugins : 'bbcode',
					// Remove unused plugins.
					removePlugins : 'bidi,button,dialogadvtab,div,flash,forms,iframe,indent,liststyle,pagebreak,showborders,table,tabletools,templates',
					// Width and height are not supported in the BBCode format, so object resizing is disabled.
					disableObjectResizing : true,
					// Define font sizes in percent values.
					fontSize_sizes : "75/75%;100/100%;120/120%;150/150%;200/200%",
					toolbar :
					[
						['Source','Undo','Redo'],
						['Styles', 'Format'],
						['Link', 'Unlink', 'Image', 'Smiley','SpecialChar'],
						['Find','Replace','-','SelectAll','RemoveFormat'],
						['Preview', 'Print','-','Maximize'],

						'/',
						['Bold', 'Italic','Underline'],
						['Cut','Copy','Paste','PasteText','PasteFromWord'],
						['JustifyLeft','JustifyCenter','JustifyRight'],
						['FontSize','Font'],
						['TextColor','BGColor'],
						['NumberedList','BulletedList','-','Blockquote'],

					],
					 width: "800px",
                     height: "320px",
					// Strip CKEditor smileys to those commonly used in BBCode.
					smiley_images :
					[
						'regular_smile.gif','sad_smile.gif','wink_smile.gif','teeth_smile.gif','tounge_smile.gif',
						'embaressed_smile.gif','omg_smile.gif','whatchutalkingabout_smile.gif','angel_smile.gif','shades_smile.gif',
						'cry_smile.gif','kiss.gif'
					],
					smiley_descriptions :
					[
						'smiley', 'sad', 'wink', 'laugh', 'cheeky', 'blush', 'surprise',
						'indecision', 'angel', 'cool', 'crying', 'kiss'
					]
			} );

			CKEDITOR.replace( 'editor2',
				{
					//extraPlugins : 'bbcode',
					// Remove unused plugins.
					removePlugins : 'bidi,button,dialogadvtab,div,flash,forms,iframe,indent,liststyle,pagebreak,showborders,table,tabletools,templates',
					// Width and height are not supported in the BBCode format, so object resizing is disabled.
					disableObjectResizing : true,
					// Define font sizes in percent values.
					fontSize_sizes : "75/75%;100/100%;120/120%;150/150%;200/200%",
					toolbar :
					[
						['Source','Undo','Redo'],
						['Styles', 'Format'],
						['Link', 'Unlink', 'Image', 'Smiley','SpecialChar'],
						['Find','Replace','-','SelectAll','RemoveFormat'],
						['Preview', 'Print','-','Maximize'],

						'/',
						['Bold', 'Italic','Underline'],
						['Cut','Copy','Paste','PasteText','PasteFromWord'],
						['JustifyLeft','JustifyCenter','JustifyRight'],
						['FontSize','Font'],
						['TextColor','BGColor'],
						['NumberedList','BulletedList','-','Blockquote'],

					],
					 width: "800px",
                     height: "110px",
					// Strip CKEditor smileys to those commonly used in BBCode.
					smiley_images :
					[
						'regular_smile.gif','sad_smile.gif','wink_smile.gif','teeth_smile.gif','tounge_smile.gif',
						'embaressed_smile.gif','omg_smile.gif','whatchutalkingabout_smile.gif','angel_smile.gif','shades_smile.gif',
						'cry_smile.gif','kiss.gif'
					],
					smiley_descriptions :
					[
						'smiley', 'sad', 'wink', 'laugh', 'cheeky', 'blush', 'surprise',
						'indecision', 'angel', 'cool', 'crying', 'kiss'
					]
			} );

			CKEDITOR.replace( 'editor3',
				{
					//extraPlugins : 'bbcode',
					// Remove unused plugins.
					removePlugins : 'bidi,button,dialogadvtab,div,flash,forms,iframe,indent,liststyle,pagebreak,showborders,table,tabletools,templates',
					// Width and height are not supported in the BBCode format, so object resizing is disabled.
					disableObjectResizing : true,
					// Define font sizes in percent values.
					fontSize_sizes : "75/75%;100/100%;120/120%;150/150%;200/200%",
					toolbar :
					[
						['Source','Undo','Redo'],
						['Styles', 'Format'],
						['Link', 'Unlink', 'Image', 'Smiley','SpecialChar'],
						['Find','Replace','-','SelectAll','RemoveFormat'],
						['Preview', 'Print','-','Maximize'],

						'/',
						['Bold', 'Italic','Underline'],
						['Cut','Copy','Paste','PasteText','PasteFromWord'],
						['JustifyLeft','JustifyCenter','JustifyRight'],
						['FontSize','Font'],
						['TextColor','BGColor'],
						['NumberedList','BulletedList','-','Blockquote'],

					],
					 width: "800px",
                     height: "90px",
					// Strip CKEditor smileys to those commonly used in BBCode.
					smiley_images :
					[
						'regular_smile.gif','sad_smile.gif','wink_smile.gif','teeth_smile.gif','tounge_smile.gif',
						'embaressed_smile.gif','omg_smile.gif','whatchutalkingabout_smile.gif','angel_smile.gif','shades_smile.gif',
						'cry_smile.gif','kiss.gif'
					],
					smiley_descriptions :
					[
						'smiley', 'sad', 'wink', 'laugh', 'cheeky', 'blush', 'surprise',
						'indecision', 'angel', 'cool', 'crying', 'kiss'
					]
			} );


text:
layout: post
date: '2016-09-11'
title: "Timeless Luxe Chiffon strapless layered gown"
category: A-Line
tags: ["layered","bride","timeless","strapless","apparel"]
image: http://www.starbrideapparel.com/3462-thickbox_default/timeless-luxe-chiffon-strapless-layered-gown.jpg
---
Timeless Luxe Chiffon strapless layered gown

On Sales: **$301.794**
<amp-img layout="responsive" width="600" height="600" src="//www.starbrideapparel.com/3462-thickbox_default/timeless-luxe-chiffon-strapless-layered-gown.jpg" alt="Timeless Luxe Chiffon strapless layered gown 0" />
<amp-img layout="responsive" width="600" height="600" src="//www.starbrideapparel.com/3463-thickbox_default/timeless-luxe-chiffon-strapless-layered-gown.jpg" alt="Timeless Luxe Chiffon strapless layered gown 1" />

Buy it: [Timeless Luxe Chiffon strapless layered gown](https://www.starbrideapparel.com/aline-wedding-dresses/1990-timeless-luxe-chiffon-strapless-layered-gown-1463394398812.html "Timeless Luxe Chiffon strapless layered gown")

View more: [A-Line](https://www.starbrideapparel.com/2-aline-wedding-dresses "A-Line")


text:
using MeliMelo.Common.Helpers;
using MeliMelo.Common.Services.Logging;
using MeliMelo.Common.Utils;
using MeliMelo.Mangas.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace MeliMelo.Mangas.Models
{
    /// <summary>
    /// Mangas task
    /// </summary>
    public class MangasTask : TimedTask
    {
        /// <summary>
        /// Creates a new MangaUpdaterImpl
        /// </summary>
        public MangasTask(ILogManager manager, MangaParser parser, MangaRepository repository)
        {
            count_ = 0;
            Interval = kNotificationUpdateInterval;
            log_ = manager.Get("MeliMelo.Mangas");
            parser_ = parser;
            repository_ = repository;
        }

        /// <summary>
        /// Gets the list of manga
        /// </summary>
        public IEnumerable<Manga> Mangas
        {
            get
            {
                return repository_.Items;
            }
        }

        /// <summary>
        /// Adds the given manga to the list
        /// </summary>
        /// <param name="manga">Manga to add</param>
        public void Add(Manga manga)
        {
            repository_.Add(manga);
            Save();
        }

        /// <summary>
        /// Removes the given manga from the list
        /// </summary>
        /// <param name="manga">Manga to remove</param>
        public void Remove(Manga manga)
        {
            repository_.Remove(manga);
            Save();
        }

        /// <summary>
        /// Run the task
        /// </summary>
        public override void Run()
        {
            UpdateAll();
        }

        /// <summary>
        /// Saves any changes
        /// </summary>
        public void Save()
        {
            repository_.Save();
        }

        /// <summary>
        /// Updates the manga list
        /// </summary>
        public void Update()
        {
            UpdateAll(true);
        }

        /// <summary>
        /// Triggered when at least one manga has received an update
        /// </summary>
        public event DataEventHandler<uint> MangaUpdated;

        /// <inheritdoc />
        protected override void OnStart()
        {
            UpdateAll(true);
        }

        /// <inheritdoc />
        protected override void OnStop()
        {
        }

        /// <summary>
        /// Updates all the mangas
        /// </summary>
        /// <param name="force">If we should force to update everything</param>
        private async void UpdateAll(bool force = false)
        {
            uint new_chapters = 0;
            count_ -= kNotificationUpdateInterval;

            foreach (Manga manga in repository_.Items)
            {
                if (count_ <= 0 || force)
                    await UpdateManga(manga);

                new_chapters += (uint)manga.Chapters.Count(chapter => !chapter.IsRead);
            }

            if (new_chapters > 0 && MangaUpdated != null)
                MangaUpdated(new_chapters);

            if (count_ <= 0)
                count_ = kFeedUpdateInterval;

            repository_.Save();
        }

        /// <summary>
        /// Updates the given manga
        /// </summary>
        /// <param name="manga">Manga to update</param>
        /// <returns>If the manga was updated or not</returns>
        private async Task UpdateManga(Manga manga)
        {
            try
            {
                string data = await HttpHelper.Get(manga.Link);

                if (!string.IsNullOrEmpty(data))
                {
                    var document = XDocument.Parse(data);

                    var items = document.Root.Element("channel").Elements("item");

                    foreach (var item in items)
                    {
                        string description_item = item.Element("description").Value;
                        string link_item = item.Element("link").Value;
                        string title_item = item.Element("title").Value;

                        var description = parser_.ParseDescription(description_item);
                        float? number = parser_.ParseChapterNumber(title_item);

                        // We assume the link never changes (Since we don't have an uuid or something
                        // like that. Thanks MangaFox)
                        var chapter = manga.Chapters.FirstOrDefault(c => c.Link == link_item);

                        // Create a new chapter
                        if (chapter == null)
                        {
                            chapter = new Chapter();

                            chapter.Description = description.Item1;
                            chapter.Team = description.Item2;
                            chapter.Link = link_item;
                            chapter.Number = number;
                            chapter.Title = title_item;

                            manga.Add(chapter);
                        }
                        // Update data
                        else
                        {
                            chapter.Description = description.Item1;
                            chapter.Team = description.Item2;
                            chapter.Number = number;
                            chapter.Title = title_item;
                        }
                    }
                }

                log_.Info("Update", "Successfully updated the manga \"" + manga.Name + "\"");
            }
            catch (Exception e)
            {
                log_.Error("Update", "Could not update the manga \"" + manga.Name + "\": "
                    + e.Message);
            }
        }

        /// <summary>
        /// Interval between two feed updates (15 minutes)
        /// </summary>
        private const int kFeedUpdateInterval = 900000;

        /// <summary>
        /// Interval between two notification updates (5 minutes)
        /// </summary>
        private const int kNotificationUpdateInterval = 300000;

        /// <summary>
        /// Count before the next feed update
        /// </summary>
        private uint count_;

        /// <summary>
        /// Logger
        /// </summary>
        private ILog log_;

        /// <summary>
        /// Manga parser (Only parses chapter numbers for now)
        /// </summary>
        private MangaParser parser_;

        /// <summary>
        /// Manga repository
        /// </summary>
        private MangaRepository repository_;
    }
}


text:
'use strict';

let Stream;
let React;
let ReactDOMFizzServer;
let Suspense;

describe('ReactDOMFizzServerNode', () => {
  beforeEach(() => {
    jest.resetModules();
    React = require('react');
    ReactDOMFizzServer = require('react-dom/server');
    Stream = require('stream');
    Suspense = React.Suspense;
  });

  function getTestWritable() {
    const writable = new Stream.PassThrough();
    writable.setEncoding('utf8');
    const output = {result: '', error: undefined};
    writable.on('data', chunk => {
      output.result += chunk;
    });
    writable.on('error', error => {
      output.error = error;
    });
    const completed = new Promise(resolve => {
      writable.on('finish', () => {
        resolve();
      });
      writable.on('error', () => {
        resolve();
      });
    });
    return {writable, completed, output};
  }

  const theError = new Error('This is an error');
  function Throw() {
    throw theError;
  }
  const theInfinitePromise = new Promise(() => {});
  function InfiniteSuspend() {
    throw theInfinitePromise;
  }

  it('should call renderToPipeableStream', () => {
    const {writable, output} = getTestWritable();
    const {pipe} = ReactDOMFizzServer.renderToPipeableStream(

hello world
,
    );
    pipe(writable);
    jest.runAllTimers();
    expect(output.result).toMatchInlineSnapshot(`"<div>hello world</div>"`);
  });

  it('should emit DOCTYPE at the root of the document', () => {
    const {writable, output} = getTestWritable();
    const {pipe} = ReactDOMFizzServer.renderToPipeableStream(

        hello world
      ,
    );
    pipe(writable);
    jest.runAllTimers();
    expect(output.result).toMatchInlineSnapshot(
      `"<!DOCTYPE html><html><body>hello world</body></html>"`,
    );
  });

  it('should emit bootstrap script src at the end', () => {
    const {writable, output} = getTestWritable();
    const {pipe} = ReactDOMFizzServer.renderToPipeableStream(

hello world
,
      {
        bootstrapScriptContent: 'INIT();',
        bootstrapScripts: ['init.js'],
        bootstrapModules: ['init.mjs'],
      },
    );
    pipe(writable);
    jest.runAllTimers();
    expect(output.result).toMatchInlineSnapshot(
      `"<div>hello world</div><script>INIT();</script><script src=\\"init.js\\" async=\\"\\"></script><script type=\\"module\\" src=\\"init.mjs\\" async=\\"\\"></script>"`,
    );
  });

  it('should start writing after pipe', () => {
    const {writable, output} = getTestWritable();
    const {pipe} = ReactDOMFizzServer.renderToPipeableStream(

hello world
,
    );
    jest.runAllTimers();
    // First we write our header.
    output.result +=
      '<!doctype html><title>test</title>';
    // Then React starts writing.
    pipe(writable);
    expect(output.result).toMatchInlineSnapshot(
      `"<!doctype html><html><head><title>test</title><head><body><div>hello world</div>"`,
    );
  });

  it('emits all HTML as one unit if we wait until the end to start', async () => {
    let hasLoaded = false;
    let resolve;
    const promise = new Promise(r => (resolve = r));
    function Wait() {
      if (!hasLoaded) {
        throw promise;
      }
      return 'Done';
    }
    let isCompleteCalls = 0;
    const {writable, output} = getTestWritable();
    const {pipe} = ReactDOMFizzServer.renderToPipeableStream(

        <Suspense fallback="Loading">
          <Wait />
        </Suspense>

,

      {
        onAllReady() {
          isCompleteCalls++;
        },
      },
    );
    await jest.runAllTimers();
    expect(output.result).toBe('');
    expect(isCompleteCalls).toBe(0);
    // Resolve the loading.
    hasLoaded = true;
    await resolve();

    await jest.runAllTimers();

    expect(output.result).toBe('');
    expect(isCompleteCalls).toBe(1);

    // First we write our header.
    output.result +=
      '<!doctype html><title>test</title>';
    // Then React starts writing.
    pipe(writable);
    expect(output.result).toMatchInlineSnapshot(
      `"<!doctype html><html><head><title>test</title><head><body><div><!--$-->Done<!-- --><!--/$--></div>"`,
    );
  });

  it('should error the stream when an error is thrown at the root', async () => {
    const reportedErrors = [];
    const reportedShellErrors = [];
    const {writable, output, completed} = getTestWritable();
    const {pipe} = ReactDOMFizzServer.renderToPipeableStream(

        <Throw />

,
      {
        onError(x) {
          reportedErrors.push(x);
        },
        onShellError(x) {
          reportedShellErrors.push(x);
        },
      },
    );

    // The stream is errored once we start writing.
    pipe(writable);

    await completed;

    expect(output.error).toBe(theError);
    expect(output.result).toBe('');
    // This type of error is reported to the error callback too.
    expect(reportedErrors).toEqual([theError]);
    expect(reportedShellErrors).toEqual([theError]);
  });

  it('should error the stream when an error is thrown inside a fallback', async () => {
    const reportedErrors = [];
    const reportedShellErrors = [];
    const {writable, output, completed} = getTestWritable();
    const {pipe} = ReactDOMFizzServer.renderToPipeableStream(

        <Suspense fallback={<Throw />}>
          <InfiniteSuspend />
        </Suspense>

,

      {
        onError(x) {
          reportedErrors.push(x.message);
        },
        onShellError(x) {
          reportedShellErrors.push(x);
        },
      },
    );
    pipe(writable);

    await completed;

    expect(output.error).toBe(theError);
    expect(output.result).toBe('');
    expect(reportedErrors).toEqual([
      theError.message,
      'The destination stream errored while writing data.',
    ]);
    expect(reportedShellErrors).toEqual([theError]);
  });

  it('should not error the stream when an error is thrown inside suspense boundary', async () => {
    const reportedErrors = [];
    const reportedShellErrors = [];
    const {writable, output, completed} = getTestWritable();
    const {pipe} = ReactDOMFizzServer.renderToPipeableStream(

        <Suspense fallback={
Loading
}>
          <Throw />
        </Suspense>

,
      {
        onError(x) {
          reportedErrors.push(x);
        },
        onShellError(x) {
          reportedShellErrors.push(x);
        },
      },
    );
    pipe(writable);

    await completed;

    expect(output.error).toBe(undefined);
    expect(output.result).toContain('Loading');
    // While no error is reported to the stream, the error is reported to the callback.
    expect(reportedErrors).toEqual([theError]);
    expect(reportedShellErrors).toEqual([]);
  });

  it('should not attempt to render the fallback if the main content completes first', async () => {
    const {writable, output, completed} = getTestWritable();

    let renderedFallback = false;
    function Fallback() {
      renderedFallback = true;
      return 'Loading...';
    }
    function Content() {
      return 'Hi';
    }
    const {pipe} = ReactDOMFizzServer.renderToPipeableStream(
      <Suspense fallback={<Fallback />}>
        <Content />
      </Suspense>,
    );
    pipe(writable);

    await completed;

    expect(output.result).toContain('Hi');
    expect(output.result).not.toContain('Loading');
    expect(renderedFallback).toBe(false);
  });

  it('should be able to complete by aborting even if the promise never resolves', async () => {
    let isCompleteCalls = 0;
    const errors = [];
    const {writable, output, completed} = getTestWritable();
    const {pipe, abort} = ReactDOMFizzServer.renderToPipeableStream(

        <Suspense fallback={
Loading
}>
          <InfiniteSuspend />
        </Suspense>

,
      {
        onError(x) {
          errors.push(x.message);
        },
        onAllReady() {
          isCompleteCalls++;
        },
      },
    );
    pipe(writable);

    jest.runAllTimers();

    expect(output.result).toContain('Loading');
    expect(isCompleteCalls).toBe(0);

    abort(new Error('uh oh'));

    await completed;

    expect(errors).toEqual(['uh oh']);
    expect(output.error).toBe(undefined);
    expect(output.result).toContain('Loading');
    expect(isCompleteCalls).toBe(1);
  });

  it('should fail the shell if you abort before work has begun', async () => {
    let isCompleteCalls = 0;
    const errors = [];
    const shellErrors = [];
    const {writable, output, completed} = getTestWritable();
    const {pipe, abort} = ReactDOMFizzServer.renderToPipeableStream(

        <Suspense fallback={
Loading
}>
          <InfiniteSuspend />
        </Suspense>

,
      {
        onError(x) {
          errors.push(x.message);
        },
        onShellError(x) {
          shellErrors.push(x.message);
        },
        onAllReady() {
          isCompleteCalls++;
        },
      },
    );
    pipe(writable);

    // Currently we delay work so if we abort, we abort the remaining CPU
    // work as well.

    // Abort before running the timers that perform the work
    const theReason = new Error('uh oh');
    abort(theReason);

    jest.runAllTimers();

    await completed;

    expect(errors).toEqual(['uh oh']);
    expect(shellErrors).toEqual(['uh oh']);
    expect(output.error).toBe(theReason);
    expect(output.result).toBe('');
    expect(isCompleteCalls).toBe(0);
  });

  it('should be able to complete by abort when the fallback is also suspended', async () => {
    let isCompleteCalls = 0;
    const errors = [];
    const {writable, output, completed} = getTestWritable();
    const {pipe, abort} = ReactDOMFizzServer.renderToPipeableStream(

        <Suspense fallback="Loading">
          <Suspense fallback={<InfiniteSuspend />}>
            <InfiniteSuspend />
          </Suspense>
        </Suspense>

,
      {
        onError(x) {
          errors.push(x.message);
        },
        onAllReady() {
          isCompleteCalls++;
        },
      },
    );
    pipe(writable);

    jest.runAllTimers();

    expect(output.result).toContain('Loading');
    expect(isCompleteCalls).toBe(0);

    abort();

    await completed;

    expect(errors).toEqual([
      // There are two boundaries that abort
      'The render was aborted by the server without a reason.',
      'The render was aborted by the server without a reason.',
    ]);
    expect(output.error).toBe(undefined);
    expect(output.result).toContain('Loading');
    expect(isCompleteCalls).toBe(1);
  });

  it('should be able to get context value when promise resolves', async () => {
    class DelayClient {
      get() {
        if (this.resolved) return this.resolved;
        if (this.pending) return this.pending;
        return (this.pending = new Promise(resolve => {
          setTimeout(() => {
            delete this.pending;
            this.resolved = 'OK';
            resolve();
          }, 500);
        }));
      }
    }

    const DelayContext = React.createContext(undefined);
    const Component = () => {
      const client = React.useContext(DelayContext);
      if (!client) {
        return 'context not found.';
      }
      const result = client.get();
      if (typeof result === 'string') {
        return result;
      }
      throw result;
    };

    const client = new DelayClient();
    const {writable, output, completed} = getTestWritable();
    ReactDOMFizzServer.renderToPipeableStream(
      <DelayContext.Provider value={client}>
        <Suspense fallback="loading">
          <Component />
        </Suspense>
      </DelayContext.Provider>,
    ).pipe(writable);

    jest.runAllTimers();

    expect(output.error).toBe(undefined);
    expect(output.result).toContain('loading');

    await completed;

    expect(output.error).toBe(undefined);
    expect(output.result).not.toContain('context never found');
    expect(output.result).toContain('OK');
  });

  it('should be able to get context value when calls renderToPipeableStream twice at the same time', async () => {
    class DelayClient {
      get() {
        if (this.resolved) return this.resolved;
        if (this.pending) return this.pending;
        return (this.pending = new Promise(resolve => {
          setTimeout(() => {
            delete this.pending;
            this.resolved = 'OK';
            resolve();
          }, 500);
        }));
      }
    }
    const DelayContext = React.createContext(undefined);
    const Component = () => {
      const client = React.useContext(DelayContext);
      if (!client) {
        return 'context never found';
      }
      const result = client.get();
      if (typeof result === 'string') {
        return result;
      }
      throw result;
    };

    const client0 = new DelayClient();
    const {
      writable: writable0,
      output: output0,
      completed: completed0,
    } = getTestWritable();
    ReactDOMFizzServer.renderToPipeableStream(
      <DelayContext.Provider value={client0}>
        <Suspense fallback="loading">
          <Component />
        </Suspense>
      </DelayContext.Provider>,
    ).pipe(writable0);

    const client1 = new DelayClient();
    const {
      writable: writable1,
      output: output1,
      completed: completed1,
    } = getTestWritable();
    ReactDOMFizzServer.renderToPipeableStream(
      <DelayContext.Provider value={client1}>
        <Suspense fallback="loading">
          <Component />
        </Suspense>
      </DelayContext.Provider>,
    ).pipe(writable1);

    jest.runAllTimers();

    expect(output0.error).toBe(undefined);
    expect(output0.result).toContain('loading');

    expect(output1.error).toBe(undefined);
    expect(output1.result).toContain('loading');

    await Promise.all([completed0, completed1]);

    expect(output0.error).toBe(undefined);
    expect(output0.result).not.toContain('context never found');
    expect(output0.result).toContain('OK');

    expect(output1.error).toBe(undefined);
    expect(output1.result).not.toContain('context never found');
    expect(output1.result).toContain('OK');
  });

  it('should be able to pop context after suspending', async () => {
    class DelayClient {
      get() {
        if (this.resolved) return this.resolved;
        if (this.pending) return this.pending;
        return (this.pending = new Promise(resolve => {
          setTimeout(() => {
            delete this.pending;
            this.resolved = 'OK';
            resolve();
          }, 500);
        }));
      }
    }

    const DelayContext = React.createContext(undefined);
    const Component = () => {
      const client = React.useContext(DelayContext);
      if (!client) {
        return 'context not found.';
      }
      const result = client.get();
      if (typeof result === 'string') {
        return result;
      }
      throw result;
    };

    const client = new DelayClient();
    const {writable, output, completed} = getTestWritable();
    ReactDOMFizzServer.renderToPipeableStream(
      <>
        <DelayContext.Provider value={client}>
          <Suspense fallback="loading">
            <Component />
          </Suspense>
        </DelayContext.Provider>
        <DelayContext.Provider value={client}>
          <Suspense fallback="loading">
            <Component />
          </Suspense>
        </DelayContext.Provider>
      </>,
    ).pipe(writable);

    jest.runAllTimers();

    expect(output.error).toBe(undefined);
    expect(output.result).toContain('loading');

    await completed;

    expect(output.error).toBe(undefined);
    expect(output.result).not.toContain('context never found');
    expect(output.result).toContain('OK');
  });

  it('should not continue rendering after the writable ends unexpectedly', async () => {
    let hasLoaded = false;
    let resolve;
    let isComplete = false;
    let rendered = false;
    const promise = new Promise(r => (resolve = r));
    function Wait() {
      if (!hasLoaded) {
        throw promise;
      }
      rendered = true;
      return 'Done';
    }
    const errors = [];
    const {writable, completed} = getTestWritable();
    const {pipe} = ReactDOMFizzServer.renderToPipeableStream(

        <Suspense fallback={
Loading
}>
          <Wait />
        </Suspense>

,
      {
        onError(x) {
          errors.push(x.message);
        },
        onAllReady() {
          isComplete = true;
        },
      },
    );
    pipe(writable);

    expect(rendered).toBe(false);
    expect(isComplete).toBe(false);

    writable.end();

    await jest.runAllTimers();

    hasLoaded = true;
    resolve();

    await completed;

    expect(errors).toEqual([
      'The destination stream errored while writing data.',
    ]);
    expect(rendered).toBe(false);
    expect(isComplete).toBe(true);
  });
});