text:
from typing import Any
from typing import Dict
from typing import List
from typing import Optional
from typing import Type

# third party
from sqlalchemy.engine import Engine
from sqlalchemy.orm import sessionmaker

# relative
from ..node_table import Base

class DatabaseManager:
    def __init__(self, schema: Type[Base], db: Engine) -> None:
        self._schema = schema
        self.db = db

    def register(self, **kwargs: Any) -> Any:
        """Register a new object into the database.

        Args:
            parameters : List of object parameters.
        Returns:
            object: Database Object
        """
        _obj = self._schema(**kwargs)
        session_local = sessionmaker(autocommit=False, autoflush=False, bind=self.db)()
        session_local.add(_obj)
        session_local.commit()
        return _obj

    def query(self, **kwargs: Any) -> List[Any]:
        """Query db objects filtering by parameters
        Args:
            parameters : List of parameters used to filter.
        """
        session_local = sessionmaker(autocommit=False, autoflush=False, bind=self.db)()
        objects = session_local.query(self._schema).filter_by(**kwargs).all()
        session_local.close()
        return objects

    def first(self, **kwargs: Any) -> Optional[Any]:
        """Query db objects filtering by parameters
        Args:
            parameters : List of parameters used to filter.
        """
        session_local = sessionmaker(autocommit=False, autoflush=False, bind=self.db)()
        objects = session_local.query(self._schema).filter_by(**kwargs).first()
        session_local.close()
        return objects

    def last(self, **kwargs: Any) -> Optional[Any]:
        """Query and return the last occurrence.

        Args:
            parameters: List of parameters used to filter.
        Return:
            obj: Last object instance.
        """
        session_local = sessionmaker(autocommit=False, autoflush=False, bind=self.db)()
        obj = session_local.query(self._schema).filter_by(**kwargs).all()[-1]
        session_local.close()
        return obj

    def all(self) -> List[Any]:
        session_local = sessionmaker(autocommit=False, autoflush=False, bind=self.db)()
        result = list(session_local.query(self._schema).all())
        session_local.close()
        return result

    def delete(self, **kwargs: Any) -> None:
        """Delete an object from the database.

        Args:
            parameters: Parameters used to filter the object.
        """
        session_local = sessionmaker(autocommit=False, autoflush=False, bind=self.db)()
        session_local.query(self._schema).filter_by(**kwargs).delete()
        session_local.commit()
        session_local.close()

    def modify(self, query: Dict[Any, Any], values: Dict[Any, Any]) -> None:
        """Modifies one or many records."""
        session_local = sessionmaker(autocommit=False, autoflush=False, bind=self.db)()
        session_local.query(self._schema).filter_by(**query).update(values)
        session_local.commit()
        session_local.close()

    def contain(self, **kwargs: Any) -> bool:
        session_local = sessionmaker(autocommit=False, autoflush=False, bind=self.db)()
        objects = session_local.query(self._schema).filter_by(**kwargs).all()
        session_local.close()
        return len(objects) != 0

    def __len__(self) -> int:
        session_local = sessionmaker(autocommit=False, autoflush=False, bind=self.db)()
        result = session_local.query(self._schema).count()
        session_local.close()
        return result

    def clear(self) -> None:
        local_session = sessionmaker(bind=self.db)()
        local_session.query(self._schema).delete()
        local_session.commit()
        local_session.close()


text:
#region Header

#endregion Header

namespace NArrange.Core.CodeElements
{
    using System.Collections.ObjectModel;

    /// <summary>
    /// Interface for generic elements.
    /// </summary>
    public interface IGenericElement
    {
        #region Properties

        /// <summary>
        /// Gets the list of type parameters.
        /// </summary>
        ReadOnlyCollection<TypeParameter> TypeParameters
        {
            get;
        }

        #endregion Properties

        #region Methods

        /// <summary>
        /// Adds a type parameter to the element.
        /// </summary>
        /// <param name="typeParameter">The type parameter.</param>
        void AddTypeParameter(TypeParameter typeParameter);

