text:
DocumentCloud is a tool for organizing and working with large documents and document collections, a document viewer that makes it easier for reporters to share source material with readers and a publicly accessible repository of primary source documents that were used in reporters' investigations.

If you're a reporter who'd like to analyze, annotate, and publish documents, [contact us][] to find out more about getting an account. Otherwise, take a spin through our public document collection and try out some of our great analytic tools.

## Search public documents and browse the notes.

Try a search for [gulf oil spill][] to find all public documents with "gulf," "oil" and "spill" in the text or title. Your results will include a number of documents relating to the British Petroleum oil spill in the Gulf of Mexico.  For each document you can see the name of the user who uploaded the document and the newsroom they work in.

If a reporter has annotated a document, you'll also see a yellow "note" indicator on the document's thumbnail. Below the thumbnail, there's a small link you can use to show the annotations that have been made on that document.

Double click on any document to read the whole document in our viewer, or read on for insights into more complex searches.

## Try out our analytic tools.

DocumentCloud gives you access to a great set of analytic tools. When a reporter uploads any document, we run it through OCR, which extracts letters and words from the documents' image. But that's not all.

Search for [source: "House Committee on the Judiciary"][].

Your results will include a handful of documents related to a DOJ report on Bush administration interrogation policies. Select all 8 of the interrogation documents and select "View Timeline" from the "Analyze" menu.

Every date reference in this collection of documents is plotted on a timeline. Hover over any dot to see the exact date in context. Click on the dot to open a document viewer to the location of that date in the text.

Close the timeline and select the "Entities" tab at the top left of the screen to view you a series of expandable lists of **people**, **organizations**, **places**, and **terms** mentioned in the documents. You'll see "John Yoo" at the top of the list, with the counter `(8)` next to his name, because he's named in all eight of the documents. Select his name to refine your search, and then select the "show pages" to dispaly a thumbnail of each page where John Yoo is mentioned. Selecting a thumbnail or highlighted link will jump directly to his name on that particular page.

## Advanced Searches

Enclose terms in quotes to search for a specific, multi-word phrase.

Use "NOT" or "-" to exclude a term from your search. For example these searches: [geithner -madoff][] and [geithner NOT madoff][] will return documents that mention "Geithner" and do not also mention "Madoff."

By default DocumentCloud will search both the title and full text of every document for for all of the words in your search term. You can, however, ask DocumentCloud to search the contents of specific fields.

## Searching by Metadata Field

Term                        | Description
----------------------------|---------------------
title                       | Will search only the titles of documents. For example: [title: deepwater][].
source                      | Reporters have the opportunity to identify the source of each document they upload.  For example: [source: supreme][] will identify documents attributed to "U.S. Supreme Court" as well as "New York State Supreme Court."
description                 | Search for a word or phrase within all document descriptions. For example: [description: manifesto][].
account                     | Specify an account id to see documents published by a specific user. Notice that clicking on any user's name in your search results will automatically filter your results to include only that user's documents.  For example: [account: 143-james-wilkerson][].
group                       | Search for all documents made public by a single newsroom. Notice that clicking on any organization name in your search results will automatically filter your results to include only that group's documents. For example: [group: chicago-tribune][].
projectid                   | Reporters can organize documents into as many projects as appropriate. To restrict a search to documents in one project, you need to know that project's canonical identifier or project id. DocumentCloud doesn't publish individual project id's, however.  For example: [projectid: 6-the-financial-crisis][]
filter                      | Filter documents by interesting criteria (one of "published", "unpublished", "annotated", or "popular"). For example, to view all published documents: [filter: published][]

## Searching with Entities

For each document we store a list of entities identified by [OpenCalais][]. These are the same entities that appear in the "Entities" tab. After searching for an entity, you can click on "show pages" to display links to the specific pages in each document that mention the person, place or thing you're searching for.

Term                        | Description
----------------------------|-------------------------
person                      | The name of a human being. If you're looking for documents that reference a person with the last name of "Lee", but keep getting swamped with unrelated words, try narrowing your search to [person: Lee][].
organization                | Organizations include businesses, government agencies, and other types of institutions. For example: [organization: "Department of Defense"][].
place                       | Addresses, names of buildings and landmarks, regions, or geographical landmarks. For example: [place: "World Trade Center"][] or [place: "Gulf of Mexico"][].
term                        | Searches for terms might include [term: "nuclear energy"][] or [term: "gross domestic product"][]. The results will be comparable to searching for the terms directly.
email                       | Complete email addresses. Documents that mention the email address of the GAO FraudNet can be found with this search: [email: fraudnet@gao.gov][].
phone                       | Telephone or Fax numbers. For example: [phone: "(251) 441-6216"][].
city                        | For example: [city: "New Orleans"][].
state                       | (Includes provinces, in countries that have provinces instead of states.) For example: [state: Arizona][].
country                     | For example: [country: Iran][].

Questions? Don't hesitate to [contact us][]. And as you go, feel free to [request features and report bugs][].

  Contact Us   |
  Terms of Service   |
  Privacy Policy

[gulf oil spill]: /public/search/gulf%20oil%20spill
[source: "House Committee on the Judiciary"]: /public/search/source%3A%20%22House%20Committee%20on%20the%20Judiciary%22
[John Yoo detainee]: /public/search/John%20Yoo%20detainee
[geithner -madoff]: /public/search/geithner%20-madoff
[geithner NOT madoff]: /public/search/geithner%20NOT%20madoff
[account: 143-james-wilkerson]: /public/search/account%3A%20143-james-wilkerson
[group: chicago-tribune]: /public/search/group%3A%20chicago-tribune
[title: deepwater]: /public/search/title%3A%20deepwater
[source: supreme]: /public/search/source%3A%20supreme
[description: manifesto]: /public/search/description%3A%20manifesto
[projectid: 6-the-financial-crisis]: /public/search/projectid%3A%206-the-financial-crisis
[access: private]: /public/search/access%3A%20private
[filter: published]: /public/search/filter%3A%20published
[person: Lee]:/public/ #search/person%3A%20Lee
[organization: "Department of Defense"]: /public/search/organization%3A%20%22Department%20of%20Defense%22
[term: "nuclear energy"]: /public/search/term%3A%20%22nuclear%20energy%22
[term: "gross domestic product"]: /public/search/term%3A%20%22gross%20domestic%20product%22
[email: fraudnet@gao.gov]: /public/search/%20email%3A%20fraudnet%40gao.gov
[phone: "(251) 441-6216"]: /public/search/%20phone%3A%20%22(251)%20441-6216%22
[place: "World Trade Center"]: /public/search/place%3A%20%22World%20Trade%20Center%22
[place: "Gulf of Mexico"]: /public/search/place%3A%20%22Gulf%20of%20Mexico%22
[city: "New Orleans"]: /public/search/city%3A%20%22New%20Orleans%22
[state: Arizona]: /public/search/state%3A%20Arizona
[country: Iran]: /public/search/country%3A%20Iran
[OpenCalais]: http://www.opencalais.com/
[contact us]: /contact
[request features and report bugs]: http://documentcloud.uservoice.com


text:
<ompts:test>
<ompts:testdescription> Test to see if implied private works properly</ompts:testdescription>
<ompts:ompversion>3.0</ompts:ompversion>
<ompts:directive>omp task</ompts:directive>
<ompts:dependences>omp single</ompts:dependences>
<ompts:testcode>
#include <stdio.h>
#include <math.h>
#include "omp_testsuite.h"

/* Utility function do spend some time in a loop */
int <ompts:testcode:functionname>omp_task_imp_firstprivate</ompts:testcode:functionname> (FILE * logFile)
{
    int i=5;
    int k = 0;
    int result = 0;
    int task_result = 1;
   #pragma omp parallel firstprivate(i)
    {
      #pragma omp single
      {

          for (k = 0; k < NUM_TASKS; k++)
	        {
                    #pragma omp task shared(result , task_result<ompts:crosscheck>, i</ompts:crosscheck>)
                        {
                          int j;
			  //check if i is private
                          if(i != 5)
                            task_result = 0;

                          for(j = 0; j < NUM_TASKS; j++)
                              i++;
                          //this should be firstprivate implicitly
                        }
		}

	  #pragma omp taskwait
	  result = (task_result && i==5);
       }

    }

    return result;
}
</ompts:testcode>
</ompts:test>

redpajama_set_name: RedPajamaGithub


text:
namespace views {
extern const char kViewsNativeHostPropForAccessibility[];
// Note: do not put NativeViewAccessibilityWin in the namespace "views";
// Visual Studio 2005 does not allow an ATL::CComObject symbol in a namespace.
}

////////////////////////////////////////////////////////////////////////////////
//
// NativeViewAccessibilityWin
//
// Class implementing the MSAA IAccessible COM interface for a generic View,
// providing accessibility to be used by screen readers and other assistive
// technology (AT).
//
////////////////////////////////////////////////////////////////////////////////
class ATL_NO_VTABLE NativeViewAccessibilityWin
  : public CComObjectRootEx<CComMultiThreadModel>,
    public IDispatchImpl<IAccessible, &IID_IAccessible, &LIBID_Accessibility> {
 public:
  BEGIN_COM_MAP(NativeViewAccessibilityWin)
    COM_INTERFACE_ENTRY2(IDispatch, IAccessible)
    COM_INTERFACE_ENTRY(IAccessible)
  END_COM_MAP()

  // Create method for view accessibility.
  static scoped_refptr<NativeViewAccessibilityWin> Create(views::View* view);

  // Returns the IAccessible interface for a view.
  static IAccessible* GetAccessibleForView(views::View* view);

  virtual ~NativeViewAccessibilityWin();

  void set_view(views::View* view) { view_ = view; }

  // Supported IAccessible methods.

  // Retrieves the child element or child object at a given point on the screen.
  STDMETHODIMP accHitTest(LONG x_left, LONG y_top, VARIANT* child);

  // Performs the object's default action.
  STDMETHODIMP accDoDefaultAction(VARIANT var_id);

  // Retrieves the specified object's current screen location.
  STDMETHODIMP accLocation(LONG* x_left,
                           LONG* y_top,
                           LONG* width,
                           LONG* height,
                           VARIANT var_id);

  // Traverses to another UI element and retrieves the object.
  STDMETHODIMP accNavigate(LONG nav_dir, VARIANT start, VARIANT* end);

  // Retrieves an IDispatch interface pointer for the specified child.
  STDMETHODIMP get_accChild(VARIANT var_child, IDispatch** disp_child);

  // Retrieves the number of accessible children.
  STDMETHODIMP get_accChildCount(LONG* child_count);

  // Retrieves a string that describes the object's default action.
  STDMETHODIMP get_accDefaultAction(VARIANT var_id, BSTR* default_action);

  // Retrieves the tooltip description.
  STDMETHODIMP get_accDescription(VARIANT var_id, BSTR* desc);

  // Retrieves the object that has the keyboard focus.
  STDMETHODIMP get_accFocus(VARIANT* focus_child);

  // Retrieves the specified object's shortcut.
  STDMETHODIMP get_accKeyboardShortcut(VARIANT var_id, BSTR* access_key);

  // Retrieves the name of the specified object.
  STDMETHODIMP get_accName(VARIANT var_id, BSTR* name);

  // Retrieves the IDispatch interface of the object's parent.
  STDMETHODIMP get_accParent(IDispatch** disp_parent);

  // Retrieves information describing the role of the specified object.
  STDMETHODIMP get_accRole(VARIANT var_id, VARIANT* role);

  // Retrieves the current state of the specified object.
  STDMETHODIMP get_accState(VARIANT var_id, VARIANT* state);

  // Retrieves the current value associated with the specified object.
  STDMETHODIMP get_accValue(VARIANT var_id, BSTR* value);

  // Non-supported IAccessible methods.

  // Selections not applicable to views.
  STDMETHODIMP get_accSelection(VARIANT* selected);
  STDMETHODIMP accSelect(LONG flags_sel, VARIANT var_id);

  // Help functions not supported.
  STDMETHODIMP get_accHelp(VARIANT var_id, BSTR* help);
  STDMETHODIMP get_accHelpTopic(BSTR* help_file,
                                VARIANT var_id,
                                LONG* topic_id);

  // Deprecated functions, not implemented here.
  STDMETHODIMP put_accName(VARIANT var_id, BSTR put_name);
  STDMETHODIMP put_accValue(VARIANT var_id, BSTR put_val);

  // Returns a conversion from the event (as defined in accessibility_types.h)
  // to an MSAA event.
  static int32 MSAAEvent(ui::AccessibilityTypes::Event event);

  // Returns a conversion from the Role (as defined in accessibility_types.h)
  // to an MSAA role.
  static int32 MSAARole(ui::AccessibilityTypes::Role role);

  // Returns a conversion from the State (as defined in accessibility_types.h)
  // to MSAA states set.
  static int32 MSAAState(ui::AccessibilityTypes::State state);

 private:
  NativeViewAccessibilityWin();

  // Determines navigation direction for accNavigate, based on left, up and
  // previous being mapped all to previous and right, down, next being mapped
  // to next. Returns true if navigation direction is next, false otherwise.
  bool IsNavDirNext(int nav_dir) const;

  // Determines if the navigation target is within the allowed bounds. Returns
  // true if it is, false otherwise.
  bool IsValidNav(int nav_dir,
                  int start_id,
                  int lower_bound,
                  int upper_bound) const;

  // Determines if the child id variant is valid.
  bool IsValidId(const VARIANT& child) const;

  // Helper function which sets applicable states of view.
  void SetState(VARIANT* msaa_state, views::View* view);

  // Returns the IAccessible interface for a native view if applicable.
  // Returns S_OK on success.
  static HRESULT GetNativeIAccessibleInterface(
      views::NativeViewHost* native_host, IAccessible** accessible);

  static HRESULT GetNativeIAccessibleInterface(
      HWND native_view_window, IAccessible** accessible);

  // Give CComObject access to the class constructor.
  template <class Base> friend class CComObject;

  // Member View needed for view-specific calls.
  views::View* view_;

  DISALLOW_COPY_AND_ASSIGN(NativeViewAccessibilityWin);
};

