text:
layout: post
title: Audax Floripa 2014. Mais 200km para o currículo.
lang: pt
tags: [ciclismo]
---
Meu objetivo este ano era completar apenas os 200km do [Audax Joinville](/2014/04/02/audax-joinville-200km-agora-foi/), mas gostei tanto da brincadeira que resolvi fazer também os 200km de Florianópolis. Nunca havia feito a volta na ilha de Floripa e esta era uma excelente oportunidade para pedalar com a turma, completar mais um brevet e ainda fazer este fantástico passeio pela ilha da magia.

Saimos de Joinville ainda no sábado pela manhã com a Van do Vitório e seguimos direto à ilha para retirada do kit, almoço e check-in no Hotel.

![](/public/images/2014/05/audax-floripa-1.jpg)

O período da tarde passou muito rápido, pois almoçamos tarde e ainda fizemos um passeio pelo shopping para comprar suprimentos para o pedal. Quando chegamos no hotel para descansar já estava quase na hora de sair para o congresso.

Fomos ao congresso técnico e aproveitamos para encher o estômago de massa em um rodízio de pizza. Mal consegui dormir a noite, parte disto por conta da ansiedade e também da quantidade de pizza que comi. Mesmo com sono, acordei às 3:30 e me arrumei rapidamente. Segui as dicas do Marcio e desci a bicicleta o mais cedo possível para evitar filas no elavador. A dica foi muito valiosa, pois alguns minutos depois já era possível notar o congestionamento de bicicletas descendo pelo elevador. Foi uma cena bastante incomum ver aquela quantidade de bicicletas no Hall do Hotel. Tive que registrar isto.

![](/public/images/2014/05/audax-floripa-2.jpg)

![](/public/images/2014/05/audax-floripa-3.jpg)

Saímos do hotel às 05:00 após tomar um delicioso e reforçado café da manhã. Apesar de fazer frio, o clima estava muito bom para pedalar. Nos juntamos aos mais de 700 ciclistas e, como é de costume, a largada foi bastante pontual, com um atraso mínimo de 5 minutos.

Foi a primeira vez que pedalei na beira-mar e posso dizer que deu um gostinho de quero mais. As fotos ficaram ruins, mas posso garantir que o visual é de tirar o fôlego, ainda mais de bike, onde fica mais fácil captar cada detalhe.

![](/public/images/2014/05/audax-floripa-5.jpg)

Formamos um pelotão de 5 pessoas, sendo 4 de Joinville  (Eu, Marcio, Tamires e Paulo) e uma de Florianópolis (Daniela) – que se juntou ao grupo durante o percurso. O Limas havia comentado que os **que mais aproveitam o Audax são os que chegam por último**, este sim curtem cada minuto do passeio. Levamos a dica a sério e resolvemos não afundar o pé e sim curtir o visual e a companhia dos amigos.

Não tivemos nenhum imprevisto com pneu furado ou problemas mecânicos. Fiquei surpreso, pois em um grupo deste tamanho é bem comum aparecer um furo aqui ou ali. Será que estavam todos com fita? Este negócio funciona mesmo!

![](/public/images/2014/05/audax-floripa-6.jpg)

![](/public/images/2014/05/audax-floripa-7.jpg)

Terminei a prova muito mais exausto e dolorido do que na edição de Joinville, mesmo não tendo uma serra para subir, haviam diversos trechos de sobe e desce, sem contar o vento contra que pegamos em alguns trechos. Tive dores no joelho pela primeira vez durante um pedal, o que me deixou bastante preocupado, já que tenho um histórico de problemas neste local. Mas como estávamos no final a empolgação tomou conta e a dor foi ficando em segundo plano.

Seguimos em um ritmo mais lento devido ao cansaço e terminamos a prova em **12h30m**, 1 hora a mais do que o meu tempo no Audax Joinville.

Se valeu a pena? É lógico. Olha este visual que nos acompanhou nos últimos km.

![](/public/images/2014/05/audax-floripa-8.jpg)


text:
<?php

if (isset( $_POST["submit"]))
{
	login();
}

function login()
{
	session_start();
	include("connect.php");
	// Taking in the login details
	$username = (isset($_POST['username']) ? $_POST['username'] : null);
	$password = (isset($_POST['password']) ? $_POST['password'] : null);
	$query = mysql_query("SELECT * FROM user WHERE username = '$username' AND password = '$password'") or die("sql query failed");

	// Need to check $result before passing it to row
	if (false === $query)
	{
	   echo mysql_error();
	   exit();
	}

	$row = mysql_fetch_array($query);

	if($row["username"]==$username && $row["password"]==$password)
	{
		$_SESSION["username"] = $username;
		$_SESSION["logged"] = true;
		header("Location: search.php");
	   exit();
	}
	else
	{
	    header("Location: http://localhost/paul/assignment/login.php");
	    exit();
	}
	mysql_close($connect);
}

?>

redpajama_set_name: RedPajamaGithub


text:
#ifndef EXECDEBUG_H
#define EXECDEBUG_H

#include "executor/executor.h"
#include "nodes/print.h"

/* ----------------------------------------------------------------
 *		debugging defines.
 *
 *		If you want certain debugging behaviour, then #define
 *		the variable to 1. No need to explicitly #undef by default,
 *		since we can use -D compiler options to enable features.
 *		- thomas 1999-02-20
 * ----------------------------------------------------------------
 */

/* ----------------
 *		EXEC_NESTLOOPDEBUG is a flag which turns on debugging of the
 *		nest loop node by NL_printf() and ENL_printf() in nodeNestloop.c
 * ----------------
#undef EXEC_NESTLOOPDEBUG
 */

/* ----------------
 *		EXEC_EVALDEBUG is a flag which turns on debugging of
 *		ExecEval and ExecTargetList() stuff by EV_printf() in execQual.c
 * ----------------
#undef EXEC_EVALDEBUG
 */

/* ----------------
 *		EXEC_SORTDEBUG is a flag which turns on debugging of
 *		the ExecSort() stuff by SO_printf() in nodeSort.c
 * ----------------
#undef EXEC_SORTDEBUG
 */

/* ----------------
 *		EXEC_MERGEJOINDEBUG is a flag which turns on debugging of
 *		the ExecMergeJoin() stuff by MJ_printf() in nodeMergejoin.c
 * ----------------
#undef EXEC_MERGEJOINDEBUG
 */

/* ----------------------------------------------------------------
 *		#defines controlled by above definitions
 *
 *		Note: most of these are "incomplete" because I didn't
 *			  need the ones not defined.  More should be added
 *			  only as necessary -cim 10/26/89
 * ----------------------------------------------------------------
 */
#define T_OR_F(b)				((b) ? "true" : "false")
#define NULL_OR_TUPLE(slot)		(TupIsNull(slot) ? "null" : "a tuple")

/* ----------------
 *		nest loop debugging defines
 * ----------------
 */
#ifdef EXEC_NESTLOOPDEBUG
#define NL_nodeDisplay(l)				nodeDisplay(l)
#define NL_printf(s)					printf(s)
#define NL1_printf(s, a)				printf(s, a)
#define ENL1_printf(message)			printf("ExecNestLoop: %s\n", message)
#else
#define NL_nodeDisplay(l)
#define NL_printf(s)
#define NL1_printf(s, a)
#define ENL1_printf(message)
#endif   /* EXEC_NESTLOOPDEBUG */

/* ----------------
 *		exec eval / target list debugging defines
 * ----------------
 */
#ifdef EXEC_EVALDEBUG
#define EV_nodeDisplay(l)				nodeDisplay(l)
#define EV_printf(s)					printf(s)
#define EV1_printf(s, a)				printf(s, a)
#else
#define EV_nodeDisplay(l)
#define EV_printf(s)
#define EV1_printf(s, a)
#endif   /* EXEC_EVALDEBUG */

/* ----------------
 *		sort node debugging defines
 * ----------------
 */
#ifdef EXEC_SORTDEBUG
#define SO_nodeDisplay(l)				nodeDisplay(l)
#define SO_printf(s)					printf(s)
#define SO1_printf(s, p)				printf(s, p)
#else
#define SO_nodeDisplay(l)
#define SO_printf(s)
#define SO1_printf(s, p)
#endif   /* EXEC_SORTDEBUG */

/* ----------------
 *		merge join debugging defines
 * ----------------
 */
#ifdef EXEC_MERGEJOINDEBUG

#define MJ_nodeDisplay(l)				nodeDisplay(l)
#define MJ_printf(s)					printf(s)
#define MJ1_printf(s, p)				printf(s, p)
#define MJ2_printf(s, p1, p2)			printf(s, p1, p2)
#define MJ_debugtup(slot)				debugtup(slot, NULL)
#define MJ_dump(state)					ExecMergeTupleDump(state)
#define MJ_DEBUG_COMPARE(res) \
  MJ1_printf("  MJCompare() returns %d\n", (res))
#define MJ_DEBUG_QUAL(clause, res) \
  MJ2_printf("  ExecQual(%s, econtext) returns %s\n", \
			 CppAsString(clause), T_OR_F(res))
#define MJ_DEBUG_PROC_NODE(slot) \
  MJ2_printf("  %s = ExecProcNode(...) returns %s\n", \
			 CppAsString(slot), NULL_OR_TUPLE(slot))
#else

#define MJ_nodeDisplay(l)
#define MJ_printf(s)
#define MJ1_printf(s, p)
#define MJ2_printf(s, p1, p2)
#define MJ_debugtup(slot)
#define MJ_dump(state)
#define MJ_DEBUG_COMPARE(res)
#define MJ_DEBUG_QUAL(clause, res)
#define MJ_DEBUG_PROC_NODE(slot)
#endif   /* EXEC_MERGEJOINDEBUG */

#endif   /* ExecDebugIncluded */


text:
* Bug fix: crashing when varname is blank

## 1.0.2 (2015-05-08)

* Bug fix: crashing when source / source ID columns missing

## 1.0.1 (2015-04-29)

* Bug fix: whitespace in list of values causing issues
* Feature: allow 'ad-hoc' lists of values (not from a standard vocabulary)

## 1.0.0 (2015-04-03)

* Production release of application


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

package com.cloudera.director.spi.v2.model;

import static com.cloudera.director.spi.v2.model.InstanceTemplate.InstanceTemplateConfigurationPropertyToken.INSTANCE_NAME_PREFIX;

import com.cloudera.director.spi.v2.model.util.SimpleConfigurationPropertyBuilder;
import com.cloudera.director.spi.v2.model.util.SimpleResourceTemplate;
import com.cloudera.director.spi.v2.util.ConfigurationPropertiesUtil;

import java.util.List;
import java.util.Map;

/**
 * Represents a template for constructing cloud instances.
 */
public class InstanceTemplate extends SimpleResourceTemplate {

  /**
   * The list of configuration properties (including inherited properties).
   */
  private static final List<ConfigurationProperty> CONFIGURATION_PROPERTIES =
      ConfigurationPropertiesUtil.merge(
          SimpleResourceTemplate.getConfigurationProperties(),
          ConfigurationPropertiesUtil.asConfigurationPropertyList(
              InstanceTemplateConfigurationPropertyToken.values())
      );

