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

namespace CouchTrafficClient
{
    class QueryE : QueryBase
    {
        public override string Run()
        {
            List<object> detectorIDs = new List<object> { }, speeds = new List<object> { };
            List<double> stationLength = new List<double> { };
            List<string> stationName = new List<string> { };
            int highwayID = 0;
            // i. Find highway ID of "I-205 NB"
            List<object> keys = new List<object> { new List<object>{"NORTH", "N", "I-205"} }, startkeys = new List<object> { "" }, endkeys = new List<object> { "" };
            var result = Query("queryE", "getHighwayID", keys, false);
            List<object> outobject;
            highwayID = Convert.ToInt32(result.Values.First().First().ToString());

            // ii. Find station names and lengths of previously found highway ID
            keys.Clear();
            result.Clear();
            //outobject.Clear();
            keys = new List<object> { highwayID };
            result = Query("queryE", "getStationIDNameAndLength", keys, false);
            if (result.TryGetValue(highwayID.ToString(), out outobject))
            {
                foreach (List<object> o in outobject)
                {
                    stationName.Add(o.ElementAt(1).ToString());
                    stationLength.Add(Convert.ToDouble(o.ElementAt(2).ToString()));
                }
            }
            else
            {
                // Return error
            }

            // iii. Find all the detector IDs of each previously found station name
            List<object> detectorIDList = new List<object> { };
            foreach (string sn in stationName)
            {
                keys.Clear();
                result.Clear();
                outobject = new List<object> { };
                keys = new List<object> { sn };
                result = Query("queryD", "getDetectorIDs", keys, false);
                if (result.TryGetValue(sn, out outobject))
                {
                    detectorIDList.Add(outobject);
                }
                else
                {
                    detectorIDList.Add(new List<object> { });
                }
            }
            outobject = new List<object> { };

            // iv For each time period between 7-9AM and 4-6PM on September 22, 2011: Find the average of the speeds for all detector IDs as previously found. Then calculate the travel time for that station ID, for all station IDs:
            int detectorCount = 0, speedCount = 0, timePeriodCount = 0, stationCount = 0;
            double totalSpeed = 0, totalDetectorSpeed = 0, avgTotalDetectorSpeed = 0, totalAverageTravelTime = 0;
            // 9/22/2011 7:00:00 -> 9/22/2011 8:59:40
            for (long timeInstance = 1316700000000; timeInstance <= 1316707180000; timeInstance += 20000) // for each time instance
            {
                stationCount = 0;
                foreach (string sn in stationName) // for each station name
                {
                    detectorIDs = (List<object>)detectorIDList.ElementAt(stationCount);
                    foreach (long detectorID in detectorIDs) // for each detector of a station
                    {
                        startkeys.Clear();
                        endkeys.Clear();
                        result.Clear();
                        speeds.Clear();
                        startkeys = new List<object> { detectorID, timeInstance };
                        endkeys = new List<object> { detectorID, timeInstance, new List<object> { } };
                        result = QueryWithStartAndEnd("queryD", "getDetectorSpeeds", startkeys, endkeys, false);
                        if (result.Count > 0)
                        {
                            if (result.Values.First().First() != "")
                            {
                                speeds.Add(result.Values.First().First());
                            }
                        }
                        foreach (long speed in speeds) // for each speed of a detector
                        {
                            totalSpeed += speed;
                            speedCount++;
                        }
                        if (speedCount > 0)
                        {
                            totalDetectorSpeed += totalSpeed / speedCount;
                            totalSpeed = 0;
                            speedCount = 0;
                            detectorCount++;
                        }
                    }
                    if (detectorCount > 0)
                    {
                        avgTotalDetectorSpeed = totalDetectorSpeed / detectorCount;
                        totalDetectorSpeed = 0;
                        detectorCount = 0;
                        totalAverageTravelTime += (stationLength.ElementAt(stationCount) / avgTotalDetectorSpeed);
                        avgTotalDetectorSpeed = 0;
                    }
                    stationCount++;
                }
                timePeriodCount++;
            }
            var returnValueAM = (totalAverageTravelTime / timePeriodCount) * 60;
            totalAverageTravelTime = 0;
            timePeriodCount = 0;
            // 9/22/2011 16:00:00 -> 9/22/2011 17:59:40
            for (long timeInstance = 1316732400000; timeInstance <= 1316739580000; timeInstance += 20000) // for each time instance
            {
                stationCount = 0;
                foreach (string sn in stationName) // for each station name
                {
                    detectorIDs = (List<object>)detectorIDList.ElementAt(stationCount);
                    foreach (long detectorID in detectorIDs) // for each detector of a station
                    {
                        startkeys.Clear();
                        endkeys.Clear();
                        result.Clear();
                        speeds.Clear();
                        startkeys = new List<object> { detectorID, timeInstance };
                        endkeys = new List<object> { detectorID, timeInstance, new List<object> { } };
                        result = QueryWithStartAndEnd("queryD", "getDetectorSpeeds", startkeys, endkeys, false);
                        if (result.Count > 0)
                        {
                            if (result.Values.First().First() != "")
                            {
                                speeds.Add(result.Values.First().First());
                            }
                        }
                        foreach (long speed in speeds) // for each speed of a detector
                        {
                            totalSpeed += speed;
                            speedCount++;
                        }
                        if (speedCount > 0)
                        {
                            totalDetectorSpeed += totalSpeed / speedCount;
                            totalSpeed = 0;
                            speedCount = 0;
                            detectorCount++;
                        }
                    }
                    if (detectorCount > 0)
                    {
                        avgTotalDetectorSpeed = totalDetectorSpeed / detectorCount;
                        totalDetectorSpeed = 0;
                        detectorCount = 0;
                        totalAverageTravelTime += (stationLength.ElementAt(stationCount) / avgTotalDetectorSpeed);
                        avgTotalDetectorSpeed = 0;
                    }
                    stationCount++;
                }
                timePeriodCount++;
            }

            var returnValuePM = (totalAverageTravelTime / timePeriodCount) * 60;
            return string.Format("The average travel time for the I-205 NB freeway in minutes on September 22, 2011 for\n7-9AM = {0}\n4-6PM = {1}.", returnValueAM.ToString(), returnValuePM.ToString());
        }
    }
}


text:
extern short	g_sModelIndexBubbles;// holds the index for the bubbles model

//-----------------------------------------------------------------------------
// Purpose: Dispatches bubbles
//-----------------------------------------------------------------------------
class CTEBubbles : public CBaseTempEntity
{
public:
	DECLARE_CLASS( CTEBubbles, CBaseTempEntity );

					CTEBubbles( const char *name );
	virtual			~CTEBubbles( void );

	virtual void	Test( const Vector& current_origin, const QAngle& current_angles );

	DECLARE_SERVERCLASS();

public:
	CNetworkVector( m_vecMins );
	CNetworkVector( m_vecMaxs );
	CNetworkVar( float, m_fHeight );
	CNetworkVar( int, m_nModelIndex );
	CNetworkVar( int, m_nCount );
	CNetworkVar( float, m_fSpeed );
};