#endif  // VIEWS_ACCESSIBILITY_NATIVE_VIEW_ACCESSIBILITY_WIN_H_


text:
def outer
  inner rescue nil
end

def inner
  wait_for_it___
end

def wait_for_it___
  boom
end

def boom
  raise "boom"
end

def another

end

outer

another


text:
MAKEFILE_DIR := $(shell dirname $(realpath $(lastword $(MAKEFILE_LIST))))

all: run

deps:
	mix deps.get
	mix deps.compile

compile:
	mix compile

run:
	iex -S mix run

test:
	mix test

clean:
	rm -rf $(MAKEFILE_DIR)/mix.lock
	rm -rf $(MAKEFILE_DIR)/_build/*
	rm -rf $(MAKEFILE_DIR)/deps/*

docs:
	rm -rf $(MAKEFILE_DIR)/doc/*
	mix docs
	open doc/index.html

fetch:
	mix gs.fetch

fetch-url:
	mix gs.fetch -u https://spreadsheets.google.com/feeds/worksheets/1k-N20RmT62RyocEu4-MIJm11DZqlZrzV89fGIddDzIs/public/basic -d priv/data

.PHONY: all deps compile run test docs clean fetch


text:
title: Home
---

{{< hero-block-center  >}}
Code for Germany ist ein Netzwerk von Open-Government-Expert\*innen, die sich als ehrenamtlich aktive Stadtentwickler\*innen für einen nachhaltigen digitalen Wandel in Politik und Verwaltung einsetzen.
{{< /hero-block-center  >}}

{{< button-center href="/mitmachen" >}}
Werde Stadtentwickler*in!
{{< /button-center >}}

{{< section >}}
{{< headline-icon icon="icon-info.svg" >}}

{{< headline-brackets-h1 color="blue"  >}}
Wer wir sind und was wir machen
{{< /headline-brackets-h1  >}}

{{< home/block-123 >}}

{{< button-center href="/ueber" >}}
Über uns
{{< /button-center >}}
{{< /section >}}

{{< section >}}
{{< headline-icon icon="icon-bracket.svg" >}}

{{< headline-brackets-h2 color="blue"  >}}
Code for Germany auf einen Blick
{{< /headline-brackets-h2  >}}

{{< home/block-auf-einen-blick >}}

{{< button-center href="/mitmachen" >}}
Mach mit!
{{< /button-center >}}
{{< /section >}}

{{< section >}}
{{< headline-icon icon="icon-documents.svg" >}}

{{< headline-brackets-h2 color="blue"  >}}
Projekte und Anwendungen finden
{{< /headline-brackets-h2  >}}

{{< paragraph-center class="text-center mb-5" >}}
Du möchtest einen Eindruck von unseren Projekten bekommen? Wir arbeiten gegenwärtig zu den Themenfeldern Mobilität, Gesellschaft, Umwelt und Politik.
{{< /paragraph-center >}}

{{< button-center href="/projekte" >}}
Projekte
{{< /button-center >}}
{{< /section >}}

{{< section >}}
{{< headline-icon icon="icon-touch.svg" >}}

{{< headline-brackets-h2 color="blue"  >}}
Unsere gesellschaftlichen Ziele

{{< /headline-brackets-h2  >}}

{{< home/block-goals >}}

{{< button-center href="/ziele" >}}
Ziele
{{< /button-center >}}
{{< /section >}}

{{< section >}}
{{< headline-icon icon="icon-power.svg" >}}

{{< headline-brackets-h2 color="blue"  >}}
Was bei uns passiert
{{< /headline-brackets-h2  >}}

{{< home/teaser-blog >}}

{{< button-center href="/blog" >}}
Mehr Blogartikel lesen
{{< /button-center >}}
{{< /section >}}


text:
exports = module.exports = function (services, passport) {
    return {
        facebook: require('./facebook')(passport),
        google: require('./google')(passport),
        local: require('./local')(services, passport)
    };
};


text:
function sensorShowImage(sensor,gam,scaleMax)
% Display the image in a scene structure.
%
%    sensorShowImage(sensor,[gam=1],[scaleMax=0])
%
% The display is shown as a r,g,b or c,m,y or monochrome array that
% indicates the values of individual pixels in the sensor, depending on
% the sensor type.
%
% This is ordinarily used from within sensorImageWindow, not from the
% command line.  When called from the command line, a new window and axis
% appear.
%
% The voltage (continuous) values are displayed. The display gamma
% parameter is read from the figure setting.
%
% The data are either scaled to a maximum of the voltage swing (default)
% or if scaleMax = 1 (Scale button is selected in the window) the image
% data are scaled to fill up the display range. This option is useful for
% small voltage values compared to the voltage swing, say in the
% simulation of human cone responses.
%
% Examples:
%   sensorShowImage(sensor,gam);
%   sensorShowImage(sensor);
%
% Copyright ImagEval Consultants, LLC, 2003.

if ieNotDefined('gam'),      gam = 1; end
if ieNotDefined('scaleMax'), scaleMax = 0; end

if isempty(sensor), cla;  return; end

% We have the voltage or digital values and we want to render them into an
% image. Here we have to handle various types of cases, include the
% multiple exposure case.
img = sensorData2Image(sensor,'volts',gam,scaleMax);

if ~isempty(img)
    % Show me what you got
    image(img); axis image; axis off;
    if (sensorGet(sensor,'nSensors') == 1), colormap(gray(256)); end
else
    % In this case, there are no volts or dvs, so we just clean up the
    % display
    cla
end

return


text: Hello DevopsCenterComponent!


text:
require 'spec_helper'

describe Nexaas::Auditor::Adapters::Nunes do
  let(:client) { double('StatisticsTracker', track_count: true, track_value: true) }
  subject { described_class.new(client) }

  it 'inherits from Nunes::Adapter' do
    expect(subject).to be_kind_of(Nunes::Adapter)
  end

  it 'uses the supplied client' do
    expect(subject.client).to eql(client)
  end

  describe '#increment' do
    it 'uses #track_count on the client, with a "rails." prefix' do
      expect(client).to receive(:track_count).with(metric: 'rails.foobar.baz', value: 42)
      subject.increment('foobar baz', 42)
    end
    it 'assumes 1 if value is not supplied' do
      expect(client).to receive(:track_count).with(metric: 'rails.foobar', value: 1)
      subject.increment('foobar')
    end
  end

  describe '#timing' do
    it 'uses #track_value on the client, with a "rails." prefix' do
      expect(client).to receive(:track_value).with(metric: 'rails.foobar.baz', value: 42.5)
      subject.timing('foobar baz', 42.5)
    end
  end

end


text:
namespace Scene
{
   // HDR: High Dynamic Range
   // Based On: https://github.com/bkaradzic/bgfx/tree/master/examples/09-hdr

   class HDR : public Scene::BaseComponent, public Rendering::RenderPostProcess
   {
      private:
         typedef Scene::BaseComponent Parent;

      protected:
         F32 mTexelHalf;
         F32 mMiddleGray;
         F32 mWhite;
         F32 mThreshold;

         Graphics::ViewTableEntry* mLuminanceView;
         Graphics::ViewTableEntry* mDownscale_Luminance0View;
         Graphics::ViewTableEntry* mDownscale_Luminance1View;
         Graphics::ViewTableEntry* mDownscale_Luminance2View;
         Graphics::ViewTableEntry* mDownscale_Luminance3View;
         Graphics::ViewTableEntry* mBrightnessView;
         Graphics::ViewTableEntry* mBlurYView;
         Graphics::ViewTableEntry* mBlurX_TonemapView;

         bgfx::UniformHandle mTonemapUniform;
         bgfx::UniformHandle mOffsetUniform;

         bgfx::FrameBufferHandle mLuminanceBuffer[5];
         bgfx::FrameBufferHandle mBrightBuffer;
         bgfx::FrameBufferHandle mBlurBuffer;

         Graphics::Shader* mLumShader;
         Graphics::Shader* mLumAvgShader;
         Graphics::Shader* mBlurShader;
         Graphics::Shader* mBrightShader;
         Graphics::Shader* mTonemapShader;

         void setOffsets2x2Lum(bgfx::UniformHandle _handle, U32 _width, U32 _height);
         void setOffsets4x4Lum(bgfx::UniformHandle _handle, U32 _width, U32 _height);

      public:
         HDR();
         ~HDR();

         virtual void onAddToScene();
         virtual void onRemoveFromScene();

         virtual void onAddToCamera();
         virtual void onRemoveFromCamera();

         virtual void process();

         static void initPersistFields();

         DECLARE_CONOBJECT(HDR);
   };
}

#endif


text:
{% extends "wagtailadmin/widgets/chooser.html" %}

{% block chooser_class %}news-chooser{% endblock %}

{% block chosen_state_view %}
    {{item}}
{% endblock %}

{% block edit_chosen_item_url %}{% if item %}{% url "wagtailnews:edit" pk=item.newsindex_id newsitem_pk=item.pk %}{% endif %}{% endblock %}

{% block icon %}icon icon-grip{% endblock %}


text:
package com.sunqi.rest;

import org.restlet.resource.Get;
import org.restlet.resource.ServerResource;

public class hello extends ServerResource{
    @Get("json")
    public String represent(){
        return "hello restlet1ss23";
    }

}


text:
@implementation PDLeftTableViewProtocol

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
  return [self.viewModel numberKindsOfProducts] ;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
  return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
  return 70;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

  PDProductListCell *cell = [PDProductListCell cellWithTableView:tableView];

  cell.nameLabel.text = [self.viewModel leftProductNameAtIndex:indexPath.row];

  [cell.iconImageView sd_setImageWithURL:[self.viewModel leftIconUrlAtIndex:indexPath.row]
                        placeholderImage:[UIImage imageNamed:@"default-icon"]];

  cell.versionLabel.text = [self.viewModel leftVersionStrAtIndex:indexPath.row];

  return cell;

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

  [self.controller leftViewClickAtIndex:indexPath.row];

}

@end


text:
from . utilities import *
from . sanitize  import sanitize
from . retry     import retry
from . testing   import with_test
from . unique    import uniq_lod


text:
export {
  default,
  transitionToExternal,
} from 'ember-route-helpers/helpers/transition-to-external';


text:
ACCEPTED

#### According to
Interim Register of Marine and Nonmarine Genera

#### Published in
Senckenb Lethaea 83 (1-2), 30 Dezember: 4.

#### Original name
null

### Remarks
null


text:
package org.rest.client;

import org.rest.client.storage.store.LocalStore;

import com.google.gwt.core.client.JavaScriptObject;

public class SyncData extends JavaScriptObject {

	protected SyncData(){}

	public final String getDebug(){
		return getVar(LocalStore.DEBUG_KEY);
	}
	public final String getHistory(){
		return getVar(LocalStore.HISTORY_KEY);
	}
	public final String getNotifications(){
		return getVar(LocalStore.NOTIFICATIONS_ENABLED_KEY);
	}
	public final String getMagicVariables(){
		return getVar(LocalStore.MAGIC_VARS_ENABLED_KEY);
	}
	public final String getCodeMirrorHeaders(){
		return getVar(LocalStore.CODE_MIRROR_HEADERS_KEY);
	}
	public final String getCodeMirrorPayload(){
		return getVar(LocalStore.CODE_MIRROR_PAYLOAD_KEY);
	}
	private final native String getVar(String key)/*-{
		return this[key] || null;
	}-*/;
}