  /**
   * Returns the list of configuration properties for creating an instance template,
   * including inherited properties.
   *
   * @return the list of configuration properties for creating an instance template,
   * including inherited properties
   */
  public static List<ConfigurationProperty> getConfigurationProperties() {
    return CONFIGURATION_PROPERTIES;
  }

  /**
   * Instance template configuration property tokens.
   */
  // Fully qualifying class name due to compiler bug
  public static enum InstanceTemplateConfigurationPropertyToken
      implements com.cloudera.director.spi.v2.model.ConfigurationPropertyToken {

    /**
     * String to use as prefix for instance names.
     */
    INSTANCE_NAME_PREFIX(new SimpleConfigurationPropertyBuilder()
        .configKey("instanceNamePrefix")
        .name("Instance name prefix")
        .defaultValue("director")
        .defaultDescription("Prefix used when generating instance names in AWS"
            + " (not part of the hostname).")
        .build());

    /**
     * The configuration property.
     */
    private final ConfigurationProperty configurationProperty;

    /**
     * Creates a configuration property token with the specified parameters.
     *
     * @param configurationProperty the configuration property
     */
    private InstanceTemplateConfigurationPropertyToken(
        ConfigurationProperty configurationProperty) {
      this.configurationProperty = configurationProperty;
    }

    @Override
    public ConfigurationProperty unwrap() {
      return configurationProperty;
    }
  }

  /**
   * The instance name prefix.
   */
  private final String instanceNamePrefix;

  /**
   * Creates an instance template with the specified parameters.
   *
   * @param name                        the name of the template
   * @param configuration               the source of configuration
   * @param tags                        the map of tags to be applied to resources created from
   *                                    the template
   * @param providerLocalizationContext the parent provider localization context
   */
  public InstanceTemplate(String name, Configured configuration, Map<String, String> tags,
      LocalizationContext providerLocalizationContext) {
    super(name, configuration, tags, providerLocalizationContext);
    LocalizationContext localizationContext = getLocalizationContext();
    this.instanceNamePrefix =
        configuration.getConfigurationValue(INSTANCE_NAME_PREFIX, localizationContext);
  }

  /**
   * Returns the string to use as a prefix for instance names.
   *
   * @return the string to use as a prefix for instance names
   */
  public String getInstanceNamePrefix() {
    return instanceNamePrefix;
  }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
J-Index (Java Prettify)
</TITLE>

<META NAME="date" CONTENT="2013-04-23">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
      Use
      Tree
      Deprecated
    Index
      Help

 PREV LETTER
 NEXT LETTER

  FRAMES
 NO FRAMES

  All Classes

A B C D E F G H I J K L M N O P R S T U V

J

JAVA_KEYWORDS -
Static variable in class prettify.parser.Prettify

Job - Class in prettify.parser
This is the job object that similar to those in JavaScript Prettify.
Job() -
Constructor for class prettify.parser.Job

Constructor.

Job(int, String) -
Constructor for class prettify.parser.Job

Constructor.

join(List<String>) -
Static method in class prettify.parser.Util

Join the strings into one string.

join(List<String>, String) -
Static method in class prettify.parser.Util

Join the strings into one string with delimiter in
 between.

join(String[]) -
Static method in class prettify.parser.Util

Join the strings into one string.

join(String[], String) -
Static method in class prettify.parser.Util

Join the strings into one string with delimiter in
 between.

JSCRIPT_KEYWORDS -
Static variable in class prettify.parser.Prettify

JTextComponentRowHeader - Class in syntaxhighlight
A row header panel for JScrollPane showing the line numbers of
 JTextComponent.
JTextComponentRowHeader(JScrollPane, JTextComponent) -
Constructor for class syntaxhighlight.JTextComponentRowHeader

Constructor.

      Overview
      Package
      Class
      Use
      Tree
      Deprecated
    Index
      Help

 PREV LETTER
 NEXT LETTER

  FRAMES
 NO FRAMES

  All Classes

A B C D E F G H I J K L M N O P R S T U V


text:
class ReadMark < ActiveRecord::Base
  belongs_to :readable, :polymorphic => true

  validates_presence_of :user_id, :readable_type

  scope :global, lambda { where(:readable_id => nil) }
  scope :single, lambda { where('readable_id IS NOT NULL') }
  scope :older_than, lambda { |timestamp| where([ 'timestamp < ?', timestamp ]) }

  # Returns the class and options defined by acts_as_reader
  class_attribute :reader_class
  class_attribute :reader_options

  # Returns the classes defined by acts_as_readable
  class_attribute :readable_classes

  def self.reader_scope
    reader_options[:scope].try(:call) || reader_class
  end
end


text:
/**
 * Created by nferraro on 8/8/14.
 */

angular.module('sample-app.common')
    .directive('sfList', sfList);

var MODES = {
        NONE: "none",
        SINGLE: "single",
        MULTI: "multi"
    },
    DEFAULT_MODE = MODES.NONE;

var fs = require('fs');

function sfList() {
    return {
        restrict: 'E',
        transclude: true,
        scope: {
            items: '=',
            listener: '=?',
            mode: '@?'
        },
        link: sfListLink
    };

    function sfListLink( scope, element, attrs, controller, transcludeFn ) {
        var selectedItems = [],
            mode = MODES.NONE,
            listener;

        scope.selectItem = selectItem;
        scope.isSelected = isSelected;

        scope.$watchCollection( 'items', updateSelectedItems );
        scope.$watch( 'mode', updateSelectionMode );
        scope.$watch( 'listener', updateListener );

        transcludeFn(scope, function(clone) {
            element.append(clone);
        });

        function updateSelectedItems( value ) {
            var newSelectedItems = [];

            for ( var i = 0; i < selectedItems.length; i++ ) {
                for ( var j = 0; j < value.length; j++ ) {
                    if ( selectedItems[i].id === value[j].id ) {
                        newSelectedItems.push( selectedItems[i] );
                        break;
                    }
                }
            }

            if ( selectedItems.length !== newSelectedItems.length ) {
                selectedItems = newSelectedItems;
                notifySelectionListener();
            }

            selectedItems = newSelectedItems;
        }

        function updateSelectionMode( value ) {
            var validMode = false,
                oldMode = mode,
                newMode = value;

            // Validate new mode value
            for ( var m in MODES ) {
                if ( MODES[m] === value ) {
                    validMode = true;
                    break;
                }
            }

            // Default value if not set or is invalid
            if ( !value || !validMode ) {
                value = MODES.NONE;
            }

            // If the directive is going from multi select to single or none select
            if ( (oldMode === MODES.MULTI && newMode !== MODES.MULTI) || (oldMode === MODES.SINGLE && newMode === MODES.NONE) ) {
                // Clear selection if none select or single select with more than 1 item currently selected
                if ( (newMode === MODES.SINGLE && selectedItems.length > 1) || newMode === MODES.NONE ) {
                    clearSelection();
                }
            }

            mode = newMode;
        }

        function updateListener(value) {
            listener = value;
        }

        function selectMultiple(item) {
            for (var i = 0; i < selectedItems.length; i++) {
                // If item is already in list, deselect it
                if ( selectedItems[i].id === item.id ) {
                    selectedItems.splice(i, 1);
                    notifySelectionListener();
                    return;
                }
            }

            // If we've made it this far, it is not on the list. Add it!
            selectedItems.push(item);
            notifySelectionListener();
        }

        function selectSingle(item) {
            selectedItems = [ item ];
            notifySelectionListener();
        }

        function selectNone(item) {
            selectSingle(item);
            selectedItems = [];
        }

        function selectItem(item) {
            if (mode === MODES.MULTI) {
                selectMultiple(item);
            } else if (mode === MODES.SINGLE) {
                selectSingle(item);
            } else {
                selectNone(item);
            }
        }

        function clearSelection() {
            selectedItems = [];
            notifySelectionListener();
        }

        function isSelected(item) {
            for (var i = 0; i < selectedItems.length; i++) {
                if (item.id === selectedItems[i].id) {
                    return true;
                }
            }

            return false;
        }

        function notifySelectionListener() {
            if (listener && listener.onSelectionChanged) {
                listener.onSelectionChanged(selectedItems);
            }
        }
    }
}


text:
package com.zyh.factory.entity;

import java.math.BigDecimal;
import java.sql.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * @author Yihang
 *
 */
@Entity
@Table(name = "sourceDemand")
public class SourceDemandEntity {

    @Id
    @GeneratedValue
    private long demandId;
    @Column
    private long sourceId;
    @Column
    private String sourceName;
    @Column
    private int quantity;
    @Column
    private String sourceColor;
    @Column
    private String sourceUnit;
    @Column
    private BigDecimal totalPrice;
    @Column
    private String providerName;
    @Column
    private long workId;
    @Column
    private long orderId;
    @Column
    private String demandStatus;
    @Column
    private Date expectDeliverDate;
    @Column
    private Date actualDeliverDate;
    @Column
    private String demandRemark;
    @Column
    private String createBy;
    @Column
    private String deliveryBy;

	public long getDemandId() {
		return demandId;
	}
	public void setDemandId(long demandId) {
		this.demandId = demandId;
	}
	public long getWorkId() {
		return workId;
	}
	public void setWorkId(long workId) {
		this.workId = workId;
	}
	public long getOrderId() {
		return orderId;
	}
	public void setOrderId(long orderId) {
		this.orderId = orderId;
	}
	public String getDemandStatus() {
		return demandStatus;
	}
	public void setDemandStatus(String demandStatus) {
		this.demandStatus = demandStatus;
	}
	public Date getExpectDeliverDate() {
		return expectDeliverDate;
	}
	public void setExpectDeliverDate(Date expectDeliverDate) {
		this.expectDeliverDate = expectDeliverDate;
	}
	public Date getActualDeliverDate() {
		return actualDeliverDate;
	}
	public void setActualDeliverDate(Date actualDeliverDate) {
		this.actualDeliverDate = actualDeliverDate;
	}
	public String getDemandRemark() {
		return demandRemark;
	}
	public void setDemandRemark(String demandRemark) {
		this.demandRemark = demandRemark;
	}
	public String getCreateBy() {
		return createBy;
	}
	public void setCreateBy(String createBy) {
		this.createBy = createBy;
	}
	public String getDeliveryBy() {
		return deliveryBy;
	}
	public void setDeliveryBy(String deliveryBy) {
		this.deliveryBy = deliveryBy;
	}
	public long getSourceId() {
		return sourceId;
	}
	public void setSourceId(long sourceId) {
		this.sourceId = sourceId;
	}

