text:
export { default as DetailsButton } from './DetailsButton';
export { default as DownloadButton } from './DownloadButton';
export { default as CopyLinkButton } from './CopyLinkButton';
export { default as PreviewButton } from './PreviewButton';
export { default as RenameButton } from './RenameButton';
export { default as ShareFileButton } from './ShareFileButton';
export { default as ShareLinkButton } from './ShareLinkButton';


text:
package com.google.api.codegen.config;

import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.when;

import com.google.api.codegen.ResourceNameTreatment;
import com.google.api.codegen.util.Name;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableMap;
import java.util.List;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

public class FieldConfigFactoryTest {

  @Mock private FieldModel parent;
  @Mock private FieldModel moreParents;

  private ResourceNameMessageConfig messageConfig;
  private ResourceNameMessageConfigs messageConfigs;
  private Map<String, ResourceNameConfig> resourceNameConfigs;
  private ResourceNameConfig archive;
  private ResourceNameConfig shelf;

  @Before
  public void setUp() {
    MockitoAnnotations.initMocks(this);
    when(parent.getSimpleName()).thenReturn("parent");
    when(parent.getParentFullName()).thenReturn("google.cloud.library.ListBooksRequest");
    when(parent.isRepeated()).thenReturn(false);
    when(moreParents.getSimpleName()).thenReturn("more_parents");
    when(moreParents.isRepeated()).thenReturn(true);
    when(moreParents.getParentFullName()).thenReturn("google.cloud.library.ListBooksRequest");

    messageConfig =
        new AutoValue_ResourceNameMessageConfig(
            "google.cloud.library.ListBooksRequest",
            ImmutableListMultimap.of(
                "parent",
                "Shelf",
                "parent",
                "Archive",
                "more_parents",
                "Shelf",
                "more_parents",
                "Archive"));

    messageConfigs =
        new AutoValue_ResourceNameMessageConfigs(
            ImmutableMap.of("google.cloud.library.ListBooksRequest", messageConfig),
            ImmutableListMultimap.of(
                "google.cloud.library.ListBooksRequest",
                parent,
                "google.cloud.library.ListBooksRequest",
                moreParents));

    archive =
        SingleResourceNameConfig.newBuilder()
            .setNamePattern("")
            .setEntityId("Archive")
            .setEntityName(Name.from("archive"))
            .build();

    shelf =
        SingleResourceNameConfig.newBuilder()
            .setNamePattern("")
            .setEntityId("Shelf")
            .setEntityName(Name.from("shelf"))
            .build();

    resourceNameConfigs = ImmutableMap.of("Archive", archive, "Shelf", shelf);
  }

  @Test
  public void testCreateFlattenedFieldConfigsForSingularMultiResourceField() {

    List<FieldConfig> fieldConfigs =
        FieldConfigFactory.createFlattenedFieldConfigs(
            messageConfigs, resourceNameConfigs, parent, ResourceNameTreatment.STATIC_TYPES);
    FieldConfig parentConfig1 =
        FieldConfig.newBuilder()
            .setResourceNameConfig(archive)
            .setMessageResourceNameConfig(archive)
            .setResourceNameTreatment(ResourceNameTreatment.STATIC_TYPES)
            .setField(parent)
            .build();
    FieldConfig parentConfig2 =
        FieldConfig.newBuilder()
            .setResourceNameConfig(shelf)
            .setMessageResourceNameConfig(shelf)
            .setResourceNameTreatment(ResourceNameTreatment.STATIC_TYPES)
            .setField(parent)
            .build();
    assertThat(fieldConfigs).containsExactly(parentConfig1, parentConfig2);
  }

  @Test
  public void testCreateFlattenedFieldConfigsForRepeatedMultiResourceField() {
    List<FieldConfig> fieldConfigs =
        FieldConfigFactory.createFlattenedFieldConfigs(
            messageConfigs, resourceNameConfigs, moreParents, ResourceNameTreatment.STATIC_TYPES);
    FieldConfig moreParentConfig1 =
        FieldConfig.newBuilder()
            .setResourceNameConfig(archive)
            .setMessageResourceNameConfig(archive)
            .setResourceNameTreatment(ResourceNameTreatment.STATIC_TYPES)
            .setField(moreParents)
            .build();
    FieldConfig moreParentConfig2 =
        FieldConfig.newBuilder()
            .setResourceNameConfig(shelf)
            .setMessageResourceNameConfig(shelf)
            .setResourceNameTreatment(ResourceNameTreatment.STATIC_TYPES)
            .setField(moreParents)
            .build();
    assertThat(fieldConfigs).containsExactly(moreParentConfig1, moreParentConfig2);
  }
}

redpajama_set_name: RedPajamaGithub


text:
package de.fuberlin.wiwiss.silk.preprocessing.config

import scala.xml.Node

/**
 * A Free text preprocessing configuration.
 * Specifies an output source.
 *
 * @param method The transform method
 * @param params A map of parameters needed for the transformer
 * @param transform An optional nested transform specification
 */
case class TransformerConfig(method: String,
                             params: Map[String,String],
                             transform: Option[TransformerConfig]) {

}

object TransformerConfig{

  def fromXML(node:Node):TransformerConfig = {

    //Read method
    val method = (node \ "@method").text

    //Read parameters
    val params = readParams(node)

    val subTransformer = (node \ "Transform").headOption
    if(subTransformer.isDefined){
      new TransformerConfig(method, params, (node \ "Transform").map(TransformerConfig.fromXML).headOption)
    }
    else{
      new TransformerConfig(method, params, None)
    }

  }

  private def readParams(element: Node): Map[String, String] = {
    element \ "Param" map (p => (p \ "@name" text, p \ "@value" text)) toMap
  }

}


text:
"""Provide common test tools for Z-Wave JS."""
AIR_TEMPERATURE_SENSOR = "sensor.multisensor_6_air_temperature"
HUMIDITY_SENSOR = "sensor.multisensor_6_humidity"
ENERGY_SENSOR = "sensor.smart_plug_with_two_usb_ports_value_electric_consumed_2"
POWER_SENSOR = "sensor.smart_plug_with_two_usb_ports_value_electric_consumed"
SWITCH_ENTITY = "switch.smart_plug_with_two_usb_ports"
LOW_BATTERY_BINARY_SENSOR = "binary_sensor.multisensor_6_low_battery_level"
ENABLED_LEGACY_BINARY_SENSOR = "binary_sensor.z_wave_door_window_sensor_any"
DISABLED_LEGACY_BINARY_SENSOR = "binary_sensor.multisensor_6_any"
NOTIFICATION_MOTION_BINARY_SENSOR = (
    "binary_sensor.multisensor_6_home_security_motion_detection"
)
NOTIFICATION_MOTION_SENSOR = "sensor.multisensor_6_home_security_motion_sensor_status"
PROPERTY_DOOR_STATUS_BINARY_SENSOR = (
    "binary_sensor.august_smart_lock_pro_3rd_gen_the_current_status_of_the_door"
)
CLIMATE_RADIO_THERMOSTAT_ENTITY = "climate.z_wave_thermostat"
CLIMATE_DANFOSS_LC13_ENTITY = "climate.living_connect_z_thermostat"
CLIMATE_EUROTRONICS_SPIRIT_Z_ENTITY = "climate.thermostatic_valve"
CLIMATE_FLOOR_THERMOSTAT_ENTITY = "climate.floor_thermostat"
CLIMATE_MAIN_HEAT_ACTIONNER = "climate.main_heat_actionner"
BULB_6_MULTI_COLOR_LIGHT_ENTITY = "light.bulb_6_multi_color"
EATON_RF9640_ENTITY = "light.allloaddimmer"
AEON_SMART_SWITCH_LIGHT_ENTITY = "light.smart_switch_6"
ID_LOCK_CONFIG_PARAMETER_SENSOR = (
    "sensor.z_wave_module_for_id_lock_150_and_101_config_parameter_door_lock_mode"
)


text:
package gudusoft.gsqlparser.sql2xml.model;

public class extract_field
{

}


text:
// Define a namespace for the library
if (typeof Readium === "undefined" || Readium === null) {
	Readium = {};
}

if(typeof Readium.FileSystemApi === "undefined") {
	throw "Ebook holds Readium::FileSystemApi as a dependency";
}

if(typeof Readium.PackageDocument === "undefined") {
	throw "Ebook holds Readium::packageDocument as a dependency";
}

if(!Readium.Utils) {
	Readium.Utils = {};
}

Readium.Utils.setCookie = function(c_name,value,exdays) {
	var exdate=new Date();
	exdate.setDate(exdate.getDate() + exdays);
	var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
	document.cookie=c_name + "=" + c_value;
}

Readium.Utils.getCookie = function(c_name) {
	var i, x, y, ARRcookies=document.cookie.split(";");
	for (i = 0; i < ARRcookies.length; i++) {
		x = ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
		y = ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
		x = x.replace(/^\s+|\s+$/g,"");
		if ( x == c_name ) {
			return unescape(y);
		}
	}
}

