text:
#if defined(_MSC_VER)
#define NOMINMAX
#pragma once
#endif

#ifndef PBRT_CAMERAS_REALISTIC_H
#define PBRT_CAMERAS_REALISTIC_H
#include "stdafx.h"

// cameras/realistic.h*
#include "pbrt.h"
#include "camera.h"
#include "film.h"

// RealisticCamera Declarations
class RealisticCamera : public Camera {
  public:
    // RealisticCamera Public Methods
    RealisticCamera(const AnimatedTransform &CameraToWorld, Float shutterOpen,
                    Float shutterClose, Float apertureDiameter,
                    Float focusDistance, bool simpleWeighting,
                    const char *lensFile, Film *film, const Medium *medium);
    Float GenerateRay(const CameraSample &sample, Ray *) const;

  private:
    // RealisticCamera Private Declarations
    struct LensElementInterface {
        Float curvatureRadius;
        Float thickness;
        Float eta;
        Float apertureRadius;
    };

    // RealisticCamera Private Data
    bool simpleWeighting;
    std::vector<LensElementInterface> elementInterfaces;
    std::vector<Bounds2f> exitPupilBounds;

    // RealisticCamera Private Methods
    Float LensRearZ() const { return elementInterfaces.back().thickness; }
    Float LensFrontZ() const {
        Float zsum = 0.f;
        for (auto element : elementInterfaces) zsum += element.thickness;
        return zsum;
    }
    Float RearElementRadius() const {
        return elementInterfaces.back().apertureRadius;
    }
    bool TraceLensesFromFilm(const Ray &ray, Ray *rOut) const;
    static bool IntersectSphericalElement(Float radius, Float center,
                                          const Ray &ray, Float *t,
                                          Normal3f *n);
    bool TraceLensesFromScene(const Ray &ray, Ray *rOut) const;
    void DrawLensSystem() const;
    void DrawRayPathFromFilm(const Ray &r, bool arrow,
                             bool toOpticalIntercept) const;
    void DrawRayPathFromScene(const Ray &r, bool arrow,
                              bool toOpticalIntercept) const;
    static void ComputeCardinalPoints(const Ray &rIn, const Ray &rOut, Float *p,
                                      Float *f);
    void ComputeThickLensApproximation(Float P[2], Float f[2]) const;
    Float FocusThickLens(Float focusDistance);
    Float FocusBinarySearch(Float focusDistance);
    Float FocusDistance(Float filmDist);
    Bounds2f BoundExitPupil(const Point2f &pFilm) const;
    void RenderExitPupil(Float sx, Float sy, const char *filename) const;
    Point3f SampleExitPupil(const Point2f &pFilm,
                            const Point2f &lensSample) const;
    void TestExitPupilBounds() const;
    Float ExitPupilPdf(const Point3f &pFilm, const Point3f &pExitPupil) const;
};

RealisticCamera *CreateRealisticCamera(const ParamSet &params,
                                       const AnimatedTransform &cam2world,
                                       Film *film, const Medium *medium);

#endif  // PBRT_CAMERAS_REALISTIC_H


text:
<?php

/**
 * saNotificationMailTemplateLoaderFilesystem
 *
 * @package    SfAdvanced
 * @subpackage util
 * @author     Kousuke Ebihara <ebihara@tejimaya.com>
 */

class saNotificationMailTemplateLoaderFilesystem extends sfTemplateSwitchableLoaderFilesystemForSymfony1
{
  public function configure()
  {
    $dirs = $this->context->getConfiguration()->getGlobalTemplateDirs();
    foreach ($dirs as $k => $v)
    {
      $this->templateDirs[$k] = $v.'/mail/%name%.%extension%';
    }
  }

  public function doLoad($template, $renderer = 'php')
  {
    $template = str_replace(array('pc_', 'mobile_', 'admin_'), array('pc/_', 'mobile/_', 'admin/_'), $template);

    return parent::doLoad($template, $renderer);
  }
}

redpajama_set_name: RedPajamaGithub


text:
from __future__ import unicode_literals

from django.db import models, migrations
import easy_thumbnails.fields

class Migration(migrations.Migration):

    dependencies = [
        ('medicos', '0002_auto_20150327_0024'),
    ]

    operations = [
        migrations.AddField(
            model_name='medicos',
            name='foto',
            field=easy_thumbnails.fields.ThumbnailerImageField(upload_to=b'medicos_fotos', null=True, verbose_name='Foto del m\xe9dico', blank=True),
            preserve_default=True,
        ),
    ]


text:
package com.cg.bank;
public class BankClient {
	public static void main(String[] args) {
		BankAccount ba1 = new BankAccount();
		ba1.setBankAccount(1111, "Smita", 1000);
		ba1.print();
		ba1.deposit(2000);
		ba1.withdraw(1200);
	}
}


text:
![alt-text](imgs/one-to-one.jpg "One-to-One Schema")

This is a one-to-one schema because each person can have only 1 (active) drivers license and each drivers license can only belong to 1 person. Just because you are a person, does not mean you necessarily have to have a drivers license though.

![alt-text](imgs/many-to-many.jpg "Many-to-Many Schema")

- What is a one-to-one database?

A one to one database is when two tables have entries where each entry only matches up to one (or none) of the entries in the other table.

- When would you use a one-to-one database? (Think generally, not in terms of the example you created).

You would use a one-to-one database if there is an option for the value to be null or empty.

- What is a many-to-many database?

A many to many database is where two tables have entries where each entry in one table can relate to many entries in the other table and vice versa.

- When would you use a many-to-many database? (Think generally, not in terms of the example you created).

You would use a many-to-many database when you want to relate the items between the two tables and add additional information about those specific instances when the two items are linked.

- What is confusing about database schemas? What makes sense?

I think the one-to-one relationship is difficult to see needing in practice when it wouldn't just be an additional column in your table. Both these schema make logical sense, will be interesting to see in practice.


text:
// Reference implementation of timer functions.  Platforms are not required to
// implement these timer methods, but they are required to enable profiling.

// On platforms that have a POSIX stack or C library, it can be written using
// methods from <sys/time.h> or clock() from <time.h>.

// To add an equivalent function for your own platform, create your own
// implementation file, and place it in a subfolder with named after the OS
// you're targeting. For example, see the Cortex M bare metal version in
// tensorflow/lite/micro/bluepill/micro_timer.cc or the mbed one on
// tensorflow/lite/micro/mbed/micro_timer.cc.

#include "tensorflow/lite/micro/micro_time.h"

// These are headers from Ambiq's Apollo3 SDK.
#include "am_bsp.h"         // NOLINT
#include "am_mcu_apollo.h"  // NOLINT
#include "am_util.h"        // NOLINT

namespace tflite {
namespace {

// Select CTIMER 1 as benchmarking timer on Sparkfun Edge. This timer must not
// be used elsewhere.
constexpr int kTimerNum = 1;

// Clock set to operate at 12MHz.
constexpr int kClocksPerSecond = 12e6;

}  // namespace

int32_t ticks_per_second() { return kClocksPerSecond; }

// Calling this method enables a timer that runs for eternity. The user is
// responsible for avoiding trampling on this timer's config, otherwise timing
// measurements may no longer be valid.
int32_t GetCurrentTimeTicks() {
  // TODO(b/150808076): Split out initialization, intialize in interpreter.
  static bool is_initialized = false;
  if (!is_initialized) {
    am_hal_ctimer_config_t timer_config;
    // Operate as a 32-bit timer.
    timer_config.ui32Link = 1;
    // Set timer A to continuous mode at 12MHz.
    timer_config.ui32TimerAConfig =
        AM_HAL_CTIMER_FN_CONTINUOUS | AM_HAL_CTIMER_HFRC_12MHZ;

    am_hal_ctimer_stop(kTimerNum, AM_HAL_CTIMER_BOTH);
    am_hal_ctimer_clear(kTimerNum, AM_HAL_CTIMER_BOTH);
    am_hal_ctimer_config(kTimerNum, &timer_config);
    am_hal_ctimer_start(kTimerNum, AM_HAL_CTIMER_TIMERA);
    is_initialized = true;
  }
  return CTIMERn(kTimerNum)->TMR0;
}

}  // namespace tflite


text:
package rdigo

import (
	"encoding/json"
	"io/ioutil"
	"log"
)

type PlaybackTokenResponse struct {
	Result string `json:"result"`
	Status string `json:"status"`
}

func (r *Rdio) GetPlaybackToken(domain string) (PlaybackTokenResponse, error) {
	query := make(map[string]string)
	query["method"] = "getPlaybackToken"
	query["domain"] = domain
	resp, err := r.consumer.Post(baseUrl, query, r.AccessToken)
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Println("Rdio Call Error:", err.Error())
		return PlaybackTokenResponse{}, err
	}
	rdioResp := PlaybackTokenResponse{}
	err = json.Unmarshal(body, &rdioResp)
	if err != nil {
		log.Println("Rdio Call Error:", err.Error())
		return PlaybackTokenResponse{}, err
	}
	return rdioResp, err
}


text:
ifndef QUATERNION
QUATERNION=QUATERNION

ifndef CLEANFOLDER
CLEANFOLDER=QUATERNION
endif

include ../../Makefile-headers/Makefile-header
R ?= ../..

# the object files to be compiled for this library
QUATERNIONOBJECTS=quaternion.o

# the libraries this library depends on
QUATERNIONLIBS=

# the headers in this library
QUATERNIONHEADERS=quaternion.h

QUATERNIONOBJECTS_FILENAMES=$(addprefix $(L)/quaternion/, $(QUATERNIONOBJECTS))
QUATERNIONHEADER_FILENAMES=$(addprefix $(L)/quaternion/, $(QUATERNIONHEADERS))
QUATERNIONLIB_MAKEFILES=$(call GET_LIB_MAKEFILES, $(QUATERNIONLIBS))
QUATERNIONLIB_FILENAMES=$(call GET_LIB_FILENAMES, $(QUATERNIONLIBS))

include $(QUATERNIONLIB_MAKEFILES)

all: $(L)/quaternion/libquaternion.a

