text:
using blink::WebInputEvent;
using blink::WebKeyboardEvent;
using blink::WebMouseEvent;
using blink::WebMouseWheelEvent;

namespace content {

static const unsigned long kDefaultScrollLinesPerWheelDelta = 3;
static const unsigned long kDefaultScrollCharsPerWheelDelta = 1;

WebKeyboardEvent WebKeyboardEventBuilder::Build(HWND hwnd,
                                                UINT message,
                                                WPARAM wparam,
                                                LPARAM lparam,
                                                double time_stamp) {
  WebKeyboardEvent result;

  result.timeStampSeconds = time_stamp;

  result.windowsKeyCode = static_cast<int>(wparam);
  // Record the scan code (along with other context bits) for this key event.
  result.nativeKeyCode = static_cast<int>(lparam);

  switch (message) {
  case WM_SYSKEYDOWN:
    result.isSystemKey = true;
  case WM_KEYDOWN:
    result.type = WebInputEvent::RawKeyDown;
    break;
  case WM_SYSKEYUP:
    result.isSystemKey = true;
  case WM_KEYUP:
    result.type = WebInputEvent::KeyUp;
    break;
  case WM_IME_CHAR:
    result.type = WebInputEvent::Char;
    break;
  case WM_SYSCHAR:
    result.isSystemKey = true;
    result.type = WebInputEvent::Char;
  case WM_CHAR:
    result.type = WebInputEvent::Char;
    break;
  default:
    NOTREACHED();
  }

  if (result.type == WebInputEvent::Char
   || result.type == WebInputEvent::RawKeyDown) {
    result.text[0] = result.windowsKeyCode;
    result.unmodifiedText[0] = result.windowsKeyCode;
  }
  result.setKeyIdentifierFromWindowsKeyCode();

  result.modifiers =
      ui::EventFlagsToWebEventModifiers(ui::GetModifiersFromKeyState());
  // NOTE: There doesn't seem to be a way to query the mouse button state in
  // this case.

  // Bit 30 of lParam represents the "previous key state". If set, the key was
  // already down, therefore this is an auto-repeat. Only apply this to key
  // down events, to match DOM semantics.
  if ((result.type == WebInputEvent::RawKeyDown) && (lparam & 0x40000000))
    result.modifiers |= WebInputEvent::IsAutoRepeat;

  return result;
}

// WebMouseEvent --------------------------------------------------------------

static int g_last_click_count = 0;
static double g_last_click_time = 0;

static LPARAM GetRelativeCursorPos(HWND hwnd) {
  POINT pos = {-1, -1};
  GetCursorPos(&pos);
  ScreenToClient(hwnd, &pos);
  return MAKELPARAM(pos.x, pos.y);
}

WebMouseEvent WebMouseEventBuilder::Build(
    HWND hwnd,
    UINT message,
    WPARAM wparam,
    LPARAM lparam,
    double time_stamp,
    blink::WebPointerProperties::PointerType pointer_type) {
  WebMouseEvent result;

  switch (message) {
  case WM_MOUSEMOVE:
    result.type = WebInputEvent::MouseMove;
    if (wparam & MK_LBUTTON)
      result.button = WebMouseEvent::ButtonLeft;
    else if (wparam & MK_MBUTTON)
      result.button = WebMouseEvent::ButtonMiddle;
    else if (wparam & MK_RBUTTON)
      result.button = WebMouseEvent::ButtonRight;
    else
      result.button = WebMouseEvent::ButtonNone;
    break;
  case WM_MOUSELEAVE:
  case WM_NCMOUSELEAVE:
    // TODO(rbyers): This should be MouseLeave but is disabled temporarily.
    // See http://crbug.com/450631
    result.type = WebInputEvent::MouseMove;
    result.button = WebMouseEvent::ButtonNone;
    // set the current mouse position (relative to the client area of the
    // current window) since none is specified for this event
    lparam = GetRelativeCursorPos(hwnd);
    break;
  case WM_LBUTTONDOWN:
  case WM_LBUTTONDBLCLK:
    result.type = WebInputEvent::MouseDown;
    result.button = WebMouseEvent::ButtonLeft;
    break;
  case WM_MBUTTONDOWN:
  case WM_MBUTTONDBLCLK:
    result.type = WebInputEvent::MouseDown;
    result.button = WebMouseEvent::ButtonMiddle;
    break;
  case WM_RBUTTONDOWN:
  case WM_RBUTTONDBLCLK:
    result.type = WebInputEvent::MouseDown;
    result.button = WebMouseEvent::ButtonRight;
    break;
  case WM_LBUTTONUP:
    result.type = WebInputEvent::MouseUp;
    result.button = WebMouseEvent::ButtonLeft;
    break;
  case WM_MBUTTONUP:
    result.type = WebInputEvent::MouseUp;
    result.button = WebMouseEvent::ButtonMiddle;
    break;
  case WM_RBUTTONUP:
    result.type = WebInputEvent::MouseUp;
    result.button = WebMouseEvent::ButtonRight;
    break;
  default:
    NOTREACHED();
  }

  result.timeStampSeconds = time_stamp;
  result.pointerType = pointer_type;

  // set position fields:

  result.x = static_cast<short>(LOWORD(lparam));
  result.y = static_cast<short>(HIWORD(lparam));
  result.windowX = result.x;
  result.windowY = result.y;

  POINT global_point = { result.x, result.y };
  ClientToScreen(hwnd, &global_point);

  // We need to convert the global point back to DIP before using it.
  gfx::Point dip_global_point = display::win::ScreenWin::ScreenToDIPPoint(
      gfx::Point(global_point.x, global_point.y));

  result.globalX = dip_global_point.x();
  result.globalY = dip_global_point.y();

  // calculate number of clicks:

  // This differs slightly from the WebKit code in WebKit/win/WebView.cpp
  // where their original code looks buggy.
  static int last_click_position_x;
  static int last_click_position_y;
  static WebMouseEvent::Button last_click_button = WebMouseEvent::ButtonLeft;

  double current_time = result.timeStampSeconds;
  bool cancel_previous_click =
      (abs(last_click_position_x - result.x) >
          (::GetSystemMetrics(SM_CXDOUBLECLK) / 2))
      || (abs(last_click_position_y - result.y) >
          (::GetSystemMetrics(SM_CYDOUBLECLK) / 2))
      || ((current_time - g_last_click_time) * 1000.0 > ::GetDoubleClickTime());

  if (result.type == WebInputEvent::MouseDown) {
    if (!cancel_previous_click && (result.button == last_click_button)) {
      ++g_last_click_count;
    } else {
      g_last_click_count = 1;
      last_click_position_x = result.x;
      last_click_position_y = result.y;
    }
    g_last_click_time = current_time;
    last_click_button = result.button;
  } else if (result.type == WebInputEvent::MouseMove
          || result.type == WebInputEvent::MouseLeave) {
    if (cancel_previous_click) {
      g_last_click_count = 0;
      last_click_position_x = 0;
      last_click_position_y = 0;
      g_last_click_time = 0;
    }
  }
  result.clickCount = g_last_click_count;

  // set modifiers:
  result.modifiers =
      ui::EventFlagsToWebEventModifiers(ui::GetModifiersFromKeyState());
  if (wparam & MK_CONTROL)
    result.modifiers |= WebInputEvent::ControlKey;
  if (wparam & MK_SHIFT)
    result.modifiers |= WebInputEvent::ShiftKey;
  if (wparam & MK_LBUTTON)
    result.modifiers |= WebInputEvent::LeftButtonDown;
  if (wparam & MK_MBUTTON)
    result.modifiers |= WebInputEvent::MiddleButtonDown;
  if (wparam & MK_RBUTTON)
    result.modifiers |= WebInputEvent::RightButtonDown;

  return result;
}

// WebMouseWheelEvent ---------------------------------------------------------

WebMouseWheelEvent WebMouseWheelEventBuilder::Build(
    HWND hwnd,
    UINT message,
    WPARAM wparam,
    LPARAM lparam,
    double time_stamp,
    blink::WebPointerProperties::PointerType pointer_type) {
  WebMouseWheelEvent result;

  result.type = WebInputEvent::MouseWheel;

  result.timeStampSeconds = time_stamp;

  result.button = WebMouseEvent::ButtonNone;

  result.pointerType = pointer_type;

  // Get key state, coordinates, and wheel delta from event.
  UINT key_state;
  float wheel_delta;
  bool horizontal_scroll = false;
  if ((message == WM_VSCROLL) || (message == WM_HSCROLL)) {
    // Synthesize mousewheel event from a scroll event.  This is needed to
    // simulate middle mouse scrolling in some laptops.  Use GetAsyncKeyState
    // for key state since we are synthesizing the input event.
    key_state = 0;
    if (GetAsyncKeyState(VK_SHIFT) & 0x8000)
      key_state |= MK_SHIFT;
    if (GetAsyncKeyState(VK_CONTROL) & 0x8000)
      key_state |= MK_CONTROL;
    // NOTE: There doesn't seem to be a way to query the mouse button state
    // in this case.

    POINT cursor_position = {0};
    GetCursorPos(&cursor_position);
    result.globalX = cursor_position.x;
    result.globalY = cursor_position.y;

    switch (LOWORD(wparam)) {
      case SB_LINEUP:    // == SB_LINELEFT
        wheel_delta = WHEEL_DELTA;
        break;
      case SB_LINEDOWN:  // == SB_LINERIGHT
        wheel_delta = -WHEEL_DELTA;
        break;
      case SB_PAGEUP:
        wheel_delta = 1;
        result.scrollByPage = true;
        break;
      case SB_PAGEDOWN:
        wheel_delta = -1;
        result.scrollByPage = true;
        break;
      default:  // We don't supoprt SB_THUMBPOSITION or SB_THUMBTRACK here.
        wheel_delta = 0;
        break;
    }

    if (message == WM_HSCROLL)
      horizontal_scroll = true;
  } else {
    // Non-synthesized event; we can just read data off the event.
    key_state = GET_KEYSTATE_WPARAM(wparam);

    result.globalX = static_cast<short>(LOWORD(lparam));
    result.globalY = static_cast<short>(HIWORD(lparam));

    // Currently we leave hasPreciseScrollingDeltas false, even for trackpad
    // scrolls that generate WM_MOUSEWHEEL, since we don't have a good way to
    // distinguish these from real mouse wheels (crbug.com/545234).
    wheel_delta = static_cast<float>(GET_WHEEL_DELTA_WPARAM(wparam));

    if (message == WM_MOUSEHWHEEL) {
      horizontal_scroll = true;
      wheel_delta = -wheel_delta;  // Windows is <- -/+ ->, WebKit <- +/- ->.
    }
  }
  if (key_state & MK_SHIFT)
    horizontal_scroll = true;

  // Set modifiers based on key state.
  result.modifiers =
      ui::EventFlagsToWebEventModifiers(ui::GetModifiersFromKeyState());
  if (key_state & MK_SHIFT)
    result.modifiers |= WebInputEvent::ShiftKey;
  if (key_state & MK_CONTROL)
    result.modifiers |= WebInputEvent::ControlKey;
  if (key_state & MK_LBUTTON)
    result.modifiers |= WebInputEvent::LeftButtonDown;
  if (key_state & MK_MBUTTON)
    result.modifiers |= WebInputEvent::MiddleButtonDown;
  if (key_state & MK_RBUTTON)
    result.modifiers |= WebInputEvent::RightButtonDown;

  // Set coordinates by translating event coordinates from screen to client.
  POINT client_point = { result.globalX, result.globalY };
  MapWindowPoints(0, hwnd, &client_point, 1);
  result.x = client_point.x;
  result.y = client_point.y;
  result.windowX = result.x;
  result.windowY = result.y;

  // Convert wheel delta amount to a number of pixels to scroll.
  //
  // How many pixels should we scroll per line?  Gecko uses the height of the
  // current line, which means scroll distance changes as you go through the
  // page or go to different pages.  IE 8 is ~60 px/line, although the value
  // seems to vary slightly by page and zoom level.  Also, IE defaults to
  // smooth scrolling while Firefox doesn't, so it can get away with somewhat
  // larger scroll values without feeling as jerky.  Here we use 100 px per
  // three lines (the default scroll amount is three lines per wheel tick).
  // Even though we have smooth scrolling, we don't make this as large as IE
  // because subjectively IE feels like it scrolls farther than you want while
  // reading articles.
  static const float kScrollbarPixelsPerLine = 100.0f / 3.0f;
  wheel_delta /= WHEEL_DELTA;
  float scroll_delta = wheel_delta;
  if (horizontal_scroll) {
    unsigned long scroll_chars = kDefaultScrollCharsPerWheelDelta;
    SystemParametersInfo(SPI_GETWHEELSCROLLCHARS, 0, &scroll_chars, 0);
    // TODO(pkasting): Should probably have a different multiplier
    // scrollbarPixelsPerChar here.
    scroll_delta *= static_cast<float>(scroll_chars) * kScrollbarPixelsPerLine;
  } else {
    unsigned long scroll_lines = kDefaultScrollLinesPerWheelDelta;
    SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0, &scroll_lines, 0);
    if (scroll_lines == WHEEL_PAGESCROLL)
      result.scrollByPage = true;
    if (!result.scrollByPage) {
      scroll_delta *=
          static_cast<float>(scroll_lines) * kScrollbarPixelsPerLine;
    }
  }

