text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<pipeline>
  <component>
    <id>img_input</id>
    <name>img_input</name>
    <class>ImgInput</class>
    <autoglue>true</autoglue>
    <property>
        <name>file_path</name>
        <value type="str">tmp/small.JPG</value>
    </property>
</component>
<component>
    <id>gray_scale</id>
    <name>gray_scale</name>
    <class>GrayScale</class>
    <autoglue>true</autoglue>
</component>
<component>
    <id>rotate</id>
    <name>rotate</name>
    <class>Rotate</class>
    <autoglue>true</autoglue>
    <property>
        <name>angle</name>
        <value type="float">10</value>
    </property>
    <additional_component>
        <id>parameter_condition</id>
        <notifier>condition</notifier>
    </additional_component>
</component>
<component>
    <id>parameter_condition</id>
    <name>condition</name>
    <class>Condition</class>
    <autoglue>true</autoglue>
    <property>
        <name>type</name>
        <value type="str">parameter</value>
    </property>
    <property>
        <name>name</name>
        <value type="str">angle</value>
    </property>
    <property>
        <name>operator</name>
        <value type="str">ge</value>
    </property>
    <property>
        <name>value</name>
        <value type="int">180</value>
    </property>
</component>
<component>
    <id>img_output</id>
    <name>img_output</name>
    <class>ImgOutput</class>
    <autoglue>true</autoglue>
    <property>
        <name>file_path</name>
        <value type="str">tmp/test.png</value>
    </property>
</component>
<component>
    <id>chart_visu</id>
    <name>line</name>
    <class>Line</class>
    <autoglue>false</autoglue>
    <property>
        <name>parameter_list</name>
        <value type="str">angle</value>
    </property>
    <additional_component>
        <id>rotate</id>
        <notifier>output</notifier>
    </additional_component>
</component>
<component>
    <id>histogram</id>
    <name>histogram</name>
    <class>Histogram</class>
    <autoglue>false</autoglue>
    <additional_component>
        <id>gray_scale</id>
        <notifier>output</notifier>
    </additional_component>
</component>
<component>
    <id>histo_visu</id>
    <name>line</name>
    <class>Line</class>
    <autoglue>false</autoglue>
    <property>
        <name>parameter_list</name>
        <value type="str">histogram</value>
    </property>
    <property>
        <name>type</name>
        <value type="str">update</value>
    </property>
    <additional_component>
        <id>histogram</id>
        <notifier>output</notifier>
    </additional_component>
</component>

</pipeline>


text:
import _ from 'lodash';
import tooltipFormatter from './formatter.js';
import numberValueFormatter from './number-value-formatter.js';

const defaultOptions = {
    tooltip: {
        trigger: 'axis',
        axisPointer: {
            type: 'line',
            snap: true
        },
        // 是否将 tooltip 框限制在图表的区域内。
        confine: true
        // alwaysShowContent: true
    },
    yAxis: {
        axisLabel: {}
    },
    xAxis: {
        show: true,
        axisLabel: {
            rotate: 40
        }
    },
    grid: {
        left: '4%',
        right: '4%',
        bottom: '10%'
    }
};

// 转换 bar 映射
const transformBarEncode = (
    encodeSeriesItem,
    source,
    nameMapper,
    encodeSeriesType
) => {
    const {
        name = 'name',
        x,
        y,
        stack,
        seriesIndex = 0,
        flip,
        label: encodeSeriesLabel
    } = encodeSeriesItem;
    const {
        tooltip,
        xAxis: encodeXAxis = {},
        yAxis: encodeYAxis = {},
        legend
    } = encodeSeriesItem.__parent;
    const xAxis = {
        axisLabel: {}
    };
    const yAxis = {
        axisLabel: {}
    };
    const grid = {};
    // xAxis.axisLabel.formatter 支持
    if (encodeXAxis.axisLabel) {
        xAxis.axisLabel = _.merge({}, encodeXAxis.axisLabel);
    }
    if (encodeXAxis.show != undefined) {
        xAxis.show = encodeXAxis.show;
    }
    if (encodeYAxis.show != undefined) {
        yAxis.show = encodeYAxis.show;
    }
    // yAxis.axisLabel.formatter 支持
    if (encodeYAxis.axisLabel) {
        yAxis.axisLabel = _.merge({}, encodeYAxis.axisLabel);
    }
    // xAxis.type 支持
    if (encodeXAxis.type) {
        xAxis.type = encodeXAxis.type;
    }
    // yAxis.type 支持
    if (encodeYAxis.type) {
        yAxis.type = encodeYAxis.type;
    }
    const seriesList = [];
    const nextTooltip = {
        formatter: (...args) => {
            if (encodeSeriesType === 'all') {
                return tooltipFormatter(...args, source, tooltip, nameMapper);
            } else {
                const sourceItem = source[seriesIndex];
                return tooltipFormatter(
                    ...args,
                    [sourceItem],
                    tooltip,
                    nameMapper
                );
            }
        }
    };

    const handleSourceItem = (sourceItem, sourceIndex) => {
        const { dataset = [] } = sourceItem;
        if (!Array.isArray(dataset)) {
            return {};
        }
        const seriesItem = {
            name: sourceItem[name],
            data: [],
            type: 'bar'
        };
        if (encodeSeriesLabel) {
            seriesItem.label = encodeSeriesLabel;
        }
        // 是否堆叠
        if (stack === true) {
            seriesItem.stack = true;
            seriesItem.areaStyle = { normal: {} };
        }
        dataset.forEach(dataItem => {
            const xValue = dataItem[x] || '';
            const yValue = dataItem[y] || '';
            if (sourceIndex === 0) {
                if (flip === true) {
                    if (!yAxis.data) {
                        yAxis.data = [];
                    }
                    if (!yAxis.type) {
                        yAxis.type = 'category';
                    }
                    yAxis.data.push(xValue);
                    grid.containLabel = true;
                    grid.left = '2%';
                    grid.bottom = '4%';
                    xAxis.axisLabel.formatter = numberValueFormatter;
                } else {
                    if (!xAxis.data) {
                        xAxis.data = [];
                    }
                    xAxis.data.push(xValue);
                    yAxis.axisLabel.formatter = numberValueFormatter;
                }
            }
            seriesItem.data.push(yValue);
        });
        seriesList.push(seriesItem);
    };

    // 通用映射显示所有数据集
    if (encodeSeriesType === 'all') {
        source.forEach((sourceItem, sourceIndex) => {
            handleSourceItem(sourceItem, sourceIndex);
        });
    } else {
        const sourceItem = source[seriesIndex] || {};
        const sourceIndex = 0;
        handleSourceItem(sourceItem, sourceIndex);
    }

    const resultOptions = _.merge({}, defaultOptions, {
        xAxis,
        yAxis,
        grid,
        tooltip: nextTooltip,
        series: seriesList,
        legend: legend
    });

    if (!resultOptions.legend) {
        if (seriesList.length > 1) {
            resultOptions.legend = {
                type: 'scroll'
            };
            resultOptions.grid.top = '10%';
        } else {
            resultOptions.grid.top = '6%';
        }
    }

    return resultOptions;
};

export default transformBarEncode;

redpajama_set_name: RedPajamaGithub


text:
using System;
using Gwen.Control;
using Gwen.Control.Layout;

namespace Gwen.UnitTest
{
    public class UnitTest : DockBase
    {
        private Control.Base m_LastControl;
        private readonly Control.StatusBar m_StatusBar;
        private readonly Control.ListBox m_TextOutput;
        private Control.TabButton m_Button;
        private readonly Control.CollapsibleList m_List;
        private readonly Center m_Center;
        private readonly Control.LabeledCheckBox m_DebugCheck;

        public double Fps; // set this in your rendering loop
        public string Note; // additional text to display in status bar

        public UnitTest(Base parent) : base(parent)
        {
            Dock = Pos.Fill;
            m_List = new Control.CollapsibleList(this);

            LeftDock.TabControl.AddPage("Unit tests", m_List);
            LeftDock.Width = 150;

            m_TextOutput = new Control.ListBox(BottomDock);
            m_Button = BottomDock.TabControl.AddPage("Output", m_TextOutput);
            BottomDock.Height = 200;

            m_DebugCheck = new Control.LabeledCheckBox(m_List);
            m_DebugCheck.Text = "Debug outlines";
            m_DebugCheck.CheckChanged += DebugCheckChanged;

            m_StatusBar = new Control.StatusBar(this);
            m_StatusBar.Dock = Pos.Bottom;
            m_StatusBar.AddControl(m_DebugCheck, true);

            m_Center = new Center(this);
            m_Center.Dock = Pos.Fill;
            GUnit test;

            {
                CollapsibleCategory cat = m_List.Add("Non-Interactive");
                {
                    test = new Label(m_Center);
                    RegisterUnitTest("Label", cat, test);
                    test = new RichLabel(m_Center);
                    RegisterUnitTest("RichLabel", cat, test);
                    test = new GroupBox(m_Center);
                    RegisterUnitTest("GroupBox", cat, test);
                    test = new ProgressBar(m_Center);
                    RegisterUnitTest("ProgressBar", cat, test);
                    test = new ImagePanel(m_Center);
                    RegisterUnitTest("ImagePanel", cat, test);
                    test = new StatusBar(m_Center);
                    RegisterUnitTest("StatusBar", cat, test);
                }
            }

            {
                CollapsibleCategory cat = m_List.Add("Standard");
                {
                    test = new Button(m_Center);
                    RegisterUnitTest("Button", cat, test);
                    test = new TextBox(m_Center);
                    RegisterUnitTest("TextBox", cat, test);
                    test = new CheckBox(m_Center);
                    RegisterUnitTest("CheckBox", cat, test);
                    test = new RadioButton(m_Center);
                    RegisterUnitTest("RadioButton", cat, test);
                    test = new ComboBox(m_Center);
                    RegisterUnitTest("ComboBox", cat, test);
                    test = new ListBox(m_Center);
                    RegisterUnitTest("ListBox", cat, test);
                    test = new NumericUpDown(m_Center);
                    RegisterUnitTest("NumericUpDown", cat, test);
                    test = new Slider(m_Center);
                    RegisterUnitTest("Slider", cat, test);
                    test = new Menu(m_Center);
                    RegisterUnitTest("Menu", cat, test);
                    test = new CrossSplitter(m_Center);
                    RegisterUnitTest("CrossSplitter", cat, test);
                }
            }

            {
                CollapsibleCategory cat = m_List.Add("Containers");
                {
                    test = new Window(m_Center);
                    RegisterUnitTest("Window", cat, test);
                    test = new TreeControl(m_Center);
                    RegisterUnitTest("TreeControl", cat, test);
                    test = new Properties(m_Center);
                    RegisterUnitTest("Properties", cat, test);
                    test = new TabControl(m_Center);
                    RegisterUnitTest("TabControl", cat, test);
                    test = new ScrollControl(m_Center);
                    RegisterUnitTest("ScrollControl", cat, test);
                    test = new Docking(m_Center);
                    RegisterUnitTest("Docking", cat, test);
                }
            }

            {
                CollapsibleCategory cat = m_List.Add("Non-standard");
                {
                    test = new CollapsibleList(m_Center);
                    RegisterUnitTest("CollapsibleList", cat, test);
                    //test.Show();
                    test = new ColorPickers(m_Center);
                    RegisterUnitTest("Color pickers", cat, test);
                }
            }

            m_StatusBar.SendToBack();
            PrintText("Unit Test started!");
        }