        #endregion Methods
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<package id="ff8080814e61e7f3014e68ac6882161f">
    <name>org.lostroncos.library.netscaler.base</name>
    <description/>
    <workflows>
        <id-8272e24a-7b26-4c43-b5b9-fb4f4d62e7e8 path="Library/Citrix NetScaler/Configuration/Create Worflows from REST Operations.workflow.xml"/>
        <id-d9243c60-e891-4425-864d-888909f97f83 path="Library/Citrix NetScaler/Configuration/Add NetScaler REST Operations.workflow.xml"/>
    </workflows>
    <actions/>
    <configurations/>
    <resources/>
</package>


text:
layout: docs
title: Brand guidelines
description: Documentation and examples for Bootstrap's logo and brand usage guidelines.
group: about
---

Have a need for Bootstrap's brand resources? Great! We have only a few guidelines we follow, and in turn ask you to follow as well. These guidelines were inspired by MailChimp's [Brand Assets](https://mailchimp.com/about/brand-assets/).

## Contents

* Will be replaced with the ToC, excluding the "Contents" header
{:toc}

## Mark and logo

Use either the Bootstrap mark (a capital **B**) or the standard logo (just **Bootstrap**). It should always appear in Helvetica Neue Bold. **Do not use the Twitter bird** in association with Bootstrap.

B

B

Bootstrap

Bootstrap

## Download mark

Download the Bootstrap mark in one of three styles, each available as an SVG file. Right click, Save as.

## Name

The project and framework should always be referred to as **Bootstrap**. No Twitter before it, no capital _s_, and no abbreviations except for one, a capital **B**.

Bootstrap

    Right

BootStrap

    Wrong

Twitter Bootstrap

    Wrong

## Colors

Our docs and branding use a handful of primary colors to differentiate what *is* Bootstrap from what *is in* Bootstrap. In other words, if it's purple, it's representative of Bootstrap.


text:
<?php

namespace Flowcode\SocialHubBundle\Service;

use Facebook\Facebook;
use Flowcode\SocialHubBundle\Repository\SocialNetworkRepository;
use Symfony\Component\HttpFoundation\Session\Session;

/**
 * Class SocialNetworkService
 */
class SocialNetworkService
{

    /**
     * @var SocialNetworkRepository
     */
    private $socialNetworkRepository;
    private $container;

    /**
     * SocialNetworkService constructor.
     * @param $container
     * @param SocialNetworkRepository $socialNetworkRepository
     */
    public function __construct($container, SocialNetworkRepository $socialNetworkRepository)
    {
        $this->container = $container;
        $this->socialNetworkRepository = $socialNetworkRepository;
    }

    public function getSocialNetwork($type)
    {
        $socialNetwork = $this->socialNetworkRepository->findOneBy(array(
            'type' => $type,
        ));

        return $socialNetwork;
    }

    public function getLoginUrls()
    {

        $socialNetworks = $this->socialNetworkRepository->findBy(array(
            'enabled' => true,
            'loginEnabled' => true
        ));

        try {
            $session = new Session();
            if (!$session->isStarted()) {
                $session->start();
            }
        } catch (\Exception $e) {

        }

        $urls = array();
        $provider_prefix = "socialhub_provider_";
        foreach ($socialNetworks as $socialNetwork) {
            $socialProvider = $this->container->get($provider_prefix . $socialNetwork->getType());

            $loginUrl = $socialProvider->getLoginUrl();

            $urls[] = array(
                'name' => $socialNetwork->getName(),
                'type' => $socialNetwork->getType(),
                'label' => "label." . $socialNetwork->getType(),
                'url' => $loginUrl,
            );
        }

        return $urls;
    }

}


text:
package cn.ieclipse.af.demo.my;

import cn.ieclipse.af.demo.common.api.BaseRequest;

/**
 * 类/接口描述
 *
 * @author Jamling
 */
public class LoginRequest extends BaseRequest {
    public String phone;
    public String code;
    public String password;
    public String type;//    类型

    public String username;
    public String pwd;
}


text:
  <title>BigSense for DB Systel GmbH (Cooperation with TK)</title>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link href="//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css" rel="stylesheet">

		  <form onsubmit="return false;">

		    <input style="font-size:x-large; margin: 5px;" type="text" placeholder="Username" id="loginUser" value=""/>

		    <input style="font-size:x-large; margin: 5px;" type="text" placeholder="Password" id="loginPassword" value=""/>

		    <input style="font-size:x-large; margin: 5px;" type="button" class="btn btn-default" id="loginButton" value="Login"/>
		  </form>

	<form onsubmit="return false;">
		<input style="font-size:x-large;" type="button" class="btn btn-default" id="logoutButton" value="Logout"/>
	</form>

APKs

Apps

Phones

Groups

Logs

		    <input type="file" class="btn btn-default" id="apkFiles" name="files[]" multiple />

		    <form onsubmit="return false;">
			    <input type="text" placeholder="New Group" id="groupName" value=""/>
			    <input type="button" class="btn btn-default" id="createButton" value="Create"/>
		  	</form>


text:
class Solution:
    def longestCommonPrefix(self, strs) -> str:
        if len(strs) == 0:
            return ''

        prefix = strs[0]
        for s in strs:
            while not s.startswith(prefix):
                prefix = prefix[:-1]
            if len(prefix) == 0:
                return ''
        return prefix


text: """The cisco_ios component."""


text:
package com.nominanuda.xml;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;

public class SwallowingTransformerHandlerBase extends
		ForwardingTransformerHandlerBase {

	@Override
	public void startDocument() throws SAXException {
	}

	@Override
	public void endDocument() throws SAXException {
	}

	@Override
	public void startPrefixMapping(String prefix, String uri)
			throws SAXException {
	}

	@Override
	public void endPrefixMapping(String prefix) throws SAXException {
	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes atts) throws SAXException {
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
	}

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
	}

	@Override
	public void ignorableWhitespace(char[] ch, int start, int length)
			throws SAXException {
	}

	@Override
	public void processingInstruction(String target, String data)
			throws SAXException {
	}

	@Override
	public void skippedEntity(String name) throws SAXException {
	}

	@Override
	public void startDTD(String name, String publicId, String systemId)
			throws SAXException {
	}

	@Override
	public void endDTD() throws SAXException {
	}

	@Override
	public void startEntity(String name) throws SAXException {
	}

	@Override
	public void endEntity(String name) throws SAXException {
	}

	@Override
	public void startCDATA() throws SAXException {
	}

	@Override
	public void endCDATA() throws SAXException {
	}

	@Override
	public void comment(char[] ch, int start, int length) throws SAXException {
	}

	@Override
	public void notationDecl(String name, String publicId, String systemId)
			throws SAXException {
	}

	@Override
	public void unparsedEntityDecl(String name, String publicId,
			String systemId, String notationName) throws SAXException {
	}

}


text:
module Steak
  class Railtie < ::Rails::Railtie
    rake_tasks do
      load 'tasks/steak_tasks.rake'
    end
  end
end


text:
/*
 * Generic interface to mice. Most graphics drivers will register a single
 * mouse object, but multiple instances are supported.
 */

#include <core/core.h>

#include "window.h"
#include "cursors.h"

AG_Mouse *
AG_MouseNew(void *drv, const char *desc)
{
	AG_Mouse *ms;

	AG_ASSERT_CLASS(drv, "AG_Driver:*");

	if ((ms = TryMalloc(sizeof(AG_Mouse))) == NULL) {
		return (NULL);
	}
	AG_ObjectInit(ms, &agMouseClass);
	AGINPUTDEV(ms)->drv = drv;
	if ((AGINPUTDEV(ms)->desc = TryStrdup(desc)) == NULL) {
		goto fail;
	}
	AGDRIVER(drv)->mouse = ms;
	AG_ObjectAttach(&agInputDevices, ms);
	return (ms);
fail:
	AG_ObjectDestroy(ms);
	return (NULL);
}

static void
Init(void *obj)
{
	AG_Mouse *ms = obj;

	OBJECT(ms)->flags |= AG_OBJECT_NAME_ONATTACH;
	ms->nButtons = 0;
	ms->btnState = 0;
	ms->x = 0;
	ms->y = 0;
	ms->xRel = 0;
	ms->yRel = 0;
}

/* Update the mouse state following a cursor motion event. */
void
AG_MouseMotionUpdate(AG_Mouse *ms, int x, int y)
{
	ms->xRel = x - ms->x;
	ms->yRel = y - ms->y;

	if (ms->xRel != 0 || ms->yRel != 0) {
		ms->x = x;
		ms->y = y;
	}
}

/*
 * Change the cursor if overlapping a registered cursor area.
 * Generally called in response to mousemotion events.
 */
void
AG_MouseCursorUpdate(AG_Window *win, int x, int y)
{
	AG_Driver *drv = WIDGET(win)->drv;
	AG_CursorArea *ca;
	AG_Rect r;

	TAILQ_FOREACH(ca, &win->cursorAreas, cursorAreas) {
		if (ca->wid->flags & AG_WIDGET_HIDE) {
			continue;
		}
		r.x = ca->r.x + ca->wid->rView.x1;
		r.y = ca->r.y + ca->wid->rView.y1;
		r.w = ca->r.w;
		r.h = ca->r.h;
		if (AG_RectInside(&r, x,y))
			break;
	}
	if (ca == NULL) {
		if (drv->activeCursor != &drv->cursors[0])
			AGDRIVER_CLASS(drv)->unsetCursor(drv);
	} else if (ca->c != drv->activeCursor) {
		AGDRIVER_CLASS(drv)->setCursor(drv, ca->c);
	}
}

/* Update the mouse state following a button press/release event. */
void
AG_MouseButtonUpdate(AG_Mouse *ms, AG_MouseButtonAction a, int which)
{
	if (a == AG_BUTTON_PRESSED) {
		ms->btnState |= AG_MOUSE_BUTTON(which);
	} else {
		ms->btnState &= ~(AG_MOUSE_BUTTON(which));
	}
}

/* Recursively deliver a mouse-motion event to widgets. */
static void
PostMouseMotion(AG_Window *win, AG_Widget *wid, int x, int y, int xRel,
    int yRel, Uint state)
{
	AG_Widget *chld;

	AG_ObjectLock(wid);
	if (wid->flags & AG_WIDGET_USE_MOUSEOVER) {
		if (AG_WidgetArea(wid, x,y)) {
			if ((wid->flags & AG_WIDGET_MOUSEOVER) == 0) {
				wid->flags |= AG_WIDGET_MOUSEOVER;
				AG_PostEvent(NULL, wid, "mouse-over", NULL);
				AG_Redraw(wid);
			}
		} else {
			if (wid->flags & AG_WIDGET_MOUSEOVER) {
				wid->flags &= ~(AG_WIDGET_MOUSEOVER);
				AG_PostEvent(NULL, wid, "mouse-over", NULL);
				AG_Redraw(wid);
			}
		}
	}
	if ((AG_WidgetIsFocusedInWindow(wid)) ||
	    (wid->flags & AG_WIDGET_UNFOCUSED_MOTION)) {
		AG_PostEvent(NULL, wid, "mouse-motion",
		    "%i(x),%i(y),%i(xRel),%i(yRel),%i(buttons)",
		    x - wid->rView.x1,
		    y - wid->rView.y1,
		    xRel,
		    yRel,
		    (int)state);
#ifdef AG_LEGACY
		AG_PostEvent(NULL, wid, "window-mousemotion",
		    "%i,%i,%i,%i,%i",
		    x - wid->rView.x1,
		    y - wid->rView.y1,
		    xRel,
		    yRel,
		    (int)state);
#endif
		if (wid == win->widExclMotion)
			goto out;			/* Skip other widgets */
	}
	OBJECT_FOREACH_CHILD(chld, wid, ag_widget)
		PostMouseMotion(win, chld, x, y, xRel, yRel, state);
out:
	AG_ObjectUnlock(wid);
}

/*
 * Recursively deliver a mouse-button-up event to widgets that either hold
 * focus or have the UNFOCUSED_BUTTONUP flag set.
 */
static void
PostMouseButtonUp(AG_Window *win, AG_Widget *wid, int x, int y,
    AG_MouseButton button)
{
	AG_Widget *chld;

	AG_ObjectLock(wid);
	if ((AG_WidgetIsFocusedInWindow(wid)) ||
	    (wid->flags & AG_WIDGET_UNFOCUSED_BUTTONUP)) {
		AG_PostEvent(NULL, wid, "mouse-button-up",
		    "%i(button),%i(x),%i(y)",
		    (int)button,
		    x - wid->rView.x1,
		    y - wid->rView.y1);
#ifdef AG_LEGACY
		AG_PostEvent(NULL, wid, "window-mousebuttonup",
		    "%i,%i,%i",
		    (int)button,
		    x - wid->rView.x1,
		    y - wid->rView.y1);
#endif
	}
	OBJECT_FOREACH_CHILD(chld, wid, ag_widget) {
		PostMouseButtonUp(win, chld, x, y, button);
	}
	AG_ObjectUnlock(wid);
}

/*
 * Recursively deliver a mouse-button-down event to widgets based on
 * widget sensitivity rectangles.
 */
static int
PostMouseButtonDown(AG_Window *win, AG_Widget *wid, int x, int y,
    AG_MouseButton button)
{
	AG_Widget *chld;
	AG_Event *ev;

	AG_ObjectLock(wid);

	/* Search for a better match. */
	OBJECT_FOREACH_CHILD(chld, wid, ag_widget) {
		if (PostMouseButtonDown(win, chld, x, y, button))
			goto match;
	}
	if (!AG_WidgetSensitive(wid, x, y)) {
		goto out;
	}
	TAILQ_FOREACH(ev, &OBJECT(wid)->events, events) {
		if (strcmp(ev->name, "mouse-button-down") == 0)
			break;
#ifdef AG_LEGACY
		if (strcmp(ev->name, "window-mousebuttondown") == 0)
			break;
#endif
	}
	if (ev != NULL) {
		AG_PostEvent(NULL, wid, "mouse-button-down",
		    "%i(button),%i(x),%i(y)",
		    (int)button,
		    x - wid->rView.x1,
		    y - wid->rView.y1);
#ifdef AG_LEGACY
		AG_PostEvent(NULL, wid, "window-mousebuttondown",
		    "%i,%i,%i",
		    (int)button,
		    x - wid->rView.x1,
		    y - wid->rView.y1);
#endif
		goto match;
	}
out:
	AG_ObjectUnlock(wid);
	return (0);
match:
	AG_ObjectUnlock(wid);
	return (1);
}

/*
 * Process a mouse-motion event relative to the given window;
 * this is called from low-level event handling code.
 */
void
AG_ProcessMouseMotion(AG_Window *win, int x, int y, int xRel, int yRel,
    Uint state)
{
	AG_Widget *wid;

	/* Allow a widget (e.g., AG_Pane) to absorb all mousemotion events */
	if ((wid = win->widExclMotion) != NULL) {
		AG_ObjectLock(wid);
		PostMouseMotion(win, wid, x, y, xRel, yRel, state);
		AG_ObjectUnlock(wid);
		return;
	}

	/* Recursively post mouse-motion to all widgets. */
	OBJECT_FOREACH_CHILD(wid, win, ag_widget)
		PostMouseMotion(win, wid, x, y, xRel, yRel, state);
}

/*
 * Process a mouse-button event relative to the given window;
 * this is called from low-level event handling code.
 */
void
AG_ProcessMouseButtonUp(AG_Window *win, int x, int y, AG_MouseButton button)
{
	AG_Widget *wid;

	OBJECT_FOREACH_CHILD(wid, win, ag_widget)
		PostMouseButtonUp(win, wid, x, y, button);
}

/*
 * Process a mouse-button event relative to the given window; this is called
 * from low-level event handling code. The agDrivers VFS must be locked.
 */
void
AG_ProcessMouseButtonDown(AG_Window *win, int x, int y, AG_MouseButton button)
{
	AG_Widget *wid;
	AG_Driver *drv;
	AG_Window *winOther;

	/* Handle modal windows. */
	AGOBJECT_FOREACH_CHILD(drv, &agDrivers, ag_driver) {
		AG_FOREACH_WINDOW(winOther, drv) {
			if (winOther == win) {
				continue;
			}
			if ((winOther->flags & AG_WINDOW_MODAL) &&
			    (winOther->transientFor == NULL ||	/* App modal */
			     winOther->transientFor == win)) {	/* Parent modal */
				AG_PostEvent(NULL, winOther,
				    "window-modal-close", "%i,%i", x, y);
			}
		}
	}

	OBJECT_FOREACH_CHILD(wid, win, ag_widget)
		PostMouseButtonDown(win, wid, x, y, button);
}

AG_ObjectClass agMouseClass = {
	"Agar(InputDevice:Mouse)",
	sizeof(AG_Mouse),
	{ 0,0 },
	Init,
	NULL,		/* reinit */
	NULL,		/* destroy */
	NULL,		/* load */
	NULL,		/* save */
	NULL		/* edit */
};


text:
var hive = require('hive');

exports = module.exports = hive.Model.extend({
	_name: 'user',
	save: function() {
		var errors = this.validate();
		if(errors) return;
		var password = this.get('password');
		if(password) {
			this.set({password: hive.hash(password)});
		}
		var method = this.isNew() ? 'create' : 'update';
		hive.sync(method, this);
	},
	validate: function() {
		var assert = this.assert;
		return this.describe({
			'email': {
				'you must enter a valid email address': function(email) {
					assert.email(email);
				}
			},
			'password': {
				'you must enter a password': function(password) {
					assert.exists(password);
				},
				'a password must be atleast 4 characters': function(password) {
					if(password) {
						assert.true(password.length >= 4);
					}
				}
			}
		});
	}
});


text:
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 *     Copyright 2018 Couchbase, Inc.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

#pragma once

#include "ep_bucket.h"

#include <folly/portability/GMock.h>

class MockItemFreqDecayerTask;

/*
 * Mock of the EPBucket class.
 */
class MockEPBucket : public EPBucket {
public:
    explicit MockEPBucket(EventuallyPersistentEngine& theEngine);

    MOCK_METHOD5(dropKey,
                 void(Vbid, const DiskDocKey&, int64_t, bool, int64_t));

    /**
     * Mock specific initialization. Does not override initialize function as
     * the general use of this mock requires avoiding the initialization of
     * background tasks
     */
    void initializeMockBucket();

    void createItemFreqDecayerTask();

    void disableItemFreqDecayerTask();

    MockItemFreqDecayerTask* getMockItemFreqDecayerTask();

    VBucketPtr makeVBucket(Vbid id,
                           vbucket_state_t state,
                           KVShard* shard,
                           std::unique_ptr<FailoverTable> table,
                           NewSeqnoCallback newSeqnoCb,
                           std::unique_ptr<Collections::VB::Manifest> manifest,
                           vbucket_state_t initState,
                           int64_t lastSeqno,
                           uint64_t lastSnapStart,
                           uint64_t lastSnapEnd,
                           uint64_t purgeSeqno,
                           uint64_t maxCas,
                           int64_t hlcEpochSeqno,
                           bool mightContainXattrs,
                           const nlohmann::json* replicationTopology,
                           uint64_t maxVisibleSeqno) override;

