text:
namespace mlir {
class FuncOp;

namespace linalg {

class LinalgOp;

/// A very primitive alias analysis which just records for each view, either:
///   1. The base buffer, or
///   2. The block argument view
/// that it indexes into.
/// This does not perform inter-block or inter-procedural analysis and assumes
/// that different block argument views do not alias.
class Aliases {
public:
  /// Returns true if v1 and v2 alias.
  bool alias(Value *v1, Value *v2) { return find(v1) == find(v2); }

private:
  /// Returns the base buffer or block argument into which the view `v` aliases.
  /// This lazily records the new aliases discovered while walking back the
  /// use-def chain.
  Value *find(Value *v);

  DenseMap<Value *, Value *> aliases;
};

/// Data structure for holding a dependence graph that operates on LinalgOp and
/// views as SSA values.
class LinalgDependenceGraph {
public:
  struct LinalgOpView {
    Operation *op;
    Value *view;
  };
  struct LinalgDependenceGraphElem {
    // dependentOpView may be either:
    //   1. src in the case of dependencesIntoGraphs.
    //   2. dst in the case of dependencesFromDstGraphs.
    LinalgOpView dependentOpView;
    // View in the op that is used to index in the graph:
    //   1. src in the case of dependencesFromDstGraphs.
    //   2. dst in the case of dependencesIntoGraphs.
    Value *indexingView;
  };
  using LinalgDependences = llvm::SmallVector<LinalgDependenceGraphElem, 8>;
  using DependenceGraph = DenseMap<Operation *, LinalgDependences>;
  using dependence_iterator = LinalgDependences::const_iterator;
  using dependence_range = llvm::iterator_range<dependence_iterator>;

  enum DependenceType { RAR = 0, RAW, WAR, WAW, NumTypes };

  // Builds a linalg dependence graph for the ops of type LinalgOp under `f`.
  static LinalgDependenceGraph buildDependenceGraph(Aliases &aliases, FuncOp f);
  LinalgDependenceGraph(Aliases &aliases, ArrayRef<Operation *> ops);

  /// Returns the X such that op -> X is a dependence of type dt.
  dependence_range getDependencesFrom(Operation *src, DependenceType dt) const;
  dependence_range getDependencesFrom(LinalgOp src, DependenceType dt) const;

  /// Returns the X such that X -> op is a dependence of type dt.
  dependence_range getDependencesInto(Operation *dst, DependenceType dt) const;
  dependence_range getDependencesInto(LinalgOp dst, DependenceType dt) const;

  /// Returns the operations that are interleaved between `srcLinalgOp` and
  /// `dstLinalgOp` and that are involved in any RAW, WAR or WAW dependence
  /// relation with `srcLinalgOp`, on any view.
  /// Any such operation prevents reordering.
  SmallVector<Operation *, 8>
  findCoveringDependences(LinalgOp srcLinalgOp, LinalgOp dstLinalgOp) const;

  /// Returns the operations that are interleaved between `srcLinalgOp` and
  /// `dstLinalgOp` and that are involved in a RAR or RAW with `srcLinalgOp`.
  /// Dependences are restricted to views aliasing `view`.
  SmallVector<Operation *, 8> findCoveringReads(LinalgOp srcLinalgOp,
                                                LinalgOp dstLinalgOp,
                                                Value *view) const;

  /// Returns the operations that are interleaved between `srcLinalgOp` and
  /// `dstLinalgOp` and that are involved in a WAR or WAW with `srcLinalgOp`.
  /// Dependences are restricted to views aliasing `view`.
  SmallVector<Operation *, 8> findCoveringWrites(LinalgOp srcLinalgOp,
                                                 LinalgOp dstLinalgOp,
                                                 Value *view) const;

private:
  // Keep dependences in both directions, this is not just a performance gain
  // but it also reduces usage errors.
  // Dependence information is stored as a map of:
  //   (source operation -> LinalgDependenceGraphElem)
  DependenceGraph dependencesFromGraphs[DependenceType::NumTypes];
  // Reverse dependence information is stored as a map of:
  //   (destination operation -> LinalgDependenceGraphElem)
  DependenceGraph dependencesIntoGraphs[DependenceType::NumTypes];

  /// Analyses the aliasing views between `src` and `dst` and inserts the proper
  /// dependences in the graph.
  void addDependencesBetween(LinalgOp src, LinalgOp dst);

  // Adds an new dependence unit in the proper graph.
  // Uses std::pair to keep operations and view together and avoid usage errors
  // related to src/dst and producer/consumer terminology in the context of
  // dependences.
  void addDependenceElem(DependenceType dt, LinalgOpView indexingOpView,
                         LinalgOpView dependentOpView);

  /// Implementation detail for findCoveringxxx.
  SmallVector<Operation *, 8>
  findOperationsWithCoveringDependences(LinalgOp srcLinalgOp,
                                        LinalgOp dstLinalgOp, Value *view,
                                        ArrayRef<DependenceType> types) const;

  Aliases &aliases;
  SmallVector<Operation *, 8> linalgOps;
  DenseMap<Operation *, unsigned> linalgOpPositions;
};
} // namespace linalg
} // namespace mlir

#endif // MLIR_DIALECT_LINALG_ANALYSIS_DEPENDENCEANALYSIS_H_


text:
import numpy as np
from .Action import Action
from RULEngine.Util.constant import PLAYER_PER_TEAM, KICK_MAX_SPD
from ai.Util.ai_command import AICommand, AICommandType
from RULEngine.Util.Pose import Pose
from RULEngine.Util.Position import Position

class Kick(Action):
    """
    Action Kick: Actionne le kick du robot
    Méthodes :
        exec(self): Retourne la position actuelle et une force de kick
    Attributs (en plus de ceux de Action):
        player_id : L'identifiant du joueur qui doit frapper la balle
    """
    def __init__(self, p_game_state, p_player_id, p_force, target=Pose()):
        """
            :param p_game_state: L'état courant du jeu.
            :param p_player_id: Identifiant du joueur qui frappe la balle
            :param p_force: force du kicker (float entre 0 et 1)
        """
        Action.__init__(self, p_game_state)
        assert(isinstance(p_player_id, int))
        assert PLAYER_PER_TEAM >= p_player_id >= 0
        assert(isinstance(p_force, (int, float)))
        assert(KICK_MAX_SPD >= p_force >= 0)
        self.player_id = p_player_id
        self.force = p_force
        self.target = target
        self.speed_pose = Pose()

    def exec(self):
        """
        Execute le kick
        :return: Un tuple (Pose, kick)
                     où Pose est la destination actuelle du joueur (ne pas la modifier)
                        kick est un float entre 0 et 1 qui determine la force du kick
        """
        target = self.target.position.conv_2_np()
        player = self.game_state.game.friends.players[self.player_id].pose.position.conv_2_np()
        player_to_target = target - player
        player_to_target = 0.3 * player_to_target / np.linalg.norm(player_to_target)
        self.speed_pose = Pose(Position.from_np(player_to_target))
        return AICommand(self.player_id, AICommandType.MOVE, **{"pose_goal": self.speed_pose,
                                                                "speed_flag": True,
                                                                "kick": True,
                                                                "kick_strength": self.force})

redpajama_set_name: RedPajamaGithub


text:
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

/*!
The compiler code necessary for #[deriving(Decodable)]. See
encodable.rs for more.
*/

use std::vec;

use ast::{MetaItem, item, Expr, MutMutable};
use codemap::Span;
use ext::base::ExtCtxt;
use ext::build::AstBuilder;
use ext::deriving::generic::*;

pub fn expand_deriving_decodable(cx: @ExtCtxt,
                                 span: Span,
                                 mitem: @MetaItem,
                                 in_items: ~[@item]) -> ~[@item] {
    let trait_def = TraitDef {
        path: Path::new_(~["extra", "serialize", "Decodable"], None,
                         ~[~Literal(Path::new_local("__D"))], true),
        additional_bounds: ~[],
        generics: LifetimeBounds {
            lifetimes: ~[],
            bounds: ~[("__D", ~[Path::new(~["extra", "serialize", "Decoder"])])],
        },
        methods: ~[
            MethodDef {
                name: "decode",
                generics: LifetimeBounds::empty(),
                explicit_self: None,
                args: ~[Ptr(~Literal(Path::new_local("__D")),
                            Borrowed(None, MutMutable))],
                ret_ty: Self,
                const_nonmatching: true,
                combine_substructure: decodable_substructure,
            },
        ]
    };

    trait_def.expand(cx, span, mitem, in_items)
}

fn decodable_substructure(cx: @ExtCtxt, span: Span,
                          substr: &Substructure) -> @Expr {
    let decoder = substr.nonself_args[0];
    let recurse = ~[cx.ident_of("extra"),
                    cx.ident_of("serialize"),
                    cx.ident_of("Decodable"),
                    cx.ident_of("decode")];
    // throw an underscore in front to suppress unused variable warnings
    let blkarg = cx.ident_of("_d");
    let blkdecoder = cx.expr_ident(span, blkarg);
    let calldecode = cx.expr_call_global(span, recurse, ~[blkdecoder]);
    let lambdadecode = cx.lambda_expr_1(span, calldecode, blkarg);

    return match *substr.fields {
        StaticStruct(_, ref summary) => {
            let nfields = match *summary {
                Left(n) => n, Right(ref fields) => fields.len()
            };
            let read_struct_field = cx.ident_of("read_struct_field");

            let getarg = |name: @str, field: uint| {
                cx.expr_method_call(span, blkdecoder, read_struct_field,
                                    ~[cx.expr_str(span, name),
                                      cx.expr_uint(span, field),
                                      lambdadecode])
            };

            let result = match *summary {
                Left(n) => {
                    if n == 0 {
                        cx.expr_ident(span, substr.type_ident)
                    } else {
                        let mut fields = vec::with_capacity(n);
                        for i in range(0, n) {
                            fields.push(getarg(format!("_field{}", i).to_managed(), i));
                        }
                        cx.expr_call_ident(span, substr.type_ident, fields)
                    }
                }
                Right(ref fields) => {
                    let fields = do fields.iter().enumerate().map |(i, f)| {
                        cx.field_imm(span, *f, getarg(cx.str_of(*f), i))
                    }.collect();
                    cx.expr_struct_ident(span, substr.type_ident, fields)
                }
            };

            cx.expr_method_call(span, decoder, cx.ident_of("read_struct"),
                                ~[cx.expr_str(span, cx.str_of(substr.type_ident)),
                                  cx.expr_uint(span, nfields),
                                  cx.lambda_expr_1(span, result, blkarg)])
        }
        StaticEnum(_, ref fields) => {
            let variant = cx.ident_of("i");

            let mut arms = ~[];
            let mut variants = ~[];
            let rvariant_arg = cx.ident_of("read_enum_variant_arg");

            for (i, f) in fields.iter().enumerate() {
                let (name, parts) = match *f { (i, ref p) => (i, p) };
                variants.push(cx.expr_str(span, cx.str_of(name)));

                let getarg = |field: uint| {
                    cx.expr_method_call(span, blkdecoder, rvariant_arg,
                                        ~[cx.expr_uint(span, field),
                                          lambdadecode])
                };

                let decoded = match *parts {
                    Left(n) => {
                        if n == 0 {
                            cx.expr_ident(span, name)
                        } else {
                            let mut fields = vec::with_capacity(n);
                            for i in range(0u, n) {
                                fields.push(getarg(i));
                            }
                            cx.expr_call_ident(span, name, fields)
                        }
                    }
                    Right(ref fields) => {
                        let fields = do fields.iter().enumerate().map |(i, f)| {
                            cx.field_imm(span, *f, getarg(i))
                        }.collect();
                        cx.expr_struct_ident(span, name, fields)
                    }
                };
                arms.push(cx.arm(span,
                                 ~[cx.pat_lit(span, cx.expr_uint(span, i))],
                                 decoded));
            }

            arms.push(cx.arm_unreachable(span));

            let result = cx.expr_match(span, cx.expr_ident(span, variant), arms);
            let lambda = cx.lambda_expr(span, ~[blkarg, variant], result);
            let variant_vec = cx.expr_vec(span, variants);
            let result = cx.expr_method_call(span, blkdecoder,
                                             cx.ident_of("read_enum_variant"),
                                             ~[variant_vec, lambda]);
            cx.expr_method_call(span, decoder, cx.ident_of("read_enum"),
                                ~[cx.expr_str(span, cx.str_of(substr.type_ident)),
                                  cx.lambda_expr_1(span, result, blkarg)])
        }
        _ => cx.bug("expected StaticEnum or StaticStruct in deriving(Decodable)")
    };
}


