text:
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
**Table of Contents**  *generated with [DocToc](https://github.com/thlorenz/doctoc)*

- [9.1 Reading Command-Line Options](#91-reading-command-line-options)
- [9.2 Environment Variables](#92-environment-variables)
- [9.3 Files and File Objects](#93-files-and-file-objects)
- [9.4 Standard Input, Output, and Error](#94-standard-input-output-and-error)
- [9.5 The `print` Statement](#95-the-print-statement)
- [9.6 The `print()` Function](#96-the-print-function)
- [9.7 Variable Interpolation in Text Output](#97-variable-interpolation-in-text-output)
- [9.8 Generating Output](#98-generating-output)
- [9.9 Unicode String Handling](#99-unicode-string-handling)
- [9.10 Unicode I/O](#910-unicode-io)
- [9.11 Unicode Character Properties](#911-unicode-character-properties)
- [9.12 Object Persistence and the `pickle` Module](#912-object-persistence-and-the-pickle-module)
- [导航](#%E5%AF%BC%E8%88%AA)

<!-- END doctoc generated TOC please keep comment here to allow auto update -->

# 9.1 Reading Command-Line Options

When Python starts, command-line options are placed in the list `sys.argv`.The first element is the name of the program.

```python
import sys
if len(sys.argv) != 3:
    sys.stderr.write("Usage : python %s inputfile outputfile\n" % sys.argv[0])
    raise SystemExit(1)
inputfile = sys.argv[1]
outputfile = sys.argv[2]
```

Raising `SystemExit` with a non-zero exit code is standard practice for reporting usage errors in command-line tools.

Use theUoptparse module for more complicated command-line handling.

```python
import optparse
p = optparse.OptionParser()
# An option taking an argument
p.add_option("-o",action="store",dest="outfile")
p.add_option("--output",action="store",dest="outfile")
# An option that sets a boolean flag
p.add_option("-d",action="store_true",dest="debug")
p.add_option("--debug",action="store_true",dest="debug")
# Set default values for selected options
p.set_defaults(debug=False)
# Parse the command line
opts, args = p.parse_args()
# Retrieve the option settings
outfile = opts.outfile
debugmode = opts.debug
```

Parsing is performed using the `p.parse_args()` method.This method returns a 2-tuple `(opts, args)` where `opts` is an object containing the parsed option values and `args` is a list of items on the command line not parsed as options.

# 9.2 Environment Variables

Environment variables are accessed in the dictionary `os.environ`.

```python
import os
path = os.environ["PATH"]
user = os.environ["USER"]
editor = os.environ["EDITOR"]
```

To modify the environment variables, set the `os.environ` variable, `os.environ["FOO"] = "BAR"`.

Modifications to `os.environ` affect both the running program and subprocesses created by Python.

# 9.3 Files and File Objects

The built-in function `open(name, [, mode, [, bufsize]])` opens and creates a file object,

```python
f = open("foo") # Opens "foo" for reading
f = open("foo",'r') # Opens "foo" for reading (same as above)
f = open("foo",'w') # Open for writing
```

The file mode is 'r' for read, 'w' for write, or 'a' for append.These file modes assume text-mode and may implicitly perform translation of the newline character '\n'.

If you are working with binary data, append a 'b' to the file mode such as 'rb' or 'wb'.This disables newline translation and should be included if you are concerned about portability of code that processes binary data.

A file can be opened for in-place updates by supplying a plus (+) character, such as 'r+' or 'w+'.

If a file is opened with mode 'U' or 'rU', it provides universal newline support for reading.

The optional `bufsize` parameter controls the buffering behavior of the file, where 0 is unbuffered, 1 is line buffered, and a negative number requests the system default.Any other positive number indicates the approximate buffer size in bytes that will be used.

File Methods

| Method | Description |
| ------ | ----------- |
| f.read([n]) | Reads at most n bytes. |
| f.readline([n]) | Reads a single line of input up to n characters. If n is omitted, this method reads the entire line. |
| f.readlines([size]) | Reads all the lines and returns a list. size optionally specifies the approximate number of characters to read on the file before stopping. |
| f.write(s) | Writes string s. |
| f.writelines(lines) | Writes all strings in sequence lines. |
| f.close() | Closes the file. |
| f.tell() | Returns the current file pointer. |
| f.seek(offset [, whence]) | Seeks to a new file position. |
| f.isatty() | Returns 1 if f is an interactive terminal. |
| f.flush() | Flushes the output buffers. |
| f.truncate([size]) | Truncates the file to at most size bytes. |
| f.fileno() | Returns an integer file descriptor. |
| f.next() | Returns the next line or raises StopIteration. In Python 3, it is called `f.__next__()`. |

The `read()` method returns the entire file as a string unless an optional length parameter is given specifying the maximum number of characters. The `readline()` method returns the next line of input, including the terminating newline.

Both the `readline()` and `readlines()` methods are platform-aware and handle different representations of newlines properly.

`read()` and `readline()` indicate end-of-file (EOF) by returning an empty string.

```python
while True:
    line = f.readline()
    if not line: # EOF
        break
```

A convenient way to read all lines in a file is to use iteration with a `for` loop,

```python
for line in f: # Iterate over all lines in the file
    # Do sth
```

In Python 2, the various read operations always return 8-bit strings, regardless of the file mode that was specified (text or binary). In Python 3, these operations return Unicode strings if a file has been opened in text mode and byte strings if the file is opened in binary mode.

`write()` and `writelines()` do not add newline characters to the output, so all output that you produce should already include all necessary formatting.

File objects also have the read-only data attributes.

| Attribute | Description |
| --------- | ----------- |
| f.closed | Boolean value indicates the file state |
| f.mode | The I/O mode for the file |
| f.name | Name of the file if created using open(). Otherwise, it will be a string indicating the source of the file. |
| f.softspace | Boolean value indicating whether a space character needs to be printed before another value when using the print statement. |
| f.newlines | When a file is opened in universal newline mode, this attribute contains the newline representation actually found in the file. |
| f.encoding | A string that indicates file encoding |

# 9.4 Standard Input, Output, and Error

The interpreter provides three standard file objects, known as standard input, standard output, and standard error, which are available in the sys module as `sys.stdin`, `sys.stdout`, and `sys.stderr`.

`stdin` is a file object corresponding to the stream of input characters supplied to the interpreter. `stdout` is the file object that receives output produced by print. `stderr` is a file that receives error messages. More often than not, `stdin` is mapped to the user's keyboard, whereas `stdout` and `stderr` produce text onscreen.

The following code writes to standard output and reads a line of input from standard input:

```python
import sys
sys.stdout.write("Enter your name : ")
name = sys.stdin.readline()
```

Alternatively, the built-in function `raw_input(prompt)` can read a line of text from `stdin` and optionally print a prompt:

```python
name = raw_input("Enter your name : ")
```

Lines read by `raw_input()` do not include the trailing newline.This is different than reading directly from `sys.stdin` where newlines are included in the input text.

Keyboard interrupts (typically generated by Ctrl+C) result in a `KeyboardInterrupt` exception that can be caught using an exception handler.

# 9.5 The `print` Statement

Python 2 uses a special print statement to produce output on the file contained in `sys.stdout`.

```python
print "The values are", x, y, z
```

For each object, the `str()` function is invoked to produce an output string. These output strings are then joined and separated by **a single space** to produce the final output string.The output is terminated by a newline unless a trailing comma is supplied to the `print` statement. In this case, the next print statement will insert a space before printing more items.

```python
print "The values are ", x, y, z, w
# Print the same text, using two print statements
print "The values are ", x, y, # Omits trailing newline
print z, w # A space is printed before z
```

To produce formatted output, use the string-formatting operator (`%`) or the `.format()` method.

```python
print "The values are %d %7.5f %s" % (x,y,z) # Formatted I/O
print "The values are {0:d} {1:7.5f} {2}".format(x,y,z)
```

You can change the destination of the `print` statement by adding the special `>>file` modifier followed by a comma.

```python
f = open("output","w")
print >>f, "hello world"
f.close()
```

# 9.6 The `print()` Function

`print` is turned into a function in Python 3. To print a series of values separated by spaces, just supply them all to `print()` like this:

```python
print("The values are", x, y, z)
```

# 9.7 Variable Interpolation in Text Output

Many scripting languages such as Perl and PHP allow variables to be inserted into strings using dollar-variable substitutions (that is, `$name`, `$address`, and so on). Python provides no direct equivalent of this feature, but it can be emulated using formatted I/O combined with triple-quoted strings.

```python
form = """\
Dear {name},
Please send back my {item} or pay me {amount:0.2f}.
Sincerely yours,
Joe Python User
"""
print form.format(name='Mr. Bush', item='blender', amount=50.0)
```

For certain kinds of forms, you can also use `Template` strings, as follows:

```python
import string
form = string.Template("""\
Dear $name,
Please send back my $item or pay me $amount.
                                    Sincerely yours,
                                    Joe Python User
""")
print form.substitute({'name': 'Mr. Bush',
                        'item': 'blender',
                        'amount': "%0.2f" % 50.0})
```

# 9.8 Generating Output

Generator functions can also be used to emit an I/O stream as a sequence of data fragments. To do this, simply use the `yield` statement like you would use a `write()` or `print` statement.

```python
def countdown(n):
    while n > 0:
        yield "T-minus %d\n" % n
        n -= 1
    yield "Kaboom!\n"
```

If you wanted to route the above output to a file `f`, you could do this:

```python
count = countdown(5)
f.writelines(count)
```

# 9.9 Unicode String Handling

If you have a string s of raw bytes containing an encoded representation of a Unicode string, use the `s.decode([encoding [,errors]])` method to convert it into a proper Unicode string.To convert a Unicode
string, `u`, to an encoded byte string, use the string method `u.encode([encoding [, errors]])`.

The default encoding is set in the `site` module and can be queried using `sys.getdefaultencoding()`. In many cases, the default encoding is 'ascii'.

# 9.10 Unicode I/O

When working with Unicode strings, **it is never possible to directly write raw Unicode data to a file**. This is due to the fact that Unicode characters are internally represented as multibyte integers and that writing such integers directly to an output stream causes problems related to byte ordering.

The built-in `codecs` module contains a collection of functions for converting byte-oriented data to and from Unicode strings according to a variety of different data-encoding schemes.

```python
f = codecs.open('foo.txt','r','utf-8','strict') # Reading
g = codecs.open('bar.txt','w','utf-8') # Writing
```

If you already have a file object, the `codecs.EncodedFile(file, inputenc [, outputenc [, errors]])` function can be used to place an encoding wrapper around it.

```python
f = open("foo.txt","rb")
fenc = codecs.EncodedFile(f,'utf-8')
```

When the encoding is read from a document, code similar to the following can be used to turn the input file into an encoded stream:

```python
f = open("somefile","rb")
# Determine encoding of the file
...
# Put an appropriate encoding wrapper on the file.
# Assumes that the BOM (if any) has already been discarded
# by earlier statements.
fenc = codecs.EncodedFile(f,encoding)
data = fenc.read()
```

# 9.11 Unicode Character Properties

The `unicodedata` module provides access to a database of character properties. General character properties can be obtained with the `unicodedata.category(c)` function. `unicodedata.category(u"A")` returns 'Lu', signifying that the character is an uppercase letter.

Another tricky problem with Unicode strings is that there might be multiple representations of the same Unicode string.

# 9.12 Object Persistence and the `pickle` Module

The `pickle` module serializes an object into a stream of bytes that can be written to a file and later restored.

```python
import pickle
obj = SomeObject()
f = open(filename,'wb')
pickle.dump(obj, f) # Save object on f
f.close()
```

To restore the object, you can use the following code:

```python
import pickle
f = open(filename,'rb')
obj = pickle.load(f) # Restore the object
f.close()
```

The `shelve` module is similar to pickle but saves objects in a dictionary-like database:

```python
import shelve
obj = SomeObject()
db = shelve.open("filename") # Open a shelve
db['key'] = obj # Save object in the shelve
...
obj = db['key'] # Retrieve it
db.close()
```

Similarly, a `shelve` can be opened to save Python objects using an alternative `pickle` protocol like this:

```python
import shelve
db = shelve.open(filename,protocol=2)
```

# 导航

[目录](README.md)

上一章:[8、模块、包与分发](8、模块、包与分发.md)

下一章:[10、执行环境](10、执行环境.md)


text:
require 'test_helper'

describe "Fog::OpenStack::Network | subnet requests" do
  before do
    @subnet_format = {
      'id'               => String,
      'name'             => String,
      'network_id'       => String,
      'cidr'             => String,
      'ip_version'       => Integer,
      'gateway_ip'       => String,
      'allocation_pools' => Array,
      'dns_nameservers'  => Array,
      'host_routes'      => Array,
      'enable_dhcp'      => Fog::Boolean,
      'tenant_id'        => String
    }
  end

  describe "success" do
    before do
      network_id = 'net_id'
      cidr = '10.2.2.0/24'
      ip_version = 4
      attributes = {
        :name             => 'subnet_name',
        :gateway_ip       => '10.2.2.1',
        :allocation_pools => [],
        :dns_nameservers  => [],
        :host_routes      => [],
        :enable_dhcp      => true,
        :tenant_id        => 'tenant_id'
      }
      @subnet = network.create_subnet(network_id, cidr, ip_version, attributes).body
    end
    it "#create_subnet" do
      @subnet.must_match_schema('subnet' => @subnet_format)
    end

    it "#list_subnet" do
      network.list_subnets.body.must_match_schema('subnets' => [@subnet_format])
    end

    it "#get_subnet" do
      subnet_id = network.subnets.all.first.id
      network.get_subnet(subnet_id).body.must_match_schema('subnet' => @subnet_format)
    end

    it "#update_subnet" do
      subnet_id = network.subnets.all.first.id
      attributes = {
        :name             => 'subnet_name',
        :gateway_ip       => '10.2.2.1',
        :allocation_pools => [],
        :dns_nameservers  => [],
        :host_routes      => [],
        :enable_dhcp      => true
      }

      network.update_subnet(subnet_id, attributes).body.must_match_schema('subnet' => @subnet_format)
    end

    it "#delete_subnet" do
      subnet_id = network.subnets.all.first.id
      network.delete_subnet(subnet_id).status.must_equal 204
    end
  end

  describe "failure" do
    it "#get_subnet" do
      proc do
        network.get_subnet(0)
      end.must_raise Fog::OpenStack::Network::NotFound
    end

    it "#update_subnet" do
      proc do
        network.update_subnet(0, {})
      end.must_raise Fog::OpenStack::Network::NotFound
    end

    it "#delete_subnet" do
      proc do
        network.delete_subnet(0)
      end.must_raise Fog::OpenStack::Network::NotFound
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows.Forms;
using System.Windows.Input;
using mze9412.ScriptCompiler.Helpers;
using mze9412.ScriptCompiler.Properties;

namespace mze9412.ScriptCompiler.ViewModels
{
    /// <summary>
    /// Settings view model ;)
    /// </summary>
    public sealed class SettingsViewModel : INotifyPropertyChanged
    {
        private string _scriptCodeDirectory;
        private string _scriptOutputDirectory;
        private bool _copyScriptToClipboard;
        private bool _autoRefreshScripts;

        /// <summary>
        /// Ctor
        /// </summary>
        public SettingsViewModel()
        {
            ScriptCodeDirectory = Settings.Default.ScriptCodeDirectory;
            ScriptOutputDirectory = Settings.Default.ScriptOutputDirectory;
            CopyScriptToClipboard = Settings.Default.CopyScriptToClipboard;
            AutoRefreshScripts = Settings.Default.AutoRefreshScripts;

            SelectDirectoryCommand = new DelegateCommand(SelectDirectory);
        }

        /// <summary>
        /// Root directory where code is located
        /// </summary>
        public string ScriptCodeDirectory
        {
            get { return _scriptCodeDirectory; }
            set
            {
                _scriptCodeDirectory = value;
                Settings.Default.ScriptCodeDirectory = value;
                Settings.Default.Save();
                RaisePropertyChanged();
            }
        }

        /// <summary>
        /// Root directory where generated script code should be sent to
        /// </summary>
        public string ScriptOutputDirectory
        {
            get { return _scriptOutputDirectory; }
            set
            {
                _scriptOutputDirectory = value;
                Settings.Default.ScriptOutputDirectory = value;
                Settings.Default.Save();
                RaisePropertyChanged();
            }
        }

        /// <summary>
        /// If true, generated script is copied to clipboard
        /// </summary>
        public bool CopyScriptToClipboard
        {
            get { return _copyScriptToClipboard; }
            set
            {
                _copyScriptToClipboard = value;
                Settings.Default.CopyScriptToClipboard = value;
                Settings.Default.Save();
                RaisePropertyChanged();
            }
        }

        /// <summary>
        /// If true, refresh is triggered automatically
        /// </summary>
        public bool AutoRefreshScripts
        {
            get { return _autoRefreshScripts; }
            set
            {
                _autoRefreshScripts = value;
                Settings.Default.AutoRefreshScripts = value;
                Settings.Default.Save();
                RaisePropertyChanged();
            }
        }

        public ICommand SelectDirectoryCommand { get; set; }

        public void SelectDirectory(object argument)
        {
            bool isForOutputDirectory = (string) argument == "ScriptOutputDirectory";

            var rootFolder = isForOutputDirectory ? ScriptOutputDirectory : ScriptCodeDirectory;

            var dialog = new FolderBrowserDialog()
            {
                Description = isForOutputDirectory ? Resources.SelectFolder_OutputDirectory : Resources.SelectFolder_CodeDirectory,
                SelectedPath = rootFolder
            };
            var res = dialog.ShowDialog();
            if (res == DialogResult.OK)
            {
                if (isForOutputDirectory)
                {
                    ScriptOutputDirectory = dialog.SelectedPath;
                }
                else
                {
                    ScriptCodeDirectory = dialog.SelectedPath;
                }
            }
        }

        #region INotifyPropertyChanged

        public event PropertyChangedEventHandler PropertyChanged;

        private void RaisePropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        #endregion
    }
}


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

import static com.amazonaws.util.StringUtils.UTF8;
import static com.amazonaws.util.StringUtils.COMMA_SEPARATOR;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.regex.Pattern;

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

/**
 * LookupDeveloperIdentityRequest Marshaller
 */
public class LookupDeveloperIdentityRequestMarshaller
        implements
        Marshaller<Request<LookupDeveloperIdentityRequest>, LookupDeveloperIdentityRequest> {

    public Request<LookupDeveloperIdentityRequest> marshall(
            LookupDeveloperIdentityRequest lookupDeveloperIdentityRequest) {

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

        Request<LookupDeveloperIdentityRequest> request = new DefaultRequest<LookupDeveloperIdentityRequest>(
                lookupDeveloperIdentityRequest, "AmazonCognitoIdentity");
        request.addHeader("X-Amz-Target",
                "AWSCognitoIdentityService.LookupDeveloperIdentity");

        request.setHttpMethod(HttpMethodName.POST);

        request.setResourcePath("");

        try {
            final SdkJsonGenerator jsonGenerator = new SdkJsonGenerator();

            jsonGenerator.writeStartObject();

            if (lookupDeveloperIdentityRequest.getIdentityPoolId() != null) {
                jsonGenerator.writeFieldName("IdentityPoolId").writeValue(
                        lookupDeveloperIdentityRequest.getIdentityPoolId());
            }
            if (lookupDeveloperIdentityRequest.getIdentityId() != null) {
                jsonGenerator.writeFieldName("IdentityId").writeValue(
                        lookupDeveloperIdentityRequest.getIdentityId());
            }
            if (lookupDeveloperIdentityRequest.getDeveloperUserIdentifier() != null) {
                jsonGenerator.writeFieldName("DeveloperUserIdentifier")
                        .writeValue(
                                lookupDeveloperIdentityRequest
                                        .getDeveloperUserIdentifier());
            }
            if (lookupDeveloperIdentityRequest.getMaxResults() != null) {
                jsonGenerator.writeFieldName("MaxResults").writeValue(
                        lookupDeveloperIdentityRequest.getMaxResults());
            }
            if (lookupDeveloperIdentityRequest.getNextToken() != null) {
                jsonGenerator.writeFieldName("NextToken").writeValue(
                        lookupDeveloperIdentityRequest.getNextToken());
            }

            jsonGenerator.writeEndObject();

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

        return request;
    }

}


text:
Track chunks begin with four bytes spelling out "MTrk", followed by the length
in bytes of the track (see readvariablelength in util.jl), followed by a sequence
of events.
=#
type MIDITrack
    events::Array{TrackEvent, 1}

    MIDITrack() = new(TrackEvent[])
    MIDITrack(events) = new(events)
end

function readtrack(f::IO)
    mtrk = join(map(Char, read(f, UInt8, 4)))
    if mtrk != MTRK
        error("Not a valid MIDI file. Expected MTrk, got $(mtrk) starting at byte $(hex(position(f)-4, 2))")
    end
    track = MIDITrack()

    # Get the length in bytes of the track
    tracklength = ntoh(read(f, UInt32))

    trackstart = position(f)
    bytesread = 0
    laststatus = UInt8(0) # Keeps track of running status
    while bytesread < tracklength
        # A track is made up of events. All events start with a variable length
        # value indicating the number of ticks (time) since the last event.

        # Get the time offset of the next event
        dT = readvariablelength(f)

        # Figure out the event type
        # Remember, endianness is byte order, not bit order. No need to ntoh here.
        event_start = read(f, UInt8)
        skip(f, -1)

        local event
        if isMIDIevent(event_start)
            event = readMIDIevent(dT, f, laststatus)
            laststatus = event.status
        elseif issysexevent(event_start)
            event = readsysexevent(dT, f)
            laststatus = UInt8(0)
        elseif ismetaevent(event_start)
            event = readmetaevent(dT, f)
            laststatus = UInt8(0)
        else
            error("Unrecognized event $(hex(event_start,2))")
        end
        push!(track.events, event)

        bytesread = position(f) - trackstart
    end

    # Validate that the track ends with a track end event
    lastevent = track.events[length(track.events)]
    if !isa(lastevent, MetaEvent) || lastevent.metatype != METATRACKEND
        error("Invalid track - does not end with track metaevent")
    else
        # strip the track end event - we don't need to worry about manipulating it
        track.events = track.events[1:length(track.events)-1]
    end

    track
end

function writetrack(f::IO, track::MIDITrack)
    write(f, convert(Array{UInt8, 1}, MTRK)) # Track identifier

    writingMIDI = false
    previous_status = UInt8(0)

    event_buffer = IOBuffer()

    for event in track.events
        if isa(event, MIDIEvent) && previous_status != 0 && previous_status == event.status
            writeevent(event_buffer, event, false)
        elseif isa(event, MIDIEvent)
            writeevent(event_buffer, event)
            previous_status = event.status
        else
            writeevent(event_buffer, event)
            previous_status = UInt8(0)
        end
    end

    # Write the track end event
    writeevent(event_buffer, MetaEvent(0, METATRACKEND, UInt8[]))

    bytes = takebuf_array(event_buffer)

    write(f, hton(UInt32(length(bytes))))
    write(f, bytes)
end

# Adds an event to a track, with an absolute time
function addevent(track::MIDITrack, time::Integer, newevent::TrackEvent)
    tracktime = 0
    addedevent = false
    for (i, event) in enumerate(track.events)
        if tracktime + event.dT > time
            # Add to track at position
            newdt = time - tracktime
            newevent.dT = newdt

            insert!(track.events, i, newevent)
            addedevent = true

            nextevent = track.events[i+1]
            nextevent.dT -= newdt

            break
        else
            tracktime += event.dT
        end
    end

    if !addedevent
        newdt = time - tracktime
        newevent.dT = newdt
        push!(track.events, newevent)
    end
end

# Adds a note to a track
function addnote(track::MIDITrack, note::Note)
    for (status, position) in [(NOTEON, note.position), (NOTEOFF, note.position + note.duration)]
        addevent(track, position, MIDIEvent(0, status | note.channel, UInt8[note.value, note.velocity]))
    end
end

# Adds a series of notes to a track
function addnotes(track::MIDITrack, notes::Array{Note, 1})
    for note in notes
        addnote(track, note)
    end
end

# Gets all of the notes on a track
function getnotes(track::MIDITrack)
    # Read through events until a noteon is found
    notes = Note[]
    tracktime = UInt64(0)
    for (i, event) in enumerate(track.events)
        tracktime += event.dT
        if isa(event, MIDIEvent) && event.status & 0xF0 == NOTEON
            duration = UInt64(0)
            for event2 in track.events[i+1:length(track.events)]
                duration += event2.dT
                # If we have a MIDI event & it's a noteoff, and it's for the same note as the first event we found, make a note
                if isa(event2, MIDIEvent) && event2.status & 0xF0 == NOTEOFF && event.data[1] == event2.data[1]
                    push!(notes, Note(event.data[1], duration, tracktime, event.status & 0x0F, event.data[2]))
                    break
                end
            end
        end
    end
    sort!(notes, lt=((x, y)->x.position<y.position))
end

# Change the program (instrument) on the given channel. Time is absolute, not relative to the last event.
function programchange(track::MIDITrack, time::Integer, channel::UInt8, program::UInt8)
    program = program - 1 # Program changes are typically given in range 1-128, but represented internally as 0-127.
    addevent(track, time, MIDIEvent(0, PROGRAMCHANGE | channel, UInt8[program]))
end


text:
package p;

class A {
    private static class C {

    }

    private static class B extends C{

    }
}


text:
<?php
/**
 * Data2Test
 *
 * PHP version 5
 *
 * @category Class
 * @package  Swagger\Client
 * @author   Swagger Codegen team
 * @link     https://github.com/swagger-api/swagger-codegen
 */

/**
 * SKU Comments Sentiment API
 *
 * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
 *
 * OpenAPI spec version:
 *
 * Generated by: https://github.com/swagger-api/swagger-codegen.git
 *
 */

/**
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen
 * Please update the test case below to test the model.
 */

namespace Swagger\Client;

/**
 * Data2Test Class Doc Comment
 *
 * @category    Class */
// * @description Data2
/**
 * @package     Swagger\Client
 * @author      Swagger Codegen team
 * @link        https://github.com/swagger-api/swagger-codegen
 */
class Data2Test extends \PHPUnit_Framework_TestCase
{

    /**
     * Setup before running any test case
     */
    public static function setUpBeforeClass()
    {

    }

    /**
     * Setup before running each test case
     */
    public function setUp()
    {

    }

    /**
     * Clean up after running each test case
     */
    public function tearDown()
    {

    }

    /**
     * Clean up after running all test cases
     */
    public static function tearDownAfterClass()
    {

    }

    /**
     * Test "Data2"
     */
    public function testData2()
    {

    }

    /**
     * Test attribute "sku"
     */
    public function testPropertySku()
    {

    }

    /**
     * Test attribute "content"
     */
    public function testPropertyContent()
    {

    }

    /**
     * Test attribute "tone"
     */
    public function testPropertyTone()
    {

    }

}


text:
<?php
namespace Google\Service\Reseller;

class SubscriptionTrialSettings extends \Google\Model
{
  public $isInTrial;
  public $trialEndTime;

  public function setIsInTrial($isInTrial)
  {
    $this->isInTrial = $isInTrial;
  }

  public function getIsInTrial()
  {
    return $this->isInTrial;
  }

  public function setTrialEndTime($trialEndTime)
  {
    $this->trialEndTime = $trialEndTime;
  }

  public function getTrialEndTime()
  {
    return $this->trialEndTime;
  }

}


text:
package os.proj.p5.sequences;

import java.util.Iterator;
import java.util.LinkedList;

public class PageSeq {

	private final int numFramesOfMemory;
	private final LinkedList<Integer> pageRequests;

	public PageSeq(int numFramesOfMemory) {
		this.numFramesOfMemory = numFramesOfMemory;
		this.pageRequests = new LinkedList<Integer>();
	}

	public void addPageRequest(int nextInt) {
		this.pageRequests.add(nextInt);
	}

	public int getFramesOfMemory() {
		return this.numFramesOfMemory;
	}

	public Iterator<Integer> getSequenceIterator() {
		return this.pageRequests.iterator();
	}

	public LinkedList<Integer> getTheSequence() {
		return this.pageRequests;
	}
}


text:
<?php
/**
 * File: Parse.php
 * User: zacharydubois
 * Date: 2016-02-05
 * Time: 20:02
 * Project: Alliance-Scraper
 */

namespace alliance;

/**
 * Class Parse
 *
 * Used for data parsing of the information obtained.
 *
 * @package alliance
 */
class Parse {

}


text:
cd cookbooks
for cb in $@; do
    knife cookbook site download $cb
    tar zxf $cb*.tar.gz && rm -f $cp*.tar.gz
done


text:
// Copyright (c) 2012 Ecma International.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
es5id: 15.2.3.5-4-170
description: >
    Object.create - one property in 'Properties' is the Math object
    that uses Object's [[Get]] method to access the 'value' property
    (8.10.5 step 5.a)
---*/

            Math.value = "MathValue";

            var newObj = Object.create({}, {
                prop: Math
            });

assert.sameValue(newObj.prop, "MathValue", 'newObj.prop');


text:
package slackapi

import "encoding/json"

/* inspired by nlopes/slack/rtm */

// Event defines the JSON-encoded output for RTM events.
type Event struct {
	Type string `json:"type"`
	Data interface{}
}

// ErrorEvent represents the websocket errors.
type ErrorEvent struct {
	Text string
}

// AccountsChangedEvent represents the accounts changed event.
type AccountsChangedEvent struct {
	Type string `json:"type"`
}

// BotAddedEvent represents the bot added event.
type BotAddedEvent struct {
	Type string `json:"type"`
	Bot  Bot    `json:"bot"`
}

// BotChangedEvent represents the bot changed event.
type BotChangedEvent struct {
	Type string `json:"type"`
	Bot  Bot    `json:"bot"`
}

// ChannelInfoEvent represents the Channel info event.
type ChannelInfoEvent struct {
	// channel_left
	// channel_deleted
	// channel_archive
	// channel_unarchive
	Type      string `json:"type"`
	Channel   string `json:"channel"`
	User      string `json:"user,omitempty"`
	Timestamp string `json:"ts,omitempty"`
}

// ChannelCreatedInfo represents the information associated with the Channel created event
type ChannelCreatedInfo struct {
	ID        string `json:"id"`
	IsChannel bool   `json:"is_channel"`
	Name      string `json:"name"`
	Created   int    `json:"created"`
	Creator   string `json:"creator"`
}

// ChannelRenameInfo represents the information associated with a Channel rename event
type ChannelRenameInfo struct {
	ID      string `json:"id"`
	Name    string `json:"name"`
	Created string `json:"created"`
}

// ChannelArchiveEvent represents the Channel archive event.
type ChannelArchiveEvent ChannelInfoEvent

// ChannelCreatedEvent represents the Channel created event.
type ChannelCreatedEvent struct {
	Type           string             `json:"type"`
	Channel        ChannelCreatedInfo `json:"channel"`
	EventTimestamp string             `json:"event_ts"`
}

// ChannelDeletedEvent represents the Channel deleted event.
type ChannelDeletedEvent ChannelInfoEvent

// ChannelHistoryChangedEvent represents the Channel history changed event.
type ChannelHistoryChangedEvent struct {
	Type           string `json:"type"`
	Latest         string `json:"latest"`
	Timestamp      string `json:"ts"`
	EventTimestamp string `json:"event_ts"`
}

// ChannelJoinedEvent represents the Channel joined event.
type ChannelJoinedEvent struct {
	Type    string  `json:"type"`
	Channel Channel `json:"channel"`
}

// ChannelLeftEvent represents the Channel left event.
type ChannelLeftEvent ChannelInfoEvent

// ChannelMarkedEvent represents the Channel marked event.
type ChannelMarkedEvent ChannelInfoEvent

// ChannelRenameEvent represents the Channel rename event.
type ChannelRenameEvent struct {
	Type      string            `json:"type"`
	Channel   ChannelRenameInfo `json:"channel"`
	Timestamp string            `json:"event_ts"`
}

// ChannelUnarchiveEvent represents the Channel unarchive event.
type ChannelUnarchiveEvent ChannelInfoEvent

// CommandsChangedEvent represents the commands changed event.
type CommandsChangedEvent struct {
	Type           string `json:"type"`
	EventTimestamp string `json:"event_ts"`
}

// DesktopNotification represents the structure of an app alert.
type DesktopNotification struct {
	Type           string `json:"type"`
	Title          string `json:"title"`
	Subtitle       string `json:"subtitle"`
	Msg            string `json:"msg"`
	Content        string `json:"content"`
	Channel        string `json:"channel"`
	LaunchURI      string `json:"launchUri"`
	AvatarImage    string `json:"avatarImage"`
	SsbFilename    string `json:"ssbFilename"`
	ImageURI       string `json:"imageUri"`
	EventTimestamp string `json:"event_ts"`
	IsShared       bool   `json:"is_shared"`
}

// DNDUpdatedEvent represents the update event for Do Not Disturb
type DNDUpdatedEvent struct {
	Type   string    `json:"type"`
	User   string    `json:"user"`
	Status DNDStatus `json:"dnd_status"`
}

// EmailDomainChangedEvent represents the email domain changed event.
type EmailDomainChangedEvent struct {
	Type           string `json:"type"`
	EventTimestamp string `json:"event_ts"`
	EmailDomain    string `json:"email_domain"`
}

// EmojiChangedEvent represents the emoji changed event.
type EmojiChangedEvent struct {
	Type           string   `json:"type"`
	SubType        string   `json:"subtype"`
	Name           string   `json:"name"`
	Names          []string `json:"names"`
	Value          string   `json:"value"`
	EventTimestamp string   `json:"event_ts"`
}

// FileActionEvent represents the File action event.
type fileActionEvent struct {
	Type           string `json:"type"`
	EventTimestamp string `json:"event_ts"`
	File           File   `json:"file"`
	// FileID is used for FileDeletedEvent
	FileID string `json:"file_id,omitempty"`
}

// FileChangeEvent represents the File change event.
type FileChangeEvent fileActionEvent

// FileCommentAddedEvent represents the File comment added event.
type FileCommentAddedEvent struct {
	fileActionEvent
	Comment Comment `json:"comment"`
}

// FileCommentDeletedEvent represents the File comment deleted event.
type FileCommentDeletedEvent struct {
	fileActionEvent
	Comment string `json:"comment"`
}

// FileCommentEditedEvent represents the File comment edited event.
type FileCommentEditedEvent struct {
	fileActionEvent
	Comment Comment `json:"comment"`
}

// FileCreatedEvent represents the File created event.
type FileCreatedEvent fileActionEvent

// FileDeletedEvent represents the File deleted event.
type FileDeletedEvent fileActionEvent

// FilePrivateEvent represents the File private event.
type FilePrivateEvent fileActionEvent

// FilePublicEvent represents the File public event.
type FilePublicEvent fileActionEvent

// FileSharedEvent represents the File shared event.
type FileSharedEvent fileActionEvent

// FileUnsharedEvent represents the File unshared event.
type FileUnsharedEvent fileActionEvent

// GroupCreatedEvent represents the Group created event.
type GroupCreatedEvent struct {
	Type    string             `json:"type"`
	User    string             `json:"user"`
	Channel ChannelCreatedInfo `json:"channel"`
}

// GroupRenameInfo represents the group info related to the renamed group
type GroupRenameInfo struct {
	ID      string `json:"id"`
	Name    string `json:"name"`
	Created string `json:"created"`
}

// GroupArchiveEvent represents the Group archive event.
type GroupArchiveEvent ChannelInfoEvent

// GroupCloseEvent represents the Group close event.
type GroupCloseEvent ChannelInfoEvent

// GroupHistoryChangedEvent represents the Group history changed event.
type GroupHistoryChangedEvent ChannelHistoryChangedEvent

// GroupJoinedEvent represents the Group joined event.
type GroupJoinedEvent ChannelJoinedEvent

// GroupLeftEvent represents the Group left event.
type GroupLeftEvent ChannelInfoEvent

// GroupMarkedEvent represents the Group marked event.
type GroupMarkedEvent ChannelInfoEvent

// GroupOpenEvent represents the Group open event.
type GroupOpenEvent ChannelInfoEvent

// GroupRenameEvent represents the Group rename event.
type GroupRenameEvent struct {
	Type      string          `json:"type"`
	Group     GroupRenameInfo `json:"channel"`
	Timestamp string          `json:"ts"`
}

// GroupUnarchiveEvent represents the Group unarchive event.
type GroupUnarchiveEvent ChannelInfoEvent

// HelloEvent represents the hello event.
type HelloEvent struct{}

// IMCloseEvent represents the IM close event.
type IMCloseEvent ChannelInfoEvent

// IMCreatedEvent represents the IM created event.
type IMCreatedEvent struct {
	Type    string             `json:"type"`
	User    string             `json:"user"`
	Channel ChannelCreatedInfo `json:"channel"`
}

// IMHistoryChangedEvent represents the IM history changed event.
type IMHistoryChangedEvent ChannelHistoryChangedEvent

// IMMarkedEvent represents the IM marked event.
type IMMarkedEvent ChannelInfoEvent

// IMMarkedHistoryChanged represents the IM marked history changed event
type IMMarkedHistoryChanged ChannelInfoEvent

// IMOpenEvent represents the IM open event.
type IMOpenEvent ChannelInfoEvent

// ManualPresenceChangeEvent represents the manual presence change event.
type ManualPresenceChangeEvent struct {
	Type     string `json:"type"`
	Presence string `json:"presence"`
}

// MessageEvent represents the message event.
type MessageEvent Message

type pinEvent struct {
	Type           string `json:"type"`
	User           string `json:"user"`
	Item           Item   `json:"item"`
	Channel        string `json:"channel_id"`
	EventTimestamp string `json:"event_ts"`
	HasPins        bool   `json:"has_pins,omitempty"`
}

// PinAddedEvent represents the Pin added event.
type PinAddedEvent pinEvent

// PinRemovedEvent represents the Pin removed event.
type PinRemovedEvent pinEvent

// PrefChangeEvent represents a user preferences change event
type PrefChangeEvent struct {
	Type  string          `json:"type"`
	Name  string          `json:"name"`
	Value json.RawMessage `json:"value"`
}

// PresenceChangeEvent represents the presence change event.
type PresenceChangeEvent struct {
	Type     string `json:"type"`
	Presence string `json:"presence"`
	User     string `json:"user"`
}

type reactionEvent struct {
	Type           string       `json:"type"`
	User           string       `json:"user"`
	ItemUser       string       `json:"item_user"`
	Item           ReactionItem `json:"item"`
	Reaction       string       `json:"reaction"`
	EventTimestamp string       `json:"event_ts"`
}

// ReactionAddedEvent represents the Reaction added event.
type ReactionAddedEvent reactionEvent

// ReactionRemovedEvent represents the Reaction removed event.
type ReactionRemovedEvent reactionEvent

// ReconnectURLEvent represents the receiving reconnect url event.
type ReconnectURLEvent struct {
	Type string `json:"type"`
	URL  string `json:"url"`
}

type starEvent struct {
	Type           string `json:"type"`
	User           string `json:"user"`
	Item           Item   `json:"item"`
	EventTimestamp string `json:"event_ts"`
}

// StarAddedEvent represents the Star added event.
type StarAddedEvent starEvent

// StarRemovedEvent represents the Star removed event.
type StarRemovedEvent starEvent

// Subteam represents the subteam metadata.
type Subteam struct {
	ID                  string              `json:"id"`
	TeamID              string              `json:"team_id"`
	IsUserGroup         bool                `json:"is_usergroup"`
	IsSubteam           bool                `json:"is_subteam"`
	IsExternal          bool                `json:"is_external"`
	AutoProvision       bool                `json:"auto_provision"`
	Name                string              `json:"name"`
	Description         string              `json:"description"`
	Handle              string              `json:"handle"`
	DateCreate          int64               `json:"date_create"`
	DateUpdate          int64               `json:"date_update"`
	DateDelete          int64               `json:"date_delete"`
	AutoType            interface{}         `json:"auto_type"`
	EnterpriseSubteamID string              `json:"enterprise_subteam_id"`
	CreatedBy           string              `json:"created_by"`
	UpdatedBy           string              `json:"updated_by"`
	DeletedBy           string              `json:"deleted_by"`
	UserCount           int                 `json:"user_count"`
	Users               []string            `json:"users"`
	Prefs               map[string][]string `json:"prefs"`
}

// SubteamUpdated represents the changes in team metadata.
type SubteamUpdated struct {
	Type           string  `json:"type"`
	Subteam        Subteam `json:"subteam"`
	EventTimestamp string  `json:"event_ts"`
}

// TeamDomainChangeEvent represents the Team domain change event.
type TeamDomainChangeEvent struct {
	Type   string `json:"type"`
	URL    string `json:"url"`
	Domain string `json:"domain"`
}

// TeamJoinEvent represents the Team join event.
type TeamJoinEvent struct {
	Type string `json:"type"`
	User User   `json:"user"`
}

// TeamMigrationStartedEvent represents the Team migration started event.
type TeamMigrationStartedEvent struct {
	Type string `json:"type"`
}

// TeamPrefChangeEvent represents the Team preference change event.
type TeamPrefChangeEvent struct {
	Type  string   `json:"type"`
	Name  string   `json:"name,omitempty"`
	Value []string `json:"value,omitempty"`
}

// TeamRenameEvent represents the Team rename event.
type TeamRenameEvent struct {
	Type           string `json:"type"`
	Name           string `json:"name,omitempty"`
	EventTimestamp string `json:"event_ts,omitempty"`
}

// UserChangeEvent represents the user change event.
type UserChangeEvent struct {
	Type string `json:"type"`
	User User   `json:"user"`
}

// UserTypingEvent represents the user typing event.
type UserTypingEvent struct {
	Type    string `json:"type"`
	User    string `json:"user"`
	Channel string `json:"channel"`
}


text:
import { AfterContentInit, Directive, ElementRef } from '@angular/core';

@Directive({
    selector: '[rtFocusOnRender]'
})
export class FocusOnRenderDirective implements AfterContentInit {
    constructor(private elementRef: ElementRef) {}
    public ngAfterContentInit(): void {
        // we need set timeout for the cases when element itself is rendered by *ngIf directive and we need to wait it's rendering
        setTimeout(() => this.elementRef.nativeElement.focus(), 0);
    }
}


text: Angular SPA template with C# .NET services


text:
namespace chromecast {
namespace shell {

AccessibilityManagerImpl::AccessibilityManagerImpl(
    CastWindowManagerAura* window_manager)
    : window_tree_host_(window_manager->window_tree_host()),
      accessibility_sound_proxy_(std::make_unique<AccessibilitySoundPlayer>()) {
  DCHECK(window_tree_host_);
  aura::Window* root_window = window_tree_host_->window()->GetRootWindow();
  wm::ActivationClient* activation_client =
      wm::GetActivationClient(root_window);
  focus_ring_controller_ =
      std::make_unique<FocusRingController>(root_window, activation_client);
  accessibility_focus_ring_controller_ =
      std::make_unique<AccessibilityFocusRingController>(root_window);
  touch_exploration_manager_ = std::make_unique<TouchExplorationManager>(
      root_window, activation_client,
      accessibility_focus_ring_controller_.get(), &accessibility_sound_proxy_,
      window_manager->GetGestureHandler());
  magnify_gesture_detector_ =
      std::make_unique<MultipleTapDetector>(root_window, this);
  magnification_controller_ =
      std::make_unique<FullscreenMagnificationController>(
          root_window, window_manager->GetGestureHandler());
}

AccessibilityManagerImpl::~AccessibilityManagerImpl() {}

void AccessibilityManagerImpl::SetFocusRingColor(SkColor color) {
  DCHECK(accessibility_focus_ring_controller_);
  accessibility_focus_ring_controller_->SetFocusRingColor(color);
}

void AccessibilityManagerImpl::ResetFocusRingColor() {
  DCHECK(accessibility_focus_ring_controller_);
  accessibility_focus_ring_controller_->ResetFocusRingColor();
}

void AccessibilityManagerImpl::SetFocusRing(
    const std::vector<gfx::Rect>& rects_in_screen,
    FocusRingBehavior focus_ring_behavior) {
  DCHECK(accessibility_focus_ring_controller_);
  accessibility_focus_ring_controller_->SetFocusRing(rects_in_screen,
                                                     focus_ring_behavior);
}

void AccessibilityManagerImpl::HideFocusRing() {
  DCHECK(accessibility_focus_ring_controller_);
  accessibility_focus_ring_controller_->HideFocusRing();
}

void AccessibilityManagerImpl::SetHighlights(
    const std::vector<gfx::Rect>& rects_in_screen,
    SkColor color) {
  DCHECK(accessibility_focus_ring_controller_);
  accessibility_focus_ring_controller_->SetHighlights(rects_in_screen, color);
}

void AccessibilityManagerImpl::HideHighlights() {
  DCHECK(accessibility_focus_ring_controller_);
  accessibility_focus_ring_controller_->HideHighlights();
}

void AccessibilityManagerImpl::SetScreenReader(bool enable) {
  touch_exploration_manager_->Enable(enable);

  // TODO(rdaum): Until we can fix triple-tap and two finger gesture conflicts
  // between TouchExplorationController, FullscreenMagnifier, and
  // TripleTapDetector, we have to make sure magnification is not on while
  // screenreader is active.
  // The triple-tap gesture can still be enabled, but will not do anything until
  // screenreader is disabled again.
  if (enable) {
    magnification_controller_->SetEnabled(false);
  }
}

void AccessibilityManagerImpl::SetTouchAccessibilityAnchorPoint(
    const gfx::Point& anchor_point) {
  touch_exploration_manager_->SetTouchAccessibilityAnchorPoint(anchor_point);
}

void AccessibilityManagerImpl::SetVirtualKeyboardBounds(const gfx::Rect& rect) {
  touch_exploration_manager_->SetVirtualKeyboardBounds(rect);
}

aura::WindowTreeHost* AccessibilityManagerImpl::window_tree_host() const {
  DCHECK(window_tree_host_);
  return window_tree_host_;
}

void AccessibilityManagerImpl::SetMagnificationGestureEnabled(
    bool gesture_enabled) {
  magnify_gesture_detector_->set_enabled(gesture_enabled);

  // If the gesture is not enabled, make sure that magnification is turned off,
  // in case we're already in magnification. Otherwise the user will be stuck in
  // magnifier and unable to get out.
  if (!gesture_enabled) {
    magnification_controller_->SetEnabled(false);
  }
}

bool AccessibilityManagerImpl::IsMagnificationGestureEnabled() const {
  return magnify_gesture_detector_->enabled();
}

void AccessibilityManagerImpl::OnTripleTap(const gfx::Point& tap_location) {
  magnification_controller_->SetEnabled(
      !magnification_controller_->IsEnabled());
}

void AccessibilityManagerImpl::SetAccessibilitySoundPlayer(
    std::unique_ptr<AccessibilitySoundPlayer> player) {
  accessibility_sound_proxy_.ResetPlayer(std::move(player));
}

}  // namespace shell
}  // namespace chromecast


text:
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*
 Copyright (C) 2007 Giorgio Facchinetti
 Copyright (C) 2007 Katiuscia Manzoni

 This file is part of QuantLib, a free-software/open-source library
 for financial quantitative analysts and developers - http://quantlib.org/

 QuantLib is free software: you can redistribute it and/or modify it
 under the terms of the QuantLib license.  You should have received a
 copy of the license along with this program; if not, please email
 <quantlib-dev@lists.sf.net>. The license is also available online at
 <http://quantlib.org/license.shtml>.

 This program is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 FOR A PARTICULAR PURPOSE.  See the license for more details.
*/

#include <ql/termstructures/volatility/optionlet/strippedoptionletadapter.hpp>
#include <ql/termstructures/volatility/optionlet/optionletstripper.hpp>
#include <ql/termstructures/volatility/capfloor/capfloortermvolsurface.hpp>
#include <ql/math/interpolations/linearinterpolation.hpp>
#include <ql/math/interpolations/sabrinterpolation.hpp>
#include <ql/termstructures/volatility/interpolatedsmilesection.hpp>
#include <ql/math/interpolations/cubicinterpolation.hpp>

namespace QuantLib {

    StrippedOptionletAdapter::StrippedOptionletAdapter(
                const boost::shared_ptr<StrippedOptionletBase>& s)
    : OptionletVolatilityStructure(s->settlementDays(),
                                   s->calendar(),
                                   s->businessDayConvention(),
                                   s->dayCounter()),
      optionletStripper_(s),
      nInterpolations_(s->optionletMaturities()),
      strikeInterpolations_(nInterpolations_) {
        registerWith(optionletStripper_);
    }

    boost::shared_ptr<SmileSection>
    StrippedOptionletAdapter::smileSectionImpl(Time t) const {
         std::vector<Rate> optionletStrikes = optionletStripper_->optionletStrikes(0); // strikes are the same for all times ?!
         std::vector<Real> stddevs;
         for(Size i=0;i<optionletStrikes.size();i++) {
             stddevs.push_back(volatilityImpl(t,optionletStrikes[i])*std::sqrt(t));
         }
         // Extrapolation may be a problem with splines, but since minStrike() and maxStrike() are set, we assume that no one will use stddevs for strikes outside these strikes
         CubicInterpolation::BoundaryCondition bc = optionletStrikes.size()>=4 ? CubicInterpolation::Lagrange : CubicInterpolation::SecondDerivative;
         return boost::shared_ptr<SmileSection>(new InterpolatedSmileSection<Cubic>(t,optionletStrikes,stddevs,Null<Real>(),
                                                            Cubic(CubicInterpolation::Spline,false,bc,0.0,bc,0.0)));
    }

    Volatility StrippedOptionletAdapter::volatilityImpl(Time length,
                                                        Rate strike) const {
        calculate();

        std::vector<Volatility> vol(nInterpolations_);
        for (Size i=0; i<nInterpolations_; ++i)
            vol[i] = strikeInterpolations_[i]->operator()(strike, true);

        const std::vector<Time>& optionletTimes =
                                    optionletStripper_->optionletFixingTimes();
        boost::shared_ptr<LinearInterpolation> timeInterpolator(new
            LinearInterpolation(optionletTimes.begin(), optionletTimes.end(),
                                vol.begin()));
        return timeInterpolator->operator()(length, true);
    }

    void StrippedOptionletAdapter::performCalculations() const {

        //const std::vector<Rate>& atmForward = optionletStripper_->atmOptionletRate();
        //const std::vector<Time>& optionletTimes = optionletStripper_->optionletTimes();

        for (Size i=0; i<nInterpolations_; ++i) {
            const std::vector<Rate>& optionletStrikes =
                optionletStripper_->optionletStrikes(i);
            const std::vector<Volatility>& optionletVolatilities =
                optionletStripper_->optionletVolatilities(i);
            //strikeInterpolations_[i] = boost::shared_ptr<SABRInterpolation>(new
            //            SABRInterpolation(optionletStrikes.begin(), optionletStrikes.end(),
            //                              optionletVolatilities.begin(),
            //                              optionletTimes[i], atmForward[i],
            //                              0.02,0.5,0.2,0.,
            //                              false, true, false, false
            //                              //alphaGuess_, betaGuess_,
            //                              //nuGuess_, rhoGuess_,
            //                              //isParameterFixed_[0],
            //                              //isParameterFixed_[1],
            //                              //isParameterFixed_[2],
            //                              //isParameterFixed_[3]
            //                              ////,
            //                              //vegaWeightedSmileFit_,
            //                              //endCriteria_,
            //                              //optMethod_
            //                              ));
            strikeInterpolations_[i] = boost::shared_ptr<LinearInterpolation>(new
                LinearInterpolation(optionletStrikes.begin(),
                                    optionletStrikes.end(),
                                    optionletVolatilities.begin()));

            //QL_ENSURE(strikeInterpolations_[i]->endCriteria()!=EndCriteria::MaxIterations,
            //          "section calibration failed: "
            //          "option time " << optionletTimes[i] <<
            //          ": " <<
            //              ", alpha " <<  strikeInterpolations_[i]->alpha()<<
            //              ", beta "  <<  strikeInterpolations_[i]->beta() <<
            //              ", nu "    <<  strikeInterpolations_[i]->nu()   <<
            //              ", rho "   <<  strikeInterpolations_[i]->rho()  <<
            //              ", error " <<  strikeInterpolations_[i]->interpolationError()
            //              );

        }
    }

    Rate StrippedOptionletAdapter::minStrike() const {
        return optionletStripper_->optionletStrikes(0).front(); //FIX
    }

    Rate StrippedOptionletAdapter::maxStrike() const {
        return optionletStripper_->optionletStrikes(0).back(); //FIX
    }

    Date StrippedOptionletAdapter::maxDate() const {
        return optionletStripper_->optionletFixingDates().back();
    }

}


text:
<?php
class Kwf_Data_Kwc_Image extends Kwf_Data_Abstract implements Kwf_Data_Kwc_ListInterface
{
    protected $_class;
    protected $_size;
    private $_subComponent;

    public function __construct($class, $size)
    {
        $this->_class = $class;
        $this->_size = $size;
    }

    public function load($row)
    {
        $model = Kwc_Abstract::createOwnModel($this->_class);
        $componentId = $row->component_id . '-' . $row->id;
        if ($this->_subComponent) {
            $componentId .= $this->_subComponent;
        }
        $row = $model->getRow($componentId);
        if ($row && $row->kwf_upload_id) {
            $hashKey = Kwf_Util_Hash::hash($row->kwf_upload_id);
            return '/kwf/media/upload/preview?uploadId='.$row->kwf_upload_id.
                   '&hashKey='.$hashKey.'&size='.$this->_size;
        } else {
            return '';
        }
    }

    public function setSubComponent($key)
    {
        $this->_subComponent = $key;
    }
    public function getSubComponent()
    {
        return $this->_subComponent;
    }
}


text:
using System;
using Windows.Graphics.Display;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace LoopMeSDK
{
    /// <summary>
    /// Interstitial page.
    /// </summary>
    sealed partial class InterstitialPage : Page
    {
        private AdDisplayController adController;
        private DisplayOrientations entryOrientations;

        public InterstitialPage()
        {
            InitializeComponent();
            NavigationCacheMode = Windows.UI.Xaml.Navigation.NavigationCacheMode.Enabled;
        }

        private void InterstitialPage_BackRequested(object sender, BackRequestedEventArgs e)
        {
            Frame frame = Window.Current.Content as Frame;
            if (frame == null)
                return;

            if (frame.Equals(this.Frame))
            {
                e.Handled = true;
                return;
            }
        }

        void Current_Resuming(object sender, object e)
        {
            Close();
        }

        protected override async void OnNavigatedTo(Windows.UI.Xaml.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            SystemNavigationManager.GetForCurrentView().BackRequested += InterstitialPage_BackRequested;
            if (Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.UI.ViewManagement.StatusBar"))
            {
                await Windows.UI.ViewManagement.StatusBar.GetForCurrentView().HideAsync();
            }

            if (e.NavigationMode == Windows.UI.Xaml.Navigation.NavigationMode.New)
            {
                Application.Current.Resuming += Current_Resuming;
                adController = (e.Parameter as AdDisplayController);
                SetOrientation();
                SetUpUI();
            }
            else
            {
                SetOrientation();
            }

            this.adController.OnNavigatedTo(this.Frame);
            await this.adController.JsClient.ExecuteEvent(JSEvent.State, JSNamespaces.Webview, WebviewStates.Visible);
        }

        private void Current_Suspending(object sender, Windows.ApplicationModel.SuspendingEventArgs e)
        {
            throw new NotImplementedException();
        }

        protected override async void OnNavigatedFrom(Windows.UI.Xaml.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);

            DisplayInformation.AutoRotationPreferences = this.entryOrientations;
            await this.adController.OnNavigatedFrom(e);

            if (e.NavigationMode == Windows.UI.Xaml.Navigation.NavigationMode.Back)
            {
                Application.Current.Resuming -= Current_Resuming;
                SystemNavigationManager.GetForCurrentView().BackRequested -= InterstitialPage_BackRequested;
                this.adController.VideoClient.MediaPlayer.Source = null;
                ContentView.Children.Remove(adController.VideoClient.MediaPlayer);
                ContentView.Children.Remove(adController.WebView);
            }

            //TODO: if needed
            if (Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.UI.ViewManagement.StatusBar"))
            {
                await Windows.UI.ViewManagement.StatusBar.GetForCurrentView().ShowAsync();
            }
        }

        void JsClient_JSClientRecievedClose(object sender, EventArgs e)
        {
            Close();
        }

        private async void Close()
        {
            Frame frame = Window.Current.Content as Frame;
            try
            {
                if (this.adController != null)
                    await this.adController.VideoClient.Stop();
            }
            catch { }
            if (frame.CanGoBack)
            {
                frame.GoBack();
            }
        }

        private async void SetUpUI()
        {
            this.adController.JsClient.JSClientRecievedClose += JsClient_JSClientRecievedClose;

            MediaElement player = this.adController.VideoClient.MediaPlayer;
            WebView wv = this.adController.WebView;

            if (!ContentView.Children.Contains(player))
            {
                ContentView.Children.Add(player);
                if (this.adController.VideoClient.VideoFile != null)
                {
                    await this.adController.VideoClient.SetupPlayerWithFile(this.adController.VideoClient.VideoFile);
                }
            }

            if (!ContentView.Children.Contains(wv))
            {
                wv.DefaultBackgroundColor = Windows.UI.Color.FromArgb(0, 1, 1, 1);

                ContentView.Children.Add(wv);
                wv.Height = Window.Current.Bounds.Height;
            }
        }

        private void SetOrientation()
        {
            if (this.adController == null)
                return;

            this.entryOrientations = DisplayInformation.AutoRotationPreferences;
            if (this.adController.Configuration.Orientation == AdOrientation.Portrait)
            {
                DisplayInformation.AutoRotationPreferences = DisplayOrientations.Portrait;
            }
            else
            {
                DisplayInformation.AutoRotationPreferences = DisplayOrientations.Landscape | DisplayOrientations.LandscapeFlipped;
            }
        }
    }
}


text:
import gql from 'graphql-tag';

import { newsFeedNewsItemFragment } from '../../components/news-feed';

export interface ISubmitNewsItemGraphQL {
  submitNewsItem: { id }; // Return type of submitNewsItem mutation
}

export const SUBMIT_NEWS_ITEM_MUTATION = gql`
  mutation SubmitNewsItem($title: String!, $url: String) {
    submitNewsItem(title: $title, url: $url) {
      id
      ...NewsFeed
    }
  }
  ${newsFeedNewsItemFragment}
`;


text:
class TomifyRecord < ActiveRecord::Base
  self.abstract_class = true

  def self.to_html(*attrs)
    attrs.each do |attr|
      define_method("#{attr}_to_html") do
        Rails.cache.fetch("#{self.class.name.downcase}-#{id}-#{attr}") do
          options = { autolink: true, tables: true }
          options.merge!(self.markdown_options) if self.try(:markdown_options)
          markdown = Redcarpet::Markdown.new(Tomify::Markdown::HTML, options)
          markdown.render(self[attr] || "").html_safe
        end
      end
    end

    define_method("bust_html_cache") do
      attrs.each do |attr|
        Rails.cache.delete("#{self.class.name.downcase}-#{id}-#{attr}")
      end
    end

    after_save :bust_html_cache
  end

  def self.date_from(*attrs)
    attrs.each do |attr|
      define_method("#{attr}_date") do
        value = read_attribute attr
        value && value.strftime("%m/%d/%y %I:%M %p")
      end
    end
  end

  date_from :created_at, :updated_at
end


text:
#import "CABaseException.h"
#import "CANumericUtilities.h"

@implementation CANumericUtilities

+(int)parseInteger:(NSString*)integerValue;
{
	NSScanner* scanner = [NSScanner scannerWithString:integerValue];
	int answer;
	if( ! [scanner scanInt:&answer] ) {

		NSString* technicalError = [NSString stringWithFormat:@"failed to parse '%@' as an integer", integerValue];
		BaseException* e = [[BaseException alloc] initWithOriginator:self line:__LINE__ faultMessage:technicalError];

		@throw e;
	}

	return answer;
}

+(NSNumber*)parseIntegerObject:(NSString*)integerValue;
{
	NSScanner* scanner = [NSScanner scannerWithString:integerValue];
	int intValue;
	if( ! [scanner scanInt:&intValue] ) {

		NSString* technicalError = [NSString stringWithFormat:@"failed to parse '%@' as an integer", integerValue];
		BaseException* e = [[BaseException alloc] initWithOriginator:self line:__LINE__ faultMessage:technicalError];

		@throw e;
	}

    NSNumber* answer = [NSNumber numberWithInt:intValue];
	return answer;

}

+(long)parseLong:(NSString*)longString {

    NSScanner* scanner = [NSScanner scannerWithString:longString];
	long long answer;
	if( ! [scanner scanLongLong:&answer] ) {

		NSString* technicalError = [NSString stringWithFormat:@"failed to parse '%@' as a 'long long'", longString];
		BaseException* e = [[BaseException alloc] initWithOriginator:self line:__LINE__ faultMessage:technicalError];

		@throw e;
	}

	return (long)answer;

}

+(NSNumber*)parseLongObject:(NSString*)longString {

    NSScanner* scanner = [NSScanner scannerWithString:longString];
	long long longValue;
	if( ! [scanner scanLongLong:&longValue] ) {

		NSString* technicalError = [NSString stringWithFormat:@"failed to parse '%@' as a 'long long'", longString];
		BaseException* e = [[BaseException alloc] initWithOriginator:self line:__LINE__ faultMessage:technicalError];

		@throw e;
	}

    NSNumber* answer = [NSNumber numberWithLong:(long)longValue];
	return answer;

}

+(double)parseDouble:(NSString*)doubleValue;
{
	NSScanner* scanner = [NSScanner scannerWithString:doubleValue];
	double answer;
	if( ! [scanner scanDouble:&answer] ) {

		NSString* technicalError = [NSString stringWithFormat:@"failed to parse '%@' as a double", doubleValue];
		BaseException* e = [[BaseException alloc] initWithOriginator:self line:__LINE__ faultMessage:technicalError];

		@throw e;
	}

	return answer;
}
@end


text:
/* */
var flag = require('./flag'),
    getActual = require('./getActual'),
    inspect = require('./inspect'),
    objDisplay = require('./objDisplay');
module.exports = function(obj, args) {
  var negate = flag(obj, 'negate'),
      val = flag(obj, 'object'),
      expected = args[3],
      actual = getActual(obj, args),
      msg = negate ? args[2] : args[1],
      flagMsg = flag(obj, 'message');
  if (typeof msg === "function")
    msg = msg();
  msg = msg || '';
  msg = msg.replace(/#\{this\}/g, function() {
    return objDisplay(val);
  }).replace(/#\{act\}/g, function() {
    return objDisplay(actual);
  }).replace(/#\{exp\}/g, function() {
    return objDisplay(expected);
  });
  return flagMsg ? flagMsg + ': ' + msg : msg;
};


text:
/**
 * Why has this not been moved to e.g. @tryghost/events or shared yet?
 *
 * - We currently massively overuse this utility, coupling together bits of the codebase in unexpected ways
 * - We want to prevent this, not reinforce it
 * * Having an @tryghost/events or shared/events module would reinforce this bad patter of using the same event emitter everywhere
 *
 * - Ideally, we want to refactor to:
 *    - either remove dependence on events where we can
 *    - or have separate event emitters for e.g. model layer and routing layer
 *
 */

const events = require('events');
const util = require('util');
let EventRegistry;
let EventRegistryInstance;

EventRegistry = function () {
    events.EventEmitter.call(this);
};

util.inherits(EventRegistry, events.EventEmitter);

/**
 * This is method is semi-hack to make sure listeners are only registered once
 * during the lifetime of the process. And example problem it solves is
 * registering duplicate listeners between Ghost instance reboots when running tests.
 * @param {String} eventName
 * @param {String} listenerName named function name registered as a listener for the event
 * @returns {Boolean}
 */
EventRegistry.prototype.hasRegisteredListener = function (eventName, listenerName) {
    return !!(this.listeners(eventName).find(listener => (listener.name === listenerName)));
};

EventRegistryInstance = new EventRegistry();
EventRegistryInstance.setMaxListeners(100);

module.exports = EventRegistryInstance;


text:
import { WebGLRenderTarget } from './WebGLRenderTarget.js';

function WebGLMultisampleRenderTarget( width, height, options ) {

	WebGLRenderTarget.call( this, width, height, options );

	this.samples = 4;

}

WebGLMultisampleRenderTarget.prototype = Object.assign( Object.create( WebGLRenderTarget.prototype ), {

	constructor: WebGLMultisampleRenderTarget,

	isWebGLMultisampleRenderTarget: true,

	copy: function ( source ) {

		WebGLRenderTarget.prototype.copy.call( this, source );

		this.samples = source.samples;

		return this;

	}

} );

export { WebGLMultisampleRenderTarget };


text:
import defaultParserInterface from '../utils/defaultParserInterface';
import pkg from 'lucene/package.json';

const ID = 'lucene';

export default {
  ...defaultParserInterface,

  id: ID,
  displayName: ID,
  version: pkg.version,
  homepage: pkg.homepage,
  locationProps: new Set(['fieldLocation', 'termLocation', 'location']),

  loadParser(callback) {
    require(['lucene'], callback);
  },

  parse({parse}, code) {
    return parse(code);
  },

  nodeToRange(node) {
    let start = [];
    let end = [];

    if (node.location) {
      start.push(node.location.start.offset);
      end.push(node.location.end.offset);
    }
    if (node.fieldLocation) {
      start.push(node.fieldLocation.start.offset);
      end.push(node.fieldLocation.end.offset);
    }
    if (node.termLocation) {
      start.push(node.termLocation.start.offset);
      end.push(node.termLocation.end.offset);
    }

    if (start.length === 0 || end.length === 0) {
      return;
    }

    return [start.reduce((a, b) => Math.min(a, b)), end.reduce((a, b) => Math.max(a, b))];
  },

  getDefaultOptions() {
    return {};
  },

};


text:
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <winsock.h>
#include <malloc.h>
#include <windows.h>
#include <memory.h>
#include "Light Bulb.h"
#define MAX_LOADSTRING 100

extern "C"
{
	#include "ILibParsers.h"
	#include "UPnPMicroStack.h"
}

static bool SwitchPower = false;
static int  DimmingService = 100;
static HWND	hWndMainWindow = NULL;
DWORD WINAPI UPnPMain(LPVOID ptr);

// Global Variables:
HINSTANCE hInst;								// current instance
TCHAR szTitle[MAX_LOADSTRING];					// The title bar text
TCHAR szWindowClass[MAX_LOADSTRING];			// the main window class name

void *UPnPmicroStackChain;
void *UPnPmicroStack;

// Forward declarations of functions included in this code module:
ATOM				MyRegisterClass(HINSTANCE hInstance);
BOOL				InitInstance(HINSTANCE, int);
LRESULT CALLBACK	WndProc(HWND, UINT, WPARAM, LPARAM);
LRESULT CALLBACK	About(HWND, UINT, WPARAM, LPARAM);

int APIENTRY _tWinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR    lpCmdLine,
                     int       nCmdShow)
{
 	// TODO: Place code here.
	MSG msg;
	HACCEL hAccelTable;

	// Initialize global strings
	LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
	LoadString(hInstance, IDC_LIGHTBULB, szWindowClass, MAX_LOADSTRING);
	MyRegisterClass(hInstance);

	// Perform application initialization:
	if (!InitInstance (hInstance, nCmdShow))
	{
		return FALSE;
	}

	hAccelTable = LoadAccelerators(hInstance, (LPCTSTR)IDC_LIGHTBULB);

	// Main message loop:
	while (GetMessage(&msg, NULL, 0, 0))
	{
		if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
	}

	return (int) msg.wParam;
}

//
//  FUNCTION: MyRegisterClass()
//
//  PURPOSE: Registers the window class.
//
//  COMMENTS:
//
//    This function and its usage are only necessary if you want this code
//    to be compatible with Win32 systems prior to the 'RegisterClassEx'
//    function that was added to Windows 95. It is important to call this function
//    so that the application will get 'well formed' small icons associated
//    with it.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
	WNDCLASSEX wcex;

	wcex.cbSize = sizeof(WNDCLASSEX);

	wcex.style			= CS_HREDRAW | CS_VREDRAW;
	wcex.lpfnWndProc	= (WNDPROC)WndProc;
	wcex.cbClsExtra		= 0;
	wcex.cbWndExtra		= 0;
	wcex.hInstance		= hInstance;
	wcex.hIcon			= LoadIcon(hInstance, (LPCTSTR)IDI_LIGHTBULB);
	wcex.hCursor		= LoadCursor(NULL, IDC_ARROW);
	wcex.hbrBackground	= (HBRUSH)(COLOR_WINDOW+1);
	wcex.lpszMenuName	= (LPCTSTR)IDC_LIGHTBULB;
	wcex.lpszClassName	= szWindowClass;
	wcex.hIconSm		= LoadIcon(wcex.hInstance, (LPCTSTR)IDC_LIGHTBULB);

	return RegisterClassEx(&wcex);
}

//
//   FUNCTION: InitInstance(HANDLE, int)
//
//   PURPOSE: Saves instance handle and creates main window
//
//   COMMENTS:
//
//        In this function, we save the instance handle in a global variable and
//        create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
   HWND hWnd;

   hInst = hInstance; // Store instance handle in our global variable

   //hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
   //   CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);

   hWnd = CreateWindow(szWindowClass, szTitle, WS_SYSMENU | WS_BORDER,
      CW_USEDEFAULT, CW_USEDEFAULT, 240, 320, NULL, NULL, hInstance, NULL);

   if (!hWnd)
   {
      return FALSE;
   }

   hWndMainWindow = hWnd;
   ShowWindow(hWnd, nCmdShow);
   UpdateWindow(hWnd);

   return TRUE;
}

//
//  FUNCTION: WndProc(HWND, unsigned, WORD, LONG)
//
//  PURPOSE:  Processes messages for the main window.
//
//  WM_COMMAND	- process the application menu
//  WM_PAINT	- Paint the main window
//  WM_DESTROY	- post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	int wmId, wmEvent;
	PAINTSTRUCT ps;
	HDC hdc;
	LPSTR s;
	LPSTR str;
	HBRUSH brush;
	COLORREF color;

	switch (message)
	{
	case WM_COMMAND:
		wmId    = LOWORD(wParam);
		wmEvent = HIWORD(wParam);
		// Parse the menu selections:
		switch (wmId)
		{
		case IDM_ABOUT:
			DialogBox(hInst, (LPCTSTR)IDD_ABOUTBOX, hWnd, (DLGPROC)About);
			break;
		case IDM_EXIT:
			PostMessage(hWnd,WM_CLOSE,0,0);
			break;
		case ID_FILE_TOGGLESWITCH:
			SwitchPower = !SwitchPower;
			InvalidateRect(hWndMainWindow,NULL,true);
			UPnPSetState_SwitchPower_Status(UPnPmicroStack,SwitchPower);
			break;
		case ID_FILE_DIMMERUP:
			DimmingService += 20;
			if (DimmingService > 100) DimmingService = 100;
			InvalidateRect(hWndMainWindow,NULL,true);
			UPnPSetState_DimmingService_LoadLevelStatus(UPnPmicroStack,DimmingService);
			break;
		case ID_FILE_DIMMERDOWN:
			DimmingService -= 20;
			if (DimmingService < 0) DimmingService = 0;
			InvalidateRect(hWndMainWindow,NULL,true);
			UPnPSetState_DimmingService_LoadLevelStatus(UPnPmicroStack,DimmingService);
			break;
		default:
			return DefWindowProc(hWnd, message, wParam, lParam);
		}
		break;
	case WM_PAINT:
		RECT rt;

		hdc = BeginPaint(hWnd, &ps);

		color = RGB(128,128,128);
		if (SwitchPower == true)
		{
			color = RGB(128+DimmingService,128+DimmingService,128-DimmingService);
		}

		GetClientRect(hWnd, &rt);
		brush = CreateSolidBrush(color);
		SetBkColor(hdc,color);
		FillRect(hdc,&rt,brush);
		DeleteObject(brush);

		if (SwitchPower == true) s = "ON"; else s = "OFF";
		str = (char*)malloc(200);
		sprintf(str,"Power %s, Dimmer %d",s,DimmingService);
		DrawText(hdc, str, (int)strlen(str), &rt, DT_SINGLELINE | DT_VCENTER | DT_CENTER);
		free(str);

		EndPaint(hWnd, &ps);
		break;
	case WM_CREATE:
		CreateThread(NULL, NULL, &UPnPMain, hWnd, 0, NULL);
		break;
	case WM_CLOSE:
		ILibStopChain(UPnPmicroStackChain);
		break;
	case WM_DESTROY:
		PostQuitMessage(0);
		break;
	default:
		return DefWindowProc(hWnd, message, wParam, lParam);
	}
	return 0;
}

// Message handler for about box.
LRESULT CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
	switch (message)
	{
	case WM_INITDIALOG:
		//IDC_ABOUTEDITBOX

		return TRUE;
	case WM_COMMAND:
		if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
		{
			EndDialog(hDlg, LOWORD(wParam));
			return TRUE;
		}
		break;
	}
	return FALSE;
}

void UPnPSwitchPower_GetStatus(void* upnptoken)
{
	UPnPResponse_SwitchPower_GetStatus(upnptoken,SwitchPower);
}

void UPnPSwitchPower_SetTarget(void* upnptoken,int newTargetValue)
{
	SwitchPower = (newTargetValue != 0);
	InvalidateRect(hWndMainWindow,NULL,true);
	UPnPResponse_SwitchPower_SetTarget(upnptoken);
	UPnPSetState_SwitchPower_Status(UPnPmicroStack,SwitchPower);
}

void UPnPDimmingService_GetLoadLevelStatus(void* upnptoken)
{
	UPnPResponse_DimmingService_GetLoadLevelStatus(upnptoken,DimmingService);
}

void UPnPDimmingService_GetMinLevel(void* upnptoken)
{
	UPnPResponse_DimmingService_GetMinLevel(upnptoken,0);
}

void UPnPDimmingService_SetLoadLevelTarget(void* upnptoken,unsigned char NewLoadLevelTarget)
{
	DimmingService = NewLoadLevelTarget;
	InvalidateRect(hWndMainWindow,NULL,true);
	UPnPResponse_DimmingService_SetLoadLevelTarget(upnptoken);
	UPnPSetState_DimmingService_LoadLevelStatus(UPnPmicroStack,DimmingService);
}

void UPnPPresentationRequest(void* upnptoken, struct packetheader *packet)
{
	UPnPPresentationResponse(upnptoken, "HTTP/1.0 404 File not found\r\n\r\n" , 31 , 1);
}

DWORD WINAPI UPnPMain(LPVOID ptr)
{
	int i;
	char guid[20];
	char friendlyname[100];
	WSADATA wsaData;

	srand((int)GetTickCount());
	for (i=0;i<19;i++)
	{
		guid[i] = (rand() % 25) + 66;
	}
	guid[19] = 0;

	if (WSAStartup(MAKEWORD(1,1), &wsaData) != 0) {exit(1);}
	memcpy(friendlyname,"Intel MicroLight (",18);
	gethostname(friendlyname+18,70);
	memcpy(friendlyname+strlen(friendlyname),")\0",2);

	UPnPmicroStackChain = ILibCreateChain();
	UPnPmicroStack = UPnPCreateMicroStack(UPnPmicroStackChain,friendlyname,guid,"0000001",120,8056);

	/* All evented state variables MUST be initialized before UPnPStart is called. */
	UPnPSetState_SwitchPower_Status(UPnPmicroStack,SwitchPower);
	UPnPSetState_DimmingService_LoadLevelStatus(UPnPmicroStack,DimmingService);

	ILibStartChain(UPnPmicroStackChain);

	WSACleanup();
	SendMessage((HWND)ptr, WM_DESTROY, 0, 0);

	return 0;
}


text:
package org.ta4j.core.indicators;

import org.junit.Before;
import org.junit.Test;
import org.ta4j.core.Decimal;
import org.ta4j.core.TimeSeries;
import org.ta4j.core.indicators.helpers.ClosePriceIndicator;
import org.ta4j.core.mocks.MockTimeSeries;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.ta4j.core.TATestsUtils.assertDecimalEquals;

public class SmoothedRSIIndicatorTest {

    private TimeSeries data;

    @Before
    public void setUp() {
        data = new MockTimeSeries(
            50.45, 50.30, 50.20,
            50.15, 50.05, 50.06,
            50.10, 50.08, 50.03,
            50.07, 50.01, 50.14,
            50.22, 50.43, 50.50,
            50.56, 50.52, 50.70,
            50.55, 50.62, 50.90,
            50.82, 50.86, 51.20, 51.30, 51.10);
    }

    @Test
    public void rsiUsingTimeFrame14UsingClosePrice() {
        SmoothedRSIIndicator rsi = new SmoothedRSIIndicator(new ClosePriceIndicator(data), 2);

        assertDecimalEquals(rsi.getValue(2), 0.0);
        assertDecimalEquals(rsi.getValue(3), 0.0);
        assertDecimalEquals(rsi.getValue(4), 0.0);
        assertDecimalEquals(rsi.getValue(5), 9.638554217);
        assertDecimalEquals(rsi.getValue(6), 48.97959184);
        assertDecimalEquals(rsi.getValue(7), 34.12322275);
        assertDecimalEquals(rsi.getValue(8), 13.55932203);
        assertDecimalEquals(rsi.getValue(9), 55.99232982);
        assertDecimalEquals(rsi.getValue(10), 22.64443583);
        assertDecimalEquals(rsi.getValue(11), 78.39740119);
        assertDecimalEquals(rsi.getValue(12), 88.55224651);
    }

    @Test
    public void smoothedRsiFirstValueShouldBeZero() {
        SmoothedRSIIndicator rsi = new SmoothedRSIIndicator(new ClosePriceIndicator(data), 14);

        assertEquals(Decimal.ZERO, rsi.getValue(0));
    }

    @Test
    public void smoothedRsiIsNeverHundredIfLossPresentInDataSeries() {
        SmoothedRSIIndicator rsi = new SmoothedRSIIndicator(new ClosePriceIndicator(data), 3);

        assertNotEquals(Decimal.HUNDRED, rsi.getValue(14));
        assertNotEquals(Decimal.HUNDRED, rsi.getValue(15));
    }
}


text:
using android_webview::InputStream;
using android_webview::InputStreamReader;
using net::TestDelegate;
using net::TestJobInterceptor;
using net::TestNetworkDelegate;
using net::TestURLRequestContext;
using net::TestURLRequest;
using testing::DoAll;
using testing::Ge;
using testing::Gt;
using testing::InSequence;
using testing::Invoke;
using testing::InvokeWithoutArgs;
using testing::NotNull;
using testing::Return;
using testing::SaveArg;
using testing::SetArgPointee;
using testing::StrictMock;
using testing::Test;
using testing::WithArg;
using testing::WithArgs;
using testing::_;

// Some of the classes will DCHECK on a null InputStream (which is desirable).
// The workaround is to use this class. None of the methods need to be
// implemented as the mock InputStreamReader should never forward calls to the
// InputStream.
class NotImplInputStream : public InputStream {
 public:
  NotImplInputStream() {}
  virtual ~NotImplInputStream() {}
  virtual bool BytesAvailable(int* bytes_available) const {
    NOTIMPLEMENTED();
    return false;
  }
  virtual bool Skip(int64_t n, int64_t* bytes_skipped) {
    NOTIMPLEMENTED();
    return false;
  }
  virtual bool Read(net::IOBuffer* dest, int length, int* bytes_read) {
    NOTIMPLEMENTED();
    return false;
  }
};

// Required in order to create an instance of AndroidStreamReaderURLRequestJob.
class StreamReaderDelegate :
    public AndroidStreamReaderURLRequestJob::Delegate {
 public:
  StreamReaderDelegate() {}

  virtual scoped_ptr<InputStream> OpenInputStream(
      JNIEnv* env,
      const GURL& url) {
    return make_scoped_ptr<InputStream>(new NotImplInputStream());
  }

  virtual void OnInputStreamOpenFailed(net::URLRequest* request,
                                       bool* restart) {
    *restart = false;
  }

  virtual bool GetMimeType(
      JNIEnv* env,
      net::URLRequest* request,
      android_webview::InputStream* stream,
      std::string* mime_type) {
    return false;
  }

  virtual bool GetCharset(
      JNIEnv* env,
      net::URLRequest* request,
      android_webview::InputStream* stream,
      std::string* charset) {
    return false;
  }
};

class NullStreamReaderDelegate : public StreamReaderDelegate {
 public:
  NullStreamReaderDelegate() {}

  virtual scoped_ptr<InputStream> OpenInputStream(
      JNIEnv* env,
      const GURL& url) {
    return make_scoped_ptr<InputStream>(NULL);
  }
};

class MockInputStreamReader : public InputStreamReader {
 public:
  MockInputStreamReader() : InputStreamReader(new NotImplInputStream()) {}
  ~MockInputStreamReader() {}

  MOCK_METHOD1(Seek, int(const net::HttpByteRange& byte_range));
  MOCK_METHOD2(ReadRawData, int(net::IOBuffer* buffer, int buffer_size));
};

class TestStreamReaderJob : public AndroidStreamReaderURLRequestJob {
 public:
  TestStreamReaderJob(
      net::URLRequest* request,
      net::NetworkDelegate* network_delegate,
      scoped_ptr<Delegate> delegate,
      scoped_ptr<InputStreamReader> stream_reader)
      : AndroidStreamReaderURLRequestJob(request,
                                         network_delegate,
                                         delegate.Pass()),
        stream_reader_(stream_reader.Pass()) {
    message_loop_proxy_ = base::MessageLoopProxy::current();
  }

  virtual scoped_ptr<InputStreamReader> CreateStreamReader(
      InputStream* stream) {
    return stream_reader_.Pass();
  }
 protected:
  virtual ~TestStreamReaderJob() {}

  virtual base::TaskRunner* GetWorkerThreadRunner() {
    return message_loop_proxy_.get();
  }

  scoped_ptr<InputStreamReader> stream_reader_;
  scoped_refptr<base::MessageLoopProxy> message_loop_proxy_;
};

class AndroidStreamReaderURLRequestJobTest : public Test {
 public:
  AndroidStreamReaderURLRequestJobTest()
      : loop_(MessageLoop::TYPE_IO) {
  }
 protected:
  virtual void SetUp() {
    context_.set_job_factory(&factory_);
    context_.set_network_delegate(&network_delegate_);
    req_.reset(
        new TestURLRequest(GURL("content://foo"),
                           &url_request_delegate_,
                           &context_,
                           &network_delegate_));
    req_->set_method("GET");
  }

  void SetRange(net::URLRequest* req, int first_byte, int last_byte) {
    net::HttpRequestHeaders headers;
    headers.SetHeader(net::HttpRequestHeaders::kRange,
                      base::StringPrintf(
                           "bytes=%" PRIuS "-%" PRIuS,
                           first_byte, last_byte));
    req->SetExtraRequestHeaders(headers);
  }

  void SetUpTestJob(scoped_ptr<InputStreamReader> stream_reader) {
    SetUpTestJob(stream_reader.Pass(),
                 make_scoped_ptr(new StreamReaderDelegate())
                     .PassAs<AndroidStreamReaderURLRequestJob::Delegate>());
  }

  void SetUpTestJob(scoped_ptr<InputStreamReader> stream_reader,
                    scoped_ptr<AndroidStreamReaderURLRequestJob::Delegate>
                        stream_reader_delegate) {
    TestStreamReaderJob* test_stream_reader_job =
        new TestStreamReaderJob(
            req_.get(),
            &network_delegate_,
            stream_reader_delegate.Pass(),
            stream_reader.Pass());
    // The Interceptor is owned by the |factory_|.
    TestJobInterceptor* protocol_handler = new TestJobInterceptor;
    protocol_handler->set_main_intercept_job(test_stream_reader_job);
    bool set_protocol = factory_.SetProtocolHandler("http", protocol_handler);
    DCHECK(set_protocol);

    protocol_handler = new TestJobInterceptor;
    protocol_handler->set_main_intercept_job(test_stream_reader_job);
    set_protocol = factory_.SetProtocolHandler("content", protocol_handler);
    DCHECK(set_protocol);
  }

  MessageLoop loop_;
  TestURLRequestContext context_;
  android_webview::AwURLRequestJobFactory factory_;
  TestDelegate url_request_delegate_;
  TestNetworkDelegate network_delegate_;
  scoped_ptr<TestURLRequest> req_;
};

TEST_F(AndroidStreamReaderURLRequestJobTest, ReadEmptyStream) {
  scoped_ptr<StrictMock<MockInputStreamReader> > stream_reader(
      new StrictMock<MockInputStreamReader>());
  {
    InSequence s;
    EXPECT_CALL(*stream_reader, Seek(_))
        .WillOnce(Return(0));
    EXPECT_CALL(*stream_reader, ReadRawData(NotNull(), Gt(0)))
        .WillOnce(Return(0));
  }

  SetUpTestJob(stream_reader.PassAs<InputStreamReader>());

  req_->Start();

  // The TestDelegate will quit the message loop on request completion.
  MessageLoop::current()->Run();

  EXPECT_FALSE(url_request_delegate_.request_failed());
  EXPECT_EQ(1, network_delegate_.completed_requests());
  EXPECT_EQ(0, network_delegate_.error_count());
  EXPECT_EQ(200, req_->GetResponseCode());
}

TEST_F(AndroidStreamReaderURLRequestJobTest, ReadWithNullStream) {
  SetUpTestJob(scoped_ptr<InputStreamReader>(),
               make_scoped_ptr(new NullStreamReaderDelegate())
                   .PassAs<AndroidStreamReaderURLRequestJob::Delegate>());
  req_->Start();

  // The TestDelegate will quit the message loop on request completion.
  MessageLoop::current()->Run();

  // The request_failed() method is named confusingly but all it checks is
  // whether the request got as far as calling NotifyHeadersComplete.
  EXPECT_FALSE(url_request_delegate_.request_failed());
  EXPECT_EQ(1, network_delegate_.completed_requests());
  // A null input stream shouldn't result in an error. See crbug.com/180950.
  EXPECT_EQ(0, network_delegate_.error_count());
  EXPECT_EQ(404, req_->GetResponseCode());
}

TEST_F(AndroidStreamReaderURLRequestJobTest, ReadPartOfStream) {
  const int bytes_available = 128;
  const int offset = 32;
  const int bytes_to_read = bytes_available - offset;
  scoped_ptr<StrictMock<MockInputStreamReader> > stream_reader(
      new StrictMock<MockInputStreamReader>());
  {
    InSequence s;
    EXPECT_CALL(*stream_reader, Seek(_))
        .WillOnce(Return(bytes_available));
    EXPECT_CALL(*stream_reader, ReadRawData(NotNull(), Ge(bytes_to_read)))
        .WillOnce(Return(bytes_to_read/2));
    EXPECT_CALL(*stream_reader, ReadRawData(NotNull(), Ge(bytes_to_read)))
        .WillOnce(Return(bytes_to_read/2));
    EXPECT_CALL(*stream_reader, ReadRawData(NotNull(), Ge(bytes_to_read)))
        .WillOnce(Return(0));
  }

  SetUpTestJob(stream_reader.PassAs<InputStreamReader>());

  SetRange(req_.get(), offset, bytes_available);
  req_->Start();

  MessageLoop::current()->Run();

  EXPECT_FALSE(url_request_delegate_.request_failed());
  EXPECT_EQ(bytes_to_read, url_request_delegate_.bytes_received());
  EXPECT_EQ(1, network_delegate_.completed_requests());
  EXPECT_EQ(0, network_delegate_.error_count());
}

TEST_F(AndroidStreamReaderURLRequestJobTest,
       ReadStreamWithMoreAvailableThanActual) {
  const int bytes_available_reported = 190;
  const int bytes_available = 128;
  const int offset = 0;
  const int bytes_to_read = bytes_available - offset;
  scoped_ptr<StrictMock<MockInputStreamReader> > stream_reader(
      new StrictMock<MockInputStreamReader>());
  {
    InSequence s;
    EXPECT_CALL(*stream_reader, Seek(_))
        .WillOnce(Return(bytes_available_reported));
    EXPECT_CALL(*stream_reader, ReadRawData(NotNull(), Ge(bytes_to_read)))
        .WillOnce(Return(bytes_available));
    EXPECT_CALL(*stream_reader, ReadRawData(NotNull(), Ge(bytes_to_read)))
        .WillOnce(Return(0));
  }

  SetUpTestJob(stream_reader.PassAs<InputStreamReader>());

  SetRange(req_.get(), offset, bytes_available_reported);
  req_->Start();

  MessageLoop::current()->Run();

  EXPECT_FALSE(url_request_delegate_.request_failed());
  EXPECT_EQ(bytes_to_read, url_request_delegate_.bytes_received());
  EXPECT_EQ(1, network_delegate_.completed_requests());
  EXPECT_EQ(0, network_delegate_.error_count());
}

TEST_F(AndroidStreamReaderURLRequestJobTest, DeleteJobMidWaySeek) {
  const int offset = 20;
  const int bytes_available = 128;
  base::RunLoop loop;
  scoped_ptr<StrictMock<MockInputStreamReader> > stream_reader(
      new StrictMock<MockInputStreamReader>());
  EXPECT_CALL(*stream_reader, Seek(_))
      .WillOnce(DoAll(InvokeWithoutArgs(&loop, &base::RunLoop::Quit),
                      Return(bytes_available)));
  ON_CALL(*stream_reader, ReadRawData(_, _))
      .WillByDefault(Return(0));

  SetUpTestJob(stream_reader.PassAs<InputStreamReader>());

  SetRange(req_.get(), offset, bytes_available);
  req_->Start();

  loop.Run();

  EXPECT_EQ(0, network_delegate_.completed_requests());
  req_->Cancel();
  EXPECT_EQ(1, network_delegate_.completed_requests());
}

TEST_F(AndroidStreamReaderURLRequestJobTest, DeleteJobMidWayRead) {
  const int offset = 20;
  const int bytes_available = 128;
  base::RunLoop loop;
  scoped_ptr<StrictMock<MockInputStreamReader> > stream_reader(
      new StrictMock<MockInputStreamReader>());
  net::CompletionCallback read_completion_callback;
  EXPECT_CALL(*stream_reader, Seek(_))
      .WillOnce(Return(bytes_available));
  EXPECT_CALL(*stream_reader, ReadRawData(_, _))
      .WillOnce(DoAll(InvokeWithoutArgs(&loop, &base::RunLoop::Quit),
                      Return(bytes_available)));

  SetUpTestJob(stream_reader.PassAs<InputStreamReader>());

  SetRange(req_.get(), offset, bytes_available);
  req_->Start();

  loop.Run();

  EXPECT_EQ(0, network_delegate_.completed_requests());
  req_->Cancel();
  EXPECT_EQ(1, network_delegate_.completed_requests());
}


text:
#ifndef POLYSHAPE_H
#define POLYSHAPE_H

#include "diatypes.h"
#include "object.h"
#include "boundingbox.h"

#define HANDLE_CORNER (HANDLE_CUSTOM1)

/* This is a subclass of DiaObject used to help implementing objects
 * that form a polygon-like shape of line-segments.
 */
struct _PolyShape {
  /* DiaObject must be first because this is a 'subclass' of it. */
  DiaObject object;

  int numpoints; /* >= 3 */
  Point *points;

  ElementBBExtras extra_spacing;
};

void polyshape_update_data(PolyShape *poly);
void polyshape_update_boundingbox(PolyShape *poly);
void polyshape_simple_draw(PolyShape *poly, DiaRenderer *renderer, real width);
void polyshape_init(PolyShape *poly, int num_points);
void polyshape_set_points(PolyShape *poly, int num_points, Point *points);
void polyshape_destroy(PolyShape *poly);
void polyshape_copy(PolyShape *from, PolyShape *to);
void polyshape_save(PolyShape *poly, ObjectNode obj_node);
void polyshape_load(PolyShape *poly, ObjectNode obj_node);  /* NOTE: Does object_init() */
ObjectChange *polyshape_add_point(PolyShape *poly, int segment, Point *point);
ObjectChange *polyshape_remove_point(PolyShape *poly, int point);
ObjectChange *polyshape_move_handle(PolyShape *poly, Handle *id,
				    Point *to, ConnectionPoint *cp,
				    HandleMoveReason reason,
				    ModifierKeys modifiers);
ObjectChange *polyshape_move(PolyShape *poly, Point *to);
real polyshape_distance_from(PolyShape *poly, Point *point,
			     real line_width);
Handle *polyshape_closest_handle(PolyShape *poly, Point *point);
int polyshape_closest_segment(PolyShape *poly, Point *point,
			      real line_width);

#define POLYSHAPE_COMMON_PROPERTIES \
  OBJECT_COMMON_PROPERTIES, \
  { "poly_points", PROP_TYPE_POINTARRAY, 0, "polyshape points", NULL} \

#define POLYSHAPE_COMMON_PROPERTIES_OFFSETS \
  OBJECT_COMMON_PROPERTIES_OFFSETS, \
  { "poly_points", PROP_TYPE_POINTARRAY, \
     offsetof(PolyShape,points), offsetof(PolyShape,numpoints)} \

#endif /* POLY_CONN_H */