text:
package com.leelit.stuer.module_stu;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;

import com.leelit.stuer.R;
import com.leelit.stuer.utils.UiUtils;

import butterknife.ButterKnife;
import butterknife.InjectView;

public class StuWebViewActivity extends AppCompatActivity {

    @InjectView(R.id.webView)
    WebView mWebView;
    @InjectView(R.id.btn_back)
    ImageView mBtnBack;
    @InjectView(R.id.btn_forward)
    ImageView mBtnForward;
    @InjectView(R.id.toolbar)
    Toolbar mToolbar;
    @InjectView(R.id.progressBar)
    ProgressBar mProgressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_stu);
        ButterKnife.inject(this);
        UiUtils.setTranslucentStatusBar(this);
        if (UiUtils.isNightMode(this)) {
            return;
        }

        webViewProgressSetting();
        initToolBar();

        WebSettings settings = mWebView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setDisplayZoomControls(false); // 隐藏webview缩放按钮
        settings.setBuiltInZoomControls(true); // 显示缩放按钮(wap网页不支持)
        settings.setUseWideViewPort(true); // 支持双击缩放(wap网页不支持)
        settings.setLoadWithOverviewMode(true); // 自适应屏幕

        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

        });

        mWebView.loadUrl(getIntent().getStringExtra("website"));

        mBtnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mWebView.canGoBack()) {
                    mWebView.goBack();
                } else {
                    finish();
                }
            }
        });

        mBtnForward.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mWebView.goForward();
            }
        });

        mWebView.setDownloadListener(new MyWebViewDownLoadListener());
    }

    private void initToolBar() {
        setSupportActionBar(mToolbar);
        mToolbar.setTitle(getIntent().getStringExtra("title"));
        mToolbar.setNavigationIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void webViewProgressSetting() {
        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    mProgressBar.setVisibility(View.INVISIBLE);
                } else {
                    if (mProgressBar.getVisibility() == View.INVISIBLE) {
                        mProgressBar.setVisibility(View.VISIBLE);
                    }
                    mProgressBar.setProgress(newProgress);
                }
            }
        });
    }

    private class MyWebViewDownLoadListener implements DownloadListener {

        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
                                    long contentLength) {
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        }
    }

    @Override
    public void onBackPressed() {
        if (mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            super.onBackPressed();
        }
    }
}


text:
The Illuminate Database component is a full database toolkit for PHP, providing an expressive query builder, ActiveRecord style ORM, and schema builder. It currently supports MySQL, Postgres, SQL Server, and SQLite. It also serves as the database layer of the Laravel PHP framework.

### Usage Instructions

First, create a new "Capsule" manager instance. Capsule aims to make configuring the library for usage outside of the Laravel framework as easy as possible.

```PHP
use Illuminate\Database\Capsule\Manager as Capsule;

$capsule = new Capsule;

$capsule->addConnection([
	'driver'    => 'mysql',
	'host'      => 'localhost',
	'database'  => 'database',
	'username'  => 'root',
	'password'  => 'password',
	'charset'   => 'utf8',
	'collation' => 'utf8_unicode_ci',
	'prefix'    => '',
]);

// Set the event dispatcher used by Eloquent models... (optional)
use Illuminate\Events\Dispatcher;
use Illuminate\Container\Container;
$capsule->setEventDispatcher(new Dispatcher(new Container));

// Make this Capsule instance available globally via static methods... (optional)
$capsule->setAsGlobal();

// Setup the Eloquent ORM... (optional; unless you've used setEventDispatcher())
$capsule->bootEloquent();
```

Once the Capsule instance has been registered. You may use it like so:

**Using The Query Builder**

```PHP
$users = Capsule::table('users')->where('votes', '>', 100)->get();
```
Other core methods may be accessed directly from the Capsule in the same manner as from the DB facade:
```PHP
$results = Capsule::select('select * from users where id = ?', array(1));
```

**Using The Schema Builder**

```PHP
Capsule::schema()->create('users', function($table)
{
	$table->increments('id');
	$table->string('email')->unique();
	$table->timestamps();
});
```

**Using The Eloquent ORM**

```PHP
class User extends Illuminate\Database\Eloquent\Model {}

$users = User::where('votes', '>', 1)->get();
```

