text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title>Blog | React</title>
  <meta name="viewport" content="width=device-width">
  <meta property="og:title" content="Blog | React">
  <meta property="og:type" content="website">
  <meta property="og:url" content="https://facebook.github.io/react/blog/page19/">
  <meta property="og:image" content="https://facebook.github.io/react/img/logo_og.png">
  <meta property="og:description" content="A JavaScript library for building user interfaces">
  <meta property="fb:app_id" content="623268441017527">

  <link rel="shortcut icon" href="/react/favicon.ico">
  <link rel="alternate" type="application/rss+xml" title="React" href="https://127.0.0.1/react/feed.xml">

  <link rel="stylesheet" href="https://cdn.jsdelivr.net/docsearch.js/1/docsearch.min.css" />
  <link rel="stylesheet" href="/react/css/syntax.css">
  <link rel="stylesheet" href="/react/css/codemirror.css">
  <link rel="stylesheet" href="/react/css/react.css">

  <link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet">

          React

Docs/文档

Support/支持

Download/下载

Blog/博客

            <input id="algolia-doc-search" type="text" placeholder="Search docs..." />

GitHub

React Native

Recent posts

Relay: State of the State

Create Apps with No Configuration

Mixins Considered Harmful

Introducing React's Error Code System

React v15.0.1

React v15.0

React v0.14.8

React v15.0 Release Candidate 2

React v15.0 Release Candidate

New Versioning Scheme

All posts ...

  Community Round-up #8

  September 24, 2013
  by

      Vjeux

A lot has happened in the month since our last update. Here are some of the more interesting things we've found. But first, we have a couple updates before we share links.

First, we are organizing a React Hackathon in Facebook's Seattle office on Saturday September 28. If you want to hack on React, meet some of the team or win some prizes, feel free to join us!

We've also reached a point where there are too many questions for us to handle directly. We're encouraging people to ask questions on StackOverflow using the tag [reactjs]. Many members of the team and community have subscribed to the tag, so feel free to ask questions there. We think these will be more discoverable than Google Groups archives or IRC logs.

Javascript Jabber #

Pete Hunt and Jordan Walke were interviewed on Javascript Jabber for an hour.  They go over many aspects of React such as 60 FPS, Data binding, Performance, Diffing Algorithm, DOM Manipulation, Node.js support, server-side rendering, JSX, requestAnimationFrame and the community. This is a gold mine of information about React.

PETE:  So React was designed all around that. Conceptually, how you build a React app is that every time your data changes, it's like hitting the refresh button in a server-rendered app. What we do is we conceptually throw out all of the markup and event handlers that you've registered and we reset the whole page and then we redraw the entire page. If you're writing a server-rendered app, handling updates is really easy because you hit the refresh button and you're pretty much guaranteed to get what you expect.

MERRICK:  That's true. You don't get into these odd states.

PETE:  Exactly, exactly. In order to implement that, we communicate it as a fake DOM. What we'll do is rather than throw out the actual browser html and event handlers, we have an internal representation of what the page looks like and then we generate a brand new representation of what we want the page to look like. Then we perform this really, really fast diffing algorithm between those two page representations, DOM representations. Then React will compute the minimum set of DOM mutations it needs to make to bring the page up to date.

Then to finally get to answer your question, that set of DOM mutations then goes into a queue and we can plug in arbitrary flushing strategies for that. For example, when we originally launched React in open source, every setState would immediately trigger a flush to the DOM. That wasn't part of the contract of setState, but that was just our strategy and it worked pretty well. Then this totally awesome open source contributor Ben Alpert at Khan Academy built a new batching strategy which would basically queue up every single DOM update and state change that happened within an event tick and would execute them in bulk at the end of the event tick.

Read the full conversation ...

JSXTransformer Trick #

While this is not going to work for all the attributes since they are camelCased in React, this is a pretty cool trick.

Turn any DOM element into a React.js function: JSXTransformer.transform("/** @jsx React.DOM */" + element.innerHTML).code
— Ross Allen (@ssorallen) September 9, 2013

Remarkable React #

Stoyan Stefanov gave a talk at BrazilJS about React and wrote an article with the content of the presentation. He goes through the difficulties of writing active apps using the DOM API and shows how React handles it.

So how does exactly React deal with it internally? Two crazy ideas - virtual DOM and synthetic events.

You define you components in React. It builds a virtual DOM in JavaScript land which is way more efficient. Then it updates the DOM. (And "virtual DOM" is a very big name for what is simply a JavaScript object with nested key-value pairs)

Data changes. React computes a diff (in JavaScript land, which is, of course, much more efficient) and updates the single table cell that needs to change. React replicates the state of the virtual DOM into the actual DOM only when and where it's necessary. And does it all at once, in most cases in a single tick of the requestAnimationFrame().

What about event handlers? They are synthetic. React uses event delegation to listen way at the top of the React tree. So removing a node in the virtual DOM has no effect on the event handling.

The events are automatically cross-browser (they are React events). They are also much closer to W3C than any browser. That means that for example e.target works, no need to look for the event object or checking whether it's e.target or e.srcElement (IE). Bubbling and capturing phases also work cross browser. React also takes the liberty of making some small fixes, e.g. the event <input onChange> fires when you type, not when blur away from the input. And of course, event delegation is used as the most efficient way to handle events. You know that "thou shall use event delegation" is also commonly given advice for making web apps snappy.

The good thing about the virtual DOM is that it's all in JavaScript land. You build all your UI in JavaScript. Which means it can be rendered on the server side, so you initial view is fast (and any SEO concerns are addressed). Also, if there are especially heavy operations they can be threaded into WebWorkers, which otherwise have no DOM access.

Read More ...

Markdown in React #

Ben Alpert converted marked, a Markdown Javascript implementation, in React: marked-react. Even without using JSX, the HTML generation is now a lot cleaner. It is also safer as forgetting a call to escape will not introduce an XSS vulnerability.

Unite from BugBusters #

Renault John Lecoultre wrote Unite, an interactive tool for analyzing code dynamically using React. It integrates with CodeMirror.

#reactjs IRC Logs #

Vjeux re-implemented the display part of the IRC logger in React. Just 130 lines are needed for a performant infinite scroll with timestamps and color-coded author names.

View the source on JSFiddle...

  Community Round-up #7

  August 26, 2013
  by

      Vjeux

It's been three months since we open sourced React and it is going well. Some stats so far:

114 285 unique visitors on this website

1933 stars and 210 forks

226 posts on Google Group

76 Github projects using React

30 contributors

15 blog posts

2 early adopters: Khan Academy and Propeller

Wolfenstein Rendering Engine Ported to React #

Pete Hunt ported the render code of the web version of Wolfenstein 3D to React. Check out the demo and render.js file for the implementation.

React & Meteor #

Ben Newman made a 13-lines wrapper to use React and Meteor together. Meteor handles the real-time data synchronization between client and server. React provides the declarative way to write the interface and only updates the parts of the UI that changed.

This repository defines a Meteor package that automatically integrates the React rendering framework on both the client and the server, to complement or replace the default Handlebars templating system.

The React core is officially agnostic about how you fetch and update your data, so it is far from obvious which approach is the best. This package provides one answer to that question (use Meteor!), and I hope you will find it a compelling combination.

var MyComponent = React.createClass({
 mixins: [MeteorMixin],

 getMeteorState: function() {
   return { foo: Session.get('foo') };
 },

 render: function() {
   return <div>{this.state.foo}</div>;
 }
});

Dependencies will be registered for any data accesses performed by getMeteorState so that the component can be automatically re-rendered whenever the data changes.

Read more ...

React Page #

Jordan Walke implemented a complete React project creator called react-page. It supports both server-side and client-side rendering, source transform and packaging JSX files using CommonJS modules, and instant reload.

Easy Application Development with React JavaScript

Why Server Rendering?

Faster initial page speed:

Markup displayed before downloading large JavaScript.

Markup can be generated more quickly on a fast server than low power client devices.

Faster Development and Prototyping:

Instantly refresh your app without waiting for any watch scripts or bundlers.

Easy deployment of static content pages/blogs: just archive using recursive wget.

SEO benefits of indexability and perf.

How Does Server Rendering Work?

react-page computes page markup on the server, sends it to the client so the user can see it quickly.

The corresponding JavaScript is then packaged and sent.

The browser runs that JavaScript, so that all of the event handlers, interactions and update code will run seamlessly on top of the server generated markup.

From the developer's (and the user's) perspective, it's just as if the rendering occurred on the client, only faster.

Try it out ...

  Use React and JSX in Python Applications

  August 19, 2013
  by

      Kunal Mehta

Today we're happy to announce the initial release of PyReact, which makes it easier to use React and JSX in your Python applications. It's designed to provide an API to transform your JSX files into JavaScript, as well as provide access to the latest React source files.

Usage #

Transform your JSX files via the provided jsx module:

from react import jsx

# For multiple paths, use the JSXTransformer class.
transformer = jsx.JSXTransformer()
for jsx_path, js_path in my_paths:
    transformer.transform(jsx_path, js_path)

# For a single file, you can use a shortcut method.
jsx.transform('path/to/input/file.jsx', 'path/to/output/file.js')

For full paths to React files, use the source module:

from react import source

# path_for raises IOError if the file doesn't exist.
react_js = source.path_for('react.min.js')

