text:
/*
 * This software is distributed under BSD 3-clause license (see LICENSE file).
 *
 * Authors: Viktor Gal, Soeren Sonnenburg, Yuyu Zhang, Bjoern Esser
 */

#ifndef __RESCALEFEATURES_H__
#define __RESCALEFEATURES_H__

#include <shogun/lib/config.h>

#include <shogun/preprocessor/DensePreprocessor.h>

namespace shogun
{
	/**@brief Preprocessor RescaleFeautres is rescaling the range of features to
	 * make the features independent of each other and aims to scale the range
	 * in [0, 1] or [-1, 1].
	 *
	 * The general formula is given as:
	 * \f[
	 * x' = \frac{x - min}{max - min}
	 * \f]
	 * where \f$x\f$ is an original value, \f$x'\f$ is the normalized value.
     */
	class CRescaleFeatures : public CDensePreprocessor<float64_t>
	{
	public:
		/** default ctor */
		CRescaleFeatures();

		/** dtor */
		virtual ~CRescaleFeatures();

		/**
		 * Fit preprocessor into features
		 *
		 * @param features the features to derive the min and max values
		 * from.
		 */
		virtual void fit(CFeatures* features);

		/**
		 * Cleanup
		 */
		virtual void cleanup();

		/**
		 * Apply preproc on a single feature vector
		 */
		virtual SGVector<float64_t>
		apply_to_feature_vector(SGVector<float64_t> vector);

		/** @return object name */
		virtual const char* get_name() const
		{
			return "RescaleFeatures";
		}

		/** return a type of preprocessor */
		virtual EPreprocessorType get_type() const
		{
			return P_RESCALEFEATURES;
		}

	private:
		void register_parameters();

	protected:
		virtual SGMatrix<float64_t> apply_to_matrix(SGMatrix<float64_t> matrix);

		/** min */
		SGVector<float64_t> m_min;
		/** 1.0/(max[i]-min[i]) */
		SGVector<float64_t> m_range;
	};
}

#endif /* __RESCALEFEATURES_H__ */


text:
var app = angular.module('stementor', ['ngRoute', 'ngMaterial', 'jkAngularCarousel', 'firebase', 'ngMessages', 'material.svgAssetsCache', 'angular-flippy', 'truncate']);

app.config(function($mdThemingProvider) {
  $mdThemingProvider
    .theme('default')
    .accentPalette('grey');

});

app.config(['$routeProvider', function($routeProvider) {
  $routeProvider
  .when('/home', {
    templateUrl: '/views/home.html',
    controller: 'HomeController',
    controllerAs: 'home'
  })
  .when('/about', {
    templateUrl: '/views/about.html',
    controller: 'AboutController',
    controllerAs: 'about'
  })
  .when('/inbox', {
    templateUrl: '/views/inbox.html',
    controller: 'InboxController',
    controllerAs: 'inbox'
  })
  .when('/message', {
    templateUrl: '/views/message.html',
    controller: 'MessageController',
    controllerAs: 'message'
  })
  .when('/profile', {
    templateUrl: '/views/profile.html',
    controller: 'ProfileController',
    controllerAs: 'profile'
  })
  .when('/search', {
    templateUrl: '/views/search.html',
    controller: 'SearchController',
    controllerAs: 'search'
  })
  .when('/signup', {
    templateUrl: '/views/sign-up.html',
    controller: 'SignUpController',
    controllerAs: 'signup'
  })
  .otherwise({
    redirectTo: 'home'
  });
}]);

redpajama_set_name: RedPajamaGithub


text:
import _Pjax, { Pjax } from '../../index';

describe('Interface: Package', function () {
  describe('default', function () {
    it('default', function () {
      assert(_Pjax === Pjax);
    });

  });

  describe('Pjax', function () {
    it('assign', function () {
      assert(typeof Pjax.assign === 'function');
    });

    it('replace', function () {
      assert(typeof Pjax.replace === 'function');
    });

  });

});


text:
<?php
require_once __DIR__.'/../vendor/autoload.php';
require_once __DIR__.'/Wookieb/Map/Tests/MapUnit.php';
require_once __DIR__.'/Wookieb/Map/Tests/CommonMapTests.php';


text:
                Vente #{{ sale.id}}

                Nouvelle vente

 0">
                 0">
                    Réduction

                <span [hidden]="editingSaleDiscount || sale.discountRatio == null || sale.discountRatio <= 0">
                    -{{ (sale.discountRatio * 100) | number:'.0' }} %

                    <input #discount
                           [initialValue]="sale.discountRatio * 100"
                           [validator]="validateDiscount"
                           (fastChange)="onSaleDiscountChange($event)"
                           (cancelled)="editingSaleDiscount = false"
                           type="number" min="0" max="100" step="1"
                           size="2" fast-input>
                    %

Encaisser

Retour


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

namespace EShop.FrontEnd.Controllers.Controllers
{
    public enum CookieDataKeys
    {
        BasketItems,
        BasketTotal,
        BasketId
    }
}


text:
// Copyright (C) Pash Contributors. License: GPL/BSD. See https://github.com/Pash-Project/Pash/

using System;
using System.Runtime.Serialization;

namespace System.Management.Automation
{
    /// <summary>
    /// Thrown when an validation attribute fails to validate.
    /// </summary>
    [Serializable]
    public class ValidationMetadataException : MetadataException
    {
        public ValidationMetadataException()
            : base(typeof(ValidationMetadataException).FullName)
        {
        }

        public ValidationMetadataException(string message)
            : base(message)
        {
        }

        protected ValidationMetadataException(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
        }

        public ValidationMetadataException(string message, Exception innerException)
            : base(message, innerException)
        {
        }
    }
}


text:
'use strict';

/**
 * @ngdoc directive
 * @name cat.directives.fieldErrors.info:catFieldErrorsInfo
 */
angular.module('cat.directives.fieldErrors.info', ['cat.service.validation'])
    .directive('catFieldErrorsInfo', function CatFieldErrorsInfoDirective() {
        return {
            replace: 'true',
            restrict: 'EA',
            scope: true,
            bindToController: true,
            controllerAs: 'catFieldErrorsInfo',
            require: ['catFieldErrorsInfo', '?^^catValidationGroup'],
            link: function (scope, elem, attr, controllers) {
                elem.addClass('cat-field-errors-info');

                var catFieldErrors = controllers[0];
                var catValidationGroupCtrl = controllers[1];
                if (!!catValidationGroupCtrl) {
                    catFieldErrors.contextId = catValidationGroupCtrl.getContextId();
                }
            },
            controller: function CatFieldErrorsController(/* CatValidationService */  catValidationService) {
                var that = this;

                this.hasErrors = function () {
                    return catValidationService.hasAnyFieldErrors(that.contextId);
                };
            },
            templateUrl: 'template/cat-field-errors-info.tpl.html'
        };
    });


text:
package io.material.demo.shrine.products;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import com.android.volley.toolbox.NetworkImageView;

/**
 * Activity that displays an individual product, including an image, name, and a short description.
 */