	public String getSourceColor() {
		return sourceColor;
	}
	public void setSourceColor(String sourceColor) {
		this.sourceColor = sourceColor;
	}
	public int getQuantity() {
		return quantity;
	}
	public void setQuantity(int quantity) {
		this.quantity = quantity;
	}
	public String getSourceUnit() {
		return sourceUnit;
	}
	public void setSourceUnit(String sourceUnit) {
		this.sourceUnit = sourceUnit;
	}
	public BigDecimal getTotalPrice() {
		return totalPrice;
	}
	public void setTotalPrice(BigDecimal totalPrice) {
		this.totalPrice = totalPrice;
	}
	public String getProviderName() {
		return providerName;
	}
	public void setProviderName(String providerName) {
		this.providerName = providerName;
	}
	public String getSourceName() {
		return sourceName;
	}
	public void setSourceName(String sourceName) {
		this.sourceName = sourceName;
	}

}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title>Forms | React</title>
  <meta name="viewport" content="width=device-width">
  <meta property="og:title" content="Forms | React">
  <meta property="og:type" content="website">
  <meta property="og:url" content="https://facebook.github.io/react/docs/forms.html">
  <meta property="og:image" content="https://facebook.github.io/react/img/logo_og.png">
  <meta property="og:description" content="A JavaScript library for building user interfaces">
  <meta property="fb:app_id" content="623268441017527">

  <link rel="shortcut icon" href="/react/favicon.ico">
  <link rel="alternate" type="application/rss+xml" title="React" href="https://127.0.0.1/react/feed.xml">

  <link rel="stylesheet" href="https://cdn.jsdelivr.net/docsearch.js/1/docsearch.min.css" />
  <link rel="stylesheet" href="/react/css/syntax.css">
  <link rel="stylesheet" href="/react/css/codemirror.css">
  <link rel="stylesheet" href="/react/css/react.css">

  <link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet">

          React

Docs/文档

Support/支持

Download/下载

Blog/博客

            <input id="algolia-doc-search" type="text" placeholder="Search docs..." />

GitHub

React Native

Quick Start / 快速入门

            Getting Started
 快速开始

            Tutorial
 教程

            Thinking in React
 深入理解React

Community Resources - - - - 社区资源

            Conferences
 会议

            Videos
 视频

            Complementary Tools
 其余工具

            Examples
 范例

Guides / 指南

            Why React?
 为什么使用 React?

            Displaying Data
 数据呈现

                    JSX in Depth
 深入理解JSX

                    JSX Spread Attributes
 JSX的延展属性

                    JSX Gotchas / JSX的陷阱

            Interactivity and Dynamic UIs
 富交互性的动态用户界面

            Multiple Components
 复合组件

            Reusable Components
 可复用组件

            Transferring Props
 传递 Props

            Forms
 表单组件

            Working With the Browser
 浏览器中的工作原理

                    Refs to Components
 关于Refs的更多内容

            Tooling Integration
 整合工具

                    Language Tooling
 语言工具

                    Package Management
 包管理器

                    Server-side Environments
 服务器端环境

            Add-Ons
 插件

                    Animation
 动画

                    Two-Way Binding Helpers
 双向绑定

                    Test Utilities
 测试工具集

                    Cloning Elements
 克隆组件

                    Keyed Fragments
 键控片段

                    Immutability Helpers
 不变性的帮手

                    PureRenderMixin
 PureRenderMixin

                    Performance Tools
 性能分析工具

                    Shallow Compare
 浅的比较

            Advanced Performance
 高阶性能

            Context
 语境上下文

Reference / 参考

            Top-Level API
 顶层 API

            Component API
 组件 API

            Component Specs and Lifecycle
 组件的详细说明和生命周期

            Supported Tags and Attributes
 标签和属性支持

            Event System
 事件系统

            DOM Differences
 与 DOM 的差异

            Special Non-DOM Attributes
 特殊的非 DOM 属性

            Reconciliation
 和解

            Web Components
 Web组件

            React (Virtual) DOM Terminology
 React(虚拟)DOM 术语

Flux

            Flux Overview
  Flux概述

            Flux TodoMVC Tutorial
 Flux的TodoMVC教程

Tips / 技巧

            Introduction
 简介

            Inline Styles
 内部样式

            If-Else in JSX
 JSX 的 If-Else

            Self-Closing Tag
 自闭合标签

            Maximum Number of JSX Root Nodes
 JSF根节点最大数目

            Shorthand for Specifying Pixel Values in style props
 像素PX

            Type of the Children props
 子组件属性的类型

            Value of null for Controlled Input
 input控件的null值

            componentWillReceiveProps Not Triggered After Mounting
 Mounting后componentWillReceiveProps未自动触发

            Props in getInitialState Is an Anti-Pattern
 反模式:在getInitialState中使用Props

            DOM Event Listeners in a Component
 组件中的DOM事件监听

            Load Initial Data via AJAX
 使用AJAX加载初始化数据

            False in JSX
 在JSX中的False

            Communicate Between Components
 组件间的通信

            Expose Component Functions
 暴露组件功能

            this.props.children undefined
 this.props.children未定义

            Use React with Other Libraries
 其它类库

            Dangerously Set innerHTML
 设置innerHTML很危险

Contributing

            Design Principles

    Edit on GitHub

      Forms

Form components such as <input>, <textarea>, and <option> differ from other native components because they can be mutated via user interactions. These components provide interfaces that make it easier to manage forms in response to user interactions.

For information on events on <form> see Form Events.

Interactive Props #

Form components support a few props that are affected via user interactions:

value, supported by <input> and <textarea> components.

checked, supported by <input> components of type checkbox or radio.

selected, supported by <option> components.

In HTML, the value of <textarea> is set via children. In React, you should use value instead.

Form components allow listening for changes by setting a callback to the onChange prop. The onChange prop works across browsers to fire in response to user interactions when:

The value of <input> or <textarea> changes.

The checked state of <input> changes.

The selected state of <option> changes.

Like all DOM events, the onChange prop is supported on all native components and can be used to listen to bubbled change events.

Note:

For <input> and <textarea>, onChange supersedes — and should generally be used instead of — the DOM's built-in oninput event handler.

Controlled Components #

A controlled <input> has a value prop. Rendering a controlled <input> will reflect the value of the value prop.

  render: function() {
    return <input type="text" value="Hello!" />;
  }

User input will have no effect on the rendered element because React has declared the value to be Hello!. To update the value in response to user input, you could use the onChange event:

  getInitialState: function() {
    return {value: 'Hello!'};
  },
  handleChange: function(event) {
    this.setState({value: event.target.value});
  },
  render: function() {
    return (
      <input
        type="text"
        value={this.state.value}
        onChange={this.handleChange}
      />
    );
  }

In this example, we are accepting the value provided by the user and updating the value prop of the <input> component. This pattern makes it easy to implement interfaces that respond to or validate user interactions. For example:

  handleChange: function(event) {
    this.setState({value: event.target.value.substr(0, 140)});
  }

This would accept user input and truncate the value to the first 140 characters.

A Controlled component does not maintain its own internal state; the component renders purely based on props.

Potential Issues With Checkboxes and Radio Buttons #

Be aware that, in an attempt to normalize change handling for checkbox and radio inputs, React uses a click event in place of a change event. For the most part this behaves as expected, except when calling preventDefault in a change handler. preventDefault stops the browser from visually updating the input, even if checked gets toggled. This can be worked around either by removing the call to preventDefault, or putting the toggle of checked in a setTimeout.

Uncontrolled Components #

An <input> without a value property is an uncontrolled component:

  render: function() {
    return <input type="text" />;
  }

This will render an input that starts off with an empty value. Any user input will be immediately reflected by the rendered element. If you wanted to listen to updates to the value, you could use the onChange event just like you can with controlled components.

An uncontrolled component maintains its own internal state.

Default Value #

If you want to initialize the component with a non-empty value, you can supply a defaultValue prop. For example:

  render: function() {
    return <input type="text" defaultValue="Hello!" />;
  }

This example will function much like the Controlled Components example above.

Likewise, <input type="checkbox"> and <input type="radio"> support defaultChecked, and <select> supports defaultValue.

Note:

The defaultValue and defaultChecked props are only used during initial render. If you need to update the value in a subsequent render, you will need to use a controlled component.

Advanced Topics #

Why Controlled Components? #

Using form components such as <input> in React presents a challenge that is absent when writing traditional form HTML. For example, in HTML:

  <input type="text" name="title" value="Untitled" />

This renders an input initialized with the value, Untitled. When the user updates the input, the node's value property will change. However, node.getAttribute('value') will still return the value used at initialization time, Untitled.

Unlike HTML, React components must represent the state of the view at any point in time and not only at initialization time. For example, in React:

  render: function() {
    return <input type="text" name="title" value="Untitled" />;
  }

Since this method describes the view at any point in time, the value of the text input should always be Untitled.

Why Textarea Value? #

In HTML, the value of <textarea> is usually set using its children:

  <!-- antipattern: DO NOT DO THIS! -->
  <textarea name="description">This is the description.</textarea>

For HTML, this easily allows developers to supply multiline values. However, since React is JavaScript, we do not have string limitations and can use \n if we want newlines. In a world where we have value and defaultValue, it is ambiguous what role children play. For this reason, you should not use children when setting <textarea> values:

  <textarea name="description" value="This is a description." />

If you do decide to use children, they will behave like defaultValue.

Why Select Value? #

The selected <option> in an HTML <select> is normally specified through that option's selected attribute. In React, in order to make components easier to manipulate, the following format is adopted instead:

  <select value="B">
    <option value="A">Apple</option>
    <option value="B">Banana</option>
    <option value="C">Cranberry</option>
  </select>

To make an uncontrolled component, defaultValue is used instead.

Note:

You can pass an array into the value attribute, allowing you to select multiple options in a select tag: <select multiple={true} value={['B', 'C']}>.

Imperative operations #

If you need to imperatively perform an operation, you have to obtain a reference to the DOM node.
For instance, if you want to imperatively submit a form, one approach would be to attach a ref to the form element and manually call form.submit().

        ← Prev(上一页)

        Next(下一页) →

        A Facebook & Instagram collaboration.

        Acknowledgements

        © 2013–2016 Facebook Inc.

        Documentation licensed under CC BY 4.0.


text:
<?php

namespace Apigee\Edge\Tests\Api\Monetization\Controller;

use Apigee\Edge\Api\Monetization\Controller\CompanyAcceptedRatePlanController;
use Apigee\Edge\Api\Monetization\Controller\RatePlanController;
use Apigee\Edge\Api\Monetization\Entity\RatePlanInterface;
use Apigee\Edge\ClientInterface;
use Apigee\Edge\Tests\Test\Controller\EntityControllerTester;
use Apigee\Edge\Tests\Test\Controller\EntityControllerTesterInterface;
use Apigee\Edge\Tests\Test\HttpClient\FileSystemResponseFactory;
use GuzzleHttp\Psr7\Request;
use Psr\Http\Message\ResponseInterface;

/**
 * Class CompanyAcceptedRatePlanControllerTest.
 *
 * @group controller
 * @group monetization
 */
class CompanyAcceptedRatePlanControllerTest extends AcceptedRatePlanControllerTestBase
{
    protected static $testCompanyName = 'phpunit';

    /**
     * {@inheritdoc}
     */
    protected static function entityController(ClientInterface $client = null): EntityControllerTesterInterface
    {
        $client = $client ?? static::defaultAPIClient();

        return new EntityControllerTester(new CompanyAcceptedRatePlanController(static::$testCompanyName, static::defaultTestOrganization($client), $client));
    }