Django #

PyReact includes a JSX compiler for django-pipeline. Add it to your project's pipeline settings like this:

PIPELINE_COMPILERS = (
  'react.utils.pipeline.JSXCompiler',
)

Installation #

PyReact is hosted on PyPI, and can be installed with pip:

$ pip install PyReact

Alternatively, add it into your requirements file:

PyReact==0.1.1

Dependencies: PyReact uses PyExecJS to execute the bundled React code, which requires that a JS runtime environment is installed on your machine. We don't explicitly set a dependency on a runtime environment; Mac OS X comes bundled with one. If you're on a different platform, we recommend PyV8.

For the initial release, we've only tested on Python 2.7. Look out for support for Python 3 in the future, and if you see anything that can be improved, we welcome your contributions!

  Community Round-up #6

  August  5, 2013
  by

      Vjeux

This is the first Community Round-up where none of the items are from Facebook/Instagram employees. It's great to see the adoption of React growing.

React Game Tutorial #

Caleb Cassel wrote a step-by-step tutorial about making a small game. It covers JSX, State and Events, Embedded Components and Integration with Backbone.

Reactify #

Andrey Popp created a Browserify helper to compile JSX files.

Browserify v2 transform for text/jsx. Basic usage is:

% browserify -t reactify main.jsx

reactify transform activates for files with either .jsx extension or /** @jsx React.DOM */ pragma as a first line for any .js file.

Check it out on Github...

React Integration with Este #

Daniel Steigerwald is now using React within Este, which is a development stack for web apps in CoffeeScript that are statically typed using the Closure Library.

este.demos.react.todoApp = este.react.create (`</span><span class="sr">/** @lends {React.ReactComponent.prototype} */</span><span class="o">`)
  render: ->
    @div [
      este.demos.react.todoList 'items': @state['items']
      if @state['items'].length
        @p "#{@state['items'].length} items."
      @form 'onSubmit': @onFormSubmit, [
        @input
          'onChange': @onChange
          'value': @state['text']
          'autoFocus': true
          'ref': 'textInput'
        @button "Add ##{@state['items'].length + 1}"
      ]
    ]

Check it out on Github...

React Stylus Boilerplate #

Zaim Bakar shared his boilerplate to get started with Stylus CSS processor.

This is my boilerplate React project using Grunt as the build tool, and Stylus as my CSS preprocessor.

Very minimal HTML boilerplate

Uses Stylus, with nib included

Uses two build targets:

grunt build to compile JSX and Stylus into a development build

grunt dist to minify and optimize the development build for production

Check it out on Github...

WebFUI #

Conrad Barski, author of the popular book Land of Lisp, wants to use React for his ClojureScript library called WebFUI.

I'm the author of "Land of Lisp" and I love your framework. I built a somewhat similar framework a year ago WebFUI aimed at ClojureScript. My framework also uses global event delegates, a global "render" function, DOM reconciliation, etc just like react.js. (Of course these ideas all have been floating around the ether for ages, always great to see more people building on them.)

Your implementation is more robust, and so I think the next point release of webfui will simply delegate all the "hard work" to react.js and will only focus on the areas where it adds value (enabling purely functional UI programming in clojurescript, and some other stuff related to streamlining event handling)

Read the full post...

  Use React and JSX in Ruby on Rails

  July 30, 2013
  by

      Paul O'Shannessy

Today we're releasing a gem to make it easier to use React and JSX in Ruby on Rails applications: react-rails.

This gem has 2 primary purposes:

To package react.js in a way that's easy to use and easy to update.

To allow you to write JSX without an external build step to transform that into JS.

Packaging react.js #

To make react.js available for use client-side, simply add react to your manifest, and declare the variant you'd like to use in your environment. When you use :production, the minified and optimized react.min.js will be used instead of the development version. For example:

# config/environments/development.rb

MyApp::Application.configure do
  config.react.variant = :development
  # use :production in production.rb
end

// app/assets/javascript/application.js

//= require react

Writing JSX #

When you name your file with myfile.js.jsx, react-rails will automatically try to transform that file. For the time being, we still require that you include the docblock at the beginning of the file. For example, this file will get transformed on request.

/** @jsx React.DOM */
React.renderComponent(<MyComponent/>, document.getElementById('example'))

Asset Pipeline #

react-rails takes advantage of the asset pipeline that was introduced in Rails 3.1. A very important part of that pipeline is the assets:precompile Rake task. react-rails will ensure that your JSX files will be transformed into regular JS before all of your assets are minified and packaged.

Installation #

Installation follows the same process you're familiar with. You can install it globally with gem install react-rails, though we suggest you add the dependency to your Gemfile directly.

          « Previous Page

          Next Page »

        A Facebook & Instagram collaboration.

        Acknowledgements

        © 2013–2016 Facebook Inc.

        Documentation licensed under CC BY 4.0.


text:
require 'rubygems'
require 'selenium-webdriver'
require 'nokogiri'

require 'appium_lib_core'

# base
require_relative 'driver'
require_relative 'sauce_labs'

# common
require_relative 'common/wait'
require_relative 'common/log'
require_relative 'common/helper'
require_relative 'common/multi_touch'
require_relative 'common/touch_actions'
require_relative 'common/http_client'
require_relative 'common/device'
require_relative 'common/command'

# ios
require_relative 'ios/ios'

# android
require_relative 'android/android'

module Appium
  class << self
    # Load arbitrary text ([toml format](https://github.com/toml-lang/toml))
    # The toml is parsed by https://github.com/fbernier/tomlrb .
    #
    # ```
    # [caps]
    # app = "path/to/app"
    #
    # [appium_lib]
    # port = 8080
    # ```
    #
    # :app is expanded
    # :require is expanded
    # all keys are converted to symbols
    #
    # @param opts [Hash] file: '/path/to/appium.txt', verbose: true
    # @return [hash] the symbolized hash with updated :app and :require keys
    def load_settings(opts = {})
      raise 'opts must be a hash' unless opts.is_a? Hash
      raise 'opts must not be empty' if opts.empty?

      toml = opts[:file]
      raise 'Must pass a capability file which has [caps] and [appium_lib]' unless toml
      verbose = opts.fetch :verbose, false

      Appium::Logger.info "appium settings path: #{toml}" if verbose

      toml_exists = File.exist? toml
      Appium::Logger.info "Exists? #{toml_exists}" if verbose

      raise "toml doesn't exist #{toml}" unless toml_exists
      require 'tomlrb'
      Appium::Logger.info "Loading #{toml}" if verbose

      data = Tomlrb.load_file(toml, symbolize_keys: true)
      if verbose
        Appium::Logger.info data unless data.empty?
      end

      if data && data[:caps] && data[:caps][:app] && !data[:caps][:app].empty?
        data[:caps][:app] = Appium::Driver.absolute_app_path data
      end

      if data && data[:appium_lib] && data[:appium_lib][:require]
        parent_dir = File.dirname toml
        data[:appium_lib][:require] = expand_required_files(parent_dir, data[:appium_lib][:require])
      end

      data
    end
    # @see load_settings
    alias load_appium_txt load_settings

    # @param [String] base_dir parent directory of loaded appium.txt (toml)
    # @param [String] file_paths
    # @return [Array] list of require files as an array, nil if require doesn't exist
    def expand_required_files(base_dir, file_paths)
      # ensure files are absolute
      Array(file_paths).map! do |f|
        file = File.exist?(f) ? f : File.join(base_dir, f)
        file = File.expand_path file

        File.exist?(file) ? file : nil
      end
      file_paths.compact! # remove nils

      files = []

      # now expand dirs
      file_paths.each do |item|
        unless File.directory? item
          # save file
          files << item
          next # only look inside folders
        end
        Dir.glob(File.expand_path(File.join(item, '**', '*.rb'))) do |f|
          # do not add folders to the file list
          files << File.expand_path(f) unless File.directory? f
        end
      end

      files
    end

    # This method is intended to work with page objects that share
    # a common module. For example, Page::HomePage, Page::SignIn
    # those could be promoted on with Appium.promote_singleton_appium_methods Page
    #
    # If you are promoting on an individual class then you should use
    # Appium.promote_appium_methods instead. The singleton method is intended
    # only for the shared module use case.
    #
    # if modules is a module instead of an array, then the constants of
    # that module are promoted on.
    # otherwise, the array of modules will be used as the promotion target.
    #
    # @param [Array<Module>] modules An array of modules
    # @param [Driver] driver A driver to extend for
    def promote_singleton_appium_methods(modules, driver = $driver)
      raise 'Global $driver is nil' if driver.nil?

      target_modules = []

      if modules.is_a? Module
        modules.constants.each do |sub_module|
          target_modules << modules.const_get(sub_module)
        end
      else
        raise 'modules must be a module or an array' unless modules.is_a? Array
        target_modules = modules
      end

      target_modules.each do |const|
        # noinspection RubyResolve
        # rubocop:disable Style/MultilineIfModifier
        driver.public_methods(false).each do |m|
          const.send(:define_singleton_method, m) do |*args, &block|
            begin
              super(*args, &block) # promote.rb
            rescue NoMethodError, ArgumentError
              driver.send m, *args, &block if driver.respond_to?(m)
            end
            # override unless there's an existing method with matching arity
          end unless const.respond_to?(m) && const.method(m).arity == driver.method(m).arity
        end
        # rubocop:enable Style/MultilineIfModifier
      end
    end

    ##
    # Promote appium methods to class instance methods
    #
    # @param [Array<Class>] class_array An array of classes
    # @param [Driver] driver A driver to extend for
    #
    # To promote methods to all classes:
    #
    # @example
    #
    #   Appium.promote_appium_methods Object
    #
    # It's better to promote on specific classes instead of Object
    #
    # @example
    #
    #   # promote on rspec
    #   Appium.promote_appium_methods RSpec::Core::ExampleGroup
    #
    # @example
    #
    #   # promote on minispec
    #   Appium.promote_appium_methods Minitest::Spec
    #
    def promote_appium_methods(class_array, driver = $driver)
      raise 'Driver is nil' if driver.nil?
      # Wrap single class into an array
      class_array = [class_array] unless class_array.class == Array
      # Promote Appium driver methods to class instance methods.
      class_array.each do |klass|
        driver.public_methods(false).each do |m|
          klass.class_eval do
            define_method m do |*args, &block|
              begin
                # Prefer existing method.
                # super will invoke method missing on driver
                super(*args, &block)

                # minitest also defines a name method,
                # so rescue argument error
                # and call the name method on $driver
              rescue NoMethodError, ArgumentError
                driver.send m, *args, &block if driver.respond_to?(m)
              end
            end
          end
        end
      end
      nil # return nil
    end
  end # class << self