//-----------------------------------------------------------------------------
// Purpose:
// Input  : *name -
//-----------------------------------------------------------------------------
CTEBubbles::CTEBubbles( const char *name ) :
	CBaseTempEntity( name )
{
	m_vecMins.Init();
	m_vecMaxs.Init();
	m_fHeight = 0.0;
	m_nModelIndex = 0;
	m_nCount = 0;
	m_fSpeed = 0;
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CTEBubbles::~CTEBubbles( void )
{
}

//-----------------------------------------------------------------------------
// Purpose:
// Input  : *current_origin -
//			*current_angles -
//-----------------------------------------------------------------------------
void CTEBubbles::Test( const Vector& current_origin, const QAngle& current_angles )
{
	// Fill in data
	m_vecMins = current_origin;

	Vector forward;

	m_vecMins.GetForModify()[2] += 24;

	AngleVectors( current_angles, &forward );
	forward[2] = 0.0;
	VectorNormalize( forward );

	VectorMA( m_vecMins, 100.0, forward, m_vecMins.GetForModify() );

	m_vecMaxs = m_vecMins + Vector( 256, 256, 256 );

	m_fSpeed = 2;
	m_nCount = 50;
	m_fHeight = 256;

	m_nModelIndex = g_sModelIndexBubbles;

	CBroadcastRecipientFilter filter;
	Create( filter, 0.0 );
}

IMPLEMENT_SERVERCLASS_ST(CTEBubbles, DT_TEBubbles)
	SendPropVector( SENDINFO(m_vecMins), -1, SPROP_COORD),
	SendPropVector( SENDINFO(m_vecMaxs), -1, SPROP_COORD),
	SendPropModelIndex( SENDINFO(m_nModelIndex) ),
	SendPropFloat( SENDINFO(m_fHeight ), 17, 0, MIN_COORD_INTEGER, MAX_COORD_INTEGER ),
	SendPropInt( SENDINFO(m_nCount), 8, SPROP_UNSIGNED ),
	SendPropFloat( SENDINFO(m_fSpeed ), 17, 0, MIN_COORD_INTEGER, MAX_COORD_INTEGER ),
END_SEND_TABLE()

// Singleton to fire TEBubbles objects
static CTEBubbles g_TEBubbles( "Bubbles" );

//-----------------------------------------------------------------------------
// Purpose:
// Input  : msg_dest -
//			delay -
//			*origin -
//			*recipient -
//			*mins -
//			*maxs -
//			height -
//			modelindex -
//			count -
//			speed -
//-----------------------------------------------------------------------------
void TE_Bubbles( IRecipientFilter& filter, float delay,
	const Vector* mins, const Vector* maxs, float height, int modelindex, int count, float speed )
{
	g_TEBubbles.m_vecMins = *mins;
	g_TEBubbles.m_vecMaxs = *maxs;
	g_TEBubbles.m_fHeight = height;
	g_TEBubbles.m_nModelIndex = modelindex;
	g_TEBubbles.m_nCount = count;
	g_TEBubbles.m_fSpeed = speed;

	// Send it over the wire
	g_TEBubbles.Create( filter, delay );
}

redpajama_set_name: RedPajamaGithub


text:
<resources>
    <string name="app_name">Faster Map Rendering</string>

    <string name="toggle_text">Faster render</string>
</resources>


text:
package influxdb

import (
	"context"

	"github.com/influxdata/influxdb/v2/kit/platform"
)

// ErrScraperTargetNotFound is the error msg for a missing scraper target.
const ErrScraperTargetNotFound = "scraper target not found"

// ops for ScraperTarget Store
const (
	OpListTargets   = "ListTargets"
	OpAddTarget     = "AddTarget"
	OpGetTargetByID = "GetTargetByID"
	OpRemoveTarget  = "RemoveTarget"
	OpUpdateTarget  = "UpdateTarget"
)

// ScraperTarget is a target to scrape
type ScraperTarget struct {
	ID            platform.ID `json:"id,omitempty"`
	Name          string      `json:"name"`
	Type          ScraperType `json:"type"`
	URL           string      `json:"url"`
	OrgID         platform.ID `json:"orgID,omitempty"`
	BucketID      platform.ID `json:"bucketID,omitempty"`
	AllowInsecure bool        `json:"allowInsecure,omitempty"`
}

// ScraperTargetStoreService defines the crud service for ScraperTarget.
type ScraperTargetStoreService interface {
	ListTargets(ctx context.Context, filter ScraperTargetFilter) ([]ScraperTarget, error)
	AddTarget(ctx context.Context, t *ScraperTarget, userID platform.ID) error
	GetTargetByID(ctx context.Context, id platform.ID) (*ScraperTarget, error)
	RemoveTarget(ctx context.Context, id platform.ID) error
	UpdateTarget(ctx context.Context, t *ScraperTarget, userID platform.ID) (*ScraperTarget, error)
}

// ScraperTargetFilter represents a set of filter that restrict the returned results.
type ScraperTargetFilter struct {
	IDs   map[platform.ID]bool `json:"ids"`
	Name  *string              `json:"name"`
	OrgID *platform.ID         `json:"orgID"`
	Org   *string              `json:"org"`
}

// ScraperType defines the scraper methods.
type ScraperType string

// Scraper types
const (
	// PrometheusScraperType parses metrics from a prometheus endpoint.
	PrometheusScraperType = "prometheus"
)

// ValidScraperType returns true is the type string is valid
func ValidScraperType(s string) bool {
	switch s {
	case PrometheusScraperType:
		return true
	default:
		return false
	}
}


text:
package com.baomidou.mybatisplus.test.mysql.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.session.RowBounds;

import com.baomidou.mybatisplus.test.mysql.MyBaseMapper;
import com.baomidou.mybatisplus.test.mysql.entity.User;

/**
 *

 * 继承 BaseMapper,就自动拥有CRUD方法
 *

 *
 * @author hubin
 * @Date 2016-01-23
 */
public interface UserMapper extends MyBaseMapper<User> {

    /**
     * 用户列表,分页显示
     *
     * @param pagination 传递参数包含该属性,即自动分页
     * @return
     */
    List<User> selectListRow(RowBounds pagination);

    /**
     * 注解插入【测试】
     */
    @Insert("insert into user(test_id,name,age) values(#{id},#{name},#{age})")
    int insertInjector(User user);

    /**
     * 自定义注入方法
     */
    int deleteAll();

    /**
     * 自定义注入逻辑删除方法

     * com.baomidou.mybatisplus.test.mysql.MetaObjectHandlerTest
     */
    int deleteLogicById(@Param("id") Long id);

    /**
     * 根据主键批量查询
     *
     * @param pagination
     * @param ids
     * @return
     */
    List<User> forSelect(RowBounds pagination, @Param("ids") List<String> ids);

}


text:
    <link data-require="bootstrap-css@3.3.6" data-semver="3.3.6" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css" />

The Chat

      <input type="text" id="nameInput" placeholder="Name" />
      <input type="text" id="messageInput" placeholder="Message" />
      <button ng-click="setmapmarker()" type="button">Locatie-delen</button>

Copyright © Your Website 2014


text:
import * as React from 'react';
import Button from '@material-ui/core/Button';
import ButtonGroup from '@material-ui/core/ButtonGroup';
import ArrowDropDownIcon from '@material-ui/icons/ArrowDropDown';
import ClickAwayListener from '@material-ui/core/ClickAwayListener';
import Grow from '@material-ui/core/Grow';
import Paper from '@material-ui/core/Paper';
import Popper from '@material-ui/core/Popper';
import MenuItem from '@material-ui/core/MenuItem';
import MenuList from '@material-ui/core/MenuList';

const options = ['Create a merge commit', 'Squash and merge', 'Rebase and merge'];

export default function SplitButton() {
  const [open, setOpen] = React.useState(false);
  const anchorRef = React.useRef<HTMLDivElement>(null);
  const [selectedIndex, setSelectedIndex] = React.useState(1);

  const handleClick = () => {
    console.info(`You clicked ${options[selectedIndex]}`);
  };

  const handleMenuItemClick = (
    event: React.MouseEvent<HTMLLIElement, MouseEvent>,
    index: number,
  ) => {
    setSelectedIndex(index);
    setOpen(false);
  };

  const handleToggle = () => {
    setOpen((prevOpen) => !prevOpen);
  };

  const handleClose = (event: Event) => {
    if (
      anchorRef.current &&
      anchorRef.current.contains(event.target as HTMLElement)
    ) {
      return;
    }

    setOpen(false);
  };

  return (
    <React.Fragment>
      <ButtonGroup variant="contained" ref={anchorRef} aria-label="split button">
        <Button onClick={handleClick}>{options[selectedIndex]}</Button>
        <Button
          size="small"
          aria-controls={open ? 'split-button-menu' : undefined}
          aria-expanded={open ? 'true' : undefined}
          aria-label="select merge strategy"
          aria-haspopup="menu"
          onClick={handleToggle}
        >
          <ArrowDropDownIcon />
        </Button>
      </ButtonGroup>
      <Popper
        open={open}
        anchorEl={anchorRef.current}
        role={undefined}
        transition
        disablePortal
      >
        {({ TransitionProps, placement }) => (
          <Grow
            {...TransitionProps}
            style={{
              transformOrigin:
                placement === 'bottom' ? 'center top' : 'center bottom',
            }}
          >
            <Paper>
              <ClickAwayListener onClickAway={handleClose}>
                <MenuList id="split-button-menu">
                  {options.map((option, index) => (
                    <MenuItem
                      key={option}
                      disabled={index === 2}
                      selected={index === selectedIndex}
                      onClick={(event) => handleMenuItemClick(event, index)}
                    >
                      {option}
                    </MenuItem>
                  ))}
                </MenuList>
              </ClickAwayListener>
            </Paper>
          </Grow>
        )}
      </Popper>
    </React.Fragment>
  );
}


text:
`Bubble` that can be shown anchored to `Anchor` element.

## [Online demo](https://mol.hyoo.ru/#!section=demos/readme/demo=mol_pop_demo)

## Usage example

```
<= Hint $mol_pop
	showed <= hint_showed?val 0
	align \bottom_center
	Anchor <= Hint_trigger $mol_check
		title \?
		checked?val <=> hint_showed?val 0
	bubble_content /
		<= hint_message @ \You can see me wen you want.
```

## Properties

**`Anchor() : $mol_view`**

`Bubble` will follow the `Anchor` component.

**`bubble_content() : $mol_view[]`**

Content of `Bubble`.

**`showed() : boolean`**

Shows `Bubble` if `true`.

**`align() : string`**

Align of `Bubble` to `Anchor`.

## Supported aligns

* `left_top`
* `left_center`
* `left_bottom`
* `right_top`
* `right_center`
* `right_bottom`
* `center`
* `top_left`
* `top_center`
* `top_right`
* `bottom_left`
* `bottom_center`
* `bottom_right`


text:
package io.fabric8.quickstarts.eip;

import org.apache.camel.language.NamespacePrefix;
import org.apache.camel.language.XPath;

/**
 * This class contains business logic that determines the region for a country. It is used by the Camel route in this example.
 */
public class RegionSupport {

    public static final String AMER = "AMER";
    public static final String APAC = "APAC";
    public static final String EMEA = "EMEA";

    /**
     * Get the region code that corresponds to the given country code.
     *
     * This method can be used as a plain Java method. However, when it is used inside a Camel route, the @XPath annotation will
     * evaluate the XPath expression and use the result as the method parameter. In this case, it will fetch the country code
     * from the order XML message. So, the method will determine the region code for the country that is in the XML message.
     *
     * @param country the country code
     * @return the region code
     */
    public String getRegion(@XPath(value = "/order:order/order:customer/order:country",
        namespaces = @NamespacePrefix(prefix = "order", uri = "http://fabric8.com/examples/order/v7")) String country) {
        if (country.equals("AU")) {
            return APAC;
        } else if (country.equals("US")) {
            return AMER;
        } else {
            return EMEA;
        }
    }
}


text:
package com.example;

import com.google.actions.api.ActionRequest;
import com.google.actions.api.ActionResponse;
import com.google.actions.api.DialogflowApp;
import com.google.actions.api.ForIntent;
import com.google.actions.api.response.ResponseBuilder;
import com.google.api.services.actions_fulfillment.v2.model.BasicCard;
import com.google.api.services.actions_fulfillment.v2.model.Image;
import com.google.api.services.actions_fulfillment.v2.model.SimpleResponse;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ResourceBundle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DevRelQuotesApp extends DialogflowApp {

  private static final String CONTENT_URL =
      "https://raw.githubusercontent.com/actions-on-google/dialogflow-quotes-java/master/quotes.json";
  private static final String BACKGROUND_IMAGE =
      "https://lh3.googleusercontent.com/t53m5nzjMl2B_9Qhwc81tuwyA2dBEc7WqKPlzZJ9syPUkt9VR8lu4Kq8heMjJevW3GVv9ekRWntyqXIBKEhc5i7v-SRrTan_=s688";

  private static final Logger LOGGER = LoggerFactory
      .getLogger(DevRelQuotesApp.class);

  // Used from unit tests to mock API calls.
  // Note that any instance variables should be final, for thread safety.
  private final URL mockUrl;

  protected DevRelQuotesApp() {
    super();
    mockUrl = null;
  }

  // Used for unit testing with mock URL instance
  protected DevRelQuotesApp(URL url) {
    super();
    mockUrl = url;
  }

  // Parses the API response and returns a random quote
  private static QuoteDetails parseQuotesJSON(JsonElement responseRoot) {
    // Deconstruct the JSON returned by the API
    JsonObject rootObj = responseRoot.getAsJsonObject();
    String info = rootObj.get("info").getAsString();
    JsonArray data = rootObj.getAsJsonArray("data");

    // Select a random author
    JsonObject randomAuthor = data.get((int) (Math.random() * data.size()))
        .getAsJsonObject();
    JsonArray quotes = randomAuthor.getAsJsonArray("quotes");
    String author = randomAuthor.get("author").getAsString();

    // Select a random quote
    String quote = quotes.get((int) (Math.random() * quotes.size()))
        .getAsString();

    return new QuoteDetails(info, author, quote);
  }

  @ForIntent("Default Welcome Intent")
  public ActionResponse defaultWelcomeIntent(ActionRequest request) {
    // Contains text resources for responses
    ResourceBundle rb = ResourceBundle.getBundle("resources");
    // Holds quote fetched from API
    QuoteDetails quote;
    // Used to build an AoG response
    ResponseBuilder responseBuilder = getResponseBuilder(request);

    try {
      quote = this.fetchQuote();
    } catch (Exception ex) {
      LOGGER.error(
          "Exception while fetching and parsing data from " + CONTENT_URL + ":",
          ex);

      // Handle error gracefully by sending a response
      return responseBuilder.add(rb.getString("problem")).endConversation()
          .build();
    }

    // Standard response for all platforms
    responseBuilder.add(
        new SimpleResponse()
            .setDisplayText(quote.information)
            .setTextToSpeech(
                String.format(
                    rb.getString("long_attribution"), quote.authorName,
                    quote.quoteText)));

    // Multimodal response for platforms with screen capability
    if (request.hasCapability("actions.capability.SCREEN_OUTPUT")) {
      responseBuilder.add(
          new BasicCard()
              .setTitle(String
                  .format(rb.getString("short_attribution"), quote.authorName))
              .setFormattedText(quote.quoteText)
              .setImage(
                  new Image()
                      .setUrl(BACKGROUND_IMAGE)
                      .setAccessibilityText(
                          rb.getString("accessibility_text"))));
    }

    // Tell the Assistant to end the conversation after this output
    return responseBuilder.endConversation().build();
  }

  // Fetches a quote from the API url
  private QuoteDetails fetchQuote() throws IOException {
    // If a URL instance has been provided for unit testing, use it
    URL quoteUrl = (mockUrl == null) ? new URL(CONTENT_URL) : mockUrl;

    // Make HTTP request and parse JSON response
    URLConnection quotesConnection = quoteUrl.openConnection();
    quotesConnection.connect();

    JsonParser parser = new JsonParser();
    InputStreamReader reader = new InputStreamReader(
        (InputStream) quotesConnection.getContent());

    JsonElement root = parser.parse(reader);

    return parseQuotesJSON(root);
  }

  // Represents a specific quote sourced from the API
  private static class QuoteDetails {

    final String information;
    final String authorName;
    final String quoteText;

    private QuoteDetails(String information, String authorName,
        String quoteText) {
      this.information = information;
      this.authorName = authorName;
      this.quoteText = quoteText;
    }
  }
}


text:
const DEBUG_CONSOLE = true;
const DEBUG_ALERT = false;

const DEFAULT_FRAMEWORK_DESCRIPTION = "The following related elements were found for this competency: ";

const LIST_VIEW_SCROLL_ITEM_OFFSET = 220;

// Screens
const GRAPH_SCREEN_SIMPLE = "graph-screen";
const GRAPH_SCREEN = "#" + GRAPH_SCREEN_SIMPLE;
const LIST_SCREEN_SIMPLE = "list-screen";
const LIST_SCREEN = "#" + LIST_SCREEN_SIMPLE;

// Color Themes
const FRAMEWORK_EXP_THEME_CLASS = "theme-burgendy";
const EXP_CIR_COLOR_RANGE = "burgendy";

// Various Page Element IDs
const CASSUI_MAIN_BUSY_CTR = "#cassUiMainBusyContainer";
const CASSUI_MAIN_BUSY_TXT = "#cassUiMainBusyText";
const CASSUI_MAIN_ERR_CTR = "#cassUiMainErrorContainer";
const CASSUI_MAIN_ERR_TXT = "#cassUiMainErrorText";
const CASSUI_HIGH_LVL_WARNING = ".cassUiHighLevelWarning";
const CASSUI_MAIN_CONTENTS_CTR = "#cassUiMainContentsContainer";

const CASSUI_MODAL_INPUT = ".cassUiModalInput";
const CASSUI_MODAL_BTN = ".cassUiModalButton";
const CASSUI_MODAL_BUSY_CTR = ".cassUiModalBusyCtr";
const CASSUI_MODAL_BUSY_TXT = ".cassUiModalBusyText";
const CASSUI_MODAL_ERROR_CTR = ".cassUiModalErrorCtr";
const CASSUI_MODAL_ERROR_TXT = ".cassUiModalErrorText";

const SHOW_GRAPH_VIEW_BTN = "#showGraphViewBtn";
const SHOW_LIST_VIEW_BTN = "#showListViewBtn";

const FRAMEWORK_EXP_NAME = "#frameworkExplorerName";

const FWK_CONT_SRCH_CTR = "#frameworkContentsSearchContainer";
const FWK_CONT_SRCH_INPT = "#frameworkContentsSearchInput";

const FWK_CONTENTS_LIST = "#list-screen__root";

const FWK_EXP_PAGE_TOOLS = "#page-tools";
const FWK_EXP_SHARE_TOOL = "#fwkExpShareTool";
const FWK_EXP_PUB_TOOL = "#fwkExpPublishTool";
const FWK_EXP_FULL_TOOLSET = "#fwkExpFullToolset";
const FWK_EXP_OPEN_ONLY_TOOLSET = "#fwkExpOpenFwkOnlyToolset";

//Circle Focus Detail Summary (left-hand side)/ Sidebar (right-hand side)  Items
const CIR_FCS_DTL_CTR = "#circleFocusDetailsSidebar";
const CIR_FCS_DTL_REL_LIST = "#circleFocusDetailsRelList";
const CIR_FCS_DTL_SING_NAME = "#circleFocusDetailsSingleName";
const CIR_FCS_DTL_SING_DESC = "#circleFocusDetailsSingleDesc";
const CIR_FCS_COMP_TOOLS = "#circleFocusCompTools";
const CIR_FCS_DTL_COMP_DTL_LINK = "#circleFocusCompDetailsLink";

const CIR_FCS_SUM_DESC = "#circleFocusSummaryDesc";
const CIR_FCS_SUM_LIST_CTR = "#circleFocusSummaryListContainer";

const CIR_FCS_SUM_ITEM_CLASS_ID = "gpsi";
const CIR_FCS_SUM_ITEM_TOGGLE_CLASS_ID = "gpsiToggle";
const CIR_FCS_SUM_ITEM_ROOT_COMP_CLASS = "gpsiRootComp";
const CIR_FCS_SUM_ITEM_NON_ROOT_COMP_CLASS = "gpsiNonRootComp";

const FWK_REL_FWK_LIST_CTR = "#circleFocusRelatedFwListContainer";
const FWK_REL_FWK_LIST = "#circleFocusRelatedFwList";

//Warning Containers
const NO_FRAMEWORKS_AVAILABLE_CTR = "#noFrameworksAvailableWarningContainer";
const CIRC_DEPEND_WARNING_CTR = "#circularDependencyWarningContainer";

// Modals
// Open Framework Modal
const OPEN_FWK_MODAL = "#modal-open-framework";
const OPEN_FWK_SRCH_INPT = "#openFrameworkSearchInput";

// Competency Info Modal
const COMP_DTL_MODAL = "#modal-competency-info";
const COMP_DTL_NAME = "#compDetCompName";
const COMP_DTL_DESC = "#compDetCompDesc";
const COMP_DTL_COMP_LINK = "#compDetCompLink";
const COMP_DTL_FRM_LINK = "#compDetFrameworkLink";
const COMP_DTL_SAVE_BTN = "#fwkExpCompInfoSaveBtn";

// Framework Share Modal
const FWK_SHARE_MODAL = "#modal-framework-share";
const FWK_SHARE_FWK_NAME = "#fwkShareFwkName";
const FWK_SHARE_SAVE_BTN = "#fwkShareSaveBtn";
const FWK_SHARE_NO_CONT_CTR = "#fwkShareNoContactsContainer";
const FWK_SHARE_CONT_LIST_HDR_CTR = "#fwkShareContactsListHdrContainer";
const FWK_SHARE_CONT_LIST_CTR = "#fwkShareContactsListContainer";
const FWK_SHARE_CONT_LIST = "#fwkShareContactsList";
const FWK_SHARE_CONT_VW_CB_ID_PREFIX = "fwk_share_cont_vw_";
const FWK_SHARE_CONT_ED_CB_ID_PREFIX = "fwk_share_cont_ed_";

// Framework Publish Modal
const FWK_PUBLISH_MODAL = "#modal-framework-publish";
const FWK_PUBLISH_FWK_NAME = "#fwkPublishFwkName";
const FWK_PUBLISH_DEST = "#fwkPublishDestination";

// Framework Align Setup Modal
const FWK_ALM_SETUP_MODAL = "#modal-alignment-setup";
const FWL_ALM_FW1 = "#fwAlmFw1";
const FWL_ALM_FW2 = "#fwAlmFw2";

//**************************************************************************************************
// Variables
var currentScreen;

//**************************************************************************************************
// General UI Utility Functions
//**************************************************************************************************

queryParams = function () {
    if (window.document.location.search == null)
        return {};
    var hashSplit = (window.document.location.search.split("?"));
    if (hashSplit.length > 1) {
        var o = {};
        var paramString = hashSplit[1];
        var parts = (paramString).split("&");
        for (var i = 0; i < parts.length; i++)
            o[parts[i].split("=")[0]] = decodeURIComponent(parts[i].replace(parts[i].split("=")[0] + "=", ""));
        return o;
    }
    return {};
};

queryParams = queryParams();

function debugMessage(msg) {
    if (DEBUG_CONSOLE) console.log(msg);
    if (DEBUG_ALERT) alert(msg);
}

function showScreen(newScreen) {
    $('.screen:visible').fadeOut('fast', function () {
        $('#' + newScreen).fadeIn('fast');
    });
}

function showPageMainContentsContainer() {
    if (!$(CASSUI_MAIN_CONTENTS_CTR).is(":visible")) {
        $(CASSUI_MAIN_BUSY_CTR).hide();
        $(CASSUI_MAIN_ERR_CTR).hide();
        $(CASSUI_MAIN_CONTENTS_CTR).show();
    }
}

function hidePageMainContentsContainer() {
    $(CASSUI_MAIN_CONTENTS_CTR).hide();
}

function showPageAsBusy(text) {
    $(CASSUI_MAIN_ERR_CTR).hide();
    $(CASSUI_HIGH_LVL_WARNING).hide();
    hidePageMainContentsContainer();
    $(CASSUI_MAIN_BUSY_TXT).html(text);
    $(CASSUI_MAIN_BUSY_CTR).show();
}

function showPageError(text) {
    console.error(text);
    $(CASSUI_MAIN_BUSY_CTR).hide();
    $(CASSUI_HIGH_LVL_WARNING).hide();
    hidePageMainContentsContainer();
    $(CASSUI_MAIN_ERR_TXT).html(text);
    $(CASSUI_MAIN_ERR_CTR).show();
    disableViewToggleButtons();
    showOnlyOpenFrameworkTool();
}

function disableModalInputsAndButtons() {
    $(CASSUI_MODAL_INPUT).attr("disabled", "true");
    $(CASSUI_MODAL_BTN).attr("disabled", "true");
}

function enableModalInputsAndButtons() {
    $(CASSUI_MODAL_INPUT).removeAttr("disabled");
    $(CASSUI_MODAL_BTN).removeAttr("disabled");
}

function showModalBusy(modalId,busyHtml) {
    hideModalError(modalId);
    disableModalInputsAndButtons();
    $(modalId + ' ' + CASSUI_MODAL_BUSY_TXT).html(busyHtml);
    $(modalId + ' ' + CASSUI_MODAL_BUSY_CTR).show();
}

function hideModalBusy(modalId) {
    $(modalId + ' ' + CASSUI_MODAL_BUSY_CTR).hide();
}

function showModalError(modalId,errorHtml) {
    hideModalBusy(modalId);
    enableModalInputsAndButtons();
    $(modalId + ' ' + CASSUI_MODAL_ERROR_TXT).html(errorHtml);
    $(modalId + ' ' + CASSUI_MODAL_ERROR_CTR).show();
}

function hideModalError(modalId) {
    $(modalId + ' ' + CASSUI_MODAL_ERROR_CTR).hide();
    $(CASSUI_MODAL_INPUT).removeClass("invalid");
}

function showModalInputAsInvalid(fieldId) {
    $(fieldId).addClass("invalid");
}

function generateAnchorLink(href, text, target) {
    return "" + escapeSingleQuote(text) + "";
}

function buildFrameworkHyperlink(frameworkId,frameworkName) {
    return generateAnchorLink("https://cassproject.github.io/cass-editor/?frameworkId=" + frameworkId + "&view=true", frameworkName, frameworkName);
}

function buildFrameworkCompetencyHyperlink(frameworkId,competencyId,competencyName) {
    return generateAnchorLink("https://cassproject.github.io/cass-editor/?frameworkId=" + frameworkId + "&competencyId=" +  + "&view=true", competencyName, competencyName);
}

if ( typeof String.prototype.startsWith != 'function' ) {
    String.prototype.startsWith = function( str ) {
        return str.length > 0 && this.substring( 0, str.length ) === str;
    }
};

if ( typeof String.prototype.endsWith != 'function' ) {
    String.prototype.endsWith = function( str ) {
        return str.length > 0 && this.substring( this.length - str.length, this.length ) === str;
    }
};

//**************************************************************************************************
// Framework Explorer Page UI Functions
//**************************************************************************************************

function setPageColorTheme() {
    $('body').addClass(FRAMEWORK_EXP_THEME_CLASS);
}

function showOnlyOpenFrameworkTool() {
    $(FWK_EXP_FULL_TOOLSET).hide();
    $(FWK_EXP_OPEN_ONLY_TOOLSET).show();
    $(FWK_EXP_PAGE_TOOLS).show();
}

function hideFrameworkExpTools() {
    $(FWK_EXP_PAGE_TOOLS).hide();
}

function setUpAndShowFrameworkExpTools() {
    if (currentFrameworkFull.hasOwner(loggedInPk)) {
        $(FWK_EXP_SHARE_TOOL).show();
        $(FWK_EXP_PUB_TOOL).show();
    }
    else {
        $(FWK_EXP_SHARE_TOOL).hide();
        $(FWK_EXP_PUB_TOOL).hide();
    }
    $(FWK_EXP_OPEN_ONLY_TOOLSET).hide();
    $(FWK_EXP_FULL_TOOLSET).show();
    $(FWK_EXP_PAGE_TOOLS).show();
}

function showListViewMainContentsScreen() {
    showPageMainContentsContainer();
    showScreen(LIST_SCREEN_SIMPLE);
    currentScreen = LIST_SCREEN_SIMPLE;
}

function showGraphViewMainContentsScreen() {
    showPageMainContentsContainer();
    showScreen(GRAPH_SCREEN_SIMPLE);
    $("html, body").animate({ scrollTop: 0 }, 500);
    currentScreen = GRAPH_SCREEN_SIMPLE;
}

function showCircleSidebarDetails() {
    $(CIR_FCS_DTL_CTR).removeClass("hide");
}

function hideCircleSidebarDetails() {
    $(CIR_FCS_DTL_CTR).addClass("hide");
}

function disableViewToggleButtons() {
    $(SHOW_GRAPH_VIEW_BTN).attr("disabled", "true");
    $(SHOW_LIST_VIEW_BTN).attr("disabled", "true");
}

function enableViewToggleButtons() {
    $(SHOW_GRAPH_VIEW_BTN).removeAttr("disabled");
    $(SHOW_LIST_VIEW_BTN).removeAttr("disabled");
}

function hideFrameworkContentsSearchBar() {
    $(FWK_CONT_SRCH_CTR).hide();
}

function showFrameworkContentsSearchBar() {
    $(FWK_CONT_SRCH_CTR).show();
}

function clearFrameworkContentsSearchBar() {
    $(FWK_CONT_SRCH_INPT).val("");
}

function clearOpenFrameworkSearchBar() {
    $(OPEN_FWK_SRCH_INPT).val("");
}

function clearAllSearchBars() {
    clearOpenFrameworkSearchBar();
    clearFrameworkContentsSearchBar();
}

function setPageFrameworkExplorerName(name) {
    $(FRAMEWORK_EXP_NAME).html(name);
}

function showNoFrameworksAvailableWarning() {
    $(CASSUI_MAIN_BUSY_CTR).hide();
    $(CASSUI_MAIN_ERR_CTR).hide();
    $(CASSUI_HIGH_LVL_WARNING).hide();
    setPageFrameworkExplorerName("No frameworks available");
    $(NO_FRAMEWORKS_AVAILABLE_CTR).show();
    showOnlyOpenFrameworkTool();
}

function showFrameworkHasCircularDependencyWarning() {
    $(CASSUI_MAIN_BUSY_CTR).hide();
    $(CASSUI_MAIN_ERR_CTR).hide();
    $(CASSUI_HIGH_LVL_WARNING).hide();
    $(CIRC_DEPEND_WARNING_CTR).show();
    showOnlyOpenFrameworkTool();
}

function goToDisplayRoot() {
    if (hasFinishedLoading) {
        //Node ID for a framework is its name..since that is the only node with a name ID, it should be fine...
        zoomExpCgByD3NodeId(currentFrameworkName, true);
    }
}

function getStringVal(f) {
    if (!f) return "";
    else if (typeof f === 'string' || f instanceof String) return f;
    else if (Array.isArray(f)) {
        if (f.length >= 1) return f[0];
        else return "";
    }
    else return "";
}

//**************************************************************************************************
// List Screen Utility Functions
//**************************************************************************************************

// Toggle sorting items
$('#filter-options').on('click', 'li', function () {
    $('#filter-options li').removeClass('active');
    $(this).addClass('active');
});

// Expand or collapse list items and their children
$('#list-screen__root li').on('click', 'h3, h4, .fa-li', function (evt) {
    // keep click event from bubbling up through all nested lists items
    evt.stopPropagation();
    evt.preventDefault();

    // switch between classes: expanded and collapsed
    // switch out list icons for .fa-li items

    var obj = $(this).closest('li');
    var action = 'none';

    if (obj.hasClass('collapsed')) action = "expand";
    if (obj.hasClass('expanded')) action = "collapse";

    $("#profileSearchInput").val("");

    switch (action) {
        case 'expand':
            obj.removeClass('collapsed').addClass('expanded');
            obj.children('.title').children('.fa-li').removeClass('fa-caret-right').addClass('fa-caret-down');
            obj.children('ul').slideDown('fast');
            break;

        case 'collapse':
            obj.removeClass('expanded').addClass('collapsed');
            obj.children('.title').children('.fa-li').addClass('fa-caret-right').removeClass('fa-caret-down');
            obj.children('ul').slideUp('fast');

            break;

        default:
        // not expandable, do nothing.
    }
});

function setCompetencyListViewActions() {
    $('#list-screen__root li').on('click', 'h3, h4, .fa-li', function (evt) {
        // keep click event from bubbling up through all nested lists items
        evt.stopPropagation();
        evt.preventDefault();

        // switch between classes: expanded and collapsed
        // switch out list icons for .fa-li items

        var obj = $(this).closest('li');
        var action = 'none';

        if (obj.hasClass('collapsed')) action = "expand";
        if (obj.hasClass('expanded')) action = "collapse";

        $("#profileSearchInput").val("");

        switch (action) {
            case 'expand':
                obj.removeClass('collapsed').addClass('expanded');
                obj.children('.title').children('.fa-li').removeClass('fa-caret-right').addClass('fa-caret-down');
                obj.children('ul').slideDown('fast');
                break;

            case 'collapse':
                obj.removeClass('expanded').addClass('collapsed');
                obj.children('.title').children('.fa-li').addClass('fa-caret-right').removeClass('fa-caret-down');
                obj.children('ul').slideUp('fast');

                break;

            default:
            // not expandable, do nothing.
        }
    });
}

//**************************************************************************************************
// JQuery Functions
//**************************************************************************************************

jQuery.fn.scrollTo = function (elem, speed) {
    $(this).animate({
        scrollTop: $(this).scrollTop() - $(this).offset().top + $(elem).offset().top
    }, speed == undefined ? 1000 : speed);
    return this;
};

//**************************************************************************************************
// Foundation
//**************************************************************************************************

$(document).foundation();


text:
<script src="https://apis.google.com/js/api.js"></script>

<script type="text/javascript">
function handleClientLoad() {
  // Loads the client library and the auth2 library together for efficiency.
  // Loading the auth2 library is optional here since `gapi.client.init` function will load it if not already loaded.
  // Loading it upfront(在前面) can save one network request.
  gapi.load('client:auth2', initClient);
}

function initClient() {
  // Initialize the client with API key and People API
  // Initialize OAuth with an OAuth 2.0 client ID and scopes (space delimited string) to request access.
  gapi.client.init({
    apiKey:'',
    clientId:'166811704494-d8tthgqdg7fs56ou745c8br1cp2a4gqi.apps.googleusercontent.com',//即OAuth client ID
    scope:'https://www.googleapis.com/auth/analytics.readonly'

  }).then(function() {
       // Listen for sign-in state changes.
       gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus)

       // Handle the initial sign-in state.
       updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
  })
}