    /**
     * {@inheritdoc}
     */
    protected function getAcceptRatePlanResponse(): ResponseInterface
    {
        $id = static::$testCompanyName;

        return (new FileSystemResponseFactory())->createResponseForRequest(new Request('GET', "v1/mint/organizations/phpunit/companies/{$id}/developer-rateplans/phpunit"));
    }

    /**
     * {@inheritdoc}
     */
    protected function getRatePlanToAccept(): RatePlanInterface
    {
        /** @var \Apigee\Edge\Api\Monetization\Controller\RatePlanControllerInterface $ratePlanController */
        $ratePlanController = new RatePlanController('phpunit', static::defaultTestOrganization(static::defaultAPIClient()), static::defaultAPIClient());
        /** @var \Apigee\Edge\Api\Monetization\Entity\CompanyRatePlanInterface $ratePlan */
        $ratePlan = $ratePlanController->load('company-rev');

        return $ratePlan;
    }
}


text:
import json
import model_price

##### model price
print model_price.daily()
print model_price.weekly()


text:
@implementation UIFont (GravitasOne)

+ (instancetype)gravitasOneFontOfSize:(CGFloat)size {
  static dispatch_once_t onceToken;
  [GFIFontLoader loadFontFile:@"GravitasOne"
                   fromBundle:@"GravitasOne"
                    onceToken:&onceToken];
  return [self fontWithName:@"GravitasOne" size:size];
}

@end


text:
task-chrono
===========

Task list with chronometry

task-chrono is a tool that helps in task planning. It does this by providing
statistics on how accurately you estimate task duration. This will give insight
in how good you are at estimating task duration, which in turn will help
planning your work.

This application runs on Google App Engine at http://task-chrono.appspot.com. A
Google account or OpenID is required.


text:
#ifndef _Scrollbar_h
#define _Scrollbar_h

/*
 * Scrollbar Widget
 */

#include <X11/Xmu/Converters.h>
#include <X11/Xfuncproto.h>

/* Scrollbar resources:

 Name		     Class		RepType		Default Value
 ----		     -----		-------		-------------
 accelerators	     Accelerators	AcceleratorTable NULL
 ancestorSensitive   AncestorSensitive	Boolean		True
 background	     Background		Pixel		XtDefaultBackground
 backgroundPixmap    Pixmap		Pixmap		XtUnspecifiedPixmap
 borderColor	     BorderColor	Pixel		XtDefaultForeground
 borderPixmap	     Pixmap		Pixmap		XtUnspecifiedPixmap
 borderWidth	     BorderWidth	Dimension	1
 colormap	     Colormap		Colormap	parent's colormap
 cursor		     Cursor		Cursor		None
 cursorName	     Cursor		String		NULL
 depth		     Depth		int		parent's depth
 destroyCallback     Callback		XtCallbackList	NULL
 foreground	     Foreground		Pixel		XtDefaultForeground
 height		     Height		Dimension	length or thickness
 insensitiveBorder   Insensitive	Pixmap		GreyPixmap
 jumpProc	     Callback		XtCallbackList	NULL
 length		     Length		Dimension	1
 mappedWhenManaged   MappedWhenManaged	Boolean		True
 minimumThumb	     MinimumThumb	Dimension	7
 orientation	     Orientation	XtOrientation	XtorientVertical
 pointerColor	     Foreground		Pixel		XtDefaultForeground
 pointerColorBackground Background	Pixel		XtDefaultBackground
 screen		     Screen		Screen		parent's screen
 scrollDCursor	     Cursor		Cursor		XC_sb_down_arrow
 scrollHCursor	     Cursor		Cursor		XC_sb_h_double_arrow
 scrollLCursor	     Cursor		Cursor		XC_sb_left_arrow
 scrollProc	     Callback		XtCallbackList	NULL
 scrollRCursor	     Cursor		Cursor		XC_sb_right_arrow
 scrollUCursor	     Cursor		Cursor		XC_sb_up_arrow
 scrollVCursor	     Cursor		Cursor		XC_sb_v_double_arrow
 sensitive	     Sensitive		Boolean		True
 shown		     Shown		Float		0.0
 thickness	     Thickness		Dimension	14
 thumb		     Thumb		Bitmap		GreyPixmap
 thumbProc	     Callback		XtCallbackList	NULL
 topOfThumb	     TopOfThumb		Float		0.0
 translations	     Translations	TranslationTable see source or doc
 width		     Width		Dimension	thickness or length
 x		     Position		Position	0
 y		     Position		Position	0

*/

#define XtCMinimumThumb "MinimumThumb"
#define XtCShown "Shown"
#define XtCTopOfThumb "TopOfThumb"

#define XtNminimumThumb "minimumThumb"
#define XtNtopOfThumb "topOfThumb"

typedef struct _ScrollbarRec	  *ScrollbarWidget;
typedef struct _ScrollbarClassRec *ScrollbarWidgetClass;

extern WidgetClass scrollbarWidgetClass;

_XFUNCPROTOBEGIN

void XawScrollbarSetThumb
(
 Widget			scrollbar,
#if NeedWidePrototypes
 double			top,
 double			shown
#else
 float			top,
 float			shown
#endif
 );

_XFUNCPROTOEND

#endif /* _Scrollbar_h */


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~   Copyright 2018 Google LLC
  ~
  ~   Licensed under the Apache License, Version 2.0 (the "License");
  ~   you may not use this file except in compliance with the License.
  ~   You may obtain a copy of the License at
  ~
  ~        http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~   Unless required by applicable law or agreed to in writing, software
  ~   distributed under the License is distributed on an "AS IS" BASIS,
  ~   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~   See the License for the specific language governing permissions and
  ~   limitations under the License.
  ~
  -->

<transitionSet
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <transitionSet android:duration="400">
        <targets>
            <target android:targetId="@id/scrim" />
        </targets>
        <fade />
        <transition
            class="io.plaidapp.search.ui.transitions.CircularReveal"
            app:centerOn="@id/searchback"
            android:interpolator="@android:interpolator/linear_out_slow_in" />
    </transitionSet>

    <fade
        android:duration="300"
        android:interpolator="@android:interpolator/linear_out_slow_in">
        <targets>
            <target android:targetId="@id/search_background" />
        </targets>
    </fade>

    <fade
        android:startDelay="400"
        android:duration="400"
        android:interpolator="@android:interpolator/linear_out_slow_in">
        <targets>
            <target android:targetId="@id/search_view" />
        </targets>
    </fade>

    <fade
        android:duration="400"
        android:interpolator="@android:interpolator/fast_out_slow_in">
        <targets>
            <target android:targetId="@android:id/navigationBarBackground" />
        </targets>
    </fade>

</transitionSet>


text:
yum_package "httpd.x86_64" do
  action :install
end

user "www" do
  supports :manage_home => true
  comment "www"
  uid 502
  gid "apache"
  home "/home/www"
  shell "/bin/bash"
end

service "gibapache" do
  service_name "httpd"
  restart_command "/sbin/service httpd restart && sleep 1"
  reload_command "/sbin/service httpd reload && sleep 1"
  supports [:restart, :reload, :status]
  action :enable
end

directory node['gibapache']['docroot_dir'] do
    mode 00755
end

%w{gibproject sfproject html}.each do |dir|
directory "#{node['gibapache']['docroot_dir']}/#{dir}" do
    mode 00755
    owner node[:gibapache][:user]
    group node[:gibapache][:group]
    action :create
    recursive true
end
end

%w{web libs cache data}.each do |dir|
directory "#{node['gibapache']['docroot_dir']}/gibproject/#{dir}" do
    mode 00755
    owner node[:gibapache][:user]
    group node[:gibapache][:group]
    action :create
    recursive true
end
end

directory node['gibapache']['log_dir'] do
    mode 00755
    owner node[:gibapache][:user]
    group node[:gibapache][:group]
    action :create
end

directory "#{node['gibapache']['log_dir']}/vhosts/default" do
    mode 00755
    owner node[:gibapache][:user]
    group node[:gibapache][:group]
    action :create
    recursive true
end

directory "#{node['gibapache']['log_dir']}/vhosts" do
    mode 00755
    owner node[:gibapache][:user]
    group node[:gibapache][:group]
end

%w{vhosts sf}.each do |dir|
directory "#{node['gibapache']['ServerRoot']}/conf/#{dir}" do
    mode 00755
    action :create
    recursive true
end
end

template "/etc/httpd/conf/httpd.conf" do
  path "#{node['gibapache']['ServerRoot']}/conf/httpd.conf"
  source "httpd.conf.erb"
  owner "root"
group "root"
mode 00644
  notifies :restart, "service[gibapache]"
end

cookbook_file "#{node['gibapache']['ServerRoot']}/conf/sf/vhosts.conf" do
  source "vhosts.conf"
  mode "0644"
end

service "gibapache" do
  action :start
end


text:
module Net
  module NTP
    ###
    # = Overview
    #
    # Contains Net::NTP::Check version number
    module Check
      VERSION = '0.0.1'
    end
  end
end


text:
package org.codehaus.griffon.runtime.validation.constraints;

import griffon.plugins.validation.Errors;
import org.apache.commons.validator.routines.CreditCardValidator;

/**
 * Validates a credit card number.
 *
 * @author Graeme Rocher (Grails 0.4)
 */
public class CreditCardConstraint extends AbstractConstraint {
    public static final String VALIDATION_DSL_NAME = "creditCard";
    public static final String DEFAULT_INVALID_CREDIT_CARD_MESSAGE_CODE = "default.invalid.creditCard.message";
    public static final String DEFAULT_INVALID_CREDIT_CARD_MESSAGE = "Property [{0}] of class [{1}] with value [{2}] is not a valid credit card number";

    private boolean creditCard;

    @Override
    protected void processValidate(Object target, Object propertyValue, Errors errors) {
        if (!creditCard) {
            return;
        }

        CreditCardValidator validator = new CreditCardValidator();

        if (!validator.isValid(propertyValue.toString())) {
            Object[] args = new Object[]{constraintPropertyName, constraintOwningClass, propertyValue};
            rejectValue(target, errors, DEFAULT_INVALID_CREDIT_CARD_MESSAGE_CODE,
                VALIDATION_DSL_NAME + INVALID_SUFFIX, args);
        }
    }

    @Override
    public void setParameter(Object constraintParameter) {
        if (!(constraintParameter instanceof Boolean)) {
            throw new IllegalArgumentException("Parameter for constraint [" +
                VALIDATION_DSL_NAME + "] of property [" +
                constraintPropertyName + "] of class [" +
                constraintOwningClass + "] must be a boolean value");
        }

        creditCard = ((Boolean) constraintParameter).booleanValue();
        super.setParameter(constraintParameter);
    }

    public String getName() {
        return VALIDATION_DSL_NAME;
    }