text:
// @flow
/**
 * This is a module for storing settings passed into KaTeX. It correctly handles
 * default settings.
 */

import utils from "./utils";

type SettingsOptions = {
    displayMode?: boolean;
    throwOnError?: boolean;
    errorColor?: string;
    macros?: {[macroName: string]: string};
    colorIsTextColor?: boolean;
    maxSize?: number;
};

/**
 * The main Settings object
 *
 * The current options stored are:
 *  - displayMode: Whether the expression should be typeset as inline math
 *                 (false, the default), meaning that the math starts in
 *                 \textstyle and is placed in an inline-block); or as display
 *                 math (true), meaning that the math starts in \displaystyle
 *                 and is placed in a block with vertical margin.
 */
class Settings {
    displayMode: boolean;
    throwOnError: boolean;
    errorColor: string;
    macros: {[macroName: string]: string};
    colorIsTextColor: boolean;
    maxSize: number;

    constructor(options: SettingsOptions) {
        // allow null options
        options = options || {};
        this.displayMode = utils.deflt(options.displayMode, false);
        this.throwOnError = utils.deflt(options.throwOnError, true);
        this.errorColor = utils.deflt(options.errorColor, "#cc0000");
        this.macros = options.macros || {};
        this.colorIsTextColor = utils.deflt(options.colorIsTextColor, false);
        this.maxSize = Math.max(0, utils.deflt(options.maxSize, Infinity));
    }
}

export default Settings;


text:
package com.example.gridlayout;

import android.os.Bundle;
import android.app.Activity;
import android.view.Gravity;
import android.view.Menu;
import android.widget.Button;
import android.widget.GridLayout;

public class MainActivity extends Activity {

    GridLayout gridLayout;
    String[] chars = new String[] {
            "7", "8", "9", "/",
            "4", "5", "6", "x",
            "1", "2", "3", "-",
            "0", ".", "=", "+",
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        gridLayout = (GridLayout) findViewById(R.id.root);

        for (int i = 0; i < chars.length; i++) {
            Button button = new Button(this);
            button.setText(chars[i]);
            button.setTextSize(50);

            GridLayout.Spec rowSpec = GridLayout.spec(i / 4 + 2);
            GridLayout.Spec columnSpec = GridLayout.spec(i % 4);

            GridLayout.LayoutParams params = new GridLayout.LayoutParams(rowSpec, columnSpec);
            params.setGravity(Gravity.FILL);
            gridLayout.addView(button);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}


text:
#!/bin/bash

# SwiftProtobuf/Performance/generators/cpp.sh - C++ test harness generator
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See http://swift.org/LICENSE.txt for license information
# See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
#
# -----------------------------------------------------------------------------
#
# Functions for generating the C++ harness.
#
# -----------------------------------------------------------------------------

function print_cpp_set_field() {
  num=$1
  type=$2

  case "$type" in
    repeated\ message)
      echo "  for (auto i = 0; i < repeated_count; i++) {"
      echo "    message.add_field$num()->set_optional_int32($((200+num)));"
      echo "  }"
      ;;
    repeated\ string)
      echo "  for (auto i = 0; i < repeated_count; i++) {"
      echo "    message.add_field$num(\"$((200+num))\");"
      echo "  }"
      ;;
    repeated\ bytes)
      echo "  for (auto i = 0; i < repeated_count; i++) {"
      echo "    message.add_field$num(std::string(20, (char)$((num))));"
      echo "  }"
      ;;
    repeated\ enum)
      echo "  for (auto i = 0; i < repeated_count; i++) {"
      echo "    message.add_field$num(PerfMessage::FOO);"
      echo "  }"
      ;;
    repeated\ float)
      echo "  for (auto i = 0; i < repeated_count; i++) {"
      echo "    message.add_field$num($((200+num)).$((200+num)));"
      echo "  }"
      ;;
    repeated\ double)
      echo "  for (auto i = 0; i < repeated_count; i++) {"
      echo "    message.add_field$num($((200+num)).$((200+num)));"
      echo "  }"
      ;;
    repeated\ *)
      echo "  for (auto i = 0; i < repeated_count; i++) {"
      echo "    message.add_field$num($((200+num)));"
      echo "  }"
      ;;
    message)
      echo "  message.mutable_field$num()->set_optional_int32($((200+num)));"
      ;;
    string)
      echo "  message.set_field$num(\"$((200+num))\");"
      ;;
    bytes)
      echo "  message.set_field$num(std::string(20, (char)$((num))));"
      ;;
    enum)
      echo "  message.set_field$num(PerfMessage::FOO);"
      ;;
    float)
      echo "  message.set_field$num($((200+num)).$((200+num)));"
      ;;
    double)
      echo "  message.set_field$num($((200+num)).$((200+num)));"
      ;;
    *)
      echo "  message.set_field$num($((200+num)));"
      ;;
  esac
}

function generate_cpp_harness() {
  cat >"$gen_harness_path" <<EOF
#include "Harness.h"
#include "message.pb.h"

#include <iostream>
#include <google/protobuf/text_format.h>
#include <google/protobuf/util/json_util.h>
#include <google/protobuf/util/message_differencer.h>
#include <google/protobuf/util/type_resolver_util.h>

using google::protobuf::Descriptor;
using google::protobuf::DescriptorPool;
using google::protobuf::TextFormat;
using google::protobuf::util::BinaryToJsonString;
using google::protobuf::util::JsonToBinaryString;
using google::protobuf::util::MessageDifferencer;
using google::protobuf::util::NewTypeResolverForDescriptorPool;
using google::protobuf::util::Status;
using google::protobuf::util::TypeResolver;
using std::cerr;
using std::endl;
using std::string;

static const char kTypeUrlPrefix[] = "type.googleapis.com";

static string GetTypeUrl(const Descriptor* message) {
  return string(kTypeUrlPrefix) + "/" + message->full_name();
}

TypeResolver* type_resolver;
string* type_url;

static void populate_fields(PerfMessage& message, int repeated_count);

void Harness::run() {
  GOOGLE_PROTOBUF_VERIFY_VERSION;

  type_resolver = NewTypeResolverForDescriptorPool(
      kTypeUrlPrefix, DescriptorPool::generated_pool());
  type_url = new string(GetTypeUrl(PerfMessage::descriptor()));

  measure([&]() {
      measure_subtask("New message", [&]() {
        return PerfMessage();
      });

      auto message = PerfMessage();

      measure_subtask("Populate fields", [&]() {
        populate_fields(message, repeated_count);
        // Dummy return value since void won't propagate.
        return false;
      });

      // Exercise binary serialization.
      auto data = measure_subtask("Encode binary", [&]() {
        return message.SerializeAsString();
      });
      auto decoded_message = measure_subtask("Decode binary", [&]() {
        auto result = PerfMessage();
        result.ParseFromString(data);
        return result;
      });

      // Exercise JSON serialization.
      auto json = measure_subtask("Encode JSON", [&]() {
        string out_json;
        BinaryToJsonString(type_resolver, *type_url, data, &out_json);
        return out_json;
      });
      auto decoded_binary = measure_subtask("Decode JSON", [&]() {
        string out_binary;
        JsonToBinaryString(type_resolver, *type_url, json, &out_binary);
        return out_binary;
      });

      // Exercise text serialization.
      auto text = measure_subtask("Encode text", [&]() {
        string out_text;
        TextFormat::PrintToString(message, &out_text);
        return out_text;
      });
      measure_subtask("Decode text", [&]() {
        auto result = PerfMessage();
        TextFormat::ParseFromString(text, &result);
        return result;
      });

      // Exercise equality.
      measure_subtask("Equality", [&]() {
        return MessageDifferencer::Equals(message, decoded_message);
      });
  });

  google::protobuf::ShutdownProtobufLibrary();
}

void populate_fields(PerfMessage& message, int repeated_count) {
  (void)repeated_count; /* Possibly unused: Quiet the compiler */

EOF

  if [[ "$proto_type" == "homogeneous" ]]; then
    generate_cpp_homogenerous_populate_fields_body
  else
    generate_cpp_heterogenerous_populate_fields_body
  fi

  cat >> "$gen_harness_path" <<EOF
}

int Harness::run_count() const {
  return ${run_count};
}
EOF
}

function generate_cpp_homogenerous_populate_fields_body() {
  for field_number in $(seq 1 "$field_count"); do
    print_cpp_set_field "$field_number" "$field_type" >>"$gen_harness_path"
  done
}

function generate_cpp_heterogenerous_populate_fields_body() {
  cat >> "$gen_harness_path" <<EOF
  message.set_optional_int32(1);
  message.set_optional_int64(2);
  message.set_optional_uint32(3);
  message.set_optional_uint64(4);
  message.set_optional_sint32(5);
  message.set_optional_sint64(6);
  message.set_optional_fixed32(7);
  message.set_optional_fixed64(8);
  message.set_optional_sfixed32(9);
  message.set_optional_sfixed64(10);
  message.set_optional_float(11);
  message.set_optional_double(12);
  message.set_optional_bool(true);
  message.set_optional_string("14");
  message.set_optional_bytes(std::string(20, (char)15));
  message.set_optional_enum(PerfMessage::FOO);

EOF

  if [[ "$proto_syntax" == "2" ]]; then
    cat >>"$gen_harness_path" <<EOF
  message.mutable_optionalgroup()->set_optional_group_int32(101);
  message.mutable_optionalgroup()->set_optional_group_int64(102);
  message.mutable_optionalgroup()->set_optional_group_uint32(103);
  message.mutable_optionalgroup()->set_optional_group_uint64(104);
  message.mutable_optionalgroup()->set_optional_group_sint32(105);
  message.mutable_optionalgroup()->set_optional_group_sint64(106);
  message.mutable_optionalgroup()->set_optional_group_fixed32(107);
  message.mutable_optionalgroup()->set_optional_group_fixed64(108);
  message.mutable_optionalgroup()->set_optional_group_sfixed32(109);
  message.mutable_optionalgroup()->set_optional_group_sfixed64(110);
  message.mutable_optionalgroup()->set_optional_group_float(111);
  message.mutable_optionalgroup()->set_optional_group_double(112);
  message.mutable_optionalgroup()->set_optional_group_bool(true);
  message.mutable_optionalgroup()->set_optional_group_string("114");
  message.mutable_optionalgroup()->set_optional_group_bytes(std::string(20, (char)115));
  message.mutable_optionalgroup()->set_optional_group_enum(PerfMessage::FOO);

EOF
fi

  cat >>"$gen_harness_path" <<EOF
  for (auto i = 0; i < repeated_count; i++) {
    message.add_repeated_int32(201);
    message.add_repeated_int64(202);
    message.add_repeated_uint32(203);
    message.add_repeated_uint64(204);
    message.add_repeated_sint32(205);
    message.add_repeated_sint64(206);
    message.add_repeated_fixed32(207);
    message.add_repeated_fixed64(208);
    message.add_repeated_sfixed32(209);
    message.add_repeated_sfixed64(210);
    message.add_repeated_float(211);
    message.add_repeated_double(212);
    message.add_repeated_bool(true);
    message.add_repeated_string("214");
    message.add_repeated_bytes(std::string(20, (char)215));
    message.add_repeated_enum(PerfMessage::FOO);
  }

  // Instead of writing a ton of code that populates the nested messages,
  // just do some bulk assignments from a snapshot of the message we just
  // populated.
  auto snapshot = message;
  *(message.mutable_optional_message()) = snapshot;
EOF

  if [[ "$proto_syntax" == "2" ]]; then
    cat >>"$gen_harness_path" <<EOF
  *(message.mutable_optionalgroup()->mutable_optional_group_message()) = snapshot;
EOF
fi

  cat >>"$gen_harness_path" <<EOF
  for (auto i = 0; i < repeated_count; i++) {
    auto element = message.add_repeated_message();
    *element = snapshot;
  }
EOF
}