function updateSigninStatus(isSignedIn) {
  // When signin status changes, this function is called.
  // If the signin status is changed to signedIn, we make an API call.
  if (isSignedIn) {
    makeApiCall();
  }
}

function makeApiCall() {

}


text:
header, main, footer {
    padding-left: 240px;
}
@media only screen and (max-width : 992px) {
    header, main, footer {
        padding-left: 0;
    }
}
i.circle {
    display: block;
    width: 42px;
    height: 42px;
    line-height: 42px;
    color: rgb(255, 255, 255);
    text-align: center;
}
.team-player, .switch {
    padding-bottom: 21px !important;
}
#team-player-template {
    display: none;
}
.collapsible-body {
    padding-left: 10px;
}
#solo-errors, #team-errors, #verify-errors, #forgot-errors {
    color: red;
}
#slide-out li a {
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
}

.promoted a {

    color: white !important;
}

.promoted {

    margin-top: 30px;
    background-color: #1976d2 !important;
}

.promoted:hover, .promoted.active {

    background-color: #ef6c00 !important;
}


text:
usage() {
    cat >&2 <<- EOF
Checks the longest blockchain from the top for structural and financial issues.

Usage:
  $(basename ${0}) [-d data_dir] [-m merkle_root_validation_block_limit] [-t transaction_validation_block_limit]

  data_dir                           - directory containing the database files, defaults to current dir
  merkle_root_validation_block_limit - on how many blocks from the top validate the merkle tree values, defaults to 0 meaning all
  transaction_validation_block_limit - on how many blocks from the top validate the transactions, defaults to 0 meaning all

IT RUNS FOR WEEKS WITH THE DEFAULT PARAMETERS. TRY TO RUN FIRST WITH:
  -m 100 -t 4

EOF
exit $1
}

