text:
package heroku

import (
	"fmt"
	"log"

	"github.com/cyberdelia/heroku-go/v3"
	"github.com/hashicorp/go-multierror"
	"github.com/hashicorp/terraform/helper/schema"
)

// herokuApplication is a value type used to hold the details of an
// application. We use this for common storage of values needed for the
// heroku.App and heroku.OrganizationApp types
type herokuApplication struct {
	Name             string
	Region           string
	Stack            string
	GitURL           string
	WebURL           string
	OrganizationName string
	Locked           bool
}

// type application is used to store all the details of a heroku app
type application struct {
	Id string // Id of the resource

	App          *herokuApplication // The heroku application
	Client       *heroku.Service    // Client to interact with the heroku API
	Vars         map[string]string  // The vars on the application
	Organization bool               // is the application organization app
}

// Updates the application to have the latest from remote
func (a *application) Update() error {
	var errs []error
	var err error

	if !a.Organization {
		app, err := a.Client.AppInfo(a.Id)
		if err != nil {
			errs = append(errs, err)
		} else {
			a.App = &herokuApplication{}
			a.App.Name = app.Name
			a.App.Region = app.Region.Name
			a.App.Stack = app.Stack.Name
			a.App.GitURL = app.GitURL
			a.App.WebURL = app.WebURL
		}
	} else {
		app, err := a.Client.OrganizationAppInfo(a.Id)
		if err != nil {
			errs = append(errs, err)
		} else {
			// No inheritance between OrganizationApp and App is killing it :/
			a.App = &herokuApplication{}
			a.App.Name = app.Name
			a.App.Region = app.Region.Name
			a.App.Stack = app.Stack.Name
			a.App.GitURL = app.GitURL
			a.App.WebURL = app.WebURL
			if app.Organization != nil {
				a.App.OrganizationName = app.Organization.Name
			} else {
				log.Println("[DEBUG] Something is wrong - didn't get information about organization name, while the app is marked as being so")
			}
			a.App.Locked = app.Locked
		}
	}

	a.Vars, err = retrieveConfigVars(a.Id, a.Client)
	if err != nil {
		errs = append(errs, err)
	}

	if len(errs) > 0 {
		return &multierror.Error{Errors: errs}
	}

	return nil
}

func resourceHerokuApp() *schema.Resource {
	return &schema.Resource{
		Create: switchHerokuAppCreate,
		Read:   resourceHerokuAppRead,
		Update: resourceHerokuAppUpdate,
		Delete: resourceHerokuAppDelete,

		Schema: map[string]*schema.Schema{
			"name": &schema.Schema{
				Type:     schema.TypeString,
				Required: true,
			},

			"region": &schema.Schema{
				Type:     schema.TypeString,
				Required: true,
				ForceNew: true,
			},

			"stack": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
				Computed: true,
				ForceNew: true,
			},

			"config_vars": &schema.Schema{
				Type:     schema.TypeList,
				Optional: true,
				Elem: &schema.Schema{
					Type: schema.TypeMap,
				},
			},

			"all_config_vars": &schema.Schema{
				Type:     schema.TypeMap,
				Computed: true,
			},

			"git_url": &schema.Schema{
				Type:     schema.TypeString,
				Computed: true,
			},

			"web_url": &schema.Schema{
				Type:     schema.TypeString,
				Computed: true,
			},

			"heroku_hostname": &schema.Schema{
				Type:     schema.TypeString,
				Computed: true,
			},

			"organization": &schema.Schema{
				Type:     schema.TypeList,
				Optional: true,
				ForceNew: true,
				Elem: &schema.Resource{
					Schema: map[string]*schema.Schema{
						"name": &schema.Schema{
							Type:     schema.TypeString,
							Required: true,
						},

						"locked": &schema.Schema{
							Type:     schema.TypeBool,
							Optional: true,
						},

						"personal": &schema.Schema{
							Type:     schema.TypeBool,
							Optional: true,
						},
					},
				},
			},
		},
	}
}

func isOrganizationApp(d *schema.ResourceData) bool {
	v := d.Get("organization").([]interface{})
	return len(v) > 0 && v[0] != nil
}

func switchHerokuAppCreate(d *schema.ResourceData, meta interface{}) error {
	if isOrganizationApp(d) {
		return resourceHerokuOrgAppCreate(d, meta)
	}

	return resourceHerokuAppCreate(d, meta)
}

func resourceHerokuAppCreate(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*heroku.Service)

	// Build up our creation options
	opts := heroku.AppCreateOpts{}

	if v, ok := d.GetOk("name"); ok {
		vs := v.(string)
		log.Printf("[DEBUG] App name: %s", vs)
		opts.Name = &vs
	}
	if v, ok := d.GetOk("region"); ok {
		vs := v.(string)
		log.Printf("[DEBUG] App region: %s", vs)
		opts.Region = &vs
	}
	if v, ok := d.GetOk("stack"); ok {
		vs := v.(string)
		log.Printf("[DEBUG] App stack: %s", vs)
		opts.Stack = &vs
	}

	log.Printf("[DEBUG] Creating Heroku app...")
	a, err := client.AppCreate(opts)
	if err != nil {
		return err
	}

	d.SetId(a.Name)
	log.Printf("[INFO] App ID: %s", d.Id())

	if v, ok := d.GetOk("config_vars"); ok {
		err = updateConfigVars(d.Id(), client, nil, v.([]interface{}))
		if err != nil {
			return err
		}
	}

	return resourceHerokuAppRead(d, meta)
}

func resourceHerokuOrgAppCreate(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*heroku.Service)
	// Build up our creation options
	opts := heroku.OrganizationAppCreateOpts{}

	v := d.Get("organization").([]interface{})
	if len(v) > 1 {
		return fmt.Errorf("Error Creating Heroku App: Only 1 Heroku Organization is permitted")
	}
	orgDetails := v[0].(map[string]interface{})

	if v := orgDetails["name"]; v != nil {
		vs := v.(string)
		log.Printf("[DEBUG] Organization name: %s", vs)
		opts.Organization = &vs
	}

	if v := orgDetails["personal"]; v != nil {
		vs := v.(bool)
		log.Printf("[DEBUG] Organization Personal: %t", vs)
		opts.Personal = &vs
	}

	if v := orgDetails["locked"]; v != nil {
		vs := v.(bool)
		log.Printf("[DEBUG] Organization locked: %t", vs)
		opts.Locked = &vs
	}

	if v := d.Get("name"); v != nil {
		vs := v.(string)
		log.Printf("[DEBUG] App name: %s", vs)
		opts.Name = &vs
	}
	if v, ok := d.GetOk("region"); ok {
		vs := v.(string)
		log.Printf("[DEBUG] App region: %s", vs)
		opts.Region = &vs
	}
	if v, ok := d.GetOk("stack"); ok {
		vs := v.(string)
		log.Printf("[DEBUG] App stack: %s", vs)
		opts.Stack = &vs
	}

	log.Printf("[DEBUG] Creating Heroku app...")
	a, err := client.OrganizationAppCreate(opts)
	if err != nil {
		return err
	}

	d.SetId(a.Name)
	log.Printf("[INFO] App ID: %s", d.Id())

	if v, ok := d.GetOk("config_vars"); ok {
		err = updateConfigVars(d.Id(), client, nil, v.([]interface{}))
		if err != nil {
			return err
		}
	}

	return resourceHerokuAppRead(d, meta)
}

func resourceHerokuAppRead(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*heroku.Service)

	configVars := make(map[string]string)
	care := make(map[string]struct{})
	for _, v := range d.Get("config_vars").([]interface{}) {
		for k, _ := range v.(map[string]interface{}) {
			care[k] = struct{}{}
		}
	}

	organizationApp := isOrganizationApp(d)

	// Only set the config_vars that we have set in the configuration.
	// The "all_config_vars" field has all of them.
	app, err := resourceHerokuAppRetrieve(d.Id(), organizationApp, client)
	if err != nil {
		return err
	}

	for k, v := range app.Vars {
		if _, ok := care[k]; ok {
			configVars[k] = v
		}
	}
	var configVarsValue []map[string]string
	if len(configVars) > 0 {
		configVarsValue = []map[string]string{configVars}
	}

	d.Set("name", app.App.Name)
	d.Set("stack", app.App.Stack)
	d.Set("region", app.App.Region)
	d.Set("git_url", app.App.GitURL)
	d.Set("web_url", app.App.WebURL)
	d.Set("config_vars", configVarsValue)
	d.Set("all_config_vars", app.Vars)
	if organizationApp {
		orgDetails := map[string]interface{}{
			"name":     app.App.OrganizationName,
			"locked":   app.App.Locked,
			"personal": false,
		}
		err := d.Set("organization", []interface{}{orgDetails})
		if err != nil {
			return err
		}
	}

	// We know that the hostname on heroku will be the name+herokuapp.com
	// You need this to do things like create DNS CNAME records
	d.Set("heroku_hostname", fmt.Sprintf("%s.herokuapp.com", app.App.Name))

	return nil
}

func resourceHerokuAppUpdate(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*heroku.Service)

	// If name changed, update it
	if d.HasChange("name") {
		v := d.Get("name").(string)
		opts := heroku.AppUpdateOpts{
			Name: &v,
		}

		renamedApp, err := client.AppUpdate(d.Id(), opts)
		if err != nil {
			return err
		}

		// Store the new ID
		d.SetId(renamedApp.Name)
	}

	// If the config vars changed, then recalculate those
	if d.HasChange("config_vars") {
		o, n := d.GetChange("config_vars")
		if o == nil {
			o = []interface{}{}
		}
		if n == nil {
			n = []interface{}{}
		}

		err := updateConfigVars(
			d.Id(), client, o.([]interface{}), n.([]interface{}))
		if err != nil {
			return err
		}
	}

	return resourceHerokuAppRead(d, meta)
}

func resourceHerokuAppDelete(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*heroku.Service)

	log.Printf("[INFO] Deleting App: %s", d.Id())
	err := client.AppDelete(d.Id())
	if err != nil {
		return fmt.Errorf("Error deleting App: %s", err)
	}

	d.SetId("")
	return nil
}

func resourceHerokuAppRetrieve(id string, organization bool, client *heroku.Service) (*application, error) {
	app := application{Id: id, Client: client, Organization: organization}

	err := app.Update()

	if err != nil {
		return nil, fmt.Errorf("Error retrieving app: %s", err)
	}

	return &app, nil
}

func retrieveConfigVars(id string, client *heroku.Service) (map[string]string, error) {
	vars, err := client.ConfigVarInfo(id)

	if err != nil {
		return nil, err
	}

	return vars, nil
}

