text:
package com.ashigeru.eclipse.internal.codereading.ui.handlers;

import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.window.Window;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.editors.text.EditorsUI;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.ui.part.AbstractMultiEditor;
import org.eclipse.ui.part.MultiPageEditorPart;
import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.ui.texteditor.ITextEditor;

import com.ashigeru.eclipse.codereading.core.utils.DocumentUtils;
import com.ashigeru.eclipse.internal.codereading.ui.Activator;
import com.ashigeru.eclipse.internal.codereading.ui.LogUtil;
import com.ashigeru.eclipse.internal.codereading.ui.dialogs.LogEditDialog;

/**
 * Appends source code snippet into log.
 */
public class LogSnippetHandler extends AbstractHandler {

    static final String DIALOG_KEY_LOG_FILE = "logfile"; //$NON-NLS-1$

    @Override
    public Object execute(ExecutionEvent event) throws ExecutionException {
        IEditorPart editor = getEditor(event);
        if (editor == null) {
            return null;
        }
        File lastLogFile = loadLogFile();
        List<String> template = getTemplate(editor);
        if (template == null) {
            return null;
        }

        LogEditDialog dialog = new LogEditDialog(HandlerUtil.getActiveShellChecked(event), lastLogFile, template);
        if (dialog.open() != Window.OK) {
            return null;
        }

        File resultFile = dialog.getResultFile();
        List<String> resultContents = dialog.getResultContents();
        try {
            appendLog(resultFile, resultContents);
        } catch (IOException e) {
            IStatus status = LogUtil.log(IStatus.ERROR, e, MessageFormat.format(
                    "Failed to append to log file: {0}",
                    resultFile));
            MessageDialog.openError(
                    HandlerUtil.getActiveShellChecked(event),
                    "Error",
                    status.getMessage());
        }
        saveLogFile(resultFile);
        return null;
    }

    private IEditorPart getEditor(ExecutionEvent event) {
        assert event != null;
        return HandlerUtil.getActiveEditor(event);
    }

    private List<String> getTemplate(IEditorPart editor) {
        assert editor != null;
        IPath path = getPath(editor);
        IDocument document = getDocument(editor);
        IRegion region = getRegion(editor);
        String location = getLocation(path, document, region);
        List<String> lines = getContents(document, region);
        String language = getLanguageKind(path, document, region);

        // FIXME meta-template
        List<String> results = new ArrayList<String>();
        results.add(""); //$NON-NLS-1$
        if (location != null || lines != null) {
            results.add(""); //$NON-NLS-1$
            if (language == null) {
                results.add("```"); //$NON-NLS-1$
            } else {
                results.add(String.format("```%s", language)); //$NON-NLS-1$
            }
            if (location != null) {
                results.add(String.format("// %s", location)); //$NON-NLS-1$
            }
            if (lines != null) {
                results.addAll(lines);
            }
            results.add("```"); //$NON-NLS-1$
            results.add(""); //$NON-NLS-1$
        }
        results.add("********"); //$NON-NLS-1$
        return results;
    }

    private IPath getPath(IEditorPart editor) {
        assert editor != null;
        IEditorInput input = editor.getEditorInput();
        IFile file = (IFile) input.getAdapter(IFile.class);
        if (file != null) {
            IProject project = file.getProject();
            if (project != null) {
                return Path.fromPortableString(project.getName()).append(file.getProjectRelativePath());
            } else {
                return file.getFullPath();
            }
        }
        IPath path = (IPath) input.getAdapter(IPath.class);
        if (path != null) {
            return path;
        }
        String name = input.getName();
        if (name != null) {
            return Path.fromPortableString(name);
        }
        return null;
    }

    private IDocument getDocument(IEditorPart editor) {
        assert editor != null;
        if (editor instanceof ITextEditor) {
            IDocumentProvider provider = ((ITextEditor) editor).getDocumentProvider();
            if (provider != null) {
                return provider.getDocument(editor.getEditorInput());
            }
        } else if (editor instanceof MultiPageEditorPart) {
            IEditorPart[] children = ((MultiPageEditorPart) editor).findEditors(editor.getEditorInput());
            for (IEditorPart child : children) {
                IDocument document = getDocument(child);
                if (document != null) {
                    return document;
                }
            }
        } else if (editor instanceof AbstractMultiEditor) {
            IEditorPart active = ((AbstractMultiEditor) editor).getActiveEditor();
            return getDocument(active);
        }
        return null;
    }

    private IRegion getRegion(IEditorPart editor) {
        assert editor != null;
        ISelectionProvider provider = editor.getSite().getSelectionProvider();
        if (provider != null) {
            ISelection selection = provider.getSelection();
            if (selection instanceof ITextSelection) {
                ITextSelection ts = (ITextSelection) selection;
                int offset = ts.getOffset();
                int length = ts.getLength();
                if (offset >= 0 && length >= 0) {
                    return new Region(offset, length);
                }
            }
        }
        return null;
    }

    private String getLocation(IPath path, IDocument document, IRegion region) {
        if (path == null) {
            return null;
        }
        if (document != null && region != null) {
            int lineNumber = getLineNumber(document, region);
            if (lineNumber >= 0) {
                return String.format("%s:L%d", path.toPortableString(), lineNumber + 1); //$NON-NLS-1$
            }
        }
        return path.toPortableString();
    }

    private int getLineNumber(IDocument document, IRegion region) {
        assert document != null;
        assert region != null;
        try {
            return document.getLineOfOffset(region.getOffset());
        } catch (BadLocationException e) {
            LogUtil.log(IStatus.ERROR, e, MessageFormat.format(
                    "Failed to compute line number: {0}",
                    region));
            return -1;
        }
    }

    /**
     * Infers programming language kind of the target.
     * @param path the target path
     * @param document the target document
     * @param region the selected region
     * @return the programming language kind, or {@code null} if it is not inferred
     */
    private String getLanguageKind(IPath path, IDocument document, IRegion region) {
        if (path == null) {
            return null;
        }
        String extension = path.getFileExtension();
        if (extension != null) {
            return extension.toLowerCase();
        }
        return null;
    }

    private List<String> getContents(IDocument document, IRegion region) {
        if (document == null || region == null) {
            return null;
        }
        int tabSize = getTabSize();
        try {
            IRegion block = DocumentUtils.toLines(document, region);
            List<String> lines = DocumentUtils.getLines(document, block);
            lines = DocumentUtils.extractHorizontalTabs(lines, tabSize);
            lines =  DocumentUtils.trimLeadingWhitespaces(lines);
            return lines;
        } catch (BadLocationException e) {
            LogUtil.log(IStatus.ERROR, e, MessageFormat.format(
                    "Failed to obtain line contents: {0}",
                    region));
            return null;
        }
    }

    private int getTabSize() {
        IPreferenceStore prefs = EditorsUI.getPreferenceStore();
        int value = prefs.getInt(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH);
        return value;
    }

    private File loadLogFile() {
        IDialogSettings settings = Activator.getDialogSettings(getClass().getSimpleName());
        String value = settings.get(DIALOG_KEY_LOG_FILE);
        if (value == null) {
            return null;
        }
        return new File(value);
    }

    private void saveLogFile(File file) {
        IDialogSettings settings = Activator.getDialogSettings(getClass().getSimpleName());
        if (file != null) {
            settings.put(DIALOG_KEY_LOG_FILE, file.getPath());
        }
    }

    private void appendLog(File file, List<String> lines) throws IOException {
        String lineBreak = getLogLineBreak();

        // FIXME out of UI thread
        Appendable appendable = openLogFile(file);
        try {
            for (String line : lines) {
                appendable.append(line);
                appendable.append(lineBreak);
            }
        } finally {
            if (appendable instanceof Closeable) {
                ((Closeable) appendable).close();
            }
        }
    }

    private Charset getLogFileEncoding() {
        // FIXME make it configurable
        return Charset.forName("UTF-8"); //$NON-NLS-1$
    }

    private String getLogLineBreak() {
        // FIXME make it configurable
        return String.format("%n"); //$NON-NLS-1$
    }

    private Writer openLogFile(File file) throws IOException {
        Charset encoding = getLogFileEncoding();
        File parent = file.getParentFile();
        if (parent.mkdirs() == false && parent.isDirectory() == false) {
            throw new IOException(MessageFormat.format(
                    "Failed to create directory for create log file: {0}",
                    parent));
        }
        return new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true), encoding));
    }
}


text:
namespace blink {

namespace {

class MockFunction : public ScriptFunction {
 public:
  static testing::StrictMock<MockFunction>* Create(ScriptState* script_state) {
    return MakeGarbageCollected<testing::StrictMock<MockFunction>>(
        script_state);
  }

  v8::Local<v8::Function> Bind() { return BindToV8Function(); }

  MOCK_METHOD1(Call, ScriptValue(ScriptValue));

 protected:
  explicit MockFunction(ScriptState* script_state)
      : ScriptFunction(script_state) {}
};

template <class T>
class DecoderTemplateTest : public testing::Test {
 public:
  DecoderTemplateTest() = default;
  ~DecoderTemplateTest() override = default;

  typename T::ConfigType* CreateConfig();
  typename T::InitType* CreateInit(MockFunction* output_callback,
                                   MockFunction* error_callback);