  // Set scroll amount based on above calculations.  WebKit expects positive
  // deltaY to mean "scroll up" and positive deltaX to mean "scroll left".
  if (horizontal_scroll) {
    result.deltaX = scroll_delta;
    result.wheelTicksX = wheel_delta;
  } else {
    result.deltaY = scroll_delta;
    result.wheelTicksY = wheel_delta;
  }

  return result;
}

}  // namespace content


text:
<?php

namespace Google\Service\Script;

class ScriptExecutionResult extends \Google\Model
{
  protected $returnValueType = Value::class;
  protected $returnValueDataType = '';

  /**
   * @param Value
   */
  public function setReturnValue(Value $returnValue)
  {
    $this->returnValue = $returnValue;
  }
  /**
   * @return Value
   */
  public function getReturnValue()
  {
    return $this->returnValue;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(ScriptExecutionResult::class, 'Google_Service_Script_ScriptExecutionResult');

redpajama_set_name: RedPajamaGithub


text:
package org.maltparserx.core.propagation;

import java.util.SortedSet;
import java.util.TreeSet;
import java.util.regex.Pattern;

import org.maltparserx.core.exception.MaltChainedException;
import org.maltparserx.core.io.dataformat.ColumnDescription;
import org.maltparserx.core.io.dataformat.DataFormatInstance;
import org.maltparserx.core.propagation.spec.PropagationSpec;
import org.maltparserx.core.symbol.SymbolTable;
import org.maltparserx.core.syntaxgraph.edge.Edge;
import org.maltparserx.core.syntaxgraph.node.DependencyNode;

/**
 * A propagation object propagate a column value from one node to a column in another node based on the propagation specification.
 *
 * @author Johan Hall
 *
 */
public class Propagation {
	/**
	 *
	 */
	private SymbolTable fromTable;
	private SymbolTable toTable;
	private SymbolTable deprelTable;
	private SortedSet<String> forSet;
	private SortedSet<String> overSet;

	private Pattern symbolSeparator;

	/**
	 * Creates a propagation object based on the propagation specification
	 *
	 * @param spec a propagation specification
	 * @param dataFormatInstance a data format instance
	 * @throws MaltChainedException
	 */
	public Propagation(PropagationSpec spec, DataFormatInstance dataFormatInstance) throws MaltChainedException {
		ColumnDescription fromColumn = dataFormatInstance.getColumnDescriptionByName(spec.getFrom());
		if (fromColumn == null) {
			throw new PropagationException("The symbol table '"+spec.getFrom()+" does not exists.");
		}
		fromTable = fromColumn.getSymbolTable();

		ColumnDescription toColumn = dataFormatInstance.getColumnDescriptionByName(spec.getTo());
		if (toColumn == null) {
			toColumn = dataFormatInstance.addInternalColumnDescription(spec.getTo(), fromColumn);
			toTable = toColumn.getSymbolTable();
		}

		forSet = new TreeSet<String>();
		if (spec.getFor() != null && spec.getFor().length() > 0) {
			String[] items = spec.getFor().split("\\|");

			for (String item : items) {
				forSet.add(item);
			}
		}

		overSet = new TreeSet<String>();
		if (spec.getOver() != null && spec.getOver().length() > 0) {
			String[] items = spec.getOver().split("\\|");

			for (String item : items) {
				overSet.add(item);
			}
		}

		ColumnDescription deprelColumn = dataFormatInstance.getColumnDescriptionByName("DEPREL");
		deprelTable = deprelColumn.getSymbolTable();
		symbolSeparator = Pattern.compile("\\|");
	}

	/**
	 * Propagate columns according to the propagation specification
	 *
	 * @param e an edge
	 * @throws MaltChainedException
	 */
	public void propagate(Edge e) throws MaltChainedException {
		if (e != null && e.hasLabel(deprelTable) && !e.getSource().isRoot()) {
			if (overSet.size() == 0 || overSet.contains(e.getLabelSymbol(deprelTable))) {
				DependencyNode to = (DependencyNode)e.getSource();
				DependencyNode from = (DependencyNode)e.getTarget();
				String fromSymbol = null;
				if (e.hasLabel(fromTable)) {
					fromSymbol = e.getLabelSymbol(fromTable);
				} else if (from.hasLabel(fromTable)) {
					fromSymbol = from.getLabelSymbol(fromTable);
				}

				String propSymbol = null;
				if (to.hasLabel(toTable)) {
					propSymbol = union(fromSymbol, to.getLabelSymbol(toTable));
				} else {
					if (forSet.size() == 0 || forSet.contains(fromSymbol)) {
						propSymbol = fromSymbol;
					}
				}
				if (propSymbol != null) {
					to.addLabel(toTable, propSymbol);
				}
			}
		}
	}

	private String union(String fromSymbol, String toSymbol) {
		SortedSet<String> symbolSet = new TreeSet<String>();

		if (fromSymbol != null && fromSymbol.length() != 0) {
			String[] fromSymbols = symbolSeparator.split(fromSymbol);
			for (int i = 0; i < fromSymbols.length; i++) {
				if (forSet.size() == 0 || forSet.contains(fromSymbols[i])) {
					symbolSet.add(fromSymbols[i]);
				}
			}
		}
		if (toSymbol != null && toSymbol.length() != 0) {
			String[] toSymbols = symbolSeparator.split(toSymbol);
			for (int i = 0; i < toSymbols.length; i++) {
				symbolSet.add(toSymbols[i]);
			}
		}

		if (symbolSet.size() > 0) {
			StringBuilder sb = new StringBuilder();
			for (String symbol : symbolSet) {
				sb.append(symbol);
				sb.append('|');
			}
			sb.setLength(sb.length()-1);
			return sb.toString();
		}

		return "";
	}
	@Override
	public String toString() {
		return "Propagation [forSet=" + forSet + ", fromTable=" + fromTable
				+ ", overSet=" + overSet + ", toTable=" + toTable + "]";
	}
}


text:
<?php

namespace Doctrine\DBAL\Schema;

use Doctrine\DBAL\Event\SchemaIndexDefinitionEventArgs;
use Doctrine\DBAL\Events;

/**
 * IBM Db2 Schema Manager for iSeries
 *
 * @link        www.doctrine-project.com
 * @since       2.5
 * @author      Benjamin Eberlei <kontakt@beberlei.de>
 */
class DB2iSeriesSchemaManager extends AbstractSchemaManager {

    /**
     * Return a list of all tables in the current database
     *
     * Apparently creator is the schema not the user who created it:
     * {@link http://publib.boulder.ibm.com/infocenter/dzichelp/v2r2/index.jsp?topic=/com.ibm.db29.doc.sqlref/db2z_sysibmsystablestable.htm}
     *
     * @return array
     */
    public function listTableNames()
    {
        $sql = $this->_platform->getListTablesSQL($this->_conn->getDatabase());
       /*
        * Some times can't garantee all tables are created using the same user
       */
       //$sql .= " AND TABLE_OWNER = UPPER('".$this->_conn->getUsername()."')";

        $tables = $this->_conn->fetchAll($sql);

        return $this->_getPortableTablesList($tables);
    }

    /**
     * Get Table Column Definition
     *
     * @param array $tableColumn
     * @return Column
     */
    protected function _getPortableTableColumnDefinition($tableColumn)
    {
        $tableColumn = array_change_key_case($tableColumn, \CASE_LOWER);

        $length = null;
        $fixed = null;
        $unsigned = false;
        $scale = false;
        $precision = false;

        $type = $this->_platform->getDoctrineTypeMapping($tableColumn['typename']);

        switch (strtolower($tableColumn['typename'])) {
            case 'varchar':
                $length = $tableColumn['length'];
                $fixed = false;
                break;
            case 'character':
                $length = $tableColumn['length'];
                $fixed = true;
                break;
            case 'clob':
                $length = $tableColumn['length'];
                break;
            case 'decimal':
            case 'double':
            case 'real':
                $scale = $tableColumn['scale'];
                $precision = $tableColumn['length'];
                break;
        }

        $options = array(
            'length' => $length,
            'unsigned' => (bool) $unsigned,
            'fixed' => (bool) $fixed,
            'default' => ($tableColumn['default'] == "NULL") ? null : $tableColumn['default'],
            'notnull' => (bool) ($tableColumn['nulls'] == 'N'),
            'scale' => null,
            'precision' => null,
            'platformOptions' => array(),
            'autoincrement' => ($tableColumn['identity'] == "Y") ? true : false,
        );

        if ($scale !== null && $precision !== null) {
            $options['scale'] = $scale;
            $options['precision'] = $precision;
        }

        return new Column($tableColumn['colname'], \Doctrine\DBAL\Types\Type::getType($type), $options);
    }

    protected function _getPortableTablesList($tables)
    {
        $tableNames = array();
        foreach ($tables as $tableRow) {
            $tableRow = array_change_key_case($tableRow, \CASE_LOWER);
            $tableNames[] = $tableRow['table_name'];
        }
        return $tableNames;
    }

    protected function _getPortableTableIndexesList($tableIndexes, $tableName = null)
    {
        $eventManager = $this->_platform->getEventManager();

        $indexes = array();
        foreach ($tableIndexes as $indexKey => $data) {
            $data = array_change_key_case($data, \CASE_LOWER);
            $unique = ($data['uniquerule'] == "D") ? false : true;
            $primary = ($data['uniquerule'] == "P");

            $indexName = strtolower($data['name']);
            if ($primary) {
                $keyName = 'primary';
            } else {
                $keyName = $indexName;
            }

            $data = array(
                'name' => $indexName,
                'columns' => explode("+", ltrim($data['colnames'], '+')),
                'unique' => $unique,
                'primary' => $primary
            );

            $index = null;
            $defaultPrevented = false;

            if (null !== $eventManager && $eventManager->hasListeners(Events::onSchemaIndexDefinition)) {
                $eventArgs = new SchemaIndexDefinitionEventArgs($data, $tableName, $this->_conn);
                $eventManager->dispatchEvent(Events::onSchemaIndexDefinition, $eventArgs);

                $defaultPrevented = $eventArgs->isDefaultPrevented();
                $index = $eventArgs->getIndex();
            }

            if (!$defaultPrevented) {
                $index = new Index($data['name'], $data['columns'], $data['unique'], $data['primary']);
            }

            if ($index) {
                $indexes[$indexKey] = $index;
            }
        }

        return $indexes;
    }

    protected function _getPortableTableForeignKeyDefinition($tableForeignKey)
    {
        $tableForeignKey = array_change_key_case($tableForeignKey, CASE_LOWER);

        $tableForeignKey['deleterule'] = $this->_getPortableForeignKeyRuleDef($tableForeignKey['deleterule']);
        $tableForeignKey['updaterule'] = $this->_getPortableForeignKeyRuleDef($tableForeignKey['updaterule']);

        return new ForeignKeyConstraint(
                array_map('trim', (array) $tableForeignKey['fkcolnames']), $tableForeignKey['reftbname'], array_map('trim', (array) $tableForeignKey['pkcolnames']), $tableForeignKey['relname'], array(
            'onUpdate' => $tableForeignKey['updaterule'],
            'onDelete' => $tableForeignKey['deleterule'],
                )
        );
    }

    protected function _getPortableForeignKeyRuleDef($def)
    {
        if ($def == "C") {
            return "CASCADE";
        } else if ($def == "N") {
            return "SET NULL";
        }
        return null;
    }

    protected function _getPortableViewDefinition($view)
    {
        $view = array_change_key_case($view, \CASE_LOWER);
        // sadly this still segfaults on PDO_IBM, see http://pecl.php.net/bugs/bug.php?id=17199
        //$view['text'] = (is_resource($view['text']) ? stream_get_contents($view['text']) : $view['text']);
        if (!is_resource($view['text'])) {
            $pos = strpos($view['text'], ' AS ');
            $sql = substr($view['text'], $pos + 4);
        } else {
            $sql = '';
        }

        return new View($view['name'], $sql);
    }

}


text:
#ifndef LULLABY_SYSTEMS_RENDER_FILAMENT_FILAMENT_UTILS_H_
#define LULLABY_SYSTEMS_RENDER_FILAMENT_FILAMENT_UTILS_H_

#include "filament/Color.h"
#include "filament/TextureSampler.h"
#include "math/mat4.h"
#include "math/vec3.h"
#include "lullaby/generated/flatbuffers/texture_def_generated.h"
#include "lullaby/generated/texture_def_generated.h"
#include "mathfu/glsl_mappings.h"

namespace lull {

template <typename T>
using FilamentResourcePtr = std::unique_ptr<T, std::function<void(T*)>>;

inline filament::LinearColor ToLinearColor(const mathfu::vec4& src) {
  return filament::LinearColor{src.x, src.y, src.z};
}

inline filament::LinearColorA ToLinearColorA(const mathfu::vec4& src) {
  return filament::LinearColorA{src.x, src.y, src.z, src.w};
}

inline filament::math::float3 FilamentFloat3FromMathfuVec3(
    const mathfu::vec3& src) {
  return {src.x, src.y, src.z};
}

inline filament::math::float4 FilamentFloat4FromMathfuVec4(
    const mathfu::vec4& src) {
  return {src.x, src.y, src.z, src.w};
}

inline filament::TextureSampler::MinFilter ToFilamentMinFilter(
    TextureFiltering filter) {
  switch (filter) {
    case TextureFiltering_Nearest:
      return filament::TextureSampler::MinFilter::NEAREST;
    case TextureFiltering_Linear:
      return filament::TextureSampler::MinFilter::LINEAR;
    case TextureFiltering_NearestMipmapNearest:
      return filament::TextureSampler::MinFilter::NEAREST_MIPMAP_NEAREST;
    case TextureFiltering_LinearMipmapNearest:
      return filament::TextureSampler::MinFilter::LINEAR_MIPMAP_NEAREST;
    case TextureFiltering_NearestMipmapLinear:
      return filament::TextureSampler::MinFilter::NEAREST_MIPMAP_LINEAR;
    case TextureFiltering_LinearMipmapLinear:
      return filament::TextureSampler::MinFilter::LINEAR_MIPMAP_LINEAR;
  }
}

inline filament::TextureSampler::MagFilter ToFilamentMagFilter(
    TextureFiltering filter) {
  switch (filter) {
    case TextureFiltering_Nearest:
      return filament::TextureSampler::MagFilter::NEAREST;
    case TextureFiltering_Linear:
      return filament::TextureSampler::MagFilter::LINEAR;
    case TextureFiltering_NearestMipmapNearest:
      return filament::TextureSampler::MagFilter::NEAREST;
    case TextureFiltering_LinearMipmapNearest:
      return filament::TextureSampler::MagFilter::NEAREST;
    case TextureFiltering_NearestMipmapLinear:
      return filament::TextureSampler::MagFilter::LINEAR;
    case TextureFiltering_LinearMipmapLinear:
      return filament::TextureSampler::MagFilter::LINEAR;
  }
}

inline filament::TextureSampler::WrapMode ToFilamentWrapMode(TextureWrap wrap) {
  switch (wrap) {
    case TextureWrap_Repeat:
      return filament::TextureSampler::WrapMode::REPEAT;
    case TextureWrap_MirroredRepeat:
      return filament::TextureSampler::WrapMode::MIRRORED_REPEAT;
    case TextureWrap_ClampToBorder:
      return filament::TextureSampler::WrapMode::CLAMP_TO_EDGE;
    case TextureWrap_ClampToEdge:
      return filament::TextureSampler::WrapMode::CLAMP_TO_EDGE;
    case TextureWrap_MirrorClampToEdge:
      return filament::TextureSampler::WrapMode::CLAMP_TO_EDGE;
  }
}

inline filament::math::mat4f MathFuMat4ToFilamentMat4f(
    const mathfu::mat4& src) {
  return filament::math::mat4f{
      filament::math::float4{src[0], src[1], src[2], src[3]},
      filament::math::float4{src[4], src[5], src[6], src[7]},
      filament::math::float4{src[8], src[9], src[10], src[11]},
      filament::math::float4{src[12], src[13], src[14], src[15]}};
}

inline filament::math::mat4 MathFuMat4ToFilamentMat4(const mathfu::mat4& src) {
  return filament::math::mat4{
      filament::math::float4{src[0], src[1], src[2], src[3]},
      filament::math::float4{src[4], src[5], src[6], src[7]},
      filament::math::float4{src[8], src[9], src[10], src[11]},
      filament::math::float4{src[12], src[13], src[14], src[15]}};
}

}  // namespace lull

#endif  // LULLABY_SYSTEMS_RENDER_FILAMENT_FILAMENT_UTILS_H_


text:
layout: default
---

{{ page.title }}

                    {% if page.subtitle %}
                    {% comment %}
                        always create a h2 for keeping the margin , Hux
                    {% endcomment %}
                    {% comment %} if page.subtitle {% endcomment %}

{{ page.subtitle }}

                    {% endif %}
                    Posted by {% if page.author %}{{ page.author }}{% else %}{{ site.title }}{% endif %} on {{ page.date | date: "%B %-d, %Y" }}

				{{ content }}

                    {% if page.previous.url %}

                        ← Previous Post

                    {% endif %}
                    {% if page.next.url %}

                        Next Post →

                    {% endif %}


text:
/**
18 Concepts Library
18.7 Callable Concepts
18.7.7 Concept strict_weak_order
2 The term strict refers to the requirement of an irreflexive relation (!comp(x,
x) for all x), and the term weak to requirements that are not as strong as those
for a total ordering, but stronger than those for a partial ordering. If we
define equiv(a, b) as !comp(a, b) && !comp(b, a), then the requirements are that
comp and equiv both be transitive relations:

https://eel.is/c++draft/concept.strictweakorder#2
*/

#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <vector>

int main() {
    // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers,readability-magic-numbers)
    std::vector<int> my_vec{{5, 3, 2, 1, 7}};
    std::sort(my_vec.begin(), my_vec.end(), std::less<>());
    for (const int value : my_vec) {
        // Avoid iostream because a lack of instrumentation may produce false
        // positives for libc++ with memory sanitizer
        // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
        printf("%d, ", value);
    }
    // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
    printf("\n");
    return EXIT_SUCCESS;
}


text:
package com.amazonaws.services.workspaces.model.transform;

import java.io.ByteArrayInputStream;
import java.util.Collections;
import java.util.Map;
import java.util.List;
import java.util.regex.Pattern;

import com.amazonaws.AmazonClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.workspaces.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.BinaryUtils;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.IdempotentUtils;
import com.amazonaws.util.StringInputStream;
import com.amazonaws.util.json.*;

/**
 * CreateWorkspacesRequest Marshaller
 */
public class CreateWorkspacesRequestMarshaller implements
        Marshaller<Request<CreateWorkspacesRequest>, CreateWorkspacesRequest> {

    public Request<CreateWorkspacesRequest> marshall(
            CreateWorkspacesRequest createWorkspacesRequest) {

        if (createWorkspacesRequest == null) {
            throw new AmazonClientException(
                    "Invalid argument passed to marshall(...)");
        }

        Request<CreateWorkspacesRequest> request = new DefaultRequest<CreateWorkspacesRequest>(
                createWorkspacesRequest, "AmazonWorkspaces");
        request.addHeader("X-Amz-Target", "WorkspacesService.CreateWorkspaces");

        request.setHttpMethod(HttpMethodName.POST);

        request.setResourcePath("");

        try {
            final StructuredJsonGenerator jsonGenerator = SdkJsonProtocolFactory
                    .createWriter(false, "1.1");

            jsonGenerator.writeStartObject();

            com.amazonaws.internal.SdkInternalList<WorkspaceRequest> workspacesList = (com.amazonaws.internal.SdkInternalList<WorkspaceRequest>) createWorkspacesRequest
                    .getWorkspaces();
            if (!workspacesList.isEmpty() || !workspacesList.isAutoConstruct()) {
                jsonGenerator.writeFieldName("Workspaces");
                jsonGenerator.writeStartArray();
                for (WorkspaceRequest workspacesListValue : workspacesList) {
                    if (workspacesListValue != null) {

                        WorkspaceRequestJsonMarshaller.getInstance().marshall(
                                workspacesListValue, jsonGenerator);
                    }
                }
                jsonGenerator.writeEndArray();
            }

            jsonGenerator.writeEndObject();

            byte[] content = jsonGenerator.getBytes();
            request.setContent(new ByteArrayInputStream(content));
            request.addHeader("Content-Length",
                    Integer.toString(content.length));
            request.addHeader("Content-Type", jsonGenerator.getContentType());
        } catch (Throwable t) {
            throw new AmazonClientException(
                    "Unable to marshall request to JSON: " + t.getMessage(), t);
        }

        return request;
    }

}


text:
wget https://packagecloud.io/slacktechnologies/slack/gpgkey -O - | apt-key add -
echo deb https://packagecloud.io/slacktechnologies/slack/debian/ jessie main | sudo tee /etc/apt/sources.list.d/slacktechnologies_slack.list
sudo apt-get update
sudo apt-get install slack-desktop


text:
$:.unshift(File.dirname(__FILE__) + '/../lib')

require 'rubygems'
gem 'test-spec', '=0.9'
require 'test/spec'

RAILS_EDGE_PATH = File.join(File.dirname(__FILE__), 'vendor/rails')
if File.exist?(RAILS_EDGE_PATH)
  RAILS_GEM_VERSION = 'edge'
  Dir[File.join(RAILS_EDGE_PATH, '**','lib')].each do |libdir|
    $LOAD_PATH.unshift libdir
  end
else
  RAILS_GEM_VERSION = ENV['RAILS_GEM_VERSION'] || '2.3.2'
  gem 'rails', RAILS_GEM_VERSION
end

require 'action_controller'
require 'active_record'
require 'active_support'
require 'action_pack/version'
require 'active_record/version'
require 'active_support/version'

puts <<-OLLA

testing for rails-#{RAILS_GEM_VERSION}:
  - [action_pack-#{ActionPack::VERSION::STRING}] action_controller
  - active_record-#{ActiveRecord::VERSION::STRING}
  - active_support-#{ActiveSupport::VERSION::STRING}

OLLA

RAILS_ROOT = File.dirname(__FILE__)
config = YAML::load(IO.read(File.dirname(__FILE__) + '/config/database.yml'))
ActiveRecord::Base.logger = Logger.new('/dev/null')
ActiveRecord::Base.establish_connection(config['test'])

ActiveRecord::Schema.verbose = false
require File.dirname(__FILE__) + "/db/schema.rb"

require "#{File.dirname(__FILE__)}/../init"

# helper methods and classes
def create_valid_event
  Event.new(:title => 'title', :comment => 'dude')
end

class Foo
  include ValidationScenarios::With
end


text: echo "nerim;http://stats.nerim.net/images/weathermap.png"


text:
package org.apache.activemq.artemis.core.persistence;

import java.util.List;

import org.apache.activemq.artemis.api.core.SimpleString;
import org.apache.activemq.artemis.core.persistence.impl.journal.codec.QueueStatusEncoding;

public interface QueueBindingInfo {

   long getId();

   SimpleString getAddress();

   SimpleString getQueueName();

   /**
    * used to rename the queue in case of a duplication during load time
    *
    * @param newName
    */
   void replaceQueueName(SimpleString newName);

   SimpleString getFilterString();

   boolean isAutoCreated();

   boolean isConfigurationManaged();

   void setConfigurationManaged(boolean configurationManaged);

   SimpleString getUser();

   void addQueueStatusEncoding(QueueStatusEncoding status);

   List<QueueStatusEncoding> getQueueStatusEncodings();

   int getMaxConsumers();

   void setMaxConsumers(int maxConsumers);

   boolean isPurgeOnNoConsumers();

   void setPurgeOnNoConsumers(boolean purgeOnNoConsumers);

   boolean isExclusive();

   void setExclusive(boolean exclusive);

   boolean isLastValue();

   void setLastValue(boolean lastValue);

   SimpleString getLastValueKey();

   void setLastValueKey(SimpleString lastValue);

   boolean isNonDestructive();

   void setNonDestructive(boolean nonDestructive);

   int getConsumersBeforeDispatch();

   void setConsumersBeforeDispatch(int consumersBeforeDispatch);

   long getDelayBeforeDispatch();

   void setDelayBeforeDispatch(long delayBeforeDispatch);

   byte getRoutingType();

   void setRoutingType(byte routingType);

   boolean isGroupRebalance();

   int getGroupBuckets();

   boolean isAutoDelete();

   long getAutoDeleteDelay();

   long getAutoDeleteMessageCount();
}


text:
require 'nokogiri'

module KDL
  class METS
    attr_reader :mets
    attr_reader :mets_file
    attr_reader :backup_file

    def initialize
      @loaded = false
    end

    def loaded?
      @loaded
    end

    def changed?
      @changed
    end

    def mark_changed
      @changed = true
    end

    # raw file access

    def load(mets_file)
      @mets_file = mets_file
      @mets = Nokogiri::XML open(@mets_file)
      @changed = false
      @loaded = true
    end

    def save
      backup
      return unless @changed
      File.open(@mets_file, 'w') do |f|
        @mets.write_xml_to f
      end
      @changed = false
    end

    def backup
      @backup_file = [
        @mets_file,
        '.bak',
      ].join('')
      FileUtils.cp @mets_file, @backup_file
    end

    # object-level metadata

    def dublin_core
      Nokogiri::XML(@mets.xpath('//oai_dc:dc', @mets.collect_namespaces).first.to_s)
    end

    def self.add_canned_query(method_name, query)
      define_method method_name do
        @mets.xpath(query).first.content
      end
    end

    add_canned_query :repository, '//mets:agent[@TYPE="REPOSITORY"]/mets:name'
    add_canned_query :date_digitized, '//mets:amdSec//mets:versionStatement'
    add_canned_query :base_resolution, '//mets:digiProvMD/mets:process/mets:process_reformat[@FIELDTYPE="reformatInfo"]'

    # item-level metadata

    def ids
      mets.xpath('//mets:fileGrp').reject { |node| node['USE'] == 'reel metadata' or node['USE'] == 'wave files' }.collect do |node|
        node['ID']
      end
    end

    def file_id_for(use, group_id)
      use.gsub(/\s+/, '_').camelize + group_id.sub('FileGrp', 'File')
    end

    def div(options)
      if options.has_key?(:master_id)
        query = "//mets:div[mets:fptr[@FILEID='#{options[:master_id]}']]"
      elsif options.has_key?(:fileGrp_id)
        id = file(:fileGrp => options[:fileGrp_id]).first['ID']
        query = "//mets:div[mets:fptr[@FILEID='#{id}']]"
      end
      @mets.xpath(query)
    end

    def hasFileGrpWithUse(use)
      fileGrp(:use => use).length > 0
    end

    def fileGrp(options)
      query = "//mets:fileGrp[@USE='#{options[:use]}']"
      @mets.xpath(query)
    end

    def file(options)
      if options.has_key?(:use)
        query = "//mets:fileGrp[@ID='#{options[:fileGrp]}']/mets:file[@USE='#{options[:use]}']"
      else
        query = "//mets:fileGrp[@ID='#{options[:fileGrp]}']/mets:file"
      end
      @mets.xpath(query)
    end

    def referenced?(string)
      @mets.xpath('//mets:FLocat').each do |flocat|
        if normalize(flocat['href']) == normalize(string) or
           normalize(flocat['xlink:href']) == normalize(string)
          return true
        end
      end
      false
    end

    def normalize(path)
      begin
        path.gsub(/^\.\//, "")
      rescue
        ""
      end
    end

    def href(options)
      if options.has_key?(:fileGrp_use)
        query = "//mets:fileGrp[@USE='#{options[:fileGrp_use]}']/mets:file[@USE='#{options[:file_use]}']//mets:FLocat"
      else
        query = "//mets:fileGrp[@ID='#{options[:fileGrp]}']/mets:file[@USE='#{options[:use]}']//mets:FLocat"
      end
      result = @mets.xpath(query).first
      if result.nil?
        ''
      elsif result['xlink:href'].nil?
        result['href'].gsub(/^\.\//, '')
      else
        result['xlink:href'].gsub(/^\.\//, '')
      end
    end

    def self.add_file_attr(method_name, attribute)
      define_method method_name do |options|
        query = "//mets:fileGrp[@ID='#{options[:fileGrp]}']/mets:file[@USE='#{options[:use]}']/@#{attribute}"
        @mets.xpath(query).first.to_s
      end
    end

    add_file_attr :mimetype, :MIMETYPE
    add_file_attr :file_id, :ID

    def self.add_path(method_name, field)
      define_method method_name do |identifier|
        the_div = div(:fileGrp_id => identifier).first
        the_path = [the_div[field.to_s]]
        while the_div.parent.name == 'div'
          the_path.unshift the_div.parent[field.to_s].sub(/\s*([,.;:!?]+\s*)+$/, '')
          the_div = the_div.parent
        end
        the_path
      end
    end

    add_path :label_path, :LABEL
    add_path :order_path, :ORDER

    def self.add_href_field(method_name, use)
      define_method method_name do |identifier|
        href :fileGrp => identifier,
             :use => use.to_s.gsub(/_/, ' ')
      end
    end

    add_href_field :print_image_path, :print_image
    add_href_field :reference_image_path, :reference_image
    add_href_field :thumbnail_path, :thumbnail
    add_href_field :front_thumbnail_path, :front_thumbnail
    add_href_field :reference_video_path, :reference_video
    add_href_field :reference_audio_path, :reference_audio
    add_href_field :secondary_reference_audio_path, :secondary_reference_audio
    add_href_field :viewer_path, :tiles_metadata
    add_href_field :text_href, :ocr
    add_href_field :alto_href, :coordinates

    def reel_metadata_href
      node = mets.xpath('//mets:fileGrp').select { |node| node['USE'] == 'reel metadata' }.first
      if node
        href :fileGrp => node['ID'],
             :use => 'reel metadata'
      end
    end

    def self.add_div_field(method_name, field)
      define_method method_name do |identifier|
        div(:fileGrp_id => identifier).first[field.to_s]
      end
    end

    add_div_field :sequence_number, :ORDER
    add_div_field :label, :LABEL
    add_div_field :page_type, :TYPE

    # file modification

    def add_file(options)
      id = file_id :fileGrp => options[:fileGrp],
                       :use => options[:use]
      if id.length == 0
        flocat = Nokogiri::XML::Node.new "FLocat", @mets
        flocat['xlink:href'] = options[:file]
        flocat['LOCTYPE'] = 'OTHER'

        the_file = Nokogiri::XML::Node.new "file", @mets
        file_id = file_id_for options[:use], options[:fileGrp]
        the_file['ID'] = file_id
        the_file['USE'] = options[:use]
        the_file['MIMETYPE'] = options[:mimetype]

        the_file.add_child(flocat)

        @mets.xpath("//mets:fileGrp[@ID='#{options[:fileGrp]}']").first.add_child(the_file)

        fptr = Nokogiri::XML::Node.new "fptr", @mets
        fptr['FILEID'] = file_id

        master_id = file_id_for 'master', options[:fileGrp]

        the_div = div :master_id => master_id
        the_div.first.add_child(fptr)

        @changed = true
      end
      file :fileGrp => options[:fileGrp],
           :use => options[:use]
    end

    def remove_file(options)
      if options.has_key?(:file_id) and options[:file_id]
        @mets.xpath("//mets:file[@ID='#{options[:file_id]}']").first.remove
        @mets.xpath("//mets:div/mets:fptr[@FILEID='#{options[:file_id]}']").each do |node|
          node.remove
        end
        @changed = true
      elsif options.has_key?(:use) and options[:use]
        @mets.xpath("//mets:fileGrp[@USE='#{options[:use]}']").each do |fileGrp|
          fileGrp.xpath("mets:file").each do |file|
            file_id = file['ID']
            @mets.xpath("//mets:div/mets:fptr[@FILEID='#{file_id}']").each do |node|
              node.remove
            end
          end
          fileGrp.remove
        end
        @changed = true
      end
    end
  end
end


text:
'use strict';

var app = angular.module('mean.system',
['ui.bootstrap', 'easypiechart', 'mgo-angular-wizard', 'textAngular', 'angular-loading-bar',
 'app.ui.ctrls', 'app.ui.directives', 'app.ui.services', 'app.form.validation',
 'app.ui.form.ctrls', 'app.ui.form.directives', 'mean.tasklist','app.chart.ctrls',
 'app.chart.directives', 'ngAnimate']);

app.controller('IndexController', ['$scope', 'Global', '$location',
function ($scope, Global, $location) {
    var vm = this;
    $scope.global = Global;

    /**
     * Determine whether the current page should have the navigation pane displayed
     * @returns {boolean}
     */
    vm.noNavPage = function() {
        var path = $location.path();
        var noNavigationPages = ['/404', '/pages/500', '/login', '/register', '/register/*'];
        // Find matches against the current page and pages without navigation
        var noNavResult = noNavigationPages.map(function (page) {
            // Exact match
            if (page === path) {
                return true;
            }
            // Match * patterns on regex
            if (page.indexOf('*') !== -1) {
                var regex = new RegExp(path.substring(0, path.lastIndexOf('/')));
                // Don't include items which can't be regex
                if (!path.lastIndexOf('/')) {
                    return false;
                }
                return regex.test(path);
            }
        }).filter(function (page) {
            return !!page;
        });
        return noNavResult.length;
    };

    // Determine the size of the right pane
    vm.rightPaneLarge = true;
    $scope.$on('rightPaneSizeChange', function (event, size) {
        vm.rightPaneLarge = size;
    });

    vm.main = {
        login: 'login',
        register: 'register'
    };
}]);


text:
import { hoistComponentBehavior } from '../src/hoister';

describe('hoister Tests', () => {
    it('check display name from displayName prop', () => {
        const comp = () => {};
        comp.displayName = 'TestComponent';
        const HositedClass = hoistComponentBehavior(comp, {});

        expect(HositedClass.displayName).toBe('HoistedComponent(TestComponent)');
    });

    it('check display name from name prop', () => {
        const TestComponent = () => {};
        const HositedClass = hoistComponentBehavior(TestComponent, {});

        expect(HositedClass.displayName).toBe('HoistedComponent(TestComponent)');
    });

    it('check display name from default name', () => {
        const HositedClass = hoistComponentBehavior(() => {}, {});

        expect(HositedClass.displayName).toBe('HoistedComponent(Component)');
    });
});


text:
<?php

declare(strict_types = 1);

namespace Reskume\FileBundle\Tests\Unit\Storage;

/**
 * Class FileStorageConfigurationTest
 */
class FileStorageConfigurationTest extends \PHPUnit_Framework_TestCase
{
    /**
     * Test that valid MIME type is detected.
     */
    public function testNullMimeTypeReturnsFalse()
    {
        $mockFile = $this->getMockBuilder('Symfony\Component\HttpFoundation\File\File')
            ->setConstructorArgs(array('bla', false))
            ->getMock();
        $mockFile->expects($this->once())
            ->method('getMimeType')
            ->willReturn(null);

        $mockFileStorage = $this->getMockBuilder('Reskume\FileBundle\Storage\AbstractFileStorageConfiguration')
            ->setMethods(null)
            ->disableOriginalConstructor()
            ->getMock();

        $this->assertFalse($mockFileStorage->isAllowedMimeType($mockFile));
    }
}


text:
class TrafficController < StatusBoardWidgets
  # Traffic graph with gaug.es
  get '/' do
    type = params[:type] || "line"
    gauges_params = params.select { |k, v| k.include?("page") }

    graph = {
      graph: {
        title: 'Traffic',
        total: true,
        type: type,
        refreshEveryNSeconds: 300,
        datasequences: []
      }
    }

    gauges_params.each do |key, gauge_id|
      gauge   = MultiJson.load(open("https://secure.gaug.es/gauges/#{gauge_id}",
                                "X-Gauges-Token" => params[:api_key]).read)["gauge"]

      date = Date.today - 30

      traffic1 = MultiJson.load(open("https://secure.gaug.es/gauges/#{gauge_id}/traffic?date=#{date}",
                                "X-Gauges-Token" => params[:api_key]).read)["traffic"]
      traffic2 = MultiJson.load(open("https://secure.gaug.es/gauges/#{gauge_id}/traffic",
                                "X-Gauges-Token" => params[:api_key]).read)["traffic"]
      traffic = traffic1 + traffic2

      ending = traffic.size - 1
      beginning = ending - 30

      if gauges_params.size == 1
        title = "Views"
        graph[:graph][:title] = gauge["title"]
        people = { title: "People", datapoints: create_datapoints(traffic, "people", beginning, ending) }
        graph[:graph][:datasequences] << people
      else
        title = gauge["title"]
      end

      views = { title: title, datapoints: create_datapoints(traffic, "views", beginning, ending) }
      graph[:graph][:datasequences] << views
    end

    json graph
  end

  private

  def create_datapoints(traffic, type, beginning, ending)
    datapoints = []
    traffic[beginning..ending].each do |entry|
      datapoints << {
        title: DateTime.parse(entry["date"]).strftime("%e.%-m."),
        value: entry[type]
      }
    end
    datapoints
  end
end


text:
package generated.zcsclient.admin;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for createDistributionListResponse complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="createDistributionListResponse">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element ref="{urn:zimbraAdmin}dl"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "createDistributionListResponse", propOrder = {
    "dl"
})
public class testCreateDistributionListResponse {

    @XmlElement(required = true)
    protected testDistributionListInfo dl;

    /**
     * Gets the value of the dl property.
     *
     * @return
     *     possible object is
     *     {@link testDistributionListInfo }
     *
     */
    public testDistributionListInfo getDl() {
        return dl;
    }

    /**
     * Sets the value of the dl property.
     *
     * @param value
     *     allowed object is
     *     {@link testDistributionListInfo }
     *
     */
    public void setDl(testDistributionListInfo value) {
        this.dl = value;
    }

}


text:
package org.agiso.core.beans.exception;

import org.agiso.core.lang.exception.BaseRuntimeException;

/**
 * Wyjątek pozyskiwania obiektu z kontekstu aplikacji.
 *
 * @author Karol Kopacz
 * @since 1.0
 */
public class BeanRetrievalException extends BaseRuntimeException {
	private static final long serialVersionUID = 1L;

//	-----------------------------------------------------------------
	private String beanName;

//	-----------------------------------------------------------------
	public BeanRetrievalException(String beanName) {
		super();
		this.beanName = beanName;
	}

	public BeanRetrievalException(String beanName, String message) {
		super(message);
		this.beanName = beanName;
	}

	public BeanRetrievalException(String beanName, Throwable cause) {
		super(cause);
		this.beanName = beanName;
	}

	public BeanRetrievalException(String beanName, String message, Throwable cause) {
		super(message, cause);
		this.beanName = beanName;
	}

//	-----------------------------------------------------------------
	/**
	 * @return Nazwa obiektu do pobrania z kontekstu aplikacji.
	 */
	public String getBeanName() {
		return beanName;
	}
}


text:
using System.Collections.Generic;

namespace Spark.Compiler
{
    public class FileContext
    {
        public string ViewSourcePath { get; set; }

        public IList<Chunk> Contents;
    }
}


text:
CREATE TABLE user_props (
  user_id    BIGINT      NOT NULL,
  prop_key   VARCHAR(64) NOT NULL,
  prop_value VARCHAR(2048),
  CONSTRAINT user_props_pk PRIMARY KEY (user_id, prop_key),
  CONSTRAINT user_props_users_fk FOREIGN KEY (user_id) REFERENCES users (user_id)
);
CREATE TABLE stats_remote (
  node_id            BIGINT NOT NULL,
  origin             varchar(64),
  download_count     BIGINT,
  last_downloaded    BIGINT,
  last_downloaded_by VARCHAR(64),
  CONSTRAINT stats_remote_pk PRIMARY KEY (node_id),
  CONSTRAINT stats_remote_nodes_fk FOREIGN KEY (node_id) REFERENCES nodes (node_id)
);


text:
@interface FATabBarItem : UITabBarItem

@end


text:
cd `dirname $0`
. ./script_root.sh
source addhistory.sh

# ¥ê¥Ö¡¼¥È¤»¤º¤ËÆóÅÙµ¯Æ°¤·¤¿»þ¤Ï²¿¤â¤·¤Ê¤¤

if [ -f ${script_local}/pre-shutdown.sh ]; then
  echo "installflash has been already executed. Skip."
  echo "Please reboot to start the installation. "
  exit 0
fi

# 32bit/64bitȽÄê
arch="amd64"
is_x86=`uname -a | grep i686`
if [ -n "{is_x86}" ]; then
  arch="i386"
fi

# downloadflash¤Ï¥Ò¥¹¥È¥ê¤ËµÏ¿¤·¤Ê¤¤¡Êɬ¤º¼êÆ°¤Çµ¯Æ°¤·¤Æ¥¤¥ó¥¹¥È¡¼¥ë¤¹¤ë¡Ë
#addhistory $0

if [ ! -d ${script_local} ]; then
  rm ${script_local} > /dev/null 2>&1
  mkdir ${script_local}
fi

# Packages.gz¤ò¥À¥¦¥ó¥í¡¼¥É¤¹¤ë
cd ${script_local}
mkdir chrome_work
cd chrome_work

echo download Packages.gz.
wget http://archive.canonical.com/ubuntu/dists/trusty/partner/binary-${arch}/Packages.gz
if [ $? -ne 0 ]; then
  echo Failed to download Packages.gz. Abort.
  cd ..
  rm -rf chrome_work
  exit 1
fi

gunzip -f Packages.gz

version=`grep -A10 -e "Package: adobe-flashplugin$" Packages | grep Version | sed -e 's/Version:.*://'`
echo version=${version}
package="adobe-flashplugin_${version}_${arch}.deb"

url="http://archive.canonical.com/ubuntu/pool/partner/a/adobe-flashplugin/${package}"

echo ${url}

echo Download Flash package...
wget ${url}

if [ $? -ne 0 ]; then
  echo Failed to download Flash Package. Abort.
  cd ..
  rm -rf chrome_work
  exit 1
fi

echo
echo Download is completed.
echo

echo Extract the package...
ar x ${package}
if [ 0 -ne $? ]; then
  echo "Failed to extract package(ar). Abort.."
  cd ..
  rm -rf chrome_work
  exit 1
fi
#tar xf data.tar.lzma --lzma
xz -dv data.tar.xz
if [ 0 -ne $? ]; then
  echo "Failed to extract package(xz). Abort.."
  cd ..
  rm -rf chrome_work
  exit 1
fi

tar xf data.tar
if [ 0 -ne $? ]; then
  echo Failed to unpack package. Abort..
  cd ..
  rm -rf chrome_work
  exit 1
fi
echo
echo Extracted.
echo

echo Create symlink.

# remount / writable
mount -o remount,rw /
if [ 0 -ne $? ]; then
  echo Failed to remount root partition. Abort..
  cd ..
  rm -rf chrome_work
  exit 1
fi

ln -s ${script_root}/installflash_ubuntu.sh ${script_local}/pre-shutdown.sh
if [ 0 -ne $? ]; then
  echo Failed to create symlink. Abort..
  cd ..
  rm -rf chrome_work
  exit 1
fi

mount -r -o remount /

echo
echo Ready to Install. Please reboot to start the installation.


text:
author: tangi
tags: Actualité
imagefeature: https://static.fablab-lannion.org/index.jpeg
layout: post
slug: appel-projet-fab-labs-2013-encore-peu-suspense
date: 2013-11-18
title: "Appel à Projet « Fab labs 2013 »  : Encore un peu de suspense…"
comments: True
---
Fleur Pellerin a annoncé dans un [communiqué](http://proxy-
pubminefi.diffusion.finances.gouv.fr/pub/document/18/16036.pdf "communiqué" )
que l'appel à projet « Fab labs 2013 » était un succès.

Nous n'aurions pas parié sur une telle mobilisation, le nombre de réponses
dépassent d'ailleurs très largement le nombre de Fablabs établis sur le
territoire. Le Fablab de Lannion a bien évidemment déposé un dossier,
ambitieux mais raisonnable, pour pouvoir rapidement atteindre un niveau
d'équipement très élevé conformément à ses ambitions MITiennes.

Nous attendons donc avec fébrilité les résultats de cet appel à projet
attendus pour la fin du mois de Novembre…

En cas de succès, on pourra envisager, outre l'acquisition d'un certain nombre
de machines, un élargissement les plages d'ouverture. Nous pourrons alors
développer de nouveaux partenariats et rencontrer de nouveaux publics.

Nous espérons que la [spécificité ](http://fablab-lannion.org/2013/06/un-
fablab-dont-la-structure-est-innovante/ "Le Fablab de Lannion, un fablab dont
la structure est innovante ?" )du Fablab de Lannion et la qualité du projet
déposé auront convaincu le jury!

En attendant, vous pouvez vous faire une petite idée du dossier en consultant
la version résumée [ici](http://fablab-lannion.org/?p=9453).

Et qui sait, Nous pourrons peut-être fêter le résultat lors des portes
ouvertes!


text:
package com.dslplatform.json;

import com.dslplatform.json.test.CustomNamingStrategyExternal;
import org.junit.Assert;
import org.junit.Test;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;

public class ConverterTest {

	@JsonConverter(target = ClosedClass.class)
	public static class ClosedClassConverter {
		public static final JsonReader.ReadObject<ClosedClass> JSON_READER = new JsonReader.ReadObject<ClosedClass>() {
			@Override
			public ClosedClass read(JsonReader reader) throws IOException {
				return ClosedClass.create(reader.readString());
			}
		};
		public static JsonWriter.WriteObject<ClosedClass> JSON_WRITER() {
			return new JsonWriter.WriteObject<ClosedClass>() {
				@Override
				public void write(JsonWriter writer, @Nullable ClosedClass value) {
					writer.writeString(value.value);
				}
			};
		}
	}

	public static class ByteArrayConverter {
		public static final JsonReader.ReadObject<byte[]> JSON_READER = new JsonReader.ReadObject<byte[]>() {
			@Override
			public byte[] read(JsonReader reader) throws IOException {
				return null;
			}
		};
		public static JsonWriter.WriteObject<byte[]> JSON_WRITER() {
			return new JsonWriter.WriteObject<byte[]>() {
				@Override
				public void write(JsonWriter writer, @Nullable byte[] value) {
					writer.writeNull();
				}
			};
		}
	}

	@CompiledJson
	public static class TestByteArrayCompilation {
		@JsonAttribute(converter = ByteArrayConverter.class)
		public final byte[] b;

		public TestByteArrayCompilation(byte[] b) {
			this.b = b;
		}
	}

	public static class ClosedClass {
		public final String value;
		private ClosedClass(String value) {
			this.value = value;
		}
		static ClosedClass create(String value) {
			return new ClosedClass(value);
		}

		@Override
		public int hashCode() {
			return value.hashCode();
		}

		@Override
		public boolean equals(Object obj) {
			if (!(obj instanceof ClosedClass)) return false;
			return value.equals(((ClosedClass)obj).value);
		}
	}

	@CompiledJson(formats = {CompiledJson.Format.ARRAY,CompiledJson.Format.OBJECT})
	public static class Composite1 {
		@JsonAttribute(index = 1, converter = IntConverter.class)
		public int x;
		@JsonAttribute(index = 2)
		public List<String> s;
		@JsonAttribute(index = 3, converter = ClosedClassConverter.class)
		public ClosedClass d;
	}
	@CompiledJson(formats = {CompiledJson.Format.OBJECT,CompiledJson.Format.ARRAY})
	public static class Composite2 {
		@JsonAttribute(index = 1, converter = IntConverter.class)
		public int x;
		@JsonAttribute(index = 2)
		public List<String> s;
		@JsonAttribute(index = 3)
		public ClosedClass d;
	}

	@CompiledJson(formats = {CompiledJson.Format.ARRAY,CompiledJson.Format.OBJECT})
	public static class ImmutableComposite1 {
		@JsonAttribute(index = 1, converter = IntConverter.class)
		public final int x;
		@JsonAttribute(index = 2)
		public final List<String> s;
		@JsonAttribute(index = 3, converter = ClosedClassConverter.class)
		public final ClosedClass d;

		public ImmutableComposite1(int x, List<String> s, ClosedClass d) {
			this.x = x;
			this.s = s;
			this.d = d;
		}
	}
	@CompiledJson(formats = {CompiledJson.Format.OBJECT,CompiledJson.Format.ARRAY})
	public static class ImmutableComposite2 {
		@JsonAttribute(index = 1, converter = IntConverter.class)
		public final int x;
		@JsonAttribute(index = 2)
		public final List<String> s;
		@JsonAttribute(index = 3)
		public final ClosedClass d;

		public ImmutableComposite2(int x, List<String> s, ClosedClass d) {
			this.x = x;
			this.s = s;
			this.d = d;
		}
	}

	public static abstract class IntConverter {
		public static JsonReader.ReadObject<Integer> getJSON_READER() {
			return NumberConverter.INT_READER;
		}
		public static JsonWriter.WriteObject<Integer> JSON_WRITER() {
			return NumberConverter.INT_WRITER;
		}
	}

	private final DslJson<Object> dslJson = new DslJson<>(new DslJson.Settings<>().allowArrayFormat(true).includeServiceLoader());

	@Test
	public void firstArrayThenObjectForEmptyCtor() throws IOException {
		Composite1 c = new Composite1();
		c.d = ClosedClass.create("123.456");
		c.s = Arrays.asList("abc", "def", null, "ghi");
		c.x = -1;
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		dslJson.serialize(c, os);
		Assert.assertEquals("[-1,[\"abc\",\"def\",null,\"ghi\"],\"123.456\"]", os.toString());
		Composite1 res1 = dslJson.deserialize(Composite1.class, os.toByteArray(), os.size());
		Assert.assertEquals(c.d, res1.d);
		Assert.assertEquals(c.s, res1.s);
		Assert.assertEquals(c.x, res1.x);
		Composite2 res2 = dslJson.deserialize(Composite2.class, os.toByteArray(), os.size());
		Assert.assertEquals(c.d, res2.d);
		Assert.assertEquals(c.s, res2.s);
		Assert.assertEquals(c.x, res2.x);
	}

	@Test
	public void firstObjectThenArrayForEmptyCtor() throws IOException {
		Composite2 c = new Composite2();
		c.d = ClosedClass.create("123.456");
		c.s = Arrays.asList("abc", "def", null, "ghi");
		c.x = -1;
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		dslJson.serialize(c, os);
		Assert.assertEquals("{\"x\":-1,\"s\":[\"abc\",\"def\",null,\"ghi\"],\"d\":\"123.456\"}", os.toString());
		Composite1 res1 = dslJson.deserialize(Composite1.class, os.toByteArray(), os.size());
		Assert.assertEquals(c.d, res1.d);
		Assert.assertEquals(c.s, res1.s);
		Assert.assertEquals(c.x, res1.x);
		Composite2 res2 = dslJson.deserialize(Composite2.class, os.toByteArray(), os.size());
		Assert.assertEquals(c.d, res2.d);
		Assert.assertEquals(c.s, res2.s);
		Assert.assertEquals(c.x, res2.x);
	}

	@Test
	public void firstArrayThenObjectForNonEmptyCtor() throws IOException {
		ImmutableComposite1 c = new ImmutableComposite1(
				-1,
				Arrays.asList("abc", "def", null, "ghi"),
				ClosedClass.create("123.456")
		);
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		dslJson.serialize(c, os);
		Assert.assertEquals("[-1,[\"abc\",\"def\",null,\"ghi\"],\"123.456\"]", os.toString());
		ImmutableComposite1 res1 = dslJson.deserialize(ImmutableComposite1.class, os.toByteArray(), os.size());
		Assert.assertEquals(c.d, res1.d);
		Assert.assertEquals(c.s, res1.s);
		Assert.assertEquals(c.x, res1.x);
		ImmutableComposite2 res2 = dslJson.deserialize(ImmutableComposite2.class, os.toByteArray(), os.size());
		Assert.assertEquals(c.d, res2.d);
		Assert.assertEquals(c.s, res2.s);
		Assert.assertEquals(c.x, res2.x);
	}

	@Test
	public void firstObjectThenArrayForNonEmptyCtor() throws IOException {
		ImmutableComposite2 c = new ImmutableComposite2(
				-1,
				Arrays.asList("abc", "def", null, "ghi"),
				ClosedClass.create("123.456")
		);
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		dslJson.serialize(c, os);
		Assert.assertEquals("{\"x\":-1,\"s\":[\"abc\",\"def\",null,\"ghi\"],\"d\":\"123.456\"}", os.toString());
		ImmutableComposite1 res1 = dslJson.deserialize(ImmutableComposite1.class, os.toByteArray(), os.size());
		Assert.assertEquals(c.d, res1.d);
		Assert.assertEquals(c.s, res1.s);
		Assert.assertEquals(c.x, res1.x);
		ImmutableComposite2 res2 = dslJson.deserialize(ImmutableComposite2.class, os.toByteArray(), os.size());
		Assert.assertEquals(c.d, res2.d);
		Assert.assertEquals(c.s, res2.s);
		Assert.assertEquals(c.x, res2.x);
	}

	@Test
	public void cantChangeJsonConverter() throws IOException {
		DslJson<Object> changedDslJson = new DslJson<>(new DslJson.Settings<>().allowArrayFormat(true).includeServiceLoader());
		changedDslJson.registerWriter(ClosedClass.class, (w, v) -> w.writeNull());
		Composite2 c = new Composite2();
		c.d = ClosedClass.create("123.456");
		c.s = Arrays.asList("abc", "def", null, "ghi");
		c.x = -1;
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		changedDslJson.serialize(c, os);
		Assert.assertEquals("{\"x\":-1,\"s\":[\"abc\",\"def\",null,\"ghi\"],\"d\":\"123.456\"}", os.toString());
		Composite2 res2 = changedDslJson.deserialize(Composite2.class, os.toByteArray(), os.size());
		Assert.assertEquals(c.d, res2.d);
		Assert.assertEquals(c.s, res2.s);
		Assert.assertEquals(c.x, res2.x);
	}

	@CompiledJson
	public static class NullChecks{
		@JsonAttribute(converter = CustomIntConverter.class, nullable = false)
		public Integer x;
	}

	public static class CustomIntConverter {
		public static final JsonReader.ReadObject<Integer> JSON_READER = null;
		public static final JsonWriter.WriteObject<Integer> JSON_WRITER = null;
	}

	@Test
	public void nullChecksOnConverter() throws IOException {
		NullChecks nc = new NullChecks();
		nc.x = null;
		try {
			dslJson.serialize(nc, new ByteArrayOutputStream());
			Assert.fail("Expecting exception");
		} catch (ConfigurationException ex) {
			Assert.assertTrue(ex.getMessage().contains("Property 'x' is not allowed to be null"));
		}
		try {
			byte[] bytes = "{\"x\":null}".getBytes(StandardCharsets.UTF_8);
			dslJson.deserialize(NullChecks.class, bytes, bytes.length);
			Assert.fail("Expecting exception");
		} catch (ParsingException ex) {
			Assert.assertTrue(ex.getMessage().contains("Property 'x' is not allowed to be null"));
		}
	}

	@CompiledJson(namingStrategy = CustomNamingStrategyExternal.class)
	public static class CustomNamingClass {
		public String MyName;
	}

	@Test
	public void checkSimpleCustomName() throws IOException {
		CustomNamingClass cn = new CustomNamingClass();
		cn.MyName = "test";
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		dslJson.serialize(cn, os);
		Assert.assertEquals("{\"myName\":\"test\"}", os.toString("UTF-8"));
	}
}


text:
import React from 'react';
import { Route, IndexRoute} from 'react-router';
import App from './App';
import AboutUs from './AboutUs';
import Home from './Home';
import CreateEvent from './CreateEvent';
import Profile from './Profile';
import Settings from './Settings';

module.exports = (
  <Route path="/" component={App}>
    <IndexRoute component={Home} />
    <Route path="home" component={Home} />
    <Route path="aboutus" component={AboutUs} />
    <Route path="createevent" component={CreateEvent} />
    <Route path="profile" component={Profile} />
    <Route path="settings" component={Settings} />
  </Route>
);


text:
A set of reusable components for Reagent.

## The Components

### text-input
TODO: description

### async-btn
TODO: description


text:
(function(){
    "use strict";

    var createGameController = function createGameController($location, identity, games, notifier){
        var vm = this;

        if(!identity.isAuthenticated()){
            $location.path('/unauthorized');
            return;
        }

        vm.createNewGame = function createNewGame(game){
            var gameToCreate = game;
            gameToCreate.creator = identity.currentUser.username;
            games
                .createNewGame(game)
                .then(function(){
                    notifier.success('Game created successfully');
                }, function(){
                    notifier.error('Unable to create game');
                });
        }
    };

    angular
        .module('cardsAgainstHumanity.controllers')
        .controller('CreateGameController', ['$location', 'identity', 'games', 'notifier', createGameController]);
}());


text:
mocha-xunit-zh
==============

Customized xunit reporter based on original mocha xunit reporter and xunit-file reporter to meet jenkins needs. Might delete it when I find more elegant solution.


text:
TEST(Feature, toString)
{
  mylib::Feature myfeature;
  ASSERT_STREQ("Feature", myfeature.toString().c_str());
}

TEST(Feature, work)
{
  mylib::Feature myfeature;
  ASSERT_STREQ("work", myfeature.work().c_str());
}


text:
package com.cg.project.dao;

import java.util.ArrayList;

import javax.sql.DataSource;

import com.cg.project.domain.Project;

public interface IProjectDao
{
	public DataSource getDataSource();
	public void setDataSource(DataSource dataSource);
	void addProject(Project e);
	void removeProject(int empNo);
	Project modifyProject(Project e);
	Project searchProject(int empNo);
	ArrayList<Project> listAllProject();
	void showAllProjectId();
	void checkProject(Project project);
	ArrayList<Integer> getAllProjectNumber();
}


text:
@interface PGViewController ()
@property (nonatomic, readonly, strong) PWMutableEncoderConfiguration *encoderConfiguration;
@end

@implementation PGViewController

#pragma mark - UIViewController
#pragma mark -

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    return self;
}

- (void)loadView
{
    UIView *v = [UIView new];
    self.view = v;

    _pgView = [[DDxView alloc] initWithFramework:[PWFramework sharedInstance] frame:CGRectZero];
    _pgView.viewName = @"PGView";
    _pgView.showImageDetails = YES;
    [_pgView updateLabel:nil];
    _pgView.delegate = [DiagnosticViewDelegate sharedInstance];

    [[DiagnosticViewDelegate sharedInstance].encoderConfiguration.changed addSubscriber:self action:@selector(encoderConfigurationDidChange:)];

    [self.view addSubview:_pgView];

    _touchButton = [[PWTouchButtonView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
    _touchButton.hidden = NO;
    [_pgView addSubview:_touchButton];

    [self encoderConfigurationDidChange:nil];

}

- (void) viewDidLayoutSubviews {

    [self resize];

}
- (void) resize {

    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
    CGRect screenRect = [PWUtility screenRect:orientation];
    CGFloat navBarOffset = [PWUtility navigationbarHeight:orientation];
    CGFloat tabBarOffset = [PWUtility tabbarHeight];
    CGFloat statusBarOffset = [PWUtility statusbarHeight];
    CGFloat totalOffset = navBarOffset + statusBarOffset;

    CGRect pgViewRect = CGRectMake(0, totalOffset, screenRect.size.width, (screenRect.size.height - tabBarOffset));
    _pgView.frame = pgViewRect;

}

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGesture:)];
    [_pgView addGestureRecognizer:pan];

    [[PWFramework sharedInstance].state.stateManager addChildChangedHandler:@"/DDx/PGView/MouseEvent"
                                                                     target:_pgView
                                                                     action:@selector(updateLabel:)];
    [_pgView.viewUpdated addSubscriber:self action:@selector(viewWasUpdated:)];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    [_pgView.viewUpdated removeSubscribersForTarget:self];
    [[PWFramework sharedInstance].state.stateManager removeAllChildChangedHandlersForTarget:self];
}

- (void)viewWasPopped
{
    [_pgView detachView];
}

#ifdef __IPHONE_6_0

- (BOOL)shouldAutorotate
{
    return YES;
}

- (UIInterfaceOrientationMask) supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskAll;
}
#endif

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return YES;
}

- (void)updateTouchButton:(CGPoint)point
{
    _touchButton.frame = CGRectMake(point.x-_touchButton.frame.size.width/2.0,
                                    point.y-_touchButton.frame.size.height/2.0,
                                    _touchButton.frame.size.width,
                                    _touchButton.frame.size.height);
}

#pragma mark - Private methods
#pragma mark -

- (void)panGesture:(UIPanGestureRecognizer *)gesture
{
    CGPoint p = [gesture locationInView:gesture.view];

    [self updateTouchButton:p];

    switch (gesture.state)
    {
        case UIGestureRecognizerStateBegan:
            [_pgView mouseEnter:p];
            break;
        case UIGestureRecognizerStateChanged:
            [_pgView mouseMove:p];
            break;
        case UIGestureRecognizerStateEnded:
            [_pgView mouseLeave];
            break;
        case UIGestureRecognizerStateCancelled:
            break;
        case UIGestureRecognizerStatePossible:
        case UIGestureRecognizerStateFailed:
            break;
    }
}

- (BOOL)getValue:(NSString *)path
{
    NSString *valueString = [[PWFramework sharedInstance].state.stateManager getValue:path];
    BOOL valueBool = [valueString boolValue];
    return valueBool;
    //return [[[PWFramework sharedInstance].state.stateManager getValue:path] boolValue];
}

- (void)updateValue:(NSString *)path enabled:(BOOL)enabled
{
    [[PWFramework sharedInstance].state.stateManager setAppStatePathWithValue:path
                                                                        value:enabled?@"True":@"False"];
}

- (void)tripleSwipeGesture:(UISwipeGestureRecognizer *)gesture
{
    [self didRequestOptionsPanel];
}

- (void)viewWasUpdated:(PWViewUpdatedEventArgs *)args
{
    [_pgView updateLabel:nil];
}

#pragma mark PGSettingsViewControllerDelegate
#pragma mark -

- (void)doneWasPushed;
{
    [self dismissViewControllerAnimated:YES completion:^{

    }];
}

- (void)asyncImageGenerationDidChange:(BOOL)enabled
{
    [self updateValue:@"/DDx/AsyncImageGeneration" enabled:enabled];
}

- (void)useDeferredRenderingDidChange:(BOOL)enabled
{
    [self updateValue:@"/DDx/UseDeferredRendering" enabled:enabled];
}

- (void)useClientSizeDidChange:(BOOL)enabled
{
    [self updateValue:@"/DDx/UseClientSize" enabled:enabled];
}

- (void)useTilesDidChange:(BOOL)enabled
{
    [self updateValue:@"/DDx/UseTiles" enabled:enabled];
}

- (void)showMousePositionDidChange:(BOOL)enabled
{
    [self updateValue:@"/DDx/ShowMousePos" enabled:enabled];
}

- (void)screenshotButtonTouchUpInside
{
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];

    [[PWFramework sharedInstance].client queueCommand:@"Screenshot" onComplete:^(PWCommandResponseEventArgs *args)
        {
            PWGuid *resourceId = [[args.response elementForName:@"ResourceKey"] getTextAsWithDefault:@encode(PWGuid) defaultValue:[PWGuid emptyGuid]];
            [self dismissViewControllerAnimated:YES completion:^(void)
                {
                    UIViewController *controller = [[UIViewController alloc] init];
                    UIImageView *view = [[UIImageView alloc] init];
                    controller.view = view;

                    [[PWFramework sharedInstance].client retrieveObject:resourceId onComplete:^(PWBinaryObject *screenShot, NSError *error)
                     {
                         dispatch_async(dispatch_get_main_queue(),^{
                             [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];

                             if(!error)
                             {
                                 [view setImage:[UIImage imageWithData:screenShot.object]];

                                 [self.navigationController pushViewController:controller animated:YES];
                             }
                         });
                     }];
                }];
        }];
}

- (PWMutableEncoderConfiguration *)encoderConfiguration
{
    PWMutableEncoderConfiguration *encoderConfiguration = [DiagnosticViewDelegate sharedInstance].encoderConfiguration;
    return encoderConfiguration;
}

- (void)mimeTypeDidChange:(NSString *)mimeType
{
    self.encoderConfiguration.interactiveQuality.mimeType = mimeType;
    self.encoderConfiguration.fullQuality.mimeType = mimeType;
}

- (void)encoderConfigurationDidChange:(NSObject *)object
{
    [_pgView updateEncoderConfiguration];
}

#pragma mark OptionsPanelDelegate
#pragma mark -

- (void)didRequestOptionsPanel
{
    PGSettingsViewController *settings = [[PGSettingsViewController alloc] init];
    settings.delegate = self;
    settings.asyncImageGeneration.on = [self getValue:@"/DDx/AsyncImageGeneration"];
    settings.useDeferredRendering.on = [self getValue:@"/DDx/UseDeferredRendering"];
    settings.useClientSize.on = [self getValue:@"/DDx/UseClientSize"];
    settings.showMousePosition.on = [self getValue:@"/DDx/ShowMousePos"];
    [settings.screenshotButton setEnabled:YES];
    settings.selectedMimeType = self.encoderConfiguration.interactiveQuality.mimeType;

    UINavigationController *settingsNav = [[UINavigationController alloc] initWithRootViewController:settings];
    settingsNav.modalPresentationStyle = UIModalPresentationFormSheet;
    settingsNav.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;

    [self presentViewController:settingsNav animated:YES completion: nil];
}

@end


text:
'use strict';

angular.module('angularDemoApp')
    .controller('UserViewController', function ($scope, $state, $stateParams, $translate,
            UserService, userData,$mdDialog) {
	 	$scope.user = userData;

		if($state.current.data){
			$scope.isModal = $state.current.data.isModal;
		}

		$scope.deleteUser = function(instance){
			return UserService.deleteInstance(instance).then(function(instance){
				$state.go('^.list');
				return instance;
			});
		};
		$scope.go = function(route){
			$state.go(route);
		};
		$scope.closeItemViewer = function () {
			$mdDialog.hide();
		};
	});


text:
from django.contrib.sites.models import Site

from .base_test import BaseTestCase

class FixturesTest(BaseTestCase):
    """Comprueba que los fixtures se han creado."""

    def test_users(self):
        """Numero de usuarios."""
        # Numero de usuarios.
        users = self.user_model.objects.all()
        self.assertEqual(users.count(), 2)

        # Usuario snicoper
        user = self.user_model.objects.get(pk=1)
        self.assertEqual(user.username, 'snicoper')
        self.assertEqual(user.email, 'snicoper@snicoper.com')
        self.assertTrue(self.client.login(username='snicoper', password='123'))
        self.assertEqual(user.first_name, 'Salvador')
        self.assertEqual(user.last_name, 'Nicolas')
        self.assertTrue(user.is_staff)
        self.assertTrue(user.is_superuser)

    def test_sites(self):
        """Sites se ha restaurado."""
        site = Site.objects.get(pk=1)

        self.assertEqual(site.name, 'snicoper.com')
        self.assertEqual(site.domain, '127.0.0.1:8000')


text:
<?php

/**
 * @category Form
 * @author   Alexandre Seiller <alexandre.seiller92@gmail.com>
 * @license  http://www.gnu.org/copyleft/gpl.html GNU General Public License
 * @link     http://longchamp-roller-team.com
 */

namespace Lrt\CMSBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use JMS\DiExtraBundle\Annotation as DI;

/**
 * @DI\Service("form.cms.categoryType")
 */
class CategoryType extends AbstractType
{

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
                ->add('name', 'text');
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Lrt\CMSBundle\Entity\Category'
        ));
    }

    public function getName()
    {
        return 'lrt_cmsbundle_categorytype';
    }

}