end # module Appium

redpajama_set_name: RedPajamaGithub


text:
package software.amazon.awssdk.protocols.jsoncore;

import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.protocols.jsoncore.internal.ArrayJsonNode;
import software.amazon.awssdk.protocols.jsoncore.internal.BooleanJsonNode;
import software.amazon.awssdk.protocols.jsoncore.internal.EmbeddedObjectJsonNode;
import software.amazon.awssdk.protocols.jsoncore.internal.NullJsonNode;
import software.amazon.awssdk.protocols.jsoncore.internal.NumberJsonNode;
import software.amazon.awssdk.protocols.jsoncore.internal.ObjectJsonNode;
import software.amazon.awssdk.protocols.jsoncore.internal.StringJsonNode;
import software.amazon.awssdk.thirdparty.jackson.core.JsonFactory;
import software.amazon.awssdk.thirdparty.jackson.core.JsonParseException;
import software.amazon.awssdk.thirdparty.jackson.core.JsonParser;
import software.amazon.awssdk.thirdparty.jackson.core.JsonToken;
import software.amazon.awssdk.thirdparty.jackson.core.json.JsonReadFeature;

/**
 * Parses an JSON document into a simple DOM-like structure, {@link JsonNode}.
 *
 *
This is created using {@link #create()} or {@link #builder()}.
 */
@SdkProtectedApi
public final class JsonNodeParser {
    /**
     * The default {@link JsonFactory} used for {@link #create()} or if a factory is not configured via
     * {@link Builder#jsonFactory(JsonFactory)}.
     */
    public static final JsonFactory DEFAULT_JSON_FACTORY =
        JsonFactory.builder()
                   .configure(JsonReadFeature.ALLOW_JAVA_COMMENTS, true)
                   .build();

    private final boolean removeErrorLocations;
    private final JsonFactory jsonFactory;

    private JsonNodeParser(Builder builder) {
        this.removeErrorLocations = builder.removeErrorLocations;
        this.jsonFactory = builder.jsonFactory;
    }

    /**
     * Create a parser using the default configuration.
     */
    public static JsonNodeParser create() {
        return builder().build();
    }

    /**
     * Create a parser using custom configuration.
     */
    public static JsonNodeParser.Builder builder() {
        return new Builder();
    }

    /**
     * Parse the provided {@link InputStream} into a {@link JsonNode}.
     */
    public JsonNode parse(InputStream content) {
        return invokeSafely(() -> {
            try (JsonParser parser = jsonFactory.createParser(content)
                                                .configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false)) {
                return parse(parser);
            }
        });
    }

    /**
     * Parse the provided {@code byte[]} into a {@link JsonNode}.
     */
    public JsonNode parse(byte[] content) {
        return invokeSafely(() -> {
            try (JsonParser parser = jsonFactory.createParser(content)
                                                .configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false)) {
                return parse(parser);
            }
        });
    }

    /**
     * Parse the provided {@link String} into a {@link JsonNode}.
     */
    public JsonNode parse(String content) {
        return invokeSafely(() -> {
            try (JsonParser parser = jsonFactory.createParser(content)
                                                .configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false)) {
                return parse(parser);
            }
        });
    }

    private JsonNode parse(JsonParser parser) throws IOException {
        try {
            return parseToken(parser, parser.nextToken());
        } catch (Exception e) {
            removeErrorLocationsIfRequired(e);
            throw e;
        }
    }

    private void removeErrorLocationsIfRequired(Throwable exception) {
        if (removeErrorLocations) {
            removeErrorLocations(exception);
        }
    }

    private void removeErrorLocations(Throwable exception) {
        if (exception == null) {
            return;
        }

        if (exception instanceof JsonParseException) {
            ((JsonParseException) exception).clearLocation();
        }

        removeErrorLocations(exception.getCause());
    }

    private JsonNode parseToken(JsonParser parser, JsonToken token) throws IOException {
        if (token == null) {
            return null;
        }
        switch (token) {
            case VALUE_STRING:
                return new StringJsonNode(parser.getText());
            case VALUE_FALSE:
                return new BooleanJsonNode(false);
            case VALUE_TRUE:
                return new BooleanJsonNode(true);
            case VALUE_NULL:
                return NullJsonNode.instance();
            case VALUE_NUMBER_FLOAT:
            case VALUE_NUMBER_INT:
                return new NumberJsonNode(parser.getText());
            case START_OBJECT:
                return parseObject(parser);
            case START_ARRAY:
                return parseArray(parser);
            case VALUE_EMBEDDED_OBJECT:
                return new EmbeddedObjectJsonNode(parser.getEmbeddedObject());
            default:
                throw new IllegalArgumentException("Unexpected JSON token - " + token);
        }
    }

    private JsonNode parseObject(JsonParser parser) throws IOException {
        JsonToken currentToken = parser.nextToken();
        Map<String, JsonNode> object = new LinkedHashMap<>();
        while (currentToken != JsonToken.END_OBJECT) {
            String fieldName = parser.getText();
            object.put(fieldName, parseToken(parser, parser.nextToken()));
            currentToken = parser.nextToken();
        }
        return new ObjectJsonNode(object);
    }

    private JsonNode parseArray(JsonParser parser) throws IOException {
        JsonToken currentToken = parser.nextToken();
        List<JsonNode> array = new ArrayList<>();
        while (currentToken != JsonToken.END_ARRAY) {
            array.add(parseToken(parser, currentToken));
            currentToken = parser.nextToken();
        }
        return new ArrayJsonNode(array);
    }

    /**
     * A builder for configuring and creating {@link JsonNodeParser}. Created via {@link #builder()}.
     */
    public static final class Builder {
        private JsonFactory jsonFactory = DEFAULT_JSON_FACTORY;
        private boolean removeErrorLocations = false;

        private Builder() {
        }

        /**
         * Whether error locations should be removed if parsing fails. This prevents the content of the JSON from appearing in
         * error messages. This is useful when the content of the JSON may be sensitive and not want to be logged.
         *
         *
By default, this is false.
         */
        public Builder removeErrorLocations(boolean removeErrorLocations) {
            this.removeErrorLocations = removeErrorLocations;
            return this;
        }

        /**
         * The {@link JsonFactory} implementation to be used when parsing the input. This allows JSON extensions like CBOR or
         * Ion to be supported.
         *
         *
It's highly recommended us use a shared {@code JsonFactory} where possible, so they should be stored statically:
         * http://wiki.fasterxml.com/JacksonBestPracticesPerformance
         *
         *
By default, this is {@link #DEFAULT_JSON_FACTORY}.
         */
        public Builder jsonFactory(JsonFactory jsonFactory) {
            this.jsonFactory = jsonFactory;
            return this;
        }

        /**
         * Build a {@link JsonNodeParser} based on the current configuration of this builder.
         */
        public JsonNodeParser build() {
            return new JsonNodeParser(this);
        }
    }
}


text:
namespace Google.Cloud.Compute.V1.Snippets
{
    // [START compute_v1_generated_Disks_GetIamPolicy_async_flattened]
    using Google.Cloud.Compute.V1;
    using System.Threading.Tasks;

    public sealed partial class GeneratedDisksClientSnippets
    {
        /// <summary>Snippet for GetIamPolicyAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated and should be regarded as a code template only.
        /// It will require modifications to work:
        /// - It may require correct/in-range values for request initialization.
        /// - It may require specifying regional endpoints when creating the service client as shown in
        ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
        /// </remarks>
        public async Task GetIamPolicyAsync()
        {
            // Create client
            DisksClient disksClient = await DisksClient.CreateAsync();
            // Initialize request argument(s)
            string project = "";
            string zone = "";
            string resource = "";
            // Make the request
            Policy response = await disksClient.GetIamPolicyAsync(project, zone, resource);
        }
    }
    // [END compute_v1_generated_Disks_GetIamPolicy_async_flattened]
}