        public void RegisterUnitTest(string name, CollapsibleCategory cat, GUnit test)
        {
            Control.Button btn = cat.Add(name);
            test.Dock = Pos.Fill;
            test.Hide();
            test.UnitTest = this;
            btn.UserData = test;
            btn.Clicked += OnCategorySelect;
        }

		private void DebugCheckChanged(Base control, EventArgs args)
        {
            if (m_DebugCheck.IsChecked)
                m_Center.DrawDebugOutlines = true;
            else
                m_Center.DrawDebugOutlines = false;
            Invalidate();
        }

		private void OnCategorySelect(Base control, EventArgs args)
        {
            if (m_LastControl != null)
            {
                m_LastControl.Hide();
            }
            Base test = control.UserData as Base;
            test.Show();
            m_LastControl = test;
        }

        public void PrintText(string str)
        {
            m_TextOutput.AddRow(str);
			m_TextOutput.ScrollToBottom();
        }

        protected override void Layout(Skin.Base skin)
        {
            base.Layout(skin);
        }

        protected override void Render(Skin.Base skin)
        {
            m_StatusBar.Text = String.Format("GWEN.Net Unit Test - {0:F0} fps. {1}", Fps, Note);

            base.Render(skin);
        }
    }
}


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

from py3compat import implements_to_string
from django.db import models

from uninond.models.SMSMessages import SMSMessage
from uninond.tools import normalized_phonenumber, phonenumber_repr

logger = logging.getLogger(__name__)

@implements_to_string
class Contact(models.Model):

    GOUVERNEUR = 'gouverneur'
    PREFET = 'prefet'
    SOUS_PREFET = 'sous-prefet'
    MAIRE = 'maire'
    DUGUTIGI = 'dugutigi'
    DRPC = 'DRPC'
    DRDSES = 'DRDSES'
    DRS = 'DRS'

    ROLES = {
        GOUVERNEUR: "Gouverneur",
        PREFET: "Préfet",
        SOUS_PREFET: "Sous-préfet",
        MAIRE: "Maire",
        DUGUTIGI: "Chef de village",
        DRPC: "DRPC",
        DRDSES: "DRDSES",
        DRS: "DRS"
    }

    identity = models.CharField(max_length=50, primary_key=True,
                                verbose_name="Numéro téléphone")
    name = models.CharField(max_length=200, blank=True, null=True,
                            verbose_name="Nom")
    role = models.SlugField(max_length=200, choices=ROLES.items(),
                            null=True, blank=True,
                            verbose_name="Rôle")
    position = models.CharField(max_length=500, blank=True, null=True,
                                verbose_name="Fonction")
    location = models.ForeignKey('Location', verbose_name="Localité")
    active = models.BooleanField(default=True, verbose_name="Actif ?")

    def __str__(self):
        return self.short_name

    @property
    def verbose_identity(self):
        return phonenumber_repr(self.identity)

    @property
    def short_name(self):
        if self.name:
            return self.name
        return self.verbose_identity

    @property
    def is_main(self):
        return self.location.main_contact == self

    @property
    def full_name(self):
        if not self.role and not self.location:
            return self.short_name
        elif not self.location:
            return "{name}, {role}".format(name=self.short_name,
                                           role=self.verbose_role)
        elif not self.role:
            return "{name} de {location}".format(
                name=self.short_name, location=self.location.name)
        else:
            return "{name}, {role_location}".format(
                name=self.short_name, role_location=self.display_role)

    @property
    def display_role(self):
        return "{role} de {location}".format(
            role=self.ROLES.get(self.role) or "Inconnu",
            location=self.location.name)

    @property
    def sms_name(self):
        if self.name:
            return "{name}/{num}".format(name=self.name,
                                         num=self.verbose_identity)
        return self.verbose_identity

    @classmethod
    def get_verbose_role(cls, role):
        return cls.ROLES.get(role) or "Inconnu"

    @property
    def verbose_role(self):
        return self.get_verbose_role(self.role)

    @classmethod
    def get_or_none(cls, identity):
        try:
            return cls.objects.get(identity=normalized_phonenumber(identity))
        except cls.DoesNotExist:
            return None

    @classmethod
    def get_or_create(cls, identity, location):
        qs = Contact.objects.filter(identity=identity)
        if qs.count():
            contact = qs.get()
            if location != contact.location:
                contact.location = location
                contact.save()
            return contact
        else:
            return Contact.objects.create(
                identity=identity,
                name=phonenumber_repr(identity),
                location=location)

    @classmethod
    def all_from(cls, location_types, identies_only=False):
        qs = cls.objects.filter(active=True) \
                        .filter(location__location_type__in=location_types)
        if identies_only:
            return [c['identity'] for c in qs.values('identity')]
        else:
            return qs

    @classmethod
    def dispatch_list(cls, gouverneur=False, drpc=False, verbose=False):
        dlist = []
        if gouverneur:
            dlist.append(cls.GOUVERNEUR)
        if drpc:
            dlist.append(cls.DRPC)

        dlist += [cls.DRS, cls.DRDSES, cls.MAIRE, cls.SOUS_PREFET, cls.PREFET]

        if verbose:
            return [cls.get_verbose_role(r) for r in dlist]

        return dlist

    def disable(self):
        self.active = False
        self.save()

    def enable(self):
        self.active = True
        self.save()

    @property
    def messages(self):
        return SMSMessage.objects.filter(identity=self.identity) \
                                 .order_by('-created_on')


text:
"use strict";

/**
 * Head Mounted Devices add-on.
 * Provides support for HMD devices using WebVR API.
 * @see https://developer.mozilla.org/en-US/docs/Web/API/WebVR_API
 * @module hmd
 */

b4w.module["hmd"] = function(exports, require) {

var m_cam    = require("camera");
var m_ctl    = require("controls");
var m_input  = require("input");
var m_quat   = require("quat");
var m_scenes = require("scenes");
var m_trans  = require("transform");
var m_util   = require("util");
var m_vec3   = require("vec3");

var _last_cam_quat = m_quat.create();
var _yaw_cam_angle = 0;
var _was_target_camera = false;
var _was_hover_camera = false;
var _was_static_camera = false;

var _vec3_tmp  = m_vec3.create();
var _vec3_tmp2 = m_vec3.create();
var _vec3_tmp3 = m_vec3.create();
var _quat_tmp  = m_quat.create();
var _quat_tmp2 = m_quat.create();
var _quat_tmp3 = m_quat.create();

/**
 * HMD behavior enum.
 * @see {@link module:hmd.HMD_NONE_MOUSE_ALL_AXES},
 * {@link module:hmd.HMD_ALL_AXES_MOUSE_NONE},
 * {@link module:hmd.HMD_ROLL_PITCH_MOUSE_YAW},
 * {@link module:hmd.HMD_ALL_AXES_MOUSE_YAW}
 * @typedef HMDBehavior
 * @type {Number}
 */

/**
 * HMD behavior: HMD does not affect camera orientation,
 * mouse controls camera rotation.
 * @const {HMDBehavior} module:hmd.HMD_NONE_MOUSE_ALL_AXES
 */
var HMD_NONE_MOUSE_ALL_AXES = 0;
exports.HMD_NONE_MOUSE_ALL_AXES = HMD_NONE_MOUSE_ALL_AXES;

/**
 * HMD behavior: HMD controls camera rotation,
 * mouse does not affect camera orientation.
 * @const {HMDBehavior} module:hmd.HMD_ALL_AXES_MOUSE_NONE
 */
var HMD_ALL_AXES_MOUSE_NONE = 1;
exports.HMD_ALL_AXES_MOUSE_NONE = HMD_ALL_AXES_MOUSE_NONE;

/**
 * HMD behavior: HMD controls roll and ritch rotation,
 * mouse controls yaw rotation.
 * @const {HMDBehavior} module:hmd.HMD_ROLL_PITCH_MOUSE_YAW
 */
var HMD_ROLL_PITCH_MOUSE_YAW = 2;
exports.HMD_ROLL_PITCH_MOUSE_YAW = HMD_ROLL_PITCH_MOUSE_YAW;

/**
 * HMD behavior: HMD affects camera rotation,
 * mouse affect yaw rotation.
 * @const {HMDBehavior} module:hmd.HMD_ALL_AXES_MOUSE_YAW
 */
var HMD_ALL_AXES_MOUSE_YAW = 3;
exports.HMD_ALL_AXES_MOUSE_YAW = HMD_ALL_AXES_MOUSE_YAW;

/**
 * Enable HMD.
 * @method module:hmd.enable_hmd
 * @param {HMDBehavior} control_type Camera rotation type.
 */
exports.enable_hmd = function(control_type) {
    var sensor = null;
    var device = m_input.get_device_by_type_element(m_input.DEVICE_HMD);
    if (device) {
        if (m_input.get_value_param(device, m_input.HMD_WEBVR_TYPE) ==
                m_input.HMD_WEBVR_DESKTOP
                || m_input.get_value_param(device, m_input.HMD_WEBVR_TYPE) ==
                        m_input.HMD_WEBVR1)
            sensor = m_ctl.create_hmd_quat_sensor();
        else
            // m_input.HMD_WEBVR_TYPE in {m_input.HMD_NON_WEBVR, m_input.HMD_WEBVR_MOBILE}
            sensor = m_ctl.create_gyro_quat_sensor();
        process_hmd(control_type, sensor);
    }
}

/**
 * Check if the browser supports WebVR API or it is a mobile version of the browser.
 * @method module:hmd.check_browser_support
 * @return {Boolean} Checking result.
 */
exports.check_browser_support = function() {
    return Boolean(m_input.can_use_device(m_input.DEVICE_HMD));
}

/**
 * Get mounted hmd device.
 * @method module:hmd.get_hmd_device
 * @return {HMDVRDevice} HMD object.
 * @deprecated
 */
exports.get_hmd_device = function() {
    return null;
}

/**
 * Reset the sensors, return position and orientation sensors values to zero.
 * @method module:hmd.reset
 * @deprecated Use {@link module:input.reset_device} instead
 */
exports.reset = function() {
    m_input.reset_device(m_input.DEVICE_HMD);
}

function process_hmd(control_type, sensor) {
    if (!sensor)
        return;

    var cam_obj = m_scenes.get_active_camera();
    if (!cam_obj)
        return;
    else
        if (!m_cam.is_eye_camera(cam_obj)) {
            _was_target_camera = m_cam.is_target_camera(cam_obj);
            _was_hover_camera = m_cam.is_hover_camera(cam_obj);
            _was_static_camera = m_cam.is_static_camera(cam_obj);

            m_cam.eye_setup(cam_obj);
        }

    var elapsed = m_ctl.create_elapsed_sensor();

    var updated_eye_data = false;
    var move_cam_cb = function(obj, id, pulse) {
        if (pulse > 0) {
            var cam_obj = m_scenes.get_active_camera();
            if (!cam_obj)
                return;

            // NOTE: init part
            if (!updated_eye_data && m_input.enable_split_screen(cam_obj)) {
                _last_cam_quat = m_trans.get_rotation(cam_obj, _last_cam_quat);
                updated_eye_data = true;
            }

            // NOTE: It is executed every frame.
            // uses _vec3_tmp, _vec3_tmp2, _vec3_tmp3, _quat_tmp, _quat_tmp2
            if (updated_eye_data && m_cam.is_eye_camera(cam_obj)) {
                var hmd_quat = m_ctl.get_sensor_payload(obj, id, 1);
                if (hmd_quat) {
                    if (control_type == HMD_ALL_AXES_MOUSE_NONE) {
                        var up_axis = m_vec3.transformQuat(m_util.AXIS_MY, hmd_quat, _vec3_tmp);
                        m_cam.set_vertical_axis(cam_obj, up_axis);
                        m_trans.set_rotation_v(cam_obj, hmd_quat);
                    } else if (control_type == HMD_ROLL_PITCH_MOUSE_YAW ||
                            control_type == HMD_ALL_AXES_MOUSE_YAW) {
                        var cam_quat = m_trans.get_rotation(cam_obj,
                                _quat_tmp2);
                        var inv_cam_quat = m_quat.invert(cam_quat,
                                _quat_tmp2);
                        var diff_cam_quat = m_quat.multiply(_last_cam_quat,
                                inv_cam_quat, _quat_tmp2);

                        var cur_vertical_axis = m_cam.get_vertical_axis(cam_obj,
                                _vec3_tmp);
                        if (Math.abs(cur_vertical_axis[2]) < Math.PI / 4)
                            var first_horiz_vec = m_vec3.cross(cur_vertical_axis,
                                    m_util.AXIS_MY, _vec3_tmp2);
                        else if (Math.abs(cur_vertical_axis[1]) < Math.PI / 4)
                            var first_horiz_vec = m_vec3.cross(cur_vertical_axis,
                                    m_util.AXIS_Z, _vec3_tmp2);

                        m_vec3.normalize(first_horiz_vec, first_horiz_vec);

                        var rotated_first_horiz_vec = m_vec3.transformQuat(
                                first_horiz_vec, diff_cam_quat, _vec3_tmp3);

                        var vertical_coef = m_vec3.dot(cur_vertical_axis,
                                rotated_first_horiz_vec);
                        var second_horiz_vec = m_vec3.scaleAndAdd(rotated_first_horiz_vec,
                                cur_vertical_axis, -vertical_coef, _vec3_tmp3);
                        m_vec3.normalize(second_horiz_vec, second_horiz_vec);

                        var sign_horiz_vec = m_vec3.cross(cur_vertical_axis,
                                first_horiz_vec, _vec3_tmp);
                        var abs_yaw_angle = Math.acos(m_util.clamp(
                                m_vec3.dot(first_horiz_vec, second_horiz_vec),
                                0, 1));
                        var sign_yaw_angle = m_util.sign(m_vec3.dot(
                                second_horiz_vec, sign_horiz_vec));
                        var diff_yaw_cam_angle = abs_yaw_angle * sign_yaw_angle;

                        _yaw_cam_angle += diff_yaw_cam_angle;
                        var yaw_cam_quat = m_quat.setAxisAngle(m_util.AXIS_Z,
                                -_yaw_cam_angle, _quat_tmp2);

                        if (control_type == HMD_ALL_AXES_MOUSE_YAW) {
                            var new_cam_quat = m_quat.multiply(yaw_cam_quat,
                                    hmd_quat, _quat_tmp);
                        } else {
                            var yaw_hmd_quat = m_util.quat_project(hmd_quat, m_util.AXIS_MZ,
                                    m_util.AXIS_Z, m_util.AXIS_Y, _quat_tmp3);
                            var yaw_hmd_inv_quat = m_quat.invert(yaw_hmd_quat, _quat_tmp3);
                            var vertical_hmd_quat = m_quat.multiply(
                                    yaw_hmd_inv_quat, hmd_quat, _quat_tmp3);

                            var new_cam_quat = m_quat.multiply(yaw_cam_quat,
                                    vertical_hmd_quat, _quat_tmp);
                        }
                        var up_axis = m_vec3.transformQuat(m_util.AXIS_MY,
                                new_cam_quat, _vec3_tmp);
                        m_cam.set_vertical_axis(cam_obj, up_axis);

                        m_trans.set_rotation_v(cam_obj, new_cam_quat);
                        m_quat.copy(new_cam_quat, _last_cam_quat);
                    }
                }
            }
        }
    }
    m_ctl.create_sensor_manifold(null, "HMD_ROTATE_CAMERA", m_ctl.CT_CONTINUOUS,
            [elapsed, sensor], null, move_cam_cb);
}

/**
 * Disable HMD.
 * @method module:hmd.disable_hmd
 */
exports.disable_hmd = function() {
    m_ctl.remove_sensor_manifold(null, "HMD_ROTATE_CAMERA");

    m_input.disable_split_screen();

    var cam_obj = m_scenes.get_active_camera();
    if (_was_target_camera)
        m_cam.target_setup(cam_obj);
    else if (_was_hover_camera)
        m_cam.hover_setup(cam_obj);
    else if (_was_static_camera)
        m_cam.static_setup(cam_obj);

    // correct up camera (non-vr mode)
    m_cam.set_vertical_axis(cam_obj, m_util.AXIS_Z);
    // TODO: update_transform
    var cam_quat = m_trans.get_rotation(cam_obj, _quat_tmp);
    m_trans.set_rotation_v(cam_obj, cam_quat);
}

};


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