For further documentation on using the various database facilities this library provides, consult the [Laravel framework documentation](http://laravel.com/docs).

redpajama_set_name: RedPajamaGithub


text:
@class AppDelegate;

@interface PacketManager : NSObject

- (NSArray *)getWaitingPacket;

- (void)sendEmptyData;
- (void)sendQuery0EData;
- (void)sendLoginData;
- (void)sendHeartbeatData;
- (void)sendReadAcStateWithAddresses:(NSArray *)addressArray;
- (void)sendCommandsWithOnoff:(BOOL)onoff mode:(int)mode fan:(int)fan temperature:(int)temperature forAddressArray:(NSArray *)addresses;
- (void)sendDevicesData;
- (void)sendTimeSynchronizationData;

- (void)sendTimerQueryWithTimerID:(int)timerID;
- (void)sendTimerQueryAll;
- (void)sendTimerQueryCount;
//- (void)sendTimerQueryList;
- (void)sendTimerDeleteWithTimerID:(int)timerID;
- (void)sendTimerDeleteAll;
- (void)sendTimerWithDic:(NSDictionary*)dic;
- (void)sendAddTimerWithDic:(NSDictionary*)dic;
- (void)sendTimerEditWithTimerID:(int)timerID enabled:(BOOL)timerEnabled hour:(int)hour minute:(int)minute week:(NSArray *)weekArray repeat:(BOOL)repeatEnabled addresses:(NSArray *)addrArray onoff:(BOOL)onoff mode:(int)mode fan:(int)fan temperature:(int)temperature name:(NSString *)timerName;
- (void)sendTimerAddWithTimerEnabled:(BOOL)timerEnabled hour:(int)hour minute:(int)minute week:(NSArray *)weekArray repeat:(BOOL)repeatEnabled addresses:(NSArray *)addrArray onoff:(BOOL)onoff mode:(int)mode fan:(int)fan temperature:(int)temperature name:(NSString *)timerName;

//- (void)sendReplyPacketWithPfc:(int)pfc;

- (BOOL)send_OF_RequestData;

- (void)sendTestSocketTcpData:(NSData*)tcpData;

- (void)clear;

@end


text:
set -o errexit
set -o nounset
set -o pipefail

OS_ROOT=$(dirname "${BASH_SOURCE}")/../..
source "${OS_ROOT}/hack/util.sh"
os::log::install_errexit

# This test validates deployments

oc get deploymentConfigs
oc get dc
oc create -f test/integration/fixtures/test-deployment-config.json
oc describe deploymentConfigs test-deployment-config
[ "$(oc env dc/test-deployment-config --list | grep TEST=value)" ]
[ ! "$(oc env dc/test-deployment-config TEST- --list | grep TEST=value)" ]
[ "$(oc env dc/test-deployment-config TEST=foo --list | grep TEST=foo)" ]
[ "$(oc env dc/test-deployment-config OTHER=foo --list | grep TEST=value)" ]
[ ! "$(oc env dc/test-deployment-config OTHER=foo -c 'ruby' --list | grep OTHER=foo)" ]
[ "$(oc env dc/test-deployment-config OTHER=foo -c 'ruby*'   --list | grep OTHER=foo)" ]
[ "$(oc env dc/test-deployment-config OTHER=foo -c '*hello*' --list | grep OTHER=foo)" ]
[ "$(oc env dc/test-deployment-config OTHER=foo -c '*world'  --list | grep OTHER=foo)" ]
[ "$(oc env dc/test-deployment-config OTHER=foo --list | grep OTHER=foo)" ]
[ "$(oc env dc/test-deployment-config OTHER=foo -o yaml | grep "name: OTHER")" ]
[ "$(echo "OTHER=foo" | oc env dc/test-deployment-config -e - --list | grep OTHER=foo)" ]
[ ! "$(echo "#OTHER=foo" | oc env dc/test-deployment-config -e - --list | grep OTHER=foo)" ]
[ "$(oc env dc/test-deployment-config TEST=bar OTHER=baz BAR-)" ]

oc deploy test-deployment-config
oc delete deploymentConfigs test-deployment-config
echo "deploymentConfigs: ok"

oc delete all --all
# TODO: remove, flake caused by deployment controller updating the following dc
sleep 1
oc delete all --all

oc create -f test/integration/fixtures/test-deployment-config.json
tryuntil oc get rc/test-deployment-config-1
# oc deploy test-deployment-config --cancel # TODO: does not block until success
# oc deploy test-deployment-config --latest
# tryuntil oc get rc/test-deployment-config-2

# scale rc via deployment configuration
oc scale dc test-deployment-config --replicas=1
# scale directly
oc scale rc test-deployment-config-1 --replicas=5
oc delete all --all
echo "scale: ok"

oc delete all --all

oc process -f examples/sample-app/application-template-dockerbuild.json -l app=dockerbuild | oc create -f -
tryuntil oc get rc/database-1

oc rollback database --to-version=1 -o=yaml
oc rollback dc/database --to-version=1 -o=yaml
oc rollback dc/database --to-version=1 --dry-run
oc rollback database-1 -o=yaml
oc rollback rc/database-1 -o=yaml
# should fail because there's no previous deployment
[ ! "$(oc rollback database -o yaml)" ]
echo "rollback: ok"

oc get dc/database
oc stop dc/database
[ ! "$(oc get dc/database)" ]
[ ! "$(oc get rc/database-1)" ]
echo "stop: ok"


text:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/img_btn_pause_pressed"
        android:state_focused="true"
        android:state_pressed="true" />
    <item android:drawable="@drawable/img_btn_pause_pressed"
        android:state_focused="false"
        android:state_pressed="true" />
    <item android:drawable="@drawable/img_btn_pause_pressed" android:state_focused="true" />
    <item android:drawable="@drawable/img_btn_pause"
        android:state_focused="false"
        android:state_pressed="false" />
</selector>


text:
package io.opensec.oval.model.esx;

import io.opensec.oval.model.OvalEnumeration;

/**
 * This enumeration defines a specific set of values that describe the support level
 * of a given ESX Server patch.
 *
 * @author  Akihito Nakamura, AIST
 * @see OVAL Language
 */
public enum SupportLevelEnumeration
    implements OvalEnumeration
{

    C           ( "C" ),
    D           ( "D" ),
    G           ( "G" ),
    H           ( "H" ),
    NONE        ( "" );

    /**
     * A factory method.
     */
    public static SupportLevelEnumeration fromValue(
                    final String value
                    )
    {
        for (SupportLevelEnumeration  e : SupportLevelEnumeration.values()) {
            if (e.value.equals( value )) {
                return e;
            }
        }

        throw new IllegalArgumentException( value );
    }

    private String  value = null;

    /**
     * Constructor.
     */
    SupportLevelEnumeration(
                    final String value
                    )
    {
        this.value = value;
    }

    public String value()
    {
        return value;
    }

    //**************************************************************
    //  java.lang.Object
    //**************************************************************

    @Override
    public String toString()
    {
        return value;
    }

}
//


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

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>io.inkstand</groupId>
		<artifactId>inkstand-parent</artifactId>
		<version>0.2.0-SNAPSHOT</version>
		<relativePath>inkstand-parent/pom.xml</relativePath>
	</parent>

	<artifactId>inkstand</artifactId>
	<version>0.2.0-SNAPSHOT</version>
	<name>${project.groupId}:${project.artifactId}</name>
	<packaging>pom</packaging>

	<modules>
		<module>inkstand-core</module>
		<module>inkstand-jcr</module>
		<module>inkstand-jcr-jackrabbit</module>
		<module>inkstand-undertow</module>
		<module>inkstand-ms</module>
		<module>inkstand-security</module>
		<module>inkstand-parent</module>
		<module>inkstand-cdi</module>
		<module>inkstand-it</module>
		<module>inkstand-mgmt</module>
	</modules>

	<dependencies>
		<!-- Code Coverage -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
		</dependency>
		<!-- Binding for Log4J -->
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-slf4j-impl</artifactId>
			<scope>runtime</scope>
		</dependency>
		<!-- Log4j API and Core implementation required for binding -->
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-api</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-core</artifactId>
			<scope>runtime</scope>
		</dependency>
		<!-- Test libraries -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.mockito</groupId>
			<artifactId>mockito-all</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

</project>


text:
This repository containes custom developed themes for lightpaper documents.

## Installation guide

1. Clone this repo into **~/.lightpaper/Themes/**
2. Open *Light Paper* preferences `cmd + ,` and choose theme

## Font Dependecies

* [CenturyGothic]()
* [Tele-GroteskNor](https://www.wfonts.com/font/tele-grotesknor)


text:
dic = ee.Dictionary({
    'B1': 182,
    'B2': 219,
    'B3': 443
})

print('Serialized representation of ee.Dictionary:', dic.serialize(), sep='\n')
# [END earthengine__apidocs__ee_dictionary_serialize]


text:
// Copyright 2009-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0

#include "taskschedulerinternal.h"
#include "../math/math.h"
#include "../sys/sysinfo.h"
#include <algorithm>

namespace embree
{
  RTC_NAMESPACE_BEGIN

  static MutexSys g_mutex;
  size_t TaskScheduler::g_numThreads = 0;
  __thread TaskScheduler* TaskScheduler::g_instance = nullptr;
  std::vector<Ref<TaskScheduler>> g_instance_vector;
  __thread TaskScheduler::Thread* TaskScheduler::thread_local_thread = nullptr;
  TaskScheduler::ThreadPool* TaskScheduler::threadPool = nullptr;

  template<typename Predicate, typename Body>
  __forceinline void TaskScheduler::steal_loop(Thread& thread, const Predicate& pred, const Body& body)
  {
    while (true)
    {
      /*! some rounds that yield */
      for (size_t i=0; i<32; i++)
      {
        /*! some spinning rounds */
        const size_t threadCount = thread.threadCount();
        for (size_t j=0; j<1024; j+=threadCount)
        {
          if (!pred()) return;
          if (thread.scheduler->steal_from_other_threads(thread)) {
            i=j=0;
            body();
          }
        }
        yield();
      }
    }
  }

  /*! run this task */
  void TaskScheduler::Task::run_internal (Thread& thread) // FIXME: avoid as many dll_exports as possible
  {
    /* try to run if not already stolen */
    if (try_switch_state(INITIALIZED,DONE))
    {
      Task* prevTask = thread.task;
      thread.task = this;
      // -- GODOT start --
      // try {
      // if (thread.scheduler->cancellingException == nullptr)
          closure->execute();
      // } catch (...) {
      //   if (thread.scheduler->cancellingException == nullptr)
      //     thread.scheduler->cancellingException = std::current_exception();
      // }
      // -- GODOT end --
      thread.task = prevTask;
      add_dependencies(-1);
    }

    /* steal until all dependencies have completed */
    steal_loop(thread,
               [&] () { return dependencies>0; },
               [&] () { while (thread.tasks.execute_local_internal(thread,this)); });

    /* now signal our parent task that we are finished */
    if (parent)
      parent->add_dependencies(-1);
  }

    /*! run this task */
  dll_export void TaskScheduler::Task::run (Thread& thread) {
    run_internal(thread);
  }

  bool TaskScheduler::TaskQueue::execute_local_internal(Thread& thread, Task* parent)
  {
    /* stop if we run out of local tasks or reach the waiting task */
    if (right == 0 || &tasks[right-1] == parent)
      return false;

    /* execute task */
    size_t oldRight = right;
    tasks[right-1].run_internal(thread);
    if (right != oldRight) {
      THROW_RUNTIME_ERROR("you have to wait for spawned subtasks");
    }

    /* pop task and closure from stack */
    right--;
    if (tasks[right].stackPtr != size_t(-1))
      stackPtr = tasks[right].stackPtr;

    /* also move left pointer */
    if (left >= right) left.store(right.load());

    return right != 0;
  }

  dll_export bool TaskScheduler::TaskQueue::execute_local(Thread& thread, Task* parent) {
    return execute_local_internal(thread,parent);
  }

  bool TaskScheduler::TaskQueue::steal(Thread& thread)
  {
    size_t l = left;
    size_t r = right;
    if (l < r)
    {
      l = left++;
       if (l >= r)
         return false;
    }
    else
      return false;

    if (!tasks[l].try_steal(thread.tasks.tasks[thread.tasks.right]))
      return false;

    thread.tasks.right++;
    return true;
  }

  /* we steal from the left */
  size_t TaskScheduler::TaskQueue::getTaskSizeAtLeft()
  {
    if (left >= right) return 0;
    return tasks[left].N;
  }

  void threadPoolFunction(std::pair<TaskScheduler::ThreadPool*,size_t>* pair)
  {
    TaskScheduler::ThreadPool* pool = pair->first;
    size_t threadIndex = pair->second;
    delete pair;
    pool->thread_loop(threadIndex);
  }

  TaskScheduler::ThreadPool::ThreadPool(bool set_affinity)
    : numThreads(0), numThreadsRunning(0), set_affinity(set_affinity), running(false) {}

  dll_export void TaskScheduler::ThreadPool::startThreads()
  {
    if (running) return;
    setNumThreads(numThreads,true);
  }

  void TaskScheduler::ThreadPool::setNumThreads(size_t newNumThreads, bool startThreads)
  {
    Lock<MutexSys> lock(g_mutex);
    assert(newNumThreads);
    newNumThreads = min(newNumThreads, (size_t) getNumberOfLogicalThreads());

    numThreads = newNumThreads;
    if (!startThreads && !running) return;
    running = true;
    size_t numThreadsActive = numThreadsRunning;

    mutex.lock();
    numThreadsRunning = newNumThreads;
    mutex.unlock();
    condition.notify_all();

    /* start new threads */
    for (size_t t=numThreadsActive; t<numThreads; t++)
    {
      if (t == 0) continue;
      auto pair = new std::pair<TaskScheduler::ThreadPool*,size_t>(this,t);
      threads.push_back(createThread((thread_func)threadPoolFunction,pair,4*1024*1024,set_affinity ? t : -1));
    }

    /* stop some threads if we reduce the number of threads */
    for (ssize_t t=numThreadsActive-1; t>=ssize_t(numThreadsRunning); t--) {
      if (t == 0) continue;
      embree::join(threads.back());
      threads.pop_back();
    }
  }

  TaskScheduler::ThreadPool::~ThreadPool()
  {
    /* leave all taskschedulers */
    mutex.lock();
    numThreadsRunning = 0;
    mutex.unlock();
    condition.notify_all();

    /* wait for threads to terminate */
    for (size_t i=0; i<threads.size(); i++)
      embree::join(threads[i]);
  }

  dll_export void TaskScheduler::ThreadPool::add(const Ref<TaskScheduler>& scheduler)
  {
    mutex.lock();
    schedulers.push_back(scheduler);
    mutex.unlock();
    condition.notify_all();
  }

  dll_export void TaskScheduler::ThreadPool::remove(const Ref<TaskScheduler>& scheduler)
  {
    Lock<MutexSys> lock(mutex);
    for (std::list<Ref<TaskScheduler> >::iterator it = schedulers.begin(); it != schedulers.end(); it++) {
      if (scheduler == *it) {
        schedulers.erase(it);
        return;
      }
    }
  }

  void TaskScheduler::ThreadPool::thread_loop(size_t globalThreadIndex)
  {
    while (globalThreadIndex < numThreadsRunning)
    {
      Ref<TaskScheduler> scheduler = NULL;
      ssize_t threadIndex = -1;
      {
        Lock<MutexSys> lock(mutex);
        condition.wait(mutex, [&] () { return globalThreadIndex >= numThreadsRunning || !schedulers.empty(); });
        if (globalThreadIndex >= numThreadsRunning) break;
        scheduler = schedulers.front();
        threadIndex = scheduler->allocThreadIndex();
      }
      scheduler->thread_loop(threadIndex);
    }
  }

  TaskScheduler::TaskScheduler()
    : threadCounter(0), anyTasksRunning(0), hasRootTask(false)
  {
    threadLocal.resize(2*getNumberOfLogicalThreads()); // FIXME: this has to be 2x as in the compatibility join mode with rtcCommitScene the worker threads also join. When disallowing rtcCommitScene to join a build we can remove the 2x.
    for (size_t i=0; i<threadLocal.size(); i++)
      threadLocal[i].store(nullptr);
  }

  TaskScheduler::~TaskScheduler()
  {
    assert(threadCounter == 0);
  }

  dll_export size_t TaskScheduler::threadID()
  {
    Thread* thread = TaskScheduler::thread();
    if (thread) return thread->threadIndex;
    else        return 0;
  }

  dll_export size_t TaskScheduler::threadIndex()
  {
    Thread* thread = TaskScheduler::thread();
    if (thread) return thread->threadIndex;
    else        return 0;
  }

  dll_export size_t TaskScheduler::threadCount() {
    return threadPool->size();
  }

  dll_export TaskScheduler* TaskScheduler::instance()
  {
    if (g_instance == NULL) {
      Lock<MutexSys> lock(g_mutex);
      g_instance = new TaskScheduler;
      g_instance_vector.push_back(g_instance);
    }
    return g_instance;
  }

  void TaskScheduler::create(size_t numThreads, bool set_affinity, bool start_threads)
  {
    if (!threadPool) threadPool = new TaskScheduler::ThreadPool(set_affinity);
    threadPool->setNumThreads(numThreads,start_threads);
  }

  void TaskScheduler::destroy() {
    delete threadPool; threadPool = nullptr;
  }

  dll_export ssize_t TaskScheduler::allocThreadIndex()
  {
    size_t threadIndex = threadCounter++;
    assert(threadIndex < threadLocal.size());
    return threadIndex;
  }

  void TaskScheduler::join()
  {
    mutex.lock();
    size_t threadIndex = allocThreadIndex();
    condition.wait(mutex, [&] () { return hasRootTask.load(); });
    mutex.unlock();
    // -- GODOT start --
    // std::exception_ptr except = thread_loop(threadIndex);
    // if (except != nullptr) std::rethrow_exception(except);
    thread_loop(threadIndex);
    // -- GODOT end --
  }

  void TaskScheduler::reset() {
    hasRootTask = false;
  }

  void TaskScheduler::wait_for_threads(size_t threadCount)
  {
    while (threadCounter < threadCount-1)
      pause_cpu();
  }

  dll_export TaskScheduler::Thread* TaskScheduler::thread() {
    return thread_local_thread;
  }

  dll_export TaskScheduler::Thread* TaskScheduler::swapThread(Thread* thread)
  {
    Thread* old = thread_local_thread;
    thread_local_thread = thread;
    return old;
  }

  dll_export bool TaskScheduler::wait()
  {
    Thread* thread = TaskScheduler::thread();
    if (thread == nullptr) return true;
    while (thread->tasks.execute_local_internal(*thread,thread->task)) {};
    return thread->scheduler->cancellingException == nullptr;
  }

