text:
import hassapi as hass
import globals

class HWCheck(hass.Hass):
    def initialize(self):
        self.listen_event(self.ha_event, "ha_started")
        self.listen_event(self.appd_event, "appd_started")

    def ha_event(self, event_name, data, kwargs):
        self.log_notify("Home Assistant is up", "INFO")
        self.run_in(self.hw_check, self.args["delay"])

    def appd_event(self, event_name, data, kwargs):
        self.log_notify("AppDaemon is up", "INFO")

    def hw_check(self, kwargs):
        state = self.get_state()

        if "zwave" in self.args and self.args["zwave"] not in state:
            self.log_notify("ZWAVE not started after delay period", "WARNING")
        if "hue" in self.args and self.args["hue"] not in state:
            self.log_notify("HUE not started after delay period", "WARNING")

    def log_notify(self, msg, level):
        self.log(msg, level)
        self.notify(msg, name=globals.notify)

    def terminate(self):
        self.log("Terminating!", "INFO")

redpajama_set_name: RedPajamaGithub


text:
package com.neopets.services.stockmarket.model.transform;

import com.neopets.NeopetsRequest;
import com.neopets.NeopetsURL;
import com.neopets.services.stockmarket.model.BuySharesRequest;
import com.neopets.transform.Marshaller;
import com.neopets.util.ParametersBuilder;

public class BuySharesRequestMarshaller implements Marshaller<BuySharesRequest> {

  @Override
  public NeopetsRequest marshall(BuySharesRequest in) {

    ParametersBuilder builder = new ParametersBuilder()
        .add("_ref_ck", in.getReferenceCheck())
        .add("type", "buy")
        .add("ticker_symbol", in.getTickerSymbol())
        .add("amount_shares", in.getAmount());

    return new NeopetsRequest(NeopetsURL.PROCESS_STOCK_MARKET, builder)
        .withOrigin(NeopetsURL.ROOT.toString())
        .withReferer(NeopetsURL.STOCK_MARKET_BUY.toString());
  }

}


text:
module Bosh::AzureCloud
  class DiskManager2
    include Bosh::Exec
    include Helpers

    def initialize(azure_client)
      @azure_client = azure_client
      @logger = Bosh::Clouds::Config.logger
    end

    ##
    # Creates a disk (possibly lazily) that will be attached later to a VM.
    #
    # @param [string]  disk_id               instance of DiskId
    # @param [string]  location              location of the disk
    # @param [Integer] size                  disk size in GiB
    # @param [string]  storage_account_type  the storage account type. Possible values: Standard_LRS or Premium_LRS.
    # When disk is in an availability zone
    # @param [String] zone                   Zone number in string. Possible values: "1", "2" or "3".
    #
    # @return [void]
    def create_disk(disk_id, location, size, storage_account_type, zone = nil)
      @logger.info("create_disk(#{disk_id}, #{location}, #{size}, #{storage_account_type}, #{zone})")
      resource_group_name = disk_id.resource_group_name
      disk_name = disk_id.disk_name
      caching = disk_id.caching
      tags = AZURE_TAGS.merge(
        'caching' => caching
      )
      disk_params = {
        name: disk_name,
        location: location,
        tags: tags,
        disk_size: size,
        account_type: storage_account_type
      }

      disk_params[:zone] = zone unless zone.nil?

      @logger.info("Start to create an empty managed disk '#{disk_name}' in resource group '#{resource_group_name}'")
      @azure_client.create_empty_managed_disk(resource_group_name, disk_params)
    end

    def create_disk_from_blob(disk_id, blob_uri, location, storage_account_type, zone = nil)
      @logger.info("create_disk_from_blob(#{disk_id}, #{blob_uri}, #{location}, #{storage_account_type}, #{zone})")
      resource_group_name = disk_id.resource_group_name
      disk_name = disk_id.disk_name
      caching = disk_id.caching
      tags = AZURE_TAGS.merge(
        'caching' => caching,
        'original_blob' => blob_uri
      )
      disk_params = {
        name: disk_name,
        location: location,
        tags: tags,
        source_uri: blob_uri,
        account_type: storage_account_type,
        zone: zone
      }
      @logger.info("Start to create a managed disk '#{disk_name}' in resource group '#{resource_group_name}' from the source uri '#{blob_uri}'")
      @azure_client.create_managed_disk_from_blob(resource_group_name, disk_params)
    end

    def delete_disk(resource_group_name, disk_name)
      @logger.info("delete_disk(#{resource_group_name}, #{disk_name})")
      retried = false
      begin
        @azure_client.delete_managed_disk(resource_group_name, disk_name) if _has_disk?(resource_group_name, disk_name)
      rescue Bosh::AzureCloud::AzureConflictError => e
        # Workaround: Do one retry for AzureConflictError, and give up if it still fails.
        #             After Managed Disks add "retry-after" in the response header,
        #             the workaround can be removed because the retry in azure_client will be triggered.
        unless retried
          @logger.debug("delete_disk: Received an AzureConflictError: '#{e.inspect}', retrying.")
          retried = true
          retry
        end
        @logger.error('delete_disk: Retry still fails due to AzureConflictError, giving up')
        raise e
      end
    end

    def delete_data_disk(disk_id)
      @logger.info("delete_data_disk(#{disk_id})")
      resource_group_name = disk_id.resource_group_name
      disk_name = disk_id.disk_name
      delete_disk(resource_group_name, disk_name)
    end

    def has_data_disk?(disk_id)
      @logger.info("has_data_disk?(#{disk_id})")
      resource_group_name = disk_id.resource_group_name
      disk_name = disk_id.disk_name
      _has_disk?(resource_group_name, disk_name)
    end

    def get_data_disk(disk_id)
      @logger.info("get_data_disk(#{disk_id})")
      resource_group_name = disk_id.resource_group_name
      disk_name = disk_id.disk_name
      _get_disk(resource_group_name, disk_name)
    end

    def snapshot_disk(snapshot_id, disk_name, metadata)
      @logger.info("snapshot_disk(#{snapshot_id}, #{disk_name}, #{metadata})")
      resource_group_name = snapshot_id.resource_group_name()
      snapshot_name = snapshot_id.disk_name
      snapshot_params = {
        name: snapshot_name,
        tags: metadata.merge(
          'original' => disk_name
        ),
        disk_name: disk_name
      }
      @logger.info("Start to create a snapshot '#{snapshot_name}' from a managed disk '#{disk_name}'")
      @azure_client.create_managed_snapshot(resource_group_name, snapshot_params)
    end

    def delete_snapshot(snapshot_id)
      @logger.info("delete_snapshot(#{snapshot_id})")
      resource_group_name = snapshot_id.resource_group_name()
      snapshot_name = snapshot_id.disk_name
      @azure_client.delete_managed_snapshot(resource_group_name, snapshot_name)
    end

    def has_snapshot?(resource_group_name, snapshot_name)
      @logger.info("has_snapshot?(#{resource_group_name}, #{snapshot_name})")
      snapshot = @azure_client.get_managed_snapshot_by_name(resource_group_name, snapshot_name)
      !snapshot.nil?
    end

    # bosh-disk-os-[VM-NAME]
    def generate_os_disk_name(vm_name)
      "#{MANAGED_OS_DISK_PREFIX}-#{vm_name}"
    end

    # bosh-disk-os-[VM-NAME]-ephemeral
    def generate_ephemeral_disk_name(vm_name)
      "#{MANAGED_OS_DISK_PREFIX}-#{vm_name}-#{EPHEMERAL_DISK_POSTFIX}"
    end

    def os_disk(vm_name, stemcell_info, size, caching, use_root_disk_as_ephemeral)
      validate_disk_caching(caching)

      disk_size = get_os_disk_size(size, stemcell_info, use_root_disk_as_ephemeral)

      {
        disk_name: generate_os_disk_name(vm_name),
        disk_size: disk_size,
        disk_caching: caching
      }
    end

    def ephemeral_disk(vm_name, instance_type, size, type, use_root_disk_as_ephemeral)
      return nil if use_root_disk_as_ephemeral

      disk_info = DiskInfo.for(instance_type)
      disk_size = disk_info.size
      unless size.nil?
        validate_disk_size(size)
        disk_size = size / 1024
      end

      {
        disk_name: generate_ephemeral_disk_name(vm_name),
        disk_size: disk_size,
        disk_caching: 'ReadWrite',
        disk_type: type
      }
    end

    def migrate_to_zone(disk_id, disk, zone)
      @logger.info("migrate_to_zone(#{disk_id}, #{disk}, #{zone})")
      resource_group_name = disk_id.resource_group_name
      disk_name = disk_id.disk_name

      snapshot_id = DiskId.create(disk_id.caching, true, resource_group_name: resource_group_name)
      snapshot_name = snapshot_id.disk_name
      snapshot_disk(snapshot_id, disk_name, {})
      @logger.info("Snapshot #{snapshot_name} is created for disk #{disk_name} for migration purpose")

      if has_snapshot?(resource_group_name, snapshot_name)
        delete_disk(resource_group_name, disk_name)
      else
        error_message = "migrate_to_zone - Can'n find snapshot '#{snapshot_name}' in resource group '#{resource_group_name}', abort migration.\n"
        error_message += "You need to migrate '#{disk_id}' to zone '#{zone}' manually."
        raise Bosh::Clouds::CloudError, error_message
      end

      disk_params = {
        name: disk_name,
        location: disk[:location],
        zone: zone,
        account_type: disk[:sku_name],
        tags: disk[:tags]
      }

      max_retries = 2
      retry_count = 0
      begin
        @azure_client.create_managed_disk_from_snapshot(resource_group_name, disk_params, snapshot_name)
      rescue StandardError => e
        if retry_count < max_retries
          @logger.info("migrate_to_zone - Got error when creating '#{disk_name}' from snapshot '#{snapshot_name}': \n#{e.inspect}\n#{e.backtrace.join('\n')}. \nRetry #{retry_count}: will retry to create the disk.")
          retry_count += 1
          retry
        end

        error_message = "migrate_to_zone - Failed to create disk '#{disk_name}' from snapshot '#{snapshot_name}' in resource group '#{resource_group_name}'.\n"
        error_message += "You need to recover '#{disk_id}' mannually from snapshot '#{snapshot_name}' and put it in zone '#{zone}'. Try:\n"
        error_message += "    'az disk create --resource-group #{resource_group_name} --location #{disk[:location]} --sku #{disk[:account_type]} --zone #{zone} --name #{disk_name} --source #{snapshot_name}'\n"
        error_message += "#{e.inspect}\n#{e.backtrace.join("\n")}"
        raise Bosh::Clouds::CloudError, error_message
      end

      if has_data_disk?(disk_id)
        delete_snapshot(snapshot_id)
        @logger.info("Disk '#{disk_name}' has migrated to zone '#{zone}'")
      else
        error_message = "migrate_to_zone - Can'n find disk '#{disk_name}' in resource group '#{resource_group_name}' after migration.\n"
        error_message += "You need to recover '#{disk_id}' manually from snapshot '#{snapshot_name}' and put it in zone '#{zone}'. Try:\n"
        error_message += "    'az disk create --resource-group #{resource_group_name} --location #{disk[:location]} --sku #{disk[:account_type]} --zone #{zone} --name #{disk_name} --source #{snapshot_name}'\n"
        raise Bosh::Clouds::CloudError, error_message
      end
    end

    private

    def _get_disk(resource_group_name, disk_name)
      @logger.info("_get_disk(#{resource_group_name}, #{disk_name})")
      disk = @azure_client.get_managed_disk_by_name(resource_group_name, disk_name)
    end

    def _has_disk?(resource_group_name, disk_name)
      @logger.info("_has_disk?(#{resource_group_name}, #{disk_name})")
      disk = _get_disk(resource_group_name, disk_name)
      !disk.nil?
    end
  end
end


text:
/**
 * Created by Douglas Anastasia on 10/6/15.
 */