public class ItemActivity extends AppCompatActivity {
  private static final String PRODUCT_TITLE = "title";
  private static final String PRODUCT_URL = "url";
  private static final String PRODUCT_DESCRIPTION = "description";
  private static final String TAG = ItemActivity.class.getSimpleName();
  private String fabMessage;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.shrine_item_activity);
    initToolbar();
    populateProductViews();
    initFab();
  }

  public static void createItemActivityIntent(Context context, ProductEntry productEntry) {
    Intent intent = new Intent(context, ItemActivity.class);
    intent.putExtra(PRODUCT_TITLE, productEntry.title);
    intent.putExtra(PRODUCT_URL, productEntry.url);
    intent.putExtra(PRODUCT_DESCRIPTION, productEntry.description);
    context.startActivity(intent);
  }

  private void populateProductViews() {
    Bundle bundle = getIntent().getExtras();
    if (bundle == null) {
      String error = "Error retrieving product information.";
      Log.e(TAG, error);
      Snackbar.make(findViewById(R.id.ProductTitle), error, Snackbar.LENGTH_SHORT).show();
      fabMessage = error;
    } else {
      TextView productTitle = (TextView) findViewById(R.id.ProductTitle);
      productTitle.setText(bundle.getString(PRODUCT_TITLE));
      TextView productDescription = (TextView) findViewById(R.id.ProductDescription);
      productDescription.setText(bundle.getString(PRODUCT_DESCRIPTION));
      initSpinner();
      NetworkImageView productImage = (NetworkImageView) findViewById(R.id.ProductImage);
      ImageRequester.getInstance(this).setImageFromUrl(productImage, bundle.getString(PRODUCT_URL));
      fabMessage = getString(R.string.shrine_product_added_message);
    }
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    getMenuInflater().inflate(R.menu.shrine_toolbar_menu, menu);
    menu.findItem(R.id.ShrineToolbarFilterIcon).setVisible(false);
    return true;
  }

  private void initToolbar() {
    Toolbar toolbar = (Toolbar) findViewById(R.id.AppBar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
  }

  private void initFab() {
    findViewById(R.id.FloatingActionButton).setOnClickListener(clickListener);
  }

  private final OnClickListener clickListener = new OnClickListener() {
    @Override
    public void onClick(View v) {
      Snackbar.make(v, fabMessage, Snackbar.LENGTH_SHORT).show();
    }
  };

  private void initSpinner() {
    Spinner spinner = (Spinner) findViewById(R.id.QuantitySpinner);
    ArrayAdapter<CharSequence> adapter =
        ArrayAdapter.createFromResource(
            this, R.array.product_quantities, R.layout.shrine_spinner_item);
    spinner.setAdapter(adapter);
  }
}


text:
A personal URL shortener using GitHub Pages, for me.

## License

The MIT License (MIT)


text:
/*
 * aes132_impl.h
 *
 * Created: 9/21/2018 7:16:19 AM
 *  Author: pvallone
 */

#ifndef AES132_IMPL_H_
#define AES132_IMPL_H_

#define AES132SHOWCOMMANDBLOCK

#include "stdlib.h"
#include <string.h>
#include "aes132_helper.h"
#include "aes132_comm.h"
#include "aes132_comm_marshaling.h"
#include "keys.h"
struct aes132a_details myDetails;

uint8_t g_tx_buffer[AES132_COMMAND_SIZE_MAX];
uint8_t g_rx_buffer[AES132_RESPONSE_SIZE_MAX];
struct aes132h_nonce_s g_nonce;

void aes132_print_command_block(int ret_code);
void aes132_read_device_details(struct aes132a_details * details);
void aes132_read_small_zone(uint8_t *data, uint8_t bytesToRead);
void aes132_read_info(uint8_t selector, uint8_t out_data[2]);

void aes132_inbound_auth_key(uint8_t keyid, uint8_t *key, uint16_t usage);
void aes132_personalize(void);
void aes132_read_configuration(void);
void aes132_read_config(uint16_t addr);
void aes132_read_counter_config(uint16_t addr);
uint8_t aes132_lock_zone(uint8_t mode);
void aes132_nonce(void);
int aes132_key_create(uint8_t *newKey);
void aes132_keyload_to_key_memory(uint16_t childKeyID, uint8_t *parentKey, uint8_t *newKey);
void aes132_encrypt_decrypt_key(uint16_t eKeyId, uint8_t *ekey);
void aes132_outbound_auth(uint16_t keyid, uint8_t *key, uint8_t mode, uint16_t usage);
void aes132_mutual_auth(uint16_t keyid, uint8_t *key, uint8_t mode, uint8_t usage);
void aes132_reset_auth(void);
void aes132_encrypt_decrypt(void);
void aes132_encrypt_encwrite(void);
void aes132_encread_decrypt(void);
void aes132_write_user_zone(void);
void aes132_volatile_keyload(void);
void aes132_volatile_key_encrypt_decrypt(void);
void aes132_create_random_number(uint8_t * random);
void aes132_read_user_zone(void);
void aes132_write_user_zone_sn(void);
void aes132_encread_decrypt_sn(void);
void aes132_read_serial(uint8_t *sn);
void aes132_decrypt_read(void);
void aes132_write_user_zone_04(void);
void aes132_crunch(uint16_t count, uint8_t *outResult);

#endif /* AES132_IMPL_H_ */


text: """Unit tests module for Image Bundle."""


text:
use std::time::Duration;

use criterion::{criterion_group, criterion_main, Criterion};

fn run_query(s: &(tree_sitter::Tree, String), pattern: &str) {
    let tree = weggli::parse(pattern, false);

    let mut c = tree.walk();
    c.goto_first_child();
    let qt = weggli::builder::build_query_tree(pattern, &mut c, false, None).unwrap();

    let matches = qt.matches(s.0.root_node(), &s.1);
    for m in matches {
        m.display(&s.1, 500, 500, false);
    }
}

fn read_file(path: &str) -> String {
    let c = std::fs::read(path).unwrap();
    std::str::from_utf8(&c).unwrap().to_string()
}

fn bench(c: &mut Criterion) {
    let p = |path| {
        let source = read_file(path);
        (weggli::parse(&source, false), source)
    };

    let cluster = p("./third_party/examples/cluster.c");
    c.bench_function("cluster.c ", |b| {
        b.iter(|| run_query(&cluster, "{zmalloc($x);}"))
    });

    c.bench_function("cluster.c - 2", |b| {
        b.iter(|| run_query(&cluster, "{$t $x; $y = _($x); return $y;"))
    });

    let malloc = p("./third_party/examples/malloc.c");
    c.bench_function("malloc.c", |b| {
        b.iter(|| run_query(&malloc, "{$t $x; $x=_+_;}"))
    });

    let parser = p("./third_party/examples/parser.c");
    c.bench_function("parser.c", |b| {
        b.iter(|| run_query(&parser, "{$func($x); $func2($x);"))
    });
}

criterion_group! {
    name = benches;
    config = Criterion::default().significance_level(0.05).measurement_time(Duration::from_millis(20000)).sample_size(100);
    targets = bench
}
criterion_main!(benches);


text:
def total(numbers)
 result = 0
 numbers.each do |x|
    result = result + x
  end
  return result
end

# 4. sentence_maker pseudocode
# make sure all pseudocode is commented out!
# Input: Array of strings
# Output: single string, capitalized
# Steps to solve the problem.
# We want to write a method that will join the strings. This can be accomplished with each, but the join method was covered in the Chris Pine book so we decided to use it.

# # 5. sentence_maker initial solution
# def sentence_maker(words)
#   words.join(" ") "."
# end

# 6. sentence_maker refactored solution
def sentence_maker(words)
  words.join(" ").capitalize + "."
end


text:
package jp.natsukishina.orm4j8;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Collections;

import org.slf4j.LoggerFactory;

import jp.natsukishina.orm4j8.annotations.ForSinglePrimaryKey;
import jp.natsukishina.orm4j8.entity.BaseEntity;
import jp.natsukishina.orm4j8.exception.DBException;

/**
 * DB操作を扱うクラス。
 * @author 417.72ki
 *
 */
public class DB {
	private static Connection con;

	private static Type type = null;
	private static String host = null;
	private static int port = -1;
	private static String dbName = null;
	private static String user = null;
	private static String pass = null;
	private static String[] option = {};

	/**
	 * 初期設定を行います。

	 * configメソッドはデータベース接続前に必ず行うようにしてください。

	 * 推奨はstaticイニシャライザによる設定です。
	 * @param type データベース種別
	 * @param host データベースサーバのホスト
	 * @param port データベースサーバのポート
	 * @param dbName データベース名
	 * @param user データベースユーザ名
	 * @param pass データベースパスワード
	 * @param option その他オプション(key=value形式)
	 */
	public static void config(Type type, String host, int port, String dbName, String user, String pass,
			String... option) {
		DB.type = type;
		DB.host = host;
		DB.port = port;
		DB.dbName = dbName;
		DB.user = user;
		DB.pass = pass;
		DB.option = option;
		loadDriver();
	}

