code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
/**
* ActivateRateCardCustomizations.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
*/
package com.google.api.ads.dfp.axis.v201306;
/**
* The action used to activate {@link RateCardCustomization} objects.
*/
public class ActivateRateCardCustomizations extends com.google.api.ads.dfp.axis.v201306.RateCardCustomizationAction implements java.io.Serializable {
public ActivateRateCardCustomizations() {
}
public ActivateRateCardCustomizations(
java.lang.String rateCardCustomizationActionType) {
super(
rateCardCustomizationActionType);
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof ActivateRateCardCustomizations)) return false;
ActivateRateCardCustomizations other = (ActivateRateCardCustomizations) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = super.equals(obj);
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = super.hashCode();
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(ActivateRateCardCustomizations.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201306", "ActivateRateCardCustomizations"));
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
| nafae/developer | modules/dfp_axis/src/main/java/com/google/api/ads/dfp/axis/v201306/ActivateRateCardCustomizations.java | Java | apache-2.0 | 2,796 |
<?php
namespace Elastica\Filter;
use Elastica\Exception\InvalidException;
/**
* Geo distance filter
*
* @category Xodoa
* @package Elastica
* @author Nicolas Ruflin <[email protected]>
* @link http://www.elasticsearch.org/guide/reference/query-dsl/geo-distance-filter.html
*/
abstract class AbstractGeoDistance extends AbstractFilter
{
const LOCATION_TYPE_GEOHASH = 'geohash';
const LOCATION_TYPE_LATLON = 'latlon';
/**
* Location type
*
* Decides if this filter uses latitude/longitude or geohash for the location.
* Values are "latlon" or "geohash".
*
* @var string
*/
protected $_locationType = null;
/**
* Key
*
* @var string
*/
protected $_key = null;
/**
* Latitude
*
* @var float
*/
protected $_latitude = null;
/**
* Longitude
*
* @var float
*/
protected $_longitude = null;
/**
* Geohash
*
* @var string
*/
protected $_geohash = null;
/**
* Create GeoDistance object
*
* @param string $key Key
* @param array|string $location Location as array or geohash: array('lat' => 48.86, 'lon' => 2.35) OR 'drm3btev3e86'
* @internal param string $distance Distance
*/
public function __construct($key, $location)
{
// Key
$this->setKey($key);
$this->setLocation($location);
}
/**
* @param string $key
* @return \Elastica\Filter\AbstractGeoDistance current filter
*/
public function setKey($key)
{
$this->_key = $key;
return $this;
}
/**
* @param array|string $location
* @return \Elastica\Filter\AbstractGeoDistance
* @throws \Elastica\Exception\InvalidException
*/
public function setLocation($location)
{
// Location
if (is_array($location)) { // Latitude/Longitude
// Latitude
if (isset($location['lat'])) {
$this->setLatitude($location['lat']);
} else {
throw new InvalidException('$location[\'lat\'] has to be set');
}
// Longitude
if (isset($location['lon'])) {
$this->setLongitude($location['lon']);
} else {
throw new InvalidException('$location[\'lon\'] has to be set');
}
} elseif (is_string($location)) { // Geohash
$this->setGeohash($location);
} else { // Invalid location
throw new InvalidException('$location has to be an array (latitude/longitude) or a string (geohash)');
}
return $this;
}
/**
* @param float $latitude
* @return \Elastica\Filter\AbstractGeoDistance current filter
*/
public function setLatitude($latitude)
{
$this->_latitude = (float) $latitude;
$this->_locationType = self::LOCATION_TYPE_LATLON;
return $this;
}
/**
* @param float $longitude
* @return \Elastica\Filter\AbstractGeoDistance current filter
*/
public function setLongitude($longitude)
{
$this->_longitude = (float) $longitude;
$this->_locationType = self::LOCATION_TYPE_LATLON;
return $this;
}
/**
* @param string $geohash
* @return \Elastica\Filter\AbstractGeoDistance current filter
*/
public function setGeohash($geohash)
{
$this->_geohash = $geohash;
$this->_locationType = self::LOCATION_TYPE_GEOHASH;
return $this;
}
/**
* @return array|string
* @throws \Elastica\Exception\InvalidException
*/
protected function _getLocationData()
{
if ($this->_locationType === self::LOCATION_TYPE_LATLON) { // Latitude/longitude
$location = array();
if (isset($this->_latitude)) { // Latitude
$location['lat'] = $this->_latitude;
} else {
throw new InvalidException('Latitude has to be set');
}
if (isset($this->_longitude)) { // Geohash
$location['lon'] = $this->_longitude;
} else {
throw new InvalidException('Longitude has to be set');
}
} elseif ($this->_locationType === self::LOCATION_TYPE_GEOHASH) { // Geohash
$location = $this->_geohash;
} else { // Invalid location type
throw new InvalidException('Invalid location type');
}
return $location;
}
/**
* @see \Elastica\Param::toArray()
* @throws \Elastica\Exception\InvalidException
*/
public function toArray()
{
$this->setParam($this->_key, $this->_getLocationData());
return parent::toArray();
}
}
| ramanna/elastica | lib/Elastica/Filter/AbstractGeoDistance.php | PHP | apache-2.0 | 5,209 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_26) on Mon May 07 13:00:01 PDT 2012 -->
<TITLE>
Uses of Class org.apache.hadoop.mapred.TaskTracker (Hadoop 0.20.2-cdh3u4 API)
</TITLE>
<META NAME="date" CONTENT="2012-05-07">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.hadoop.mapred.TaskTracker (Hadoop 0.20.2-cdh3u4 API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/hadoop/mapred/TaskTracker.html" title="class in org.apache.hadoop.mapred"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/apache/hadoop/mapred//class-useTaskTracker.html" target="_top"><B>FRAMES</B></A>
<A HREF="TaskTracker.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.apache.hadoop.mapred.TaskTracker</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Packages that use <A HREF="../../../../../org/apache/hadoop/mapred/TaskTracker.html" title="class in org.apache.hadoop.mapred">TaskTracker</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.apache.hadoop.mapred"><B>org.apache.hadoop.mapred</B></A></TD>
<TD>A software framework for easily writing applications which process vast
amounts of data (multi-terabyte data-sets) parallelly on large clusters
(thousands of nodes) built of commodity hardware in a reliable, fault-tolerant
manner. </TD>
</TR>
</TABLE>
<P>
<A NAME="org.apache.hadoop.mapred"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../org/apache/hadoop/mapred/TaskTracker.html" title="class in org.apache.hadoop.mapred">TaskTracker</A> in <A HREF="../../../../../org/apache/hadoop/mapred/package-summary.html">org.apache.hadoop.mapred</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../org/apache/hadoop/mapred/package-summary.html">org.apache.hadoop.mapred</A> with parameters of type <A HREF="../../../../../org/apache/hadoop/mapred/TaskTracker.html" title="class in org.apache.hadoop.mapred">TaskTracker</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>abstract org.apache.hadoop.mapred.TaskRunner</CODE></FONT></TD>
<TD><CODE><B>Task.</B><B><A HREF="../../../../../org/apache/hadoop/mapred/Task.html#createRunner(org.apache.hadoop.mapred.TaskTracker, org.apache.hadoop.mapred.TaskTracker.TaskInProgress, org.apache.hadoop.mapred.TaskTracker.RunningJob)">createRunner</A></B>(<A HREF="../../../../../org/apache/hadoop/mapred/TaskTracker.html" title="class in org.apache.hadoop.mapred">TaskTracker</A> tracker,
org.apache.hadoop.mapred.TaskTracker.TaskInProgress tip,
org.apache.hadoop.mapred.TaskTracker.RunningJob rjob)</CODE>
<BR>
Return an approprate thread runner for this task.</TD>
</TR>
</TABLE>
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/hadoop/mapred/TaskTracker.html" title="class in org.apache.hadoop.mapred"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/apache/hadoop/mapred//class-useTaskTracker.html" target="_top"><B>FRAMES</B></A>
<A HREF="TaskTracker.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright © 2009 The Apache Software Foundation
</BODY>
</HTML>
| Shmuma/hadoop | docs/api/org/apache/hadoop/mapred/class-use/TaskTracker.html | HTML | apache-2.0 | 8,472 |
/**
* Copyright (C) 2015 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.fabric8.kubernetes.client.dsl.internal;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import io.fabric8.kubernetes.api.model.HasMetadata;
import io.fabric8.kubernetes.api.model.KubernetesResourceList;
import io.fabric8.kubernetes.api.model.ListOptions;
import io.fabric8.kubernetes.client.Watcher;
import io.fabric8.kubernetes.client.http.HttpClient;
import io.fabric8.kubernetes.client.http.HttpRequest;
import io.fabric8.kubernetes.client.http.HttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class WatchHTTPManager<T extends HasMetadata, L extends KubernetesResourceList<T>> extends AbstractWatchManager<T> {
private static final Logger logger = LoggerFactory.getLogger(WatchHTTPManager.class);
private CompletableFuture<HttpResponse<InputStream>> call;
public WatchHTTPManager(final HttpClient client,
final BaseOperation<T, L, ?> baseOperation,
final ListOptions listOptions, final Watcher<T> watcher, final int reconnectInterval,
final int reconnectLimit)
throws MalformedURLException {
// Default max 32x slowdown from base interval
this(client, baseOperation, listOptions, watcher, reconnectInterval, reconnectLimit, 5);
}
public WatchHTTPManager(final HttpClient client,
final BaseOperation<T, L, ?> baseOperation,
final ListOptions listOptions, final Watcher<T> watcher, final int reconnectInterval,
final int reconnectLimit, int maxIntervalExponent)
throws MalformedURLException {
super(
watcher, baseOperation, listOptions, reconnectLimit, reconnectInterval, maxIntervalExponent,
() -> client.newBuilder()
.readTimeout(0, TimeUnit.MILLISECONDS)
.forStreaming()
.build());
}
@Override
protected synchronized void run(URL url, Map<String, String> headers) {
HttpRequest.Builder builder = client.newHttpRequestBuilder().url(url);
headers.forEach(builder::header);
call = client.sendAsync(builder.build(), InputStream.class);
call.whenComplete((response, t) -> {
if (!call.isCancelled() && t != null) {
logger.info("Watch connection failed. reason: {}", t.getMessage());
}
if (response != null) {
try (InputStream body = response.body()){
if (!response.isSuccessful()) {
if (onStatus(OperationSupport.createStatus(response.code(), response.message()))) {
return; // terminal state
}
} else {
resetReconnectAttempts();
BufferedReader source = new BufferedReader(new InputStreamReader(body, StandardCharsets.UTF_8));
String message = null;
while ((message = source.readLine()) != null) {
onMessage(message);
}
}
} catch (Exception e) {
logger.info("Watch terminated unexpectedly. reason: {}", e.getMessage());
}
}
if (!call.isCancelled()) {
scheduleReconnect();
}
});
}
@Override
protected synchronized void closeRequest() {
if (call != null) {
call.cancel(true);
call = null;
}
}
}
| fabric8io/kubernetes-client | kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/WatchHTTPManager.java | Java | apache-2.0 | 4,143 |
<?php
declare(strict_types=1);
/**
* DO NOT EDIT THIS FILE as it will be overwritten by the Pbj compiler.
* @link https://github.com/gdbots/pbjc-php
*
* Returns an array of curies using mixin "triniti:curator:mixin:has-related-teasers:v1"
* @link http://schemas.triniti.io/json-schema/triniti/curator/mixin/has-related-teasers/1-0-0.json#
*/
return [
];
| triniti/schemas | build/php/src/manifests/triniti/curator/mixin/has-related-teasers/v1.php | PHP | apache-2.0 | 362 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_151) on Tue Dec 12 12:37:08 MST 2017 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>HTTPAcceptorSupplier (BOM: * : All 2012.12.0 API)</title>
<meta name="date" content="2017-12-12">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="HTTPAcceptorSupplier (BOM: * : All 2012.12.0 API)";
}
}
catch(err) {
}
//-->
var methods = {"i0":6};
var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],4:["t3","Abstract Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/HTTPAcceptorSupplier.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">WildFly Swarm API, 2012.12.0</div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/HTTPAcceptorConsumer.html" title="interface in org.wildfly.swarm.config.messaging.activemq.server"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/HTTPConnector.html" title="class in org.wildfly.swarm.config.messaging.activemq.server"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/wildfly/swarm/config/messaging/activemq/server/HTTPAcceptorSupplier.html" target="_top">Frames</a></li>
<li><a href="HTTPAcceptorSupplier.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.wildfly.swarm.config.messaging.activemq.server</div>
<h2 title="Interface HTTPAcceptorSupplier" class="title">Interface HTTPAcceptorSupplier<T extends <a href="../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/HTTPAcceptor.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">HTTPAcceptor</a>></h2>
</div>
<div class="contentContainer">
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>Functional Interface:</dt>
<dd>This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.</dd>
</dl>
<hr>
<br>
<pre><a href="http://docs.oracle.com/javase/8/docs/api/java/lang/FunctionalInterface.html?is-external=true" title="class or interface in java.lang">@FunctionalInterface</a>
public interface <span class="typeNameLabel">HTTPAcceptorSupplier<T extends <a href="../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/HTTPAcceptor.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">HTTPAcceptor</a>></span></pre>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t3" class="tableTab"><span><a href="javascript:show(4);">Abstract Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code><a href="../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/HTTPAcceptor.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">HTTPAcceptor</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/HTTPAcceptorSupplier.html#get--">get</a></span>()</code>
<div class="block">Constructed instance of HTTPAcceptor resource</div>
</td>
</tr>
</table>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="get--">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>get</h4>
<pre><a href="../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/HTTPAcceptor.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">HTTPAcceptor</a> get()</pre>
<div class="block">Constructed instance of HTTPAcceptor resource</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>The instance</dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/HTTPAcceptorSupplier.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">WildFly Swarm API, 2012.12.0</div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/HTTPAcceptorConsumer.html" title="interface in org.wildfly.swarm.config.messaging.activemq.server"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/HTTPConnector.html" title="class in org.wildfly.swarm.config.messaging.activemq.server"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/wildfly/swarm/config/messaging/activemq/server/HTTPAcceptorSupplier.html" target="_top">Frames</a></li>
<li><a href="HTTPAcceptorSupplier.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2017 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p>
</body>
</html>
| wildfly-swarm/wildfly-swarm-javadocs | 2012.12.0/apidocs/org/wildfly/swarm/config/messaging/activemq/server/HTTPAcceptorSupplier.html | HTML | apache-2.0 | 9,740 |
/**
* Copyright 2019, Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const functions = require('firebase-functions');
const { google } = require('googleapis');
const { firestore } = require('../admin');
/**
* Return a Promise to obtain the device from Cloud IoT Core
*/
function getDevice(client, deviceId) {
return new Promise((resolve, reject) => {
const projectId = process.env.GCLOUD_PROJECT;
const parentName = `projects/${projectId}/locations/${functions.config().cloudiot.region}`;
const registryName = `${parentName}/registries/${functions.config().cloudiot.registry}`;
const request = {
name: `${registryName}/devices/${deviceId}`
};
client.projects.locations.registries.devices.get(request, (err, resp) => {
if (err) {
return reject(err);
} else {
resolve(resp.data);
}
});
});
}
/**
* Validate that the public key provided by the pending device matches
* the key currently stored in IoT Core for that device id.
*
* Method throws an error if the keys do not match.
*/
function verifyDeviceKey(pendingDevice, deviceKey) {
// Convert the pending key into PEM format
const chunks = pendingDevice.public_key.match(/(.{1,64})/g);
chunks.unshift('-----BEGIN PUBLIC KEY-----');
chunks.push('-----END PUBLIC KEY-----');
const pendingKey = chunks.join('\n');
if (deviceKey !== pendingKey) throw new Error(`Public Key Mismatch:\nExpected: ${deviceKey}\nReceived: ${pendingKey}`);
}
/**
* Cloud Function: Verify IoT device and add to user
*/
module.exports = functions.firestore.document('pending/{device}').onWrite(async (change, context) => {
const deviceId = context.params.device;
// Verify this is either a create or update
if (!change.after.exists) {
console.log(`Pending device removed for ${deviceId}`);
return;
}
console.log(`Pending device created for ${deviceId}`);
const pending = change.after.data();
// Create a new Cloud IoT client
const auth = await google.auth.getClient({
scopes: ['https://www.googleapis.com/auth/cloud-platform']
});
const client = google.cloudiot({
version: 'v1',
auth: auth
});
try {
// Verify device does NOT already exist in Firestore
const deviceRef = firestore.doc(`devices/${deviceId}`);
const deviceDoc = await deviceRef.get();
if (deviceDoc.exists) throw new Error(`${deviceId} is already registered to another user`);
// Verify device exists in IoT Core
const result = await getDevice(client, deviceId);
// Verify the device public key
verifyDeviceKey(pending, result.credentials[0].publicKey.key.trim());
// Verify the device type
let configValue = null;
switch (pending.type) {
case 'light':
configValue = require('./default-light.json');
break;
case 'thermostat':
configValue = require('./default-thermostat.json');
break;
default:
throw new Error(`Invalid device type found in ${deviceId}: ${pending.type}`);
}
// Commit the following changes together
const batch = firestore.batch();
// Insert valid device for the requested owner
const device = {
name: pending.serial_number,
owner: pending.owner,
type: pending.type,
online: false
};
batch.set(deviceRef, device);
// Generate a default configuration
const configRef = firestore.doc(`device-configs/${deviceId}`);
const config = {
owner: pending.owner,
value: configValue
};
batch.set(configRef, config);
// Remove the pending device entry
batch.delete(change.after.ref);
await batch.commit();
console.log(`Added device ${deviceId} for user ${pending.owner}`);
} catch (error) {
// Device does not exist in IoT Core or key doesn't match
console.error('Unable to register new device', error);
}
});
| GoogleCloudPlatform/iot-smart-home-cloud | firebase/functions/device-cloud/register-device.js | JavaScript | apache-2.0 | 4,394 |
package com.google.api.ads.adwords.jaxws.v201406.cm;
import java.util.List;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.ws.RequestWrapper;
import javax.xml.ws.ResponseWrapper;
/**
*
* Service used to manage campaign feed links, and matching functions.
*
*
* This class was generated by the JAX-WS RI.
* JAX-WS RI 2.2.4-b01
* Generated source version: 2.1
*
*/
@WebService(name = "CampaignFeedServiceInterface", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201406")
@XmlSeeAlso({
ObjectFactory.class
})
public interface CampaignFeedServiceInterface {
/**
*
* Returns a list of CampaignFeeds that meet the selector criteria.
*
* @param selector Determines which CampaignFeeds to return. If empty all
* Campaign feeds are returned.
* @return The list of CampaignFeeds.
* @throws ApiException Indicates a problem with the request.
*
*
* @param selector
* @return
* returns com.google.api.ads.adwords.jaxws.v201406.cm.CampaignFeedPage
* @throws ApiException_Exception
*/
@WebMethod
@WebResult(name = "rval", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201406")
@RequestWrapper(localName = "get", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201406", className = "com.google.api.ads.adwords.jaxws.v201406.cm.CampaignFeedServiceInterfaceget")
@ResponseWrapper(localName = "getResponse", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201406", className = "com.google.api.ads.adwords.jaxws.v201406.cm.CampaignFeedServiceInterfacegetResponse")
public CampaignFeedPage get(
@WebParam(name = "selector", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201406")
Selector selector)
throws ApiException_Exception
;
/**
*
* Adds, sets or removes CampaignFeeds.
*
* @param operations The operations to apply.
* @return The resulting Feeds.
* @throws ApiException Indicates a problem with the request.
*
*
* @param operations
* @return
* returns com.google.api.ads.adwords.jaxws.v201406.cm.CampaignFeedReturnValue
* @throws ApiException_Exception
*/
@WebMethod
@WebResult(name = "rval", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201406")
@RequestWrapper(localName = "mutate", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201406", className = "com.google.api.ads.adwords.jaxws.v201406.cm.CampaignFeedServiceInterfacemutate")
@ResponseWrapper(localName = "mutateResponse", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201406", className = "com.google.api.ads.adwords.jaxws.v201406.cm.CampaignFeedServiceInterfacemutateResponse")
public CampaignFeedReturnValue mutate(
@WebParam(name = "operations", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201406")
List<CampaignFeedOperation> operations)
throws ApiException_Exception
;
/**
*
* Returns a list of {@link CampaignFeed}s inside a {@link CampaignFeedPage} that matches
* the query.
*
* @param query The SQL-like AWQL query string.
* @throws ApiException when there are one or more errors with the request.
*
*
* @param query
* @return
* returns com.google.api.ads.adwords.jaxws.v201406.cm.CampaignFeedPage
* @throws ApiException_Exception
*/
@WebMethod
@WebResult(name = "rval", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201406")
@RequestWrapper(localName = "query", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201406", className = "com.google.api.ads.adwords.jaxws.v201406.cm.CampaignFeedServiceInterfacequery")
@ResponseWrapper(localName = "queryResponse", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201406", className = "com.google.api.ads.adwords.jaxws.v201406.cm.CampaignFeedServiceInterfacequeryResponse")
public CampaignFeedPage query(
@WebParam(name = "query", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201406")
String query)
throws ApiException_Exception
;
}
| nafae/developer | modules/adwords_appengine/src/main/java/com/google/api/ads/adwords/jaxws/v201406/cm/CampaignFeedServiceInterface.java | Java | apache-2.0 | 4,521 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Test lasp_SUITE:enforce_once_test result</title>
<meta http-equiv="cache-control" content="no-cache"></meta>
<meta http-equiv="content-type" content="text/html; charset=utf-8"></meta>
<link rel="stylesheet" href="../../ct_default.css" type="text/css"></link>
<script type="text/javascript" src="../../jquery-latest.js"></script>
<script type="text/javascript" src="../../jquery.tablesorter.min.js"></script>
</head>
<body>
<a name="top"></a><pre>
=== Test case: <a href="lasp_suite.src.html#enforce_once_test-1">lasp_SUITE:enforce_once_test/1</a> (click for source code)
=== Config value:
[{watchdog,<0.501.0>},
{tc_logfile,"/Users/anne-francevanswieten/lasp/_build/test/logs/[email protected]_21.47.49/lib.lasp.lasp_SUITE.logs/run.2017-05-05_21.47.49/lasp_suite.enforce_once_test.html"},
{tc_group_properties,[]},
{tc_group_path,[]},
{data_dir,"/Users/anne-francevanswieten/lasp/_build/test/lib/lasp/test/lasp_SUITE_data/"},
{priv_dir,"/Users/anne-francevanswieten/lasp/_build/test/logs/[email protected]_21.47.49/lib.lasp.lasp_SUITE.logs/run.2017-05-05_21.47.49/log_private/"}]
=== Current directory is "/Users/anne-francevanswieten/lasp/_build/test/logs/[email protected]_21.47.49"
=== Started at 2017-05-05 21:53:12
<br />
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:12.275 ***</b>
Beginning case: enforce_once_test
</pre></div>
<pre>
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:12.291 ***</b>
21:53:12.291 [info] Configured peer_service_manager partisan_default_peer_service_manager on node 'runner@MacBook-Pro-de-Anne-France'
</pre></div>
<pre>
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:12.334 ***</b>
21:53:12.334 [info] Application partisan started on node 'runner@MacBook-Pro-de-Anne-France'
</pre></div>
<pre>
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:12.334 ***</b>
21:53:12.334 [info] Setting jitter: false
</pre></div>
<pre>
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:12.337 ***</b>
21:53:12.337 [info] Setting tutorial: false
</pre></div>
<pre>
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:12.340 ***</b>
21:53:12.339 [info] Setting event interval: 0
</pre></div>
<pre>
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:12.342 ***</b>
21:53:12.342 [info] Setting max events: 1000
</pre></div>
<pre>
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:12.345 ***</b>
21:53:12.345 [info] Setting extended logging: false
</pre></div>
<pre>
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:12.349 ***</b>
21:53:12.349 [info] Setting mailbox logging: false
</pre></div>
<pre>
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:12.352 ***</b>
21:53:12.352 [info] Setting operation mode: state_based
</pre></div>
<pre>
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:12.355 ***</b>
21:53:12.355 [info] Setting set type: orset
</pre></div>
<pre>
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:12.360 ***</b>
21:53:12.360 [info] Setting broadcast: false
</pre></div>
<pre>
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:12.403 ***</b>
21:53:12.403 [info] Membership: false
</pre></div>
<pre>
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:12.406 ***</b>
21:53:12.406 [info] Workflow: true
</pre></div>
<pre>
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:12.417 ***</b>
21:53:12.417 [info] AdClientEnabled: false
</pre></div>
<pre>
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:12.422 ***</b>
21:53:12.422 [info] AdServerEnabled: false
</pre></div>
<pre>
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:12.425 ***</b>
21:53:12.425 [info] TournClientEnabled: false
</pre></div>
<pre>
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:12.428 ***</b>
21:53:12.427 [info] TournServerEnabled: false
</pre></div>
<pre>
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:12.430 ***</b>
21:53:12.430 [info] ThroughputType: gset
</pre></div>
<pre>
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:12.433 ***</b>
21:53:12.433 [info] ThroughputClientEnabled: false
</pre></div>
<pre>
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:12.435 ***</b>
21:53:12.435 [info] ThroughputServerEnabled: false
</pre></div>
<pre>
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:12.438 ***</b>
21:53:12.438 [info] DivergenceType: gcounter
</pre></div>
<pre>
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:12.441 ***</b>
21:53:12.440 [info] DivergenceClientEnabled: false
</pre></div>
<pre>
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:12.443 ***</b>
21:53:12.443 [info] DivergenceServerEnabled: false
</pre></div>
<pre>
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:12.456 ***</b>
21:53:12.456 [info] Application lasp started on node 'runner@MacBook-Pro-de-Anne-France'
</pre></div>
<pre>
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:13.717 ***</b>
21:53:13.716 [info] Enabling membership...
</pre></div>
<pre>
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:13.718 ***</b>
21:53:13.718 [info] Disabling blocking sync...
</pre></div>
<pre>
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:13.723 ***</b>
21:53:13.722 [info] Configured peer_service_manager partisan_default_peer_service_manager on node 'node-1@MacBook-Pro-de-Anne-France'
</pre></div>
<pre>
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:15.261 ***</b>
21:53:15.261 [info] Enabling membership...
</pre></div>
<pre>
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:15.263 ***</b>
21:53:15.263 [info] Disabling blocking sync...
</pre></div>
<pre>
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:15.268 ***</b>
21:53:15.268 [info] Configured peer_service_manager partisan_default_peer_service_manager on node 'node-2@MacBook-Pro-de-Anne-France'
</pre></div>
<pre>
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:16.774 ***</b>
21:53:16.774 [info] Enabling membership...
</pre></div>
<pre>
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:16.776 ***</b>
21:53:16.776 [info] Disabling blocking sync...
</pre></div>
<pre>
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:16.781 ***</b>
21:53:16.781 [info] Configured peer_service_manager partisan_default_peer_service_manager on node 'node-3@MacBook-Pro-de-Anne-France'
</pre></div>
<pre>
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:17.029 ***</b>
Joining node: 'node-3@MacBook-Pro-de-Anne-France' to 'runner@MacBook-Pro-de-Anne-France' at port 52183
</pre></div>
<pre>
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:17.030 ***</b>
Joining issued: 'node-3@MacBook-Pro-de-Anne-France' to 'runner@MacBook-Pro-de-Anne-France' at port 52183
</pre></div>
<pre>
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:17.031 ***</b>
Joining node: 'node-2@MacBook-Pro-de-Anne-France' to 'runner@MacBook-Pro-de-Anne-France' at port 52166
</pre></div>
<pre>
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:17.032 ***</b>
Joining issued: 'node-2@MacBook-Pro-de-Anne-France' to 'runner@MacBook-Pro-de-Anne-France' at port 52166
</pre></div>
<pre>
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:17.032 ***</b>
Joining node: 'node-1@MacBook-Pro-de-Anne-France' to 'runner@MacBook-Pro-de-Anne-France' at port 52154
</pre></div>
<pre>
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:17.033 ***</b>
Joining issued: 'node-1@MacBook-Pro-de-Anne-France' to 'runner@MacBook-Pro-de-Anne-France' at port 52154
</pre></div>
<pre>
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:17.094 ***</b>
Waiting for join to complete with manager: partisan_default_peer_service_manager
</pre></div>
<pre>
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:17.096 ***</b>
Finished.
</pre></div>
<pre>
</pre>
<div class="ct_internal"><pre><b>*** CT 2017-05-05 21:53:17.096 *** COVER INFO</b>
Adding nodes to cover test: ['runner@MacBook-Pro-de-Anne-France']
</pre></div>
<pre>
</pre>
<div class="ct_internal"><pre><b>*** CT 2017-05-05 21:53:17.105 *** COVER INFO</b>
Successfully added nodes to cover test: []
</pre></div>
<pre>
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:17.105 ***</b>
21:53:17.105 [info] Manager: partisan_default_peer_service_manager
</pre></div>
<pre>
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:17.105 ***</b>
21:53:17.105 [info] Nodes: ['runner@MacBook-Pro-de-Anne-France','node-3@MacBook-Pro-de-Anne-France','node-2@MacBook-Pro-de-Anne-France','node-1@MacBook-Pro-de-Anne-France']
</pre></div>
<pre>
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:17.105 ***</b>
21:53:17.105 [info] Waiting for cluster to stabilize.
</pre></div>
<pre>
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:27.112 ***</b>
21:53:27.112 [info] Adding invariant on node: 'node-1@MacBook-Pro-de-Anne-France'!
</pre></div>
<pre>
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:27.113 ***</b>
21:53:27.113 [info] Invariant configured!
</pre></div>
<pre>
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:27.142 ***</b>
21:53:27.142 [info] Waiting for response...
</pre></div>
<pre>
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:27.142 ***</b>
21:53:27.142 [info] Finished enforce_once test.
</pre></div>
<pre>
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:27.142 ***</b>
Case finished: enforce_once_test
</pre></div>
<pre>
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:34.190 ***</b>
21:53:34.190 [info] Application lasp exited with reason: stopped
</pre></div>
<pre>
</pre>
<div class="default"><pre><b>*** User 2017-05-05 21:53:34.192 ***</b>
21:53:34.192 [info] Application partisan exited with reason: stopped
</pre></div>
<pre>
<a name="end"></a>
=== Ended at 2017-05-05 21:53:34
=== successfully completed test case
=== Returned value: ok
</pre>
<center>
<br /><hr /><p>
<a href="../../../all_runs.html">Test run history
</a> | <a href="../../../index.html">Top level test index
</a>
</p>
<div class="copyright">Copyright © 2017 <a href="http://www.erlang.org">Open Telecom Platform</a><br />
Updated: <!--date-->Fri May 05 2017 21:53:12<!--/date--><br />
</div>
</center>
</body>
</html>
| anne-france/finalproject | _build/test/logs/[email protected]_21.47.49/lib.lasp.lasp_SUITE.logs/run.2017-05-05_21.47.49/lasp_suite.enforce_once_test.html | HTML | apache-2.0 | 10,821 |
/*
* Licensed to Metamarkets Group Inc. (Metamarkets) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Metamarkets licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.druid.query.extraction;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.metamx.common.StringUtils;
import java.nio.ByteBuffer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*/
public class MatchingDimExtractionFn extends DimExtractionFn
{
private final String expr;
private final Pattern pattern;
@JsonCreator
public MatchingDimExtractionFn(
@JsonProperty("expr") String expr
)
{
Preconditions.checkNotNull(expr, "expr must not be null");
this.expr = expr;
this.pattern = Pattern.compile(expr);
}
@Override
public byte[] getCacheKey()
{
byte[] exprBytes = StringUtils.toUtf8(expr);
return ByteBuffer.allocate(1 + exprBytes.length)
.put(ExtractionCacheHelper.CACHE_TYPE_ID_MATCHING_DIM)
.put(exprBytes)
.array();
}
@Override
public String apply(String dimValue)
{
Matcher matcher = pattern.matcher(Strings.nullToEmpty(dimValue));
return matcher.find() ? Strings.emptyToNull(dimValue) : null;
}
@JsonProperty("expr")
public String getExpr()
{
return expr;
}
@Override
public boolean preservesOrdering()
{
return false;
}
@Override
public ExtractionType getExtractionType()
{
return ExtractionType.MANY_TO_ONE;
}
@Override
public String toString()
{
return String.format("regex_matches(%s)", expr);
}
@Override
public boolean equals(Object o)
{
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
MatchingDimExtractionFn that = (MatchingDimExtractionFn) o;
if (!expr.equals(that.expr)) {
return false;
}
return true;
}
@Override
public int hashCode()
{
return expr.hashCode();
}
}
| pdeva/druid | processing/src/main/java/io/druid/query/extraction/MatchingDimExtractionFn.java | Java | apache-2.0 | 2,777 |
/*
* Copyright 2009-2020 Aarhus University
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dk.brics.tajs.analysis.dom.event;
import dk.brics.tajs.analysis.InitialStateBuilder;
import dk.brics.tajs.analysis.PropVarOperations;
import dk.brics.tajs.analysis.Solver;
import dk.brics.tajs.analysis.dom.DOMObjects;
import dk.brics.tajs.analysis.dom.DOMWindow;
import dk.brics.tajs.lattice.ObjectLabel;
import dk.brics.tajs.lattice.State;
import dk.brics.tajs.lattice.Value;
import static dk.brics.tajs.analysis.dom.DOMFunctions.createDOMProperty;
public class EventException {
public static ObjectLabel CONSTRUCTOR;
public static ObjectLabel PROTOTYPE;
public static ObjectLabel INSTANCES;
public static void build(Solver.SolverInterface c) {
State s = c.getState();
PropVarOperations pv = c.getAnalysis().getPropVarOperations();
CONSTRUCTOR = ObjectLabel.make(DOMObjects.EVENT_EXCEPTION_CONSTRUCTOR, ObjectLabel.Kind.FUNCTION);
PROTOTYPE = ObjectLabel.make(DOMObjects.EVENT_EXCEPTION_PROTOTYPE, ObjectLabel.Kind.OBJECT);
INSTANCES = ObjectLabel.make(DOMObjects.EVENT_EXCEPTION_INSTANCES, ObjectLabel.Kind.OBJECT);
// Constructor Object
s.newObject(CONSTRUCTOR);
pv.writePropertyWithAttributes(CONSTRUCTOR, "length", Value.makeNum(0).setAttributes(true, true, true));
pv.writePropertyWithAttributes(CONSTRUCTOR, "prototype", Value.makeObject(PROTOTYPE).setAttributes(true, true, true));
s.writeInternalPrototype(CONSTRUCTOR, Value.makeObject(InitialStateBuilder.OBJECT_PROTOTYPE));
pv.writeProperty(DOMWindow.WINDOW, "EventException", Value.makeObject(CONSTRUCTOR));
// Prototype object.
s.newObject(PROTOTYPE);
s.writeInternalPrototype(PROTOTYPE, Value.makeObject(InitialStateBuilder.OBJECT_PROTOTYPE));
// Multiplied object.
s.newObject(INSTANCES);
s.writeInternalPrototype(INSTANCES, Value.makeObject(PROTOTYPE));
/*
* Properties.
*/
createDOMProperty(INSTANCES, "code", Value.makeAnyNumUInt(), c);
s.multiplyObject(INSTANCES);
INSTANCES = INSTANCES.makeSingleton().makeSummary();
/*
* Constants.
*/
createDOMProperty(PROTOTYPE, "UNSPECIFIED_EVENT_TYPE_ERR", Value.makeNum(0), c);
/*
* Functions.
*/
}
}
| cs-au-dk/TAJS | src/dk/brics/tajs/analysis/dom/event/EventException.java | Java | apache-2.0 | 2,982 |
package com.svcet.cashportal.service;
import com.svcet.cashportal.web.beans.UserRequest;
import com.svcet.cashportal.web.beans.UserRolesScreenRequest;
import com.svcet.cashportal.web.beans.UserRolesScreenResponse;
public interface UserRoleService {
UserRolesScreenResponse editUserRoles(UserRequest userRequest);
void updateUserRoles(UserRolesScreenRequest userRolesScreenRequest);
}
| blessonkavala/cp | cashportal/src/main/java/com/svcet/cashportal/service/UserRoleService.java | Java | apache-2.0 | 391 |
# New-VSRoboMakerRobot
## SYNOPSIS
Adds an AWS::RoboMaker::Robot resource to the template.
The AWS::RoboMaker::RobotApplication resource creates an AWS RoboMaker robot.
## SYNTAX
```
New-VSRoboMakerRobot [-LogicalId] <String> [-Fleet <Object>] -Architecture <Object> -GreengrassGroupId <Object>
[-Tags <Object>] [-Name <Object>] [-DeletionPolicy <String>] [-UpdateReplacePolicy <String>]
[-DependsOn <String[]>] [-Metadata <Object>] [-UpdatePolicy <Object>] [-Condition <Object>]
[<CommonParameters>]
```
## DESCRIPTION
Adds an AWS::RoboMaker::Robot resource to the template.
The AWS::RoboMaker::RobotApplication resource creates an AWS RoboMaker robot.
## PARAMETERS
### -LogicalId
The logical ID must be alphanumeric (A-Za-z0-9) and unique within the template.
Use the logical name to reference the resource in other parts of the template.
For example, if you want to map an Amazon Elastic Block Store volume to an Amazon EC2 instance, you reference the logical IDs to associate the block stores with the instance.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: True
Position: 1
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Fleet
The Amazon Resource Name ARN of the fleet to which the robot will be registered.
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-robomaker-robot.html#cfn-robomaker-robot-fleet
PrimitiveType: String
UpdateType: Immutable
```yaml
Type: Object
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Architecture
The architecture of the robot.
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-robomaker-robot.html#cfn-robomaker-robot-architecture
PrimitiveType: String
UpdateType: Immutable
```yaml
Type: Object
Parameter Sets: (All)
Aliases:
Required: True
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -GreengrassGroupId
The Greengrass group associated with the robot.
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-robomaker-robot.html#cfn-robomaker-robot-greengrassgroupid
PrimitiveType: String
UpdateType: Immutable
```yaml
Type: Object
Parameter Sets: (All)
Aliases:
Required: True
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Tags
A map that contains tag keys and tag values that are attached to the robot.
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-robomaker-robot.html#cfn-robomaker-robot-tags
PrimitiveType: Json
UpdateType: Mutable
```yaml
Type: Object
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Name
The name of the robot.
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-robomaker-robot.html#cfn-robomaker-robot-name
PrimitiveType: String
UpdateType: Immutable
```yaml
Type: Object
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -DeletionPolicy
With the DeletionPolicy attribute you can preserve or (in some cases) backup a resource when its stack is deleted.
You specify a DeletionPolicy attribute for each resource that you want to control.
If a resource has no DeletionPolicy attribute, AWS CloudFormation deletes the resource by default.
To keep a resource when its stack is deleted, specify Retain for that resource.
You can use retain for any resource.
For example, you can retain a nested stack, S3 bucket, or EC2 instance so that you can continue to use or modify those resources after you delete their stacks.
You must use one of the following options: "Delete","Retain","Snapshot"
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -UpdateReplacePolicy
Use the UpdateReplacePolicy attribute to retain or (in some cases) backup the existing physical instance of a resource when it is replaced during a stack update operation.
When you initiate a stack update, AWS CloudFormation updates resources based on differences between what you submit and the stack's current template and parameters.
If you update a resource property that requires that the resource be replaced, AWS CloudFormation recreates the resource during the update.
Recreating the resource generates a new physical ID.
AWS CloudFormation creates the replacement resource first, and then changes references from other dependent resources to point to the replacement resource.
By default, AWS CloudFormation then deletes the old resource.
Using the UpdateReplacePolicy, you can specify that AWS CloudFormation retain or (in some cases) create a snapshot of the old resource.
For resources that support snapshots, such as AWS::EC2::Volume, specify Snapshot to have AWS CloudFormation create a snapshot before deleting the old resource instance.
You can apply the UpdateReplacePolicy attribute to any resource.
UpdateReplacePolicy is only executed if you update a resource property whose update behavior is specified as Replacement, thereby causing AWS CloudFormation to replace the old resource with a new one with a new physical ID.
For example, if you update the Engine property of an AWS::RDS::DBInstance resource type, AWS CloudFormation creates a new resource and replaces the current DB instance resource with the new one.
The UpdateReplacePolicy attribute would then dictate whether AWS CloudFormation deleted, retained, or created a snapshot of the old DB instance.
The update behavior for each property of a resource is specified in the reference topic for that resource in the AWS Resource and Property Types Reference.
For more information on resource update behavior, see Update Behaviors of Stack Resources.
The UpdateReplacePolicy attribute applies to stack updates you perform directly, as well as stack updates performed using change sets.
Note
Resources that are retained continue to exist and continue to incur applicable charges until you delete those resources.
Snapshots that are created with this policy continue to exist and continue to incur applicable charges until you delete those snapshots.
UpdateReplacePolicy retains the old physical resource or snapshot, but removes it from AWS CloudFormation's scope.
UpdateReplacePolicy differs from the DeletionPolicy attribute in that it only applies to resources replaced during stack updates.
Use DeletionPolicy for resources deleted when a stack is deleted, or when the resource definition itself is deleted from the template as part of a stack update.
You must use one of the following options: "Delete","Retain","Snapshot"
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -DependsOn
With the DependsOn attribute you can specify that the creation of a specific resource follows another.
When you add a DependsOn attribute to a resource, that resource is created only after the creation of the resource specified in the DependsOn attribute.
This parameter takes a string or list of strings representing Logical IDs of resources that must be created prior to this resource being created.
```yaml
Type: String[]
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Metadata
The Metadata attribute enables you to associate structured data with a resource.
By adding a Metadata attribute to a resource, you can add data in JSON or YAML to the resource declaration.
In addition, you can use intrinsic functions (such as GetAtt and Ref), parameters, and pseudo parameters within the Metadata attribute to add those interpreted values.
You must use a PSCustomObject containing key/value pairs here.
This will be returned when describing the resource using AWS CLI.
```yaml
Type: Object
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -UpdatePolicy
Use the UpdatePolicy attribute to specify how AWS CloudFormation handles updates to the AWS::AutoScaling::AutoScalingGroup resource.
AWS CloudFormation invokes one of three update policies depending on the type of change you make or whether a scheduled action is associated with the Auto Scaling group.
You must use the "Add-UpdatePolicy" function here.
```yaml
Type: Object
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Condition
Logical ID of the condition that this resource needs to be true in order for this resource to be provisioned.
```yaml
Type: Object
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).
## INPUTS
## OUTPUTS
### Vaporshell.Resource.RoboMaker.Robot
## NOTES
## RELATED LINKS
[http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-robomaker-robot.html](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-robomaker-robot.html)
| scrthq/Vaporshell | docs/docs/glossary/New-VSRoboMakerRobot.md | Markdown | apache-2.0 | 9,910 |
package com.igoldin.qa.school.appmanager;
import com.igoldin.qa.school.model.ContactData;
import com.igoldin.qa.school.model.Contacts;
import com.igoldin.qa.school.model.GroupData;
import com.igoldin.qa.school.model.Groups;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import java.util.List;
public class DbHelper {
private final SessionFactory sessionFactory;
public DbHelper() {
// A SessionFactory is set up once for an application!
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
.configure() // configures settings from hibernate.cfg.xml
.build();
sessionFactory = new MetadataSources( registry ).buildMetadata().buildSessionFactory();
}
public Groups groups() {
Session session = sessionFactory.openSession();
session.beginTransaction();
List<GroupData> result = session.createQuery("from GroupData" ).list();
session.getTransaction().commit();
session.close();
return new Groups(result);
}
public Contacts contacts() {
Session session = sessionFactory.openSession();
session.beginTransaction();
List<ContactData> result = session.createQuery("from ContactData where deprecated = '0000-00-00 00:00:00'" ).list();
session.getTransaction().commit();
session.close();
return new Contacts(result);
}
}
| igoldin74/java_for_testers | addressbook_tests/src/test/java/com/igoldin/qa/school/appmanager/DbHelper.java | Java | apache-2.0 | 1,614 |
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Tests for nova websocketproxy."""
import mock
from nova.console import websocketproxy
from nova import exception
from nova import test
class NovaProxyRequestHandlerBaseTestCase(test.TestCase):
def setUp(self):
super(NovaProxyRequestHandlerBaseTestCase, self).setUp()
self.wh = websocketproxy.NovaProxyRequestHandlerBase()
self.wh.socket = mock.MagicMock()
self.wh.msg = mock.MagicMock()
self.wh.do_proxy = mock.MagicMock()
self.wh.headers = mock.MagicMock()
@mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token')
def test_new_websocket_client(self, check_token):
check_token.return_value = {
'host': 'node1',
'port': '10000'
}
self.wh.socket.return_value = '<socket>'
self.wh.path = "ws://127.0.0.1/?token=123-456-789"
self.wh.new_websocket_client()
check_token.assert_called_with(mock.ANY, token="123-456-789")
self.wh.socket.assert_called_with('node1', 10000, connect=True)
self.wh.do_proxy.assert_called_with('<socket>')
@mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token')
def test_new_websocket_client_token_invalid(self, check_token):
check_token.return_value = False
self.wh.path = "ws://127.0.0.1/?token=XXX"
self.assertRaises(exception.InvalidToken,
self.wh.new_websocket_client)
check_token.assert_called_with(mock.ANY, token="XXX")
@mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token')
def test_new_websocket_client_novnc(self, check_token):
check_token.return_value = {
'host': 'node1',
'port': '10000'
}
self.wh.socket.return_value = '<socket>'
self.wh.path = "http://127.0.0.1/"
self.wh.headers.getheader.return_value = "token=123-456-789"
self.wh.new_websocket_client()
check_token.assert_called_with(mock.ANY, token="123-456-789")
self.wh.socket.assert_called_with('node1', 10000, connect=True)
self.wh.do_proxy.assert_called_with('<socket>')
@mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token')
def test_new_websocket_client_novnc_token_invalid(self, check_token):
check_token.return_value = False
self.wh.path = "http://127.0.0.1/"
self.wh.headers.getheader.return_value = "token=XXX"
self.assertRaises(exception.InvalidToken,
self.wh.new_websocket_client)
check_token.assert_called_with(mock.ANY, token="XXX")
@mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token')
def test_new_websocket_client_internal_access_path(self, check_token):
check_token.return_value = {
'host': 'node1',
'port': '10000',
'internal_access_path': 'vmid'
}
tsock = mock.MagicMock()
tsock.recv.return_value = "HTTP/1.1 200 OK\r\n\r\n"
self.wh.socket.return_value = tsock
self.wh.path = "ws://127.0.0.1/?token=123-456-789"
self.wh.new_websocket_client()
check_token.assert_called_with(mock.ANY, token="123-456-789")
self.wh.socket.assert_called_with('node1', 10000, connect=True)
self.wh.do_proxy.assert_called_with(tsock)
@mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token')
def test_new_websocket_client_internal_access_path_err(self, check_token):
check_token.return_value = {
'host': 'node1',
'port': '10000',
'internal_access_path': 'xxx'
}
tsock = mock.MagicMock()
tsock.recv.return_value = "HTTP/1.1 500 Internal Server Error\r\n\r\n"
self.wh.socket.return_value = tsock
self.wh.path = "ws://127.0.0.1/?token=123-456-789"
self.assertRaises(Exception, self.wh.new_websocket_client) # noqa
check_token.assert_called_with(mock.ANY, token="123-456-789")
| berrange/nova | nova/tests/console/test_websocketproxy.py | Python | apache-2.0 | 4,576 |
<?php
/**
* User: shenzhe
* Date: 13-6-17
*
*/
namespace ZPHP\Rank;
use ZPHP\Core\Factory as CFactory;
use ZPHP\Core\Config as ZConfig;
class Factory
{
public static function getInstance($adapter = 'Redis', $config = null)
{
if (empty($config)) {
$config = ZConfig::get('rank');
if (!empty($config['adapter'])) {
$adapter = $config['adapter'];
}
}
$className = __NAMESPACE__ . "\\Adapter\\{$adapter}";
return CFactory::getInstance($className, $config);
}
} | shenzhe/zphp | ZPHP/Rank/Factory.php | PHP | apache-2.0 | 559 |
package org.netbeans.modules.manifestsupport.dataobject;
import org.openide.loaders.DataNode;
import org.openide.nodes.Children;
public class ManifestDataNode extends DataNode {
private static final String IMAGE_ICON_BASE = "SET/PATH/TO/ICON/HERE";
public ManifestDataNode(ManifestDataObject obj) {
super(obj, Children.LEAF);
// setIconBaseWithExtension(IMAGE_ICON_BASE);
}
// /** Creates a property sheet. */
// protected Sheet createSheet() {
// Sheet s = super.createSheet();
// Sheet.Set ss = s.get(Sheet.PROPERTIES);
// if (ss == null) {
// ss = Sheet.createPropertiesSet();
// s.put(ss);
// }
// // TODO add some relevant properties: ss.put(...)
// return s;
// }
}
| bernhardhuber/netbeansplugins | nb-manifest-support/zip/ManifestSupport/src/org/netbeans/modules/manifestsupport/dataobject/ManifestDataNode.java | Java | apache-2.0 | 805 |
<?php
session_start();
if(isset($_SESSION['id']))
{
$zoubouboubou=$_SESSION['mail'];
$id_etudiant=$_SESSION['id'];
require_once("includes/connexion.php");
$sql="SELECT id, mail FROM compte_etudiant WHERE id='$id_etudiant'";
$req=mysql_query($sql);
$ligne=mysql_fetch_assoc($req);
if($id_etudiant==$ligne['id'])
{
if (isset($_GET['section']))
{
$sql="DELETE FROM compte_etudiant WHERE mail='$zoubouboubou'";
mysql_query($sql);
mysql_close($db);
header('location:index.php');
exit;
}
elseif (isset($_GET['numeri']))
{
$sql="DELETE FROM commande_new WHERE id_etudiant='$id_etudiant'";
mysql_query($sql);
mysql_close($db);
header('location:accueilUtilisateur.php');
exit;
}
else
{
header('location:connexion.php');
exit;
}
}
}
else
{
header('location:index.php');
exit;
}
| r0mdau/espelette | effUser.php | PHP | apache-2.0 | 880 |
using Aggregator.Core.Monitoring;
namespace Aggregator.Core.Configuration
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Schema;
#pragma warning disable S101 // Types should be named in camel case
/// <summary>
/// This class represents Core settings as properties
/// </summary>
/// <remarks>Marked partial to apply nested trick</remarks>
public partial class TFSAggregatorSettings
#pragma warning restore S101 // Types should be named in camel case
{
private static readonly char[] ListSeparators = new char[] { ',', ';' };
/// <summary>
/// Load configuration from file. Main scenario.
/// </summary>
/// <param name="settingsPath">Path to policies file</param>
/// <param name="logger">Logging object</param>
/// <returns>An instance of <see cref="TFSAggregatorSettings"/> or null</returns>
public static TFSAggregatorSettings LoadFromFile(string settingsPath, ILogEvents logger)
{
DateTime lastWriteTime
= System.IO.File.GetLastWriteTimeUtc(settingsPath);
var parser = new AggregatorSettingsXmlParser(logger);
return parser.Parse(lastWriteTime, (xmlLoadOptions) => XDocument.Load(settingsPath, xmlLoadOptions));
}
/// <summary>
/// Load configuration from string. Used by automated tests.
/// </summary>
/// <param name="content">Configuration data to parse</param>
/// <param name="logger">Logging object</param>
/// <returns>An instance of <see cref="TFSAggregatorSettings"/> or null</returns>
public static TFSAggregatorSettings LoadXml(string content, ILogEvents logger)
{
// conventional point in time reference
DateTime staticTimestamp = new DateTime(0, DateTimeKind.Utc);
var parser = new AggregatorSettingsXmlParser(logger);
return parser.Parse(staticTimestamp, (xmlLoadOptions) => XDocument.Parse(content, xmlLoadOptions));
}
public LogLevel LogLevel { get; private set; }
public string ScriptLanguage { get; private set; }
public bool AutoImpersonate { get; private set; }
public Uri ServerBaseUrl { get; private set; }
public string PersonalToken { get; private set; }
public string BasicPassword { get; private set; }
public string BasicUsername { get; private set; }
public string Hash { get; private set; }
public IEnumerable<Snippet> Snippets { get; private set; }
public IEnumerable<Function> Functions { get; private set; }
public IEnumerable<Rule> Rules { get; private set; }
public IEnumerable<Policy> Policies { get; private set; }
public bool Debug { get; set; }
public RateLimit RateLimit { get; set; }
public bool WhatIf { get; set; }
public bool IgnoreSslErrors { get; set; }
}
}
| tfsaggregator/tfsaggregator | Aggregator.Core/Aggregator.Core/Configuration/TFSAggregatorSettings.cs | C# | apache-2.0 | 3,073 |
# Add-VSEMRClusterKerberosAttributes
## SYNOPSIS
Adds an AWS::EMR::Cluster.KerberosAttributes resource property to the template.
KerberosAttributes is a property of the AWS::EMR::Cluster resource.
KerberosAttributes define the cluster-specific Kerberos configuration when Kerberos authentication is enabled using a security configuration.
The cluster-specific configuration must be compatible with the security configuration.
For more information see Use Kerberos Authentication: https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-kerberos.html in the *EMR Management Guide*.
## SYNTAX
```
Add-VSEMRClusterKerberosAttributes [[-ADDomainJoinPassword] <Object>] [[-ADDomainJoinUser] <Object>]
[[-CrossRealmTrustPrincipalPassword] <Object>] [-KdcAdminPassword] <Object> [-Realm] <Object>
[<CommonParameters>]
```
## DESCRIPTION
Adds an AWS::EMR::Cluster.KerberosAttributes resource property to the template.
KerberosAttributes is a property of the AWS::EMR::Cluster resource.
KerberosAttributes define the cluster-specific Kerberos configuration when Kerberos authentication is enabled using a security configuration.
The cluster-specific configuration must be compatible with the security configuration.
For more information see Use Kerberos Authentication: https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-kerberos.html in the *EMR Management Guide*.
## PARAMETERS
### -ADDomainJoinPassword
The Active Directory password for ADDomainJoinUser.
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-kerberosattributes.html#cfn-elasticmapreduce-cluster-kerberosattributes-addomainjoinpassword
PrimitiveType: String
UpdateType: Mutable
```yaml
Type: Object
Parameter Sets: (All)
Aliases:
Required: False
Position: 1
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -ADDomainJoinUser
Required only when establishing a cross-realm trust with an Active Directory domain.
A user with sufficient privileges to join resources to the domain.
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-kerberosattributes.html#cfn-elasticmapreduce-cluster-kerberosattributes-addomainjoinuser
PrimitiveType: String
UpdateType: Mutable
```yaml
Type: Object
Parameter Sets: (All)
Aliases:
Required: False
Position: 2
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -CrossRealmTrustPrincipalPassword
Required only when establishing a cross-realm trust with a KDC in a different realm.
The cross-realm principal password, which must be identical across realms.
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-kerberosattributes.html#cfn-elasticmapreduce-cluster-kerberosattributes-crossrealmtrustprincipalpassword
PrimitiveType: String
UpdateType: Mutable
```yaml
Type: Object
Parameter Sets: (All)
Aliases:
Required: False
Position: 3
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -KdcAdminPassword
The password used within the cluster for the kadmin service on the cluster-dedicated KDC, which maintains Kerberos principals, password policies, and keytabs for the cluster.
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-kerberosattributes.html#cfn-elasticmapreduce-cluster-kerberosattributes-kdcadminpassword
PrimitiveType: String
UpdateType: Mutable
```yaml
Type: Object
Parameter Sets: (All)
Aliases:
Required: True
Position: 4
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Realm
The name of the Kerberos realm to which all nodes in a cluster belong.
For example, EC2.INTERNAL.
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-kerberosattributes.html#cfn-elasticmapreduce-cluster-kerberosattributes-realm
PrimitiveType: String
UpdateType: Mutable
```yaml
Type: Object
Parameter Sets: (All)
Aliases:
Required: True
Position: 5
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).
## INPUTS
## OUTPUTS
### Vaporshell.Resource.EMR.Cluster.KerberosAttributes
## NOTES
## RELATED LINKS
[http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-kerberosattributes.html](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-kerberosattributes.html)
| scrthq/Vaporshell | docs/docs/glossary/Add-VSEMRClusterKerberosAttributes.md | Markdown | apache-2.0 | 4,948 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0-google-v3) on Fri May 13 11:40:11 CDT 2011 -->
<TITLE>
com.google.appengine.api.blobstore.dev
</TITLE>
<META NAME="date" CONTENT="2011-05-13">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../dev_javadoc.css" TITLE="Style">
</HEAD>
<BODY BGCOLOR="white">
<FONT size="+1" CLASS="FrameTitleFont">
<A HREF="../../../../../../com/google/appengine/api/blobstore/dev/package-summary.html" target="classFrame">com.google.appengine.api.blobstore.dev</A></FONT>
<TABLE BORDER="0" WIDTH="100%" SUMMARY="">
<TR>
<TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont">
Interfaces</FONT>
<FONT CLASS="FrameItemFont">
<BR>
<A HREF="BlobStorage.html" title="interface in com.google.appengine.api.blobstore.dev" target="classFrame"><I>BlobStorage</I></A></FONT></TD>
</TR>
</TABLE>
<TABLE BORDER="0" WIDTH="100%" SUMMARY="">
<TR>
<TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont">
Classes</FONT>
<FONT CLASS="FrameItemFont">
<BR>
<A HREF="BlobInfoStorage.html" title="class in com.google.appengine.api.blobstore.dev" target="classFrame">BlobInfoStorage</A>
<BR>
<A HREF="BlobStorageFactory.html" title="class in com.google.appengine.api.blobstore.dev" target="classFrame">BlobStorageFactory</A>
<BR>
<A HREF="BlobUploadSessionStorage.html" title="class in com.google.appengine.api.blobstore.dev" target="classFrame">BlobUploadSessionStorage</A>
<BR>
<A HREF="LocalBlobstoreService.html" title="class in com.google.appengine.api.blobstore.dev" target="classFrame">LocalBlobstoreService</A>
<BR>
<A HREF="ServeBlobFilter.html" title="class in com.google.appengine.api.blobstore.dev" target="classFrame">ServeBlobFilter</A>
<BR>
<A HREF="ServeBlobFilter.ResponseWrapper.html" title="class in com.google.appengine.api.blobstore.dev" target="classFrame">ServeBlobFilter.ResponseWrapper</A>
<BR>
<A HREF="UploadBlobServlet.html" title="class in com.google.appengine.api.blobstore.dev" target="classFrame">UploadBlobServlet</A></FONT></TD>
</TR>
</TABLE>
</BODY>
</HTML>
| BobEvans/omgpaco | tools/appengine-java-sdk-1.5.0.1/docs/testing/javadoc/com/google/appengine/api/blobstore/dev/package-frame.html | HTML | apache-2.0 | 2,154 |
<!DOCTYPE html>
<html>
<head>
<title>PoseNet - Camera Feed Demo</title>
<style>.footer {
position: fixed;
left: 0;
bottom: 0;
width: 100%;
color: black;
}
.footer-text {
max-width: 600px;
text-align: center;
margin: auto;
}
@media only screen and (max-width: 600px) {
.footer-text,
.dg {
display: none;
}
}
/*
* The following loading spinner CSS is from SpinKit project
* https://github.com/tobiasahlin/SpinKit
*/
.sk-spinner-pulse {
width: 20px;
height: 20px;
margin: auto 10px;
float: left;
background-color: #333;
border-radius: 100%;
-webkit-animation: sk-pulseScaleOut 1s infinite ease-in-out;
animation: sk-pulseScaleOut 1s infinite ease-in-out;
}
@-webkit-keyframes sk-pulseScaleOut {
0% {
-webkit-transform: scale(0);
transform: scale(0);
}
100% {
-webkit-transform: scale(1.0);
transform: scale(1.0);
opacity: 0;
}
}
@keyframes sk-pulseScaleOut {
0% {
-webkit-transform: scale(0);
transform: scale(0);
}
100% {
-webkit-transform: scale(1.0);
transform: scale(1.0);
opacity: 0;
}
}
.spinner-text {
float: left;
}</style>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://fonts.googleapis.com/css2?family=Poppins&display=swap" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="info" style="display:none">
</div>
<div id="loading" style="display:flex">
<div class="spinner-text">
Loading PoseNet model...
</div>
<div class="sk-spinner sk-spinner-pulse"></div>
</div>
<br><br><br>
<div id="contentContainer">
<div id="leftContainer">
<div id="objectListContainer">
<span class="paragraphTitle">Object List</span>
<button id="newImage">Add New Image</button>
</div>
<div id="objectPropertyContainer">
<span class="paragraphTitle">Property Editor</span>
<div id="properties">
<div id="inputHandler">
<button id="inputButton">
<label for="inputImg">
Choose File
</label>
</button><input id="inputImg" type="file" accept="image/*" style="display:none">
<label id="currentInput"></label>
</div>
<div class="property">
Size
<input id="sizeMultiplier" type="text" value="1.00"><br>
</div>
<div class="property">
Rotation
<input id="rotationInput" type="text" value="0.00"><br>
</div>
<div class="property">
Horizontal offset
<input id="horizontalTranslation" type="text" value="0.0"><br>
</div>
<div class="property">
Vertical offset
<input id="verticalTranslation" type="text" value="0.0"><br>
</div>
<div class="property">
<select id="model" style="display: none;">
<option value="posenet">PoseNet</option>
</select>
</div>
<div class="property">
Anchor Point
<select id="imageKeypointAttachIndexSelect">
</select>
</div>
<div class="property">
Tolerance
<input id="marginOfError" type="text" value="0"><br>
(For background removal)
<div class="useClear"></div>
</div>
<div class="property">
Remove White Background
<input id="removeBg" type="checkbox" class="checkbox"><br>
</div>
</div>
</div>
</div>
<div id="cameraOutputContainer">
<div id="main" style="display:none">
<video id="video" playsinline="" style="display: none;">
</video>
<canvas id="output">
</canvas></div>
</div>
</div>
<script src="camera.js"></script>
</body>
</html>
| googleinterns/pose-playground | docs/index.html | HTML | apache-2.0 | 4,667 |
/**
* Copyright [2009-2010] [dennis zhuang([email protected])] Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance with the License. You
* may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by
* applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
* the License for the specific language governing permissions and limitations under the License
*/
/**
* Copyright [2009-2010] [dennis zhuang([email protected])] Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance with the License. You
* may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by
* applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
* the License for the specific language governing permissions and limitations under the License
*/
package net.rubyeye.xmemcached.command.text;
import java.util.Collection;
import java.util.concurrent.CountDownLatch;
import net.rubyeye.xmemcached.command.Command;
import net.rubyeye.xmemcached.command.CommandType;
import net.rubyeye.xmemcached.transcoders.CachedData;
/**
* Get command for text protocol
*
* @author dennis
*
*/
public class TextGetOneCommand extends TextGetCommand {
public TextGetOneCommand(String key, byte[] keyBytes, CommandType cmdType, CountDownLatch latch) {
super(key, keyBytes, cmdType, latch);
}
@Override
public void dispatch() {
if (this.mergeCount < 0) {
// single get
if (this.returnValues.get(this.getKey()) == null) {
if (!this.wasFirst) {
decodeError();
} else {
this.countDownLatch();
}
} else {
CachedData data = this.returnValues.get(this.getKey());
setResult(data);
this.countDownLatch();
}
} else {
// merge get
// Collection<Command> mergeCommands = mergeCommands.values();
getIoBuffer().free();
for (Command nextCommand : mergeCommands.values()) {
TextGetCommand textGetCommand = (TextGetCommand) nextCommand;
textGetCommand.countDownLatch();
if (textGetCommand.assocCommands != null) {
for (Command assocCommand : textGetCommand.assocCommands) {
assocCommand.countDownLatch();
}
}
}
}
}
}
| killme2008/xmemcached | src/main/java/net/rubyeye/xmemcached/command/text/TextGetOneCommand.java | Java | apache-2.0 | 2,662 |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
using System.Reflection;
namespace System.Web.OData.Builder
{
/// <summary>
/// Represents the configuration for a complex property of a structural type (an entity type or a complex type).
/// </summary>
public class ComplexPropertyConfiguration : StructuralPropertyConfiguration
{
/// <summary>
/// Instantiates a new instance of the <see cref="ComplexPropertyConfiguration"/> class.
/// </summary>
/// <param name="property">The property of the configuration.</param>
/// <param name="declaringType">The declaring type of the property.</param>
public ComplexPropertyConfiguration(PropertyInfo property, StructuralTypeConfiguration declaringType)
: base(property, declaringType)
{
}
/// <inheritdoc />
public override PropertyKind Kind
{
get { return PropertyKind.Complex; }
}
/// <inheritdoc />
public override Type RelatedClrType
{
get { return PropertyInfo.PropertyType; }
}
/// <summary>
/// Marks the current complex property as optional.
/// </summary>
/// <returns>Returns itself so that multiple calls can be chained.</returns>
public ComplexPropertyConfiguration IsOptional()
{
OptionalProperty = true;
return this;
}
/// <summary>
/// Marks the current complex property as required.
/// </summary>
/// <returns>Returns itself so that multiple calls can be chained.</returns>
public ComplexPropertyConfiguration IsRequired()
{
OptionalProperty = false;
return this;
}
}
}
| Terminator-Aaron/Katana | OData/src/System.Web.OData/OData/Builder/ComplexPropertyConfiguration.cs | C# | apache-2.0 | 1,872 |
---
copyright:
years: 2015, 2016
---
{:shortdesc: .shortdesc}
{:new_window: target="_blank"}
{:codeblock: .codeblock}
{:screen: .screen}
#Protezione delle applicazioni
{: #securingapps}
*Ultimo aggiornamento: 9 maggio 2016*
{: .last-updated}
Puoi proteggere le tue applicazioni caricando dei certificati SSL e limitando l'accesso alle applicazioni.
{:shortdesc}
##Creazione di richieste di firma del certificato
{: #ssl_csr}
Prima di poter caricare i certificati SSL a cui hai diritto con {{site.data.keyword.Bluemix}}, devi creare una richiesta di firma del certificato, o CSR, sul tuo server.
Un CSR è un messaggio che viene inviato a un'autorità di certificazione per richiedere la firma di una chiave pubblica
e le informazioni associate. Più comunemente, i CSR sono in formato PKCS #10. Il CSR include una chiave pubblica,
così come un nome comune, organizzazione, città, stato, paese ed e-mail. Le richieste di certificati SSL
vengono accettate solo con una lunghezza di chiave CSR pari a 2048 bit.
Affinché il CSR sia valido, durante la sua creazione è necessario immettere le seguenti informazioni:
**Nome paese**
Un codice a due cifre che rappresenta il paese o la regione. Ad esempio, "US" rappresenta gli Stati
Uniti. Per gli altri paesi o regioni, consulta l'[elenco di codici paese ISO](https://www.iso.org/obp/ui/#search){:new_window} prima di creare il CSR.
**Stato o provincia**
Il nome completo senza abbreviazioni dello stato o provincia.
**Località**
Il nome completo della città.
**Organizzazione**
Il nome completo dell'azienda o società, come legalmente registrata nella tua località, o il nome
personale. Per le società, assicurati di includere il suffisso di registrazione, ad esempio Ltd., Inc. o NV.
**Unità organizzativa**
Il nome della sezione della tua società che ordina il certificato, ad esempio Accounting o
Marketing.
**Nome comune**
Il nome di dominio completo (FQDN) per il quale stai richiedendo il certificato SSL.
I metodi per creare un CSR variano a seconda del tuo sistema operativo. Il seguente esempio mostra come creare un CSR utilizzando [lo strumento riga di comando OpenSSL](http://www.openssl.org/){:new_window}:
```
openssl req -out CSR.csr -new -newkey rsa:2048 -nodes -keyout
privatekey.key
```
**Nota:** l'implementazione OpenSSL SHA-512 dipende dal supporto del compilatore per il tipo intero a 64 bit. Puoi utilizzare
l'opzione SHA-1 per le applicazioni che presentano problemi di compatibilità con il certificato
SHA-256.
Un certificato viene emesso da un'autorità di
certificazione e viene firmato in maniera digitale da tale autorità. Dopo aver creato il CSR, puoi generare il tuo certificato SSL su un'autorità di certificazione pubblica.
##Caricamento di certificati SSL
{: #ssl_certificate}
Puoi applicare un protocollo di sicurezza per garantire la riservatezza
delle comunicazioni della tua applicazione in modo da prevenire l'intercettazione delle comunicazioni,
la manomissione e la falsificazione dei messaggi.
Per ogni organizzazione in {{site.data.keyword.Bluemix_notm}} con
un proprietario di account che dispone di un piano di pagamento a consumo o di abbonamento, hai diritto
al caricamento di quattro certificati gratuiti. Per ogni organizzazione
con un proprietario di account che dispone di un account di prova gratuita, hai diritto al
caricamento di un certificato gratuito.
Prima di poter caricare i certificati, devi creare una
richiesta di firma del certificato. Vedi [Creazione di richieste di firma del certificato](#ssl_csr).
Quando utilizzi un dominio personalizzato, per servire il certificato SSL, utilizza i seguenti endpoint della regione per fornire la rotta URL assegnata alla tua organizzazione in Bluemix.
* Stati Uniti Sud: secure.us-south.bluemix.net
* EUROPA-REGNO UNITO: secure.eu-gb.bluemix.net
* AUSTRALIA-SYDNEY: secure.au-syd.bluemix.net
Per caricare un certificato per la tua applicazione:
1. Crea una rotta oppure modificane una esistente selezionando **Modifica
rotta e accesso all'applicazione** dal menu dell'applicazione.
2. Nella finestra di dialogo Modifica rotte e accesso all'applicazione, fai clic su **Gestisci domini**.
3. Per il tuo dominio personalizzato, fai clic su **Carica certificato**.
4. Sfoglia per caricare un certificato, una chiave privata e,
facoltativamente, un certificato intermedio. Puoi anche selezionare la casella di spunta per abilitare le richieste di un certificato client. Se abiliti l'opzione di richiesta di un certificato client, devi caricare un file truststore certificato client che definisce l'accesso utente consentito al tuo dominio personalizzato.
**Certificato**
Un documento digitale che esegue il bind di una chiave pubblica all'identità del proprietario del certificato,
consentendo così al proprietario del certificato di essere autenticato. Un certificato viene emesso da un'autorità di
certificazione e viene firmato in maniera digitale da tale autorità.
Un certificato viene in genere emesso e firmato da un'autorità di certificazione. Tuttavia, per scopi di test e di sviluppo, puoi utilizzare un certificato autofirmato.
In {{site.data.keyword.Bluemix_notm}} sono supportati i seguenti tipi di certificati:
* PEM (pem, .crt, .cer e .cert)
* DER (.der o .cer )
* PKCS #7 (p7b, p7r, spc)
**Chiave privata**
Un modello algoritmico utilizzato per crittografare messaggi che possono essere decrittografati
solo mediante la chiave pubblica corrispondente. Inoltre, la chiave privata viene utilizzata per decrittografare i messaggi crittografati con la chiave pubblica corrispondente. La chiave privata è conservata sul sistema dell'utente e protetta da password.
In
{{site.data.keyword.Bluemix_notm}} sono supportati i seguenti tipi di chiavi private:
* PEM (pem, .key)
* PKCS #8 (p8, pk8)
**Limitazione:** non è possibile caricare le chiavi private protette da una passphrase.
**Certificato intermedio**
Un certificato subordinato emesso dall'autorità di certificazione (CA) radice attendibile
specificamente per emettere certificati server per l'entità finale. Il risultato è una catena di certificati
che inizia dalla CA radice attendibile, passa per il certificato intermedio e termina con il certificato
SSL emesso per l'organizzazione.
Devi utilizzare un certificato intermedio per verificare l'autenticità del certificato principale. I certificati intermedi vengono generalmente ottenuti da una terza parte attendibile. Potresti non aver bisogno
di un certificato intermedio durante il test della tua applicazione, prima della sua distribuzione nella produzione.
**Abilita richiesta di certificato client**
Se abiliti questa opzione, a un utente che prova ad accedere a un dominio protetto da SSL viene richiesto di fornire un certificato lato client. Ad esempio, in un browser web, quando un utente prova ad accedere a un dominio protetto da SSL,
il browser web gli richiede di fornire un certificato client per il dominio. Utilizza l'opzione di caricamento file **Truststore certificato client** per definire i certificati lato client a cui consenti di accedere al tuo dominio personalizzato.
**Nota:** la funzione relativa al certificato personalizzato nella gestione del dominio di {{site.data.keyword.Bluemix_notm}} dipende dall'estensione Server Name Indication (SNI) del protocollo TLS (Transport Layer Security). Pertanto, il codice
client che accede alle applicazioni {{site.data.keyword.Bluemix_notm}}
protette da certificati personalizzati deve supportare l'estensione SNI nell'implementazione
TLS. Per ulteriori informazioni, vedi la [sezione 7.4.2 del RFC
4346](http://tools.ietf.org/html/rfc4346#section-7.4.2){:new_window}.
**Truststore certificato client**
Il truststore certificato client è un file che contiene i certificati client per gli utenti per cui desideri consentire l'accesso alla tua applicazione. Se abiliti l'opzione di richiesta di un certificato client, carica un file truststore certificato client.
In {{site.data.keyword.Bluemix_notm}} sono supportati i seguenti tipi di certificati:
* PEM (pem, .crt, .cer e .cert)
* DER (.der o .cer )
* PKCS #7 (p7b, p7r, spc)
Per eliminare un certificato oppure sostituirne uno esistente con uno nuovo, vai in **Gestisci organizzazioni** > **Domini** > **Visualizza certificato** per gestire i tuoi certificati.
| patsmith-ibm/docs | manageapps/nl/it/secapps.md | Markdown | apache-2.0 | 8,670 |
/*
* Copyright (c) 2018 <Carlos Chacón>
* All rights reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#ifndef _GAME_OBJECT_DEBUG_DEFS_H
#define _GAME_OBJECT_DEBUG_DEFS_H
/**********************
* System Includes *
***********************/
/*************************
* 3rd Party Includes *
**************************/
/***************************
* Game Engine Includes *
****************************/
/**************
* Defines *
***************/
/// <summary>
/// Name for Basic Colro Material in Visualizer
/// </summary>
#define AE_GOD_V_BASIC_COLOR_MAT_NAME "AE GOD V Basic Color Material"
/// <summary>
/// Name for Basic Line Material in Visualizer
/// </summary>
#define AE_GOD_V_BASIC_LINE_MAT_NAME "AE GOD V Basic Line Material"
/// <summary>
/// Name for Diffuse Texture Basic Material in Visualizer
/// </summary>
#define AE_GOD_V_DIFFUSE_TEXTURE_BASIC_MAT_NAME "AE GOD V Diffuse Texture Basic Material"
/// <summary>
/// Name for Directional Light Icon Texture
/// </summary>
#define AE_GOD_DIRECTIONAL_LIGHT_ICON_TEXTURE_NAME "AE Directional Light Icon"
/// <summary>
/// Name for Omni Light Icon Texture
/// </summary>
#define AE_GOD_OMNI_LIGHT_ICON_TEXTURE_NAME "AE Omni Light Icon"
/// <summary>
/// Name for Spot Light Icon Texture
/// </summary>
#define AE_GOD_SPOT_LIGHT_ICON_TEXTURE_NAME "AE Spot Light Icon"
/// <summary>
/// Name for Camera Icon Texture
/// </summary>
#define AE_GOD_CAMERA_ICON_TEXTURE_NAME "AE Camera Icon"
/// <summary>
/// File path for Directional Light Icon Texture
/// </summary>
#define AE_GOD_DIRECTIONAL_LIGHT_ICON_PATH AE_Base_FS_PATH "Data\\Textures\\DirLightIcon.dds"
/// <summary>
/// File path for Omni Light Icon Texture
/// </summary>
#define AE_GOD_OMNI_LIGHT_ICON_PATH AE_Base_FS_PATH "Data\\Textures\\OmniLightIcon.dds"
/// <summary>
/// File path for Spot Light Icon Texture
/// </summary>
#define AE_GOD_SPOT_LIGHT_ICON_PATH AE_Base_FS_PATH "Data\\Textures\\SpotLightIcon.dds"
/// <summary>
/// File path for Camera Icon Texture
/// </summary>
#define AE_GOD_CAMERA_ICON_PATH AE_Base_FS_PATH "Data\\Textures\\VideoCameraIcon.dds"
/// <summary>
/// Scale Amount for Light Icons
/// </summary>
#define AE_LIGHT_ICONS_DEFAULT_SCALE_AMOUNT 0.5f
/// <summary>
/// Scale Amount for Directional Light Shape
/// </summary>
#define AE_LIGHT_SHAPE_DIR_DEFAULT_SCALE_AMOUNT 2.0f
/************
* Using *
*************/
/********************
* Forward Decls *
*********************/
/****************
* Constants *
*****************/
/******************
* Struct Decl *
*******************/
struct GameObjectsDebugVisualizerConfig sealed : AEObject
{
bool m_CameraIconDrawEnabled = true;
bool m_LightIconDrawEnabled = true;
bool m_GameObjectDebugRenderEnabled = true;
float m_LightIconScale = AE_LIGHT_ICONS_DEFAULT_SCALE_AMOUNT;
float m_DirectionalLightShapeScale = AE_LIGHT_SHAPE_DIR_DEFAULT_SCALE_AMOUNT;
GameObjectsDebugVisualizerConfig()
{
}
};
#endif
| aliascc/Arenal-Engine | CodeSolution/Code/AEngine_GameComponents/Game Objects Debug/GameObjectsDebugDefs.h | C | apache-2.0 | 3,699 |
#!/bin/sh
$SPARK_HOME/bin/spark-submit \
--master "local[*]" \
--deploy-mode client \
--class com.godatadriven.twitter_classifier.HdfsToKafka \
target/scala-2.10/twitter-to-neo4j-assembly-1.0.jar | rweverwijk/twitter-to-neo4j | hdfs_to_kafka.sh | Shell | apache-2.0 | 204 |
package com.gbaldera.yts.fragments;
import android.content.Loader;
import com.gbaldera.yts.loaders.PopularMoviesLoader;
import com.jakewharton.trakt.entities.Movie;
import java.util.List;
public class PopularMoviesFragment extends BaseMovieFragment {
@Override
protected int getLoaderId() {
return BaseMovieFragment.POPULAR_MOVIES_LOADER_ID;
}
@Override
protected Loader<List<Movie>> getLoader() {
return new PopularMoviesLoader(getActivity());
}
}
| gbaldera/Yts | app/src/main/java/com/gbaldera/yts/fragments/PopularMoviesFragment.java | Java | apache-2.0 | 495 |
using System.Collections.Generic;
using System.Windows.Forms;
using System.Xml;
using System.Xml.XPath;
namespace PlaylistEditor
{
class HTMLHandler
{
public static string XPathHTML(HtmlElement elem)
{
string elemXPath = "";
string children = "";
List<string> ParentTagsList = new List<string>();
List<string> TagsList = new List<string>();
while (elem.Parent != null)
{
//from actual node go to parent
HtmlElement prnt = elem.Parent;
ParentTagsList.Add(prnt.TagName);
children += "|" + prnt.TagName;
//loop through all the children
foreach (HtmlElement chld in prnt.Children)
{
//=> this code is retrieving all the paths to the root.
//=>I will create an array with it instead of looping trough all the childern of the parent
TagsList.Add(chld.TagName);
}
elem = elem.Parent;
TagsList.Add(elem.TagName);
}
string prevtag = ""; //holds the previous tag to create the duplicate tag index
int tagcount = 1; //holds the duplicate tag index
foreach (string tag in TagsList)
{
if (tag == prevtag)
{
//if (tagcount == 1)
//{
// tagcount++;
// int prvtaglength = ("/" + tag + "/").Length;
// if (prvtaglength > elemXPath.Length - prvtaglength)
// {
// elemXPath = "/" + tag + "[" + tagcount + "]";
// }
// else
// {
// elemXPath = elemXPath.Substring(prvtaglength, elemXPath.Length - prvtaglength);
// elemXPath = "/" + tag + "[" + tagcount + "]/" + elemXPath;
// }
//}
//else
//{
int prvtaglength = ("/" + tag + "[" + tagcount + "]/").Length;
if (prvtaglength > elemXPath.Length - prvtaglength)
{
elemXPath = "/" + tag + "[" + tagcount + "]";
}
else
{
elemXPath = elemXPath.Substring(prvtaglength, elemXPath.Length - prvtaglength);
tagcount++;
elemXPath = "/" + tag + "[" + tagcount + "]/" + elemXPath;
}
//}
}
else
{
tagcount = 1;
elemXPath = "/" + tag + "[" + tagcount + "]" + elemXPath;
}
prevtag = tag;
}
//this.txtExtracted.Text = children + Environment.NewLine + elemXPath.ToLower();
return elemXPath.ToLower();
}
public static string XPathHTMLSimple(HtmlElement elem)
{
HtmlElement selelem = elem;
string elemXPath = "";
string prntXPath = "";
string children = "";
List<string> ParentTagsList = new List<string>();
List<string> TagsList = new List<string>();
//loop through the parents until reaching root
while (elem.Parent != null)
{
//from actual node go to parent
HtmlElement prnt = elem.Parent;
ParentTagsList.Add(prnt.TagName);
prntXPath = getParentLocation(prnt) + prntXPath;
elem = elem.Parent;
}
//Add selected element to path;
elemXPath = getParentLocation(selelem);
//Join the selected path with the route to root
elemXPath = prntXPath + elemXPath;
////br[1]/div[1]/ul[8]/li[1]/a
//TODO: The XPath should be shorten to the nearest unique value and use // (from root XPath indicator)
//this.txtExtracted.Text = children + Environment.NewLine + elemXPath.ToLower();
return elemXPath.ToLower();
}
public static string XPathHTMLtoXMLBackwards(HtmlElement elem)
{
string prntXPath = "";
List<string> ParentTagsList = new List<string>();
string XMLelem = "";
XPathNavigator xpathNav = null;
//Convert selected element to XML
XMLelem = XMLHandler.HTMLtoXMLString(elem.OuterHtml);
//TODO!! ==V
//The search has to be done after the complete document is in xml not using parent and intermediate conversions
//the result is not the same
XmlDocument prntXDoc = null;
//loop through the parents until reaching root
while (elem.Parent != null)
{ //(Using HTMLElement)
//from actual node go to parent
//HtmlElement prnt = elem.Parent;
//ParentTagsList.Add(prnt.TagName);
//prntXPath = getParentLocation(prnt) + prntXPath;
//(Using HTMLDocument)
prntXDoc = XMLHandler.HTMLtoXML(elem.Parent.OuterHtml);
string Xelem = XMLHandler.HTMLtoXMLString(elem.OuterHtml);
ParentTagsList.Add(prntXDoc.DocumentElement.Name);
prntXPath = XMLHandler.getParentXPath(prntXDoc.FirstChild.ChildNodes, Xelem, elem.TagName.ToLower()) + prntXPath;
elem = elem.Parent;
}
if (prntXDoc != null)
{
prntXPath = "/" + prntXDoc.FirstChild.Name + "[1]" + prntXPath;
}
////br[1]/div[1]/ul[8]/li[1]/a
///html[1]/body[1]/br[1]/p[1]/hr[1]/center[1]/hr[1]/p[1]/p[1]
//TODO: The XPath should be shorten to the nearest unique value and use // (from root XPath indicator)
//this.txtExtracted.Text = prntXPath;
return prntXPath.ToLower();
}
public static string XPathHTMLtoXML(string html, string elem, string tagname)
{
string prntXPath = "";
List<string> ParentTagsList = new List<string>();
string XMLelem = "";
//Convert selected element to XML
XMLelem = XMLHandler.HTMLtoXMLString(elem);
//TODO!! ==V
//The search has to be done after the complete document is in xml not using parent and intermediate conversions
//the result is not the same
XmlDocument prntXDoc = null;
prntXDoc = XMLHandler.HTMLtoXML(html);
prntXPath = XMLHandler.getChildrenXPath(prntXDoc.FirstChild.ChildNodes, XMLelem) + prntXPath;
if (prntXDoc != null)
{
prntXPath = "//" + prntXDoc.FirstChild.Name + "[1]" + prntXPath;
}
////br[1]/div[1]/ul[8]/li[1]/a
///html[1]/body[1]/br[1]/p[1]/hr[1]/center[1]/hr[1]/p[1]/p[1]
//TODO: The XPath should be shorten to the nearest unique value and use // (from root XPath indicator)
//this.txtExtracted.Text = prntXPath;
return prntXPath.ToLower();
}
public static string getParentLocation(HtmlElement selelem)
{
string elemXPath = "";
string prevtag = ""; //holds the previous tag to create the duplicate tag index
int tagcount = 0; //holds the duplicate tag index
if (selelem.Parent != null && selelem.Parent.Children != null)
{
foreach (HtmlElement chld in selelem.Parent.Children)
{
string tag = chld.TagName;
if (tag == selelem.TagName)//Only write to XPath if the tag is the same not if it is a sibling. 7-13-2015
{
//if (tag == prevtag)
//{
tagcount++;
int prvtaglength = ("/" + tag + "[" + tagcount + "]/").Length;
if (prvtaglength > elemXPath.Length - prvtaglength)
{
elemXPath = "/" + tag + "[" + tagcount + "]";
}
else
{
elemXPath = elemXPath.Substring(prvtaglength, elemXPath.Length - prvtaglength);
tagcount++;
elemXPath = elemXPath + "/" + tag + "[" + tagcount + "]";
}
//}
//else
//{
// tagcount = 1;
// elemXPath = elemXPath + "/" + tag + "[" + tagcount + "]";
//}
}
prevtag = tag;
if (chld.InnerHtml == selelem.InnerHtml) { break; }
}
}
return elemXPath;
}
}
}
| jeborgesm/PlaylistEditor | PlaylistEditor/Objects/HTMLHandler.cs | C# | apache-2.0 | 9,234 |
/*
* Copyright 2003-2019 Dave Griffith, Bas Leijdekkers
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.siyeh.ig.javadoc;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.codeInspection.ui.SingleCheckboxOptionsPanel;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.pom.Navigatable;
import com.intellij.psi.*;
import com.intellij.psi.javadoc.PsiDocComment;
import com.intellij.psi.javadoc.PsiDocTag;
import com.intellij.psi.javadoc.PsiDocTagValue;
import com.intellij.psi.javadoc.PsiDocToken;
import com.intellij.psi.util.PsiUtil;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.BaseInspection;
import com.siyeh.ig.BaseInspectionVisitor;
import com.siyeh.ig.InspectionGadgetsFix;
import com.siyeh.ig.psiutils.MethodUtils;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
final class MissingDeprecatedAnnotationInspection extends BaseInspection {
@SuppressWarnings("PublicField") public boolean warnOnMissingJavadoc = false;
@Override
@NotNull
protected String buildErrorString(Object... infos) {
final boolean annotationWarning = ((Boolean)infos[0]).booleanValue();
return annotationWarning
? InspectionGadgetsBundle.message("missing.deprecated.annotation.problem.descriptor")
: InspectionGadgetsBundle.message("missing.deprecated.tag.problem.descriptor");
}
@NotNull
@Override
public JComponent createOptionsPanel() {
return new SingleCheckboxOptionsPanel(InspectionGadgetsBundle.message("missing.deprecated.tag.option"),
this, "warnOnMissingJavadoc");
}
@Override
public boolean runForWholeFile() {
return true;
}
@Override
protected InspectionGadgetsFix buildFix(Object... infos) {
final boolean annotationWarning = ((Boolean)infos[0]).booleanValue();
return annotationWarning ? new MissingDeprecatedAnnotationFix() : new MissingDeprecatedTagFix();
}
private static class MissingDeprecatedAnnotationFix extends InspectionGadgetsFix {
@Override
@NotNull
public String getFamilyName() {
return InspectionGadgetsBundle.message("missing.deprecated.annotation.add.quickfix");
}
@Override
public void doFix(Project project, ProblemDescriptor descriptor) {
final PsiElement identifier = descriptor.getPsiElement();
final PsiModifierListOwner parent = (PsiModifierListOwner)identifier.getParent();
if (parent == null) {
return;
}
final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
final PsiAnnotation annotation = factory.createAnnotationFromText("@java.lang.Deprecated", parent);
final PsiModifierList modifierList = parent.getModifierList();
if (modifierList == null) {
return;
}
modifierList.addAfter(annotation, null);
}
}
private static class MissingDeprecatedTagFix extends InspectionGadgetsFix {
private static final String DEPRECATED_TAG_NAME = "deprecated";
@Nls(capitalization = Nls.Capitalization.Sentence)
@NotNull
@Override
public String getFamilyName() {
return InspectionGadgetsBundle.message("missing.add.deprecated.javadoc.tag.quickfix");
}
@Override
protected void doFix(Project project, ProblemDescriptor descriptor) {
PsiElement parent = descriptor.getPsiElement().getParent();
if (!(parent instanceof PsiJavaDocumentedElement)) {
return;
}
PsiJavaDocumentedElement documentedElement = (PsiJavaDocumentedElement)parent;
PsiDocComment docComment = documentedElement.getDocComment();
if (docComment != null) {
PsiDocTag existingTag = docComment.findTagByName(DEPRECATED_TAG_NAME);
if (existingTag != null) {
moveCaretAfter(existingTag);
return;
}
PsiDocTag deprecatedTag = JavaPsiFacade.getElementFactory(project).createDocTagFromText("@" + DEPRECATED_TAG_NAME + " TODO: explain");
PsiElement addedTag = docComment.add(deprecatedTag);
moveCaretAfter(addedTag);
}
else {
PsiDocComment newDocComment = JavaPsiFacade.getElementFactory(project).createDocCommentFromText(
StringUtil.join("/**\n", " * ", "@" + DEPRECATED_TAG_NAME + " TODO: explain", "\n */")
);
PsiElement addedComment = documentedElement.addBefore(newDocComment, documentedElement.getFirstChild());
if (addedComment instanceof PsiDocComment) {
PsiDocTag addedTag = ((PsiDocComment)addedComment).findTagByName(DEPRECATED_TAG_NAME);
if (addedTag != null) {
moveCaretAfter(addedTag);
}
}
}
}
private static void moveCaretAfter(PsiElement newCaretPosition) {
PsiElement sibling = newCaretPosition.getNextSibling();
if (sibling instanceof Navigatable) {
((Navigatable)sibling).navigate(true);
}
}
}
@Override
public boolean shouldInspect(PsiFile file) {
return PsiUtil.isLanguageLevel5OrHigher(file);
}
@Override
public BaseInspectionVisitor buildVisitor() {
return new MissingDeprecatedAnnotationVisitor();
}
private class MissingDeprecatedAnnotationVisitor extends BaseInspectionVisitor {
@Override
public void visitModule(@NotNull PsiJavaModule module) {
super.visitModule(module);
if (hasDeprecatedAnnotation(module)) {
if (warnOnMissingJavadoc && !hasDeprecatedComment(module, true)) {
registerModuleError(module, Boolean.FALSE);
}
}
else if (hasDeprecatedComment(module, false)) {
registerModuleError(module, Boolean.TRUE);
}
}
@Override
public void visitClass(@NotNull PsiClass aClass) {
super.visitClass(aClass);
if (hasDeprecatedAnnotation(aClass)) {
if (warnOnMissingJavadoc && !hasDeprecatedComment(aClass, true)) {
registerClassError(aClass, Boolean.FALSE);
}
}
else if (hasDeprecatedComment(aClass, false)) {
registerClassError(aClass, Boolean.TRUE);
}
}
@Override
public void visitMethod(@NotNull PsiMethod method) {
if (method.getNameIdentifier() == null) {
return;
}
if (hasDeprecatedAnnotation(method)) {
if (warnOnMissingJavadoc) {
PsiMethod m = method;
while (m != null) {
if (hasDeprecatedComment(m, true)) {
return;
}
m = MethodUtils.getSuper(m);
}
registerMethodError(method, Boolean.FALSE);
}
}
else if (hasDeprecatedComment(method, false)) {
registerMethodError(method, Boolean.TRUE);
}
}
@Override
public void visitField(@NotNull PsiField field) {
if (hasDeprecatedAnnotation(field)) {
if (warnOnMissingJavadoc && !hasDeprecatedComment(field, true)) {
registerFieldError(field, Boolean.FALSE);
}
}
else if (hasDeprecatedComment(field, false)) {
registerFieldError(field, Boolean.TRUE);
}
}
private boolean hasDeprecatedAnnotation(PsiModifierListOwner element) {
final PsiModifierList modifierList = element.getModifierList();
return modifierList != null && modifierList.hasAnnotation(CommonClassNames.JAVA_LANG_DEPRECATED);
}
private boolean hasDeprecatedComment(PsiJavaDocumentedElement documentedElement, boolean checkContent) {
final PsiDocComment comment = documentedElement.getDocComment();
if (comment == null) {
return false;
}
final PsiDocTag deprecatedTag = comment.findTagByName("deprecated");
if (deprecatedTag == null) {
return false;
}
if (!checkContent) {
return true;
}
for (PsiElement element : deprecatedTag.getDataElements()) {
if (element instanceof PsiDocTagValue ||
element instanceof PsiDocToken && ((PsiDocToken)element).getTokenType() == JavaDocTokenType.DOC_COMMENT_DATA) {
return true;
}
}
return false;
}
}
} | leafclick/intellij-community | plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/javadoc/MissingDeprecatedAnnotationInspection.java | Java | apache-2.0 | 8,667 |
/***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************/
#ifndef MY_HOSTNAME_H
#define MY_HOSTNAME_H
#include "stream.h"
#include <string>
#include <set>
class CondorError;
bool init_network_interfaces( CondorError * errorStack );
/* Find local addresses that match a given NETWORK_INTERFACE
*
* Prefers public addresses. Strongly prefers "up" addresses.
*
* interface_param_name - Optional, but recommended, exclusively used
* in log messages. Probably "NETWORK_INTERFACE" or "PRIVATE_NETWORK_INTERFACE"
* interface_pattern - Required. The value of the param. Something like
* "*" or "192.168.0.23"
* ipv4 - best ipv4 address found. May be empty if no ipv4 addresses are found
* that match the interface pattern.
* ipv6 - best ipv6 address found. May be empty if no ipv6 addresses are found
* that match the interface pattern.
* ipbest - If you absolutely need a single result, this is our best bet.
* But really, just don't do that. Should be one of ipv4 or ipv6.
*/
bool network_interface_to_ip(
char const *interface_param_name,
char const *interface_pattern,
std::string & ipv4,
std::string & ipv6,
std::string & ipbest);
#endif /* MY_HOSTNAME_H */
| htcondor/htcondor | src/condor_utils/my_hostname.h | C | apache-2.0 | 1,965 |
#!/usr/bin/env ruby
# Encoding: utf-8
#
# Author:: [email protected] (David Torres)
#
# Copyright:: Copyright 2013, Google Inc. All Rights Reserved.
#
# License:: Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This example gets uninvited contacts. To create contacts, run
# create_contacts.rb.
#
# Tags: ContactService.getContactsByStatement.
require 'dfp_api'
API_VERSION = :v201405
PAGE_SIZE = 500
def get_uninvited_contacts()
# Get DfpApi instance and load configuration from ~/dfp_api.yml.
dfp = DfpApi::Api.new
# To enable logging of SOAP requests, set the log_level value to 'DEBUG' in
# the configuration file or provide your own logger:
# dfp.logger = Logger.new('dfp_xml.log')
# Get the ContactService.
contact_service = dfp.service(:ContactService, API_VERSION)
# Define initial values.
offset = 0
page = {}
query_base = 'WHERE status = :status ORDER BY id LIMIT %d OFFSET %d'
# Create statement.
statement = {
:values => [
{:key => 'status',
:value => {:value => 'UNINVITED', :xsi_type => 'TextValue'}}
]
}
begin
# Update statement for one page with current offset.
statement[:query] = query_base % [PAGE_SIZE, offset]
# Get contacts by statement.
page = contact_service.get_contacts_by_statement(statement)
if page[:results]
# Increase query offset by page size.
offset += PAGE_SIZE
# Get the start index for printout.
start_index = page[:start_index]
# Print details about each content object in results page.
page[:results].each_with_index do |contact, index|
puts "%d) Contact ID: %d, name: %s." % [index + start_index,
contact[:id], contact[:name]]
end
end
end while offset < page[:total_result_set_size]
# Print a footer
if page.include?(:total_result_set_size)
puts "Total number of results: %d" % page[:total_result_set_size]
end
end
if __FILE__ == $0
begin
get_uninvited_contacts()
# HTTP errors.
rescue AdsCommon::Errors::HttpError => e
puts "HTTP Error: %s" % e
# API errors.
rescue DfpApi::Errors::ApiException => e
puts "Message: %s" % e.message
puts 'Errors:'
e.errors.each_with_index do |error, index|
puts "\tError [%d]:" % (index + 1)
error.each do |field, value|
puts "\t\t%s: %s" % [field, value]
end
end
end
end
| pngarland/google-api-ads-ruby | dfp_api/examples/v201405/contact_service/get_uninvited_contacts.rb | Ruby | apache-2.0 | 2,965 |
package com.google.api.ads.adwords.jaxws.v201406.video;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
import com.google.api.ads.adwords.jaxws.v201406.cm.Money;
/**
*
* Class representing the various summary budgets for a campaign page.
*
*
* <p>Java class for SummaryBudgets complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="SummaryBudgets">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="totalVideoBudget" type="{https://adwords.google.com/api/adwords/video/v201406}VideoBudget" minOccurs="0"/>
* <element name="nonVideoBudget" type="{https://adwords.google.com/api/adwords/cm/v201406}Money" minOccurs="0"/>
* <element name="combinedBudget" type="{https://adwords.google.com/api/adwords/cm/v201406}Money" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "SummaryBudgets", propOrder = {
"totalVideoBudget",
"nonVideoBudget",
"combinedBudget"
})
public class SummaryBudgets {
protected VideoBudget totalVideoBudget;
protected Money nonVideoBudget;
protected Money combinedBudget;
/**
* Gets the value of the totalVideoBudget property.
*
* @return
* possible object is
* {@link VideoBudget }
*
*/
public VideoBudget getTotalVideoBudget() {
return totalVideoBudget;
}
/**
* Sets the value of the totalVideoBudget property.
*
* @param value
* allowed object is
* {@link VideoBudget }
*
*/
public void setTotalVideoBudget(VideoBudget value) {
this.totalVideoBudget = value;
}
/**
* Gets the value of the nonVideoBudget property.
*
* @return
* possible object is
* {@link Money }
*
*/
public Money getNonVideoBudget() {
return nonVideoBudget;
}
/**
* Sets the value of the nonVideoBudget property.
*
* @param value
* allowed object is
* {@link Money }
*
*/
public void setNonVideoBudget(Money value) {
this.nonVideoBudget = value;
}
/**
* Gets the value of the combinedBudget property.
*
* @return
* possible object is
* {@link Money }
*
*/
public Money getCombinedBudget() {
return combinedBudget;
}
/**
* Sets the value of the combinedBudget property.
*
* @param value
* allowed object is
* {@link Money }
*
*/
public void setCombinedBudget(Money value) {
this.combinedBudget = value;
}
}
| nafae/developer | modules/adwords_appengine/src/main/java/com/google/api/ads/adwords/jaxws/v201406/video/SummaryBudgets.java | Java | apache-2.0 | 3,027 |
var assert = require("assert"),
expect = require('expect.js'),
cda = require("../utils/xml.js").cda,
DOMParser = require('xmldom').DOMParser,
XmlSerializer = require('xmldom').XMLSerializer,
xmlUtils = require("../utils/xml.js").xml,
FunctionalStatusSectionCreator = require("../Model/FunctionalStatusSection.js"),
FunctionalStatusEntryCreator = require("../Model/FunctionalStatusEntry.js"),
FunctionalStatusPainScaleEntryCreator = require("../Model/FunctionalStatusPainScaleEntry.js"),
Σ = xmlUtils.CreateNode,
A = xmlUtils.CreateAttributeWithNameAndValue,
adapter = require("../CDA/ModeltoCDA.js").cda;
var createMockEntry = function(num) {
var entry = FunctionalStatusEntryCreator.create();
entry.Name = "Name " + num;
entry.Value = "Value " + num;
entry.EffectiveTime = new Date().toString();
return entry;
};
var createMockPainScaleEntry = function (num) {
var entry = FunctionalStatusPainScaleEntryCreator.create();
entry.id = num;
entry.PainScore = 1;
entry.PainScoreEffectiveTime = '2/1/2013';
return entry;
};
describe("Build Functional Status Section.", function() {
it("Should be able to generate an entry for each type.", function() {
var e = new adapter.FunctionalStatusSection();
var document = new DOMParser().parseFromString("<?xml version='1.0' standalone='yes'?><ClinicalDocument xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='urn:hl7-org:v3 CDA/infrastructure/cda/CDA_SDTC.xsd' xmlns='urn:hl7-org:v3' xmlns:cda='urn:hl7-org:v3' xmlns:sdtc='urn:hl7-org:sdtc'></ClinicalDocument>", "text/xml");
var section = FunctionalStatusSectionCreator.create();
section.Capabilities.push(createMockEntry(1));
section.Cognitions.push(createMockEntry(1));
section.DailyLivings.push(createMockEntry(1));
section.PainScales.push(createMockPainScaleEntry(1));
var cdaAdapter = new adapter.FunctionalStatusSection();
var node = cdaAdapter.BuildAll(section, document);
assert.equal(node.getElementsByTagName("title")[0].childNodes[0].nodeValue, "FUNCTIONAL STATUS");
assert.equal(node.getElementsByTagName("templateId")[0].getAttributeNode("root").value, "2.16.840.1.113883.10.20.22.2.14");
assert.equal(node.getElementsByTagName("code")[0].getAttributeNode("code").value, "47420-5");
//var output = new XmlSerializer().serializeToString(node);
//console.log(output);
});
}); | lantanagroup/SEE-Tool | test/functionalStatus.js | JavaScript | apache-2.0 | 2,525 |
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2008,2009,2010,2011,2012,2013,2014,2018 Contributor
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Contains the logic for `aq add rack --bunker`."""
from aquilon.worker.broker import BrokerCommand # pylint: disable=W0611
from aquilon.worker.commands.add_rack import CommandAddRack
class CommandAddRackBunker(CommandAddRack):
required_parameters = ["bunker", "row", "column"]
| quattor/aquilon | lib/aquilon/worker/commands/add_rack_bunker.py | Python | apache-2.0 | 1,006 |
# New-VSPinpointAPNSChannel
## SYNOPSIS
Adds an AWS::Pinpoint::APNSChannel resource to the template.
A *channel* is a type of platform that you can deliver messages to.
You can use the APNs channel to send push notification messages to the Apple Push Notification service (APNs.
Before you can use Amazon Pinpoint to send notifications to APNs, you have to enable the APNs channel for an Amazon Pinpoint application.
## SYNTAX
```
New-VSPinpointAPNSChannel [-LogicalId] <String> [-BundleId <Object>] [-PrivateKey <Object>] [-Enabled <Object>]
[-DefaultAuthenticationMethod <Object>] [-TokenKey <Object>] -ApplicationId <Object> [-TeamId <Object>]
[-Certificate <Object>] [-TokenKeyId <Object>] [-DeletionPolicy <String>] [-UpdateReplacePolicy <String>]
[-DependsOn <String[]>] [-Metadata <Object>] [-UpdatePolicy <Object>] [-Condition <Object>]
[<CommonParameters>]
```
## DESCRIPTION
Adds an AWS::Pinpoint::APNSChannel resource to the template.
A *channel* is a type of platform that you can deliver messages to.
You can use the APNs channel to send push notification messages to the Apple Push Notification service (APNs.
Before you can use Amazon Pinpoint to send notifications to APNs, you have to enable the APNs channel for an Amazon Pinpoint application.
The AWS::Pinpoint::APNSChannel resource defines the status and authentication settings of the APNs channel for an application.
## PARAMETERS
### -LogicalId
The logical ID must be alphanumeric (A-Za-z0-9) and unique within the template.
Use the logical name to reference the resource in other parts of the template.
For example, if you want to map an Amazon Elastic Block Store volume to an Amazon EC2 instance, you reference the logical IDs to associate the block stores with the instance.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: True
Position: 1
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -BundleId
The bundle identifier that's assigned to your iOS app.
This identifier is used for APNs tokens.
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-pinpoint-apnschannel.html#cfn-pinpoint-apnschannel-bundleid
PrimitiveType: String
UpdateType: Mutable
```yaml
Type: Object
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -PrivateKey
The private key for the APNs client certificate that you want Amazon Pinpoint to use to communicate with APNs.
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-pinpoint-apnschannel.html#cfn-pinpoint-apnschannel-privatekey
PrimitiveType: String
UpdateType: Mutable
```yaml
Type: Object
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Enabled
Specifies whether to enable the APNs channel for the application.
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-pinpoint-apnschannel.html#cfn-pinpoint-apnschannel-enabled
PrimitiveType: Boolean
UpdateType: Mutable
```yaml
Type: Object
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -DefaultAuthenticationMethod
The default authentication method that you want Amazon Pinpoint to use when authenticating with APNs, key or certificate.
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-pinpoint-apnschannel.html#cfn-pinpoint-apnschannel-defaultauthenticationmethod
PrimitiveType: String
UpdateType: Mutable
```yaml
Type: Object
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -TokenKey
The authentication key to use for APNs tokens.
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-pinpoint-apnschannel.html#cfn-pinpoint-apnschannel-tokenkey
PrimitiveType: String
UpdateType: Mutable
```yaml
Type: Object
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -ApplicationId
The unique identifier for the application that the APNs channel applies to.
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-pinpoint-apnschannel.html#cfn-pinpoint-apnschannel-applicationid
PrimitiveType: String
UpdateType: Immutable
```yaml
Type: Object
Parameter Sets: (All)
Aliases:
Required: True
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -TeamId
The identifier that's assigned to your Apple developer account team.
This identifier is used for APNs tokens.
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-pinpoint-apnschannel.html#cfn-pinpoint-apnschannel-teamid
PrimitiveType: String
UpdateType: Mutable
```yaml
Type: Object
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Certificate
The APNs client certificate that you received from Apple, if you want Amazon Pinpoint to communicate with APNs by using an APNs certificate.
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-pinpoint-apnschannel.html#cfn-pinpoint-apnschannel-certificate
PrimitiveType: String
UpdateType: Mutable
```yaml
Type: Object
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -TokenKeyId
The key identifier that's assigned to your APNs signing key, if you want Amazon Pinpoint to communicate with APNs by using APNs tokens.
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-pinpoint-apnschannel.html#cfn-pinpoint-apnschannel-tokenkeyid
PrimitiveType: String
UpdateType: Mutable
```yaml
Type: Object
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -DeletionPolicy
With the DeletionPolicy attribute you can preserve or (in some cases) backup a resource when its stack is deleted.
You specify a DeletionPolicy attribute for each resource that you want to control.
If a resource has no DeletionPolicy attribute, AWS CloudFormation deletes the resource by default.
To keep a resource when its stack is deleted, specify Retain for that resource.
You can use retain for any resource.
For example, you can retain a nested stack, S3 bucket, or EC2 instance so that you can continue to use or modify those resources after you delete their stacks.
You must use one of the following options: "Delete","Retain","Snapshot"
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -UpdateReplacePolicy
Use the UpdateReplacePolicy attribute to retain or (in some cases) backup the existing physical instance of a resource when it is replaced during a stack update operation.
When you initiate a stack update, AWS CloudFormation updates resources based on differences between what you submit and the stack's current template and parameters.
If you update a resource property that requires that the resource be replaced, AWS CloudFormation recreates the resource during the update.
Recreating the resource generates a new physical ID.
AWS CloudFormation creates the replacement resource first, and then changes references from other dependent resources to point to the replacement resource.
By default, AWS CloudFormation then deletes the old resource.
Using the UpdateReplacePolicy, you can specify that AWS CloudFormation retain or (in some cases) create a snapshot of the old resource.
For resources that support snapshots, such as AWS::EC2::Volume, specify Snapshot to have AWS CloudFormation create a snapshot before deleting the old resource instance.
You can apply the UpdateReplacePolicy attribute to any resource.
UpdateReplacePolicy is only executed if you update a resource property whose update behavior is specified as Replacement, thereby causing AWS CloudFormation to replace the old resource with a new one with a new physical ID.
For example, if you update the Engine property of an AWS::RDS::DBInstance resource type, AWS CloudFormation creates a new resource and replaces the current DB instance resource with the new one.
The UpdateReplacePolicy attribute would then dictate whether AWS CloudFormation deleted, retained, or created a snapshot of the old DB instance.
The update behavior for each property of a resource is specified in the reference topic for that resource in the AWS Resource and Property Types Reference.
For more information on resource update behavior, see Update Behaviors of Stack Resources.
The UpdateReplacePolicy attribute applies to stack updates you perform directly, as well as stack updates performed using change sets.
Note
Resources that are retained continue to exist and continue to incur applicable charges until you delete those resources.
Snapshots that are created with this policy continue to exist and continue to incur applicable charges until you delete those snapshots.
UpdateReplacePolicy retains the old physical resource or snapshot, but removes it from AWS CloudFormation's scope.
UpdateReplacePolicy differs from the DeletionPolicy attribute in that it only applies to resources replaced during stack updates.
Use DeletionPolicy for resources deleted when a stack is deleted, or when the resource definition itself is deleted from the template as part of a stack update.
You must use one of the following options: "Delete","Retain","Snapshot"
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -DependsOn
With the DependsOn attribute you can specify that the creation of a specific resource follows another.
When you add a DependsOn attribute to a resource, that resource is created only after the creation of the resource specified in the DependsOn attribute.
This parameter takes a string or list of strings representing Logical IDs of resources that must be created prior to this resource being created.
```yaml
Type: String[]
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Metadata
The Metadata attribute enables you to associate structured data with a resource.
By adding a Metadata attribute to a resource, you can add data in JSON or YAML to the resource declaration.
In addition, you can use intrinsic functions (such as GetAtt and Ref), parameters, and pseudo parameters within the Metadata attribute to add those interpreted values.
You must use a PSCustomObject containing key/value pairs here.
This will be returned when describing the resource using AWS CLI.
```yaml
Type: Object
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -UpdatePolicy
Use the UpdatePolicy attribute to specify how AWS CloudFormation handles updates to the AWS::AutoScaling::AutoScalingGroup resource.
AWS CloudFormation invokes one of three update policies depending on the type of change you make or whether a scheduled action is associated with the Auto Scaling group.
You must use the "Add-UpdatePolicy" function here.
```yaml
Type: Object
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Condition
Logical ID of the condition that this resource needs to be true in order for this resource to be provisioned.
```yaml
Type: Object
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).
## INPUTS
## OUTPUTS
### Vaporshell.Resource.Pinpoint.APNSChannel
## NOTES
## RELATED LINKS
[http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-pinpoint-apnschannel.html](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-pinpoint-apnschannel.html)
| scrthq/Vaporshell | docs/docs/glossary/New-VSPinpointAPNSChannel.md | Markdown | apache-2.0 | 12,932 |
package com.rodbate.httpserver.nioserver.old;
public interface WriterChannel {
}
| rodbate/httpserver | src/main/java/com/rodbate/httpserver/nioserver/old/WriterChannel.java | Java | apache-2.0 | 86 |
package com.glaf.base.modules.sys.model;
import java.io.Serializable;
import java.util.Date;
public class Dictory implements Serializable {
private static final long serialVersionUID = 2756737871937885934L;
private long id;
private long typeId;
private String code;
private String name;
private int sort;
private String desc;
private int blocked;
private String ext1;
private String ext2;
private String ext3;
private String ext4;
private Date ext5;
private Date ext6;
public int getBlocked() {
return blocked;
}
public String getCode() {
return code;
}
public String getDesc() {
return desc;
}
public String getExt1() {
return ext1;
}
public String getExt2() {
return ext2;
}
public String getExt3() {
return ext3;
}
public String getExt4() {
return ext4;
}
public Date getExt5() {
return ext5;
}
public Date getExt6() {
return ext6;
}
public long getId() {
return id;
}
public String getName() {
return name;
}
public int getSort() {
return sort;
}
public long getTypeId() {
return typeId;
}
public void setBlocked(int blocked) {
this.blocked = blocked;
}
public void setCode(String code) {
this.code = code;
}
public void setDesc(String desc) {
this.desc = desc;
}
public void setExt1(String ext1) {
this.ext1 = ext1;
}
public void setExt2(String ext2) {
this.ext2 = ext2;
}
public void setExt3(String ext3) {
this.ext3 = ext3;
}
public void setExt4(String ext4) {
this.ext4 = ext4;
}
public void setExt5(Date ext5) {
this.ext5 = ext5;
}
public void setExt6(Date ext6) {
this.ext6 = ext6;
}
public void setId(long id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setSort(int sort) {
this.sort = sort;
}
public void setTypeId(long typeId) {
this.typeId = typeId;
}
}
| jior/glaf-gac | glaf-base/src/main/java/com/glaf/base/modules/sys/model/Dictory.java | Java | apache-2.0 | 1,856 |
/**
* AudienceSegmentAudienceSegmentType.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
*/
package com.google.api.ads.dfp.axis.v201311;
public class AudienceSegmentAudienceSegmentType implements java.io.Serializable {
private java.lang.String _value_;
private static java.util.HashMap _table_ = new java.util.HashMap();
// Constructor
protected AudienceSegmentAudienceSegmentType(java.lang.String value) {
_value_ = value;
_table_.put(_value_,this);
}
public static final java.lang.String _FIRST_PARTY = "FIRST_PARTY";
public static final java.lang.String _SHARED = "SHARED";
public static final java.lang.String _THIRD_PARTY = "THIRD_PARTY";
public static final java.lang.String _UNKNOWN = "UNKNOWN";
public static final AudienceSegmentAudienceSegmentType FIRST_PARTY = new AudienceSegmentAudienceSegmentType(_FIRST_PARTY);
public static final AudienceSegmentAudienceSegmentType SHARED = new AudienceSegmentAudienceSegmentType(_SHARED);
public static final AudienceSegmentAudienceSegmentType THIRD_PARTY = new AudienceSegmentAudienceSegmentType(_THIRD_PARTY);
public static final AudienceSegmentAudienceSegmentType UNKNOWN = new AudienceSegmentAudienceSegmentType(_UNKNOWN);
public java.lang.String getValue() { return _value_;}
public static AudienceSegmentAudienceSegmentType fromValue(java.lang.String value)
throws java.lang.IllegalArgumentException {
AudienceSegmentAudienceSegmentType enumeration = (AudienceSegmentAudienceSegmentType)
_table_.get(value);
if (enumeration==null) throw new java.lang.IllegalArgumentException();
return enumeration;
}
public static AudienceSegmentAudienceSegmentType fromString(java.lang.String value)
throws java.lang.IllegalArgumentException {
return fromValue(value);
}
public boolean equals(java.lang.Object obj) {return (obj == this);}
public int hashCode() { return toString().hashCode();}
public java.lang.String toString() { return _value_;}
public java.lang.Object readResolve() throws java.io.ObjectStreamException { return fromValue(_value_);}
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.EnumSerializer(
_javaType, _xmlType);
}
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.EnumDeserializer(
_javaType, _xmlType);
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(AudienceSegmentAudienceSegmentType.class);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201311", "AudienceSegment.AudienceSegmentType"));
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
}
| nafae/developer | modules/dfp_axis/src/main/java/com/google/api/ads/dfp/axis/v201311/AudienceSegmentAudienceSegmentType.java | Java | apache-2.0 | 3,381 |
# Copyright 2018 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import netaddr
from rally.common import logging
from rally.common.utils import RandomNameGeneratorMixin
from rally_ovs.plugins.ovs import ovsclients
from rally_ovs.plugins.ovs import utils
LOG = logging.getLogger(__name__)
class OvnClientMixin(ovsclients.ClientsMixin, RandomNameGeneratorMixin):
def _get_ovn_controller(self, install_method="sandbox"):
ovn_nbctl = self.controller_client("ovn-nbctl")
ovn_nbctl.set_sandbox("controller-sandbox", install_method,
self.context['controller']['host_container'])
ovn_nbctl.set_daemon_socket(self.context.get("daemon_socket", None))
return ovn_nbctl
def _start_daemon(self):
ovn_nbctl = self._get_ovn_controller(self.install_method)
return ovn_nbctl.start_daemon()
def _stop_daemon(self):
ovn_nbctl = self._get_ovn_controller(self.install_method)
ovn_nbctl.stop_daemon()
def _restart_daemon(self):
self._stop_daemon()
return self._start_daemon()
def _create_lswitches(self, lswitch_create_args, num_switches=-1):
self.RESOURCE_NAME_FORMAT = "lswitch_XXXXXX_XXXXXX"
if (num_switches == -1):
num_switches = lswitch_create_args.get("amount", 1)
batch = lswitch_create_args.get("batch", num_switches)
start_cidr = lswitch_create_args.get("start_cidr", "")
if start_cidr:
start_cidr = netaddr.IPNetwork(start_cidr)
mcast_snoop = lswitch_create_args.get("mcast_snoop", "true")
mcast_idle = lswitch_create_args.get("mcast_idle_timeout", 300)
mcast_table_size = lswitch_create_args.get("mcast_table_size", 2048)
LOG.info("Create lswitches method: %s" % self.install_method)
ovn_nbctl = self._get_ovn_controller(self.install_method)
ovn_nbctl.enable_batch_mode()
flush_count = batch
lswitches = []
for i in range(num_switches):
name = self.generate_random_name()
if start_cidr:
cidr = start_cidr.next(i)
name = "lswitch_%s" % cidr
else:
name = self.generate_random_name()
other_cfg = {
'mcast_snoop': mcast_snoop,
'mcast_idle_timeout': mcast_idle,
'mcast_table_size': mcast_table_size
}
lswitch = ovn_nbctl.lswitch_add(name, other_cfg)
if start_cidr:
lswitch["cidr"] = cidr
LOG.info("create %(name)s %(cidr)s" % \
{"name": name, "cidr": lswitch.get("cidr", "")})
lswitches.append(lswitch)
flush_count -= 1
if flush_count < 1:
ovn_nbctl.flush()
flush_count = batch
ovn_nbctl.flush() # ensure all commands be run
ovn_nbctl.enable_batch_mode(False)
return lswitches
def _create_routers(self, router_create_args):
self.RESOURCE_NAME_FORMAT = "lrouter_XXXXXX_XXXXXX"
amount = router_create_args.get("amount", 1)
batch = router_create_args.get("batch", 1)
ovn_nbctl = self._get_ovn_controller(self.install_method)
ovn_nbctl.enable_batch_mode()
flush_count = batch
lrouters = []
for i in range(amount):
name = self.generate_random_name()
lrouter = ovn_nbctl.lrouter_add(name)
lrouters.append(lrouter)
flush_count -= 1
if flush_count < 1:
ovn_nbctl.flush()
flush_count = batch
ovn_nbctl.flush() # ensure all commands be run
ovn_nbctl.enable_batch_mode(False)
return lrouters
def _connect_network_to_router(self, router, network):
LOG.info("Connect network %s to router %s" % (network["name"], router["name"]))
ovn_nbctl = self.controller_client("ovn-nbctl")
ovn_nbctl.set_sandbox("controller-sandbox", self.install_method,
self.context['controller']['host_container'])
ovn_nbctl.enable_batch_mode(False)
base_mac = [i[:2] for i in self.task["uuid"].split('-')]
base_mac[0] = str(hex(int(base_mac[0], 16) & 254))
base_mac[3:] = ['00']*3
mac = utils.get_random_mac(base_mac)
lrouter_port = ovn_nbctl.lrouter_port_add(router["name"], network["name"], mac,
str(network["cidr"]))
ovn_nbctl.flush()
switch_router_port = "rp-" + network["name"]
lport = ovn_nbctl.lswitch_port_add(network["name"], switch_router_port)
ovn_nbctl.db_set('Logical_Switch_Port', switch_router_port,
('options', {"router-port":network["name"]}),
('type', 'router'),
('address', 'router'))
ovn_nbctl.flush()
def _connect_networks_to_routers(self, lnetworks, lrouters, networks_per_router):
for lrouter in lrouters:
LOG.info("Connect %s networks to router %s" % (networks_per_router, lrouter["name"]))
for lnetwork in lnetworks[:networks_per_router]:
LOG.info("connect networks %s cidr %s" % (lnetwork["name"], lnetwork["cidr"]))
self._connect_network_to_router(lrouter, lnetwork)
lnetworks = lnetworks[networks_per_router:]
| openvswitch/ovn-scale-test | rally_ovs/plugins/ovs/ovnclients.py | Python | apache-2.0 | 5,955 |
## COMISS - Compare Scalar Ordered Single-Precision Floating-Point Values and Set EFLAGS
> Operation
``` slim
RESULT <- OrderedCompare(SRC1[31:0] <> SRC2[31:0]) {
(\* Set EFLAGS \*) CASE (RESULT) OF```
### UNORDERED
### GREATER_THAN
### LESS_THAN
### EQUAL
ESAC;
OF,AF,SF <- 0; }
> Intel C/C++ Compiler Intrinsic Equivalents
``` slim
int _mm_comieq_ss (__m128 a, __m128 b) int _mm_comilt_ss (__m128 a, __m128 b)
int _mm_comile_ss (__m128 a, __m128 b) int _mm_comigt_ss (__m128 a, __m128 b)
int _mm_comige_ss (__m128 a, __m128 b) int _mm_comineq_ss (__m128 a, __m128
b)
```
Opcode/Instruction | Op/En| 64/32-bit Mode| CPUID Feature Flag| Description
--- | --- | --- | --- | ---
0F 2F /r COMISS xmm1, xmm2/m32 | RM | V/V | SSE | Compare low single-precision floating-point
| | | | values in xmm1 and xmm2/mem32 and set
| | | | the EFLAGS flags accordingly.
VEX.LIG.0F.WIG 2F /r VCOMISS xmm1, xmm2/m32| RM | V/V | AVX | Compare low single precision floating-point
| | | | values in xmm1 and xmm2/mem32 and set
| | | | the EFLAGS flags accordingly.
### Instruction Operand Encoding
Op/En| Operand 1 | Operand 2 | Operand 3| Operand 4
--- | --- | --- | --- | ---
RM | ModRM:reg (r)| ModRM:r/m (r)| NA | NA
### Description
Compares the single-precision floating-point values in the low doublewords of
operand 1 (first operand) and operand 2 (second operand), and sets the ZF, PF,
and CF flags in the EFLAGS register according to the result (unordered, greater
than, less than, or equal). The OF, SF, and AF flags in the EFLAGS register
are set to 0. The unordered result is returned if either source operand is a
NaN (QNaN or SNaN). The sign of zero is ignored for comparisons, so that -0.0
is equal to +0.0.
Operand 1 is an XMM register; Operand 2 can be an XMM register or a 32 bit memory
location.
The COMISS instruction differs from the UCOMISS instruction in that it signals
a SIMD floating-point invalid operation exception (**``#I)``** when a source operand
is either a QNaN or SNaN. The UCOMISS instruction signals an invalid numeric
exception only if a source operand is an SNaN.
The EFLAGS register is not updated if an unmasked SIMD floating-point exception
is generated.
In 64-bit mode, use of the REX.R prefix permits this instruction to access additional
registers (XMM8-XMM15). Note: In VEX-encoded versions, VEX.vvvv is reserved
and must be 1111b, otherwise instructions will **``#UD.``**
### SIMD Floating-Point Exceptions
Invalid (if SNaN or QNaN operands), Denormal.
### Other Exceptions
See Exceptions Type 3; additionally
| |
---- | -----
**``#UD``**| If VEX.vvvv != 1111B.
| Rami114/x86.help | includes/instruction/_comiss.md | Markdown | apache-2.0 | 3,137 |
<?php
namespace OpenOrchestra\ModelBundle\Repository;
use OpenOrchestra\ModelInterface\Repository\RedirectionRepositoryInterface;
use OpenOrchestra\Repository\AbstractAggregateRepository;
use OpenOrchestra\Pagination\Configuration\PaginateFinderConfiguration;
use Solution\MongoAggregation\Pipeline\Stage;
/**
* Class RedirectionRepository
*/
class RedirectionRepository extends AbstractAggregateRepository implements RedirectionRepositoryInterface
{
/**
* @param string $nodeId
* @param string $locale
* @param string $siteId
*
* @return array
*/
public function findByNode($nodeId, $locale, $siteId){
$qa = $this->createAggregationQuery();
$qa->match(array(
'nodeId' => $nodeId,
'locale' => $locale,
'siteId' => $siteId,
));
return $this->hydrateAggregateQuery($qa);
}
/**
* @param string $siteId
*
* @return array
*/
public function findBySiteId($siteId){
$qa = $this->createAggregationQuery();
$qa->match(array(
'siteId' => $siteId,
));
return $this->hydrateAggregateQuery($qa);
}
/**
* @param PaginateFinderConfiguration $configuration
*
* @return array
*/
public function findForPaginate(PaginateFinderConfiguration $configuration)
{
$qa = $this->createAggregationQuery();
$this->filterSearch($configuration, $qa);
$order = $configuration->getOrder();
if (!empty($order)) {
$qa->sort($order);
}
$qa->skip($configuration->getSkip());
$qa->limit($configuration->getLimit());
return $this->hydrateAggregateQuery($qa);
}
/**
* @return int
*/
public function count()
{
$qa = $this->createAggregationQuery();
return $this->countDocumentAggregateQuery($qa);
}
/**
* @param string $pattern
* @param string $redirectionId
*
* @return int
*/
public function countByPattern($pattern, $redirectionId)
{
$qa = $this->createAggregationQuery();
$qa->match(array(
'routePattern' => $pattern,
'_id' => array('$ne' => new \MongoId($redirectionId))
));
return $this->countDocumentAggregateQuery($qa);
}
/**
* @param PaginateFinderConfiguration $configuration
*
* @return int
*/
public function countWithFilter(PaginateFinderConfiguration $configuration)
{
$qa = $this->createAggregationQuery();
$this->filterSearch($configuration, $qa);
return $this->countDocumentAggregateQuery($qa);
}
/**
* @param PaginateFinderConfiguration $configuration
* @param Stage $qa
*
* @return array
*/
protected function filterSearch(PaginateFinderConfiguration $configuration, Stage $qa)
{
$siteName = $configuration->getSearchIndex('site_name');
if (null !== $siteName && '' !== $siteName) {
$qa->match(array('siteName' => new \MongoRegex('/.*' . $siteName . '.*/i')));
}
$locale = $configuration->getSearchIndex('locale');
if (null !== $locale && '' !== $locale) {
$qa->match(array('locale' => new \MongoRegex('/.*' . $locale . '.*/i')));
}
$routePattern = $configuration->getSearchIndex('route_pattern');
if (null !== $routePattern && '' !== $routePattern) {
$qa->match(array('routePattern' => new \MongoRegex('/.*' . $routePattern . '.*/i')));
}
$redirection = $configuration->getSearchIndex('redirection');
if (null !== $redirection && '' !== $redirection) {
$qa->match(array('$or' => array(
array('url' => new \MongoRegex('/.*' . $redirection . '.*/i')),
array('nodeId' => new \MongoRegex('/.*' . $redirection . '.*/i'))
)));
}
$permanent = $configuration->getSearchIndex('permanent');
if (null !== $redirection && '' !== $permanent) {
if ('true' == $permanent) {
$qa->match(array('permanent' => true));
}
if ('false' == $permanent) {
$qa->match(array('permanent' => false));
}
}
return $qa;
}
/**
* @param array $redirectionIds
*
* @throws \Exception
*/
public function removeRedirections(array $redirectionIds)
{
$redirectionMongoIds = array();
foreach ($redirectionIds as $redirectionId) {
$redirectionMongoIds[] = new \MongoId($redirectionId);
}
$qb = $this->createQueryBuilder();
$qb->remove()
->field('id')->in($redirectionMongoIds)
->getQuery()
->execute();
}
}
| open-orchestra/open-orchestra-model-bundle | ModelBundle/Repository/RedirectionRepository.php | PHP | apache-2.0 | 4,860 |
<?php
// Check for empty fields
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['phone']) ||
empty($_POST['message']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
// Create the email and send the message
$to = '[email protected]'; // Add your email address inbetween the '' replacing [email protected] - This is where the form will send a message to.
$email_subject = "Website Contact Form: $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: [email protected]\n"; // This is the email address the generated message will be from. We recommend using something like [email protected].
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>
| seanwash/sharay.com | mail/contact_me.php | PHP | apache-2.0 | 1,091 |
---
code: true
type: page
title: mCreateOrReplace
description: Creates or replaces documents in kuzzle
---
# MCreateOrReplace
Creates or replaces multiple documents.
Returns a partial error (error code 206) if one or more document creations/replacements fail.
## Arguments
```go
MCreateOrReplace(
index string,
collection string,
documents json.RawMessage,
options types.QueryOptions) (json.RawMessage, error)
```
<br/>
| Argument | Type | Description |
| ------------ | ----------------------------- | --------------------------------- |
| `index` | <pre>string</pre> | Index name |
| `collection` | <pre>string</pre> | Collection name |
| `documents` | <pre>json.RawMessage</pre> | JSON array of documents to create |
| `options` | <pre>types.QueryOptions</pre> | A struct containing query options |
### options
Additional query options
| Option | Type<br/>(default) | Description |
| ---------- | ----------------------------- | ---------------------------------------------------------------------------------- |
| `Queuable` | <pre>bool</pre> <br/>(`true`) | If true, queues the request during downtime, until connected to Kuzzle again |
| `Refresh` | <pre>string</pre><br/>(`""`) | If set to `wait_for`, waits for the change to be reflected for `search` (up to 1s) |
## Return
Returns a json.RawMessage containing two arrays, successes and errors.
Each created or replaced document is an object of the `successes` array with the following properties:
| Name | Type | Description |
| ---------- | -------------------------- | ------------------------------------------------------ |
| `_id` | <pre>string</pre> | Document ID |
| `_version` | <pre>int</pre> | Version of the document in the persistent data storage |
| `_source` | <pre>json.RawMessage</pre> | Document content |
| `created` | <pre>bool</pre> | True if the document was created |
Each errored document is an object of the `errors` array with the following properties:
| Name | Type | Description |
| ---------- | -------------------------- | ----------------------------- |
| `document` | <pre>json.RawMessage</pre> | Document that caused the error |
| `status` | <pre>int</pre> | HTTP error status |
| `reason` | <pre>string</pre> | Human readable reason |
## Usage
<<< ./snippets/m-create-or-replace.go
| kuzzleio/sdk-go | .doc/3/controllers/document/mCreateOrReplace/index.md | Markdown | apache-2.0 | 2,833 |
<!-- About Section -->
<section id="about" class="container content-section text-center">
<div class="row">
<div class="col-lg-8 col-lg-offset-2">
<h2>About Me</h2>
<p>I am a Computer Science Undergrad from <span>National Institute of Technology, Silchar.</span></p>
<p>Love to spend my time coding and hanging out with friends.If you like to create and kill 'BUGS',
Party Hard or Dream Big you will feel right at home with me.
</p>
<p>I am more of a laid-back ambitious coder, and like to know about stuffs. My interests include Competitive
Programming, Machine Learning, Contributing to Open source. I like to share what I know and
if you feel I can help you in any way drop me a mail at
<a href="mailto:[email protected]">[email protected]</a>
</p>
</div>
</div>
</section>
| jamesBondu/test | _includes/about.html | HTML | apache-2.0 | 1,015 |
/**
* DeleteCustomTargetingValues.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
*/
package com.google.api.ads.dfp.axis.v201308;
/**
* Represents the delete action that can be performed on
* {@link CustomTargetingValue} objects.
*/
public class DeleteCustomTargetingValues extends com.google.api.ads.dfp.axis.v201308.CustomTargetingValueAction implements java.io.Serializable {
public DeleteCustomTargetingValues() {
}
public DeleteCustomTargetingValues(
java.lang.String customTargetingValueActionType) {
super(
customTargetingValueActionType);
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof DeleteCustomTargetingValues)) return false;
DeleteCustomTargetingValues other = (DeleteCustomTargetingValues) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = super.equals(obj);
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = super.hashCode();
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(DeleteCustomTargetingValues.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "DeleteCustomTargetingValues"));
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
| nafae/developer | modules/dfp_axis/src/main/java/com/google/api/ads/dfp/axis/v201308/DeleteCustomTargetingValues.java | Java | apache-2.0 | 2,806 |
'use strict';
goog.provide('Blockly.JavaScript.serial');
goog.require('Blockly.JavaScript');
Blockly.JavaScript.serial_print = function() {
var content = Blockly.JavaScript.valueToCode(this, 'CONTENT', Blockly.JavaScript.ORDER_ATOMIC) || '\"\"'
var code = 'serial.writeString(\'\' + '+content+');\n';
return code;
};
Blockly.JavaScript.serial_println = function() {
var content = Blockly.JavaScript.valueToCode(this, 'CONTENT', Blockly.JavaScript.ORDER_ATOMIC) || '\"\"'
var code = 'serial.writeLine(\'\' + '+content+');\n';
return code;
};
Blockly.JavaScript.serial_print_hex = function() {
var content = Blockly.JavaScript.valueToCode(this, 'CONTENT', Blockly.JavaScript.ORDER_ATOMIC) || '0';
var code = 'serial.writeLine('+content+'.toString(16));\n';
return code;
};
Blockly.JavaScript.serial_receive_data_event = function() {
var char_marker = Blockly.JavaScript.valueToCode(this, 'char_marker', Blockly.JavaScript.ORDER_ATOMIC) || ';';
var branch = Blockly.JavaScript.statementToCode(this, 'DO');
Blockly.JavaScript.definitions_['func_serial_receive_data_event_' + char_marker.charCodeAt(1)] = "serial.onDataReceived(" + char_marker + ", () => {\n" + branch + "};\n";
};
Blockly.JavaScript.serial_readstr = function() {
var code ="serial.readString()";
return [code,Blockly.JavaScript.ORDER_ATOMIC];
};
Blockly.JavaScript.serial_readline = function() {
var code ="serial.readLine()";
return [code,Blockly.JavaScript.ORDER_ATOMIC];
};
Blockly.JavaScript.serial_readstr_until = function() {
var char_marker = this.getFieldValue('char_marker');
var code ="serial.readUntil("+char_marker + ")";
return [code,Blockly.JavaScript.ORDER_ATOMIC];
};
Blockly.JavaScript.serial_softserial = function () {
var dropdown_pin1 = Blockly.JavaScript.valueToCode(this, 'RX',Blockly.JavaScript.ORDER_ATOMIC);
var dropdown_pin2 = Blockly.JavaScript.valueToCode(this, 'TX',Blockly.JavaScript.ORDER_ATOMIC);
var baudrate = this.getFieldValue('baudrate');
return "serial.redirect(" + dropdown_pin1 + ", " + dropdown_pin2 + ", BaudRate.BaudRate" + baudrate + ");\n";
};
| xbed/Mixly_Arduino | mixly_arduino/blockly/generators/microbit_js/serial.js | JavaScript | apache-2.0 | 2,128 |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
from google.cloud.spanner_v1.proto import (
result_set_pb2 as google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2,
)
from google.cloud.spanner_v1.proto import (
spanner_pb2 as google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2,
)
from google.cloud.spanner_v1.proto import (
transaction_pb2 as google_dot_cloud_dot_spanner__v1_dot_proto_dot_transaction__pb2,
)
from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2
class SpannerStub(object):
"""Cloud Spanner API
The Cloud Spanner API can be used to manage sessions and execute
transactions on data stored in Cloud Spanner databases.
"""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.CreateSession = channel.unary_unary(
"/google.spanner.v1.Spanner/CreateSession",
request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.CreateSessionRequest.SerializeToString,
response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.Session.FromString,
)
self.BatchCreateSessions = channel.unary_unary(
"/google.spanner.v1.Spanner/BatchCreateSessions",
request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.BatchCreateSessionsRequest.SerializeToString,
response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.BatchCreateSessionsResponse.FromString,
)
self.GetSession = channel.unary_unary(
"/google.spanner.v1.Spanner/GetSession",
request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.GetSessionRequest.SerializeToString,
response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.Session.FromString,
)
self.ListSessions = channel.unary_unary(
"/google.spanner.v1.Spanner/ListSessions",
request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ListSessionsRequest.SerializeToString,
response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ListSessionsResponse.FromString,
)
self.DeleteSession = channel.unary_unary(
"/google.spanner.v1.Spanner/DeleteSession",
request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.DeleteSessionRequest.SerializeToString,
response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString,
)
self.ExecuteSql = channel.unary_unary(
"/google.spanner.v1.Spanner/ExecuteSql",
request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ExecuteSqlRequest.SerializeToString,
response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.ResultSet.FromString,
)
self.ExecuteStreamingSql = channel.unary_stream(
"/google.spanner.v1.Spanner/ExecuteStreamingSql",
request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ExecuteSqlRequest.SerializeToString,
response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.PartialResultSet.FromString,
)
self.ExecuteBatchDml = channel.unary_unary(
"/google.spanner.v1.Spanner/ExecuteBatchDml",
request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ExecuteBatchDmlRequest.SerializeToString,
response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ExecuteBatchDmlResponse.FromString,
)
self.Read = channel.unary_unary(
"/google.spanner.v1.Spanner/Read",
request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ReadRequest.SerializeToString,
response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.ResultSet.FromString,
)
self.StreamingRead = channel.unary_stream(
"/google.spanner.v1.Spanner/StreamingRead",
request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ReadRequest.SerializeToString,
response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.PartialResultSet.FromString,
)
self.BeginTransaction = channel.unary_unary(
"/google.spanner.v1.Spanner/BeginTransaction",
request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.BeginTransactionRequest.SerializeToString,
response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_transaction__pb2.Transaction.FromString,
)
self.Commit = channel.unary_unary(
"/google.spanner.v1.Spanner/Commit",
request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.CommitRequest.SerializeToString,
response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.CommitResponse.FromString,
)
self.Rollback = channel.unary_unary(
"/google.spanner.v1.Spanner/Rollback",
request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.RollbackRequest.SerializeToString,
response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString,
)
self.PartitionQuery = channel.unary_unary(
"/google.spanner.v1.Spanner/PartitionQuery",
request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.PartitionQueryRequest.SerializeToString,
response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.PartitionResponse.FromString,
)
self.PartitionRead = channel.unary_unary(
"/google.spanner.v1.Spanner/PartitionRead",
request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.PartitionReadRequest.SerializeToString,
response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.PartitionResponse.FromString,
)
class SpannerServicer(object):
"""Cloud Spanner API
The Cloud Spanner API can be used to manage sessions and execute
transactions on data stored in Cloud Spanner databases.
"""
def CreateSession(self, request, context):
"""Creates a new session. A session can be used to perform
transactions that read and/or modify data in a Cloud Spanner database.
Sessions are meant to be reused for many consecutive
transactions.
Sessions can only execute one transaction at a time. To execute
multiple concurrent read-write/write-only transactions, create
multiple sessions. Note that standalone reads and queries use a
transaction internally, and count toward the one transaction
limit.
Active sessions use additional server resources, so it is a good idea to
delete idle and unneeded sessions.
Aside from explicit deletes, Cloud Spanner can delete sessions for which no
operations are sent for more than an hour. If a session is deleted,
requests to it return `NOT_FOUND`.
Idle sessions can be kept alive by sending a trivial SQL query
periodically, e.g., `"SELECT 1"`.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def BatchCreateSessions(self, request, context):
"""Creates multiple new sessions.
This API can be used to initialize a session cache on the clients.
See https://goo.gl/TgSFN2 for best practices on session cache management.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def GetSession(self, request, context):
"""Gets a session. Returns `NOT_FOUND` if the session does not exist.
This is mainly useful for determining whether a session is still
alive.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def ListSessions(self, request, context):
"""Lists all sessions in a given database.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def DeleteSession(self, request, context):
"""Ends a session, releasing server resources associated with it. This will
asynchronously trigger cancellation of any operations that are running with
this session.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def ExecuteSql(self, request, context):
"""Executes an SQL statement, returning all results in a single reply. This
method cannot be used to return a result set larger than 10 MiB;
if the query yields more data than that, the query fails with
a `FAILED_PRECONDITION` error.
Operations inside read-write transactions might return `ABORTED`. If
this occurs, the application should restart the transaction from
the beginning. See [Transaction][google.spanner.v1.Transaction] for more details.
Larger result sets can be fetched in streaming fashion by calling
[ExecuteStreamingSql][google.spanner.v1.Spanner.ExecuteStreamingSql] instead.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def ExecuteStreamingSql(self, request, context):
"""Like [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql], except returns the result
set as a stream. Unlike [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql], there
is no limit on the size of the returned result set. However, no
individual row in the result set can exceed 100 MiB, and no
column value can exceed 10 MiB.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def ExecuteBatchDml(self, request, context):
"""Executes a batch of SQL DML statements. This method allows many statements
to be run with lower latency than submitting them sequentially with
[ExecuteSql][google.spanner.v1.Spanner.ExecuteSql].
Statements are executed in sequential order. A request can succeed even if
a statement fails. The [ExecuteBatchDmlResponse.status][google.spanner.v1.ExecuteBatchDmlResponse.status] field in the
response provides information about the statement that failed. Clients must
inspect this field to determine whether an error occurred.
Execution stops after the first failed statement; the remaining statements
are not executed.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def Read(self, request, context):
"""Reads rows from the database using key lookups and scans, as a
simple key/value style alternative to
[ExecuteSql][google.spanner.v1.Spanner.ExecuteSql]. This method cannot be used to
return a result set larger than 10 MiB; if the read matches more
data than that, the read fails with a `FAILED_PRECONDITION`
error.
Reads inside read-write transactions might return `ABORTED`. If
this occurs, the application should restart the transaction from
the beginning. See [Transaction][google.spanner.v1.Transaction] for more details.
Larger result sets can be yielded in streaming fashion by calling
[StreamingRead][google.spanner.v1.Spanner.StreamingRead] instead.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def StreamingRead(self, request, context):
"""Like [Read][google.spanner.v1.Spanner.Read], except returns the result set as a
stream. Unlike [Read][google.spanner.v1.Spanner.Read], there is no limit on the
size of the returned result set. However, no individual row in
the result set can exceed 100 MiB, and no column value can exceed
10 MiB.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def BeginTransaction(self, request, context):
"""Begins a new transaction. This step can often be skipped:
[Read][google.spanner.v1.Spanner.Read], [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql] and
[Commit][google.spanner.v1.Spanner.Commit] can begin a new transaction as a
side-effect.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def Commit(self, request, context):
"""Commits a transaction. The request includes the mutations to be
applied to rows in the database.
`Commit` might return an `ABORTED` error. This can occur at any time;
commonly, the cause is conflicts with concurrent
transactions. However, it can also happen for a variety of other
reasons. If `Commit` returns `ABORTED`, the caller should re-attempt
the transaction from the beginning, re-using the same session.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def Rollback(self, request, context):
"""Rolls back a transaction, releasing any locks it holds. It is a good
idea to call this for any transaction that includes one or more
[Read][google.spanner.v1.Spanner.Read] or [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql] requests and
ultimately decides not to commit.
`Rollback` returns `OK` if it successfully aborts the transaction, the
transaction was already aborted, or the transaction is not
found. `Rollback` never returns `ABORTED`.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def PartitionQuery(self, request, context):
"""Creates a set of partition tokens that can be used to execute a query
operation in parallel. Each of the returned partition tokens can be used
by [ExecuteStreamingSql][google.spanner.v1.Spanner.ExecuteStreamingSql] to specify a subset
of the query result to read. The same session and read-only transaction
must be used by the PartitionQueryRequest used to create the
partition tokens and the ExecuteSqlRequests that use the partition tokens.
Partition tokens become invalid when the session used to create them
is deleted, is idle for too long, begins a new transaction, or becomes too
old. When any of these happen, it is not possible to resume the query, and
the whole operation must be restarted from the beginning.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def PartitionRead(self, request, context):
"""Creates a set of partition tokens that can be used to execute a read
operation in parallel. Each of the returned partition tokens can be used
by [StreamingRead][google.spanner.v1.Spanner.StreamingRead] to specify a subset of the read
result to read. The same session and read-only transaction must be used by
the PartitionReadRequest used to create the partition tokens and the
ReadRequests that use the partition tokens. There are no ordering
guarantees on rows returned among the returned partition tokens, or even
within each individual StreamingRead call issued with a partition_token.
Partition tokens become invalid when the session used to create them
is deleted, is idle for too long, begins a new transaction, or becomes too
old. When any of these happen, it is not possible to resume the read, and
the whole operation must be restarted from the beginning.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def add_SpannerServicer_to_server(servicer, server):
rpc_method_handlers = {
"CreateSession": grpc.unary_unary_rpc_method_handler(
servicer.CreateSession,
request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.CreateSessionRequest.FromString,
response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.Session.SerializeToString,
),
"BatchCreateSessions": grpc.unary_unary_rpc_method_handler(
servicer.BatchCreateSessions,
request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.BatchCreateSessionsRequest.FromString,
response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.BatchCreateSessionsResponse.SerializeToString,
),
"GetSession": grpc.unary_unary_rpc_method_handler(
servicer.GetSession,
request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.GetSessionRequest.FromString,
response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.Session.SerializeToString,
),
"ListSessions": grpc.unary_unary_rpc_method_handler(
servicer.ListSessions,
request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ListSessionsRequest.FromString,
response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ListSessionsResponse.SerializeToString,
),
"DeleteSession": grpc.unary_unary_rpc_method_handler(
servicer.DeleteSession,
request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.DeleteSessionRequest.FromString,
response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString,
),
"ExecuteSql": grpc.unary_unary_rpc_method_handler(
servicer.ExecuteSql,
request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ExecuteSqlRequest.FromString,
response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.ResultSet.SerializeToString,
),
"ExecuteStreamingSql": grpc.unary_stream_rpc_method_handler(
servicer.ExecuteStreamingSql,
request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ExecuteSqlRequest.FromString,
response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.PartialResultSet.SerializeToString,
),
"ExecuteBatchDml": grpc.unary_unary_rpc_method_handler(
servicer.ExecuteBatchDml,
request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ExecuteBatchDmlRequest.FromString,
response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ExecuteBatchDmlResponse.SerializeToString,
),
"Read": grpc.unary_unary_rpc_method_handler(
servicer.Read,
request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ReadRequest.FromString,
response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.ResultSet.SerializeToString,
),
"StreamingRead": grpc.unary_stream_rpc_method_handler(
servicer.StreamingRead,
request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ReadRequest.FromString,
response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.PartialResultSet.SerializeToString,
),
"BeginTransaction": grpc.unary_unary_rpc_method_handler(
servicer.BeginTransaction,
request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.BeginTransactionRequest.FromString,
response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_transaction__pb2.Transaction.SerializeToString,
),
"Commit": grpc.unary_unary_rpc_method_handler(
servicer.Commit,
request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.CommitRequest.FromString,
response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.CommitResponse.SerializeToString,
),
"Rollback": grpc.unary_unary_rpc_method_handler(
servicer.Rollback,
request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.RollbackRequest.FromString,
response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString,
),
"PartitionQuery": grpc.unary_unary_rpc_method_handler(
servicer.PartitionQuery,
request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.PartitionQueryRequest.FromString,
response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.PartitionResponse.SerializeToString,
),
"PartitionRead": grpc.unary_unary_rpc_method_handler(
servicer.PartitionRead,
request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.PartitionReadRequest.FromString,
response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.PartitionResponse.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
"google.spanner.v1.Spanner", rpc_method_handlers
)
server.add_generic_rpc_handlers((generic_handler,))
| tseaver/google-cloud-python | spanner/google/cloud/spanner_v1/proto/spanner_pb2_grpc.py | Python | apache-2.0 | 22,552 |
package com.comps.util;
import com.google.gson.Gson;
public class GsonManager {
private static Gson instance;
public static Gson getInstance(){
if (instance == null){
instance = new Gson();
}
return instance;
}
}
| diogocs1/comps | mobile/src/com/comps/util/GsonManager.java | Java | apache-2.0 | 231 |
/**
* Blueprint API Configuration
* (sails.config.blueprints)
*
* These settings are for the global configuration of blueprint routes and
* request options (which impact the behavior of blueprint actions).
*
* You may also override any of these settings on a per-controller basis
* by defining a '_config' key in your controller defintion, and assigning it
* a configuration object with overrides for the settings in this file.
* A lot of the configuration options below affect so-called "CRUD methods",
* or your controllers' `find`, `create`, `update`, and `destroy` actions.
*
* It's important to realize that, even if you haven't defined these yourself, as long as
* a model exists with the same name as the controller, Sails will respond with built-in CRUD
* logic in the form of a JSON API, including support for sort, pagination, and filtering.
*
* For more information on the blueprint API, check out:
* http://sailsjs.org/#/documentation/reference/blueprint-api
*
* For more information on the settings in this file, see:
* http://sailsjs.org/#/documentation/reference/sails.config/sails.config.blueprints.html
*
*/
module.exports.blueprints = {
/***************************************************************************
* *
* Action routes speed up the backend development workflow by *
* eliminating the need to manually bind routes. When enabled, GET, POST, *
* PUT, and DELETE routes will be generated for every one of a controller's *
* actions. *
* *
* If an `index` action exists, additional naked routes will be created for *
* it. Finally, all `actions` blueprints support an optional path *
* parameter, `id`, for convenience. *
* *
* `actions` are enabled by default, and can be OK for production-- *
* however, if you'd like to continue to use controller/action autorouting *
* in a production deployment, you must take great care not to *
* inadvertently expose unsafe/unintentional controller logic to GET *
* requests. *
* *
***************************************************************************/
actions: true,
/***************************************************************************
* *
* RESTful routes (`sails.config.blueprints.rest`) *
* *
* REST blueprints are the automatically generated routes Sails uses to *
* expose a conventional REST API on top of a controller's `find`, *
* `create`, `update`, and `destroy` actions. *
* *
* For example, a BoatController with `rest` enabled generates the *
* following routes: *
* ::::::::::::::::::::::::::::::::::::::::::::::::::::::: *
* GET /boat/:id? -> BoatController.find *
* POST /boat -> BoatController.create *
* PUT /boat/:id -> BoatController.update *
* DELETE /boat/:id -> BoatController.destroy *
* *
* `rest` blueprint routes are enabled by default, and are suitable for use *
* in a production scenario, as long you take standard security precautions *
* (combine w/ policies, etc.) *
* *
***************************************************************************/
rest: true,
/***************************************************************************
* *
* Shortcut routes are simple helpers to provide access to a *
* controller's CRUD methods from your browser's URL bar. When enabled, *
* GET, POST, PUT, and DELETE routes will be generated for the *
* controller's`find`, `create`, `update`, and `destroy` actions. *
* *
* `shortcuts` are enabled by default, but should be disabled in *
* production. *
* *
***************************************************************************/
shortcuts: true,
/***************************************************************************
* *
* An optional mount path for all blueprint routes on a controller, *
* including `rest`, `actions`, and `shortcuts`. This allows you to take *
* advantage of blueprint routing, even if you need to namespace your API *
* methods. *
* *
* (NOTE: This only applies to blueprint autoroutes, not manual routes from *
* `sails.config.routes`) *
* *
***************************************************************************/
prefix: '/api/v1.0',
/***************************************************************************
* *
* Whether to pluralize controller names in blueprint routes. *
* *
* (NOTE: This only applies to blueprint autoroutes, not manual routes from *
* `sails.config.routes`) *
* *
* For example, REST blueprints for `FooController` with `pluralize` *
* enabled: *
* GET /foos/:id? *
* POST /foos *
* PUT /foos/:id? *
* DELETE /foos/:id? *
* *
***************************************************************************/
// pluralize: false,
/***************************************************************************
* *
* Whether the blueprint controllers should populate model fetches with *
* data from other models which are linked by associations *
* *
* If you have a lot of data in one-to-many associations, leaving this on *
* may result in very heavy api calls *
* *
***************************************************************************/
// populate: true,
/****************************************************************************
* *
* Whether to run Model.watch() in the find and findOne blueprint actions. *
* Can be overridden on a per-model basis. *
* *
****************************************************************************/
// autoWatch: true,
/****************************************************************************
* *
* The default number of records to show in the response from a "find" *
* action. Doubles as the default size of populated arrays if populate is *
* true. *
* *
****************************************************************************/
// defaultLimit: 30
};
| kmangutov/leaguemontages | config/blueprints.js | JavaScript | apache-2.0 | 9,115 |
-------------------------------------------------------------------------------
-- budget info
-------------------------------------------------------------------------------
CREATE TABLE BUDGET_INFO(
ID BIGINT NOT NULL,
NAME VARCHAR(200),
CREATE_TIME DATETIME,
STATUS VARCHAR(50),
TYPE VARCHAR(50),
MONEY DOUBLE,
START_TIME DATETIME,
END_TIME DATETIME,
DESCRIPTION TEXT,
USER_ID VARCHAR(64),
TENANT_ID VARCHAR(64),
CONSTRAINT PK_BUDGET_INFO PRIMARY KEY(ID)
) ENGINE=INNODB CHARSET=UTF8;
| topie/topie-oa | src/main/resources/dbmigrate/mysql/budget/V0_0_0_1__budget_info.sql | SQL | apache-2.0 | 518 |
import { IInjectable } from "../common/common";
import { TypedMap } from "../common/common";
import { StateProvider } from "./stateProvider";
import { ResolveContext } from "../resolve/resolveContext";
import * as angular from 'angular';
import IScope = angular.IScope;
/**
* Annotates a controller expression (may be a controller function(), a "controllername",
* or "controllername as name")
*
* - Temporarily decorates $injector.instantiate.
* - Invokes $controller() service
* - Calls $injector.instantiate with controller constructor
* - Annotate constructor
* - Undecorate $injector
*
* returns an array of strings, which are the arguments of the controller expression
*/
export declare function annotateController(controllerExpression: (IInjectable | string)): string[];
declare module "../router" {
interface UIRouter {
/** @hidden TODO: move this to ng1.ts */
stateProvider: StateProvider;
}
}
export declare function watchDigests($rootScope: IScope): void;
export declare const getLocals: (ctx: ResolveContext) => TypedMap<any>;
| sztymelq/sztymelscy-webpack | node_modules/angular-ui-router/release/ng1/services.d.ts | TypeScript | apache-2.0 | 1,103 |
// This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.java_smt.test;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.TruthJUnit.assume;
import static org.sosy_lab.java_smt.api.FormulaType.BooleanType;
import static org.sosy_lab.java_smt.api.FormulaType.IntegerType;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.testing.EqualsTester;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
import org.sosy_lab.java_smt.SolverContextFactory.Solvers;
import org.sosy_lab.java_smt.api.ArrayFormula;
import org.sosy_lab.java_smt.api.BitvectorFormula;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.FormulaType;
import org.sosy_lab.java_smt.api.FormulaType.ArrayFormulaType;
import org.sosy_lab.java_smt.api.FunctionDeclaration;
import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula;
import org.sosy_lab.java_smt.api.SolverException;
@RunWith(Parameterized.class)
public class FormulaManagerTest extends SolverBasedTest0 {
@Parameters(name = "{0}")
public static Object[] getAllSolvers() {
return Solvers.values();
}
@Parameter(0)
public Solvers solver;
@Override
protected Solvers solverToUse() {
return solver;
}
@Test
public void testEmptySubstitution() throws SolverException, InterruptedException {
// Boolector does not support substitution
assume().that(solverToUse()).isNotEqualTo(Solvers.BOOLECTOR);
assume().withMessage("Princess fails").that(solver).isNotEqualTo(Solvers.PRINCESS);
IntegerFormula variable1 = imgr.makeVariable("variable1");
IntegerFormula variable2 = imgr.makeVariable("variable2");
IntegerFormula variable3 = imgr.makeVariable("variable3");
IntegerFormula variable4 = imgr.makeVariable("variable4");
FunctionDeclaration<BooleanFormula> uf2Decl =
fmgr.declareUF("uf", BooleanType, IntegerType, IntegerType);
BooleanFormula f1 = fmgr.callUF(uf2Decl, variable1, variable3);
BooleanFormula f2 = fmgr.callUF(uf2Decl, variable2, variable4);
BooleanFormula input = bmgr.xor(f1, f2);
BooleanFormula out = mgr.substitute(input, ImmutableMap.of());
assertThatFormula(out).isEquivalentTo(input);
}
@Test
public void testNoSubstitution() throws SolverException, InterruptedException {
// Boolector does not support substitution
assume().that(solverToUse()).isNotEqualTo(Solvers.BOOLECTOR);
assume().withMessage("Princess fails").that(solver).isNotEqualTo(Solvers.PRINCESS);
IntegerFormula variable1 = imgr.makeVariable("variable1");
IntegerFormula variable2 = imgr.makeVariable("variable2");
IntegerFormula variable3 = imgr.makeVariable("variable3");
IntegerFormula variable4 = imgr.makeVariable("variable4");
FunctionDeclaration<BooleanFormula> uf2Decl =
fmgr.declareUF("uf", BooleanType, IntegerType, IntegerType);
BooleanFormula f1 = fmgr.callUF(uf2Decl, variable1, variable3);
BooleanFormula f2 = fmgr.callUF(uf2Decl, variable2, variable4);
BooleanFormula input = bmgr.xor(f1, f2);
Map<BooleanFormula, BooleanFormula> substitution =
ImmutableMap.of(
bmgr.makeVariable("a"), bmgr.makeVariable("a1"),
bmgr.makeVariable("b"), bmgr.makeVariable("b1"),
bmgr.and(bmgr.makeVariable("c"), bmgr.makeVariable("d")), bmgr.makeVariable("e"));
BooleanFormula out = mgr.substitute(input, substitution);
assertThatFormula(out).isEquivalentTo(input);
}
@Test
public void testSubstitution() throws SolverException, InterruptedException {
// Boolector does not support substitution
assume().that(solverToUse()).isNotEqualTo(Solvers.BOOLECTOR);
BooleanFormula input =
bmgr.or(
bmgr.and(bmgr.makeVariable("a"), bmgr.makeVariable("b")),
bmgr.and(bmgr.makeVariable("c"), bmgr.makeVariable("d")));
BooleanFormula out =
mgr.substitute(
input,
ImmutableMap.of(
bmgr.makeVariable("a"), bmgr.makeVariable("a1"),
bmgr.makeVariable("b"), bmgr.makeVariable("b1"),
bmgr.and(bmgr.makeVariable("c"), bmgr.makeVariable("d")), bmgr.makeVariable("e")));
assertThatFormula(out)
.isEquivalentTo(
bmgr.or(
bmgr.and(bmgr.makeVariable("a1"), bmgr.makeVariable("b1")),
bmgr.makeVariable("e")));
}
@Test
public void testSubstitutionTwice() throws SolverException, InterruptedException {
// Boolector does not support substitution
assume().that(solverToUse()).isNotEqualTo(Solvers.BOOLECTOR);
BooleanFormula input =
bmgr.or(
bmgr.and(bmgr.makeVariable("a"), bmgr.makeVariable("b")),
bmgr.and(bmgr.makeVariable("c"), bmgr.makeVariable("d")));
ImmutableMap<BooleanFormula, BooleanFormula> substitution =
ImmutableMap.of(
bmgr.makeVariable("a"), bmgr.makeVariable("a1"),
bmgr.makeVariable("b"), bmgr.makeVariable("b1"),
bmgr.and(bmgr.makeVariable("c"), bmgr.makeVariable("d")), bmgr.makeVariable("e"));
BooleanFormula out = mgr.substitute(input, substitution);
assertThatFormula(out)
.isEquivalentTo(
bmgr.or(
bmgr.and(bmgr.makeVariable("a1"), bmgr.makeVariable("b1")),
bmgr.makeVariable("e")));
BooleanFormula out2 = mgr.substitute(out, substitution);
assertThatFormula(out2).isEquivalentTo(out);
}
@Test
public void formulaEqualsAndHashCode() {
// Solvers without integers (Boolector) get their own test below
assume().that(solverToUse()).isNotEqualTo(Solvers.BOOLECTOR);
FunctionDeclaration<IntegerFormula> fb = fmgr.declareUF("f_b", IntegerType, IntegerType);
new EqualsTester()
.addEqualityGroup(bmgr.makeBoolean(true))
.addEqualityGroup(bmgr.makeBoolean(false))
.addEqualityGroup(bmgr.makeVariable("bool_a"))
.addEqualityGroup(imgr.makeVariable("int_a"))
// Way of creating numbers should not make a difference.
.addEqualityGroup(
imgr.makeNumber(0.0),
imgr.makeNumber(0L),
imgr.makeNumber(BigInteger.ZERO),
imgr.makeNumber(BigDecimal.ZERO),
imgr.makeNumber("0"))
.addEqualityGroup(
imgr.makeNumber(1.0),
imgr.makeNumber(1L),
imgr.makeNumber(BigInteger.ONE),
imgr.makeNumber(BigDecimal.ONE),
imgr.makeNumber("1"))
// The same formula when created twice should compare equal.
.addEqualityGroup(bmgr.makeVariable("bool_b"), bmgr.makeVariable("bool_b"))
.addEqualityGroup(
bmgr.and(bmgr.makeVariable("bool_a"), bmgr.makeVariable("bool_b")),
bmgr.and(bmgr.makeVariable("bool_a"), bmgr.makeVariable("bool_b")))
.addEqualityGroup(
imgr.equal(imgr.makeNumber(0), imgr.makeVariable("int_a")),
imgr.equal(imgr.makeNumber(0), imgr.makeVariable("int_a")))
// UninterpretedFunctionDeclarations should not compare equal to Formulas,
// but declaring one twice needs to return the same UIF.
.addEqualityGroup(
fmgr.declareUF("f_a", IntegerType, IntegerType),
fmgr.declareUF("f_a", IntegerType, IntegerType))
.addEqualityGroup(fb)
.addEqualityGroup(fmgr.callUF(fb, imgr.makeNumber(0)))
.addEqualityGroup(fmgr.callUF(fb, imgr.makeNumber(1)), fmgr.callUF(fb, imgr.makeNumber(1)))
.testEquals();
}
@Test
public void bitvectorFormulaEqualsAndHashCode() {
// Boolector does not support integers and it is easier to make a new test with bvs
requireBitvectors();
FunctionDeclaration<BitvectorFormula> fb =
fmgr.declareUF(
"f_bv",
FormulaType.getBitvectorTypeWithSize(8),
FormulaType.getBitvectorTypeWithSize(8));
new EqualsTester()
.addEqualityGroup(bmgr.makeBoolean(true))
.addEqualityGroup(bmgr.makeBoolean(false))
.addEqualityGroup(bmgr.makeVariable("bool_a"))
.addEqualityGroup(bvmgr.makeVariable(8, "bv_a"))
// Way of creating numbers should not make a difference.
.addEqualityGroup(
bvmgr.makeBitvector(8, 0L),
bvmgr.makeBitvector(8, 0),
bvmgr.makeBitvector(8, BigInteger.ZERO))
.addEqualityGroup(
bvmgr.makeBitvector(8, 1L),
bvmgr.makeBitvector(8, 1),
bvmgr.makeBitvector(8, BigInteger.ONE))
// The same formula when created twice should compare equal.
.addEqualityGroup(bmgr.makeVariable("bool_b"), bmgr.makeVariable("bool_b"))
.addEqualityGroup(
bmgr.and(bmgr.makeVariable("bool_a"), bmgr.makeVariable("bool_b")),
bmgr.and(bmgr.makeVariable("bool_a"), bmgr.makeVariable("bool_b")))
.addEqualityGroup(
bvmgr.equal(bvmgr.makeBitvector(8, 0), bvmgr.makeVariable(8, "int_a")),
bvmgr.equal(bvmgr.makeBitvector(8, 0), bvmgr.makeVariable(8, "int_a")))
// UninterpretedFunctionDeclarations should not compare equal to Formulas,
// but declaring one twice needs to return the same UIF.
.addEqualityGroup(
fmgr.declareUF(
"f_a",
FormulaType.getBitvectorTypeWithSize(8),
FormulaType.getBitvectorTypeWithSize(8)),
fmgr.declareUF(
"f_a",
FormulaType.getBitvectorTypeWithSize(8),
FormulaType.getBitvectorTypeWithSize(8)))
.addEqualityGroup(fb)
.addEqualityGroup(fmgr.callUF(fb, bvmgr.makeBitvector(8, 0)))
.addEqualityGroup(
fmgr.callUF(fb, bvmgr.makeBitvector(8, 1)), // why not equal?!
fmgr.callUF(fb, bvmgr.makeBitvector(8, 1)))
.testEquals();
}
@Test
public void variableNameExtractorTest() {
// Since Boolector does not support integers we use bitvectors
if (imgr != null) {
BooleanFormula constr =
bmgr.or(
imgr.equal(
imgr.subtract(
imgr.add(imgr.makeVariable("x"), imgr.makeVariable("z")),
imgr.makeNumber(10)),
imgr.makeVariable("y")),
imgr.equal(imgr.makeVariable("xx"), imgr.makeVariable("zz")));
assertThat(mgr.extractVariables(constr).keySet()).containsExactly("x", "y", "z", "xx", "zz");
assertThat(mgr.extractVariablesAndUFs(constr)).isEqualTo(mgr.extractVariables(constr));
} else {
BooleanFormula bvConstr =
bmgr.or(
bvmgr.equal(
bvmgr.subtract(
bvmgr.add(bvmgr.makeVariable(8, "x"), bvmgr.makeVariable(8, "z")),
bvmgr.makeBitvector(8, 10)),
bvmgr.makeVariable(8, "y")),
bvmgr.equal(bvmgr.makeVariable(8, "xx"), bvmgr.makeVariable(8, "zz")));
requireVisitor();
assertThat(mgr.extractVariables(bvConstr).keySet())
.containsExactly("x", "y", "z", "xx", "zz");
assertThat(mgr.extractVariablesAndUFs(bvConstr)).isEqualTo(mgr.extractVariables(bvConstr));
}
}
@Test
public void ufNameExtractorTest() {
// Since Boolector does not support integers we use bitvectors for constraints
if (imgr != null) {
BooleanFormula constraint =
imgr.equal(
fmgr.declareAndCallUF("uf1", IntegerType, ImmutableList.of(imgr.makeVariable("x"))),
fmgr.declareAndCallUF("uf2", IntegerType, ImmutableList.of(imgr.makeVariable("y"))));
assertThat(mgr.extractVariablesAndUFs(constraint).keySet())
.containsExactly("uf1", "uf2", "x", "y");
assertThat(mgr.extractVariables(constraint).keySet()).containsExactly("x", "y");
} else {
BooleanFormula bvConstraint =
bvmgr.equal(
fmgr.declareAndCallUF(
"uf1",
FormulaType.getBitvectorTypeWithSize(8),
ImmutableList.of(bvmgr.makeVariable(8, "x"))),
fmgr.declareAndCallUF(
"uf2",
FormulaType.getBitvectorTypeWithSize(8),
ImmutableList.of(bvmgr.makeVariable(8, "y"))));
requireVisitor();
assertThat(mgr.extractVariablesAndUFs(bvConstraint).keySet())
.containsExactly("uf1", "uf2", "x", "y");
assertThat(mgr.extractVariables(bvConstraint).keySet()).containsExactly("x", "y");
}
}
@Test
public void simplifyIntTest() throws SolverException, InterruptedException {
requireIntegers();
// x=1 && y=x+2 && z=y+3 --> simplified: x=1 && y=3 && z=6
IntegerFormula num1 = imgr.makeNumber(1);
IntegerFormula num2 = imgr.makeNumber(2);
IntegerFormula num3 = imgr.makeNumber(3);
IntegerFormula x = imgr.makeVariable("x");
IntegerFormula y = imgr.makeVariable("y");
IntegerFormula z = imgr.makeVariable("z");
BooleanFormula f =
bmgr.and(
imgr.equal(x, num1),
imgr.equal(y, imgr.add(x, num2)),
imgr.equal(z, imgr.add(y, num3)));
assertThatFormula(mgr.simplify(f)).isEquisatisfiableTo(f);
}
@Test
public void simplifyArrayTest() throws SolverException, InterruptedException {
requireIntegers();
requireArrays();
// exists arr : (arr[0]=5 && x=arr[0]) --> simplified: x=5
ArrayFormula<IntegerFormula, IntegerFormula> arr =
amgr.makeArray("arr", new ArrayFormulaType<>(IntegerType, IntegerType));
IntegerFormula index = imgr.makeNumber(0);
IntegerFormula value = imgr.makeNumber(5);
IntegerFormula x = imgr.makeVariable("x");
ArrayFormula<IntegerFormula, IntegerFormula> write = amgr.store(arr, index, value);
IntegerFormula read = amgr.select(write, index);
BooleanFormula f = imgr.equal(x, read);
assertThatFormula(mgr.simplify(f)).isEquisatisfiableTo(f);
}
}
| sosy-lab/java-smt | src/org/sosy_lab/java_smt/test/FormulaManagerTest.java | Java | apache-2.0 | 14,364 |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.0-b52-fcs
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2012.09.17 at 02:39:44 오후 KST
//
package com.athena.chameleon.engine.entity.xml.application.jeus.v5_0;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
/**
* <p>Java class for vendorType.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="vendorType">
* <restriction base="{http://www.w3.org/2001/XMLSchema}token">
* <enumeration value="oracle"/>
* <enumeration value="sybase"/>
* <enumeration value="mssql"/>
* <enumeration value="db2"/>
* <enumeration value="tibero"/>
* <enumeration value="informix"/>
* <enumeration value="mysql"/>
* <enumeration value="others"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlEnum
public enum VendorType {
@XmlEnumValue("db2")
DB_2("db2"),
@XmlEnumValue("informix")
INFORMIX("informix"),
@XmlEnumValue("mssql")
MSSQL("mssql"),
@XmlEnumValue("mysql")
MYSQL("mysql"),
@XmlEnumValue("oracle")
ORACLE("oracle"),
@XmlEnumValue("others")
OTHERS("others"),
@XmlEnumValue("sybase")
SYBASE("sybase"),
@XmlEnumValue("tibero")
TIBERO("tibero");
private final String value;
VendorType(String v) {
value = v;
}
public String value() {
return value;
}
public static VendorType fromValue(String v) {
for (VendorType c: VendorType.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v.toString());
}
}
| OpenSourceConsulting/athena-chameleon | src/main/java/com/athena/chameleon/engine/entity/xml/application/jeus/v5_0/VendorType.java | Java | apache-2.0 | 1,969 |
#!/bin/bash
SOURCE="${BASH_SOURCE[0]}"
while [ -h ${SOURCE} ];do
DIR=$( cd -P $( dirname ${SOURCE} ) && pwd )
SOURCE="$(readlink ${SOURCE})"
[[ ${SOURCE} != /* ]] && SOURCE=${DIR}/${SOURCE}
done
BASEDIR="$( cd -P $( dirname ${SOURCE} ) && pwd )"
cd ${BASEDIR}
docker build -t zkpregistry.com:5043/alpine-tomcat:jre7tomcat7 -f ${BASEDIR}/Dockerfile ${BASEDIR}/
| blackfishdel/paas | docker-script/docker-alpine3.4-jre7-tomcat7/build.sh | Shell | apache-2.0 | 367 |
package it.unibz.inf.ontop.renderer;
/*
* #%L
* ontop-obdalib-core
* %%
* Copyright (C) 2009 - 2014 Free University of Bozen-Bolzano
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import it.unibz.inf.ontop.io.PrefixManager;
import it.unibz.inf.ontop.io.SimplePrefixManager;
import it.unibz.inf.ontop.model.Constant;
import it.unibz.inf.ontop.model.DatatypeFactory;
import it.unibz.inf.ontop.model.ExpressionOperation;
import it.unibz.inf.ontop.model.Function;
import it.unibz.inf.ontop.model.Predicate;
import it.unibz.inf.ontop.model.Term;
import it.unibz.inf.ontop.model.URIConstant;
import it.unibz.inf.ontop.model.URITemplatePredicate;
import it.unibz.inf.ontop.model.ValueConstant;
import it.unibz.inf.ontop.model.Variable;
import it.unibz.inf.ontop.model.impl.OBDADataFactoryImpl;
import it.unibz.inf.ontop.model.impl.OBDAVocabulary;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* A utility class to render a Target Query object into its representational
* string.
*/
public class TargetQueryRenderer {
private static final DatatypeFactory dtfac = OBDADataFactoryImpl.getInstance().getDatatypeFactory();
/**
* Transforms the given <code>OBDAQuery</code> into a string. The method requires
* a prefix manager to shorten full IRI name.
*/
public static String encode(List<Function> input, PrefixManager prefixManager) {
TurtleWriter turtleWriter = new TurtleWriter();
List<Function> body = input;
for (Function atom : body) {
String subject, predicate, object = "";
String originalString = atom.getFunctionSymbol().toString();
if (isUnary(atom)) {
Term subjectTerm = atom.getTerm(0);
subject = getDisplayName(subjectTerm, prefixManager);
predicate = "a";
object = getAbbreviatedName(originalString, prefixManager, false);
if (originalString.equals(object)) {
object = "<" + object + ">";
}
}
else if (originalString.equals("triple")) {
Term subjectTerm = atom.getTerm(0);
subject = getDisplayName(subjectTerm, prefixManager);
Term predicateTerm = atom.getTerm(1);
predicate = getDisplayName(predicateTerm, prefixManager);
Term objectTerm = atom.getTerm(2);
object = getDisplayName(objectTerm, prefixManager);
}
else {
Term subjectTerm = atom.getTerm(0);
subject = getDisplayName(subjectTerm, prefixManager);
predicate = getAbbreviatedName(originalString, prefixManager, false);
if (originalString.equals(predicate)) {
predicate = "<" + predicate + ">";
}
Term objectTerm = atom.getTerm(1);
object = getDisplayName(objectTerm, prefixManager);
}
turtleWriter.put(subject, predicate, object);
}
return turtleWriter.print();
}
/**
* Checks if the atom is unary or not.
*/
private static boolean isUnary(Function atom) {
return atom.getArity() == 1 ? true : false;
}
/**
* Prints the short form of the predicate (by omitting the complete URI and
* replacing it by a prefix name).
*
* Note that by default this method will consider a set of predefined
* prefixes, i.e., rdf:, rdfs:, owl:, xsd: and quest: To support this
* prefixes the method will temporally add the prefixes if they dont exist
* already, taken care to remove them if they didn't exist.
*
* The implementation requires at the moment, the implementation requires
* cloning the existing prefix manager, and hence this is highly inefficient
* method. *
*/
private static String getAbbreviatedName(String uri, PrefixManager pm, boolean insideQuotes) {
// Cloning the existing manager
PrefixManager prefManClone = new SimplePrefixManager();
Map<String,String> currentMap = pm.getPrefixMap();
for (String prefix: currentMap.keySet()) {
prefManClone.addPrefix(prefix, pm.getURIDefinition(prefix));
}
return prefManClone.getShortForm(uri, insideQuotes);
}
private static String appendTerms(Term term){
if (term instanceof Constant){
String st = ((Constant) term).getValue();
if (st.contains("{")){
st = st.replace("{", "\\{");
st = st.replace("}", "\\}");
}
return st;
}else{
return "{"+((Variable) term).getName()+"}";
}
}
//Appends nested concats
public static void getNestedConcats(StringBuilder stb, Term term1, Term term2){
if (term1 instanceof Function){
Function f = (Function) term1;
getNestedConcats(stb, f.getTerms().get(0), f.getTerms().get(1));
}else{
stb.append(appendTerms(term1));
}
if (term2 instanceof Function){
Function f = (Function) term2;
getNestedConcats(stb, f.getTerms().get(0), f.getTerms().get(1));
}else{
stb.append(appendTerms(term2));
}
}
/**
* Prints the text representation of different terms.
*/
private static String getDisplayName(Term term, PrefixManager prefixManager) {
StringBuilder sb = new StringBuilder();
if (term instanceof Function) {
Function function = (Function) term;
Predicate functionSymbol = function.getFunctionSymbol();
String fname = getAbbreviatedName(functionSymbol.toString(), prefixManager, false);
if (function.isDataTypeFunction()) {
// if the function symbol is a data type predicate
if (dtfac.isLiteral(functionSymbol)) {
// if it is rdfs:Literal
int arity = function.getArity();
if (arity == 1) {
// without the language tag
Term var = function.getTerms().get(0);
sb.append(getDisplayName(var, prefixManager));
sb.append("^^rdfs:Literal");
} else if (arity == 2) {
// with the language tag
Term var = function.getTerms().get(0);
Term lang = function.getTerms().get(1);
sb.append(getDisplayName(var, prefixManager));
sb.append("@");
if (lang instanceof ValueConstant) {
// Don't pass this to getDisplayName() because
// language constant is not written as @"lang-tag"
sb.append(((ValueConstant) lang).getValue());
} else {
sb.append(getDisplayName(lang, prefixManager));
}
}
} else { // for the other data types
Term var = function.getTerms().get(0);
sb.append(getDisplayName(var, prefixManager));
sb.append("^^");
sb.append(fname);
}
} else if (functionSymbol instanceof URITemplatePredicate) {
Term firstTerm = function.getTerms().get(0);
if(firstTerm instanceof Variable)
{
sb.append("<{");
sb.append(((Variable) firstTerm).getName());
sb.append("}>");
}
else {
String template = ((ValueConstant) firstTerm).getValue();
// Utilize the String.format() method so we replaced placeholders '{}' with '%s'
String templateFormat = template.replace("{}", "%s");
List<String> varNames = new ArrayList<String>();
for (Term innerTerm : function.getTerms()) {
if (innerTerm instanceof Variable) {
varNames.add(getDisplayName(innerTerm, prefixManager));
}
}
String originalUri = String.format(templateFormat, varNames.toArray());
if (originalUri.equals(OBDAVocabulary.RDF_TYPE)) {
sb.append("a");
} else {
String shortenUri = getAbbreviatedName(originalUri, prefixManager, false); // shorten the URI if possible
if (!shortenUri.equals(originalUri)) {
sb.append(shortenUri);
} else {
// If the URI can't be shorten then use the full URI within brackets
sb.append("<");
sb.append(originalUri);
sb.append(">");
}
}
}
}
else if (functionSymbol == ExpressionOperation.CONCAT) { //Concat
List<Term> terms = function.getTerms();
sb.append("\"");
getNestedConcats(sb, terms.get(0),terms.get(1));
sb.append("\"");
//sb.append("^^rdfs:Literal");
}
else { // for any ordinary function symbol
sb.append(fname);
sb.append("(");
boolean separator = false;
for (Term innerTerm : function.getTerms()) {
if (separator) {
sb.append(", ");
}
sb.append(getDisplayName(innerTerm, prefixManager));
separator = true;
}
sb.append(")");
}
} else if (term instanceof Variable) {
sb.append("{");
sb.append(((Variable) term).getName());
sb.append("}");
} else if (term instanceof URIConstant) {
String originalUri = term.toString();
String shortenUri = getAbbreviatedName(originalUri, prefixManager, false); // shorten the URI if possible
if (!shortenUri.equals(originalUri)) {
sb.append(shortenUri);
} else {
// If the URI can't be shorten then use the full URI within brackets
sb.append("<");
sb.append(originalUri);
sb.append(">");
}
} else if (term instanceof ValueConstant) {
sb.append("\"");
sb.append(((ValueConstant) term).getValue());
sb.append("\"");
}
return sb.toString();
}
private TargetQueryRenderer() {
// Prevent initialization
}
}
| srapisarda/ontop | obdalib-core/src/main/java/it/unibz/inf/ontop/renderer/TargetQueryRenderer.java | Java | apache-2.0 | 9,391 |
#define SQLITE_ASCII
#define SQLITE_DISABLE_LFS
#define SQLITE_ENABLE_OVERSIZE_CELL_CHECK
#define SQLITE_MUTEX_OMIT
#define SQLITE_OMIT_AUTHORIZATION
#define SQLITE_OMIT_DEPRECATED
#define SQLITE_OMIT_GET_TABLE
#define SQLITE_OMIT_INCRBLOB
#define SQLITE_OMIT_LOOKASIDE
#define SQLITE_OMIT_SHARED_CACHE
#define SQLITE_OMIT_UTF16
#define SQLITE_OMIT_WAL
#define SQLITE_OS_WIN
#define SQLITE_SYSTEM_MALLOC
#define VDBE_PROFILE_OFF
#define WINDOWS_MOBILE
#define NDEBUG
#define _MSC_VER
#define YYFALLBACK
//#define SQLITE_HAS_CODEC
using System;
using System.Diagnostics;
using System.Text;
using u8 = System.Byte;
using u32 = System.UInt32;
namespace Community.CsharpSqlite
{
using sqlite3_value = Sqlite3.Mem;
public partial class Sqlite3
{
/*
** 2003 April 6
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains code used to implement the ATTACH and DETACH commands.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2
**
*************************************************************************
*/
//#include "sqliteInt.h"
#if !SQLITE_OMIT_ATTACH
/*
** Resolve an expression that was part of an ATTACH or DETACH statement. This
** is slightly different from resolving a normal SQL expression, because simple
** identifiers are treated as strings, not possible column names or aliases.
**
** i.e. if the parser sees:
**
** ATTACH DATABASE abc AS def
**
** it treats the two expressions as literal strings 'abc' and 'def' instead of
** looking for columns of the same name.
**
** This only applies to the root node of pExpr, so the statement:
**
** ATTACH DATABASE abc||def AS 'db2'
**
** will fail because neither abc or def can be resolved.
*/
static int resolveAttachExpr( NameContext pName, Expr pExpr )
{
int rc = SQLITE_OK;
if ( pExpr != null )
{
if ( pExpr.op != TK_ID )
{
rc = sqlite3ResolveExprNames( pName, ref pExpr );
if ( rc == SQLITE_OK && sqlite3ExprIsConstant( pExpr ) == 0 )
{
sqlite3ErrorMsg( pName.pParse, "invalid name: \"%s\"", pExpr.u.zToken );
return SQLITE_ERROR;
}
}
else
{
pExpr.op = TK_STRING;
}
}
return rc;
}
/*
** An SQL user-function registered to do the work of an ATTACH statement. The
** three arguments to the function come directly from an attach statement:
**
** ATTACH DATABASE x AS y KEY z
**
** SELECT sqlite_attach(x, y, z)
**
** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
** third argument.
*/
static void attachFunc(
sqlite3_context context,
int NotUsed,
sqlite3_value[] argv
)
{
int i;
int rc = 0;
sqlite3 db = sqlite3_context_db_handle( context );
string zName;
string zFile;
string zPath = "";
string zErr = "";
int flags;
Db aNew = null;
string zErrDyn = "";
sqlite3_vfs pVfs = null;
UNUSED_PARAMETER( NotUsed );
zFile = argv[0].z != null && ( argv[0].z.Length > 0 ) && argv[0].flags != MEM_Null ? sqlite3_value_text( argv[0] ) : "";
zName = argv[1].z != null && ( argv[1].z.Length > 0 ) && argv[1].flags != MEM_Null ? sqlite3_value_text( argv[1] ) : "";
//if( zFile==null ) zFile = "";
//if ( zName == null ) zName = "";
/* Check for the following errors:
**
** * Too many attached databases,
** * Transaction currently open
** * Specified database name already being used.
*/
if ( db.nDb >= db.aLimit[SQLITE_LIMIT_ATTACHED] + 2 )
{
zErrDyn = sqlite3MPrintf( db, "too many attached databases - max %d",
db.aLimit[SQLITE_LIMIT_ATTACHED]
);
goto attach_error;
}
if ( 0 == db.autoCommit )
{
zErrDyn = sqlite3MPrintf( db, "cannot ATTACH database within transaction" );
goto attach_error;
}
for ( i = 0; i < db.nDb; i++ )
{
string z = db.aDb[i].zName;
Debug.Assert( z != null && zName != null );
if ( z.Equals( zName, StringComparison.InvariantCultureIgnoreCase ) )
{
zErrDyn = sqlite3MPrintf( db, "database %s is already in use", zName );
goto attach_error;
}
}
/* Allocate the new entry in the db.aDb[] array and initialise the schema
** hash tables.
*/
/* Allocate the new entry in the db.aDb[] array and initialise the schema
** hash tables.
*/
//if( db.aDb==db.aDbStatic ){
// aNew = sqlite3DbMallocRaw(db, sizeof(db.aDb[0])*3 );
// if( aNew==0 ) return;
// memcpy(aNew, db.aDb, sizeof(db.aDb[0])*2);
//}else {
if ( db.aDb.Length <= db.nDb )
Array.Resize( ref db.aDb, db.nDb + 1 );//aNew = sqlite3DbRealloc(db, db.aDb, sizeof(db.aDb[0])*(db.nDb+1) );
if ( db.aDb == null )
return; // if( aNew==0 ) return;
//}
db.aDb[db.nDb] = new Db();//db.aDb = aNew;
aNew = db.aDb[db.nDb];//memset(aNew, 0, sizeof(*aNew));
// memset(aNew, 0, sizeof(*aNew));
/* Open the database file. If the btree is successfully opened, use
** it to obtain the database schema. At this point the schema may
** or may not be initialised.
*/
flags = (int)db.openFlags;
rc = sqlite3ParseUri( db.pVfs.zName, zFile, ref flags, ref pVfs, ref zPath, ref zErr );
if ( rc != SQLITE_OK )
{
//if ( rc == SQLITE_NOMEM )
//db.mallocFailed = 1;
sqlite3_result_error( context, zErr, -1 );
//sqlite3_free( zErr );
return;
}
Debug.Assert( pVfs != null);
flags |= SQLITE_OPEN_MAIN_DB;
rc = sqlite3BtreeOpen( pVfs, zPath, db, ref aNew.pBt, 0, (int)flags );
//sqlite3_free( zPath );
db.nDb++;
if ( rc == SQLITE_CONSTRAINT )
{
rc = SQLITE_ERROR;
zErrDyn = sqlite3MPrintf( db, "database is already attached" );
}
else if ( rc == SQLITE_OK )
{
Pager pPager;
aNew.pSchema = sqlite3SchemaGet( db, aNew.pBt );
//if ( aNew.pSchema == null )
//{
// rc = SQLITE_NOMEM;
//}
//else
if ( aNew.pSchema.file_format != 0 && aNew.pSchema.enc != ENC( db ) )
{
zErrDyn = sqlite3MPrintf( db,
"attached databases must use the same text encoding as main database" );
rc = SQLITE_ERROR;
}
pPager = sqlite3BtreePager( aNew.pBt );
sqlite3PagerLockingMode( pPager, db.dfltLockMode );
sqlite3BtreeSecureDelete( aNew.pBt,
sqlite3BtreeSecureDelete( db.aDb[0].pBt, -1 ) );
}
aNew.safety_level = 3;
aNew.zName = zName;//sqlite3DbStrDup(db, zName);
//if( rc==SQLITE_OK && aNew.zName==0 ){
// rc = SQLITE_NOMEM;
//}
#if SQLITE_HAS_CODEC
if ( rc == SQLITE_OK )
{
//extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
//extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
int nKey;
string zKey;
int t = sqlite3_value_type( argv[2] );
switch ( t )
{
case SQLITE_INTEGER:
case SQLITE_FLOAT:
zErrDyn = "Invalid key value"; //sqlite3DbStrDup( db, "Invalid key value" );
rc = SQLITE_ERROR;
break;
case SQLITE_TEXT:
case SQLITE_BLOB:
nKey = sqlite3_value_bytes( argv[2] );
zKey = sqlite3_value_blob( argv[2] ).ToString(); // (char *)sqlite3_value_blob(argv[2]);
rc = sqlite3CodecAttach( db, db.nDb - 1, zKey, nKey );
break;
case SQLITE_NULL:
/* No key specified. Use the key from the main database */
sqlite3CodecGetKey( db, 0, out zKey, out nKey ); //sqlite3CodecGetKey(db, 0, (void**)&zKey, nKey);
if ( nKey > 0 || sqlite3BtreeGetReserve( db.aDb[0].pBt ) > 0 )
{
rc = sqlite3CodecAttach( db, db.nDb - 1, zKey, nKey );
}
break;
}
}
#endif
/* If the file was opened successfully, read the schema for the new database.
** If this fails, or if opening the file failed, then close the file and
** remove the entry from the db.aDb[] array. i.e. put everything back the way
** we found it.
*/
if ( rc == SQLITE_OK )
{
sqlite3BtreeEnterAll( db );
rc = sqlite3Init( db, ref zErrDyn );
sqlite3BtreeLeaveAll( db );
}
if ( rc != 0 )
{
int iDb = db.nDb - 1;
Debug.Assert( iDb >= 2 );
if ( db.aDb[iDb].pBt != null )
{
sqlite3BtreeClose( ref db.aDb[iDb].pBt );
db.aDb[iDb].pBt = null;
db.aDb[iDb].pSchema = null;
}
sqlite3ResetInternalSchema( db, -1 );
db.nDb = iDb;
if ( rc == SQLITE_NOMEM || rc == SQLITE_IOERR_NOMEM )
{
//// db.mallocFailed = 1;
sqlite3DbFree( db, ref zErrDyn );
zErrDyn = sqlite3MPrintf( db, "out of memory" );
}
else if ( zErrDyn == "" )
{
zErrDyn = sqlite3MPrintf( db, "unable to open database: %s", zFile );
}
goto attach_error;
}
return;
attach_error:
/* Return an error if we get here */
if ( zErrDyn != "" )
{
sqlite3_result_error( context, zErrDyn, -1 );
sqlite3DbFree( db, ref zErrDyn );
}
if ( rc != 0 )
sqlite3_result_error_code( context, rc );
}
/*
** An SQL user-function registered to do the work of an DETACH statement. The
** three arguments to the function come directly from a detach statement:
**
** DETACH DATABASE x
**
** SELECT sqlite_detach(x)
*/
static void detachFunc(
sqlite3_context context,
int NotUsed,
sqlite3_value[] argv
)
{
string zName = argv[0].z != null && ( argv[0].z.Length > 0 ) ? sqlite3_value_text( argv[0] ) : "";//(sqlite3_value_text(argv[0]);
sqlite3 db = sqlite3_context_db_handle( context );
int i;
Db pDb = null;
StringBuilder zErr = new StringBuilder( 200 );
UNUSED_PARAMETER( NotUsed );
if ( zName == null )
zName = "";
for ( i = 0; i < db.nDb; i++ )
{
pDb = db.aDb[i];
if ( pDb.pBt == null )
continue;
if ( pDb.zName.Equals( zName, StringComparison.InvariantCultureIgnoreCase ) )
break;
}
if ( i >= db.nDb )
{
sqlite3_snprintf( 200, zErr, "no such database: %s", zName );
goto detach_error;
}
if ( i < 2 )
{
sqlite3_snprintf( 200, zErr, "cannot detach database %s", zName );
goto detach_error;
}
if ( 0 == db.autoCommit )
{
sqlite3_snprintf( 200, zErr,
"cannot DETACH database within transaction" );
goto detach_error;
}
if ( sqlite3BtreeIsInReadTrans( pDb.pBt ) || sqlite3BtreeIsInBackup( pDb.pBt ) )
{
sqlite3_snprintf( 200, zErr, "database %s is locked", zName );
goto detach_error;
}
sqlite3BtreeClose( ref pDb.pBt );
pDb.pBt = null;
pDb.pSchema = null;
sqlite3ResetInternalSchema( db, -1 );
return;
detach_error:
sqlite3_result_error( context, zErr.ToString(), -1 );
}
/*
** This procedure generates VDBE code for a single invocation of either the
** sqlite_detach() or sqlite_attach() SQL user functions.
*/
static void codeAttach(
Parse pParse, /* The parser context */
int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */
FuncDef pFunc, /* FuncDef wrapper for detachFunc() or attachFunc() */
Expr pAuthArg, /* Expression to pass to authorization callback */
Expr pFilename, /* Name of database file */
Expr pDbname, /* Name of the database to use internally */
Expr pKey /* Database key for encryption extension */
)
{
NameContext sName;
Vdbe v;
sqlite3 db = pParse.db;
int regArgs;
sName = new NameContext();// memset( &sName, 0, sizeof(NameContext));
sName.pParse = pParse;
if (
SQLITE_OK != resolveAttachExpr( sName, pFilename ) ||
SQLITE_OK != resolveAttachExpr( sName, pDbname ) ||
SQLITE_OK != resolveAttachExpr( sName, pKey )
)
{
pParse.nErr++;
goto attach_end;
}
#if !SQLITE_OMIT_AUTHORIZATION
if( pAuthArg ){
char *zAuthArg;
if( pAuthArg->op==TK_STRING ){
zAuthArg = pAuthArg->u.zToken;
}else{
zAuthArg = 0;
}
int rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
if(rc!=SQLITE_OK ){
goto attach_end;
}
}
#endif //* SQLITE_OMIT_AUTHORIZATION */
v = sqlite3GetVdbe( pParse );
regArgs = sqlite3GetTempRange( pParse, 4 );
sqlite3ExprCode( pParse, pFilename, regArgs );
sqlite3ExprCode( pParse, pDbname, regArgs + 1 );
sqlite3ExprCode( pParse, pKey, regArgs + 2 );
Debug.Assert( v != null /*|| db.mallocFailed != 0 */ );
if ( v != null )
{
sqlite3VdbeAddOp3( v, OP_Function, 0, regArgs + 3 - pFunc.nArg, regArgs + 3 );
Debug.Assert( pFunc.nArg == -1 || ( pFunc.nArg & 0xff ) == pFunc.nArg );
sqlite3VdbeChangeP5( v, (u8)( pFunc.nArg ) );
sqlite3VdbeChangeP4( v, -1, pFunc, P4_FUNCDEF );
/* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
** statement only). For DETACH, set it to false (expire all existing
** statements).
*/
sqlite3VdbeAddOp1( v, OP_Expire, ( type == SQLITE_ATTACH ) ? 1 : 0 );
}
attach_end:
sqlite3ExprDelete( db, ref pFilename );
sqlite3ExprDelete( db, ref pDbname );
sqlite3ExprDelete( db, ref pKey );
}
/*
** Called by the parser to compile a DETACH statement.
**
** DETACH pDbname
*/
static FuncDef detach_func = new FuncDef(
1, /* nArg */
SQLITE_UTF8, /* iPrefEnc */
0, /* flags */
null, /* pUserData */
null, /* pNext */
detachFunc, /* xFunc */
null, /* xStep */
null, /* xFinalize */
"sqlite_detach", /* zName */
null, /* pHash */
null /* pDestructor */
);
static void sqlite3Detach( Parse pParse, Expr pDbname )
{
codeAttach( pParse, SQLITE_DETACH, detach_func, pDbname, null, null, pDbname );
}
/*
** Called by the parser to compile an ATTACH statement.
**
** ATTACH p AS pDbname KEY pKey
*/
static FuncDef attach_func = new FuncDef(
3, /* nArg */
SQLITE_UTF8, /* iPrefEnc */
0, /* flags */
null, /* pUserData */
null, /* pNext */
attachFunc, /* xFunc */
null, /* xStep */
null, /* xFinalize */
"sqlite_attach", /* zName */
null, /* pHash */
null /* pDestructor */
);
static void sqlite3Attach( Parse pParse, Expr p, Expr pDbname, Expr pKey )
{
codeAttach( pParse, SQLITE_ATTACH, attach_func, p, p, pDbname, pKey );
}
#endif // * SQLITE_OMIT_ATTACH */
/*
** Initialize a DbFixer structure. This routine must be called prior
** to passing the structure to one of the sqliteFixAAAA() routines below.
**
** The return value indicates whether or not fixation is required. TRUE
** means we do need to fix the database references, FALSE means we do not.
*/
static int sqlite3FixInit(
DbFixer pFix, /* The fixer to be initialized */
Parse pParse, /* Error messages will be written here */
int iDb, /* This is the database that must be used */
string zType, /* "view", "trigger", or "index" */
Token pName /* Name of the view, trigger, or index */
)
{
sqlite3 db;
if ( NEVER( iDb < 0 ) || iDb == 1 )
return 0;
db = pParse.db;
Debug.Assert( db.nDb > iDb );
pFix.pParse = pParse;
pFix.zDb = db.aDb[iDb].zName;
pFix.zType = zType;
pFix.pName = pName;
return 1;
}
/*
** The following set of routines walk through the parse tree and assign
** a specific database to all table references where the database name
** was left unspecified in the original SQL statement. The pFix structure
** must have been initialized by a prior call to sqlite3FixInit().
**
** These routines are used to make sure that an index, trigger, or
** view in one database does not refer to objects in a different database.
** (Exception: indices, triggers, and views in the TEMP database are
** allowed to refer to anything.) If a reference is explicitly made
** to an object in a different database, an error message is added to
** pParse.zErrMsg and these routines return non-zero. If everything
** checks out, these routines return 0.
*/
static int sqlite3FixSrcList(
DbFixer pFix, /* Context of the fixation */
SrcList pList /* The Source list to check and modify */
)
{
int i;
string zDb;
SrcList_item pItem;
if ( NEVER( pList == null ) )
return 0;
zDb = pFix.zDb;
for ( i = 0; i < pList.nSrc; i++ )
{//, pItem++){
pItem = pList.a[i];
if ( pItem.zDatabase == null )
{
pItem.zDatabase = zDb;// sqlite3DbStrDup( pFix.pParse.db, zDb );
}
else if ( !pItem.zDatabase.Equals( zDb ,StringComparison.InvariantCultureIgnoreCase ) )
{
sqlite3ErrorMsg( pFix.pParse,
"%s %T cannot reference objects in database %s",
pFix.zType, pFix.pName, pItem.zDatabase );
return 1;
}
#if !SQLITE_OMIT_VIEW || !SQLITE_OMIT_TRIGGER
if ( sqlite3FixSelect( pFix, pItem.pSelect ) != 0 )
return 1;
if ( sqlite3FixExpr( pFix, pItem.pOn ) != 0 )
return 1;
#endif
}
return 0;
}
#if !SQLITE_OMIT_VIEW || !SQLITE_OMIT_TRIGGER
static int sqlite3FixSelect(
DbFixer pFix, /* Context of the fixation */
Select pSelect /* The SELECT statement to be fixed to one database */
)
{
while ( pSelect != null )
{
if ( sqlite3FixExprList( pFix, pSelect.pEList ) != 0 )
{
return 1;
}
if ( sqlite3FixSrcList( pFix, pSelect.pSrc ) != 0 )
{
return 1;
}
if ( sqlite3FixExpr( pFix, pSelect.pWhere ) != 0 )
{
return 1;
}
if ( sqlite3FixExpr( pFix, pSelect.pHaving ) != 0 )
{
return 1;
}
pSelect = pSelect.pPrior;
}
return 0;
}
static int sqlite3FixExpr(
DbFixer pFix, /* Context of the fixation */
Expr pExpr /* The expression to be fixed to one database */
)
{
while ( pExpr != null )
{
if ( ExprHasAnyProperty( pExpr, EP_TokenOnly ) )
break;
if ( ExprHasProperty( pExpr, EP_xIsSelect ) )
{
if ( sqlite3FixSelect( pFix, pExpr.x.pSelect ) != 0 )
return 1;
}
else
{
if ( sqlite3FixExprList( pFix, pExpr.x.pList ) != 0 )
return 1;
}
if ( sqlite3FixExpr( pFix, pExpr.pRight ) != 0 )
{
return 1;
}
pExpr = pExpr.pLeft;
}
return 0;
}
static int sqlite3FixExprList(
DbFixer pFix, /* Context of the fixation */
ExprList pList /* The expression to be fixed to one database */
)
{
int i;
ExprList_item pItem;
if ( pList == null )
return 0;
for ( i = 0; i < pList.nExpr; i++ )//, pItem++ )
{
pItem = pList.a[i];
if ( sqlite3FixExpr( pFix, pItem.pExpr ) != 0 )
{
return 1;
}
}
return 0;
}
#endif
#if !SQLITE_OMIT_TRIGGER
static int sqlite3FixTriggerStep(
DbFixer pFix, /* Context of the fixation */
TriggerStep pStep /* The trigger step be fixed to one database */
)
{
while ( pStep != null )
{
if ( sqlite3FixSelect( pFix, pStep.pSelect ) != 0 )
{
return 1;
}
if ( sqlite3FixExpr( pFix, pStep.pWhere ) != 0 )
{
return 1;
}
if ( sqlite3FixExprList( pFix, pStep.pExprList ) != 0 )
{
return 1;
}
pStep = pStep.pNext;
}
return 0;
}
#endif
}
}
| hsu1994/Terminator | Client/Assets/Scripts/Air2000/Utility/Sqlite/Sqlite3/source/src/attach_c.cs | C# | apache-2.0 | 19,135 |
/*
* ******************************************************************************
* Copyright 2014-2017 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* ****************************************************************************
*/
// This code is auto-generated, do not modify
package com.spectralogic.ds3client.commands.parsers;
import com.spectralogic.ds3client.commands.parsers.interfaces.AbstractResponseParser;
import com.spectralogic.ds3client.commands.parsers.utils.ResponseParserUtils;
import com.spectralogic.ds3client.commands.spectrads3.ModifyUserSpectraS3Response;
import com.spectralogic.ds3client.models.SpectraUser;
import com.spectralogic.ds3client.networking.WebResponse;
import com.spectralogic.ds3client.serializer.XmlOutput;
import java.io.IOException;
import java.io.InputStream;
public class ModifyUserSpectraS3ResponseParser extends AbstractResponseParser<ModifyUserSpectraS3Response> {
private final int[] expectedStatusCodes = new int[]{200};
@Override
public ModifyUserSpectraS3Response parseXmlResponse(final WebResponse response) throws IOException {
final int statusCode = response.getStatusCode();
if (ResponseParserUtils.validateStatusCode(statusCode, expectedStatusCodes)) {
switch (statusCode) {
case 200:
try (final InputStream inputStream = response.getResponseStream()) {
final SpectraUser result = XmlOutput.fromXml(inputStream, SpectraUser.class);
return new ModifyUserSpectraS3Response(result, this.getChecksum(), this.getChecksumType());
}
default:
assert false: "validateStatusCode should have made it impossible to reach this line";
}
}
throw ResponseParserUtils.createFailedRequest(response, expectedStatusCodes);
}
} | DenverM80/ds3_java_sdk | ds3-sdk/src/main/java/com/spectralogic/ds3client/commands/parsers/ModifyUserSpectraS3ResponseParser.java | Java | apache-2.0 | 2,377 |
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2016 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides control sap.m.MessagePopover.
sap.ui.define(["jquery.sap.global", "./ResponsivePopover", "./Button", "./Toolbar", "./ToolbarSpacer", "./Bar", "./List",
"./StandardListItem", "./library", "sap/ui/core/Control", "./PlacementType", "sap/ui/core/IconPool",
"sap/ui/core/HTML", "./Text", "sap/ui/core/Icon", "./SegmentedButton", "./Page", "./NavContainer",
"./semantic/SemanticPage", "./Popover", "./MessagePopoverItem", "jquery.sap.dom"],
function (jQuery, ResponsivePopover, Button, Toolbar, ToolbarSpacer, Bar, List,
StandardListItem, library, Control, PlacementType, IconPool,
HTML, Text, Icon, SegmentedButton, Page, NavContainer, SemanticPage, Popover, MessagePopoverItem) {
"use strict";
/**
* Constructor for a new MessagePopover
*
* @param {string} [sId] ID for the new control, generated automatically if no id is given
* @param {object} [mSettings] Initial settings for the new control
*
* @class
* A MessagePopover is a Popover containing a summarized list with messages.
* @extends sap.ui.core.Control
*
* @author SAP SE
* @version 1.36.11
*
* @constructor
* @public
* @since 1.28
* @alias sap.m.MessagePopover
* @ui5-metamodel This control also will be described in the legacy UI5 design-time metamodel
*/
var MessagePopover = Control.extend("sap.m.MessagePopover", /** @lends sap.m.MessagePopover.prototype */ {
metadata: {
library: "sap.m",
properties: {
/**
* Callback function for resolving a promise after description has been asynchronously loaded inside this function
* @callback sap.m.MessagePopover~asyncDescriptionHandler
* @param {object} config A single parameter object
* @param {MessagePopoverItem} config.item Reference to respective MessagePopoverItem instance
* @param {object} config.promise Object grouping a promise's reject and resolve methods
* @param {function} config.promise.resolve Method to resolve promise
* @param {function} config.promise.reject Method to reject promise
*/
asyncDescriptionHandler: {type: "any", group: "Behavior", defaultValue: null},
/**
* Callback function for resolving a promise after a link has been asynchronously validated inside this function
* @callback sap.m.MessagePopover~asyncURLHandler
* @param {object} config A single parameter object
* @param {string} config.url URL to validate
* @param {string|Int} config.id ID of the validation job
* @param {object} config.promise Object grouping a promise's reject and resolve methods
* @param {function} config.promise.resolve Method to resolve promise
* @param {function} config.promise.reject Method to reject promise
*/
asyncURLHandler: {type: "any", group: "Behavior", defaultValue: null},
/**
* Determines the position, where the control will appear on the screen. Possible values are: sap.m.VerticalPlacementType.Top, sap.m.VerticalPlacementType.Bottom and sap.m.VerticalPlacementType.Vertical.
* The default value is sap.m.VerticalPlacementType.Vertical. Setting this property while the control is open, will not cause any re-rendering and changing of the position. Changes will only be applied with the next interaction.
*/
placement: {type: "sap.m.VerticalPlacementType", group: "Behavior", defaultValue: "Vertical"},
/**
* Sets the initial state of the control - expanded or collapsed. By default the control opens as expanded
*/
initiallyExpanded: {type: "boolean", group: "Behavior", defaultValue: true}
},
defaultAggregation: "items",
aggregations: {
/**
* A list with message items
*/
items: {type: "sap.m.MessagePopoverItem", multiple: true, singularName: "item"}
},
events: {
/**
* This event will be fired after the popover is opened
*/
afterOpen: {
parameters: {
/**
* This refers to the control which opens the popover
*/
openBy: {type: "sap.ui.core.Control"}
}
},
/**
* This event will be fired after the popover is closed
*/
afterClose: {
parameters: {
/**
* Refers to the control which opens the popover
*/
openBy: {type: "sap.ui.core.Control"}
}
},
/**
* This event will be fired before the popover is opened
*/
beforeOpen: {
parameters: {
/**
* Refers to the control which opens the popover
*/
openBy: {type: "sap.ui.core.Control"}
}
},
/**
* This event will be fired before the popover is closed
*/
beforeClose: {
parameters: {
/**
* Refers to the control which opens the popover
* See sap.ui.core.MessageType enum values for types
*/
openBy: {type: "sap.ui.core.Control"}
}
},
/**
* This event will be fired when description is shown
*/
itemSelect: {
parameters: {
/**
* Refers to the message popover item that is being presented
*/
item: {type: "sap.m.MessagePopoverItem"},
/**
* Refers to the type of messages being shown
* See sap.ui.core.MessageType values for types
*/
messageTypeFilter: {type: "sap.ui.core.MessageType"}
}
},
/**
* This event will be fired when one of the lists is shown when (not) filtered by type
*/
listSelect: {
parameters: {
/**
* This parameter refers to the type of messages being shown.
*/
messageTypeFilter: {type: "sap.ui.core.MessageType"}
}
},
/**
* This event will be fired when the long text description data from a remote URL is loaded
*/
longtextLoaded: {},
/**
* This event will be fired when a validation of a URL from long text description is ready
*/
urlValidated: {}
}
}
});
var CSS_CLASS = "sapMMsgPopover",
ICONS = {
back: IconPool.getIconURI("nav-back"),
close: IconPool.getIconURI("decline"),
information: IconPool.getIconURI("message-information"),
warning: IconPool.getIconURI("message-warning"),
error: IconPool.getIconURI("message-error"),
success: IconPool.getIconURI("message-success")
},
LIST_TYPES = ["all", "error", "warning", "success", "information"],
// Property names array
ASYNC_HANDLER_NAMES = ["asyncDescriptionHandler", "asyncURLHandler"],
// Private class variable used for static method below that sets default async handlers
DEFAULT_ASYNC_HANDLERS = {
asyncDescriptionHandler: function (config) {
var sLongTextUrl = config.item.getLongtextUrl();
if (sLongTextUrl) {
jQuery.ajax({
type: "GET",
url: sLongTextUrl,
success: function (data) {
config.item.setDescription(data);
config.promise.resolve();
},
error: function() {
var sError = "A request has failed for long text data. URL: " + sLongTextUrl;
jQuery.sap.log.error(sError);
config.promise.reject(sError);
}
});
}
}
};
/**
* Setter for default description and URL validation callbacks across all instances of MessagePopover
* @static
* @protected
* @param {object} mDefaultHandlers An object setting default callbacks
* @param {function} mDefaultHandlers.asyncDescriptionHandler
* @param {function} mDefaultHandlers.asyncURLHandler
*/
MessagePopover.setDefaultHandlers = function (mDefaultHandlers) {
ASYNC_HANDLER_NAMES.forEach(function (sFuncName) {
if (mDefaultHandlers.hasOwnProperty(sFuncName)) {
DEFAULT_ASYNC_HANDLERS[sFuncName] = mDefaultHandlers[sFuncName];
}
});
};
/**
* Initializes the control
*
* @override
* @private
*/
MessagePopover.prototype.init = function () {
var that = this;
var oPopupControl;
this._oResourceBundle = sap.ui.getCore().getLibraryResourceBundle("sap.m");
this._oPopover = new ResponsivePopover(this.getId() + "-messagePopover", {
showHeader: false,
contentWidth: "440px",
placement: this.getPlacement(),
showCloseButton: false,
modal: false,
afterOpen: function (oEvent) {
that.fireAfterOpen({openBy: oEvent.getParameter("openBy")});
},
afterClose: function (oEvent) {
that._navContainer.backToTop();
that.fireAfterClose({openBy: oEvent.getParameter("openBy")});
},
beforeOpen: function (oEvent) {
that.fireBeforeOpen({openBy: oEvent.getParameter("openBy")});
},
beforeClose: function (oEvent) {
that.fireBeforeClose({openBy: oEvent.getParameter("openBy")});
}
}).addStyleClass(CSS_CLASS);
this._createNavigationPages();
this._createLists();
oPopupControl = this._oPopover.getAggregation("_popup");
oPopupControl.oPopup.setAutoClose(false);
oPopupControl.addEventDelegate({
onBeforeRendering: this.onBeforeRenderingPopover,
onkeypress: this._onkeypress
}, this);
if (sap.ui.Device.system.phone) {
this._oPopover.setBeginButton(new Button({
text: this._oResourceBundle.getText("MESSAGEPOPOVER_CLOSE"),
press: this.close.bind(this)
}));
}
// Check for default async handlers and set them appropriately
ASYNC_HANDLER_NAMES.forEach(function (sFuncName) {
if (DEFAULT_ASYNC_HANDLERS.hasOwnProperty(sFuncName)) {
that.setProperty(sFuncName, DEFAULT_ASYNC_HANDLERS[sFuncName]);
}
});
};
/**
* Called when the control is destroyed
*
* @private
*/
MessagePopover.prototype.exit = function () {
this._oResourceBundle = null;
this._oListHeader = null;
this._oDetailsHeader = null;
this._oSegmentedButton = null;
this._oBackButton = null;
this._navContainer = null;
this._listPage = null;
this._detailsPage = null;
this._sCurrentList = null;
if (this._oLists) {
this._destroyLists();
}
// Destroys ResponsivePopover control that is used by MessagePopover
// This will walk through all aggregations in the Popover and destroy them (in our case this is NavContainer)
// Next this will walk through all aggregations in the NavContainer, etc.
if (this._oPopover) {
this._oPopover.destroy();
this._oPopover = null;
}
};
/**
* Required adaptations before rendering MessagePopover
*
* @private
*/
MessagePopover.prototype.onBeforeRenderingPopover = function () {
// Bind automatically to the MessageModel if no items are bound
if (!this.getBindingInfo("items")) {
this._makeAutomaticBinding();
}
// Update lists only if 'items' aggregation is changed
if (this._bItemsChanged) {
this._clearLists();
this._fillLists(this.getItems());
this._clearSegmentedButton();
this._fillSegmentedButton();
this._bItemsChanged = false;
}
this._setInitialFocus();
};
/**
* Makes automatic binding to the Message Model with default template
*
* @private
*/
MessagePopover.prototype._makeAutomaticBinding = function () {
this.setModel(sap.ui.getCore().getMessageManager().getMessageModel(), "message");
this.bindAggregation("items",
{
path: "message>/",
template: new MessagePopoverItem({
type: "{message>type}",
title: "{message>title}",
description: "{message>description}",
longtextUrl: "{message>longtextUrl}"
})
}
);
};
/**
* Handles keyup event
*
* @param {jQuery.Event} oEvent - keyup event object
* @private
*/
MessagePopover.prototype._onkeypress = function (oEvent) {
if (oEvent.shiftKey && oEvent.keyCode == jQuery.sap.KeyCodes.ENTER) {
this._fnHandleBackPress();
}
};
/**
* Returns header of the MessagePopover's ListPage
*
* @returns {sap.m.Toolbar} ListPage header
* @private
*/
MessagePopover.prototype._getListHeader = function () {
return this._oListHeader || this._createListHeader();
};
/**
* Returns header of the MessagePopover's ListPage
*
* @returns {sap.m.Toolbar} DetailsPage header
* @private
*/
MessagePopover.prototype._getDetailsHeader = function () {
return this._oDetailsHeader || this._createDetailsHeader();
};
/**
* Creates header of MessagePopover's ListPage
*
* @returns {sap.m.Toolbar} ListPage header
* @private
*/
MessagePopover.prototype._createListHeader = function () {
var sCloseBtnDescr = this._oResourceBundle.getText("MESSAGEPOPOVER_CLOSE");
var sCloseBtnDescrId = this.getId() + "-CloseBtnDescr";
var oCloseBtnARIAHiddenDescr = new HTML(sCloseBtnDescrId, {
content: "<span id=\"" + sCloseBtnDescrId + "\" style=\"display: none;\">" + sCloseBtnDescr + "</span>"
});
var sHeadingDescr = this._oResourceBundle.getText("MESSAGEPOPOVER_ARIA_HEADING");
var sHeadingDescrId = this.getId() + "-HeadingDescr";
var oHeadingARIAHiddenDescr = new HTML(sHeadingDescrId, {
content: "<span id=\"" + sHeadingDescrId + "\" style=\"display: none;\" role=\"heading\">" + sHeadingDescr + "</span>"
});
this._oPopover.addAssociation("ariaDescribedBy", sHeadingDescrId, true);
var oCloseBtn = new Button({
icon: ICONS["close"],
visible: !sap.ui.Device.system.phone,
ariaLabelledBy: oCloseBtnARIAHiddenDescr,
tooltip: sCloseBtnDescr,
press: this.close.bind(this)
}).addStyleClass(CSS_CLASS + "CloseBtn");
this._oSegmentedButton = new SegmentedButton(this.getId() + "-segmented", {}).addStyleClass("sapMSegmentedButtonNoAutoWidth");
this._oListHeader = new Toolbar({
content: [this._oSegmentedButton, new ToolbarSpacer(), oCloseBtn, oCloseBtnARIAHiddenDescr, oHeadingARIAHiddenDescr]
});
return this._oListHeader;
};
/**
* Creates header of MessagePopover's ListPage
*
* @returns {sap.m.Toolbar} DetailsPage header
* @private
*/
MessagePopover.prototype._createDetailsHeader = function () {
var sCloseBtnDescr = this._oResourceBundle.getText("MESSAGEPOPOVER_CLOSE");
var sCloseBtnDescrId = this.getId() + "-CloseBtnDetDescr";
var oCloseBtnARIAHiddenDescr = new HTML(sCloseBtnDescrId, {
content: "<span id=\"" + sCloseBtnDescrId + "\" style=\"display: none;\">" + sCloseBtnDescr + "</span>"
});
var sBackBtnDescr = this._oResourceBundle.getText("MESSAGEPOPOVER_ARIA_BACK_BUTTON");
var sBackBtnDescrId = this.getId() + "-BackBtnDetDescr";
var oBackBtnARIAHiddenDescr = new HTML(sBackBtnDescrId, {
content: "<span id=\"" + sBackBtnDescrId + "\" style=\"display: none;\">" + sBackBtnDescr + "</span>"
});
var oCloseBtn = new Button({
icon: ICONS["close"],
visible: !sap.ui.Device.system.phone,
ariaLabelledBy: oCloseBtnARIAHiddenDescr,
tooltip: sCloseBtnDescr,
press: this.close.bind(this)
}).addStyleClass(CSS_CLASS + "CloseBtn");
this._oBackButton = new Button({
icon: ICONS["back"],
press: this._fnHandleBackPress.bind(this),
ariaLabelledBy: oBackBtnARIAHiddenDescr,
tooltip: sBackBtnDescr
});
this._oDetailsHeader = new Toolbar({
content: [this._oBackButton, new ToolbarSpacer(), oCloseBtn, oCloseBtnARIAHiddenDescr, oBackBtnARIAHiddenDescr]
});
return this._oDetailsHeader;
};
/**
* Creates navigation pages
*
* @returns {sap.m.MessagePopover} Reference to the 'this' for chaining purposes
* @private
*/
MessagePopover.prototype._createNavigationPages = function () {
// Create two main pages
this._listPage = new Page(this.getId() + "listPage", {
customHeader: this._getListHeader()
});
this._detailsPage = new Page(this.getId() + "-detailsPage", {
customHeader: this._getDetailsHeader()
});
// TODO: check if this is the best location for this
// Disable clicks on disabled and/or pending links
this._detailsPage.addEventDelegate({
onclick: function(oEvent) {
var target = oEvent.target;
if (target.nodeName.toUpperCase() === 'A' &&
(target.className.indexOf('sapMMsgPopoverItemDisabledLink') !== -1 ||
target.className.indexOf('sapMMsgPopoverItemPendingLink') !== -1)) {
oEvent.preventDefault();
}
}
});
// Initialize nav container with two main pages
this._navContainer = new NavContainer(this.getId() + "-navContainer", {
initialPage: this.getId() + "listPage",
pages: [this._listPage, this._detailsPage],
navigate: this._navigate.bind(this),
afterNavigate: this._afterNavigate.bind(this)
});
// Assign nav container to content of _oPopover
this._oPopover.addContent(this._navContainer);
return this;
};
/**
* Creates Lists of the MessagePopover
*
* @returns {sap.m.MessagePopover} Reference to the 'this' for chaining purposes
* @private
*/
MessagePopover.prototype._createLists = function () {
this._oLists = {};
LIST_TYPES.forEach(function (sListName) {
this._oLists[sListName] = new List({
itemPress: this._fnHandleItemPress.bind(this),
visible: false
});
// no re-rendering
this._listPage.addAggregation("content", this._oLists[sListName], true);
}, this);
return this;
};
/**
* Destroy items in the MessagePopover's Lists
*
* @returns {sap.m.MessagePopover} Reference to the 'this' for chaining purposes
* @private
*/
MessagePopover.prototype._clearLists = function () {
LIST_TYPES.forEach(function (sListName) {
if (this._oLists[sListName]) {
this._oLists[sListName].destroyAggregation("items", true);
}
}, this);
return this;
};
/**
* Destroys internal Lists of the MessagePopover
*
* @private
*/
MessagePopover.prototype._destroyLists = function () {
LIST_TYPES.forEach(function (sListName) {
this._oLists[sListName] = null;
}, this);
this._oLists = null;
};
/**
* Fill the list with items
*
* @param {array} aItems An array with items type of sap.ui.core.Item.
* @private
*/
MessagePopover.prototype._fillLists = function (aItems) {
aItems.forEach(function (oMessagePopoverItem) {
var oListItem = this._mapItemToListItem(oMessagePopoverItem),
oCloneListItem = this._mapItemToListItem(oMessagePopoverItem);
// add the mapped item to the List
this._oLists["all"].addAggregation("items", oListItem, true);
this._oLists[oMessagePopoverItem.getType().toLowerCase()].addAggregation("items", oCloneListItem, true);
}, this);
};
/**
* Map a MessagePopoverItem to StandardListItem
*
* @param {sap.m.MessagePopoverItem} oMessagePopoverItem Base information to generate the list items
* @returns {sap.m.StandardListItem | null} oListItem List item which will be displayed
* @private
*/
MessagePopover.prototype._mapItemToListItem = function (oMessagePopoverItem) {
if (!oMessagePopoverItem) {
return null;
}
var sType = oMessagePopoverItem.getType(),
oListItem = new StandardListItem({
title: oMessagePopoverItem.getTitle(),
icon: this._mapIcon(sType),
type: sap.m.ListType.Navigation
}).addStyleClass(CSS_CLASS + "Item").addStyleClass(CSS_CLASS + "Item" + sType);
oListItem._oMessagePopoverItem = oMessagePopoverItem;
return oListItem;
};
/**
* Map an MessageType to the Icon URL.
*
* @param {sap.ui.core.ValueState} sIcon Type of Error
* @returns {string | null} Icon string
* @private
*/
MessagePopover.prototype._mapIcon = function (sIcon) {
if (!sIcon) {
return null;
}
return ICONS[sIcon.toLowerCase()];
};
/**
* Destroy the buttons in the SegmentedButton
*
* @returns {sap.m.MessagePopover} Reference to the 'this' for chaining purposes
* @private
*/
MessagePopover.prototype._clearSegmentedButton = function () {
if (this._oSegmentedButton) {
this._oSegmentedButton.destroyAggregation("buttons", true);
}
return this;
};
/**
* Fill SegmentedButton with needed Buttons for filtering
*
* @returns {sap.m.MessagePopover} Reference to the 'this' for chaining purposes
* @private
*/
MessagePopover.prototype._fillSegmentedButton = function () {
var that = this;
var pressClosure = function (sListName) {
return function () {
that._fnFilterList(sListName);
};
};
LIST_TYPES.forEach(function (sListName) {
var oList = this._oLists[sListName],
iCount = oList.getItems().length,
oButton;
if (iCount > 0) {
oButton = new Button(this.getId() + "-" + sListName, {
text: sListName == "all" ? this._oResourceBundle.getText("MESSAGEPOPOVER_ALL") : iCount,
icon: ICONS[sListName],
press: pressClosure(sListName)
}).addStyleClass(CSS_CLASS + "Btn" + sListName.charAt(0).toUpperCase() + sListName.slice(1));
this._oSegmentedButton.addButton(oButton, true);
}
}, this);
return this;
};
/**
* Sets icon in details page
* @param {sap.m.MessagePopoverItem} oMessagePopoverItem
* @param {sap.m.StandardListItem} oListItem
* @private
*/
MessagePopover.prototype._setIcon = function (oMessagePopoverItem, oListItem) {
this._previousIconTypeClass = CSS_CLASS + "DescIcon" + oMessagePopoverItem.getType();
this._oMessageIcon = new Icon({
src: oListItem.getIcon()
})
.addStyleClass(CSS_CLASS + "DescIcon")
.addStyleClass(this._previousIconTypeClass);
this._detailsPage.addContent(this._oMessageIcon);
};
/**
* Sets title part of details page
* @param {sap.m.MessagePopoverItem} oMessagePopoverItem
* @private
*/
MessagePopover.prototype._setTitle = function (oMessagePopoverItem) {
this._oMessageTitleText = new Text(this.getId() + 'MessageTitleText', {
text: oMessagePopoverItem.getTitle()
}).addStyleClass('sapMMsgPopoverTitleText');
this._detailsPage.addAggregation("content", this._oMessageTitleText);
};
/**
* Sets description text part of details page
* When markup description is used it is sanitized within it's container's setter method (MessagePopoverItem)
* @param {sap.m.MessagePopoverItem} oMessagePopoverItem
* @private
*/
MessagePopover.prototype._setDescription = function (oMessagePopoverItem) {
if (oMessagePopoverItem.getMarkupDescription()) {
// description is sanitized in MessagePopoverItem.setDescription()
this._oMessageDescriptionText = new HTML(this.getId() + 'MarkupDescription', {
content: "<div class='markupDescription'>" + oMessagePopoverItem.getDescription() + "</div>"
});
} else {
this._oMessageDescriptionText = new Text(this.getId() + 'MessageDescriptionText', {
text: oMessagePopoverItem.getDescription()
}).addStyleClass('sapMMsgPopoverDescriptionText');
}
this._detailsPage.addContent(this._oMessageDescriptionText);
};
MessagePopover.prototype._iNextValidationTaskId = 0;
MessagePopover.prototype._validateURL = function (sUrl) {
if (jQuery.sap.validateUrl(sUrl)) {
return sUrl;
}
jQuery.sap.log.warning("You have entered invalid URL");
return '';
};
MessagePopover.prototype._queueValidation = function (href) {
var fnAsyncURLHandler = this.getAsyncURLHandler();
var iValidationTaskId = ++this._iNextValidationTaskId;
var oPromiseArgument = {};
var oPromise = new window.Promise(function(resolve, reject) {
oPromiseArgument.resolve = resolve;
oPromiseArgument.reject = reject;
var config = {
url: href,
id: iValidationTaskId,
promise: oPromiseArgument
};
fnAsyncURLHandler(config);
});
oPromise.id = iValidationTaskId;
return oPromise;
};
MessagePopover.prototype._getTagPolicy = function () {
var that = this,
i;
/*global html*/
var defaultTagPolicy = html.makeTagPolicy(this._validateURL());
return function customTagPolicy(tagName, attrs) {
var href,
validateLink = false;
if (tagName.toUpperCase() === "A") {
for (i = 0; i < attrs.length;) {
// if there is href the link should be validated, href's value is on position(i+1)
if (attrs[i] === "href") {
validateLink = true;
href = attrs[i + 1];
attrs.splice(0, 2);
continue;
}
i += 2;
}
}
// let the default sanitizer do its work
// it won't see the href attribute
attrs = defaultTagPolicy(tagName, attrs);
// if we detected a link before, we modify the <A> tag
// and keep the link in a dataset attribute
if (validateLink && typeof that.getAsyncURLHandler() === "function") {
attrs = attrs || [];
var done = false;
// first check if there is a class attribute and enrich it with 'sapMMsgPopoverItemDisabledLink'
for (i = 0; i < attrs.length; i += 2) {
if (attrs[i] === "class") {
attrs[i + 1] += "sapMMsgPopoverItemDisabledLink sapMMsgPopoverItemPendingLink";
done = true;
break;
}
}
// check for existing id
var indexOfId = attrs.indexOf("id");
if (indexOfId > -1) {
// we start backwards
attrs.splice(indexOfId + 1, 1);
attrs.splice(indexOfId, 1);
}
// if no class attribute was found, add one
if (!done) {
attrs.unshift("sapMMsgPopoverItemDisabledLink sapMMsgPopoverItemPendingLink");
attrs.unshift("class");
}
var oValidation = that._queueValidation(href);
// add other attributes
attrs.push("href");
// the link is deactivated via class names later read by event delegate on the description page
attrs.push(href);
// let the page open in another window, so state is preserved
attrs.push("target");
attrs.push("_blank");
// use id here as data attributes are not passing through caja
attrs.push("id");
attrs.push("sap-ui-" + that.getId() + "-link-under-validation-" + oValidation.id);
oValidation
.then(function (result) {
// Update link in output
var $link = jQuery.sap.byId("sap-ui-" + that.getId() + "-link-under-validation-" + result.id);
if (result.allowed) {
jQuery.sap.log.info("Allow link " + href);
} else {
jQuery.sap.log.info("Disallow link " + href);
}
// Adapt the link style
$link.removeClass('sapMMsgPopoverItemPendingLink');
$link.toggleClass('sapMMsgPopoverItemDisabledLink', !result.allowed);
that.fireUrlValidated();
})
.catch(function () {
jQuery.sap.log.warning("Async URL validation could not be performed.");
});
}
return attrs;
};
};
/**
* Perform description sanitization based on Caja HTML sanitizer
* @param {sap.m.MessagePopoverItem} oMessagePopoverItem
* @private
*/
MessagePopover.prototype._sanitizeDescription = function (oMessagePopoverItem) {
jQuery.sap.require("jquery.sap.encoder");
jQuery.sap.require("sap.ui.thirdparty.caja-html-sanitizer");
var tagPolicy = this._getTagPolicy();
/*global html*/
var sanitized = html.sanitizeWithPolicy(oMessagePopoverItem.getDescription(), tagPolicy);
oMessagePopoverItem.setDescription(sanitized);
this._setDescription(oMessagePopoverItem);
};
/**
* Handles click of the ListItems
*
* @param {jQuery.Event} oEvent ListItem click event object
* @private
*/
MessagePopover.prototype._fnHandleItemPress = function (oEvent) {
var oListItem = oEvent.getParameter("listItem"),
oMessagePopoverItem = oListItem._oMessagePopoverItem;
var asyncDescHandler = this.getAsyncDescriptionHandler();
var loadAndNavigateToDetailsPage = function (suppressNavigate) {
this._setTitle(oMessagePopoverItem);
this._sanitizeDescription(oMessagePopoverItem);
this._setIcon(oMessagePopoverItem, oListItem);
this.fireLongtextLoaded();
if (!suppressNavigate) {
this._navContainer.to(this._detailsPage);
}
}.bind(this);
this._previousIconTypeClass = this._previousIconTypeClass || '';
this.fireItemSelect({
item: oMessagePopoverItem,
messageTypeFilter: this._getCurrentMessageTypeFilter()
});
this._detailsPage.destroyContent();
if (typeof asyncDescHandler === "function" && !!oMessagePopoverItem.getLongtextUrl()) {
// Set markupDescription to true as markup description should be processed as markup
oMessagePopoverItem.setMarkupDescription(true);
var oPromiseArgument = {};
var oPromise = new window.Promise(function (resolve, reject) {
oPromiseArgument.resolve = resolve;
oPromiseArgument.reject = reject;
});
var proceed = function () {
this._detailsPage.setBusy(false);
loadAndNavigateToDetailsPage(true);
}.bind(this);
oPromise
.then(function () {
proceed();
})
.catch(function () {
jQuery.sap.log.warning("Async description loading could not be performed.");
proceed();
});
this._navContainer.to(this._detailsPage);
this._detailsPage.setBusy(true);
asyncDescHandler({
promise: oPromiseArgument,
item: oMessagePopoverItem
});
} else {
loadAndNavigateToDetailsPage();
}
this._listPage.$().attr("aria-hidden", "true");
};
/**
* Handles click of the BackButton
*
* @private
*/
MessagePopover.prototype._fnHandleBackPress = function () {
this._listPage.$().removeAttr("aria-hidden");
this._navContainer.back();
};
/**
* Handles click of the SegmentedButton
*
* @param {string} sCurrentListName ListName to be shown
* @private
*/
MessagePopover.prototype._fnFilterList = function (sCurrentListName) {
LIST_TYPES.forEach(function (sListIterName) {
if (sListIterName != sCurrentListName && this._oLists[sListIterName].getVisible()) {
// Hide Lists if they are visible and their name is not the same as current list name
this._oLists[sListIterName].setVisible(false);
}
}, this);
this._sCurrentList = sCurrentListName;
this._oLists[sCurrentListName].setVisible(true);
this._expandMsgPopover();
this.fireListSelect({messageTypeFilter: this._getCurrentMessageTypeFilter()});
};
/**
* Returns current selected List name
*
* @returns {string} Current list name
* @private
*/
MessagePopover.prototype._getCurrentMessageTypeFilter = function () {
return this._sCurrentList == "all" ? "" : this._sCurrentList;
};
/**
* Handles navigate event of the NavContainer
*
* @private
*/
MessagePopover.prototype._navigate = function () {
if (this._isListPage()) {
this._oRestoreFocus = jQuery(document.activeElement);
}
};
/**
* Handles navigate event of the NavContainer
*
* @private
*/
MessagePopover.prototype._afterNavigate = function () {
// Just wait for the next tick to apply the focus
jQuery.sap.delayedCall(0, this, this._restoreFocus);
};
/**
* Checks whether the current page is ListPage
*
* @returns {boolean} Whether the current page is ListPage
* @private
*/
MessagePopover.prototype._isListPage = function () {
return (this._navContainer.getCurrentPage() == this._listPage);
};
/**
* Sets initial focus of the control
*
* @private
*/
MessagePopover.prototype._setInitialFocus = function () {
if (this._isListPage()) {
// if current page is the list page - set initial focus to the list.
// otherwise use default functionality built-in the popover
this._oPopover.setInitialFocus(this._oLists[this._sCurrentList]);
}
};
/**
* Restores the focus after navigation
*
* @private
*/
MessagePopover.prototype._restoreFocus = function () {
if (this._isListPage()) {
var oRestoreFocus = this._oRestoreFocus && this._oRestoreFocus.control(0);
if (oRestoreFocus) {
oRestoreFocus.focus();
}
} else {
this._oBackButton.focus();
}
};
/**
* Restores the state defined by the initiallyExpanded property of the MessagePopover
* @private
*/
MessagePopover.prototype._restoreExpansionDefaults = function () {
if (this.getInitiallyExpanded()) {
this._fnFilterList("all");
this._oSegmentedButton.setSelectedButton(null);
} else {
this._collapseMsgPopover();
}
};
/**
* Expands the MessagePopover so that the width and height are equal
* @private
*/
MessagePopover.prototype._expandMsgPopover = function () {
this._oPopover
.setContentHeight(this._oPopover.getContentWidth())
.removeStyleClass(CSS_CLASS + "-init");
};
/**
* Sets the height of the MessagePopover to auto so that only the header with
* the SegmentedButton is visible
* @private
*/
MessagePopover.prototype._collapseMsgPopover = function () {
LIST_TYPES.forEach(function (sListName) {
this._oLists[sListName].setVisible(false);
}, this);
this._oPopover
.addStyleClass(CSS_CLASS + "-init")
.setContentHeight("auto");
this._oSegmentedButton.setSelectedButton("none");
};
/**
* Opens the MessagePopover
*
* @param {sap.ui.core.Control} oControl Control which opens the MessagePopover
* @returns {sap.m.MessagePopover} Reference to the 'this' for chaining purposes
* @public
* @ui5-metamodel
*/
MessagePopover.prototype.openBy = function (oControl) {
var oResponsivePopoverControl = this._oPopover.getAggregation("_popup"),
oParent = oControl.getParent();
// If MessagePopover is opened from an instance of sap.m.Toolbar and is instance of sap.m.Popover remove the Arrow
if (oResponsivePopoverControl instanceof Popover) {
if ((oParent instanceof Toolbar || oParent instanceof Bar || oParent instanceof SemanticPage)) {
oResponsivePopoverControl.setShowArrow(false);
} else {
oResponsivePopoverControl.setShowArrow(true);
}
}
if (this._oPopover) {
this._restoreExpansionDefaults();
this._oPopover.openBy(oControl);
}
return this;
};
/**
* Closes the MessagePopover
*
* @returns {sap.m.MessagePopover} Reference to the 'this' for chaining purposes
* @public
*/
MessagePopover.prototype.close = function () {
if (this._oPopover) {
this._oPopover.close();
}
return this;
};
/**
* The method checks if the MessagePopover is open. It returns true when the MessagePopover is currently open
* (this includes opening and closing animations), otherwise it returns false
*
* @public
* @returns {boolean} Whether the MessagePopover is open
*/
MessagePopover.prototype.isOpen = function () {
return this._oPopover.isOpen();
};
/**
* This method toggles between open and closed state of the MessagePopover instance.
* oControl parameter is mandatory in the same way as in 'openBy' method
*
* @param {sap.ui.core.Control} oControl Control which opens the MessagePopover
* @returns {sap.m.MessagePopover} Reference to the 'this' for chaining purposes
* @public
*/
MessagePopover.prototype.toggle = function (oControl) {
if (this.isOpen()) {
this.close();
} else {
this.openBy(oControl);
}
return this;
};
/**
* The method sets the placement position of the MessagePopover. Only accepted Values are:
* sap.m.PlacementType.Top, sap.m.PlacementType.Bottom and sap.m.PlacementType.Vertical
*
* @param {sap.m.PlacementType} sPlacement Placement type
* @returns {sap.m.MessagePopover} Reference to the 'this' for chaining purposes
*/
MessagePopover.prototype.setPlacement = function (sPlacement) {
this.setProperty("placement", sPlacement, true);
this._oPopover.setPlacement(sPlacement);
return this;
};
MessagePopover.prototype.getDomRef = function (sSuffix) {
return this._oPopover && this._oPopover.getAggregation("_popup").getDomRef(sSuffix);
};
["addStyleClass", "removeStyleClass", "toggleStyleClass", "hasStyleClass", "getBusyIndicatorDelay",
"setBusyIndicatorDelay", "getVisible", "setVisible", "getBusy", "setBusy"].forEach(function(sName){
MessagePopover.prototype[sName] = function() {
if (this._oPopover && this._oPopover[sName]) {
var oPopover = this._oPopover;
var res = oPopover[sName].apply(oPopover, arguments);
return res === oPopover ? this : res;
}
};
});
// The following inherited methods of this control are extended because this control uses ResponsivePopover for rendering
["setModel", "bindAggregation", "setAggregation", "insertAggregation", "addAggregation",
"removeAggregation", "removeAllAggregation", "destroyAggregation"].forEach(function (sFuncName) {
// First, they are saved for later reference
MessagePopover.prototype["_" + sFuncName + "Old"] = MessagePopover.prototype[sFuncName];
// Once they are called
MessagePopover.prototype[sFuncName] = function () {
// We immediately call the saved method first
var result = MessagePopover.prototype["_" + sFuncName + "Old"].apply(this, arguments);
// Then there is additional logic
// Mark items aggregation as changed and invalidate popover to trigger rendering
// See 'MessagePopover.prototype.onBeforeRenderingPopover'
this._bItemsChanged = true;
// If Popover dependency has already been instantiated ...
if (this._oPopover) {
// ... invalidate it
this._oPopover.invalidate();
}
// If the called method is 'removeAggregation' or 'removeAllAggregation' ...
if (["removeAggregation", "removeAllAggregation"].indexOf(sFuncName) !== -1) {
// ... return the result of the operation
return result;
}
return this;
};
});
return MessagePopover;
}, /* bExport= */ true);
| pro100den/openui5-bundle | Resources/public/sap/m/MessagePopover-dbg.js | JavaScript | apache-2.0 | 37,700 |
using BdlIBMS.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BdlIBMS.Repositories
{
public interface IUserRepository : IRepository<string, User>
{
User FindByUserNameAndPassword(string userName, string password);
}
}
| chengliangkaka/PazhouBanghua_BMS | BdlIBMS/Repositories/IUserRepository.cs | C# | apache-2.0 | 328 |
<div class="table-overflow overflow">
<table class="efor-table-logs mdl-data-table mdl-shadow--2dp">
<thead>
<tr>
<th class="mdl-data-table__cell--non-numeric">Nombre</th>
<th class="mdl-data-table__cell--non-numeric" width="280px">Email</th>
<th class="mdl-data-table__cell--non-numeric">Apellido</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in users">
<td class="text-a-left" data-title="Nombre">{[{user.first_name}]}</td>
<td class="text-a-left" data-title="email">
<a ng-href="{[{user.email}]}" class="text-overflow">{[{user.email}]}</a>
</td>
<td class="text-a-left" data-title="Apellido">
{[{user.last_name}]}
<button id="menu-lower-right-{[{$index}]}" class="button-to-right mdl-button mdl-js-button mdl-button--icon">
<i class="material-icons">more_vert</i>
</button>
<ul class="efor-menu efor-menu__small mdl-menu mdl-menu--bottom-right mdl-js-menu mdl-js-ripple-effect" for="menu-lower-right-{[{$index}]}">
<li class="mdl-menu__item" ng-click="openDelete(user)">
<i class="material-icons">delete</i>
{[{'user_delete_title' | translate}]}
</li>
</ul>
</td>
</tr>
</tbody>
</table>
</div>
| Eforcers/python-gae-template | static/html/partials/user_list.html | HTML | apache-2.0 | 1,560 |
package com.github.particlesystem.modifiers;
import com.github.particlesystem.Particle;
public interface ParticleModifier {
/**
* modifies the specific value of a particle given the current miliseconds
*
* @param particle
* @param miliseconds
*/
void apply(Particle particle, long miliseconds);
}
| rohitiskul/ParticleSystem | particlesystem/src/main/java/com/github/particlesystem/modifiers/ParticleModifier.java | Java | apache-2.0 | 335 |
package com.ftfl.icare;
import java.util.List;
import com.ftfl.icare.adapter.CustomAppointmentAdapter;
import com.ftfl.icare.adapter.CustomDoctorAdapter;
import com.ftfl.icare.helper.AppointmentDataSource;
import com.ftfl.icare.helper.DoctorProfileDataSource;
import com.ftfl.icare.model.Appointment;
import com.ftfl.icare.model.DoctorProfile;
import com.ftfl.icare.util.FragmentHome;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class FragmentAppointmentList extends Fragment {
TextView mId_tv = null;
AppointmentDataSource mAppointmentDataSource;
Appointment mAppointment;
FragmentManager mFrgManager;
Fragment mFragment;
Context mContext;
ListView mLvProfileList;
List<Appointment> mDoctorProfileList;
String mId;
Bundle mArgs = new Bundle();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_doctor_list, container,
false);
mContext = container.getContext();
mAppointmentDataSource = new AppointmentDataSource(getActivity());
mDoctorProfileList = mAppointmentDataSource.appointmentList();
CustomAppointmentAdapter arrayAdapter = new CustomAppointmentAdapter(
getActivity(), mDoctorProfileList);
mLvProfileList = (ListView) view.findViewById(R.id.lvDoctorList);
mLvProfileList.setAdapter(arrayAdapter);
mLvProfileList
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
final int pos = position;
new AlertDialog.Builder(mContext)
.setTitle("Delete entry")
.setMessage(
"Are you sure you want to delete this entry?")
.setPositiveButton(android.R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
mAppointmentDataSource = new AppointmentDataSource(
getActivity());
if (mAppointmentDataSource.deleteData(Integer
.parseInt(mDoctorProfileList
.get(pos)
.getId())) == true) {
Toast toast = Toast
.makeText(
getActivity(),
"Successfully Deleted.",
Toast.LENGTH_LONG);
toast.show();
mFragment = new FragmentHome();
mFrgManager = getFragmentManager();
mFrgManager
.beginTransaction()
.replace(
R.id.content_frame,
mFragment)
.commit();
setTitle("Home");
} else {
Toast toast = Toast
.makeText(
getActivity(),
"Error, Couldn't inserted data to database",
Toast.LENGTH_LONG);
toast.show();
}
}
})
.setNegativeButton(android.R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
// do nothing
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
});
return view;
}
public void setTitle(CharSequence title) {
getActivity().getActionBar().setTitle(title);
}
} | FTFL02-ANDROID/julkarnine | ICare/src/com/ftfl/icare/FragmentAppointmentList.java | Java | apache-2.0 | 3,803 |
---
title: IDEA
date: 2017-05-27 10:50:00
tags: idea
categories: tools
---
## [下载](https://confluence.jetbrains.com/display/IDEADEV/IDEA+14.1+EAP)
- [Windows](https://download.jetbrains.com/idea/ideaIU-14.1.7.zip)
- [OS X](https://download.jetbrains.com/idea/ideaIU-14.1.7.dmg)
- [Linux](https://download.jetbrains.com/idea/ideaIU-14.1.7.tar.gz)
## 安装
1. 将IntelliJ免安装版解压到指定(如 D:\Portable\IntelliJ)目录
2. 修改`${idea.home}/bin/idea.properties`
``` properties
# idea.config.path=${user.home}/.IntelliJIdea/config
idea.config.path=${idea.home}/config
# idea.system.path=${user.home}/.IntelliJIdea/system
idea.system.path=${idea.home}/system
```
3. 修改`${idea.home}/bin/idea(64).exe.vmoptions`追加`-Dfile.encoding=UTF-8`
4. 其它配置
``` py
# 显示行号
File > Settings > Editor > General > Appearance > Show line numbers
# 代码字体设置
File > Settings > Editor > Colors & Fonts > Font
# 快捷键设置
File > Settings > Keymap > Keymaps > Eclipse
File > Settings > Keymap > Main menu > Code > Completion > Cyclic Expand Word > Alt+. & Basic > Alt+/
File > Settings > Editor > General > Code Completion > Case sensitive completion=None
# 类方法不自动折叠
File > Settings > Editor > General > Code Folding > One-line methods=false
File > Settings > Editor > Code Style > Java > Imports > Class count to use import with ‘*’=99
# 编码设置
File > Settings > Editor > File Encodings > IDE Encoding&Project Encoding&Default encoding > UTF-8
# 隐藏项目配置文件
File > Settings > Editor > File Types > Ignore files and folders > *.idea;*.iml
```
## 安装Plugin
- [JRebel](http://dl.zeroturnaround.com/idea/)
http://dl.zeroturnaround.com/idea/jr-ide-intellij-7.0.9_13-17.zip
> *说明:安装插件时将包含lib目录的插件文件夹拷贝到${idea.home}/plugins目录即可。* | lugavin/blog | source/_posts/tools/idea.md | Markdown | apache-2.0 | 1,866 |
package com.ymsino.water.service.manager.manager;
import java.util.List;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.ws.RequestWrapper;
import javax.xml.ws.ResponseWrapper;
/**
* This class was generated by the JAX-WS RI. JAX-WS RI 2.1.3-hudson-390- Generated source version: 2.0
*
*/
@WebService(name = "ManagerService", targetNamespace = "http://api.service.manager.esb.ymsino.com/")
public interface ManagerService {
/**
* 登录(密码为明文密码,只有状态为开通的管理员才能登录)
*
* @param mangerId
* @param password
* @return returns com.ymsino.water.service.manager.manager.ManagerReturn
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "login", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.Login")
@ResponseWrapper(localName = "loginResponse", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.LoginResponse")
public ManagerReturn login(@WebParam(name = "mangerId", targetNamespace = "") String mangerId, @WebParam(name = "password", targetNamespace = "") String password);
/**
* 保存管理员
*
* @param managerSaveParam
* @return returns java.lang.Boolean
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "save", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.Save")
@ResponseWrapper(localName = "saveResponse", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.SaveResponse")
public Boolean save(@WebParam(name = "managerSaveParam", targetNamespace = "") ManagerSaveParam managerSaveParam);
/**
* 根据查询参数获取管理员分页列表
*
* @param queryParam
* @param startRow
* @param pageSize
* @return returns java.util.List<com.ymsino.water.service.manager.manager.ManagerReturn>
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "getListpager", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.GetListpager")
@ResponseWrapper(localName = "getListpagerResponse", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.GetListpagerResponse")
public List<ManagerReturn> getListpager(@WebParam(name = "queryParam", targetNamespace = "") QueryParam queryParam, @WebParam(name = "startRow", targetNamespace = "") Integer startRow, @WebParam(name = "pageSize", targetNamespace = "") Integer pageSize);
/**
* 停用帐号(审核不通过)
*
* @param mangerId
* @return returns java.lang.Boolean
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "closeStatus", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.CloseStatus")
@ResponseWrapper(localName = "closeStatusResponse", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.CloseStatusResponse")
public Boolean closeStatus(@WebParam(name = "mangerId", targetNamespace = "") String mangerId);
/**
* 修改管理员
*
* @param managerModifyParam
* @return returns java.lang.Boolean
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "modify", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.Modify")
@ResponseWrapper(localName = "modifyResponse", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.ModifyResponse")
public Boolean modify(@WebParam(name = "managerModifyParam", targetNamespace = "") ManagerModifyParam managerModifyParam);
/**
* 根据查询参数获取管理员记录数
*
* @param queryParam
* @return returns java.lang.Integer
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "getCount", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.GetCount")
@ResponseWrapper(localName = "getCountResponse", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.GetCountResponse")
public Integer getCount(@WebParam(name = "queryParam", targetNamespace = "") QueryParam queryParam);
/**
* 启用帐号(审核通过)
*
* @param managerId
* @return returns java.lang.Boolean
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "openStatus", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.OpenStatus")
@ResponseWrapper(localName = "openStatusResponse", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.OpenStatusResponse")
public Boolean openStatus(@WebParam(name = "managerId", targetNamespace = "") String managerId);
/**
* 根据管理员id获取管理员实体
*
* @param mangerId
* @return returns com.ymsino.water.service.manager.manager.ManagerReturn
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "getByManagerId", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.GetByManagerId")
@ResponseWrapper(localName = "getByManagerIdResponse", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.GetByManagerIdResponse")
public ManagerReturn getByManagerId(@WebParam(name = "mangerId", targetNamespace = "") String mangerId);
}
| xcjava/ymWaterWeb | manager_ws_client/com/ymsino/water/service/manager/manager/ManagerService.java | Java | apache-2.0 | 6,070 |
# -*- coding: utf-8 -*-
import allure
from selenium.webdriver.common.by import By
from .base import BasePage
from .elements import SimpleInput, SimpleText
from .blocks.nav import NavBlock
class BrowseMoviePageLocators(object):
"""Локаторы страницы просмотра информации о фильме"""
TITLE_LOCATOR = (By.CSS_SELECTOR, '#movie h2')
COUNTRY_LOCATOR = (By.NAME, 'country')
DIRECTOR_LOCATOR = (By.NAME, 'director')
WRITER_LOCATOR = (By.NAME, 'writer')
PRODUCER_LOCATOR = (By.NAME, 'producer')
EDIT_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Edit"]')
REMOVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]')
class BrowseMoviePage(BasePage):
"""Страница просмотра информации о фильме"""
def __init__(self, driver):
super(BrowseMoviePage, self).__init__(driver)
self.nav = NavBlock(driver)
title = SimpleText(BrowseMoviePageLocators.TITLE_LOCATOR)
director = SimpleText(BrowseMoviePageLocators.DIRECTOR_LOCATOR)
writer = SimpleText(BrowseMoviePageLocators.WRITER_LOCATOR)
producer = SimpleText(BrowseMoviePageLocators.PRODUCER_LOCATOR)
@allure.step('Нажмем на кноку "Edit"')
def click_edit_button(self):
"""
:rtype: EditMoviePage
"""
self._click(BrowseMoviePageLocators.EDIT_BUTTON_LOCATOR)
return EditMoviePage(self._driver)
@allure.step('Нажмем на кноку "Remove"')
def click_remove_button(self):
"""
:rtype: HomePage
"""
self._click(BrowseMoviePageLocators.REMOVE_BUTTON_LOCATOR)
self.alert_accept()
from .home import HomePage
return HomePage(self._driver)
class AddMoviePageLocators(object):
"""Локаторы страницы создания описания фильма"""
TITLE_INPUT_LOCATOR = (By.NAME, 'name')
TITLE_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="name"].error')
ALSO_KNOWN_AS_INPUT_LOCATOR = (By.NAME, 'aka')
YEAR_INPUT_LOCATOR = (By.NAME, 'year')
YEAR_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="year"].error')
DURATION_INPUT_LOCATOR = (By.NAME, 'duration')
TRAILER_URL_INPUT_LOCATOR = (By.NAME, 'trailer')
FORMAT_INPUT_LOCATOR = (By.NAME, 'format')
COUNTRY_INPUT_LOCATOR = (By.NAME, 'country')
DIRECTOR_INPUT_LOCATOR = (By.NAME, 'director')
WRITER_INPUT_LOCATOR = (By.NAME, 'writer')
PRODUCER_INPUT_LOCATOR = (By.NAME, 'producer')
SAVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Save"]')
class AddMoviePage(BasePage):
"""Страница создания описания фильма"""
def __init__(self, driver):
super(AddMoviePage, self).__init__(driver)
self.nav = NavBlock(driver)
title = SimpleInput(AddMoviePageLocators.TITLE_INPUT_LOCATOR, 'название фильма')
also_know_as = SimpleInput(AddMoviePageLocators.ALSO_KNOWN_AS_INPUT_LOCATOR, 'оригинальное название фильма')
year = SimpleInput(AddMoviePageLocators.YEAR_INPUT_LOCATOR, 'год')
duration = SimpleInput(AddMoviePageLocators.DURATION_INPUT_LOCATOR, 'продолжительность')
trailer_url = SimpleInput(AddMoviePageLocators.TRAILER_URL_INPUT_LOCATOR, 'адрес трейлера')
format = SimpleInput(AddMoviePageLocators.FORMAT_INPUT_LOCATOR, 'формат')
country = SimpleInput(AddMoviePageLocators.COUNTRY_INPUT_LOCATOR, 'страну')
director = SimpleInput(AddMoviePageLocators.DIRECTOR_INPUT_LOCATOR, 'директора')
writer = SimpleInput(AddMoviePageLocators.WRITER_INPUT_LOCATOR, 'сценариста')
producer = SimpleInput(AddMoviePageLocators.PRODUCER_INPUT_LOCATOR, 'продюсера')
@allure.step('Нажмем на кноку "Save"')
def click_save_button(self):
"""
:rtype: BrowseMoviePage
"""
self._click(AddMoviePageLocators.SAVE_BUTTON_LOCATOR)
return BrowseMoviePage(self._driver)
def title_field_is_required_present(self):
"""
:rtype: bool
"""
return self._is_element_present(AddMoviePageLocators.TITLE_INPUT_ERROR_LOCATOR)
def year_field_is_required_present(self):
"""
:rtype: bool
"""
return self._is_element_present(AddMoviePageLocators.YEAR_INPUT_ERROR_LOCATOR)
class EditMoviePageLocators(object):
"""Локаторы для страницы редактирования описания фильма"""
REMOVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]')
class EditMoviePage(AddMoviePage):
"""Страница редактирования описания фильма"""
@allure.step('Нажмем на кноку "Remove"')
def click_remove_button(self):
"""
:rtype: HomePage
"""
self._click(EditMoviePageLocators.REMOVE_BUTTON_LOCATOR)
self.alert_accept()
from .home import HomePage
return HomePage(self._driver)
| adv-tsk/Course-Se-Python | php4dvd/pages/movie.py | Python | apache-2.0 | 5,067 |
Contextual Image Delivery
=============================
This is an optional module for the SDL Digital Experience Accelerator Java web application. It contains an implementation
of interface `MediaHelper` that uses Tridion Contextual Image Delivery (CID) to resize images on the server side.
Note that in order to use Tridion CID, you need a license. If you do not have a license for CID or if you are not sure,
then contact SDL if you want to use CID.
You can also choose to not use CID. The web application will then use a different implementation of `MediaHelper` to
resize images.
In the `dxa-common-api` there is a Spring factory bean `MediaHelperFactory` that automatically chooses the
implementation of `MediaHelper` to use. It does this by checking if the CID-specific implementation is available in the
classpath. If it is, it will use the CID-specific implementation, otherwise it will use the default implementation.
## Enabling or disabling the use of CID
When you activate the Maven profile `cid`, this module and its dependencies will be included in the project. This means
you can compile the web application with support for CID by compiling the project with:
mvn clean package -P cid
If you do not want to use CID, simply leave off `-P cid`.
Note that if you do use CID, you will have to edit the configuration file `cd_ambient_conf` in
`dxa-webapp\src\main\resources` to enable the CID Ambient Data Framework cartridge.
| sdl/dxa-modules | webapp-java/dxa-module-cid/README.md | Markdown | apache-2.0 | 1,451 |
//
// DZYSquareCell.h
// budejie
//
// Created by dzy on 16/1/7.
// Copyright © 2016年 董震宇. All rights reserved.
//
#import <UIKit/UIKit.h>
@class DZYSquareModel;
@interface DZYSquareCell : UICollectionViewCell
/** 方块模型 */
@property (nonatomic, strong) DZYSquareModel *squareModel;
@end
| dongzhenyu/CoderBS | budejie/budejie/Classes/Me(我)/View/DZYSquareCell.h | C | apache-2.0 | 310 |
package app.yweather.com.yweather.util;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.preference.PreferenceManager;
import org.json.JSONArray;
import org.json.JSONObject;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
/**
* 解析JSON工具类
*/
public class Utility {
//解析服务器返回的JSON数据,并将解析出的数据存储到本地。
public static void handleWeatherResponse(Context context, String response){
try{
JSONArray jsonObjs = new JSONObject(response).getJSONArray("results");
JSONObject locationJsonObj = ((JSONObject)jsonObjs.opt(0)).getJSONObject("location");
String id = locationJsonObj.getString("id");
String name = locationJsonObj.getString("name");
JSONObject nowJsonObj = ((JSONObject)jsonObjs.opt(0)).getJSONObject("now");
String text = nowJsonObj.getString("text");
String temperature = nowJsonObj.getString("temperature");
String wind = nowJsonObj.getString("wind_direction");
String lastUpdateTime = ((JSONObject) jsonObjs.opt(0)).getString("last_update");
lastUpdateTime = lastUpdateTime.substring(lastUpdateTime.indexOf("+") + 1,lastUpdateTime.length());
LogUtil.e("Utility", "name:" + name + ",text:"+ text + "wind:" + wind + ",lastUpdateTime:" + lastUpdateTime);
saveWeatherInfo(context,name,id,temperature,text,lastUpdateTime);
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 将服务器返回的天气信息存储到SharedPreferences文件中
* context : Context对象
* cityName : 城市名称
* cityId : 城市id
* temperature: 温度
* text :天气现象文字说明,如多云
* lastUpdateTime : 数据更新时间
* 2016-07-16T13:10:00+08:00
*/
@TargetApi(Build.VERSION_CODES.N) //指定使用的系统版本
public static void saveWeatherInfo(Context context, String cityName, String cityId, String temperature,
String text, String lastUpdateTime){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年M月d日", Locale.CANADA);
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
editor.putBoolean("city_selected",true);
editor.putString("city_name",cityName);
editor.putString("city_id",cityId);
editor.putString("temperature",temperature);
editor.putString("text",text);
editor.putString("last_update_time",lastUpdateTime);
editor.putString("current_date",sdf.format(new Date()));
editor.commit();
}
}
| llxyhuang/YWeather | app/src/main/java/app/yweather/com/yweather/util/Utility.java | Java | apache-2.0 | 2,845 |
package pl.touk.nussknacker.engine.flink.util.timestamp
import com.github.ghik.silencer.silent
import org.apache.flink.streaming.api.functions.AssignerWithPeriodicWatermarks
import org.apache.flink.streaming.api.watermark.Watermark
import scala.annotation.nowarn
/**
* It is a copy-paste of BoundedOutOfOrdernessTimestampExtractor but taking timestamp from previousElementTimestamp
* See https://ci.apache.org/projects/flink/flink-docs-stable/dev/connectors/kafka.html#using-kafka-timestamps-and-flink-event-time-in-kafka-010
*/
@silent("deprecated")
@nowarn("cat=deprecation")
class BoundedOutOfOrderPreviousElementAssigner[T](maxOutOfOrdernessMillis: Long)
extends AssignerWithPeriodicWatermarks[T] with Serializable {
private var currentMaxTimestamp = Long.MinValue + maxOutOfOrdernessMillis
private var lastEmittedWatermark = Long.MinValue
override def extractTimestamp(element: T, previousElementTimestamp: Long): Long = {
if (previousElementTimestamp > currentMaxTimestamp)
currentMaxTimestamp = previousElementTimestamp
previousElementTimestamp
}
override def getCurrentWatermark: Watermark = {
val potentialWM = currentMaxTimestamp - maxOutOfOrdernessMillis
if (potentialWM >= lastEmittedWatermark)
lastEmittedWatermark = potentialWM
new Watermark(lastEmittedWatermark)
}
}
| TouK/nussknacker | engine/flink/components-utils/src/main/scala/pl/touk/nussknacker/engine/flink/util/timestamp/BoundedOutOfOrderPreviousElementAssigner.scala | Scala | apache-2.0 | 1,340 |
/*
* Copyright (C) 2017 grandcentrix GmbH
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.grandcentrix.thirtyinch;
import android.content.res.Configuration;
import android.os.Bundle;
import androidx.annotation.CallSuper;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import java.util.List;
import java.util.concurrent.Executor;
import net.grandcentrix.thirtyinch.internal.DelegatedTiActivity;
import net.grandcentrix.thirtyinch.internal.InterceptableViewBinder;
import net.grandcentrix.thirtyinch.internal.PresenterAccessor;
import net.grandcentrix.thirtyinch.internal.PresenterSavior;
import net.grandcentrix.thirtyinch.internal.TiActivityDelegate;
import net.grandcentrix.thirtyinch.internal.TiLoggingTagProvider;
import net.grandcentrix.thirtyinch.internal.TiPresenterProvider;
import net.grandcentrix.thirtyinch.internal.TiViewProvider;
import net.grandcentrix.thirtyinch.internal.UiThreadExecutor;
import net.grandcentrix.thirtyinch.util.AnnotationUtil;
/**
* An Activity which has a {@link TiPresenter} to build the Model View Presenter architecture on
* Android.
*
* <p>
* The {@link TiPresenter} will be created in {@link #providePresenter()} called in
* {@link #onCreate(Bundle)}. Depending on the {@link TiConfiguration} passed into the
* {@link TiPresenter#TiPresenter(TiConfiguration)} constructor the {@link TiPresenter} survives
* orientation changes (default).
* </p>
* <p>
* The {@link TiPresenter} requires a interface to communicate with the View. Normally the Activity
* implements the View interface (which must extend {@link TiView}) and is returned by default
* from {@link #provideView()}.
* </p>
*
* <p>
* Example:
* <code>
* <pre>
* public class MyActivity extends TiActivity<MyPresenter, MyView> implements MyView {
*
* @Override
* public MyPresenter providePresenter() {
* return new MyPresenter();
* }
* }
*
* public class MyPresenter extends TiPresenter<MyView> {
*
* @Override
* protected void onCreate() {
* super.onCreate();
* }
* }
*
* public interface MyView extends TiView {
*
* // void showItems(List<Item> items);
*
* // Observable<Item> onItemClicked();
* }
* </pre>
* </code>
* </p>
*
* @param <V> the View type, must implement {@link TiView}
* @param <P> the Presenter type, must extend {@link TiPresenter}
*/
public abstract class TiActivity<P extends TiPresenter<V>, V extends TiView>
extends AppCompatActivity
implements TiPresenterProvider<P>, TiViewProvider<V>, DelegatedTiActivity,
TiLoggingTagProvider, InterceptableViewBinder<V>, PresenterAccessor<P, V> {
private final String TAG = this.getClass().getSimpleName()
+ ":" + TiActivity.class.getSimpleName()
+ "@" + Integer.toHexString(this.hashCode());
private final TiActivityDelegate<P, V> mDelegate
= new TiActivityDelegate<>(this, this, this, this, PresenterSavior.getInstance());
private final UiThreadExecutor mUiThreadExecutor = new UiThreadExecutor();
@CallSuper
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDelegate.onCreate_afterSuper(savedInstanceState);
}
@CallSuper
@Override
protected void onStart() {
super.onStart();
mDelegate.onStart_afterSuper();
}
@CallSuper
@Override
protected void onStop() {
mDelegate.onStop_beforeSuper();
super.onStop();
mDelegate.onStop_afterSuper();
}
@CallSuper
@Override
protected void onSaveInstanceState(@NonNull final Bundle outState) {
super.onSaveInstanceState(outState);
mDelegate.onSaveInstanceState_afterSuper(outState);
}
@CallSuper
@Override
protected void onDestroy() {
super.onDestroy();
mDelegate.onDestroy_afterSuper();
}
@NonNull
@Override
public final Removable addBindViewInterceptor(@NonNull final BindViewInterceptor interceptor) {
return mDelegate.addBindViewInterceptor(interceptor);
}
@Override
public final Object getHostingContainer() {
return this;
}
@Nullable
@Override
public final V getInterceptedViewOf(@NonNull final BindViewInterceptor interceptor) {
return mDelegate.getInterceptedViewOf(interceptor);
}
@NonNull
@Override
public final List<BindViewInterceptor> getInterceptors(
@NonNull final Filter<BindViewInterceptor> predicate) {
return mDelegate.getInterceptors(predicate);
}
@Override
public String getLoggingTag() {
return TAG;
}
/**
* is {@code null} before {@link #onCreate(Bundle)}
*/
@Override
public final P getPresenter() {
return mDelegate.getPresenter();
}
@Override
public final Executor getUiThreadExecutor() {
return mUiThreadExecutor;
}
/**
* Invalidates the cache of the latest bound view. Forces the next binding of the view to run
* through all the interceptors (again).
*/
@Override
public final void invalidateView() {
mDelegate.invalidateView();
}
@Override
public final boolean isActivityFinishing() {
return isFinishing();
}
@CallSuper
@Override
public void onConfigurationChanged(@NonNull final Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDelegate.onConfigurationChanged_afterSuper(newConfig);
}
@SuppressWarnings("unchecked")
@NonNull
@Override
public V provideView() {
final Class<?> foundViewInterface = AnnotationUtil
.getInterfaceOfClassExtendingGivenInterface(this.getClass(), TiView.class);
if (foundViewInterface == null) {
throw new IllegalArgumentException(
"This Activity doesn't implement a TiView interface. "
+ "This is the default behaviour. Override provideView() to explicitly change this.");
} else {
if (foundViewInterface.getSimpleName().equals("TiView")) {
throw new IllegalArgumentException(
"extending TiView doesn't make sense, it's an empty interface."
+ " This is the default behaviour. Override provideView() to explicitly change this.");
} else {
// assume that the activity itself is the view and implements the TiView interface
return (V) this;
}
}
}
@Override
public String toString() {
String presenter = mDelegate.getPresenter() == null ? "null" :
mDelegate.getPresenter().getClass().getSimpleName()
+ "@" + Integer.toHexString(mDelegate.getPresenter().hashCode());
return getClass().getSimpleName()
+ ":" + TiActivity.class.getSimpleName()
+ "@" + Integer.toHexString(hashCode())
+ "{presenter = " + presenter + "}";
}
}
| grandcentrix/ThirtyInch | thirtyinch/src/main/java/net/grandcentrix/thirtyinch/TiActivity.java | Java | apache-2.0 | 7,692 |
/*jslint browser: true*/
/*global $, jQuery, alert*/
(function ($) {
"use strict";
$(document).ready(function () {
$("input[name=dob]").datepicker({
dateFormat: 'yy-mm-dd',
inline: true,
showOtherMonths: true
});
});
$(document).ready(function () {
$("input[name='rep_password']").focusout(function () {
var p1 = $('input[name="password"]').val(), p2 = $('input[name="rep_password"]').val();
if (p1 !== p2) {
$('#passDM').show(300);
} else if (p1 === "") {
$('#passDM').show(300);
} else {
$('#passDM').hide(300);
}
});
});
$(document).ready(function () {
$("input[name=password]").focusin(function () {
$('#passDM').hide(300);
});
$("input[name=rep_password]").focusin(function () {
$('#passDM').hide(300);
});
});
}(jQuery)); | manoj2509/Sensa | js/logIn.js | JavaScript | apache-2.0 | 1,018 |
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V. licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
//
// Code generated from specification version 7.7.0: DO NOT EDIT
package esapi
import (
"context"
"io"
"net/http"
"strings"
)
func newAutoscalingPutAutoscalingPolicyFunc(t Transport) AutoscalingPutAutoscalingPolicy {
return func(name string, body io.Reader, o ...func(*AutoscalingPutAutoscalingPolicyRequest)) (*Response, error) {
var r = AutoscalingPutAutoscalingPolicyRequest{Name: name, Body: body}
for _, f := range o {
f(&r)
}
return r.Do(r.ctx, t)
}
}
// ----- API Definition -------------------------------------------------------
// AutoscalingPutAutoscalingPolicy -
//
// This API is experimental.
//
// See full documentation at https://www.elastic.co/guide/en/elasticsearch/reference/current/autoscaling-put-autoscaling-policy.html.
//
type AutoscalingPutAutoscalingPolicy func(name string, body io.Reader, o ...func(*AutoscalingPutAutoscalingPolicyRequest)) (*Response, error)
// AutoscalingPutAutoscalingPolicyRequest configures the Autoscaling Put Autoscaling Policy API request.
//
type AutoscalingPutAutoscalingPolicyRequest struct {
Body io.Reader
Name string
Pretty bool
Human bool
ErrorTrace bool
FilterPath []string
Header http.Header
ctx context.Context
}
// Do executes the request and returns response or error.
//
func (r AutoscalingPutAutoscalingPolicyRequest) Do(ctx context.Context, transport Transport) (*Response, error) {
var (
method string
path strings.Builder
params map[string]string
)
method = "PUT"
path.Grow(1 + len("_autoscaling") + 1 + len("policy") + 1 + len(r.Name))
path.WriteString("/")
path.WriteString("_autoscaling")
path.WriteString("/")
path.WriteString("policy")
path.WriteString("/")
path.WriteString(r.Name)
params = make(map[string]string)
if r.Pretty {
params["pretty"] = "true"
}
if r.Human {
params["human"] = "true"
}
if r.ErrorTrace {
params["error_trace"] = "true"
}
if len(r.FilterPath) > 0 {
params["filter_path"] = strings.Join(r.FilterPath, ",")
}
req, err := newRequest(method, path.String(), r.Body)
if err != nil {
return nil, err
}
if len(params) > 0 {
q := req.URL.Query()
for k, v := range params {
q.Set(k, v)
}
req.URL.RawQuery = q.Encode()
}
if r.Body != nil {
req.Header[headerContentType] = headerContentTypeJSON
}
if len(r.Header) > 0 {
if len(req.Header) == 0 {
req.Header = r.Header
} else {
for k, vv := range r.Header {
for _, v := range vv {
req.Header.Add(k, v)
}
}
}
}
if ctx != nil {
req = req.WithContext(ctx)
}
res, err := transport.Perform(req)
if err != nil {
return nil, err
}
response := Response{
StatusCode: res.StatusCode,
Body: res.Body,
Header: res.Header,
}
return &response, nil
}
// WithContext sets the request context.
//
func (f AutoscalingPutAutoscalingPolicy) WithContext(v context.Context) func(*AutoscalingPutAutoscalingPolicyRequest) {
return func(r *AutoscalingPutAutoscalingPolicyRequest) {
r.ctx = v
}
}
// WithPretty makes the response body pretty-printed.
//
func (f AutoscalingPutAutoscalingPolicy) WithPretty() func(*AutoscalingPutAutoscalingPolicyRequest) {
return func(r *AutoscalingPutAutoscalingPolicyRequest) {
r.Pretty = true
}
}
// WithHuman makes statistical values human-readable.
//
func (f AutoscalingPutAutoscalingPolicy) WithHuman() func(*AutoscalingPutAutoscalingPolicyRequest) {
return func(r *AutoscalingPutAutoscalingPolicyRequest) {
r.Human = true
}
}
// WithErrorTrace includes the stack trace for errors in the response body.
//
func (f AutoscalingPutAutoscalingPolicy) WithErrorTrace() func(*AutoscalingPutAutoscalingPolicyRequest) {
return func(r *AutoscalingPutAutoscalingPolicyRequest) {
r.ErrorTrace = true
}
}
// WithFilterPath filters the properties of the response body.
//
func (f AutoscalingPutAutoscalingPolicy) WithFilterPath(v ...string) func(*AutoscalingPutAutoscalingPolicyRequest) {
return func(r *AutoscalingPutAutoscalingPolicyRequest) {
r.FilterPath = v
}
}
// WithHeader adds the headers to the HTTP request.
//
func (f AutoscalingPutAutoscalingPolicy) WithHeader(h map[string]string) func(*AutoscalingPutAutoscalingPolicyRequest) {
return func(r *AutoscalingPutAutoscalingPolicyRequest) {
if r.Header == nil {
r.Header = make(http.Header)
}
for k, v := range h {
r.Header.Add(k, v)
}
}
}
// WithOpaqueID adds the X-Opaque-Id header to the HTTP request.
//
func (f AutoscalingPutAutoscalingPolicy) WithOpaqueID(s string) func(*AutoscalingPutAutoscalingPolicyRequest) {
return func(r *AutoscalingPutAutoscalingPolicyRequest) {
if r.Header == nil {
r.Header = make(http.Header)
}
r.Header.Set("X-Opaque-Id", s)
}
}
| control-center/serviced | vendor/github.com/elastic/go-elasticsearch/v7/esapi/api.xpack.autoscaling.put_autoscaling_policy.go | GO | apache-2.0 | 4,902 |
"""
Copyright 2015-2018 IBM
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Licensed Materials - Property of IBM
© Copyright IBM Corp. 2015-2018
"""
import asyncio
from confluent_kafka import Producer
class ProducerTask(object):
def __init__(self, conf, topic_name):
self.topic_name = topic_name
self.producer = Producer(conf)
self.counter = 0
self.running = True
def stop(self):
self.running = False
def on_delivery(self, err, msg):
if err:
print('Delivery report: Failed sending message {0}'.format(msg.value()))
print(err)
# We could retry sending the message
else:
print('Message produced, offset: {0}'.format(msg.offset()))
@asyncio.coroutine
def run(self):
print('The producer has started')
while self.running:
message = 'This is a test message #{0}'.format(self.counter)
key = 'key'
sleep = 2 # Short sleep for flow control
try:
self.producer.produce(self.topic_name, message, key, -1, self.on_delivery)
self.producer.poll(0)
self.counter += 1
except Exception as err:
print('Failed sending message {0}'.format(message))
print(err)
sleep = 5 # Longer sleep before retrying
yield from asyncio.sleep(sleep)
self.producer.flush()
| ibm-messaging/message-hub-samples | kafka-python-console-sample/producertask.py | Python | apache-2.0 | 1,944 |
/*
* Copyright 2012 International Business Machines Corp.
*
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership. Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ibm.jbatch.jsl.util;
import javax.xml.bind.ValidationEvent;
import javax.xml.bind.ValidationEventHandler;
public class JSLValidationEventHandler implements ValidationEventHandler {
private boolean eventOccurred = false;
public boolean handleEvent(ValidationEvent event) {
System.out.println("\nMESSAGE: " + event.getMessage());
System.out.println("\nSEVERITY: " + event.getSeverity());
System.out.println("\nLINKED EXC: " + event.getLinkedException());
System.out.println("\nLOCATOR INFO:\n------------");
System.out.println("\n COLUMN NUMBER: " + event.getLocator().getColumnNumber());
System.out.println("\n LINE NUMBER: " + event.getLocator().getLineNumber());
System.out.println("\n OFFSET: " + event.getLocator().getOffset());
System.out.println("\n CLASS: " + event.getLocator().getClass());
System.out.println("\n NODE: " + event.getLocator().getNode());
System.out.println("\n OBJECT: " + event.getLocator().getObject());
System.out.println("\n URL: " + event.getLocator().getURL());
eventOccurred = true;
// Allow more parsing feedback
return true;
}
public boolean eventOccurred() {
return eventOccurred;
}
}
| papegaaij/jsr-352 | JSR352.JobXML.Model/src/main/java/com/ibm/jbatch/jsl/util/JSLValidationEventHandler.java | Java | apache-2.0 | 2,107 |
---
layout: post
title: Underperformance of Lenovo ThinkBook Intel i7-8565U with Windows 10 pro
date: 2021-07-07
type: post
published: true
status: publish
categories: [travel]
tags:
author:
login: MiguelGamboa
email:
display_name: Miguel Gamboa
---
The stack Lenovo-Intel-Win10 is a completely rubbish for remote software developer work. Other guys with the same CPU and Windows 10 on different brand laptops have no breaks of performance as I am experiencing in my laptop.
Simply put, every time I am working with Zoom or Skype my CPU stays limited to 0.39GHz! After a while it returns to normality, as you can observe in next screen shots during and after a CPU break.
<img src="/assets/lenovo-i7-CPU-0.39ghz.png" width="300px">
<img src="/assets/lenovo-i7-CPU-4.02ghz.png" width="300px"> | fmcarvalho/fmcarvalho.github.io | _posts/2021-07-07-lenovo-thinkbook-rubbish.markdown | Markdown | apache-2.0 | 805 |
# -*- coding: utf-8 -*-
import unittest
import pykintone
from pykintone.model import kintoneModel
import tests.envs as envs
class TestAppModelSimple(kintoneModel):
def __init__(self):
super(TestAppModelSimple, self).__init__()
self.my_key = ""
self.stringField = ""
class TestComment(unittest.TestCase):
def test_comment(self):
app = pykintone.load(envs.FILE_PATH).app()
model = TestAppModelSimple()
model.my_key = "comment_test"
model.stringField = "comment_test_now"
result = app.create(model)
self.assertTrue(result.ok) # confirm create the record to test comment
_record_id = result.record_id
# create comment
r_created = app.comment(_record_id).create("コメントのテスト")
self.assertTrue(r_created.ok)
# it requires Administrator user is registered in kintone
r_created_m = app.comment(_record_id).create("メンションのテスト", [("Administrator", "USER")])
self.assertTrue(r_created_m.ok)
# select comment
r_selected = app.comment(_record_id).select(True, 0, 10)
self.assertTrue(r_selected.ok)
self.assertTrue(2, len(r_selected.raw_comments))
comments = r_selected.comments()
self.assertTrue(1, len(comments[-1].mentions))
# delete comment
for c in comments:
r_deleted = app.comment(_record_id).delete(c.comment_id)
self.assertTrue(r_deleted.ok)
r_selected = app.comment(_record_id).select()
self.assertEqual(0, len(r_selected.raw_comments))
# done test
app.delete(_record_id)
| icoxfog417/pykintone | tests/test_comment.py | Python | apache-2.0 | 1,667 |
package com.iclockwork.percy.wechat4j;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/**
* HelloWorldTest
*
* @author: fengwang
* @date: 2016/3/9 13:40
* @version: 1.0
* @since: JDK 1.7
*/
public class HelloWorldTest {
/**
* helloworld
*/
private HelloWorld helloworld;
@BeforeMethod
public void setUp() throws Exception {
helloworld = new HelloWorld();
}
@AfterMethod
public void tearDown() throws Exception {
}
@Test
public void testHello() throws Exception {
helloworld.hello();
}
}
| iclockwork/percy | wechat4j/src/test/java/com/iclockwork/percy/wechat4j/HelloWorldTest.java | Java | apache-2.0 | 646 |
/*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// buildifier defines a Prow plugin that runs buildifier over modified BUILD,
// WORKSPACE, and skylark (.bzl) files in pull requests.
package buildifier
import (
"bytes"
"fmt"
"io/ioutil"
"path/filepath"
"regexp"
"sort"
"strings"
"time"
"github.com/bazelbuild/buildtools/build"
"github.com/sirupsen/logrus"
"k8s.io/test-infra/prow/genfiles"
"k8s.io/test-infra/prow/git"
"k8s.io/test-infra/prow/github"
"k8s.io/test-infra/prow/pluginhelp"
"k8s.io/test-infra/prow/plugins"
)
const (
pluginName = "buildifier"
maxComments = 20
)
var buildifyRe = regexp.MustCompile(`(?mi)^/buildif(y|ier)\s*$`)
func init() {
plugins.RegisterGenericCommentHandler(pluginName, handleGenericComment, nil)
}
func helpProvider(config *plugins.Configuration, enabledRepos []string) (*pluginhelp.PluginHelp, error) {
// The Config field is omitted because this plugin is not configurable.
pluginHelp := &pluginhelp.PluginHelp{
Description: "The buildifier plugin runs buildifier on changes made to Bazel files in a PR. It then creates a new review on the pull request and leaves warnings at the appropriate lines of code.",
}
pluginHelp.AddCommand(pluginhelp.Command{
Usage: "/buildif(y|ier)",
Featured: false,
Description: "Runs buildifier on changes made to Bazel files in a PR",
WhoCanUse: "Anyone can trigger this command on a PR.",
Examples: []string{"/buildify", "/buildifier"},
})
return pluginHelp, nil
}
type githubClient interface {
GetFile(org, repo, filepath, commit string) ([]byte, error)
GetPullRequest(org, repo string, number int) (*github.PullRequest, error)
GetPullRequestChanges(org, repo string, number int) ([]github.PullRequestChange, error)
CreateReview(org, repo string, number int, r github.DraftReview) error
ListPullRequestComments(org, repo string, number int) ([]github.ReviewComment, error)
}
func handleGenericComment(pc plugins.Agent, e github.GenericCommentEvent) error {
return handle(pc.GitHubClient, pc.GitClient, pc.Logger, &e)
}
// modifiedBazelFiles returns a map from filename to patch string for all Bazel files
// that are modified in the PR.
func modifiedBazelFiles(ghc githubClient, org, repo string, number int, sha string) (map[string]string, error) {
changes, err := ghc.GetPullRequestChanges(org, repo, number)
if err != nil {
return nil, err
}
gfg, err := genfiles.NewGroup(ghc, org, repo, sha)
if err != nil {
return nil, err
}
modifiedFiles := make(map[string]string)
for _, change := range changes {
switch {
case gfg.Match(change.Filename):
continue
case change.Status == github.PullRequestFileRemoved || change.Status == github.PullRequestFileRenamed:
continue
// This also happens to match BUILD.bazel.
case strings.Contains(change.Filename, "BUILD"):
break
case strings.Contains(change.Filename, "WORKSPACE"):
break
case filepath.Ext(change.Filename) != ".bzl":
continue
}
modifiedFiles[change.Filename] = change.Patch
}
return modifiedFiles, nil
}
func uniqProblems(problems []string) []string {
sort.Strings(problems)
var uniq []string
last := ""
for _, s := range problems {
if s != last {
last = s
uniq = append(uniq, s)
}
}
return uniq
}
// problemsInFiles runs buildifier on the files. It returns a map from the file to
// a list of problems with that file.
func problemsInFiles(r *git.Repo, files map[string]string) (map[string][]string, error) {
problems := make(map[string][]string)
for f := range files {
src, err := ioutil.ReadFile(filepath.Join(r.Dir, f))
if err != nil {
return nil, err
}
// This is modeled after the logic from buildifier:
// https://github.com/bazelbuild/buildtools/blob/8818289/buildifier/buildifier.go#L261
content, err := build.Parse(f, src)
if err != nil {
return nil, fmt.Errorf("parsing as Bazel file %v", err)
}
beforeRewrite := build.Format(content)
var info build.RewriteInfo
build.Rewrite(content, &info)
ndata := build.Format(content)
if !bytes.Equal(src, ndata) && !bytes.Equal(src, beforeRewrite) {
// TODO(mattmoor): This always seems to be empty?
problems[f] = uniqProblems(info.Log)
}
}
return problems, nil
}
func handle(ghc githubClient, gc *git.Client, log *logrus.Entry, e *github.GenericCommentEvent) error {
// Only handle open PRs and new requests.
if e.IssueState != "open" || !e.IsPR || e.Action != github.GenericCommentActionCreated {
return nil
}
if !buildifyRe.MatchString(e.Body) {
return nil
}
org := e.Repo.Owner.Login
repo := e.Repo.Name
pr, err := ghc.GetPullRequest(org, repo, e.Number)
if err != nil {
return err
}
// List modified files.
modifiedFiles, err := modifiedBazelFiles(ghc, org, repo, pr.Number, pr.Head.SHA)
if err != nil {
return err
}
if len(modifiedFiles) == 0 {
return nil
}
log.Infof("Will buildify %d modified Bazel files.", len(modifiedFiles))
// Clone the repo, checkout the PR.
startClone := time.Now()
r, err := gc.Clone(e.Repo.FullName)
if err != nil {
return err
}
defer func() {
if err := r.Clean(); err != nil {
log.WithError(err).Error("Error cleaning up repo.")
}
}()
if err := r.CheckoutPullRequest(e.Number); err != nil {
return err
}
finishClone := time.Now()
log.WithField("duration", time.Since(startClone)).Info("Cloned and checked out PR.")
// Compute buildifier errors.
problems, err := problemsInFiles(r, modifiedFiles)
if err != nil {
return err
}
log.WithField("duration", time.Since(finishClone)).Info("Buildified.")
// Make the list of comments.
var comments []github.DraftReviewComment
for f := range problems {
comments = append(comments, github.DraftReviewComment{
Path: f,
// TODO(mattmoor): Include the messages if they are ever non-empty.
Body: strings.Join([]string{
"This Bazel file needs formatting, run:",
"```shell",
fmt.Sprintf("buildifier -mode=fix %q", f),
"```"}, "\n"),
Position: 1,
})
}
// Trim down the number of comments if necessary.
totalProblems := len(problems)
// Make the review body.
s := "s"
if totalProblems == 1 {
s = ""
}
response := fmt.Sprintf("%d warning%s.", totalProblems, s)
return ghc.CreateReview(org, repo, e.Number, github.DraftReview{
Body: plugins.FormatResponseRaw(e.Body, e.HTMLURL, e.User.Login, response),
Action: github.Comment,
Comments: comments,
})
}
| kargakis/test-infra | prow/plugins/buildifier/buildifier.go | GO | apache-2.0 | 6,914 |
#!/bin/bash
# Copyright 2016 Nitor Creations Oy
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
if [ "$_ARGCOMPLETE" ]; then
# Handle command completion executions
unset _ARGCOMPLETE
source $(n-include autocomplete-helpers.sh)
case $COMP_CWORD in
2)
if [ "$COMP_INDEX" = "$COMP_CWORD" ]; then
DRY="-d "
fi
compgen -W "$DRY-h $(get_stack_dirs)" -- $COMP_CUR
;;
3)
compgen -W "$(get_serverless $COMP_PREV)" -- $COMP_CUR
;;
*)
exit 1
;;
esac
exit 0
fi
usage() {
echo "usage: ndt deploy-serverless [-d] [-h] component serverless-name" >&2
echo "" >&2
echo "Exports ndt parameters into component/serverless-name/variables.yml, runs npm i in the" >&2
echo "serverless project and runs sls deploy -s \$paramEnvId for the same" >&2
echo "" >&2
echo "positional arguments:" >&2
echo " component the component directory where the serverless directory is" >&2
echo " serverless-name the name of the serverless directory that has the template" >&2
echo " For example for lambda/serverless-sender/template.yaml" >&2
echo " you would give sender" >&2
echo "" >&2
echo "optional arguments:" >&2
echo " -d, --dryrun dry-run - do only parameter expansion and template pre-processing and npm i" >&2
echo " -h, --help show this help message and exit" >&2
if "$@"; then
echo "" >&2
echo "$@" >&2
fi
exit 1
}
if [ "$1" = "--help" -o "$1" = "-h" ]; then
usage
fi
if [ "$1" = "-d" -o "$1" = "--dryrun" ]; then
DRYRUN=1
shift
fi
die () {
echo "$1" >&2
usage
}
set -xe
component="$1" ; shift
[ "${component}" ] || die "You must give the component name as argument"
serverless="$1"; shift
[ "${serverless}" ] || die "You must give the serverless name as argument"
TSTAMP=$(date +%Y%m%d%H%M%S)
if [ -z "$BUILD_NUMBER" ]; then
BUILD_NUMBER=$TSTAMP
else
BUILD_NUMBER=$(printf "%04d\n" $BUILD_NUMBER)
fi
eval "$(ndt load-parameters "$component" -l "$serverless" -e -r)"
#If assume-deploy-role.sh is on the path, run it to assume the appropriate role for deployment
if [ -n "$DEPLOY_ROLE_ARN" ] && [ -z "$AWS_SESSION_TOKEN" ]; then
eval $(ndt assume-role $DEPLOY_ROLE_ARN)
elif which assume-deploy-role.sh > /dev/null && [ -z "$AWS_SESSION_TOKEN" ]; then
eval $(assume-deploy-role.sh)
fi
ndt load-parameters "$component" -l "$serverless" -y -r > "$component/serverless-$ORIG_SERVERLESS_NAME/variables.yml"
ndt yaml-to-yaml "$component/serverless-$ORIG_SERVERLESS_NAME/template.yaml" > "$component/serverless-$ORIG_SERVERLESS_NAME/serverless.yml"
cd "$component/serverless-$ORIG_SERVERLESS_NAME"
if [ -x "./pre_deploy.sh" ]; then
"./pre_deploy.sh"
fi
if [ -z "$SKIP_NPM" -o "$SKIP_NPM" = "n" ]; then
npm i
fi
if [ -n "$DRYRUN" ]; then
exit 0
fi
sls deploy -s $paramEnvId | NitorCreations/nitor-deploy-tools | n_utils/includes/deploy-serverless.sh | Shell | apache-2.0 | 3,341 |
package com.scicrop.se.commons.utils;
import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.RollingFileAppender;
public class LogHelper {
private LogHelper(){}
private static LogHelper INSTANCE = null;
public static LogHelper getInstance(){
if(INSTANCE == null) INSTANCE = new LogHelper();
return INSTANCE;
}
public void setLogger(String logNamePattern, String logFolder){
String logPath = logFolder + Constants.APP_NAME+"_"+logNamePattern+".log";
Logger rootLogger = Logger.getRootLogger();
rootLogger.setLevel(Level.INFO);
PatternLayout layout = new PatternLayout("%d{ISO8601} [%t] %-5p %c %x - %m%n");
rootLogger.addAppender(new ConsoleAppender(layout));
try {
RollingFileAppender fileAppender = new RollingFileAppender(layout, logPath);
rootLogger.addAppender(fileAppender);
} catch (IOException e) {
System.err.println("Failed to find/access "+logPath+" !");
System.exit(1);
}
}
public void handleVerboseLog(boolean isVerbose, boolean isLog, Log log, char type, String data){
if(isLog){
logData(data, type, log);
}
if(isVerbose){
verbose(data, type);
}
}
public void logData(String data, char type, Log log){
switch (type) {
case 'i':
log.info(data);
break;
case 'w':
log.warn(data);
break;
case 'e':
log.error(data);
break;
default:
log.info(data);
break;
}
}
public void verbose(String data, char type){
switch (type) {
case 'e':
System.err.println(data);
break;
default:
System.out.println(data);
break;
}
}
}
| Scicrop/sentinel-extractor | source-code/sentinel-extractor-commons/src/com/scicrop/se/commons/utils/LogHelper.java | Java | apache-2.0 | 1,743 |
function Add-VSWAFv2RuleGroupCountAction {
<#
.SYNOPSIS
Adds an AWS::WAFv2::RuleGroup.CountAction resource property to the template.
.DESCRIPTION
Adds an AWS::WAFv2::RuleGroup.CountAction resource property to the template.
.LINK
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafv2-rulegroup-countaction.html
.FUNCTIONALITY
Vaporshell
#>
[OutputType('Vaporshell.Resource.WAFv2.RuleGroup.CountAction')]
[cmdletbinding()]
Param
(
)
Begin {
$obj = [PSCustomObject]@{}
$commonParams = @('Verbose','Debug','ErrorAction','WarningAction','InformationAction','ErrorVariable','WarningVariable','InformationVariable','OutVariable','OutBuffer','PipelineVariable')
}
Process {
foreach ($key in $PSBoundParameters.Keys | Where-Object {$commonParams -notcontains $_}) {
switch ($key) {
Default {
$obj | Add-Member -MemberType NoteProperty -Name $key -Value $PSBoundParameters.$key
}
}
}
}
End {
$obj | Add-ObjectDetail -TypeName 'Vaporshell.Resource.WAFv2.RuleGroup.CountAction'
Write-Verbose "Resulting JSON from $($MyInvocation.MyCommand): `n`n$($obj | ConvertTo-Json -Depth 5)`n"
}
}
| scrthq/Vaporshell | VaporShell/Public/Resource Property Types/Add-VSWAFv2RuleGroupCountAction.ps1 | PowerShell | apache-2.0 | 1,332 |
// Copyright 2015 Thomas Trapp
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef HTMLEXT_FILE_H_INCLUDED
#define HTMLEXT_FILE_H_INCLUDED
#include <string>
#include <stdexcept>
namespace htmlext {
/// Custom exception type for file errors.
class FileError : public std::runtime_error
{
public:
explicit FileError(const std::string& msg) noexcept;
};
/// Read file at path to buffer. Throws FileError on failure.
/// Can read regular files as well as named pipes.
std::string ReadFileOrThrow(const std::string& path);
} // namespace htmlext
#endif // HTMLEXT_FILE_H_INCLUDED
| thomastrapp/hext | htmlext/htmlext/File.h | C | apache-2.0 | 1,104 |
# -*- coding: utf-8 -*-
'''
The Salt Key backend API and interface used by the CLI. The Key class can be
used to manage salt keys directly without interfacing with the CLI.
'''
# Import python libs
from __future__ import absolute_import, print_function
import os
import copy
import json
import stat
import shutil
import fnmatch
import hashlib
import logging
# Import salt libs
import salt.crypt
import salt.utils
import salt.exceptions
import salt.utils.event
import salt.daemons.masterapi
from salt.utils import kinds
from salt.utils.event import tagify
# Import third party libs
# pylint: disable=import-error,no-name-in-module,redefined-builtin
import salt.ext.six as six
from salt.ext.six.moves import input
# pylint: enable=import-error,no-name-in-module,redefined-builtin
try:
import msgpack
except ImportError:
pass
log = logging.getLogger(__name__)
def get_key(opts):
if opts['transport'] in ('zeromq', 'tcp'):
return Key(opts)
else:
return RaetKey(opts)
class KeyCLI(object):
'''
Manage key CLI operations
'''
def __init__(self, opts):
self.opts = opts
if self.opts['transport'] in ('zeromq', 'tcp'):
self.key = Key(opts)
else:
self.key = RaetKey(opts)
def list_status(self, status):
'''
Print out the keys under a named status
:param str status: A string indicating which set of keys to return
'''
keys = self.key.list_keys()
if status.startswith('acc'):
salt.output.display_output(
{self.key.ACC: keys[self.key.ACC]},
'key',
self.opts
)
elif status.startswith(('pre', 'un')):
salt.output.display_output(
{self.key.PEND: keys[self.key.PEND]},
'key',
self.opts
)
elif status.startswith('rej'):
salt.output.display_output(
{self.key.REJ: keys[self.key.REJ]},
'key',
self.opts
)
elif status.startswith('den'):
if self.key.DEN:
salt.output.display_output(
{self.key.DEN: keys[self.key.DEN]},
'key',
self.opts
)
elif status.startswith('all'):
self.list_all()
def list_all(self):
'''
Print out all keys
'''
salt.output.display_output(
self.key.list_keys(),
'key',
self.opts)
def accept(self, match, include_rejected=False):
'''
Accept the keys matched
:param str match: A string to match against. i.e. 'web*'
:param bool include_rejected: Whether or not to accept a matched key that was formerly rejected
'''
def _print_accepted(matches, after_match):
if self.key.ACC in after_match:
accepted = sorted(
set(after_match[self.key.ACC]).difference(
set(matches.get(self.key.ACC, []))
)
)
for key in accepted:
print('Key for minion {0} accepted.'.format(key))
matches = self.key.name_match(match)
keys = {}
if self.key.PEND in matches:
keys[self.key.PEND] = matches[self.key.PEND]
if include_rejected and bool(matches.get(self.key.REJ)):
keys[self.key.REJ] = matches[self.key.REJ]
if not keys:
msg = (
'The key glob {0!r} does not match any unaccepted {1}keys.'
.format(match, 'or rejected ' if include_rejected else '')
)
print(msg)
raise salt.exceptions.SaltSystemExit(code=1)
if not self.opts.get('yes', False):
print('The following keys are going to be accepted:')
salt.output.display_output(
keys,
'key',
self.opts)
try:
veri = input('Proceed? [n/Y] ')
except KeyboardInterrupt:
raise SystemExit("\nExiting on CTRL-c")
if not veri or veri.lower().startswith('y'):
_print_accepted(
matches,
self.key.accept(
match_dict=keys,
include_rejected=include_rejected
)
)
else:
print('The following keys are going to be accepted:')
salt.output.display_output(
keys,
'key',
self.opts)
_print_accepted(
matches,
self.key.accept(
match_dict=keys,
include_rejected=include_rejected
)
)
def accept_all(self, include_rejected=False):
'''
Accept all keys
:param bool include_rejected: Whether or not to accept a matched key that was formerly rejected
'''
self.accept('*', include_rejected=include_rejected)
def delete(self, match):
'''
Delete the matched keys
:param str match: A string to match against. i.e. 'web*'
'''
def _print_deleted(matches, after_match):
deleted = []
for keydir in (self.key.ACC, self.key.PEND, self.key.REJ):
deleted.extend(list(
set(matches.get(keydir, [])).difference(
set(after_match.get(keydir, []))
)
))
for key in sorted(deleted):
print('Key for minion {0} deleted.'.format(key))
matches = self.key.name_match(match)
if not matches:
print(
'The key glob {0!r} does not match any accepted, unaccepted '
'or rejected keys.'.format(match)
)
raise salt.exceptions.SaltSystemExit(code=1)
if not self.opts.get('yes', False):
print('The following keys are going to be deleted:')
salt.output.display_output(
matches,
'key',
self.opts)
try:
veri = input('Proceed? [N/y] ')
except KeyboardInterrupt:
raise SystemExit("\nExiting on CTRL-c")
if veri.lower().startswith('y'):
_print_deleted(
matches,
self.key.delete_key(match_dict=matches)
)
else:
print('Deleting the following keys:')
salt.output.display_output(
matches,
'key',
self.opts)
_print_deleted(
matches,
self.key.delete_key(match_dict=matches)
)
def delete_all(self):
'''
Delete all keys
'''
self.delete('*')
def reject(self, match, include_accepted=False):
'''
Reject the matched keys
:param str match: A string to match against. i.e. 'web*'
:param bool include_accepted: Whether or not to accept a matched key that was formerly accepted
'''
def _print_rejected(matches, after_match):
if self.key.REJ in after_match:
rejected = sorted(
set(after_match[self.key.REJ]).difference(
set(matches.get(self.key.REJ, []))
)
)
for key in rejected:
print('Key for minion {0} rejected.'.format(key))
matches = self.key.name_match(match)
keys = {}
if self.key.PEND in matches:
keys[self.key.PEND] = matches[self.key.PEND]
if include_accepted and bool(matches.get(self.key.ACC)):
keys[self.key.ACC] = matches[self.key.ACC]
if not keys:
msg = 'The key glob {0!r} does not match any {1} keys.'.format(
match,
'accepted or unaccepted' if include_accepted else 'unaccepted'
)
print(msg)
return
if not self.opts.get('yes', False):
print('The following keys are going to be rejected:')
salt.output.display_output(
keys,
'key',
self.opts)
veri = input('Proceed? [n/Y] ')
if veri.lower().startswith('n'):
return
_print_rejected(
matches,
self.key.reject(
match_dict=matches,
include_accepted=include_accepted
)
)
def reject_all(self, include_accepted=False):
'''
Reject all keys
:param bool include_accepted: Whether or not to accept a matched key that was formerly accepted
'''
self.reject('*', include_accepted=include_accepted)
def print_key(self, match):
'''
Print out a single key
:param str match: A string to match against. i.e. 'web*'
'''
matches = self.key.key_str(match)
salt.output.display_output(
matches,
'key',
self.opts)
def print_all(self):
'''
Print out all managed keys
'''
self.print_key('*')
def finger(self, match):
'''
Print out the fingerprints for the matched keys
:param str match: A string to match against. i.e. 'web*'
'''
matches = self.key.finger(match)
salt.output.display_output(
matches,
'key',
self.opts)
def finger_all(self):
'''
Print out all fingerprints
'''
matches = self.key.finger('*')
salt.output.display_output(
matches,
'key',
self.opts)
def prep_signature(self):
'''
Searches for usable keys to create the
master public-key signature
'''
self.privkey = None
self.pubkey = None
# check given pub-key
if self.opts['pub']:
if not os.path.isfile(self.opts['pub']):
print('Public-key {0} does not exist'.format(self.opts['pub']))
return
self.pubkey = self.opts['pub']
# default to master.pub
else:
mpub = self.opts['pki_dir'] + '/' + 'master.pub'
if os.path.isfile(mpub):
self.pubkey = mpub
# check given priv-key
if self.opts['priv']:
if not os.path.isfile(self.opts['priv']):
print('Private-key {0} does not exist'.format(self.opts['priv']))
return
self.privkey = self.opts['priv']
# default to master_sign.pem
else:
mpriv = self.opts['pki_dir'] + '/' + 'master_sign.pem'
if os.path.isfile(mpriv):
self.privkey = mpriv
if not self.privkey:
if self.opts['auto_create']:
print('Generating new signing key-pair {0}.* in {1}'
''.format(self.opts['master_sign_key_name'],
self.opts['pki_dir']))
salt.crypt.gen_keys(self.opts['pki_dir'],
self.opts['master_sign_key_name'],
self.opts['keysize'],
self.opts.get('user'))
self.privkey = self.opts['pki_dir'] + '/' + self.opts['master_sign_key_name'] + '.pem'
else:
print('No usable private-key found')
return
if not self.pubkey:
print('No usable public-key found')
return
print('Using public-key {0}'.format(self.pubkey))
print('Using private-key {0}'.format(self.privkey))
if self.opts['signature_path']:
if not os.path.isdir(self.opts['signature_path']):
print('target directory {0} does not exist'
''.format(self.opts['signature_path']))
else:
self.opts['signature_path'] = self.opts['pki_dir']
sign_path = self.opts['signature_path'] + '/' + self.opts['master_pubkey_signature']
self.key.gen_signature(self.privkey,
self.pubkey,
sign_path)
def run(self):
'''
Run the logic for saltkey
'''
if self.opts['gen_keys']:
self.key.gen_keys()
return
elif self.opts['gen_signature']:
self.prep_signature()
return
if self.opts['list']:
self.list_status(self.opts['list'])
elif self.opts['list_all']:
self.list_all()
elif self.opts['print']:
self.print_key(self.opts['print'])
elif self.opts['print_all']:
self.print_all()
elif self.opts['accept']:
self.accept(
self.opts['accept'],
include_rejected=self.opts['include_all']
)
elif self.opts['accept_all']:
self.accept_all(include_rejected=self.opts['include_all'])
elif self.opts['reject']:
self.reject(
self.opts['reject'],
include_accepted=self.opts['include_all']
)
elif self.opts['reject_all']:
self.reject_all(include_accepted=self.opts['include_all'])
elif self.opts['delete']:
self.delete(self.opts['delete'])
elif self.opts['delete_all']:
self.delete_all()
elif self.opts['finger']:
self.finger(self.opts['finger'])
elif self.opts['finger_all']:
self.finger_all()
else:
self.list_all()
class MultiKeyCLI(KeyCLI):
'''
Manage multiple key backends from the CLI
'''
def __init__(self, opts):
opts['__multi_key'] = True
super(MultiKeyCLI, self).__init__(opts)
# Remove the key attribute set in KeyCLI.__init__
delattr(self, 'key')
zopts = copy.copy(opts)
ropts = copy.copy(opts)
self.keys = {}
zopts['transport'] = 'zeromq'
self.keys['ZMQ Keys'] = KeyCLI(zopts)
ropts['transport'] = 'raet'
self.keys['RAET Keys'] = KeyCLI(ropts)
def _call_all(self, fun, *args):
'''
Call the given function on all backend keys
'''
for kback in self.keys:
print(kback)
getattr(self.keys[kback], fun)(*args)
def list_status(self, status):
self._call_all('list_status', status)
def list_all(self):
self._call_all('list_all')
def accept(self, match, include_rejected=False):
self._call_all('accept', match, include_rejected)
def accept_all(self, include_rejected=False):
self._call_all('accept_all', include_rejected)
def delete(self, match):
self._call_all('delete', match)
def delete_all(self):
self._call_all('delete_all')
def reject(self, match, include_accepted=False):
self._call_all('reject', match, include_accepted)
def reject_all(self, include_accepted=False):
self._call_all('reject_all', include_accepted)
def print_key(self, match):
self._call_all('print_key', match)
def print_all(self):
self._call_all('print_all')
def finger(self, match):
self._call_all('finger', match)
def finger_all(self):
self._call_all('finger_all')
def prep_signature(self):
self._call_all('prep_signature')
class Key(object):
'''
The object that encapsulates saltkey actions
'''
ACC = 'minions'
PEND = 'minions_pre'
REJ = 'minions_rejected'
DEN = 'minions_denied'
def __init__(self, opts):
self.opts = opts
kind = self.opts.get('__role', '') # application kind
if kind not in kinds.APPL_KINDS:
emsg = ("Invalid application kind = '{0}'.".format(kind))
log.error(emsg + '\n')
raise ValueError(emsg)
self.event = salt.utils.event.get_event(
kind,
opts['sock_dir'],
opts['transport'],
opts=opts,
listen=False)
def _check_minions_directories(self):
'''
Return the minion keys directory paths
'''
minions_accepted = os.path.join(self.opts['pki_dir'], self.ACC)
minions_pre = os.path.join(self.opts['pki_dir'], self.PEND)
minions_rejected = os.path.join(self.opts['pki_dir'],
self.REJ)
minions_denied = os.path.join(self.opts['pki_dir'],
self.DEN)
return minions_accepted, minions_pre, minions_rejected, minions_denied
def gen_keys(self):
'''
Generate minion RSA public keypair
'''
salt.crypt.gen_keys(
self.opts['gen_keys_dir'],
self.opts['gen_keys'],
self.opts['keysize'])
return
def gen_signature(self, privkey, pubkey, sig_path):
'''
Generate master public-key-signature
'''
return salt.crypt.gen_signature(privkey,
pubkey,
sig_path)
def check_minion_cache(self, preserve_minions=None):
'''
Check the minion cache to make sure that old minion data is cleared
Optionally, pass in a list of minions which should have their caches
preserved. To preserve all caches, set __opts__['preserve_minion_cache']
'''
if preserve_minions is None:
preserve_minions = []
m_cache = os.path.join(self.opts['cachedir'], self.ACC)
if not os.path.isdir(m_cache):
return
keys = self.list_keys()
minions = []
for key, val in six.iteritems(keys):
minions.extend(val)
if not self.opts.get('preserve_minion_cache', False) or not preserve_minions:
for minion in os.listdir(m_cache):
if minion not in minions and minion not in preserve_minions:
shutil.rmtree(os.path.join(m_cache, minion))
def check_master(self):
'''
Log if the master is not running
:rtype: bool
:return: Whether or not the master is running
'''
if not os.path.exists(
os.path.join(
self.opts['sock_dir'],
'publish_pull.ipc'
)
):
return False
return True
def name_match(self, match, full=False):
'''
Accept a glob which to match the of a key and return the key's location
'''
if full:
matches = self.all_keys()
else:
matches = self.list_keys()
ret = {}
if ',' in match and isinstance(match, str):
match = match.split(',')
for status, keys in six.iteritems(matches):
for key in salt.utils.isorted(keys):
if isinstance(match, list):
for match_item in match:
if fnmatch.fnmatch(key, match_item):
if status not in ret:
ret[status] = []
ret[status].append(key)
else:
if fnmatch.fnmatch(key, match):
if status not in ret:
ret[status] = []
ret[status].append(key)
return ret
def dict_match(self, match_dict):
'''
Accept a dictionary of keys and return the current state of the
specified keys
'''
ret = {}
cur_keys = self.list_keys()
for status, keys in six.iteritems(match_dict):
for key in salt.utils.isorted(keys):
for keydir in (self.ACC, self.PEND, self.REJ, self.DEN):
if keydir and fnmatch.filter(cur_keys.get(keydir, []), key):
ret.setdefault(keydir, []).append(key)
return ret
def local_keys(self):
'''
Return a dict of local keys
'''
ret = {'local': []}
for fn_ in salt.utils.isorted(os.listdir(self.opts['pki_dir'])):
if fn_.endswith('.pub') or fn_.endswith('.pem'):
path = os.path.join(self.opts['pki_dir'], fn_)
if os.path.isfile(path):
ret['local'].append(fn_)
return ret
def list_keys(self):
'''
Return a dict of managed keys and what the key status are
'''
key_dirs = []
# We have to differentiate between RaetKey._check_minions_directories
# and Zeromq-Keys. Raet-Keys only have three states while ZeroMQ-keys
# havd an additional 'denied' state.
if self.opts['transport'] in ('zeromq', 'tcp'):
key_dirs = self._check_minions_directories()
else:
key_dirs = self._check_minions_directories()
ret = {}
for dir_ in key_dirs:
ret[os.path.basename(dir_)] = []
try:
for fn_ in salt.utils.isorted(os.listdir(dir_)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(dir_, fn_)):
ret[os.path.basename(dir_)].append(fn_)
except (OSError, IOError):
# key dir kind is not created yet, just skip
continue
return ret
def all_keys(self):
'''
Merge managed keys with local keys
'''
keys = self.list_keys()
keys.update(self.local_keys())
return keys
def list_status(self, match):
'''
Return a dict of managed keys under a named status
'''
acc, pre, rej, den = self._check_minions_directories()
ret = {}
if match.startswith('acc'):
ret[os.path.basename(acc)] = []
for fn_ in salt.utils.isorted(os.listdir(acc)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(acc, fn_)):
ret[os.path.basename(acc)].append(fn_)
elif match.startswith('pre') or match.startswith('un'):
ret[os.path.basename(pre)] = []
for fn_ in salt.utils.isorted(os.listdir(pre)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(pre, fn_)):
ret[os.path.basename(pre)].append(fn_)
elif match.startswith('rej'):
ret[os.path.basename(rej)] = []
for fn_ in salt.utils.isorted(os.listdir(rej)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(rej, fn_)):
ret[os.path.basename(rej)].append(fn_)
elif match.startswith('den'):
ret[os.path.basename(den)] = []
for fn_ in salt.utils.isorted(os.listdir(den)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(den, fn_)):
ret[os.path.basename(den)].append(fn_)
elif match.startswith('all'):
return self.all_keys()
return ret
def key_str(self, match):
'''
Return the specified public key or keys based on a glob
'''
ret = {}
for status, keys in six.iteritems(self.name_match(match)):
ret[status] = {}
for key in salt.utils.isorted(keys):
path = os.path.join(self.opts['pki_dir'], status, key)
with salt.utils.fopen(path, 'r') as fp_:
ret[status][key] = fp_.read()
return ret
def key_str_all(self):
'''
Return all managed key strings
'''
ret = {}
for status, keys in six.iteritems(self.list_keys()):
ret[status] = {}
for key in salt.utils.isorted(keys):
path = os.path.join(self.opts['pki_dir'], status, key)
with salt.utils.fopen(path, 'r') as fp_:
ret[status][key] = fp_.read()
return ret
def accept(self, match=None, match_dict=None, include_rejected=False):
'''
Accept public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_rejected:
keydirs.append(self.REJ)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
eload = {'result': True,
'act': 'accept',
'id': key}
self.event.fire_event(eload, tagify(prefix='key'))
except (IOError, OSError):
pass
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def accept_all(self):
'''
Accept all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
eload = {'result': True,
'act': 'accept',
'id': key}
self.event.fire_event(eload, tagify(prefix='key'))
except (IOError, OSError):
pass
return self.list_keys()
def delete_key(self, match=None, match_dict=None, preserve_minions=False):
'''
Delete public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
To preserve the master caches of minions who are matched, set preserve_minions
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
for status, keys in six.iteritems(matches):
for key in keys:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload, tagify(prefix='key'))
except (OSError, IOError):
pass
self.check_minion_cache(preserve_minions=matches.get('minions', []))
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def delete_all(self):
'''
Delete all keys
'''
for status, keys in six.iteritems(self.list_keys()):
for key in keys:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload, tagify(prefix='key'))
except (OSError, IOError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return self.list_keys()
def reject(self, match=None, match_dict=None, include_accepted=False):
'''
Reject public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_accepted:
keydirs.append(self.ACC)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
eload = {'result': True,
'act': 'reject',
'id': key}
self.event.fire_event(eload, tagify(prefix='key'))
except (IOError, OSError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def reject_all(self):
'''
Reject all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
eload = {'result': True,
'act': 'reject',
'id': key}
self.event.fire_event(eload, tagify(prefix='key'))
except (IOError, OSError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return self.list_keys()
def finger(self, match):
'''
Return the fingerprint for a specified key
'''
matches = self.name_match(match, True)
ret = {}
for status, keys in six.iteritems(matches):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = salt.utils.pem_finger(path, sum_type=self.opts['hash_type'])
return ret
def finger_all(self):
'''
Return fingerprins for all keys
'''
ret = {}
for status, keys in six.iteritems(self.list_keys()):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = salt.utils.pem_finger(path, sum_type=self.opts['hash_type'])
return ret
class RaetKey(Key):
'''
Manage keys from the raet backend
'''
ACC = 'accepted'
PEND = 'pending'
REJ = 'rejected'
DEN = None
def __init__(self, opts):
Key.__init__(self, opts)
self.auto_key = salt.daemons.masterapi.AutoKey(self.opts)
self.serial = salt.payload.Serial(self.opts)
def _check_minions_directories(self):
'''
Return the minion keys directory paths
'''
accepted = os.path.join(self.opts['pki_dir'], self.ACC)
pre = os.path.join(self.opts['pki_dir'], self.PEND)
rejected = os.path.join(self.opts['pki_dir'], self.REJ)
return accepted, pre, rejected
def check_minion_cache(self, preserve_minions=False):
'''
Check the minion cache to make sure that old minion data is cleared
'''
keys = self.list_keys()
minions = []
for key, val in six.iteritems(keys):
minions.extend(val)
m_cache = os.path.join(self.opts['cachedir'], 'minions')
if os.path.isdir(m_cache):
for minion in os.listdir(m_cache):
if minion not in minions:
shutil.rmtree(os.path.join(m_cache, minion))
kind = self.opts.get('__role', '') # application kind
if kind not in kinds.APPL_KINDS:
emsg = ("Invalid application kind = '{0}'.".format(kind))
log.error(emsg + '\n')
raise ValueError(emsg)
role = self.opts.get('id', '')
if not role:
emsg = ("Invalid id.")
log.error(emsg + "\n")
raise ValueError(emsg)
name = "{0}_{1}".format(role, kind)
road_cache = os.path.join(self.opts['cachedir'],
'raet',
name,
'remote')
if os.path.isdir(road_cache):
for road in os.listdir(road_cache):
root, ext = os.path.splitext(road)
if ext not in ['.json', '.msgpack']:
continue
prefix, sep, name = root.partition('.')
if not name or prefix != 'estate':
continue
path = os.path.join(road_cache, road)
with salt.utils.fopen(path, 'rb') as fp_:
if ext == '.json':
data = json.load(fp_)
elif ext == '.msgpack':
data = msgpack.load(fp_)
if data['role'] not in minions:
os.remove(path)
def gen_keys(self):
'''
Use libnacl to generate and safely save a private key
'''
import libnacl.public
d_key = libnacl.dual.DualSecret()
path = '{0}.key'.format(os.path.join(
self.opts['gen_keys_dir'],
self.opts['gen_keys']))
d_key.save(path, 'msgpack')
def check_master(self):
'''
Log if the master is not running
NOT YET IMPLEMENTED
'''
return True
def local_keys(self):
'''
Return a dict of local keys
'''
ret = {'local': []}
fn_ = os.path.join(self.opts['pki_dir'], 'local.key')
if os.path.isfile(fn_):
ret['local'].append(fn_)
return ret
def status(self, minion_id, pub, verify):
'''
Accepts the minion id, device id, curve public and verify keys.
If the key is not present, put it in pending and return "pending",
If the key has been accepted return "accepted"
if the key should be rejected, return "rejected"
'''
acc, pre, rej = self._check_minions_directories() # pylint: disable=W0632
acc_path = os.path.join(acc, minion_id)
pre_path = os.path.join(pre, minion_id)
rej_path = os.path.join(rej, minion_id)
# open mode is turned on, force accept the key
keydata = {
'minion_id': minion_id,
'pub': pub,
'verify': verify}
if self.opts['open_mode']: # always accept and overwrite
with salt.utils.fopen(acc_path, 'w+b') as fp_:
fp_.write(self.serial.dumps(keydata))
return self.ACC
if os.path.isfile(rej_path):
log.debug("Rejection Reason: Keys already rejected.\n")
return self.REJ
elif os.path.isfile(acc_path):
# The minion id has been accepted, verify the key strings
with salt.utils.fopen(acc_path, 'rb') as fp_:
keydata = self.serial.loads(fp_.read())
if keydata['pub'] == pub and keydata['verify'] == verify:
return self.ACC
else:
log.debug("Rejection Reason: Keys not match prior accepted.\n")
return self.REJ
elif os.path.isfile(pre_path):
auto_reject = self.auto_key.check_autoreject(minion_id)
auto_sign = self.auto_key.check_autosign(minion_id)
with salt.utils.fopen(pre_path, 'rb') as fp_:
keydata = self.serial.loads(fp_.read())
if keydata['pub'] == pub and keydata['verify'] == verify:
if auto_reject:
self.reject(minion_id)
log.debug("Rejection Reason: Auto reject pended.\n")
return self.REJ
elif auto_sign:
self.accept(minion_id)
return self.ACC
return self.PEND
else:
log.debug("Rejection Reason: Keys not match prior pended.\n")
return self.REJ
# This is a new key, evaluate auto accept/reject files and place
# accordingly
auto_reject = self.auto_key.check_autoreject(minion_id)
auto_sign = self.auto_key.check_autosign(minion_id)
if self.opts['auto_accept']:
w_path = acc_path
ret = self.ACC
elif auto_sign:
w_path = acc_path
ret = self.ACC
elif auto_reject:
w_path = rej_path
log.debug("Rejection Reason: Auto reject new.\n")
ret = self.REJ
else:
w_path = pre_path
ret = self.PEND
with salt.utils.fopen(w_path, 'w+b') as fp_:
fp_.write(self.serial.dumps(keydata))
return ret
def _get_key_str(self, minion_id, status):
'''
Return the key string in the form of:
pub: <pub>
verify: <verify>
'''
path = os.path.join(self.opts['pki_dir'], status, minion_id)
with salt.utils.fopen(path, 'r') as fp_:
keydata = self.serial.loads(fp_.read())
return 'pub: {0}\nverify: {1}'.format(
keydata['pub'],
keydata['verify'])
def _get_key_finger(self, path):
'''
Return a sha256 kingerprint for the key
'''
with salt.utils.fopen(path, 'r') as fp_:
keydata = self.serial.loads(fp_.read())
key = 'pub: {0}\nverify: {1}'.format(
keydata['pub'],
keydata['verify'])
return hashlib.sha256(key).hexdigest()
def key_str(self, match):
'''
Return the specified public key or keys based on a glob
'''
ret = {}
for status, keys in six.iteritems(self.name_match(match)):
ret[status] = {}
for key in salt.utils.isorted(keys):
ret[status][key] = self._get_key_str(key, status)
return ret
def key_str_all(self):
'''
Return all managed key strings
'''
ret = {}
for status, keys in six.iteritems(self.list_keys()):
ret[status] = {}
for key in salt.utils.isorted(keys):
ret[status][key] = self._get_key_str(key, status)
return ret
def accept(self, match=None, match_dict=None, include_rejected=False):
'''
Accept public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_rejected:
keydirs.append(self.REJ)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
except (IOError, OSError):
pass
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def accept_all(self):
'''
Accept all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
except (IOError, OSError):
pass
return self.list_keys()
def delete_key(self, match=None, match_dict=None, preserve_minions=False):
'''
Delete public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
for status, keys in six.iteritems(matches):
for key in keys:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
except (OSError, IOError):
pass
self.check_minion_cache(preserve_minions=matches.get('minions', []))
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def delete_all(self):
'''
Delete all keys
'''
for status, keys in six.iteritems(self.list_keys()):
for key in keys:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
except (OSError, IOError):
pass
self.check_minion_cache()
return self.list_keys()
def reject(self, match=None, match_dict=None, include_accepted=False):
'''
Reject public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_accepted:
keydirs.append(self.ACC)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
except (IOError, OSError):
pass
self.check_minion_cache()
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def reject_all(self):
'''
Reject all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
except (IOError, OSError):
pass
self.check_minion_cache()
return self.list_keys()
def finger(self, match):
'''
Return the fingerprint for a specified key
'''
matches = self.name_match(match, True)
ret = {}
for status, keys in six.iteritems(matches):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = self._get_key_finger(path)
return ret
def finger_all(self):
'''
Return fingerprints for all keys
'''
ret = {}
for status, keys in six.iteritems(self.list_keys()):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = self._get_key_finger(path)
return ret
def read_all_remote(self):
'''
Return a dict of all remote key data
'''
data = {}
for status, mids in six.iteritems(self.list_keys()):
for mid in mids:
keydata = self.read_remote(mid, status)
if keydata:
keydata['acceptance'] = status
data[mid] = keydata
return data
def read_remote(self, minion_id, status=ACC):
'''
Read in a remote key of status
'''
path = os.path.join(self.opts['pki_dir'], status, minion_id)
if not os.path.isfile(path):
return {}
with salt.utils.fopen(path, 'rb') as fp_:
return self.serial.loads(fp_.read())
def read_local(self):
'''
Read in the local private keys, return an empy dict if the keys do not
exist
'''
path = os.path.join(self.opts['pki_dir'], 'local.key')
if not os.path.isfile(path):
return {}
with salt.utils.fopen(path, 'rb') as fp_:
return self.serial.loads(fp_.read())
def write_local(self, priv, sign):
'''
Write the private key and the signing key to a file on disk
'''
keydata = {'priv': priv,
'sign': sign}
path = os.path.join(self.opts['pki_dir'], 'local.key')
c_umask = os.umask(191)
if os.path.exists(path):
#mode = os.stat(path).st_mode
os.chmod(path, stat.S_IWUSR | stat.S_IRUSR)
with salt.utils.fopen(path, 'w+') as fp_:
fp_.write(self.serial.dumps(keydata))
os.chmod(path, stat.S_IRUSR)
os.umask(c_umask)
def delete_local(self):
'''
Delete the local private key file
'''
path = os.path.join(self.opts['pki_dir'], 'local.key')
if os.path.isfile(path):
os.remove(path)
def delete_pki_dir(self):
'''
Delete the private key directory
'''
path = self.opts['pki_dir']
if os.path.exists(path):
shutil.rmtree(path)
| smallyear/linuxLearn | salt/salt/key.py | Python | apache-2.0 | 48,988 |
/* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'chapter4-components',
environment: environment,
baseURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
},
contentSecurityPolicy: {
'default-src': "'none'",
'script-src': "'self' 'unsafe-inline' 'unsafe-eval' *",
'font-src': "'self' *",
'connect-src': "'self' *",
'img-src': "'self' *",
'style-src': "'self' 'unsafe-inline' *",
'frame-src': "*"
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
}
return ENV;
};
| ubuntuvim/my_emberjs_code | chapter4_components/config/environment.js | JavaScript | apache-2.0 | 1,376 |
require_relative '../lib/rails_stub'
require_relative 'lib/pb_core_ingester'
require_relative '../lib/has_logger'
require 'rake'
require_relative '../app/models/collection'
require_relative '../app/models/exhibit'
class Exception
def short
message + "\n" + backtrace[0..2].join("\n")
end
end
class ParamsError < StandardError
end
class Ingest
include HasLogger
def const_init(name)
const_name = name.upcase.tr('-', '_')
flag_name = "--#{name}"
begin
# to avoid "warning: already initialized constant" in tests.
Ingest.const_get(const_name)
rescue NameError
Ingest.const_set(const_name, flag_name)
end
end
def initialize(argv)
orig_argv = argv.dup
%w(files dirs grep-files grep-dirs).each do |name|
const_init(name)
end
%w(batch-commit stdout-log).each do |name|
flag_name = const_init(name)
variable_name = "@is_#{name.tr('-', '_')}"
instance_variable_set(variable_name, argv.include?(flag_name))
argv.delete(flag_name)
end
# The code above sets fields which log_init needs,
# but it also modifies argv in place, so we need the dup.
log_init!(orig_argv)
mode = argv.shift
args = argv
@flags = { is_just_reindex: @is_just_reindex }
begin
case mode
when DIRS
fail ParamsError.new if args.empty? || args.map { |dir| !File.directory?(dir) }.any?
target_dirs = args
when FILES
fail ParamsError.new if args.empty?
@files = args
when GREP_DIRS
fail ParamsError.new if args.empty?
@regex = argv.shift
fail ParamsError.new if args.empty? || args.map { |dir| !File.directory?(dir) }.any?
target_dirs = args
when GREP_FILES
fail ParamsError.new if args.empty?
@regex = argv.shift
fail ParamsError.new if args.empty?
@files = args
else
fail ParamsError.new
end
rescue ParamsError
abort usage_message
end
@files ||= target_dirs.map do |target_dir|
Dir.entries(target_dir)
.reject { |file_name| ['.', '..'].include?(file_name) }
.map { |file_name| "#{target_dir}/#{file_name}" }
end.flatten.sort
end
def log_init!(argv)
# Specify a log file unless we are logging to stdout
unless @is_stdout_log
self.logger = Logger.new(log_file_name)
# Print to stdout where the logfile is
puts "logging to #{log_file_name}"
end
logger.formatter = proc do |severity, datetime, _progname, msg|
"#{severity} [#{datetime.strftime('%Y-%m-%d %H:%M:%S')}]: #{msg}\n"
end
# Log how the script was invoked
logger.info("START: Process ##{Process.pid}: #{__FILE__} #{argv.join(' ')}")
end
def usage_message
<<-EOF.gsub(/^ {4}/, '')
USAGE: #{File.basename(__FILE__)}
[#{BATCH_COMMIT}] [#{STDOUT_LOG}]
#{FILES} FILE ... |
#{DIRS} DIR ... |
#{GREP_FILES} REGEX FILE ... |
#{GREP_DIRS} REGEX DIR ...
boolean flags:
#{BATCH_COMMIT}: Optionally, make just one commit at the end, rather than
one commit per file.
#{STDOUT_LOG}: Optionally, log to stdout, rather than a log file.
mutually exclusive modes:
#{DIRS}: Clean and ingest the given directories.
#{FILES}: Clean and ingest the given files (either xml or zip).
#{GREP_DIRS} and #{GREP_FILES}: Same as above, except a regex is also provided.
Only PBCore which matches the regexp is ingested.
EOF
end
def process
ingester = PBCoreIngester.new(regex: @regex)
# set the PBCoreIngester's logger to the same as this object's logger
ingester.logger = logger
@files.each do |path|
begin
success_count_before = ingester.success_count
error_count_before = ingester.errors.values.flatten.count
ingester.ingest(path: path, is_batch_commit: @is_batch_commit)
success_count_after = ingester.success_count
error_count_after = ingester.errors.values.flatten.count
logger.info("Processed '#{path}' #{'but not committed' if @is_batch_commit}")
logger.info("success: #{success_count_after - success_count_before}; " \
"error: #{error_count_after - error_count_before}")
end
end
if @is_batch_commit
logger.info('Starting one big commit...')
ingester.commit
logger.info('Finished one big commit.')
end
# TODO: Investigate whether optimization is worth it. Requires a lot of disk and time.
# puts 'Ingest complete; Begin optimization...'
# ingester.optimize
errors = ingester.errors.sort # So related errors are together
error_count = errors.map { |pair| pair[1] }.flatten.count
success_count = ingester.success_count
total_count = error_count + success_count
logger.info('SUMMARY: DETAIL')
errors.each do |type, list|
logger.warn("#{list.count} #{type} errors:\n#{list.join("\n")}")
end
logger.info('SUMMARY: STATS')
logger.info('(Look just above for details on each error.)')
errors.each do |type, list|
logger.warn("#{list.count} (#{percent(list.count, total_count)}%) #{type}")
end
logger.info("#{success_count} (#{percent(success_count, total_count)}%) succeeded")
logger.info('DONE')
end
def percent(part, whole)
(100.0 * part / whole).round(1)
end
def log_file_name
@log_file_name ||= "#{Rails.root}/log/ingest.#{Time.now.strftime('%Y-%m-%d_%H%M%S')}.log"
end
end
Ingest.new(ARGV).process if __FILE__ == $PROGRAM_NAME
| WGBH/openvault3 | scripts/ingest.rb | Ruby | apache-2.0 | 5,618 |
Python 机器学习的必备技巧
======
> 尝试使用 Python 掌握机器学习、人工智能和深度学习。

想要入门机器学习并不难。除了<ruby>大规模网络公开课<rt>Massive Open Online Courses</rt></ruby>(MOOCs)之外,还有很多其它优秀的免费资源。下面我分享一些我觉得比较有用的方法。
1. 阅览一些关于这方面的视频、文章或者书籍,例如 [The Master Algorithm: How the Quest for the Ultimate Learning Machine Will Remake Our World][29],你肯定会喜欢这些[关于机器学习的互动页面][30]。
2. 对于“机器学习”、“人工智能”、“深度学习”、“数据科学”、“计算机视觉”和“机器人技术”这一堆新名词,你需要知道它们之前的区别。你可以阅览这些领域的专家们的演讲,例如[数据科学家 Brandon Rohrer 的这个视频][1]。
3. 明确你自己的学习目标,并选择合适的 [Coursera 课程][3],或者参加高校的网络公开课。例如[华盛顿大学的课程][4]就很不错。
4. 关注优秀的博客:例如 [KDnuggets][32] 的博客、[Mark Meloon][33] 的博客、[Brandon Rohrer][34] 的博客、[Open AI][35] 的博客,这些都值得推荐。
5. 如果你对在线课程有很大兴趣,后文中会有如何[正确选择 MOOC 课程][31]的指导。
6. 最重要的是,培养自己对这些技术的兴趣。加入一些优秀的社交论坛,专注于阅读和了解,将这些技术的背景知识和发展方向理解透彻,并积极思考在日常生活和工作中如何应用机器学习或数据科学的原理。例如建立一个简单的回归模型来预测下一次午餐的成本,又或者是从电力公司的网站上下载历史电费数据,在 Excel 中进行简单的时序分析以发现某种规律。在你对这些技术产生了浓厚兴趣之后,可以观看以下这个视频。
<https://www.youtube.com/embed/IpGxLWOIZy4>
### Python 是机器学习和人工智能方面的最佳语言吗?
除非你是一名专业的研究一些复杂算法纯理论证明的研究人员,否则,对于一个机器学习的入门者来说,需要熟悉至少一种高级编程语言一家相关的专业知识。因为大多数情况下都是需要考虑如何将机器学习算法应用于解决实际问题,而这需要有一定的编程能力作为基础。
哪一种语言是数据科学的最佳语言?这个讨论一直没有停息过。对于这方面,你可以提起精神来看一下 FreeCodeCamp 上这一篇关于[数据科学语言][6]的文章,又或者是 KDnuggets 关于 [Python 和 R][7] 之间的深入探讨。
目前人们普遍认为 Python 在开发、部署、维护各方面的效率都是比较高的。与 Java、C 和 C++ 这些较为传统的语言相比,Python 的语法更为简单和高级。而且 Python 拥有活跃的社区群体、广泛的开源文化、数百个专用于机器学习的优质代码库,以及来自业界巨头(包括Google、Dropbox、Airbnb 等)的强大技术支持。
### 基础 Python 库
如果你打算使用 Python 实施机器学习,你必须掌握一些 Python 包和库的使用方法。
#### NumPy
NumPy 的完整名称是 [Numerical Python][8],它是 Python 生态里高性能科学计算和数据分析都需要用到的基础包,几乎所有高级工具(例如 [Pandas][9] 和 [scikit-learn][10])都依赖于它。[TensorFlow][11] 使用了 NumPy 数组作为基础构建块以支持 Tensor 对象和深度学习的图形流。很多 NumPy 操作的速度都非常快,因为它们都是通过 C 实现的。高性能对于数据科学和现代机器学习来说是一个非常宝贵的优势。

#### Pandas
Pandas 是 Python 生态中用于进行通用数据分析的最受欢迎的库。Pandas 基于 NumPy 数组构建,在保证了可观的执行速度的同时,还提供了许多数据工程方面的功能,包括:
* 对多种不同数据格式的读写操作
* 选择数据子集
* 跨行列计算
* 查找并补充缺失的数据
* 将操作应用于数据中的独立组
* 按照多种格式转换数据
* 组合多个数据集
* 高级时间序列功能
* 通过 Matplotlib 和 Seaborn 进行可视化

#### Matplotlib 和 Seaborn
数据可视化和数据分析是数据科学家的必备技能,毕竟仅凭一堆枯燥的数据是无法有效地将背后蕴含的信息向受众传达的。这两项技能对于机器学习来说同样重要,因为首先要对数据集进行一个探索性分析,才能更准确地选择合适的机器学习算法。
[Matplotlib][12] 是应用最广泛的 2D Python 可视化库。它包含海量的命令和接口,可以让你根据数据生成高质量的图表。要学习使用 Matplotlib,可以参考这篇详尽的[文章][13]。

[Seaborn][14] 也是一个强大的用于统计和绘图的可视化库。它在 Matplotlib 的基础上提供样式灵活的 API、用于统计和绘图的常见高级函数,还可以和 Pandas 提供的功能相结合。要学习使用 Seaborn,可以参考这篇优秀的[教程][15]。

#### Scikit-learn
Scikit-learn 是机器学习方面通用的重要 Python 包。它实现了多种[分类][16]、[回归][17]和[聚类][18]算法,包括[支持向量机][19]、[随机森林][20]、[梯度增强][21]、[k-means 算法][22]和 [DBSCAN 算法][23],可以与 Python 的数值库 NumPy 和科学计算库 [SciPy][24] 结合使用。它通过兼容的接口提供了有监督和无监督的学习算法。Scikit-learn 的强壮性让它可以稳定运行在生产环境中,同时它在易用性、代码质量、团队协作、文档和性能等各个方面都有良好的表现。可以参考这篇基于 Scikit-learn 的[机器学习入门][25],或者这篇基于 Scikit-learn 的[简单机器学习用例演示][26]。
本文使用 [CC BY-SA 4.0][28] 许可,在 [Heartbeat][27] 上首发。
--------------------------------------------------------------------------------
via: https://opensource.com/article/18/10/machine-learning-python-essential-hacks-and-tricks
作者:[Tirthajyoti Sarkar][a]
选题:[lujun9972][b]
译者:[HankChow](https://github.com/HankChow)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]: https://opensource.com/users/tirthajyoti
[b]: https://github.com/lujun9972
[1]: https://www.youtube.com/watch?v=tKa0zDDDaQk
[2]: https://www.youtube.com/watch?v=Ura_ioOcpQI
[3]: https://www.coursera.org/learn/machine-learning
[4]: https://www.coursera.org/specializations/machine-learning
[5]: https://towardsdatascience.com/how-to-choose-effective-moocs-for-machine-learning-and-data-science-8681700ed83f
[6]: https://medium.freecodecamp.org/which-languages-should-you-learn-for-data-science-e806ba55a81f
[7]: https://www.kdnuggets.com/2017/09/python-vs-r-data-science-machine-learning.html
[8]: http://numpy.org/
[9]: https://pandas.pydata.org/
[10]: http://scikit-learn.org/
[11]: https://www.tensorflow.org/
[12]: https://matplotlib.org/
[13]: https://realpython.com/python-matplotlib-guide/
[14]: https://seaborn.pydata.org/
[15]: https://www.datacamp.com/community/tutorials/seaborn-python-tutorial
[16]: https://en.wikipedia.org/wiki/Statistical_classification
[17]: https://en.wikipedia.org/wiki/Regression_analysis
[18]: https://en.wikipedia.org/wiki/Cluster_analysis
[19]: https://en.wikipedia.org/wiki/Support_vector_machine
[20]: https://en.wikipedia.org/wiki/Random_forests
[21]: https://en.wikipedia.org/wiki/Gradient_boosting
[22]: https://en.wikipedia.org/wiki/K-means_clustering
[23]: https://en.wikipedia.org/wiki/DBSCAN
[24]: https://en.wikipedia.org/wiki/SciPy
[25]: http://scikit-learn.org/stable/tutorial/basic/tutorial.html
[26]: https://towardsdatascience.com/machine-learning-with-python-easy-and-robust-method-to-fit-nonlinear-data-19e8a1ddbd49
[27]: https://heartbeat.fritz.ai/some-essential-hacks-and-tricks-for-machine-learning-with-python-5478bc6593f2
[28]: https://creativecommons.org/licenses/by-sa/4.0/
[29]: https://www.goodreads.com/book/show/24612233-the-master-algorithm
[30]: http://www.r2d3.us/visual-intro-to-machine-learning-part-1/
[31]: https://towardsdatascience.com/how-to-choose-effective-moocs-for-machine-learning-and-data-science-8681700ed83f
[32]: https://www.kdnuggets.com/
[33]: http://www.markmeloon.com/
[34]: https://brohrer.github.io/blog.html
[35]: https://blog.openai.com/
| Flowsnow/TranslateProject | translated/tech/20181029 Machine learning with Python- Essential hacks and tricks.md | Markdown | apache-2.0 | 9,090 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.mail.search;
import javax.mail.Address;
/**
* Term that compares two addresses.
*
* @version $Rev: 920714 $ $Date: 2010-03-09 07:55:49 +0100 (Di, 09. Mär 2010) $
*/
public abstract class AddressTerm extends SearchTerm {
private static final long serialVersionUID = 2005405551929769980L;
/**
* The address.
*/
protected Address address;
/**
* Constructor taking the address for this term.
* @param address the address
*/
protected AddressTerm(Address address) {
this.address = address;
}
/**
* Return the address of this term.
*
* @return the addre4ss
*/
public Address getAddress() {
return address;
}
/**
* Match to the supplied address.
*
* @param address the address to match with
* @return true if the addresses match
*/
protected boolean match(Address address) {
return this.address.equals(address);
}
public boolean equals(Object other) {
if (this == other) return true;
if (other instanceof AddressTerm == false) return false;
return address.equals(((AddressTerm) other).address);
}
public int hashCode() {
return address.hashCode();
}
}
| salyh/jm14specsvn | src/main/java/javax/mail/search/AddressTerm.java | Java | apache-2.0 | 2,071 |
// ==UserScript==
// @name tabtweet
// @namespace http://chiptheglasses.com
// @description add a classic RT button to tweets
// @include http://*twitter.com*
// ==/UserScript==
// contains jQuery 1.4.1; It is patched.
/*!
* jQuery JavaScript Library v1.4.1
* http://jquery.com/
*
* Copyright 2010, John Resig
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* Includes Sizzle.js
* http://sizzlejs.com/
* Copyright 2010, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
*
* Date: Mon Jan 25 19:43:33 2010 -0500
*/
(function(z,v){function la(){if(!c.isReady){try{r.documentElement.doScroll("left")}catch(a){setTimeout(la,1);return}c.ready()}}function Ma(a,b){b.src?c.ajax({url:b.src,async:false,dataType:"script"}):c.globalEval(b.text||b.textContent||b.innerHTML||"");b.parentNode&&b.parentNode.removeChild(b)}function X(a,b,d,f,e,i){var j=a.length;if(typeof b==="object"){for(var n in b)X(a,n,b[n],f,e,d);return a}if(d!==v){f=!i&&f&&c.isFunction(d);for(n=0;n<j;n++)e(a[n],b,f?d.call(a[n],n,e(a[n],b)):d,i);return a}return j?
e(a[0],b):null}function J(){return(new Date).getTime()}function Y(){return false}function Z(){return true}function ma(a,b,d){d[0].type=a;return c.event.handle.apply(b,d)}function na(a){var b,d=[],f=[],e=arguments,i,j,n,o,m,s,x=c.extend({},c.data(this,"events").live);if(!(a.button&&a.type==="click")){for(o in x){j=x[o];if(j.live===a.type||j.altLive&&c.inArray(a.type,j.altLive)>-1){i=j.data;i.beforeFilter&&i.beforeFilter[a.type]&&!i.beforeFilter[a.type](a)||f.push(j.selector)}else delete x[o]}i=c(a.target).closest(f,
a.currentTarget);m=0;for(s=i.length;m<s;m++)for(o in x){j=x[o];n=i[m].elem;f=null;if(i[m].selector===j.selector){if(j.live==="mouseenter"||j.live==="mouseleave")f=c(a.relatedTarget).closest(j.selector)[0];if(!f||f!==n)d.push({elem:n,fn:j})}}m=0;for(s=d.length;m<s;m++){i=d[m];a.currentTarget=i.elem;a.data=i.fn.data;if(i.fn.apply(i.elem,e)===false){b=false;break}}return b}}function oa(a,b){return"live."+(a?a+".":"")+b.replace(/\./g,"`").replace(/ /g,"&")}function pa(a){return!a||!a.parentNode||a.parentNode.nodeType===
11}function qa(a,b){var d=0;b.each(function(){if(this.nodeName===(a[d]&&a[d].nodeName)){var f=c.data(a[d++]),e=c.data(this,f);if(f=f&&f.events){delete e.handle;e.events={};for(var i in f)for(var j in f[i])c.event.add(this,i,f[i][j],f[i][j].data)}}})}function ra(a,b,d){var f,e,i;if(a.length===1&&typeof a[0]==="string"&&a[0].length<512&&a[0].indexOf("<option")<0&&(c.support.checkClone||!sa.test(a[0]))){e=true;if(i=c.fragments[a[0]])if(i!==1)f=i}if(!f){b=b&&b[0]?b[0].ownerDocument||b[0]:r;f=b.createDocumentFragment();
c.clean(a,b,f,d)}if(e)c.fragments[a[0]]=i?f:1;return{fragment:f,cacheable:e}}function K(a,b){var d={};c.each(ta.concat.apply([],ta.slice(0,b)),function(){d[this]=a});return d}function ua(a){return"scrollTo"in a&&a.document?a:a.nodeType===9?a.defaultView||a.parentWindow:false}var c=function(a,b){return new c.fn.init(a,b)},Na=z.jQuery,Oa=z.$,r=z.document,S,Pa=/^[^<]*(<[\w\W]+>)[^>]*$|^#([\w-]+)$/,Qa=/^.[^:#\[\.,]*$/,Ra=/\S/,Sa=/^(\s|\u00A0)+|(\s|\u00A0)+$/g,Ta=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,O=navigator.userAgent,
va=false,P=[],L,$=Object.prototype.toString,aa=Object.prototype.hasOwnProperty,ba=Array.prototype.push,Q=Array.prototype.slice,wa=Array.prototype.indexOf;c.fn=c.prototype={init:function(a,b){var d,f;if(!a)return this;if(a.nodeType){this.context=this[0]=a;this.length=1;return this}if(typeof a==="string")if((d=Pa.exec(a))&&(d[1]||!b))if(d[1]){f=b?b.ownerDocument||b:r;if(a=Ta.exec(a))if(c.isPlainObject(b)){a=[r.createElement(a[1])];c.fn.attr.call(a,b,true)}else a=[f.createElement(a[1])];else{a=ra([d[1]],
[f]);a=(a.cacheable?a.fragment.cloneNode(true):a.fragment).childNodes}}else{if(b=r.getElementById(d[2])){if(b.id!==d[2])return S.find(a);this.length=1;this[0]=b}this.context=r;this.selector=a;return this}else if(!b&&/^\w+$/.test(a)){this.selector=a;this.context=r;a=r.getElementsByTagName(a)}else return!b||b.jquery?(b||S).find(a):c(b).find(a);else if(c.isFunction(a))return S.ready(a);if(a.selector!==v){this.selector=a.selector;this.context=a.context}return c.isArray(a)?this.setArray(a):c.makeArray(a,
this)},selector:"",jquery:"1.4.1",length:0,size:function(){return this.length},toArray:function(){return Q.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this.slice(a)[0]:this[a]},pushStack:function(a,b,d){a=c(a||null);a.prevObject=this;a.context=this.context;if(b==="find")a.selector=this.selector+(this.selector?" ":"")+d;else if(b)a.selector=this.selector+"."+b+"("+d+")";return a},setArray:function(a){this.length=0;ba.apply(this,a);return this},each:function(a,b){return c.each(this,
a,b)},ready:function(a){c.bindReady();if(c.isReady)a.call(r,c);else P&&P.push(a);return this},eq:function(a){return a===-1?this.slice(a):this.slice(a,+a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(Q.apply(this,arguments),"slice",Q.call(arguments).join(","))},map:function(a){return this.pushStack(c.map(this,function(b,d){return a.call(b,d,b)}))},end:function(){return this.prevObject||c(null)},push:ba,sort:[].sort,splice:[].splice};
c.fn.init.prototype=c.fn;c.extend=c.fn.extend=function(){var a=arguments[0]||{},b=1,d=arguments.length,f=false,e,i,j,n;if(typeof a==="boolean"){f=a;a=arguments[1]||{};b=2}if(typeof a!=="object"&&!c.isFunction(a))a={};if(d===b){a=this;--b}for(;b<d;b++)if((e=arguments[b])!=null)for(i in e){j=a[i];n=e[i];if(a!==n)if(f&&n&&(c.isPlainObject(n)||c.isArray(n))){j=j&&(c.isPlainObject(j)||c.isArray(j))?j:c.isArray(n)?[]:{};a[i]=c.extend(f,j,n)}else if(n!==v)a[i]=n}return a};c.extend({noConflict:function(a){z.$=
Oa;if(a)z.jQuery=Na;return c},isReady:false,ready:function(){if(!c.isReady){if(!r.body)return setTimeout(c.ready,13);c.isReady=true;if(P){for(var a,b=0;a=P[b++];)a.call(r,c);P=null}c.fn.triggerHandler&&c(r).triggerHandler("ready")}},bindReady:function(){if(!va){va=true;if(r.readyState==="complete")return c.ready();if(r.addEventListener){r.addEventListener("DOMContentLoaded",L,false);z.addEventListener("load",c.ready,false)}else if(r.attachEvent){r.attachEvent("onreadystatechange",L);z.attachEvent("onload",
c.ready);var a=false;try{a=z.frameElement==null}catch(b){}r.documentElement.doScroll&&a&&la()}}},isFunction:function(a){return $.call(a)==="[object Function]"},isArray:function(a){return $.call(a)==="[object Array]"},isPlainObject:function(a){if(!a||$.call(a)!=="[object Object]"||a.nodeType||a.setInterval)return false;if(a.constructor&&!aa.call(a,"constructor")&&!aa.call(a.constructor.prototype,"isPrototypeOf"))return false;var b;for(b in a);return b===v||aa.call(a,b)},isEmptyObject:function(a){for(var b in a)return false;
return true},error:function(a){throw a;},parseJSON:function(a){if(typeof a!=="string"||!a)return null;if(/^[\],:{}\s]*$/.test(a.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,"")))return z.JSON&&z.JSON.parse?z.JSON.parse(a):(new Function("return "+a))();else c.error("Invalid JSON: "+a)},noop:function(){},globalEval:function(a){if(a&&Ra.test(a)){var b=r.getElementsByTagName("head")[0]||
r.documentElement,d=r.createElement("script");d.type="text/javascript";if(c.support.scriptEval)d.appendChild(r.createTextNode(a));else d.text=a;b.insertBefore(d,b.firstChild);b.removeChild(d)}},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,b,d){var f,e=0,i=a.length,j=i===v||c.isFunction(a);if(d)if(j)for(f in a){if(b.apply(a[f],d)===false)break}else for(;e<i;){if(b.apply(a[e++],d)===false)break}else if(j)for(f in a){if(b.call(a[f],f,a[f])===false)break}else for(d=
a[0];e<i&&b.call(d,e,d)!==false;d=a[++e]);return a},trim:function(a){return(a||"").replace(Sa,"")},makeArray:function(a,b){b=b||[];if(a!=null)a.length==null||typeof a==="string"||c.isFunction(a)||typeof a!=="function"&&a.setInterval?ba.call(b,a):c.merge(b,a);return b},inArray:function(a,b){if(b.indexOf)return b.indexOf(a);for(var d=0,f=b.length;d<f;d++)if(b[d]===a)return d;return-1},merge:function(a,b){var d=a.length,f=0;if(typeof b.length==="number")for(var e=b.length;f<e;f++)a[d++]=b[f];else for(;b[f]!==
v;)a[d++]=b[f++];a.length=d;return a},grep:function(a,b,d){for(var f=[],e=0,i=a.length;e<i;e++)!d!==!b(a[e],e)&&f.push(a[e]);return f},map:function(a,b,d){for(var f=[],e,i=0,j=a.length;i<j;i++){e=b(a[i],i,d);if(e!=null)f[f.length]=e}return f.concat.apply([],f)},guid:1,proxy:function(a,b,d){if(arguments.length===2)if(typeof b==="string"){d=a;a=d[b];b=v}else if(b&&!c.isFunction(b)){d=b;b=v}if(!b&&a)b=function(){return a.apply(d||this,arguments)};if(a)b.guid=a.guid=a.guid||b.guid||c.guid++;return b},
uaMatch:function(a){a=a.toLowerCase();a=/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version)?[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||!/compatible/.test(a)&&/(mozilla)(?:.*? rv:([\w.]+))?/.exec(a)||[];return{browser:a[1]||"",version:a[2]||"0"}},browser:{}});O=c.uaMatch(O);if(O.browser){c.browser[O.browser]=true;c.browser.version=O.version}if(c.browser.webkit)c.browser.safari=true;if(wa)c.inArray=function(a,b){return wa.call(b,a)};S=c(r);if(r.addEventListener)L=function(){r.removeEventListener("DOMContentLoaded",
L,false);c.ready()};else if(r.attachEvent)L=function(){if(r.readyState==="complete"){r.detachEvent("onreadystatechange",L);c.ready()}};(function(){c.support={};var a=r.documentElement,b=r.createElement("script"),d=r.createElement("div"),f="script"+J();d.style.display="none";d.innerHTML=" <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>";var e=d.getElementsByTagName("*"),i=d.getElementsByTagName("a")[0];if(!(!e||!e.length||!i)){c.support=
{leadingWhitespace:d.firstChild.nodeType===3,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/red/.test(i.getAttribute("style")),hrefNormalized:i.getAttribute("href")==="/a",opacity:/^0.55$/.test(i.style.opacity),cssFloat:!!i.style.cssFloat,checkOn:d.getElementsByTagName("input")[0].value==="on",optSelected:r.createElement("select").appendChild(r.createElement("option")).selected,checkClone:false,scriptEval:false,noCloneEvent:true,boxModel:null};
b.type="text/javascript";try{b.appendChild(r.createTextNode("window."+f+"=1;"))}catch(j){}a.insertBefore(b,a.firstChild);if(z[f]){c.support.scriptEval=true;delete z[f]}a.removeChild(b);if(d.attachEvent&&d.fireEvent){d.attachEvent("onclick",function n(){c.support.noCloneEvent=false;d.detachEvent("onclick",n)});d.cloneNode(true).fireEvent("onclick")}d=r.createElement("div");d.innerHTML="<input type='radio' name='radiotest' checked='checked'/>";a=r.createDocumentFragment();a.appendChild(d.firstChild);
c.support.checkClone=a.cloneNode(true).cloneNode(true).lastChild.checked;c(function(){var n=r.createElement("div");n.style.width=n.style.paddingLeft="1px";r.body.appendChild(n);c.boxModel=c.support.boxModel=n.offsetWidth===2;r.body.removeChild(n).style.display="none"});a=function(n){var o=r.createElement("div");n="on"+n;var m=true;if(!m){o.setAttribute(n,"return;");m=typeof o[n]==="function"}return m};c.support.submitBubbles=a("submit");c.support.changeBubbles=a("change");a=b=d=e=i=null}})();c.props=
{"for":"htmlFor","class":"className",readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",colspan:"colSpan",tabindex:"tabIndex",usemap:"useMap",frameborder:"frameBorder"};var G="jQuery"+J(),Ua=0,xa={},Va={};c.extend({cache:{},expando:G,noData:{embed:true,object:true,applet:true},data:function(a,b,d){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==z?xa:a;var f=a[G],e=c.cache;if(!b&&!f)return null;f||(f=++Ua);if(typeof b==="object"){a[G]=f;e=e[f]=c.extend(true,
{},b)}else e=e[f]?e[f]:typeof d==="undefined"?Va:(e[f]={});if(d!==v){a[G]=f;e[b]=d}return typeof b==="string"?e[b]:e}},removeData:function(a,b){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==z?xa:a;var d=a[G],f=c.cache,e=f[d];if(b){if(e){delete e[b];c.isEmptyObject(e)&&c.removeData(a)}}else{try{delete a[G]}catch(i){a.removeAttribute&&a.removeAttribute(G)}delete f[d]}}}});c.fn.extend({data:function(a,b){if(typeof a==="undefined"&&this.length)return c.data(this[0]);else if(typeof a==="object")return this.each(function(){c.data(this,
a)});var d=a.split(".");d[1]=d[1]?"."+d[1]:"";if(b===v){var f=this.triggerHandler("getData"+d[1]+"!",[d[0]]);if(f===v&&this.length)f=c.data(this[0],a);return f===v&&d[1]?this.data(d[0]):f}else return this.trigger("setData"+d[1]+"!",[d[0],b]).each(function(){c.data(this,a,b)})},removeData:function(a){return this.each(function(){c.removeData(this,a)})}});c.extend({queue:function(a,b,d){if(a){b=(b||"fx")+"queue";var f=c.data(a,b);if(!d)return f||[];if(!f||c.isArray(d))f=c.data(a,b,c.makeArray(d));else f.push(d);
return f}},dequeue:function(a,b){b=b||"fx";var d=c.queue(a,b),f=d.shift();if(f==="inprogress")f=d.shift();if(f){b==="fx"&&d.unshift("inprogress");f.call(a,function(){c.dequeue(a,b)})}}});c.fn.extend({queue:function(a,b){if(typeof a!=="string"){b=a;a="fx"}if(b===v)return c.queue(this[0],a);return this.each(function(){var d=c.queue(this,a,b);a==="fx"&&d[0]!=="inprogress"&&c.dequeue(this,a)})},dequeue:function(a){return this.each(function(){c.dequeue(this,a)})},delay:function(a,b){a=c.fx?c.fx.speeds[a]||
a:a;b=b||"fx";return this.queue(b,function(){var d=this;setTimeout(function(){c.dequeue(d,b)},a)})},clearQueue:function(a){return this.queue(a||"fx",[])}});var ya=/[\n\t]/g,ca=/\s+/,Wa=/\r/g,Xa=/href|src|style/,Ya=/(button|input)/i,Za=/(button|input|object|select|textarea)/i,$a=/^(a|area)$/i,za=/radio|checkbox/;c.fn.extend({attr:function(a,b){return X(this,a,b,true,c.attr)},removeAttr:function(a){return this.each(function(){c.attr(this,a,"");this.nodeType===1&&this.removeAttribute(a)})},addClass:function(a){if(c.isFunction(a))return this.each(function(o){var m=
c(this);m.addClass(a.call(this,o,m.attr("class")))});if(a&&typeof a==="string")for(var b=(a||"").split(ca),d=0,f=this.length;d<f;d++){var e=this[d];if(e.nodeType===1)if(e.className)for(var i=" "+e.className+" ",j=0,n=b.length;j<n;j++){if(i.indexOf(" "+b[j]+" ")<0)e.className+=" "+b[j]}else e.className=a}return this},removeClass:function(a){if(c.isFunction(a))return this.each(function(o){var m=c(this);m.removeClass(a.call(this,o,m.attr("class")))});if(a&&typeof a==="string"||a===v)for(var b=(a||"").split(ca),
d=0,f=this.length;d<f;d++){var e=this[d];if(e.nodeType===1&&e.className)if(a){for(var i=(" "+e.className+" ").replace(ya," "),j=0,n=b.length;j<n;j++)i=i.replace(" "+b[j]+" "," ");e.className=i.substring(1,i.length-1)}else e.className=""}return this},toggleClass:function(a,b){var d=typeof a,f=typeof b==="boolean";if(c.isFunction(a))return this.each(function(e){var i=c(this);i.toggleClass(a.call(this,e,i.attr("class"),b),b)});return this.each(function(){if(d==="string")for(var e,i=0,j=c(this),n=b,o=
a.split(ca);e=o[i++];){n=f?n:!j.hasClass(e);j[n?"addClass":"removeClass"](e)}else if(d==="undefined"||d==="boolean"){this.className&&c.data(this,"__className__",this.className);this.className=this.className||a===false?"":c.data(this,"__className__")||""}})},hasClass:function(a){a=" "+a+" ";for(var b=0,d=this.length;b<d;b++)if((" "+this[b].className+" ").replace(ya," ").indexOf(a)>-1)return true;return false},val:function(a){if(a===v){var b=this[0];if(b){if(c.nodeName(b,"option"))return(b.attributes.value||
{}).specified?b.value:b.text;if(c.nodeName(b,"select")){var d=b.selectedIndex,f=[],e=b.options;b=b.type==="select-one";if(d<0)return null;var i=b?d:0;for(d=b?d+1:e.length;i<d;i++){var j=e[i];if(j.selected){a=c(j).val();if(b)return a;f.push(a)}}return f}if(za.test(b.type)&&!c.support.checkOn)return b.getAttribute("value")===null?"on":b.value;return(b.value||"").replace(Wa,"")}return v}var n=c.isFunction(a);return this.each(function(o){var m=c(this),s=a;if(this.nodeType===1){if(n)s=a.call(this,o,m.val());
if(typeof s==="number")s+="";if(c.isArray(s)&&za.test(this.type))this.checked=c.inArray(m.val(),s)>=0;else if(c.nodeName(this,"select")){var x=c.makeArray(s);c("option",this).each(function(){this.selected=c.inArray(c(this).val(),x)>=0});if(!x.length)this.selectedIndex=-1}else this.value=s}})}});c.extend({attrFn:{val:true,css:true,html:true,text:true,data:true,width:true,height:true,offset:true},attr:function(a,b,d,f){if(!a||a.nodeType===3||a.nodeType===8)return v;if(f&&b in c.attrFn)return c(a)[b](d);
f=a.nodeType!==1||!c.isXMLDoc(a);var e=d!==v;b=f&&c.props[b]||b;if(a.nodeType===1){var i=Xa.test(b);if(b in a&&f&&!i){if(e){b==="type"&&Ya.test(a.nodeName)&&a.parentNode&&c.error("type property can't be changed");a[b]=d}if(c.nodeName(a,"form")&&a.getAttributeNode(b))return a.getAttributeNode(b).nodeValue;if(b==="tabIndex")return(b=a.getAttributeNode("tabIndex"))&&b.specified?b.value:Za.test(a.nodeName)||$a.test(a.nodeName)&&a.href?0:v;return a[b]}if(!c.support.style&&f&&b==="style"){if(e)a.style.cssText=
""+d;return a.style.cssText}e&&a.setAttribute(b,""+d);a=!c.support.hrefNormalized&&f&&i?a.getAttribute(b,2):a.getAttribute(b);return a===null?v:a}return c.style(a,b,d)}});var ab=function(a){return a.replace(/[^\w\s\.\|`]/g,function(b){return"\\"+b})};c.event={add:function(a,b,d,f){if(!(a.nodeType===3||a.nodeType===8)){if(a.setInterval&&a!==z&&!a.frameElement)a=z;if(!d.guid)d.guid=c.guid++;if(f!==v){d=c.proxy(d);d.data=f}var e=c.data(a,"events")||c.data(a,"events",{}),i=c.data(a,"handle"),j;if(!i){j=
function(){return typeof c!=="undefined"&&!c.event.triggered?c.event.handle.apply(j.elem,arguments):v};i=c.data(a,"handle",j)}if(i){i.elem=a;b=b.split(/\s+/);for(var n,o=0;n=b[o++];){var m=n.split(".");n=m.shift();if(o>1){d=c.proxy(d);if(f!==v)d.data=f}d.type=m.slice(0).sort().join(".");var s=e[n],x=this.special[n]||{};if(!s){s=e[n]={};if(!x.setup||x.setup.call(a,f,m,d)===false)if(a.addEventListener)a.addEventListener(n,i,false);else a.attachEvent&&a.attachEvent("on"+n,i)}if(x.add)if((m=x.add.call(a,
d,f,m,s))&&c.isFunction(m)){m.guid=m.guid||d.guid;m.data=m.data||d.data;m.type=m.type||d.type;d=m}s[d.guid]=d;this.global[n]=true}a=null}}},global:{},remove:function(a,b,d){if(!(a.nodeType===3||a.nodeType===8)){var f=c.data(a,"events"),e,i,j;if(f){if(b===v||typeof b==="string"&&b.charAt(0)===".")for(i in f)this.remove(a,i+(b||""));else{if(b.type){d=b.handler;b=b.type}b=b.split(/\s+/);for(var n=0;i=b[n++];){var o=i.split(".");i=o.shift();var m=!o.length,s=c.map(o.slice(0).sort(),ab);s=new RegExp("(^|\\.)"+
s.join("\\.(?:.*\\.)?")+"(\\.|$)");var x=this.special[i]||{};if(f[i]){if(d){j=f[i][d.guid];delete f[i][d.guid]}else for(var A in f[i])if(m||s.test(f[i][A].type))delete f[i][A];x.remove&&x.remove.call(a,o,j);for(e in f[i])break;if(!e){if(!x.teardown||x.teardown.call(a,o)===false)if(a.removeEventListener)a.removeEventListener(i,c.data(a,"handle"),false);else a.detachEvent&&a.detachEvent("on"+i,c.data(a,"handle"));e=null;delete f[i]}}}}for(e in f)break;if(!e){if(A=c.data(a,"handle"))A.elem=null;c.removeData(a,
"events");c.removeData(a,"handle")}}}},trigger:function(a,b,d,f){var e=a.type||a;if(!f){a=typeof a==="object"?a[G]?a:c.extend(c.Event(e),a):c.Event(e);if(e.indexOf("!")>=0){a.type=e=e.slice(0,-1);a.exclusive=true}if(!d){a.stopPropagation();this.global[e]&&c.each(c.cache,function(){this.events&&this.events[e]&&c.event.trigger(a,b,this.handle.elem)})}if(!d||d.nodeType===3||d.nodeType===8)return v;a.result=v;a.target=d;b=c.makeArray(b);b.unshift(a)}a.currentTarget=d;(f=c.data(d,"handle"))&&f.apply(d,
b);f=d.parentNode||d.ownerDocument;try{if(!(d&&d.nodeName&&c.noData[d.nodeName.toLowerCase()]))if(d["on"+e]&&d["on"+e].apply(d,b)===false)a.result=false}catch(i){}if(!a.isPropagationStopped()&&f)c.event.trigger(a,b,f,true);else if(!a.isDefaultPrevented()){d=a.target;var j;if(!(c.nodeName(d,"a")&&e==="click")&&!(d&&d.nodeName&&c.noData[d.nodeName.toLowerCase()])){try{if(d[e]){if(j=d["on"+e])d["on"+e]=null;this.triggered=true;d[e]()}}catch(n){}if(j)d["on"+e]=j;this.triggered=false}}},handle:function(a){var b,
d;a=arguments[0]=c.event.fix(a||z.event);a.currentTarget=this;d=a.type.split(".");a.type=d.shift();b=!d.length&&!a.exclusive;var f=new RegExp("(^|\\.)"+d.slice(0).sort().join("\\.(?:.*\\.)?")+"(\\.|$)");d=(c.data(this,"events")||{})[a.type];for(var e in d){var i=d[e];if(b||f.test(i.type)){a.handler=i;a.data=i.data;i=i.apply(this,arguments);if(i!==v){a.result=i;if(i===false){a.preventDefault();a.stopPropagation()}}if(a.isImmediatePropagationStopped())break}}return a.result},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),
fix:function(a){if(a[G])return a;var b=a;a=c.Event(b);for(var d=this.props.length,f;d;){f=this.props[--d];a[f]=b[f]}if(!a.target)a.target=a.srcElement||r;if(a.target.nodeType===3)a.target=a.target.parentNode;if(!a.relatedTarget&&a.fromElement)a.relatedTarget=a.fromElement===a.target?a.toElement:a.fromElement;if(a.pageX==null&&a.clientX!=null){b=r.documentElement;d=r.body;a.pageX=a.clientX+(b&&b.scrollLeft||d&&d.scrollLeft||0)-(b&&b.clientLeft||d&&d.clientLeft||0);a.pageY=a.clientY+(b&&b.scrollTop||
d&&d.scrollTop||0)-(b&&b.clientTop||d&&d.clientTop||0)}if(!a.which&&(a.charCode||a.charCode===0?a.charCode:a.keyCode))a.which=a.charCode||a.keyCode;if(!a.metaKey&&a.ctrlKey)a.metaKey=a.ctrlKey;if(!a.which&&a.button!==v)a.which=a.button&1?1:a.button&2?3:a.button&4?2:0;return a},guid:1E8,proxy:c.proxy,special:{ready:{setup:c.bindReady,teardown:c.noop},live:{add:function(a,b){c.extend(a,b||{});a.guid+=b.selector+b.live;b.liveProxy=a;c.event.add(this,b.live,na,b)},remove:function(a){if(a.length){var b=
0,d=new RegExp("(^|\\.)"+a[0]+"(\\.|$)");c.each(c.data(this,"events").live||{},function(){d.test(this.type)&&b++});b<1&&c.event.remove(this,a[0],na)}},special:{}},beforeunload:{setup:function(a,b,d){if(this.setInterval)this.onbeforeunload=d;return false},teardown:function(a,b){if(this.onbeforeunload===b)this.onbeforeunload=null}}}};c.Event=function(a){if(!this.preventDefault)return new c.Event(a);if(a&&a.type){this.originalEvent=a;this.type=a.type}else this.type=a;this.timeStamp=J();this[G]=true};
c.Event.prototype={preventDefault:function(){this.isDefaultPrevented=Z;var a=this.originalEvent;if(a){a.preventDefault&&a.preventDefault();a.returnValue=false}},stopPropagation:function(){this.isPropagationStopped=Z;var a=this.originalEvent;if(a){a.stopPropagation&&a.stopPropagation();a.cancelBubble=true}},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=Z;this.stopPropagation()},isDefaultPrevented:Y,isPropagationStopped:Y,isImmediatePropagationStopped:Y};var Aa=function(a){for(var b=
a.relatedTarget;b&&b!==this;)try{b=b.parentNode}catch(d){break}if(b!==this){a.type=a.data;c.event.handle.apply(this,arguments)}},Ba=function(a){a.type=a.data;c.event.handle.apply(this,arguments)};c.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){c.event.special[a]={setup:function(d){c.event.add(this,b,d&&d.selector?Ba:Aa,a)},teardown:function(d){c.event.remove(this,b,d&&d.selector?Ba:Aa)}}});if(!c.support.submitBubbles)c.event.special.submit={setup:function(a,b,d){if(this.nodeName.toLowerCase()!==
"form"){c.event.add(this,"click.specialSubmit."+d.guid,function(f){var e=f.target,i=e.type;if((i==="submit"||i==="image")&&c(e).closest("form").length)return ma("submit",this,arguments)});c.event.add(this,"keypress.specialSubmit."+d.guid,function(f){var e=f.target,i=e.type;if((i==="text"||i==="password")&&c(e).closest("form").length&&f.keyCode===13)return ma("submit",this,arguments)})}else return false},remove:function(a,b){c.event.remove(this,"click.specialSubmit"+(b?"."+b.guid:""));c.event.remove(this,
"keypress.specialSubmit"+(b?"."+b.guid:""))}};if(!c.support.changeBubbles){var da=/textarea|input|select/i;function Ca(a){var b=a.type,d=a.value;if(b==="radio"||b==="checkbox")d=a.checked;else if(b==="select-multiple")d=a.selectedIndex>-1?c.map(a.options,function(f){return f.selected}).join("-"):"";else if(a.nodeName.toLowerCase()==="select")d=a.selectedIndex;return d}function ea(a,b){var d=a.target,f,e;if(!(!da.test(d.nodeName)||d.readOnly)){f=c.data(d,"_change_data");e=Ca(d);if(a.type!=="focusout"||
d.type!=="radio")c.data(d,"_change_data",e);if(!(f===v||e===f))if(f!=null||e){a.type="change";return c.event.trigger(a,b,d)}}}c.event.special.change={filters:{focusout:ea,click:function(a){var b=a.target,d=b.type;if(d==="radio"||d==="checkbox"||b.nodeName.toLowerCase()==="select")return ea.call(this,a)},keydown:function(a){var b=a.target,d=b.type;if(a.keyCode===13&&b.nodeName.toLowerCase()!=="textarea"||a.keyCode===32&&(d==="checkbox"||d==="radio")||d==="select-multiple")return ea.call(this,a)},beforeactivate:function(a){a=
a.target;a.nodeName.toLowerCase()==="input"&&a.type==="radio"&&c.data(a,"_change_data",Ca(a))}},setup:function(a,b,d){for(var f in T)c.event.add(this,f+".specialChange."+d.guid,T[f]);return da.test(this.nodeName)},remove:function(a,b){for(var d in T)c.event.remove(this,d+".specialChange"+(b?"."+b.guid:""),T[d]);return da.test(this.nodeName)}};var T=c.event.special.change.filters}r.addEventListener&&c.each({focus:"focusin",blur:"focusout"},function(a,b){function d(f){f=c.event.fix(f);f.type=b;return c.event.handle.call(this,
f)}c.event.special[b]={setup:function(){this.addEventListener(a,d,true)},teardown:function(){this.removeEventListener(a,d,true)}}});c.each(["bind","one"],function(a,b){c.fn[b]=function(d,f,e){if(typeof d==="object"){for(var i in d)this[b](i,f,d[i],e);return this}if(c.isFunction(f)){e=f;f=v}var j=b==="one"?c.proxy(e,function(n){c(this).unbind(n,j);return e.apply(this,arguments)}):e;return d==="unload"&&b!=="one"?this.one(d,f,e):this.each(function(){c.event.add(this,d,j,f)})}});c.fn.extend({unbind:function(a,
b){if(typeof a==="object"&&!a.preventDefault){for(var d in a)this.unbind(d,a[d]);return this}return this.each(function(){c.event.remove(this,a,b)})},trigger:function(a,b){return this.each(function(){c.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0]){a=c.Event(a);a.preventDefault();a.stopPropagation();c.event.trigger(a,b,this[0]);return a.result}},toggle:function(a){for(var b=arguments,d=1;d<b.length;)c.proxy(a,b[d++]);return this.click(c.proxy(a,function(f){var e=(c.data(this,"lastToggle"+
a.guid)||0)%d;c.data(this,"lastToggle"+a.guid,e+1);f.preventDefault();return b[e].apply(this,arguments)||false}))},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});c.each(["live","die"],function(a,b){c.fn[b]=function(d,f,e){var i,j=0;if(c.isFunction(f)){e=f;f=v}for(d=(d||"").split(/\s+/);(i=d[j++])!=null;){i=i==="focus"?"focusin":i==="blur"?"focusout":i==="hover"?d.push("mouseleave")&&"mouseenter":i;b==="live"?c(this.context).bind(oa(i,this.selector),{data:f,selector:this.selector,
live:i},e):c(this.context).unbind(oa(i,this.selector),e?{guid:e.guid+this.selector+i}:null)}return this}});c.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error".split(" "),function(a,b){c.fn[b]=function(d){return d?this.bind(b,d):this.trigger(b)};if(c.attrFn)c.attrFn[b]=true});z.attachEvent&&!z.addEventListener&&z.attachEvent("onunload",function(){for(var a in c.cache)if(c.cache[a].handle)try{c.event.remove(c.cache[a].handle.elem)}catch(b){}});
(function(){function a(g){for(var h="",k,l=0;g[l];l++){k=g[l];if(k.nodeType===3||k.nodeType===4)h+=k.nodeValue;else if(k.nodeType!==8)h+=a(k.childNodes)}return h}function b(g,h,k,l,q,p){q=0;for(var u=l.length;q<u;q++){var t=l[q];if(t){t=t[g];for(var y=false;t;){if(t.sizcache===k){y=l[t.sizset];break}if(t.nodeType===1&&!p){t.sizcache=k;t.sizset=q}if(t.nodeName.toLowerCase()===h){y=t;break}t=t[g]}l[q]=y}}}function d(g,h,k,l,q,p){q=0;for(var u=l.length;q<u;q++){var t=l[q];if(t){t=t[g];for(var y=false;t;){if(t.sizcache===
k){y=l[t.sizset];break}if(t.nodeType===1){if(!p){t.sizcache=k;t.sizset=q}if(typeof h!=="string"){if(t===h){y=true;break}}else if(o.filter(h,[t]).length>0){y=t;break}}t=t[g]}l[q]=y}}}var f=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,e=0,i=Object.prototype.toString,j=false,n=true;[0,0].sort(function(){n=false;return 0});var o=function(g,h,k,l){k=k||[];var q=h=h||r;if(h.nodeType!==1&&h.nodeType!==9)return[];if(!g||
typeof g!=="string")return k;for(var p=[],u,t,y,R,H=true,M=w(h),I=g;(f.exec(""),u=f.exec(I))!==null;){I=u[3];p.push(u[1]);if(u[2]){R=u[3];break}}if(p.length>1&&s.exec(g))if(p.length===2&&m.relative[p[0]])t=fa(p[0]+p[1],h);else for(t=m.relative[p[0]]?[h]:o(p.shift(),h);p.length;){g=p.shift();if(m.relative[g])g+=p.shift();t=fa(g,t)}else{if(!l&&p.length>1&&h.nodeType===9&&!M&&m.match.ID.test(p[0])&&!m.match.ID.test(p[p.length-1])){u=o.find(p.shift(),h,M);h=u.expr?o.filter(u.expr,u.set)[0]:u.set[0]}if(h){u=
l?{expr:p.pop(),set:A(l)}:o.find(p.pop(),p.length===1&&(p[0]==="~"||p[0]==="+")&&h.parentNode?h.parentNode:h,M);t=u.expr?o.filter(u.expr,u.set):u.set;if(p.length>0)y=A(t);else H=false;for(;p.length;){var D=p.pop();u=D;if(m.relative[D])u=p.pop();else D="";if(u==null)u=h;m.relative[D](y,u,M)}}else y=[]}y||(y=t);y||o.error(D||g);if(i.call(y)==="[object Array]")if(H)if(h&&h.nodeType===1)for(g=0;y[g]!=null;g++){if(y[g]&&(y[g]===true||y[g].nodeType===1&&E(h,y[g])))k.push(t[g])}else for(g=0;y[g]!=null;g++)y[g]&&
y[g].nodeType===1&&k.push(t[g]);else k.push.apply(k,y);else A(y,k);if(R){o(R,q,k,l);o.uniqueSort(k)}return k};o.uniqueSort=function(g){if(C){j=n;g.sort(C);if(j)for(var h=1;h<g.length;h++)g[h]===g[h-1]&&g.splice(h--,1)}return g};o.matches=function(g,h){return o(g,null,null,h)};o.find=function(g,h,k){var l,q;if(!g)return[];for(var p=0,u=m.order.length;p<u;p++){var t=m.order[p];if(q=m.leftMatch[t].exec(g)){var y=q[1];q.splice(1,1);if(y.substr(y.length-1)!=="\\"){q[1]=(q[1]||"").replace(/\\/g,"");l=m.find[t](q,
h,k);if(l!=null){g=g.replace(m.match[t],"");break}}}}l||(l=h.getElementsByTagName("*"));return{set:l,expr:g}};o.filter=function(g,h,k,l){for(var q=g,p=[],u=h,t,y,R=h&&h[0]&&w(h[0]);g&&h.length;){for(var H in m.filter)if((t=m.leftMatch[H].exec(g))!=null&&t[2]){var M=m.filter[H],I,D;D=t[1];y=false;t.splice(1,1);if(D.substr(D.length-1)!=="\\"){if(u===p)p=[];if(m.preFilter[H])if(t=m.preFilter[H](t,u,k,p,l,R)){if(t===true)continue}else y=I=true;if(t)for(var U=0;(D=u[U])!=null;U++)if(D){I=M(D,t,U,u);var Da=
l^!!I;if(k&&I!=null)if(Da)y=true;else u[U]=false;else if(Da){p.push(D);y=true}}if(I!==v){k||(u=p);g=g.replace(m.match[H],"");if(!y)return[];break}}}if(g===q)if(y==null)o.error(g);else break;q=g}return u};o.error=function(g){throw"Syntax error, unrecognized expression: "+g;};var m=o.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,
TAG:/^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(g){return g.getAttribute("href")}},relative:{"+":function(g,h){var k=typeof h==="string",l=k&&!/\W/.test(h);k=k&&!l;if(l)h=h.toLowerCase();l=0;for(var q=g.length,
p;l<q;l++)if(p=g[l]){for(;(p=p.previousSibling)&&p.nodeType!==1;);g[l]=k||p&&p.nodeName.toLowerCase()===h?p||false:p===h}k&&o.filter(h,g,true)},">":function(g,h){var k=typeof h==="string";if(k&&!/\W/.test(h)){h=h.toLowerCase();for(var l=0,q=g.length;l<q;l++){var p=g[l];if(p){k=p.parentNode;g[l]=k.nodeName.toLowerCase()===h?k:false}}}else{l=0;for(q=g.length;l<q;l++)if(p=g[l])g[l]=k?p.parentNode:p.parentNode===h;k&&o.filter(h,g,true)}},"":function(g,h,k){var l=e++,q=d;if(typeof h==="string"&&!/\W/.test(h)){var p=
h=h.toLowerCase();q=b}q("parentNode",h,l,g,p,k)},"~":function(g,h,k){var l=e++,q=d;if(typeof h==="string"&&!/\W/.test(h)){var p=h=h.toLowerCase();q=b}q("previousSibling",h,l,g,p,k)}},find:{ID:function(g,h,k){if(typeof h.getElementById!=="undefined"&&!k)return(g=h.getElementById(g[1]))?[g]:[]},NAME:function(g,h){if(typeof h.getElementsByName!=="undefined"){var k=[];h=h.getElementsByName(g[1]);for(var l=0,q=h.length;l<q;l++)h[l].getAttribute("name")===g[1]&&k.push(h[l]);return k.length===0?null:k}},
TAG:function(g,h){return h.getElementsByTagName(g[1])}},preFilter:{CLASS:function(g,h,k,l,q,p){g=" "+g[1].replace(/\\/g,"")+" ";if(p)return g;p=0;for(var u;(u=h[p])!=null;p++)if(u)if(q^(u.className&&(" "+u.className+" ").replace(/[\t\n]/g," ").indexOf(g)>=0))k||l.push(u);else if(k)h[p]=false;return false},ID:function(g){return g[1].replace(/\\/g,"")},TAG:function(g){return g[1].toLowerCase()},CHILD:function(g){if(g[1]==="nth"){var h=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(g[2]==="even"&&"2n"||g[2]==="odd"&&
"2n+1"||!/\D/.test(g[2])&&"0n+"+g[2]||g[2]);g[2]=h[1]+(h[2]||1)-0;g[3]=h[3]-0}g[0]=e++;return g},ATTR:function(g,h,k,l,q,p){h=g[1].replace(/\\/g,"");if(!p&&m.attrMap[h])g[1]=m.attrMap[h];if(g[2]==="~=")g[4]=" "+g[4]+" ";return g},PSEUDO:function(g,h,k,l,q){if(g[1]==="not")if((f.exec(g[3])||"").length>1||/^\w/.test(g[3]))g[3]=o(g[3],null,null,h);else{g=o.filter(g[3],h,k,true^q);k||l.push.apply(l,g);return false}else if(m.match.POS.test(g[0])||m.match.CHILD.test(g[0]))return true;return g},POS:function(g){g.unshift(true);
return g}},filters:{enabled:function(g){return g.disabled===false&&g.type!=="hidden"},disabled:function(g){return g.disabled===true},checked:function(g){return g.checked===true},selected:function(g){return g.selected===true},parent:function(g){return!!g.firstChild},empty:function(g){return!g.firstChild},has:function(g,h,k){return!!o(k[3],g).length},header:function(g){return/h\d/i.test(g.nodeName)},text:function(g){return"text"===g.type},radio:function(g){return"radio"===g.type},checkbox:function(g){return"checkbox"===
g.type},file:function(g){return"file"===g.type},password:function(g){return"password"===g.type},submit:function(g){return"submit"===g.type},image:function(g){return"image"===g.type},reset:function(g){return"reset"===g.type},button:function(g){return"button"===g.type||g.nodeName.toLowerCase()==="button"},input:function(g){return/input|select|textarea|button/i.test(g.nodeName)}},setFilters:{first:function(g,h){return h===0},last:function(g,h,k,l){return h===l.length-1},even:function(g,h){return h%2===
0},odd:function(g,h){return h%2===1},lt:function(g,h,k){return h<k[3]-0},gt:function(g,h,k){return h>k[3]-0},nth:function(g,h,k){return k[3]-0===h},eq:function(g,h,k){return k[3]-0===h}},filter:{PSEUDO:function(g,h,k,l){var q=h[1],p=m.filters[q];if(p)return p(g,k,h,l);else if(q==="contains")return(g.textContent||g.innerText||a([g])||"").indexOf(h[3])>=0;else if(q==="not"){h=h[3];k=0;for(l=h.length;k<l;k++)if(h[k]===g)return false;return true}else o.error("Syntax error, unrecognized expression: "+
q)},CHILD:function(g,h){var k=h[1],l=g;switch(k){case "only":case "first":for(;l=l.previousSibling;)if(l.nodeType===1)return false;if(k==="first")return true;l=g;case "last":for(;l=l.nextSibling;)if(l.nodeType===1)return false;return true;case "nth":k=h[2];var q=h[3];if(k===1&&q===0)return true;h=h[0];var p=g.parentNode;if(p&&(p.sizcache!==h||!g.nodeIndex)){var u=0;for(l=p.firstChild;l;l=l.nextSibling)if(l.nodeType===1)l.nodeIndex=++u;p.sizcache=h}g=g.nodeIndex-q;return k===0?g===0:g%k===0&&g/k>=
0}},ID:function(g,h){return g.nodeType===1&&g.getAttribute("id")===h},TAG:function(g,h){return h==="*"&&g.nodeType===1||g.nodeName.toLowerCase()===h},CLASS:function(g,h){return(" "+(g.className||g.getAttribute("class"))+" ").indexOf(h)>-1},ATTR:function(g,h){var k=h[1];g=m.attrHandle[k]?m.attrHandle[k](g):g[k]!=null?g[k]:g.getAttribute(k);k=g+"";var l=h[2];h=h[4];return g==null?l==="!=":l==="="?k===h:l==="*="?k.indexOf(h)>=0:l==="~="?(" "+k+" ").indexOf(h)>=0:!h?k&&g!==false:l==="!="?k!==h:l==="^="?
k.indexOf(h)===0:l==="$="?k.substr(k.length-h.length)===h:l==="|="?k===h||k.substr(0,h.length+1)===h+"-":false},POS:function(g,h,k,l){var q=m.setFilters[h[2]];if(q)return q(g,k,h,l)}}},s=m.match.POS;for(var x in m.match){m.match[x]=new RegExp(m.match[x].source+/(?![^\[]*\])(?![^\(]*\))/.source);m.leftMatch[x]=new RegExp(/(^(?:.|\r|\n)*?)/.source+m.match[x].source.replace(/\\(\d+)/g,function(g,h){return"\\"+(h-0+1)}))}var A=function(g,h){g=Array.prototype.slice.call(g,0);if(h){h.push.apply(h,g);return h}return g};
try{Array.prototype.slice.call(r.documentElement.childNodes,0)}catch(B){A=function(g,h){h=h||[];if(i.call(g)==="[object Array]")Array.prototype.push.apply(h,g);else if(typeof g.length==="number")for(var k=0,l=g.length;k<l;k++)h.push(g[k]);else for(k=0;g[k];k++)h.push(g[k]);return h}}var C;if(r.documentElement.compareDocumentPosition)C=function(g,h){if(!g.compareDocumentPosition||!h.compareDocumentPosition){if(g==h)j=true;return g.compareDocumentPosition?-1:1}g=g.compareDocumentPosition(h)&4?-1:g===
h?0:1;if(g===0)j=true;return g};else if("sourceIndex"in r.documentElement)C=function(g,h){if(!g.sourceIndex||!h.sourceIndex){if(g==h)j=true;return g.sourceIndex?-1:1}g=g.sourceIndex-h.sourceIndex;if(g===0)j=true;return g};else if(r.createRange)C=function(g,h){if(!g.ownerDocument||!h.ownerDocument){if(g==h)j=true;return g.ownerDocument?-1:1}var k=g.ownerDocument.createRange(),l=h.ownerDocument.createRange();k.setStart(g,0);k.setEnd(g,0);l.setStart(h,0);l.setEnd(h,0);g=k.compareBoundaryPoints(Range.START_TO_END,
l);if(g===0)j=true;return g};(function(){var g=r.createElement("div"),h="script"+(new Date).getTime();g.innerHTML="<a name='"+h+"'/>";var k=r.documentElement;k.insertBefore(g,k.firstChild);if(r.getElementById(h)){m.find.ID=function(l,q,p){if(typeof q.getElementById!=="undefined"&&!p)return(q=q.getElementById(l[1]))?q.id===l[1]||typeof q.getAttributeNode!=="undefined"&&q.getAttributeNode("id").nodeValue===l[1]?[q]:v:[]};m.filter.ID=function(l,q){var p=typeof l.getAttributeNode!=="undefined"&&l.getAttributeNode("id");
return l.nodeType===1&&p&&p.nodeValue===q}}k.removeChild(g);k=g=null})();(function(){var g=r.createElement("div");g.appendChild(r.createComment(""));if(g.getElementsByTagName("*").length>0)m.find.TAG=function(h,k){k=k.getElementsByTagName(h[1]);if(h[1]==="*"){h=[];for(var l=0;k[l];l++)k[l].nodeType===1&&h.push(k[l]);k=h}return k};g.innerHTML="<a href='#'></a>";if(g.firstChild&&typeof g.firstChild.getAttribute!=="undefined"&&g.firstChild.getAttribute("href")!=="#")m.attrHandle.href=function(h){return h.getAttribute("href",
2)};g=null})();r.querySelectorAll&&function(){var g=o,h=r.createElement("div");h.innerHTML="<p class='TEST'></p>";if(!(h.querySelectorAll&&h.querySelectorAll(".TEST").length===0)){o=function(l,q,p,u){q=q||r;if(!u&&q.nodeType===9&&!w(q))try{return A(q.querySelectorAll(l),p)}catch(t){}return g(l,q,p,u)};for(var k in g)o[k]=g[k];h=null}}();(function(){var g=r.createElement("div");g.innerHTML="<div class='test e'></div><div class='test'></div>";if(!(!g.getElementsByClassName||g.getElementsByClassName("e").length===
0)){g.lastChild.className="e";if(g.getElementsByClassName("e").length!==1){m.order.splice(1,0,"CLASS");m.find.CLASS=function(h,k,l){if(typeof k.getElementsByClassName!=="undefined"&&!l)return k.getElementsByClassName(h[1])};g=null}}})();var E=r.compareDocumentPosition?function(g,h){return g.compareDocumentPosition(h)&16}:function(g,h){return g!==h&&(g.contains?g.contains(h):true)},w=function(g){return(g=(g?g.ownerDocument||g:0).documentElement)?g.nodeName!=="HTML":false},fa=function(g,h){var k=[],
l="",q;for(h=h.nodeType?[h]:h;q=m.match.PSEUDO.exec(g);){l+=q[0];g=g.replace(m.match.PSEUDO,"")}g=m.relative[g]?g+"*":g;q=0;for(var p=h.length;q<p;q++)o(g,h[q],k);return o.filter(l,k)};c.find=o;c.expr=o.selectors;c.expr[":"]=c.expr.filters;c.unique=o.uniqueSort;c.getText=a;c.isXMLDoc=w;c.contains=E})();var bb=/Until$/,cb=/^(?:parents|prevUntil|prevAll)/,db=/,/;Q=Array.prototype.slice;var Ea=function(a,b,d){if(c.isFunction(b))return c.grep(a,function(e,i){return!!b.call(e,i,e)===d});else if(b.nodeType)return c.grep(a,
function(e){return e===b===d});else if(typeof b==="string"){var f=c.grep(a,function(e){return e.nodeType===1});if(Qa.test(b))return c.filter(b,f,!d);else b=c.filter(b,f)}return c.grep(a,function(e){return c.inArray(e,b)>=0===d})};c.fn.extend({find:function(a){for(var b=this.pushStack("","find",a),d=0,f=0,e=this.length;f<e;f++){d=b.length;c.find(a,this[f],b);if(f>0)for(var i=d;i<b.length;i++)for(var j=0;j<d;j++)if(b[j]===b[i]){b.splice(i--,1);break}}return b},has:function(a){var b=c(a);return this.filter(function(){for(var d=
0,f=b.length;d<f;d++)if(c.contains(this,b[d]))return true})},not:function(a){return this.pushStack(Ea(this,a,false),"not",a)},filter:function(a){return this.pushStack(Ea(this,a,true),"filter",a)},is:function(a){return!!a&&c.filter(a,this).length>0},closest:function(a,b){if(c.isArray(a)){var d=[],f=this[0],e,i={},j;if(f&&a.length){e=0;for(var n=a.length;e<n;e++){j=a[e];i[j]||(i[j]=c.expr.match.POS.test(j)?c(j,b||this.context):j)}for(;f&&f.ownerDocument&&f!==b;){for(j in i){e=i[j];if(e.jquery?e.index(f)>
-1:c(f).is(e)){d.push({selector:j,elem:f});delete i[j]}}f=f.parentNode}}return d}var o=c.expr.match.POS.test(a)?c(a,b||this.context):null;return this.map(function(m,s){for(;s&&s.ownerDocument&&s!==b;){if(o?o.index(s)>-1:c(s).is(a))return s;s=s.parentNode}return null})},index:function(a){if(!a||typeof a==="string")return c.inArray(this[0],a?c(a):this.parent().children());return c.inArray(a.jquery?a[0]:a,this)},add:function(a,b){a=typeof a==="string"?c(a,b||this.context):c.makeArray(a);b=c.merge(this.get(),
a);return this.pushStack(pa(a[0])||pa(b[0])?b:c.unique(b))},andSelf:function(){return this.add(this.prevObject)}});c.each({parent:function(a){return(a=a.parentNode)&&a.nodeType!==11?a:null},parents:function(a){return c.dir(a,"parentNode")},parentsUntil:function(a,b,d){return c.dir(a,"parentNode",d)},next:function(a){return c.nth(a,2,"nextSibling")},prev:function(a){return c.nth(a,2,"previousSibling")},nextAll:function(a){return c.dir(a,"nextSibling")},prevAll:function(a){return c.dir(a,"previousSibling")},
nextUntil:function(a,b,d){return c.dir(a,"nextSibling",d)},prevUntil:function(a,b,d){return c.dir(a,"previousSibling",d)},siblings:function(a){return c.sibling(a.parentNode.firstChild,a)},children:function(a){return c.sibling(a.firstChild)},contents:function(a){return c.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:c.makeArray(a.childNodes)}},function(a,b){c.fn[a]=function(d,f){var e=c.map(this,b,d);bb.test(a)||(f=d);if(f&&typeof f==="string")e=c.filter(f,e);e=this.length>1?c.unique(e):
e;if((this.length>1||db.test(f))&&cb.test(a))e=e.reverse();return this.pushStack(e,a,Q.call(arguments).join(","))}});c.extend({filter:function(a,b,d){if(d)a=":not("+a+")";return c.find.matches(a,b)},dir:function(a,b,d){var f=[];for(a=a[b];a&&a.nodeType!==9&&(d===v||a.nodeType!==1||!c(a).is(d));){a.nodeType===1&&f.push(a);a=a[b]}return f},nth:function(a,b,d){b=b||1;for(var f=0;a;a=a[d])if(a.nodeType===1&&++f===b)break;return a},sibling:function(a,b){for(var d=[];a;a=a.nextSibling)a.nodeType===1&&a!==
b&&d.push(a);return d}});var Fa=/ jQuery\d+="(?:\d+|null)"/g,V=/^\s+/,Ga=/(<([\w:]+)[^>]*?)\/>/g,eb=/^(?:area|br|col|embed|hr|img|input|link|meta|param)$/i,Ha=/<([\w:]+)/,fb=/<tbody/i,gb=/<|&\w+;/,sa=/checked\s*(?:[^=]|=\s*.checked.)/i,Ia=function(a,b,d){return eb.test(d)?a:b+"></"+d+">"},F={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],
col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]};F.optgroup=F.option;F.tbody=F.tfoot=F.colgroup=F.caption=F.thead;F.th=F.td;if(!c.support.htmlSerialize)F._default=[1,"div<div>","</div>"];c.fn.extend({text:function(a){if(c.isFunction(a))return this.each(function(b){var d=c(this);d.text(a.call(this,b,d.text()))});if(typeof a!=="object"&&a!==v)return this.empty().append((this[0]&&this[0].ownerDocument||r).createTextNode(a));return c.getText(this)},
wrapAll:function(a){if(c.isFunction(a))return this.each(function(d){c(this).wrapAll(a.call(this,d))});if(this[0]){var b=c(a,this[0].ownerDocument).eq(0).clone(true);this[0].parentNode&&b.insertBefore(this[0]);b.map(function(){for(var d=this;d.firstChild&&d.firstChild.nodeType===1;)d=d.firstChild;return d}).append(this)}return this},wrapInner:function(a){if(c.isFunction(a))return this.each(function(b){c(this).wrapInner(a.call(this,b))});return this.each(function(){var b=c(this),d=b.contents();d.length?
d.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){c(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){c.nodeName(this,"body")||c(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,
false,function(b){this.parentNode.insertBefore(b,this)});else if(arguments.length){var a=c(arguments[0]);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,this.nextSibling)});else if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,c(arguments[0]).toArray());return a}},clone:function(a){var b=this.map(function(){if(!c.support.noCloneEvent&&
!c.isXMLDoc(this)){var d=this.outerHTML,f=this.ownerDocument;if(!d){d=f.createElement("div");d.appendChild(this.cloneNode(true));d=d.innerHTML}return c.clean([d.replace(Fa,"").replace(V,"")],f)[0]}else return this.cloneNode(true)});if(a===true){qa(this,b);qa(this.find("*"),b.find("*"))}return b},html:function(a){if(a===v)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(Fa,""):null;else if(typeof a==="string"&&!/<script/i.test(a)&&(c.support.leadingWhitespace||!V.test(a))&&!F[(Ha.exec(a)||
["",""])[1].toLowerCase()]){a=a.replace(Ga,Ia);try{for(var b=0,d=this.length;b<d;b++)if(this[b].nodeType===1){c.cleanData(this[b].getElementsByTagName("*"));this[b].innerHTML=a}}catch(f){this.empty().append(a)}}else c.isFunction(a)?this.each(function(e){var i=c(this),j=i.html();i.empty().append(function(){return a.call(this,e,j)})}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(c.isFunction(a))return this.each(function(b){var d=c(this),f=d.html();d.replaceWith(a.call(this,
b,f))});else a=c(a).detach();return this.each(function(){var b=this.nextSibling,d=this.parentNode;c(this).remove();b?c(b).before(a):c(d).append(a)})}else return this.pushStack(c(c.isFunction(a)?a():a),"replaceWith",a)},detach:function(a){return this.remove(a,true)},domManip:function(a,b,d){function f(s){return c.nodeName(s,"table")?s.getElementsByTagName("tbody")[0]||s.appendChild(s.ownerDocument.createElement("tbody")):s}var e,i,j=a[0],n=[];if(!c.support.checkClone&&arguments.length===3&&typeof j===
"string"&&sa.test(j))return this.each(function(){c(this).domManip(a,b,d,true)});if(c.isFunction(j))return this.each(function(s){var x=c(this);a[0]=j.call(this,s,b?x.html():v);x.domManip(a,b,d)});if(this[0]){e=a[0]&&a[0].parentNode&&a[0].parentNode.nodeType===11?{fragment:a[0].parentNode}:ra(a,this,n);if(i=e.fragment.firstChild){b=b&&c.nodeName(i,"tr");for(var o=0,m=this.length;o<m;o++)d.call(b?f(this[o],i):this[o],e.cacheable||this.length>1||o>0?e.fragment.cloneNode(true):e.fragment)}n&&c.each(n,
Ma)}return this}});c.fragments={};c.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){c.fn[a]=function(d){var f=[];d=c(d);for(var e=0,i=d.length;e<i;e++){var j=(e>0?this.clone(true):this).get();c.fn[b].apply(c(d[e]),j);f=f.concat(j)}return this.pushStack(f,a,d.selector)}});c.each({remove:function(a,b){if(!a||c.filter(a,[this]).length){if(!b&&this.nodeType===1){c.cleanData(this.getElementsByTagName("*"));c.cleanData([this])}this.parentNode&&
this.parentNode.removeChild(this)}},empty:function(){for(this.nodeType===1&&c.cleanData(this.getElementsByTagName("*"));this.firstChild;)this.removeChild(this.firstChild)}},function(a,b){c.fn[a]=function(){return this.each(b,arguments)}});c.extend({clean:function(a,b,d,f){b=b||r;if(typeof b.createElement==="undefined")b=b.ownerDocument||b[0]&&b[0].ownerDocument||r;var e=[];c.each(a,function(i,j){if(typeof j==="number")j+="";if(j){if(typeof j==="string"&&!gb.test(j))j=b.createTextNode(j);else if(typeof j===
"string"){j=j.replace(Ga,Ia);var n=(Ha.exec(j)||["",""])[1].toLowerCase(),o=F[n]||F._default,m=o[0];i=b.createElement("div");for(i.innerHTML=o[1]+j+o[2];m--;)i=i.lastChild;if(!c.support.tbody){m=fb.test(j);n=n==="table"&&!m?i.firstChild&&i.firstChild.childNodes:o[1]==="<table>"&&!m?i.childNodes:[];for(o=n.length-1;o>=0;--o)c.nodeName(n[o],"tbody")&&!n[o].childNodes.length&&n[o].parentNode.removeChild(n[o])}!c.support.leadingWhitespace&&V.test(j)&&i.insertBefore(b.createTextNode(V.exec(j)[0]),i.firstChild);
j=c.makeArray(i.childNodes)}if(j.nodeType)e.push(j);else e=c.merge(e,j)}});if(d)for(a=0;e[a];a++)if(f&&c.nodeName(e[a],"script")&&(!e[a].type||e[a].type.toLowerCase()==="text/javascript"))f.push(e[a].parentNode?e[a].parentNode.removeChild(e[a]):e[a]);else{e[a].nodeType===1&&e.splice.apply(e,[a+1,0].concat(c.makeArray(e[a].getElementsByTagName("script"))));d.appendChild(e[a])}return e},cleanData:function(a){for(var b=0,d;(d=a[b])!=null;b++){c.event.remove(d);c.removeData(d)}}});var hb=/z-?index|font-?weight|opacity|zoom|line-?height/i,
Ja=/alpha\([^)]*\)/,Ka=/opacity=([^)]*)/,ga=/float/i,ha=/-([a-z])/ig,ib=/([A-Z])/g,jb=/^-?\d+(?:px)?$/i,kb=/^-?\d/,lb={position:"absolute",visibility:"hidden",display:"block"},mb=["Left","Right"],nb=["Top","Bottom"],ob=r.defaultView&&r.defaultView.getComputedStyle,La=c.support.cssFloat?"cssFloat":"styleFloat",ia=function(a,b){return b.toUpperCase()};c.fn.css=function(a,b){return X(this,a,b,true,function(d,f,e){if(e===v)return c.curCSS(d,f);if(typeof e==="number"&&!hb.test(f))e+="px";c.style(d,f,e)})};
c.extend({style:function(a,b,d){if(!a||a.nodeType===3||a.nodeType===8)return v;if((b==="width"||b==="height")&&parseFloat(d)<0)d=v;var f=a.style||a,e=d!==v;if(!c.support.opacity&&b==="opacity"){if(e){f.zoom=1;b=parseInt(d,10)+""==="NaN"?"":"alpha(opacity="+d*100+")";a=f.filter||c.curCSS(a,"filter")||"";f.filter=Ja.test(a)?a.replace(Ja,b):b}return f.filter&&f.filter.indexOf("opacity=")>=0?parseFloat(Ka.exec(f.filter)[1])/100+"":""}if(ga.test(b))b=La;b=b.replace(ha,ia);if(e)f[b]=d;return f[b]},css:function(a,
b,d,f){if(b==="width"||b==="height"){var e,i=b==="width"?mb:nb;function j(){e=b==="width"?a.offsetWidth:a.offsetHeight;f!=="border"&&c.each(i,function(){f||(e-=parseFloat(c.curCSS(a,"padding"+this,true))||0);if(f==="margin")e+=parseFloat(c.curCSS(a,"margin"+this,true))||0;else e-=parseFloat(c.curCSS(a,"border"+this+"Width",true))||0})}a.offsetWidth!==0?j():c.swap(a,lb,j);return Math.max(0,Math.round(e))}return c.curCSS(a,b,d)},curCSS:function(a,b,d){var f,e=a.style;if(!c.support.opacity&&b==="opacity"&&
a.currentStyle){f=Ka.test(a.currentStyle.filter||"")?parseFloat(RegExp.$1)/100+"":"";return f===""?"1":f}if(ga.test(b))b=La;if(!d&&e&&e[b])f=e[b];else if(ob){if(ga.test(b))b="float";b=b.replace(ib,"-$1").toLowerCase();e=a.ownerDocument.defaultView;if(!e)return null;if(a=e.getComputedStyle(a,null))f=a.getPropertyValue(b);if(b==="opacity"&&f==="")f="1"}else if(a.currentStyle){d=b.replace(ha,ia);f=a.currentStyle[b]||a.currentStyle[d];if(!jb.test(f)&&kb.test(f)){b=e.left;var i=a.runtimeStyle.left;a.runtimeStyle.left=
a.currentStyle.left;e.left=d==="fontSize"?"1em":f||0;f=e.pixelLeft+"px";e.left=b;a.runtimeStyle.left=i}}return f},swap:function(a,b,d){var f={};for(var e in b){f[e]=a.style[e];a.style[e]=b[e]}d.call(a);for(e in b)a.style[e]=f[e]}});if(c.expr&&c.expr.filters){c.expr.filters.hidden=function(a){var b=a.offsetWidth,d=a.offsetHeight,f=a.nodeName.toLowerCase()==="tr";return b===0&&d===0&&!f?true:b>0&&d>0&&!f?false:c.curCSS(a,"display")==="none"};c.expr.filters.visible=function(a){return!c.expr.filters.hidden(a)}}var pb=
J(),qb=/<script(.|\s)*?\/script>/gi,rb=/select|textarea/i,sb=/color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week/i,N=/=\?(&|$)/,ja=/\?/,tb=/(\?|&)_=.*?(&|$)/,ub=/^(\w+:)?\/\/([^\/?#]+)/,vb=/%20/g;c.fn.extend({_load:c.fn.load,load:function(a,b,d){if(typeof a!=="string")return this._load(a);else if(!this.length)return this;var f=a.indexOf(" ");if(f>=0){var e=a.slice(f,a.length);a=a.slice(0,f)}f="GET";if(b)if(c.isFunction(b)){d=b;b=null}else if(typeof b==="object"){b=
c.param(b,c.ajaxSettings.traditional);f="POST"}var i=this;c.ajax({url:a,type:f,dataType:"html",data:b,complete:function(j,n){if(n==="success"||n==="notmodified")i.html(e?c("<div />").append(j.responseText.replace(qb,"")).find(e):j.responseText);d&&i.each(d,[j.responseText,n,j])}});return this},serialize:function(){return c.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?c.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&
(this.checked||rb.test(this.nodeName)||sb.test(this.type))}).map(function(a,b){a=c(this).val();return a==null?null:c.isArray(a)?c.map(a,function(d){return{name:b.name,value:d}}):{name:b.name,value:a}}).get()}});c.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){c.fn[b]=function(d){return this.bind(b,d)}});c.extend({get:function(a,b,d,f){if(c.isFunction(b)){f=f||d;d=b;b=null}return c.ajax({type:"GET",url:a,data:b,success:d,dataType:f})},getScript:function(a,
b){return c.get(a,null,b,"script")},getJSON:function(a,b,d){return c.get(a,b,d,"json")},post:function(a,b,d,f){if(c.isFunction(b)){f=f||d;d=b;b={}}return c.ajax({type:"POST",url:a,data:b,success:d,dataType:f})},ajaxSetup:function(a){c.extend(c.ajaxSettings,a)},ajaxSettings:{url:location.href,global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:z.XMLHttpRequest&&(z.location.protocol!=="file:"||!z.ActiveXObject)?function(){return new z.XMLHttpRequest}:
function(){try{return new z.ActiveXObject("Microsoft.XMLHTTP")}catch(a){}},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},etag:{},ajax:function(a){function b(){e.success&&e.success.call(o,n,j,w);e.global&&f("ajaxSuccess",[w,e])}function d(){e.complete&&e.complete.call(o,w,j);e.global&&f("ajaxComplete",[w,e]);e.global&&!--c.active&&c.event.trigger("ajaxStop")}
function f(q,p){(e.context?c(e.context):c.event).trigger(q,p)}var e=c.extend(true,{},c.ajaxSettings,a),i,j,n,o=a&&a.context||e,m=e.type.toUpperCase();if(e.data&&e.processData&&typeof e.data!=="string")e.data=c.param(e.data,e.traditional);if(e.dataType==="jsonp"){if(m==="GET")N.test(e.url)||(e.url+=(ja.test(e.url)?"&":"?")+(e.jsonp||"callback")+"=?");else if(!e.data||!N.test(e.data))e.data=(e.data?e.data+"&":"")+(e.jsonp||"callback")+"=?";e.dataType="json"}if(e.dataType==="json"&&(e.data&&N.test(e.data)||
N.test(e.url))){i=e.jsonpCallback||"jsonp"+pb++;if(e.data)e.data=(e.data+"").replace(N,"="+i+"$1");e.url=e.url.replace(N,"="+i+"$1");e.dataType="script";z[i]=z[i]||function(q){n=q;b();d();z[i]=v;try{delete z[i]}catch(p){}A&&A.removeChild(B)}}if(e.dataType==="script"&&e.cache===null)e.cache=false;if(e.cache===false&&m==="GET"){var s=J(),x=e.url.replace(tb,"$1_="+s+"$2");e.url=x+(x===e.url?(ja.test(e.url)?"&":"?")+"_="+s:"")}if(e.data&&m==="GET")e.url+=(ja.test(e.url)?"&":"?")+e.data;e.global&&!c.active++&&
c.event.trigger("ajaxStart");s=(s=ub.exec(e.url))&&(s[1]&&s[1]!==location.protocol||s[2]!==location.host);if(e.dataType==="script"&&m==="GET"&&s){var A=r.getElementsByTagName("head")[0]||r.documentElement,B=r.createElement("script");B.src=e.url;if(e.scriptCharset)B.charset=e.scriptCharset;if(!i){var C=false;B.onload=B.onreadystatechange=function(){if(!C&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete")){C=true;b();d();B.onload=B.onreadystatechange=null;A&&B.parentNode&&
A.removeChild(B)}}}A.insertBefore(B,A.firstChild);return v}var E=false,w=e.xhr();if(w){e.username?w.open(m,e.url,e.async,e.username,e.password):w.open(m,e.url,e.async);try{if(e.data||a&&a.contentType)w.setRequestHeader("Content-Type",e.contentType);if(e.ifModified){c.lastModified[e.url]&&w.setRequestHeader("If-Modified-Since",c.lastModified[e.url]);c.etag[e.url]&&w.setRequestHeader("If-None-Match",c.etag[e.url])}s||w.setRequestHeader("X-Requested-With","XMLHttpRequest");w.setRequestHeader("Accept",
e.dataType&&e.accepts[e.dataType]?e.accepts[e.dataType]+", */*":e.accepts._default)}catch(fa){}if(e.beforeSend&&e.beforeSend.call(o,w,e)===false){e.global&&!--c.active&&c.event.trigger("ajaxStop");w.abort();return false}e.global&&f("ajaxSend",[w,e]);var g=w.onreadystatechange=function(q){if(!w||w.readyState===0||q==="abort"){E||d();E=true;if(w)w.onreadystatechange=c.noop}else if(!E&&w&&(w.readyState===4||q==="timeout")){E=true;w.onreadystatechange=c.noop;j=q==="timeout"?"timeout":!c.httpSuccess(w)?
"error":e.ifModified&&c.httpNotModified(w,e.url)?"notmodified":"success";var p;if(j==="success")try{n=c.httpData(w,e.dataType,e)}catch(u){j="parsererror";p=u}if(j==="success"||j==="notmodified")i||b();else c.handleError(e,w,j,p);d();q==="timeout"&&w.abort();if(e.async)w=null}};try{var h=w.abort;w.abort=function(){w&&h.call(w);g("abort")}}catch(k){}e.async&&e.timeout>0&&setTimeout(function(){w&&!E&&g("timeout")},e.timeout);try{w.send(m==="POST"||m==="PUT"||m==="DELETE"?e.data:null)}catch(l){c.handleError(e,
w,null,l);d()}e.async||g();return w}},handleError:function(a,b,d,f){if(a.error)a.error.call(a.context||a,b,d,f);if(a.global)(a.context?c(a.context):c.event).trigger("ajaxError",[b,a,f])},active:0,httpSuccess:function(a){try{return!a.status&&location.protocol==="file:"||a.status>=200&&a.status<300||a.status===304||a.status===1223||a.status===0}catch(b){}return false},httpNotModified:function(a,b){var d=a.getResponseHeader("Last-Modified"),f=a.getResponseHeader("Etag");if(d)c.lastModified[b]=d;if(f)c.etag[b]=
f;return a.status===304||a.status===0},httpData:function(a,b,d){var f=a.getResponseHeader("content-type")||"",e=b==="xml"||!b&&f.indexOf("xml")>=0;a=e?a.responseXML:a.responseText;e&&a.documentElement.nodeName==="parsererror"&&c.error("parsererror");if(d&&d.dataFilter)a=d.dataFilter(a,b);if(typeof a==="string")if(b==="json"||!b&&f.indexOf("json")>=0)a=c.parseJSON(a);else if(b==="script"||!b&&f.indexOf("javascript")>=0)c.globalEval(a);return a},param:function(a,b){function d(j,n){if(c.isArray(n))c.each(n,
function(o,m){b?f(j,m):d(j+"["+(typeof m==="object"||c.isArray(m)?o:"")+"]",m)});else!b&&n!=null&&typeof n==="object"?c.each(n,function(o,m){d(j+"["+o+"]",m)}):f(j,n)}function f(j,n){n=c.isFunction(n)?n():n;e[e.length]=encodeURIComponent(j)+"="+encodeURIComponent(n)}var e=[];if(b===v)b=c.ajaxSettings.traditional;if(c.isArray(a)||a.jquery)c.each(a,function(){f(this.name,this.value)});else for(var i in a)d(i,a[i]);return e.join("&").replace(vb,"+")}});var ka={},wb=/toggle|show|hide/,xb=/^([+-]=)?([\d+-.]+)(.*)$/,
W,ta=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];c.fn.extend({show:function(a,b){if(a||a===0)return this.animate(K("show",3),a,b);else{a=0;for(b=this.length;a<b;a++){var d=c.data(this[a],"olddisplay");this[a].style.display=d||"";if(c.css(this[a],"display")==="none"){d=this[a].nodeName;var f;if(ka[d])f=ka[d];else{var e=c("<"+d+" />").appendTo("body");f=e.css("display");if(f==="none")f="block";e.remove();
ka[d]=f}c.data(this[a],"olddisplay",f)}}a=0;for(b=this.length;a<b;a++)this[a].style.display=c.data(this[a],"olddisplay")||"";return this}},hide:function(a,b){if(a||a===0)return this.animate(K("hide",3),a,b);else{a=0;for(b=this.length;a<b;a++){var d=c.data(this[a],"olddisplay");!d&&d!=="none"&&c.data(this[a],"olddisplay",c.css(this[a],"display"))}a=0;for(b=this.length;a<b;a++)this[a].style.display="none";return this}},_toggle:c.fn.toggle,toggle:function(a,b){var d=typeof a==="boolean";if(c.isFunction(a)&&
c.isFunction(b))this._toggle.apply(this,arguments);else a==null||d?this.each(function(){var f=d?a:c(this).is(":hidden");c(this)[f?"show":"hide"]()}):this.animate(K("toggle",3),a,b);return this},fadeTo:function(a,b,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,d)},animate:function(a,b,d,f){var e=c.speed(b,d,f);if(c.isEmptyObject(a))return this.each(e.complete);return this[e.queue===false?"each":"queue"](function(){var i=c.extend({},e),j,n=this.nodeType===1&&c(this).is(":hidden"),
o=this;for(j in a){var m=j.replace(ha,ia);if(j!==m){a[m]=a[j];delete a[j];j=m}if(a[j]==="hide"&&n||a[j]==="show"&&!n)return i.complete.call(this);if((j==="height"||j==="width")&&this.style){i.display=c.css(this,"display");i.overflow=this.style.overflow}if(c.isArray(a[j])){(i.specialEasing=i.specialEasing||{})[j]=a[j][1];a[j]=a[j][0]}}if(i.overflow!=null)this.style.overflow="hidden";i.curAnim=c.extend({},a);c.each(a,function(s,x){var A=new c.fx(o,i,s);if(wb.test(x))A[x==="toggle"?n?"show":"hide":x](a);
else{var B=xb.exec(x),C=A.cur(true)||0;if(B){x=parseFloat(B[2]);var E=B[3]||"px";if(E!=="px"){o.style[s]=(x||1)+E;C=(x||1)/A.cur(true)*C;o.style[s]=C+E}if(B[1])x=(B[1]==="-="?-1:1)*x+C;A.custom(C,x,E)}else A.custom(C,x,"")}});return true})},stop:function(a,b){var d=c.timers;a&&this.queue([]);this.each(function(){for(var f=d.length-1;f>=0;f--)if(d[f].elem===this){b&&d[f](true);d.splice(f,1)}});b||this.dequeue();return this}});c.each({slideDown:K("show",1),slideUp:K("hide",1),slideToggle:K("toggle",
1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(a,b){c.fn[a]=function(d,f){return this.animate(b,d,f)}});c.extend({speed:function(a,b,d){var f=a&&typeof a==="object"?a:{complete:d||!d&&b||c.isFunction(a)&&a,duration:a,easing:d&&b||b&&!c.isFunction(b)&&b};f.duration=c.fx.off?0:typeof f.duration==="number"?f.duration:c.fx.speeds[f.duration]||c.fx.speeds._default;f.old=f.complete;f.complete=function(){f.queue!==false&&c(this).dequeue();c.isFunction(f.old)&&f.old.call(this)};return f},easing:{linear:function(a,
b,d,f){return d+f*a},swing:function(a,b,d,f){return(-Math.cos(a*Math.PI)/2+0.5)*f+d}},timers:[],fx:function(a,b,d){this.options=b;this.elem=a;this.prop=d;if(!b.orig)b.orig={}}});c.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this);(c.fx.step[this.prop]||c.fx.step._default)(this);if((this.prop==="height"||this.prop==="width")&&this.elem.style)this.elem.style.display="block"},cur:function(a){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==
null))return this.elem[this.prop];return(a=parseFloat(c.css(this.elem,this.prop,a)))&&a>-10000?a:parseFloat(c.curCSS(this.elem,this.prop))||0},custom:function(a,b,d){function f(i){return e.step(i)}this.startTime=J();this.start=a;this.end=b;this.unit=d||this.unit||"px";this.now=this.start;this.pos=this.state=0;var e=this;f.elem=this.elem;if(f()&&c.timers.push(f)&&!W)W=setInterval(c.fx.tick,13)},show:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.show=true;this.custom(this.prop===
"width"||this.prop==="height"?1:0,this.cur());c(this.elem).show()},hide:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(a){var b=J(),d=true;if(a||b>=this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;for(var f in this.options.curAnim)if(this.options.curAnim[f]!==true)d=false;if(d){if(this.options.display!=null){this.elem.style.overflow=
this.options.overflow;a=c.data(this.elem,"olddisplay");this.elem.style.display=a?a:this.options.display;if(c.css(this.elem,"display")==="none")this.elem.style.display="block"}this.options.hide&&c(this.elem).hide();if(this.options.hide||this.options.show)for(var e in this.options.curAnim)c.style(this.elem,e,this.options.orig[e]);this.options.complete.call(this.elem)}return false}else{e=b-this.startTime;this.state=e/this.options.duration;a=this.options.easing||(c.easing.swing?"swing":"linear");this.pos=
c.easing[this.options.specialEasing&&this.options.specialEasing[this.prop]||a](this.state,e,0,1,this.options.duration);this.now=this.start+(this.end-this.start)*this.pos;this.update()}return true}};c.extend(c.fx,{tick:function(){for(var a=c.timers,b=0;b<a.length;b++)a[b]()||a.splice(b--,1);a.length||c.fx.stop()},stop:function(){clearInterval(W);W=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){c.style(a.elem,"opacity",a.now)},_default:function(a){if(a.elem.style&&a.elem.style[a.prop]!=
null)a.elem.style[a.prop]=(a.prop==="width"||a.prop==="height"?Math.max(0,a.now):a.now)+a.unit;else a.elem[a.prop]=a.now}}});if(c.expr&&c.expr.filters)c.expr.filters.animated=function(a){return c.grep(c.timers,function(b){return a===b.elem}).length};c.fn.offset="getBoundingClientRect"in r.documentElement?function(a){var b=this[0];if(a)return this.each(function(e){c.offset.setOffset(this,a,e)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);var d=b.getBoundingClientRect(),
f=b.ownerDocument;b=f.body;f=f.documentElement;return{top:d.top+(self.pageYOffset||c.support.boxModel&&f.scrollTop||b.scrollTop)-(f.clientTop||b.clientTop||0),left:d.left+(self.pageXOffset||c.support.boxModel&&f.scrollLeft||b.scrollLeft)-(f.clientLeft||b.clientLeft||0)}}:function(a){var b=this[0];if(a)return this.each(function(s){c.offset.setOffset(this,a,s)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);c.offset.initialize();var d=b.offsetParent,f=
b,e=b.ownerDocument,i,j=e.documentElement,n=e.body;f=(e=e.defaultView)?e.getComputedStyle(b,null):b.currentStyle;for(var o=b.offsetTop,m=b.offsetLeft;(b=b.parentNode)&&b!==n&&b!==j;){if(c.offset.supportsFixedPosition&&f.position==="fixed")break;i=e?e.getComputedStyle(b,null):b.currentStyle;o-=b.scrollTop;m-=b.scrollLeft;if(b===d){o+=b.offsetTop;m+=b.offsetLeft;if(c.offset.doesNotAddBorder&&!(c.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(b.nodeName))){o+=parseFloat(i.borderTopWidth)||
0;m+=parseFloat(i.borderLeftWidth)||0}f=d;d=b.offsetParent}if(c.offset.subtractsBorderForOverflowNotVisible&&i.overflow!=="visible"){o+=parseFloat(i.borderTopWidth)||0;m+=parseFloat(i.borderLeftWidth)||0}f=i}if(f.position==="relative"||f.position==="static"){o+=n.offsetTop;m+=n.offsetLeft}if(c.offset.supportsFixedPosition&&f.position==="fixed"){o+=Math.max(j.scrollTop,n.scrollTop);m+=Math.max(j.scrollLeft,n.scrollLeft)}return{top:o,left:m}};c.offset={initialize:function(){var a=r.body,b=r.createElement("div"),
d,f,e,i=parseFloat(c.curCSS(a,"marginTop",true))||0;c.extend(b.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"});b.innerHTML="<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";a.insertBefore(b,a.firstChild);
d=b.firstChild;f=d.firstChild;e=d.nextSibling.firstChild.firstChild;this.doesNotAddBorder=f.offsetTop!==5;this.doesAddBorderForTableAndCells=e.offsetTop===5;f.style.position="fixed";f.style.top="20px";this.supportsFixedPosition=f.offsetTop===20||f.offsetTop===15;f.style.position=f.style.top="";d.style.overflow="hidden";d.style.position="relative";this.subtractsBorderForOverflowNotVisible=f.offsetTop===-5;this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==i;a.removeChild(b);c.offset.initialize=c.noop},
bodyOffset:function(a){var b=a.offsetTop,d=a.offsetLeft;c.offset.initialize();if(c.offset.doesNotIncludeMarginInBodyOffset){b+=parseFloat(c.curCSS(a,"marginTop",true))||0;d+=parseFloat(c.curCSS(a,"marginLeft",true))||0}return{top:b,left:d}},setOffset:function(a,b,d){if(/static/.test(c.curCSS(a,"position")))a.style.position="relative";var f=c(a),e=f.offset(),i=parseInt(c.curCSS(a,"top",true),10)||0,j=parseInt(c.curCSS(a,"left",true),10)||0;if(c.isFunction(b))b=b.call(a,d,e);d={top:b.top-e.top+i,left:b.left-
e.left+j};"using"in b?b.using.call(a,d):f.css(d)}};c.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),d=this.offset(),f=/^body|html$/i.test(b[0].nodeName)?{top:0,left:0}:b.offset();d.top-=parseFloat(c.curCSS(a,"marginTop",true))||0;d.left-=parseFloat(c.curCSS(a,"marginLeft",true))||0;f.top+=parseFloat(c.curCSS(b[0],"borderTopWidth",true))||0;f.left+=parseFloat(c.curCSS(b[0],"borderLeftWidth",true))||0;return{top:d.top-f.top,left:d.left-f.left}},offsetParent:function(){return this.map(function(){for(var a=
this.offsetParent||r.body;a&&!/^body|html$/i.test(a.nodeName)&&c.css(a,"position")==="static";)a=a.offsetParent;return a})}});c.each(["Left","Top"],function(a,b){var d="scroll"+b;c.fn[d]=function(f){var e=this[0],i;if(!e)return null;if(f!==v)return this.each(function(){if(i=ua(this))i.scrollTo(!a?f:c(i).scrollLeft(),a?f:c(i).scrollTop());else this[d]=f});else return(i=ua(e))?"pageXOffset"in i?i[a?"pageYOffset":"pageXOffset"]:c.support.boxModel&&i.document.documentElement[d]||i.document.body[d]:e[d]}});
c.each(["Height","Width"],function(a,b){var d=b.toLowerCase();c.fn["inner"+b]=function(){return this[0]?c.css(this[0],d,false,"padding"):null};c.fn["outer"+b]=function(f){return this[0]?c.css(this[0],d,false,f?"margin":"border"):null};c.fn[d]=function(f){var e=this[0];if(!e)return f==null?null:this;if(c.isFunction(f))return this.each(function(i){var j=c(this);j[d](f.call(this,i,j[d]()))});return"scrollTo"in e&&e.document?e.document.compatMode==="CSS1Compat"&&e.document.documentElement["client"+b]||
e.document.body["client"+b]:e.nodeType===9?Math.max(e.documentElement["client"+b],e.body["scroll"+b],e.documentElement["scroll"+b],e.body["offset"+b],e.documentElement["offset"+b]):f===v?c.css(e,d):this.css(d,typeof f==="string"?f:f+"px")}});z.jQuery=z.$=c})(window);
$(".actions-hover").append($('<li style="margin-left:5px"><span class="classicrt_icon">♲ </span><a href="#" class="classicrt"> Classic RT</a></li>'));
$(".classicrt").mouseover(function (e) {
$(this).siblings(".classicrt_icon").text("♻ ");
});
$(".classicrt").mouseout(function (e) {
$(this).siblings(".classicrt_icon").text("♲ ");
});
$(".classicrt").click( function(e) {
var tweeter = $(this).parents(".status-body").children().children(":first").text();
var tweet = $(this).parents(".status-body").children().children(".entry-content").text();
tweet.substr(1, tweet.length -1); // strip ""
$("#status").attr("value", "RT @"+tweeter+" "+tweet);
});
| nathanielksmith/classicrt | grease/tabtweet.user.js | JavaScript | artistic-2.0 | 71,750 |
# Shamelessly stolen from http://github.com/masak/yapsi/blob/master/Makefile
# With alpha replaced with perl6 & SOURCES changed to my sources.
PERL6 = perl6
SOURCES=lib/SIC/AST.pm lib/SIC/Grammar.pm \
lib/SIC/Actions.pm lib/SIC/Compiler.pm
PIRS=$(SOURCES:.pm=.pir)
all: $(PIRS)
%.pir: %.pm
env PERL6LIB=`pwd`/lib $(PERL6) --target=pir --output=$@ $<
clean:
rm -f $(PIRS)
test: all
env PERL6LIB=`pwd`/lib prove -e '$(PERL6)' -r --nocolor t/
| ekiru/Bennu | Makefile | Makefile | artistic-2.0 | 451 |
# GitURL
GitURL represents something that can be passed to `git clone`.
## clone
>method clone([Str](./Str.md) **:$to** ⟶ [File](./File.md))
Calls `git clone` on the the url and returns the path to the cloned directory.
```perl6
GitURL<https://github.com/spitsh/spitsh.git/>.clone.cd;
say ${ $*git status };
```
|Parameter|Description|
|---------|-----------|
|**:$to**| Path to clone the repo to|
## name
>method name( ⟶ [Str](./Str.md))
Gets the last section of the url without its extension. This is the same as directory name git will use to clone into by default.
```perl6
say GitURL<https://github.com/nodejs/node.git>.name #->node
```
| spitsh/spitsh | doc/classes/GitURL.md | Markdown | artistic-2.0 | 653 |
// (c) Jean Fabre, 2011-2013 All rights reserved.
// http://www.fabrejean.net
// contact: http://www.fabrejean.net/contact.htm
//
// Version Alpha 0.92
// INSTRUCTIONS
// Drop a PlayMakerArrayList script onto a GameObject, and define a unique name for reference if several PlayMakerArrayList coexists on that GameObject.
// In this Action interface, link that GameObject in "arrayListObject" and input the reference name if defined.
// Note: You can directly reference that GameObject or store it in an Fsm variable or global Fsm variable
using UnityEngine;
namespace HutongGames.PlayMaker.Actions
{
[ActionCategory("ArrayMaker/ArrayList")]
[Tooltip("Set an item at a specified index to a PlayMaker array List component")]
public class ArrayListSet : ArrayListActions
{
[ActionSection("Set up")]
[RequiredField]
[Tooltip("The gameObject with the PlayMaker ArrayList Proxy component")]
[CheckForComponent(typeof(PlayMakerArrayListProxy))]
public FsmOwnerDefault gameObject;
[Tooltip("Author defined Reference of the PlayMaker ArrayList Proxy component (necessary if several component coexists on the same GameObject)")]
[UIHint(UIHint.FsmString)]
public FsmString reference;
[Tooltip("The index of the Data in the ArrayList")]
[UIHint(UIHint.FsmString)]
public FsmInt atIndex;
public bool everyFrame;
[ActionSection("Data")]
[Tooltip("The variable to add.")]
public FsmVar variable;
public override void Reset()
{
gameObject = null;
reference = null;
variable = null;
everyFrame = false;
}
public override void OnEnter()
{
if ( SetUpArrayListProxyPointer(Fsm.GetOwnerDefaultTarget(gameObject),reference.Value) )
SetToArrayList();
if (!everyFrame){
Finish();
}
}
public override void OnUpdate()
{
SetToArrayList();
}
public void SetToArrayList()
{
if (! isProxyValid() ) return;
proxy.Set(atIndex.Value,PlayMakerUtils.GetValueFromFsmVar(Fsm,variable),variable.Type.ToString());
}
}
} | maxbottega/wheelie | Assets/PlayMaker ArrayMaker/Actions/ArrayList/ArrayListSet.cs | C# | artistic-2.0 | 2,041 |
#!/bin/sh
#------------------------------------------------------------------------------
#
# MyRPM - Rpm Utilities
# Copyright (c) Jean-Marie RENOUARD 2014 - LightPath
# Contact : Jean-Marie Renouard <jmrenouard at gmail.com>
#
# This program is open source, licensed under the Artistic Licence v2.0.
#
# Artistic Licence 2.0
# Everyone is permitted to copy and distribute verbatim copies of
# this license document, but changing it is not allowed.
#
#------------------------------------------------------------------------------
TMP_DIR=/tmp
MD5_SUM=$(echo "$1_$2" | md5sum | cut -d' ' -f 1)
TMP_FILE="$TMP_DIR/$MD5_SUM.dat"
if [ -e "$TMP_FILE" ]; then
DATE_TMP_FILE=$(stat -c '%Y' $TMP_FILE)
DATE=$(date +%s)
DIFF_DATE=$(echo "$DATE-$DATE_TMP_FILE"|bc)
if [ "$DIFF_DATE" -lt "200" ]; then
echo "$2:`cat $TMP_FILE`"
exit 0
fi
fi
#Recherche de la derniere version d'un repertoire
echo_last_installed_version() {
echo `ls -1tr -d $1/* | grep $2 | tail -n 1`
}
JAVA="$JAVA_HOME/bin/java JmxClient"
HOST="localhost"
PORT="7091"
ATTR="$2"
ATTR=`echo $2 | cut -d. -f1`
ELT=`echo $2 | cut -d. -f2`
result=`$JAVA $HOST $PORT $1 $ATTR`
if [ "$ATTR" != "$ELT" ]; then
result=`echo $result| cut -d{ -f2 | sed -e 's/})//' -e 's/ //g' -e 's/,/\n/g'| grep $ELT | cut -d= -f2`
fi
echo "$result" > $TMP_FILE
echo "$2:$result"
| jmrenouard/jmxclient | jmxClient.sh | Shell | artistic-2.0 | 1,345 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_292) on Fri Jul 02 03:47:37 UTC 2021 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>com.destroystokyo.paper (Glowkit 1.12.2-R6.0-SNAPSHOT API)</title>
<meta name="date" content="2021-07-02">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="com.destroystokyo.paper (Glowkit 1.12.2-R6.0-SNAPSHOT API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-all.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../co/aikar/util/package-summary.html">Prev Package</a></li>
<li><a href="../../../com/destroystokyo/paper/entity/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?com/destroystokyo/paper/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 title="Package" class="title">Package com.destroystokyo.paper</h1>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation">
<caption><span>Class Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Class</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../../com/destroystokyo/paper/ParticleBuilder.html" title="class in com.destroystokyo.paper">ParticleBuilder</a></td>
<td class="colLast">
<div class="block">Helps prepare a particle to be sent to players.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../com/destroystokyo/paper/Title.html" title="class in com.destroystokyo.paper">Title</a></td>
<td class="colLast">
<div class="block">Represents a title to may be sent to a <a href="../../../org/bukkit/entity/Player.html" title="interface in org.bukkit.entity"><code>Player</code></a>.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../com/destroystokyo/paper/Title.Builder.html" title="class in com.destroystokyo.paper">Title.Builder</a></td>
<td class="colLast">
<div class="block">A builder for creating titles</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Enum Summary table, listing enums, and an explanation">
<caption><span>Enum Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Enum</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../../com/destroystokyo/paper/VersionHistoryManager.html" title="enum in com.destroystokyo.paper">VersionHistoryManager</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-all.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../co/aikar/util/package-summary.html">Prev Package</a></li>
<li><a href="../../../com/destroystokyo/paper/entity/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?com/destroystokyo/paper/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2021. All rights reserved.</small></p>
</body>
</html>
| GlowstoneMC/glowstonemc.github.io | content/jd/glowkit/1.12/com/destroystokyo/paper/package-summary.html | HTML | artistic-2.0 | 6,298 |
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Transforms</title>
<style>
#threed-example {
margin: 50px 20px;
-webkit-transform: rotateZ(5deg);
-moz-transform: rotateZ(5deg);
-o-transform: rotateZ(5deg);
transform: rotateZ(5deg);
-webkit-transition: -webkit-transform 2s ease-in-out;
-moz-transition: -moz-transform 2s ease-in-out;
-o-transition: -o-transform 2s ease-in-out;
transition: transform 2s ease-in-out;
}
#threed-example:hover {
-webkit-transform: rotateZ(-5deg);
-moz-transform: rotateZ(-5deg);
-o-transform: rotateZ(-5deg);
transform: rotateZ(-5deg);
}
</style>
</head>
<body>
<div class="slide styling" id="css-transforms">
<header><span class="css">CSS</span> <h1>Transforms</h1></header>
<section>
<p class="center">
Hover over me:
</p>
<pre id="threed-example">-webkit-<b>transform</b>: <b>rotateY</b>(45deg);
-webkit-transform: <b>scaleX</b>(25deg);
-webkit-transform: <b>translate3d</b>(0, 0, 90deg);
-webkit-transform: <b>perspective</b>(500px)
</pre>
<pre>#threed-example {
-webkit-transform: rotateZ(5deg);
-webkit-transition: -webkit-transform 2s ease-in-out;
}
#threed-example:hover {
-webkit-transform: rotateZ(-5deg);
}
</pre>
<p class="center">
Now press <span class="key">3</span>!
</p>
</section>
</div>
</body>
</html> | kenu/oksample | html5/WebContent/css3/transform.html | HTML | artistic-2.0 | 1,465 |
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="chrome=1">
<title>De Mulierum Subtili Deceptione</title>
</head>
<body>
<!--XXVII De Mulierum Subtili Deceptione-->
<h4>The Subtle Deciption of a Woman</h4>
<p>
<!--
Darius regnavit prudens valde, qui tres filios habuit quos
multum dilexit. Cum vero mori deberet totam hereditatem
primogenito legavit; secundo filio dedit omnia quae in
tempore suo acquisivit; tertio filio, scilicet minori,
tria iocalia pretiosa dedit, scilicet anulum aureum,
monile et pannum pretiosum. Anulus illam virtutem habuit
quod qui ipsum in digito gestabat gratiam omnium habuit,
in tantum quod, quicquid ab eis peteret, obtineret; monile
illam virtutem habuit quod qui eum in pectore portabat,
quicquid cor suum desiderabat quod possibile esset,
obtineret. Pannus illam virtutem habuit quod, quicumque
super eum sederet et intra se cogitaret ubicumque esse
vellet, subito ibi esset.
-->
Once upon a time Darius reigned. He was highly learned,
and loved his three sons intensely. Indeed, when he was
about to die he bequeathed his entire inheritance to the
first-born; to the second he gave everything that he had
acquired in his lifetime; and to the third, the youngest
of course, he gave three costly possesions - a gold ring,
a necklace and a costly rug. The ring had the virtue
that whoever wore it on their finger had the goodwill of
all men, so much so, that whatsoever they might ask of
them, they would gain; the necklace had the virtue that
whoever carried it on their breast, whatever their heart
desired that might be possible, they would gain. The rug
had the virtue that, whoever might sit upon it and think
to themselves wherever they wished to be, they would
suddenly be there.
<!--
Ista tria iocalia dedit filio suo iuniori ut ad studium
pergeret et mater ea custodiret et tempore opportuno ei
daret; statimque rex spiritum emisit, qui honorifice
est sepultus. Duo primi filii eius legata occupabant,
tertius filius anulum a matre recepit ut ad studium
pergeret; cui mater dixit: "Fili, scientiam acquire et a
muliere caveas ne forte anulum perdas." Ionathas anulum
accepit, ad studium accessit et in scientia profecit.
-->
He gave these three possessions to his youngest son so
that he could proceed with his studies and that his
mother should watch over them and give them to him at an
opportune time; and at once the king gave up the ghost,
and was honorably buried. His first two sons seized
their legacies, while the third son recieved the ring
from his mother so that he might continue with his
studies. And his mother said to him: "Son, gain
learning, and may you avoid a woman, and not by chance
lose the ring." Jonathan accepted the ring, undertook
his studies and became accomplished in learning.
</p>
<p>
<!--
Post hoc cito quadam die in platea ei quaedam puella
occurrebat satis formosa et, captus eius amore, eam secum
duxit; continuo anulo utebatur et gratiam omnium habuit et
quicquid ab eis voluit habere obtinuit. Puella eius
concubina mirabatur quod tam laute viveret cum tamen
pecuniam non haberet; rationem quadam vice, cum laetus
esset, quaesivit, dicens quod creatura* sub caelo non
esset quam magis diligeret; ideo sibi dicere
deberet. Ille, de malitia non praemeditatus sibi, dixit
virtutem anuli esse talem, etc.
-->
Soon after this there came a day that he met a young
woman in the high street. She was pretty enough and,
seized with love, he led her away with him. He constantly
made use of the ring and had all goodwill and whatsoever
he wished to have of them he gained. The young woman,
now his concubine, marvelled that he lived so sumptuously
when he didn't have any money; and one day, when he was
in a good mood, she asked how it was, saying that there
was no creature under heaven who loved him more; and
therefore he should tell her. He, not considering malice
towards himself, told her that virtue of the ring was
such, etc.
<!--
At illa: "Cum singulis diebus cum hominibus conversare
soles, perdere posses; ideo custodiam tibi eum fideliter."
Qui tradidit ei anulum, sed cum repeteret, penuria ductus,
illa alta voce clamavit quod fures abstulissent; qui motus
flevit amare, quia unde viveret non habuit. Qui statim
ad reginam, matrem suam, est reversus denuntians ei anulum
perditum. At illa: "Fili mi, tibi praedixi ut a muliere te
caveres; ecce tibi iam trado monile quod diligentius
custodias; si perdideris, honore et commodo perpetuo
carebis." Ionathas monile recepit et ad idem studium est
reversus, et ecce concubina eius in porta civitatis
occurrit et cum gaudio eum recepit; ille, ut prius,
convivia multa habuit et laute vixit.
-->
But she said: "You are wont to keep company with men
every day, you might lose it; therefore I will faithfully
guard it for you." And he handed over the ring, but when
he returned, led by want, she cried out in a loud voice
that theives had carried it off; and he was agitated and
wept bitterly, for he didn't have the wherewithall to
live on. And he returned at once to his mother the queen,
and announced the loss of the ring to her. But she said:
"My son, I warned you to beware a woman. Look, I am now
handing over to you the necklace that you must guard
carefully; if you were to lose it, then you will lose
honor and profit forever." Jonathan accepted the
necklace and returned to his studies, and lo his
concubine met him at the gate of the city and received
him joyfully; and he, as before, had great banquets and
lived sumptuously.
</p>
<p>
<!--
Concubina mirabatur quia nec aurum nec argentum videbat, et
cogitabat quod aliud iocale apportasset, quod sagaciter ab
eo indagavit; qui ei monile ostendit et virtutem eius dixit.
Quae ait: "Semper monile tecum portas; una hora tantum
cogitare posses quod per annum sufficeret tibi; ideo trade
mihi ad custodiendum."
-->
The concubine marveled, for she saw neither gold nor silver, and
reflected that he had brought another possession, which she
shrewdly dug out from him; and he showed her the necklace and
told her of its virtue. And she said: "You always carry the
necklace with you; a single hour is enough for you to imagine
what would suffice you for a year; therefore hand it over to me
for safekeeping."
<!--
At ille: "Timeo quod sicut anulum perdidisti sic perderes monile
et sic damnum maximum incurrerem."
-->
But he said: "I'm afraid that, just as you lost the ring, so
might you lose the necklace, and so I would incur a very great
loss."
<!--
Quae ait: "O domine, iam per anulum scientiam acquisivi; unde
tibi fideliter promitto quod sic custodiam monile quod nullus
posset a me auferre."
-->
And she said: "O lord, I have already gotten experience from
the ring; from which I faithfully promise you that I will guard
the ring so well that no one could carry it away from me."
<!--
Ille credens dictis eius, monile ei tradidit. Postquam omnia
consumpta fuissent monile petiit; ilia, sicut prius, iuravit quod
furtive ablatum esset. Quod audiens Ionathas flevit amare et ait:
"Nonne sensum perdidi quod post anulum perditum monile tibi
tradidi!"
-->
Believing in her words, he handed the necklace over to her.
After everything had been used up he asked for the necklace;
but she, as before, swore that it had been furtively stolen
away. On hearing this Jonathan wept bitterly and said: "Surely
I have not lost the thought that, after losing the ring, I gave
you the necklace!"
</p>
<p>
<!--
Perrexit ad matrem et ei totum processum nuntiavit; illa non
modicum dolens dixit: "O fili carissime, quare spem posuisti in
muliere? Iam altera vice deceptus es per eam et ab omnibus ut
stultus reputaris; ammodo sapientiam addiscas quia nihil habeo
tibi nisi pannum pretiosum quem pater tuus tibi dedit, et si
illum perdideris, ad me amplius redire non valeas."
-->
He proceeded to his mother and reported to her the entire course
of events. She, grieving not a little, said: "O my dearest son,
why have you put your hope in a women? You have already been
cheated in another exchange with her and are thought to be
foolish by everyone; henceforth you should learn wisdom, for I
have nothing else for you except the costly length of cloth that
your father gave you, and if you lose that, it will not avail
you to come back to me."
<!--
Ille pannum recepit et ad studium perrexit et concubina eius, ut
prius, gaudenter eum recepit. Qui expandens pannum dixit:
"Carissima, istum pannum dedit mihi pater meus," et ambo
posuerunt se super pannum.
-->
He accepted this length of cloth and went on to his studies and
his concubine, as before, received him with joy. And he,
spreading out the cloth, said: "Dearest love, my father gave me
this cloth," and they both sat down upon the cloth.
<!--
Ionathas intra se cogitabat: "Utinam essemus in tantam
distantiam ubi nullus hominum ante venit!" Et sic factum
est; fuerunt enim in fine mundi in una foresta quae multum
distabat ab hominibus. Illa tristabatur et Ionathas votum
vovit Deo caeli quod dimitteret eam bestiis ad devorandum
donec redderet anulum et monile; quae promisit facere si
posset, et ad petitionem concubinae Ionathas virtutem panni
dixit, scilicet, quicumque super eo quiesceret et cogitaret ubi
esse vellet, ibi statim esset.
-->
Jonathan thought to himself: "If only we were so far away
that no man had been there before!" And so it happened; for
they were at the end of the world in a forest which was far away
from men. She was grieved, and Jonathan made a vow to God in heaven
that he would leave her to be devoured by wild animals unless
she restored the ring and the necklace. She promised to do this
if she could, and Jonathan spoke of the virtue of the cloth,
namely, that whoever sat on it and thought where they wished to
go, there they were at once.
<!--
Deinde ipsa se super pannum posuit et caput eius in gremio suo
collocavit et, cum dormire coepisset, ipsa partem panni supra quam
sedebat ad se traxit. At illa cogitabat: "Utinam essem in loco ubi
mane fui!" Quod et factum est, et Ionathas dormiens in foresta
mansit.
-->
Then she positioned herself on the cloth and placed his head on her
lap and, when he had fallen asleep, drew the part of the cloth on
which he was lying towards her. But then she thought: "If only I
were in the place where I was this morning!" And this was
accomplished, and Jonathan remained asleep in the forest.
</p>
<p>
<!--
Cum autem de somno surrexisset et pannum ablatum cum concubina
vidisset, flevit amarissime nec scivit ad quem locum pergeret.
Surrexit et, signo crucis se muniens, per quandam viam ambulavit, per
quam ad aquam profundam venit per quam transire oportebat, quae tam
amara et fervida fuit quod carnes pedum usque ad nuda ossa
separavit. Ille vero, de hoc contristatus, vas implevit et secum
portavit et ulterius veniens coepit esurire, vidensque quandam
arborem, de fructu eius comedit et statim factus est leprosus. De
fructu illo etiam collegit et secum portavit. Tunc veniens ad aliam
aquam, per quam transivit, quae aqua carnes restaurabat pedum, vas de
ea implevit et secum portavit et ulterius procedens coepit esurire;
et videns quandam arborem, de cuius fructu cepit et comedit et, sicut
per primum fructum infectus erat, sic per secundum fructum a lepra
est mundatus. De illo fructu etiam attulit et secum portavit.
-->
But when he awoke from his sleep and saw that the cloth had been
carried off, along with his concubine, he wept most bitterly and
knew not where to go. He got up and, fortifying himself with the
sign of the cross, wandered along a road, which led him to a deep
body of water that he needed to cross, but which was so caustic and
boiling hot that the flesh of his feet was nearly stripped to the
bone. Indeed, he was disheartened by this, filled up a vessel and
carried it with him and, coming to the far side, began to feel
hunger. He saw a tree, and ate of its fruit and at once contracted
leprosy. He gathered some of this fruit as well and carried it with
him. Then he came to another body of water and crossed over it, and
it restored the flesh to his feet. He filled a vessel with this
water and carried it with him and, once on the other side, grew
hungry. And when he saw a tree, he seized its fruit and ate it, so
that as he had been infected by the the first fruit, so by the
second he was healed of the leprosy. He picked more of this fruit
and carried it away with him.
</p>
<p>
<!--
Dum vero ulterius ambularet vidit quoddam castrum, et duo homines ei
obviabant, quaerentes quis esset. At ille: "Medicus peritus sum."
Qui dixerunt: "Rex istius regni manet in isto castro et est homo
leprosus; si eum a lepra curare posses, multas divitias tibi daret."
At ille: "Etiam."
-->
Truly, while he wandered on the far shore he saw a castle, and two
men met him, asking who he might be. And he said, "I am a skilled
physician." And they said: "The king of this realm lies in that
castle and is a leper; if you can cure him of the leprosy, he will
give you great riches." And he said: "Very well."
</p>
<p>
<!--
Qui adducentes ipsum ad regem, dedit ei de secundo fructu et curatus
est a lepra, et de secunda aqua ad bibendum, quae carnes eius
restaurabat. Rex ergo multa donaria ei contulit. Ionathas igitur
postea invenit navem de civitate sua et illuc transfretavit. Rumor
per totam civitatem exivit quod magnus medicus advenisset et
concubina sua, quae abstulerat iocalia ei, ad mortem infirmata est
mittens pro medico isto.
-->
They conducted him to the king, and he gave him some of the second
fruit and he was cured of the leprosy. And he gave him some of the
second water to drink, and his flesh was restored. And so the king
gathered together many gifts for him. And so Jonathan afterwards
found a ship and sailed from that city to there. The rumor issued
through the entire city that a great physician had arrived, and his
concubine, who had stolen his possessions, was sick unto death and
sent for this physician.
<!--
Ionathas ignotus est ab omnibus sed ipse eam cognoscens dixit ei quod
medicina sua non valeret ei, nisi prius confiteretur omnia peccata
sua, et si aliquem defraudasset, quod redderet. Illa vero alta voce
confitebatur quomodo Ionatham decepisset de anulo, monili et panno et
quomodo eum in loco deserto reliquisset bestiis ad devorandum. Ille
hoc audiens ait: "Dic, domina, ubi sunt ista tria iocalia?" Et illa:
"In area mea." Et dedit ei claves arcae et invenit ea. Ionathas ei
de fructu illius arboris a qua lepram recepit ad comedendum dedit et
de aqua prima, quae carnem de ossibus separavit, ad bibendum ei
tribuit; et cum gustasset et bibisset statim est arefacta et, dolores
interiores sentiens, lacrimabiliter clamavit et spiritum
emisit. Ionathas cum iocalibus suis ad matrem suam perrexit, de cuius
adventu totus populus gaudebat. Ille vero matri a principio usque ad
finem narravit quomodo Deus eum a multis malis periculis liberavit et
per aliquos annos vixit et vitam in pace finivit.
-->
Jonathan was a stranger to all, but he recognized her and said to
her that his medicine would avail her nothing, unless she would
first confess all of her sins, and if she had cheated anyone, then
she must pay them back. Indeed she confessed in a loud voice how
she had abandoned Jonathan to be devoured by the wild animals. He
heard this and said: "Tell me, lady, where are the three
possessions?" And she said: "In my courtyard." And she gave him the
keys to the courtyard and he found them. Jonathan gave her the
fruit of the first tree and she recieved leprosy from it. And he
gave her some of the first water, which strips the flesh from the
bones, and presented it to her to drink; and when she had eaten and
drunk she at once withered up and, feeling pain within her, cried
out mournfully and gave up the ghost. Jonathan took his possessions
and proceeded to his mother, and the whole population rejoiced at
his coming. Indeed he related to his mother from beginning to end
how God freed him from many grim perils, and lived for some years,
and finished his life in peace.
</p>
</body>
</html>
| alijc/Latin | medlat/028-mulierum-deceptione.html | HTML | artistic-2.0 | 16,268 |
// Convert DMD CodeView debug information to PDB files
// Copyright (c) 2009-2010 by Rainer Schuetze, All Rights Reserved
//
// License for redistribution is given by the Artistic License 2.0
// see file LICENSE for further details
#include "mspdb.h"
#include <windows.h>
#pragma comment(lib, "rpcrt4.lib")
HMODULE modMsPdb;
mspdb::fnPDBOpen2W *pPDBOpen2W;
char* mspdb80_dll = "mspdb80.dll";
char* mspdb100_dll = "mspdb100.dll";
bool mspdb::DBI::isVS10 = false;
bool getInstallDir(const char* version, char* installDir, DWORD size)
{
char key[260] = "SOFTWARE\\Microsoft\\";
strcat(key, version);
HKEY hkey;
if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, key, 0, KEY_QUERY_VALUE, &hkey) != ERROR_SUCCESS)
return false;
bool rc = RegQueryValueExA(hkey, "InstallDir", 0, 0, (LPBYTE)installDir, &size) == ERROR_SUCCESS;
RegCloseKey(hkey);
return rc;
}
bool tryLoadMsPdb(const char* version, const char* mspdb)
{
char installDir[260];
if (!getInstallDir(version, installDir, sizeof(installDir)))
return false;
char* p = installDir + strlen(installDir);
if (p[-1] != '\\' && p[-1] != '/')
*p++ = '\\';
strcpy(p, mspdb);
modMsPdb = LoadLibraryA(installDir);
return modMsPdb != 0;
}
bool initMsPdb()
{
if (!modMsPdb)
modMsPdb = LoadLibraryA(mspdb80_dll);
if (!modMsPdb)
tryLoadMsPdb("VisualStudio\\9.0", mspdb80_dll);
if (!modMsPdb)
tryLoadMsPdb("VisualStudio\\8.0", mspdb80_dll);
if (!modMsPdb)
tryLoadMsPdb("VCExpress\\9.0", mspdb80_dll);
if (!modMsPdb)
tryLoadMsPdb("VCExpress\\8.0", mspdb80_dll);
#if 1
if (!modMsPdb)
{
modMsPdb = LoadLibraryA(mspdb100_dll);
if (!modMsPdb)
tryLoadMsPdb("VisualStudio\\10.0", mspdb100_dll);
if (!modMsPdb)
tryLoadMsPdb("VCExpress\\10.0", mspdb100_dll);
if (modMsPdb)
mspdb::DBI::isVS10 = true;
}
#endif
if (!modMsPdb)
return false;
if (!pPDBOpen2W)
pPDBOpen2W = (mspdb::fnPDBOpen2W*) GetProcAddress(modMsPdb, "PDBOpen2W");
if (!pPDBOpen2W)
return false;
return true;
}
bool exitMsPdb()
{
pPDBOpen2W = 0;
if (modMsPdb)
FreeLibrary(modMsPdb);
modMsPdb = 0;
return true;
}
mspdb::PDB* CreatePDB(const wchar_t* pdbname)
{
if (!initMsPdb ())
return 0;
mspdb::PDB* pdb = 0;
long data[194] = { 193, 0 };
wchar_t ext[256] = L".exe";
if (!(*pPDBOpen2W) (pdbname, "wf", data, ext, 0x400, &pdb))
return 0;
return pdb;
}
| MartinNowak/cv2pdb | src/mspdb.cpp | C++ | artistic-2.0 | 2,441 |
package TearDrop::Command::import_blast;
use 5.12.0;
use Mojo::Base 'Mojolicious::Command';
use Carp;
use Try::Tiny;
use TearDrop::Task::ImportBLAST;
use Getopt::Long qw(GetOptionsFromArray :config no_auto_abbrev no_ignore_case);
has description => 'Import BLAST results (currently only custom format)';
has usage => sub { shift->extract_usage };
sub run {
my ($self, @args) = @_;
my %opt = (evalue_cutoff => 0.01, max_target_seqs => 20);
GetOptionsFromArray(\@args, \%opt, 'project|p=s', 'reverse',
'db_source|db=s', 'assembly|a=s', 'evalue_cutoff=f', 'max_target_seqs=i')
or croak $self->help;
croak 'need project context' unless $opt{project};
croak 'need db_source that was blasted' unless $opt{db_source};
croak 'need assembly that was blasted against for reverse' if $opt{reverse} && !$opt{assembly};
my $task = new TearDrop::Task::ImportBLAST(
project => $opt{project},
assembly => $opt{assembly},
database => $opt{db_source},
reverse => $opt{reverse},
files => \@args,
evalue_cutoff => $opt{evalue_cutoff},
max_target_seqs => $opt{max_target_seqs},
);
try {
my $res = $task->run || croak 'task failed!';
say $res->{count}." entries imported.\n";
} catch {
croak 'import failed: '.$_;
};
}
1;
=pod
=head1 NAME
TearDrop::Command::import_blast - import BLAST results
=head1 SYNOPSIS
Usage: tear_drop import_blast [OPTIONS] [files...]
Required Options:
-p, --project [project]
Name of the project context in which to run. See L<TearDrop::Command::deploy_project>.
"Forward" BLAST:
--db, --db_source [db]
Name of a configured db source that was queried
"Reverse" BLAST:
--reverse
This was a reverse BLAST, ie. you extracted sequences from a BLAST db and blasted against a transcript assembly.
-a, --assembly [assembly]
Name of the assembly that was queried
--db, --db_source [db]
Name of the database that was BLASTed, ie. where you extracted the sequences from. This database needs to be configured!
Filtering (currently non-functional, please set the corresponding BLAST options).
--evalue_cutoff
default .01
--max_target_seqs
default 20
If no files are specified, input is read from STDIN.
Currently only a custom tabular format is understood, please use
-outfmt "6 qseqid sseqid bitscore qlen length nident pident ppos evalue slen qseq sseq qstart qend sstart send stitle"
=head1 DESCRIPTION
=head1 METHODS
Inherits all methods from L<Mojolicious::Command> and implements the following new ones.
=head2 run
$import_blast->run(@ARGV);
=cut
| h3kker/tearDrop | lib/TearDrop/Command/import_blast.pm | Perl | artistic-2.0 | 2,639 |
public class Lab4_2
{
public static void main(String[] arg)
{
System.out.print(" * |");
for(int x=1;x<=12;x++) {
if (x<10) System.out.print(' ');
if (x<100) System.out.print(' ');
System.out.print(x+" ");
}
System.out.println();
for(int x=1;x<=21;x++) {
if (x<10) System.out.print('-');
System.out.print("--");
}
System.out.println();
for(int i=1;i<=12;i++)
{
if (i<10) System.out.print(' ');
System.out.print(i+" |");
for(int j=1;j<=12;j++) {
if (i*j<10) System.out.print(' ');
if (j*i<100) System.out.print(' ');
System.out.print(j*i+" ");
}
System.out.println();
}
System.out.println();
System.out.println();
System.out.print(" + |");
for(int x=1;x<=12;x++) {
if (x<10) System.out.print(' ');
if (x<100) System.out.print(' ');
System.out.print(x+" ");
}
System.out.println();
for(int x=1;x<=21;x++) {
if (x<10) System.out.print('-');
System.out.print("--");
}
System.out.println();
for(int i=1;i<=12;i++)
{
if (i<10) System.out.print(' ');
System.out.print(i+" |");
for(int j=1;j<=12;j++) {
if (i+j<10) System.out.print(' ');
if (j+i<100) System.out.print(' ');
System.out.print(j+i+" ");
}
System.out.println();
}
}
}
| Seven-and-Nine/example-code-for-nine | Java/normal code/Java I/Lab4/Lab4_2.java | Java | artistic-2.0 | 1,401 |
var HLSP = {
/*
set squareness to 0 for a flat land
*/
// intensità colore land audioreattivab più bassa
mizu: {
cameraPositionY: 10,
seaLevel: 0,
displayText: '<b>CHAPTER ONE, MIZU</b><br/><i>TO BE TRAPPED INTO THE MORNING UNDERTOW</i>',
speed: 10,
modelsParams: ['stones', function(){return 1+Math.random()*40}, 3, true, true, 0],
tiles: 62,
repeatUV: 1,
bFactor: 0.5,
cFactor: 0.07594379703811609,
buildFreq: 10,
natural: 0.6834941733430447,
rainbow: 0.5641539208545766,
squareness: 0.022450016948639295,
map: 'white',
landRGB: 1966335,
horizonRGB: 0,
skyMap: 'sky4',
},
// fft1 più speedup moveSpeed
solar_valley: {
cameraPositionY: -180,
seaLevel: -450,
fogDensity: 0.00054,
displayText: '<b>CHAPTER TWO, SOLAR VALLEY</b><br><i>FIRE EXECUTION STOPPED BY CLOUDS</i>',
speed: 10,
modelsParams: ['stones', function(){return 1+Math.random()*5}, 40, true, false, -750],
tiles: 200,
repeatUV: 7,
bFactor: 0.6617959456178687,
cFactor: 0.3471716436028164,
buildFreq: 10,
natural: 0.18443493566399619,
rainbow: 0.03254734158776403,
squareness: 0.00001,
map: 'land3',
landRGB: 9675935,
horizonRGB: 3231404,
skyMap: 'sky4',
},
// camera underwater
escher_surfers: {
cameraPositionY: 40,
seaLevel: 50,
displayText: '<b>CHAPTER THREE, ESCHER SURFERS</b><br><i>TAKING REST ON K 11</i>',
speed: 15,
modelsParams: ['cube', 3, 1, true, true, 0 ],
tiles: 73,
repeatUV: 112,
bFactor: 1.001,
cFactor: 0,
buildFreq: 10,
natural: 0,
rainbow: 0.16273670793882017,
squareness: 0.08945796327125173,
map: 'pattern1',
landRGB: 16727705,
horizonRGB: 7935,
skyMap: 'sky1',
},
// sea level più basso
// modelli: cubid
currybox: {
cameraPositionY: 100,//HLE.WORLD_HEIGHT*.5,
seaLevel: -100,
displayText: '<b>CHAPTER FOUR, CURRYBOX</b><br><i>A FLAKE ON THE ROAD AND A KING AND HIS BONES</i>',
speed: 5,
modelsParams: [['cube'], function(){return 1+Math.random()*5}, 1, true, false,-100],
tiles: 145,
repeatUV: 1,
bFactor: 0.751,
cFactor: 0.054245569312940056,
buildFreq: 10,
natural: 0.176420247632921,
rainbow: 0.21934025248846812,
squareness: 0.01,
map: 'white',
landRGB: 13766158,
horizonRGB: 2665099,
skyMap: 'sky1',
},
// sealevel basso
galaxy_glacier: {
cameraPositionY: 50,
seaLevel: -100,
displayText: '<b>CHAPTER FIVE, GALAXY GLACIER</b><br><i>HITTING ICEBERGS BLAMES</i>',
speed: 2,
modelsParams: [null, 1, true, true],
tiles: 160,
repeatUV: 1,
bFactor: 0.287989180087759,
cFactor: 0.6148319562024518,
buildFreq: 61.5837970429,
natural: 0.4861551769529205,
rainbow: 0.099628324585666777,
squareness: 0.01198280149135716,
map: 'pattern5', //%
landRGB: 11187452,
horizonRGB: 6705,
skyMap: 'sky1',
},
firefly: {
cameraPositionY: 50,
displayText: '<b>CHAPTER SIX, FIREFLY</b>',
speed: 10,
modelsParams: ['sea', 1, true, true],
tiles: 100,
repeatUV: 1,
bFactor: 1,
cFactor: 1,
buildFreq: 1,
natural: 1,
rainbow: 0,
squareness: 0,
map: 'white',
landRGB: 2763306,
horizonRGB: 0,
skyMap: 'sky1',
},
//camera position.y -400
// partire sopra acqua, e poi gradualmente finire sott'acqua
//G
drift: {
cameraPositionY: -450,
seaLevel: 0,
displayText: '<b>CHAPTER SEVEN, DRIFT</b><br><i>LEAVING THE BOAT</i>',
speed: 3,
modelsParams: [['ducky'], function(){return 1+Math.random()*2}, 2, true, true, 0],
tiles: 128,
repeatUV: 0,
bFactor: 0.24952961883952426,
cFactor: 0.31,
buildFreq: 15.188759407623216,
natural: 0.3471716436028164,
rainbow: 1.001,
squareness: 0.00001,
map: 'land1',
landRGB: 16777215,
horizonRGB: 6039170,
skyMap: 'sky2',
},
//H
hyperocean: {
cameraPositionY: 50,
displayText: '<b>CHAPTER EIGHT, HYPEROCEAN</b><br><i>CRAVING FOR LOVE LASTS FOR LIFE</i>',
speed: 8,//18,
modelsParams: ['space', 2, 40, true, false, 200],
tiles: 200,
repeatUV: 12,
bFactor: 1.001,
cFactor: 0.21934025248846812,
buildFreq: 15.188759407623216,
natural: 0.7051924010682208,
rainbow: 0.1952840495265842,
squareness: 0.00001,
map: 'land5',
landRGB: 14798516,
horizonRGB: 7173242,
skyMap: 'sky2',
},
// balene
// capovolgere di conseguenza modelli balene
//I
twin_horizon: {
cameraPositionY: 100,
displayText: '<b>CHAPTER NINE, TWIN HORIZON</b><br><i>ON THE RIGHT VISION TO THE RIGHT SEASON</i>',
speed: 10,
modelsParams: ['sea', function(){return 20+Math.random()*20}, 20, false, false, 550],
tiles: 99,
repeatUV: 1,
bFactor: 0.20445411338494512,
cFactor: 0.33632252974022836,
buildFreq: 45.50809304437684,
natural: 0.4448136683661085,
rainbow: 0,
squareness: 0.0013619887944460984,
map: 'white',
landRGB: 0x000fff,
horizonRGB: 16728899,
skyMap: 'sky1',
},
// da un certo punto random colors (quando il pezzo aumenta)
// da stesso punto aumenta velocità
// sea level basso
// modelli elettrodomestici / elettronica
//J
else: {
cameraPositionY: 50,
displayText: '<b>CHAPTER TEN, ELSE</b><br><i>DIE LIKE AN ELECTRIC MACHINE</i>',
speed: 10,
modelsParams: [['ducky'], function(){return 2+Math.random()*20}, 3, true, true, 0],
tiles: 104,
repeatUV: 128,
bFactor: 0.5641539208545766,
cFactor: 0,
buildFreq: 30.804098302357595,
natural: 0.0,
rainbow: 0.6458797021572349,
squareness: 0.013562721707765414,
map: 'pattern2',
landRGB: 65399,
horizonRGB: 0x000000,
skyMap: 'sky3',
},
// quando iniziano i kick randomizza landscape
// odissea nello spazio
// cielo stellato (via lattea)
//K
roger_water: {
cameraPositionY: 50,
displayText: '<b>CHAPTER ELEVEN, ROGER WATER</b><br><i>PROTECT WATER</i>',
speed: 10,
modelsParams: ['stones', function(){return 1+Math.random()*40}, 3, true, true, 0],
tiles: 80,
repeatUV: 1,
bFactor: 0,
cFactor: 0.20613316338917223,
buildFreq: 10,
natural: 1.001,
rainbow: 0.1735858218014082,
squareness: 0.00001,
map: 'white',
landRGB: 2105376,
horizonRGB: 0,
skyMap: 'sky1',
},
//L
alpha_11: {
cameraPositionY: 50,
displayText: '<b>CHAPTER TWELVE, ALPHA 11</b><br><i>A MASSIVE WAVE IS DRIVING ME HOME</i>',
speed: 1,
modelsParams: ['stones', function(){return 1+Math.random()*40}, 3, true, true, 0],
tiles: 6,
repeatUV: 1,
bFactor: 0,
cFactor: 0,
buildFreq: 44.48136683661085,
natural: 0,
rainbow: 0,
squareness: 0.00001,
map: 'white',
landRGB: 0,
horizonRGB: 3980219,
skyMap: 'sky1',
},
//M
blackpool: {
displayText: 'BLACKPOOL',
speed: -10,
modelsParams: ['space', 2, 400, true, false, 200],
cameraPositionY: 110,
seaLevel: 10,
// speed: 4,
// modelsParams: ['sea', 1, true, true],
tiles: 182,
repeatUV: 16.555478741450983,
bFactor: 0.6048772396441062,
cFactor: 0.016358953883098624,
buildFreq: 73.3797815423632,
natural: 0.9833741906510363,
rainbow: 0.10821609644148733,
squareness: 0.00599663055740593,
map: 'land3',
landRGB: 12105440,
horizonRGB: 2571781,
skyMap: 'sky1',
},
intro: {
cameraPositionY: 650,
seaLevel:0,
displayText: 'INTRO',
speed: 0,
modelsParams: ['sea', 1, true, true],
tiles: 100,
repeatUV: 1,
bFactor: 0,
cFactor: 0,
buildFreq: 10,
natural: 1,
rainbow: 0,
squareness: 0,
map: 'sky1',
landRGB: 0x111111,
horizonRGB: 0x6f6f6f,
skyMap: 'sky3'
}
}
| stmaccarelli/HYPERLAND | src/sceneParams_0.js | JavaScript | artistic-2.0 | 9,148 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.