    void setDurabilityCompletionTask(
            std::shared_ptr<DurabilityCompletionTask> task);

    /// @returns a non-const pointer to Flusher object.
    Flusher* getFlusherNonConst(Vbid vbid);

    void setCollectionsManagerPreSetStateAtWarmupHook(
            std::function<void()> hook);

    void removeMakeCompactionContextCallback();
};


text:
import {ChangeDetectionStrategy, Component, EventEmitter, Input, OnInit, Output, TemplateRef} from '@angular/core'
import {addMonths, eachDayOfInterval, endOfMonth, isBefore, isSameDay, startOfMonth, getDay, isSameWeek} from 'date-fns'

export interface DateRange {
  start: Date | null,
  end: Date | null,
}

export interface YahteeDateRangePickerContext {
  isToday: boolean
  isDisabled: boolean
  isEnabled: boolean
  isStart: boolean
  isEnd: boolean
  isInsideRange: boolean
  isOutsideRange: boolean
  isHighlighted: boolean
  isInsidePotentialRange: boolean
  isFirstRow: boolean
  isLastRow: boolean
  isFirstColumn: boolean
  isLastColumn: boolean
}

export interface DateRangePickerStrategy {
  init(this: YahteeDateRangePickerComponent): void
  select(this: YahteeDateRangePickerComponent, date: Date): void
  focus(this: YahteeDateRangePickerComponent, date: Date): void
  blur(this: YahteeDateRangePickerComponent, date: Date): void
}

const START_STRATEGY: DateRangePickerStrategy = {
  init() {},
  select(this: YahteeDateRangePickerComponent, date: Date): void {
    if (!this.isDisabled(date)) {
      this.dateStart = date
    }
  },
  focus(this: YahteeDateRangePickerComponent, date: Date): void {
    this.highlightedDate = date
  },
  blur(this: YahteeDateRangePickerComponent, date: Date): void {
    this.highlightedDate = null
  },
}

export interface AlternatingStrategyContext {
  brush: 'start' | 'end'
}
const ALTERNATING_START_STRATEGY: DateRangePickerStrategy = {
  init(this: YahteeDateRangePickerComponent): void {
    this.context = {brush: 'start'}
  },
  select(this: YahteeDateRangePickerComponent, date: Date): void {
    if (!this.isDisabled(date)) {
      if (this.context.brush == 'start') {
        // I'm expected to click a start date
        this.dateStart = date
        if (this.dateEnd && isBefore(this.dateEnd, this.dateStart)) {
          // Even though I'm expected to click a start date, I've chosen
          // a date which is after the currently chosen end date.
          // This is invalid because end must come after start.
          // So let's just forget about that old end date.
          this.dateEnd = null
        }
        this.context.brush = 'end'
      } else {
        // I'm expected to click an end date
        if (this.dateStart && isBefore(date, this.dateStart)) {
          // Even though I'm expected to click an end date, I've chosen
          // a date which is before the currently chosen start date.
          // This is invalid because end must come after start.
          // So let' treat this as if it was actually a start date
          this.dateStart = date
          // No context change because we expect the user to input end date now.
        } else {
          // I'm expected to click an end date and I've done so.
          this.dateEnd = date
          this.context.brush = 'start'
        }
      }
    }
  },
  focus(this: YahteeDateRangePickerComponent, date: Date): void {
    this.highlightedDate = date
  },
  blur(this: YahteeDateRangePickerComponent, date: Date): void {
    this.highlightedDate = null
  },
}

@Component({
  selector: 'yahtee-date-range-picker',
  template: `
    <yahtee-dumb-calendar *ngFor="let index of calendarCount | range"
                          [dateTemplate]="dateTemplate"
                          [dayOfWeekTemplate]="dayOfWeekTemplate"
                          [dayContexts]="dayContexts"
                          [displayDate]="displayDate | addMonths : (index * (multipleCalendersDirection == 'past' ? -1 : +1))"
                          [weekStartsOn]="weekStartsOn"
                          [disableOutline]="disableOutline"
                          (dateClick)="onDateClick($event)"
                          (dateMouseEnter)="onDateMouseEnter($event)"
                          (dateMouseLeave)="onDateMouseLeave($event)"
    ></yahtee-dumb-calendar>
  `,
  styles: [`:host {
    display: flex;
  }`],
  changeDetection: ChangeDetectionStrategy.OnPush,
  exportAs: 'yahtee'
})
export class YahteeDateRangePickerComponent implements OnInit {

  @Input() public dateStart: Date | null
  @Input() public dateEnd: Date | null
  @Output() public dateRangeChange = new EventEmitter<DateRange>()

  @Input() public strategy: DateRangePickerStrategy = ALTERNATING_START_STRATEGY

  @Input() public dateTemplate: TemplateRef<YahteeDateRangePickerContext>
  @Input() public dayOfWeekTemplate: TemplateRef<0 | 1 | 2 | 3 | 4 | 5 | 6>

  @Input() public displayDate: Date = new Date()
  @Input() public weekStartsOn: 0 | 1 | 2 | 3 | 4 | 5 | 6 = 1
  @Input() public calendarCount: number = 1
  @Input() public multipleCalendersDirection: 'past' | 'future' = 'past'

  @Input() public disableDates: Date[] = []
  @Input() public disableAllDatesUntil: Date | null = null
  @Input() public disableAllDatesFrom: Date | null = null
  @Input() public allowEnclosingDisabledDates: boolean = false

  @Input() public disableOutline: boolean

  public highlightedDate: Date | null
  public potentialRange: DateRange = {start: null, end: null}

  public context: any = null

  public onDateClick(date: Date): void {
    this.strategy.select.call(this, date)
    this.dateRangeChange.emit({start: this.dateStart, end: this.dateEnd})
  }

  public onDateMouseEnter(date: Date): void {
    this.strategy.focus.call(this, date)
  }

  public onDateMouseLeave(date: Date): void {
    this.strategy.blur.call(this, date)
  }

  public isDisabled(date: Date): boolean {
    return this.disableDates.some(disabledDate => isSameDay(disabledDate, date)) ||
      (!!this.disableAllDatesUntil && isBefore(date, this.disableAllDatesUntil)) ||
      (!!this.disableAllDatesFrom && isBefore(this.disableAllDatesFrom, date))
  }

  public isInsidePotentialRangeInclusive(date: Date): boolean {
    return !!this.potentialRange.start && !!this.potentialRange.end &&
      (
        (isBefore(this.potentialRange.start, date) && isBefore(date, this.potentialRange.end))
        ||
        isSameDay(this.potentialRange.start, date)
        ||
        isSameDay(this.potentialRange.end, date)
      )
  }

  public getContextFor(date: Date): YahteeDateRangePickerContext {
    const isSameAs = isSameDay.bind(null, date) as (date: Date) => boolean

    const isToday = isSameAs(new Date())
    const isDisabled = this.isDisabled(date)
    const isStart = !!this.dateStart && isSameAs(this.dateStart)
    const isEnd = !!this.dateEnd && isSameAs(this.dateEnd)
    const isInsideRange = this.dateStart != null &&
      this.dateEnd != null &&
      isBefore(this.dateStart, date) &&
      isBefore(date, this.dateEnd)
    const isHighlighted = !!this.highlightedDate && isSameAs(this.highlightedDate)
    const isInsidePotentialRange = this.isInsidePotentialRangeInclusive(date)

    const weekNumber = getDay(date)

    const isFirstColumn = weekNumber == this.weekStartsOn
    const isLastColumn = weekNumber == (this.weekStartsOn + 6) % 7
    const isFirstRow = isSameWeek(startOfMonth(date), date, {weekStartsOn: this.weekStartsOn})
    const isLastRow = isSameWeek(endOfMonth(date), date, {weekStartsOn: this.weekStartsOn})

    return {
      isToday,
      isDisabled,
      isEnabled: !isDisabled,
      isStart,
      isEnd,
      isInsideRange,
      isOutsideRange: !isInsideRange,
      isHighlighted,
      isInsidePotentialRange,
      isFirstRow,
      isLastRow,
      isFirstColumn,
      isLastColumn,
    }
  }

  public get dayContexts() {
    // TODO: This is run too often
    const dayContexts = new Map<string, YahteeDateRangePickerContext>()
    const [start, end] = [startOfMonth(this.displayDate), endOfMonth(addMonths(this.displayDate, this.calendarCount))]
    eachDayOfInterval({start, end}).forEach(day => {
      const iso = day.toISOString()
      const context = this.getContextFor(day)
      dayContexts.set(iso, context)
    })
    return dayContexts
  }

  public ngOnInit(): void {
    this.strategy.init.call(this)
  }

}


text:
package jetbrains.exodus.entitystore.iterate;

import jetbrains.exodus.ByteIterable;
import jetbrains.exodus.bindings.ComparableBinding;
import jetbrains.exodus.bindings.ComparableSet;
import jetbrains.exodus.bindings.ComparableValueType;
import jetbrains.exodus.bindings.LongBinding;
import jetbrains.exodus.entitystore.*;
import jetbrains.exodus.entitystore.tables.PropertyKey;
import jetbrains.exodus.entitystore.tables.PropertyValue;
import jetbrains.exodus.env.Cursor;
import jetbrains.exodus.env.Store;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

@SuppressWarnings({"RawUseOfParameterizedType"})
public class PropertiesIterable extends EntityIterableBase {

    private final int entityTypeId;
    private final int propertyId;

    static {
        registerType(getType(), (txn, store, parameters) -> new PropertiesIterable(txn, Integer.parseInt((String) parameters[0]), Integer.parseInt((String) parameters[1])));
    }

    private static EntityIterableType getType() {
        return EntityIterableType.ENTITIES_WITH_PROPERTY_SORTED_BY_VALUE;
    }

    public int getEntityTypeId() {
        return entityTypeId;
    }

    public PropertiesIterable(@NotNull final PersistentStoreTransaction txn, final int entityTypeId, final int propertyId) {
        super(txn);
        this.entityTypeId = entityTypeId;
        this.propertyId = propertyId;
    }

    @Override
    public boolean isSortedById() {
        return false;
    }

    @Override
    @NotNull
    public EntityIteratorBase getIteratorImpl(@NotNull final PersistentStoreTransaction txn) {
        final PropertiesIterator result = getIterator(txn, true);
        if (result == null) {
            return EntityIteratorBase.EMPTY;
        }
        return result;
    }

    @Override
    public boolean nonCachedHasFastCountAndIsEmpty() {
        return true;
    }

    @NotNull
    @Override
    public EntityIterator getReverseIteratorImpl(@NotNull final PersistentStoreTransaction txn) {
        final PropertiesIterator result = getIterator(txn, false);
        if (result == null) {
            return EntityIteratorBase.EMPTY;
        }
        return result;
    }

    @Override
    @NotNull
    protected EntityIterableHandle getHandleImpl() {
        return new PropertiesIterableHandle();
    }

    @Override
    protected CachedInstanceIterable createCachedInstance(@NotNull final PersistentStoreTransaction txn) {
        return UpdatablePropertiesCachedInstanceIterable.newInstance(txn, getIterator(txn, true), this);
    }