text:
pub mod array;
pub mod array_data;
pub mod bitmap;
pub mod buffer;
pub mod builder;
pub mod compute;
pub mod csv;
pub mod datatypes;
pub mod error;
pub mod json;
pub mod memory;
pub mod record_batch;
pub mod tensor;
pub mod util;


text:
"K-Nearest-Neighbors Classifier with test data"

import csv
import math
import operator
import copy
import sys

#offset values by a small amount to avoid division by 0
EPSI = sys.float_info.epsilon

#functions

#main function
def main():
    "main function"
    BUPA_NUM_ATTRIBUTES = 7
    CAR_NUM_ATTRIBUTES = 7

    BUPA_CLASS_INDEX = 6
    CAR_CLASS_INDEX = 6

    MIN_K = 15
    MAX_K = 15

    #numerical conversions for non-numerical car data
    CAR_VALUES = [
        {'vhigh' : 4.0,
         'high' : 3.0,
         'med' : 2.0,
         'low' : 1.0},
        {'vhigh' : 4.0,
         'high' : 3.0,
         'med' : 2.0,
         'low' : 1.0},
        {'5more' : 5.0},
        {'more' : 6.0},
        {'small' : 1.0,
         'med' : 2.0,
         'big' : 3.0},
        {'low' : 1.0,
         'med' : 2.0,
         'high' : 3.0},
        {'unacc' : 1.0,
         'acc' : 2.0,
         'good' : 3.0,
         'vgood' : 4.0}
        ]

    #load BUPA set
    BUPATrainingSet = loadcsv("bupa_data_trainset.csv")
    BUPATestSet = loadcsv("bupa_data_testset.csv")
    #print set details
    print("BUPA set: ")
    printDetails(BUPATrainingSet, BUPA_CLASS_INDEX)
    print()
    runClassification(BUPATrainingSet, BUPATestSet, BUPA_CLASS_INDEX, True, MIN_K, MAX_K)
    print("\nReversing testing and training sets...\n")
    printDetails(BUPATestSet, BUPA_CLASS_INDEX)
    print()
    runClassification(BUPATestSet, BUPATrainingSet, BUPA_CLASS_INDEX, True, MIN_K, MAX_K)
    print()

    #load car set
    carTrainingSet = loadcsv("car_data_trainset.csv")
    carTestSet = loadcsv("car_data_testset.csv")
    print("Car set: ")
    printDetails(carTrainingSet, CAR_CLASS_INDEX)
    print()
    #convert car data to purely numerical values
    convertedCarTrainingSet = convertData(carTrainingSet, CAR_VALUES)
    convertedCarTestSet = convertData(carTestSet, CAR_VALUES)
    runClassification(convertedCarTrainingSet, convertedCarTestSet, CAR_CLASS_INDEX, False, MIN_K, MAX_K)
    print("\nReversing testing and training sets...\n")
    printDetails(carTestSet, CAR_CLASS_INDEX)
    print()
    runClassification(convertedCarTestSet, convertedCarTrainingSet, CAR_CLASS_INDEX, False, MIN_K, MAX_K)

#run knn classification for the given training and test sets, with classifications at the given index, for the given k range, and print results
#whether the classifier is nominal or not is indicated by the flag nominal
#an optional parameter positive classifiers provides a list of classifiers considered "positive" for evaluating recall and precision, if not provided only accuracy calculated
def runClassification(trainingSet, testSet, classIndex, nominal, minK, maxK):
    #separate out classification data
    rawTrainingSet = separateClass(trainingSet, classIndex)
    rawTestSet = separateClass(testSet, classIndex)
    #get normalized training sets and zip with classification data
    #zipped with classification data so classification order maintained when sorted
    normalizedTrainingSet = list(zip(normalize(rawTrainingSet[0]), rawTrainingSet[1]))
    rawTrainingSet = list(zip(rawTrainingSet[0], rawTrainingSet[1]))
    #get normalized test sets
    #leave testing classifiers unzipped since order will remain the same, and simplifies element iteration
    normalizedTestSet = (normalize(rawTestSet[0]), rawTestSet[1])
    #sets to run classification on
    sets = [(('e',  normalizedTestSet, normalizedTrainingSet), "Euclidian Distance"),
            (('c',  normalizedTestSet, normalizedTrainingSet), "Cosine Similarity"),
            (('p',  rawTestSet, rawTrainingSet), "Pearson Correlation")]

    maxAccuracy = (0, 0, 0)
    maxRecall = (0, 0, 0)
    maxPrecision = (0, 0, 0)
    #classify for specified k range
    for k in range(minK, maxK + 1):
        print("k: " + str(k))
        #classify each set type
        for set in sets:
            classification = []
            print("Function: " + set[1])
            #get classifications
            classification = classify(k, nominal, *set[0])
            print()
            #get confusion matrix for classification
            confusion = getConfusion(classification, set[0][1][1])
            print("Confusion Matrix:")
            printConfusion(confusion)
            print()
            #get accuracy, recall, and precision for each class and global accuracy of the classifier
            arp = ARPStats(confusion)
            #print statistics
            print("Classifiers:\n")
            for classifier in arp[0]:
                print(str(classifier) + ": ")
                print("Accuracy: " + str(arp[0][classifier][0]))
                print("Recall: " + str(arp[0][classifier][1]))
                print("Precision: " + str(arp[0][classifier][2]) + "\n")
            print("Total:")
            print("Accuracy: " + str(arp[1]))
            print()
            #determine which classification technique and k value in range gave best accuracy
            if arp[1] > maxAccuracy[0]:
                maxAccuracy = (arp[1], k, set[1])
        print()
    print("Maximum Accuracy: " + str(maxAccuracy))
    return

def printDetails(dataSet, classIndex):
    #get number of each class
    numClass = numClassification(set[classIndex] for set in dataSet)
    #get number of attributes
    numAttributes = len(dataSet[0])
    #print details
    print("Data set contains " + str(len(numClass)) + " classifiers:")
    for classifier in numClass:
        print(str(classifier) + ": " + str(numClass[classifier]))
    print("Total attributes: " + str(numAttributes))

def numClassification(classifiers):
    found = {}
    #count number of each classifier in given set
    for classifier in classifiers:
        if classifier not in found:
            found[classifier] = 1
        else:
            found[classifier] += 1
    return found

#convert data to numerical data based on provided value conversion dictionary
#for classification to work properly classifiers must be
def convertData(dataSet, valueIndex):
    set = copy.deepcopy(dataSet)
    numAttributes = len(dataSet[0])
    #convert data
    for element in set:
        for i in range(numAttributes):
            if element[i] in valueIndex[i]:
                element[i] = valueIndex[i][element[i]]
    return set

#offset values by global value epsilon
def offsetEpsi(numericalDataSet):
    for row in numericalDataSet:
        for element in row:
            element += EPSI
    return numericalDataSet

#print confusion matrix for given 2d dictionary of classifiers
def printConfusion(confusion):
    first = True
    print("\t\tPredicted")
    print('\t\t', end = '')
    for classifier in confusion:
        print(str(classifier) + '\t', end = '')
    print()
    for classifier1 in confusion:
        if first:
            print("Actual", end = '')
            first = False
        print('\t' + str(classifier1), end = '\t')
        for classifier2 in confusion[classifier1]:
            print(str(confusion[classifier1][classifier2]) + '\t', end = '')
        print()

#get the accuracy, precision, and recall for each class and the total classification accuracy from the given confusion matrix
def ARPStats(confusion):
    stats = {}
    totalT = 0
    totalF = 0
    totalAccuracy = 0
    #find true positives, true negatives, false positives, and false negatives for each class
    for classifier in confusion:
        TP = 0
        TN = 0
        FP = 0
        FN = 0
        TP += confusion[classifier][classifier]
        #total correctly classified values for global accuracy
        totalT += confusion[classifier][classifier]
        for classifier2 in confusion:
            if classifier2 != classifier:
                #total incorrectly classified values for global accuracy
                totalF += confusion[classifier][classifier2]
                FN += confusion[classifier][classifier2]
                FP += confusion[classifier2][classifier]
                for offClass in confusion:
                    if offClass != classifier:
                        TN += confusion[classifier2][offClass]
        #calculate class accuracy, recall and precision from found values
        try:
            accuracy = (TP + TN) / (TP + TN + FP + FN) * 100
        except ZeroDivisionError:
            accuracy = 'N/A'
        try:
            recall = TP / (TP + FN) * 100
        except ZeroDivisionError:
            recall = 'N/A'
        try:
            precision = TP / (TP + FP) * 100
        except ZeroDivisionError:
            precision = 'N/A'
        stats[classifier] = (accuracy, recall, precision)
    #calculate total accuracy
    totalAccuracy = totalT / (totalT + totalF) * 100
    return (stats, totalAccuracy)

#build a 2d disctionary of classifiers representing the confusion matrix for the classification
def getConfusion(computedClassification, knownClassification):
    classifiers = []
    confusion = {}
    for classifier in knownClassification:
        if classifier not in classifiers:
            classifiers.append(classifier)
    for classifier1 in classifiers:
        confusion[classifier1] = {}
        for classifier2 in classifiers:
            confusion[classifier1][classifier2] = 0
    #count classifications in each category for each class
    for classifier in zip(knownClassification, computedClassification):
        confusion[classifier[0]][classifier[1]] += 1
    return confusion