DATA_DIR="."
MERKLE_TREE_VALIDATION_BLOCK_LIMIT=0
TRANSACTION_VALIDATION_BLOCK_LIMIT=0

main() {
    checkParams "$@"
    cd "$(dirname ${0})"
    java -Dlogback.configurationFile=../conf/logback.xml -jar ../target/hyperledger-server-validator-2.0.0-SNAPSHOT-shaded.jar "${DATA_DIR}" ${MERKLE_TREE_VALIDATION_BLOCK_LIMIT} ${TRANSACTION_VALIDATION_BLOCK_LIMIT}
    cd - > /dev/null
}

log() {
    echo -e "{$@}"
}

error() {
    echo -e "$@" >&2
}

checkParams() {
    while getopts ":d:m:t:h" optname
    do
        case "$optname" in
            "h")
                usage 0
            ;;
            "d")
                DATA_DIR="${OPTARG}"
            ;;
            "m")
                MERKLE_TREE_VALIDATION_BLOCK_LIMIT="${OPTARG}"
            ;;
            "t")
                TRANSACTION_VALIDATION_BLOCK_LIMIT="${OPTARG}"
            ;;
            *)
                error "Unknown argument ${OPTARG}\\n"
                usage 1
            ;;
        esac
    done
}

main "$@"


text:
package ezbake.groups.graph;

import ezbake.groups.graph.api.GroupIDProvider;

public class StubIDProvider implements GroupIDProvider {
    public long id = 0;

    public void setCurrentID(long id) throws Exception {
        this.id = id;
    }

    @Override
    public void setCurrentID() throws Exception {
        this.id = 0;
    }

    @Override
    public long currentID() throws Exception {
        return id;
    }