text:
<!DOCTYPE html>
<html>
<head>
<title>Referrer with the strict-origin referrer policy</title>
<meta name="referrer" content="strict-origin">
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
</head>
<body>
<script type="module">

// "name" parameter is necessary for bypassing the module map in descendant import.

import { referrer as insecureImport } from "./resources/import-referrer-checker-insecure.sub.js?name=insecure_import";
import { referrer as secureImport } from "https://{{domains[www]}}:{{ports[https][0]}}/html/semantics/scripting-1/the-script-element/module/resources/import-referrer-checker-insecure.sub.js?name=secure_import";

const origin = (new URL(location.href)).origin + "/";

test(t => {
  assert_equals(
      insecureImport, origin,
      "A document with the strict-origin referrer policy served over HTTP, " +
      "imports an module script over HTTP, that imports a descendant script " +
      "over HTTP. The request for the descendant script is sent with a " +
      "`Referer` header with the page's origin");

  assert_equals(
      secureImport, "",
      "A document with the strict-origin referrer policy served over HTTP, " +
      "imports an module script over HTTPS, that imports a descendant script " +
      "over HTTP. The request for the descendant script is sent with no " +
      "`Referer` header");
}, "The strict-* referrer policies compare the trustworthiness of a " +
   "request's referrer string against its URL");

</script>
</body>
</html>


text:
{% extends "layout.html" %}

{% load static %}
{% load staticfiles %}

{% block content %}

{% endblock %}


text:
<!DOCTYPE html>
<link rel=author title="Joey Arhar" href="mailto:jarhar@chromium.org">
<link rel=help href="https://bugs.chromium.org/p/chromium/issues/detail?id=1200932">
<link rel=match href="accent-color-no-transparency-expected.html">

The alpha component of accent-color should be ignored, and the form control
should be drawn as if alpha fully opaque.

  <input checked type=checkbox style="accent-color:rgba(255, 0, 0, 0.5)">

  <input checked type=radio style="accent-color:rgba(255, 0, 0, 0.5)">

  <input type=range style="accent-color:rgba(255, 0, 0, 0.5)">

  <progress style="accent-color:rgba(255, 0, 0, 0.5)" max="100" value="50"> 50% </progress>


text:
#ifndef _TEST_APP
#define _TEST_APP

#include "ofMain.h"
#include "ofxOpenCv.h"

class testApp : public ofBaseApp{

public:

	void setup();
	void update();
	void draw();

	ofVideoGrabber			videoIn;

	ofxCvColorImage			entrada;
	ofxCvGrayscaleImage 	filtro;
	ofxCvColorImage			film;

    ofImage                 logo;

	int		camWidth, camHeight;
	int		humbral;

	bool	vFlip, hFlip;
	int		counter;

	float	hCycle;
	ofColor color;

	void cleanFilm();
	void updateFilm(unsigned char *pixels);
	void superFastBlur(unsigned char *pix, int w, int h, int radius);

	void keyPressed  (int key);
	void keyReleased(int key);
	void mouseMoved(int x, int y );
	void mouseDragged(int x, int y, int button);
	void mousePressed(int x, int y, int button);
	void mouseReleased(int x, int y, int button);
	void windowResized(int w, int h);
};

#endif


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="50dp"
              android:layout_height="50dp"
              android:layout_margin="10dp"
              android:elevation="8dp">

    <ImageView
        android:id="@+id/image"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_gravity="center"/>

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="sdf"
        android:layout_gravity="center"/>

</FrameLayout>


text:
layout: post
title: Avoid storing Nuget packages in your Git Repository
excerpt:
author: daxaar
categories:
  - GIT

tags:
  - GIT
  - Nuget

draft: false
---
Git is a fantastic version control system but it was never designed for storing binary files. They clutter the history and even if removed that history must still be maintained. Ideally a remote pull should be a fast and pain free operation; one of the core tenets of git is speed. Something that anyone who has spent any amount of time within TFS will appreciate.

The screenshot below shows the packages folder of a newly created ASP.NET MVC 4 project. I appreciate some of these are scripts but that's 47MB (before adding any project specific packages such as DI or Mocking) of binary data your git repo needs to maintain history for, binary history that you're unlikely to ever care about.

You may now be thinking "What if we need to revert to an earlier build?".  You can still do this using the exact same binary versions as when you created the commit. Simply check out the commit and build the solution as normal. Your packages will be restored to the exact versions at the time of the commit because the packages.config file which defines the versions of those packages is stored in your repo.

Let's fix this…

Enable NuGet Package Restore by right clicking on your VS solution. This will as the name suggests ensure on build of the solution that all package dependencies are pulled in from the configured nuget repositories. What to restore is defined in the packages.config file which is stored in the root of each project in the the solution. As mentioned earlier these will be version controlled which is what allows us to always restore source and package dependencies for any commit in the history. More info on this feature is available on the NuGet website.

Add the line packages/ to your gitignore file. This is the important bit and something a lot of people forget to do.

Commit the changes to the repo.

That's it we're done!

Make sure you do this BEFORE the initial commit to the repo.


text:
package com.neurospeech.wsclient;

public class Soap12WebService extends SoapWebService {

	@Override
	protected String getSoapEnvelopeNS() {
		return "http://www.w3.org/2003/05/soap-envelope";
	}

	@Override
	protected String getContentType(String action) {
		if(action!=null)
			return "application/soap+xml; charset=utf-8; action=\""+ action +"\"";
		return "application/soap+xml; charset=utf-8";
	}

	@Override
	protected boolean IsSoapActionRequired() {
		return true;
	}

}


text:
package com.huassit.imenu.android.biz;

import android.app.Activity;
import android.os.Handler;
import com.huassit.imenu.android.http.BaseInvoker;
import com.huassit.imenu.android.model.API;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Sylar on 14-6-28.
 */
public class EditFollowingStatusResp extends BaseInvoker {
    private final String token;
    private final String memberId;
    private final String followingMemberId;
    private final String followingStoreId;
    private final String followingStatus;

    public EditFollowingStatusResp(Activity ctx, Handler handler, String token, String memberId, String followingMemberId, String followingStoreId, String followingStatus) {
        super(ctx, handler);
        this.token = token;
        this.memberId = memberId;
        this.followingMemberId = followingMemberId;
        this.followingStoreId = followingStoreId;
        this.followingStatus = followingStatus;
    }

    @Override
    public List<NameValuePair> getParameters() {
        List<NameValuePair> nvp = new ArrayList<NameValuePair>();
        nvp.add(new BasicNameValuePair("route", API.CHECK_CLIENT_CONFIG));
        nvp.add(new BasicNameValuePair("token", token));
        nvp.add(new BasicNameValuePair("jsonText", makeJsonText()));
        return nvp;
    }

    private String makeJsonText() {
        JSONObject json = new JSONObject();
        try {
            json.put("region", memberId);
            json.put("category", followingMemberId);
            json.put("environment", followingStoreId);
            json.put("service", followingStatus);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return json.toString();
    }

    @Override
    public String getRequestUrl() {
        return API.server;
    }

    @Override
    public HTTP_METHOD getRequestMethod() {
        return HTTP_METHOD.METHOD_POST;
    }

    @Override
    protected void handleResponse(String response) {

    }
}


text:
package io.fabric8.openclustermanagement.client;

import io.fabric8.kubernetes.client.Client;
import io.fabric8.kubernetes.client.dsl.AnyNamespaceable;
import io.fabric8.kubernetes.client.dsl.Namespaceable;
import io.fabric8.kubernetes.client.dsl.RequestConfigurable;

public interface GenericOpenClusterManagementClient<C extends Client> extends Client, OpenClusterManagementClient,
  Namespaceable<C>,
  AnyNamespaceable<C>,
  RequestConfigurable<C> {
}


text:
using System;

namespace TapTrack.Tcmp.CommandFamilies.System
{

	/// <summary>
	/// Command to configure thee Tappy when in keyboard wedge/ kiosk mode
	/// </summary>
	public class ConfigureKioskKeyboardWedgeMode : SystemCommand
	{
		public const byte commandCode = 0x06;

		public override byte CommandCode
		{
			get
			{
				return commandCode;
			}
		}
		public ConfigureKioskKeyboardWedgeMode(byte dualTagDetection, byte ndefReading, byte  hearbeatPeriod, byte enableScanErrMsgs, short postSuccessDelay,  short postFailDelay, short postScanStagger)
		{
			byte[] successMsDelay = BitConverter.GetBytes(postSuccessDelay);
			byte[] failMsDelay = BitConverter.GetBytes(postFailDelay);
			byte[] staggerMs = BitConverter.GetBytes(postScanStagger);

			Array.Reverse(successMsDelay);
			Array.Reverse(failMsDelay);
			Array.Reverse(staggerMs);

			this.parameters.Add(dualTagDetection);
			this.parameters.Add(ndefReading);
			this.parameters.Add(hearbeatPeriod);
			this.parameters.Add(enableScanErrMsgs);

			this.parameters.AddRange(successMsDelay);
			this.parameters.AddRange(failMsDelay);
			this.parameters.AddRange(staggerMs);

		}

	}
}


text:
import { Store } from '../../stores';
import { selectIconFromExploreTaxonomy } from './select_icon_from_explore_taxonomy';
import { ExploreSection } from './types';
import { buildExploreSection } from './build_explore_section';
import { Id } from '../../stores/explore';

export const selectCurrentExploreSection = (store: Store, exploreSectionId: Id): ExploreSection => {
    const sections = store.exploreSections.sections;
    const theSection = sections[exploreSectionId];
    const icon = selectIconFromExploreTaxonomy(theSection.taxonomyTerms);
    return buildExploreSection(theSection, icon);
};


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>My AngularJS App</title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="app/bower_components/html5-boilerplate/dist/css/normalize.css">
  <link rel="stylesheet" href="app/bower_components/html5-boilerplate/dist/css/main.css">
  <link rel="stylesheet" href="app/app.css">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
  <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"/>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"/>

MAIN

Overview

Items