    @Override
    protected long countImpl(@NotNull final PersistentStoreTransaction txn) {
        final Store valueIndex = getStore().getPropertiesTable(txn, entityTypeId).getValueIndex(txn, propertyId, false);
        return valueIndex == null ? 0 : valueIndex.count(txn.getEnvironmentTransaction());
    }

    @Override
    public boolean isEmptyImpl(@NotNull final PersistentStoreTransaction txn) {
        return countImpl(txn) == 0;
    }

    private Cursor openCursor(@NotNull final PersistentStoreTransaction txn) {
        return getStore().getPropertyValuesIndexCursor(txn, entityTypeId, propertyId);
    }

    private PropertiesIterator getIterator(@NotNull final PersistentStoreTransaction txn, final boolean ascending) {
        try (Cursor primaryIndex = getStore().getPrimaryPropertyIndexCursor(txn, entityTypeId)) {
            final Cursor valueIdx = openCursor(txn);
            if (valueIdx == null) {
                return null;
            }
            return new PropertiesIterator(valueIdx, primaryIndex, ascending);
        }
    }

    /**
     * Public access is needed in order to access directly from PersistentStoreTransaction.
     */

    private final class PropertiesIterableHandle extends ConstantEntityIterableHandle {

        public PropertiesIterableHandle() {
            super(PropertiesIterable.this.getStore(), PropertiesIterable.getType());
        }

        @NotNull
        @Override
        public int[] getPropertyIds() {
            return new int[]{propertyId};
        }

        @Override
        public void toString(@NotNull final StringBuilder builder) {
            super.toString(builder);
            builder.append(entityTypeId);
            builder.append('-');
            builder.append(propertyId);
        }

        @Override
        public void hashCode(@NotNull final EntityIterableHandleHash hash) {
            hash.apply(entityTypeId);
            hash.applyDelimiter();
            hash.apply(propertyId);
        }

        @Override
        public int getEntityTypeId() {
            return entityTypeId;
        }

        @Override
        public boolean isMatchedPropertyChanged(@NotNull final EntityId id,
                                                final int propertyId,
                                                @Nullable final Comparable oldValue,
                                                @Nullable final Comparable newValue) {
            return PropertiesIterable.this.propertyId == propertyId && entityTypeId == id.getTypeId();
        }

        @Override
        public boolean onPropertyChanged(@NotNull PropertyChangedHandleChecker handleChecker) {
            UpdatablePropertiesCachedInstanceIterable iterable
                = PersistentStoreTransaction.getUpdatable(handleChecker, this, UpdatablePropertiesCachedInstanceIterable.class);
            if (iterable != null) {
                final Comparable oldValue = handleChecker.getOldValue();
                final Comparable newValue = handleChecker.getNewValue();
                final long localId = handleChecker.getLocalId();
                if (oldValue instanceof ComparableSet || newValue instanceof ComparableSet) {
                    //noinspection ConstantConditions
                    final ComparableSet oldSet = (ComparableSet) oldValue;
                    final ComparableSet newSet = (ComparableSet) newValue;
                    if (oldSet != null) {
                        //noinspection unchecked
                        for (final Comparable item : (Iterable<? extends Comparable>) oldSet.minus(newSet)) {
                            iterable.update(entityTypeId, localId, item, null);
                        }
                    }
                    if (newSet != null) {
                        //noinspection unchecked
                        for (final Comparable item : (Iterable<? extends Comparable>) newSet.minus(oldSet)) {
                            iterable.update(entityTypeId, localId, null, item);
                        }
                    }
                } else {
                    iterable.update(entityTypeId, localId, oldValue, newValue);
                }
                return true;
            }
            return false;
        }
    }

    /**
     * Public access is needed in order to access directly from SortIterator.
     */
    private final class PropertiesIterator extends EntityIteratorBase implements PropertyValueIterator {

        private boolean hasNext;
        private final boolean ascending;
        private final ComparableBinding binding;
        @Nullable
        private ByteIterable currentCursorKey;
        @Nullable
        private Comparable currentValue;

        private PropertiesIterator(@NotNull final Cursor secondaryIndex,
                                   @NotNull final Cursor primaryIndex,
                                   final boolean ascending) {
            super(PropertiesIterable.this);
            setCursor(secondaryIndex);
            this.ascending = ascending;
            //noinspection AssignmentUsedAsCondition
            if (hasNext = getNext(secondaryIndex)) {
                final long entityLocalId = LongBinding.compressedEntryToLong(secondaryIndex.getValue());
                final ByteIterable value = primaryIndex.getSearchKey(
                    PropertyKey.propertyKeyToEntry(new PropertyKey(entityLocalId, propertyId)));
                if ((hasNext = value != null)) {
                    final PropertyValue propertyValue = getStore().getPropertyTypes().entryToPropertyValue(value);
                    if (propertyValue.getType().getTypeId() != ComparableValueType.COMPARABLE_SET_VALUE_TYPE) {
                        binding = propertyValue.getBinding();
                    } else {
                        final Class itemClass = ((ComparableSet) propertyValue.getData()).getItemClass();
                        if (itemClass == null) {
                            throw new NullPointerException("Can't be: null item class for a non-empty ComparableSet");
                        }
                        //noinspection unchecked
                        binding = getStore().getPropertyTypes().getPropertyType(itemClass).getBinding();
                    }
                } else {
                    binding = null;
                }
            } else {
                binding = null;
            }
        }

        @Override
        public boolean hasNextImpl() {
            if (hasNext) {
                final ByteIterable key = getCursor().getKey();
                if (key != currentCursorKey) { // equality check to boost BTreeDup same-key access
                    currentValue = binding.entryToObject(key);
                    currentCursorKey = key;
                }
            } else {
                currentValue = null;
                currentCursorKey = null;
            }
            return hasNext;
        }

        @Override
        @Nullable
        public EntityId nextIdImpl() {
            if (hasNextImpl()) {
                explain(getType());
                final Cursor cursor = getCursor();
                final EntityId result = new PersistentEntityId(entityTypeId, LongBinding.compressedEntryToLong(cursor.getValue()));
                hasNext = getNext(cursor);
                return result;
            }
            return null;
        }

        @Override
        @Nullable
        public Comparable currentValue() {
            return currentValue;
        }

        private boolean getNext(@NotNull final Cursor cursor) {
            return ascending ? cursor.getNext() : cursor.getPrev();
        }
    }
}


text:
package darks.grid.executor.job;

import java.io.Serializable;
import java.util.List;

import darks.grid.executor.ExecuteConfig;
import darks.grid.executor.ExecuteConfig.ResponseType;
import darks.grid.executor.task.GridTask;
import darks.grid.executor.task.GridTask.TaskType;
import darks.grid.utils.UUIDUtils;

public abstract class GridJob implements Serializable
{

	/**
	 *
	 */
	private static final long serialVersionUID = -6904973711082130126L;

	private String jobId = UUIDUtils.newUUID();

    private String taskId;

	private TaskType taskType;

	private boolean failRedo = true;

	private boolean callback = true;

	private int timeout = 0;

	public GridJob()
	{

	}

    public void setTask(GridTask task, ExecuteConfig config)
    {
        this.taskId = task.getId();
        this.taskType = task.getTaskType();
        this.callback = config.getResponseType() != ResponseType.NONE;
        this.timeout = config.getTimeout();
    }

    public abstract Object execute();

    public abstract <P> P getParameter();

    public abstract <P> P getParameter(int pos);

    public abstract List<Object> getParameterList();

    public abstract boolean isEmpty();

	public String getTaskId()
	{
		return taskId;
	}

	public void setTaskId(String taskId)
	{
		this.taskId = taskId;
	}

	public String getJobId()
	{
		return jobId;
	}

	public boolean isFailRedo()
	{
		return failRedo;
	}

	public void setFailRedo(boolean failRedo)
	{
		this.failRedo = failRedo;
	}

	public TaskType getTaskType()
    {
        return taskType;
    }

    public void setTaskType(TaskType taskType)
    {
        this.taskType = taskType;
    }

    public boolean isCallback()
    {
        return callback;
    }

    public void setCallback(boolean callback)
    {
        this.callback = callback;
    }

    public int getTimeout()
	{
		return timeout;
	}

	public void setTimeout(int timeout)
	{
		this.timeout = timeout;
	}

	@Override
	public String toString()
	{
		return "GridJob [jobId=" + jobId + ", taskId=" + taskId + ", taskType=" + taskType
				+ ", failRedo=" + failRedo + ", callback=" + callback + ", timeout=" + timeout
				+ "]";
	}

}


text:
#ifndef __itkMeanSampleFilter_h
#define __itkMeanSampleFilter_h

#include "itkProcessObject.h"
#include "itkArray.h"
#include "itkSimpleDataObjectDecorator.h"

namespace itk
{
namespace Statistics
{
/** \class MeanSampleFilter
 * \brief Given a sample, this filter computes the sample mean
 *
 * The sample is plugged in using SetSample method. Then invoke
 * update() method to compute the sample mean.
 *
 * The sample mean is computed as follows
 * \f$ = \frac{1}{n}\sum^{n}_{i=1}x_{i}\f$ where \f$n\f$ is the
 * number of measurement vectors in the target
 *
 * Recent API changes:
 * The static const macro to get the length of a measurement vector,
 * 'MeasurementVectorSize'  has been removed to allow the length of a measurement
 * vector to be specified at run time. It is now obtained from the input sample.
 * Please use the function GetMeasurementVectorSize() to obtain the length.
 * \ingroup ITKStatistics
 */

template< class TSample >
class MeanSampleFilter:public ProcessObject
{
public:
  /**Standard class typedefs. */
  typedef MeanSampleFilter           Self;
  typedef ProcessObject              Superclass;
  typedef SmartPointer< Self >       Pointer;
  typedef SmartPointer< const Self > ConstPointer;
  typedef TSample                    SampleType;

  /**Standard Macros */
  itkTypeMacro(MeanSampleFilter, ProcessObject);
  itkNewMacro(Self);

  /** Length of a measurement vector */
  typedef unsigned int                                                MeasurementVectorSizeType;
  typedef typename TSample::MeasurementVectorType                     MeasurementVectorType;
  typedef typename TSample::MeasurementType                           MeasurementType;
  typedef typename NumericTraits< MeasurementType >::RealType         MeasurementRealType;
  typedef typename NumericTraits< MeasurementVectorType >::RealType   MeasurementVectorRealType;

  /** Method to set/get the sample */
  using Superclass::SetInput;
  void SetInput(const SampleType *sample);

  const SampleType *  GetInput() const;

  /** MeasurementVector is not a DataObject, we need to decorate it to push it down
   * a ProcessObject's pipeline */
  typedef  SimpleDataObjectDecorator< MeasurementVectorRealType > MeasurementVectorDecoratedType;

  typedef MeasurementVectorDecoratedType OutputType;

  /** Get the mean measurement vector */
  const MeasurementVectorDecoratedType * GetOutput() const;

  const MeasurementVectorRealType GetMean() const;

  MeasurementVectorSizeType GetMeasurementVectorSize() const;

protected:
  MeanSampleFilter();
  virtual ~MeanSampleFilter();
  void PrintSelf(std::ostream & os, Indent indent) const;

  /** DataObject pointer */
  typedef DataObject::Pointer DataObjectPointer;

  typedef ProcessObject::DataObjectPointerArraySizeType DataObjectPointerArraySizeType;
  using Superclass::MakeOutput;
  virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType idx);

