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

using Poderosa.Commands;

namespace Poderosa.Benchmark {

    /// <summary>
    /// A menu group for Benchmark Plugin
    /// </summary>
    internal class BenchmarkMenuGroup : PoderosaMenuGroupImpl {

        /// <summary>
        /// Constructor
        /// </summary>
        public BenchmarkMenuGroup()
            : base(new BenchmarkMenuFolder()) {
        }

        /// <summary>
        /// Menu folder
        /// </summary>
        private class BenchmarkMenuFolder : IPoderosaMenuFolder {

            private readonly IPoderosaMenuGroup[] _childGroups;

            public BenchmarkMenuFolder() {
                _childGroups = new IPoderosaMenuGroup[] {
                    new PoderosaMenuGroupImpl(
                        new IPoderosaMenu[] {
                            new StartXTermBenchmark(),
                            new StartDataLoadBenchmark(),
                        })
                };
            }

            public IPoderosaMenuGroup[] ChildGroups {
                get {
                    return _childGroups;
                }
            }

            public string Text {
                get {
                    return BenchmarkPlugin.Instance.StringResource.GetString("Menu.Benchmark");
                }
            }

            public bool IsEnabled(ICommandTarget target) {
                return true;
            }

            public bool IsChecked(ICommandTarget target) {
                return false;
            }

            public IAdaptable GetAdapter(Type adapter) {
                return BenchmarkPlugin.Instance.PoderosaWorld.AdapterManager.GetAdapter(this, adapter);
            }
        }

        /// <summary>
        /// Base class of a menu item which implements IPoderosaCommand
        /// </summary>
        private abstract class AbstractBenchmarkMenuItem : IPoderosaMenuItem, IPoderosaCommand {

            private readonly string _menuTextId;

            public AbstractBenchmarkMenuItem(string menuTextId) {
                _menuTextId = menuTextId;
            }

            public abstract CommandResult InternalExecute(ICommandTarget target, params IAdaptable[] args);

            public bool CanExecute(ICommandTarget target) {
                return true;
            }

            public IPoderosaCommand AssociatedCommand {
                get {
                    return this;
                }
            }

            public string Text {
                get {
                    return BenchmarkPlugin.Instance.StringResource.GetString(_menuTextId);
                }
            }

            public bool IsEnabled(ICommandTarget target) {
                return true;
            }

            public bool IsChecked(ICommandTarget target) {
                return false;
            }

            public IAdaptable GetAdapter(Type adapter) {
                return BenchmarkPlugin.Instance.PoderosaWorld.AdapterManager.GetAdapter(this, adapter);
            }
        }

        /// <summary>
        /// XTerm benchmark
        /// </summary>
        private class StartXTermBenchmark : AbstractBenchmarkMenuItem {

            public StartXTermBenchmark()
                : base("Menu.StartXTermBenchmark") {
            }

            public override CommandResult InternalExecute(ICommandTarget target, params IAdaptable[] args) {
                XTermBenchmarkPattern pattern;
                using (ChoosePatternDialog dialog = new ChoosePatternDialog()) {
                    DialogResult result = dialog.ShowDialog();
                    if (result != DialogResult.OK)
                        return CommandResult.Cancelled;
                    pattern = dialog.Pattern;
                }

                XTermBenchmark benchmark = new XTermBenchmark(target, pattern);
                return benchmark.Start();
            }
        }

        /// <summary>
        /// XTerm benchmark
        /// </summary>
        private class StartDataLoadBenchmark : AbstractBenchmarkMenuItem {

            public StartDataLoadBenchmark()
                : base("Menu.StartDataLoadBenchmark") {
            }

            public override CommandResult InternalExecute(ICommandTarget target, params IAdaptable[] args) {
                string path;
                int repeat;
                using (DataLoadDialog dialog = new DataLoadDialog()) {
                    DialogResult result = dialog.ShowDialog();
                    if (result != DialogResult.OK)
                        return CommandResult.Cancelled;
                    path = dialog.DataFileToLoad;
                    repeat = dialog.Repeat;
                }

                byte[] data = LoadFile(path);
                if (data == null)
                    return CommandResult.Failed;

                DataLoadBenchmark benchmark = new DataLoadBenchmark(target, data, repeat);
                return benchmark.Start();
            }

            private static byte[] LoadFile(string path) {
                FileInfo fileInfo = new FileInfo(path);
                long fileSize = fileInfo.Length;
                int dataSize = (fileSize > Int32.MaxValue) ? Int32.MaxValue : (int)fileSize;
                byte[] data = new byte[dataSize];
                using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) {
                    int readSize = fs.Read(data, 0, dataSize);
                    if (readSize != dataSize)
                        return null;
                }
                return data;
            }
        }
    }

}


text:
<?php
namespace PayrollDeduction\Controller;

use Application\Controller\BaseController;
use PayrollDeduction\Service\PayrollDeductionServiceInterface;
use PayrollDeduction\Form\PayrollDeductionForm;
use Zend\View\Model\ViewModel;

class UpdateController extends BaseController
{
    /**
     *
     * @var PayrollDeductionServiceInterface
     */
    protected $service;

    /**
     *
     * @var PayrollDeductionForm
     */
    protected $form;

    /**
     *
     * @param PayrollDeductionServiceInterface $service
     * @param PayrollDeductionForm $form
     */
    public function __construct(PayrollDeductionServiceInterface $service, PayrollDeductionForm $form)
    {
        $this->service = $service;

        $this->form = $form;

    }

    /**
     *
     * {@inheritDoc}
     * @see \Zend\Mvc\Controller\AbstractActionController::indexAction()
     */
    public function indexAction()
    {
        $request = $this->getRequest();

        $id = $this->params()->fromRoute('payrollDeductionId');

        $entity = $this->service->get($id);

        if(! $entity) {
            $this->flashMessenger()->addErrorMessage('Payroll deduction not found');

            return $this->redirect()->toRoute('payrol-index');
        }

        // if we have a post
        if ($request->isPost()) {

            $postData = $request->getPost();

            $this->form->setData($postData);

            // if the form is valid
            if ($this->form->isValid()) {

                $entity = $this->form->getData();

                $payrollDeductionEntity = $this->service->save($entity);

                // trigger event
                $this->getEventManager()->trigger('productDeductionUpdate', $this, array(
                    'payrollDeductionEntity' => $payrollDeductionEntity,
                    'authId' => $this->identity()->getAuthId(),
                    'historyUrl' => $this->getRequest()->getUri()
                ));

                $this->flashMessenger()->addSuccessMessage('Payroll Deduction saved');

                return $this->redirect()->toRoute('payroll-view', array('payrollId' => $entity->getPayrollId()));
            }
        }

        // bind form
        $this->form->bind($entity);

        // return view model
        return new ViewModel(array(
            'form' => $this->form
        ));
    }
}

redpajama_set_name: RedPajamaGithub