$(L)/quaternion/libquaternion.a: $(QUATERNIONOBJECTS_FILENAMES)
	ar r $@ $^; cp $@ $(L)/lib; cp $(L)/quaternion/*.h $(L)/include

$(QUATERNIONOBJECTS_FILENAMES): %.o: %.cpp $(QUATERNIONLIB_FILENAMES) $(QUATERNIONHEADER_FILENAMES)
	$(CXX) $(CXXFLAGS) -c $(INCLUDE) $(BLASLAPACK_INCLUDE) $< -o $@

ifeq ($(CLEANFOLDER), QUATERNION)
clean: cleanquaternion
endif

deepclean: cleanquaternion

cleanquaternion:
	$(RM) $(QUATERNIONOBJECTS_FILENAMES) $(L)/quaternion/libquaternion.a

endif


text:
package es.uvigo.ei.sing.sds
package searcher

import scala.concurrent.Future

import play.api.libs.concurrent.Execution.Implicits.defaultContext

import entity._
import service.ABNERService

final class SimpleSearcher extends SearcherAdapter {

  override def search(query: String): Future[Set[Keyword.ID]] =
    searchNormalized(query.toLowerCase.split("\\s+").toSet)

}


text:
<?php

namespace IonXLab\IonXApi\network;

class ApiResponse {

	/**
	 * Status of the HTTP response
     * @type int
	 */
	private $status;
    /**
     * @type string
     */
	private $contentType;
    /**
     * @var array
     */
	private $body;
    /**
     * @var \IonXLab\IonXApi\network\ApiResponse
     */
    private static $instance = null;

    private function __construct() {
	}

    /**
     * Return current or new ApiResponse instance
     * @return ApiResponse
     */
    public static function getInstance() {
        if (is_null(self::$instance)) {
            self::$instance = new ApiResponse();
        }
        return self::$instance;
    }

    public function setResponseError($status, $message="") {
        $this->status = $status;
        if($message!="") {
            $this->body["api-error"] = $message;
        }
    }

	/**
	* @return int
	*/
	public function getStatus()
	{
	    return $this->status;
	}

	/**
	* @param int $status
	*/
	public function setStatus($status)
	{
	    $this->status = $status;
	}

	/**
	* @return string
	*/
	public function getContentType()
	{
	    return $this->contentType;
	}

	/**
	* @param string $contentType
	*/
	public function setContentType($contentType)
	{
	    $this->contentType = $contentType;
	}

	/**
	* @return string
	*/
	public function getBody()
	{
	    return $this->body;
	}

	/**
	* @param string $body
	*/
	public function setBody($body)
	{
	    $this->body = $body;
	}
}

?>


text:
package com.nouribygi.sokhan.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;

import com.nouribygi.sokhan.AboutUsActivity;
import com.nouribygi.sokhan.HelpActivity;
import com.nouribygi.sokhan.PreferenceActivity;
import com.nouribygi.sokhan.R;
import com.nouribygi.sokhan.SokhanApplication;
import com.nouribygi.sokhan.database.BookmarksDBAdapter;
import com.nouribygi.sokhan.ui.fragment.NoteTabsFragment;
import com.nouribygi.sokhan.ui.helper.BookmarkHandler;
import com.nouribygi.sokhan.util.FontStyle;
import com.nouribygi.sokhan.util.SokhanSettings;

public class NotesActivity extends AppCompatActivity
        implements BookmarkHandler {
    public static final String TABS_FRAGMENT_TAG = "tabs_main";

    public static final String EXTRA_POEM_ID = "poemId";

    NoteTabsFragment tabsFragment = null;

    private BookmarksDBAdapter mBookmarksDBAdapter = null;

    private int mPoemId;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        ((SokhanApplication) getApplication()).refreshLocale(false);

        super.onCreate(savedInstanceState);

        boolean mNightMode = SokhanSettings.isNightMode(this);
        if (mNightMode) {
            setTheme(R.style.SokhanTheme_Dark);
        } else {
            setTheme(R.style.SokhanTheme_Light);
        }

        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        if (extras != null) {
            mPoemId = extras.getInt(EXTRA_POEM_ID, 0);
        }

        if (savedInstanceState != null) {
            tabsFragment =
                    (NoteTabsFragment) getSupportFragmentManager().findFragmentByTag(TABS_FRAGMENT_TAG);
        } else {
            tabsFragment = NoteTabsFragment.newInstance(mPoemId);

            getSupportFragmentManager().beginTransaction().add(R.id.content_frame, tabsFragment, TABS_FRAGMENT_TAG).commit();
        }

        setContentView(R.layout.main_layout_wod);

        ActionBar actionbar = getSupportActionBar();
        actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);

        mBookmarksDBAdapter = new BookmarksDBAdapter(this);

        updateActionBarTitle();

    }

    private void updateActionBarTitle() {
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayShowHomeEnabled(true);
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        actionBar.setTitle(R.string.menu_notes);

        int titleId = getResources().getIdentifier("action_bar_title", "id",
                "android");
        TextView titleTextView = (TextView) findViewById(titleId);
        if (titleTextView != null) {
            FontStyle.applyTitrTypeface(this, titleTextView);
            titleTextView.setTextSize(14);
        }
    }

    @Override
    protected void onDestroy() {
        mBookmarksDBAdapter.close();
        super.onDestroy();
    }

    @Override
    public BookmarksDBAdapter getBookmarksAdapter() {
        return mBookmarksDBAdapter;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.home_menu, menu);
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
        MenuItem item = menu.findItem(R.id.search);
        if (item != null) {
            item.setVisible(false);
        }
        item = menu.findItem(R.id.settings);
        if (item != null) {
            item.setVisible(false);
        }

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        } else if (item.getItemId() == R.id.settings) {
            Intent i = new Intent(this, PreferenceActivity.class);
            startActivity(i);
            return true;
        } else if (item.getItemId() == R.id.help) {
            Intent i = new Intent(this, HelpActivity.class);
            startActivity(i);
            return true;
        } else if (item.getItemId() == R.id.about) {
            Intent i = new Intent(this, AboutUsActivity.class);
            startActivity(i);
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

}


text:
//using System;
//using System.Collections.Generic;

//namespace Rock.StaticDependencyInjection
//{
//    public class Widget
//    {
//        private readonly IFoo _foo;
//        private readonly IBar _bar;
//        private readonly IEnumerable<IBaz> _bazes;
//        private readonly IEnumerable<IQux> _quxes;

//        /// <summary>
//        /// Initializes a new instance of the <see cref="Widget"/> class using
//        /// the specified dependencies.
//        /// </summary>
//        /// <param name="foo">
//        /// An instance of <see cref="IFoo"/>. If null or not provided, the value
//        /// of Foo.Current will be used.
//        /// </param>
//        /// <param name="bar">
//        /// An instance of <see cref="IBar"/>. If null or not provided, the value
//        /// of Bar.Current will be used.
//        /// </param>
//        /// <param name="bazes">
//        /// A collection of <see cref="IBaz"/> instances. If null or not provided,
//        /// the value of BazCollection.Current will be used.
//        /// </param>
//        /// <param name="quxes">
//        /// A collection of <see cref="IQux"/> instances. If null or not provided,
//        /// the value of QuxCollection.Current will be used.
//        /// </param>
//        public Widget(
//            IFoo foo = null,
//            IBar bar = null,
//            IEnumerable<IBaz> bazes = null,
//            IEnumerable<IQux> quxes = null)
//        {
//            _foo = foo ?? Foo.Current;
//            _bar = bar ?? Bar.Current;
//            _bazes = bazes ?? BazCollection.Current;
//            _quxes = quxes ?? QuxCollection.Current;
//        }

//        public void ReportDependencies()
//        {
//            Console.WriteLine("IFoo: {0}", _foo);
//            Console.WriteLine("IBar: {0}", _bar);
//            Console.WriteLine("Array of IBaz: [{0}]", string.Join(", ", _bazes));
//            Console.WriteLine("Array of IQux: [{0}]", string.Join(", ", _quxes));
//        }
//    }

//    public interface IFoo
//    {
//    }

//    public class DefaultFoo : IFoo
//    {
//    }

//    public static class Foo
//    {
//        static Foo()
//        {
//            Current = new DefaultFoo();
//        }

//        public static IFoo Current { internal get; set; }
//    }

//    public interface IBar
//    {
//    }

//    public class DefaultBar : IBar
//    {
//    }

//    public static class Bar
//    {
//        static Bar()
//        {
//            Current = new DefaultBar();
//        }

//        public static IBar Current { internal get; set; }
//    }

//    public interface IBarFactory
//    {
//        IBar GetBar();
//    }

//    public interface IBaz
//    {
//    }

//    public static class BazCollection
//    {
//        static BazCollection()
//        {
//            Current = new IBaz[0];
//        }

//        public static IEnumerable<IBaz> Current { internal get; set; }
//    }

//    public interface IQux
//    {
//    }

//    public static class QuxCollection
//    {
//        static QuxCollection()
//        {
//            Current = new IQux[0];
//        }

//        public static IEnumerable<IQux> Current { internal get; set; }
//    }

//    public interface IQuxFactory
//    {
//        IQux GetQux();
//    }
//}


text:
import theano.tensor as T
import theano.tensor.nnet as Tnn
import numpy
import theano
import nonlinearity

class FullyConnected(object):

    """
    Typical hidden layer of a MLP: units are fully-connected and have
    sigmoidal activation function. Weight matrix W is of shape (n_in,n_out)
    and the bias vector b is of shape (n_out,).
    """

    def __init__(self, rng, n_in, n_out, W=None, b=None,
                 activation=T.tanh):

        """
        :type rng: numpy.random.RandomState
        :param rng: a random number generator used to initialize weights

        :type input: theano.tensor.dmatrix
        :param input: a symbolic tensor of shape (n_examples, n_in)

        :type n_in: int
        :param n_in: dimensionality of input

        :type n_out: int
        :param n_out: number of hidden units

        :type activation: theano.Op or function
        :param activation: Non linearity to be applied in the hidden
                           layer
        """

        # `W` is initialized with `W_values` which is uniformely sampled
        # from sqrt(-6./(n_in+n_hidden)) and sqrt(6./(n_in+n_hidden))
        # for tanh activation function
        #
        # the output of uniform if converted using asarray to dtype
        #
        # theano.config.floatX so that the code is runable on GPU
        #
        # Note : optimal initialization of weights is dependent on the
        #        activation function used (among other things).
        #        For example, results presented in [Xavier10] suggest that you
        #        should use 4 times larger initial weights for sigmoid
        #        compared to tanh
        #        We have no info for other function, so we use the same as
        #        tanh.
        if W is None:
            if activation == T.tanh or activation == nonlinearity.tanh or activation == Tnn.sigmoid:
                W_values = numpy.asarray(
                    rng.uniform(
                        low=-numpy.sqrt(6. / (n_in + n_out)),
                        high=numpy.sqrt(6. / (n_in + n_out)),
                        size=(n_in, n_out)
                    ),
                    dtype=theano.config.floatX
                )
                if activation == Tnn.sigmoid:
                    W_values *= 4
            elif activation == nonlinearity.softplus or activation == nonlinearity.relu or activation == None:
                W_values = nonlinearity.initialize_matrix(rng, n_in, n_out)
            else:
                raise Exception('Unknown activation in HiddenLayer.')

            W = theano.shared(value=W_values, name='W', borrow=True)

        if b is None:
            b_values = nonlinearity.initialize_vector(rng, n_out)
            b = theano.shared(value=b_values, name='b', borrow=True)

        self.W = W
        self.b = b
        # parameters of the model
        self.params = [self.W, self.b]
        self.activation = activation

    def output(self, input):
        lin_output = T.dot(input, self.W) + self.b
        return (
            lin_output if self.activation is None
            else self.activation(lin_output)
        )

    def drop_output(self, input, drop=0, rng=None, p=0.5):
        lin_output = T.dot(input, self.W) + self.b
        output = (
            lin_output if self.activation is None
            else self.activation(lin_output)
        )
        droppedOutput = nonlinearity.dropout(rng, output, p)
        return T.switch(T.neq(drop, 0), droppedOutput, output)