  void GenerateData();

private:
  MeanSampleFilter(const Self &); //purposely not implemented
  void operator=(const Self &);   //purposely not implemented
};                                // end of class
} // end of namespace Statistics
} // end of namespace itk

#ifndef ITK_MANUAL_INSTANTIATION
#include "itkMeanSampleFilter.hxx"
#endif

#endif


text:
using CartaMei.Common;
using System.Windows;
using System.Windows.Controls;

namespace CartaMei.WPF
{
    public class ObjectTemplateSelector : DataTemplateSelector
    {
        public DataTemplate MapTemplate { get; set; }
        public DataTemplate MapObjectTemplate { get; set; }

        public override DataTemplate SelectTemplate(object item, DependencyObject container)
        {
            return item as IMap != null ? this.MapTemplate : this.MapObjectTemplate;
        }
    }
}


text:
// <copyright file="FindSelectedOptionProperties.cs" company="WebDriver Committers">
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>

using System.Collections.Generic;
using System.Collections.ObjectModel;
using OpenQA.Selenium;

namespace Selenium.Internal.SeleniumEmulation
{
    /// <summary>
    /// Defines the command for the findSelectedOptionProperties keyword.
    /// </summary>
    internal class FindSelectedOptionProperties : SeleneseCommand
    {
        private ElementFinder finder;
        private string property;

        /// <summary>
        /// Initializes a new instance of the <see cref="FindSelectedOptionProperties"/> class.
        /// </summary>
        /// <param name="finder">A <see cref="ElementFinder"/> that gets options from the element.</param>
        /// <param name="property">The property on which to select the options.</param>
        public FindSelectedOptionProperties(ElementFinder finder, string property)
        {
            this.finder = finder;
            this.property = property;
        }

        /// <summary>
        /// Handles the command.
        /// </summary>
        /// <param name="driver">The driver used to execute the command.</param>
        /// <param name="locator">The first parameter to the command.</param>
        /// <param name="value">The second parameter to the command.</param>
        /// <returns>The result of the command.</returns>
        protected override object HandleSeleneseCommand(IWebDriver driver, string locator, string value)
        {
            SeleniumSelect select = new SeleniumSelect(this.finder, driver, locator);
            ReadOnlyCollection<IWebElement> allOptions = select.SelectedOptions;
            List<string> values = new List<string>();

            foreach (IWebElement element in allOptions)
            {
                values.Add(element.GetAttribute(this.property));
            }

            return values.ToArray();
        }
    }
}


text:
require 'xero_priv_auth/version'

module XeroPrivAuth
  # Your code goes here...
end


text:
/**
 *  Defines the module userMap for AngularJS. It's controller and template are
 *  defined in user_position_map.component.js
 *  DEPRECATED: This file is part of the old version 1 of the MADCAP web application. Please use v2 modules in combination with the master instead.
 */
angular.module('timeline', []);


text:
package scalafiddle.server

import org.slf4j.LoggerFactory
import upickle.Js
import upickle.default._

import scala.io.BufferedSource
import scalafiddle.shared._

class Librarian(libSource: () => BufferedSource) {

  case class LibraryVersion(
      version: String,
      scalaVersions: Seq[String],
      scalaJSVersions: Seq[String],
      extraDeps: Seq[String],
      organization: Option[String],
      artifact: Option[String],
      doc: Option[String],
      example: Option[String]
  )

  implicit val libraryVersionReader = upickle.default.Reader[LibraryVersion] {
    case Js.Obj(valueSeq @ _*) =>
      val values = valueSeq.toMap
      LibraryVersion(
        readJs[String](values("version")),
        readJs[Seq[String]](values("scalaVersions")),
        values.get("scalaJSVersions").map(readJs[Seq[String]]).getOrElse(Seq("0.6")),
        readJs[Seq[String]](values.getOrElse("extraDeps", Js.Arr())),
        values.get("organization").map(readJs[String]),
        values.get("artifact").map(readJs[String]),
        values.get("doc").map(readJs[String]),
        values.get("example").map(readJs[String])
      )
  }

  case class LibraryDef(
      name: String,
      organization: String,
      artifact: String,
      doc: String,
      versions: Seq[LibraryVersion],
      compileTimeOnly: Boolean
  )

  case class LibraryGroup(
      group: String,
      libraries: Seq[LibraryDef]
  )

  val repoSJSRE = """([^ %]+) *%%% *([^ %]+) *% *([^ %]+)""".r
  val repoRE    = """([^ %]+) *%% *([^ %]+) *% *([^ %]+)""".r
  val log       = LoggerFactory.getLogger(getClass)
  var libraries = Seq.empty[Library]
  refresh()

  def refresh(): Unit = {
    try {
      log.debug(s"Loading libraries...")
      val newLibs = loadLibraries
      log.debug(s"  loaded ${newLibs.size} libraries")
      libraries = newLibs
    } catch {
      case e: Throwable =>
        log.error(s"Error loading libraries", e)
    }
  }

  def loadLibraries: Seq[Library] = {
    val data      = libSource().mkString
    val libGroups = read[Seq[LibraryGroup]](data)
    for {
      (group, idx) <- libGroups.zipWithIndex
      lib          <- group.libraries
      versionDef   <- lib.versions
    } yield {
      Library(
        lib.name,
        versionDef.organization.getOrElse(lib.organization),
        versionDef.artifact.getOrElse(lib.artifact),
        versionDef.version,
        lib.compileTimeOnly,
        versionDef.scalaVersions,
        versionDef.scalaJSVersions,
        versionDef.extraDeps,
        f"$idx%02d:${group.group}",
        createDocURL(versionDef.doc.getOrElse(lib.doc)),
        versionDef.example
      )
    }
  }

  def findLibrary(libDef: String): Option[Library] = libDef match {
    case repoSJSRE(group, artifact, version) =>
      libraries.find(l => l.organization == group && l.artifact == artifact && l.version == version && !l.compileTimeOnly)
    case repoRE(group, artifact, version) =>
      libraries.find(l => l.organization == group && l.artifact == artifact && l.version == version && l.compileTimeOnly)
    case _ =>
      None
  }

  private def createDocURL(doc: String): String = {
    val githubRef = """([^/]+)/([^/]+)""".r
    doc match {
      case githubRef(org, lib) => s"https://github.com/$org/$lib"
      case _                   => doc
    }
  }
}


text:
#import "TSharedProcessorFactory.h"

@interface TSharedProcessorFactory ()

@property(strong, nonatomic) id<TProcessor> sharedProcessor;

@end

@implementation TSharedProcessorFactory

-(id) initWithSharedProcessor:(id<TProcessor>)sharedProcessor
{
  self = [super init];
  if (self) {
    _sharedProcessor = sharedProcessor;
  }

  return self;
}

-(id<TProcessor>) processorForTransport:(id<TTransport>)transport
{
  return _sharedProcessor;
}

@end


text:
If you've found and fixed a bug, or have a new feature you would like to add we would love you to chip in.

Here are a few tips
* To make sure your pull-request makes it into the project please ensure you carefully read the
[Engineering guidelines](ENGINEERING-GUIDELINES.md)
* We have a well defined workflow. Before you lodge a pull-request check out our guide to the [Contributing Process](CONTRIBUTING-PROCESS.md)
* Make sure you can build the code.
  (Even better, configure continuous deployment and provide a link to your branch deployed and working)
* If you don't know what a pull request is read this article: [Using pull requests](https://help.github.com/articles/using-pull-requests).
* Check out these two blogs posts on contributing code: [Open Source Contribution Etiquette](http://tirania.org/blog/archive/2010/Dec-31.html) by Miguel de Icaza and [Don't "Push" Your Pull Requests](https://www.igvita.com/2011/12/19/dont-push-your-pull-requests/) by Ilya Grigorik.
* Note that all code submissions will be rigorously reviewed and tested by the SSW team, and only those that meet an extremely high bar for both quality and design/roadmap appropriateness will be merged into the source.

## Contributing Overview

1. Discuss your your proposed change

2. For the repo and implement your change / fix / feature

3. Get a code review & feedback

4. Submit a pull request

## Discuss your proposed change

* **For suggested features or substantial code contributions** please discuss it with the team and ensure it follows the product roadmap. We don't want you investing a lot of time developing something that may not be included in the project because it doesn't fix with the core contributors plans for the project.

* **For small changes / bug fixes ** open a GitHub issue, include your problem or suggestion and how you intend to implement it. Getting feedback will help ensure the quickest path to a successful pull request.

* May of our projects have **Community Standups** where you can join a real-time video discussion of the core teams plans for the upcoming sprint. The details for your projects community standup will be on the Readme.md for that project.

## Code reviews and checkins

To help ensure that only the highest quality code makes its way into the project, please submit all your code changes to GitHub as PRs. This includes runtime code changes, unit test updates, and updates to official samples (e.g. Music Store). For example, sending a PR for just an update to a unit test might seem like a waste of time but the unit tests are just as important as the product code and as such, reviewing changes to them is also just as important.

The advantages are numerous: improving code quality, more visibility on changes and their potential impact, avoiding duplication of effort, and creating general awareness of progress being made in various areas.

In general a PR should be signed off (using the :shipit: `:shipit:` emoticon) by the Subject Matter Expert (SME) of that code. For example, a change to the Banana project should be signed off by `@MrMonkey`, and not by `@MrsGiraffe`. If you don't know the SME, please talk to one of the engineering leads and they will be happy to help you identify the SME. Of course, sometimes it's the SME who is making a change, in which case a secondary person will have to sign off on the change (e.g. `@JuniorMonkey`).

To commit the PR to the repo **do not use the Big Green Button**. Instead, do a typical push that you would use with Git (e.g. local pull, rebase, merge, push).

TODO: Rule - 'Do You Know How To Submit Pull Requests'

## Branch strategy

TODO: To be updated to reflect GitHub flow

In general:

* `master` has the code for the latest release on NuGet.org (e.g. alpha, beta, RC, RTM)
* `dev` has the code that is being worked on but not yet released. This is the branch into which devs normally submit pull requests and merge changes into.
* `release` has the code that is being staged and stabilized for an upcoming release

Shortly before a release, the `release` branches are created from `dev`, and stabilization work happens there. Post-release work continus in the `dev` branch. Once the release takes place, the code is pushed from `release` to `master`.

## Commit/Pull Request Format

```
Summary of the changes (Less than 80 chars)
 - Detail 1
 - Detail 2

Addresses #bugnumber (in this specific format)
```


text:
module Loggly
  class Model
    include Logging

    METADATA_KEYS = {}

    attr_accessor :attributes, :response

    def initialize(attributes = {})
      @attributes = OpenStruct.new(attributes)
      @response = nil
    end

    def to_hash
      @attributes.marshal_dump
    end

    def to_json(pretty = false)
      MultiJson.dump(self.to_hash, :pretty => pretty)
    end

    def to_log(options = {})
      self.to_json(true)
    end

    module ClassMethods

      def from_hash(h)
        new h
      end

      def from_json(s)
        from_hash MultiJson.load(s, :symbolize_keys => true)
      end

    end

    extend ClassMethods

  end
end


text:
Parser::Parser() : _validScene(false) {
  _shapes.emplace("Sphere", [this]() { _objects.emplace_back(new Sphere()); });
  _shapes.emplace("Rectangle",
                  [this]() { _objects.emplace_back(new Rectangle()); });
  _shapes.emplace("Light", [this]() { _lights.emplace_back(new Light()); });

  _elements.emplace("Camera",
                    ParsableWrapper(_camera, [this]() { _validScene = true; }));
}

bool Parser::parse(const std::string &fileName) {
  std::ifstream file;
  bool ret = false;

  file.open(fileName);
  if (file.is_open()) {
    ret = this->readFile(file);
    file.close();
  } else
    std::cerr << "Could not open the file named \"" << fileName << "\""
              << std::endl;
  return ret;
}

bool Parser::readFile(std::ifstream &file) {
  std::string line;
  std::string keyword;
  std::size_t pos;
  Parsable *obj = nullptr;

  while (std::getline(file, line)) {
    std::stringstream ss(line);

    if (line.empty())
      continue;
    pos = line.find_first_of(" \t");
    if (pos == std::string::npos)
      pos = line.size();
    else
      ++pos;
    keyword = line.substr(0, pos);

    auto it = _shapes.find(keyword);
    if (it == _shapes.end()) {
      auto it2 = _elements.find(keyword);

      if (it2 == _elements.end()) {
        if (obj == nullptr)
          continue;
        else
          obj->parseArgs(ss);
      } else {
        it2->second.callback();
        obj = std::addressof(it2->second.obj);
      }
    } else {
      it->second();
      if (keyword.compare("Light") == 0)
        obj = _lights.back().get();
      else
        obj = _objects.back().get();
    }
  }
  return true;
}

const std::vector<std::shared_ptr<SceneObj>> &Parser::getObjects() const {
  return _objects;
}

const std::vector<std::shared_ptr<Light>> &Parser::getLights() const {
  return _lights;
}

const Camera &Parser::getCamera() const { return _camera; }


text:
package com.example.joshua.quiz.Fragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.joshua.quiz.AndroidBus;
import com.example.joshua.quiz.R;
import com.example.joshua.quiz.event.QuestionAnswerEvent;
import com.squareup.picasso.Picasso;

import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.InjectViews;
import butterknife.OnClick;

/**
 * Fragment to display the question
 */
public class QuizQuestionFragment extends Fragment {
    private static final String ARG_CURRENT_NO = "CURRENT_NO";
    private static final String ARG_TITLE = "TITLE";
    private static final String ARG_IMAGES = "IMAGES";
    public static final String TAG = "QUESTION";

    private int mQuestionNumber;
    private String mTitle;
    private String mCurrentAnswer;
    private String[] mAnswers;

    @InjectView(R.id.question_number) TextView questionNumberView;
    @InjectView(R.id.title) TextView titleTextView;
    @InjectView(R.id.submit) Button submitButton;
    @InjectViews({R.id.image1, R.id.image2, R.id.image3, R.id.image4}) List<ImageView> answersViews;
    @InjectViews({R.id.background1, R.id.background2, R.id.background3, R.id.background4})
    List<View> backgroundViews;

    /**
     * Factory method to create a new instance of * this fragment to display the question
     *
     * @param questionNumber the question number
     * @param title          the description of the question
     * @param answers        the image urls of the answers
     * @return A new instance of fragment QuizQuestionFragment.
     */
    public static QuizQuestionFragment newInstance(int questionNumber, String title, List<String> answers) {
        String[] images = new String[answers.size()];
        answers.toArray(images);

        QuizQuestionFragment fragment = new QuizQuestionFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_CURRENT_NO, questionNumber);
        args.putString(ARG_TITLE, title);
        args.putStringArray(ARG_IMAGES, images);
        fragment.setArguments(args);
        return fragment;
    }

    public QuizQuestionFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mQuestionNumber = getArguments().getInt(ARG_CURRENT_NO);
            mTitle = getArguments().getString(ARG_TITLE);
            mAnswers = getArguments().getStringArray(ARG_IMAGES);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_quiz_question, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        ButterKnife.inject(this, view);

        // setup ui
        questionNumberView.setText(getString(R.string.question, mQuestionNumber));
        titleTextView.setText(mTitle);
        submitButton.setEnabled(false);

        for (int i = 0; i < mAnswers.length; i++) {
            String answer = mAnswers[i];
            Picasso.with(getActivity()).load(answer).into(answersViews.get(i));
        }
    }

