text:
/* 	$NetBSD: cpuvar.h,v 1.3 2003/10/27 13:43:48 junyoung Exp $ */

/*-
 * Copyright (c) 2000 The NetBSD Foundation, Inc.
 * All rights reserved.
 *
 * This code is derived from software contributed to The NetBSD Foundation
 * by RedBack Networks Inc.
 *
 * Author: Bill Sommerfeld
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *        This product includes software developed by the NetBSD
 *        Foundation, Inc. and its contributors.
 * 4. Neither the name of The NetBSD Foundation nor the names of its
 *    contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * Copyright (c) 1999 Stefan Grefen
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *      This product includes software developed by the NetBSD
 *      Foundation, Inc. and its contributors.
 * 4. Neither the name of The NetBSD Foundation nor the names of its
 *    contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR AND CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

struct cpu_functions {
	int (*start)(struct cpu_info *);
	int (*stop)(struct cpu_info *);
	void (*cleanup)(struct cpu_info *);
};

extern struct cpu_functions mp_cpu_funcs;

#define CPU_ROLE_SP	0
#define CPU_ROLE_BP	1
#define CPU_ROLE_AP	2

struct cpu_attach_args {
	const char *caa_name;
	int cpu_number;
	int cpu_role;
	struct cpu_functions *cpu_func;
};

#define MP_PICMODE	0x00000001      /* System booted in picmode */

#ifdef _KERNEL

#include "opt_multiprocessor.h"

#ifdef MULTIPROCESSOR
extern u_int32_t cpus_running;
#endif

int x86_ipi(int,int,int);
void x86_self_ipi(int);
int x86_ipi_init(int);

void identifycpu(struct cpu_info *);
void cpu_init(struct cpu_info *);
void cpu_init_first(void);

#endif

redpajama_set_name: RedPajamaGithub


text:
//  Copyright (c) 2001-2011 Hartmut Kaiser
//
//  Distributed under the Boost Software License, Version 1.0. (See accompanying
//  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#if !defined(BOOST_SPIRIT_KARMA_EOL_JUL_08_2008_1014AM)
#define BOOST_SPIRIT_KARMA_EOL_JUL_08_2008_1014AM

#if defined(_MSC_VER)
#pragma once
#endif

#include <boost/spirit/home/support/common_terminals.hpp>
#include <boost/spirit/home/support/info.hpp>
#include <boost/spirit/home/support/unused.hpp>
#include <boost/spirit/home/karma/detail/attributes.hpp>
#include <boost/spirit/home/karma/domain.hpp>
#include <boost/spirit/home/karma/meta_compiler.hpp>
#include <boost/spirit/home/karma/delimit_out.hpp>
#include <boost/spirit/home/karma/detail/generate_to.hpp>

namespace boost { namespace spirit
{
    ///////////////////////////////////////////////////////////////////////////
    // Enablers
    ///////////////////////////////////////////////////////////////////////////
    template <>
    struct use_terminal<karma::domain, tag::eol>       // enables eol
      : mpl::true_ {};

}}

///////////////////////////////////////////////////////////////////////////////
namespace boost { namespace spirit { namespace karma
{
#ifndef BOOST_SPIRIT_NO_PREDEFINED_TERMINALS
    using boost::spirit::eol;
#endif
    using boost::spirit::eol_type;

    struct eol_generator : primitive_generator<eol_generator>
    {
        template <typename Context, typename Unused>
        struct attribute
        {
            typedef unused_type type;
        };

        template <
            typename OutputIterator, typename Context, typename Delimiter
          , typename Attribute>
        static bool generate(OutputIterator& sink, Context&, Delimiter const& d
          , Attribute const& /*attr*/)
        {
            return detail::generate_to(sink, '\n') &&
                   karma::delimit_out(sink, d);   // always do post-delimiting
        }

        template <typename Context>
        info what(Context const& /*context*/) const
        {
            return info("eol");
        }
    };

    ///////////////////////////////////////////////////////////////////////////
    // Generator generators: make_xxx function (objects)
    ///////////////////////////////////////////////////////////////////////////
    template <typename Modifiers>
    struct make_primitive<tag::eol, Modifiers>
    {
        typedef eol_generator result_type;
        result_type operator()(unused_type, unused_type) const
        {
            return result_type();
        }
    };

}}}

#endif


text:
package utask.commons.events.ui;

import utask.commons.events.BaseEvent;

//@@author A0139996A
/*
 * This event is used to notify all subscribe that escape key has been press,
 * which results in the dismissal of dialogs and overlay
 * */
public class KeyboardEscapeKeyPressedEvent extends BaseEvent {
    @Override
    public String toString() {
        return this.getClass().getSimpleName();
    }
}


text:
__author__ = 'Sergey Ragatsky'

import string

from nose.tools import nottest, ok_, assert_equal, assert_false, assert_in
from nose.plugins.attrib import attr

from nose_ittr import IttrMultiplier, ittr

class TestMetaClassIttrMultiplayer(object):

    def setup(self):
        self.test_class_one = test_class_one()
        self.test_class_two = test_class_two()

    def teardown(self):
        pass

    @attr(id=1)
    def test_correct_mirroring(self):
        """
        Test metaclass set ittr attributes in mirrors functions
        """
        ok_(hasattr(self.test_class_one.test_method_8_val_a_val_b_val_c,
                    'attr_one'))
        ok_(hasattr(self.test_class_one.test_method_8_val_a_val_b_val_c,
                    'attr_two'))
        ok_(hasattr(self.test_class_one.test_method_8_val_a_val_b_val_c,
                    'attr_three'))

    @attr(id=2)
    def test_ittr_attribute_insertion(self):
        """
        Tests metaclass adds ittr attribute to test
        """
        assert_in('attr_one',
                  self.test_class_one.test_method_8_val_a_val_b_val_c.ittr)
        assert_in('attr_two',
                  self.test_class_one.test_method_8_val_a_val_b_val_c.ittr)
        assert_in('attr_three',
                  self.test_class_one.test_method_8_val_a_val_b_val_c.ittr)

    @attr(id=3)
    def test_self_modification_by_test_method(self):
        """
        Verifies that when mirror method ran, it modifies self
        """
        self.test_class_one.test_method_9_val_b_val_c()
        ok_(hasattr(self.test_class_one, 'attr_one'))
        ok_(hasattr(self.test_class_one, 'attr_two'))

    @attr(id=4)
    def test_mirror_methods_suffix_name_creation(self):
        """
        Check that the suffix created correctly
        """
        ok_(hasattr(self.test_class_one, 'test_method_1'))
        ok_(hasattr(self.test_class_one, 'test_method_2'))
        ok_(hasattr(self.test_class_one, 'test_method_3'))
        ok_(hasattr(self.test_class_one, 'test_method_4'))
        ok_(hasattr(self.test_class_one, 'test_method_5'))
        ok_(hasattr(self.test_class_one, 'test_method_6_val_a'))
        ok_(hasattr(self.test_class_one, 'test_method_7_val_a_val_c'))
        ok_(hasattr(self.test_class_one, 'test_method_7_val_b_val_c'))
        ok_(hasattr(self.test_class_one, 'test_method_7_val_b_val_c'))
        ok_(hasattr(self.test_class_one, 'test_method_8_val_a_val_b_val_c'))
        ok_(hasattr(self.test_class_one, 'test_method_8_val_a_val_b_val_d'))
        ok_(hasattr(self.test_class_one, 'test_method_9_val_a_val_c'))
        ok_(hasattr(self.test_class_one, 'test_method_9_val_b_val_c'))
        ok_(hasattr(self.test_class_one, 'test_method_9_val_b_val_c'))
        ok_(hasattr(self.test_class_one, 'test_method_10_val_a_val_d_val_b'))
        ok_(hasattr(self.test_class_one, 'test_method_11_val_a__'))

    @attr(id=5)
    def test_ittr_product_method_number(self):
        """
        Verify correct number of methods duplicated based on ittr
        """
        res = filter(lambda x: 'test' in x or None, dir(self.test_class_one))
        assert_equal(len(res), 21)

    @attr(id=6)
    def test_original_method_has_notest_hook(self):
        """
        Original method, that been mirrored receive no test hook
        """
        assert_false(self.test_class_one.test_method_1.__test__)
        assert_false(self.test_class_one.test_method_2.__test__)
        assert_false(self.test_class_one.test_method_3.__test__)
        assert_false(self.test_class_one.test_method_6.__test__)
        assert_false(self.test_class_one.test_method_7.__test__)
        assert_false(self.test_class_one.test_method_8.__test__)
        assert_false(self.test_class_one.test_method_9.__test__)
        assert_false(self.test_class_one.test_method_10.__test__)
        assert_false(self.test_class_one.test_method_11.__test__)

    @attr(id=7)
    def test_class_decorator(self):
        ok_(hasattr(self.test_class_two, 'test_method_1_linux'))
        ok_(hasattr(self.test_class_two, 'test_method_1_mac'))
        ok_(hasattr(self.test_class_two, 'test_method_2_val_a_linux'))
        ok_(hasattr(self.test_class_two, 'test_method_2_val_a_mac'))
        ok_(hasattr(self.test_class_two, 'test_method_2_val_b_linux'))
        ok_(hasattr(self.test_class_two, 'test_method_2_val_b_mac'))

@nottest
class test_class_two(object):

    __metaclass__ = IttrMultiplier
    __ittr__ = {'os': ['linux', 'mac']}

    def test_method_1(self):
        """Test method docstring"""
        pass

    @ittr(ittr_val=['val_a', 'val_b'])
    def test_method_2(self):
        """Test method docstring"""
        pass

@nottest
class test_class_one(object):

    __metaclass__ = IttrMultiplier

    @ittr(attr_one=[])
    def test_method_1(self):
        """Test method docstring"""
        pass

    @ittr(attr_one=[], attr_two=[])
    def test_method_2(self):
        """Test method docstring"""
        pass

    @ittr(attr_one={})
    def test_method_3(self):
        """Test method docstring"""
        pass

    @ittr()
    def test_method_4(self):
        """Test method docstring"""
        pass

    def test_method_5(self):
        """Test method docstring"""
        pass

    @ittr(attr_one=['val_a'])
    def test_method_6(self):
        pass

    @ittr(attr_one=['val_a', 'val_b'], attr_two=['val_c'])
    @attr(id=1234, section='test')
    def test_method_7(self):
        pass

    @ittr(attr_one=['val_a'], attr_two=['val_b'])
    @ittr(attr_three=['val_c', 'val_d'])
    def test_method_8(self):
        """Test method docstring"""
        pass

    @ittr(attr_one=['val_a', 'val_b'], attr_two=['val_c'])
    @ittr(attr_one=['val_e', 'val_d'])
    def test_method_9(self):
        """Test method docstring"""
        pass

    @ittr(attr_one=['val_a'], attr_two=['val_b'])
    @ittr(attr_one=['val_c'], attr_four=['val_d'])
    def test_method_10(self):
        """Test method docstring"""
        pass

    @ittr(attr_one=['val_a'+string.punctuation])
    def test_method_11(self):
        """Test method docstring"""
        pass