text:
// ***********************************************************************
// Assembly         : zohoprojects
// Author           : hari-2197
// Created          : 06-19-2014
//
// Last Modified By : hari-2197
// Last Modified On : 06-19-2014
// ***********************************************************************
// <copyright file="ZohoProjects.cs" company="Zoho Corporation">
//     Copyright (c) . All rights reserved.
// </copyright>
// <summary></summary>
// ***********************************************************************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using zohoprojects.api;

namespace zohoprojects.service
{
    /// <summary>
    /// Class ZohoProjects is used to provide all API instances for the Zoho Project services.
    /// </summary>
    public class ZohoProjects
    {
        /// <summary>
        /// The authentication token
        /// </summary>
        string authToken;
        /// <summary>
        /// The portal identifier
        /// </summary>
        string portalId;
        /// <summary>
        /// Initializes the specified auth_token.
        /// </summary>
        /// <param name="auth_token">The auth_token.</param>
        /// <param name="portal_id">The portal_id.</param>
        public void initialize(string auth_token,string portal_id)
        {
            this.authToken = auth_token;
            this.portalId = portal_id;
        }
        /// <summary>
        /// Gets the dashboard API.
        /// </summary>
        /// <returns>DashboardApi.</returns>
        public DashboardApi GetDashboardApi()
        {
            var dashboardApi = new DashboardApi(authToken, portalId);
            return dashboardApi;
        }
        /// <summary>
        /// Gets the milestones API.
        /// </summary>
        /// <returns>MilestonesApi.</returns>
        public MilestonesApi GetMilestonesApi()
        {
            var milestonesApi = new MilestonesApi(authToken, portalId);
            return milestonesApi;
        }
        /// <summary>
        /// Gets the portals API.
        /// </summary>
        /// <returns>PortalsApi.</returns>
        public PortalsApi GetPortalsApi()
        {
            var portalsApi = new PortalsApi(authToken);
            return portalsApi;
        }
        /// <summary>
        /// Gets the projects API.
        /// </summary>
        /// <returns>ProjectsApi.</returns>
        public ProjectsApi GetProjectsApi()
        {
            var projectsApi = new ProjectsApi(authToken,portalId);
            return projectsApi;
        }
        /// <summary>
        /// Gets the tasklists API.
        /// </summary>
        /// <returns>TasklistsApi.</returns>
        public TasklistsApi GetTasklistsApi()
        {
            var tasklistsApi = new TasklistsApi(authToken, portalId);
            return tasklistsApi;
        }
        /// <summary>
        /// Gets the tasks API.
        /// </summary>
        /// <returns>TasksApi.</returns>
        public TasksApi GetTasksApi()
        {
            var tasksApi = new TasksApi(authToken, portalId);
            return tasksApi;
        }
        /// <summary>
        /// Gets the timesheets API.
        /// </summary>
        /// <returns>TimesheetsApi.</returns>
        public TimesheetsApi GetTimesheetsApi()
        {
            var timesheetsApi = new TimesheetsApi(authToken, portalId);
            return timesheetsApi;
        }
        /// <summary>
        /// Gets the bugs API.
        /// </summary>
        /// <returns>BugsApi.</returns>
        public BugsApi GetBugsApi()
        {
            var bugsApi = new BugsApi(authToken, portalId);
            return bugsApi;
        }
        /// <summary>
        /// Gets the events API.
        /// </summary>
        /// <returns>EventsApi.</returns>
        public EventsApi GetEventsApi()
        {
            var eventsApi = new EventsApi(authToken, portalId);
            return eventsApi;
        }
        /// <summary>
        /// Gets the documents API.
        /// </summary>
        /// <returns>DocumentsApi.</returns>
        public DocumentsApi GetDocumentsApi()
        {
            var documentsApi = new DocumentsApi(authToken, portalId);
            return documentsApi;
        }
        /// <summary>
        /// Gets the forums API.
        /// </summary>
        /// <returns>ForumsApi.</returns>
        public ForumsApi GetForumsApi()
        {
            var forumsApi = new ForumsApi(authToken, portalId);
            return forumsApi;
        }
        /// <summary>
        /// Gets the users API.
        /// </summary>
        /// <returns>UsersApi.</returns>
        public UsersApi GetUsersApi()
        {
            var usersApi = new UsersApi(authToken, portalId);
            return usersApi;
        }
    }
}


text:
fhc-preview(1) -- FeedHenry Application Preview
===============================================

## SYNOPSIS

    fhc preview [show] <app-id>
    fhc preview url <app-id>

## DESCRIPTION

This command can be used to preview your application in your browser. By default, the 'open' command is the default command used on OSX to open the preview url, otherwise 'google-chrome' is the default command.

To set your default brower: fhc set browser firefox
Or on windows: fhc set browser start

## EXAMPLES

    fhc preview mfLkParVTDcr80-uEk8OhEfT


text:
namespace boost {
namespace coroutines2 {
namespace detail {

template< typename T >
class push_coroutine {
private:
    template< typename X >
    friend class pull_coroutine;

    struct control_block;

    control_block   *   cb_;

    explicit push_coroutine( control_block *) noexcept;

public:
    template< typename Fn,
              typename = detail::disable_overload< push_coroutine, Fn >
    >
    explicit push_coroutine( Fn &&);

    template< typename StackAllocator, typename Fn >
    push_coroutine( StackAllocator, Fn &&);

    ~push_coroutine() noexcept;

    push_coroutine( push_coroutine const&) = delete;
    push_coroutine & operator=( push_coroutine const&) = delete;

    push_coroutine( push_coroutine &&) noexcept;

    push_coroutine & operator=( push_coroutine && other) noexcept {
        if ( this == & other) return * this;
        cb_ = other.cb_;
        other.cb_ = nullptr;
        return * this;
    }

    push_coroutine & operator()( T const&);

    push_coroutine & operator()( T &&);

    explicit operator bool() const noexcept;

    bool operator!() const noexcept;

    class iterator : public std::iterator< std::output_iterator_tag, void, void, void, void > {
    private:
        push_coroutine< T > *   c_{ nullptr };

    public:
        constexpr iterator() noexcept = default;

        explicit iterator( push_coroutine< T > * c) noexcept :
            c_{ c } {
        }

        iterator & operator=( T t) {
            BOOST_ASSERT( c_);
            if ( ! ( * c_)( t) ) {
                c_ = nullptr;
            }
            return * this;
        }

        bool operator==( iterator const& other) const noexcept {
            return other.c_ == c_;
        }

        bool operator!=( iterator const& other) const noexcept {
            return other.c_ != c_;
        }

        iterator & operator*() noexcept {
            return * this;
        }

        iterator & operator++() noexcept {
            return * this;
        }
    };
};

template< typename T >
class push_coroutine< T & > {
private:
    template< typename X >
    friend class pull_coroutine;

    struct control_block;

    control_block   *   cb_;

    explicit push_coroutine( control_block *) noexcept;

public:
    template< typename Fn,
              typename = detail::disable_overload< push_coroutine, Fn >
    >
    explicit push_coroutine( Fn &&);

    template< typename StackAllocator, typename Fn >
    push_coroutine( StackAllocator, Fn &&);

    ~push_coroutine() noexcept;

    push_coroutine( push_coroutine const&) = delete;
    push_coroutine & operator=( push_coroutine const&) = delete;

    push_coroutine( push_coroutine &&) noexcept;

    push_coroutine & operator=( push_coroutine && other) noexcept {
        if ( this == & other) return * this;
        cb_ = other.cb_;
        other.cb_ = nullptr;
        return * this;
    }

    push_coroutine & operator()( T &);

    explicit operator bool() const noexcept;

    bool operator!() const noexcept;

    class iterator : public std::iterator< std::output_iterator_tag, void, void, void, void > {
    private:
        push_coroutine< T & >   *   c_{ nullptr };

    public:
        constexpr iterator() noexcept = default;

        explicit iterator( push_coroutine< T & > * c) noexcept :
            c_{ c } {
        }

        iterator & operator=( T & t) {
            BOOST_ASSERT( c_);
            if ( ! ( * c_)( t) ) {
                c_ = nullptr;
            }
            return * this;
        }

        bool operator==( iterator const& other) const noexcept {
            return other.c_ == c_;
        }

        bool operator!=( iterator const& other) const noexcept {
            return other.c_ != c_;
        }

        iterator & operator*() noexcept {
            return * this;
        }

        iterator & operator++() noexcept {
            return * this;
        }
    };
};

template<>
class push_coroutine< void > {
private:
    template< typename X >
    friend class pull_coroutine;

    struct control_block;

    control_block   *   cb_;

    explicit push_coroutine( control_block *) noexcept;

public:
    template< typename Fn,
              typename = detail::disable_overload< push_coroutine, Fn >
    >
    explicit push_coroutine( Fn &&);

    template< typename StackAllocator, typename Fn >
    push_coroutine( StackAllocator, Fn &&);

    ~push_coroutine() noexcept;

    push_coroutine( push_coroutine const&) = delete;
    push_coroutine & operator=( push_coroutine const&) = delete;

    push_coroutine( push_coroutine &&) noexcept;

    push_coroutine & operator=( push_coroutine && other) noexcept {
        if ( this == & other) return * this;
        cb_ = other.cb_;
        other.cb_ = nullptr;
        return * this;
    }

    push_coroutine & operator()();

    explicit operator bool() const noexcept;

    bool operator!() const noexcept;
};

template< typename T >
typename push_coroutine< T >::iterator
begin( push_coroutine< T > & c) {
    return typename push_coroutine< T >::iterator( & c);
}

template< typename T >
typename push_coroutine< T >::iterator
end( push_coroutine< T > &) {
    return typename push_coroutine< T >::iterator();
}

}}}

#ifdef BOOST_HAS_ABI_HEADERS
#  include BOOST_ABI_SUFFIX
#endif

#endif // BOOST_COROUTINES2_DETAIL_PUSH_COROUTINE_HPP


text:
package models.gitbucket

import java.sql.Clob

import org.joda.time.DateTime

import scalikejdbc._

case class Milestone(
  userName: String,
  repositoryName: String,
  milestoneId: Int,
  title: String,
  description: Option[Clob] = None,
  dueDate: Option[DateTime] = None,
  closedDate: Option[DateTime] = None) {

  def save()(implicit session: DBSession = Milestone.autoSession): Milestone = Milestone.save(this)(session)

  def destroy()(implicit session: DBSession = Milestone.autoSession): Unit = Milestone.destroy(this)(session)

}

object Milestone extends SQLSyntaxSupport[Milestone] {

  override val tableName = "MILESTONE"

  override val columns = Seq("USER_NAME", "REPOSITORY_NAME", "MILESTONE_ID", "TITLE", "DESCRIPTION", "DUE_DATE", "CLOSED_DATE")