// -- GODOT start --
//   std::exception_ptr TaskScheduler::thread_loop(size_t threadIndex)
  void TaskScheduler::thread_loop(size_t threadIndex)
// -- GODOT end --
  {
    /* allocate thread structure */
    std::unique_ptr<Thread> mthread(new Thread(threadIndex,this)); // too large for stack allocation
    Thread& thread = *mthread;
    threadLocal[threadIndex].store(&thread);
    Thread* oldThread = swapThread(&thread);

    /* main thread loop */
    while (anyTasksRunning)
    {
      steal_loop(thread,
                 [&] () { return anyTasksRunning > 0; },
                 [&] () {
                   anyTasksRunning++;
                   while (thread.tasks.execute_local_internal(thread,nullptr));
                   anyTasksRunning--;
                 });
    }
    threadLocal[threadIndex].store(nullptr);
    swapThread(oldThread);

    /* remember exception to throw */
    // -- GODOT start --
    // std::exception_ptr except = nullptr;
    // if (cancellingException != nullptr) except = cancellingException;
    // -- GODOT end --
    /* wait for all threads to terminate */
    threadCounter--;
#if defined(__WIN32__)
	size_t loopIndex = 1;
#endif
#define LOOP_YIELD_THRESHOLD (4096)
	while (threadCounter > 0) {
#if defined(__WIN32__)
          if ((loopIndex % LOOP_YIELD_THRESHOLD) == 0)
            yield();
          else
            _mm_pause();
	  loopIndex++;
#else
          yield();
#endif
	}
     // -- GODOT start --
     // return except;
     return;
     // -- GODOT end --
  }

  bool TaskScheduler::steal_from_other_threads(Thread& thread)
  {
    const size_t threadIndex = thread.threadIndex;
    const size_t threadCount = this->threadCounter;

    for (size_t i=1; i<threadCount; i++)
    {
      pause_cpu(32);
      size_t otherThreadIndex = threadIndex+i;
      if (otherThreadIndex >= threadCount) otherThreadIndex -= threadCount;

      Thread* othread = threadLocal[otherThreadIndex].load();
      if (!othread)
        continue;

      if (othread->tasks.steal(thread))
        return true;
    }

    return false;
  }

  dll_export void TaskScheduler::startThreads() {
    threadPool->startThreads();
  }

  dll_export void TaskScheduler::addScheduler(const Ref<TaskScheduler>& scheduler) {
    threadPool->add(scheduler);
  }

  dll_export void TaskScheduler::removeScheduler(const Ref<TaskScheduler>& scheduler) {
    threadPool->remove(scheduler);
  }

  RTC_NAMESPACE_END
}


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

<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<TITLE>
PipelineHandler (Yax - an XProc (XML Pipeline) Implementation 0.11.0-SNAPSHOT API)
</TITLE>

<META NAME="date" CONTENT="2008-03-04">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

de.opsdesign.yax

Interface PipelineHandler

public interface PipelineHandler

Method Summary

 java.lang.String
buildUsageMessage()

 java.lang.String
buildYaxVersionMessage()

 void
configure()

 Configuration
getConfiguration()

 void
log(java.lang.String msg)

 void
log(java.lang.String msg,
    int msgSeverity)

 void
log(YaxEvent yaxEvent)

 void
log(YaxException yaxException)

 void
run()

 org.w3c.dom.Document
toDocument()

          returns an XML document of the configuration (implementation and pipeline)

Method Detail

configure

void configure()
               throws ConfigurationException

Throws:

ConfigurationException

run

void run()
         throws RunException

Throws:

RunException

getConfiguration

Configuration getConfiguration()

buildYaxVersionMessage

java.lang.String buildYaxVersionMessage()

buildUsageMessage

java.lang.String buildUsageMessage()

toDocument

org.w3c.dom.Document toDocument()

returns an XML document of the configuration (implementation and pipeline)

Returns:
XML document of the configuration

log

void log(java.lang.String msg)

log

void log(java.lang.String msg,
         int msgSeverity)

log

void log(YaxEvent yaxEvent)

log

void log(YaxException yaxException)

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright © 2008 OPS Design GmbH. All Rights Reserved.


text:
package org.dizitart.no2.event;

/**
 * An interface when implemented makes an object be
 * able to listen to any changes in a {@link org.dizitart.no2.NitriteCollection}
 * or {@link org.dizitart.no2.objects.ObjectRepository}.
 *
 * [[app-listing]]
 * [source,java]
 * .Example
 * --
 *
 *  // observe any change to the collection
 *  collection.register(new ChangeListener() {
 *
 *      @Override
 *      public void onChange(ChangeInfo changeInfo) {
 *          System.out.println("Action - " + changeInfo.getChangeType());
 *
 *          System.out.println("List of affected ids:");
 *          for (NitriteId id : changeInfo.getChangedItems()) {
 *              System.out.println("Id - " + id);
 *          }
 *      }
 *  });
 *
 * --
 *
 * @since 1.0
 * @author Anindya Chatterjee.
 */
public interface ChangeListener {

    /**
     * Listener routine to be invoked for each change event.
     *
     * @param changeInfo the change information
     */
    void onChange(ChangeInfo changeInfo);
}


text:
package org.apache.flink.cep.pattern.conditions;

import org.apache.flink.annotation.Internal;
import org.apache.flink.util.Preconditions;

/**
 * A {@link IterativeCondition condition} which filters elements of the given type. An element is
 * filtered out iff it is not assignable to the given subtype of {@code T}.
 *
 * @param <T> Type of the elements to be filtered
 */
@Internal
public class SubtypeCondition<T> extends SimpleCondition<T> {
    private static final long serialVersionUID = -2990017519957561355L;

    /** The subtype to filter for. */
    private final Class<? extends T> subtype;

    public SubtypeCondition(final Class<? extends T> subtype) {
        this.subtype = Preconditions.checkNotNull(subtype, "The subtype cannot be null.");
    }

    @Override
    public boolean filter(T value) throws Exception {
        return subtype.isAssignableFrom(value.getClass());
    }
}


text:
package org.nd4j.linalg.api.ops.impl.scalar;

import org.apache.commons.math3.util.FastMath;
import org.nd4j.linalg.api.complex.IComplexNumber;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.ops.BaseScalarOp;
import org.nd4j.linalg.api.ops.Op;

/**
 * Scalar max operation.
 * Returns the max of an element
 * in the ndarray of the specified number.
 *
 * @author Adam Gibson
 */
public class ScalarMin extends BaseScalarOp {
    public ScalarMin() {
    }

    public ScalarMin(INDArray x, INDArray y, INDArray z, long n, Number num) {
        super(x, y, z, n, num);
    }

    public ScalarMin(INDArray x, Number num) {
        super(x, num);
    }

    public ScalarMin(INDArray x, INDArray y, INDArray z, long n, IComplexNumber num) {
        super(x, y, z, n, num);
    }

    public ScalarMin(INDArray x, IComplexNumber num) {
        super(x, num);
    }

    @Override
    public int opNum() {
        return 12;
    }

    @Override
    public String name() {
        return "max_scalar";
    }

    @Override
    public IComplexNumber op(IComplexNumber origin, double other) {
        if (origin.absoluteValue().doubleValue() > complexNumber.absoluteValue().doubleValue())
            return origin;
        return complexNumber;
    }

    @Override
    public IComplexNumber op(IComplexNumber origin, float other) {
        if (origin.absoluteValue().doubleValue() > complexNumber.absoluteValue().doubleValue())
            return origin;
        return complexNumber;
    }

    @Override
    public IComplexNumber op(IComplexNumber origin, IComplexNumber other) {
        if (origin.absoluteValue().doubleValue() > complexNumber.absoluteValue().doubleValue())
            return origin;
        return complexNumber;
    }

    @Override
    public float op(float origin, float other) {
        return FastMath.max(origin, num.floatValue());
    }

    @Override
    public double op(double origin, double other) {
        return FastMath.max(origin, num.doubleValue());
    }

    @Override
    public double op(double origin) {
        return FastMath.max(origin, num.doubleValue());

    }

    @Override
    public float op(float origin) {
        return FastMath.max(origin, num.floatValue());

    }

    @Override
    public IComplexNumber op(IComplexNumber origin) {
        if (origin.absoluteValue().doubleValue() > complexNumber.absoluteValue().doubleValue())
            return origin;
        return complexNumber;
    }

    @Override
    public Op opForDimension(int index, int dimension) {
        if (num != null)
            return new ScalarMin(x.vectorAlongDimension(index, dimension), num);
        else
            return new ScalarMin(x.vectorAlongDimension(index, dimension), complexNumber);
    }

    @Override
    public Op opForDimension(int index, int... dimension) {
        if (num != null)
            return new ScalarMin(x.tensorAlongDimension(index, dimension), num);
        else
            return new ScalarMin(x.tensorAlongDimension(index, dimension), complexNumber);
    }

    @Override
    public void init(INDArray x, INDArray y, INDArray z, long n) {
        super.init(x, y, z, n);
        if (num != null)
            this.extraArgs = new Object[]{num};
        else
            this.extraArgs = new Object[]{complexNumber};

    }
}


text:
puts "What is your first name?"
first_name = gets.chomp
puts "What is your middle name?"
middle_name = gets.chomp
puts "What is your last name?"
last_name = gets.chomp

puts 'Greetings, ' + first_name + ' ' + middle_name + ' ' + last_name + '!'

puts "What is your favorite number?"
fav_num = gets.chomp.to_i
big_num = fav_num + 1
puts "I think " + big_num.to_s + ' is a better and bigger number'

=begin
Link to excercises

Empty Method:
https://github.com/amitzman/phase-0/blob/master/week-4/my_solution.rb

Address:
https://github.com/amitzman/phase-0/blob/master/week-4/address/my_solution.rb

Math:
https://github.com/amitzman/phase-0/blob/master/week-4/math/my_solution.rb

How do you define a local variable?

You define a local variable like the this: my_name = "Alex".  The first character of the variable must be lowercase.

How do you define a method?

You define a method like this:

def method_name (parameter)
  method
end

What is the difference between a local variable and a method?

Local variables store information like strings and can be called upon within the block and can be changed as well.