text:
package default_package;
import java.awt.Panel;

public class panel
  extends Panel
{
  public panel() {}
}


text:
//= require d3.v3.min.js

//*********************************** */
//Dataview Admin
//*********************************** */

doWhenPresent('body.a_dataviews.index', function dataviewsAdminIndexPageIsReady() {
  $('.footable').footable();

    // GAUGE PLUGIN
    // =================================================================
    // Require Gauge.js
    // -----------------------------------------------------------------
    // http://bernii.github.io/gauge.js/
    // =================================================================
    var opts = {
      angle: 0.15, // The span of the gauge arc
      lineWidth: 0.44, // The line thickness
      radiusScale: 1, // Relative radius
      pointer: {
        length: 0.6, // // Relative to gauge radius
        strokeWidth: 0.035, // The thickness
        color: '#000000' // Fill color
      },
      limitMax: false,     // If false, max value increases automatically if value > maxValue
      limitMin: false,     // If true, the min value of the gauge will be fixed
      colorStart: '#6FADCF',   // Colors
      colorStop: '#8FC0DA',    // just experiment with them
      strokeColor: '#E0E0E0',  // to see which ones work best for you
      generateGradient: true,
      highDpiSupport: true,     // High resolution support

    };

  var target = document.getElementById('metadata-gauge'); // your canvas element
  var gauge = new Gauge(target).setOptions(opts); // create sexy gauge!
  gauge.maxValue = 100; // set max gauge value
  gauge.animationSpeed = 32; // set animation speed (32 is default value)
  gauge.set(Number($(target).attr('gauge_value'))); // set actual value

});