	/**
	 * 初期設定を行います

	 * 但し、ポートはDBMSのデフォルトポートを使用します
	 * configメソッドはデータベース接続前に必ず行うようにしてください。

	 * 推奨はstaticイニシャライザによる設定です。
	 * @param type データベース種別
	 * @param host データベースサーバのホスト
	 * @param dbName データベース名
	 * @param user データベースユーザ名
	 * @param pass データベースパスワード
	 * @param option その他オプション(key=value形式)
	 */
	public static void config(Type type, String host, String dbName, String user, String pass,
			String... option) {
		config(type, host, type.defaultPort, dbName, user, pass, option);
	}

	private DB() {
	}

	private static Connection getConnection() {
		try {
			if(con == null || con.isClosed()) {
				con = DriverManager.getConnection(createDBUrl(type, host, port, dbName), user, pass);
			}
			return con;
		} catch (Exception e) {
			throw new DBException(e);
		}
	}

	/**
	 * 検索用クエリを発行します。
	 * @param <E> データベースのテーブルを示す型
	 * @param clazz 検索対象テーブルのクラス
	 * @return 検索用クエリ
	 */
	public static <E extends BaseEntity> Query<E> find(Class<E> clazz) {
		if(clazz == null) {
			throw new IllegalArgumentException("clazz must not be null");
		}
		return Query.Builder.createFindQuery(getConnection(), clazz);
	}

	/**
	 * 主キーを元にエンティティを検索します
	 * @param <E> データベースのテーブルを示す型
	 * @param clazz 検索対象テーブルのクラスオブジェクト
	 * @param primaryKey 主キーの値
	 * @return 検索結果エンティティ
	 */
	@ForSinglePrimaryKey
	public static <E extends BaseEntity> E findByPrimary(Class<E> clazz, Object primaryKey) {
		if(clazz == null) {
			throw new IllegalArgumentException("clazz must not be null");
		}
		if(primaryKey == null) {
			throw new IllegalArgumentException("primaryKey must not be null");
		}
		return find(clazz).where(DBUtil.getPrimaryColumn(clazz), "=", primaryKey.toString()).execute().get();
	}

	/**
	 * エンティティをデータベースに登録・更新します。

	 * @param <E> データベースのテーブルを示す型
	 * @param element 登録するエンティティ
	 * @return 登録結果
	 */
	public static <E extends BaseEntity> boolean save(E element) {
		if (element == null) {
			throw new IllegalArgumentException("element must not be null");
		}
		if (DBUtil.getPrimaryValue(element) == null) {
			return Query.Builder.createInsertQuery(getConnection(), element).execute().result();
		}

		switch (Query.Builder.createUpdateQuery(getConnection(), element).execute().getUpdateCount()) {
		case 0:
			return Query.Builder.createInsertQuery(getConnection(), element).execute().result();
		case -1:
			return false;
		default:
			return true;
		}
	}

	/**
	 * エンティティをDBから削除します
	 * @param <E> データベースのテーブルを示す型
	 * @param element 削除するエンティティ
	 * @return 削除結果
	 */
	public static <E extends BaseEntity> boolean delete(E element) {
		if (element == null) {
			throw new IllegalArgumentException("element must not be null");
		}
		return Query.Builder.createDeleteQuery(getConnection(), element).execute().result();
	}

	@Deprecated
	static <E extends BaseEntity> Query<E> rawQuery(Class<E> clazz, String query) {
		if (clazz == null) {
			throw new IllegalArgumentException("class must not be null");
		}

		if(query == null || query.isEmpty()) {
			throw new IllegalArgumentException("query must not be empty");
		}

		return Query.Builder.createRawQuery(getConnection(), clazz, query);
	}

	private static String createDBUrl(Type type, String host, int port, String dbName) {
		if (port == -1) {
			port = type.defaultPort;
		}
		String url = String.format("jdbc:%1$s%2$s:%3$d/%4$s?%5$s", type.protocol, host, port, dbName,
				StringUtils.join(option, "&"));
		return url;
	}

	/**
	 * トランザクションを開始します

	 * 内部的には{@link java.sql.Connection}インスタンスのautoCommitプロパティをfalseにして

	 * 自動コミットをオフにしているだけです。

	 * 実際にトランザクションが開始されるタイミングはJDBCドライバに依存します。
	 */
	public static void beginTransaction() {
		try {
			if (!getConnection().getAutoCommit()) {
				return;
			}

			getConnection().setAutoCommit(false);
		} catch (SQLException e) {
			throw new DBException(e);
		}
	}

	/**
	 * トランザクションをコミットします
	 */
	public static void commit() {
		try {
			if (getConnection().getAutoCommit()) {
				return;
			}
			getConnection().commit();
			getConnection().setAutoCommit(true);

		} catch (SQLException e) {
			throw new DBException(e);
		}
	}

	/**
	 * トランザクションをロールバックします
	 */
	public static void rollback() {
		try {
			if (getConnection().getAutoCommit()) {
				return;
			}
			getConnection().rollback();
			getConnection().setAutoCommit(true);

		} catch (SQLException e) {
			throw new DBException(e);
		}
	}

	static {
		//JVMのシャットダウン時にコネクションの破棄とJDBCドライバーの参照破棄を行う
		Runtime.getRuntime().addShutdownHook(new Thread(() -> {
			LoggerFactory.getLogger(DB.class).debug("shutdown orm4j8");
			closeConnection();
			unloadDriver();
		}));
	}

	/**
	 * JDBCドライバーをロードする

	 * 参照の登録は各ドライバーのstaticイニシャライザに委譲している
	 */
	private static void loadDriver() {
		try {
			Class.forName(type.driverClass);
		} catch (Exception e) {
			throw new DBException(e);
		}
	}

	/**
	 * JDBCドライバーの参照を破棄する
	 */
	private static void unloadDriver() {
		Collections.list(DriverManager.getDrivers()).forEach(d -> {
			try {
				DriverManager.deregisterDriver(d);
			} catch (Exception e) {
				throw new DBException(e);
			}
		});
	}