Methods are things that do something.  For example .to_f will change it to a float.  So we can a variable, num = 5.  Then we can do num.to_f and will change number to 5.0.

How do you run a ruby program from the command line?

You can run a ruby program from the command line by typing "ruby filename.rb"

How do you run an RSpec file from the command line?

You can run an RSpec file from the command line by typing "rspec rpsec_filename.rb".

What was confusing about this material? What made sense?

Nothing was too confusing, except for trying to remember all of the methods.  I thought the methods did make sense, like .upcase makes all the letters in a string uppercase and vice versa with .downcase.

=end


text:
declare function dec(target: Object, propertyKey: string | symbol, parameterIndex: number): void;

export default class {
    method(@dec p: number) {}
}

//// [decoratorOnClassMethodParameter1.es6.js]
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
export default class default_1 {
    method(p) { }
}
__decorate([
    __param(0, dec)
], default_1.prototype, "method", null);


text:
using System;
using Newtonsoft.Json;

namespace RGBPi.Core
{
	[JsonObject]
	public class Host
	{
		public string name;
		public string ip;
		public int port;

		public Host(){
			name = string.Empty;
			ip = string.Empty;
			port = 0;
		}

		public Host(string name, string ip, int port){
			this.name = name;
			this.ip = ip;
			this.port = port;
		}

		public bool IsValid{
			get{
				return !string.IsNullOrWhiteSpace (name) && !string.IsNullOrWhiteSpace (ip) && port > 0;
			}
		}

		public override bool Equals (object obj)
		{
			if(obj != null && obj is Host){
				Host other = (Host)obj;
				return other.name ==this.name || other.ip == this.ip && other.port == this.port;
			}

			return false;
		}

        public override int GetHashCode()
        {
            return base.GetHashCode();
        }

        public override string ToString ()
		{
			return string.Format ("Host: {0} (IP={1}, Port={2})", name, ip, port);
		}
	}
}


text:
var cornerstoneWADOImageLoader = (function ($, cornerstone, cornerstoneWADOImageLoader) {

    "use strict";

    if(cornerstoneWADOImageLoader === undefined) {
        cornerstoneWADOImageLoader = {};
    }

    var canvas = document.createElement('canvas');
    var lastImageIdDrawn = "";

    function arrayBufferToString(buffer) {
        return binaryToString(String.fromCharCode.apply(null, Array.prototype.slice.apply(new Uint8Array(buffer))));
    }

    function binaryToString(binary) {
        var error;

        try {
            return decodeURIComponent(escape(binary));
        } catch (_error) {
            error = _error;
            if (error instanceof URIError) {
                return binary;
            } else {
                throw error;
            }
        }
    }

    function extractStoredPixels(dataSet, byteArray, photometricInterpretation, width, height, frame) {
        canvas.height = height;
        canvas.width = width;

        var planarConfiguration = dataSet.uint16('x00280006');
        var pixelDataElement = dataSet.elements.x7fe00010;
        var pixelDataOffset = pixelDataElement.dataOffset;
        var transferSyntax = dataSet.string('x00020010');
        var samplesPerPixel = dataSet.uint16('x00280002');

        var frameSize = width * height * samplesPerPixel;
        var frameOffset = pixelDataOffset + frame * frameSize;
        var encodedPixelData;
        var context = canvas.getContext('2d');
        var imageData = context.createImageData(width, height);

        var deferred = $.Deferred();

        // this is an exception
        if( (photometricInterpretation === "YBR_FULL_422" || photometricInterpretation === "YBR_FULL") &&
                transferSyntax === "1.2.840.10008.1.2.4.50")
        {
            encodedPixelData = dicomParser.readEncapsulatedPixelData(dataSet, frame);
            // need to read the encapsulated stream here i think
            var imgBlob = new Blob([encodedPixelData], {type: "image/jpeg"});
            var r = new FileReader();
            if(r.readAsBinaryString === undefined) {
                r.readAsArrayBuffer(imgBlob);
            }
            else {
                r.readAsBinaryString(imgBlob); // doesn't work on IE11
            }
            r.onload = function(){
                var img=new Image();
                img.onload = function() {
                    context.drawImage(this, 0, 0);
                    imageData = context.getImageData(0, 0, width, height);
                    deferred.resolve(imageData);
                };
                img.onerror = function(z) {
                    deferred.reject();
                };
                if(r.readAsBinaryString === undefined) {
                    img.src = "data:image/jpeg;base64,"+window.btoa(arrayBufferToString(r.result));
                }
                else {
                    img.src = "data:image/jpeg;base64,"+window.btoa(r.result); // doesn't work on IE11
                }

            };
            return deferred;
        }

        // verify transfer syntax
        if( transferSyntax === "1.2.840.10008.1.2.1") {
            encodedPixelData = new Uint8Array(byteArray.buffer, frameOffset, frameSize);

        } else if ( transferSyntax === "1.2.840.10008.1.2.5" ) {
            planarConfiguration=1;
            var frameData = dicomParser.readEncapsulatedPixelData( dataSet, frame );
            var pixelFormat = cornerstoneWADOImageLoader.getPixelFormat(dataSet);
            encodedPixelData=cornerstoneWADOImageLoader.unRLE( pixelFormat, samplesPerPixel, frameData, width, height);

        } else if ( transferSyntax === "1.2.840.10008.1.2.4.50" ) {
            frameData = dicomParser.readEncapsulatedPixelData( dataSet, frame );
            var jpeg = new JpegImage();
            jpeg.parse( frameData );
            encodedPixelData=jpeg.getData(width, height);

        } else
            throw "no codec for " + photometricInterpretation + " ts=" + transferSyntax;

        // verify photometrci interpretation
        if( photometricInterpretation === "RGB" ) {
            cornerstoneWADOImageLoader.decodeRGB(encodedPixelData, imageData.data, planarConfiguration);

        } else if( photometricInterpretation === "PALETTE COLOR" )  {
            cornerstoneWADOImageLoader.decodePALETTE(encodedPixelData, imageData.data, dataSet );

        }
        else if( photometricInterpretation === "YBR_FULL_422" || photometricInterpretation === "YBR_FULL" ) {
            cornerstoneWADOImageLoader.decodeYBRFull(encodedPixelData, imageData.data, planarConfiguration);

        } else
            throw "no codec for " + photometricInterpretation + " ts=" + transferSyntax;

        deferred.resolve(imageData);
        return deferred;
/*
        if (photometricInterpretation === "RGB" &&
                transferSyntax === "1.2.840.10008.1.2.1")
        {
            encodedPixelData = new Uint8Array(byteArray.buffer, frameOffset, frameSize);
            cornerstoneWADOImageLoader.decodeRGB(encodedPixelData, imageData.data);
            deferred.resolve(imageData);
            return deferred;
        }
        else if( photometricInterpretation === "RGB" &&
                transferSyntax === "1.2.840.10008.1.2.4.50")
        {
            encodedPixelData = dicomParser.readEncapsulatedPixelData( dataSet, frame );
            var jpeg = new JpegImage();
            jpeg.parse( encodedPixelData );
            imageData=jpeg.getData(width, height);
            cornerstoneWADOImageLoader.decodeRGB(encodedPixelData, imageData.data);
            deferred.resolve(imageData);
            return deferred;
        }
        else if (photometricInterpretation === "RGB" &&
                transferSyntax === "1.2.840.10008.1.2.5")
        {
            // RLE
        }
        else if( (photometricInterpretation === "YBR_FULL_422" || photometricInterpretation === "YBR_FULL") &&
                transferSyntax === "1.2.840.10008.1.2.1" )
        {
            encodedPixelData = new Uint8Array(byteArray.buffer, frameOffset, frameSize);
            cornerstoneWADOImageLoader.decodeYBRFull(encodedPixelData, imageData.data, planarConfiguration);
            deferred.resolve(imageData);
            return deferred;
        }
        else if( (photometricInterpretation === "YBR_FULL_422" || photometricInterpretation === "YBR_FULL") &&
                transferSyntax === "1.2.840.10008.1.2.4.50")
        {
            encodedPixelData = dicomParser.readEncapsulatedPixelData(dataSet, frame);
            // need to read the encapsulated stream here i think
            var imgBlob = new Blob([encodedPixelData], {type: "image/jpeg"});
            var r = new FileReader();
            if(r.readAsBinaryString === undefined) {
                r.readAsArrayBuffer(imgBlob);
            }
            else {
                r.readAsBinaryString(imgBlob); // doesn't work on IE11
            }
            r.onload = function(){
                var img=new Image();
                img.onload = function() {
                    context.drawImage(this, 0, 0);
                    imageData = context.getImageData(0, 0, width, height);
                    deferred.resolve(imageData);
                };
                img.onerror = function(z) {
                    deferred.reject();
                };
                if(r.readAsBinaryString === undefined) {
                    img.src = "data:image/jpeg;base64,"+window.btoa(arrayBufferToString(r.result));
                }
                else {
                    img.src = "data:image/jpeg;base64,"+window.btoa(r.result); // doesn't work on IE11
                }

            };
            return deferred;
        }
        else if( (photometricInterpretation === "YBR_FULL_422" || photometricInterpretation === "YBR_FULL") &&
                transferSyntax === "1.2.840.10008.1.2.5" )
        {
            // RLE
        }
        else if( photometricInterpretation === "PALETTE COLOR"
                && transferSyntax === "1.2.840.10008.1.2.1" )
        {
            encodedPixelData = new Uint8Array(byteArray.buffer, frameOffset, frameSize);
            cornerstoneWADOImageLoader.decodePALETTE(encodedPixelData, imageData.data, dataSet );
            deferred.resolve(imageData);
            return deferred;
        }
        else if( photometricInterpretation === "PALETTE COLOR"
                && transferSyntax === "1.2.840.10008.1.2.5" )
        {
            // RLE
        }
*/
    }

    function makeColorImage(imageId, dataSet, byteArray, photometricInterpretation, frame, ovls) {

        // extract the DICOM attributes we need
        var pixelSpacing = cornerstoneWADOImageLoader.getPixelSpacing(dataSet);
        var rows = dataSet.uint16('x00280010');
        var columns = dataSet.uint16('x00280011');
        var rescaleSlopeAndIntercept = cornerstoneWADOImageLoader.getRescaleSlopeAndIntercept(dataSet);
        var bytesPerPixel = 4;
        var numPixels = rows * columns;
        var sizeInBytes = numPixels * bytesPerPixel;
        var windowWidthAndCenter = cornerstoneWADOImageLoader.getWindowWidthAndCenter(dataSet);

        var deferred = $.Deferred();

        // Decompress and decode the pixel data for this image
        var imageDataPromise = extractStoredPixels(dataSet, byteArray, photometricInterpretation, columns, rows, frame);
        imageDataPromise.then(function(imageData) {
            function getPixelData() {
                return imageData.data;
            }

            function getImageData() {
                return imageData;
            }

            function getCanvas() {
                if(lastImageIdDrawn === imageId) {
                    return canvas;
                }

                canvas.height = rows;
                canvas.width = columns;
                var context = canvas.getContext('2d');
                context.putImageData(imageData, 0, 0 );
                lastImageIdDrawn = imageId;
                return canvas;
            }

            // Extract the various attributes we need
            var image = {
                imageId : imageId,
                minPixelValue : 0,
                maxPixelValue : 255,
                slope: rescaleSlopeAndIntercept.slope,
                intercept: rescaleSlopeAndIntercept.intercept,
                windowCenter : windowWidthAndCenter.windowCenter,
                windowWidth : windowWidthAndCenter.windowWidth,
                render: cornerstone.renderColorImage,
                getPixelData: getPixelData,
                getImageData: getImageData,
                getCanvas: getCanvas,
                rows: rows,
                columns: columns,
                height: rows,
                width: columns,
                color: true,
                columnPixelSpacing: pixelSpacing.column,
                rowPixelSpacing: pixelSpacing.row,
                data: dataSet,
                invert: false,
                sizeInBytes: sizeInBytes,
                overlays: ovls
            };

            if(image.windowCenter === undefined) {
                image.windowWidth = 255;
                image.windowCenter = 128;
            }
            deferred.resolve(image);
        }, function() {
            deferred.reject();
        });

        return deferred;
    }

    // module exports
    cornerstoneWADOImageLoader.makeColorImage = makeColorImage;

    return cornerstoneWADOImageLoader;
}($, cornerstone, cornerstoneWADOImageLoader));