// Asynchronous constructor
Readium.Ebook = function(properties, successCallback, errorCallback) {

	// private members
	var _properties;
	var _fsApi;
	var _packageDocUrl; // not used
	var _rootUrl;

	var loadBookMark = function() {
		var str = Readium.Utils.getCookie(_properties.key);
		return parseInt(str) || 0;
	}

	var validateProperties = function(obj) {
		var key;
		var keys = "id key lang package_doc_path updated_at created_at".split(" ")

		for(var i = 0; i < keys.length; i++) {
			key = keys[i];
			if(!obj[key]) {
				return false;
			}
		}
		_properties = obj;
		return true;
	}

	var save = function(callback) {
		_properties.updated_at = new Date();
		if(!_properties.key) {
			// should never get here
			throw "FATAL ERROR: cannot save record with no key";
		}
		Lawnchair(function() {
			this.save(properties, function(obj) {
				callback(obj);
			});
		});
	};

	// initialization code
	var init = function() {
		var initPackageDocument = function(domString, fileEntry) {
			_packageDocument = Readium.PackageDocument(domString);
			_packageDocument.setPosition( loadBookMark() );
			_packageDocUrl = fileEntry.toURL();

			// execute callback and pass back api for "this"
			successCallback(api);
		};

		if(validateProperties(properties)) {

			Readium.FileSystemApi(function(fs) {
				_fsApi = fs;
				_rootUrl = _fsApi.getFileSystem().root.toURL();
				_fsApi.readTextFile(_properties.package_doc_path, initPackageDocument, errorCallback);
			});
		}
		else if (errorCallback){
			errorCallback("invalid properties");
		}
	};

	var resolvePath = function(path) {
		var suffix;
		if(path.indexOf("../") === 0) {
			suffix = path.substr(3);
		}
		else {
			suffix = path;
		}
		var ind = _properties.package_doc_path.lastIndexOf("/")
		return _properties.package_doc_path.substr(0, ind) + "/" + suffix;
	}

	var resolveUrl = function(path) {
		return _rootUrl + resolvePath(path);
	}

	var savePosition = function() {
		Readium.Utils.setCookie(_properties.key, _packageDocument.getPosition(), 365);
	}

	var buildTocHtml = function(text, callback) {
		var parser = new window.DOMParser();
		var dom = parser.parseFromString(text, 'text/xml');
		var ul = '
';
		var navPoints = dom.getElementsByTagName('navPoint');
		var label; var href;

		for(var i = 0; i < navPoints.length; i++) {
			label = navPoints[i].getElementsByTagName('text')[0].textContent;
			href = navPoints[i].getElementsByTagName('content')[0].attributes["src"].value;
			ul += "
" + label + "
";
		}
		ul += '
'

		callback(ul);

	};

	/************************* bindings handling code, move it? **********************/

	var applyBindings = function(domSpot) {
		var key;
		var bindings = jQuery.extend({}, _packageDocument.getBindingHandlers());

		// break out early if there are none <= any point to this?
		if(!bindings || Object.keys(bindings).length === 0) {
			return;
		}

		// resolve all the bindings paths to absolute urls
		for( key in bindings ) {
			bindings[key] = resolveUrl(bindings[key]);
		}

		$('object[type]', domSpot).each(function() {
			var params; var src; var frame;
			var $this = $(this);
			var type = $this.attr('type');
			if( bindings.hasOwnProperty(type) ) {
				params = parseBindingsParams($this);
				src = bindings[type] + '?' + params;
				frame = $('');
				frame.load(function() {
					// this project was supposed to be done yesterday
					// don't judge me :(
					var that = this;
					var $dom = $(this.contentDocument.body);
					var calcZoom = function() {
						return  $dom.height() / $(that).height();
					}

					$(window).resize(function() {
						$dom.css('zoom', calcZoom());
					});
					$dom.css('zoom', calcZoom());
				});
				frame.attr('src', src);
				frame.attr('height', '100%');
				frame.attr('width', '100%');
				frame.attr('noresize', "noresize");
				frame.attr('frameborder', '0');
				frame.attr('marginwidth', '0');
				frame.attr('marginheight', '0');
				$this.html(frame);
			}
		});

	};

	var parseBindingsParams = function($obj) {
		var params = [];
		params.push("src=" + resolveUrl( $obj.attr('data') ) );
		params.push("type=" + $obj.attr('type') );
		$('param', $obj).each(function() {
			var $this = $(this);
			params.push($this.attr('name') + '=' + $this.attr('value') )
		});
		params = params.join('&');

		/* need to escape special chars as per RFC3987 */
		return encodeURI(params);
	};

	/************************* END bindings handling code, move it? **********************/

	// declare api
	var api = {
		resolvePath: resolvePath,

		resolveUrl: resolveUrl,

		goToNextSection: function() {
			if(_packageDocument.hasNextSection() ) {
				_packageDocument.goToNextSection();
				savePosition();
				return true;
			}
			return false;
		},

		goToPrevSection: function() {
			if(_packageDocument.hasPrevSection() ) {
				_packageDocument.goToPrevSection();
				savePosition();
				return true;
			}
			return false;
		},

		getSectionText: function(successCallback, failureCallback) {
			var path = _packageDocument.currentSection();
			Readium.FileSystemApi(function(fs) {
				fs.readTextFile(resolvePath(path), successCallback, failureCallback);
			});
		},

		getAllSectionTexts: function(sectionCallback, failureCallback, completeCallback) {
			var i = 0;
			var spine = _packageDocument.getSpineArray();
			var thatFs;

			var callback = function(content, fileEntry) {
				sectionCallback(content);
				i += 1;
				if(i < spine.length) {
					thatFs.readTextFile(resolvePath(spine[i]), callback, failureCallback);
				}
				else {
					completeCallback();
				}

			};

			Readium.FileSystemApi(function(fs) {
				thatFs = fs;
				thatFs.readTextFile(resolvePath(spine[i]), callback, failureCallback);
			});

		},

		getAllSectionUris: function() {
			var temp = _packageDocument.getSpineArray();
			for(var i = 0; i < temp.length; i++) {
				temp[i] = resolveUrl(temp[i]);
			}
			return temp;
		},

		getTocText: function(successCallback, failureCallback) {
			var path = _packageDocument.getTocPath();
			if(!path) {
				failureCallback();
				return;
			}

			if(_packageDocument.getTocType() === _packageDocument.XHTML_MIME) {
				Readium.FileSystemApi(function(fs) {
					fs.readTextFile(resolvePath(path), function(result) {
						var parser = new window.DOMParser();
						var dom = parser.parseFromString(result, 'text/xml');
						successCallback( $('body', dom).html() );
					}, failureCallback);
				});
			}

			else if(_packageDocument.getTocType() === _packageDocument.NCX_MIME) {
				Readium.FileSystemApi(function(fs) {
					fs.readTextFile(resolvePath(path), function(result) {
						buildTocHtml(result, successCallback)
					}, failureCallback);
				});
			}

			else {

			}

		},

		goToHref: function(href) {
			if(_packageDocument.goToHref(href)) {
				savePosition();
				return true;
			}
			return false;
		},

		getProperties: function() {
			return _properties;
		},

		isFixedLayout: function() {
			return _properties.fixed_layout;
		},

		applyBindings: applyBindings
	};

	init();
}


text:
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { AngularFire, FirebaseListObservable } from 'angularfire2';

import { AuthService } from '../../providers/auth-service';
import { DetallePedidoPage } from '../detalle-pedido/detalle-pedido';
import { LoginPage } from "../login/login";

@Component({
  selector: 'page-perfil',
  templateUrl: 'perfil.html'
})
export class Perfil {

  pedidos: FirebaseListObservable<any>;
  pendientes: number;
  entregados: number;
  usu: any;
  log: boolean = false;

  constructor(public navCtrl: NavController, public auth: AuthService, public af: AngularFire) {
    if (this.auth.getStatus()) { this.log = true; }
    else { this.log = false; }

    if (this.log) {
      this.pedidos = this.auth.getPedidos();
      this.usu = this.auth.getStatus().auth.email;

      // contamos el total de pedidos que tiene el usuario
      if (this.pedidos) {
        this.pedidos.subscribe(snapshot => {
          // inicializamos las cantidades
          this.pendientes = 0;
          this.entregados = 0;
          snapshot.forEach(value => {
            // si esta pagado se cuenta como pedido completo
            if (value.datos.estado == 'pagado') {
              // comprobamos los estados de los pedidos
              if (value.datos.entregado == 'pendiente') {
                  this.pendientes++;
              } else if (value.datos.entregado == 'entregado') {
                  this.entregados++;
              }
            }
          });
        });
      } else {
        this.pendientes = 0;
        this.entregados = 0;
      }
    } else {

    }
  }

  // metodo para mostrar el detalle del pedido
  goToPedido(key) {
    this.navCtrl.push(DetallePedidoPage, {
      id: key
    });
  }

  // para loguarse
  loguarse() {
    this.navCtrl.push(LoginPage);
  }
}


text:
@implementation MKPolygon (MKPolygon_BHEExtensions)

static char overlayColorKey;

- (void)setOverlayColor:(UIColor *)overlayColor {
    objc_setAssociatedObject(self, &overlayColorKey, overlayColor, OBJC_ASSOCIATION_RETAIN );
}

- (UIColor*)overlayColor {
    return objc_getAssociatedObject( self, &overlayColorKey );
}

@end


text:
package net.dv8tion.jda.handle;

import net.dv8tion.jda.entities.Guild;
import net.dv8tion.jda.entities.User;
import net.dv8tion.jda.entities.VoiceChannel;
import net.dv8tion.jda.entities.impl.JDAImpl;
import net.dv8tion.jda.entities.impl.VoiceChannelImpl;
import net.dv8tion.jda.entities.impl.VoiceStatusImpl;
import net.dv8tion.jda.events.voice.*;
import net.dv8tion.jda.requests.GuildLock;
import org.json.JSONObject;

public class VoiceChangeHandler extends SocketHandler
{
    public VoiceChangeHandler(JDAImpl api, int responseNumber)
    {
        super(api, responseNumber);
    }

    @Override
    protected String handleInternally(JSONObject content)
    {
        if (GuildLock.get(api).isLocked(content.getString("guild_id")))
        {
            return content.getString("guild_id");
        }

        User user = api.getUserMap().get(content.getString("user_id"));
        if (user == null)
        {
            if (!content.isNull("channel_id"))
                throw new IllegalArgumentException("Received a VOICE_STATE_UPDATE for an unknown User! JSON: " + content);
            else
                return null; //This is most likely a VOICE_STATE_UPDATE telling us that a user that left/was kicked/was banned
                             // has been disconnected from the VoiceChannel they were in.
                             //The VoiceLeaveEvent has already been handled by GuildMemberRemoveHandler
        }

        Guild guild = api.getGuildMap().get(content.getString("guild_id"));
        if (guild == null)
            throw new IllegalArgumentException("Received a VOICE_STATE_UPDATE for an unknown Guild! JSON: " + content);

        VoiceStatusImpl status = (VoiceStatusImpl) guild.getVoiceStatusOfUser(user);

        if (status == null)
        {
            //This voiceStatus update is caused by a user being kicked/banned from a guild
            //we already cleared him in the GuildMemberRemoveHandler, and therefore cant access his status anymore
            return null;
        }

        if (content.isNull("channel_id"))
        {
            if (status.getChannel() != null)
            {
                VoiceChannel oldChannel = status.getChannel();
                if (oldChannel != null)
                {
                    status.setChannel(null);
                    ((VoiceChannelImpl) oldChannel).getUsersModifiable().remove(user);
                    api.getEventManager().handle(new VoiceLeaveEvent(api, responseNumber, status, oldChannel));
                }
            }
        }
        else
        {
            if (status.getChannel() == null ||
                    !content.getString("channel_id").equals(status.getChannel().getId()))
            {
                VoiceChannel oldChannel = status.getChannel();
                VoiceChannel newChannel = api.getVoiceChannelMap().get(content.getString("channel_id"));
                status.setChannel(newChannel);
                if (oldChannel != null)
                {
                    ((VoiceChannelImpl) oldChannel).getUsersModifiable().remove(user);
                    api.getEventManager().handle(new VoiceLeaveEvent(api, responseNumber, status, oldChannel));
                }
                ((VoiceChannelImpl) newChannel).getUsersModifiable().add(user);
                api.getEventManager().handle(new VoiceJoinEvent(api, responseNumber, status));
            }
        }

        //TODO: Implement event for changing of session id? Might be important...
        if (!content.isNull("session_id"))
            status.setSessionId(content.getString("session_id"));
        else
            status.setSessionId(null);

        //TODO: Implement event for changing of suppressed value? Only occurs when entering an AFK room. Maybe important...
        status.setSuppressed(content.getBoolean("suppress"));

        boolean isSelfMute = !content.isNull("self_mute") && content.getBoolean("self_mute");
        if (isSelfMute != status.isMuted())
        {
            status.setMute(!status.isMuted());
            api.getEventManager().handle(new VoiceSelfMuteEvent(api, responseNumber, status));
        }
        boolean isSelfDeaf = !content.isNull("self_deaf") && content.getBoolean("self_deaf");
        if (isSelfDeaf != status.isDeaf())
        {
            status.setDeaf(!status.isDeaf());
            api.getEventManager().handle(new VoiceSelfDeafEvent(api, responseNumber, status));
        }
        if (content.getBoolean("mute") != status.isServerMuted())
        {
            status.setServerMute(!status.isServerMuted());
            api.getEventManager().handle(new VoiceServerMuteEvent(api, responseNumber, status));
        }
        if (content.getBoolean("deaf") != status.isServerDeaf())
        {
            status.setServerDeaf(!status.isServerDeaf());
            api.getEventManager().handle(new VoiceServerDeafEvent(api, responseNumber, status));
        }
        return null;
    }
}


text:
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
 * Copyright (c) 2010 Dean Armstrong
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation;
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * Author: Dean Armstrong <deanarm@gmail.com>
 */

#ifndef WIFI_INFORMATION_ELEMENT_H
#define WIFI_INFORMATION_ELEMENT_H

#include "ns3/header.h"
#include "ns3/simple-ref-count.h"