text:
require 'active_support/core_ext/class/attribute'

module ActionController
  module Serialization
    extend ActiveSupport::Concern

    include ActionController::Renderers

    def _render_option_json(resource, options)
      serializer = ActiveModel::Serializer.serializer_for(resource)

      if serializer
        # omg hax
        object = serializer.new(resource)
        adapter = ActiveModel::Serializer.adapter.new(object)

        super(adapter, options)
      else
        super
      end
    end
  end
end


text:
<?php

namespace Devtrw\Bundle\GoogleMapsBundle\Service;

use Devtrw\Bundle\GoogleMapsBundle\Entity\Directions\Request;
use Devtrw\Bundle\GoogleMapsBundle\Entity\Directions\Response;

/**
 * This service is exposed to provide a simple interface with the Google Maps API
 *
 * @author Steven Nance <steven@devtrw.com>
 */
class Directions extends MapsService
{
    /**
     * Make a request against the Google Maps API for directions
     *
     * @param Request $request
     *
     * @return Response
     */
    public function getDirections(Request $request)
    {
        $response = $this->client->getDirections($request);

        return $this->assembleDirectionsResponse($response);
    }

    /**
     * @param array $response
     *
     * @return Response
     */
    private function assembleDirectionsResponse($response)
    {
        $directionsResponse = new Response();

        return $directionsResponse::assembleFromArray($response);
    }
}


text:
layout: default
title: "Baroness Kingsmill"
house: lords

---

        {% include members/baroness-kingsmill.html %}

What is Baroness Kingsmill interested in?

Baroness Kingsmill hasn't said she is interested in anything! Why not write to them and ask?

Party

Baroness Kingsmill is part of the Labour party.

What is a party?


text:
package de.martinreinhardt.jee.controller;

import java.util.logging.Logger;

import javax.annotation.security.PermitAll;
import javax.ejb.Stateless;
import javax.enterprise.event.Event;
import javax.inject.Inject;
import javax.persistence.EntityManager;

import de.martinreinhardt.jee.domain.Member;

/**
 * Controller for the member registration process.
 *
 * By using the stateless annotation the transaction is automatically ended
 * (implicit)
 *
 * @author mreinhardt
 *
 */
@Stateless
@PermitAll
public class MemberRegistration {

	@Inject
	private Logger        log;

	@Inject
	private EntityManager em;

	@Inject
	private Event<Member> memberEventSrc;

	public void register(Member member) throws Exception {
		log.info("Registering " + member.getName());
		em.persist(member);
		memberEventSrc.fire(member);
	}
}


text:
package orc.lib.orchard.forms;

import java.util.LinkedList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class MultipartFormData implements FormData {
    private final List<FileItem> items;

    public MultipartFormData(final List<FileItem> items) {
        this.items = items;
    }

    public MultipartFormData(final HttpServletRequest request) throws FileUploadException {
        final FileItemFactory factory = new DiskFileItemFactory();
        final ServletFileUpload upload = new ServletFileUpload(factory);
        this.items = upload.parseRequest(request);
    }

    @Override
    public FileItem getItem(final String key) {
        for (final FileItem item : items) {
            if (item.getFieldName().equals(key)) {
                return item;
            }
        }
        return null;
    }

    @Override
    public FileItem[] getItems(final String key) {
        final LinkedList<FileItem> out = new LinkedList<FileItem>();
        for (final FileItem item : items) {
            if (item.getFieldName().equals(key)) {
                out.add(item);
            }
        }
        return out.toArray(new FileItem[0]);
    }

    @Override
    public List<FileItem> getItems() {
        return items;
    }

    @Override
    public String getParameter(final String key) {
        final FileItem item = getItem(key);
        if (item == null) {
            return null;
        }
        return item.getString();
    }

    @Override
    public String[] getParameterValues(final String key) {
        final FileItem[] items = getItems(key);
        final String[] out = new String[items.length];
        for (int i = 0; i < items.length; ++i) {
            out[i] = items[i].toString();
        }
        return out;
    }
}


text:
From **Flask Web Development**
Make a page that only sets a cookie
> note to self:
> figure out the dynamic relationships thing in Example 5.4
> make sure that you reread `Integration with the Python Shell`
Some of the auto importing seems like it would be super useful for testing

##starting server that is available externally

* install flask-script
    * `pip install flask-script`
* run the script like `$ python script.py runserver --host 0.0.0.0`
* example of template doing conditionals
```HTML+Django
    {% if name %}
        < h1> {{ name }} just won!</h1>
    {% else %}
        <p>You won, I guess</p>
    {% endif %}
```
* example of looping through a conditional in a template
```HTML+Django
    <ul>
        {% for comment in comments %}
            <li>{{ comment }}</li>
        {% endfor %}
    </ul>
```
* also works with macros
    * macros are stored in standalone file that is imported
    as needed.
    * macro creation
```HTML+Django
        {% macro render_comment(comment) %}
            <li>{{ comment }}</li>
        {% endmacro %}
```
    * macro use
```HTML+Django
        <ul>
            {% for comment in comments %}
                {{ render_comment(comment) }}
            {% endfor %}
        </ul>
```
* some things about sqlalchemy
    * correct url format -
    mysql://username:password@hostname/database
    * holy crap, it is some next level magic stuff.
    * from icp db.create_all() builds out the structures
    that you specify in application
```python
        >>> from t1 import db
        >>> db.create_all()
        >>> from t1 import Role, User
        >>> admin_role = Role(name='admin')
        >>> user_role = Role(name='user')
        >>> user_a = User(username="a", role=admin_role)
        >>> user_b = User(username="b", role=user_role)
        >>> db.session.add_all([admin_role, user_role, user_a, user_b])
        >>> db.session.commit()
        >>> print(admin_role.id)
        >>> admin_role.name = "Something Different"
        >>> db.session.add(admin_role)
        >>> db.session.commit()
```
    * `admin_role = Role(name='admin')` creating a row in
    the table, basically
    * `user_a = User(username="a", role=admin_role)`
    assigning foreign keys
    * `db.session.add_all([admin_role, user_role, user_a, user_b])`
    preparing these rows from the objects
    * `db.session.commit()` actually making the queued
    changes
    * `admin_role.name = "Something Different"` updating an
    object that is created in the database
    * `db.session.add(admin_role)`queuing the change to be
    written
    * `db.session.commit()` writing the change
    * Also
        * `db.session.delete(object)` -> `db.session.commit()`
        to delete an item from the database
        * `Role.query.all()` to get all items from the Role
        table (note that Role is an object I imported from
        my main script)
        * `User.query.filter_by(role=user_role).all()` brings
        back the users who are admin
    * when you have to build the data from scratch
        * `user_role = Role.query.filter_by(name='User`).first()

    * NOTE: do not try and build and run these concurrently.
    When anything calls commit() it commits whatever is there
    right then.

============================================================

###Email

* `pip install flask-mail`
* Example, sending mail though gmail, with credentials in
the environment

```python
app.config['MAIL_SERVER'] = 'smtp.googlemail.com'
app.config['MAIL_PORT'] = 587
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USERNAME'] = os.environ.get('MAIL_USERNAME')
app.config['MAIL_PASSWORD'] = os.environ.get('MAIL_PASSWORD')
app.config['FLASKY_MAIL_SUBJECT_PREFIX'] = '[Flasky]'
app.config['FLASKY_MAIL_SENDER'] = 'Flasky Admin <flasky@example.com>'
app.config['FLASKY_ADMIN'] = os.environ.get('FLASKY_ADMIN')
```

* example of setting up asynch mail, very nice!


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using DataExplorer.Application.Core.Events;
using DataExplorer.Application.Core.Queries;
using DataExplorer.Application.Importers.CsvFiles.Events;
using DataExplorer.Application.Importers.CsvFiles.Queries;
using DataExplorer.Presentation.Core;

namespace DataExplorer.Presentation.Importers.CsvFile.Body
{
    public class CsvFileImportBodyViewModel :
        BaseViewModel,
        ICsvFileImportBodyViewModel,
        IEventHandler<CsvFileSourceChangedEvent>
    {
        private readonly IQueryBus _queryBus;

        public CsvFileImportBodyViewModel(IQueryBus queryBus)
        {
            _queryBus = queryBus;
        }

        public List<SourceMapViewModel> MapViewModels
        {
            get { return GetMapViewModels(); }
        }

        private List<SourceMapViewModel> GetMapViewModels()
        {
            var maps = _queryBus.Execute(new GetCsvFileSourceMapsQuery());

            var mapViewModels = maps.Select(p => new SourceMapViewModel(p))
                .ToList();

            return mapViewModels;
        }

        public void Handle(CsvFileSourceChangedEvent args)
        {
            OnPropertyChanged(() => MapViewModels);
        }
    }
}


text:
<?php

namespace Application\Migrations;

use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;

/**
 * Auto-generated Migration: Please modify to your needs!
 */
class Version20150212203655 extends AbstractMigration
{
    public function up(Schema $schema)
    {
        // this up() migration is auto-generated, please modify it to your needs
        $this->addSql("ALTER TABLE  `thread_post` ADD  `subposts` INT UNSIGNED NOT NULL DEFAULT  '0' COMMENT  '子话题数量' AFTER  `parentId`;");
    }

    public function down(Schema $schema)
    {
        // this down() migration is auto-generated, please modify it to your needs

    }
}


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title>Module: UnitTestHelpers</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <meta http-equiv="Content-Script-Type" content="text/javascript" />
  <link rel="stylesheet" href=".././rdoc-style.css" type="text/css" media="screen" />

          Module
          UnitTestHelpers

            In:

                lib/unit_test_helpers.rb

Unless you are writing your own specialized test you probably are looking
for the helpers in UnitTestHelpers::ClassMethods.

This module provides basic unit level test helpers to test the various
aspects of a model. It provides the basic building blocks for the test
helpers in UnitTestHelpers::ClassMethods.
These instance level methods can also be used to build new tests when the
tests fall outside of the domain covered by the main test helpers. All of
the helpers rely on a definition of a DefaultValue at the test class level.
This is to be a hash of attribute value pairs that match the model.

Example:

  class SomeModelTest < ActiveSupport::TestCase

    DefaultValues =  {
      :name => "Some Name",
      :location => "123 Main",
      :color => "Blue"
    }

  end

Methods

      check_create
      check_format_of
      check_inclusion_of
      check_longer_than
      check_numericality_of
      check_presence_of
      check_shorter_than
      check_uniqueness_of
      check_update
      default_values
      error_messages_from
      instance_with
      instance_without
      new_instance
      with_instance

Classes and Modules

      Module UnitTestHelpers::ClassMethods

Public Instance methods

          check_create()

Asserts that an instance of the model can be created and saved using the
default values.

Example:

  DefaultValues =  {
    :name => "Some Name",
    :location => "123 Main",
    :color => "Blue"
  }

  def test_create
    check_create
  end