    @Override
    public long nextID() throws Exception {
        if (id < 0) {
            throw new Exception();
        }
        return ++id;
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<TITLE>TNativeXmlC14N Events</TITLE>
    <META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <META name="GENERATOR" content="Doc-O-Matic">
    <LINK rel="STYLESHEET" href="default.css" type="text/css">

NativeXml Help

Content | Index | Reference

TNativeXmlC14N Events

TNativeXmlC14N


text:
From column: _manufacturer_
>``` python
return as_getTextHash(getValue("manufacturer"),getValue("model"))
```

#### _model_clean_
From column: _model_
>``` python
return el_clean_model(getValue("model"))
```

#### _manufacturer_clean_
From column: _manufacturer_
>``` python
return el_clean_manufacturer(getValue("manufacturer"))
```

#### _manufacturer_uri_
From column: _manufacturer_
>``` python
return el_manufacturer_uri(getValue("manufacturer"))
```

#### _product_uri_
From column: _model_
>``` python
return el_product_uri(getValue("model"))
```

### Semantic Types
| Column | Property | Class |
|  ----- | -------- | ----- |
| _manufacturer_clean_ | `schema:name` | `schema:Organization1`|
| _manufacturer_uri_ | `uri` | `schema:Organization1`|
| _model_clean_ | `schema:mpn` | `schema:Product1`|
| _product_uri_ | `uri` | `schema:Product1`|
| _quantity_ | `schema:inventoryLevel` | `schema:Offer1`|
| _seller_ | `uri` | `schema:Organization2`|
| _uri_ | `uri` | `schema:Offer1`|

### Links
| From | Property | To |
|  --- | -------- | ---|
| `schema:Offer1` | `schema:itemOffered` | `schema:Product1`|
| `schema:Offer1` | `schema:seller` | `schema:Organization2`|
| `schema:Product1` | `schema:manufacturer` | `schema:Organization1`|


text:
@interface MagnifyingViewController()
@property(nonatomic, assign) CGSize magnifyingViewSize;
@property(nonatomic, assign) MagnifyingView* magnifyingView;
@property(nonatomic, assign) CGPoint currentMagnificationCenter;
@property(nonatomic, assign) UIView* currentMagnificationCenterView;
@end

@implementation MagnifyingViewController

#pragma mark - Initialization and deallocation

// -----------------------------------------------------------------------------
/// @brief Initializes an MagnifyingViewController object.
///
/// @note This is the designated initializer of MagnifyingViewController.
// -----------------------------------------------------------------------------
- (id) init
{
  // Call designated initializer of superclass (UIViewController)
  self = [super initWithNibName:nil bundle:nil];
  if (! self)
    return nil;
  self.magnifyingViewControllerDelegate = nil;
  self.magnifyingViewSize = CGSizeMake(magnifyingGlassDimension, magnifyingGlassDimension);
  self.magnifyingView = nil;
  self.currentMagnificationCenter = CGPointZero;
  self.currentMagnificationCenterView = nil;
  return self;
}

// -----------------------------------------------------------------------------
/// @brief Deallocates memory allocated by this MagnifyingViewController object.
// -----------------------------------------------------------------------------
- (void) dealloc
{
  self.magnifyingViewControllerDelegate = nil;
  self.magnifyingView = nil;
  self.currentMagnificationCenterView = nil;
  [super dealloc];
}

#pragma mark - UIViewController overrides

// -----------------------------------------------------------------------------
/// @brief UIViewController method.
// -----------------------------------------------------------------------------
- (void) loadView
{
  CGRect magnifyingViewFrame = CGRectZero;
  magnifyingViewFrame.size = self.magnifyingViewSize;
  self.magnifyingView = [[[MagnifyingView alloc] initWithFrame:magnifyingViewFrame] autorelease];
  self.view = self.magnifyingView;
  self.view.opaque = NO;
}

#pragma mark - Public API

// -----------------------------------------------------------------------------
/// @brief Grabs the screen content at and around @a magnificationCenter and
/// magnifies it. Also places the magnifying view at a position that is relative
/// to @a magnificationCenter, according to the rules specified in the class
/// documentation. @a view is the view with @a magnificationCenter in its
/// coordinate system.
// -----------------------------------------------------------------------------
- (void) updateMagnificationCenter:(CGPoint)magnificationCenter inView:(UIView*)magnificationCenterView
{
  // floor-ing prevents potential rounding errors and anti-aliasing. Combined
  // with the following check, floor-ing also prevents updates if the
  // magnification center only changed by a fraction.
  CGPoint flooredMagnificationCenter = CGPointMake(floorf(magnificationCenter.x), floorf(magnificationCenter.y));
  // Prevent unnecessary updates
  if (CGPointEqualToPoint(self.currentMagnificationCenter, flooredMagnificationCenter) &&
      self.currentMagnificationCenterView == magnificationCenterView)
  {
    return;
  }
  self.currentMagnificationCenter = flooredMagnificationCenter;
  self.currentMagnificationCenterView = magnificationCenterView;

  // Hide the magnifying view because we don't want to capture the magnifying
  // glass itself
  self.magnifyingView.hidden = YES;

  UIView* superviewOfMagnifyingView = self.view.superview;
  UIView* viewWithContentToMagnify = superviewOfMagnifyingView;
  CGPoint convertedMagnificationCenter = [viewWithContentToMagnify convertPoint:self.currentMagnificationCenter fromView:self.currentMagnificationCenterView];
  // floor-ing prevents potential rounding errors and anti-aliasing
  convertedMagnificationCenter = CGPointMake(floorf(convertedMagnificationCenter.x), floorf(convertedMagnificationCenter.y));
  CGSize sizeToCapture = CGSizeMake(self.magnifyingViewSize.width / magnifyingGlassMagnification,
                                    self.magnifyingViewSize.height / magnifyingGlassMagnification);
  CGRect frameToCapture = CGRectMake(convertedMagnificationCenter.x - (sizeToCapture.width / 2.0f),
                                     convertedMagnificationCenter.y - (sizeToCapture.height / 2.0f),
                                     sizeToCapture.width,
                                     sizeToCapture.height);
  UIImage* capturedImage = [UiUtilities captureFrame:frameToCapture
                                              inView:viewWithContentToMagnify];
  self.magnifyingView.magnifiedImage = capturedImage;

  // Place the magnifying glass above the intersection identified by the
  // specified GoPoint
  CGRect magnifyingViewFrame = self.magnifyingView.frame;
  magnifyingViewFrame.origin.x = convertedMagnificationCenter.x - (magnifyingViewFrame.size.width / 2.0f);
  magnifyingViewFrame.origin.y = convertedMagnificationCenter.y - (magnifyingViewFrame.size.height / 2.0f);
  magnifyingViewFrame.origin.y -= magnifyingGlassDistanceFromMagnificationCenter;
  magnifyingViewFrame = [self magnifyingViewFrameByVeeringAwayFromFrame:magnifyingViewFrame
                                                      inSuperviewBounds:superviewOfMagnifyingView.bounds];
  self.magnifyingView.frame = magnifyingViewFrame;

  // Show the magnifying view again after all updates were made
  self.magnifyingView.hidden = NO;
}

// -----------------------------------------------------------------------------
/// @brief Examines @a magnifyingViewFrame in the context of @a superviewBounds
/// to see whether any veering is required. If no veering is required, returns
/// @a magnifyingViewFrame unchanged. If veering is required, returns a copy of
/// @a magnifyingViewFrame that is modified according to the veering rules
/// specified in the class documentation.
// -----------------------------------------------------------------------------
- (CGRect) magnifyingViewFrameByVeeringAwayFromFrame:(CGRect)magnifyingViewFrame
                                   inSuperviewBounds:(CGRect)superviewBounds
{
  if (magnifyingViewFrame.origin.y >= 0.0f)
    return magnifyingViewFrame;

  CGFloat horizontalVeeringDistance = -magnifyingViewFrame.origin.y;
  magnifyingViewFrame.origin.y = 0.0f;
  enum MagnifyingGlassVeerDirection veerDirection = [self.magnifyingViewControllerDelegate magnifyingViewControllerVeerDirection:self];
  switch (veerDirection)
  {
    case MagnifyingGlassVeerDirectionLeft:
    {
      magnifyingViewFrame.origin.x -= horizontalVeeringDistance;
      if (magnifyingViewFrame.origin.x < 0.0f)
      {
        CGFloat verticalVeeringDistance = -magnifyingViewFrame.origin.x;
        magnifyingViewFrame.origin.x = 0.0f;
        magnifyingViewFrame.origin.y += verticalVeeringDistance;
      }
      break;
    }
    case MagnifyingGlassVeerDirectionRight:
    {
      magnifyingViewFrame.origin.x += horizontalVeeringDistance;
      if (CGRectGetMaxX(magnifyingViewFrame) > CGRectGetMaxX(superviewBounds))
      {
        CGFloat verticalVeeringDistance = CGRectGetMaxX(magnifyingViewFrame) - CGRectGetMaxX(superviewBounds);
        magnifyingViewFrame.origin.x -= verticalVeeringDistance;
        magnifyingViewFrame.origin.y += verticalVeeringDistance;
      }
      break;
    }
    default:
    {
      [ExceptionUtility throwNotImplementedException];
      break;
    }
  }
  return magnifyingViewFrame;
}

@end


text:
using System;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Infrastructure;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Migrations;
using EverReader.Models;

namespace EverReader.Migrations
{
    [DbContext(typeof(EverReaderContext))]
    [Migration("20151127133301_NotebookChanges")]
    partial class NotebookChanges
    {
        protected override void BuildTargetModel(ModelBuilder modelBuilder)
        {
            modelBuilder
                .Annotation("ProductVersion", "7.0.0-beta8-15964")
                .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);

            modelBuilder.Entity("EverReader.Models.ApplicationUser", b =>
                {
                    b.Property<string>("Id");

                    b.Property<int>("AccessFailedCount");

                    b.Property<string>("ConcurrencyStamp")
                        .IsConcurrencyToken();

                    b.Property<string>("Email")
                        .Annotation("MaxLength", 256);

                    b.Property<bool>("EmailConfirmed");

                    b.Property<int?>("EvernoteCredentialsId");

                    b.Property<bool>("HasAuthorisedEvernote");

                    b.Property<bool>("LockoutEnabled");

                    b.Property<DateTimeOffset?>("LockoutEnd");

                    b.Property<string>("NormalizedEmail")
                        .Annotation("MaxLength", 256);

                    b.Property<string>("NormalizedUserName")
                        .Annotation("MaxLength", 256);

                    b.Property<string>("PasswordHash");

                    b.Property<string>("PhoneNumber");

                    b.Property<bool>("PhoneNumberConfirmed");

                    b.Property<string>("SecurityStamp");

                    b.Property<bool>("TwoFactorEnabled");

                    b.Property<string>("UserName")
                        .Annotation("MaxLength", 256);

                    b.HasKey("Id");

                    b.Index("NormalizedEmail")
                        .Annotation("Relational:Name", "EmailIndex");

                    b.Index("NormalizedUserName")
                        .Annotation("Relational:Name", "UserNameIndex");

                    b.Annotation("Relational:TableName", "AspNetUsers");
                });

            modelBuilder.Entity("EverReader.Models.Bookmark", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("BookmarkTitle");

                    b.Property<DateTime>("NoteCreated");

                    b.Property<string>("NoteGuid");

                    b.Property<int>("NoteLength");

                    b.Property<string>("NoteTitle");

                    b.Property<DateTime>("NoteUpdated");

                    b.Property<decimal>("PercentageRead");

                    b.Property<int>("Type");

                    b.Property<DateTime>("Updated");

                    b.Property<string>("UserId");

                    b.HasKey("Id");
                });

            modelBuilder.Entity("EverReader.Models.EFDbEvernoteCredentials", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("AuthToken");

                    b.Property<DateTime>("Expires");

                    b.Property<string>("NotebookUrl");

                    b.Property<string>("Shard");

                    b.Property<string>("UserId");

                    b.Property<string>("WebApiUrlPrefix");

                    b.HasKey("Id");
                });

            modelBuilder.Entity("EverReader.Models.NotebookData", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("Guid");

                    b.Property<string>("Name");

                    b.Property<string>("UserId");

                    b.HasKey("Id");
                });