	/**
	 * コネクションを破棄する
	 */
	private static void closeConnection() {
		try {
			if (con != null && !con.isClosed()) {
				con.close();
			}
			con = null;
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * データベース種別を定義するenum型

	 * 各値ごとにドライバクラス、プロトコル、デフォルトポートの情報を格納しています。
	 */
	public enum Type {
		/** MySQL */
		MYSQL("com.mysql.jdbc.Driver", "mysql://", 3306),
		/** PostgreSQL */
		POSTGRES("org.postgresql.Driver", "postgresql://", 5432),
		/** Oracle DB */
		ORACLE("oracle.jdbc.driver.OracleDriver", "oracle://", 1521),
		// SQLITE("org.sqlite.JDBC", "sqlite://", 4983)
		;

		/**	ドライバクラス名 */
		public final String driverClass;
		/** プロトコル */
		public final String protocol;
		/** DBMSで定義されているデフォルトポート */
		public final int defaultPort;

		private Type(String driverClass, String protocol, int defaultPort) {
			this.driverClass = driverClass;
			this.protocol = protocol;
			this.defaultPort = defaultPort;
		}
	}
}


text:
import { VNodeData, VNodeChildren, VirtualNode, HtmlTagNames } from '../../types';
import { h } from './h';

export interface HyperscriptHelperFn<T extends Node> {
  (): VirtualNode<T>;
  (classNameOrId: string, data: VNodeData, children: VNodeChildren): VirtualNode<T>;
  (classNameOrId: string, data: VNodeData): VirtualNode<T>;
  (classNameOrId: string, children: VNodeChildren): VirtualNode<T>;
  (classNameOrId: string): VirtualNode<T>;
  (data: VNodeData): VirtualNode<T>;
  (data: VNodeData, children: VNodeChildren): VirtualNode<T>;
  (children: VNodeChildren): VirtualNode<T>;
}

export function hh <T extends Node>(tagName: HtmlTagNames): HyperscriptHelperFn<T> {
  return function (): VirtualNode<T> {
    const selector = arguments[0];
    const data = arguments[1];
    const children = arguments[2];

    if (isSelector(selector))
      if (Array.isArray(data))
        return h(tagName + selector, {}, data);
      else if (typeof data === 'object')
        return h(tagName + selector, data, children);
      else
        return h(tagName + selector, data || {});

    if (Array.isArray(selector))
      return h(tagName, {}, selector);
    else if (typeof selector === 'object')
      return h(tagName, selector, data);
    else
      return h(tagName, selector || {});
  };
};

function isValidString (param: any): boolean {
  return typeof param === 'string' && param.length > 0;
}

function isSelector (param: any): boolean {
  return isValidString(param) && (param[0] === '.' || param[0] === '#');
}

export const a = hh<HTMLAnchorElement>('a');
export const abbr = hh('abbr');
export const acronym = hh('acronym');
export const address = hh('address');
export const applet = hh<HTMLAppletElement>('applet');
export const area = hh<HTMLAreaElement>('area');
export const article = hh('article');
export const aside = hh('aside');
export const audio = hh<HTMLAudioElement>('audio');
export const b = hh('b');
export const base = hh<HTMLBaseElement>('base');
export const basefont = hh<HTMLBaseFontElement>('basefont');
export const bdi = hh('bdi');
export const bdo = hh('bdo');
export const bgsound = hh('bgsound');
export const big = hh('big');
export const blink = hh('blink');
export const blockquote = hh('blockquote');
export const body = hh<HTMLBodyElement>('body');
export const br = hh<HTMLBRElement>('br');
export const button = hh<HTMLButtonElement>('button');
export const canvas = hh<HTMLCanvasElement>('canvas');
export const caption = hh('caption');
export const center = hh('center');
export const cite = hh('cite');
export const code = hh('code');
export const col = hh('col');
export const colgroup = hh('colgroup');
export const command = hh('command');
export const content = hh('content');
export const data = hh('data');
export const datalist = hh<HTMLDataListElement>('datalist');
export const dd = hh('dd');
export const del = hh('del');
export const details = hh('details');
export const dfn = hh('dfn');
export const dialog = hh('dialog');
export const dir = hh<HTMLDirectoryElement>('dir');
export const div = hh<HTMLDivElement>('div');
export const dl = hh('dl');
export const dt = hh('dt');
export const element = hh('element');
export const em = hh('em');
export const embed = hh('embed');
export const fieldset = hh<HTMLFieldSetElement>('fieldset');
export const figcaption = hh('figcaption');
export const figure = hh('figure');
export const font = hh<HTMLFontElement>('font');
export const footer = hh('footer');
export const form = hh<HTMLFormElement>('form');
export const frame = hh<HTMLFrameElement>('frame');
export const frameset = hh<HTMLFrameSetElement>('frameset');
export const h1 = hh<HTMLHeadingElement>('h1');
export const h2 = hh<HTMLHeadingElement>('h2');
export const h3 = hh<HTMLHeadingElement>('h3');
export const h4 = hh<HTMLHeadingElement>('h4');
export const h5 = hh<HTMLHeadingElement>('h5');
export const h6 = hh<HTMLHeadingElement>('h6');
export const head = hh('head');
export const header = hh('header');
export const hgroup = hh('hgroup');
export const hr = hh<HTMLHRElement>('hr');
export const html = hh<HTMLHtmlElement>('html');
export const img = hh<HTMLImageElement>('img');
export const input = hh<HTMLInputElement>('input');
export const ins = hh('ins');
export const isindex = hh('isindex');
export const kbd = hh('kbd');
export const keygen = hh('keygen');
export const label = hh<HTMLLabelElement>('label');
export const legend = hh('legend');
export const li = hh<HTMLLIElement>('li');
export const link = hh<HTMLLinkElement>('link');
export const listing = hh('listing');
export const main = hh('main');
export const map = hh<HTMLMapElement>('map');
export const mark = hh('mark');
export const marquee = hh<HTMLMarqueeElement>('marquee');
export const math = hh('math');
export const menu = hh<HTMLMenuElement>('menu');
export const menuitem = hh('menuitem');
export const meta = hh<HTMLMetaElement>('meta');
export const meter = hh('meter');
export const multicol = hh('multicol');
export const nav = hh('nav');
export const nextid = hh('nextid');
export const nobr = hh('nobr');
export const noembed = hh('noembed');
export const noframes = hh('noframes');
export const noscript = hh('noscript');
export const object = hh('object');
export const ol = hh('ol');
export const optgroup = hh('optgroup');
export const option = hh<HTMLOptionElement>('option');
export const output = hh('output');
export const p = hh<HTMLParagraphElement>('p');
export const param = hh<HTMLParamElement>('param');
export const picture = hh<HTMLPictureElement>('picture');
export const plaintext = hh('plaintext');
export const pre = hh('pre');
export const progress = hh<HTMLProgressElement>('progress');
export const q = hh<HTMLQuoteElement>('q');
export const rb = hh('rb');
export const rbc = hh('rbc');
export const rp = hh('rp');
export const rt = hh('rt');
export const rtc = hh('rtc');
export const ruby = hh('ruby');
export const s = hh('s');
export const samp = hh('samp');
export const script = hh<HTMLScriptElement>('script');
export const section = hh('section');
export const select = hh<HTMLSelectElement>('select');
export const shadow = hh('shadow');
export const small = hh('small');
export const source = hh<HTMLSourceElement>('source');
export const spacer = hh('spacer');
export const span = hh<HTMLSpanElement>('span');
export const strike = hh('strike');
export const strong = hh('strong');
export const style = hh('style');
export const sub = hh('sub');
export const summary = hh('summary');
export const sup = hh('sup');
export const table = hh<HTMLTableElement>('table');
export const tbody = hh('tbody');
export const td = hh('td');
export const template = hh('template');
export const textarea = hh('textarea');
export const tfoot = hh('tfoot');
export const th = hh('th');
export const tr = hh<HTMLTableRowElement>('tr');
export const track = hh('track');
export const tt = hh('tt');
export const u = hh('u');
export const ul = hh<HTMLUListElement>('ul');
export const video = hh<HTMLVideoElement>('video');
export const wbr = hh('wbr');
export const xmp = hh('xmp');


text:
<?php

defined ( 'BASEPATH' ) or exit ( 'No direct script access allowed' );

/**
 * Migration Class
 *
 * All migrations should implement this, forces up() and down() and gives
 * access to the CI super-global.
 *
 * @package CodeIgniter
 * @subpackage Libraries
 * @category Libraries
 * @author Reactor Engineers
 * @link
 *
 */
class CI_Migration {

	/**
	 * Whether the library is enabled
	 *
	 * @var bool
	 */
	protected $_migration_enabled = FALSE;

	/**
	 * Migration numbering type
	 *
	 * @var bool
	 */
	protected $_migration_type = 'sequential';

	/**
	 * Path to migration classes
	 *
	 * @var string
	 */
	protected $_migration_path = NULL;

	/**
	 * Current migration version
	 *
	 * @var mixed
	 */
	protected $_migration_version = 0;

	/**
	 * Database table with migration info
	 *
	 * @var string
	 */
	protected $_migration_table = 'migrations';

	/**
	 * Whether to automatically run migrations
	 *
	 * @var bool
	 */
	protected $_migration_auto_latest = FALSE;

	/**
	 * Migration basename regex
	 *
	 * @var bool
	 */
	protected $_migration_regex = NULL;

	/**
	 * Error message
	 *
	 * @var string
	 */
	protected $_error_string = '';

	/**
	 * Initialize Migration Class
	 *
	 * @param array $config
	 * @return void
	 */
	public function __construct($config = array()) {
		// Only run this constructor on main library load
		if (! in_array ( get_class ( $this ), array (
				'CI_Migration',
				config_item ( 'subclass_prefix' ) . 'Migration'
		), TRUE )) {
			return;
		}

		foreach ( $config as $key => $val ) {
			$this->{'_' . $key} = $val;
		}

		log_message ( 'info', 'Migrations Class Initialized' );

		// Are they trying to use migrations while it is disabled?
		if ($this->_migration_enabled !== TRUE) {
			show_error ( 'Migrations has been loaded but is disabled or set up incorrectly.' );
		}

		// If not set, set it
		$this->_migration_path !== '' or $this->_migration_path = APPPATH . 'migrations/';

		// Add trailing slash if not set
		$this->_migration_path = rtrim ( $this->_migration_path, '/' ) . '/';

		// Load migration language
		$this->lang->load ( 'migration' );

		// They'll probably be using dbforge
		$this->load->dbforge ();

		// Make sure the migration table name was set.
		if (empty ( $this->_migration_table )) {
			show_error ( 'Migrations configuration file (migration.php) must have "migration_table" set.' );
		}

		// Migration basename regex
		$this->_migration_regex = ($this->_migration_type === 'timestamp') ? '/^\d{14}_(\w+)$/' : '/^\d{3}_(\w+)$/';

		// Make sure a valid migration numbering type was set.
		if (! in_array ( $this->_migration_type, array (
				'sequential',
				'timestamp'
		) )) {
			show_error ( 'An invalid migration numbering type was specified: ' . $this->_migration_type );
		}

		// If the migrations table is missing, make it
		if (! $this->db->table_exists ( $this->_migration_table )) {
			$this->dbforge->add_field ( array (
					'version' => array (
							'type' => 'BIGINT',
							'constraint' => 20
					)
			) );

			$this->dbforge->create_table ( $this->_migration_table, TRUE );

			$this->db->insert ( $this->_migration_table, array (
					'version' => 0
			) );
		}

		// Do we auto migrate to the latest migration?
		if ($this->_migration_auto_latest === TRUE && ! $this->latest ()) {
			show_error ( $this->error_string () );
		}
	}

	// --------------------------------------------------------------------

	/**
	 * Migrate to a schema version
	 *
	 * Calls each migration step required to get to the schema version of
	 * choice
	 *
	 * @param string $target_version
	 *        	version
	 * @return mixed if already latest, FALSE if failed, string if upgraded
	 */
	public function version($target_version) {
		// Note: We use strings, so that timestamp versions work on 32-bit systems
		$current_version = $this->_get_version ();

		if ($this->_migration_type === 'sequential') {
			$target_version = sprintf ( '%03d', $target_version );
		} else {
			$target_version = ( string ) $target_version;
		}

		$migrations = $this->find_migrations ();

		if ($target_version > 0 && ! isset ( $migrations [$target_version] )) {
			$this->_error_string = sprintf ( $this->lang->line ( 'migration_not_found' ), $target_version );
			return FALSE;
		}

		if ($target_version > $current_version) {
			// Moving Up
			$method = 'up';
		} else {
			// Moving Down, apply in reverse order
			$method = 'down';
			krsort ( $migrations );
		}

		if (empty ( $migrations )) {
			return TRUE;
		}

		$previous = FALSE;

		// Validate all available migrations, and run the ones within our target range
		foreach ( $migrations as $number => $file ) {
			// Check for sequence gaps
			if ($this->_migration_type === 'sequential' && $previous !== FALSE && abs ( $number - $previous ) > 1) {
				$this->_error_string = sprintf ( $this->lang->line ( 'migration_sequence_gap' ), $number );
				return FALSE;
			}

			include_once ($file);
			$class = 'Migration_' . ucfirst ( strtolower ( $this->_get_migration_name ( basename ( $file, '.php' ) ) ) );

			// Validate the migration file structure
			if (! class_exists ( $class, FALSE )) {
				$this->_error_string = sprintf ( $this->lang->line ( 'migration_class_doesnt_exist' ), $class );
				return FALSE;
			}

			$previous = $number;

			// Run migrations that are inside the target range
			if (($method === 'up' && $number > $current_version && $number <= $target_version) or ($method === 'down' && $number <= $current_version && $number > $target_version)) {
				$instance = new $class ();
				if (! is_callable ( array (
						$instance,
						$method
				) )) {
					$this->_error_string = sprintf ( $this->lang->line ( 'migration_missing_' . $method . '_method' ), $class );
					return FALSE;
				}

				log_message ( 'debug', 'Migrating ' . $method . ' from version ' . $current_version . ' to version ' . $number );
				call_user_func ( array (
						$instance,
						$method
				) );
				$current_version = $number;
				$this->_update_version ( $current_version );
			}
		}

		// This is necessary when moving down, since the the last migration applied
		// will be the down() method for the next migration up from the target
		if ($current_version != $target_version) {
			$current_version = $target_version;
			$this->_update_version ( $current_version );
		}

		log_message ( 'debug', 'Finished migrating to ' . $current_version );

		return $current_version;
	}

	// --------------------------------------------------------------------

	/**
	 * Sets the schema to the latest migration
	 *
	 * @return mixed if already latest, FALSE if failed, string if upgraded
	 */
	public function latest() {
		$migrations = $this->find_migrations ();

		if (empty ( $migrations )) {
			$this->_error_string = $this->lang->line ( 'migration_none_found' );
			return FALSE;
		}

		$last_migration = basename ( end ( $migrations ) );

		// Calculate the last migration step from existing migration
		// filenames and proceed to the standard version migration
		return $this->version ( $this->_get_migration_number ( $last_migration ) );
	}

	// --------------------------------------------------------------------

	/**
	 * Sets the schema to the migration version set in config
	 *
	 * @return mixed if already current, FALSE if failed, string if upgraded
	 */
	public function current() {
		return $this->version ( $this->_migration_version );
	}

	// --------------------------------------------------------------------

	/**
	 * Error string
	 *
	 * @return string message returned as a string
	 */
	public function error_string() {
		return $this->_error_string;
	}

	// --------------------------------------------------------------------

	/**
	 * Retrieves list of available migration scripts
	 *
	 * @return array of migration file paths sorted by version
	 */
	public function find_migrations() {
		$migrations = array ();

		// Load all *_*.php files in the migrations path
		foreach ( glob ( $this->_migration_path . '*_*.php' ) as $file ) {
			$name = basename ( $file, '.php' );

			// Filter out non-migration files
			if (preg_match ( $this->_migration_regex, $name )) {
				$number = $this->_get_migration_number ( $name );

				// There cannot be duplicate migration numbers
				if (isset ( $migrations [$number] )) {
					$this->_error_string = sprintf ( $this->lang->line ( 'migration_multiple_version' ), $number );
					show_error ( $this->_error_string );
				}

				$migrations [$number] = $file;
			}
		}

		ksort ( $migrations );
		return $migrations;
	}

	// --------------------------------------------------------------------

	/**
	 * Extracts the migration number from a filename
	 *
	 * @param string $migration
	 * @return string portion of a migration filename
	 */
	protected function _get_migration_number($migration) {
		return sscanf ( $migration, '%[0-9]+', $number ) ? $number : '0';
	}

	// --------------------------------------------------------------------

	/**
	 * Extracts the migration class name from a filename
	 *
	 * @param string $migration
	 * @return string portion of a migration filename
	 */
	protected function _get_migration_name($migration) {
		$parts = explode ( '_', $migration );
		array_shift ( $parts );
		return implode ( '_', $parts );
	}

	// --------------------------------------------------------------------

	/**
	 * Retrieves current schema version
	 *
	 * @return string migration version
	 */
	protected function _get_version() {
		$row = $this->db->select ( 'version' )->get ( $this->_migration_table )->row ();
		return $row ? $row->version : '0';
	}

	// --------------------------------------------------------------------

	/**
	 * Stores the current schema version
	 *
	 * @param string $migration
	 * @return void
	 */
	protected function _update_version($migration) {
		$this->db->update ( $this->_migration_table, array (
				'version' => $migration
		) );
	}

	// --------------------------------------------------------------------

	/**
	 * Enable the use of CI super-global
	 *
	 * @param string $var
	 * @return mixed
	 */
	public function __get($var) {
		return get_instance ()->$var;
	}
}


text:
"""Hue sensor entities."""
from aiohue.sensors import (
    TYPE_ZLL_LIGHTLEVEL,
    TYPE_ZLL_ROTARY,
    TYPE_ZLL_SWITCH,
    TYPE_ZLL_TEMPERATURE,
)

from homeassistant.const import (
    DEVICE_CLASS_BATTERY,
    DEVICE_CLASS_ILLUMINANCE,
    DEVICE_CLASS_TEMPERATURE,
    LIGHT_LUX,
    PERCENTAGE,
    TEMP_CELSIUS,
)
from homeassistant.helpers.entity import Entity

from .const import DOMAIN as HUE_DOMAIN
from .sensor_base import SENSOR_CONFIG_MAP, GenericHueSensor, GenericZLLSensor

LIGHT_LEVEL_NAME_FORMAT = "{} light level"
REMOTE_NAME_FORMAT = "{} battery level"
TEMPERATURE_NAME_FORMAT = "{} temperature"

async def async_setup_entry(hass, config_entry, async_add_entities):
    """Defer sensor setup to the shared sensor module."""
    await hass.data[HUE_DOMAIN][
        config_entry.entry_id
    ].sensor_manager.async_register_component("sensor", async_add_entities)

class GenericHueGaugeSensorEntity(GenericZLLSensor, Entity):
    """Parent class for all 'gauge' Hue device sensors."""

    async def _async_update_ha_state(self, *args, **kwargs):
        await self.async_update_ha_state(self, *args, **kwargs)

class HueLightLevel(GenericHueGaugeSensorEntity):
    """The light level sensor entity for a Hue motion sensor device."""

    device_class = DEVICE_CLASS_ILLUMINANCE
    unit_of_measurement = LIGHT_LUX

    @property
    def state(self):
        """Return the state of the device."""
        if self.sensor.lightlevel is None:
            return None

        # https://developers.meethue.com/develop/hue-api/supported-devices/#clip_zll_lightlevel
        # Light level in 10000 log10 (lux) +1 measured by sensor. Logarithm
        # scale used because the human eye adjusts to light levels and small
        # changes at low lux levels are more noticeable than at high lux
        # levels.
        return round(float(10 ** ((self.sensor.lightlevel - 1) / 10000)), 2)

    @property
    def device_state_attributes(self):
        """Return the device state attributes."""
        attributes = super().device_state_attributes
        attributes.update(
            {
                "lightlevel": self.sensor.lightlevel,
                "daylight": self.sensor.daylight,
                "dark": self.sensor.dark,
                "threshold_dark": self.sensor.tholddark,
                "threshold_offset": self.sensor.tholdoffset,
            }
        )
        return attributes

class HueTemperature(GenericHueGaugeSensorEntity):
    """The temperature sensor entity for a Hue motion sensor device."""

    device_class = DEVICE_CLASS_TEMPERATURE
    unit_of_measurement = TEMP_CELSIUS

    @property
    def state(self):
        """Return the state of the device."""
        if self.sensor.temperature is None:
            return None

        return self.sensor.temperature / 100

class HueBattery(GenericHueSensor):
    """Battery class for when a batt-powered device is only represented as an event."""

    @property
    def unique_id(self):
        """Return a unique identifier for this device."""
        return f"{self.sensor.uniqueid}-battery"

    @property
    def state(self):
        """Return the state of the battery."""
        return self.sensor.battery

    @property
    def device_class(self):
        """Return the class of the sensor."""
        return DEVICE_CLASS_BATTERY

    @property
    def unit_of_measurement(self):
        """Return the unit of measurement of this entity."""
        return PERCENTAGE

SENSOR_CONFIG_MAP.update(
    {
        TYPE_ZLL_LIGHTLEVEL: {
            "platform": "sensor",
            "name_format": LIGHT_LEVEL_NAME_FORMAT,
            "class": HueLightLevel,
        },
        TYPE_ZLL_TEMPERATURE: {
            "platform": "sensor",
            "name_format": TEMPERATURE_NAME_FORMAT,
            "class": HueTemperature,
        },
        TYPE_ZLL_SWITCH: {
            "platform": "sensor",
            "name_format": REMOTE_NAME_FORMAT,
            "class": HueBattery,
        },
        TYPE_ZLL_ROTARY: {
            "platform": "sensor",
            "name_format": REMOTE_NAME_FORMAT,
            "class": HueBattery,
        },
    }
)


text:
Gojira
======
A nifty lisp interpreter

Gojira is a dialect of lisp derived primarily from scheme. It's intended to be
a somewhat minimal but entirely usable language, with some experimental ideas
and practicality as a goal.

It is something of a pet project for me; a bit more serious than a toy project,
but I'm not going to advise you use it over python, etc (yet).

It's also fairly portable, relying on a small subset of the libc for core functionality.

To build
- - - - -

    git clone --recursive https://github.com/dragontux/gojira.git
    cd gojira
    ./configure   # the default prefix is /usr/local, use --prefix= to change it
    make
    make install
    make test

To run a file,

    gojira example/colors.scm

    # To run multiple files in the same environment:
    gojira example/colors.scm example/calc.scm

    # To continue interpreting after finished running:
    gojira -i example/fizzbuzz.scm

Status
- - - -

Currently supports:

- Decent scheme support with some standard operators (+, -, map, iota, etc)
- Mark-and-sweep garbage collection
- UTF-8 variable names
- (Incomplete) syntax-rules
- Sort of python-ish iterators
- Hashmaps
- Applicable booleans
- Networking with TCP
- A simple module system
- Modules for documention, ansi terminal colors, input prompts, ...
- A (also incomplete) C API for using gojira as an extension language
- some r6rs bytevector functions
- And more!
- Order now and recieve up to 20% more source

Coming soon:

- Tail call elimination
- First-class continuations
- External (C function) linking


text:
<?php

use \Core\Page;
use \Core\View;

class Basket extends Page{
	public function home(){
		$data = $this->getData();

		return (new View('basket/home.php'))
			->assign('title', 'basket')
			->assign('data', $data)
			->render();
	}

	public function add(){
		$data = $this->getData();
		$item = $_GET['item'];

		if(isset($data[$item])){
			if(isset($_SESSION['items'][$item])){
				$_SESSION['items'][$item]['quantity']++;
			}
			else{
				$_SESSION['items'][$item]['quantity'] = 1;
				$_SESSION['items'][$item]['item'] = $data[$item];
			}
		}

		header('location:/'.\Core\Url::get('index-home'));
	}

	public function edit(){
		$data = $this->getData();
		$item = $_GET['item'];
		$quantity = $_GET['quantity'];

		if(isset($data[$item])){
			if(isset($_SESSION['items'][$item])){
				$_SESSION['items'][$item]['quantity'] = $quantity;
			}
		}

		header('location:'.\Core\Url::get('basket-home'));
	}

	public function delete(){
		$item = $_GET['item'];
		unset($_SESSION['items'][$item]);

		header('location:'.\Core\Url::get('basket-home'));
	}

	private function getData(){
		return json_decode(file_get_contents('data.json'), true);
	}
}


text:
using System;
using System.Collections.Generic;

namespace Goofy.Core.Entity.Base
{
    public interface IEntityJsonConfigProvider
    {
        IDictionary<string, object> GetConfigurations<TEntity>() where TEntity : class;
        IDictionary<string, object> GetConfigurations(Type entityType);
    }
}


text:
'use strict';

var defaultCompare = require('./common/default-compare');

/**
 * Sorts an array using top down merge sort.
 * @param {Array} array The array to sort.
 * @param {function} compare The compare function.
 * @returns The sorted array.
 */
function sort(array, compare) {
  if (array.length <= 1) {
    return array;
  }

  var i;
  var middle = Math.floor(array.length / 2);
  var left = new Array(middle);
  var right = new Array(array.length - middle);

  for (i = 0; i < left.length; i++) {
    left[i] = array[i];
  }
  for (i = 0; i < right.length; i++) {
    right[i] = array[i + left.length];
  }

  return merge(sort(left, compare), sort(right, compare), compare);
}

/**
 * Merges two arrays in to a new array.
 * @param {Array} left The first array.
 * @param {Array} left The second array.
 * @param {function} compare The compare function.
 * @return The merged array.
 */
function merge(left, right, compare) {
  var result = [];
  var leftIndex = 0;
  var rightIndex = 0;

  while (leftIndex < left.length || rightIndex < right.length) {
    if (leftIndex < left.length && rightIndex < right.length) {
      if (compare(left[leftIndex], right[rightIndex]) <= 0) {
        result.push(left[leftIndex++]);
      } else {
        result.push(right[rightIndex++]);
      }
    } else if (leftIndex < left.length) {
      result.push(left[leftIndex++]);
    } else if (rightIndex < right.length) {
      result.push(right[rightIndex++]);
    }
  }
  return result;
}

/**
 * Sorts an array using top down merge sort.
 * @param {Array} array The array to sort.
 * @param {function} customCompare A custom compare function.
 * @returns The sorted array.
 */
module.exports = function (array, customCompare) {
  var compare = customCompare || defaultCompare;
  return sort(array, compare);
};


text:
package org.apache.hadoop.hdds.scm.container.placement.metrics;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;

/**
 * SCM Node Metric that is used in the placement classes.
 */
public class SCMNodeMetric implements DatanodeMetric<SCMNodeStat, Long> {
  private SCMNodeStat stat;

  /**
   * Constructs an SCMNode Metric.
   *
   * @param stat - SCMNodeStat.
   */
  public SCMNodeMetric(SCMNodeStat stat) {
    this.stat = stat;
  }

  /**
   * Set the capacity, used and remaining space on a datanode.
   *
   * @param capacity in bytes
   * @param used in bytes
   * @param remaining in bytes
   */
  @VisibleForTesting
  public SCMNodeMetric(long capacity, long used, long remaining) {
    this.stat = new SCMNodeStat();
    this.stat.set(capacity, used, remaining);
  }

  /**
   *
   * @param o - Other Object
   * @return - True if *this* object is greater than argument.
   */
  @Override
  public boolean isGreater(SCMNodeStat o) {
    Preconditions.checkNotNull(this.stat, "Argument cannot be null");
    Preconditions.checkNotNull(o, "Argument cannot be null");

    // if zero, replace with 1 for the division to work.
    long thisDenominator = (this.stat.getCapacity().get() == 0)
        ? 1 : this.stat.getCapacity().get();
    long otherDenominator = (o.getCapacity().get() == 0)
        ? 1 : o.getCapacity().get();

    float thisNodeWeight =
        stat.getScmUsed().get() / (float) thisDenominator;

    float oNodeWeight =
        o.getScmUsed().get() / (float) otherDenominator;

    if (Math.abs(thisNodeWeight - oNodeWeight) > 0.000001) {
      return thisNodeWeight > oNodeWeight;
    }
    // if these nodes are have similar weight then return the node with more
    // free space as the greater node.
    return stat.getRemaining().isGreater(o.getRemaining().get());
  }

  /**
   * Inverse of isGreater.
   *
   * @param o - other object.
   * @return True if *this* object is Lesser than argument.
   */
  @Override
  public boolean isLess(SCMNodeStat o) {
    Preconditions.checkNotNull(o, "Argument cannot be null");

    // if zero, replace with 1 for the division to work.
    long thisDenominator = (this.stat.getCapacity().get() == 0)
        ? 1 : this.stat.getCapacity().get();
    long otherDenominator = (o.getCapacity().get() == 0)
        ? 1 : o.getCapacity().get();

    float thisNodeWeight =
        stat.getScmUsed().get() / (float) thisDenominator;

    float oNodeWeight =
        o.getScmUsed().get() / (float) otherDenominator;

    if (Math.abs(thisNodeWeight - oNodeWeight) > 0.000001) {
      return thisNodeWeight < oNodeWeight;
    }

    // if these nodes are have similar weight then return the node with less
    // free space as the lesser node.
    return stat.getRemaining().isLess(o.getRemaining().get());
  }

  /**
   * Returns true if the object has same values. Because of issues with
   * equals, and loss of type information this interface supports isEqual.
   *
   * @param o object to compare.
   * @return True, if the values match.
   * TODO : Consider if it makes sense to add remaining to this equation.
   */
  @Override
  public boolean isEqual(SCMNodeStat o) {
    float thisNodeWeight = stat.getScmUsed().get() / (float)
        stat.getCapacity().get();
    float oNodeWeight = o.getScmUsed().get() / (float) o.getCapacity().get();
    return Math.abs(thisNodeWeight - oNodeWeight) < 0.000001;
  }

  /**
   * A resourceCheck, defined by resourceNeeded.
   * For example, S could be bytes required
   * and DatanodeMetric can reply by saying it can be met or not.
   *
   * @param resourceNeeded -  ResourceNeeded in its own metric.
   * @return boolean, True if this resource requirement can be met.
   */
  @Override
  public boolean hasResources(Long resourceNeeded) {
    return false;
  }

  /**
   * Returns the metric.
   *
   * @return T, the object that represents this metric.
   */
  @Override
  public SCMNodeStat get() {
    return stat;
  }

  /**
   * Sets the value of this metric.
   *
   * @param value - value of the metric.
   */
  @Override
  public void set(SCMNodeStat value) {
    stat.set(value.getCapacity().get(), value.getScmUsed().get(),
        value.getRemaining().get());
  }

  /**
   * Adds a value of to the base.
   *
   * @param value - value
   */
  @Override
  public void add(SCMNodeStat value) {
    stat.add(value);
  }

  /**
   * subtract a value.
   *
   * @param value value
   */
  @Override
  public void subtract(SCMNodeStat value) {
    stat.subtract(value);
  }

  /**
   * Compares this object with the specified object for order.  Returns a
   * negative integer, zero, or a positive integer as this object is less
   * than, equal to, or greater than the specified object.
   *
   * @param o the object to be compared.
   * @return a negative integer, zero, or a positive integer as this object is
   * less than, equal to, or greater than the specified object.
   * @throws NullPointerException if the specified object is null
   * @throws ClassCastException   if the specified object's type prevents it
   *                              from being compared to this object.
   */
  @Override
  public int compareTo(SCMNodeStat o) {
    if (isEqual(o)) {
      return 0;
    }
    if (isGreater(o)) {
      return 1;
    } else {
      return -1;
    }
  }

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

    SCMNodeMetric that = (SCMNodeMetric) o;

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

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


text:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">
    <data>
        <variable name="tweet" type="com.codepath.apps.twitterclient.models.Tweet"/>
    </data>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <LinearLayout
            android:orientation="vertical"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:id="@+id/activity_tweet"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            tools:context="com.codepath.apps.twitterclient.activities.TweetActivity">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="?attr/colorPrimary"
                app:layout_scrollFlags="scroll|enterAlways"/>
            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/dp15">
                <LinearLayout
                    android:id="@+id/lltop"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">
                    <ImageView
                        android:id="@+id/ivProfile"
                        android:layout_width="@dimen/dp50"
                        android:layout_height="@dimen/dp50"
                        tools:src="@drawable/ic_twitter"
                        android:tint="@color/primary"
                        android:layout_marginRight="@dimen/dp10"/>
                    <LinearLayout
                        android:layout_gravity="center"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:orientation="vertical"
                        android:layout_toRightOf="@id/ivProfile"
                        android:gravity="center_vertical"
                        android:id="@+id/llInfo">
                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:id="@+id/tvScreenname"
                            tools:text="Rocio Romero"
                            android:text="@{tweet.user.screenName}"
                            android:textStyle="bold"
                            android:textColor="@color/primary_dark"/>
                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:id="@+id/tvUsername"
                            android:text="@{`@` + tweet.user.name}"
                            android:textColor="@color/lightText"
                            tools:text="@string/example_username"/>
                    </LinearLayout>
                </LinearLayout>

                <LinearLayout
                    android:id="@+id/llExtra"
                    android:layout_below="@id/lltop"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="@dimen/dp10">
                    <ImageView
                        android:id="@+id/ivExtra"
                        android:layout_width="@dimen/dp10"
                        android:layout_height="@dimen/dp10"
                        android:background="@drawable/ic_twitter_retweet"
                        android:layout_gravity="center_vertical"
                        android:layout_marginRight="6dp"/>
                    <TextView
                        android:id="@+id/tvExtra"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textColor="@color/lightText"
                        android:layout_marginLeft="4dp"
                        android:text="Reply to"/>
                </LinearLayout>
                <TextView
                    android:id="@+id/tvBody"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/llExtra"
                    android:layout_marginTop="@dimen/dp10"
                    android:layout_marginBottom="@dimen/dp20"
                    android:textSize="@dimen/dp24"
                    android:text="@{tweet.body}"
                    android:autoLink="all"
                    tools:text="@string/example_body"/>

                <FrameLayout
                    android:id="@+id/flMedia"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_margin="@dimen/dp5"
                    android:maxHeight="@dimen/dp200"
                    android:layout_below="@id/tvBody">
                    <ImageView
                        android:id="@+id/ivMedia"
                        android:scaleType="fitCenter"
                        android:adjustViewBounds="true"
                        android:maxHeight="@dimen/dp200"
                        android:visibility="gone"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        tools:src="@mipmap/ic_launcher"
                        android:layout_margin="@dimen/dp5"/>

                    <VideoView
                        android:id="@+id/vvVideo"
                        android:layout_width="match_parent"
                        android:visibility="gone"
                        android:layout_height="wrap_content" />
                </FrameLayout>
                <TextView
                    android:id="@+id/tvDate"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    tools:text="@string/example_date_format"
                    android:layout_below="@+id/flMedia"
                    android:text='@{tweet.formattedDate}'
                    android:textColor="@color/lightText"
                    android:layout_marginBottom="@dimen/dp10"/>
                <View
                    android:layout_width="match_parent"
                    android:id="@+id/viewt"
                    android:layout_height="1dp"
                    android:background="@color/separators"
                    android:layout_below="@id/tvDate"/>
                <LinearLayout
                    android:id="@+id/llRTL"
                    android:orientation="horizontal"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@id/viewt"
                    android:layout_marginTop="@dimen/dp5"
                    android:layout_marginBottom="@dimen/dp5"
                    android:gravity="left">

                    <TextView
                        android:id="@+id/tvRT"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@{tweet.RTCount + ` Retweets`}"
                        android:textColor="@color/primary"
                        android:textSize="@dimen/dp15"
                        tools:text="@string/example_following" />
                    <TextView
                        android:id="@+id/tvLikes"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:paddingLeft="@dimen/dp20"
                        android:textSize="@dimen/dp15"
                        android:textColor="@color/primary"
                        android:text="@{tweet.liked + ` Likes`}"
                        tools:text="@string/example_followers"/>
                </LinearLayout>

                <View
                    android:layout_width="match_parent"
                    android:id="@+id/viewm"
                    android:layout_height="1dp"
                    android:background="@color/separators"
                    android:layout_below="@id/llRTL"/>
                <LinearLayout
                    android:id="@+id/llButtons"
                    android:orientation="horizontal"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@id/viewm"
                    android:gravity="center"
                    android:layout_marginTop="@dimen/dp10">
                    <ImageButton
                        android:id="@+id/btReply"
                        android:layout_width="@dimen/dp24"
                        android:layout_height="@dimen/dp20"
                        android:background="@drawable/ic_twitter_reply_outline"/>
                    <Space
                        android:layout_width="0dp"
                        android:layout_height="1dp"
                        android:layout_weight="1" >
                    </Space>
                    <ImageButton
                        android:id="@+id/btRt"
                        android:layout_width="@dimen/dp24"
                        android:layout_height="@dimen/dp20"
                        android:background="@drawable/ic_twitter_retweet"/>
                    <Space
                        android:layout_width="0dp"
                        android:layout_height="1dp"
                        android:layout_weight="1" >
                    </Space>
                    <ImageButton
                        android:id="@+id/btLike"
                        android:layout_width="@dimen/dp24"
                        android:layout_height="@dimen/dp20"
                        android:background="@drawable/ic_twitter_like_outline"/>
                    <Space
                        android:layout_width="0dp"
                        android:layout_height="1dp"
                        android:layout_weight="1" >
                    </Space>
                    <ImageButton
                        android:id="@+id/btMessage"
                        android:layout_width="@dimen/dp24"
                        android:layout_height="@dimen/dp20"
                        android:background="@drawable/ic_twitter_newmessage"/>
                </LinearLayout>

            </RelativeLayout>
            <View
                android:layout_width="match_parent"
                android:id="@+id/viewb"
                android:layout_height="1dp"
                android:background="@color/separators"
                android:layout_below="@id/llButtons"/>

        </LinearLayout>
    </ScrollView>
</layout>


text:
title: Rand Paul, Kentucky Senator
name: Rand Paul
avatar: /ui/img/avatars/Rand_Paul.jpg
party: republican
state: kentucky
type: senator
lasthall: 2016-09-16
phone: (202) 224-4343
never:
twitter: SenRandPaul
---


text:
module Gitlab
  module Metrics
    # Module for gathering system/process statistics such as the memory usage.
    #
    # This module relies on the /proc filesystem being available. If /proc is
    # not available the methods of this module will be stubbed.
    module System
      if File.exist?('/proc')
        # Returns the current process' memory usage in bytes.
        def self.memory_usage
          mem   = 0
          match = File.read('/proc/self/status').match(/VmRSS:\s+(\d+)/)

          if match and match[1]
            mem = match[1].to_f * 1024
          end

          mem
        end

        def self.file_descriptor_count
          Dir.glob('/proc/self/fd/*').length
        end
      else
        def self.memory_usage
          0.0
        end

        def self.file_descriptor_count
          0
        end
      end

      # THREAD_CPUTIME is not supported on OS X
      if Process.const_defined?(:CLOCK_THREAD_CPUTIME_ID)
        def self.cpu_time
          Process.
            clock_gettime(Process::CLOCK_THREAD_CPUTIME_ID, :millisecond).to_f
        end
      else
        def self.cpu_time
          Process.
            clock_gettime(Process::CLOCK_PROCESS_CPUTIME_ID, :millisecond).to_f
        end
      end

      # Returns the current real time in a given precision.
      #
      # Returns the time as a Float.
      def self.real_time(precision = :millisecond)
        Process.clock_gettime(Process::CLOCK_REALTIME, precision).to_f
      end

      # Returns the current monotonic clock time in a given precision.
      #
      # Returns the time as a Float.
      def self.monotonic_time(precision = :millisecond)
        Process.clock_gettime(Process::CLOCK_MONOTONIC, precision).to_f
      end
    end
  end
end