[Source]

     # File lib/unit_test_helpers.rb, line 510
510:   def check_create
511:     with_instance do |instance|
512:       assert_not_nil instance, "Failed to create #{self.class.target.name}."
513:       assert instance.errors.empty?, "Failed to create valid #{self.class.target.name} with #{instance.inspect}.\n" + error_messages_from(instance).join("\n")
514:     end
515:   end

          check_format_of(item, value=nil, valid=true)

Asserts that an attribute is required to fit a certain format by the model.
Best paired with validates_format_of.

Example:

  DefaultValues =  {
    :name => "Some Name",
    :location => "123 Main",
    :color => "Blue"
  }

  def test_format_of_location
    check_format_of :location
    check_format_of :location, "456 Elm St."
    check_format_of :location, "Street 101 WTF", false
  end

[Source]

     # File lib/unit_test_helpers.rb, line 599
599:   def check_format_of(item, value=nil, valid=true)
600:     value = default_values[item].to_s if value.nil?
601:     instance_with(item => value) do |instance|
602:       errors = instance.errors.invalid?(item)
603:       if valid
604:         assert !errors, "#{self.class.target.name} should have allowed the format of #{value} for #{item}."
605:       else
606:         assert errors, "#{self.class.target.name} should not have allowed the format of #{value} for #{item}."
607:       end
608:     end
609:   end

          check_inclusion_of(item, value=nil, valid=true)

Asserts that an attribute is required to fit within a certain list of
acceptable values by the model. Best paired with validates_inclusion_of.

Example:

  DefaultValues =  {
    :name => "Some Name",
    :location => "123 Main",
    :color => "Blue"
  }

  def test_inclusion_of_color
    check_inclusion_of :color
    check_inclusion_of :color, "Red"
    check_inclusion_of :color, "Blu", false
  end

[Source]

     # File lib/unit_test_helpers.rb, line 626
626:   def check_inclusion_of(item, value=nil, valid=true)
627:     value = default_values[item].to_s if value.nil?
628:     instance_with(item => value) do |instance|
629:       errors = instance.errors.invalid?(item)
630:       if valid
631:         assert !errors, "#{self.class.target.name} should have allowed the inclusion of #{value} for #{item}."
632:       else
633:         assert errors, "#{self.class.target.name} should not have allowed the inclusion of #{value} for #{item}."
634:       end
635:     end
636:   end

          check_longer_than(item, length=nil, value=nil)

Asserts that an attribute is required to have a maximum length by the
model. Best paired with validates_length_of.

If a length is not given, the maximum length will be inferred from the
value used.

If a value is supplied then the inferred maximum length will be the length
of the supplied value minus one.

If a value is not supplied then the inferred maximum length will be exactly
the length of the default value for the attribute.

If a length is given without a value, the default attribute value will be
repeated until it reaches the length of one more than the supplied length
and then tested.

Example:

  DefaultValues =  {
    :name => "Some Name",
    :location => "123 Main",
    :color => "Blue"
  }

  def test_maximum_size_of_name
    # The following are equivalent if the model requires a maximum name length of 9.
    check_longer_than :name
    check_longer_than :name, 9
    check_longer_than :name, nil, "ABCDEFGHI"
    check_longer_than :name, 9, "Some really long name"
  end

  def test_maximum_size_of_location
    # The following are equivalent if the model requires a maximum location length of 10.
    check_longer_than :location, 10
    check_longer_than :location, nil, "ABCDEFGHIJ"
    check_longer_than :location, 10, "12345678 ExtraLong Street"
  end

[Source]

     # File lib/unit_test_helpers.rb, line 705
705:   def check_longer_than(item, length=nil, value=nil)
706:     length = (value.nil? ? default_values[item].to_s.length : (value.to_s.length - 1)) if length.nil?
707:     value = (default_values[item].to_s * length.to_i)[0..length.to_i] if value.nil?
708:     instance_with(item => value) { |instance| assert instance.errors.invalid?(item), "#{self.class.target.name} should not have allowed #{item} longer than #{length}." }
709:   end

          check_numericality_of(item, value=nil)

Asserts that an attribute is required to be numeric by the model. Best
paired with validates_numericality_of. If no value is given, a non numeric
value will be created by treating the default value as a string, removing
the last digit, and adding the letter ‘z’ to the beginning of
the string.

Example:

  DefaultValues =  {
    :name => "Some Name",
    :location => "123 Main",
    :color => "Blue",
    :quantity => 7
  }

  def test_numericality_of_quantity
    check_numericality_of :quantity
    check_numericality_of :quantity, 'cabbadabbajabba'
  end

[Source]

     # File lib/unit_test_helpers.rb, line 579
579:   def check_numericality_of(item, value=nil)
580:     value = ("z" + default_values[item].to_s)[0..-2] if value.nil?
581:     instance_with(item => value) { |instance| assert instance.errors.invalid?(item), "#{self.class.target.name} should not have allowed a nonnumeric #{item}." }
582:   end

          check_presence_of(item)

Asserts that an attribute is required to be present by the model. Best
paired with validates_presence_of.

Example:

  DefaultValues =  {
    :name => "Some Name",
    :location => "123 Main",
    :color => "Blue"
  }

  def test_presence_of_name
    check_presence_of :name
  end

[Source]

     # File lib/unit_test_helpers.rb, line 558
558:   def check_presence_of(item)
559:     instance_without(item) { |instance| assert instance.errors.invalid?(item), "#{self.class.target.name} should not have allowed an empty #{item}." }
560:   end

          check_shorter_than(item, length=nil, value=nil)

Asserts that an attribute is required to have a minimum length by the
model. Best paired with validates_length_of.

If a length is not given, the minimum length will be inferred from the
value used.

If a value is supplied then the inferred minimum length will be the length
of the supplied value plus one.

If a value is not supplied then the inferred minimum length will be exactly
the length of the default value for the attribute.

If a length is given without a value, the default attribute value will be
trimmed down to a length of one less than the supplied length and then
tested.

Example:

  DefaultValues =  {
    :name => "Some Name",
    :location => "123 Main",
    :color => "Blue"
  }

  def test_minimum_size_of_name
    # The following are equivalent if the model requires a minimum name length of 9.
    check_shorter_than :name
    check_shorter_than :name, 9
    check_shorter_than :name, nil, "Some Nam"
    check_shorter_than :name, 9, "ABC"
  end

  def test_minimum_size_of_location
    # The following are equivalent if the model requires a minimum location length of 4.
    check_shorter_than :location, 4
    check_shorter_than :location, nil, "123"
    check_shorter_than :location, 4, "XYZ"
  end

[Source]

     # File lib/unit_test_helpers.rb, line 669
669:   def check_shorter_than(item, length=nil, value=nil)
670:     length = (value.nil? ? default_values[item].to_s.length : (value.to_s.length + 1)) if length.nil?
671:     value = (" " + default_values[item].to_s)[1..length.to_i-1] if value.nil?
672:     instance_with(item => value) { |instance| assert instance.errors.invalid?(item), "#{self.class.target.name} should not have allowed #{item} shorter than #{length}." }
673:   end

          check_uniqueness_of(item)

Asserts that an attribute is required to be unique by the model. Best
paired with validates_uniqueness_of.

Example:

  DefaultValues =  {
    :name => "Some Name",
    :location => "123 Main",
    :color => "Blue"
  }

  def test_uniqueness_of_name
    check_uniqueness_of :name
  end

[Source]

     # File lib/unit_test_helpers.rb, line 724
724:   def check_uniqueness_of(item)
725:     with_instance { |instance| assert self.class.target.create(default_values).errors.invalid?(item), "#{self.class.target.name} should not have allowed a duplicate #{item}." }
726:   end

          check_update(changed_values_hash)

Asserts that an instance of the model can have the specified attributes
updated and saved. Then asserts that each updated value can be retrieved
back from the database.

Example:

  DefaultValues =  {
    :name => "Some Name",
    :location => "123 Main",
    :color => "Blue"
  }

  def test_update
    check_update :name => "Sum Name", :color => "Bloo"
  end

[Source]

     # File lib/unit_test_helpers.rb, line 531
531:   def check_update(changed_values_hash)
532:     values = resolve_delayed_fixtures(changed_values_hash)
533:     id = values.delete(:id) { send(self.class.target.name.tableize.to_sym, :one).id }
534:     instance = self.class.target.find(id)
535:     instance.update_attributes(values)
536:     instance.save
537:     assert instance.errors.empty?, "Failed to update to a valid #{self.class.target.name} with #{values.inspect}.\n" + error_messages_from(instance).join("\n")
538:     instance.reload
539:     values.each do |attribute, new_value|
540:       current_value = instance.send(attribute)
541:       assert_equal current_value, new_value, "Failed to update #{attribute} to #{new_value} for #{self.class.target.name}.\nIt is currently #{current_value}."
542:     end
543:   end

          default_values()

Returns the default values hash after resolving any delayed fixtures.

Example:

  DefaultValues =  {
    :name => "Some Name",
    :location => "123 Main",
    :color => "Blue"
    :user_name => users(:test_user).name
  }

  def test_delayed_fixture_resolution
    values = default_values
    assert_equal "Some Name", values.name
    assert_equal "123 Main", values.location
    assert_equal "Blue", values.color
    assert_equal User.find_by_name("test_user").name, values.user_name
  end

[Source]

     # File lib/unit_test_helpers.rb, line 746
746:   def default_values
747:     resolve_delayed_fixtures self.class.default_values
748:   end

          error_messages_from(instance, indent=0)

Recusively traverses an instance and returns a human readable set of errors
that caused the instance not to validate. The errors are nested so that if
a child resource is causing the problem, it is easily identifiable.

[Source]

     # File lib/unit_test_helpers.rb, line 752
752:   def error_messages_from(instance, indent=0)
753:     if instance.is_a?(ActiveRecord::Base)
754:       errors = Hash[*instance.errors.to_a.flatten]
755:       errors.map do |attr, msg|
756:         attr_human = (attr == "base") ? "" : "#{attr.humanize} "
757:         error_messages_from(instance.send(attr.to_sym), indent + 1).unshift("    " * indent + attr_human + msg)
758:       end
759:     else
760:       []
761:     end
762:   end

          instance_with(hash)

Creates a new instance of the current model from the DefaultValues hash
merged with the hash of alternate values.

Example:

  DefaultValues =  {
    :name => "Some Name",
    :location => "123 Main",
    :color => "Blue"
  }

  def test_with_badly_spelled_name_and_color
    instance = instance_with(:name => "Sum Name", :color => "Bloo")
    assert_equal "Sum Name", instance.name
    assert_equal "123 Main", instance.location
    assert_equal "Bloo", instance.color
  end

[Source]

     # File lib/unit_test_helpers.rb, line 488
488:   def instance_with(hash)
489:     values = default_values.merge(hash)
490:     if block_given?
491:       with_instance values, &Proc.new
492:     else
493:       new_instance values
494:     end
495:   end

          instance_without(*items)