  T* CreateDecoder(ScriptState*, const typename T::InitType*, ExceptionState&);
};

template <>
AudioDecoderConfig* DecoderTemplateTest<AudioDecoder>::CreateConfig() {
  auto* config = MakeGarbageCollected<AudioDecoderConfig>();
  config->setCodec("mp3");
  config->setSampleRate(48000);
  config->setNumberOfChannels(2);
  return config;
}

template <>
AudioDecoder* DecoderTemplateTest<AudioDecoder>::CreateDecoder(
    ScriptState* script_state,
    const AudioDecoderInit* init,
    ExceptionState& exception_state) {
  return MakeGarbageCollected<AudioDecoder>(script_state, init,
                                            exception_state);
}

template <>
AudioDecoderInit* DecoderTemplateTest<AudioDecoder>::CreateInit(
    MockFunction* output_callback,
    MockFunction* error_callback) {
  auto* init = MakeGarbageCollected<AudioDecoderInit>();
  init->setOutput(V8AudioDataOutputCallback::Create(output_callback->Bind()));
  init->setError(V8WebCodecsErrorCallback::Create(error_callback->Bind()));
  return init;
}

template <>
VideoDecoderConfig* DecoderTemplateTest<VideoDecoder>::CreateConfig() {
  auto* config = MakeGarbageCollected<VideoDecoderConfig>();
  config->setCodec("vp09.00.10.08");
  return config;
}

template <>
VideoDecoderInit* DecoderTemplateTest<VideoDecoder>::CreateInit(
    MockFunction* output_callback,
    MockFunction* error_callback) {
  auto* init = MakeGarbageCollected<VideoDecoderInit>();
  init->setOutput(V8VideoFrameOutputCallback::Create(output_callback->Bind()));
  init->setError(V8WebCodecsErrorCallback::Create(error_callback->Bind()));
  return init;
}

template <>
VideoDecoder* DecoderTemplateTest<VideoDecoder>::CreateDecoder(
    ScriptState* script_state,
    const VideoDecoderInit* init,
    ExceptionState& exception_state) {
  return MakeGarbageCollected<VideoDecoder>(script_state, init,
                                            exception_state);
}

using DecoderTemplateImplementations =
    testing::Types<AudioDecoder, VideoDecoder>;

TYPED_TEST_SUITE(DecoderTemplateTest, DecoderTemplateImplementations);

TYPED_TEST(DecoderTemplateTest, BasicConstruction) {
  V8TestingScope v8_scope;

  auto* output_callback = MockFunction::Create(v8_scope.GetScriptState());
  auto* error_callback = MockFunction::Create(v8_scope.GetScriptState());

  auto* decoder =
      this->CreateDecoder(v8_scope.GetScriptState(),
                          this->CreateInit(output_callback, error_callback),
                          v8_scope.GetExceptionState());
  ASSERT_TRUE(decoder);
  EXPECT_FALSE(v8_scope.GetExceptionState().HadException());
}

TYPED_TEST(DecoderTemplateTest, ResetDuringFlush) {
  V8TestingScope v8_scope;

  // Create a decoder.
  auto* output_callback = MockFunction::Create(v8_scope.GetScriptState());
  auto* error_callback = MockFunction::Create(v8_scope.GetScriptState());

  auto* decoder =
      this->CreateDecoder(v8_scope.GetScriptState(),
                          this->CreateInit(output_callback, error_callback),
                          v8_scope.GetExceptionState());
  ASSERT_TRUE(decoder);
  ASSERT_FALSE(v8_scope.GetExceptionState().HadException());

  // Configure the decoder.
  decoder->configure(this->CreateConfig(), v8_scope.GetExceptionState());
  ASSERT_FALSE(v8_scope.GetExceptionState().HadException());

  // flush() to ensure configure completes.
  {
    auto promise = decoder->flush(v8_scope.GetExceptionState());
    ASSERT_FALSE(v8_scope.GetExceptionState().HadException());

    ScriptPromiseTester tester(v8_scope.GetScriptState(), promise);
    tester.WaitUntilSettled();
    ASSERT_TRUE(tester.IsFulfilled());
  }

  // flush() again but reset() before it gets started.
  {
    auto promise = decoder->flush(v8_scope.GetExceptionState());
    ASSERT_FALSE(v8_scope.GetExceptionState().HadException());
    decoder->reset(v8_scope.GetExceptionState());
    ASSERT_FALSE(v8_scope.GetExceptionState().HadException());

    ScriptPromiseTester tester(v8_scope.GetScriptState(), promise);
    tester.WaitUntilSettled();
    ASSERT_TRUE(tester.IsRejected());
  }
}

#if defined(OS_LINUX) && defined(THREAD_SANITIZER)
// https://crbug.com/1247967
#define MAYBE_CodecReclamation DISABLED_CodecReclamation
#else
#define MAYBE_CodecReclamation CodecReclamation
#endif
// Ensures codecs can be reclaimed in a configured or unconfigured state.
TYPED_TEST(DecoderTemplateTest, MAYBE_CodecReclamation) {
  V8TestingScope v8_scope;

  // Create a decoder.
  auto* output_callback = MockFunction::Create(v8_scope.GetScriptState());
  auto* error_callback = MockFunction::Create(v8_scope.GetScriptState());

  auto* decoder =
      this->CreateDecoder(v8_scope.GetScriptState(),
                          this->CreateInit(output_callback, error_callback),
                          v8_scope.GetExceptionState());
  ASSERT_TRUE(decoder);
  ASSERT_FALSE(v8_scope.GetExceptionState().HadException());

  // Simulate backgrounding to enable reclamation.
  if (!decoder->is_backgrounded_for_testing()) {
    decoder->SimulateLifecycleStateForTesting(
        scheduler::SchedulingLifecycleState::kHidden);
    DCHECK(decoder->is_backgrounded_for_testing());
  }

  // Configure the decoder.
  decoder->configure(this->CreateConfig(), v8_scope.GetExceptionState());
  ASSERT_FALSE(v8_scope.GetExceptionState().HadException());

  ASSERT_TRUE(decoder->IsReclamationTimerActiveForTesting());

  // Resets count as activity for decoders.
  decoder->reset(v8_scope.GetExceptionState());
  ASSERT_TRUE(decoder->IsReclamationTimerActiveForTesting());

  // Reclaiming a reset decoder should not call the error callback.
  EXPECT_CALL(*error_callback, Call(testing::_)).Times(0);
  decoder->SimulateCodecReclaimedForTesting();
  ASSERT_FALSE(decoder->IsReclamationTimerActiveForTesting());

  testing::Mock::VerifyAndClearExpectations(error_callback);

  // Configure the decoder once more.
  decoder->configure(this->CreateConfig(), v8_scope.GetExceptionState());
  ASSERT_FALSE(v8_scope.GetExceptionState().HadException());
  ASSERT_TRUE(decoder->IsReclamationTimerActiveForTesting());

  // Reclaiming a configured decoder should call the error callback.
  EXPECT_CALL(*error_callback, Call(testing::_)).Times(1);
  decoder->SimulateCodecReclaimedForTesting();
  ASSERT_FALSE(decoder->IsReclamationTimerActiveForTesting());

  testing::Mock::VerifyAndClearExpectations(error_callback);
}

}  // namespace

}  // namespace blink

redpajama_set_name: RedPajamaGithub


text:
This page explains how to managing GoBGP with your favorite Language.
You can use any language supported by [gRPC](http://www.grpc.io/) (10
languages are supported now). This page gives an example in Python,
Ruby, and C++. It assumes that you use Ubuntu 14.04 (64bit).

## Contents

