text:
**Disclaimer: none of this is too relevant anymore. I wrote all this in 5th grade and I just uploaded it as a record.**

`sysmon.py` is a program designed to monitor your system.

Install by navigating to the directory you have Setup.py stored in.

Then, type `sudo python Setup.py` in the terminal.
It will not work with python3, as it is written in python2.

To use, type `sysmon` into the command line.

The log is stored at `/var/log/sysmon.log`.
This program will work with your LINUX system provided you have the right hardware.

## Development
**Note: These examples are written in Python 2.7**

    sudo apt-get install pip
    sudo pip install psutil

Now that we have the modules installed, we can start coding.

First, create a file called `usage.py`.

    gedit ~/usage.py

Start by importing `psutil`

    import psutil

Then, create a function to monitor the percentage your CPU cores are running at.

<!-- language: python -->

    def cpu_perc():

        cpu_perc = psutil.cpu_percent(interval=1, percpu=True)
        for i in range(len(cpu_perc)):
            print "CPU Core", str(i+1),":", str(cpu_perc[i]), "%"

Let's break that down a bit, shall we?

The first line, `cpu_num = psutil.cpu_percent(interval=1, percpu=True)`, finds the percentage that the cores in your CPU are running at and assigns it to a list called `cpu_perc`.

This loop right here

<!-- language: python -->

    for i in range(len(cpu_num)):
        print "CPU Core", str(i+1),":", str(cpu_perc[i]), "%"

is a for loop that prints out the current percentage of each of your CPU cores.

Let's add the RAM usage.

Create a function called `ram_perc`.

<!-- language: python -->

    def ram_perc():
        mem = psutil.virtual_memory()
        mem_perc = mem.percent
        print "RAM: ", mem_perc, "%"

`psutil.virtual_memory` gives a data set containing different facts about the RAM in your computer.

Next, you can add some facts about your network.

<!-- language: python -->

    def net():
        net = psutil.net_io_counters()
        mbytes_sent = float(net.bytes_sent) / 1048576
        mbytes_recv = float(net.bytes_recv) / 1048576
        print "MB sent: ", mbytes_sent
        print "MB received: ", mbytes_recv

Since `psutil.net_io_counters()` only gives us information about packets sent and received in bytes, some converting was necessary.

To get some information about swap space, add this function.

<!-- language: python -->

    def swap_perc():
        swap = psutil.swap_memory()
        swap_perc = swap.percent

This one is pretty straightforward.

Temperature is kind of hard to do, so you may need to do some research of your own to figure out what will work with your hardware.
You will have to display the contents of a certain file.

Disk usage is a lot easier than temperature. All you need to do is to pass the disk you want to monitor (i.e: `/`) through a certain function.

<!-- language: python -->

    def disks():
        if len(sys.argv) > 1:
            for disk in range(1, len(sys.argv)):
                tmp = psutil.disk_usage(sys.argv[disk])
                print sys.argv[disk], "\n"
                print "Megabytes total: ",
                print str(float(tmp.total) / 1048576)
                print "Megabytes used: ",
                print str(float(tmp.used) / 1048576)
                print "Megabytes free: ",
                print str(float(tmp.free) / 1048576)
                print "Percentage used: ",
                print tmp.percent, "\n"

The original output of `psutil.disk_usage` is this,

    >>>psutil.disk_usage('/')
    sdiskusage(total=21378641920, used=4809781248, free=15482871808, percent=22.5)

but you can also just receive `total`, `used`, `free`, or `percent`.

The completed program: (the aforementioned functions were combined)

<!-- language: python -->

    import psutil, os, sys
    mem_perc = 0 #init var
    swap_perc = 0 #init var
    mbytes_sent = 0 #init var
    mbytes_recv = 0 #init var
    cpu_perc = 0 #init var
    swap = 0 #init var
    mem = 0 #init var
    net = 0 #init var

    def disp(degree):
        global cpu_perc
        global swap
        global swap_perc
        global mem
        global mem_perc
        global net
        global mbytes_sent
        global mbytes_recv

        cpu_perc = psutil.cpu_percent(interval=1, percpu=True)
        swap = psutil.swap_memory()
        swap_perc = swap.percent
        mem = psutil.virtual_memory()
        mem_perc = mem.percent
        net = psutil.net_io_counters()
        mbytes_sent = float(net.bytes_sent) / 1048576
        mbytes_recv = float(net.bytes_recv) / 1048576

        os.system('clear') #clear the screen

        print "-"*30
        print "CPU"
        print "-"*30
        print "CPU Temperature: " , degree, "'C"
        for i in range(len(cpu_perc)):
            print "CPU Core", str(i+1),":", str(cpu_perc[i]), "%"

        print "-"*30
        print "MEMORY"
        print "-"*30
        print "RAM: ", mem_perc, "%"
        print "Swap: ", swap_perc, "%"
        print "-"*30
        print "NETWORK"
        print "-"*30
        print "MB sent: ", mbytes_sent
        print "MB received: ", mbytes_recv
        print "-"*30
        print "DISKS"
        print "-"*30

        if len(sys.argv) > 1:
            for disk in range(1, len(sys.argv)):
                tmp = psutil.disk_usage(sys.argv[disk])
                print sys.argv[disk], "\n"
                print "Megabytes total: ",
                print str(float(tmp.total) / 1048576)
                print "Megabytes used: ",
                print str(float(tmp.used) / 1048576)
                print "Megabytes free: ",
                print str(float(tmp.free) / 1048576)
                print "Percentage used: ",
                print tmp.percent, "\n"

    def main():
        print("Press Ctrl+C to exit")
        while True:
            temp = open("/sys/class/thermal/thermal_zone0/temp").read().strip().lstrip('temperature :').rstrip(' C')
            temp = float(temp) / 1000
            disp(temp)

    main()

The line `temp = open("/sys/class/thermal/thermal_zone0/temp").read().strip().lstrip('temperature :').rstrip(' C')` might not work with your hardware configuration.

Run this program from the command line. Pass the disks you want to monitor as arguments from the command line.

    $ python usage.py /

    Press Ctrl+C to exit

    ------------------------------
    CPU
    ------------------------------
    CPU Temperature:  39.0 'C
    CPU Core 1 : 4.8 %
    CPU Core 2 : 1.0 %
    CPU Core 3 : 0.0 %
    CPU Core 4 : 4.9 %
    ------------------------------
    MEMORY
    ------------------------------
    RAM:  33.6 %
    Swap:  6.4 %
    ------------------------------
    NETWORK
    ------------------------------
    MB sent:  2.93382358551
    MB received:  17.2131490707
    ------------------------------
    DISKS
    ------------------------------
    /

    Megabytes total:  13952.484375
    Megabytes used:  8542.6640625
    Megabytes free:  4678.5703125
    Percentage used:  61.2

    /media/calvin/Data

    Megabytes total:  326810.996094
    Megabytes used:  57536.953125
    Megabytes free:  269274.042969
    Percentage used:  17.6


text:
<?php

namespace Eulogix\Cool\Bundle\CoreBundle\Model\Core\map;

use \RelationMap;

/**
 * This class defines the structure of the 'core.async_job' table.
 *
 *
 *
 * This map class is used by Propel to do runtime db structure discovery.
 * For example, the createSelectSql() method checks the type of a given column used in an
 * ORDER BY clause to know whether it needs to apply SQL to make the ORDER BY case-insensitive
 * (i.e. if it's a text column type).
 *
 * @package    propel.generator.vendor.eulogix.cool-core-bundle.Bundle.CoreBundle.Model.Core.map
 */
class AsyncJobTableMap extends \Eulogix\Cool\Lib\Database\Propel\CoolTableMap
{

    /**
     * The (dot-path) name of this class
     */
    const CLASS_NAME = 'vendor.eulogix.cool-core-bundle.Bundle.CoreBundle.Model.Core.map.AsyncJobTableMap';

    /**
     * Initialize the table attributes, columns and validators
     * Relations are not initialized by this method since they are lazy loaded
     *
     * @return void
     * @throws PropelException
     */
    public function initialize()
    {
        // attributes
        $this->setName('core.async_job');
        $this->setPhpName('AsyncJob');
        $this->setClassname('Eulogix\\Cool\\Bundle\\CoreBundle\\Model\\Core\\AsyncJob');
        $this->setPackage('vendor.eulogix.cool-core-bundle.Bundle.CoreBundle.Model.Core');
        $this->setUseIdGenerator(true);
        $this->setPrimaryKeyMethodInfo('core.async_job_async_job_id_seq');
        // columns
        $this->addPrimaryKey('async_job_id', 'AsyncJobId', 'INTEGER', true, null, null);
        $this->addForeignKey('issuer_user_id', 'IssuerUserId', 'INTEGER', 'core.account', 'account_id', false, null, null);
        $this->addColumn('context', 'Context', 'LONGVARCHAR', false, null, null);
        $this->addColumn('executor_type', 'ExecutorType', 'LONGVARCHAR', false, null, null);
        $this->addColumn('execution_id', 'ExecutionId', 'LONGVARCHAR', false, null, null);
        $this->addColumn('job_path', 'JobPath', 'LONGVARCHAR', false, null, null);
        $this->addColumn('parameters', 'Parameters', 'LONGVARCHAR', false, null, null);
        $this->addColumn('start_date', 'StartDate', 'TIMESTAMP', false, null, null);
        $this->addColumn('completion_date', 'CompletionDate', 'TIMESTAMP', false, null, null);
        $this->addColumn('completion_percentage', 'CompletionPercentage', 'INTEGER', false, null, null);
        $this->addColumn('outcome', 'Outcome', 'LONGVARCHAR', false, null, null);
        $this->addColumn('job_output', 'JobOutput', 'LONGVARCHAR', false, null, null);
        $this->addColumn('creation_date', 'CreationDate', 'TIMESTAMP', false, null, null);
        $this->addColumn('update_date', 'UpdateDate', 'TIMESTAMP', false, null, null);
        $this->addForeignKey('creation_user_id', 'CreationUserId', 'INTEGER', 'core.account', 'account_id', false, null, null);
        $this->addForeignKey('update_user_id', 'UpdateUserId', 'INTEGER', 'core.account', 'account_id', false, null, null);
        $this->addColumn('record_version', 'RecordVersion', 'INTEGER', false, null, null);
        // validators
    } // initialize()

    /**
     * Build the RelationMap objects for this table relationships
     */
    public function buildRelations()
    {
        $this->addRelation('AccountRelatedByIssuerUserId', 'Eulogix\\Cool\\Bundle\\CoreBundle\\Model\\Core\\Account', RelationMap::MANY_TO_ONE, array('issuer_user_id' => 'account_id', ), 'RESTRICT', null);
        $this->addRelation('AccountRelatedByCreationUserId', 'Eulogix\\Cool\\Bundle\\CoreBundle\\Model\\Core\\Account', RelationMap::MANY_TO_ONE, array('creation_user_id' => 'account_id', ), 'RESTRICT', null);
        $this->addRelation('AccountRelatedByUpdateUserId', 'Eulogix\\Cool\\Bundle\\CoreBundle\\Model\\Core\\Account', RelationMap::MANY_TO_ONE, array('update_user_id' => 'account_id', ), 'RESTRICT', null);
    } // buildRelations()

    /**
     *
     * Gets the list of behaviors registered for this table
     *
     * @return array Associative array (name => parameters) of behaviors
     */
    public function getBehaviors()
    {
        return array(
            'auditable' =>  array (
  'create_column' => 'creation_date',
  'created_by_column' => 'creation_user_id',
  'update_column' => 'update_date',
  'updated_by_column' => 'update_user_id',
  'version_column' => 'record_version',
  'target' => 'EulogixCoolCoreBundle/core',
),
            'notifier' =>  array (
  'channel' => NULL,
  'per_row' => false,
  'schema' => 'core',
  'target' => 'EulogixCoolCoreBundle/core',
),
        );
    } // getBehaviors()

} // AsyncJobTableMap