    @OnClick(R.id.submit)
    void submit() {
        AndroidBus.getInstance().post(new QuestionAnswerEvent(mQuestionNumber, mCurrentAnswer));
    }

    @OnClick({R.id.background1, R.id.background2, R.id.background3, R.id.background4})
    public void pickAnswer(View pickedView) {
        for (int i = 0; i < backgroundViews.size(); i++) {
            View view = backgroundViews.get(i);
            view.setSelected(view.equals(pickedView));
            if (view.equals(pickedView)) {
                mCurrentAnswer = mAnswers[i];
            }
        }
        submitButton.setEnabled(true);
    }

}


text:
layout: page
title: About DiPP
---

Data in Public Policy (DIPP) is a student organization at the University of Chicago Harris School for Public Policy founded to build analytical skills and expertise among Harris students in open-source data platforms, foster a professional relationship with the data and tech community in Chicago, and to generally serve as a resource for Harris students interested in the intersection of data and public policy.  Created informally in Fall 2012, DIPP launched as an official Harris Student Organization in Fall 2013.

DiPP Newsletter

<button style="float:right; margin-left: 5px;" type="button" onclick="window.location.href='http://eepurl.com/40NIn';">Sign Up</button>

We send a weekly newsletter announcing DiPP events, Data in the News, Hack Harris tutorials and workshops, job opportunities, and other ways to get involved.

This Website

We developed this website ourselves on the GitHub platform using Jekyll and Hyde. You can help us make it better by finding us on GitHub and reading our wiki on how to contribute.

Join Us

To receive our newsletter and learn about upcoming events, job opportunities, tutorials, and more, sign up here. You can also follow us on Twitter.

Executive Board

Bridgit Donnelly

Second-year MSCAPP student

Aaron Politsky

Second-year MPP student

Kyle Magida

Second-year MSCAPP student

Alex Warofka

Second-year MPP student

Shafia Imtiaz

Second-year MPP student

Xiaorui Tang

Second-year MSCAPP student


text:
importScripts('bootFOAMWorker.js');

foam.CLASS({
  name: 'SharedWorker',
  extends: 'foam.apps.chat.SharedWorkerI',

  imports: [
    'registry'
  ],

  exports: [
    'messageDAO'
  ],

  topics: [
    'journalUpdate'
  ],

  properties: [
    {
      name: 'syncAgent',
      factory: function() {
        return foam.apps.chat.FgSyncAgent.create(null, this);
      }
    },
    {
      name: 'messageDAO',
      factory: function() {
        return foam.apps.chat.MessageDAO.create(null, this);
      }
    },
    {
      name: 'remoteMessageDAO',
      factory: function() {
        return foam.apps.chat.RemoteMessageDAO.create(null, this);
      }
    }
  ],

  methods: [
    function init() {
      this.registry.register(
        'messageDAO',
        null,
        foam.box.SkeletonBox.create({
          data: this.messageDAO
        }, this));

      this.registry.register(
        'control',
        null,
        foam.box.SkeletonBox.create({
          data: this,
        }, this));

      this.messageDAO.outboundJournal.on.sub(this.onJournalUpdate);

      this.remoteMessageDAO.on.sub(this.onJournalUpdate);
      this.remoteMessageDAO.delegate.startEvents();

      this.sync();
    },

    function sync() {
      this.syncAgent.sync.sync();
    }
  ],

  listeners: [
    {
      name: 'onJournalUpdate',
      isMerged: 100,
      code: function() {
        this.journalUpdate.pub();
      }
    }
  ]
});

var env = foam.apps.chat.Context.create();
env.messagePortService.source = self;

var agent = SharedWorker.create(null, env);


text:
import logging
import optparse
import os
import shutil
import sys
import zipfile

from telemetry import decorators
from telemetry.core import browser_finder
from telemetry.core import command_line
from telemetry.core import util
from telemetry.page import page_runner
from telemetry.page import cloud_storage
from telemetry.page import page_set
from telemetry.page import page_test
from telemetry.page import test_expectations
from telemetry.results import page_test_results

Disabled = decorators.Disabled
Enabled = decorators.Enabled

class Test(command_line.Command):
  """Base class for a Telemetry test or benchmark.

  A test packages a PageTest/PageMeasurement and a PageSet together.
  """
  options = {}

  @classmethod
  def Name(cls):
    name = cls.__module__.split('.')[-1]
    if hasattr(cls, 'tag'):
      name += '.' + cls.tag
    if hasattr(cls, 'page_set'):
      name += '.' + cls.page_set.Name()
    return name

  @classmethod
  def AddCommandLineArgs(cls, parser):
    cls.PageTestClass().AddCommandLineArgs(parser)

    if hasattr(cls, 'AddTestCommandLineArgs'):
      group = optparse.OptionGroup(parser, '%s test options' % cls.Name())
      cls.AddTestCommandLineArgs(group)
      parser.add_option_group(group)

  @classmethod
  def SetArgumentDefaults(cls, parser):
    cls.PageTestClass().SetArgumentDefaults(parser)
    parser.set_defaults(**cls.options)

  @classmethod
  def ProcessCommandLineArgs(cls, parser, args):
    cls.PageTestClass().ProcessCommandLineArgs(parser, args)

  def CustomizeBrowserOptions(self, options):
    """Add browser options that are required by this benchmark."""

  def Run(self, args):
    """Run this test with the given options."""
    self.CustomizeBrowserOptions(args.browser_options)

    test = self.PageTestClass()()
    test.__name__ = self.__class__.__name__

    if hasattr(self, '_disabled_strings'):
      test._disabled_strings = self._disabled_strings
    if hasattr(self, '_enabled_strings'):
      test._enabled_strings = self._enabled_strings

    ps = self.CreatePageSet(args)
    expectations = self.CreateExpectations(ps)

    self._DownloadGeneratedProfileArchive(args)

    results = page_test_results.PageTestResults()
    try:
      results = page_runner.Run(test, ps, expectations, args)
    except page_test.TestNotSupportedOnPlatformFailure as failure:
      logging.warning(str(failure))

    results.PrintSummary()
    return len(results.failures) + len(results.errors)

  def _DownloadGeneratedProfileArchive(self, options):
    """Download and extract profile directory archive if one exists."""
    archive_name = getattr(self, 'generated_profile_archive', None)

    # If attribute not specified, nothing to do.
    if not archive_name:
      return

    # If profile dir specified on command line, nothing to do.
    if options.browser_options.profile_dir:
      logging.warning("Profile directory specified on command line: %s, this"
          "overrides the benchmark's default profile directory.",
          options.browser_options.profile_dir)
      return

    # Download profile directory from cloud storage.
    found_browser = browser_finder.FindBrowser(options)
    test_data_dir = os.path.join(util.GetChromiumSrcDir(), 'tools', 'perf',
        'generated_profiles',
        found_browser.target_os)
    generated_profile_archive_path = os.path.normpath(
        os.path.join(test_data_dir, archive_name))

    try:
      cloud_storage.GetIfChanged(generated_profile_archive_path,
          cloud_storage.PUBLIC_BUCKET)
    except (cloud_storage.CredentialsError,
            cloud_storage.PermissionError) as e:
      if os.path.exists(generated_profile_archive_path):
        # If the profile directory archive exists, assume the user has their
        # own local copy simply warn.
        logging.warning('Could not download Profile archive: %s',
            generated_profile_archive_path)
      else:
        # If the archive profile directory doesn't exist, this is fatal.
        logging.error('Can not run without required profile archive: %s. '
                      'If you believe you have credentials, follow the '
                      'instructions below.',
                      generated_profile_archive_path)
        logging.error(e)
        sys.exit(-1)

    # Unzip profile directory.
    extracted_profile_dir_path = (
        os.path.splitext(generated_profile_archive_path)[0])
    if not os.path.isfile(generated_profile_archive_path):
      raise Exception("Profile directory archive not downloaded: ",
          generated_profile_archive_path)
    with zipfile.ZipFile(generated_profile_archive_path) as f:
      try:
        f.extractall(os.path.dirname(generated_profile_archive_path))
      except e:
        # Cleanup any leftovers from unzipping.
        if os.path.exists(extracted_profile_dir_path):
          shutil.rmtree(extracted_profile_dir_path)
        logging.error("Error extracting profile directory zip file: %s", e)
        sys.exit(-1)

    # Run with freshly extracted profile directory.
    logging.info("Using profile archive directory: %s",
        extracted_profile_dir_path)
    options.browser_options.profile_dir = extracted_profile_dir_path

  @classmethod
  def PageTestClass(cls):
    """Get the PageTest for this Test.

    If the Test has no PageTest, raises NotImplementedError.
    """
    if not hasattr(cls, 'test'):
      raise NotImplementedError('This test has no "test" attribute.')
    if not issubclass(cls.test, page_test.PageTest):
      raise TypeError('"%s" is not a PageTest.' % cls.test.__name__)
    return cls.test

  @classmethod
  def PageSetClass(cls):
    """Get the PageSet for this Test.

    If the Test has no PageSet, raises NotImplementedError.
    """
    if not hasattr(cls, 'page_set'):
      raise NotImplementedError('This test has no "page_set" attribute.')
    if not issubclass(cls.page_set, page_set.PageSet):
      raise TypeError('"%s" is not a PageSet.' % cls.page_set.__name__)
    return cls.page_set

  @classmethod
  def CreatePageSet(cls, options):  # pylint: disable=W0613
    """Get the page set this test will run on.

    By default, it will create a page set from the file at this test's
    page_set attribute. Override to generate a custom page set.
    """
    return cls.PageSetClass()()

  @classmethod
  def CreateExpectations(cls, ps):  # pylint: disable=W0613
    """Get the expectations this test will run with.

    By default, it will create an empty expectations set. Override to generate
    custom expectations.
    """
    if hasattr(cls, 'expectations'):
      return cls.expectations
    else:
      return test_expectations.TestExpectations()

