text:
[![Bower version](https://img.shields.io/bower/v/angular-computed.svg?style=flat-square)](http://bower.io/)

Computed properties allow to produce efficient and elegant properties that are a result of some calculation dependent on other properties. With **$computed** you get an easy way to define them using pattern similar to Angular's Dependency Injection. Here are some advantages:

- property computation is executed just once after input change
- property computation is executed just once even if property is used in multiple places
- property computation can make use of promises (e.g. compute property via API call)
- views are simplified with `{{ prop }}` instead of `{{ computeProp() }}`
- computed properties are visually separated in controller code
- definition syntax is consistent with core Angular concepts

Internally, **$computed** is very simple and mostly based on Angular's `$watch`. It's just a tiny, clean pattern implementation.

## Usage

First off, add **angular-computed.js** file to your project. You can download it from [here](https://raw.githubusercontent.com/karolsluszniak/angular-computed/master/angular-computed.js) or require bower `angular-computed` package.

Then, add `cloudless.computed` as your app's dependency:

```js
var app = angular.module('app', ['cloudless.computed']);
```

**$computed** works both with `controller as` syntax introduced in Angular 1.2 and with explicit `$scope` injected into controllers, services etc.

### With `controller as`

Here's how to declare a computed property when you use `controller as`:

```js
app.controller('AppCtrl', ['$computed', function($computed) {
  // Input variables
  this.a     = 15;
  this.b     = 32;
  this.const = 1;

  // Computed property
  $computed(this, 'sum', ['a', 'b', function(a, b) {
    // You can still use *this* inside computing function
    return a + b + this.const;
  }]);
}]);
```

Then, you can use it in your view like this:

```html
<div ng-controller="AppCtrl as app">
  <p>The sum is: {{ app.sum }}</p>
</div>
```

### With `$scope`

Here's how to declare a computed property when you use `$scope` injection:

```js
app.controller('AppCtrl', ['$scope', function($scope) {
  // Input variables
  $scope.a     = 15;
  $scope.b     = 32;
  $scope.const = 1;

  // Computed property
  $scope.$computed('sum', ['a', 'b', function(a, b) {
    // Here, *this* refers to your scope
    return a + b + this.const;
  }]);
}]);
```

Then, you can use it in your view like this:

```html
<div ng-controller="AppCtrl">
  <p>The sum is: {{ sum }}</p>
</div>
```

### Defining dependencies

You can provide dependencies as strings with property names:

```js
$computed(this, 'sum', ['a', 'b', computeFunc]);
```

Or, if you need more control, as functions:

```js
this.nested = { num: 31 };
var local = 49;

$computed(this, 'sum', [
  function() { return this.nested.num; },
  function() { return local; },
  computeFunc]);
```

Guessing dependencies from function signature, like Angular's DI, is not supported. It would not work after minification and could create ugly bugs in your code.

### Computing the property

Compute function gets called when any of its dependencies change. It takes all dependencies as arguments and should return new property value:

```js
$computed(scope, 'descriptionIsLong', ['description', function(description) {
  return (description.length > 100);
}]);
```

You can also return a promise from your compute function. This, for instance, makes it possible to use AJAX calls to compute your properties:

```js
$computed(scope, 'userName', ['userId', function(userId) {
  return $http.get('/users/' + userId).then(function(response) {
    return response.data.firstName + ' ' + response.data.lastName;
  });
}]);
```

**$computed** protects your async properties against race conditions. If input changes again before previous promise was resolved, the value returned by that previous promise will never get assigned to the property anymore.

Your `then()` callbacks will still execute, but there's a way to avoid it - by using a special `$valid` function injected for your convenience by **$computed**:

```js
$computed(scope, 'userName', ['userId', function(userId, $valid) {
  return $http.get('/users/' + userId).then(function(response) {
    if ($valid()) {
      // imagine here a code you don't want to process for old promises
      scope.userChangeCount += 1;
    }

    return response.data.firstName + ' ' + response.data.lastName;
  });
}]);
```

### Dependency chain

You can add computed properties that are dependent on other computed properties. In fact, this is where the pattern implemented by **$computed** really starts to shine with its performance benefits.

```js
app.controller('AppCtrl', ['$computed', function($computed) {
  // Input variables
  this.a = 15;
  this.b = 32;

  // Computed property
  $computed(this, 'sum', ['a', 'b', function(a, b) {
    return a + b;
  }]);

  // Other computed property
  $computed(this, 'sumPow', ['sum', function(sum) {
    return Math.pow(sum, 2);
  }]);
}]);
```

Imagine something like this happens later in controller lifecycle:

```js
this.a = this.a + 1;
this.b = this.b - 1;
```

The `sum` property will be recomputed due to input change but its result will not change and thus the `sumPow` property will not have to be recomputed. Neat, isn't it?

### Manual recalculation

You may wish to recompute previously defined property on demand, even if none of its dependencies have changed. You can do so like this:

```js
$computed(this, 'prop').touch();
```

You could even define a computed property without dependencies and have it computed automatically only once, on scope initialization, and recompute it on demand afterwards. This is not a primary application of **$computed**, but this behavior may prove useful at some point.

## Contributing

1. Fork it (https://github.com/karolsluszniak/angular-computed/fork)
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request


text:
package com.baidu.rigel.biplatform.queryrouter.queryplugin.plugins.common.jdbc;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.baidu.rigel.biplatform.ac.query.data.impl.SqlDataSourceInfo;
import com.baidu.rigel.biplatform.ac.query.model.ConfigQuestionModel;
import com.baidu.rigel.biplatform.ac.query.model.QuestionModel;
import com.baidu.rigel.biplatform.queryrouter.queryplugin.plugins.common.QuestionModel4TableDataUtils;
import com.baidu.rigel.biplatform.queryrouter.queryplugin.plugins.common.jdbc.parsecheck.TableExistCheckService;
import com.baidu.rigel.biplatform.queryrouter.queryplugin.plugins.model.QuestionModelTransformationException;
import com.baidu.rigel.biplatform.queryrouter.queryplugin.plugins.model.SqlColumn;
import com.baidu.rigel.biplatform.queryrouter.queryplugin.plugins.model.SqlExpression;

/**
 *
 * JdbcQuestionModelUtil的转换类
 *
 * @author luowenlei
 *
 */
@Service("jdbcQuestionModelUtil")
@Scope("prototype")
public class JdbcQuestionModelUtil {

    /**
     * TableExistCheck
     */
    @Resource(name = "tableExistCheckService")
    private TableExistCheckService tableExistCheckService;

    /**
     * convertQuestionModel2Sql
     *
     * @param questionModel
     *            questionModel
     * @return String sql str
     */
    public SqlExpression convertQuestionModel2Sql(QuestionModel questionModel, String tableName)
            throws QuestionModelTransformationException {
        ConfigQuestionModel configQuestionModel = (ConfigQuestionModel) questionModel;
        questionModel.setUseIndex(false);
        Map<String, SqlColumn> allColums = QuestionModel4TableDataUtils.getAllCubeColumns(questionModel);
        List<SqlColumn> needColums = QuestionModel4TableDataUtils.getNeedColumns(questionModel);
        SqlDataSourceInfo sqlDataSource = (SqlDataSourceInfo) configQuestionModel
                .getDataSourceInfo();
        SqlExpression sqlExpression = new SqlExpression(sqlDataSource.getDataBase().getDriver());
        sqlExpression.setTableName(tableName);
        sqlExpression.generateSql(configQuestionModel, allColums, needColums);
        return sqlExpression;
    }

}

redpajama_set_name: RedPajamaGithub


text:
/*
 * 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.
 */
package io.prestosql.spi.eventlistener;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

public class StageCpuDistribution
{
    private final int stageId;
    private final int tasks;
    private final long p25;
    private final long p50;
    private final long p75;
    private final long p90;
    private final long p95;
    private final long p99;
    private final long min;
    private final long max;
    private final long total;
    private final double average;

    @JsonCreator
    public StageCpuDistribution(
            @JsonProperty("stageId") int stageId,
            @JsonProperty("tasks") int tasks,
            @JsonProperty("p25") long p25,
            @JsonProperty("p50") long p50,
            @JsonProperty("p75") long p75,
            @JsonProperty("p90") long p90,
            @JsonProperty("p95") long p95,
            @JsonProperty("p99") long p99,
            @JsonProperty("min") long min,
            @JsonProperty("max") long max,
            @JsonProperty("total") long total,
            @JsonProperty("average") double average)
    {
        this.stageId = stageId;
        this.tasks = tasks;
        this.p25 = p25;
        this.p50 = p50;
        this.p75 = p75;
        this.p90 = p90;
        this.p95 = p95;
        this.p99 = p99;
        this.min = min;
        this.max = max;
        this.total = total;
        this.average = average;
    }

    @JsonProperty
    public int getStageId()
    {
        return stageId;
    }

    @JsonProperty
    public int getTasks()
    {
        return tasks;
    }

    @JsonProperty
    public long getP25()
    {
        return p25;
    }

    @JsonProperty
    public long getP50()
    {
        return p50;
    }

    @JsonProperty
    public long getP75()
    {
        return p75;
    }

    @JsonProperty
    public long getP90()
    {
        return p90;
    }

    @JsonProperty
    public long getP95()
    {
        return p95;
    }

    @JsonProperty
    public long getP99()
    {
        return p99;
    }

    @JsonProperty
    public long getMin()
    {
        return min;
    }

    @JsonProperty
    public long getMax()
    {
        return max;
    }

    @JsonProperty
    public long getTotal()
    {
        return total;
    }

    @JsonProperty
    public double getAverage()
    {
        return average;
    }
}


text:
var path = require('path')
var { parse: parseCookie } = require('cookie')

module.exports = {
  // Webpack aliases
  aliases: {
    quasar: path.resolve(__dirname, '../node_modules/quasar-framework/'),
    src: path.resolve(__dirname, '../src'),
    assets: path.resolve(__dirname, '../src/assets'),
    components: path.resolve(__dirname, '../src/components'),
    pages: path.resolve(__dirname, '../src/pages'),
    layouts: path.resolve(__dirname, '../src/layouts'),
    directives: path.resolve(__dirname, '../src/directives')
  },

  // Progress Bar Webpack plugin format
  // https://github.com/clessg/progress-bar-webpack-plugin#options
  progressFormat: ' [:bar] ' + ':percent'.bold + ' (:msg)',

  // Default theme to build with ('ios' or 'mat')
  defaultTheme: 'mat',

  build: {
    env: require('./prod.env'),
    index: path.resolve(__dirname, '../dist/index.html'),
    publicPath: '',
    productionSourceMap: false,
    // Gzip off by default as many popular static hosts such as
    // Surge or Netlify already gzip all static assets for you.
    // Before setting to `true`, make sure to:
    // npm install --save-dev compression-webpack-plugin
    productionGzip: false,
    productionGzipExtensions: ['js', 'css']
  },
  dev: {
    env: require('./dev.env'),
    cssSourceMap: true,
    // auto open browser or not
    openBrowser: false,
    publicPath: '/',
    port: 8080,

    // If for example you are using Quasar Play
    // to generate a QR code then on each dev (re)compilation
    // you need to avoid clearing out the console, so set this
    // to "false", otherwise you can set it to "true" to always
    // have only the messages regarding your last (re)compilation.
    clearConsoleOnRebuild: false,

    // Proxy your API if using any.
    // Also see /build/script.dev.js and search for "proxy api requests"
    // https://github.com/chimurai/http-proxy-middleware
    proxyTable: {

      // proxy to symfony api backend
      '/api': {
        target: require('./dev.backends').api,
        changeOrigin: true
      },

      // proxy directly to the nodejs chat backend
      '/foodsharing/socket': {
        target: require('./dev.backends').chat,
        changeOrigin: true,
        ws: true,
        pathRewrite: {
          '^/': '/socket.io/'
        },
        onProxyReq: (proxyReq, req, res) => {
          // the chat server will use the PHP session to identify us
          // unless we remove the cookie, we should just care about the django cookie
          removeCookie(proxyReq, req, 'PHPSESSID');
        }
      },

      // TODO: limit this to just login... /xhrapp.php?app=login&m=loginsubmit
      '/fs': {
        target: require('./dev.backends').foodsharing,
        changeOrigin: true,
        pathRewrite: {
          '^/fs': ''
        }
      }

    }
  }
}

/*
 * proxyTable example:
 *
   proxyTable: {
      // proxy all requests starting with /api
      '/api': {
        target: 'https://some.address.com/api',
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      }
    }
 */

function removeCookie(proxyReq, req, cookieName) {
  let { cookie: cookieVal } = req.headers;
  if (cookieVal) {
    let cookie = parseCookie(cookieVal);
    if (cookie[cookieName]) {
      delete cookie[cookieName];
      proxyReq.setHeader('cookie', serializeCookieObject(cookie));
    }
  }
}

// https://gist.github.com/project-pp/18c81c02b9c9a6f89a7f7bcf815bf1d6
function serializeCookieObject(o) {
  return Object.keys(o).reduce((a, k) => a.concat([k, o[k]].map(encodeURI).join('=')), []).join(';');
}


text:
package lang

import (
	"fmt"
	"os"

	gm "github.com/getgauge/gauge-proto/go/gauge_messages"
	"github.com/getgauge/gauge/config"
	"github.com/getgauge/gauge/logger"
	"github.com/getgauge/gauge/manifest"
	"github.com/getgauge/gauge/runner"
	"github.com/getgauge/gauge/util"
	"github.com/sourcegraph/go-langserver/pkg/lsp"
)

type langRunner struct {
	lspID  string
	runner *runner.GrpcRunner
}

var lRunner langRunner

var recommendedExtensions = map[string]string{
	"java":   "vscjava.vscode-java-pack",
	"dotnet": "ms-dotnettools.csharp",
	"python": "ms-python.python",
	"ruby":   "rebornix.ruby",
}

func startRunner() error {
	var err = connectToRunner()
	if err != nil {
		var installMessage = ""
		m, e := manifest.ProjectManifest()
		if e == nil {
			installMessage = fmt.Sprintf(" Install '%s' extension for code insights.", recommendedExtensions[m.Language])
		}
		errStr := "Gauge could not initialize.%s For more information see" +
			"[Problems](command:workbench.actions.view.problems), check logs." +
			"[Troubleshooting](https://docs.gauge.org/troubleshooting.html?language=javascript&ide=vscode#gauge-could-not-initialize-for-more-information-see-problems)"
		return fmt.Errorf(errStr, installMessage)
	}
	return nil
}

func connectToRunner() error {
	logInfo(nil, "Starting language runner")
	outFile, err := util.OpenFile(logger.ActiveLogFile)
	if err != nil {
		return err
	}
	err = os.Setenv("GAUGE_LSP_GRPC", "true")
	if err != nil {
		return err
	}
	manifest, err := manifest.ProjectManifest()
	if err != nil {
		return err
	}

	lRunner.runner, err = runner.StartGrpcRunner(manifest, outFile, outFile, config.IdeRequestTimeout(), false)
	return err
}

func cacheFileOnRunner(uri lsp.DocumentURI, text string, isClosed bool, status gm.CacheFileRequest_FileStatus) error {
	r := &gm.Message{
		MessageType: gm.Message_CacheFileRequest,
		CacheFileRequest: &gm.CacheFileRequest{
			Content:  text,
			FilePath: string(util.ConvertURItoFilePath(uri)),
			IsClosed: false,
			Status:   status,
		},
	}
	_, err := lRunner.runner.ExecuteMessageWithTimeout(r)
	return err
}

func globPatternRequest() (*gm.ImplementationFileGlobPatternResponse, error) {
	implFileGlobPatternRequest := &gm.Message{MessageType: gm.Message_ImplementationFileGlobPatternRequest, ImplementationFileGlobPatternRequest: &gm.ImplementationFileGlobPatternRequest{}}
	response, err := lRunner.runner.ExecuteMessageWithTimeout(implFileGlobPatternRequest)
	if err != nil {
		return nil, err
	}
	return response.GetImplementationFileGlobPatternResponse(), nil
}

func getStepPositionResponse(uri lsp.DocumentURI) (*gm.StepPositionsResponse, error) {
	stepPositionsRequest := &gm.Message{MessageType: gm.Message_StepPositionsRequest, StepPositionsRequest: &gm.StepPositionsRequest{FilePath: util.ConvertURItoFilePath(uri)}}
	response, err := lRunner.runner.ExecuteMessageWithTimeout(stepPositionsRequest)
	if err != nil {
		return nil, fmt.Errorf("error while connecting to runner : %s", err)
	}
	if response.GetStepPositionsResponse().GetError() != "" {
		return nil, fmt.Errorf("error while connecting to runner : %s", response.GetStepPositionsResponse().GetError())
	}
	return response.GetStepPositionsResponse(), nil
}

func getImplementationFileList() (*gm.ImplementationFileListResponse, error) {
	implementationFileListRequest := &gm.Message{MessageType: gm.Message_ImplementationFileListRequest}
	response, err := lRunner.runner.ExecuteMessageWithTimeout(implementationFileListRequest)
	if err != nil {
		return nil, fmt.Errorf("error while connecting to runner : %s", err.Error())
	}
	return response.GetImplementationFileListResponse(), nil
}

func getStepNameResponse(stepValue string) (*gm.StepNameResponse, error) {
	stepNameRequest := &gm.Message{MessageType: gm.Message_StepNameRequest, StepNameRequest: &gm.StepNameRequest{StepValue: stepValue}}
	response, err := lRunner.runner.ExecuteMessageWithTimeout(stepNameRequest)
	if err != nil {
		return nil, fmt.Errorf("error while connecting to runner : %s", err)
	}
	return response.GetStepNameResponse(), nil
}

func putStubImplementation(filePath string, codes []string) (*gm.FileDiff, error) {
	stubImplementationCodeRequest := &gm.Message{
		MessageType: gm.Message_StubImplementationCodeRequest,
		StubImplementationCodeRequest: &gm.StubImplementationCodeRequest{
			ImplementationFilePath: filePath,
			Codes:                  codes,
		},
	}
	response, err := lRunner.runner.ExecuteMessageWithTimeout(stubImplementationCodeRequest)
	if err != nil {
		return nil, fmt.Errorf("error while connecting to runner : %s", err.Error())
	}
	return response.GetFileDiff(), nil
}

func getAllStepsResponse() (*gm.StepNamesResponse, error) {
	getAllStepsRequest := &gm.Message{MessageType: gm.Message_StepNamesRequest, StepNamesRequest: &gm.StepNamesRequest{}}
	response, err := lRunner.runner.ExecuteMessageWithTimeout(getAllStepsRequest)
	if err != nil {
		return nil, fmt.Errorf("error while connecting to runner : %s", err.Error())
	}
	return response.GetStepNamesResponse(), nil
}

func killRunner() error {
	if lRunner.runner != nil {
		return lRunner.runner.Kill()
	}
	return nil
}

func getLanguageIdentifier() (string, error) {
	m, err := manifest.ProjectManifest()
	if err != nil {
		return "", err
	}
	info, err := runner.GetRunnerInfo(m.Language)
	if err != nil {
		return "", err
	}
	return info.LspLangId, nil
}


text:
namespace chromeos {

// A fake implementation of ImageLoaderClient. This class does nothing.
class CHROMEOS_EXPORT FakeImageLoaderClient : public ImageLoaderClient {
 public:
  FakeImageLoaderClient() {}
  ~FakeImageLoaderClient() override {}

  // DBusClient ovveride.
  void Init(dbus::Bus* dbus) override {}

  // ImageLoaderClient override:
  void RegisterComponent(const std::string& name,
                         const std::string& version,
                         const std::string& component_folder_abs_path,
                         const BoolDBusMethodCallback& callback) override;

 private:
  DISALLOW_COPY_AND_ASSIGN(FakeImageLoaderClient);
};

}  // namespace chromeos

#endif  // CHROMEOS_DBUS_FAKE_IMAGE_LOADER_CLIENT_H_


text:
package org.apache.taverna.workbench.ui.servicepanel.tree;

import static org.apache.taverna.workbench.icons.WorkbenchIcons.folderClosedIcon;
import static org.apache.taverna.workbench.icons.WorkbenchIcons.folderOpenIcon;

import java.awt.Component;

import javax.swing.JTree;
import javax.swing.tree.DefaultTreeCellRenderer;

@SuppressWarnings("serial")
public class FilterTreeCellRenderer extends DefaultTreeCellRenderer {
	private Filter filter = null;

	@Override
	public Component getTreeCellRendererComponent(JTree tree, Object value,
			boolean sel, boolean expanded, boolean leaf, int row,
			boolean hasFocus) {

		super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf,
				row, hasFocus);
		Filter filter = getFilter();
		if (filter != null)
			setText(filter.filterRepresentation(getText()));
		if (expanded)
			setIcon(folderOpenIcon);
		else
			setIcon(folderClosedIcon);
		return this;
	}

	public Filter getFilter() {
		return filter;
	}

	public void setFilter(Filter currentFilter) {
		this.filter = currentFilter;
	}
}


text:
<?php

namespace NoreSources;

/**
 * An object that can be compared to another.
 */
interface ComparableInterface
{

	/**
	 * Compare instance with another Comparable.
	 *
	 *
	 * @throws NotComparableException:: This method MUST throw NotComparableException if $value
	 *         cannot be compared to instance.
	 * @param mixed $value
	 *        	Value to compare to instance.
	 *
	 * @return integer One of
	 *

	 *
< 0 If instance value is less than $value

	 *
0 if instance and $value are equal

	 *
> 0 if instance value is greater than $value

	 *

	 *         The meaning of "less", "equal" and "greater" depends on class value type.
	 */
	public function compare($value);
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<module xmlns="urn:jboss:module:1.1" name="org.bouncycastle.ext">
  <resources>
    <resource-root path="bcpg-jdk15on-1.52.jar" />
  </resources>
  <dependencies>
    <module name="javax.api" />
    <module name="org.bouncycastle" />
  </dependencies>
</module>


text:
import * as ts from 'typescript';

import {NgDecorator, getAngularDecorators} from '../../utils/ng_decorators';
import {getPropertyNameText} from '../../utils/typescript/property_name';

export interface ResolvedNgModule {
  name: string;
  node: ts.ClassDeclaration;
  decorator: NgDecorator;
  providersExpr: ts.Expression|null;
}

/**
 * Visitor that walks through specified TypeScript nodes and collects all
 * found NgModule definitions.
 */
export class NgModuleCollector {
  resolvedModules: ResolvedNgModule[] = [];

  constructor(public typeChecker: ts.TypeChecker) {}

  visitNode(node: ts.Node) {
    if (ts.isClassDeclaration(node)) {
      this.visitClassDeclaration(node);
    }

    ts.forEachChild(node, n => this.visitNode(n));
  }

  private visitClassDeclaration(node: ts.ClassDeclaration) {
    if (!node.decorators || !node.decorators.length) {
      return;
    }

    const ngDecorators = getAngularDecorators(this.typeChecker, node.decorators);
    const ngModuleDecorator = ngDecorators.find(({name}) => name === 'NgModule');

    if (ngModuleDecorator) {
      this._visitNgModuleClass(node, ngModuleDecorator);
    }
  }

  private _visitNgModuleClass(node: ts.ClassDeclaration, decorator: NgDecorator) {
    const decoratorCall = decorator.node.expression;
    const metadata = decoratorCall.arguments[0];

    if (!metadata || !ts.isObjectLiteralExpression(metadata)) {
      return;
    }

    const providersNode = metadata.properties.filter(ts.isPropertyAssignment)
                              .find(p => getPropertyNameText(p.name) === 'providers');
    this.resolvedModules.push({
      name: node.name ? node.name.text : 'default',
      node,
      decorator,
      providersExpr: providersNode !== undefined ? providersNode.initializer : null,
    });
  }
}


text:
numpy.random.multivariate_normal
================================

.. currentmodule:: numpy.random

.. autofunction:: multivariate_normal


text:
package com.gemstone.gemfire.management;

import com.gemstone.gemfire.cache.DiskStore;

/**
 * MBean that provides access to information and management functionality for a
 * {@link DiskStore}.
 *
 * @author rishim
 * @since 7.0
 *
 */
public interface DiskStoreMXBean {

  /**
   * Returns the name of the DiskStore.
   */
  public String getName();

  /**
   * Returns whether disk files are to be automatically compacted.
   *
   * @return True if disk files are automatically compacted, false otherwise
   */
  public boolean isAutoCompact();

  /**
   * Returns the threshold at which an op-log may be compacted. Until it
   * reaches this threshold the op-log will not be compacted. The threshold is
   * a percentage in the range 0..100.
   */
  public int getCompactionThreshold();

  /**
   * Returns whether manual compaction of disk files is allowed.
   *
   * @return True if manual compaction is allowed, false otherwise.
   */
  public boolean isForceCompactionAllowed();

  /**
   * Returns the maximum size (in megabytes) that a single op-log can grow to.
   */
  public long getMaxOpLogSize();

  /**
   * Returns the time (in milliseconds) that can elapse before unwritten
   * data is saved to disk.
   */
  public long getTimeInterval();

  /**
   * Returns the size of the write buffer that this DiskStore will use when
   * writing data to disk.
   */
  public int getWriteBufferSize();

  /**
   * Returns the names of the directories to which the region's data will be
   * written.
   */
  public String[] getDiskDirectories();

  /**
   * Returns the maximum number of operations that can be asynchronously
   * queued for saving to disk. When this limit is reached operations
   * will block until they can be put in the queue.
   */
  public int getQueueSize();

  /**
   * Returns the total number of bytes of space this DiskStore has used.
   */
  public long getTotalBytesOnDisk();

  /**
   * Returns the average latency of disk reads in nanoseconds Its the average
   * latency required to read a byte from disk.
   *
   * Each entry in region has some overhead in terms of number of extra bytes
   * while persisting data. So this rate won't match the number of bytes put in
   * all regions.This is rate of actual bytes system is persisting.
   */
  public float getDiskReadsRate();

  /**
   * Returns the average latency of disk writes in nanoseconds. Its the average
   * latency required to write a byte to disk.
   *
   * Each entry in region has some overhead in terms of number of extra bytes
   * while persisting data. So this rate won't match the number of bytes put in
   * all regions. This is rate of actual bytes system is persisting.
   */
  public float getDiskWritesRate();

  /**
   * Returns the disk reads average latency in nanoseconds. It depicts average
   * time needed to read one byte of data from disk.
   */
  public long getDiskReadsAvgLatency();

  /**
   * Returns the disk writes average latency in nanoseconds. It depicts average
   * time needed to write one byte of data to disk.
   */
  public long getDiskWritesAvgLatency();

  /**
   * Returns the flush time average latency.
   */
  public long getFlushTimeAvgLatency();

  /**
   * Returns the number of entries in the asynchronous queue waiting to be written
   * to disk.
   */
  public int getTotalQueueSize();

  /**
   * Returns the number of backups currently in progress on this DiskStore.
   */
  public int getTotalBackupInProgress();

  /**
   * Returns the number of backups of this DiskStore that have been completed.
   */
  public int getTotalBackupCompleted();

  /**
   * Returns the number of persistent regions currently being recovered from disk.
   */
  public int getTotalRecoveriesInProgress();

  /**
   * Requests the DiskStore to start writing to a new op-log. The old oplog will
   * be asynchronously compressed if compaction is set to true. The new op-log will
   * be created in the next available directory with free space. If there is no
   * directory with free space available and compaction is set to false, then a
   * DiskAccessException saying that the disk is full will be thrown. If
   * compaction is true then the application will wait for the other op-logs to
   * be compacted and additional space is available.
   */
  public void forceRoll();

  /**
   * Requests the DiskStore to start compacting. The compaction is done even if
   * automatic compaction is not configured. If the current, active op-log has
   * had data written to it, and may be compacted, then an implicit  call to
   * forceRoll will be made so that the active op-log can be compacted. This
   * method will block until compaction finishes.
   *
   * @return True if one or more op-logs were compacted or false to indicate
   *         that no op-logs were ready to be compacted or that a compaction was
   *         already in progress.
   */
  public boolean forceCompaction();

  /**
   * Causes any data that is currently in the asynchronous queue to be written
   * to disk. Does not return until the flush is complete.
   */
  public void flush();

}


text:
package de.bytefish.jtinycsvparser.tokenizer.decorator;

import de.bytefish.jtinycsvparser.tokenizer.ITokenizer;
import de.bytefish.jtinycsvparser.tokenizer.fixed.ColumnDefinition;
import de.bytefish.jtinycsvparser.tokenizer.fixed.FixedLengthTokenizer;
import org.junit.Assert;
import org.junit.Test;

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

public class ProcessingTokenizerDecoratorTest {

    @Test
    public void testFixedLengthTokenizer_TokenizeLine() {

        List<ColumnDefinition> columnDefinition = new ArrayList<>();

        columnDefinition.add(new ColumnDefinition(0, 10));
        columnDefinition.add(new ColumnDefinition(10, 20));

        String input = " Philipp   Wagner   ";

        // The Tokenizer to wrap:
        ITokenizer tokenizer = new FixedLengthTokenizer(columnDefinition);
        // Define Pre- and Postprocessors:
        StringPreprocessor preprocessor = new StringPreprocessor(s -> s.toUpperCase());
        StringPostprocessor postprocessor = new StringPostprocessor(s -> s.trim());
        // Decorate the Tokenizer:
        ITokenizer decoratedTokenizer = new ProcessingTokenizerDecorator(tokenizer, preprocessor, postprocessor);

        String[] result = decoratedTokenizer.tokenize(input);

        Assert.assertNotNull(result);
        Assert.assertEquals(2, result.length);
        Assert.assertEquals("PHILIPP", result[0]);
        Assert.assertEquals("WAGNER", result[1]);
    }
}


text:
WarpWallet Verification
=======================

Java WarpWallet(https://keybase.io/warp) verification project. I put this together to independently verify that the calculations being done by WarpWallet matched both SCrypt and PBKDF2 algorithms.

Compiling
=========

`gradle build`

Usage
=====
`java -jar warpwallet-verify.jar <password> [salt]`
Example: `java -jar warpwallet-verify.jar test test@test.com`

Output:
```
Password: test
Salt: test@test.com
SCrypt Result: 5405ac36f5e9b59914d2b53311984c9ea6330faa384f7078c8be7bbc2f3896d8
PBKDF2 Result: 0b342e09cdb609cd4bc39a9815df5bf870fab98cd4bd94418d977f35691002b4
Private Key  : 5f31823f385fbc545f112fab04471766d6c9b626ecf2e439452904894628946c
Private Key Encoded : 5JYDAkj6icvkXuKSnFAveGZzGyAteMuufvUhMkje8Z1dA8cshjS
```

License
=======

Apache 2.0

Attributions
=============
This project utilizes the following libraries under the following licenses:
+ Apache Commons Collections (Apache 2.0)
+ github.com/wg/scrypt (Apache 2.0)
+ JUnit (BSD)


text:
const i = 0;

function appLogic(cs, ds)
{
    // console.log("TODO: whitelist me");
    // params["TODO: don't inline me"];
    i; // References a const symbol to inline.
}

var tc = new TestClass();
tc.forward("fancyStage", appLogic, {});


text:
.class Lcom/android/server/tv/TvInputHardwareManager$1;
.super Landroid/content/BroadcastReceiver;
.source "TvInputHardwareManager.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/server/tv/TvInputHardwareManager;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/android/server/tv/TvInputHardwareManager;

# direct methods
.method constructor <init>(Lcom/android/server/tv/TvInputHardwareManager;)V
    .locals 0

    .prologue
    .line 99
    iput-object p1, p0, Lcom/android/server/tv/TvInputHardwareManager$1;->this$0:Lcom/android/server/tv/TvInputHardwareManager;

    invoke-direct {p0}, Landroid/content/BroadcastReceiver;-><init>()V

    return-void
.end method

# virtual methods
.method public onReceive(Landroid/content/Context;Landroid/content/Intent;)V
    .locals 1
    .param p1, "context"    # Landroid/content/Context;
    .param p2, "intent"    # Landroid/content/Intent;

    .prologue
    .line 102
    iget-object v0, p0, Lcom/android/server/tv/TvInputHardwareManager$1;->this$0:Lcom/android/server/tv/TvInputHardwareManager;

    # invokes: Lcom/android/server/tv/TvInputHardwareManager;->handleVolumeChange(Landroid/content/Context;Landroid/content/Intent;)V
    invoke-static {v0, p1, p2}, Lcom/android/server/tv/TvInputHardwareManager;->access$300(Lcom/android/server/tv/TvInputHardwareManager;Landroid/content/Context;Landroid/content/Intent;)V

    .line 103
    return-void
.end method


text:
module VagrantPlugins
  module GuestNetBSD
    module Cap
      class MountNFSFolder
        def self.mount_nfs_folder(machine, ip, folders)
          folders.each do |name, opts|
            machine.communicate.sudo("mkdir -p #{opts[:guestpath]}")
            machine.communicate.sudo("/sbin/mount -t nfs '#{ip}:#{opts[:hostpath]}' '#{opts[:guestpath]}'")
          end
        end
      end
    end
  end
end


text:
var util = require('util');
var http = require('http');
var urllib = require('url');

var conf = require('./npm-proxy.config.json');

var internalNpm = urllib.parse(conf.internalNpm);
var publicNpm = urllib.parse(conf.publicNpm);

var fwdProxy = false;
if ( conf.fwdProxy )
  fwdProxy = urllib.parse(conf.fwdProxy);

var server = http.createServer(request);

if ( conf.listenHost )
{
  console.log('Listening on',conf.listenHost+":"+conf.listenPort);
  server.listen(conf.listenHost, conf.listenPort);
}
else
{
  console.log('Listening on port', conf.listenPort);
  server.listen(conf.listenPort);
}

console.log('Internal:', urllib.format(internalNpm));
console.log('Public:', urllib.format(publicNpm));
if ( fwdProxy )
  console.log('Proxy:', urllib.format(fwdProxy));

function request(req, res)
{
  var body = '';

  req.on('data', function(chunk) {
    body += chunk;
  });

  req.on('end', function() {
    internalRequest(req, body, res);
  });
}

function internalRequest(req, body, res)
{
  var opt = {
    method: req.method,
    path: internalNpm.path.replace(/\/$/,'')+req.url,
    headers: req.headers,
    host: internalNpm.hostname,
    port: internalNpm.port
  }

  opt.headers.host = internalNpm.hostname+":"+internalNpm.port;
  delete opt.headers['cookie'];

  console.log('Checking internal NPM:', util.inspect(opt));

  var internal = http.request(opt, done);

  internal.on('error', function(err) {
    res.statusCode = 500;
    res.setHeader('Content-Type','text/plain');
    res.end(util.inspect(err));
  });

  internal.end(body);

  function done(internalRes)
  {
    if ( internalRes.statusCode >= 200 && internalRes.statusCode <= 399 )
    {
      console.log('Found in internal');
      res.statusCode = internalRes.statusCode;
      copyHeaders(internalRes,res);
      internalRes.pipe(res);
    }
    else
    {
      console.log("Didn't find in internal, checking public");
      publicRequest(req,body,res);
      internal.abort();
    }
  }
}

function publicRequest(req, body, res)
{
  var opt = {
    method: req.method,
    path: req.url,
    headers: req.headers,
    host: internalNpm.hostname,
    port: internalNpm.port
  }

  if ( fwdProxy )
  {
    opt.path = urllib.format(publicNpm).replace(/\/+$/,'')+ req.url;
    opt.protocol = fwdProxy.protocol;
    opt.host = fwdProxy.hostname;
    opt.port = fwdProxy.port;
    opt.headers.host = publicNpm.hostname;
  }

  delete opt.headers['authorization'];
  delete opt.headers['cookie'];

  console.log('Checking Public NPM:', util.inspect(opt));
  var pub = http.request(opt, done);

  pub.on('error', function(err) {
    res.statusCode = 500;
    res.setHeader('Content-Type','text/plain');
    res.end(util.inspect(err));
  });

  pub.end(body);

  function done(pubRes)
  {
    if ( pubRes.statusCode >= 200 && pubRes.statusCode <= 299 )
    {
      console.log('Found in public');
    }
    else
    {
      console.log("Didn't find in public, giving up");
    }

    res.statusCode = pubRes.statusCode;
    copyHeaders(pubRes,res);
    pubRes.pipe(res);
  }
}

function copyHeaders(from,to)
{
  var keys = Object.keys(from.headers);
  var k, v;
  for ( var i = 0 ; i < keys.length ; i++ )
  {
    k = keys[i];
    v = from.headers[k];
    to.setHeader(k,v);
  }
}


text:
<?php

namespace Rcm\Install\Service\Database;

class DataBase implements DatabaseServiceInterface
{
    protected $service;

    public function __construct($dbType) {
        $this->service = $this->getDbServiceByType($dbType);
    }

    public function isValid($postData) {
        return $this->service->isValid($postData);
    }

    public function testConnection($db_info)
    {
        return $this->service->testConnection($db_info);
    }

    public function getDoctrineConfigArray($db_info)
    {
        return $this->service->getDoctrineConfigArray($db_info);
    }

    protected function getDbServiceByType($type)
    {
        switch ($type) {
            case 'PDOMySql' :
                return new MySql();
            case 'PDOPgSql' :
                return new Postgresql();
            case 'PDOSqlite' :
                return new Sqlite();
            case 'oci8' :
                return new Oci();
        }

        throw new \Exception("No DB Service found for db type: ".$type);
    }
}


text:
class HelloWorldGem
  # Say hi to the world!
  #
  # Example:
  #   >> Hello.hi("indonesia")
  #   => haloo dunia!
  #
  # Arguments:
  #   language: (String)
  def self.hi(language = "indonesia")
    translator = Translator.new(language)
    translator.hi
  end

end

require 'hello/translator'


text:
/*
 * 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.
 */
package com.facebook.presto.execution;

import com.facebook.presto.Session;
import com.facebook.presto.common.QualifiedObjectName;
import com.facebook.presto.metadata.Metadata;
import com.facebook.presto.security.AccessControl;
import com.facebook.presto.spi.ColumnMetadata;
import com.facebook.presto.spi.ConnectorId;
import com.facebook.presto.spi.ConnectorMaterializedViewDefinition;
import com.facebook.presto.spi.ConnectorTableMetadata;
import com.facebook.presto.spi.PrestoException;
import com.facebook.presto.spi.SchemaTableName;
import com.facebook.presto.spi.TableHandle;
import com.facebook.presto.sql.analyzer.Analysis;
import com.facebook.presto.sql.analyzer.Analyzer;
import com.facebook.presto.sql.analyzer.SemanticException;
import com.facebook.presto.sql.parser.SqlParser;
import com.facebook.presto.sql.tree.CreateMaterializedView;
import com.facebook.presto.sql.tree.Expression;
import com.facebook.presto.transaction.TransactionManager;
import com.google.common.util.concurrent.ListenableFuture;

import javax.inject.Inject;

import java.util.List;
import java.util.Map;
import java.util.Optional;

import static com.facebook.presto.metadata.MetadataUtil.createQualifiedObjectName;
import static com.facebook.presto.metadata.MetadataUtil.toSchemaTableName;
import static com.facebook.presto.spi.StandardErrorCode.ALREADY_EXISTS;
import static com.facebook.presto.spi.StandardErrorCode.NOT_FOUND;
import static com.facebook.presto.sql.MaterializedViewUtils.computeMaterializedViewToBaseTableColumnMappings;
import static com.facebook.presto.sql.NodeUtils.mapFromProperties;
import static com.facebook.presto.sql.SqlFormatterUtil.getFormattedSql;
import static com.facebook.presto.sql.analyzer.SemanticErrorCode.MATERIALIZED_VIEW_ALREADY_EXISTS;
import static com.facebook.presto.sql.analyzer.SemanticErrorCode.NOT_SUPPORTED;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.util.concurrent.Futures.immediateFuture;
import static java.util.Objects.requireNonNull;

public class CreateMaterializedViewTask
        implements DataDefinitionTask<CreateMaterializedView>
{
    private final SqlParser sqlParser;

    @Inject
    public CreateMaterializedViewTask(SqlParser sqlParser)
    {
        this.sqlParser = requireNonNull(sqlParser, "sqlParser is null");
    }

    @Override
    public String getName()
    {
        return "CREATE MATERIALIZED VIEW";
    }

    @Override
    public ListenableFuture<?> execute(CreateMaterializedView statement, TransactionManager transactionManager, Metadata metadata, AccessControl accessControl, QueryStateMachine stateMachine, List<Expression> parameters)
    {
        Session session = stateMachine.getSession();
        QualifiedObjectName viewName = createQualifiedObjectName(session, statement, statement.getName());

        Optional<TableHandle> viewHandle = metadata.getTableHandle(session, viewName);
        if (viewHandle.isPresent()) {
            if (!statement.isNotExists()) {
                throw new SemanticException(MATERIALIZED_VIEW_ALREADY_EXISTS, statement, "Materialized view '%s' already exists", viewName);
            }
            return immediateFuture(null);
        }

        accessControl.checkCanCreateTable(session.getRequiredTransactionId(), session.getIdentity(), session.getAccessControlContext(), viewName);
        accessControl.checkCanCreateView(session.getRequiredTransactionId(), session.getIdentity(), session.getAccessControlContext(), viewName);

        Analyzer analyzer = new Analyzer(session, metadata, sqlParser, accessControl, Optional.empty(), parameters, stateMachine.getWarningCollector());
        Analysis analysis = analyzer.analyze(statement);

        ConnectorId connectorId = metadata.getCatalogHandle(session, viewName.getCatalogName())
                .orElseThrow(() -> new PrestoException(NOT_FOUND, "Catalog does not exist: " + viewName.getCatalogName()));
        List<ColumnMetadata> columnMetadata = analysis.getOutputDescriptor(statement.getQuery())
                .getVisibleFields().stream()
                .map(field -> new ColumnMetadata(field.getName().get(), field.getType()))
                .collect(toImmutableList());

        Map<String, Expression> sqlProperties = mapFromProperties(statement.getProperties());
        Map<String, Object> properties = metadata.getTablePropertyManager().getProperties(
                connectorId,
                viewName.getCatalogName(),
                sqlProperties,
                session,
                metadata,
                parameters);

        ConnectorTableMetadata viewMetadata = new ConnectorTableMetadata(
                toSchemaTableName(viewName),
                columnMetadata,
                properties,
                statement.getComment());

        String sql = getFormattedSql(statement.getQuery(), sqlParser, Optional.of(parameters));

        List<SchemaTableName> baseTables = analysis.getTableNodes().stream()
                .map(table -> {
                    QualifiedObjectName tableName = createQualifiedObjectName(session, table, table.getName());
                    if (!viewName.getCatalogName().equals(tableName.getCatalogName())) {
                        throw new SemanticException(
                                NOT_SUPPORTED,
                                statement,
                                "Materialized view %s created from a base table in a different catalog %s is not supported.",
                                viewName, tableName);
                    }
                    return toSchemaTableName(tableName);
                })
                .distinct()
                .collect(toImmutableList());

        ConnectorMaterializedViewDefinition viewDefinition = new ConnectorMaterializedViewDefinition(
                sql,
                viewName.getSchemaName(),
                viewName.getObjectName(),
                baseTables,
                Optional.of(session.getUser()),
                computeMaterializedViewToBaseTableColumnMappings(analysis),
                Optional.empty());
        try {
            metadata.createMaterializedView(session, viewName.getCatalogName(), viewMetadata, viewDefinition, statement.isNotExists());
        }
        catch (PrestoException e) {
            // connectors are not required to handle the ignoreExisting flag
            if (!e.getErrorCode().equals(ALREADY_EXISTS.toErrorCode()) || !statement.isNotExists()) {
                throw e;
            }
        }

        return immediateFuture(null);
    }

    @Override
    public String explain(CreateMaterializedView statement, List<Expression> parameters)
    {
        return "CREATE MATERIALIZED VIEW" + statement.getName();
    }
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Notus - Better Popup Notifications</title>
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
    <link rel="stylesheet" href="prism.css" charset="utf-8">
    <link rel="stylesheet" href="//cdn.rawgit.com/kushalpandya/notus/master/src/notus.css" charset="utf-8">
    <link rel="stylesheet" href="//cdn.rawgit.com/kushalpandya/notus/master/src/animate.css" charset="utf-8">

Notus

Notus - Web Notifications Widget

Yet another non-blocking pop-up notification library for the web, strictly without jQuery.

                    Title
                    <input id="notusTitle" type="text" class="form-control" placeholder="Title..." value="Notus">

                    Message
                    <textarea id="notusMessage" class="form-control" rows="3" placeholder="Message...">Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas!</textarea>

                            <input type="radio" name="notusType" value="popup" checked="checked">
                            Popup

                            <input type="radio" name="notusType" value="toast">
                            Toast

                            <input type="radio" name="notusType" value="snackbar">
                            Snackbar

                             Position
                             Alert Type
                             Behavior
                             Animation Type

                                        <input type="radio" name="notusPosition" value="top" data-supported="ts" disabled>
                                        Top

                                        <input type="radio" name="alertType" checked="checked" value="none">
                                        None

                                        <input type="checkbox" name="closable" checked="checked">
                                        Closable

                                        <input type="radio" name="animationType" value="slide" checked="checked">
                                        Slide

                                        <input type="radio" name="notusPosition" value="bottom" data-supported="ts" disabled>
                                        Bottom

                                        <input type="radio" name="alertType" value="success">
                                        Success

                                        <input type="checkbox" name="autoClose" checked="checked">
                                        Auto-close

                                        <input type="radio" name="animationType" value="fade">
                                        Fade

                                        <input type="radio" name="notusPosition" value="top-left" data-supported="p" checked="checked">
                                        Top-left

                                        <input type="radio" name="alertType" value="failure">
                                        Failure

                                        <input type="checkbox" name="animate" checked="checked">
                                        Animate

                                        <input type="radio" name="animationType" value="custom">
                                        Custom

                                        <input type="radio" name="notusPosition" value="top-right" data-supported="p">
                                        Top-right

                                        <input type="radio" name="alertType" value="warning">
                                        Warning

                                        <input type="checkbox" name="actionable">
                                        Actionable

                                        <input type="radio" name="notusPosition" value="bottom-left" data-supported="p">
                                        Bottom-left

                                        <input type="radio" name="notusPosition" value="bottom-right" data-supported="p">
                                        Bottom-right

Configuration

{
    title: "Notus",
    message: "Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas!",
    autoCloseDuration: 5000,
    notusPosition: "top-left",
    htmlString: true
}

<button class="btn btn-lg btn-primary" id="btnNotify"> Ping Notus!</button>

or

 Download

No Dependencies

There are ton of Notification widgets out there but they either depend on jQuery or they are too heavy to include in your already large project, Notus has no dependencies and is super-small to blend in your existing project. Honourable mentions; Notify.js & AlertifyJS

Light Weight

Notus is less than 4 KB (2 KB for JS & little over 1 KB for CSS) minified and gzipped.

Fully Flexible

Notus is fully customizable and supports several ways to show notifications (Popup, Toast & Snackbar) as well as custom styling using themeClass config.

Pure CSS3 Animations

Notus provides basic Slide and Fade animations which are entirely CSS driven. It even allows custom easing function (with animationFunction) and animation duration (with animationDuration) in config.

Works with Browsers, NodeJS & TypeScript

Notus supports web browsers as well as Desktop platforms like Electron or NW.js. It also supports TypeScript Type Definitions starting v0.3.1.

Latest Browser Support

Notus supports latest Chrome, Firefox, Safari & IE11+.

Kushal Pandya

MIT License


text:
package io.prelink.critbit;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.ardverk.collection.StringKeyAnalyzer;

//import org.ardverk.collection.PatriciaTrie;
//import org.ardverk.collection.StringKeyAnalyzer;

public class PatriciaTrieTest {
    private static final int WARMUPS = 1000;
    private static final int ITERS = 30000;
    private static final int SEED = 42;

    private static interface Putter {
        String name();
        void put(String key, String val);
    }
    private static String randomString(Random rand) {
        int len = RandomUtils.nextInt(rand, 100) + 1;
        return RandomStringUtils.random(len, 0, 0, false, false, null, rand);
    }
    private static void putTest(Putter p) {
        Random rand = new Random(SEED);
        System.out.print("Warming up " + p.name() + "... ");
        for(int i=0; i<WARMUPS; i++) {
            String key = randomString(rand);
            p.put(key, ""+i);
        }
        System.out.println("Done!");
        System.out.print(String.format("Starting test for %s...", p.name()));
        final long start = System.currentTimeMillis();
        for(int i=0; i<ITERS; i++) {
            String key = randomString(rand);
            p.put(key, ""+i);
        }
        final long end = System.currentTimeMillis();
        System.out.println(
            String.format("Done! Put %s keys in %s ms", ITERS, end-start));

        p.put("", "nothing");
        p.put("", "nothingelse");
        p.put("something", "something");
        p.put("something", "somethingelse");
    }

    private static class FCBFlipper {
        //Since FCB is purely functional, this helper class will handle
        //tracking the current FCB.
        private CritBitTree<String,String> fcb;
        public FCBFlipper() {
            this.fcb = new CritBitTree<String, String>(StringKeyAnalyzer.INSTANCE);
        }
        public void put(String key, String val) {
            this.fcb = fcb.put(key, val);
        }
    }

    public static void main(final String[] args) throws Exception {

        final Map<String, String> hm = new HashMap<String, String>();
        putTest(new Putter() {
            public String name() { return "HashMap"; }
            public void put(String k, String v) { hm.put(k, v); }
        });

        final Map<String, String> pshm =
            new HashMap<String, String>(WARMUPS+ITERS);
        putTest(new Putter() {
            public String name() { return "Presized HashMap"; }
            public void put(String k, String v) { pshm.put(k, v); }
        });

        final Map<String, String> tm = new TreeMap<String, String>();
        putTest(new Putter() {
            public String name() { return "TreeMap"; }
            public void put(String k, String v) { tm.put(k, v); }
        });

        final FCBFlipper fcb = new FCBFlipper();
        putTest(new Putter() {
            public String name() { return "Functional Crit Bit"; }
            public void put(String k, String v) { fcb.put(k, v); }
        });

        final MCritBitTree<String, String> mcb =
            new MCritBitTree<String, String>(StringKeyAnalyzer.INSTANCE);
        putTest(new Putter() {
            public String name() { return "Mutable Crit Bit"; }
            public void put(String k, String v) { mcb.put(k, v); }
        });

//      final PatriciaTrie<String, String> ptrie =
//          new PatriciaTrie<String, String>(StringKeyAnalyzer.INSTANCE);
//      putTest(new Putter() {
//          public String name() { return "Patricia Trie"; }
//          public void put(String k, String v) { ptrie.put(k, v); }
//      });

        //Give us a chance to look at the heap.
        for(int i=0;i<Integer.MAX_VALUE;i++) Thread.sleep(1000);

        //Added to avoid garbage collection.
        System.out.println(hm);
        System.out.println(pshm);
        System.out.println(tm);
        System.out.println(fcb);
        System.out.println(mcb);
//      System.out.println(ptrie);
    }

}


text:
using System;
using System.Linq;
using System.ComponentModel;
using System.ComponentModel.Composition;
using System.Reflection;

namespace Eagle.FilePicker.ViewModels
{
    [Export(typeof(IObjectPropertiesProvider))]
    public class ObjectPropertiesProvider : IObjectPropertiesProvider
    {
        public PropertyCollection GetProperties(INotifyPropertyChanged obj)
        {
            var visibleProperties =
                from p in obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)
                where p.IsDefined(typeof(UIVisibleAttribute))
                select p;

            var collection = new PropertyCollection();

            foreach (var item in visibleProperties)
            {
                var propertyValue = (PropertyValue)Activator.CreateInstance(
                    typeof(PropertyValue<>).MakeGenericType(item.PropertyType),
                    obj,
                    item);

                collection.Items.Add(propertyValue);
            }

            return collection;
        }
    }
}


text:
'use strict';

(function() {

  function UserResource($resource) {
    return $resource('/api/users/:id/:controller', {
      id: '@_id'
    }, {
      changePassword: {
        method: 'PUT',
        params: {
          controller: 'password'
        }
      },
      resetDemoAccountBalance: {
        method: 'PUT',
        params: {
          controller: 'resetdemoaccountbalance'
        }
      },
      get: {
        method: 'GET',
        params: {
          id: 'me'
        }
      }
    });
  }

  angular.module('notteryApp.auth')
    .factory('User', UserResource);
})();


text:
package io.gravitee.repository.elasticsearch.monitoring;

import io.gravitee.repository.elasticsearch.AbstractElasticRepository;
import io.gravitee.repository.elasticsearch.utils.DateUtils;
import io.gravitee.repository.monitoring.MonitoringRepository;
import io.gravitee.repository.monitoring.model.MonitoringResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.Client;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDate;
import java.time.ZonedDateTime;
import java.util.Map;

import static java.lang.String.format;
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;

/**
 * @author Azize Elamrani (azize dot elamrani at gmail dot com)
 * @author GraviteeSource Team
 */
public class ElasticMonitoringRepository extends AbstractElasticRepository implements MonitoringRepository {

    private final static String FIELD_GATEWAY_NAME = "gateway";
    private final static String FIELD_TIMESTAMP = "@timestamp";
    private final static String FIELD_HOSTNAME = "hostname";

    private final static String FIELD_JVM = "jvm";
    private final static String FIELD_PROCESS = "process";
    private final static String FIELD_OS = "os";

    private final static String TYPE_MONITOR = "monitor";

    @Autowired
    private Client client;

    @Override
    public MonitoringResponse query(final String gatewayId) {
        final String suffixDay = LocalDate.now().format(DateUtils.ES_DAILY_INDICE);

        final SearchRequestBuilder monitor = client
                .prepareSearch(configuration.getIndexName() + '-' + suffixDay)
                .setTypes(TYPE_MONITOR)
                .setQuery(boolQuery().must(termQuery(FIELD_GATEWAY_NAME, gatewayId)))
                .setSearchType(SearchType.QUERY_THEN_FETCH)
                .addSort(FIELD_TIMESTAMP, SortOrder.DESC)
                .setSize(1);

        final SearchResponse searchResponse = monitor.get();
        final SearchHits hits = searchResponse.getHits();
        if (hits != null && hits.getHits().length > 0) {
            return convert(hits.getHits()[0].getSource());
        }
        return null;
    }

    @SuppressWarnings("unchecked")
    private MonitoringResponse convert(final Map<String, Object> source) {
        final MonitoringResponse monitoringResponse = new MonitoringResponse();
        monitoringResponse.setGatewayId((String) source.get(FIELD_GATEWAY_NAME));
        monitoringResponse.setTimestamp(ZonedDateTime.parse((String) source.get(FIELD_TIMESTAMP)));
        monitoringResponse.setHostname((String) source.get(FIELD_HOSTNAME));

        // OS

        final Map<String, Object> os = (Map<String, Object>) source.get(FIELD_OS);

        final Map<String, Object> cpu = (Map<String, Object>) os.get("cpu");
        monitoringResponse.setOsCPUPercent((Integer) cpu.get("percent"));
        monitoringResponse.setOsCPULoadAverage((Map<String, ? super Number>) cpu.get("load_average"));

        final Map<String, Object> osMem = (Map<String, Object>) os.get("mem");
        monitoringResponse.setOsMemUsedInBytes(getLongValue(osMem.get("used_in_bytes")));
        monitoringResponse.setOsMemFreeInBytes(getLongValue(osMem.get("free_in_bytes")));
        monitoringResponse.setOsMemTotalInBytes(getLongValue(osMem.get("total_in_bytes")));
        monitoringResponse.setOsMemUsedPercent((Integer) osMem.get("used_percent"));
        monitoringResponse.setOsMemFreePercent((Integer) osMem.get("free_percent"));

        // Process

        final Map<String, Object> process = (Map<String, Object>) source.get(FIELD_PROCESS);

        monitoringResponse.setJvmProcessOpenFileDescriptors((Integer) process.get("open_file_descriptors"));
        monitoringResponse.setJvmProcessMaxFileDescriptors((Integer) process.get("max_file_descriptors"));

        // JVM

        final Map<String, Object> jvm = (Map<String, Object>) source.get(FIELD_JVM);

        monitoringResponse.setJvmUptimeInMillis(getLongValue(jvm.get("uptime_in_millis")));
        monitoringResponse.setJvmTimestamp(getLongValue(jvm.get("timestamp")));

        final Map<String, Object> jvmMem = (Map<String, Object>) jvm.get("mem");
        monitoringResponse.setJvmHeapCommittedInBytes(getLongValue(jvmMem.get("heap_committed_in_bytes")));
        monitoringResponse.setJvmHeapUsedPercent((Integer) jvmMem.get("heap_used_percent"));
        monitoringResponse.setJvmHeapMaxInBytes(getLongValue(jvmMem.get("heap_max_in_bytes")));
        monitoringResponse.setJvmNonHeapCommittedInBytes(getLongValue(jvmMem.get("non_heap_committed_in_bytes")));
        monitoringResponse.setJvmHeapUsedInBytes(getLongValue(jvmMem.get("heap_used_in_bytes")));
        monitoringResponse.setJvmNonHeapUsedInBytes(getLongValue(jvmMem.get("non_heap_used_in_bytes")));

        final Map<String, Object> jvmMemPools = (Map<String, Object>) jvmMem.get("pools");

        final Map<String, Object> jvmMemPoolsYoung = (Map<String, Object>) jvmMemPools.get("young");

        monitoringResponse.setJvmMemPoolYoungUsedInBytes(getLongValue(jvmMemPoolsYoung.get("used_in_bytes")));
        monitoringResponse.setJvmMemPoolYoungPeakUsedInBytes(getLongValue(jvmMemPoolsYoung.get("peak_used_in_bytes")));
        monitoringResponse.setJvmMemPoolYoungMaxInBytes(getLongValue(jvmMemPoolsYoung.get("max_in_bytes")));
        monitoringResponse.setJvmMemPoolYoungPeakMaxInBytes(getLongValue(jvmMemPoolsYoung.get("peak_max_in_bytes")));

        final Map<String, Object> jvmMemPoolsOld = (Map<String, Object>) jvmMemPools.get("old");

        monitoringResponse.setJvmMemPoolOldUsedInBytes(getLongValue(jvmMemPoolsOld.get("used_in_bytes")));
        monitoringResponse.setJvmMemPoolOldPeakUsedInBytes(getLongValue(jvmMemPoolsOld.get("peak_used_in_bytes")));
        monitoringResponse.setJvmMemPoolOldMaxInBytes(getLongValue(jvmMemPoolsOld.get("max_in_bytes")));
        monitoringResponse.setJvmMemPoolOldPeakMaxInBytes(getLongValue(jvmMemPoolsOld.get("peak_max_in_bytes")));

        final Map<String, Object> jvmMemPoolsSurvivor = (Map<String, Object>) jvmMemPools.get("survivor");

        monitoringResponse.setJvmMemPoolSurvivorUsedInBytes(getLongValue(jvmMemPoolsSurvivor.get("used_in_bytes")));
        monitoringResponse.setJvmMemPoolSurvivorPeakUsedInBytes(getLongValue(jvmMemPoolsSurvivor.get("peak_used_in_bytes")));
        monitoringResponse.setJvmMemPoolSurvivorMaxInBytes(getLongValue(jvmMemPoolsSurvivor.get("max_in_bytes")));
        monitoringResponse.setJvmMemPoolSurvivorPeakMaxInBytes(getLongValue(jvmMemPoolsSurvivor.get("peak_max_in_bytes")));

        final Map<String, Object> jvmThreads = (Map<String, Object>) jvm.get("threads");

        monitoringResponse.setJvmThreadCount((Integer) jvmThreads.get("count"));
        monitoringResponse.setJvmThreadPeakCount((Integer) jvmThreads.get("peak_count"));

        final Map<String, Object> jvmGC = (Map<String, Object>) jvm.get("gc");

        final Map<String, Object> jvmGCCollectors = (Map<String, Object>) jvmGC.get("collectors");

        final Map<String, Object> jvmGCCollectorsYoung = (Map<String, Object>) jvmGCCollectors.get("young");

        monitoringResponse.setJvmGCCollectorsYoungCollectionCount((Integer) jvmGCCollectorsYoung.get("collection_count"));
        monitoringResponse.setJvmGCCollectorsYoungCollectionTimeInMillis(getLongValue(jvmGCCollectorsYoung.get("collection_time_in_millis")));

        final Map<String, Object> jvmGCCollectorsOld = (Map<String, Object>) jvmGCCollectors.get("old");

        monitoringResponse.setJvmGCCollectorsOldCollectionCount((Integer) jvmGCCollectorsOld.get("collection_count"));
        monitoringResponse.setJvmGCCollectorsOldCollectionTimeInMillis(getLongValue(jvmGCCollectorsOld.get("collection_time_in_millis")));

        return monitoringResponse;
    }

    private Long getLongValue(final Object value) {
        if (value instanceof Integer) {
            return ((Integer) value).longValue();
        } else if (value instanceof Long) {
            return (Long) value;
        } else {
            throw new IllegalArgumentException(format("Expected a Long and get a %s", value.getClass().getName()));
        }
    }
}


text:
import Mongoose from 'mongoose'

let Schema = Mongoose.Schema
let conversationSchema = new Schema({
    last_message: {
        type: String,
        require: true
    },
    client_id: {
        type: Schema.Types.ObjectId,
        refs: 'Clients'
    }
})

export default Mongoose.model('Conversations', conversationSchema)


text:
import datetime
import uuid

from django.utils import datetime_safe
from keystoneauth1.access import access
from keystoneauth1.access import service_catalog
from keystoneclient.v3 import domains
from keystoneclient.v3 import projects
from keystoneclient.v3 import roles
from keystoneclient.v3 import users
import requests

class TestDataContainer(object):
    """Arbitrary holder for test data in an object-oriented fashion."""
    pass

class TestResponse(requests.Response):
    """Class used to wrap requests.Response.

    It also provides some convenience to initialize with a dict.
    """

    def __init__(self, data):
        self._text = None
        super().__init__()
        if isinstance(data, dict):
            self.status_code = data.get('status_code', 200)
            self.headers = data.get('headers', None)
            # Fake the text attribute to streamline Response creation
            self._text = data.get('text', None)
        else:
            self.status_code = data

    def __eq__(self, other):
        return self.__dict__ == other.__dict__

    @property
    def text(self):
        return self._text

def generate_test_data(service_providers=False, endpoint='localhost'):
    '''Builds a set of test_data data as returned by Keystone V2.'''
    test_data = TestDataContainer()

    keystone_service = {
        'type': 'identity',
        'id': uuid.uuid4().hex,
        'endpoints': [
            {
                'url': 'http://admin.%s/identity/v3' % endpoint,
                'region': 'RegionOne',
                'interface': 'admin',
                'id': uuid.uuid4().hex,
            },
            {
                'url': 'http://internal.%s/identity/v3' % endpoint,
                'region': 'RegionOne',
                'interface': 'internal',
                'id': uuid.uuid4().hex
            },
            {
                'url': 'http://public.%s/identity/v3' % endpoint,
                'region': 'RegionOne',
                'interface': 'public',
                'id': uuid.uuid4().hex
            }
        ]
    }

    # Domains
    domain_dict = {'id': uuid.uuid4().hex,
                   'name': 'domain',
                   'description': '',
                   'enabled': True}
    test_data.domain = domains.Domain(domains.DomainManager(None),
                                      domain_dict, loaded=True)

    # Users
    user_dict = {'id': uuid.uuid4().hex,
                 'name': 'gabriel',
                 'email': 'gabriel@example.com',
                 'password': 'swordfish',
                 'domain_id': domain_dict['id'],
                 'token': '',
                 'enabled': True}
    test_data.user = users.User(users.UserManager(None),
                                user_dict, loaded=True)

    # Projects
    project_dict_1 = {'id': uuid.uuid4().hex,
                      'name': 'tenant_one',
                      'description': '',
                      'domain_id': domain_dict['id'],
                      'enabled': True}
    project_dict_2 = {'id': uuid.uuid4().hex,
                      'name': 'tenant_two',
                      'description': '',
                      'domain_id': domain_dict['id'],
                      'enabled': False}
    test_data.project_one = projects.Project(projects.ProjectManager(None),
                                             project_dict_1,
                                             loaded=True)
    test_data.project_two = projects.Project(projects.ProjectManager(None),
                                             project_dict_2,
                                             loaded=True)

    # Roles
    role_dict = {'id': uuid.uuid4().hex,
                 'name': 'Member'}
    test_data.role = roles.Role(roles.RoleManager, role_dict)

    nova_service = {
        'type': 'compute',
        'id': uuid.uuid4().hex,
        'endpoints': [
            {
                'url': ('http://nova-admin.%s:8774/v2.0/%s'
                        % (endpoint, project_dict_1['id'])),
                'region': 'RegionOne',
                'interface': 'admin',
                'id': uuid.uuid4().hex,
            },
            {
                'url': ('http://nova-internal.%s:8774/v2.0/%s'
                        % (endpoint, project_dict_1['id'])),
                'region': 'RegionOne',
                'interface': 'internal',
                'id': uuid.uuid4().hex
            },
            {
                'url': ('http://nova-public.%s:8774/v2.0/%s'
                        % (endpoint, project_dict_1['id'])),
                'region': 'RegionOne',
                'interface': 'public',
                'id': uuid.uuid4().hex
            },
            {
                'url': ('http://nova2-admin.%s:8774/v2.0/%s'
                        % (endpoint, project_dict_1['id'])),
                'region': 'RegionTwo',
                'interface': 'admin',
                'id': uuid.uuid4().hex,
            },
            {
                'url': ('http://nova2-internal.%s:8774/v2.0/%s'
                        % (endpoint, project_dict_1['id'])),
                'region': 'RegionTwo',
                'interface': 'internal',
                'id': uuid.uuid4().hex
            },
            {
                'url': ('http://nova2-public.%s:8774/v2.0/%s'
                        % (endpoint, project_dict_1['id'])),
                'region': 'RegionTwo',
                'interface': 'public',
                'id': uuid.uuid4().hex
            }
        ]
    }

    # Tokens
    tomorrow = datetime_safe.datetime.now() + datetime.timedelta(days=1)
    expiration = datetime_safe.datetime.isoformat(tomorrow)
    auth_token = uuid.uuid4().hex

    auth_response_headers = {
        'X-Subject-Token': auth_token
    }

    auth_response = TestResponse({
        "headers": auth_response_headers
    })

    scoped_token_dict = {
        'token': {
            'methods': ['password'],
            'expires_at': expiration,
            'project': {
                'id': project_dict_1['id'],
                'name': project_dict_1['name'],
                'domain': {
                    'id': domain_dict['id'],
                    'name': domain_dict['name']
                }
            },
            'user': {
                'id': user_dict['id'],
                'name': user_dict['name'],
                'domain': {
                    'id': domain_dict['id'],
                    'name': domain_dict['name']
                }
            },
            'roles': [role_dict],
            'catalog': [keystone_service, nova_service]
        }
    }

    sp_list = None
    if service_providers:
        test_data.sp_auth_url = 'http://service_provider_endp/identity/v3'
        test_data.service_provider_id = 'k2kserviceprovider'
        # The access info for the identity provider
        # should return a list of service providers
        sp_list = [
            {'auth_url': test_data.sp_auth_url,
             'id': test_data.service_provider_id,
             'sp_url': 'https://k2kserviceprovider/sp_url'}
        ]
        scoped_token_dict['token']['service_providers'] = sp_list

    test_data.scoped_access_info = access.create(
        resp=auth_response,
        body=scoped_token_dict
    )

    domain_token_dict = {
        'token': {
            'methods': ['password'],
            'expires_at': expiration,
            'domain': {
                'id': domain_dict['id'],
                'name': domain_dict['name'],
            },
            'user': {
                'id': user_dict['id'],
                'name': user_dict['name'],
                'domain': {
                    'id': domain_dict['id'],
                    'name': domain_dict['name']
                }
            },
            'roles': [role_dict],
            'catalog': [keystone_service, nova_service]
        }
    }
    test_data.domain_scoped_access_info = access.create(
        resp=auth_response,
        body=domain_token_dict
    )

    unscoped_token_dict = {
        'token': {
            'methods': ['password'],
            'expires_at': expiration,
            'user': {
                'id': user_dict['id'],
                'name': user_dict['name'],
                'domain': {
                    'id': domain_dict['id'],
                    'name': domain_dict['name']
                }
            },
            'catalog': [keystone_service]
        }
    }

    if service_providers:
        unscoped_token_dict['token']['service_providers'] = sp_list

    test_data.unscoped_access_info = access.create(
        resp=auth_response,
        body=unscoped_token_dict
    )

    # Service Catalog
    test_data.service_catalog = service_catalog.ServiceCatalogV3(
        [keystone_service, nova_service])

    # federated user
    federated_scoped_token_dict = {
        'token': {
            'methods': ['password'],
            'expires_at': expiration,
            'project': {
                'id': project_dict_1['id'],
                'name': project_dict_1['name'],
                'domain': {
                    'id': domain_dict['id'],
                    'name': domain_dict['name']
                }
            },
            'user': {
                'id': user_dict['id'],
                'name': user_dict['name'],
                'domain': {
                    'id': domain_dict['id'],
                    'name': domain_dict['name']
                },
                'OS-FEDERATION': {
                    'identity_provider': 'ACME',
                    'protocol': 'OIDC',
                    'groups': [
                        {'id': uuid.uuid4().hex},
                        {'id': uuid.uuid4().hex}
                    ]
                }
            },
            'roles': [role_dict],
            'catalog': [keystone_service, nova_service]
        }
    }

    test_data.federated_scoped_access_info = access.create(
        resp=auth_response,
        body=federated_scoped_token_dict
    )

    federated_unscoped_token_dict = {
        'token': {
            'methods': ['password'],
            'expires_at': expiration,
            'user': {
                'id': user_dict['id'],
                'name': user_dict['name'],
                'domain': {
                    'id': domain_dict['id'],
                    'name': domain_dict['name']
                },
                'OS-FEDERATION': {
                    'identity_provider': 'ACME',
                    'protocol': 'OIDC',
                    'groups': [
                        {'id': uuid.uuid4().hex},
                        {'id': uuid.uuid4().hex}
                    ]
                }
            },
            'catalog': [keystone_service]
        }
    }

    test_data.federated_unscoped_access_info = access.create(
        resp=auth_response,
        body=federated_unscoped_token_dict
    )

    return test_data


text:
using System;
using Koopakiller.Apps.MagicMirror.Model;
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;

namespace Koopakiller.Apps.MagicMirror.UnitTests.Model
{
    [TestClass]
    public class TemperatureTests
    {
        [TestMethod]
        public void Constructor()
        {
            var temp = new Temperature();
            this.Check(temp, 0D);
        }

        [TestMethod]
        public void FromCelsius()
        {
            var temp = Temperature.FromCelsius(0);
            this.Check(temp, 0D);
            temp = Temperature.FromCelsius(100);
            this.Check(temp, 100D);
        }

        [TestMethod]
        public void FromDelisle()
        {
            var temp = Temperature.FromDelisle(0);
            this.Check(temp, 100 - 0D * 2 / 3);
            temp = Temperature.FromDelisle(100);
            this.Check(temp, 100 - 100D * 2 / 3);
        }

        [TestMethod]
        public void FromFahrenheit()
        {
            var temp = Temperature.FromFahrenheit(0);
            this.Check(temp, (0D - 32) * 5 / 9);
            temp = Temperature.FromFahrenheit(100);
            this.Check(temp, (100D - 32) * 5 / 9);
        }

        [TestMethod]
        public void FromKelvin()
        {
            var temp = Temperature.FromKelvin(0);
            this.Check(temp, 0D - 273.15);
            temp = Temperature.FromKelvin(100);
            this.Check(temp, 100D - 273.15);
        }

        [TestMethod]
        public void FromNewton()
        {
            var temp = Temperature.FromNewton(0);
            this.Check(temp, 0D * 100 / 33);
            temp = Temperature.FromNewton(100);
            this.Check(temp, 100D * 100 / 33);
        }

        [TestMethod]
        public void FromRankine()
        {
            var temp = Temperature.FromRankine(0);
            this.Check(temp, (0D - 491.67) * 5 / 9);
            temp = Temperature.FromRankine(100);
            this.Check(temp, (100D - 491.67) * 5 / 9);
        }

        [TestMethod]
        public void FromReaumur()
        {
            var temp = Temperature.FromReaumur(0);
            this.Check(temp, 0D * 5 / 4);
            temp = Temperature.FromReaumur(100);
            this.Check(temp, 100D * 5 / 4);
        }

        [TestMethod]
        public void FromRomer()
        {
            var temp = Temperature.FromRomer(0);
            this.Check(temp, (0D - 7.5) * 40 / 21);
            temp = Temperature.FromRomer(100);
            this.Check(temp, (100D - 7.5) * 40 / 21);
        }

        private void Check(Temperature temp, double celsius)
        {
            var delta = Math.Abs(celsius) * 1E-14;
            Assert.AreEqual(celsius, temp.Celsius, delta, $"Failed at {nameof(temp.Celsius)}");
            Assert.AreEqual((100 - celsius) * 3 / 2, temp.Delisle, delta, $"Failed at {nameof(temp.Delisle)}");
            Assert.AreEqual(celsius * 9 / 5 + 32, temp.Fahrenheit, delta, $"Failed at {nameof(temp.Fahrenheit)}");
            Assert.AreEqual(celsius + 273.15, temp.Kelvin, delta, $"Failed at {nameof(temp.Kelvin)}");
            Assert.AreEqual(celsius * 33 / 100, temp.Newton, delta, $"Failed at {nameof(temp.Newton)}");
            Assert.AreEqual((celsius + 273.15) * 9 / 5, temp.Rankine, delta, $"Failed at {nameof(temp.Rankine)}");
            Assert.AreEqual(celsius * 4 / 5, temp.Reaumur, delta, $"Failed at {nameof(temp.Reaumur)}");
            Assert.AreEqual(celsius * 21 / 40 + 7.5, temp.Romer, delta, $"Failed at {nameof(temp.Romer)}");
        }
    }
}


text:
<?php

declare(strict_types=1);

/**
 * This file is part of Narrowspark Framework.
 *
 * (c) Daniel Bannert <d.bannert@anolilab.de>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Viserio\Component\Mail\Tests\Transport;

use Aws\Ses\SesClient;
use Mockery;
use Narrowspark\TestingHelper\Phpunit\MockeryTestCase;
use Swift_Message;
use Viserio\Component\Mail\Tests\Transport\Fixture\SendRawEmailMock;
use Viserio\Component\Mail\Transport\SesTransport;
use Viserio\Component\Support\Str;

/**
 * @internal
 *
 * @small
 */
final class SesTransportTest extends MockeryTestCase
{
    /** @var \Aws\Ses\SesClient|\Mockery\MockInterface */
    private $httpMock;

    /**
     * {@inheritdoc}
     */
    protected function setUp(): void
    {
        parent::setUp();

        $this->httpMock = Mockery::mock(SesClient::class);
    }

    public function testSend(): void
    {
        $message = new Swift_Message('Foo subject', 'Bar body');
        $message->setSender('myself@example.com');
        $message->setTo('me@example.com');
        $message->setBcc('you@example.com');

        $transport = new SesTransport($this->httpMock);

        $messageId = Str::random(32);
        $sendRawEmailMock = new SendRawEmailMock($messageId);

        $this->httpMock
            ->shouldReceive('sendRawEmail')
            ->with([
                'Source' => 'myself@example.com',
                'RawMessage' => ['Data' => (string) $message],
            ])
            ->andReturn($sendRawEmailMock);

        $transport->send($message);

        self::assertEquals($messageId, $message->getHeaders()->get('X-SES-Message-ID')->getFieldBody());
    }

    /**
     * {@inheritdoc}
     */
    protected function allowMockingNonExistentMethods(bool $allow = false): void
    {
        parent::allowMockingNonExistentMethods(true);
    }
}


text:
package misc

import (
	"context"
	"os/exec"
	"runtime"
	"testing"
	"time"

	"github.com/GoogleContainerTools/skaffold/testutil"
)

func TestGracefulBuildCancel(t *testing.T) {
	if runtime.GOOS == "windows" {
		t.Skip("graceful cancel doesn't work on windows")
	}

	tests := []struct {
		description string
		command     string
		shouldErr   bool
	}{
		{
			description: "terminate before timeout",
			command:     "echo done",
		},
		{
			description: "terminate gracefully and exit 0",
			command:     "trap 'echo trap' INT; sleep .1",
		},
		{
			description: "kill process after sigint",
			command:     "trap 'echo trap' INT; sleep 100",
			shouldErr:   true,
		},
	}

	for _, test := range tests {
		testutil.Run(t, test.description, func(t *testutil.T) {
			t.Override(&gracePeriod, 200*time.Millisecond)
			ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
			defer cancel()

			cmd := exec.Command("bash", "-c", test.command)
			t.CheckNoError(cmd.Start())

			err := HandleGracefulTermination(ctx, cmd)
			t.CheckError(test.shouldErr, err)
		})
	}
}


text:
import JSONModel    from "sap/ui/model/json/JSONModel";
import Device       from "sap/ui/Device";

export default {
    createDeviceModel(): JSONModel {
        //TODO|ui5ts: generate constructors
        var oModel = new JSONModel(Device);
        oModel.setDefaultBindingMode(sap.ui.model.BindingMode.OneWay);
        return oModel;
    }
};


text:
package com.macrossx.wechat.entity.server;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;

@Data
@EqualsAndHashCode(callSuper=false)
@ToString(callSuper=true)
@XmlRootElement(name="xml")
public class WechatImageResponse extends WechatHttpEntity{
	@XmlElement(name = "Image")
	private Image Image;

	public WechatImageResponse(){
		setMsgType("image");
	}

	@Data
	public static class Image {
		@XmlElement(name = "MediaId")
		private String MediaId;

	}

}


text:
<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.spacedog</groupId>
		<artifactId>spacedog-parent</artifactId>
		<version>3.0.0-SNAPSHOT</version>
	</parent>

	<artifactId>spacedog-server-sdk</artifactId>
	<packaging>jar</packaging>

	<build>
		<plugins>

			<plugin>
				<artifactId>maven-assembly-plugin</artifactId>
				<version>2.5.3</version>
				<executions>

					<execution>
						<id>bundle</id>
						<configuration>
							<descriptors>
								<descriptor>assembly-server.xml</descriptor>
							</descriptors>
							<attach>false</attach>
							<outputDirectory>${project.build.directory}</outputDirectory>
						</configuration>
						<phase>package</phase>
						<goals>
							<goal>single</goal>
						</goals>
					</execution>

				</executions>
			</plugin>
		</plugins>

	</build>

	<dependencies>
		<dependency>
			<groupId>io.spacedog</groupId>
			<artifactId>spacedog-client-sdk</artifactId>
			<version>${project.parent.version}</version>
		</dependency>
		<dependency>
			<groupId>io.spacedog</groupId>
			<artifactId>spacedog-jobs</artifactId>
			<version>${project.parent.version}</version>
		</dependency>
		<dependency>
			<groupId>net.code-story</groupId>
			<artifactId>http</artifactId>
			<version>2.105</version>
		</dependency>
		<!-- overrides jackson version from fluent-http dependency -->
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-annotations</artifactId>
			<version>${jackson-version}</version>
		</dependency>
		<!-- overrides jackson version from http dependency -->
		<dependency>
			<groupId>com.fasterxml.jackson.datatype</groupId>
			<artifactId>jackson-datatype-jsr310</artifactId>
			<version>${jackson-version}</version>
		</dependency>
		<dependency>
			<groupId>com.amazonaws</groupId>
			<artifactId>aws-java-sdk-sns</artifactId>
			<version>${aws-version}</version>
		</dependency>
		<dependency>
			<groupId>com.amazonaws</groupId>
			<artifactId>aws-java-sdk-s3</artifactId>
			<version>${aws-version}</version>
		</dependency>
		<dependency>
			<groupId>com.amazonaws</groupId>
			<artifactId>aws-java-sdk-lambda</artifactId>
			<version>${aws-version}</version>
		</dependency>
		<dependency>
			<groupId>com.amazonaws</groupId>
			<artifactId>aws-java-sdk-events</artifactId>
			<version>${aws-version}</version>
		</dependency>
		<dependency>
			<groupId>com.amazonaws</groupId>
			<artifactId>aws-java-sdk-logs</artifactId>
			<version>${aws-version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-email</artifactId>
			<version>1.4</version>
		</dependency>
		<dependency>
			<groupId>com.sun.mail</groupId>
			<artifactId>javax.mail</artifactId>
			<version>1.5.6</version>
		</dependency>
		<dependency>
			<groupId>com.mitchellbosecke</groupId>
			<artifactId>pebble</artifactId>
			<version> 2.2.3 </version>
		</dependency>
		<dependency>
			<groupId>com.univocity</groupId>
			<artifactId>univocity-parsers</artifactId>
			<version>2.6.1</version>
			<type>jar</type>
		</dependency>
		<dependency>
			<groupId>org.elasticsearch.client</groupId>
			<artifactId>
				elasticsearch-rest-high-level-client
			</artifactId>
			<version>${es-version}</version>
		</dependency>
	</dependencies>

</project>


text:
package com.khartec.waltz.common;

import org.junit.Test;

import java.util.Collections;

import static com.khartec.waltz.common.CollectionUtilities.notEmpty;
import static junit.framework.TestCase.assertTrue;
import static org.junit.Assert.assertFalse;

public class CollectionUtilities_notEmpty {

    @Test
    public void nullCollectionIsEmpty() {
        assertFalse(notEmpty(null));
    }

    @Test
    public void emptyCollectionIsEmpty() {
        assertFalse(notEmpty(Collections.emptyList()));
    }

    @Test
    public void collectionWithAnythingInItIsNotEmpty() {
        assertTrue(notEmpty(SetUtilities.asSet("A")));
    }

}


text:
<?php

namespace Filternet\Commands;

use Filternet\Checkers\Sni;
use Filternet\Utility\Status;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\ProgressBar;
use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class CheckSniCommand extends Command
{
    /**
     * Configure command
     */
    protected function configure()
    {
        $this
            ->setName('check:sni')
            ->setDescription('Is blocked by TLS SNI?')
            ->addArgument(
                'domain',
                InputArgument::REQUIRED,
                'Domain name (example: youtube.com)'
            )
            ->addOption(
                'timeout',
                't',
                InputOption::VALUE_OPTIONAL,
                'Connection timeout',
                20
            )
            ->addOption(
                'host',
                null,
                InputOption::VALUE_OPTIONAL,
                'Connect to which host (example: google.com)',
                'google.com'
            );
    }

    /**
     * Execute command
     *
     * @param InputInterface $input
     * @param OutputInterface $output
     * @return int|null|void
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $lowerDomain = $input->getArgument('domain');
        $upperDomain = strtoupper($lowerDomain);

        $sni = new Sni();
        $sni->setHost($input->getOption('host'));
        $sni->setTimeout($input->getOption('timeout'));

        $progress = new ProgressBar($output, 2);

        $lowerStatus = $this->status($sni->blocked($lowerDomain));
        $lowerError = $sni->error() ?: Status::unknown();

        $progress->advance();

        $upperStatus = $this->status($sni->blocked($upperDomain));
        $upperError = $sni->error() ?: Status::unknown();

        $progress->finish();

        $date = date('Y-m-d H:i:s');

        $output->writeln(' Done!');

        $table = new Table($output);
        $table
            ->setHeaders(['SNI Name', 'Status', 'Error', 'Date'])
            ->setRows([
                [$lowerDomain, $lowerStatus, $lowerError, $date],
                [$upperDomain, $upperStatus, $upperError, $date]
            ]);
        $table->render();
    }

    /**
     * Get Status
     *
     * @param bool $blocked
     * @return string
     */
    protected function status($blocked)
    {
        return $blocked ? Status::blocked() : Status::open();
    }

}


text:
//
//  TMFResponse.h
//
// Copyright (c) 2013 Martin Gratzer, http://www.mgratzer.com
// All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// This file is part of 3MF http://threemf.com
//

#import <Foundation/Foundation.h>

/**
 Class representing the response for a TMFRequest of a TMFRequestResponseCommand
 */
@interface TMFResponse : NSObject
/**
 Unique Identifier for the request.
 This property is used to identify the corresponding callback for a TMFResponse.
 */
@property (nonatomic, copy) id identifier;
/**
 A request's result.
 The type and structure of the result depends on the corresponding TMFRequestResponseCommand.
 May be nil in the case of an error
 */
@property (nonatomic, copy) id result;
/**
 Error object if anything went wrong, otherwise nil.
 */
@property (nonatomic, copy) id error;

/**
 Creates a new response.
 @param identifier RPC identifier
 @param result a request's result, may be nil in the case of an error
 @param error a error object if anything went wrong, otherwise nil
 */
+ (TMFResponse *)responseWithidentifier:(id)identifier result:(id)result error:(id)error;

@end


text:
<md-card class="auth-card" md-colors="{background: 'primary-50'}">
  <md-card-title>
    <md-card-title-text>
      Not logged in

        Hello, {{$ctrl.Me.data.name}}

    </md-card-title-text>
  </md-card-title>

  <md-card-actions>
    <md-button
      ng-if="!$ctrl.isAuthenticated()"
      class="md-primary"
      aria-label="Login"
      ng-click="$ctrl.login()">
      Login
    </md-button>
    <md-button
      ng-if="$ctrl.isAuthenticated()"
      class="md-primary"
      aria-label="Logout"
      ng-click="$ctrl.logout()">
      Logout
    </md-button>
  </md-card-actions>
</md-card>