    @SuppressWarnings("rawtypes")
    public boolean supports(Class type) {
        return type != null && (String.class.isAssignableFrom(type));
    }
}


text:
include_attribute 'sc-mongodb::default'

default['mongodb']['sysconfig']['DAEMON'] = '/usr/bin/$NAME'
default['mongodb']['sysconfig']['DAEMON_USER'] = node['mongodb']['user']
default['mongodb']['sysconfig']['DAEMON_OPTS'] = "--config #{node['mongodb']['dbconfig_file']}"
default['mongodb']['sysconfig']['CONFIGFILE'] = node['mongodb']['dbconfig_file']
default['mongodb']['sysconfig']['ENABLE_MONGODB'] = 'yes'

# these are backward compat purposes
default['mongodb']['sysconfig']['DAEMONUSER'] = node['mongodb']['sysconfig']['DAEMON_USER']
default['mongodb']['sysconfig']['ENABLE_MONGOD'] = node['mongodb']['sysconfig']['ENABLE_MONGODB']
default['mongodb']['sysconfig']['ENABLE_MONGO'] = node['mongodb']['sysconfig']['ENABLE_MONGODB']


text:
require 'redis'
require 'rails/all'
require 'awrence'
require 'plissken'
require 'entangled/version'
require 'entangled/helpers'
require 'entangled/model'
require 'entangled/controller'
require 'entangled/routes'


text:
secrets_file = "/etc/chef-marketplace/chef-marketplace-secrets.json"
secrets_from_file = if ::File.exist?(secrets_file)
                      Chef::JSONCompat.from_json(::File.read(secrets_file))
                    else
                      {}
                    end

## ADD NEW SECRETS HERE ##
# To add a new secret to chef-markteplace, simply add it into the hash here. It will
# be randomly generated to your specification with the SecureRandom class and
# automatically persisted to the secrets file upon a reconfigure.
#
default_secrets = {
  "biscotti" => {
    "token" => SecureRandom.hex(50)
  },
  "automate" => {
    "postgresql" => {
      "superuser_password" => SecureRandom.hex(50)
    },
    "data_collector" => {
      "token" => SecureRandom.hex(50)
    },
    "passwords" => {
      "chef_user" => SecureRandom.base64(12),
      "admin_user" => SecureRandom.base64(12),
      "builder_user" => SecureRandom.base64(12)
    }
  }
}

# Hash#merge will override any values in the original hash with values that
# come from the input, so all values coming from the file on disk will be
# overwrite the random data
new_secrets = Chef::Mixin::DeepMerge.deep_merge(secrets_from_file, default_secrets)

file secrets_file do
  content Chef::JSONCompat.to_json_pretty(new_secrets)
  sensitive true
  action :create
end

node.consume_attributes("chef-marketplace" => new_secrets)


text:
require 'carrierwave/orm/activerecord'
require 'file_size_validator'

class Note < ActiveRecord::Base
  include Gitlab::CurrentSettings
  include Participable
  include Mentionable

  default_value_for :system, false

  attr_mentionable :note, cache: true, pipeline: :note
  participant :author

  belongs_to :project
  belongs_to :noteable, polymorphic: true
  belongs_to :author, class_name: "User"
  belongs_to :updated_by, class_name: "User"

  delegate :name, to: :project, prefix: true
  delegate :name, :email, to: :author, prefix: true

  before_validation :set_award!

  validates :note, :project, presence: true
  validates :note, uniqueness: { scope: [:author, :noteable_type, :noteable_id] }, if: ->(n) { n.is_award }
  validates :note, inclusion: { in: Emoji.emojis_names }, if: ->(n) { n.is_award }
  validates :line_code, line_code: true, allow_blank: true
  # Attachments are deprecated and are handled by Markdown uploader
  validates :attachment, file_size: { maximum: :max_attachment_size }

  validates :noteable_id, presence: true, if: ->(n) { n.noteable_type.present? && n.noteable_type != 'Commit' }
  validates :commit_id, presence: true, if: ->(n) { n.noteable_type == 'Commit' }
  validates :author, presence: true

  mount_uploader :attachment, AttachmentUploader

  # Scopes
  scope :awards, ->{ where(is_award: true) }
  scope :nonawards, ->{ where(is_award: false) }
  scope :for_commit_id, ->(commit_id) { where(noteable_type: "Commit", commit_id: commit_id) }
  scope :inline, ->{ where("line_code IS NOT NULL") }
  scope :not_inline, ->{ where(line_code: [nil, '']) }
  scope :system, ->{ where(system: true) }
  scope :user, ->{ where(system: false) }
  scope :common, ->{ where(noteable_type: ["", nil]) }
  scope :fresh, ->{ order(created_at: :asc, id: :asc) }
  scope :inc_author_project, ->{ includes(:project, :author) }
  scope :inc_author, ->{ includes(:author) }

  scope :with_associations, -> do
    includes(:author, :noteable, :updated_by,
             project: [:project_members, { group: [:group_members] }])
  end

  serialize :st_diff
  before_create :set_diff, if: ->(n) { n.line_code.present? }

  class << self
    def discussions_from_notes(notes)
      discussion_ids = []
      discussions = []

      notes.each do |note|
        next if discussion_ids.include?(note.discussion_id)

        # don't group notes for the main target
        if !note.for_diff_line? && note.noteable_type == "MergeRequest"
          discussions << [note]
        else
          discussions << notes.select do |other_note|
            note.discussion_id == other_note.discussion_id
          end
          discussion_ids << note.discussion_id
        end
      end

      discussions
    end

    def build_discussion_id(type, id, line_code)
      [:discussion, type.try(:underscore), id, line_code].join("-").to_sym
    end

    def search(query)
      where("LOWER(note) like :query", query: "%#{query.downcase}%")
    end

    def grouped_awards
      awards.select(:note).distinct.map do |note|
        [ note.note, where(note: note.note) ]
      end
    end
  end

  def cross_reference?
    system && SystemNoteService.cross_reference?(note)
  end

  def max_attachment_size
    current_application_settings.max_attachment_size.megabytes.to_i
  end

  def find_diff
    return nil unless noteable && noteable.diffs.present?

    @diff ||= noteable.diffs.find do |d|
      Digest::SHA1.hexdigest(d.new_path) == diff_file_index if d.new_path
    end
  end

  def hook_attrs
    attributes
  end

  def set_diff
    # First lets find notes with same diff
    # before iterating over all mr diffs
    diff = diff_for_line_code unless for_merge_request?
    diff ||= find_diff

    self.st_diff = diff.to_hash if diff
  end

  def diff
    @diff ||= Gitlab::Git::Diff.new(st_diff) if st_diff.respond_to?(:map)
  end

  def diff_for_line_code
    Note.where(noteable_id: noteable_id, noteable_type: noteable_type, line_code: line_code).last.try(:diff)
  end

  # Check if such line of code exists in merge request diff
  # If exists - its active discussion
  # If not - its outdated diff
  def active?
    return true unless self.diff
    return false unless noteable

    noteable.diffs.each do |mr_diff|
      next unless mr_diff.new_path == self.diff.new_path

      lines = Gitlab::Diff::Parser.new.parse(mr_diff.diff.lines.to_a)

      lines.each do |line|
        if line.text == diff_line
          return true
        end
      end
    end

    false
  end

  def outdated?
    !active?
  end

  def diff_file_index
    line_code.split('_')[0] if line_code
  end

  def diff_file_name
    diff.new_path if diff
  end

  def file_path
    if diff.new_path.present?
      diff.new_path
    elsif diff.old_path.present?
      diff.old_path
    end
  end

  def diff_old_line
    line_code.split('_')[1].to_i if line_code
  end

  def diff_new_line
    line_code.split('_')[2].to_i if line_code
  end

  def generate_line_code(line)
    Gitlab::Diff::LineCode.generate(file_path, line.new_pos, line.old_pos)
  end

  def diff_line
    return @diff_line if @diff_line

    if diff
      diff_lines.each do |line|
        if generate_line_code(line) == self.line_code
          @diff_line = line.text
        end
      end
    end

    @diff_line
  end

  def diff_line_type
    return @diff_line_type if @diff_line_type

    if diff
      diff_lines.each do |line|
        if generate_line_code(line) == self.line_code
          @diff_line_type = line.type
        end
      end
    end

    @diff_line_type
  end

  def truncated_diff_lines
    max_number_of_lines = 16
    prev_match_line = nil
    prev_lines = []

    diff_lines.each do |line|
      if line.type == "match"
        prev_lines.clear
        prev_match_line = line
      else
        prev_lines << line

        break if generate_line_code(line) == self.line_code

        prev_lines.shift if prev_lines.length >= max_number_of_lines
      end
    end

    prev_lines
  end

  def diff_lines
    @diff_lines ||= Gitlab::Diff::Parser.new.parse(diff.diff.lines.to_a)
  end

  def discussion_id
    @discussion_id ||= Note.build_discussion_id(noteable_type, noteable_id || commit_id, line_code)
  end

  def for_commit?
    noteable_type == "Commit"
  end

  def for_commit_diff_line?
    for_commit? && for_diff_line?
  end

  def for_diff_line?
    line_code.present?
  end

  def for_issue?
    noteable_type == "Issue"
  end

  def for_merge_request?
    noteable_type == "MergeRequest"
  end

  def for_merge_request_diff_line?
    for_merge_request? && for_diff_line?
  end

  def for_project_snippet?
    noteable_type == "Snippet"
  end

  # override to return commits, which are not active record
  def noteable
    if for_commit?
      project.commit(commit_id)
    else
      super
    end
  # Temp fix to prevent app crash
  # if note commit id doesn't exist
  rescue
    nil
  end

  # Mentionable override.
  def gfm_reference(from_project = nil)
    noteable.gfm_reference(from_project)
  end

  # Mentionable override.
  def local_reference
    noteable
  end

  def noteable_type_name
    noteable_type.downcase if noteable_type.present?
  end

  # FIXME: Hack for polymorphic associations with STI
  #        For more information visit http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#label-Polymorphic+Associations
  def noteable_type=(noteable_type)
    super(noteable_type.to_s.classify.constantize.base_class.to_s)
  end

  # Reset notes events cache
  #
  # Since we do cache @event we need to reset cache in special cases:
  # * when a note is updated
  # * when a note is removed
  # Events cache stored like  events/23-20130109142513.
  # The cache key includes updated_at timestamp.
  # Thus it will automatically generate a new fragment
  # when the event is updated because the key changes.
  def reset_events_cache
    Event.reset_event_cache_for(self)
  end

  def system?
    read_attribute(:system)
  end

  # Deprecated. Still exists to preserve API compatibility.
  def downvote?
    false
  end

  # Deprecated. Still exists to preserve API compatibility.
  def upvote?
    false
  end

  def editable?
    !system? && !is_award
  end

  # Checks if note is an award added as a comment
  #
  # If note is an award, this method sets is_award to true
  #   and changes content of the note to award name.
  #
  # Method is executed as a before_validation callback.
  #
  def set_award!
    return unless awards_supported? && contains_emoji_only?
    self.is_award = true
    self.note = award_emoji_name
  end

  private

  def awards_supported?
    noteable.kind_of?(Issue) || noteable.is_a?(MergeRequest)
  end

  def contains_emoji_only?
    note =~ /\A#{Banzai::Filter::EmojiFilter.emoji_pattern}\s?\Z/
  end