text:
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using Microsoft.Win32;

namespace APOD_to_Desktop
{

    class DesktopManager
    {
        const int SPI_SETDESKWALLPAPER = 20;
        const int SPIF_UPDATEINIFILE = 0x01;
        const int SPIF_SENDWININICHANGE = 0x02;

        [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool SystemParametersInfo(uint uiAction, uint uiParam,
            string pvParam, uint fWinIni);

        /// <summary>
        /// Get the current wallpaper image.
        /// </summary>
        public static void Get()
        {
            string wallpaper;
            RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Control Panel\Desktop", true);
            wallpaper = key.GetValue(@"Wallpaper", 0).ToString();

            // Rename to save as possible future option.
            Console.Write(wallpaper);
        }

        /// <summary>
        /// Set the new wallpaper to the APOD.
        /// </summary>
        /// <param name="path">Path of the saved image.</param>
        public static void Set(string path)
        {
            RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Control Panel\Desktop", true);
            string style = Properties.Settings.Default.Style;

            switch (style)
            {
                case "Fill":
                    key.SetValue(@"WallpaperStyle", "10");
                    key.SetValue(@"TileWallpaper", "0");
                    break;
                case "Stretch":
                    key.SetValue(@"WallpaperStyle", "2");
                    key.SetValue(@"TileWallpaper", "0");
                    break;
                case "Tile":
                    key.SetValue(@"WallpaperStyle", "0");
                    key.SetValue(@"TileWallpaper", "1");
                    break;
                case "Center":
                    key.SetValue(@"WallpaperStyle", "0");
                    key.SetValue(@"TileWallpaper", "0");
                    break;
                case "Fit":
                    key.SetValue(@"WallpaperStyle", "6");
                    key.SetValue(@"TileWallpaper", "0");
                    break;
            }

            key.Close();

            // Set the desktop wallpapaer by calling the Win32 API SystemParametersInfo
            // with the SPI_SETDESKWALLPAPER desktop parameter. The changes should
            // persist, and also be immediately visible.
            if (!SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, path,
                SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE))
            {
                throw new Win32Exception();
            }
        }
    }
}


text:
package com.blackducksoftware.integration.hub.detect.workflow.search.result;

import com.blackducksoftware.integration.hub.detect.type.OperatingSystemType;

public class WrongOperatingSystemResult extends FailedDetectorResult {
    private final OperatingSystemType currentOperatingSystem;

    public WrongOperatingSystemResult(final OperatingSystemType currentOperatingSystem) {
        this.currentOperatingSystem = currentOperatingSystem;
    }

    @Override
    public String toDescription() {
        return String.format("Cannot run on %s", currentOperatingSystem.toString());
    }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Trans. Linn. Soc. London 27: 178 (1869)

#### Original name
Graphis submarcescens Leight.

### Remarks
null


text:
package cpsr.model;

import java.util.HashMap;
import java.util.HashSet;

import org.jblas.DoubleMatrix;

import cpsr.environment.DataSet;
import cpsr.environment.TrainingDataSet;
import cpsr.environment.components.Action;
import cpsr.environment.components.ActionObservation;
import cpsr.environment.components.Observation;
import cpsr.model.components.Minf;
import cpsr.model.components.PredictionVector;
import cpsr.model.exceptions.PSRRuntimeException;
import cpsr.stats.PSRObserver;

public class MemorylessState extends APSR {

	private static final long serialVersionUID = -2790344407555914392L;

	Observation lastOb;
	/**
	 * Constructor initializes PSR of specified psrType with DataSet
	 *
	 * @param data The DataSet which the PSR is used to model.
	 * @param maxHistoryLength Max history length.
	 */
	public MemorylessState(TrainingDataSet data)
	{
		super(data);
		DoubleMatrix initVec = new DoubleMatrix(1,1);
		initVec.put(0,0, -1);
		initialPv = new PredictionVector(initVec);
	}

	@Override
	public void build()
	{
		performBuild();
		isBuilt = true;
	}

	/* (non-Javadoc)
	 * @see cpsr.model.IPSR#isBuilt()
	 */
	@Override
	public boolean isBuilt()
	{
		return isBuilt;
	}

	/* (non-Javadoc)
	 * @see cpsr.model.IPSR#getDataSet()
	 */
	@Override
	public DataSet getDataSet()
	{
		return trainData;
	}

	public void update()
	{
		performUpdate();
	}

	/* (non-Javadoc)
	 * @see cpsr.model.IPSR#update(cpsr.environment.components.ActionObservation)
	 */
	@Override
	public void update(ActionObservation ao)
	{
		lastOb = ao.getObservation();
	}

	/* (non-Javadoc)
	 * @see cpsr.model.IPSR#resetToStartState()
	 */
	@Override
	public void resetToStartState()
	{
		lastOb = null;
	}

	/* (non-Javadoc)
	 * @see cpsr.model.IPSR#getActionSet()
	 */
	@Override
	public HashSet<Action> getActionSet()
	{
		return this.trainData.getActionSet();
	}

	/**
	 * Returns deep copy of prediction vector.
	 *
	 * @return Deep copy of prediction vector.
	 */
	public PredictionVector getPredictionVector()
	{
		if(lastOb == null)
		{
			return initialPv;
		}
		else
		{
			DoubleMatrix obVec = new DoubleMatrix(1,1);
			obVec.put(0,0, lastOb.getID());
			return new PredictionVector(obVec);
		}
	}

	/**
	 * Returns reference to Minf parameter.
	 *
	 * @return Reference to Minf parameter.
	 */
	public Minf getMinf()
	{
		return null;
	}

	/**
	 * Returns reference to specified Mao parameter matrix.
	 *
	 * @param actob The action observation pair used to specify the Mao.
	 * @return The specified Mao parameter matrix.
	 * @throws PSRRuntimeException
	 */
	public DoubleMatrix getAOMat(ActionObservation actob) throws PSRRuntimeException
	{
		return null;
	}

	/**
	 * Returns hash map of Mao parameters.
	 *
	 * @return Hash map of Mao parameters.
	 */
	public HashMap<ActionObservation, DoubleMatrix> getAOMats()
	{
		return null;
	}
	@Override
	public void addPSRObserver(PSRObserver observer) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void performBuild() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void performUpdate() {
		// TODO Auto-generated method stub

	}

}


text:
package de.tor.tribes.util;

/*Source: http://www.koders.com/java/fid1182C9330FDC66A60312A33932E82F09B5C4CA9F.aspx?s=graph
  @author OpenJGraph
 */
import java.awt.*;
import java.awt.geom.FlatteningPathIterator;
import java.awt.geom.GeneralPath;
import java.awt.geom.Line2D;
import java.awt.geom.PathIterator;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * The Intersection class provides methods for determining
 * the intersection point of two lines and the intersection
 * point of a line and a GeneralPath object.
 *
 * @author        Jesus M. Salvo Jr.
 */
public class Intersection {

    /**
     * Log4J Category. The name of the category is the fully qualified name of the
     * enclosing class.
     */
    static Logger logger = LogManager.getLogger(Intersection.class);

    /**
     * Returns the intersection point of two lines.
     *
     * @param   line1   First line
     * @param   line2   Second line
     * @return  The Point object where the two lines intersect. This method
     * returns null if the two lines do not intersect.
     * @throws  <tt>MultipleIntersectionException</tt> when the two lines
     * have more than one intersection point.
     */
    static public Point getIntersection(Line2D line1, Line2D line2)
            throws Exception {
        double dyline1, dxline1;
        double dyline2, dxline2, e, f;
        double x1line1, y1line1, x2line1, y2line1;
        double x1line2, y1line2, x2line2, y2line2;

        if (!line1.intersectsLine(line2)) {
            return null;
        }

        /* first, check to see if the segments intersect by parameterization
        on s and t; if s and t are both between [0,1], then the
        segments intersect */
        x1line1 =  line1.getX1();
        y1line1 =  line1.getY1();
        x2line1 =  line1.getX2();
        y2line1 =  line1.getY2();

        x1line2 =  line2.getX1();
        y1line2 =  line2.getY1();
        x2line2 =  line2.getX2();
        y2line2 =  line2.getY2();

        /* check to see if the segments have any endpoints in common. If they do,
        then return the endpoints as the intersection point */
        if ((x1line1 == x1line2) && (y1line1 == y1line2)) {
            return (new Point((int) x1line1, (int) y1line1));
        }
        if ((x1line1 == x2line2) && (y1line1 == y2line2)) {
            return (new Point((int) x1line1, (int) y1line1));
        }
        if ((x2line1 == x1line2) && (y2line1 == y1line2)) {
            return (new Point((int) x2line1, (int) y2line1));
        }
        if ((x2line1 == x2line2) && (y2line1 == y2line2)) {
            return (new Point((int) x2line1, (int) y2line1));
        }

        dyline1 = -(y2line1 - y1line1);
        dxline1 = x2line1 - x1line1;

        dyline2 = -(y2line2 - y1line2);
        dxline2 = x2line2 - x1line2;

        e = -(dyline1 * x1line1) - (dxline1 * y1line1);
        f = -(dyline2 * x1line2) - (dxline2 * y1line2);

        /* compute the intersection point using
        ax+by+e = 0 and cx+dy+f = 0

        If there is more than 1 intersection point between two lines,
         */
        if ((dyline1 * dxline2 - dyline2 * dxline1) == 0) {
            throw new Exception("ZERO!");
        }
        return (new Point(
                (int) (-(e * dxline2 - dxline1 * f) / (dyline1 * dxline2 - dyline2 * dxline1)),
                (int) (-(dyline1 * f - dyline2 * e) / (dyline1 * dxline2 - dyline2 * dxline1))));
    }