namespace Org.OpenEngSB.DotNet.Lib.RealDomainService.Communication.Jms
{
    public class Destination
    {
        public string Host { get; set; }
        public string Queue { get; set; }

        public string FullDestination
        {
            get
            {
                if(string.IsNullOrEmpty(Queue))
                    return Host;
                return Host + "?" + Queue;
            }
        }

        public Destination(string destination)
        {
            string[] parts = destination.Split('?');

            if (parts.Length != 2)
                throw new ApplicationException("JMSPort Destination string invalid!");

            Host = parts[0].Trim();
            Queue = parts[1].Trim();
        }

        public static string CreateDestinationString(string host, string queue)
        {
            return host + "?" + queue;
        }
    }
}


text:
/**
 */
package eclassxmlschemacommon_2_0Simplified;

import org.eclipse.emf.ecore.EObject;

/**
 *
 * A representation of the model object 'LOCALIZEDSTRING'.
 *
 *
 *

 * The following features are supported:
 *

 *

 *
{@link eclassxmlschemacommon_2_0Simplified.LOCALIZEDSTRING#getValue Value}

 *
{@link eclassxmlschemacommon_2_0Simplified.LOCALIZEDSTRING#getCountryCode Country Code}

 *
{@link eclassxmlschemacommon_2_0Simplified.LOCALIZEDSTRING#getLanguageCode Language Code}

 *

 *
 * @see eclassxmlschemacommon_2_0Simplified.Eclassxmlschemacommon_2_0SimplifiedPackage#getLOCALIZEDSTRING()
 * @model annotation="http://www.eclipse.org/emf/2002/Ecore constraints='patternCountryCode patternLanguageCode'"
 *        annotation="http://www.eclipse.org/emf/2002/Ecore/OCL/Pivot patternCountryCode='(self.countryCode=null) or self.countryCode.matches(\'[A-z]*\')' patternLanguageCode='self.languageCode.matches(\'[A-z]*\')'"
 * @generated
 */
public interface LOCALIZEDSTRING extends EObject {
	/**
	 * Returns the value of the 'Value' attribute.
	 *
	 *

	 * If the meaning of the 'Value' attribute isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Value' attribute.
	 * @see #setValue(String)
	 * @see eclassxmlschemacommon_2_0Simplified.Eclassxmlschemacommon_2_0SimplifiedPackage#getLOCALIZEDSTRING_Value()
	 * @model
	 * @generated
	 */
	String getValue();

	/**
	 * Sets the value of the '{@link eclassxmlschemacommon_2_0Simplified.LOCALIZEDSTRING#getValue Value}' attribute.
	 *
	 *
	 * @param value the new value of the 'Value' attribute.
	 * @see #getValue()
	 * @generated
	 */
	void setValue(String value);

	/**
	 * Returns the value of the 'Country Code' attribute.
	 *
	 *

	 * If the meaning of the 'Country Code' attribute isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Country Code' attribute.
	 * @see #setCountryCode(String)
	 * @see eclassxmlschemacommon_2_0Simplified.Eclassxmlschemacommon_2_0SimplifiedPackage#getLOCALIZEDSTRING_CountryCode()
	 * @model
	 * @generated
	 */
	String getCountryCode();

	/**
	 * Sets the value of the '{@link eclassxmlschemacommon_2_0Simplified.LOCALIZEDSTRING#getCountryCode Country Code}' attribute.
	 *
	 *
	 * @param value the new value of the 'Country Code' attribute.
	 * @see #getCountryCode()
	 * @generated
	 */
	void setCountryCode(String value);

	/**
	 * Returns the value of the 'Language Code' attribute.
	 *
	 *

	 * If the meaning of the 'Language Code' attribute isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Language Code' attribute.
	 * @see #setLanguageCode(String)
	 * @see eclassxmlschemacommon_2_0Simplified.Eclassxmlschemacommon_2_0SimplifiedPackage#getLOCALIZEDSTRING_LanguageCode()
	 * @model required="true"
	 * @generated
	 */
	String getLanguageCode();

	/**
	 * Sets the value of the '{@link eclassxmlschemacommon_2_0Simplified.LOCALIZEDSTRING#getLanguageCode Language Code}' attribute.
	 *
	 *
	 * @param value the new value of the 'Language Code' attribute.
	 * @see #getLanguageCode()
	 * @generated
	 */
	void setLanguageCode(String value);

} // LOCALIZEDSTRING


text:
package ir.asparsa.hobbytaste.ui.mvp.presenter;

import android.support.annotation.NonNull;
import android.support.v4.util.Pair;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import ir.asparsa.android.core.logger.L;
import ir.asparsa.hobbytaste.ApplicationLauncher;
import ir.asparsa.hobbytaste.core.manager.PreferencesManager;
import ir.asparsa.hobbytaste.core.manager.StoresManager;
import ir.asparsa.hobbytaste.core.util.MapUtil;
import ir.asparsa.hobbytaste.database.model.StoreModel;
import ir.asparsa.hobbytaste.ui.fragment.content.FragmentDelegate;
import ir.asparsa.hobbytaste.ui.fragment.content.MainContentFragment;
import ir.asparsa.hobbytaste.ui.mvp.holder.MainContentViewHolder;
import ir.asparsa.hobbytaste.ui.wrapper.WCameraPosition;
import ir.asparsa.hobbytaste.ui.wrapper.WMap;
import rx.Observer;
import rx.subscriptions.CompositeSubscription;

import javax.inject.Inject;
import java.util.*;

/**
 * @author hadi
 * @since 4/14/2017 AD.
 */
public class StorePresenter implements Presenter<MainContentViewHolder> {

    private static final String BUNDLE_KEY_STORES = "BUNDLE_KEY_STORES";
    private static final String BUNDLE_KEY_OFFSET = "BUNDLE_KEY_OFFSET";
    private static final int STORES_LIMIT = 20;
    private WCameraPosition mCameraPosition;

    @Inject
    StoresManager mStoresManager;
    @Inject
    PreferencesManager mPreferencesManager;
    @Inject
    MapUtil mMapUtil;

    private final FragmentDelegate mFragment;
    private MainContentViewHolder mHolder;
    private ArrayList<StoreModel> mStores = new ArrayList<>();
    private List<Marker> mMarkers = new ArrayList<>();
    private CompositeSubscription mSubscription = new CompositeSubscription();
    private boolean mTryAgainLater = true;
    private int mOffset;
    private boolean mOnMapReady = false;