//------------------------------------/
//CREATE DATASET page
//------------------------------------/
doWhenPresent('body.a_dataviews.create', function dataviewsAdminCreatePageIsReady() {

    $('#Title').focus();

    var summernoteElement = $('.summernote');

    //Adds Validation
    $(summernoteElement).summernote({
      tabsize: 2,
      height: 150,
      callbacks: {
        onChange: function (contents, $editable) {
            // Note that at this point, the value of the `textarea` is not the same as the one
            // you entered into the summernote editor, so you have to set it yourself to make
            // the validation consistent and in sync with the value.
            summernoteElement.val(summernoteElement.summernote('isEmpty') ? "" : contents);

            // You should re-validate your element after change, because the plugin will have
            // no way to know that the value of your `textarea` has been changed if the change
            // was done programmatically.
            summernoteValidator.element(summernoteElement);
        }
    }});

    $("#createForm").validate({
      ignore: ':hidden:not(.summernote),.note-editable.card-block',
      errorPlacement: function (error, element) {
          // Add the `help-block` class to the error element
          error.addClass("invalid-feedback");
          console.log(element);
          if (element.prop("type") === "checkbox") {
              error.insertAfter(element.siblings("label"));
          } else if (element.hasClass("summernote")) {
              error.insertAfter(element.siblings(".note-editor"));
          } else {
              error.insertAfter(element);
          }
      },
      submitHandler: function(form) {
        var markup = $('#Description').summernote('code');

        var nodeData = {
            name: $('#Title').val(),
            description: markup,
            shortdescription: $('#ShortDescription').val(),
            keywords: $('#Keywords').val(),
            status: 'In Progress',
            datasets: {}
        };
        if($('#parent-dataset').length) {
          nodeData.datasets[$('#parent-dataset').attr('ds-name')] = {};
        }

          $.ajax({
            url: '/admin/dataviews/make_new',
            type: 'POST',
            data: JSON.stringify({ 'props': nodeData }),
            contentType: 'application/json',
            beforeSend: function(xhr) {
              xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
            },
          }).
          then(function createSuccess(uuid) {
            window.location.href = 'edit/' + uuid;
          }).
          fail(function createFail(err) {
            console.log('error: ' + JSON.stringify(err));
            // should probably inform the user too
            alert("Request Failed");
          });
      }
    });

  });