text:
<?xml version="1.0" encoding="utf-8" ?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
         http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
         version="2.4">

    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.smart4j.framework.DispatcherServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>

</web-app>


text:
<?php

/* @EasyAdmin/default/label_empty.html.twig */
class __TwigTemplate_35c2a9e6ce4546ab83ff39ff867d2758376fb3df273e98a3d2bb0c4b8a452313 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $__internal_0bc1be422d87224232922b9e8996b4db0e2727d9afa3ffbd2f77048ab074285e = $this->env->getExtension("Symfony\\Bundle\\WebProfilerBundle\\Twig\\WebProfilerExtension");
        $__internal_0bc1be422d87224232922b9e8996b4db0e2727d9afa3ffbd2f77048ab074285e->enter($__internal_0bc1be422d87224232922b9e8996b4db0e2727d9afa3ffbd2f77048ab074285e_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "@EasyAdmin/default/label_empty.html.twig"));

        $__internal_7df5b13ce7d95fe5d1b5d239704b7af0242ad604c406360ab0ec0a7fda67dc50 = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension");
        $__internal_7df5b13ce7d95fe5d1b5d239704b7af0242ad604c406360ab0ec0a7fda67dc50->enter($__internal_7df5b13ce7d95fe5d1b5d239704b7af0242ad604c406360ab0ec0a7fda67dc50_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "@EasyAdmin/default/label_empty.html.twig"));

        // line 1
        echo "";
        echo twig_escape_filter($this->env, $this->env->getExtension('Symfony\Bridge\Twig\Extension\TranslationExtension')->trans("label.empty", array(), "EasyAdminBundle"), "html", null, true);
        echo "
";

        $__internal_0bc1be422d87224232922b9e8996b4db0e2727d9afa3ffbd2f77048ab074285e->leave($__internal_0bc1be422d87224232922b9e8996b4db0e2727d9afa3ffbd2f77048ab074285e_prof);

        $__internal_7df5b13ce7d95fe5d1b5d239704b7af0242ad604c406360ab0ec0a7fda67dc50->leave($__internal_7df5b13ce7d95fe5d1b5d239704b7af0242ad604c406360ab0ec0a7fda67dc50_prof);

    }

    public function getTemplateName()
    {
        return "@EasyAdmin/default/label_empty.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  25 => 1,);
    }

    /** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */
    public function getSource()
    {
        @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED);

        return $this->getSourceContext()->getCode();
    }

    public function getSourceContext()
    {
        return new Twig_Source("{{ 'label.empty'|trans(domain = 'EasyAdminBundle') }}
", "@EasyAdmin/default/label_empty.html.twig", "C:\\wamp64\\www\\Projet\\CFPMS\\siteweb\\dudeego\\vendor\\javiereguiluz\\easyadmin-bundle\\Resources\\views\\default\\label_empty.html.twig");
    }
}


text:
Without violating encapsulation, capture and externalize an object's internal
state so that the object can be restored to this state later.

## Applicability
Use the Memento pattern when
* a snapshot of (some portion of) an object's state must be saved so that it can be restored to that state later, and
* a direct interface to obtaining the state would expose implementation details and break the object's encapsulation.

## Structure
![memento](./etc/memento.png)

## Participants
* **Memento**
    - stores internal state of the Originator object.
    - protects against access by objects other than the originator.
* **Originator**
    - creates a memento containing a snapshot of its current internal state.
    - uses the memento to restore its internal state.
* **Caretaker**
    - is responsible for the memento's safekeeping.
    - never operates on or examines the contents of a memento.

## Example
A NotebookMemento is a snapshot of a Notebook. Notebook can restore its state and provide undo operation according to the NotebookMemento.

Participants in this example:
* Notebook is the **Originator**.
* NotebookMemento is the **Memento**, and NotebookMementoInternal is the **ConcreteMemento**.
* App is the **Caretaker**.

## Scala Tips
N/A

## Reference
* Design Patterns: Elements of Reusable Object-Oriented Software


text:
require "spec_helper"

describe EventMachine::Twilio do
  describe "#send_sms" do
    it "raises MissingCredentialsError if missing credentials" do
      lambda {
        EM::Twilio.send_sms("+12135550000", "+13105550000", "Hello")
      }.should raise_error(EM::Twilio::MissingCredentialsError)
    end

    it "creates an SMS message and delivers it" do
      EM::Twilio.authenticate("foo", "bar")

      mock_sms = mock(EM::Twilio::SMS)
      mock_sms.should_receive(:deliver).once
      EM::Twilio::SMS.should_receive(:new).with("+12135550000", "+13105550000", "Hello").and_return(mock_sms)

      EM::Twilio.send_sms("+12135550000", "+13105550000", "Hello")
    end

    # This basically tests that the block is passed all the way down
    it "calls block with SID on success" do
      EM::Twilio.authenticate("account_sid", "token")
        url = "https://api.twilio.com/2010-04-01/Accounts/account_sid/SMS/Messages"
        stub_request(:post, url).with(
          :body => {
            "To"    => "+12135550000",
            "From"  => "+13105550000",
            "Body"  => "Hello"
          },
          :headers => {
            "Authorization" => [EM::Twilio.account_sid, EM::Twilio.token],
            "User-Agent" => "em-twilio #{EM::Twilio::VERSION}"
          }
        ).to_return(fixture("created.txt"))

        EM.run_block do
          EM::Twilio.send_sms("+12135550000", "+13105550000", "Hello") do |response|
            response.sid.should == "SM805624cca3b410ad489c9e6dcf116b87"
            response.error.should be_nil
          end
        end
    end
  end

  describe "#authenticate" do
    it "sets account_sid and token" do
      EM::Twilio.authenticate("foo", "bar")
      EM::Twilio.account_sid.should == "foo"
      EM::Twilio.token.should == "bar"
    end
  end
end


text:
var GameObjectFactory = require('../GameObjectFactory');
var ParticleEmitterManager = require('./ParticleEmitterManager');

/**
 * Creates a new Particle Emitter Manager Game Object and adds it to the Scene.
 *
 * Note: This method will only be available if the Particles Game Object has been built into Phaser.
 *
 * @method Phaser.GameObjects.GameObjectFactory#particles
 * @since 3.0.0
 *
 * @param {string} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager.
 * @param {(string|integer|object)} [frame] - An optional frame from the Texture this Game Object is rendering with.
 * @param {ParticleEmitterConfig|ParticleEmitterConfig[]} [emitters] - Configuration settings for one or more emitters to create.
 *
 * @return {Phaser.GameObjects.Particles.ParticleEmitterManager} The Game Object that was created.
 */
GameObjectFactory.register('particles', function (key, frame, emitters)
{
    var manager = new ParticleEmitterManager(this.scene, key, frame, emitters);

    this.displayList.add(manager);
    this.updateList.add(manager);

    return manager;
});

//  When registering a factory function 'this' refers to the GameObjectFactory context.
//
//  There are several properties available to use:
//
//  this.scene - a reference to the Scene that owns the GameObjectFactory
//  this.displayList - a reference to the Display List the Scene owns
//  this.updateList - a reference to the Update List the Scene owns


text:
/*
 ** © 2018 by Philipp Dunkel, Ben Noordhuis, Elan Shankar
 ** Licensed under MIT License.
 */

/* jshint node:true */
'use strict';

const path = require('path');
const assert = require('assert');
const fsevents = require('../fsevents');
const { run, sleep } = require('./utils/misc.js');
const { touch } = require('./utils/fs.js');

const DIR = process.argv[2];

run(async () => {
  const events = [];
  const stopWatching = fsevents.watch(DIR, (...args) => events.push(args));
  await sleep(500);
  for (let idx = 0; idx < 10; idx++) {
    await touch(path.join(DIR, `${idx + 1}.touch`));
    await sleep(250);
  }
  await sleep(500);
  assert.equal(events.length, 10);
  await stopWatching();
});


text:
package agent;

import jade.core.Agent;
import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;

/**
 * Administrator agent.
 * TODO time out
 */
public class Administrator extends Agent {

    @Override
    protected void setup() {
        System.out.println("Hello ! My name is " + getLocalName());
        System.out.println("AID : " + getAID().getName());

        parseArguments();

        addBehaviour(new CyclicBehaviour(this) {
            @Override
            public void action() {
                System.out.println("Waiting for message");
                ACLMessage message = myAgent.receive();
                if (message != null) {
                    // process the received message
                    System.out.println("Receive message : " + message.getContent());
                    //
                    ACLMessage reply = message.createReply();
                    reply.setPerformative(ACLMessage.CONFIRM);
                    reply.setContent("ACK");
                    send(reply);
                } else {
                    // block the behaviour while receiving message
                    System.out.println("block");
                    block();
                }
            }
        });
    }

    private void parseArguments() {
        // get arguments
        Object[] args = getArguments();
        String s;

        if (args != null && args.length > 0) {
            for (int i = 0; i < args.length; i++) {
                s = (String) args[i];
                System.out.println("p" + i + ": " + s);
            }
        }
    }

    @Override
    protected void takeDown() {
        System.out.println("Good bye");
    }
}


text:
// Strong Hold BOB 2016 Subsystems (Drive Train)

package org.usfirst.frc319.subsystems;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.usfirst.frc319.LeftMotionProfile;
import org.usfirst.frc319.RightMotionProfile;
import org.usfirst.frc319.Robot;
import org.usfirst.frc319.RobotMap;
import org.usfirst.frc319.commands.*;
import org.usfirst.frc319.motionProfiles.*;

import com.kauailabs.navx.frc.AHRS;
import com.team319.pid.IPidChangeListener;
import com.team319.pid.Pid;
import com.team319.pid.PidManager;
import com.team319.robot.StatefulSubsystem;
import com.team319.robot.logging.LoggableCanTalon;
import com.team319.robot.logging.LoggableSensor;
import com.team319.trajectory.CombinedSrxMotionProfile;
import com.team319.trajectory.ITrajectoryChangeListener;
import com.team319.vision.ITargetListener;
import com.team319.vision.Target;
import com.team319.vision.TargetManager;

import edu.wpi.first.wpilibj.AnalogGyro;
import edu.wpi.first.wpilibj.BuiltInAccelerometer;
import edu.wpi.first.wpilibj.CANTalon;
import edu.wpi.first.wpilibj.CANTalon.FeedbackDevice;
import edu.wpi.first.wpilibj.CANTalon.MotionProfileStatus;
import edu.wpi.first.wpilibj.DoubleSolenoid;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.CANTalon.TalonControlMode;
import edu.wpi.first.wpilibj.SPI;
import edu.wpi.first.wpilibj.command.Subsystem;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;

/**
 *
 */
public class DriveTrain extends Subsystem implements IPidChangeListener, ITargetListener{// extends
																			// StatefulSubsystem{

	public boolean shift;
	public boolean isBrakeModeEnabled;

	public String highGear = "High Gear";
	public String lowGear = "Low Gear";

	private final DoubleSolenoid shifter = RobotMap.driveTrainshifter;
	private final CANTalon rightDriveLead = RobotMap.driveTrainrightDriveLead;
	private final CANTalon leftDriveLead = RobotMap.driveTrainleftDriveLead;
	private final CANTalon rightDriveFollow = RobotMap.driveTrainrightDriveFollow;
	private final CANTalon leftDriveFollow = RobotMap.driveTrainleftDriveFollow;
	private final RobotDrive drivetrain = RobotMap.driveTraindriveTrain;
	private final AnalogGyro gyro = RobotMap.gyro;
	private final BuiltInAccelerometer rioAccelerometer = RobotMap.rioAccelerometer;

	private Pid pid = null;

	LeftMotionProfile leftProfile = new LeftMotionProfile(leftDriveLead);
	RightMotionProfile rightProfile = new RightMotionProfile(rightDriveLead);

	private CombinedSrxMotionProfile currentProfile;
	private double horizontalOffset = 0d;;