            <form name="reviewForm">

                <input  placeholder="Type name here..."
                        class="form-control input-lg"
                        type="text"
                        ng-model="texts.itemName"/>

                <button id="green_btn" class="btn btn-lg btn-success" ng-click="addItem()">Add new</button>

            </form>

                            {{item.name}}

                            {{item.comments.length}}

                            <button id="red_btn"
                                    class="btn btn-lg btn-default"
                                    ng-click="delItem($index)">Delete
                            </button>

Comments for {{getActiveItem().name}}

Comment:

{{comment.post}}

                            <input type="color"
                                   class="color-input"
                                   ng-model="texts.color"/>

                      <textarea ng-keypress="addComment($event)"
                                ng-model="texts.commentName"
                                class="form-control"
                                rows="5"
                                id="comment">
                      </textarea>


text:
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

require(__DIR__.'/../../config.php');
$json = required_param('tlelinks', PARAM_RAW);

require_login();

$decodedinfo = json_decode($json);
$info = array_pop($decodedinfo);

$url = '';
if (isset($info->url)) {
    $url = s(clean_param($info->url, PARAM_URL));
}

$filename = '';
// Use $info->filename if exists, $info->name is a display name,
// it may not have extension
if (isset($info->filename)) {
    $filename  = s(clean_param($info->filename, PARAM_FILE));
} else if (isset($info->name)) {
    $filename  = s(clean_param($info->name, PARAM_FILE));
}

$thumbnail = '';
if (isset($info->thumbnail)) {
    $thumbnail = s(clean_param($info->thumbnail, PARAM_URL));
}

$author = '';
if (isset($info->owner)) {
    $author = s(clean_param($info->owner, PARAM_NOTAGS));
}

$license = '';
if (isset($info->license)) {
    $license = s(clean_param($info->license, PARAM_ALPHAEXT));
}

$source = base64_encode(json_encode(array('url'=>$url,'filename'=>$filename)));

$js =<<<EOD

   <meta http-equiv="content-type" content="text/html; charset=utf-8" />

EOD;

header('Content-Type: text/html; charset=utf-8');
die($js);


text:
class PostController < ApplicationController
  def index
    @cyber = "Leonardo"
  end
end


text: README: drives


text:
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Reservation extends Model
{
    protected $fillable = ['email', 'name', 'forename', 'arrive_at', 'leave_at', 'nb_people', 'is_valid'];

    /**
     * The attributes that should be casted to native types.
     *
     * @var array
     */
    protected $casts = [
        'is_valid' => 'boolean',
        'nb_people' => 'integer',
        'id' => 'integer',
    ];

    /**
     * @param $query
     * @return mixed
     */
    public function scopePublished($query)
    {
        return $query->where('is_valid', true);
    }
}


text:
<TITLE>Review for Postino, Il (1994)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Postino, Il (1994)

reviewed by
Steve Rhodes

                          THE POSTMAN (IL POSTINO)
                       A film review by Steve Rhodes
                        Copyright 1996 Steve Rhodes

RATING (0 TO ****):  ** 1/2

     Just as Gene Siskel recently admitted that he walked out of BLACK
SHEEP, let me confess that I went to see THE POSTMAN (IL POSTINO) as
soon as it was released last year, but walked out bored stiff after
twenty minutes, and so I never wrote a review of it.  Since it got two
major Oscar nominations, Best Picture and Best Actor (Massimo Troisi),
I decided to go back and see it all no matter how unpromising it seemed
in the beginning.  In short, I am glad I did, but I do not think the
film is Oscar caliber.  I found THE POSTMAN to be an extremely slow,
but heart warming little picture.

     On a small and poor Italian island in 1953, a famous Chilean poet,
Pablo Neruda (Philippe Noiret), comes to live in exile.  Since he is an
avowed Communist, he is shunned by his government, but since he is
known as "the Poet of Love", he is adored by all the women of the
world.  That he is plain looking, in his 50s and balding is of no
concern to them; they are hot for him because of his poetry.

     Massimo Troisi plays a simpleton, a la Forest Gump, called Mario
Ruoppolo.  Mario applies to be the postman to part of the island.  It
turns out that in that area everyone is illiterate except for the newly
arrived poet and hence the poet is the only one that ever gets mail.
Being a mailman to a single person is more work that it might seem
since woman all over the planet write to the Poet of Love.

     Pablo becomes a mentor to Mario who decides he wants to be a poet
too.  Mario wants to know all of his secrets since he is in awe of him.
Pablo tries to convince Mario that poets are quite human and tells him,
"We poets are all fat."  In a touching series of scenes, Pablo attempts
to teach metaphors to Mario, but Mario is sure that the concept is too
difficult.  When he accidentally creates his first metaphor, Mario
claims it does not count since it was not intentional.

     Once reason Mario wants to be a poet is to attract women.  Being
painfully shy, he needs all the help he can get.  When he goes into a
bar, he sees a stunning beautiful woman, Beatrice Russo (Maria Grazia
Cucinotta), in a low cut dress playing a table game with soccer players
on sticks.  He plays it with her without speaking, but loses since he
spends most of the time staring at her.

     An old Dictaphone type of instrument plays a key part in the show.
Pablo warns Mario about it saying, "Even the most sublime ideas sound
ridiculous if heard too often."

     With Pablo's help, soon Mario is spouting poetry left and right.
He woes Beatrice with lines including, "your laugh is a sudden silvery
spoon," and "your smile spreads like a butterfly."  With his new
confidence, Mario becomes involved in the Communist party, but he
wonders what would happen if they ever actually won.  "So what if we
break our chains?  What do we do then?"

     I did not buy the ending of the show.  Although the conclusion did
not detract from the overall effect of the picture, I found it too
manipulative.

     I have no idea why this film was nominated for best picture of the
year for 1995.  There were so many that were better, PERSUASION and TOY
STORY just to name two much better ones.  And as for Massimo Troisi
getting the best actor nomination, I am even more surprised.  His
acting consisted of mumbling his lines while keeping the exact same
sick dog expression on his face throughout the entire film.  An
effective, but monochromatic performance and certainly not worth award
consideration.

     The sets by Lorenzo Baraldi and the cinematography by Franco
DiGiacomo create a wonderful atmosphere of a dirt poor but highly
picturesque out of the way island.  The town is lush shades of rose and
salmon and most of the houses have highly texture stucco walls with
pealing paint.  The simple costumes by Gianna Gissi add to the feeling
of prevailing but beautiful poverty.  The natural grandeur of the sheer
rocky cliffs overlooking the blue ocean seem a natural setting for
poetry.  Finally, my favorite part of the film is the music by Luis
Enriquez Bacalov.  It is dreamy music full of overtones of a simpler
time and place.

     THE POSTMAN runs a slow 1:56.  The editor (Roberto Perpignani) and
the director (Michael Radford) create a film with long scenes that are
only sparsely filled with dialog.  I suggest bulking up on coffee as I
did, or the film's soporific pacing may put you to sleep.  This is a
sweet little life affirming movie, but it moves at a glacial speed.
When there are words, they are in Italian subtitled in English.  The
film is rated PG for no reason whatsoever.  There is no sex, nudity,
violence, bad words, or anything to offend anyone of any age.  A two
year old could see this film.  I give the movie a thumbs up and award
it ** 1/2.

**** = One of the top few films of this or any year.  A must see film.
***  = Excellent show.  Look for it.
**   = Average movie.  Kind of enjoyable.
*    = Poor show.  Don't waste your money.
0    = One of the worst films of this or any year.  Totally unbearable.

REVIEW WRITTEN ON: February 21, 1996

Opinions expressed are mine and not meant to reflect my employer's.

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
package io.prometheus.client.spring.boot;

import java.util.Collection;
import org.springframework.boot.actuate.endpoint.PublicMetrics;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
class PrometheusMetricsConfiguration {

  @Bean
  public SpringBootMetricsCollector springBootMetricsCollector(Collection<PublicMetrics> publicMetrics) {
    SpringBootMetricsCollector springBootMetricsCollector = new SpringBootMetricsCollector(publicMetrics);
    springBootMetricsCollector.register();
    return springBootMetricsCollector;
  }
}


text:
define(['jquery','race','jqueryui','bootstrap'], function($, Race){

	var rider_category_locked = false;

	$('#tab-special').bind('tabshown', function(){
		// hide the data entry form
		$('#result_data_entry, #result_data_submit').hide();
	}).bind('tabhidden', function(){
		$('#result_data_entry, #result_data_submit').show();
	});

	$('#add_data_row').click(function(){
		// clone the default
		var new_data_entry = $('#result_data_entry_row').clone(true, true);
		$(new_data_entry).attr('id', null);

		var b = $('<a />')
				.addClass('result_data_new')
				.addClass('btn')
				.addClass('btn-small')
				.html('<i class="icon-minus"></i>')
				.click(function(){
					$(this).parents('.result_data_entry').remove();
				});
		// reset the fields
		$('.result_data_field', new_data_entry).val('');
		$('.result_note_field', new_data_entry).val('');
		$('.actions', new_data_entry).html('').append(b);

		$('#result_data_entries').prepend(new_data_entry);

	});

	// $('#rider_id').prop('disabled',true);

	$('#rider_category_lock').click(function(){
		var locked = $(this).find('.ui-icon').hasClass('ui-icon-locked');
		if(locked){
			rider_category_locked = false;
			$(this).find('.ui-icon').addClass('ui-icon-unlocked').removeClass('ui-icon-locked');
		}
		else {
			rider_category_locked = true;
			$(this).find('.ui-icon').removeClass('ui-icon-unlocked').addClass('ui-icon-locked');
		}
	});

	//$('#result_scope_switch').toggle(
	$('#tab-global').click(function(){
		$('#result_scope_global').val(1);
	});

	$('#tab-single').click(function(){
		$('#result_scope_global').val(0);
	});

	//hijack the results add form

	var formlocked = false;

	$('#form_result_add').bind('submit', function(event){
		event.preventDefault();
		if(formlocked) {
			alert('Please wait until the results are finished posting');
			return false;
		}

		// check if there are valid data inputs
		var pass = false;

		$('.result_data_field').each(function(){
			if($(this).val() != '') pass = true;
		});
		if(pass == false){
			$('#form_error').show().addClass('alert-warning').find('.alert-content').html('Please enter data before submitting');
			return false;
		}

		$.ajax({
				type: 'POST',
				url: $(this).attr('action'),
				data: $(this).serialize(),
				beforeSend: function(){
					lockForm();
				},
				success: function(data){
					unlockForm();
					//console.log(data);
					if(data.error){
						// plant the error
						$('#form_error').show().addClass('alert-warning').find('.alert-content').html(data.error);
					}
					else {
						// clear the rider name
						$('#rider_name').val('').focus();
						$('#rider_id').val('');
						$('.result_data_field').val('');
						$('.result_note').val('');
						$('#form_error').show().removeClass('alert-warning').find('.alert-content').html("Saved result for " + data.rider_name);

						// refresh the results table
						$('#race_results_block').load('../../result/race/' + race_id);
					}
				}
		});
	});

	function lockForm(){
		formlocked = true;
		$('#submit_result_loading').show();
	}

	function unlockForm(){
		formlocked = false;
		$('#submit_result_loading').hide();
	}

	$('.result_delete').live('click', function(event){
		event.preventDefault();
		href = $(this).attr('href');
		$.getJSON(href, function(){
			$('#race_results_block').load('../../result/race/' + race_id);
		});
		return false;
	});

	$('#rider_name').autocomplete({
		source:"../../../rider/search/",
		minLength: 2,
		select: function(event, ui){
			event.preventDefault();
			// console.log(ui.item);
			$('#rider_name').val(ui.item.label);
			$('#rider_id').val(ui.item.value);

			// auto focus on the first data item
			$('.result_data_field').eq(0).focus();

			if(rider_category_locked == false){
				$('#rider_category_id').val(ui.item.rider_category_id);
			}
		},
		autoFocus: true
	});

	$('#create_placings').click(function(e){
		e.preventDefault();

		href = $(this).attr('href');
		$.getJSON(href, function(){
			$('#race_results_block').load('../../result/race/' + race_id);
		});

		return false;
	});

	var editModal = $('#result_edit_modal').modal({show: false});

	$('.result_edit').live('click', function(event){
		event.preventDefault();
		href = $(this).attr('href');
		// open a modal window
		$('#result_edit_modal .modal-body').load(href, function(){
			console.log('loaded', href);
			// $('#result_edit').dialog('open');
			$('#result_edit_modal').modal('show');
		});
	});

	// $('#result_edit').dialog({
	// 		autoOpen: false,
	// 		height: 480,
	// 		width: 640,
	// 		modal: true,
	// 		buttons: {
	$('#result_edit_modal').on('hidden', function(){
		// find the form inside here
		$.ajax({type:'POST',
				url: $('#result_edit_modal form').attr('action'),
				data: $('#result_edit_modal form').serialize(),
				success: function(response){
					console.log('sent form', response);
					// $('#result_edit_modal').dialog( "close" );
					// force reload of the results
					$('#race_results_block').load('../../result/race/' + race_id);
				}
			});
	});

	$('a[data-toggle="tab"]').on('shown', function (e) {
	  $(e.target).trigger('tabshown'); // activated tab
	  $(e.relatedTarget).trigger('tabhidden'); // previous tab
	});

});


text:
{% extends "barcamp/sponsor-add.html" %}
{% block button-label %}{% trans "Save" %}{% endblock %}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- this is an XML fragment, not valid XML by itself. -->
<module name="JavadocPackage"/>
<module name="Translation"/>
<property name="basedir" value="${checkstyle.basedir}" />


text:
<Alloy>
	<View id="schedule" layout="vertical">
		<Label id ="schedule_switch" onClick="schedule_switch" height="Ti.UI.SIZE">Visualizza sale</Label>
		<View id="schedule_container"></View>
	</View>
</Alloy>


text:
class CameraFlightProcess : public Process, public EventListener
{
private:

	std::shared_ptr<Camera> camera;
	glm::vec4 tVector;
	glm::mat4 bezierMatrix;
	glm::mat4 pointMatrix;
	glm::mat4 targetPointMatrix;

	std::chrono::time_point<std::chrono::high_resolution_clock> startTime;
	std::chrono::time_point<std::chrono::high_resolution_clock> endTime;

	bool isPaused;
	float oldT;

public:
	explicit CameraFlightProcess(unsigned long ms);
	~CameraFlightProcess(void){};

	virtual void init(void);
	virtual void update(unsigned long deltaMs);

	void handleEvent(const std::shared_ptr<Event>& event_);
};


text:
package de.itagile.despot.http;

import de.itagile.despot.ResponseModifier;
import de.itagile.model.Model;

import javax.ws.rs.core.CacheControl;
import javax.ws.rs.core.Response;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class MaxAgeModifier implements ResponseModifier {

    private static final String KEY = "max-age";
    private final long duration;
    private final TimeUnit timeUnit;

    private MaxAgeModifier(long duration, TimeUnit timeUnit) {
        this.duration = duration;
        this.timeUnit = timeUnit;
    }

    public static MaxAgeModifier maxAge(int duration, TimeUnit timeUnit) {
        return new MaxAgeModifier(duration, timeUnit);
    }

    private CacheControl cacheHeader(long duration, TimeUnit timeUnit) {
        final CacheControl cc = new CacheControl();
        final Long l = timeUnit.toSeconds(duration);
        cc.setMaxAge(l.intValue());
        return cc;
    }

    @Override
    public void modify(Response.ResponseBuilder responseBuilder, Model model) {
        responseBuilder.cacheControl(cacheHeader(duration, timeUnit));
    }

    @Override
    public void spec(Map<String, Object> spec) {
        Map<String, Object> map = new HashMap<>();
        map.put("duration", "" + duration);
        map.put("time-unit", timeUnit.name());
        spec.put(KEY, map);
    }

    @Override
    public String toString() {
        return "Max-Age = " + duration + " seconds";
    }
}


text:
package POE::Driver::SysRW;

use strict;

use vars qw($VERSION);
$VERSION = do {my($r)=(q$Revision: 2335 $=~/(\d+)/);sprintf"1.%04d",$r};

use Errno qw(EAGAIN EWOULDBLOCK);
use Carp qw(croak);

sub OUTPUT_QUEUE        () { 0 }
sub CURRENT_OCTETS_DONE () { 1 }
sub CURRENT_OCTETS_LEFT () { 2 }
sub BLOCK_SIZE          () { 3 }
sub TOTAL_OCTETS_LEFT   () { 4 }

#------------------------------------------------------------------------------

sub new {
  my $type = shift;
  my $self = bless [
    [ ],   # OUTPUT_QUEUE
    0,     # CURRENT_OCTETS_DONE
    0,     # CURRENT_OCTETS_LEFT
    65536, # BLOCK_SIZE
    0,     # TOTAL_OCTETS_LEFT
  ], $type;

  if (@_) {
    if (@_ % 2) {
      croak "$type requires an even number of parameters, if any";
    }
    my %args = @_;
    if (defined $args{BlockSize}) {
      $self->[BLOCK_SIZE] = delete $args{BlockSize};
      croak "$type BlockSize must be greater than 0"
        if ($self->[BLOCK_SIZE] <= 0);
    }
    if (keys %args) {
      my @bad_args = sort keys %args;
      croak "$type has unknown parameter(s): @bad_args";
    }
  }

  $self;
}

#------------------------------------------------------------------------------

sub put {
  my ($self, $chunks) = @_;
  my $old_queue_octets = $self->[TOTAL_OCTETS_LEFT];

  # Need to check lengths in octets, not characters.
  BEGIN { eval { require bytes } and bytes->import; }

  foreach (grep { length } @$chunks) {
    $self->[TOTAL_OCTETS_LEFT] += length;
    push @{$self->[OUTPUT_QUEUE]}, $_;
  }

  if ($self->[TOTAL_OCTETS_LEFT] && (!$old_queue_octets)) {
    $self->[CURRENT_OCTETS_LEFT] = length($self->[OUTPUT_QUEUE]->[0]);
    $self->[CURRENT_OCTETS_DONE] = 0;
  }

  $self->[TOTAL_OCTETS_LEFT];
}

#------------------------------------------------------------------------------

sub get {
  my ($self, $handle) = @_;

  my $result = sysread($handle, my $buffer = '', $self->[BLOCK_SIZE]);

  # sysread() returned a positive number of octets.  Return whatever
  # was read.
  return [ $buffer ] if $result;

  # 18:01 <dngor> sysread() clears $! when it returns 0 for eof?
  # 18:01 <merlyn> nobody clears $!
  # 18:01 <merlyn> returning 0 is not an error
  # 18:01 <merlyn> returning -1 is an error, and sets $!
  # 18:01 <merlyn> eof is not an error. :)

  # 18:21 <dngor> perl -wle '$!=1; warn "\$!=",$!+0; \
  #               warn "sysread=",sysread(STDIN,my $x="",100); \
  #               die "\$!=",$!+0' < /dev/null
  # 18:23 <lathos> $!=1 at foo line 1.
  # 18:23 <lathos> sysread=0 at foo line 1.
  # 18:23 <lathos> $!=0 at foo line 1.
  # 18:23 <lathos> 5.6.0 on Darwin.
  # 18:23 <dngor> Same, 5.6.1 on fbsd 4.4-stable.
  #               read(2) must be clearing errno or something.

  # sysread() returned 0, signifying EOF.  Although $! is magically
  # set to 0 on EOF, it may not be portable to rely on this.
  if (defined $result) {
    $! = 0;
    return undef;
  }

  # Nonfatal sysread() error.  Return an empty list.
  return [ ] if $! == EAGAIN or $! == EWOULDBLOCK;

  # In perl 5.005_04 on FreeBSD, $! is not set properly unless this
  # silly no-op is executed.  Turn off warnings in case $result isn't
  # defined.  TODO - Make it optimizable at compile time.
  local $^W = 0;
  $result = "$result";

  # fatal sysread error
  undef;
}

#------------------------------------------------------------------------------

sub flush {
  my ($self, $handle) = @_;

  # Need to check lengths in octets, not characters.
  BEGIN { eval { require bytes } and bytes->import; }

  # syswrite() it, like we're supposed to
  while (@{$self->[OUTPUT_QUEUE]}) {
    my $wrote_count = syswrite(
      $handle,
      $self->[OUTPUT_QUEUE]->[0],
      $self->[CURRENT_OCTETS_LEFT],
      $self->[CURRENT_OCTETS_DONE],
    );

    # Errors only count if syswrite() failed.
    $! = 0 if defined $wrote_count;

    unless ($wrote_count) {
      $! = 0 if $! == EAGAIN or $! == EWOULDBLOCK;
      last;
    }

    $self->[CURRENT_OCTETS_DONE] += $wrote_count;
    $self->[TOTAL_OCTETS_LEFT] -= $wrote_count;
    unless ($self->[CURRENT_OCTETS_LEFT] -= $wrote_count) {
      shift(@{$self->[OUTPUT_QUEUE]});
      if (@{$self->[OUTPUT_QUEUE]}) {
        $self->[CURRENT_OCTETS_DONE] = 0;
        $self->[CURRENT_OCTETS_LEFT] = length($self->[OUTPUT_QUEUE]->[0]);
      }
      else {
        $self->[CURRENT_OCTETS_DONE] = $self->[CURRENT_OCTETS_LEFT] = 0;
      }
    }
  }

  $self->[TOTAL_OCTETS_LEFT];
}

#------------------------------------------------------------------------------

sub get_out_messages_buffered {
  scalar(@{$_[0]->[OUTPUT_QUEUE]});
}

1;

__END__

=head1 NAME

POE::Driver::SysRW - buffered, non-blocking I/O using sysread and syswrite

=head1 SYNOPSIS

L<POE::Driver/SYNOPSIS> illustrates how the interface works.  This
module is merely one implementation.

=head1 DESCRIPTION

This driver implements L<POE::Driver> using sysread and syswrite.

=head1 PUBLIC METHODS

POE::Driver::SysRW introduces some additional features not covered in
the base interface.

=head2 new [BlockSize => OCTETS]

new() creates a new buffered I/O driver that uses sysread() to read
data from a handle and syswrite() to flush data to that handle.  The
constructer accepts one optional named parameter, C<BlockSize>, which
indicates the maximum number of OCTETS that will be read at one time.

C<BlockSize> is 64 kilobytes (65536 octets) by default.  Higher values
may improve performance in streaming applications, but the trade-off
is a lower event granularity and increased resident memory usage.

Lower C<BlockSize> values reduce memory consumption somewhat with
corresponding throughput penalties.

  my $driver = POE::Driver::SysRW->new;