text:
module CommentTags
  include Radiant::Taggable

  desc "Provides tags and behaviors to support comments in Radiant."

  desc %{
    Renders the contained elements if comments are enabled on the page.
  }
  tag "if_enable_comments" do |tag|
    tag.expand if (tag.locals.page.enable_comments?)
  end
  # makes more sense to me
  tag "if_comments_enabled" do |tag|
    tag.expand if (tag.locals.page.enable_comments?)
  end

  desc %{
    Renders the contained elements unless comments are enabled on the page.
  }
  tag "unless_enable_comments" do |tag|
    tag.expand unless (tag.locals.page.enable_comments?)
  end

  # makes more sense to me
  tag "unless_comments_enabled" do |tag|
    tag.expand unless (tag.locals.page.enable_comments?)
  end

  desc %{
     Expands if this is the first comment
  }
  tag "if_first" do |tag|
    tag.expand if tag.locals.comments.first.eql? tag.locals.comment
  end

  desc %{
     Expands if this is the last comment
  }
  tag "if_last" do |tag|
    tag.expand if tag.locals.comments.last.eql? tag.locals.comment
  end

  desc %{
    Renders the contained elements if the page has comments.
  }
  tag "if_comments" do |tag|
    tag.expand if tag.locals.page.has_visible_comments?
  end

  desc %{
    Renders the contained elements unless the page has comments.
  }
  tag "unless_comments" do |tag|
    tag.expand unless tag.locals.page.has_visible_comments?
  end

  desc %{
    Renders the contained elements if the page has comments _or_ comment is enabled on it.
  }
  tag "if_comments_or_enable_comments" do |tag|
    tag.expand if(tag.locals.page.has_visible_comments? || tag.locals.page.enable_comments?)
  end

  desc %{
    Gives access to comment-related tags
  }
  tag "comments" do |tag|
    comments = tag.locals.page.comments.approved
    tag.expand
  end

  desc %{
    Cycles through each comment and renders the enclosed tags for each.
  }
  tag "comments:each" do |tag|
    page = tag.locals.page
    tag.locals.comments = page.comments.approved.to_a
    tag.locals.comments << page.selected_comment if page.selected_comment && page.selected_comment.unapproved?
    result = []
    tag.locals.comments.each_with_index do |comment, index|
      tag.locals.comment = comment
      tag.locals.index = index
      result << tag.expand
    end
    result
  end

  desc %{
    Gives access to the particular fields for each comment.
  }
  tag "comments:field" do |tag|
    tag.expand
  end

  desc %{
    Renders the index number for this comment.
  }
  tag 'comments:field:index' do |tag|
    tag.locals.index + 1
  end

  %w(id author author_email author_url content content_html filter_id).each do |field|
    desc %{ Print the value of the #{field} field for this comment. }
    tag "comments:field:#{field}" do |tag|
      options = tag.attr.dup
      #options.inspect
      value = tag.locals.comment.send(field)
      value
    end
  end

  desc %{
    Renders the date a comment was created.

    *Usage:*

<r:date [format="%A, %B %d, %Y"] />

  }
  tag 'comments:field:date' do |tag|
    comment = tag.locals.comment
    format = (tag.attr['format'] || '%A, %B %d, %Y')
    date = comment.created_at
    date.strftime(format)
  end

  desc %{
    Renders a link if there's an author_url, otherwise just the author's name.
  }
  tag "comments:field:author_link" do |tag|
    if tag.locals.comment.author_url.blank?
      tag.locals.comment.author
    else
      %(#{tag.locals.comment.author})
    end
  end

  desc %{
    Renders the contained elements if the comment has an author_url specified.
  }
  tag "comments:field:if_author_url" do |tag|
    tag.expand unless tag.locals.comment.author_url.blank?
  end

  desc %{
    Renders the contained elements if the comment is selected - that is, if it is a comment
    the user has just posted
  }
  tag "comments:field:if_selected" do |tag|
    tag.expand if tag.locals.comment == tag.locals.page.selected_comment
  end

  desc %{
    Renders the contained elements if the comment has been approved
  }
  tag "comments:field:if_approved" do |tag|
    tag.expand if tag.locals.comment.approved?
  end

  desc %{
    Renders the contained elements if the comment has not been approved
  }
  tag "comments:field:unless_approved" do |tag|
    tag.expand unless tag.locals.comment.approved?
  end

  desc %{
    Renders a Gravatar URL for the author of the comment.
  }
  tag "comments:field:gravatar_url" do |tag|
    email = tag.locals.comment.author_email
    size = tag.attr['size']
    format = tag.attr['format']
    rating = tag.attr['rating']
    default = tag.attr['default']
    md5 = Digest::MD5.hexdigest(email)
    returning "http://www.gravatar.com/avatar/#{md5}" do |url|
      url << ".#{format.downcase}" if format
      if size || rating || default
        attrs = []
        attrs << "s=#{size}" if size
        attrs << "d=#{default}" if default
        attrs << "r=#{rating.downcase}" if rating
        url << "?#{attrs.join('&')}"
      end
    end
  end

  desc %{
    Renders a comment form.

    *Usage:*
    <r:comment:form [class="comments" id="comment_form"]>...</r:comment:form>
  }
  tag "comments:form" do |tag|
    attrs = tag.attr.symbolize_keys
    html_class, html_id = attrs[:class], attrs[:id]
    r = %Q{ <form action="#{tag.locals.page.url}#{'comments' unless Radiant::Config['comments.post_to_page?']}}
      r << %Q{##{html_id}} unless html_id.blank?
    r << %{" method="post" } #comlpete the quotes for the action
      r << %{ id="#{html_id}" } unless html_id.blank?
      r << %{ class="#{html_class}" } unless html_class.blank?
    r << '>' #close the form element
    r <<  tag.expand
    r << %{</form>}
    r
  end

  tag 'comments:error' do |tag|
    if comment = tag.locals.page.last_comment
      if on = tag.attr['on']
        if error = comment.errors.on(on)
          tag.locals.error_message = error
          tag.expand
        end
      else
        tag.expand if !comment.valid?
      end
    end
  end

  tag 'comments:error:message' do |tag|
    tag.locals.error_message
  end

  %w(text password hidden).each do |type|
    desc %{Builds a #{type} form field for comments.}
    tag "comments:#{type}_field_tag" do |tag|
      attrs = tag.attr.symbolize_keys
      r = %{<input type="#{type}"}
      r << %{ id="comment_#{attrs[:name]}"}
      r << %{ name="comment[#{attrs[:name]}]"}
      r << %{ class="#{attrs[:class]}"} if attrs[:class]
      if value = (tag.locals.page.last_comment ? tag.locals.page.last_comment.send(attrs[:name]) : attrs[:value])
        r << %{ value="#{value}" }
      end
      r << %{ />}
    end
  end

  %w(submit reset).each do |type|
    desc %{Builds a #{type} form button for comments.}
    tag "comments:#{type}_tag" do |tag|
      attrs = tag.attr.symbolize_keys
      r = %{<input type="#{type}"}
      r << %{ id="#{attrs[:name]}"}
      r << %{ name="#{attrs[:name]}"}
      r << %{ class="#{attrs[:class]}"} if attrs[:class]
      r << %{ value="#{attrs[:value]}" } if attrs[:value]
      r << %{ />}
    end
  end

  desc %{Builds a text_area form field for comments.}
  tag "comments:text_area_tag" do |tag|
    attrs = tag.attr.symbolize_keys
    r = %{<textarea}
    r << %{ id="comment_#{attrs[:name]}"}
    r << %{ name="comment[#{attrs[:name]}]"}
    r << %{ class="#{attrs[:class]}"} if attrs[:class]
    r << %{ rows="#{attrs[:rows]}"} if attrs[:rows]
    r << %{ cols="#{attrs[:cols]}"} if attrs[:cols]
    r << %{>}
    if content = (tag.locals.page.last_comment ? tag.locals.page.last_comment.send(attrs[:name]) : attrs[:content])
      r << content
    end
    r << %{</textarea>}
  end

  desc %{Build a drop_box form field for the filters avaiable.}
  tag "comments:filter_box_tag" do |tag|
    attrs = tag.attr.symbolize_keys
    value = attrs.delete(:value)
    name = attrs.delete(:name)
    r =  %{<select name="comment[#{name}]"}
    unless attrs.empty?
      r << " "
      r << attrs.map {|k,v| %Q(#{k}="#{v}") }.join(" ")
    end
    r << %{>}

    TextFilter.descendants.each do |filter|

      r << %{<option value="#{filter.filter_name}"}
      r << %{ selected="selected"} if value == filter.filter_name
      r << %{>#{filter.filter_name}</option>}

    end

    r << %{</select>}
  end

  desc %{Prints the number of comments. }
  tag "comments:count" do |tag|
    tag.locals.page.comments.approved.count
  end

  tag "recent_comments" do |tag|
    tag.expand
  end

  desc %{Returns the last [limit] comments throughout the site.

    *Usage:*

<r:recent_comments:each [limit="10"]>...</r:recent_comments:each>

    }
  tag "recent_comments:each" do |tag|
    limit = tag.attr['limit'] || 10
    comments = Comment.approved.recent.all(:limit => limit)
    result = []
    comments.each_with_index do |comment, index|
      tag.locals.comment = comment
      tag.locals.index = index
      tag.locals.page = comment.page
      result << tag.expand
    end
    result
  end

  desc %{
    Use this to prevent spam bots from filling your site with spam.

    *Usage:*

What day comes after Monday? <r:comments:spam_answer_tag answer="Tuesday" />

  }
  tag "comments:spam_answer_tag" do |tag|
      attrs = tag.attr.symbolize_keys
      valid_spam_answer = attrs[:answer] || 'hemidemisemiquaver'
      md5_answer = Digest::MD5.hexdigest(valid_spam_answer.to_slug)
      r = %{<input type="text" id="comment_spam_answer" name="comment[spam_answer]"}
      r << %{ class="#{attrs[:class]}"} if attrs[:class]
      if value = (tag.locals.page.last_comment ? tag.locals.page.last_comment.send(:spam_answer) : '')
        r << %{ value="#{value}" }
      end
      r << %{ />}
      r << %{<input type="hidden" name="comment[valid_spam_answer]" value="#{md5_answer}" />}
  end

  desc %{
    Render the contained elements if using the simple spam filter.
  }
  tag "if_comments_simple_spam_filter_enabled" do |tag|
    tag.expand if Comment.simple_spam_filter_enabled?
  end

  desc %{
    Render the contained elements unless using the simple spam filter.
  }
  tag "unless_comments_simple_spam_filter_enabled" do |tag|
    tag.expand unless Comment.simple_spam_filter_enabled?
  end

end


text:
package com.twitter.util

/**
 * An alternative interface for performing Future transformations;
 * that is, converting a Future[A] to a Future[B]. This interface is
 * designed to be friendly to Java users since it does not require
 * creating many small Function objects. It is used in conjunction
 * with `transformedBy`.
 *
 * You must override one of `{map, flatMap}`. If you override both
 * `map` and `flatMap`, `flatMap` takes precedence. If you fail to
 * override one of `{map, flatMap}`, an `AbstractMethodError` will be
 * thrown at Runtime.
 *
 * '''Note:''' to end a result with a failure, we encourage you to use either
 * `flatMap` or `rescue` and return a failed Future, instead of throwing an
 * exception.  A failed future can be used by returning
 * `Future.exception(throwable)` instead of throwing an exception.
 *
 * @see [[Future.transform]] which is the equivalent Scala API for further details.
 * @see [[Future.transformedBy]] for using it with a `Future`.
 * @see [[FutureEventListener]] for a Java API for side-effects.
 */
abstract class FutureTransformer[-A, +B] {

  /**
   * Invoked if the computation completes successfully. Returns the
   * new transformed value in a Future.
   */
  def flatMap(value: A): Future[B] = Future.value(map(value))

  /**
   * Invoked if the computation completes successfully. Returns the
   * new transformed value.
   *
   * ''Note'': this method will throw an `AbstractMethodError` if it is not overridden.
   */
  def map(value: A): B =
    throw new AbstractMethodError(s"`map` must be implemented by $this")

  /**
   * Invoked if the computation completes unsuccessfully. Returns the
   * new Future value.
   */
  def rescue(throwable: Throwable): Future[B] = Future.value(handle(throwable))

  /**
   * Invoked if the computation fails. Returns the new transformed
   * value.
   */
  def handle(throwable: Throwable): B = throw throwable
}


text:
#ifndef XSC_CFG_BUILDER_H
#define XSC_CFG_BUILDER_H

#include "VisitorTracker.h"
#include "InstructionFactory.h"
#include "Module.h"

namespace Xsc
{

// CFG builder class.
class CFGBuilder : public VisitorTracker
{

    public:

        //CFGBuilder(Log* log);

    private:

        struct CFG
        {
            BasicBlock* in;
            BasicBlock* out;
        };

        /* === Functions === */

        // Makes a CFG with an input and output basic block.
        CFG MakeCFG(const std::string& name);

        // Pushes the specified input/output basic blocks to the CFG stack.
        void PushCFG(const CFG& cfg);

        // Pops and returns the top most input/output basic blocks from the CFG stack.
        CFG PopCFG();

        // Pushes the specified basic block to the break block stack (e.g. "endif", "endfor" etc.).
        void PushBreak(BasicBlock* bb);

        // Pops the basic block from the break block stack.
        void PopBreak();

        // Returns the basic block from the break block stack.
        BasicBlock* TopBreak() const;

        /* --- Visitor implementation --- */

        DECL_VISIT_PROC( Program           );
        DECL_VISIT_PROC( CodeBlock         );
        DECL_VISIT_PROC( SwitchCase        );
        DECL_VISIT_PROC( ArrayDimension    );
        DECL_VISIT_PROC( TypeSpecifier     );

        DECL_VISIT_PROC( VarDecl           );
        DECL_VISIT_PROC( StructDecl        );
        DECL_VISIT_PROC( SamplerDecl       );

        DECL_VISIT_PROC( FunctionDecl      );
        DECL_VISIT_PROC( UniformBufferDecl );
        DECL_VISIT_PROC( BufferDeclStmnt   );
        DECL_VISIT_PROC( SamplerDeclStmnt  );
        DECL_VISIT_PROC( VarDeclStmnt      );
        DECL_VISIT_PROC( AliasDeclStmnt    );
        DECL_VISIT_PROC( BasicDeclStmnt    );

        DECL_VISIT_PROC( NullStmnt         );
        DECL_VISIT_PROC( CodeBlockStmnt    );
        DECL_VISIT_PROC( ForLoopStmnt      );
        DECL_VISIT_PROC( WhileLoopStmnt    );
        DECL_VISIT_PROC( DoWhileLoopStmnt  );
        DECL_VISIT_PROC( IfStmnt           );
        DECL_VISIT_PROC( ElseStmnt         );
        DECL_VISIT_PROC( SwitchStmnt       );
        DECL_VISIT_PROC( ExprStmnt         );
        DECL_VISIT_PROC( ReturnStmnt       );
        DECL_VISIT_PROC( CtrlTransferStmnt );

        DECL_VISIT_PROC( SequenceExpr      );
        DECL_VISIT_PROC( LiteralExpr       );
        DECL_VISIT_PROC( TypeSpecifierExpr );
        DECL_VISIT_PROC( TernaryExpr       );
        DECL_VISIT_PROC( BinaryExpr        );
        DECL_VISIT_PROC( UnaryExpr         );
        DECL_VISIT_PROC( PostUnaryExpr     );
        DECL_VISIT_PROC( CallExpr          );
        DECL_VISIT_PROC( BracketExpr       );
        DECL_VISIT_PROC( ObjectExpr        );
        DECL_VISIT_PROC( AssignExpr        );
        DECL_VISIT_PROC( ArrayExpr         );
        DECL_VISIT_PROC( CastExpr          );
        DECL_VISIT_PROC( InitializerExpr   );

        /* --- Helper functions for CFG builder --- */

        /* === Members === */

        Module                  module_;
        ModuleFunction*         moduleFunc_         = nullptr;  // Active module function.

        std::stack<CFG>         cfgStack_;
        std::stack<BasicBlock*> breakBlockStack_;

        InstructionFactory      factory_;

};

} // /namespace Xsc

#endif

// ================================================================================


text:
cask :v1 => 'oovoo' do
  version :latest
  sha256 :no_check

  url 'http://download.cdn.oovoo.com/download/ooVoo.dmg'
  homepage 'http://www.oovoo.com'
  license :unknown

  app 'Oovoo.app'
end


text:
import json
import codecs
from collections import OrderedDict
from scrapy.exceptions import DropItem

import pymongo

class DuplicatesPipeline(object):

    def __init__(self):
        self.client = pymongo.MongoClient('mongodb://114.215.104.130:27017/')
        self.db = self.client.zhidao

    def process_item(self, item, spider):
        if self.db.QuestionItem.find_one({"qid": item["qid"]}):
            raise DropItem("Duplicate item found: %s" % item)
        else:
            return item

class JsonWithEncodingPipeline(object):

    def __init__(self):
        self.file = codecs.open('data_utf8.json', 'w', encoding='utf-8')

    def process_item(self, item, spider):
        line = json.dumps(OrderedDict(item), ensure_ascii=False, sort_keys=False) + "\n"
        self.file.write(line)
        return item

    def spider_closed(self, spider):
        self.file.close()

class MongoPipeline(object):

    def __init__(self, mongo_uri, mongo_db):
        self.mongo_uri = mongo_uri
        self.mongo_db = mongo_db

    @classmethod
    def from_crawler(cls, crawler):
        return cls(
            mongo_uri=crawler.settings.get('MONGO_URI'),
            mongo_db=crawler.settings.get('MONGO_DATABASE', 'zhidao')
        )

    def open_spider(self, spider):
        self.client = pymongo.MongoClient(self.mongo_uri)
        self.db = self.client[self.mongo_db]

    def close_spider(self, spider):
        self.client.close()

    def process_item(self, item, spider):
        collection_name = item.__class__.__name__
        self.db[collection_name].insert(dict(item))
        return item


text:
/* AUTO-GENERATED FILE.  DO NOT MODIFY.
 *
 * This class was automatically generated by the
 * aapt tool from the resource data it found.  It
 * should not be modified by hand.
 */

package io.cordova.hellocordova;

public final class R {
    public static final class attr {
    }
    public static final class drawable {
        public static final int ic_action_next_item=0x7f020000;
        public static final int ic_action_previous_item=0x7f020001;
        public static final int ic_action_remove=0x7f020002;
        public static final int icon=0x7f020003;
        public static final int screen=0x7f020004;
        public static final int splash=0x7f020005;
    }
    public static final class string {
        public static final int app_name=0x7f040000;
    }
    public static final class xml {
        public static final int config=0x7f030000;
    }
}


text:
#ifndef __XEN_PUBLIC_ELFNOTE_H__
#define __XEN_PUBLIC_ELFNOTE_H__

/*
 * `incontents 200 elfnotes ELF notes
 *
 * The notes should live in a PT_NOTE segment and have "Xen" in the
 * name field.
 *
 * Numeric types are either 4 or 8 bytes depending on the content of
 * the desc field.
 *
 * LEGACY indicated the fields in the legacy __xen_guest string which
 * this a note type replaces.
 *
 * String values (for non-legacy) are NULL terminated ASCII, also known
 * as ASCIZ type.
 */

/*
 * NAME=VALUE pair (string).
 */
#define XEN_ELFNOTE_INFO           0

/*
 * The virtual address of the entry point (numeric).
 *
 * LEGACY: VIRT_ENTRY
 */
#define XEN_ELFNOTE_ENTRY          1

/* The virtual address of the hypercall transfer page (numeric).
 *
 * LEGACY: HYPERCALL_PAGE. (n.b. legacy value is a physical page
 * number not a virtual address)
 */
#define XEN_ELFNOTE_HYPERCALL_PAGE 2

/* The virtual address where the kernel image should be mapped (numeric).
 *
 * Defaults to 0.
 *
 * LEGACY: VIRT_BASE
 */
#define XEN_ELFNOTE_VIRT_BASE      3

/*
 * The offset of the ELF paddr field from the actual required
 * pseudo-physical address (numeric).
 *
 * This is used to maintain backwards compatibility with older kernels
 * which wrote __PAGE_OFFSET into that field. This field defaults to 0
 * if not present.
 *
 * LEGACY: ELF_PADDR_OFFSET. (n.b. legacy default is VIRT_BASE)
 */
#define XEN_ELFNOTE_PADDR_OFFSET   4

/*
 * The version of Xen that we work with (string).
 *
 * LEGACY: XEN_VER
 */
#define XEN_ELFNOTE_XEN_VERSION    5

/*
 * The name of the guest operating system (string).
 *
 * LEGACY: GUEST_OS
 */
#define XEN_ELFNOTE_GUEST_OS       6

/*
 * The version of the guest operating system (string).
 *
 * LEGACY: GUEST_VER
 */
#define XEN_ELFNOTE_GUEST_VERSION  7

/*
 * The loader type (string).
 *
 * LEGACY: LOADER
 */
#define XEN_ELFNOTE_LOADER         8

/*
 * The kernel supports PAE (x86/32 only, string = "yes", "no" or
 * "bimodal").
 *
 * For compatibility with Xen 3.0.3 and earlier the "bimodal" setting
 * may be given as "yes,bimodal" which will cause older Xen to treat
 * this kernel as PAE.
 *
 * LEGACY: PAE (n.b. The legacy interface included a provision to
 * indicate 'extended-cr3' support allowing L3 page tables to be
 * placed above 4G. It is assumed that any kernel new enough to use
 * these ELF notes will include this and therefore "yes" here is
 * equivalent to "yes[entended-cr3]" in the __xen_guest interface.
 */
#define XEN_ELFNOTE_PAE_MODE       9

/*
 * The features supported/required by this kernel (string).
 *
 * The string must consist of a list of feature names (as given in
 * features.h, without the "XENFEAT_" prefix) separated by '|'
 * characters. If a feature is required for the kernel to function
 * then the feature name must be preceded by a '!' character.
 *
 * LEGACY: FEATURES
 */
#define XEN_ELFNOTE_FEATURES      10

/*
 * The kernel requires the symbol table to be loaded (string = "yes" or "no")
 * LEGACY: BSD_SYMTAB (n.b. The legacy treated the presence or absence
 * of this string as a boolean flag rather than requiring "yes" or
 * "no".
 */
#define XEN_ELFNOTE_BSD_SYMTAB    11

/*
 * The lowest address the hypervisor hole can begin at (numeric).
 *
 * This must not be set higher than HYPERVISOR_VIRT_START. Its presence
 * also indicates to the hypervisor that the kernel can deal with the
 * hole starting at a higher address.
 */
#define XEN_ELFNOTE_HV_START_LOW  12

/*
 * List of maddr_t-sized mask/value pairs describing how to recognize
 * (non-present) L1 page table entries carrying valid MFNs (numeric).
 */
#define XEN_ELFNOTE_L1_MFN_VALID  13

/*
 * Whether or not the guest supports cooperative suspend cancellation.
 * This is a numeric value.
 *
 * Default is 0
 */
#define XEN_ELFNOTE_SUSPEND_CANCEL 14

/*
 * The (non-default) location the initial phys-to-machine map should be
 * placed at by the hypervisor (Dom0) or the tools (DomU).
 * The kernel must be prepared for this mapping to be established using
 * large pages, despite such otherwise not being available to guests.
 * The kernel must also be able to handle the page table pages used for
 * this mapping not being accessible through the initial mapping.
 * (Only x86-64 supports this at present.)
 */
#define XEN_ELFNOTE_INIT_P2M      15

/*
 * Whether or not the guest can deal with being passed an initrd not
 * mapped through its initial page tables.
 */
#define XEN_ELFNOTE_MOD_START_PFN 16

/*
 * The features supported by this kernel (numeric).
 *
 * Other than XEN_ELFNOTE_FEATURES on pre-4.2 Xen, this note allows a
 * kernel to specify support for features that older hypervisors don't
 * know about. The set of features 4.2 and newer hypervisors will
 * consider supported by the kernel is the combination of the sets
 * specified through this and the string note.
 *
 * LEGACY: FEATURES
 */
#define XEN_ELFNOTE_SUPPORTED_FEATURES 17

/*
 * The number of the highest elfnote defined.
 */
#define XEN_ELFNOTE_MAX XEN_ELFNOTE_SUPPORTED_FEATURES

/*
 * System information exported through crash notes.
 *
 * The kexec / kdump code will create one XEN_ELFNOTE_CRASH_INFO
 * note in case of a system crash. This note will contain various
 * information about the system, see xen/include/xen/elfcore.h.
 */
#define XEN_ELFNOTE_CRASH_INFO 0x1000001

/*
 * System registers exported through crash notes.
 *
 * The kexec / kdump code will create one XEN_ELFNOTE_CRASH_REGS
 * note per cpu in case of a system crash. This note is architecture
 * specific and will contain registers not saved in the "CORE" note.
 * See xen/include/xen/elfcore.h for more information.
 */
#define XEN_ELFNOTE_CRASH_REGS 0x1000002

/*
 * xen dump-core none note.
 * xm dump-core code will create one XEN_ELFNOTE_DUMPCORE_NONE
 * in its dump file to indicate that the file is xen dump-core
 * file. This note doesn't have any other information.
 * See tools/libxc/xc_core.h for more information.
 */
#define XEN_ELFNOTE_DUMPCORE_NONE               0x2000000

/*
 * xen dump-core header note.
 * xm dump-core code will create one XEN_ELFNOTE_DUMPCORE_HEADER
 * in its dump file.
 * See tools/libxc/xc_core.h for more information.
 */
#define XEN_ELFNOTE_DUMPCORE_HEADER             0x2000001

/*
 * xen dump-core xen version note.
 * xm dump-core code will create one XEN_ELFNOTE_DUMPCORE_XEN_VERSION
 * in its dump file. It contains the xen version obtained via the
 * XENVER hypercall.
 * See tools/libxc/xc_core.h for more information.
 */
#define XEN_ELFNOTE_DUMPCORE_XEN_VERSION        0x2000002

/*
 * xen dump-core format version note.
 * xm dump-core code will create one XEN_ELFNOTE_DUMPCORE_FORMAT_VERSION
 * in its dump file. It contains a format version identifier.
 * See tools/libxc/xc_core.h for more information.
 */
#define XEN_ELFNOTE_DUMPCORE_FORMAT_VERSION     0x2000003

#endif /* __XEN_PUBLIC_ELFNOTE_H__ */

/*
 * Local variables:
 * mode: C
 * c-file-style: "BSD"
 * c-basic-offset: 4
 * tab-width: 4
 * indent-tabs-mode: nil
 * End:
 */


text:
var findRoot = require("find-root"),
	Path = require("path"),
	utils = require("./lib/utils"),
	fs = require("fs");

// dir should be the dir you want to find the
// nearest package.json to.
module.exports = function(dir){

	// Module object
	var park = {};

	// Returns package.json readable stream
	park.read = function(){
		return fs.createReadStream(park.path);
	}

	// Get value from package.json
	// If key contains dots, it assumes object string syntax.
	park.get = function(key){
		return utils.getSubObject(park.obj, key);
	}

	// Set value on package object and save
	// If key contains dots, it assumes object string syntax.
	// Returns writeable stream
	park.set = function(key, val){
		// Set value on object key
		utils.setSubObject(park.obj, key, val);
		return park.save();
	}

	// Save package.json as prettified JSON from park.obj
	// Returns writeable stream
	park.save = function(){
		// Pretty JSON buffer
		var json = new Buffer(JSON.stringify(park.obj, null, 2));

		var stream = fs.createWriteStream(park.path, json);
		stream.write(json);
		stream.end();

		// Returns a writeable stream
		return stream;
	}

	// Get closest package.json to dir, recursing upwards
	// until it's found.
	park.path = Path.join(findRoot(dir), "package.json");

	// package.json as an object
	park.obj = require(park.path);

	// Return module
	return park;

}


text:
# Building and shipping a .NET Core application with Docker and TravisCI

With the .NET Core ecosystem slowly maturing since the [first official release](http://www.hanselman.com/blog/NETCore10IsNowReleased.aspx) this year I started to increasingly spend more time playing and building software with it.

I am a big fan of managed CI systems like [AppVeyor](https://www.appveyor.com/) and [TravisCI](https://travis-ci.org/) and one of the first things I wanted to work out was how easily I could build and ship a [.NET Core](https://www.microsoft.com/net/core#windows) application with one of these tools. This was a major consideration for me because I would have been less interested in building a .NET Core app if the deployment story wasn't great yet and I am not very keen in building my own CI server as I don't think this is the best use of a developer's time. Luckily I was very happy to find out that the deployment experience and integration with TravisCI is extremely easy and intuitive, which is what I will be trying to cover in this blog post today.

Up until now I was more or less tied down to AppVeyor as the only vendor which uses Windows Server VMs for its build nodes and therefore the only viable option of building full .NET framework applications. TravisCI and [other popular CI platforms](https://circleci.com/) use Linux nodes for their build jobs and .NET support was limited to the [Mono framework](http://www.mono-project.com/) at most. However, with .NET Core being the first officially Microsoft supported cross platform framework my options have suddenly increased from one to many. TravisCI already offered a good integration with Mono and now that [.NET Core is part of their default offering](https://docs.travis-ci.com/user/languages/csharp/#Testing-Against-Mono-and-.NET-Core) I was keen to give it a shot.

In this blog post I will be covering what I believe is a typical deployment scenario for a .NET Core application which will be shipped as a Docker image to either the [official Docker Hub](https://hub.docker.com/) or a private registry.

## 1. Creating a .NET Core application

First I need to create a .NET Core application. For the purpose of this blog post I am just going to create a default hello world app and you can skip this step for the most part if you are already familiar with the framework. For everyone else I will quickly skim through the creation of a new .NET Core application.

Let's open a Windows command line prompt and navigate to `C:\temp` and create a new folder called `NetCoreDemo`:

cd C:\temp
mkdir NetCoreDemo
cd NetCoreDemo

Inside that folder I can run `dotnet new --type console` to create a new hello world console application:

For a full reference of the `dotnet new` command check out the [official documentation](https://docs.microsoft.com/en-us/dotnet/articles/core/tools/dotnet-new).

If you don't have the .NET Core CLI available you need to install the [.NET Core SDK for Windows](https://www.microsoft.com/net/core#windows) (or your operating system of choice).

After the command has completed I can run `dotnet restore` to restore all dependencies followed by a `dotnet run` which will build and subsequently start the hello world application:

This is literally all I had to do to get a simple C# console app running and therefore will stop at this point and move on to the next part where I will set up a build and deployment pipeline in TravisCI.

If you want to learn more about building .NET Core applications then I would highly recommend to check out the [official ASP.NET Core tutorials](https://docs.asp.net/en/latest/tutorials/index.html) or read [other great blog posts](https://www.asp.net/community/articles) by developers who have covered this topic extensively.

## 2. Setting up TravisCI for building a .NET Core application

If you are not familiar with TravisCI yet (or a similar platform), then please follow the instructions to [set up TravisCI with your source control repository](https://docs.travis-ci.com/user/for-beginners) and add a `.travis.yml` file to your project repository. This file will contain the entire build configuration for a project.

The first line in the `.travis.yml` file should be the `language` declaration. In our case this will be `language: csharp` which is the correct setting for any .NET language (including VB.NET and F#).

Next we need to set the correct environment type.

The standard TravisCI build environment runs on an [Ubuntu 12.04 LTS Server Edition 64 bit](https://docs.travis-ci.com/user/ci-environment/#Virtualization-environments) distribution. This is no good for us because [.NET Core only supports Ubuntu 14.04 or higher](https://www.microsoft.com/net/core#ubuntu). Fortunately there is a new [Ubuntu 14.04 (aka Trusty) beta environment](https://docs.travis-ci.com/user/trusty-ci-environment/) available. In order to make use of this new beta environment we need to enable `sudo` and set the `dist` setting to `trusty`:

sudo: required
dist: trusty

Next I want to specify what version of Mono and .NET Core I want to have installed when running my builds. At the moment I am only interested in .NET Core so I am going to skip Mono and set the `dotnet` setting to the currently latest SDK:

language: csharp
sudo: required
dist: trusty
mono: none
dotnet: 1.0.0-preview2-003131

The next step is not required nor necessarily recommended, but more of my personal preference to disable the [.NET Core Tools Telemetry](https://docs.microsoft.com/en-us/dotnet/articles/core/tools/telemetry) by setting the `DOTNET_CLI_TELEMETRY_OPTOUT` environment variable to `1` during the `install` step of the TravisCI lifecycle:

install:
  - export DOTNET_CLI_TELEMETRY_OPTOUT=1

After that I have to set access permissions for two script files in the `before_script` step:

before_script:
  - chmod a+x ./build.sh
  - chmod a+x ./deploy.sh

The [chmod command](https://en.wikipedia.org/wiki/Chmod) changes the access permissions of my build and deployment script to allow execution by any user on the system. TravisCI recommends to set `chmod ugo+x` which is effectdively the same as `chmod a+x`, where `a` is a shortcut for `ugo`.

Following `before_script` I am going to set the `script` step which is responsible for the actual build instructions:

script:
  - ./build.sh

At last I am giong to define a `deploy` step as well, which will automatically trigger only after the `script` setp has successfully completed:

deploy:
  - provider: script
    script: ./deploy.sh $TRAVIS_TAG $DOCKER_USERNAME $DOCKER_PASSWORD
    skip_cleanup: true
    on:
      tags: true

Here I am essentially calling a second script called `deploy.sh` and passing in three environment variables which I will explain in a moment. Additionally I defined the trigger to deploy for tags only. You can set up [different deploy conditions](https://docs.travis-ci.com/user/deployment#Conditional-Releases-with-on%3A), but in most cases you either want to deploy on each push to `master` or when a commit has been tagged. I chose the latter, because sometimes I want to publish an alpha or beta version of my application which is likely to be on a different branch than `master` and therefore the tag condition made more sense in my case.

The `TRAVIS_TAG` variable is a [default environment variable](https://docs.travis-ci.com/user/environment-variables/#Default-Environment-Variables) which gets set by TravisCI for every build which has been triggered by a tag push and will contain the string value of the tag. `DOCKER_USERNAME` and `DOCKER_PASSWORD` are two custom [environment variables which I have set through the UI](https://docs.travis-ci.com/user/environment-variables/#Defining-Variables-in-Repository-Settings) to follow TravisCI's recommendation to keep sensitive data secret:

Another option would have been to [encrypt environment variables](https://docs.travis-ci.com/user/environment-variables/#Encrypting-environment-variables) in the `.travis.yml` file to keep those values secret. Both options are valid as far as I know and it is up to you which one you prefer.

#### Tip:

If you have to store access credentials to 3rd party platforms like a private registry or the official Docker Hub inside TravisCI then it is highly recommended to register a dedicated user for TravisCI and add that user as an additional collaborator to your Docker Hub repository, so that you can easily limit or revoke access when required:

After defining the `script` and `deploy` step I am basically done with the `.travis.yml` file.

Note that I purposefully didn't choose to place the individual build and deployment instructions directly into the `script` step, because I wanted to seperate out the actual build instructions from the TravisCI configuration.

This has a few advantages:
- There is a clear distinction between environment setup and the actual build steps which are required to build and deploy the project. The `.travis.yml` file is the definition for the build environment and the `build.sh` and `deploy.sh` script files are the recipe to build and deploy an application.
- The build and deploy scripts are completely independent from the CI platform and I could easily switch the CI provider at any given time.
- The actual build and deployment scripts can be executed from anywhere. Both are a generic bash script which developers can run on their personal machines to build, test and deploy a project.

The last point is probably the most important in my view. Even though managed CI systems are super easy to integrate with, it can be a pain if you are tied down to a particular provider. Imagine you have a new developer joining your team and the first question they ask is how to build your project. It would be a pain to tell them to open up the `.travis.yml` file and follow all the instructions manually if you could just tell them to run `build.sh` and it will work.

If I put everything together then the final `.travis.yml` file will look something like this:

language: csharp
sudo: required
dist: trusty
mono: none
dotnet: 1.0.0-preview2-003131
install:
  - export DOTNET_CLI_TELEMETRY_OPTOUT=1
before_script:
  - chmod a+x ./build.sh
  - chmod a+x ./deploy.sh
script:
  - ./build.sh
deploy:
  - provider: script
    script: ./deploy.sh $TRAVIS_TAG $DOCKER_USERNAME $DOCKER_PASSWORD
    skip_cleanup: true
    on:
      tags: true

One last thing that I wanted to mention is that even though I said we are going to use Docker to deploy the project I didn't have to [specify Docker as an extra service](https://docs.travis-ci.com/user/docker/) anywhere in the `.travis.yml` file. This is because unlike the standard TravisCI environment the Trusty beta environment comes with Docker pre-configured out of the box.

## 3. Building and deploying a .NET Core app from a bash script

Now that the build environment is set up in the `.travis.yml` file and we deferred the entire build and deployment logic to external bash scripts we have to actually create those scripts to complete the puzzle.

#### build.sh

The `build.sh` script is going to be very quick:

#!/bin/bash
set -ev
dotnet restore
dotnet test
dotnet build -c Release

The first line is not necessarily required, but it is good practice to include `#!/bin/bash` at top of the script so the shell knows which interpreter to run. The second line tells the shell to exit immediately if a command fails with a non zero exit code (`set -e`) and to print shell input lines as they are read (`set -v`).

The last three commands are using the normal `dotnet` CLI to [restore](https://docs.microsoft.com/en-us/dotnet/articles/core/tools/dotnet-restore), [build](https://docs.microsoft.com/en-us/dotnet/articles/core/tools/dotnet-build) and [test](https://docs.microsoft.com/en-us/dotnet/articles/core/tools/dotnet-test) the application.

#### deploy.sh

The `deploy.sh` script is going to be fairly easy as well. The first two lines are going to be the same as in `build.sh` and then I am assigning the three parameters that we are passing into the script to named variables:

#!/bin/bash
set -ev

TAG=$1
DOCKER_USERNAME=$2
DOCKER_PASSWORD=$3

Next I am going to use the `dotnet` CLI [publish](https://docs.microsoft.com/en-us/dotnet/articles/core/tools/dotnet-publish) command to package the application and all of its dependencies into the publish folder:

dotnet publish -c Release

Now that everything is packaged up I can use the `docker` CLI to build an image with the supplied tag and the `latest` tag:

docker build -t repository/project:$TAG bin/Release/netcoreapp1.0/publish/.
docker tag repository/project:$TAG repository/project:latest

Make sure that `repository/project` matches your own repository and project name.

Lastly I have to authenticate with the official Docker registry and push both images to the hub:

docker login -u="$DOCKER_USERNAME" -p="$DOCKER_PASSWORD"
docker push repository/project:$TAG
docker push repository/project:latest

And with that I have finished the continuous deployment setup with Docker and TravisCI. The final `deploy.sh` looks like this:

#!/bin/bash
set -ev

TAG=$1
DOCKER_USERNAME=$2
DOCKER_PASSWORD=$3

# Create publish artifact
dotnet publish -c Release src

# Build the Docker images
docker build -t repository/project:$TAG src/bin/Release/netcoreapp1.0/publish/.
docker tag repository/project:$TAG repository/project:latest

# Login to Docker Hub and upload images
docker login -u="$DOCKER_USERNAME" -p="$DOCKER_PASSWORD"
docker push repository/project:$TAG
docker push repository/project:latest

#### Tip:

Some projects follow a naming convention where version tags begin with a lowercase `v` in git, for example `v1.0.0`, but want to remove the `v` from the Docker image tag. In that case you can use this additional snippet to create a variable called `SEMVER` which will be the same as `TAG` without the leading `v`:

# Remove a leading v from the major version number (e.g. if the tag was v1.0.0)
IFS='.' read -r -a tag_array <<< "$TAG"
MAJOR="${tag_array[0]//v}"
MINOR=${tag_array[1]}
BUILD=${tag_array[2]}
SEMVER="$MAJOR.$MINOR.$BUILD"

Place that snippet after the `dotnet publish` command in the `deploy.sh` and use `$SEMVER` instead of `$TAG` when building and publishing the Docker images.

If you want to see a full working example you can check out [one of my open source projects](https://github.com/dustinmoris/NewsHacker) where I use this setup to publish a Docker image of an F# .NET Core application.


text:
<?php

namespace Octava\Bundle\AdministratorBundle\Entity;

use Doctrine\ORM\EntityRepository;
use Octava\Bundle\AdministratorBundle\Entity\Resource as EntityResource;

/**
 * ResourceRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class ResourceRepository extends EntityRepository
{
    protected $accessList = [];

    public function getActions()
    {
        $queryBuilder = $this->createQueryBuilder('r')
            ->select('DISTINCT r.action')
            ->getQuery();
        $rows = $queryBuilder->getResult();
        $ret = [];
        foreach ($rows as $row) {
            $ret[] = $row['action'];
        }
        return $ret;
    }

    public function getList()
    {
        if (!empty($this->accessList)) {
            return $this->accessList;
        }
        /** @var EntityResource[] $a */
        $rows = $this->findAll();
        foreach ($rows as $row) {
            /** @var EntityResource $row */
            $this->accessList[$row->getResource()][$row->getAction()] = $row->getId();
        }
        return $this->accessList;
    }

    public function isVisible($admin, $action, $user)
    {
        /** @var Administrator $user */
        $resource = get_class($admin);
        $ret = $this->findOneBy(['resource' => $resource, 'action' => $action]);
        return !$ret instanceof Resource || !$ret->getHidden();
    }

    public function getModules()
    {
        $queryBuilder = $this->createQueryBuilder('r')
            ->select('r.resource', 'r.label')
            ->distinct()
            ->orderBy('r.sort');
        return $queryBuilder->getQuery()->getArrayResult();
    }
}


text:
'use strict'

/* eslint-env mocha */

const supertest = require('supertest')
const expect = require('chai').expect
const sinon = require('sinon')
const EventEmitter = require('events')
const http = require('http')

describe('cache middleware', function () {
  var mod
  var app
  var request
  var slowModuleStub
  var shouldCacheStub
  var engineStubs
  var PROCESSING_DELAY = 50

  beforeEach(function () {
    app = require('express')()

    engineStubs = {
      set: sinon.stub(),
      get: sinon.stub(),
      del: sinon.stub(),
      keys: sinon.stub(),
      ttl: sinon.stub(),
      flush: sinon.stub(),
      isObjectMode: sinon.stub().returns(true),
      getKeyWithoutNamespace: sinon.stub(),
      getNamespaceFromKey: sinon.stub()
    }

    shouldCacheStub = sinon.stub()

    // A fake module that we simulate slow responses from
    slowModuleStub = sinon.stub()

    // Create an instance
    mod = require('lib/middleware')

    // Add our cache to the express app
    app.use(
      mod(
        {
          shouldCache: shouldCacheStub,
          defaultTtl: 5000,
          namespace: 'expresstest',
          engine: engineStubs
        }
      )
    )

    // Convuluted function to simulate slow loading, chunked responses
    // We wrap with the first setTimeout to mimic a slow loading request/db
    // call. The second setTimeout mimics a stream that is taking a while to
    // write data which is necessary to test the ability of this module to
    // intelligently decide if it should buffer a response in memory to be
    // cached based on the fact it might already be buffering the same response
    function onReq (req, res) {
      setTimeout(function () {
        slowModuleStub(function (code) {
          if (code === 500) {
            res.status(500).end('500 error')
          } else if (code === 304) {
            res.set('etag', 'ETAG')
            res.status(304).end()
          } else {
            res.write('o', 'utf8')

            // Simulate a slow stream
            setTimeout(function () {
              res.end('k')
            }, 50)
          }
        })
      }, PROCESSING_DELAY)
    }

    app.get('/404', (req, res) => {
      res.status(404).end('404 test for a non cached response')
    })
    app.get('/*', onReq)
    app.post('/*', onReq)

    request = supertest(app)
  })

  it('should return data in the standard fashion', function (done) {
    engineStubs.get.yields(null, null)
    engineStubs.set.yields(null)
    slowModuleStub.yields(200)
    shouldCacheStub.returns(true)

    request
      .get('/')
      .expect(200)
      .end(function (err, res) {
        expect(err).to.equal(null)
        // Need a timeout since the "cache.set" might be called a few
        // milliseconds after the response has finished
        setTimeout(() => {
          expect(engineStubs.get.calledOnce).to.equal(true)
          expect(engineStubs.set.calledOnce).to.equal(true)
          expect(shouldCacheStub.calledOnce).to.equal(true)
          expect(slowModuleStub.calledOnce).to.equal(true)

          expect(res.text).to.equal('ok')

          done()
        }, 100)
      })
  })

  it('should use cache for the second call', function (done) {
    slowModuleStub.yields(200)
    shouldCacheStub.returns(true)
    engineStubs.set.yields(null)
    engineStubs.get.yields(null, null)

    request
      .get('/use-cache-for-subsequent-call')
      .expect(200)
      .expect('x-expeditious-cache', 'miss')
      .end(function (err, firstRes) {
        expect(err).to.equal(null)

        setTimeout(function () {
          // On the second call we want the cached data from the first call to
          // be returned to us
          engineStubs.get.yields(
            null,
            engineStubs.set.getCall(0).args[1]
          )

          request
            .get('/use-cache-for-subsequent-call')
            .expect('x-expeditious-cache', 'hit')
            .expect(200)
            .end(function (err, secondRes) {
              expect(err).to.equal(null)
              expect(firstRes.text).to.equal(secondRes.text)

              expect(slowModuleStub.calledOnce).to.equal(true)
              expect(engineStubs.get.callCount).to.equal(2)
              expect(engineStubs.set.calledOnce).to.equal(true)
              expect(shouldCacheStub.callCount).to.equal(2)

              done()
            })
        }, 100)
      })
  })

  it('should not use the cache for any calls', function (done) {
    slowModuleStub.yields(200)
    shouldCacheStub.returns(false)

    function doRequest (callback) {
      request
        .get('/')
        .expect(200)
        .end(callback)
    }

    doRequest(function (err, firstRes) {
      expect(err).to.equal(null)

      setTimeout(function () {
        doRequest(function (err, secondRes) {
          expect(err).to.equal(null)
          expect(firstRes.text).to.equal(secondRes.text)

          expect(slowModuleStub.callCount).to.equal(2)
          expect(shouldCacheStub.callCount).to.equal(2)

          done()
        })
      }, 100)
    })
  })

  it('should use default route if cache.get fails', function (done) {
    slowModuleStub.yields(200)
    shouldCacheStub.returns(true)
    engineStubs.get.yields(new Error('failed to read cache'))

    request
      .get('/')
      .expect('x-expeditious-cache', 'miss')
      .expect(200)
      .end(function (err, res) {
        expect(err).to.equal(null)
        // Need a timeout since the "cache.set" might be called a few
        // milliseconds after the response has finished
        setTimeout(() => {
          expect(err).to.equal(null)
          expect(slowModuleStub.calledOnce).to.equal(true)
          expect(shouldCacheStub.calledOnce).to.equal(true)
          expect(engineStubs.get.calledOnce).to.equal(true)
          expect(engineStubs.set.calledOnce).to.equal(true)
          expect(res.text).to.equal('ok')

          done()
        }, 100)
      })
  })

  it('should process request on cache.set error', function (done) {
    slowModuleStub.yields(200)
    shouldCacheStub.returns(true)
    engineStubs.get.yields(null, null)
    engineStubs.set.yields(new Error('cache.set error'), null)

    request
      .get('/cache-set-error')
      .expect(200)
      .end(function (err, res) {
        setTimeout(() => {
          expect(err).to.equal(null)
          expect(slowModuleStub.calledOnce).to.equal(true)
          expect(shouldCacheStub.calledOnce).to.equal(true)
          expect(engineStubs.get.calledOnce).to.equal(true)
          expect(engineStubs.set.calledOnce).to.equal(true)
          expect(res.text).to.equal('ok')

          done()
        }, 100)
      })
  })

  it('should not call cache.set due to bad status code and no opts.statusCodeExpires being provided', function (done) {
    slowModuleStub.yields(500)
    shouldCacheStub.returns(true)
    engineStubs.get.yields(null, null)

    request
      .get('/')
      .expect(500)
      .end(function (err, res) {
        expect(err).to.equal(null)
        expect(slowModuleStub.calledOnce).to.equal(true)
        expect(shouldCacheStub.calledOnce).to.equal(true)
        expect(engineStubs.get.calledOnce).to.equal(true)

        // This is the key to this test - cache should not be called at all
        expect(engineStubs.set.calledOnce).to.equal(false)

        expect(res.text).to.equal('500 error')

        done()
      })
  })

  it('should only cache.set once on concurrent requests', function (done) {
    slowModuleStub.yields(200)
    shouldCacheStub.returns(true)
    engineStubs.get.yields(null, null)
    engineStubs.set.yields(null, null)

    function doRequest (callback) {
      request
        .get('/cache-set-once-only')
        .expect(200)
        .end(callback)
    }

    require('async').parallel([
      doRequest,
      doRequest
    ], function () {
      // Need a timeout since the "cache.set" might be called a few
      // milliseconds after the response has finished
      setTimeout(() => {
        expect(slowModuleStub.callCount).to.equal(2)
        expect(shouldCacheStub.callCount).to.equal(2)
        expect(engineStubs.get.callCount).to.equal(2)
        expect(engineStubs.set.callCount).to.equal(1)

        done()
      }, 100)
    })
  })

  it('should respond with a 304 due to matching etag in second request', function (done) {
    slowModuleStub.yields(200)
    shouldCacheStub.returns(true)
    engineStubs.get.onCall(0).yields(null, null)
    engineStubs.set.yields(null, null)

    engineStubs.get.onCall(1).yields(null, JSON.stringify({
      headers: 'HTTP/1.1 200 Not Modified\r\nX-Powered-By: Express\r\nx-expeditious-cache: hit\r\nETag: W/"11a-5VdvADh/zRWypLIWVzof8gO9s3U"',
      data: JSON.stringify(Buffer.from('\r\n Hello World'))
    }))

    request
      .get('/expecting-a-304')
      .expect(200)
      .end(function () {
        request
          .get('/expecting-a-304')
          .set('if-none-match', 'W/"11a-5VdvADh/zRWypLIWVzof8gO9s3U"')
          .expect(304)
          .end(done)
      })
  })

  it('should respond with a 304 and generate a 304 cache entry', (done) => {
    slowModuleStub.yields(304)
    shouldCacheStub.returns(true)
    engineStubs.get.yields(null, null)

    request
      .get('/expecting-a-304')
      .expect(304)
      .end((err) => {
        setTimeout(() => {
          expect(err).to.equal(null)
          expect(engineStubs.set.calledOnce).to.equal(true)
          expect(engineStubs.set.getCall(0).args[0]).to.equal(
            'expresstest:GET-/expecting-a-304-ETAG'
          )
          done()
        }, 200)
      })
  })

  it('should not cache since the status code is non cacheable', (done) => {
    shouldCacheStub.returns(true)
    engineStubs.get.yields(null, null)

    request
      .get('/404')
      .expect(404)
      .end(done)
  })

  it('should use the default memory engine', () => {
    mod({
      defaultTtl: 30000,
      namespace: 'expresscache'
    })
  })

  it('should wait for a socket', (done) => {
    // This test mocks out a request flow. We need to simulate a request that
    // doesn't have a response socket bound (not sure how this can happen) but
    // appears to be possible based on issue #28

    engineStubs.get.yields(null, null)

    const mw = mod({
      defaultTtl: 5000,
      namespace: 'expresstest',
      engine: engineStubs
    })

    const req = {
      on: sinon.stub(),
      headers: {},
      originalUrl: '/test/socket-event',
      url: '/socket-event',
      method: 'GET'
    }

    const res = new EventEmitter()
    const responseText = 'all good'

    res.set = sinon.stub()
    res.end = function (data) {
      res.socket.write(data)
    }

    // Trigger the socket bind event so it occurs shortly
    // after the middleware has configured our request.
    // If the event handlers are bound correctly in middleware.js
    // then socket.write will be called
    setTimeout(() => {
      res.socket = {
        write: (data) => {
          expect(engineStubs.get.calledOnce).to.equal(true)
          expect(res.set.calledOnce).to.equal(true)
          expect(data.toString()).to.equal(responseText)
          done()
        }
      }
      res.emit('socket')
    }, 100)

    mw(req, res, () => res.end(responseText))
  })

  it('should not expose header', done => {
    app = require('express')()

    // Create an instance
    mod = require('lib/middleware')

    // Add our cache to the express app
    app.use(
      mod(
        {
          defaultTtl: 5000,
          namespace: 'expresstest',
          cacheStatusHeader: false
        }
      )
    )

    app.get('/*', (req, res) => {
      res.json({})
    })

    supertest(app)
      .get('/test')
      .end((err, res) => {
        expect(err).to.equal(null)
        expect(res.headers['x-expeditious-cache']).to.equal(undefined)
        done()
      })
  })

  it('should expose custom header', done => {
    app = require('express')()

    // Create an instance
    mod = require('lib/middleware')

    // Add our cache to the express app
    app.use(
      mod(
        {
          defaultTtl: 5000,
          namespace: 'expresstest',
          cacheStatusHeader: 'X-Cool-Cached'
        }
      )
    )

    app.get('/*', (req, res) => {
      res.json({})
    })

    supertest(app)
      .get('/test')
      .end((_err, res) => {
        expect(res.headers['x-cool-cached']).to.equal('miss')
        done()
      })
  })

  it('should not cache a request that errors', (done) => {
    const REQ_TIMEOUT = 250
    const ASSERT_TIMEOUT = 1000

    engineStubs.get.yields(null, null)
    shouldCacheStub.returns(true)

    let clientReq = null
    const app = require('express')()
    const port = Math.floor(Math.random() * 60000) + 1024

    app.use(
      mod({
        shouldCache: shouldCacheStub,
        defaultTtl: 5000,
        namespace: 'expresstest',
        engine: engineStubs
      })
    )

    app.post('/', (req, res) => {
      // Set the client to kill connection during the response
      setTimeout(() => clientReq.socket.end(), REQ_TIMEOUT)

      setTimeout(() => res.write('O'), REQ_TIMEOUT / 2)
      setTimeout(() => res.write('K'), REQ_TIMEOUT)
      setTimeout(() => res.end(), REQ_TIMEOUT * 2)
    })

    const server = app.listen(port, (err) => {
      if (err) {
        return done(err)
      }

      // Make a http request, then abort it before the server responds
      clientReq = http.request({
        port: port,
        host: 'localhost',
        path: '/',
        method: 'POST'
      }, (res) => {})
      clientReq.on('error', () => {}) // Required to prevent uncaught expection
      clientReq.write('hello')

      setTimeout(() => {
        try {
          // Should try read from cache to fulfill the request
          expect(engineStubs.get.called).to.equal(true)
          // Should not cache since request was aborted by the client
          expect(engineStubs.set.called).to.equal(false)
          // This is called if a cache miss occurs as is the case here
          expect(shouldCacheStub.called).to.equal(true)

          server.close(done)
        } catch (e) {
          server.close(() => {
            done(e)
          })
        }
      }, ASSERT_TIMEOUT)
    })
  })
})


text:
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

using Microsoft.Kinect;
using Microsoft.VisualStudio.DebuggerVisualizers;

using MyFramework.Kinect.VisualStudio.DebuggerVisualizers.InternalData;
using MyFramework.Kinect.VisualStudio.DebuggerVisualizers.Design;

namespace MyFramework.Kinect.VisualStudio.DebuggerVisualizers
{
    internal class BodyIndexFrameVisualizerObjectSource : VisualizerObjectSource
    {
        public override void GetData(object target, Stream outgoingData)
        {
            var bodyIndexFrame = (target as BodyIndexFrame);

            if (bodyIndexFrame == null)
                return;

            var formatter = new BinaryFormatter();
            var internalBodyIndexFrame = new InternalBodyIndexFrame();

            internalBodyIndexFrame.FrameDescription = new InternalFrameDescription()
            {
                BytesPerPixel = bodyIndexFrame.FrameDescription.BytesPerPixel,
                DiagonalFieldOfView = bodyIndexFrame.FrameDescription.DiagonalFieldOfView,
                Height = bodyIndexFrame.FrameDescription.Height,
                HorizontalFieldOfView = bodyIndexFrame.FrameDescription.HorizontalFieldOfView,
                LengthInPixels = bodyIndexFrame.FrameDescription.LengthInPixels,
                VerticalFieldOfView = bodyIndexFrame.FrameDescription.VerticalFieldOfView,
                Width = bodyIndexFrame.FrameDescription.Width,
            };

            internalBodyIndexFrame.RelativeTime = bodyIndexFrame.RelativeTime;
            internalBodyIndexFrame.Image = bodyIndexFrame.GetPixelArrayFrame();

            formatter.Serialize(outgoingData, internalBodyIndexFrame);

            outgoingData.Flush();
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
    <title>Unit testing - Jasmine</title>
    <link href="assets/css/ionic.css" rel="stylesheet" type="text/css">
    <link href="assets/css/keypoint.css" rel="stylesheet" type="text/css">
    <link href="assets/css/prettify.css" rel="stylesheet" type="text/css">
    <link href="assets/css/slides.css" rel="stylesheet" type="text/css">
    <link rel="apple-touch-icon" sizes="57x57" href="../../assets/favicon.ico/apple-icon-57x57.png">
    <link rel="apple-touch-icon" sizes="60x60" href="../../assets/favicon.ico/apple-icon-60x60.png">
    <link rel="apple-touch-icon" sizes="72x72" href="../../assets/favicon.ico/apple-icon-72x72.png">
    <link rel="apple-touch-icon" sizes="76x76" href="../../assets/favicon.ico/apple-icon-76x76.png">
    <link rel="apple-touch-icon" sizes="114x114" href="../../assets/favicon.ico/apple-icon-114x114.png">
    <link rel="apple-touch-icon" sizes="120x120" href="../../assets/favicon.ico/apple-icon-120x120.png">
    <link rel="apple-touch-icon" sizes="144x144" href="../../assets/favicon.ico/apple-icon-144x144.png">
    <link rel="apple-touch-icon" sizes="152x152" href="../../assets/favicon.ico/apple-icon-152x152.png">
    <link rel="apple-touch-icon" sizes="180x180" href="../../assets/favicon.ico/apple-icon-180x180.png">
    <link rel="icon" type="image/png" sizes="192x192"  href="../../assets/favicon.ico/android-icon-192x192.png">
    <link rel="icon" type="image/png" sizes="32x32" href="../../assets/favicon.ico/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="96x96" href="../../assets/favicon.ico/favicon-96x96.png">
    <link rel="icon" type="image/png" sizes="16x16" href="../../assets/favicon.ico/favicon-16x16.png">
    <link rel="manifest" href="/manifest.json">
    <meta name="msapplication-TileColor" content="#ffffff">
    <meta name="msapplication-TileImage" content="/ms-icon-144x144.png">
    <meta name="theme-color" content="#ffffff">

Introduction to Jasmine

@dothanhlam

About

Lam Do

Ho Chi Minh City, Vietnam

@dothanhlam

http://dothanhlam.wordpress.com

https://github.com/dothanhlam

Concepts

What is Unit Testing

Benefit

Limitation

What is unit ?

The smallest testable part of an application.

Individually and independently for proper operation.

Functions, classes, procedures, interfaces are considered as units

What is testing ?

An investigation conducted to provide stakeholders with information about the quality of the product or service under test.

Unit Testing

Unit testing is a method by which individual units of source code are tested to determine if they are fit for use.

Unit Testing - The mindset

Written and executed by software developers

Isolate each part of the program and test that the individual parts are working correctly

Benefits

Issues are found at early stage

Easy for maintaining and changing the code

Integration testing is easier

Acts as documentation of the system.

Reducing the cost of bug fixes

Simplifying the debugging process

Limitation

Time consuming

Hard to set up realistic, useful tests

Integration errors or system errors can be missed

Need to have a review process for test case failures

Test code is likely to be at least as buggy as the code it is testing

Value and accuracy of unit tests can be diminished if initial conditions are not set correctly

Take an example

FizzBuzz - a common coding exercise in job interviews

FizzBuzz

If a number is divisible by 3 return "Fizz"

If a number is divisible by 5 return "Buzz"

If a number is divisible by 3 and 5 return "FizzBuzz"

Writing Specs

            If a number is divisible by 3 return "Fizz"
            <xmp class="prettyprint small">expect( fizzBuzz( 3 ) ).toEqual( 'Fizz' );</xmp>

            If a number is divisible by 5 return "Buzz"
            <xmp class="prettyprint small">expect( fizzBuzz( 5 ) ).toEqual( 'Buzz' );</xmp>

            If a number is divisible by 5 return "Buzz"
            <xmp class="prettyprint small">expect( fizzBuzz( 15 ) ).toEqual( 'FizzBuzz' );</xmp>

fizzBuzz implementation

        <xmp class="prettyprint small">var fizzBuzz : function( test ){
    if ( test % 3 === 0 ){
        return 'Fizz';
    }
    return '';
}
        </xmp>

Refactor

        <xmp class="prettyprint small">var fizzBuzz : function( test ){
    if ( test % 3 === 0 ){
    return 'Fizz';
    }
    else if ( test % 5 === 0 ){
    return 'Buzz';
    }
    else if ( test % 3 === 0 && test % 5 === 0 ){
    return 'FizzBuzz';
    }
    return '';
}
        </xmp>

Almost done, but it' a trap

The code does not work as expectation! You know why

Writing testable JavaScript code

Not testable code

        <xmp class="prettyprint small">
$(document).ready(function(){
    var div1 = $('div.one'),
    itemCount = getItemCount( 'li.item' );

    div1.on('click',function(){
    // do something
    });

    function getItemCount( selector ){
        return $( selector ).length;
    }
});
        </xmp>

Why ?

        <xmp class="prettyprint small">$(document).ready(function(){ ... });</xmp>

All the code is hidden in the $(document).ready() closure.

        <xmp class="prettyprint small build">div1.on('click',function(){ ...});</xmp>

The event handler is anonymous function passed directly into the on function.

Refactor for more testable

        <xmp class="prettyprint small">
var app = {
    init : function(){
        div1.on( 'click', this.handleDivClick );
        this.itemCount = this.getItemCount( 'li.item' );
    },

    getItemCount : function( selector ){
        return $( selector ).length;
    },

    handleDivClick : function( e ){
        //this in here will still be div1
    }
};
        </xmp>

Why is it more testable?

init set the click handler

init set the item count

getItemCount() returns what we expect

handleDivClick() does what we want

Jasmine

framework for testing JavaScript code

Test Suites

Describe Your Tests

Begin with a call to the global Jasmine function describe

Pass with two parameters: a string and a function

Example of Test Suite

        <xmp class="prettyprint small">

describe('fizzbuzz - A suite is just a function'){

    it('should return fizz when the number is divisible by 3',
        function(){
            expect(fizzBuzz(3)c).toEqual('Fizz'); //matcher
            expect(fizzBuzz(0)).toEqual( '' );
    });
});
            </xmp>

Specs

Spec files are where your tests live

Typically a single spec will be written for each .js file in your app

To be defined by calling the global Jasmine function it

Pass with two parameters: a string and a function

Specs ... more

A spec contains expectations that test the state of the code

A spec with all true expectations is a passing spec

A spec with one or more false expectations is a failing spec

Example

        <xmp class="prettyprint small">
it('should return fizz when the number is divisible by 3',
    function(){
        expect(fizzBuzz(3)c).toEqual('Fizz'); //matcher
        expect(fizzBuzz(0)).toEqual( '' );
    }
);
        </xmp>

Test Setup & Teardown

        <xmp class="prettyprint small">
beforeEach( function (){
    //run before each "it"
});

afterEach( function (){
    //run after each "it"
});
        </xmp>

Expectation

Are built with the function expect which takes a value, called the actual

It is chained with a Matcher function, which takes the expected value

Matcher

Implements a boolean comparison between the actual value and the expected value

Responsible for reporting to Jasmine if the expectation is true or false

Matchers

Matchers - toBe and toEqual

        <xmp class="prettyprint small">toBe( 'expected' ) //exact compare (===)</xmp>
        <xmp class="prettyprint small">toEqual( 'expected' ) //more general compare, can compare objects</xmp>

Matchers - toBeUndefined and toBeDefined

        <xmp class="prettyprint small">toBeUndefined( ) //checks for undefined</xmp>
        <xmp class="prettyprint small">toBeDefined( ) //checks if var is not undefined</xmp>

Matchers - toMatch and toBeNull

        <xmp class="prettyprint small">toMatch( /regex/ ) //matches against regex</xmp>
        <xmp class="prettyprint small">toBeNull( /regex/ ) //checks if a var is null</xmp>

Matchers - toBeTruthy and toBeFalsy

        <xmp class="prettyprint small">toBeTruthy( ) //checks if var is truthy</xmp>
        <xmp class="prettyprint small">toBeFalsy( ) //checks if var is falsy</xmp>

Matchers - toBeLessThan and toBeGreaterThan

        <xmp class="prettyprint small">toBeLessThan( number ) //checks if value is less than number</xmp>
        <xmp class="prettyprint small">toBeGreaterThan( number ) //checks if value is greater than number</xmp>

Matchers - toContain and toThrow

        <xmp class="prettyprint small">toContain( item ) //look for item in array</xmp>
       <xmp class="prettyprint small">expect( function(){ fn(); }).toThrow( e ) //fn() should throw an error</xmp>

Matchers - not

Any matcher can be "reversed" by including the not keyword.

        <xmp class="prettyprint small">expect( 5 ).not.toEqual( 3 );</xmp>

runs/waits

runs/waits purpose

What if you have code like this?

        <xmp class="prettyprint small">
hide : function(){
    $('.hidden').slideDown(5000);
}
        </xmp>

Jasmine provides runs/waits for this

        <xmp class="prettyprint small">
runs(
    function(){
        myObject.hide();
    });

    waits( 5100 );

    runs( function(){
        expect( $('.hidden') ).not.toBeVisible();
    }
);
        </xmp>

runs/waits purposes

When you have runs / waits functions Jasmine runs the first function, waits the duration of the waits function call, then calls the next runs function.

Good for jQuery animations, setTimeouts, setIntervals, or any other asynchronous and timed code.

Spies

What are spies ?

Spies are utilities provided by jasmine to make sure a callback function has been called.

How to use Spies

To use it we tell Jasmine to spyOn something

By default they are similar to mocks in other unit testing frameworks

        <xmp class="prettyprint small">
it('must call the success callback',
    function(){
        //overwrites showOtherDiv with the spy
        spyOn( myObj, 'showOtherDiv' );

        expect( myObj.showOtherDiv ).toHaveBeenCalled();
    }
);
        </xmp>

Spy Matchers

        <xmp class="prettyprint small">
expect( myObj.showOtherDiv ).toHaveBeenCalled();
//validates that the method was called
        </xmp>
        <xmp class="prettyprint small">
expect( myObj.showOtherDiv ).toHaveBeenCalledWith( args );
//validates that the method was called with specific arguments
        </xmp>

Spy Metadata

        <xmp class="prettyprint small">
myObj.showOtherDiv.calls.length //number of times called
        </xmp>
        <xmp class="prettyprint small">
myObj.showOtherDiv.mostRecentCall
//get last call, has same metadata as other calls
        </xmp>

Jasmine integration

Installing commands

        <xmp class="prettyprint small">
$ cd /path/to/project
$ npm install grunt
$ npm install grunt-jasmine-runner
            </xmp>

If you're on a Mac and use Homebrew you can grab PhantomJS:

        <xmp class="prettyprint small">
$ brew install phantomjs
        </xmp>

Configuration to a gruntfile.js

        <xmp class="prettyprint small">
module.exports = function(grunt) {
    grunt.initConfig({
        jasmine : {
        // Your project's source files
        src : 'src/**/*.js',
        // Your Jasmine spec files
        specs : 'specs/**/*spec.js',
        // Your spec helper files
        helpers : 'specs/helpers/*.js'
    }
});

// Register tasks.
grunt.loadNpmTasks('grunt-jasmine-runner');

// Default task.
grunt.registerTask('default', 'jasmine');
};
        </xmp>

Questions

Keypoint


text:
/* Roman Podolski - r.podolski@web.de, Janek Schoenwetter - janek.schoenwetter@yahoo.com
 * Praktikum Softwareentwicklung II, SS2011
 * Geotelematik und Navigation (GO1b), Hochschule München
 *   ____
 *  / ___|___  _ __ _____      ____ _ _ __
 * | |   / _ \| '__/ _ \ \ /\ / / _` | '__|
 * | |__| (_) | | |  __/\ V  V / (_| | |
 *  \____\___/|_|  \___| \_/\_/ \__,_|_|
 *
 * Sun Microsystems Inc. Java 1.6.0_24,
 * Windows 7 Enterprise, Windows 7 Starter
 * CANTIA-(Intel(R) Core(TM)2 Duo CPU 2.26GHz, 2267 MHz)
 * ASUS Eee PC (Intel(R) Atom(TM) CPU N550 @ 1,50 GHz)
 */
package corewar.common.constants;
/**
 * Class initializes constants as system properties or by default values.
 * @author Roman Podolski, Janek Schoenwetter.
 * @version 1.0
 */
public final class Constants {
	/**
	 * Constant value for the core size, Integer-value.
	 */
	public static final int CORE_SIZE = getProb("coresize", 4000);
	/**
	 * Constant for the minimal number of arguments in a RedCode instruction.
	 */
	public static final int MIN_ARGUMENT = 2;
	/**
	 * Constant for the maximal number of arguments in a RedCode instruction.
	 */
	public static final int MAX_ARGUMENT = 3;
	/**
	 * Constant for the maximal (possible) core size.
	 */
	public static final int MAX_SCOPE = 10000;

	/**
	 * Constructor. Initializations blocked.
	 */
	private Constants() {
		assert false : "Utility class without instances";
	}
	/**
	 * Getter for a system property given Integer value.
	 * @param probName
	 *            Name of the property.
	 * @param defValue
	 *            default value if system property isn't used.
	 * @return Integer value, can be the default value or a system property.
	 */
	private static int getProb(final String probName, final int defValue){
		final String name = System.getProperty(probName);
		int result = defValue;
		if (name != null)
			result = Integer.parseInt(name);
		return result;
	}
}


text:
package com.googlecode.javaewah;

import java.util.BitSet;
import java.util.Iterator;
// credit @svanmald
public class BackwardBitSetIterator implements Iterator<Integer> {

    private final BitSet bitSet;
    private int next;

    public BackwardBitSetIterator(BitSet bitSet) {
        this.bitSet = bitSet;
        this.next = bitSet.previousSetBit(bitSet.length());
    }

    @Override
    public boolean hasNext() {
        return next != -1;
    }

    @Override
    public Integer next() {
        int current = next;
        next = bitSet.previousSetBit(current - 1);
        return current;
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>
    {% if page.title %}{{ page.title }}{% else %}{{ site.title }}{% endif %}
  </title>

  <link href="//fonts.googleapis.com/css?family=Raleway:400,300,600" rel="stylesheet" type="text/css">

  <link rel="stylesheet" href="{{ site.baseurl }}/css/normalize.css">
  <link rel="stylesheet" href="{{ site.baseurl }}/css/skeleton.css">
  <link rel="stylesheet" href="{{ site.baseurl }}/css/main.css">

        home

        about

    {{content}}


text:
layout: page
title: Mcdonald Media Show
date: 2016-05-24
author: Joyce Ritter
tags: weekly links, java
status: published
summary: Sed pharetra mi metus, ac.
banner: images/banner/leisure-05.jpg
booking:
  startDate: 06/07/2019
  endDate: 06/10/2019
  ctyhocn: FLLAPHX
  groupCode: MMS
published: true
---
Mauris ultrices nec turpis id commodo. Aenean a felis venenatis, tincidunt dui id, lacinia nisi. Morbi ac nisi nec nibh commodo venenatis. Cras luctus dolor dolor, a imperdiet nisl mattis ac. Nulla a urna justo. Donec at nisl ac arcu rhoncus posuere. Sed sit amet dui gravida, porta urna vitae, suscipit quam. Aenean ut purus semper, elementum mauris ut, dapibus erat. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec vestibulum augue elit, a fringilla lacus feugiat id. Sed luctus, erat in commodo vulputate, lectus eros bibendum turpis, nec euismod turpis velit ut ex. Maecenas et arcu mauris. Fusce finibus sem dolor.
Fusce laoreet a ligula quis dignissim. Donec vitae diam ac eros malesuada venenatis. Quisque elementum, diam a convallis facilisis, dolor urna gravida tellus, vel luctus sem purus sed nisl. Aliquam rhoncus eleifend metus id pharetra. Aliquam sed sapien a elit tincidunt sodales at quis nibh. Curabitur ut dignissim ipsum. Nam rhoncus felis at urna auctor, et malesuada lacus consequat. Curabitur eget nisi mi. Nam at turpis interdum, ultricies nulla at, fringilla sem.

* Etiam venenatis dolor vel bibendum mattis
* Quisque tempus erat sed elit pharetra feugiat
* Suspendisse maximus mauris at ligula laoreet pharetra
* Etiam in lectus eu justo consequat convallis eu hendrerit urna.

Curabitur tempor eget neque a consectetur. Aliquam ipsum turpis, molestie non vestibulum et, accumsan lobortis dolor. Phasellus id felis pretium, ultrices orci quis, dignissim dui. Nunc lectus sapien, pharetra eget aliquet tincidunt, porta ut enim. Praesent sit amet diam in dui hendrerit tempus quis vel tellus. Donec malesuada nisl a tristique sagittis. Etiam facilisis pulvinar malesuada. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Praesent tincidunt mauris mi. Quisque tortor lacus, accumsan nec dolor et, accumsan commodo orci.


text:
/* eslint-disable no-underscore-dangle, no-console */

const path = require('path');
const { execSync } = require('child_process');
const Files = require('./filesystem');

class Npm {
  constructor() {
    this.fs = new Files();
    this.filterOptions = { nameFilter: n => n !== 'node_modules' && !n.startsWith('.') };
  }

  async installForSubdirectories(directory) {
    const subDirectoryList = await this.fs.getDirectories(directory, this.filterOptions);
    const packageDirs = await Promise.all(subDirectoryList
      .map(d => this.fs.exists(path.join(d, 'package.json'))
        .then(exists => ({ dir: d, isNodePackage: exists }))));
    packageDirs
      .filter(d => d.isNodePackage)
      .map(d => d.dir)
      .forEach((dir) => {
        if (dir !== directory) {
          console.log(`Performing "npm install" inside ./${path.relative(directory, dir)}`);
          Npm.install(dir);
        }
      });
  }

  static install(where) {
    execSync(`cd ${where} && npm install`, { env: process.env, stdio: 'inherit' });
  }

  async uninstallForSubdirectories(directory) {
    const subDirectoryList = await this.fs.getDirectories(directory, this.filterOptions);
    const packageDirs = await Promise.all(subDirectoryList
      .map(d => path.join(d, 'package.json'))
      .map(d => this.fs.exists(d).then(exists => ({ dir: d, isNodePackage: exists }))));
    packageDirs
      .filter(d => d.isNodePackage)
      .map(d => d.dir)
      .forEach((dir) => {
        if (dir !== directory) {
          console.log(`Performing "npm uninstall" inside ./${path.relative(directory, dir)}`);
          Npm.uninstall(directory);
        }
      });
  }

  static uninstall(dir) {
    execSync(`cd ${dir}  && rm -rf node_modules`, { env: process.env, stdio: 'inherit' });
  }
}

module.exports = Npm;


text:
// Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.

namespace MartinCostello.ProjectEuler.Puzzles;

/// <summary>
/// A class representing the solution to <c>https://projecteuler.net/problem=22</c>. This class cannot be inherited.
/// </summary>
public sealed class Puzzle022 : Puzzle
{
    /// <inheritdoc />
    public override string Question => "What is the total of all the name scores in the names data?";

    /// <summary>
    /// Returns the score for a name when at a specified position.
    /// </summary>
    /// <param name="name">The name to get the score for.</param>
    /// <param name="position">The original position of the name in the set it belongs to.</param>
    /// <returns>
    /// The score of <paramref name="name"/> when at <paramref name="position"/>.
    /// </returns>
    internal static int Score(string name, int position)
    {
        int score = 0;
        int length = name.Length;

        for (int i = 0; i < length; i++)
        {
            score += name[i] - 'A' + 1;
        }

        return score * position;
    }

    /// <summary>
    /// Reads the sorted list of names from the data associated with the puzzle.
    /// </summary>
    /// <returns>
    /// An <see cref="IList{T}"/> that returns the sorted list of names.
    /// </returns>
    internal IList<string> ReadNames()
    {
        using var stream = ReadResource();
        using var reader = new StreamReader(stream);

        string namesText = reader.ReadToEnd();

        // Remove quotes and any rogue new-line characters
        var trimChars = new[] { '"', '\r', '\n' };

        return namesText
            .Split(',')
            .Select((p) => p.Trim(trimChars))
            .Order(StringComparer.Ordinal)
            .ToList();
    }

    /// <inheritdoc />
    protected override int SolveCore(string[] args)
    {
        IList<string> names = ReadNames();

        int total = 0;

        for (int i = 0; i < names.Count; i++)
        {
            total += Score(names[i], i + 1);
        }

        Answer = total;

        return 0;
    }
}