  def apply(m: SyntaxProvider[Milestone])(rs: WrappedResultSet): Milestone = apply(m.resultName)(rs)
  def apply(m: ResultName[Milestone])(rs: WrappedResultSet): Milestone = new Milestone(
    userName = rs.get(m.userName),
    repositoryName = rs.get(m.repositoryName),
    milestoneId = rs.get(m.milestoneId),
    title = rs.get(m.title),
    description = rs.get(m.description),
    dueDate = rs.get(m.dueDate),
    closedDate = rs.get(m.closedDate)
  )

  val m = Milestone.syntax("m")

  override val autoSession = AutoSession

  def find(milestoneId: Int, repositoryName: String, userName: String)(implicit session: DBSession = autoSession): Option[Milestone] = {
    withSQL {
      select.from(Milestone as m).where.eq(m.milestoneId, milestoneId).and.eq(m.repositoryName, repositoryName).and.eq(m.userName, userName)
    }.map(Milestone(m.resultName)).single.apply()
  }

  def findAll()(implicit session: DBSession = autoSession): List[Milestone] = {
    withSQL(select.from(Milestone as m)).map(Milestone(m.resultName)).list.apply()
  }

  def countAll()(implicit session: DBSession = autoSession): Long = {
    withSQL(select(sqls.count).from(Milestone as m)).map(rs => rs.long(1)).single.apply().get
  }

  def findBy(where: SQLSyntax)(implicit session: DBSession = autoSession): Option[Milestone] = {
    withSQL {
      select.from(Milestone as m).where.append(where)
    }.map(Milestone(m.resultName)).single.apply()
  }

  def findAllBy(where: SQLSyntax)(implicit session: DBSession = autoSession): List[Milestone] = {
    withSQL {
      select.from(Milestone as m).where.append(where)
    }.map(Milestone(m.resultName)).list.apply()
  }

  def countBy(where: SQLSyntax)(implicit session: DBSession = autoSession): Long = {
    withSQL {
      select(sqls.count).from(Milestone as m).where.append(where)
    }.map(_.long(1)).single.apply().get
  }

  def create(
    userName: String,
    repositoryName: String,
    title: String,
    description: Option[Clob] = None,
    dueDate: Option[DateTime] = None,
    closedDate: Option[DateTime] = None)(implicit session: DBSession = autoSession): Milestone = {
    val generatedKey = withSQL {
      insert.into(Milestone).columns(
        column.userName,
        column.repositoryName,
        column.title,
        column.description,
        column.dueDate,
        column.closedDate
      ).values(
        userName,
        repositoryName,
        title,
        description,
        dueDate,
        closedDate
      )
    }.updateAndReturnGeneratedKey.apply()

    Milestone(
      milestoneId = generatedKey.toInt,
      userName = userName,
      repositoryName = repositoryName,
      title = title,
      description = description,
      dueDate = dueDate,
      closedDate = closedDate)
  }

  def save(entity: Milestone)(implicit session: DBSession = autoSession): Milestone = {
    withSQL {
      update(Milestone).set(
        column.userName -> entity.userName,
        column.repositoryName -> entity.repositoryName,
        column.milestoneId -> entity.milestoneId,
        column.title -> entity.title,
        column.description -> entity.description,
        column.dueDate -> entity.dueDate,
        column.closedDate -> entity.closedDate
      ).where.eq(column.milestoneId, entity.milestoneId).and.eq(column.repositoryName, entity.repositoryName).and.eq(column.userName, entity.userName)
    }.update.apply()
    entity
  }

  def destroy(entity: Milestone)(implicit session: DBSession = autoSession): Unit = {
    withSQL { delete.from(Milestone).where.eq(column.milestoneId, entity.milestoneId).and.eq(column.repositoryName, entity.repositoryName).and.eq(column.userName, entity.userName) }.update.apply()
  }

}


text:
package org.elasticsearch.spark.rdd.api.java

import java.util.{Map => JMap}

import scala.collection.JavaConverters.mapAsScalaMapConverter

import org.apache.spark.api.java.JavaPairRDD
import org.apache.spark.api.java.JavaPairRDD.fromRDD
import org.apache.spark.api.java.JavaRDD
import org.apache.spark.api.java.JavaSparkContext
import org.elasticsearch.hadoop.cfg.ConfigurationOptions.ES_OUTPUT_JSON
import org.elasticsearch.hadoop.cfg.ConfigurationOptions.ES_QUERY
import org.elasticsearch.hadoop.cfg.ConfigurationOptions.ES_RESOURCE_READ
import org.elasticsearch.spark.rdd.EsSpark
import org.elasticsearch.spark.rdd.JavaEsRDD

object JavaEsSpark {

  // specify the return types to make sure the bytecode is generated properly (w/o any scala.collections in it)
  def esRDD(jsc: JavaSparkContext): JavaPairRDD[String, JMap[String, Object]] = fromRDD(new JavaEsRDD[JMap[String, Object]](jsc.sc))
  def esRDD(jsc: JavaSparkContext, resource: String): JavaPairRDD[String, JMap[String, Object]] =
    fromRDD(new JavaEsRDD[JMap[String, Object]](jsc.sc, Map(ES_RESOURCE_READ -> resource)))
  def esRDD(jsc: JavaSparkContext, resource: String, query: String): JavaPairRDD[String, JMap[String, Object]] =
    fromRDD(new JavaEsRDD[JMap[String, Object]](jsc.sc, Map(ES_RESOURCE_READ -> resource, ES_QUERY -> query)))
  def esRDD(jsc: JavaSparkContext, cfg: JMap[String, String]): JavaPairRDD[String, JMap[String, Object]] =
    fromRDD(new JavaEsRDD[JMap[String, Object]](jsc.sc, cfg.asScala))

  def esJsonRDD(jsc: JavaSparkContext): JavaPairRDD[String, String] = fromRDD(new JavaEsRDD[String](jsc.sc, Map(ES_OUTPUT_JSON -> true.toString)))
  def esJsonRDD(jsc: JavaSparkContext, resource: String): JavaPairRDD[String, String] =
    fromRDD(new JavaEsRDD[String](jsc.sc, Map(ES_RESOURCE_READ -> resource, ES_OUTPUT_JSON -> true.toString)))
  def esJsonRDD(jsc: JavaSparkContext, resource: String, query: String): JavaPairRDD[String, String] =
    fromRDD(new JavaEsRDD[String](jsc.sc, Map(ES_RESOURCE_READ -> resource, ES_QUERY -> query, ES_OUTPUT_JSON -> true.toString)))
  def esJsonRDD(jsc: JavaSparkContext, cfg: JMap[String, String]): JavaPairRDD[String, String] =
    fromRDD(new JavaEsRDD[String](jsc.sc, cfg.asScala += (ES_OUTPUT_JSON -> true.toString)))

  def saveToEs(jrdd: JavaRDD[_], resource: String) = EsSpark.saveToEs(jrdd.rdd, resource)
  def saveToEs(jrdd: JavaRDD[_], resource: String, cfg: JMap[String, String]) = EsSpark.saveToEs(jrdd.rdd, resource, cfg.asScala)
  def saveToEs(jrdd: JavaRDD[_], cfg: JMap[String, String]) = EsSpark.saveToEs(jrdd.rdd, cfg.asScala)

  def saveToEsWithMeta[K, V](jrdd: JavaPairRDD[K, V], resource: String) = EsSpark.saveToEsWithMeta(jrdd.rdd, resource)
  def saveToEsWithMeta[K, V](jrdd: JavaPairRDD[K, V], resource: String, cfg: JMap[String, String]) = EsSpark.saveToEsWithMeta(jrdd.rdd, resource, cfg.asScala)
  def saveToEsWithMeta[K, V](jrdd: JavaPairRDD[K, V], cfg: JMap[String, String]) = EsSpark.saveToEsWithMeta(jrdd.rdd, cfg.asScala)

  def saveJsonToEs(jrdd: JavaRDD[String], resource: String) = EsSpark.saveJsonToEs(jrdd.rdd, resource)
  def saveJsonToEs(jrdd: JavaRDD[String], resource: String, cfg: JMap[String, String]) = EsSpark.saveJsonToEs(jrdd.rdd, resource, cfg.asScala)
  def saveJsonToEs(jrdd: JavaRDD[String], cfg: JMap[String, String]) = EsSpark.saveJsonToEs(jrdd.rdd, cfg.asScala)

  def saveJsonByteArrayToEs(jrdd: JavaRDD[Array[Byte]], resource: String) = EsSpark.saveJsonToEs(jrdd.rdd, resource)
  def saveJsonByteArrayToEs(jrdd: JavaRDD[Array[Byte]], resource: String, cfg: JMap[String, String]) = EsSpark.saveJsonToEs(jrdd.rdd, resource, cfg.asScala)
  def saveJsonByteArrayToEs(jrdd: JavaRDD[Array[Byte]], cfg: JMap[String, String]) = EsSpark.saveJsonToEs(jrdd.rdd, cfg.asScala)
}


text:
package com.frank.search.solr.config;

import com.frank.search.solr.repository.config.SolrRepositoryConfigExtension;
import com.frank.search.solr.server.config.EmbeddedSolrServerBeanDefinitionParser;
import com.frank.search.solr.server.config.HttpSolrClientBeanDefinitionParser;
import org.springframework.beans.factory.xml.NamespaceHandlerSupport;
import org.springframework.data.repository.config.RepositoryBeanDefinitionParser;
import org.springframework.data.repository.config.RepositoryConfigurationExtension;

/**
 * {@link org.springframework.beans.factory.xml.NamespaceHandler} implementation to register parser for {@code <solr:repositories />},
 * {@code <solr:embedded-solr-server solrHome="path/to/solr/home/directory" />} elements.
 *
 * @author Oliver Gierke
 * @author Christoph Strobl
 */
class SolrNamespaceHandler extends NamespaceHandlerSupport {

	/*
	 * (non-Javadoc)
	 * @see org.springframework.beans.factory.xml.NamespaceHandler#init()
	 */
	@Override
	public void init() {

		RepositoryConfigurationExtension extension = new SolrRepositoryConfigExtension();
		RepositoryBeanDefinitionParser parser = new RepositoryBeanDefinitionParser(extension);

		registerBeanDefinitionParser("repositories", parser);
		registerBeanDefinitionParser("embedded-solr-server", new EmbeddedSolrServerBeanDefinitionParser());
		registerBeanDefinitionParser("solr-client", new HttpSolrClientBeanDefinitionParser());
	}
}


text:
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<script type="application/javascript" src="../node_modules/seajs/dist/sea.js"></script>
<script type="application/javascript">
    seajs.config({
        base: "./js"
    });
    seajs.use("../js/loadAudio", function (loadAudio) {
        var context = new AudioContext();
        loadAudio.setconfig(context, "../audio/test.mp3", function (buffer) {
            console.log("this");
            var source = context.createBufferSource();
            source.buffer = buffer;
            source.connect(context.destination);
            source.start(0);
        });
        loadAudio.start();
    });
</script>
</body>
</html>


text:
package restclient.jamadomain.lazyresources;