    public StorePresenter(
            FragmentDelegate fragment
    ) {
        ApplicationLauncher.mainComponent().inject(this);
        this.mFragment = fragment;
    }

    @Override public void bindView(@NonNull MainContentViewHolder viewHolder) {
        L.d(getClass(), "bind view gets called. " + mStores);
        mHolder = viewHolder;
        ArrayList<StoreModel> stores = mFragment.getArguments().getParcelableArrayList(BUNDLE_KEY_STORES);
        if (stores != null) {
            addNewStores(stores);
        }

        double lat = mPreferencesManager.getFloat(PreferencesManager.KEY_DEFAULT_CAMERA_POSITION_LATITUDE, 0f);
        double lng = mPreferencesManager.getFloat(PreferencesManager.KEY_DEFAULT_CAMERA_POSITION_LONGITUDE, 0f);
        float zoom = mPreferencesManager.getFloat(PreferencesManager.KEY_DEFAULT_CAMERA_POSITION_ZOOM, 0f);
        if (lat != 0f && lng != 0f && zoom != 0) {
            mCameraPosition = new WCameraPosition(mMapUtil.fromLatLngZoom(lat, lng, zoom));
        }
        if (mTryAgainLater) {
            mTryAgainLater = false;

            mOffset = mFragment.getArguments().getInt(BUNDLE_KEY_OFFSET, 0);
            startLoading(lat, lng, mOffset);
        } else {
            publish();
        }
    }

    @Override public void unbindView() {
        L.d(getClass(), "unbind view gets called. " + mStores);
        if (mHolder == null) {
            return;
        }

        WMap map = mHolder.getMap();
        if (map != null) {
            mCameraPosition = map.getCameraPosition();
            if (mCameraPosition != null && mCameraPosition.getTarget() != null) {
                mPreferencesManager.put(
                        PreferencesManager.KEY_DEFAULT_CAMERA_POSITION_LATITUDE,
                        (float) mCameraPosition.getTarget().getLatitude());
                mPreferencesManager.put(
                        PreferencesManager.KEY_DEFAULT_CAMERA_POSITION_LONGITUDE,
                        (float) mCameraPosition.getTarget().getLongitude());
                mPreferencesManager.put(PreferencesManager.KEY_DEFAULT_CAMERA_POSITION_ZOOM, mCameraPosition.getZoom());
            }
        }
        mHolder.removeMarkers(mMarkers);
        mFragment.getArguments().putInt(BUNDLE_KEY_OFFSET, mOffset);
        mFragment.getArguments().putParcelableArrayList(BUNDLE_KEY_STORES, mStores);
        mHolder = null;
    }

    @Override public void publish() {
        L.d(getClass(), "publish gets called. " + mStores);
        if (mHolder == null) {
            return;
        }

        WMap map = mHolder.getMap();
        if (mOnMapReady && mCameraPosition != null && map != null) {
            mOnMapReady = false;
            map.moveCamera(mCameraPosition.getRealCameraPosition());
        }
        if (map != null && mStores.size() != 0) {

            mHolder.removeMarkers(mMarkers);
            for (StoreModel store : mStores) {
                LatLng latLng = new LatLng(store.getLat(), store.getLon());

                Marker marker = mHolder.addMarker(latLng, store.getTitle());
                mMarkers.add(marker);
            }

            if (mCameraPosition == null && mMarkers.size() != 0) {
                LatLngBounds.Builder builder = new LatLngBounds.Builder();
                for (Marker marker : mMarkers) {
                    builder.include(marker.getPosition());
                }
                LatLngBounds bounds = builder.build();
                map.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 0));
                mCameraPosition = mHolder.getMap().getCameraPosition();
            }
            map.setOnMarkerClickListener(mHolder);
        }
    }

    private void startLoading(
            double lat,
            double lng,
            int offset
    ) {
        StoresManager.Constraint constraint = new StoresManager.Constraint(lat, lng, offset, STORES_LIMIT);
        mSubscription.add(mStoresManager.loadStores(constraint, getStoreObserver(constraint)));
    }

    public void onMapReady() {
        L.d(getClass(), "on map ready gets called.");
        mOnMapReady = true;
        publish();
    }

    private Observer<StoresManager.StoresResult> getStoreObserver(final StoresManager.Constraint constraint) {
        return new Observer<StoresManager.StoresResult>() {
            @Override public void onCompleted() {
                L.i(MainContentFragment.class, "Refresh request gets completed");
            }

            @Override public void onError(Throwable e) {
                L.w(MainContentFragment.class, "Store gets error", e);
                Toast.makeText(mFragment.getContext(), e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
                mTryAgainLater = true;
            }

            @Override public void onNext(StoresManager.StoresResult result) {
                if (result.getStores() == null || result.getStores().size() == 0) {
                    return;
                }

                if (mOffset + STORES_LIMIT < result.getTotalElements()) {
                    mOffset += STORES_LIMIT;
                    double lat = constraint.getLatitude();
                    double lng = constraint.getLongitude();
                    if (mHolder.getMap() != null) {
                        ArrayList<StoreModel> list = new ArrayList<>(result.getStores());
                        StoreModel lastModel = list.get(list.size() - 1);
                        if (!mHolder.getMap().getProjection().getVisibleRegion().latLngBounds
                                .contains(new LatLng(lastModel.getLat(), lastModel.getLon()))) {
                            mCameraPosition = mHolder.getMap().getCameraPosition();
                            if (mCameraPosition != null && mCameraPosition.getTarget() != null) {
                                mOffset = 0;
                                lat = mCameraPosition.getTarget().getLatitude();
                                lng = mCameraPosition.getTarget().getLongitude();
                            }
                        }
                    }
                    startLoading(lat, lng, mOffset);
                }
                onSuccessfullyReceived(result.getStores());
            }
        };
    }

    private void onSuccessfullyReceived(Collection<StoreModel> stores) {
        L.i(MainContentFragment.class, "Stores successfully received: " + stores);

        addNewStores(stores);
        publish();
    }

    private void addNewStores(@NonNull Collection<StoreModel> stores) {
        if (stores.size() == 0) {
            return;
        }
        Collection<StoreModel> s = new ArrayDeque<>(stores);
        Iterator<StoreModel> iterator = s.iterator();
        do {
            if (mStores.contains(iterator.next())) {
                iterator.remove();
            }
        } while (iterator.hasNext());

        mStores.addAll(s);
    }

    public boolean onMarkerClick(Marker marker) {
        int index = mMarkers.indexOf(marker);
        if (index != -1) {
            mFragment.onEvent(MainContentFragment.EVENT_KEY_INSTANTIATE_STORE_DETAIL, mStores.get(index));
            return true;
        }
        return false;
    }

    public void onNewStore(StoreModel storeModel) {
        if (mStores != null) {
            mStores.add(storeModel);
        } else {
            mTryAgainLater = true;
        }
    }

    public void onRefreshStores() {
        if (mHolder.getMap() != null) {
            mCameraPosition = mHolder.getMap().getCameraPosition();
            if (mCameraPosition != null && mCameraPosition.getTarget() != null) {
                mStores.clear();
                mOffset = 0;
                double lat = mCameraPosition.getTarget().getLatitude();
                double lng = mCameraPosition.getTarget().getLongitude();
                startLoading(lat, lng, mOffset);
            }
        }
    }

    public Pair<Double, Double> getPosition() {
        double lat = mPreferencesManager.getFloat(PreferencesManager.KEY_DEFAULT_CAMERA_POSITION_LATITUDE, 0f);
        double lng = mPreferencesManager.getFloat(PreferencesManager.KEY_DEFAULT_CAMERA_POSITION_LONGITUDE, 0f);
        if (mHolder.getMap() != null) {
            mCameraPosition = mHolder.getMap().getCameraPosition();
            if (mCameraPosition != null && mCameraPosition.getTarget() != null) {
                lat = mCameraPosition.getTarget().getLatitude();
                lng = mCameraPosition.getTarget().getLongitude();
            }
        }
        return new Pair<>(lat, lng);
    }
}


text:
function [bincenters,averages,errors]=binmedians(x,y,min,max,oversamplingratio,nbins,varargin)
% [bincenters,averages,errors]=bin(x,y,min,max,oversamplingratio,nbins,varargin)
% Return the median values for independent variable y binned as a funciton
% of independent variable x.

if nargin==6
    binoverlap = 0;
elseif nargin==7
    binoverlap=varargin{1};
elseif nargin<6
    error('Too few input arguments.')
elseif nargin>7
    error('Too many input arguments.')
end

averages=NaN(1,nbins);
errors=NaN(1,nbins);

if binoverlap>1
    binhalfwidth=(max-min)/nbins*binoverlap/2;
    bincenters=linspace(min,max,nbins);

    for i=1:nbins
        averages(i)=nanmedian(y(x>bincenters(i)-binhalfwidth&x<bincenters(i)+binhalfwidth));
%         errors(i)=nansem(y(x>bincenters(i)-binhalfwidth&x<bincenters(i)+binhalfwidth)).*sqrt(oversamplingratio); % Standard error of the mean
        errors(i)=nanmsem(y(x>bincenters(i)-binhalfwidth&x<bincenters(i)+binhalfwidth)).*sqrt(oversamplingratio); % Standard error of the median (MAD/sqrt(n))
    end
else
    binwidth=(max-min)/nbins;
    binedges=linspace(min,max,nbins+1);
    bincenters=min+binwidth/2:binwidth:max-binwidth/2;

    for i=1:nbins
        averages(i)=nanmedian(y(x>binedges(i)&x<binedges(i+1)));
%         errors(i)=nansem(y(x>binedges(i)&x<binedges(i+1))).*sqrt(oversamplingratio); % Standard error of the mean
        errors(i)=nanmsem(y(x>binedges(i)&x<binedges(i+1))).*sqrt(oversamplingratio); % Standard error of the median (MAD/sqrt(n))
    end
end


text:
@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.

    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];

    NSDictionary* barButtonItemAttributes = @{NSFontAttributeName: [UIFont systemFontOfSize:16.0],
                                              NSForegroundColorAttributeName: [UIColor whiteColor],
                                              };
    [[UIBarButtonItem appearanceWhenContainedIn: [UINavigationController class], nil] setTitleTextAttributes:barButtonItemAttributes
                                                                                forState:UIControlStateNormal];

    [[UITabBar appearance] setBarTintColor:[UIColor black:1]];
    [[UITabBarItem appearance] setTitleTextAttributes:@{ UITextAttributeTextColor : [UIColor whiteColor] }
                                             forState:UIControlStateNormal];
    [[UITabBarItem appearance] setTitleTextAttributes:@{ UITextAttributeTextColor : [UIColor emerald:1] }
                                             forState:UIControlStateSelected];

    if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1) {
        [[UINavigationBar appearance] setTintColor:[UIColor turquoise:1]];
    } else {
        [[UINavigationBar appearance] setBarTintColor:[UIColor turquoise:1]];
    }

    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    User *user = [SailsDefaults getUser];
    if(user == nil || user.username == nil || user.password == nil) {
        [SailsDefaults clear];
        CatchPointViewController *catchview = [[CatchPointViewController alloc] init];
        UINavigationController *navcontroller = [[UINavigationController alloc] initWithRootViewController:catchview];
        [self.window addSubview:navcontroller.view];
        self.window.rootViewController = navcontroller;
    } else {
        UITabBarController *tabBarController = [[UITabBarController alloc] init];

        UserViewController* vc1 = [[UserViewController alloc] initWithStyle:UITableViewStyleGrouped];
        ChatViewController* vc2 = [[ChatViewController alloc] initWithStyle:UITableViewStyleGrouped];

        NSArray* controllers = [NSArray arrayWithObjects:vc1, vc2, nil];
        tabBarController.viewControllers = controllers;

        vc1.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"Chatter" image:nil selectedImage:nil];
        vc2.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"Room" image:nil selectedImage:nil];

        UINavigationController *navcontroller = [[UINavigationController alloc] initWithRootViewController:tabBarController];
        [self.window addSubview:navcontroller.view];
        self.window.rootViewController = navcontroller;
    }

    [self.window makeKeyAndVisible];

    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end