//------------------------------------/
//SHOW DATASET page
//------------------------------------/

doWhenPresent('body.a_dataviews.show', function dataviewsAdminEditPageIsReady()  {

 loadRelatedContent();

  $('#ClickNotice').click(function embedDataview() {
    $('#preview-wrapper').hide();
    $('#dataview-embed').show();
    SimpleTableau.embed('#dataview-embed', 'edit');
  });
});

doWhenPresent('body.a_dataviews.edit', function dataviewsAdminEditPageIsReady()  {

    var nodeUuid = nodeJson().uuid;

    $('.nav-tabs').tabdrop();
    $('.nav-tabs').css("overflow", "initial");
    $(".nav-tabs").attr("style.overflow","");

    var ajaxOptions = {
      beforeSend: function(xhr) {
        xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
      },
      success: editSuccess,
      error: editFail,
    };

    $.fn.editable.defaults.mode = 'inline';

    $('#updateTableauPreviewButton').click(function requestTableauPreviewUpdate() {
      $('#updateTableauPreviewButton').text('Updating...');
      $.ajax({
        url: '/admin/dataviews/update_tableau_preview/' + nodeUuid,
        type: 'PUT',
        beforeSend: generalAjaxOptions.beforeSend,
      }).
      then(function updatePreviewSuccess() {
        $('#updateTableauPreviewButton').text('Update Tableau Preview');
      }).
      fail(function updatePreviewFail(err) {
        $('#updateTableauPreviewButton').text('Update Tableau Preview');
        displayErrorModal(err);
      });
    });

    adminEditor.editable('#name', 'dataviews', 'name');
    adminEditor.editable('#shortdescription', 'dataviews', 'shortdescription', {"type":"textarea"});
    adminEditor.summernote('#description', 'dataviews', 'description');
    adminEditor.editable('#keywords', 'dataviews', 'keywords', {"clear":true});
    adminEditor.editable('#internal_notes', 'dataviews', 'internal_notes', {"type":"textarea"});
    adminEditor.editable('#author', 'dataviews', 'author');
    adminEditor.editable('#update_frequency', 'dataviews', 'update_frequency');
    adminEditor.editable('#tableau_view_url', 'dataviews', 'tableau_view_url');
    // adminEditor.summernote('#interpretation', 'dataviews', 'interpretation');
    // adminEditor.editable('#service_now_url', 'dataviews', 'service_now_url');

    $('#Status').editable({
        type: 'select',
        title: 'Select Status',
        placement: 'right',
        inputclass: "form-control",
        source: [{
            value: 'Approved',
            text: 'Approved'
          },
          {
            value: 'In Progress',
            text: 'In Progress'
          },
        ],
        pk: nodeUuid,
        url: '/admin/dataviews/modify/' + nodeUuid + '/status',
        ajaxOptions: ajaxOptions,
      });

$('#non_indexed').change(function submitChanges() {
    var postdata = { name: "non_indexed", pk: nodeUuid, value : $('#non_indexed').is(":checked") }
    $.ajax({
    url: '/admin/dataviews/modify/' + nodeUuid + '/non_indexed',
    type: 'POST',
    data: postdata,
    beforeSend: generalAjaxOptions.beforeSend,
    }).
    then(editSuccess).
    fail(editFail);
});

$('#can_download_csv').change(function submitChanges() {
    var postdata = { name: "can_download_csv", pk: nodeUuid, value : $('#can_download_csv').is(":checked") }
    $.ajax({
        url: '/admin/dataviews/modify/' + nodeUuid + '/can_download_csv',
        type: 'POST',
        data: postdata,
        beforeSend: generalAjaxOptions.beforeSend,
    }).
    then(editSuccess).
    fail(editFail);
    });

$('#show_preview_image').change(function submitChanges() {
    var postdata = { name: "show_preview_image", pk: nodeUuid, value : $('#show_preview_image').is(":checked") }
    $.ajax({
        url: '/admin/dataviews/modify/' + nodeUuid + '/show_preview_image',
        type: 'POST',
        data: postdata,
        beforeSend: generalAjaxOptions.beforeSend,
    }).
    then(editSuccess).
    fail(editFail);
    });

$('#show_sample_data').change(function submitChanges() {
  var postdata = { name: "show_sample_data", pk: nodeUuid, value : $('#show_sample_data').is(":checked") }
  $.ajax({
      url: '/admin/dataviews/modify/' + nodeUuid + '/show_sample_data',
      type: 'POST',
      data: postdata,
      beforeSend: generalAjaxOptions.beforeSend,
  }).
  then(editSuccess).
  fail(editFail);
  });

$('#can_download_tableau').change(function submitChanges() {
    var postdata = { name: "can_download_tableau", pk: nodeUuid, value : $('#can_download_tableau').is(":checked") }
    $.ajax({
        url: '/admin/dataviews/modify/' + nodeUuid + '/can_download_tableau',
        type: 'POST',
        data: postdata,
        beforeSend: generalAjaxOptions.beforeSend,
    }).
    then(editSuccess).
    fail(editFail);
    });

       //optionShow_sql_to_end_user
       $('#optionShow_sql_to_end_user').change(function submitChanges() {
        var postdata = { name: "show_sql_to_end_user", pk: nodeUuid, value : $('#optionShow_sql_to_end_user').is(":checked") }
        $.ajax({
          url: '/admin/dataviews/modify/' + nodeUuid + '/show_sql_to_end_user',
          type: 'POST',
          data: postdata,
          beforeSend: generalAjaxOptions.beforeSend,
        }).
        then(editSuccess).
        fail(editFail);
      });

//       $('#dataview_type').editable({
//         type: 'select',
//         title: 'Select Dataview Type',
//         placement: 'right',
//         inputclass: "form-control",
//         source: [{
//             value: 'Tableau',
//             text: 'Tableau'
//           },
//           {
//             value: 'SQL',
//             text: 'SQL'
//           },
//         ],
//         pk: nodeUuid,
//         url: '/admin/dataviews/modify/' + nodeUuid + '/dataview_type',
//         ajaxOptions: ajaxOptions,
//       });

  // ##----------------------------
  // ## TAB: Relationships
  // ##----------------------------

  // //Related Items
  // reloadGraphMap('#related-network', nodeUuid);
  // setUpRelatedItems('#related-items','#related-network', "dataviews");

    // //Related Items
    // setUpRelatedItems('#view-items','#view-network', "dataviews");

  //Definitions
  reloadGraphMap('#term-network', nodeUuid);
  setUpRelatedItems('#term-items','#term-network', "dataviews");

  // // Inbound Sources
  // reloadGraphMap('#source-network-in', nodeUuid);
  // setUpRelatedItems('#source-items-in','#source-network-in', "dataviews", "inbound");

  // // Outbound Sources
  // reloadGraphMap('#source-network-out', nodeUuid);
  // setUpRelatedItems('#source-items-out','#source-network-out', "dataviews", "outbound");

  // ##----------------------------
  // ## TAB: User Comments - TODO
  // ##----------------------------

  // ##----------------------------
  // ## TAB: Change History - TODO
  // ##----------------------------

  // OTHER

    //add jstree button  +  - action
    $("div.input-group a i.fa.fa-plus").click(function () {
      //clear out the search first
      $('#jstreeField').jstree('search', '');
      $("#jstreeField").jstree("open_all");
      //clear text box out
      $("#quickFieldsearch").val('');
  });

  $("div.input-group a i.fa.fa-minus").click(function () {
      //clear out the search first
      $('#jstreeField').jstree('search', '');
      $("#jstreeField").jstree("close_all");
      $("#quickFieldsearch").val('');

  });

  //attach keyup event to quickFieldsearch
  $("#quickFieldsearch").keyup(function () {
      var searchString = $(this).val();
      $('#jstreeField').jstree('search', searchString);

  });

  //hide js tree tooltip  div alt
  $('#jstreeAlt').hide()

			// $('#tree-fieldsa').jstree({
      //   'core' : {
      //       'check_callback' : true
      //   },
      //   'plugins' : [ 'types', 'dnd' ],
      //   'types' : {
      //       'default' : {
      //           'icon' : 'fa fa-folder-o'
      //       },
      //       'dimension' : {
      //           'icon' : 'fa fa-list-alt'
      //       },
      //       'measure' : {
      //           'icon' : 'fa fa-columns'
      //       }
      //   }});

        $('#jstreeField').jstree({
          'core': {
              "multiple": false,
              "animation": 0,
              'themes': {
                "icons": true,
                "variant": "large",
                "dots": false
            },
              // 'types' : {
              //   'default' : {
              //       'icon' : 'fa fa-folder-o'
              //   },
              //   'dimension' : {
              //       'icon' : 'fa fa-list-alt'
              //   },
              //   'measure' : {
              //       'icon' : 'fa fa-columns'
              //   }
              // },

               },

              "search": {

                  "case_insensitive": true,
                  "show_only_matches": true
                  , "show_only_matches_children": true

              },

              "plugins": ['types', 'dnd', "search"]

          })
              .bind("search.jstree", function (e, data) {
                  ////make first item show always??
                  $('ul.jstree-container-ul > li.jstree-node')
                      .show();
              })
              .bind("select_node.jstree", function (node, selected, event) {
                  //redirect to attribute page
                  //check if data is not null

                  if (selected.node.data == null) {
                      //window.location.href = "/";
                      return false;
                  } else {
                      if (selected.node.data.uid != null) {
                          // var url = selected.node.data.type + ":" + selected.node.data.uid;
                          // alert(url);
                          window.location.href = "/Field/ViewItem/" + selected.node.data.type + "/" + selected.node.data.uid;
                      }
                  }

              });

  function editSuccess(json) {
    if(metascoreDisplay) { metascoreDisplay.update(); }
    $('#UpdatedAt').text(json.updated_at);
    $('#UpdatedBy').text(json.updated_by);
    console.log('yay');
  }

  function editFail(err) {
    console.log('error: ' + JSON.stringify(err));
    // should probably inform the user too
    alert("Request Failed");
  }

   $("#jsonform").steps();
});