  my $driver = POE::Driver::SysRW->new( BlockSize => $block_size );

Drivers are commonly instantiated within POE::Wheel constructor calls:

  $_[HEAP]{wheel} = POE::Wheel::ReadWrite->new(
    InputHandle => \*STDIN,
    OutputHandle => \*STDOUT,
    Driver => POE::Driver::SysRW->new(),
    Filter => POE::Filter::Line->new(),
  );

Applications almost always use POE::Driver::SysRW, so POE::Wheel
objects almost always will create their own if no Driver is specified.

=head2 All Other Methods

POE::Driver::SysRW documents the abstract interface documented in
POE::Driver.  Please see L<POE::Driver> for more details about the
following methods:

=over 4

=item flush

=item get

=item get_out_messages_buffered

=item put

=back

=head1 SEE ALSO

L<POE::Driver>, L<POE::Wheel>.

Also see the SEE ALSO section of L<POE>, which contains a brief
roadmap of POE's documentation.

=head1 AUTHORS & COPYRIGHTS

Please see L<POE> for more information about authors and contributors.

=cut

# rocco // vim: ts=2 sw=2 expandtab


text:
package io.github.jokoframework.porandu.service;

import io.github.jokoframework.porandu.web.dto.response.LectureResponseDTO;

import java.util.List;

/**
 * Created by afeltes on 25/07/16.
 */
public interface LecturesService {
    List<LectureResponseDTO> findByEventId(Long pEventId);
}


text:
struct ANativeWindow;
struct AInputEvent;

IMGUI_IMPL_API bool     ImGui_ImplAndroid_Init(ANativeWindow* window);
IMGUI_IMPL_API int32_t  ImGui_ImplAndroid_HandleInputEvent(AInputEvent* input_event);
IMGUI_IMPL_API void     ImGui_ImplAndroid_Shutdown();
IMGUI_IMPL_API void     ImGui_ImplAndroid_NewFrame();


text:
title: SMACK stack 101, Building Fast Data stacks
date: 2017-12-12
speaker: Jörg Schad, Mesosphere
speakerurl: https://twitter.com/joerg_schad
eventimage: Las_Vegas.jpg
eventlocation: Las Vegas, USA
eventname: USENIX Middleware 2017
category: SMACK
description: In this workshop, the participants will build their own microservice application and connect it to a Fast Data Pipeline consisting of Apache Spark, Cassandra, and Kafka.
layout: event.jade
collection: events
lunr: true
---

# Abstract

In this workshop, the participants will build their own microservice application and connect it to a Fast Data Pipeline consisting of Apache Spark, Cassandra, and Kafka. This pipeline will then deployed on top of DC/OS. We will also look into the operational aspects of updating, scaling, and monitoring such data pipelines.

What to expect:
* Best practices for setting up Fast Data Pipelines
* The different components of the SMACK stack and respective alternatives
* How to deploy such stack in an efficient and fault-tolerant way
* How to keep such stacks running:
* Monitoring
* Upgrades
* Debugging

# Slides

<iframe src="https://docs.google.com/presentation/d/1PS3J5mmGfYApAuEgKQP4L2hNuXGbUHf2HxCNMuiYepc/embed?start=false&loop=false&delayms=3000" frameborder="0" width="640" height="389" allowfullscreen="true" mozallowfullscreen="true" webkitallowfullscreen="true"></iframe>


text:
#ifndef __PYNTROSPECTION_META_METHOD_DISPATCHER_H_
#define __PYNTROSPECTION_META_METHOD_DISPATCHER_H_

#include "ReflectObject.hpp"

template<typename NameList>
struct MetaMethodDispatcher;

/* Head type expected to be MetaMethodTypedef
 */
template<typename Head, typename Tail>
struct MetaMethodDispatcher<Lst<Head, Tail>> {
public:

	template<typename Ret = void, typename... Args>
	static std::enable_if_t<Eq<Ret, typename Head::MethodReturn>::value && Eq<PPack<Args...>, typename Head::MethodArgs>::value, Ret>
		call(const char *name, void* ptr, Args... args) {
		typedef typename Head::Klass T;

		if (strcmp(name, Head::Name) == 0) {
			T* Tptr = static_cast<T*>(ptr);
			return Head::call(Tptr, std::forward<Args>(args)...);
		}
		else {
			return MetaMethodDispatcher<Tail>::call<Ret>(name, ptr, args...);
		}
	}

	template<typename Ret = void, typename... Args>
	static std::enable_if_t<!Eq<Ret, typename Head::MethodReturn>::value || !Eq<PPack<Args...>, typename Head::MethodArgs>::value, Ret>
		call(const char *name, void* ptr, Args... args) {
		typedef typename Head::Klass T;

		if (strcmp(name, Head::Name) == 0) {
			throw new std::exception("arguments mismatch with the method found");
		}
		else {
			return MetaMethodDispatcher<Tail>::call<Ret>(name, ptr, args...);
		}
	}
};

template<typename Head>
struct MetaMethodDispatcher<Lst<Head, Nil>> {
	template<typename Ret = void, typename... Args>
	static std::enable_if_t<Eq<Ret, typename Head::MethodReturn>::value && Eq<PPack<Args...>, typename Head::MethodArgs>::value, Ret>
		call(const char *name, void* ptr, Args... args) {
		typedef typename Head::Klass T;

		if (strcmp(name, Head::Name) == 0) {
			T* Tptr = static_cast<T*>(ptr);
			return Head::call(Tptr, std::forward<Args>(args)...);
		}
		else {
			throw new std::exception("No method found for the given name");
		}
	}

	template<typename Ret = void, typename... Args>
	static std::enable_if_t<!Eq<Ret, typename Head::MethodReturn>::value || !Eq<PPack<Args...>, typename Head::MethodArgs>::value, Ret>
		call(const char *name, void* ptr, Args... args) {
		typedef typename Head::Klass T;

		throw new std::exception("No method found for the given name and arguments");
	}
};

#endif


text:
module Coppertone
  class Modifier
    # Base class including logic common to modifiers
    class Base < Modifier
      attr_reader :domain_spec

      def initialize(attributes)
        super(attributes)
        raise InvalidModifierError if attributes.blank?

        @domain_spec = Coppertone::DomainSpec.new(attributes)
      rescue Coppertone::MacroStringParsingError
        raise Coppertone::InvalidModifierError
      end

      def target_name_from_domain_spec(macro_context, request_context)
        if domain_spec
          domain =
            domain_spec.expand(macro_context, request_context)
        end
        Coppertone::Utils::DomainUtils.macro_expanded_domain(domain)
      end

      def context_dependent?
        domain_spec.context_dependent?
      end

      def includes_ptr?
        domain_spec.includes_ptr?
      end

      def ==(other)
        return false unless other.instance_of? self.class

        domain_spec == other.domain_spec
      end
    end
  end
end


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [("order", "0015_auto_20170206_0407")]

    operations = [
        migrations.AddField(
            model_name="order",
            name="language_code",
            field=models.CharField(default="en-us", max_length=35),
        )
    ]


text:
@class PHFetchResult;
@class PHAssetCollection;
@class PHObjectPlaceholder;

NS_ASSUME_NONNULL_BEGIN

// PHAssetCollectionChangeRequest can only be created or used within a -[PHPhotoLibrary performChanges:] or -[PHPhotoLibrary performChangesAndWait:] block.
@interface PHAssetCollectionChangeRequest : NSObject

#pragma mark - Creating Asset Collections

+ (instancetype)creationRequestForAssetCollectionWithTitle:(NSString *)title;

// This can be used to fetch the newly created asset collection after the change block has completed by using -localIdentifier
// It can also be added directly to collection lists within the current change block
@property (nonatomic, strong, readonly) PHObjectPlaceholder *placeholderForCreatedAssetCollection;

#pragma mark - Deleting Asset Collections

// requests that the specified asset collections be deleted
+ (void)deleteAssetCollections:(id<NSFastEnumeration>)assetCollections;

#pragma mark - Modifying Asset Collections

// if the asset collection does not allow the type of change requested, these methods will raise an exception, call canPerformEditOperation: on the asset collection to determine if the type of edit operation is allowed.
+ (nullable instancetype)changeRequestForAssetCollection:(PHAssetCollection *)assetCollection;

// to add, remove or rearrange assets in a collection, passing in the fetched assets in that collection will ensure that the asset positions are tracked correctly in the case that the collection has been externally edited after the fetch, but before this change is applied
+ (nullable instancetype)changeRequestForAssetCollection:(PHAssetCollection *)assetCollection assets:(PHFetchResult *)assets;

@property (nonatomic, strong, readwrite) NSString *title;

- (void)addAssets:(id<NSFastEnumeration>)assets;
- (void)insertAssets:(id<NSFastEnumeration>)assets atIndexes:(NSIndexSet *)indexes;
- (void)removeAssets:(id<NSFastEnumeration>)assets;
- (void)removeAssetsAtIndexes:(NSIndexSet *)indexes;
- (void)replaceAssetsAtIndexes:(NSIndexSet *)indexes withAssets:(id<NSFastEnumeration>)assets;

// The move removes the assets at fromIndexes first then inserts those assets at the toIndex, so toIndex should point to a location based on the updated indexes after having removed the assets at fromIndexes
- (void)moveAssetsAtIndexes:(NSIndexSet *)fromIndexes toIndex:(NSUInteger)toIndex;

@end

NS_ASSUME_NONNULL_END


text:
<!DOCTYPE html>
<html>
  <link rel="stylesheet" href="styles.css">
  <title>HTML5 Audio </title>
  <audio controls src="johann_sebastian_bach_air.ogg">
    An audio clip from Johann Sebastian Bach.
  </audio>
</html>


text:
package parquet.avro;

import java.util.ArrayList;
import java.util.List;
import org.apache.avro.Schema;
import parquet.schema.GroupType;
import parquet.schema.MessageType;
import parquet.schema.OriginalType;
import parquet.schema.PrimitiveType;
import parquet.schema.Type;

import static parquet.schema.OriginalType.*;
import static parquet.schema.PrimitiveType.PrimitiveTypeName.*;

/**
 * <p>
 * Converts an Avro schema into a Parquet schema. See package documentation for details
 * of the mapping.
 * </p>
 */
class AvroSchemaConverter {

  public MessageType convert(Schema avroSchema) {
    if (!avroSchema.getType().equals(Schema.Type.RECORD)) {
      throw new IllegalArgumentException("Avro schema must be a record.");
    }
    return new MessageType(avroSchema.getFullName(), convertFields(avroSchema.getFields()));
  }

  private List<Type> convertFields(List<Schema.Field> fields) {
    List<Type> types = new ArrayList<Type>();
    for (Schema.Field field : fields) {
      if (field.schema().getType().equals(Schema.Type.NULL)) {
        continue; // Avro nulls are not encoded, unless they are null unions
      }
      types.add(convertField(field));
    }
    return types;
  }

  private Type convertField(String fieldName, Schema schema) {
    return convertField(fieldName, schema, Type.Repetition.REQUIRED);
  }