            modelBuilder.Entity("EverReader.Models.PrivateBetaUser", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("Email");

                    b.HasKey("Id");
                });

            modelBuilder.Entity("EverReader.Models.TagData", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("Guid");

                    b.Property<string>("Name");

                    b.Property<string>("UserId");

                    b.HasKey("Id");
                });

            modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b =>
                {
                    b.Property<string>("Id");

                    b.Property<string>("ConcurrencyStamp")
                        .IsConcurrencyToken();

                    b.Property<string>("Name")
                        .Annotation("MaxLength", 256);

                    b.Property<string>("NormalizedName")
                        .Annotation("MaxLength", 256);

                    b.HasKey("Id");

                    b.Index("NormalizedName")
                        .Annotation("Relational:Name", "RoleNameIndex");

                    b.Annotation("Relational:TableName", "AspNetRoles");
                });

            modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("ClaimType");

                    b.Property<string>("ClaimValue");

                    b.Property<string>("RoleId");

                    b.HasKey("Id");

                    b.Annotation("Relational:TableName", "AspNetRoleClaims");
                });

            modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("ClaimType");

                    b.Property<string>("ClaimValue");

                    b.Property<string>("UserId");

                    b.HasKey("Id");

                    b.Annotation("Relational:TableName", "AspNetUserClaims");
                });

            modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
                {
                    b.Property<string>("LoginProvider");

                    b.Property<string>("ProviderKey");

                    b.Property<string>("ProviderDisplayName");

                    b.Property<string>("UserId");

                    b.HasKey("LoginProvider", "ProviderKey");

                    b.Annotation("Relational:TableName", "AspNetUserLogins");
                });

            modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
                {
                    b.Property<string>("UserId");

                    b.Property<string>("RoleId");

                    b.HasKey("UserId", "RoleId");

                    b.Annotation("Relational:TableName", "AspNetUserRoles");
                });

            modelBuilder.Entity("EverReader.Models.ApplicationUser", b =>
                {
                    b.HasOne("EverReader.Models.EFDbEvernoteCredentials")
                        .WithMany()
                        .ForeignKey("EvernoteCredentialsId");
                });

            modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
                {
                    b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
                        .WithMany()
                        .ForeignKey("RoleId");
                });

            modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
                {
                    b.HasOne("EverReader.Models.ApplicationUser")
                        .WithMany()
                        .ForeignKey("UserId");
                });

            modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
                {
                    b.HasOne("EverReader.Models.ApplicationUser")
                        .WithMany()
                        .ForeignKey("UserId");
                });

            modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
                {
                    b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
                        .WithMany()
                        .ForeignKey("RoleId");

                    b.HasOne("EverReader.Models.ApplicationUser")
                        .WithMany()
                        .ForeignKey("UserId");
                });
        }
    }
}


text:
<?php

namespace Northern\Doctrine\Command;

use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Command\Command;

use Doctrine\Common\DataFixtures\Loader;
use Doctrine\Common\DataFixtures\Purger\ORMPurger;
use Doctrine\Common\DataFixtures\Executor\ORMExecutor;

class LoadFixturesCommand extends Command {

	protected function configure()
	{
		$this
			->setName('fixtures:load')
			->setDescription('Loads the fixtures.')
			->setDefinition(
				array(
					new InputArgument('directory', InputArgument::REQUIRED, 'The directory where the fixtures are located.'),
				)
			)
			->setHelp( <<<EOT
The <info>directory</info> specifies the directory where the fixtures are kept. The fixtures are defined as a set of files.
More information can be found here: <comment>https://github.com/doctrine/data-fixtures</comment>
EOT
			)
		;
	}

	protected function execute( InputInterface $input, OutputInterface $output )
	{
		if( ( $directory = $input->getArgument('directory') ) === NULL )
		{
			throw new \RuntimeException("Argument 'directory' is required in order to execute this command correctly.");
		}

		$entityManager = $this->getHelper('em')->getEntityManager();

		$loader = new Loader();
		$loader->loadFromDirectory( $directory );

		$purger = new ORMPurger( $entityManager );
		$executor = new ORMExecutor( $entityManager, $purger );

		$executor->execute( $loader->getFixtures() );
	}

}


text:
<?php

namespace Ypt\JqGridBundle\Grid;

use Doctrine\ORM\Query;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\HttpFoundation\Response;

use Ypt\JqGridBundle\FilterMapper\FilterMapperFactory;

/**
 * A class to define the grid for a JqGrid table
 *
 * @author pascal
 * @author Yuri Teixeira
 */
class Grid
{
    /**
     * @var \Symfony\Component\DependencyInjection\Container
     */
    protected $container;

    /**
     * @var \Knp\Component\Pager\Paginator
     */
    protected $paginator;

    /**
     * @var array
     */
    protected $paginatorOptions = array();

    /**
     * @var \Symfony\Component\Routing\Router
     */
    protected $router;

    /**
     * @var \Symfony\Component\HttpFoundation\Request
     */
    protected $request;

    /**
     * @var \Doctrine\Common\Persistence\ObjectManager
     */
    protected $entityManager;

    /**
     * @var \Twig_TemplateInterface
     */
    protected $templating;

    /**
     * @var \Symfony\Component\HttpFoundation\Session\Session
     */
    protected $session;

    /**
     * @var array
     */
    protected $columns;

    /**
     * @var string
     */
    protected $caption;

    /**
     * @var string
     */
    protected $url;

    /**
     * @var bool
     */
    protected $onlyData;

    /**
     * @var string
     */
    protected $name;

    /**
     * @var array
     */
    protected $gridOptions;

    /**
     * @var array
     */
    protected $navigationOptions;

    /**
     * @var string
     */
    protected $datePickerFormat;

    /**
     * @var string
     */
    protected $datePickerPhpFormat;

    /**
     * @var \Doctrine\ORM\QueryBuilder
     */
    protected $queryBuilder;

    /**
     * @var string
     */
    protected $hash;

    /**
     * @var \Ypt\JqGridBundle\Grid\Grid
     */
    protected $subGrid;

    /**
     * @var string
     */
    protected $entityName;

    /**
     * @var string
     */
    protected $eventsNamespace;

    public $tplGridName;

    /**
     * @param \Symfony\Component\DependencyInjection\Container $container
     */
    public function __construct($container)
    {
        $this->container = $container;

        $this->paginator = $this->container->get('knp_paginator');
        $this->router = $this->container->get('router');
        $this->request = $this->container->get('request');
        $this->entityManager = $this->container->get('doctrine.orm.entity_manager');
        $this->templating = $this->container->get('templating');
        $this->session = $this->request->getSession();

        $this->columns = array();
        $this->caption = '';
        $this->url = '';
        $this->onlyData = $this->request->isXmlHttpRequest() ? true : false;

        $now = new \DateTime();
        $this->name = md5($now->format('Y-m-d H:i:s:u'));

        $this->resetOptions();
    }

     // --- Common getters and setters ---
     public function getTplGridName() {
         return $this->tplGridName;
     }

     public function setTplGridName($tplGridName) {
         $this->tplGridName = $tplGridName;
     }

         /**
     * @param string $format A Jquery Datepicker Plugin date format
     *
     * @see http://jqueryui.com/demos/datepicker/
     */
    public function setDatePickerFormat($format)
    {
        $this->datePickerFormat = $format;
    }

    /**
     * @return string A Jquery Datepicker Plugin date format
     *
     * @see http://jqueryui.com/demos/datepicker/
     */
    public function getDatePickerFormat()
    {
        return $this->datePickerFormat;
    }

    /**
     * Set Paginator Options
     *
     * @param $options
     */
    public function setPaginatorOptions($options)
    {
        $this->paginatorOptions = $options;
    }

    /**
     * Get Paginator Options
     *
     * @return array
     */
    public function getPaginatorOptions()
    {
        return $this->paginatorOptions;
    }

    /**
     * @param string $format A PHP date format
     *
     * @see http://br2.php.net/manual/en/function.date.php
     */
    public function setDatePickerPhpFormat($format)
    {
        $this->datePickerPhpFormat = $format;
    }

    /**
     * @return string A PHP date format
     *
     * @see http://br2.php.net/manual/en/function.date.php
     */
    public function getDatePickerPhpFormat()
    {
        return $this->datePickerPhpFormat;
    }

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

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

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

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

    /**
     * @param string $route Url from where the grid will fetch data
     */
    public function setUrl($route)
    {
        $this->url = $route;
    }

    /**
     * @return string
     */
    public function getUrl()
    {
        if (!$this->url) {
            $this->url = $this->router->generate($this->request->get('_route'));
        }

        return $this->url;
    }

    /**
     * @return bool If true (Ajax Request), returns json. Else (Regular request), renders html
     */
    public function isOnlyData()
    {
        return $this->onlyData;
    }

    /**
     * @return string A hash that identifies the grid
     */
    public function getHash()
    {
        return $this->hash;
    }

    /**
     * @param \Ypt\JqGridBundle\Grid\Grid $grid
     */
    public function setSubGrid(\Ypt\JqGridBundle\Grid\Grid $grid)
    {
        $this->subGrid = $grid;
    }

    /**
     * @return \Ypt\JqGridBundle\Grid\Grid
     */
    public function getSubGrid()
    {
        return $this->subGrid;
    }

    /**
     * Return an array with column definitions
     *
     * @return array
     */
    public function getColumns()
    {
        return $this->columns;
    }

    /**
     * @return array
     */
    public function getGridOptions()
    {
        return $this->gridOptions;
    }

    /**
     * @return array
     */
    public function getNavigationOptions()
    {
        return $this->navigationOptions;
    }

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

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

    /**
     * @return \Doctrine\ORM\QueryBuilder
     */
    public function getQueryBuilder()
    {
        return $this->queryBuilder;
    }

    // --- Auxiliar methods ---

    /**
     * Set the grid default options
     */
    protected function resetOptions()
    {
        $this->gridOptions = array(
            'width' => '100%',
            'height' => '100%',
            'rowNum' => 20,
            'rowList' => array(20, 50, 100, 500, 1000),
            'datatype' => 'json',
            'viewrecords' => true,
        );

        $this->navigationOptions = array(
            'view' => false,
            'search' => false,
            'edit' => false,
            'add' => false,
            'del' => false,
        );
    }

    /**
     * Add a new column definition to grid
     */
    public function addColumn($name, array $columnModel)
    {
        $column = new Column($this->container, $name);
        $column->setColumnModel($columnModel);

        $this->columns[] = $column;
        return $column;
    }

    /**
     * Return an array with the column names inside the column definitions
     *
     * @return string
     */
    public function getColumnsNames()
    {
        $columnNames = array();

        /* @var Column $column */
        foreach ($this->columns as $column) {
            $columnNames[] = $column->getName();
        }

        return $columnNames;
    }

    public function getColumnsModels($toView = false)
    {
        $columnsModels = array();

        /* @var Column $column */
        foreach ($this->columns as $column) {
            $columnsModels[] =
                $toView ?
                    $column->getColumnModelToView($this->name) :
                    $column->getColumnModel();
        }

        return $columnsModels;
    }