  def award_emoji_name
    original_name = note.match(Banzai::Filter::EmojiFilter.emoji_pattern)[1]
    AwardEmoji.normilize_emoji_name(original_name)
  end
end


text:
package com.all.downloader.download;

import com.all.downloader.bean.DownloadStatus;

public class SearchSourcesEvent extends DownloadUpdateEvent {

	private static final long serialVersionUID = 1L;
	private final ManagedDownloader downloader;

	public SearchSourcesEvent(ManagedDownloader source, String downloadId, DownloadStatus status) {
		super(source, downloadId, status);
		downloader = source;
	}

	public ManagedDownloader getDownloader() {
		return downloader;
	}

}


text:
<?php
/**
 * Ionize
 *
 * @package		Ionize
 * @author		Ionize Dev Team
 * @license		http://doc.ionizecms.com/en/basic-infos/license-agreement
 * @link		http://ionizecms.com
 * @since		Version 0.9.7
 *
 */

/**
 * Ionize Pages Class
 *
 * @package		Ionize
 * @subpackage	Libraries
 * @category	TagManager Libraries
 *
 */
class Pages
{

	protected static $_inited = FALSE;

	protected static $user = FALSE;

	static $ci;

	function init()
	{
		if(self::$_inited)
		{
			return;
		}
		self::$_inited = TRUE;

		self::$ci =& get_instance();
	}

	// ------------------------------------------------------------------------

	/* Returns all pages
	 * Used by the TagManager Page and the TagManager Navigation
	 *
	 */
	public static function get_pages($lang = NULL)
	{
		if ($lang == NULL) $lang = Settings::get_lang('current');

		self::$ci->load->model('page_model');

		$pages = self::$ci->page_model->get_lang_list(NULL, $lang);

		// Should never be displayed : no pages are set.
		if (empty($pages))
		{
			show_error('Internal error : No pages found.
Solution: Create at least one online page.', 500 );
			exit;
		}

		/* Spread authorizations from parents pages to chidrens.
		 * This adds the group ID to the childrens pages of a protected page
		 * If you don't want this, just uncomment this line.
		 */
		// self::$ci->page_model->spread_authorizations($pages);

		// Filter pages regarding the authorizations
		if (User()->get('role_level') < 1000)
			$pages = array_values(array_filter($pages, array(__CLASS__, '_filter_pages_authorization')));

		// Set all abolute URLs one time, for perf.
		self::init_absolute_urls($pages, $lang);

		return $pages;
	}

	// ------------------------------------------------------------------------

	/**
	 * Inits the Absolutes URLs of each page
	 *
	 * @TODO : Rewrite the "absolute_urls" definition so that it takes the internal links in account.
	 *
	 *
	 */
	public static function init_absolute_urls(&$pages, $lang)
	{
		$short_mode = (config_item('url_mode') === 'short');

		$languages = (Authority::can('access', 'admin') && Settings::get('display_front_offline_content') == 1) ? Settings::get_languages() : Settings::get_online_languages();

		foreach ($pages as &$page)
		{
			// Set the page complete URL
			$page['absolute_url'] = '';
			$url = ($short_mode) ? $page['url'] : $page['path'];

			// Link
			if ($page['link_type'] != '' )
			{
				// External
				if (in_array($page['link_type'], array('external', 'anchor')))
				{
					$page['absolute_url'] = $page['link'];
				}
				else if ($page['link_type'] === 'email')
				{
					$page['absolute_url'] = auto_link($page['link'], 'both', TRUE);
				}
				// Internal
				else
				{
					// Article
					if($page['link_type'] === 'article')
					{
						// Get the article to which this page links
						$rel = explode('.', $page['link_id']);
						$target_article = self::$ci->article_model->get_context($rel[1], $rel[0], $lang);

						// Of course, only if not empty...
						if ( ! empty($target_article))
						{
							// Get the article's parent page
							$page['absolute_url'] = '';

							foreach($pages as $p)
							{
								if ($p['id_page'] == $target_article['id_page'])
								{
									$p_url = ($short_mode) ? $p['url'] : $p['path'];
									$page['absolute_url'] = $p_url . '/' . $target_article['url'];
								}
							}
						}
					}
					// Page
					else
					{
						// Get the page to which the page links
						$page['absolute_url'] = '';

						foreach($pages as $p)
						{
							if ($p['id_page'] == $page['link_id'])
								$page['absolute_url'] = ($short_mode) ? $p['url'] : $p['path'];
						}
					}
					if ( count($languages) > 1 OR Settings::get('force_lang_urls') == '1' )
					{
						$page['absolute_url'] =  $lang. '/' . $page['absolute_url'];
					}
					$page['absolute_url'] = base_url() . $page['absolute_url'];

				}
			}
			else
			{
				if ( count($languages) > 1 OR Settings::get('force_lang_urls') == '1' )
				{
					// Home page : doesn't contains the page URL
					if ($page['home'] == 1 )
					{
						// Default language : No language code in the URL for the home page
						// Other language : The home page has the lang code in URL
						if (Settings::get_lang('default') != $lang)
						{
							$page['absolute_url'] = $lang;
						}
					}
					// Other pages : lang code in URL
					else
					{
						// If page URL if already set because of a link, don't replace it.
						// $url = ($short_mode) ? $page['url'] : $page['path'];
						$page['absolute_url'] = ($page['absolute_url'] != '') ? $lang . '/' . $page['absolute_url'] : $lang . '/' . $url;
					}

					$page['absolute_url'] = base_url() . $page['absolute_url'];

					// Set the lang code depending URL (used by language subtag)
					$page['absolute_urls'] = array();
				}
				else
				{
					if ($page['home'] == 1)
					{
						$page['absolute_url'] = base_url();
					}
					else
					{
						// $url = ($short_mode) ? $page['url'] : $page['path'];
						$page['absolute_url'] = base_url() . $url;
					}
					// Set the lang code depending URL (used by language subtag)
					$page['absolute_urls'][$lang] = $page['absolute_url'];
				}
			}

			// Explode the concatenated URLs infos
			$page_url_langs = explode(';', $page['url_langs']);
			$page_url_path = explode(';', $page['url_paths']);

			foreach ($languages as $language)
			{
				if ($page['home'] == 1 )
				{
					// Default language : No language code in the URL for the home page
					if (Settings::get_lang('default') == $language['lang'])
					{
						$page['absolute_urls'][$language['lang']] = base_url();
					}
					// Other language : The home page has the lang code in URL
					else
					{
						$page['absolute_urls'][$language['lang']] = base_url() . $language['lang'];
					}
				}
				// Other pages : lang code in URL
				else
				{
					if ( ! $short_mode)
					{
						// The index of the processed lang code will be the index of the path
						$index = array_search($language['lang'], $page_url_langs);
						$url = ($index !== FALSE) ? $page_url_path[$index] : '';
						$page['absolute_urls'][$language['lang']] = base_url() . $language['lang'] . '/' . $url;
					}
					else
					{
						$page['absolute_urls'][$language['lang']] = base_url() . $language['lang'] . '/' . $page['urls'][$language['lang']];
					}
				}
			}
		}
	}

	// ------------------------------------------------------------------------

	/**
	 * @return string
	 */
	public static function get_home_page_url()
	{
		$url = base_url();

		if (Settings::get_lang('default') != Settings::get_lang())
			$url .= Settings::get_lang() . '/';

		return $url;
	}

	// ------------------------------------------------------------------------

	/**
	 * @param $page
	 *
	 * @return bool
	 */
	private static function _filter_pages_authorization($page)
	{
		$resource = 'frontend/page/' . $page['id_page'];

		if ( Authority::cannot('access', $resource, NULL, TRUE))
		{
			if (empty($page['deny_code']) OR $page['deny_code'] === '404' )
				return FALSE;
		}

		return TRUE;
	}
}

Pages::init();


text:
<?php

    @@HEADER@@

    require_once 'payments.class.php';

    class Donation extends Payment
    {
        public $emailAddress;
        public $name;
        public $message;
        public $showNoAmount;
        public $showAnonymous;

        function __construct($id, $amount = 0, $emailAddress = '', $name = '', $message = '', $paymentVerification = '', $paymentMethod = '', $paymentId = null, $paymentStatus = null, $showNoAmount = false, $showAnonymous = false, $locale = '', $timestamp = null)
        {
            parent::__construct($id, PaymentTypes::Donation, $amount, $emailAddress, $paymentVerification, $paymentMethod, $paymentId, $paymentStatus, $locale, '', $timestamp);

            $this->name = $name;
            $this->message = $message;
            $this->showNoAmount = $showNoAmount;
            $this->showAnonymous = $showAnonymous;
        }

        public static function withPayment($payment)
        {
            $instance = new self($payment->id, $payment->amount, $payment->getUserId(), '', '', $payment->paymentVerification, $payment->paymentMethod, $payment->paymentId, $payment->paymentStatus, false, false, $payment->locale, $payment->timestamp);
            $instance->setData($payment->getData());
            $instance->deserializeData();
            return $instance;
        }

        public function getType()
        {
            return PaymentTypes::Donation;
        }

        public function getUserId()
        {
            return $this->emailAddress;
        }

        protected function setData($data)
        {
            $this->_data = $data;
        }

        public function setUserId($value)
        {
            $this->emailAddress = $value;
            $this->userid = $value;
        }

        public function serializeData()
        {
            $this->_data = json_encode(array(
                'name' => utf8_encode($this->name),
                'message' => utf8_encode($this->message),
                'showNoAmount' => $this->showNoAmount,
                'showAnonymous' => $this->showAnonymous
            ));
        }

        public function deserializeData()
        {
            if (!$this->_data || !is_string($this->_data))
                return;

            $array = json_decode($this->_data, true);

            if (!$array || !is_array($array))
                return;

            if (isset($array['name'])) { $this->name = utf8_decode($array['name']); }
            if (isset($array['message'])) { $this->message = utf8_decode($array['message']); }
            if (isset($array['showNoAmount'])) { $this->showNoAmount = $array['showNoAmount']; }
            if (isset($array['showAnonymous'])) { $this->showAnonymous = $array['showAnonymous']; }
        }

		public static function validEMailAddress($emailaddress)
        {
			return preg_match('/^([0-9a-zA-Z_]([-.\w\+]*[0-9a-zA-Z_])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,})$/', $emailaddress);
		}
    }

    class Donations extends Payments
    {
        public function __construct($dsn, $username, $password = '')
        {
            parent::__construct($dsn, $username, $password);
        }

        public function addDonation($donation)
        {
            $donation->serializeData();
            return $this->addPayment($donation);
        }

        public function getDonation($id, $verification)
        {
            if (!$payment = $this->getPayment($id, $verification))
                return null;

            if (!$donation = Donation::withPayment($payment))
                return null;

            return $donation;
        }

        public function getDonationsList($page = 1, $itemsPerPage = 10, $sortOrder = 'DESC')
        {
            $donations = [];

            if (!$payments = $this->getPaymentsList(PaymentTypes::Donation, PaymentStatus::Paid_Or_PaidOut, $page, $itemsPerPage, $sortOrder))
                return null;

            foreach($payments as $payment) {
                if ($donation = Donation::withPayment($payment))
                    $donations[] = $donation;
            }

            return $donations;
        }