    /**
     * Returns the intersection point of a line and a GeneralPath. Given that
     * a line can intersect more than one segment of a GeneralPath, this method
     * will return the intersection point of the first segment, returned by
     * a PathIterator, and the line. No consideration is taken if the line
     * intersects more than one segment of the GeneralPath since this is internally
     * used by salvo.jesus.graph.VisualEdge wherein the edge of a line
     * will intersect only one segment of the VisualVertex's GeneralPath.
     *
     * @param   line   First line
     * @param   path    GeneralPath representing line segments
     * @return  The Point object where the line and the GeneralPath object intersect.
     * This method returns null if they do not intersect.
     */
    static public Point getIntersection(Line2D line, GeneralPath path) {
        Line2D.Double rectline = new Line2D.Double();
        Point intersectpoint = null;
        Point testintersectpoint = null;
        Point previousintersectpoint;
        Point lineorigin = new Point((int) line.getX1(), (int) line.getY1());
        FlatteningPathIterator pathiterator;
        double coords[] = new double[6];
        int segmenttype;
        double prevx = -1, prevy = -1;

        // Iterate through the segments
        pathiterator = new FlatteningPathIterator(path.getPathIterator(null), 1.0);
        while (!pathiterator.isDone()) {
            segmenttype = pathiterator.currentSegment(coords);
            // Since we are are iterating through a GeneralPath, all segments
            // are guaranteed to be a line.
            switch (segmenttype) {
                case PathIterator.SEG_MOVETO:
                    prevx = coords[0];
                    prevy = coords[1];
                    break;
                case PathIterator.SEG_QUADTO:
                case PathIterator.SEG_CUBICTO:
                case PathIterator.SEG_LINETO:
                    // If prevx or prev = -1, then we do not have an initial SEG_MOVETO yet.
                    // Therefore, the if block does not get executed and the coordinates
                    // are treated as if it were a SEG_MOVETO.
                    if (prevx != -1 && prevy != 1) {
                        // Check if the line segment intersects with the line in the argument
                        rectline.setLine(prevx, prevy, coords[0], coords[1]);

                        // Workaround at the moment
                        try {
                            testintersectpoint = getIntersection(line, rectline);
                        } catch (Exception ex) {
                            logger.error("Multiple Intersections Detected", ex);
                            testintersectpoint = null;
                        }

                        if (testintersectpoint != null) {
                            previousintersectpoint = intersectpoint;
                            intersectpoint = testintersectpoint;
                            // Yes, the line segment intersects with the line, but does it have
                            // a shorter distance to the line in the argument, so assign the
                            // variable intersectpoint to this intersection point.

                            // However, if the new intersection point is farther away from
                            // the origin of the line than that of the previous intersection point,
                            // revert the intersect point back to the previous intereection point.
                            if (previousintersectpoint != null
                                    && (lineorigin.distance(intersectpoint) > lineorigin.distance(previousintersectpoint))) {
                                intersectpoint = previousintersectpoint;
                            }
                        }
                    }
                    prevx = coords[0];
                    prevy = coords[1];
                    break;
            }
            pathiterator.next();
        }
        return intersectpoint;
    }
}


text:
namespace SmartConnect.Web.ViewModels.Account
{
    using System;
    using System.ComponentModel.DataAnnotations;
    using System.Web;

    public class RegisterUserViewModel
    {
        [Required]
        [Display(Name = "First name")]
        public string FirstName { get; set; }

        [Required]
        [Display(Name = "Last name")]
        public string LastName { get; set; }

        [Required]
        [Display(Name = "Date of birth")]
        public DateTime DateOfBirth { get; set; }

        [Display(Name = "Profile picture")]
        public HttpPostedFileBase ProfilePicture { get; set; }

        [Required]
        public string Country { get; set; }

        [Required]
        [Display(Name = "Username")]
        public string UserName { get; set; }

        [Required]
        [EmailAddress]
        [Display(Name = "Email")]
        public string Email { get; set; }

        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }
    }
}


text:
SYSCONF_DIR := /etc
INIT_DIR := init.d
INSTALL_DIR := /usr/sbin

all:

install:
	mkdir -p $(DESTDIR)/$(SYSCONF_DIR)/wifish
	mkdir -p $(DESTDIR)/$(SYSCONF_DIR)/wifish/networks
	mkdir -p $(DESTDIR)/$(INSTALL_DIR)/
	cp ressources/wifish.conf $(DESTDIR)/$(SYSCONF_DIR)/wifish/
	cp ressources/init/wifishd $(DESTDIR)/$(SYSCONF_DIR)/$(INIT_DIR)/wifishd
	cp -r ressources/templates $(DESTDIR)/$(SYSCONF_DIR)/wifish/
	chmod 644 $(DESTDIR)/$(SYSCONF_DIR)/wifish/wifish.conf
	chmod 644 $(DESTDIR)/$(SYSCONF_DIR)/wifish/templates/*
	cat src/wifish-common.sh src/wifish-cfg.sh > $(DESTDIR)/$(INSTALL_DIR)/wifish-cfg
	cat src/wifish-common.sh src/wifishd.sh > $(DESTDIR)/$(INSTALL_DIR)/wifishd
	cp src/wifish $(DESTDIR)/$(INSTALL_DIR)/wifish
	sed -i "s|^DEFAULT_CONFIG_FILE.*|DEFAULT_CONFIG_FILE='$(SYSCONF_DIR)/wifish/wifish.conf'|" $(DESTDIR)/$(INSTALL_DIR)/wifish-cfg $(DESTDIR)/$(INSTALL_DIR)/wifishd $(DESTDIR)/$(SYSCONF_DIR)/$(INIT_DIR)/wifishd
	sed -i "s|^TEMPLATES_DIR.*|TEMPLATES_DIR='$(SYSCONF_DIR)/wifish/templates/'|" $(DESTDIR)/$(SYSCONF_DIR)/wifish/wifish.conf
	sed -i "s|^USER_NETWORK_DIR.*|USER_NETWORK_DIR='$(SYSCONF_DIR)/wifish/networks/'|" $(DESTDIR)/$(SYSCONF_DIR)/wifish/wifish.conf
	chmod 755 $(DESTDIR)/$(INSTALL_DIR)/wifish-cfg $(DESTDIR)/$(INSTALL_DIR)/wifishd $(DESTDIR)/$(INSTALL_DIR)/wifish $(DESTDIR)/$(SYSCONF_DIR)/$(INIT_DIR)/wifishd


text:
package org.hunter.a361camera.util;

import android.graphics.PointF;
import android.graphics.Rect;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.params.MeteringRectangle;
import android.util.SparseIntArray;
import android.view.Surface;

public class CameraUtil {
    private static final String TAG = "CameraUtil";

    private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
    private static final int MAX_PREVIEW_WIDTH = 1920;
    private static final int MAX_PREVIEW_HEIGHT = 1080;

    private static final MeteringRectangle[] ZERO_WEIGHT_3A_REGION = new MeteringRectangle[]{
            new MeteringRectangle(0, 0, 0, 0, 0)};

    static {
        ORIENTATIONS.append(Surface.ROTATION_0, 90);
        ORIENTATIONS.append(Surface.ROTATION_90, 0);
        ORIENTATIONS.append(Surface.ROTATION_180, 270);
        ORIENTATIONS.append(Surface.ROTATION_270, 180);
    }

    private CameraUtil() {

    }

    private static float calculateFullSizeAspectRatio(CameraCharacteristics characteristics) {
        Rect activeArraySize =
                characteristics.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE);
        return ((float) (activeArraySize.width())) / activeArraySize.height();
    }

    public static int getJPEGOrientation(int rotation, int sensorOrientation) {
        // Sensor orientation is 90 for most devices, or 270 for some devices (eg. Nexus 5X)
        // We have to take that into account and rotate JPEG properly.
        // For devices with orientation of 90, we simply return our mapping from ORIENTATIONS.
        // For devices with orientation of 270, we need to rotate the JPEG 180 degrees.
        return (ORIENTATIONS.get(rotation) + sensorOrientation + 270) % 360;
    }

    public static int getJPEGOrientation(int rotation, CameraCharacteristics cameraCharacteristics) {
        Integer sensorOrientation = cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
        sensorOrientation = sensorOrientation == null ? 0 : sensorOrientation;
        // Sensor orientation is 90 for most devices, or 270 for some devices (eg. Nexus 5X)
        // We have to take that into account and rotate JPEG properly.
        // For devices with orientation of 90, we simply return our mapping from ORIENTATIONS.
        // For devices with orientation of 270, we need to rotate the JPEG 180 degrees.
        return (ORIENTATIONS.get(rotation) + sensorOrientation + 270) % 360;
    }

    public static PointF normalizedSensorCoordsForNormalizedDisplayCoords(
            float nx, float ny, int sensorOrientation) {
        switch (sensorOrientation) {
            case 0:
                return new PointF(nx, ny);
            case 90:
                return new PointF(ny, 1.0f - nx);
            case 180:
                return new PointF(1.0f - nx, 1.0f - ny);
            case 270:
                return new PointF(1.0f - ny, nx);
            default:
                return null;
        }
    }

    /**
     * Clamps x to between min and max (inclusive on both ends, x = min --> min,
     * x = max --> max).
     */
    public static int clamp(int x, int min, int max) {
        if (x > max) {
            return max;
        }
        if (x < min) {
            return min;
        }
        return x;
    }
}


text:
'use strict';

define(['angular', 'require'], function(angular, require) {
  return angular.module('portal.help.controllers', [])
    .controller('SessionInfoController', [
      '$log', '$scope', 'portalAboutService', 'SERVICE_LOC',
      function($log, $scope, portalAboutService, SERVICE_LOC) {
        portalAboutService.getFrameDetails()
          .then(function(result) {
            $scope.frameInfo = result;
            return result;
          }).catch(function() {
          $log.warn('issue getting frame details');
        });

        $scope.appInfo = null;
        if (SERVICE_LOC.aboutURL) {
          portalAboutService.getDetails(SERVICE_LOC.aboutURL)
            .then(function(result) {
              $scope.appInfo = result;
              return result;
            }).catch(function() {
            $log.warn('issue getting app info');
          });
        }
      }]);
});


text:
from __future__ import division
from builtins import str
from builtins import range
from past.utils import old_div
import re
from math import log10

import ROOT
from array import array
from PyAnalysisTools.base import InvalidInputError, _logger

def rebin(histograms, factor=None, disable_bin_width_division=False):
    """
    Rebin a histogram. Can be either symmetric, i.e. just merging X bins, or asymmetric
    :param histograms: hists to be rebinned
    :type histograms: list, dict, TH1
    :param factor: rebin factor. If integer a symmetric rebinning will be performed, if a list of bin boarders are
    provided an asymmetric rebinning will be performed
    :type factor: int, list
    :param disable_bin_width_division: disable division by bin width for asymmetric binning
    :return: rebinned hists
    :rtype: type(hists), i.e. list, dict, TH1
    """
    if factor is None or factor == 1:
        return histograms
    if type(histograms) == dict:
        for key, hist in list(histograms.items()):
            if issubclass(hist.__class__, ROOT.TH1):
                histograms[key] = _rebin_hist(hist, factor)
            elif isinstance(hist, list):
                histograms[key] = [_rebin_hist(h, factor) for h in hist]
            else:
                raise InvalidInputError('Invalid binning: ' + str(factor))
    elif isinstance(histograms, list):
        histograms = [_rebin_hist(h, factor) for h in histograms]
    else:
        histograms = _rebin_hist(histograms, factor, disable_bin_width_division)
    return histograms

