text:
package com.sicao.smartwine;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.sicao.smartwine.xapp.AppManager;
import com.sicao.smartwine.xdata.XUserData;
import com.sicao.smartwine.xdevice.entity.XProductEntity;
import com.sicao.smartwine.xdevice.entity.XProductHistoryEntity;
import com.sicao.smartwine.xdevice.entity.XWineEntity;
import com.sicao.smartwine.xhttp.XApiCallBack;
import com.sicao.smartwine.xhttp.XApiException;
import com.sicao.smartwine.xhttp.XApisCallBack;
import com.sicao.smartwine.xhttp.XCallBack;
import com.sicao.smartwine.xhttp.XConfig;
import com.sicao.smartwine.xhttp.XHttpUtil;
import com.sicao.smartwine.xuser.address.XAddressEntity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xclcharts.chart.PointD;

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

/**
 * 非硬件部分API
 */

public class SmartSicaoApi implements XApiException {

    public static String URL = "http://www.putaoji.com/apiwine/";

    /***
     * 检测接口执行状态status
     *
     * @param object 接口返回对象
     * @return 是否执行OK
     */
    public boolean status(JSONObject object) throws JSONException {
        return object.getBoolean("status");
    }

    /***
     * 接口错误信息打印
     *
     * @param error
     */
    @Override
    public void error(String error) {
        if (XConfig.DEBUG)
            Log.i(XConfig.LOG_TAG, error);
    }

    /***
     * 日志打印
     *
     * @param logs
     */
    public static void log(String logs) {
        if (XConfig.DEBUG)
            Log.i(XConfig.LOG_TAG, logs);
    }

    /***
     * 为url设置通用参数
     *
     * @param api     对应的具体接口(如apix/pubaTopic/lists)
     * @param context 上下文对象
     * @return 设置参数后的url
     */
    public String configParamsUrl(String api, Context context) {
        return URL + api + "?user_token=" + XUserData.getToken(context)
                + "&uid=" + XUserData.getUID(context) + "&api_version="
                + XConfig.API_VERSION;
    }

    /***
     * 接口校验参数之校验码的获取
     *
     * @param context
     * @param callback
     */
    public void getCode(final Context context, final XApiCallBack callback) {
        String url = configParamsUrl("ContentKey/getNewInfo", context);
        XHttpUtil http = new XHttpUtil(context);
        http.get(url, new XCallBack() {
            @Override
            public void success(String response) {
                try {
                    JSONObject object = new JSONObject(response);
                    log("切换KEY----" + response);
                    if (status(object)) {
                        if (null != callback) {
                            callback.response(object.getJSONObject("data").getString("newKey"));
                        }
                    } else {
                        if (null != callback) {
                            callback.response(XUserData.getCode(context));
                        }
                    }
                } catch (JSONException e) {
                    if (null != callback) {
                        callback.response(XUserData.getCode(context));
                    }
                }
            }

            @Override
            public void fail(String response) {
                if (null != callback) {
                    callback.response(XUserData.getCode(context));
                }
                error(response);
            }
        });
    }

    /***
     * 登录葡萄集平台,获取该平台中对应帐号的uid以便于登录机智云平台
     *
     * @param context      上下文对象
     * @param username     用户手机号
     * @param password     用户密码
     * @param xApiCallBack 结果回调
     */
    public void login(final Context context, final String username, final String password, final XApiCallBack xApiCallBack, final XApiException xApiException) {
        String url = configParamsUrl("user/login?mobile=" + username + "&value=" + password + "&type=2", context);
        log(url);
        XHttpUtil http = new XHttpUtil(context);
        http.get(url, new XCallBack() {
            @Override
            public void success(String response) {
                try {
                    JSONObject object = new JSONObject(response);
                    log("login----" + response);
                    if (status(object)) {
                        XUserData.saveToken(context, object.getJSONObject("data").getString("user_token"));
                        XUserData.setUID(context, object.getJSONObject("data").getString("uid"));
                        XUserData.setPassword(context, password);
                        XUserData.setUserName(context, username);
                        if (null != xApiCallBack) {
                            xApiCallBack.response("success");
                        }
                    } else {
                        error(object.getString("message"));
                        if (null != xApiException) {
                            xApiException.error(object.getString("message"));
                        }
                    }
                } catch (JSONException e) {
                    error(e.getMessage());
                }
            }

            @Override
            public void fail(String response) {
                error(response);
                if (null != xApiException) {
                    xApiException.error(response);
                }
            }
        });
    }

    /***
     * 注册(使用手机号和验证码进行注册)
     *
     * @param context   上下文对象
     * @param mobile    手机号码
     * @param code      验证码
     * @param password  密码
     * @param callback  接口执行OK回调对象
     * @param exception 接口实现失败回调
     */
    public void register(final Context context, final String mobile, String code,
                         final String password, final XApiCallBack callback,
                         final XApiException exception) {
        String url = configParamsUrl("user/setPassword", context) + "&mobile="
                + mobile + "&code=" + code + "&password=" + password;
        XHttpUtil http = new XHttpUtil(context);
        http.get(url, new XCallBack() {
            @Override
            public void success(String response) {
                try {
                    JSONObject object = new JSONObject(response);
                    if (status(object)) {
                        if (null != callback) {
                            XUserData.saveToken(context, object.getJSONObject("data").getString("user_token"));
                            XUserData.setUID(context, object.getJSONObject("data").getString("uid"));
                            XUserData.setPassword(context, password);
                            XUserData.setUserName(context, mobile);
                            callback.response("success");
                        }
                    } else {
                        if (null != exception) {
                            exception.error(object.getString("message"));
                        }
                    }
                } catch (Exception e) {
                }
            }

            @Override
            public void fail(String response) {
                error(response);
                if (null != exception) {
                    exception.error(response);
                }
            }
        });
    }