function build_deploy_data() {
    var postData = {};
    var tags = $('#tagbox');
    $('#paramCol').find('.box').each(function (index, box) {
        if ($(box).hasClass('hidden')) {
            return;
        }
        var tempData = {};
        var boxName = $(box).find('.box-title').html();
        if (boxName == 'Tags') {
            return
        }
        tempData['name'] = boxName;
        $(box).find('.box-body input').each(function (i, item) {
            var name = $(item).attr('id');
            tempData[name] = $(item).val()
        });
        tags.find('input').each(function (i, item) {
            var name = $(item).attr('id');
            tempData[name] = $(item).val()
        });
        postData[index] = tempData;
    });
    send_deploy_data(postData)
}

function update_vpc() {
    var csrftoken = getCookie('csrftoken');
    var deploy_id = $('#deploy_id').html();
    var region = $("#region-group").find('.btn').val();
    var account = $("#account-group").find('.btn').val();

    $("#vpc-group").find('.selection').html('');
    var requestData = {
        'csrfmiddlewaretoken': csrftoken,
        'data': 'vpc',
        'function': 'list',
        'deploy_id': deploy_id,
        'region': region,
        'account': account
    };
    $.ajax({
            type: "POST",
            url: callback_url,
            data: requestData,
            dataType: "json",
            success: function (response) {
                var regionHTML = '';
                $.each(response, function (index, vpc) {
                    regionHTML += '
' + vpc.name + ' (' + vpc.id + ')' + '
';
                });
                var vpcDropdown = $('#vpc_dropdown');
                vpcDropdown.html(regionHTML);
                var vpcGroup = $("#vpc-group");
                vpcGroup.find('.selection').html('None');
                vpcGroup.find('.btn').val('None');

                vpcDropdown.find("li a").click(function () {
                    $(this).parents("#vpc-group").find('.selection').html($(this).text());
                    $(this).parents("#vpc-group").find('.btn').val($(this).data('value'));
                });

                $('#vpc_spin').remove();
            }
        }
    )
}

function update_regions() {
    var page_content = $('.content');
    var csrftoken = getCookie('csrftoken');
    var deploy_id = $('#deploy_id').html();
    var requestData = {
        'csrfmiddlewaretoken': csrftoken,
        'data': 'data',
        'function': 'regions',
        'deploy_id': deploy_id
    };
    $.ajax({
            type: "POST",
            url: callback_url,
            data: requestData,
            dataType: "json",
            success: function (response) {
                var regionHTML = '';
                $.each(response, function (index, region) {
                    regionHTML += '
' + region + '
';
                });
                var regionDropdown = $('#region_dropdown');
                regionDropdown.html(regionHTML);

                var vpcGroup = $("#region-group");
                vpcGroup.find('.selection').html('None');
                vpcGroup.find('.btn').val('None');

                regionDropdown.find("li a").click(function () {
                    $(this).parents("#region-group").find('.selection').html($(this).text());
                    $(this).parents("#region-group").find('.btn').val($(this).text());
                    update_vpc();
                });

                $('#region_spin').remove();
            }
        }
    )
}

function send_deploy_data(postData) {
    var page_content = $('.content');
    var csrftoken = getCookie('csrftoken');
    var deployId = $('#deploy_id').html();
    var region = $("#region-group").find('.btn').val();
    var account = $("#account-group").find('.btn').val();
    var vpcId = $("#vpc-group").find('.btn').val();
    var appName = $("#appName").val();
    var googleGroup = $("#googleGroup").val();
    var requestData = {
        'csrfmiddlewaretoken': csrftoken,
        'data': 'deploy',
        'function': 'do_deploy',
        'deploy_id': deployId,
        'region': region,
        'account': account,
        'vpcid': vpcId,
        'appName': appName,
        'googleGroup': googleGroup,
        'deployData': JSON.stringify(postData)
    };
    //requestData['deployData'] = JSON.stringify(postData);

    $.ajax({
            type: "POST",
            url: callback_url,
            data: requestData,
            dataType: "json",
            success: function (response) {
                //template_list_html(response);
            }
        }
    )
}

function update_subnet_template_list() {
    var page_content = $('.content');
    var csrftoken = getCookie('csrftoken');
    var deploy_id = $('#deploy_id').html();
    $.ajax({
            type: "POST",
            url: callback_url,
            data: {
                'csrfmiddlewaretoken': csrftoken,
                'data': 'deploy',
                'function': 'template_list',
                'deploy_id': deploy_id
            },
            dataType: "json",
            success: function (response) {
                //template_list_html(response);
                var listHTML = '
';
                $.each(response, function (key, value) {
                    listHTML += '
' + key + '
';
                    if (typeof(Storage) !== "undefined") {
                        localStorage.setItem(key, JSON.stringify(value));
                    }
                });

                listHTML += '
';
                var page_content = $('.content');
                page_content.find('#template-list').html(listHTML);

                $('#template_ul').find("i").on("click", function (event) {
                    add_template_html($(this).attr('id'));
                });
            }
        }
    )
}

function update_vpc_template_list() {
    var page_content = $('.content');
    var csrftoken = getCookie('csrftoken');
    var deploy_id = $('#deploy_id').html();
    $.ajax({
        type: "POST",
        url: callback_url,
        data: {
            'csrfmiddlewaretoken': csrftoken,
            'data': 'deploy',
            'function': 'get_vtemplates',
                'deploy_id': deploy_id
            },
            dataType: "json",
            success: function (response) {
                //template_list_html(response);
                var listHTML = '
';
                $.each(response, function (key, value) {
                    listHTML += '
' + key + '
';
                    if (typeof(Storage) !== "undefined") {
                        localStorage.setItem(key, JSON.stringify(value));
                    }
                });

                listHTML += '
';
                var page_content = $('.content');
                page_content.find('#template-list').html(listHTML);

                $('#template_ul').find("i").on("click", function (event) {
                    add_template_html($(this).attr('id'));
                });
            }
        }
    )
}

function add_template_html(template_name) {
    var blankBoxElement = $('#template-box');
    var tagBoxElement = $('#tagbox');
    var parameterCol = $('#paramCol');
    if (tagBoxElement.length == 0) {
        tagBoxElement = blankBoxElement.clone();
        tagBoxElement.attr('id', 'tagbox');
        tagBoxElement.find('.box-title').html('Tags');
        tagBoxElement.removeClass('hidden').removeClass('box-primary').addClass('box-warning');
        tagBoxElement.find('.box-footer').remove();
        parameterCol.prepend(tagBoxElement)

    }

    var boxElement = blankBoxElement.clone();
    var templateJson = JSON.parse(localStorage.getItem(template_name));
    boxElement.find('.box-title').html(template_name);
    boxElement.attr('id', template_name);
    var tagList = '';
    var paramList = '';
    $.each(templateJson['parameters'], function (key, value) {
        var tempElement = '\

' + key + '\
';
        tempElement += '\
<input type="text" class="form-control" id="' + key + '\"\>

';
        if (key.toLowerCase().indexOf('tag') < 0 && key.toLowerCase() != roleArn.toLowerCase()) {
            paramList += tempElement
        } else {
            if (tagBoxElement.find('#' + key).length == 0) {
                tagList += tempElement
            }
        }
    });

    boxElement.find('.box-body').html(paramList);
    if (tagList != '') {
        tagBoxElement.find('.box-body').append(tagList);
    }
    boxElement.removeClass('hidden');
    parameterCol.append(boxElement);

}


text:
namespace Umbraco.Cms.Core.Models;

public class AnchorsModel
{
    public string? RteContent { get; set; }
}


text:
package com.intellij.ide.startup;

import com.intellij.openapi.vfs.VirtualFile;

import java.util.Collection;

/**
 * @author peter
 */
public interface BackgroundableCacheUpdater extends CacheUpdater {

  boolean initiallyBackgrounded();

  boolean canBeSentToBackground(Collection<VirtualFile> remaining);

  void backgrounded(Collection<VirtualFile> remaining);

}


text:
class CreateLists < ActiveRecord::Migration
  def self.up
    create_table :lists do |t|
      t.string :title
      t.boolean :share
      t.references :user

      t.timestamps
    end
  end

  def self.down
    drop_table :lists
  end
end


text:
/**
 * Created by aaronphillips on 12/07/2016.
 */

//Two hand crafted scenes with a number of scenes
var scenes = [
    {
        'name': name,
        'maximumOnScreen': {
            'image': 3,
            'text': 1,
            'video': 1,
            'audio': 1
        },
        'displayDuration': 10,
        'displayInterval': 3,
        'transitionDuration': 1.4,
        'themes': {
            "ThemeArt": ",,",
            "ThemeGreat": ",,",
            "ThemeBikes": ",,",
            "ThemeDisruption": ",,",
            "ThemeHappy": ",,",
            "ThemeGraduation": ",,"
        },
        'style': {
            'backgroundColor': 'black'
        },
        'scene': []
    },{
        'name': name,
        'maximumOnScreen': {
            'image': 3,
            'text': 1,
            'video': 1,
            'audio': 1
        },
        'displayDuration': 10,
        'displayInterval': 3,
        'transitionDuration': 1.4,
        'themes': {
            "ThemeRainy": ",,",
            "ThemeGreen": ",,",
            "ThemeBusy": ",,",
            "ThemeTrams": ",,",
            "ThemeCars": ",,",
            "ThemeHappy": ",,"
        },
        'style': {
            'backgroundColor': 'black'
        },
        'scene': []
    }
];

//Full union of themes from scenes
var fullThemesFromScenes = [
    "ThemeArt","ThemeGreat","ThemeRainy","ThemeBikes","ThemeGreen","ThemeTrams","ThemeDisruption","ThemeHappy","ThemeBusy","ThemeGraduation","ThemeCars"
];

//Union of themes with excludes (to mimic user excluding a theme) [ ThemeGraduation, ThemeCars ] excluded
var themesFromScenesWithExcludes = [
    "ThemeArt","ThemeGreat","ThemeRainy","ThemeBikes","ThemeGreen","ThemeTrams","ThemeDisruption","ThemeHappy","ThemeBusy"
];

//Basics of structure for the scene graph - in the implementation more state is required such as the scene list that was used to generate the sceneGraph
var sceneGraph = {
    city: {
        chicago: {
            "ThemeArt": {
                "ThemePainting": {

                },
                "ThemePublicAttractions": {
                    "ThemeGallery": {

                    }
                }
            },
            "ThemeGreat": {}
        },
        manchester: {
            "ThemeArt": {},
            "ThemeRainy": {}
        }
    },
    movement: {
        chicago: {
            "ThemeBikes": {

            },
            "ThemeGreen": {
                "ThemeElectricBus": {

                }
            }
        },
        manchester: {
            "ThemeTrams": {

            },
            "ThemeDisruption": {

            }
        }
    },
    people: {
        chicago: {
            "ThemeHappy": {}
        },
        manchester: {
            "ThemeBusy": {}
        }
    }
};

//Purely a place holder for a theme node
var emptyThemeNode = {
    type: "Theme",
    id: "",
    name: "",
    parentRelationshipIds: [],
    childRelationshipIds: []
};

//Purely a place holder for a scene node
var emptySceneNode = {
    type: "Scene",
    id: "",
    name: "",
    parentRelationshipIds: [],
    childRelationshipIds: []
};