def _rebin_hist(hist, factor, disable_bin_width_division=False):
    if type(factor) is int:
        hist = _rebin_1d_hist(hist, factor)
    elif type(factor) == list:
        binning = array('d', factor)
        _logger.debug('rebin histogram %s asymmetrically' % (hist.GetName()))
        hist = __rebin_asymmetric_1d_hist(hist, len(factor), binning, disable_bin_width_division)
    else:
        raise InvalidInputError('Invalid binning: ' + str(factor))
    return hist

def _parse_y_title(hist):
    binning = None
    y_title = hist.GetYaxis().GetTitle()
    try:
        binning = float(re.findall('[0-9].+', y_title)[0])
    except IndexError:
        try:
            binning = int(re.findall('[0-9]+', y_title)[0])
        except IndexError:
            pass
    return binning

def _rebin_1d_hist(hist, factor):
    y_title = hist.GetYaxis().GetTitle()
    if not factor:
        return
    try:
        try:
            binning = float(re.findall('[0-9].+', y_title)[0])
        except ValueError:
            binning = int(re.findall('[0-9]+', y_title)[0])
        y_title = y_title.replace(str(binning), str(binning * factor))
    except (IndexError, KeyError):
        pass
    hist.GetYaxis().SetTitle(y_title)
    ROOT.SetOwnership(hist, True)
    return hist.Rebin(factor)

def __rebin_asymmetric_1d_hist(hist, n_bins, bins, disable_bin_width_division=False):
    binning = _parse_y_title(hist)
    if binning is not None:
        hist.GetYaxis().SetTitle(hist.GetYaxis().GetTitle() + ' x %i' % n_bins)

    if disable_bin_width_division:
        return hist.Rebin(n_bins - 1, hist.GetName(), bins)

    htmp = hist.Rebin(n_bins - 1, hist.GetName(), bins)
    for b in range(htmp.GetNbinsX() + 2):
        htmp.SetBinContent(b, htmp.GetBinContent(b) / htmp.GetBinWidth(b))
        htmp.SetBinError(b, htmp.GetBinError(b) / htmp.GetBinWidth(b))
    return htmp

def __rebin_asymmetric_2d_hist(hist, n_binsx, bins_x):
    hist.GetYaxis().SetTitle(+ '{:s} x {:d}'.format(hist.GetYaxis().GetTitle(), n_binsx))
    return hist.Rebin(n_binsx - 1, hist.GetName(), bins_x)

def merge_overflow_bins(hists, x_max=None, y_max=None):
    """
    Merge overflow bins
    :param hists: hists for which merging should be applied
    :type hists: dict, list, TH1
    :param x_max: optional parameter to perform merging from a given x-value
    :type x_max: float
    :param y_max: optional parameter to perform merging from a given y-value (2D hists only)
    :type y_max: float
    :return: nothing
    :rtype: None
    """
    if type(hists) == dict:
        for item in list(hists.values()):
            if isinstance(item, list):
                for i in item:
                    _merge_overflow_bins_1d(i, x_max)
            else:
                _merge_overflow_bins_1d(item, x_max)
    else:
        if isinstance(hists, ROOT.TH2):
            _merge_overflow_bins_2d(hists, x_max, y_max)
        else:
            _merge_overflow_bins_1d(hists, x_max)

def _merge_overflow_bins_1d(hist, x_max=None):
    if isinstance(hist, ROOT.TH2):
        return
    if x_max is not None:
        last_visible_bin = hist.FindBin(x_max)
    else:
        last_visible_bin = hist.GetNbinsX()
    hist.SetBinContent(last_visible_bin, hist.Integral(last_visible_bin, -1))
    for b in range(last_visible_bin+1, hist.GetNbinsX()+2):
        hist.SetBinContent(b, 0)

def _merge_overflow_bins_2d(hist, x_max=None, y_max=None):
    if x_max:
        last_visible_bin_x = hist.GetXaxis().FindBin(x_max)
    else:
        last_visible_bin_x = hist.GetNbinsX()
    if y_max:
        last_visible_bin_y = hist.GetYaxis().FindBin(y_max)
    else:
        last_visible_bin_y = hist.GetNbinsY()
    for i in range(hist.GetXaxis().GetNbins()):
        hist.SetBinContent(i+1, last_visible_bin_y, hist.Integral(i + 1, i + 1, last_visible_bin_y, -1))
    for i in range(hist.GetYaxis().GetNbins()):
        hist.SetBinContent(last_visible_bin_x, i + 1, hist.Integral(last_visible_bin_x, -1, i + 1, i + 1))

def merge_underflow_bins(hists, x_min=None):
    """
    Merge underflow bins
    :param hists: hists for which merging should be applied
    :type hists: dict, list, TH1
    :param x_min: optional parameter to perform merging up to a given x-value
    :type x_min: float
    :return: nothing
    :rtype: None
    """
    if type(hists) == dict:
        for item in list(hists.values()):
            if isinstance(item, list):
                for i in item:
                    _merge_underflow_bins_1d(i, x_min)
            else:
                _merge_underflow_bins_1d(item, x_min)
    else:
        _merge_underflow_bins_1d(hists, x_min)

def _merge_underflow_bins_1d(hist, x_min=None):
    if isinstance(hist, ROOT.TH2):
        return
    if x_min:
        first_visible_bin = hist.FindBin(x_min)
    else:
        first_visible_bin = 1
    hist.SetBinContent(first_visible_bin, hist.Integral(0, first_visible_bin))

def scale(hist, weight):
    """
    Wrapper around TH1::Scale. Scales each bin content by weight
    :param hist: histogram
    :type hist: TH1
    :param weight: scale factor
    :type weight: float
    :return: nothing
    :rtype: None
    """
    hist.Scale(weight)

def normalise(hists, integration_range=None, norm_scale=1.):
    """
    Wrapper for normalisation of histograms to a given scale in a given interval
    :param hists: histograms
    :type hists: list of dictionary of histograms
    :param integration_range: range in which integration should be performed (default fill range)
    :type integration_range: list (default: None)
    :param norm_scale: normalisation scale (default 1.)
    :type norm_scale: float
    :return: nothing
    :rtype: None
    """
    if integration_range is None:
        integration_range = [-1, -1]
    if type(hists) == dict:
        for h in list(hists.keys()):
            hists[h] = normalise_hist(hists[h], integration_range, norm_scale)
    elif type(hists) == list:
        for h in hists:
            h = normalise_hist(h, integration_range, norm_scale)
    else:
        hists = normalise_hist(hists, integration_range, norm_scale)

def normalise_hist(hist, integration_range=[-1, -1], norm_scale=1.):
    """
    Perform histogram normalisation
    :param hist: single histogram
    :type hist: TH1
    :param integration_range: range in which integration should be performed (default fill range)
    :type integration_range: list (default: None)
    :param norm_scale: normalisation scale (default 1.)
    :type norm_scale: float
    :return: nothing
    :rtype: None
    """
    if isinstance(hist, ROOT.TH2):
        return _normalise_2d_hist(hist, integration_range, norm_scale)
    if isinstance(hist, ROOT.TH1):
        return _normalise_1d_hist(hist, integration_range, norm_scale)

def has_asymmetric_binning(hist):
    """
    Check if graph object has asymmetric x-binning
    :param hist: histogram
    :type hist: TH1
    :return: true/false on asymmetric binning
    :rtype: bool
    """
    return len(set([hist.GetBinWidth(b) for b in range(hist.GetNbinsX() + 1)])) > 1

def _normalise_1d_hist(hist, integration_range=[-1, -1], norm_scale=1.):
    if isinstance(hist, ROOT.THStack):
        return hist
    integral = hist.Integral(*integration_range)
    if integral == 0:
        return hist
    hist.Scale(old_div(norm_scale, integral))
    return hist

def _normalise_2d_hist(hist, integration_range=[-1, -1], norm_scale=1.):
    _logger.error("Normalisation of 2D histograms not implemented, yet. Open a jira ticket if needed.")
    return hist

def read_bin_from_label(hist, label):
    labels = [hist.GetXaxis().GetBinLabel(i) for i in range(hist.GetNbinsX() + 1)]
    matched_labels = [l for l in labels if re.search(label, l) is not None]
    if len(matched_labels) == 0:
        _logger.error("Could not find label matching {:s} in {:s}".format(label, hist.GetName()))
        return None
    if len(matched_labels) > 1:
        _logger.warning("Found multiple matches for label {:s} in {:s}".format(label, hist.GetName()))
    return labels.index(matched_labels[0])

def get_colors(hists):
    """
    Get colors of plotted objects from draw option
    :param hists: histograms
    :type hists: list
    :return: list of colors
    :rtype: list
    """
    def get_color(hist):
        draw_option = hist.GetDrawOption()
        if isinstance(hist, ROOT.TEfficiency):
            return max(hist.GetPaintedGraph().GetLineColor(), hist.GetPaintedGraph().GetMarkerColor())
        if "hist" in draw_option.lower():
            return hist.GetLineColor()
    return [get_color(hist) for hist in hists]

def set_axis_labels(obj, plot_config):
    """
    Set bin labels for x axis
    :param obj: plot object
    :type obj: TH1, TGraph
    :param plot_config: plot configuration
    :type plot_config: PlotConfig
    :return: nothing
    :rtype: None
    """
    if plot_config.axis_labels is None:
        return
    for b, label in enumerate(plot_config.axis_labels):
        obj.GetXaxis().SetBinLabel(b + 1, label)

def get_log_scale_x_bins(nbins, xmin, xmax):
    """
    Calculate bin boarders for equidistant bins for log scale x-axis binning
    :param nbins: number of bins
    :type nbins: int
    :param xmin: minimum of x-axis
    :type xmin: float
    :param xmax: maximum of x-axis
    :type xmax: float
    :return: binning
    :rtype:
    """
    log_min = log10(xmin)
    log_max = log10(xmax)
    bin_width = old_div((log_max - log_min), int(nbins))
    return [pow(10, log_min + i * bin_width) for i in range(0, int(nbins) + 1)]

def check_name(name):
    """
    Checks name for problematic characters and replaces them
    :param name: object name
    :type name: str
    :return: converted name
    :rtype: str
    """
    name = name.replace('>', '_geq_')
    name = name.replace('<', '_leq_')
    name = name.replace('=', '_eq_')
    return name


text:
package org.codehaus.jremoting.itests.stubs;

import org.codehaus.jremoting.server.servicehandlers.ServiceHandler;
import org.codehaus.jremoting.server.Publisher;
import org.codehaus.jremoting.server.Publication;
import org.codehaus.jremoting.requests.InvokeMethod;
import org.codehaus.jremoting.itests.TestFacade;
import org.codehaus.jremoting.itests.TestFacade2;
import org.codehaus.jremoting.itests.TestFacade3;
import org.codehaus.jremoting.itests.CustomSerializableParam;