// Updates the config vars for from an expanded configuration.
func updateConfigVars(
	id string,
	client *heroku.Service,
	o []interface{},
	n []interface{}) error {
	vars := make(map[string]*string)

	for _, v := range o {
		if v != nil {
			for k, _ := range v.(map[string]interface{}) {
				vars[k] = nil
			}
		}
	}
	for _, v := range n {
		if v != nil {
			for k, v := range v.(map[string]interface{}) {
				val := v.(string)
				vars[k] = &val
			}
		}
	}

	log.Printf("[INFO] Updating config vars: *%#v", vars)
	if _, err := client.ConfigVarUpdate(id, vars); err != nil {
		return fmt.Errorf("Error updating config vars: %s", err)
	}

	return nil
}


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace LyncBillingUI.Pages.SiteAdministration {

    public partial class ExclusionsList {

        /// <summary>
        /// ManageExceptionsListGrid control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::Ext.Net.GridPanel ManageExceptionsListGrid;

        /// <summary>
        /// ManageExceptionsListStore control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::Ext.Net.Store ManageExceptionsListStore;

        /// <summary>
        /// ManageExceptionsListStoreModel control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::Ext.Net.Model ManageExceptionsListStoreModel;

        /// <summary>
        /// ManageDepartments_RowEditing control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::Ext.Net.RowEditing ManageDepartments_RowEditing;

        /// <summary>
        /// EntityColumn control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::Ext.Net.Column EntityColumn;

        /// <summary>
        /// Editor_Entity_TextField control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::Ext.Net.TextField Editor_Entity_TextField;

        /// <summary>
        /// EntityTypeColumn control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::Ext.Net.Column EntityTypeColumn;

        /// <summary>
        /// Editor_EntityType_Combobox control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::Ext.Net.ComboBox Editor_EntityType_Combobox;

        /// <summary>
        /// ZeroCostColumn control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::Ext.Net.Column ZeroCostColumn;

        /// <summary>
        /// Editor_ZeroCost_Combobox control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::Ext.Net.ComboBox Editor_ZeroCost_Combobox;

        /// <summary>
        /// AutoMarkColumn control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::Ext.Net.Column AutoMarkColumn;

        /// <summary>
        /// Editor_AutoMark_Combobox control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::Ext.Net.ComboBox Editor_AutoMark_Combobox;

        /// <summary>
        /// DescriptionColumn control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::Ext.Net.Column DescriptionColumn;

        /// <summary>
        /// Editor_Description_TextField control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::Ext.Net.TextField Editor_Description_TextField;

        /// <summary>
        /// RejectChange control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::Ext.Net.CommandColumn RejectChange;

        /// <summary>
        /// DeleteButtonsColumn control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::Ext.Net.ImageCommandColumn DeleteButtonsColumn;

        /// <summary>
        /// FilterDelegatesExceptionsToolBar control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::Ext.Net.Toolbar FilterDelegatesExceptionsToolBar;

        /// <summary>
        /// FilterExceptionsBySite control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::Ext.Net.ComboBox FilterExceptionsBySite;

        /// <summary>
        /// FilterExceptionsBySiteStore control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::Ext.Net.Store FilterExceptionsBySiteStore;

        /// <summary>
        /// SiteModel control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::Ext.Net.Model SiteModel;

        /// <summary>
        /// AddExceptionButton control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::Ext.Net.Button AddExceptionButton;

        /// <summary>
        /// ToolbarSeparaator control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::Ext.Net.ToolbarSeparator ToolbarSeparaator;

        /// <summary>
        /// SaveChangesButton control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::Ext.Net.Button SaveChangesButton;

        /// <summary>
        /// ManageExceptionsListPagingToolbar control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::Ext.Net.PagingToolbar ManageExceptionsListPagingToolbar;

        /// <summary>
        /// AddNewExceptionWindowPanel control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::Ext.Net.Window AddNewExceptionWindowPanel;

        /// <summary>
        /// NewException_ExceptionEntity control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::Ext.Net.TextField NewException_ExceptionEntity;

        /// <summary>
        /// NewException_ExceptionType control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::Ext.Net.ComboBox NewException_ExceptionType;

        /// <summary>
        /// NewException_ZeroCost control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::Ext.Net.ComboBox NewException_ZeroCost;

        /// <summary>
        /// NewException_AutoMark control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::Ext.Net.ComboBox NewException_AutoMark;

        /// <summary>
        /// NewException_SitesList control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::Ext.Net.ComboBox NewException_SitesList;

        /// <summary>
        /// NewException_SitesListStore control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::Ext.Net.Store NewException_SitesListStore;

        /// <summary>
        /// NewException_SitesListStoreModel control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::Ext.Net.Model NewException_SitesListStoreModel;

        /// <summary>
        /// NewException_Description control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::Ext.Net.TextField NewException_Description;

        /// <summary>
        /// NewExceptionWindowBottomBar control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::Ext.Net.StatusBar NewExceptionWindowBottomBar;

        /// <summary>
        /// AddNewExceptionButton control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::Ext.Net.Button AddNewExceptionButton;

        /// <summary>
        /// CancelNewExceptionButton control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::Ext.Net.Button CancelNewExceptionButton;

        /// <summary>
        /// NewExceptionWindow_BottomBarSeparator control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::Ext.Net.ToolbarSeparator NewExceptionWindow_BottomBarSeparator;

        /// <summary>
        /// NewException_StatusMessage control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::Ext.Net.ToolbarTextItem NewException_StatusMessage;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.shevart.google_map.util;

import android.app.Activity;
import android.content.Intent;
import android.support.annotation.NonNull;

import com.shevart.google_map.ui.screens.select_last_place.SelectPlaceFromHistoryActivity;

@SuppressWarnings("WeakerAccess")
public class Launcher {
    public static final int SELECT_START_TRIP_POINT_FROM_HISTORY_CODE = 1;
    public static final int SELECT_END_TRIP_POINT_FROM_HISTORY_CODE = 2;

    public static class ActivityComponents {
        public static void startTripPointSelectFromHistory(@NonNull Activity activity) {
            Intent intent = new Intent(activity, SelectPlaceFromHistoryActivity.class);
            activity.startActivityForResult(intent, SELECT_START_TRIP_POINT_FROM_HISTORY_CODE);
        }

        public static void endTripPointSelectFromHistory(@NonNull Activity activity) {
            Intent intent = new Intent(activity, SelectPlaceFromHistoryActivity.class);
            activity.startActivityForResult(intent, SELECT_END_TRIP_POINT_FROM_HISTORY_CODE);
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Hendersonia tunetana A.L. Guyot

### Remarks
null


text:
/**
 * @file
 *   This file includes definitions for a time ticker.
 */

#ifndef TIME_TICKER_HPP_
#define TIME_TICKER_HPP_

#include "openthread-core-config.h"

#include <limits.h>

#include "common/locator.hpp"
#include "common/non_copyable.hpp"
#include "common/time.hpp"
#include "common/timer.hpp"

namespace ot {

/**
 * This class represents a time ticker.
 *
 * The time ticker emits periodic ticks (with 1 second period interval) to a set of registered tick receiver modules.
 * The tick receivers (OpenThread objects) are identified by the `Receiver` enumeration. The receiver objects
 * must provide `HandleTimeTick()` method which would be invoked by `TimeTicker` periodically.
 *
 */
class TimeTicker : public InstanceLocator, private NonCopyable
{
public:
    /**
     * This enumeration represents time tick receivers.
     *
     * This enumeration contains the list of all OpenThread modules that can be registered as time tick receivers.
     *
     */
    enum Receiver : uint8_t
    {
        kMeshForwarder,          ///< `MeshForwarder`
        kMleRouter,              ///< `Mle::MleRouter`
        kAddressResolver,        ///< `AddressResolver`
        kChildSupervisor,        ///< `Utils::ChildSupervisor`
        kIp6FragmentReassembler, ///< `Ip6::Ip6` (handling of fragmented messages)
        kDuaManager,             ///< `DuaManager`
        kMlrManager,             ///< `MlrManager`
        kNetworkDataNotifier,    ///< `NetworkData::Notifier`

        kNumReceivers, ///< Number of receivers.
    };

    /**
     * This constructor initializes the `TimeTicker` instance.
     *
     */
    explicit TimeTicker(Instance &aInstance);

    /**
     * This method registers a receiver with `TimeTicker` to receive periodic ticks.
     *
     * @param[in] aReceiver   A tick receiver identifier.
     *
     */
    void RegisterReceiver(Receiver aReceiver);

    /**
     * This method unregisters a receiver with `TimeTicker` to receive periodic ticks.
     *
     * @param[in] aReceiver   A tick receiver identifier.
     *
     */
    void UnregisterReceiver(Receiver aReceiver);

    /**
     * This method indicates whether a receiver is registered with `TimeTicker` to receive periodic ticks.
     *
     * @param[in] aReceiver   A tick receiver identifier.
     *
     * @retval TRUE   If @p aReceiver is registered with `TimeTicker`.
     * @retval FALSE  If @p aReceiver is not registered with `TimeTicker`.
     *
     */
    bool IsReceiverRegistered(Receiver aReceiver) const { return (mReceivers & Mask(aReceiver)) != 0; }

private:
    static constexpr uint32_t kTickInterval  = Time::kOneSecondInMsec;
    static constexpr uint32_t kRestartJitter = 4; // in msec, jitter added when restarting the timer [-4,+4] ms.

    constexpr static uint32_t Mask(Receiver aReceiver) { return static_cast<uint32_t>(1U) << aReceiver; }

    void HandleTimer(void);

    using TickerTimer = TimerMilliIn<TimeTicker, &TimeTicker::HandleTimer>;

    uint32_t    mReceivers;
    TickerTimer mTimer;

    static_assert(kNumReceivers < sizeof(mReceivers) * CHAR_BIT, "Too many `Receiver`s - does not fit in a bit mask");
};

} // namespace ot

#endif // TIMER_HPP_


text:
set -euo pipefail
IFS=$'\n\t'
[ "${VERBOSE:-}" != true ]|| set -x

# PVC mount and folder variables, removing any trailing slashes (%/)
#
DEST_MNT=${DEST_MNT:-/backup}
DEST_MNT=${DEST_MNT%/}
#
DEST_DIR=${DEST_MNT}/documents
TMP_BK=${NEW_BK:-${DEST_DIR}/bk-tmp}
NEW_BK=${NEW_BK:-${DEST_DIR}/bk}

du -hd 1 ${DEST_MNT}

# Check if NFS repository is initialized.  If not, initialize it.
# RESTIC_PASSWORD is required.
if ! restic -r /mnt/dest/gwells-documents snapshots > /dev/null 2>&1; then
    restic -r /mnt/dest/gwells-documents init ; fi

# Backup files using delta (de-duplicate) and encryption
restic --cache-dir ${DEST_DIR}/.cache -r /mnt/dest/gwells-documents backup ${NEW_BK}

# Clean up old snapshots.
# As an example, the following arguments:
# --keep-daily 7 --keep-weekly 5 --keep-monthly 12 --keep-yearly 2
# will keep the most recent 7 daily snapshots, 5 weekly, 12 monthly, and 2 yearly snapshots.
# The rest will be pruned.
restic -r /mnt/dest/gwells-documents forget --keep-daily 7 --keep-weekly 5 --keep-monthly 12 --keep-yearly 10 --prune

# check repository integrity before exiting
restic -r /mnt/dest/gwells-documents check


text:
''' Define the Transformer model '''
import torch
import torch.nn as nn
import numpy as np
from transformer.Layers import EncoderLayer, DecoderLayer

__author__ = "Yu-Hsiang Huang"

def get_pad_mask(seq, pad_idx):
    return (seq != pad_idx).unsqueeze(-2)

def get_subsequent_mask(seq):
    ''' For masking out the subsequent info. '''
    sz_b, len_s = seq.size()
    subsequent_mask = (1 - torch.triu(
        torch.ones((1, len_s, len_s), device=seq.device), diagonal=1)).bool()
    return subsequent_mask

class PositionalEncoding(nn.Module):

    def __init__(self, d_hid, n_position=200):
        super(PositionalEncoding, self).__init__()

        # Not a parameter
        self.register_buffer('pos_table', self._get_sinusoid_encoding_table(n_position, d_hid))

    def _get_sinusoid_encoding_table(self, n_position, d_hid):
        ''' Sinusoid position encoding table '''
        # TODO: make it with torch instead of numpy

        def get_position_angle_vec(position):
            return [position / np.power(10000, 2 * (hid_j // 2) / d_hid) for hid_j in range(d_hid)]

        sinusoid_table = np.array([get_position_angle_vec(pos_i) for pos_i in range(n_position)])
        sinusoid_table[:, 0::2] = np.sin(sinusoid_table[:, 0::2])  # dim 2i
        sinusoid_table[:, 1::2] = np.cos(sinusoid_table[:, 1::2])  # dim 2i+1

        return torch.FloatTensor(sinusoid_table).unsqueeze(0)

    def forward(self, x):
        return x + self.pos_table[:, :x.size(1)].clone().detach()

class Encoder(nn.Module):
    ''' A encoder model with self attention mechanism. '''

    def __init__(
            self, n_src_vocab, d_word_vec, n_layers, n_head, d_k, d_v,
            d_model, d_inner, pad_idx, dropout=0.1, n_position=200, scale_emb=False):

        super().__init__()

        self.src_word_emb = nn.Embedding(n_src_vocab, d_word_vec, padding_idx=pad_idx)
        self.position_enc = PositionalEncoding(d_word_vec, n_position=n_position)
        self.dropout = nn.Dropout(p=dropout)
        self.layer_stack = nn.ModuleList([
            EncoderLayer(d_model, d_inner, n_head, d_k, d_v, dropout=dropout)
            for _ in range(n_layers)])
        self.layer_norm = nn.LayerNorm(d_model, eps=1e-6)
        self.scale_emb = scale_emb
        self.d_model = d_model

    def forward(self, src_seq, src_mask, return_attns=False):

        enc_slf_attn_list = []

        # -- Forward
        enc_output = self.src_word_emb(src_seq)
        if self.scale_emb:
            enc_output *= self.d_model ** 0.5
        enc_output = self.dropout(self.position_enc(enc_output))
        enc_output = self.layer_norm(enc_output)

        for enc_layer in self.layer_stack:
            enc_output, enc_slf_attn = enc_layer(enc_output, slf_attn_mask=src_mask)
            enc_slf_attn_list += [enc_slf_attn] if return_attns else []

        if return_attns:
            return enc_output, enc_slf_attn_list
        return enc_output,

class Decoder(nn.Module):
    ''' A decoder model with self attention mechanism. '''

    def __init__(
            self, n_trg_vocab, d_word_vec, n_layers, n_head, d_k, d_v,
            d_model, d_inner, pad_idx, n_position=200, dropout=0.1, scale_emb=False):

        super().__init__()

        self.trg_word_emb = nn.Embedding(n_trg_vocab, d_word_vec, padding_idx=pad_idx)
        self.position_enc = PositionalEncoding(d_word_vec, n_position=n_position)
        self.dropout = nn.Dropout(p=dropout)
        self.layer_stack = nn.ModuleList([
            DecoderLayer(d_model, d_inner, n_head, d_k, d_v, dropout=dropout)
            for _ in range(n_layers)])
        self.layer_norm = nn.LayerNorm(d_model, eps=1e-6)
        self.scale_emb = scale_emb
        self.d_model = d_model

    def forward(self, trg_seq, trg_mask, enc_output, src_mask, return_attns=False):

        dec_slf_attn_list, dec_enc_attn_list = [], []

        # -- Forward
        dec_output = self.trg_word_emb(trg_seq)
        if self.scale_emb:
            dec_output *= self.d_model ** 0.5
        dec_output = self.dropout(self.position_enc(dec_output))
        dec_output = self.layer_norm(dec_output)

        for dec_layer in self.layer_stack:
            dec_output, dec_slf_attn, dec_enc_attn = dec_layer(
                dec_output, enc_output, slf_attn_mask=trg_mask, dec_enc_attn_mask=src_mask)
            dec_slf_attn_list += [dec_slf_attn] if return_attns else []
            dec_enc_attn_list += [dec_enc_attn] if return_attns else []

        if return_attns:
            return dec_output, dec_slf_attn_list, dec_enc_attn_list
        return dec_output,

class Transformer(nn.Module):
    ''' A sequence to sequence model with attention mechanism. '''

    def __init__(
            self, n_src_vocab, n_trg_vocab, src_pad_idx, trg_pad_idx,
            d_word_vec=512, d_model=512, d_inner=2048,
            n_layers=6, n_head=8, d_k=64, d_v=64, dropout=0.1, n_position=200,
            trg_emb_prj_weight_sharing=True, emb_src_trg_weight_sharing=True,
            scale_emb_or_prj='prj'):

        super().__init__()

        self.src_pad_idx, self.trg_pad_idx = src_pad_idx, trg_pad_idx

        # In section 3.4 of paper "Attention Is All You Need", there is such detail:
        # "In our model, we share the same weight matrix between the two
        # embedding layers and the pre-softmax linear transformation...
        # In the embedding layers, we multiply those weights by \sqrt{d_model}".
        #
        # Options here:
        #   'emb': multiply \sqrt{d_model} to embedding output
        #   'prj': multiply (\sqrt{d_model} ^ -1) to linear projection output
        #   'none': no multiplication

        assert scale_emb_or_prj in ['emb', 'prj', 'none']
        scale_emb = (scale_emb_or_prj == 'emb') if trg_emb_prj_weight_sharing else False
        self.scale_prj = (scale_emb_or_prj == 'prj') if trg_emb_prj_weight_sharing else False
        self.d_model = d_model

        self.encoder = Encoder(
            n_src_vocab=n_src_vocab, n_position=n_position,
            d_word_vec=d_word_vec, d_model=d_model, d_inner=d_inner,
            n_layers=n_layers, n_head=n_head, d_k=d_k, d_v=d_v,
            pad_idx=src_pad_idx, dropout=dropout, scale_emb=scale_emb)

        self.decoder = Decoder(
            n_trg_vocab=n_trg_vocab, n_position=n_position,
            d_word_vec=d_word_vec, d_model=d_model, d_inner=d_inner,
            n_layers=n_layers, n_head=n_head, d_k=d_k, d_v=d_v,
            pad_idx=trg_pad_idx, dropout=dropout, scale_emb=scale_emb)

        self.trg_word_prj = nn.Linear(d_model, n_trg_vocab, bias=False)

        for p in self.parameters():
            if p.dim() > 1:
                nn.init.xavier_uniform_(p)

        assert d_model == d_word_vec, \
        'To facilitate the residual connections, \
         the dimensions of all module outputs shall be the same.'

        if trg_emb_prj_weight_sharing:
            # Share the weight between target word embedding & last dense layer
            self.trg_word_prj.weight = self.decoder.trg_word_emb.weight

        if emb_src_trg_weight_sharing:
            self.encoder.src_word_emb.weight = self.decoder.trg_word_emb.weight

    def forward(self, src_seq, trg_seq):

        src_mask = get_pad_mask(src_seq, self.src_pad_idx)
        trg_mask = get_pad_mask(trg_seq, self.trg_pad_idx) & get_subsequent_mask(trg_seq)

        enc_output, *_ = self.encoder(src_seq, src_mask)
        dec_output, *_ = self.decoder(trg_seq, trg_mask, enc_output, src_mask)
        seq_logit = self.trg_word_prj(dec_output)
        if self.scale_prj:
            seq_logit *= self.d_model ** -0.5

        return seq_logit.view(-1, seq_logit.size(2))


text:
{%extends resModule + ":baseChartOptionsDialogBody.html"%}
{%block staticFigure%}
{%endblock%}
{%block customFormFields%}

	Mapbox Access Token:
	<input type="text" class="form-control" id="mapboxtoken{{prefix}}" name="mapboxtoken" value="{{this.options.get("mapboxtoken") or "pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4M29iazA2Z2gycXA4N2pmbDZmangifQ.-g_vE53SD2WrJ6tFX7QHmA"}}">

{%endblock%}


text:
Test if socket_set_option() works, option:SO_SEOLINGER
--DESCRIPTION--
-wrong params
-set/get params comparison
-l_linger not given
--SKIPIF--
<?php
if (!extension_loaded('sockets')) {
        die('SKIP sockets extension not available.');
}
?>
--FILE--
<?php
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

if (!$socket) {
        die('Unable to create AF_INET socket [socket]');
}
// wrong params
$retval_1 = socket_set_option( $socket, SOL_SOCKET, SO_LINGER, array());

// set/get comparison
$options = array("l_onoff" => 1, "l_linger" => 1);
$retval_2 = socket_set_option( $socket, SOL_SOCKET, SO_LINGER, $options);
$retval_3 = socket_get_option( $socket, SOL_SOCKET, SO_LINGER);

//l_linger not given
$options_2 = array("l_onoff" => 1);
var_dump(socket_set_option( $socket, SOL_SOCKET, SO_LINGER, $options_2));

var_dump($retval_2);
var_dump($retval_3["l_linger"] === $options["l_linger"]);
// value of l_onoff is not always 1, Darwin returns 128
var_dump((bool)$retval_3["l_onoff"] === (bool)$options["l_onoff"]);

socket_close($socket);
?>

--EXPECTF--
Warning: socket_set_option(): no key "l_onoff" passed in optval in %s on line %d

Warning: socket_set_option(): no key "l_linger" passed in optval in %s on line %d
bool(false)
bool(true)
bool(true)
bool(true)
--CREDITS--
Moritz Neuhaeuser, info@xcompile.net
PHP Testfest Berlin 2009-05-10


text:
<?php

class Metadataextractor_ExtractorComponent extends AppComponent
{
  /** extract metadata */
  public function extract($revision)
    {
    $modelLoader = new MIDAS_ModelLoader;
    $itemRevisionModel = $modelLoader->loadModel("ItemRevision");
    $revision = $itemRevisionModel->load($revision['itemrevision_id']);
    $bitstreams = $revision->getBitstreams();
    if(count($bitstreams) != 1)
      {
      return;
      }
    $bitstream = $bitstreams[0];
    $ext = strtolower(substr(strrchr($bitstream->getName(), '.'), 1));

    $MetadataModel = $modelLoader->loadModel("Metadata");
    if($ext == 'pdf')
      {
      $pdf = Zend_Pdf::load($bitstream->getFullPath());
      foreach($pdf->properties as $name => $property)
        {
        $name = strtolower($name);
        try
          {
          $metadataDao = $MetadataModel->getMetadata(MIDAS_METADATA_GLOBAL, 'misc', $name);
          if(!$metadataDao)
            {
            $MetadataModel->addMetadata(MIDAS_METADATA_GLOBAL, 'misc', $name, '');
            }
          $MetadataModel->addMetadataValue($revision, MIDAS_METADATA_GLOBAL,
                       'misc', $name, $property);
          }
        catch (Zend_Exception $exc)
          {
          echo $exc->getMessage();
          }
        }
      }
    else
      {
      $modulesConfig=Zend_Registry::get('configsModules');
      $command = $modulesConfig['metadataextractor']->hachoir;
      exec(str_replace("'", '"',$command).' "'.$bitstream->getFullPath().'"', $output);

      if(!isset($output[0]) || $output[0] != "Metadata:")
        {
        return;
        }
      unset($output[0]);
      foreach($output as $out)
        {
        $out = substr($out, 2);
        $pos = strpos($out, ": ");
        $name = strtolower(substr($out, 0, $pos));
        $value = substr($out, $pos + 2);
        try
          {
          $metadataDao = $MetadataModel->getMetadata(MIDAS_METADATA_GLOBAL, 'misc', $name);
          if(!$metadataDao)
            {
            $MetadataModel->addMetadata(MIDAS_METADATA_GLOBAL, 'misc', $name, '');
            }
          $MetadataModel->addMetadataValue($revision, MIDAS_METADATA_GLOBAL,
               'misc', $name, $value);
          }
        catch (Zend_Exception $exc)
          {
          echo $exc->getMessage();
          }
        }
      }
    return;
    }

} // end class
?>


text:
const gulp = require('gulp');
const sourcemaps = require('gulp-sourcemaps');
const templateCache = require('gulp-angular-templatecache');
const concat = require('gulp-concat');
const addStream = require('add-stream');
const less = require('gulp-less');
const uglify = require('gulp-uglify');
const uglifycss = require('gulp-uglifycss');
const clean = require('gulp-clean');
const rollup = require('gulp-rollup');
const rollupBabel = require("rollup-plugin-babel");
const ngAnnotate = require('gulp-ng-annotate');

const cleanTask = () =>
  gulp.src('build/*', {
    read: false
  })
  .pipe(clean());

const lessTask = () =>
  gulp.src('src/cron-gen.less')
  .pipe(less())
  .pipe(uglifycss())
  .pipe(concat('cron-gen.min.css'))
  .pipe(gulp.dest('build'));

const srcTask = () =>
  gulp.src('src/**/*.js')
  .pipe(sourcemaps.init())
  .pipe(rollup({
    output: {
      format: 'iife'
    },
    plugins: [
      rollupBabel()
    ],
    input: 'src/cron-gen.module.js'
  }))
  .pipe(ngAnnotate())
  .pipe(addStream.obj(() => gulp.src('src/templates/*.html')
    .pipe(templateCache({
      root: 'angular-cron-gen',
      module: 'angular-cron-gen'
    }))))
  .pipe(gulp.dest('build'))
  .pipe(concat('cron-gen.min.js'))
  .pipe(uglify())
  .pipe(sourcemaps.write('.'))
  .pipe(gulp.dest('build'));

const build = gulp.series(cleanTask, srcTask, lessTask);

export default build;


text:
package characteristic

const TypePairingPairings = "50"

type PairingPairings struct {
	*Bytes
}

func NewPairingPairings() *PairingPairings {
	char := NewBytes(TypePairingPairings)
	char.Format = FormatTLV8
	char.Perms = []string{PermRead, PermWrite}

	char.SetValue([]byte{})

	return &PairingPairings{char}
}


text:
package com.mcac0006.services.siftscience;

import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;

import net.minidev.json.JSONArray;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.junit.Assert;
import org.junit.Test;

import com.jayway.jsonpath.JsonPath;
import com.mcac0006.siftscience.SiftScienceHelper;
import com.mcac0006.siftscience.event.domain.CreateAccount;
import com.mcac0006.siftscience.event.domain.UpdateAccount;
import com.mcac0006.siftscience.types.Address;
import com.mcac0006.siftscience.types.PaymentMethod;
import com.mcac0006.siftscience.types.PaymentType;
import com.mcac0006.siftscience.types.SocialSignOnType;

import static com.mcac0006.services.siftscience.AssertJsonKeys.assertEquals;

public class CreateaAndUpdateAccountBodyTest {

	@Test
	@SuppressWarnings("unchecked")
	public void createAccountTest() throws JsonGenerationException, JsonMappingException, IOException {

		final PaymentMethod pm = new PaymentMethod();
		pm.setPaymentType(PaymentType.CREDIT_CARD).setCardBIN("542486").setCardLast4("4444");

		final Address billingAddress = new Address();
		billingAddress.setName("Bill Jones").setAddressLine1("2100 Main Street").setAddressLine2("Apt 3B").setCity("New London").setRegion("New Hampshire").setCountry("US").setZipCode("03257");

		final CreateAccount create_account = new CreateAccount();
		create_account.setApiKey("INSERT_API_KEY_HERE");
		create_account.setUserId("billy_jones_301").setSessionId("gigtleqddo84l8cm15qe4il3q3").setUserEmail("bill@gmail.com").setName("Bill Jones").setPhone("1-415-555-6040").setReferrerUserId("janejane101").setSocialSignOnType(SocialSignOnType.TWITTER).setPaymentMethods(new PaymentMethod[]{ pm }).setBillingAddress(billingAddress);

		/*
		 * Assert.
		 */

		final String json = SiftScienceHelper.serialize(create_account); // the json object we will be asserting

		final Object read = JsonPath.read(json, "$");
		final LinkedHashMap<String, Object> $ =(LinkedHashMap<String, Object>)read;

		// assert first level
		final List<String> $expectedKeys = Arrays.asList("$type", "$api_key", "$user_id", "$session_id", "$user_email", "$name", "$phone", "$referrer_user_id", "$payment_methods", "$billing_address", "$social_sign_on_type");
		assertEquals($.keySet(), $expectedKeys);

		// then assert the values
		Assert.assertEquals("INSERT_API_KEY_HERE", $.get("$api_key"));
		Assert.assertEquals("$create_account", $.get("$type"));
		Assert.assertEquals("billy_jones_301", $.get("$user_id"));
		Assert.assertEquals("gigtleqddo84l8cm15qe4il3q3", $.get("$session_id"));

		Assert.assertEquals("bill@gmail.com", $.get("$user_email"));
		Assert.assertEquals("Bill Jones", $.get("$name"));
		Assert.assertEquals("1-415-555-6040", $.get("$phone"));
		Assert.assertEquals("janejane101", $.get("$referrer_user_id"));
		Assert.assertEquals("$twitter", $.get("$social_sign_on_type"));

		// then assert the child keys and values
		final JSONArray pmjarray =(JSONArray)JsonPath.read(json, "$.$payment_methods");
		Assert.assertEquals(1, pmjarray.size());
		LinkedHashMap<String, Object> pmj = (LinkedHashMap<String, Object>)pmjarray.get(0);
		final List<String> pmexpectedKeys = Arrays.asList("$payment_type", "$card_bin", "$card_last4");
		assertEquals(pmj.keySet(), pmexpectedKeys);
		Assert.assertEquals("$credit_card", pmj.get("$payment_type"));
		Assert.assertEquals("542486", pmj.get("$card_bin"));
		Assert.assertEquals("4444", pmj.get("$card_last4"));

		final LinkedHashMap<String, Object> ba =(LinkedHashMap<String, Object>)JsonPath.read(json, "$.$billing_address");
		final List<String> baexpectedKeys = Arrays.asList("$name", "$address_1", "$address_2", "$city", "$region", "$country", "$zipcode");
		assertEquals(ba.keySet(), baexpectedKeys);
		Assert.assertEquals("Bill Jones", ba.get("$name"));
		Assert.assertEquals("2100 Main Street", ba.get("$address_1"));
		Assert.assertEquals("Apt 3B", ba.get("$address_2"));
		Assert.assertEquals("New London", ba.get("$city"));
		Assert.assertEquals("New Hampshire", ba.get("$region"));
		Assert.assertEquals("US", ba.get("$country"));
		Assert.assertEquals("03257", ba.get("$zipcode"));
	}

	@Test
	@SuppressWarnings("unchecked")
	public void updateAccountTest() throws JsonGenerationException, JsonMappingException, IOException {

		final PaymentMethod paymentMethod = new PaymentMethod();
		paymentMethod.setPaymentType(PaymentType.CREDIT_CARD).setCardBIN("542486").setCardLast4("4444");

		final Address billingAddress = new Address();
		billingAddress.setPhone("1-415-555-6041").setAddressLine1("2100 Main Street").setAddressLine2("Apt 3B").setCity("New London").setRegion("New Hampshire").setCountry("US").setZipCode("03257");

		final UpdateAccount update_account = new UpdateAccount();
		update_account.setApiKey("INSERT_API_KEY_HERE");
		update_account.setUserId("billy_jones_301").setChangedPassword(true).setUserEmail("bill@gmail.com").setName("Bill Jones").setPhone("1-415-555-6040").setReferrerUserId("janejane102").setPaymentMethods(new PaymentMethod[]{paymentMethod}).setBillingAddress(billingAddress).setSocialSignOnType(SocialSignOnType.TWITTER);

		/*
		 * Assert.
		 */

		final String json = SiftScienceHelper.serialize(update_account); // the json object we will be asserting

		final Object read = JsonPath.read(json, "$");
		final LinkedHashMap<String, Object> $ =(LinkedHashMap<String, Object>)read;

		// assert first level
		final List<String> $expectedKeys = Arrays.asList("$type", "$api_key", "$user_id", "$changed_password", "$user_email", "$name", "$phone", "$referrer_user_id", "$payment_methods", "$billing_address", "$social_sign_on_type");
		assertEquals($.keySet(), $expectedKeys);

		// then assert the values
		Assert.assertEquals("INSERT_API_KEY_HERE", $.get("$api_key"));
		Assert.assertEquals("$update_account", $.get("$type"));
		Assert.assertEquals("billy_jones_301", $.get("$user_id"));

		Assert.assertEquals("bill@gmail.com", $.get("$user_email"));
		Assert.assertEquals("Bill Jones", $.get("$name"));
		Assert.assertEquals("1-415-555-6040", $.get("$phone"));
		Assert.assertEquals("janejane102", $.get("$referrer_user_id"));
		Assert.assertEquals("$twitter", $.get("$social_sign_on_type"));

		// then assert the child keys and values
		final JSONArray pmjarray =(JSONArray)JsonPath.read(json, "$.$payment_methods");
		Assert.assertEquals(1, pmjarray.size());
		LinkedHashMap<String, Object> pmj = (LinkedHashMap<String, Object>)pmjarray.get(0);
		final List<String> pmexpectedKeys = Arrays.asList("$payment_type", "$card_bin", "$card_last4");
		assertEquals(pmj.keySet(), pmexpectedKeys);
		Assert.assertEquals("$credit_card", pmj.get("$payment_type"));
		Assert.assertEquals("542486", pmj.get("$card_bin"));
		Assert.assertEquals("4444", pmj.get("$card_last4"));

		final LinkedHashMap<String, Object> ba =(LinkedHashMap<String, Object>)JsonPath.read(json, "$.$billing_address");
		final List<String> baexpectedKeys = Arrays.asList("$phone", "$address_1", "$address_2", "$city", "$region", "$country", "$zipcode");
		assertEquals(ba.keySet(), baexpectedKeys);
		Assert.assertEquals("1-415-555-6041", ba.get("$phone"));
		Assert.assertEquals("2100 Main Street", ba.get("$address_1"));
		Assert.assertEquals("Apt 3B", ba.get("$address_2"));
		Assert.assertEquals("New London", ba.get("$city"));
		Assert.assertEquals("New Hampshire", ba.get("$region"));
		Assert.assertEquals("US", ba.get("$country"));
		Assert.assertEquals("03257", ba.get("$zipcode"));
	}
}


text:
using namespace fl::metis;
using fl::tests::TestPath;
using fl::fs::Directory;

BOOST_AUTO_TEST_SUITE( metis )

BOOST_AUTO_TEST_CASE (testLevelRangeCreation)
{
	try
	{
		TestConfig config;
		Manager manager(config.config());
		BOOST_REQUIRE(manager.loadAll());

		ItemHeader item;
		item.level = 1;
		item.subLevel = 1;
		item.itemKey = 1;

		BOOST_REQUIRE(manager.addLevel(item.level, item.subLevel));

		TRangePtr range;
		bool wasAdded;
		auto storages = manager.clusterManager().storages();
		for (auto s = storages.begin(); s != storages.end(); s++)
		{
			StoragePingAnswer storageAnswer;
			storageAnswer.serverID = (*s)->id();
			static const size_t DEFAULT_RANGE_SIZE = 320000;
			storageAnswer.leftSpace = config.config()->averageItemSize() * DEFAULT_RANGE_SIZE * 2;
			(*s)->ping(storageAnswer);
		}
		BOOST_REQUIRE(manager.fillAndAdd(item, range, wasAdded));
		BOOST_REQUIRE(range->rangeID() == 1);
		BOOST_REQUIRE(range->rangeIndex() == 0);
		BOOST_REQUIRE(wasAdded);

		item.itemKey = 2000000;
		BOOST_REQUIRE(manager.fillAndAdd(item, range, wasAdded));
		BOOST_REQUIRE(range->rangeID() == 2);
		BOOST_REQUIRE(range->rangeIndex() == 15);
		BOOST_REQUIRE(wasAdded);

		item.rangeID = 0;
		BOOST_REQUIRE(manager.index().find(ItemLevelIndex(item), range));
		BOOST_REQUIRE(2 == range->rangeID());

		Manager manager2(config.config());
	} catch (...) {
		BOOST_CHECK_NO_THROW(throw);
	}
}

BOOST_AUTO_TEST_CASE (testParseURLToItem)
{
	try
	{
		TestConfig config;
		Manager manager(config.config());
		BOOST_REQUIRE(manager.loadAll());

		ItemLevelIndex item;
		TCrc urlCrc;
		BOOST_CHECK(manager.index().parseURL("", "/1/2/", item, urlCrc));
		BOOST_CHECK((item.level == 1) && (item.subLevel == 2));

		BOOST_CHECK(manager.index().parseURL("", "/1/2/3", item, urlCrc));
		BOOST_CHECK((item.level == 1) && (item.subLevel == 2) && (item.itemKey == 3));

	} catch (...) {
		BOOST_CHECK_NO_THROW(throw);
	}
}

BOOST_AUTO_TEST_SUITE_END()


text:
CREATE TABLE TYPETEST (
  TYPE2 CHAR(10 CHAR),
  TYPE4 DATE,
  TYPE6 NCHAR(10),
  TYPE8 NUMBER(10,2),
  TYPE9 NVARCHAR2(10),
  TYPE10 TIMESTAMP,
  TYPE11 VARCHAR2(10 CHAR),
  TYPE12 FLOAT(8)
);
COMMENT ON table TYPETEST is 'タイプテスト';
COMMENT ON column TYPETEST.TYPE2 is 'TYPE2';
COMMENT ON column TYPETEST.TYPE4 is 'TYPE4';
COMMENT ON column TYPETEST.TYPE6 is 'TYPE6';
COMMENT ON column TYPETEST.TYPE8 is 'TYPE8';
COMMENT ON column TYPETEST.TYPE9 is 'TYPE9';
COMMENT ON column TYPETEST.TYPE10 is 'TYPE10';
COMMENT ON column TYPETEST.TYPE11 is 'TYPE11';
COMMENT ON column TYPETEST.TYPE12 is 'TYPE12';


text:
title   : "Back to the Mac"
author  : "Klinkenberg"
date    : '2020-07-24'
tags    : ["mac", "switch"]
math    : false
summary : "I caved, there was no love."

image:
  caption : "MacBook Pro"
  placement : 3
---

Remember that time [I switched to windows](http://www.klinkenberg.amsterdam/post/switched/)? Well, after less than half a year, I already caved. Though I really tried to make this relationship work, in the end, there was just no love. Within a month of purchasing the DELL XPS 13, I already had significant regret. Not for Mac craving but because a new XPS was announced. An even slicker smaller better one than the one I just got. So, initially, it was not windows that made me restless. I even invested heavily in learning the superuser tricks. Installing linux subsystem for windows, getting to know a bunch of shortcuts, and diving deep into system thingies to customize the heck out of the XPS. Setting up incremental backups and system restore points, the whole shebang.

All the while, having that beautiful 4K touch screen to stare at. But wait, that screen is sucking the battery dry in no time. I ended up with a DELL powerbank because the ones I owned could not output 90 Watts.

And then came the updates. The OCD in me wants to have an up to date system. So, I installed the first update, and the second, and they kept coming. Not just the windows updates, but also an insane amount of DELL command center updates. It just would not stop.

![MacBook Pro](/media/back_to_mac_2.png)

That's when I started to play around with Linux. Trying out different distros, but I always ran into one or the other problem. I was searching for solutions to problems I didn't have on the Mac.

And then, out of nowhere, came the salvation. Apple updated its MacBook Pro lineup. Bringing the 13-inch model back on spec with no keyboard issues anymore. So here I am, back in my walled garden, writing this blog on a Mac again.


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>net.thecamaras</groupId>
    <artifactId>flickr-download-server</artifactId>
    <version>0.1.0</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.1.RELEASE</version>
    </parent>

    <properties>
        <java.version>1.8</java.version>
        <flickr.version>2.15</flickr.version>
        <swagger.version>2.4.0</swagger.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.hsqldb</groupId>
            <artifactId>hsqldb</artifactId>
        </dependency>
        <dependency>
            <groupId>com.flickr4java</groupId>
            <artifactId>flickr4java</artifactId>
            <version>${flickr.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>springloaded</artifactId>
            <version>1.2.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.4</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>${swagger.version}</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>${swagger.version}</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>


text:
require 'spec_helper'

RSpec.describe Ci::PipelineSchedule do
  subject { build(:ci_pipeline_schedule) }

  it { is_expected.to belong_to(:project) }
  it { is_expected.to belong_to(:owner) }

  it { is_expected.to have_many(:pipelines) }
  it { is_expected.to have_many(:variables) }

  it { is_expected.to respond_to(:ref) }
  it { is_expected.to respond_to(:cron) }
  it { is_expected.to respond_to(:cron_timezone) }
  it { is_expected.to respond_to(:description) }
  it { is_expected.to respond_to(:next_run_at) }

  it_behaves_like 'includes Limitable concern' do
    subject { build(:ci_pipeline_schedule) }
  end

  describe 'validations' do
    it 'does not allow invalid cron patterns' do
      pipeline_schedule = build(:ci_pipeline_schedule, cron: '0 0 0 * *')

      expect(pipeline_schedule).not_to be_valid
    end

    it 'does not allow invalid cron patterns' do
      pipeline_schedule = build(:ci_pipeline_schedule, cron_timezone: 'invalid')

      expect(pipeline_schedule).not_to be_valid
    end

    context 'when active is false' do
      it 'does not allow nullified ref' do
        pipeline_schedule = build(:ci_pipeline_schedule, :inactive, ref: nil)

        expect(pipeline_schedule).not_to be_valid
      end
    end

    context 'when cron contains trailing whitespaces' do
      it 'strips the attribute' do
        pipeline_schedule = build(:ci_pipeline_schedule, cron: ' 0 0 * * *   ')

        expect(pipeline_schedule).to be_valid
        expect(pipeline_schedule.cron).to eq('0 0 * * *')
      end
    end
  end

  describe '.runnable_schedules' do
    subject { described_class.runnable_schedules }

    let!(:pipeline_schedule) do
      Timecop.freeze(1.day.ago) do
        create(:ci_pipeline_schedule, :hourly)
      end
    end

    it 'returns the runnable schedule' do
      is_expected.to eq([pipeline_schedule])
    end

    context 'when there are no runnable schedules' do
      let!(:pipeline_schedule) { }

      it 'returns an empty array' do
        is_expected.to be_empty
      end
    end
  end

  describe '.preloaded' do
    subject { described_class.preloaded }

    before do
      create_list(:ci_pipeline_schedule, 3)
    end

    it 'preloads the associations' do
      subject

      query = ActiveRecord::QueryRecorder.new { subject.map(&:project).each(&:route) }

      expect(query.count).to eq(3)
    end
  end

  describe '#set_next_run_at' do
    let(:pipeline_schedule) { create(:ci_pipeline_schedule, :nightly) }
    let(:ideal_next_run_at) { pipeline_schedule.send(:ideal_next_run_from, Time.zone.now) }
    let(:cron_worker_next_run_at) { pipeline_schedule.send(:cron_worker_next_run_from, Time.zone.now) }

    context 'when PipelineScheduleWorker runs at a specific interval' do
      before do
        allow(Settings).to receive(:cron_jobs) do
          {
            'pipeline_schedule_worker' => {
              'cron' => '0 1 2 3 *'
            }
          }
        end
      end

      it "updates next_run_at to the sidekiq worker's execution time" do
        expect(pipeline_schedule.next_run_at.min).to eq(0)
        expect(pipeline_schedule.next_run_at.hour).to eq(1)
        expect(pipeline_schedule.next_run_at.day).to eq(2)
        expect(pipeline_schedule.next_run_at.month).to eq(3)
      end
    end

    context 'when pipeline schedule runs every minute' do
      let(:pipeline_schedule) { create(:ci_pipeline_schedule, :every_minute) }

      it "updates next_run_at to the sidekiq worker's execution time" do
        Timecop.freeze(Time.zone.parse("2019-06-01 12:18:00+0000")) do
          expect(pipeline_schedule.next_run_at).to eq(cron_worker_next_run_at)
        end
      end
    end

    context 'when there are two different pipeline schedules in different time zones' do
      let(:pipeline_schedule_1) { create(:ci_pipeline_schedule, :weekly, cron_timezone: 'Eastern Time (US & Canada)') }
      let(:pipeline_schedule_2) { create(:ci_pipeline_schedule, :weekly, cron_timezone: 'UTC') }

      it 'sets different next_run_at' do
        expect(pipeline_schedule_1.next_run_at).not_to eq(pipeline_schedule_2.next_run_at)
      end
    end

    context 'when there are two different pipeline schedules in the same time zones' do
      let(:pipeline_schedule_1) { create(:ci_pipeline_schedule, :weekly, cron_timezone: 'UTC') }
      let(:pipeline_schedule_2) { create(:ci_pipeline_schedule, :weekly, cron_timezone: 'UTC') }

      it 'sets the sames next_run_at' do
        expect(pipeline_schedule_1.next_run_at).to eq(pipeline_schedule_2.next_run_at)
      end
    end

    context 'when updates cron of exsisted pipeline schedule' do
      let(:new_cron) { '0 0 1 1 *' }

      it 'updates next_run_at automatically' do
        expect { pipeline_schedule.update!(cron: new_cron) }
          .to change { pipeline_schedule.next_run_at }
      end
    end
  end

  describe '#schedule_next_run!' do
    let!(:pipeline_schedule) { create(:ci_pipeline_schedule, :nightly) }

    before do
      pipeline_schedule.update_column(:next_run_at, nil)
    end

    it 'updates next_run_at' do
      expect { pipeline_schedule.schedule_next_run! }
        .to change { pipeline_schedule.next_run_at }
    end

    context 'when record is invalid' do
      before do
        allow(pipeline_schedule).to receive(:save!) { raise ActiveRecord::RecordInvalid.new(pipeline_schedule) }
      end

      it 'nullifies the next run at' do
        pipeline_schedule.schedule_next_run!

        expect(pipeline_schedule.next_run_at).to be_nil
      end
    end
  end

  describe '#job_variables' do
    let!(:pipeline_schedule) { create(:ci_pipeline_schedule) }

    let!(:pipeline_schedule_variables) do
      create_list(:ci_pipeline_schedule_variable, 2, pipeline_schedule: pipeline_schedule)
    end

    subject { pipeline_schedule.job_variables }

    before do
      pipeline_schedule.reload
    end

    it { is_expected.to contain_exactly(*pipeline_schedule_variables.map(&:to_runner_variable)) }
  end
end


text:
package org.sbml.extconverter;

import org.sbml.jsbml.Model;
import org.sbml.wrapper.ModelWrapper;

// TODO: Auto-generated Javadoc
/**
 * The Class MultiConverter.
 *
 * @author Kaito Ii
 *         Date Created: Aug 7, 2016
 */
// TODO convert complex species and included species from CellDesigner
// Annootation to SBML Multi package
public class MultiConverter extends EXTConverter {

  /**
   * Instantiates a new multi converter.
   *
   * @param model
   *        the model
   * @param mWrapper
   *        the m wrapper
   */
  public MultiConverter(Model model, ModelWrapper mWrapper) {
    super(model, mWrapper);
  }

  /**
   * Convert.
   */
  public void convert() {
  }
}


text:
class Ansiweather < Formula
  desc "Weather in your terminal, with ANSI colors and Unicode symbols"
  homepage "https://github.com/fcambus/ansiweather"
  url "https://github.com/fcambus/ansiweather/archive/1.17.0.tar.gz"
  sha256 "eabc5ad709e2a459d59402b190511b44542eafce293205a29fb2b73c3e075ee7"
  license "BSD-2-Clause"
  head "https://github.com/fcambus/ansiweather.git", branch: "master"

  bottle do
    sha256 cellar: :any_skip_relocation, all: "ef34ba57b350fcf65cfd5fbcab88c5209c75d225e2af9a8b9c48bffc99d01b37"
  end

  depends_on "jq"

  def install
    bin.install "ansiweather"
  end

  test do
    assert_match "Wind", shell_output("#{bin}/ansiweather")
  end
end


text:
package blog.bn;

import java.util.*;

import blog.model.BuiltInTypes;
import blog.model.DependencyModel;
import blog.model.Model;
import blog.model.OriginFunction;
import blog.model.POP;
import blog.model.Type;
import blog.model.DependencyModel.Distrib;
import blog.sample.EvalContext;
import blog.world.PartialWorld;

/**
 * A number random variable. It consists of a potential object pattern (POP) and
 * a tuple of generating objects. Its value in a given world is the number of
 * objects generated by that POP and those generating objects.
 */
public class NumberVar extends VarWithDistrib {
	/**
	 * Creates a new NumberVar for the given POP and given tuple of generating
	 * objects.
	 */
	public NumberVar(POP pop, List args) {
		super(args);
		this.pop = pop;
	}

	/**
	 * Creates a new NumberVar for the given POP and given tuple of generating
	 * objects.
	 */
	public NumberVar(POP pop, Object[] args) {
		super(args);
		this.pop = pop;
	}

	/**
	 * Creates a new NumberVar for the given POP and given tuple of generating
	 * objects. If stable is true, then the caller guarantees that
	 * the given args array will not be modified externally.
	 */
	public NumberVar(POP pop, Object[] args, boolean stable) {
		super(args, stable);
		this.pop = pop;
	}

	/**
	 * Returns the potential object pattern associated with this number variable.
	 */
	public final POP pop() {
		return pop;
	}

	public DependencyModel.Distrib getDistrib(EvalContext context) {
		context.pushEvaluee(this);
		DependencyModel.Distrib distrib = pop.getDepModel().getDistribWithBinding(
				context, pop.getGenObjVars(), args(), ZERO);
		context.popEvaluee();
		return distrib;
	}

	/**
	 * Returns the integer type.
	 */
	public Type getType() {
		return BuiltInTypes.NATURAL_NUM;
	}

	public int getOrderingIndex() {
		return pop.getDepModel().getCreationIndex();
	}

	public DependencyModel getDepModel() {
		return pop.getDepModel();
	}

	/**
	 * Returns the value that the given origin function yields on all objects that
	 * satisfy this number variable. This is either one of this variable's
	 * arguments or Model.NULL.
	 *
	 * @throws IllegalArgumentException
	 *           if the argument type of the given origin function is not the type
	 *           of objects that satisfy this variable
	 */
	public Object getOriginFuncValue(OriginFunction g) {
		if (g.getArgType() != pop.type()) {
			throw new IllegalArgumentException("Can't evaluate origin function " + g
					+ " on objects " + "of type " + pop.type());
		}

		int index = pop.getOriginFuncIndex(g);
		if (index == -1) {
			return Model.NULL;
		}
		return args[index];
	}

	/**
	 * Returns the number of objects generated by this POP on this tuple of
	 * generating objects in the given world.
	 */
	public int numGenerated(PartialWorld w) {
		return ((Integer) getValue(w)).intValue();
	}

	public Object clone() {
		return new NumberVar(pop, args);
	}

	/**
	 * Two NumberVar objects are equal if they have the same POP and their
	 * argument lists are equal (recall that list equality is checked by calling
	 * the equals method on each corresponding pair of objects in the
	 * two lists).
	 */
	public boolean equals(Object obj) {
		if (obj instanceof NumberVar) {
			NumberVar other = (NumberVar) obj;
			return ((pop == other.pop()) && Arrays.equals(args, other.args()));
		}
		return false;
	}

	public int hashCode() {
		int code = pop.hashCode();
		for (int i = 0; i < args.length; ++i) {
			code ^= args[i].hashCode();
		}
		return code;
	}

	/**
	 * Returns a string of the form #Type(f1 = o1, ..., fK = oK) where f1, ..., fK
	 * are the origin functions and o1, ..., oK are the generating objects.
	 */
	public String toString() {
		StringBuffer buf = new StringBuffer();
		buf.append("#");
		buf.append(pop.type());

		OriginFunction[] originFuncs = pop.originFuncs();
		if (originFuncs.length > 0) {
			buf.append("(");
			for (int i = 0; i < originFuncs.length; ++i) {
				buf.append(originFuncs[i]);
				buf.append(" = ");
				buf.append(args[i]);
				if (i + 1 < originFuncs.length) {
					buf.append(", ");
				}
			}
			buf.append(")");
		}

		return buf.toString();
	}

	private POP pop;

	private static final Integer ZERO = new Integer(0);
}


text:
layout: post
title:  Improve your Life THIS YEAR with these Simple Tips
redirect_from: /Goals-2017/
author: Lewis Gavin
comments: true
tags:
- self improvement
- health
---

![Getting the most out of this year](https://www.lewisgavin.co.uk/images/goalsthis year.jpg)

First things first, Happy new year! If you're anything like me, you've just enjoyed a nice break for the holidays and are ready to kill it this year.

After spending time reflecting on what I want out of this year, I came up with a list of priorities for the year and the actions I could take in order to fulfill them. The main goal is to focus on **Enjoyment, Minimalism and Reduction**

This post will outline my goals and plan for the year. I will be adding subsequent posts to then follow my progress throughout the year and share any tips and tricks I have found useful.

## Goals for this year

- Reduce and Minimise everything in my life.
- Live more, work less and get outdoors more often!
- See friends and family more frequently.
- Use my phone less to remove the distractions.
- Blog more about my lifestyle.
- Continue to enhance and configure my daily routine.

As you can see, all of these lead to a more enjoyable lifestyle with less being more!

After compiling this list I then wanted to look at what things I really enjoy doing. If I can understand what these activities are, and then look at the activities that I find burdens, I can then try remove the burdens in order to have more time to do the more enjoyable activities.

Here are the two, very simple lists.

### Things I enjoy doing

- Socialising
- Writing my blog
- Going for walks & being in relaxing outdoor places
- Meditating
- Exercising

### Things I feel are burdens

- Commute to work (~2h per day)
- Chores/Cleaning (1 day a week, usually a weekend)
- Food shopping (2-3 times per week)

### Improvement plan

Looking at the above burdens, there are only 3 real burdens that I feel consume time that should be free for me.

Looking at each in turn, I then began to note down potential solutions to reduce or remove them completely.

#### Commute and time spent at Work

- Find a new job closer to home
    + I really enjoy my job so this would have to be a last resort
- Change work hours
    + Could I work from home for a few days a week when feasible?
    + Being more disciplined to leave work at a reasonable time.

I decided that I would set a "home time" every day and stick to it to stop myself from overworking.

I will also be looking to work from home one or two days per week where I have no physical commitments such as meetings.

#### Chores/Cleaning

- Pay for a cleaner

This one was simple and something I should have looked into earlier. By paying for someone to come and clean the house will totally remove this from my burdens list.

#### Food Shopping

It seems like something so trivial, we all have to do it. However finding time to go food shopping is not always easy. It's an activity that usually consumes a large part of the weekend and I always find that I visit the supermarket a few times a week.

Again the solution to this problem was relatively simple.
- Use an online service and have the food delivered straight to my front door.

Similar to paying for a cleaner, this solution might end up costing a little more (although to begin with it seems fairly similar). However the amount it costs is negligible if it is going to allow me to spend that time enjoying other things.

## What's Next!

With two simple changes (removing chores and shopping from my weekend) I have now opened up my weekends and evenings to spend more time on the activities on my "Things I enjoy doing" list. With the improvement to my work schedule too, this year will undoubtedly be a fun and simple year.

For the rest of this year I will be mixing up this blog with lifestyle and self improvement posts, on top of the usual technology posts. Each week I will be bringing a new post breaking down the steps I will be taking to **Enjoy, Minimise and Reduce** so please stay tuned.

As a sneak peak - the first post will be looking at how I've changed my habits regarding my mobile phone and social networks.


text:
package Geo::TigerLine::Record::Parser;

use Carp::Assert;
use vars qw($VERSION);
$VERSION = '0.01';

=pod

=head1 NAME

Geo::TigerLine::Record::Parser - Parsing superclass for TIGER/Line records.

=head1 SYNOPSIS

  package Geo::TigerLine::Record::23;
  use base qw(Geo::TigerLine::Record::Parser);

  @records = __PACKAGE__->parse_file($fh);
  __PACKAGE__->parse_file($fh, \&callback);

  $record = __PACKAGE__->parse($row);

=head1 DESCRIPTION

Parses raw TIGER/Line data into Geo::TigerLine::Record objects.  This
is intended to be used as a superclass of Geo::TigerLine::Record
objects and not used directly.

You shouldn't be here.

=head2 Methods

=over 4

=item B<parse_file>

    @records = __PACKAGE__->parse_file($fh);
    __PACKAGE__->parse_file($fh, \&callback);

Parses a given filehandle as a TIGER/Line data file.  The data
definition is taken from __PACKAGE__->Pack_Tmpl, __PACKAGE__->Dict and
__PACKAGE__->Fields.  Returns an array of objects of type __PACKAGE__.

&callback will be called for each record and given a record object and
its position in the file (ie. 1 for the first, 2 for the second, etc...).
A sample callback...

    sub callback {
        my($record, $pos) = @_;

        printf "Record #$pos is %s\n", $record->tlid;
    }

If a &callback is given, a list of records will B<NOT> be returned.
It is assumed you'll be taking care of arrangements to store the
records in your callback and @records can eat up huge amounds of
memory for a typical TIGER/Line data file.

=cut

#'#
sub parse_file {
    my($proto, $fh, $callback) = @_;
    my($class) = ref $proto || $proto;

    my @records = ();

    my $num = 1;
    while(<$fh>) {
        chomp;
        my $record = $class->parse($_);

        if( defined $callback ) {
            $callback->($record, $num);
        }
        else {
            push @records, $record;
        }

        $num++;
    }

    return @records;
}

=pod

=item B<parse>

    $record = __PACKAGE__->parse($line);

Parses a single record of TIGER/Line data.

=cut

sub parse {
    my($proto, $line) = @_;
    my($class) = ref $proto || $proto;

    my $data_def = $class->Dict;
    my $data_fields = $class->Fields;
    my @fields = unpack($class->Pack_Tmpl, $line);

    assert(@fields == keys %$data_def);

    my %fields = map { ($_ => shift @fields) } @$data_fields;

    # Clip leading whitespace off right justified fields.
    foreach my $field ( map { $_->{field} } grep { $_->{fmt} eq 'R' }
                                              values %$data_def )
    {
        $fields{$field} =~ s/^\s+//;
    }

    my $obj =  $class->new(\%fields);
    return $obj;
}

=pod

=back

=head1 AUTHOR

Michael G Schwern <schwern@pobox.com>

=head1 SEE ALSO

L<Geo::TigerLine>

=cut

1;


text:
window.onload = inicia;

function inicia() {
	$("btnGo").onclick=consulta;//al hacer click se llama funcion para ver si el registro existe

	//ocultando campos que no son llave primaria y boton borrar
	//$("divContent").className="oculto";
	$("from").disabled = true;
	$("to").disabled = true;
	$("one").checked = true;
	$("one").className = "oculto";

	$("fromTo").onclick = function(){
		if($("fromTo").checked == true){
			$("wbNbr").disabled = true;
			$("from").disabled = false;
			$("to").disabled = false;
			$("one").checked = false;
			$("one").className = "";
			$("fromTo").className = "oculto";
		}
	}

	$("one").onclick = function(){
		if($("one").checked == true){
			$("from").disabled = true;
			$("to").disabled = true;
			$("wbNbr").disabled = false;
			$("one").className = "oculto";
			$("fromTo").checked = false;
			$("fromTo"). className = "";

		}
   }

}

function consulta() {

		//Limpiar la tabla primero
		tabla=document.getElementById("contenido");
		if(tabla){
			if(document.getElementById("contenido").rows.length>1){
				var ultima = document.getElementById("contenido").rows.length;
				for(var j=ultima; j>=1; j--){
							 document.getElementById("contenido").deleteRow(0);

				}
			}
		}

		var wrong = 0;
		if ($("one").checked == true){
			if($("wbNbr").value == "" || isNaN($("wbNbr").value)){wrong ++;}
				}
		else{
		if($("from").value == "" || $("to").value == "" || isNaN($("from").value) || isNaN($("to").value)){
			wrong ++;
			}
		}

		if(wrong == 0 && $("one").checked == true)
		{
			var query ="SELECT cveGuia , recepcionCYE , nombreRemitente ,   piezas , kg , volumen , recibio , sello , fechaEntrega , status , firma,"+
			"cconsignatarios.nombre AS nombreDestinatario, cestados.nombre AS estadoDestinatario"+
			" FROM cguias"+
			" LEFT JOIN cconsignatarios ON cguias.cveConsignatario = cconsignatarios.cveConsignatario"+
			" INNER JOIN cestados ON cconsignatarios.estado = cestados.cveEstado"+
			" WHERE  cveGuia = "+$("wbNbr").value+" AND cveCliente="+$("hdnCliente").value;

			var parametro = "query=" + query;

			$Ajax("scripts/consultaGuias.php?opc=0", {metodo: $metodo.POST, onfinish: carga_campos, parametros: parametro, avisoCargando:"loading"});
		}

		if(wrong == 0 && $("fromTo").checked == true){

			//Checar que el número del rango "hasta" sea mayor al de "de"
			rangoinicio=parseInt($("from").value);
			rangofin=parseInt($("to").value);

			if(rangofin<rangoinicio){
				alert("El rango final(hasta) es menor al rango inicial(de).");
				return; //NO necesario
			}
			else if(rangofin==rangoinicio)
			{
				alert("El rango final(hasta) es igual al rango inicial(de), puede emplear la primera opci\u00F3n en caso de que desee buscar \u00FAnicamente una gu\u00EDa.");
				return; //NO necesario
			}
			else{
				var query = "SELECT cveGuia , recepcionCYE , nombreRemitente ,   piezas , kg , volumen , recibio , sello , fechaEntrega , status , firma,"+
				"cconsignatarios.nombre AS nombreDestinatario, cestados.nombre AS estadoDestinatario"+
				" FROM cguias"+
				" LEFT JOIN cconsignatarios ON cguias.cveConsignatario = cconsignatarios.cveConsignatario"+
				" INNER JOIN cestados ON cconsignatarios.estado = cestados.cveEstado"+
				" WHERE cveGuia >= '"+$("from").value + "' AND cveGuia <= '" + $("to").value + "' AND cveCliente="+$("hdnCliente").value + " ORDER BY cveGuia";

				var parametro = "query=" + query;

				$Ajax("scripts/consultaGuias.php?opc=1", {metodo: $metodo.POST, onfinish: carga_campos, parametros: parametro, avisoCargando:"loading"});
			}

		}

}
		function carga_campos(respuesta){
		$("divContent").innerHTML = respuesta;

		}

		function fin(res){
		alert(res);
		$("divContent").className="oculto";
		//$("txtWbId").disabled=false;

		$("btnGo").disabled=false;
		//$("txtWbId").value = "";

		$("status").innerHTML="";

		}

		function allgood(){
		var notGood = 0;

		if($("lstStatus").value == "" || $("lstStatus").value == "ended"){$("lstStatus").addClassName("invalid"); notGood ++;} else {$("lstStatus").className = "";}

		if($("lstStatus").value == "dlvd" && ($("txtDlvdDate").value == "" || $("txtRcbdBy").value == "")){ notGood ++}

		if(($("txtDlvdDate").value != "" && $("txtRcbdBy").value == "") || ($("txtRcbdBy").value != "" && $("txtDlvdDate").value == "")){notGood ++;};

		if(notGood > 0){alert("Hay Informacion erronea");return false;} else{return true;}
		}


text:
<!DOCTYPE html>

        <title>Home</title>

            	Home
            	Manage Site Content

Welcome User!


text:
// extend es5 nodes
var nodes = module.exports = Object.create(require('../es5').nodes);

// prepare node-registry
var Factory  = require('../jsonml').factory;
var register = function(type) {

  var nodetype = Factory.apply(null, arguments);

  // register new nodetype
  nodes[type] = nodetype;
};

/**
 * Lambda
 * ------
 * A shorthand version of a function expression.
 *
 * Example usage:
 * instead of writing `function(){}` you may write `{||}` and
 * instead of writing `function(arg){ return arg*2; }` you may write `{|arg| arg*2; }`
 *
 * To provide backward-compatibility implicit returns are only enabled for lambdas
 *
 * @argument [FunctionArgs] args
 * @argument [BlockStmt] body It's an AST-node and hence looks like: `[#BlockStmt, {}, child1, ...]`
 */
register('LambdaExpr');

/**
 * FunctionArgs with rest-parameter
 * --------------------------------
 * TODO implement
 *
 * Representation:
 *     [#FunctionArgs, { rest: "r"}, ...Expressions]
 *
 * Call like:
 *     ES5Builder.FunctionArgs(...args).rest("r");
 */
register("FunctionArgs", { rest: undefined }, function(args) {
  this.appendAll(args);
});

register('SliceExpr');

register('ExtendExpr');

register('PrototypeExpr');

/**
 * Example usage:
 *    var foo = "foo #{bar} baz";
 */
register('StringExpr', {}, function(parts) {

  // if it's a simple string, then immediately convert it, to clean the AST
  if(parts.length == 1 && parts[0][0] == 'String')
      return parts[0]

  this.appendAll(parts)
});

register('ScopeExpr');

/**
 * Class
 * -----
 */
register('ClassStmt', {
  name: undefined,
  parent: undefined

}, function(name, parent, sections, props, constr) {
  this.name(name)
      .parent(parent)
      .append(sections, props, constr);
});

register('DebugStmt');

register('ModuleStmt', { name: undefined }, function(name, impl) {
  this.name(name)
      .append(impl);
});

register('ForOfStmt');

register('PatternMatcher', {}, function(expr, cases) {
  this.append(expr)
      .appendAll(cases)
});
register('PatternCase');
register('Pattern', { kind: undefined, binding: undefined }, function(els) {
  this.appendAll(els);
});


text:
import com.twilio.sdk.TwilioRestException;
import com.twilio.sdk.TwilioTaskRouterClient;
import com.twilio.sdk.resource.instance.taskrouter.Workspace;
import com.twilio.sdk.resource.list.taskrouter.WorkspaceList;

public class Example {

  // Find your Account Sid and Token at twilio.com/user/account
  private static final String ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
  private static final String AUTH_TOKEN = "your_auth_token";
  private static final String WORKSPACE_SID = "WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

  public static void main(String[] args) throws TwilioRestException {
    TwilioTaskRouterClient client = new TwilioTaskRouterClient(ACCOUNT_SID, AUTH_TOKEN);

    WorkspaceList workspaces = client.getWorkspaces();
    for(Workspace workspace : workspaces) {
        System.out.println(workspace.getFriendlyName());
    }
  }
}


text:
layout: people
title: Lucile Appert
description: Associate Director for Instructional Design, CTL
img: lappert.jpeg
author: Alex Gil
teams:
- Center for Teaching and Learning
---

Lucy Appert is the CTL Associate Director for Instructional Design. She leads the CTL's innovative project partnerships with faculty using its Design Research methodology. She is the first point of contact for inquiries about grant-funded opportunities and other partnerships requiring video, creative design, or development resources. Her areas of special interest include digital literacy, digital humanities, and project-based learning.

Prior to joining the CTL, Lucy served as Director of Educational Technology for New York University's Liberal Studies Program, where she led the team providing instructional technology solutions for Liberal Studies faculty and students in New York and at NYU's Global Sites. She was also a faculty member in the program and has more than 20 years of teaching experience, having taught at Tulane, Vanderbilt, and Yale, in addition to NYU. Lucy holds a Ph.D. in 17th & 18th c. British literature from Tulane University and a B.A. in Classics and English from UNC-Chapel Hill.


text:
/**
 * @file worker-pool.h
 * @brief a worker pool definition.
 */
#ifndef EPYX_WORKER_POOL_H
#define EPYX_WORKER_POOL_H

#include "blocking-queue.h"
#include <atomic>
#include <boost/noncopyable.hpp>
#include <list>
#include <map>
#include <memory>
#include <mutex>
#include <string>
#include <sstream>
#include <thread>

namespace Epyx
{
    /**
     * @class WorkerPool
     *
     * @brief A mean to distribute work between several threads easily
     *
     * A WorkerPool allows you to distribute a work on several threads by
     * passing "messages" that are in facts function arguments. To use it
     * subclass the WorkerPool and implement the treat() function that will
     * process the message in a thread.
     *
     * @tparam T the base type of the messages passed to the workers
     */
    template<typename T>class WorkerPool : private boost::noncopyable
    {
    public:
        /**
         * @brief Internal shortcut for unique_ptr to type T
         */
        typedef std::unique_ptr<T> TPtr;

        /**
         * @brief The WorkerPool constructor
         * @param num_workers the initial number of worker threads
         * @param name the prefix of the name of the worker threads in the logs
         */
        WorkerPool(int num_workers, const std::string& name);

        /**
         * @brief The WorkerPool other constructor
         */
        WorkerPool();

        /**
         * @brief The WorkerPool destructor
         *
         * @todo What will happen with the messages that are still to be processed ?
         */
        virtual ~WorkerPool();

        /**
         * @brief Stop WorkerPool (wait all children threads)
         */
        void stop();

        /**
         * @brief Adds a message to be processed
         * @param message the message
         */
        void post(T* message);

        /**
         * @brief Adds a message to be processed
         * @param message the message
         */
        void post(TPtr message);

        /**
         * @brief set the name of the workers
         * Please call this functionto set a name BEFORE starting any worker
         */
        void setName(const std::string& name);

        /**
         * @brief gets the number of workers
         * @return the current number of workers
         */
        int getNumWorkers() const;

        /**
         * @brief sets the number of workers
         * @param n the number of workers needed
         */
        void setNumWorkers(int n);

    protected:
        /**
         * @brief this is the method to override
         * @param message the message to be processed
         */
        virtual void treat(TPtr message) = 0;

    private:
        void addWorker();
        void removeWorker();

        // Finalise a worker destruction
        void bookKeep();

        // Worker threads
        class Worker
        {
        public:
            // Spawn a new thread
            Worker(WorkerPool *pool, int id);

            // Tell the worker to stop ASAP, return the previous state
            bool tellStop();

            // Wait for the thread to terminate
            void wait();
        private:
            void run(WorkerPool *pool);

            bool running;
            int id;
            std::thread thread;
        };

        // Message queue
        BlockingQueue<T> messages;

        // Name prefix
        std::string name;

        // Last used ID, to be used for new workers
        std::atomic<int> lastId;

        // Running workers
        std::atomic<int> worker_count;
        std::mutex workers_mutex;
        std::map<int, std::unique_ptr<Worker> > workers;

        // Terminated workers, waiting a join()
        BlockingQueue<int> workers_to_destroy;
    };

}

#include "worker-pool-detail.h"

#endif /* EPYX_WORKER_POOL_H */


text:
// Code generated by informer-gen. DO NOT EDIT.

package v1alpha1

import (
	time "time"

	ranchervm_v1alpha1 "github.com/rancher/vm/pkg/apis/ranchervm/v1alpha1"
	versioned "github.com/rancher/vm/pkg/client/clientset/versioned"
	internalinterfaces "github.com/rancher/vm/pkg/client/informers/externalversions/internalinterfaces"
	v1alpha1 "github.com/rancher/vm/pkg/client/listers/ranchervm/v1alpha1"
	v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	runtime "k8s.io/apimachinery/pkg/runtime"
	watch "k8s.io/apimachinery/pkg/watch"
	cache "k8s.io/client-go/tools/cache"
)

// MachineImageInformer provides access to a shared informer and lister for
// MachineImages.
type MachineImageInformer interface {
	Informer() cache.SharedIndexInformer
	Lister() v1alpha1.MachineImageLister
}

type machineImageInformer struct {
	factory          internalinterfaces.SharedInformerFactory
	tweakListOptions internalinterfaces.TweakListOptionsFunc
}

// NewMachineImageInformer constructs a new informer for MachineImage type.
// Always prefer using an informer factory to get a shared informer instead of getting an independent
// one. This reduces memory footprint and number of connections to the server.
func NewMachineImageInformer(client versioned.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {
	return NewFilteredMachineImageInformer(client, resyncPeriod, indexers, nil)
}

// NewFilteredMachineImageInformer constructs a new informer for MachineImage type.
// Always prefer using an informer factory to get a shared informer instead of getting an independent
// one. This reduces memory footprint and number of connections to the server.
func NewFilteredMachineImageInformer(client versioned.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {
	return cache.NewSharedIndexInformer(
		&cache.ListWatch{
			ListFunc: func(options v1.ListOptions) (runtime.Object, error) {
				if tweakListOptions != nil {
					tweakListOptions(&options)
				}
				return client.VirtualmachineV1alpha1().MachineImages().List(options)
			},
			WatchFunc: func(options v1.ListOptions) (watch.Interface, error) {
				if tweakListOptions != nil {
					tweakListOptions(&options)
				}
				return client.VirtualmachineV1alpha1().MachineImages().Watch(options)
			},
		},
		&ranchervm_v1alpha1.MachineImage{},
		resyncPeriod,
		indexers,
	)
}

func (f *machineImageInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {
	return NewFilteredMachineImageInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)
}

func (f *machineImageInformer) Informer() cache.SharedIndexInformer {
	return f.factory.InformerFor(&ranchervm_v1alpha1.MachineImage{}, f.defaultInformer)
}

func (f *machineImageInformer) Lister() v1alpha1.MachineImageLister {
	return v1alpha1.NewMachineImageLister(f.Informer().GetIndexer())
}


text:
package org.wildfly.camel.test.spring;

import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.spring.SpringCamelContext;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.wildfly.camel.test.spring.subD.MyConfiguration.Counter;
import org.wildfly.camel.test.spring.subD.MyConfiguration;
import org.wildfly.extension.camel.CamelAware;

@CamelAware
@RunWith(Arquillian.class)
public class SpringExplicitConfigurationTest {

    @Deployment
    public static JavaArchive createdeployment() {
        final JavaArchive archive = ShrinkWrap.create(JavaArchive.class, "camel-spring-config-tests");
        archive.addClasses(MyConfiguration.class);
        return archive;
    }

    @Test
    public void testSpringJavaConfig() throws Exception {

        AnnotationConfigApplicationContext appctx = new AnnotationConfigApplicationContext(MyConfiguration.class);
        CamelContext camelctx = new SpringCamelContext(appctx);
        camelctx.addRoutes(appctx.getBean(RouteBuilder.class));

        camelctx.start();
        try {
            ProducerTemplate producer = camelctx.createProducerTemplate();
            String result = producer.requestBody("direct:start", "Kermit", String.class);
            Assert.assertEquals("Hello Kermit", result);
        } finally {
            camelctx.close();
        }
    }

    @Test
    @SuppressWarnings("resource")
    public void testCounterA() throws Exception {

        ApplicationContext appctx = new AnnotationConfigApplicationContext(MyConfiguration.class);
        Assert.assertEquals(1, appctx.getBean(Counter.class).getCount());
        Assert.assertEquals(1, appctx.getBean(Counter.class).getCount());
    }
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package spaceracegame;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 *
 * @author Terekhov F.V. <fterekhov@gmail.com>
 */
public class Warehouse implements Serializable {

    public ArrayList<StoreObject> delivery = new ArrayList<StoreObject>(); //Array for future deliveries of objects. Format: Date, Object
    public ArrayList<StoreObject> usage = new ArrayList<StoreObject>(); //Array for future usage of objects. Format: Date, Object
    public int[] storehouse;
    private Player player;
//    public static int[] warehouseUsed;

    Warehouse(Player givenPlayer) {
        player = givenPlayer;
    }

    public void setPlayer(Player givenPlayer) {
        player = givenPlayer;
    }

    public void removePlayer() {
        player = null;
    }

    public void initialize() {
        storehouse = new int[1000];
    }

    public ArrayList<StoreObject> getDeliveryByDate(Date date) {

        ArrayList<StoreObject> tempstoreobjectlist = new ArrayList<StoreObject>();

        for (int i = 0; i < delivery.size(); i++) {
            if (delivery.get(i).objectdate.equals(date)) {
                tempstoreobjectlist.add(delivery.get(i));
            }
        }
        return tempstoreobjectlist;
    }

    public ArrayList<StoreObject> getDeliveryAfterDate(Date date) {

        ArrayList<StoreObject> tempstoreobjectlist = new ArrayList<StoreObject>();

        for (int i = 0; i < delivery.size(); i++) {
            if (delivery.get(i).objectdate.after(date)) {
                tempstoreobjectlist.add(delivery.get(i));
            }
        }
        return tempstoreobjectlist;
    }

    public ArrayList<StoreObject> removeDeliveryByDate(Date date) {

        ArrayList<StoreObject> tempstoreobjectlist = new ArrayList<StoreObject>();

        for (int i = 0; i < delivery.size(); i++) {
            if (delivery.get(i).objectdate.equals(date)) {
                tempstoreobjectlist.add(delivery.remove(i));
            }
        }
        return tempstoreobjectlist;
    }

    public void parseDelivery() {

        for (int i = 0; i < delivery.size(); i++) {
            if (delivery.get(i).objectdate.before(Dateutils.getDateMonthShift(1))) {
                storehouse[delivery.get(i).objectcode]++;
                delivery.remove(i);
                i--;

            }
        }

    }

    public void addDelivery(Date objectdate, int gameobject) {
        StoreObject tempstoreobject = new StoreObject();
        tempstoreobject.objectcode = gameobject;
        tempstoreobject.objectdate = objectdate;
        delivery.add(tempstoreobject);

    }

    public void addDeliveryInt(int monthshift, int gameobject) {
        StoreObject tempstoreobject = new StoreObject();
        tempstoreobject.objectcode = gameobject;
        tempstoreobject.objectdate = Dateutils.getDateMonthShift(monthshift);
        delivery.add(tempstoreobject);
    }

    public int getDeliveryByDateCountObject(Date date, int objectcode) {
        int counter = 0;
        ArrayList<StoreObject> templist = getDeliveryByDate(date);
        for (int i = 0; i < templist.size(); i++) {
            if (templist.get(i).objectcode == objectcode) {
                counter++;
            }
        }
        return counter;
    }

    public int getDeliveryAfterDateCountObject(Date date, int objectcode) {
        int counter = 0;
        ArrayList<StoreObject> templist = getDeliveryAfterDate(date);
        for (int i = 0; i < templist.size(); i++) {
            if (templist.get(i).objectcode == objectcode) {
                counter++;
            }
        }
        return counter;
    }

    public String getCurrentWarehouse() {
        String tempstring = "<html>";
        for (int i = 0; i < storehouse.length; i++) {
            if (storehouse[i] > 0) {
                tempstring = tempstring + " " + player.spaceObjectArray.findObjectByCode(i).name + ": " + Integer.toString(storehouse[i]) + " <br>";
            }
        }
        return tempstring;
    }

    public boolean isInStock(int code) {
        boolean result = storehouse[code] > 0;
        return result;
    }
}