	public DriveTrain() {

		PidManager.getInstance().registerListener(this);
		//TargetManager.getInstance().registerListener(this);

		rightDriveLead.changeControlMode(TalonControlMode.PercentVbus);
		rightDriveFollow.changeControlMode(TalonControlMode.Follower);
		rightDriveFollow.set(rightDriveLead.getDeviceID());
		leftDriveLead.changeControlMode(TalonControlMode.PercentVbus);
		leftDriveFollow.changeControlMode(TalonControlMode.Follower);
		leftDriveFollow.set(leftDriveLead.getDeviceID());

		rightDriveLead.setFeedbackDevice(FeedbackDevice.QuadEncoder);
		rightDriveLead.configEncoderCodesPerRev(1024);
		rightDriveLead.reverseSensor(true);// true
		rightDriveLead.reverseOutput(false);

		rightDriveLead.setF(0.312);
		rightDriveLead.setP(.2);//0.32);

		leftDriveLead.setFeedbackDevice(FeedbackDevice.QuadEncoder);
		leftDriveLead.configEncoderCodesPerRev(1024);
		leftDriveLead.reverseSensor(false);
		leftDriveLead.reverseOutput(true);

		leftDriveLead.setF(0.333);
		leftDriveLead.setP(.2);//0.32);

	}

	public void initDefaultCommand() {
		setDefaultCommand(new ArcadeDrive());

	}

	public void arcadeDrive(double moveValue, double rotateValue) {

		drivetrain.arcadeDrive(-moveValue, rotateValue, true);
		SmartDashboard.putNumber("moveValue", moveValue);
		SmartDashboard.putNumber("rotateValue", rotateValue);

		// true is a boolean for "squared inputs" - derrick 1/20/16

		// moved two lines below to teleop Periodic 3:20 pm 2/6/16
		leftProfile.control();
		rightProfile.control();
		// leftProfile.reset();
		// rightProfile.reset();
	}

	public void reverseArcadeDrive(double moveValue, double rotateValue) {

		drivetrain.arcadeDrive(moveValue, rotateValue, true);

		leftProfile.control();
		rightProfile.control();

	}

	public void driveStraight(double speed) {
		double angle = gyro.getAngle();
		double angleCorrectionFactor = .05;
		drivetrain.drive(speed, -angle * angleCorrectionFactor);

	}

	public double getGyroAngle() {
		return gyro.getAngle();
	}

	public void resetGyro() {
		gyro.reset();
	}
	public double getZAxis(){
		return (rioAccelerometer.getZ()-1);
	}
	public double getYAxis(){
		return (rioAccelerometer.getY());
	}

	public int getLeftDrivetrainPosition() {
		return leftDriveLead.getEncPosition();
	}

	public int getRightDrivetrainPosition() {
		return rightDriveLead.getEncPosition();
	}

	public void setRightEncoderToZero() {
		rightDriveLead.setEncPosition(0);
	}

	public void setLeftEncodertoZero() {
		leftDriveLead.setEncPosition(0);
	}

	public void setDTEncodersToZero() {
		//rightDriveLead.changeControlMode(TalonControlMode.Position);
		//leftDriveLead.changeControlMode(TalonControlMode.Position);
		System.out.println("setDTencoders to Zero phase 1 Right: " +rightDriveLead.getEncPosition());
		System.out.println("setDTencoders to Zero phase 1 Left: " +leftDriveLead.getEncPosition());
		//leftDriveLead.reset();
		//rightDriveLead.reset();
		System.out.println("Is the left drive reset?");
		System.out.println("Is the left drive Reset?");
		leftDriveLead.setPosition(0);
		rightDriveLead.setPosition(0);
		System.out.println("setDTencoders to Zero phase 2 Right: " +rightDriveLead.getEncPosition());
		System.out.println("setDTencoders to Zero phase 2 Left: " +leftDriveLead.getEncPosition());
		leftDriveLead.setEncPosition(0);
		rightDriveLead.setEncPosition(0);
		System.out.println("setDTencoders to Zero phase 3 Right: " +rightDriveLead.getEncPosition());
		System.out.println("setDTencoders to Zero phase 3 Left: " +leftDriveLead.getEncPosition());
		//rightDriveLead.changeControlMode(TalonControlMode.PercentVbus);
		//leftDriveLead.changeControlMode(TalonControlMode.PercentVbus);
		System.out.println("setDTencoders to Zero");
	}

	// ------used for drive straight command-----//
	public double getDistanceFromEncoderValues() {
		double leftDistance = Math.abs(leftDriveLead.getEncPosition());
		double rightDistance = Math.abs(rightDriveLead.getEncPosition());
		double robotDistance = (leftDistance + rightDistance) / 2;
		return robotDistance;
	}

	// Output Shift to Smart Dash Board as a boolean (Wyatt- 1/27/16)
	public void shiftUp() {
		Robot.driveTrain.shifter.set(DoubleSolenoid.Value.kForward);// need to
																	// verify
																	// that
																	// shift up
																	// is shift
																	// up
		shift = false;

	}

	public void shiftDown() {
		Robot.driveTrain.shifter.set(DoubleSolenoid.Value.kReverse);
		shift = true;

	}

	public void controlRightMotionProfile() {
		rightProfile.control();
	}

	public void controlLeftMotionProfile() {
		leftProfile.control();
	}

	public void toggleDrive() {
		// drivetrain.arcadeDrive(stick);

	}

	// all of this is now in the FollowBothMotion Profiles Command
	/*
	 * public void rightFollowMotionProfile() {
	 *
	 * // leftProfile.control();//I think this may need to be moved to the //
	 * default Command of the subsystem (Derrick 2/6/15)
	 * rightDriveLead.changeControlMode(TalonControlMode.MotionProfile);
	 * CANTalon.SetValueMotionProfile setOutput = rightProfile.getSetValue();
	 * rightDriveLead.set(setOutput.value); }
	 *
	 * public void leftFollowMotionProfile() {
	 * leftDriveLead.changeControlMode(TalonControlMode.MotionProfile);
	 * CANTalon.SetValueMotionProfile setOutput = leftProfile.getSetValue();
	 * leftDriveLead.set(setOutput.value); }
	 *
	 * public void enableMotionProfileMode() {
	 * rightDriveLead.setFeedbackDevice(FeedbackDevice.QuadEncoder);
	 * rightDriveLead.configEncoderCodesPerRev(1024);
	 * rightDriveLead.reverseSensor(true); //
	 * rightDriveLead.changeControlMode(TalonControlMode.MotionProfile);
	 *
	 * rightDriveLead.setF(0.15); // not sure where to tune PID -DErrick //
	 * 1/29/15 rightDriveLead.setP(0); rightDriveLead.setI(0);
	 * rightDriveLead.setD(0); rightDriveLead.setIZone(0);
	 * rightDriveLead.setCloseLoopRampRate(0);
	 *
	 * leftDriveLead.setFeedbackDevice(FeedbackDevice.QuadEncoder);
	 * leftDriveLead.configEncoderCodesPerRev(1024);
	 * leftDriveLead.reverseSensor(true); //
	 * leftDriveLead.changeControlMode(TalonControlMode.MotionProfile);
	 *
	 * leftDriveLead.setF(0.15); // not sure where to tune PID -DErrick 1/29/15
	 * leftDriveLead.setP(0); leftDriveLead.setI(0); leftDriveLead.setD(0);
	 * leftDriveLead.setIZone(0); leftDriveLead.setCloseLoopRampRate(0);
	 *
	 * }
	 *
	 * public void startLeftMotionProfile() { leftProfile.startMotionProfile();
	 * }
	 *
	 * public void startRightMotionProfile() {
	 * rightProfile.startMotionProfile(); }
	 *
	 * public void resetLeftMotionProfile() { leftProfile.reset(); }
	 *
	 * public void resetRightMotionProfile() { rightProfile.reset(); }
	 *
	 * public int getRightTimeoutCnt() { return rightProfile.getTimeoutCnt(); }
	 *
	 * public int getLeftTimeoutCnt() { return leftProfile.getTimeoutCnt(); }
	 */
	/*
	 * public boolean isRightMotionProfileFinished() { MotionProfileStatus
	 * rightMPStatus = new MotionProfileStatus();
	 * rightDriveLead.getMotionProfileStatus(rightMPStatus);
	 *
	 * return rightMPStatus.activePoint.isLastPoint; }
	 *
	 * public boolean isLeftMotionProfileFinished() { MotionProfileStatus
	 * leftMPStatus = new MotionProfileStatus();
	 * leftDriveLead.getMotionProfileStatus(leftMPStatus);
	 *
	 * return leftMPStatus.activePoint.isLastPoint; }
	 */

	public void setModeToVBus() {
		rightDriveLead.changeControlMode(TalonControlMode.PercentVbus);
		rightDriveFollow.changeControlMode(TalonControlMode.Follower);
		rightDriveFollow.set(rightDriveLead.getDeviceID());
		leftDriveLead.changeControlMode(TalonControlMode.PercentVbus);
		leftDriveFollow.changeControlMode(TalonControlMode.Follower);
		leftDriveFollow.set(leftDriveLead.getDeviceID());
	}

	public void setModeToVelocity(){
		rightDriveLead.changeControlMode(TalonControlMode.Speed);
		leftDriveLead.changeControlMode(TalonControlMode.Speed);
	}

	public void setLeftRightSpeeds(double leftSpeed, double rightSpeed){
		rightDriveLead.set(rightSpeed);
		leftDriveLead.set(leftSpeed);
	}

	// @Override
	public Map<String, Object> getCustomProperties() {
		// TODO Auto-generated method stub
		Map<String, Object> properties = new HashMap<String, Object>();
		properties.put("isHighGear", !shift);
		return properties;
	}

	// @Override
	public List<LoggableSensor> getSensors() {
		// TODO Auto-generated method stub
		List<LoggableSensor> sensors = new ArrayList<LoggableSensor>();

		sensors.add(new LoggableCanTalon("leftTalon", this.leftDriveLead));
		sensors.add(new LoggableCanTalon("rightTalon", this.rightDriveLead));

		return sensors;
	}

	/**
	 *
	 * @return the latest profile provided by the Trajectory Server
	 */
	public CombinedSrxMotionProfile getCurrentProfile() {
		return currentProfile;
	}

	/**
	 *
	 * @param currentProfile
	 *            store the profile that was generated by the Trajectory Server
	 */
	public void setCurrentProfile(CombinedSrxMotionProfile currentProfile) {
		// same as Robot.driveTrain.currentProfile = currentProfile
		this.currentProfile = currentProfile;
	}

	public void enableBrakeMode(boolean brake) {
		this.leftDriveLead.enableBrakeMode(brake);
		this.leftDriveFollow.enableBrakeMode(brake);
		this.rightDriveLead.enableBrakeMode(brake);
		this.rightDriveFollow.enableBrakeMode(brake);
		this.isBrakeModeEnabled = brake;

	}

	@Override
	public void onPidChange(Pid pid) {
		this.pid = pid;
	}

	public Pid getPid() {
		return pid;
	}

	public void setVoltageRampRate(double rampRate)
	{
		this.leftDriveLead.setVoltageRampRate(rampRate);
		this.rightDriveLead.setVoltageRampRate(rampRate);
	}
	public boolean leftDriveLeadStatus(){
		return this.leftDriveLead.isAlive();
	}
	public boolean rightDriveLeadStatus(){
		return this.rightDriveLead.isAlive();
	}

	public void setTargetHorizontalOffset(double horizontalOffset) {
		this.horizontalOffset = horizontalOffset;
	}

	public double getHorizontalOffset() {
		return horizontalOffset;
	}

	@Override
	public void onTargetChange(Target target) {
		this.horizontalOffset = target.getHorizontalOffset();

	}
}


text:
#ifndef __FORK_POST_PROCESSOR_GAUSSIAN_BLUR_H__
#define __FORK_POST_PROCESSOR_GAUSSIAN_BLUR_H__

#include "Video/AdvancedRenderer/PostProcessor/PostProcessor.h"
#include "Video/RenderSystem/Shader/ShaderComposition.h"
#include "Video/RenderSystem/Shader/StandardShader/GaussianBlurConstantBuffers.h"
#include "Video/RenderSystem/Texture/Texture2D.h"
#include "Video/RenderSystem/Texture/RenderTarget.h"
#include "Video/RenderSystem/RenderState/SamplerState.h"