import com.jamasoftware.services.restclient.JamaConfig;
import com.jamasoftware.services.restclient.exception.RestClientException;
import com.jamasoftware.services.restclient.httpconnection.TestHttpClient;
import com.jamasoftware.services.restclient.jamadomain.core.JamaInstance;
import com.jamasoftware.services.restclient.jamadomain.fields.RichTextField;
import com.jamasoftware.services.restclient.jamadomain.lazyresources.JamaItem;
import com.jamasoftware.services.restclient.jamadomain.lazyresources.JamaItemType;
import com.jamasoftware.services.restclient.jamadomain.lazyresources.JamaProject;
import com.jamasoftware.services.restclient.jamadomain.lazyresources.JamaUser;
import com.jamasoftware.services.restclient.jamadomain.values.*;
import junit.framework.TestCase;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.concurrent.TimeUnit;

public class JamaItemTest extends TestCase {

    public void testRetrieval() throws RestClientException {
        JamaConfig jamaConfig = new JamaConfig();
        jamaConfig.setBaseUrl("test");
        jamaConfig.setHttpClient(new TestHttpClient());
        jamaConfig.setPassword("");
        jamaConfig.setUsername("");
        jamaConfig.setResourceTimeOut(1);

        JamaInstance jamaInstance = new JamaInstance(jamaConfig);
        JamaItem jamaItem = jamaInstance.getItem(2210690);

        assertEquals("Test Item", jamaItem.getName().getValue());
        assertEquals("GID-AFD-113502", jamaItem.getGlobalId());
        assertEquals("Z-AFD-1", jamaItem.getDocumentKey());
        assertEquals(JamaItemType.class, jamaItem.getItemType().getClass());
        assertEquals(JamaProject.class, jamaItem.getProject().getClass());
        assertNull(jamaItem.getChildItemType());
        Date createdDate = new Date(1478733450000L);
        assertEquals(createdDate, jamaItem.getCreatedDate());
        assertNull(jamaItem.getModifiedDate());
        assertEquals(JamaUser.class, jamaItem.getCreatedBy().getClass());
        assertEquals(jamaItem.getSequence(), "1.1");
        //TODO assertEquals(jamaItem.getParent().getName(), "AllFieldsDemos");
        assertFalse(jamaItem.isLocked());
        assertEquals(createdDate, jamaItem.lastLockedDate());
        assertEquals(createdDate, jamaItem.lastLockedDate());
        assertNull(jamaItem.lockedBy());
        assertEquals(2210690, jamaItem.getId().intValue());
        try {
            refresh(jamaItem);
            fields(jamaItem);
        } catch (Exception e) {
            throw new RestClientException(e);
        }

    }

    public void refresh(JamaItem jamaItem) throws Exception {
        Field field = JamaItem.class.getDeclaredField("name");
        field.setAccessible(true);
        TextFieldValue oldNameValue = new TextFieldValue();
        oldNameValue.setValue("oldName");
        field.set(jamaItem, oldNameValue);
        assertEquals("oldName", field.get(jamaItem).toString());
        TimeUnit.SECONDS.sleep(1);
        assertEquals("Test Item", jamaItem.getName().getValue());
    }

    public void checkField(Class clazz, String value, JamaFieldValue fieldValue) {
        assertTrue(clazz.isInstance(fieldValue));
        assertEquals(value, fieldValue.toString());
    }

    public void fields(JamaItem jamaItem) throws Exception {
        checkField(TextFieldValue.class, "Z-AFD-1", jamaItem.getFieldValueByName("documentKey"));
        checkField(RichTextFieldValue.class, "
Description
\n", jamaItem.getFieldValueByName("description"));
        //TODO: test with multiSelectFieldValue
        checkField(FlagFieldValue.class, "true", jamaItem.getFieldValueByName("flag"));
        assertEquals(new Date(1478592000000L), jamaItem.getFieldValueByName("date").getValue());
        checkField(DateFieldValue.class, "Tue Nov 08 00:00:00 PST 2016", jamaItem.getFieldValueByName("date"));
        checkField(URLFieldValue.class, "http://www.google.com", jamaItem.getFieldValueByName("url"));
        //TODO: test with userFieldValue, PickListFieldValue, ReleaseFieldValue
        checkField(RollupFieldValue.class, "50", jamaItem.getFieldValueByName("rollup"));
        checkField(CalculatedFieldValue.class, "3", jamaItem.getFieldValueByName("calculated"));
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;

namespace Tavis.UriTemplates
{
    public static class UriTemplateExtensions
    {
        public static UriTemplate AddParameter(this UriTemplate template, string name, object value)
        {
            template.SetParameter(name, value);

            return template;
        }

        public static UriTemplate AddParameters(this UriTemplate template, object parametersObject)
        {

            if (parametersObject != null)
            {
                IEnumerable<PropertyInfo> properties;
#if NETSTANDARD1_0
                var type = parametersObject.GetType().GetTypeInfo();
                properties = type.DeclaredProperties.Where(p=> p.CanRead);
#else
                properties = parametersObject.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
#endif

                foreach (var propinfo in properties)
                {
                    template.SetParameter(propinfo.Name, propinfo.GetValue(parametersObject, null));
                }
            }

            return template;
        }
        public static UriTemplate AddParameters(this UriTemplate uriTemplate, IDictionary<string, object> linkParameters)
        {
            if (linkParameters != null)
            {
                foreach (var parameter in linkParameters)
                {
                    uriTemplate.SetParameter(parameter.Key, parameter.Value);
                }
            }
            return uriTemplate;
        }
    }

    public static class UriExtensions
    {
        public static UriTemplate MakeTemplate(this Uri uri)
        {
            var parameters = uri.GetQueryStringParameters();
            return MakeTemplate(uri, parameters);

        }

        public static UriTemplate MakeTemplate(this Uri uri, IDictionary<string, object> parameters)
        {
            var target = uri.GetComponents(UriComponents.AbsoluteUri
                                                     & ~UriComponents.Query
                                                     & ~UriComponents.Fragment, UriFormat.Unescaped);
            var template = new UriTemplate(target + "{?" + string.Join(",", parameters.Keys.ToArray()) + "}");
            template.AddParameters(parameters);

            return template;
        }

        public static Dictionary<string, object> GetQueryStringParameters(this Uri target)
        {
            Uri uri = target;
            var parameters = new Dictionary<string, object>();

            var reg = new Regex(@"([-A-Za-z0-9._~]*)=([^&]*)&?");		// Unreserved characters: http://tools.ietf.org/html/rfc3986#section-2.3
            foreach (Match m in reg.Matches(uri.Query))
            {
                string key = m.Groups[1].Value.ToLowerInvariant();
                string value = m.Groups[2].Value;
                parameters.Add(key, value);
            }
            return parameters;
        }

    }
}


text:
package controlador;

import spark.*;
import modelo.*;
import java.util.*;
import persistencia.ResenhaDAO;

/** Testa se o usuário está logado, se sim "seta" a resenha, o número do usuário e o ISBN do livro. Cria uma variável booleana que
 * testa se a resenha já existe, se sim envia uma mensagem de erro, se não salva e direciona para ver_resenha com o número do ISBN */
public class SalvaResenhaControlador implements TemplateViewRoute {

	ResenhaDAO dao = new ResenhaDAO();

	public ModelAndView handle(Request req, Response resp) {
		Resenha resenha = new Resenha();
		Usuario usuario = req.session().attribute("usuario_logado");
		resenha.setTexto(req.queryMap("texto").value());
		resenha.setNumero(usuario.getNumero());
		resenha.setISBN(req.params("ISBN"));

		boolean resenhaJaExiste = dao.resenhaExiste(resenha);
		if (!resenhaJaExiste) dao.save(resenha);
		else {
			String erro2 = "Você já tem resenha desse livro!";
			HashMap mapa2 = new HashMap();
			mapa2.put("erro2", erro2);
			return new ModelAndView(mapa2, "adiciona_resenha.html");
		}

		req.session().attribute("resenha_logada", resenha);
		resp.redirect("/ver_resenha/" + resenha.getISBN());
		return null;
	}
}


text:
We have started containers in the foreground, and in the background.

In this chapter, we will see how to:

* Put a container in the background.
* Attach to a background container to bring it to the foreground.
* Restart a stopped container.

---

## Background and foreground

The distinction between foreground and background containers is arbitrary.

From Docker's point of view, all containers are the same.

All containers run the same way, whether there is a client attached to them or not.

It is always possible to detach from a container, and to reattach to a container.

Analogy: attaching to a container is like plugging a keyboard and screen to a physical server.

---

## Detaching from a container (Linux/macOS)

* If you have started an *interactive* container (with option `-it`), you can detach from it.

* The "detach" sequence is `^P^Q`.

* Otherwise you can detach by killing the Docker client.

  (But not by hitting `^C`, as this would deliver `SIGINT` to the container.)

What does `-it` stand for?

* `-t` means "allocate a terminal."
* `-i` means "connect stdin to the terminal."

---

## Detaching cont. (Win PowerShell and cmd.exe)

* Docker for Windows has a different detach experience due to shell features.

* `^P^Q` does not work.

* `^C` will detach, rather than stop the container.

* Using Bash, Subsystem for Linux, etc. on Windows behaves like Linux/macOS shells.

* Both PowerShell and Bash work well in Win 10; just be aware of differences.

---

class: extra-details

## Specifying a custom detach sequence

* You don't like `^P^Q`? No problem!
* You can change the sequence with `docker run --detach-keys`.
* This can also be passed as a global option to the engine.

Start a container with a custom detach command:

```bash
$ docker run -ti --detach-keys ctrl-x,x jpetazzo/clock
```

Detach by hitting `^X x`. (This is ctrl-x then x, not ctrl-x twice!)

Check that our container is still running:

```bash
$ docker ps -l
```

---

class: extra-details

## Attaching to a container

You can attach to a container:

```bash
$ docker attach <containerID>
```

* The container must be running.
* There *can* be multiple clients attached to the same container.
* If you don't specify `--detach-keys` when attaching, it defaults back to `^P^Q`.

Try it on our previous container:

```bash
$ docker attach $(docker ps -lq)
```

Check that `^X x` doesn't work, but `^P ^Q` does.

---

## Detaching from non-interactive containers

* **Warning:** if the container was started without `-it`...

  * You won't be able to detach with `^P^Q`.
  * If you hit `^C`, the signal will be proxied to the container.

* Remember: you can always detach by killing the Docker client.

---

## Checking container output

* Use `docker attach` if you intend to send input to the container.

* If you just want to see the output of a container, use `docker logs`.

```bash
$ docker logs --tail 1 --follow <containerID>
```

---

## Restarting a container

When a container has exited, it is in stopped state.

It can then be restarted with the `start` command.

```bash
$ docker start <yourContainerID>
```

The container will be restarted using the same options you launched it
with.

You can re-attach to it if you want to interact with it:

```bash
$ docker attach <yourContainerID>
```

Use `docker ps -a` to identify the container ID of a previous `jpetazzo/clock` container,
and try those commands.

---

## Attaching to a REPL

* REPL = Read Eval Print Loop

* Shells, interpreters, TUI ...

* Symptom: you `docker attach`, and see nothing

* The REPL doesn't know that you just attached, and doesn't print anything

* Try hitting `^L` or `Enter`

---

class: extra-details

## SIGWINCH

* When you `docker attach`, the Docker Engine sends SIGWINCH signals to the container.

* SIGWINCH = WINdow CHange; indicates a change in window size.

* This will cause some CLI and TUI programs to redraw the screen.

* But not all of them.

???

:EN:- Restarting old containers
:EN:- Detaching and reattaching to container
:FR:- Redémarrer des anciens conteneurs
:FR:- Se détacher et rattacher à des conteneurs


text:
var midi = require("../../midi.js");
var input = new midi.Input();


text:
'''
Unit tests for the robotutils.config_helper module.

This is a port of the JUnit test for the corresponding Java
robotutils class, ConfigurationHelper
Author: JMJ
'''

import unittest
import io

from .context import config_helper

class TestConfigHelper(unittest.TestCase):
    """Container for config_helper unit tests"""

    def test_simple_section_usage(self):
        """Test simple non-empty section"""
        inp = "\n".join(("mySection:", "  sk: sv", "  ik: 10\n"))
        reader = io.StringIO(inp) # in-memory stream input
        keys = []
        mapper = config_helper.read_section(reader, "mySection", keys)
        writer = io.StringIO() # in-memory stream output
        bresult = config_helper.write_section("mySection", mapper, keys, writer)
        self.assertTrue(bresult)
        output = writer.getvalue()
        self.assertEqual(inp, output)

    def test_simple_list_usage(self):
        """Test a simple list of two items"""
        inp = "\n".join(("myList:", "  - item1", "  - item2\n"))

        reader = io.StringIO(inp) # in-memory stream input
        lines = config_helper.read_list("myList", reader)
        writer = io.StringIO() # in-memory stream output
        bresult = config_helper.write_list("myList", lines, writer)
        self.assertTrue(bresult)
        output = writer.getvalue()
        self.assertEqual(inp, output)

    def test_messy_yaml_input(self):
        """Test a much more complicated config file"""
        inp = """
# This is a comment
---

# Section 1
section1:
  k1a: v1a
  k1b: v1b
sectionx:# empty section
section2: # with comment
    k2a:     v2a
    k2b:     v2b

section3: # with comment
    kComplex: #complex section to be ignored
      with complex floating text
       complex1: 1
       complex2: 2
    k3a:     v3a # added comment
# some comment and empty lines and lines with spacecs
  # comment

               \t
    k3b:     v3b

section4: # with comment

    k4a: v4a
    k4b: v4b
  badSect: badVal
    skip: skip
# List 1
list1:
  - v1a
  - v1b
listx:# empty section
list2: # with comment
    -     v2a
    -   v2b

list3: # with comment
    -     v3a # added comment
# some comment and empty lines and lines with spacecs
  # comment

               \t
    -   v3b
    kComplex: #complex section will trigger early quitting
      with complex floating text
       complex1: 1
       complex2: 2
    - random item

list4: # with comment

    - v4a
    - v4b
  - badVal
    - skip
"""

        keys = []
        writer = io.StringIO() # in-memory stream output
        reader = io.StringIO(inp) # in-memory stream input

        # Process sections
        for i in range(1, 5):
            stri = str(i)
            section = "section" + stri
            mapping = config_helper.read_section(reader, section, keys)
            ret = config_helper.write_section(section, mapping, keys, writer)
            self.assertEqual(True, ret)

            # We expect certain keys and values to be there.
            self.assertEqual(2, len(mapping))
            self.assertEqual("v" + stri + "a", mapping.get("k" + stri + "a"))
            self.assertEqual("v" + stri + "b", mapping.get("k" + stri + "b"))

        # Process lists
        for i in range(1, 5):
            stri = str(i)
            section = "list" + stri
            items = config_helper.read_list(section, reader)
            ret = config_helper.write_list(section, items, writer)
            self.assertTrue(ret)

            # We expect certain list items to be there.
            self.assertEqual(2, len(items))
            self.assertEqual("v"+ stri +"a", items[0])
            self.assertEqual("v"+ stri +"b", items[1])

        # Creat new input from what was just written
        input2 = writer.getvalue()
        writer2 = io.StringIO()

        # Process sections a 2nd time - from the new input
        reader = io.StringIO(input2)

        for i in range(1, 5):
            section = "section" + str(i)
            mapping = config_helper.read_section(reader, section, keys)
            ret = config_helper.write_section(section, mapping, keys, writer2)
            self.assertTrue(ret)

        # Process lists a 2nd time - from the new input
        for i in range(1, 5):
            section = "list" + str(i)
            items = config_helper.read_list(section, reader)
            ret = config_helper.write_list(section, items, writer2)
            self.assertTrue(ret)

        output2 = writer2.getvalue()
        self.assertEqual(input2, output2)


text:
package com.zhimei.weixiaoyuan;

import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;

public class SecoMarketActivity extends Activity {
    private ImageView back;
    private ImageView backhome;
    private GridView gv;
    private ArrayList<HashMap<String, Object>> item_list;
    private  SimpleAdapter type_adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_seco_market);
        initData();

        initView();
    }
    void initData(){

        item_list=new ArrayList<HashMap<String, Object>>();
        HashMap<String, Object> map1 = new HashMap<String, Object>();
        map1.put("picture",R.mipmap.book);
        map1.put("name","书籍");
        item_list.add(map1);

        HashMap<String, Object> map2 = new HashMap<String, Object>();
        map2.put("picture",R.mipmap.shouji);
        map2.put("name","手机");
        item_list.add(map2);

        HashMap<String, Object> map3 = new HashMap<String, Object>();
        map3.put("picture",R.mipmap.bike);
        map3.put("name","校园代步");
        item_list.add(map3);

        HashMap<String, Object> map4 = new HashMap<String, Object>();
        map4.put("picture",R.mipmap.sports);
        map4.put("name","体育健身");
        item_list.add(map4);

        HashMap<String, Object> map5 = new HashMap<String, Object>();
        map5.put("picture",R.mipmap.compuer);
        map5.put("name","电脑");
        item_list.add(map5);

        HashMap<String, Object> map6 = new HashMap<String, Object>();
        map6.put("picture",R.mipmap.cloths);
        map6.put("name","衣服鞋帽");
        item_list.add(map6);

        HashMap<String, Object> map7 = new HashMap<String, Object>();
        map7.put("picture",R.mipmap.camara);
        map7.put("name","数码产品");
        item_list.add(map7);

        HashMap<String, Object> map8 = new HashMap<String, Object>();
        map8.put("picture",R.mipmap.others);
        map8.put("name","其他");
        item_list.add(map8);

        type_adapter = new SimpleAdapter(this,
                item_list,// 数据源
                R.layout.sec_item,// 显示布局
                new String[] { "picture", "name" },
                new int[] { R.id.sec_iv_item, R.id.sec_tv_item });

    }

    void initView(){
        gv=(GridView)findViewById(R.id.sec_gridview);
        back=(ImageView)findViewById(R.id.sec_back);
        backhome=(ImageView)findViewById(R.id.sec_index);

        gv.setAdapter(type_adapter);
        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(SecoMarketActivity.this,"根据不同item跳转到不同页面",Toast.LENGTH_SHORT).show();
            }
        });

        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        backhome.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
                Intent intent=new Intent(SecoMarketActivity.this,MainActivity.class);
                startActivity(intent);
            }
        });

    }

}