#compute accuracy of a classification
def getAccuracy(computedClassification, knownClassification):
    accurate = 0
    #count accurate classifications
    for classifier in zip(computedClassification, knownClassification):
        #print(classifier[0])
        if classifier[0] == classifier[1]:
            accurate += 1
    #calculate percent accuaracy
    return float(accurate) / len(knownClassification) * 100

#classify data with k nearest neighbors function
def classify(k, nominal, distanceFunction, testSet, trainingSet):
    classification = []

    #classify on greatest number of similar classifiers if classifier nominal
    if nominal:
        classifiers = {}
        #enumerate possible classifiers
        for point in trainingSet:
            if point[1] not in classifiers:
                classifiers[point[1]] = 0
        #classify each point in set
        for point in testSet[0]:
            average = 0
            for classifier in knn(distanceFunction, trainingSet, point, k):
                classifiers[classifier] += 1
            classification.append(max(classifiers, key = lambda value: classifiers[value]))
            #reset counts
            for classifier in classifiers:
                classifiers[classifier] = 0

    #classifiy on average of classifiers if classifier ordinal
    else:
        classifiers = []
        #enumerate possible classifiers
        for point in trainingSet:
            if point[1] not in classifiers:
                classifiers.append(point[1])
        for point in testSet[0]:
            average = 0
            #enumerate possible classifiers
            for classifier in knn(distanceFunction, trainingSet, point, k):
                average += classifier
            #ensure average properly computed by casting
            average = float(average) / k
            #find the classifier that is closest to the average
            closestClassifier = 0
            minDifference = math.inf
            classification.append(min(classifiers, key = lambda val: abs(average - val)))
            #for classifier in classifiers:
            #    if abs(average - classifier) < minDifference:
            #        closestClassifier = classifier
            #        minDifference = abs(average - classifier)
            #classification.append(closestClassifier)

    #return list of classifications for each point
    return classification

#seperate out classification attribute from data set
def separateClass(dataSet, classIndex):
    set = copy.deepcopy(dataSet)
    classifier = []
    for item in set:
        classifier.append(item.pop(classIndex))
    #offset non-classifiers by epsi to avoid zero division
    return (offsetEpsi(set), classifier)

#normalize a data set by placing values between epsilon and 1 + epsilon
def normalize(set):
    numAttributes = len(set[0])
    numRows = len(set)
    setRange = []
    norm = [[] for _ in range(numRows)]
    #find maxes and mins of each attribute
    for i in range(numAttributes):
        setRange.append((max(set, key = lambda row: row[i])[i], min(set, key = lambda row: row[i])[i]))
        for j in range(numRows):
            #normalize to set range, with the minimum value at epsilon, and the maximum at 1 + epsilon
            #range offset by epsilon to avoid 0 division if a 0 vector is created
            norm[j].append(((set[j][i] - setRange[i][1]) / (setRange[i][0] - setRange[i][1])) + EPSI)
    return norm

#load a CSV file and return list of vectors
def loadcsv(fname):
    "loads a csv file"
    rlist = []
    test = 0
    #open file for reading
    with open(fname, 'r') as fvar:
        reader = csv.reader(fvar)
        #read each row into array and attempt to convert attributes to numbers if numerical values
        for row in reader:
            row[:] = [(float(item)) if testNum(item) else item for item in row]
            rlist.append(row)
    return rlist

#test if given value is a number
def testNum(f):
    try:
        float(f)
        return True
    except ValueError:
        return False

#Euclidean Distance Function 2 vectors
def edist2(vector1, vector2):
    "Euclidean Distance Function for 2 Vectors"
    #assumes both vectors same dimensionality
    dist = 0
    length = len(vector1)
    for i in range(length):
        dist += pow((vector1[i] - vector2[i]), 2)
    return math.sqrt(dist)

#Dot Product
def dprod(vector1, vector2):
    "Dot Product"
    if len(vector1) != len(vector2):
        return 0
    return sum(i[0] * i[1] for i in zip(vector1, vector2))

#Euclidean Distance Function 1 vector
def edist(vector1):
    "Euclidean Distance Function for 1 Vector"
    dist = 0
    for item in vector1:
        dist += pow(item, 2)
    return math.sqrt(dist)

#Cosine Similarity Function
def cosim(vector1, vector2):
    "Cosine Similarity Function"
    return dprod(vector1, vector2) / (edist(vector1) * edist(vector2))

#Pearsons Correlation
def pearson(vector1, vector2):
    "Pearson Correlation"
    xbar = 0
    ybar = 0
    sxy = 0
    sx = 0
    sy = 0
    n = len(vector1)
    for i in range(0, n):
        xbar += vector1[i]
        ybar += vector2[i]
    xbar /= n
    ybar /= n
    for i in range(0, n):
        sx += pow(vector1[i] - xbar, 2)
    sx /= n - 1
    sx = math.sqrt(sx)
    for i in range(0, n):
        sy += pow(vector2[i] - ybar, 2)
    sy /= n - 1
    sy = math.sqrt(sy)
    if sx == 0 or sy == 0:
        return 0
    for i in range(0, n):
        sxy += (vector1[i] - xbar) * (vector2[i] - ybar)
    sxy /= n - 1
    return sxy / (sx * sy)

#get k nearest neighbors
def knn(distanceFunction, dataSet, dataPoint, k):
    "Get Neighbors"
    dist = []
    #run using specified distance function
    if distanceFunction == 'e':
        #evaluate distance to points in training set
        for i in range(0, len(dataSet)):
            dist.append((dataSet[i], edist2(dataPoint, dataSet[i][0])))
        #sort points and select nearest points based on type of distance function
        dist.sort(key = operator.itemgetter(1))
        return [element[0][1] for element in dist[:k]]
    elif distanceFunction == 'c':
        for i in range(0, len(dataSet)):
            dist.append((dataSet[i], cosim(dataPoint, dataSet[i][0])))
        dist.sort(key = operator.itemgetter(1))
        return [element[0][1] for element in dist[-k:]]
    elif distanceFunction == 'p':
        for i in range(0, len(dataSet)):
            #use absolute value of distance evaluation since 0 is lowest correlation and range is on [-1, 1]
            dist.append((dataSet[i], abs(pearson(dataPoint, dataSet[i][0]))))
        dist.sort(key = operator.itemgetter(1))
        return [element[0][1] for element in dist[-k:]]
    else:
        raise ValueError("Invalid distance function type")

#main block
main()


text:
namespace pwn
{
namespace render
{
    World3Widget::World3Widget(
            const Dock& dock,
            boost::shared_ptr<World3> world)
        : Widget(dock)
        , world(world)
        , camera(math::Origo3(), math::qIdentity(), 45.0f, 0.5f, 1000.0f)
    {
    }

    World3Widget::~World3Widget()
    {
    }

    void
    World3Widget::updateCamera(const Camera& camera)
    {
        this->camera = camera;
    }

    void
    World3Widget::render(int width, int height)
    {
        const math::rect rect = dock.getRect(width, height);
        const int x = static_cast<GLsizei>(LeftOf(rect));
        const int y = -static_cast<GLsizei>(TopOf(rect));
        const int w = static_cast<GLsizei>(WidthOf(rect));
        const int h = static_cast<GLsizei>(HeightOf(rect));

        // todo: test for mask occlusion and possible render to a temporary texture
        RenderArgs ra(camera, x, y, w, h, AspectOf(rect));
        Assert(camera.pipeline);
        if (camera.pipeline)
        {
            camera.pipeline->render(world.get(), ra);
        }
        glDisable(GL_DEPTH_TEST);
        pwnAssert_NoGLError();
    }
}
}


text:
using System;

namespace Person
{
    class StartUpPerson
    {
        public static void Main(string[] args)
        {
            var firstPerson = new Person(27);
            Console.WriteLine(firstPerson.ToString());

            var secondPerson = new Person(30);
            Console.WriteLine(secondPerson.ToString());
        }
    }
}


text:
import { useRouter } from 'next/router'
import Link from 'next/link'
import styles from '../../styles.module.css'
import Code from '../../components/Code'

export default function News() {
  const { asPath, route, query } = useRouter()

  return (

Path: {asPath}

          This page was rendered by {`pages${route}.tsx`}.

          The query slug for this page is:{' '}
          {JSON.stringify(query.slug)}

        <Link href="/">← Back home</Link>

  )
}


text:
echo `date` "Running mongod repair"
/usr/bin/mongod --repair --config /etc/mongod.conf

echo `date` "Starting MongoDB"
/usr/bin/mongod --config /etc/mongod.conf --fork --smallfiles

# Test for and execute a hook script (to be past by docker images layered
# on top of this image.
if [ -x /start-image-hook.sh ]
then
  echo `date` "Running start-image-hook"
  . /start-image-hook.sh
fi

echo `date` "Preparing MEAN.IO Appserver"
su - mean -c "cd appserver && gulp cssmin && gulp uglify"

echo `date` "Starting MEAN.IO Appserver. NODEARGS:${NODEARGS} MEANARGS:${MEANARGS}"
su - mean -c "cd appserver && NODE_ENV=production forever --spinSleepTime=5000 --killSignal=SIGTERM ${FOREVERARGS} -c 'node ${NODEARGS}' server.js ${MEANARGS}"