		public function getDonationsListCount()
        {
            return $this->getPaymentsListCount(PaymentTypes::Donation, PaymentStatus::Paid_Or_PaidOut);
		}

		public function getTotalDonationsAmount()
        {
            return $this->getTotalPaymentsAmount(PaymentTypes::Donation, PaymentStatus::Paid_Or_PaidOut);
        }

		public function getPercentageOfGoal($current, $goal, $max)
        {
			$goalPercentage = 0;

			if ($goal > 0) {

				$goalPercentage = ((float)$current / (float)$goal) * 100;

				if ($goalPercentage > $max)
					$goalPercentage = $max;
			}

			return $goalPercentage;
		}

    }


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycologia 78(1): 136 (1986)

#### Original name
Nolanea quadrospora Largent & O.K. Mill.

### Remarks
null


text:
var Promise = require('bluebird');
var report = require('./capture.report');

//동영상 관련 처리
var movies = function (vars) {
	return new Promise(function (resolve, reject) {
		//jQuery 삽입
		if (vars.page.injectJs(vars.jQueryPath)) {

			//안과 밖의 변수명 바꾸기..
			var mediaProperties = vars.page.evaluate(function (vars) {
				var __mediaProperties = [];

				//동영상의 절대 위치 -> FIXME var 형태로 할래 ㅋ
				var absolutePostion = function (element, parentBoundingClientRectTop, parentBoundingClientRectLeft) {
					var selectedPosX = 0;
					var selectedPosY = 0;

					while (element != null) {
						selectedPosX += element.offsetLeft;
						selectedPosY += element.offsetTop;
						element = element.offsetParent;
					}

					return [parentBoundingClientRectTop + selectedPosY, parentBoundingClientRectLeft + selectedPosX];
				};

				//flash 관련 정보 추출 및 썸네일로 치환
				var removeFlash = function (currentDocument, parentBoundingClientRectWidth) {
					var params = currentDocument.querySelectorAll('param[name="movie"][value*="swf"]');

					//FIXME 라인이 너무 길다. 읽기 좋게 변경 필요..
					//FIXME jQuery 감싸기..

					[].forEach.call(params, function (item) {
						var object = item.parentNode;
						var $object = $(object);
						var width = ($(object).width() < vars.cautionImage.width) ? vars.cautionImage.width : (($(object).width() > parentBoundingClientRectWidth) ? parentBoundingClientRectWidth : $(object).width()) || parentBoundingClientRectWidth;
						var height = ($(object).height() < vars.cautionImage.height) ? vars.cautionImage.height : $(object).height() || 0 | width / 2;

						$(object).replaceWith("

");
					});
				};

				//video 태그 관련 정보 추출 및 썸네일로 치환
				var replaceVideo = function (currentDocument, parentBoundingClientRectTop, parentBoundingClientRectLeft, parentBoundingClientRectWidth) {
					var sources = currentDocument.querySelectorAll('source[src][type*="video"]');

					[].forEach.call(sources, function (item) {
						var object = item.parentNode;
						var src = item.src;
						var id = Number(new Date());
						var width = ($(object).width() > parentBoundingClientRectWidth) ? parentBoundingClientRectWidth : $(object).width() || parentBoundingClientRectWidth;
						var height = ($(object).width() > parentBoundingClientRectWidth) ? 0 | parentBoundingClientRectWidth * $(object).height() / $(object).width() : $(object).height() || 0 | width / 2;
						var thumbnail = '';
						var absolutePos = absolutePostion(object, parentBoundingClientRectTop, parentBoundingClientRectLeft);
						$(object).replaceWith("

");

						__mediaProperties.push({id:id, src:src, width:Number(width), height:Number(height), thumbnail:thumbnail, top:absolutePos[0], left:absolutePos[1]});
					});
				};

				//youtube 관련 정보 추출 및 썸네일로 치환
				var replaceYoutube = function (currentDocument, parentBoundingClientRectTop, parentBoundingClientRectLeft, parentBoundingClientRectWidth) {
					var iframes = currentDocument.querySelectorAll('iframe[src*="youtube.com"]');
					var embeds = currentDocument.querySelectorAll('embed[src*="youtube.com"]');

					[].forEach.call(iframes, function (item) {
						var src = item.src;
						var id = item.src.match(/.+\/([^\/\?]+)/)[1];
						var width = ($(item).width() > parentBoundingClientRectWidth) ? parentBoundingClientRectWidth : $(item).width() || parentBoundingClientRectWidth;
						var height = ($(item).width() > parentBoundingClientRectWidth) ? 0 | parentBoundingClientRectWidth * $(item).height() / $(item).width() : $(item).height() || 0 | width / 2;
						var thumbnail = "http://img.youtube.com/vi/" + id + "/0.jpg";
						var absolutePos = absolutePostion(item, parentBoundingClientRectTop, parentBoundingClientRectLeft);
						$(item).replaceWith("

");

						__mediaProperties.push({id:id, src:src, width:Number(width), height:Number(height), thumbnail:thumbnail, top:absolutePos[0], left:absolutePos[1]});
					});

					[].forEach.call(embeds, function (item) {
						var src = item.src;
						var id = item.src.match(/.+\/([^\/\?]+)/)[1];
						var width = ($(item).width() > parentBoundingClientRectWidth) ? parentBoundingClientRectWidth : $(item).width() || parentBoundingClientRectWidth;
						var height = ($(item).width() > parentBoundingClientRectWidth) ? 0 | parentBoundingClientRectWidth * $(item).height() / $(item).width() : $(item).height() || 0 | width / 2;
						var thumbnail = "http://img.youtube.com/vi/" + id + "/0.jpg";
						var absolutePos = absolutePostion(item, parentBoundingClientRectTop, parentBoundingClientRectLeft);
						$(item).replaceWith("

");

						__mediaProperties.push({id:id, src:src, width:Number(width), height:Number(height), thumbnail:thumbnail, top:absolutePos[0], left:absolutePos[1]});
					});
				};

				//vimeo 관련 정보 추출 및 썸네일로 치환
				var replaceVimeo = function (currentDocument, parentBoundingClientRectTop, parentBoundingClientRectLeft, parentBoundingClientRectWidth) {
					var iframes = currentDocument.querySelectorAll('iframe[src*="player.vimeo.com"]');

					[].forEach.call(iframes, function (item) {
						var src = item.src;
						var id = item.src.match(/.+\/([^\/\?]+)/)[1];
						var width = ($(item).width() > parentBoundingClientRectWidth) ? parentBoundingClientRectWidth : $(item).width() || parentBoundingClientRectWidth;
						var height = ($(item).width() > parentBoundingClientRectWidth) ? 0 | parentBoundingClientRectWidth * $(item).height() / $(item).width() : $(item).height() || 0 | width / 2;
						var thumbnail = "https://i.vimeocdn.com/video/" + id;
						var absolutePos = absolutePostion(item, parentBoundingClientRectTop, parentBoundingClientRectLeft);
						$(item).replaceWith("

");

						__mediaProperties.push({id:id, src:src, width:Number(width), height:Number(height), thumbnail:thumbnail, top:absolutePos[0], left:absolutePos[1]});
					});
				};

				//tvpot 관련 정보 추출 및 썸네일로 치환
				var replaceTvpot = function (currentDocument, parentBoundingClientRectTop, parentBoundingClientRectLeft, parentBoundingClientRectWidth) {
					var iframes = currentDocument.querySelectorAll('iframe[src*="videofarm.daum.net"]');
					var embeds = currentDocument.querySelectorAll('embed[src*="videofarm.daum.net"]');

					[].forEach.call(iframes, function (item) {
						var src = item.src;
						var id = item.src.match(/vid=([^&]+)/)[1];
						var width = ($(item).width() > parentBoundingClientRectWidth) ? parentBoundingClientRectWidth : $(item).width() || parentBoundingClientRectWidth;
						var height = ($(item).width() > parentBoundingClientRectWidth) ? 0 | parentBoundingClientRectWidth * $(item).height() / $(item).width() : $(item).height() || 0 | width / 2;
						var thumbnail = "http://i1.daumcdn.net/svc/image/U03/tvpot_thumb/" + id + "/thumb.png";
						var absolutePos = absolutePostion(item, parentBoundingClientRectTop, parentBoundingClientRectLeft);
						$(item).replaceWith("

");

						__mediaProperties.push({id:id, src:src, width:Number(width), height:Number(height), thumbnail:thumbnail, top:absolutePos[0], left:absolutePos[1]});
					});

					[].forEach.call(embeds, function (item) {
						var src = item.src;
						var id = item.flashvars.match(/vid=([^&]+)/)[1];
						var width = ($(item).width() > parentBoundingClientRectWidth) ? parentBoundingClientRectWidth : $(item).width() || parentBoundingClientRectWidth;
						var height = ($(item).width() > parentBoundingClientRectWidth) ? 0 | parentBoundingClientRectWidth * $(item).height() / $(item).width() : $(item).height() || 0 | width / 2;
						var thumbnail = "http://i1.daumcdn.net/svc/image/U03/tvpot_thumb/" + id + "/thumb.png";
						var absolutePos = absolutePostion(item, parentBoundingClientRectTop, parentBoundingClientRectLeft);
						$(item).replaceWith("

");

						__mediaProperties.push({id:id, src:src, width:Number(width), height:Number(height), thumbnail:thumbnail, top:absolutePos[0], left:absolutePos[1]});
					});
				};

				//동영상을 모두 썸네일로 치환하고 iframe을 찾아서 다시 반복 수행
				var iframeFinder = function (currentDocument, parentBoundingClientRectTop, parentBoundingClientRectLeft, parentBoundingClientRectWidth) {
					//현재 document 에서 플래시를 모두 제거
					removeFlash(currentDocument, parentBoundingClientRectWidth);
					//현재 document 에서 동영상을 모두 썸네일로 치환
					replaceVideo(currentDocument, parentBoundingClientRectTop, parentBoundingClientRectLeft, parentBoundingClientRectWidth);
					replaceYoutube(currentDocument, parentBoundingClientRectTop, parentBoundingClientRectLeft, parentBoundingClientRectWidth);
					replaceVimeo(currentDocument, parentBoundingClientRectTop, parentBoundingClientRectLeft, parentBoundingClientRectWidth);
					replaceTvpot(currentDocument, parentBoundingClientRectTop, parentBoundingClientRectLeft, parentBoundingClientRectWidth);

					//남아있는 iframe을 검출한 뒤,
					var iframes = currentDocument.querySelectorAll('iframe');

					//각 iframe마다 iframeFinder를 수행
					[].forEach.call(iframes, function (item) {
						//탐색할 iframe의 위치값 추출
						var childBoundingClientRect = item.getBoundingClientRect();
						//iframe 탐색
						iframeFinder(item.contentWindow.document, parentBoundingClientRectTop + childBoundingClientRect.top, parentBoundingClientRectLeft + childBoundingClientRect.left, childBoundingClientRect.width);
					});
				};

				//최상위 window의 body 위치값 추출
				var topBoundingClientRect = document.body.getBoundingClientRect();
				//현재 document부터 썸네일화 시작
				iframeFinder(document, topBoundingClientRect.top, topBoundingClientRect.left, topBoundingClientRect.width);

				//변환된 결과들 리턴
				return __mediaProperties;
			}, vars);

			//썸네일 로딩이 완료되는 타이밍을 고려해서 동영상 처리 완료
			window.setTimeout(function () {
				//동영상의 위치로 정렬하는 함수
				var comparePosition = function (a, b) {
					if (a.top  b.top) {
						return 1;
					}
					else {
						if (a.left  b.left) {
							return 1;
						}
						else {
							return 0;
						}
					}
				}

				//동영상의 절대 높이에 따라 정렬
				mediaProperties.sort(comparePosition);
				//동영상 관련 정보 저장
				vars.mediaProperties = mediaProperties;
				//Promise 성공
				resolve(vars);

			}, vars.thumbnailDownloadDuration);
		}
		else {
			//오류 리포트 생성
			vars.result = report.result("MOVI00", "페이지에 JQuery를 인젝션하는데 실패했습니다.");
			//실패 처리
			reject(vars);
		}
	});
};

module.exports = movies;


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

namespace Microsoft.Samples.WindowsAzure.ServiceManagement
{
    using System;
    using System.Collections.Generic;
    using System.Runtime.Serialization;

    [CollectionDataContract(Name = "Certificates", ItemName = "Certificate", Namespace = Constants.ServiceManagementNS)]
    public class CertificateList : List<Certificate>
    {
        public CertificateList()
        {
        }

        public CertificateList(IEnumerable<Certificate> certificateList)
            : base(certificateList)
        {
        }
    }

    [DataContract(Namespace = Constants.ServiceManagementNS)]
    public class Certificate : IExtensibleDataObject
    {
        [DataMember(Order = 1, EmitDefaultValue = false)]
        public Uri CertificateUrl { get; set; }

        [DataMember(Order = 2, EmitDefaultValue = false)]
        public string Thumbprint { get; set; }

        [DataMember(Order = 3, EmitDefaultValue = false)]
        public string ThumbprintAlgorithm { get; set; }

        [DataMember(Order = 4, EmitDefaultValue = false)]
        public string Data { get; set; }

        public ExtensionDataObject ExtensionData { get; set; }
    }

    [DataContract(Namespace = Constants.ServiceManagementNS)]
    public class SubscriptionCertificate : IExtensibleDataObject
    {
        [DataMember(Order = 1)]
        public string PublicKey { get; set; }

        [DataMember(Order = 2)]
        public string Thumbprint { get; set; }

        [DataMember(Order = 3)]
        public string Data { get; set; }

        public ExtensionDataObject ExtensionData { get; set; }
    }

    [DataContract(Namespace = Constants.ServiceManagementNS)]
    public class CertificateFile : IExtensibleDataObject
    {
        [DataMember(Order = 1)]
        public string Data { get; set; }

        [DataMember(Order = 2)]
        public string CertificateFormat { get; set; }

        [DataMember(Order = 3)]
        public string Password { get; set; }

        public ExtensionDataObject ExtensionData { get; set; }
    }
}


text:
package org.apache.cxf.jaxrs.swagger;

import io.swagger.jaxrs.ext.AbstractSwaggerExtension;
/**
 * Make application server classloaders happy.
 * Will be fixed in CXF 3.2
 */
public class JaxRs2Extension extends AbstractSwaggerExtension {
}


text:
package org.apache.rave.portal.model;

import com.google.common.collect.Maps;
import org.apache.rave.model.PageTemplate;
import org.apache.rave.model.PageTemplateRegion;
import org.apache.rave.model.PageTemplateWidget;
import org.apache.rave.portal.model.conversion.ConvertingListProxyFactory;
import org.apache.rave.portal.model.conversion.JpaConverter;

import javax.persistence.*;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Entity
@Table(name = "page_template_region")
@NamedQueries({
        @NamedQuery(name = "PageTemplateRegion.findAll", query = "SELECT p FROM JpaPageTemplateRegion p"),
        @NamedQuery(name = "PageTemplateRegion.findByPageTemplateRegionId", query = "SELECT p FROM JpaPageTemplateRegion p WHERE p.entityId = :id")
})
@Access(AccessType.FIELD)
public class JpaPageTemplateRegion implements BasicEntity, Serializable, PageTemplateRegion {
    private static final long serialVersionUID = 1L;

    @Id
    @Column(name="entity_id")
    @GeneratedValue(strategy = GenerationType.TABLE, generator = "pageTemplateRegionIdGenerator")
    @TableGenerator(name = "pageTemplateRegionIdGenerator", table = "RAVE_PORTAL_SEQUENCES", pkColumnName = "SEQ_NAME",
            valueColumnName = "SEQ_COUNT", pkColumnValue = "page_template_region", allocationSize = 1, initialValue = 1)
    private Long entityId;

    @Basic(optional = false)
    @Column(name = "render_sequence")
    private long renderSequence;

    @JoinColumn(name = "page_template_id")
    @ManyToOne(optional = false)
    private JpaPageTemplate pageTemplate;

    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
    @OrderBy("renderSequence")
    @JoinColumn(name = "page_template_region_id")
    private List<JpaPageTemplateWidget> pageTemplateWidgets;

    @Basic(optional = false)
    @Column(name = "locked")
    private boolean locked;

    @Override
    public Long getEntityId() {
        return entityId;
    }

    @Override
    public void setEntityId(Long entityId) {
        this.entityId = entityId;
    }

    @Override
    public String getId() {
        return this.getEntityId() == null ? null : this.getEntityId().toString();
    }

    @Override
    public long getRenderSequence() {
        return renderSequence;
    }

    @Override
    public void setRenderSequence(long renderSequence) {
        this.renderSequence = renderSequence;
    }

    @Override
    public JpaPageTemplate getPageTemplate() {
        return pageTemplate;
    }

    @Override
    public void setPageTemplate(PageTemplate pageTemplate) {
        this.pageTemplate = JpaConverter.getInstance().convert(pageTemplate, PageTemplate.class);
    }

    @Override
    public List<PageTemplateWidget> getPageTemplateWidgets() {
        return ConvertingListProxyFactory.createProxyList(PageTemplateWidget.class, this.pageTemplateWidgets);
    }

    @Override
    public void setPageTemplateWidgets(List<PageTemplateWidget> pageTemplateWidgets) {
        if(this.pageTemplateWidgets == null) {
            this.pageTemplateWidgets = new ArrayList<JpaPageTemplateWidget>();
        }
        this.getPageTemplateWidgets().clear();
        if(pageTemplateWidgets != null) {
            for(PageTemplateWidget widget : pageTemplateWidgets) {
                widget.setPageTemplateRegion(this);
                this.getPageTemplateWidgets().add(widget);
            }
        }
    }

    @Override
    public boolean isLocked() {
        return locked;
    }

    @Override
    public void setLocked(boolean locked) {
        this.locked = locked;
    }

    @Override
    public Map<String, Object> getProperties() {
        return Maps.newHashMap();
    }

    @Override
    public void setProperties(Map<String, Object> properties) {
        // TODO: Implement this
    }
}


text:
import { allStrategies } from '../../../resources/strategies'
import { allCrews } from '../../../resources/crews'

// ------------------------------------
// Constants
// ------------------------------------
export const LOAD_STRATEGIES = 'LOAD_STRATEGIES'
export const SELECT_CREW = 'SELECT_CREW'
export const UPDATE_FILTER = 'UPDATE_FILTER'

export const DEFAULT_CREW = { id: 'al', name: 'All' }

// ------------------------------------
// Actions
// ------------------------------------
export function loadStrategies () {
  return {
    type : LOAD_STRATEGIES
  }
}

export function selectCrew (crew = DEFAULT_CREW) {
  return {
    type : SELECT_CREW,
    crew : crew
  }
}

export function updateFilter (filter = '') {
  return {
    type: UPDATE_FILTER,
    filter: filter
  }
}

export const actions = {
  loadStrategies,
  selectCrew,
  updateFilter
}

// ------------------------------------
// Action Handlers
// ------------------------------------
const ACTION_HANDLERS = {
  [LOAD_STRATEGIES]    : (state, action) => {
    let fullCrews = [ DEFAULT_CREW, ...allCrews ]
    return Object.assign({}, state, {
      allStrategies: allStrategies,
      strategies: allStrategies,
      allCrews: fullCrews,
      crew: fullCrews[0]
    })
  },
  [SELECT_CREW] : (state, action) => {
    let crew = action.crew
    if (typeof (crew) === 'string') {
      if (crew.length === 0) {
        console.log('Invalid crew string provided. Length was 0.')
        return state
      }
      try {
        crew = JSON.parse(crew)
      } catch (e) {
        console.log('Invalid crew string provided. Error: ' + e.msg)
        console.log(e)
        return state
      }
    }
    if (crew === undefined) {
      crew = DEFAULT_CREW
    }
    let crewId = crew.id
    let resultStrategies
    if (crewId !== 'al') {
      resultStrategies = state.allStrategies.reduce((result, strat) => {
        if (strat.crews !== undefined) {
          if (strat.crews.indexOf(crewId) !== -1) {
            result.push(strat)
          }
        } else {
          result.push(strat)
        }
        return result
      }, [])
    } else {
      resultStrategies = [...state.allStrategies]
    }
    return Object.assign({}, state, {
      crew: crew,
      strategies: resultStrategies
    })
  },
  [UPDATE_FILTER]: (state, action) => {
    let filter = action.filter
    let lowerFilter = filter.toLowerCase()

    let newStrategies = state.allStrategies.reduce((resultStrategies, strategy) => {
      if (strategy.name.toLowerCase().indexOf(lowerFilter) !== -1 || strategy.text.toLowerCase().indexOf(lowerFilter) !== -1) {
        resultStrategies.push(strategy)
      }
      return resultStrategies
    }, [])

    let searchParams = new URLSearchParams()
    searchParams.append('filter', filter)
    history.pushState({}, '', location.origin + location.pathname + '?' + searchParams)

    return Object.assign({}, state, {
      strategies: newStrategies,
      crew: DEFAULT_CREW
    })
  }
}

// ------------------------------------
// Reducer
// ------------------------------------
const initialState = {
  allStrategies: allStrategies,
  strategies: allStrategies,
  allCrews: [ DEFAULT_CREW, ...allCrews ],
  crew: DEFAULT_CREW
}
export default function strategiesReducer (state = initialState, action) {
  const handler = ACTION_HANDLERS[action.type]

  return handler ? handler(state, action) : state
}


text:
angular.module('plan').controller('DeliveryFormController', ['$scope', '$location', 'delivery', 'AngularDataStore',
    function ($scope, $location, delivery, AngularDataStore) {
        if (delivery.locked) {
            throw Error('delivery locked');
        }

        $scope.delivery = delivery;

        $scope.save = function () {
            AngularDataStore.save($scope.delivery);
            $location.path('/delivery');
        };
    }
]);