Creates a new instance of the current model from the DefaultValues hash but
without the attributes specified.

Example:

  DefaultValues =  {
    :name => "Some Name",
    :location => "123 Main",
    :color => "Blue"
  }

  def test_with_only_name
    instance = instance_without(:location, :color)
    assert_not_nil instance.name
    assert_nil instance.location
    assert_nil instance.color
  end

[Source]

     # File lib/unit_test_helpers.rb, line 462
462:   def instance_without(*items)
463:     items = [items].flatten.map { |key| key.to_s.to_sym }
464:     values = default_values.reject{ |key, value| items.include?(key)}
465:     if block_given?
466:       with_instance values, &Proc.new
467:     else
468:       new_instance values
469:     end
470:   end

          new_instance(values=nil)

Creates a new instance of the current model being tested, utilizing a hash
of attribute names and values.

If no values are passed the DefaultValues hash is used.

Example:

  DefaultValues =  {
    :name => "Some Name",
    :location => "123 Main",
    :color => "Blue"
  }

  def test_with_default_values
    instance = new_instance
    assert_equal "Some Name", instance.name
    assert_equal "123 Main", instance.location
    assert_equal "Blue", instance.color
  end

  def test_with_misspelled_values
    instance = new_instance(:name => "Sum Name", :location => "123 Mane", :color => "Bloo")
    assert_equal "Sum Name", instance.name
    assert_equal "123 Mane", instance.location
    assert_equal "Bloo", instance.color
  end

  def test_with_only_name
    instance = new_instance(:name => "All Alone")
    assert_equal "All Alone", instance.name
    assert_nil instance.location
    assert_nil instance.color
  end

[Source]

     # File lib/unit_test_helpers.rb, line 388
388:   def new_instance(values=nil)
389:     values = values.nil? ? default_values : resolve_delayed_fixtures(values)
390:     self.class.target.create(values)
391:   end

          with_instance(values=nil) {|instance| ...}

Creates a new instance of the current model being tested, utilizing the
values hash being passed. This instance is then passed to your block and
destroyed when the block returns.

If no values are passed the DefaultValues hash is used.

The result of your block is returned.

Example: (And a very contrived one at that. This example tests way to many
unrelated things in one method)

  DefaultValues =  {
    :name => "Some Name",
    :location => "123 Main",
    :color => "Blue"
  }

  def test_two_separate_instances_and_name_collision

    reverse_color1 = with_instance do |default_instance|
      assert_equal "Some Name", default_instance.name
      assert_equal "123 Main", default_instance.location
      assert_equal "Blue", default_instance.color
      assert default_instance.valid?
      default_instance.color.reverse
    end

    reverse_color2 = with_instance(default_values.merge(:color => "Red")) do |duplicate_name_instance|
      assert_equal "Some Name", duplicate_name_instance.name
      assert_equal "123 Main", duplicate_name_instance.location
      assert_equal "Red", duplicate_name_instance.color
      assert duplicate_name_instance.valid?
      duplicate_name_instance.color.reverse
    end

    assert_equal "eulB", reverse_color1
    assert_equal "deR", reverse_color2

    with_instance do |default_instance|
      assert default_instance.valid?
      with_instance(default_values.merge(:color => "Red")) do |duplicate_name_instance|
        assert !duplicate_name_instance.valid?
      end
    end

  end

[Source]

     # File lib/unit_test_helpers.rb, line 437
437:   def with_instance(values=nil, &block)
438:     instance = new_instance(values)
439:     begin
440:       yield(instance)
441:     ensure
442:       instance.destroy unless instance.nil?
443:     end
444:   end

[Validate]


text:
<?php

namespace phpManufaktur\Event\Control\Backend;

use phpManufaktur\Event\Control\Backend\Backend;
use Silex\Application;
use phpManufaktur\Event\Data\Event\Propose as ProposeData;

class Propose extends Backend {

    /**
     * Show the about dialog for Event
     *
     * @return string rendered dialog
     */
    public function controllerList(Application $app)
    {
        $this->initialize($app);

        $ProposeData = new ProposeData($app);
        $proposes = $ProposeData->selectList();

        return $this->app['twig']->render($this->app['utils']->getTemplateFile(
            '@phpManufaktur/Event/Template', 'admin/list.propose.twig'),
            array(
                'usage' => self::$usage,
                'toolbar' => $this->getToolbar('propose'),
                'proposes' => $proposes,
                'alert' => $this->getAlert()
            ));
    }

}


text:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Caliburn.Micro.Xamarin.Forms;
using EasyStocks.Model;
using EasyStocks.Settings;
using EasyStocks.ViewModel;
using Xamarin.Forms;
using INavigationService = EasyStocks.ViewModel.INavigationService;
using IXamarinNavigationService = Caliburn.Micro.Xamarin.Forms.INavigationService;
using Caliburn.Micro;

namespace EasyStocks.App.Platform
{
    public class XamarinNavigationServiceAdapter : INavigationService
    {
        private readonly IXamarinNavigationService _xamarinNavigationService;
        // container is needed so that we can create view models directly
        private readonly SimpleContainer _container;
        private int _pageCount = 0; // we count how many pages were added to the root page so we know when we reach the top

        public XamarinNavigationServiceAdapter(
            IXamarinNavigationService xamarinNavigationService,
            SimpleContainer container)
        {
            _xamarinNavigationService = xamarinNavigationService;
            _container = container;
        }

        public void NavigateToCreateAccountItem(ShareDailyInformation shareInfo)
        {
            _pageCount++;
            // in order to create the view model, the parameters must either be provided
            // as dictionary (which does not work for us, since we want to set all parameters at once)
            // or by using a single parameter which will be set to the "Parameter" property.
            _xamarinNavigationService.NavigateToViewModelAsync<AccountItemCreateViewModel>(shareInfo);
    }

        public void NavigateToEditAccountItem(IEnumerable<AccountItemId> accountItemIds)
        {
            _pageCount++;
            _xamarinNavigationService.NavigateToViewModelAsync<AccountItemEditViewModel>(accountItemIds);
        }

        public void NavigateToPortfolio()
        {
            if(_pageCount > 0)
                _xamarinNavigationService.GoBackToRootAsync();
            _pageCount = 0;
        }

        public void NavigateToSearchView()
        {
            _pageCount++;
            _xamarinNavigationService.NavigateToViewModelAsync<SearchShareViewModel>();
        }

        public async Task NavigateToStorageSelection(ApplicationSettings settings)
        {
            _pageCount++;
            // there is only one instance of this view model, so we can get it from the container
            var selectStorageByUser = _container.GetInstance<StorageSelectionViewModel>();
            await _xamarinNavigationService.NavigateToViewModelAsync<StorageSelectionViewModel>(settings);
            // when the dialog closes, it should set its task state
            await selectStorageByUser.ViewModelClosedTask;
        }

        public async Task NavigateToDropBoxLogin(ApplicationSettings settings)
        {
            _pageCount++;
            var dropboxLogin = _container.GetInstance<DropboxLoginViewModel>();
            await _xamarinNavigationService.NavigateToViewModelAsync<DropboxLoginViewModel>(settings);
            await dropboxLogin.ViewModelClosedTask;
        }
    }
}


text:
# node-telegram-bot-manager
An API/manager for easily setting up a telegram messenger bot in NodeJS.

## How to use?
```javascript
// Using it with a 3 second polling system
let telegram = new (require('telegram-bot-manager').BotManager)({"botToken": yourBotToken});

// Using webhooks
let telegram = new (require('telegram-bot-manager').BotManager)({
  "botToken": yourBotToken
  , "type": "webhook"
  , "key": yourSslKey
  , "cert": yourSslCertificate
  , "receiver": { // Settings for the webhook endpoint
    "port": incomingWebhookPort // The port it will be running on, make sure you have access to it on your server
    , "protocol": "http" // What protocol will it use, http or https depending on how you want to use it
    , "endpoint": yourBotLocation // The url or ip for where your server is located
  }
});

// To execute a call to the API use the name of the API call and add a data object
telegram.apiCall(
    'sendMessage' // API to call
    , { // Required data object
        "chatId": 1234
        , "encodedMessage": "Hello, how are you?"
    }
);

// To get output from your bot, you register callbacks, these callbacks are the instructions sent like "/start"
telegram.on('start', startCall); // Start/help/settings are suggested by telegram messenger to always have for your bot
telegram.on('help', helpCall);
telegram.on('settings', settingsCall);
telegram.on('default', defaultCall);  // This one is unique to this library as this will take any not registered calls,
// as well as any generic messages (if privacy mode is off on the bot)
```

Link to telegram messenger bot API reference: https://core.telegram.org/bots/api

Currently this code only supports polling telegram messenger for bot messages, but now that telegram messenger API supports self signed certificates, this will be implemented.


text:
L'interrupteur permet d'activer ou d'inactiver une option ou encore de faire un choix parmi deux états mutuellement exclusifs.

## Caractéristiques
### Libellé
Le libellé décrivant l'option est toujours placé à droite du bouton. Dans certaines situations, par exemple si on désire aligner plusieurs interrupteurs l'un sous l'autre, il peut être utile de placer le libellé à gauche.

### États et messages de validation
Ce composent gère les états (en attente, désactivé, erreur, valide) et les messages de validation tout en offrant la possibilité de personaliser chacun de ces paramètres.

<modul-demo>

```html
<m-switch :disabled="true" label="Zone de texte"></m-switch>
<m-switch :waiting="true" label="Zone de texte"></m-switch>
<m-switch :error="true" label="Zone de texte" error-message="Nulla excepteur cillum occaecat nisi occaecat duis in."></m-switch>
<m-switch :valid="true" label="Zone de texte" valid-message="Nulla excepteur cillum occaecat nisi occaecat duis in."></m-switch>
```

```css
.m-switch {
    margin-top: 12px;
}

.m-switch:first-child {
    margin-top: 0;
}
```

</modul-demo>


text:
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;

namespace Microsoft.CodeAnalysis.LanguageServices
{
    internal interface ISymbolDisplayService : ILanguageService
    {
        string ToDisplayString(ISymbol symbol, SymbolDisplayFormat format = null);
        string ToMinimalDisplayString(SemanticModel semanticModel, int position, ISymbol symbol, SymbolDisplayFormat format = null);
        ImmutableArray<SymbolDisplayPart> ToDisplayParts(ISymbol symbol, SymbolDisplayFormat format = null);
        ImmutableArray<SymbolDisplayPart> ToMinimalDisplayParts(SemanticModel semanticModel, int position, ISymbol symbol, SymbolDisplayFormat format = null);
        Task<string> ToDescriptionStringAsync(Workspace workspace, SemanticModel semanticModel, int position, ISymbol symbol, SymbolDescriptionGroups groups = SymbolDescriptionGroups.All, CancellationToken cancellationToken = default(CancellationToken));
        Task<string> ToDescriptionStringAsync(Workspace workspace, SemanticModel semanticModel, int position, ImmutableArray<ISymbol> symbols, SymbolDescriptionGroups groups = SymbolDescriptionGroups.All, CancellationToken cancellationToken = default(CancellationToken));
        Task<ImmutableArray<SymbolDisplayPart>> ToDescriptionPartsAsync(Workspace workspace, SemanticModel semanticModel, int position, ImmutableArray<ISymbol> symbols, SymbolDescriptionGroups groups = SymbolDescriptionGroups.All, CancellationToken cancellationToken = default(CancellationToken));
        Task<IDictionary<SymbolDescriptionGroups, ImmutableArray<SymbolDisplayPart>>> ToDescriptionGroupsAsync(Workspace workspace, SemanticModel semanticModel, int position, ImmutableArray<ISymbol> symbols, CancellationToken cancellationToken = default(CancellationToken));
    }
}