text:
package s3

import (
	"fmt"
	"net/url"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/s3"

	"k8s.io/test-infra/boskos/aws-janitor/regions"
)

type Path struct {
	Region string
	Bucket string
	Key    string
}

func GetPath(sess *session.Session, s string) (*Path, error) {
	url, err := url.Parse(s)
	if err != nil {
		return nil, err
	}

	if url.Scheme != "s3" {
		return nil, fmt.Errorf("Scheme %q != 's3'", url.Scheme)
	}

	svc := s3.New(sess, &aws.Config{Region: aws.String(regions.Default)})

	resp, err := svc.GetBucketLocation(&s3.GetBucketLocationInput{Bucket: aws.String(url.Host)})
	if err != nil {
		return nil, err
	}

	region := regions.Default
	if resp.LocationConstraint != nil {
		region = *resp.LocationConstraint
	}

	return &Path{Region: region, Bucket: url.Host, Key: url.Path}, nil
}


text:
package org.mifos.test.acceptance.core;

import java.io.File;
import java.io.FilenameFilter;

import org.dbunit.dataset.IDataSet;
import org.mifos.framework.util.DbUnitUtilities;
import org.mifos.test.acceptance.framework.MifosPage;
import org.mifos.test.acceptance.framework.UiTestCaseBase;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.test.context.ContextConfiguration;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;

@ContextConfiguration(locations = { "classpath:ui-test-context.xml" })
@Test(sequential = true, groups = {"core","acceptance"})
public class DatasetVersionTest extends UiTestCaseBase {

    @Autowired
    private DriverManagerDataSource dataSource;
    @Autowired
    private DbUnitUtilities dbUnitUtilities;

    @AfterMethod
    public void logOut() {
        (new MifosPage(selenium)).logout();
    }

    @SuppressWarnings("PMD.SignatureDeclareThrowsException")
    public void checkDataSetDatabaseVersion() throws Exception {

        class FileExtensionFilter implements FilenameFilter{
            String prefix="*";
            String ext="*";
            public FileExtensionFilter(String prefix, String ext){
                this.prefix = prefix;
                this.ext = ext;
            }

            public boolean accept(@SuppressWarnings("unused") File dir, String name){
                boolean validFile = false;
                if (name.startsWith(prefix) && name.endsWith(ext) ){
                    validFile = true;
                }
                return validFile;
            }
        }

        // FIXME - Path works for maven build but not from eclipse
        // To run this test in eclipse, change path below to: "acceptanceTests/target/test-classes/dataSets"
        File f = new File("target/test-classes/dataSets");
        FileExtensionFilter filter = new FileExtensionFilter("", "dbunit.xml.zip");
        File[] acceptList = f.listFiles(filter);

        for (File element : acceptList) {
            verifyDatabaseVersion(element.getName());
        }
    }

    @SuppressWarnings("PMD.SignatureDeclareThrowsException")
    private void verifyDatabaseVersion(String acceptanceDataSetFile) throws Exception {
        String[] tablesToValidate = { "DATABASE_VERSION" };

        IDataSet acceptanceDataSet = dbUnitUtilities.getDataSetFromDataSetDirectoryFile(acceptanceDataSetFile);
        IDataSet databaseDataSet = dbUnitUtilities.getDataSetForTables(dataSource, tablesToValidate);

        //compare acceptance data set version to db version on running application
        dbUnitUtilities.verifyTables(tablesToValidate, acceptanceDataSet, databaseDataSet);

    }
}


text:
// Type definitions for pacote 9.5
// Project: https://github.com/npm/pacote#readme
// Definitions by: Joel Spadin <https://github.com/ChaosinaCan>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 3.0

/// <reference types="node" />

import { Readable } from 'stream';
import npmFetch = require('npm-registry-fetch');

import extract = require('./extract');
import manifest = require('./manifest');
import packument = require('./packument');
import prefetch = require('./prefetch');
import tarball = require('./tarball');

export { extract, manifest, packument, prefetch, tarball };

/**
 * This utility function can be used to force pacote to release its references
 * to any memoized data in its various internal caches. It might help free some
 * memory.
 */
export function clearMemoized(): void;

export interface Manifest {
    name: string;
    version: string;
    dependencies: Record<string, string>;
    optionalDependencies: Record<string, string>;
    devDependencies: Record<string, string>;
    peerDependencies: Record<string, string>;
    bundleDependencies: false | string[];
    bin: Record<string, string> | null;
    _resolved: string;
    _integrity: string;
    _shrinkwrap: Record<string, unknown> | null;

    engines?: Record<string, string> | undefined;
    cpu?: string[] | undefined;
    os?: string[] | undefined;
    _id?: string | undefined;

    [key: string]: unknown;
}

export interface PackageDist {
    shasum: string;
    tarball: string;
    integrity?: string | undefined;
    fileCount?: number | undefined;
    unpackedSize?: number | undefined;
}

export interface Human {
    name: string;
    email?: string | undefined;
    url?: string | undefined;
}

export interface PackageVersion {
    name: string;
    version: string;
    dependencies?: Record<string, string> | undefined;
    optionalDependencies?: Record<string, string> | undefined;
    devDependencies?: Record<string, string> | undefined;
    peerDependencies?: Record<string, string> | undefined;
    directories: {};
    dist: PackageDist;
    _hasShrinkwrap: boolean;

    // Extra metadata which may be added by the registry:
    description?: string | undefined;
    main?: string | undefined;
    scripts?: Record<string, string> | undefined;
    repository?: {
        type: string;
        url: string;
        directory?: string | undefined;
    } | undefined;
    engines?: Record<string, string> | undefined;
    keywords?: string[] | undefined;
    author?: Human | undefined;
    contributors?: Human[] | undefined;
    maintainers?: Human[] | undefined;
    license?: string | undefined;
    homepage?: string | undefined;
    bugs?: { url: string } | undefined;
    _id?: string | undefined;
    _nodeVersion?: string | undefined;
    _npmVersion?: string | undefined;
    _npmUser?: Human | undefined;

    [key: string]: unknown;
}

export interface Packument {
    name: string;
    'dist-tags': { latest: string; } & Record<string, string>;
    versions: Record<string, PackageVersion>;

    [key: string]: unknown;
}

export interface PacoteOptions {
    /**
     * Expects a function that takes a single argument, `dir`, and returns a
     * `ReadableStream` that outputs packaged tarball data. Used when creating
     * tarballs for package specs that are not already packaged, such as git and
     * directory dependencies. The default `opts.dirPacker` does not execute
     * `prepare` scripts, even though npm itself does.
     */
    dirPacker?: ((dir: string) => Readable) | undefined;
    /**
     * If passed in, will be used while resolving to filter the versions for
     * **registry dependencies** such that versions published **after**
     * `opts.enjoy-by` are not considered -- as if they'd never been published.
     */
    'enjoy-by'?: Date | string | number | undefined;
    /** Alias for `enjoy-by` */
    enjoyBy?: Date | string | number | undefined;
    /** Alias for `enjoy-by` */
    before?: Date | string | number | undefined;
    /**
     * If false, deprecated versions will be skipped when selecting from
     * registry range specifiers. If true, deprecations do not affect version
     * selection.
     */
    'include-deprecated'?: boolean | undefined;
    /** Alias for 'include-deprecated' */
    includeDeprecated?: boolean | undefined;
    /**
     * If `true`, the full packument will be fetched when doing metadata
     * requests. By default, pacote only fetches the summarized packuments, also
     * called "corgis".
     */
    'full-metadata'?: boolean | undefined;
    /**
     * Package version resolution tag. When processing registry spec ranges,
     * this option is used to determine what dist-tag to treat as "latest". For
     * more details about how `pacote` selects versions and how `tag` is
     * involved, see [the documentation for `npm-pick-manifest`](https://npm.im/npm-pick-manifest).
     */
    tag?: string | undefined;
    /** Alias for `tag` */
    defaultTag?: string | undefined;
    /**
     * When fetching tarballs, this option can be passed in to skip registry
     * metadata lookups when downloading tarballs. If the string is a `file:`
     * URL, pacote will try to read the referenced local file before attempting
     * to do any further lookups. This option does not bypass integrity checks
     * when `opts.integrity` is passed in.
     */
    resolved?: string | undefined;
    /**
     * Passed as an argument to [`npm-package-arg`](https://npm.im/npm-package-arg)
     * when resolving `spec` arguments. Used to determine what path to resolve
     * local path specs relatively from.
     */
    where?: string | undefined;
}

export type Options = PacoteOptions & npmFetch.Options;


text:
layout: post
title: Jersey, from Android to Mainframe
excerpt: As usual, the Jersey Team is busy cranking out new releases...
---