- [Python](#python)
- [Ruby](#ruby)
- [C++](#cpp)

##  Python

### Installing LinuxBrew

We use LinuxBrew to simplify the instruction.
```bash
$ sudo apt-get update
$ sudo apt-get install -y build-essential curl git python-dev python-pip m4 ruby
$ ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/linuxbrew/go/install)"
$ export PATH=$HOME/.linuxbrew/bin:$PATH
$ brew doctor
```
It's useful to add '$HOME/.linuxbrew/bin' to your PATH environment variable.

And then add configuration to load libs under '.linuxbrew'.
```
$ echo "$HOME/.linuxbrew/lib" | sudo tee /etc/ld.so.conf.d/grpc.conf
$ sudo ldconfig
```

### Installing gRPC and Python Libraries

We install gRPC and python liblaries in python virtual environment by using LinuxBrew.
These steps are based on [gRPC HomeBrew](https://github.com/grpc/homebrew-grpc).

```bash
$ sudo apt-get update
$ sudo apt-get install python-virtualenv
$ cd $GOPATH/src/github.com/osrg/gobgp/tools/grpc/python
$ virtualenv venv
$ source ./venv/bin/activate
$ curl -fsSL https://goo.gl/getgrpc | bash -s python
$ sudo ldconfig
```

### Generating Stub Code

We need to generate stub code GoBGP at first.
```bash
$ cd $GOPATH/src/github.com/osrg/gobgp/tools/grpc/python
$ GOBGP_API=$GOPATH/src/github.com/osrg/gobgp/api
$ protoc  -I $GOBGP_API --python_out=. --grpc_out=. --plugin=protoc-gen-grpc=`which grpc_python_plugin` $GOBGP_API/gobgp.proto
```

### Get Neighbor

Here is an example for getting neighbor's information and we assumed that it's created in 'get_neighbor.py' under '$GOPATH/src/github.com/osrg/gobgp/tools/grpc/python'.
```python
import gobgp_pb2
import sys

_TIMEOUT_SECONDS = 10

def run(gobgpd_addr, neighbor_addr):
    with gobgp_pb2.early_adopter_create_GobgpApi_stub(gobgpd_addr, 8080) as stub:
        peer = stub.GetNeighbor(gobgp_pb2.Arguments(rf=4, name=neighbor_addr), _TIMEOUT_SECONDS)
        print("BGP neighbor is %s, remote AS %d" % (peer.conf.remote_ip, peer.conf.remote_as))
        print("  BGP version 4, remote router ID %s" % ( peer.conf.id))
        print("  BGP state = %s, up for %s" % ( peer.info.bgp_state, peer.info.uptime))
        print("  BGP OutQ = %d, Flops = %d" % (peer.info.out_q, peer.info.flops))
        print("  Hold time is %d, keepalive interval is %d seconds" % ( peer.info.negotiated_holdtime, peer.info.keepalive_interval))
        print("  Configured hold time is %d, keepalive interval is %d seconds" % ( peer.conf.holdtime, peer.conf.keepalive_interval))
        print("")

if __name__ == '__main__':
    gobgp = sys.argv[1]
    neighbor = sys.argv[2]
    run(gobgp, neighbor)
```

We need to import gobgp_pb2 and call 'early_adopter_create_GobgpApi_stub' in your code.

Let's run this script.

```bash
$ source ./venv/bin/activate
(venv)$ python get_neighbor.py 10.0.255.1 10.0.0.1
BGP neighbor is 10.0.0.1, remote AS 65001
  BGP version 4, remote router ID 192.168.0.1
  BGP state = BGP_FSM_ESTABLISHED, up for 9042
  BGP OutQ = 0, Flops = 0
  Hold time is 30, keepalive interval is 10 seconds
  Configured hold time is 30, keepalive interval is 10 seconds

D0821 12:31:07.821508149   91029 iomgr.c:119]                Waiting for 1 iomgr objects to be destroyed and executing final callbacks

```

We got neighbor information successfully.

##  Ruby

### Installing LinuxBrew

See [python](#python).

### Installing gRPC and Ruby Libraries

```bash
$ curl -fsSL https://goo.gl/getgrpc | bash -s ruby
$ sudo ldconfig
```

### Generating Stub Code

We need to generate stub code GoBGP at first.
```bash
$ cd $GOPATH/src/github.com/osrg/gobgp/tools/grpc/ruby
$ GOBGP_API=$GOPATH/src/github.com/osrg/gobgp/api
$ protoc  -I $GOBGP_API --ruby_out=. --grpc_out=. --plugin=protoc-gen-grpc=`which grpc_ruby_plugin` $GOBGP_API/gobgp.proto
```

### Get Neighbor

Here is an example for getting neighbor's information.
```ruby
require 'gobgp'
require 'gobgp_services'

host = 'localhost'
host = ARGV[0] if ARGV.length > 0

stub = Api::Grpc::Stub.new("#{host}:8080")
arg = Api::Arguments.new()
stub.get_neighbors(arg).each do |n|
    puts "BGP neighbor is #{n.conf.remote_ip}, remote AS #{n.conf.remote_as}"
    puts "\tBGP version 4, remote route ID #{n.conf.id}"
    puts "\tBGP state = #{n.info.bgp_state}, up for #{n.info.uptime}"
    puts "\tBGP OutQ = #{n.info.out_q}, Flops = #{n.info.flops}"
    puts "\tHold time is #{n.info.negotiated_holdtime}, keepalive interval is #{n.info.keepalive_interval} seconds"
    puts "\tConfigured hold time is #{n.conf.holdtime}"
end
```

Let's run this script.

```bash
$ruby -I . ./get_neighbors.rb
BGP neighbor is 192.168.10.2, remote AS 65001
    BGP version 4, remote route ID <nil>
    BGP state = BGP_FSM_ACTIVE, up for 0
    BGP OutQ = 0, Flops = 0
    Hold time is 0, keepalive interval is 0 seconds
    Configured hold time is 90
BGP neighbor is 192.168.10.3, remote AS 65001
    BGP version 4, remote route ID <nil>
    BGP state = BGP_FSM_ACTIVE, up for 0
    BGP OutQ = 0, Flops = 0
    Hold time is 0, keepalive interval is 0 seconds
    Configured hold time is 90
D0827 18:43:24.628846574    3379 iomgr.c:119] Waiting for 1 iomgr objects to be destroyed and executing final callbacks
```

##  C++

For gRPC we need so much dependencies, please make coffee and be ready!

### Install ProtoBuffers:
```bash
apt-get update
apt-get install -y gcc make autoconf automake git libtool g++ curl

cd /usr/src
wget https://github.com/google/protobuf/archive/v3.0.0-alpha-4.tar.gz
tar -xf v3.0.0-alpha-4.tar.gz
cd protobuf-3.0.0-alpha-4/
./autogen.sh
./configure --prefix=/opt/protobuf_3.0.0_alpha4
make -j 4
make install
```

### Install gRPC:
```bash
apt-get update
apt-get install -y gcc make autoconf automake git libtool g++ python-all-dev python-virtualenv

cd /usr/src/
git clone https://github.com/grpc/grpc.git
cd grpc
git submodule update --init
make -j 4
make install prefix=/opt/grpc
```

Add libs to the system path:
```bash
echo "/opt/grpc/lib" > /etc/ld.so.conf.d/grpc.conf
echo "/opt/protobuf_3.0.0_alpha4/lib" > /etc/ld.so.conf.d/protobuf.conf
ldconfig
```

Clone this repository and build API example:
```bash
export PATH="$PATH:/opt//grpc/bin:/opt/protobuf_3.0.0_alpha4/bin/"

cd /usr/src
git clone https://github.com/osrg/gobgp.git
cp gobgp/api/gobgp.proto gobgp/tools/grpc/cpp/gobgp_api_client.proto
cd gobgp/tools/grpc/cpp
make
```

### Let's run it:
```bash
./gobgp_api_client
We received: Peer AS: 65001
Peer router id: 213.133.111.200
Peer flops: 0
BGP state: BGP_FSM_ESTABLISHED
```


text:
using namespace std;

class Solution {
public:
	string longestPalindrome(string s) {
		string longest;

		size_t str_len = s.length();

		for (size_t i = 0; i < str_len; ++i) {
			for (size_t j = i; j < str_len; ++j) {
				string substr = s.substr(i, j - i + 1);
				if (isPalindromic(substr)) {
					if (substr.length() > longest.length()) {
						longest = substr;
					}
				}
			}
		}

		return longest;
	}

private:
	bool isPalindromic(string s) {
		size_t first = 0;
		size_t end = s.length() - 1;

		while (first < end) {
			if (s[first] != s[end]) {
				return false;
			}

			first++;
			end--;
		}

		return true;
	}

};

int main()
{
	Solution s;

	cout << s.longestPalindrome("gphyvqruxjmwhonjjrgumxjhfyupajxbjgthzdvrdqmdouuukeaxhjumkmmhdglqrrohydrmbvtuwstgkobyzjjtdtjroqpyusfsbjlusekghtfbdctvgmqzeybnwzlhdnhwzptgkzmujfldoiejmvxnorvbiubfflygrkedyirienybosqzrkbpcfidvkkafftgzwrcitqizelhfsruwmtrgaocjcyxdkovtdennrkmxwpdsxpxuarhgusizmwakrmhdwcgvfljhzcskclgrvvbrkesojyhofwqiwhiupujmkcvlywjtmbncurxxmpdskupyvvweuhbsnanzfioirecfxvmgcpwrpmbhmkdtckhvbxnsbcifhqwjjczfokovpqyjmbywtpaqcfjowxnmtirdsfeujyogbzjnjcmqyzciwjqxxgrxblvqbutqittroqadqlsdzihngpfpjovbkpeveidjpfjktavvwurqrgqdomiibfgqxwybcyovysydxyyymmiuwovnevzsjisdwgkcbsookbarezbhnwyqthcvzyodbcwjptvigcphawzxouixhbpezzirbhvomqhxkfdbokblqmrhhioyqubpyqhjrnwhjxsrodtblqxkhezubprqftrqcyrzwywqrgockioqdmzuqjkpmsyohtlcnesbgzqhkalwixfcgyeqdzhnnlzawrdgskurcxfbekbspupbduxqxjeczpmdvssikbivjhinaopbabrmvscthvoqqbkgekcgyrelxkwoawpbrcbszelnxlyikbulgmlwyffurimlfxurjsbzgddxbgqpcdsuutfiivjbyqzhprdqhahpgenjkbiukurvdwapuewrbehczrtswubthodv") << endl;

	return 0;
}


text:
module FinanceMath
  VERSION = "1.0.5"
end


text:
!function e(t, n, r) {
    function s(o, u) {
        if (!n[o]) {
            if (!t[o]) {
                var a = "function" == typeof require && require;
                if (!u && a)return a(o, !0);
                if (i)return i(o, !0);
                throw new Error("Cannot find module '" + o + "'")
            }
            var f = n[o] = {exports: {}};
            t[o][0].call(f.exports, function (e) {
                var n = t[o][1][e];
                return s(n ? n : e)
            }, f, f.exports, e, t, n, r)
        }
        return n[o].exports
    }

    for (var i = "function" == typeof require && require, o = 0; o < r.length; o++)s(r[o]);
    return s
}({
    1: [function (require, module, exports) {
        "use strict";
        function load(location, callback) {
            var xhr;
            xhr = window.XMLHttpRequest ? new XMLHttpRequest : new ActiveXObject("Microsoft.XMLHTTP"), xhr.open("GET", location, !0), xhr.onreadystatechange = function () {
                if (200 === xhr.status && 4 === xhr.readyState)try {
                    callback(null, JSON.parse(xhr.responseText))
                } catch (err) {
                    callback(err, null)
                }
            }, xhr.send()
        }

        module.exports = {load: load}
    }, {}],
    2: [function (require, module, exports) {
        "use strict";
        module.exports = function OptionsValidator(params) {
            function validateParams(params) {
                return params ? void 0 !== params.required && params.required instanceof Array : !1
            }

            if (!validateParams(params))throw new Error("-- OptionsValidator: required options missing");
            if (!(this instanceof OptionsValidator))return new OptionsValidator(params);
            var requiredOptions = params.required;
            this.getRequiredOptions = function () {
                return requiredOptions
            }, this.validate = function (parameters) {
                var errors = [];
                return requiredOptions.forEach(function (requiredOptionName) {
                    void 0 === parameters[requiredOptionName] && errors.push(requiredOptionName)
                }), errors
            }
        }
    }, {}],
    3: [function (require, module, exports) {
        "use strict";
        function put(data) {
            return isObject(data) ? addObject(data) : isArray(data) ? addArray(data) : void 0
        }

        function clear() {
            return data.length = 0, data
        }

        function get() {
            return data
        }

        function isObject(obj) {
            return !!obj && "[object Object]" === Object.prototype.toString.call(obj)
        }

        function isArray(obj) {
            return !!obj && "[object Array]" === Object.prototype.toString.call(obj)
        }

        function addObject(_data) {
            return data.push(_data), data
        }

        function addArray(_data) {
            for (var added = [], i = 0; i < _data.length; i++)isObject(_data[i]) && added.push(addObject(_data[i]));
            return added
        }

        function search(crit) {
            return crit ? findMatches(data, crit, opt.searchStrategy, opt) : []
        }

        function setOptions(_opt) {
            opt = _opt || {}, opt.fuzzy = _opt.fuzzy || !1, opt.limit = _opt.limit || 10, opt.searchStrategy = _opt.fuzzy ? FuzzySearchStrategy : LiteralSearchStrategy
        }

        function findMatches(data, crit, strategy, opt) {
            for (var matches = [], i = 0; i < data.length && matches.length < opt.limit; i++) {
                var match = findMatchesInObject(data[i], crit, strategy, opt);
                match && matches.push(match)
            }
            return matches
        }

        function findMatchesInObject(obj, crit, strategy, opt) {
            for (var key in obj)if (!isExcluded(obj[key], opt.exclude) && strategy.matches(obj[key], crit))return obj
        }

        function isExcluded(term, excludedTerms) {
            var excluded = !1;
            excludedTerms = excludedTerms || [];
            for (var i = 0; i < excludedTerms.length; i++) {
                var excludedTerm = excludedTerms[i];
                !excluded && new RegExp(term).test(excludedTerm) && (excluded = !0)
            }
            return excluded
        }

        module.exports = {put: put, clear: clear, get: get, search: search, setOptions: setOptions};
        var FuzzySearchStrategy = require("./SearchStrategies/FuzzySearchStrategy"), LiteralSearchStrategy = require("./SearchStrategies/LiteralSearchStrategy"), data = [], opt = {};
        opt.fuzzy = !1, opt.limit = 10, opt.searchStrategy = opt.fuzzy ? FuzzySearchStrategy : LiteralSearchStrategy
    }, {"./SearchStrategies/FuzzySearchStrategy": 4, "./SearchStrategies/LiteralSearchStrategy": 5}],
    4: [function (require, module, exports) {
        "use strict";
        function FuzzySearchStrategy() {
            function fuzzyRegexFromString(string) {
                return new RegExp(string.split("").join(".*?"), "gi")
            }

            this.matches = function (string, crit) {
                return "string" != typeof string ? !1 : (string = string.trim(), !!fuzzyRegexFromString(crit).test(string))
            }
        }

        module.exports = new FuzzySearchStrategy
    }, {}],
    5: [function (require, module, exports) {
        "use strict";
        function LiteralSearchStrategy() {
            function matchesString(string, crit) {
                return string.toLowerCase().indexOf(crit.toLowerCase()) >= 0
            }

            this.matches = function (string, crit) {
                return "string" != typeof string ? !1 : (string = string.trim(), matchesString(string, crit))
            }
        }

        module.exports = new LiteralSearchStrategy
    }, {}],
    6: [function (require, module, exports) {
        "use strict";
        function setOptions(_options) {
            options.pattern = _options.pattern || options.pattern, options.template = _options.template || options.template, "function" == typeof _options.middleware && (options.middleware = _options.middleware)
        }

        function compile(data) {
            return options.template.replace(options.pattern, function (match, prop) {
                var value = options.middleware(prop, data[prop], options.template);
                return void 0 !== value ? value : data[prop] || match
            })
        }

        module.exports = {compile: compile, setOptions: setOptions};
        var options = {};
        options.pattern = /\{(.*?)\}/g, options.template = "", options.middleware = function () {
        }
    }, {}],
    7: [function (require, module, exports) {
        !function (window, document, undefined) {
            "use strict";
            function initWithJSON(json) {
                repository.put(json), registerInput()
            }

            function initWithURL(url) {
                jsonLoader.load(url, function (err, json) {
                    err && throwError("failed to get JSON (" + url + ")"), initWithJSON(json)
                })
            }

            function emptyResultsContainer() {
                options.resultsContainer.innerHTML = ""
            }

            function appendToResultsContainer(text) {
                options.resultsContainer.innerHTML += text
            }

            function registerInput() {
                options.searchInput.addEventListener("keyup", function (e) {
                    emptyResultsContainer(), e.target.value.length > 0 && render(repository.search(e.target.value))
                })
            }

            function render(results) {
                if (0 === results.length)return appendToResultsContainer(options.noResultsText);
                for (var i = 0; i < results.length; i++)appendToResultsContainer(templater.compile(results[i]))
            }

            function throwError(message) {
                throw new Error("SimpleJekyllSearch --- " + message)
            }

            var options = {
                searchInput: null,
                resultsContainer: null,
                json: [],
                searchResultTemplate: '
{title}
',
                templateMiddleware: function () {
                },
                noResultsText: "No results found",
                limit: 10,
                fuzzy: !1,
                exclude: []
            }, requiredOptions = ["searchInput", "resultsContainer", "json"], templater = require("./Templater"), repository = require("./Repository"), jsonLoader = require("./JSONLoader"), optionsValidator = require("./OptionsValidator")({required: requiredOptions}), utils = require("./utils");
            window.SimpleJekyllSearch = function (_options) {
                var errors = optionsValidator.validate(_options);
                errors.length > 0 && throwError("You must specify the following required options: " + requiredOptions), options = utils.merge(options, _options), templater.setOptions({
                    template: options.searchResultTemplate,
                    middleware: options.templateMiddleware
                }), repository.setOptions({
                    fuzzy: options.fuzzy,
                    limit: options.limit
                }), utils.isJSON(options.json) ? initWithJSON(options.json) : initWithURL(options.json)
            }, window.SimpleJekyllSearch.init = window.SimpleJekyllSearch
        }(window, document)
    }, {"./JSONLoader": 1, "./OptionsValidator": 2, "./Repository": 3, "./Templater": 6, "./utils": 8}],
    8: [function (require, module, exports) {
        "use strict";
        function merge(defaultParams, mergeParams) {
            var mergedOptions = {};
            for (var option in defaultParams)mergedOptions[option] = defaultParams[option], void 0 !== mergeParams[option] && (mergedOptions[option] = mergeParams[option]);
            return mergedOptions
        }

        function isJSON(json) {
            try {
                return json instanceof Object && JSON.parse(JSON.stringify(json)) ? !0 : !1
            } catch (e) {
                return !1
            }
        }

        module.exports = {merge: merge, isJSON: isJSON}
    }, {}]
}, {}, [7]);


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

using Google.Api.Gax;
using Google.Apis.Bigquery.v2.Data;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;

namespace Google.Cloud.BigQuery.V2
{
    /// <summary>
    /// A row used for streaming data insertion.
    /// </summary>
    /// <remarks>
    /// <para>
    /// This is effectively a dictionary where each key is the field name (a string)
    /// and the value is the corresponding value for that field.
    /// Supported value types:
    /// </para>
    /// <list type="bullet">
    ///   <item><description><c>System.Boolean</c></description></item>
    ///   <item><description><c>System.Int16</c></description></item>
    ///   <item><description><c>System.UInt16</c></description></item>
    ///   <item><description><c>System.Int32</c></description></item>
    ///   <item><description><c>System.UInt32</c></description></item>
    ///   <item><description><c>System.Int64</c></description></item>
    ///   <item><description><c>System.Float</c></description></item>
    ///   <item><description><c>System.Double</c></description></item>
    ///   <item><description><c>System.String</c></description></item>
    ///   <item><description><c>System.DateTime</c></description></item>
    ///   <item><description><c>System.DateTimeOffset</c></description></item>
    ///   <item><description><c>System.TimeSpan</c></description></item>
    ///   <item><description><c>Google.Cloud.BigQuery.V2.BigQueryNumeric</c></description></item>
    ///   <item><description><c>Google.Cloud.BigQuery.V2.BigQueryGeography</c></description></item>
    ///   <item><description>A <c>Google.Cloud.BigQuery.V2.InsertRow</c> (for record/struct fields)</description></item>
    ///   <item><description>Any <c>IReadOnlyList<T></c> of one of the above types (for repeated fields). This
    ///   includes arrays and <c>List<T></c> values.</description></item>
    /// </list>
    /// <para>
    /// Note that all integer types are stored as <c>System.Int64</c>, and all floating point
    /// types are stored as <c>System.Double.</c></para>
    /// <para><c>DateTimeOffset</c> values are converted to UTC and treated as timestamp. The handling
    /// of <c>DateTime</c> values depends on the <c>Kind</c>: values with a <c>Kind</c> of <c>Local</c> are rejected;
    /// values with a <c>Kind</c> of <c>UTC</c> are treated as timestamps; values with a <c>Kind</c> of <c>Unspecified</c>
    /// are treated as civil datetime values. All values are stored with a precision of a microsecond.
    /// </para>
    /// <para>
    /// <c>TimeSpan</c> values must be non-negative and less than 24 hours, used to represent a time-of-day.
    /// </para>
    /// <para>
    /// Although date values are retrieved as <c>System.DateTime</c>, they must be inserted as string values, in the format
    /// "yyyy-MM-dd".
    /// </para>
    /// <para>
    /// <see cref="BigQueryInsertRow"/> is used for record/struct fields for convenience, but only the <see cref="InsertId"/>
    /// of the top-level row is relevant.
    /// </para>
    /// <para>
    /// Null elements within repeated fields are prohibited. This is validated client-side when the row is inserted; validating
    /// when a value is added to the row would be ineffective as the values could change before insertion.
    /// </para>
    /// </remarks>
    public sealed class BigQueryInsertRow : IEnumerable
    {
        private static HashSet<Type> ValidSingleTypes = new HashSet<Type>
        {
            typeof(int), typeof(long), typeof(uint),
            typeof(short), typeof(ushort),
            typeof(float), typeof(double),
            typeof(string), typeof(byte[]),
            typeof(bool),
            typeof(DateTime), typeof(DateTimeOffset),
            typeof(TimeSpan),
            typeof(BigQueryNumeric),
            typeof(BigQueryBigNumeric),
            typeof(BigQueryGeography),
            typeof(BigQueryInsertRow)
        };

        private static List<TypeInfo> ValidRepeatedTypes = ValidSingleTypes
            .Select(t => typeof(IReadOnlyList<>).MakeGenericType(t).GetTypeInfo())
            .ToList();

        private readonly IDictionary<string, object> _fields = new Dictionary<string, object>();

        /// <summary>
        /// To help ensure data consistency, you can supply an <see cref="InsertId" /> for each inserted row.
        /// BigQuery remembers this ID for at least one minute. If you try to stream the same set of rows within
        /// that time period and the insertId property is set, BigQuery uses the property to de-duplicate
        /// your data on a best effort basis. By default if no ID is specified, one will be generated to allow
        /// de-duplicating efforts if insert operations need to be retried.
        /// You can allow empty <see cref="InsertId"/> by setting <see cref="InsertOptions.AllowEmptyInsertIds"/> to true.
        /// This will allow for faster row inserts at the expense of possible record duplication if the operation needs to be retried.
        /// See https://cloud.google.com/bigquery/quotas#streaming_inserts for more information.
        /// </summary>
        public string InsertId { get; set; }

        /// <summary>
        /// Constructs an empty row with the specified insert ID.
        /// </summary>
        /// <param name="insertId">Insert ID used for deduplication. May be null.</param>
        public BigQueryInsertRow(string insertId)
        {
            InsertId = insertId;
        }

        /// <summary>
        /// Constructs an empty row with no insert ID.
        /// </summary>
        public BigQueryInsertRow()
        {
        }

        /// <summary>
        /// Adds all the values in the specified dictionary to the row.
        /// </summary>
        /// <remarks>
        /// This being named <c>Add</c> rather than <c>AddRange</c> allows
        /// it to be specified in a collection initializer, which can be useful
        /// to provide a set of common fields and then some extra values.
        /// </remarks>
        /// <param name="fields">The fields to add to the row. Must not be null.</param>
        public void Add(IDictionary<string, object> fields)
        {
            GaxPreconditions.CheckNotNull(fields, nameof(fields));
            foreach (var entry in fields)
            {
                Add(entry.Key, entry.Value);
            }
        }

        /// <summary>
        /// Adds a single field value to the row.
        /// </summary>
        /// <param name="key">The name of the field. Must be a valid BigQuery field name.</param>
        /// <param name="value">The value for the field, which must be <c>null</c> or one of the supported types.</param>
        public void Add(string key, object value)
        {
            TableSchemaBuilder.ValidateFieldName(key, nameof(key));
            ValidateValue(value, nameof(value));
            _fields.Add(key, value);
        }

        /// <summary>
        /// Returns an enumerator over the fields in this insert row. This
        /// method is only provided in order to implement <see cref="IEnumerable"/>,
        /// to permit collection initializers.
        /// </summary>
        /// <returns>An enumerator over the fields in this insert row.</returns>
        IEnumerator IEnumerable.GetEnumerator() => _fields.GetEnumerator();

        /// <summary>
        /// Accesses a field in the row by name.
        /// </summary>
        /// <param name="name">The name of the field to access. Must be a valid BigQuery field name.</param>
        /// <exception cref="KeyNotFoundException">The row does not have a key with the given name.</exception>
        /// <returns>The value associated with <paramref name="name"/>.</returns>
        public object this[string name]
        {
            get
            {
                TableSchemaBuilder.ValidateFieldName(name, nameof(name));
                return _fields[name];
            }
            set
            {
                TableSchemaBuilder.ValidateFieldName(name, nameof(name));
                ValidateValue(value, nameof(value));
                _fields[name] = value;
            }
        }

        /// <summary>
        /// Converts an insert row into the API representation.
        /// </summary>
        internal TableDataInsertAllRequest.RowsData ToRowsData(bool allowEmptyInsertIds)
            => new TableDataInsertAllRequest.RowsData
            {
                InsertId = allowEmptyInsertIds ? InsertId : InsertId ?? Guid.NewGuid().ToString(),
                Json = GetJsonValues()
            };

        internal Dictionary<string, object> GetJsonValues() => _fields.ToDictionary(pair => pair.Key, pair => ConvertRowValue(pair.Value));

        private static object ConvertRowValue(object value)
        {
            // Types that require special handling
            switch (value)
            {
                case null:
                    return null;
                case DateTime dt:
                    // TODO: three patterns in C# 8 with property matching?
                    switch (dt.Kind)
                    {
                        // Civil datetime
                        case DateTimeKind.Unspecified:
                            return dt.ToString("yyyy-MM-dd'T'HH:mm:ss.FFFFFF", CultureInfo.InvariantCulture);
                        // Timestamp
                        case DateTimeKind.Utc:
                            return dt.ToString("yyyy-MM-dd'T'HH:mm:ss.FFFFFF'Z'", CultureInfo.InvariantCulture);
                        // We can get into this situation if we accept a list of DateTime values. We can't
                        // validate when we're given the list, as it can change.
                        default:
                            throw new InvalidOperationException("Local DateTime values are not supported");
                    }
                case DateTimeOffset dto:
                    // Timestamp
                    return dto.ToUniversalTime().ToString("yyyy-MM-dd'T'HH:mm:ss.FFFFFF'Z'", CultureInfo.InvariantCulture);
                case TimeSpan ts:
                    if (ts < TimeSpan.Zero || ts >= TimeSpan.FromHours(24))
                    {
                        throw new InvalidOperationException("TimeSpan values must be non-negative and less than 24 hours");
                    }
                    // This is ugly, but it avoids a trailing . when there are no fractional seconds.
                    return (new DateTime(1970, 1, 1) + ts).ToString("HH:mm:ss.FFFFFF", CultureInfo.InvariantCulture);
                case BigQueryNumeric numeric:
                    return numeric.ToString();
                case BigQueryBigNumeric bigNumeric:
                    return bigNumeric.ToString();
                case BigQueryGeography geography:
                    return geography.ToString();
                case BigQueryInsertRow row:
                    return row.GetJsonValues();
            }
            if (ValidSingleTypes.Contains(value.GetType()))
            {
                // Anything single value should be fine as it is. We've already validated that it's a known type.
                return value;
            }
            // Note: not IEnumerable<object> as we need to box value types.
            IEnumerable values = (IEnumerable)value;
            return values.Cast<object>().Select(ValidateRepeatedElementNotNull).Select(ConvertRowValue).ToArray();
        }

        private static object ValidateRepeatedElementNotNull(object value)
        {
            if (value == null)
            {
                throw new InvalidOperationException("Elements of repeated fields must not be null");
            }
            return value;
        }

        private void ValidateValue(object value, string paramName)
        {
            if (value == null)
            {
                return;
            }
            Type type = value.GetType();
            if (value is DateTime)
            {
                DateTime dt = (DateTime) value;
                if (dt.Kind == DateTimeKind.Local)
                {
                    throw new ArgumentException("Local DateTime values are not supported", paramName);
                }
            }
            if (value is TimeSpan)
            {
                TimeSpan ts = (TimeSpan) value;
                if (ts < TimeSpan.Zero || ts >= TimeSpan.FromHours(24))
                {
                    throw new ArgumentException("TimeSpan values must be non-negative and less than 24 hours", paramName);
                }
            }
            if (ValidSingleTypes.Contains(type))
            {
                return;
            }
            TypeInfo typeInfo = type.GetTypeInfo();
            if (ValidRepeatedTypes.Any(ti => ti.IsAssignableFrom(typeInfo)))
            {
                return;
            }
            throw new ArgumentException($"Unable to use value of type {value.GetType()} in {nameof(BigQueryInsertRow)}", paramName);
        }
    }
}


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

<!--L
  Copyright Oracle Inc

  Distributed under the OSI-approved BSD 3-Clause License.
  See http://ncip.github.com/cadsr-cgmdr-nci-uk/LICENSE.txt for details.
L-->

<cgMDR:Non_Enumerated_Value_Domain xmlns:cgMDR="http://www.cancergrid.org/schema/cgMDR" item_registration_authority_identifier="GB-CANCERGRID-CA" data_identifier="429991D27" version="0.1">
    <cgMDR:administered_item_administration_record>
        <cgMDR:administrative_note>for Oxford Vaccines Group</cgMDR:administrative_note>
        <cgMDR:administrative_status>scheduledForReview</cgMDR:administrative_status>
        <cgMDR:creation_date>2007-03-07</cgMDR:creation_date>
        <cgMDR:effective_date>2007-03-07</cgMDR:effective_date>
        <cgMDR:last_change_date>2008-04-07</cgMDR:last_change_date>
        <cgMDR:registration_status>Recorded</cgMDR:registration_status>
    </cgMDR:administered_item_administration_record>
    <cgMDR:administered_by>GB-CANCERGRID-200002-1</cgMDR:administered_by>
    <cgMDR:registered_by>GB-CANCERGRID-100009-1</cgMDR:registered_by>
    <cgMDR:submitted_by>GB-CANCERGRID-200002-1</cgMDR:submitted_by>
    <cgMDR:described_by>DADE82861</cgMDR:described_by>
    <cgMDR:having>
        <cgMDR:context_identifier>GB-CANCERGRID-000001-1</cgMDR:context_identifier>
        <cgMDR:containing>
            <cgMDR:language_section_language_identifier>
                <cgMDR:country_identifier>GB</cgMDR:country_identifier>
                <cgMDR:language_identifier>eng</cgMDR:language_identifier>
            </cgMDR:language_section_language_identifier>
            <cgMDR:name>Subject Number</cgMDR:name>
            <cgMDR:definition_text>A unique identifier assigned to a study subject in a Vaccines group clinical trial</cgMDR:definition_text>
            <cgMDR:preferred_designation>true</cgMDR:preferred_designation>
            <cgMDR:definition_source_reference/>
        </cgMDR:containing>
    </cgMDR:having>
    <cgMDR:typed_by>GB-CANCERGRID-000100-1</cgMDR:typed_by>
    <cgMDR:value_domain_datatype>KRMZ1P97F</cgMDR:value_domain_datatype>
    <cgMDR:value_domain_unit_of_measure>MV3QWZ2YG</cgMDR:value_domain_unit_of_measure>
    <cgMDR:representing>GB-CANCERGRID-CA-53E99B8E1-0.1</cgMDR:representing>
</cgMDR:Non_Enumerated_Value_Domain>


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/com_lenovo_pay_process_bg">
    <RelativeLayout
        android:id="@+id/layout_title"
        android:layout_width="fill_parent"
        android:layout_height="52dp" >

        <TextView
            android:id="@+id/title_label"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text="@string/com_lenovo_pay_dlg_tip_title_text"
            android:textColor="@color/com_lenovo_pay_goods_label"
            android:textSize="@dimen/com_lenovo_pay_goods_fontsize" />

        <View
            android:id="@+id/layout_title_line"
            android:layout_width="fill_parent"
            android:layout_height="1px"
            android:layout_alignParentBottom="true"
            android:background="@color/com_lenovo_pay_gray" />
    </RelativeLayout>
    <LinearLayout
        android:id="@+id/layout_text"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/layout_title"
        android:gravity="center_vertical"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/txt_message"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="@dimen/com_lenovo_pay_goods_marginTop"
            android:layout_marginLeft="@dimen/com_lenovo_pay_goods_marginLeft"
            android:layout_marginRight="@dimen/com_lenovo_pay_goods_marginLeft"
            android:layout_marginTop="@dimen/com_lenovo_pay_goods_marginTop"
            android:text="@string/com_lenovo_pay_update_tip_text"
            android:textColor="@color/com_lenovo_pay_goods_label"
            android:textSize="@dimen/com_lenovo_pay_goods_fontsize" />
    </LinearLayout>

    <View
        android:id="@+id/view_line"
        android:layout_width="fill_parent"
        android:layout_height="1px"
        android:layout_below="@id/layout_text"
        android:background="@color/com_lenovo_pay_gray" />

    <LinearLayout
        android:id="@+id/layout_button"
        android:layout_width="fill_parent"
        android:layout_height="@dimen/com_lenovo_pay_button_height"
        android:layout_below="@id/view_line"
        android:gravity="center_vertical"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/btn_close"
            android:layout_width="0dp"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:background="@color/com_lenovo_pay_transparent_color"
            android:clickable="true"
            android:gravity="center"
            android:text="@string/com_lenovo_pay_dlg_ok_text"
            android:textColor="@color/com_lenovo_pay_button"
            android:textSize="@dimen/com_lenovo_pay_button_fontsize" />
    </LinearLayout>

</RelativeLayout>


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

<title>ClusterManager</title>
<meta name="date" content="2014-01-30">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.vertx.java.core.spi.cluster

Interface ClusterManager

public interface ClusterManager

A cluster provider for Vert.x must implement this interface.

 In order for HA to work correctly, all implementations of this interface MUST be implemented such that:

 1. Whenever a node joins or leaves the cluster the registered NodeListener (if any) MUST be called with the
 appropriate join or leave event.
 2. For all nodes that are part of the cluster, the registered NodeListener MUST be called with the exact same
 sequence of join and leave events on all nodes.
 3. For any particular join or leave event that is handled in any NodeListener, anywhere in the cluster, the List
 of nodes returned by getNodes must be identical.
 4. All of the methods in the implementation must return immediately, i.e. they must not block while the operation
 is being executed. If the underlying implementation does block, that can be wrapped in an
 Action instance and executed using the method
 VertxSPI.executeBlocking(org.vertx.java.core.spi.Action, org.vertx.java.core.Handler)

Method Summary

Methods

Modifier and Type
Method and Description

<K,V> AsyncMap<K,V>
getAsyncMap(java.lang.String name)

Return an async map for the given name

<K,V> AsyncMultiMap<K,V>
getAsyncMultiMap(java.lang.String name)

Return an async multi-map for the given name

java.lang.String
getNodeID()

Return the unique node ID for this node

java.util.List<java.lang.String>
getNodes()

Return a list of node IDs corresponding to the nodes in the cluster

<K,V> java.util.Map<K,V>
getSyncMap(java.lang.String name)

Return a synchronous map for the given name

void
join()

Join the cluster

void
leave()

Leave the cluster

void
nodeListener(NodeListener listener)

Set a listener that will be called when a node joins or leaves the cluster.

Method Detail

getAsyncMultiMap

<K,V> AsyncMultiMap<K,V> getAsyncMultiMap(java.lang.String name)

Return an async multi-map for the given name

getAsyncMap

<K,V> AsyncMap<K,V> getAsyncMap(java.lang.String name)

Return an async map for the given name

getSyncMap

<K,V> java.util.Map<K,V> getSyncMap(java.lang.String name)

Return a synchronous map for the given name

getNodeID

java.lang.String getNodeID()

Return the unique node ID for this node

getNodes

java.util.List<java.lang.String> getNodes()

Return a list of node IDs corresponding to the nodes in the cluster

nodeListener

void nodeListener(NodeListener listener)

Set a listener that will be called when a node joins or leaves the cluster.

Parameters:

listener -

join

void join()

Join the cluster

leave

void leave()

Leave the cluster

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
package com.btc.redg.jpa.model;

import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import java.util.List;

@Entity
public class ReferencedEntity1 {

	@Id
	private long id;

	@ManyToOne
	private ReferencedEntity2 refEntity2;

	@ManyToOne
	@JoinColumns(value = {
			@JoinColumn(name = "REF_2_ID1", referencedColumnName = "ID1"),
			@JoinColumn(name = "REF_2_ID2", referencedColumnName = "ID_2")
	})
	private ReferencedEntity2 referencedEntity2WithExpliciteJoinColumns;

	@ManyToOne
	private SubEntityJoined1 manyToOneToSubEntityJoined1;

	@OneToMany
	private List<SubEntityJoined1> oneToManyToSubEntityJoined1;

	@ManyToMany
	private List<SubEntityJoined1> manyToManyToSubEntityJoined1;

	@ManyToOne
	private SubEntitySingleTable1 manyToOneToSubEntitySingleTable1;

	@OneToMany
	private List<SubEntitySingleTable1> oneToManyToSubEntitySingleTable1;

	@ManyToMany
	private List<SubEntitySingleTable1> manyToManyToSubEntitySingleTable1;

	@ManyToOne
	private SubEntityTablePerClass1 manyToOneToSubEntityTablePerClass1;

	@OneToMany
	private List<SubEntityTablePerClass1> oneToManyToSubEntityTablePerClass1;

	@ManyToMany
	private List<SubEntityTablePerClass1> manyToManyToSubEntityTablePerClass1;

	@ManyToOne
	private SubEntity subEntity;

	@Embedded
	private TestEmbeddable testEmbeddable;

}


text:
<?php
namespace VersionPress\Storages;

use Nette\Utils\Strings;
use VersionPress\ChangeInfos\ChangeInfo;
use VersionPress\Database\EntityInfo;
use VersionPress\Storages\Serialization\IniSerializer;

/**
 * Stores an entity to a file that can be versioned by Git. Storages are chosen by {@link VersionPress\Storages\Mirror},
 * in a way "implement" its API of saving and deleting entities and in the end
 * manage INI files in the `wp-content/vpdb` folder.
 */
abstract class Storage
{

    const PREFIX_PLACEHOLDER = "<<table-prefix>>";

    /** @var bool */
    protected $isTransaction;

    /** @var bool */
    public $ignoreFrequentlyWrittenEntities = true;

    /** @var EntityInfo */
    protected $entityInfo;

    /** @var string */
    private $dbPrefix;

    public function __construct(EntityInfo $entityInfo, $dbPrefix)
    {
        $this->entityInfo = $entityInfo;
        $this->dbPrefix = $dbPrefix;
    }

    /**
     * Saves data to a storage
     *
     * @param array $data Associative array with values to save. On `insert`, the $data will contain full entity data
     *                    plus things like VPID. On further updates, the data will typically contain just the updated
     *                    values and a VPID (assigned in {@link VersionPress\Database\WpdbMirrorBridge} so that
     *                    the appropriate file could be located).
     * @return ChangeInfo|null Null indicates that the save operation didn't really change anything (may happen).
     *                         Otherwise, the ChangeInfo object is returned.
     */
    abstract public function save($data);

    /**
     * Deletes entity from a storage
     *
     * @param array $restriction An array that typically contains a 'vp_id' key that specifies which entity to delete
     * @return ChangeInfo|null Null indicates that no actual delete happened (for example, the INI file for a given VPID
     *                         didn't exist). Otherwise, the ChangeInfo object is returned (its action is usually
     *                         'delete').
     */
    abstract public function delete($restriction);

    /**
     * Load an entity by given VPID
     *
     * @param string $id VPID
     * @param string $parentId VPID of parent entity (for example post for postmeta)
     * @return array Array representing an entity
     */
    abstract public function loadEntity($id, $parentId);

    /**
     * Loads all entities managed by this storage
     *
     * @return array[] Array of arrays where keys are VPIDs and values are arrays with entity data
     */
    abstract public function loadAll();

    /**
     * True / false if the entity should be saved / ignored. Works as a filtering method.
     *
     * @param array $data
     * @return bool
     */
    public function shouldBeSaved($data)
    {
        $shouldBeSaved = true;

        if ($this->entityInfo->isIgnoredEntity($data)) {
            $shouldBeSaved = false;
        }

        if ($this->ignoreFrequentlyWrittenEntities) {
            $isFrequentlyWrittenEntity = $this->entityInfo->isFrequentlyWrittenEntity($data);
            $shouldBeSaved = $shouldBeSaved && !$isFrequentlyWrittenEntity;
        }

        $entityName = $this->entityInfo->entityName;
        return apply_filters("vp_entity_should_be_saved_$entityName", $shouldBeSaved, $data, $this);
    }

    /**
     * Called from {@link VersionPress\Initialization\Initializer} to give storage a chance to prepare itself.
     * For example, directory storage uses this to create its folder.
     *
     * Note: consider if this method needs to be here
     */
    abstract public function prepareStorage();

    /**
     * Returns a physical path to an INI file where the entity is stored
     *
     * @param string $id VPID
     * @param string|null $parentId VPID of parent entity (for example post for postmeta)
     * @return string
     */
    abstract public function getEntityFilename($id, $parentId);

    abstract public function getPathCommonToAllEntities();

    /**
     * Returns true if the entity exists.
     *
     * @param string $id VPID
     * @param string|null $parentId VPID of parent entity (for example post for postmeta)
     * @return bool
     */
    abstract public function exists($id, $parentId);

    /**
     * Saves data only in memory (used during initialization).
     *
     * @param array $data {@see Storage::save()}
     */
    abstract public function saveLater($data);

    /**
     * Transfers data from memory (saved by Storage::saveLater()) to the files.
     */
    abstract public function commit();

    protected function deserializeEntity($serializedEntity)
    {
        if ($serializedEntity === '') {
            return [];
        }

        $entity = IniSerializer::deserialize($serializedEntity);
        $entity = $this->flattenEntity($entity);
        $entity[$this->entityInfo->vpidColumnName] = $this->maybeReplacePlaceholderWithPrefix($entity[$this->entityInfo->vpidColumnName]);
        return $entity;
    }

    protected function serializeEntity($vpid, $entity)
    {
        $vpid = $this->maybeReplacePrefixWithPlaceholder($vpid);

        unset($entity[$this->entityInfo->vpidColumnName]);
        return IniSerializer::serialize([$vpid => $entity]);
    }

    private function flattenEntity($entity)
    {
        if (count($entity) === 0) {
            return $entity;
        }

        reset($entity);
        $vpid = key($entity);
        $flatEntity = $entity[$vpid];
        $flatEntity[$this->entityInfo->vpidColumnName] = $vpid;

        return $flatEntity;
    }

    protected function maybeReplacePrefixWithPlaceholder($key)
    {
        if (Strings::startsWith($key, $this->dbPrefix)) {
            return self::PREFIX_PLACEHOLDER . Strings::substring($key, Strings::length($this->dbPrefix));
        }
        return $key;
    }

    protected function maybeReplacePlaceholderWithPrefix($key)
    {
        if (Strings::startsWith($key, self::PREFIX_PLACEHOLDER)) {
            return $this->dbPrefix . Strings::substring($key, Strings::length(self::PREFIX_PLACEHOLDER));
        }
        return $key;
    }
}


text:
The MIT License (MIT)

Copyright (c) 2014-2015,  Mark Rogaski.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

--]]--------------------------------------------------------------------------

local salsa20 = {}

require("bit32")

local function apply(f, y, z, slice)
    local iv = {}
    for i, j in ipairs(slice) do
        iv[i] = y[j]
    end
    local ov = f(iv)
    for i, j in ipairs(slice) do
        z[j] = ov[i]
    end
end

local function byte_inc(b)
    local c = 1
    for i = 1, 8 do
        local new = (b[i] + c) % 0xFF
        c = math.floor((b[i] + c) / 0xFF)
        b[i] = new
        if c == 0 then
            break
        end
    end
    return b
end

function salsa20.quarterround(y)
    assert(#y == 4)
    local z = {}
    z[2] = bit32.bxor(y[2], bit32.lrotate(y[1] + y[4], 7))
    z[3] = bit32.bxor(y[3], bit32.lrotate(z[2] + y[1], 9))
    z[4] = bit32.bxor(y[4], bit32.lrotate(z[3] + z[2], 13))
    z[1] = bit32.bxor(y[1], bit32.lrotate(z[4] + z[3], 18))
    return z
end

function salsa20.rowround(y)
    assert(#y == 16)
    local z = {}
    apply(salsa20.quarterround, y, z, {1, 2, 3, 4})
    apply(salsa20.quarterround, y, z, {6, 7, 8, 5})
    apply(salsa20.quarterround, y, z, {11, 12, 9, 10})
    apply(salsa20.quarterround, y, z, {16, 13, 14, 15})
    return z
end

function salsa20.columnround(y)
    assert(#y == 16)
    local z = {}
    apply(salsa20.quarterround, y, z, {1, 5, 9, 13})
    apply(salsa20.quarterround, y, z, {6, 10, 14, 2})
    apply(salsa20.quarterround, y, z, {11, 15, 3, 7})
    apply(salsa20.quarterround, y, z, {16, 4, 8, 12})
    return z
end

function salsa20.doubleround(y)
    assert(#y == 16)
    return salsa20.rowround(salsa20.columnround(y))
end

function salsa20.littleendian(b)
    assert(#b == 4)
    return b[1] + 2^8 * b[2] + 2^16 * b[3] + 2^24 * b[4]
end

function salsa20.littleendian_inv(x)
    local b = {}
    for i = 1, 4 do
        b[i] = bit32.band(bit32.rshift(x, (i - 1) * 8), 0xFF)
    end
    return b
end

function salsa20.hash(b, rounds)
    rounds = rounds or 20
    assert(#b == 64)
    assert(rounds == 20 or rounds == 12 or rounds == 8)
    local x = {}
    for i = 1, 16 do
        local quad = {}
        for j = 1, 4 do
            quad[j] = b[((i - 1) * 4) + j]
        end
        x[i] = salsa20.littleendian(quad)
    end
    local z = salsa20.doubleround(x)
    for i = 1, ((rounds / 2) - 1) do
        z = salsa20.doubleround(z)
    end
    local h = {}
    for i = 1, 16 do
        local y = salsa20.littleendian_inv(z[i] + x[i])
        for j = 1, 4 do
            h[((i - 1) * 4) + j] = y[j]
        end
    end
    return h
end

function salsa20.expand(k, n)
    assert(#k == 16 or #k == 32)
    assert(#n == 16)

    local c = { string.byte(string.format("expand %2d-byte k", #k), 1, 16) }
    local x = {}

    for i =  1,  4 do table.insert(x, c[i]) end
    for i =  1, 16 do table.insert(x, k[i]) end
    for i =  5,  8 do table.insert(x, c[i]) end
    for i =  1, 16 do table.insert(x, n[i]) end
    for i =  9, 12 do table.insert(x, c[i]) end
    if #k == 16 then
        for i =  1, 16 do table.insert(x, k[i]) end
    else
        for i = 17, 32 do table.insert(x, k[i]) end
    end
    for i = 13, 16 do table.insert(x, c[i]) end

    return x
end

--- Generate the i^th 64-byte block of the Salsa20_k(v) 2^70-byte sequence.
-- @param k A 16-byte or 32-byte sequence representing the secret key.
-- @param v An 8-byte sequence representing the nonce.
-- @param i An 8-byte sequence representing the stream position of the 64-byte block.
-- @param rounds Optional number of rounds. May be 20 (default), 12, or 8.
-- @return A 64-byte output block.
function salsa20.generate(k, v, i, rounds)
    assert(#k == 16 or #k == 32)
    assert(#v == 8)
    assert(#i == 8)
    local n = {}
    for j = 1, 8 do
        n[j]     = v[j]
        n[j + 8] = i[j]
    end
    return salsa20.hash(salsa20.expand(k, n), rounds)
end

--- Encrypt a string.
-- @param key A 16-octet or 32-octet bytestring.
-- @param nonce An 8-octet bytestring nonce.
-- @param plaintext The unencrypted message.
-- @param rounds Optional number of rounds. May be 20 (default), 12, or 8.
-- @return The encrypted message.
function salsa20.encrypt(key, nonce, plaintext, rounds)
    assert(type(key) == "string" and (key:len() == 16 or key:len() == 32))
    assert(type(nonce) == "string" and nonce:len() == 8)
    assert(type(plaintext) == "string")

    local k = { key:byte(1, #key) }
    local v = { nonce:byte(1, #nonce) }
    local i = { 0, 0, 0, 0, 0, 0, 0, 0 }
    local store = {}
    local ciphertext = ""

    for _, m in pairs({ plaintext:byte(1, #plaintext) }) do
        if #store == 0 then
            store = salsa20.generate(k, v, i, rounds)
            i = byte_inc(i)
        end
        local r = table.remove(store, 1)
        ciphertext = ciphertext .. string.char(bit32.bxor(m, r))
    end
    return ciphertext
end

--- Decrypt a string.
-- @param key A 16-octet or 32-octet bytestring.
-- @param nonce An 8-octet bytestring nonce.
-- @param ciphertext The encrypted message.
-- @param rounds Optional number of rounds. May be 20 (default), 12, or 8.
-- @return The unencrypted message.
function salsa20.decrypt(key, nonce, ciphertext, rounds)
    -- The easiest thing I've done all week.
    salsa20.encrypt(key, nonce, ciphertext, rounds)
end

--- Encrypt a table of strings.
-- @param key A 16-octet or 32-octet bytestring.
-- @param nonce An 8-octet bytestring nonce.
-- @param plaintext The unencrypted messages.
-- @param rounds Optional number of rounds. May be 20 (default), 12, or 8.
-- @return The encrypted messages.
function salsa20.encrypt_table(key, nonce, plaintext, rounds)
    assert(type(key) == "string" and (key:len() == 16 or key:len() == 32))
    assert(type(nonce) == "string" and nonce:len() == 8)
    assert(type(plaintext) == "table")

    local k = { key:byte(1, #key) }
    local v = { nonce:byte(1, #nonce) }
    local i = { 0, 0, 0, 0, 0, 0, 0, 0 }
    local store = {}
    local ciphertext = {}

    for _, s in pairs(plaintext) do
        local segment = ""
        for _, m in pairs({ s:byte(1, #s) }) do
            if #store == 0 then
                store = salsa20.generate(k, v, i, rounds)
                i = byte_inc(i)
            end
            local r = table.remove(store, 1)
            segment = segment .. string.char(bit32.bxor(m, r))
        end
        table.insert(ciphertext, segment)
    end
    return ciphertext
end

--- Decrypt a string.
-- @param key A 16-octet or 32-octet bytestring.
-- @param nonce An 8-octet bytestring nonce.
-- @param ciphertext The encrypted messages.
-- @param rounds Optional number of rounds. May be 20 (default), 12, or 8.
-- @return The unencrypted messages.
function salsa20.decrypt_table(key, nonce, ciphertext, rounds)
    -- The second easiest thing I've done all week.
    salsa20.encrypt_table(key, nonce, ciphertext, rounds)
end

return salsa20


text:
What's done:

1) Async bitcoin rates retrieval

2) MVP structure

3) RX integration

4) Options for different time periods

5) One graph renderer class and one prototype

6) One GraphView that can by stylized

7) Rendering supports touch events

What I didn't do, but would like to see in a production ready class:

1) State saving of the renderer

2) Offline cache of rates and results

3) Limits to zoom and translations

4) Separate geometry for Labels and graphs

5) Better error handling

6) Base activity with all needed methods

7) Animations for bars loading and appearing

8) Integration tests for repo methods

IMO all that is easily done with the current architecture and more time. Personal learnings for me - RX is helpful for quick setup of an ASYNC pipeline. Got better understanding of Canvas class and Android API rendering. Honestly - OpenGL seems more robust and just as painful to setup.


text:
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name = "text_to_speech.v1">
    <test name = "test">
        <classes>
            <class name = "com.ibm.watson.text_to_speech.v1.TextToSpeechTest"/>
        </classes>
    </test>
</suite>


text:
<?php

namespace KKL\Ligatool;

use stdClass;

class Shortcodes {

  public static function getClub($atts, $content, $tag) {

    $kkl_twig = Template\Service::getTemplateEngine();

    $db = new DB\Wordpress();

    $context = Plugin::getContext();
    $club = $db->getClubData($atts['id']);

    return $kkl_twig->render('shortcodes/club.twig', array('context' => $context, 'club' => $club));

  }

  public static function leagueOverview($attrs, $content, $tag) {

    $kkl_twig = Template\Service::getTemplateEngine();
    $db = new DB\Wordpress();

    $context = Plugin::getContext();
    $all_leagues = $db->getActiveLeagues();
    $leagues = array();
    foreach($all_leagues as $league) {
      $league->season = $db->getSeason($league->current_season);
      $league->teams = $db->getTeamsForSeason($league->season->id);
      foreach($league->teams as $team) {
        $club = $db->getClub($team->club_id);
        if(!$team->logo) {
          $team->logo = $club->logo;
          if(!$club->logo) {
            $team->logo = "";
          }
        } else {
          $team->logo = "/images/team/" . $team->logo;
        }
        // HACK
        $team->link = Plugin::getLink('club', array('club' => $club->short_name));
      }

      $day = $db->getGameDay($league->season->current_game_day);

      $league->link = Plugin::getLink(
        'league', array('league'   => $league->code, 'season' => date('Y', strtotime($league->season->start_date)),
                        'game_day' => $day->number,)
      );
      $leagues[] = $league;
    }

    return $kkl_twig->render(
      'shortcodes/league_overview.twig',
      array('context' => $context, 'leagues' => $leagues, 'all_leagues' => $all_leagues,)
    );
  }

  public static function leagueTable($atts, $content, $tag) {

    $kkl_twig = Template\Service::getTemplateEngine();
    $db = new DB\Wordpress();

    $context = Plugin::getContext();
    $rankings = array();

    $ranking = new stdClass;
    $ranking->league = $context['league'];
    $ranking->ranks = $db->getRankingForLeagueAndSeasonAndGameDay(
      $context['league']->id, $context['season']->id, $context['game_day']->number
    );
    foreach($ranking->ranks as $rank) {
      $team = $db->getTeam($rank->team_id);
      $club = $db->getClub($team->club_id);
      $rank->team->link = Plugin::getLink('club', array('club' => $club->short_name));
    }
    $properties = $db->getSeasonProperties($context['season']->id);
    if($properties && array_key_exists('relegation_explanation', $properties)) {
      $ranking->relegation_explanation = $properties['relegation_explanation'];
    }
    $rankings[] = $ranking;

    return $kkl_twig->render('shortcodes/table.twig', array('context' => $context, 'rankings' => $rankings));
  }

  public static function tableOverview($atts, $content, $tag) {

    $kkl_twig = Template\Service::getTemplateEngine();
    $db = new DB\Wordpress();

    $context = Plugin::getContext();
    $rankings = array();
    foreach($db->getActiveLeagues() as $league) {
      $season = $db->getSeason($league->current_season);
      $day = $db->getGameDay($season->current_game_day);
      $ranking = new stdClass;
      $ranking->league = $league;
      $ranking->ranks = $db->getRankingForLeagueAndSeasonAndGameDay($league->id, $season->id, $day->number);
      foreach($ranking->ranks as $rank) {
        $team = $db->getTeam($rank->team_id);
        $club = $db->getClub($team->club_id);
        $rank->team->link = Plugin::getLink('club', array('club' => $club->short_name));
      }

      $ranking->league->link = Plugin::getLink(
        'league', array('league'   => $league->code, 'season' => date('Y', strtotime($season->start_date)),
                        'game_day' => $day->number)
      );
      $rankings[] = $ranking;
    }

    return $kkl_twig->render('shortcodes/table.twig', array('context' => $context, 'rankings' => $rankings));
  }

  public static function gameDayTable($atts, $content, $tag) {

    $kkl_twig = Template\Service::getTemplateEngine();
    $db = new DB\Wordpress();

    $context = Plugin::getContext();
    $schedules = array();
    $schedule = $db->getScheduleForGameDay($context['game_day']);
    foreach($schedule->matches as $match) {
      $home_club = $db->getClub($match->home->club_id);
      $away_club = $db->getClub($match->away->club_id);
      $match->home->link = Plugin::getLink('club', array('club' => $home_club->short_name));
      $match->away->link = Plugin::getLink('club', array('club' => $away_club->short_name));
    }
    $schedule->link = Plugin::getLink(
      'schedule',
      array('league' => $context['league']->code, 'season' => date('Y', strtotime($context['season']->start_date)))
    );

    $schedules[] = $schedule;

    return $kkl_twig->render(
      'shortcodes/game_day.twig', array('context' => $context, 'schedules' => $schedules, 'view' => 'current')
    );
  }

  public static function gameDayOverview($atts, $content, $tag) {

    $kkl_twig = Template\Service::getTemplateEngine();
    $db = new DB\Wordpress();

    $data = $db->getAllUpcomingGames();
    $games = array();
    $leagues = array();
    foreach($data as $game) {
      $leagues[$game->league_id] = true;
      $games[$game->league_id][] = $game;
    }
    foreach(array_keys($leagues) as $league_id) {
      $league = $db->getLeague($league_id);
      echo $kkl_twig->render(
        'shortcodes/gameday_overview.twig', array('schedule' => $games[$league_id], 'league' => $league)
      );
    }
  }

  public static function seasonSchedule($atts, $content, $tag) {

    $kkl_twig = Template\Service::getTemplateEngine();
    $db = new DB\Wordpress();

    $activeTeam = $_GET['team'];

    $context = Plugin::getContext();
    $schedules = $db->getScheduleForSeason($context['season']);
    foreach($schedules as $schedule) {
      foreach($schedule->matches as $match) {
        $home_club = $db->getClub($match->home->club_id);
        $away_club = $db->getClub($match->away->club_id);
        $match->home->link = Plugin::getLink('club', array('club' => $home_club->short_name));
        $match->away->link = Plugin::getLink('club', array('club' => $away_club->short_name));
      }
    }

    return $kkl_twig->render(
      'shortcodes/game_day.twig',
      array('context' => $context, 'schedules' => $schedules, 'view' => 'all', 'activeTeam' => $activeTeam)
    );
  }

  public static function clubDetail($atts, $content, $tag) {

    $kkl_twig = Template\Service::getTemplateEngine();

    $db = new DB\Wordpress();
    $context = Plugin::getContext();
    $contextClub = $context['club'];

    $seasonTeams = $db->getTeamsForClub($contextClub->id);
    $teams = array();
    foreach($seasonTeams as $seasonTeam) {

      $seasonTeam->season = $db->getSeason($seasonTeam->season_id);
      if (!$seasonTeam->season->hide_in_overview) {
        $seasonTeam->season->league = $db->getLeague($seasonTeam->season->league_id);

        $ranking = $db->getRankingForLeagueAndSeasonAndGameDay(
          $seasonTeam->season->league_id, $seasonTeam->season->id, $seasonTeam->season->current_game_day
        );
        $position = 1;
        foreach($ranking as $rank) {
          if($rank->team_id == $seasonTeam->id) {
            $seasonTeam->scores = $rank;
            $seasonTeam->scores->position = $position;
            break;
          }
          $position++;
        }

        $seasonTeam->link = Plugin::getLink('club', array('club' => $contextClub->short_name));
        $seasonTeam->schedule_link = Plugin::getLink(
          'schedule', array('league' => $seasonTeam->season->league->code, 'season' => date(
                      'Y', strtotime($seasonTeam->season->start_date)
                    ), 'team'        => $seasonTeam->short_name)
        );

        $teams[$seasonTeam->id] = $seasonTeam;
      }
    }

    $currentTeam = $db->getCurrentTeamForClub($contextClub->id);
    $currentLocation = $db->getLocation($currentTeam->properties['location']);

    return $kkl_twig->render(
      'shortcodes/club_detail.twig',
      array('context' => $context, 'club' => $contextClub, 'teams' => $teams, 'current_location' => $currentLocation)
    );

  }

  public static function gameDayPager($atts, $content, $tag) {
    $kkl_twig = Template\Service::getTemplateEngine();

    $db = new DB\Wordpress();
    $context = Plugin::getContext();

    $day = $context['game_day'];
    $league = $context['league'];
    $season = $context['season'];

    $prev = $db->getPreviousGameDay($day);
    if(!$prev) {
      $day->isFirst = true;
    } else {
      $prev->link = Plugin::getLink(
        'league', array('league'   => $league->code, 'season' => date('Y', strtotime($season->start_date)),
                        'game_day' => $prev->number)
      );

    }
    $next = $db->getNextGameDay($day);
    if(!$next) {
      $day->isLast = true;
    } else {
      $next->link = Plugin::getLink(
        'league', array('league'   => $league->code, 'season' => date('Y', strtotime($season->start_date)),
                        'game_day' => $next->number)
      );
      $next->link = Plugin::getLink('league', array('league' => $league->code, 'season' => date('Y', strtotime($season->start_date)), 'game_day' => $next->number));
    }

    return $kkl_twig->render(
      'shortcodes/gameday_pager.twig', array('context' => $context, 'prev' => $prev, 'day' => $day, 'next' => $next)
    );

  }

  /**
   * @param $atts
   * @param $content
   * @param $tag
   *
   * @return mixed
   */
  public static function contactList($atts, $content, $tag) {
    $kkl_twig = Template\Service::getTemplateEngine();

    $db = new DB\Wordpress();

    $leagues = $db->getActiveLeagues();
    $leagueadmins = $db->getLeagueAdmins();
    $captains = $db->getCaptainsContactData();
    $vicecaptains = $db->getViceCaptainsContactData();
    $players = array_merge($leagueadmins, $captains, $vicecaptains);

    $leagueMap = array();
    foreach ( $leagues as $league ) {
      $leagueMap[$league->code] = $league;
    }

    $contactMap = array();
    foreach ( $players as $player ) {

      if ( $player->league_short ) {
        if ( !isset( $contactMap[ $player->league_short ] ) ) {
          $contactMap[ $player->league_short ]['league'] = $leagueMap[$player->league_short];
        }
        $contactMap[ $player->league_short ]['players'][] = $player;
      } else if ( $player->role === 'ligaleitung' ) {
        if ( !isset( $contactMap['ligaleitung'] ) ) {
          $contactMap['ligaleitung']['league'] = array(
              'id' => 'ligaleitung',
              'code' => 'ligaleitung',
              'name' => 'Ligaleitung'
          );
        }

        $contactMap['ligaleitung']['players'][] = $player;
      }
    }

    usort($contactMap, array(__CLASS__, "cmp",));

    return $kkl_twig->render(
      'shortcodes/contact_list.twig', array(
        'leagues' => $leagues,
        'contactMap' => $contactMap
      )
    );

  }

  public static function setMatchFixture($atts, $content, $tag) {

    $templateEngine = Template\Service::getTemplateEngine();
    $db = new DB\Wordpress();
    $data = $db->getAllGamesForCurrentGameday();

    $all_matches = array();
    foreach($data as $game) {
      $teamProperties = $db->getTeamProperties($game->homeid);

      $leagueData = $db->getLeague($game->league_id);
      $all_matches[$game->league_id]["id"] = $game->league_id;
      $all_matches[$game->league_id]["name"] = $leagueData->name;
      $all_matches[$game->league_id]["code"] = $leagueData->code;
      $all_matches[$game->league_id]["matches"][] = array("match"       => $game,
                                                          "location_id" => $teamProperties["location"]);
    }

    $all_locations = $db->getLocations();
    return $templateEngine->render(
      'shortcodes/set_match_fixture.twig',
      array(
        'api_url' => get_site_url(),
        'all_matches' => $all_matches,
        'all_locations' => $all_locations
      )
    );

  }

  private static function cmp($a, $b) {
    return strcmp($a->team, $b->team);
  }

}


text:
require File.expand_path('../../helper', __FILE__)

describe('Beehive::Client') do

  before(:all) do
    if ENV.key?('REDIS')
      @client = Beehive::Client.new([ENV['REDIS']])
    else
      @client = Beehive::Client.new
    end
  end

  it('Queue a new job') do
    @client.queue('video', :title => 'hello')

    job = @client.get('video')

    job['title'].should === 'hello'
  end

  after(:all) do
    @client = nil
  end

end


text:
@implementation DDContextAllowlistFilterLogFormatter (Deprecated)

- (void)addToWhitelist:(NSInteger)loggingContext {
    [self addToAllowlist:loggingContext];
}

- (void)removeFromWhitelist:(NSInteger)loggingContext {
    [self removeFromAllowlist:loggingContext];
}

- (NSArray *)whitelist {
    return [self allowlist];
}

- (BOOL)isOnWhitelist:(NSInteger)loggingContext {
    return [self isOnAllowlist:loggingContext];
}

@end

@implementation DDContextDenylistFilterLogFormatter (Deprecated)

- (void)addToBlacklist:(NSInteger)loggingContext {
    [self addToDenylist:loggingContext];
}

- (void)removeFromBlacklist:(NSInteger)loggingContext {
    [self removeFromDenylist:loggingContext];
}

- (NSArray *)blacklist {
    return [self denylist];
}

- (BOOL)isOnBlacklist:(NSInteger)loggingContext {
    return [self isOnDenylist:loggingContext];
}

@end


text:
var DRController = angular.module('DRController', []);

DRController.controller('MainListCtrl', ['$scope', '$http', '$location', function($scope, $http, $location){
	$scope.orders = [];
	$scope.reports = [];
	$scope.set_order = function(data){
		$scope.orders = data;
	}
}]);

function get_page_data($scope){
	var infos = {
		category: $scope.category,
		code:$scope.code,
		encounter:$scope.encounter,
		subject:$scope.subject,
		performer:$scope.performer,
		effective:$scope.effective,
		issued:$scope.issued,
		specimen:$scope.specimen,
		observation:$scope.observation_list,
		conclusion:$scope.conclusion,
		status:$scope.new_status,
	}
	return infos;
}

DRController.controller('NewOrdCtrl', ['$scope', '$http', '$location', function($scope, $http, $location){
	$scope.submit = function(id){
		var post_data = form_report_json(get_page_data($scope));
		var req = {
			method:'POST',
			url:'/datas/update_report',
			data: {
				report:post_data,
				id:id
			}
		}
		$http(req).then(function(result){
			show_msg('Success');
		});
	}
}]);

function form_report_json(info){
	var res_json = {
		'resourceType':'DiagnosticReport',
		'text':{
			'status':'generated',
			'div': form_div(info),
		},
		'contained':get_observation(info),
		'status':info.status,
		'subject':{
			'reference':info.subject,
			'display':''
		},
		'effectiveDateTime':info.effective,
		'issued':info.issued,
		'performer':{
			'reference':info.performer,
			'display':''
		},
		'specimen':[{
			'reference':info.specimen,
			'display':''
		}],
		'result': get_result(info)
	}
	return res_json;
}

function set_order_data(data){
	$('.item').remove();
	$('.report-item').remove();
	var mid_element = angular.element(document.getElementById("mid-panel"));
	var mid_scope = mid_element.scope();
	mid_scope.set_order(data);
}

DRController.controller('left_panel', ['$scope', '$http', '$location', function($scope, $http, $location){
	$scope.order_flag = false;
	$scope.report_flag = false;
	$scope.toggle_order = function(){
		FHIR.oauth2.ready(onReady, onError);
		function onError(){
	            console.log("Loading error", arguments);
	        };

        function onReady(smart){
            // Load up the patient from SMART
            // Note: we use DI to inject the patient model ($dmPatient) into the view models within the start method
            console.log('hello');
            smart.user.api.fetchAll({type:'DiagnosticOrder' }).done(function(dr){
            	console.log(dr);
            })
        };
		$scope.order_flag = !$scope.order_flag;
	}
	$scope.get_all_orders = function() {
		$http.get('/orders').success( function(data) {
			set_order_data(data);
		});
		$location.path('#/')
	}
	$scope.get_na_orders = function() {
		$http.get('/orders').success( function(data) {
			set_order_data(data)
		})
	}
	$scope.get_ac_orders = function() {
		console.log("2333");
		$http.get('/orders').success( function(data) {
			console.log("2333");
			set_order_data(data);
		})
	}
	$scope.get_rj_orders = function(){
		$http.get('/orders').success( function(data) {
			set_order_data(data);
		})
	}
	$scope.create_new_order = function(){
	}
}]);


text:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { ShelfDetailResolverService } from '../api-services/shelf-detail-resolver.service';
import { NgxPermissionsGuard } from 'ngx-permissions';
import { EditComponent } from './edit/edit.component';
import { ViewComponent } from './view/view.component';
import { NewComponent } from './new/new.component';
import { ListComponent } from './list/list.component';

const routes: Routes = [
  {
    path: 'new',
    component: NewComponent,
    canActivate: [NgxPermissionsGuard],
    data: { permissions: { only: ['inventory-management:shelves:create'] } },
  },
  {
    path: ':id',
    component: ViewComponent,
    canActivate: [NgxPermissionsGuard],
    data: { permissions: { only: ['inventory-management:shelves:get'] } },
    resolve: {
      shelf: ShelfDetailResolverService,
    },
  },
  {
    path: ':id/edit',
    component: EditComponent,
    canActivate: [NgxPermissionsGuard],
    data: { permissions: { only: ['inventory-management:shelves:update'] } },
    resolve: {
      shelf: ShelfDetailResolverService,
    },
  },
  {
    path: '',
    canActivate: [NgxPermissionsGuard],
    data: {
      permissions: {
        only: [
          'inventory-management:shelves:find',
          'inventory-management:shelves:list',
        ],
      },
    },
    component: ListComponent,
  },
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule],
})
export class ShelvesRoutingModule {}


text:
<!DOCTYPE html>

<form>
  First Name: <input type="text" name="fname" value="Donald">

  Last Name: <input type="text" name="lname" value="Duck">
</form>

Click the button to display the number of form elements in the document.

<button onclick="myFunction()">Try it</button>

<?php

//yukarıdaki kod bize form sayısını geri döndürür..
//
//
//
//

//HALİL_BARIM.

?>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Torula muriae J. Kickx f.

### Remarks
null


text:
<!DOCTYPE html>

    <meta charset="utf-8">

    <title>Анатолий Найдёнов — Резюме</title>
    <meta name="description" content="-">
    <meta name="author" content="{{ site.author }} @{{ site.twitter }}">

    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

    <link rel="stylesheet" href="{{ site.baseurl }}static/css/cv_base.css">
    <link rel="stylesheet" href="{{ site.baseurl }}static/css/cv_skeleton.css">
    <link rel="stylesheet" href="{{ site.baseurl }}static/css/cv_layout.css">
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">

    <link rel="shortcut icon" href="{{ site.baseurl }}static/img/favicon.ico">
    <link rel="apple-touch-icon-precomposed" sizes="72x72" href="{{ site.baseurl }}static/img/apple-touch-icon-144.png"/>
    <link rel="apple-touch-icon" sizes="114x114" href="{{ site.baseurl }}static/img/apple-touch-icon-144.png">

    <meta property="og:url" content="http://a-naydenov.github.com/index.html">
    <meta property="og:locale" content="ru_RU"/>
    <meta property="og:type" content="website"/>
    <meta property="og:title" content="">
    <meta property="og:description" content="">
    <meta property="twitter:card" content="summary"/>
    <meta property="twitter:site" content="@a_naydenov">
    <meta property="twitter:title" content=""/>

Анатолий Найдёнов

            {{ site.age }} лет

            {{ site.location }}

            {{ site.email }}

             Linkedin / Мой круг

        {{ content }}

         На главную

         англоязычное резюме
         1.09.16
        СКАЧАТЬ PDF


text:
package net.sf.qualitycheck.exception;

import org.junit.Assert;
import org.junit.Test;

public class IllegalNumberArgumentExceptionTest {

	@Test
	public void construct_withArgName_successful() {
		new IllegalNumberArgumentException("argName", "42a");
	}

	@Test
	public void construct_withEmptyArgName_successful() {
		new IllegalNumberArgumentException("", "42a");
	}

	@Test
	public void construct_withEmptyArgNameAndNullCause() {
		new IllegalNumberArgumentException("", "42a", null);
	}

	@Test
	public void construct_withFilledArgNameAndFilledCause() {
		new IllegalNumberArgumentException("argName", "42a", new NumberFormatException());
	}

	@Test
	public void construct_withFilledArgNameAndNullCause() {
		final IllegalNumberArgumentException e = new IllegalNumberArgumentException("argName", "42a", null);
		Assert.assertEquals("The passed argument 'argName' must be a number.", e.getMessage());
	}

	@Test
	public void construct_withFilledCause() {
		new IllegalNumberArgumentException("42a", new NumberFormatException());
	}

	@Test
	public void construct_withNullArgName() {
		new IllegalNumberArgumentException((String) null, "42a");
	}

	@Test
	public void construct_withNullArgNameAndNullCause() {
		new IllegalNumberArgumentException((String) null, null, null);
	}

	@Test
	public void construct_withNullCause() {
		new IllegalNumberArgumentException(null, (Throwable) null);
	}

	@Test
	public void construct_withoutArgs_successful() {
		new IllegalNumberArgumentException("42a");
	}

	@Test
	public void testGetIllegalArgument() {
		final IllegalArgumentHolder<CharSequence> iah = new IllegalNumberArgumentException("42a");
		Assert.assertEquals("42a", iah.getIllegalArgument());
	}
}


text:
Incydentnik::Application.routes.draw do
  root to: "main#index"

  resources :incidents, only: [:create, :index]
end