text:
'use strict';
require('../common');

const assert = require('assert');
const async_hooks = require('async_hooks');
const triggerAsyncId = async_hooks.triggerAsyncId;

const triggerAsyncId0 = triggerAsyncId();
let triggerAsyncId1;

process.nextTick(() => {
  process.nextTick(() => {
    triggerAsyncId1 = triggerAsyncId();
    assert.notStrictEqual(
      triggerAsyncId0,
      triggerAsyncId1,
      'Async resources having different causal ancestry ' +
      'should have different triggerAsyncIds');
  });
  process.nextTick(() => {
    const triggerAsyncId2 = triggerAsyncId();
    assert.strictEqual(
      triggerAsyncId1,
      triggerAsyncId2,
      'Async resources having the same causal ancestry ' +
      'should have the same triggerAsyncId');
  });
});


text:
package com.keyhan.brakessupplier.controller;

import com.keyhan.model.Brake;
import com.keyhan.model.BrakeOrder;
import com.keyhan.model.BrakeType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by keyhan on 2016-11-13.
 */
@RestController
@Slf4j
public class BrakeController {

    @RequestMapping(method = RequestMethod.POST, path="/brake",consumes= MediaType.APPLICATION_JSON_VALUE
            , produces = MediaType.APPLICATION_JSON_VALUE)
    public Brake handleOrder(@RequestBody BrakeOrder brakeOrder) throws UnknownHostException, InterruptedException {

        InetAddress ip = InetAddress.getLocalHost();

        log.info("new brake order recieved: "+ brakeOrder);
        log.info("this server hostname is: " + ip.getHostName());

        Thread.sleep(1000);
        return Brake.builder().brakeType(BrakeType.Disc)
                    .manufacturer("Keyhanu").model("101").build();

    }
}