redpajama_set_name: RedPajamaGithub


text:
package io.netty.handler.codec.socksx.v5;

/**
 * A SOCKS5 request detail message, as defined in
 * the section 4, RFC1928.
 */
public interface Socks5CommandRequest extends Socks5Message {

    /**
     * Returns the type of this request.
     */
    Socks5CommandType type();

    /**
     * Returns the type of the {@code DST.ADDR} field of this request.
     */
    Socks5AddressType dstAddrType();

    /**
     * Returns the {@code DST.ADDR} field of this request.
     */
    String dstAddr();

    /**
     * Returns the {@code DST.PORT} field of this request.
     */
    int dstPort();
}


text:
require 'test_helper'

describe Scraprr::RegexpFilter do
  describe "#run" do
    before do
      @chain = MiniTest::Mock.new
    end

    it "returns value that matches regexp" do
      value = 'Beer1 - 5%, 330ml'
      @chain.expect(:run, value, [value])

      @chain = Scraprr::RegexpFilter.new(@chain, /^(.*) -.*$/)
      @chain.run(value).must_equal('Beer1')
    end

    it "returns nil with no regexp match" do
      value = 'Beer1 - 5%, 330ml'
      @chain.expect(:run, value, [value])

      @chain = Scraprr::RegexpFilter.new(@chain, /^(nothing)$/)
      @chain.run(value).must_equal(nil)
    end
  end
end


text:
"use strict"
var http = require("http");
var _private = {
	printHeader: function(){
		var code = arguments[0].code;
		var context = arguments[0].context;
		var type = arguments[0].type;
		var response = context.get('response');
		response.headersSent || response.writeHead(code, {'Content-Type': type});
//		(code > 199 && code <  299) || response.write(code + ' - ' + http.STATUS_CODES[code]);
	},
	printContent : function(){
		var content = arguments[0].content;
		var context = arguments[0].context;
		var response = context.get('response');
		switch(context.get('route').type){
			case "xml":
				response.write(_private.toXML(content));
				break;
			case "html":
				response.write(_private.toHTML(context, content));
				break;
			case "text":
				response.write(JSON.stringify(content));
				break;
			case "json":
				response.write(JSON.stringify(content));
				break;
		}
		response.write("\n");
	},
	getContentType: function(){
		var context = arguments[0];
		var type = context.get('route').type;
		return type == "xml" ? "text/xml" : type == "html" ? "text/html" : type == "json" ? "application/json" : "text/plain";
	},
	toXML : function(){
		var content = arguments[0];
		var xml = _private.buildXML({content : content});
		xml.unshift('<?xml version="1.0"?>');
		return xml.join('\n');
	},
	buildXML : function(){
		var content = arguments[0];
		var xml = [];
		for(var i in content){
			var name = isNaN(i) ? i : 'node-' + String(i);
			var value = ['number', 'boolean', 'string'].indexOf(typeof content[i]) == -1 ? _private.buildXML(content[i], xml) : String(content[i]);
			xml.push('<'+name+'>'+value+'</'+name+'>');
		}
		return xml;
	},
	toHTML : function(){
		var context = arguments[0];
		var content = arguments[1];
		var xslt = require('node_xslt');
		var stylesheet = xslt.readXsltFile('./templates/' + context.get('site').settings.theme + '/' + context.get('route').stylesheet);
		var xml = xslt.readXmlString(_private.toXML(content));
		return xslt.transform(stylesheet, xml, []);
	}
};

module.exports = {
	init : function(){
		var context = arguments[0];
		var broker = context.get("broker");
		broker.on(['authenticator.failed'], function(){
			var context = arguments[0].data;
			_private.printHeader({code: 403, context: context});
			context.get("response").end()
        });
		broker.on(['routing.failed', 'aliasing.failed'], function(){
			var context = arguments[0].data;
			_private.printHeader({code: 404, context: context, type: 'text/plain'});
			context.get("response").end()
		});
		broker.on(["app.data", "cache.data", "app.error"], function(){
			var args = arguments[0];
			var context = args.data.context;
			var type = _private.getContentType(context);
			var sync = context.get("route").sync;
			var queue = (context.get("queue") - 1);
			var statusCode = context.get('statusCode') ? context.get('statusCode') : (queue ? 206 : 200);
			sync || _private.printHeader({code: statusCode, type: type, context: context});
			sync ? context.buffer(args.data) : _private.printContent(args.data);
		});
		broker.on(["app.end", "app.error", "cache.data"], function(){
			var context = arguments[0].data.context;
			var type = _private.getContentType(context);
			var sync = context.get("route").sync;
			var queue = (context.get("queue") - 1);
			queue && context.set("queue", queue);
			var statusCode = context.get('statusCode') ? context.get('statusCode') : 200;
			queue || (sync && _private.printHeader({code: statusCode, type: type, context: context}));
			queue || (sync && _private.printContent({context: context, content: context.get("buffer")}))
			queue || context.get("response").end();
		});
		broker.on("app.error", function(){
			var context = arguments[0].data.context;
			context.log(arguments[0].data.content);
		});
	}
};


text:
require_relative 'event_module'

class Button
  include EventModule

  def click
    emit :click
  end
end

button = Button.new
button.connect(:click) do
  puts "Button clicked!"
end
button.click


text:
Standards
---------

A collection of Rails utilities and helpers that we routinely use.

Installation
------------

Add this line to your application's Gemfile:

    gem 'standards', git: 'https://github.com/struck/rails-utilities.git'

Tools and Utilities
-------------------

### Basic Http Auth

Initializes http authentication using `Rack::Auth::Basic`. Expects to enforce authentication if env variables `HTTP_USERNAME` and `HTTP_PASSWORD` are defined. General use case for this configuration is the locking down of a staging environment.

__add to application.rb__

    include Standards::BasicHttpAuth

### Cache

Clears the Rails cache.

__add to your Rakefile__

    require 'standards/resque'

Use it on demand:

    rake cache:clear

    rake cache:flush # (alias for cache:clear)

### Cashier

Configures Cashier to store in redis, use the current redis instance, and namespace the store with "cashier". Cashier notifications will also be subscribed to for the purpose of logging information about cashier events.

Gem dependencies:

    gem 'redis-namespace'
    gem 'cashier'