namespace Fork
{

namespace Video
{

DECL_SHR_PTR(GaussianBlur);

/**
Gaussian blur post processor. This can be used to blur an image smoothly.
\code
auto gaussianBlur = std::make_unique<Video::GaussianBlur>(screenResolution);
auto frameBufferTexture = renderSystem->CreateTexture2D(Video::TextureFormats::RGBA, screenResolution);
auto frameBufferTarget = renderSystem->CreateRenderTarget({ frameBufferTexture });
//...
renderSystem->Bind(frameBufferTarget.get());
{
    // Draw scene into render target ...
}
// Draw gaussian blur effect:
gaussianBlur->Draw(frameBufferTexture.get(), renderContext->GetMainRenderTarget());
\endcode
\remarks This is not the same as the bloom filter. The bloom filter blurs the image
(also with a gaussian blur) in a lower resolution.
\remarks Here is an example picture of this post-processing effect:
\image html images/GaussianBlur.Example.png
\ingroup postprocessor
*/
class FORK_EXPORT GaussianBlur : public PostProcessor
{

    public:

        /* === Structures === */

        //! Effect configuration structure.
        struct FORK_EXPORT Configuration
        {
            int     numSamples      = 1;    //!< Number of texture samples to blur the image. By default 1.
            float   stretchFactor   = 1.0f; //!< Stretch factor of the texture coordinates. By default 1.0.
            float   variance        = 0.1f; //!< Gaussian distribution variance. By default 0.1.
        };

        /* === Functions === */

        GaussianBlur(const Math::Size2i& initResolution);

        //! Returns "Gaussian Blur".
        std::string Name() const override;

        void Draw(RenderTarget* renderTarget) override;

        /**
        Initializes this post processing effect.
        \param[in] inputTexture Specifies the input texture which is to be blured.
        \remarks The input texture will not be modified, instead the blurred version
        will be rendered to the render target, specified in the 'Draw' function.
        \note This must be called before the effect can be drawn!
        \see Draw
        */
        void Setup(const Texture2D* inputTexture);

        /**
        Changes the effect configuration.
        \param[in] numSamples Specifies the number of texture samples to blur the output image.
        This value will be clamped to the range [1 .. GaussianBlurConfigConstBuffer::maxNumSamples]. By default 8.
        \param[in] stretchFactor Specifies the factor which is used to stretch the blur texture samples.
        Values greater than 1.0 may produce a lower quality but a larger blur. By default 1.0.
        \param[in] variance Specifies the variance of the gaussian distribution.
        A large value (e.g. 10+) will converge the blur to a box filter (i.e. less smooth). By default 0.1.
        \see GaussianBlurConfigConstBuffer::maxNumSamples
        */
        void ChangeConfig(int numSamples, float stretchFactor = 1.0f, float variance = 0.1f);

        //! Returns the effect configuration.
        inline const Configuration& GetConfig() const
        {
            return config_;
        }

    private:

        static const int renderPassHorz = 0;
        static const int renderPassVert = 1;

        /* === Functions === */

        void OnUpdateResolution() override;

        void CreateShader();
        void CreateRenderTarget();
        void CreateSamplerState();

        void UpdateTextureSize();
        void UpdateConfigConstantBuffer();

        void SetupRenderPass(int renderPass);
        void DrawRenderPass(const Texture2D* inputTexture, RenderTarget* renderTarget, int renderPass);

        void ComputeWeights(int numSamples, float variance);
        void ComputeOffsets(int numSamples, float stretchFactor);

        float HalfSize(int numSamples) const;
        float GaussianValue(float pos, float mean, float stdDeviation) const;

        /* === Members === */

        ShaderCompositionPtr    shader_;

        ConstantBufferPtr       constBufferConfig_;
        ConstantBufferPtr       constBufferRenderPass_;

        StandardShader::GaussianBlurShader::ConfigConstBuffer constBufferConfigData_;

        const Texture2D*        inputTexture_ = nullptr;
        Texture2DPtr            tempTexture_;           //!< Temporary texture for a separate render pass.
        RenderTargetPtr         tempRenderTarget_;      //!< Render target for the separate render pass.
        SamplerStatePtr         clampedSamplerState_;

        Configuration           config_;

};

} // /namespace Video

} // /namespace Fork

#endif

// ========================


text:
<!DOCTYPE html>

<title>工作流任务查看</title>

<link rel="stylesheet" href="page/M0/M0012.css"/>

			流程信息
			<button type="button" class="btn k-btn k-btn-collapse"></button>

			<button type="button" class="btn btn-success k-btn " onclick="mprint()">打印</button>
			<form name="M0013P01F001" class="k-form col3 " id="M0013P01F001" enctype="multipart/form-data">

					流程ID

					流程

					主题

					提交人

			</form>

			审批信息
			<button type="button" class="btn k-btn k-btn-collapse"></button>

				节点标注:

				未审批节点

				已审批节点

				拒绝节点

					操作前数据
					<button type="button" class="btn k-btn k-btn-collapse"></button>

								基本信息

任务ID

					操作后数据
					<button type="button" class="btn k-btn k-btn-collapse"></button>

								基本信息

任务ID


text:
/***************************************************************************
*  FILENAME: draw_heat.c   C VERSION
*  DESCRIPTION:
*    Called by heat2D example files.  No attempt is made to
*    document this code.  It is simply meant to provide a graphical interface
*    for the heat2D sample code's results.
*  AUTHOR: Blaise Barney
*  LAST REVISED: 01/26/09
***************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>

#define HEIGHT         750
#define WIDTH          750
#define NCOLORS        255

typedef struct {
   Window window;
   XSizeHints hints;
   XColor backcolor;
   XColor bordcolor;
   int    bordwidth;
} MYWINDOW;

char title[] = {"draw_heat"},
     moreword[] = {"More"},
     exitword[] = {"Exit"},
     text[10];

/* To call from Fortran: uncomment the routine below with the extra underscore in the name
void draw_heat_(int nx, int ny) {
*/
/* To call from C, use the routine below - without the extra underscore */
void draw_heat(int nx, int ny) {

float 	scale, point, high, *a1, *a2, coloratio = 65535.0 / 255.0;
int 	i,j,k,x,y,done, myscreen, rectheight, rectwidth,toggle;
FILE	*initial, *final;

MYWINDOW base,more,quit;
Font 	font,font2;
GC 		itemgc,textgc,rectgc[NCOLORS],linegc;
XColor 	rectcolor,red,yellow,blue,green,black,white;
XEvent 	myevent;
Colormap cmap;
KeySym 	mykey;
Display *mydisp;

/* Set rgb values for colors */
yellow.red= (int) (255 * coloratio);
yellow.green= (int) (255 * coloratio);
yellow.blue= (int) (0 * coloratio);

green.red= (int) (0 * coloratio);
green.green= (int) (255 * coloratio);
green.blue= (int) (0 * coloratio);

black.red= (int) (0 * coloratio);
black.green= (int) (0 * coloratio);
black.blue= (int) (0 * coloratio);

white.red= (int) (255 * coloratio);
white.green= (int) (255 * coloratio);
white.blue= (int) (255 * coloratio);

mydisp = XOpenDisplay("");
if (!mydisp) {
   fprintf (stderr, "Hey! Either you don't have X or something's not right.\n");
   fprintf (stderr, "Guess I won't be showing the graph.  No big deal.\n");
   exit(1);
   }
myscreen = DefaultScreen(mydisp);
cmap = DefaultColormap (mydisp, myscreen);
XAllocColor (mydisp, cmap, &yellow);
XAllocColor (mydisp, cmap, &black);
XAllocColor (mydisp, cmap, &green);
XAllocColor (mydisp, cmap, &white);

/* initial window position and size */
base.hints.x = 50;
base.hints.y = 50;
base.hints.width = WIDTH;
base.hints.height = HEIGHT;
base.hints.flags = PPosition | PSize;
base.bordwidth = 5;

/* window Creation */
base.window = XCreateSimpleWindow (mydisp, DefaultRootWindow (mydisp),
            base.hints.x, base.hints.y, base.hints.width, base.hints.height,
            base.bordwidth, black.pixel, black.pixel);
XSetStandardProperties (mydisp, base.window, title, title, None,
                        NULL, 0, &base.hints);

/* quit window position and size (subwindow of base) */
quit.hints.x = 5;
quit.hints.y = HEIGHT-75;
quit.hints.width = 70;
quit.hints.height = 30;
quit.hints.flags = PPosition | PSize;
quit.bordwidth = 5;

quit.window = XCreateSimpleWindow (mydisp, base.window, quit.hints.x,
              quit.hints.y, quit.hints.width, quit.hints.height,
              quit.bordwidth, green.pixel, yellow.pixel);
XSetStandardProperties (mydisp, quit.window, exitword, exitword, None,
             NULL, 0, &quit.hints);
/* more window position and size (subwindow of base) */
more.hints.x = WIDTH-85;
more.hints.y = HEIGHT-75;
more.hints.width = 70;
more.hints.height = 30;
more.hints.flags = PPosition | PSize;
more.bordwidth = 5;

more.window = XCreateSimpleWindow (mydisp, base.window, more.hints.x,
              more.hints.y, more.hints.width, more.hints.height,
              more.bordwidth, green.pixel, yellow.pixel);
XSetStandardProperties (mydisp, more.window, moreword, moreword, None,
             NULL, 0, &more.hints);

/* Load fonts */
/*
font = XLoadFont (mydisp, "Rom28");
font2 = XLoadFont (mydisp, "Rom17.500");
*/
font = XLoadFont (mydisp, "fixed");
font2 = XLoadFont (mydisp, "fixed");

/* GC creation and initialization */
textgc = XCreateGC (mydisp, base.window, 0,0);
XSetFont (mydisp, textgc, font);
XSetForeground (mydisp, textgc, green.pixel);

linegc = XCreateGC (mydisp, base.window, 0,0);
XSetForeground (mydisp, linegc, white.pixel);

itemgc = XCreateGC (mydisp, quit.window, 0,0);
XSetFont (mydisp, itemgc, font2);
XSetForeground (mydisp, itemgc, black.pixel);

/* create shades of red color scale */
for (k=0;k<NCOLORS;k++) {
  rectgc[k] = XCreateGC (mydisp, base.window, 0,0);
  rectcolor.red= (int) (k * coloratio);
  rectcolor.green= (int) (0 * coloratio);
  rectcolor.blue= (int) (0 * coloratio);
  XAllocColor (mydisp, cmap, &rectcolor);
  XSetForeground (mydisp, rectgc[k], rectcolor.pixel);
  }

/* The program is event driven; the XSelectInput call sets which kinds of */
/* interrupts are desired for each window. These aren't all used. */
XSelectInput (mydisp, base.window,
              ButtonPressMask | KeyPressMask | ExposureMask);
XSelectInput (mydisp, quit.window,
              ButtonPressMask | KeyPressMask | ExposureMask);
XSelectInput (mydisp, more.window,
              ButtonPressMask | KeyPressMask | ExposureMask);

/* window mapping -- this lets windows be displayed */
XMapRaised (mydisp, base.window);
XMapSubwindows (mydisp, base.window);

/* create space for data to be read */
a1 = (float *) malloc(nx*ny*sizeof(float));
a2 = (float *) malloc(nx*ny*sizeof(float));

/* Read the two data files created by heat2D program execution */
/* Also determine the highest value read */
high = 0.0;
initial = fopen("initial.dat","r");
for (k=0;k<nx*ny;k++) {
  fscanf(initial,"%f",a1+k);
  if ( *(a1+k) > high) high = *(a1+k);
  }
fclose(initial);

final = fopen("final.dat","r");
for (k=0;k<nx*ny;k++)
  fscanf(final,"%f",a2+k);
fclose(final);

/* Scale rectangle size and color */
rectwidth = WIDTH/ny;
rectheight = HEIGHT/nx;
scale = ((float)NCOLORS) / high;

/* Main event loop  --  exits when user clicks on "exit" */
done = 0;
toggle = 0;
while (! done) {
   XNextEvent (mydisp, &myevent);   /* Read next event */
   switch (myevent.type) {
   case Expose:
      if (myevent.xexpose.count == 0) {
         if (myevent.xexpose.window == base.window) {
            for (x=0;x<nx;x++) {
              for (y=0;y<ny;y++) {
                if (toggle == 0)
                  point = scale * *(a1+x*ny+y);
                else
                  point = scale * *(a2+x*ny+y);
                k = (int) point;
                if (k >= NCOLORS) k = NCOLORS-1;
                XFillRectangle (mydisp, base.window, rectgc[k], y*rectwidth,
                                x*rectheight, rectwidth, rectheight);
                }
              }
            for (x=0;x<nx;x++)
              XDrawLine (mydisp, base.window, linegc, 1,x*rectheight,WIDTH,
                         x*rectheight);
            for (y=0;y<ny;y++)
              XDrawLine (mydisp, base.window, linegc, y*rectwidth,1,
                         y*rectwidth,HEIGHT);
            XDrawString (mydisp, base.window, textgc,325,30,"Heat2D",6);
            if (toggle == 0)
              XDrawString (mydisp, base.window, textgc,325,735,"INITIAL",7);
            else
              XDrawString (mydisp,base.window,textgc,330,735,"FINAL",5);
            }

         else if (myevent.xexpose.window == quit.window)
            XDrawString (mydisp, quit.window, itemgc, 12,20, exitword,
                         strlen(exitword));
         else if (myevent.xexpose.window == more.window)
            XDrawString (mydisp, more.window, itemgc, 12,20, moreword,
                         strlen(moreword));
      }   /* case Expose */
      break;

   case ButtonPress:
      if (myevent.xbutton.window == quit.window)
         done = 1;
      else if (myevent.xbutton.window == more.window) {
         if (toggle==0)
           toggle = 1;
         else if (toggle==1)
           toggle = 0;
         for (x=0;x<nx;x++) {
           for (y=0;y<ny;y++) {
             if (toggle==0)
               point = scale * *(a1+x*ny+y);
             else
               point = scale * *(a2+x*ny+y);
             k = (int) point;
             if (k >= NCOLORS) k = NCOLORS-1;
             XFillRectangle (mydisp, base.window, rectgc[k], y*rectwidth,
                            x*rectheight, rectwidth, rectheight);
             }
          }
          for (x=0;x<nx;x++)
            XDrawLine (mydisp, base.window, linegc, 1,x*rectheight,WIDTH,
                      x*rectheight);
          for (y=0;y<ny;y++)
            XDrawLine (mydisp, base.window, linegc, y*rectwidth,1,
                       y*rectwidth,HEIGHT);
          XDrawString (mydisp, base.window, textgc,325,30,"heat2D",6);
          if (toggle==0)
            XDrawString (mydisp, base.window, textgc,325,735,"INITIAL",7);
          else
            XDrawString (mydisp,base.window,textgc,330,735,"FINAL",5);
       }

      break;

   case MappingNotify:
/*
      XRefreshKeyboardMapping (&myevent);
*/
      break;

      }  /* switch (myevent.type) */

   }   /* while (! done) */

XDestroyWindow (mydisp, base.window);
XCloseDisplay (mydisp);
}