//OPTION 1: The output nodes we can give to D3 - Each theme is parented to a city node,
// these city nodes are children of each of the graphThemes - this may hide the connection of the child of the city node to which graph theme they are to be applied too.
// I think OPTION 2 may be more ideal - will discuss
var sceneGraphNodesWithSingleCityNodes = [
    {
        type: "Scene",
        id: "Scene2",
        name: "Scene2",
        parentRelationshipIds: [
            "ThemeRainy",
            "ThemeGreen",
            "ThemeBusy",
            "ThemeTrams",
            "ThemeCars",
            "ThemeHappy"
        ],
        childRelationshipIds: []
    },
    {
        type: "Scene",
        id: "Scene1",
        name: "Scene1",
        parentRelationshipIds: [
            "ThemeArt",
            "ThemeGreat",
            "ThemeBikes",
            "ThemeDisruption",
            "ThemeHappy",
            "ThemeGraduation"
        ],
        childRelationshipIds: []
    },
    {
        type: "Theme",
        id: "ThemeBusy",
        name: "ThemeBusy",
        parentRelationshipIds: [
            "ManchesterCity"
        ],
        childRelationshipIds: []
    },
    {
        type: "Theme",
        id: "ThemeHappy",
        name: "ThemeHappy",
        parentRelationshipIds: [
            "ChicagoCity"
        ],
        childRelationshipIds: []
    },
    {
        type: "Theme",
        id: "ThemeDisruption",
        name: "ThemeDisruption",
        parentRelationshipIds: [
            "ManchesterCity"
        ],
        childRelationshipIds: []
    },
    {
        type: "Theme",
        id: "ThemeTrams",
        name: "ThemeTrams",
        parentRelationshipIds: [
            "ManchesterCity"
        ],
        childRelationshipIds: []
    },
    {
        type: "Theme",
        id: "ThemeElectricBus",
        name: "ThemeElectricBus",
        parentRelationshipIds: [
            "ThemeGreen"
        ],
        childRelationshipIds: []
    },
    {
        type: "Theme",
        id: "ThemeGreen",
        name: "ThemeGreen",
        parentRelationshipIds: [
            "ChicagoCity"
        ],
        childRelationshipIds: [
            "ThemeElectricBus"
        ]
    },
    {
        type: "Theme",
        id: "ThemeBikes",
        name: "ThemeBikes",
        parentRelationshipIds: [
            "ChicagoCity"
        ],
        childRelationshipIds: []
    },
    {
        type: "Theme",
        id: "ThemeRainy",
        name: "ThemeRainy",
        parentRelationshipIds: [
            "ManchesterCity"
        ],
        childRelationshipIds: []
    },
    {
        type: "Theme",
        id: "ThemeGallery",
        name: "ThemeGallery",
        parentRelationshipIds: [
            "ThemePublicAttractions"
        ],
        childRelationshipIds: []
    },
    {
        type: "Theme",
        id: "ThemePublicAttractions",
        name: "ThemePublicAttractions",
        parentRelationshipIds: [
            "ThemeArt"
        ],
        childRelationshipIds: [
            "ThemeGallery"
        ]
    },
    {
        type: "Theme",
        id: "ThemePainting",
        name: "ThemePainting",
        parentRelationshipIds: [
            "ThemeArt"
        ],
        childRelationshipIds: []
    },
    {
        type: "Theme",
        id: "ThemeArt",
        name: "ThemeArt",
        parentRelationshipIds: [
            "ChicagoCity", "ManchesterCity"
        ],
        childRelationshipIds: [
            "ThemePainting", "ThemePublicAttractions"
        ]
    },
    {
        type: "City",
        _id: "ManchesterCity",
        name: "Manchester,",
        parentRelationshipIds: [
            "GraphThemeCity", "GraphThemePeople", "GraphThemeMovement"
        ],
        childRelationshipIds: []
    },
    {
        type: "City",
        _id: "ChicagoCity",
        name: "Chicago,",
        parentRelationshipIds: [
            "GraphThemeCity", "GraphThemePeople", "GraphThemeMovement"
        ],
        childRelationshipIds: []
    },
    {
        type: "root", //could also be called GraphTheme
        _id: "GraphThemeCity",
        name: "City",
        parentRelationshipIds: [],
        childRelationshipIds: []
    },
    {
        type: "root", //could also be called GraphTheme
        _id: "GraphThemePeople",
        name: "People",
        parentRelationshipIds: [],
        childRelationshipIds: []
    },
    {
        type: "root", //could also be called GraphTheme
        _id: "GraphThemeMovement",
        name: "Movement",
        parentRelationshipIds: [],
        childRelationshipIds: []
    }
];

//OPTION 2 - Scene Graph nodes with unique city nodes per graph theme
var sceneGraphNodesWithUniqueCityForEachGraphTheme = [
    {
        type: "Theme",
        id: "ThemeBusy",
        name: "ThemeBusy",
        parentRelationshipIds: [
            "PeopleManchesterCity"
        ],
        childRelationshipIds: []
    },
    {
        type: "Theme",
        id: "ThemeHappy",
        name: "ThemeHappy",
        parentRelationshipIds: [
            "PeopleChicagoCity"
        ],
        childRelationshipIds: []
    },
    {
        type: "Theme",
        id: "ThemeDisruption",
        name: "ThemeDisruption",
        parentRelationshipIds: [
            "MovementManchesterCity"
        ],
        childRelationshipIds: []
    },
    {
        type: "Theme",
        id: "ThemeTrams",
        name: "ThemeTrams",
        parentRelationshipIds: [
            "MovementManchesterCity"
        ],
        childRelationshipIds: []
    },
    {
        type: "Theme",
        id: "ThemeElectricBus",
        name: "ThemeElectricBus",
        parentRelationshipIds: [
            "ThemeGreen"
        ],
        childRelationshipIds: []
    },
    {
        type: "Theme",
        id: "ThemeGreen",
        name: "ThemeGreen",
        parentRelationshipIds: [
            "MovementChicagoCity"
        ],
        childRelationshipIds: [
            "ThemeElectricBus"
        ]
    },
    {
        type: "Theme",
        id: "ThemeBikes",
        name: "ThemeBikes",
        parentRelationshipIds: [
            "MovementChicagoCity"
        ],
        childRelationshipIds: []
    },
    {
        type: "Theme",
        id: "ThemeRainy",
        name: "ThemeRainy",
        parentRelationshipIds: [
            "CityManchesterCity"
        ],
        childRelationshipIds: []
    },
    {
        type: "Theme",
        id: "ThemeGallery",
        name: "ThemeGallery",
        parentRelationshipIds: [
            "ThemePublicAttractions"
        ],
        childRelationshipIds: []
    },
    {
        type: "Theme",
        id: "ThemePublicAttractions",
        name: "ThemePublicAttractions",
        parentRelationshipIds: [
            "ThemeArt"
        ],
        childRelationshipIds: [
            "ThemeGallery"
        ]
    },
    {
        type: "Theme",
        id: "ThemePainting",
        name: "ThemePainting",
        parentRelationshipIds: [
            "ThemeArt"
        ],
        childRelationshipIds: []
    },
    {
        type: "Theme",
        id: "ThemeArt",
        name: "ThemeArt",
        parentRelationshipIds: [
            "CityChicagoCity", "CityManchesterCity"
        ],
        childRelationshipIds: [
            "ThemePainting", "ThemePublicAttractions"
        ]
    },
    //graph theme 1
    {
        type: "City",
        _id: "CityManchesterCity",
        name: "Manchester,",
        parentRelationshipIds: [
            "GraphThemeCity", "GraphThemePeople", "GraphThemeMovement"
        ],
        childRelationshipIds: []
    },
    {
        type: "City",
        _id: "CityChicagoCity",
        name: "Chicago,",
        parentRelationshipIds: [
            "GraphThemeCity", "GraphThemePeople", "GraphThemeMovement"
        ],
        childRelationshipIds: []
    },
    //graph theme 2
    {
        type: "City",
        _id: "PeopleManchesterCity",
        name: "Manchester,",
        parentRelationshipIds: [
            "GraphThemeCity", "GraphThemePeople", "GraphThemeMovement"
        ],
        childRelationshipIds: []
    },
    {
        type: "City",
        _id: "PeopleChicagoCity",
        name: "Chicago,",
        parentRelationshipIds: [
            "GraphThemeCity", "GraphThemePeople", "GraphThemeMovement"
        ],
        childRelationshipIds: []
    },
    //graph theme 3
    {
        type: "City",
        _id: "MovementManchesterCity",
        name: "Manchester,",
        parentRelationshipIds: [
            "GraphThemeCity", "GraphThemePeople", "GraphThemeMovement"
        ],
        childRelationshipIds: []
    },
    {
        type: "City",
        _id: "MovementChicagoCity",
        name: "Chicago,",
        parentRelationshipIds: [
            "GraphThemeCity", "GraphThemePeople", "GraphThemeMovement"
        ],
        childRelationshipIds: []
    },
    {
        type: "root", //could also be called GraphTheme
        _id: "GraphThemeCity",
        name: "City",
        parentRelationshipIds: [],
        childRelationshipIds: []
    },
    {
        type: "root", //could also be called GraphTheme
        _id: "GraphThemePeople",
        name: "People",
        parentRelationshipIds: [],
        childRelationshipIds: []
    },
    {
        type: "root", //could also be called GraphTheme
        _id: "GraphThemeMovement",
        name: "Movement",
        parentRelationshipIds: [],
        childRelationshipIds: []
    }
];

//CREATED FROM SCRIPT

var nodes = [ { _id: 'city',
    name: 'city',
    parentRelationshipIds: [],
    childrenRelationshIds: [] },
    { _id: 'ThemePainting',
        name: 'ThemePainting',
        parentRelationshipIds: [ 'ThemeArt' ],
        childrenRelationshIds: [] },
    { _id: 'ThemeGallery',
        name: 'ThemeGallery',
        parentRelationshipIds: [ 'ThemePublicAttractions' ],
        childrenRelationshIds: [] },
    { _id: 'ThemePublicAttractions',
        name: 'ThemePublicAttractions',
        parentRelationshipIds: [ 'ThemeArt' ],
        childrenRelationshIds: [] },
    { _id: 'ThemeArt',
        name: 'ThemeArt',
        parentRelationshipIds: [ 'chicago' ],
        childrenRelationshIds: [] },
    { _id: 'ThemeGreat',
        name: 'ThemeGreat',
        parentRelationshipIds: [ 'chicago' ],
        childrenRelationshIds: [] },
    { _id: 'chicago',
        name: 'chicago',
        parentRelationshipIds: [ 'city' ],
        childrenRelationshIds: [] },
    { _id: 'ThemeArt',
        name: 'ThemeArt',
        parentRelationshipIds: [ 'manchester' ],
        childrenRelationshIds: [] },
    { _id: 'ThemeRainy',
        name: 'ThemeRainy',
        parentRelationshipIds: [ 'manchester' ],
        childrenRelationshIds: [] },
    { _id: 'manchester',
        name: 'manchester',
        parentRelationshipIds: [ 'city' ],
        childrenRelationshIds: [] },
    { _id: 'movement',
        name: 'movement',
        parentRelationshipIds: [],
        childrenRelationshIds: [] },
    { _id: 'ThemeBikes',
        name: 'ThemeBikes',
        parentRelationshipIds: [ 'chicago' ],
        childrenRelationshIds: [] },
    { _id: 'ThemeElectricBus',
        name: 'ThemeElectricBus',
        parentRelationshipIds: [ 'ThemeGreen' ],
        childrenRelationshIds: [] },
    { _id: 'ThemeGreen',
        name: 'ThemeGreen',
        parentRelationshipIds: [ 'chicago' ],
        childrenRelationshIds: [] },
    { _id: 'chicago',
        name: 'chicago',
        parentRelationshipIds: [ 'movement' ],
        childrenRelationshIds: [] },
    { _id: 'ThemeTrams',
        name: 'ThemeTrams',
        parentRelationshipIds: [ 'manchester' ],
        childrenRelationshIds: [] },
    { _id: 'ThemeDisruption',
        name: 'ThemeDisruption',
        parentRelationshipIds: [ 'manchester' ],
        childrenRelationshIds: [] },
    { _id: 'manchester',
        name: 'manchester',
        parentRelationshipIds: [ 'movement' ],
        childrenRelationshIds: [] },
    { _id: 'people',
        name: 'people',
        parentRelationshipIds: [],
        childrenRelationshIds: [] },
    { _id: 'ThemeHappy',
        name: 'ThemeHappy',
        parentRelationshipIds: [ 'chicago' ],
        childrenRelationshIds: [] },
    { _id: 'chicago',
        name: 'chicago',
        parentRelationshipIds: [ 'people' ],
        childrenRelationshIds: [] },
    { _id: 'ThemeBusy',
        name: 'ThemeBusy',
        parentRelationshipIds: [ 'manchester' ],
        childrenRelationshIds: [] },
    { _id: 'manchester',
        name: 'manchester',
        parentRelationshipIds: [ 'people' ],
        childrenRelationshIds: [] } ]