text:
Creates ZIP output streams. Depends on Node's build-in zlib module for compression available since version 0.6.

*This is a fork of the original repo meant to resolve several issues and hopefully more active development.*

## Install
    npm install zipstream-ctalkington

## API
    createZip(options)

Creates a ZipStream object. Options are passed to Zlib.

    ZipStream.addFile(inputStream, options, callback)

Adds a file to the ZIP stream. At this moment, options must contain "name". If the "store" option is set to true, the file will be added uncompressed.

    ZipStream.finalize(callback(bytes written))

Finalizes the ZIP. When everything is done, callback is called with the total number of bytes in the ZIP archive.

## Example
```javascript
var fs = require('fs');

var zipstream = require('zipstream-ctalkington');

var out = fs.createWriteStream('out.zip');
var zip = zipstream.createZip({ level: 1 });

zip.pipe(out);

zip.addFile(fs.createReadStream('file1.js'), { name: 'file1.js' }, function() {
  zip.addFile(fs.createReadStream('file2.js'), { name: 'file2.js' }, function() {
    zip.finalize(function(written) { console.log(written + ' total bytes written'); });
  });
});
```

## Contributing

#### Code Style Guide

* code should be indented with 2 spaces
* single quotes should be used where feasible
* commas should be followed by a single space (function params, etc)
* variable declaration should include `var`, [no multiple declarations](http://benalman.com/news/2012/05/multiple-var-statements-javascript/)

#### Tests

* tests should be added to the nodeunit config in `test/tests.js`
* tests can be run with `npm test`
* see existing tests for guidance

## Credits
Originally written by Antoine van Wel ([website](http://wellawaretech.com)).


text:
package org.lpw.tephra.dao.dialect;

import org.lpw.tephra.bean.BeanFactory;
import org.lpw.tephra.bean.ContextRefreshedListener;
import org.springframework.stereotype.Repository;

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

/**
 * @author lpw
 */
@Repository("tephra.dao.dialect.factory")
public class DialectFactoryImpl implements DialectFactory, ContextRefreshedListener {
    protected Map<String, Dialect> dialects;

    @Override
    public Dialect get(String name) {
        return dialects.get(name);
    }

    @Override
    public int getContextRefreshedSort() {
        return 2;
    }

    @Override
    public void onContextRefreshed() {
        dialects = new HashMap<>();
        BeanFactory.getBeans(Dialect.class).forEach(dialect -> dialects.put(dialect.getName(), dialect));
    }
}


text:
/** @babel */

/* eslint-env jasmine */
import log4js from 'log4js'
import PkgGroupsGroup from '../lib/pkg-groups-group'

const logger = log4js.getLogger('pkg-groups-group-spec')
logger.level = 'debug'

describe('PkgGroupsGroup', () => {
  let betty
  const pkgList = ['pkg-groups', 'MagicPython', 'project-manager']

  beforeEach(() => {
    betty = new PkgGroupsGroup({name: 'test1', packages: pkgList, type: 'group', deserializer: 'pkgGroupsGroup'})
  })

  it('has a name', () => {
    let fred = new PkgGroupsGroup({name: 'fred', packages: [], type: 'group'})
    expect(fred.name).toBe('fred')
  })

  it('has a list of packages', () => {
    expect(betty.name).toBe('test1')
    for (const pkg of pkgList) {
      expect(betty.has(pkg))
    }
    expect(betty.size).toEqual(pkgList.length)
  })

  it('serializes', () => {
    let data = betty.serialize()
    // verify that data is in fact convertible
    let checkConvert = JSON.stringify(data)
    expect(checkConvert).toContain('"type":"group"')
    expect(data['type']).toEqual('group')
    expect(data['name']).toEqual('test1')
    expect(data['packages']).toContain('pkg-groups')
    expect(data['deserializer']).toEqual('PkgGroupsGroup')
  })

  it('can call a function with each package', () => {
    let actual = []
    /* actual signature is (value, key, iter) */
    /* for a Set value === key, and iter === the Set */
    const add = (value) => actual.push(value)
    betty.forEach(add)
    const expected = ['pkg-groups', 'MagicPython', 'project-manager']
    expect(actual).toEqual(expected)
  })

  it('can pass a context to the callback', () => {
    let actualContext = { pkgs: [] }
    const expected = ['pkg-groups', 'MagicPython', 'project-manager']
    /* actual signature is (value, key, iter) */
    /* for a Set value === key, and iter === the Set */
    const add = function (value) { this.pkgs.push(value) }
    betty.forEach(add, actualContext)
    expect(actualContext.pkgs).toEqual(expected)
  })
})


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="renderer" content="webkit">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="liu.wang">
    <meta http-equiv="Cache-Control" content="max-age=2592000" />
    <meta http-equiv="Access-Control-Allow-Origin" content="http://api.football-data.org" />
    <link href="styles/css/font-awesome.css" rel="stylesheet" />

    <title>Where I have been | by liuw53</title>
    <link href="image/favicon.ico" type="image/x-icon" rel="shortcut icon">
    <link rel="stylesheet" href="frm/fish-desktop/css/fish-desktop-default.css">
    <link rel="stylesheet" href="styles/css/tooltip-proj-all.css">
    <link rel="stylesheet" href="styles/css/tooltip-proj-all.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">


text:
package com.jcertif.offlinebox.beans;

import java.util.List;
import lombok.Data;

/**
 * A wrapper class that contains list of {@link WebSite}, the purpose of this class is to
 * unmarshall the websites value from the config file
 * @author Komi Serge Innocent <komi.innocent@gmail.com>
 */

@Data
public class WebSiteWrapper {

    private List<WebSite> webSites;

    public WebSiteWrapper() {

    }
}


text:
<!--
   Copyright 2004 The Apache Software Foundation

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
-->

<body>

Classes and interfaces used in the implementation of conditional contributions.

</body>


text:
import pandas as pd
import numpy as np
import xgboost as xgb
from scipy import sparse
from sklearn.feature_extraction import FeatureHasher
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.preprocessing import LabelEncoder, OneHotEncoder, scale
from sklearn.decomposition import TruncatedSVD, SparsePCA
from sklearn.cross_validation import train_test_split, cross_val_score
from sklearn.feature_selection import SelectPercentile, f_classif, chi2
from sklearn.linear_model import LogisticRegression, SGDClassifier
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier
from sklearn.metrics import log_loss

# Create bag-of-apps in character string format
# first by event
# then merge to generate larger bags by device

# import code; code.interact(local=dict(globals(), **locals()))

path = "data/"

##################
#  Train and Test
##################
print("# Generate Train and Test")

train = pd.read_csv("data/gender_age_train.csv",
                    dtype={'device_id': np.str})
train.drop(["age", "gender"], axis=1, inplace=True)

test = pd.read_csv("data/gender_age_test.csv",
                   dtype={'device_id': np.str})
test["group"] = np.nan

split_len = len(train)

# Group Labels
Y = train["group"]
lable_group = LabelEncoder()
Y = lable_group.fit_transform(Y)
device_id = test["device_id"]

FLS = pd.read_csv(path+"fls.csv",
                  dtype={'device_id': np.str})

###################
# User-Item Feature
###################
print("# User-Item-Feature")

device_ids = FLS["device_id"].unique()
feature_cs = FLS["feature"].unique()

data = np.ones(len(FLS))
dec = LabelEncoder().fit(FLS["device_id"])
row = dec.transform(FLS["device_id"])
col = LabelEncoder().fit_transform(FLS["feature"])
sparse_matrix = sparse.csr_matrix(
    (data, (row, col)), shape=(len(device_ids), len(feature_cs)))

sparse_matrix = sparse_matrix[:, sparse_matrix.getnnz(0) > 0]

##################
#      Data
##################

train_row = dec.transform(train["device_id"])
train_sp = sparse_matrix[train_row, :]

test_row = dec.transform(test["device_id"])
test_sp = sparse_matrix[test_row, :]

X_train, X_val, y_train, y_val = train_test_split(
    train_sp, Y, train_size=.90, random_state=10)

##################
#   Feature Sel
##################
print("# Feature Selection")
selector = SelectPercentile(f_classif, percentile=100)

selector.fit(X_train, y_train)

X_train = selector.transform(X_train)
X_val = selector.transform(X_val)

train_sp = selector.transform(train_sp)
test_sp = selector.transform(test_sp)

print("# Num of Features: ", X_train.shape[1])

##################
#  Build Model
##################

dtrain = xgb.DMatrix(X_train, y_train)
dvalid = xgb.DMatrix(X_val, y_val)

params = {
    "objective": "multi:softprob",
    "num_class": 12,
    "booster": "gblinear",
    "max_depth": 5,
    "eval_metric": "mlogloss",
    "eta": 0.02,
    "silent": 1,
    "alpha": 3,
    "min_child_weight": 2.7,
    "gamma": 0,
    "subsample": 0.5,
    "colsample_bytree": 0.5
}
watchlist = [(dtrain, 'train'), (dvalid, 'eval')]
gbm = xgb.train(params, dtrain, 300, evals=watchlist,
                early_stopping_rounds=25, verbose_eval=True)

y_pre = gbm.predict(xgb.DMatrix(test_sp))

# Write results
result = pd.DataFrame(y_pre, columns=lable_group.classes_)
result["device_id"] = device_id
result = result.set_index("device_id")
result.to_csv('fine_tune.csv', index=True,
          index_label='device_id')


text:
import static org.junit.Assert.assertEquals;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import tester.annotations.*;

@Exercises({ @Ex(exID = "Locale", points = 1) })
public class UnitTest {

	@Rule
	public final PointsLogger pointsLogger = new PointsLogger();
	@ClassRule
	public final static PointsSummary pointsSummary = new PointsSummary();

	@Test(timeout = 500)
	@Points(exID = "Locale", bonus = 1)
	public void test() {
		assertEquals(42, ToTest.test());
	}
}


text:
<?xml version='1.0' encoding='UTF-8' ?>
<pdashReportArchive version="1.0">
  <file name="arch_item_86.png" contentType="image/png" />
  <file name="arch_item_95.png" contentType="image/png" />
  <file name="arch_item_75.png" contentType="image/png" />
  <file name="arch_item_88.gif" contentType="image/gif" />
  <file name="arch_item_53.png" contentType="image/png" />
  <file name="arch_item_58.png" contentType="image/png" />
  <file name="arch_item_61.png" contentType="image/png" />
  <file name="arch_item_81.png" contentType="image/png" />
  <file name="arch_item_72.htm" contentType="text/html; charset=UTF-8" />
  <file name="arch_item_79.png" contentType="image/png" />
  <file name="arch_item_28.htm" contentType="text/html; charset=UTF-8" />
  <file name="arch_item_71.htm" contentType="text/html; charset=UTF-8" />
  <file name="arch_item_55.css" contentType="text/css" />
  <file name="arch_item_49.png" contentType="image/png" />
  <file name="arch_item_14.js" contentType="text/javascript" />
  <file name="arch_item_67.png" contentType="image/png" />
  <file name="arch_item_91.png" contentType="image/png" />
  <file name="arch_item_39.png" contentType="image/png" />
  <file name="arch_item_92.png" contentType="image/png" />
  <file name="arch_item_11.css" contentType="text/css" />
  <file name="arch_item_13.css" contentType="text/css" />
  <file name="arch_item_9.gif" contentType="image/gif" />
  <file name="arch_item_2.gif" contentType="image/gif" />
  <file name="arch_item_10.js" contentType="text/javascript" />
  <file name="arch_item_19.js" contentType="text/javascript" />
  <file name="arch_item_83.png" contentType="image/png" />
  <file name="arch_item_35.png" contentType="image/png" />
  <file name="arch_item_34.png" contentType="image/png" />
  <file name="arch_item_32.js" contentType="text/javascript" />
  <file name="arch_item_23.png" contentType="image/png" />
  <file name="arch_item_33.js" contentType="text/javascript" />
  <file name="arch_item_41.png" contentType="image/png" />
  <file name="arch_item_60.png" contentType="image/png" />
  <file name="arch_item_3.gif" contentType="image/gif" />
  <file name="arch_item_82.png" contentType="image/png" />
  <file name="arch_item_90.png" contentType="image/png" />
  <file name="arch_item_48.png" contentType="image/png" />
  <file name="arch_item_52.png" contentType="image/png" />
  <file name="arch_item_69.css" contentType="text/css" />
  <file name="arch_item_89.gif" contentType="image/gif" />
  <file name="arch_item_17.css" contentType="text/css" />
  <file name="arch_item_70.txt" contentType="text/plain" />
  <file name="arch_item_84.gif" contentType="image/gif" />
  <file name="arch_item_38.png" contentType="image/png" />
  <file name="arch_item_97.png" contentType="image/png" />
  <file name="arch_item_21.png" contentType="image/png" />
  <file name="arch_item_37.png" contentType="image/png" />
  <file name="arch_item_0.htm" contentType="text/html; charset=UTF-8" isDefault="true" />
  <file name="arch_item_62.png" contentType="image/png" />
  <file name="arch_item_76.gif" contentType="image/gif" />
  <file name="arch_item_1.htm" contentType="text/html; charset=UTF-8" />
  <file name="arch_item_57.png" contentType="image/png" />
  <file name="arch_item_26.htm" contentType="text/html; charset=UTF-8" />
  <file name="arch_item_20.png" contentType="image/png" />
  <file name="arch_item_93.gif" contentType="image/gif" />
  <file name="arch_item_66.png" contentType="image/png" />
  <file name="arch_item_42.png" contentType="image/png" />
  <file name="arch_item_77.png" contentType="image/png" />
  <file name="arch_item_80.png" contentType="image/png" />
  <file name="arch_item_5.gif" contentType="image/gif" />
  <file name="arch_item_78.png" contentType="image/png" />
  <file name="arch_item_45.png" contentType="image/png" />
  <file name="arch_item_64.png" contentType="image/png" />
  <file name="arch_item_27.htm" contentType="text/html; charset=UTF-8" />
  <file name="arch_item_63.png" contentType="image/png" />
  <file name="arch_item_44.png" contentType="image/png" />
  <file name="arch_item_22.png" contentType="image/png" />
  <file name="arch_item_68.png" contentType="image/png" />
  <file name="arch_item_36.png" contentType="image/png" />
  <file name="arch_item_96.png" contentType="image/png" />
  <file name="arch_item_18.js" contentType="text/javascript" />
  <file name="arch_item_15.css" contentType="text/css" />
  <file name="arch_item_43.png" contentType="image/png" />
  <file name="arch_item_25.css" contentType="text/css" />
  <file name="arch_item_65.png" contentType="image/png" />
  <file name="arch_item_16.js" contentType="text/javascript" />
  <file name="arch_item_59.png" contentType="image/png" />
  <file name="arch_item_85.gif" contentType="image/gif" />
  <file name="arch_item_51.png" contentType="image/png" />
  <file name="arch_item_56.js" contentType="text/javascript" />
  <file name="arch_item_47.png" contentType="image/png" />
  <file name="arch_item_40.png" contentType="image/png" />
  <file name="arch_item_4.gif" contentType="image/gif" />
  <file name="arch_item_94.png" contentType="image/png" />
  <file name="arch_item_87.png" contentType="image/png" />
  <file name="arch_item_24.png" contentType="image/png" />
  <file name="arch_item_74.gif" contentType="image/gif" />
  <file name="arch_item_6.gif" contentType="image/gif" />
  <file name="arch_item_30.css" contentType="text/css" />
  <file name="arch_item_54.htm" contentType="text/html; charset=UTF-8" />
  <file name="arch_item_8.gif" contentType="image/gif" />
  <file name="arch_item_46.png" contentType="image/png" />
  <file name="arch_item_50.png" contentType="image/png" />
  <file name="arch_item_7.gif" contentType="image/gif" />
  <file name="arch_item_73.png" contentType="image/png" />
  <file name="arch_item_12.js" contentType="text/javascript" />
  <file name="arch_item_31.js" contentType="text/javascript" />
  <file name="arch_item_98.png" contentType="image/png" />
  <file name="arch_item_29.htm" contentType="text/html; charset=UTF-8" />
</pdashReportArchive>


text:
package no.nextgentel.oss.akkatools.persistence

import java.io.UnsupportedEncodingException
import java.net.URLDecoder

import akka.actor.{ActorPath, PoisonPill}
import akka.contrib.pattern.ShardRegion

import scala.concurrent.duration.FiniteDuration
import scala.reflect.ClassTag

abstract class EnhancedPersistentShardingActor[E:ClassTag, Ex <: Exception : ClassTag]
(
  idleTimeout:FiniteDuration,
  ourDispatcherActor:ActorPath
  ) extends EnhancedPersistentActor[E, Ex](idleTimeout) {

  def this(ourDispatcherActor:ActorPath) = this(EnhancedPersistentActor.DEFAULT_IDLE_TIMEOUT_IN_SECONDS, ourDispatcherActor)

  override def persistenceId: String = {
    // Same as in akka 2.3.3
    // We need to have it resolvable like this
    // Sharding is creating instances of these actors with no id in constructor, so we must resolve it from the path.
    // Sharding IS giving eavh actor a unique name based on the (correct) id.
    val pathWithoutAddress: String = self.path.toStringWithoutAddress
    try {
      // Sharding urlencodes the last part of the path which is our id - therefor we must url-decode it
      return URLDecoder.decode(pathWithoutAddress, "UTF-8")
    }
    catch {
      case e: UnsupportedEncodingException => {
        throw new RuntimeException("Error url-decoding persistenceId " + pathWithoutAddress, e)
      }
    }
  }

  protected def onInactiveTimeout() {
    context.parent ! ShardRegion.Passivate(PoisonPill)
  }

  // The dispatchId that is used when sending messages to this actor - typically serviceId or requestId - extract it from actorPath
  lazy val dispatchId: String = {
    val id: String = self.path.name
    try {
      URLDecoder.decode(id, "UTF-8")
    }
    catch {
      case e: UnsupportedEncodingException => {
        throw new RuntimeException("Error url-decoding dispatchId " + id, e)
      }
    }
  }

  override protected def getDurableMessageSender(): ActorPath = ourDispatcherActor

  // Sending messages with our dispatcherId as confirmation routing info - to help the confirmation coming back to us
  override protected def sendAsDurableMessage(payload: AnyRef, destinationActor: ActorPath): Unit =
    sendAsDurableMessage(payload, destinationActor, dispatchId)

  // Sending messages with our dispatcherId as confirmation routing info - to help the confirmation coming back to us
  override protected def sendAsDurableMessage(sendAsDurableMessage: SendAsDurableMessage): Unit = {
    super.sendAsDurableMessage( sendAsDurableMessage.copy(confirmationRoutingInfo = dispatchId) )
  }
}

abstract class EnhancedPersistentShardingJavaActor[Ex <: Exception : ClassTag](idleTimeout:FiniteDuration, ourDispatcherActor:ActorPath) extends EnhancedPersistentShardingActor[AnyRef, Ex](idleTimeout, ourDispatcherActor) with EnhancedPersistentJavaActorLike {

  def this(ourDispatcherActor:ActorPath) = this(EnhancedPersistentActor.DEFAULT_IDLE_TIMEOUT_IN_SECONDS, ourDispatcherActor)

}


text:
package org.wso2.carbon.uuf.renderablecreator.hbs.helpers.runtime;

import org.testng.Assert;
import org.testng.annotations.Test;
import org.wso2.carbon.uuf.core.RequestLookup;
import org.wso2.carbon.uuf.renderablecreator.hbs.exception.HbsRenderingException;

import static org.mockito.Mockito.when;
import static org.wso2.carbon.uuf.renderablecreator.hbs.helpers.runtime.RuntimeHelpersTestUtil.createAPI;
import static org.wso2.carbon.uuf.renderablecreator.hbs.helpers.runtime.RuntimeHelpersTestUtil.createLookup;
import static org.wso2.carbon.uuf.renderablecreator.hbs.helpers.runtime.RuntimeHelpersTestUtil.createRenderable;

/**
 * Test cases for the {@code {{favicon}}} helper.
 *
 * @since 1.0.0
 */
public class FaviconHelperTest {

    @Test
    public void test() {
        RequestLookup requestLookup = createRequestLookup();
        createRenderable("{{favicon \"img/favicon.png\" type=\"image/png\"}}")
                .render(null, createLookup(), requestLookup, createAPI());
        String faviconUrl = "<link rel=\"shortcut icon\" href=\"/myapp/public/component/base/img/favicon.png\" " +
                "type=\"image/png\" />\n";

        String output = createRenderable("X {{placeholder \"favicon\"}} Y")
                .render(null, createLookup(), requestLookup, createAPI());
        Assert.assertEquals(output, "X " + faviconUrl + " Y");
    }

    @Test
    public void testWithDefault() {
        String layoutTemplate = "X" +
                "{{#placeholder \"favicon\"}}" +
                " <link rel=\"shortcut icon\" href=\"{{public \"img/default-favicon.png\"}}\" type=\"image/png\"/>" +
                "{{/placeholder}}" +
                " Y";
        String faviconUrl =
                "<link rel=\"shortcut icon\" href=\"/myapp/public/component/base/img/default-favicon.png\" " +
                        "type=\"image/png\"/>";

        String output = createRenderable(layoutTemplate).render(null, createLookup(), createRequestLookup(),
                                                                createAPI());
        Assert.assertEquals(output, "X " + faviconUrl + " Y");
    }

    @Test
    public void testValidation() {
        Assert.assertThrows(HbsRenderingException.class,
                            () -> createRenderable("{{favicon null}}")
                                    .render(null, createLookup(), createRequestLookup(), createAPI()));
    }

    private static RequestLookup createRequestLookup() {
        RequestLookup requestLookup = RuntimeHelpersTestUtil.createRequestLookup();
        when(requestLookup.getPublicUri()).thenReturn("/myapp/public/component/base");
        return requestLookup;
    }
}


text:
import {
  Photo,
  photosEmptyInitialValues,
  PhotosFormModel,
} from "app/Scenes/SellWithArtsy/SubmitArtwork/UploadPhotos/validation"
import { Action, action } from "easy-peasy"
import {
  artworkDetailsEmptyInitialValues,
  ArtworkDetailsFormModel,
} from "../SubmitArtwork/ArtworkDetails/validation"

interface ConsignmentsSubmissionUtmParams {
  utm_term?: string
  utm_medium?: string
  utm_source?: string
}

export interface ArtworkSubmissionModel {
  submissionId: string
  submissionIdForMyCollection: string
  setSubmissionId: Action<ArtworkSubmissionModel, string>
  artworkDetails: ArtworkDetailsFormModel
  dirtyArtworkDetailsValues: ArtworkDetailsFormModel
  setArtworkDetailsForm: Action<ArtworkSubmissionModel, ArtworkDetailsFormModel>
  setDirtyArtworkDetailsValues: Action<ArtworkSubmissionModel, ArtworkDetailsFormModel>
  initializeArtworkDetailsForm: Action<ArtworkSubmissionModel, Partial<ArtworkDetailsFormModel>>
  initializePhotos: Action<ArtworkSubmissionModel, Photo[]>
  photos: PhotosFormModel
  photosForMyCollection: PhotosFormModel
  setPhotos: Action<ArtworkSubmissionModel, PhotosFormModel>
  setPhotosForMyCollection: Action<ArtworkSubmissionModel, PhotosFormModel>
  setSubmissionIdForMyCollection: Action<ArtworkSubmissionModel, string>
  setUtmParams: Action<ArtworkSubmissionModel, ConsignmentsSubmissionUtmParams>
  resetSessionState: Action<ArtworkSubmissionModel>
}

export interface SubmissionModel {
  submission: ArtworkSubmissionModel
}

export const getSubmissionModel = (): SubmissionModel => ({
  submission: {
    submissionId: "",
    submissionIdForMyCollection: "",
    artworkDetails: artworkDetailsEmptyInitialValues,
    dirtyArtworkDetailsValues: artworkDetailsEmptyInitialValues,
    photos: photosEmptyInitialValues,
    photosForMyCollection: photosEmptyInitialValues,
    setPhotosForMyCollection: action((state, photos) => {
      state.photosForMyCollection = photos
    }),
    setSubmissionIdForMyCollection: action((state, submissionId) => {
      state.submissionIdForMyCollection = submissionId
    }),
    setPhotos: action((state, photos) => {
      state.photos = photos
    }),
    initializePhotos: action((state, photos) => {
      state.photos.initialPhotos = photos
    }),
    setSubmissionId: action((state, id) => {
      state.submissionId = id
    }),
    setArtworkDetailsForm: action((state, form) => {
      state.artworkDetails = form
    }),
    setDirtyArtworkDetailsValues: action((state, form) => {
      state.dirtyArtworkDetailsValues = form
    }),
    initializeArtworkDetailsForm: action((state, form) => {
      state.artworkDetails = { ...state.artworkDetails, ...form }
    }),
    setUtmParams: action((state, params) => {
      state.artworkDetails = {
        ...state.artworkDetails,
        utmMedium: params.utm_medium,
        utmSource: params.utm_source,
        utmTerm: params.utm_term,
      }
    }),
    resetSessionState: action((state) => {
      state.submissionId = ""
      state.artworkDetails = artworkDetailsEmptyInitialValues
      state.photos = photosEmptyInitialValues
    }),
  },
})


text:
<?php

namespace RedisClient\Protocol;

use RedisClient\Client\AbstractRedisClient;
use RedisClient\Connection\ConnectionFactory;

class ProtocolFactory {

    /**
     * @param AbstractRedisClient $RedisClient
     * @param array $config
     * @return RedisProtocol
     */
    public static function createRedisProtocol(AbstractRedisClient $RedisClient, $config) {
        $onConnect = function() use ($RedisClient, $config) {
            /** @var \RedisClient\RedisClient $RedisClient */
            if (isset($config[AbstractRedisClient::CONFIG_PASSWORD])) {
                $RedisClient->auth($config[AbstractRedisClient::CONFIG_PASSWORD]);
            }
            if (!empty($config[AbstractRedisClient::CONFIG_DATABASE])) {
                $RedisClient->select($config[AbstractRedisClient::CONFIG_DATABASE]);
            }
        };
        return new RedisProtocol(
            ConnectionFactory::createStreamConnection(
                $config[AbstractRedisClient::CONFIG_SERVER],
                $config[AbstractRedisClient::CONFIG_TIMEOUT],
                $config[AbstractRedisClient::CONFIG_CONNECTION],
                $onConnect
            )
        );
    }
}


text:
#pragma once
#include "cocos2d.h"
#include "ui/CocosGUI.h"

USING_NS_CC;

class MainMenuScene :public Layer
{
public:
	static cocos2d::Scene* createScene();
	CREATE_FUNC(MainMenuScene);
	virtual bool init();

private:
	ui::Button *_star;
	ui::Button *_start;
	ui::Button *_setting;

	bool _isSceneReplaced;
	Layer *_aboutLayer;

	void addBackground();
	void addButton();
	void addAboutLayer();
	void removeAboutLayer();
};


text:
/*
 *
 *
 *
 */
package netserv;

import com.corundumstudio.socketio.Configuration;
import com.corundumstudio.socketio.SocketIONamespace;
import com.corundumstudio.socketio.SocketIOServer;
import connexion.NetConnexion;
import general.NetGeneral;
import java.util.logging.Level;
import java.util.logging.Logger;
import main.Const;
import main.StartNStop;
import matchmaking.Matchmaking;
import salon.net.NetSalon;

/**
 * NetworkServeur.java
 *
 */
public class NetworkServeur implements StartNStop {

	public static final String CLIENT_VERSION = "version";
	public static final String CLIENT_CLIENT = "client";
	public static final String CLIENT_SALON = "salon";

	private static final String NSP_NAME = "main";

	private final SocketIOServer io;
	private final SocketIONamespace nspMain;

	private final NetConnexion connexion;
	private final NetGeneral general;
	private final Matchmaking matchmaking;
	private final NetSalon salon;

	public NetworkServeur() {
		this.io = new SocketIOServer(getIOConf());
		this.nspMain = this.io.addNamespace("/" + NSP_NAME);

		this.connexion = new NetConnexion(this.nspMain);
		this.general = new NetGeneral(this.nspMain);
		this.matchmaking = new Matchmaking(this.nspMain);
		this.salon = new NetSalon(this.nspMain);
	}

	@Override
	public void onStart() {
		Logger.getGlobal().log(Level.INFO, "D\u00e9marrage network - ''localhost:{0}''", io.getConfiguration().getPort());

		this.io.start();
	}

	@Override
	public void onStop() {
		this.io.stop();
	}

	private Configuration getIOConf() {
		Configuration conf = new Configuration();
		conf.setHostname("localhost");
		conf.setPort(Const.SERVEUR_PORT);
		return conf;
	}

}


text:
<!doctype html>
<html lang="ja">
    <head>
        <title>Sample list by riot-nav.</title>

        <meta charset="utf-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
        <meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0'/>
        <meta name="viewport" content="width=device-width" />

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    </head>

    <body>
        <application />
    </body>

    <script
      src="https://code.jquery.com/jquery-3.2.1.min.js"
      integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
      crossorigin="anonymous">
    </script>
    <script
      src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"
      integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
      crossorigin="anonymous">
    </script>
    <script src="https://cdn.jsdelivr.net/npm/riot@3.6/riot+compiler.min.js"></script>

    <!-- riot-tags -->
    <script type="riot/tag" src="assets/tags/application.tag"></script>
    <script type="riot/tag" src="assets/tags/navigationbar.tag"></script>

    <script>
        riot.compile(function(){
            riot.mount("application")
        })
    </script>

</html>


text:
[//]: # "This README.md file is auto-generated, all changes to this file will be lost."
[//]: # "To regenerate it, use `python -m synthtool`."
<img src="https://avatars2.githubusercontent.com/u/2810941?v=3&s=96" alt="Google Cloud Platform logo" title="Google Cloud Platform" align="right" height="96" width="96"/>

# [Google BigQuery Storage: Node.js Client](https://github.com/googleapis/google-cloud-node)

[![release level](https://img.shields.io/badge/release%20level-stable-brightgreen.svg?style=flat)](https://cloud.google.com/terms/launch-stages)
[![npm version](https://img.shields.io/npm/v/@google-cloud/bigquery-storage.svg)](https://www.npmjs.org/package/@google-cloud/bigquery-storage)

Client for the BigQuery Storage API

A comprehensive list of changes in each version may be found in
[the CHANGELOG](https://github.com/googleapis/google-cloud-node/tree/main/packages/google-cloud-bigquery-storage/CHANGELOG.md).

* [Google BigQuery Storage Node.js Client API Reference][client-docs]
* [Google BigQuery Storage Documentation][product-docs]
* [github.com/googleapis/google-cloud-node/packages/google-cloud-bigquery-storage](https://github.com/googleapis/google-cloud-node/tree/main/packages/google-cloud-bigquery-storage)

Read more about the client libraries for Cloud APIs, including the older
Google APIs Client Libraries, in [Client Libraries Explained][explained].

[explained]: https://cloud.google.com/apis/docs/client-libraries-explained

**Table of contents:**

* [Quickstart](#quickstart)
  * [Before you begin](#before-you-begin)
  * [Installing the client library](#installing-the-client-library)
  * [Using the client library](#using-the-client-library)
* [Samples](#samples)
* [Versioning](#versioning)
* [Contributing](#contributing)
* [License](#license)

## Quickstart

### Before you begin

1.  [Select or create a Cloud Platform project][projects].
1.  [Enable billing for your project][billing].
1.  [Enable the Google BigQuery Storage API][enable_api].
1.  [Set up authentication with a service account][auth] so you can access the
    API from your local workstation.

### Installing the client library

```bash
npm install @google-cloud/bigquery-storage
```

### Using the client library

```javascript

// The read stream contains blocks of Avro-encoded bytes. We use the
// 'avsc' library to decode these blocks. Install avsc with the following
// command: npm install avsc
const avro = require('avsc');

// See reference documentation at
// https://cloud.google.com/bigquery/docs/reference/storage
const {BigQueryReadClient} = require('@google-cloud/bigquery-storage');

const client = new BigQueryReadClient();

async function bigqueryStorageQuickstart() {
  // Get current project ID. The read session is created in this project.
  // This project can be different from that which contains the table.
  const myProjectId = await client.getProjectId();

  // This example reads baby name data from the public datasets.
  const projectId = 'bigquery-public-data';
  const datasetId = 'usa_names';
  const tableId = 'usa_1910_current';

  const tableReference = `projects/${projectId}/datasets/${datasetId}/tables/${tableId}`;

  const parent = `projects/${myProjectId}`;

  /* We limit the output columns to a subset of those allowed in the table,
   * and set a simple filter to only report names from the state of
   * Washington (WA).
   */
  const readOptions = {
    selectedFields: ['name', 'number', 'state'],
    rowRestriction: 'state = "WA"',
  };

  let tableModifiers = null;
  const snapshotSeconds = 0;

  // Set a snapshot time if it's been specified.
  if (snapshotSeconds > 0) {
    tableModifiers = {snapshotTime: {seconds: snapshotSeconds}};
  }

  // API request.
  const request = {
    parent,
    readSession: {
      table: tableReference,
      // This API can also deliver data serialized in Apache Arrow format.
      // This example leverages Apache Avro.
      dataFormat: 'AVRO',
      readOptions,
      tableModifiers,
    },
  };

  const [session] = await client.createReadSession(request);

  const schema = JSON.parse(session.avroSchema.schema);

  const avroType = avro.Type.forSchema(schema);

  /* The offset requested must be less than the last
   * row read from ReadRows. Requesting a larger offset is
   * undefined.
   */
  let offset = 0;

  const readRowsRequest = {
    // Required stream name and optional offset. Offset requested must be less than
    // the last row read from readRows(). Requesting a larger offset is undefined.
    readStream: session.streams[0].name,
    offset,
  };

  const names = new Set();
  const states = [];

  /* We'll use only a single stream for reading data from the table. Because
   * of dynamic sharding, this will yield all the rows in the table. However,
   * if you wanted to fan out multiple readers you could do so by having a
   * reader process each individual stream.
   */
  client
    .readRows(readRowsRequest)
    .on('error', console.error)
    .on('data', data => {
      offset = data.avroRows.serializedBinaryRows.offset;

      try {
        // Decode all rows in buffer
        let pos;
        do {
          const decodedData = avroType.decode(
            data.avroRows.serializedBinaryRows,
            pos
          );

          if (decodedData.value) {
            names.add(decodedData.value.name);

            if (!states.includes(decodedData.value.state)) {
              states.push(decodedData.value.state);
            }
          }

          pos = decodedData.offset;
        } while (pos > 0);
      } catch (error) {
        console.log(error);
      }
    })
    .on('end', () => {
      console.log(`Got ${names.size} unique names in states: ${states}`);
      console.log(`Last offset: ${offset}`);
    });
}

```

## Samples

Samples are in the [`samples/`](https://github.com/googleapis/google-cloud-node/tree/main/samples) directory. Each sample's `README.md` has instructions for running its sample.

| Sample                      | Source Code                       | Try it |
| --------------------------- | --------------------------------- | ------ |
| Big_query_read.create_read_session | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-bigquery-storage/samples/generated/v1/big_query_read.create_read_session.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=packages/google-cloud-bigquery-storage/samples/generated/v1/big_query_read.create_read_session.js,samples/README.md) |
| Big_query_read.read_rows | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-bigquery-storage/samples/generated/v1/big_query_read.read_rows.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=packages/google-cloud-bigquery-storage/samples/generated/v1/big_query_read.read_rows.js,samples/README.md) |
| Big_query_read.split_read_stream | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-bigquery-storage/samples/generated/v1/big_query_read.split_read_stream.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=packages/google-cloud-bigquery-storage/samples/generated/v1/big_query_read.split_read_stream.js,samples/README.md) |
| Big_query_write.append_rows | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-bigquery-storage/samples/generated/v1/big_query_write.append_rows.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=packages/google-cloud-bigquery-storage/samples/generated/v1/big_query_write.append_rows.js,samples/README.md) |
| Big_query_write.batch_commit_write_streams | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-bigquery-storage/samples/generated/v1/big_query_write.batch_commit_write_streams.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=packages/google-cloud-bigquery-storage/samples/generated/v1/big_query_write.batch_commit_write_streams.js,samples/README.md) |
| Big_query_write.create_write_stream | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-bigquery-storage/samples/generated/v1/big_query_write.create_write_stream.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=packages/google-cloud-bigquery-storage/samples/generated/v1/big_query_write.create_write_stream.js,samples/README.md) |
| Big_query_write.finalize_write_stream | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-bigquery-storage/samples/generated/v1/big_query_write.finalize_write_stream.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=packages/google-cloud-bigquery-storage/samples/generated/v1/big_query_write.finalize_write_stream.js,samples/README.md) |
| Big_query_write.flush_rows | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-bigquery-storage/samples/generated/v1/big_query_write.flush_rows.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=packages/google-cloud-bigquery-storage/samples/generated/v1/big_query_write.flush_rows.js,samples/README.md) |
| Big_query_write.get_write_stream | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-bigquery-storage/samples/generated/v1/big_query_write.get_write_stream.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=packages/google-cloud-bigquery-storage/samples/generated/v1/big_query_write.get_write_stream.js,samples/README.md) |
| Big_query_storage.batch_create_read_session_streams | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-bigquery-storage/samples/generated/v1beta1/big_query_storage.batch_create_read_session_streams.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=packages/google-cloud-bigquery-storage/samples/generated/v1beta1/big_query_storage.batch_create_read_session_streams.js,samples/README.md) |
| Big_query_storage.create_read_session | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-bigquery-storage/samples/generated/v1beta1/big_query_storage.create_read_session.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=packages/google-cloud-bigquery-storage/samples/generated/v1beta1/big_query_storage.create_read_session.js,samples/README.md) |
| Big_query_storage.finalize_stream | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-bigquery-storage/samples/generated/v1beta1/big_query_storage.finalize_stream.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=packages/google-cloud-bigquery-storage/samples/generated/v1beta1/big_query_storage.finalize_stream.js,samples/README.md) |
| Big_query_storage.read_rows | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-bigquery-storage/samples/generated/v1beta1/big_query_storage.read_rows.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=packages/google-cloud-bigquery-storage/samples/generated/v1beta1/big_query_storage.read_rows.js,samples/README.md) |
| Big_query_storage.split_read_stream | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-bigquery-storage/samples/generated/v1beta1/big_query_storage.split_read_stream.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=packages/google-cloud-bigquery-storage/samples/generated/v1beta1/big_query_storage.split_read_stream.js,samples/README.md) |
| BigQuery Storage Quickstart | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-bigquery-storage/samples/quickstart.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=packages/google-cloud-bigquery-storage/samples/quickstart.js,samples/README.md) |
| Quickstart | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-bigquery-storage/samples/test/quickstart.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=packages/google-cloud-bigquery-storage/samples/test/quickstart.js,samples/README.md) |

The [Google BigQuery Storage Node.js Client API Reference][client-docs] documentation
also contains samples.

## Supported Node.js Versions

Our client libraries follow the [Node.js release schedule](https://nodejs.org/en/about/releases/).
Libraries are compatible with all current _active_ and _maintenance_ versions of
Node.js.
If you are using an end-of-life version of Node.js, we recommend that you update
as soon as possible to an actively supported LTS version.

Google's client libraries support legacy versions of Node.js runtimes on a
best-efforts basis with the following warnings:

* Legacy versions are not tested in continuous integration.
* Some security patches and features cannot be backported.
* Dependencies cannot be kept up-to-date.

Client libraries targeting some end-of-life versions of Node.js are available, and
can be installed through npm [dist-tags](https://docs.npmjs.com/cli/dist-tag).
The dist-tags follow the naming convention `legacy-(version)`.
For example, `npm install @google-cloud/bigquery-storage@legacy-8` installs client libraries
for versions compatible with Node.js 8.

## Versioning

This library follows [Semantic Versioning](http://semver.org/).

This library is considered to be **stable**. The code surface will not change in backwards-incompatible ways
unless absolutely necessary (e.g. because of critical security issues) or with
an extensive deprecation period. Issues and requests against **stable** libraries
are addressed with the highest priority.

More Information: [Google Cloud Platform Launch Stages][launch_stages]

[launch_stages]: https://cloud.google.com/terms/launch-stages

## Contributing

Contributions welcome! See the [Contributing Guide](https://github.com/googleapis/google-cloud-node/blob/main/CONTRIBUTING.md).

Please note that this `README.md`, the `samples/README.md`,
and a variety of configuration files in this repository (including `.nycrc` and `tsconfig.json`)
are generated from a central template. To edit one of these files, make an edit
to its templates in
[directory](https://github.com/googleapis/synthtool).

## License

Apache Version 2.0

See [LICENSE](https://github.com/googleapis/google-cloud-node/blob/main/LICENSE)

[client-docs]: https://cloud.google.com/nodejs/docs/reference/bigquery-storage/latest
[product-docs]: https://cloud.google.com/bigquery/docs/reference/storage
[shell_img]: https://gstatic.com/cloudssh/images/open-btn.png
[projects]: https://console.cloud.google.com/project
[billing]: https://support.google.com/cloud/answer/6293499#enable-billing
[enable_api]: https://console.cloud.google.com/flows/enableapi?apiid=bigquerystorage.googleapis.com
[auth]: https://cloud.google.com/docs/authentication/getting-started


text:
Phylogenetic Tree and Multiple Sequence Alignment (MSA) Services
=============================================

Overview
----------
This service provides a set of methods for querying, manipulating, and analyzing multiple
sequence alignments and phylogenetic trees.  It also has functions to build alignments and
trees.

Authors
---------
Michael Sneddon, LBL (mwsneddon@lbl.gov)
Fangfang Xia, ANL (fangfang.xia@gmail.com)
Matt Henderson, LBL (mhenderson@lbl.gov)
Roman Sutormin, LBL (rsutormin@lbl.gov)

Special deployment instructions
----------
* The Tree service is currently only supported for server deployment in a linux environment.  Only clients and
scripts should be deployed on a Mac.  (to deploy only clients/scripts, use make deploy-client; make deploy-scripts)
* follow the standard KBase deployment and testing procedures

Starting/Stopping the service, and other notes
---------------------------
* to start and stop the service, use the 'start_service' and 'stop_service'
  scripts in (the default location) /kb/deployment/services/trees


text:
require('proof')(1, (okay) => {
    const rethrow = require('../rethrow')
    try {
        rethrow(new Error('thrown'))
        throw new Error
    } catch (error) {
        okay(error.message, 'thrown', 'thrown')
    }
})