text:
import * as fs from 'fs';

export type Stats = fs.Stats;

export function open(path: string, mode: string): Promise<number> {
  return new Promise((resolve, reject) => {
    fs.open(path, mode, (err, fd) => {
      err ? reject(err) : resolve(fd);
    });
  });
}

export async function read(fd: number, length: number): Promise<Buffer> {
  let buffer = Buffer.allocUnsafe(length);
  let bytesRead = await new Promise((resolve, reject) => {
    fs.read(fd, buffer, 0, length, null, (err, bytesRead) => {
      err ? reject(err) : resolve(bytesRead);
    });
  });
  return buffer.slice(0, bytesRead);
}

export function close(fd: number): Promise<void> {
  return new Promise((resolve, reject) => {
    fs.close(fd, err => {
      err ? reject(err) : resolve();
    });
  });
}

export async function readlink(path: string): Promise<string> {
  const buffer = new Promise((resolve, reject) => {
    fs.readlink(path, (err, dest) => {
      err ? reject(err) : resolve(dest);
    });
  });
  return buffer instanceof Buffer ? buffer.toString() : buffer;
}

export function lstat(path: string): Promise<Stats> {
  return new Promise((resolve, reject) => {
    fs.lstat(path, (err, stat) => {
      err ? reject(err) : resolve(stat);
    });
  });
}

// noinspection JSUnusedGlobalSymbols
export function stat(path: string): Promise<Stats> {
  return new Promise((resolve, reject) => {
    fs.stat(path, (err, stat) => {
      err ? reject(err) : resolve(stat);
    });
  });
}

export async function readdir(path: string): Promise<string[]> {
  const names = await new Promise((resolve, reject) => {
    fs.readdir(path, (err, names) => {
      err ? reject(err) : resolve(names);
    });
  });
  // Googling gives mixed results about whether fs.readdir() sorts and
  // whether it sorts on all platforms. Just sort it ourselves to be sure.
  names.sort((a, b) => (a === b ? 0 : a > b ? 1 : -1));
  return names;
}

export function rmdir(path: string): Promise<void> {
  return new Promise((resolve, reject) => {
    fs.rmdir(path, err => {
      err ? reject(err) : resolve();
    });
  });
}

export function unlink(path: string): Promise<void> {
  return new Promise((resolve, reject) => {
    fs.unlink(path, err => {
      err ? reject(err) : resolve();
    });
  });
}


text:
from __future__ import unicode_literals

import autoslug.fields
from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('groups', '0001_initial'),
    ]

    operations = [
        migrations.AddField(
            model_name='company',
            name='slug',
            field=autoslug.fields.AutoSlugField(default='', editable=False, populate_from='name'),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='family',
            name='slug',
            field=autoslug.fields.AutoSlugField(default='', editable=False, populate_from='name'),
            preserve_default=False,
        ),
    ]


text:
package gov.nih.nci.cananolab.restful;

import static org.junit.Assert.*;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;

import org.glassfish.jersey.client.ClientConfig;
import org.junit.Before;
import org.junit.Test;

public class SecurityServicesTest {

	String urlbase = "http://localhost:8080/caNanoLab/rest/";
	Client client;

	@Before
	public void setUp() throws Exception {
		client = ClientBuilder.newClient();
	}

	@Test
	public void testLogin() {
		try {
		String jsonString = client.target(urlbase)
				.register(SampleServices.class)
				.path("security/login")
				.queryParam("username", "canano_res").queryParam("password", "Quality@4")
				.request("application/json")
				.header("some-header", "true")
				.get(String.class);

		assertNotNull(jsonString);
		assertTrue(jsonString.length() > 0);

		jsonString = client.target(urlbase)
				.register(SampleServices.class)
				.path("security/logout")
				.request("application/json")
				.header("some-header", "true")
				.get(String.class);

		//test with fake password
			assertNotNull(jsonString);
			assertTrue(!jsonString.contains("success"));
		} catch (Exception e) {
			assertTrue(e.getMessage().equals("HTTP 404 Not Found"));
		}
	}

	@Test
	public void testLogout() {
		String jsonString = client.target(urlbase)
				.register(SampleServices.class)
				.path("security/logout")
				.request("application/json")
				.header("some-header", "true")
				.get(String.class);

		assertNotNull(jsonString);
		assertTrue(jsonString.contains("success"));
	}

}


text:
import {UPDATE_SETUP, UPDATE_SETUP_SUCCESS} from './actionTypes.js';

export function update(key, value) {
  return {
    type:    UPDATE_SETUP,
    payload: {key, value}
  }
}

function postSession(session) {
  return fetch('/createSession', {
    method:      'POST',
    headers:     {'Content-Type': 'application/json'},
    credentials: 'same-origin',
    body:        JSON.stringify(session)
  })
}

function endSessionPost() {
  return fetch('/endSession', {
    method:      'POST',
    headers:     {'Content-Type': 'application/json'},
    credentials: 'same-origin',
  })
}

function handleResponse(response) {
  console.log('response', response);
  if (response.ok) {
    return response;
  }

  const error = new Error(response);
  error.response = response;
  throw error;
}

export function createSession(session) {
  return dispatch => postSession(session)
    .then(handleResponse)
    .then(res => res.json())
    .then(res => dispatch(success(res)))
    .catch(() => dispatch(failed()));
}

export function endSession(_id) {
  return dispatch => {
    dispatch({type: 'END SESSION'});
    endSessionPost(_id)
    .then(handleResponse)
    .then(() => alert('session ended'))
    .catch(() => alert('failed to end session'));
  }
}

export function success(session) {
  return {
    type:    UPDATE_SETUP_SUCCESS,
    payload: {
      session: session
    }
  }
}

export function failed() {
  alert('failed something went wrong');
}


text:
exports.up = function(knex, Promise) {
  return Promise.all([
    knex.schema.createTable('post', (table) => {
      table.increments();
      table.string('title');
      table.string('content');
      table.timestamps(false, true);
    })
      .createTable('comment', (table) => {
        table.increments();
        table.integer('post_id').unsigned().references('id').inTable('post').onDelete('CASCADE');
        table.string('content');
        table.timestamps(false, true);
      })
  ]);
};

exports.down = function(knex, Promise) {
  return Promise.all([
    knex.schema.dropTable('post'),
    knex.schema.dropTable('comment'),
  ]);
};


text:
SRC = src
BUILD = build

build: test build-directory js

install:
	elm-package install -y
	pushd tests && elm-package install -y && popd

build-directory:
	mkdir -p $(BUILD)

js:
	elm-make src/Ntriples/Filter.elm --output $(BUILD)/filter.js

test:
	cd tests && elm-test Main.elm

doc:
	elm-make --docs=documentation.json


text:
package com.liulishuo.filedownloader;

/**
 * The handler for handing the case of the connect with the downloader service is lost when tasks is
 * running.
 */

public interface ILostServiceConnectedHandler {

    /**
     * @return Whether in the waiting list, what is waiting for the downloader service reconnected,
     * and when it reconnected, all tasks in the waiting list will be started.
     */
    boolean isInWaitingList(BaseDownloadTask.IRunningTask task);

    /**
     * @param task is works well, so it will be removed from the waiting list.
     */
    void taskWorkFine(BaseDownloadTask.IRunningTask task);

    /**
     * @return {@code true} if the start action was dispatched.
     */
    boolean dispatchTaskStart(BaseDownloadTask.IRunningTask task);
}


text:
import {ConnectionBackend, Connection} from '../interfaces';
import {ReadyStates, RequestMethods, ResponseTypes} from '../enums';
import {Request} from '../static_request';
import {Response} from '../static_response';
import {ResponseOptions, BaseResponseOptions} from '../base_response_options';
import {Injectable} from 'angular2/di';
import {BrowserXhr} from './browser_xhr';
import {EventEmitter, ObservableWrapper} from 'angular2/src/core/facade/async';
import {isPresent} from 'angular2/src/core/facade/lang';

/**
 * Creates connections using `XMLHttpRequest`. Given a fully-qualified
 * request, an `XHRConnection` will immediately create an `XMLHttpRequest` object and send the
 * request.
 *
 * This class would typically not be created or interacted with directly inside applications, though
 * the {@link MockConnection} may be interacted with in tests.
 */
export class XHRConnection implements Connection {
  request: Request;
  /**
   * Response {@link EventEmitter} which emits a single {@link Response} value on load event of
   * `XMLHttpRequest`.
   */
  response: EventEmitter;  // TODO: Make generic of <Response>;
  readyState: ReadyStates;
  private _xhr;  // TODO: make type XMLHttpRequest, pending resolution of
                 // https://github.com/angular/ts2dart/issues/230
  constructor(req: Request, browserXHR: BrowserXhr, baseResponseOptions?: ResponseOptions) {
    this.request = req;
    this.response = new EventEmitter();
    this._xhr = browserXHR.build();
    // TODO(jeffbcross): implement error listening/propagation
    this._xhr.open(RequestMethods[req.method].toUpperCase(), req.url);
    this._xhr.addEventListener('load', (_) => {
      // responseText is the old-school way of retrieving response (supported by IE8 & 9)
      // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
      let response = isPresent(this._xhr.response) ? this._xhr.response : this._xhr.responseText;

      // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
      let status = this._xhr.status === 1223 ? 204 : this._xhr.status;

      // fix status code when it is 0 (0 status is undocumented).
      // Occurs when accessing file resources or on Android 4.1 stock browser
      // while retrieving files from application cache.
      if (status === 0) {
        status = response ? 200 : 0;
      }

      var responseOptions = new ResponseOptions({body: response, status: status});
      if (isPresent(baseResponseOptions)) {
        responseOptions = baseResponseOptions.merge(responseOptions);
      }

      ObservableWrapper.callNext(this.response, new Response(responseOptions));
      // TODO(gdi2290): defer complete if array buffer until done
      ObservableWrapper.callReturn(this.response);
    });

    this._xhr.addEventListener('error', (err) => {
      var responseOptions = new ResponseOptions({body: err, type: ResponseTypes.Error});
      if (isPresent(baseResponseOptions)) {
        responseOptions = baseResponseOptions.merge(responseOptions);
      }
      ObservableWrapper.callThrow(this.response, new Response(responseOptions));
    });
    // TODO(jeffbcross): make this more dynamic based on body type

    if (isPresent(req.headers)) {
      req.headers.forEach((value, name) => { this._xhr.setRequestHeader(name, value); });
    }

    this._xhr.send(this.request.text());
  }