import java.util.Map;
import java.util.HashMap;
import java.lang.reflect.InvocationTargetException;
import java.beans.PropertyVetoException;
import java.io.IOException;

public class HandCraftedServiceHandler extends ServiceHandler {

        Map<String, Execr> map = new HashMap<String, Execr>();

        public HandCraftedServiceHandler(Publisher publisher, String publishedThing, Publication publicationDescription, Class facadeClass) {
            super(publisher, publishedThing, publicationDescription, facadeClass);

            map.put("hashCode()", new HashCode());
            map.put("testSpeed()", new TestSpeed());
            map.put("hello(java.lang.String)", new Hello());
            map.put("intParamReturningInt(int)", new IntParam());
            map.put("shortParamThatMayReturnBoolOrThrow(short)", new ShortParam());
            map.put("floatAndDoubleParamsReturningStrungBuffer(float, double)", new FloatAnd());
            map.put("makeTestFacade2Or3(java.lang.String)", new MakeTest());
            map.put("morphName(org.codehaus.jremoting.itests.TestFacade2)", new Morph());
            map.put("findTestFacade2ByName(java.lang.String)", new FindTest());
            map.put("setName(java.lang.String)", new SetName());
            map.put("getTestFacade2s()", new GetTest());
            map.put("getName()", new GetName());
            map.put("getTestObjects()", new GetTestObjects());
            map.put("changeTestObjectNames()", new ChgTestObjs());
            map.put("makeNewTestObjectNames()", new MakeNew());
            map.put("toString()", new ToString());
            map.put("ping()", new Ping());
            map.put("byteArrayParamReturningByte(byte, [B)", new ByteArray());
            map.put("throwSpecialException(int)", new ThrowSpecial());
            map.put("testLong(long)", new TestLong());
            map.put("equals(java.lang.Object)", new Equals());
            map.put("testCustomSerializableParameter(org.codehaus.jremoting.itests.CustomSerializableParam)", new TestCustom());
        }

        protected boolean isFacadeMethodSignature(String methodSignature) {
            return map.containsKey(methodSignature);
        }

        protected Object invokeFacadeMethod(InvokeMethod request, String methodSignature, Object instance) throws InvocationTargetException {
            Object[] args = request.getArgs();
            try {
                return map.get(methodSignature).exec(instance, args);
            } catch (RuntimeException e) {
                throw new InvocationTargetException(e);
            } catch (Error e) {
                throw new InvocationTargetException(e);
            }
        }

        abstract static class Execr {
            abstract Object exec(Object target, Object[] args) throws InvocationTargetException;
        }

        private static class HashCode extends Execr {
            Object exec(Object target, Object[] args) {
                return (target).hashCode();
            }
        }

        private static class TestSpeed extends Execr {
            Object exec(Object target, Object[] args) {
                ((TestFacade)target).testSpeed();
                return null;
            }
        }

        private static class Hello extends Execr {
            Object exec(Object target, Object[] args) {
                ((TestFacade)target).hello((String) args[0]);
                return null;
            }
        }

        private static class IntParam extends Execr {
            Object exec(Object target, Object[] args) {
                return ((TestFacade)target).intParamReturningInt((Integer) args[0]);
            }
        }

        private static class ShortParam extends Execr {
            Object exec(Object target, Object[] args) throws InvocationTargetException {
                try {
                    return ((TestFacade)target).shortParamThatMayReturnBoolOrThrow((Short) args[0]);
                } catch (PropertyVetoException e) {
                    throw new InvocationTargetException(e);
                } catch (IOException e) {
                    throw new InvocationTargetException(e);
                }
            }
        }

        private static class FloatAnd extends Execr {
            Object exec(Object target, Object[] args) {
                return ((TestFacade)target).floatAndDoubleParamsReturningStrungBuffer((Float) args[0], (Double) args[1]);
            }
        }

        private static class MakeTest extends Execr {
            Object exec(Object target, Object[] args) {
                return ((TestFacade)target).makeTestFacade2Or3((String) args[0]);
            }
        }

        private static class Morph extends Execr {
            Object exec(Object target, Object[] args) {
                ((TestFacade)target).morphName((TestFacade2) args[0]);
                return null;
            }
        }

        private static class FindTest extends Execr {
            Object exec(Object target, Object[] args) {
                return ((TestFacade)target).findTestFacade2ByName((String) args[0]);

            }
        }

        private static class SetName extends Execr {
            Object exec(Object target, Object[] args) {
                ((TestFacade2) target).setName((String) args[0]);
                return null;
            }
        }

        private static class GetTest extends Execr {
            Object exec(Object target, Object[] args) {
                return ((TestFacade)target).getTestFacade2s();
            }
        }

        private static class GetName extends Execr {
            Object exec(Object target, Object[] args) {
                return ((TestFacade2) target).getName();
            }
        }

        private static class GetTestObjects extends Execr {
            Object exec(Object target, Object[] args) {
                return ((TestFacade)target).getTestObjects();
            }
        }

        private static class ChgTestObjs extends Execr {
            Object exec(Object target, Object[] args) {
                ((TestFacade)target).changeTestObjectNames();
                return null;
            }
        }

        private static class MakeNew extends Execr {
            Object exec(Object target, Object[] args) {
                ((TestFacade)target).makeNewTestObjectNames();
                return null;
            }
        }

        private static class ToString extends Execr {
            Object exec(Object target, Object[] args) {
                String s = (target).toString();
                return s;
            }
        }

        private static class Ping extends Execr {
            Object exec(Object target, Object[] args) {
                ((TestFacade)target).ping();
                return null;
            }
        }

        private static class ByteArray extends Execr {
            Object exec(Object target, Object[] args) {
                return ((TestFacade)target).byteArrayParamReturningByte((Byte) args[0], (byte[]) args[1]);
            }
        }

        private static class ThrowSpecial extends Execr {
            Object exec(Object target, Object[] args) {
                ((TestFacade)target).throwSpecialException((Integer) args[0]);
                return null;
            }
        }

        private static class TestLong extends Execr {
            Object exec(Object target, Object[] args) {
                ((TestFacade)target).testLong((Long) args[0]);
                return null;
            }
        }

        private static class Equals extends Execr {
            Object exec(Object target, Object[] args) {
                if (target instanceof TestFacade) {
                    return (target).equals(args[0]);
                } else if (target instanceof TestFacade3) {
                    return ((TestFacade3) target).equals(args[0]);
                } else {
                    return ((TestFacade2) target).equals(args[0]);
                }
            }
        }

        private static class TestCustom extends Execr {
            Object exec(Object target, Object[] args) {
                return ((TestFacade)target).testCustomSerializableParameter((CustomSerializableParam) args[0]);
            }
        }
    }


text:
<?php declare(strict_types=1);

namespace Aircury\IDEConfiguration\Util;

class ComposerLockHelper
{
    private $contents = [];

    public function __construct(string $projectRootDir)
    {
        $composerLockPath = $projectRootDir . '/composer.lock';

        if (!file_exists($composerLockPath)) {
            return;
        }

        $this->contents = json_decode(file_get_contents($composerLockPath), true);
    }

    public function hasPackage(string $packageName): bool
    {
        foreach (array_merge($this->contents['packages'] ?? [], $this->contents['packages-dev'] ?? []) as $package) {
            if ($package['name'] === $packageName) {
                return true;
            }
        }

        return false;
    }

    public function getPackageVersion(string $packageName): string
    {
        foreach (array_merge($this->contents['packages'] ?? [], $this->contents['packages-dev'] ?? []) as $package) {
            if ($package['name'] === $packageName) {
                $version = $package['version'];

                if ('v' === ($firstCharacter = substr($version, 0, 1))) {
                    return substr($version, 1);
                }

                return is_numeric($firstCharacter) ? $version : '';
            }
        }

        return '';
    }
}


text:
//package com.github.onsdigital.json.taxonomy;
//
//import java.net.URI;
//
///**
// *
// * Holds name and uri of any data item to be referenced from taxonomy home pages
// *
// */
//public class DataItemLink {
//	public String name;
//	public URI uri;
//
//	public DataItemLink(String name, URI uri) {
//		this.name = name;
//		this.uri = uri;
//	}
// }


text:
package com.android.build.gradle.internal.test.report;

import static org.gradle.api.tasks.testing.TestResult.ResultType;

import java.util.ArrayList;
import java.util.List;

/**
 * Custom test result based on Gradle's TestResult
 */
class TestResult extends TestResultModel implements Comparable<TestResult> {

    private final long duration;
    private final String device;
    private final String project;
    private final String flavor;
    final ClassTestResults classResults;
    final List<TestFailure> failures = new ArrayList<TestFailure>();
    final String name;
    private boolean ignored;

    public TestResult(String name, long duration, String device, String project, String flavor,
                      ClassTestResults classResults) {
        this.name = name;
        this.duration = duration;
        this.device = device;
        this.project = project;
        this.flavor = flavor;
        this.classResults = classResults;
    }

    public Object getId() {
        return name;
    }

    public String getName() {
        return name;
    }

    public String getDevice() {
        return device;
    }

    public String getProject() {
        return project;
    }

    public String getFlavor() {
        return flavor;
    }

    @Override
    public String getTitle() {
        return String.format("Test %s", name);
    }

    @Override
    public ResultType getResultType() {
        if (ignored) {
            return ResultType.SKIPPED;
        }
        return failures.isEmpty() ? ResultType.SUCCESS : ResultType.FAILURE;
    }

    @Override
    public long getDuration() {
        return duration;
    }

    @Override
    public String getFormattedDuration() {
        return ignored ? "-" : super.getFormattedDuration();
    }

    public ClassTestResults getClassResults() {
        return classResults;
    }

    public List<TestFailure> getFailures() {
        return failures;
    }

    public void addFailure(String message, String stackTrace,
                           String deviceName, String projectName, String flavorName) {
        classResults.failed(this, deviceName, projectName, flavorName);
        failures.add(new TestFailure(message, stackTrace, null));
    }

    public void ignored() {
        ignored = true;
    }

    @Override
    public int compareTo(TestResult testResult) {
        int diff = classResults.getName().compareTo(testResult.classResults.getName());
        if (diff != 0) {
            return diff;
        }

        diff = name.compareTo(testResult.name);
        if (diff != 0) {
            return diff;
        }

        diff = device.compareTo(testResult.device);
        if (diff != 0) {
            return diff;
        }

        diff = flavor.compareTo(testResult.flavor);
        if (diff != 0) {
            return diff;
        }

        Integer thisIdentity = System.identityHashCode(this);
        int otherIdentity = System.identityHashCode(testResult);
        return thisIdentity.compareTo(otherIdentity);
    }

    public static class TestFailure {
        private final String message;
        private final String stackTrace;
        private final String exceptionType;

        public TestFailure(String message, String stackTrace, String exceptionType) {
            this.message = message;
            this.stackTrace = stackTrace;
            this.exceptionType = exceptionType;
        }

        public String getMessage() {
            return message;
        }

        public String getStackTrace() {
            return stackTrace;
        }

        public String getExceptionType() {
            return exceptionType;
        }
    }

}