text:
package org.realityforge.sqlserver.ssrs;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

final class Uploader
{
  @Nonnull
  private final SSRS _ssrs;

  Uploader( @Nonnull final String reportTarget,
            @Nonnull final String uploadPrefix,
            @Nullable final String domain,
            @Nullable final String username,
            @Nullable final String password )
    throws MalformedURLException
  {
    if ( null != username )
    {
      NTLMAuthenticator.install( Objects.requireNonNull( domain ),
                                 Objects.requireNonNull( username ),
                                 Objects.requireNonNull( password ) );
    }

    _ssrs = new SSRS( new URL( Objects.requireNonNull( reportTarget ) + "/ReportService2005.asmx" ),
                      Objects.requireNonNull( uploadPrefix ) );
  }

  void uploadReports( @Nonnull final Report[] reports )
  {
    deleteReports( reports );
    for ( final Report report : reports )
    {
      createParentDirectory( report.name );
      _ssrs.createReport( report.name, report.filename );
    }
  }

  private void createParentDirectory( @Nonnull final String itemName )
  {
    final String directory = itemName.replaceAll( "/[^/]*$", "" );
    if ( !directory.equals( itemName ) )
    {
      _ssrs.mkdir( directory );
    }
  }

  void deleteReports( @Nonnull final Report[] reports )
  {
    extractTopLevelDirectories( reports ).forEach( _ssrs::delete );
  }

  void uploadDataSources( @Nonnull final DataSource[] dataSources )
  {
    for ( final DataSource dataSource : dataSources )
    {
      createParentDirectory( dataSource.name );
      _ssrs.delete( dataSource.name );
      _ssrs.createSQLDataSource( dataSource.name, dataSource.connectionString );
    }
  }

  void deleteDataSources( @Nonnull final DataSource[] dataSources )
  {
    for ( final DataSource dataSource : dataSources )
    {
      _ssrs.delete( dataSource.name );
    }
  }

  @Nonnull
  private List<String> extractTopLevelDirectories( @Nonnull final Report[] reports )
  {
    return Stream
      .of( reports )
      .map( r -> {
        final String[] parts = r.name.replaceFirst( "^/", "" ).split( "/" );
        return parts.length > 1 && !parts[ 0 ].equals( "" ) ? parts[ 0 ] : null;
      } )
      .filter( Objects::nonNull )
      .distinct()
      .sorted()
      .collect( Collectors.toList() );
  }
}


text:
extern const size_t buzhash_width;

uint32_t buzhash (const char *);
uint32_t buzhash_update (const char *, uint32_t);

#endif


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="icon" type="image/png" href="https://just2us.com/img/favicon-180.png" />
    <link rel="apple-touch-icon" href="https://just2us.com/img/favicon-192.png"/>

    <link rel="stylesheet" href="/css/bootstrap.min.css">
    <link rel="stylesheet" href="/css/clean-blog.min.css">
    <link rel="stylesheet" href="/css/syntax.css">

    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href='https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic&display=swap' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800&display=swap' rel='stylesheet' type='text/css'>

    <link type="application/atom+xml" rel="alternate" href="https://just2me.com/feed.xml" title="Just2me" />

<title>Fern Green Primary School Ballot History | Just2me</title>
<meta name="generator" content="Jekyll v4.0.0" />
<meta property="og:title" content="Fern Green Primary School Ballot History" />
<meta property="og:locale" content="en_US" />
<meta name="description" content="The Singapore primary schools statistics you need" />
<meta property="og:description" content="The Singapore primary schools statistics you need" />
<link rel="canonical" href="https://just2me.com/sgprimary/school/fern-green/" />
<meta property="og:url" content="https://just2me.com/sgprimary/school/fern-green/" />
<meta property="og:site_name" content="Just2me" />
<meta property="og:image" content="https://just2me.com/img/tables-pattern.jpg" />
<meta name="twitter:card" content="summary" />
<meta property="twitter:image" content="https://just2me.com/img/tables-pattern.jpg" />
<meta property="twitter:title" content="Fern Green Primary School Ballot History" />
<meta name="twitter:site" content="@samwize" />
<meta name="twitter:creator" content="@samwize" />
<meta property="fb:admins" content="704185456" />

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                Toggle navigation

            </button>
            Just2me

                  Stories

                  Apps

                  Quotes

                  About

Fern Green Primary School Ballot History

                    The Singapore primary schools statistics you need

Fern Green Primary School

Area: Sengkang

Chinese: Yes

Malay: Yes

Tamil: No

Ballot History

      Year
      Phase 1
      2A1
      2A2
      2B
      2C
      2CS
      3
      Total

      2017

      ↳ Vacancy
      -
      -
      -
      120
      240
      100
      6
      240

      ↳ Applied
      -
      -
      -
      0
      140
      94
      -
      -

      ↳ Taken
      0
      0
      0
      0
      140
      94
      -
      234

      2018

      ↳ Vacancy
      -
      -
      -
      140
      276
      60
      0
      300

      ↳ Applied
      -
      -
      -
      3
      216
      71
      -
      -

      ↳ Taken
      21
      0
      0
      3
      216
      60
      -
      300

      2019

      ↳ Vacancy
      230
      169
      169
      83
      164
      7
      -
      270

      ↳ Applied
      61
      0
      44
      2
      157
      14
      -
      -

      ↳ Taken
      61
      0
      44
      2
      157
      7
      -
      271

Average

      Phase 1
      2A1
      2A2
      2B
      2C
      2CS
      3
      Total

      ↳ Vacancy
      230
      169
      169
      114
      226
      55
      3
      270

      ↳ Applied
      61
      0
      44
      1
      171
      59
      -
      -

      ↳ Taken
      27
      0
      14
      1
      171
      53
      -
      268

Cumulative Take Up Rate

      Year
      Phase 1
      2A1
      2A2
      2B
      2C
      2CS
      Total Vacancy

      2017
      0
      0
      0
      0
      140
      234
      240

      2018
      21
      21
      21
      24
      240
      300
      300

      2019
      61
      61
      105
      107
      264
      271
      270

Copyright © Junda Ong 1983-2021


text:
//
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright (c) Texas Instruments Incorporated.  All rights reserved.
// See LICENSE file in the project root for full license information.
//

#ifndef SIMPLELINK_CC32XX_PROVISIONING_TASK_H
#define SIMPLELINK_CC32XX_PROVISIONING_TASK_H

#include <ti/drivers/net/wifi/simplelink.h>

/* POSIX Header files */
#include <semaphore.h>
#include <pthread.h>
#include <time.h>

#include <nanoCLR_Headers.h>

/*!
 *  \brief  Provisioning events
 */
typedef enum
{
    PrvnEvent_Triggered,
    PrvnEvent_Started,
    PrvnEvent_StartFailed,
    PrvnEvent_ConfirmationSuccess,
    PrvnEvent_ConfirmationFailed,
    PrvnEvent_Stopped,
    PrvnEvent_WaitForConn,
    PrvnEvent_Timeout,
    PrvnEvent_Error,
    PrvnEvent_Max,
} PrvnEvent;

/*!
 *  \brief  Provisioning states
 */
typedef enum
{
    PrvnState_Init,
    PrvnState_Idle,
    PrvnState_WaitForConfirmation,
    PrvnState_Completed,
    PrvnState_Error,
    PrvnState_Max
} PrvnState;

typedef struct Provisioning_ControlBlock_t
{
    sem_t connectionAsyncEvent;
    sem_t provisioningDoneSignal;
    sem_t provisioningConnDoneToOtaServerSignal;
} Provisioning_CB;

/****************************************************************************
                      GLOBAL VARIABLES
****************************************************************************/
extern Provisioning_CB Provisioning_ControlBlock;

//****************************************************************************
//                      FUNCTION PROTOTYPES
//****************************************************************************

//*****************************************************************************
//
//! \brief This function signals the application events
//!
//! \param[in]  None
//!
//! \return 0 on success, negative value otherwise
//!
//****************************************************************************
_i16 SignalProvisioningEvent(PrvnEvent event);

//*****************************************************************************
//
//! \brief This function gets the current provisioning state
//!
//! \param[in]  None
//!
//! \return provisioning state
//!
//****************************************************************************
PrvnState GetProvisioningState();

//*****************************************************************************
//
//! \brief The interrupt handler for the LED timer
//!
//! \param[in]  None
//!
//! \return None
//!
//****************************************************************************
void LedTimerIntHandler(sigval val);

//*****************************************************************************
//
//! \brief This function starts the led toggling timer
//!
//! \param[in]  None
//!
//! \return 0 on success, negative value otherwise
//!
//****************************************************************************
int32_t StartLedEvtTimer(uint32_t timeout);

//*****************************************************************************
//
//! \brief This function stops the led toggling timer
//!
//! \param[in]  None
//!
//! \return 0 on success, negative value otherwise
//!
//****************************************************************************
int32_t StopLedEvtTimer(void);

//*****************************************************************************
//
//! \brief This function stops provisioning process
//!
//! \param[in]  None
//!
//! \return SL_RET_CODE_PROVISIONING_IN_PROGRESS if provisioning was running, otherwise 0
//!
//****************************************************************************
int32_t provisioningStop(void);

//*****************************************************************************
//
//! \brief This is the main provisioning task
//!
//! \param[in]  None
//!
//! \return None
//!
//****************************************************************************
void *provisioningTask(void *pvParameters);

#endif //SIMPLELINK_CC32XX_PROVISIONING_TASK_H


text:
from south.v2 import DataMigration