  /**
   * Calls abort on the underlying XMLHttpRequest.
   */
  dispose(): void { this._xhr.abort(); }
}

/**
 * Creates {@link XHRConnection} instances.
 *
 * This class would typically not be used by end users, but could be
 * overridden if a different backend implementation should be used,
 * such as in a node backend.
 *
 * #Example
 *
 * ```
 * import {Http, MyNodeBackend, HTTP_BINDINGS, BaseRequestOptions} from 'angular2/http';
 * @Component({
 *   viewBindings: [
 *     HTTP_BINDINGS,
 *     bind(Http).toFactory((backend, options) => {
 *       return new Http(backend, options);
 *     }, [MyNodeBackend, BaseRequestOptions])]
 * })
 * class MyComponent {
 *   constructor(http:Http) {
 *     http('people.json').subscribe(res => this.people = res.json());
 *   }
 * }
 * ```
 *
 **/
@Injectable()
export class XHRBackend implements ConnectionBackend {
  constructor(private _browserXHR: BrowserXhr, private _baseResponseOptions: ResponseOptions) {}
  createConnection(request: Request): XHRConnection {
    return new XHRConnection(request, this._browserXHR, this._baseResponseOptions);
  }
}


text:
package com.google.template.soy.types;

import static com.google.common.truth.Truth.assertThat;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.template.soy.SoyFileSetParserBuilder;
import com.google.template.soy.data.SoyValue;
import com.google.template.soy.soytree.TemplateNode;
import com.google.template.soy.types.aggregate.ListType;
import com.google.template.soy.types.aggregate.MapType;
import com.google.template.soy.types.aggregate.RecordType;
import com.google.template.soy.types.aggregate.UnionType;
import com.google.template.soy.types.primitive.AnyType;
import com.google.template.soy.types.primitive.BoolType;
import com.google.template.soy.types.primitive.FloatType;
import com.google.template.soy.types.primitive.IntType;
import com.google.template.soy.types.primitive.StringType;
import com.google.template.soy.types.primitive.UnknownType;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Unit tests for the type parser. */
@RunWith(JUnit4.class)
public class TypeParserTest {

  private static final SoyType FOO_BAR_TYPE =
      new SoyType() {
        @Override
        public Kind getKind() {
          return null;
        }

        @Override
        public boolean isAssignableFrom(SoyType srcType) {
          return false;
        }

        @Override
        public boolean isInstance(SoyValue value) {
          return false;
        }
      };

  private static final SoyTypeProvider TYPE_PROVIDER =
      new SoyTypeProvider() {
        @Override
        public SoyType getType(String typeName, SoyTypeRegistry typeRegistry) {
          if (typeName.equals("foo.bar")) {
            return FOO_BAR_TYPE;
          }
          return null;
        }
      };

  private SoyTypeRegistry typeRegistry;

  @Before
  public void setUp() throws Exception {
    typeRegistry = new SoyTypeRegistry(ImmutableSet.of(TYPE_PROVIDER));
  }

  @Test
  public void testParseTypeNames() {
    assertTypeEquals(AnyType.getInstance(), "any");
    assertTypeEquals(AnyType.getInstance(), " any ");
    assertTypeEquals(IntType.getInstance(), "int");
    assertTypeEquals(BoolType.getInstance(), "bool");
    assertTypeEquals(FOO_BAR_TYPE, "foo.bar");
    assertTypeEquals(FOO_BAR_TYPE, " foo.bar ");
    assertTypeEquals(FOO_BAR_TYPE, " foo . bar ");
    assertTypeEquals(UnknownType.getInstance(), "?");
  }

  @Test
  public void testParseUnionTypes() {
    assertTypeEquals(UnionType.of(IntType.getInstance(), BoolType.getInstance()), "int|bool");
    assertTypeEquals(
        UnionType.of(IntType.getInstance(), BoolType.getInstance(), StringType.getInstance()),
        "int|bool|string");
    assertTypeEquals(UnionType.of(IntType.getInstance(), BoolType.getInstance()), " int | bool ");
  }

  @Test
  public void testParseRecordTypes() {
    assertTypeEquals(RecordType.of(ImmutableMap.of("a", IntType.getInstance())), "[a:int]");
    assertTypeEquals(RecordType.of(ImmutableMap.of("a", IntType.getInstance())), "[a:int]");
    assertTypeEquals(
        RecordType.of(ImmutableMap.of("a", IntType.getInstance(), "b", FloatType.getInstance())),
        "[a:int, b:float]");
    assertTypeEquals(
        RecordType.of(
            ImmutableMap.of(
                "a", IntType.getInstance(), "b", ListType.of(StringType.getInstance()))),
        "[a:int, b:list<string>]");
  }

  @Test
  public void testParameterizedTypes() {
    assertTypeEquals(ListType.of(StringType.getInstance()), "list<string>");
    assertTypeEquals(ListType.of(StringType.getInstance()), "list < string > ");
    assertTypeEquals(MapType.of(IntType.getInstance(), BoolType.getInstance()), "map<int, bool>");
  }

  // -----------------------------------------------------------------------------------------------
  // Helpers.

  private void assertTypeEquals(SoyType expected, String typeInput) {
    assertThat(parseType(typeInput)).isEqualTo(expected);
  }

  private SoyType parseType(String input) {
    TemplateNode template =
        SoyFileSetParserBuilder.forTemplateContents("{@param p : " + input + "}\n{$p ? 't' : 'f'}")
            .typeRegistry(typeRegistry)
            .parse()
            .fileSet()
            .getChild(0)
            .getChild(0);
    return Iterables.getOnlyElement(template.getAllParams()).type();
  }
}