namespace ns3 {

/**
 * This type is used to represent an Information Element ID. An
 * enumeration would be tidier, but doesn't provide for the
 * inheritance that is currently preferable to cleanly support
 * pre-standard modules such as mesh. Maybe there is a nice way of
 * doing this with a class.
 *
 * Until such time as a better way of implementing this is dreamt up
 * and applied, developers will need to be careful to avoid
 * duplication of IE IDs in the defines below (and in files which
 * declare "subclasses" of WifiInformationElement). Sorry.
 */
typedef uint8_t WifiInformationElementId;

/**
 * Here we have definition of all Information Element IDs in IEEE
 * 802.11-2007. See the comments for WifiInformationElementId - this could
 * probably be done in a considerably tidier manner.
 */
#define IE_SSID                                ((WifiInformationElementId)0)
#define IE_SUPPORTED_RATES                     ((WifiInformationElementId)1)
#define IE_FH_PARAMETER_SET                    ((WifiInformationElementId)2)
#define IE_DS_PARAMETER_SET                    ((WifiInformationElementId)3)
#define IE_CF_PARAMETER_SET                    ((WifiInformationElementId)4)
#define IE_TIM                                 ((WifiInformationElementId)5)
#define IE_IBSS_PARAMETER_SET                  ((WifiInformationElementId)6)
#define IE_COUNTRY                             ((WifiInformationElementId)7)
#define IE_HOPPING_PATTERN_PARAMETERS          ((WifiInformationElementId)8)
#define IE_HOPPING_PATTERN_TABLE               ((WifiInformationElementId)9)
#define IE_REQUEST                             ((WifiInformationElementId)10)
#define IE_BSS_LOAD                            ((WifiInformationElementId)11)
#define IE_EDCA_PARAMETER_SET                  ((WifiInformationElementId)12)
#define IE_TSPEC                               ((WifiInformationElementId)13)
#define IE_TCLAS                               ((WifiInformationElementId)14)
#define IE_SCHEDULE                            ((WifiInformationElementId)15)
#define IE_CHALLENGE_TEXT                      ((WifiInformationElementId)16)
// 17 to 31 are reserved in 802.11-2007
#define IE_POWER_CONSTRAINT                    ((WifiInformationElementId)32)
#define IE_POWER_CAPABILITY                    ((WifiInformationElementId)33)
#define IE_TPC_REQUEST                         ((WifiInformationElementId)34)
#define IE_TPC_REPORT                          ((WifiInformationElementId)35)
#define IE_SUPPORTED_CHANNELS                  ((WifiInformationElementId)36)
#define IE_CHANNEL_SWITCH_ANNOUNCEMENT         ((WifiInformationElementId)37)
#define IE_MEASUREMENT_REQUEST                 ((WifiInformationElementId)38)
#define IE_MEASUREMENT_REPORT                  ((WifiInformationElementId)39)
#define IE_QUIET                               ((WifiInformationElementId)40)
#define IE_IBSS_DFS                            ((WifiInformationElementId)41)
#define IE_ERP_INFORMATION                     ((WifiInformationElementId)42)
#define IE_TS_DELAY                            ((WifiInformationElementId)43)
#define IE_TCLAS_PROCESSING                    ((WifiInformationElementId)44)
#define IE_HT_CAPABILITIES                     ((WifiInformationElementId)45)
#define IE_QOS_CAPABILITY                      ((WifiInformationElementId)46)
// 47 is reserved in 802.11-2007
#define IE_RSN                                 ((WifiInformationElementId)48)
// 49 is reserved in 802.11-2007
#define IE_EXTENDED_SUPPORTED_RATES            ((WifiInformationElementId)50)
// 51 to 60 are reserved in 802.11-2007
#define IE_HT_OPERATIONS                       ((WifiInformationElementId)61)
// 62 to 126 are reserved in 802.11-2007
#define IE_EXTENDED_CAPABILITIES               ((WifiInformationElementId)127)
// 128 to 190 are reserved in 802.11-2007
#define IE_VHT_CAPABILITIES                    ((WifiInformationElementId)191)
#define IE_VENDOR_SPECIFIC                     ((WifiInformationElementId)221)
// 222 to 255 are reserved in 802.11-2007
#define IE11S_LINK_METRIC_REPORT               ((WifiInformationElementId)115)
#define IE11S_CONGESTION_NOTIFICATION          ((WifiInformationElementId)116)
#define IE11S_SUPP_MBSS_REG_CLASSES_CHANNELS   ((WifiInformationElementId)23)
#define IE11S_MESH_CHANNEL_SWITCH_ANNOUNCEMENT ((WifiInformationElementId)24)
#define IE11S_MESH_TIM                         ((WifiInformationElementId)25)
#define IE11S_AWAKE_WINDOW                     ((WifiInformationElementId)119)
#define IE11S_BEACON_TIMING                    ((WifiInformationElementId)120)
#define IE11S_MCCAOP_SETUP_REQUEST             ((WifiInformationElementId)121)
#define IE11S_MCCAOP_SETUP_REPLY               ((WifiInformationElementId)122)
#define IE11S_MCCAOP_ADVERTISEMENT             ((WifiInformationElementId)123)
#define IE11S_MCCAOP_RESERVATION_TEARDOWN      ((WifiInformationElementId)31)
#define IE11S_PORTAL_ANNOUNCEMENT              ((WifiInformationElementId)32)
#define IE11S_PROXY_UPDATE                     ((WifiInformationElementId)137)
#define IE11S_PROXY_UPDATE_CONFIRMATION        ((WifiInformationElementId)138)
#define IE11S_ABBREVIATED_HANDSHAKE            ((WifiInformationElementId)39)
/* begin of open80211s-compatible IDs */
#define IE11S_MESH_CONFIGURATION               ((WifiInformationElementId)113)
#define IE11S_MESH_ID                          ((WifiInformationElementId)114)
#define IE11S_PEERING_MANAGEMENT               ((WifiInformationElementId)117)
/* end of open80211s-compatible IDs */
#define IE11S_RANN                             ((WifiInformationElementId)126)
/* begin of open80211s-compatible IDs */
#define IE11S_PREQ                             ((WifiInformationElementId)130)
#define IE11S_PREP                             ((WifiInformationElementId)131)
#define IE11S_PERR                             ((WifiInformationElementId)132)
/* end of open80211s-compatible IDs */
#define IE11S_MESH_PEERING_PROTOCOL_VERSION    ((WifiInformationElementId)74)

/**
 * \brief Information element, as defined in 802.11-2007 standard
 * \ingroup wifi
 *
 * The IEEE 802.11 standard includes the notion of Information
 * Elements, which are encodings of management information to be
 * communicated between STAs in the payload of various frames of type
 * Management. Information Elements (IEs) have a common format, each
 * starting with a single octet - the Element ID, which indicates the
 * specific type of IE (a type to represent the options here is
 * defined as WifiInformationElementId). The next octet is a length field and
 * encodes the number of octets in the third and final field, which is
 * the IE Information field.
 *
 * The class ns3::WifiInformationElement provides a base for classes
 * which represent specific Information Elements. This class defines
 * pure virtual methods for serialisation
 * (ns3::WifiInformationElement::SerializeInformationField) and
 * deserialisation
 * (ns3::WifiInformationElement::DeserializeInformationField) of IEs, from
 * or to data members or other objects that simulation objects use to
 * maintain the relevant state.
 *
 * This class also provides an implementation of the equality
 * operator, which operates by comparing the serialised versions of
 * the two WifiInformationElement objects concerned.
 *
 * Elements are defined to have a common general format consisting of
 * a 1 octet Element ID field, a 1 octet length field, and a
 * variable-length element-specific information field. Each element is
 * assigned a unique Element ID as defined in this standard. The
 * Length field specifies the number of octets in the Information
 * field.
 *
 * This class is pure virtual and acts as base for classes which know
 * how to serialize specific IEs.
 */
class WifiInformationElement : public SimpleRefCount<WifiInformationElement>
{
public:
  virtual ~WifiInformationElement ();
  /**
   * Serialize entire IE including Element ID and length fields
   *
   * \param i an iterator which points to where the IE should be written.
   *
   * \return an iterator
   */
  Buffer::Iterator Serialize (Buffer::Iterator i) const;
  /**
   * Deserialize entire IE, which must be present. The iterator
   * passed in must be pointing at the Element ID (i.e., the very
   * first octet) of the correct type of information element,
   * otherwise this method will generate a fatal error.
   *
   * \param i an iterator which points to where the IE should be read.
   *
   * \return an iterator
   */
  Buffer::Iterator Deserialize (Buffer::Iterator i);
  /**
   * Deserialize entire IE if it is present. The iterator passed in
   * must be pointing at the Element ID of an information element. If
   * the Element ID is not the one that the given class is interested
   * in then it will return the same iterator.
   *
   * \param i an iterator which points to where the IE should be read.
   *
   * \return an iterator
   */
  Buffer::Iterator DeserializeIfPresent (Buffer::Iterator i);
  /**
   * Get the size of the serialized IE including Element ID and
   * length fields.
   *
   * \return the size of the serialized IE
   */
  uint16_t GetSerializedSize () const;

  // Each subclass must implement these pure virtual functions:
  /// Own unique Element ID
  virtual WifiInformationElementId ElementId () const = 0;
  /**
   * Length of serialized information (i.e., the length of the body
   * of the IE, not including the Element ID and length octets. This
   * is the value that will appear in the second octet of the entire
   * IE - the length field)
   *
   * \return the length of serialized information
   */
  virtual uint8_t GetInformationFieldSize () const = 0;
  /**
   * Serialize information (i.e., the body of the IE, not including
   * the Element ID and length octets)
   *
   * \param start an iterator which points to where the information should
   *        be written.
   */
  virtual void SerializeInformationField (Buffer::Iterator start) const = 0;
  /**
   * Deserialize information (i.e., the body of the IE, not including
   * the Element ID and length octets)
   *
   * \param start an iterator which points to where the information should be written.
   * \param length
   *
   * \return the number of bytes read
   */
  virtual uint8_t DeserializeInformationField (Buffer::Iterator start,
                                               uint8_t length) = 0;

  // In addition, a subclass may optionally override the following...
  /**
   * Generate human-readable form of IE
   *
   * \param os output stream
   */
  virtual void Print (std::ostream &os) const;
  /**
   * Compare information elements using Element ID
   *
   * \param a another information element to compare with
   *
   * \return true if the Element ID is less than the other IE Element ID,
   *         false otherwise
   */
  virtual bool operator< (WifiInformationElement const & a) const;
  /**
   * Compare two IEs for equality by ID & Length, and then through
   * memcmp of serialised version
   *
   * \param a another information element to compare with
   *
   * \return true if the two IEs are equal,
   *         false otherwise
   */
  virtual bool operator== (WifiInformationElement const & a) const;

};

} //namespace ns3

#endif /* WIFI_INFORMATION_ELEMENT_H */


text:
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using Xunit;

namespace Microsoft.Azure.WebJobs.Logging.FunctionalTests
{
    public class FunctionIdTests
    {
        // Test normalization
        [Fact]
        public void Operators()
        {
            var f1 = FunctionId.Build("h1", "FFF1");
            var f2 = FunctionId.Build("H1", "fff1"); // different casing.

            Assert.Equal("h1-fff1", f2.ToString());

            // Names have been normalized.
            Assert.True(f1.Equals(f2));
            Assert.Equal(f1.GetHashCode(), f2.GetHashCode());
            Assert.True(f1 == f2);
            Assert.False(f1 != f2);
        }

        // Characters are escaped.
        [Fact]
        public void Escapes()
        {
            var f = FunctionId.Build("h-1", "F-:1");

            string str = f.ToString();
            Assert.Equal("h:2D1-f:2D:3A1", str);
        }

        // Direct creation doesn't roundtrip.
        [Fact]
        public void Direct()
        {
            string str = "ab-def%:x$";
            var f = FunctionId.Parse(str);

            Assert.Equal(str, f.ToString());
        }
    }
}


text:
/**
 * notification controller
 *
 * @docs        :: http://wejs.org/docs/we/request-response.controllers
 */