As usual, the Jersey Team is busy cranking out new releases. In February, the team has released [Jersey 2.16](https://github.com/jersey/jersey/releases/tag/2.16) and [Jersey 1.19](https://github.com/jersey/jersey-1.x/releases/tag/1.19) (see related [blog](https://blog.dejavu.sk/2015/02/13/jersey-1-19-is-released/)).

Jersey has a large, active and involved community. For example, there was a bug in Jersey when used on z/OS (who doesn't use Jersey on z/OS?). A community member raised this particular issue along with a suggested fix, fix which has been integrated in 2.16.

Jersey 2.16 is also solving some of the issues related to [running the Jersey client stack on Android](https://blogs.oracle.com/japod/jersey-2x-client-on-android). Supporting Android is more a side project and Jersey 2.16 clearly shows some initial success. But more work needs to be done. The Jersey Team is looking for concrete feedback on real uses-cases and why not, community contributions too.

So with 2.16, you can finally run a Jersey client on an Android phone connecting to a Jersey server running on Z/OS! Yeah!

And it's not because the Jersey community is already large and active that you cannot participate, contributions are always welcome! See here on the different ways to contribute to Jersey.

*Originaly posted on [The Aquarium](https://blogs.oracle.com/theaquarium/jersey%2C-from-android-to-mainframe) blog.*


text:
package pav.sprykerFileCreator.model.definition.spryker;

import pav.sprykerFileCreator.model.definition.ClassDefinitionInterface;
import pav.sprykerFileCreator.model.generator.SprykerConstants;

public class ClientDefinition implements ClassDefinitionInterface {

    @Override
    public String getClassType() {
        return SprykerConstants.CLIENT;
    }

    @Override
    public String getNamePattern() {
        return "{{ bundleName }}Client";
    }

    @Override
    public String getNamespacePattern() {
        return "{{ projectName }}\\Client\\{{ bundleName }}";
    }

    @Override
    public String getMethodForReturnType() {
        return "getClient()";
    }

    @Override
    public String[] getDocBlockClasses() {
        String [] docBlockClasses = {};

        return docBlockClasses;
    }

    @Override
    public String getDefaultParentClass() {
        return null;
    }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using RestSharp.Deserializers;
using StockFighter.Common;

namespace StockFighter.Gamemaster.Responses
{
    /// <summary>
    /// Response from starting a StockFighter level.
    /// </summary>
    public class StartedLevel : APIResponse
    {
        /// <summary>
        /// The account for the level.
        /// </summary>
        public string account { get; set; }
        /// <summary>
        /// The instance ID of the level.
        /// </summary>
        public int instanceId { get; set; }
        /// <summary>
        /// The list of instructions.
        /// </summary>
        public List<instruction> instructions { get; set; }
        /// <summary>
        /// The seconds per trading day.
        /// </summary>
        public int secondsPerTradingDay { get; set; }
        /// <summary>
        /// The list of tickers.
        /// </summary>
        public List<string> tickers { get; set; }
        /// <summary>
        /// The list of venues.
        /// </summary>
        public List<string> venues { get; set; }
        /// <summary>
        /// The list of balances.
        /// </summary>
        public List<balance> balances { get; set; }

        /// <summary>
        /// An instruction for a level.
        /// </summary>
        public class instruction
        {
            /// <summary>
            /// The text for one instruction.
            /// </summary>
            public string Instructions { get; set; }
            /// <summary>
            /// The type of order.
            /// </summary>
            [DeserializeAs(Name = "Order Types")]
            public string OrderTypes { get; set; }
        }

        /// <summary>
        /// A balance for a level.
        /// </summary>
        public class balance
        {
            /// <summary>
            /// The balance in United States dollars.
            /// </summary>
            public int USD { get; set; }
        }
    }
}


text:
from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
import warnings

from google.api_core import gapic_v1, grpc_helpers_async, operations_v1
from google.auth import credentials as ga_credentials  # type: ignore
from google.auth.transport.grpc import SslCredentials  # type: ignore
from google.longrunning import operations_pb2  # type: ignore
import grpc  # type: ignore
from grpc.experimental import aio  # type: ignore

from google.cloud.network_management_v1.types import connectivity_test, reachability

from .base import DEFAULT_CLIENT_INFO, ReachabilityServiceTransport
from .grpc import ReachabilityServiceGrpcTransport

class ReachabilityServiceGrpcAsyncIOTransport(ReachabilityServiceTransport):
    """gRPC AsyncIO backend transport for ReachabilityService.

    The Reachability service in the Google Cloud Network
    Management API provides services that analyze the reachability
    within a single Google Virtual Private Cloud (VPC) network,
    between peered VPC networks, between VPC and on-premises
    networks, or between VPC networks and internet hosts. A
    reachability analysis is based on Google Cloud network
    configurations.

    You can use the analysis results to verify these configurations
    and to troubleshoot connectivity issues.

    This class defines the same methods as the primary client, so the
    primary client can load the underlying transport implementation
    and call it.

    It sends protocol buffers over the wire using gRPC (which is built on
    top of HTTP/2); the ``grpcio`` package must be installed.
    """

    _grpc_channel: aio.Channel
    _stubs: Dict[str, Callable] = {}

    @classmethod
    def create_channel(
        cls,
        host: str = "networkmanagement.googleapis.com",
        credentials: ga_credentials.Credentials = None,
        credentials_file: Optional[str] = None,
        scopes: Optional[Sequence[str]] = None,
        quota_project_id: Optional[str] = None,
        **kwargs,
    ) -> aio.Channel:
        """Create and return a gRPC AsyncIO channel object.
        Args:
            host (Optional[str]): The host for the channel to use.
            credentials (Optional[~.Credentials]): The
                authorization credentials to attach to requests. These
                credentials identify this application to the service. If
                none are specified, the client will attempt to ascertain
                the credentials from the environment.
            credentials_file (Optional[str]): A file with credentials that can
                be loaded with :func:`google.auth.load_credentials_from_file`.
                This argument is ignored if ``channel`` is provided.
            scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
                service. These are only used when credentials are not specified and
                are passed to :func:`google.auth.default`.
            quota_project_id (Optional[str]): An optional project to use for billing
                and quota.
            kwargs (Optional[dict]): Keyword arguments, which are passed to the
                channel creation.
        Returns:
            aio.Channel: A gRPC AsyncIO channel object.
        """

        return grpc_helpers_async.create_channel(
            host,
            credentials=credentials,
            credentials_file=credentials_file,
            quota_project_id=quota_project_id,
            default_scopes=cls.AUTH_SCOPES,
            scopes=scopes,
            default_host=cls.DEFAULT_HOST,
            **kwargs,
        )

    def __init__(
        self,
        *,
        host: str = "networkmanagement.googleapis.com",
        credentials: ga_credentials.Credentials = None,
        credentials_file: Optional[str] = None,
        scopes: Optional[Sequence[str]] = None,
        channel: aio.Channel = None,
        api_mtls_endpoint: str = None,
        client_cert_source: Callable[[], Tuple[bytes, bytes]] = None,
        ssl_channel_credentials: grpc.ChannelCredentials = None,
        client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None,
        quota_project_id=None,
        client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
        always_use_jwt_access: Optional[bool] = False,
        api_audience: Optional[str] = None,
    ) -> None:
        """Instantiate the transport.

        Args:
            host (Optional[str]):
                 The hostname to connect to.
            credentials (Optional[google.auth.credentials.Credentials]): The
                authorization credentials to attach to requests. These
                credentials identify the application to the service; if none
                are specified, the client will attempt to ascertain the
                credentials from the environment.
                This argument is ignored if ``channel`` is provided.
            credentials_file (Optional[str]): A file with credentials that can
                be loaded with :func:`google.auth.load_credentials_from_file`.
                This argument is ignored if ``channel`` is provided.
            scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
                service. These are only used when credentials are not specified and
                are passed to :func:`google.auth.default`.
            channel (Optional[aio.Channel]): A ``Channel`` instance through
                which to make calls.
            api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.
                If provided, it overrides the ``host`` argument and tries to create
                a mutual TLS channel with client SSL credentials from
                ``client_cert_source`` or application default SSL credentials.
            client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):
                Deprecated. A callback to provide client SSL certificate bytes and
                private key bytes, both in PEM format. It is ignored if
                ``api_mtls_endpoint`` is None.
            ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
                for the grpc channel. It is ignored if ``channel`` is provided.
            client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
                A callback to provide client certificate bytes and private key bytes,
                both in PEM format. It is used to configure a mutual TLS channel. It is
                ignored if ``channel`` or ``ssl_channel_credentials`` is provided.
            quota_project_id (Optional[str]): An optional project to use for billing
                and quota.
            client_info (google.api_core.gapic_v1.client_info.ClientInfo):
                The client info used to send a user-agent string along with
                API requests. If ``None``, then default info will be used.
                Generally, you only need to set this if you're developing
                your own client library.
            always_use_jwt_access (Optional[bool]): Whether self signed JWT should
                be used for service account credentials.

        Raises:
            google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
              creation failed for any reason.
          google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
              and ``credentials_file`` are passed.
        """
        self._grpc_channel = None
        self._ssl_channel_credentials = ssl_channel_credentials
        self._stubs: Dict[str, Callable] = {}
        self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None

        if api_mtls_endpoint:
            warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
        if client_cert_source:
            warnings.warn("client_cert_source is deprecated", DeprecationWarning)

        if channel:
            # Ignore credentials if a channel was passed.
            credentials = False
            # If a channel was explicitly provided, set it.
            self._grpc_channel = channel
            self._ssl_channel_credentials = None
        else:
            if api_mtls_endpoint:
                host = api_mtls_endpoint

                # Create SSL credentials with client_cert_source or application
                # default SSL credentials.
                if client_cert_source:
                    cert, key = client_cert_source()
                    self._ssl_channel_credentials = grpc.ssl_channel_credentials(
                        certificate_chain=cert, private_key=key
                    )
                else:
                    self._ssl_channel_credentials = SslCredentials().ssl_credentials

            else:
                if client_cert_source_for_mtls and not ssl_channel_credentials:
                    cert, key = client_cert_source_for_mtls()
                    self._ssl_channel_credentials = grpc.ssl_channel_credentials(
                        certificate_chain=cert, private_key=key
                    )

        # The base transport sets the host, credentials and scopes
        super().__init__(
            host=host,
            credentials=credentials,
            credentials_file=credentials_file,
            scopes=scopes,
            quota_project_id=quota_project_id,
            client_info=client_info,
            always_use_jwt_access=always_use_jwt_access,
            api_audience=api_audience,
        )

        if not self._grpc_channel:
            self._grpc_channel = type(self).create_channel(
                self._host,
                # use the credentials which are saved
                credentials=self._credentials,
                # Set ``credentials_file`` to ``None`` here as
                # the credentials that we saved earlier should be used.
                credentials_file=None,
                scopes=self._scopes,
                ssl_credentials=self._ssl_channel_credentials,
                quota_project_id=quota_project_id,
                options=[
                    ("grpc.max_send_message_length", -1),
                    ("grpc.max_receive_message_length", -1),
                ],
            )

        # Wrap messages. This must be done after self._grpc_channel exists
        self._prep_wrapped_messages(client_info)

    @property
    def grpc_channel(self) -> aio.Channel:
        """Create the channel designed to connect to this service.

        This property caches on the instance; repeated calls return
        the same channel.
        """
        # Return the channel from cache.
        return self._grpc_channel

    @property
    def operations_client(self) -> operations_v1.OperationsAsyncClient:
        """Create the client designed to process long-running operations.

        This property caches on the instance; repeated calls return the same
        client.
        """
        # Quick check: Only create a new client if we do not already have one.
        if self._operations_client is None:
            self._operations_client = operations_v1.OperationsAsyncClient(
                self.grpc_channel
            )

        # Return the client from cache.
        return self._operations_client

    @property
    def list_connectivity_tests(
        self,
    ) -> Callable[
        [reachability.ListConnectivityTestsRequest],
        Awaitable[reachability.ListConnectivityTestsResponse],
    ]:
        r"""Return a callable for the list connectivity tests method over gRPC.

        Lists all Connectivity Tests owned by a project.

        Returns:
            Callable[[~.ListConnectivityTestsRequest],
                    Awaitable[~.ListConnectivityTestsResponse]]:
                A function that, when called, will call the underlying RPC
                on the server.
        """
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "list_connectivity_tests" not in self._stubs:
            self._stubs["list_connectivity_tests"] = self.grpc_channel.unary_unary(
                "/google.cloud.networkmanagement.v1.ReachabilityService/ListConnectivityTests",
                request_serializer=reachability.ListConnectivityTestsRequest.serialize,
                response_deserializer=reachability.ListConnectivityTestsResponse.deserialize,
            )
        return self._stubs["list_connectivity_tests"]

    @property
    def get_connectivity_test(
        self,
    ) -> Callable[
        [reachability.GetConnectivityTestRequest],
        Awaitable[connectivity_test.ConnectivityTest],
    ]:
        r"""Return a callable for the get connectivity test method over gRPC.

        Gets the details of a specific Connectivity Test.

        Returns:
            Callable[[~.GetConnectivityTestRequest],
                    Awaitable[~.ConnectivityTest]]:
                A function that, when called, will call the underlying RPC
                on the server.
        """
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "get_connectivity_test" not in self._stubs:
            self._stubs["get_connectivity_test"] = self.grpc_channel.unary_unary(
                "/google.cloud.networkmanagement.v1.ReachabilityService/GetConnectivityTest",
                request_serializer=reachability.GetConnectivityTestRequest.serialize,
                response_deserializer=connectivity_test.ConnectivityTest.deserialize,
            )
        return self._stubs["get_connectivity_test"]

    @property
    def create_connectivity_test(
        self,
    ) -> Callable[
        [reachability.CreateConnectivityTestRequest],
        Awaitable[operations_pb2.Operation],
    ]:
        r"""Return a callable for the create connectivity test method over gRPC.

        Creates a new Connectivity Test. After you create a test, the
        reachability analysis is performed as part of the long running
        operation, which completes when the analysis completes.

        If the endpoint specifications in ``ConnectivityTest`` are
        invalid (for example, containing non-existent resources in the
        network, or you don't have read permissions to the network
        configurations of listed projects), then the reachability result
        returns a value of ``UNKNOWN``.

        If the endpoint specifications in ``ConnectivityTest`` are
        incomplete, the reachability result returns a value of
        AMBIGUOUS. For more information, see the Connectivity Test
        documentation.

        Returns:
            Callable[[~.CreateConnectivityTestRequest],
                    Awaitable[~.Operation]]:
                A function that, when called, will call the underlying RPC
                on the server.
        """
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "create_connectivity_test" not in self._stubs:
            self._stubs["create_connectivity_test"] = self.grpc_channel.unary_unary(
                "/google.cloud.networkmanagement.v1.ReachabilityService/CreateConnectivityTest",
                request_serializer=reachability.CreateConnectivityTestRequest.serialize,
                response_deserializer=operations_pb2.Operation.FromString,
            )
        return self._stubs["create_connectivity_test"]

    @property
    def update_connectivity_test(
        self,
    ) -> Callable[
        [reachability.UpdateConnectivityTestRequest],
        Awaitable[operations_pb2.Operation],
    ]:
        r"""Return a callable for the update connectivity test method over gRPC.

        Updates the configuration of an existing ``ConnectivityTest``.
        After you update a test, the reachability analysis is performed
        as part of the long running operation, which completes when the
        analysis completes. The Reachability state in the test resource
        is updated with the new result.

        If the endpoint specifications in ``ConnectivityTest`` are
        invalid (for example, they contain non-existent resources in the
        network, or the user does not have read permissions to the
        network configurations of listed projects), then the
        reachability result returns a value of UNKNOWN.

        If the endpoint specifications in ``ConnectivityTest`` are
        incomplete, the reachability result returns a value of
        ``AMBIGUOUS``. See the documentation in ``ConnectivityTest`` for
        for more details.

        Returns:
            Callable[[~.UpdateConnectivityTestRequest],
                    Awaitable[~.Operation]]:
                A function that, when called, will call the underlying RPC
                on the server.
        """
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "update_connectivity_test" not in self._stubs:
            self._stubs["update_connectivity_test"] = self.grpc_channel.unary_unary(
                "/google.cloud.networkmanagement.v1.ReachabilityService/UpdateConnectivityTest",
                request_serializer=reachability.UpdateConnectivityTestRequest.serialize,
                response_deserializer=operations_pb2.Operation.FromString,
            )
        return self._stubs["update_connectivity_test"]

    @property
    def rerun_connectivity_test(
        self,
    ) -> Callable[
        [reachability.RerunConnectivityTestRequest], Awaitable[operations_pb2.Operation]
    ]:
        r"""Return a callable for the rerun connectivity test method over gRPC.

        Rerun an existing ``ConnectivityTest``. After the user triggers
        the rerun, the reachability analysis is performed as part of the
        long running operation, which completes when the analysis
        completes.

        Even though the test configuration remains the same, the
        reachability result may change due to underlying network
        configuration changes.

        If the endpoint specifications in ``ConnectivityTest`` become
        invalid (for example, specified resources are deleted in the
        network, or you lost read permissions to the network
        configurations of listed projects), then the reachability result
        returns a value of ``UNKNOWN``.

        Returns:
            Callable[[~.RerunConnectivityTestRequest],
                    Awaitable[~.Operation]]:
                A function that, when called, will call the underlying RPC
                on the server.
        """
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "rerun_connectivity_test" not in self._stubs:
            self._stubs["rerun_connectivity_test"] = self.grpc_channel.unary_unary(
                "/google.cloud.networkmanagement.v1.ReachabilityService/RerunConnectivityTest",
                request_serializer=reachability.RerunConnectivityTestRequest.serialize,
                response_deserializer=operations_pb2.Operation.FromString,
            )
        return self._stubs["rerun_connectivity_test"]

    @property
    def delete_connectivity_test(
        self,
    ) -> Callable[
        [reachability.DeleteConnectivityTestRequest],
        Awaitable[operations_pb2.Operation],
    ]:
        r"""Return a callable for the delete connectivity test method over gRPC.

        Deletes a specific ``ConnectivityTest``.

        Returns:
            Callable[[~.DeleteConnectivityTestRequest],
                    Awaitable[~.Operation]]:
                A function that, when called, will call the underlying RPC
                on the server.
        """
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "delete_connectivity_test" not in self._stubs:
            self._stubs["delete_connectivity_test"] = self.grpc_channel.unary_unary(
                "/google.cloud.networkmanagement.v1.ReachabilityService/DeleteConnectivityTest",
                request_serializer=reachability.DeleteConnectivityTestRequest.serialize,
                response_deserializer=operations_pb2.Operation.FromString,
            )
        return self._stubs["delete_connectivity_test"]

    def close(self):
        return self.grpc_channel.close()

__all__ = ("ReachabilityServiceGrpcAsyncIOTransport",)