__add to your application.rb (after configuring Redis or your `config.cache_store`__

    include Standards::Cashier

### Configs

Provides a number of methods for pulling configurations out of ENV and other configuration locations based on standardized names.

Each configs method will return a hash.

##### Methods

`smtp`: `smtp`: Standard smtp settings for the ActionMailer smtp_settings configuration.

__add to your config/application.rb (or environment configuration)__

    config.action_mailer.smtp_settings = Standards.configs.smtp

- SMTP_ADDRESS
- SMTP_USER_NAME
- SMTP_PASSWORD
- SMTP_PORT                 (default: 587)
- SMTP_AUTHENTICATION       (default: 'plain')
- SMTP_ENABLE_STARTTLS_AUTO
- SMTP_OPENSSL_VERIFY_MODE
- SMTP_DOMAIN

The smtp method will automatically fill in values when env configurations are recognized. For example, the smtp servers for gmail and sendgrid use different ports, and the config will set the correct port if no port is specified.

### Force

Configures controllers and views to offer a "force?" method useful in applying and checking for forced values, typically via a get parameter named "force".

To use as a helper method in both controller and views, simply include in your controller:

class SomeController < ActionController::Base
  include Standards::Force
  ...
end

### Resque

Provides a standard resque worker task.

__add to your Rakefile__

    require 'standards/resque'

__Procfile (or in a terminal)__

    worker:    bundle exec rake resque:setup resque:work QUEUE='*'

### Statsd

Configures the [Statsd client](http://rubygems.org/gems/statsd-ruby) from environment variables and sets a `Statsd.current` class attribute to access the current connection instance.

__add to your Gemfile__

    gem 'statsd-ruby'

__config/initializers/statsd.rb__

    require 'standards/statsd'

### Unicorn

Defines a standard unicorn configuration. Automatically detects connections that may need to be reestablished on forks.

__config/unicorn.rb (or whatever your unicorn config file is)__

    require 'standards/unicorn'

__Procfile (or in a terminal)__

    web: bundle exec unicorn -p $PORT -c ./config/unicorn.rb

##### Reconnections

The following are automatic service connections made on the unicorn after_fork callback:

- ActiveRecord: `ActiveRecord::Base.establish_connection`
- Redis: `Redis.current.connect`
- Cache: `Rails.cache.reconnect` (only if the cache store is an instance of ActiveSupport::Cache::RedisStore)

The following are automatic service disconnections made on the unicorn before_fork callback:

- `ActiveRecord::Base.connection.disconnect!`
- `Redis.current.quit`

Roadmap
-------

- Configurations: Sendgrid
- Configurations: SMTP
- S3 Storage/Carrierwave
- Doctor task
- Deploy task (primarily for git deployment), including config writer for deploy environments
- Sprite generation and "autosprite" task. Pngquant and imageoptim.
- Mobile detection
- Exception handling (using layouts instead of public .html files, and allowing for introspection when forced)

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "remoting/client/notification/notification_client.h"

#include <memory>

#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "base/test/mock_callback.h"
#include "base/values.h"
#include "remoting/client/notification/json_fetcher.h"
#include "remoting/client/notification/notification_message.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/abseil-cpp/absl/types/optional.h"

namespace remoting {

namespace {

using ::testing::ByMove;
using ::testing::Return;

constexpr char kTestEmail[] = "test@example.com";
constexpr char kTestPlatform[] = "IOS";
constexpr char kTestVersion[] = "76.0.3809.13";
constexpr char kTestLocale[] = "zh-CN";

class MockJsonFetcher : public JsonFetcher {
 public:
  // GMock doesn't work with rvalue parameters. This works around it.
  MOCK_CONST_METHOD1(FetchJsonFile,
                     absl::optional<base::Value>(const std::string&));
  void FetchJsonFile(const std::string& relative_path,
                     FetchJsonFileCallback done,
                     const net::NetworkTrafficAnnotationTag&) override {
    auto value_opt = FetchJsonFile(relative_path);
    std::move(done).Run(std::move(value_opt));
  }
};

MATCHER(NoMessage, "") {
  return !arg.has_value();
}

MATCHER_P(MessageMatches, expected, "") {
  return arg->message_id == expected.message_id &&
         arg->message_text == expected.message_text &&
         arg->link_text == expected.link_text &&
         arg->link_url == expected.link_url;
}

template <typename T>
decltype(auto) ReturnByMove(T t) {
  return Return(ByMove(std::move(t)));
}

base::Value CreateDefaultRule() {
  base::Value rule(base::Value::Type::DICTIONARY);
  rule.SetStringKey("target_platform", "IOS");
  rule.SetStringKey("version", "[75-)");
  rule.SetStringKey("message_id", "test_message");
  rule.SetStringKey("message_text", "message_text.json");
  rule.SetStringKey("link_text", "link_text.json");
  rule.SetStringKey("link_url", "https://example.com/some_link");
  rule.SetIntKey("percent", 100);
  rule.SetBoolKey("allow_silence", true);
  return rule;
}

base::Value CreateDefaultTranslations(const std::string& text) {
  base::Value translations(base::Value::Type::DICTIONARY);
  translations.SetStringKey("en-US", "en-US:" + text);
  translations.SetStringKey("zh-CN", "zh-CN:" + text);
  return translations;
}

NotificationMessage CreateDefaultNotification() {
  NotificationMessage message;
  message.message_id = "test_message";
  message.message_text = "zh-CN:message";
  message.link_text = "zh-CN:link";
  message.link_url = "https://example.com/some_link";
  message.allow_silence = true;
  return message;
}

}  // namespace

class NotificationClientTest : public ::testing::Test {
 public:
  NotificationClientTest() { Reset(true); }

  ~NotificationClientTest() override = default;

 protected:
  void Reset(bool should_ignore_dev_messages) {
    auto fetcher = std::make_unique<MockJsonFetcher>();
    fetcher_ = fetcher.get();
    client_ = base::WrapUnique(
        new NotificationClient(std::move(fetcher), kTestPlatform, kTestVersion,
                               kTestLocale, should_ignore_dev_messages));
  }

  raw_ptr<MockJsonFetcher> fetcher_;
  std::unique_ptr<NotificationClient> client_;
};

TEST_F(NotificationClientTest, NoRule) {
  base::Value rules(base::Value::Type::LIST);
  EXPECT_CALL(*fetcher_, FetchJsonFile("notification/rules.json"))
      .WillOnce(ReturnByMove(std::move(rules)));

  base::MockCallback<NotificationClient::NotificationCallback> callback;
  EXPECT_CALL(callback, Run(NoMessage()));
  client_->GetNotification(kTestEmail, callback.Get());
}

TEST_F(NotificationClientTest, DefaultRule) {
  base::Value rules(base::Value::Type::LIST);
  rules.Append(CreateDefaultRule());
  EXPECT_CALL(*fetcher_, FetchJsonFile("notification/rules.json"))
      .WillOnce(ReturnByMove(std::move(rules)));
  EXPECT_CALL(*fetcher_, FetchJsonFile("notification/message_text.json"))
      .WillOnce(ReturnByMove(CreateDefaultTranslations("message")));
  EXPECT_CALL(*fetcher_, FetchJsonFile("notification/link_text.json"))
      .WillOnce(ReturnByMove(CreateDefaultTranslations("link")));

  base::MockCallback<NotificationClient::NotificationCallback> callback;
  EXPECT_CALL(callback, Run(MessageMatches(CreateDefaultNotification())));
  client_->GetNotification(kTestEmail, callback.Get());
}

TEST_F(NotificationClientTest, PlatformNotMatched) {
  base::Value rule = CreateDefaultRule();
  rule.SetStringKey("target_platform", "ANDROID");
  base::Value rules(base::Value::Type::LIST);
  rules.Append(std::move(rule));
  EXPECT_CALL(*fetcher_, FetchJsonFile("notification/rules.json"))
      .WillOnce(ReturnByMove(std::move(rules)));

  base::MockCallback<NotificationClient::NotificationCallback> callback;
  EXPECT_CALL(callback, Run(NoMessage()));
  client_->GetNotification(kTestEmail, callback.Get());
}

TEST_F(NotificationClientTest, VersionNotMatched) {
  base::Value rule = CreateDefaultRule();
  rule.SetStringKey("version", "[77-)");
  base::Value rules(base::Value::Type::LIST);
  rules.Append(std::move(rule));
  EXPECT_CALL(*fetcher_, FetchJsonFile("notification/rules.json"))
      .WillOnce(ReturnByMove(std::move(rules)));

  base::MockCallback<NotificationClient::NotificationCallback> callback;
  EXPECT_CALL(callback, Run(NoMessage()));
  client_->GetNotification(kTestEmail, callback.Get());
}

TEST_F(NotificationClientTest, UserNotSelected) {
  base::Value rule = CreateDefaultRule();
  rule.SetIntKey("percent", 0);
  base::Value rules(base::Value::Type::LIST);
  rules.Append(std::move(rule));
  EXPECT_CALL(*fetcher_, FetchJsonFile("notification/rules.json"))
      .WillOnce(ReturnByMove(std::move(rules)));

  base::MockCallback<NotificationClient::NotificationCallback> callback;
  EXPECT_CALL(callback, Run(NoMessage()));
  client_->GetNotification(kTestEmail, callback.Get());
}

TEST_F(NotificationClientTest, SecondRuleMatches) {
  base::Value rules(base::Value::Type::LIST);
  base::Value rule_1 = CreateDefaultRule();
  rule_1.SetStringKey("target_platform", "ANDROID");
  rule_1.SetStringKey("message_text", "message_text_1.json");
  rules.Append(std::move(rule_1));
  rules.Append(CreateDefaultRule());
  EXPECT_CALL(*fetcher_, FetchJsonFile("notification/rules.json"))
      .WillOnce(ReturnByMove(std::move(rules)));
  EXPECT_CALL(*fetcher_, FetchJsonFile("notification/message_text.json"))
      .WillOnce(ReturnByMove(CreateDefaultTranslations("message")));
  EXPECT_CALL(*fetcher_, FetchJsonFile("notification/link_text.json"))
      .WillOnce(ReturnByMove(CreateDefaultTranslations("link")));

  base::MockCallback<NotificationClient::NotificationCallback> callback;
  EXPECT_CALL(callback, Run(MessageMatches(CreateDefaultNotification())));
  client_->GetNotification(kTestEmail, callback.Get());
}

TEST_F(NotificationClientTest, MultipleMatchingRules_FirstRuleSelected) {
  base::Value rules(base::Value::Type::LIST);
  rules.Append(CreateDefaultRule());
  base::Value rule_2 = CreateDefaultRule();
  rule_2.SetStringKey("message_text", "message_text_2.json");
  rules.Append(std::move(rule_2));
  EXPECT_CALL(*fetcher_, FetchJsonFile("notification/rules.json"))
      .WillOnce(ReturnByMove(std::move(rules)));
  EXPECT_CALL(*fetcher_, FetchJsonFile("notification/message_text.json"))
      .WillOnce(ReturnByMove(CreateDefaultTranslations("message")));
  EXPECT_CALL(*fetcher_, FetchJsonFile("notification/link_text.json"))
      .WillOnce(ReturnByMove(CreateDefaultTranslations("link")));

  base::MockCallback<NotificationClient::NotificationCallback> callback;
  EXPECT_CALL(callback, Run(MessageMatches(CreateDefaultNotification())));
  client_->GetNotification(kTestEmail, callback.Get());
}

TEST_F(NotificationClientTest, TextFilesNotFound) {
  base::Value rules(base::Value::Type::LIST);
  rules.Append(CreateDefaultRule());
  EXPECT_CALL(*fetcher_, FetchJsonFile("notification/rules.json"))
      .WillOnce(ReturnByMove(std::move(rules)));

  base::Value translation = CreateDefaultTranslations("message");

  EXPECT_CALL(*fetcher_, FetchJsonFile("notification/message_text.json"))
      .WillOnce(ReturnByMove(absl::nullopt));
  EXPECT_CALL(*fetcher_, FetchJsonFile("notification/link_text.json"))
      .WillOnce(ReturnByMove(absl::nullopt));

  base::MockCallback<NotificationClient::NotificationCallback> callback;
  EXPECT_CALL(callback, Run(NoMessage()));
  client_->GetNotification(kTestEmail, callback.Get());
}

TEST_F(NotificationClientTest, TranslationNotFound_FallbackToEnglish) {
  base::Value rules(base::Value::Type::LIST);
  rules.Append(CreateDefaultRule());
  EXPECT_CALL(*fetcher_, FetchJsonFile("notification/rules.json"))
      .WillOnce(ReturnByMove(std::move(rules)));

  base::Value translations = CreateDefaultTranslations("message");
  translations.RemoveKey("zh-CN");
  EXPECT_CALL(*fetcher_, FetchJsonFile("notification/message_text.json"))
      .WillOnce(ReturnByMove(std::move(translations)));
  EXPECT_CALL(*fetcher_, FetchJsonFile("notification/link_text.json"))
      .WillOnce(ReturnByMove(CreateDefaultTranslations("link")));

  NotificationMessage notification = CreateDefaultNotification();
  notification.message_text = "en-US:message";
  base::MockCallback<NotificationClient::NotificationCallback> callback;
  EXPECT_CALL(callback, Run(MessageMatches(notification)));
  client_->GetNotification(kTestEmail, callback.Get());
}

TEST_F(NotificationClientTest, NoAvailableTranslation) {
  base::Value rules(base::Value::Type::LIST);
  rules.Append(CreateDefaultRule());
  EXPECT_CALL(*fetcher_, FetchJsonFile("notification/rules.json"))
      .WillOnce(ReturnByMove(std::move(rules)));

  EXPECT_CALL(*fetcher_, FetchJsonFile("notification/message_text.json"))
      .WillOnce(ReturnByMove(base::Value(base::Value::Type::DICTIONARY)));
  EXPECT_CALL(*fetcher_, FetchJsonFile("notification/link_text.json"))
      .WillOnce(ReturnByMove(base::Value(base::Value::Type::DICTIONARY)));

  base::MockCallback<NotificationClient::NotificationCallback> callback;
  EXPECT_CALL(callback, Run(NoMessage()));
  client_->GetNotification(kTestEmail, callback.Get());
}

TEST_F(NotificationClientTest, ReleaseBuildsIgnoreDevMessages) {
  base::Value rules(base::Value::Type::LIST);
  base::Value rule = CreateDefaultRule();
  rule.SetBoolKey("dev_mode", true);
  rules.Append(std::move(rule));
  EXPECT_CALL(*fetcher_, FetchJsonFile("notification/rules.json"))
      .WillOnce(ReturnByMove(std::move(rules)));

  base::MockCallback<NotificationClient::NotificationCallback> callback;
  EXPECT_CALL(callback, Run(NoMessage()));
  client_->GetNotification(kTestEmail, callback.Get());
}

TEST_F(NotificationClientTest, ReleaseBuildsDontIgnoreDevMessages) {
  base::Value rules(base::Value::Type::LIST);
  base::Value rule = CreateDefaultRule();
  rule.SetBoolKey("dev_mode", false);
  rules.Append(std::move(rule));
  EXPECT_CALL(*fetcher_, FetchJsonFile("notification/rules.json"))
      .WillOnce(ReturnByMove(std::move(rules)));
  EXPECT_CALL(*fetcher_, FetchJsonFile("notification/message_text.json"))
      .WillOnce(ReturnByMove(CreateDefaultTranslations("message")));
  EXPECT_CALL(*fetcher_, FetchJsonFile("notification/link_text.json"))
      .WillOnce(ReturnByMove(CreateDefaultTranslations("link")));

  base::MockCallback<NotificationClient::NotificationCallback> callback;
  EXPECT_CALL(callback, Run(MessageMatches(CreateDefaultNotification())));
  client_->GetNotification(kTestEmail, callback.Get());
}

TEST_F(NotificationClientTest, DebugBuildsDontIgnoreDevMessages) {
  Reset(/* should_ignore_dev_messages */ false);

  base::Value rules(base::Value::Type::LIST);
  base::Value rule = CreateDefaultRule();
  rule.SetBoolKey("dev_mode", true);
  rules.Append(std::move(rule));
  EXPECT_CALL(*fetcher_, FetchJsonFile("notification/rules.json"))
      .WillOnce(ReturnByMove(std::move(rules)));
  EXPECT_CALL(*fetcher_, FetchJsonFile("notification/message_text.json"))
      .WillOnce(ReturnByMove(CreateDefaultTranslations("message")));
  EXPECT_CALL(*fetcher_, FetchJsonFile("notification/link_text.json"))
      .WillOnce(ReturnByMove(CreateDefaultTranslations("link")));

  base::MockCallback<NotificationClient::NotificationCallback> callback;
  EXPECT_CALL(callback, Run(MessageMatches(CreateDefaultNotification())));
  client_->GetNotification(kTestEmail, callback.Get());
}

TEST_F(NotificationClientTest, AllowSilenceNotSet_DefaultToFalse) {
  base::Value rules(base::Value::Type::LIST);
  base::Value rule = CreateDefaultRule();
  rule.RemoveKey("allow_silence");
  rules.Append(std::move(rule));
  EXPECT_CALL(*fetcher_, FetchJsonFile("notification/rules.json"))
      .WillOnce(ReturnByMove(std::move(rules)));
  EXPECT_CALL(*fetcher_, FetchJsonFile("notification/message_text.json"))
      .WillOnce(ReturnByMove(CreateDefaultTranslations("message")));
  EXPECT_CALL(*fetcher_, FetchJsonFile("notification/link_text.json"))
      .WillOnce(ReturnByMove(CreateDefaultTranslations("link")));

  NotificationMessage notification = CreateDefaultNotification();
  notification.allow_silence = false;
  base::MockCallback<NotificationClient::NotificationCallback> callback;
  EXPECT_CALL(callback, Run(MessageMatches(notification)));
  client_->GetNotification(kTestEmail, callback.Get());
}

}  // namespace remoting


text:
(function() {
    var _this;

    var injector = null;
    var speakerProperties = null;
    var soundURL;
    var soundVolume;
    var soundLocal;
    var soundLoop;
    var speakerUserData;
    var TIME_OUT = 2000;

    var Speaker = function() {
        _this = this;
    };

    Speaker.prototype = {

        preload: function(entityID) {
            _this.entityID = entityID;
            _this.getSoundData();
        },

        getSoundData: function() {
            speakerProperties = Entities.getEntityProperties(_this.entityID, ["position", "userData"]);
            if (!speakerProperties.userData || speakerProperties.userData === "{}") {
                print("Speaker ", _this.entityID, " is missing user data.");
                return;
            }

            try {
                speakerUserData = JSON.parse(speakerProperties.userData);
                soundURL = SoundCache.getSound(speakerUserData.soundURL);
                soundVolume = !isNaN(speakerUserData.soundVolume) ? speakerUserData.soundVolume : 0.0;
                soundLocal = speakerUserData.isLocal ? speakerUserData.isLocal : false;
                soundLoop = speakerUserData.soundLoop ? speakerUserData.soundLoop : false;
                // verify that settings are legit
                Script.setTimeout(function() {
                    _this.playSound();
                },TIME_OUT);

            } catch (e) {
                print("Error in retrieving soundData");
                return;
            }
        },

        playSound: function() {
            if (injector) {
                injector.stop();
            }
            if (soundURL && soundURL.downloaded) {
                injector = Audio.playSound(soundURL, {
                    position: speakerProperties.position,
                    volume: soundVolume,
                    loop: soundLoop,
                    localOnly: soundLocal
                });
            } else {
                print("soundURL not downloaded!");
                return;
            }
        },

        unload: function() {
            if (injector) {
                injector.stop();
                injector = null;
            }
        }
    };

    return new Speaker;

});


text:
import * as compiler from '@angular/compiler';
import {TemplateMigrator} from '../../template-migrator';
import {updateAttribute, visitElements} from '../../tree-traversal';
import {Update} from '../../../../../migration-utilities';

export class CardTemplateMigrator extends TemplateMigrator {
  getUpdates(ast: compiler.ParsedTemplate): Update[] {
    const updates: Update[] = [];

    visitElements(ast.nodes, (node: compiler.TmplAstElement) => {
      if (node.name !== 'mat-card') {
        return;
      }

      updates.push({
        offset: node.startSourceSpan.start.offset,
        updateFn: html => updateAttribute(html, node, 'appearance', () => 'outlined'),
      });
    });

    return updates;
  }
}


text: require 'sudoku/solution_set'


text:
package jenkins.security;

import edu.umd.cs.findbugs.annotations.CheckForNull;
import hudson.security.UnwrapSecurityExceptionFilter;
import java.io.IOException;
import java.util.function.Function;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.acegisecurity.AcegiSecurityException;
import org.springframework.security.web.access.ExceptionTranslationFilter;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;

/**
 * Translates {@link AcegiSecurityException}s to Spring Security equivalents.
 * Used by other filters like {@link UnwrapSecurityExceptionFilter} and {@link ExceptionTranslationFilter}.
 */
@Restricted(NoExternalUse.class)
public class AcegiSecurityExceptionFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        try {
            chain.doFilter(request, response);
        } catch (IOException x) {
            throw translate(x, IOException::new);
        } catch (ServletException x) {
            throw translate(x, ServletException::new);
        } catch (RuntimeException x) {
            throw translate(x, RuntimeException::new);
        }
    }

    private static <T extends Throwable> T translate(T t, Function<Throwable, T> ctor) {
        RuntimeException cause = convertedCause(t);
        if (cause != null) {
            T t2 = ctor.apply(cause);
            t2.addSuppressed(t);
            return t2;
        } else {
            return t;
        }
    }

    private static @CheckForNull RuntimeException convertedCause(@CheckForNull Throwable t) {
        if (t instanceof AcegiSecurityException) {
            return ((AcegiSecurityException) t).toSpring();
        } else if (t != null) {
            return convertedCause(t.getCause());
        } else {
            return null;
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}

    @Override
    public void destroy() {}

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Beih. Sydowia 2: 617 (1961)

#### Original name
Irenopsis senecionis Hansf.

### Remarks
null


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you 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.
-->
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:jaxrs="http://cxf.apache.org/jaxrs"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:cxf="http://cxf.apache.org/core"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://cxf.apache.org/jaxrs
                           http://cxf.apache.org/schemas/jaxrs.xsd
                           http://cxf.apache.org/core
                           http://cxf.apache.org/schemas/core.xsd
                           http://www.springframework.org/schema/util
                           http://www.springframework.org/schema/util/spring-util.xsd">

  <bean id="httpClientConnManager"
        class="org.apache.http.impl.conn.PoolingClientConnectionManager"/>

  <bean id="httpClientParams" class="org.apache.syncope.client.http.HttpClientParams">
    <property name="parameterMap">
      <map key-type="java.lang.String">
        <entry>
          <key>
            <value>http.protocol.handle-authentication</value>
          </key>
          <value type="java.lang.Boolean">
            false
          </value>
        </entry>
      </map>
    </property>
  </bean>

  <bean id="httpClientFactory"
        class="org.apache.syncope.client.http.PreemptiveAuthHttpRequestFactory">
    <constructor-arg value="localhost"/>
    <constructor-arg value="9080"/>
    <constructor-arg value="http"/>
    <constructor-arg ref="httpClientConnManager"/>
    <constructor-arg ref="httpClientParams"/>
  </bean>

  <bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
    <constructor-arg ref="httpClientFactory"/>
    <property name="messageConverters">
      <list>
        <ref bean="mappingJacksonHttpMessageConverter"/>
        <ref bean="mappingXstreamHttpMessageConverter"/>
      </list>
    </property>
    <property name="errorHandler">
      <bean id="syncopeClientErrorHandler"
            class="org.apache.syncope.common.validation.SyncopeClientErrorHandler"/>
    </property>
  </bean>

  <!-- JSON (via Jackson) -->
  <bean id="jacksonObjectMapper" class="org.apache.syncope.core.rest.data.UnwrappedObjectMapper"/>
  <bean id="mappingJacksonHttpMessageConverter"
        class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
    <property name="objectMapper" ref="jacksonObjectMapper"/>
  </bean>

  <!-- XML (via XStream) -->
  <bean id="xStreamXmlMarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller">
    <property name="autodetectAnnotations" value="true"/>
  </bean>
  <bean id="mappingXstreamHttpMessageConverter"
        class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
    <constructor-arg ref="xStreamXmlMarshaller"/>
  </bean>

  <!-- CXF Configuration - BEGIN -->
  <bean id="jaxbProvider" class="org.apache.cxf.jaxrs.provider.JAXBElementProvider">
    <property name="depthProperties">
      <bean id="depthProperties" class="org.apache.cxf.staxutils.DocumentDepthProperties">
        <property name="innerElementCountThreshold" value="500"/>
      </bean>
    </property>
    <property name="marshallerProperties">
      <map>
        <entry key="jaxb.formatted.output">
          <value type="java.lang.Boolean">true</value>
        </entry>
      </map>
    </property>
  </bean>

  <bean id="jsonProvider" class="org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider">
    <property name="mapper" ref="jacksonObjectMapper"/>
  </bean>

  <bean id="exceptionMapper" class="org.apache.syncope.client.rest.utils.RestClientExceptionMapper"/>

  <bean id="restClientFactory" class="org.apache.cxf.jaxrs.client.JAXRSClientFactoryBean">
    <property name="address" value="http://localhost:9080/syncope/cxf"/>
    <property name="threadSafe" value="true"/>
    <property name="username" value="admin"/>
    <property name="password" value="password"/>
    <property name="inheritHeaders" value="true"/>
    <property name="features">
      <list>
        <cxf:logging/>
      </list>
    </property>
    <property name="providers">
      <list>
        <ref bean="jaxbProvider"/>
        <ref bean="jsonProvider"/>
        <ref bean="exceptionMapper"/>
      </list>
    </property>
  </bean>
  <!-- CXF Configuration - END -->

</beans>


text:
@implementation UMLogin
+ (void)login:(UMLoginType)type completion:(UMLoginCompletionBlock)completion
{
        UMSocialPlatformType platform = UMSocialPlatformType_UnKnown;
        switch (type) {
                case UMLoginTypeWeiBo:
                        platform = UMSocialPlatformType_Sina;
                        break;
                case UMLoginTypeQQ:
                        platform = UMSocialPlatformType_QQ;
                        break;
                case UMLoginTypeWeiXin:
                        platform = UMSocialPlatformType_WechatSession;
                        break;

                default:
                        break;
        }

        [self getUserInfoForPlatform:platform LoginType:type completion:completion];
}

+ (void)getUserInfoForPlatform:(UMSocialPlatformType)platformType LoginType:(UMLoginType)type completion:(UMLoginCompletionBlock)completion
{
        [[UMSocialManager defaultManager] getUserInfoWithPlatform:platformType currentViewController:nil completion:^(id result, NSError *error) {
                if (!error && [result isKindOfClass:[UMSocialUserInfoResponse class]])
                {
                        UMSocialUserInfoResponse *userinfo =result;

                        if (completion)
                        {
                                completion(YES, nil, [userinfo modelToJSONObject]);
                        }

                }
                else if (completion)
                {
                        completion(NO,[NSError appErrorWithCode:APP_ERROR_CODE_ERR msg:[NSString app_AuthorizationFailed] remark:error.localizedDescription],nil);
                }
        }];
}

@end


text:
using namespace ABI::Windows::Devices::Sensors;

class AccelerometerModule : BaseModule
{
public:
	AccelerometerModule(SensorDemo * parent);
	~AccelerometerModule();
private:
	void PollForData();
	AccelerometerData GetAccelerometerData();

	SensorDemo *parent;
	Logger log;
};


text:
package com.vimeo.sample_java_model;

import com.google.gson.annotations.SerializedName;
import com.vimeo.stag.UseStag;

/**
 * A model used to verify that wrapper type adapters are correctly called.
 * <p>
 * Created by restainoa on 12/18/17.
 */
@UseStag
public class WrapperTypeAdapterModel {

    @SerializedName("inner_type")
    private InnerType mInnerType;

    public InnerType getInnerType() {
        return mInnerType;
    }

    public void setInnerType(InnerType innerType) {
        mInnerType = innerType;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) { return true; }
        if (o == null || getClass() != o.getClass()) { return false; }

        WrapperTypeAdapterModel that = (WrapperTypeAdapterModel) o;

        return mInnerType != null ? mInnerType.equals(that.mInnerType) : that.mInnerType == null;
    }

    @Override
    public int hashCode() {
        return mInnerType != null ? mInnerType.hashCode() : 0;
    }

    @UseStag
    public static class InnerType {

        @SerializedName("hello")
        private String mHello;

        public String getHello() {
            return mHello;
        }

        public void setHello(String hello) {
            mHello = hello;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) { return true; }
            if (o == null || getClass() != o.getClass()) { return false; }

            InnerType innerType = (InnerType) o;

            return mHello != null ? mHello.equals(innerType.mHello) : innerType.mHello == null;
        }

        @Override
        public int hashCode() {
            return mHello != null ? mHello.hashCode() : 0;
        }
    }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Ann. R. bot. Gdns Peradeniya 9: 293 (1925)

#### Original name
Peniophora stratosa Petch

### Remarks
null


text:
/*
 * testIA32.cpp
 *
 * Tests the
 *
 * Author: Elad Raz <e@eladraz.com>
 */
#include "xStl/types.h"
#include "xStl/os/os.h"
#include "xStl/os/threadUnsafeMemoryAccesser.h"
#include "xStl/data/datastream.h"
#include "xStl/utils/algorithm.h"
#include "xStl/except/trace.h"
#include "xStl/except/assert.h"
#include "xStl/stream/ioStream.h"
#include "xStl/stream/memoryStream.h"
#include "xStl/stream/memoryAccesserStream.h"
#include "xStl/../../tests/tests.h"
#include "dismount/Opcode.h"
#include "dismount/OpcodeSubsystems.h"
#include "dismount/StreamDisassembler.h"
#include "dismount/StreamDisassemblerFactory.h"
#include "dismount/DefaultOpcodeDataFormatter.h"
#include "dismount/proc/ia32/IA32Opcode.h"

class TestObjectTestIA32 : public cTestObject {
public:
    // The number of opcode byte to view
    enum { NUMBER_OF_OPCODE = 7,
           OPCODE_MARGIN = 10 };

    /*
     * This function tests the dismount by trying to disassemble the function
     * its self
     */
    void appTest32()
    {
        cVirtualMemoryAccesserPtr context(new cThreadUnsafeMemoryAccesser());
        addressNumericValue start = getNumeric(&CoCreateInstance);
        // start = 0x400000; // 0x0419E80;
        addressNumericValue end = start + 0x100;
        cMemoryAccesserStream stream(context, start, end);

        // Generate the disassembler
        StreamDisassemblerPtr disassembler = StreamDisassemblerFactory::disassemble(
                OpcodeSubsystems::DISASSEMBLER_INTEL_32,
                BasicInputPtr(&stream, SMARTPTR_DESTRUCT_NONE),
                true,
                ProcessorAddress(ProcessorAddress::PROCESSOR_32, start));

        XSTL_TRY
        {
            // Prepare the default data-formatter
            DefaultOpcodeDataFormatter formatter(OPCODE_MARGIN);

            while (true)
            {
                OpcodePtr opcode = disassembler->next();
                cBuffer opcodeData = opcode->getOpcode();

                // Format the opcode-data-bytes
                cString opcodeString;
                int i = 0;
                for (; i < t_min((int)NUMBER_OF_OPCODE, (int)opcodeData.getSize()); i++)
                {
                    opcodeString+= HEXBYTE(opcodeData[i]) + " ";
                }
                for (i = 0; i < NUMBER_OF_OPCODE - (int)opcodeData.getSize(); i++) {
                    opcodeString+= "   ";
                }
                opcodeString+= "  ";

                // Get the translated opcode
                OpcodeFormatterPtr fr = disassembler->getOpcodeFormat(opcode,
                                                           formatter);

                // Flush the information to the screen

                // Show address, if avaliable
                ProcessorAddress address(gNullPointerProcessorAddress);
                if (opcode->getOpcodeAddress(address))
                    cout << formatter.translateAbsoluteAddress(address) << "   ";

                // Show opcode bytes
                cout << opcodeString;

                // Show the complete formatted opcode
                cout << fr->string() << endl;
            }
        } XSTL_CATCH_ALL
        {
            // End-of-stream, or error, let's check it

        }
    }

    void test32()
    {
        #ifndef XSTL_64BIT
            appTest32();
        #endif
    }

    virtual void test()
    {
        // Test the 32bit opcode table
        test32();
        // Test the 16bit opcode table
        // test16();
    }

    // Return the name of the module
    virtual cString getName() { return __FILE__; }
};

// Instance test object
TestObjectTestIA32 g_globalTestIA32;


text:
TestDox: Default output; Data Provider with string data set name; TestDox metadata with placeholders
--FILE--
<?php declare(strict_types=1);
$_SERVER['argv'][] = '--do-not-cache-result';
$_SERVER['argv'][] = '--no-configuration';
$_SERVER['argv'][] = '--no-progress';
$_SERVER['argv'][] = '--testdox';
$_SERVER['argv'][] = '--colors=never';
$_SERVER['argv'][] = __DIR__ . '/_files/DataProviderWithNumericDataSetNameAndMetadataWithPlaceholdersTest.php';

require_once __DIR__ . '/../../bootstrap.php';

PHPUnit\TextUI\Application::main();
--EXPECTF--
PHPUnit %s by Sebastian Bergmann and contributors.

Runtime:       %s

Time: %s, Memory: %s

Text from class-level TestDox metadata
 ✔ Text from method-level TestDox metadata for successful test with placeholders (string, 0, 0.0 array, true, bar)
 ✘ Text from method-level TestDox metadata for failing test with placeholders (string, 0, 0.0 array, true, bar)
   │
   │ Failed asserting that false is true.
   │
   │ %s:%d
   │

FAILURES!
Tests: 2, Assertions: 2, Failures: 1.


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd">

    <!-- 配置主页 -->
    <mvc:view-controller path="/" view-name="redirect:/home" />

    <resources mapping="/resources/**" location="/resources/" />
    <resources mapping="/favicon.ico" location="/favicon.ico" />
    <resources mapping="/logo.png" location="/logo.png" />

    <beans:bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <beans:property name="messageConverters">
            <beans:list>
                <beans:bean class="org.springframework.http.converter.StringHttpMessageConverter">
                    <beans:property name="supportedMediaTypes">
                        <beans:list>
                            <beans:value>text/html;charset=UTF-8</beans:value>
                        </beans:list>
                    </beans:property>
                </beans:bean>
                <beans:bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                    <beans:property name="supportedMediaTypes">
                        <beans:list>
                            <beans:value>application/json;charset=UTF-8</beans:value>
                        </beans:list>
                    </beans:property>
                    <beans:property name="objectMapper">
                        <beans:bean class="com.fasterxml.jackson.databind.ObjectMapper" scope="singleton" />
                    </beans:property>
                </beans:bean>
            </beans:list>
        </beans:property>
    </beans:bean>

    <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/pages/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>

    <beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <beans:property name="maxUploadSize" value="10000000" />
    </beans:bean>

    <mvc:annotation-driven />

    <context:component-scan base-package="com.bh.wechat.controller" />

</beans:beans>


text:
package net.edzard.kinetic;

/**
 * A custom shape.
 * The shape is defined using a given path object.
 * Custom shapes are CPU intensive to render.
 * @author Ed
 */
public class CustomShape extends Shape {

	/** Protected Ctor keeps GWT happy */
	protected CustomShape() {}

	/**
	 * Retrieve the custom shape's path.
	 * @return The path
	 */
	public final native Path getPath() /*-{
		return this.path;
	}-*/;

	/**
	 * Assign a path to the custom shape.
	 * @param path The new path
	 */
	public final native void setPath(Path path) /*-{
		this.path = path;
	}-*/;
}


text:
// Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0

#include "sw/device/silicon_creator/lib/drivers/pinmux.h"

#include "sw/device/lib/base/abs_mmio.h"
#include "sw/device/lib/base/hardened.h"
#include "sw/device/lib/base/macros.h"
#include "sw/device/silicon_creator/lib/base/chip.h"
#include "sw/device/silicon_creator/lib/drivers/otp.h"

#include "hw/top_earlgrey/sw/autogen/top_earlgrey.h"
#include "otp_ctrl_regs.h"
#include "pinmux_regs.h"

enum {
  /**
   * Base address of the pinmux registers.
   */
  kBase = TOP_EARLGREY_PINMUX_AON_BASE_ADDR,
};

/**
 * A peripheral input and MIO pad to link it to.
 */
typedef struct pinmux_input {
  top_earlgrey_pinmux_peripheral_in_t periph;
  top_earlgrey_pinmux_insel_t insel;
  top_earlgrey_muxed_pads_t pad;
} pinmux_input_t;

/**
 * An MIO pad and a peripheral output to link it to.
 */
typedef struct pinmux_output {
  top_earlgrey_pinmux_mio_out_t mio;
  top_earlgrey_pinmux_outsel_t outsel;
  top_earlgrey_muxed_pads_t pad;
} pinmux_output_t;

/**
 * UART RX pin.
 */
static const pinmux_input_t kInputUart0 = {
    .periph = kTopEarlgreyPinmuxPeripheralInUart0Rx,
    .insel = kTopEarlgreyPinmuxInselIoc3,
    .pad = kTopEarlgreyMuxedPadsIoc3,
};

/**
 * UART TX pin.
 */
static const pinmux_output_t kOutputUart0 = {
    .mio = kTopEarlgreyPinmuxMioOutIoc4,
    .outsel = kTopEarlgreyPinmuxOutselUart0Tx,
    .pad = kTopEarlgreyMuxedPadsIoc4,
};

/**
 * SW strap pins.
 */
#define PINMUX_ASSERT_EQ_(a, b) \
  static_assert((a) == (b), "Unexpected software strap configuration.")

PINMUX_ASSERT_EQ_(SW_STRAP_0_PERIPH, kTopEarlgreyPinmuxPeripheralInGpioGpio22);
PINMUX_ASSERT_EQ_(SW_STRAP_0_INSEL, kTopEarlgreyPinmuxInselIoc0);
PINMUX_ASSERT_EQ_(SW_STRAP_0_PAD, kTopEarlgreyMuxedPadsIoc0);
static const pinmux_input_t kInputSwStrap0 = {
    .periph = SW_STRAP_0_PERIPH,
    .insel = SW_STRAP_0_INSEL,
    .pad = SW_STRAP_0_PAD,
};

PINMUX_ASSERT_EQ_(SW_STRAP_1_PERIPH, kTopEarlgreyPinmuxPeripheralInGpioGpio23);
PINMUX_ASSERT_EQ_(SW_STRAP_1_INSEL, kTopEarlgreyPinmuxInselIoc1);
PINMUX_ASSERT_EQ_(SW_STRAP_1_PAD, kTopEarlgreyMuxedPadsIoc1);
static const pinmux_input_t kInputSwStrap1 = {
    .periph = SW_STRAP_1_PERIPH,
    .insel = SW_STRAP_1_INSEL,
    .pad = SW_STRAP_1_PAD,
};

PINMUX_ASSERT_EQ_(SW_STRAP_2_PERIPH, kTopEarlgreyPinmuxPeripheralInGpioGpio24);
PINMUX_ASSERT_EQ_(SW_STRAP_2_INSEL, kTopEarlgreyPinmuxInselIoc2);
PINMUX_ASSERT_EQ_(SW_STRAP_2_PAD, kTopEarlgreyMuxedPadsIoc2);
static const pinmux_input_t kInputSwStrap2 = {
    .periph = SW_STRAP_2_PERIPH,
    .insel = SW_STRAP_2_INSEL,
    .pad = SW_STRAP_2_PAD,
};

/**
 * Sets the input pad for the specified peripheral input.
 *
 * @param input A peripheral input and MIO pad to link it to.
 */
static void configure_input(pinmux_input_t input) {
  abs_mmio_write32(kBase + PINMUX_MIO_PERIPH_INSEL_0_REG_OFFSET +
                       input.periph * sizeof(uint32_t),
                   input.insel);
}

/**
 * Enables pull-down for the specified pad.
 *
 * @param pad A MIO pad.
 */
static void enable_pull_down(top_earlgrey_muxed_pads_t pad) {
  uint32_t reg =
      bitfield_bit32_write(0, PINMUX_MIO_PAD_ATTR_0_PULL_EN_0_BIT, true);
  abs_mmio_write32(
      kBase + PINMUX_MIO_PAD_ATTR_0_REG_OFFSET + pad * sizeof(uint32_t), reg);
}

/**
 * Sets the peripheral output for each specified output pad.
 *
 * @param output An MIO pad and a peripheral output to link it to.
 */
static void configure_output(pinmux_output_t output) {
  abs_mmio_write32(
      kBase + PINMUX_MIO_OUTSEL_0_REG_OFFSET + output.mio * sizeof(uint32_t),
      output.outsel);
}

void pinmux_init(void) {
  uint32_t bootstrap_en =
      otp_read32(OTP_CTRL_PARAM_OWNER_SW_CFG_ROM_BOOTSTRAP_EN_OFFSET);
  if (launder32(bootstrap_en) == kHardenedBoolTrue) {
    HARDENED_CHECK_EQ(bootstrap_en, kHardenedBoolTrue);
    // Note: attributes should be configured before the pinmux matrix to avoid
    // "undesired electrical behavior and/or contention at the pads".
    enable_pull_down(kInputSwStrap0.pad);
    enable_pull_down(kInputSwStrap1.pad);
    enable_pull_down(kInputSwStrap2.pad);
    configure_input(kInputSwStrap0);
    configure_input(kInputSwStrap1);
    configure_input(kInputSwStrap2);
  }

  configure_input(kInputUart0);
  configure_output(kOutputUart0);
}


text:
from django.contrib import admin

from oscar.core.loading import get_model

Line = get_model('basket', 'line')

class LineInline(admin.TabularInline):
    model = Line
    readonly_fields = ('line_reference', 'product', 'price_excl_tax',
                       'price_incl_tax', 'price_currency', 'stockrecord')

class LineAdmin(admin.ModelAdmin):
    list_display = ('id', 'basket', 'product', 'stockrecord', 'quantity',
                    'price_excl_tax', 'price_currency', 'date_created')
    readonly_fields = ('basket', 'stockrecord', 'line_reference', 'product',
                       'price_currency', 'price_incl_tax', 'price_excl_tax',
                       'quantity')

class BasketAdmin(admin.ModelAdmin):
    list_display = ('id', 'owner', 'status', 'num_lines',
                    'contains_a_voucher', 'date_created', 'date_submitted',
                    'time_before_submit')
    readonly_fields = ('owner', 'date_merged', 'date_submitted')
    inlines = [LineInline]

admin.site.register(get_model('basket', 'basket'), BasketAdmin)
admin.site.register(Line, LineAdmin)
admin.site.register(get_model('basket', 'LineAttribute'))


text:
<?php

namespace spec\Judopay;

use GuzzleHttp\Psr7\Request;
use PHPUnit\Framework\Assert;
use spec\SpecHelper;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class RequestSpec extends ObjectBehavior
{
    public function it_is_initializable()
    {
        $this->beConstructedWith(SpecHelper::getConfiguration());
        $this->shouldHaveType('Judopay\Request');
    }

    public function it_sends_the_right_authorization_header_for_oauth2()
    {
        // Add access token to configuration
        $oauthAccessToken = 'xyz';
        $config = SpecHelper::getConfiguration();
        $config->add('oauthAccessToken', $oauthAccessToken);

        // Create a request
        $this->beConstructedWith($config);

        $headers = $this->getHeaders();
        $request = new Request(
            'get',
            'http://example.com',
            $headers->getWrappedObject()
        );

        // Make sure the Authorization header is correct
        Assert::assertEquals('Bearer '.$oauthAccessToken, $request->getHeader('Authorization')[0]);
    }

    public function getMatchers()
    {
        return array(
            'startWith' => function ($subject, $key) {
                return (stripos(trim($subject), $key) === 0);
            },
        );
    }
}


text:
package netfakes

import (
	"net/http"
	"sync"

	"github.com/cloudfoundry/cli/cf/net"
)

type FakeRequestDumperInterface struct {
	DumpRequestStub        func(*http.Request)
	dumpRequestMutex       sync.RWMutex
	dumpRequestArgsForCall []struct {
		arg1 *http.Request
	}
	DumpResponseStub        func(*http.Response)
	dumpResponseMutex       sync.RWMutex
	dumpResponseArgsForCall []struct {
		arg1 *http.Response
	}
}

func (fake *FakeRequestDumperInterface) DumpRequest(arg1 *http.Request) {
	fake.dumpRequestMutex.Lock()
	fake.dumpRequestArgsForCall = append(fake.dumpRequestArgsForCall, struct {
		arg1 *http.Request
	}{arg1})
	fake.dumpRequestMutex.Unlock()
	if fake.DumpRequestStub != nil {
		fake.DumpRequestStub(arg1)
	}
}

func (fake *FakeRequestDumperInterface) DumpRequestCallCount() int {
	fake.dumpRequestMutex.RLock()
	defer fake.dumpRequestMutex.RUnlock()
	return len(fake.dumpRequestArgsForCall)
}

func (fake *FakeRequestDumperInterface) DumpRequestArgsForCall(i int) *http.Request {
	fake.dumpRequestMutex.RLock()
	defer fake.dumpRequestMutex.RUnlock()
	return fake.dumpRequestArgsForCall[i].arg1
}

func (fake *FakeRequestDumperInterface) DumpResponse(arg1 *http.Response) {
	fake.dumpResponseMutex.Lock()
	fake.dumpResponseArgsForCall = append(fake.dumpResponseArgsForCall, struct {
		arg1 *http.Response
	}{arg1})
	fake.dumpResponseMutex.Unlock()
	if fake.DumpResponseStub != nil {
		fake.DumpResponseStub(arg1)
	}
}

func (fake *FakeRequestDumperInterface) DumpResponseCallCount() int {
	fake.dumpResponseMutex.RLock()
	defer fake.dumpResponseMutex.RUnlock()
	return len(fake.dumpResponseArgsForCall)
}

func (fake *FakeRequestDumperInterface) DumpResponseArgsForCall(i int) *http.Response {
	fake.dumpResponseMutex.RLock()
	defer fake.dumpResponseMutex.RUnlock()
	return fake.dumpResponseArgsForCall[i].arg1
}

var _ net.RequestDumperInterface = new(FakeRequestDumperInterface)


text:
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent('range-selector', 'Integration | Component | range selector', {
  integration: true
});

test('it renders', function(assert) {
  // Set any properties with this.set('myProperty', 'value');
  // Handle any actions with this.on('myAction', function(val) { ... });

  this.render(hbs`{{range-selector}}`);

  assert.equal(this.$().text().trim(), '');

  // Template block usage:
  this.render(hbs`
    {{#range-selector}}
      template block text
    {{/range-selector}}
  `);

  assert.equal(this.$().text().trim(), 'template block text');
});


text:
/**
 * @class Ext.util.Group
 * Encapsulates a grouped collection of records within a {@link Ext.util.Collection}
 */
Ext.define('Ext.util.Group', {
    extend: 'Ext.util.Collection',

    config: {
        groupKey: null
    }
});


text:
> see https://aka.ms/autorest

This is the AutoRest configuration file for Batch.

---
## Getting Started
To build the SDK for Batch, simply [Install AutoRest](https://aka.ms/autorest/install) and in this folder, run:

> `autorest`

To see additional help and options, run:

> `autorest --help`
---

## Configuration

### Basic Information
These are the global settings for the Batch API.

``` yaml
openapi-type: data-plane
tag: package-2018-08.7.0
```

### Tag: package-2018-08.7.0

These settings apply only when `--tag=package-2018-08.7.0` is specified on the command line.

``` yaml $(tag) == 'package-2018-08.7.0'
input-file:
- Microsoft.Batch/stable/2018-08-01.7.0/BatchService.json
```

### Tag: package-2018-03.6.1

These settings apply only when `--tag=package-2018-03.6.1` is specified on the command line.

``` yaml $(tag) == 'package-2018-03.6.1'
input-file:
- Microsoft.Batch/stable/2018-03-01.6.1/BatchService.json
```

### Tag: package-2017-09.6.0

These settings apply only when `--tag=package-2017-09.6.0` is specified on the command line.

``` yaml $(tag) == 'package-2017-09.6.0'
input-file:
- Microsoft.Batch/stable/2017-09-01.6.0/BatchService.json
```

### Tag: package-2017-06.5.1

These settings apply only when `--tag=package-2017-06.5.1` is specified on the command line.

``` yaml $(tag) == 'package-2017-06.5.1'
input-file:
- Microsoft.Batch/stable/2017-06-01.5.1/BatchService.json
```

## Suppression

Note that this setting should be removed once [this GitHub bug](https://github.com/Azure/azure-openapi-validator/issues/68) is fixed.
``` yaml
directive:
  - suppress: R2063
    from: BatchService.json
    reason: Bug in linter
```

Note that this setting should be removed once [this GitHub bug](https://github.com/Azure/azure-openapi-validator/issues/69) is fixed.
``` yaml
directive:
  - suppress: R2064
    from: BatchService.json
    reason: This is a data plane swagger specification, LRO's do not apply
```

``` yaml
directive:
  - suppress: R3016
    from: BatchService.json
    where: $..["odata.nextLink"]
    reason: The casing of this property is not incorrect.
```

``` yaml
directive:
  - suppress: R3016
    from: BatchService.json
    where: $..["publicFQDN"]
    reason: The suggested casing of this property is worse than the casing that we're using
```

``` yaml
directive:
  - suppress: R3016
    from: BatchService.json
    where: $.definitions.JobScheduleStatistics.properties.kernelCPUTime
    reason: The suggested casing of this property is worse than the casing that we're using
```

``` yaml
directive:
  - suppress: R3016
    from: BatchService.json
    where: $.definitions.TaskStatistics.properties.userCPUTime
    reason: The suggested casing of this property is worse than the casing that we're using
```

``` yaml
directive:
  - suppress: R3016
    from: BatchService.json
    where: $.definitions.TaskStatistics.properties.kernelCPUTime
    reason: The suggested casing of this property is worse than the casing that we're using
```

``` yaml
directive:
  - suppress: R3016
    from: BatchService.json
    where: $.definitions.JobScheduleStatistics.properties.userCPUTime
    reason: The suggested casing of this property is worse than the casing that we're using
```

``` yaml
directive:
  - suppress: R3016
    from: BatchService.json
    where: $.definitions.JobStatistics.properties.kernelCPUTime
    reason: The suggested casing of this property is worse than the casing that we're using
```

``` yaml
directive:
  - suppress: R3016
    from: BatchService.json
    where: $.definitions.JobStatistics.properties.userCPUTime
    reason: The suggested casing of this property is worse than the casing that we're using
```

``` yaml
directive:
  - suppress: R3016
    from: BatchService.json
    where: $.definitions.ResourceStatistics.properties.avgCPUPercentage
    reason: The suggested casing of this property is worse than the casing that we're using
```

``` yaml
directive:
  - suppress: R3016
    from: BatchService.json
    where: $.definitions.PoolEndpointConfiguration.properties.inboundNATPools
    reason: The suggested casing of this property is worse than the casing that we're using
```

``` yaml
directive:
  - suppress: R3016
    from: BatchService.json
    where: $.definitions.VirtualMachineConfiguration.properties.nodeAgentSKUId
    reason: The suggested casing of this property is worse than the casing that we're using
```

### Tag: package-2017-05.5.0

These settings apply only when `--tag=package-2017-05.5.0` is specified on the command line.

``` yaml $(tag) == 'package-2017-05.5.0'
input-file:
- Microsoft.Batch/stable/2017-05-01.5.0/BatchService.json
```

### Tag: package-2017-01.4.0

These settings apply only when `--tag=package-2017-01.4.0` is specified on the command line.

``` yaml $(tag) == 'package-2017-01.4.0'
input-file:
- Microsoft.Batch/stable/2017-01-01.4.0/BatchService.json
```

### Tag: package-2016-07.3.1

These settings apply only when `--tag=package-2016-07.3.1` is specified on the command line.

``` yaml $(tag) == 'package-2016-07.3.1'
input-file:
- Microsoft.Batch/stable/2016-07-01.3.1/BatchService.json
```

### Tag: package-2016-02.3.0

These settings apply only when `--tag=package-2016-02.3.0` is specified on the command line.

``` yaml $(tag) == 'package-2016-02.3.0'
input-file:
- Microsoft.Batch/stable/2016-02-01.3.0/BatchService.json
```

### Tag: package-2015-12.2.2

These settings apply only when `--tag=package-2015-12.2.2` is specified on the command line.

``` yaml $(tag) == 'package-2015-12.2.2'
input-file:
- Microsoft.Batch/stable/2015-12-01.2.2/BatchService.json
```

---
# Code Generation

## Swagger to SDK

This section describes what SDK should be generated by the automatic system.
This is not used by Autorest itself.

``` yaml $(swagger-to-sdk)
swagger-to-sdk:
  - repo: azure-sdk-for-go
  - repo: azure-sdk-for-js
  - repo: azure-sdk-for-node
```

## C#

These settings apply only when `--csharp` is specified on the command line.
Please also specify `--csharp-sdks-folder=<path to "SDKs" directory of your azure-sdk-for-net clone>`.

``` yaml $(csharp)
csharp:
  azure-arm: true
  license-header: MICROSOFT_MIT_NO_VERSION
  payload-flattening-threshold: 1
  namespace: Microsoft.Azure.Batch.Protocol
  output-folder: $(csharp-sdks-folder)/Batch/DataPlane/Azure.Batch/GeneratedProtocol
  clear-output-folder: true
  client-side-validation: false
```

## Python

These settings apply only when `--python` is specified on the command line.
Please also specify `--python-sdks-folder=<path to the root directory of your azure-sdk-for-python clone>`.
Use `--python-mode=update` if you already have a setup.py and just want to update the code itself.

``` yaml $(python)
python-mode: create
python:
  azure-arm: true
  license-header: MICROSOFT_MIT_NO_VERSION
  payload-flattening-threshold: 2
  namespace: azure.batch
  package-name: azure-batch
  clear-output-folder: true
```
``` yaml $(python) && $(python-mode) == 'update'
python:
  no-namespace-folders: true
  output-folder: $(python-sdks-folder)/azure-batch/azure/batch
```
``` yaml $(python) && $(python-mode) == 'create'
python:
  basic-setup-py: true
  output-folder: $(python-sdks-folder)/azure-batch
```

## Go

See configuration in [readme.go.md](./readme.go.md)

## Java

These settings apply only when `--java` is specified on the command line.
Please also specify `--node-sdks-folder=<path to root folder of your azure-batch-sdk-for-java clone>`.

``` yaml $(java)
nodejs:
  azure-arm: true
  license-header: MICROSOFT_MIT_NO_VERSION
  namespace: com.microsoft.azure.batch.protocol
  output-folder: $(node-sdks-folder)/src/main/java
  payload-flattening-threshold: 1
  generate-license-txt: true
  clear-output-folder: true
```

## Java

These settings apply only when `--java` is specified on the command line.
Please also specify `--azure-libraries-for-java-folder=<path to the root directory of your azure-libraries-for-java clone>`.

``` yaml $(java)
java:
  azure-arm: true
  fluent: true
  namespace: com.microsoft.azure.batch
  license-header: MICROSOFT_MIT_NO_CODEGEN
  payload-flattening-threshold: 1
  output-folder: $(azure-libraries-for-java-folder)/azure-batch
```


text:
using System;
using System.Globalization;
using System.Linq;
using Bmz.Framework.Extensions;
using Shouldly;
using Xunit;

namespace Bmz.Framework.Tests.Extensions
{
    public class StringExtensions_Tests
    {
        [Fact]
        public void EnsureEndsWith_Test()
        {
            //Expected use-cases
            "Test".EnsureEndsWith('!').ShouldBe("Test!");
            "Test!".EnsureEndsWith('!').ShouldBe("Test!");
            @"C:\test\folderName".EnsureEndsWith('\\').ShouldBe(@"C:\test\folderName\");
            @"C:\test\folderName\".EnsureEndsWith('\\').ShouldBe(@"C:\test\folderName\");

            //Case differences
            "TurkeY".EnsureEndsWith('y').ShouldBe("TurkeYy");
            "TurkeY".EnsureEndsWith('y', StringComparison.InvariantCultureIgnoreCase).ShouldBe("TurkeY");

            //Edge cases for Turkish 'i'.
            "TAKSİ".EnsureEndsWith('i', true, new CultureInfo("tr-TR")).ShouldBe("TAKSİ");
            "TAKSİ".EnsureEndsWith('i', false, new CultureInfo("tr-TR")).ShouldBe("TAKSİi");
        }

        [Fact]
        public void EnsureStartsWith_Test()
        {
            //Expected use-cases
            "Test".EnsureStartsWith('~').ShouldBe("~Test");
            "~Test".EnsureStartsWith('~').ShouldBe("~Test");

            //Case differences
            "Turkey".EnsureStartsWith('t').ShouldBe("tTurkey");
            "Turkey".EnsureStartsWith('t', StringComparison.InvariantCultureIgnoreCase).ShouldBe("Turkey");

            //Edge cases for Turkish 'i'.
            "İstanbul".EnsureStartsWith('i', true, new CultureInfo("tr-TR")).ShouldBe("İstanbul");
            "İstanbul".EnsureStartsWith('i', false, new CultureInfo("tr-TR")).ShouldBe("iİstanbul");
        }

        [Fact]
        public void ToPascalCase_Test()
        {
            "helloWorld".ToPascalCase().ShouldBe("HelloWorld");
            "istanbul".ToPascalCase().ShouldBe("Istanbul");
            "istanbul".ToPascalCase(new CultureInfo("tr-TR")).ShouldBe("İstanbul");
        }

        [Fact]
        public void ToCamelCase_Test()
        {
            "HelloWorld".ToCamelCase().ShouldBe("helloWorld");
            "Istanbul".ToCamelCase().ShouldBe("istanbul");
            "Istanbul".ToCamelCase(new CultureInfo("tr-TR")).ShouldBe("ıstanbul");
            "İstanbul".ToCamelCase(new CultureInfo("tr-TR")).ShouldBe("istanbul");
        }

        [Fact]
        public void Right_Test()
        {
            const string str = "This is a test string";

            str.Right(3).ShouldBe("ing");
            str.Right(0).ShouldBe("");
            str.Right(str.Length).ShouldBe(str);
        }

        [Fact]
        public void Left_Test()
        {
            const string str = "This is a test string";

            str.Left(3).ShouldBe("Thi");
            str.Left(0).ShouldBe("");
            str.Left(str.Length).ShouldBe(str);
        }

        [Fact]
        public void NormalizeLineEndings_Test()
        {
            const string str = "This\r\n is a\r test \n string";
            var normalized = str.NormalizeLineEndings();
            var lines = normalized.SplitToLines();
            lines.Length.ShouldBe(4);
        }

        [Fact]
        public void NthIndexOf_Test()
        {
            const string str = "This is a test string";

            str.NthIndexOf('i', 0).ShouldBe(-1);
            str.NthIndexOf('i', 1).ShouldBe(2);
            str.NthIndexOf('i', 2).ShouldBe(5);
            str.NthIndexOf('i', 3).ShouldBe(18);
            str.NthIndexOf('i', 4).ShouldBe(-1);
        }

        [Fact]
        public void Truncate_Test()
        {
            const string str = "This is a test string";
            const string nullValue = null;

            str.Truncate(7).ShouldBe("This is");
            str.Truncate(0).ShouldBe("");
            str.Truncate(100).ShouldBe(str);

            nullValue.Truncate(5).ShouldBe(null);
        }

        [Fact]
        public void TruncateWithPostFix_Test()
        {
            const string str = "This is a test string";
            const string nullValue = null;

            str.TruncateWithPostfix(3).ShouldBe("...");
            str.TruncateWithPostfix(12).ShouldBe("This is a...");
            str.TruncateWithPostfix(0).ShouldBe("");
            str.TruncateWithPostfix(100).ShouldBe(str);

            nullValue.Truncate(5).ShouldBe(null);

            str.TruncateWithPostfix(3, "~").ShouldBe("Th~");
            str.TruncateWithPostfix(12, "~").ShouldBe("This is a t~");
            str.TruncateWithPostfix(0, "~").ShouldBe("");
            str.TruncateWithPostfix(100, "~").ShouldBe(str);

            nullValue.TruncateWithPostfix(5, "~").ShouldBe(null);
        }

        [Fact]
        public void ToEnum_Test()
        {
            "MyValue1".ToEnum<MyEnum>().ShouldBe(MyEnum.MyValue1);
            "MyValue2".ToEnum<MyEnum>().ShouldBe(MyEnum.MyValue2);
        }

        private enum MyEnum
        {
            MyValue1,
            MyValue2
        }
    }
}


text:
<?php

namespace Eagle\AdminBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class productCategoriesControllerTest extends WebTestCase
{
    public function testAdd()
    {
        $client = static::createClient();

        $crawler = $client->request('GET', 'productCategories/add');
    }

    public function testView()
    {
        $client = static::createClient();

        $crawler = $client->request('GET', 'productCategories/view');
    }

}


text:
var ghpages = require('gh-pages');
var path = require('path');

ghpages.publish(path.join(__dirname, 'dist'), function(err) {
  console.err("Could not deploy to gh-pages : " + err);
});


text:
    #include "chrono_irrlicht/ChVisualSystemIrrlicht.h"
#endif

#ifdef CHRONO_PARDISO_MKL
    #include "chrono_pardisomkl/ChSolverPardisoMKL.h"
#endif

#ifdef CHRONO_MUMPS
    #include "chrono_mumps/ChSolverMumps.h"
#endif

#ifdef CHRONO_PARDISOPROJECT
    #include "chrono_pardisoproject/ChSolverPardisoProject.h"
#endif

using namespace chrono;
using namespace chrono::fea;

enum class SolverType { MINRES, MKL, MUMPS, PARDISO_PROJECT, SparseQR };

template <int N>
class ANCFshell : public utils::ChBenchmarkTest {
  public:
    virtual ~ANCFshell() { delete m_system; }

    ChSystem* GetSystem() override { return m_system; }
    void ExecuteStep() override { m_system->DoStepDynamics(1e-4); }

    void SimulateVis();

  protected:
    ANCFshell(SolverType solver_type);

    ChSystemSMC* m_system;
};

template <int N>
class ANCFshell_MINRES : public ANCFshell<N> {
  public:
    ANCFshell_MINRES() : ANCFshell<N>(SolverType::MINRES) {}
};

template <int N>
class ANCFshell_SparseQR : public ANCFshell<N> {
  public:
    ANCFshell_SparseQR() : ANCFshell<N>(SolverType::SparseQR) {}
};

template <int N>
class ANCFshell_MKL : public ANCFshell<N> {
  public:
    ANCFshell_MKL() : ANCFshell<N>(SolverType::MKL) {}
};

template <int N>
class ANCFshell_MUMPS : public ANCFshell<N> {
  public:
    ANCFshell_MUMPS() : ANCFshell<N>(SolverType::MUMPS) {}
};

template <int N>
class ANCFshell_PARDISOPROJECT : public ANCFshell<N> {
  public:
    ANCFshell_PARDISOPROJECT() : ANCFshell<N>(SolverType::PARDISO_PROJECT) {}
};

template <int N>
ANCFshell<N>::ANCFshell(SolverType solver_type) {
    m_system = new ChSystemSMC();
    m_system->Set_G_acc(ChVector<>(0, -9.8, 0));
    m_system->SetNumThreads(4);

    // Set solver parameters
#ifndef CHRONO_PARDISO_MKL
    if (solver_type == SolverType::MKL) {
        solver_type = SolverType::MINRES;
        std::cout << "WARNING! Chrono::MKL not enabled. Forcing use of MINRES solver" << std::endl;
    }
#endif

#ifndef CHRONO_MUMPS
    if (solver_type == SolverType::MUMPS) {
        solver_type = SolverType::MINRES;
        std::cout << "WARNING! Chrono::MUMPS not enabled. Forcing use of MINRES solver" << std::endl;
    }
#endif

#ifndef CHRONO_PARDISOPROJECT
    if (solver_type == SolverType::PARDISO_PROJECT) {
        solver_type = SolverType::MINRES;
        std::cout << "WARNING! Chrono::PARDISO_PROJECT not enabled. Forcing use of MINRES solver" << std::endl;
    }
#endif

    switch (solver_type) {
        case SolverType::MINRES: {
            auto solver = chrono_types::make_shared<ChSolverMINRES>();
            m_system->SetSolver(solver);
            solver->SetMaxIterations(100);
            solver->SetTolerance(1e-10);
            solver->EnableDiagonalPreconditioner(true);
            solver->SetVerbose(false);
            m_system->SetSolverForceTolerance(1e-10);
            break;
        }
        case SolverType::MKL: {
#ifdef CHRONO_PARDISO_MKL
            auto solver = chrono_types::make_shared<ChSolverPardisoMKL>(4);
            solver->UseSparsityPatternLearner(false);
            solver->LockSparsityPattern(true);
            solver->SetVerbose(false);
            m_system->SetSolver(solver);
#endif
            break;
        }
        case SolverType::MUMPS: {
#ifdef CHRONO_MUMPS
            auto solver = chrono_types::make_shared<ChSolverMumps>(4);
            solver->UseSparsityPatternLearner(false);
            solver->LockSparsityPattern(true);
            solver->SetVerbose(false);
            m_system->SetSolver(solver);
#endif
            break;
        }
        case SolverType::PARDISO_PROJECT: {
#ifdef CHRONO_PARDISOPROJECT
            auto solver = chrono_types::make_shared<ChSolverPardisoProject>();
            solver->UseSparsityPatternLearner(false);
            solver->LockSparsityPattern(true);
            solver->SetVerbose(false);
            m_system->SetSolver(solver);
#endif
            break;
        }
        case SolverType::SparseQR: {
            auto solver = chrono_types::make_shared<ChSolverSparseQR>();
            m_system->SetSolver(solver);
            break;
        }
    }

    // Set up integrator
    m_system->SetTimestepperType(ChTimestepper::Type::HHT);
    auto integrator = std::static_pointer_cast<ChTimestepperHHT>(m_system->GetTimestepper());
    integrator->SetAlpha(-0.2);
    integrator->SetMaxiters(100);
    integrator->SetAbsTolerances(1e-5);
    integrator->SetMode(ChTimestepperHHT::ACCELERATION);
    integrator->SetScaling(true);
    integrator->SetVerbose(false);

    // Mesh properties
    double length = 1;
    double width = 0.1;
    double thickness = 0.01;

    double rho = 500;
    ChVector<> E(2.1e7, 2.1e7, 2.1e7);
    ChVector<> nu(0.3, 0.3, 0.3);
    ChVector<> G(8.0769231e6, 8.0769231e6, 8.0769231e6);
    auto mat = chrono_types::make_shared<ChMaterialShellANCF>(rho, E, nu, G);

    // Create mesh nodes and elements
    auto mesh = chrono_types::make_shared<ChMesh>();
    m_system->Add(mesh);

    auto vis_surf = chrono_types::make_shared<ChVisualShapeFEA>(mesh);
    vis_surf->SetFEMdataType(ChVisualShapeFEA::DataType::SURFACE);
    vis_surf->SetWireframe(true);
    vis_surf->SetDrawInUndeformedReference(true);
    mesh->AddVisualShapeFEA(vis_surf);

    auto vis_node = chrono_types::make_shared<ChVisualShapeFEA>(mesh);
    vis_node->SetFEMglyphType(ChVisualShapeFEA::GlyphType::NODE_DOT_POS);
    vis_node->SetFEMdataType(ChVisualShapeFEA::DataType::NONE);
    vis_node->SetSymbolsThickness(0.004);
    mesh->AddVisualShapeFEA(vis_node);

    double dx = length / N;
    ChVector<> dir(0, 1, 0);

    auto nodeA = chrono_types::make_shared<ChNodeFEAxyzD>(ChVector<>(0, 0, -width / 2), dir);
    auto nodeB = chrono_types::make_shared<ChNodeFEAxyzD>(ChVector<>(0, 0, +width / 2), dir);
    nodeA->SetFixed(true);
    nodeB->SetFixed(true);
    mesh->AddNode(nodeA);
    mesh->AddNode(nodeB);

    for (int i = 1; i < N; i++) {
        auto nodeC = chrono_types::make_shared<ChNodeFEAxyzD>(ChVector<>(i * dx, 0, -width / 2), dir);
        auto nodeD = chrono_types::make_shared<ChNodeFEAxyzD>(ChVector<>(i * dx, 0, +width / 2), dir);
        mesh->AddNode(nodeC);
        mesh->AddNode(nodeD);

        auto element = chrono_types::make_shared<ChElementShellANCF_3423>();
        element->SetNodes(nodeA, nodeB, nodeD, nodeC);
        element->SetDimensions(dx, width);
        element->AddLayer(thickness, 0 * CH_C_DEG_TO_RAD, mat);
        element->SetAlphaDamp(0.0);
        mesh->AddElement(element);

        nodeA = nodeC;
        nodeB = nodeD;
    }
}

template <int N>
void ANCFshell<N>::SimulateVis() {
#ifdef CHRONO_IRRLICHT
    // Create the Irrlicht visualization system
    auto vis = chrono_types::make_shared<irrlicht::ChVisualSystemIrrlicht>();
    m_system->SetVisualSystem(vis);
    vis->SetWindowSize(800, 600);
    vis->SetWindowTitle("ANCF shells");
    vis->Initialize();
    vis->AddLogo();
    vis->AddSkyBox();
    vis->AddTypicalLights();
    vis->AddCamera(ChVector<>(-0.2, 0.2, 0.2), ChVector<>(0, 0, 0));

    while (vis->Run()) {
        vis->BeginScene();
        vis->DrawAll();
        irrlicht::tools::drawSegment(vis.get(), ChVector<>(0), ChVector<>(1, 0, 0), ChColor(1, 0, 0));
        irrlicht::tools::drawSegment(vis.get(), ChVector<>(0), ChVector<>(0, 1, 0), ChColor(0, 1, 0));
        irrlicht::tools::drawSegment(vis.get(), ChVector<>(0), ChVector<>(0, 0, 1), ChColor(0, 0, 1));
        ExecuteStep();
        vis->EndScene();
    }
#endif
}

// =============================================================================

#define NUM_SKIP_STEPS 10  // number of steps for hot start
#define NUM_SIM_STEPS 100  // number of simulation steps for each benchmark

CH_BM_SIMULATION_LOOP(ANCFshell08_MINRES, ANCFshell_MINRES<8>, NUM_SKIP_STEPS, NUM_SIM_STEPS, 10);
CH_BM_SIMULATION_LOOP(ANCFshell16_MINRES, ANCFshell_MINRES<16>, NUM_SKIP_STEPS, NUM_SIM_STEPS, 10);
CH_BM_SIMULATION_LOOP(ANCFshell32_MINRES, ANCFshell_MINRES<32>, NUM_SKIP_STEPS, NUM_SIM_STEPS, 10);
CH_BM_SIMULATION_LOOP(ANCFshell64_MINRES, ANCFshell_MINRES<64>, NUM_SKIP_STEPS, NUM_SIM_STEPS, 10);

CH_BM_SIMULATION_LOOP(ANCFshell08_SparseQR, ANCFshell_SparseQR<8>, NUM_SKIP_STEPS, NUM_SIM_STEPS, 10);
CH_BM_SIMULATION_LOOP(ANCFshell16_SparseQR, ANCFshell_SparseQR<16>, NUM_SKIP_STEPS, NUM_SIM_STEPS, 10);
CH_BM_SIMULATION_LOOP(ANCFshell32_SparseQR, ANCFshell_SparseQR<32>, NUM_SKIP_STEPS, NUM_SIM_STEPS, 10);
CH_BM_SIMULATION_LOOP(ANCFshell64_SparseQR, ANCFshell_SparseQR<64>, NUM_SKIP_STEPS, NUM_SIM_STEPS, 10);

#ifdef CHRONO_PARDISO_MKL
CH_BM_SIMULATION_LOOP(ANCFshell08_MKL, ANCFshell_MKL<8>, NUM_SKIP_STEPS, NUM_SIM_STEPS, 10);
CH_BM_SIMULATION_LOOP(ANCFshell16_MKL, ANCFshell_MKL<16>, NUM_SKIP_STEPS, NUM_SIM_STEPS, 10);
CH_BM_SIMULATION_LOOP(ANCFshell32_MKL, ANCFshell_MKL<32>, NUM_SKIP_STEPS, NUM_SIM_STEPS, 10);
CH_BM_SIMULATION_LOOP(ANCFshell64_MKL, ANCFshell_MKL<64>, NUM_SKIP_STEPS, NUM_SIM_STEPS, 10);
#endif

#ifdef CHRONO_MUMPS
CH_BM_SIMULATION_LOOP(ANCFshell08_MUMPS, ANCFshell_MUMPS<8>, NUM_SKIP_STEPS, NUM_SIM_STEPS, 10);
CH_BM_SIMULATION_LOOP(ANCFshell16_MUMPS, ANCFshell_MUMPS<16>, NUM_SKIP_STEPS, NUM_SIM_STEPS, 10);
CH_BM_SIMULATION_LOOP(ANCFshell32_MUMPS, ANCFshell_MUMPS<32>, NUM_SKIP_STEPS, NUM_SIM_STEPS, 10);
CH_BM_SIMULATION_LOOP(ANCFshell64_MUMPS, ANCFshell_MUMPS<64>, NUM_SKIP_STEPS, NUM_SIM_STEPS, 10);
#endif

#ifdef CHRONO_PARDISOPROJECT
CH_BM_SIMULATION_LOOP(ANCFshell08_PARDISOPROJECT, ANCFshell_PARDISOPROJECT<8>, NUM_SKIP_STEPS, NUM_SIM_STEPS, 10);
CH_BM_SIMULATION_LOOP(ANCFshell16_PARDISOPROJECT, ANCFshell_PARDISOPROJECT<16>, NUM_SKIP_STEPS, NUM_SIM_STEPS, 10);
CH_BM_SIMULATION_LOOP(ANCFshell32_PARDISOPROJECT, ANCFshell_PARDISOPROJECT<32>, NUM_SKIP_STEPS, NUM_SIM_STEPS, 10);
CH_BM_SIMULATION_LOOP(ANCFshell64_PARDISOPROJECT, ANCFshell_PARDISOPROJECT<64>, NUM_SKIP_STEPS, NUM_SIM_STEPS, 10);
#endif

// =============================================================================

int main(int argc, char* argv[]) {
    ::benchmark::Initialize(&argc, argv);

#ifdef CHRONO_IRRLICHT
    if (::benchmark::ReportUnrecognizedArguments(argc, argv)) {
        ANCFshell_MINRES<16> test;
        test.SimulateVis();
        return 0;
    }
#endif

    ::benchmark::RunSpecifiedBenchmarks();
}