text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width" />

<link rel="shortcut icon" type="image/x-icon" href="../../../../../../../favicon.ico" />
<title>EventEntity | Android Developers</title>

<link rel="stylesheet"
href="http://fonts.googleapis.com/css?family=Roboto+Condensed">
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Roboto:light,regular,medium,thin,italic,mediumitalic,bold"
  title="roboto">
<link href="../../../../../../../assets/css/default.css" rel="stylesheet" type="text/css">

<link href="../../../../../../../assets/css/fullscreen.css" rel="stylesheet" class="fullscreen"
type="text/css">

            Quicknav
            Quicknav

              Design

Develop

Distribute

Links

Google Play Developer Console

Android Developers Blog

About Android

Android Sites

Android.com

Android Developers

Android Open Source Project

      <form onsubmit="return submit_search()">
        <input id="search_autocomplete" type="text" value="" autocomplete="off" name="q"
          onfocus="search_focus_changed(this, true)" onblur="search_focus_changed(this, false)"
          onkeydown="return search_changed(event, true, '../../../../../../../')"
          onkeyup="return search_changed(event, false, '../../../../../../../')" />
      </form>

      close

Get Started

Style

Patterns

Building Blocks

Downloads

Videos

Training

API Guides

Reference

Tools

Get the SDK

Google Services

Google Play

Essentials

Get Users

Engage & Retain

Monetize

Tools & Reference

Developer Stories

Training

API Guides

Reference

Tools

Google Services

Results

Loading...

EventEntity

          API level:

            <select id="apiLevelSelector">

            </select>

Android APIs

  com.google.android.gms

  com.google.android.gms.actions

  com.google.android.gms.ads

  com.google.android.gms.ads.doubleclick

  com.google.android.gms.ads.identifier

  com.google.android.gms.ads.mediation

  com.google.android.gms.ads.mediation.admob

  com.google.android.gms.ads.mediation.customevent

  com.google.android.gms.ads.purchase

  com.google.android.gms.ads.search

  com.google.android.gms.analytics

  com.google.android.gms.analytics.ecommerce

  com.google.android.gms.appindexing

  com.google.android.gms.appstate

  com.google.android.gms.auth

  com.google.android.gms.cast

  com.google.android.gms.common

  com.google.android.gms.common.annotation

  com.google.android.gms.common.api

  com.google.android.gms.common.data

  com.google.android.gms.common.images

  com.google.android.gms.drive

  com.google.android.gms.drive.events

  com.google.android.gms.drive.metadata

  com.google.android.gms.drive.query

  com.google.android.gms.drive.widget

  com.google.android.gms.games

  com.google.android.gms.games.achievement

  com.google.android.gms.games.event

  com.google.android.gms.games.leaderboard

  com.google.android.gms.games.multiplayer

  com.google.android.gms.games.multiplayer.realtime

  com.google.android.gms.games.multiplayer.turnbased

  com.google.android.gms.games.quest

  com.google.android.gms.games.request

  com.google.android.gms.games.snapshot

  com.google.android.gms.gcm

  com.google.android.gms.identity.intents

  com.google.android.gms.identity.intents.model

  com.google.android.gms.location

  com.google.android.gms.maps

  com.google.android.gms.maps.model

  com.google.android.gms.panorama

  com.google.android.gms.plus

  com.google.android.gms.plus.model.moments

  com.google.android.gms.plus.model.people

  com.google.android.gms.security

  com.google.android.gms.tagmanager

  com.google.android.gms.wallet

  com.google.android.gms.wallet.fragment

  com.google.android.gms.wearable

Interfaces

Event

Events

Events.LoadEventsResult

Classes

EventBuffer

EventEntity

      fullscreen
      Use Tree NavigationUse Panel Navigation

Summary:

  Inherited Constants

  | Fields

  | Ctors

  | Methods

  | Inherited Methods

| [Expand All]

    public

    final

    class

EventEntity

    extends Object

      implements

        SafeParcelable

        Event

        java.lang.Object

               ↳

        com.google.android.gms.games.event.EventEntity

Class Overview

Data object representing the data for a event. This is immutable, and therefore safe
 to cache or store. Note, however, that the data it represents may grow stale.

Summary

  [Expand]

Inherited Constants

  From interface
android.os.Parcelable

        int
        CONTENTS_FILE_DESCRIPTOR

        int
        PARCELABLE_WRITE_RETURN_VALUE

  From interface
com.google.android.gms.common.internal.safeparcel.SafeParcelable

        String
        NULL

Fields

          <nobr>
          public
          static
          final
          EventEntityCreator</nobr>
          CREATOR

Public Constructors

        <nobr>

            </nobr>

        <nobr>
        EventEntity(Event event)</nobr>

Public Methods

        <nobr>

            int</nobr>

        <nobr>
        describeContents()</nobr>

        <nobr>

            boolean</nobr>

        <nobr>
        equals(Object obj)</nobr>

        <nobr>

            Event</nobr>

        <nobr>
        freeze()</nobr>

Freeze a volatile representation into an immutable representation.

        <nobr>

            String</nobr>

        <nobr>
        getDescription()</nobr>

Retrieves the description for this event.

        <nobr>

            void</nobr>

        <nobr>
        getDescription(CharArrayBuffer dataOut)</nobr>

Loads the event description into the given CharArrayBuffer.

        <nobr>

            String</nobr>

        <nobr>
        getEventId()</nobr>

Retrieves the ID of this event.

        <nobr>

            String</nobr>

        <nobr>
        getFormattedValue()</nobr>

Retrieves the sum of increments have been made to this event (formatted for the user's
 locale).

        <nobr>

            void</nobr>

        <nobr>
        getFormattedValue(CharArrayBuffer dataOut)</nobr>