def AddCommandLineArgs(parser):
  page_runner.AddCommandLineArgs(parser)

def ProcessCommandLineArgs(parser, args):
  page_runner.ProcessCommandLineArgs(parser, args)


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/colorControlHighlight" android:state_pressed="true"/>
    <item android:drawable="@color/colorControlHighlight" android:state_focused="true"/>
    <item android:drawable="@color/md_deep_teal_300"/>
</selector>


text:
import JailedAdapter from '../jailed-adapter'

let mockPlugin = null

class MockPluginClass {
  constructor(url, api) {
    mockPlugin = this
    this.url = url
    this.api = api
  }

  whenConnected = jest.fn(cb => {
    this.connectedCallback = cb
  })

  whenFailed = jest.fn(cb => {
    this.failedCallback = cb
  })

  whenDisconnected = jest.fn(cb => {
    this.disconnected = cb
  })

  disconnect = jest.fn()

  remote = {
    echo: jest.fn(),
  }
}

describe('JailedAdapter', () => {
  afterEach(() => {
    mockPlugin = null
  })

  it('passes the specified bootstrap parameter to the jailed plugin', () => {
    const adapter = new JailedAdapter(MockPluginClass, 'some url', jest.fn())
    adapter.start()
    expect(mockPlugin.url).toBe('some url')
  })

  it('reports connected after the connected call has gone through', () => {
    const adapter = new JailedAdapter(MockPluginClass, 'some url', jest.fn())
    adapter.start()
    expect(adapter.isConnected()).toBeFalsy()
    mockPlugin.connectedCallback()
    expect(adapter.isConnected()).toBeTruthy()
  })

  it('resolves the promise when connected', () => {
    const adapter = new JailedAdapter(MockPluginClass, 'some url', jest.fn())
    const promise = adapter.start()
    mockPlugin.connectedCallback()
    return promise.catch(() => {
      expect(false).toBe('expected this to resolve but it rejected instead')
    })
  })

  it('rejects the promise when failed', () => {
    const adapter = new JailedAdapter(MockPluginClass, 'some url', jest.fn())
    const promise = adapter.start()
    mockPlugin.failedCallback()
    return promise
      .then(() => {
        expect(false).toBe('expected this to reject but it resolved instead')
        return null
      })
      .catch(() => {}) // actually passes when it rejects
  })

  it('forwards calls to the plugin', () => {
    const adapter = new JailedAdapter(MockPluginClass, 'some url', jest.fn())
    adapter.start()
    mockPlugin.connectedCallback()
    const cb = jest.fn()
    adapter.echo('foo', cb)
    expect(mockPlugin.remote.echo).toHaveBeenCalledWith('foo', cb)
  })

  it('calls the onStop method when the disconnected method is called', () => {
    const onStop = jest.fn()
    const adapter = new JailedAdapter(MockPluginClass, 'some url', onStop)
    adapter.start()
    mockPlugin.disconnected()
    expect(onStop).toHaveBeenCalled()
  })

  it('throws if methods are called before the plugin is connected', () => {
    const adapter = new JailedAdapter(MockPluginClass, 'some url', jest.fn())
    adapter.start()
    expect(() => adapter.echo()).toThrow()
  })

  it('disconnects when requested', () => {
    const adapter = new JailedAdapter(MockPluginClass, 'some url', jest.fn())
    adapter.start()
    adapter.stop()
    expect(mockPlugin.disconnect).toHaveBeenCalled()
  })
})


text:
layout: home
author_profile: true
header:
  overlay_image: /assets/images/banner/image/drawing_v02.png
  overlay_filter: 0.4 # same as adding an opacity of 0.5 to a black background
  # overlay filter with 0.01 crash the website
  # the close to 1.0 the blacker is the backgroud
---


text:
/*global exports */
exports.reporter = 'teamcity';
exports.ignoreMessages = ['jasmineDone', 'minimal-ui'];
exports.jsLibraryPath = 'lib/jquery-1.11.1/jquery-1.11.1.min.js'; // loads any other JavaScript library you may require
exports.jasminePath = 'lib/jasmine-2.1.0/';
exports.render = false; // render a test failure
exports.timeout = 60000;
exports.viewports = [{ width: 1400, height: 768 }, { width: 1024, height: 768 }, { width: 768, height: 1024 }, { width: 320, height: 640 }];


text:
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <title>Git - Grishy.ru</title>
    <meta name="description" content="">

    <meta name="HandheldFriendly" content="True">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="google-site-verification" content="FEe4nBxnLwpk7K-xg-_HTuqPkDwk5-IrSRPOnZcmnWw">

    <link rel="shortcut icon" href="../../assets/favicon.png?v=ac46b05395">

    <link rel="stylesheet" type="text/css" href="../../assets/css/font-awesome.css?v=ac46b05395">
    <link rel="stylesheet" type="text/css" href="../../assets/css/main.css?v=ac46b05395">
    <link rel="stylesheet" type="text/css" href="../../assets/css/generate.css?v=ac46b05395">
    <link rel="stylesheet" type="text/css" href="../../assets/css/responsive.css?v=ac46b05395">
    <link rel="stylesheet" type="text/css" href="../../assets/css/hl.css?v=ac46b05395">

    <link rel="alternate" type="application/rss+xml" title="Grishy.ru" href="../../rss/index.html">

            Grishy.ru

Блог о программировании

                    Grishy.ru

    	Главная

    	Проекты

    	О сайте

    	Главная

    	Проекты

    	О сайте

Записи по тегу: Git

Генерация статического сайта из любого сайта

			<time class="post-date" datetime="2015-08-19">19 августа 2015 г.</time>

Сейчас рассмотрим как сделать статическую(локальную) копию сайта, если у него нет такой функции в CMS и загружать его на GitHub Pages. К слову, если нужен простой сайт, то можно попробовать использовать встроенный в GitHub Jekyll и если у вас блог и вам понравилась идея Jekyll, попробуйте Octopress. Я так собираю этот блог на работающий на Ghost.

Легче всего генерировать просто скачав все файлы, которые использует блог для отображения страниц. Грубо говоря зайдя на все страницы сайта и нажать Ctrl+

                        © Grishy.ru 2015 • All rights reserved.


text:
package org.springframework.samples.jpetstore.web.spring;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.ModelAndViewDefiningException;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.util.WebUtils;

/**
 * @author Juergen Hoeller
 * @since 01.12.2003
 */
public class SignonInterceptor extends HandlerInterceptorAdapter {

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		UserSession userSession = (UserSession) WebUtils.getSessionAttribute(request, "userSession");
		if (userSession == null) {
			String url = request.getServletPath();
			String query = request.getQueryString();
			ModelAndView modelAndView = new ModelAndView("SignonForm");
			if (query != null) {
				modelAndView.addObject("signonForwardAction", url+"?"+query);
			}
			else {
				modelAndView.addObject("signonForwardAction", url);
			}
			throw new ModelAndViewDefiningException(modelAndView);
		}
		else {
			return true;
		}
	}

}


text:
@class CTSProfileContactRes;

@interface CTSContactUpdate : JSONModel
@property(  strong) NSString* firstName, *lastName;
@property(  strong) NSString* type;
@property(  strong) NSString<Optional>* email;
@property(  strong) NSString<Optional>* mobile;
@property(  strong) NSString<Optional>* password;

-(void)substituteDefaults;
-(instancetype)initDefault;
-(void)substituteFromProfile:(CTSProfileContactRes *)profile;
@end


text:
<?php namespace FireflyIII\Http\Controllers;

use Amount;
use Carbon\Carbon;
use Config;
use ExpandedForm;
use FireflyIII\Http\Requests\PiggyBankFormRequest;
use FireflyIII\Models\PiggyBank;
use FireflyIII\Repositories\Account\AccountRepositoryInterface as ARI;
use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface;
use Illuminate\Support\Collection;
use Input;
use Log;
use Preferences;
use Session;
use Steam;
use URL;
use View;

/**
 *
 *
 * Class PiggyBankController
 *
 * @package FireflyIII\Http\Controllers
 */
class PiggyBankController extends Controller
{

    /**
     *
     */
    public function __construct()
    {
        parent::__construct();
        View::share('title', trans('firefly.piggyBanks'));
        View::share('mainTitleIcon', 'fa-sort-amount-asc');
    }

    /**
     * Add money to piggy bank
     *
     * @param ARI       $repository
     * @param PiggyBank $piggyBank
     *
     * @return $this
     */
    public function add(ARI $repository, PiggyBank $piggyBank)
    {
        /** @var Carbon $date */
        $date          = session('end', Carbon::now()->endOfMonth());
        $leftOnAccount = $repository->leftOnAccount($piggyBank->account, $date);
        $savedSoFar    = $piggyBank->currentRelevantRep()->currentamount;
        $leftToSave    = bcsub($piggyBank->targetamount, $savedSoFar);
        $maxAmount     = min($leftOnAccount, $leftToSave);

        return view('piggy-banks.add', compact('piggyBank', 'maxAmount'));
    }