var deduped =  [ { _id: 'city',
    name: 'city',
    parentRelationshipIds: [],
    childrenRelationshIds: [] },
    { _id: 'ThemePainting',
        name: 'ThemePainting',
        parentRelationshipIds: [ 'ThemeArt' ],
        childrenRelationshIds: [] },
    { _id: 'ThemeGallery',
        name: 'ThemeGallery',
        parentRelationshipIds: [ 'ThemePublicAttractions' ],
        childrenRelationshIds: [] },
    { _id: 'ThemePublicAttractions',
        name: 'ThemePublicAttractions',
        parentRelationshipIds: [ 'ThemeArt' ],
        childrenRelationshIds: [] },
    { _id: 'ThemeArt',
        name: 'ThemeArt',
        parentRelationshipIds: [ 'chicago' ],
        childrenRelationshIds: [] },
    { _id: 'ThemeGreat',
        name: 'ThemeGreat',
        parentRelationshipIds: [ 'chicago' ],
        childrenRelationshIds: [] },
    { _id: 'chicago',
        name: 'chicago',
        parentRelationshipIds: [ 'city' ],
        childrenRelationshIds: [] },
    { _id: 'ThemeArt',
        name: 'ThemeArt',
        parentRelationshipIds: [ 'manchester' ],
        childrenRelationshIds: [] },
    { _id: 'ThemeRainy',
        name: 'ThemeRainy',
        parentRelationshipIds: [ 'manchester' ],
        childrenRelationshIds: [] },
    { _id: 'manchester',
        name: 'manchester',
        parentRelationshipIds: [ 'city' ],
        childrenRelationshIds: [] },
    { _id: 'movement',
        name: 'movement',
        parentRelationshipIds: [],
        childrenRelationshIds: [] },
    { _id: 'ThemeBikes',
        name: 'ThemeBikes',
        parentRelationshipIds: [ 'chicago' ],
        childrenRelationshIds: [] },
    { _id: 'ThemeElectricBus',
        name: 'ThemeElectricBus',
        parentRelationshipIds: [ 'ThemeGreen' ],
        childrenRelationshIds: [] },
    { _id: 'ThemeGreen',
        name: 'ThemeGreen',
        parentRelationshipIds: [ 'chicago' ],
        childrenRelationshIds: [] },
    { _id: 'chicago',
        name: 'chicago',
        parentRelationshipIds: [ 'movement' ],
        childrenRelationshIds: [] },
    { _id: 'ThemeTrams',
        name: 'ThemeTrams',
        parentRelationshipIds: [ 'manchester' ],
        childrenRelationshIds: [] },
    { _id: 'ThemeDisruption',
        name: 'ThemeDisruption',
        parentRelationshipIds: [ 'manchester' ],
        childrenRelationshIds: [] },
    { _id: 'manchester',
        name: 'manchester',
        parentRelationshipIds: [ 'movement' ],
        childrenRelationshIds: [] },
    { _id: 'people',
        name: 'people',
        parentRelationshipIds: [],
        childrenRelationshIds: [] },
    { _id: 'ThemeHappy',
        name: 'ThemeHappy',
        parentRelationshipIds: [ 'chicago' ],
        childrenRelationshIds: [] },
    { _id: 'chicago',
        name: 'chicago',
        parentRelationshipIds: [ 'people' ],
        childrenRelationshIds: [] },
    { _id: 'ThemeBusy',
        name: 'ThemeBusy',
        parentRelationshipIds: [ 'manchester' ],
        childrenRelationshIds: [] },
    { _id: 'manchester',
        name: 'manchester',
        parentRelationshipIds: [ 'people' ],
        childrenRelationshIds: [] } ]

var fullyUnique =  [ { _id: 'city',
    name: 'city',
    parentRelationshipIds: [],
    childrenRelationshIds: [] },
    { _id: 'ThemePainting',
        name: 'ThemePainting',
        parentRelationshipIds: [ 'ThemeArt' ],
        childrenRelationshIds: [] },
    { _id: 'ThemeGallery',
        name: 'ThemeGallery',
        parentRelationshipIds: [ 'ThemePublicAttractions' ],
        childrenRelationshIds: [] },
    { _id: 'ThemePublicAttractions',
        name: 'ThemePublicAttractions',
        parentRelationshipIds: [ 'ThemeArt' ],
        childrenRelationshIds: [] },
    { _id: 'ThemeArt',
        name: 'ThemeArt',
        parentRelationshipIds: [ 'chicago', 'manchester' ],
        childrenRelationshIds: [] },
    { _id: 'ThemeGreat',
        name: 'ThemeGreat',
        parentRelationshipIds: [ 'chicago' ],
        childrenRelationshIds: [] },
    { _id: 'chicago',
        name: 'chicago',
        parentRelationshipIds: [ 'city', 'movement', 'people' ],
        childrenRelationshIds: [] },
    { _id: 'ThemeRainy',
        name: 'ThemeRainy',
        parentRelationshipIds: [ 'manchester' ],
        childrenRelationshIds: [] },
    { _id: 'manchester',
        name: 'manchester',
        parentRelationshipIds: [ 'city', 'movement', 'people' ],
        childrenRelationshIds: [] },
    { _id: 'movement',
        name: 'movement',
        parentRelationshipIds: [],
        childrenRelationshIds: [] },
    { _id: 'ThemeBikes',
        name: 'ThemeBikes',
        parentRelationshipIds: [ 'chicago' ],
        childrenRelationshIds: [] },
    { _id: 'ThemeElectricBus',
        name: 'ThemeElectricBus',
        parentRelationshipIds: [ 'ThemeGreen' ],
        childrenRelationshIds: [] },
    { _id: 'ThemeGreen',
        name: 'ThemeGreen',
        parentRelationshipIds: [ 'chicago' ],
        childrenRelationshIds: [] },
    { _id: 'ThemeTrams',
        name: 'ThemeTrams',
        parentRelationshipIds: [ 'manchester' ],
        childrenRelationshIds: [] },
    { _id: 'ThemeDisruption',
        name: 'ThemeDisruption',
        parentRelationshipIds: [ 'manchester' ],
        childrenRelationshIds: [] },
    { _id: 'people',
        name: 'people',
        parentRelationshipIds: [],
        childrenRelationshIds: [] },
    { _id: 'ThemeHappy',
        name: 'ThemeHappy',
        parentRelationshipIds: [ 'chicago' ],
        childrenRelationshIds: [] },
    { _id: 'ThemeBusy',
        name: 'ThemeBusy',
        parentRelationshipIds: [ 'manchester' ],
        childrenRelationshIds: [] } ]


text:
class LineItem < ActiveRecord::Base
  belongs_to :ticket
  belongs_to :cart
  belongs_to :payment

  validates :quantity, :seat_no, presence: true

  def total_price_after_discount
    discount = Discount.where ticket_id: ticket.id
    if !discount.nil?
      discount = discount.pluck(:code)
      if discount.include?(self[:code])
        percentage = Discount.find_by(code: self[:code])
        initial_amount = (ticket.price).to_f
        discounted_total = initial_amount * (percentage.discount_percentage.to_f / 100)
        initial_amount - discounted_total
      else
        ticket.price
      end
    else
      ticket.price
    end
  end

  def total_seats
    (ticket.min_seat_no.to_i..ticket.max_seat_no.to_i).to_a
  end

  def remaining_seats_by_quantity
    line_items = LineItem.where(ticket_id: ticket_id)
    total_taken_seat = line_items.collect { |li| li.valid? ? (li.quantity) : 0 }.sum
    ticket.quantity.to_i - total_taken_seat.to_i
  end

  # for ticket * quantity
  def ticket_quantity
    line_items = LineItem.where(ticket_id: ticket_id)
    total_taken_seat = line_items.collect { |li| li.valid? ? (li.quantity) : 0 }.sum
  end

  def all_taken_seat
    line_items = LineItem.where(ticket_id: ticket_id)
    line_items.pluck(:seat_no)
  end

  def booking_quantity_cannot_be_greater_than_total_quantity
  	if self.quantity.to_i > ticket.quantity.to_i
      errors.add(:quantity, "can't be greater than total quantity")
    end
  end

  def discount_percentage
    Discount.find_by(code: self[:code]).discount_percentage
  end

  def promo_code
    Discount.where(ticket_id: ticket.id).pluck(:code)
  end

  # def receipt
  #   Receipts::Receipt.new(
  #     id: payment_id,
  #     product: "Tickets",
  #     company: {
  #       name: "Diversecity",
  #       address: "Jalan Damansara 10, Malaysia",
  #       email: "admin@diversecity",
  #       logo: Rails.root.join("app/assets/images/diversecity.png")
  #     },
  #     line_items: [
  #       # ["Date",           line.created_at.strftime("%e %b %Y %H:%M:%S%p")],
  #       # ["Account Billed", "#{payment.user.name} (#{payment.user.email})"],
  #       ["Buyer Name", User.find(self.user_id).name],
  #       ["Event", self.ticket.event.name],
  #       ["Tickets Quantity", self.quantity],
  #       ["Seat No", self.seat_no],
  #       ["Transaction ID", self.uid]
  #     ]
  #   )
  # end
end


text:
date: 2014-05-27 15:22
title: Affiliate Links with Alfred
permalink: /post/2014-05-27-affilliate-links-with-alfred
categories: business
layout: post
share: true
---