class Migration(DataMigration):

    depends_on = (
        ("lists", "0001_initial"),
    )

    def forwards(self, orm):
        favorite_lists = {}

        # Create a List for Everyone who has Favorited a Package
        for user in orm["favorites.Favorite"].objects.distinct("user").values_list("user", flat=True):
            u = orm["auth.User"].objects.get(pk=user)
            favorite_lists[user] = orm["lists.List"].objects.create(user=u, name="Favorites", private=True)

        for fav in orm["favorites.Favorite"].objects.all():
            favorite_lists[fav.user.pk].packages.add(fav.package)

    def backwards(self, orm):
        raise Exception("Cannot Go Backwards")

    models = {
        'auth.group': {
            'Meta': {'object_name': 'Group'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
        },
        'auth.permission': {
            'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
        },
        'auth.user': {
            'Meta': {'object_name': 'User'},
            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
        },
        'contenttypes.contenttype': {
            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        },
        'favorites.favorite': {
            'Meta': {'unique_together': "(('user', 'package'),)", 'object_name': 'Favorite'},
            'created': ('model_utils.fields.AutoCreatedField', [], {'default': 'datetime.datetime.now'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'modified': ('model_utils.fields.AutoLastModifiedField', [], {'default': 'datetime.datetime.now'}),
            'package': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['packages.Package']"}),
            'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
        },
        'lists.list': {
            'Meta': {'unique_together': "(('user', 'name'),)", 'object_name': 'List'},
            'created': ('model_utils.fields.AutoCreatedField', [], {'default': 'datetime.datetime.now'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'modified': ('model_utils.fields.AutoLastModifiedField', [], {'default': 'datetime.datetime.now'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '50', 'db_index': 'True'}),
            'packages': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['packages.Package']", 'symmetrical': 'False'}),
            'private': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
        },
        'packages.package': {
            'Meta': {'object_name': 'Package'},
            'created': ('model_utils.fields.AutoCreatedField', [], {'default': 'datetime.datetime.now'}),
            'downloads_synced_on': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'modified': ('model_utils.fields.AutoLastModifiedField', [], {'default': 'datetime.datetime.now'}),
            'name': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '150'}),
            'normalized_name': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '150'})
        }
    }

    complete_apps = ['lists', 'favorites']
    symmetrical = True


text:
namespace Bor{

Animation::Animation(Token * token, Paintown::Character * const owner):
Paintown::Animation(token, owner){
}

Animation::Animation(const Animation & animation, Paintown::Character * const owner):
Paintown::Animation(animation, owner){
}

int Animation::getOffsetX() const {
    return getWidth() / 2 - Paintown::Animation::getOffsetX();
}

int Animation::getOffsetY() const {
    return getHeight() - Paintown::Animation::getOffsetY();
}

Paintown::Animation * Animation::copy(Paintown::Character * owner) const {
    return new Animation(*this, owner);
}

}


text:
<form name="searchForm">

        <md-input-container flex>
            <md-icon>search</md-icon>
            Buscar
            <input ng-model="query" md-select-on-focus>
        </md-input-container>
        <md-button ng-click="add()">
            note_add
        </md-button>

    <md-progress-linear ng-show="loading" md-mode="indeterminate"></md-progress-linear>
</form>

<md-card ng-repeat="payment in payments">
    <md-card-title>
        <md-card-title-text>
            {{payment.name}}
            Proximo Pago: {{payment.payments.next | date:'fullDate'}}.
            Ciclo de pagos finalizado.
        </md-card-title-text>
        <md-chips ng-model="payment.tags" readonly="true"></md-chips>
    </md-card-title>
    <md-card-content>{{payment.description}}</md-card-content>
    <md-card-actions layout="row" layout-align="end center">
        <md-button ng-click="pay(payment)">money_off</md-button>
        <md-button ng-click="edit(payment)">mode_edit</md-button>
        <md-button ng-click="deletePrompt(payment)">delete</md-button>
    </md-card-actions>
</md-card>

    <md-button ng-click="loadMore()" class="md-raised md-cornered">
        expand_more
    </md-button>


text:
const router = require('koa-router')();

const home = require('./home');
// cross domain
const allowOrigin = require('koa-allow-origin');

router.use(allowOrigin(process.env.NODE_ENV, []));
router.use('/', home.routes(), home.allowedMethods());

module.exports = router;


text:
var isNode = false;
(function(exports, require) {

// Keep compatibility with old browsers
if (!Array.isArray) {
  Array.isArray = function(vArg) {
    return Object.prototype.toString.call(vArg) === "[object Array]";
  };
}

// Make sure to know if we are in real node or not (the `require` variable
// could actually be require.js, for example.
var isNode = typeof module !== 'undefined' && !!module.exports;

var vm = isNode ?
    require('vm') : {
      runInNewContext: function(expr, context) { with (context) return eval(expr); }
    };
exports.eval = jsonPath;

var cache = {};

function push(arr, elem) { arr = arr.slice(); arr.push(elem); return arr; }
function unshift(elem, arr) { arr = arr.slice(); arr.unshift(elem); return arr; }

function jsonPath(obj, expr, arg) {
   var P = {
      resultType: arg && arg.resultType || "VALUE",
      flatten: arg && arg.flatten || false,
      wrap: (arg && arg.hasOwnProperty('wrap')) ? arg.wrap : true,
      sandbox: (arg && arg.sandbox) ? arg.sandbox : {},
      normalize: function(expr) {
         if (cache[expr]) return cache[expr];
         var subx = [];
         var normalized = expr.replace(/[\['](\??\(.*?\))[\]']/g, function($0,$1){return "[#"+(subx.push($1)-1)+"]";})
                     .replace(/'?\.'?|\['?/g, ";")
                     .replace(/(;)?(\^+)(;)?/g, function(_, front, ups, back) { return ';' + ups.split('').join(';') + ';'; })
                     .replace(/;;;|;;/g, ";..;")
                     .replace(/;$|'?\]|'$/g, "");
         var exprList = normalized.split(';').map(function(expr) {
            var match = expr.match(/#([0-9]+)/);
            return !match || !match[1] ? expr : subx[match[1]];
         })
         return cache[expr] = exprList;
      },
      asPath: function(path) {
         var x = path, p = "$";
         for (var i=1,n=x.length; i<n; i++)
            p += /^[0-9*]+$/.test(x[i]) ? ("["+x[i]+"]") : ("['"+x[i]+"']");
         return p;
      },
      trace: function(expr, val, path) {
         // no expr to follow? return path and value as the result of this trace branch
         if (!expr.length) return [{path: path, value: val}];

         var loc = expr[0], x = expr.slice(1);
         // the parent sel computation is handled in the frame above using the
         // ancestor object of val
         if (loc === '^') return path.length ? [{path: path.slice(0,-1), expr: x, isParentSelector: true}] : [];

         // we need to gather the return value of recursive trace calls in order to
         // do the parent sel computation.
         var ret = [];
         function addRet(elems) { ret = ret.concat(elems); }

         if (val && val.hasOwnProperty(loc)) // simple case, directly follow property
            addRet(P.trace(x, val[loc], push(path, loc)));
         else if (loc === "*") { // any property
            P.walk(loc, x, val, path, function(m,l,x,v,p) {
               addRet(P.trace(unshift(m, x), v, p)); });
         }
         else if (loc === "..") { // all chid properties
            addRet(P.trace(x, val, path));
            P.walk(loc, x, val, path, function(m,l,x,v,p) {
               if (typeof v[m] === "object")
                  addRet(P.trace(unshift("..", x), v[m], push(p, m)));
            });
         }
         else if (loc[0] === '(') { // [(expr)]
            addRet(P.trace(unshift(P.eval(loc, val, path[path.length], path),x), val, path));
         }
         else if (loc.indexOf('?(') === 0) { // [?(expr)]
            P.walk(loc, x, val, path, function(m,l,x,v,p) {
               if (P.eval(l.replace(/^\?\((.*?)\)$/,"$1"),v[m],m, path))
                  addRet(P.trace(unshift(m,x),v,p));
            });
         }
         else if (loc.indexOf(',') > -1) { // [name1,name2,...]
            for (var parts = loc.split(','), i = 0; i < parts.length; i++)
               addRet(P.trace(unshift(parts[i], x), val, path));
         }
         else if (/^(-?[0-9]*):(-?[0-9]*):?([0-9]*)$/.test(loc)) { // [start:end:step]  python slice syntax
            addRet(P.slice(loc, x, val, path));
         }

         // we check the resulting values for parent selections. for parent
         // selections we discard the value object and continue the trace with the
         // current val object
         return ret.reduce(function(all, ea) {
            return all.concat(ea.isParentSelector ? P.trace(ea.expr, val, ea.path) : [ea]);
         }, []);
      },
      walk: function(loc, expr, val, path, f) {
         if (Array.isArray(val))
            for (var i = 0, n = val.length; i < n; i++)
               f(i, loc, expr, val, path);
         else if (typeof val === "object")
            for (var m in val)
               if (val.hasOwnProperty(m))
                  f(m, loc, expr, val, path);
      },
      slice: function(loc, expr, val, path) {
         if (!Array.isArray(val)) return;
         var len = val.length, parts = loc.split(':'),
             start = (parts[0] && parseInt(parts[0])) || 0,
             end = (parts[1] && parseInt(parts[1])) || len,
             step = (parts[2] && parseInt(parts[2])) || 1;
         start = (start < 0) ? Math.max(0,start+len) : Math.min(len,start);
         end   = (end < 0)   ? Math.max(0,end+len)   : Math.min(len,end);
         var ret = [];
         for (var i = start; i < end; i += step)
            ret = ret.concat(P.trace(unshift(i,expr), val, path));
         return ret;
      },
      eval: function(code, _v, _vname, path) {
         if (!$ || !_v) return false;
         if (code.indexOf("@path") > -1) {
            P.sandbox["_path"] = P.asPath(path.concat([_vname]));
            code = code.replace(/@path/g, "_path");
         }
         if (code.indexOf("@") > -1) {
            P.sandbox["_v"] = _v;
            code = code.replace(/@/g, "_v");
         }
         try {
             return vm.runInNewContext(code, P.sandbox);
         }
         catch(e) {
             console.log(e);
             throw new Error("jsonPath: " + e.message + ": " + code);
         }
      }
   };

   var $ = obj;
   var resultType = P.resultType.toLowerCase();
   if (expr && obj && (resultType == "value" || resultType == "path")) {
      var exprList = P.normalize(expr);
      if (exprList[0] === "$" && exprList.length > 1) exprList.shift();
      var result = P.trace(exprList, obj, ["$"]);
      result = result.filter(function(ea) { return ea && !ea.isParentSelector; });
      if (!result.length) return P.wrap ? [] : false;
      if (result.length === 1 && !P.wrap && !Array.isArray(result[0].value)) return result[0][resultType] || false;
      return result.reduce(function(result, ea) {
         var valOrPath = ea[resultType];
         if (resultType === 'path') valOrPath = P.asPath(valOrPath);
         if (P.flatten && Array.isArray(valOrPath)) {
            result = result.concat(valOrPath);
         } else {
            result.push(valOrPath);
         }
         return result;
      }, []);
   }
}
})(typeof exports === 'undefined' ? this['jsonPath'] = {} : exports, typeof require == "undefined" ? null : require);


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

namespace Gale.Db.Factories
{
    /// <summary>
    /// Defines a SQL Server Factory
    /// </summary>
    public class SQLServerFactory : Gale.Db.Factories.AbstractFactory<System.Data.SqlClient.SqlConnection, System.Data.SqlClient.SqlDataAdapter>
    {

        /// <summary>
        /// Base Constructor
        /// </summary>
        /// <param name="ConnectionString">Connection String</param>
        public SQLServerFactory(string ConnectionString)
            : base(ConnectionString)
        {

        }

        /// <summary>
        /// Callback Method when a Exception has ocurred
        /// </summary>
        /// <param name="ex"></param>
        public override void OnException(System.Exception ex)
        {
            if (ex is System.Data.SqlClient.SqlException)
            {
                //CUSTOM DB HANDLER ERROR && (ERROR NUMBER MUST BE >= 50000) AND
                // SEVERITY >= 16
                //https://msdn.microsoft.com/en-us/library/ms178592.aspx
                var DB_EX = (ex as System.Data.SqlClient.SqlException);
                if (DB_EX.Number >= 50000 && Convert.ToInt32(DB_EX.Class) >= 16)
                {
                    throw new Gale.Exception.SqlClient.CustomDatabaseException(DB_EX.Number.ToString(), DB_EX.Message);
                }
            }

        }

        /// <summary>
        /// Parsing Step for each parameter in the service configuration (Useful for parsing c# values to DB Values)
        /// </summary>
        /// <param name="dbParameter">Database Referencial Parameter</param>
        /// <param name="serviceparameter">Service Configured Parameter</param>
        protected override void ParameterParse(ref System.Data.IDbDataParameter dbParameter, DataParameter serviceparameter)
        {
            Type valueType = serviceparameter.Value.GetType();

            if (valueType == typeof(byte[]))
            {
                //Binary
                dbParameter.DbType = System.Data.DbType.Binary;
            }
            else if (valueType == typeof(DateTime))
            {
                /*
                //Date Time
                DateTime value = (DateTime)serviceparameter.Value;

                dbParameter.Value = (value).ToString("yyyy-MM-ddTHH:mm:ss.0");
                dbParameter.DbType = System.Data.DbType.String;
                */

                DateTime value = (DateTime)serviceparameter.Value;

                //http://www.hanselman.com/blog/OnTheNightmareThatIsJSONDatesPlusJSONNETAndASPNETWebAPI.aspx
                //http://thewebjedi.com/be/post/2014/02/22/dates-and-time-zones-in-javascript-c-and-sql-server.aspx

                //SET TO UTC Universal TIME, to Work with local times, and fix the Web API Nightmare of Date
                dbParameter.Value = value;
                dbParameter.DbType = System.Data.DbType.DateTime;
            }
        }
    }
}


text:
title: Using MapKit JS with Rails
path: /posts/using-mapkit-js-with-rails
author: Dwight Watson
date: 2019-08-06
tags: ["rails", "mapkit"]
---

Recently we migrated a website to use Apple's MapKit JS service - one that is currently in beta, but comes with plenty of daily quota for rendering static and dynamic maps. Rather than using a single token to load maps, MapKit appears to prefer you generate short-lived tokens for users, and also to sign any URL that links to a static map. The documentation only included example code for JavaScript (intended for server-side use) and so I've compiled our implementation for Rails (though mostly plain old Ruby) in case it's useful.

First, make your key ID and team ID available as application secrets in `config/secrets.yml`. For whatever reason I couldn't get the private key to load through here properly so I loaded it separately as you'll see later. Might be worth experimenting on your end to see if you get different results.

```yml
shared:
  mapkit:
    key_id: <%= ENV['MAPKIT_KEY_ID'] %>
    team_id: <%= ENV['MAPKIT_TEAM_ID'] %>
```

Next, here is the main `MapKit` class that is responsible for generating JWT and signing strings. They're just class methods with no additional magic going on - but you'll see the method `private_key` which loads the key file directly from the ENV, as it wasn't loading correctly through the application secrets.

```rb
class MapKit
  class << self
    def token
      headers = {
        'alg': ALGORITHM,
        'kid': Rails.application.secrets.dig(:mapkit, :key_id),
        'typ': 'JWT'
      }

      payload = {
        'iss': Rails.application.secrets.dig(:mapkit, :team_id),
        'iat': Time.now.to_i,
        'exp': 1.day.from_now.to_i
      }

      JWT.encode(payload, private_key, ALGORITHM, headers)
    end

    def sign(path)
      JWT::Base64.url_encode(JWT::Signature.sign(ALGORITHM, path, private_key))
    end

    private

    def private_key
      OpenSSL::PKey::EC.new(ENV['MAPKIT_PRIVATE_KEY'])
    end
  end
end
```

## Dynamic maps

You can use `MapKit.JWT` to generate the token you'll need to pass into the `authorizationCallback` to initialize MapKit JS. How you pass the token into your JavaScript will depend on your front-end approach, but with Stimulus.JS I just pass it through as a data attribute.

```html
<div data-controller="map" data-map-token="<%= MapKit.jwt %>">
</div>
```

Then it's easy to access in the controller connection phase.

```js
connect() {
  mapkit.init({
    authorizationCallback: (done) => {
      done(this.data.get('token'));
    }
  });
}
```

## Static maps

There are plenty of options to configure static maps - and whether you want markers on them or not, but here's my example for a plain old map centered on a given region. This shows how you use `MapKit.sign` to add the URL signature to authorize the request and adjust how you see fit.

```rb
def static_map(latitude, longitude, size: '400x150')
  options = {
    center: "#{address.latitude},#{address.longitude}",
    teamId: Rails.application.secrets.dig(:mapkit, :team_id),
    keyId: Rails.application.secrets.dig(:mapkit, :key_id),
    size: size,
    poi: 0,
    expires: 1.minute.from_now.to_i,
    z: 14
  }

  path = "/api/v1/snapshot?#{Rack::Utils.build_query(options)}"
  signature = MapKit.sign(path)
  "https://snapshot.apple-mapkit.com#{path}&signature=#{signature}"
end
```

That's all there is to it to get up and running. Though getting the authentication stuff working took a bit of stuffing around - I haven't used JWT before - I've really enjoyed working with MapKit JS. The documentation is still early and basic but there's enough detail there to get what you need out of it, and it's well designed enough to poke around and find that things work the way you expect. I look forward to seeing what more they do with MapKit JS going forward.


text:
<?php
/**
 * QQ开放平台操作
 *
 * the last known user to change this file in the repository  <$LastChangedBy: suqian $>
 * @author Su qian <suqian@pipi.cn>
 * @version $Id: templates.xml 894 2010-12-28 07:55:25Z suqian $
 * @package
 */
class QqOAuth extends OAuth{

	public function authorizeURL() {
		return 'https://graph.qq.com/oauth2.0/authorize';
	}

	public function AccessTokenUrl() {
		return 'https://graph.qq.com/oauth2.0/token';
	}

	public function getOpenIdUrl(){
		return 'https://graph.qq.com/oauth2.0/me';
	}

	public function checkSessionAccessToken(){
		$key = $this->open_platfrom.'_token';
		$accessToken = Yii::app()->session[$key];
		if(empty($accessToken) || $accessToken['expires_in']+$accessToken['create_time'] < time()){
			Yii::app()->request->redirect($this->getAuthorizeURL('code'));
		}
		return $accessToken;
	}

	public function processToken($response){
		 if(strpos($response, "callback") !== false){
            $lpos = strpos($response, "(");
            $rpos = strrpos($response, ")");
            $response  = substr($response, $lpos + 1, $rpos - $lpos -1);
            $msg = json_decode($response);
            if(isset($msg->error)){
                throw new OAuthException($msg->error.": ".$msg->error_description);
            }
        }
        $params = array();
        parse_str($response, $params);
		return $params;
	}

	public function getOpenId(){
		$accessToken = $this->checkSessionAccessToken();
		$params['access_token'] = $accessToken['access_token'];
		$response = self::$http->oAuthRequest($this->getOpenIdUrl(),'GET',$params);
		if(strpos($response, "callback") !== false){

            $lpos = strpos($response, "(");
            $rpos = strrpos($response, ")");
            $response = substr($response, $lpos + 1, $rpos - $lpos -1);
        }

        $open = json_decode($response);
        if(isset($open->error)){
            throw new OAuthException($msg->error);
        }
        return $open;
	}

	public function getUserInfo(){
		$open = $this->getOpenId();
		$accessToken = $this->checkSessionAccessToken();
		$params['access_token'] = $accessToken['access_token'];
		$params['oauth_consumer_key'] = $this->client_id;
		$params['format'] = $this->data_type;
		$params['openid'] = $open->openid;
		$userApi = 'https://graph.qq.com/user/get_user_info';
		$response = self::$http->oAuthRequest($userApi,'GET',$params);
		$response = json_decode($response,true);
		$response['openid'] = $open->openid;
		$returnUser = array();
		if($response){
			$returnUser['open_uid'] = 0;
			$returnUser['open_id'] = $open->openid;
			$returnUser['nickname'] = $response['nickname'];
		}
		return $returnUser;

	}

	public function getOpenIdByAccessToken($access_token){
		$params['access_token']=$access_token;
		$response = self::$http->oAuthRequest($this->getOpenIdUrl(),'GET',$params);
		if(strpos($response, "callback") !== false){

			$lpos = strpos($response, "(");
			$rpos = strrpos($response, ")");
			$response = substr($response, $lpos + 1, $rpos - $lpos -1);
		}

		$open = json_decode($response);
		if(isset($open->error)){
			throw new OAuthException($msg->error);
		}
		return $open;
	}

	public function getUserInfoByAccessToken($openid,$access_token){
		$params['access_token'] = $access_token;
		$params['oauth_consumer_key'] = $this->client_id;
		$params['format'] = $this->data_type;
		$params['openid'] = $openid;
		$userApi = 'https://graph.qq.com/user/get_user_info';
		$response = self::$http->oAuthRequest($userApi,'GET',$params);
		$response = json_decode($response,true);
		$response['openid'] = $openid;
		$returnUser = array();
		if($response){
			$returnUser['open_uid'] = 0;
			$returnUser['open_id'] = $openid;
			$returnUser['nickname'] = isset($response['nickname'])?$response['nickname']:'';
		}
		return $returnUser;
	}

}

?>


text:
from oslo_config import cfg

from jacket.tests.compute.functional.api_sample_tests import api_sample_base
from jacket.tests.compute.unit.image import fake

CONF = cfg.CONF
CONF.import_opt('osapi_compute_extension',
                'compute.api.openstack.compute.legacy_v2.extensions')

class AccessIPsSampleJsonTest(api_sample_base.ApiSampleTestBaseV21):
    extension_name = 'os-access-ips'

    def _get_flags(self):
        f = super(AccessIPsSampleJsonTest, self)._get_flags()
        f['osapi_compute_extension'] = CONF.osapi_compute_extension[:]
        f['osapi_compute_extension'].append(
            'compute.api.openstack.compute.contrib.keypairs.Keypairs')
        f['osapi_compute_extension'].append(
            'compute.api.openstack.compute.contrib.extended_ips.Extended_ips')
        f['osapi_compute_extension'].append(
            'compute.api.openstack.compute.contrib.extended_ips_mac.'
            'Extended_ips_mac')
        return f

    def _servers_post(self, subs):
        response = self._do_post('servers', 'server-post-req', subs)
        return self._verify_response('server-post-resp', subs, response, 202)

    def test_servers_post(self):
        subs = {
            'image_id': fake.get_valid_image_id(),
            'compute_endpoint': self._get_compute_endpoint(),
            'access_ip_v4': '1.2.3.4',
            'access_ip_v6': 'fe80::'
        }
        self._servers_post(subs)

    def test_servers_get(self):
        subs = {
            'image_id': fake.get_valid_image_id(),
            'compute_endpoint': self._get_compute_endpoint(),
            'access_ip_v4': '1.2.3.4',
            'access_ip_v6': 'fe80::'
        }
        uuid = self._servers_post(subs)
        response = self._do_get('servers/%s' % uuid)
        subs['hostid'] = '[a-f0-9]+'
        subs['id'] = uuid
        self._verify_response('server-get-resp', subs, response, 200)

    def test_servers_details(self):
        subs = {
            'image_id': fake.get_valid_image_id(),
            'compute_endpoint': self._get_compute_endpoint(),
            'access_ip_v4': '1.2.3.4',
            'access_ip_v6': 'fe80::'
        }
        uuid = self._servers_post(subs)
        response = self._do_get('servers/detail')
        subs['hostid'] = '[a-f0-9]+'
        subs['id'] = uuid
        self._verify_response('servers-details-resp', subs, response, 200)

    def test_servers_rebuild(self):
        subs = {
            'image_id': fake.get_valid_image_id(),
            'compute_endpoint': self._get_compute_endpoint(),
            'access_ip_v4': '1.2.3.4',
            'access_ip_v6': 'fe80::'
        }
        uuid = self._servers_post(subs)
        subs['access_ip_v4'] = "4.3.2.1"
        subs['access_ip_v6'] = '80fe::'
        response = self._do_post('servers/%s/action' % uuid,
                                 'server-action-rebuild', subs)
        subs['hostid'] = '[a-f0-9]+'
        subs['id'] = uuid
        self._verify_response('server-action-rebuild-resp',
                              subs, response, 202)


text:
<?xml version="1.0"?>

<layout xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/layout_generic.xsd">
    <update handle="formkey"/>
    <container name="root">
        <block class="Dotdigitalgroup\Email\Block\Coupon" name="ddg.coupon.container" template="Dotdigitalgroup_Email::email/coupon.phtml" cacheable="false"/>
    </container>
</layout>


text:
/*
 * ecs
 *
 * ECS Open API
 *
 */

package model

import (
	"encoding/json"
	"errors"
	"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/huaweicloud/huaweicloud-sdk-go-v3/core/converter"
	"strings"
)

// This is a auto create Body Object
type BatchDeleteServerTagsRequestBody struct {
	// 操作标识(仅支持小写):delete(删除)。
	Action BatchDeleteServerTagsRequestBodyAction `json:"action"`
	// 标签列表。
	Tags []ServerTag `json:"tags"`
}

func (o BatchDeleteServerTagsRequestBody) String() string {
	data, _ := json.Marshal(o)
	return strings.Join([]string{"BatchDeleteServerTagsRequestBody", string(data)}, " ")
}

type BatchDeleteServerTagsRequestBodyAction struct {
	value string
}

type BatchDeleteServerTagsRequestBodyActionEnum struct {
	DELETE BatchDeleteServerTagsRequestBodyAction
}

func GetBatchDeleteServerTagsRequestBodyActionEnum() BatchDeleteServerTagsRequestBodyActionEnum {
	return BatchDeleteServerTagsRequestBodyActionEnum{
		DELETE: BatchDeleteServerTagsRequestBodyAction{
			value: "delete",
		},
	}
}

func (c BatchDeleteServerTagsRequestBodyAction) MarshalJSON() ([]byte, error) {
	return json.Marshal(c.value)
}

func (c *BatchDeleteServerTagsRequestBodyAction) UnmarshalJSON(b []byte) error {
	myConverter := converter.StringConverterFactory("string")
	if myConverter != nil {
		val, err := myConverter.CovertStringToInterface(strings.Trim(string(b[:]), "\""))
		if err == nil {
			c.value = val.(string)
			return nil
		}
		return err
	} else {
		return errors.New("convert enum data to string error")
	}
}


text:
package gov.faa.ang.swac.controller.core.montecarlo.replay;

import gov.faa.ang.swac.common.datatypes.Timestamp;

import java.util.SortedMap;
import java.util.TreeMap;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

/**
 * This is a transitional mapping container for cached configurations: the CachedScenarioConfiguration
 * for a specific scenarioExecutionId contains an indexed collection of CachedTaskConfigurations, which
 * in turn contain the name-value property pairs. CachedScenarioConfiguration uses XML parsing and
 * rendering in conjunction with ConfigurationCache and CachedTaskConfiguration to implement StreamSerializable
 *
 * @author csmith
 *
 */
public class CachedScenarioConfiguration
{

	public static final String ELEMENT_NAME = "scenario";
	public static final String ID_ATTRIBUTE_NAME = "scenarioExecutionId";
	private static final String BASE_DATE_ATTRIBUTE_NAME = "baseDate";
	private static final String FORECAST_FY_ATTRIBUTE_NAME = "forecastFiscalYear";
	private static final String CLASSIFIER_ATTRIBUTE_NAME = "classifier";

	private final Integer scenarioExecutionId;
	private Timestamp baseDate;
	private int forecastFiscalYear;
	private String classifier;
	private SortedMap<String,CachedTaskConfiguration> tasks = new TreeMap<String,CachedTaskConfiguration>();

	/**
	 * scenarioExecutionId is an immutable property
	 * @param scenarioExecutionId
	 */
	public CachedScenarioConfiguration(Integer scenarioExecutionId)
	{
		this.scenarioExecutionId = scenarioExecutionId;
	}

	/**
	 *
	 * @return instance id
	 */
	public Integer getScenarioExecutionId()
	{
		return this.scenarioExecutionId;
	}

	public Timestamp getBaseDate() {
		return baseDate;
	}

	public void setBaseDate(Timestamp baseDate) {
		this.baseDate = baseDate;
	}

	public int getForecastFiscalYear() {
		return forecastFiscalYear;
	}

	public void setForecastFiscalYear(int forecastFiscalYear) {
		this.forecastFiscalYear = forecastFiscalYear;
	}

	public String getClassifier() {
		return classifier;
	}

	public void setClassifier(String classifier) {
		this.classifier = classifier;
	}

	/**
	 * Get-or-create behavior so calling code never explicitly needs to
	 * construct CachedTaskConfigurations
	 * @param taskId
	 * @return
	 */
	public CachedTaskConfiguration getTask(String taskId)
	{
		CachedTaskConfiguration retVal = this.tasks.get(taskId);
		if (retVal == null)
		{
			retVal = new CachedTaskConfiguration(taskId);
			this.tasks.put(taskId, retVal);
		}
		return retVal;
	}

	/**
	 * Flagged protected because calling code shouldn't need to use this method
	 * @param task
	 */
	protected void putTask(CachedTaskConfiguration task)
	{
		this.tasks.put(task.getTaskId(), task);
	}

	/**
	 * XML parsing. Sub-element parsing is delegated to CachedTaskConfiguration
	 * @param element
	 * @return
	 */
	protected static CachedScenarioConfiguration readElement(Element element) {
		CachedScenarioConfiguration scenario = new CachedScenarioConfiguration(Integer.parseInt(element.getAttribute(ID_ATTRIBUTE_NAME)));

		scenario.setBaseDate(Timestamp.myValueOf(element.getAttribute(BASE_DATE_ATTRIBUTE_NAME)));
		scenario.setForecastFiscalYear(Integer.parseInt(element.getAttribute(FORECAST_FY_ATTRIBUTE_NAME)));
		scenario.setClassifier(element.getAttribute(CLASSIFIER_ATTRIBUTE_NAME));

		NodeList taskList = element.getElementsByTagName(CachedTaskConfiguration.ELEMENT_NAME);
        for (int i = 0; i < taskList.getLength(); i++) {
            scenario.putTask(CachedTaskConfiguration.readElement((Element) taskList.item(i)));
        }

		return scenario;
    }

	/**
	 * XML formatting. Sub-element formatting is delegated to CachedTaskConfiguration
	 * @param d
	 * @param parent
	 * @param scenario
	 */
	protected static void writeElement(Document d, Element parent, CachedScenarioConfiguration scenario)
	{
		Element element = d.createElement(ELEMENT_NAME);
        parent.appendChild(element);

        element.setAttribute(ID_ATTRIBUTE_NAME, scenario.getScenarioExecutionId().toString());
        element.setAttribute(BASE_DATE_ATTRIBUTE_NAME, scenario.getBaseDate().toBonnDateOnlyString());
        element.setAttribute(FORECAST_FY_ATTRIBUTE_NAME, String.valueOf(scenario.getForecastFiscalYear()));
        element.setAttribute(CLASSIFIER_ATTRIBUTE_NAME, scenario.getClassifier());

        for (CachedTaskConfiguration task : scenario.tasks.values())
        {
        	CachedTaskConfiguration.writeElement(d, element, task);
        }
	}
}


text:
package com.kakao.hbase.stat.load;

import org.apache.hadoop.hbase.HRegionInfo;

public class RegionName implements Comparable<RegionName> {
    private final HRegionInfo hRegionInfo;
    private final int serverIndex;

    public RegionName(HRegionInfo hRegionInfo, int serverIndex) {
        this.hRegionInfo = hRegionInfo;
        this.serverIndex = serverIndex;
    }

    public String name() {
        return hRegionInfo.getEncodedName() + " | " + serverIndex;
    }

    @Override
    public int compareTo(RegionName o) {
        return hRegionInfo.compareTo(o.hRegionInfo);
    }
}


text:
import React from 'react';
import {version} from '../../package.json';

export const CURRENT_MAJOR = `v${version.split('.')[0]}`;
export const HOME_PATHS = ['/', '/tippyjs/'];
export const BOLD_HELLO = Hello;

function shouldShowLink(path, currentPath) {
  const version = getVersionFromPath(path);

  // Default to latest docs
  if (HOME_PATHS.includes(currentPath)) {
    return path.includes(CURRENT_MAJOR);
  }

  return currentPath.includes(version);
}

export function sortActivePages(edges, location) {
  return [...edges]
    .sort((a, b) => a.node.frontmatter.index - b.node.frontmatter.index)
    .filter(
      ({node}) =>
        shouldShowLink(node.frontmatter.path, location.pathname) ||
        (HOME_PATHS.includes(node.frontmatter.path) &&
          getVersionFromPath(location.pathname) === CURRENT_MAJOR)
    );
}

export function getVersionFromPath(path) {
  return (path.match(/\/(v\d+?)\//) || [null, CURRENT_MAJOR])[1];
}

export const ALL_PLACEMENTS = ['top', 'right', 'bottom', 'left'].reduce(
  (acc, placement) => {
    return acc.concat(placement, `${placement}-start`, `${placement}-end`);
  },
  []
);

export const EXTRA_ANIMATIONS = [
  'shift-away',
  'shift-toward',
  'scale',
  'perspective',
].reduce((acc, animation) => {
  return acc.concat(animation, `${animation}-subtle`, `${animation}-extreme`);
}, []);


text:
import AbstractDialog from "./abstract-dialog.js";
import worker from "../worker.js";
import utils from "../utils.js";
import app from "../app.js";
import structure from "../structure.js";
import templates from "../templates.js";

function nodeVisitor(name, node) {
    if (node instanceof Map) {
        let result = Object.create(null);
        for (let [key, value] of node) {
            result[key] = value;
        }
        return result;
    }
    return node;
}

let saveSummary = Object.assign(new AbstractDialog(".oe-save-summary-form"), {
    data: null,

    handleCollectStats(data) {
        this.data = data;
        this.show();
    },

    handleSave(e) {
        if (this.data) {
            let type = e.target.getAttribute("data-type"),
                text;
            switch (type) {
                case "text/html":
                    text = templates.get("summary")(this.data);
                    break;
                case "application/json":
                    text = JSON.stringify(this.data, nodeVisitor, 2);
                    break;
                default:
                    text = "TBD";
                    break;
            }
            e.target.href = utils.getBlobURL(text, type);
            this.hide();
        }
    }
});

saveSummary.listen([
    {type: "collectStats", owner: worker, handler: "handleCollectStats"},
    {type: "click", filter: "a[download]", handler: "handleSave"}
]);

export default saveSummary;

app.addAction("saveSummary", {
    get enabled() {
        return structure.structure.potentials.size > 0;
    },
    exec() {
        worker.invoke("collectStats");
    }
});