text:
export CPPLIBS=$HOME/oop/projects/libs
export LD_LIBRARY_PATH=$CPPLIBS


text:
Angular Todo App
================

Simple todo app with angularjs.

Release: 0.0.1

## Deployment

http://richistron.github.io/todo-angular

## Status

[![Build Status](https://travis-ci.org/richistron/todo-angular.png?branch=master)](https://travis-ci.org/richistron/todo-angular)

Install
=======

```
npm install
bower install
```

Run development server

```
grunt server
```

Deployment, testing and build

```
grunt
```

Unit testing

```
grunt test
```

Install yeoman ubuntu 12.04
===========================

Yeoman requires nodejs and ruby to run, if you have installed this two already, go ahead to step 3.

### Step 1 (installing ruby)

```
sudo apt-get update

sudo apt-get install curl

\curl -L https://get.rvm.io | bash -s stable

source ~/.rvm/scripts/rvm

rvm requirements

rvm install ruby

rvm use ruby --default

rvm rubygems current

```

Source: [digitalocean](https://www.digitalocean.com/community/articles/how-to-install-ruby-on-rails-on-ubuntu-12-04-lts-precise-pangolin-with-rvm)

### Step 2 (installing nodejs)

```
sudo apt-get update

sudo apt-get install build-essential openssl libssl-dev pkg-config

cd ~/

wget http://nodejs.org/dist/node-latest.tar.gz

tar -xzf node-latest.tar.gz

cd node-v*

sudo make install
```

### Step 3 (installing yo)

```
npm install -g yo
```


text:
begin
  require 'minitest'
rescue LoadError
end
require 'minitest/autorun'

$LOAD_PATH.unshift File.join( File.dirname( File.expand_path( __FILE__ ) ),
                              '..', 'lib' )
# due to development dependencies we have a cycle, so remove it
$LOAD_PATH.delete_if { |lp| lp.match /maven-tools-/ }


text:
namespace autofill {

struct IcuEnvironment {
  IcuEnvironment() { CHECK(base::i18n::InitializeICU()); }
  // Used by ICU integration.
  base::AtExitManager at_exit_manager;
};

IcuEnvironment* env = new IcuEnvironment();

extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
  // At least 2 bytes are needed for |default_region|, due to the
  // ParsePhoneNumber contract.
  if (size < 2)
    return 0;

  std::string default_region(reinterpret_cast<const char*>(data), 2);
  std::u16string value(reinterpret_cast<const char16_t*>(data + 2),
                       (size - 2) / 2);
  std::u16string dummy_country_code;
  std::u16string dummy_city_code;
  std::u16string dummy_number;
  std::string dummy_inferred_region;
  ::i18n::phonenumbers::PhoneNumber dummy_i18n_number;

  bool dummy_result = i18n::ParsePhoneNumber(
      value, default_region, &dummy_country_code, &dummy_city_code,
      &dummy_number, &dummy_inferred_region, &dummy_i18n_number);
  if (dummy_result)
    return 0;
  return 0;
}

}  // namespace autofill


text:
;(function() {
	'use strict';

	angular.module('app', ['ui.router'])
	.config(function($stateProvider, $urlRouterProvider, $locationProvider) {

		$locationProvider.html5Mode(true);
		$urlRouterProvider.otherwise('/');

		$stateProvider
			.state('home', {
				url: '/'
			});

	});
})();