    /**
     * @param ARI $repository
     *
     * @return mixed
     */
    public function create(ARI $repository)
    {

        $periods      = Config::get('firefly.piggy_bank_periods');
        $accounts     = ExpandedForm::makeSelectList($repository->getAccounts(['Default account', 'Asset account']));
        $subTitle     = trans('firefly.new_piggy_bank');
        $subTitleIcon = 'fa-plus';

        // put previous url in session if not redirect from store (not "create another").
        if (session('piggy-banks.create.fromStore') !== true) {
            Session::put('piggy-banks.create.url', URL::previous());
        }
        Session::forget('piggy-banks.create.fromStore');
        Session::flash('gaEventCategory', 'piggy-banks');
        Session::flash('gaEventAction', 'create');

        return view('piggy-banks.create', compact('accounts', 'periods', 'subTitle', 'subTitleIcon'));
    }

    /**
     * @param PiggyBank $piggyBank
     *
     * @return $this
     */
    public function delete(PiggyBank $piggyBank)
    {
        $subTitle = trans('firefly.delete_piggy_bank', ['name' => $piggyBank->name]);

        // put previous url in session
        Session::put('piggy-banks.delete.url', URL::previous());
        Session::flash('gaEventCategory', 'piggy-banks');
        Session::flash('gaEventAction', 'delete');

        return view('piggy-banks.delete', compact('piggyBank', 'subTitle'));
    }

    /**
     * @param PiggyBankRepositoryInterface $repository
     * @param PiggyBank                    $piggyBank
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function destroy(PiggyBankRepositoryInterface $repository, PiggyBank $piggyBank)
    {

        Session::flash('success', strval(trans('firefly.deleted_piggy_bank', ['name' => e($piggyBank->name)])));
        Preferences::mark();
        $repository->destroy($piggyBank);

        return redirect(session('piggy-banks.delete.url'));
    }

    /**
     * @param ARI       $repository
     * @param PiggyBank $piggyBank
     *
     * @return View
     */
    public function edit(ARI $repository, PiggyBank $piggyBank)
    {

        $periods      = Config::get('firefly.piggy_bank_periods');
        $accounts     = ExpandedForm::makeSelectList($repository->getAccounts(['Default account', 'Asset account']));
        $subTitle     = trans('firefly.update_piggy_title', ['name' => $piggyBank->name]);
        $subTitleIcon = 'fa-pencil';

        /*
         * Flash some data to fill the form.
         */
        if (is_null($piggyBank->targetdate) || $piggyBank->targetdate == '') {
            $targetDate = null;
        } else {
            $targetDate = new Carbon($piggyBank->targetdate);
            $targetDate = $targetDate->format('Y-m-d');
        }
        $preFilled = ['name'         => $piggyBank->name,
                      'account_id'   => $piggyBank->account_id,
                      'targetamount' => $piggyBank->targetamount,
                      'targetdate'   => $targetDate,
        ];
        Session::flash('preFilled', $preFilled);
        Session::flash('gaEventCategory', 'piggy-banks');
        Session::flash('gaEventAction', 'edit');

        // put previous url in session if not redirect from store (not "return_to_edit").
        if (session('piggy-banks.edit.fromUpdate') !== true) {
            Session::put('piggy-banks.edit.url', URL::previous());
        }
        Session::forget('piggy-banks.edit.fromUpdate');

        return view('piggy-banks.edit', compact('subTitle', 'subTitleIcon', 'piggyBank', 'accounts', 'periods', 'preFilled'));
    }

    /**
     * @param ARI                          $repository
     * @param PiggyBankRepositoryInterface $piggyRepository
     *
     * @return View
     */
    public function index(ARI $repository, PiggyBankRepositoryInterface $piggyRepository)
    {
        /** @var Collection $piggyBanks */
        $piggyBanks = $piggyRepository->getPiggyBanks();
        /** @var Carbon $end */
        $end = session('end', Carbon::now()->endOfMonth());

        $accounts = [];
        /** @var PiggyBank $piggyBank */
        foreach ($piggyBanks as $piggyBank) {
            $piggyBank->savedSoFar = round($piggyBank->currentRelevantRep()->currentamount, 2);
            $piggyBank->percentage = $piggyBank->savedSoFar != 0 ? intval($piggyBank->savedSoFar / $piggyBank->targetamount * 100) : 0;
            $piggyBank->leftToSave = bcsub($piggyBank->targetamount, $piggyBank->savedSoFar);

            /*
             * Fill account information:
             */
            $account = $piggyBank->account;
            if (!isset($accounts[$account->id])) {
                $accounts[$account->id] = [
                    'name'              => $account->name,
                    'balance'           => Steam::balance($account, $end, true),
                    'leftForPiggyBanks' => $repository->leftOnAccount($account, $end),
                    'sumOfSaved'        => strval($piggyBank->savedSoFar),
                    'sumOfTargets'      => strval(round($piggyBank->targetamount, 2)),
                    'leftToSave'        => $piggyBank->leftToSave,
                ];
            } else {
                $accounts[$account->id]['sumOfSaved']   = bcadd($accounts[$account->id]['sumOfSaved'], $piggyBank->savedSoFar);
                $accounts[$account->id]['sumOfTargets'] = bcadd($accounts[$account->id]['sumOfTargets'], $piggyBank->targetamount);
                $accounts[$account->id]['leftToSave']   = bcadd($accounts[$account->id]['leftToSave'], $piggyBank->leftToSave);
            }
        }

        return view('piggy-banks.index', compact('piggyBanks', 'accounts'));
    }

    /**
     * @param PiggyBankRepositoryInterface $repository
     */
    public function order(PiggyBankRepositoryInterface $repository)
    {
        $data = Input::get('order');

        // set all users piggy banks to zero:
        $repository->reset();

        if (is_array($data)) {
            foreach ($data as $order => $id) {
                $repository->setOrder(intval($id), ($order + 1));
            }
        }
    }

    /**
     * @param PiggyBankRepositoryInterface $repository
     * @param ARI                          $accounts
     * @param PiggyBank                    $piggyBank
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function postAdd(PiggyBankRepositoryInterface $repository, ARI $accounts, PiggyBank $piggyBank)
    {
        $amount = round(Input::get('amount'), 2);
        /** @var Carbon $date */
        $date          = session('end', Carbon::now()->endOfMonth());
        $leftOnAccount = $accounts->leftOnAccount($piggyBank->account, $date);
        $savedSoFar    = $piggyBank->currentRelevantRep()->currentamount;
        $leftToSave    = bcsub($piggyBank->targetamount, $savedSoFar);
        $maxAmount     = round(min($leftOnAccount, $leftToSave), 2);

        if ($amount <= $maxAmount) {
            $repetition                = $piggyBank->currentRelevantRep();
            $repetition->currentamount = bcadd($repetition->currentamount, $amount);
            $repetition->save();

            // create event
            $repository->createEvent($piggyBank, $amount);

            Session::flash(
                'success', strval(trans('firefly.added_amount_to_piggy', ['amount' => Amount::format($amount, false), 'name' => e($piggyBank->name)]))
            );
            Preferences::mark();
        } else {
            Log::error('Cannot add ' . $amount . ' because max amount is ' . $maxAmount . ' (left on account is ' . $leftOnAccount . ')');
            Session::flash(
                'error', strval(trans('firefly.cannot_add_amount_piggy', ['amount' => Amount::format($amount, false), 'name' => e($piggyBank->name)]))
            );
        }

        return redirect(route('piggy-banks.index'));
    }

    /**
     * @param PiggyBankRepositoryInterface $repository
     * @param PiggyBank                    $piggyBank
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function postRemove(PiggyBankRepositoryInterface $repository, PiggyBank $piggyBank)
    {
        $amount = round(Input::get('amount'), 2);

        $savedSoFar = $piggyBank->currentRelevantRep()->currentamount;

        if ($amount <= $savedSoFar) {
            $repetition                = $piggyBank->currentRelevantRep();
            $repetition->currentamount = bcsub($repetition->currentamount, $amount);
            $repetition->save();

            // create event
            $repository->createEvent($piggyBank, bcmul($amount, '-1'));

            Session::flash(
                'success', strval(trans('firefly.removed_amount_from_piggy', ['amount' => Amount::format($amount, false), 'name' => e($piggyBank->name)]))
            );
            Preferences::mark();
        } else {
            Session::flash(
                'error', strval(trans('firefly.cannot_remove_from_piggy', ['amount' => Amount::format($amount, false), 'name' => e($piggyBank->name)]))
            );
        }

        return redirect(route('piggy-banks.index'));
    }

    /**
     * @param PiggyBank $piggyBank
     *
     *
     * @return \Illuminate\View\View
     */
    public function remove(PiggyBank $piggyBank)
    {
        return view('piggy-banks.remove', compact('piggyBank'));
    }

    /**
     * @param PiggyBankRepositoryInterface $repository
     * @param PiggyBank                    $piggyBank
     *
     * @return View
     */
    public function show(PiggyBankRepositoryInterface $repository, PiggyBank $piggyBank)
    {
        $events   = $repository->getEvents($piggyBank);
        $subTitle = e($piggyBank->name);

        return view('piggy-banks.show', compact('piggyBank', 'events', 'subTitle'));

    }

    /**
     * @param PiggyBankFormRequest         $request
     * @param PiggyBankRepositoryInterface $repository
     *
     * @return $this|\Illuminate\Http\RedirectResponse
     */
    public function store(PiggyBankFormRequest $request, PiggyBankRepositoryInterface $repository)
    {

        $piggyBankData = [
            'name'          => $request->get('name'),
            'startdate'     => new Carbon,
            'account_id'    => intval($request->get('account_id')),
            'targetamount'  => round($request->get('targetamount'), 2),
            'remind_me'     => false,
            'reminder_skip' => 0,
            'order'         => $repository->getMaxOrder() + 1,
            'targetdate'    => strlen($request->get('targetdate')) > 0 ? new Carbon($request->get('targetdate')) : null,
        ];

        $piggyBank = $repository->store($piggyBankData);

        Session::flash('success', strval(trans('firefly.stored_piggy_bank', ['name' => e($piggyBank->name)])));
        Preferences::mark();

        if (intval(Input::get('create_another')) === 1) {
            Session::put('piggy-banks.create.fromStore', true);

            return redirect(route('piggy-banks.create'))->withInput();
        }

        // redirect to previous URL.
        return redirect(session('piggy-banks.create.url'));
    }

    /**
     * @param PiggyBankRepositoryInterface $repository
     * @param PiggyBankFormRequest         $request
     * @param PiggyBank                    $piggyBank
     *
     * @return $this
     */
    public function update(PiggyBankRepositoryInterface $repository, PiggyBankFormRequest $request, PiggyBank $piggyBank)
    {
        $piggyBankData = [
            'name'          => $request->get('name'),
            'startdate'     => is_null($piggyBank->startdate) ? $piggyBank->created_at : $piggyBank->startdate,
            'account_id'    => intval($request->get('account_id')),
            'targetamount'  => round($request->get('targetamount'), 2),
            'remind_me'     => false,
            'reminder_skip' => 0,
            'targetdate'    => strlen($request->get('targetdate')) > 0 ? new Carbon($request->get('targetdate')) : null,
        ];

        $piggyBank = $repository->update($piggyBank, $piggyBankData);

        Session::flash('success', strval(trans('firefly.updated_piggy_bank', ['name' => e($piggyBank->name)])));
        Preferences::mark();

        if (intval(Input::get('return_to_edit')) === 1) {
            Session::put('piggy-banks.edit.fromUpdate', true);

            return redirect(route('piggy-banks.edit', [$piggyBank->id]));
        }

        // redirect to previous URL.
        return redirect(session('piggy-banks.edit.url'));

    }

}