text:
#pragma once
#include <aws/neptune/Neptune_EXPORTS.h>
#include <aws/neptune/NeptuneRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Neptune
{
namespace Model
{

  /**
   */
  class AWS_NEPTUNE_API DescribeGlobalClustersRequest : public NeptuneRequest
  {
  public:
    DescribeGlobalClustersRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "DescribeGlobalClusters"; }

    Aws::String SerializePayload() const override;

  protected:
    void DumpBodyToUrl(Aws::Http::URI& uri ) const override;

  public:

    /**
     *
The user-supplied DB cluster identifier. If this parameter is specified, only
     * information about the specified DB cluster is returned. This parameter is not
     * case-sensitive.

Constraints: If supplied, must match an existing DB
     * cluster identifier.

     */
    inline const Aws::String& GetGlobalClusterIdentifier() const{ return m_globalClusterIdentifier; }

    /**
     *
The user-supplied DB cluster identifier. If this parameter is specified, only
     * information about the specified DB cluster is returned. This parameter is not
     * case-sensitive.

Constraints: If supplied, must match an existing DB
     * cluster identifier.

     */
    inline bool GlobalClusterIdentifierHasBeenSet() const { return m_globalClusterIdentifierHasBeenSet; }

    /**
     *
The user-supplied DB cluster identifier. If this parameter is specified, only
     * information about the specified DB cluster is returned. This parameter is not
     * case-sensitive.

Constraints: If supplied, must match an existing DB
     * cluster identifier.

     */
    inline void SetGlobalClusterIdentifier(const Aws::String& value) { m_globalClusterIdentifierHasBeenSet = true; m_globalClusterIdentifier = value; }

    /**
     *
The user-supplied DB cluster identifier. If this parameter is specified, only
     * information about the specified DB cluster is returned. This parameter is not
     * case-sensitive.

Constraints: If supplied, must match an existing DB
     * cluster identifier.

     */
    inline void SetGlobalClusterIdentifier(Aws::String&& value) { m_globalClusterIdentifierHasBeenSet = true; m_globalClusterIdentifier = std::move(value); }

    /**
     *
The user-supplied DB cluster identifier. If this parameter is specified, only
     * information about the specified DB cluster is returned. This parameter is not
     * case-sensitive.

Constraints: If supplied, must match an existing DB
     * cluster identifier.

     */
    inline void SetGlobalClusterIdentifier(const char* value) { m_globalClusterIdentifierHasBeenSet = true; m_globalClusterIdentifier.assign(value); }

    /**
     *
The user-supplied DB cluster identifier. If this parameter is specified, only
     * information about the specified DB cluster is returned. This parameter is not
     * case-sensitive.

Constraints: If supplied, must match an existing DB
     * cluster identifier.

     */
    inline DescribeGlobalClustersRequest& WithGlobalClusterIdentifier(const Aws::String& value) { SetGlobalClusterIdentifier(value); return *this;}

    /**
     *
The user-supplied DB cluster identifier. If this parameter is specified, only
     * information about the specified DB cluster is returned. This parameter is not
     * case-sensitive.

Constraints: If supplied, must match an existing DB
     * cluster identifier.

     */
    inline DescribeGlobalClustersRequest& WithGlobalClusterIdentifier(Aws::String&& value) { SetGlobalClusterIdentifier(std::move(value)); return *this;}

    /**
     *
The user-supplied DB cluster identifier. If this parameter is specified, only
     * information about the specified DB cluster is returned. This parameter is not
     * case-sensitive.

Constraints: If supplied, must match an existing DB
     * cluster identifier.

     */
    inline DescribeGlobalClustersRequest& WithGlobalClusterIdentifier(const char* value) { SetGlobalClusterIdentifier(value); return *this;}

    /**
     *
The maximum number of records to include in the response. If more records
     * exist than the specified MaxRecords value, a pagination marker
     * token is included in the response that you can use to retrieve the remaining
     * results.

Default: 100

Constraints: Minimum 20,
     * maximum 100.

     */
    inline int GetMaxRecords() const{ return m_maxRecords; }

    /**
     *
The maximum number of records to include in the response. If more records
     * exist than the specified MaxRecords value, a pagination marker
     * token is included in the response that you can use to retrieve the remaining
     * results.

Default: 100

Constraints: Minimum 20,
     * maximum 100.

     */
    inline bool MaxRecordsHasBeenSet() const { return m_maxRecordsHasBeenSet; }

    /**
     *
The maximum number of records to include in the response. If more records
     * exist than the specified MaxRecords value, a pagination marker
     * token is included in the response that you can use to retrieve the remaining
     * results.

Default: 100

Constraints: Minimum 20,
     * maximum 100.

     */
    inline void SetMaxRecords(int value) { m_maxRecordsHasBeenSet = true; m_maxRecords = value; }

    /**
     *
The maximum number of records to include in the response. If more records
     * exist than the specified MaxRecords value, a pagination marker
     * token is included in the response that you can use to retrieve the remaining
     * results.

Default: 100

Constraints: Minimum 20,
     * maximum 100.

     */
    inline DescribeGlobalClustersRequest& WithMaxRecords(int value) { SetMaxRecords(value); return *this;}

    /**
     *
(Optional) A pagination token returned by a previous call to
     * DescribeGlobalClusters. If this parameter is specified, the
     * response will only include records beyond the marker, up to the number specified
     * by MaxRecords.

     */
    inline const Aws::String& GetMarker() const{ return m_marker; }

    /**
     *
(Optional) A pagination token returned by a previous call to
     * DescribeGlobalClusters. If this parameter is specified, the
     * response will only include records beyond the marker, up to the number specified
     * by MaxRecords.

     */
    inline bool MarkerHasBeenSet() const { return m_markerHasBeenSet; }

    /**
     *
(Optional) A pagination token returned by a previous call to
     * DescribeGlobalClusters. If this parameter is specified, the
     * response will only include records beyond the marker, up to the number specified
     * by MaxRecords.

     */
    inline void SetMarker(const Aws::String& value) { m_markerHasBeenSet = true; m_marker = value; }

    /**
     *
(Optional) A pagination token returned by a previous call to
     * DescribeGlobalClusters. If this parameter is specified, the
     * response will only include records beyond the marker, up to the number specified
     * by MaxRecords.

     */
    inline void SetMarker(Aws::String&& value) { m_markerHasBeenSet = true; m_marker = std::move(value); }

    /**
     *
(Optional) A pagination token returned by a previous call to
     * DescribeGlobalClusters. If this parameter is specified, the
     * response will only include records beyond the marker, up to the number specified
     * by MaxRecords.

     */
    inline void SetMarker(const char* value) { m_markerHasBeenSet = true; m_marker.assign(value); }

    /**
     *
(Optional) A pagination token returned by a previous call to
     * DescribeGlobalClusters. If this parameter is specified, the
     * response will only include records beyond the marker, up to the number specified
     * by MaxRecords.

     */
    inline DescribeGlobalClustersRequest& WithMarker(const Aws::String& value) { SetMarker(value); return *this;}

    /**
     *
(Optional) A pagination token returned by a previous call to
     * DescribeGlobalClusters. If this parameter is specified, the
     * response will only include records beyond the marker, up to the number specified
     * by MaxRecords.

     */
    inline DescribeGlobalClustersRequest& WithMarker(Aws::String&& value) { SetMarker(std::move(value)); return *this;}

    /**
     *
(Optional) A pagination token returned by a previous call to
     * DescribeGlobalClusters. If this parameter is specified, the
     * response will only include records beyond the marker, up to the number specified
     * by MaxRecords.

     */
    inline DescribeGlobalClustersRequest& WithMarker(const char* value) { SetMarker(value); return *this;}

  private:

    Aws::String m_globalClusterIdentifier;
    bool m_globalClusterIdentifierHasBeenSet = false;

    int m_maxRecords;
    bool m_maxRecordsHasBeenSet = false;

    Aws::String m_marker;
    bool m_markerHasBeenSet = false;
  };

} // namespace Model
} // namespace Neptune
} // namespace Aws


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.

#[link(name = "rustc",
       vers = "0.8-pre",
       uuid = "0ce89b41-2f92-459e-bbc1-8f5fe32f16cf",
       url = "https://github.com/mozilla/rust/tree/master/src/rustc")];

#[comment = "The Rust compiler"];
#[license = "MIT/ASL2"];
#[crate_type = "lib"];

#[allow(non_implicitly_copyable_typarams)];
#[deny(deprecated_pattern)];

extern mod extra;
extern mod syntax;

use driver::driver::{host_triple, optgroups, early_error};
use driver::driver::{str_input, file_input, build_session_options};
use driver::driver::{build_session, build_configuration, parse_pretty};
use driver::driver::{pp_mode, pretty_print_input, list_metadata};
use driver::driver::{compile_input};
use driver::session;
use middle::lint;

use std::io;
use std::num;
use std::os;
use std::result;
use std::str;
use std::task;
use std::vec;
use extra::getopts::{groups, opt_present};
use extra::getopts;
use syntax::codemap;
use syntax::diagnostic;

pub mod middle {
    #[path = "trans/mod.rs"]
    pub mod trans;
    pub mod ty;
    pub mod subst;
    pub mod resolve;
    #[path = "typeck/mod.rs"]
    pub mod typeck;
    pub mod check_loop;
    pub mod check_match;
    pub mod check_const;
    pub mod lint;
    #[path = "borrowck/mod.rs"]
    pub mod borrowck;
    pub mod dataflow;
    pub mod mem_categorization;
    pub mod liveness;
    pub mod kind;
    pub mod freevars;
    pub mod pat_util;
    pub mod region;
    pub mod const_eval;
    pub mod astencode;
    pub mod lang_items;
    pub mod privacy;
    pub mod moves;
    pub mod entry;
    pub mod effect;
    pub mod reachable;
    pub mod graph;
    #[path = "cfg/mod.rs"]
    pub mod cfg;
}

pub mod front {
    pub mod config;
    pub mod test;
    pub mod std_inject;
}

pub mod back {
    pub mod link;
    pub mod abi;
    pub mod upcall;
    pub mod arm;
    pub mod mips;
    pub mod x86;
    pub mod x86_64;
    pub mod rpath;
    pub mod target_strs;
    pub mod passes;
}

#[path = "metadata/mod.rs"]
pub mod metadata;

#[path = "driver/mod.rs"]
pub mod driver;

pub mod util {
    pub mod common;
    pub mod ppaux;
    pub mod enum_set;
}

pub mod lib {
    pub mod llvm;
}

// A curious inner module that allows ::std::foo to be available in here for
// macros.
/*
mod std {
    pub use std::cmp;
    pub use std::os;
    pub use std::str;
    pub use std::sys;
    pub use std::to_bytes;
    pub use std::unstable;
    pub use extra::serialize;
}
*/

pub fn version(argv0: &str) {
    let mut vers = ~"unknown version";
    let env_vers = env!("CFG_VERSION");
    if env_vers.len() != 0 { vers = env_vers.to_owned(); }
    io::println(fmt!("%s %s", argv0, vers));
    io::println(fmt!("host: %s", host_triple()));
}

pub fn usage(argv0: &str) {
    let message = fmt!("Usage: %s [OPTIONS] INPUT", argv0);
    io::println(fmt!("%s\
Additional help:
    -W help             Print 'lint' options and default settings
    -Z help             Print internal options for debugging rustc\n",
                     groups::usage(message, optgroups())));
}