module.exports = {
  getNotificationCount( req, res ) {
    if(!req.isAuthenticated()) return res.forbidden();

    let read = req.query.read || false;

    req.we.db.models.notification
    .count({
      where: {
        userId: req.user.id,
        read: Boolean (read)
      }
    })
    .then( (count)=> {
      res.send({ count: count });
      return null;
    })
    .catch(res.queryError);
  },

  /**
   * Find current user notifications
   *
   */
  find(req, res) {
    if (!req.isAuthenticated()) return res.forbidden();

    if (req.query.read === 'all') {
      res.locals.isNAll = true;
      res.locals.title = res.locals.__('notification.find.all');
      res.locals.query.where.read = null;
    } else if (req.query.read === 'true'){
      res.locals.isReads = true;
      res.locals.title = res.locals.__('notification.find.read');
      res.locals.query.where.read = true;
    } else {
      res.locals.query.where.read = false;
      res.locals.isUnreads = true;
      res.locals.title = res.locals.__('notification.find.unread');
    }

    res.locals.query.where.userId = req.user.id;

    req.we.db.models.notification
    .findAll(res.locals.query)
    .then( (r)=> {

      res.locals.data = r;

      return req.we.db.models.notification
      .count({
        where: {
          userId: req.user.id,
          read: res.locals.query.where.read
        }
      })
      .then( (count)=> {
        res.locals.metadata.count = count;
        res.ok();
        return null;
      });
    })
    .catch(res.queryError); // findAll
  },

  create(req, res) {
    return res.notFound();
  },

  /**
   * Update notification read status attr
   */
  setNotificationRead(req, res) {
    if(!req.isAuthenticated()) return res.forbidden();

    let redirectTo = req.we.utils.getRedirectUrl(req, res);

    req.we.db.models.notification
    .findById(req.params.notificationId)
    .then( (r)=> {
      if (!r) {
        res.notFound();
        return null;
      }
      // not is owner
      if (r.userId != req.user.id) {
        res.forbidden();
        return null;
      }

      let read;
      if (req.body.isRead == 'true') {
        read = true;
      } else {
        read = false;
      }

      if (r.read == read) {
        if (redirectTo) {
          res.goTo(redirectTo);
        } else {
          res.send({ notification: r });
        }
        return null;
      }

      r.read = read;

      r.save()
      .then( ()=> {
        if (req.we.io) {
          // emit to other users devices
          req.we.io.sockets.in('user_' + req.user.id)
          .emit('notification:update:read', {
            id: r.id, read: r.read
          });
        }

        if (redirectTo) {
          res.goTo(redirectTo);
        } else {
          res.send({ notification: r });
        }

        return null;
      })
      .catch(res.queryError);
    })
    .catch(res.queryError);
  },

  markAllModelNotificationAsRead(req, res) {
    if(!req.isAuthenticated()) return res.forbidden();

    const model = req.params.model;
    const modelId = req.params.modelId;

    if ( !model && !modelId ) {
      res.badRequest('model and modelId is required');
      return null;
    }

    req.we.db.models.notification
    .update({
      read: true
    },{
      where: {
        user: req.user.id,
        read: false,
        modelName: model,
        modelId: modelId
      }
    })
    .then(function updated(records) {
      if (!records || !records.length) {
        // no unread notifications
        res.send({});
      } else {
        // if success respond with updated notifications
        res.send({ notification: records });
      }
      return null;
    })
    .catch(res.queryError);
  },

  markAllNotificationAsRead(req, res) {
    if(!req.isAuthenticated()) return res.forbidden();

    let redirectTo = req.we.utils.getRedirectUrl(req, res);

    req.we.db.models.notification
    .update({
      read: true
    },{
      where: {
        userId: req.user.id,
        read: false
      }
    })
    .then(function updated() {
      if (redirectTo) {
        res.goTo(redirectTo);
      } else {
        res.send({});
      }
      return null;
    })
    .catch(res.queryError);
  },

  /**
   * Redirect user to related model
   *
   */
  linkPermanent(req, res) {
    req.we.db.models
    .findById(req.params.id)
    .then( (notification)=> {
      if ( !notification ) {
        res.notFound();
      } else {
        let url = '/' + notification.modelName + '/' + notification.modelId;
        res.goTo(url);
      }

      return null;
    })
    .catch(res.queryError);
  },

  userNotificationSettings(req, res) {
    if (!req.isAuthenticated()) return res.forbidden();

    if (!res.locals.data) res.locals.data = {};

    res.locals.Model
    .findOne({
      userId: req.user.id
    })
    .then( (record)=> {

      if (req.method == 'POST') {
        if (!record) {
          //create
          return res.locals.Model
          .create(req.body)
          .then( (record)=> {
            res.locals.data = record;
            res.ok();
            return null;
          })
          .catch(res.queryError);
        } else {
          // update
          return record.updateAttributes(req.body)
          .then( ()=> {
            res.locals.data = record;
            res.ok();
            return null;
          })
          .catch(res.queryError);
        }
      } else {
        res.locals.data = record;
        res.ok();
      }

      return null;
    })
    .catch(res.queryError);
  }
};


text:
INSERT INTO SENDMAIL_CONFIG(ID,NAME,HOST,USERNAME,PASSWORD,SMTP_AUTH,SMTP_STARTTLS,STATUS,DEFAULT_FROM,SCOPE_ID) VALUES(1,'default','smtp.gmail.com','demo.mossle@gmail.com','demo5mossle',1,1,1,'demo.mossle@gmail.com',1);

INSERT INTO SENDMAIL_TEMPLATE(ID,NAME,SENDER,RECEIVER,SUBJECT,CONTENT,MANUAL) VALUES(1,'test','测试<demo.mossle@gmail.com>','xyz20003<xyz20003@gmail.com>,临远<lingo.mossle@gmail.com>','test','test',0);

INSERT INTO SENDMAIL_TEMPLATE(ID,NAME,SENDER,RECEIVER,SUBJECT,CONTENT,MANUAL) VALUES(2,'template','测试<demo.mossle@gmail.com>','演示<demo.mossle@gmail.com>','template','${name}<#list list as item>${item}</#list>',1);


text:
import math

## \brief Verifies that input values satisfy the physical constraints
# \param v_launch launch speed: the initial speed of the projectile when launched (m/s)
# \param theta launch angle: the angle between the launcher and a straight line from the launcher to the target (rad)
# \param p_target target position: the distance from the launcher to the target (m)
def input_constraints(v_launch, theta, p_target):
    if (not(v_launch > 0.0)) :
        print("Warning: ", end="")
        print("v_launch has value ", end="")
        print(v_launch, end="")
        print(", but is suggested to be ", end="")
        print("above ", end="")
        print(0.0, end="")
        print(".")
    if (not(0.0 < theta and theta < math.pi / 2.0)) :
        print("Warning: ", end="")
        print("theta has value ", end="")
        print(theta, end="")
        print(", but is suggested to be ", end="")
        print("between ", end="")
        print(0.0, end="")
        print(" and ", end="")
        print(math.pi / 2.0, end="")
        print(" ((pi)/(2))", end="")
        print(".")
    if (not(p_target > 0.0)) :
        print("Warning: ", end="")
        print("p_target has value ", end="")
        print(p_target, end="")
        print(", but is suggested to be ", end="")
        print("above ", end="")
        print(0.0, end="")
        print(".")


text:
/*
 * See config/index.js for further explanation.
 * test config overrides global config values
 */

var config = require('./config.global');

config.env = 'test';
config.mongo.db = 'boycott_test_db';

config.mongo.uri = 'localhost';
config.mongo.db = 'boycott_test_db';

// config.mongo.user = '';
// config.mongo.pass = '';
// config.mongo.port = 27017;

config.mongo.connectionString = 'mongodb://' + config.mongo.uri + '/' + config.mongo.db;

module.exports = config;


text:
	<bx_repeat:cats>

                        __icon__

                    __name__

__num__

	</bx_repeat:cats>


text:
ActiveRecord::Schema.define(:version => 20130302153106) do

  create_table "admins", :force => true do |t|
    t.string   "email"
    t.string   "first_name"
    t.string   "middle_name"
    t.string   "last_name"
    t.date     "birthdate"
    t.datetime "created_at",  :null => false
    t.datetime "updated_at",  :null => false
  end

  create_table "users", :force => true do |t|
    t.string   "email"
    t.string   "first_name"
    t.string   "middle_name"
    t.string   "last_name"
    t.date     "birthdate"
    t.datetime "created_at",  :null => false
    t.datetime "updated_at",  :null => false
  end

end


text:
package io.youi.component.feature

import io.youi.component.types.{Border, ColumnFill, Prop, SizeProperty}

class ColumnFeature(override val parent: FeatureParent) extends Feature {
  lazy val count: Prop[Int] = new Prop[Int](-1, i => parent.css.columnCount = i)
  lazy val fill: Prop[ColumnFill] = Prop.stringify[ColumnFill](parent.css.columnFill, parent.css.columnFill_=, ColumnFill, ColumnFill.Initial)
  lazy val gap: SizeProperty = new SizeProperty("", s => parent.css.columnGap = s)
  lazy val rule: Prop[Border] = Prop.stringify(parent.css.columnRule, parent.css.columnRule_=, Border, Border.undefined)
  lazy val width: SizeProperty = new SizeProperty("", s => parent.css.columnWidth = s)
}


text:
from JumpScale import j
import JumpScale.baselib.watchdog.manager
import JumpScale.baselib.redis
import JumpScale.lib.rogerthat

descr = """
critical alert
"""

organization = "jumpscale"
enable = True

API_KEY = j.application.config.get('rogerthat.apikey')
redis_client = j.clients.redis.getByInstanceName('system')
rogerthat_client = j.clients.rogerthat.get(API_KEY)

ANSWERS = [{'id': 'yes', 'caption': 'Take', 'action': '', 'type': 'button'},]

def _send_message(message, contacts, answers=ANSWERS, alert_flags=6):
    result = rogerthat_client.send_message(message, contacts, answers=answers, alert_flags=alert_flags)
    if result:
        if result['error']:
            j.logger.log('Could not send rogerthat message')
            return
        else:
            message_id = result['result']
            return message_id

def escalateL1(watchdogevent):
    if not j.tools.watchdog.manager.inAlert(watchdogevent):
        watchdogevent.escalationstate = 'L1'
        contact1 = redis_client.hget('contacts', '1')
        message = str(watchdogevent)
        message_id = _send_message(message, [contact1,])
        watchdogevent.message_id = message_id
        j.tools.watchdog.manager.setAlert(watchdogevent)

def escalateL2(watchdogevent):
    if watchdogevent.escalationstate == 'L1':
        watchdogevent.escalationstate = 'L2'
        contacts = redis_client.hgetall('contacts')
        message = str(watchdogevent)
        message_id = _send_message(message, [contacts['2'], contacts['3']])
        watchdogevent.message_id = message_id
        j.tools.watchdog.manager.setAlert(watchdogevent)

def escalateL3(watchdogevent):
    if watchdogevent.escalationstate == 'L2':
        watchdogevent.escalationstate = 'L3'
        contacts = redis_client.hgetall('contacts')['all'].split(',')
        message = str(watchdogevent)
        message_id = _send_message(message, contacts)
        watchdogevent.message_id = message_id
        j.tools.watchdog.manager.setAlert(watchdogevent)


text: A simple POC that initiates motion-based lock and buzzer.


text:
Countly is an innovative, real-time, open source mobile analytics application. It collects data from mobile phones, and visualizes this information to analyze mobile application usage and end-user behavior. There are two parts of Countly: the server that collects and analyzes data, and mobile SDK that sends this data (for iOS & Android).

Countly:

- [Countly (Countly)](https://count.ly)

Countly Server;

- [Countly Server (countly-server)](https://github.com/Countly/countly-server)

Titanium Countly Messaging Modules
- [Countly Titanium Android Messaging Module](https://github.com/dieskim/countly-sdk-appcelerator-titanium-android)
- [Countly Titanium iOS Messaging Module](https://github.com/dieskim/countly-sdk-appcelerator-titanium-ios)

Other Countly SDK repositories;

- [Countly Android SDK (countly-sdk-android)](https://github.com/Countly/countly-sdk-android)
- [Countly iOS SDK (countly-sdk-ios)](https://github.com/Countly/countly-sdk-ios)

Countly SDK Guides;
- [Countly Android Messaging Guide](http://resources.count.ly/docs/countly-sdk-for-android#setting-up-push-notifications)
- [Countly iOS Messaging Guide](http://resources.count.ly/docs/countly-sdk-for-ios-and-os-x#setting-up-push-notifications)

## This Titanium Android module is written to take use of all the Count.ly functions - including events, userData, Messaging and now Crash Reports!
### It is written with functions as close to the Android module as possible to create uniformed functions.
### Please note that this Module is under development.
### Please log issues via github issues
### Any pull requests and suggestions welcome!
### Author: Dieskim of (Kiteplans.info)](https://www.kiteplans.info)
### Development Sponsors:
#### - Messaging: http://Hamsane.com - Friend who loves your way of working - Thanks!
#### - Crash Reports: http://www.count.ly

### TEST APP - easy Test app you can download, build and run to test all the functions in this modul [Countly Appcelerator Module Test App](https://github.com/dieskim/ly-count-appcelerator)
https://github.com/dieskim/ly-count-appcelerator

## Installation

1. Go to: https://github.com/dieskim/countly-sdk-appcelerator-titanium-android
2. Download: count.ly-messaging-android-x.x.x.zip
3. Move Zip to root of your Application
4. Build Application - Titanium will automatically extract the module

### Register your module with your application by editing `tiapp.xml` and adding your module.

```
<modules>
<module platform="android">count.ly.messaging</module>
</modules>
```

## Usage

**Require the Count.ly Module**
```
var Countly = require('count.ly.messaging');
```

** Set App Name in AndroidManifest.xml
- Follow the [Titanium App Name Localization Guide](http://docs.appcelerator.com/titanium/3.0/#!/guide/Internationalization-section-29004892_Internationalization-AppNameLocalization) to set android:label="@string/app_name" in your AndroidManifest.xml - else you will receive the error below

```
[WARN] :   ResourceType: No package identifier when getting value for resource number 0x00000000

[ERROR] :  MessagingAdapter: Couldn't store configuration in Countly Messaging
```

*Enable Debugginh**
```
// enableDebug if needed
Countly.enableDebug();
```

### SETUP Count.ly WITHOUT Messaging - Push

**Start Count.ly on own server without Messaging**
```
Countly.start('APP_KEY','http://YOUR_HOST.com');
```

**Start Count.ly on cloud without Messaging**
```
Countly.startOnCloud('APP_KEY');
```

### SETUP Count.ly WITH Messaging - Push

**Set Push Setup functions**
```
// ADD EVENTLISTENTER AND FUNCTION TO MODULE
Countly.addEventListener('receivePush',function(pushMessageData){

// *** IN ANDROID THERE IS NO NEED TO RUN recordPushOpen as it happens Automaticall on the Native Module side **//

// Ti.API.info Raw pushMessage
Ti.API.info("Received Push");
Ti.API.info(JSON.stringify(pushMessageData));

var pushID = pushMessageData.id;
var pushAlertMessage = pushMessageData.message;
var pushType = pushMessageData.type || 'unknownType';
var pushLink = pushMessageData.link || '';
var pushSound = pushMessageData.sound || '';
var pushData = pushMessageData.data;						// all message data if needed

Ti.API.info("pushID: " + pushID + " pushAlertMessage: " + pushAlertMessage + "pushType: " + pushType + " pushData: " + pushData + " pushSound: " + pushSound);

if (pushType == "hasLink"){

///////////////////////////////////////////////////////////
//              SHOW AN LINK ALERT HERE                 //
// 1. Use info  - pushType
//              - pushLink
//              - pushAlertMessage
// 2. Once user Takes action log action with recordPushAction using pushID

// Count.ly record Push Action
// Countly.recordPushAction(pushID);

}else if (pushType == "hasReview"){

// SHOW AN REVIEW ALERT HERE

}else if (pushType == "hasMessage"){

// SHOW NORMAL ALERT HERE

};

});
```

**START Countly with Messaging - DEVELOPMENT TEST**
```
// START Countly with Messaging - DEVELOPMENT TEST
Countly.startMessagingTest('COUNLY_APP_KEY','http://yourserver.com','GCM_PROJECT_NUMBER');
```

**START Countly with Messaging - PRODUCTION**
```
// START Countly with Messaging - PRODUCTION
Countly.startMessaging('COUNLY_APP_KEY','http://yourserver.com','GCM_PROJECT_NUMBER');
```

### User Locations

```
// Countly Set user location
var latitudeString = 12;
var longitudeString = 10;
Countly.setLocation(latitudeString,longitudeString);
```
- Takes two strings: latitudeString and longitudeString of 2 digit lengths

### Events

**Set any of the following Fields in an Object**

```
var segmentation = {device:"iPhone 4S", country:"USA"};
var eventData = {name: "keySegmentationCountSum", segmentation:segmentation, count: 1, sum: 0.99};
```
- name (required) : Name of the event to track
- _(example - Track clicks on the help button "clickedHelp" )_
- count (required) : Number to increment the event in the db
- _(example - User purchases item increment by 1 )_
- sum : If the event is tied to an overall numerical data, such as a purchase, we can use sum to keep track of that
- _(example - 0.99)_
- segmentation : Categorization of the event
- _(example - User is from USA and uses an iPhone 4S so the segmentation will be {device:"iPhone 4S", country:"USA"} )_

**Track Events Examples**

```
var segmentation = {device:"iPhone 4S", country:"USA"};

Ti.API.log("Send keyCount Event");
var eventData = {name: "keyCount", count: 1};
Countly.event(eventData);

Ti.API.log("Send keyCountSum Event");
var eventData = {name: "keyCountSum", count: 1, sum: 0.99};
Countly.event(eventData);

Ti.API.log("Send keySegmentationCount Event");
var eventData = {name: "keySegmentationCount", segmentation:segmentation, count: 1};
Countly.event(eventData);

Ti.API.log("Send keySegmentationCountSum Event");
var eventData = {name: "keySegmentationCountSum", segmentation:segmentation, count: 1, sum: 0.99};
Countly.event(eventData);
```

### UserData

**Set any of the following Fields in an Object**

**Set userData{} as information about user
**Possible keys are:

- name - (String) providing user's full name
- username - (String) providing user's nickname
- email - (String) providing user's email address
- organization - (String) providing user's organization's name where user works
- phone - (String) providing user's phone number
- picture - (String) providing WWW URL to user's avatar or profile picture
- picturePath - (String) providing local path to user's avatar or profile picture
- gender - (String) providing user's gender as M for male and F for female
- byear - (int) providing user's year of birth as integer
```
var userData = {	name: "testName",
username: "testUsername",
email: "testemail@gmail.com",
organization: "testOrg",
phone: "testPhone",
picture: "https://count.ly/wp-content/uploads/2014/10/logo.png",
picturePath: "/images/appicon.png",
gender: "M",
byear: "1980",
};
```

**Set customUserData{} as information about user with custom properties
**In customUserData you can provide any string key values to be stored with user

```
var customUserData = {	key1: "value1",
key2:"value2",
};
```

**Set Userdata as set in userData and customData
**Can contain both userData and customData - or just userdata

```
Ti.API.log("Set UserData");
var args = {	userData:userData,
customUserData:customUserData,
};

Countly.userData(args);
```

### Crash Reporting
** There are 3 types of Crashes that can be logged:
- Fatal Native Exception/Crash - Automatically logged via Count.ly SDK
- Fatal Javascript Exception/Crash - Automatically logged via Module after one function added (Titanium SDK > 4.1 only)
- Non-Fatal Javascript Exception/Crash - Manually Logged by user in App code as needed via- Countly.recordHandledException
- The user can also add entries to Crash logs in app code via - Countly.addCrashLog
- 4 CrashTest are built in to help test crash reporting

**Start Crash Reporting - WITH or WITHOUT Segments**
- Segments can be added as key values - these are sent with every crash
- When Crash Reporting is started the Countly SDK will automatically catch and log Fatal Native Exception/Crash

```
// Start Crash Reporting - WITHOUT Segments
Countly.startCrashReporting();
```

```
// Start Crash Reporting - WITH Segments
// Add Keypairs to be added to every Crash that is logged for this app
// Example: FacebookSDK: "4.0"
var segments = { 	FacebookSDK: "4.0",
key2: "value2",
};

Countly.startCrashReportingWithSegments(segments);
```

**Add Fatal Javascript Exception/Crash Support**
- Automatically logged via Module after one function added (Titanium SDK > 4.1 only)
- This crash type will NOT QUIT out of app in Development (shows red error box), but will QUIT out of app in Production.
- Error will be logged on Javascript side and sent to native module to send to Countly
- For this to work you for need to add the uncaughtException listener to the app
- Then run the Countly.recordUncaughtException inside the

```
Ti.App.addEventListener('uncaughtException', function(exception) {

Ti.API.log("Javascript Fatal Exception");   // remove if you want

// send exception to Countly
Countly.recordUncaughtException(exception);

});

```

**Add Non-Fatal Javascript Exception/Crash Support**
- This is a Crash Report you can Define and send Manually very much like an error log
- run the Countly.recordHandledException function to manually log a non-fatal crash report

```
// Non-Fatal Javascript Exception/Crash Manually via  to Countly
Countly.recordHandledException(exception);
```

**Add Crash Log Entry**
- add Keypairs to a crash log as needed throughout your app
- will be sent with crash log when/if app crashes
- Example: Button Clicked, Audio Downloaded etc

```
Ti.API.log("addCrashLog");

var crashLog = {    yourMessage: "Error Message",
key1: "value1",
};

Countly.addCrashLog(crashLog);
```

**Crash Test**
- There are 4 types of Crash Test Built in
- crashTest 3 will cause a native error and exit out of app - On Android Create a button to Run the Function and run it a few times quickly to make it exit the app
```
\\ NATIVE CRASH TESTS - Exits out of app and logs to Countly
Countly.crashTest(3);

\\ Other Crash Tests - Do not exit out of app - get logged via Ti.App.addEventListener uncaughtException
Countly.crashTest(1);
Countly.crashTest(2);
Countly.crashTest(4);
```

## Author

Author: Dieskim of (Kiteplans.info)](https://www.kiteplans.info)

## License

MIT as in License.txt


text:
package org.speedfirst.leetcode.math;

import java.util.LinkedList;
import java.util.Queue;

/**
 * Given the k-th number which only has 3, 5 or 7 factors. The list
 * looks like:
 * <pre>
 *     1, 3, 5, 7, 9, 15, 21, 25, 27, ...
 * </pre>
 * @author jiankuan
 * @since 1/13/15
 */
public class GetKthMagicNumber {

    public int  getKthMagicNumber(int k) {

        if (k <= 0) {
            throw new IllegalArgumentException();
        }

        Queue<Integer> q3 = new LinkedList<>();
        Queue<Integer> q5 = new LinkedList<>();
        Queue<Integer> q7 = new LinkedList<>();

        q3.offer(3);
        q5.offer(5);
        q7.offer(7);

        int val = 1;
        while (k > 1) {
            Queue<Integer> q = getQueueWithMinValue(q3, q5, q7);
            val = q.poll();
            q3.offer(val * 3);  // Note avoid duplication here. For instance, you got 5 from q5, do not append 5 * 3 to q3
                                // because before you have already append 3 * 5 to q5.
            if (q == q5 || q == q7) {
                q5.offer(val * 5);
                if (q == q7) {
                    q7.offer(val * 7);
                }
            }
            k--;
        }
        return val;
    }

    private int[] buffer = new int[3];

    private Queue<Integer> getQueueWithMinValue(Queue<Integer> q3, Queue<Integer> q5, Queue<Integer> q7) {
        buffer[0] = q3.peek();
        buffer[1] = q5.peek();
        buffer[2] = q7.peek();

        int minIdx = 0;
        for (int i = 1; i < 3; i++) {
            if (buffer[minIdx] > buffer[i]) {
                minIdx = i;
            }
        }

        switch (minIdx) {
            case 0:
                return q3;
            case 1:
                return q5;
            case 2:
                return q7;
        }

        return null;
    }

    public static void main(String[] args) {
        GetKthMagicNumber sol = new GetKthMagicNumber();
        System.out.println(sol.getKthMagicNumber(1));
        System.out.println(sol.getKthMagicNumber(2));
        System.out.println(sol.getKthMagicNumber(3));
        System.out.println(sol.getKthMagicNumber(4));
        System.out.println(sol.getKthMagicNumber(5));
        System.out.println(sol.getKthMagicNumber(6));
        System.out.println(sol.getKthMagicNumber(7));
        System.out.println(sol.getKthMagicNumber(8));
        System.out.println(sol.getKthMagicNumber(9));
        System.out.println(sol.getKthMagicNumber(10));
        System.out.println(sol.getKthMagicNumber(11));
        System.out.println(sol.getKthMagicNumber(12));
        System.out.println(sol.getKthMagicNumber(13));
        System.out.println(sol.getKthMagicNumber(14));
        System.out.println(sol.getKthMagicNumber(15));
    }
}


text:
1. Clone the Angular-CLI repo. A local copy works just fine.
1. Create an upstream remote:

```bash
$ git remote add upstream https://github.com/angular/angular-cli.git
```

# Caretaker

The caretaker should triage issues, merge PR, and sheppard the release.

Caretaker calendar can be found [here](https://calendar.google.com/calendar/embed?src=angular.io_jf53juok1lhpm84hv6bo6fmgbc%40group.calendar.google.com&ctz=America%2FLos_Angeles).

Each shift consists of two caretakers. The primary caretaker is responsible for
merging PRs to master and patch whereas the secondary caretaker is responsible
for the release. Primary-secondary pairs are as follows:

| Primary | Secondary |
| ------- | --------- |
| Alan    | Doug      |
| Charles | Keen      |
| Filipe  | Joey      |

## Merging PRs

The list of PRs which are currently ready to merge (approved with passing status checks) can
be found with [this search](https://github.com/angular/angular-cli/pulls?q=is%3Apr+is%3Aopen+label%3A%22PR+action%3A+merge%22+-is%3Adraft).
This list should be checked daily and any ready PRs should be merged. For each PR, check the
`target` label to understand where it should be merged to. You can find which branches a specific
PR will be merged into with the `yarn ng-dev pr check-target-branches <pr>` command.

When ready to merge a PR, run the following command:

```
yarn ng-dev pr merge <pr>
```

### Maintaining LTS branches

Releases that are under Long Term Support (LTS) are listed on [angular.io](https://angular.io/guide/releases#support-policy-and-schedule).

Since there could be more than one LTS branch at any one time, PR authors who want to
merge commits into LTS branches must open a pull request against the specific base branch they'd like to target.

In general, cherry picks for LTS should only be done if it meets one of the criteria below:

1. It addresses a critical security vulnerability.
2. It fixes a breaking change in the external environment.
   For example, this could happen if one of the dependencies is deleted from NPM.
3. It fixes a legitimate failure on CI for a particular LTS branch.

# Release

For each version to be released, check out the associated branch and:

1. Increment the CLI version number in
   [`package.json`](https://github.com/angular/angular-cli/blob/master/package.json).
1. Update `Angular` version in
   [`packages/schematics/angular/utility/latest-versions.ts`](https://github.com/angular/angular-cli/blob/master/packages/schematics/angular/utility/latest-versions.ts)
   to match the lastest framework patch version for the associated minor.
   - This number _usually_ aligns with the CLI version **but not always**. Framework may have
     required a hotfix release, which could desync the two version numbers. Check the latest version
     with `yarn info @angular/core dist-tags` or look at the most recent FW release in the
     [#news channel](https://angular-team.slack.com/archives/C0439GUGA).

As commits are cherry-picked when PRs are merged, creating the release should be a matter of creating a tag.

```bash
git add packages/schematics/angular/utility/latest-versions.ts package.json
git commit -m 'release: vXX'
git tag -a 'vXX' -m 'release: tag vXX'
```

The package versions we are about to publish are derived from `version` in the root
[`package.json`](https://github.com/angular/angular-cli/blob/master/package.json#L3). Double check that the versions are correct by running the
following command.

```bash
yarn admin packages --releaseCheck
```

Now push the commit and the tag to the upstream repository. **Make sure to use
`--follow-tags`, as tags need to be pushed immediately or CI may fail!**

```bash
git push upstream --follow-tags
```

## Authenticating

**This can ONLY be done by a Google employee.**

Log in to the Wombat publishing service using your own github and google.com
account to publish. This enforces the login is done using 2Factor auth.

Run `npm login --registry https://wombat-dressing-room.appspot.com`:

1. In the new browser tab, the registry app will ask you to connect with GitHub to create a token
1. After connecting with github, you will be redirected to create a token
1. Upon redirect, an auth token is added to your ~/.npmrc for the proxy

After closing the tab, you have successfully logged in, it is time to publish.

**NOTE: After publishing, remove the token added to your `~/.npmrc` file to logout.**

## Publishing

**This can ONLY be done by a Google employee.**

**Wait for CI to be green after pushing the release commit.**

For the first release of a major version, follow the instructions in
[Publishing a Major Version](#publishing-a-major-version) section.

For non-major release, check out the patch branch (e.g. `9.1.x`), then run:

```bash
rm -rf node_modules/ && yarn install --frozen-lockfile # Reload dependencies
yarn admin publish --tag latest
```

If also publishing a prerelease, check out `master`, then run:

```bash
rm -rf node_modules/ && yarn install --frozen-lockfile # Reload dependencies
yarn admin publish --tag next
```

If also publish an LTS branch, check out that patch branch (e.g. `8.3.x`), then
run:

**Make sure to update the NPM tag for the version you are releasing!**

```bash
rm -rf node_modules/ && yarn # Reload dependencies
yarn admin publish --tag v8-lts
```

## Release Notes

`yarn run -s admin changelog` takes `from` and `to` arguments which are any valid git
ref.

For example, running the following command will output the release notes on
stdout between v1.2.3 and 1.2.4:

```bash
yarn run -s admin changelog --from=v1.2.3 --to=v1.2.4
```

Copy the output (you can use `| pbcopy` on MacOS or `| xclip` on Linux) and
paste the release notes on [GitHub](https://github.com/angular/angular-cli/releases)
for the tag just released.

If you have an API token for GitHub you can create a draft automatically by
using the `--githubToken` flag. You just then have to confirm the draft.

> **Tags containing `next` or `rc` should be marked as pre-release.**

## Post-release

Don't forget to update the Slack [#tools](https://angular-team.slack.com/archives/C46U16D4Z) channel
topic with the next caretaker shift from the
[calendar](https://calendar.google.com/calendar/embed?src=angular.io_jf53juok1lhpm84hv6bo6fmgbc%40group.calendar.google.com&ctz=America%2FLos_Angeles).

## Publishing a Major Version

For the first release of a major version, say `v10.0.0`, checkout the major branch
(i.e. `10.0.x`), then run:

```bash
yarn # Reload dependencies
yarn admin publish --tag next # a major release is always tagged as next initially
```

Confirm with downstream repositories (Components, etc) that everything is ok.
Once the release is stable, wait for Framework to retag their packages, then
retag the CLI packages as `latest`.
The command below will automatically retag stable packages as well as experimental
packages.

```bash
yarn admin dist-tag --version 10.0.0 --tag latest
```

## Changing shifts

If you need to update the
[caretaker calendar](https://calendar.google.com/calendar/embed?src=angular.io_jf53juok1lhpm84hv6bo6fmgbc%40group.calendar.google.com&ctz=America%2FLos_Angeles)
to modify shifts, **make sure you are logged in as your @angular.io account** and
click the "+ Google Calendar" button in the bottom right to add it to your Google
Calendar account. You should then be able to find and modify events on
calendar.google.com. The calendar is a part of the `angular.io` organization, so
events can only be modified by users in the same organization.


text:
package com.alibaba.druid.bvt.pool;

import org.junit.Assert;
import junit.framework.TestCase;

import com.alibaba.druid.pool.DruidDataSource;

/**
 * 这个场景测试initialSize > maxActive
 *
 * @author wenshao<szujobs@hotmail.com>
 */
public class DruidDataSourceTest_maxActive3 extends TestCase {

    private DruidDataSource dataSource;

    protected void setUp() throws Exception {
        dataSource = new DruidDataSource();
        dataSource.setUrl("jdbc:mock:xxx");
        dataSource.setTestOnBorrow(false);
        dataSource.setFilters("stat");
        dataSource.setMinIdle(100);
        dataSource.setMaxActive(10);

    }

    protected void tearDown() throws Exception {
        dataSource.close();
    }

    public void test_error() throws Exception {
        Exception error = null;
        try {
            dataSource.init();
        } catch (IllegalArgumentException e) {
            error = e;
        }
        Assert.assertNotNull(error);
    }
}


text:
require "spec_helper"

describe Alextra::SimpleCard do
end


text:
{{title}}

Strappy is The AngularJS/Bootstrap/FontAwesome bootstrapper, brought to you by the folks at Lotpath.  Check out the Readme for more info.


text:
package jp.co.opentone.bsol.linkbinder.dao.impl;

import java.util.Date;
import java.util.GregorianCalendar;

import javax.annotation.Resource;

import org.junit.Test;

import jp.co.opentone.bsol.framework.core.dao.Entity;
import jp.co.opentone.bsol.framework.core.dao.KeyDuplicateException;
import jp.co.opentone.bsol.framework.core.dao.RecordNotFoundException;
import jp.co.opentone.bsol.framework.core.dao.StaleRecordException;
import jp.co.opentone.bsol.framework.test.AbstractDaoTestCase;
import jp.co.opentone.bsol.linkbinder.dto.CorresponReadStatus;
import jp.co.opentone.bsol.linkbinder.dto.User;
import jp.co.opentone.bsol.linkbinder.dto.code.ReadStatus;

/**
 * @link CorresponReadStatusDaoImpl}のテストケース.
 * @author opentone
 */
public class CorresponReadStatusDaoImplTest extends AbstractDaoTestCase {

    /**
     * テスト対象.
     */
    @Resource
    private CorresponReadStatusDaoImpl dao;

    /**
     * {@link jp.co.opentone.bsol.linkbinder.dao.AbstractDao#c.framework.core.daoc.framework.core.dao.Entity)} のためのテスト・メソッド.
     */
    @Test
    public void testCreate() throws Exception {
        // ログインユーザーの準備
        User login = new User();
        login.setEmpNo("ZZA02");

        // 登録内容の準備
        CorresponReadStatus status = new CorresponReadStatus();
        status.setEmpNo("ZZA02");
        status.setCorresponId(2L);
        status.setReadStatus(ReadStatus.READ);
        status.setCreatedBy(login);
        status.setUpdatedBy(login);

        // 登録
        Long id = new Long(0L);

        // id(自動採番)を最大値にするためのループ
        while (true) {
            try {
                id = dao.create(status);
                break;
            } catch (KeyDuplicateException e) {
                continue;
            }
        }

        assertNotNull(id);

        CorresponReadStatus actual = dao.findById(id);

        assertEquals(id, actual.getId());
        assertEquals(status.getEmpNo(), actual.getEmpNo());
        assertEquals(status.getCorresponId(), actual.getCorresponId());
        assertEquals(status.getReadStatus(), actual.getReadStatus());
        assertEquals(status.getCreatedBy().getEmpNo(), actual.getCreatedBy().getEmpNo());
        assertEquals(status.getUpdatedBy().getEmpNo(), actual.getUpdatedBy().getEmpNo());
        assertEquals(Long.valueOf(1L), actual.getVersionNo());
        assertEquals(Long.valueOf(0L), actual.getDeleteNo());
        assertNotNull(actual.getCreatedAt());
        assertNotNull(actual.getUpdatedAt());
    }

    /**
     * 一意エラーの場合、{@link KeyDuplicateException}が発生することを検証する.
     * @throws Exception
     */
    @Test(expected = KeyDuplicateException.class)
    public void testCreateDuplicate() throws Exception {
        // ログインユーザーの準備
        User login = new User();
        login.setEmpNo("ZZA01");

        // 更新内容の準備
        CorresponReadStatus status = new CorresponReadStatus();
        status.setEmpNo("ZZA01");
        status.setCorresponId(1L);
        status.setReadStatus(ReadStatus.READ);
        status.setCreatedBy(login);
        status.setUpdatedBy(login);

        dao.create(status);

        fail("例外が発生していない");
    }

    /**
     * {@link jp.co.opentone.bsol.linkbinder.dao.Abs.framework.core.daoe( Entity )} のためのテスト・メソッド.
     */
    @Test
    public void testUpdate() throws Exception {
        // ログインユーザーの準備
        User login = new User();
        login.setEmpNo("ZZA03");

        // 更新内容の準備
        CorresponReadStatus status = new CorresponReadStatus();
        status.setId(3L);
        status.setReadStatus(ReadStatus.NEW);
        status.setCreatedBy(login);
        status.setUpdatedBy(login);
        status.setVersionNo(0L);

        Integer resultCount = dao.update(status);
        assertEquals(new Integer(1), resultCount);

        CorresponReadStatus actual = dao.findById(status.getId());

        assertEquals(status.getId(), actual.getId());
        assertEquals("ZZA02", actual.getEmpNo()); // Excelデータ参照
        assertEquals(Long.valueOf(1L), actual.getCorresponId()); // Excelデータ参照
        assertEquals(status.getReadStatus(), actual.getReadStatus());
        assertEquals("ZZA02", actual.getCreatedBy().getEmpNo()); // Excelデータ参照
        assertEquals(status.getUpdatedBy().getEmpNo(), actual.getUpdatedBy().getEmpNo());
        assertEquals(Long.valueOf(1L), actual.getVersionNo());
        assertEquals(Long.valueOf(0L), actual.getDeleteNo());
        assertNotNull(actual.getCreatedAt());
        assertNotNull(actual.getUpdatedAt());

        Date createDate = new GregorianCalendar(2009, 3, 2, 10, 20, 31).getTime(); // Excelデータ参照
        Date oldDate = new GregorianCalendar(2009, 3, 2, 10, 40, 31).getTime();

        assertEquals(createDate, actual.getCreatedAt());
        assertFalse(oldDate.equals(actual.getUpdatedAt()));
    }

    /**
     * {@link jp.co.opentone.bsol.linkbinder.da.framework.core.daoupdate( Entity )} のためのテスト・メソッド.
     * レコードが存在しない場合に、{@link StaleRecordException}が発生することを検証する.
     * @throws Exception
     */
    @Test(expected = StaleRecordException.class)
    public void testUpdateRecordNotFound() throws Exception {
        // ログインユーザーの準備
        User login = new User();
        login.setEmpNo("ZZA03");

        // 更新内容の準備
        CorresponReadStatus status = new CorresponReadStatus();
        status.setId(-1L);
        status.setReadStatus(ReadStatus.NEW);
        status.setCreatedBy(login);
        status.setUpdatedBy(login);
        status.setVersionNo(0L);

        dao.update(status);
        fail("例外が発生していない");
    }

    /**
     * {@link jp.co.opentone.bsol.jcot.framework.core.daotDao#update(Entity)} のためのテスト・メソッド.
     */
    @Test
    public void testUpdateByCorresponId_01() throws Exception {

        // ログインユーザーの準備
        User login = new User();
        login.setEmpNo("ZZA01");

        // 更新内容の準備
        CorresponReadStatus status = new CorresponReadStatus();

        status.setCorresponId(1L);
        status.setReadStatus(ReadStatus.NEW);
        status.setCreatedBy(login);
        status.setUpdatedBy(login);

        Integer resultCount = dao.updateByCorresponId(status);
        assertEquals(new Integer(3), resultCount);

        CorresponReadStatus actual = dao.findById(3L);

        assertEquals(Long.valueOf(3), actual.getId());
        assertEquals("ZZA02", actual.getEmpNo()); // Excelデータ参照
        assertEquals(Long.valueOf(1L), actual.getCorresponId()); // Excelデータ参照
        assertEquals(status.getReadStatus(), actual.getReadStatus());
        assertEquals("ZZA02", actual.getCreatedBy().getEmpNo()); // Excelデータ参照
        assertEquals(status.getUpdatedBy().getEmpNo(), actual.getUpdatedBy().getEmpNo());
        assertEquals(Long.valueOf(1L), actual.getVersionNo());
        assertEquals(Long.valueOf(0L), actual.getDeleteNo());
        assertNotNull(actual.getCreatedAt());
        assertNotNull(actual.getUpdatedAt());

//        Date createDate = new GregorianCalendar(2009, 3, 2, 10, 20, 31).getTime(); // Excelデータ参照
        Date oldDate = new GregorianCalendar(2009, 3, 2, 10, 40, 31).getTime();

//        assertEquals(createDate, actual.getCreatedAt());
        assertFalse(oldDate.equals(actual.getUpdatedAt()));
    }

    /**
     * {@link jp.co.opentone.bsol.framework.core.daostractDao#update(Entity)} のためのテスト・メソッド.
     */
    @Test
    public void testUpdateByCorresponId_02() throws Exception {

        // ログインユーザーの準備
        User login = new User();
        login.setEmpNo("ZZA01");

        // 更新内容の準備
        CorresponReadStatus status = new CorresponReadStatus();

        status.setCorresponId(3L);
        status.setReadStatus(ReadStatus.NEW);
        status.setCreatedBy(login);
        status.setUpdatedBy(login);

        Integer resultCount = dao.updateByCorresponId(status);
        assertEquals(new Integer(1), resultCount);

        CorresponReadStatus actual = dao.findById(6L);

        assertEquals(Long.valueOf(6), actual.getId());
        assertEquals("ZZA01", actual.getEmpNo()); // Excelデータ参照
        assertEquals(Long.valueOf(3L), actual.getCorresponId()); // Excelデータ参照
        assertEquals(status.getReadStatus(), actual.getReadStatus());
        assertEquals("ZZA01", actual.getCreatedBy().getEmpNo()); // Excelデータ参照
        assertEquals(status.getUpdatedBy().getEmpNo(), actual.getUpdatedBy().getEmpNo());
        assertEquals(Long.valueOf(2L), actual.getVersionNo());
        assertEquals(Long.valueOf(0L), actual.getDeleteNo());
        assertNotNull(actual.getCreatedAt());
        assertNotNull(actual.getUpdatedAt());

//        Date createDate = new GregorianCalendar(2009, 3, 2, 10, 20, 31).getTime(); // Excelデータ参照
        Date oldDate = new GregorianCalendar(2009, 3, 2, 10, 40, 31).getTime();

//        assertEquals(createDate, actual.getCreatedAt());
        assertFalse(oldDate.equals(actual.getUpdatedAt()));
    }

    /**
     * {@link jp.c.framework.core.daoao.AbstractDao#update(Entity)} のためのテスト・メソッド.
     * 排他チェックにかかった場合、{@link StaleRecordException}が発生することを検証する.
     * @throws Exception
     */
    @Test(expected = StaleRecordException.class)
    public void testUpdateVersionNo() throws Exception {
        // ログインユーザーの準備
        User login = new User();
        login.setEmpNo("ZZA03");

        // 更新内容の準備
        CorresponReadStatus status = new CorresponReadStatus();
        status.setId(3L);
        status.setReadStatus(ReadStatus.NEW);
        status.setCreatedBy(login);
        status.setUpdatedBy(login);
        // 排他
        status.setVersionNo(9L);

        dao.update(status);

        fail("例外が発生していない");
    }

    /**
     * {@link jp.co.opentone.bsol.linkbinder.dao.AbstractDao#findById(java.lang.Long)} のためのテスト・メソッド.
     */
    @Test
    public void testFindById() throws Exception {
        CorresponReadStatus actual = dao.findById(1L);

        assertDataSetEquals(newDataSet("CorresponReadStatusDaoImplTest_testFindById_expected.xls"),
                            actual);
    }

    /**
     * {@link jp.co.opentone.bsol.linkbinder.dao.AbstractDao#findById(java.lang.Long)} のためのテスト・メソッド.
     */
    @Test
    public void testFindByEmpNo() throws Exception {
        CorresponReadStatus actual = dao.findByEmpNo(1L, "ZZA01");

        assertDataSetEquals(newDataSet("CorresponReadStatusDaoImplTest_testFindByEmpNo_expected.xls"),
                            actual);
    }

    /**
     * {@link jp.co.opentone.bsol.linkbinder.dao.AbstractDao#findById(java.lang.Long)} のためのテスト・メソッド.
     * (存在しないID)
     */
    @Test(expected = RecordNotFoundException.class)
    public void testFindByIdRecordNotFound() throws Exception {
        dao.findById(-1L);
        fail("例外が発生していない");
    }

    /**
     * {@link jp.co.opentone.bsol.linkbinder.dao.AbstractDao#findById(java.lang.Long)} のためのテスト・メソッド.
     * (削除済みレコード)
     */
    @Test(expected = RecordNotFoundException.class)
    public void testFindByIdDeleteRecord() throws Exception {
        dao.findById(2L);
        fail("例外が発生していない");
    }
}


text:
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <winpr/crt.h>
#include <winpr/synch.h>
#include <winpr/ssl.h>
#include <winpr/thread.h>

#ifdef WITH_OPENSSL

#include <openssl/ssl.h>
#include <openssl/err.h>

#include "../log.h"
#define TAG WINPR_TAG("utils.ssl")

static BOOL g_winpr_openssl_initialized_by_winpr = FALSE;

/**
 * Note from OpenSSL 1.1.0 "CHANGES":
 * OpenSSL now uses a new threading API. It is no longer necessary to
 * set locking callbacks to use OpenSSL in a multi-threaded environment.
 */

#if (OPENSSL_VERSION_NUMBER < 0x10100000L)

#define WINPR_OPENSSL_LOCKING_REQUIRED 1

static int g_winpr_openssl_num_locks = 0;
static HANDLE* g_winpr_openssl_locks = NULL;

struct CRYPTO_dynlock_value
{
	HANDLE mutex;
};

#if (OPENSSL_VERSION_NUMBER < 0x10000000L)
static unsigned long _winpr_openssl_id(void)
{
	return (unsigned long)GetCurrentThreadId();
}
#endif

static void _winpr_openssl_locking(int mode, int type, const char* file, int line)
{
	if (mode & CRYPTO_LOCK)
	{
		WaitForSingleObject(g_winpr_openssl_locks[type], INFINITE);
	}
	else
	{
		ReleaseMutex(g_winpr_openssl_locks[type]);
	}
}

static struct CRYPTO_dynlock_value* _winpr_openssl_dynlock_create(const char* file, int line)
{
	struct CRYPTO_dynlock_value* dynlock;

	if (!(dynlock = (struct CRYPTO_dynlock_value*) malloc(sizeof(struct CRYPTO_dynlock_value))))
		return NULL;

	if (!(dynlock->mutex = CreateMutex(NULL, FALSE, NULL)))
	{
		free(dynlock);
		return NULL;
	}

	return dynlock;
}

static void _winpr_openssl_dynlock_lock(int mode, struct CRYPTO_dynlock_value* dynlock, const char* file, int line)
{
	if (mode & CRYPTO_LOCK)
	{
		WaitForSingleObject(dynlock->mutex, INFINITE);
	}
	else
	{
		ReleaseMutex(dynlock->mutex);
	}
}

static void _winpr_openssl_dynlock_destroy(struct CRYPTO_dynlock_value* dynlock, const char* file, int line)
{
	CloseHandle(dynlock->mutex);
	free(dynlock);
}

static BOOL _winpr_openssl_initialize_locking(void)
{
	int i, count;

	/* OpenSSL static locking */

	if (CRYPTO_get_locking_callback())
	{
		WLog_WARN(TAG, "OpenSSL static locking callback is already set");
	}
	else
	{
		if ((count = CRYPTO_num_locks()) > 0)
		{
			HANDLE* locks;

			if (!(locks = calloc(count, sizeof(HANDLE))))
			{
				WLog_ERR(TAG, "error allocating lock table");
				return FALSE;
			}

			for (i = 0; i < count; i++)
			{
				if (!(locks[i] = CreateMutex(NULL, FALSE, NULL)))
				{
					WLog_ERR(TAG, "error creating lock #%d", i);

					while (i--)
					{
						if (locks[i])
							CloseHandle(locks[i]);
					}

					free(locks);
					return FALSE;
				}
			}

			g_winpr_openssl_locks = locks;
			g_winpr_openssl_num_locks = count;
			CRYPTO_set_locking_callback(_winpr_openssl_locking);
		}
	}

	/* OpenSSL dynamic locking */

	if (CRYPTO_get_dynlock_create_callback() ||
			CRYPTO_get_dynlock_lock_callback()   ||
			CRYPTO_get_dynlock_destroy_callback())
	{
		WLog_WARN(TAG, "dynamic locking callbacks are already set");
	}
	else
	{
		CRYPTO_set_dynlock_create_callback(_winpr_openssl_dynlock_create);
		CRYPTO_set_dynlock_lock_callback(_winpr_openssl_dynlock_lock);
		CRYPTO_set_dynlock_destroy_callback(_winpr_openssl_dynlock_destroy);
	}

	/* Use the deprecated CRYPTO_get_id_callback() if building against OpenSSL < 1.0.0 */
#if (OPENSSL_VERSION_NUMBER < 0x10000000L)

	if (CRYPTO_get_id_callback())
	{
		WLog_WARN(TAG, "OpenSSL id_callback is already set");
	}
	else
	{
		CRYPTO_set_id_callback(_winpr_openssl_id);
	}

#endif
	return TRUE;
}

static BOOL _winpr_openssl_cleanup_locking(void)
{
	/* undo our static locking modifications */
	if (CRYPTO_get_locking_callback() == _winpr_openssl_locking)
	{
		int i;
		CRYPTO_set_locking_callback(NULL);

		for (i = 0; i < g_winpr_openssl_num_locks; i++)
		{
			CloseHandle(g_winpr_openssl_locks[i]);
		}

		g_winpr_openssl_num_locks = 0;
		free(g_winpr_openssl_locks);
		g_winpr_openssl_locks = NULL;
	}

	/* unset our dynamic locking callbacks */

	if (CRYPTO_get_dynlock_create_callback() == _winpr_openssl_dynlock_create)
	{
		CRYPTO_set_dynlock_create_callback(NULL);
	}

	if (CRYPTO_get_dynlock_lock_callback() == _winpr_openssl_dynlock_lock)
	{
		CRYPTO_set_dynlock_lock_callback(NULL);
	}

	if (CRYPTO_get_dynlock_destroy_callback() == _winpr_openssl_dynlock_destroy)
	{
		CRYPTO_set_dynlock_destroy_callback(NULL);
	}

#if (OPENSSL_VERSION_NUMBER < 0x10000000L)

	if (CRYPTO_get_id_callback() == _winpr_openssl_id)
	{
		CRYPTO_set_id_callback(NULL);
	}

#endif
	return TRUE;
}

#endif /* OpenSSL < 1.1.0 */

static BOOL CALLBACK _winpr_openssl_initialize(PINIT_ONCE once, PVOID param, PVOID* context)
{
	DWORD flags = param ? *(PDWORD)param : WINPR_SSL_INIT_DEFAULT;

	if (flags & WINPR_SSL_INIT_ALREADY_INITIALIZED)
	{
		return TRUE;
	}

#ifdef WINPR_OPENSSL_LOCKING_REQUIRED
	if (flags & WINPR_SSL_INIT_ENABLE_LOCKING)
	{
		if (!_winpr_openssl_initialize_locking())
		{
			return FALSE;
		}
	}
#endif
	/* SSL_load_error_strings() is void */
	SSL_load_error_strings();
	/* SSL_library_init() always returns "1" */
	SSL_library_init();
	g_winpr_openssl_initialized_by_winpr = TRUE;
	return TRUE;
}

/* exported functions */

BOOL winpr_InitializeSSL(DWORD flags)
{
	static INIT_ONCE once = INIT_ONCE_STATIC_INIT;
	return InitOnceExecuteOnce(&once, _winpr_openssl_initialize, &flags, NULL);
}

BOOL winpr_CleanupSSL(DWORD flags)
{
	if (flags & WINPR_SSL_CLEANUP_GLOBAL)
	{
		if (!g_winpr_openssl_initialized_by_winpr)
		{
			WLog_WARN(TAG, "ssl was not initialized by winpr");
			return FALSE;
		}

		g_winpr_openssl_initialized_by_winpr = FALSE;
#ifdef WINPR_OPENSSL_LOCKING_REQUIRED
		_winpr_openssl_cleanup_locking();
#endif
		CRYPTO_cleanup_all_ex_data();
		ERR_free_strings();
		EVP_cleanup();
		flags |= WINPR_SSL_CLEANUP_THREAD;
	}

#ifdef WINPR_OPENSSL_LOCKING_REQUIRED
	if (flags & WINPR_SSL_CLEANUP_THREAD)
	{
#if (OPENSSL_VERSION_NUMBER < 0x10000000L)
		ERR_remove_state(0);
#else
		ERR_remove_thread_state(NULL);
#endif
	}
#endif
	return TRUE;
}

#else

BOOL winpr_InitializeSSL(DWORD flags)
{
	return TRUE;
}

BOOL winpr_CleanupSSL(DWORD flags)
{
	return TRUE;
}

#endif


text:
using System;
using System.IO;

namespace Excelerator.Examples.Export
{
	public class ExportExampleBase
	{
		protected readonly string ExportExamplesPath = "Examples\\Export";

		protected void Iterate(Action<int> action, int maxValue)
		{
			for (var i = 0; i < maxValue; i++)
				action(i);
		}
	}
}


text:
namespace media {
namespace cast {
namespace transport {

enum RtcpMode {
  kRtcpCompound,     // Compound RTCP mode is described by RFC 4585.
  kRtcpReducedSize,  // Reduced-size RTCP mode is described by RFC 5506.
};

enum VideoCodec {
  kUnknownVideoCodec,
  kFakeSoftwareVideo,
  kVp8,
  kH264,
  kVideoCodecLast = kH264
};

enum AudioCodec {
  kUnknownAudioCodec,
  kOpus,
  kPcm16,
  kAudioCodecLast = kPcm16
};

struct RtpConfig {
  RtpConfig();
  ~RtpConfig();
  uint32 ssrc;
  int max_delay_ms;
  int payload_type;
  std::string aes_key;      // Binary string of size kAesKeySize.
  std::string aes_iv_mask;  // Binary string of size kAesBlockSize.
};

struct CastTransportRtpConfig {
  CastTransportRtpConfig();
  ~CastTransportRtpConfig();
  RtpConfig config;
  int max_outstanding_frames;
};

struct CastTransportAudioConfig {
  CastTransportAudioConfig();
  ~CastTransportAudioConfig();

  CastTransportRtpConfig rtp;
  AudioCodec codec;
  int frequency;
  int channels;
};

struct CastTransportVideoConfig {
  CastTransportVideoConfig();
  ~CastTransportVideoConfig();

  CastTransportRtpConfig rtp;
  VideoCodec codec;
};

// A combination of metadata and data for one encoded frame.  This can contain
// audio data or video data or other.
struct EncodedFrame {
  enum Dependency {
    // "null" value, used to indicate whether |dependency| has been set.
    UNKNOWN_DEPENDENCY,

    // Not decodable without the reference frame indicated by
    // |referenced_frame_id|.
    DEPENDENT,

    // Independently decodable.
    INDEPENDENT,

    // Independently decodable, and no future frames will depend on any frames
    // before this one.
    KEY,

    DEPENDENCY_LAST = KEY
  };

  EncodedFrame();
  ~EncodedFrame();

  // Convenience accessors to data as an array of uint8 elements.
  const uint8* bytes() const {
    return reinterpret_cast<uint8*>(string_as_array(
        const_cast<std::string*>(&data)));
  }
  uint8* mutable_bytes() {
    return reinterpret_cast<uint8*>(string_as_array(&data));
  }

  // Copies all data members except |data| to |dest|.
  // Does not modify |dest->data|.
  void CopyMetadataTo(EncodedFrame* dest) const;

  // This frame's dependency relationship with respect to other frames.
  Dependency dependency;

  // The label associated with this frame.  Implies an ordering relative to
  // other frames in the same stream.
  uint32 frame_id;

  // The label associated with the frame upon which this frame depends.  If
  // this frame does not require any other frame in order to become decodable
  // (e.g., key frames), |referenced_frame_id| must equal |frame_id|.
  uint32 referenced_frame_id;

  // The stream timestamp, on the timeline of the signal data.  For example, RTP
  // timestamps for audio are usually defined as the total number of audio
  // samples encoded in all prior frames.  A playback system uses this value to
  // detect gaps in the stream, and otherwise stretch the signal to match
  // playout targets.
  uint32 rtp_timestamp;

  // The common reference clock timestamp for this frame.  This value originates
  // from a sender and is used to provide lip synchronization between streams in
  // a receiver.  Thus, in the sender context, this is set to the time at which
  // the frame was captured/recorded.  In the receiver context, this is set to
  // the target playout time.  Over a sequence of frames, this time value is
  // expected to drift with respect to the elapsed time implied by the RTP
  // timestamps; and it may not necessarily increment with precise regularity.
  base::TimeTicks reference_time;

  // The encoded signal data.
  std::string data;
};

typedef std::vector<uint8> Packet;
typedef scoped_refptr<base::RefCountedData<Packet> > PacketRef;
typedef std::vector<PacketRef> PacketList;

typedef base::Callback<void(scoped_ptr<Packet> packet)> PacketReceiverCallback;

class PacketSender {
 public:
  // Send a packet to the network. Returns false if the network is blocked
  // and we should wait for |cb| to be called. It is not allowed to called
  // SendPacket again until |cb| has been called. Any other errors that
  // occur will be reported through side channels, in such cases, this function
  // will return true indicating that the channel is not blocked.
  virtual bool SendPacket(PacketRef packet, const base::Closure& cb) = 0;
  virtual ~PacketSender() {}
};

struct RtcpSenderInfo {
  RtcpSenderInfo();
  ~RtcpSenderInfo();
  // First three members are used for lipsync.
  // First two members are used for rtt.
  uint32 ntp_seconds;
  uint32 ntp_fraction;
  uint32 rtp_timestamp;
  uint32 send_packet_count;
  size_t send_octet_count;
};

struct RtcpReportBlock {
  RtcpReportBlock();
  ~RtcpReportBlock();
  uint32 remote_ssrc;  // SSRC of sender of this report.
  uint32 media_ssrc;   // SSRC of the RTP packet sender.
  uint8 fraction_lost;
  uint32 cumulative_lost;  // 24 bits valid.
  uint32 extended_high_sequence_number;
  uint32 jitter;
  uint32 last_sr;
  uint32 delay_since_last_sr;
};

struct RtcpDlrrReportBlock {
  RtcpDlrrReportBlock();
  ~RtcpDlrrReportBlock();
  uint32 last_rr;
  uint32 delay_since_last_rr;
};

// This is only needed because IPC messages don't support more than
// 5 arguments.
struct SendRtcpFromRtpSenderData {
  SendRtcpFromRtpSenderData();
  ~SendRtcpFromRtpSenderData();
  uint32 packet_type_flags;
  uint32 sending_ssrc;
  std::string c_name;
  uint32 ntp_seconds;
  uint32 ntp_fraction;
  uint32 rtp_timestamp;
};

inline bool operator==(RtcpSenderInfo lhs, RtcpSenderInfo rhs) {
  return lhs.ntp_seconds == rhs.ntp_seconds &&
         lhs.ntp_fraction == rhs.ntp_fraction &&
         lhs.rtp_timestamp == rhs.rtp_timestamp &&
         lhs.send_packet_count == rhs.send_packet_count &&
         lhs.send_octet_count == rhs.send_octet_count;
}

}  // namespace transport
}  // namespace cast
}  // namespace media

#endif  // MEDIA_CAST_TRANSPORT_CAST_TRANSPORT_CONFIG_H_