Retrieves the sum of increments have been made to this event (formatted
 for the user's locale).

        <nobr>

            Uri</nobr>

        <nobr>
        getIconImageUri()</nobr>

Retrieves a URI that can be used to load the event's image icon.

        <nobr>

            String</nobr>

        <nobr>
        getIconImageUrl()</nobr>

        <nobr>

            void</nobr>

        <nobr>
        getName(CharArrayBuffer dataOut)</nobr>

Loads the event name into the given CharArrayBuffer.

        <nobr>

            String</nobr>

        <nobr>
        getName()</nobr>

Retrieves the name of this event.

        <nobr>

            Player</nobr>

        <nobr>
        getPlayer()</nobr>

Retrieves the player information associated with this event.

        <nobr>

            long</nobr>

        <nobr>
        getValue()</nobr>

Retrieves the number of increments this user has made to this event.

        <nobr>

            int</nobr>

        <nobr>
        hashCode()</nobr>

        <nobr>

            boolean</nobr>

        <nobr>
        isDataValid()</nobr>

Check to see if this object is valid for use.

        <nobr>

            boolean</nobr>

        <nobr>
        isVisible()</nobr>

Retrieves whether the event should be displayed to the user in any event related UIs.

        <nobr>

            String</nobr>

        <nobr>
        toString()</nobr>

        <nobr>

            void</nobr>

        <nobr>
        writeToParcel(Parcel out, int flags)</nobr>

  [Expand]

Inherited Methods

From class

  java.lang.Object

        <nobr>

            Object</nobr>

        <nobr>
        clone()</nobr>

        <nobr>

            boolean</nobr>

        <nobr>
        equals(Object arg0)</nobr>

        <nobr>

            void</nobr>

        <nobr>
        finalize()</nobr>

        <nobr>

            final

            Class<?></nobr>

        <nobr>
        getClass()</nobr>

        <nobr>

            int</nobr>

        <nobr>
        hashCode()</nobr>

        <nobr>

            final

            void</nobr>

        <nobr>
        notify()</nobr>

        <nobr>

            final

            void</nobr>

        <nobr>
        notifyAll()</nobr>

        <nobr>

            String</nobr>

        <nobr>
        toString()</nobr>

        <nobr>

            final

            void</nobr>

        <nobr>
        wait()</nobr>

        <nobr>

            final

            void</nobr>

        <nobr>
        wait(long arg0, int arg1)</nobr>

        <nobr>

            final

            void</nobr>

        <nobr>
        wait(long arg0)</nobr>

From interface

  android.os.Parcelable

        <nobr>
            abstract

            int</nobr>

        <nobr>
        describeContents()</nobr>

        <nobr>
            abstract

            void</nobr>

        <nobr>
        writeToParcel(Parcel arg0, int arg1)</nobr>

From interface

  com.google.android.gms.common.data.Freezable

        <nobr>
            abstract

            T</nobr>

        <nobr>
        freeze()</nobr>

Freeze a volatile representation into an immutable representation.

        <nobr>
            abstract

            boolean</nobr>

        <nobr>
        isDataValid()</nobr>

Check to see if this object is valid for use.

From interface

  com.google.android.gms.games.event.Event

        <nobr>
            abstract

            String</nobr>

        <nobr>
        getDescription()</nobr>

Retrieves the description for this event.

        <nobr>
            abstract

            void</nobr>

        <nobr>
        getDescription(CharArrayBuffer dataOut)</nobr>

Loads the event description into the given CharArrayBuffer.

        <nobr>
            abstract

            String</nobr>

        <nobr>
        getEventId()</nobr>

Retrieves the ID of this event.

        <nobr>
            abstract

            String</nobr>

        <nobr>
        getFormattedValue()</nobr>

Retrieves the sum of increments have been made to this event (formatted for the user's
 locale).

        <nobr>
            abstract

            void</nobr>

        <nobr>
        getFormattedValue(CharArrayBuffer dataOut)</nobr>

Retrieves the sum of increments have been made to this event (formatted
 for the user's locale).

        <nobr>
            abstract

            Uri</nobr>

        <nobr>
        getIconImageUri()</nobr>

Retrieves a URI that can be used to load the event's image icon.

        <nobr>
            abstract

            String</nobr>

        <nobr>
        getName()</nobr>

Retrieves the name of this event.

        <nobr>
            abstract

            void</nobr>

        <nobr>
        getName(CharArrayBuffer dataOut)</nobr>

Loads the event name into the given CharArrayBuffer.

        <nobr>
            abstract

            Player</nobr>

        <nobr>
        getPlayer()</nobr>

Retrieves the player information associated with this event.

        <nobr>
            abstract

            long</nobr>

        <nobr>
        getValue()</nobr>

Retrieves the number of increments this user has made to this event.

        <nobr>
            abstract

            boolean</nobr>

        <nobr>
        isVisible()</nobr>

Retrieves whether the event should be displayed to the user in any event related UIs.

Fields

        public
        static
        final
        EventEntityCreator

        CREATOR

Public Constructors

        public

      EventEntity
      (Event event)

Public Methods

        public

        int

      describeContents
      ()

        public

        boolean

      equals
      (Object obj)

        public

        Event

      freeze
      ()

Freeze a volatile representation into an immutable representation. Objects returned from this
 call are safe to cache.

 Note that the output of freeze may not be identical to the parent object, but should
 be equal. In other words:

 Freezable f1 = new Freezable();
 Freezable f2 = f1.freeze();
 f1 == f2 may not be true.
 f1.equals(f2) will be true.

Returns

A concrete implementation of the data object.

        public

        String

      getDescription
      ()

Retrieves the description for this event.

Returns

The event description.

        public

        void

      getDescription
      (CharArrayBuffer dataOut)

Loads the event description into the given CharArrayBuffer.

Parameters

          dataOut
          The buffer to load the data into.

        public

        String

      getEventId
      ()

Retrieves the ID of this event.

Returns

The event ID.

        public

        String

      getFormattedValue
      ()

Retrieves the sum of increments have been made to this event (formatted for the user's
 locale).

Returns

The formatted number of increments this user has made to this event.

        public

        void

      getFormattedValue
      (CharArrayBuffer dataOut)

Retrieves the sum of increments have been made to this event (formatted
 for the user's locale).

Parameters

          dataOut
          The buffer to load the data into.

        public

        Uri

      getIconImageUri
      ()

Retrieves a URI that can be used to load the event's image icon. Returns null if the event
 has no image.

 To retrieve the Image from the Uri, use ImageManager.

Returns

The image URI for the achievement's unlocked image icon, or null if the achievement
         has no unlocked image.

        public

        String

      getIconImageUrl
      ()

        public

        void

      getName
      (CharArrayBuffer dataOut)

Loads the event name into the given CharArrayBuffer.

Parameters

          dataOut
          The buffer to load the data into.

        public

        String

      getName
      ()

Retrieves the name of this event.

Returns

The event name.

        public

        Player

      getPlayer
      ()

Retrieves the player information associated with this event.

 Note that this object is a volatile representation, so it is not safe to cache the output of
 this directly. Instead, cache the result of freeze().

Returns

The player associated with this event.

        public

        long

      getValue
      ()

Retrieves the number of increments this user has made to this event.

Returns

The number of increments this user has made to this event.

        public

        int

      hashCode
      ()

        public

        boolean

      isDataValid
      ()

Check to see if this object is valid for use. If the object is still volatile, this method
 will indicate whether or not the object can be safely used. The output of a call to
 freeze() will always be valid.

Returns

whether or not the object is valid for use.

        public

        boolean

      isVisible
      ()

Retrieves whether the event should be displayed to the user in any event related UIs.

Returns

Whether to display the event to the user.

        public

        String

      toString
      ()

        public

        void

      writeToParcel
      (Parcel out, int flags)

  Except as noted, this content is licensed under Apache 2.0.
  For details and restrictions, see the
  Content License.

    Android GmsCore 1307510 r —

    About Android  |
    Legal  |
    Support


text:
package com.hack23.cia.web.impl.ui.application.views.admin.system.pagemode;

import java.text.MessageFormat;
import java.util.Arrays;
import java.util.List;

import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;

import com.hack23.cia.model.internal.application.system.impl.ApplicationEventGroup;
import com.hack23.cia.model.internal.application.user.impl.UserAccount;
import com.hack23.cia.model.internal.application.user.impl.UserAccount_;
import com.hack23.cia.service.api.DataContainer;
import com.hack23.cia.service.api.action.admin.ManageUserAccountRequest;
import com.hack23.cia.service.api.action.admin.ManageUserAccountRequest.AccountOperation;
import com.hack23.cia.web.impl.ui.application.action.ViewAction;
import com.hack23.cia.web.impl.ui.application.views.common.labelfactory.LabelFactory;
import com.hack23.cia.web.impl.ui.application.views.common.rows.RowUtil;
import com.hack23.cia.web.impl.ui.application.views.common.sizing.ContentRatio;
import com.hack23.cia.web.impl.ui.application.views.common.viewnames.AdminViews;
import com.hack23.cia.web.impl.ui.application.views.pageclicklistener.ManageUserAccountClickListener;
import com.hack23.cia.web.impl.ui.application.views.pageclicklistener.PageItemPropertyClickListener;
import com.jarektoro.responsivelayout.ResponsiveRow;
import com.vaadin.icons.VaadinIcons;
import com.vaadin.ui.Button;
import com.vaadin.ui.Layout;
import com.vaadin.ui.MenuBar;
import com.vaadin.ui.Panel;
import com.vaadin.ui.VerticalLayout;

/**
 * The Class AdminUserAccountPageModContentFactoryImpl.
 */
@Component
public final class AdminUserAccountPageModContentFactoryImpl extends AbstractAdminSystemPageModContentFactoryImpl {

	/** The Constant ADMIN_USERACCOUNT. */
	private static final String ADMIN_USERACCOUNT = "Admin Useraccount";

	private static final List<String> AS_LIST = Arrays.asList("username", "createdDate", "email", "country",
			"numberOfVisits" );

	/** The Constant BUTTON_ID_PATTERN. */
	private static final String BUTTON_ID_PATTERN = "{0}.{1}";

	/** The Constant BUTTON_PATTERN. */
	private static final String BUTTON_PATTERN = "Perform {0}";

	private static final String[] COLUMN_ORDER = { "hjid", "modelObjectId", "modelObjectVersion", "createdDate", "userId", "username",
			"userType", "userRole", "userpassword", "email", "country", "numberOfVisits" };

	private static final String[] HIDE_COLUMNS = { "hjid", "modelObjectId", "modelObjectVersion","userId","userpassword", "address" };

	private static final PageItemPropertyClickListener LISTENER = new PageItemPropertyClickListener(AdminViews.ADMIN_USERACCOUNT_VIEW_NAME, "hjid");

	/** The Constant NAME. */
	public static final String NAME = AdminViews.ADMIN_USERACCOUNT_VIEW_NAME;

	private static final String USER_ACCOUNT = "UserAccount";

	/**
	 * Instantiates a new admin user account page mod content factory impl.
	 */
	public AdminUserAccountPageModContentFactoryImpl() {
		super(NAME);
	}

	@Secured({ "ROLE_ADMIN" })
	@Override
	public Layout createContent(final String parameters, final MenuBar menuBar, final Panel panel) {
		final VerticalLayout content = createPanelContent();

		final String pageId = getPageId(parameters);
		final int pageNr= getPageNr(parameters);

		getMenuItemFactory().createMainPageMenuBar(menuBar);

		LabelFactory.createHeader2Label(content,ADMIN_USERACCOUNT);

		final DataContainer<UserAccount, Long> dataContainer = getApplicationManager()
				.getDataContainer(UserAccount.class);

		final List<UserAccount> pageOrderBy = dataContainer.getPageOrderBy(pageNr,DEFAULT_RESULTS_PER_PAGE,UserAccount_.createdDate);

		getPagingUtil().createPagingControls(content,NAME,pageId, dataContainer.getSize(), pageNr, DEFAULT_RESULTS_PER_PAGE);

		getGridFactory().createBasicBeanItemGrid(content, UserAccount.class,
				pageOrderBy,
				USER_ACCOUNT,
				COLUMN_ORDER, HIDE_COLUMNS,
				LISTENER, null, null);

		if (pageId != null && !pageId.isEmpty()) {

			final UserAccount userAccount = dataContainer.load(Long.valueOf(pageId));

			if (userAccount != null) {

				getFormFactory()
						.addFormPanelTextFields(content, userAccount, UserAccount.class,
								AS_LIST);

				final VerticalLayout overviewLayout = new VerticalLayout();
				overviewLayout.setSizeFull();
				content.addComponent(overviewLayout);
				content.setExpandRatio(overviewLayout, ContentRatio.LARGE);

				final ResponsiveRow grid = RowUtil.createGridLayout(overviewLayout);

				for (final AccountOperation accountOperation : ManageUserAccountRequest.AccountOperation.values()) {
					final ManageUserAccountRequest request = new ManageUserAccountRequest();
					request.setSessionId(RequestContextHolder.currentRequestAttributes().getSessionId());
					request.setAccountOperation(accountOperation);
					request.setUserAcountId(userAccount.getUserId());
					final Button accountOperationButton = new Button(MessageFormat.format(BUTTON_PATTERN, accountOperation) , VaadinIcons.BULLSEYE);
					accountOperationButton.addClickListener(new ManageUserAccountClickListener(request));
					accountOperationButton.setId(MessageFormat.format(BUTTON_ID_PATTERN, ViewAction.START_AGENT_BUTTON, accountOperation));
					RowUtil.createRowItem(grid, accountOperationButton, "Will perform useraccount action");
				}

			}
		}

		getPageActionEventHelper().createPageEvent(ViewAction.VISIT_ADMIN_USERACCOUNT_VIEW, ApplicationEventGroup.ADMIN,
				NAME, null, pageId);

		return content;

	}

}

redpajama_set_name: RedPajamaGithub


text:
package net.ljcomputing.people.web.controller;

import net.ljcomputing.gson.converter.GsonConverterService;
import net.ljcomputing.logging.annotation.InjectLogging;

import org.junit.Before;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

/**
 * Abstract implementation of controller tests.
 *
 * @author James G. Willmore
 *
 */
public abstract class AbstractControllerTest {
    @InjectLogging
    protected static Logger logger;

    /** The gson converter service. */
    @Autowired
    protected GsonConverterService gsonConverterService;

    /** The wac. */
    @Autowired
    protected WebApplicationContext wac;

    /** The mock mvc. */
    protected MockMvc mockMvc;

    /**
     * Set up.
     *
     * @throws Exception the exception
     */
    @Before
    public void setUp() throws Exception {
	mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
    }

    /**
     * Log begin test.
     */
    protected void logBeginTest() {
	logger.debug("Begin test");
    }

    /**
     * Log end test.
     */
    protected void logEndTest() {
	logger.debug("End test");
    }

    /**
     * Log results.
     *
     * @param results the results
     */
    protected void logResults(Object results) {
	logger.debug("results: {}", results);
    }
}


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const path = require("path");
const cli_utils_1 = require("@ionic/cli-utils");
const modules_1 = require("../lib/modules");
function getPages(context) {
    return tslib_1.__awaiter(this, void 0, void 0, function* () {
        const AppScripts = modules_1.load('@ionic/app-scripts');
        const pages = yield AppScripts.getNgModules(context, ['page', 'component']);
        const ngModuleSuffix = yield AppScripts.getStringPropertyValue('IONIC_NG_MODULE_FILENAME_SUFFIX');
        return pages.map((page) => {
            return {
                fileName: path.basename(page.absolutePath, ngModuleSuffix),
                absolutePath: page.absolutePath,
                relativePath: path.relative(context.rootDir, page.absolutePath)
            };
        });
    });
}
exports.getPages = getPages;
function prompt(context) {
    return tslib_1.__awaiter(this, void 0, void 0, function* () {
        return context.appNgModulePath;
    });
}
exports.prompt = prompt;
function getModules(context, kind) {
    return tslib_1.__awaiter(this, void 0, void 0, function* () {
        switch (kind) {
            case 'component':
                return context.componentsNgModulePath ? context.componentsNgModulePath : context.appNgModulePath;
            case 'pipe':
                return context.pipesNgModulePath ? context.pipesNgModulePath : context.appNgModulePath;
            case 'directive':
                return context.directivesNgModulePath ? context.directivesNgModulePath : context.appNgModulePath;
        }
    });
}
exports.getModules = getModules;
function tabsPrompt(env) {
    return tslib_1.__awaiter(this, void 0, void 0, function* () {
        const tabNames = [];
        const howMany = yield env.prompt({
            type: 'input',
            name: 'howMany',
            message: 'How many tabs?',
            validate: v => cli_utils_1.validators.numeric(v),
        });
        for (let i = 0; i < parseInt(howMany, 10); i++) {
            const tabName = yield env.prompt({
                type: 'input',
                name: 'tabName',
                message: 'Name of this tab:'
            });
            tabNames.push(tabName);
        }
        return tabNames;
    });
}
exports.tabsPrompt = tabsPrompt;


text:
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.contrib.admin.views.decorators import staff_member_required
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.views.generic.list_detail import object_list
from django.conf import settings
from django.core.urlresolvers import reverse

from scritti.posts.models import Post

from tagging.models import Tag, TaggedItem

def get_published_posts():
    return Post.objects.filter(published=True, is_page=False).order_by('-pub_date')

def get_published_pages():
    return Post.objects.filter(published=True, is_page=True)

def index(request, page=1):
    post_list = get_published_posts().order_by('-pub_date')
    paginator = Paginator(post_list, settings.POSTS_PER_PAGE)

    try:
        posts = paginator.page(page)
    except (EmptyPage, InvalidPage):
        posts = paginator.page(paginator.num_pages)

    return render_to_response('posts/post_list.html', {'posts': posts}, RequestContext(request))

def render_post(request, post, preview=False):
    return render_to_response('posts/detail.html', {'post': post, 'preview': preview}, RequestContext(request))

@staff_member_required
def preview(request, post_slug):
    post = get_object_or_404(Post, slug=post_slug, published=False)
    return render_post(request, post, preview=True)

def detail(request, post_slug):
    post = get_object_or_404(Post, slug=post_slug, published=True)
    return render_post(request, post)

# Legacy URL handler
def detail_date(request, post_slug, year, month, day):
    return HttpResponseRedirect(reverse('post_view', args=[post_slug]))

def search(request, page=1):
    from whoosh.support.pyparsing import ParseException
    error = None
    before_error = None
    after_error = None
    posts = []

    query_text = request.GET.get('q', None)
    try:
        post_list = Post.objects.query(query_text).filter(published=True)
    except ParseException, e:
        before_error = query_text[:e.col]
        error = query_text[e.col]
        if e.col < len(query_text):
            after_error = query_text[e.col+1:]

    if not error:
        paginator = Paginator(post_list, settings.POSTS_PER_PAGE)

        try:
            posts = paginator.page(page)
        except (EmptyPage, InvalidPage):
            posts = paginator.page(paginator.num_pages)

    vars = {
             'posts': posts,
             'query': query_text,
             'parse_error': error,
             'before_error': before_error,
             'after_error': after_error
           }
    return render_to_response('posts/search_results.html', vars, RequestContext(request))

def tagged(request, tag_name, page=1):
    tags = Tag.objects.get(name=tag_name)
    post_list = TaggedItem.objects.get_by_model(Post, tags).filter(published=True).order_by('-pub_date')
    paginator = Paginator(post_list, settings.POSTS_PER_PAGE)

    try:
        posts = paginator.page(page)
    except (EmptyPage, InvalidPage):
        posts = paginator.page(paginator.num_pages)

    return render_to_response('posts/tag_post_list.html', {'posts': posts, 'tag': tag_name}, RequestContext(request))


text:
Provide local repositories using Satis.

## Installation

In a Web folder, clone this git repository.

Then type:

    composer update

And build the packages list:

    composer build

## Access

The packages list can be accessed via `http://<host>/private-packages/web/`.

## Usage

In other projects' composer.json:

```json
	"repositories": [
		{
			"type": "composer",
			"url": "http://<host>/private-packages/web/"
		}
	]
```

## Packages list update

Edit `repositories.json` and add the Git repositories.

And then, update the packages list:

    composer build

Version this repository when required.

## When to build the packages list?

The packages list should be re-built when a repository is updated, i.e. when new tags are created.

### Automatic build

If your Web server is able to interpret PHP scripts, you can enable the rebuild function:

    composer enable-rebuild-hook

This command-line copies the `rebuild.php` file in the `web` folder, and makes it available at this address: `http://<host>/private-packages/web/rebuild.php`.

You can access it manually, or start it from the Git `post-receive` hook, for example:

```php
#!/usr/bin/env php

<?php
$rebuildResult = file_get_contents("http://uri/private-packages/rebuild.php");

$rebuildResult = explode("\n", $rebuildResult);

if ($rebuildResult[0] === "success") {
	echo "Private packages rebuilt!";
} else {
	echo "Private packages rebuild failed";
}

echo "\n";
```

## References

The Satis documentation: https://getcomposer.org/doc/articles/handling-private-packages-with-satis.md


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AddInContracts
{
    [Serializable]
    public class ScheduleOptions
    {
        public string CronExpression { get; set; }
    }
}


text:
module Bigcommerce
  class GoogleProductSearchMapping < Resource
    include Bigcommerce::Request.new 'products/%d/googleproductsearch'

    property :size
    property :color
    property :gender
    property :enabled
    property :pattern
    property :material
    property :age_group
    property :product_id
    property :category_id
    property :custom_item
    property :global_trade_item_number
    property :manufacturer_part_number
    property :google_shopping_product_category_path

    def self.all(product_id, params = {})
      get path.build(product_id), params
    end
  end
end


text:
package org.cyclops.cyclopscore.nbt.path.parse;

import org.cyclops.cyclopscore.nbt.path.INbtPathExpression;
import org.cyclops.cyclopscore.nbt.path.NbtPathExpressionMatches;
import org.cyclops.cyclopscore.nbt.path.navigate.INbtPathNavigation;

import javax.annotation.Nullable;
import java.util.stream.Stream;

/**
 * A handler that picks the root of the NBT tree via "$".
 */
public class NbtPathExpressionParseHandlerRoot implements INbtPathExpressionParseHandler {

    @Nullable
    @Override
    public HandleResult handlePrefixOf(String nbtPathExpression, int pos) {
        if (nbtPathExpression.charAt(pos) != '$') {
            return HandleResult.INVALID;
        }

        return new HandleResult(Expression.INSTANCE, 1);
    }

    public static class Expression implements INbtPathExpression {

        public static final Expression INSTANCE = new Expression();

        @Override
        public NbtPathExpressionMatches matchContexts(Stream<NbtPathExpressionExecutionContext> executionContexts) {
            return new NbtPathExpressionMatches(executionContexts.map(NbtPathExpressionExecutionContext::getRootContext));
        }

        @Override
        public INbtPathNavigation asNavigation(@Nullable INbtPathNavigation child) {
            return child;
        }
    }
}


text:
#ifndef MSHADOW_EXTENSION_REDUCE_WITH_AXIS_H_
#define MSHADOW_EXTENSION_REDUCE_WITH_AXIS_H_

#include "../extension.h"

namespace mshadow {
namespace expr {

/*! \brief reduce out the dimension of src labeled by axis.
 *  \tparam Reducer type of reducer
 *  \tparam SrcExp type of source expression
 *  \tparam DType data type
 */
template<typename Reducer, typename SrcExp, typename DType, int dimsrc, bool mask, int dimdst>
struct ReduceWithAxisExp:
    public MakeTensorExp<ReduceWithAxisExp<Reducer, SrcExp, DType, dimsrc, mask, dimdst>,
                         SrcExp, dimdst, DType> {
  /*! \brief source oprand */
  const SrcExp &src_;
  /*! \brief size of last destination dimension */
  index_t last_dst_dim_;
  /*! \brief size of trailing dimensions */
  index_t trailing_;
  /*! \brief size of axis dimension */
  index_t size_;
  /*! \brief size of last src dimension */
  index_t last_;
  /*! constructor */
  explicit ReduceWithAxisExp(const SrcExp &src, int axis)
    : src_(src) {
    bool keepdim = (dimsrc == dimdst);
    CHECK(dimsrc > axis) << "reduce axis out of bound";
    Shape<dimsrc> src_shape = ShapeCheck<dimsrc, SrcExp>::Check(src_);
    for (int i = 0; i < axis; ++i) {
      this->shape_[i] = src_shape[i];
    }
    this->size_ = src_shape[axis];
    this->trailing_ = 1;
    if (!keepdim) {
      for (int i = axis + 1; i < dimsrc; ++i) {
        this->trailing_ *= src_shape[i];
        this->shape_[i - 1] = src_shape[i];
      }
    } else {
      this->shape_[axis] = 1;
      for (index_t i = axis + 1; i < dimsrc; ++i) {
        this->trailing_ *= src_shape[i];
        this->shape_[i] = src_shape[i];
      }
    }

    this->last_ = src_shape[dimsrc - 1];
    this->last_dst_dim_ = this->shape_[dimdst - 1];
  }
};  // struct ReduceWithAxisExp

/*!
 * \brief reduce out the dimension of src labeled by axis.
 * \param Reducer type of the reducing operation
 * \param mask whether to output the unmask indices
 * \tparam SrcExp source expression
 * \tparam DType data type
 * \tparam etype type of the expression
 */
template<typename Reducer, bool mask, typename SrcExp, typename DType, int etype>
inline ReduceWithAxisExp<Reducer, SrcExp, DType, ExpInfo<SrcExp>::kDim, mask,
  ExpInfo<SrcExp>::kDim - 1>
reduce_with_axis(const Exp<SrcExp, DType, etype> &src, int axis) {
  return ReduceWithAxisExp<Reducer, SrcExp, DType, ExpInfo<SrcExp>::kDim, mask,
    ExpInfo<SrcExp>::kDim- 1>(src.self(), axis);
}

/*!
* \brief reduce out the dimension of src labeled by axis, keepdim turned on.
* \param Reducer type of the reducing operation
* \param mask whether to output the unmask indices
* \tparam SrcExp source expression
* \tparam DType data type
* \tparam etype type of the expression
*/
template<typename Reducer, bool mask, typename SrcExp, typename DType, int etype>
inline ReduceWithAxisExp<Reducer, SrcExp, DType, ExpInfo<SrcExp>::kDim, mask,
  ExpInfo<SrcExp>::kDim>
  reduce_keepdim(const Exp<SrcExp, DType, etype> &src, int axis) {
  return ReduceWithAxisExp<Reducer, SrcExp, DType, ExpInfo<SrcExp>::kDim, mask,
    ExpInfo<SrcExp>::kDim>(src.self(), axis);
}

//----------------------
// Execution plan
//----------------------
template<typename Reducer, typename SrcExp, typename DType, int dimsrc, bool mask, int dimdst>
struct Plan<ReduceWithAxisExp<Reducer, SrcExp, DType, dimsrc, mask, dimdst>, DType> {
 public:
  explicit Plan(const ReduceWithAxisExp<Reducer, SrcExp, DType, dimsrc, mask, dimdst> &e)
      : src_(MakePlan(e.src_)), last_dst_dim_(e.last_dst_dim_), trailing_(e.trailing_),
        size_(e.size_), last_(e.last_) {}
  MSHADOW_XINLINE DType Eval(index_t i, index_t j) const {
    index_t x = (i*last_dst_dim_ + j)/trailing_;
    index_t y = (i*last_dst_dim_ + j)%trailing_;

    if (mask) {
      index_t idx = 0;
      DType res; Reducer::SetInitValue(res);
      for (index_t k = 0; k < size_; ++k) {
        index_t z = (x*size_+k)*trailing_+y;
        DType tmp = res;
        Reducer::Reduce(res, src_.Eval(z/last_, z%last_));
        if (tmp != res) {
          idx = k;
        }
      }
      return static_cast<DType>(static_cast<int>(idx));
    } else {
      DType res; Reducer::SetInitValue(res);
      for (index_t k = 0; k < size_; ++k) {
        index_t z = (x*size_+k)*trailing_+y;
        Reducer::Reduce(res, src_.Eval(z/last_, z%last_));
      }
      return res;
    }
  }

 private:
  Plan<SrcExp, DType> src_;
  const index_t last_dst_dim_, trailing_, size_, last_;
};
}  // namespace expr
}  // namespace mshadow
#endif  // MSHADOW_EXTENSION_REDUCE_WITH_AXIS_H_


text:
project (${DOTNET_HOST_EXE_NAME})

if(WIN32)
    add_compile_options($<$<CONFIG:RelWithDebInfo>:/MT>)
    add_compile_options($<$<CONFIG:Release>:/MT>)
    add_compile_options($<$<CONFIG:Debug>:/MTd>)
else()
    add_compile_options(-fPIE)
endif()

include(../../setup.cmake)

# Include directories
if(WIN32)
    include_directories("${CLI_CMAKE_RESOURCE_DIR}/${DOTNET_HOST_EXE_NAME}")
endif()
include_directories(../../../)
include_directories(../../../common)
include_directories(../../)
include_directories(../../fxr)

# CMake does not recommend using globbing since it messes with the freshness checks
list(APPEND SOURCES
    ../../../corehost.cpp
    ../../../common/trace.cpp
    ../../../common/utils.cpp)

if(WIN32)
    list(APPEND SOURCES
        ../../../common/pal.windows.cpp
        ../../../common/longfile.windows.cpp)
else()
    list(APPEND SOURCES ../../../common/pal.unix.cpp)
endif()

set(RESOURCES)
if(WIN32 AND NOT SKIP_VERSIONING)
    list(APPEND RESOURCES ../../native.rc)
endif()

add_executable(${DOTNET_HOST_EXE_NAME} ${SOURCES} ${RESOURCES})
install(TARGETS ${DOTNET_HOST_EXE_NAME} DESTINATION bin)

# Specify the import library to link against for Arm32 build since the default set is minimal
if (WIN32 AND CLI_CMAKE_PLATFORM_ARCH_ARM)
    target_link_libraries(${DOTNET_HOST_EXE_NAME} shell32.lib)
endif()

if(${CMAKE_SYSTEM_NAME} MATCHES "Linux")
    target_link_libraries (${DOTNET_HOST_EXE_NAME} "dl" "pthread")
endif()


text:
These are various Dockerfiles and related bits for running the
HashiCorp suite of open source DevOps tools in Docker containers.

These include containers published by others and containers built locally
from Dockerfiles.

## Example Consul Template Environment with Docker and Vagrant and VirtualBox
### (oh my)

I have a 5 node Consul server cluster running as Vagrant machines under
VirtualBox (don't ask)... Using native macOS Docker, I can launch a container
for consul Template and HAProxy with
[registrator](https://github.com/gliderlabs/registrator) to register the
services of new Docker containers with Consul.

Using a local Dockerfile, build a HAProxy container:

```
docker build -t "jbs_haproxy:dockerfile" .
```

Then run it:

```
docker run --name haproxy --dns 10.1.42.210 --rm jbs_haproxy:dockerfile -consul=10.1.42.210:8500
```

It's logging to stdout so you can see reloads and debug issues.

Next, pull and launch a registrator container that listens on the Docker
socket and notifies the Consul cluster:

```
docker pull gliderlabs/registrator:latest
docker run --name=registrator --net=host \
  --volume=/var/run/docker.sock:/tmp/docker.sock \
  gliderlabs/registrator:latest consul://10.1.42.210:8500
```

Finally, we fire up some example Python based web applications with a specific
`SERVICE_NAME` and `SERVICE_TAGS`:

```
docker pull jlordiales/python-micro-service:latest
for i in {1..5}; do
  docker run -d --name webapp${i} \
    -e SERVICE_NAME=tacoda \
    -e SERVICE_TAGS=shamazing \
    -P jlordiales/python-micro-service;
done
```


text:
/**
 */
package COSEM.COSEMObjects;

import COSEM.InterfaceClasses.M_Bus_client;

/**
 *
 * A representation of the model object 'MBus Client Object'.
 *
 *
 *
 * @see COSEM.COSEMObjects.COSEMObjectsPackage#getM_BusClientObject()
 * @model
 * @generated
 */
public interface M_BusClientObject extends M_Bus_client {
} // M_BusClientObject


text:
using System;
using System.Configuration;

namespace Helpers {

	public class Configuration {

		public static string LoginUrl {
			get { return ConfigurationManager.AppSettings["LoginUrl"]; }
		}

		public static string ApplicationUrl {
			get { return ConfigurationManager.AppSettings["ApplicationUrl"]; }
		}

		public static string EmailAddress {
			get { return ConfigurationManager.AppSettings["EmailAddress"]; }
		}

		public static string Password {
			get { return ConfigurationManager.AppSettings["Password"]; }
		}

		public static int ImplicitWaitTime {
			get { return Convert.ToInt32(ConfigurationManager.AppSettings["ImplicitWaitTime"]); }
		}

		public static int ExplicitWaitTime {
			get { return Convert.ToInt32(ConfigurationManager.AppSettings["ExplicitWaitTime"]); }
		}

		public static BrowserType BrowserType {
			get {
				switch (ConfigurationManager.AppSettings["BrowserType"].Trim().ToLower()) {
					case "chrome":
						return BrowserType.Chrome;
					case "firefox":
						return BrowserType.Firefox;
					case "ie":
						return BrowserType.InternetExplorer;
					case "internetexplorer":
						return BrowserType.InternetExplorer;
					default:
						return BrowserType.Unknown;
				}
			}
		}

	}
}


text:
extern "Java"
{
  namespace javax
  {
    namespace management
    {
        class ObjectName;
        class Query$BinaryRelQueryExp;
        class ValueExp;
    }
  }
}

class javax::management::Query$BinaryRelQueryExp : public ::javax::management::QueryEval
{

public:
  Query$BinaryRelQueryExp(jint, ::javax::management::ValueExp *, ::javax::management::ValueExp *);
  jboolean apply(::javax::management::ObjectName *);
  ::java::lang::String * toString();
private:
  static const jlong serialVersionUID = -5690656271650491000LL;
  jint __attribute__((aligned(__alignof__( ::javax::management::QueryEval)))) relOp;
  ::javax::management::ValueExp * exp1;
  ::javax::management::ValueExp * exp2;
public:
  static ::java::lang::Class class$;
};

#endif // __javax_management_Query$BinaryRelQueryExp__


text:
package http2

import (
	"fmt"

	"golang.org/x/net/http2"

	"github.com/summerwind/h2spec/config"
	"github.com/summerwind/h2spec/spec"
)

func InitialFlowControlWindowSize() *spec.TestGroup {
	tg := NewTestGroup("6.9.2", "Initial Flow-Control Window Size")

	// When the value of SETTINGS_INITIAL_WINDOW_SIZE changes,
	// a receiver MUST adjust the size of all stream flow-control
	// windows that it maintains by the difference between the new
	// value and the old value.
	tg.AddTestCase(&spec.TestCase{
		Desc:        "Changes SETTINGS_INITIAL_WINDOW_SIZE after sending HEADERS frame",
		Requirement: "The endpoint MUST adjust the size of all stream flow-control windows.",
		Run: func(c *config.Config, conn *spec.Conn) error {
			var streamID uint32 = 1
			var actual spec.Event

			// Skip this test case when the length of data is 0.
			dataLen, err := spec.ServerDataLength(c)
			if err != nil {
				return err
			}
			if dataLen < 1 {
				return spec.ErrSkipped
			}

			err = conn.Handshake()
			if err != nil {
				return err
			}

			// Set SETTINGS_INITIAL_WINDOW_SIZE to 0 to prevent sending
			// DATA frame.
			settings1 := []http2.Setting{
				http2.Setting{
					ID:  http2.SettingInitialWindowSize,
					Val: 0,
				},
			}
			conn.WriteSettings(settings1...)

			err = spec.VerifySettingsFrameWithAck(conn)
			if err != nil {
				return err
			}

			// Send a HEADERS frame.
			headers := spec.CommonHeaders(c)
			hp := http2.HeadersFrameParam{
				StreamID:      streamID,
				EndStream:     true,
				EndHeaders:    true,
				BlockFragment: conn.EncodeHeaders(headers),
			}
			conn.WriteHeaders(hp)

			// Set SETTINGS_INITIAL_WINDOW_SIZE to 1 so that the server
			// can send DATA frame.
			settings2 := []http2.Setting{
				http2.Setting{
					ID:  http2.SettingInitialWindowSize,
					Val: 1,
				},
			}
			conn.WriteSettings(settings2...)

			// Wait for DATA frame...
			actual, passed := conn.WaitEventByType(spec.EventDataFrame)
			switch event := actual.(type) {
			case spec.DataFrameEvent:
				passed = (event.Header().Length == 1)
			default:
				passed = false
			}

			if !passed {
				expected := []string{
					fmt.Sprintf("DATA Frame (length:1, flags:0x00, stream_id:%d)", streamID),
				}

				return &spec.TestError{
					Expected: expected,
					Actual:   actual.String(),
				}
			}

			return nil
		},
	})

	// A sender MUST track the negative flow-control window and
	// MUST NOT send new flow-controlled frames until it receives
	// WINDOW_UPDATE frames that cause the flow-control window to
	// become positive.
	tg.AddTestCase(&spec.TestCase{
		Desc:        "Sends a SETTINGS frame for window size to be negative",
		Requirement: "The endpoint MUST track the negative flow-control window.",
		Run: func(c *config.Config, conn *spec.Conn) error {
			var streamID uint32 = 1
			var actual spec.Event

			// Skip this test case when the length of data is 0.
			dataLen, err := spec.ServerDataLength(c)
			if err != nil {
				return err
			}
			if dataLen < 5 {
				return spec.ErrSkipped
			}

			err = conn.Handshake()
			if err != nil {
				return err
			}

			// Set SETTINGS_INITIAL_WINDOW_SIZE to 3 to prevent sending
			// all of DATA frame.
			settings1 := []http2.Setting{
				http2.Setting{
					ID:  http2.SettingInitialWindowSize,
					Val: 3,
				},
			}
			conn.WriteSettings(settings1...)

			err = spec.VerifySettingsFrameWithAck(conn)
			if err != nil {
				return err
			}

			// Send a HEADERS frame.
			headers := spec.CommonHeaders(c)
			hp := http2.HeadersFrameParam{
				StreamID:      streamID,
				EndStream:     true,
				EndHeaders:    true,
				BlockFragment: conn.EncodeHeaders(headers),
			}
			conn.WriteHeaders(hp)

			// Verify reception of DATA frame.
			err = spec.VerifyEventType(conn, spec.EventDataFrame)
			if err != nil {
				return err
			}

			// Set SETTINGS_INITIAL_WINDOW_SIZE to 2 to make the window
			// size negative.
			settings2 := []http2.Setting{
				http2.Setting{
					ID:  http2.SettingInitialWindowSize,
					Val: 2,
				},
			}
			conn.WriteSettings(settings2...)

			err = spec.VerifySettingsFrameWithAck(conn)
			if err != nil {
				return err
			}

			// Send WINDOW_UPDATE with increment size 2.
			conn.WriteWindowUpdate(streamID, 2)

			// Wait for DATA frame...
			actual, passed := conn.WaitEventByType(spec.EventDataFrame)
			switch event := actual.(type) {
			case spec.DataFrameEvent:
				passed = (event.Header().Length == 1)
			default:
				passed = false
			}

			if !passed {
				expected := []string{
					fmt.Sprintf("DATA Frame (length:1, flags:0x00, stream_id:%d)", streamID),
				}

				return &spec.TestError{
					Expected: expected,
					Actual:   actual.String(),
				}
			}

			return nil
		},
	})

	// An endpoint MUST treat a change to SETTINGS_INITIAL_WINDOW_SIZE
	// that causes any flow-control window to exceed the maximum size
	// as a connection error (Section 5.4.1) of type FLOW_CONTROL_ERROR.
	tg.AddTestCase(&spec.TestCase{
		Desc:        "Sends a SETTINGS_INITIAL_WINDOW_SIZE settings with an exceeded maximum window size value",
		Requirement: "The endpoint MUST treat this as a connection error of type FLOW_CONTROL_ERROR.",
		Run: func(c *config.Config, conn *spec.Conn) error {
			err := conn.Handshake()
			if err != nil {
				return err
			}

			// SETTINGS frame:
			// SETTINGS_INITIAL_WINDOW_SIZE: 2147483648
			conn.Send([]byte("\x00\x00\x06\x04\x00\x00\x00\x00\x00"))
			conn.Send([]byte("\x00\x04\x80\x00\x00\x00"))

			return spec.VerifyConnectionError(conn, http2.ErrCodeFlowControl)
		},
	})

	return tg
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Problem_02___Grand_Theft_Examo
{
    class Program
    {
        static void Main(string[] args)
        {
            //32 min
            int n = int.Parse(Console.ReadLine());
            long slapedThieves = 0;
            long drinkedBeers = 0;
            long esckapedThieves = 0;

            for (int i = 0; i < n; i++)
            {
                uint thieves = uint.Parse(Console.ReadLine());
                uint beers = uint.Parse(Console.ReadLine());

                if (thieves >= 5)
                {
                    slapedThieves += 5;
                    esckapedThieves += (thieves - 5);
                }
                else
                {
                    slapedThieves += thieves;
                }

                drinkedBeers += beers;
            }

            long sixPacks = drinkedBeers / 6;
            long beersOff = drinkedBeers % 6;

            Console.WriteLine("{0} thieves slapped.", slapedThieves);
            Console.WriteLine("{0} thieves escaped.", esckapedThieves);
            Console.WriteLine("{0} packs, {1} bottles.", sixPacks, beersOff);
        }
    }
}


text:
namespace CoCSharp.Data
{
    /// <summary>
    /// Defines data from alliance_portal.csv.
    /// </summary>
    public class AlliancePortalData : CoCData
    {
        /// <summary>
        /// Initalizes a new instance of the <see cref="AlliancePortalData"/> class.
        /// </summary>
        public AlliancePortalData()
        {
            // Space
        }

        public string Name { get; set; }
        public string TID { get; set; }
        public string SWF { get; set; }
        public string ExportName { get; set; }
        public int Width { get; set; }
        public int Height { get; set; }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Skeddly.Constants
{
	public static class Ec2InstanceIdentificationMethods
	{
		public const string AllInstances = "all-instances";
		public const string ByResourceTag = "by-resource-tag";
		public const string ByInstanceId = "by-instance-id";
		public const string ByInstanceNameTag = "by-instance-name-tag";
	}
}


text:
Home

Tables

Managed Tables

Managed Tables header small text goes here...

                                <button class="btn btn-success btn-xs" type="button">操作</button>
                                <button class="btn btn-success btn-xs dropdown-toggle" type="button" data-toggle="dropdown">

                                </button>

                                        新建

Data Table - Default

                                            Id
                                            省
                                            市
                                            县/区
                                            详细地址
                                            邮编
                                            操作

                                            Trident
                                            Internet Explorer 4.0
                                            Win 95+
                                            Win 95+
                                            4
                                            X
                                             修改 删除

                                            Trident
                                            Internet Explorer 5.0
                                            Win 95+
                                            Win 95+
                                            5
                                            C
                                             修改 删除

Color Theme

Header Styling

                        <select name="header-styling" class="form-control input-sm">
                            <option value="1">default</option>
                            <option value="2">inverse</option>
                        </select>

Header

                        <select name="header-fixed" class="form-control input-sm">
                            <option value="1">fixed</option>
                            <option value="2">default</option>
                        </select>

Sidebar Styling

                        <select name="sidebar-styling" class="form-control input-sm">
                            <option value="1">default</option>
                            <option value="2">grid</option>
                        </select>

Sidebar

                        <select name="sidebar-fixed" class="form-control input-sm">
                            <option value="1">fixed</option>
                            <option value="2">default</option>
                        </select>

Sidebar Gradient

                        <select name="content-gradient" class="form-control input-sm">
                            <option value="1">disabled</option>
                            <option value="2">enabled</option>
                        </select>

Content Styling

                        <select name="content-styling" class="form-control input-sm">
                            <option value="1">default</option>
                            <option value="2">black</option>
                        </select>

                         Reset Local Storage


text:
<!doctype HTML>

<meta charset="utf8">
<title>Content Visibility: scrollIntoView prevented</title>
<link rel="author" title="Vladimir Levin" href="mailto:vmpstr@chromium.org">
<link rel="help" href="https://drafts.csswg.org/css-contain/#content-visibility">
<link rel="match" href="spacer-and-container-ref.html">
<meta name="assert" content="scrollIntoView is prevented when the target is hidden">

Test passes if there is no red.

FAIL


text:
Library for using Git in Ruby.

## Homepage

Git public hosting of the project source code is at:

http://github.com/schacon/ruby-git

## Install

You can install Ruby/Git like this:

    $ sudo gem install git

## Code Status

* [![Build Status](https://api.travis-ci.org/schacon/ruby-git.png)](https://travis-ci.org/schacon/ruby-git)
* [![Code Climate](https://codeclimate.com/github/schacon/ruby-git.png)](https://codeclimate.com/github/schacon/ruby-git)
* [![Gem Version](https://badge.fury.io/rb/git.png)](http://badge.fury.io/rb/git)
* [![Dependencies](https://gemnasium.com/schacon/ruby-git.png?travis)](https://gemnasium.com/schacon/ruby-git)

## Major Objects

**Git::Base** - The object returned from a `Git.open` or `Git.clone`. Most major actions are called from this object.

**Git::Object** - The base object for your tree, blob and commit objects, returned from `@git.gtree` or `@git.object` calls.  the `Git::AbstractObject` will have most of the calls in common for all those objects.

**Git::Diff** - returns from a `@git.diff` command.  It is an Enumerable that returns `Git::Diff:DiffFile` objects from which you can get per file patches and insertion/deletion statistics.  You can also get total statistics from the Git::Diff object directly.

**Git::Status** - returns from a `@git.status` command.  It is an Enumerable that returns
`Git:Status::StatusFile` objects for each object in git, which includes files in the working
directory, in the index and in the repository.  Similar to running 'git status' on the command line to determine untracked and changed files.

**Git::Branches** - Enumerable object that holds `Git::Branch objects`.  You can call .local or .remote on it to filter to just your local or remote branches.

**Git::Remote**- A reference to a remote repository that is tracked by this repository.

**Git::Log** - An Enumerable object that references all the `Git::Object::Commit` objects that encompass your log query, which can be constructed through methods on the `Git::Log object`,
like:

 `@git.log(20).object("some_file").since("2 weeks ago").between('v2.6', 'v2.7').each { |commit| [block] }`

## Examples

Here are a bunch of examples of how to use the Ruby/Git package.

Ruby < 1.9 will require rubygems to be loaded.

```ruby
    require 'rubygems'
```

Require the 'git' gem.
```ruby
    require 'git'
```

Here are the operations that need read permission only.

```ruby
    g = Git.open(working_dir, :log => Logger.new(STDOUT))

    g.index
    g.index.readable?
    g.index.writable?
    g.repo
    g.dir

    g.log   # returns array of Git::Commit objects
    g.log.since('2 weeks ago')
    g.log.between('v2.5', 'v2.6')
    g.log.each {|l| puts l.sha }
    g.gblob('v2.5:Makefile').log.since('2 weeks ago')

    g.object('HEAD^').to_s  # git show / git rev-parse
    g.object('HEAD^').contents
    g.object('v2.5:Makefile').size
    g.object('v2.5:Makefile').sha

    g.gtree(treeish)
    g.gblob(treeish)
    g.gcommit(treeish)

    commit = g.gcommit('1cc8667014381')

    commit.gtree
    commit.parent.sha
    commit.parents.size
    commit.author.name
    commit.author.email
    commit.author.date.strftime("%m-%d-%y")
    commit.committer.name
    commit.date.strftime("%m-%d-%y")
    commit.message

    tree = g.gtree("HEAD^{tree}")

    tree.blobs
    tree.subtrees
    tree.children # blobs and subtrees

    g.revparse('v2.5:Makefile')

    g.branches # returns Git::Branch objects
    g.branches.local
    g.branches.remote
    g.branches[:master].gcommit
    g.branches['origin/master'].gcommit

    g.grep('hello')  # implies HEAD
    g.blob('v2.5:Makefile').grep('hello')
    g.tag('v2.5').grep('hello', 'docs/')

    g.diff(commit1, commit2).size
    g.diff(commit1, commit2).stats
    g.gtree('v2.5').diff('v2.6').insertions
    g.diff('gitsearch1', 'v2.5').path('lib/')
    g.diff('gitsearch1', @git.gtree('v2.5'))
    g.diff('gitsearch1', 'v2.5').path('docs/').patch
    g.gtree('v2.5').diff('v2.6').patch

    g.gtree('v2.5').diff('v2.6').each do |file_diff|
       puts file_diff.path
       puts file_diff.patch
       puts file_diff.blob(:src).contents
    end

    g.config('user.name')  # returns 'Scott Chacon'
    g.config # returns whole config hash

    g.tags # returns array of Git::Tag objects
```

And here are the operations that will need to write to your git repository.

```ruby
      g = Git.init
       Git.init('project')
       Git.init('/home/schacon/proj',
        { :repository => '/opt/git/proj.git',
           :index => '/tmp/index'} )

     g = Git.clone(URI, NAME, :path => '/tmp/checkout')
     g.config('user.name', 'Scott Chacon')
     g.config('user.email', 'email@email.com')

     g.add                                   # git add -- "."
     g.add(:all=>true)                       # git add --all -- "."
     g.add('file_path')                      # git add -- "file_path"
     g.add(['file_path_1', 'file_path_2'])   # git add -- "file_path_1" "file_path_2"

     g.remove('file.txt')
     g.remove(['file.txt', 'file2.txt'])

     g.commit('message')
     g.commit_all('message')

     g = Git.clone(repo, 'myrepo')
     g.chdir do
      new_file('test-file', 'blahblahblah')
      g.status.changed.each do |file|
       puts file.blob(:index).contents
      end
     end

     g.reset # defaults to HEAD
     g.reset_hard(Git::Commit)

     g.branch('new_branch') # creates new or fetches existing
     g.branch('new_branch').checkout
     g.branch('new_branch').delete
     g.branch('existing_branch').checkout

     g.checkout('new_branch')
     g.checkout(g.branch('new_branch'))

     g.branch(name).merge(branch2)
     g.branch(branch2).merge  # merges HEAD with branch2

     g.branch(name).in_branch(message) { # add files }  # auto-commits
     g.merge('new_branch')
     g.merge('origin/remote_branch')
     g.merge(g.branch('master'))
     g.merge([branch1, branch2])

     r = g.add_remote(name, uri)  # Git::Remote
     r = g.add_remote(name, Git::Base)  # Git::Remote

     g.remotes  # array of Git::Remotes
     g.remote(name).fetch
     g.remote(name).remove
     g.remote(name).merge
     g.remote(name).merge(branch)

     g.fetch
     g.fetch(g.remotes.first)

     g.pull
     g.pull(Git::Repo, Git::Branch) # fetch and a merge

     g.add_tag('tag_name') # returns Git::Tag
     g.add_tag('tag_name', 'object_reference')
     g.add_tag('tag_name', 'object_reference', {:options => 'here'})
     g.add_tag('tag_name', {:options => 'here'})

     Options:
       :a | :annotate
       :d
       :f
       :m | :message
       :s

     g.delete_tag('tag_name')

     g.repack

     g.push
     g.push(g.remote('name'))
```

Some examples of more low-level index and tree operations

```ruby
     g.with_temp_index do

       g.read_tree(tree3) # calls self.index.read_tree
       g.read_tree(tree1, :prefix => 'hi/')

       c = g.commit_tree('message')
       # or #
       t = g.write_tree
       c = g.commit_tree(t, :message => 'message', :parents => [sha1, sha2])

       g.branch('branch_name').update_ref(c)
       g.update_ref(branch, c)

       g.with_temp_working do # new blank working directory
         g.checkout
         g.checkout(another_index)
         g.commit # commits to temp_index
       end
     end

     g.set_index('/path/to/index')

     g.with_index(path) do
       # calls set_index, then switches back after
     end

     g.with_working(dir) do
     # calls set_working, then switches back after
     end

     g.with_temp_working(dir) do
       g.checkout_index(:prefix => dir, :path_limiter => path)
       # do file work
       g.commit # commits to index
     end
```

## License

licensed under MIT License Copyright (c) 2008  Scott Chacon. See LICENSE for further details.


text:
module.exports = function(mongoose, properties, schemaExtensions) {

    'use strict';

    var Schema = mongoose.Schema;
    var Account = schemaExtensions && schemaExtensions.Account || require('./account')(mongoose, properties);
    var Promise = require('es6-promise').Promise;

    var userSchemaFields = {
        accounts: [Account],
        firstName: String,
        lastName: String,
        gender: String,
        dateOfBirth: Date
    };

    if (schemaExtensions && schemaExtensions.fields) {
        for (var field in schemaExtensions.fields) {
            if (schemaExtensions.fields.hasOwnProperty(field)) {
                if (!userSchemaFields[field]) {
                    userSchemaFields[field] = schemaExtensions.fields[field];
                }
                else {
                    throw "User schema field " + field + " cannot be overridden.";
                }
            }
        }
    }

    var User = new Schema(userSchemaFields);

    User.methods.addAccount = function(accountType, accountId, accessToken) {
        var user = this;

        this.accounts.push(new Account({
            type: accountType,
            id: accountId,
            accessToken: accessToken
        }));

        return new Promise(function (resolve, reject) {
            user.save(function (err, update) {
                err ? reject(err) : resolve(user);
            });
        });
    };

    User.methods.accountByType = function (accountType) {
        return this.accounts.filter(function (account) {
            return account.accountType === accountType
        }).shift();
    };

    User.statics.findOrCreate = function(accountType, accountId, accessToken, profileData) {
        var resolve, reject;
        this.findOneAndUpdate({
                'accounts.accountType': accountType,
                'accounts.accountId': accountId
            },
            profileData,
            {
                upsert: true,
                new: true
            },
            function (err, user) {
                user.accountByType(accountType).accessToken = accessToken;
                user.save(function (err, user) {
                    err ? reject(err) : resolve(user);
                });
            }
        );

        return new Promise(function (_resolve, _reject) {
            resolve = _resolve;
            reject = _reject;
        });
    };

    User.statics.findLocal = function (username, password, onDone) {
        var account = this.model('account').Local(username, password);
        this.findOne({
            'accounts.accountType': account.accountType,
            'accounts.accountId': account.accountId
        }, function (err, user) {
            if (!err && !user) {
                err = new Error("Invalid User");
            }
            if (!err && user && user.accounts[0].accessToken != account.accessToken) {
                err = new Error("Invalid Password");
            }

            onDone(err, !err && user || null);
        });
    };

    'methods statics'.split(' ').forEach(function (extension) {
        if (schemaExtensions && schemaExtensions[extension]) {
            for (var ext in schemaExtensions[extension]) {
                if (schemaExtensions[extension].hasOwnProperty(ext)) {
                    if (!User[extension][ext]) {
                        User[extension][ext] = schemaExtensions[extension][ext];
                    }
                    else {
                        throw "User schema " + extension + " cannot override built-in " + ext;
                    }
                }
            }
        }
    });

    return User;

};


text:
\input{document-settings}
\input{personal-information}
\begin{document}
\input{curriculum-vitae}
\clearpage
\input{cover-letter}
\end{document}


text:
import React, { PropTypes } from 'react';

import { IconRadio, TextField, PriceField, Checkbox, JSONList } from '../../Fields';

import PriceSVG from '../../SVGs/Price';
import PaymentMethodSVG from '../../SVGs/PaymentMethod';
import FeatureModal from '../../../containers/Modals/Feature';

import styles from './styles.css';

const PAYMENT_OPTIONS = [
  { text: 'FREE', value: 'free', icon: <PriceSVG free /> },
  { text: 'PAID', value: 'paid', icon: <PriceSVG /> }
];

const METHODS_OPTIONS = [
  { text: 'Cash only', value: 'cash', icon: <PaymentMethodSVG cash /> },
  { text: 'Cash or card', value: 'cash,card', icon: <PaymentMethodSVG card cash /> },
  { text: 'Card only', value: 'card', icon: <PaymentMethodSVG card /> }
];

export default class PricingField extends React.Component { // eslint-disable-line react/prefer-stateless-function
  static propTypes = {
    value: PropTypes.object,
    onChange: PropTypes.func
  };
  static contextTypes = {
    notify: PropTypes.func,
    modal: PropTypes.object
  }
  setFree = () => {
    const { value, onChange } = this.props;
    if (!value || value.type !== 'free') onChange({ type: 'free' });
  }
  setPaid = () => {
    const { value, onChange } = this.props;
    if (!value || value.type !== 'paid') onChange({ type: 'paid', prices: [{}] });
  }
  setPaidMulti = () => {
    const { value } = this.props;
    const { prices } = value;
    value.type = 'multi';
    value.prices = (prices && prices.length) ? prices : [{}];
    this.props.onChange(value);
  }
  setPaidSimple = () => {
    const { value } = this.props;
    value.type = 'paid';
    value.prices = value.prices.concat({ price: '' }).slice(0, 1);
    this.props.onChange(value);
  }
  setMethod = methods => {
    const { value, onChange } = this.props;
    value.paymentMethods = methods;
    onChange(value);
  }
  setPrices = prices => {
    const { value, onChange } = this.props;
    value.prices = prices;
    onChange(value);
  }
  setFirstFree = firstFree => {
    const { value, onChange } = this.props;
    value.firstFree = firstFree;
    onChange(value);
  }
  changePrice = price => {
    const { value, onChange } = this.props;
    value.prices[0].price = price;
    onChange(value);
  }
  renderFree() {
    return (

 Your session is free to attend

);
  }
  renderPaid() {
    const { value } = this.props;
    return (

        {value.type === 'multi' ? this.renderPrices() : this.renderPrice()}

        What payment methods do you accept?
        <IconRadio value={value.paymentMethods} options={METHODS_OPTIONS} onChange={this.setMethod} />

        Offer the first session for free?

          <Checkbox checked={value.firstFree} onChange={checked => this.setFirstFree(checked)} label="Yes, first time attendees get a free session" />

);
  }
  renderPrice() {
    const { value } = this.props;
    return (

      How much does this session cost?

<PriceField value={value.prices[0] ? value.prices[0].price : ''} onChange={this.changePrice} />

More than one price?

);
  }
  renderPrices() {
    const { value } = this.props;
    return (

<JSONList
        value={value.prices}
        onChange={this.setPrices}
        onAddEmpty={() => ({})}
        addText="Add attendee type"
        components={[
          { label: 'Type of attendee', Component: TextField, props: { name: 'type', size: 'S', placeholder: 'E.g. Adults / concessions' } },
          { label: 'Price', Component: PriceField, props: { name: 'price' } }
        ]}
      />

Wait! My session has one simple price for everybody

);
  }
  render() {
    const { value } = this.props;
    const isPaid = value && ['paid', 'multi'].indexOf(value.type) !== -1;
    return (

<IconRadio options={PAYMENT_OPTIONS} onChange={val => (val === 'free' ? this.setFree() : this.setPaid())} value={isPaid ? 'paid' : 'free'} inline />

      {isPaid ? this.renderPaid() : this.renderFree()}

        !

Please note: attendees will be able to turn up at your session without reserving a spot

 this.context.modal.dispatch({ component: <FeatureModal feature="Booking & attendee list" /> })}>Need to know who's coming?

);
  }
}


text:
package com.lethalskillzz.bakingapp.recipedetail;

import android.support.test.espresso.contrib.RecyclerViewActions;
import android.support.test.filters.LargeTest;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;

import com.lethalskillzz.bakingapp.R;
import com.lethalskillzz.baker.presentation.recipedetail.RecipeDetailActivity;

import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.assertion.ViewAssertions.doesNotExist;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withParent;
import static org.hamcrest.CoreMatchers.allOf;

@RunWith(AndroidJUnit4.class)
@LargeTest
public class RecipeDetailsActivityUITest {

  private static final int STEP_WITH_VIDEO = 0;
  private static final int STEP_WITHOUT_VIDEO = 1;

  @Rule
  public ActivityTestRule<RecipeDetailActivity> activityActivityTestRule =
      new ActivityTestRule<>(RecipeDetailActivity.class);

  @Test
  public void clickOnRecyclerViewItem_opensRecipeStepActivity() {

    onView(withId(R.id.recipe_detail_recycler_view))
        .perform(RecyclerViewActions.actionOnItemAtPosition(1, click()));

    onView(withId(R.id.step_viewpager))
        .check(matches(isDisplayed()));
  }

  @Test
  public void clickOnStepWithVideo_showsVideoPlayerView() {

    onView(withId(R.id.recipe_detail_recycler_view))
        .perform(RecyclerViewActions.actionOnItemAtPosition(STEP_WITH_VIDEO, click()));

    onView(
        allOf(
            withId(R.id.fragment_step_exo_player_view),
            withParent(withParent(withId(R.id.recipe_step_layout))),
            isDisplayed()))
        .check(matches(isDisplayed()));
  }

  @Test
  public void clickOnStepWithoutVideo_hidesVideoPlayerView() {

    onView(withId(R.id.recipe_detail_recycler_view))
        .perform(RecyclerViewActions.actionOnItemAtPosition(STEP_WITHOUT_VIDEO, click()));

    onView(
        allOf(
            withId(R.id.fragment_step_exo_player_view),
            withParent(withParent(withId(R.id.recipe_step_layout))),
            isDisplayed()))
        .check(doesNotExist());
  }
}


text:
https-happiness
===============

Goal is to add all Australian government sites to [HTTPS Everywhere](https://www.eff.org/https-everywhere).

Status
-------

**DONE!**
11/11 chunks merged with HTTPS Everywhere (Each chunk has 10 rules)

Setup
--------

* I used [Digital Ocean](https://www.digitalocean.com/?refcode=2f68bde48289)'s 512mb droplet with Ubuntu 14.04 x64.
* `apt-get install nodejs npm php5`
* `npm install cheerio request`

Production Quality?
-------------------
These are quick and dirty scripts to get the job done! The data ends up being reviewed manually.


text: Rails.application.config.session_store :cookie_store, key: '_spirit_on_rails_session'


text:
namespace ekam {

// TODO:  Use new openat() and friends?  Very capability-like!

namespace {

class DirectoryReader {
public:
  DirectoryReader(const std::string& path)
      : path(path),
        dir(opendir(path.c_str())) {
    if (dir == NULL) {
      // TODO:  Better exception type.
      throw OsError(path, "opendir", ENOTDIR);
    }
  }

  ~DirectoryReader() {
    if (closedir(dir) < 0) {
      DEBUG_ERROR << path << ": closedir: " << strerror(errno);
    }
  }

  bool next(std::string* output) {
    struct dirent entry, *entryPointer;
    int error = readdir_r(dir, &entry, &entryPointer);
    if (error != 0) {
      throw OsError(path, "readdir", error);
    }

    if (entryPointer == NULL) {
      return false;
    } else {
      *output = entryPointer->d_name;
      return true;
    }
  }

private:
  const std::string& path;
  DIR* dir;
};

bool statIfExists(const std::string& path, struct stat* output) {
  int result;
  do {
    result = stat(path.c_str(), output);
  } while (result < 0 && errno == EINTR);

  if (result == 0) {
    return true;
  } else if (errno == ENOENT) {
    return false;
  } else {
    throw OsError(path, "stat", errno);
  }
}

}  // anonymous namespace

DiskFile::DiskFile(const std::string& path, File* parent) : path(path) {
  if (parent != NULL) {
    this->parentRef = parent->clone();
  }
}
DiskFile::~DiskFile() {}

std::string DiskFile::basename() {
  if (path.empty()) {
    return ".";
  }

  std::string::size_type slashPos = path.find_last_of('/');
  if (slashPos == std::string::npos) {
    return path;
  } else {
    return path.substr(slashPos + 1);
  }
}

std::string DiskFile::canonicalName() {
  if (parentRef == NULL) {
    return ".";
  }

  std::string result = parentRef->canonicalName();
  if (result == ".") {
    result.clear();
  } else {
    result.push_back('/');
  }
  result.append(basename());

  return result;
}

OwnedPtr<File> DiskFile::clone() {
  return newOwned<DiskFile>(path, parentRef.get());
}

bool DiskFile::hasParent() {
  return parentRef != NULL;
}

OwnedPtr<File> DiskFile::parent() {
  if (parentRef == NULL) {
    throw std::runtime_error("Tried to get parent of top-level directory: " + canonicalName());
  }
  return parentRef->clone();
}

bool DiskFile::equals(File* other) {
  DiskFile* otherDiskFile = dynamic_cast<DiskFile*>(other);
  return otherDiskFile != NULL && otherDiskFile->path == path;
}

size_t DiskFile::identityHash() {
  return std::hash<std::string>()(path);
}

class DiskFile::DiskRefImpl : public File::DiskRef {
public:
  DiskRefImpl(const std::string& path) : pathName(path) {}
  ~DiskRefImpl() {}

  // implements DiskRef ------------------------------------------------------------------
  virtual const std::string& path() { return pathName; }

private:
  std::string pathName;
};

OwnedPtr<File::DiskRef> DiskFile::getOnDisk(Usage usage) {
  return newOwned<DiskRefImpl>(path);
}

bool DiskFile::exists() {
  struct stat stats;
  return statIfExists(path.c_str(), &stats) && (S_ISREG(stats.st_mode) || S_ISDIR(stats.st_mode));
}

bool DiskFile::isFile() {
  struct stat stats;
  return statIfExists(path.c_str(), &stats) && S_ISREG(stats.st_mode);
}

bool DiskFile::isDirectory() {
  struct stat stats;
  return statIfExists(path.c_str(), &stats) && S_ISDIR(stats.st_mode);
}

// File only.
Hash DiskFile::contentHash() {
  try {
    Hash::Builder hasher;
    ByteStream fd(path, O_RDONLY);

    char buffer[8192];

    while (true) {
      size_t n = fd.read(buffer, sizeof(buffer));
      if (n == 0) {
        return hasher.build();
      }

      hasher.add(buffer, n);
    }
  } catch (const OsError& e) {
    if (e.getErrorNumber() == ENOENT || e.getErrorNumber() == EACCES ||
        e.getErrorNumber() == EISDIR) {
      return Hash::NULL_HASH;
    }
    throw;
  }
}

std::string DiskFile::readAll() {
  ByteStream fd(path, O_RDONLY);

  struct stat stats;
  fd.stat(&stats);
  size_t size = stats.st_size;

  std::string result;
  if (size > 0) {
    result.resize(size);
    char* buffer = &*result.begin();
    size_t bytesRead = 0;
    while (size > bytesRead) {
      ssize_t n = fd.read(buffer + bytesRead, size - bytesRead);

      if (n == 0) {
        result.resize(bytesRead);
        size = bytesRead;
      } else {
        bytesRead += n;
      }
    }
  }

  return result;
}

void DiskFile::writeAll(const std::string& content) {
  ByteStream fd(path, O_WRONLY | O_TRUNC | O_CREAT);

  std::string::size_type pos = 0;
  while (pos < content.size()) {
    pos += fd.write(content.data() + pos, content.size() - pos);
  }
}

void DiskFile::writeAll(const void* data, int size) {
  ByteStream fd(path, O_WRONLY | O_TRUNC | O_CREAT);

  const char* pos = reinterpret_cast<const char*>(data);
  while (size > 0) {
    int n = fd.write(pos, size);
    pos += n;
    size -= n;
  }
}

// Directory only.
void DiskFile::list(OwnedPtrVector<File>::Appender output) {
  std::string prefix;
  if (!path.empty()) {
    prefix = path + "/";
  }

  DirectoryReader reader(path);
  std::string filename;
  while (reader.next(&filename)) {
    if (filename.empty()) {
      DEBUG_ERROR << "DirectoryReader returned empty file name.";
    } else if (filename[0] != '.') {  // skip hidden files
      output.add(newOwned<DiskFile>(prefix + filename, this));
    }
  }
}

OwnedPtr<File> DiskFile::relative(const std::string& path) {
  if (path.empty()) {
    throw std::invalid_argument("File::relative(): path cannot be empty.");
  } else if (path[0] == '/') {
    throw std::invalid_argument("File::relative(): path cannot start with a slash.");
  }

  std::string::size_type slash_pos = path.find_first_of('/');
  std::string first_part;
  std::string rest;
  if (slash_pos == std::string::npos) {
    if (path == ".") {
      return clone();
    } else if (path == "..") {
      return parent();
    } else if (this->path.empty()) {
      return newOwned<DiskFile>(path, this);
    } else {
      return newOwned<DiskFile>(this->path + "/" + path, this);
    }

  } else {
    first_part.assign(path, 0, slash_pos);

    std::string::size_type after_slash_pos = path.find_first_not_of('/', slash_pos);

    if (after_slash_pos == std::string::npos) {
      // Trailing slash.  Bah.
      return relative(first_part);
    } else {
      rest.assign(path, after_slash_pos, std::string::npos);

      if (first_part == ".") {
        return relative(rest);
      } else if (first_part == "..") {
        if (parentRef == NULL) {
          throw std::runtime_error(
              "Tried to get parent of top-level directory: " + canonicalName());
        }
        return parentRef->relative(rest);
      } else {
        OwnedPtr<File> temp;
        if (this->path.empty()) {
          temp = newOwned<DiskFile>(first_part, this);
        } else {
          temp = newOwned<DiskFile>(this->path + "/" + first_part, this);
        }
        return temp->relative(rest);
      }
    }
  }
}

void DiskFile::createDirectory() {
  while (true) {
    if (mkdir(path.c_str(), 0777) == 0) {
      return;
    } else if (errno != EINTR) {
      throw OsError(path, "mkdir", errno);
    }
  }
}

void DiskFile::link(File* target) {
  DiskFile* diskTarget = dynamic_cast<DiskFile*>(target);
  if (diskTarget == NULL) {
    throw new std::invalid_argument("Cannot link disk file to non-disk file: " + path);
  }

  WRAP_SYSCALL(link, diskTarget->path.c_str(), path.c_str());
}

void DiskFile::unlink() {
  WRAP_SYSCALL(unlink, path.c_str());
}

}  // namespace ekam


text:
.. SPDX-License-Identifier: GPL-2.0

=======================
Linux PCI Bus Subsystem
=======================

.. toctree::
   :maxdepth: 2
   :numbered:

   pci
   pciebus-howto
   pci-iov-howto
   msi-howto
   acpi-info
   pci-error-recovery
   pcieaer-howto
   endpoint/index


text:
#ifndef ACGL_OPENGL_OBJECTS_ELEMENTBUFFERDATA_HH
#define ACGL_OPENGL_OBJECTS_ELEMENTBUFFERDATA_HH

/**
 * An ElementArrayBuffer is an index into ArrayBuffers and defines which
 * elements of that array should be drawn in which order.
 *
 * The combination of (multiple) attributes of (multiple) ArrayBuffers
 * and one (optional) ElementArrayBuffer is a VertexBufferObject or VertexArrayObject.
 *
 * Note: In some documents ElementArrayBuffer are called VertexBufferObjects, VBOs
 *       or IndexBufferObjects (IBOs). But ArrayBuffers can also be called VBOs...
 *       The original extension that introduced these two new buffer types was called
 *       ARB_vertex_buffer_object but the buffers itself are called ArrayBuffer and
 *       ElementArrayBuffer.
 *
 * WARNING: On word of warning about the EAB: Setting data (e.g. via setData() ) will
 *          of course have to bind this buffer first. The binding of an EAB is a state
 *          of the currently bound VAO, not a global OpenGL state so make sure you bind
 *          the corresponding VAO or VAO 0 first, otherwise there will be a side-effect
 *          of having the wrong EAB bound to some random VAO that just happened to be
 *          bound by chance.
 *          While this behaviour is also true for other buffers and textures, those are
 *          bound to a global OpenGL state that gets changed all the time anyway so you
 *          are probably used to rebind those before using while a VAO does not rebind
 *          its own EAB before drawing as the binding is a state of the VAO.
 *          In debug mode the VAO will check for this kind of inconsistancy that arise
 *          from wrong usage.
 *          Other reasons why a wrong EAB is set to a VAO: Driver bug (some older Intel
 *          drivers did not store the EAB as a VAO state), manual binding (calling of bare
 *          OpenGL commands).
 */

#include <ACGL/ACGL.hh>

#include <ACGL/Base/Macros.hh>
#include <ACGL/OpenGL/GL.hh>
#include <ACGL/OpenGL/Tools.hh>
#include <ACGL/OpenGL/Objects/Buffer.hh>

namespace ACGL{
namespace OpenGL{

class ElementArrayBuffer : public Buffer
{
    // ========================================================================================================= \/
    // ============================================================================================ CONSTRUCTORS \/
    // ========================================================================================================= \/
public:
    ElementArrayBuffer( GLenum _type = GL_UNSIGNED_INT)
        : Buffer(GL_ELEMENT_ARRAY_BUFFER), mType(_type)
    {}

    ElementArrayBuffer( SharedBufferObject _pBuffer, GLenum _type  = GL_UNSIGNED_INT)
         : Buffer(_pBuffer, GL_ELEMENT_ARRAY_BUFFER), mType(_type)
    {}

    // ==================================================================================================== \/
    // ============================================================================================ GETTERS \/
    // ==================================================================================================== \/
public:
    //! returns the index data type: GL_UNSIGNED_BYTE, GL_UNSIGNED_SHORT, GL_UNSIGNED_INT
    inline GLenum getType(void) const { return mType; }

    // ==================================================================================================== \/
    // ============================================================================================ SETTERS \/
    // ==================================================================================================== \/
public:
    //! _type has to be one of GL_UNSIGNED_BYTE, GL_UNSIGNED_SHORT, GL_UNSIGNED_INT and indicates the
    //! datatype of the indices
    inline void setType (GLenum _type) { mType = _type; }

    //! set data for this buffer for a given number of elements (size in bytes == _elements * size of mType)
    inline void setDataElements( uint_t _elements, const GLvoid *_pData = NULL, GLenum _usage = GL_STATIC_DRAW )
    {
        setData( mTarget, _elements * getGLTypeSize(mType), _pData, _usage );
    }

    //! Returns the number of indices:
    inline GLuint getElements() const
    {
        return (GLuint)( getSize() / getGLTypeSize(mType));
    }

    //! Overloaded from the base class to _prevent_ redefining of the binding target! (see Buffer)
    inline void setTarget( GLenum )
    {
        ACGL::Utils::error() << "DON'T redefine the target binding point of an ElementArrayBuffer" << std::endl;
    }

    // =================================================================================================== \/
    // ============================================================================================ FIELDS \/
    // =================================================================================================== \/
protected:
    //! index data type: GL_UNSIGNED_BYTE, GL_UNSIGNED_SHORT, GL_UNSIGNED_INT
    GLenum mType;
};

ACGL_SMARTPOINTER_TYPEDEFS(ElementArrayBuffer)

} // OpenGL
} // ACGL

#endif // ACGL_OPENGL_OBJECTS_ELEMENTBUFFERDATA_HH


text:
'use strict';

const state = require('../../../yakServerState');
const InstanceState = require('../../../instance/instanceState');
const log = require('../../../infrastructure/logger').defaultLogger;
const HttpStatus = require('http-status-codes');

/**
 * @param request
 * @param response
 */
function postRestartRunningInstancesRoute(request, response) {
    let instances = state.instanceManager.getInstances();

    Promise
        .all(instances
            .filter(instance => instance.state === InstanceState.RUNNING)
            .map(instance => instance
                .stop()
                .then(instance.start)
                .catch(() => {
                    response.status(HttpStatus.INTERNAL_SERVER_ERROR);
                    log.warn('Could not restart all running instances.');
                })
            )
        )
        .then(() => {
            response.send();
        });
}

module.exports = postRestartRunningInstancesRoute;


text:
#region << 版 本 注 释 >>

#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;

namespace Dos.ORM
{
    public class PartialEvaluator : PartialEvaluatorBase
    {
        public PartialEvaluator()
            : base(new Evaluator())
        { }
    }
}


text:
date: 2015-10-22
title: Working in a Production Environment
speaker: Jay Bobo and Vasanth Pappu from CoverMyMeds
type: Meeting
---

Hi everyone,

This Thursday at 7:00PM in Caldwell Labs 120, Jay Bobo and Vasanth Pappu from CoverMyMeds will discuss what it's like working in a production environment. For those that are unfamiliar, CoverMyMeds is a Columbus startup that automates the Prior Authorization process in the healthcare industry. I urge everyone to go check them out!

Laptops are encouraged but not required, and as always, there will be pizza.


text:
package main

import (
	"github.com/dgnorton/dmapi"
	htmlTemplate "html/template"
	"io"
	"io/ioutil"
	textTemplate "text/template"
)

func fprintText(wr io.Writer, e *dmapi.Entries, templateFile string) error {
	bytes, err := ioutil.ReadFile(templateFile)
	if err != nil {
		return err
	}

	txt, err := textTemplate.New("txt").Parse(string(bytes))
	if err != nil {
		return err
	}

	err = txt.ExecuteTemplate(wr, "txt", e)

	return err
}

func fprintHTML(wr io.Writer, e *dmapi.Entries, templateFile string) error {
	bytes, err := ioutil.ReadFile(templateFile)
	if err != nil {
		return err
	}

	html, err := htmlTemplate.New("html").Parse(string(bytes))
	if err != nil {
		return err
	}

	err = html.ExecuteTemplate(wr, "html", e)

	return err
}


text:
require "extend/string"
require "tempfile"
require "utils/inreplace"

describe StringInreplaceExtension do
  subject { described_class.new(string.dup) }

  describe "#change_make_var!" do
    context "flag" do
      context "with spaces" do
        let(:string) do
          <<~EOS
            OTHER=def
            FLAG = abc
            FLAG2=abc
          EOS
        end

        it "is successfully replaced" do
          subject.change_make_var! "FLAG", "def"
          expect(subject.inreplace_string).to eq <<~EOS
            OTHER=def
            FLAG=def
            FLAG2=abc
          EOS
        end

        it "is successfully appended" do
          subject.change_make_var! "FLAG", "\\1 def"
          expect(subject.inreplace_string).to eq <<~EOS
            OTHER=def
            FLAG=abc def
            FLAG2=abc
          EOS
        end
      end

      context "with tabs" do
        let(:string) do
          <<~EOS
            CFLAGS\t=\t-Wall -O2
            LDFLAGS\t=\t-lcrypto -lssl
          EOS
        end

        it "is successfully replaced" do
          subject.change_make_var! "CFLAGS", "-O3"
          expect(subject.inreplace_string).to eq <<~EOS
            CFLAGS=-O3
            LDFLAGS\t=\t-lcrypto -lssl
          EOS
        end
      end

      context "with newlines" do
        let(:string) do
          <<~'EOS'
            CFLAGS = -Wall -O2 \
                     -DSOME_VAR=1
            LDFLAGS = -lcrypto -lssl
          EOS
        end

        it "is successfully replaced" do
          subject.change_make_var! "CFLAGS", "-O3"
          expect(subject.inreplace_string).to eq <<~EOS
            CFLAGS=-O3
            LDFLAGS = -lcrypto -lssl
          EOS
        end
      end
    end

    context "empty flag between other flags" do
      let(:string) do
        <<~EOS
          OTHER=def
          FLAG =
          FLAG2=abc
        EOS
      end

      it "is successfully replaced" do
        subject.change_make_var! "FLAG", "def"
        expect(subject.inreplace_string).to eq <<~EOS
          OTHER=def
          FLAG=def
          FLAG2=abc
        EOS
      end
    end

    context "empty flag" do
      let(:string) do
        <<~EOS
          FLAG =
          mv file_a file_b
        EOS
      end

      it "is successfully replaced" do
        subject.change_make_var! "FLAG", "def"
        expect(subject.inreplace_string).to eq <<~EOS
          FLAG=def
          mv file_a file_b
        EOS
      end
    end

    context "shell-style variable" do
      let(:string) do
        <<~EOS
          OTHER=def
          FLAG=abc
          FLAG2=abc
        EOS
      end

      it "is successfully replaced" do
        subject.change_make_var! "FLAG", "def"
        expect(subject.inreplace_string).to eq <<~EOS
          OTHER=def
          FLAG=def
          FLAG2=abc
        EOS
      end
    end
  end

  describe "#remove_make_var!" do
    context "flag" do
      context "with spaces" do
        let(:string) do
          <<~EOS
            OTHER=def
            FLAG = abc
            FLAG2 = def
          EOS
        end

        it "is successfully removed" do
          subject.remove_make_var! "FLAG"
          expect(subject.inreplace_string).to eq <<~EOS
            OTHER=def
            FLAG2 = def
          EOS
        end
      end

      context "with tabs" do
        let(:string) do
          <<~EOS
            CFLAGS\t=\t-Wall -O2
            LDFLAGS\t=\t-lcrypto -lssl
          EOS
        end

        it "is successfully removed" do
          subject.remove_make_var! "LDFLAGS"
          expect(subject.inreplace_string).to eq <<~EOS
            CFLAGS\t=\t-Wall -O2
          EOS
        end
      end

      context "with newlines" do
        let(:string) do
          <<~'EOS'
            CFLAGS = -Wall -O2 \
                     -DSOME_VAR=1
            LDFLAGS = -lcrypto -lssl
          EOS
        end

        it "is successfully removed" do
          subject.remove_make_var! "CFLAGS"
          expect(subject.inreplace_string).to eq <<~EOS
            LDFLAGS = -lcrypto -lssl
          EOS
        end
      end
    end

    context "multiple flags" do
      let(:string) do
        <<~EOS
          OTHER=def
          FLAG = abc
          FLAG2 = def
          OTHER2=def
        EOS
      end

      specify "are be successfully removed" do
        subject.remove_make_var! ["FLAG", "FLAG2"]
        expect(subject.inreplace_string).to eq <<~EOS
          OTHER=def
          OTHER2=def
        EOS
      end
    end
  end

  describe "#get_make_var" do
    context "with spaces" do
      let(:string) do
        <<~EOS
          CFLAGS = -Wall -O2
          LDFLAGS = -lcrypto -lssl
        EOS
      end

      it "extracts the value for a given variable" do
        expect(subject.get_make_var("CFLAGS")).to eq("-Wall -O2")
      end
    end

    context "with tabs" do
      let(:string) do
        <<~EOS
          CFLAGS\t=\t-Wall -O2
          LDFLAGS\t=\t-lcrypto -lssl
        EOS
      end

      it "extracts the value for a given variable" do
        expect(subject.get_make_var("CFLAGS")).to eq("-Wall -O2")
      end
    end

    context "with newlines" do
      let(:string) do
        <<~'EOS'
          CFLAGS = -Wall -O2 \
                   -DSOME_VAR=1
          LDFLAGS = -lcrypto -lssl
        EOS
      end

      it "extracts the value for a given variable" do
        expect(subject.get_make_var("CFLAGS")).to match(/^-Wall -O2 \\\n +-DSOME_VAR=1$/)
      end
    end
  end

  describe "#sub!" do
    let(:string) { "foo" }

    it "replaces the first occurrence" do
      subject.sub!("o", "e")
      expect(subject.inreplace_string).to eq("feo")
    end
  end

  describe "#gsub!" do
    let(:string) { "foo" }

    it "replaces all occurrences" do
      subject.gsub!("o", "e") # rubocop:disable Performance/StringReplacement
      expect(subject.inreplace_string).to eq("fee")
    end
  end
end

describe Utils::Inreplace do
  let(:file) { Tempfile.new("test") }

  before do
    file.write <<~EOS
      a
      b
      c
    EOS
  end

  after { file.unlink }

  it "raises error if there are no files given to replace" do
    expect {
      described_class.inreplace [], "d", "f"
    }.to raise_error(Utils::Inreplace::Error)
  end

  it "raises error if there is nothing to replace" do
    expect {
      described_class.inreplace file.path, "d", "f"
    }.to raise_error(Utils::Inreplace::Error)
  end

  it "raises error if there is nothing to replace in block form" do
    expect {
      described_class.inreplace(file.path) do |s|
        s.gsub!("d", "f") # rubocop:disable Performance/StringReplacement
      end
    }.to raise_error(Utils::Inreplace::Error)
  end

  it "raises error if there is no make variables to replace" do
    expect {
      described_class.inreplace(file.path) do |s|
        s.change_make_var! "VAR", "value"
        s.remove_make_var! "VAR2"
      end
    }.to raise_error(Utils::Inreplace::Error)
  end

  describe "#inreplace_pairs" do
    it "raises error if there is no old value" do
      expect {
        described_class.inreplace_pairs(file.path, [[nil, "f"]])
      }.to raise_error(Utils::Inreplace::Error)
    end
  end
end


text:
/**
 * Converts Object into string JSON representation
 */
function objectToJSON(object) {
    if (!object.typeof(Object)) {
        return null;
    }
    var objectJSONstring = JSON.stringify(object);
    return objectJSONstring;
}

/**
 * Converts JSON string representation of object into Object
 */
function JSONStringToObject(JSONString) {
    if (!JSONString.typeof(String)) {
        return null;
    }

    var object = JSON.parse(JSONString);
    return object;
}


text:
import logging
import inspect
import unittest

from perfkitbenchmarker import log_util
from perfkitbenchmarker import vm_util

class LogUtilTestCase(unittest.TestCase):
  """Tests exercising the utilities in log_util."""

  def testThreadLogContextExtendLabel(self):
    """Verify ThreadLogContext.ExtendLabel behavior."""
    context = log_util.ThreadLogContext()
    self.assertEqual(context.label, '')
    with context.ExtendLabel('LABEL-A'):
      self.assertEqual(context.label, 'LABEL-A ')
      with context.ExtendLabel('LABEL-B'):
        self.assertEqual(context.label, 'LABEL-A LABEL-B ')
      self.assertEqual(context.label, 'LABEL-A ')
    self.assertEqual(context.label, '')

  def testThreadLogContextExtendLabelEmptyStrings(self):
    """Verify ThreadLogContext.ExtendLabel behavior with empty strings."""
    context = log_util.ThreadLogContext()
    self.assertEqual(context.label, '')
    with context.ExtendLabel(''):
      self.assertEqual(context.label, '')
      with context.ExtendLabel('LABEL-A'):
        self.assertEqual(context.label, 'LABEL-A ')
        with context.ExtendLabel(''):
          self.assertEqual(context.label, 'LABEL-A ')
          with context.ExtendLabel('LABEL-B'):
            self.assertEqual(context.label, 'LABEL-A LABEL-B ')
          self.assertEqual(context.label, 'LABEL-A ')
        self.assertEqual(context.label, 'LABEL-A ')
      self.assertEqual(context.label, '')
    self.assertEqual(context.label, '')

  def testThreadLogContextCopyConstruct(self):
    """Verify ThreadLogContext init with a reference ThreadLogContext behavior.

    The label state of the first ThreadLogContext should be copied.
    """
    original = log_util.ThreadLogContext()
    self.assertEqual(original.label, '')
    with original.ExtendLabel('LABEL-A'):
      self.assertEqual(original.label, 'LABEL-A ')
      copied = log_util.ThreadLogContext(original)
      self.assertEqual(original.label, 'LABEL-A ')
      self.assertEqual(copied.label, 'LABEL-A ')
      with original.ExtendLabel('LABEL-B'):
        self.assertEqual(original.label, 'LABEL-A LABEL-B ')
        self.assertEqual(copied.label, 'LABEL-A ')
        with copied.ExtendLabel('LABEL-C'):
          self.assertEqual(original.label, 'LABEL-A LABEL-B ')
          self.assertEqual(copied.label, 'LABEL-A LABEL-C ')
        self.assertEqual(original.label, 'LABEL-A LABEL-B ')
        self.assertEqual(copied.label, 'LABEL-A ')
      self.assertEqual(original.label, 'LABEL-A ')
      self.assertEqual(copied.label, 'LABEL-A ')
    self.assertEqual(original.label, '')
    self.assertEqual(copied.label, 'LABEL-A ')

  def testRunThreadedContextCopy(self):
    """Verify that ThreadLogContext is copied to threads by vm_util.RunThreaded.
    """
    original = log_util.ThreadLogContext()
    log_util.SetThreadLogContext(original)
    t1_list = ['T1']
    t2_list = ['T2']
    self.assertEqual(original.label, '')
    with original.ExtendLabel('T0'):
      self.assertEqual(original.label, 'T0 ')
      vm_util.RunThreaded(
          target=LogUtilTestCase.RunThreadedContextCopyHelper,
          thread_params=[t1_list, t2_list])
      self.assertEqual(original.label, 'T0 ')
      self.assertEqual(t1_list, ['T1', 'T0 ', 'T0 T1 ', 'T0 '])
      self.assertEqual(t2_list, ['T2', 'T0 ', 'T0 T2 ', 'T0 '])

  @staticmethod
  def RunThreadedContextCopyHelper(my_list):
    """Helper method used by testRunThreadedContextCopy."""
    context = log_util.GetThreadLogContext()
    my_list.append(context.label)
    with context.ExtendLabel(my_list[0]):
      my_list.append(context.label)
    my_list.append(context.label)

  def testPkbLogFilter(self):
    """Verify that PkbLogFilter sets the pkb_label of LogRecords it processes.
    """
    logger_name = 'log_util_test.LogUtilTestCase.testPkbLogFilter'
    context = log_util.ThreadLogContext()
    log_util.SetThreadLogContext(context)
    with context.ExtendLabel('LABEL-A'):
      log_record = logging.LogRecord(
          name=logger_name, level=logging.INFO, pathname=__file__,
          lineno=inspect.getframeinfo(inspect.currentframe()).lineno + 1,
          msg="Log message.", args=None, exc_info=None)
      log_util.PkbLogFilter().filter(log_record)
      self.assertEqual(log_record.pkb_label, 'LABEL-A ')

if __name__ == '__main__':
  unittest.main()