When I released [avTag](http://avtag.it) I also signed up to Apple's iTunes Affiliate Program ([US Link](http://www.apple.com/itunes/affiliates/) | [UK Link](http://www.apple.com/uk/itunes/affiliates/)). It's a simple way to earn money when people buy iTunes items (music, films, iBooks, apps, etc.) via links you have supplied. After signing up all you need to do is append your affiliate program token to the end of an item's URL. [David Smith](http://twitter.com/_DavidSmith) has [a more detailed write-up](http://david-smith.org/blog/2013/08/19/itunes-affiliate-linking/) which is worth reading.

The Affiliate Program gives you access to tools for creating links with your token appended but if like me you tend to pick up links from Twitter or from within the iTunes Store or App Stores themselves you might find my [Alfred](http://www.alfredapp.com) workflow handy.

When you trigger it (I have it set to 'ita' for 'iTunes Affiliate') it parses the contents of the clipboard (ideally an iTunes or App Store URL) and appends your affiliate token to the end. Optionally you can add a campaign name such as 'blog' or 'twitter' and that too gets added.

If you must, customise it by editing the AppleScript and enter your own affiliate ID at the top. I don't mind if you leave mine in-place however!

[Download the Alfred workflow](https://www.swwritings.com/images/Append_iTunes_Affiliate_Token.zip)

---

Update: [Joe Workman](http://joeworkman.net) pointed me towards [Affiliate](https://itunes.apple.com/gb/app/affiliate/id789724698?mt=12&at=10lGfq) which does the same thing but for more services.


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bull. Torrey bot. Club 30(8): 429 (1903)

#### Original name
Polyporus caeruleoporus Peck

### Remarks
null


text:
require File.dirname(__FILE__) + '/../spec_helper'

describe "truncate_words" do
  include ActionView::Helpers::TextHelper

  it "should not truncate short contents" do
    truncate_words("hello", :length => 10, :omission => "...").should == "hello"
  end

  it "should return the omission string if the length is less than the first full word plus the omission string" do
    truncate_words("hello there", :length => 7, :omission => "...").should == "..."
  end

  it "should truncate the text to less than or equal to the given length" do
    text = "Returns the KC normalization of the string by default. NFKC is considered the best normalization form for passing strings to databases and validations."
    result = "Returns the KC normalization of the string by..."
    truncate_words(text, :length => 50, :omission => "...").length.should <= 50
  end

  it "should not truncate the text if the text is shorter than the the given length" do
    truncate_words("hello there", :length => 11, :omission => "...").should == "hello there"
  end

  it "should to the last full word within the given length plus the omission length" do
    truncate_words("hello there", :length => 9, :omission => "...").should == "hello..."
  end

  it "should truncate long contents" do
    text = "Returns the KC normalization of the string by default. NFKC is considered the best normalization form for passing strings to databases and validations."
    result = "Returns the KC normalization of the string by..."
    truncate_words(text, :length => 50, :omission => "...").should == result
  end

  it "should truncate multibyte contents" do
    truncate_words("ɦɛĺłø ŵőřļđ".mb_chars, :length => 9, :omission => "...").should == "ɦɛĺłø..."
  end
end


text:
package bitcoind

import (
	"github.com/OpenBazaar/spvwallet"
	"github.com/btcsuite/btcd/chaincfg/chainhash"
	"github.com/btcsuite/btcrpcclient"
	"io/ioutil"
	"net/http"
)

type NotificationListener struct {
	client    *btcrpcclient.Client
	listeners []func(spvwallet.TransactionCallback)
}

func (l *NotificationListener) notify(w http.ResponseWriter, r *http.Request) {
	b, err := ioutil.ReadAll(r.Body)
	if err != nil {
		return
	}
	txid := string(b)
	hash, err := chainhash.NewHashFromStr(txid)
	if err != nil {
		return
	}
	tx, err := l.client.GetRawTransaction(hash)
	if err != nil {
		return
	}
	var outputs []spvwallet.TransactionOutput
	for i, txout := range tx.MsgTx().TxOut {
		out := spvwallet.TransactionOutput{ScriptPubKey: txout.PkScript, Value: txout.Value, Index: uint32(i)}
		outputs = append(outputs, out)
	}
	var inputs []spvwallet.TransactionInput
	for _, txin := range tx.MsgTx().TxIn {
		in := spvwallet.TransactionInput{OutpointHash: txin.PreviousOutPoint.Hash.CloneBytes(), OutpointIndex: txin.PreviousOutPoint.Index}
		prev, err := l.client.GetRawTransaction(&txin.PreviousOutPoint.Hash)
		if err != nil {
			inputs = append(inputs, in)
			continue
		}
		in.LinkedScriptPubKey = prev.MsgTx().TxOut[txin.PreviousOutPoint.Index].PkScript
		in.Value = prev.MsgTx().TxOut[txin.PreviousOutPoint.Index].Value
		inputs = append(inputs, in)
	}
	cb := spvwallet.TransactionCallback{Txid: tx.Hash().CloneBytes(), Inputs: inputs, Outputs: outputs}
	for _, lis := range l.listeners {
		lis(cb)
	}
}

func startNotificationListener(client *btcrpcclient.Client, listeners []func(spvwallet.TransactionCallback)) {
	l := NotificationListener{
		client:    client,
		listeners: listeners,
	}
	http.HandleFunc("/", l.notify)
	http.ListenAndServe(":8330", nil)
}


text:
package com.jpattern.ioc.xml.typebuilder;

/**
 *
 * @author Francesco Cina'
 *
 * 19/dic/2009
 */
public class Primitive_char_Builder extends ATypeBuilder {

	private static final long serialVersionUID = 1L;

	public Primitive_char_Builder() {
		this(new NullTypeBuilder());
	}

	public Primitive_char_Builder(ITypeBuilder aSuccessor) {
		super(aSuccessor);
	}

	protected ResultType result(String typeName, String value) {
		ResultType type = new ResultType();
		if ( PRIMITIVE_CHAR.equals( typeName ) ) {
			try {
				type.setInstance( Character.valueOf( value.charAt(0) ) );
			}
			catch (Exception e) {
				type.setInstance( Character.valueOf('a') );
			}
			type.setClassOfInstance( char.class );
			type.setValid(true);

		}

		return type;

	}

}


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

namespace Alfred.IO
{
    public class ConsoleTable
    {
        public IList<object> Columns { get; set; }
        public IList<object[]> Rows { get; protected set; }

        public ConsoleTableOptions Options { get; protected set; }

        public ConsoleTable(params string[] columns)
            : this(new ConsoleTableOptions { Columns = new List<string>(columns) })
        {
        }

        public ConsoleTable(ConsoleTableOptions options)
        {
            Options = options ?? throw new ArgumentNullException("options");
            Rows = new List<object[]>();
            Columns = new List<object>(options.Columns);
        }

        public ConsoleTable AddColumn(IEnumerable<string> names)
        {
            foreach (var name in names)
                Columns.Add(name);
            return this;
        }

        public ConsoleTable AddRow(params object[] values)
        {
            if (values == null)
                throw new ArgumentNullException(nameof(values));

            if (!Columns.Any())
                throw new Exception("Please set the columns first");

            if (Columns.Count != values.Length)
                throw new Exception(
                    $"The number columns in the row ({Columns.Count}) does not match the values ({values.Length}");

            Rows.Add(values);
            return this;
        }

        public static ConsoleTable From<T>(IEnumerable<T> values)
        {
            var table = new ConsoleTable();

            var columns = GetColumns<T>();

            table.AddColumn(columns);

            foreach (var propertyValues in values.Select(value => columns.Select(column => GetColumnValue<T>(value, column))))
                table.AddRow(propertyValues.ToArray());

            return table;
        }

        public override string ToString()
        {
            var builder = new StringBuilder();

            // find the longest column by searching each row
            var columnLengths = ColumnLengths();

            // create the string format with padding
            var format = Enumerable.Range(0, Columns.Count)
                .Select(i => " | {" + i + ",-" + columnLengths[i] + "}")
                .Aggregate((s, a) => s + a) + " |";

            // find the longest formatted line
            var maxRowLength = Math.Max(0, Rows.Any() ? Rows.Max(row => string.Format(format, row).Length) : 0);
            var columnHeaders = string.Format(format, Columns.ToArray());

            // longest line is greater of formatted columnHeader and longest row
            var longestLine = Math.Max(maxRowLength, columnHeaders.Length);

            // add each row
            var results = Rows.Select(row => string.Format(format, row)).ToList();

            // create the divider
            var divider = " " + string.Join("", Enumerable.Repeat("-", longestLine - 1)) + " ";

            builder.AppendLine(divider);
            builder.AppendLine(columnHeaders);

            foreach (var row in results)
            {
                builder.AppendLine(divider);
                builder.AppendLine(row);
            }

            builder.AppendLine(divider);

            if (Options.EnableCount)
            {
                builder.AppendLine("");
                builder.AppendFormat(" Count: {0}", Rows.Count);
            }

            return builder.ToString();
        }

        public string ToMarkDownString()
        {
            return ToMarkDownString('|');
        }

        private string ToMarkDownString(char delimiter)
        {
            var builder = new StringBuilder();

            // find the longest column by searching each row
            var columnLengths = ColumnLengths();

            // create the string format with padding
            var format = Format(columnLengths, delimiter);

            // find the longest formatted line
            var columnHeaders = string.Format(format, Columns.ToArray());

            // add each row
            var results = Rows.Select(row => string.Format(format, row)).ToList();

            // create the divider
            var divider = Regex.Replace(columnHeaders, @"[^|]", "-");

            builder.AppendLine(columnHeaders);
            builder.AppendLine(divider);
            results.ForEach(row => builder.AppendLine(row));

            return builder.ToString();
        }

        public string ToMinimalString()
        {
            return ToMarkDownString(char.MinValue);
        }

        public string ToStringAlternative()
        {
            var builder = new StringBuilder();

            // find the longest column by searching each row
            var columnLengths = ColumnLengths();

            // create the string format with padding
            var format = Format(columnLengths);

            // find the longest formatted line
            var columnHeaders = string.Format(format, Columns.ToArray());

            // add each row
            var results = Rows.Select(row => string.Format(format, row)).ToList();

            // create the divider
            var divider = Regex.Replace(columnHeaders, @"[^|]", "-");
            var dividerPlus = divider.Replace("|", "+");

            builder.AppendLine(dividerPlus);
            builder.AppendLine(columnHeaders);

            foreach (var row in results)
            {
                builder.AppendLine(dividerPlus);
                builder.AppendLine(row);
            }
            builder.AppendLine(dividerPlus);

            return builder.ToString();
        }

        private string Format(List<int> columnLengths, char delimiter = '|')
        {
            var delimiterStr = delimiter == char.MinValue ? string.Empty : delimiter.ToString();
            var format = (Enumerable.Range(0, Columns.Count)
                .Select(i => " " + delimiterStr + " {" + i + ",-" + columnLengths[i] + "}")
                .Aggregate((s, a) => s + a) + " " + delimiterStr).Trim();
            return format;
        }

        private List<int> ColumnLengths()
        {
            var columnLengths = Columns
                .Select((t, i) => Rows.Select(x => x[i])
                    .Union(Columns)
                    .Where(x => x != null)
                    .Select(x => x.ToString().Length).Max())
                .ToList();
            return columnLengths;
        }

        public void Write(Format format = IO.Format.Default)
        {
            switch (format)
            {
                case IO.Format.Default:
                    Console.WriteLine(ToString());
                    break;
                case IO.Format.MarkDown:
                    Console.WriteLine(ToMarkDownString());
                    break;
                case IO.Format.Alternative:
                    Console.WriteLine(ToStringAlternative());
                    break;
                case IO.Format.Minimal:
                    Console.WriteLine(ToMinimalString());
                    break;
                default:
                    throw new ArgumentOutOfRangeException(nameof(format), format, null);
            }
        }

        private static IEnumerable<string> GetColumns<T>()
        {
            return typeof(T).GetProperties().Select(x => x.Name).ToArray();
        }

        private static object GetColumnValue<T>(object target, string column)
        {
            return typeof(T).GetProperty(column).GetValue(target, null);
        }
    }

    public class ConsoleTableOptions
    {
        public IEnumerable<string> Columns { get; set; } = new List<string>();
        public bool EnableCount { get; set; } = true;
    }

    public enum Format
    {
        Default = 0,
        MarkDown = 1,
        Alternative = 2,
        Minimal = 3
    }
}


text:
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: `ci_template`
--

--
-- Dumping data for table `settings`
--

INSERT INTO `settings` (`setting_id`, `setting_name`, `setting_var`) VALUES
(1, 'CI Template', 'site_name'),
(2, 'upload', 'file_upload_path'),
(3, 'ci_template', 'base_dir'),
(4, 'assets', 'asset_path');

--
-- Dumping data for table `template`
--

INSERT INTO `template` (`template_id`, `template_name`, `selected`) VALUES
(1, 'default', 1);

--
-- Dumping data for table `template_settings`
--

INSERT INTO `template_settings` (`setting_id`, `template_id`, `setting_name`, `setting_var`) VALUES
(5, 1, 'default', 'theme_name'),
(6, 1, 'index.html', 'theme_default_filename');

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;


text:
<%= title %>'s Hubpolio!

      Always a pleasure scaffolding your apps.

Splendid!

              {{portfolio.title}}

{{ portfolio.updated_at }}

{{portfolio.description}}

{{portfolio.url}}

powered by hubpolio © copyleft 2015


text:
layout: section
title: "Beam Calcite SQL query syntax"
section_menu: section-menu/sdks.html
permalink: /documentation/dsls/sql/calcite/query-syntax/
redirect_from: /documentation/dsls/sql/statements/select/
               /documentation/dsls/sql/select/
---
<!--
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->

# Beam Calcite SQL query syntax

Query statements scan one or more tables or expressions and return the computed
result rows.

Generally, the semantics of queries is standard. See the following
sections to learn about extensions for supporting Beam's unified
batch/streaming model:

 - [Joins]({{ site.baseurl}}/documentation/dsls/sql/extensions/joins)
 - [Windowing & Triggering]({{ site.baseurl}}/documentation/dsls/sql/windowing-and-triggering/)

The main functionality of Beam SQL is the `SELECT` statement. This is how you
query and join data. The operations supported are a subset of
[Apache Calcite SQL](http://calcite.apache.org/docs/reference.html#grammar).

## SQL Syntax

    query_statement:
        [ WITH with_query_name AS ( query_expr ) [, ...] ]
        query_expr

    query_expr:
        { select | ( query_expr ) | query_expr set_op query_expr }
        [ LIMIT count [ OFFSET skip_rows ] ]

    select:
        SELECT  [{ ALL | DISTINCT }]
            { [ expression. ]* [ EXCEPT ( column_name [, ...] ) ]
                [ REPLACE ( expression [ AS ] column_name [, ...] ) ]
            | expression [ [ AS ] alias ] } [, ...]
        [ FROM from_item  [, ...] ]
        [ WHERE bool_expression ]
        [ GROUP BY { expression [, ...] | ROLLUP ( expression [, ...] ) } ]
        [ HAVING bool_expression ]

    set_op:
        UNION { ALL | DISTINCT } | INTERSECT DISTINCT | EXCEPT DISTINCT

    from_item: {
        table_name [ [ AS ] alias ] |
        join |
        ( query_expr ) [ [ AS ] alias ]
        with_query_name [ [ AS ] alias ]
    }

    join:
        from_item [ join_type ] JOIN from_item
        [ { ON bool_expression | USING ( join_column [, ...] ) } ]

    join_type:
        { INNER | CROSS | FULL [OUTER] | LEFT [OUTER] | RIGHT [OUTER] }

Notation:

-   Square brackets "\[ \]" indicate optional clauses.
-   Parentheses "( )" indicate literal parentheses.
-   The vertical bar "|" indicates a logical OR.
-   Curly braces "{ }" enclose a set of options.
-   A comma followed by an ellipsis within square brackets "\[, ... \]"
    indicates that the preceding item can repeat in a comma-separated list.

## SELECT list

Syntax:

    SELECT  [{ ALL | DISTINCT }]
        { [ expression. ]*
        | expression [ [ AS ] alias ] } [, ...]

The `SELECT` list defines the columns that the query will return. Expressions in
the `SELECT` list can refer to columns in any of the `from_item`s in its
corresponding `FROM` clause.

Each item in the `SELECT` list is one of:

-   \*
-   `expression`
-   `expression.*`

### SELECT \*

`SELECT *`, often referred to as *select star*, produces one output column for
each column that is visible after executing the full query.

```
SELECT * FROM (SELECT 'apple' AS fruit, 'carrot' AS vegetable);

+-------+-----------+
| fruit | vegetable |
+-------+-----------+
| apple | carrot    |
+-------+-----------+
```

### SELECT `expression`

Items in a `SELECT` list can be expressions. These expressions evaluate to a
single value and produce one output column, with an optional explicit `alias`.

If the expression does not have an explicit alias, it receives an implicit alias
according to the rules for [implicit aliases](#implicit-aliases), if possible.
Otherwise, the column is anonymous and you cannot refer to it by name elsewhere
in the query.

### SELECT `expression.*` {#select-expression_1}

An item in a `SELECT` list can also take the form of `expression.*`. This
produces one output column for each column or top-level field of `expression`.
The expression must be a table alias.

The following query produces one output column for each column in the table
`groceries`, aliased as `g`.

```
WITH groceries AS
  (SELECT 'milk' AS dairy,
   'eggs' AS protein,
   'bread' AS grain)
SELECT g.*
FROM groceries AS g;

+-------+---------+-------+
| dairy | protein | grain |
+-------+---------+-------+
| milk  | eggs    | bread |
+-------+---------+-------+
```

### SELECT modifiers

You can modify the results returned from a `SELECT` query, as follows.

#### SELECT DISTINCT

A `SELECT DISTINCT` statement discards duplicate rows and returns only the
remaining rows. `SELECT DISTINCT` cannot return columns of the following types:

-   STRUCT
-   ARRAY

#### SELECT ALL

A `SELECT ALL` statement returns all rows, including duplicate rows. `SELECT
ALL` is the default behavior of `SELECT`.

### Aliases

See [Aliases](#aliases_2) for information on syntax and visibility for
`SELECT` list aliases.

## FROM clause

The `FROM` clause indicates the table or tables from which to retrieve rows, and
specifies how to join those rows together to produce a single stream of rows for
processing in the rest of the query.

### Syntax

    from_item: {
        table_name [ [ AS ] alias ] |
        join |
        ( query_expr ) [ [ AS ] alias ] |
        with_query_name [ [ AS ] alias ]
    }

#### table\_name

The name (optionally qualified) of an existing table.

    SELECT * FROM Roster;
    SELECT * FROM beam.Roster;

#### join

See [JOIN Types](#join-types) below and [Joins]({{ site.baseurl}}/documentation/dsls/sql/extensions/joins).

#### select {#select_1}

`( select ) [ [ AS ] alias ]` is a table [subquery](#subqueries).

#### with\_query\_name

The query names in a `WITH` clause (see [WITH Clause](#with-clause)) act like
names of temporary tables that you can reference anywhere in the `FROM` clause.
In the example below, `subQ1` and `subQ2` are `with_query_names`.

Example:

    WITH
      subQ1 AS (SELECT * FROM Roster WHERE SchoolID = 52),
      subQ2 AS (SELECT SchoolID FROM subQ1)
    SELECT DISTINCT * FROM subQ2;

The `WITH` clause hides any permanent tables with the same name for the duration
of the query, unless you qualify the table name, e.g. `beam.Roster`.

### Subqueries

A subquery is a query that appears inside another statement, and is written
inside parentheses. These are also referred to as "sub-SELECTs" or "nested
SELECTs". The full `SELECT` syntax is valid in subqueries.

There are two types of subquery:

-   Expression Subqueries
    which you can use in a query wherever expressions are valid. Expression
    subqueries return a single value.
-   Table subqueries, which you can use only in a `FROM` clause. The outer query
    treats the result of the subquery as a table.

Note that there must be parentheses around both types of subqueries.

Example:

```
SELECT AVG ( PointsScored )
FROM
( SELECT PointsScored
  FROM Stats
  WHERE SchoolID = 77 )
```

Optionally, a table subquery can have an alias.

Example:

```
SELECT r.LastName
FROM
( SELECT * FROM Roster) AS r;
```

### Aliases {#aliases_1}

See [Aliases](#aliases_2) for information on syntax and visibility for
`FROM` clause aliases.

## JOIN types

Also see [Joins]({{ site.baseurl}}/documentation/dsls/sql/extensions/joins).

### Syntax {#syntax_1}

    join:
        from_item [ join_type ] JOIN from_item
        [ ON bool_expression | USING ( join_column [, ...] ) ]

    join_type:
        { INNER | CROSS | FULL [OUTER] | LEFT [OUTER] | RIGHT [OUTER] }

The `JOIN` clause merges two `from_item`s so that the `SELECT` clause can query
them as one source. The `join_type` and `ON` or `USING` clause (a "join
condition") specify how to combine and discard rows from the two `from_item`s to
form a single source.

All `JOIN` clauses require a `join_type`.

A `JOIN` clause requires a join condition unless one of the following conditions
is true:

-   `join_type` is `CROSS`.
-   One or both of the `from_item`s is not a table, e.g. an `array_path` or
    `field_path`.

### \[INNER\] JOIN

An `INNER JOIN`, or simply `JOIN`, effectively calculates the Cartesian product
of the two `from_item`s and discards all rows that do not meet the join
condition. "Effectively" means that it is possible to implement an `INNER JOIN`
without actually calculating the Cartesian product.

### CROSS JOIN

`CROSS JOIN` is generally not yet supported.

### FULL \[OUTER\] JOIN

A `FULL OUTER JOIN` (or simply `FULL JOIN`) returns all fields for all rows in
both `from_item`s that meet the join condition.

`FULL` indicates that *all rows* from both `from_item`s are returned, even if
they do not meet the join condition. For streaming jobs, all rows that are
not late according to default trigger and belonging to the same window
if there's non-global window applied.

`OUTER` indicates that if a given row from one `from_item` does not join to any
row in the other `from_item`, the row will return with NULLs for all columns
from the other `from_item`.

Also see [Joins]({{ site.baseurl}}/documentation/dsls/sql/extensions/joins).

### LEFT \[OUTER\] JOIN

The result of a `LEFT OUTER JOIN` (or simply `LEFT JOIN`) for two `from_item`s
always retains all rows of the left `from_item` in the `JOIN` clause, even if no
rows in the right `from_item` satisfy the join predicate.

`LEFT` indicates that all rows from the *left* `from_item` are returned; if a
given row from the left `from_item` does not join to any row in the *right*
`from_item`, the row will return with NULLs for all columns from the right
`from_item`. Rows from the right `from_item` that do not join to any row in the
left `from_item` are discarded.

### RIGHT \[OUTER\] JOIN

The result of a `RIGHT OUTER JOIN` (or simply `RIGHT JOIN`) is similar and
symmetric to that of `LEFT OUTER JOIN`.

### ON clause

The `ON` clause contains a `bool_expression`. A combined row (the result of
joining two rows) meets the join condition if `bool_expression` returns TRUE.

Example:

```
SELECT * FROM Roster INNER JOIN PlayerStats
ON Roster.LastName = PlayerStats.LastName;
```

### USING clause

The `USING` clause requires a `column_list` of one or more columns which occur
in both input tables. It performs an equality comparison on that column, and the
rows meet the join condition if the equality comparison returns TRUE.

In most cases, a statement with the `USING` keyword is equivalent to using the
`ON` keyword. For example, the statement:

```
SELECT FirstName
FROM Roster INNER JOIN PlayerStats
USING (LastName);
```

is equivalent to:

```
SELECT FirstName
FROM Roster INNER JOIN PlayerStats
ON Roster.LastName = PlayerStats.LastName;
```

The results from queries with `USING` do differ from queries that use `ON` when
you use `SELECT *`. To illustrate this, consider the query:

```
SELECT * FROM Roster INNER JOIN PlayerStats
USING (LastName);
```

This statement returns the rows from `Roster` and `PlayerStats` where
`Roster.LastName` is the same as `PlayerStats.LastName`. The results include a
single `LastName` column.

By contrast, consider the following query:

```
SELECT * FROM Roster INNER JOIN PlayerStats
ON Roster.LastName = PlayerStats.LastName;
```

This statement returns the rows from `Roster` and `PlayerStats` where
`Roster.LastName` is the same as `PlayerStats.LastName`. The results include two
`LastName` columns; one from `Roster` and one from `PlayerStats`.

### Sequences of JOINs

The `FROM` clause can contain multiple `JOIN` clauses in sequence.

Example:

```
SELECT * FROM a LEFT JOIN b ON TRUE LEFT JOIN c ON TRUE;
```

where `a`, `b`, and `c` are any `from_item`s. JOINs are bound from left to
right, but you can insert parentheses to group them in a different order.

## WHERE clause

### Syntax {#syntax_2}

```
WHERE bool_expression
```

The `WHERE` clause filters out rows by evaluating each row against
`bool_expression`, and discards all rows that do not return TRUE (that is, rows
that return FALSE or NULL).

Example:

```
SELECT * FROM Roster
WHERE SchoolID = 52;
```

The `bool_expression` can contain multiple sub-conditions.

Example:

```
SELECT * FROM Roster
WHERE LastName LIKE 'Mc%' OR LastName LIKE 'Mac%';
```

You cannot reference column aliases from the `SELECT` list in the `WHERE`
clause.

Expressions in an `INNER JOIN` have an equivalent expression in the `WHERE`
clause. For example, a query using `INNER` `JOIN` and `ON` has an equivalent
expression using `CROSS JOIN` and `WHERE`.

Example - this query:

```
SELECT * FROM Roster INNER JOIN TeamMascot
ON Roster.SchoolID = TeamMascot.SchoolID;
```

is equivalent to:

```
SELECT * FROM Roster CROSS JOIN TeamMascot
WHERE Roster.SchoolID = TeamMascot.SchoolID;
```

## GROUP BY clause

Also see [Windowing & Triggering]({{ site.baseurl}}/documentation/dsls/sql/windowing-and-triggering/)

### Syntax {#syntax_3}

    GROUP BY { expression [, ...] | ROLLUP ( expression [, ...] ) }

The `GROUP BY` clause groups together rows in a table with non-distinct values
for the `expression` in the `GROUP BY` clause. For multiple rows in the source
table with non-distinct values for `expression`, the `GROUP BY` clause produces
a single combined row. `GROUP BY` is commonly used when aggregate functions are
present in the `SELECT` list, or to eliminate redundancy in the output.

Example:

```
SELECT SUM(PointsScored), LastName
FROM PlayerStats
GROUP BY LastName;
```

## HAVING clause

### Syntax {#syntax_4}

```
HAVING bool_expression
```

The `HAVING` clause is similar to the `WHERE` clause: it filters out rows that
do not return TRUE when they are evaluated against the `bool_expression`.

As with the `WHERE` clause, the `bool_expression` can be any expression that
returns a boolean, and can contain multiple sub-conditions.

The `HAVING` clause differs from the `WHERE` clause in that:

-   The `HAVING` clause requires `GROUP BY` or aggregation to be present in the
    query.
-   The `HAVING` clause occurs after `GROUP BY` and aggregation.
    This means that the `HAVING` clause is evaluated once for every
    aggregated row in the result set. This differs from the `WHERE` clause,
    which is evaluated before `GROUP BY` and aggregation.

The `HAVING` clause can reference columns available via the `FROM` clause, as
well as `SELECT` list aliases. Expressions referenced in the `HAVING` clause
must either appear in the `GROUP BY` clause or they must be the result of an
aggregate function:

```
SELECT LastName
FROM Roster
GROUP BY LastName
HAVING SUM(PointsScored) > 15;
```

## Set operators

### Syntax {#syntax_6}

    UNION { ALL | DISTINCT } | INTERSECT DISTINCT | EXCEPT DISTINCT

Set operators combine results from two or more input queries into a single
result set. You must specify `ALL` or `DISTINCT`; if you specify `ALL`, then all
rows are retained. If `DISTINCT` is specified, duplicate rows are discarded.

If a given row R appears exactly m times in the first input query and n times in
the second input query (m >= 0, n >= 0):

-   For `UNION ALL`, R appears exactly m + n times in the result.
-   For `UNION DISTINCT`, the `DISTINCT` is computed after the `UNION` is
    computed, so R appears exactly one time.
-   For `INTERSECT DISTINCT`, the `DISTINCT` is computed after the result above
    is computed.
-   For `EXCEPT DISTINCT`, row R appears once in the output if m > 0 and
    n = 0.
-   If there are more than two input queries, the above operations generalize
    and the output is the same as if the inputs were combined incrementally from
    left to right.

The following rules apply:

-   For set operations other than `UNION ALL`, all column types must support
    equality comparison.
-   The input queries on each side of the operator must return the same number
    of columns.
-   The operators pair the columns returned by each input query according to the
    columns' positions in their respective `SELECT` lists. That is, the first
    column in the first input query is paired with the first column in the
    second input query.
-   The result set always uses the column names from the first input query.
-   The result set always uses the supertypes of input types in corresponding
    columns, so paired columns must also have either the same data type or a
    common supertype.
-   You must use parentheses to separate different set operations; for this
    purpose, set operations such as `UNION ALL` and `UNION DISTINCT` are
    different. If the statement only repeats the same set operation, parentheses
    are not necessary.

Examples:

```
query1 UNION ALL (query2 UNION DISTINCT query3)
query1 UNION ALL query2 UNION ALL query3
```

Invalid:

    query1 UNION ALL query2 UNION DISTINCT query3
    query1 UNION ALL query2 INTERSECT ALL query3;  // INVALID.

### UNION

The `UNION` operator combines the result sets of two or more input queries by
pairing columns from the result set of each query and vertically concatenating
them.

### INTERSECT

The `INTERSECT` operator returns rows that are found in the result sets of both
the left and right input queries. Unlike `EXCEPT`, the positioning of the input
queries (to the left vs. right of the `INTERSECT` operator) does not matter.

### EXCEPT

The `EXCEPT` operator returns rows from the left input query that are not
present in the right input query.

## LIMIT clause and OFFSET clause

### Syntax {#syntax_7}

```
LIMIT count [ OFFSET skip_rows ]
```

`LIMIT` specifies a non-negative `count` of type INTEGER, and no more than `count`
rows will be returned. `LIMIT` `0` returns 0 rows. If there is a set operation,
`LIMIT` is applied after the set operation is evaluated.

`OFFSET` specifies a non-negative `skip_rows` of type INTEGER, and only rows from
that offset in the table will be considered.

These clauses accept only literal or parameter values.

The rows that are returned by `LIMIT` and `OFFSET` is unspecified.

## WITH clause

The `WITH` clause contains one or more named subqueries which execute every time
a subsequent `SELECT` statement references them. Any clause or subquery can
reference subqueries you define in the `WITH` clause. This includes any `SELECT`
statements on either side of a set operator, such as `UNION`.

Example:

```
WITH subQ1 AS (SELECT SchoolID FROM Roster),
     subQ2 AS (SELECT OpponentID FROM PlayerStats)
SELECT * FROM subQ1
UNION ALL
SELECT * FROM subQ2;
```

## Aliases {#aliases_2}

An alias is a temporary name given to a table, column, or expression present in
a query. You can introduce explicit aliases in the `SELECT` list or `FROM`
clause, or Beam will infer an implicit alias for some expressions.
Expressions with neither an explicit nor implicit alias are anonymous and the
query cannot reference them by name.

### Explicit alias syntax

You can introduce explicit aliases in either the `FROM` clause or the `SELECT`
list.

In a `FROM` clause, you can introduce explicit aliases for any item, including
tables, arrays, subqueries, and `UNNEST` clauses, using `[AS] alias`. The `AS`
keyword is optional.

Example:

```
SELECT s.FirstName, s2.SongName
FROM Singers AS s JOIN Songs AS s2 ON s.SingerID = s2.SingerID;
```

You can introduce explicit aliases for any expression in the `SELECT` list using
`[AS] alias`. The `AS` keyword is optional.

Example:

```
SELECT s.FirstName AS name, LOWER(s.FirstName) AS lname
FROM Singers s;
```

### Explicit alias visibility

After you introduce an explicit alias in a query, there are restrictions on
where else in the query you can reference that alias. These restrictions on
alias visibility are the result of Beam's name scoping rules.

#### FROM clause aliases

Beam processes aliases in a `FROM` clause from left to right, and aliases
are visible only to subsequent `JOIN` clauses.

### Ambiguous aliases

Beam provides an error if a name is ambiguous, meaning it can resolve to
more than one unique object.

Examples:

This query contains column names that conflict between tables, since both
`Singers` and `Songs` have a column named `SingerID`:

```
SELECT SingerID
FROM Singers, Songs;
```

### Implicit aliases

In the `SELECT` list, if there is an expression that does not have an explicit
alias, Beam assigns an implicit alias according to the following rules.
There can be multiple columns with the same alias in the `SELECT` list.

-   For identifiers, the alias is the identifier. For example, `SELECT abc`
    implies `AS abc`.
-   For path expressions, the alias is the last identifier in the path. For
    example, `SELECT abc.def.ghi` implies `AS ghi`.
-   For field access using the "dot" member field access operator, the alias is
    the field name. For example, `SELECT (struct_function()).fname` implies `AS
    fname`.

In all other cases, there is no implicit alias, so the column is anonymous and
cannot be referenced by name. The data from that column will still be returned
and the displayed query results may have a generated label for that column, but
the label cannot be used like an alias.

In a `FROM` clause, `from_item`s are not required to have an alias. The
following rules apply:

If there is an expression that does not have an explicit alias, Beam assigns
an implicit alias in these cases:

-   For identifiers, the alias is the identifier. For example, `FROM abc`
    implies `AS abc`.
-   For path expressions, the alias is the last identifier in the path. For
    example, `FROM abc.def.ghi` implies `AS ghi`

Table subqueries do not have implicit aliases.

`FROM UNNEST(x)` does not have an implicit alias.

> Portions of this page are modifications based on
> [work](https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax)
> created and
> [shared by Google](https://developers.google.com/terms/site-policies)
> and used according to terms described in the [Creative Commons 3.0
> Attribution License](http://creativecommons.org/licenses/by/3.0/).


text:
/** BSegmentCRF.java
 * Created on Apr 14, 2005
 *
 * @author Sunita Sarawagi
 * @since 1.2
 * @version 1.3
 *
 * BSegmentCRF (A significantly faster version of Semi-CRFs that employs a compact feature representation)
 * for fast training and inference of semi-Markov models.
 */
package iitb.BSegmentCRF;

import gnu.trove.map.hash.TIntDoubleHashMap;
import iitb.CRF.DataSequence;
import iitb.CRF.SegmentCRF;
import iitb.CRF.Trainer;
import iitb.CRF.Viterbi;

import java.util.Properties;

public class BSegmentCRF extends SegmentCRF {
    /**
	 *
	 */
	private static final long serialVersionUID = 655531342585250258L;
	BFeatureGenerator bfgen;
    /**
     * @param numLabels
     * @param fgen
     * @param arg
     */
    public BSegmentCRF(int numLabels, BFeatureGenerator fgen, String arg) {
        super(numLabels, fgen, arg);
        bfgen = fgen;
    }
    /**
     * @param numLabels
     * @param fgen
     * @param configOptions
     */
    public BSegmentCRF(int numLabels, BFeatureGenerator fgen,
            Properties configOptions) {
        super(numLabels, fgen, configOptions);
        bfgen = fgen;
    }
    protected Trainer getTrainer() {
        Trainer thisTrainer = dynamicallyLoadedTrainer();
        if (thisTrainer != null)
            return thisTrainer;
        return new BSegmentTrainer(params);
    }

    public Viterbi getViterbi(int beamsize) {
        return params.miscOptions.getProperty("segmentViterbi", "false").equals("true")?
                super.getViterbi(beamsize):new BSegmentViterbi(this,numY,beamsize);
    }
    public double segmentMarginalProbabilities(DataSequence dataSequence, TIntDoubleHashMap segmentMarginals[][], TIntDoubleHashMap edgeMarginals[][][]) {
        System.err.println("Not yet implemented for this CRF--use SegmentCRF");
        System.exit(-1);
        return 0;
    }

}


text:
using Baskerville.Models.Constants;
using System;
using System.ComponentModel.DataAnnotations;

namespace Baskerville.Models.ViewModels
{
    public class EventViewModel
    {
        private DateTime? startDate;

        public int Id { get; set; }

        [Required(ErrorMessage = AdminMessages.RequiredFieldMessage)]
        [Display(Name = "Име (БГ)")]
        [StringLength(
            maximumLength: AdminMessages.MaxEventNameLegnth
            , MinimumLength = AdminMessages.MinEventNameLegnth
            , ErrorMessage = AdminMessages.NameLenghtMessage)]
        public string NameBg { get; set; }

        [Required(ErrorMessage = AdminMessages.RequiredFieldMessage)]
        [Display(Name = "Име (АНГ)")]
        [StringLength(
            maximumLength: AdminMessages.MaxEventNameLegnth
            , MinimumLength = AdminMessages.MinEventNameLegnth
            , ErrorMessage = AdminMessages.NameLenghtMessage)]
        public string NameEn { get; set; }

        [Required(ErrorMessage = AdminMessages.RequiredFieldMessage)]
        [Display(Name = "Описание (БГ)")]
        [StringLength(
            maximumLength: AdminMessages.MaxEventDescriptionLegnth
            , MinimumLength = AdminMessages.MinEventDescriptionLegnth
            , ErrorMessage = AdminMessages.DescriptionLenghtMessage)]
        public string DescriptionBg { get; set; }

        [Required(ErrorMessage = AdminMessages.RequiredFieldMessage)]
        [Display(Name = "Описание (АНГ)")]
        [StringLength(
            maximumLength: AdminMessages.MaxEventDescriptionLegnth
            , MinimumLength = AdminMessages.MinEventDescriptionLegnth
            , ErrorMessage = AdminMessages.DescriptionLenghtMessage)]
        public string DescriptionEn { get; set; }

        [Required(ErrorMessage = AdminMessages.RequiredFieldMessage)]
        [Display(Name = "Снимка (URL)")]
        public string ImageUrl { get; set; }

        [Required(ErrorMessage = AdminMessages.RequiredFieldMessage)]
        [Display(Name = "Начало")]
        public DateTime StartDate
        {
            get { return this.startDate ?? DateTime.Now; }
            set { this.startDate = value; }
        }

        [Display(Name = "Публично")]
        public bool IsPublic { get; set; }
    }
}


text:
<!DOCTYPE html>

    <title>Reisa's World</title>
    <link rel="stylesheet" type="text/css" href="./bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="./Includes/style.css">
    <link href="./slider/jquery.bxslider.css" rel="stylesheet" />

ABOUT

PROJECTS

CONTACT

Reisa Sitohang |

About

                        Born and raised in Amsterdam with Indonesian roots.

I love the world so I am trying to find a balance between materialism and tree huggerism that works for me.

I also love animals, so I don't eat them.

 I'm an aspiring web developer currently following a full stack web-development course at NYCDA.

I'm still a noob at building websites, but stay tuned for future projects!

-Reisa Sitohang

Short dance project

More

Coming

Soon

reisasitohang@gmail.com


text:
<?php
/* @var $this subjectController */
/* @var $model Infosubject */

$this->breadcrumbs=array(
	'Info Categories'=>array('index'),
	'Create',
);

$this->menu=array(
	array('label'=>'List Infosubject', 'url'=>array('index')),
	array('label'=>'Manage Infosubject', 'url'=>array('admin')),
);
?>

Create Infosubject

		<?php $this->renderPartial('_form', array('model'=>$model)); ?>


text:
package guard

import (
	"testing"

	"gopkg.in/workanator/go-floc.v2"
)

func TestComplete(t *testing.T) {
	const tpl = "completed"

	flow := Complete(tpl)

	result, data, err := floc.Run(flow)
	if !result.IsCompleted() {
		t.Fatalf("%s expects result to be Completed but has %s", t.Name(), result.String())
	} else if data == nil {
		t.Fatalf("%s expects data to be not nil", t.Name())
	} else if s, ok := data.(string); !ok {
		t.Fatalf("%s expects data to be of type string but has %T", t.Name(), data)
	} else if s != tpl {
		t.Fatalf("%s expects data to be %s but has %s", t.Name(), tpl, s)
	} else if err != nil {
		t.Fatalf("%s expects error to be nil but has %v", t.Name(), err)
	}
}


text:
cd $WORKDIR

## create log
echo "#######################"                                     >  $LOG
echo "# OBD2 data collector #"                                     >> $LOG
echo "#######################"                                     >> $LOG

## change into working directory
echo "[`date`] Changed already into working directory. ("$WORKDIR")" >> $LOG

## check for usb mount
#echo "[`date`] Checking for USB stick availablility"                 >> $LOG
#while [ ! -e $USBSTICK ]
#do
#    echo "[`date`]  [ERROR] USB Stick not found... ($USBSTICK)"
#    echo "[`date`]  [ERROR] USB Stick not found... ($USBSTICK)"      >> $LOG
#    python obd2collector/display.py "E: USB missing."
#    sleep 3
#done

if [ ! -d data ] ; then
    echo "[`date`]  [WARNING] data directory not found."             >> $LOG
    mkdir data                                                       >> $LOG
fi

STICKMOUNTED=`cat /etc/mtab | grep $USBSTICK | wc -l`
if [ $STICKMOUNTED -ne 1 ] ; then
    echo "[`date`] Mounting USB stick ($WORKDIR/data)"               >> $LOG
    mount $USBSTICK $WORKDIR/data                                    >> $LOG 2>> $LOG
fi

# restarting bluetooth
echo "[`date`] Restarting Bluetooth"                                 >> $LOG 2>> $LOG
/etc/init.d/bluetooth restart

## check for adapter
#echo "[`date`] Looking for CAN adapter"                              >> $LOG
#while [ ! -e $CANADAPTER ]
#do
#    echo "[`date`]  [ERROR] CAN adapter not found... ($CANADAPTER)"
#    echo "[`date`]  [ERROR] CAN adapter not found... ($CANADAPTER)"  >> $LOG
#    python obd2collector/display.py "E: CAN missing."
#    sleep 3
#done

# create directory
echo "[`date`] Creating data directory"                              >> $LOG 2>> $LOG
mkdir -p $DATADIR

# call collector
echo "[`date`] Starting data collection"                             >> $LOG
python obd2collector/display.py "Running..."
python -u obd2collector $DATADIR                                     >> $LOG 2>> $LOG

## change back into starting directory
echo "[`date`] Done."                                                >> $LOG


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

<title>Using as: RL78-Modifiers</title>

<meta name="description" content="Using as: RL78-Modifiers">
<meta name="keywords" content="Using as: RL78-Modifiers">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="makeinfo">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="index.html#Top" rel="start" title="Top">
<link href="AS-Index.html#AS-Index" rel="index" title="AS Index">
<link href="index.html#SEC_Contents" rel="contents" title="Table of Contents">
<link href="RL78_002dDependent.html#RL78_002dDependent" rel="up" title="RL78-Dependent">
<link href="RL78_002dDirectives.html#RL78_002dDirectives" rel="next" title="RL78-Directives">
<link href="RL78_002dOpts.html#RL78_002dOpts" rel="prev" title="RL78-Opts">

Next: RL78-Directives, Previous: RL78-Opts, Up: RL78-Dependent   [Contents][Index]

9.36.2 Symbolic Operand Modifiers

The RL78 has three modifiers that adjust the relocations used by the
linker:

%lo16()

When loading a 20-bit (or wider) address into registers, this modifier
selects the 16 least significant bits.

  movw ax,#%lo16(_sym)

%hi16()

When loading a 20-bit (or wider) address into registers, this modifier
selects the 16 most significant bits.

  movw ax,#%hi16(_sym)

%hi8()

When loading a 20-bit (or wider) address into registers, this modifier
selects the 8 bits that would go into CS or ES (i.e. bits 23..16).

  mov es, #%hi8(_sym)


text: © 2017 All Rights Reserved


text:
<?php

/**
 * The "sinks" collection of methods.
 * Typical usage is:
 *  <code>
 *   $loggingService = new Google_Service_Logging(...);
 *   $sinks = $loggingService->sinks;
 *  </code>
 */
class Google_Service_Logging_Resource_ProjectsSinks extends Google_Service_Resource
{
  /**
   * Creates a sink. (sinks.create)
   *
   * @param string $projectName The resource name of the project in which to
   * create the sink. Example: `"projects/my-project-id"`. The new sink must be
   * provided in the request.
   * @param Google_Service_Logging_LogSink $postBody
   * @param array $optParams Optional parameters.
   * @return Google_Service_Logging_LogSink
   */
  public function create($projectName, Google_Service_Logging_LogSink $postBody, $optParams = array())
  {
    $params = array('projectName' => $projectName, 'postBody' => $postBody);
    $params = array_merge($params, $optParams);
    return $this->call('create', array($params), "Google_Service_Logging_LogSink");
  }
  /**
   * Deletes a sink. (sinks.delete)
   *
   * @param string $sinkName The resource name of the sink to delete. Example:
   * `"projects/my-project-id/sinks/my-sink-id"`.
   * @param array $optParams Optional parameters.
   * @return Google_Service_Logging_LoggingEmpty
   */
  public function delete($sinkName, $optParams = array())
  {
    $params = array('sinkName' => $sinkName);
    $params = array_merge($params, $optParams);
    return $this->call('delete', array($params), "Google_Service_Logging_LoggingEmpty");
  }
  /**
   * Gets a sink. (sinks.get)
   *
   * @param string $sinkName The resource name of the sink to return. Example:
   * `"projects/my-project-id/sinks/my-sink-id"`.
   * @param array $optParams Optional parameters.
   * @return Google_Service_Logging_LogSink
   */
  public function get($sinkName, $optParams = array())
  {
    $params = array('sinkName' => $sinkName);
    $params = array_merge($params, $optParams);
    return $this->call('get', array($params), "Google_Service_Logging_LogSink");
  }
  /**
   * Lists sinks. (sinks.listProjectsSinks)
   *
   * @param string $projectName Required. The resource name of the project
   * containing the sinks. Example: `"projects/my-logging-project"`.
   * @param array $optParams Optional parameters.
   *
   * @opt_param string pageToken Optional. If the `pageToken` parameter is
   * supplied, then the next page of results is retrieved. The `pageToken`
   * parameter must be set to the value of the `nextPageToken` from the previous
   * response. The value of `projectName` must be the same as in the previous
   * request.
   * @opt_param int pageSize Optional. The maximum number of results to return
   * from this request. You must check for presence of `nextPageToken` to
   * determine if additional results are available, which you can retrieve by
   * passing the `nextPageToken` value as the `pageToken` parameter in the next
   * request.
   * @return Google_Service_Logging_ListSinksResponse
   */
  public function listProjectsSinks($projectName, $optParams = array())
  {
    $params = array('projectName' => $projectName);
    $params = array_merge($params, $optParams);
    return $this->call('list', array($params), "Google_Service_Logging_ListSinksResponse");
  }
  /**
   * Creates or updates a sink. (sinks.update)
   *
   * @param string $sinkName The resource name of the sink to update. Example:
   * `"projects/my-project-id/sinks/my-sink-id"`. The updated sink must be
   * provided in the request and have the same name that is specified in
   * `sinkName`. If the sink does not exist, it is created.
   * @param Google_Service_Logging_LogSink $postBody
   * @param array $optParams Optional parameters.
   * @return Google_Service_Logging_LogSink
   */
  public function update($sinkName, Google_Service_Logging_LogSink $postBody, $optParams = array())
  {
    $params = array('sinkName' => $sinkName, 'postBody' => $postBody);
    $params = array_merge($params, $optParams);
    return $this->call('update', array($params), "Google_Service_Logging_LogSink");
  }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Fragm. 4:72. 1864

#### Original name
Harmogia pentandra F.Muell.

### Remarks
null


text:
drop database if exists hibernate;

create database hibernate;

use hibernate;

CREATE TABLE event_inf (
  event_id int(11) NOT NULL auto_increment,
  happenDate date default NULL,
  title varchar(255) default NULL,
  PRIMARY KEY  (event_id)
);

INSERT INTO event_inf VALUES
(1,'2004-10-03','很高兴的事情'),
(2,'2005-10-03','很普通的事情'),
(3,'2004-10-04','疯狂Java筹备中'),
(4,'2005-10-05','疯狂Java开始培训');

CREATE TABLE person_inf (
  person_id int(11) NOT NULL auto_increment,
  name varchar(255) default NULL,
  age int(11) default NULL,
  event_id int(11),
  PRIMARY KEY (person_id),
  FOREIGN KEY (event_id) REFERENCES event_inf(event_id)
);

INSERT INTO person_inf VALUES
(1,'yeeku',30 , 1),
(2,'老朱',30 , 1);

CREATE TABLE person_email (
  person_id int(11) NOT NULL,
  email varchar(255) default NULL,
  KEY FKECD3B632CC53FFDC (person_id),
  FOREIGN KEY (person_id) REFERENCES person_inf (person_id)
);

INSERT INTO person_email VALUES
(1,'kongyeeku@apache.org'),
(1,'kongyeeku@mysql.com'),
(2,'dddd@163.com'),
(2,'vvvvvv@163.com');


text:
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.weblayer_private;

import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.components.webxr.ArCompositorDelegate;
import org.chromium.components.webxr.ArCompositorDelegateProvider;
import org.chromium.content_public.browser.WebContents;

/**
 * Weblayer-specific implementation of ArCompositorDelegateProvider interface.
 */
@JNINamespace("weblayer")
public class ArCompositorDelegateProviderImpl implements ArCompositorDelegateProvider {
    @CalledByNative
    public ArCompositorDelegateProviderImpl() {}

    @Override
    public ArCompositorDelegate create(WebContents webContents) {
        return new ArCompositorDelegateImpl(webContents);
    }
}