text:
#include "CmsConnectionStartStopTest.h"

#include <activemq/core/ActiveMQConnectionFactory.h>
#include <activemq/exceptions/ActiveMQException.h>

#include <decaf/lang/Runnable.h>
#include <decaf/lang/Pointer.h>
#include <decaf/lang/Integer.h>
#include <decaf/util/Random.h>
#include <decaf/util/concurrent/CopyOnWriteArrayList.h>
#include <decaf/util/concurrent/TimeUnit.h>
#include <decaf/util/concurrent/ThreadPoolExecutor.h>
#include <decaf/util/concurrent/LinkedBlockingQueue.h>

using namespace std;
using namespace cms;
using namespace activemq;
using namespace activemq::test;
using namespace activemq::core;
using namespace activemq::exceptions;

using namespace decaf;
using namespace decaf::util;
using namespace decaf::util::concurrent;
using namespace decaf::lang;

////////////////////////////////////////////////////////////////////////////////
CmsConnectionStartStopTest::CmsConnectionStartStopTest() :
    CMSTestFixture(), startedConnection(), stoppedConnection() {
}

////////////////////////////////////////////////////////////////////////////////
CmsConnectionStartStopTest::~CmsConnectionStartStopTest() {
}

////////////////////////////////////////////////////////////////////////////////
void CmsConnectionStartStopTest::setUp() {

    CMSTestFixture::setUp();

    Pointer<ActiveMQConnectionFactory> factory(new ActiveMQConnectionFactory(cmsProvider->getBrokerURL()));

    startedConnection.reset(factory->createConnection());
    startedConnection->start();
    stoppedConnection.reset(factory->createConnection());
}

////////////////////////////////////////////////////////////////////////////////
void CmsConnectionStartStopTest::tearDown() {

    startedConnection->close();
    stoppedConnection->close();

    startedConnection.reset(NULL);
    stoppedConnection.reset(NULL);

    CMSTestFixture::tearDown();
}

////////////////////////////////////////////////////////////////////////////////
void CmsConnectionStartStopTest::testStoppedConsumerHoldsMessagesTillStarted() {

    Pointer<Session> startedSession(startedConnection->createSession());
    Pointer<Session> stoppedSession(stoppedConnection->createSession());

    // Setup the consumers.
    Pointer<Topic> topic(startedSession->createTopic("test"));
    Pointer<MessageConsumer> startedConsumer(startedSession->createConsumer(topic.get()));
    Pointer<MessageConsumer> stoppedConsumer(stoppedSession->createConsumer(topic.get()));

    // Send the message.
    Pointer<MessageProducer> producer(startedSession->createProducer(topic.get()));
    Pointer<TextMessage> message(startedSession->createTextMessage("Hello"));
    producer->send(message.get());

    // Test the assertions.
    Pointer<Message> m(startedConsumer->receive(2000));
    CPPUNIT_ASSERT(m != NULL);

    m.reset(stoppedConsumer->receive(2000));
    CPPUNIT_ASSERT(m == NULL);

    stoppedConnection->start();
    m.reset(stoppedConsumer->receive(5000));
    CPPUNIT_ASSERT(m != NULL);

    startedSession->close();
    stoppedSession->close();
}

////////////////////////////////////////////////////////////////////////////////
void CmsConnectionStartStopTest::testMultipleConnectionStops() {

    testStoppedConsumerHoldsMessagesTillStarted();
    stoppedConnection->stop();
    testStoppedConsumerHoldsMessagesTillStarted();
    stoppedConnection->stop();
    testStoppedConsumerHoldsMessagesTillStarted();
}

////////////////////////////////////////////////////////////////////////////////
namespace {

    class CreateSessionRunnable : public Runnable {
    private:

        Connection* connection;
        Random rand;
        CopyOnWriteArrayList<std::string>* exceptions;

    private:

        CreateSessionRunnable(const CreateSessionRunnable&);
        CreateSessionRunnable& operator= (const CreateSessionRunnable&);

    public:

        CreateSessionRunnable(Connection* connection, CopyOnWriteArrayList<std::string>* exceptions) :
            Runnable(), connection(connection), rand(), exceptions(exceptions) {
        }

        virtual ~CreateSessionRunnable() {}

        virtual void run() {
            try {
                TimeUnit::MILLISECONDS.sleep(rand.nextInt(10));
                Pointer<Session>(connection->createSession());
            } catch (CMSException& e) {
                exceptions->add(e.getMessage());
            }
        }
    };

    class StartStopRunnable : public Runnable {
    private:

        Connection* connection;
        Random rand;
        CopyOnWriteArrayList<std::string>* exceptions;

    private:

        StartStopRunnable(const StartStopRunnable&);
        StartStopRunnable& operator= (const StartStopRunnable&);

    public:

        StartStopRunnable(Connection* connection, CopyOnWriteArrayList<std::string>* exceptions) :
            Runnable(), connection(connection), rand(), exceptions(exceptions) {
        }

        virtual ~StartStopRunnable() {}

        virtual void run() {
            try {
                TimeUnit::MILLISECONDS.sleep(rand.nextInt(10));
                connection->start();
                connection->stop();
            } catch (CMSException& e) {
                exceptions->add(e.getMessage());
            }

        }
    };

}

////////////////////////////////////////////////////////////////////////////////
void CmsConnectionStartStopTest::testConcurrentSessionCreateWithStart() {

    ThreadPoolExecutor executor(50, Integer::MAX_VALUE, 60LL, TimeUnit::SECONDS, new LinkedBlockingQueue<Runnable*>());

    CopyOnWriteArrayList<std::string> exceptions;
    Random rand;

    for (int i=0; i<2000; i++) {
        executor.execute(new CreateSessionRunnable(stoppedConnection.get(), &exceptions));
        executor.execute(new StartStopRunnable(stoppedConnection.get(), &exceptions));
    }

    executor.shutdown();
    CPPUNIT_ASSERT_MESSAGE("executor terminated", executor.awaitTermination(45, TimeUnit::SECONDS));
    CPPUNIT_ASSERT_MESSAGE("no exceptions: " + exceptions.toString(), exceptions.isEmpty());
}


text:
play2-birt
==========

Play2 BIRT Integration


text:
<?php
      $pagetype = 1;
      include '../html/html_head.html';
      if (isset($_GET['ed_id']) && is_numeric($_GET['ed_id']))
       {
         include '../php/event.php';
         $dateID = $_GET['ed_id'];
         $aEvent = findEventByDateID($dateID);
         if (!is_null($aEvent))
         {
            #if check for ownership if not admin
            if (!$_SESSION['user_admin'] && $_SESSION['user_id'] != $aEvent['us_id'])
            {
               header("Location: ../html/index.php");
               die();
            }
            else
            {
               include '../php/interests.php';
               $eventID = $aEvent['eh_id'];
               $title = $aEvent['eh_title'];
               $description = $aEvent['eh_description'];
               $address = $aEvent['eh_address'];
               $city = $aEvent['eh_city'];
               $dtStart = date_create($aEvent['ed_start']);
               $dtEnd = date_create($aEvent['ed_end']);
               $startDate = date_format($dtStart,"m/d/Y");
               $startTime = date_format($dtStart,"h:i");
               $startAP = date_format($dtStart,"A");
               $endDate = date_format($dtEnd,"m/d/Y");
               $endTime = date_format($dtEnd,"h:i");
               $endAP = date_format($dtEnd,"A");
               $imagefile = $aEvent['eh_image_name'];
               $tagIDs = $aEvent['tagIDs'];
               $tags = $aEvent['tags'];
               $Owner = $aEvent['us_id'];
               $referer = end(explode("/", $_SERVER['HTTP_REFERER']));
            }
         }
       }
       else
       {
         header("Location: ../html/manageevents.php");
         die();
       }
      ?>
      <title>Edit Event</title>

      <?php include 'header.html'; ?>

      <?php include 'nav_bar.html'; ?>

               <?php include "../html/flash_message.php"; ?>

               <fieldset>
      <legend>
         Edit Event:
      </legend>
      <form action="../php/update_event_script.php" method="post" onsubmit="return validateEditEvent(this);"  enctype="multipart/form-data" >

            <?php

            if ($_SESSION['user_admin'] && $referer == "manageevents.php")
            {
               echo "EventID:<input id='eventID' type='text' name='eventID' value=" . $eventID .
               " readonly style='background-color:#e0e0e0;border:1px solid grey;' />
";
               echo "DateID:<input id='dateID 'type='text' name='dateID' value=" . $dateID .
               " readonly style='background-color:#e0e0e0;border:1px solid grey;'/>
";
            }
            else
            {
               echo "<input type='hidden' name='eventID' value=" . $eventID . ">";
               echo "<input type='hidden' name='dateID' value=" . $dateID . ">";
            }
            ?>

            <input type="hidden" name="referer" value="<?php echo $referer;?>">
            Title*: <input type="text" id = "title" name = "title" value="<?php echo $title;?>"/>

            Description: <textarea id = "description" name = "description" cols="40" rows="5"><?php echo $description ?></textarea>

            Address*: <input type="text" id = "address" name = "address" value="<?php echo $address ?>"/>

            City*: <input type="text" id = "city" name = "city" value="<?php echo $city ?>"/>

            Start*: <input type="text" id = "eventstart" name = "eventstart"  value="<?php echo $startDate ?>"/>
            <input type="text" id = "eventstarttime" name = "eventstarttime" value="<?php echo $startTime ?>" />
            <select id="startampm" name="startampm"><option value="AM">AM</option><option value="PM" <?php echo ($startAP == 'PM')?'selected':''; ?>>PM</option></select>

            End*: <input type="text" id = "eventend" name = "eventend" value="<?php echo $endDate ?>"/>
            <input type="text" id = "eventendtime" name = "eventendtime" value="<?php echo $endTime ?>" />
            <select id="endampm" name="endampm"><option value="AM">AM</option><option value="PM" <?php echo ($endAP == 'PM')?'selected':''; ?>>PM</option></select>

            <input type="hidden" name="MAX_FILE_SIZE" value="50000">
            <?php

            echo "<input type='hidden' id='currentImage' name='currentImage' value=' " . $imagefile . "' />";
            if($imagefile != "")
            {
                echo "Current Image:" .
                "<input type='checkbox' name='deleteimage' id='deleteimage' value='true'>Delete Image
" .
                "Change Image:";

            }
            else
            {
               echo "Add Image:";
            }

            ?>

            <input name="userfile" type="file">Note: Image sizes are limited to 50kb

            Tags*:
            <select id="tag_select" onChange="tagPicked()">
               <?php
                  getInterestsOptions();
               ?>
            </select>
            <input type="text" id = "tags" name = "tags" value="<?php echo $tags ?>" readonly/>
            Clear
            <input type="hidden" id = "tagids" name = "tagids" value="<?php echo $tagIDs ?>"/>

            <?php

               if ($_SESSION['user_admin'] && $referer == "manageevents.php")
               {
                  echo "Owner*:<input id='userID' name='userID' type='text' value='" . $Owner ."'/>
";
               }
               else
               {
                  echo "<input id='userID' name='userID' type='hidden' value='" . $Owner ."'/>";
               }
            ?>
            <input type="submit">

      </form>
   </fieldset>

<?php include 'footer.html'; ?>


text:
---
uuid: a8cff422-53e9-4937-94b4-fef1b83b8c84
layout: post
title: >-
  Gulp and FTP: update a website "on the fly"
slug: gulp-and-ftp-update-a-website-on-the-fly
subtitle: null
date: 2015-10-25T18:47:00.000Z
updated: 2016-12-13T21:24:35.000Z
author: Luciano Mammino
author_slug: luciano-mammino
header_img: ./gulp-and-ftp-update-a-website-on-the-fly-1.png
fb_img: ./gulp-and-ftp-update-a-website-on-the-fly-fb.png
tw_img: ./gulp-and-ftp-update-a-website-on-the-fly-tw.png
status: published
language: en_US
meta_title: null
meta_description: null
tags:
  - gulp
  - javascript
  - ftp
  - server
---