    /***
     * 获取短信验证码
     *
     * @param context   上下文对象
     * @param mobile    手机号码
     * @param callback  接口执行OK回调对象
     * @param exception 接口执行失败回调对象
     */
    public void getCodeForRegister(final Context context, String mobile, String type,
                                   final XApiCallBack callback, final XApiException exception) {
        String url = configParamsUrl("User/verifymobile", context) + "&mobile="
                + mobile + "&type=" + type;
        XHttpUtil httpUtil = new XHttpUtil(context);
        httpUtil.get(url, new XCallBack() {
            @Override
            public void success(String response) {
                try {
                    JSONObject object = new JSONObject(response);
                    if (status(object)) {
                        if (null != callback) {
                            callback.response("true");
                        }
                    } else {
                        Toast.makeText(context, object.getString("message"), Toast.LENGTH_LONG).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void fail(String response) {
                error(response);
                if (null != exception)
                    exception.error(response);
            }
        });
    }

    /***
     * 拉取个人信息
     *
     * @param context     上下文对象
     * @param apiCallBack 接口执行OK回调对象
     * @param exception   接口执行失败回调对象
     */
    public void getUserInfo(Context context, final XApiCallBack apiCallBack, final XApiException exception) {
        String url = configParamsUrl("user/getProfile", context);
        XHttpUtil http = new XHttpUtil(context);
        http.get(url, new XCallBack() {
            @Override
            public void success(String response) {
                try {
                    JSONObject object = new JSONObject(response);
                    if (status(object)) {
                        JSONObject info = object.getJSONObject("data")
                                .getJSONObject("profile");
                        if (null != apiCallBack) {
                            apiCallBack.response(info);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void fail(String response) {
                error(response);
                if (null != exception)
                    exception.error(response);
            }
        });
    }

    /***
     * 用户反馈接口/帖子举报接口
     *
     * @param context 上下文对象
     * @param remark  type为1时标识为意见反馈,remark表示意见内容
     */
    public void feedBack(final Context context, final String remark,
                         final XApiCallBack callback, final XApiException exception) {
        String url = configParamsUrl("mine/feedback", context);
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("type", "1");
        // 用户反馈
        params.put("remark", remark + "");
        XHttpUtil httpUtil = new XHttpUtil(context);
        httpUtil.post(url, params, new XCallBack() {
            @Override
            public void success(String response) {
                try {
                    JSONObject object = new JSONObject(response);
                    if (object.getBoolean("status")) {
                        if (null != callback) {
                            callback.response(object);
                        }
                    } else {
                        Toast.makeText(context, object.getString("message"), Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                }
            }

            @Override
            public void fail(String response) {
                error(response);
                if (null != exception)
                    exception.error(response);
            }
        });
    }

    /***
     * 设置某一个地址为的默认地址
     *
     * @param context   上下文对象
     * @param id        地址ID
     * @param callBack  接口执行OK回调对象
     * @param exception 接口执行失败回调对象
     */
    public void configDefaultAddress(final Context context, String id,
                                     final XApiCallBack callBack, final XApiException exception) {
        String url = configParamsUrl("DealAddress/setdefaultaddress", context) + "&id=" + id;
        XHttpUtil http = new XHttpUtil(context);
        http.get(url, new XCallBack() {
            @Override
            public void success(String response) {
                try {
                    JSONObject object = new JSONObject(response);
                    if (status(object)) {
                        if (null != callBack) {
                            callBack.response(object);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void fail(String response) {
                error(response);
                if (null != exception)
                    exception.error(response);
            }
        });
    }

    /***
     * 获取我的地址列表信息
     *
     * @param context   上下文对象
     * @param callBack  接口执行OK回调对象
     * @param exception 接口执行失败回调对象
     */
    public void getAddressList(final Context context,
                               final XApisCallBack callBack, final XApiException exception) {
        String url = configParamsUrl("DealAddress/getaddress", context);
        XHttpUtil http = new XHttpUtil(context);
        http.get(url, new XCallBack() {
            @Override
            public void success(String response) {
                try {
                    JSONObject object = new JSONObject(response);
                    if (status(object)) {
                        ArrayList<XAddressEntity> list = new ArrayList<>();
                        JSONObject info = object.getJSONObject("data");
                        JSONArray array = info.getJSONArray("list");
                        for (int i = 0; i < array.length(); i++) {
                            XAddressEntity add = new XAddressEntity();
                            JSONObject address = array.getJSONObject(i);
                            add.setAddress(address.getString("address"));
                            add.setPhone(address.getString("tel"));
                            add.setName(address.getString("realName"));
                            add.setId(address.getString("id"));
                            String defaults = address.getString("default");
                            if ("1".equals(defaults)) {
                                add.setIsdefault(true);
                            } else {
                                add.setIsdefault(false);
                            }
                            list.add(add);
                        }
                        if (null != callBack) {
                            callBack.response(list);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void fail(String response) {
                error(response);
                if (null != exception)
                    exception.error(response);
            }
        });
    }

    /***
     * 根据某一个地址的地址ID删除某一个地址
     *
     * @param context   上下文对象
     * @param id        地址ID
     * @param callBack  接口执行OK回调对象
     * @param exception 接口执行失败回调对象
     */
    public void deleteAddressByID(final Context context, String id,
                                  final XApiCallBack callBack, final XApiException exception) {
        String url = configParamsUrl("DealAddress/deleteaddress", context) + "&id=" + id;
        XHttpUtil http = new XHttpUtil(context);
        http.get(url, new XCallBack() {
            @Override
            public void success(String response) {
                try {
                    JSONObject object = new JSONObject(response);
                    if (status(object)) {
                        if (null != callBack) {
                            callBack.response(object);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void fail(String response) {
                error(response);
                if (null != exception)
                    exception.error(response);
            }
        });
    }

    /***
     * 添加地址
     * @param context  上下文对象
     * @param name     收货人姓名
     * @param phone    收货人电话
     * @param address  收货人地址
     * @param callBack    接口执行OK回调对象
     * @param exception   接口执行失败回调对象
     */
    public void addAddress(final Context context, final String name, final String phone,
                           final String address, final XApiCallBack callBack, final XApiException exception) {
        String url = configParamsUrl("DealAddress/addaddress", context);
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("user_token", XUserData.getToken(context));
        params.put("realName", name);
        params.put("address", address);
        params.put("tel", phone);
        params.put("userId", XUserData.getUID(context));
        XHttpUtil httpUtil = new XHttpUtil(context);
        httpUtil.post(url, params, new XCallBack() {
            @Override
            public void success(String response) {
                try {
                    JSONObject object = new JSONObject(response);
                    if (object.getBoolean("status")) {
                        if (null != callBack) {
                            callBack.response(object);
                        }
                    } else {
                        Toast.makeText(context, object.getString("message"), Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                }
            }

            @Override
            public void fail(String response) {
                error(response);
                if (null != exception)
                    exception.error(response);
            }
        });
    }

    /***
     * 获取酒柜中的酒信息
     * @param context   上下文对象
     * @param mac       酒柜mac
     * @param callback  接口执行OK回调对象
     * @param exception 接口执行失败回调对象
     */
    public void getGoodsByMac(Context context, String mac, final XApisCallBack callback, final XApiException exception) {
        String url = "http://t.putaoji.cn:8080/cabinet/get_product_by_mac?mac=" + mac;
        log(url);
        XHttpUtil httpUtil = new XHttpUtil(context);
        httpUtil.get(url, new XCallBack() {
            @Override
            public void success(String response) {
                log(response);
                try {
                    JSONObject object = new JSONObject(response);
                    if (status(object)) {
                        JSONArray array = object.getJSONArray("data");
                        ArrayList<XWineEntity> mList = new ArrayList<>();
                        for (int i = 0; i < array.length(); i++) {
                            JSONObject wine = array.getJSONObject(i);
                            XWineEntity wineEntity = new XWineEntity();
                            XProductEntity xProductEntity = new XProductEntity();
                            xProductEntity.setName(wine.getString("name"));
                            xProductEntity.setCurrent_price(wine.getString("price"));
                            xProductEntity.setIcon(wine.getString("icon"));
                            xProductEntity.setId(wine.getString("id"));
                            wineEntity.setProduct(xProductEntity);
                            wineEntity.setRfidnum(wine.getString("count"));
                            mList.add(wineEntity);
                        }
                        if (null != callback) callback.response(mList);
                    } else {
                        log(object.getString("msg"));
                    }
                } catch (JSONException e) {
                }
            }

            @Override
            public void fail(String response) {
                error(response);
                if (null != exception)
                    exception.error(response);
            }
        });
    }

    /***
     * 根据设备的mac信息获取该设备的标签数据
     * @param context
     * @param mac
     * @param callBack
     */
    public void getServerCabinetRfidsByMAC(Context context, String mac, final XApiCallBack callBack, final XApiException exception) {
        String url = "http://t.putaoji.cn:8080/cabinet/getrfids?mac=" + mac;
        log(url);
        XHttpUtil xHttpUtil = new XHttpUtil(context);
        xHttpUtil.get(url, new XCallBack() {
            @Override
            public void success(String response) {
                try {
                    JSONObject object = new JSONObject(response);
                    if (status(object)) {
                        if (null != callBack) callBack.response(object.getJSONObject("data"));
                    } else {
                        log(object.getString("msg"));
                        if (null != exception)
                            exception.error(response);
                    }
                } catch (JSONException e) {
                }
            }

            @Override
            public void fail(String response) {
                error(response);
                if (null != exception)
                    exception.error(response);
            }
        });
    }

    /***
     * 获取商品详情
     * @param context
     * @param productID
     * @param callBack
     * @param exception
     */
    public void getProductInfo(Context context, String productID, final XApiCallBack callBack, final XApiException exception) {
        String url = configParamsUrl("deal/get", context) + "&id=" + productID;
        log(url);
        XHttpUtil xHttpUtil = new XHttpUtil(context);
        xHttpUtil.get(url, new XCallBack() {
            @Override
            public void success(String response) {
                try {
                    JSONObject object = new JSONObject(response);
                    if (status(object)) {

                        XProductEntity entity = new Gson().fromJson(object.getJSONObject("data").getJSONObject("product").toString(), XProductEntity.class);
                        if (null != callBack) callBack.response(entity);
                    } else {
                        log(object.getString("message"));
                    }
                } catch (JSONException e) {
                }
            }

            @Override
            public void fail(String response) {
                error(response);
                if (null != exception)
                    exception.error(response);
            }
        });
    }

    /***
     * 获取商品详情
     * @param context
     * @param rfid
     * @param callBack
     * @param exception
     */
    public void getProductsByRFID(Context context, String rfid, final XApisCallBack callBack, final XApiException exception) {
        String url = "http://t.putaoji.cn:8080/cabinet/get_product_by_code?mac=" + rfid;
        log(url);
        XHttpUtil xHttpUtil = new XHttpUtil(context);
        xHttpUtil.get(url, new XCallBack() {
            @Override
            public void success(String response) {
                try {
                    JSONObject object = new JSONObject(response);
                    if (status(object)) {
                        JSONArray array = object.getJSONArray("data");
                        ArrayList<XProductEntity> l = new ArrayList<XProductEntity>();
                        for (int i = 0; i < array.length(); i++) {
                            JSONObject wine = array.getJSONObject(i);
                            XProductEntity xProductEntity = new XProductEntity();
                            xProductEntity.setName(wine.getString("name"));
                            xProductEntity.setCurrent_price(wine.getString("price"));
                            xProductEntity.setIcon(wine.getString("icon"));
                            xProductEntity.setId(wine.getString("id"));
                            l.add(xProductEntity);
                        }
                        if (null != callBack) callBack.response(l);
                    } else {
                        log(object.getString("message"));
                    }
                } catch (JSONException e) {
                }
            }

            @Override
            public void fail(String response) {
                error(response);
                if (null != exception)
                    exception.error(response);
            }
        });
    }

    /***
     * 每月每天的数据统计
     * @param context
     * @param mac
     * @param callback
     * @param exception
     */
    public void getstatistics(Context context, String mac, final XApisCallBack callback, final XApiException exception) {
        String url = "http://t.putaoji.cn:8080/cabinet/getstatistics?mac=" + mac;
        log(url);
        XHttpUtil httpUtil = new XHttpUtil(context);
        httpUtil.get(url, new XCallBack() {
            @Override
            public void success(String response) {
                log(response);
                try {
                    JSONObject object = new JSONObject(response);
                    if (status(object)) {
                        JSONArray array = object.getJSONArray("data");
                        ArrayList<PointD> linePoint1 = new ArrayList<PointD>();
                        for (int i = 0; i < array.length(); i++) {
                            JSONObject wine = array.getJSONObject(i);
                            linePoint1.add(new PointD(Integer.parseInt(wine.getString("date").substring(8, 10)), wine.getInt("count")));
                        }
                        if (null != callback) callback.response(linePoint1);
                    } else {
                        log(object.getString("msg"));
                    }
                } catch (JSONException e) {
                }
            }

            @Override
            public void fail(String response) {
                error(response);
                if (null != exception)
                    exception.error(response);
            }
        });
    }

    /***
     * 获取当天柜子的历史记录
     * @param context
     * @param mac
     * @param callback
     * @param exception
     */
    public void getCurHistoryByMac(Context context, String mac, final XApisCallBack callback, final XApiException exception) {
        String url = "http://t.putaoji.cn:8080/cabinet/get_history_by_mac?type=1&page=1&mac=" + mac;
        log(url);
        XHttpUtil httpUtil = new XHttpUtil(context);
        httpUtil.get(url, new XCallBack() {
            @Override
            public void success(String response) {
                log(response);
                try {
                    JSONObject object = new JSONObject(response);
                    if (status(object)) {
                        JSONArray array = object.getJSONArray("data");
                        ArrayList<XProductHistoryEntity> list = new ArrayList<>();
                        for (int i = 0; i < array.length(); i++) {
                            JSONObject wine = array.getJSONObject(i);
                            XProductHistoryEntity e = new Gson().fromJson(wine.toString(), XProductHistoryEntity.class);
                            list.add(e);
                        }
                        if (null != callback) callback.response(list);
                    } else {
                        log(object.getString("msg"));
                        if (null != exception)
                            exception.error(response);
                    }
                } catch (JSONException e) {
                    if (null != exception)
                        exception.error(response);
                }
            }

            @Override
            public void fail(String response) {
                error(response);
                if (null != exception)
                    exception.error(response);
            }
        });
    }

    /***
     * 获取柜子的历史记录
     * @param context
     * @param mac
     * @param callback
     * @param exception
     */
    public void getHistoryByMac(Context context, String mac, String page, final XApisCallBack callback, final XApiException exception) {
        String url = "http://t.putaoji.cn:8080/cabinet/get_history_by_mac?type=2&page=" + page + "&mac=" + mac;
        log(url);
        XHttpUtil httpUtil = new XHttpUtil(context);
        httpUtil.get(url, new XCallBack() {
            @Override
            public void success(String response) {
                log(response);
                try {
                    JSONObject object = new JSONObject(response);
                    if (status(object)) {
                        JSONArray array = object.getJSONArray("data");
                        ArrayList<XProductHistoryEntity> list = new ArrayList<>();
                        for (int i = 0; i < array.length(); i++) {
                            JSONObject wine = array.getJSONObject(i);
                            XProductHistoryEntity e = new Gson().fromJson(wine.toString(), XProductHistoryEntity.class);
                            list.add(e);
                        }
                        if (null != callback) callback.response(list);
                    } else {
                        log(object.getString("msg"));
                        if (null != exception)
                            exception.error(response);
                    }
                } catch (JSONException e) {
                    if (null != exception)
                        exception.error(response);
                }
            }

            @Override
            public void fail(String response) {
                error(response);
                if (null != exception)
                    exception.error(response);
            }
        });
    }
}


text:
require "rom/schema"

RSpec.describe ROM::Schema, "#merge" do
  subject(:schema) { left.merge(right) }

  let(:left) do
    define_schema(:users, id: :Integer, name: :String)
  end

  let(:right) do
    define_schema(:tasks, user_id: :Integer)
  end

  it "returns a new schema with attributes from two schemas" do
    expect(schema.map(&:name)).to eql(%i[id name user_id])
  end
end

redpajama_set_name: RedPajamaGithub


text:
// Generated by CoffeeScript 1.6.2
/*

  Call Connect/Express apps over arbitrary streams (even WebSocket)
*/

var EventEmitter, Request, Response, express, rpc,
  __hasProp = {}.hasOwnProperty,
  __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

express = require('express');

EventEmitter = require('events').EventEmitter;

rpc = require('stream-rpc');

Request = (function() {
  function Request(message) {
    this.message = message;
    this.method = message.method || 'GET';
    this.url = message.url || '/';
    this.headers = message.headers || {};
    this.body = message.body || {};
  }

  return Request;

})();

Response = (function(_super) {
  __extends(Response, _super);

  function Response() {
    this.headers = {};
    this.statusCode = 200;
  }

  Response.prototype.send = function(statusCode, body) {
    if (!body) {
      body = statusCode;
      statusCode = 200;
    }
    this.statusCode = statusCode;
    return this.end(body);
  };

  Response.prototype.end = function(data) {
    if (data) {
      this.body = data;
    }
    if (!this.headers['Content-Type']) {
      this.headers['Connect-Type'] = 'application/json';
    }
    return this.emit('end');
  };

  Response.prototype.getHeader = function(name) {
    return this.headers[name];
  };

  Response.prototype.setHeader = function(name, value) {
    return this.headers[name] = value;
  };

  return Response;

})(EventEmitter);

module.exports = function(app) {
  var outerApp, stream;

  outerApp = express();
  outerApp.request = {
    __proto__: Request.prototype
  };
  outerApp.response = {
    __proto__: Response.prototype
  };
  outerApp.use(app);
  stream = rpc({
    handle: function(message, done) {
      var req, res;

      req = new Request(message);
      res = new Response();
      res.on('end', function() {
        return done(null, {
          statusCode: res.statusCode,
          body: res.body,
          headers: res.headers
        });
      });
      return app.handle(req, res);
    }
  });
  return stream;
};


text:
#ifndef SkScan_DEFINED
#define SkScan_DEFINED

#include "SkFixed.h"
#include "SkRect.h"

class SkRasterClip;
class SkRegion;
class SkBlitter;
class SkPath;

/** Defines a fixed-point rectangle, identical to the integer SkIRect, but its
    coordinates are treated as SkFixed rather than int32_t.
*/
typedef SkIRect SkXRect;

class SkScan {
public:
    /*
     *  Draws count-1 line segments, one at a time:
     *      line(pts[0], pts[1])
     *      line(pts[1], pts[2])
     *      line(......, pts[count - 1])
     */
    typedef void (*HairRgnProc)(const SkPoint[], int count, const SkRegion*, SkBlitter*);
    typedef void (*HairRCProc)(const SkPoint[], int count, const SkRasterClip&, SkBlitter*);

    static void FillPath(const SkPath&, const SkIRect&, SkBlitter*);

    ///////////////////////////////////////////////////////////////////////////
    // rasterclip

    static void FillIRect(const SkIRect&, const SkRasterClip&, SkBlitter*);
    static void FillXRect(const SkXRect&, const SkRasterClip&, SkBlitter*);
    static void FillRect(const SkRect&, const SkRasterClip&, SkBlitter*);
    static void AntiFillRect(const SkRect&, const SkRasterClip&, SkBlitter*);
    static void AntiFillXRect(const SkXRect&, const SkRasterClip&, SkBlitter*);
    static void FillPath(const SkPath&, const SkRasterClip&, SkBlitter*);
    static void AntiFillPath(const SkPath&, const SkRasterClip&, SkBlitter*);
    static void FrameRect(const SkRect&, const SkPoint& strokeSize,
                          const SkRasterClip&, SkBlitter*);
    static void AntiFrameRect(const SkRect&, const SkPoint& strokeSize,
                              const SkRasterClip&, SkBlitter*);
    static void FillTriangle(const SkPoint pts[], const SkRasterClip&, SkBlitter*);
    static void HairLine(const SkPoint[], int count, const SkRasterClip&, SkBlitter*);
    static void AntiHairLine(const SkPoint[], int count, const SkRasterClip&, SkBlitter*);
    static void HairRect(const SkRect&, const SkRasterClip&, SkBlitter*);
    static void AntiHairRect(const SkRect&, const SkRasterClip&, SkBlitter*);
    static void HairPath(const SkPath&, const SkRasterClip&, SkBlitter*);
    static void AntiHairPath(const SkPath&, const SkRasterClip&, SkBlitter*);
    static void HairSquarePath(const SkPath&, const SkRasterClip&, SkBlitter*);
    static void AntiHairSquarePath(const SkPath&, const SkRasterClip&, SkBlitter*);
    static void HairRoundPath(const SkPath&, const SkRasterClip&, SkBlitter*);
    static void AntiHairRoundPath(const SkPath&, const SkRasterClip&, SkBlitter*);

private:
    friend class SkAAClip;
    friend class SkRegion;

    static void FillIRect(const SkIRect&, const SkRegion* clip, SkBlitter*);
    static void FillXRect(const SkXRect&, const SkRegion* clip, SkBlitter*);
    static void FillRect(const SkRect&, const SkRegion* clip, SkBlitter*);
    static void AntiFillRect(const SkRect&, const SkRegion* clip, SkBlitter*);
    static void AntiFillXRect(const SkXRect&, const SkRegion*, SkBlitter*);
    static void FillPath(const SkPath&, const SkRegion& clip, SkBlitter*);
    static void AntiFillPath(const SkPath&, const SkRegion& clip, SkBlitter*,
                             bool forceRLE = false);
    static void FillTriangle(const SkPoint pts[], const SkRegion*, SkBlitter*);

    static void AntiFrameRect(const SkRect&, const SkPoint& strokeSize,
                              const SkRegion*, SkBlitter*);
    static void HairLineRgn(const SkPoint[], int count, const SkRegion*, SkBlitter*);
    static void AntiHairLineRgn(const SkPoint[], int count, const SkRegion*, SkBlitter*);
};

/** Assign an SkXRect from a SkIRect, by promoting the src rect's coordinates
    from int to SkFixed. Does not check for overflow if the src coordinates
    exceed 32K
*/
static inline void XRect_set(SkXRect* xr, const SkIRect& src) {
    xr->fLeft = SkIntToFixed(src.fLeft);
    xr->fTop = SkIntToFixed(src.fTop);
    xr->fRight = SkIntToFixed(src.fRight);
    xr->fBottom = SkIntToFixed(src.fBottom);
}

/** Assign an SkXRect from a SkRect, by promoting the src rect's coordinates
    from SkScalar to SkFixed. Does not check for overflow if the src coordinates
    exceed 32K
*/
static inline void XRect_set(SkXRect* xr, const SkRect& src) {
    xr->fLeft = SkScalarToFixed(src.fLeft);
    xr->fTop = SkScalarToFixed(src.fTop);
    xr->fRight = SkScalarToFixed(src.fRight);
    xr->fBottom = SkScalarToFixed(src.fBottom);
}

/** Round the SkXRect coordinates, and store the result in the SkIRect.
*/
static inline void XRect_round(const SkXRect& xr, SkIRect* dst) {
    dst->fLeft = SkFixedRoundToInt(xr.fLeft);
    dst->fTop = SkFixedRoundToInt(xr.fTop);
    dst->fRight = SkFixedRoundToInt(xr.fRight);
    dst->fBottom = SkFixedRoundToInt(xr.fBottom);
}

/** Round the SkXRect coordinates out (i.e. use floor for left/top, and ceiling
    for right/bottom), and store the result in the SkIRect.
*/
static inline void XRect_roundOut(const SkXRect& xr, SkIRect* dst) {
    dst->fLeft = SkFixedFloorToInt(xr.fLeft);
    dst->fTop = SkFixedFloorToInt(xr.fTop);
    dst->fRight = SkFixedCeilToInt(xr.fRight);
    dst->fBottom = SkFixedCeilToInt(xr.fBottom);
}

#endif


text:
package net.floodlightcontroller.core.web.serializers;

import java.io.IOException;

import org.projectfloodlight.openflow.types.IPv6Address;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
/**
 * Serialize an IPv6Address in dotted decimal format
 */
public class IPv6Serializer extends JsonSerializer<IPv6Address> {

    @Override
    public void serialize(IPv6Address ipv6, JsonGenerator jGen,
                          SerializerProvider serializer)
                                  throws IOException, JsonProcessingException {
        jGen.writeString(ipv6.toString());
    }
}


text:
package com.blazebit.persistence.view.testsuite.inheritance.basic.model;

import com.blazebit.persistence.view.EntityView;
import com.blazebit.persistence.view.EntityViewInheritance;
import com.blazebit.persistence.view.EntityViewInheritanceMapping;
import com.blazebit.persistence.testsuite.entity.Document;

import java.util.Set;

/**
 *
 * @author Christian Beikov
 * @since 1.2.0
 */
@EntityView(Document.class)
@EntityViewInheritance({ NewSub1DocumentView.class, NewSub2DocumentView.class })
@EntityViewInheritanceMapping("age < 15")
public interface NewDocumentView extends DocumentBaseView {

    public Set<SimplePersonSubView> getContacts();
}


text:
import * as React from 'react';
import Loader from "./components/Loader";
import {Tilstand} from "./domain/domain";
import {connect} from "react-redux";
import Cards from "./components/Cards";
import LoadMore from "./components/LoadMore";
import {reload, reloadT} from "./actions/actions";

interface AppProps {
    laster: boolean,
    numLoaded: number,
    reload: reloadT
}
export class App extends React.Component<AppProps, {}> {
    render(){
        return (

Landingsopplysninger

                    <button id="butRefresh"
                            className="headerButton"
                            aria-label="Refresh"
                            onClick={(e) => this.props.reload(this.props.numLoaded, 0)}></button>

                    <Cards />
                    <LoadMore />

                {this.props.laster && <Loader/>}

        );
    }
}

const mapStateToProps = (state: Tilstand) => {
    const datoer = new Set(state.landingsdata
        .map(ld => ld.landingsdato.toString()));
    return {
        laster: state.laster,
        numLoaded: datoer.size
    }
};
const mapDispatchToProps =  ({
    reload: reload
});
export default connect(mapStateToProps, mapDispatchToProps)(App);


text:
package tcpmiddleware

import (
	"context"
	"fmt"
	"strings"

	"github.com/traefik/traefik/v2/pkg/config/runtime"
	ipwhitelist "github.com/traefik/traefik/v2/pkg/middlewares/tcp/ipwhitelist"
	"github.com/traefik/traefik/v2/pkg/server/provider"
	"github.com/traefik/traefik/v2/pkg/tcp"
)

type middlewareStackType int

const (
	middlewareStackKey middlewareStackType = iota
)

// Builder the middleware builder.
type Builder struct {
	configs map[string]*runtime.TCPMiddlewareInfo
}

// NewBuilder creates a new Builder.
func NewBuilder(configs map[string]*runtime.TCPMiddlewareInfo) *Builder {
	return &Builder{configs: configs}
}

// BuildChain creates a middleware chain.
func (b *Builder) BuildChain(ctx context.Context, middlewares []string) *tcp.Chain {
	chain := tcp.NewChain()

	for _, name := range middlewares {
		middlewareName := provider.GetQualifiedName(ctx, name)

		chain = chain.Append(func(next tcp.Handler) (tcp.Handler, error) {
			constructorContext := provider.AddInContext(ctx, middlewareName)
			if midInf, ok := b.configs[middlewareName]; !ok || midInf.TCPMiddleware == nil {
				return nil, fmt.Errorf("middleware %q does not exist", middlewareName)
			}

			var err error
			if constructorContext, err = checkRecursion(constructorContext, middlewareName); err != nil {
				b.configs[middlewareName].AddError(err, true)
				return nil, err
			}

			constructor, err := b.buildConstructor(constructorContext, middlewareName)
			if err != nil {
				b.configs[middlewareName].AddError(err, true)
				return nil, err
			}

			handler, err := constructor(next)
			if err != nil {
				b.configs[middlewareName].AddError(err, true)
				return nil, err
			}

			return handler, nil
		})
	}

	return &chain
}

func checkRecursion(ctx context.Context, middlewareName string) (context.Context, error) {
	currentStack, ok := ctx.Value(middlewareStackKey).([]string)
	if !ok {
		currentStack = []string{}
	}

	if inSlice(middlewareName, currentStack) {
		return ctx, fmt.Errorf("could not instantiate middleware %s: recursion detected in %s", middlewareName, strings.Join(append(currentStack, middlewareName), "->"))
	}

	return context.WithValue(ctx, middlewareStackKey, append(currentStack, middlewareName)), nil
}

func (b *Builder) buildConstructor(ctx context.Context, middlewareName string) (tcp.Constructor, error) {
	config := b.configs[middlewareName]
	if config == nil || config.TCPMiddleware == nil {
		return nil, fmt.Errorf("invalid middleware %q configuration", middlewareName)
	}

	var middleware tcp.Constructor

	// IPWhiteList
	if config.IPWhiteList != nil {
		middleware = func(next tcp.Handler) (tcp.Handler, error) {
			return ipwhitelist.New(ctx, next, *config.IPWhiteList, middlewareName)
		}
	}

	if middleware == nil {
		return nil, fmt.Errorf("invalid middleware %q configuration: invalid middleware type or middleware does not exist", middlewareName)
	}

	return middleware, nil
}

func inSlice(element string, stack []string) bool {
	for _, value := range stack {
		if value == element {
			return true
		}
	}
	return false
}


text:
module Business
  VERSION = "0.0.1"
end


text:
``` diff
 namespace System.Diagnostics {
     public sealed class ProcessStartInfo {
+        public Collection<string> ArgumentList { get; }
     }
 }
```


text:
package test

import (
	"context"
	"testing"

	"github.com/sacloud/libsacloud/v2/sacloud"
	"github.com/sacloud/libsacloud/v2/sacloud/testutil"
	"github.com/sacloud/libsacloud/v2/sacloud/types"
	"github.com/stretchr/testify/assert"
)

func TestRegionOp_Find(t *testing.T) {
	t.Parallel()

	client := sacloud.NewRegionOp(singletonAPICaller())

	searched, err := client.Find(context.Background(), &sacloud.FindCondition{Count: 1})
	assert.NoError(t, err)

	err = testutil.DoAsserts(
		testutil.AssertLenFunc(t, searched.Regions, 1, "Regions"),
		testutil.AssertNotEmptyFunc(t, searched.Regions[0].ID, "Region.ID"),
		testutil.AssertNotEmptyFunc(t, searched.Regions[0].Name, "Region.Name"),
		testutil.AssertNotEmptyFunc(t, searched.Regions[0].Description, "Region.Description"),
		testutil.AssertNotEmptyFunc(t, searched.Regions[0].NameServers, "Region.NameServers"),
	)
	assert.NoError(t, err)
}

func TestRegionOp_Read(t *testing.T) {
	t.Parallel()

	client := sacloud.NewRegionOp(singletonAPICaller())

	sandboxRegionID := types.ID(290)
	region, err := client.Read(context.Background(), sandboxRegionID)
	assert.NoError(t, err)

	err = testutil.DoAsserts(
		testutil.AssertEqualFunc(t, region.ID, sandboxRegionID, "Region.ID"),
		testutil.AssertNotEmptyFunc(t, region.Name, "Region.Name"),
		testutil.AssertNotEmptyFunc(t, region.Description, "Region.Description"),
		testutil.AssertNotEmptyFunc(t, region.NameServers, "Region.NameServers"),
	)
	assert.NoError(t, err)
}


text:
module.exports = {
  setCheckboxValue : function (locate, value) {
    var el;
    return locate
      .then(function (located) {
        el = located;
        return el.isSelected();
      })
      .then(function (isSelected) {
        if (isSelected && !value || !isSelected && value) {
          return el.click();
        }
      });
  },
  setInputValue : function (locate, value) {
    return locate
      .then(function (el) {
        return el.click().clear().sendKeys(value);
      });
  }
};


text:
from __future__ import (unicode_literals, absolute_import,
                        division, print_function)
import datetime
import logging

from py3compat import PY2
from optparse import make_option
from django.core.management.base import BaseCommand
from django.utils import timezone

from snisi_core.models.Entities import Entity
from snisi_core.models.Periods import MonthPeriod
from snisi_core.models.Projects import Cluster, Participation
from snisi_tools.datetime import DEBUG_change_system_date

if PY2:
    import unicodecsv as csv
else:
    import csv

logger = logging.getLogger(__name__)

class Command(BaseCommand):

    option_list = BaseCommand.option_list + (
        make_option('-f',
                    help='CSV file to import Health Entities from',
                    action='store',
                    dest='input_file'),
        make_option('-c',
                    help='Delete all Participations to clusters first',
                    action='store_true',
                    dest='clear')
        )

    def handle(self, *args, **options):

        msi_cluster = Cluster.objects.get(slug="msi_reprohealth_routine")
        msi_cluster_sms = \
            Cluster.objects.get(slug="msi_reprohealth_routine_sms")
        DEBUG_change_system_date(
            MonthPeriod.from_url_str("08-2012").end_on
            - datetime.timedelta(days=5), True)

        headers = ['SNISI', 'Name', 'Type']
        input_file = open(options.get('input_file'), 'r')
        csv_reader = csv.DictReader(input_file, fieldnames=headers)

        if options.get('clear'):
            Participation.objects.filter(
                cluster__in=[msi_cluster, msi_cluster_sms]).delete()

        for entry in csv_reader:
            if csv_reader.line_num == 1:
                continue

            health_unit = Entity.get_or_none(entry.get('SNISI'))
            if health_unit is None:
                continue

            logger.info(health_unit)

            p, created = Participation.objects.get_or_create(
                cluster=msi_cluster,
                entity=health_unit,
                modified_on=timezone.now())
            p, created = Participation.objects.get_or_create(
                cluster=msi_cluster_sms,
                entity=health_unit,
                modified_on=timezone.now())

        DEBUG_change_system_date(None, True)


text:
package org.redhelix.core.chassis;

import java.util.List;
import org.redhelix.core.action.RedHxActionGroup;
import org.redhelix.core.chassis.id.RedHxChassisAssetTag;
import org.redhelix.core.chassis.id.RedHxChassisDescription;
import org.redhelix.core.chassis.id.RedHxChassisId;
import org.redhelix.core.chassis.id.RedHxChassisManufacturerName;
import org.redhelix.core.chassis.id.RedHxChassisModelNumber;
import org.redhelix.core.chassis.id.RedHxChassisName;
import org.redhelix.core.chassis.id.RedHxChassisPartNumber;
import org.redhelix.core.chassis.id.RedHxChassisSKU;
import org.redhelix.core.chassis.id.RedHxChassisSerialNumber;
import org.redhelix.core.util.RedHxIndicatorLedStateEnum;
import org.redhelix.core.util.RedHxOperatingHealthEnum;
import org.redhelix.core.util.RedHxOperatingStateEnum;
import org.redhelix.core.util.RedHxUriPath;

/**
 *
 * A chassis that may contain other chassis or computer systems.
 *
 * @since RedHelix Version 0.1
 * @author Hank Bruning
 */
public interface RedHxChassis {

  /**
   * get all actions that can be preformed on the shelf.
   *
   * @return a null if no actions can be preformed otherwise the actions.
   */
  RedHxActionGroup getActionGroup();

  /**
   * get the asset tag assigned to the shelf.
   *
   * @return a null if no asset tag has been assigned otherwise the asset tag.
   */
  RedHxChassisAssetTag getAssetTag();

  RedHxChassisDescription getChassisDescription();

  RedHxChassisId getChassisId();

  RedHxChassisName getChassisName();

  RedHxChassisTypeEnum getChassisType();

  List<RedHxUriPath> getComputerSystemUriPathList();

  RedHxUriPath getContainedByUriPath();

  List<RedHxUriPath> getContainsList();

  List<RedHxUriPath> getCooledByUriPathList();

  RedHxIndicatorLedStateEnum getIndicatorLedState();

  RedHxUriPath getLogServicesUriPath();

  RedHxChassisManufacturerName getManufacturerName();

  RedHxChassisModelNumber getModelNumber();

  RedHxOperatingHealthEnum getOperatingHealth();

  RedHxOperatingStateEnum getOperatingState();

  RedHxChassisPartNumber getPartNumber();

  List<RedHxUriPath> getPoweredByList();

  RedHxUriPath getPowerUriPath();

  RedHxChassisSerialNumber getSerialNumber();

  RedHxChassisSKU getSku();

  List<RedHxUriPath> getSystemManagerUriPathList();

  RedHxUriPath getThermalUriPath();
}


text:
layout: post
title: Structure Learning for Bayesian Networks
---
## Structure learning for Bayesian networks

The task of structure learning for Bayesian networks refers to learn the structure of the directed acyclic graph (DAG) from data. There are two major approaches for the structure learning: score-based approach and constraint-based approach .

### Score-based approach

The score-based approach first defines a criterion to evaluate how well the Bayesian network fits the data, then searches over the space of DAGs for a structure with maximal score. In this way, the score-based approach is essentially a search problem and consists of two parts: the definition of score metric and the search algorithm.

### Score metrics

The score metrics for a structure $$\mathcal{G}$$ and data $$D$$ can be generally defined as:
$$Score(G:D)= LL(G:D) - \phi(|D|) \|G\|.$$

Here $$LL(G:D)$$ refers to the log-likelihood of the data under the graph structure $$\mathcal{G}.$$  The parameters in Bayesian network $$G$$ are estimated based on MLE and the log-likelihood score is calculated based on the estimated parameters. If we consider only the log-likelihood in the score function, we will end up with an overfitting structure (namely, a complete graph.) That is why we have the second term in the scoring function. $$|D|$$ is the number of sample and $$\|G\|$$ is the number of parameters in the graph
$$ \mathcal{G}.$$ With this extra term, we will penalize the over-complicated graph structure and avoid overfitting.  For AIC the function $$\phi(t) = 1, $$ while for BIC $$\phi(t) =  \log(t)/2.$$ It is important to note that in BIC, the influence of model complexity will decrease as M grows, allowing the log-likelihood term to eventually dominate the score.

There is another family of Bayesian score function called BD (Bayesian Dirichlet) score. For BD score, if first defines the probability of data $$D$$ conditional on the graph structure $$\mathcal{G}$$ as

{%math%}
P(D|\mathcal{G})=\int P(D|\mathcal{G}, \Theta_{\mathcal{G}})P(\Theta_{\mathcal{G}}|\mathcal{G})d\Theta_{\mathcal{G}},
{%endmath%}

where $$P(D\mid| \mathcal{G} \Theta_{\mathcal{G}})$$ is the probability of the data given the network structure and parameters, and $$P(\Theta_{\mathcal{G}}\mid \mathcal{G})$$ is the prior probability of the parameters. When the prior probability is specified as a Dirichlet distribution,

{%math%}
P(D|\Theta_{\mathcal{G}}) = \prod_{i} \prod_{\pi_i} \left[ \frac{\Gamma(\sum_j N'_{i,\pi_i,j})}{\Gamma(\sum_j N'_{i,\pi_i,j} + N_{i,\pi_i,j} )} \prod_{j}\frac{\Gamma(N'_{i,\pi_i,j} + N_{i,\pi_i,j})}{\Gamma(N'_{i,\pi_i,j})}\right].
{%endmath%}

Here $$\pi_i$$ refers to the parent configuration of the variable $$i$$ and $$N_{i,\pi_i,j}$$ is the count of variable $$i$$ taking value $$j$$ with parent configuration $$\pi_i$$. $$N'$$ represents the counts in the prior respectively.

With a prior for the graph structure $$P(\Theta_{\mathcal{G}})$$ (say, a uniform one), the BD score is defined as

{%math%}
\log P(D|\Theta_{\mathcal{G}}) + \log P(\Theta_{\mathcal{G}}).
{%endmath%}

Notice there is no penalty term appending to the BD score due to that it will penalize the overfitting implicitly via the integral over parameter space.

### Search algorithms

The most common choice for search algorithms are local search and  greedy search.

For local search algorithm, it starts with an empty graph or a complete graph. At each step, it attempts to change the graph structure by a single operation of adding an edge, removing an edge or reversing an edge. (Of course, the operation should preserve the acyclic property.) If the score increases, then it adopts the attempt and does the change, otherwise it makes another attempt.

For greedy search (namely the K3 algorithm), we first assume a topological order of the graph. For each variable, we restrict its parent set to the variables with a higher order. While searching for parent set for each variable, it takes a greedy approach by adding the parent that increases the score most until no improvement can be made.

Although both approach are computational tractable, neither of them have a guarantee of the quality of the graph that we end up with. The graph space is highly "non-convex" and both algorithm might get stuck at some sub-optimal regions.

### Constraint-based approach

The constraint-based case employs the independence test to identify a set of edge constraints for the graph and then finds the best DAG that satisfies the constraints. For example, we could distinguish V-structure and fork-structure by doing an independence test for the two variables on the sides conditional on the variable in the middle. This approach works well with some other prior (expert) knowledge of structure but requires lots of data samples to guarantee testing power. So it is less reliable when the number of sample is small.

### Recent Advances

In this section, we will briefly introduce two recent algorithms for graph search: order-search (OS) approach and integer linear programming (ILP) approach.

The OS approach, as the name refers, conducts a search over the topological orders and the search over graph space at the same time. The K3 algorithm assumes a topological order in advance and do the search only over the graphs that obey the topological order. When the order specified is a poor one, it may end with a bad graph structure (with a low graph score). The OS algorithm resolves this problem by doing search over orders at the same time. It shifts two adjacent variable in an order at each step and employs the K3 algorithm as a sub-routine.

The ILP approach encodes the graph structure, scoring and the acyclic constraints into a linear programming problem. Thus it can utilize the state-of-art integer programming solver. But this approach requires a bound on the maximum number of node parents in the graph (say to be 4 or 5). Otherwise, the number of constraints in the ILP will explode and the computation will be intractable.

<br/>

|[Index](../../) | [Previous](../bayesianlearning) |  [Next](../../extras/vae)|


text:
<link rel="icon" type="images/png" href="images/favicon.png">

		<link rel="stylesheet" href="style.css">
		<link rel="stylesheet" type="text/css" href="engine1/style.css" />

		 <?php include('header.php');?>

Hrithik Roshan is an Indian film actor. and has been cited in the media as one of the most attractive male celebrities in India.

Aishwarya Rai Bachchan, also known as Aishwarya Rai, is an Indian actress, model and the winner of the Miss World pageant of 1994.

Deepika Padukone is an Indian film actress and model. One of the most popular and highest-paid Indian celebrity

Mark Sinclair better known by his stage name Vin Diesel, is an American actor. He is best known for his portrayals of Dominic Toretto in The Fast and the Furious film series and Richard B. Riddick in The Chronicles of Riddick trilogy.

Nina Dobrev is a Bulgarian Canadian actress and model. She played the role of Mia Jones on Degrassi: The Next Generation in seasons six to nine.

John Abraham, is an Indian film actor, producer and a former model.

Madhuri Dixit is an Indian actress who is known for her work in Hindi cinema. A leading actress of Bollywood in the 1980s, 1990s and early-2000s,

Robert John Downey Jr. is an American actor whose career has included critical and popular success in his youth. He is best known for his roles as Tony Stark in Iron Man.

Jensen Ross Ackles is an American actor and director. He is known for his roles in television in Days of Our Lives and Supernatural

Shah Rukh Khan, also known as SRK, is an Indian film actor, producer and television personality.

Shahid Kapoor, also known as Shahid Khattar, is an Indian actor who appears in Hindi films.

Shraddha Kapoor is an Indian film actress who works in Bollywood films. The daughter of actor Shakti Kapoor.

Varun Dhawan is an Indian actor who appears in Hindi films. The son of film director David Dhawan, he studied Business Management from the Nottingham Trent University.

Rajiv Hari Om Bhatia, better known by his stage name Akshay Kumar, is an Indian actor, producer and martial artist who has appeared in over a hundred Hindi films.

Amitabh Harivansh Bachchan is an Indian film actor. He first gained popularity in the early 1970s for movies like Deewar and Zanjeer known as Angry Youn Man.

Daniel Jacob Radcliffe is an English actor who rose to prominence as the title character in the Harry Potter film series.

Kajal Aggarwal is an Indian film actress and model. Primarily known for her work in Telugu and Tamil films, Kajal has also appeared in Bollywood films.

Kajol Devgan, known mononymously as Kajol, is a critically acclaimed Indian film actress who predominantly works in Hindi cinema.

Sonam Kapoor is an Indian actress who appears in Bollywood films and is the daughter of actor Anil Kapoor.

Anushka Sharma is an Indian film actress and producer. She has established a career in Hindi cinema, and is the recipient of a Filmfare Award from four nominations.

Chris Hemsworth is an Australian actor. He is best known for his roles as Kim Hyde in the Australian TV series Home and Away and as Thor in the Marvel Cinematic Universe films.

Taylor Alison Swift is an American singer-songwriter. Raised in Wyomissing, Pennsylvania, she moved to Nashville, Tennessee, at the age of 14 to pursue a career in country music.

Priyanka Chopra is an Indian film actress and singer, and the winner of the Miss World pageant of 2000.

Mahira Hafeez Khan better known as Mahira Khan is a Pakistani film and television actress and former VJ. She is known for playing a variety of characters in a range of film genre and serials-from contemporary social to romantic dramas.

CSS Slideshow Gallery by WOWSlider.com v2.2.3

		<?php include('left_header.php');?>
		<?php include('right_header.php');?>

Prev Page                                                   Next Page

Home Continue..

Tips For Making 2016 Your Most Beautiful And Healthy Year Ever

(NAPSI)—As one of the world's most-photographed supermodels. Supermodel Rachel Hunter has advice on looking your best.
North American Precis Syndicate has spent most of her professional life focused on fashion and beauty. She's graced the covers of Elle, Cosmopolitan, Sports Illustrated's famous swimsuit issues and many more publications.

						Read More..

-

Bollywood star Salman Khan acquitted in 13-year-old hit-and-run case

						An Indian court on Thursday overturned Bollywood actor Salman Khan's conviction in a 13-year-old hit-and-run case, scrapping a lower court's sentence of five years in jail for running over a homeless man...

						Read More..

-

The Charming Arrogance of Robert Downey, Jr. Reduced To His 10 Best Quotes

						I saw an interview with Robert Downey, Jr. -- who is already starting his promotional tour for Iron Man 3 -- over on Moviefone today, where he was referred to as the Greatest Actor of the Generation...

						Read More..

-

Page 3

Prev Page                                                   Next Page

			<?php include_once('footer.php'); ?>


text: <!DOCTYPE html>


text:
/**
 *
 */
package com.withinet.opaas.wicket.services;

/**
 * Decouples feedback messages from pages
 *
 * @author Folarin
 *
 */
public class FeedbackMessage {

	private String message;

	private int level;

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public int getLevel() {
		return level;
	}

	public void setLevel(int level) {
		this.level = level;
	}
}


text:
namespace proxy_wasm {

class WasmVm;
std::unique_ptr<WasmVm> createNullVm();

} // namespace proxy_wasm


text:
class CTempDlg : public CDHtmlDialog
{
	DECLARE_DYNCREATE(CTempDlg)

public:
	CTempDlg(CWnd* pParent = NULL);   // standard constructor
	virtual ~CTempDlg();
// Overrides
	HRESULT OnButtonOK(IHTMLElement *pElement);
	HRESULT OnButtonCancel(IHTMLElement *pElement);

// Dialog Data
	enum { IDD = IDD_DIALOG_TEMP, IDH = IDR_HTML_TEMPDLG };

protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	virtual BOOL OnInitDialog();

	DECLARE_MESSAGE_MAP()
	DECLARE_DHTML_EVENT_MAP()
public:
	afx_msg void OnBnClickedOk();
};


text:
"""
Householder QR.

Use the script run_householder.py to use the code.

Austin R. Benson
David F. Gleich
Copyright (c) 2012-2014
"""

import struct
import numpy
import math

import util
import mrmc
import sys

import dumbo
import dumbo.backends.common
from dumbo import opt

def parse_info(f):
  PICKED_SET = '(picked_set) '
  ALPHA = '(alpha) '
  TAU = '(tau) '
  SIGMA = '(sigma) '

  info = {PICKED_SET: None, ALPHA: None, TAU: None, SIGMA: None}

  # TODO(arbenson): This is ugly.  The file is small and specific, so things
  # are annoying to parse.  Make this cleaner.
  for key in info:
    info_data = open(f, 'r')
    for line in info_data:
      if len(line) > len(key) and line[:len(key)] == key:
        # Handle doubles
        if key != PICKED_SET:
          info[key] = float(line[len(key):])
        else:
          line = line[len(key):]
          line = line.lstrip('[').rstrip(']\n').split(',')
          line = [k.lstrip().lstrip('\'').rstrip('\'') for k in line]
          info[key] = line
    info_data.close()

  return (info[PICKED_SET], info[ALPHA], info[TAU], info[SIGMA])

@opt("getpath", "yes")
class HouseholderMap1(mrmc.MatrixHandler):
  def __init__(self, step, last_step, info_file=None, w_file=None, blocksize=500):
    mrmc.MatrixHandler.__init__(self)
    self.data = 0.0
    self.A_data = []

    # step of alg: i = 0, 1, ..., n-1
    self.step = step
    self.first_step = (step == 0)
    self.last_step = last_step

    if self.first_step:
      self.picked_set = []
    else:
      self.picked_set, self.alpha, self.tau, self.sigma = parse_info(info_file)
      self.last_picked = self.picked_set[-1]
      self.w = self.parse_w(w_file)

    self.nrows = 0
    self.blocksize = blocksize
    self.first_key = None
    self.first_value = None

  def parse_w(self, f):
    w = []
    for line in open(f, 'r'):
      ind = line.find(')') + 2
      w.append(float(line[ind:]))
    return w

  def store(self, key, value):
    if self.last_step:
      if key in self.picked_set:
        self.A_data.append((key, value))
    else:
      if key not in self.picked_set:
        if self.first_key is None:
          self.first_key = key
          self.first_value = value[self.step]
        else:
          self.data += value[self.step] * value[self.step]
      self.A_data.append((key, value))

  def collect(self, key, value):
    new_row = [float(v) for v in value]
    if not self.first_step:
      if key == self.last_picked:
        new_row[self.step - 1] = self.alpha
      elif key not in self.picked_set:
        new_row[self.step - 1] *= self.sigma

    if not self.first_step:
      last_picked = self.picked_set[-1]
      w = self.w[self.step:]
      if key in self.picked_set:
        if key != last_picked:
          for i, val in enumerate(w):
            new_row[self.step + i] -= val * self.tau
      else:
        for i, val in enumerate(w):
          new_row[self.step + i] -= val * self.tau * new_row[self.step - 1]

    self.nrows += 1
    # write status updates so Hadoop doesn't complain
    if self.nrows % 50000 == 0:
      self.counters['rows processed'] += 50000
    self.store(key, new_row)

  def flush(self, last_flush=False):
    for pair in self.A_data:
      key, value = pair
      if not self.last_step:
        value = struct.pack('d' * len(value), *value)
      yield ('A_matrix', key), value
    self.A_data = []

    if not self.last_step and last_flush:
      if self.first_value is not None:
        yield ('KV_output', self.first_key), [self.first_value, '']
      if self.data != 0.0:
        key = numpy.random.randint(0, 4000000000)
        yield ('KV_output', key), [self.data]

    self.nrows = 0

  def __call__(self, data):
    for key, value in data:
      self.collect_data_instance(key, value)
      if self.nrows == self.blocksize:
        for key, val in self.flush():
          yield key, val
    for key, val in self.flush(last_flush=True):
      yield key, val

class HouseholderRed2(dumbo.backends.common.MapRedBase):
  def __init__(self, step, info_file):
    if step == 0:
      self.picked_set = []
    else:
      self.picked_set, _, _, _ = parse_info(info_file)
    self.picked = None
    self.alpha = None
    self.norm = 0.0

  def collect(self, key, value, picked_possibility=False):
    if picked_possibility:
      if self.picked is None:
        self.picked = key
        self.alpha = value
      self.norm += value * value
    else:
      self.norm += value

  def close(self):
    beta = math.sqrt(self.norm)
    beta = float(-1.0) * math.copysign(beta, self.alpha)
    tau = (beta - self.alpha) / beta
    sigma = float(1.0) / (self.alpha - beta)
    self.alpha = beta
    self.picked_set.append(self.picked)
    yield 'picked_set', self.picked_set
    yield 'alpha', self.alpha
    yield 'tau', tau
    yield 'sigma', sigma

  def __call__(self, data):
    for key, values in data:
      for value in values:
        self.collect(key, float(value[0]), len(value) == 2)

    for key, val in self.close():
      yield key, val

class HouseholderMap3(mrmc.MatrixHandler):
  def __init__(self, step, info_file):
    mrmc.MatrixHandler.__init__(self)
    self.output_vals = {}
    self.step = step
    self.picked_set, self.alpha, _, self.sigma = parse_info(info_file)
    self.last_picked = self.picked_set[-1]
    self.nrows = 0
    self.first_row_done = False

  def collect(self, key, value):
    value = list(value)
    if key == self.last_picked:
      value[self.step] = self.alpha
    elif key not in self.picked_set:
      value[self.step] *= self.sigma
    self.nrows += 1

    # write status updates so Hadoop doesn't complain
    if self.nrows % 50000 == 0:
      self.counters['rows processed'] += 50000

    if not self.first_row_done:
      for i in xrange(self.step + 1, self.ncols):
        self.output_vals[i] = 0.0
      self.first_row_done = True

    if key in self.picked_set:
      if key == self.last_picked:
        for i, val in enumerate(value[self.step + 1:]):
          k = self.step + 1 + i
          self.output_vals[k] += val
    else:
      mult = value[self.step]
      for i, val in enumerate(value[self.step + 1:]):
        k = self.step + 1 + i
        self.output_vals[k] += mult * val

  def close(self):
    for key in self.output_vals:
      yield key, self.output_vals[key]

  def __call__(self, data):
    self.collect_data(data)
    for key, val in self.close():
      yield key, val

class HouseholderRed3(dumbo.backends.common.MapRedBase):
  def __init__(self):
    pass

  def __call__(self, data):
    for key, values in data:
      yield key, sum(values)


text:
package org.qi4j.valueserialization.orgjson;

import java.io.InputStream;
import java.io.OutputStream;
import org.qi4j.api.structure.Application;
import org.qi4j.api.structure.Module;
import org.qi4j.api.type.ValueType;
import org.qi4j.api.value.ValueSerialization;
import org.qi4j.api.value.ValueSerializationException;
import org.qi4j.functional.Function;
import org.qi4j.functional.Function2;

/**
 * ValueSerialization producing and consuming JSON documents using org.json.
 *
 *

 *     This class is used internally by the Qi4j Runtime to provide default ValueSerialization when no
 *     ValueSerialization Service is available.
 *

 *

 *     In application code, prefer the use of {@link OrgJsonValueSerializationService}.
 *

 */
public class OrgJsonValueSerialization
    implements ValueSerialization
{

    private final OrgJsonValueSerializer serializer;
    private final OrgJsonValueDeserializer deserializer;

    public OrgJsonValueSerialization( Application application, Module module, final Module valuesModule )
    {
        this.serializer = new OrgJsonValueSerializer();
        this.deserializer = new OrgJsonValueDeserializer( application, module, new Function<Application, Module>()
        {
            @Override
            public Module map( Application from )
            {
                return valuesModule;
            }
        } );
    }

    @Override
    public <T> Function<T, String> serialize()
    {
        return serializer.serialize();
    }

    @Override
    public <T> Function<T, String> serialize( Options options )
    {
        return serializer.serialize( options );
    }

    @Override
    @Deprecated
    public <T> Function<T, String> serialize( boolean includeTypeInfo )
    {
        return serializer.serialize( includeTypeInfo );
    }

    @Override
    public String serialize( Object object )
        throws ValueSerializationException
    {
        return serializer.serialize( object );
    }

    @Override
    public String serialize( Options options, Object object )
        throws ValueSerializationException
    {
        return serializer.serialize( options, object );
    }

    @Override
    @Deprecated
    public String serialize( Object object, boolean includeTypeInfo )
        throws ValueSerializationException
    {
        return serializer.serialize( object, includeTypeInfo );
    }

    @Override
    public void serialize( Object object, OutputStream output )
        throws ValueSerializationException
    {
        serializer.serialize( object, output );
    }

    @Override
    public void serialize( Options options, Object object, OutputStream output )
        throws ValueSerializationException
    {
        serializer.serialize( options, object, output );
    }

    @Override
    @Deprecated
    public void serialize( Object object, OutputStream output, boolean includeTypeInfo )
        throws ValueSerializationException
    {
        serializer.serialize( object, output, includeTypeInfo );
    }

    @Override
    public <T> Function<String, T> deserialize( Class<T> type )
    {
        return deserializer.deserialize( type );
    }

    @Override
    public <T> Function<String, T> deserialize( ValueType valueType )
    {
        return deserializer.deserialize( valueType );
    }

    @Override
    public <T> Function2<ValueType, String, T> deserialize()
    {
        return deserializer.deserialize();
    }

    @Override
    public <T> T deserialize( Class<?> type, String input )
        throws ValueSerializationException
    {
        return deserializer.deserialize( type, input );
    }

    @Override
    public <T> T deserialize( ValueType type, String input )
        throws ValueSerializationException
    {
        return deserializer.deserialize( type, input );
    }

    @Override
    public <T> T deserialize( Class<?> type, InputStream input )
        throws ValueSerializationException
    {
        return deserializer.deserialize( new ValueType( type ), input );
    }

    @Override
    public <T> T deserialize( ValueType type, InputStream input )
        throws ValueSerializationException
    {
        return deserializer.deserialize( type, input );
    }
}


text:
package uk.ac.open.kmi.msm4j.nfp;

import uk.ac.open.kmi.msm4j.Resource;

import java.net.URI;
import java.net.URL;

/**
 * Created by Luca Panziera on 02/07/2014.
 */
public class Forum extends Resource {
    private Double vitality;
    private URL site;

    public Forum(URI uri) {
        super(uri);
    }

    public Double getVitality() {
        return vitality;
    }

    public void setVitality(Double vitality) {
        this.vitality = vitality;
    }

    public URL getSite() {
        return site;
    }

    public void setSite(URL site) {
        this.site = site;
    }
}


text:
sudo docker run -d --name example-java-echo -p 8080:8080 -p 8081:8081 --link cassandra-1:cassandra \
      -e CASSANDRA_SEED_HOST=cassandra  example/java-echo:0.1


text:
package au.id.cxd.math.probability.regression

import au.id.cxd.math.function.matrix.PseudoInverse
import au.id.cxd.math.probability.analysis.CriticalValue
import au.id.cxd.math.probability.continuous.Normal
import breeze.linalg.{DenseMatrix, DenseVector}

/**
  * ##import MathJax
  *
  *
The Bayesian linear regression for assumed uniform variance.

  *
  *

  * Bayesian Linear Regression extends the Ordinary Least Squares Regression by accounting for the uncertainty about the parameters within the model to generate a posterior distribution for the parameters and a posterior predictive distribution for the target variable. The bayesian regression model makes specific assumptions about the location and variance parameters and about the distributions of each and provides update rules for adjusting the model in light of new examples.
  *

  *
  * The method extends the standard linear regression where
  *
  * $$
  * p(Y|\beta,\sigma^2) \sim N(\mu = X\beta, \Sigma^{-1} = \sigma^2 I)
  * $$
  *
  * Box and Tiao show the distribution to be
  *
  * $$
  * p(Y|\beta,\sigma^2) = \left( \frac{1}{\sqrt{2\pi}} \right)^n \sigma^{-n} \exp{ \left[ -\frac{1}{2\sigma^2} \left[ vs^2 + (\beta - \hat{\beta})'X'X(\beta - \hat{\beta}) \right]  \right] }
  * $$
  *
  * with
  *
  * $$
  * v = n - k
  * $$
  * $$
  * s^2 = (1/v)(Y - \hat{Y})'(Y-\hat{Y})
  * $$
  *
  * $$
  * \hat{\beta} = (X'X)^{-1}X'Y
  * $$
  *
  * $$
  * \hat{Y} = X\hat{\beta}
  * $$
  *
  * The uniform variance $\sigma^2$ estimates the error such that
  *
  * $$
  * p(\epsilon|\sigma^2) \sim N(0, \sigma^2 I)
  * $$
  *
  * The conditional distribution for $Y$ is expressed as
  *
  * $$
  * p(Y|\beta, \sigma^2, X) \sim N(X\beta, \sigma^2I)
  * $$
  *
  * The joint uninformative prior distribution for the parameters $\beta$ and $\sigma^2$ with uniform variance is given as
  *
  * $$
  * p(\beta, \sigma^2 | X) \propto  \sigma^{-2}
  * $$
  *
  *
Posterior distribution for parameters

  *
  * The posterior distribution of the parameters is defined as
  *
  * $$
  * p(\beta,\sigma^2|Y) \propto f(Y|\beta,\sigma^2) \times p(\beta,\sigma^2)
  * $$
  *
  * under uniform variance this is
  *
  * $$
  * \propto \sigma^{-(v+1)} \exp{ \left[ -\frac{1}{2\sigma^2} \left[vs^2 + (\beta - \hat{\beta})'(X'X)(\beta - \hat{\beta}) \right]  \right] }
  * $$
  *
  * Gelman demonstrates that the posterior factorises into
  *
  * $$
  * \propto   \exp{ \left[ (\beta - \hat{\beta})'(X'X)(\beta - \hat{\beta}) \right] } \times \sigma^{-(v+1)} \exp{ \left[ \frac{vs^2}{2\sigma^2} \right]}
  * $$
  *
  * $$
  * N \left(\hat{\beta}, \sigma^2(X'X)^{-1} \right) \times Inverse-\chi^2 (v,s^2)
  * $$
  *
  * Note that $X$ will have the constraint that the number of rows in $X$, $n$ will be greater than the number of columns $k$ and that the columns of $X$ should be linearly independent.
  *
  *
Joint Posterior predictive distribution

  *
  * The joint posterior predictive distribution for new examples $\tilde{Y}$ and $\tilde{X}$ is dependent on the previous conditional distribution of the parameters and the
  * previous data $Y$ and $X$.
  *
  * $$
  * p(\tilde{Y}|\beta,\sigma^2,\tilde{X},Y,X) = f(\tilde{Y}|\beta,\sigma^2,\tilde{X}) \times p(\beta,\sigma^2|Y,X)
  * $$
  *
  * Consider that the conditional distribution of
  *
  * $$
  * p(\tilde{Y}|\beta,\sigma^2,\tilde{X},Y,X) \sim N(\tilde{X}\beta,\sigma^2 I)
  * $$
  *
  * Then the likelihood $\times$ the posterior distribution for the parameters is
  *
  * $$
  * \propto \sigma^{-n} \exp{ \left[ - \frac{1}{2\sigma^2}(\tilde{Y} - \tilde{X}\beta)'(\tilde{Y} - \tilde{X}\beta)  \right] } \times \sigma^{-(n+1)}\exp{\left[ -\frac{1}{2\sigma^2}(Y - X\beta)'(Y - X\beta) \right]  }
  * $$
  *
  * $$
  * \propto \sigma^{-(n + \tilde{n} + 1)} \exp{\left[ -\frac{1}{2\sigma^2} \left( (\tilde{Y} - \tilde{X}\beta)'(\tilde{Y} - \tilde{X}\beta) + (Y-X\beta)'(Y-X\beta)  \right)  \right]}
  * $$
  *
  * In order to obtain the marginal distribution of $\tilde{Y}$, Gelman uses two steps firstly by marginalising $\beta$ and then by marginalising $\sigma$.
  *
  * Using the conditional expectation $\beta$ the parameters for $\mu$ and $\sigma$ of the distribution for $\tilde{Y}$ are derived as
  *
  * $$
  * E\left[\tilde{Y}|\sigma,Y\right] = E\left[ E\left[ \tilde{Y}|\beta,\sigma,Y\right]\right]
  * $$
  *
  * $$
  * E\left[\tilde{Y}|\sigma,Y\right] = E\left[ \tilde{X} \beta | \sigma, Y \right]
  * $$
  *
  * $$
  * \mu = \tilde{X} \hat{\beta}
  * $$
  *
  * And for the variance
  *
  * $$
  * Var\left[\tilde{Y}|\sigma,Y\right] = E\left[ Var\left[\tilde{Y}|\beta,\sigma,Y\right] \right] + Var\left[ E\left[\tilde{Y}|\beta,\sigma,Y\right]  \right]
  * $$
  * $$
  * Var\left[\tilde{Y}|\sigma,Y\right] = E[\sigma^2I|\sigma,Y] + Var[\tilde{X}\beta|\sigma,Y]
  * $$
  * $$
  * Var\left[\tilde{Y}|\sigma,Y\right] = (I + \tilde{X}V_\beta\tilde{X}')\sigma^2
  * $$
  * where $V_\beta = (X'X)^{-1}$
  *
  * The posterior density conditioned on $\sigma$ is
  *
  * $$
  * p(\tilde{Y}|\sigma,Y\tilde{X},X) \sim N\left( \tilde{X}\hat{\beta},  (I + \tilde{X}V_\beta\tilde{X}')\sigma^2 \right)
  * $$
  *
  * The next step is to marginalise over $\sigma$ to obtain the predictive density.
  *
  * $$
  * p(\tilde{Y}|\tilde{X},Y,X) \propto \int p(\tilde{Y}|\sigma,\tilde{X},Y,X) \times p(\sigma|Y,X) d\sigma
  * $$
  * *
  * $$
  * p(\tilde{Y}|\tilde{X},Y,X) \propto \int \sigma^{-(n - k + 1)} \exp{\left[ \frac{\nu s^2}{2\sigma^2} \right]} \times
  * $$
  * *
  * $$
  * (\sigma^2)^{-n/2}\left|I + \tilde{X}V\tilde{X}'\right|^{-n/2}\exp{\left[-\frac{1}{2\sigma^2}(\tilde{X} - \tilde{X}\hat{\beta})'\left[I + \tilde{X}V\tilde{X}' \right]^{-1}(\tilde{X} - \tilde{X}\hat{\beta}) \right]} d\sigma
  * $$
  * *
  * $$
  * \propto \int \sigma^{-(n - k + 1)/2}\left|I + \tilde{X}V\tilde{X}'\right|^{-n/2} \exp{\left[ -\frac{1}{2\sigma^2}\left( \nu s^2  + (\tilde{X} - \tilde{X}\hat{\beta})'\left[I + \tilde{X}V\tilde{X}' \right]^{-1}(\tilde{X} - \tilde{X}\hat{\beta}) \right) \right]} d\sigma
  * $$
  * $$
  * \propto \left|I + \tilde{X}V\tilde{X}'\right|^{-n/2} \int \sigma^{-(\nu + 1)/2} \exp{\left[-\frac{1}{2\sigma^2}A \right]} d\sigma^2
  * $$
  * Where $A = \left( \nu s^2  + (\tilde{X} - \tilde{X}\hat{\beta})'\left[I + \tilde{X}V\tilde{X}' \right]^{-1}(\tilde{X} - \tilde{X}\hat{\beta}) \right)$ and we substitute $z = \frac{A}{2\sigma^2}$ as described in "Quadratic form statistics" on wikipedia (see below) to produce
  * $$
  * p(\tilde{Y}|Y,\tilde{X},X) \propto A^{-\frac{\nu + 1}{2}}\int z^{(\nu - 1)/2}\exp(-z)dz
  * $$
  * which evaluates to
  * $$
  * \left[ 1 + \frac{(\tilde{X} - \tilde{X}\hat{\beta})'\left[I + \tilde{X}V\tilde{X}' \right]^{-1}(\tilde{X} - \tilde{X}\hat{\beta})}{\nu s^2} \right]^{-\frac{1}{2}(\nu + 1)}
  * $$
  * which is a multivariate t-distribution centered at $\tilde{X}\hat{\beta}$ and scaled by $[I+\tilde{X}V\tilde{X}'] s^2$ with $\nu = n - k$ degrees of freedom.
  *
  * The posterior predictive density can be used to draw samples in performing simulation of the distribution of $\tilde{Y}$.
  *
  *
Credible Intervals and Highest Posterior Density

  *
  * Note that earlier the joint posterior distributions of the parameters were derived for $p(\beta|\sigma^2,Y,X)$ and $p(\sigma^2|Y,X)$.
  * Note also that once $\sigma^2$ is marginalised the posterior distribution for $p(\beta|Y,X)$ is
  *
  * $$
  * p(\beta|Y,X) \propto \left[ 1 + \frac{(\beta - \hat{\beta})'X'X(\beta-\hat{\beta})}{\nu s^2} \right] ^ {-\frac{1}{2}(\nu + k)}
  * $$
  *
  * which is a multivariate t-distribution centred at $\hat{\beta}$ and scaled by $X'Xs^2$ with $\nu = n - k$ degrees of freedom.
  *
  * Using the posterior distributions it is possible to obtain credible intervals for the parameters and for the distribution of the expected values of the target variable
  * at a given critical level $\alpha$.
  *
  * The intervals of interest include credible intervals for the mean coefficient parameters $\beta$ under the conditional distiribution $p(\beta|Y,X)$
  * and the credible intervals for the uniform variance $\sigma^2$ given $Y$, $p(\sigma^2|Y)$.
  *
  * When seeking credible intervals for $\beta$ using the posterior multivariate t-distribution $p(\beta|Y,X)$ when variance is assumed known we can make use of the
  * t values for the $1-\alpha$ level at $\nu = n - k$ degrees of freedom scaled by $(X'X)s^2$.
  *
  * $$
  * \hat{\beta} \pm t_{\nu,\alpha/2}\sqrt{(X'X)s^2}
  * $$
  *
  * Since $\sigma^2$ is takne to be of uniform variance it is taken as a univariate parameter. The credible interval is for the univeriate $Inverse-\chi^2$ distribution with degree of freedom $\nu$ and scale $s^2$.
  * The distribution of $W = \frac{s^2}{\sigma^2}$ has the $\chi^2$ distribution of $\nu$ degrees of freedom, the credible intervals are calculated by
  * inverting this quantity such that
  *
  * $$
  * P\left(u < \frac{s^2}{\sigma^2} < l\right) = 1 - \alpha
  * $$
  *
  * $$
  * P \left(\frac{s^2}{l} < \sigma^2 < \frac{s^2}{u} \right) = 1 - \alpha
  * $$
  * with $u$ for the upper and $l$ for the lower tail areas.
  * This can be expressed as
  *
  * $$
  * \sigma^2 \pm \frac{s^2}{\chi^2_{\nu,\alpha2}}
  * $$
  *
  *
Highest Posterior Density

  *
  * The credible interval is extended by the "Highest Posterior Density" (Box and Tiao) which proides a representation of the contours of a multivariate distribution
  * at a number of significant levels for $1 - \alpha$. The highest posterior density is a useful tool for the visualisation of credible regions of the parameter space and
  * for visual comparison of parameter estimates. The parameter space may be partitioned such that
  *
  * $$
  * \beta = \begin{bmatrix}
  * \beta_1 \\
  * \beta_2
  * \end{bmatrix} \begin{matrix}
  * r \\
  * k - r
  * \end{matrix}
  * $$
  * $$
  * \hat{\beta} = \begin{bmatrix}
  * \hat{\beta}_1 \\
  * \hat{\beta}_2
  * \end{bmatrix} \begin{matrix}
  * r \\
  * k - r
  * \end{matrix}
  * $$
  * *
  * $$
  * X'X = \begin{bmatrix}
  * ~ & r & k - r \\
  * r & X_1'X_1 & X_1'X_2 \\
  * k - r & X_2'X_1 & X_2'X_2
  * \end{bmatrix}
  * $$
  * *
  * $$
  * (X'X)^{-1} = C = \begin{bmatrix}
  * ~ & r & k - r \\
  * r & C_{11} & C_{12} \\
  * k - r & C_{21} & C_{22}
  * \end{bmatrix}
  * $$
  * *
  * where $r < k$. The subset $\theta_i$ has the property of being normally distributed
  * $$
  * p(\theta_i|\sigma^2,Y,X) \sim N\left(\hat{\theta_i}, \sigma^2c_{ii}\right)
  * $$
  * where $c_ii$ is the $ith$ diagonal element of $C$, and the conditional distribution of $p(\theta_2|\theta_1,\sigma^2,Y,X)$ is normally distributed such that
  * $$
  * p(\theta_2|\theta_1,\sigma^2,Y,X) \sim N\left(\hat{\theta_{2,1}}, \sigma^2(X_2'X)^{-1}\right)
  * $$
  * where $\hat{\theta_{2,1}} = \hat{\theta_2} + (X_2'X_2)^{-1}X_2X_1(\theta_1 - \hat{\theta_1})$.
  * Once partitioned the regions of the highest posterior density can be computed for the parameters $\theta_1$ and $\theta_2$ and charted for comparison.
  *
  *
Update Rules

  *
  *
  * The bayesian method allows the model to be adjusted in light of new observations by using the posterior distribution as the prior distribution. This allows the parameters to be adjusted given new evidence. The posterior distribution for the parameters factors into
  * $$
  * p(\theta,\sigma^2|Y,X) \propto p(\theta|\sigma^2,Y,X) \times p(\sigma^2|Y,X)
  * $$
  * $$
  * p(\theta,\sigma^2|Y,X) \propto N\left(\hat{\beta},\sigma^2V_\beta\right) \times Inverse-\chi^2(\nu,s^2)
  * $$
  * For the uniform variance it is possible to update first the distribution of $\sigma^2$ and then the distribution of $\beta|\sigma^2$.
  * Since in the posterior distribution of $\sigma^2$ we have two parameters the degrees of freedom $\nu = n - k$ and
  * the scale $s^2 = \frac{1}{\nu}(Y - X\hat{\beta})'(Y-X\hat{\beta})$.
  * When faced with a new set of evidence and observation variables $X_{new}$  with rank $k$ and $Y_{new}$ having variance $\sigma^2$
  * we consider the distribution of the variance in the new data to also be the $Inverse-\chi^2$ distribution with $n_{new} - k$ degrees of freedom
  * and scale $s'^2 = \frac{1}{n_{new} - k}(Y_{new} - X_{new}\hat{\beta})'(Y_{new} - X_{new}\hat{\beta})$.
  * As this is the conjugate prior the update rules (from Boltstad) are as follows.
  * $$
  * s_{n}^2 = s^2 + \frac{1}{n_{new} - k}(Y_{new} - X_{new}\hat{\beta})'(Y_{new} - X_{new}\hat{\beta})
  * $$
  * and the degree of freedom
  * $$
  * \nu_{n} = \nu + (n_{new} - k)
  * $$
  * This gives the updated distribution for $\sigma^2$ as $Inverse-\chi^2(\nu_{n}, s_{n}^2)$.
  * The normal distribution for $p(\theta|\sigma^2,Y,X)$ has the initial parameters
  * $$
  * \mu_0 = \hat{\beta} = V_\beta X'y
  * $$
  * $$
  * \Lambda_0 = V_\beta
  * $$
  * where $V_\beta = (X'X)^{-1}$.
  * When performing the update with the new data we consider the new data to be normally distributed with uniform variance such that $p(\mu|\Sigma,Y_{new},X_{new}) \sim N\left(\mu,\Sigma/n_{new}\right)$.
  * The normal is the conjugate prior so that the update rules can be applied as follows
  * $$
  * \Lambda_n = \Lambda_0^{-1} + \Sigma^{-1}
  * $$
  * $$
  * \mu_n = (\Lambda_0^{-1} + \Sigma^{-1})^{-1}(\Lambda_0^{-1}\mu_0 + \Sigma^{-1}\bar{Y}_{new})
  * $$
  * where $\Sigma = (X_{new}'X_{new})$. The updated distribution for $\beta$ is
  * $$
  * p(\beta|\sigma^2,Y_{new},Y,X_{new},X) \sim N\left(\mu_n, \sigma^2\Lambda_n\right)
  * $$
  * The updated joint distribution becomes
  * $$
  * p(\beta,\sigma^2|Y_{new},Y,X_{new},X) \propto  N\left(\mu_n, \sigma^2\Lambda_n\right) \times Inverse-\chi^2(\nu_n, s_n^2)
  * $$
  *
  *
  *
  *
  *
References

  *
  * For further details see:
  *
  * Box George E P,Tiao George C, Bayesian Inference in Statistical Analysis. Wiley 1992.
  *
  * Gelman Andrew, Carlin John B, Stern Hal S, Dunson David B, Vehtari Aki, Rubin Donald B, Bayesian Data Analysis. Chapman and Hall/CRC Press Taylor and Francis Group 3rd edition, 2013
  *
  * Bishop Christopher M. Pattern Recognition and Machine Learning. Springer Science + Business Media LLC 2006
  *
  * Bolstad William M, Introduction to Bayesian Statistics. Wiley 2nd edition, 2007.
  *
  * "Quadratic form (statistics)", Wikipedia 29th July 2015, 5 Nov 2015. https://en.wikipedia.org/wiki/Quadratic_form_(statistics)
  *
  *
  *
Implementation and Usage

  *
  * This class implements the bayes linear regression for uniform variance.
  * It extends the OLS method and adds an Update method in order to update the generated model in light of new data
  * using the update rules above.
  *
  *
  * This class
  *
  * Created by cd on 17/04/2016.
  */
class BayesLinearRegression(@transient var inX: DenseMatrix[Double], @transient var inY: DenseVector[Double], override val m: Int = 1)
  extends OrdLeastSquares(inX, inY, m) with UpdatableRegressor {

  /**
    * implement the update rules for the linear regression model after already having trained the model.
    *
    * This will update the parameter matrix Beta and the variance.
    *
    * it will not predict against the data, after updating use the predict methods to get a prediction and calculate residuals.
    *
    * @param newX
    * @param newY
    */
  override def update(newX: DenseMatrix[Double], newY: DenseVector[Double])  : (DenseMatrix[Double], Double) = {
    val newP = createPolynomial(newX, m)

    val newY1 = DenseMatrix.tabulate[Double](newY.length, 1) { case (i, j) => newY(i) }

    val prevB = Beta
    val prevSigma = variance
    // the df has been stored from the last iteration.
    val lastdf = this.df
    val nu = lastdf + (newP.rows - newP.cols)

    val prevMu = (1.0 / Y.length) * Y.foldLeft(0.0) { (accum, y) => accum + y }

    val mu = (1.0 / newY.length) * newY.foldLeft(0.0) { (accum, y) => accum + y }

    val prevSd = (1.0 / (Y.length - 1)) * Y.foldLeft(0.0) { (accum, y) => accum + Math.pow((y - prevMu), 2) }

    val sd = (1.0 / (newY.length - 1)) * newY.foldLeft(0.0) { (accum, y) => accum + Math.pow((y - mu), 2) }

    val muC = (prevMu + mu) / 2.0

    // the new uniform variance
    val sigma = (P.rows * (prevSd + Math.pow(prevMu - muC, 2)) + newP.rows * (sd + Math.pow(mu - muC, 2))) / (P.rows + newP.rows)
    val newVariance = Math.pow(sigma, 2)

    /**
      * determine the new value for $\sigmaI$ from the prior work I've done in my research assignments
      * the new $I$ is not the identity matrix, but it taken from the diagonal of the $V_\beta = (X'X)^{-1}$ parameter.
      * The diagonal is used in the OLS as the $v_j$ parameter for the variance of the $\beta$ parameter.
      **/
    val newI = DenseMatrix.tabulate[Double](pseudoInverse.rows, pseudoInverse.cols) {
      case (i, j) => i == j match {
        case true => {
          // uniform variance
          // sigma
          // based on previous beta variance
          pseudoInverse(j, j)
        }
        case _ => 0.0
      }
    }
    val mu0 = Beta
    val lambda0 = pseudoInverse
    val cov = DenseMatrix.tabulate(newI.rows, newI.cols) {
      case (i,j) => newVariance * newI(i,j)
    }
    val lambdaNew = lambda0 + cov

    /**
      * from R
      *
      * ones of mu2
      *
      * MeanVec <- as.matrix(sample(x = c(1), size = nrow(Mu0), replace = TRUE) * mu2)
      * *
      *
      *
      * Mu2 <- ginv(ginv(Lambda0) + n2*ginv(Lambda2)) %*%(ginv(Lambda0)%*%Mu0 + n2*ginv(Cov)%*%MeanVec)
      * Mu2 <- data.frame(Mu2)
      * rownames(Mu2) <- rownames(Mu0)
      * result2$V <- Lambda2
      * result2$B <- as.matrix(Mu2)
      */

    /**
      * calculate the new Beta
      *
      * Mu2 <- ginv( ginv(Lambda0) + n2*ginv(Lambda2) ) %*%(ginv(Lambda0)%*%Mu0 + n2*ginv(Cov)%*%MeanVec)
      * Mu2 <- data.frame(Mu2)
      * result2$B <- as.matrix(Mu2)
      */
    // inverse of the inverse
    val meanVec = DenseMatrix.ones[Double](mu0.t.rows, 1) * mu
    val invLambda1 = PseudoInverse(lambda0)
    val invLambda2 = PseudoInverse(lambdaNew)
    val invCov = PseudoInverse(cov)
    val mat1 = invLambda1 + (invLambda2 * newP.rows.toDouble)
    val a = mu0 * invLambda1
    val b = meanVec.t * (invCov * newP.rows.toDouble)

    val mat2 = DenseMatrix.tabulate[Double](b.rows, b.cols) {
      case (i, j) => b(i, j) + a(0,j)
    }

    /**
      *  Mu2 <- ginv( ginv(Lambda0) + n2*ginv(Lambda2) ) %*%(ginv(Lambda0)%*%Mu0 + n2*ginv(Cov)%*%MeanVec)
      * becomes
      * ginv(mat1) * (a + b)
      */

    val newBeta = mat2 * PseudoInverse(mat1)
    // update the parameters
    pseudoInverse = lambdaNew
    Beta = newBeta
    variance = newVariance

    // estimate $\hat{Y}$
    val yHat = Beta * newP.t
    residuals = (newY1 - yHat.t).toDenseVector
    mse = squaredError(yHat.t, newY1)

    // update the z-values and p-values
    // take the diagonal of the pseudoInverse (X'X)^-1
    // note that the pseudoinverse actually may be negative, the square root may infact be imaginary.
    val vj = DenseVector.tabulate(pseudoInverse.cols) {
      j => pseudoInverse(j, j)
    }
    /*
    * $$
      * z_j = \frac{\hat{\beta_j}}{\hat{\sigma}\sqrt{v_j}}
    * $$
    *
    * Since we are predicting a 1 column Y vector the beta matrix is always a single column matrix
    *
    * The row in beta corresponds to the coefficient of the ith column in X.
    *
    */
    betaZScore = DenseMatrix.tabulate[Double](Beta.rows, Beta.cols) {
      case (i, j) => Beta(i, j) / sigma * Math.sqrt(vj(i))
    }

    /**
      * the corresponding p-value for beta_j can be calculated
      * from the T distribution with N - p - 1 degrees of freedom.
      * The null hypothesis is that beta_j is equal to 0, and therefore the corresponding X value does not contribute
      * to the prediction.
      *
      * Testing against the hypothesis we reject the hypothesis if { |Z| > 0 }
      */
    val stdNorm = Normal(0.0)(1.0)
    betaPValue = DenseMatrix.tabulate[Double](betaZScore.rows, betaZScore.cols) {
      case (i, j) => stdNorm.pdf(betaZScore(i, j))
    }

    val criticalValue = CriticalValue.upperCriticalValue(0.0, 4 * 1.0, stdNorm)
    criticalBetaZValue = criticalValue.value(alpha)
    criticalPValue = stdNorm.pdf(criticalBetaZValue)

    (yHat, mse)
  }

}

object BayesLinearRegression {
  def apply(inX: DenseMatrix[Double], inY: DenseVector[Double], m: Int = 1) =
    new BayesLinearRegression(inX, inY, m)
}


text:
#requires -Modules ExchangeAnalyzer

#This function tests each Exchange server to verify if SSL 3.0 is disabled
Function Run-CAS003()
{
    [CmdletBinding()]
    param()

    $TestID = "CAS003"
    Write-Verbose "----- Starting test $TestID"

    $PassedList = @()
    $FailedList = @()
    $WarningList = @()
    $InfoList = @()
    $ErrorList = @()

    foreach ($server in $exchangeservers) {
        # Set the inital value
        $name = $server.name
        $up = $true
        $SSLv3Enabled = $null
        try {
            $Registry = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey("LocalMachine",$name)
        } catch {
            $up = $false
        }

        if ($up -eq $true) {
            # Check the registry path
            $check1 = $registry.OpenSubKey("System\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0")

            if ($check1 -ne $null) {
                # Check the next registry path
                $check2 = $registry.OpenSubKey("System\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Server")

                if ($check2 -ne $null) {

                    # Check to see if Enabled value is present with a '0' value
                    $check3 = $registry.OpenSubKey("System\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Server").GetValue("Enabled")
                    if ($Check3 -eq "0") {
                        $SSLv3Enabled = $true
                    } else {
                        $SSLv3Enabled = $false
                    }
                }
            }

            # Decide if the test has failed based off of the values missing or present and what value is there if present
            Switch ($SSLv3Enabled)
            {
                $true {
                        $PassedList += $name
                        Write-Verbose "SSL 3.0 is disabled on the server $name"
                    }
                $false {
                        $FailedList += $name
                        Write-Verbose "SSL 3.0 is not disabed on server $name"
                    }
                default {
                        Write-Verbose "SSL 3.0 status could not be determined for $name"
                        $WarningList += "$name - SSL 3.0 status unknown"
                    }
            }

        }
        else
        {
            $WarningList += "$name - unable to connect to registry"
            Write-Verbose "Unable to connect to registry of $name"
        }
    }

    #Roll the object to be returned to the results
    $ReportObj = Get-TestResultObject -ExchangeAnalyzerTests $ExchangeAnalyzerTests `
                                      -TestId $TestID `
                                      -PassedList $PassedList `
                                      -FailedList $FailedList `
                                      -WarningList $WarningList `
                                      -InfoList $InfoList `
                                      -ErrorList $ErrorList `
                                      -Verbose:($PSBoundParameters['Verbose'] -eq $true)

    return $ReportObj
}

Run-CAS003


text:
package quanlynhansu.controller;

import java.sql.SQLException;
import java.util.ArrayList;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import quanlynhansu.model.dto.DonViChucNangDTO;
import quanlynhansu.model.dto.HopDongCanBoDTO;
import quanlynhansu.model.dto.LoaiHopDongDTO;
import quanlynhansu.service.IDonViChucNangService;
import quanlynhansu.service.IHopDongCanBoService;
import quanlynhansu.service.ILoaiHopDongService;

@Controller
@RequestMapping("/hopDongCanBoController")
public class HopDongCanBoController {
	@Autowired
	private IHopDongCanBoService hopDongCanBoService;
	@Autowired
	private IDonViChucNangService donViChucNangService;
	@Autowired
	private ILoaiHopDongService loaiHopDongService;

	@GetMapping("/show")
	public ModelAndView getdata() {
		ArrayList<DonViChucNangDTO> donViChucNangLists = donViChucNangService.getAll();
		ArrayList<LoaiHopDongDTO> loaiHopDongLists = loaiHopDongService.getAll();
		ModelAndView model = new ModelAndView("hopdongcanbo");
		model.addObject("donViChucNangLists", donViChucNangLists);
		model.addObject("loaiHopDongLists", loaiHopDongLists);
		return model;
	}

	@RequestMapping(value = "/delete/{pK}", method = RequestMethod.DELETE)
	public String delete(@PathVariable Integer pK, @RequestParam(value = "version") Integer version) {
		hopDongCanBoService.delete(pK, version);
		return "hopdongcanbo";
	}

	@PostMapping("/update")
	public String update(@RequestBody HopDongCanBoDTO hd, Model model) throws SQLException {
		hopDongCanBoService.update(hd);
		return "hopdongcanbo";
	}

	@PostMapping("/add")
	public String insert(@RequestBody HopDongCanBoDTO hd, Model model) throws SQLException {
		hopDongCanBoService.insert(hd);
		return "hopdongcanbo";
	}
}