text:
pychromecast [![Build Status](https://travis-ci.org/balloob/pychromecast.svg?branch=master)](https://travis-ci.org/balloob/pychromecast)
============

Library for Python 2 and 3 to communicate with the Google Chromecast. It currently supports:
 - Auto discovering connected Chromecasts on the network
 - Start the default media receiver and play any online media
 - Control playback of current playing media
 - Implement Google Chromecast api v2
 - Communicate with apps via channels
 - Easily extendable to add support for unsupported namespaces

*PyChromecast 0.6 introduces some backward incompatible changes due to the migration from DIAL to socket for retrieving the app status.*

Dependencies
------------
PyChromecast depends on the Python packages requests, protobuf and zeroconf. Make sure you have these dependencies installed using `pip install -r requirements.txt`

_Some users running Python 2.7 have [reported](https://github.com/balloob/pychromecast/issues/47#issuecomment-107822162) that they had to upgrade their version of pip using `pip install --upgrade pip` before they were able to install the latest version of the dependencies._

How to use
----------

    >> from __future__ import print_function
    >> import time
    >> import pychromecast

    >> pychromecast.get_chromecasts_as_dict().keys()
    ['Dev', 'Living Room', 'Den', 'Bedroom']

    >> cast = pychromecast.get_chromecast(friendly_name="Living Room")
    >> print(cast.device)
    DeviceStatus(friendly_name='Living Room', model_name='Eureka Dongle', manufacturer='Google Inc.', api_version=(1, 0))

    >> print(cast.status)
    CastStatus(is_active_input=True, is_stand_by=False, volume_level=1.0, volume_muted=False, app_id=u'CC1AD845', display_name=u'Default Media Receiver', namespaces=[u'urn:x-cast:com.google.cast.player.message', u'urn:x-cast:com.google.cast.media'], session_id=u'CCA39713-9A4F-34A6-A8BF-5D97BE7ECA5C', transport_id=u'web-9', status_text='')

    >> mc = cast.media_controller
    >> print(mc.status)
    MediaStatus(current_time=42.458322, content_id=u'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4', content_type=u'video/mp4', duration=596.474195, stream_type=u'BUFFERED', idle_reason=None, media_session_id=1, playback_rate=1, player_state=u'PLAYING', supported_media_commands=15, volume_level=1, volume_muted=False)

    >> mc.pause()
    >> time.sleep(5)
    >> mc.play()
    >> from pychromecast.controllers.youtube import YouTubeController
    >> yt = YouTubeController()
    >> cast.register_handler(yt)
    >> yt.play_video("L0MK7qz13bU")

Adding support for extra namespaces
-----------------------------------
Each app that runs on the Chromecast supports namespaces. They specify a JSON-based mini-protocol. This is used to communicate between the Chromecast and your phone/browser and now Python.

Support for extra namespaces is added by using controllers. To add your own namespace to a current chromecast instance you will first have to define your controller. Example of a minimal controller:

    from pychromecast.controllers import BaseController

    class MyController(BaseController):
        def __init__(self):
            super(MediaController, self).__init__(
                "urn:x-cast:my.super.awesome.namespace")

        def receive_message(self, message, data):
            print("Wow, I received this message: {}".format(data))

            return True # indicate you handled this message

        def request_beer(self):
            self.send_message({'request': 'beer'})

After you have defined your controller you will have to add an instance to a Chromecast object: `cast.register_handler(MyController())`. When a message is received with your namespace it will be routed to your controller.

For more options see the [BaseController](https://github.com/balloob/pychromecast/blob/master/pychromecast/controllers/__init__.py). For an example of a fully implemented controller see the [MediaController](https://github.com/balloob/pychromecast/blob/master/pychromecast/controllers/media.py).

Exploring existing namespaces
-------------------------------
So you've got PyChromecast running and decided it is time to add support to your favorite app. No worries, the following instructions will have you covered in exploring the possibilities.

The following instructions require the use of the [Google Chrome browser](https://www.google.com/chrome/) and the [Google Cast plugin](https://chrome.google.com/webstore/detail/google-cast/boadgeojelhgndaghljhdicfkmllpafd).

 * In Chrome, go to `chrome://net-internals/#capture`
 * Enable the checkbox 'Include the actual bytes sent/received.'
 * Open a new tab, browse to your favorite application on the web that has Chromecast support and start casting.
 * Go back to the tab that is capturing events and click on stop.
 * From the dropdown click on events. This will show you a table with events that happened while you were recording.
 * In the filter box enter the text `Tr@n$p0rt`. This should give one SOCKET connection as result: the connection with your Chromecast.
 * Go through the results and collect the JSON that is exchanged.
 * Now write a controller that is able to mimic this behavior :-)

Ignoring CEC Data
-----------------
The Chromecast typically reports whether it is the active input on the device
to which it is connected. This value is stored inside a cast object in the
following property.

    cast.status.is_active_input

Some Chromecast users have reported CEC incompatibilities with their media
center devices. These incompatibilities may sometimes cause this active input
value to be reported improperly.

This active input value is typically used to determine if the Chromecast is
idle. PyChromecast is capable of ignoring the active input value when
determining if the Chromecast is idle in the instance that the Chromecast is
returning erroneous values. To ignore this CEC detection data in PyChromecast,
append a [Linux style wildcard](http://tldp.org/LDP/GNU-Linux-Tools-Summary/html/x11655.htm)
formatted string to the IGNORE_CEC list in PyChromecast like in the example
below.

    pychromecast.IGNORE_CEC.append('*')  # Ignore CEC on all devices
    pychromecast.IGNORE_CEC.append('Living Room')  # Ignore CEC on Chromecasts named Living Room

Thanks
------
I would like to thank [Fred Clift](https://github.com/minektur) for laying the socket client ground work. Without him it would not have been possible!


text:
layout: category
title: News
category: news
---


text:
using System;
using System.Security;
using Engine.Model.Client;
using Engine.Model.Common.Entities;
using ThirtyNineEighty.BinarySerializer;

namespace Engine.Api.Client.Messages
{
  [SecurityCritical]
  class ClientOutSystemMessageCommand :
    ClientCommand<ClientOutSystemMessageCommand.MessageContent>
  {
    public const long CommandId = (long)ClientCommandId.OutSystemMessage;

    public override long Id
    {
      [SecuritySafeCritical]
      get { return CommandId; }
    }

    [SecuritySafeCritical]
    protected override void OnRun(MessageContent content, CommandArgs args)
    {
      if (content.Message == SystemMessageId.None)
        throw new ArgumentException("content.Message");

      ClientModel.Notifier.ReceiveMessage(new ReceiveMessageEventArgs
      {
        SystemMessage = content.Message,
        SystemMessageFormat = content.FormatParams,
        Time = DateTime.UtcNow,
        Type = MessageType.System
      });
    }

    [Serializable]
    [BinType("ClientOutSystemMessage")]
    public class MessageContent
    {
      [BinField("m")]
      public SystemMessageId Message;

      [BinField("p")]
      public string[] FormatParams;
    }
  }
}


text:
package com.github.nrudenko.orm.commons;

public enum DbType {
	INT("INTEGER DEFAULT 0"),
	INT_DEF("INTEGER DEFAULT -1"),
	REAL("REAL"),
	TEXT("TEXT"),
	NUMERIC("NUMERIC"),
	TEXT_NOT_NULL("TEXT NOT NULL"),
    TEXT_DEFAULT_EMPTY("TEXT DEFAULT \"\""),
    BLOB("BLOB"),
    SERIALIZED("BLOB"),
    NO_TYPE(""); // just for default annotation value

	private String sqlRepresentation;

	DbType(String value) {
		this.sqlRepresentation = value;
	}

	public String getSqlRep() {
		return sqlRepresentation;
	}
}


text:
#
# This module detects if globus-gsi-cert-utils is installed and determines where the
# include files and libraries are.
#
# This code sets the following variables:
#
# GLOBUS_GSI_CERT_UTILS_LIBRARIES       = full path to the globus-gsi-cert-utils libraries
# GLOBUS_GSI_CERT_UTILS_INCLUDE_DIR     = include dir to be used when using the globus-gsi-cert-utils library
# GLOBUS_GSI_CERT_UTILS_FOUND           = set to true if globus-gsi-cert-utils was found successfully
#
# GLOBUS_GSI_CERT_UTILS_LOCATION
#   setting this enables search for globus-gsi-cert-utils libraries / headers in this location

find_package (PkgConfig)
pkg_check_modules(GLOBUS_GSI_CERT_UTILS_PKG globus-gsi-cert-utils)

if (GLOBUS_GSI_CERT_UTILS_PKG_FOUND)
    set (GLOBUS_GSI_CERT_UTILS_LIBRARIES ${GLOBUS_GSI_CERT_UTILS_PKG_LIBRARIES})
    set (GLOBUS_GSI_CERT_UTILS_INCLUDE_DIRS ${GLOBUS_GSI_CERT_UTILS_PKG_INCLUDE_DIRS})
    set (GLOBUS_GSI_CERT_UTILS_DEFINITIONS "${GLOBUS_GSI_CERT_UTILS_PKG_CFLAGS}")
else (GLOBUS_GSI_CERT_UTILS_PKG_FOUND)

    set (CMAKE_FIND_FRAMEWORK NEVER)

    find_library(GLOBUS_GSI_CERT_UTILS_LIBRARIES
        NAMES globus_gsi_cert_utils
        HINTS ${GLOBUS_GSI_CERT_UTILS_LOCATION}
              ${CMAKE_INSTALL_PREFIX}/globus/*/${PLATFORM}/
              ${CMAKE_INSTALL_PREFIX}/Grid/epel/*/${PLATFORM}/lib
              ${CMAKE_INSTALL_PREFIX}/Grid/epel/*/${PLATFORM}/lib64
              ${CMAKE_INSTALL_PREFIX}/opt/globus-toolkit/libexec/lib
              ${GLOBUS_PREFIX}/libexec/lib
        DOC "The main globus-gsi-cert-utils library"
    )

    find_path(GLOBUS_GSI_CERT_UTILS_INCLUDE_DIRS
        NAMES globus_gsi_cert_utils.h
        HINTS ${GLOBUS_GSI_CERT_UTILS_LOCATION}/include/*
              ${CMAKE_INSTALL_PREFIX}/globus/*/${PLATFORM}/include
              ${CMAKE_INSTALL_PREFIX}/Grid/epel/*/${PLATFORM}/include
              ${CMAKE_INSTALL_PREFIX}/opt/globus-toolkit/libexec/include
              ${GLOBUS_PREFIX}/libexec/include
        DOC "The globus-gsi-cert-utils include directory"
    )

    set (GLOBUS_GSI_CERT_UTILS_DEFINITIONS "")
endif (GLOBUS_GSI_CERT_UTILS_PKG_FOUND)

if (GLOBUS_GSI_CERT_UTILS_LIBRARIES)
    message (STATUS "GLOBUS_GSI_CERT_UTILS libraries: ${GLOBUS_GSI_CERT_UTILS_LIBRARIES}")
endif (GLOBUS_GSI_CERT_UTILS_LIBRARIES)
if (GLOBUS_GSI_CERT_UTILS_INCLUDE_DIRS)
    message (STATUS "GLOBUS_GSI_CERT_UTILS include dir: ${GLOBUS_GSI_CERT_UTILS_INCLUDE_DIRS}")
endif (GLOBUS_GSI_CERT_UTILS_INCLUDE_DIRS)

# -----------------------------------------------------
# handle the QUIETLY and REQUIRED arguments and set GLOBUS_GSI_CERT_UTILS_FOUND to TRUE if
# all listed variables are TRUE
# -----------------------------------------------------
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args (GLOBUS_GSI_CERT_UTILS DEFAULT_MSG
    GLOBUS_GSI_CERT_UTILS_LIBRARIES  GLOBUS_GSI_CERT_UTILS_INCLUDE_DIRS
)
mark_as_advanced(GLOBUS_GSI_CERT_UTILS_INCLUDE_DIRS GLOBUS_GSI_CERT_UTILS_LIBRARIES)


text:
from swagger.data_type import DataType, Items, PRIMITIVES
from swagger.exceptions import SwaggerFieldError, SwaggerTypeError

from nose.tools import raises, assert_equals, assert_is_instance

class TestItems(object):
    @raises(SwaggerFieldError)
    def test_no_ref_no_type(self):
        Items({})

    def test_valid_primitives(self):
        for t, type_props in PRIMITIVES.iteritems():
            items = Items({'type': t})
            assert_equals(items.type, t)
            for f in type_props['formats']:
                items = Items({'type': t, 'format': f})
                assert_equals(items.type, t)
                assert_equals(items.format, f)

    def test_ref(self):
        dt = Items({'$ref': 'MyModel'})
        assert_equals(getattr(dt, '$ref'), 'MyModel')

    @raises(SwaggerTypeError)
    def test_invalid_type(self):
        Items({'type': 'array'})

class TestDataType(object):

    @raises(SwaggerFieldError)
    def test_no_ref_no_type(self):
        DataType({}, {}, {})

    def test_valid_primitives(self):
        for t, type_props in PRIMITIVES.iteritems():
            dt = DataType({'type': t}, {}, {})
            assert_equals(dt.type, t)
            for f in type_props['formats']:
                dtf = DataType({'type': t, 'format': f}, {}, {})
                assert_equals(dtf.type, t)
                assert_equals(dtf.format, f)

    @raises(SwaggerTypeError)
    def test_invalid_primitive(self):
        dt = DataType({'type': 'string', 'format': 'blue'}, {}, {})

    def test_ref(self):
        dt = DataType({'$ref': 'MyModel'}, {}, {})
        assert_equals(getattr(dt, '$ref'), 'MyModel')

    @raises(SwaggerTypeError)
    def test_invalid_default_enum(self):
        DataType({'type': 'string', 'enum': ['blue', 'green'], 'defaultValue': 'orange'}, {}, {})

    @raises(SwaggerFieldError)
    def test_invalid_type_enum(self):
        DataType({'type': 'integer', 'enum': [1, 2]}, {}, {})

    def test_enum(self):
        dt = DataType({'type': 'string', 'enum': ['blue', 'green']}, {}, {})
        assert_equals(dt.type, 'string')
        assert_equals(dt.enum, ['blue', 'green'])

    @raises(SwaggerTypeError)
    def test_invalid_default(self):
        DataType({'type': 'string', 'defaultValue': 3}, {}, {})

    def test_default_values(self):
        dv_tests = {'integer': 9, 'number': 3.5, 'string': 'blue', 'boolean': True}
        for t, dv in dv_tests.iteritems():
            dt = DataType({'type': t, 'defaultValue': dv}, {}, {})
            assert_equals(dt.type, t)
            assert_equals(dt.defaultValue, dv)

    def test_min_max_with_default(self):
        dv_tests = {'integer': {'max': '10', 'min': '5', 'default': 7},
                    'number': {'max': '30.5', 'min': '10.2', 'default': 20.5}}
        for t, values in dv_tests.iteritems():
            dt = DataType({'type': t, 'minimum': values['min'],
                           'maximum': values['max'],
                           'defaultValue': values['default']}, {}, {})

    @raises(SwaggerTypeError)
    def test_invalid_default_min_int(self):
        DataType({'type': 'integer', 'minimum': '5', 'defaultValue': 4}, {}, {})

    @raises(SwaggerTypeError)
    def test_invalid_default_max_int(self):
        DataType({'type': 'integer', 'maximum': '5', 'defaultValue': 6}, {}, {})

    @raises(SwaggerTypeError)
    def test_invalid_default_min_num(self):
        DataType({'type': 'number', 'minimum': '5.5', 'defaultValue': 5.3}, {}, {})

    @raises(SwaggerTypeError)
    def test_invalid_default_max_num(self):
        DataType({'type': 'number', 'maximum': '5.5', 'defaultValue': 5.7}, {}, {})

    @raises(SwaggerFieldError)
    def test_array_no_items(self):
        DataType({'type': 'array'}, {}, {})

    def test_array(self):
        dt = DataType({'type': 'array', 'items': {'type': 'string'}}, {}, {})
        assert_equals(dt.type, 'array')
        assert_is_instance(dt.items, Items)

        dt = DataType({'type': 'array', 'items': {'type': 'string'}, 'uniqueItems': True}, {}, {})
        assert_is_instance(dt.uniqueItems, bool)
        assert_equals(dt.uniqueItems, True)


text:
In order to follow along with the examples in this book, the following needs to be installed on your
system:

## kpt

[Install the kpt CLI][install] and ensure you are running **version 1.0 or later**:

```shell
$ kpt version
```

## Git

kpt requires that you have [Git] installed and configured.

## Container Runtime

`kpt` requires you to have at least one of the following runtimes installed and configured.

### Docker

Please follow the [instructions][install-docker] to install and configure Docker.

### Podman

Please follow the [instructions][install-podman] to install and configure Podman.

If you want to set up rootless container runtime, [this][rootless] may be a
useful resource for you.

Environment variable can be used to control which container runtime to use. More
details can be found in the reference documents for [`kpt fn render`](/reference/cli/fn/render/)
and [`kpt fn eval`](/reference/cli/fn/eval/).

## Kubernetes cluster

In order to deploy the examples, you need a Kubernetes cluster and a configured kubeconfig context.

For testing purposes, [kind] tool is useful for running ephemeral Kubernetes cluster on your local host.

[install]: /installation/
[install-docker]: https://docs.docker.com/get-docker/
[install-podman]: https://podman.io/getting-started/installation
[rootless]: https://rootlesscontaine.rs/
[git]: https://git-scm.com/book/en/v2/Getting-Started-Installing-Git
[kind]: https://kind.sigs.k8s.io/docs/user/quick-start/


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="rustdoc">
    <meta name="description" content="API documentation for the Rust `align_of_val` fn in crate `std`.">
    <meta name="keywords" content="rust, rustlang, rust-lang, align_of_val">

    <title>std::mem::align_of_val - Rust</title>

    <link rel="stylesheet" type="text/css" href="../../main.css">

    <link rel="shortcut icon" href="http://www.rust-lang.org/favicon.ico">

std::<wbr>mem

        <form class="search-form js-only">

                <input class="search-input" name="search"
                       autocomplete="off"
                       placeholder="Click or press 'S' to search, '?' for more options..."
                       type="search">

        </form>

Function std::<wbr>mem::<wbr>align_of_val<wbr>Stable
            [-] [+]
        [src]

pub fn align_of_val<T>(_val: &T) -> usize

Returns the alignment of the type of the value that _val points to.

This is similar to align_of, but function will properly handle types such as trait objects
(in the future), returning the alignment for an arbitrary value at runtime.

Examples
fn main() {
    use std::mem;

    assert_eq!(4, mem::align_of_val(&5i32));
}

use std::mem;

assert_eq!(4, mem::align_of_val(&5i32));

Keyboard shortcuts

?

Show this help dialog

S

Focus the search field

⇤

Move up in search results

⇥

Move down in search results

⏎

Go to active search result

Search tricks

                Prefix searches with a type followed by a colon (e.g.
                fn:) to restrict the search to a given type.

                Accepted types are: fn, mod,
                struct, enum,
                trait, typedef (or
                tdef).