    /**
     * Set the query builder that will be used to get data to the grid
     *
     * @param \Doctrine\ORM\QueryBuilder $queryBuilder
     */
    public function setSource(QueryBuilder $queryBuilder)
    {
        $this->queryBuilder = $queryBuilder;
        $this->createHash();
    }

    /**
     * Return the culture locale set on config
     *
     * @return string
     */
    public function getCulture()
    {
        $locale = $this->request->get('_locale') ?: \Locale::getDefault();
        return $locale;
    }

    /**
     * Create a hash to represent the grid
     */
    public function createHash()
    {
        $this->hash = 'grid_' . md5($this->request->get('_controller') . '_' . $this->getName());
        $this->session->set($this->getHash(), 'Y');
    }

    /**
     * Set the grid options based on the passed key/value array
     *
     * @param array $options
     */
    public function setGridOptions(array $options)
    {
        foreach ($options as $key => $value) {
            $this->gridOptions[$key] = $value;
        }
    }

    /**
     * @param array $options
     */
    public function setNavigationOptions(array $options)
    {
        foreach ($options as $key => $value) {
            $this->navigationOptions[$key] = $value;
        }
    }

    // --- Main methods ---

    /**
     * Collect filter parameters from url and builds related criteria on query builder
     *
     * @see http://www.trirand.com/jqgridwiki/doku.php?id=wiki:search_config)
     * @todo Move code from the switch to classes and load them with a factory
     */
    protected function generateFilters()
    {
        $filtersParam = $this->request->query->get('filters');
        $filters = json_decode($filtersParam, true);

        $rules = $filters['rules'];
        $groupOperator = $filters['groupOp']; // AND or OR

        if ($rules) {
            foreach ($rules as $rule) {

                /* @var \Ypt\JqGridBundle\Grid\Column $column */
                foreach ($this->columns as $column) {

                    if ($column->getFieldIndex() == $rule['field']) {
                        $filterMapper = FilterMapperFactory::getFilterMapper($this, $column);
                        $filterMapper->execute($rule, $groupOperator);
                    }
                }
            }
        }
    }

    /**
     * Evaluate the "fetch data" request sent by the jqgrid
     * applying column order, filters and pagination
     *
     * @return array
     *
     * @throws \Exception
     */
    public function getData()
    {
        if ($this->session->get($this->getHash()) == 'Y') {

            $page        = $this->request->query->get('page');
            $limit       = $this->request->query->get('rows');
            $sortIndex   = $this->request->query->get('sidx');
            $sortOrder   = $this->request->query->get('sord');
            $search      = $this->request->query->get('_search', 'false');
            $isSearching = $search == 'true' ? true : false;

            if ($sortIndex) {
                $this->queryBuilder->orderBy($sortIndex, $sortOrder);
            }

            if ($isSearching) {
                $this->generateFilters();
            }

            $pagination = $this->paginator->paginate(
                $this->queryBuilder->getQuery()->setHydrationMode(Query::HYDRATE_ARRAY),
                $page,
                $limit,
                $this->getPaginatorOptions()
            );

            $totalRows = $pagination->getTotalItemCount();
            $totalPages = $totalRows > 0 ? ceil($totalRows / $limit) : 0;

            $response = array(
                'page' => $page,
                'total' => $totalPages,
                'records' => $totalRows
            );

            foreach ($pagination as $key => $row) {
                $value = array();

                /* @var Column $column */
                foreach ($this->columns as $column) {

                    $fieldValue = ' ';

                    // Getting the field value through various strategies
                    if (array_key_exists($column->getFieldName(), $row)) {

                        $fieldValue = $row[$column->getFieldName()];

                    } elseif (array_key_exists(0, $row) && array_key_exists($column->getFieldName(), $row[0])) {

                        $fieldValue = $row[0][$column->getFieldName()];

                    } elseif ($column->getFieldValue()) {

                        $fieldValue = $column->getFieldValue();

                    } elseif ($column->getFieldTwig()) {

                        $fieldValue = $this->templating->render(
                            $column->getFieldTwig(),

                            array(
                                'row' => $row
                            )
                        );
                    }

                    // Applying field value conversions
                    if ($fieldValue instanceof \DateTime) {

                        /* @var \DateTime $fieldValue */
                        if ($column->getFieldFormatter() == 'date' || $column->getFieldFormatter() == 'datetime') {
                            $fieldValue = $fieldValue->format('Y-m-d H:i:s');
                        }
                    }

                    $value[] = $fieldValue;
                }

                $response['rows'][$key]['cell'] = $value;
            }

            return $response;

        } else {

            throw \Exception('Invalid query');
        }
    }

    /**
     * Returns the an array with a GridView instance for normal requests and json for AJAX requests
     *
     * @return array | \Symfony\Component\HttpFoundation\Response
     */
    public function render($tplGridName = null)
    {
        if(!empty($tplGridName)){
            $this->setTplGridName ($tplGridName);
        }
        if ($this->isOnlyData()) {

            $data = $this->getData();
            $json = json_encode($data);

            $response = new Response();
            $response->setContent($json);
            $response->headers->set('Content-Type', 'application/json');

            return $response;

        } else {
            if(!empty($this->tplGridName)){
                $tplGridName = $this->tplGridName;
                return array(
                    "$tplGridName" => new GridView($this)
                );
            }
            return array(
                'gridView' => new GridView($this)
            );
        }
    }

    /**
     * @param string $namespace
     */
    public function setEventsNamespace($namespace)
    {
        $this->eventsNamespace = $namespace;
    }

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


text:
import styled from 'styled-components'

let CommonHeader = `
  max-width: ${({theme}) => theme.width};

  color: ${({theme}) => theme.color};
  line-height: ${({theme}) => theme.lineHeight};
`
export const StyledH1 = styled.h1`${CommonHeader}`
export const StyledH2 = styled.h2`${CommonHeader}`
export const StyledH3 = styled.h3`${CommonHeader}`
export const StyledH4 = styled.h4`${CommonHeader}`
export const StyledH5 = styled.h5`${CommonHeader}`
export const StyledH6 = styled.h6`${CommonHeader}`


text:
<?php

class Crunchbutton_Blast_User_Log extends Cana_Table {
	public function __construct($id = null) {
		parent::__construct();
		$this
			->table('blast_user_log')
			->idVar('id_blast_user_log')
			->load($id);
	}
}


text:
package pit.opengles;

import android.content.Context;
import android.opengl.GLES20;

/**
 * Created by paulh on 11.10.2017.
 */

public class Shader
{
    private Context mContext;
    private int mProgram;

	public Shader(Context context)
    {
        mContext = context;
        String vertexShader = ResourceLoader.readShader(mContext, R.raw.mainvertexshader);
        String fragmentShader = ResourceLoader.readShader(mContext, R.raw.mainfragmenthader);
        mProgram = init(vertexShader, fragmentShader);
    }

    public int init(String vsSrc, String fsSrc)
    {
        int vs = Create(vsSrc, GLES20.GL_VERTEX_SHADER);
        int fs = Create(fsSrc, GLES20.GL_FRAGMENT_SHADER);

        int program = GLES20.glCreateProgram();

        if (program != 0)

            GLES20.glAttachShader(program, vs);
            GLES20.glAttachShader(program, fs);

            GLES20.glBindAttribLocation(program, 0, "position");
            GLES20.glBindAttribLocation(program, 1, "texCoords");

            GLES20.glLinkProgram(program);

            final int[] linkStatus = new int[1];
            GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, linkStatus, 0);

            if (linkStatus[0] == 0)
            {
                GLES20.glDeleteProgram(program);
                program = 0;
            }
        if (program == 0)
        {
            throw new RuntimeException("Error creating program");
        }
        return program;
    }

    private int Create(String shaderSource, int shaderType)
    {
        int id = GLES20.glCreateShader(shaderType);

        if(id != 0) {
            GLES20.glShaderSource(id, shaderSource);

            GLES20.glCompileShader(id);

            final int[] compileStatus = new int[1];
            GLES20.glGetShaderiv(id, GLES20.GL_COMPILE_STATUS, compileStatus, 0);

            if (compileStatus[0] == 0)
            {
                GLES20.glDeleteShader(id);
                id = 0;
            }
        }
        if (id == 0) {
            throw new RuntimeException("Shader: Creation failed");
        }
        return id;
    }

    public int getMainProgram(){ return mProgram;}
}


text:
        <form method="POST" class="well" action="/login" id="loginForm" name="loginForm">

&{'hub.Login'}

            #{if flash.error}

                x
                ${flash.error}

            #{/if}
            #{if flash.success}

                x
                ${flash.success}

            #{/if}
            #{if views.Helpers.hasErrors(loginForm)}

                x

                #{list views.Helpers.listGlobalErrors(loginForm), as: 'e'}

${e}

                #{/list}

            #{/if}

            #{form.textField name:"userName", placeholder: messages.get("hub.Username"), form: loginForm /}
            #{form.passwordField name:"password", placeholder: messages.get("hub.Password"), form: loginForm /}

                    <input type="checkbox" name="remember" id="remember" value="true" ${flash.remember ? 'checked=\"true\"' : ''} />
                    &{'hub.RememberMe'}

                #{btnButton label: messages.get("hub.Login"), extraClass:"btn-primary btn-block", type:"submit", id:"signin" /}

                #{href label: messages.get('hub.IForgotMyPassword'), href:"/registration/lostPassword", rel:"nofollow" /}

        </form>


text:
using Avalonia.Controls.Templates;
using Avalonia.Layout;
using Avalonia.Metadata;

namespace Avalonia.Controls
{
    /// <summary>
    /// Defines a control that displays <see cref="Content"/> according to a
    /// <see cref="Avalonia.Controls.Templates.FuncDataTemplate"/>.
    /// </summary>
    [NotClientImplementable]
    public interface IContentControl : IControl
    {
        /// <summary>
        /// Gets or sets the content to display.
        /// </summary>
        object? Content { get; set; }

        /// <summary>
        /// Gets or sets the data template used to display the content of the control.
        /// </summary>
        IDataTemplate? ContentTemplate { get; set; }

        /// <summary>
        /// Gets or sets the horizontal alignment of the content within the control.
        /// </summary>
        HorizontalAlignment HorizontalContentAlignment { get; set; }

        /// <summary>
        /// Gets or sets the vertical alignment of the content within the control.
        /// </summary>
        VerticalAlignment VerticalContentAlignment { get; set; }
    }
}


text:
autocommit off;
drop table if exists tz_test;

create table tz_test(a int, ts timestamp, tsltz timestamp with local time zone, tstz timestamp with time zone);

set timezone 'UTC';
insert into tz_test values(1, timestamptz'2019-01-02 12:00:01', timestamptz'2019-01-02 12:00:01', timestamptz'2019-01-02 12:00:01');
insert into tz_test values(2, timestamptz'2019-01-02 12:00:01 -10:00', timestamptz'2019-01-02 12:00:01 -10:00', timestamptz'2019-01-02 12:00:01 -10:00');
insert into tz_test values(3, timestamptz'2019-01-02 12:00:01 +8:00', timestamptz'2019-01-02 12:00:01 +8:00', timestamptz'2019-01-02 12:00:01 +8:00');
insert into tz_test values(4, timestamptz'2019-01-02 12:00:01 Asia/Tokyo', timestamptz'2019-01-02 12:00:01 Asia/Tokyo', timestamptz'2019-01-02 12:00:01 Asia/Tokyo');
commit;