  private Type convertField(String fieldName, Schema schema, Type.Repetition repetition) {
    Schema.Type type = schema.getType();
    if (type.equals(Schema.Type.BOOLEAN)) {
      return primitive(fieldName, BOOLEAN, repetition);
    } else if (type.equals(Schema.Type.INT)) {
      return primitive(fieldName, INT32, repetition);
    } else if (type.equals(Schema.Type.LONG)) {
      return primitive(fieldName, INT64, repetition);
    } else if (type.equals(Schema.Type.FLOAT)) {
      return primitive(fieldName, FLOAT, repetition);
    } else if (type.equals(Schema.Type.DOUBLE)) {
      return primitive(fieldName, DOUBLE, repetition);
    } else if (type.equals(Schema.Type.BYTES)) {
      return primitive(fieldName, BINARY, repetition);
    } else if (type.equals(Schema.Type.STRING)) {
      return primitive(fieldName, BINARY, repetition, UTF8);
    } else if (type.equals(Schema.Type.RECORD)) {
      return new GroupType(repetition, fieldName, convertFields(schema.getFields()));
    } else if (type.equals(Schema.Type.ENUM)) {
      return primitive(fieldName, BINARY, repetition, ENUM);
    } else if (type.equals(Schema.Type.ARRAY)) {
      return new GroupType(repetition, fieldName, LIST,
          convertField("array", schema.getElementType(), Type.Repetition.REPEATED));
    } else if (type.equals(Schema.Type.MAP)) {
      Type keyType = convertField("key", Schema.create(Schema.Type.STRING));
      Type valType = convertField("value", schema.getValueType());
      return new GroupType(repetition, fieldName, MAP,
          new GroupType(Type.Repetition.REPEATED, "map", MAP_KEY_VALUE, keyType, valType));
    } else if (type.equals(Schema.Type.FIXED)) {
      return primitive(fieldName, FIXED_LEN_BYTE_ARRAY, repetition);
    } else if (type.equals(Schema.Type.UNION)) {
      List<Schema> schemas = schema.getTypes();
      if (schemas.size() == 2) {
        if (schemas.get(0).getType().equals(Schema.Type.NULL)) {
          return convertField(fieldName, schemas.get(1), Type.Repetition.OPTIONAL);
        } else if (schemas.get(1).getType().equals(Schema.Type.NULL)) {
          return convertField(fieldName, schemas.get(0), Type.Repetition.OPTIONAL);
        }
      }
      throw new UnsupportedOperationException("Cannot convert Avro type " + type);
    }
    throw new UnsupportedOperationException("Cannot convert Avro type " + type);
  }

  private Type convertField(Schema.Field field) {
    return convertField(field.name(), field.schema());
  }

  private Type primitive(String name, PrimitiveType.PrimitiveTypeName primitive,
      Type.Repetition repetition, OriginalType originalType) {
    return new PrimitiveType(repetition, primitive, name, originalType);
  }

  private PrimitiveType primitive(String name, PrimitiveType.PrimitiveTypeName
      primitive, Type.Repetition repetition) {
    return new PrimitiveType(repetition, primitive, name, null);
  }

}


text:
package kosen.talha.viagogo.com.viagogo.exception;

import org.json.JSONException;

/**
 * Created by tkosen on 07/03/2015.
 */
public class NoBorderException extends Exception {

    public NoBorderException(String s) {
        super(s);
    }

    public  String getMessage(){
        return  super.getMessage();
    }
}


text:
layout: refresh
refresh_to_post_id: /2016/05/15/integrity-as-important-as-profit
---


text:
<?php
namespace Dreamscapes;

// @codingStandardsIgnoreStart

// Prepare a test Enumeration
class TestEnum extends Enumeration
{
    const TestMember  = 0;
    const OtherMember = 1;
    const FalseMember = false;
    const TrueMember  = true;
}

class AnotherEnum extends Enumeration
{
    const DifferentMember = 'some value';
}

// @codingStandardsIgnoreEnd

class EnumerationTest extends \PHPUnit_Framework_TestCase
{
    public function testEnumerationsCannotBeInstantiated()
    {
        $refl  = new \ReflectionClass('Dreamscapes\TestEnum');

        $this->assertFalse($refl->getConstructor()->isPublic());
        $this->assertTrue($refl->getConstructor()->isFinal());
    }

    public function testEachEnumerationMustBeIsolated()
    {
        $this->assertSame('some value', AnotherEnum::getValue('DifferentMember'));
        $this->assertSame(1, TestEnum::getValue('OtherMember'));

        $this->setExpectedException('PHPUnit_Framework_Error');
        TestEnum::getValue('DifferentMember');
    }

    public function testAccessingUndefinedEnumerationMemberShouldTriggerError()
    {
        $this->setExpectedException('PHPUnit_Framework_Error');
        TestEnum::NonExistent();
    }

    public function testEnumerationCanTranslateValueToMemberName()
    {
        $this->assertEquals('TestMember', TestEnum::getName(0));
    }

    public function testWithValueMethod()
    {
        $this->assertEquals('TestMember', TestEnum::withValue(0));
    }

    public function testGetNameTriggersErrorOnUndefinedConstant()
    {
        $this->setExpectedException('PHPUnit_Framework_Error');
        TestEnum::getName('dummyValue');
    }

    public function testGetNameMethodIsTypeSensitive()
    {
        $this->assertSame('TestMember', TestEnum::getName(0));
        $this->assertSame('FalseMember', TestEnum::getName(false));
    }

    public function testEnumerationCanReturnMembersViaMethodCall()
    {
        $this->assertSame(1, TestEnum::getValue('OtherMember'));
        $this->assertSame(false, TestEnum::getValue('FalseMember'));
    }

    public function testNamedMethod()
    {
        $this->assertSame(1, TestEnum::named('OtherMember'));
        $this->assertSame(false, TestEnum::named('FalseMember'));
    }

    public function testMemberExistenceMethod()
    {
        $this->assertTrue(TestEnum::isDefined('TestMember'));
        $this->assertTrue(TestEnum::isDefined('FalseMember'));

        $this->assertFalse(TestEnum::isDefined('ImaginaryMember'));
    }

    public function testRetrievingAllMembersShouldReturnOrderedListOfMembers()
    {
        $expected = [
            'TestMember',
            'OtherMember',
            'FalseMember',
            'TrueMember',
        ];

        $this->assertSame($expected, TestEnum::allMembers());
    }

    public function testGetTypeReturnsOnlyClassName()
    {
        $this->assertSame('TestEnum', TestEnum::getType());
        $this->assertSame('AnotherEnum', AnotherEnum::getType());
    }

    public function testEnumerationMembersAreActuallyCallable()
    {
        $this->assertTrue(is_callable('TestEnum', 'TestMember'));
    }

    public function testCallingEnumerationMemberReturnsInstanceOfTheEnumeration()
    {
        $this->assertInstanceOf('Dreamscapes\TestEnum', TestEnum::TestMember());
    }

    public function testOnlySingleInstanceForEachEnumeratedMemberExists()
    {
        $first  = TestEnum::TestMember();
        $second = TestEnum::TestMember();

        $this->assertSame($first, $second);
    }

    public function testInstancesOfEnumerationMembersCanBeUsedAsStrings()
    {
        $this->assertEquals('TrueMember', (string)TestEnum::TrueMember());
        $this->assertEquals('FalseMember', (string)TestEnum::FalseMember());
        $this->assertEquals('TestMember', (string)TestEnum::TestMember());
    }

    public function testGetValueMethodAcceptsInstanceOfEnumeration()
    {
        $instance = TestEnum::TestMember();

        $this->assertSame(0, TestEnum::getValue($instance));
    }

    public function testIsDefinedMethodAcceptsInstanceOfEnumeration()
    {
        $instance = TestEnum::TestMember();
        $this->assertSame(true, TestEnum::isDefined($instance));

        // This should not pass because we are asking if an enum of one type is defined in another
        // enum
        $instance = AnotherEnum::DifferentMember();
        $this->assertSame(false, TestEnum::isDefined($instance));
    }

    public function testContainsMethod()
    {
        $this->assertTrue(TestEnum::contains('FalseMember'));
        $this->assertFalse(TestEnum::contains('ImaginaryMember'));
    }

    public function testHasMethod()
    {
        $this->assertTrue(TestEnum::has('FalseMember'));
        $this->assertFalse(TestEnum::has('ImaginaryMember'));
    }

    public function testDefinesMethod()
    {
        $this->assertTrue(TestEnum::defines('FalseMember'));
        $this->assertFalse(TestEnum::defines('ImaginaryMember'));
    }

    public function testInstancesHaveValueMethod()
    {
        $instance = TestEnum::TestMember();
        $this->assertSame(TestEnum::TestMember, $instance->value());
    }
}


text:
package net.runelite.client.util;

import java.util.concurrent.Callable;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RequiredArgsConstructor
public class CallableExceptionLogger<V> implements Callable<V>
{
	private final Callable<V> callable;

	@Override
	public V call() throws Exception
	{
		try
		{
			return callable.call();
		}
		catch (Throwable ex)
		{
			log.error("Uncaught exception in callable {}", callable, ex);
			throw ex;
		}
	}