In this post I will explain you how to use [Gulp](http://gulpjs.com/) to interact with the files on your server through FTP. You will learn how to watch the files you are editing on your local machine and automatically synchronize them with your server as they change and how to setup a task to launch an FTP deploy on demand.

## Premise

Few days ago I was assigned to take care of updating few sections on **a legacy website which development environment is currently accessible only through FTP**. So no local virtualized development environment, no Git, no automated deploy, only old-school "FTP live edit and test"!

I would have used an FTP desktop app to create a virtual drive to allow me to edit files easily and open the full project in Sublime, but I couldn't find any good one for the last version of OS X (El Capitan), so I decided to work out a simple solution by myself using Gulp.

If you ever had a similar situation or if you just want to have a simple and fast command line solution to edit a website you can access to only through FTP, keep reading, this post is for you!

**NOTE**: I just want to stress on the fact that this solution must not be considered a best practice for development and deploy, but only a useful trick in case you have to deal with a very basic setup, especially if you are not in control of the development and deployment environments.

## Installing Gulp

In case you don't know it, Gulp is a very popular build system written in Node.js. It uses streams, so it's quite efficient in dealing with data transformations and in managing streams of data from different sources.

![Gulp is a very popular stream-based build system written in Node.js](./gulp-is-the-streaming-web-build-system.png)

To be able to run the script we are going to write you need to have Node.js and Gulp installed in your machine. If you don't have Gulp already you can easily install it with NPM:

```bash
npm install -g gulp
```

## Preparing the project

You will need to have a copy of the full project on your local machine, so if you don't have it already you need to login to your server and download a copy of the source files. You can use any FTP software to do so, but if you are on a Mac there's a quick trick that allows you to avoid to install any additional software: you can simply open finder and press `⌘` + `k` to start the **connect to server** window and specify the FTP url of your project with the following syntax: `ftp://username:password@host:port/path`. This will allow you to see and copy all the files from your project and, in case you are wondering, this is a read-only access!

Once you copied all the files you have to initialize NPM on the copied project with:

```bash
npm init
```

Follow the on screen instructions and provide all the missing informations.

Then you need to install Gulp also as a local dependency:

```bash
npm install --save-dev gulp
```

Also we are going to use a couple of external libraries, so let's install them as well:

```bash
npm install --save-dev gulp-util vinyl-ftp
```

[gulp-util](https://www.npmjs.com/package/gulp-util) is a module that offers a series of utilities functions for gulp (we will mainly use the log related functions) and [vinyl-ftp](https://www.npmjs.com/package/vinyl-ftp) is an FTP library that allows you to access FTP files and folders as streams and it's a perfect match for Gulp.

Ok, now the last step before moving to some code is to initialize a new gulp project. To do so just run:

```bash
gulp init
```

It will create a new `gulpfile.js` file, let's finally jump to some code.

## The gulpfile

We are going to implement two different Gulp commands: `ftp-deploy` and `ftp-deploy-watch`. The first one allows us to deploy all the local changes to the server, the second one instead activates a live watch that constantly monitors our files and uploads immediately any change to the files, very useful when you want to live-code against a development server.

To enable these two commands you need to copy paste the following code inside your `gulpfile.js` file.

```javascript
'use strict'

var gulp = require('gulp')
var gutil = require('gulp-util')
var ftp = require('vinyl-ftp')

/** Configuration **/
var user = process.env.FTP_USER
var password = process.env.FTP_PWD
var host = 'your hostname or ip address'
var port = 21
var localFilesGlob = ['./**/*']
var remoteFolder = '/myApp'

// helper function to build an FTP connection based on our configuration
function getFtpConnection() {
  return ftp.create({
    host: host,
    port: port,
    user: user,
    password: password,
    parallel: 5,
    log: gutil.log,
  })
}

/**
 * Deploy task.
 * Copies the new files to the server
 *
 * Usage: `FTP_USER=someuser FTP_PWD=somepwd gulp ftp-deploy`
 */
gulp.task('ftp-deploy', function() {
  var conn = getFtpConnection()

  return gulp
    .src(localFilesGlob, { base: '.', buffer: false })
    .pipe(conn.newer(remoteFolder)) // only upload newer files
    .pipe(conn.dest(remoteFolder))
})

/**
 * Watch deploy task.
 * Watches the local copy for changes and copies the new files to the server whenever an update is detected
 *
 * Usage: `FTP_USER=someuser FTP_PWD=somepwd gulp ftp-deploy-watch`
 */
gulp.task('ftp-deploy-watch', function() {
  var conn = getFtpConnection()

  gulp.watch(localFilesGlob).on('change', function(event) {
    console.log(
      'Changes detected! Uploading file "' + event.path + '", ' + event.type
    )

    return gulp
      .src([event.path], { base: '.', buffer: false })
      .pipe(conn.newer(remoteFolder)) // only upload newer files
      .pipe(conn.dest(remoteFolder))
  })
})
```

The Gulp script is very simple and pretty self-descriptive, but let's try to have a look at it in greater detail.

After importing our modules, we have a series of configuration variables. The ones you have to set are `host`, `port`, `localFilesGlob` and `remoteFolder`.

- `host` is the hostname or the IP address of your FTP server (e.g. `myserver.com` or `123.124.125.126`)
- `port` is the port where your FTP server is listening (generally it's the default: `21`)
- `localFilesGlob` is an array containing one or more [glob](https://www.npmjs.com/package/glob) expressions. These expressions are used to determine which files from your local copy should be watched and deployed into the server. The default option is very "open", it will copy all the files in your project folder. Most of the time it's better to be more specific so, be sure to build your own custom array of glob to avoid copying unnecessary or sensible data.
- `remoteFolder` is the folder in your remote server that contains the whole project (where the new files will be copied).

As you probably noticed we also have the `username` and `password` variables mapped to an environment variable. Is generally a good idea to not write passwords in configuration files, especially if you are going to publish this file somewhere. With this approach we can also share the same gulpfile with other people in the team and allow everyone to use their personal credentials.

After the configuration variables block we have the `getFtpConnection` function. This function is used as an helper to build an FTP connection using the previously specified options. You can also add some [additional options](https://www.npmjs.com/package/vinyl-ftp#ftp-create-config), for instance `parallel` allows you to define the maximum number of files to upload in parallel.

At the end we have our two real Gulp commands: `ftp-deploy` and `ftp-deploy-watch`.

They simply defines a stream starting from the glob expressions and pipe it to the destination server through the FTP connection. The only difference between the two commands is that in the `ftp-deploy` we read all the files from the glob expressions and send them through the connection, in the second case we watch the files and send only the one that changes while command is running.

It's also worth noticing that we are piping the files through the function `conn.newer`. This function ensures that only the files that are different from the server gets overwritten.

## Running the commands

To run the commands you must first specify the `FTP_USER` and `FTP_PWD` environment variables. For example you can do it this way:

```bash
FTP_USER=someuser FTP_PWD=somepwd gulp ftp-deploy
```

or

```bash
FTP_USER=someuser FTP_PWD=somepwd gulp ftp-deploy-watch
```

Or if you prefer you can export the variables in your `.bashrc` or `.bash_profile` files (in this case I suggest you to rename the variables into something more specific to avoid collisions).

## Conclusions

This approach allowed me to solve the problem easily and quickly having a mechanism that is quite fast to use and easy to maintain.

I am also more and more impressed about how easy is to have simple but effective solutions up and running with Node.js and the tools in its ecosystem. I am also impressed by the versatility of Gulp and how its stream-based approach makes things very concise and uniform.

I hope this article was useful and interesting for you.
I'd really love to receive **your opinions in the comments box** about it and, in case you are a veteran Gulp user, I'm curious to know **what was the most interesting command you have ever written using Gulp**.

Until next time!

Regards


text:
class Testssl < Formula
  desc "Tool which checks for the support of TLS/SSL ciphers and flaws"
  homepage "https://testssl.sh/"
  url "https://github.com/drwetter/testssl.sh/archive/3.0.5.tar.gz"
  sha256 "9de744fe0e51a03d42fa85e4b83340948baeaa7080427f90b0efd23e9106fece"
  license "GPL-2.0"
  head "https://github.com/drwetter/testssl.sh.git", branch: "3.1dev"

  bottle :unneeded

  depends_on "openssl@1.1"

  def install
    bin.install "testssl.sh"
    man1.install "doc/testssl.1"
    prefix.install "etc"
    env = {
      PATH:                "#{Formula["openssl@1.1"].opt_bin}:$PATH",
      TESTSSL_INSTALL_DIR: prefix,
    }
    bin.env_script_all_files(libexec/"bin", env)
  end

  test do
    system "#{bin}/testssl.sh", "--local", "--warnings", "off"
  end
end


text:
const DefaultRoles = require('../data/json/role');

exports.seed = (knex) => {
  const rolePromiseArray = [];
  DefaultRoles.forEach((role) => {
    rolePromiseArray.push(
      knex.transaction((trx) => {
        knex('role').transacting(trx).insert(role)
        .then(trx.commit)
        .catch(
          (err) => {
            trx.rollback();
            console.error(err);
            process.exit(1);
          }
        );
      })
    );
  });

  return Promise.all(rolePromiseArray);
};


text:
//=============================================================================
// EscapeDungeon.js
//=============================================================================

/*:
 * @plugindesc Escape to the specified position from a dungeon.
 * @author Sasuke KANNAZUKI
 *
 * @param mapIdVal
 * @desc variable id for escape map ID.
 * Escape is disabled when variable number mapIdVal equals 0.
 * @default 21
 *
 * @param xCoordVal
 * @desc variable id for escape x coordinate.
 * @default 22
 *
 * @param yCoordVal
 * @desc variable id for escape y coordinate.
 * @default 23
 *
 * @help This plugin does not provide plugin commands.
 *
 * - Set the position variables when player enters the dungeon.
 * - Be sure to disable when player exits from the dungeon,
 *  especially when the player moves to other map by an event.
 *   (to disable this, let variables number mapIdVal be 0).
 * - After escape exection, escape is automatically disabled
 *
 * check points:
 * - this plugin only for menu scene, cannot apply at battle scene.
 * - the scope must be 0(none).
 *
 * Item/Skill Note:
 * <ESCAPE> : the item/skill is for escape.
 */
/*:ja
 * @plugindesc ダンジョンから特定の場所にエスケープ
 * @author 神無月サスケ
 *
 * @param mapIdVal
 * @desc 脱出するマップのIDを格納するゲーム変数番号
 * この値が 0 の時は、エスケープは出来ません。
 * @default 21
 *
 * @param xCoordVal
 * @desc 脱出するマップのX座標用の変数を格納するゲーム変数番号
 * @default 22
 *
 * @param yCoordVal
 * @desc 脱出するマップのY座標用の変数を格納するゲーム変数番号
 * @default 23
 *
 * @help このプラグインにプラグインコマンドはありません。
 *
 * - プレイヤーがダンジョンに入る際に変数を設定してください。
 * - ダンジョンから出る時は、忘れずにエスケープ禁止にしてください。
 *  特にダンジョンからイベントで別の場所に行く場合は忘れずに。
 *   (mapIdVal の変数を 0 にしてください)。
 * - エスケープした後、自動的にエスケープ不可になります。
 *
 * チェックポイント:
 * - このプラグインはメニュー専用です。戦闘時は使用できません。
 * - 「範囲」は「なし」にしてください。
 *
 * アイテムや魔法のメモに以下を書くとエスケープとみなされます:
 * <ESCAPE>
 */

(function() {
  var parameters = PluginManager.parameters('EscapeDungeon');
  var mapIdVal = Number(parameters['mapIdVal'] || 21);
  var xCoordVal = Number(parameters['xCoordVal'] || 22);
  var yCoordVal = Number(parameters['yCoordVal'] || 23);
  var reEscape = /<ESCAPE>/i;

  //
  // use escape item
  //
  var _Scene_ItemBase_useItem = Scene_ItemBase.prototype.useItem;
  Scene_ItemBase.prototype.useItem = function() {
    _Scene_ItemBase_useItem.call(this);
    if(reEscape.exec(this.item().note) != null){
      this.useEscapeItem();
    }
  };

  Scene_ItemBase.prototype.useEscapeItem = function() {
    var mapId = $gameVariables.value(mapIdVal);
    var x = $gameVariables.value(xCoordVal);
    var y = $gameVariables.value(yCoordVal);
    $gamePlayer.reserveTransfer(mapId, x, y, 2, 0);
    SceneManager.goto(Scene_Map);
    $gameVariables.setValue(mapIdVal, 0);  // disable escape
  };

  //
  // check whether one can escape or not
  //
  var _Game_BattlerBase_meetsUsableItemConditions =
   Game_BattlerBase.prototype.meetsUsableItemConditions;
  Game_BattlerBase.prototype.meetsUsableItemConditions = function(item) {
    if (reEscape.exec(item.note) != null &&
     $gameVariables.value(mapIdVal) == 0) {
      return false;
    }
    return _Game_BattlerBase_meetsUsableItemConditions.call(this, item);
  };
})();


text:
function [xc, xm] = center(x)
%CENTER	  Centers data by subtraction of the mean.
%
%    [XC, XM] = CENTER(X) centers the data in X by subtraction of the
%    mean XM. If X contains NaNs, indicating missing values, the mean
%    of X is computed from the available data.
%
%    See also NANMEAN, MEAN.

  %narginchk(1,1)          % check number of input arguments
  if ndims(x) > 2,  error('X must be vector or 2-D array.'); end

  % if x is a vector, make sure it is a row vector
  if length(x)==numel(x)
    x   = x(:);
  end
  m     = size(x, 1);

  % get mean of x
  if any(any(isnan(x)))               % there are missing values in x
    xm  = nanmean(x);
  else                                % no missing values
    xm  = mean(x);
  end

  % remove mean
  xc    = x - repmat(xm, m, 1);