set system parameters 'alter_table_change_type_strict=yes';

--test: cast ts column to date/time types
alter table tz_test change ts ts date;
show columns in tz_test;
select * from tz_test order by 1;
rollback;
alter table tz_test change ts ts time;
show columns in tz_test;
select * from tz_test order by 1;
rollback;
alter table tz_test change ts ts timestamp;
show columns in tz_test;
select * from tz_test order by 1;
rollback;
alter table tz_test change ts ts datetime;
show columns in tz_test;
select * from tz_test order by 1;
rollback;

--test: cast tsltz column to date/time types
alter table tz_test change tsltz tsltz date;
show columns in tz_test;
select * from tz_test order by 1;
rollback;
alter table tz_test change tsltz tsltz time;
show columns in tz_test;
select * from tz_test order by 1;
rollback;
alter table tz_test change tsltz tsltz timestamp;
show columns in tz_test;
select * from tz_test order by 1;
rollback;
alter table tz_test change tsltz tsltz datetime;
show columns in tz_test;
select * from tz_test order by 1;
rollback;

--test: cast tstz column to date/time types
alter table tz_test change tstz tstz date;
show columns in tz_test;
select * from tz_test order by 1;
rollback;
alter table tz_test change tstz tstz time;
show columns in tz_test;
select * from tz_test order by 1;
rollback;
alter table tz_test change tstz tstz timestamp;
show columns in tz_test;
select * from tz_test order by 1;
rollback;
alter table tz_test change tstz tstz datetime;
show columns in tz_test;
select * from tz_test order by 1;
rollback;

drop table tz_test;
commit;

set timezone 'Asia/Seoul';
set system parameters 'alter_table_change_type_strict=no';

autocommit on;


text:
@interface GunControls : NSObject

@property (nonatomic, assign) NSUInteger trigger;

- (instancetype)initWithTrigger:(NSUInteger)trigger;

@end


text:
module.exports = function(grunt){
    //project setting
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),

        //configuration for Alarm the Ghost theme
        alarm: {
          //make sure i18n/your_locale.json exists
          locale: 'zh_CN',

          //set the nav menu as desired
          nav: [{
            url: '/',
            title: 'Home'
          },{
            url: '/works/',
            title: 'Works'
          },{
            url: '/about/',
            title: 'About Me'
          }],

          //there is a automatically generated nav item when user viewing
          //single article or static page, config it's title
          navContentTitle: 'Content',

          disqus: {
            enable: false,
            shortname: 'your_disqus_id_here'  //http://xxx.disqus.com should be vaild
          },

          googleAnalytics: {
            enable: false,
            id: 'your_GA_id_here'
          },

          syntaxHighlight: {
            enable: true
          },

          tableOfContent: {
            enable: true
          }
        },

        //implement the i18n feature using text replace
        replace: {
          dist: {
            src: ['dist/**/*.hbs', 'dist/assets/css/style.css'],
            overwrite: true,
            replacements: []
          }
        },

        concat: {
          dist: {
            dest: 'dist/assets/css/main.css'
          }
        },

        copy: {
          dist: {
            expand: true,
            cwd: 'src/',
            src: '**',
            dest: 'dist/'
          }
        },

        cssmin: {
          dist: {
            files: {
              'dist/assets/css/main.min.css': ['dist/assets/css/main.css']
            }
          }
        },

        clean:{
          dist:{
            src: 'dist'
          }
        },

        watch: {
          style: {
            files: ['src/assets/**/*', 'src/*.hbs', 'src/partials/*.hbs'],
            tasks: ['dist'],
            options: {
              livereload: true
            }
          }
        }
    });

    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-contrib-cssmin');
    grunt.loadNpmTasks('grunt-text-replace');

    grunt.registerTask('dist', 'distribute the theme', function(){
      var options = grunt.config.get('alarm');
      var locale = options.locale || 'en_US';

      var i18n = 'i18n/' + locale + '.json';
      var localeObj = grunt.file.readJSON(i18n);
      if (!localeObj) {
        grunt.log.error("Can't find locale json file: " + i18n);
        return false;
      }

      //remove previous dist
      grunt.task.run('clean');
      //copy src to dist then run tasks in it
      grunt.task.run('copy:dist');

      //i18n it is
      var replacements = localeObj.filter(function(v, i){
        if (v.from && v.to) {
          return true;
        }
      });
      grunt.log.subhead('building with locale ' + locale);

      //config disqus
      var disqus = [];
      if (options.disqus.enable) {
        grunt.log.oklns("Disqus enabled");
        disqus = [
        {
          from: "ALARM_DISQUS_ENABLE",
          to: "{{> comment}}"
        },
        {
          from: "ALARM_DISQUS_SHORTNAME",
          to: options.disqus.shortname
        }];
      }
      else{
        disqus = [{from: "ALARM_DISQUS_ENABLE", to: ""}];
      }
      replacements = replacements.concat(disqus);

      //config google analytics
      var ga = [];
      if (options.googleAnalytics.enable) {
        ga = [
        {
          from: "ALARM_GA_ENABLE",
          to: "{{> ga}}"
        },
        {
          from: "ALARM_GA_ID",
          to: options.googleAnalytics.id
        }];
      grunt.log.oklns("Google analytics enabled");
      }
      else{
        ga = [{from: "ALARM_GA_ENABLE", to: ""}];
      }
      replacements = replacements.concat(ga);

      //config syntax highlight
      var sh = [];
      if (options.syntaxHighlight.enable) {
        grunt.log.oklns("Syntax highlighting enabled");
        sh = [{from: "ALARM_SH_ENABLE", to: "{{> syntaxHighlight}}"}];
      }
      else{
        sh = [{from: "ALARM_SH_ENABLE", to: ""}];
      }
      replacements = replacements.concat(sh);

      //config table of content
      var toc = [];
      if (options.tableOfContent.enable) {
        grunt.log.oklns("Table of content enabled");
        toc = [{from: "ALARM_TOC_ENABLE", to: "{{> toc}}"}];
      }
      else{
        toc = [{from: "ALARM_TOC_ENABLE", to: ""}];
      }
      replacements = replacements.concat(toc);

      //nav menu
      var navItemWidth = (100 / options.nav.length).toFixed(4) + '%';
      replacements = replacements.concat([
        {from: "ALARM_NAV_WIDTH", to: navItemWidth},
        {from: "ALARM_NAV_CONTENT", to: options.navContentTitle}
      ]);

      var navHTML = '
';
      options.nav.forEach(function(v){
        navHTML += '
' + v.title + '';
      });
      navHTML += '
';
      replacements = replacements.concat([{from: "ALARM_NAV_HTML", to: navHTML}]);

      grunt.config.set('replace.dist.replacements', replacements);
      grunt.task.run('replace');

      //concat css
      var cssSrc = ['dist/assets/css/*.css'];
      if (!options.syntaxHighlight.enable) {
        cssSrc.concat(['!dist/assets/css/monokai_sublime.css']);
      }
      grunt.config.set('concat.dist.src', cssSrc);
      grunt.task.run('concat');
      grunt.task.run('cssmin');

      grunt.log.oklns("Now enjoy your new Ghost theme --- Alarm");
      grunt.log.writeln("copy dist directory to Ghost/content/themes and rename it to alarm, then restart Ghost to make it take effect.");
    });
};


text:
package com.github.toastshaman.dropwizard.auth.jwt;

import com.codahale.metrics.MetricRegistry;
import com.google.common.base.Throwables;
import com.google.common.cache.CacheBuilderSpec;
import io.dropwizard.auth.Authenticator;
import io.dropwizard.auth.PrincipalImpl;
import org.jose4j.jws.AlgorithmIdentifiers;
import org.jose4j.jws.JsonWebSignature;
import org.jose4j.jwt.JwtClaims;
import org.jose4j.jwt.consumer.JwtConsumer;
import org.jose4j.jwt.consumer.JwtConsumerBuilder;
import org.jose4j.jwt.consumer.JwtContext;
import org.jose4j.keys.HmacKey;
import org.junit.Before;
import org.junit.Test;

import java.security.Principal;
import java.util.Optional;

import static com.google.common.base.Charsets.UTF_8;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;

public class JwtCachingAuthenticatorTest {

    @SuppressWarnings("unchecked")
    private final Authenticator<JwtContext, Principal> underlying = mock(Authenticator.class);

    private final CachingJwtAuthenticator<Principal> cached = new CachingJwtAuthenticator<>(new MetricRegistry(),
        underlying, CacheBuilderSpec.parse("maximumSize=1"));

    private final String SECRET = "Po70rBeXjKDhckY9yWmhNVte/UajN8xbA==lkDvaBTeWRja0SFMzcz113d/bi3Tn";

    private final JwtConsumer consumer = new JwtConsumerBuilder()
        .setAllowedClockSkewInSeconds(30) // allow some leeway in validating time based claims to account for clock skew
        .setRequireSubject() // the JWT must have a subject claim
        .setExpectedIssuer("Issuer") // whom the JWT needs to have been issued by
        .setExpectedAudience("Audience") // whom the JWT needs to have been issued by
        .setVerificationKey(new HmacKey(SECRET.getBytes(UTF_8))) // verify the signature with the public key
        .setRelaxVerificationKeyValidation() // relaxes key length requirement
        .build();// create the JwtConsumer instance

    private JwtContext tokenOne() {
        final JwtClaims claims = new JwtClaims();
        claims.setSubject("good-guy");
        claims.setIssuer("Issuer");
        claims.setAudience("Audience");

        final JsonWebSignature jws = new JsonWebSignature();
        jws.setPayload(claims.toJson());
        jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA512);
        jws.setKey(new HmacKey(SECRET.getBytes(UTF_8)));
        jws.setDoKeyValidation(false);

        try {
            return consumer.process(jws.getCompactSerialization());
        }
        catch (Exception e) { throw Throwables.propagate(e); }
    }

    private JwtContext tokenTwo() {
        final JwtClaims claims = new JwtClaims();
        claims.setSubject("good-guy-two");
        claims.setIssuer("Issuer");
        claims.setAudience("Audience");

        final JsonWebSignature jws = new JsonWebSignature();
        jws.setPayload(claims.toJson());
        jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA512);
        jws.setKey(new HmacKey(SECRET.getBytes(UTF_8)));
        jws.setDoKeyValidation(false);

        try {
            return consumer.process(jws.getCompactSerialization());
        }
        catch (Exception e) { throw Throwables.propagate(e); }
    }

    @Before
    public void setUp() throws Exception {
        when(underlying.authenticate(any(JwtContext.class)))
            .thenReturn(Optional.<Principal>of(new PrincipalImpl("principal")));
    }

    @Test
    public void cachesTheFirstReturnedPrincipal() throws Exception {
        assertThat(cached.authenticate(tokenOne())).isEqualTo(Optional.<Principal>of(new PrincipalImpl("principal")));
        assertThat(cached.authenticate(tokenOne())).isEqualTo(Optional.<Principal>of(new PrincipalImpl("principal")));

        verify(underlying, times(1)).authenticate(any(JwtContext.class));
    }

    @Test
    public void doesNotCacheDifferingTokens() throws Exception {
        assertThat(cached.authenticate(tokenOne())).isEqualTo(Optional.<Principal>of(new PrincipalImpl("principal")));
        assertThat(cached.authenticate(tokenTwo())).isEqualTo(Optional.<Principal>of(new PrincipalImpl("principal")));

        verify(underlying, times(2)).authenticate(any(JwtContext.class));
    }
}