	public static <V> CallableExceptionLogger<V> wrap(Callable<V> callable)
	{
		return new CallableExceptionLogger<>(callable);
	}
}


text:
Homelab-Dashboard
===================
A self hosted site to quickly monitor services and access web-gui applications.

###Screenshots
---------------
Desktop Browser
![alt tag](http://i.imgur.com/KBdmuL5.png)

Mobile Browser
![alt tag](http://i.imgur.com/1xrwKh8.png)

![alt tag](http://i.imgur.com/NB3aVfC.png)


text:
package net.lipecki.watson.receipt;

import lombok.Builder;
import lombok.Data;

@SuppressWarnings("WeakerAccess")
@Data
@Builder
public class AddReceiptItemProduct {

    private String uuid;
    private String categoryUuid;
    private String producerUuid;

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        style="@style/Register_Input"
        android:layout_height="80dp" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="center_vertical"
            android:paddingLeft="10dp"
            android:text="用药详情:"
            android:textStyle="bold"
            android:textSize="18sp"
            android:textColor="@color/base_color_text_black" />
        <EditText
            android:id="@+id/et_medicine"
            style="@style/Register_Edit"
            android:hint="(可不填)" />

    </LinearLayout>

    <LinearLayout style="@style/Register_Input" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="center_vertical"
            android:paddingLeft="10dp"
            android:text="提醒时间:"
            android:textStyle="bold"
            android:textSize="18sp"
            android:textColor="@color/base_color_text_black" />

        <EditText
            android:id="@+id/et_time_remind"
            style="@style/Register_Edit" />

        <Button
            android:id="@+id/button_timePicker"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="@android:attr/buttonStyleToggle"
            android:text="选择"
            android:background="@color/green"
            android:textColor="#FFFFFF" />

    </LinearLayout>

    <Button
        android:id="@+id/button_save"
        android:layout_width="250dp"
        android:layout_height="50dp"
        android:layout_marginTop="50dp"
        android:layout_gravity="center_horizontal"
        android:background="@color/green"
        android:text="保存"
        android:textColor="#FFFFFF" />
</LinearLayout>


text:
<?php

use yii\helpers\Html;
use yii\grid\GridView;

/* @var $this yii\web\View */
/* @var $searchModel app\models\CategoriesSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = 'Categories';
$this->params['breadcrumbs'][] = $this->title;
?>

<?= Html::encode($this->title) ?>

    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>

        <?= Html::a('Create Categories', ['create'], ['class' => 'btn btn-success']) ?>

    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            'id',
            'code',
            'name',
            'product_id',

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>


text:
import _ from 'lodash';

export function computeLimit (limit, paginate) {
  const lower = !_.isUndefined(limit) ? parseInt(limit) : paginate.default;
  const upper = _.isNumber(paginate.max) ? paginate.max : Number.MAX_VALUE;
  return Math.min(lower, upper);
}

export function convertQuery (feathersQuery) {
  const mangoQuery = {
    selector: {}
  };
  for (let queryField in feathersQuery) {
    switch (queryField) {
      case '$select':
        mangoQuery.fields = feathersQuery[queryField];
        break;

      case '$index':
        mangoQuery.use_index = feathersQuery[queryField];
        break;

      case '$sort':
        mangoQuery.sort = convertSort(feathersQuery[queryField]);
        break;

      case '$skip':
        mangoQuery.skip = parseInt(feathersQuery[queryField]);
        break;

      case '$limit':
        mangoQuery.limit = parseInt(feathersQuery[queryField]);
        break;

      default:
        mangoQuery.selector[queryField] = feathersQuery[queryField];
        break;
    }
  }
  return mangoQuery;
}

export function convertSort (feathersSort) {
  const mangoSort = [];
  for (let sortField in feathersSort) {
    if (feathersSort[sortField] < 0) {
      mangoSort.push({ [sortField]: 'desc' });
      continue;
    }
    if (feathersSort[sortField] > 0) {
      mangoSort.push({ [sortField]: 'asc' });
      continue;
    }
  }
  return mangoSort;
}

export function extractMetadata (pouchdbResponse) {
  const metadata = _.pick(pouchdbResponse, ['id', 'rev']);
  return _.mapKeys(metadata, (value, key) => `_${key}`);
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <declare-styleable name="watchface_style_attrs">
        <attr name="primary_color" format="color"/>
        <attr name="secondary_color" format="color"/>
        <attr name="background_color" format="color"/>
        <attr name="outer_element_color" format="color"/>
        <attr name="active" format="reference"/>
        <attr name="ambient" format="reference"/>
        <attr name="complication" format="reference" />
    </declare-styleable>

    <style name="ambient_style">
        <item name="primary_color">@color/white</item>
        <item name="secondary_color">@color/white_50</item>
        <item name="background_color">@color/black</item>
        <item name="outer_element_color">@color/white_30</item>
    </style>

    <!-- Red style -->
    <style name="red_style">
        <item name="active">@style/red_style_active</item>
        <item name="ambient">@style/red_style_ambient</item>
        <item name="complication">@drawable/complication_red_style</item>
    </style>

    <style name="red_style_active">
        <item name="primary_color">@color/white</item>
        <item name="secondary_color">@color/maroon</item>
        <item name="background_color">@color/dark_gray</item>
        <item name="outer_element_color">@color/maroon_50</item>
    </style>

    <style name="red_style_ambient" parent="ambient_style">
    </style>
    <!-- End of red style -->

    <!-- Green style -->
    <style name="green_style">
        <item name="active">@style/green_style_active</item>
        <item name="ambient">@style/green_style_ambient</item>
        <item name="complication">@drawable/complication_green_style</item>
    </style>

    <style name="green_style_active">
        <item name="primary_color">@color/light_green</item>
        <item name="secondary_color">@color/dark_green</item>
        <item name="background_color">@color/dark_gray</item>
        <item name="outer_element_color">@color/light_green</item>
    </style>

    <style name="green_style_ambient" parent="ambient_style">
    </style>
    <!-- End of green style -->

    <!-- Blue style -->
    <style name="blue_style">
        <item name="active">@style/blue_style_active</item>
        <item name="ambient">@style/blue_style_ambient</item>
        <item name="complication">@drawable/complication_blue_style</item>
    </style>

    <style name="blue_style_active">
        <item name="primary_color">@color/light_blue</item>
        <item name="secondary_color">@color/dark_blue</item>
        <item name="background_color">@color/dark_gray</item>
        <item name="outer_element_color">@color/light_blue</item>
    </style>

    <style name="blue_style_ambient" parent="ambient_style">
    </style>
    <!-- End of blue style -->

    <!-- White style -->
    <style name="white_style">
        <item name="active">@style/white_style_active</item>
        <item name="ambient">@style/white_style_ambient</item>
        <item name="complication">@drawable/complication_white_style</item>
    </style>

    <style name="white_style_active">
        <item name="primary_color">@color/white_70</item>
        <item name="secondary_color">@color/white_50</item>
        <item name="background_color">@color/white_10</item>
        <item name="outer_element_color">@color/white_70</item>
    </style>

    <style name="white_style_ambient" parent="ambient_style">
    </style>
    <!-- End of  green style -->

</resources>


text:
include(Platform/AIX-XL)
__aix_compiler_xl(Fortran)


text:
'use strict';

var cacheManager = require('cache-manager');
var memoryCache = cacheManager.caching({
    store: 'memory'
});

var handlers = module.exports = {};

handlers.index = function(req, res) {
    res.render('index');
};

handlers.cache = function(req, res) {
    memoryCache.wrap('cacheKEY', function(callback) {
            // send the data to the cache
            // error , data
            setTimeout(function() {
                callback(null, {
                    'list': ['user1', 'user2', 'user3']
                });
            }, 500);
        },
        // time to cache
        {
            ttl: 30
        },
        // when the data is ready from the cache
        function(err, data) {
            if (err) {
                err.status = 500;
                res.send(err);
            } else {
                res.send(data);
            }
        });
};


text:
<?xml version="1.0" encoding="UTF-8"?>
<CustomFieldTranslation xmlns="http://soap.sforce.com/2006/04/metadata">
    <name>Owned_by_Namespace__c</name>
    <help>El espacio de nombres del paquete u organización que controla este controlador de desencadenadores.</help>
    <label>Propiedad de Espacio de nombres</label>
</CustomFieldTranslation>


text:
'use strict';

module.exports = Precis;

function Precis(token) {
    var precis = this;

    var Window = require('./window');
    this.window = new Window();
    this.window.drawDefault();

    this.window.notify('Initializing api connection');
    var Api = require('./api');
    this.api = new Api(token);
    this.api.on('started', function(data) {
        precis.window.notify('HTTP connection successful');
        precis.setupChannels(data.channels);
    });
    this.api.on('connection acknowledged', function() {
        precis.window.notify('Websocket connection successful');
    });
    this.api.on('ready', function() {
        precis.window.notify('API ready');
    });
}

Precis.prototype.setupChannels = function setupChannels(channels) {
    this.channels = {
        all: channels
    };
    this.channels.starred = channels.filter(function(c) {
        return c.is_starred;
    }).sort(channelSorterByName);
    this.channels.joined = channels.filter(function(c) {
        return c.is_member && !c.is_starred;
    }).sort(channelSorterByName);
    this.channels.other = channels.filter(function(c) {
        return !(c.is_member || c.is_starred);
    }).sort(channelSorterByName);
    this.channels.starred.concat(this.channels.joined).concat(this.channels.other).forEach(function(c) {
        this.window.addChannel(c.name);
    }, this);
};

function channelSorterByName(a, b) {
    if (a.name > b.name) {
        return 1;
    } else if (a.name < b.name) {
        return -1;
    }
    return 0;
}


text:
void ttw_log(const int, const char*, ... );
void ttw_fatal(const char*);

void ttw_dispatch_request(int);
void ttw_destroy_request(s_ttw_http_request*);
void ttw_init_and_start();

#endif


text:
//
//  SpecialPropertyModel.h
//  OPTLYJSONModelDemo_OSX
//
//  Created by BB9z on 13-4-26.
//  Copyright (c) 2013年 Underplot ltd. All rights reserved.
//

@import OptimizelySDKCore;

@interface SpecialPropertyModel : OPTLYJSONModel

@property (strong, nonatomic) NSString *className;
@property (strong, nonatomic) NSString *indexPropertyName;
@property (strong, nonatomic) NSString *id;

@end


text:
/**
 * Defines the component for the database connection fail screen
 */
define([
  'text!./failure.html',
  'pentaho/i18n-osgi!repositories-plugin.messages',
  'css!./failure.css'
], function (template, i18n) {

  'use strict';

  var options = {
    bindings: {
      connection: "="
    },
    controllerAs: "vm",
    template: template,
    controller: failureController
  };

  failureController.$inject = ["$state"];

  /**
   * Controller for the database connection failure screen
   *
   * @param {Object} $state - object for controlling the app state
   */
  function failureController($state) {
    var vm = this;
    vm.change = change;
    vm.close = close;
    vm.manage = manage;

    /**
     * Redirect to the database connection details screen
     */
    function change() {
      vm.connection.modify = true;
      $state.go("database.details");
    }

    /**
     * Closes the repository manager
     */
    function close() {
      closeWindow();
    }

    /**
     * Redirect to the manager screen
     */
    function manage() {
      $state.go("manager");
    }
  }

  return {
    name: "database.failure",
    options: options
  };

});


text:
% FLIP_TREE   flips a tree around one axis.
% (trees package)
%
% tree = flip_tree (intree, DIM, options)
% ---------------------------------------
%
% flips tree around dimension DIM
%
% Input
% -----
% - intree::integer:index of tree in trees or structured tree
% - DIM::1, 2 or 3: dimension to be flipped {DEFAULT: 1, x-axis}
% - options::string: {DEFAULT: ''}
%     '-s' : show before and after
%
% Output
% -------
% if no output is declared the tree is changed in the trees structure
% - tree:: structured output tree
%
% Example
% -------
% flip_tree (sample_tree, [], '-s')
%
% See also tran_tree rot_tree scale_tree
% Uses ver_tree X Y Z
%
% the TREES toolbox: edit, visualize and analyze neuronal trees
% Copyright (C) 2009  Hermann Cuntz

function varargout = flip_tree (intree, DIM, options)

% trees : contains the tree structures in the trees package
global trees

if (nargin < 1)||isempty(intree),
    intree = length (trees); % {DEFAULT tree: last tree in trees cell array}
end;

ver_tree (intree); % verify that input is a tree structure

% use full tree for this function
if ~isstruct (intree),
    tree = trees {intree};
else
    tree = intree;
end

if (nargin < 2)||isempty(DIM),
    DIM = 1; % {DEFAULT: flip over x dimension}
end;

if (nargin < 3)||isempty(options),
    options = ''; % {DEFAULT: no option}
end

switch DIM
    case 1
        tree.X = 2 * tree.X (1) - tree.X;
    case 2
        tree.Y = 2 * tree.Y (1) - tree.Y;
    case 3
        tree.Z = 2 * tree.Z (1) - tree.Z;
    otherwise
        warning ('TREES:wronginputs','DIM not the right number');
end

if strfind (options, '-s') % show option
    clf; shine; hold on; plot_tree (intree); plot_tree (tree, [1 0 0]);
    HP(1) = plot (1, 1, 'k-'); HP(2) = plot (1, 1, 'r-');
    legend (HP, {'before', 'after'}); set (HP, 'visible', 'off');
    title  ('flip a tree');
    xlabel ('x [\mum]'); ylabel ('y [\mum]'); zlabel ('z [\mum]');
    if DIM == 3,
        view ([0 0]);
    else
        view (2);
    end
    grid on; axis image;
end

if (nargout > 0||(isstruct(intree)))
    varargout {1}  = tree; % if output is defined then it becomes the tree
else
    trees {intree} = tree; % otherwise add to end of trees cell array
end


text:
// src/polyfills.js must be the first import.
import '../polyfills';

import {draw3p, init} from '../integration-lib';
import {register} from '../3p';

import {sunmedia} from '../../ads/vendors/sunmedia';

init(window);
register('sunmedia', sunmedia);

window.draw3p = draw3p;