pub fn describe_warnings() {
    use extra::sort::Sort;
    io::println(fmt!("
Available lint options:
    -W <foo>           Warn about <foo>
    -A <foo>           Allow <foo>
    -D <foo>           Deny <foo>
    -F <foo>           Forbid <foo> (deny, and deny all overrides)
"));

    let lint_dict = lint::get_lint_dict();
    let mut lint_dict = lint_dict.consume_iter()
                                 .transform(|(k, v)| (v, k))
                                 .collect::<~[(lint::LintSpec, &'static str)]>();
    lint_dict.qsort();

    let mut max_key = 0;
    for lint_dict.iter().advance |&(_, name)| {
        max_key = num::max(name.len(), max_key);
    }
    fn padded(max: uint, s: &str) -> ~str {
        str::from_bytes(vec::from_elem(max - s.len(), ' ' as u8)) + s
    }
    io::println(fmt!("\nAvailable lint checks:\n"));
    io::println(fmt!("    %s  %7.7s  %s",
                     padded(max_key, "name"), "default", "meaning"));
    io::println(fmt!("    %s  %7.7s  %s\n",
                     padded(max_key, "----"), "-------", "-------"));
    for lint_dict.consume_iter().advance |(spec, name)| {
        let name = name.replace("_", "-");
        io::println(fmt!("    %s  %7.7s  %s",
                         padded(max_key, name),
                         lint::level_to_str(spec.default),
                         spec.desc));
    }
    io::println("");
}

pub fn describe_debug_flags() {
    io::println(fmt!("\nAvailable debug options:\n"));
    let r = session::debugging_opts_map();
    for r.iter().advance |pair| {
        let (name, desc, _) = /*bad*/copy *pair;
        io::println(fmt!("    -Z %-20s -- %s", name, desc));
    }
}

pub fn run_compiler(args: &~[~str], demitter: diagnostic::Emitter) {
    // Don't display log spew by default. Can override with RUST_LOG.
    ::std::logging::console_off();

    let mut args = /*bad*/copy *args;
    let binary = args.shift().to_managed();

    if args.is_empty() { usage(binary); return; }

    let matches =
        &match getopts::groups::getopts(args, optgroups()) {
          Ok(m) => m,
          Err(f) => {
            early_error(demitter, getopts::fail_str(f));
          }
        };

    if opt_present(matches, "h") || opt_present(matches, "help") {
        usage(binary);
        return;
    }

    // Display the available lint options if "-W help" or only "-W" is given.
    let lint_flags = vec::append(getopts::opt_strs(matches, "W"),
                                 getopts::opt_strs(matches, "warn"));

    let show_lint_options = lint_flags.iter().any(|x| x == &~"help") ||
        (opt_present(matches, "W") && lint_flags.is_empty());

    if show_lint_options {
        describe_warnings();
        return;
    }

    let r = getopts::opt_strs(matches, "Z");
    if r.iter().any(|x| x == &~"help") {
        describe_debug_flags();
        return;
    }

    if getopts::opt_maybe_str(matches, "passes") == Some(~"list") {
        back::passes::list_passes();
        return;
    }

    if opt_present(matches, "v") || opt_present(matches, "version") {
        version(binary);
        return;
    }
    let input = match matches.free.len() {
      0u => early_error(demitter, ~"no input filename given"),
      1u => {
        let ifile = matches.free[0].as_slice();
        if "-" == ifile {
            let src = str::from_bytes(io::stdin().read_whole_stream());
            str_input(src.to_managed())
        } else {
            file_input(Path(ifile))
        }
      }
      _ => early_error(demitter, ~"multiple input filenames provided")
    };

    let sopts = build_session_options(binary, matches, demitter);
    let sess = build_session(sopts, demitter);
    let odir = getopts::opt_maybe_str(matches, "out-dir");
    let odir = odir.map(|o| Path(*o));
    let ofile = getopts::opt_maybe_str(matches, "o");
    let ofile = ofile.map(|o| Path(*o));
    let cfg = build_configuration(sess, binary, &input);
    let pretty = getopts::opt_default(matches, "pretty", "normal").map(
                    |a| parse_pretty(sess, *a));
    match pretty {
      Some::<pp_mode>(ppm) => {
        pretty_print_input(sess, cfg, &input, ppm);
        return;
      }
      None::<pp_mode> => {/* continue */ }
    }
    let ls = opt_present(matches, "ls");
    if ls {
        match input {
          file_input(ref ifile) => {
            list_metadata(sess, &(*ifile), io::stdout());
          }
          str_input(_) => {
            early_error(demitter, ~"can not list metadata for stdin");
          }
        }
        return;
    }

    compile_input(sess, cfg, &input, &odir, &ofile);
}

#[deriving(Eq)]
pub enum monitor_msg {
    fatal,
    done,
}

/*
This is a sanity check that any failure of the compiler is performed
through the diagnostic module and reported properly - we shouldn't be calling
plain-old-fail on any execution path that might be taken. Since we have
console logging off by default, hitting a plain fail statement would make the
compiler silently exit, which would be terrible.

This method wraps the compiler in a subtask and injects a function into the
diagnostic emitter which records when we hit a fatal error. If the task
fails without recording a fatal error then we've encountered a compiler
bug and need to present an error.
*/
pub fn monitor(f: ~fn(diagnostic::Emitter)) {
    use std::comm::*;
    let (p, ch) = stream();
    let ch = SharedChan::new(ch);
    let ch_capture = ch.clone();
    match do task::try || {
        let ch = ch_capture.clone();
        let ch_capture = ch.clone();
        // The 'diagnostics emitter'. Every error, warning, etc. should
        // go through this function.
        let demitter: @fn(Option<(@codemap::CodeMap, codemap::span)>,
                          &str,
                          diagnostic::level) =
                          |cmsp, msg, lvl| {
            if lvl == diagnostic::fatal {
                ch_capture.send(fatal);
            }
            diagnostic::emit(cmsp, msg, lvl);
        };

        struct finally {
            ch: SharedChan<monitor_msg>,
        }

        impl Drop for finally {
            fn drop(&self) { self.ch.send(done); }
        }

        let _finally = finally { ch: ch };

        f(demitter);

        // Due reasons explain in #7732, if there was a jit execution context it
        // must be consumed and passed along to our parent task.
        back::link::jit::consume_engine()
    } {
        result::Ok(_) => { /* fallthrough */ }
        result::Err(_) => {
            // Task failed without emitting a fatal diagnostic
            if p.recv() == done {
                diagnostic::emit(
                    None,
                    diagnostic::ice_msg("unexpected failure"),
                    diagnostic::error);

                let xs = [
                    ~"the compiler hit an unexpected failure path. \
                     this is a bug",
                    ~"try running with RUST_LOG=rustc=1,::rt::backtrace \
                     to get further details and report the results \
                     to github.com/mozilla/rust/issues"
                ];
                for xs.iter().advance |note| {
                    diagnostic::emit(None, *note, diagnostic::note)
                }
            }
            // Fail so the process returns a failure code
            fail!();
        }
    }
}

pub fn main() {
    let args = os::args();
    do monitor |demitter| {
        run_compiler(&args, demitter);
    }
}

redpajama_set_name: RedPajamaGithub


text:
APIProduct

                <colgroup>
                    <col style="width: 10%;"/>
                    <col style="width: 30%;"/>
                    <col style="width: 10%;"/>
                    <col style="width: 20%;"/>
                    <col style="width: 30%;"/>
                </colgroup>

                    Name
                    Description
                    Schema
                    Default
                    Example

id

                                optional

UUID of the api product

                                string

null

01234567-0123-0123-0123-012345678901

name

                                required

Name of the API product

                                string

null

CalculatorAPIProduct

description

                                optional

A brief description about the API product

                                string

null

A calculator API product that supports basic operations

provider

                                required

If the provider value is not given user invoking the api will be used as the provider.

                                string

null

admin

apiDefinition

                                required

Swagger definition of the API product which contains details about URI templates and scopes

                                string

null

tiers

                                optional

The subscription tiers selected for the particular API product

                                array

null

["Unlimited"]

thumbnailUrl

                                optional

                                string

null

additionalProperties

                                optional

Custom(user defined) properties of API product

                                map

null

{}

businessInformation

                                optional

                                APIProduct_businessInformation

null


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Terminal.ViewModels;

namespace Terminal.Views
{
    /// <summary>
    /// MainWindow.xaml の相互作用ロジック
    /// </summary>
    public partial class MainWindow : Window
    {
        private MainWindowViewModel ViewModel { get; set; }

        public MainWindow()
        {
            InitializeComponent();

            ((App)Application.Current).CoreData
                .WindowPlacement.Register(this, "TerminalHeavensRock");

            this.ViewModel = new MainWindowViewModel() { View = this };

            this.ViewModel.SubscribeTextChanged(this.inputText);

            this.DataContext = this.ViewModel;
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
            => this.ViewModel?.Dispose();

    }
}


text:
#include "config.h"
#include "core/page/PageLifecycleObserver.h"

namespace blink {

PageLifecycleObserver::PageLifecycleObserver(Page* page)
    : LifecycleObserver<Page, PageLifecycleObserver, PageLifecycleNotifier>(page)
{
    setContext(page);
}

PageLifecycleObserver::~PageLifecycleObserver()
{
}

Page* PageLifecycleObserver::page() const
{
    return static_cast<Page*>(lifecycleContext());
}

} // namespace blink


text:
[#]: subject: "Parsing command options in Lua"
[#]: via: "https://opensource.com/article/21/8/parsing-commands-lua"
[#]: author: "Seth Kenlon https://opensource.com/users/seth"
[#]: collector: "lujun9972"
[#]: translator: " "
[#]: reviewer: " "
[#]: publisher: " "
[#]: url: " "

Parsing command options in Lua
======
My favorite way to solve the problem of parsing in Lua is alt-getopt.
![Woman sitting in front of her laptop][1]

When you enter a command into your terminal, there are usually [options][2], also called _switches_ or _flags_, that you can use to modify how the command runs. This is a useful convention defined by the [POSIX specification][3], so as a programmer, it's helpful to know how to detect and parse options.

As with most languages, there are several ways to solve the problem of parsing options in Lua. My favorite is [alt-getopt][4].

### Installing

The easiest way to obtain and use **alt-getopt** in your code is to [install it with LuaRocks][5]. For most use-cases, you probably want to install it into your local project directory:

```
$ mkdir local
$ luarocks --tree=local install alt-getopt
Installing <https://luarocks.org/alt-getopt-0.X.Y-1.src.rock>
[...]
alt-getopt 0.X.Y-1 is now installed in /tux/myproject/local (license: MIT/X11)
```

Alternately, you can download the code from [GitHub][6].

### Adding a library to your Lua code

Assuming you've installed the library locally, then you can define your Lua package path and then `require` the **alt-getopt** package:

```
package.path = package.path .. ';local/share/lua/5.1/?.lua'

local alt_getopt = require("alt_getopt")
```

If you've installed it to a known system location, you can omit the `package.path` line (because Lua already knows to look for system-wide libraries.)

Now you're set to parse options in Lua.

### Option parsing in Lua

The first thing you must do to parse options is to define the valid options your application can accept. The **alt_getopt** library sees all options primarily as short options, meaning that you define options as single letters. You can add long versions later.

When you define valid options, you create a list delimited by colons (`:`), which is interpreted by the `get_opts` function provided by **alt-getopts**.

First, create some variables to represent the options. The variables `short_opt` and `optarg` represent the short option and the option argument. These are arbitrary variable names, so you can call them anything (as long as it's a valid name for a variable).

The table `long_opts` must exist, but I find it easiest to define the values of the long options after you've decided on the short options, so leave it empty for now.

```
local long_opts = {}

local short_opt
local optarg
```

With those variables declared, you can iterate over the arguments provided by the user, checking to see whether any argument matches your approved list of valid short options.

If a valid option is found, you use the `pairs` function in Lua to extract the value of the option.

To create an option that accepts no argument of its own but is either _on_ or _off_ (often called a _switch_), you place the short option you want to define to the right of a colon (`:`) character.

In this example, I've created a loop to check for the short option `-a`, which is a switch:

```
short_opt,optarg = alt_getopt.get_opts (arg, ":a", long_opts)
local optvalues = {}
for k,v in pairs (short_opt) do
   table.insert (optvalues, "value of " .. k .. " is " .. v .. "\n")
end

table.sort (optvalues)
io.write (table.concat (optvalues))

for i = optarg,#arg do
   io.write (string.format ("ARGV [%s] = %s\n", i, arg [i]))
end
```

At the end of this sample code, I included a for-loop to iterate over any remaining arguments in the command because anything not detected as a valid option must be an argument (probably a file name, URI, or whatever it is that your application operates upon).

Test the code:

```
$ lua test.lua -a
value of a is 1
```

The test script has successfully detected the option `-a`, and has assigned it a value of **1** to represent that it does exist.

Try it again with an extra argument:

```
$ lua test.lua -a hello
value of a is 1
ARGV [2] = hello
```

### Options with arguments

Some options require an argument all their own. For instance, you might want to allow the user to point your application to a custom configuration file, set an attribute to a color, or set the resolution of a graphic. In **alt_getopt**, options that accept arguments are placed on the left of the colon (`:`) in the short options list.

```
`short_opt,optarg = alt_getopt.get_opts (arg, "c:a", long_opts)`
```

Test the code:

```
$ lua test.lua -a -c my.config
value of a is 1
value of c is my.config
```

Try it again, this time with a spare argument:

```
$ lua test.lua -a -c my.config hello
value of a is 1
value of c is my.config
ARGV [4] = hello
```

### Long options

Short options are great for power users, but they don't tend to be very memorable. You can create a table of long options that point to short options so users can learn long options before abbreviating their commands with single-letter options.

```
local long_opts = {
   alpha = "a",
   config = "c"
}
```

Users now have the choice between long and short options:

```
$ lua test.lua --config my.config --alpha hello
value of a is 1
value of c is my.config
ARGV [4] = hello
```

### Option parsing

Here's the full demonstration code for your reference:

```
#!/usr/bin/env lua
package.path = package.path .. ';local/share/lua/5.1/?.lua'

local alt_getopt = require("alt_getopt")

local long_opts = {
   alpha = "a",
   config = "c"
}

local short_opt
local optarg

short_opt,optarg = alt_getopt.get_opts (arg, "c:a", long_opts)
local optvalues = {}
for k,v in pairs (short_opt) do
   table.insert (optvalues, "value of " .. k .. " is " .. v .. "\n")
end

table.sort (optvalues)
io.write (table.concat (optvalues))

for i = optarg,#arg do
   io.write (string.format ("ARGV [%s] = %s\n", i, arg [i]))
end
```

There are further examples in the project's Git repository. Including options for your users is an important feature for any application, and Lua makes it easy to do. There are other libraries aside from **alt_getopt**, but I find this one easy and quick to use.

--------------------------------------------------------------------------------

via: https://opensource.com/article/21/8/parsing-commands-lua

作者:[Seth Kenlon][a]
选题:[lujun9972][b]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)

本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出

[a]: https://opensource.com/users/seth
[b]: https://github.com/lujun9972
[1]: https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/OSDC_women_computing_4.png?itok=VGZO8CxT (Woman sitting in front of her laptop)
[2]: https://opensource.com/article/21/7/linux-terminal-basics#options
[3]: https://opensource.com/article/19/7/what-posix-richard-stallman-explains
[4]: https://luarocks.org/modules/mpeterv/alt-getopt
[5]: https://opensource.com/article/19/11/getting-started-luarocks
[6]: https://github.com/cheusov/lua-alt-getopt


text:
using System;
namespace FFImageLoading.Exceptions
{
    [Preserve(AllMembers = true)]
    public class DownloadReadTimeoutException : Exception
    {
        public DownloadReadTimeoutException() : base("Read timeout")
        {
        }
    }
}


text: Building an e-commerce application with the MEAN stack


text:
Commands['get'] = lambda do |env, command, args|
  value = env.get(args.first)
  [Command::Success, Output.new(value), env]
end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Ascobolus daldinianus De Not.

### Remarks
null


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>teamJSON</title>
    <meta content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no' name='viewport'>

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

    <link href="dist/css/font-awesome.min.css" rel="stylesheet" type="text/css" />

    <link href="dist/css/AdminLTE.min.css" rel="stylesheet" type="text/css" />
    <link href="dist/css/skins/skin-blue.min.css" rel="stylesheet" type="text/css" />

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

        PolicyHack

            Toggle navigation

          <form action="#" method="get" class="sidebar-form">

              <input type="text" name="q" class="form-control" placeholder="Search..."/>

                <button type='submit' name='search' id='search-btn' class="btn btn-flat"></button>

          </form>

HEADER

Live<

Individual<

Data Data<

            Page Header
            Optional description

          Anything you want

        Copyright © 2015 Company. All rights reserved.


text:
require 'spec_helper'

describe BoxView::Document, '#document_id' do

  it 'should raise error when document id is nil' do
    expect{BoxView.document_id}.to raise_error(BoxView::Errors::DocumentIdNotFound)
  end

end

describe BoxView::Document, '#url' do
  it 'should raise error when url is nil' do
    BoxView::Document.url = nil
    expect{BoxView::Document.url}.to raise_error(BoxView::Errors::UrlNotFound)
  end

  it 'should return url when defined' do
    BoxView::Document.url = 'http://imgur.com/cats.jpeg'
    expect(BoxView::Document.url).not_to be_nil
  end
end

describe BoxView::Document, '#type' do
  it 'should raise error when setting with invalid type' do
    expect{BoxView::Document.type = 'jpeg'}.to raise_error(BoxView::Errors::TypeNotFound)
  end

  it 'should return when type is valid' do
    expect(BoxView::Document.type = 'pdf').not_to be_nil
  end
end

describe BoxView::Document, '#dimensions' do

  it 'should raise error when dimensions are nil' do
    expect{BoxView::Document.dimensions}.to raise_error(BoxView::Errors::DimensionsNotFound)
  end

  it 'should raise error when height is nil, but width is defined' do
    BoxView::Document.width = 100
    BoxView::Document.height = nil
    expect{BoxView::Document.dimensions}.to raise_error(BoxView::Errors::DimensionsNotFound)
  end

  it 'should raise error when width is nil, but height is defined' do
    BoxView::Document.width = nil
    BoxView::Document.height = 100
    expect{BoxView::Document.dimensions}.to raise_error(BoxView::Errors::DimensionsNotFound)
  end

end

describe BoxView::Document, '#thumbnail_params' do

  it 'should raise when dimensions are nil' do
    expect{BoxView::Document.thumbnail_params}.to raise_error(BoxView::Errors::DimensionsNotFound)
  end

  it 'should raise when height is nil, but width is defined' do
    BoxView::Document.width = 100
    BoxView::Document.height = nil
    expect{BoxView::Document.thumbnail_params}.to raise_error(BoxView::Errors::DimensionsNotFound)
  end

  it 'should raise when width is nil, but height is defined' do
    BoxView::Document.width = nil
    BoxView::Document.height = 100
    expect{BoxView::Document.thumbnail_params}.to raise_error(BoxView::Errors::DimensionsNotFound)
  end
end
describe BoxView::Document, '#create' do
  let(:mock_response) { double('202 Response', { :code => 201, :body => '{"id": "123"}'}) }

  before do
    allow(BoxView).to receive(:post).and_return(mock_response)
  end

  xit 'should raise when receiving a bad request' do
  end

  context 'when receiving a bad api key' do
    let(:mock_response) { double('401 Response', { :code => 401 }) }

    it 'should raise' do
      BoxView.api_key = 'somesortofbadapikey'
      BoxView::Document.url = 'http://imgur.com/cats.jpeg'
      expect{BoxView::Document.create}.to raise_error(BoxView::Errors::DocumentIdNotGenerated)
    end
  end

  it 'should return the response when sent a good request (200..202)' do
    BoxView.api_key = API_KEY
    BoxView::Document.url = 'http://i.imgur.com/4RZkFbE.png'
    response = BoxView::Document.create
    expect(200..202).to cover(response.code)
  end
end
describe BoxView::Document, '#delete' do
  let(:mock_response) { double('204 Response', { :code => 204, :body => '' }) }

  before do
    allow(BoxView).to receive(:delete).and_return(mock_response)
  end

  it 'should return an empty string when sent a good request resulting in a 204 (empty) response' do
    response = BoxView::Document.delete document_id: "xyz"
    expect(response.body).to eq ''
  end
end


text:
#import "KFSearchFieldC.h"

@implementation KFSearchFieldC

BOOL skipNextCompletion = NO;

- (NSRange) rangeForUserCompletion {
	NSRange range = [super rangeForUserCompletion];
	range.location = 0;
	range.length = [[self string] length];
	return range;
}

- (void)insertCompletion:(NSString *)word forPartialWordRange:(NSRange)charRange
				movement:(NSInteger)movement isFinal:(BOOL)flag {
    if (movement == NSCancelTextMovement || movement == NSLeftTextMovement || movement == NSRightTextMovement) {
        skipNextCompletion = YES;
    } else if (flag && movement == NSReturnTextMovement) {
		skipNextCompletion = YES;
        [[self delegate] performSelector:@selector(performClick:) withObject:self];
        [[self delegate] textDidChange:[NSNotification notificationWithName:NSTextDidChangeNotification object:self]];
        [[self delegate] textDidEndEditing:[NSNotification notificationWithName:NSTextDidEndEditingNotification object:self]];
	} else {
        [super insertCompletion: word forPartialWordRange: charRange movement: movement isFinal: flag];
    }

}

- (NSArray *)completionsForPartialWordRange:(NSRange)charRange indexOfSelectedItem:(NSInteger *)index {
	if (skipNextCompletion) {
		skipNextCompletion = NO;
		return nil;
	} else {
		return [super completionsForPartialWordRange: charRange indexOfSelectedItem: index];
	}
}

@end


text:
package com.meltmedia.cadmium.core.worker;

import java.util.concurrent.Callable;
import java.util.concurrent.Future;

import com.meltmedia.cadmium.core.git.DelayedGitServiceInitializer;

public class SwitchRepositoryTask implements Callable<Boolean> {

  private DelayedGitServiceInitializer service;
  private String repository;
  private Future<Boolean> lastTask;

  public SwitchRepositoryTask(DelayedGitServiceInitializer service, String repository, Future<Boolean> lastTask) {
    this.service = service;
    this.repository = repository;
    this.lastTask = lastTask;
  }

  @Override
  public Boolean call() throws Exception {
    if(lastTask != null) {
      Boolean lastResponse = lastTask.get();
      if(lastResponse != null && !lastResponse.booleanValue() ) {
        throw new Exception("Previous task failed");
      }
    }
    service.switchRepository(repository);
    return true;
  }

}


text:
DROP TABLE IF EXISTS "ns_cat_type";
CREATE TABLE "ns_cat_type" (
  "ns_cat_type_id" int(11) NOT NULL AUTO_INCREMENT,
  "ns_cat_type_name" varchar(40) DEFAULT NULL,
  PRIMARY KEY ("ns_cat_type_id")
);


text:
/*
 * @(#)Spouse.java	1.5 06/02/11
 */

package com.sun.ts.tests.ejb30.persistence.query.language.schema30;

import javax.persistence.Id;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Column;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.CascadeType;

/*
 * Spouse
 */

@Entity
@Table(name="SPOUSE_TABLE")
public class Spouse implements java.io.Serializable {

    // Instance variables
    private String id;
    private String first;
    private String maiden;
    private String last;
    private String sNumber;
    private Info info;
    private Customer customer;

    public Spouse()
    {
    }

    public Spouse(String v1, String v2, String v3, String v4,
		String v5, Info v6)
    {
	id = v1;
	first = v2;
	maiden = v3;
	last = v4;
	sNumber = v5;
	info = v6;
    }

    public Spouse(String v1, String v2, String v3, String v4,
		String v5, Info v6, Customer v7)
    {
	id = v1;
	first = v2;
	maiden = v3;
	last = v4;
	sNumber = v5;
	info = v6;
        customer = v7;
    }

    // getters and setters for state fields

    @Id
    @Column(name="ID")
    public String getId()
    {
	return id;
    }
    public void setId(String v)
    {
	id = v;
    }

    @Column(name="FIRSTNAME")
    public String getFirstName()
    {
	return first;
    }
    public void setFirstName(String v)
    {
	first = v;
    }

    @Column(name="MAIDENNAME")
    public String getMaidenName()
    {
	return maiden;
    }
    public void setMaidenName(String v)
    {
	maiden = v;
    }

    @Column(name="LASTNAME")
    public String getLastName()
    {
        return last;
    }
    public void setLastName(String v)
    {
        last = v;
    }

    @Column(name="SOCSECNUM")
    public String getSocialSecurityNumber()
    {
	return sNumber;
    }
    public void setSocialSecurityNumber(String v)
    {
	sNumber = v;
    }

    // 1X1
    @OneToOne(cascade=CascadeType.ALL)
    @JoinColumn(
	name="FK_FOR_INFO_TABLE")
    public Info getInfo()
    {
        return info;
    }
    public void setInfo(Info v)
    {
        info = v;
    }

    // 1X1
    @OneToOne(cascade=CascadeType.ALL)
    @JoinColumn(
	name="FK7_FOR_CUSTOMER_TABLE")
    public Customer getCustomer()
    {
        return customer;
    }
    public void setCustomer(Customer v)
    {
        customer = v;
    }

}


text:
<?php

namespace app\models;

use nodge\eauth\ErrorException;
use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;

/**
 * User model
 *
 * @property integer $id
 * @property string $steamid
 * @property string $username
 * @property string $auth_key
 * @property string $profile_url
 * @property string $avatar
 * @property string $avatar_md
 * @property string $avatar_lg
 * @property integer $status
 * @property integer $created_at
 * @property integer $updated_at
 */
class User extends ActiveRecord implements IdentityInterface
{
    const STATUS_DELETED = 0;
    const STATUS_ACTIVE = 10;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%user}}';
    }

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            ['status', 'default', 'value' => self::STATUS_ACTIVE],
            ['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],
        ];
    }

    /**
     * @inheritdoc
     */
    public static function findIdentity($id)
    {
        if (Yii::$app->getSession()->has('user-' . $id)) {
            return new self(Yii::$app->getSession()->get('user-' . $id));
        }

        return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
    }

    /**
     * @param \nodge\eauth\ServiceBase $service
     * @return User
     * @throws ErrorException
     */
    public static function findByEAuth($service)
    {
        if (!$service->getIsAuthenticated()) {
            throw new ErrorException('EAuth user should be authenticated before creating identity.');
        }

        $id = $service->getServiceName().'-'.$service->getId();

        $attributes = [
            'id' => $id,
            'steamid' => $service->getAttribute('steamid'),
            'username' => $service->getAttribute('username'),
            'profile_url' => $service->getAttribute('profile_url'),
            'avatar' => $service->getAttribute('avatar'),
            'avatar_md' => $service->getAttribute('avatar_md'),
            'avatar_lg' => $service->getAttribute('avatar_lg'),
        ];

        Yii::$app->getSession()->set('user-'.$id, $attributes);

        return new self($attributes);
    }

    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
    }

    /**
     * Finds user by username
     *
     * @param string $username
     * @return static|null
     */
    public static function findByUsername($username)
    {
        return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]);
    }

    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->auth_key;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }

    /**
     * Generates "remember me" authentication key
     */
    public function generateAuthKey()
    {
        $this->auth_key = Yii::$app->security->generateRandomString();
    }

    public function getMessages()
    {
        return $this->hasMany(Message::className(), ['steamid' => 'steamid']);
    }
}


text:
package org.rapidoid.config;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.rapidoid.annotation.Authors;
import org.rapidoid.annotation.Since;
import org.rapidoid.env.Env;
import org.rapidoid.io.IO;
import org.rapidoid.test.AbstractCommonsTest;
import org.rapidoid.test.TestIO;
import org.rapidoid.util.Msc;

@Authors("Nikolche Mihajlovski")
@Since("5.2.5")
public class RootCustomizationTest extends AbstractCommonsTest {

    @BeforeEach
    public void reset() {
        Env.reset();
        Conf.reset();
    }

    @Test
    public void testConfigRootSetup() {
        String dir = TestIO.createTempDir("app");

        IO.save(Msc.path(dir, "config.yml"), "id: abc1");

        Env.setArgs("root=" + dir, "config=config");

        eq(Conf.ROOT.entry("id").getOrNull(), "abc1");
    }

    @Test
    public void testConfigRootAndFileSetup() {
        String dir = TestIO.createTempDir("app");

        IO.save(Msc.path(dir, "the-config.yml"), "id: abc2");

        Env.setArgs("root=" + dir, "config=the-config");

        eq(Conf.ROOT.entry("id").getOrNull(), "abc2");
    }

}


text:
package com.greenpepper.runner;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 *
CompositeSpecificationRunnerMonitor class.

 *
 * @author oaouattara
 * @version $Id: $Id
 */
public class CompositeSpecificationRunnerMonitor implements SpecificationRunnerMonitor
{
    private final List<SpecificationRunnerMonitor> monitors;

    /**
     *
Constructor for CompositeSpecificationRunnerMonitor.

     *
     * @param monitors a {@link com.greenpepper.runner.SpecificationRunnerMonitor} object.
     */
    public CompositeSpecificationRunnerMonitor( SpecificationRunnerMonitor... monitors )
    {
        this( Arrays.asList( monitors ) );
    }

    /**
     *
Constructor for CompositeSpecificationRunnerMonitor.

     *
     * @param monitors a {@link java.util.List} object.
     */
    public CompositeSpecificationRunnerMonitor( List<SpecificationRunnerMonitor> monitors )
    {
        this.monitors = new ArrayList<SpecificationRunnerMonitor>();
        this.monitors.addAll( monitors );
    }

    /**
     *
Constructor for CompositeSpecificationRunnerMonitor.

     */
    public CompositeSpecificationRunnerMonitor()
    {
        this( Collections.<SpecificationRunnerMonitor>emptyList() );
    }

    /**
     *
add.

     *
     * @param monitor a {@link com.greenpepper.runner.SpecificationRunnerMonitor} object.
     */
    public void add( SpecificationRunnerMonitor monitor )
    {
        monitors.add( monitor );
    }

    /** {@inheritDoc} */
    public void testRunning( String location )
    {
        for (SpecificationRunnerMonitor monitor : monitors)
        {
            monitor.testRunning( location );
        }
    }

    /** {@inheritDoc} */
    public void testDone( int rightCount, int wrongCount, int exceptionCount, int ignoreCount ) {
        // reverse the order in which the monitors are notified
        Collections.reverse(monitors);
        for (SpecificationRunnerMonitor monitor : monitors) {
            monitor.testDone( rightCount, wrongCount, exceptionCount, ignoreCount );
        }
        Collections.reverse(monitors);
    }

    /** {@inheritDoc} */
    public void exceptionOccured( Throwable t )
    {
        for (SpecificationRunnerMonitor monitor : monitors)
        {
            monitor.exceptionOccured( t );
        }
    }
}


text:
const closureBuilder = require('closure-builder');
const glob = closureBuilder.globSupport();

closureBuilder.build({
  name: 'standard',
  srcs: glob([
    'src/js/*.js',
  ]),
  out: 'demo/bundle.js',
  out_source_map: 'demo/bundle.js.map',
  append: '//@ sourceMappingURL=bundle.js.map'
});


text:
namespace Gwen
{
namespace ControlsInternal
{

GWEN_CONTROL_CONSTRUCTOR(Slider, Base)
{
    _bar = new ControlsInternal::SliderBar(this);
    _bar->SetWidth(15);
    _bar->_on_dragged.Add(this, &Slider::OnMoved);

    _minimum = 0.0f;
    _maximum = 1.0f;

    _clamp_to_notches = false;
    _number_of_notches = 5;

    _value = 0.0f;

    SetBounds(Rectangle(0, 0, 128, 16));
    SetTabable(true);
}

void Slider::Layout(Skin::Base* skin)
{
    // Call the base class.
    Base::Layout(skin);
}

void Slider::SetClampToNotches(bool clamp)
{
    _clamp_to_notches = clamp;
}

void Slider::SetNotchCount(unsigned count)
{
    _number_of_notches = count;
}

unsigned Slider::GetNotchCount() const
{
    return _number_of_notches;
}

void Slider::SetMinimum(float minimum)
{
    _minimum = minimum;
}

float Slider::GetMinimum() const
{
    return _minimum;
}

void Slider::SetMaximum(float maximum)
{
    _maximum = maximum;
}

float Slider::GetMaximum() const
{
    return _maximum;
}

void Slider::SetValue(float value, bool)
{
    value = Utility::Clamp(value, _minimum, _maximum);
    value = (value - _minimum) / (_maximum - _minimum);

    _SetValueInternal(value);

    Redraw();
}

float Slider::GetValue()
{
    return _minimum + (_value * (_maximum - _minimum));
}

float Slider::CalculateValue()
{
    return 0.0f;
}

void Slider::OnMoved(Controls::Base*)
{
    _SetValueInternal(CalculateValue());
}

bool Slider::OnKeyLeft(bool is_down)
{
    if (is_down)
    {
        SetValue(GetValue() - 1.0f, true);
    }

    return true;
}

bool Slider::OnKeyRight(bool is_down)
{
    if (is_down)
    {
        SetValue(GetValue() + 1.0f, true);
    }

    return true;
}

bool Slider::OnKeyUp(bool is_down)
{
    if (is_down)
    {
        SetValue(GetValue() + 1.0f, true);
    }

    return true;
}

bool Slider::OnKeyDown(bool is_down)
{
    if (is_down)
    {
        SetValue(GetValue() - 1.0f, true);
    }

    return true;
}

void Slider::_SetValueInternal(float value)
{
    if (_clamp_to_notches)
    {
        value = floorf(value * static_cast<float>(_number_of_notches) + 0.5f);
        value /= static_cast<float>(_number_of_notches);
    }

    if (_value != value)
    {
        _value = value;
        onValueChanged.Call(this);
    }

    UpdateBarFromValue();
}

void Slider::RenderFocus(Gwen::Skin::Base* skin)
{
    if (Gwen::Controls::_keyboard_focus != this)
    {
        return;
    }

    if (!IsTabable())
    {
        return;
    }

    skin->DrawKeyboardHighlight(this, GetRenderBounds(), 0);
}

void Slider::_OnBoundsChanged(const Gwen::Rectangle& old_bounds)
{
    // Call the base class.
    Base::_OnBoundsChanged(old_bounds);
}

}; // namespace ControlsInternal

}; // namespace Gwen


text:
#ifndef SDK_ANDROID_SRC_JNI_PC_PEERCONNECTIONFACTORY_H_
#define SDK_ANDROID_SRC_JNI_PC_PEERCONNECTIONFACTORY_H_

#include <jni.h>

namespace webrtc {
namespace jni {

void PeerConnectionFactoryNetworkThreadReady();
void PeerConnectionFactoryWorkerThreadReady();
void PeerConnectionFactorySignalingThreadReady();

}  // namespace jni
}  // namespace webrtc

#endif  // SDK_ANDROID_SRC_JNI_PC_PEERCONNECTIONFACTORY_H_


text:
effmount
========

Nikon serial number scraper


text:
#define PAGE_SIZE 4096

#define MIN_PKT_SIZE 64
#define MAX_PKT_SIZE 1500
typedef struct _pkt {
	double timestamp;
	unsigned int bytes;
	unsigned int priority;
	struct _pkt *next;
} pkt;

#define MIN_PRIORITY 0
#define MAX_PRIORITY 63
#define MIN_WEIGHT 1
#define MAX_WEIGHT 100
#define MIN_DEPTH 1
#define MAX_DEPTH 1024
#define MIN_QUEUES 1
#define MAX_QUEUES 8
typedef struct _queue {
	unsigned int max_depth;
	unsigned int curr_depth;
	unsigned int bucket;
	unsigned int max_tokens;
	unsigned int total_pkts;
	unsigned int total_bytes;
	unsigned int dropped_pkts;
	double cumulative_latency;
	unsigned char min_priority;
	unsigned char max_priority;
	unsigned char weight;
	pkt *head;
	pkt *free;
	pkt *ring_buffer;
} queue;

typedef struct _interface {
	unsigned int speed;
	unsigned int total_pkts;
	unsigned int total_bytes;
	unsigned char num_queues;
	double ifg;
	char priority_queue_enabled;
	queue **ifqueue;
} interface;

int InitQueues(void);
int InitRingBuffer(unsigned int, pkt **);
int DestroyRingBuffer(unsigned char);
int DestroyQueues(void);


text:
<?php

require_once('generate_ntree.php');

function generate_root_category_for_multishop()
{
	Db::getInstance()->execute('
		UPDATE `'._DB_PREFIX_.'category` SET `level_depth`=`level_depth`+1
	');

	Db::getInstance()->execute('
		INSERT INTO `'._DB_PREFIX_.'category` (`id_parent`, `level_depth`, `active`, `date_add`, `date_upd`, `is_root_category`) VALUES
		(0, 0, 1, NOW(), NOW(), 0)
	');
	$id = Db::getInstance()->insert_id();
	// set vars config
	Db::getInstance()->execute('INSERT INTO `'._DB_PREFIX_.'configuration` (`name`, `value`, `date_add`, `date_upd`) VALUES
	(\'PS_ROOT_CATEGORY\', '.(int)$id.', NOW(), NOW()),
	(\'PS_HOME_CATEGORY\', 1, NOW(), NOW())
	');

	$langs = Db::getInstance()->executeS('
		SELECT `id_lang`
		FROM `'._DB_PREFIX_.'lang`
	');

	$shops = Db::getInstance()->executeS('
		SELECT `id_shop`
		FROM `'._DB_PREFIX_.'shop`
	');

	$data = array();
	if(is_array($shops) && is_array($langs))
	{
		foreach ($langs as $lang)
			foreach ($shops as $shop)
				$data[] = array(
					'id_lang' => $lang['id_lang'],
					'id_shop' => $shop['id_shop'],
					'id_category' => $id,
					'name' => 'Root',
					'link_rewrite' => '',
				);
		Db::getInstance()->insert('category_lang', $data);
	}

	$categories = Db::getInstance()->executeS('
		SELECT `id_category`
		FROM `'._DB_PREFIX_.'category`
	');
	$data = array();
	if(is_array($shops) && is_array($categories))
	{
		foreach ($categories as $category)
			foreach ($shops as $shop)
				$data[] = array(
					'id_category' => $category['id_category'],
					'id_shop' => $shop['id_shop']
				);
		Db::getInstance()->insert('category_shop', $data);
	}

	Db::getInstance()->execute('
		UPDATE `'._DB_PREFIX_.'category`
		SET `id_parent` = '.(int)$id.'
		WHERE `id_parent` = 0 AND `id_category` <> '.(int)$id.'
	');
	Db::getInstance()->execute('
		UPDATE `'._DB_PREFIX_.'shop`
		SET `id_category` = 1
		WHERE `id_shop` = 1
	');

	generate_ntree();
}


text:
package ru.job4j;

/**
 *Class Teacher, решение задачи 3.1 части 002.
 *@author Konstantin Alekseev.
 *@since 23.04.2017.
 *@version 1.0.
 */

 public class Teacher extends Profession {

 /**
 *@param schedule - поле класса.
 */
private String schedule;

/**
 *Class Teacher, конструктор.
 *@param name - поле класса.
 *@param specialization - поле класса.
 *@param diploma - поле класса.
 */
public Teacher(String name, String specialization, String diploma) {
    super(name, specialization, diploma);
	  }

/**
 *Метод teach - выводит строку о том, кого учит учитель.
 *@param learner - входной параметр ученик.
 *@return - возвращает эту строку.
 */
 public String teach(String learner) {
 return String.format("Учитель учит " + learner);
 }
}


text:
// <copyright file="SepiaProcessor.cs" company="James Jackson-South">
// Copyright (c) James Jackson-South and contributors.
// Licensed under the Apache License, Version 2.0.
// </copyright>

namespace ImageSharp.Processing.Processors
{
    using System;
    using System.Numerics;

    using ImageSharp.PixelFormats;

    /// <summary>
    /// Converts the colors of the image to their sepia equivalent.
    /// The formula used matches the svg specification. <see href="http://www.w3.org/TR/filter-effects/#sepiaEquivalent"/>
    /// </summary>
    /// <typeparam name="TPixel">The pixel format.</typeparam>
    internal class SepiaProcessor<TPixel> : ColorMatrixProcessor<TPixel>
        where TPixel : struct, IPixel<TPixel>
    {
        /// <inheritdoc/>
        public override Matrix4x4 Matrix => new Matrix4x4
        {
            M11 = .393F,
            M12 = .349F,
            M13 = .272F,
            M21 = .769F,
            M22 = .686F,
            M23 = .534F,
            M31 = .189F,
            M32 = .168F,
            M33 = .131F,
            M44 = 1
        };

        /// <inheritdoc/>
        public override bool Compand => false;
    }
}


text:
package ar.edu.itba.paw.persistence.hibernate;

import ar.edu.itba.paw.persistence.AddressDao;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

@Repository
public class AddressHibernateDao implements AddressDao{

    @PersistenceContext
    private EntityManager em;

    @Override
    @SuppressWarnings("unchecked")
    public List<String> getAllNeighborhoods() {
        final Query query = em.createQuery("SELECT DISTINCT neighborhood FROM Address");
        return query.getResultList();
    }
}


text:
"use strict";

window.addEvent('domready', function() {
  var container = $('container'), preview = $('preview'), tetris = new uTetris(container, preview, {
    keypress: true,
    box_width: "20px",
    box_height: "20px"
  });

  var play = $("play"),
      score = $("score"),
      level = $("level"),
      lines = $("lines");

  tetris.addEvents({
    "start": function(e) {
      container.addClass('game');
      preview.addClass('game');
      setInfo(e);
      setPause();
    },
    "lines": setInfo,
    "fixed": setInfo,
    "pause": setPause,
    "gameover": function() {
      container.removeClass('game');
      preview.removeClass('game');
      play.set("html", "Play");
    }
  });

  function setLabel(str) {
    play.set("html", str);
  }

  function setInfo(obj) {
    level.set("html", "Level: " + obj.level || 0);
    score.set("html", "Score: " + obj.score || 0);
    lines.set("html", "Lines: " + obj.lines || 0);
  }

  function setPause(pause) {
    setLabel(pause ? "Resume" : "Pause");
  }

  play.addEvent("click", function() {
    if (this.isStop()) {
      this.restart();
    } else {
      this.pause();
    }
  }.bind(tetris));
});


text:
    <meta charset="UTF-8">
    <title>Projection Space</title>

    <meta name="description" content="Projection Space: Instanced geometry used as projection for textures (still, video, render target)">
    <meta name="keywords" content="WebGL, three.js, shader programming, instancing, javascript">
    <meta name="author" content="Kai Salmen">

    <link href="../../src/css/ThreeJsApp.css" type="text/css" rel="stylesheet"/>
    <link href="../nav/NavMenu.css" type="text/css" rel="stylesheet"/>
    <link rel="import" href="../nav/NavMenu.html" />

Loading...

        <canvas id="DivGLFullCanvas"></canvas>
        <video id="DivGLFullVideo" loop muted controls>
            <source src="../../resource/video/CosmosLaundromat_FirstCycle_1080p.mp4" type="video/mp4">
            <source src="../../resource/video/CosmosLaundromat_FirstCycle_1080p.ogv" type='video/ogg; codecs="theora, vorbis"'>
        </video>
        <canvas id="DivGLFullVideoBuffer"></canvas>

What do I see here? Please explain!

        You see a two dimensional array of instantiated box meshes. I call it the "Projection Space".
        Every single box of the Projection Space is used to render either one of the three:

        - Render Target Texture (RTT): The default scene you see once the page is loaded

        - Video Texture: Blender Foundations's Cosmos Laundromat is shown

        - Static Texture: A static preview image of the demo links is shown on mouse-over

        Each box receives color information (via texture UV coordinates) from the textures. The color is used to transform the box. The brighter the pixel, the higher the box.
        Slider "Extrusion" enhances the effect. The transformation can be inverted (dark=high; bright=low) via "Invert Ext.".
        Each box can be scaled ('Box Scale') and the distance from each other can be changed ('Box Spacing').

        The box instance count is adjustable on five levels. The count is 24.000, 217.440, 686.080, 1.543.680, 6.174.720 respectively.
        The last two levels require fast GPUs (mobile is no fun here).

        If the texture is animated (RTT) or plays a video then this playback is paused or continued via "Animate/Play". Video needs to be enabled via "Enable Video".

        Parameters "Extrusion", "Invert Ext.", "Box Scale", "Box Spacing" are used by the Vertex Shader and are processed directly on the GPU.
        The "Instance Count" defines how many instantiated boxes are being sent to the GPU including adjusted texture coordinates.
        Attribute arrays for all levels are generated when the website is loaded and the Javascript code is interpreted.

            Cubemap by Humus

            Video by (CC) Blender Foundation | gooseberry.blender.org


text:
goog.provide('shaka.cea.Mp4CeaParser');

goog.require('goog.asserts');
goog.require('shaka.cea.ICeaParser');
goog.require('shaka.cea.SeiProcessor');
goog.require('shaka.log');
goog.require('shaka.util.DataViewReader');
goog.require('shaka.util.Error');
goog.require('shaka.util.Mp4Parser');
goog.require('shaka.util.Mp4BoxParsers');

/**
 * MPEG4 stream parser used for extracting 708 closed captions data.
 * @implements {shaka.cea.ICeaParser}
 */
shaka.cea.Mp4CeaParser = class {
  /** */
  constructor() {
    /**
     * SEI data processor.
     * @private
     * @const {!shaka.cea.SeiProcessor}
     */
    this.seiProcessor_ = new shaka.cea.SeiProcessor();

    /**
     * Map of track id to corresponding timescale.
     * @private {!Map<number, number>}
     */
    this.trackIdToTimescale_ = new Map();

    /**
     * Default sample duration, as specified by the TREX box.
     * @private {number}
     */
    this.defaultSampleDuration_ = 0;

    /**
     * Default sample size, as specified by the TREX box.
     * @private {number}
     */
    this.defaultSampleSize_ = 0;

    /**
     * @private {shaka.cea.Mp4CeaParser.BitstreamFormat}
     */
    this.bitstreamFormat_ = shaka.cea.Mp4CeaParser.BitstreamFormat.UNKNOWN;
  }

  /**
   * Parses the init segment. Gets Default Sample Duration and Size from the
   * TREX box, and constructs a map of Track IDs to timescales. Each TRAK box
   * contains a track header (TKHD) containing track ID, and a media header box
   * (MDHD) containing the timescale for the track
   * @override
   */
  init(initSegment) {
    const Mp4Parser = shaka.util.Mp4Parser;
    const BitstreamFormat = shaka.cea.Mp4CeaParser.BitstreamFormat;
    const trackIds = [];
    const timescales = [];

    // This generates a box-parser callback that simply sets a particular
    // bitstream format.  It makes the list of codec-signalling boxes below
    // more compact and readable.
    const bitstreamFormatSetter = (format) => {
      return (box) => {
        this.bitstreamFormat_ = format;
      };
    };

    new Mp4Parser()
        .box('moov', Mp4Parser.children)
        .box('mvex', Mp4Parser.children)
        .fullBox('trex', (box) => {
          const parsedTREXBox = shaka.util.Mp4BoxParsers.parseTREX(
              box.reader);

          this.defaultSampleDuration_ = parsedTREXBox.defaultSampleDuration;
          this.defaultSampleSize_ = parsedTREXBox.defaultSampleSize;
        })
        .box('trak', Mp4Parser.children)
        .fullBox('tkhd', (box) => {
          goog.asserts.assert(
              box.version != null,
              'TKHD is a full box and should have a valid version.');
          const parsedTKHDBox = shaka.util.Mp4BoxParsers.parseTKHD(
              box.reader, box.version);
          trackIds.push(parsedTKHDBox.trackId);
        })
        .box('mdia', Mp4Parser.children)
        .fullBox('mdhd', (box) => {
          goog.asserts.assert(
              box.version != null,
              'MDHD is a full box and should have a valid version.');
          const parsedMDHDBox = shaka.util.Mp4BoxParsers.parseMDHD(
              box.reader, box.version);
          timescales.push(parsedMDHDBox.timescale);
        })
        .box('minf', Mp4Parser.children)
        .box('stbl', Mp4Parser.children)
        .fullBox('stsd', Mp4Parser.sampleDescription)

        // These are the various boxes that signal a codec.
        // Use these to set bistreamFormat_.
        .box('avc1', bitstreamFormatSetter(BitstreamFormat.H264))
        .box('avc3', bitstreamFormatSetter(BitstreamFormat.H264))
        .box('hev1', bitstreamFormatSetter(BitstreamFormat.H265))
        .box('hvc1', bitstreamFormatSetter(BitstreamFormat.H265))
        // Dobly vision is also H265.
        .box('dvh1', bitstreamFormatSetter(BitstreamFormat.H265))
        .box('dvhe', bitstreamFormatSetter(BitstreamFormat.H265))

        .parse(initSegment, /* partialOkay= */ true);

    // At least one track should exist, and each track should have a
    // corresponding Id in TKHD box, and timescale in its MDHD box
    if (!trackIds.length|| !timescales.length ||
      trackIds.length != timescales.length) {
      throw new shaka.util.Error(
          shaka.util.Error.Severity.CRITICAL,
          shaka.util.Error.Category.TEXT,
          shaka.util.Error.Code.INVALID_MP4_CEA);
    }

    if (this.bitstreamFormat_ == BitstreamFormat.UNKNOWN) {
      shaka.log.alwaysWarn(
          'Unable to determine bitstream format for CEA parsing!');
    }

    // Populate the map from track Id to timescale
    trackIds.forEach((trackId, idx) => {
      this.trackIdToTimescale_.set(trackId, timescales[idx]);
    });
  }

  /**
   * Parses each video segment. In fragmented MP4s, MOOF and MDAT come in
   * pairs. The following logic gets the necessary info from MOOFs to parse
   * MDATs (base media decode time, sample sizes/offsets/durations, etc),
   * and then parses the MDAT boxes for CEA-708 packets using this information.
   * CEA-708 packets are returned in the callback.
   * @override
   */
  parse(mediaSegment) {
    const Mp4Parser = shaka.util.Mp4Parser;
    const BitstreamFormat = shaka.cea.Mp4CeaParser.BitstreamFormat;

    if (this.bitstreamFormat_ == BitstreamFormat.UNKNOWN) {
      // We don't know how to extract SEI from this.
      return [];
    }

    /** @type {!Array<!shaka.cea.ICeaParser.CaptionPacket>} **/
    const captionPackets = [];

    // Fields that are found in MOOF boxes
    let defaultSampleDuration = this.defaultSampleDuration_;
    let defaultSampleSize = this.defaultSampleSize_;
    let sampleData = [];
    let moofOffset = null;
    let trunOffset = null;
    let baseMediaDecodeTime = null;
    let timescale = shaka.cea.ICeaParser.DEFAULT_TIMESCALE_VALUE;

    new Mp4Parser()
        .box('moof', (box) => {
          moofOffset = box.start;
          Mp4Parser.children(box);
        })
        .box('traf', Mp4Parser.children)
        .fullBox('trun', (box) => {
          goog.asserts.assert(
              box.version != null && box.flags!=null,
              'TRUN is a full box and should have a valid version & flags.');

          const parsedTRUN = shaka.util.Mp4BoxParsers.parseTRUN(
              box.reader, box.version, box.flags);

          sampleData = parsedTRUN.sampleData;
          trunOffset = parsedTRUN.dataOffset;
        })

        .fullBox('tfhd', (box) => {
          goog.asserts.assert(
              box.flags != null,
              'TFHD is a full box and should have valid flags.');

          const parsedTFHD = shaka.util.Mp4BoxParsers.parseTFHD(
              box.reader, box.flags);

          // If specified, defaultSampleDuration and defaultSampleSize
          // override the ones specified in the TREX box
          defaultSampleDuration = parsedTFHD.defaultSampleDuration ||
              this.defaultSampleDuration_;

          defaultSampleSize = parsedTFHD.defaultSampleSize ||
              this.defaultSampleSize_;

          const trackId = parsedTFHD.trackId;

          // Get the timescale from the track Id
          if (this.trackIdToTimescale_.has(trackId)) {
            timescale = this.trackIdToTimescale_.get(trackId);
          }
        })

        .fullBox('tfdt', (box) => {
          goog.asserts.assert(
              box.version != null,
              'TFDT is a full box and should have a valid version.');

          const parsedTFDT = shaka.util.Mp4BoxParsers.parseTFDT(
              box.reader, box.version);

          baseMediaDecodeTime = parsedTFDT.baseMediaDecodeTime;
        })
        .box('mdat', (box) => {
          if (baseMediaDecodeTime === null) {
            // This field should have been populated by
            // the Base Media Decode time in the TFDT box
            throw new shaka.util.Error(
                shaka.util.Error.Severity.CRITICAL,
                shaka.util.Error.Category.TEXT,
                shaka.util.Error.Code.INVALID_MP4_CEA);
          }
          const offset = (moofOffset || 0) + (trunOffset || 0) - box.start - 8;
          this.parseMdat_(box.reader, baseMediaDecodeTime, timescale,
              defaultSampleDuration, defaultSampleSize, offset, sampleData,
              captionPackets);
        })
        .parse(mediaSegment, /* partialOkay= */ false);

    return captionPackets;
  }

  /**
   * Parse MDAT box.
   * @param {!shaka.util.DataViewReader} reader
   * @param {number} time
   * @param {number} timescale
   * @param {number} defaultSampleDuration
   * @param {number} defaultSampleSize
   * @param {number} offset
   * @param {!Array<shaka.util.ParsedTRUNSample>} sampleData
   * @param {!Array<!shaka.cea.ICeaParser.CaptionPacket>} captionPackets
   * @private
   */
  parseMdat_(reader, time, timescale, defaultSampleDuration,
      defaultSampleSize, offset, sampleData, captionPackets) {
    const BitstreamFormat = shaka.cea.Mp4CeaParser.BitstreamFormat;
    const ICeaParser = shaka.cea.ICeaParser;
    let sampleIndex = 0;

    // The fields in each ParsedTRUNSample contained in the sampleData
    // array are nullable. In the case of sample data and sample duration,
    // we use the defaults provided by the TREX/TFHD boxes. For sample
    // composition time offset, we default to 0.
    let sampleSize = defaultSampleSize;

    if (sampleData.length) {
      sampleSize = sampleData[0].sampleSize || defaultSampleSize;
    }

    reader.skip(offset);

    while (reader.hasMoreData()) {
      const naluSize = reader.readUint32();
      const naluHeader = reader.readUint8();
      let naluType = null;
      let isSeiMessage = false;

      goog.asserts.assert(this.bitstreamFormat_ != BitstreamFormat.UNKNOWN,
          'Bitstream format should have been checked before now!');
      switch (this.bitstreamFormat_) {
        case BitstreamFormat.H264:
          naluType = naluHeader & 0x1f;
          isSeiMessage = naluType == ICeaParser.H264_NALU_TYPE_SEI;
          break;

        case BitstreamFormat.H265:
          naluType = (naluHeader >> 1) & 0x3f;
          isSeiMessage =
              naluType == ICeaParser.H265_PREFIX_NALU_TYPE_SEI ||
              naluType == ICeaParser.H265_SUFFIX_NALU_TYPE_SEI;
          break;

        default:
          return;
      }

      if (isSeiMessage) {
        let timeOffset = 0;

        if (sampleData.length > sampleIndex) {
          timeOffset = sampleData[sampleIndex].sampleCompositionTimeOffset || 0;
        }

        const pts = (time + timeOffset)/timescale;
        for (const packet of this.seiProcessor_
            .process(reader.readBytes(naluSize - 1))) {
          captionPackets.push({
            packet,
            pts,
          });
        }
      } else {
        try {
          reader.skip(naluSize - 1);
        } catch (e) {
          // It is necessary to ignore this error because it can break the start
          // of playback even if the user does not want to see the subtitles.
          break;
        }
      }
      sampleSize -= (naluSize + 4);
      if (sampleSize == 0) {
        if (sampleData.length > sampleIndex) {
          time += sampleData[sampleIndex].sampleDuration ||
              defaultSampleDuration;
        } else {
          time += defaultSampleDuration;
        }

        sampleIndex++;

        if (sampleData.length > sampleIndex) {
          sampleSize = sampleData[sampleIndex].sampleSize || defaultSampleSize;
        } else {
          sampleSize = defaultSampleSize;
        }
      }
    }
  }
};

/** @enum {number} */
shaka.cea.Mp4CeaParser.BitstreamFormat = {
  UNKNOWN: 0,
  H264: 1,
  H265: 2,
};


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**attempt** | [**AttemptRequestBody**](AttemptRequestBody.md) |  | [optional]
**daily_refresh** | **bool** | whether the connection should be automatically refreshed by Salt Edge. | [optional]
**include_fake_providers** | **bool** | if sent as `true`, the customers of [live](/general/#live) clients will be able to connect [fake providers](#providers-fake). | [optional]
**categorization** | **str** | the type of categorization applied. | [optional] [default to 'personal']

[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)


text:
<?php

namespace Nocks\SDK\Model;

/**
 * Class TradeMarket
 *
 * @method string getCode()
 * @method Currency getLast()
 * @method Currency getVolume()
 * @method Currency getLow()
 * @method Currency getHigh()
 * @method Currency getBuy()
 * @method Currency getSell()
 * @method Currency getResource()
 *
 * @package Nocks\SDK\Model
 */
class TradeMarket extends Model {

	/**
	 * @return bool
	 */
	public function isActive() {
		return (bool) $this->is_active;
	}
}


text:
//
//  GameHUD.m
//  Cocos2D Build a Tower Defense Game
//
//  Created by jack on 13-7-9.
//  Copyright (c) 2013年 jack. All rights reserved.
//

#import "GameHUD.h"
#import "DataModel.h"

#import "MainScene.h"
#import "LevelResult.h"
#import "GameData.h"
@implementation GameHUD
@synthesize baseHp = baseHp;
@synthesize resources = resources;
//@synthesize baseHpPercentage = baseHpPercentage;
@synthesize movableSprites = movableSprites;
@synthesize towerBase = towerBase;
int waveCount;

//**
bool resetGameHUD;
//**

static GameHUD *_sharedHUD = nil;

+ (GameHUD *)sharedHUD
{
	@synchronized([GameHUD class])
	{
		if (!_sharedHUD)
			[[self alloc] init];
		return _sharedHUD;
	}
	// to avoid compiler warning
	return nil;
}

+(id)alloc
{
	@synchronized([GameHUD class])
	{
		NSAssert(_sharedHUD == nil, @"Attempted to allocate a second instance of a singleton.");
		_sharedHUD = [super alloc];
		return _sharedHUD;
	}
	// to avoid compiler warning
	return nil;
}

-(id) init
{
	if ((self=[super init]) ) {

		CGSize winSize = [CCDirector sharedDirector].winSize;

        [CCTexture2D setDefaultAlphaPixelFormat:kCCTexture2DPixelFormat_RGB565];
       /* background = [CCSprite spriteWithFile:@"game_hud.png"];
        background.anchorPoint = ccp(0,0);
        [self addChild:background];*/
        float h=winSize.height;
        float w=winSize.width;
        CCLOG(@"/*/*/*/*/*//*/*-----h %f     w %f",h,w);
        [CCTexture2D setDefaultAlphaPixelFormat:kCCTexture2DPixelFormat_Default];

        movableSprites = [[NSMutableArray alloc] init];
        towerBase = [[NSMutableArray alloc] init];
        NSArray *images = [NSArray arrayWithObjects:@"danpao1.png", @"jiansu1.png", @"shuangpao1.png", @"sanpao1.png",@"wudi1.png",nil];
        NSArray *images2 = [NSArray arrayWithObjects:@"danpaojizuo.png",@"jiansujizuo.png",@"shuangpaojizuo.png",@"sanpaojizuo.png",@"wudijizuo.png", nil];
        for(int i = 0; i < images.count; ++i) {
            NSString *image = [images objectAtIndex:i];
            NSString *image2 = [images2 objectAtIndex:i];
            //objectAtIndex 只适用于集合(数组)。可根据索引获取对象
            CCSprite *sprite = [CCSprite spriteWithFile:image];
            CCSprite *sprite2 = [CCSprite spriteWithFile:image2];
            float offsetFraction = ((float)(i+1))/(images.count+1);
            sprite.position = ccp(winSize.width*offsetFraction, 35);
            float offsetFraction2 = ((float)(i+1))/(images.count+1);
            sprite2.position = ccp(winSize.width*offsetFraction2, 35);

            sprite.tag = i+1;//屏幕下方的基座炮塔tag值,设定为1~5
            sprite2.tag = i+1;//这里是炮塔的基座,tag也设定为1~5
            printf("tag %i", sprite.tag);
            [self addChild:sprite z:2];
            [self addChild:sprite2 z:1];
            [movableSprites addObject:sprite];
            [towerBase addObject:sprite2];
            //设置塔的价格
            CCLabelTTF *towerCost = [CCLabelTTF labelWithString:@"$" fontName:@"Marker Felt" fontSize:10];
            towerCost.position = ccp(winSize.width*offsetFraction, 15);
            towerCost.color = ccc3(0, 0, 0);
            [self addChild:towerCost z:1];

            //Set cost values
            switch (i) {
                case 0:
                    [towerCost setString:[NSString stringWithFormat:@"$ 25"]];
                    break;
                case 1:
                    [towerCost setString:[NSString stringWithFormat:@"$ 35"]];
                    break;
                case 2:
                    [towerCost setString:[NSString stringWithFormat:@"$ 65"]];
                    break;
                case 3:
                    [towerCost setString:[NSString stringWithFormat:@"$ 75"]];
                    break;
                case 4:
                    [towerCost setString:[NSString stringWithFormat:@"$ 150"]];
                    break;
                default:
                    break;
            }
        }

        // Set up Resources and Resource label
        resources = 100;
        self->resourceLabel = [CCLabelTTF labelWithString:@"Money $100" dimensions:CGSizeMake(150, 25) hAlignment:NSTextAlignmentRight fontName:@"Marker Felt" fontSize:20];
        resourceLabel.position = ccp(30, (winSize.height - 15));
        resourceLabel.color = ccc3(255,80,20);
        [self addChild:resourceLabel z:1];

        // Set up BaseHplabel
        baseHp = 10;
        baseHpLabel = [CCLabelTTF labelWithString:@"Base Health 10" dimensions:CGSizeMake(150, 25) hAlignment:NSTextAlignmentRight fontName:@"Marker Felt" fontSize:20];
        baseHpLabel.position = ccp((winSize.width - 185), (winSize.height - 15));
        baseHpLabel.color = ccc3(255,80,20);
        [self addChild:baseHpLabel z:1];

        // Set up wavecount label
        waveCount = 1;
        int WCount;
        if ([GameData sharedData].selectedLevel == 1) {

            WCount = [GameData sharedData].level1Wave;

        }else if ([GameData sharedData].selectedLevel == 2) {

            WCount = [GameData sharedData].level2Wave;

        }else if ([GameData sharedData].selectedLevel == 3) {

            WCount = [GameData sharedData].level3Wave;

        }else if ([GameData sharedData].selectedLevel == 4) {

            WCount = [GameData sharedData].level4Wave;

        }else if ([GameData sharedData].selectedLevel == 5) {
            WCount = [GameData sharedData].level5Wave;
        }

        if ([GameData sharedData].selectedChapter == 3) {
            CCLOG(@"wowowow");
            NSString *normal = [NSString stringWithFormat:@"Wave %i",waveCount];
            self->waveCountLabel = [CCLabelTTF labelWithString:normal dimensions:CGSizeMake(150, 25) hAlignment:NSTextAlignmentRight fontName:@"Marker Felt" fontSize:20];
        }else{
            NSString *normal = [NSString stringWithFormat:@"Wave %i / %i",waveCount,WCount];
            self->waveCountLabel = [CCLabelTTF labelWithString:normal dimensions:CGSizeMake(150, 25) hAlignment:NSTextAlignmentRight fontName:@"Marker Felt" fontSize:20];
        }

        //self->waveCountLabel = [CCLabelTTF labelWithString:@"Wave 1/5" dimensions:CGSizeMake(150, 25) hAlignment:NSTextAlignmentRight fontName:@"Marker Felt" fontSize:20];
        waveCountLabel.position = ccp(((winSize.width/2) - 80), (winSize.height - 15));
        waveCountLabel.color = ccc3(100,0,100);
        [self addChild:waveCountLabel z:1];

        //***
        //[[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:NO];
        [[[CCDirector sharedDirector]touchDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:NO];
        //***
        [self schedule:@selector(update:)];

        resetGameHUD = NO;
        //***

	}

    return self;
}

//***
+(void) resetGameHUD
{

    resetGameHUD = YES;

}
-(void) resetGameHUDLayer
{
    resetGameHUD = NO;
     baseHp = 10;
    [baseHpLabel setString:[NSString stringWithFormat:@"Base Health 10"]];
    waveCount = 1;
    int WCount;
    if ([GameData sharedData].selectedLevel == 1) {

        WCount = [GameData sharedData].level1Wave;

    }else if ([GameData sharedData].selectedLevel == 2) {

        WCount = [GameData sharedData].level2Wave;

    }else if ([GameData sharedData].selectedLevel == 3) {

        WCount = [GameData sharedData].level3Wave;

    }else if ([GameData sharedData].selectedLevel == 4) {

        WCount = [GameData sharedData].level4Wave;

    }else if ([GameData sharedData].selectedLevel == 5) {
        WCount = [GameData sharedData].level5Wave;
    }

    if ([GameData sharedData].selectedChapter == 3) {
        [waveCountLabel setString:[NSString stringWithFormat: @"Wave %i",waveCount]];
    }else{
        NSString *normal = [NSString stringWithFormat:@"Wave %i / %i",waveCount,WCount];
        [waveCountLabel setString:[NSString stringWithFormat: normal,waveCount]];
    }

    //[waveCountLabel setString:[NSString stringWithFormat: @"Wave 1/5"]];
    resources = 100;
    [resourceLabel setString:[NSString stringWithFormat: @"Money $%i",resources]];
}

-(void) update:(ccTime) dt{

    if (resetGameHUD == YES) {

        CCLOG(@"我3");
        [self resetGameHUDLayer];
    }

}

//***

-(void) updateBaseHp:(int)amount{
    baseHp += amount;
    [self->baseHpLabel setString:[NSString stringWithFormat: @"baseHp %i",baseHp]];
    /* if (baseHpPercentage <= 25) {
        [self->healthBar setSprite:[CCSprite spriteWithFile:@"health_bar_red.png"]];
        [self->healthBar setScale:0.5];

    }*/

    if (baseHp <= 0) {
        //Game Over Scenario

        CCTransitionFade *trans = [CCTransitionSlideInR transitionWithDuration:0.2f scene:[LevelResult scene]];
        [[CCDirector sharedDirector]replaceScene:trans];

        //Implement Game Over Scenario
    }

  //  [self->healthBar setPercentage:baseHpPercentage];
}

-(void) updateResources:(int)amount{
    resources += amount;
    [self->resourceLabel setString:[NSString stringWithFormat: @"Money $%i",resources]];
}

/*-(void) updateResourcesNom{
    resources += 1;
    [self->resourceLabel setString:[NSString stringWithFormat: @"Money $%i",resources]];
}*/
-(void) updateWaveCount{
    waveCount++;
    int WCount;
    if ([GameData sharedData].selectedLevel == 1) {

        WCount = [GameData sharedData].level1Wave;

    }else if ([GameData sharedData].selectedLevel == 2) {

        WCount = [GameData sharedData].level2Wave;

    }else if ([GameData sharedData].selectedLevel == 3) {

        WCount = [GameData sharedData].level3Wave;

    }else if ([GameData sharedData].selectedLevel == 4) {

        WCount = [GameData sharedData].level4Wave;

    }else if ([GameData sharedData].selectedLevel == 5) {
        WCount = [GameData sharedData].level5Wave;
    }

    if ([GameData sharedData].selectedChapter == 3) {
        [self->waveCountLabel setString:[NSString stringWithFormat: @"Wave %i",waveCount]];
    }else{
        NSString *normal = [NSString stringWithFormat:@"Wave %i / %i",waveCount,WCount];
        [self->waveCountLabel setString:[NSString stringWithFormat: normal,waveCount]];
    }
}
/*void HelloWorld::ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent){
 CCTouch *touch = (CCTouch *)pTouches->anyObject();
 CCPoint beginLoc = touch->locationInView();
 beginLoc = CCDirector::sharedDirector()->convertToGL(beginLoc);

 CCRect rect = pSprite1->boundingBox();          //得到精灵的矩形框
 int x = rect.origin.x;                          //得到矩形框的左下角x坐标
 int y = rect.origin.y;                          //得到矩形框的左下角x坐标
 int w = rect.size.width;                        //得到矩形框的宽
 int h = rect.size.height;                       //得到矩形框的高

 rect = CCRect(210, 130, 20, 20);                //重新设置精灵的矩形框x坐标为210,Y坐标为130,宽w为20,高h为20
 CCLog("%d==%d==%d==%d",x,y,w,h);
 if(CCRect::CCRectContainsPoint(rect, beginLoc)){
 plabel1->setVisible(true);
 }
 } */

- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
   //NSLog(@"touch");
    //CGPoint touchLocation = [self convertTouchToNodeSpace:touch];

    CGPoint touchLocation=[touch locationInView:[touch view]];
    touchLocation=[[CCDirector sharedDirector]convertToGL:touchLocation];
    touchLocation=[self convertToNodeSpace:touchLocation];
    CCSprite * newSprite = nil;
    CCSprite * newSprite2 = nil;
    for (CCSprite *sprite in movableSprites) {
        for(CCSprite *sprite2 in towerBase){
            if (CGRectContainsPoint(sprite.boundingBox, touchLocation)&&CGRectContainsPoint(sprite2.boundingBox, touchLocation)) {
                [[SimpleAudioEngine sharedEngine]playEffect:@"sound.caf"];

			DataModel *m = [DataModel getModel];
			m._gestureRecognizer.enabled = NO;

			selSpriteRange = [CCSprite spriteWithFile:@"Range.png"];
			selSpriteRange.scale = 2.1;
			[self addChild:selSpriteRange z:-1];
			selSpriteRange.position = sprite.position;

            newSprite = [CCSprite spriteWithTexture:[sprite texture]]; //sprite;
            newSprite2 = [CCSprite spriteWithTexture:[sprite2 texture]];
			newSprite.position = sprite.position;
            newSprite2.position = sprite2 .position;
			selSprite = newSprite;
            selSprite2 = newSprite2;
            selSprite.tag = sprite.tag;
            selSprite2.tag = sprite2.tag;
			[self addChild:newSprite z:2];
            [self addChild:newSprite2 z:1];

            break;
        }
    }
    }
    if (CGRectContainsPoint(selSprite.boundingBox, touchLocation)){
        CCLOG(@"touch");

    }
        return YES;
}

- (void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event {
    CGPoint touchLocation = [self convertTouchToNodeSpace:touch];

    CGPoint oldTouchLocation = [touch previousLocationInView:touch.view];
    oldTouchLocation = [[CCDirector sharedDirector] convertToGL:oldTouchLocation];
    oldTouchLocation = [self convertToNodeSpace:oldTouchLocation];

    CGPoint translation = ccpSub(touchLocation, oldTouchLocation);

	if (selSprite&&selSprite2) {
		CGPoint newPos = ccpAdd(selSprite.position, translation);
        CGPoint newPos2 = ccpAdd(selSprite2.position,translation);
        selSprite.position = newPos;
        selSprite2.position = newPos;
		selSpriteRange.position = newPos;

		DataModel *m = [DataModel getModel];
        if ([GameData sharedData].selectedChapter != 2) {
            CGPoint touchLocationInGameLayer = [m._gameLayer convertTouchToNodeSpace:touch];

            BOOL isBuildable = [m._gameLayer canBuildOnTilePosition: touchLocationInGameLayer];
            if (isBuildable) {
                [selSpriteRange setColor:ccc3(0, 225, 0)];
                selSpriteRange.opacity = 255;
            } else {
                [selSpriteRange setColor:ccc3(225, 0, 0)];
                selSpriteRange.opacity = 255;
            }
        }
    }
}

- (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event {
    //NSLog(@"touching");
	CGPoint touchLocation = [self convertTouchToNodeSpace:touch];
	DataModel *m = [DataModel getModel];

	if (selSprite) {
		CGRect backgroundRect = CGRectMake(background.position.x,
									   background.position.y,
									   background.contentSize.width,
									   background.contentSize.height);

		if (!CGRectContainsPoint(backgroundRect, touchLocation)) {
			CGPoint touchLocationInGameLayer = [m._gameLayer convertTouchToNodeSpace:touch];
            //float x=touchLocationInGameLayer.x * 2;
            //float y=touchLocationInGameLayer.y * 2;
            //CGPoint touc=ccp(x, y);
			[m._gameLayer addTower:touchLocationInGameLayer :selSprite.tag];
            BOOL isBuildable = [m._gameLayer canBuildOnTilePosition: touchLocationInGameLayer];
            if (isBuildable) {
                [[SimpleAudioEngine sharedEngine]playEffect:@"sound.caf"];
            }else{
                [[SimpleAudioEngine sharedEngine]playEffect:@"unable.mp3"];
            }
            //[m._gameLayer addTower:touchLocationInGameLayer :selSprite2.tag];
		}
		//获取当前所选炮塔的类型,并将其传递给TutorialScene类中的addTower方法
        [self removeChild:selSprite cleanup:YES];
        [self removeChild:selSprite2 cleanup:YES];
		selSprite = nil;
        selSprite2 = nil;
		[self removeChild:selSpriteRange cleanup:YES];
		selSpriteRange = nil;
	}

	m._gestureRecognizer.enabled = YES;
}

- (void) registerWithTouchDispatcher
{
	[[[CCDirector sharedDirector]touchDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:NO];
}

// on "dealloc" you need to release all your retained objects
- (void) dealloc
{
	[movableSprites release];
    [towerBase release];
    towerBase = nil;
    movableSprites = nil;
	[super dealloc];
}

@end


text:
/**
 * Module dependencies.
 */

var Emitter = require('events').EventEmitter;

/**
 * Module exports.
 */

module.exports = Adapter;

/**
 * Memory adapter constructor.
 *
 * @param {Namespace} nsp
 * @api public
 */

function Adapter(nsp){
  this.nsp = nsp;
  this.rooms = {};
  this.sids = {};
}

/**
 * Inherits from `EventEmitter`.
 */

Adapter.prototype.__proto__ = Emitter.prototype;

/**
 * Adds a socket from a room.
 *
 * @param {String} socket id
 * @param {String} room name
 * @param {Function} callback
 * @api public
 */

Adapter.prototype.add = function(id, room, fn){
	(this.sids[id] || {})[room] = true;
	(this.rooms[room] = this.rooms[room] || {})[id] = true;
	if (fn) process.nextTick(fn.bind(null, null));
};

/**
 * Removes a socket from a room.
 *
 * @param {String} socket id
 * @param {String} room name
 * @param {Function} callback
 * @api public
 */

Adapter.prototype.del = function(id, room, fn){
	var _sid;
	if (_sid = this.sids[id])
		delete _sid[room];
	this._delFromRoom(id, room);
	if (fn) process.nextTick(fn.bind(null, null));
};

/**
 * Removes the socket from the specified room
 *
 * @param {String} socket id
 * @param {String} room name
 * @returns {undefined}
 */
Adapter.prototype._delFromRoom = function(id, room) {
	var _room;
	if (_room = this.rooms[room]) {
		delete _room[id];
		// Deletes the room when no one is using it
		// If we don't, this is a potential memory leak
		if (!Object.keys(_room).length)
			delete this.rooms[room];
	}
};

/**
 * Removes a socket from all rooms it's joined.
 *
 * @param {String} socket id
 * @api public
 */

Adapter.prototype.delAll = function(id, fn){
	var rooms = this.sids[id];
	if (rooms) {
		for (var room in rooms) {
			_delFromRoom(id, room);
		}
	}
	delete this.sids[id];
};

/**
 * Broadcasts a packet.
 *
 * Options:
 *  - `flags` {Object} flags for this packet
 *  - `except` {Array} sids that should be excluded
 *  - `rooms` {Array} list of rooms to broadcast to
 *
 * @param {Object} packet object
 * @api public
 */

Adapter.prototype.broadcast = function(packet, opts){
  var rooms = opts.rooms || [];
  var except = opts.except || [];
  var ids = {};
  var socket;

  if (rooms.length) {
    for (var i = 0; i < rooms.length; i++) {
      var room = this.rooms[rooms[i]];
      if (!room) continue;
      for (var id in room) {
        if (ids[id] || ~except.indexOf(id)) continue;
        socket = this.nsp.connected[id];
        if (socket) {
          socket.packet(packet);
          ids[id] = true;
        }
      }
    }
  } else {
    for (var id in this.sids) {
      if (~except.indexOf(id)) continue;
      socket = this.nsp.connected[id];
      if (socket) socket.packet(packet);
    }
  }
};


text:
const React = require('react')
const Backbone = require('backbone')
const ACTIONS = require('./actions')

const PaymentsView = React.createClass({

   _handlePaymentSubmission: function(evt){
   evt.preventDefault()
   //console.log(this)

   let newPaymentData = {
      name: this.refs.name.value,
      income: this.refs.income.value,
      rent: this.refs.rent.value,
      utilities: this.refs.utilities.value,
      other: this.refs.other.value
   }
   console.log(newPaymentData)
   ACTIONS.submitNewBudget(newPaymentData)
},
   render: function() {
      return (

               <form className="form-group grid-container" onSubmit={this._handlePaymentSubmission}>

Budget name

(This is what you are saving money for.)

                        <input className="payment-inputs" ref={'name'} type="text" name="name"/>

Income

(This is your income for one month.)

                        <input className="payment-inputs" ref={'income'} type="text" name="name"/>

Housing

(Here you should put your housing expenses for month.)

                        <input className="payment-inputs" ref={'rent'} type="text" name="name"/>

Utilities

                        <input className="payment-inputs" ref={'utilities'} type="text" name="name"/>

Other

(Misc. expenses)

                        <input className="payment-inputs" ref={'other'} type="text" name="name"/>

                        <input type="submit" className="btn btn-default" value="Oven!" />

               </form>

      )
   }
})

module.exports = PaymentsView


text:
package com.peertopark.java.validators;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;

/**
 *
 * @author hector
 */
public class PasswordValidatorTest {

    public PasswordValidatorTest() {
    }

    @BeforeClass
    public static void setUpClass() {
    }

    @AfterClass
    public static void tearDownClass() {
    }

    @Before
    public void setUp() {
    }

    @After
    public void tearDown() {
    }

    @Test
    public void testValidatePassword() {
        assertTrue(PasswordValidator.validate("12345678"));
        assertFalse(PasswordValidator.validate("asdf"));
        assertTrue(PasswordValidator.validate("012345678901234"));
        assertFalse(PasswordValidator.validate("0123456789012345"));
        assertTrue(PasswordValidator.validate("1234asdf"));
        assertFalse(PasswordValidator.validate("1234añçf"));

        PasswordValidator.setPasswordMinLength(2);
        PasswordValidator.setPasswordMaxLength(20);
        PasswordValidator.setPasswordRegex(".");
        assertTrue(PasswordValidator.validate("12345678"));
        assertTrue(PasswordValidator.validate("123"));
        assertFalse(PasswordValidator.validate("a"));
        assertTrue(PasswordValidator.validate("añ/|"));
    }

}