code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9
values | license stringclasses 15
values | size int32 3 1.05M |
|---|---|---|---|---|---|
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
* 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.appium.java_client.pagefactory;
import io.appium.java_client.MobileElement;
import io.appium.java_client.TouchableElement;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidElement;
import io.appium.java_client.ios.IOSDriver;
import io.appium.java_client.ios.IOSElement;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.*;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.SearchContext;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.RemoteWebElement;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.pagefactory.ElementLocator;
import org.openqa.selenium.support.pagefactory.FieldDecorator;
import static io.appium.java_client.pagefactory.AppiumElementUtils.getGenericParameterClass;
/**
* Default decorator for use with PageFactory. Will decorate 1) all of the
* WebElement fields and 2) List<WebElement> fields that have
* {@literal @AndroidFindBy}, {@literal @AndroidFindBys}, or
* {@literal @iOSFindBy/@iOSFindBys} annotation with a proxy that locates the
* elements using the passed in ElementLocatorFactory.
*
* Please pay attention: fields of {@link WebElement}, {@link RemoteWebElement},
* {@link MobileElement}, {@link AndroidElement} and {@link IOSElement} are allowed
* to use with this decorator
*/
public class AppiumFieldDecorator implements FieldDecorator {
private final static Map<Class<? extends SearchContext>, Class<? extends WebElement>> elementRuleMap =
new HashMap<Class<? extends SearchContext>, Class<? extends WebElement>>(){
private static final long serialVersionUID = 1L;
{
put(AndroidDriver.class, AndroidElement.class);
put(AndroidElement.class, AndroidElement.class);
put(IOSDriver.class, IOSElement.class);
put(IOSElement.class, IOSElement.class);
}
};
private final AppiumElementLocatorFactory factory;
private final SearchContext context;
public static long DEFAULT_IMPLICITLY_WAIT_TIMEOUT = 1;
public static TimeUnit DEFAULT_TIMEUNIT = TimeUnit.SECONDS;
public AppiumFieldDecorator(SearchContext context, long implicitlyWaitTimeOut, TimeUnit timeUnit) {
this.context = context;
factory = new AppiumElementLocatorFactory(this.context, new TimeOutDuration(implicitlyWaitTimeOut, timeUnit));
}
public AppiumFieldDecorator(SearchContext context, TimeOutDuration timeOutDuration) {
this.context = context;
factory = new AppiumElementLocatorFactory(this.context, timeOutDuration);
}
public AppiumFieldDecorator(SearchContext context) {
this.context = context;
factory = new AppiumElementLocatorFactory(this.context);
}
public Object decorate(ClassLoader ignored, Field field) {
ElementLocator locator;
String name = getName(field);
if (AppiumElementUtils.isDecoratableElement(field)) {
locator = factory.createLocator(field);
return proxyForLocator(getTypeForProxy(), locator, name);
}
if (AppiumElementUtils.isDecoratableList(field)) {
locator = factory.createLocator(field);
return proxyForListLocator(locator, name);
}
if(AppiumElementUtils.isDecoratableMobileElement(field)) {
locator = factory.createLocator(field.getType());
for (Class annotation : Annotations.FIND_BY) {
if (field.isAnnotationPresent(annotation)) {
locator = factory.createLocator(field);
break;
}
}
MobileElement element = (MobileElement) proxyForLocator(field.getType(), locator, name);
PageFactory.initElements(new AppiumFieldDecorator(element), element);
return element;
}
if(AppiumElementUtils.isDecoratableMobileElementsList(field)) {
Class<? extends MobileElement> clazz = AppiumElementUtils.getGenericParameterClass(field);
locator = factory.createLocator(clazz);
return proxyForListLocator(clazz, locator, name);
}
return null;
}
private String getName(Field field) {
if(field.isAnnotationPresent(Name.class)) {
return field.getAnnotation(Name.class).value();
}
if(field.getType().isAnnotationPresent(Name.class)) {
return field.getType().getAnnotation(Name.class).value();
}
if(AppiumElementUtils.isDecoratableList(field)) {
Class<?> clazz = getGenericParameterClass(field);
if(clazz.isAnnotationPresent(Name.class)) {
return clazz.getAnnotation(Name.class).value();
}
}
return field.getName();
}
private Class<?> getTypeForProxy(){
Class<?> contextClass = context.getClass();
Iterable<Map.Entry<Class<? extends SearchContext>, Class<? extends WebElement>>> rules = elementRuleMap.entrySet();
Iterator<Map.Entry<Class<? extends SearchContext>, Class<? extends WebElement>>> iterator = rules.iterator();
while (iterator.hasNext()){ //it will return MobileElement subclass when here is something
//that extends AppiumDriver or MobileElement
Map.Entry<Class<? extends SearchContext>, Class<? extends WebElement>> e = iterator.next();
if (e.getKey().isAssignableFrom(contextClass))
return e.getValue();
} //it is compatible with desktop browser. So at this case it returns RemoteWebElement.class
return RemoteWebElement.class; // будет всегда возвращать у дочерних элементов, потому-что левый класс не привести к AndroidElement
}
@SuppressWarnings("unchecked")
private Object proxyForLocator(Class<?> clazz, ElementLocator locator, String name) {
ElementInterceptor elementInterceptor = new ElementInterceptor(clazz, locator, name);
return ProxyFactory.getEnhancedProxy(clazz, elementInterceptor);
}
@SuppressWarnings("unchecked")
private List<? extends WebElement> proxyForListLocator(ElementLocator locator, String name) {
ElementListInterceptor elementInterceptor = new ElementListInterceptor(locator, name);
return ProxyFactory.getEnhancedProxy(ArrayList.class, elementInterceptor);
}
@SuppressWarnings("unchecked")
private <T extends MobileElement> List<T> proxyForListLocator(Class<T> clazz, ElementLocator locator, String name) {
MobileElementListInterceptor elementInterceptor = new MobileElementListInterceptor<>(clazz, locator, name);
return ProxyFactory.getEnhancedProxy(ArrayList.class, elementInterceptor);
}
}
| d0lfin/java-client | src/main/java/io/appium/java_client/pagefactory/AppiumFieldDecorator.java | Java | apache-2.0 | 7,217 |
/*
* Copyright 1999-2011 Alibaba Group Holding Ltd.
*
* 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 org.durid.sql.visitor;
import org.durid.sql.ast.SQLCommentHint;
import org.durid.sql.ast.SQLDataType;
import org.durid.sql.ast.SQLObject;
import org.durid.sql.ast.SQLOrderBy;
import org.durid.sql.ast.SQLOver;
import org.durid.sql.ast.expr.SQLAggregateExpr;
import org.durid.sql.ast.expr.SQLAllColumnExpr;
import org.durid.sql.ast.expr.SQLAllExpr;
import org.durid.sql.ast.expr.SQLAnyExpr;
import org.durid.sql.ast.expr.SQLBetweenExpr;
import org.durid.sql.ast.expr.SQLBinaryOpExpr;
import org.durid.sql.ast.expr.SQLBitStringLiteralExpr;
import org.durid.sql.ast.expr.SQLCaseExpr;
import org.durid.sql.ast.expr.SQLCastExpr;
import org.durid.sql.ast.expr.SQLCharExpr;
import org.durid.sql.ast.expr.SQLCurrentOfCursorExpr;
import org.durid.sql.ast.expr.SQLDateLiteralExpr;
import org.durid.sql.ast.expr.SQLDefaultExpr;
import org.durid.sql.ast.expr.SQLExistsExpr;
import org.durid.sql.ast.expr.SQLHexExpr;
import org.durid.sql.ast.expr.SQLHexStringLiteralExpr;
import org.durid.sql.ast.expr.SQLIdentifierExpr;
import org.durid.sql.ast.expr.SQLInListExpr;
import org.durid.sql.ast.expr.SQLInSubQueryExpr;
import org.durid.sql.ast.expr.SQLIntegerExpr;
import org.durid.sql.ast.expr.SQLIntervalLiteralExpr;
import org.durid.sql.ast.expr.SQLListExpr;
import org.durid.sql.ast.expr.SQLMethodInvokeExpr;
import org.durid.sql.ast.expr.SQLNCharExpr;
import org.durid.sql.ast.expr.SQLNotExpr;
import org.durid.sql.ast.expr.SQLNullExpr;
import org.durid.sql.ast.expr.SQLNumberExpr;
import org.durid.sql.ast.expr.SQLPropertyExpr;
import org.durid.sql.ast.expr.SQLQueryExpr;
import org.durid.sql.ast.expr.SQLSomeExpr;
import org.durid.sql.ast.expr.SQLUnaryExpr;
import org.durid.sql.ast.expr.SQLVariantRefExpr;
import org.durid.sql.ast.statement.NotNullConstraint;
import org.durid.sql.ast.statement.SQLAlterTableAddColumn;
import org.durid.sql.ast.statement.SQLAlterTableAddPrimaryKey;
import org.durid.sql.ast.statement.SQLAlterTableDropColumnItem;
import org.durid.sql.ast.statement.SQLAlterTableDropIndex;
import org.durid.sql.ast.statement.SQLAssignItem;
import org.durid.sql.ast.statement.SQLCallStatement;
import org.durid.sql.ast.statement.SQLColumnDefinition;
import org.durid.sql.ast.statement.SQLCommentStatement;
import org.durid.sql.ast.statement.SQLCreateDatabaseStatement;
import org.durid.sql.ast.statement.SQLCreateTableStatement;
import org.durid.sql.ast.statement.SQLCreateViewStatement;
import org.durid.sql.ast.statement.SQLDeleteStatement;
import org.durid.sql.ast.statement.SQLDropIndexStatement;
import org.durid.sql.ast.statement.SQLDropTableStatement;
import org.durid.sql.ast.statement.SQLDropViewStatement;
import org.durid.sql.ast.statement.SQLExprTableSource;
import org.durid.sql.ast.statement.SQLInsertStatement;
import org.durid.sql.ast.statement.SQLJoinTableSource;
import org.durid.sql.ast.statement.SQLReleaseSavePointStatement;
import org.durid.sql.ast.statement.SQLRollbackStatement;
import org.durid.sql.ast.statement.SQLSavePointStatement;
import org.durid.sql.ast.statement.SQLSelect;
import org.durid.sql.ast.statement.SQLSelectGroupByClause;
import org.durid.sql.ast.statement.SQLSelectItem;
import org.durid.sql.ast.statement.SQLSelectOrderByItem;
import org.durid.sql.ast.statement.SQLSelectQueryBlock;
import org.durid.sql.ast.statement.SQLSelectStatement;
import org.durid.sql.ast.statement.SQLSetStatement;
import org.durid.sql.ast.statement.SQLSubqueryTableSource;
import org.durid.sql.ast.statement.SQLTableElement;
import org.durid.sql.ast.statement.SQLTruncateStatement;
import org.durid.sql.ast.statement.SQLUnionQuery;
import org.durid.sql.ast.statement.SQLUniqueConstraint;
import org.durid.sql.ast.statement.SQLUpdateSetItem;
import org.durid.sql.ast.statement.SQLUpdateStatement;
import org.durid.sql.ast.statement.SQLUseStatement;
public interface SQLASTVisitor {
void endVisit(SQLAllColumnExpr x);
void endVisit(SQLBetweenExpr x);
void endVisit(SQLBinaryOpExpr x);
void endVisit(SQLCaseExpr x);
void endVisit(SQLCaseExpr.Item x);
void endVisit(SQLCharExpr x);
void endVisit(SQLIdentifierExpr x);
void endVisit(SQLInListExpr x);
void endVisit(SQLIntegerExpr x);
void endVisit(SQLExistsExpr x);
void endVisit(SQLNCharExpr x);
void endVisit(SQLNotExpr x);
void endVisit(SQLNullExpr x);
void endVisit(SQLNumberExpr x);
void endVisit(SQLPropertyExpr x);
void endVisit(SQLSelectGroupByClause x);
void endVisit(SQLSelectItem x);
void endVisit(SQLSelectStatement selectStatement);
void postVisit(SQLObject astNode);
void preVisit(SQLObject astNode);
boolean visit(SQLAllColumnExpr x);
boolean visit(SQLBetweenExpr x);
boolean visit(SQLBinaryOpExpr x);
boolean visit(SQLCaseExpr x);
boolean visit(SQLCaseExpr.Item x);
boolean visit(SQLCastExpr x);
boolean visit(SQLCharExpr x);
boolean visit(SQLExistsExpr x);
boolean visit(SQLIdentifierExpr x);
boolean visit(SQLInListExpr x);
boolean visit(SQLIntegerExpr x);
boolean visit(SQLNCharExpr x);
boolean visit(SQLNotExpr x);
boolean visit(SQLNullExpr x);
boolean visit(SQLNumberExpr x);
boolean visit(SQLPropertyExpr x);
boolean visit(SQLSelectGroupByClause x);
boolean visit(SQLSelectItem x);
void endVisit(SQLCastExpr x);
boolean visit(SQLSelectStatement astNode);
void endVisit(SQLAggregateExpr astNode);
boolean visit(SQLAggregateExpr astNode);
boolean visit(SQLVariantRefExpr x);
void endVisit(SQLVariantRefExpr x);
boolean visit(SQLQueryExpr x);
void endVisit(SQLQueryExpr x);
boolean visit(SQLUnaryExpr x);
void endVisit(SQLUnaryExpr x);
boolean visit(SQLHexExpr x);
void endVisit(SQLHexExpr x);
boolean visit(SQLBitStringLiteralExpr x);
void endVisit(SQLBitStringLiteralExpr x);
boolean visit(SQLHexStringLiteralExpr x);
void endVisit(SQLHexStringLiteralExpr x);
boolean visit(SQLDateLiteralExpr x);
void endVisit(SQLDateLiteralExpr x);
boolean visit(SQLSelect x);
void endVisit(SQLSelect select);
boolean visit(SQLSelectQueryBlock x);
void endVisit(SQLSelectQueryBlock x);
boolean visit(SQLExprTableSource x);
void endVisit(SQLExprTableSource x);
boolean visit(SQLIntervalLiteralExpr x);
void endVisit(SQLIntervalLiteralExpr x);
boolean visit(SQLOrderBy x);
void endVisit(SQLOrderBy x);
boolean visit(SQLSelectOrderByItem x);
void endVisit(SQLSelectOrderByItem x);
boolean visit(SQLDropTableStatement x);
void endVisit(SQLDropTableStatement x);
boolean visit(SQLCreateTableStatement x);
void endVisit(SQLCreateTableStatement x);
boolean visit(SQLTableElement x);
void endVisit(SQLTableElement x);
boolean visit(SQLColumnDefinition x);
void endVisit(SQLColumnDefinition x);
boolean visit(SQLDataType x);
void endVisit(SQLDataType x);
boolean visit(SQLDeleteStatement x);
void endVisit(SQLDeleteStatement x);
boolean visit(SQLCurrentOfCursorExpr x);
void endVisit(SQLCurrentOfCursorExpr x);
boolean visit(SQLInsertStatement x);
void endVisit(SQLInsertStatement x);
boolean visit(SQLInsertStatement.ValuesClause x);
void endVisit(SQLInsertStatement.ValuesClause x);
boolean visit(SQLUpdateSetItem x);
void endVisit(SQLUpdateSetItem x);
boolean visit(SQLUpdateStatement x);
void endVisit(SQLUpdateStatement x);
boolean visit(SQLCreateViewStatement x);
void endVisit(SQLCreateViewStatement x);
boolean visit(SQLUniqueConstraint x);
void endVisit(SQLUniqueConstraint x);
boolean visit(NotNullConstraint x);
void endVisit(NotNullConstraint x);
void endVisit(SQLMethodInvokeExpr x);
boolean visit(SQLMethodInvokeExpr x);
void endVisit(SQLUnionQuery x);
boolean visit(SQLUnionQuery x);
void endVisit(SQLSetStatement x);
boolean visit(SQLSetStatement x);
void endVisit(SQLAssignItem x);
boolean visit(SQLAssignItem x);
void endVisit(SQLCallStatement x);
boolean visit(SQLCallStatement x);
void endVisit(SQLJoinTableSource x);
boolean visit(SQLJoinTableSource x);
void endVisit(SQLSomeExpr x);
boolean visit(SQLSomeExpr x);
void endVisit(SQLAnyExpr x);
boolean visit(SQLAnyExpr x);
void endVisit(SQLAllExpr x);
boolean visit(SQLAllExpr x);
void endVisit(SQLInSubQueryExpr x);
boolean visit(SQLInSubQueryExpr x);
void endVisit(SQLListExpr x);
boolean visit(SQLListExpr x);
void endVisit(SQLSubqueryTableSource x);
boolean visit(SQLSubqueryTableSource x);
void endVisit(SQLTruncateStatement x);
boolean visit(SQLTruncateStatement x);
void endVisit(SQLDefaultExpr x);
boolean visit(SQLDefaultExpr x);
void endVisit(SQLCommentStatement x);
boolean visit(SQLCommentStatement x);
void endVisit(SQLUseStatement x);
boolean visit(SQLUseStatement x);
boolean visit(SQLAlterTableAddColumn x);
void endVisit(SQLAlterTableAddColumn x);
boolean visit(SQLAlterTableDropColumnItem x);
void endVisit(SQLAlterTableDropColumnItem x);
boolean visit(SQLAlterTableDropIndex x);
void endVisit(SQLAlterTableDropIndex x);
boolean visit(SQLAlterTableAddPrimaryKey x);
void endVisit(SQLAlterTableAddPrimaryKey x);
boolean visit(SQLDropIndexStatement x);
void endVisit(SQLDropIndexStatement x);
boolean visit(SQLDropViewStatement x);
void endVisit(SQLDropViewStatement x);
boolean visit(SQLSavePointStatement x);
void endVisit(SQLSavePointStatement x);
boolean visit(SQLRollbackStatement x);
void endVisit(SQLRollbackStatement x);
boolean visit(SQLReleaseSavePointStatement x);
void endVisit(SQLReleaseSavePointStatement x);
void endVisit(SQLCommentHint x);
boolean visit(SQLCommentHint x);
void endVisit(SQLCreateDatabaseStatement x);
boolean visit(SQLCreateDatabaseStatement x);
void endVisit(SQLOver x);
boolean visit(SQLOver x);
}
| lane-cn/elasticsql | src/main/java/org/durid/sql/visitor/SQLASTVisitor.java | Java | apache-2.0 | 10,697 |
<?php
if (! defined ( 'BASEPATH' ))
exit ( 'No direct script access allowed' );
/**
* @类功能说明: 考勤action
* @类修改者:
* @修改日期:
* @修改说明:
* @公司名称:深圳市穗鑫网络购物有限公司
* @作者:panda
* @创建时间:2015-7-23 上午11:44:32
* @版本:V1.0
*/
class clocking_action extends CI_Model
{
private $url;
public function __construct()
{
$this->url = my_server_url () . "ClockingAction!";
$this->load->model ( 'tool/get_html' );
$this->load->model ( 'tool/json_helper' );
}
/**
* 函数功能说明 添加一条考勤记录<br>
* 作者名字 panda<br>
* 创建日期 2015-7-22<br>
* @参数: <br>
* @return <br>
*/
public function addAttendance( $attendance )
{
$jstr = $this->json_helper->encode( $attendance );
$data = array (
"jstr" => $jstr
);
$html = $this->get_html->doFileGetContentsget_html2 ( $this->url . "addAttendance", $data );
return $html;
}
/**
* 函数功能说明 传入考勤记录的对象json,修改考勤记录<br>
* 作者名字 panda<br>
* 创建日期 2015-7-22<br>
* @参数: <br>
* @return <br>
*/
public function updateAttendance( $attendance )
{
$jstr = $this->json_helper->encode( $attendance );
$data = array (
"jstr" => $jstr
);
$html = $this->get_html->doFileGetContentsget_html2 ( $this->url . "updateAttendance", $data );
return $html;
}
/**
* 函数功能说明 传入workID、date查找某个员工在某天的考勤情况<br>
* 作者名字 RO<br>
* 创建日期 2015-7-22<br>
* @参数: workID、date<br>
* @return <br>
*/
public function getClockingsByWorkIDAndDate( $work_id, $date )
{
$data = "workID=" . $work_id . "&date=" . $date ;
$html = $this->get_html->doFileGetContentsget_html ( $this->url . "getClockingsByWorkIDAndDate", $data );
$obj = $this->json_helper->decode ( $html );
return $obj;
}
/**
* @函数功能说明:获取所有的考勤列表
* @创建人:panda 2015-7-24
* @修改者:
* @修改时间:
* @修改内容:
* @修改说明
*/
public function getClockings()
{
$html = $this->get_html->doFileGetContentsget_html ( $this->url . "getClockings" );
$obj = $this->json_helper->decode ( $html );
return $obj;
}
}
?> | pandakill/team_project | application/models/clocking_system/clocking_action.php | PHP | apache-2.0 | 2,573 |
package com.linkedin.metadata.models;
import com.linkedin.data.schema.DataSchema;
import com.linkedin.data.schema.PathSpec;
import com.linkedin.metadata.models.annotation.SearchableAnnotation;
import lombok.NonNull;
import lombok.Value;
@Value
public class SearchableFieldSpec implements FieldSpec {
@NonNull PathSpec path;
@NonNull SearchableAnnotation searchableAnnotation;
@NonNull DataSchema pegasusSchema;
public boolean isArray() {
return path.getPathComponents().contains("*");
}
} | linkedin/WhereHows | entity-registry/src/main/java/com/linkedin/metadata/models/SearchableFieldSpec.java | Java | apache-2.0 | 507 |
// Copyright (c) Gurmit Teotia. Please see the LICENSE file in the project root for license information.
using System;
using Guflow.Decider;
using NUnit.Framework;
namespace Guflow.Tests.Decider
{
[TestFixture]
public class SignalWorkflowRequestTests
{
[Test]
public void Invalid_arguments_test()
{
Assert.Throws<ArgumentException>(() => new SignalWorkflowRequest("workflowId", null));
Assert.Throws<ArgumentException>(() => new SignalWorkflowRequest("workflowId", ""));
Assert.Throws<ArgumentException>(() => new SignalWorkflowRequest("", "name"));
Assert.Throws<ArgumentException>(() => new SignalWorkflowRequest(null, "name"));
}
[Test]
public void Serialize_signal_input_to_json_format()
{
var req = new SignalWorkflowRequest("id", "name");
req.SignalInput = new {Id = 10};
var swfRequest = req.SwfFormat("d");
Assert.That(swfRequest.Input, Is.EqualTo("{\"Id\":10}"));
}
}
} | gurmitteotia/guflow | Guflow.Tests/Decider/Signal/SignalWorkflowRequestTests.cs | C# | apache-2.0 | 1,061 |
onmessage = function(e) {
var args = e.data;
var MAXIMUM_ROUNDS = (!args[0])? 1000000 : args[0];
var fee = (!args[1])? 10 : args[1];
var coinRecord = {}; // { "123": 10, "245": 145 .... }
var totalEarning = 0;
for (var currentRound = 0; currentRound < MAXIMUM_ROUNDS; currentRound++) {
var coinAccumulation = 0, pow = 0;
// 0 is negative, and 1 is positive
while (((Math.random() / .5) & 1) == 0) {
pow++;
};
coinAccumulation = Math.pow(2, pow);
totalEarning += coinAccumulation;
var property = "" + coinAccumulation; // fast converting integer to string
coinRecord[property] = (!coinRecord[property])? 1 : coinRecord[property] + 1;
};
var totalCost = fee * MAXIMUM_ROUNDS;
var earnPerRound = totalEarning / MAXIMUM_ROUNDS;
console.log("Earn: " + totalEarning);
console.log("Cost: " + totalCost);
console.log("Earn per round: " + earnPerRound);
// converting coinRecord to [ [123, 10], [245, 145] ]
var distDataSet = [],
properties = Object.keys(coinRecord);
for (var i = 0; i < properties.length; i++) {
distDataSet.push([parseFloat(properties[i]), coinRecord[properties[i]]]);
};
postMessage([distDataSet, totalEarning, totalCost, earnPerRound, MAXIMUM_ROUNDS, fee]);
// console.log(distDataSet);
close();
} | duraraxbaccano/gist | st.petersburg.paradox.js | JavaScript | apache-2.0 | 1,299 |
/*
* 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 org.apache.cassandra.repair;
import java.net.InetAddress;
import java.nio.ByteBuffer;
import java.util.*;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.*;
import org.apache.commons.lang3.time.DurationFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.cassandra.concurrent.JMXConfigurableThreadPoolExecutor;
import org.apache.cassandra.concurrent.NamedThreadFactory;
import org.apache.cassandra.cql3.QueryOptions;
import org.apache.cassandra.cql3.QueryProcessor;
import org.apache.cassandra.cql3.UntypedResultSet;
import org.apache.cassandra.cql3.statements.SelectStatement;
import org.apache.cassandra.db.ColumnFamilyStore;
import org.apache.cassandra.db.ConsistencyLevel;
import org.apache.cassandra.dht.Range;
import org.apache.cassandra.dht.Token;
import org.apache.cassandra.repair.messages.RepairOption;
import org.apache.cassandra.service.ActiveRepairService;
import org.apache.cassandra.service.QueryState;
import org.apache.cassandra.service.StorageService;
import org.apache.cassandra.tracing.TraceKeyspace;
import org.apache.cassandra.tracing.TraceState;
import org.apache.cassandra.tracing.Tracing;
import org.apache.cassandra.transport.messages.ResultMessage;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.cassandra.utils.FBUtilities;
import org.apache.cassandra.utils.UUIDGen;
import org.apache.cassandra.utils.WrappedRunnable;
import org.apache.cassandra.utils.progress.ProgressEvent;
import org.apache.cassandra.utils.progress.ProgressEventNotifier;
import org.apache.cassandra.utils.progress.ProgressEventType;
import org.apache.cassandra.utils.progress.ProgressListener;
public class RepairRunnable extends WrappedRunnable implements ProgressEventNotifier
{
private static final Logger logger = LoggerFactory.getLogger(RepairRunnable.class);
private StorageService storageService;
private final int cmd;
private final RepairOption options;
private final String keyspace;
private final List<ProgressListener> listeners = new ArrayList<>();
public RepairRunnable(StorageService storageService, int cmd, RepairOption options, String keyspace)
{
this.storageService = storageService;
this.cmd = cmd;
this.options = options;
this.keyspace = keyspace;
}
@Override
public void addProgressListener(ProgressListener listener)
{
listeners.add(listener);
}
@Override
public void removeProgressListener(ProgressListener listener)
{
listeners.remove(listener);
}
protected void fireProgressEvent(String tag, ProgressEvent event)
{
for (ProgressListener listener : listeners)
{
listener.progress(tag, event);
}
}
protected void fireErrorAndComplete(String tag, int progressCount, int totalProgress, String message)
{
fireProgressEvent(tag, new ProgressEvent(ProgressEventType.ERROR, progressCount, totalProgress, message));
fireProgressEvent(tag, new ProgressEvent(ProgressEventType.COMPLETE, progressCount, totalProgress));
}
protected void runMayThrow() throws Exception
{
final TraceState traceState;
final String tag = "repair:" + cmd;
final AtomicInteger progress = new AtomicInteger();
final int totalProgress = 3 + options.getRanges().size(); // calculate neighbors, validation, prepare for repair + number of ranges to repair
String[] columnFamilies = options.getColumnFamilies().toArray(new String[options.getColumnFamilies().size()]);
Iterable<ColumnFamilyStore> validColumnFamilies = storageService.getValidColumnFamilies(false, false, keyspace,
columnFamilies);
final long startTime = System.currentTimeMillis();
String message = String.format("Starting repair command #%d, repairing keyspace %s with %s", cmd, keyspace,
options);
logger.info(message);
fireProgressEvent(tag, new ProgressEvent(ProgressEventType.START, 0, 100, message));
if (options.isTraced())
{
StringBuilder cfsb = new StringBuilder();
for (ColumnFamilyStore cfs : validColumnFamilies)
cfsb.append(", ").append(cfs.keyspace.getName()).append(".").append(cfs.name);
UUID sessionId = Tracing.instance.newSession(Tracing.TraceType.REPAIR);
traceState = Tracing.instance.begin("repair", ImmutableMap.of("keyspace", keyspace, "columnFamilies",
cfsb.substring(2)));
Tracing.traceRepair(message);
traceState.enableActivityNotification(tag);
for (ProgressListener listener : listeners)
traceState.addProgressListener(listener);
Thread queryThread = createQueryThread(cmd, sessionId);
queryThread.setName("RepairTracePolling");
queryThread.start();
}
else
{
traceState = null;
}
final Set<InetAddress> allNeighbors = new HashSet<>();
Map<Range, Set<InetAddress>> rangeToNeighbors = new HashMap<>();
//pre-calculate output of getLocalRanges and pass it to getNeighbors to increase performance and prevent
//calculation multiple times
Collection<Range<Token>> keyspaceLocalRanges = storageService.getLocalRanges(keyspace);
try
{
for (Range<Token> range : options.getRanges())
{
Set<InetAddress> neighbors = ActiveRepairService.getNeighbors(keyspace, keyspaceLocalRanges,
range, options.getDataCenters(),
options.getHosts());
rangeToNeighbors.put(range, neighbors);
allNeighbors.addAll(neighbors);
}
progress.incrementAndGet();
}
catch (IllegalArgumentException e)
{
logger.error("Repair failed:", e);
fireErrorAndComplete(tag, progress.get(), totalProgress, e.getMessage());
return;
}
// Validate columnfamilies
List<ColumnFamilyStore> columnFamilyStores = new ArrayList<>();
try
{
Iterables.addAll(columnFamilyStores, validColumnFamilies);
progress.incrementAndGet();
}
catch (IllegalArgumentException e)
{
fireErrorAndComplete(tag, progress.get(), totalProgress, e.getMessage());
return;
}
String[] cfnames = new String[columnFamilyStores.size()];
for (int i = 0; i < columnFamilyStores.size(); i++)
{
cfnames[i] = columnFamilyStores.get(i).name;
}
final UUID parentSession = UUIDGen.getTimeUUID();
SystemDistributedKeyspace.startParentRepair(parentSession, keyspace, cfnames, options.getRanges());
long repairedAt;
try
{
ActiveRepairService.instance.prepareForRepair(parentSession, FBUtilities.getBroadcastAddress(), allNeighbors, options, columnFamilyStores);
repairedAt = ActiveRepairService.instance.getParentRepairSession(parentSession).getRepairedAt();
progress.incrementAndGet();
}
catch (Throwable t)
{
SystemDistributedKeyspace.failParentRepair(parentSession, t);
fireErrorAndComplete(tag, progress.get(), totalProgress, t.getMessage());
return;
}
// Set up RepairJob executor for this repair command.
final ListeningExecutorService executor = MoreExecutors.listeningDecorator(new JMXConfigurableThreadPoolExecutor(options.getJobThreads(),
Integer.MAX_VALUE,
TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(),
new NamedThreadFactory("Repair#" + cmd),
"internal"));
List<ListenableFuture<RepairSessionResult>> futures = new ArrayList<>(options.getRanges().size());
for (Range<Token> range : options.getRanges())
{
final RepairSession session = ActiveRepairService.instance.submitRepairSession(parentSession,
range,
keyspace,
options.getParallelism(),
rangeToNeighbors.get(range),
repairedAt,
executor,
cfnames);
if (session == null)
continue;
// After repair session completes, notify client its result
Futures.addCallback(session, new FutureCallback<RepairSessionResult>()
{
public void onSuccess(RepairSessionResult result)
{
/**
* If the success message below is modified, it must also be updated on
* {@link org.apache.cassandra.utils.progress.jmx.LegacyJMXProgressSupport}
* for backward-compatibility support.
*/
String message = String.format("Repair session %s for range %s finished", session.getId(),
session.getRange().toString());
logger.info(message);
fireProgressEvent(tag, new ProgressEvent(ProgressEventType.PROGRESS,
progress.incrementAndGet(),
totalProgress,
message));
}
public void onFailure(Throwable t)
{
/**
* If the failure message below is modified, it must also be updated on
* {@link org.apache.cassandra.utils.progress.jmx.LegacyJMXProgressSupport}
* for backward-compatibility support.
*/
String message = String.format("Repair session %s for range %s failed with error %s",
session.getId(), session.getRange().toString(), t.getMessage());
logger.error(message, t);
fireProgressEvent(tag, new ProgressEvent(ProgressEventType.PROGRESS,
progress.incrementAndGet(),
totalProgress,
message));
}
});
futures.add(session);
}
// After all repair sessions completes(successful or not),
// run anticompaction if necessary and send finish notice back to client
final Collection<Range<Token>> successfulRanges = new ArrayList<>();
final AtomicBoolean hasFailure = new AtomicBoolean();
final ListenableFuture<List<RepairSessionResult>> allSessions = Futures.successfulAsList(futures);
ListenableFuture anticompactionResult = Futures.transform(allSessions, new AsyncFunction<List<RepairSessionResult>, Object>()
{
@SuppressWarnings("unchecked")
public ListenableFuture apply(List<RepairSessionResult> results) throws Exception
{
// filter out null(=failed) results and get successful ranges
for (RepairSessionResult sessionResult : results)
{
if (sessionResult != null)
{
successfulRanges.add(sessionResult.range);
}
else
{
hasFailure.compareAndSet(false, true);
}
}
return ActiveRepairService.instance.finishParentSession(parentSession, allNeighbors, successfulRanges);
}
});
Futures.addCallback(anticompactionResult, new FutureCallback<Object>()
{
public void onSuccess(Object result)
{
SystemDistributedKeyspace.successfulParentRepair(parentSession, successfulRanges);
if (hasFailure.get())
{
fireProgressEvent(tag, new ProgressEvent(ProgressEventType.ERROR, progress.get(), totalProgress,
"Some repair failed"));
}
else
{
fireProgressEvent(tag, new ProgressEvent(ProgressEventType.SUCCESS, progress.get(), totalProgress,
"Repair completed successfully"));
}
repairComplete();
}
public void onFailure(Throwable t)
{
fireProgressEvent(tag, new ProgressEvent(ProgressEventType.ERROR, progress.get(), totalProgress, t.getMessage()));
SystemDistributedKeyspace.failParentRepair(parentSession, t);
repairComplete();
}
private void repairComplete()
{
String duration = DurationFormatUtils.formatDurationWords(System.currentTimeMillis() - startTime,
true, true);
String message = String.format("Repair command #%d finished in %s", cmd, duration);
fireProgressEvent(tag, new ProgressEvent(ProgressEventType.COMPLETE, progress.get(), totalProgress, message));
logger.info(message);
if (options.isTraced() && traceState != null)
{
for (ProgressListener listener : listeners)
traceState.removeProgressListener(listener);
// Because DebuggableThreadPoolExecutor#afterExecute and this callback
// run in a nondeterministic order (within the same thread), the
// TraceState may have been nulled out at this point. The TraceState
// should be traceState, so just set it without bothering to check if it
// actually was nulled out.
Tracing.instance.set(traceState);
Tracing.traceRepair(message);
Tracing.instance.stopSession();
}
executor.shutdownNow();
}
});
}
private Thread createQueryThread(final int cmd, final UUID sessionId)
{
return new Thread(new WrappedRunnable()
{
// Query events within a time interval that overlaps the last by one second. Ignore duplicates. Ignore local traces.
// Wake up upon local trace activity. Query when notified of trace activity with a timeout that doubles every two timeouts.
public void runMayThrow() throws Exception
{
TraceState state = Tracing.instance.get(sessionId);
if (state == null)
throw new Exception("no tracestate");
String format = "select event_id, source, activity from %s.%s where session_id = ? and event_id > ? and event_id < ?;";
String query = String.format(format, TraceKeyspace.NAME, TraceKeyspace.EVENTS);
SelectStatement statement = (SelectStatement) QueryProcessor.parseStatement(query).prepare().statement;
ByteBuffer sessionIdBytes = ByteBufferUtil.bytes(sessionId);
InetAddress source = FBUtilities.getBroadcastAddress();
HashSet<UUID>[] seen = new HashSet[] { new HashSet<>(), new HashSet<>() };
int si = 0;
UUID uuid;
long tlast = System.currentTimeMillis(), tcur;
TraceState.Status status;
long minWaitMillis = 125;
long maxWaitMillis = 1000 * 1024L;
long timeout = minWaitMillis;
boolean shouldDouble = false;
while ((status = state.waitActivity(timeout)) != TraceState.Status.STOPPED)
{
if (status == TraceState.Status.IDLE)
{
timeout = shouldDouble ? Math.min(timeout * 2, maxWaitMillis) : timeout;
shouldDouble = !shouldDouble;
}
else
{
timeout = minWaitMillis;
shouldDouble = false;
}
ByteBuffer tminBytes = ByteBufferUtil.bytes(UUIDGen.minTimeUUID(tlast - 1000));
ByteBuffer tmaxBytes = ByteBufferUtil.bytes(UUIDGen.maxTimeUUID(tcur = System.currentTimeMillis()));
QueryOptions options = QueryOptions.forInternalCalls(ConsistencyLevel.ONE, Lists.newArrayList(sessionIdBytes,
tminBytes,
tmaxBytes));
ResultMessage.Rows rows = statement.execute(QueryState.forInternalCalls(), options);
UntypedResultSet result = UntypedResultSet.create(rows.result);
for (UntypedResultSet.Row r : result)
{
if (source.equals(r.getInetAddress("source")))
continue;
if ((uuid = r.getUUID("event_id")).timestamp() > (tcur - 1000) * 10000)
seen[si].add(uuid);
if (seen[si == 0 ? 1 : 0].contains(uuid))
continue;
String message = String.format("%s: %s", r.getInetAddress("source"), r.getString("activity"));
fireProgressEvent("repair:" + cmd,
new ProgressEvent(ProgressEventType.NOTIFICATION, 0, 0, message));
}
tlast = tcur;
si = si == 0 ? 1 : 0;
seen[si].clear();
}
}
});
}
}
| lynchlee/play-jmx | src/main/java/org/apache/cassandra/repair/RepairRunnable.java | Java | apache-2.0 | 20,493 |
package com.ibm.developer;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
/**
* Hello world!
*
*/
public class App {
public static void main(String[] args) throws IOException {
int port = Integer.parseInt(System.getenv("VCAP_APP_PORT"));
ServerSocket ss = new ServerSocket(port);
while (true) {
Socket s = ss.accept();
s.getOutputStream()
.write(("HTTP/1.1 200 OK\nContent-Type: text/html; charset=utf-8\nContent-Length: 2\n\n" + veryComplicatedMethod())
.getBytes());
}
}
public static int veryComplicatedMethod() {
return 42;
}
}
| cadrianomendes/bozocopy | src/main/java/com/ibm/developer/App.java | Java | apache-2.0 | 605 |
package fiddlewith.camel.component;
import java.io.File;
import java.net.URL;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.junit.Test;
import fiddle.repository.manager.FiddlesRepositoryManager;
import fiddle.repository.manager.RepositoryManager;
import fiddle.repository.manager.ResourcesRepositoryManager;
import fiddle.repository.manager.TemplatesRepositoryManager;
import fiddle.ruby.RubyExecutor;
public class HowToUse {
private static class TestRoute extends RouteBuilder {
@Override
public void configure() throws Exception {
from("direct:start").to("fiddle:demo:add").to("fiddle:demo:pow").process(new Processor() {
@Override
public void process(Exchange exchange) throws Exception {
System.out.println(exchange.getIn().getBody());
}
});
}
}
private final CamelContext camel;
public HowToUse() throws Exception {
final URL url = this.getClass().getResource("localised.donoterase");
final File globalDir = new File(url.getFile()).getParentFile();
final File repoDir = new File(globalDir, "repository");
this.camel = new DefaultCamelContext();
this.camel.addComponent("fiddle",
new FiddleComponent(
new RepositoryManager(
new FiddlesRepositoryManager(repoDir),
new TemplatesRepositoryManager(repoDir),
new ResourcesRepositoryManager(repoDir, null, null)),
new RubyExecutor()));
this.camel.addRoutes(new TestRoute());
this.camel.start();
}
@Test
public void tryOut() throws Exception {
camel.createProducerTemplate().sendBody("direct:start", "{\"a\":5, \"b\":6}");
camel.createProducerTemplate().sendBody("direct:start", "{\"a\":4, \"b\":3}");
camel.createProducerTemplate().sendBody("direct:start", "{\"a\":9, \"b\":0}");
}
}
| cedricbou/FiddleWith | camel-component/src/test/java/fiddlewith/camel/component/HowToUse.java | Java | apache-2.0 | 1,902 |
package com.imethod.service.sys.service;
import com.imethod.service.sys.dao.AuthDao;
import com.imethod.service.sys.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* auth : iMethod
* create_at: 15/12/1.
* desc:
* note:
* 1.
*/
@Service
public class AuthService {
@Autowired
private AuthDao authDao;
public User getLoginUser(String inputEmail, String inputPassword) {
return authDao.getLoginUser(inputEmail, inputPassword);
}
}
| bqxu/JMethod | service/sys/src/main/java/com/imethod/service/sys/service/AuthService.java | Java | apache-2.0 | 541 |
/*
* This source has been modified. The original source applied this license:
*
* Copyright (C) 2007 The Guava 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.
*/
package com.jameswald.skinnylatte.common.util.concurrent;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
public interface ListenableFuture<V> extends Future<V> {
void addListener(Runnable listener, Executor executor);
}
| jameswald/skinny-latte | common/src/main/java/com/jameswald/skinnylatte/common/util/concurrent/ListenableFuture.java | Java | apache-2.0 | 932 |
/* Generated by camel build tools - do NOT edit this file! */
package org.apache.camel.component.fhir;
import java.util.Map;
import org.apache.camel.CamelContext;
import org.apache.camel.spi.ConfigurerStrategy;
import org.apache.camel.spi.GeneratedPropertyConfigurer;
import org.apache.camel.spi.PropertyConfigurerGetter;
import org.apache.camel.util.CaseInsensitiveMap;
import org.apache.camel.component.fhir.FhirValidateEndpointConfiguration;
/**
* Generated by camel build tools - do NOT edit this file!
*/
@SuppressWarnings("unchecked")
public class FhirValidateEndpointConfigurationConfigurer extends org.apache.camel.support.component.PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter {
private static final Map<String, Object> ALL_OPTIONS;
static {
Map<String, Object> map = new CaseInsensitiveMap();
map.put("AccessToken", java.lang.String.class);
map.put("ApiName", org.apache.camel.component.fhir.internal.FhirApiName.class);
map.put("Client", ca.uhn.fhir.rest.client.api.IGenericClient.class);
map.put("ClientFactory", ca.uhn.fhir.rest.client.api.IRestfulClientFactory.class);
map.put("Compress", boolean.class);
map.put("ConnectionTimeout", java.lang.Integer.class);
map.put("DeferModelScanning", boolean.class);
map.put("Encoding", java.lang.String.class);
map.put("ExtraParameters", java.util.Map.class);
map.put("FhirContext", ca.uhn.fhir.context.FhirContext.class);
map.put("FhirVersion", java.lang.String.class);
map.put("ForceConformanceCheck", boolean.class);
map.put("Log", boolean.class);
map.put("MethodName", java.lang.String.class);
map.put("Password", java.lang.String.class);
map.put("PrettyPrint", boolean.class);
map.put("ProxyHost", java.lang.String.class);
map.put("ProxyPassword", java.lang.String.class);
map.put("ProxyPort", java.lang.Integer.class);
map.put("ProxyUser", java.lang.String.class);
map.put("Resource", org.hl7.fhir.instance.model.api.IBaseResource.class);
map.put("ResourceAsString", java.lang.String.class);
map.put("ServerUrl", java.lang.String.class);
map.put("SessionCookie", java.lang.String.class);
map.put("SocketTimeout", java.lang.Integer.class);
map.put("Summary", java.lang.String.class);
map.put("Username", java.lang.String.class);
map.put("ValidationMode", java.lang.String.class);
ALL_OPTIONS = map;
ConfigurerStrategy.addConfigurerClearer(FhirValidateEndpointConfigurationConfigurer::clearConfigurers);
}
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
org.apache.camel.component.fhir.FhirValidateEndpointConfiguration target = (org.apache.camel.component.fhir.FhirValidateEndpointConfiguration) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "accesstoken":
case "AccessToken": target.setAccessToken(property(camelContext, java.lang.String.class, value)); return true;
case "apiname":
case "ApiName": target.setApiName(property(camelContext, org.apache.camel.component.fhir.internal.FhirApiName.class, value)); return true;
case "client":
case "Client": target.setClient(property(camelContext, ca.uhn.fhir.rest.client.api.IGenericClient.class, value)); return true;
case "clientfactory":
case "ClientFactory": target.setClientFactory(property(camelContext, ca.uhn.fhir.rest.client.api.IRestfulClientFactory.class, value)); return true;
case "compress":
case "Compress": target.setCompress(property(camelContext, boolean.class, value)); return true;
case "connectiontimeout":
case "ConnectionTimeout": target.setConnectionTimeout(property(camelContext, java.lang.Integer.class, value)); return true;
case "defermodelscanning":
case "DeferModelScanning": target.setDeferModelScanning(property(camelContext, boolean.class, value)); return true;
case "encoding":
case "Encoding": target.setEncoding(property(camelContext, java.lang.String.class, value)); return true;
case "extraparameters":
case "ExtraParameters": target.setExtraParameters(property(camelContext, java.util.Map.class, value)); return true;
case "fhircontext":
case "FhirContext": target.setFhirContext(property(camelContext, ca.uhn.fhir.context.FhirContext.class, value)); return true;
case "fhirversion":
case "FhirVersion": target.setFhirVersion(property(camelContext, java.lang.String.class, value)); return true;
case "forceconformancecheck":
case "ForceConformanceCheck": target.setForceConformanceCheck(property(camelContext, boolean.class, value)); return true;
case "log":
case "Log": target.setLog(property(camelContext, boolean.class, value)); return true;
case "methodname":
case "MethodName": target.setMethodName(property(camelContext, java.lang.String.class, value)); return true;
case "password":
case "Password": target.setPassword(property(camelContext, java.lang.String.class, value)); return true;
case "prettyprint":
case "PrettyPrint": target.setPrettyPrint(property(camelContext, boolean.class, value)); return true;
case "proxyhost":
case "ProxyHost": target.setProxyHost(property(camelContext, java.lang.String.class, value)); return true;
case "proxypassword":
case "ProxyPassword": target.setProxyPassword(property(camelContext, java.lang.String.class, value)); return true;
case "proxyport":
case "ProxyPort": target.setProxyPort(property(camelContext, java.lang.Integer.class, value)); return true;
case "proxyuser":
case "ProxyUser": target.setProxyUser(property(camelContext, java.lang.String.class, value)); return true;
case "resource":
case "Resource": target.setResource(property(camelContext, org.hl7.fhir.instance.model.api.IBaseResource.class, value)); return true;
case "resourceasstring":
case "ResourceAsString": target.setResourceAsString(property(camelContext, java.lang.String.class, value)); return true;
case "serverurl":
case "ServerUrl": target.setServerUrl(property(camelContext, java.lang.String.class, value)); return true;
case "sessioncookie":
case "SessionCookie": target.setSessionCookie(property(camelContext, java.lang.String.class, value)); return true;
case "sockettimeout":
case "SocketTimeout": target.setSocketTimeout(property(camelContext, java.lang.Integer.class, value)); return true;
case "summary":
case "Summary": target.setSummary(property(camelContext, java.lang.String.class, value)); return true;
case "username":
case "Username": target.setUsername(property(camelContext, java.lang.String.class, value)); return true;
case "validationmode":
case "ValidationMode": target.setValidationMode(property(camelContext, java.lang.String.class, value)); return true;
default: return false;
}
}
@Override
public Map<String, Object> getAllOptions(Object target) {
return ALL_OPTIONS;
}
public static void clearBootstrapConfigurers() {
}
public static void clearConfigurers() {
ALL_OPTIONS.clear();
}
@Override
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
org.apache.camel.component.fhir.FhirValidateEndpointConfiguration target = (org.apache.camel.component.fhir.FhirValidateEndpointConfiguration) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "accesstoken":
case "AccessToken": return target.getAccessToken();
case "apiname":
case "ApiName": return target.getApiName();
case "client":
case "Client": return target.getClient();
case "clientfactory":
case "ClientFactory": return target.getClientFactory();
case "compress":
case "Compress": return target.isCompress();
case "connectiontimeout":
case "ConnectionTimeout": return target.getConnectionTimeout();
case "defermodelscanning":
case "DeferModelScanning": return target.isDeferModelScanning();
case "encoding":
case "Encoding": return target.getEncoding();
case "extraparameters":
case "ExtraParameters": return target.getExtraParameters();
case "fhircontext":
case "FhirContext": return target.getFhirContext();
case "fhirversion":
case "FhirVersion": return target.getFhirVersion();
case "forceconformancecheck":
case "ForceConformanceCheck": return target.isForceConformanceCheck();
case "log":
case "Log": return target.isLog();
case "methodname":
case "MethodName": return target.getMethodName();
case "password":
case "Password": return target.getPassword();
case "prettyprint":
case "PrettyPrint": return target.isPrettyPrint();
case "proxyhost":
case "ProxyHost": return target.getProxyHost();
case "proxypassword":
case "ProxyPassword": return target.getProxyPassword();
case "proxyport":
case "ProxyPort": return target.getProxyPort();
case "proxyuser":
case "ProxyUser": return target.getProxyUser();
case "resource":
case "Resource": return target.getResource();
case "resourceasstring":
case "ResourceAsString": return target.getResourceAsString();
case "serverurl":
case "ServerUrl": return target.getServerUrl();
case "sessioncookie":
case "SessionCookie": return target.getSessionCookie();
case "sockettimeout":
case "SocketTimeout": return target.getSocketTimeout();
case "summary":
case "Summary": return target.getSummary();
case "username":
case "Username": return target.getUsername();
case "validationmode":
case "ValidationMode": return target.getValidationMode();
default: return null;
}
}
@Override
public Object getCollectionValueType(Object target, String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase() : name) {
case "extraparameters":
case "ExtraParameters": return java.lang.Object.class;
default: return null;
}
}
}
| mcollovati/camel | components/camel-fhir/camel-fhir-component/src/generated/java/org/apache/camel/component/fhir/FhirValidateEndpointConfigurationConfigurer.java | Java | apache-2.0 | 10,640 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MvvmCross.Plugins.BLE.iOS")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Zuehlke Technology Group")]
[assembly: AssemblyProduct("MvvmCross.Plugins.BLE.iOS")]
[assembly: AssemblyCopyright("Copyright © Zuehlke Technology Group 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("7ba2a80e-62f9-44f8-bb2d-2a9fafe38d3d")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.1.0")]
[assembly: AssemblyVersion("1.1.0")]
[assembly: AssemblyFileVersion("1.1.0")]
| gtg529s/xamarin-bluetooth-le | Source/MvvmCross.Plugins.BLE.iOS/Properties/AssemblyInfo.cs | C# | apache-2.0 | 1,502 |
/*
* Copyright (C) 2020 The Android Open Source Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if defined(LIBC_STATIC)
#error This file should not be compiled for static targets.
#endif
#include <fcntl.h>
#include <signal.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/ucontext.h>
#include <sys/un.h>
#include <async_safe/log.h>
#include <platform/bionic/malloc.h>
#include <platform/bionic/reserved_signals.h>
#include <private/ErrnoRestorer.h>
#include <private/ScopedFd.h>
#include "malloc_heapprofd.h"
// This file defines the handler for the reserved signal sent by the Android
// platform's profilers. The accompanying signal value discriminates between
// specific requestors:
// 0: heapprofd heap profiler.
// 1: traced_perf perf profiler.
static constexpr int kHeapprofdSignalValue = 0;
static constexpr int kTracedPerfSignalValue = 1;
static void HandleProfilingSignal(int, siginfo_t*, void*);
// Called during dynamic libc preinit.
__LIBC_HIDDEN__ void __libc_init_profiling_handlers() {
struct sigaction action = {};
action.sa_flags = SA_SIGINFO | SA_RESTART;
action.sa_sigaction = HandleProfilingSignal;
sigaction(BIONIC_SIGNAL_PROFILER, &action, nullptr);
// The perfetto_hprof ART plugin installs a signal handler to handle this signal. That plugin
// does not get loaded for a) non-apps, b) non-profilable apps on user. The default signal
// disposition is to crash. We do not want the target to crash if we accidentally target a
// non-app or non-profilable process.
//
// This does *not* get run for processes that statically link libc, and those will still crash.
signal(BIONIC_SIGNAL_ART_PROFILER, SIG_IGN);
}
static void HandleSigsysSeccompOverride(int, siginfo_t*, void*);
static void HandleTracedPerfSignal();
static void HandleProfilingSignal(int /*signal_number*/, siginfo_t* info, void* /*ucontext*/) {
ErrnoRestorer errno_restorer;
if (info->si_code != SI_QUEUE) {
return;
}
int signal_value = info->si_value.sival_int;
async_safe_format_log(ANDROID_LOG_INFO, "libc", "%s: received profiling signal with si_value: %d",
getprogname(), signal_value);
// Proceed only if the process is considered profileable.
bool profileable = false;
android_mallopt(M_GET_PROCESS_PROFILEABLE, &profileable, sizeof(profileable));
if (!profileable) {
async_safe_write_log(ANDROID_LOG_ERROR, "libc", "profiling signal rejected (not profileable)");
return;
}
// Temporarily override SIGSYS handling, in a best-effort attempt at not
// crashing if we happen to be running in a process with a seccomp filter that
// disallows some of the syscalls done by this signal handler. This protects
// against SECCOMP_RET_TRAP with a crashing SIGSYS handler (typical of android
// minijails). Won't help if the filter is using SECCOMP_RET_KILL_*.
// Note: the override is process-wide, but short-lived. The syscalls are still
// blocked, but the overridden handler recovers from SIGSYS, and fakes the
// syscall return value as ENOSYS.
struct sigaction sigsys_override = {};
sigsys_override.sa_sigaction = &HandleSigsysSeccompOverride;
sigsys_override.sa_flags = SA_SIGINFO;
struct sigaction old_act = {};
sigaction(SIGSYS, &sigsys_override, &old_act);
if (signal_value == kHeapprofdSignalValue) {
HandleHeapprofdSignal();
} else if (signal_value == kTracedPerfSignalValue) {
HandleTracedPerfSignal();
} else {
async_safe_format_log(ANDROID_LOG_ERROR, "libc", "unrecognized profiling signal si_value: %d",
signal_value);
}
sigaction(SIGSYS, &old_act, nullptr);
}
// Open /proc/self/{maps,mem}, connect to traced_perf, send the fds over the
// socket. Everything happens synchronously within the signal handler. Socket
// is made non-blocking, and we do not retry.
static void HandleTracedPerfSignal() {
ScopedFd sock_fd{ socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0 /*protocol*/) };
if (sock_fd.get() == -1) {
async_safe_format_log(ANDROID_LOG_ERROR, "libc", "failed to create socket: %s", strerror(errno));
return;
}
sockaddr_un saddr{ AF_UNIX, "/dev/socket/traced_perf" };
size_t addrlen = sizeof(sockaddr_un);
if (connect(sock_fd.get(), reinterpret_cast<const struct sockaddr*>(&saddr), addrlen) == -1) {
async_safe_format_log(ANDROID_LOG_ERROR, "libc", "failed to connect to traced_perf socket: %s",
strerror(errno));
return;
}
ScopedFd maps_fd{ open("/proc/self/maps", O_RDONLY | O_CLOEXEC) };
if (maps_fd.get() == -1) {
async_safe_format_log(ANDROID_LOG_ERROR, "libc", "failed to open /proc/self/maps: %s",
strerror(errno));
return;
}
ScopedFd mem_fd{ open("/proc/self/mem", O_RDONLY | O_CLOEXEC) };
if (mem_fd.get() == -1) {
async_safe_format_log(ANDROID_LOG_ERROR, "libc", "failed to open /proc/self/mem: %s",
strerror(errno));
return;
}
// Send 1 byte with auxiliary data carrying two fds.
int send_fds[2] = { maps_fd.get(), mem_fd.get() };
int num_fds = 2;
char iobuf[1] = {};
msghdr msg_hdr = {};
iovec iov = { reinterpret_cast<void*>(iobuf), sizeof(iobuf) };
msg_hdr.msg_iov = &iov;
msg_hdr.msg_iovlen = 1;
alignas(cmsghdr) char control_buf[256] = {};
const auto raw_ctl_data_sz = num_fds * sizeof(int);
const size_t control_buf_len = static_cast<size_t>(CMSG_SPACE(raw_ctl_data_sz));
msg_hdr.msg_control = control_buf;
msg_hdr.msg_controllen = control_buf_len; // used by CMSG_FIRSTHDR
struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg_hdr);
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_RIGHTS;
cmsg->cmsg_len = static_cast<size_t>(CMSG_LEN(raw_ctl_data_sz));
memcpy(CMSG_DATA(cmsg), send_fds, num_fds * sizeof(int));
if (sendmsg(sock_fd.get(), &msg_hdr, 0) == -1) {
async_safe_format_log(ANDROID_LOG_ERROR, "libc", "failed to sendmsg: %s", strerror(errno));
}
}
static void HandleSigsysSeccompOverride(int /*signal_number*/, siginfo_t* info,
void* void_context) {
ErrnoRestorer errno_restorer;
if (info->si_code != SYS_SECCOMP) {
return;
}
async_safe_format_log(
ANDROID_LOG_WARN, "libc",
"Profiling setup: trapped seccomp SIGSYS for syscall %d. Returning ENOSYS to caller.",
info->si_syscall);
// The handler is responsible for setting the return value as if the system
// call happened (which is arch-specific). Use a plausible unsuccessful value.
auto ret = -ENOSYS;
ucontext_t* ctx = reinterpret_cast<ucontext_t*>(void_context);
#if defined(__arm__)
ctx->uc_mcontext.arm_r0 = ret;
#elif defined(__aarch64__)
ctx->uc_mcontext.regs[0] = ret; // x0
#elif defined(__i386__)
ctx->uc_mcontext.gregs[REG_EAX] = ret;
#elif defined(__x86_64__)
ctx->uc_mcontext.gregs[REG_RAX] = ret;
#else
#error "unsupported architecture"
#endif
}
| webos21/xbionic | platform_bionic-android-vts-12.0_r2/libc/bionic/android_profiling_dynamic.cpp | C++ | apache-2.0 | 8,263 |
package ru.aplana.tools;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Random;
import java.util.UUID;
import javax.jms.BytesMessage;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.TextMessage;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;
import org.apache.commons.lang.StringUtils;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
/**
* Some useful methods
*
* @author Maksim Stepanov
* @version 1.0
*/
public class Common {
/**
* non -instanceable class
*
*/
private Common() {
}
/**
*
* Convert a SOAP message to String
*
* @param soapResponse
* - soap message
* @return String representation of SOAP message
*/
public static String convertSOAPResponse(SOAPMessage soapResponse) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
soapResponse.writeTo(out);
} catch (SOAPException | IOException e) {
e.printStackTrace();
}
String resp = new String(out.toString());
return resp;
}
/**
* Generating random task_id
*
*
* @return String at format 442FBA62-156E-185F-34A0-CD82B7A1F7A9
*
*/
public static String generateTaskId() {
String taskid = "";
String characters = "QWERTYUIOPASDFGHJKLZXCVBNM";
Random rng = new Random();
for (int i = 0; i < 16; i++) {
int value = (int) (Math.random() * 10);
taskid += value;
String ch = String.valueOf(characters.charAt(rng.nextInt(characters.length())));
taskid += ch;
switch (taskid.length()) {
case 8:
taskid += "-";
break;
case 13:
taskid += "-";
break;
case 18:
taskid += "-";
break;
case 23:
taskid += "-";
break;
}
}
return taskid;
}
/**
* Generating random number requirement length
*
* @param length
* - requirement length
*
* @return Random string of numbers. If length = 0 return empty string
*/
public static String generateNumber(int length) {
String id = "";
for (int i = 0; i < length; i++) {
int value = (int) (1 + (Math.random() * 9));
id += value;
}
return id;
}
/**
* Convert MQ message to String
*
* @param inputMsg
* - message from MQ
* @return string representation MQ message
*/
public static String parseMessMQ(Message inputMsg) {
String request = "";
if (inputMsg instanceof TextMessage) {
try {
request = ((TextMessage) inputMsg).getText();
} catch (JMSException e) {
e.printStackTrace();
}
} else if (inputMsg instanceof BytesMessage) {
try {
int l = (int) ((BytesMessage) inputMsg).getBodyLength();
byte[] buff = new byte[l];
((BytesMessage) inputMsg).readBytes(buff);
request = new String(buff);
} catch (JMSException e) {
e.printStackTrace();
}
}
return request;
}
/**
* Generating date of birthday
*
* @param yearStart
* - start year, offset - offset relatively yearStart
*
* @return Date of birthday at format yyyy-mm-dd
*
*/
public static String generateDOB(int yearStart, int offset) {
String dob = "";
int valueMonth = (int) (1 + (Math.random() * 12));
int valueDay = (int) (1 + (Math.random() * 28));
int valueYear = (int) (yearStart + (Math.random() * offset));
String year = String.valueOf(valueYear);
String day = String.valueOf(valueDay);
String month = String.valueOf(valueMonth);
if (day.length() == 1) {
day = "0" + day;
}
if (month.length() == 1) {
month = "0" + month;
}
dob = year + "-" + month + "-" + day;
return dob;
}
/**
* Generating RQUID
*
* @return String of digits with length 32 signs
*
*/
public static String generateRqUID() {
return StringUtils.replace(UUID.randomUUID().toString(), "-", "");
}
/**
* Generating random Name requirement length
*
* @param length
* - length for value
*
* @return Random string requirement length
*
*/
public static String generateName(int length) {
Random rng = new Random();
String characters = null;
characters = "йцукенгшщзхъэждлорпавыфячсмитьбю";
char[] text = new char[length];
for (int i = 0; i < length; i++) {
text[i] = characters.charAt(rng.nextInt(characters.length()));
}
return new String(text);
}
/**
*
* Convert to translit
*
* HashMap<Character, String> relate = new HashMap<Character, String>(40);
*
* relate.put('�', "A"); relate.put('�', "B"); relate.put('�', "V");
* relate.put('�', "G"); relate.put('�', "D"); relate.put('�', "E");
* relate.put('�', "Jo"); relate.put('�', "J"); relate.put('�', "Zh");
* relate.put('�', "I"); relate.put('�', "I"); relate.put('�', "K");
* relate.put('�', "L"); relate.put('�', "M"); relate.put('�', "N");
* relate.put('�', "O"); relate.put('�', "P"); relate.put('�', "R");
* relate.put('�', "S"); relate.put('�', "T"); relate.put('�', "U");
* relate.put('�', "F"); relate.put('�', "H"); relate.put('�', "Ch");
* relate.put('�', "C"); relate.put('�', "Sh"); relate.put('�', "Csh");
* relate.put('�', "E"); relate.put('�', "Ju"); relate.put('�', "Ja");
* relate.put('�', "Y"); relate.put('�', "`"); relate.put('�', "'");
*
* }
*
* @param word
* - Russian word
* @param relate
* relation
* @return Translite representation of Russian word
*
*/
public static String convertToTranslite(String russianWord, HashMap<String, String> relate) {
String result = "";
int length = russianWord.length();
for (int i = 0; i < length; i++) {
result += relate.get(russianWord.charAt(i));
}
return result;
}
/**
*
* Return root element of xml
*
* @param message
* - xml representation of message
* @return root element
* @throws ParserConfigurationException
* @throws IOException
* @throws SAXException
*/
public static String getParentNodeName(String message)
throws ParserConfigurationException, SAXException, IOException {
String root = null;
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputStream inputStream1 = new ByteArrayInputStream(message.getBytes("UTF-8"));
Element records1 = builder.parse(inputStream1).getDocumentElement();
records1.normalize();
String parentTagName = records1.getTagName();
String[] tags = parentTagName.split(":");
if (tags.length == 2) {
root = tags[1];
} else {
root = tags[0];
}
return root;
}
/**
*
* Call any soap service
*
* @param message
* - soap message
* @param url
* - http url to soap server
* @return - String representation of soap message
* @throws SOAPException
* @throws UnsupportedOperationException
*/
public static String callSoapService(SOAPMessage message, String url)
throws UnsupportedOperationException, SOAPException {
SOAPConnectionFactory soapConnectionFactory = null;
SOAPConnection soapConnection = null;
String response = "";
try {
// Create SOAP Connection
soapConnectionFactory = SOAPConnectionFactory.newInstance();
soapConnection = soapConnectionFactory.createConnection();
// Send SOAP Message to SOAP Server
SOAPMessage soapResponse = soapConnection.call(message, url);
// Process the SOAP Response
try {
response = convertSOAPResponse(soapResponse);
} catch (Exception e) {
e.printStackTrace();
}
} finally {
if (null != soapConnection) {
try {
soapConnection.close();
soapConnectionFactory = null;
} catch (SOAPException e) {
e.printStackTrace();
}
}
}
return response;
}
/**
*
* Generate snils number
*
* @return snils in format 123-123-123 12
*/
public static String generateSnils() {
StringBuilder sb = new StringBuilder();
int sum = 0;
for (int i = 9; i > 0; i--) {
int value = (int) (1 + (Math.random() * 9));
sum += value * i;
sb.append(value);
if (i == 7 || i == 4) {
sb.append("-");
}
}
sb.append(" ").append(getSnilsControlNumber(sum));
return sb.toString();
}
/**
* Get control number of snils
*
* @param sum
* of snils numbers
* @return - control number of snils
*/
private static String getSnilsControlNumber(int sum) {
String controlNumber = "";
if (sum < 100) {
if (sum < 10) {
controlNumber = "0" + sum;
} else {
controlNumber = String.valueOf(sum);
}
}
if (sum == 100 || sum == 101) {
controlNumber = "00";
}
if (sum > 101) {
controlNumber = getSnilsControlNumber(sum % 101);
}
return controlNumber;
}
}
| maksim-stsiapanau/Java-JMS | ru.aplana.lib/src/main/java/ru/aplana/tools/Common.java | Java | apache-2.0 | 9,019 |
package com.yingt.service.util;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
/**
* Map Utils
*
* @author <a href="http://www.trinea.cn" target="_blank">Trinea</a> 2011-7-22
*/
public class MapUtils {
/** default separator between key and value **/
public static final String DEFAULT_KEY_AND_VALUE_SEPARATOR = ":";
/** default separator between key-value pairs **/
public static final String DEFAULT_KEY_AND_VALUE_PAIR_SEPARATOR = ",";
private MapUtils() {
throw new AssertionError();
}
/**
* is null or its size is 0
*
* <pre>
* isEmpty(null) = true;
* isEmpty({}) = true;
* isEmpty({1, 2}) = false;
* </pre>
*
* @param sourceMap
* @return if map is null or its size is 0, return true, else return false.
*/
public static <K, V> boolean isEmpty(Map<K, V> sourceMap) {
return (sourceMap == null || sourceMap.size() == 0);
}
/**
* add key-value pair to map, and key need not null or empty
*
* @param map
* @param key
* @param value
* @return <ul>
* <li>if map is null, return false</li>
* <li>if key is null or empty, return false</li>
* <li>return {@link Map#put(Object, Object)}</li>
* </ul>
*/
public static boolean putMapNotEmptyKey(Map<String, String> map, String key, String value) {
if (map == null || StringUtils.isEmpty(key)) {
return false;
}
map.put(key, value);
return true;
}
/**
* add key-value pair to map, both key and value need not null or empty
*
* @param map
* @param key
* @param value
* @return <ul>
* <li>if map is null, return false</li>
* <li>if key is null or empty, return false</li>
* <li>if value is null or empty, return false</li>
* <li>return {@link Map#put(Object, Object)}</li>
* </ul>
*/
public static boolean putMapNotEmptyKeyAndValue(Map<String, String> map, String key, String value) {
if (map == null || StringUtils.isEmpty(key) || StringUtils.isEmpty(value)) {
return false;
}
map.put(key, value);
return true;
}
/**
* add key-value pair to map, key need not null or empty
*
* @param map
* @param key
* @param value
* @param defaultValue
* @return <ul>
* <li>if map is null, return false</li>
* <li>if key is null or empty, return false</li>
* <li>if value is null or empty, put defaultValue, return true</li>
* <li>if value is neither null nor empty,put value, return true</li>
* </ul>
*/
public static boolean putMapNotEmptyKeyAndValue(Map<String, String> map, String key, String value,
String defaultValue) {
if (map == null || StringUtils.isEmpty(key)) {
return false;
}
map.put(key, StringUtils.isEmpty(value) ? defaultValue : value);
return true;
}
/**
* add key-value pair to map, key need not null
*
* @param map
* @param key
* @param value
* @return <ul>
* <li>if map is null, return false</li>
* <li>if key is null, return false</li>
* <li>return {@link Map#put(Object, Object)}</li>
* </ul>
*/
public static <K, V> boolean putMapNotNullKey(Map<K, V> map, K key, V value) {
if (map == null || key == null) {
return false;
}
map.put(key, value);
return true;
}
/**
* add key-value pair to map, both key and value need not null
*
* @param map
* @param key
* @param value
* @return <ul>
* <li>if map is null, return false</li>
* <li>if key is null, return false</li>
* <li>if value is null, return false</li>
* <li>return {@link Map#put(Object, Object)}</li>
* </ul>
*/
public static <K, V> boolean putMapNotNullKeyAndValue(Map<K, V> map, K key, V value) {
if (map == null || key == null || value == null) {
return false;
}
map.put(key, value);
return true;
}
/**
* get key by value, match the first entry front to back
* <ul>
* <strong>Attentions:</strong>
* <li>for HashMap, the order of entry not same to put order, so you may need to use TreeMap</li>
* </ul>
*
* @param <V>
* @param map
* @param value
* @return <ul>
* <li>if map is null, return null</li>
* <li>if value exist, return key</li>
* <li>return null</li>
* </ul>
*/
public static <K, V> K getKeyByValue(Map<K, V> map, V value) {
if (isEmpty(map)) {
return null;
}
for (Entry<K, V> entry : map.entrySet()) {
if (ObjectUtils.isEquals(entry.getValue(), value)) {
return entry.getKey();
}
}
return null;
}
/**
* parse key-value pairs to map, ignore empty key
*
* <pre>
* parseKeyAndValueToMap("","","",true)=null
* parseKeyAndValueToMap(null,"","",true)=null
* parseKeyAndValueToMap("a:b,:","","",true)={(a,b)}
* parseKeyAndValueToMap("a:b,:d","","",true)={(a,b)}
* parseKeyAndValueToMap("a:b,c:d","","",true)={(a,b),(c,d)}
* parseKeyAndValueToMap("a=b, c = d","=",",",true)={(a,b),(c,d)}
* parseKeyAndValueToMap("a=b, c = d","=",",",false)={(a, b),( c , d)}
* parseKeyAndValueToMap("a=b, c=d","=", ",", false)={(a,b),( c,d)}
* parseKeyAndValueToMap("a=b; c=d","=", ";", false)={(a,b),( c,d)}
* parseKeyAndValueToMap("a=b, c=d", ",", ";", false)={(a=b, c=d)}
* </pre>
*
* @param source key-value pairs
* @param keyAndValueSeparator separator between key and value
* @param keyAndValuePairSeparator separator between key-value pairs
* @param ignoreSpace whether ignore space at the begging or end of key and value
* @return
*/
public static Map<String, String> parseKeyAndValueToMap(String source, String keyAndValueSeparator,
String keyAndValuePairSeparator, boolean ignoreSpace) {
if (StringUtils.isEmpty(source)) {
return null;
}
if (StringUtils.isEmpty(keyAndValueSeparator)) {
keyAndValueSeparator = DEFAULT_KEY_AND_VALUE_SEPARATOR;
}
if (StringUtils.isEmpty(keyAndValuePairSeparator)) {
keyAndValuePairSeparator = DEFAULT_KEY_AND_VALUE_PAIR_SEPARATOR;
}
Map<String, String> keyAndValueMap = new HashMap<String, String>();
String[] keyAndValueArray = source.split(keyAndValuePairSeparator);
if (keyAndValueArray == null) {
return null;
}
int seperator;
for (String valueEntity : keyAndValueArray) {
if (!StringUtils.isEmpty(valueEntity)) {
seperator = valueEntity.indexOf(keyAndValueSeparator);
if (seperator != -1) {
if (ignoreSpace) {
MapUtils.putMapNotEmptyKey(keyAndValueMap, valueEntity.substring(0, seperator).trim(),
valueEntity.substring(seperator + 1).trim());
} else {
MapUtils.putMapNotEmptyKey(keyAndValueMap, valueEntity.substring(0, seperator),
valueEntity.substring(seperator + 1));
}
}
}
}
return keyAndValueMap;
}
/**
* parse key-value pairs to map, ignore empty key
*
* @param source key-value pairs
* @param ignoreSpace whether ignore space at the begging or end of key and value
* @return
* @see {@link MapUtils#parseKeyAndValueToMap(String, String, String, boolean)}, keyAndValueSeparator is
* {@link #DEFAULT_KEY_AND_VALUE_SEPARATOR}, keyAndValuePairSeparator is
* {@link #DEFAULT_KEY_AND_VALUE_PAIR_SEPARATOR}
*/
public static Map<String, String> parseKeyAndValueToMap(String source, boolean ignoreSpace) {
return parseKeyAndValueToMap(source, DEFAULT_KEY_AND_VALUE_SEPARATOR, DEFAULT_KEY_AND_VALUE_PAIR_SEPARATOR,
ignoreSpace);
}
/**
* parse key-value pairs to map, ignore empty key, ignore space at the begging or end of key and value
*
* @param source key-value pairs
* @return
* @see {@link MapUtils#parseKeyAndValueToMap(String, String, String, boolean)}, keyAndValueSeparator is
* {@link #DEFAULT_KEY_AND_VALUE_SEPARATOR}, keyAndValuePairSeparator is
* {@link #DEFAULT_KEY_AND_VALUE_PAIR_SEPARATOR}, ignoreSpace is true
*/
public static Map<String, String> parseKeyAndValueToMap(String source) {
return parseKeyAndValueToMap(source, DEFAULT_KEY_AND_VALUE_SEPARATOR, DEFAULT_KEY_AND_VALUE_PAIR_SEPARATOR,
true);
}
/**
* join map
*
* @param map
* @return
*/
public static String toJson(Map<String, String> map) {
if (map == null || map.size() == 0) {
return null;
}
StringBuilder paras = new StringBuilder();
paras.append("{");
Iterator<Entry<String, String>> ite = map.entrySet().iterator();
while (ite.hasNext()) {
Entry<String, String> entry = (Entry<String, String>)ite.next();
paras.append("\"").append(entry.getKey()).append("\":\"").append(entry.getValue()).append("\"");
if (ite.hasNext()) {
paras.append(",");
}
}
paras.append("}");
return paras.toString();
}
}
| wanlihuan/phone-touch | yingt-framework/common-service/src/main/java/com/yingt/service/util/MapUtils.java | Java | apache-2.0 | 9,918 |
//FILE: bg.js
/**
* this is a background service and this code will run *every* time the
* application goes into the foreground
*/
var value = "Hello from Running BG service - bg.js";
Ti.API.info(value);
var notification = Ti.App.iOS.scheduleLocalNotification({
alertBody:"App was put in background",
alertAction:"Re-Launch!",
userInfo:{"hello":"world"},
date:new Date(new Date().getTime() + 3000) // 3 seconds after backgrounding
});
Ti.App.iOS.addEventListener('notification',function(){
Ti.API.info('background event received = '+notification);
//Ti.App.currentService.unregister();
});
// we need to explicitly stop the service or it will continue to run
// you should only stop it if you aren't listening for notifications in the background
// to conserve system resources. you can stop like this:
//Ti.App.currentService.stop();
// you can unregister the service by calling
// Ti.App.currentService.unregister()
// and this service will be unregistered and never invoked again | mixandmatch/titanium | app/assets/bg.js | JavaScript | apache-2.0 | 1,022 |
# Copyright 2019, The TensorFlow Federated 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.
from typing import Any, Iterable, List, Tuple, Type
from absl.testing import absltest
from absl.testing import parameterized
import tensorflow as tf
from tensorflow_federated.proto.v0 import computation_pb2 as pb
from tensorflow_federated.python.common_libs import structure
from tensorflow_federated.python.core.impl.compiler import intrinsic_defs
from tensorflow_federated.python.core.impl.computation import computation_impl
from tensorflow_federated.python.core.impl.context_stack import context_stack_impl
from tensorflow_federated.python.core.impl.executors import eager_tf_executor
from tensorflow_federated.python.core.impl.executors import executor_test_utils
from tensorflow_federated.python.core.impl.executors import executor_value_base
from tensorflow_federated.python.core.impl.executors import federated_resolving_strategy
from tensorflow_federated.python.core.impl.executors import federating_executor
from tensorflow_federated.python.core.impl.executors import reference_resolving_executor
from tensorflow_federated.python.core.impl.types import computation_types
from tensorflow_federated.python.core.impl.types import placements
from tensorflow_federated.python.core.impl.types import type_serialization
def all_isinstance(objs: Iterable[Any], classinfo: Type[Any]) -> bool:
return all(isinstance(x, classinfo) for x in objs)
def create_test_executor(
number_of_clients: int = 3) -> federating_executor.FederatingExecutor:
def create_bottom_stack():
executor = eager_tf_executor.EagerTFExecutor()
return reference_resolving_executor.ReferenceResolvingExecutor(executor)
factory = federated_resolving_strategy.FederatedResolvingStrategy.factory({
placements.SERVER:
create_bottom_stack(),
placements.CLIENTS: [
create_bottom_stack() for _ in range(number_of_clients)
],
})
return federating_executor.FederatingExecutor(factory, create_bottom_stack())
def get_named_parameters_for_supported_intrinsics() -> List[Tuple[str, Any]]:
# pyformat: disable
return [
('intrinsic_def_federated_aggregate',
*executor_test_utils.create_whimsy_intrinsic_def_federated_aggregate()),
('intrinsic_def_federated_apply',
*executor_test_utils.create_whimsy_intrinsic_def_federated_apply()),
('intrinsic_def_federated_broadcast',
*executor_test_utils.create_whimsy_intrinsic_def_federated_broadcast()),
('intrinsic_def_federated_eval_at_clients',
*executor_test_utils.create_whimsy_intrinsic_def_federated_eval_at_clients()),
('intrinsic_def_federated_eval_at_server',
*executor_test_utils.create_whimsy_intrinsic_def_federated_eval_at_server()),
('intrinsic_def_federated_map',
*executor_test_utils.create_whimsy_intrinsic_def_federated_map()),
('intrinsic_def_federated_map_all_equal',
*executor_test_utils.create_whimsy_intrinsic_def_federated_map_all_equal()),
('intrinsic_def_federated_mean',
*executor_test_utils.create_whimsy_intrinsic_def_federated_mean()),
('intrinsic_def_federated_select',
*executor_test_utils.create_whimsy_intrinsic_def_federated_select()),
('intrinsic_def_federated_sum',
*executor_test_utils.create_whimsy_intrinsic_def_federated_sum()),
('intrinsic_def_federated_value_at_clients',
*executor_test_utils.create_whimsy_intrinsic_def_federated_value_at_clients()),
('intrinsic_def_federated_value_at_server',
*executor_test_utils.create_whimsy_intrinsic_def_federated_value_at_server()),
('intrinsic_def_federated_weighted_mean',
*executor_test_utils.create_whimsy_intrinsic_def_federated_weighted_mean()),
('intrinsic_def_federated_zip_at_clients',
*executor_test_utils.create_whimsy_intrinsic_def_federated_zip_at_clients()),
('intrinsic_def_federated_zip_at_server',
*executor_test_utils.create_whimsy_intrinsic_def_federated_zip_at_server()),
]
# pyformat: enable
class FederatingExecutorCreateValueTest(executor_test_utils.AsyncTestCase,
parameterized.TestCase):
# pyformat: disable
@parameterized.named_parameters([
('placement_literal',
*executor_test_utils.create_whimsy_placement_literal()),
('computation_intrinsic',
*executor_test_utils.create_whimsy_computation_intrinsic()),
('computation_lambda',
*executor_test_utils.create_whimsy_computation_lambda_empty()),
('computation_tensorflow',
*executor_test_utils.create_whimsy_computation_tensorflow_empty()),
('federated_type_at_clients',
*executor_test_utils.create_whimsy_value_at_clients()),
('federated_type_at_clients_all_equal',
*executor_test_utils.create_whimsy_value_at_clients_all_equal()),
('federated_type_at_server',
*executor_test_utils.create_whimsy_value_at_server()),
('unplaced_type',
*executor_test_utils.create_whimsy_value_unplaced()),
] + get_named_parameters_for_supported_intrinsics())
# pyformat: enable
def test_returns_value_with_value_and_type(self, value, type_signature):
executor = create_test_executor()
result = self.run_sync(executor.create_value(value, type_signature))
self.assertIsInstance(result, executor_value_base.ExecutorValue)
self.assertEqual(result.type_signature.compact_representation(),
type_signature.compact_representation())
# pyformat: disable
@parameterized.named_parameters([
('placement_literal',
*executor_test_utils.create_whimsy_placement_literal()),
('computation_intrinsic',
*executor_test_utils.create_whimsy_computation_intrinsic()),
('computation_lambda',
*executor_test_utils.create_whimsy_computation_lambda_empty()),
('computation_tensorflow',
*executor_test_utils.create_whimsy_computation_tensorflow_empty()),
])
# pyformat: enable
def test_returns_value_with_value_only(self, value, type_signature):
executor = create_test_executor()
result = self.run_sync(executor.create_value(value))
self.assertIsInstance(result, executor_value_base.ExecutorValue)
self.assertEqual(result.type_signature.compact_representation(),
type_signature.compact_representation())
# pyformat: disable
@parameterized.named_parameters([
('computation_intrinsic',
*executor_test_utils.create_whimsy_computation_intrinsic()),
('computation_lambda',
*executor_test_utils.create_whimsy_computation_lambda_empty()),
('computation_tensorflow',
*executor_test_utils.create_whimsy_computation_tensorflow_empty()),
])
# pyformat: enable
def test_returns_value_with_computation_impl(self, proto, type_signature):
executor = create_test_executor()
value = computation_impl.ConcreteComputation(
proto, context_stack_impl.context_stack)
result = self.run_sync(executor.create_value(value, type_signature))
self.assertIsInstance(result, executor_value_base.ExecutorValue)
self.assertEqual(result.type_signature.compact_representation(),
type_signature.compact_representation())
# pyformat: disable
@parameterized.named_parameters([
('federated_type_at_clients',
*executor_test_utils.create_whimsy_value_at_clients()),
('federated_type_at_clients_all_equal',
*executor_test_utils.create_whimsy_value_at_clients_all_equal()),
('federated_type_at_server',
*executor_test_utils.create_whimsy_value_at_server()),
('unplaced_type',
*executor_test_utils.create_whimsy_value_unplaced()),
] + get_named_parameters_for_supported_intrinsics())
# pyformat: enable
def test_raises_type_error_with_value_only(self, value, type_signature):
del type_signature # Unused.
executor = create_test_executor()
with self.assertRaises(TypeError):
self.run_sync(executor.create_value(value))
# pyformat: disable
@parameterized.named_parameters([
('placement_literal',
*executor_test_utils.create_whimsy_placement_literal()),
('computation_call',
*executor_test_utils.create_whimsy_computation_call()),
('computation_intrinsic',
*executor_test_utils.create_whimsy_computation_intrinsic()),
('computation_lambda',
*executor_test_utils.create_whimsy_computation_lambda_empty()),
('computation_selection',
*executor_test_utils.create_whimsy_computation_selection()),
('computation_tensorflow',
*executor_test_utils.create_whimsy_computation_tensorflow_empty()),
('computation_tuple',
*executor_test_utils.create_whimsy_computation_tuple()),
('federated_type_at_clients',
*executor_test_utils.create_whimsy_value_at_clients()),
('federated_type_at_clients_all_equal',
*executor_test_utils.create_whimsy_value_at_clients_all_equal()),
('federated_type_at_server',
*executor_test_utils.create_whimsy_value_at_server()),
('unplaced_type',
*executor_test_utils.create_whimsy_value_unplaced()),
] + get_named_parameters_for_supported_intrinsics())
# pyformat: enable
def test_raises_type_error_with_value_and_bad_type(self, value,
type_signature):
del type_signature # Unused.
executor = create_test_executor()
bad_type_signature = computation_types.TensorType(tf.string)
with self.assertRaises(TypeError):
self.run_sync(executor.create_value(value, bad_type_signature))
# pyformat: disable
@parameterized.named_parameters([
('computation_call',
*executor_test_utils.create_whimsy_computation_call()),
('computation_placement',
*executor_test_utils.create_whimsy_computation_placement()),
('computation_reference',
*executor_test_utils.create_whimsy_computation_reference()),
('computation_selection',
*executor_test_utils.create_whimsy_computation_selection()),
('computation_tuple',
*executor_test_utils.create_whimsy_computation_tuple()),
])
# pyformat: enable
def test_raises_value_error_with_value(self, value, type_signature):
executor = create_test_executor()
with self.assertRaises(ValueError):
self.run_sync(executor.create_value(value, type_signature))
def test_raises_value_error_with_unrecognized_computation_intrinsic(self):
executor = create_test_executor()
type_signature = computation_types.TensorType(tf.int32)
# A `ValueError` will be raised because `create_value` can not recognize the
# following intrinsic, because it has not been added to the intrinsic
# registry.
type_signature = computation_types.TensorType(tf.int32)
value = pb.Computation(
type=type_serialization.serialize_type(type_signature),
intrinsic=pb.Intrinsic(uri='unregistered_intrinsic'))
with self.assertRaises(ValueError):
self.run_sync(executor.create_value(value, type_signature))
def test_raises_value_error_with_unrecognized_computation_selection(self):
executor = create_test_executor()
source, _ = executor_test_utils.create_whimsy_computation_tuple()
type_signature = computation_types.StructType([])
# A `ValueError` will be raised because `create_value` can not handle the
# following `pb.Selection`, because does not set either a name or an index
# field.
value = pb.Computation(
type=type_serialization.serialize_type(type_signature),
selection=pb.Selection(source=source))
with self.assertRaises(ValueError):
self.run_sync(executor.create_value(value, type_signature))
# pyformat: disable
@parameterized.named_parameters([
('intrinsic_def_federated_aggregate',
*executor_test_utils.create_whimsy_intrinsic_def_federated_aggregate()),
('intrinsic_def_federated_apply',
*executor_test_utils.create_whimsy_intrinsic_def_federated_apply()),
('intrinsic_def_federated_eval_at_server',
*executor_test_utils.create_whimsy_intrinsic_def_federated_eval_at_server()),
('intrinsic_def_federated_mean',
*executor_test_utils.create_whimsy_intrinsic_def_federated_mean()),
('intrinsic_def_federated_sum',
*executor_test_utils.create_whimsy_intrinsic_def_federated_sum()),
('intrinsic_def_federated_value_at_server',
*executor_test_utils.create_whimsy_intrinsic_def_federated_value_at_server()),
('intrinsic_def_federated_weighted_mean',
*executor_test_utils.create_whimsy_intrinsic_def_federated_weighted_mean()),
('intrinsic_def_federated_zip_at_server',
*executor_test_utils.create_whimsy_intrinsic_def_federated_zip_at_server()),
('federated_type_at_server',
*executor_test_utils.create_whimsy_value_at_server()),
])
# pyformat: enable
def test_raises_value_error_with_no_target_executor_server(
self, value, type_signature):
factory = federated_resolving_strategy.FederatedResolvingStrategy.factory({
placements.CLIENTS: eager_tf_executor.EagerTFExecutor(),
})
executor = federating_executor.FederatingExecutor(
factory, eager_tf_executor.EagerTFExecutor())
value, type_signature = executor_test_utils.create_whimsy_value_at_server()
with self.assertRaises(ValueError):
self.run_sync(executor.create_value(value, type_signature))
def test_raises_value_error_with_unexpected_federated_type_at_clients(self):
executor = create_test_executor()
value = [10, 20]
type_signature = computation_types.at_clients(tf.int32)
with self.assertRaises(ValueError):
self.run_sync(executor.create_value(value, type_signature))
def test_raises_type_error_with_unexpected_federated_type_at_clients_all_equal(
self):
executor = create_test_executor()
value = [10] * 3
type_signature = computation_types.at_clients(tf.int32, all_equal=True)
with self.assertRaises(TypeError):
self.run_sync(executor.create_value(value, type_signature))
class FederatingExecutorCreateCallTest(executor_test_utils.AsyncTestCase,
parameterized.TestCase):
# pyformat: disable
@parameterized.named_parameters([
('intrinsic_def_federated_aggregate',
*executor_test_utils.create_whimsy_intrinsic_def_federated_aggregate(),
[executor_test_utils.create_whimsy_value_at_clients(),
executor_test_utils.create_whimsy_value_unplaced(),
executor_test_utils.create_whimsy_computation_tensorflow_add(),
executor_test_utils.create_whimsy_computation_tensorflow_add(),
executor_test_utils.create_whimsy_computation_tensorflow_identity()],
43.0),
('intrinsic_def_federated_apply',
*executor_test_utils.create_whimsy_intrinsic_def_federated_apply(),
[executor_test_utils.create_whimsy_computation_tensorflow_identity(),
executor_test_utils.create_whimsy_value_at_server()],
10.0),
('intrinsic_def_federated_broadcast',
*executor_test_utils.create_whimsy_intrinsic_def_federated_broadcast(),
[executor_test_utils.create_whimsy_value_at_server()],
10.0),
('intrinsic_def_federated_eval_at_clients',
*executor_test_utils.create_whimsy_intrinsic_def_federated_eval_at_clients(),
[executor_test_utils.create_whimsy_computation_tensorflow_constant()],
[10.0] * 3),
('intrinsic_def_federated_eval_at_server',
*executor_test_utils.create_whimsy_intrinsic_def_federated_eval_at_server(),
[executor_test_utils.create_whimsy_computation_tensorflow_constant()],
10.0),
('intrinsic_def_federated_map',
*executor_test_utils.create_whimsy_intrinsic_def_federated_map(),
[executor_test_utils.create_whimsy_computation_tensorflow_identity(),
executor_test_utils.create_whimsy_value_at_clients()],
[10.0, 11.0, 12.0]),
('intrinsic_def_federated_map_all_equal',
*executor_test_utils.create_whimsy_intrinsic_def_federated_map_all_equal(),
[executor_test_utils.create_whimsy_computation_tensorflow_identity(),
executor_test_utils.create_whimsy_value_at_clients_all_equal()],
10.0),
('intrinsic_def_federated_mean',
*executor_test_utils.create_whimsy_intrinsic_def_federated_mean(),
[executor_test_utils.create_whimsy_value_at_clients()],
11.0),
('intrinsic_def_federated_select',
*executor_test_utils.create_whimsy_intrinsic_def_federated_select(),
executor_test_utils.create_whimsy_federated_select_args(),
executor_test_utils.create_whimsy_federated_select_expected_result(),
),
('intrinsic_def_federated_sum',
*executor_test_utils.create_whimsy_intrinsic_def_federated_sum(),
[executor_test_utils.create_whimsy_value_at_clients()],
33.0),
('intrinsic_def_federated_value_at_clients',
*executor_test_utils.create_whimsy_intrinsic_def_federated_value_at_clients(),
[executor_test_utils.create_whimsy_value_unplaced()],
10.0),
('intrinsic_def_federated_value_at_server',
*executor_test_utils.create_whimsy_intrinsic_def_federated_value_at_server(),
[executor_test_utils.create_whimsy_value_unplaced()],
10.0),
('intrinsic_def_federated_weighted_mean',
*executor_test_utils.create_whimsy_intrinsic_def_federated_weighted_mean(),
[executor_test_utils.create_whimsy_value_at_clients(),
executor_test_utils.create_whimsy_value_at_clients()],
11.060606),
('intrinsic_def_federated_zip_at_clients',
*executor_test_utils.create_whimsy_intrinsic_def_federated_zip_at_clients(),
[executor_test_utils.create_whimsy_value_at_clients(),
executor_test_utils.create_whimsy_value_at_clients()],
[structure.Struct([(None, 10.0), (None, 10.0)]),
structure.Struct([(None, 11.0), (None, 11.0)]),
structure.Struct([(None, 12.0), (None, 12.0)])]),
('intrinsic_def_federated_zip_at_server',
*executor_test_utils.create_whimsy_intrinsic_def_federated_zip_at_server(),
[executor_test_utils.create_whimsy_value_at_server(),
executor_test_utils.create_whimsy_value_at_server()],
structure.Struct([(None, 10.0), (None, 10.0)])),
('computation_intrinsic',
*executor_test_utils.create_whimsy_computation_intrinsic(),
[executor_test_utils.create_whimsy_computation_tensorflow_constant()],
10.0),
('computation_tensorflow',
*executor_test_utils.create_whimsy_computation_tensorflow_identity(),
[executor_test_utils.create_whimsy_value_unplaced()],
10.0),
])
# pyformat: enable
def test_returns_value_with_comp_and_arg(self, comp, comp_type, args,
expected_result):
executor = create_test_executor()
comp = self.run_sync(executor.create_value(comp, comp_type))
elements = [self.run_sync(executor.create_value(*x)) for x in args]
if len(elements) > 1:
arg = self.run_sync(executor.create_struct(elements))
else:
arg = elements[0]
result = self.run_sync(executor.create_call(comp, arg))
self.assertIsInstance(result, executor_value_base.ExecutorValue)
self.assertEqual(result.type_signature.compact_representation(),
comp_type.result.compact_representation())
actual_result = self.run_sync(result.compute())
self.assert_maybe_list_equal(actual_result, expected_result)
def assert_maybe_list_equal(self, actual_result, expected_result):
if (all_isinstance([actual_result, expected_result], list) or
all_isinstance([actual_result, expected_result], tf.data.Dataset)):
for actual_element, expected_element in zip(actual_result,
expected_result):
self.assert_maybe_list_equal(actual_element, expected_element)
else:
self.assertEqual(actual_result, expected_result)
def test_returns_value_with_intrinsic_def_federated_eval_at_clients_and_random(
self):
executor = create_test_executor(number_of_clients=3)
comp, comp_type = executor_test_utils.create_whimsy_intrinsic_def_federated_eval_at_clients(
)
arg, arg_type = executor_test_utils.create_whimsy_computation_tensorflow_random(
)
comp = self.run_sync(executor.create_value(comp, comp_type))
arg = self.run_sync(executor.create_value(arg, arg_type))
result = self.run_sync(executor.create_call(comp, arg))
self.assertIsInstance(result, executor_value_base.ExecutorValue)
self.assertEqual(result.type_signature.compact_representation(),
comp_type.result.compact_representation())
actual_result = self.run_sync(result.compute())
unique_results = set([x.numpy() for x in actual_result])
if len(actual_result) != len(unique_results):
self.fail(
'Expected the result to contain different random numbers, found {}.'
.format(actual_result))
# pyformat: disable
@parameterized.named_parameters([
('computation_tensorflow',
*executor_test_utils.create_whimsy_computation_tensorflow_empty()),
])
# pyformat: enable
def test_returns_value_with_comp_only(self, comp, comp_type):
executor = create_test_executor()
comp = self.run_sync(executor.create_value(comp, comp_type))
result = self.run_sync(executor.create_call(comp))
self.assertIsInstance(result, executor_value_base.ExecutorValue)
self.assertEqual(result.type_signature.compact_representation(),
comp_type.result.compact_representation())
actual_result = self.run_sync(result.compute())
expected_result = []
self.assertCountEqual(actual_result, expected_result)
def test_raises_type_error_with_unembedded_comp(self):
executor = create_test_executor()
comp, _ = executor_test_utils.create_whimsy_computation_tensorflow_identity(
)
arg, arg_type = executor_test_utils.create_whimsy_value_unplaced()
arg = self.run_sync(executor.create_value(arg, arg_type))
with self.assertRaises(TypeError):
self.run_sync(executor.create_call(comp, arg))
def test_raises_type_error_with_unembedded_arg(self):
executor = create_test_executor()
comp, comp_type = executor_test_utils.create_whimsy_computation_tensorflow_identity(
)
arg, _ = executor_test_utils.create_whimsy_value_unplaced()
comp = self.run_sync(executor.create_value(comp, comp_type))
with self.assertRaises(TypeError):
self.run_sync(executor.create_call(comp, arg))
# pyformat: disable
@parameterized.named_parameters([
('computation_intrinsic',
*executor_test_utils.create_whimsy_computation_intrinsic()),
('computation_lambda',
*executor_test_utils.create_whimsy_computation_lambda_identity()),
('computation_tensorflow',
*executor_test_utils.create_whimsy_computation_tensorflow_identity()),
] + get_named_parameters_for_supported_intrinsics())
# pyformat: enable
def test_raises_type_error_with_comp_and_bad_arg(self, comp, comp_type):
executor = create_test_executor()
bad_arg = 'string'
bad_arg_type = computation_types.TensorType(tf.string)
comp = self.run_sync(executor.create_value(comp, comp_type))
arg = self.run_sync(executor.create_value(bad_arg, bad_arg_type))
with self.assertRaises(TypeError):
self.run_sync(executor.create_call(comp, arg))
# pyformat: disable
@parameterized.named_parameters([
('computation_lambda',
*executor_test_utils.create_whimsy_computation_lambda_empty()),
('federated_type_at_clients',
*executor_test_utils.create_whimsy_value_at_clients()),
('federated_type_at_clients_all_equal',
*executor_test_utils.create_whimsy_value_at_clients_all_equal()),
('federated_type_at_server',
*executor_test_utils.create_whimsy_value_at_server()),
('unplaced_type',
*executor_test_utils.create_whimsy_value_unplaced()),
])
# pyformat: enable
def test_raises_value_error_with_comp(self, comp, comp_type):
executor = create_test_executor()
comp = self.run_sync(executor.create_value(comp, comp_type))
with self.assertRaises(ValueError):
self.run_sync(executor.create_call(comp))
def test_raises_not_implemented_error_with_intrinsic_def_federated_secure_sum_bitwidth(
self):
executor = create_test_executor()
comp, comp_type = executor_test_utils.create_whimsy_intrinsic_def_federated_secure_sum_bitwidth(
)
arg_1 = [10, 11, 12]
arg_1_type = computation_types.at_clients(tf.int32, all_equal=False)
arg_2 = 10
arg_2_type = computation_types.TensorType(tf.int32)
comp = self.run_sync(executor.create_value(comp, comp_type))
arg_1 = self.run_sync(executor.create_value(arg_1, arg_1_type))
arg_2 = self.run_sync(executor.create_value(arg_2, arg_2_type))
args = self.run_sync(executor.create_struct([arg_1, arg_2]))
with self.assertRaises(NotImplementedError):
self.run_sync(executor.create_call(comp, args))
def test_raises_not_implemented_error_with_unimplemented_intrinsic(self):
executor = create_test_executor()
# `whimsy_intrinsic` definition is needed to allow lookup.
whimsy_intrinsic = intrinsic_defs.IntrinsicDef(
'WHIMSY_INTRINSIC', 'whimsy_intrinsic',
computation_types.AbstractType('T'))
type_signature = computation_types.TensorType(tf.int32)
comp = pb.Computation(
intrinsic=pb.Intrinsic(uri='whimsy_intrinsic'),
type=type_serialization.serialize_type(type_signature))
del whimsy_intrinsic
comp = self.run_sync(executor.create_value(comp))
with self.assertRaises(NotImplementedError):
self.run_sync(executor.create_call(comp))
class FederatingExecutorCreateStructTest(executor_test_utils.AsyncTestCase,
parameterized.TestCase):
# pyformat: disable
@parameterized.named_parameters([
('federated_type_at_clients',
*executor_test_utils.create_whimsy_value_at_clients()),
('federated_type_at_clients_all_equal',
*executor_test_utils.create_whimsy_value_at_clients_all_equal()),
('federated_type_at_server',
*executor_test_utils.create_whimsy_value_at_server()),
('unplaced_type',
*executor_test_utils.create_whimsy_value_unplaced()),
])
# pyformat: enable
def test_returns_value_with_elements_value(self, value, type_signature):
executor = create_test_executor()
element = self.run_sync(executor.create_value(value, type_signature))
elements = [element] * 3
type_signature = computation_types.StructType([type_signature] * 3)
result = self.run_sync(executor.create_struct(elements))
self.assertIsInstance(result, executor_value_base.ExecutorValue)
self.assertEqual(result.type_signature.compact_representation(),
type_signature.compact_representation())
actual_result = self.run_sync(result.compute())
expected_result = [self.run_sync(element.compute())] * 3
self.assertCountEqual(actual_result, expected_result)
def test_returns_value_with_elements_value_placement_literal(self):
executor = create_test_executor()
value, type_signature = executor_test_utils.create_whimsy_placement_literal(
)
element = self.run_sync(executor.create_value(value, type_signature))
elements = [element] * 3
type_signature = computation_types.StructType([type_signature] * 3)
result = self.run_sync(executor.create_struct(elements))
self.assertIsInstance(result, executor_value_base.ExecutorValue)
self.assertEqual(result.type_signature.compact_representation(),
type_signature.compact_representation())
# pyformat: disable
@parameterized.named_parameters([
('intrinsic_def_federated_eval_at_server',
*executor_test_utils.create_whimsy_intrinsic_def_federated_eval_at_server(),
*executor_test_utils.create_whimsy_computation_tensorflow_constant()),
('computation_intrinsic',
*executor_test_utils.create_whimsy_computation_intrinsic(),
*executor_test_utils.create_whimsy_computation_tensorflow_constant()),
])
# pyformat: enable
def test_returns_value_with_elements_fn_and_arg(self, fn, fn_type, arg,
arg_type):
executor = create_test_executor()
fn = self.run_sync(executor.create_value(fn, fn_type))
arg = self.run_sync(executor.create_value(arg, arg_type))
element = self.run_sync(executor.create_call(fn, arg))
elements = [element] * 3
type_signature = computation_types.StructType([fn_type.result] * 3)
result = self.run_sync(executor.create_struct(elements))
self.assertIsInstance(result, executor_value_base.ExecutorValue)
self.assertEqual(result.type_signature.compact_representation(),
type_signature.compact_representation())
actual_result = self.run_sync(result.compute())
expected_result = [self.run_sync(element.compute())] * 3
self.assertCountEqual(actual_result, expected_result)
# pyformat: disable
@parameterized.named_parameters([
('computation_tensorflow',
*executor_test_utils.create_whimsy_computation_tensorflow_empty()),
])
# pyformat: enable
def test_returns_value_with_elements_fn_only(self, fn, fn_type):
executor = create_test_executor()
fn = self.run_sync(executor.create_value(fn, fn_type))
element = self.run_sync(executor.create_call(fn))
elements = [element] * 3
type_signature = computation_types.StructType([fn_type.result] * 3)
result = self.run_sync(executor.create_struct(elements))
self.assertIsInstance(result, executor_value_base.ExecutorValue)
self.assertEqual(result.type_signature.compact_representation(),
type_signature.compact_representation())
actual_result = self.run_sync(result.compute())
expected_result = [self.run_sync(element.compute())] * 3
self.assertCountEqual(actual_result, expected_result)
def test_raises_type_error_with_unembedded_elements(self):
executor = create_test_executor()
element, _ = executor_test_utils.create_whimsy_value_unplaced()
elements = [element] * 3
with self.assertRaises(TypeError):
self.run_sync(executor.create_struct(elements))
class FederatingExecutorCreateSelectionTest(executor_test_utils.AsyncTestCase):
def test_returns_value_with_source_and_index_computation_tensorflow(self):
executor = create_test_executor()
source, type_signature = executor_test_utils.create_whimsy_computation_tensorflow_tuple(
)
source = self.run_sync(executor.create_value(source, type_signature))
source = self.run_sync(executor.create_call(source))
result = self.run_sync(executor.create_selection(source, 0))
self.assertIsInstance(result, executor_value_base.ExecutorValue)
self.assertEqual(result.type_signature.compact_representation(),
type_signature.result[0].compact_representation())
actual_result = self.run_sync(result.compute())
expected_result = self.run_sync(source.compute())[0]
self.assertEqual(actual_result, expected_result)
def test_returns_value_with_source_and_index_structure(self):
executor = create_test_executor()
element, element_type = executor_test_utils.create_whimsy_value_unplaced()
element = self.run_sync(executor.create_value(element, element_type))
elements = [element] * 3
type_signature = computation_types.StructType([element_type] * 3)
source = self.run_sync(executor.create_struct(elements))
result = self.run_sync(executor.create_selection(source, 0))
self.assertIsInstance(result, executor_value_base.ExecutorValue)
self.assertEqual(result.type_signature.compact_representation(),
type_signature[0].compact_representation())
actual_result = self.run_sync(result.compute())
expected_result = self.run_sync(source.compute())[0]
self.assertEqual(actual_result, expected_result)
def test_returns_value_with_source_and_name_computation_tensorflow(self):
executor = create_test_executor()
source, type_signature = executor_test_utils.create_whimsy_computation_tensorflow_tuple(
)
source = self.run_sync(executor.create_value(source, type_signature))
source = self.run_sync(executor.create_call(source))
result = self.run_sync(executor.create_selection(source, 0))
self.assertIsInstance(result, executor_value_base.ExecutorValue)
self.assertEqual(result.type_signature.compact_representation(),
type_signature.result['a'].compact_representation())
actual_result = self.run_sync(result.compute())
expected_result = self.run_sync(source.compute())['a']
self.assertEqual(actual_result, expected_result)
def test_returns_value_with_source_and_name_structure(self):
executor = create_test_executor()
element, element_type = executor_test_utils.create_whimsy_value_unplaced()
names = ['a', 'b', 'c']
element = self.run_sync(executor.create_value(element, element_type))
elements = structure.Struct((n, element) for n in names)
type_signature = computation_types.StructType(
(n, element_type) for n in names)
source = self.run_sync(executor.create_struct(elements))
result = self.run_sync(executor.create_selection(source, 0))
self.assertIsInstance(result, executor_value_base.ExecutorValue)
self.assertEqual(result.type_signature.compact_representation(),
type_signature['a'].compact_representation())
actual_result = self.run_sync(result.compute())
expected_result = self.run_sync(source.compute())['a']
self.assertEqual(actual_result, expected_result)
def test_raises_type_error_with_unembedded_source(self):
executor = create_test_executor()
element, element_type = executor_test_utils.create_whimsy_value_unplaced()
element = self.run_sync(executor.create_value(element, element_type))
source = [element] * 3
with self.assertRaises(TypeError):
self.run_sync(executor.create_selection(source, 0))
def test_raises_type_error_with_not_tuple_type(self):
executor = create_test_executor()
element, element_type = executor_test_utils.create_whimsy_value_unplaced()
source = self.run_sync(executor.create_value(element, element_type))
with self.assertRaises(TypeError):
self.run_sync(executor.create_selection(source, 0))
def test_raises_value_error_with_unrecognized_generic_zero(self):
executor = create_test_executor()
value = intrinsic_defs.GENERIC_ZERO
type_signature = computation_types.StructType(
[computation_types.TensorType(tf.int32)] * 3)
source = self.run_sync(executor.create_value(value, type_signature))
with self.assertRaises(ValueError):
self.run_sync(executor.create_selection(source, 0))
if __name__ == '__main__':
absltest.main()
| tensorflow/federated | tensorflow_federated/python/core/impl/executors/federating_executor_test.py | Python | apache-2.0 | 35,600 |
/*
* Copyright (c) 2008-2021, Hazelcast, Inc. 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.
*/
'use strict';
const { Client } = require('hazelcast-client');
class CustomSerializable {
constructor(value) {
this.value = value;
this.hzCustomId = 10;
}
}
class CustomSerializer {
constructor() {
this.id = 10;
}
read(input) {
const len = input.readInt();
let str = '';
for (let i = 0; i < len; i++) {
str = str + String.fromCharCode(input.readInt());
}
return new CustomSerializable(str);
}
write(output, obj) {
output.writeInt(obj.value.length);
for (let i = 0; i < obj.value.length; i++) {
output.writeInt(obj.value.charCodeAt(i));
}
}
}
(async () => {
try {
// Start the Hazelcast Client and connect to an already running
// Hazelcast Cluster on 127.0.0.1
const hz = await Client.newHazelcastClient({
serialization: {
customSerializers: [new CustomSerializer()]
}
});
// CustomSerializer will serialize/deserialize CustomSerializable objects
// Shutdown this Hazelcast client
await hz.shutdown();
} catch (err) {
console.error('Error occurred:', err);
process.exit(1);
}
})();
| hazelcast-incubator/hazelcast-nodejs-client | code_samples/com-website/CustomSerializerSample.js | JavaScript | apache-2.0 | 1,882 |
package edu.cs4730.restdemo2;
import android.content.Context;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
/*
* this adapter is very similar to the adapters used for listview, except a ViewHolder is required
* see http://developer.android.com/training/improving-layouts/smooth-scrolling.html
* except instead having to implement a ViewHolder, it is implemented within
* the adapter.
*/
class myAdapter extends RecyclerView.Adapter<myAdapter.ViewHolder> {
private ArrayList<myObj> myList;
private int rowLayout;
private Context mContext;
// Define listener member variable
private OnItemClickListener listener;
// Define the listener interface
interface OnItemClickListener {
void onItemClick(String mid, String mtitle, String mbody);
}
// Define the method that allows the parent activity or fragment to define the listener
void setOnItemClickListener(OnItemClickListener listener) {
this.listener = listener;
}
myAdapter(ArrayList<myObj> myList, int rowLayout, Context context) {
this.myList = myList;
this.rowLayout = rowLayout;
this.mContext = context;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(rowLayout, viewGroup, false);
return new ViewHolder(v);
}
@Override
public void onBindViewHolder(final ViewHolder viewHolder, int i) {
myObj entry;
entry = myList.get(i);
viewHolder.tvID.setText(String.valueOf(entry.id));
viewHolder.title.setText(entry.title);
viewHolder.body.setText(entry.body);
viewHolder.cardview.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (listener != null) {
listener.onItemClick(viewHolder.tvID.getText().toString(), viewHolder.title.getText().toString(), viewHolder.body.getText().toString());
}
//Toast.makeText(mContext, "id is " + viewHolder.tvID.getText().toString(), Toast.LENGTH_LONG).show();
}
});
}
@Override
public int getItemCount() {
return myList == null ? 0 : myList.size();
}
public void setData(ArrayList<myObj> list) {
myList = list;
notifyDataSetChanged();
}
static class ViewHolder extends RecyclerView.ViewHolder {
TextView tvID;
TextView title;
TextView body;
CardView cardview;
ViewHolder(View itemView) {
super(itemView);
tvID = itemView.findViewById(R.id.tv_id);
title = itemView.findViewById(R.id.tv_title);
body = itemView.findViewById(R.id.tv_body);
cardview = itemView.findViewById(R.id.cardview);
}
}
}
| JimSeker/networking | ReSTServices/RestDemo2/app/src/main/java/edu/cs4730/restdemo2/myAdapter.java | Java | apache-2.0 | 3,081 |
//----- Requires -----
dojo.require('comum.format');
dojo.require('comum.CampoRedondo');
dojo.require('main.Pedido');
dojo.provide('main.Restaurante');
dojo.declare('main.Restaurante', null, {
restaurante : null,
loader : null,
restaurantes : new Array(),
pedido : null,
constructor : function () {
this.pedido = new main.Pedido();
this.pedido.preenchePedido();
},
carregando : function () {
this.loader = colocaLoader(dojo.query('#cardapio tbody')[0], 'only');
dojo.query('#tituloRestaurante h2')[0].innerHTML = 'Carregando';
},
carregaRestaurante : function (id) {
if (this.restaurante != null && this.restaurante.id == id) return;
var novoRestaurante = null;
dojo.forEach(this.restaurantes, function (item) {
if (item.id == id) {
novoRestaurante = item;
return false;
}
}, this);
// Se encontrou o restaurante já carregado
if (novoRestaurante != null) {
this.restaurante = novoRestaurante;
this.preencheRestaurante();
return;
}
var callback = dojo.hitch(this, function (response) {
if (response.failure) {
alert('Restaurante não encontrado.');
this.preencheRestaurante();
return;
}
this.restaurante = response;
this.restaurantes.push(this.restaurante);
this.preencheRestaurante();
});
// Se não, carrega
dojo.xhr('GET', {
url : contexto + '/getRestaurant.do',
content : {id : id},
handleAs : 'json',
load : callback,
error: callback
});
},
criaItemCardapio : function (item) {
var resultado = dojo.create('tr', { id : item.id });
var descricao = dojo.create('td', null, resultado);
dojo.addClass(descricao, 'descricao');
descricao.innerHTML = '<span>' + item.title + '</span> - ' + item.description;
dojo.place('<td>' + formataMoeda(item.price) + '</td>', resultado);
var quantidade = dojo.place('<td class="quantidade"></td>', resultado);
dojo.place('<span>- </span>', quantidade);
var campo = new comum.CampoRedondo({largura:25, altura: 15, name: 'quantidade'});
var outroNo = dojo.place(campo.domNode, quantidade);
dojo.place('<span> +</span>', quantidade);
campo.setValor(1);
var acompanhamentos = dojo.place('<td><a href="#">Selecionar</a></td>', resultado);
var pedir = dojo.place('<td></td>', resultado);
var callback = dojo.hitch(this, function (evt) {
var tr = evt.currentTarget.parentNode;
var id = dojo.attr(tr, 'id');
var campoQtd = dojo.query('input', tr)[0];
var quantidade = campoQtd.value;
var nome = dojo.query('.descricao span', tr)[0].innerHTML;
this.pedido.adicionar({id : id, quantity : quantidade, name : nome});
});
dojo.connect(pedir, 'onclick', callback);
var imagemPedir = dojo.place('<img src="../../resources/img/btPedir.png" alt="Pedir" />', pedir);
return resultado;
},
limpaCampos : function () {
var titulo = dojo.byId('tituloRestaurante');
var imagem = dojo.query('img', titulo)[0];
dojo.attr(imagem, 'src', '');
dojo.attr(imagem, 'alt', '');
var nomeRestaurante = dojo.query('h2', titulo)[0];
dojo.empty(nomeRestaurante);
var descricao = dojo.query('p', titulo)[0];
descricao.innerHTML = '';
var listaCategorias = dojo.byId('categorias');
dojo.empty(listaCategorias);
var tabelaCardapio = dojo.query('#cardapio tbody')[0];
dojo.empty(tabelaCardapio);
},
mostraCategoria : function (categoria) {
if (this.restaurante == null) return;
dojo.query('#categorias li').forEach(function (item) {
if (item.innerHTML == categoria) {
dojo.addClass(item, 'selecionado');
return false;
}
});
var tabelaCardapio = dojo.query('#cardapio tbody')[0];
dojo.empty(tabelaCardapio);
var pratos = this.restaurante.plates;
for (var i = 0; i < pratos.length; i++) {
var prato = pratos[i];
if (prato.category == categoria) {
dojo.place(this.criaItemCardapio(prato), tabelaCardapio);
}
}
},
preencheCardapio : function (itens) {
if (!itens) return;
var listaCategorias = dojo.byId('categorias');
dojo.empty(listaCategorias);
var categorias = new Array();
for (var i = 0; i < itens.length; i++) {
if (dojo.indexOf(categorias, itens[i].category) == -1) {
var categoria = itens[i].category;
categorias.push(categoria);
var itemCategoria = dojo.place('<li>' + categoria + '</li>', listaCategorias);
var callback = dojo.hitch(this, function (evt) {
var categoria = evt.target.innerHTML;
var selecionado = dojo.query('.selecionado', listaCategorias)[0];
if (selecionado) {
// se for o mesmo não faz nada
if (selecionado.innerHTML == categoria) return;
// Se não for o mesmo, remove a classe
dojo.removeClass(selecionado, 'selecionado');
}
this.mostraCategoria(categoria);
});
dojo.connect(itemCategoria, 'onclick', callback);
}
}
categorias.sort();
this.mostraCategoria(categorias[0]);
},
preencheRestaurante : function () {
if (!this.restaurante) {
dojo.style('conteudo_main', 'display', 'block');
dojo.style('conteudo_restaurante', 'display', 'none');
return;
}
// Remove o loader se tiver
if (this.loader) dojo.destroy(this.loader);
var titulo = dojo.byId('tituloRestaurante');
var imagem = dojo.query('img', titulo)[0];
dojo.attr(imagem, {
src : contexto + '/' + this.restaurante.imageUrl,
alt : this.restaurante.imageAlt
});
var nomeRestaurante = dojo.query('h2', titulo)[0];
nomeRestaurante.innerHTML = this.restaurante.name;
var descricao = dojo.query('p', titulo)[0];
descricao.innerHTML = this.restaurante.description;
this.preencheCardapio(this.restaurante.plates);
this.pedido.mostraPedido();
},
setRestaurante : function (id) {
window.location.hash = 'restaurantId=' + id;
if (this.restaurante == null || id != this.restaurante.id) {
this.limpaCampos();
this.carregando();
this.carregaRestaurante(id);
}
}
}); | rafaelcoutinho/comendobemdelivery | war/scripts/main/Restaurante.js | JavaScript | apache-2.0 | 5,972 |
package com.educative.graph;
import java.util.Iterator;
import java.util.LinkedList;
public class StronglyConnected {
public static void utilityFunction(Graph g, int v, boolean visited[]) {
visited[v] = true;
LinkedList<Integer> adj[] = g.getAdj();
Iterator<Integer> i = adj[v].listIterator();
while(i.hasNext()) {
int temp = i.next();
if (!visited[temp]) {
utilityFunction(g, temp, visited);
}
}
}
public static Object isStronglyConnected(Graph g) {
int v = g.getVertices();
boolean visited[] = new boolean[v];
utilityFunction(g, 0, visited);
for (boolean visit : visited) {
if (!visit) return false;
}
// reset visited[]
for (int i = 0; i < v; i++) {
visited[i] = false;
}
Graph tg = g.getTranspose();
utilityFunction(tg, 0, visited);
for (boolean visit : visited) {
if (!visit) return false;
}
return true;
}
}
| magictortoise/Lintcode | src/main/java/com/educative/graph/StronglyConnected.java | Java | apache-2.0 | 1,068 |
/*
* Copyright 2016 jiajunhui
*
* 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.kk.taurus.animeffect.anims;
import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.view.View;
import com.kk.taurus.animeffect.base.BaseAnimator;
/**
* Created by Taurus on 2016/12/8.
*/
public class AnimatorZoomCenter extends BaseAnimator {
@Override
public Animator[] togetherAnimators(View view) {
return new Animator[]{
ObjectAnimator.ofFloat(view,PropertyType.Alpha.getValue(),0,1).setDuration(getDuration()),
ObjectAnimator.ofFloat(view,PropertyType.ScaleX.getValue(),0,1).setDuration(getDuration()),
ObjectAnimator.ofFloat(view,PropertyType.ScaleY.getValue(),0,1).setDuration(getDuration())
};
}
}
| jiajunhui/AnimEffect | Anim-Effect/src/main/java/com/kk/taurus/animeffect/anims/AnimatorZoomCenter.java | Java | apache-2.0 | 1,355 |
@ModuleGen(groupPackage = "io.vertx.blueprint.kue.queue", name = "vertx-kue-queue-core-module")
package io.vertx.blueprint.kue.queue;
import io.vertx.codegen.annotations.ModuleGen; | Kayuii/examples-kue | kue-core/src/main/java/io/vertx/blueprint/kue/queue/package-info.java | Java | apache-2.0 | 181 |
class TestLab
unless const_defined?(:VERSION)
# TestLab Gem Version
VERSION = "1.22.4"
end
end
| lookout/testlab | lib/testlab/version.rb | Ruby | apache-2.0 | 107 |
package ndfs.mcndfs_alg3;
import java.lang.Runnable;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.Collections;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.ExecutorService;
import java.io.File;
import java.io.FileNotFoundException;
import graph.State;
import graph.Graph;
import graph.GraphFactory;
import ndfs.Result;
import ndfs.CycleFound;
import ndfs.NoCycleFound;
import ndfs.MapWithDefaultValues;
import ndfs.Color;
class Worker implements Runnable
{
// Locals
private final Graph graph;
private MapWithDefaultValues<State,Color> colors;
private long randomSeed;
// Globals
private MapWithDefaultValues<State, Boolean> isRed;
private MapWithDefaultValues<State, AtomicInteger> visitCount;
private ExecutorService executor;
public Worker(File file,
MapWithDefaultValues<State, Boolean> isRed,
MapWithDefaultValues<State, AtomicInteger> visitCount,
long randomSeed,
ExecutorService executor
)
{
// create local reference to prevent (invalid) compiler complaints
Graph graph = null;
try{
graph = GraphFactory.createGraph(file);
} catch(FileNotFoundException e){
System.out.println("Could not open file");
System.exit(1);
}
this.graph = graph;
this.colors = new MapWithDefaultValues<State,Color>(new HashMap<State,Color>(),Color.WHITE);
this.randomSeed = randomSeed;
// Globals
this.isRed = isRed;
this.visitCount = visitCount;
this.executor = executor;
}
private void dfsRed(State s) throws Result {
if (Thread.currentThread().isInterrupted()) {
return;
}
colors.setValue(s, Color.PINK);
List<State> shuffledList = graph.post(s);
Collections.shuffle(shuffledList, new Random(randomSeed));
for (State t : shuffledList) {
if (colors.hasKeyValuePair(t, Color.CYAN)) {
throw new CycleFound();
}
if ( true
&& (!colors.hasKeyValuePair(t, Color.PINK))
&& isRed.hasKeyValuePair(t, false)
){
dfsRed(t);
}
}
if (s.isAccepting()) {
visitCount.getValue(s).decrementAndGet();
System.out.println("");
while (visitCount.getValue(s).get() != 0){
// spin
System.out.println("dfsRed(): " + visitCount.getValue(s).get() + "hash code: " + s.hashCode());
if (Thread.currentThread().isInterrupted()) {
break;
}
}
}
isRed.setValue(s, true);
}
private void dfsBlue(State s) throws Result {
if (Thread.currentThread().isInterrupted()) {
return;
}
boolean allRed = true;
colors.setValue(s, Color.CYAN);
List<State> shuffledList = graph.post(s);
Collections.shuffle(shuffledList, new Random(randomSeed));
for (State t : shuffledList) {
if( true
&& colors.hasKeyValuePair(t, Color.CYAN)
&& (s.isAccepting() || t.isAccepting())
){
System.out.println("Early");
throw new CycleFound();
}
if( true
&& colors.hasKeyValuePair(t, Color.WHITE)
&& isRed.hasKeyValuePair(t, false)
){
dfsBlue(t);
}
if(isRed.hasKeyValuePair(t, false)){
allRed = false;
}
}
if(allRed){
isRed.setValue(s, true);
}
else if(s.isAccepting()){
visitCount.getValue(s).incrementAndGet();
System.out.println("dfsBlue(): " + visitCount.getValue(s).get() + "hash code : " + s.hashCode());
try{
Thread.sleep(5000);
} catch(InterruptedException ie){}
dfsRed(s);
}
colors.setValue(s, Color.BLUE);
}
public void run(){
long start = System.currentTimeMillis();
long end;
try {
dfsBlue(graph.getInitialState());
throw new NoCycleFound();
}
catch (CycleFound cf) {
end = System.currentTimeMillis();
System.out.println(cf.getMessage());
System.out.printf("%s took %d ms\n", "MC_NDFS", end - start);
executor.shutdownNow();
}
catch (Result r) {
end = System.currentTimeMillis();
System.out.println(r.getMessage());
System.out.printf("%s took %d ms\n", "MC_NDFS", end - start);
//executor.shutdownNow();
}
}
}
| unmeshvrije/C-- | src/ndfs/mcndfs_alg3/Worker.java | Java | apache-2.0 | 4,367 |
package com.sky.hsf1002.designpattern.Decorator;
/**
* Created by hefeng on 17-9-15.
*/
public interface IPerson {
void dressed();
}
| LoveGoogleLoveAndroid/design-pattern | app/src/main/java/com/sky/hsf1002/designpattern/Decorator/IPerson.java | Java | apache-2.0 | 141 |
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* 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.
*/
#include <folly/logging/test/XlogHeader1.h>
#include <folly/logging/xlog.h>
namespace logging_test {
void testXlogFile2Dbg1(folly::StringPiece msg) {
XLOG(DBG1, "file2: ", msg);
}
} // namespace logging_test
| facebook/folly | folly/logging/test/XlogFile2.cpp | C++ | apache-2.0 | 831 |
// Copyright 2007-2018 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// 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.
namespace MassTransit.ActiveMqTransport.Topology
{
using Builders;
using Entities;
using MassTransit.Topology;
public interface IActiveMqMessagePublishTopology<TMessage> :
IMessagePublishTopology<TMessage>,
IActiveMqMessagePublishTopology
where TMessage : class
{
Topic Topic { get; }
/// <summary>
/// Returns the send settings for a publish endpoint, which are mostly unused now with topology
/// </summary>
/// <returns></returns>
SendSettings GetSendSettings();
BrokerTopology GetBrokerTopology(PublishBrokerTopologyOptions options = PublishBrokerTopologyOptions.MaintainHierarchy);
}
public interface IActiveMqMessagePublishTopology
{
/// <summary>
/// Apply the message topology to the builder, including any implemented types
/// </summary>
/// <param name="builder">The topology builder</param>
void Apply(IPublishEndpointBrokerTopologyBuilder builder);
}
} | SanSYS/MassTransit | src/MassTransit.ActiveMqTransport/Topology/IActiveMqMessagePublishTopology.cs | C# | apache-2.0 | 1,710 |
package me.uuus.sue4j.model;
public class Role {
private Long id;
private String roleName;
private String roleSign;
private String description;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName == null ? null : roleName.trim();
}
public String getRoleSign() {
return roleSign;
}
public void setRoleSign(String roleSign) {
this.roleSign = roleSign == null ? null : roleSign.trim();
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description == null ? null : description.trim();
}
} | sue0917/sue4j | src/main/java/me/uuus/sue4j/model/Role.java | Java | apache-2.0 | 861 |
package io.vertx.resourceadapter.impl;
import java.security.AccessController;
import java.security.PrivilegedAction;
/**
*
* @author Lin Gao <lgao@redhat.com>
*
*/
class SecurityActions {
private SecurityActions() {
}
/**
* Gets current context class loader
*
* @return the current context class loader
*/
static ClassLoader getContextClassLoader() {
if (System.getSecurityManager() == null) {
return Thread.currentThread().getContextClassLoader();
}
return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
@Override
public ClassLoader run() {
return Thread.currentThread().getContextClassLoader();
}
});
}
/**
* Sets current context classloader
*
* @param classLoader
*/
static void setCurrentContextClassLoader(final ClassLoader classLoader) {
if (System.getSecurityManager() == null) {
Thread.currentThread().setContextClassLoader(classLoader);
} else {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
@Override
public Void run() {
Thread.currentThread().setContextClassLoader(classLoader);
return null;
}
});
}
}
/**
* Gets the system property.
*
* @param propName
* the property name
* @return the property value
*/
static String getSystemProperty(final String propName) {
if (System.getSecurityManager() == null) {
return System.getProperty(propName);
}
return AccessController.doPrivileged(new PrivilegedAction<String>() {
@Override
public String run() {
return System.getProperty(propName);
}
});
}
// =========================================================
// Some Util Methods Below
// =========================================================
/**
* Whether the string is a valid expression.
*
* @param string
* the string
* @return true if the string starts with '${' and ends with '}', false
* otherwise
*/
static boolean isExpression(final String string) {
if (string == null) {
return false;
}
return string.startsWith("${") && string.endsWith("}");
}
/**
* Gets the express value by the key.
*
* @param key
* the key where the system property is set.
* @return the expression value or the key itself if the system property is
* not set.
*/
static String getExpressValue(final String key) {
if (isExpression(key)) {
String keyValue = getSystemProperty(key.substring(2, key.length() - 1));
return keyValue == null ? key : keyValue;
} else {
return key;
}
}
}
| vert-x3/vertx-jca | rar/src/main/java/io/vertx/resourceadapter/impl/SecurityActions.java | Java | apache-2.0 | 2,712 |
using NServiceBus;
public class EndpointConfig :
IConfigureThisEndpoint,
AsA_Server,
IWantCustomInitialization
{
public void Init()
{
Configure configure = Configure.With();
configure.DefineEndpointName("Samples.Logging.HostDefault");
configure.DefaultBuilder();
configure.InMemorySagaPersister();
configure.UseInMemoryTimeoutPersister();
configure.InMemorySubscriptionStorage();
configure.JsonSerializer();
}
} | pashute/docs.particular.net | samples/logging/hostdefault/Version_3_3/Sample/EndpointConfig.cs | C# | apache-2.0 | 494 |
,.<?php
require 'vendor/autoload.php';
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Tools\Setup;
use Doctrine\ORM\Tools\Console\ConsoleRunner;
$devMode = true;
$path = array('stockscreener/Resource/Database');
$config = Setup::createAnnotationMetadataConfiguration($path, $devMode);
$settings = require '../config/settings.php';
$db = $settings['doctrine']['connection'];
$connectionOptions = array(
'driver' => $db['driver'],
'host' => $db['host'],
'dbname' => $db['dbname'],
'user' => $db['user'],
'password' => $db['password']
);
$entityManager = EntityManager::create($connectionOptions, $config);
return ConsoleRunner::createHelperSet($entityManager);
| MDILLENB/finanzmarktportal | config/cli-config.php | PHP | apache-2.0 | 800 |
package cn.xishan.oftenporter.porter.core.util.config;
import cn.xishan.oftenporter.porter.core.util.OftenTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Vector;
/**
* @author Created by https://github.com/CLovinr on 2020-11-04.
*/
public class ChangeableProperty<T> implements AutoCloseable, OnPropertyChange<T>
{
private static final Logger LOGGER = LoggerFactory.getLogger(ChangeableProperty.class);
protected T value;
protected T defaultValue;
private List<OnPropertyChange<T>> changeList = new Vector<>();
private String attr;
public ChangeableProperty(T value)
{
this(null, value);
}
public ChangeableProperty(String attr, T value)
{
this.attr = attr;
this.value = value;
}
public ChangeableProperty(String attr, T value, T defaultValue)
{
this.attr = attr;
this.value = value == null ? defaultValue : value;
this.defaultValue = defaultValue;
}
public String getAttr()
{
return attr;
}
public void setAttr(String attr)
{
this.attr = attr;
}
public T getValue()
{
return value;
}
public T getValue(T defaultValue)
{
T v = getValue();
if (v == null)
{
v = defaultValue;
}
return v;
}
public ChangeableProperty<T> setDefaultValue(T t)
{
this.defaultValue = t;
return this;
}
public ChangeableProperty<T> addListener(OnPropertyChange<T> change)
{
return addListener(false, change);
}
public ChangeableProperty<T> addListener(boolean trigger, OnPropertyChange<T> change)
{
changeList.add(change);
if (trigger)
{
change.onChange(this, getAttr(), getValue(), null);
}
return this;
}
public ChangeableProperty<T> removeListener(OnPropertyChange<T> change)
{
changeList.remove(change);
return this;
}
protected void onChangeFinished(T newValue, T oldValue)
{
}
public ChangeableProperty<T> submitValue(T newValue)
{
if (newValue == null)
{
newValue = defaultValue;
}
T oldValue = getValue();
if (OftenTool.notEqual(newValue, oldValue))
{
this.value = newValue;
for (OnPropertyChange<T> change : changeList)
{
if (change != this)
{
try
{
change.onChange(this, attr, newValue, oldValue);
} catch (Exception e)
{
LOGGER.warn(e.getMessage(), e);
}
}
}
onChangeFinished(newValue, oldValue);
}
return this;
}
/**
* 释放该属性。
*/
public void release()
{
value = null;
defaultValue = null;
changeList.clear();
}
@Override
public void close()
{
release();
}
@Override
public void onChange(ChangeableProperty<T> property, String attr, T newValue, T oldValue)
{
this.submitValue(newValue);
}
}
| gzxishan/OftenPorter | Porter-Core/src/main/java/cn/xishan/oftenporter/porter/core/util/config/ChangeableProperty.java | Java | apache-2.0 | 3,291 |
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using Functional.Contracts.Utility;
namespace Functional.Utility {
public class Something<T> : ISomething<T> {
public T Item { get; set; }
public override string ToString() { return this.Item.ToString(); }
private Something(T t){ this.Item = t; }
public static Func<T,ISomething<T>> Create = (t) => new Something<T>(t);
public static Func<T,T,int> compare = (t1, t2) => 0; //set this to be useful
public static Func<ISomething<T>,ISomething<T>,int> Compare = (t1,t2) => compare(t1.Item, t2.Item);
}
public class SomethingImmutable<T> : ISomethingImmutable<T> {
public T Item { get; private set; }
public override string ToString() { return this.Item.ToString(); }
private SomethingImmutable(T t) { this.Item = t; }
public static Func<T,ISomethingImmutable<T>> Create = (t) => new SomethingImmutable<T>(t);
public static Func<T,T,int> compare = (t1, t2) => 0; //set this to be useful
public static Func<ISomethingImmutable<T>,ISomethingImmutable<T>,int> Compare = (t1,t2) => compare(t1.Item, t2.Item);
}
} | codecore/Functional | Functional/Utility/Something.cs | C# | apache-2.0 | 1,262 |
// +-------------------------------------------------------------------------
// | Copyright (C) 2016 Yunify, Inc.
// +-------------------------------------------------------------------------
// | Licensed under the Apache License, Version 2.0 (the "License");
// | you may not use this work except in compliance with the License.
// | You may obtain a copy of the License in the LICENSE file, or 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 service
import (
"fmt"
"time"
"github.com/yunify/qingcloud-sdk-go/config"
"github.com/yunify/qingcloud-sdk-go/request"
"github.com/yunify/qingcloud-sdk-go/request/data"
"github.com/yunify/qingcloud-sdk-go/request/errors"
)
var _ fmt.State
var _ time.Time
type InstanceService struct {
Config *config.Config
Properties *InstanceServiceProperties
}
type InstanceServiceProperties struct {
// QingCloud Zone ID
Zone *string `json:"zone" name:"zone"` // Required
}
func (s *QingCloudService) Instance(zone string) (*InstanceService, error) {
properties := &InstanceServiceProperties{
Zone: &zone,
}
return &InstanceService{Config: s.Config, Properties: properties}, nil
}
// Documentation URL: https://docs.qingcloud.com/api/instance/describe_instance_types.html
func (s *InstanceService) DescribeInstanceTypes(i *DescribeInstanceTypesInput) (*DescribeInstanceTypesOutput, error) {
if i == nil {
i = &DescribeInstanceTypesInput{}
}
o := &data.Operation{
Config: s.Config,
Properties: s.Properties,
APIName: "DescribeInstanceTypes",
RequestMethod: "GET",
}
x := &DescribeInstanceTypesOutput{}
r, err := request.New(o, i, x)
if err != nil {
return nil, err
}
err = r.Send()
if err != nil {
return nil, err
}
return x, err
}
type DescribeInstanceTypesInput struct {
InstanceTypes []*string `json:"instance_types" name:"instance_types" location:"params"`
}
func (v *DescribeInstanceTypesInput) Validate() error {
return nil
}
type DescribeInstanceTypesOutput struct {
Message *string `json:"message" name:"message"`
Action *string `json:"action" name:"action" location:"elements"`
InstanceTypeSet []*InstanceType `json:"instance_type_set" name:"instance_type_set" location:"elements"`
RetCode *int `json:"ret_code" name:"ret_code" location:"elements"`
TotalCount *int `json:"total_count" name:"total_count" location:"elements"`
}
// Documentation URL: https://docs.qingcloud.com/api/instance/describe_instances.html
func (s *InstanceService) DescribeInstances(i *DescribeInstancesInput) (*DescribeInstancesOutput, error) {
if i == nil {
i = &DescribeInstancesInput{}
}
o := &data.Operation{
Config: s.Config,
Properties: s.Properties,
APIName: "DescribeInstances",
RequestMethod: "GET",
}
x := &DescribeInstancesOutput{}
r, err := request.New(o, i, x)
if err != nil {
return nil, err
}
err = r.Send()
if err != nil {
return nil, err
}
return x, err
}
type DescribeInstancesInput struct {
ImageID []*string `json:"image_id" name:"image_id" location:"params"`
// InstanceClass's available values: 0, 1
InstanceClass *int `json:"instance_class" name:"instance_class" location:"params"`
InstanceType []*string `json:"instance_type" name:"instance_type" location:"params"`
Instances []*string `json:"instances" name:"instances" location:"params"`
Limit *int `json:"limit" name:"limit" default:"20" location:"params"`
Offset *int `json:"offset" name:"offset" default:"0" location:"params"`
SearchWord *string `json:"search_word" name:"search_word" location:"params"`
Status []*string `json:"status" name:"status" location:"params"`
Tags []*string `json:"tags" name:"tags" location:"params"`
// Verbose's available values: 0, 1
Verbose *int `json:"verbose" name:"verbose" location:"params"`
}
func (v *DescribeInstancesInput) Validate() error {
if v.InstanceClass != nil {
instanceClassValidValues := []string{"0", "1"}
instanceClassParameterValue := fmt.Sprint(*v.InstanceClass)
instanceClassIsValid := false
for _, value := range instanceClassValidValues {
if value == instanceClassParameterValue {
instanceClassIsValid = true
}
}
if !instanceClassIsValid {
return errors.ParameterValueNotAllowedError{
ParameterName: "InstanceClass",
ParameterValue: instanceClassParameterValue,
AllowedValues: instanceClassValidValues,
}
}
}
if v.Verbose != nil {
verboseValidValues := []string{"0", "1"}
verboseParameterValue := fmt.Sprint(*v.Verbose)
verboseIsValid := false
for _, value := range verboseValidValues {
if value == verboseParameterValue {
verboseIsValid = true
}
}
if !verboseIsValid {
return errors.ParameterValueNotAllowedError{
ParameterName: "Verbose",
ParameterValue: verboseParameterValue,
AllowedValues: verboseValidValues,
}
}
}
return nil
}
type DescribeInstancesOutput struct {
Message *string `json:"message" name:"message"`
Action *string `json:"action" name:"action" location:"elements"`
InstanceSet []*Instance `json:"instance_set" name:"instance_set" location:"elements"`
RetCode *int `json:"ret_code" name:"ret_code" location:"elements"`
TotalCount *int `json:"total_count" name:"total_count" location:"elements"`
}
// Documentation URL: https://docs.qingcloud.com/api/monitor/get_monitor.html
func (s *InstanceService) GetInstanceMonitor(i *GetInstanceMonitorInput) (*GetInstanceMonitorOutput, error) {
if i == nil {
i = &GetInstanceMonitorInput{}
}
o := &data.Operation{
Config: s.Config,
Properties: s.Properties,
APIName: "GetMonitor",
RequestMethod: "GET",
}
x := &GetInstanceMonitorOutput{}
r, err := request.New(o, i, x)
if err != nil {
return nil, err
}
err = r.Send()
if err != nil {
return nil, err
}
return x, err
}
type GetInstanceMonitorInput struct {
EndTime *time.Time `json:"end_time" name:"end_time" format:"ISO 8601" location:"params"` // Required
Meters []*string `json:"meters" name:"meters" location:"params"` // Required
Resource *string `json:"resource" name:"resource" location:"params"` // Required
StartTime *time.Time `json:"start_time" name:"start_time" format:"ISO 8601" location:"params"` // Required
// Step's available values: 5m, 15m, 2h, 1d
Step *string `json:"step" name:"step" location:"params"` // Required
}
func (v *GetInstanceMonitorInput) Validate() error {
if len(v.Meters) == 0 {
return errors.ParameterRequiredError{
ParameterName: "Meters",
ParentName: "GetInstanceMonitorInput",
}
}
if v.Resource == nil {
return errors.ParameterRequiredError{
ParameterName: "Resource",
ParentName: "GetInstanceMonitorInput",
}
}
if v.Step == nil {
return errors.ParameterRequiredError{
ParameterName: "Step",
ParentName: "GetInstanceMonitorInput",
}
}
if v.Step != nil {
stepValidValues := []string{"5m", "15m", "2h", "1d"}
stepParameterValue := fmt.Sprint(*v.Step)
stepIsValid := false
for _, value := range stepValidValues {
if value == stepParameterValue {
stepIsValid = true
}
}
if !stepIsValid {
return errors.ParameterValueNotAllowedError{
ParameterName: "Step",
ParameterValue: stepParameterValue,
AllowedValues: stepValidValues,
}
}
}
return nil
}
type GetInstanceMonitorOutput struct {
Message *string `json:"message" name:"message"`
Action *string `json:"action" name:"action" location:"elements"`
MeterSet []*Meter `json:"meter_set" name:"meter_set" location:"elements"`
ResourceID *string `json:"resource_id" name:"resource_id" location:"elements"`
RetCode *int `json:"ret_code" name:"ret_code" location:"elements"`
}
// Documentation URL: https://docs.qingcloud.com/api/instance/modify_instance_attributes.html
func (s *InstanceService) ModifyInstanceAttributes(i *ModifyInstanceAttributesInput) (*ModifyInstanceAttributesOutput, error) {
if i == nil {
i = &ModifyInstanceAttributesInput{}
}
o := &data.Operation{
Config: s.Config,
Properties: s.Properties,
APIName: "ModifyInstanceAttributes",
RequestMethod: "GET",
}
x := &ModifyInstanceAttributesOutput{}
r, err := request.New(o, i, x)
if err != nil {
return nil, err
}
err = r.Send()
if err != nil {
return nil, err
}
return x, err
}
type ModifyInstanceAttributesInput struct {
Description *string `json:"description" name:"description" location:"params"`
Instance *string `json:"instance" name:"instance" location:"params"` // Required
InstanceName *string `json:"instance_name" name:"instance_name" location:"params"`
}
func (v *ModifyInstanceAttributesInput) Validate() error {
if v.Instance == nil {
return errors.ParameterRequiredError{
ParameterName: "Instance",
ParentName: "ModifyInstanceAttributesInput",
}
}
return nil
}
type ModifyInstanceAttributesOutput struct {
Message *string `json:"message" name:"message"`
Action *string `json:"action" name:"action" location:"elements"`
RetCode *int `json:"ret_code" name:"ret_code" location:"elements"`
}
// Documentation URL: https://docs.qingcloud.com/api/instance/reset_instances.html
func (s *InstanceService) ResetInstances(i *ResetInstancesInput) (*ResetInstancesOutput, error) {
if i == nil {
i = &ResetInstancesInput{}
}
o := &data.Operation{
Config: s.Config,
Properties: s.Properties,
APIName: "ResetInstances",
RequestMethod: "GET",
}
x := &ResetInstancesOutput{}
r, err := request.New(o, i, x)
if err != nil {
return nil, err
}
err = r.Send()
if err != nil {
return nil, err
}
return x, err
}
type ResetInstancesInput struct {
Instances []*string `json:"instances" name:"instances" location:"params"` // Required
LoginKeyPair *string `json:"login_keypair" name:"login_keypair" location:"params"`
// LoginMode's available values: keypair, passwd
LoginMode *string `json:"login_mode" name:"login_mode" location:"params"` // Required
LoginPasswd *string `json:"login_passwd" name:"login_passwd" location:"params"`
// NeedNewSID's available values: 0, 1
NeedNewSID *int `json:"need_newsid" name:"need_newsid" default:"0" location:"params"`
}
func (v *ResetInstancesInput) Validate() error {
if len(v.Instances) == 0 {
return errors.ParameterRequiredError{
ParameterName: "Instances",
ParentName: "ResetInstancesInput",
}
}
if v.LoginMode == nil {
return errors.ParameterRequiredError{
ParameterName: "LoginMode",
ParentName: "ResetInstancesInput",
}
}
if v.LoginMode != nil {
loginModeValidValues := []string{"keypair", "passwd"}
loginModeParameterValue := fmt.Sprint(*v.LoginMode)
loginModeIsValid := false
for _, value := range loginModeValidValues {
if value == loginModeParameterValue {
loginModeIsValid = true
}
}
if !loginModeIsValid {
return errors.ParameterValueNotAllowedError{
ParameterName: "LoginMode",
ParameterValue: loginModeParameterValue,
AllowedValues: loginModeValidValues,
}
}
}
if v.NeedNewSID != nil {
needNewSIDValidValues := []string{"0", "1"}
needNewSIDParameterValue := fmt.Sprint(*v.NeedNewSID)
needNewSIDIsValid := false
for _, value := range needNewSIDValidValues {
if value == needNewSIDParameterValue {
needNewSIDIsValid = true
}
}
if !needNewSIDIsValid {
return errors.ParameterValueNotAllowedError{
ParameterName: "NeedNewSID",
ParameterValue: needNewSIDParameterValue,
AllowedValues: needNewSIDValidValues,
}
}
}
return nil
}
type ResetInstancesOutput struct {
Message *string `json:"message" name:"message"`
Action *string `json:"action" name:"action" location:"elements"`
JobID *string `json:"job_id" name:"job_id" location:"elements"`
RetCode *int `json:"ret_code" name:"ret_code" location:"elements"`
}
// Documentation URL: https://docs.qingcloud.com/api/instance/resize_instances.html
func (s *InstanceService) ResizeInstances(i *ResizeInstancesInput) (*ResizeInstancesOutput, error) {
if i == nil {
i = &ResizeInstancesInput{}
}
o := &data.Operation{
Config: s.Config,
Properties: s.Properties,
APIName: "ResizeInstances",
RequestMethod: "GET",
}
x := &ResizeInstancesOutput{}
r, err := request.New(o, i, x)
if err != nil {
return nil, err
}
err = r.Send()
if err != nil {
return nil, err
}
return x, err
}
type ResizeInstancesInput struct {
// CPU's available values: 1, 2, 4, 8, 16
CPU *int `json:"cpu" name:"cpu" location:"params"`
InstanceType *string `json:"instance_type" name:"instance_type" location:"params"`
Instances []*string `json:"instances" name:"instances" location:"params"` // Required
// Memory's available values: 1024, 2048, 4096, 6144, 8192, 12288, 16384, 24576, 32768
Memory *int `json:"memory" name:"memory" location:"params"`
}
func (v *ResizeInstancesInput) Validate() error {
if v.CPU != nil {
cpuValidValues := []string{"1", "2", "4", "8", "16"}
cpuParameterValue := fmt.Sprint(*v.CPU)
cpuIsValid := false
for _, value := range cpuValidValues {
if value == cpuParameterValue {
cpuIsValid = true
}
}
if !cpuIsValid {
return errors.ParameterValueNotAllowedError{
ParameterName: "CPU",
ParameterValue: cpuParameterValue,
AllowedValues: cpuValidValues,
}
}
}
if len(v.Instances) == 0 {
return errors.ParameterRequiredError{
ParameterName: "Instances",
ParentName: "ResizeInstancesInput",
}
}
if v.Memory != nil {
memoryValidValues := []string{"1024", "2048", "4096", "6144", "8192", "12288", "16384", "24576", "32768"}
memoryParameterValue := fmt.Sprint(*v.Memory)
memoryIsValid := false
for _, value := range memoryValidValues {
if value == memoryParameterValue {
memoryIsValid = true
}
}
if !memoryIsValid {
return errors.ParameterValueNotAllowedError{
ParameterName: "Memory",
ParameterValue: memoryParameterValue,
AllowedValues: memoryValidValues,
}
}
}
return nil
}
type ResizeInstancesOutput struct {
Message *string `json:"message" name:"message"`
Action *string `json:"action" name:"action" location:"elements"`
JobID *string `json:"job_id" name:"job_id" location:"elements"`
RetCode *int `json:"ret_code" name:"ret_code" location:"elements"`
}
// Documentation URL: https://docs.qingcloud.com/api/instance/restart_instances.html
func (s *InstanceService) RestartInstances(i *RestartInstancesInput) (*RestartInstancesOutput, error) {
if i == nil {
i = &RestartInstancesInput{}
}
o := &data.Operation{
Config: s.Config,
Properties: s.Properties,
APIName: "RestartInstances",
RequestMethod: "GET",
}
x := &RestartInstancesOutput{}
r, err := request.New(o, i, x)
if err != nil {
return nil, err
}
err = r.Send()
if err != nil {
return nil, err
}
return x, err
}
type RestartInstancesInput struct {
Instances []*string `json:"instances" name:"instances" location:"params"` // Required
}
func (v *RestartInstancesInput) Validate() error {
if len(v.Instances) == 0 {
return errors.ParameterRequiredError{
ParameterName: "Instances",
ParentName: "RestartInstancesInput",
}
}
return nil
}
type RestartInstancesOutput struct {
Message *string `json:"message" name:"message"`
Action *string `json:"action" name:"action" location:"elements"`
JobID *string `json:"job_id" name:"job_id" location:"elements"`
RetCode *int `json:"ret_code" name:"ret_code" location:"elements"`
}
// Documentation URL: https://docs.qingcloud.com/api/instance/run_instances.html
func (s *InstanceService) RunInstances(i *RunInstancesInput) (*RunInstancesOutput, error) {
if i == nil {
i = &RunInstancesInput{}
}
o := &data.Operation{
Config: s.Config,
Properties: s.Properties,
APIName: "RunInstances",
RequestMethod: "GET",
}
x := &RunInstancesOutput{}
r, err := request.New(o, i, x)
if err != nil {
return nil, err
}
err = r.Send()
if err != nil {
return nil, err
}
return x, err
}
type RunInstancesInput struct {
BillingID *string `json:"billing_id" name:"billing_id" location:"params"`
Count *int `json:"count" name:"count" default:"1" location:"params"`
// CPU's available values: 1, 2, 4, 8, 16
CPU *int `json:"cpu" name:"cpu" default:"1" location:"params"`
Hostname *string `json:"hostname" name:"hostname" location:"params"`
ImageID *string `json:"image_id" name:"image_id" location:"params"` // Required
// InstanceClass's available values: 0, 1
InstanceClass *int `json:"instance_class" name:"instance_class" location:"params"`
InstanceName *string `json:"instance_name" name:"instance_name" location:"params"`
InstanceType *string `json:"instance_type" name:"instance_type" location:"params"`
LoginKeyPair *string `json:"login_keypair" name:"login_keypair" location:"params"`
// LoginMode's available values: keypair, passwd
LoginMode *string `json:"login_mode" name:"login_mode" location:"params"` // Required
LoginPasswd *string `json:"login_passwd" name:"login_passwd" location:"params"`
// Memory's available values: 1024, 2048, 4096, 6144, 8192, 12288, 16384, 24576, 32768
Memory *int `json:"memory" name:"memory" default:"1024" location:"params"`
// NeedNewSID's available values: 0, 1
NeedNewSID *int `json:"need_newsid" name:"need_newsid" default:"0" location:"params"`
// NeedUserdata's available values: 0, 1
NeedUserdata *int `json:"need_userdata" name:"need_userdata" default:"0" location:"params"`
SecurityGroup *string `json:"security_group" name:"security_group" location:"params"`
UIType *string `json:"ui_type" name:"ui_type" location:"params"`
UserdataFile *string `json:"userdata_file" name:"userdata_file" default:"etc/rc.local" location:"params"`
UserdataPath *string `json:"userdata_path" name:"userdata_path" default:"etc/qingcloud/userdata" location:"params"`
// UserdataType's available values: plain, exec, tar
UserdataType *string `json:"userdata_type" name:"userdata_type" location:"params"`
UserdataValue *string `json:"userdata_value" name:"userdata_value" location:"params"`
Volumes []*string `json:"volumes" name:"volumes" location:"params"`
VxNets []*string `json:"vxnets" name:"vxnets" location:"params"`
}
func (v *RunInstancesInput) Validate() error {
if v.CPU != nil {
cpuValidValues := []string{"1", "2", "4", "8", "16"}
cpuParameterValue := fmt.Sprint(*v.CPU)
cpuIsValid := false
for _, value := range cpuValidValues {
if value == cpuParameterValue {
cpuIsValid = true
}
}
if !cpuIsValid {
return errors.ParameterValueNotAllowedError{
ParameterName: "CPU",
ParameterValue: cpuParameterValue,
AllowedValues: cpuValidValues,
}
}
}
if v.ImageID == nil {
return errors.ParameterRequiredError{
ParameterName: "ImageID",
ParentName: "RunInstancesInput",
}
}
if v.InstanceClass != nil {
instanceClassValidValues := []string{"0", "1"}
instanceClassParameterValue := fmt.Sprint(*v.InstanceClass)
instanceClassIsValid := false
for _, value := range instanceClassValidValues {
if value == instanceClassParameterValue {
instanceClassIsValid = true
}
}
if !instanceClassIsValid {
return errors.ParameterValueNotAllowedError{
ParameterName: "InstanceClass",
ParameterValue: instanceClassParameterValue,
AllowedValues: instanceClassValidValues,
}
}
}
if v.LoginMode == nil {
return errors.ParameterRequiredError{
ParameterName: "LoginMode",
ParentName: "RunInstancesInput",
}
}
if v.LoginMode != nil {
loginModeValidValues := []string{"keypair", "passwd"}
loginModeParameterValue := fmt.Sprint(*v.LoginMode)
loginModeIsValid := false
for _, value := range loginModeValidValues {
if value == loginModeParameterValue {
loginModeIsValid = true
}
}
if !loginModeIsValid {
return errors.ParameterValueNotAllowedError{
ParameterName: "LoginMode",
ParameterValue: loginModeParameterValue,
AllowedValues: loginModeValidValues,
}
}
}
if v.Memory != nil {
memoryValidValues := []string{"1024", "2048", "4096", "6144", "8192", "12288", "16384", "24576", "32768"}
memoryParameterValue := fmt.Sprint(*v.Memory)
memoryIsValid := false
for _, value := range memoryValidValues {
if value == memoryParameterValue {
memoryIsValid = true
}
}
if !memoryIsValid {
return errors.ParameterValueNotAllowedError{
ParameterName: "Memory",
ParameterValue: memoryParameterValue,
AllowedValues: memoryValidValues,
}
}
}
if v.NeedNewSID != nil {
needNewSIDValidValues := []string{"0", "1"}
needNewSIDParameterValue := fmt.Sprint(*v.NeedNewSID)
needNewSIDIsValid := false
for _, value := range needNewSIDValidValues {
if value == needNewSIDParameterValue {
needNewSIDIsValid = true
}
}
if !needNewSIDIsValid {
return errors.ParameterValueNotAllowedError{
ParameterName: "NeedNewSID",
ParameterValue: needNewSIDParameterValue,
AllowedValues: needNewSIDValidValues,
}
}
}
if v.NeedUserdata != nil {
needUserdataValidValues := []string{"0", "1"}
needUserdataParameterValue := fmt.Sprint(*v.NeedUserdata)
needUserdataIsValid := false
for _, value := range needUserdataValidValues {
if value == needUserdataParameterValue {
needUserdataIsValid = true
}
}
if !needUserdataIsValid {
return errors.ParameterValueNotAllowedError{
ParameterName: "NeedUserdata",
ParameterValue: needUserdataParameterValue,
AllowedValues: needUserdataValidValues,
}
}
}
if v.UserdataType != nil {
userdataTypeValidValues := []string{"plain", "exec", "tar"}
userdataTypeParameterValue := fmt.Sprint(*v.UserdataType)
userdataTypeIsValid := false
for _, value := range userdataTypeValidValues {
if value == userdataTypeParameterValue {
userdataTypeIsValid = true
}
}
if !userdataTypeIsValid {
return errors.ParameterValueNotAllowedError{
ParameterName: "UserdataType",
ParameterValue: userdataTypeParameterValue,
AllowedValues: userdataTypeValidValues,
}
}
}
return nil
}
type RunInstancesOutput struct {
Message *string `json:"message" name:"message"`
Action *string `json:"action" name:"action" location:"elements"`
Instances []*string `json:"instances" name:"instances" location:"elements"`
JobID *string `json:"job_id" name:"job_id" location:"elements"`
RetCode *int `json:"ret_code" name:"ret_code" location:"elements"`
}
// Documentation URL: https://docs.qingcloud.com/api/instance/start_instances.html
func (s *InstanceService) StartInstances(i *StartInstancesInput) (*StartInstancesOutput, error) {
if i == nil {
i = &StartInstancesInput{}
}
o := &data.Operation{
Config: s.Config,
Properties: s.Properties,
APIName: "StartInstances",
RequestMethod: "GET",
}
x := &StartInstancesOutput{}
r, err := request.New(o, i, x)
if err != nil {
return nil, err
}
err = r.Send()
if err != nil {
return nil, err
}
return x, err
}
type StartInstancesInput struct {
Instances []*string `json:"instances" name:"instances" location:"params"` // Required
}
func (v *StartInstancesInput) Validate() error {
if len(v.Instances) == 0 {
return errors.ParameterRequiredError{
ParameterName: "Instances",
ParentName: "StartInstancesInput",
}
}
return nil
}
type StartInstancesOutput struct {
Message *string `json:"message" name:"message"`
Action *string `json:"action" name:"action" location:"elements"`
JobID *string `json:"job_id" name:"job_id" location:"elements"`
RetCode *int `json:"ret_code" name:"ret_code" location:"elements"`
}
// Documentation URL: https://docs.qingcloud.com/api/instance/stop_instances.html
func (s *InstanceService) StopInstances(i *StopInstancesInput) (*StopInstancesOutput, error) {
if i == nil {
i = &StopInstancesInput{}
}
o := &data.Operation{
Config: s.Config,
Properties: s.Properties,
APIName: "StopInstances",
RequestMethod: "GET",
}
x := &StopInstancesOutput{}
r, err := request.New(o, i, x)
if err != nil {
return nil, err
}
err = r.Send()
if err != nil {
return nil, err
}
return x, err
}
type StopInstancesInput struct {
// Force's available values: 0, 1
Force *int `json:"force" name:"force" default:"0" location:"params"`
Instances []*string `json:"instances" name:"instances" location:"params"` // Required
}
func (v *StopInstancesInput) Validate() error {
if v.Force != nil {
forceValidValues := []string{"0", "1"}
forceParameterValue := fmt.Sprint(*v.Force)
forceIsValid := false
for _, value := range forceValidValues {
if value == forceParameterValue {
forceIsValid = true
}
}
if !forceIsValid {
return errors.ParameterValueNotAllowedError{
ParameterName: "Force",
ParameterValue: forceParameterValue,
AllowedValues: forceValidValues,
}
}
}
if len(v.Instances) == 0 {
return errors.ParameterRequiredError{
ParameterName: "Instances",
ParentName: "StopInstancesInput",
}
}
return nil
}
type StopInstancesOutput struct {
Message *string `json:"message" name:"message"`
Action *string `json:"action" name:"action" location:"elements"`
JobID *string `json:"job_id" name:"job_id" location:"elements"`
RetCode *int `json:"ret_code" name:"ret_code" location:"elements"`
}
// Documentation URL: https://docs.qingcloud.com/api/instance/terminate_instances.html
func (s *InstanceService) TerminateInstances(i *TerminateInstancesInput) (*TerminateInstancesOutput, error) {
if i == nil {
i = &TerminateInstancesInput{}
}
o := &data.Operation{
Config: s.Config,
Properties: s.Properties,
APIName: "TerminateInstances",
RequestMethod: "GET",
}
x := &TerminateInstancesOutput{}
r, err := request.New(o, i, x)
if err != nil {
return nil, err
}
err = r.Send()
if err != nil {
return nil, err
}
return x, err
}
type TerminateInstancesInput struct {
Instances []*string `json:"instances" name:"instances" location:"params"` // Required
}
func (v *TerminateInstancesInput) Validate() error {
if len(v.Instances) == 0 {
return errors.ParameterRequiredError{
ParameterName: "Instances",
ParentName: "TerminateInstancesInput",
}
}
return nil
}
type TerminateInstancesOutput struct {
Message *string `json:"message" name:"message"`
Action *string `json:"action" name:"action" location:"elements"`
JobID *string `json:"job_id" name:"job_id" location:"elements"`
RetCode *int `json:"ret_code" name:"ret_code" location:"elements"`
}
| jolestar/qingcloud-sdk-go | service/instance.go | GO | apache-2.0 | 27,243 |
/**
* 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 org.apache.pulsar.common.compression;
import com.github.luben.zstd.Zstd;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import java.io.IOException;
import java.nio.ByteBuffer;
/**
* Zstandard Compression
*/
public class CompressionCodecZstd implements CompressionCodec {
private static final int ZSTD_COMPRESSION_LEVEL = 3;
@Override
public ByteBuf encode(ByteBuf source) {
int uncompressedLength = source.readableBytes();
int maxLength = (int) Zstd.compressBound(uncompressedLength);
ByteBuf target = PooledByteBufAllocator.DEFAULT.directBuffer(maxLength, maxLength);
int compressedLength;
if (source.hasMemoryAddress()) {
compressedLength = (int) Zstd.compressUnsafe(target.memoryAddress(), maxLength,
source.memoryAddress() + source.readerIndex(),
uncompressedLength, ZSTD_COMPRESSION_LEVEL);
} else {
ByteBuffer sourceNio = source.nioBuffer(source.readerIndex(), source.readableBytes());
ByteBuffer targetNio = target.nioBuffer(0, maxLength);
compressedLength = Zstd.compress(targetNio, sourceNio, ZSTD_COMPRESSION_LEVEL);
}
target.writerIndex(compressedLength);
return target;
}
@Override
public ByteBuf decode(ByteBuf encoded, int uncompressedLength) throws IOException {
ByteBuf uncompressed = PooledByteBufAllocator.DEFAULT.directBuffer(uncompressedLength, uncompressedLength);
if (encoded.hasMemoryAddress()) {
Zstd.decompressUnsafe(uncompressed.memoryAddress(), uncompressedLength,
encoded.memoryAddress() + encoded.readerIndex(),
encoded.readableBytes());
} else {
ByteBuffer uncompressedNio = uncompressed.nioBuffer(0, uncompressedLength);
ByteBuffer encodedNio = encoded.nioBuffer(encoded.readerIndex(), encoded.readableBytes());
Zstd.decompress(uncompressedNio, encodedNio);
}
uncompressed.writerIndex(uncompressedLength);
return uncompressed;
}
}
| nkurihar/pulsar | pulsar-common/src/main/java/org/apache/pulsar/common/compression/CompressionCodecZstd.java | Java | apache-2.0 | 2,951 |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/ads/googleads/v9/errors/url_field_error.proto
require 'google/api/annotations_pb'
require 'google/protobuf'
Google::Protobuf::DescriptorPool.generated_pool.build do
add_file("google/ads/googleads/v9/errors/url_field_error.proto", :syntax => :proto3) do
add_message "google.ads.googleads.v9.errors.UrlFieldErrorEnum" do
end
add_enum "google.ads.googleads.v9.errors.UrlFieldErrorEnum.UrlFieldError" do
value :UNSPECIFIED, 0
value :UNKNOWN, 1
value :INVALID_TRACKING_URL_TEMPLATE, 2
value :INVALID_TAG_IN_TRACKING_URL_TEMPLATE, 3
value :MISSING_TRACKING_URL_TEMPLATE_TAG, 4
value :MISSING_PROTOCOL_IN_TRACKING_URL_TEMPLATE, 5
value :INVALID_PROTOCOL_IN_TRACKING_URL_TEMPLATE, 6
value :MALFORMED_TRACKING_URL_TEMPLATE, 7
value :MISSING_HOST_IN_TRACKING_URL_TEMPLATE, 8
value :INVALID_TLD_IN_TRACKING_URL_TEMPLATE, 9
value :REDUNDANT_NESTED_TRACKING_URL_TEMPLATE_TAG, 10
value :INVALID_FINAL_URL, 11
value :INVALID_TAG_IN_FINAL_URL, 12
value :REDUNDANT_NESTED_FINAL_URL_TAG, 13
value :MISSING_PROTOCOL_IN_FINAL_URL, 14
value :INVALID_PROTOCOL_IN_FINAL_URL, 15
value :MALFORMED_FINAL_URL, 16
value :MISSING_HOST_IN_FINAL_URL, 17
value :INVALID_TLD_IN_FINAL_URL, 18
value :INVALID_FINAL_MOBILE_URL, 19
value :INVALID_TAG_IN_FINAL_MOBILE_URL, 20
value :REDUNDANT_NESTED_FINAL_MOBILE_URL_TAG, 21
value :MISSING_PROTOCOL_IN_FINAL_MOBILE_URL, 22
value :INVALID_PROTOCOL_IN_FINAL_MOBILE_URL, 23
value :MALFORMED_FINAL_MOBILE_URL, 24
value :MISSING_HOST_IN_FINAL_MOBILE_URL, 25
value :INVALID_TLD_IN_FINAL_MOBILE_URL, 26
value :INVALID_FINAL_APP_URL, 27
value :INVALID_TAG_IN_FINAL_APP_URL, 28
value :REDUNDANT_NESTED_FINAL_APP_URL_TAG, 29
value :MULTIPLE_APP_URLS_FOR_OSTYPE, 30
value :INVALID_OSTYPE, 31
value :INVALID_PROTOCOL_FOR_APP_URL, 32
value :INVALID_PACKAGE_ID_FOR_APP_URL, 33
value :URL_CUSTOM_PARAMETERS_COUNT_EXCEEDS_LIMIT, 34
value :INVALID_CHARACTERS_IN_URL_CUSTOM_PARAMETER_KEY, 39
value :INVALID_CHARACTERS_IN_URL_CUSTOM_PARAMETER_VALUE, 40
value :INVALID_TAG_IN_URL_CUSTOM_PARAMETER_VALUE, 41
value :REDUNDANT_NESTED_URL_CUSTOM_PARAMETER_TAG, 42
value :MISSING_PROTOCOL, 43
value :INVALID_PROTOCOL, 52
value :INVALID_URL, 44
value :DESTINATION_URL_DEPRECATED, 45
value :INVALID_TAG_IN_URL, 46
value :MISSING_URL_TAG, 47
value :DUPLICATE_URL_ID, 48
value :INVALID_URL_ID, 49
value :FINAL_URL_SUFFIX_MALFORMED, 50
value :INVALID_TAG_IN_FINAL_URL_SUFFIX, 51
value :INVALID_TOP_LEVEL_DOMAIN, 53
value :MALFORMED_TOP_LEVEL_DOMAIN, 54
value :MALFORMED_URL, 55
value :MISSING_HOST, 56
value :NULL_CUSTOM_PARAMETER_VALUE, 57
value :VALUE_TRACK_PARAMETER_NOT_SUPPORTED, 58
end
end
end
module Google
module Ads
module GoogleAds
module V9
module Errors
UrlFieldErrorEnum = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.ads.googleads.v9.errors.UrlFieldErrorEnum").msgclass
UrlFieldErrorEnum::UrlFieldError = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.ads.googleads.v9.errors.UrlFieldErrorEnum.UrlFieldError").enummodule
end
end
end
end
end
| googleads/google-ads-ruby | lib/google/ads/google_ads/v9/errors/url_field_error_pb.rb | Ruby | apache-2.0 | 3,464 |
package designPattern.abstractFactory;
public class Visualization {
private AbstractUIFactory abf;
public Visualization(AbstractUIFactory abf){
this.abf=abf;
}
public Object createButton(){
return this.abf.createButton();
}
}
| outskywind/myproject | demos/src/main/java/designPattern/abstractFactory/Visualization.java | Java | apache-2.0 | 262 |
package com.chenpan.commoner.mvp.modle.imp;
import android.content.Context;
import com.android.volley.VolleyError;
import com.chenpan.commoner.bean.NewsSummary;
import com.chenpan.commoner.mvp.modle.MyCallback;
import com.chenpan.commoner.mvp.modle.NewFragmentModel;
import com.chenpan.commoner.network.VolleyInterface;
import com.chenpan.commoner.network.VolleyRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
/**
* Created by Administrator on 2016/10/10.
*/
public class INewsFragmentModel implements NewFragmentModel{
// String url="http://v.juhe.cn/toutiao/index";
//http://c.m.163.com/nc/article/headline/T1348647909107/0-20.html
@Override
public void parserNews(Context context,String url, final String tag, final MyCallback<List<NewsSummary>> mCallback) {
VolleyRequest.RequestGetString(url, tag, new VolleyInterface() {
@Override
public void onMySuccess(String result) {
Gson gson = new Gson();
JSONObject jsonObject=null;
try {
jsonObject=new JSONObject(result);
} catch (JSONException e) {
e.printStackTrace();
}
if(jsonObject!=null){
String newslist=null;
try {
newslist=jsonObject.getString(tag);
} catch (JSONException e) {
e.printStackTrace();
}
List<NewsSummary> newsSummaries=gson.fromJson(newslist, new TypeToken<List<NewsSummary>>() {
}.getType());
if (newsSummaries!=null){
mCallback.onSccuss(newsSummaries);
}else{
mCallback.onFaild();
}}else{
mCallback.onFaild();
}
}
@Override
public void onMyError(VolleyError result) {
mCallback.onFaild();
}
});
}
} | a616707902/Commoner | Commoner/app/src/main/java/com/chenpan/commoner/mvp/modle/imp/INewsFragmentModel.java | Java | apache-2.0 | 2,139 |
/*
* Licensed to The Apereo Foundation under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* The Apereo Foundation 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 com.tle.core.security;
import java.util.Set;
public interface SecurityTargetHandler {
/**
* Add all applicable labels for a target to the set of labels. For example, an item target would
* add a label for itself, its status, its collection (or a transformer could deal with this),
* etc... This is used when gathering all the applicable permissions that apply to a given target.
*
* @param labels a set of labels that should be added to.
* @param target the target object to generate labels for.
*/
void gatherAllLabels(Set<String> labels, Object target);
/**
* Add only the primary label for a target, ignoring any "parent" labels that may apply. For
* example, an item target would return "I:{uuid}" only. This is used when getting/setting target
* lists to the database.
*
* @param target the target object to generate the primary label for.
* @return the primary label.
*/
String getPrimaryLabel(Object target);
/**
* Transforms a security target into another type. For example, an ItemPack target can be
* transformed into an Item object that would then get processed by other handlers. To try and
* avoid circular transformation loops try to transform targets "up" the hierarchy, eg, Item to
* Collection. This typically makes sense anyway as "parent" targets won't have the information
* regarding which "child" target to transform to.
*
* @param target the target object to transform.
* @return the transformed object.
*/
Object transform(Object target);
/**
* @param target the object to determine ownership of.
* @param userId the user identifier we're checking for ownership.
* @return true if the target is owner by the userId.
*/
boolean isOwner(Object target, String userId);
}
| equella/Equella | Source/Plugins/Security/com.tle.core.security/src/com/tle/core/security/SecurityTargetHandler.java | Java | apache-2.0 | 2,607 |
/**
* @file genetic_solver.cpp
* @brief Genetic Solver implementation of "Genetic algorithms for modelling
* and optimisation"
* @ingroup optimisation
*
* @author Christophe Ecabert
* @date 10.04.18
* Copyright © 2018 Christophe Ecabert. All rights reserved.
*/
#include <fstream>
#include "facekit/optimisation/genetic_solver.hpp"
/**
* @namespace FaceKit
* @brief Development space
*/
namespace FaceKit {
#pragma mark -
#pragma mark Initialisation
/*
* @name GeneticSolver
* @fn GeneticSolver(const size_t& pop_size, const size_t& chromo_size,
* const ChromosomeCtor& ctor)
* @brief Constructor
* @param[in] pop_size Population size (Number of chromosomes)
* @param[in] chromo_size Size of one chromosome
* @param[in] ctor Callback creating a derived chromosome
*/
template<typename T>
GeneticSolver<T>::GeneticSolver(const size_t& pop_size,
const size_t& chromo_size,
const ChromosomeCtor& ctor) :
curr_population_(new Population<T>(pop_size)),
next_population_(new Population<T>(pop_size)),
chromo_length_(chromo_size) {
// Init population
curr_population_->Create(chromo_size, ctor);
next_population_->Create(chromo_size, ctor);
}
/*
* @name ~GeneticSolver
* @fn ~GeneticSolver(void)
* @brief Destructor
*/
template<typename T>
GeneticSolver<T>::~GeneticSolver(void) {
if (curr_population_) {
delete curr_population_;
}
if (next_population_) {
delete next_population_;
}
}
#pragma mark -
#pragma mark Usage
/*
* @name Solve
* @fn ConvergenceType Solve(const Parameters& params)
* @brief Solve the given optimisation problem
* @param[in] params Configuration
*/
template<typename T>
typename GeneticSolver<T>::ConvergenceType
GeneticSolver<T>::Solve(const Parameters& params) {
std::ofstream stream("log.txt");
// Compute fitness
// T avg_fit_begin = curr_population_->Fitness();
size_t n_gen = 0;
T prev_max_fit = 0.0;
T max_max_fit = 0.0;
size_t hist_max_fit_cnt = 0; // Counter of how many gen have the same max_fit
// Iterate
while(n_gen < params.max_generation &&
prev_max_fit < params.fitness_target &&
hist_max_fit_cnt < params.n_max_fitness_generation) {
// Perform CrossOver / Mutation / Fitness
this->CrossOver(params.p_crossover);
this->Mutate(params.p_mutation);
T avg_fit_next = next_population_->Fitness();
T next_max_fit = next_population_->maximum_fitness();
// Alternate current <-> next generation
std::swap(curr_population_, next_population_);
n_gen++;
prev_max_fit = next_max_fit;
if (prev_max_fit > max_max_fit) {
max_max_fit = prev_max_fit;
hist_max_fit_cnt = 0;
} else {
T fit_inc_percent = std::abs(prev_max_fit - max_max_fit) / max_max_fit;
if (fit_inc_percent != 0.0 &&
fit_inc_percent <= params.percentage_fitness) {
hist_max_fit_cnt += 1;
} else {
hist_max_fit_cnt = 0;
}
}
stream << avg_fit_next << "," << next_max_fit << std::endl;
}
return (n_gen == params.max_generation ?
ConvergenceType::kReachMaxGeneration : ConvergenceType::kConverged);
}
/*
* @name BestFitness
* @fn ChromosomeType* BestFitness(void) const
* @brief Give the chromosome with the best fitness
* @return Chromosome with solution
*/
template<typename T>
typename GeneticSolver<T>::ChromosomeType*
GeneticSolver<T>::BestFitness(void) const {
// Get best fitness index
size_t k = curr_population_->maximum_fitness_index();
return curr_population_->at(k);
}
#pragma mark -
#pragma mark Private
/*
* @name CrossOver
* @fn void CrossOver(const T& rate)
* @brief Perform crossover
* @param[in] rate Crossover rate
*/
template<typename T>
void GeneticSolver<T>::CrossOver(const T& rate) {
// Loop overall
size_t k = 0;
/*for (; k < curr_population_->size() - 2; k += 2) {
auto* s1 = next_population_->at(k);
auto* s2 = next_population_->at(k+1);
curr_population_->CrossOver(rate, s1, s2);
}*/
for (;k < curr_population_->size(); ++k) {
auto* s1 = next_population_->at(k);
curr_population_->CrossOver(rate, s1, nullptr);
}
}
/*
* @name Mutate
* @fn void Mutate(const T& rate)
* @brief Perform mutation
* @param[in] rate Mutation rate
*/
template<typename T>
void GeneticSolver<T>::Mutate(const T& rate) {
next_population_->Mutate(rate);
}
#pragma mark -
#pragma mark Explicit instantiation
/** Float */
template class GeneticSolver<float>;
/** Double */
template class GeneticSolver<double>;
} // namespace FaceKit
| ChristopheEcabert/FaceKit | modules/optimisation/src/genetic_solver.cpp | C++ | apache-2.0 | 4,724 |
/*
* Copyright (c) 2011-2013, Peter Abeles. All Rights Reserved.
*
* This file is part of BoofCV (http://boofcv.org).
*
* 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 boofcv.core.image;
import boofcv.struct.image.*;
import java.lang.reflect.Method;
/**
* <p>
* Generalized functions for converting between different image types. Numerical values do not change or are closely
* approximated in these functions. If an output image is not specified then a new instance is declared and returned.
* </p>
*
* @author Peter Abeles
*/
public class GConvertImage {
/**
* <p>
* Converts one type of {@link ImageSingleBand} into a different type by typecasting each pixel.
* </p>
*
* @param input Input image which is being converted. Not modified.
* @param output (Optional) The output image. If null a new image is created. Modified.
* @return Converted image.
*/
public static void convert( ImageSingleBand input , ImageSingleBand output ) {
if( input.getClass() == output.getClass() ) {
output.setTo(input);
} else {
try {
Method m = ConvertImage.class.getMethod("convert",input.getClass(),output.getClass());
m.invoke(null,input,output);
} catch (Exception e) {
throw new IllegalArgumentException("Unknown conversion");
}
}
}
/**
* Converts a {@link MultiSpectral} into a {@link ImageSingleBand} by computing the average value of each pixel
* across all the bands.
*
* @param input Input MultiSpectral image that is being converted. Not modified.
* @param output (Optional) The single band output image. If null a new image is created. Modified.
* @return Converted image.
*/
public static <T extends ImageSingleBand>T average( MultiSpectral<T> input , T output ) {
Class type = input.getType();
if( type == ImageUInt8.class ) {
return (T)ConvertImage.average((MultiSpectral<ImageUInt8>)input,(ImageUInt8)output);
} else if( type == ImageSInt8.class ) {
return (T)ConvertImage.average((MultiSpectral<ImageSInt8>)input,(ImageSInt8)output);
} else if( type == ImageUInt16.class ) {
return (T)ConvertImage.average((MultiSpectral<ImageUInt16>)input,(ImageUInt16)output);
} else if( type == ImageSInt16.class ) {
return (T)ConvertImage.average((MultiSpectral<ImageSInt16>)input,(ImageSInt16)output);
} else if( type == ImageSInt32.class ) {
return (T)ConvertImage.average((MultiSpectral<ImageSInt32>)input,(ImageSInt32)output);
} else if( type == ImageSInt64.class ) {
return (T)ConvertImage.average((MultiSpectral<ImageSInt64>)input,(ImageSInt64)output);
} else if( type == ImageFloat32.class ) {
return (T)ConvertImage.average((MultiSpectral<ImageFloat32>)input,(ImageFloat32)output);
} else if( type == ImageFloat64.class ) {
return (T)ConvertImage.average((MultiSpectral<ImageFloat64>)input,(ImageFloat64)output);
} else {
throw new IllegalArgumentException("Unknown image type: "+type.getSimpleName());
}
}
}
| intrack/BoofCV-master | main/ip/src/boofcv/core/image/GConvertImage.java | Java | apache-2.0 | 3,455 |
import React from 'react';
import planList from './plans';
import {paymentCountries} from './config';
import Popover from 'material-ui/Popover';
class PlanDetails extends React.Component {
constructor(props) {
super(props);
this.state = {
selectedPlan: planList[0],
openPlanSelector: false
};
}
handleTouchTap = (event) => {
event.preventDefault();
this.setState({openPlanSelector: true, anchorEl: event.currentTarget})
}
handleRequestClose = () => {
this.setState({openPlanSelector: false})
}
selectPlan(plan) {
this.setState({selectedPlan: plan})
this.handleRequestClose()
}
render() {
return (
<div className="plans">
<div className="planname" onTouchTap={this.handleTouchTap}>
<span className="type">{this.state.selectedPlan.label}</span>
<span className="value">{this.state.selectedPlan.price || this.state.selectedPlan.price === 0
? '$ ' + this.state.selectedPlan.price
: ''}</span>
<i className="icon ion-ios-arrow-down arrow"></i>
</div>
<Popover open={this.state.openPlanSelector} anchorEl={this.state.anchorEl} anchorOrigin={{
horizontal: 'left',
vertical: 'bottom'
}} targetOrigin={{
horizontal: 'left',
vertical: 'top'
}} onRequestClose={this.handleRequestClose}>
{planList.map((plan, i) => {
return <div className="plannamepop" key={i} onClick={this.selectPlan.bind(this, plan)}>
<span className="type">{plan.label}</span>
<span className="value">{plan.price || plan.price === 0
? '$ ' + plan.price
: 'Custom'}</span>
</div>
})
}
</Popover>
<p className="divlabel">DATABASE</p>
<div className="divdetail">
<span className="type">API Calls</span>
<span className="value">{this.state.selectedPlan.usage[0].features[0].limit.label}</span>
</div>
<div className="divdetail">
<span className="type">Storage</span>
<span className="value">{this.state.selectedPlan.usage[0].features[1].limit.label}</span>
</div>
<p className="divlabel">REALTIME</p>
<div className="divdetail">
<span className="type">Connections</span>
<span className="value">{this.state.selectedPlan.usage[1].features[0].limit.label}</span>
</div>
<p className="divlabel">MISC</p>
<div className="divdetail">
<span className="type">MongoDB Access</span>
<span className="value">{this.state.selectedPlan.usage[2].features[0].limit.show
? 'Available'
: '-'}</span>
</div>
</div>
)
}
}
export default PlanDetails
| CloudBoost/cloudboost | payment-ui/src/planDetails.js | JavaScript | apache-2.0 | 3,357 |
package com.saq.android.data;
public class AccompagnementReference extends Reference {
}
| cipicip/android | saq.forked/app/src/main/java/com/saq/android/data/AccompagnementReference.java | Java | apache-2.0 | 90 |
/*
* Mark Benjamin 6th March 2019
* Copyright (c) 2019 Mark Benjamin
*/
#ifndef FASTRL_DOMAIN_SINGLEAGENT_POMDP_TIGER_TIGER_DOMAIN_HPP
#define FASTRL_DOMAIN_SINGLEAGENT_POMDP_TIGER_TIGER_DOMAIN_HPP
class TigerDomain {
};
#endif //FASTRL_DOMAIN_SINGLEAGENT_POMDP_TIGER_TIGER_DOMAIN_HPP
| MarkieMark/fastrl | src/domain/singleagent/pomdp/tiger/tiger_domain.hpp | C++ | apache-2.0 | 293 |
package com.redhat.ceylon.compiler.java.runtime.tools.impl;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Set;
import com.redhat.ceylon.cmr.api.ArtifactContext;
import com.redhat.ceylon.cmr.api.ArtifactResult;
import com.redhat.ceylon.cmr.api.ImportType;
import com.redhat.ceylon.cmr.api.JDKUtils;
import com.redhat.ceylon.cmr.api.RepositoryException;
import com.redhat.ceylon.cmr.api.RepositoryManager;
import com.redhat.ceylon.cmr.ceylon.CeylonUtils;
import com.redhat.ceylon.cmr.impl.FlatRepository;
import com.redhat.ceylon.common.ModuleUtil;
import com.redhat.ceylon.common.Versions;
import com.redhat.ceylon.compiler.java.runtime.metamodel.Metamodel;
import com.redhat.ceylon.compiler.java.runtime.tools.JavaRunnerOptions;
import com.redhat.ceylon.compiler.java.runtime.tools.JavaRunner;
import com.redhat.ceylon.compiler.java.runtime.tools.RunnerOptions;
import com.redhat.ceylon.compiler.typechecker.model.Module;
public class JavaRunnerImpl implements JavaRunner {
private Map<String,ArtifactResult> loadedModules = new HashMap<String,ArtifactResult>();
private Map<String,String> loadedModuleVersions = new HashMap<String,String>();
private RepositoryManager repositoryManager;
private Set<String> loadedModulesInCurrentClassLoader = new HashSet<String>();
private ClassLoader moduleClassLoader;
private ClassLoader delegateClassLoader;
private String module;
private Map<String, String> extraModules;
public JavaRunnerImpl(RunnerOptions options, String module, String version){
repositoryManager = CeylonUtils.repoManager()
.userRepos(options.getUserRepositories())
.systemRepo(options.getSystemRepository())
.offline(options.isOffline())
.buildManager();
if(options instanceof JavaRunnerOptions){
delegateClassLoader = ((JavaRunnerOptions) options).getDelegateClassLoader();
}
if(delegateClassLoader == null)
delegateClassLoader = JavaRunnerImpl.class.getClassLoader();
this.module = module;
this.extraModules = options.getExtraModules();
try {
// those come from the delegate class loader
loadModule(Module.LANGUAGE_MODULE_NAME, Versions.CEYLON_VERSION_NUMBER, false, true);
loadModule("com.redhat.ceylon.compiler.java", Versions.CEYLON_VERSION_NUMBER, false, true);
loadModule("com.redhat.ceylon.common", Versions.CEYLON_VERSION_NUMBER, false, true);
loadModule("com.redhat.ceylon.module-resolver", Versions.CEYLON_VERSION_NUMBER, false, true);
loadModule("com.redhat.ceylon.typechecker", Versions.CEYLON_VERSION_NUMBER, false, true);
// these ones not necessarily
loadModule(module, version, false, false);
for(Entry<String,String> entry : options.getExtraModules().entrySet()){
loadModule(entry.getKey(), entry.getValue(), false, false);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
setupClassLoader();
initialiseMetamodel();
}
@Override
public void run(String... arguments){
if(moduleClassLoader == null)
throw new ceylon.language.AssertionError("Cannot call run method after cleanup is called");
// now load and invoke the main class
invokeMain(module, arguments);
}
@Override
public ClassLoader getModuleClassLoader() {
if(moduleClassLoader == null)
throw new ceylon.language.AssertionError("Cannot get class loader after cleanup is called");
return moduleClassLoader;
}
private void setupClassLoader(){
// make a Class loader for this module if required
if(loadedModulesInCurrentClassLoader.contains(module))
moduleClassLoader = delegateClassLoader;
else
moduleClassLoader = makeModuleClassLoader();
}
private void initialiseMetamodel() {
Set<String> registered = new HashSet<String>();
registerInMetamodel("ceylon.language", registered);
registerInMetamodel("com.redhat.ceylon.typechecker", registered);
registerInMetamodel("com.redhat.ceylon.common", registered);
registerInMetamodel("com.redhat.ceylon.module-resolver", registered);
registerInMetamodel("com.redhat.ceylon.compiler.java", registered);
registerInMetamodel(module, registered);
if(extraModules != null){
for(String extraModule : extraModules.keySet()){
registerInMetamodel(extraModule, registered);
}
}
}
@Override
public void cleanup() {
if(moduleClassLoader != delegateClassLoader
&& moduleClassLoader instanceof URLClassLoader){
try {
((URLClassLoader) moduleClassLoader).close();
moduleClassLoader = null;
} catch (IOException e) {
// ignore
e.printStackTrace();
}
}
}
// for tests
public URL[] getClassLoaderURLs(){
if(moduleClassLoader != delegateClassLoader
&& moduleClassLoader instanceof URLClassLoader){
return ((URLClassLoader) moduleClassLoader).getURLs();
}
return null;
}
private void invokeMain(String module, String[] arguments) {
String className;
if(module.equals(com.redhat.ceylon.compiler.typechecker.model.Module.DEFAULT_MODULE_NAME))
className = "run_";
else
className = module + ".run_";
try {
Class<?> runClass = moduleClassLoader.loadClass(className);
Method main = runClass.getMethod("main", String[].class);
Thread currentThread = Thread.currentThread();
ClassLoader oldCcl = currentThread.getContextClassLoader();
try{
currentThread.setContextClassLoader(moduleClassLoader);
main.invoke(null, (Object)arguments);
}finally{
currentThread.setContextClassLoader(oldCcl);
}
} catch (ClassNotFoundException e) {
throw new RuntimeException("Cannot find main class for module "+module+": "+className, e);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException e) {
throw new RuntimeException("Failed to invoke main method for module "+module+": "+className, e);
}
}
private ClassLoader makeModuleClassLoader() {
// we need to make a class loader for all the modules it requires which are not provided by the current class loader
Set<String> modulesNotInCurrentClassLoader = new HashSet<String>();
for(Entry<String, ArtifactResult> entry : loadedModules.entrySet()){
if(entry.getValue() != null)
modulesNotInCurrentClassLoader.add(entry.getKey());
}
modulesNotInCurrentClassLoader.removeAll(loadedModulesInCurrentClassLoader);
URL[] urls = new URL[modulesNotInCurrentClassLoader.size()];
int i=0;
for(String module : modulesNotInCurrentClassLoader){
ArtifactResult artifact = loadedModules.get(module);
try {
@SuppressWarnings("deprecation")
URL url = artifact.artifact().toURL();
urls[i++] = url;
} catch (MalformedURLException | RepositoryException e) {
throw new RuntimeException("Failed to get a URL for module file for "+module, e);
}
}
return new URLClassLoader(urls , delegateClassLoader);
}
private void loadModule(String name, String version, boolean optional, boolean inCurrentClassLoader) throws IOException {
// skip JDK modules
if(JDKUtils.isJDKModule(name) || JDKUtils.isOracleJDKModule(name))
return;
if(loadedModules.containsKey(name)){
ArtifactResult loadedModule = loadedModules.get(name);
String resolvedVersion = loadedModuleVersions.get(name);
// we loaded the module already, but did we load it with the same version?
if(!Objects.equals(version, resolvedVersion)){
// version conflict, even if one was a missing optional
throw new RuntimeException("Requiring two modules with the same name ("+name+") but conflicting versions: "+version+" and "+resolvedVersion);
}
// now we're sure the version was the same
if(loadedModule == null){
// it was resolved to null so it was optional, but perhaps it's required now?
if(!optional){
throw new RuntimeException("Missing module: "+ModuleUtil.makeModuleName(name, version));
}
}
// already resolved and same version, we're good
return;
}
ArtifactContext artifactContext = new ArtifactContext(name, version, ArtifactContext.CAR, ArtifactContext.JAR);
ArtifactResult result = repositoryManager.getArtifactResult(artifactContext);
if(!optional
&& (result == null || result.artifact() == null || !result.artifact().exists())){
throw new RuntimeException("Missing module: "+ModuleUtil.makeModuleName(name, version));
}
// save even missing optional modules as nulls to not re-resolve them
loadedModules.put(name, result);
loadedModuleVersions.put(name, version);
if(result != null){
// everything we know should be in the current class loader
// plus everything from flat repositories
if(inCurrentClassLoader || result.repository() instanceof FlatRepository){
loadedModulesInCurrentClassLoader.add(name);
}
for(ArtifactResult dep : result.dependencies()){
loadModule(dep.name(), dep.version(), dep.importType() == ImportType.OPTIONAL, inCurrentClassLoader);
}
}
}
// we only need the module name since we already dealt with conflicting versions
private void registerInMetamodel(String module, Set<String> registered) {
if(!registered.add(module))
return;
// skip JDK modules
if(JDKUtils.isJDKModule(module) || JDKUtils.isOracleJDKModule(module))
return;
// use the one we got from the CMR rather than the one for dependencies mapping
ArtifactResult dependencyArtifact = loadedModules.get(module);
// it may be optional, we already dealt with those checks earlier
if(dependencyArtifact != null){
ClassLoader dependencyClassLoader;
if(loadedModulesInCurrentClassLoader.contains(module))
dependencyClassLoader = delegateClassLoader;
else
dependencyClassLoader = moduleClassLoader;
registerInMetamodel(dependencyArtifact, dependencyClassLoader, registered);
}
}
private void registerInMetamodel(ArtifactResult artifact, ClassLoader classLoader, Set<String> registered) {
Metamodel.loadModule(artifact.name(), artifact.version(), artifact, classLoader);
// also register its dependencies
for(ArtifactResult dep : artifact.dependencies()){
registerInMetamodel(dep.name(), registered);
}
}
}
| jvasileff/ceylon.language | runtime/com/redhat/ceylon/compiler/java/runtime/tools/impl/JavaRunnerImpl.java | Java | apache-2.0 | 11,825 |
#include "extensions/grpc_credentials/example/config.h"
#include "envoy/api/v2/core/grpc_service.pb.h"
#include "envoy/grpc/google_grpc_creds.h"
#include "envoy/registry/registry.h"
#include "common/grpc/google_grpc_creds_impl.h"
namespace Envoy {
namespace Extensions {
namespace GrpcCredentials {
namespace Example {
std::shared_ptr<grpc::ChannelCredentials>
AccessTokenExampleGrpcCredentialsFactory::getChannelCredentials(
const envoy::api::v2::core::GrpcService& grpc_service_config) {
const auto& google_grpc = grpc_service_config.google_grpc();
std::shared_ptr<grpc::ChannelCredentials> creds =
defaultSslChannelCredentials(grpc_service_config, false);
std::shared_ptr<grpc::CallCredentials> call_creds = nullptr;
for (const auto& credential : google_grpc.call_credentials()) {
switch (credential.credential_specifier_case()) {
case envoy::api::v2::core::GrpcService::GoogleGrpc::CallCredentials::kAccessToken: {
if (!credential.access_token().empty()) {
std::shared_ptr<grpc::CallCredentials> new_call_creds = grpc::MetadataCredentialsFromPlugin(
std::make_unique<StaticHeaderAuthenticator>(credential.access_token()));
if (call_creds == nullptr) {
call_creds = new_call_creds;
} else {
call_creds = grpc::CompositeCallCredentials(call_creds, new_call_creds);
}
}
break;
}
default:
// unused credential types
continue;
}
}
if (call_creds != nullptr) {
return grpc::CompositeChannelCredentials(creds, call_creds);
}
return creds;
}
grpc::Status
StaticHeaderAuthenticator::GetMetadata(grpc::string_ref, grpc::string_ref, const grpc::AuthContext&,
std::multimap<grpc::string, grpc::string>* metadata) {
// this function is run on a separate thread by the gRPC client library (independent of Envoy
// threading), so it can perform actions such as refreshing an access token without blocking
// the main thread. see:
// https://grpc.io/grpc/cpp/classgrpc_1_1_metadata_credentials_plugin.html#a6faf44f7c08d0311a38a868fdb8cbaf0
metadata->insert(std::make_pair("authorization", "Bearer " + ticket_));
return grpc::Status::OK;
}
/**
* Static registration for the static header Google gRPC credentials factory. @see RegisterFactory.
*/
static Registry::RegisterFactory<AccessTokenExampleGrpcCredentialsFactory,
Grpc::GoogleGrpcCredentialsFactory>
access_token_google_grpc_credentials_registered_;
} // namespace Example
} // namespace GrpcCredentials
} // namespace Extensions
} // namespace Envoy
| sebrandon1/envoy | source/extensions/grpc_credentials/example/config.cc | C++ | apache-2.0 | 2,636 |
import {ApiFile} from '../api/api_interfaces';
import {Directory, File, PathSpecPathType} from '../models/vfs';
import {assertEnum, assertKeyNonNull, assertNonNull} from '../preconditions';
import {isStatEntry, translateHashToHex, translateStatEntry} from './flow';
import {createDate} from './primitive';
const VFS_PATH_RE = /^(\/*fs\/+)?([a-z]+)(.*)$/;
/** Splits a VFS path "fs/os/foo" into PathType "OS" and path "/foo". */
export function parseVfsPath(vfsPath: string):
{pathtype: PathSpecPathType, path: string} {
const match = VFS_PATH_RE.exec(vfsPath);
assertNonNull(match, 'match');
const pathtype = match[2].toUpperCase();
assertEnum(pathtype, PathSpecPathType);
return {pathtype, path: match[3]};
}
/** Constructs a File or Directory from the corresponding API data structure */
export function translateFile(file: ApiFile): File|Directory {
assertKeyNonNull(file, 'isDirectory');
assertKeyNonNull(file, 'name');
assertKeyNonNull(file, 'path');
const {path, pathtype} = parseVfsPath(file.path);
const base = {
name: file.name,
path,
pathtype,
isDirectory: file.isDirectory,
};
if (base.isDirectory) {
return base as Directory;
}
let lastContentCollected: File['lastContentCollected'];
if (file.lastCollected) {
assertKeyNonNull(file, 'lastCollectedSize');
lastContentCollected = {
timestamp: createDate(file.lastCollected),
size: BigInt(file.lastCollectedSize),
};
}
assertKeyNonNull(file, 'age');
assertKeyNonNull(file, 'stat');
const stat = translateStatEntry(file.stat);
if (!isStatEntry(stat)) {
throw new Error('translateFile only works for non-Registry files for now.');
}
return {
...base,
type: file.type,
stat,
hash: file.hash ? translateHashToHex(file.hash) : undefined,
lastContentCollected,
lastMetadataCollected: createDate(file.age),
};
}
| google/grr | grr/server/grr_response_server/gui/ui/lib/api_translation/vfs.ts | TypeScript | apache-2.0 | 1,901 |
package fm.jiecao.jcvideoplayer_lib;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Handler;
import android.provider.Settings;
import android.support.v7.app.ActionBar;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import java.lang.reflect.Constructor;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
/**
* Created by Nathen on 16/7/30.
*/
public abstract class JCVideoPlayer extends FrameLayout implements View.OnClickListener, SeekBar.OnSeekBarChangeListener, View.OnTouchListener {
public static final String TAG = "JieCaoVideoPlayer";
public static boolean ACTION_BAR_EXIST = true;
public static boolean TOOL_BAR_EXIST = true;
public static int FULLSCREEN_ORIENTATION = ActivityInfo.SCREEN_ORIENTATION_SENSOR;
public static int NORMAL_ORIENTATION = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
public static boolean SAVE_PROGRESS = true;
public static boolean WIFI_TIP_DIALOG_SHOWED = false;
public static final int FULLSCREEN_ID = 33797;
public static final int TINY_ID = 33798;
public static final int THRESHOLD = 80;
public static final int FULL_SCREEN_NORMAL_DELAY = 300;
public static long CLICK_QUIT_FULLSCREEN_TIME = 0;
public static final int SCREEN_LAYOUT_NORMAL = 0;
public static final int SCREEN_LAYOUT_LIST = 1;
public static final int SCREEN_WINDOW_FULLSCREEN = 2;
public static final int SCREEN_WINDOW_TINY = 3;
public static final int CURRENT_STATE_NORMAL = 0;
public static final int CURRENT_STATE_PREPARING = 1;
public static final int CURRENT_STATE_PLAYING = 2;
public static final int CURRENT_STATE_PLAYING_BUFFERING_START = 3;
public static final int CURRENT_STATE_PAUSE = 5;
public static final int CURRENT_STATE_AUTO_COMPLETE = 6;
public static final int CURRENT_STATE_ERROR = 7;
public static int BACKUP_PLAYING_BUFFERING_STATE = -1;
public int currentState = -1;
public int currentScreen = -1;
public boolean loop = false;
public Map<String, String> headData;
public String url = "";
public Object[] objects = null;
public int seekToInAdvance = 0;
public ImageView startButton;
public SeekBar progressBar;
public ImageView fullscreenButton;
public TextView currentTimeTextView, totalTimeTextView;
public ViewGroup textureViewContainer;
public ViewGroup topContainer, bottomContainer;
protected static JCUserAction JC_USER_EVENT;
protected static Timer UPDATE_PROGRESS_TIMER;
protected int mScreenWidth;
protected int mScreenHeight;
protected AudioManager mAudioManager;
protected Handler mHandler;
protected ProgressTimerTask mProgressTimerTask;
protected boolean mTouchingProgressBar;
protected float mDownX;
protected float mDownY;
protected boolean mChangeVolume;
protected boolean mChangePosition;
protected boolean mChangeBrightness;
protected int mGestureDownPosition;
protected int mGestureDownVolume;
protected float mGestureDownBrightness;
protected int mSeekTimePosition;
public JCVideoPlayer(Context context) {
super(context);
init(context);
}
public JCVideoPlayer(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public abstract int getLayoutId();
public void init(Context context) {
View.inflate(context, getLayoutId(), this);
startButton = (ImageView) findViewById(R.id.start);
fullscreenButton = (ImageView) findViewById(R.id.fullscreen);
progressBar = (SeekBar) findViewById(R.id.bottom_seek_progress);
currentTimeTextView = (TextView) findViewById(R.id.current);
totalTimeTextView = (TextView) findViewById(R.id.total);
bottomContainer = (ViewGroup) findViewById(R.id.layout_bottom);
textureViewContainer = (ViewGroup) findViewById(R.id.surface_container);
topContainer = (ViewGroup) findViewById(R.id.layout_top);
startButton.setOnClickListener(this);
fullscreenButton.setOnClickListener(this);
progressBar.setOnSeekBarChangeListener(this);
bottomContainer.setOnClickListener(this);
textureViewContainer.setOnClickListener(this);
textureViewContainer.setOnTouchListener(this);
mScreenWidth = getContext().getResources().getDisplayMetrics().widthPixels;
mScreenHeight = getContext().getResources().getDisplayMetrics().heightPixels;
mAudioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
mHandler = new Handler();
NORMAL_ORIENTATION = context.getResources().getConfiguration().orientation;
}
public void setUp(String url, int screen, Object... objects) {
if (!TextUtils.isEmpty(this.url) && TextUtils.equals(this.url, url)) {
return;
}
this.url = url;
this.objects = objects;
this.currentScreen = screen;
this.headData = null;
onStateNormal();
}
//===============================================新增的代码=======================================================================
private OnVideoClickListener mOnVideoClickListener;
public void setOnVideoClickListener(OnVideoClickListener listener){
mOnVideoClickListener = listener;
}
@Override
public void onClick(View v) {
int i = v.getId();
if (i == R.id.start) {
Log.i(TAG, "onClick start [" + this.hashCode() + "] ");
//===============================================新增的代码=======================================================================
if (mOnVideoClickListener != null && currentState == -1){
mOnVideoClickListener.onVideoClickToStart();
}
if (currentState == CURRENT_STATE_NORMAL || currentState == CURRENT_STATE_ERROR) {
if (TextUtils.isEmpty(url)) {
Toast.makeText(getContext(), getResources().getString(R.string.no_url), Toast.LENGTH_SHORT).show();
return;
}
if (!url.startsWith("file") && !JCUtils.isWifiConnected(getContext()) && !WIFI_TIP_DIALOG_SHOWED) {
showWifiDialog(JCUserActionStandard.ON_CLICK_START_ICON);
return;
}
startVideo();
onEvent(currentState != CURRENT_STATE_ERROR ? JCUserAction.ON_CLICK_START_ICON : JCUserAction.ON_CLICK_START_ERROR);
} else if (currentState == CURRENT_STATE_PLAYING) {
onEvent(JCUserAction.ON_CLICK_PAUSE);
Log.d(TAG, "pauseVideo [" + this.hashCode() + "] ");
JCMediaManager.instance().mediaPlayer.pause();
onStatePause();
} else if (currentState == CURRENT_STATE_PAUSE) {
onEvent(JCUserAction.ON_CLICK_RESUME);
JCMediaManager.instance().mediaPlayer.start();
onStatePlaying();
} else if (currentState == CURRENT_STATE_AUTO_COMPLETE) {
onEvent(JCUserAction.ON_CLICK_START_AUTO_COMPLETE);
startVideo();
}
} else if (i == R.id.fullscreen) {
Log.i(TAG, "onClick fullscreen [" + this.hashCode() + "] ");
if (currentState == CURRENT_STATE_AUTO_COMPLETE) return;
if (currentScreen == SCREEN_WINDOW_FULLSCREEN) {
//quit fullscreen
backPress();
} else {
Log.d(TAG, "toFullscreenActivity [" + this.hashCode() + "] ");
onEvent(JCUserAction.ON_ENTER_FULLSCREEN);
startWindowFullscreen();
}
} else if (i == R.id.surface_container && currentState == CURRENT_STATE_ERROR) {
Log.i(TAG, "onClick surfaceContainer State=Error [" + this.hashCode() + "] ");
startVideo();
}
}
@Override
public boolean onTouch(View v, MotionEvent event) {
float x = event.getX();
float y = event.getY();
int id = v.getId();
if (id == R.id.surface_container) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.i(TAG, "onTouch surfaceContainer actionDown [" + this.hashCode() + "] ");
mTouchingProgressBar = true;
mDownX = x;
mDownY = y;
mChangeVolume = false;
mChangePosition = false;
mChangeBrightness = false;
break;
case MotionEvent.ACTION_MOVE:
Log.i(TAG, "onTouch surfaceContainer actionMove [" + this.hashCode() + "] ");
float deltaX = x - mDownX;
float deltaY = y - mDownY;
float absDeltaX = Math.abs(deltaX);
float absDeltaY = Math.abs(deltaY);
if (currentScreen == SCREEN_WINDOW_FULLSCREEN) {
if (!mChangePosition && !mChangeVolume && !mChangeBrightness) {
if (absDeltaX > THRESHOLD || absDeltaY > THRESHOLD) {
cancelProgressTimer();
if (absDeltaX >= THRESHOLD) {
// 全屏模式下的CURRENT_STATE_ERROR状态下,不响应进度拖动事件.
// 否则会因为mediaplayer的状态非法导致App Crash
if (currentState != CURRENT_STATE_ERROR) {
mChangePosition = true;
mGestureDownPosition = getCurrentPositionWhenPlaying();
}
} else {
//如果y轴滑动距离超过设置的处理范围,那么进行滑动事件处理
if (mDownX < mScreenWidth * 0.5f) {//左侧改变亮度
mChangeBrightness = true;
WindowManager.LayoutParams lp = JCUtils.getAppCompActivity(getContext()).getWindow().getAttributes();
if (lp.screenBrightness < 0) {
try {
mGestureDownBrightness = Settings.System.getInt(getContext().getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
Log.i(TAG, "current system brightness: " + mGestureDownBrightness);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
}
} else {
mGestureDownBrightness = lp.screenBrightness * 255;
Log.i(TAG, "current activity brightness: " + mGestureDownBrightness);
}
} else {//右侧改变声音
mChangeVolume = true;
mGestureDownVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
}
}
}
}
}
if (mChangePosition) {
int totalTimeDuration = getDuration();
mSeekTimePosition = (int) (mGestureDownPosition + deltaX * totalTimeDuration / mScreenWidth);
if (mSeekTimePosition > totalTimeDuration)
mSeekTimePosition = totalTimeDuration;
String seekTime = JCUtils.stringForTime(mSeekTimePosition);
String totalTime = JCUtils.stringForTime(totalTimeDuration);
showProgressDialog(deltaX, seekTime, mSeekTimePosition, totalTime, totalTimeDuration);
}
if (mChangeVolume) {
deltaY = -deltaY;
int max = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
int deltaV = (int) (max * deltaY * 3 / mScreenHeight);
mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, mGestureDownVolume + deltaV, 0);
//dialog中显示百分比
int volumePercent = (int) (mGestureDownVolume * 100 / max + deltaY * 3 * 100 / mScreenHeight);
showVolumeDialog(-deltaY, volumePercent);
}
if (mChangeBrightness) {
deltaY = -deltaY;
int deltaV = (int) (255 * deltaY * 3 / mScreenHeight);
WindowManager.LayoutParams params = JCUtils.getAppCompActivity(getContext()).getWindow().getAttributes();
if (((mGestureDownBrightness + deltaV) / 255) >= 1) {//这和声音有区别,必须自己过滤一下负值
params.screenBrightness = 1;
} else if (((mGestureDownBrightness + deltaV) / 255) <= 0) {
params.screenBrightness = 0.01f;
} else {
params.screenBrightness = (mGestureDownBrightness + deltaV) / 255;
}
JCUtils.getAppCompActivity(getContext()).getWindow().setAttributes(params);
//dialog中显示百分比
int brightnessPercent = (int) (mGestureDownBrightness * 100 / 255 + deltaY * 3 * 100 / mScreenHeight);
showBrightnessDialog(brightnessPercent);
// mDownY = y;
}
break;
case MotionEvent.ACTION_UP:
Log.i(TAG, "onTouch surfaceContainer actionUp [" + this.hashCode() + "] ");
mTouchingProgressBar = false;
dismissProgressDialog();
dismissVolumeDialog();
dismissBrightnessDialog();
if (mChangePosition) {
onEvent(JCUserAction.ON_TOUCH_SCREEN_SEEK_POSITION);
JCMediaManager.instance().mediaPlayer.seekTo(mSeekTimePosition);
int duration = getDuration();
int progress = mSeekTimePosition * 100 / (duration == 0 ? 1 : duration);
progressBar.setProgress(progress);
}
if (mChangeVolume) {
onEvent(JCUserAction.ON_TOUCH_SCREEN_SEEK_VOLUME);
}
startProgressTimer();
break;
}
}
return false;
}
public void startVideo() {
JCVideoPlayerManager.completeAll();
Log.d(TAG, "startVideo [" + this.hashCode() + "] ");
initTextureView();
addTextureView();
AudioManager mAudioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
mAudioManager.requestAudioFocus(onAudioFocusChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
JCUtils.scanForActivity(getContext()).getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
JCMediaManager.CURRENT_PLAYING_URL = url;
JCMediaManager.CURRENT_PLING_LOOP = loop;
JCMediaManager.MAP_HEADER_DATA = headData;
onStatePreparing();
JCVideoPlayerManager.setFirstFloor(this);
}
public void onPrepared() {
Log.i(TAG, "onPrepared " + " [" + this.hashCode() + "] ");
if (currentState != CURRENT_STATE_PREPARING && currentState != CURRENT_STATE_PLAYING_BUFFERING_START)
return;
if (seekToInAdvance != 0) {
JCMediaManager.instance().mediaPlayer.seekTo(seekToInAdvance);
seekToInAdvance = 0;
} else {
int position = JCUtils.getSavedProgress(getContext(), url);
if (position != 0) {
JCMediaManager.instance().mediaPlayer.seekTo(position);
}
}
startProgressTimer();
onStatePlaying();
}
public void setState(int state) {
switch (state) {
case CURRENT_STATE_NORMAL:
onStateNormal();
break;
case CURRENT_STATE_PREPARING:
onStatePreparing();
break;
case CURRENT_STATE_PLAYING:
onStatePlaying();
break;
case CURRENT_STATE_PAUSE:
onStatePause();
break;
case CURRENT_STATE_PLAYING_BUFFERING_START:
onStatePlaybackBufferingStart();
break;
case CURRENT_STATE_ERROR:
onStateError();
break;
case CURRENT_STATE_AUTO_COMPLETE:
onStateAutoComplete();
break;
}
}
public void onStateNormal() {
Log.i(TAG, "onStateNormal " + " [" + this.hashCode() + "] ");
currentState = CURRENT_STATE_NORMAL;
cancelProgressTimer();
if (isCurrentJcvd()) {//这个if是无法取代的,否则进入全屏的时候会releaseMediaPlayer
JCMediaManager.instance().releaseMediaPlayer();
}
}
public void onStatePreparing() {
Log.i(TAG, "onStatePreparing " + " [" + this.hashCode() + "] ");
currentState = CURRENT_STATE_PREPARING;
resetProgressAndTime();
}
public void onStatePlaying() {
Log.i(TAG, "onStatePlaying " + " [" + this.hashCode() + "] ");
currentState = CURRENT_STATE_PLAYING;
startProgressTimer();
}
public void onStatePause() {
Log.i(TAG, "onStatePause " + " [" + this.hashCode() + "] ");
currentState = CURRENT_STATE_PAUSE;
startProgressTimer();
}
public void onStatePlaybackBufferingStart() {
Log.i(TAG, "onStatePlaybackBufferingStart " + " [" + this.hashCode() + "] ");
currentState = CURRENT_STATE_PLAYING_BUFFERING_START;
startProgressTimer();
}
public void onStateError() {
Log.i(TAG, "onStateError " + " [" + this.hashCode() + "] ");
currentState = CURRENT_STATE_ERROR;
cancelProgressTimer();
}
public void onStateAutoComplete() {
Log.i(TAG, "onStateAutoComplete " + " [" + this.hashCode() + "] ");
currentState = CURRENT_STATE_AUTO_COMPLETE;
cancelProgressTimer();
progressBar.setProgress(100);
currentTimeTextView.setText(totalTimeTextView.getText());
}
public void onInfo(int what, int extra) {
Log.d(TAG, "onInfo what - " + what + " extra - " + extra);
if (what == MediaPlayer.MEDIA_INFO_BUFFERING_START) {
if (currentState == CURRENT_STATE_PLAYING_BUFFERING_START) return;
BACKUP_PLAYING_BUFFERING_STATE = currentState;
onStatePlaybackBufferingStart();
Log.d(TAG, "MEDIA_INFO_BUFFERING_START");
} else if (what == MediaPlayer.MEDIA_INFO_BUFFERING_END) {
if (BACKUP_PLAYING_BUFFERING_STATE != -1) {
if (currentState == CURRENT_STATE_PLAYING_BUFFERING_START) {
setState(BACKUP_PLAYING_BUFFERING_STATE);
}
BACKUP_PLAYING_BUFFERING_STATE = -1;
}
Log.d(TAG, "MEDIA_INFO_BUFFERING_END");
}
}
public void onError(int what, int extra) {
Log.e(TAG, "onError " + what + " - " + extra + " [" + this.hashCode() + "] ");
if (what != 38 && what != -38 && extra != -38) {
onStateError();
if (isCurrentJcvd()) {
JCMediaManager.instance().releaseMediaPlayer();
}
}
}
public int widthRatio = 0;
public int heightRatio = 0;
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (currentScreen == SCREEN_WINDOW_FULLSCREEN || currentScreen == SCREEN_WINDOW_TINY) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
return;
}
if (widthRatio != 0 && heightRatio != 0) {
int specWidth = MeasureSpec.getSize(widthMeasureSpec);
int specHeight = (int) ((specWidth * (float) heightRatio) / widthRatio);
setMeasuredDimension(specWidth, specHeight);
int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(specWidth, MeasureSpec.EXACTLY);
int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(specHeight, MeasureSpec.EXACTLY);
getChildAt(0).measure(childWidthMeasureSpec, childHeightMeasureSpec);
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
public void onAutoCompletion() {
//加上这句,避免循环播放video的时候,内存不断飙升。
Runtime.getRuntime().gc();
Log.i(TAG, "onAutoCompletion " + " [" + this.hashCode() + "] ");
onEvent(JCUserAction.ON_AUTO_COMPLETE);
dismissVolumeDialog();
dismissProgressDialog();
dismissBrightnessDialog();
cancelProgressTimer();
onStateAutoComplete();
if (currentScreen == SCREEN_WINDOW_FULLSCREEN) {
backPress();
}
JCUtils.saveProgress(getContext(), url, 0);
}
public void onCompletion() {
Log.i(TAG, "onCompletion " + " [" + this.hashCode() + "] ");
//save position
if (currentState == CURRENT_STATE_PLAYING || currentState == CURRENT_STATE_PAUSE) {
int position = getCurrentPositionWhenPlaying();
// int duration = getDuration();
JCUtils.saveProgress(getContext(), url, position);
}
cancelProgressTimer();
onStateNormal();
// 清理缓存变量
textureViewContainer.removeView(JCMediaManager.textureView);
JCMediaManager.instance().currentVideoWidth = 0;
JCMediaManager.instance().currentVideoHeight = 0;
AudioManager mAudioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
mAudioManager.abandonAudioFocus(onAudioFocusChangeListener);
JCUtils.scanForActivity(getContext()).getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
clearFullscreenLayout();
JCUtils.getAppCompActivity(getContext()).setRequestedOrientation(NORMAL_ORIENTATION);
JCMediaManager.textureView = null;
JCMediaManager.savedSurfaceTexture = null;
}
public void release() {
if (url.equals(JCMediaManager.CURRENT_PLAYING_URL) &&
(System.currentTimeMillis() - CLICK_QUIT_FULLSCREEN_TIME) > FULL_SCREEN_NORMAL_DELAY) {
//在非全屏的情况下只能backPress()
if (JCVideoPlayerManager.getSecondFloor() != null &&
JCVideoPlayerManager.getSecondFloor().currentScreen == SCREEN_WINDOW_FULLSCREEN) {//点击全屏
} else if (JCVideoPlayerManager.getSecondFloor() == null && JCVideoPlayerManager.getFirstFloor() != null &&
JCVideoPlayerManager.getFirstFloor().currentScreen == SCREEN_WINDOW_FULLSCREEN) {//直接全屏
} else {
Log.d(TAG, "release [" + this.hashCode() + "]");
releaseAllVideos();
}
}
}
public static void releaseAllVideos() {
if ((System.currentTimeMillis() - CLICK_QUIT_FULLSCREEN_TIME) > FULL_SCREEN_NORMAL_DELAY) {
Log.d(TAG, "releaseAllVideos");
JCVideoPlayerManager.completeAll();
JCMediaManager.instance().releaseMediaPlayer();
}
}
public void initTextureView() {
removeTextureView();
JCMediaManager.textureView = new JCResizeTextureView(getContext());
JCMediaManager.textureView.setSurfaceTextureListener(JCMediaManager.instance());
}
public void addTextureView() {
Log.d(TAG, "addTextureView [" + this.hashCode() + "] ");
FrameLayout.LayoutParams layoutParams =
new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT,
Gravity.CENTER);
textureViewContainer.addView(JCMediaManager.textureView, layoutParams);
}
public void removeTextureView() {
JCMediaManager.savedSurfaceTexture = null;
if (JCMediaManager.textureView != null && JCMediaManager.textureView.getParent() != null) {
((ViewGroup) JCMediaManager.textureView.getParent()).removeView(JCMediaManager.textureView);
}
}
public void clearFullscreenLayout() {
ViewGroup vp = (ViewGroup) (JCUtils.scanForActivity(getContext()))//.getWindow().getDecorView();
.findViewById(Window.ID_ANDROID_CONTENT);
View oldF = vp.findViewById(FULLSCREEN_ID);
View oldT = vp.findViewById(TINY_ID);
if (oldF != null) {
vp.removeView(oldF);
}
if (oldT != null) {
vp.removeView(oldT);
}
showSupportActionBar(getContext());
}
public void clearFloatScreen() {
JCUtils.getAppCompActivity(getContext()).setRequestedOrientation(NORMAL_ORIENTATION);
showSupportActionBar(getContext());
JCVideoPlayer currJcvd = JCVideoPlayerManager.getCurrentJcvd();
currJcvd.textureViewContainer.removeView(JCMediaManager.textureView);
ViewGroup vp = (ViewGroup) (JCUtils.scanForActivity(getContext()))//.getWindow().getDecorView();
.findViewById(Window.ID_ANDROID_CONTENT);
vp.removeView(currJcvd);
JCVideoPlayerManager.setSecondFloor(null);
}
public void onVideoSizeChanged() {
Log.i(TAG, "onVideoSizeChanged " + " [" + this.hashCode() + "] ");
if (JCMediaManager.textureView != null) {
JCMediaManager.textureView.setVideoSize(JCMediaManager.instance().getVideoSize());
}
}
public void startProgressTimer() {
cancelProgressTimer();
UPDATE_PROGRESS_TIMER = new Timer();
mProgressTimerTask = new ProgressTimerTask();
UPDATE_PROGRESS_TIMER.schedule(mProgressTimerTask, 0, 300);
}
public void cancelProgressTimer() {
if (UPDATE_PROGRESS_TIMER != null) {
UPDATE_PROGRESS_TIMER.cancel();
}
if (mProgressTimerTask != null) {
mProgressTimerTask.cancel();
}
}
public class ProgressTimerTask extends TimerTask {
@Override
public void run() {
if (currentState == CURRENT_STATE_PLAYING || currentState == CURRENT_STATE_PAUSE || currentState == CURRENT_STATE_PLAYING_BUFFERING_START) {
// Log.v(TAG, "onProgressUpdate " + position + "/" + duration + " [" + this.hashCode() + "] ");
mHandler.post(new Runnable() {
@Override
public void run() {
int position = getCurrentPositionWhenPlaying();
int duration = getDuration();
int progress = position * 100 / (duration == 0 ? 1 : duration);
setProgressAndText(progress, position, duration);
}
});
}
}
}
public void setProgressAndText(int progress, int position, int duration) {
if (!mTouchingProgressBar) {
if (progress != 0) progressBar.setProgress(progress);
}
if (position != 0) currentTimeTextView.setText(JCUtils.stringForTime(position));
totalTimeTextView.setText(JCUtils.stringForTime(duration));
}
public void setBufferProgress(int bufferProgress) {
if (bufferProgress != 0) progressBar.setSecondaryProgress(bufferProgress);
}
public void resetProgressAndTime() {
progressBar.setProgress(0);
progressBar.setSecondaryProgress(0);
currentTimeTextView.setText(JCUtils.stringForTime(0));
totalTimeTextView.setText(JCUtils.stringForTime(0));
}
public int getCurrentPositionWhenPlaying() {
int position = 0;
if (JCMediaManager.instance().mediaPlayer == null)
return position;//这行代码不应该在这,如果代码和逻辑万无一失的话,心头之恨呐
if (currentState == CURRENT_STATE_PLAYING ||
currentState == CURRENT_STATE_PAUSE ||
currentState == CURRENT_STATE_PLAYING_BUFFERING_START) {
try {
position = JCMediaManager.instance().mediaPlayer.getCurrentPosition();
} catch (IllegalStateException e) {
e.printStackTrace();
return position;
}
}
return position;
}
public int getDuration() {
int duration = 0;
if (JCMediaManager.instance().mediaPlayer == null) return duration;
try {
duration = JCMediaManager.instance().mediaPlayer.getDuration();
} catch (IllegalStateException e) {
e.printStackTrace();
return duration;
}
return duration;
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
Log.i(TAG, "bottomProgress onStartTrackingTouch [" + this.hashCode() + "] ");
cancelProgressTimer();
ViewParent vpdown = getParent();
while (vpdown != null) {
vpdown.requestDisallowInterceptTouchEvent(true);
vpdown = vpdown.getParent();
}
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
Log.i(TAG, "bottomProgress onStopTrackingTouch [" + this.hashCode() + "] ");
onEvent(JCUserAction.ON_SEEK_POSITION);
startProgressTimer();
ViewParent vpup = getParent();
while (vpup != null) {
vpup.requestDisallowInterceptTouchEvent(false);
vpup = vpup.getParent();
}
if (currentState != CURRENT_STATE_PLAYING &&
currentState != CURRENT_STATE_PAUSE) return;
int time = seekBar.getProgress() * getDuration() / 100;
JCMediaManager.instance().mediaPlayer.seekTo(time);
Log.i(TAG, "seekTo " + time + " [" + this.hashCode() + "] ");
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
public void startWindowFullscreen() {
Log.i(TAG, "startWindowFullscreen " + " [" + this.hashCode() + "] ");
hideSupportActionBar(getContext());
JCUtils.getAppCompActivity(getContext()).setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
ViewGroup vp = (ViewGroup) (JCUtils.scanForActivity(getContext()))//.getWindow().getDecorView();
.findViewById(Window.ID_ANDROID_CONTENT);
View old = vp.findViewById(FULLSCREEN_ID);
if (old != null) {
vp.removeView(old);
}
// ((ViewGroup)JCMediaManager.textureView.getParent()).removeView(JCMediaManager.textureView);
textureViewContainer.removeView(JCMediaManager.textureView);
try {
Constructor<JCVideoPlayer> constructor = (Constructor<JCVideoPlayer>) JCVideoPlayer.this.getClass().getConstructor(Context.class);
JCVideoPlayer jcVideoPlayer = constructor.newInstance(getContext());
jcVideoPlayer.setId(FULLSCREEN_ID);
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
vp.addView(jcVideoPlayer, lp);
jcVideoPlayer.setUp(url, JCVideoPlayerStandard.SCREEN_WINDOW_FULLSCREEN, objects);
jcVideoPlayer.setState(currentState);
jcVideoPlayer.addTextureView();
JCVideoPlayerManager.setSecondFloor(jcVideoPlayer);
// final Animation ra = AnimationUtils.loadAnimation(getContext(), R.anim.start_fullscreen);
// jcVideoPlayer.setAnimation(ra);
CLICK_QUIT_FULLSCREEN_TIME = System.currentTimeMillis();
} catch (Exception e) {
e.printStackTrace();
}
}
public void startWindowTiny() {
Log.i(TAG, "startWindowTiny " + " [" + this.hashCode() + "] ");
onEvent(JCUserAction.ON_ENTER_TINYSCREEN);
if (currentState == CURRENT_STATE_NORMAL || currentState == CURRENT_STATE_ERROR) return;
ViewGroup vp = (ViewGroup) (JCUtils.scanForActivity(getContext()))//.getWindow().getDecorView();
.findViewById(Window.ID_ANDROID_CONTENT);
View old = vp.findViewById(TINY_ID);
if (old != null) {
vp.removeView(old);
}
textureViewContainer.removeView(JCMediaManager.textureView);
try {
Constructor<JCVideoPlayer> constructor = (Constructor<JCVideoPlayer>) JCVideoPlayer.this.getClass().getConstructor(Context.class);
JCVideoPlayer jcVideoPlayer = constructor.newInstance(getContext());
jcVideoPlayer.setId(TINY_ID);
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(400, 400);
lp.gravity = Gravity.RIGHT | Gravity.BOTTOM;
vp.addView(jcVideoPlayer, lp);
jcVideoPlayer.setUp(url, JCVideoPlayerStandard.SCREEN_WINDOW_TINY, objects);
jcVideoPlayer.setState(currentState);
jcVideoPlayer.addTextureView();
JCVideoPlayerManager.setSecondFloor(jcVideoPlayer);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void startFullscreen(Context context, Class _class, String url, Object... objects) {
hideSupportActionBar(context);
JCUtils.getAppCompActivity(context).setRequestedOrientation(FULLSCREEN_ORIENTATION);
ViewGroup vp = (ViewGroup) (JCUtils.scanForActivity(context))//.getWindow().getDecorView();
.findViewById(Window.ID_ANDROID_CONTENT);
View old = vp.findViewById(JCVideoPlayer.FULLSCREEN_ID);
if (old != null) {
vp.removeView(old);
}
try {
Constructor<JCVideoPlayer> constructor = _class.getConstructor(Context.class);
final JCVideoPlayer jcVideoPlayer = constructor.newInstance(context);
jcVideoPlayer.setId(JCVideoPlayer.FULLSCREEN_ID);
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
vp.addView(jcVideoPlayer, lp);
// final Animation ra = AnimationUtils.loadAnimation(context, R.anim.start_fullscreen);
// jcVideoPlayer.setAnimation(ra);
jcVideoPlayer.setUp(url, JCVideoPlayerStandard.SCREEN_WINDOW_FULLSCREEN, objects);
CLICK_QUIT_FULLSCREEN_TIME = System.currentTimeMillis();
jcVideoPlayer.startButton.performClick();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
//isCurrentJcvd and isCurrenPlayUrl should be two logic methods,isCurrentJcvd is for different jcvd with same
//url when fullscreen or tiny screen. isCurrenPlayUrl is to find where is myself when back from tiny screen.
//Sometimes they are overlap.
public boolean isCurrentJcvd() {//虽然看这个函数很不爽,但是干不掉
return JCVideoPlayerManager.getCurrentJcvd() != null
&& JCVideoPlayerManager.getCurrentJcvd() == this;
}
// public boolean isCurrenPlayingUrl() {
// return url.equals(JCMediaManager.CURRENT_PLAYING_URL);
// }
//退出全屏和小窗的方法
public void playOnThisJcvd() {
Log.i(TAG, "playOnThisJcvd " + " [" + this.hashCode() + "] ");
//1.清空全屏和小窗的jcvd
currentState = JCVideoPlayerManager.getSecondFloor().currentState;
clearFloatScreen();
//2.在本jcvd上播放
setState(currentState);
addTextureView();
}
public static boolean backPress() {
Log.i(TAG, "backPress");
if ((System.currentTimeMillis() - CLICK_QUIT_FULLSCREEN_TIME) < FULL_SCREEN_NORMAL_DELAY)
return false;
if (JCVideoPlayerManager.getSecondFloor() != null) {
CLICK_QUIT_FULLSCREEN_TIME = System.currentTimeMillis();
JCVideoPlayer jcVideoPlayer = JCVideoPlayerManager.getSecondFloor();
jcVideoPlayer.onEvent(jcVideoPlayer.currentScreen == JCVideoPlayerStandard.SCREEN_WINDOW_FULLSCREEN ?
JCUserAction.ON_QUIT_FULLSCREEN :
JCUserAction.ON_QUIT_TINYSCREEN);
JCVideoPlayerManager.getFirstFloor().playOnThisJcvd();
return true;
} else if (JCVideoPlayerManager.getFirstFloor() != null &&
(JCVideoPlayerManager.getFirstFloor().currentScreen == SCREEN_WINDOW_FULLSCREEN ||
JCVideoPlayerManager.getFirstFloor().currentScreen == SCREEN_WINDOW_TINY)) {//以前我总想把这两个判断写到一起,这分明是两个独立是逻辑
CLICK_QUIT_FULLSCREEN_TIME = System.currentTimeMillis();
//直接退出全屏和小窗
JCVideoPlayerManager.getCurrentJcvd().currentState = CURRENT_STATE_NORMAL;
JCVideoPlayerManager.getFirstFloor().clearFloatScreen();
JCMediaManager.instance().releaseMediaPlayer();
JCVideoPlayerManager.setFirstFloor(null);
return true;
}
return false;
}
public static void showSupportActionBar(Context context) {
if (ACTION_BAR_EXIST) {
ActionBar ab = JCUtils.getAppCompActivity(context).getSupportActionBar();
if (ab != null) {
ab.setShowHideAnimationEnabled(false);
ab.show();
}
}
if (TOOL_BAR_EXIST) {
JCUtils.getAppCompActivity(context).getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
}
public static void hideSupportActionBar(Context context) {
if (ACTION_BAR_EXIST) {
ActionBar ab = JCUtils.getAppCompActivity(context).getSupportActionBar();
if (ab != null) {
ab.setShowHideAnimationEnabled(false);
ab.hide();
}
}
if (TOOL_BAR_EXIST) {
JCUtils.getAppCompActivity(context).getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
}
public static long lastAutoFullscreenTime = 0;
//重力感应的时候调用的函数,
public void autoFullscreen(float x) {
if (isCurrentJcvd()
&& currentState == CURRENT_STATE_PLAYING
&& currentScreen != SCREEN_WINDOW_FULLSCREEN
&& currentScreen != SCREEN_WINDOW_TINY) {
if (x > 0) {
JCUtils.getAppCompActivity(getContext()).setRequestedOrientation(
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else {
JCUtils.getAppCompActivity(getContext()).setRequestedOrientation(
ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
}
onEvent(JCUserAction.ON_ENTER_FULLSCREEN);
startWindowFullscreen();
}
}
public void autoQuitFullscreen() {
if ((System.currentTimeMillis() - lastAutoFullscreenTime) > 2000
&& isCurrentJcvd()
&& currentState == CURRENT_STATE_PLAYING
&& currentScreen == SCREEN_WINDOW_FULLSCREEN) {
lastAutoFullscreenTime = System.currentTimeMillis();
backPress();
}
}
public static class JCAutoFullscreenListener implements SensorEventListener {
@Override
public void onSensorChanged(SensorEvent event) {//可以得到传感器实时测量出来的变化值
final float x = event.values[SensorManager.DATA_X];
float y = event.values[SensorManager.DATA_Y];
float z = event.values[SensorManager.DATA_Z];
//过滤掉用力过猛会有一个反向的大数值
if (((x > -15 && x < -10) || (x < 15 && x > 10)) && Math.abs(y) < 1.5) {
if ((System.currentTimeMillis() - lastAutoFullscreenTime) > 2000) {
if (JCVideoPlayerManager.getCurrentJcvd() != null) {
JCVideoPlayerManager.getCurrentJcvd().autoFullscreen(x);
}
lastAutoFullscreenTime = System.currentTimeMillis();
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
public static void clearSavedProgress(Context context, String url) {
JCUtils.clearSavedProgress(context, url);
}
public static void setJcUserAction(JCUserAction jcUserEvent) {
JC_USER_EVENT = jcUserEvent;
}
public void onEvent(int type) {
if (JC_USER_EVENT != null && isCurrentJcvd()) {
JC_USER_EVENT.onEvent(type, url, currentScreen, objects);
}
}
public static AudioManager.OnAudioFocusChangeListener onAudioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
@Override
public void onAudioFocusChange(int focusChange) {
switch (focusChange) {
case AudioManager.AUDIOFOCUS_GAIN:
break;
case AudioManager.AUDIOFOCUS_LOSS:
releaseAllVideos();
Log.d(TAG, "AUDIOFOCUS_LOSS [" + this.hashCode() + "]");
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
try {
if (JCMediaManager.instance().mediaPlayer != null &&
JCMediaManager.instance().mediaPlayer.isPlaying()) {
JCMediaManager.instance().mediaPlayer.pause();
}
} catch (IllegalStateException e) {
e.printStackTrace();
}
Log.d(TAG, "AUDIOFOCUS_LOSS_TRANSIENT [" + this.hashCode() + "]");
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
break;
}
}
};
//TODO 是否有用
public void onSeekComplete() {
}
public void showWifiDialog(int event) {
}
public void showProgressDialog(float deltaX,
String seekTime, int seekTimePosition,
String totalTime, int totalTimeDuration) {
}
public void dismissProgressDialog() {
}
public void showVolumeDialog(float deltaY, int volumePercent) {
}
public void dismissVolumeDialog() {
}
public void showBrightnessDialog(int brightnessPercent) {
}
public void dismissBrightnessDialog() {
}
}
| Wilshion/HeadlineNews | jcvideoplayer-lib/src/main/java/fm/jiecao/jcvideoplayer_lib/JCVideoPlayer.java | Java | apache-2.0 | 44,269 |
/* Generated by camel build tools - do NOT edit this file! */
package org.apache.camel.component.google.calendar;
import java.util.Map;
import org.apache.camel.CamelContext;
import org.apache.camel.spi.GeneratedPropertyConfigurer;
import org.apache.camel.spi.PropertyConfigurerGetter;
import org.apache.camel.util.CaseInsensitiveMap;
import org.apache.camel.support.component.PropertyConfigurerSupport;
/**
* Generated by camel build tools - do NOT edit this file!
*/
@SuppressWarnings("unchecked")
public class GoogleCalendarEndpointConfigurer extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter {
private static final Map<String, Object> ALL_OPTIONS;
static {
Map<String, Object> map = new CaseInsensitiveMap();
map.put("apiName", org.apache.camel.component.google.calendar.internal.GoogleCalendarApiName.class);
map.put("methodName", java.lang.String.class);
map.put("applicationName", java.lang.String.class);
map.put("clientId", java.lang.String.class);
map.put("emailAddress", java.lang.String.class);
map.put("inBody", java.lang.String.class);
map.put("p12FileName", java.lang.String.class);
map.put("scopes", java.lang.String.class);
map.put("user", java.lang.String.class);
map.put("bridgeErrorHandler", boolean.class);
map.put("sendEmptyMessageWhenIdle", boolean.class);
map.put("exceptionHandler", org.apache.camel.spi.ExceptionHandler.class);
map.put("exchangePattern", org.apache.camel.ExchangePattern.class);
map.put("pollStrategy", org.apache.camel.spi.PollingConsumerPollStrategy.class);
map.put("lazyStartProducer", boolean.class);
map.put("basicPropertyBinding", boolean.class);
map.put("synchronous", boolean.class);
map.put("backoffErrorThreshold", int.class);
map.put("backoffIdleThreshold", int.class);
map.put("backoffMultiplier", int.class);
map.put("delay", long.class);
map.put("greedy", boolean.class);
map.put("initialDelay", long.class);
map.put("repeatCount", long.class);
map.put("runLoggingLevel", org.apache.camel.LoggingLevel.class);
map.put("scheduledExecutorService", java.util.concurrent.ScheduledExecutorService.class);
map.put("scheduler", java.lang.Object.class);
map.put("schedulerProperties", java.util.Map.class);
map.put("startScheduler", boolean.class);
map.put("timeUnit", java.util.concurrent.TimeUnit.class);
map.put("useFixedDelay", boolean.class);
map.put("accessToken", java.lang.String.class);
map.put("clientSecret", java.lang.String.class);
map.put("refreshToken", java.lang.String.class);
map.put("calendarId", java.lang.String.class);
map.put("content", com.google.api.services.calendar.model.AclRule.class);
map.put("contentChannel", com.google.api.services.calendar.model.Channel.class);
map.put("destination", java.lang.String.class);
map.put("eventId", java.lang.String.class);
map.put("ruleId", java.lang.String.class);
map.put("setting", java.lang.String.class);
map.put("text", java.lang.String.class);
ALL_OPTIONS = map;
}
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
GoogleCalendarEndpoint target = (GoogleCalendarEndpoint) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "accesstoken":
case "accessToken": target.getConfiguration().setAccessToken(property(camelContext, java.lang.String.class, value)); return true;
case "applicationname":
case "applicationName": target.getConfiguration().setApplicationName(property(camelContext, java.lang.String.class, value)); return true;
case "backofferrorthreshold":
case "backoffErrorThreshold": target.setBackoffErrorThreshold(property(camelContext, int.class, value)); return true;
case "backoffidlethreshold":
case "backoffIdleThreshold": target.setBackoffIdleThreshold(property(camelContext, int.class, value)); return true;
case "backoffmultiplier":
case "backoffMultiplier": target.setBackoffMultiplier(property(camelContext, int.class, value)); return true;
case "basicpropertybinding":
case "basicPropertyBinding": target.setBasicPropertyBinding(property(camelContext, boolean.class, value)); return true;
case "bridgeerrorhandler":
case "bridgeErrorHandler": target.setBridgeErrorHandler(property(camelContext, boolean.class, value)); return true;
case "clientid":
case "clientId": target.getConfiguration().setClientId(property(camelContext, java.lang.String.class, value)); return true;
case "clientsecret":
case "clientSecret": target.getConfiguration().setClientSecret(property(camelContext, java.lang.String.class, value)); return true;
case "delay": target.setDelay(property(camelContext, long.class, value)); return true;
case "emailaddress":
case "emailAddress": target.getConfiguration().setEmailAddress(property(camelContext, java.lang.String.class, value)); return true;
case "exceptionhandler":
case "exceptionHandler": target.setExceptionHandler(property(camelContext, org.apache.camel.spi.ExceptionHandler.class, value)); return true;
case "exchangepattern":
case "exchangePattern": target.setExchangePattern(property(camelContext, org.apache.camel.ExchangePattern.class, value)); return true;
case "greedy": target.setGreedy(property(camelContext, boolean.class, value)); return true;
case "inbody":
case "inBody": target.setInBody(property(camelContext, java.lang.String.class, value)); return true;
case "initialdelay":
case "initialDelay": target.setInitialDelay(property(camelContext, long.class, value)); return true;
case "lazystartproducer":
case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true;
case "p12filename":
case "p12FileName": target.getConfiguration().setP12FileName(property(camelContext, java.lang.String.class, value)); return true;
case "pollstrategy":
case "pollStrategy": target.setPollStrategy(property(camelContext, org.apache.camel.spi.PollingConsumerPollStrategy.class, value)); return true;
case "refreshtoken":
case "refreshToken": target.getConfiguration().setRefreshToken(property(camelContext, java.lang.String.class, value)); return true;
case "repeatcount":
case "repeatCount": target.setRepeatCount(property(camelContext, long.class, value)); return true;
case "runlogginglevel":
case "runLoggingLevel": target.setRunLoggingLevel(property(camelContext, org.apache.camel.LoggingLevel.class, value)); return true;
case "scheduledexecutorservice":
case "scheduledExecutorService": target.setScheduledExecutorService(property(camelContext, java.util.concurrent.ScheduledExecutorService.class, value)); return true;
case "scheduler": target.setScheduler(property(camelContext, java.lang.Object.class, value)); return true;
case "schedulerproperties":
case "schedulerProperties": target.setSchedulerProperties(property(camelContext, java.util.Map.class, value)); return true;
case "scopes": target.getConfiguration().setScopes(property(camelContext, java.lang.String.class, value)); return true;
case "sendemptymessagewhenidle":
case "sendEmptyMessageWhenIdle": target.setSendEmptyMessageWhenIdle(property(camelContext, boolean.class, value)); return true;
case "startscheduler":
case "startScheduler": target.setStartScheduler(property(camelContext, boolean.class, value)); return true;
case "synchronous": target.setSynchronous(property(camelContext, boolean.class, value)); return true;
case "timeunit":
case "timeUnit": target.setTimeUnit(property(camelContext, java.util.concurrent.TimeUnit.class, value)); return true;
case "usefixeddelay":
case "useFixedDelay": target.setUseFixedDelay(property(camelContext, boolean.class, value)); return true;
case "user": target.getConfiguration().setUser(property(camelContext, java.lang.String.class, value)); return true;
default: return false;
}
}
@Override
public Map<String, Object> getAllOptions(Object target) {
return ALL_OPTIONS;
}
@Override
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
GoogleCalendarEndpoint target = (GoogleCalendarEndpoint) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "accesstoken":
case "accessToken": return target.getConfiguration().getAccessToken();
case "applicationname":
case "applicationName": return target.getConfiguration().getApplicationName();
case "backofferrorthreshold":
case "backoffErrorThreshold": return target.getBackoffErrorThreshold();
case "backoffidlethreshold":
case "backoffIdleThreshold": return target.getBackoffIdleThreshold();
case "backoffmultiplier":
case "backoffMultiplier": return target.getBackoffMultiplier();
case "basicpropertybinding":
case "basicPropertyBinding": return target.isBasicPropertyBinding();
case "bridgeerrorhandler":
case "bridgeErrorHandler": return target.isBridgeErrorHandler();
case "clientid":
case "clientId": return target.getConfiguration().getClientId();
case "clientsecret":
case "clientSecret": return target.getConfiguration().getClientSecret();
case "delay": return target.getDelay();
case "emailaddress":
case "emailAddress": return target.getConfiguration().getEmailAddress();
case "exceptionhandler":
case "exceptionHandler": return target.getExceptionHandler();
case "exchangepattern":
case "exchangePattern": return target.getExchangePattern();
case "greedy": return target.isGreedy();
case "inbody":
case "inBody": return target.getInBody();
case "initialdelay":
case "initialDelay": return target.getInitialDelay();
case "lazystartproducer":
case "lazyStartProducer": return target.isLazyStartProducer();
case "p12filename":
case "p12FileName": return target.getConfiguration().getP12FileName();
case "pollstrategy":
case "pollStrategy": return target.getPollStrategy();
case "refreshtoken":
case "refreshToken": return target.getConfiguration().getRefreshToken();
case "repeatcount":
case "repeatCount": return target.getRepeatCount();
case "runlogginglevel":
case "runLoggingLevel": return target.getRunLoggingLevel();
case "scheduledexecutorservice":
case "scheduledExecutorService": return target.getScheduledExecutorService();
case "scheduler": return target.getScheduler();
case "schedulerproperties":
case "schedulerProperties": return target.getSchedulerProperties();
case "scopes": return target.getConfiguration().getScopes();
case "sendemptymessagewhenidle":
case "sendEmptyMessageWhenIdle": return target.isSendEmptyMessageWhenIdle();
case "startscheduler":
case "startScheduler": return target.isStartScheduler();
case "synchronous": return target.isSynchronous();
case "timeunit":
case "timeUnit": return target.getTimeUnit();
case "usefixeddelay":
case "useFixedDelay": return target.isUseFixedDelay();
case "user": return target.getConfiguration().getUser();
default: return null;
}
}
}
| alvinkwekel/camel | components/camel-google-calendar/src/generated/java/org/apache/camel/component/google/calendar/GoogleCalendarEndpointConfigurer.java | Java | apache-2.0 | 11,968 |
/*
* Copyright 2017 Basis Technology Corp.
*
* 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.basistech.rosette.apimodel.batch;
import com.basistech.rosette.annotations.JacksonMixin;
import com.basistech.rosette.apimodel.Response;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
@Getter
@EqualsAndHashCode
@Builder
@JacksonMixin
public final class BatchResponse extends Response {
// batch id
private final String id;
// URL where the batch results will be stored
private final String batchOutputUrl;
// progress checking endpoint/url
private final String batchCheckProgressUrl;
}
| rosette-api/java | model/src/main/java/com/basistech/rosette/apimodel/batch/BatchResponse.java | Java | apache-2.0 | 1,143 |
/**
* @author Roman Lotnyk(romanlotnik@yandex.ru)
* @version 1
* @since 16.09.2017
*/
package ru.lotnyk.todo_list.repository; | RomanLotnyk/lotnyk | chapter_010/src/main/java/ru/lotnyk/todo_list/repository/package-info.java | Java | apache-2.0 | 129 |
# Copyright 2013, Big Switch Networks
#
# 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 logging
from django.core.exceptions import ValidationError # noqa
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import forms
from horizon import messages
from openstack_dashboard.dashboards.project.routers.extensions.routerrules\
import rulemanager
LOG = logging.getLogger(__name__)
class RuleCIDRField(forms.IPField):
"""Extends IPField to allow ('any','external') keywords and requires CIDR
"""
def __init__(self, *args, **kwargs):
kwargs['mask'] = True
super(RuleCIDRField, self).__init__(*args, **kwargs)
def validate(self, value):
keywords = ['any', 'external']
if value in keywords:
self.ip = value
else:
if '/' not in value:
raise ValidationError(_("Input must be in CIDR format"))
super(RuleCIDRField, self).validate(value)
class AddRouterRule(forms.SelfHandlingForm):
source = RuleCIDRField(label=_("Source CIDR"),
widget=forms.TextInput(), required=True)
destination = RuleCIDRField(label=_("Destination CIDR"),
widget=forms.TextInput(), required=True)
action = forms.ChoiceField(label=_("Action"), required=True)
nexthops = forms.MultiIPField(label=_("Optional: Next Hop "
"Addresses (comma delimited)"),
widget=forms.TextInput(), required=False)
router_id = forms.CharField(label=_("Router ID"),
widget=forms.TextInput(attrs={'readonly':
'readonly'}))
failure_url = 'horizon:project:routers:detail'
def __init__(self, request, *args, **kwargs):
super(AddRouterRule, self).__init__(request, *args, **kwargs)
self.fields['action'].choices = [('permit', _('Permit')),
('deny', _('Deny'))]
def handle(self, request, data, **kwargs):
try:
if 'rule_to_delete' in request.POST:
rulemanager.remove_rules(request,
[request.POST['rule_to_delete']],
router_id=data['router_id'])
except Exception:
exceptions.handle(request, _('Unable to delete router rule.'))
try:
if 'nexthops' not in data:
data['nexthops'] = ''
if data['source'] == '0.0.0.0/0':
data['source'] = 'any'
if data['destination'] == '0.0.0.0/0':
data['destination'] = 'any'
rule = {'action': data['action'],
'source': data['source'],
'destination': data['destination'],
'nexthops': data['nexthops'].split(',')}
rulemanager.add_rule(request,
router_id=data['router_id'],
newrule=rule)
msg = _('Router rule added')
LOG.debug(msg)
messages.success(request, msg)
return True
except Exception as e:
msg = _('Failed to add router rule %s') % e
LOG.info(msg)
messages.error(request, msg)
redirect = reverse(self.failure_url, args=[data['router_id']])
exceptions.handle(request, msg, redirect=redirect)
| spandanb/horizon | openstack_dashboard/dashboards/project/routers/extensions/routerrules/forms.py | Python | apache-2.0 | 4,117 |
class CreateProfessions < ActiveRecord::Migration
def change
create_table :professions do |t|
t.string :name
t.timestamps null: false
end
end
end
| Eptikar-IT-Solutions/openngo | db/migrate/20151126124435_create_professions.rb | Ruby | apache-2.0 | 171 |
/*
* Copyright (C) 2015 Archie L. Cobbs. All rights reserved.
*/
package org.jsimpledb.kv;
/**
* Thrown when an operation on a {@link KVTransaction} fails.
*/
@SuppressWarnings("serial")
public class KVTransactionException extends KVDatabaseException {
private final KVTransaction kvt;
public KVTransactionException(KVTransaction kvt) {
super(kvt.getKVDatabase());
this.kvt = kvt;
}
public KVTransactionException(KVTransaction kvt, Throwable cause) {
super(kvt.getKVDatabase(), cause);
this.kvt = kvt;
}
public KVTransactionException(KVTransaction kvt, String message) {
super(kvt.getKVDatabase(), message);
this.kvt = kvt;
}
public KVTransactionException(KVTransaction kvt, String message, Throwable cause) {
super(kvt.getKVDatabase(), message, cause);
this.kvt = kvt;
}
/**
* Get the {@link KVTransaction} that generated this exception.
*
* @return the associated transaction
*/
public KVTransaction getTransaction() {
return this.kvt;
}
}
| tempbottle/jsimpledb | src/java/org/jsimpledb/kv/KVTransactionException.java | Java | apache-2.0 | 1,096 |
package org.ovirt.engine.ui.uicommonweb.models.vms;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.queries.GetAllAuditLogsByVMNameParameters;
import org.ovirt.engine.core.common.queries.VdcQueryType;
public class UserPortalVmEventListModel extends VmEventListModel {
@Override
protected void Refresh() {
if (getEntity() == null) {
return;
}
VM vm = (VM) getEntity();
super.SyncSearch(VdcQueryType.GetAllAuditLogsByVMName, new GetAllAuditLogsByVMNameParameters(vm.getvm_name()));
}
@Override
protected void preSearchCalled(VM vm) {
// do nothing - only the webadmin sets the search string
}
}
| derekhiggins/ovirt-engine | frontend/webadmin/modules/uicommonweb/src/main/java/org/ovirt/engine/ui/uicommonweb/models/vms/UserPortalVmEventListModel.java | Java | apache-2.0 | 721 |
namespace JSLintNet.Models
{
/// <summary>
/// Contains the details of a JSLint error.
/// </summary>
public interface IJSLintError
{
/// <summary>
/// Gets the line (relative to 0) at which the lint was found.
/// </summary>
int Line { get; }
/// <summary>
/// Gets the character (relative to 0) at which the lint was found.
/// </summary>
int Character { get; }
/// <summary>
/// Gets the problem.
/// </summary>
string Reason { get; }
/// <summary>
/// Gets the text line in which the problem occurred.
/// </summary>
string Evidence { get; }
/// <summary>
/// Gets the error code.
/// </summary>
/// <value>
/// The error code.
/// </value>
string Code { get; }
}
}
| ajayanandgit/jslintnet | source/JSLintNet/Models/IJSLintError.cs | C# | apache-2.0 | 885 |
<?php
namespace ProjetoAngular\Entities;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class User extends Model implements AuthenticatableContract, AuthorizableContract, CanResetPasswordContract {
use Authenticatable,
Authorizable,
CanResetPassword;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['name', 'email', 'password'];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = ['password', 'remember_token'];
public function projects() {
return $this->belongsToMany(Project::class, 'project_members', 'member_id', 'project_id');
}
}
| ygc27/laravel-angular | app/Entities/User.php | PHP | apache-2.0 | 1,196 |
import calendar
c = calendar.TextCalendar(calendar.SUNDAY)
c.prmonth(2017, 7)
| jasonwee/asus-rt-n14uhp-mrtg | src/lesson_dates_and_times/calendar_textcalendar.py | Python | apache-2.0 | 79 |
/*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. 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://aws.amazon.com/apache2.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.
*/
package com.amazonaws.services.devicefarm.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
* <p>
* Represents the request to return information about the remote access session.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/ListRemoteAccessSessions"
* target="_top">AWS API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ListRemoteAccessSessionsRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The Amazon Resource Name (ARN) of the remote access session about which you are requesting information.
* </p>
*/
private String arn;
/**
* <p>
* An identifier that was returned from the previous call to this operation, which can be used to return the next
* set of items in the list.
* </p>
*/
private String nextToken;
/**
* <p>
* The Amazon Resource Name (ARN) of the remote access session about which you are requesting information.
* </p>
*
* @param arn
* The Amazon Resource Name (ARN) of the remote access session about which you are requesting information.
*/
public void setArn(String arn) {
this.arn = arn;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the remote access session about which you are requesting information.
* </p>
*
* @return The Amazon Resource Name (ARN) of the remote access session about which you are requesting information.
*/
public String getArn() {
return this.arn;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the remote access session about which you are requesting information.
* </p>
*
* @param arn
* The Amazon Resource Name (ARN) of the remote access session about which you are requesting information.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListRemoteAccessSessionsRequest withArn(String arn) {
setArn(arn);
return this;
}
/**
* <p>
* An identifier that was returned from the previous call to this operation, which can be used to return the next
* set of items in the list.
* </p>
*
* @param nextToken
* An identifier that was returned from the previous call to this operation, which can be used to return the
* next set of items in the list.
*/
public void setNextToken(String nextToken) {
this.nextToken = nextToken;
}
/**
* <p>
* An identifier that was returned from the previous call to this operation, which can be used to return the next
* set of items in the list.
* </p>
*
* @return An identifier that was returned from the previous call to this operation, which can be used to return the
* next set of items in the list.
*/
public String getNextToken() {
return this.nextToken;
}
/**
* <p>
* An identifier that was returned from the previous call to this operation, which can be used to return the next
* set of items in the list.
* </p>
*
* @param nextToken
* An identifier that was returned from the previous call to this operation, which can be used to return the
* next set of items in the list.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListRemoteAccessSessionsRequest withNextToken(String nextToken) {
setNextToken(nextToken);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getArn() != null)
sb.append("Arn: ").append(getArn()).append(",");
if (getNextToken() != null)
sb.append("NextToken: ").append(getNextToken());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof ListRemoteAccessSessionsRequest == false)
return false;
ListRemoteAccessSessionsRequest other = (ListRemoteAccessSessionsRequest) obj;
if (other.getArn() == null ^ this.getArn() == null)
return false;
if (other.getArn() != null && other.getArn().equals(this.getArn()) == false)
return false;
if (other.getNextToken() == null ^ this.getNextToken() == null)
return false;
if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getArn() == null) ? 0 : getArn().hashCode());
hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
return hashCode;
}
@Override
public ListRemoteAccessSessionsRequest clone() {
return (ListRemoteAccessSessionsRequest) super.clone();
}
}
| jentfoo/aws-sdk-java | aws-java-sdk-devicefarm/src/main/java/com/amazonaws/services/devicefarm/model/ListRemoteAccessSessionsRequest.java | Java | apache-2.0 | 6,247 |
#include <halley/support/exception.h>
#include "halley/tools/cli_tool.h"
#include "halley/tools/codegen/codegen_tool.h"
#include "halley/tools/distance_field/distance_field_tool.h"
#include "halley/tools/make_font/make_font_tool.h"
#include "halley/tools/assets/import_tool.h"
#include "halley/tools/packer/asset_packer_tool.h"
#include "halley/support/logger.h"
#include "halley/core/game/halley_statics.h"
#include "halley/tools/vs_project/vs_project_tool.h"
#include "halley/tools/packer/asset_pack_inspector.h"
#include "halley/tools/runner/runner_tool.h"
using namespace Halley;
CommandLineTools::CommandLineTools()
{
factories["import"] = []() { return std::make_unique<ImportTool>(); };
factories["codegen"] = []() { return std::make_unique<CodegenTool>(); };
factories["distField"] = []() { return std::make_unique<DistanceFieldTool>(); };
factories["makeFont"] = []() { return std::make_unique<MakeFontTool>(); };
factories["pack"] = []() { return std::make_unique<AssetPackerTool>(); };
factories["pack-inspector"] = []() { return std::make_unique<AssetPackInspectorTool>(); };
factories["vs_project"] = []() { return std::make_unique<VSProjectTool>(); };
factories["run"] = []() { return std::make_unique<RunnerTool>(); };
}
Vector<std::string> CommandLineTools::getToolNames()
{
auto result = Vector<std::string>();
for (auto& kv : factories) {
result.push_back(kv.first);
}
return result;
}
std::unique_ptr<CommandLineTool> CommandLineTools::getTool(std::string name)
{
auto result = factories.find(name);
if (result != factories.end()) {
return result->second();
} else {
throw Exception("Unknown tool name", HalleyExceptions::Tools);
}
}
CommandLineTool::~CommandLineTool()
{
}
int CommandLineTool::runRaw(int argc, char** argv)
{
Vector<std::string> args;
for (int i = 2; i < argc; i++) {
String arg = argv[i];
if (!arg.startsWith("--")) {
args.push_back(arg.cppStr());
}
}
statics = std::make_unique<HalleyStatics>();
statics->resume(nullptr, std::thread::hardware_concurrency());
StdOutSink logSink(true);
Logger::addSink(logSink);
env.parseProgramPath(argv[0]);
return run(args);
}
int CommandLineTool::run(Vector<std::string> args)
{
throw Exception("Tool's run() method not implemented", HalleyExceptions::Tools);
}
| amzeratul/halley | src/tools/tools/src/tool/cli_tool.cpp | C++ | apache-2.0 | 2,287 |
/*******************************************************************************
* Copyright (c) 2015-2018 Skymind, Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://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.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
package org.deeplearning4j.clustering.util;
import org.apache.commons.math3.linear.CholeskyDecomposition;
import org.apache.commons.math3.linear.NonSquareMatrixException;
import org.apache.commons.math3.linear.RealMatrix;
import org.apache.commons.math3.random.RandomGenerator;
import org.apache.commons.math3.util.FastMath;
import org.nd4j.linalg.primitives.Counter;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Set;
/**
* This is a math utils class.
*
* @author Adam Gibson
*
*/
public class MathUtils {
/** The natural logarithm of 2. */
public static double log2 = Math.log(2);
/**
* Normalize a value
* (val - min) / (max - min)
* @param val value to normalize
* @param max max value
* @param min min value
* @return the normalized value
*/
public static double normalize(double val, double min, double max) {
if (max < min)
throw new IllegalArgumentException("Max must be greater than min");
return (val - min) / (max - min);
}
/**
* Clamps the value to a discrete value
* @param value the value to clamp
* @param min min for the probability distribution
* @param max max for the probability distribution
* @return the discrete value
*/
public static int clamp(int value, int min, int max) {
if (value < min)
value = min;
if (value > max)
value = max;
return value;
}
/**
* Discretize the given value
* @param value the value to discretize
* @param min the min of the distribution
* @param max the max of the distribution
* @param binCount the number of bins
* @return the discretized value
*/
public static int discretize(double value, double min, double max, int binCount) {
int discreteValue = (int) (binCount * normalize(value, min, max));
return clamp(discreteValue, 0, binCount - 1);
}
/**
* See: https://stackoverflow.com/questions/466204/rounding-off-to-nearest-power-of-2
* @param v the number to getFromOrigin the next power of 2 for
* @return the next power of 2 for the passed in value
*/
public static long nextPowOf2(long v) {
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;
return v;
}
/**
* Generates a binomial distributed number using
* the given rng
* @param rng
* @param n
* @param p
* @return
*/
public static int binomial(RandomGenerator rng, int n, double p) {
if ((p < 0) || (p > 1)) {
return 0;
}
int c = 0;
for (int i = 0; i < n; i++) {
if (rng.nextDouble() < p) {
c++;
}
}
return c;
}
/**
* Generate a uniform random number from the given rng
* @param rng the rng to use
* @param min the min num
* @param max the max num
* @return a number uniformly distributed between min and max
*/
public static double uniform(Random rng, double min, double max) {
return rng.nextDouble() * (max - min) + min;
}
/**
* Returns the correlation coefficient of two double vectors.
*
* @param residuals residuals
* @param targetAttribute target attribute vector
*
* @return the correlation coefficient or r
*/
public static double correlation(double[] residuals, double targetAttribute[]) {
double[] predictedValues = new double[residuals.length];
for (int i = 0; i < predictedValues.length; i++) {
predictedValues[i] = targetAttribute[i] - residuals[i];
}
double ssErr = ssError(predictedValues, targetAttribute);
double total = ssTotal(residuals, targetAttribute);
return 1 - (ssErr / total);
}//end correlation
/**
* 1 / 1 + exp(-x)
* @param x
* @return
*/
public static double sigmoid(double x) {
return 1.0 / (1.0 + FastMath.exp(-x));
}
/**
* How much of the variance is explained by the regression
* @param residuals error
* @param targetAttribute data for target attribute
* @return the sum squares of regression
*/
public static double ssReg(double[] residuals, double[] targetAttribute) {
double mean = sum(targetAttribute) / targetAttribute.length;
double ret = 0;
for (int i = 0; i < residuals.length; i++) {
ret += Math.pow(residuals[i] - mean, 2);
}
return ret;
}
/**
* How much of the variance is NOT explained by the regression
* @param predictedValues predicted values
* @param targetAttribute data for target attribute
* @return the sum squares of regression
*/
public static double ssError(double[] predictedValues, double[] targetAttribute) {
double ret = 0;
for (int i = 0; i < predictedValues.length; i++) {
ret += Math.pow(targetAttribute[i] - predictedValues[i], 2);
}
return ret;
}
/**
* Calculate string similarity with tfidf weights relative to each character
* frequency and how many times a character appears in a given string
* @param strings the strings to calculate similarity for
* @return the cosine similarity between the strings
*/
public static double stringSimilarity(String... strings) {
if (strings == null)
return 0;
Counter<String> counter = new Counter<>();
Counter<String> counter2 = new Counter<>();
for (int i = 0; i < strings[0].length(); i++)
counter.incrementCount(String.valueOf(strings[0].charAt(i)), 1.0f);
for (int i = 0; i < strings[1].length(); i++)
counter2.incrementCount(String.valueOf(strings[1].charAt(i)), 1.0f);
Set<String> v1 = counter.keySet();
Set<String> v2 = counter2.keySet();
Set<String> both = SetUtils.intersection(v1, v2);
double sclar = 0, norm1 = 0, norm2 = 0;
for (String k : both)
sclar += counter.getCount(k) * counter2.getCount(k);
for (String k : v1)
norm1 += counter.getCount(k) * counter.getCount(k);
for (String k : v2)
norm2 += counter2.getCount(k) * counter2.getCount(k);
return sclar / Math.sqrt(norm1 * norm2);
}
/**
* Returns the vector length (sqrt(sum(x_i))
* @param vector the vector to return the vector length for
* @return the vector length of the passed in array
*/
public static double vectorLength(double[] vector) {
double ret = 0;
if (vector == null)
return ret;
else {
for (int i = 0; i < vector.length; i++) {
ret += Math.pow(vector[i], 2);
}
}
return ret;
}
/**
* Inverse document frequency: the total docs divided by the number of times the word
* appeared in a document
* @param totalDocs the total documents for the data applyTransformToDestination
* @param numTimesWordAppearedInADocument the number of times the word occurred in a document
* @return log(10) (totalDocs/numTImesWordAppearedInADocument)
*/
public static double idf(double totalDocs, double numTimesWordAppearedInADocument) {
//return totalDocs > 0 ? Math.log10(totalDocs/numTimesWordAppearedInADocument) : 0;
if (totalDocs == 0)
return 0;
double idf = Math.log10(totalDocs / numTimesWordAppearedInADocument);
return idf;
}
/**
* Term frequency: 1+ log10(count)
* @param count the count of a word or character in a given string or document
* @return 1+ log(10) count
*/
public static double tf(int count, int documentLength) {
//return count > 0 ? 1 + Math.log10(count) : 0
double tf = ((double) count / documentLength);
return tf;
}
/**
* Return td * idf
* @param tf the term frequency (assumed calculated)
* @param idf inverse document frequency (assumed calculated)
* @return td * idf
*/
public static double tfidf(double tf, double idf) {
// System.out.println("TF-IDF Value: " + (tf * idf));
return tf * idf;
}
private static int charForLetter(char c) {
char[] chars = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
't', 'u', 'v', 'w', 'x', 'y', 'z'};
for (int i = 0; i < chars.length; i++)
if (chars[i] == c)
return i;
return -1;
}
/**
* Total variance in target attribute
* @param residuals error
* @param targetAttribute data for target attribute
* @return Total variance in target attribute
*/
public static double ssTotal(double[] residuals, double[] targetAttribute) {
return ssReg(residuals, targetAttribute) + ssError(residuals, targetAttribute);
}
/**
* This returns the sum of the given array.
* @param nums the array of numbers to sum
* @return the sum of the given array
*/
public static double sum(double[] nums) {
double ret = 0;
for (double d : nums)
ret += d;
return ret;
}//end sum
/**
* This will merge the coordinates of the given coordinate system.
* @param x the x coordinates
* @param y the y coordinates
* @return a vector such that each (x,y) pair is at ret[i],ret[i+1]
*/
public static double[] mergeCoords(double[] x, double[] y) {
if (x.length != y.length)
throw new IllegalArgumentException(
"Sample sizes must be the same for each data applyTransformToDestination.");
double[] ret = new double[x.length + y.length];
for (int i = 0; i < x.length; i++) {
ret[i] = x[i];
ret[i + 1] = y[i];
}
return ret;
}//end mergeCoords
/**
* This will merge the coordinates of the given coordinate system.
* @param x the x coordinates
* @param y the y coordinates
* @return a vector such that each (x,y) pair is at ret[i],ret[i+1]
*/
public static List<Double> mergeCoords(List<Double> x, List<Double> y) {
if (x.size() != y.size())
throw new IllegalArgumentException(
"Sample sizes must be the same for each data applyTransformToDestination.");
List<Double> ret = new ArrayList<>();
for (int i = 0; i < x.size(); i++) {
ret.add(x.get(i));
ret.add(y.get(i));
}
return ret;
}//end mergeCoords
/**
* This returns the minimized loss values for a given vector.
* It is assumed that the x, y pairs are at
* vector[i], vector[i+1]
* @param vector the vector of numbers to getFromOrigin the weights for
* @return a double array with w_0 and w_1 are the associated indices.
*/
public static double[] weightsFor(List<Double> vector) {
/* split coordinate system */
List<double[]> coords = coordSplit(vector);
/* x vals */
double[] x = coords.get(0);
/* y vals */
double[] y = coords.get(1);
double meanX = sum(x) / x.length;
double meanY = sum(y) / y.length;
double sumOfMeanDifferences = sumOfMeanDifferences(x, y);
double xDifferenceOfMean = sumOfMeanDifferencesOnePoint(x);
double w_1 = sumOfMeanDifferences / xDifferenceOfMean;
double w_0 = meanY - (w_1) * meanX;
//double w_1=(n*sumOfProducts(x,y) - sum(x) * sum(y))/(n*sumOfSquares(x) - Math.pow(sum(x),2));
// double w_0=(sum(y) - (w_1 * sum(x)))/n;
double[] ret = new double[vector.size()];
ret[0] = w_0;
ret[1] = w_1;
return ret;
}//end weightsFor
/**
* This will return the squared loss of the given
* points
* @param x the x coordinates to use
* @param y the y coordinates to use
* @param w_0 the first weight
*
* @param w_1 the second weight
* @return the squared loss of the given points
*/
public static double squaredLoss(double[] x, double[] y, double w_0, double w_1) {
double sum = 0;
for (int j = 0; j < x.length; j++) {
sum += Math.pow((y[j] - (w_1 * x[j] + w_0)), 2);
}
return sum;
}//end squaredLoss
public static double w_1(double[] x, double[] y, int n) {
return (n * sumOfProducts(x, y) - sum(x) * sum(y)) / (n * sumOfSquares(x) - Math.pow(sum(x), 2));
}
public static double w_0(double[] x, double[] y, int n) {
double weight1 = w_1(x, y, n);
return (sum(y) - (weight1 * sum(x))) / n;
}
/**
* This returns the minimized loss values for a given vector.
* It is assumed that the x, y pairs are at
* vector[i], vector[i+1]
* @param vector the vector of numbers to getFromOrigin the weights for
* @return a double array with w_0 and w_1 are the associated indices.
*/
public static double[] weightsFor(double[] vector) {
/* split coordinate system */
List<double[]> coords = coordSplit(vector);
/* x vals */
double[] x = coords.get(0);
/* y vals */
double[] y = coords.get(1);
double meanX = sum(x) / x.length;
double meanY = sum(y) / y.length;
double sumOfMeanDifferences = sumOfMeanDifferences(x, y);
double xDifferenceOfMean = sumOfMeanDifferencesOnePoint(x);
double w_1 = sumOfMeanDifferences / xDifferenceOfMean;
double w_0 = meanY - (w_1) * meanX;
double[] ret = new double[vector.length];
ret[0] = w_0;
ret[1] = w_1;
return ret;
}//end weightsFor
public static double errorFor(double actual, double prediction) {
return actual - prediction;
}
/**
* Used for calculating top part of simple regression for
* beta 1
* @param vector the x coordinates
* @param vector2 the y coordinates
* @return the sum of mean differences for the input vectors
*/
public static double sumOfMeanDifferences(double[] vector, double[] vector2) {
double mean = sum(vector) / vector.length;
double mean2 = sum(vector2) / vector2.length;
double ret = 0;
for (int i = 0; i < vector.length; i++) {
double vec1Diff = vector[i] - mean;
double vec2Diff = vector2[i] - mean2;
ret += vec1Diff * vec2Diff;
}
return ret;
}//end sumOfMeanDifferences
/**
* Used for calculating top part of simple regression for
* beta 1
* @param vector the x coordinates
* @return the sum of mean differences for the input vectors
*/
public static double sumOfMeanDifferencesOnePoint(double[] vector) {
double mean = sum(vector) / vector.length;
double ret = 0;
for (int i = 0; i < vector.length; i++) {
double vec1Diff = Math.pow(vector[i] - mean, 2);
ret += vec1Diff;
}
return ret;
}//end sumOfMeanDifferences
public static double variance(double[] vector) {
return sumOfMeanDifferencesOnePoint(vector) / vector.length;
}
/**
* This returns the product of all numbers in the given array.
* @param nums the numbers to multiply over
* @return the product of all numbers in the array, or 0
* if the length is or nums i null
*/
public static double times(double[] nums) {
if (nums == null || nums.length == 0)
return 0;
double ret = 1;
for (int i = 0; i < nums.length; i++)
ret *= nums[i];
return ret;
}//end times
/**
* This returns the sum of products for the given
* numbers.
* @param nums the sum of products for the give numbers
* @return the sum of products for the given numbers
*/
public static double sumOfProducts(double[]... nums) {
if (nums == null || nums.length < 1)
return 0;
double sum = 0;
for (int i = 0; i < nums.length; i++) {
/* The ith column for all of the rows */
double[] column = column(i, nums);
sum += times(column);
}
return sum;
}//end sumOfProducts
/**
* This returns the given column over an n arrays
* @param column the column to getFromOrigin values for
* @param nums the arrays to extract values from
* @return a double array containing all of the numbers in that column
* for all of the arrays.
* @throws IllegalArgumentException if the index is < 0
*/
private static double[] column(int column, double[]... nums) throws IllegalArgumentException {
double[] ret = new double[nums.length];
for (int i = 0; i < nums.length; i++) {
double[] curr = nums[i];
ret[i] = curr[column];
}
return ret;
}//end column
/**
* This returns the coordinate split in a list of coordinates
* such that the values for ret[0] are the x values
* and ret[1] are the y values
* @param vector the vector to split with x and y values/
* @return a coordinate split for the given vector of values.
* if null, is passed in null is returned
*/
public static List<double[]> coordSplit(double[] vector) {
if (vector == null)
return null;
List<double[]> ret = new ArrayList<>();
/* x coordinates */
double[] xVals = new double[vector.length / 2];
/* y coordinates */
double[] yVals = new double[vector.length / 2];
/* current points */
int xTracker = 0;
int yTracker = 0;
for (int i = 0; i < vector.length; i++) {
//even value, x coordinate
if (i % 2 == 0)
xVals[xTracker++] = vector[i];
//y coordinate
else
yVals[yTracker++] = vector[i];
}
ret.add(xVals);
ret.add(yVals);
return ret;
}//end coordSplit
/**
* This returns the coordinate split in a list of coordinates
* such that the values for ret[0] are the x values
* and ret[1] are the y values
* @param vector the vector to split with x and y values
* Note that the list will be more stable due to the size operator.
* The array version will have extraneous values if not monitored
* properly.
* @return a coordinate split for the given vector of values.
* if null, is passed in null is returned
*/
public static List<double[]> coordSplit(List<Double> vector) {
if (vector == null)
return null;
List<double[]> ret = new ArrayList<>();
/* x coordinates */
double[] xVals = new double[vector.size() / 2];
/* y coordinates */
double[] yVals = new double[vector.size() / 2];
/* current points */
int xTracker = 0;
int yTracker = 0;
for (int i = 0; i < vector.size(); i++) {
//even value, x coordinate
if (i % 2 == 0)
xVals[xTracker++] = vector.get(i);
//y coordinate
else
yVals[yTracker++] = vector.get(i);
}
ret.add(xVals);
ret.add(yVals);
return ret;
}//end coordSplit
/**
* This returns the x values of the given vector.
* These are assumed to be the even values of the vector.
* @param vector the vector to getFromOrigin the values for
* @return the x values of the given vector
*/
public static double[] xVals(double[] vector) {
if (vector == null)
return null;
double[] x = new double[vector.length / 2];
int count = 0;
for (int i = 0; i < vector.length; i++) {
if (i % 2 != 0)
x[count++] = vector[i];
}
return x;
}//end xVals
/**
* This returns the odd indexed values for the given vector
* @param vector the odd indexed values of rht egiven vector
* @return the y values of the given vector
*/
public static double[] yVals(double[] vector) {
double[] y = new double[vector.length / 2];
int count = 0;
for (int i = 0; i < vector.length; i++) {
if (i % 2 == 0)
y[count++] = vector[i];
}
return y;
}//end yVals
/**
* This returns the sum of squares for the given vector.
*
* @param vector the vector to obtain the sum of squares for
* @return the sum of squares for this vector
*/
public static double sumOfSquares(double[] vector) {
double ret = 0;
for (double d : vector)
ret += Math.pow(d, 2);
return ret;
}
/**
* This returns the determination coefficient of two vectors given a length
* @param y1 the first vector
* @param y2 the second vector
* @param n the length of both vectors
* @return the determination coefficient or r^2
*/
public static double determinationCoefficient(double[] y1, double[] y2, int n) {
return Math.pow(correlation(y1, y2), 2);
}
/**
* Returns the logarithm of a for base 2.
*
* @param a a double
* @return the logarithm for base 2
*/
public static double log2(double a) {
if (a == 0)
return 0.0;
return Math.log(a) / log2;
}
/**
* This returns the slope of the given points.
* @param x1 the first x to use
* @param x2 the end x to use
* @param y1 the begin y to use
* @param y2 the end y to use
* @return the slope of the given points
*/
public double slope(double x1, double x2, double y1, double y2) {
return (y2 - y1) / (x2 - x1);
}//end slope
/**
* This returns the root mean squared error of two data sets
* @param real the real values
* @param predicted the predicted values
* @return the root means squared error for two data sets
*/
public static double rootMeansSquaredError(double[] real, double[] predicted) {
double ret = 0.0;
for (int i = 0; i < real.length; i++) {
ret += Math.pow((real[i] - predicted[i]), 2);
}
return Math.sqrt(ret / real.length);
}//end rootMeansSquaredError
/**
* This returns the entropy (information gain, or uncertainty of a random variable).
* @param vector the vector of values to getFromOrigin the entropy for
* @return the entropy of the given vector
*/
public static double entropy(double[] vector) {
if (vector == null || vector.length < 1)
return 0;
else {
double ret = 0;
for (double d : vector)
ret += d * Math.log(d);
return ret;
}
}//end entropy
/**
* This returns the kronecker delta of two doubles.
* @param i the first number to compare
* @param j the second number to compare
* @return 1 if they are equal, 0 otherwise
*/
public static int kroneckerDelta(double i, double j) {
return (i == j) ? 1 : 0;
}
/**
* This calculates the adjusted r^2 including degrees of freedom.
* Also known as calculating "strength" of a regression
* @param rSquared the r squared value to calculate
* @param numRegressors number of variables
* @param numDataPoints size of the data applyTransformToDestination
* @return an adjusted r^2 for degrees of freedom
*/
public static double adjustedrSquared(double rSquared, int numRegressors, int numDataPoints) {
double divide = (numDataPoints - 1.0) / (numDataPoints - numRegressors - 1.0);
double rSquaredDiff = 1 - rSquared;
return 1 - (rSquaredDiff * divide);
}
public static double[] normalizeToOne(double[] doubles) {
normalize(doubles, sum(doubles));
return doubles;
}
public static double min(double[] doubles) {
double ret = doubles[0];
for (double d : doubles)
if (d < ret)
ret = d;
return ret;
}
public static double max(double[] doubles) {
double ret = doubles[0];
for (double d : doubles)
if (d > ret)
ret = d;
return ret;
}
/**
* Normalizes the doubles in the array using the given value.
*
* @param doubles the array of double
* @param sum the value by which the doubles are to be normalized
* @exception IllegalArgumentException if sum is zero or NaN
*/
public static void normalize(double[] doubles, double sum) {
if (Double.isNaN(sum)) {
throw new IllegalArgumentException("Can't normalize array. Sum is NaN.");
}
if (sum == 0) {
// Maybe this should just be a return.
throw new IllegalArgumentException("Can't normalize array. Sum is zero.");
}
for (int i = 0; i < doubles.length; i++) {
doubles[i] /= sum;
}
}//end normalize
/**
* Converts an array containing the natural logarithms of
* probabilities stored in a vector back into probabilities.
* The probabilities are assumed to sum to one.
*
* @param a an array holding the natural logarithms of the probabilities
* @return the converted array
*/
public static double[] logs2probs(double[] a) {
double max = a[maxIndex(a)];
double sum = 0.0;
double[] result = new double[a.length];
for (int i = 0; i < a.length; i++) {
result[i] = Math.exp(a[i] - max);
sum += result[i];
}
normalize(result, sum);
return result;
}//end logs2probs
/**
* This returns the entropy for a given vector of probabilities.
* @param probabilities the probabilities to getFromOrigin the entropy for
* @return the entropy of the given probabilities.
*/
public static double information(double[] probabilities) {
double total = 0.0;
for (double d : probabilities) {
total += (-1.0 * log2(d) * d);
}
return total;
}//end information
/**
*
*
* Returns index of maximum element in a given
* array of doubles. First maximum is returned.
*
* @param doubles the array of doubles
* @return the index of the maximum element
*/
public static /*@pure@*/ int maxIndex(double[] doubles) {
double maximum = 0;
int maxIndex = 0;
for (int i = 0; i < doubles.length; i++) {
if ((i == 0) || (doubles[i] > maximum)) {
maxIndex = i;
maximum = doubles[i];
}
}
return maxIndex;
}//end maxIndex
/**
* This will return the factorial of the given number n.
* @param n the number to getFromOrigin the factorial for
* @return the factorial for this number
*/
public static double factorial(double n) {
if (n == 1 || n == 0)
return 1;
for (double i = n; i > 0; i--, n *= (i > 0 ? i : 1)) {
}
return n;
}//end factorial
/** The small deviation allowed in double comparisons. */
public static double SMALL = 1e-6;
/**
* Returns the log-odds for a given probability.
*
* @param prob the probability
*
* @return the log-odds after the probability has been mapped to
* [Utils.SMALL, 1-Utils.SMALL]
*/
public static /*@pure@*/ double probToLogOdds(double prob) {
if (gr(prob, 1) || (sm(prob, 0))) {
throw new IllegalArgumentException("probToLogOdds: probability must " + "be in [0,1] " + prob);
}
double p = SMALL + (1.0 - 2 * SMALL) * prob;
return Math.log(p / (1 - p));
}
/**
* Rounds a double to the next nearest integer value. The JDK version
* of it doesn't work properly.
*
* @param value the double value
* @return the resulting integer value
*/
public static /*@pure@*/ int round(double value) {
return value > 0 ? (int) (value + 0.5) : -(int) (Math.abs(value) + 0.5);
}//end round
/**
* This returns the permutation of n choose r.
* @param n the n to choose
* @param r the number of elements to choose
* @return the permutation of these numbers
*/
public static double permutation(double n, double r) {
double nFac = MathUtils.factorial(n);
double nMinusRFac = MathUtils.factorial((n - r));
return nFac / nMinusRFac;
}//end permutation
/**
* This returns the combination of n choose r
* @param n the number of elements overall
* @param r the number of elements to choose
* @return the amount of possible combinations for this applyTransformToDestination of elements
*/
public static double combination(double n, double r) {
double nFac = MathUtils.factorial(n);
double rFac = MathUtils.factorial(r);
double nMinusRFac = MathUtils.factorial((n - r));
return nFac / (rFac * nMinusRFac);
}//end combination
/**
* sqrt(a^2 + b^2) without under/overflow.
*/
public static double hypotenuse(double a, double b) {
double r;
if (Math.abs(a) > Math.abs(b)) {
r = b / a;
r = Math.abs(a) * Math.sqrt(1 + r * r);
} else if (b != 0) {
r = a / b;
r = Math.abs(b) * Math.sqrt(1 + r * r);
} else {
r = 0.0;
}
return r;
}//end hypotenuse
/**
* Rounds a double to the next nearest integer value in a probabilistic
* fashion (e.g. 0.8 has a 20% chance of being rounded down to 0 and a
* 80% chance of being rounded up to 1). In the limit, the average of
* the rounded numbers generated by this procedure should converge to
* the original double.
*
* @param value the double value
* @param rand the random number generator
* @return the resulting integer value
*/
public static int probRound(double value, Random rand) {
if (value >= 0) {
double lower = Math.floor(value);
double prob = value - lower;
if (rand.nextDouble() < prob) {
return (int) lower + 1;
} else {
return (int) lower;
}
} else {
double lower = Math.floor(Math.abs(value));
double prob = Math.abs(value) - lower;
if (rand.nextDouble() < prob) {
return -((int) lower + 1);
} else {
return -(int) lower;
}
}
}//end probRound
/**
* Rounds a double to the given number of decimal places.
*
* @param value the double value
* @param afterDecimalPoint the number of digits after the decimal point
* @return the double rounded to the given precision
*/
public static /*@pure@*/ double roundDouble(double value, int afterDecimalPoint) {
double mask = Math.pow(10.0, (double) afterDecimalPoint);
return (double) (Math.round(value * mask)) / mask;
}//end roundDouble
/**
* Rounds a double to the given number of decimal places.
*
* @param value the double value
* @param afterDecimalPoint the number of digits after the decimal point
* @return the double rounded to the given precision
*/
public static /*@pure@*/ float roundFloat(float value, int afterDecimalPoint) {
float mask = (float) Math.pow(10, (float) afterDecimalPoint);
return (float) (Math.round(value * mask)) / mask;
}//end roundDouble
/**
* This will return the bernoulli trial for the given event.
* A bernoulli trial is a mechanism for detecting the probability
* of a given event occurring k times in n independent trials
* @param n the number of trials
* @param k the number of times the target event occurs
* @param successProb the probability of the event happening
* @return the probability of the given event occurring k times.
*/
public static double bernoullis(double n, double k, double successProb) {
double combo = MathUtils.combination(n, k);
double q = 1 - successProb;
return combo * Math.pow(successProb, k) * Math.pow(q, n - k);
}//end bernoullis
/**
* Tests if a is smaller than b.
*
* @param a a double
* @param b a double
*/
public static /*@pure@*/ boolean sm(double a, double b) {
return (b - a > SMALL);
}
/**
* Tests if a is greater than b.
*
* @param a a double
* @param b a double
*/
public static /*@pure@*/ boolean gr(double a, double b) {
return (a - b > SMALL);
}
/**
* This will take a given string and separator and convert it to an equivalent
* double array.
* @param data the data to separate
* @param separator the separator to use
* @return the new double array based on the given data
*/
public static double[] fromString(String data, String separator) {
String[] split = data.split(separator);
double[] ret = new double[split.length];
for (int i = 0; i < split.length; i++) {
ret[i] = Double.parseDouble(split[i]);
}
return ret;
}//end fromString
/**
* Computes the mean for an array of doubles.
*
* @param vector the array
* @return the mean
*/
public static /*@pure@*/ double mean(double[] vector) {
double sum = 0;
if (vector.length == 0) {
return 0;
}
for (int i = 0; i < vector.length; i++) {
sum += vector[i];
}
return sum / (double) vector.length;
}//end mean
/**
* This will return the cholesky decomposition of
* the given matrix
* @param m the matrix to convert
* @return the cholesky decomposition of the given
* matrix.
* See:
* http://en.wikipedia.org/wiki/Cholesky_decomposition
* @throws NonSquareMatrixException
*/
public CholeskyDecomposition choleskyFromMatrix(RealMatrix m) throws Exception {
return new CholeskyDecomposition(m);
}//end choleskyFromMatrix
/**
* This will convert the given binary string to a decimal based
* integer
* @param binary the binary string to convert
* @return an equivalent base 10 number
*/
public static int toDecimal(String binary) {
long num = Long.parseLong(binary);
long rem;
/* Use the remainder method to ensure validity */
while (num > 0) {
rem = num % 10;
num = num / 10;
if (rem != 0 && rem != 1) {
System.out.println("This is not a binary number.");
System.out.println("Please try once again.");
return -1;
}
}
return Integer.parseInt(binary, 2);
}//end toDecimal
/**
* This will translate a vector in to an equivalent integer
* @param vector the vector to translate
* @return a z value such that the value is the interleaved lsd to msd for each
* double in the vector
*/
public static int distanceFinderZValue(double[] vector) {
StringBuilder binaryBuffer = new StringBuilder();
List<String> binaryReps = new ArrayList<>(vector.length);
for (int i = 0; i < vector.length; i++) {
double d = vector[i];
int j = (int) d;
String binary = Integer.toBinaryString(j);
binaryReps.add(binary);
}
//append from left to right, the least to the most significant bit
//till all strings are empty
while (!binaryReps.isEmpty()) {
for (int j = 0; j < binaryReps.size(); j++) {
String curr = binaryReps.get(j);
if (!curr.isEmpty()) {
char first = curr.charAt(0);
binaryBuffer.append(first);
curr = curr.substring(1);
binaryReps.set(j, curr);
} else
binaryReps.remove(j);
}
}
return Integer.parseInt(binaryBuffer.toString(), 2);
}//end distanceFinderZValue
/**
* This returns the distance of two vectors
* sum(i=1,n) (q_i - p_i)^2
* @param p the first vector
* @param q the second vector
* @return the distance between two vectors
*/
public static double euclideanDistance(double[] p, double[] q) {
double ret = 0;
for (int i = 0; i < p.length; i++) {
double diff = (q[i] - p[i]);
double sq = Math.pow(diff, 2);
ret += sq;
}
return ret;
}//end euclideanDistance
/**
* This returns the distance of two vectors
* sum(i=1,n) (q_i - p_i)^2
* @param p the first vector
* @param q the second vector
* @return the distance between two vectors
*/
public static double euclideanDistance(float[] p, float[] q) {
double ret = 0;
for (int i = 0; i < p.length; i++) {
double diff = (q[i] - p[i]);
double sq = Math.pow(diff, 2);
ret += sq;
}
return ret;
}//end euclideanDistance
/**
* This will generate a series of uniformally distributed
* numbers between l times
* @param l the number of numbers to generate
* @return l uniformally generated numbers
*/
public static double[] generateUniform(int l) {
double[] ret = new double[l];
Random rgen = new Random();
for (int i = 0; i < l; i++) {
ret[i] = rgen.nextDouble();
}
return ret;
}//end generateUniform
/**
* This will calculate the Manhattan distance between two sets of points.
* The Manhattan distance is equivalent to:
* 1_sum_n |p_i - q_i|
* @param p the first point vector
* @param q the second point vector
* @return the Manhattan distance between two object
*/
public static double manhattanDistance(double[] p, double[] q) {
double ret = 0;
for (int i = 0; i < p.length; i++) {
double difference = p[i] - q[i];
ret += Math.abs(difference);
}
return ret;
}//end manhattanDistance
public static double[] sampleDoublesInInterval(double[][] doubles, int l) {
double[] sample = new double[l];
for (int i = 0; i < l; i++) {
int rand1 = randomNumberBetween(0, doubles.length - 1);
int rand2 = randomNumberBetween(0, doubles[i].length);
sample[i] = doubles[rand1][rand2];
}
return sample;
}
/**
* Generates a random integer between the specified numbers
* @param begin the begin of the interval
* @param end the end of the interval
* @return an int between begin and end
*/
public static int randomNumberBetween(double begin, double end) {
if (begin > end)
throw new IllegalArgumentException("Begin must not be less than end");
return (int) begin + (int) (Math.random() * ((end - begin) + 1));
}
/**
* Generates a random integer between the specified numbers
* @param begin the begin of the interval
* @param end the end of the interval
* @return an int between begin and end
*/
public static int randomNumberBetween(double begin, double end, RandomGenerator rng) {
if (begin > end)
throw new IllegalArgumentException("Begin must not be less than end");
return (int) begin + (int) (rng.nextDouble() * ((end - begin) + 1));
}
/**
* Generates a random integer between the specified numbers
* @param begin the begin of the interval
* @param end the end of the interval
* @return an int between begin and end
*/
public static int randomNumberBetween(double begin, double end, org.nd4j.linalg.api.rng.Random rng) {
if (begin > end)
throw new IllegalArgumentException("Begin must not be less than end");
return (int) begin + (int) (rng.nextDouble() * ((end - begin) + 1));
}
/**
*
* @param begin
* @param end
* @return
*/
public static float randomFloatBetween(float begin, float end) {
float rand = (float) Math.random();
return begin + (rand * ((end - begin)));
}
public static double randomDoubleBetween(double begin, double end) {
return begin + (Math.random() * ((end - begin)));
}
public static void shuffleArray(int[] array, long rngSeed) {
shuffleArray(array, new Random(rngSeed));
}
public static void shuffleArray(int[] array, Random rng) {
//https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm
for (int i = array.length - 1; i > 0; i--) {
int j = rng.nextInt(i + 1);
int temp = array[j];
array[j] = array[i];
array[i] = temp;
}
}
}
| RobAltena/deeplearning4j | deeplearning4j/deeplearning4j-nearestneighbors-parent/nearestneighbor-core/src/main/java/org/deeplearning4j/clustering/util/MathUtils.java | Java | apache-2.0 | 42,321 |
package com.dhian;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ComposeShader;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.Shader;
import android.graphics.Shader.TileMode;
import android.util.AttributeSet;
import android.view.View;
public class AmbilWarnaSquare extends View {
Paint paint;
Shader luar;
final float[] color = { 1.f, 1.f, 1.f };
public AmbilWarnaSquare(Context context, AttributeSet attrs) {
super(context, attrs);
}
public AmbilWarnaSquare(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@SuppressLint("DrawAllocation") @Override protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (paint == null) {
paint = new Paint();
luar = new LinearGradient(0.f, 0.f, 0.f, this.getMeasuredHeight(), 0xffffffff, 0xff000000, TileMode.CLAMP);
}
int rgb = Color.HSVToColor(color);
Shader dalam = new LinearGradient(0.f, 0.f, this.getMeasuredWidth(), 0.f, 0xffffffff, rgb, TileMode.CLAMP);
ComposeShader shader = new ComposeShader(luar, dalam, PorterDuff.Mode.MULTIPLY);
paint.setShader(shader);
canvas.drawRect(0.f, 0.f, this.getMeasuredWidth(), this.getMeasuredHeight(), paint);
}
void setHue(float hue) {
color[0] = hue;
invalidate();
}
}
| DhianRusdhiana/CustomTema | CustomTema/app/src/main/java/com/dhian/AmbilWarnaSquare.java | Java | apache-2.0 | 1,442 |
package com.kevin.mirs.vo;
public class LoginUser {
private String username;
private String password;
private String captcha;
// FIXME: 2016/11/20 奇怪,不加上默认构造器就出错
public LoginUser() {
}
public LoginUser(String username, String password, String captcha) {
this.username = username;
this.password = password;
this.captcha = captcha;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public String getCaptcha() {
return captcha;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public void setCaptcha(String captcha) {
this.captcha = captcha;
}
@Override
public String toString() {
return "LoginUser{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
", captcha='" + captcha + '\'' +
'}';
}
}
| firery/mirs | src/main/java/com/kevin/mirs/vo/LoginUser.java | Java | apache-2.0 | 1,131 |
package com.paleblue.persistence.milkha;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.time.Instant;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import com.paleblue.persistence.milkha.dto.BankAccountItem;
import com.paleblue.persistence.milkha.dto.TransactionStatus;
import com.paleblue.persistence.milkha.exception.ContentionException;
import com.paleblue.persistence.milkha.exception.TransactionNotStartedException;
import com.paleblue.persistence.milkha.mapper.BankAccountItemMapper;
import com.paleblue.persistence.milkha.mapper.TransactionLogItemMapper;
import com.paleblue.persistence.milkha.util.Futures;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import com.amazonaws.services.dynamodbv2.model.DeleteItemRequest;
import com.amazonaws.services.dynamodbv2.model.GetItemRequest;
import com.amazonaws.services.dynamodbv2.model.QueryRequest;
import com.amazonaws.services.dynamodbv2.model.QueryResult;
import com.amazonaws.services.dynamodbv2.model.ScanRequest;
import com.amazonaws.services.dynamodbv2.model.ScanResult;
import com.amazonaws.services.dynamodbv2.model.UpdateItemRequest;
import org.junit.Before;
import org.junit.Test;
public class TransactionCoordinatorItemPersistenceTest extends TransactionCoordinatorBaseTest {
private BankAccountItem drEvilSavingsAccount;
@Before
public void setup() {
String beneficiaryName = String.format("DrEvil-%s", UUID.randomUUID().toString());
Integer usdAmount = random.nextInt(1000000);
drEvilSavingsAccount = new BankAccountItem(beneficiaryName, SAVINGS_ACCOUNT_TYPE, usdAmount);
}
private Map<String, AttributeValue> getDrEvilSavingsItemFromDynamo() {
GetItemRequest request = bankAccountItemMapper.
generateGetItemRequest(drEvilSavingsAccount.getBeneficiaryName(), drEvilSavingsAccount.getAccountType());
List<String> attributesToGet = request.getAttributesToGet();
attributesToGet.addAll(TransactionCoordinator.TRANSACTION_CONTROL_FIELDS);
return ddbClient.getItem(request).getItem();
}
private QueryRequest getDrEvilSavingsQueryRequest() {
return bankAccountItemMapper.generateQueryRequest(drEvilSavingsAccount.getBeneficiaryName(),
drEvilSavingsAccount.getAccountType());
}
private DeleteItemRequest getDrEvilSavingsDeleteItemRequest() {
return bankAccountItemMapper.generateDeleteItemRequest(drEvilSavingsAccount.getBeneficiaryName(),
drEvilSavingsAccount.getAccountType());
}
@Test
public void whenCommitWithoutUnlockIsInvokedAfterCreateThenItemIsPersistedWithCorrectControlAttributes() {
String transactionId = randomTransactionId();
createItemWithoutUnlockingCommit(transactionId, drEvilSavingsAccount);
Map<String, AttributeValue> ddbItemMap = getDrEvilSavingsItemFromDynamo();
assertEquals(transactionId, ddbItemMap.get(TransactionCoordinator.TRANSACTION_ID_CONTROL_FIELD).getS());
assertEquals(TransactionCoordinator.TRANSACTION_OPERATION_ADD_VALUE, ddbItemMap.get(TransactionCoordinator.TRANSACTION_OPERATION_CONTROL_FIELD).getS());
}
@Test
public void whenCommitIsInvokedControlFieldsAreCleared() {
String transactionId = randomTransactionId();
createItemWithUnlockingCommit(transactionId, drEvilSavingsAccount);
Map<String, AttributeValue> itemMap = getDrEvilSavingsItemFromDynamo();
assertNull(itemMap.get(TransactionCoordinator.TRANSACTION_ID_CONTROL_FIELD));
assertNull(itemMap.get(TransactionCoordinator.TRANSACTION_OPERATION_CONTROL_FIELD));
}
@Test(expected = IllegalArgumentException.class)
public void whenUpdateItemRequestHasConditionalExpressionSetThenThrowException() {
coordinator.startTransaction();
UpdateItemRequest updateItemRequest = bankAccountItemMapper.generateUpdateItemRequest(drEvilSavingsAccount);
updateItemRequest.setConditionExpression(String.format("%s > 999999", BankAccountItemMapper.TOTAL_AMOUNT_IN_USD_KEY_NAME));
coordinator.createItem(updateItemRequest);
}
@Test(expected = ContentionException.class)
public void whenCreatingAnExistingItemThenThrowException() {
coordinator.startTransaction();
coordinator.createItem(bankAccountItemMapper.generateUpdateItemRequest(drEvilSavingsAccount));
coordinator.commitWithoutUnlocking();
coordinator.startTransaction();
coordinator.createItem(bankAccountItemMapper.generateUpdateItemRequest(drEvilSavingsAccount));
coordinator.commitWithoutUnlocking();
}
@Test
public void itemNotPersistedToDynamoOncreateUnlessTransactionCommitInvoked() {
coordinator.startTransaction();
coordinator.createItem(bankAccountItemMapper.generateUpdateItemRequest(drEvilSavingsAccount));
assertNull(getDrEvilSavingsItemFromDynamo());
}
@Test(expected = TransactionNotStartedException.class)
public void whenCreateIsInvokedWithoutStartingTransactionThenThrowException() {
coordinator.createItem(bankAccountItemMapper.generateUpdateItemRequest(drEvilSavingsAccount));
}
@Test(expected = TransactionNotStartedException.class)
public void whenDeleteIsInvokedWithoutStartingTransactionThenThrowException() {
coordinator.deleteItem(getDrEvilSavingsDeleteItemRequest());
}
@Test
public void whenCommitWithoutUnlockIsInvokedAfterDeleteThenItemIsUpdatedWithCorrectControlAttributes() {
createItemWithUnlockingCommit(drEvilSavingsAccount);
String transactionId = randomTransactionId();
coordinator.startTransaction(transactionId);
coordinator.deleteItem(getDrEvilSavingsDeleteItemRequest());
coordinator.commitWithoutUnlocking();
Map<String, AttributeValue> ddbItemMap = getDrEvilSavingsItemFromDynamo();
assertEquals(transactionId, ddbItemMap.get(TransactionCoordinator.TRANSACTION_ID_CONTROL_FIELD).getS());
assertEquals(TransactionCoordinator.TRANSACTION_OPERATION_DELETE_VALUE, ddbItemMap.get(TransactionCoordinator.TRANSACTION_OPERATION_CONTROL_FIELD).getS());
}
@Test(expected = ContentionException.class)
public void whenDeletingPendingItemThenThrowContentionException() {
coordinator.startTransaction();
coordinator.createItem(bankAccountItemMapper.generateUpdateItemRequest(drEvilSavingsAccount));
coordinator.commitWithoutUnlocking();
coordinator.startTransaction();
coordinator.deleteItem(getDrEvilSavingsDeleteItemRequest());
coordinator.commitWithoutUnlocking();
}
@Test(expected = IllegalArgumentException.class)
public void whenUserSetsConditionExpressionDuringDeleteThenThrowException() {
coordinator.startTransaction();
DeleteItemRequest deleteItemRequest = getDrEvilSavingsDeleteItemRequest();
Map<String, String> expressionAttributeName = new HashMap<>(1);
expressionAttributeName.put("#usdAmount", BankAccountItemMapper.TOTAL_AMOUNT_IN_USD_KEY_NAME);
Map<String, AttributeValue> expressionAttributeValue = new HashMap<>(1);
expressionAttributeValue.put(":usdAmount", new AttributeValue().withN("1000000"));
deleteItemRequest.setExpressionAttributeNames(expressionAttributeName);
deleteItemRequest.setExpressionAttributeValues(expressionAttributeValue);
deleteItemRequest.setConditionExpression("#usdAmount > :usdAmount");
coordinator.deleteItem(deleteItemRequest);
}
@Test
public void whenNoConditionExpressionSpecifiedByUserInDeleteItemRequestThenSucceed() {
createItemWithUnlockingCommit(drEvilSavingsAccount);
coordinator.startTransaction();
coordinator.deleteItem(getDrEvilSavingsDeleteItemRequest());
coordinator.commitWithoutUnlocking();
}
@Test
public void deleteItemDoesNotUpdateItemInDynamoBeforeCommitIsInvoked() {
createItemWithUnlockingCommit(drEvilSavingsAccount);
coordinator.startTransaction();
coordinator.deleteItem(getDrEvilSavingsDeleteItemRequest());
Map<String, AttributeValue> ddbItemMap = getDrEvilSavingsItemFromDynamo();
assertNull(ddbItemMap.get(TransactionCoordinator.TRANSACTION_ID_CONTROL_FIELD));
assertNull(ddbItemMap.get(TransactionCoordinator.TRANSACTION_OPERATION_CONTROL_FIELD));
}
@Test
public void commitDeletesItemFromDynamo() throws ExecutionException, InterruptedException {
createItemWithUnlockingCommit(drEvilSavingsAccount);
coordinator.startTransaction();
coordinator.deleteItem(getDrEvilSavingsDeleteItemRequest());
List<Future> unlockFutures = coordinator.commit();
Futures.blockOnAllFutures(unlockFutures, Instant.now().plusSeconds(1));
assertNull(getDrEvilSavingsItemFromDynamo());
}
@Test(expected = ContentionException.class)
public void whenItemIsAlreadyMarkedForDeletionThenThrowContentionException() throws ExecutionException, InterruptedException {
createItemWithUnlockingCommit(drEvilSavingsAccount);
coordinator.startTransaction();
coordinator.deleteItem(getDrEvilSavingsDeleteItemRequest());
coordinator.commitWithoutUnlocking();
coordinator.startTransaction();
coordinator.deleteItem(getDrEvilSavingsDeleteItemRequest());
List<Future> unlockFutures = coordinator.commit();
Futures.blockOnAllFutures(unlockFutures, Instant.now().plusSeconds(1));
}
@Test(expected = ContentionException.class)
public void whenDeletingNonExistentItemThenThrowException() {
coordinator.startTransaction();
coordinator.deleteItem(getDrEvilSavingsDeleteItemRequest());
coordinator.commitWithoutUnlocking();
}
@Test
public void whenAddedItemIsCommittedAndUnlockedThenUserSeesItem() {
createItemWithUnlockingCommit(drEvilSavingsAccount);
QueryResult queryResult = coordinator.query(getDrEvilSavingsQueryRequest());
List<Map<String, AttributeValue>> committedItems = queryResult.getItems();
assertEquals(1, committedItems.size());
Map<String, AttributeValue> committedItem = committedItems.get(0);
assertEquals(drEvilSavingsAccount.getBeneficiaryName(), committedItem.get(BankAccountItemMapper.ACCOUNT_BENEFICIARY_KEY_NAME).getS());
assertEquals(drEvilSavingsAccount.getTotalAmountInUsd(), new Integer(committedItem.get(BankAccountItemMapper.TOTAL_AMOUNT_IN_USD_KEY_NAME).getN()));
}
@Test
public void whenAddedItemIsCommittedButLockedThenUserSeesItem() {
coordinator.startTransaction();
coordinator.createItem(bankAccountItemMapper.generateUpdateItemRequest(drEvilSavingsAccount));
coordinator.commitWithoutUnlocking();
QueryResult queryResult = coordinator.query(getDrEvilSavingsQueryRequest());
List<Map<String, AttributeValue>> committedItems = queryResult.getItems();
assertEquals(1, committedItems.size());
Map<String, AttributeValue> committedItem = committedItems.get(0);
assertEquals(drEvilSavingsAccount.getBeneficiaryName(), committedItem.get(BankAccountItemMapper.ACCOUNT_BENEFICIARY_KEY_NAME).getS());
assertEquals(drEvilSavingsAccount.getTotalAmountInUsd(), new Integer(committedItem.get(BankAccountItemMapper.TOTAL_AMOUNT_IN_USD_KEY_NAME).getN()));
}
@Test
public void whenDeletedItemIsCommittedAndUnlockedThenUserDoesNotSeeItem() throws ExecutionException, InterruptedException {
createItemWithUnlockingCommit(drEvilSavingsAccount);
QueryResult queryResult = coordinator.query(getDrEvilSavingsQueryRequest());
assertEquals(1, queryResult.getItems().size());
coordinator.startTransaction();
coordinator.deleteItem(getDrEvilSavingsDeleteItemRequest());
List<Future> unlockFutures = coordinator.commit();
Futures.blockOnAllFutures(unlockFutures, Instant.now().plusSeconds(1));
queryResult = coordinator.query(getDrEvilSavingsQueryRequest());
List<Map<String, AttributeValue>> committedItems = queryResult.getItems();
assertEquals(0, committedItems.size());
}
@Test
public void whenDeletedItemIsCommittedButLockedThenUserDoesNotSeeItem() {
createItemWithUnlockingCommit(drEvilSavingsAccount);
QueryResult queryResult = coordinator.query(getDrEvilSavingsQueryRequest());
assertEquals(1, queryResult.getItems().size());
coordinator.startTransaction();
coordinator.deleteItem(getDrEvilSavingsDeleteItemRequest());
coordinator.commitWithoutUnlocking();
queryResult = coordinator.query(getDrEvilSavingsQueryRequest());
List<Map<String, AttributeValue>> committedItems = queryResult.getItems();
assertEquals(0, committedItems.size());
}
@Test
public void itemsInQueryResultDoNotHaveControlAttributes() {
createItemWithUnlockingCommit(drEvilSavingsAccount);
QueryResult queryResult = coordinator.query(getDrEvilSavingsQueryRequest());
List<Map<String, AttributeValue>> committedItems = queryResult.getItems();
assertEquals(1, committedItems.size());
Map<String, AttributeValue> committedItem = committedItems.get(0);
assertFalse(committedItem.containsKey(TransactionCoordinator.TRANSACTION_ID_CONTROL_FIELD));
assertFalse(committedItem.containsKey(TransactionCoordinator.TRANSACTION_OPERATION_CONTROL_FIELD));
for (String controlField : TransactionCoordinator.TRANSACTION_CONTROL_FIELDS) { // In case there are more fields in the future
assertFalse(committedItem.containsKey(controlField));
}
}
@Test
public void whenDynamoQueryReturnsNothingThenNoItemsAreReturnedInResult() {
QueryResult queryResult = coordinator.query(getDrEvilSavingsQueryRequest());
assertTrue(queryResult.getItems().isEmpty());
}
@Test
public void queryMethodDoesNotThrowExceptionIfTransactionIsNotStarted() {
coordinator.query(getDrEvilSavingsQueryRequest());
}
private void whenAddedItemIsPersistedButNotCommittedThenUserDoesNotSeeItem(TransactionStatus txStatusOverride) {
String transactionId = randomTransactionId();
createItemWithoutUnlockingCommit(transactionId, drEvilSavingsAccount);
QueryRequest queryRequest = getDrEvilSavingsQueryRequest();
QueryResult queryResult = coordinator.query(queryRequest);
assertEquals(1, queryResult.getItems().size());
overrideTransactionStatus(transactionId, txStatusOverride);
queryRequest = getDrEvilSavingsQueryRequest();
queryResult = coordinator.query(queryRequest);
assertEquals(0, queryResult.getItems().size());
}
@Test
public void whenAddedItemIsPersistedAndParentTransactionIsStartedThenUserDoesNotSeeItem() {
whenAddedItemIsPersistedButNotCommittedThenUserDoesNotSeeItem(TransactionStatus.START_COMMIT);
}
@Test
public void whenAddedItemIsPersistedAndParentTransactionIsRolledBackThenUserDoesNotSeeItem() {
whenAddedItemIsPersistedButNotCommittedThenUserDoesNotSeeItem(TransactionStatus.ROLLED_BACK);
}
private void whenDeletedItemIsPersistedButNotCommittedThenUserSeesItem(TransactionStatus txStatusOverride) {
createItemWithUnlockingCommit(drEvilSavingsAccount);
QueryRequest queryRequest = getDrEvilSavingsQueryRequest();
QueryResult queryResult = coordinator.query(queryRequest);
assertEquals(1, queryResult.getItems().size());
String transactionId = randomTransactionId();
coordinator.startTransaction(transactionId);
coordinator.deleteItem(getDrEvilSavingsDeleteItemRequest());
coordinator.commitWithoutUnlocking();
queryRequest = getDrEvilSavingsQueryRequest();
queryResult = coordinator.query(queryRequest);
assertEquals(0, queryResult.getItems().size());
overrideTransactionStatus(transactionId, txStatusOverride);
queryRequest = getDrEvilSavingsQueryRequest();
queryResult = coordinator.query(queryRequest);
assertEquals(1, queryResult.getItems().size());
}
@Test
public void whenDeletedItemIsPersistedAndParentTransactionIsStartedThenUserSeesItem() {
whenDeletedItemIsPersistedButNotCommittedThenUserSeesItem(TransactionStatus.START_COMMIT);
}
@Test
public void whenDeletedItemIsPersistedAndParentTransactionIsRolledBackThenUserSeesItem() {
whenDeletedItemIsPersistedButNotCommittedThenUserSeesItem(TransactionStatus.ROLLED_BACK);
}
@Test
public void userSuppliedFilterExpressionNarrowsResults() {
createItemWithUnlockingCommit(drEvilSavingsAccount);
QueryRequest request = getDrEvilSavingsQueryRequest();
request.getExpressionAttributeNames().put("#amount", BankAccountItemMapper.TOTAL_AMOUNT_IN_USD_KEY_NAME);
request.getExpressionAttributeValues().put(":amount", new AttributeValue().withN(drEvilSavingsAccount.getTotalAmountInUsd().toString()));
request.setFilterExpression("#amount > :amount");
QueryResult result = coordinator.query(request);
assertTrue(result.getItems().isEmpty());
}
@Test
public void userCanPaginateQuery() {
BankAccountItem drEvilCheckingAccount = new BankAccountItem(drEvilSavingsAccount.getBeneficiaryName(), "checking", 1000);
createItemWithUnlockingCommit(drEvilCheckingAccount);
createItemWithUnlockingCommit(drEvilSavingsAccount);
QueryRequest request = getDrEvilSavingsQueryRequest();
request.getExpressionAttributeValues().put(":rangevalue", new AttributeValue("xyz")); // "xyz" is greater than "checking" and "savings"
request.setKeyConditionExpression("#hashkey = :hashvalue AND #rangekey < :rangevalue");
request.setLimit(1);
QueryResult result = coordinator.query(request);
assertEquals(1, result.getItems().size());
assertNotNull(result.getLastEvaluatedKey());
BankAccountItem firstAccount = bankAccountItemMapper.unmarshall(result.getItems().get(0));
request.setExclusiveStartKey(result.getLastEvaluatedKey());
result = coordinator.query(request);
assertEquals(1, result.getItems().size());
assertNotNull(result.getLastEvaluatedKey());
BankAccountItem secondAccount = bankAccountItemMapper.unmarshall(result.getItems().get(0));
assertTrue(firstAccount.getAccountType() != secondAccount.getAccountType());
request.setExclusiveStartKey(result.getLastEvaluatedKey());
result = coordinator.query(request);
assertEquals(0, result.getItems().size());
assertNull(result.getLastEvaluatedKey());
}
@Test
public void userCanQueryLSI() {
createItemWithoutUnlockingCommit(drEvilSavingsAccount);
Map<String, String> expressionAttributeNames = new HashMap<>();
expressionAttributeNames.put("#hashkey", bankAccountItemMapper.getHashKeyName());
expressionAttributeNames.put("#rangekey", BankAccountItemMapper.TOTAL_AMOUNT_IN_USD_KEY_NAME);
Map<String, AttributeValue> expressionAttributeValues = new HashMap<>();
expressionAttributeValues.put(":hashvalue", new AttributeValue(drEvilSavingsAccount.getBeneficiaryName()));
expressionAttributeValues.put(":rangevalue", new AttributeValue().withN(drEvilSavingsAccount.getTotalAmountInUsd().toString()));
QueryRequest queryRequest = new QueryRequest().
withConsistentRead(true).
withTableName(bankAccountItemMapper.getTableName()).
withIndexName(BankAccountItemMapper.TOTAL_AMOUNT_LSI_NAME).
withExpressionAttributeNames(expressionAttributeNames).
withExpressionAttributeValues(expressionAttributeValues).
withKeyConditionExpression("#hashkey = :hashvalue AND #rangekey = :rangevalue");
QueryResult result = coordinator.query(queryRequest);
List<Map<String, AttributeValue>> items = result.getItems();
assertEquals(1, items.size());
BankAccountItem returnedItem = bankAccountItemMapper.unmarshall(items.get(0));
assertEquals(drEvilSavingsAccount.getBeneficiaryName(), returnedItem.getBeneficiaryName());
assertEquals(drEvilSavingsAccount.getAccountType(), returnedItem.getAccountType());
assertEquals(drEvilSavingsAccount.getTotalAmountInUsd(), returnedItem.getTotalAmountInUsd());
}
@Test
public void synchronousRollbackUnlocksAddedItem() {
String transactionId = randomTransactionId();
coordinator.startTransaction(transactionId);
coordinator.createItem(bankAccountItemMapper.generateUpdateItemRequest(drEvilSavingsAccount));
coordinator.commitWithoutUnlocking();
QueryRequest queryRequest = getDrEvilSavingsQueryRequest();
QueryResult queryResult = coordinator.query(queryRequest);
assertEquals(1, queryResult.getItems().size());
overrideTransactionStatus(transactionId, TransactionStatus.START_COMMIT);
coordinator.reloadTransactionLogItem();
List<Future> unlockFutures = coordinator.rollback();
Futures.blockOnAllFutures(unlockFutures, Instant.now().plusSeconds(1));
queryResult = coordinator.query(queryRequest);
assertEquals(0, queryResult.getItems().size());
Map<String, AttributeValue> rawTxLogItem = getRawTxLogItem(transactionId);
assertEquals(TransactionStatus.ROLLED_BACK.name(), rawTxLogItem.get(TransactionLogItemMapper.TRANSACTION_STATUS_KEY_NAME).getS());
}
@Test(expected = ContentionException.class)
public void whenTransactionRecordIsSweepedRollbackThrowsContentionException() {
String transactionId = randomTransactionId();
coordinator.startTransaction(transactionId);
coordinator.createItem(bankAccountItemMapper.generateUpdateItemRequest(drEvilSavingsAccount));
coordinator.commitWithoutUnlocking();
overrideTransactionStatus(transactionId, TransactionStatus.START_COMMIT);
coordinator.reloadTransactionLogItem();
deleteTransactionLogItem(transactionId);
coordinator.rollback();
}
@Test
public void synchronousRollbackUnlocksDeletedItem() {
createItemWithUnlockingCommit(drEvilSavingsAccount);
String transactionId = randomTransactionId();
coordinator.startTransaction(transactionId);
coordinator.deleteItem(getDrEvilSavingsDeleteItemRequest());
coordinator.commitWithoutUnlocking();
QueryRequest queryRequest = getDrEvilSavingsQueryRequest();
QueryResult queryResult = coordinator.query(queryRequest);
assertEquals(0, queryResult.getItems().size());
overrideTransactionStatus(transactionId, TransactionStatus.START_COMMIT);
coordinator.reloadTransactionLogItem();
List<Future> unlockFutures = coordinator.rollback();
Futures.blockOnAllFutures(unlockFutures, Instant.now().plusSeconds(1));
queryResult = coordinator.query(queryRequest);
assertEquals(1, queryResult.getItems().size());
Map<String, AttributeValue> rawTxLogItem = getRawTxLogItem(transactionId);
assertEquals(TransactionStatus.ROLLED_BACK.name(), rawTxLogItem.get(TransactionLogItemMapper.TRANSACTION_STATUS_KEY_NAME).getS());
}
@Test
public void exceptionsDuringPostCommitUnlockAreNotThrown() {
createItemWithUnlockingCommit(drEvilSavingsAccount);
coordinator.executePostCommitUnlocks(); // Sync commit already unlocked
}
@Test
public void scanDoesNotExposeUncommittedAddedItem() {
String transactionId = randomTransactionId();
createItemWithoutUnlockingCommit(transactionId, drEvilSavingsAccount);
overrideTransactionStatus(transactionId, TransactionStatus.START_COMMIT);
ScanResult result = coordinator.scan(bankAccountItemMapper.generateScanRequest());
assertTrue(result.getItems().isEmpty());
assertNull(result.getLastEvaluatedKey());
}
@Test
public void scanExposesUncommittedDeletedItem() {
String transactionId = randomTransactionId();
createItemWithUnlockingCommit(drEvilSavingsAccount);
coordinator.startTransaction(transactionId);
coordinator.deleteItem(getDrEvilSavingsDeleteItemRequest());
coordinator.commitWithoutUnlocking();
overrideTransactionStatus(transactionId, TransactionStatus.START_COMMIT);
ScanResult result = coordinator.scan(bankAccountItemMapper.generateScanRequest());
assertEquals(1, result.getItems().size());
assertNull(result.getLastEvaluatedKey());
}
@Test
public void scanExposesCommittedItems() {
createItemWithUnlockingCommit(drEvilSavingsAccount);
ScanResult result = coordinator.scan(bankAccountItemMapper.generateScanRequest());
assertEquals(1, result.getItems().size());
assertNull(result.getLastEvaluatedKey());
}
@Test
public void scanIsolatesCommittedButLockedAddedAndDeletedItems() {
createItemWithUnlockingCommit(drEvilSavingsAccount);
coordinator.startTransaction();
coordinator.deleteItem(getDrEvilSavingsDeleteItemRequest());
coordinator.commitWithoutUnlocking();
BankAccountItem drEvilCheckingAccount = new BankAccountItem(drEvilSavingsAccount.getBeneficiaryName(), "checking", 1000);
createItemWithoutUnlockingCommit(drEvilCheckingAccount);
ScanResult result = coordinator.scan(bankAccountItemMapper.generateScanRequest());
assertEquals(1, result.getItems().size());
assertTrue("checking".equals(bankAccountItemMapper.unmarshall(result.getItems().get(0)).getAccountType()));
assertNull(result.getLastEvaluatedKey());
}
@Test
public void userSpecifiedPageSizeLimitIsExercisedOnScan() {
BankAccountItem drEvilCheckingAccount = new BankAccountItem(drEvilSavingsAccount.getBeneficiaryName(), "checking", 1000);
createItemWithUnlockingCommit(drEvilSavingsAccount);
createItemWithUnlockingCommit(drEvilCheckingAccount);
ScanRequest scanRequest = bankAccountItemMapper.generateScanRequest();
scanRequest.withLimit(1);
ScanResult result = coordinator.scan(scanRequest);
assertEquals(1, result.getItems().size());
assertNotNull(result.getLastEvaluatedKey());
scanRequest.withExclusiveStartKey(result.getLastEvaluatedKey());
result = coordinator.scan(scanRequest);
assertEquals(1, result.getItems().size());
if (result.getLastEvaluatedKey() != null) {
scanRequest.withExclusiveStartKey(result.getLastEvaluatedKey());
result = coordinator.scan(scanRequest);
assertTrue(result.getItems().isEmpty());
assertNull(result.getLastEvaluatedKey());
}
}
@Test
public void userSpecifiedScanFiltersAreApplied() {
createItemWithUnlockingCommit(drEvilSavingsAccount);
ScanRequest scanRequest = bankAccountItemMapper.generateScanRequest();
scanRequest.setExpressionAttributeNames(Collections.singletonMap("#amount", BankAccountItemMapper.TOTAL_AMOUNT_IN_USD_KEY_NAME));
scanRequest.setExpressionAttributeValues(Collections.singletonMap(":amount", new AttributeValue().withN(drEvilSavingsAccount.getTotalAmountInUsd().toString())));
scanRequest.setFilterExpression("#amount > :amount");
ScanResult result = coordinator.scan(scanRequest);
assertTrue(result.getItems().isEmpty());
assertNull(result.getLastEvaluatedKey());
}
@Test
public void scanResultsDontHaveControlFields() {
createItemWithoutUnlockingCommit(drEvilSavingsAccount);
ScanResult result = coordinator.scan(bankAccountItemMapper.generateScanRequest());
assertEquals(1, result.getItems().size());
assertNull(result.getLastEvaluatedKey());
Map<String, AttributeValue> rawItem = result.getItems().get(0);
assertFalse(rawItem.containsKey(TransactionCoordinator.TRANSACTION_ID_CONTROL_FIELD));
assertFalse(rawItem.containsKey(TransactionCoordinator.TRANSACTION_OPERATION_CONTROL_FIELD));
}
}
| aggarwal/dynamodb-milkhatx | tst/com/paleblue/persistence/milkha/TransactionCoordinatorItemPersistenceTest.java | Java | apache-2.0 | 28,608 |
/*
* Licensed to CRATE Technology GmbH ("Crate") under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership. Crate 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.
*
* However, if you have executed another commercial license agreement
* with Crate these terms will supersede the license and you may use the
* software solely pursuant to the terms of the relevant commercial agreement.
*/
package io.crate.operation.scalar.cast;
import com.google.common.collect.ImmutableList;
import io.crate.analyze.symbol.Function;
import io.crate.analyze.symbol.Literal;
import io.crate.analyze.symbol.Symbol;
import io.crate.exceptions.ConversionException;
import io.crate.metadata.FunctionIdent;
import io.crate.operation.Input;
import io.crate.operation.scalar.AbstractScalarFunctionsTest;
import io.crate.types.DataType;
import io.crate.types.DataTypes;
import org.junit.Test;
import java.util.Collections;
import static io.crate.testing.TestingHelpers.isLiteral;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.core.Is.is;
public class ToShortFunctionTest extends AbstractScalarFunctionsTest {
private final String functionName = CastFunctionResolver.FunctionNames.TO_SHORT;
private Short evaluate(Object value, DataType type) {
Input[] input = {(Input)Literal.newLiteral(type, value)};
ToPrimitiveFunction fn = getFunction(functionName, type);
return (Short) fn.evaluate(input);
}
private Symbol normalize(Object value, DataType type) {
ToPrimitiveFunction function = getFunction(functionName, type);
return function.normalizeSymbol(new Function(function.info(),
Collections.<Symbol>singletonList(Literal.newLiteral(type, value))));
}
@Test
@SuppressWarnings("unchecked")
public void testNormalizeSymbol() throws Exception {
assertThat(normalize("123", DataTypes.STRING), isLiteral((short)123));
assertThat(normalize(12.5f, DataTypes.FLOAT), isLiteral((short)12));
}
@Test
public void testEvaluate() throws Exception {
assertThat(evaluate("123", DataTypes.STRING), is((short)123));
assertThat(evaluate(null, DataTypes.STRING), nullValue());
assertThat(evaluate(123.5f, DataTypes.FLOAT), is((short)123));
assertThat(evaluate(123.5d, DataTypes.DOUBLE), is((short) 123));
assertThat(evaluate(null, DataTypes.FLOAT), nullValue());
assertThat(evaluate(42L, DataTypes.LONG), is((short)42));
assertThat(evaluate(null, DataTypes.INTEGER), nullValue());
}
@Test
public void testInvalidType() throws Exception {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("type 'object' not supported for conversion");
functions.get(new FunctionIdent(functionName, ImmutableList.<DataType>of(DataTypes.OBJECT)));
}
@Test
public void testNormalizeInvalidString() throws Exception {
expectedException.expect(ConversionException.class);
expectedException.expectMessage("cannot cast 'hello' to type short");
normalize("hello", DataTypes.STRING);
}
}
| aslanbekirov/crate | sql/src/test/java/io/crate/operation/scalar/cast/ToShortFunctionTest.java | Java | apache-2.0 | 3,778 |
/*-
*
* * Copyright 2015 Skymind,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 org.nd4j.linalg.api.buffer;
import lombok.NonNull;
import org.bytedeco.javacpp.Pointer;
import org.bytedeco.javacpp.indexer.FloatIndexer;
import org.bytedeco.javacpp.indexer.Indexer;
import org.nd4j.linalg.api.complex.IComplexDouble;
import org.nd4j.linalg.api.complex.IComplexFloat;
import org.nd4j.linalg.api.memory.MemoryWorkspace;
import java.nio.ByteBuffer;
/**
* Data buffer for floats
*
* @author Adam Gibson
*/
public class FloatBuffer extends BaseDataBuffer {
/**
* Meant for creating another view of a buffer
*
* @param pointer the underlying buffer to create a view from
* @param indexer the indexer for the pointer
* @param length the length of the view
*/
public FloatBuffer(Pointer pointer, Indexer indexer, long length) {
super(pointer, indexer, length);
}
/**
* Create a float buffer with the given length
* @param length the float buffer with the given length
*/
public FloatBuffer(long length) {
super(length);
}
public FloatBuffer(long length, boolean initialize) {
super(length, initialize);
}
public FloatBuffer(long length, boolean initialize, MemoryWorkspace workspace) {
super(length, initialize, workspace);
}
public FloatBuffer(int length, int elementSize) {
super(length, elementSize);
}
public FloatBuffer(int length, int elementSize, long offset) {
super(length, elementSize, offset);
}
/**
* Initialize the type of this buffer
*/
@Override
protected void initTypeAndSize() {
type = Type.FLOAT;
elementSize = 4;
}
public FloatBuffer(DataBuffer underlyingBuffer, long length, long offset) {
super(underlyingBuffer, length, offset);
}
public FloatBuffer(float[] data) {
this(data, true);
}
public FloatBuffer(float[] data, MemoryWorkspace workspace) {
this(data, true, workspace);
}
public FloatBuffer(int[] data) {
this(data, true);
}
public FloatBuffer(double[] data) {
this(data, true);
}
public FloatBuffer(int[] data, boolean copyOnOps) {
super(data, copyOnOps);
}
public FloatBuffer(int[] data, boolean copy, long offset) {
super(data, copy, offset);
}
public FloatBuffer(double[] data, boolean copyOnOps) {
super(data, copyOnOps);
}
public FloatBuffer(double[] data, boolean copy, long offset) {
super(data, copy, offset);
}
public FloatBuffer(ByteBuffer buffer, int length) {
super(buffer, length);
}
public FloatBuffer(ByteBuffer buffer, int length, long offset) {
super(buffer, length, offset);
}
public FloatBuffer(byte[] data, int length) {
super(data, length);
}
@Override
public IComplexFloat getComplexFloat(long i) {
return null;
}
@Override
public IComplexDouble getComplexDouble(long i) {
return null;
}
public FloatBuffer(float[] floats, boolean copy) {
super(floats, copy);
}
public FloatBuffer(float[] floats, boolean copy, MemoryWorkspace workspace) {
super(floats, copy, workspace);
}
public FloatBuffer(float[] data, boolean copy, long offset) {
super(data, copy, offset);
}
public FloatBuffer(float[] data, boolean copy, long offset, MemoryWorkspace workspace) {
super(data, copy, offset, workspace);
}
@Override
protected DataBuffer create(long length) {
return new FloatBuffer(length);
}
@Override
public DataBuffer create(double[] data) {
return new FloatBuffer(data);
}
@Override
public DataBuffer create(float[] data) {
return new FloatBuffer(data);
}
@Override
public DataBuffer create(int[] data) {
return new FloatBuffer(data);
}
}
| huitseeker/nd4j | nd4j-buffer/src/main/java/org/nd4j/linalg/api/buffer/FloatBuffer.java | Java | apache-2.0 | 4,583 |
class Loader(object):
"""
Base class of every Loaders
"""
def __init__(self, scheduler):
"""
:param host: the scheduler
"""
self._scheduler = scheduler
self._nodes = []
self._links = []
def get_nodes(self):
"""
:return: the loaded nodes or an empty list
"""
return self._nodes
def get_links(self):
"""
:return: the loaded links or an empty list
"""
return self._links
class JSONLoader(Loader):
"""
A JSON Loader that can load data which follows the structure:
{
"nodes":{
"NodeName1":{
"inputs": [list of inputs]
"outputs": [list of outputs]
},
...
}
"links":{
"LinkName1":{
"out":{
"node": "NameNodeN" # MUST be in "nodes"
"attr": "AttributeName"
},
"in":{
"node": "NameNodeN" # MUST be in "nodes"
"attr": "AttributeName"
}
},
...
}
}
"""
def __init__(self, scheduler, config_data):
super(JSONLoader, self).__init__(scheduler)
# load the nodes
self._prepare_nodes(config_data['nodes'])
# then the links
self._prepare_links(config_data['links'])
def _find_in_nodes(self, str_node):
for node in self._nodes:
if str_node == node:
return node
def _prepare_nodes(self, nodes):
for name, data in nodes.items():
self._nodes.append(name)
def _prepare_links(self, links):
for data in links:
in_data = data["input"]
out_data = data["output"]
in_node = self._find_in_nodes(in_data['node'])
if in_node is None:
raise AttributeError("The input node "+in_data['node']+" is not initialised.")
out_node = self._find_in_nodes(out_data['node'])
if in_node is None:
raise AttributeError("The out node "+out_data['node']+" is not initialised.")
self._scheduler.create_data_link(out_node, out_data['attribute'], in_node, in_data['attribute'])
| IntegrCiTy/obnl | obnl/core/impl/loaders.py | Python | apache-2.0 | 2,342 |
using System;
using System.Collections.Generic;
namespace DapperDal.Test.Entities
{
public class PersonEntity
{
public long PersonId { get; set; }
public string PersonName { get; set; }
public int CarId { get; set; }
public DateTime CreateTime { get; set; }
public DateTime UpdateTime { get; set; }
public short IsActive { get; set; }
}
} | arbing/DapperDal | test/DapperDal.Test/Entities/PersonEntity.cs | C# | apache-2.0 | 405 |
from __future__ import absolute_import
from __future__ import unicode_literals
from mb.lib.memoize import memoize
class SomeClass:
def __init__(self):
self._x = 0
def _the_test(self, number):
self._x += 1
return number * self._x
@memoize
def TestCache1(self, number):
return self._the_test(number)
@memoize("self", "number")
def TestCache2(self, number, **kw):
tmp = self._the_test(kw["number2"])
return self._the_test(tmp - number)
def test_NoArgumentsPassed_UsesAllArgumentsForCache():
someClass = SomeClass()
assert someClass._the_test(5) == 5
assert someClass.TestCache1(5) == 10
assert someClass.TestCache1(5) == 10
def test_ArgumentsPassedToUseForCache_UsesArgumentsForCache():
someClass = SomeClass()
assert someClass.TestCache2(5, number2=10) == 10
assert someClass.TestCache2(5, number2=10) == 10
| silverbp/master-builder | tests/memoize_test.py | Python | apache-2.0 | 916 |
#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package}.model.graphserver;
import graphene.dao.DocumentBuilder;
import graphene.dao.G_Parser;
import graphene.dao.GraphTraversalRuleService;
import graphene.dao.HyperGraphBuilder;
import graphene.model.idl.G_CanonicalPropertyType;
import graphene.model.idl.G_Constraint;
import org.apache.tapestry5.ioc.Configuration;
import org.apache.tapestry5.ioc.MappedConfiguration;
import org.apache.tapestry5.ioc.ScopeConstants;
import org.apache.tapestry5.ioc.ServiceBinder;
import org.apache.tapestry5.ioc.annotations.Contribute;
import org.apache.tapestry5.ioc.annotations.InjectService;
public class GraphServerModule {
public static final String MEDIA = "Media";
public static void bind(final ServiceBinder binder) {
binder.bind(HyperGraphBuilder.class, HyperGraphBuilder${projectName}Impl.class).withId("HyperProperty")
.eagerLoad().scope(ScopeConstants.PERTHREAD);
/**
* Here is where you would add in different parsers for different document types. For this example we supply one MediaGraphParser that was designed to work on scraped Instagram data. You can change this one or swap in your own. In most cases you'll have a different parser for each document type, and they will have different ways of adding nodes to a graph.
*/
binder.bind(G_Parser.class, MediaGraphParser.class).withId(MEDIA);
}
/**
* Contribute to the list of available parsers.
*
*
* @param singletons
* @param media
*/
@Contribute(DocumentBuilder.class)
public static void contributeParsers(final Configuration<G_Parser> singletons,
@InjectService(MEDIA) final G_Parser media) {
singletons.add(media);
}
@Contribute(GraphTraversalRuleService.class)
public static void contributeTraversalRules(final MappedConfiguration<String, G_Constraint> rules) {
rules.add("default", G_Constraint.CONTAINS);
// Lose rules that will use common terms
rules.add(G_CanonicalPropertyType.ACCOUNT.name(), G_Constraint.CONTAINS);
// More strict rules that will use match
rules.add(G_CanonicalPropertyType.ADDRESS.name(), G_Constraint.EQUALS);
rules.add(G_CanonicalPropertyType.ADDRESS_STREET.name(), G_Constraint.EQUALS);
rules.add(G_CanonicalPropertyType.NAME.name(), G_Constraint.EQUALS);
rules.add(G_CanonicalPropertyType.MEDIA.name(), G_Constraint.EQUALS);
}
}
| Cognami/graphene | graphene-parent/graphene-archetype/src/main/resources/archetype-resources/__rootArtifactId__-web/src/main/java/model/graphserver/GraphServerModule.java | Java | apache-2.0 | 2,389 |
package org.codingmatters.value.objects.values.vals.json;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import org.codingmatters.value.objects.values.vals.Val;
import java.io.IOException;
public class ValReader {
public Val read(JsonParser parser) throws IOException {
if(parser.currentToken() == null) {
parser.nextToken();
}
return this.parse(parser);
}
private Val parse(JsonParser parser) throws IOException {
if(parser.currentToken() == JsonToken.VALUE_NULL) return null;
if(parser.currentToken() == JsonToken.START_OBJECT) {
return this.parseObject(parser);
} else if(parser.currentToken() == JsonToken.START_ARRAY) {
return this.parseArray(parser);
} else if(parser.currentToken().isScalarValue()) {
return this.parseBaseType(parser);
} else {
throw new IOException("don't know what to do with token : " + parser.currentToken());
}
}
private Val parseBaseType(JsonParser parser) throws IOException {
if (parser.currentToken().isBoolean()) {
return Val.booleanValue(Boolean.parseBoolean(parser.getText()));
} else if (parser.currentToken().isNumeric()) {
if (parser.getText().contains(".")) {
return Val.doubleValue(Double.parseDouble(parser.getText()));
} else {
return Val.longValue(Long.parseLong(parser.getText()));
}
} else {
return Val.stringValue(parser.getText());
}
}
private Val parseArray(JsonParser parser) throws IOException {
Val.ArrayVal.Builder builder = Val.array();
while (parser.nextToken() != JsonToken.END_ARRAY) {
builder.with(this.parse(parser));
}
return builder.build();
}
private Val parseObject(JsonParser parser) throws IOException {
Val.ObjectVal.Builder builder = Val.object();
while (parser.nextToken() != JsonToken.END_OBJECT) {
String propertyName = parser.getCurrentName();
parser.nextToken();
builder.property(propertyName, this.parse(parser));
}
return builder.build();
}
}
| nelt/codingmatters-value-objects | cdm-value-objects-values/src/main/java/org/codingmatters/value/objects/values/vals/json/ValReader.java | Java | apache-2.0 | 2,278 |
/*
Copyright (c) 2011 Serge Danzanvilliers
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.
*/
using System;
namespace SimpleActorsExamples.SimpleLoop
{
using SimpleConcurrency.Actors;
class SimpleLoopActor : SimpleActor<int>
{
protected override void Act()
{
React(m =>
{
if (m >= 0)
{
Console.Write(m);
Console.Write(" ");
this.Post(--m);
Act();
}
else Console.WriteLine();
});
}
}
}
| sdanzan/SimpleConcurrency | src/Samples/SimpleActorsExamples/SimpleLoop.cs | C# | apache-2.0 | 1,123 |
package com.example.jmcruzya.intentapplication;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
public class DetailsActivity extends AppCompatActivity implements View.OnClickListener {
private static final String KEY_OBJ = "obj" ;
public static final int WEB = 0 ;
public static final int TELEFONO = 1 ;
private Contacto contacto;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
Bundle extras = getIntent().getExtras();
if(extras != null){
contacto = (Contacto)extras.getSerializable(KEY_OBJ);
TextView txtNombre = (TextView)findViewById(R.id.textNombre);
TextView txtTelefono = (TextView)findViewById(R.id.textTelefono);
TextView txtWeb = (TextView)findViewById(R.id.textWeb);
txtNombre.setText(contacto.getNombre());
txtTelefono.setText(String.valueOf(contacto.getTelefono()));
txtWeb.setText(contacto.getWeb());
//que vistas le quiero poner el evento
txtTelefono.setOnClickListener(this);
txtWeb.setOnClickListener(this);
}
}
@Override
public void onClick(View v) {
Intent intent = new Intent();
switch (v.getId()) {
case R.id.textTelefono:
intent.putExtra("value",contacto.getTelefono());
setResult(TELEFONO, intent);
break;
case R.id.textWeb:
intent.putExtra("value",contacto.getWeb());
setResult(WEB, intent);
break;
}
finish();
}
}
| juanman12/CursoAppTelefonica | IntentApplication/app/src/main/java/com/example/jmcruzya/intentapplication/DetailsActivity.java | Java | apache-2.0 | 1,846 |
package fr.javatronic.blog.massive.annotation2;
import fr.javatronic.blog.processor.Annotation_002;
@Annotation_002
public class Class_588 {
}
| lesaint/experimenting-annotation-processing | experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation2/Class_588.java | Java | apache-2.0 | 145 |
/*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. 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://aws.amazon.com/apache2.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.
*/
package com.amazonaws.services.iot1clickdevices.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.iot1clickdevices.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* DeviceEvent JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DeviceEventJsonUnmarshaller implements Unmarshaller<DeviceEvent, JsonUnmarshallerContext> {
public DeviceEvent unmarshall(JsonUnmarshallerContext context) throws Exception {
DeviceEvent deviceEvent = new DeviceEvent();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return null;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("device", targetDepth)) {
context.nextToken();
deviceEvent.setDevice(DeviceJsonUnmarshaller.getInstance().unmarshall(context));
}
if (context.testExpression("stdEvent", targetDepth)) {
context.nextToken();
deviceEvent.setStdEvent(context.getUnmarshaller(String.class).unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return deviceEvent;
}
private static DeviceEventJsonUnmarshaller instance;
public static DeviceEventJsonUnmarshaller getInstance() {
if (instance == null)
instance = new DeviceEventJsonUnmarshaller();
return instance;
}
}
| jentfoo/aws-sdk-java | aws-java-sdk-iot1clickdevices/src/main/java/com/amazonaws/services/iot1clickdevices/model/transform/DeviceEventJsonUnmarshaller.java | Java | apache-2.0 | 2,935 |
/*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. 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://aws.amazon.com/apache2.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.
*/
package com.amazonaws.services.mediaconnect.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.mediaconnect.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.protocol.*;
import com.amazonaws.protocol.Protocol;
import com.amazonaws.annotation.SdkInternalApi;
/**
* DeleteFlowRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class DeleteFlowRequestProtocolMarshaller implements Marshaller<Request<DeleteFlowRequest>, DeleteFlowRequest> {
private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.REST_JSON).requestUri("/v1/flows/{flowArn}")
.httpMethodName(HttpMethodName.DELETE).hasExplicitPayloadMember(false).hasPayloadMembers(false).serviceName("AWSMediaConnect").build();
private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory;
public DeleteFlowRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) {
this.protocolFactory = protocolFactory;
}
public Request<DeleteFlowRequest> marshall(DeleteFlowRequest deleteFlowRequest) {
if (deleteFlowRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
final ProtocolRequestMarshaller<DeleteFlowRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING,
deleteFlowRequest);
protocolMarshaller.startMarshalling();
DeleteFlowRequestMarshaller.getInstance().marshall(deleteFlowRequest, protocolMarshaller);
return protocolMarshaller.finishMarshalling();
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| jentfoo/aws-sdk-java | aws-java-sdk-mediaconnect/src/main/java/com/amazonaws/services/mediaconnect/model/transform/DeleteFlowRequestProtocolMarshaller.java | Java | apache-2.0 | 2,596 |
package com.github.mozvip.subtitles.cli;
import picocli.CommandLine;
import java.nio.file.Path;
import java.nio.file.Paths;
public class PathConverter implements CommandLine.ITypeConverter<Path> {
@Override
public Path convert(String value) {
return Paths.get(value);
}
}
| mozvip/subtitles-finder | src/main/java/com/github/mozvip/subtitles/cli/PathConverter.java | Java | apache-2.0 | 295 |
/*
* Copyright 2020 ThoughtWorks, 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 _ from "lodash";
import Stream from "mithril/stream";
import {ConfigRepoJSON, ConfigReposJSON, MaterialModificationJSON, ParseInfoJSON,} from "models/config_repos/serialization";
import {Material, Materials} from "models/materials/types";
import {Errors} from "models/mixins/errors";
import {applyMixins} from "models/mixins/mixins";
import {ValidatableMixin} from "models/mixins/new_validatable_mixin";
import {Rules} from "models/rules/rules";
import {Configuration, PlainTextValue} from "models/shared/plugin_infos_new/plugin_settings/plugin_settings";
import {AutoSuggestions} from "../roles/auto_suggestion";
//tslint:disable-next-line
export interface ConfigRepo extends ValidatableMixin {
}
//tslint:disable-next-line
export interface LastParse extends ValidatableMixin {
}
export class ConfigRepo implements ValidatableMixin {
static readonly PIPELINE_PATTERN = "pipeline_pattern";
static readonly ENVIRONMENT_PATTERN = "environment_pattern";
static readonly FILE_PATTERN = "file_pattern";
static readonly JSON_PLUGIN_ID = "json.config.plugin";
static readonly YAML_PLUGIN_ID = "yaml.config.plugin";
static readonly GROOVY_PLUGIN_ID = "cd.go.contrib.plugins.configrepo.groovy";
id: Stream<string | undefined>;
pluginId: Stream<string | undefined>;
material: Stream<Material | undefined>;
canAdminister: Stream<boolean>;
configuration: Stream<Configuration[] | undefined>;
lastParse: Stream<ParseInfo | null | undefined>;
__jsonPluginPipelinesPattern: Stream<string> = Stream("");
__jsonPluginEnvPattern: Stream<string> = Stream("");
__yamlPluginPattern: Stream<string> = Stream("");
materialUpdateInProgress: Stream<boolean>;
rules: Stream<Rules>;
constructor(id?: string,
pluginId?: string,
material?: Material,
canAdminister?: boolean,
configuration?: Configuration[],
lastParse?: ParseInfo | null,
materialUpdateInProgress?: boolean,
rules?: Rules) {
this.id = Stream(id);
this.pluginId = Stream(pluginId);
this.material = Stream(material);
this.canAdminister = Stream(canAdminister || false);
this.configuration = Stream(configuration);
this.lastParse = Stream(lastParse);
this.materialUpdateInProgress = Stream(materialUpdateInProgress || false);
this.rules = Stream(rules || []);
if (configuration) {
this.__jsonPluginPipelinesPattern = Stream(ConfigRepo.findConfigurationValue(configuration,
ConfigRepo.PIPELINE_PATTERN));
this.__jsonPluginEnvPattern = Stream(ConfigRepo.findConfigurationValue(configuration,
ConfigRepo.ENVIRONMENT_PATTERN));
this.__yamlPluginPattern = Stream(ConfigRepo.findConfigurationValue(configuration,
ConfigRepo.FILE_PATTERN));
}
ValidatableMixin.call(this);
this.validatePresenceOf("id", {message: "Please provide a name for this repository"});
this.validateIdFormat("id", {message: "Only letters, numbers, hyphens, underscores, and periods. Must not start with a period. Max 255 chars."});
this.validatePresenceOf("pluginId");
this.validateAssociated("material");
this.validateEach("rules");
}
static findConfigurationValue(configuration: Configuration[], key: string) {
const config = configuration.find((config) => config.key === key);
return config ? config.value : "";
}
static fromJSON(json: ConfigRepoJSON) {
const configurations = json.configuration.map((config) => Configuration.fromJSON(config));
const parseInfo = ParseInfo.fromJSON(json.parse_info);
const configRepo = new ConfigRepo(json.id,
json.plugin_id,
Materials.fromJSON(json.material),
json.can_administer,
configurations,
parseInfo,
json.material_update_in_progress,
Rules.fromJSON(json.rules));
configRepo.errors(new Errors(json.errors));
return configRepo;
}
createConfigurationsFromText() {
const configurations = [];
if (this.pluginId() === ConfigRepo.YAML_PLUGIN_ID && this.__yamlPluginPattern().length > 0) {
configurations.push(new Configuration(ConfigRepo.FILE_PATTERN, new PlainTextValue(this.__yamlPluginPattern())));
}
if (this.pluginId() === ConfigRepo.JSON_PLUGIN_ID) {
if (this.__jsonPluginPipelinesPattern().length > 0) {
configurations.push(new Configuration(ConfigRepo.PIPELINE_PATTERN,
new PlainTextValue(this.__jsonPluginPipelinesPattern())));
}
if (this.__jsonPluginEnvPattern().length > 0) {
configurations.push(new Configuration(ConfigRepo.ENVIRONMENT_PATTERN,
new PlainTextValue(this.__jsonPluginEnvPattern())));
}
}
return configurations;
}
matches(textToMatch: string): boolean {
if (!textToMatch) {
return true;
}
const id = this.id();
const goodRevision = this.lastParse() && this.lastParse()!.goodRevision();
const latestRevision = this.lastParse() && this.lastParse()!.latestRevision();
const materialUrl = this.material()!.materialUrl();
return [
id,
goodRevision,
latestRevision,
materialUrl
].some((value) => value ? value.toLowerCase().includes(textToMatch.toLowerCase()) : false);
}
}
applyMixins(ConfigRepo, ValidatableMixin);
export class ConfigRepos {
configRepos: ConfigRepo[];
autoCompletion: AutoSuggestions;
constructor(configRepos: ConfigRepo[], autoCompletion: AutoSuggestions) {
this.configRepos = configRepos;
this.autoCompletion = autoCompletion;
}
static fromJSON(json?: ConfigReposJSON): ConfigRepos {
const configRepos = _.map(json!._embedded.config_repos, (json: ConfigRepoJSON) => {
return ConfigRepo.fromJSON(json);
});
return new ConfigRepos(configRepos, AutoSuggestions.fromJSON(json!.auto_completion));
}
}
export class MaterialModification {
readonly username: string;
readonly emailAddress: string | null;
readonly revision: string;
readonly comment: string;
readonly modifiedTime: string;
constructor(username: string, emailAddress: string | null, revision: string, comment: string, modifiedTime: string) {
this.username = username;
this.emailAddress = emailAddress;
this.revision = revision;
this.comment = comment;
this.modifiedTime = modifiedTime;
}
static fromJSON(modification: MaterialModificationJSON): MaterialModification {
return new MaterialModification(modification.username,
modification.email_address,
modification.revision,
modification.comment,
modification.modified_time);
}
}
export class ParseInfo {
error: Stream<string | null | undefined>;
readonly latestParsedModification: MaterialModification | null;
readonly goodModification: MaterialModification | null;
constructor(latestParsedModification: MaterialModification | null,
goodModification: MaterialModification | null,
error: string | undefined | null) {
this.latestParsedModification = latestParsedModification;
this.goodModification = goodModification;
this.error = Stream(error);
}
static fromJSON(json: ParseInfoJSON) {
if (!_.isEmpty(json)) {
const latestParsedModification = json.latest_parsed_modification ? MaterialModification.fromJSON(json.latest_parsed_modification) : null;
const goodModification = json.good_modification ? MaterialModification.fromJSON(json.good_modification) : null;
return new ParseInfo(latestParsedModification, goodModification, json.error);
}
}
goodRevision() {
if (this.goodModification) {
return this.goodModification.revision;
}
}
latestRevision() {
if (this.latestParsedModification) {
return this.latestParsedModification.revision;
}
}
}
const HUMAN_NAMES_FOR_MATERIAL_ATTRIBUTES: { [index: string]: string } = {
autoUpdate: "Auto-update",
branch: "Branch",
checkExternals: "Check Externals",
domain: "Domain",
encryptedPassword: "Password",
name: "Material Name",
destination: "Alternate Checkout Path",
projectPath: "Project Path",
url: "URL",
username: "Username",
password: "Password",
port: "Host and Port",
useTickets: "Use Tickets",
view: "View",
emailAddress: "Email",
revision: "Revision",
comment: "Comment",
modifiedTime: "Modified Time"
};
const MATERIAL_TYPE_MAP: { [index: string]: string } = {
git: "Git",
hg: "Mercurial",
tfs: "Team Foundation Server",
svn: "Subversion",
p4: "Perforce",
};
const CONFIG_ATTRIBUTE: { [index: string]: string } = {
file_pattern: "File Pattern"
};
export function humanizedMaterialNameForMaterialType(materialType: string) {
return MATERIAL_TYPE_MAP[materialType];
}
export function humanizedMaterialAttributeName(key: string) {
return HUMAN_NAMES_FOR_MATERIAL_ATTRIBUTES[key] || CONFIG_ATTRIBUTE[key] || key;
}
| ketan/gocd | server/src/main/webapp/WEB-INF/rails/webpack/models/config_repos/types.ts | TypeScript | apache-2.0 | 10,518 |
package Graph;
// http://blog.csdn.net/hawksoft/article/details/7687730
public class KruskalTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
/* /// <summary>
/// ͼÀ࣬ÓɽڵãºÍ±ß¹¹³É.
/// </summary>
public class Graphic
{
public List<Node> Nodes { get; set; }
public List<Edge> Edges { get; set; }
public Graphic()
{
Nodes = new List<Node>();
Edges = new List<Edge>();
}
public void Add(Node Node)
{
if (this.Nodes.IndexOf(Node) < 0)
{
this.Nodes.Add(Node);
}
}
public void Add(Edge Edge)
{
if (this.Edges.IndexOf(Edge) < 0)
{
this.Edges.Add(Edge);
}
}
}
/// <summary>
/// Ê÷À࣬°üÀ¨½ÚµãºÍ±ß¹¹³É
/// </summary>
public class Tree
{
public List<Node> Nodes { get; set; }
public List<Edge> Edges { get; set; }
public Tree()
{
Nodes = new List<Node>();
Edges = new List<Edge>();
}
public void Add(Node Node)
{
if (this.Nodes.IndexOf(Node) < 0)
{
this.Nodes.Add(Node);
}
}
public void Add(Edge Edge)
{
if (this.Edges.IndexOf(Edge) < 0)
{
this.Edges.Add(Edge);
}
}
}
/// <summary>
/// ½ÚµãÀà
/// </summary>
public class Node
{
public string Symbol { get; set; }
public Node(string Symbol)
{
this.Symbol = Symbol;
}
}
/// <summary>
/// ±ßÀ࣬°üÀ¨Á½¸ö½ÚµãºÍÈ¨ÖØ.
/// </summary>
public class Edge
{
public Node Node1 { get; set; }
public Node Node2 { get; set; }
public int Weight { get; set; }
public Edge(Node N1, Node N2, int Weight)
{
this.Node1 = N1;
this.Node2 = N2;
this.Weight = Weight;
}
}
*/
| coodoing/AlgoTraining | src/Graph/KruskalTest.java | Java | apache-2.0 | 2,122 |
package com.example.cpv.domain.util;
import java.time.*;
import java.util.Date;
import org.springframework.core.convert.converter.Converter;
public final class JSR310DateConverters {
private JSR310DateConverters() {}
public static class LocalDateToDateConverter implements Converter<LocalDate, Date> {
public static final LocalDateToDateConverter INSTANCE = new LocalDateToDateConverter();
private LocalDateToDateConverter() {}
@Override
public Date convert(LocalDate source) {
return source == null ? null : Date.from(source.atStartOfDay(ZoneId.systemDefault()).toInstant());
}
}
public static class DateToLocalDateConverter implements Converter<Date, LocalDate> {
public static final DateToLocalDateConverter INSTANCE = new DateToLocalDateConverter();
private DateToLocalDateConverter() {}
@Override
public LocalDate convert(Date source) {
return source == null ? null : ZonedDateTime.ofInstant(source.toInstant(), ZoneId.systemDefault()).toLocalDate();
}
}
public static class ZonedDateTimeToDateConverter implements Converter<ZonedDateTime, Date> {
public static final ZonedDateTimeToDateConverter INSTANCE = new ZonedDateTimeToDateConverter();
private ZonedDateTimeToDateConverter() {}
@Override
public Date convert(ZonedDateTime source) {
return source == null ? null : Date.from(source.toInstant());
}
}
public static class DateToZonedDateTimeConverter implements Converter<Date, ZonedDateTime> {
public static final DateToZonedDateTimeConverter INSTANCE = new DateToZonedDateTimeConverter();
private DateToZonedDateTimeConverter() {}
@Override
public ZonedDateTime convert(Date source) {
return source == null ? null : ZonedDateTime.ofInstant(source.toInstant(), ZoneId.systemDefault());
}
}
public static class LocalDateTimeToDateConverter implements Converter<LocalDateTime, Date> {
public static final LocalDateTimeToDateConverter INSTANCE = new LocalDateTimeToDateConverter();
private LocalDateTimeToDateConverter() {}
@Override
public Date convert(LocalDateTime source) {
return source == null ? null : Date.from(source.atZone(ZoneId.systemDefault()).toInstant());
}
}
public static class DateToLocalDateTimeConverter implements Converter<Date, LocalDateTime> {
public static final DateToLocalDateTimeConverter INSTANCE = new DateToLocalDateTimeConverter();
private DateToLocalDateTimeConverter() {}
@Override
public LocalDateTime convert(Date source) {
return source == null ? null : LocalDateTime.ofInstant(source.toInstant(), ZoneId.systemDefault());
}
}
}
| borisbsu/continious-delivery-test | src/main/java/com/example/cpv/domain/util/JSR310DateConverters.java | Java | apache-2.0 | 2,855 |
// Copyright (C) LINBIT HA-Solutions GmbH
// All Rights Reserved.
// Author: Roland Kammerer <roland.kammerer@linbit.com>
//
// 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 client
import (
"context"
"github.com/LINBIT/golinstor/devicelayerkind"
)
// copy & paste from generated code
// Node represents a node in LINSTOR
type Node struct {
Name string `json:"name"`
Type string `json:"type"`
Flags []string `json:"flags,omitempty"`
// A string to string property map.
Props map[string]string `json:"props,omitempty"`
NetInterfaces []NetInterface `json:"net_interfaces,omitempty"`
// Enum describing the current connection status.
ConnectionStatus string `json:"connection_status,omitempty"`
// unique object id
Uuid string `json:"uuid,omitempty"`
StorageProviders []ProviderKind `json:"storage_providers,omitempty"`
ResourceLayers []devicelayerkind.DeviceLayerKind `json:"resource_layers,omitempty"`
UnsupportedProviders map[ProviderKind][]string `json:"unsupported_providers,omitempty"`
UnsupportedLayers map[devicelayerkind.DeviceLayerKind][]string `json:"unsupported_layers,omitempty"`
// milliseconds since unix epoch in UTC
EvictionTimestamp *TimeStampMs `json:"eviction_timestamp,omitempty"`
}
type NodeModify struct {
NodeType string `json:"node_type,omitempty"`
// A string to string property map.
GenericPropsModify
}
type NodeRestore struct {
DeleteResources *bool `json:"delete_resources,omitempty"`
DeleteSnapshots *bool `json:"delete_snapshots,omitempty"`
}
// NetInterface represents a node's network interface.
type NetInterface struct {
Name string `json:"name"`
Address string `json:"address"`
SatellitePort int32 `json:"satellite_port,omitempty"`
SatelliteEncryptionType string `json:"satellite_encryption_type,omitempty"`
// Defines if this netinterface should be used for the satellite connection
IsActive bool `json:"is_active,omitempty"`
// unique object id
Uuid string `json:"uuid,omitempty"`
}
// StoragePool represents a nodes storage pool as defined in LINSTOR.
type StoragePool struct {
StoragePoolName string `json:"storage_pool_name"`
NodeName string `json:"node_name,omitempty"`
ProviderKind ProviderKind `json:"provider_kind"`
// A string to string property map.
Props map[string]string `json:"props,omitempty"`
// read only map of static storage pool traits
StaticTraits map[string]string `json:"static_traits,omitempty"`
// Kibi - read only
FreeCapacity int64 `json:"free_capacity,omitempty"`
// Kibi - read only
TotalCapacity int64 `json:"total_capacity,omitempty"`
// read only
FreeSpaceMgrName string `json:"free_space_mgr_name,omitempty"`
// unique object id
Uuid string `json:"uuid,omitempty"`
// Currently known report messages for this storage pool
Reports []ApiCallRc `json:"reports,omitempty"`
// true if the storage pool supports snapshots. false otherwise
SupportsSnapshots bool `json:"supports_snapshots,omitempty"`
// name of the shared space or null if none given
SharedSpace string `json:"shared_space,omitempty"`
// true if a shared storage pool uses linstor-external locking, like cLVM
ExternalLocking bool `json:"external_locking,omitempty"`
}
// ProviderKind is a type that represents various types of storage.
type ProviderKind string
// List of ProviderKind
const (
DISKLESS ProviderKind = "DISKLESS"
LVM ProviderKind = "LVM"
LVM_THIN ProviderKind = "LVM_THIN"
ZFS ProviderKind = "ZFS"
ZFS_THIN ProviderKind = "ZFS_THIN"
OPENFLEX_TARGET ProviderKind = "OPENFLEX_TARGET"
FILE ProviderKind = "FILE"
FILE_THIN ProviderKind = "FILE_THIN"
SPDK ProviderKind = "SPDK"
)
// custom code
// NodeProvider acts as an abstraction for a NodeService. It can be swapped out
// for another NodeService implementation, for example for testing.
type NodeProvider interface {
// GetAll gets information for all registered nodes.
GetAll(ctx context.Context, opts ...*ListOpts) ([]Node, error)
// Get gets information for a particular node.
Get(ctx context.Context, nodeName string, opts ...*ListOpts) (Node, error)
// Create creates a new node object.
Create(ctx context.Context, node Node) error
// Modify modifies the given node and sets/deletes the given properties.
Modify(ctx context.Context, nodeName string, props NodeModify) error
// Delete deletes the given node.
Delete(ctx context.Context, nodeName string) error
// Lost marks the given node as lost to delete an unrecoverable node.
Lost(ctx context.Context, nodeName string) error
// Reconnect reconnects a node to the controller.
Reconnect(ctx context.Context, nodeName string) error
// GetNetInterfaces gets information about all network interfaces of a given node.
GetNetInterfaces(ctx context.Context, nodeName string, opts ...*ListOpts) ([]NetInterface, error)
// GetNetInterface gets information about a particular network interface on a given node.
GetNetInterface(ctx context.Context, nodeName, nifName string, opts ...*ListOpts) (NetInterface, error)
// CreateNetInterface creates the given network interface on a given node.
CreateNetInterface(ctx context.Context, nodeName string, nif NetInterface) error
// ModifyNetInterface modifies the given network interface on a given node.
ModifyNetInterface(ctx context.Context, nodeName, nifName string, nif NetInterface) error
// DeleteNetinterface deletes the given network interface on a given node.
DeleteNetinterface(ctx context.Context, nodeName, nifName string) error
// GetStoragePoolView gets information about all storage pools in the cluster.
GetStoragePoolView(ctx context.Context, opts ...*ListOpts) ([]StoragePool, error)
// GetStoragePools gets information about all storage pools on a given node.
GetStoragePools(ctx context.Context, nodeName string, opts ...*ListOpts) ([]StoragePool, error)
// GetStoragePool gets information about a specific storage pool on a given node.
GetStoragePool(ctx context.Context, nodeName, spName string, opts ...*ListOpts) (StoragePool, error)
// CreateStoragePool creates a storage pool on a given node.
CreateStoragePool(ctx context.Context, nodeName string, sp StoragePool) error
// ModifyStoragePool modifies a storage pool on a given node.
ModifyStoragePool(ctx context.Context, nodeName, spName string, sp StoragePool) error
// DeleteStoragePool deletes a storage pool on a given node.
DeleteStoragePool(ctx context.Context, nodeName, spName string) error
// CreateDevicePool creates an LVM, LVM-thin or ZFS pool, optional VDO under it on a given node.
CreateDevicePool(ctx context.Context, nodeName string, psc PhysicalStorageCreate) error
// GetPhysicalStorage gets a grouped list of physical storage that can be turned into a LINSTOR storage-pool
GetPhysicalStorage(ctx context.Context, opts ...*ListOpts) ([]PhysicalStorage, error)
// GetStoragePoolPropsInfos gets meta information about the properties
// that can be set on a storage pool on a particular node.
GetStoragePoolPropsInfos(ctx context.Context, nodeName string, opts ...*ListOpts) ([]PropsInfo, error)
// GetPropsInfos gets meta information about the properties that can be
// set on a node.
GetPropsInfos(ctx context.Context, opts ...*ListOpts) ([]PropsInfo, error)
// Evict the given node, migrating resources to the remaining nodes, if possible.
Evict(ctx context.Context, nodeName string) error
// Restore an evicted node, optionally keeping existing resources.
Restore(ctx context.Context, nodeName string, restore NodeRestore) error
}
// NodeService is the service that deals with node related tasks.
type NodeService struct {
client *Client
}
var _ NodeProvider = &NodeService{}
// GetAll gets information for all registered nodes.
func (n *NodeService) GetAll(ctx context.Context, opts ...*ListOpts) ([]Node, error) {
var nodes []Node
_, err := n.client.doGET(ctx, "/v1/nodes", &nodes, opts...)
return nodes, err
}
// Get gets information for a particular node.
func (n *NodeService) Get(ctx context.Context, nodeName string, opts ...*ListOpts) (Node, error) {
var node Node
_, err := n.client.doGET(ctx, "/v1/nodes/"+nodeName, &node, opts...)
return node, err
}
// Create creates a new node object.
func (n *NodeService) Create(ctx context.Context, node Node) error {
_, err := n.client.doPOST(ctx, "/v1/nodes", node)
return err
}
// Modify modifies the given node and sets/deletes the given properties.
func (n *NodeService) Modify(ctx context.Context, nodeName string, props NodeModify) error {
_, err := n.client.doPUT(ctx, "/v1/nodes/"+nodeName, props)
return err
}
// Delete deletes the given node.
func (n *NodeService) Delete(ctx context.Context, nodeName string) error {
_, err := n.client.doDELETE(ctx, "/v1/nodes/"+nodeName, nil)
return err
}
// Lost marks the given node as lost to delete an unrecoverable node.
func (n *NodeService) Lost(ctx context.Context, nodeName string) error {
_, err := n.client.doDELETE(ctx, "/v1/nodes/"+nodeName+"/lost", nil)
return err
}
// Reconnect reconnects a node to the controller.
func (n *NodeService) Reconnect(ctx context.Context, nodeName string) error {
_, err := n.client.doPUT(ctx, "/v1/nodes/"+nodeName+"/reconnect", nil)
return err
}
// GetNetInterfaces gets information about all network interfaces of a given node.
func (n *NodeService) GetNetInterfaces(ctx context.Context, nodeName string, opts ...*ListOpts) ([]NetInterface, error) {
var nifs []NetInterface
_, err := n.client.doGET(ctx, "/v1/nodes/"+nodeName+"/net-interfaces", &nifs, opts...)
return nifs, err
}
// GetNetInterface gets information about a particular network interface on a given node.
func (n *NodeService) GetNetInterface(ctx context.Context, nodeName, nifName string, opts ...*ListOpts) (NetInterface, error) {
var nif NetInterface
_, err := n.client.doGET(ctx, "/v1/nodes/"+nodeName+"/net-interfaces/"+nifName, &nif, opts...)
return nif, err
}
// CreateNetInterface creates the given network interface on a given node.
func (n *NodeService) CreateNetInterface(ctx context.Context, nodeName string, nif NetInterface) error {
_, err := n.client.doPOST(ctx, "/v1/nodes/"+nodeName+"/net-interfaces", nif)
return err
}
// ModifyNetInterface modifies the given network interface on a given node.
func (n *NodeService) ModifyNetInterface(ctx context.Context, nodeName, nifName string, nif NetInterface) error {
_, err := n.client.doPUT(ctx, "/v1/nodes/"+nodeName+"/net-interfaces/"+nifName, nif)
return err
}
// DeleteNetinterface deletes the given network interface on a given node.
func (n *NodeService) DeleteNetinterface(ctx context.Context, nodeName, nifName string) error {
_, err := n.client.doDELETE(ctx, "/v1/nodes/"+nodeName+"/net-interfaces/"+nifName, nil)
return err
}
// GetStoragePoolView gets information about all storage pools in the cluster.
func (n *NodeService) GetStoragePoolView(ctx context.Context, opts ...*ListOpts) ([]StoragePool, error) {
var sps []StoragePool
_, err := n.client.doGET(ctx, "/v1/view/storage-pools", &sps, opts...)
return sps, err
}
// GetStoragePools gets information about all storage pools on a given node.
func (n *NodeService) GetStoragePools(ctx context.Context, nodeName string, opts ...*ListOpts) ([]StoragePool, error) {
var sps []StoragePool
_, err := n.client.doGET(ctx, "/v1/nodes/"+nodeName+"/storage-pools", &sps, opts...)
return sps, err
}
// GetStoragePool gets information about a specific storage pool on a given node.
func (n *NodeService) GetStoragePool(ctx context.Context, nodeName, spName string, opts ...*ListOpts) (StoragePool, error) {
var sp StoragePool
_, err := n.client.doGET(ctx, "/v1/nodes/"+nodeName+"/storage-pools/"+spName, &sp, opts...)
return sp, err
}
// CreateStoragePool creates a storage pool on a given node.
func (n *NodeService) CreateStoragePool(ctx context.Context, nodeName string, sp StoragePool) error {
_, err := n.client.doPOST(ctx, "/v1/nodes/"+nodeName+"/storage-pools", sp)
return err
}
// ModifyStoragePool modifies a storage pool on a given node.
func (n *NodeService) ModifyStoragePool(ctx context.Context, nodeName, spName string, sp StoragePool) error {
_, err := n.client.doPOST(ctx, "/v1/nodes/"+nodeName+"/storage-pools/"+spName, sp)
return err
}
// DeleteStoragePool deletes a storage pool on a given node.
func (n *NodeService) DeleteStoragePool(ctx context.Context, nodeName, spName string) error {
_, err := n.client.doDELETE(ctx, "/v1/nodes/"+nodeName+"/storage-pools/"+spName, nil)
return err
}
// GetStoragePoolPropsInfos gets meta information about the properties that can
// be set on a storage pool on a particular node.
func (n *NodeService) GetStoragePoolPropsInfos(ctx context.Context, nodeName string, opts ...*ListOpts) ([]PropsInfo, error) {
var infos []PropsInfo
_, err := n.client.doGET(ctx, "/v1/nodes/"+nodeName+"/storage-pools/properties/info", &infos, opts...)
return infos, err
}
// GetPropsInfos gets meta information about the properties that can be set on
// a node.
func (n *NodeService) GetPropsInfos(ctx context.Context, opts ...*ListOpts) ([]PropsInfo, error) {
var infos []PropsInfo
_, err := n.client.doGET(ctx, "/v1/nodes/properties/info", &infos, opts...)
return infos, err
}
// Evict the given node, migrating resources to the remaining nodes, if possible.
func (n NodeService) Evict(ctx context.Context, nodeName string) error {
_, err := n.client.doPUT(ctx, "/v1/nodes/"+nodeName+"/evict", nil)
return err
}
// Restore an evicted node, optionally keeping existing resources.
func (n *NodeService) Restore(ctx context.Context, nodeName string, restore NodeRestore) error {
_, err := n.client.doPUT(ctx, "/v1/nodes/"+nodeName+"/restore", restore)
return err
}
| libopenstorage/stork | vendor/github.com/LINBIT/golinstor/client/node.go | GO | apache-2.0 | 14,405 |
/*
* Copyright 2013-present Facebook, 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 com.facebook.buck.apple;
import static com.facebook.buck.swift.SwiftLibraryDescription.isSwiftTarget;
import com.facebook.buck.cxx.CxxCompilationDatabase;
import com.facebook.buck.cxx.CxxDescriptionEnhancer;
import com.facebook.buck.cxx.CxxLibraryDescription;
import com.facebook.buck.cxx.CxxPlatform;
import com.facebook.buck.cxx.CxxStrip;
import com.facebook.buck.cxx.Linker;
import com.facebook.buck.cxx.ProvidesLinkedBinaryDeps;
import com.facebook.buck.cxx.StripStyle;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.Either;
import com.facebook.buck.model.Flavor;
import com.facebook.buck.model.FlavorConvertible;
import com.facebook.buck.model.FlavorDomain;
import com.facebook.buck.model.Flavored;
import com.facebook.buck.model.ImmutableFlavor;
import com.facebook.buck.parser.NoSuchBuildTargetException;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.BuildRuleParams;
import com.facebook.buck.rules.BuildRuleResolver;
import com.facebook.buck.rules.BuildRuleType;
import com.facebook.buck.rules.BuildTargetSourcePath;
import com.facebook.buck.rules.CellPathResolver;
import com.facebook.buck.rules.Description;
import com.facebook.buck.rules.ImplicitDepsInferringDescription;
import com.facebook.buck.rules.ImplicitFlavorsInferringDescription;
import com.facebook.buck.rules.MetadataProvidingDescription;
import com.facebook.buck.rules.SourcePath;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.TargetGraph;
import com.facebook.buck.swift.SwiftLibraryDescription;
import com.facebook.buck.util.HumanReadableException;
import com.facebook.infer.annotation.SuppressFieldNotInitialized;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
public class AppleLibraryDescription implements
Description<AppleLibraryDescription.Arg>,
Flavored,
ImplicitDepsInferringDescription<AppleLibraryDescription.Arg>,
ImplicitFlavorsInferringDescription,
MetadataProvidingDescription<AppleLibraryDescription.Arg> {
public static final BuildRuleType TYPE = BuildRuleType.of("apple_library");
@SuppressWarnings("PMD") // PMD doesn't understand method references
private static final Set<Flavor> SUPPORTED_FLAVORS = ImmutableSet.of(
CxxCompilationDatabase.COMPILATION_DATABASE,
CxxCompilationDatabase.UBER_COMPILATION_DATABASE,
CxxDescriptionEnhancer.HEADER_SYMLINK_TREE_FLAVOR,
CxxDescriptionEnhancer.EXPORTED_HEADER_SYMLINK_TREE_FLAVOR,
CxxDescriptionEnhancer.STATIC_FLAVOR,
CxxDescriptionEnhancer.SHARED_FLAVOR,
AppleDescriptions.FRAMEWORK_FLAVOR,
AppleDebugFormat.DWARF_AND_DSYM.getFlavor(),
AppleDebugFormat.DWARF.getFlavor(),
AppleDebugFormat.NONE.getFlavor(),
StripStyle.NON_GLOBAL_SYMBOLS.getFlavor(),
StripStyle.ALL_SYMBOLS.getFlavor(),
StripStyle.DEBUGGING_SYMBOLS.getFlavor(),
ImmutableFlavor.of("default"));
private enum Type implements FlavorConvertible {
HEADERS(CxxDescriptionEnhancer.HEADER_SYMLINK_TREE_FLAVOR),
EXPORTED_HEADERS(CxxDescriptionEnhancer.EXPORTED_HEADER_SYMLINK_TREE_FLAVOR),
SHARED(CxxDescriptionEnhancer.SHARED_FLAVOR),
STATIC_PIC(CxxDescriptionEnhancer.STATIC_PIC_FLAVOR),
STATIC(CxxDescriptionEnhancer.STATIC_FLAVOR),
MACH_O_BUNDLE(CxxDescriptionEnhancer.MACH_O_BUNDLE_FLAVOR),
FRAMEWORK(AppleDescriptions.FRAMEWORK_FLAVOR),
;
private final Flavor flavor;
Type(Flavor flavor) {
this.flavor = flavor;
}
@Override
public Flavor getFlavor() {
return flavor;
}
}
public static final FlavorDomain<Type> LIBRARY_TYPE =
FlavorDomain.from("C/C++ Library Type", Type.class);
private final CxxLibraryDescription delegate;
private final SwiftLibraryDescription swiftDelegate;
private final FlavorDomain<AppleCxxPlatform> appleCxxPlatformFlavorDomain;
private final CxxPlatform defaultCxxPlatform;
private final CodeSignIdentityStore codeSignIdentityStore;
private final ProvisioningProfileStore provisioningProfileStore;
private final AppleDebugFormat defaultDebugFormat;
public AppleLibraryDescription(
CxxLibraryDescription delegate,
SwiftLibraryDescription swiftDelegate,
FlavorDomain<AppleCxxPlatform> appleCxxPlatformFlavorDomain,
CxxPlatform defaultCxxPlatform,
CodeSignIdentityStore codeSignIdentityStore,
ProvisioningProfileStore provisioningProfileStore,
AppleDebugFormat defaultDebugFormat) {
this.delegate = delegate;
this.swiftDelegate = swiftDelegate;
this.appleCxxPlatformFlavorDomain = appleCxxPlatformFlavorDomain;
this.defaultCxxPlatform = defaultCxxPlatform;
this.codeSignIdentityStore = codeSignIdentityStore;
this.provisioningProfileStore = provisioningProfileStore;
this.defaultDebugFormat = defaultDebugFormat;
}
@Override
public BuildRuleType getBuildRuleType() {
return TYPE;
}
@Override
public AppleLibraryDescription.Arg createUnpopulatedConstructorArg() {
return new Arg();
}
@Override
public boolean hasFlavors(ImmutableSet<Flavor> flavors) {
return FluentIterable.from(flavors).allMatch(SUPPORTED_FLAVORS::contains) ||
delegate.hasFlavors(flavors) ||
swiftDelegate.hasFlavors(flavors);
}
@Override
public <A extends AppleLibraryDescription.Arg> BuildRule createBuildRule(
TargetGraph targetGraph,
BuildRuleParams params,
BuildRuleResolver resolver,
A args) throws NoSuchBuildTargetException {
Optional<Map.Entry<Flavor, Type>> type = LIBRARY_TYPE.getFlavorAndValue(
params.getBuildTarget());
if (type.isPresent() && type.get().getValue().equals(Type.FRAMEWORK)) {
return createFrameworkBundleBuildRule(targetGraph, params, resolver, args);
} else {
return createLibraryBuildRule(
targetGraph,
params,
resolver,
args,
args.linkStyle,
Optional.empty(),
ImmutableSet.of());
}
}
private <A extends Arg> BuildRule createFrameworkBundleBuildRule(
TargetGraph targetGraph,
BuildRuleParams params,
BuildRuleResolver resolver,
A args) throws NoSuchBuildTargetException {
if (!args.infoPlist.isPresent()) {
throw new HumanReadableException(
"Cannot create framework for apple_library '%s':\n" +
"No value specified for 'info_plist' attribute.",
params.getBuildTarget().getUnflavoredBuildTarget());
}
if (!AppleDescriptions.INCLUDE_FRAMEWORKS.getValue(params.getBuildTarget()).isPresent()) {
return resolver.requireRule(
params.getBuildTarget().withAppendedFlavors(
AppleDescriptions.INCLUDE_FRAMEWORKS_FLAVOR));
}
AppleDebugFormat debugFormat = AppleDebugFormat.FLAVOR_DOMAIN
.getValue(params.getBuildTarget()).orElse(defaultDebugFormat);
if (!params.getBuildTarget().getFlavors().contains(debugFormat.getFlavor())) {
return resolver.requireRule(
params.getBuildTarget().withAppendedFlavors(debugFormat.getFlavor()));
}
return AppleDescriptions.createAppleBundle(
delegate.getCxxPlatforms(),
defaultCxxPlatform,
appleCxxPlatformFlavorDomain,
targetGraph,
params,
resolver,
codeSignIdentityStore,
provisioningProfileStore,
params.getBuildTarget(),
Either.ofLeft(AppleBundleExtension.FRAMEWORK),
Optional.empty(),
args.infoPlist.get(),
args.infoPlistSubstitutions,
args.deps,
args.tests,
debugFormat);
}
/**
* @param targetGraph The target graph.
* @param bundleLoader The binary in which the current library will be (dynamically) loaded into.
* Only valid when building a shared library with MACH_O_BUNDLE link type.
*/
public <A extends AppleNativeTargetDescriptionArg> BuildRule createLibraryBuildRule(
TargetGraph targetGraph,
BuildRuleParams params,
BuildRuleResolver resolver,
A args,
Optional<Linker.LinkableDepType> linkableDepType,
Optional<SourcePath> bundleLoader,
ImmutableSet<BuildTarget> blacklist) throws NoSuchBuildTargetException {
Optional<BuildRule> swiftCompanionBuildRule = swiftDelegate.createCompanionBuildRule(
targetGraph, params, resolver, args);
if (swiftCompanionBuildRule.isPresent()) {
// when creating a swift target, there is no need to proceed with apple binary rules,
// otherwise, add this swift rule as a dependency.
if (isSwiftTarget(params.getBuildTarget())) {
return swiftCompanionBuildRule.get();
} else {
args.exportedDeps = ImmutableSortedSet.<BuildTarget>naturalOrder()
.addAll(args.exportedDeps)
.add(swiftCompanionBuildRule.get().getBuildTarget())
.build();
params = params.appendExtraDeps(ImmutableSet.of(swiftCompanionBuildRule.get()));
}
}
// We explicitly remove strip flavor from params to make sure rule
// has the same output regardless if we will strip or not.
Optional<StripStyle> flavoredStripStyle =
StripStyle.FLAVOR_DOMAIN.getValue(params.getBuildTarget());
params = CxxStrip.removeStripStyleFlavorInParams(params, flavoredStripStyle);
SourcePathResolver pathResolver = new SourcePathResolver(resolver);
BuildRule unstrippedBinaryRule = requireUnstrippedBuildRule(
params,
resolver,
args,
linkableDepType,
bundleLoader,
blacklist,
pathResolver);
if (!shouldWrapIntoDebuggableBinary(params.getBuildTarget(), unstrippedBinaryRule)) {
return unstrippedBinaryRule;
}
// If we built a multiarch binary, we can just use the strip tool from any platform.
// We pick the platform in this odd way due to FlavorDomain's restriction of allowing only one
// matching flavor in the build target.
CxxPlatform representativePlatform =
delegate.getCxxPlatforms().getValue(
Iterables.getFirst(
Sets.intersection(
delegate.getCxxPlatforms().getFlavors(),
params.getBuildTarget().getFlavors()),
defaultCxxPlatform.getFlavor()));
BuildRule strippedBinaryRule = CxxDescriptionEnhancer.createCxxStripRule(
CxxStrip.restoreStripStyleFlavorInParams(params, flavoredStripStyle),
resolver,
representativePlatform.getStrip(),
flavoredStripStyle.orElse(StripStyle.NON_GLOBAL_SYMBOLS),
pathResolver,
unstrippedBinaryRule);
return AppleDescriptions.createAppleDebuggableBinary(
CxxStrip.restoreStripStyleFlavorInParams(params, flavoredStripStyle),
resolver,
strippedBinaryRule,
(ProvidesLinkedBinaryDeps) unstrippedBinaryRule,
AppleDebugFormat.FLAVOR_DOMAIN.getValue(params.getBuildTarget()).orElse(defaultDebugFormat),
delegate.getCxxPlatforms(),
delegate.getDefaultCxxPlatform(),
appleCxxPlatformFlavorDomain);
}
private <A extends AppleNativeTargetDescriptionArg> BuildRule requireUnstrippedBuildRule(
BuildRuleParams params,
BuildRuleResolver resolver,
A args,
Optional<Linker.LinkableDepType> linkableDepType,
Optional<SourcePath> bundleLoader,
ImmutableSet<BuildTarget> blacklist,
SourcePathResolver pathResolver) throws NoSuchBuildTargetException {
Optional<MultiarchFileInfo> multiarchFileInfo =
MultiarchFileInfos.create(appleCxxPlatformFlavorDomain, params.getBuildTarget());
if (multiarchFileInfo.isPresent()) {
ImmutableSortedSet.Builder<BuildRule> thinRules = ImmutableSortedSet.naturalOrder();
for (BuildTarget thinTarget : multiarchFileInfo.get().getThinTargets()) {
thinRules.add(
requireSingleArchUnstrippedBuildRule(
params.copyWithBuildTarget(thinTarget),
resolver,
args,
linkableDepType,
bundleLoader,
blacklist,
pathResolver));
}
return MultiarchFileInfos.requireMultiarchRule(
// In the same manner that debug flavors are omitted from single-arch constituents, they
// are omitted here as well.
params.copyWithBuildTarget(
params.getBuildTarget().withoutFlavors(AppleDebugFormat.FLAVOR_DOMAIN.getFlavors())),
resolver,
multiarchFileInfo.get(),
thinRules.build());
} else {
return requireSingleArchUnstrippedBuildRule(
params,
resolver,
args,
linkableDepType,
bundleLoader,
blacklist,
pathResolver);
}
}
private <A extends AppleNativeTargetDescriptionArg> BuildRule
requireSingleArchUnstrippedBuildRule(
BuildRuleParams params,
BuildRuleResolver resolver,
A args,
Optional<Linker.LinkableDepType> linkableDepType,
Optional<SourcePath> bundleLoader,
ImmutableSet<BuildTarget> blacklist,
SourcePathResolver pathResolver) throws NoSuchBuildTargetException {
CxxLibraryDescription.Arg delegateArg = delegate.createUnpopulatedConstructorArg();
AppleDescriptions.populateCxxLibraryDescriptionArg(
pathResolver,
delegateArg,
args,
params.getBuildTarget());
// remove all debug format related flavors from cxx rule so it always ends up in the same output
BuildTarget unstrippedTarget = params.getBuildTarget()
.withoutFlavors(AppleDebugFormat.FLAVOR_DOMAIN.getFlavors());
Optional<BuildRule> existingRule = resolver.getRuleOptional(unstrippedTarget);
if (existingRule.isPresent()) {
return existingRule.get();
} else {
BuildRule rule = delegate.createBuildRule(
params.copyWithBuildTarget(unstrippedTarget),
resolver,
delegateArg,
linkableDepType,
bundleLoader,
blacklist);
return resolver.addToIndex(rule);
}
}
private boolean shouldWrapIntoDebuggableBinary(BuildTarget buildTarget, BuildRule buildRule) {
if (!AppleDebugFormat.FLAVOR_DOMAIN.getValue(buildTarget).isPresent()) {
return false;
}
if (!buildTarget.getFlavors().contains(CxxDescriptionEnhancer.SHARED_FLAVOR) &&
!buildTarget.getFlavors().contains(CxxDescriptionEnhancer.MACH_O_BUNDLE_FLAVOR)) {
return false;
}
return AppleDebuggableBinary.isBuildRuleDebuggable(buildRule);
}
@Override
public <A extends Arg, U> Optional<U> createMetadata(
BuildTarget buildTarget,
BuildRuleResolver resolver,
A args,
Class<U> metadataClass) throws NoSuchBuildTargetException {
if (!metadataClass.isAssignableFrom(FrameworkDependencies.class) ||
!buildTarget.getFlavors().contains(AppleDescriptions.FRAMEWORK_FLAVOR)) {
CxxLibraryDescription.Arg delegateArg = delegate.createUnpopulatedConstructorArg();
AppleDescriptions.populateCxxLibraryDescriptionArg(
new SourcePathResolver(resolver),
delegateArg,
args,
buildTarget);
return delegate.createMetadata(buildTarget, resolver, delegateArg, metadataClass);
}
Optional<Flavor> cxxPlatformFlavor = delegate.getCxxPlatforms().getFlavor(buildTarget);
Preconditions.checkState(
cxxPlatformFlavor.isPresent(),
"Could not find cxx platform in:\n%s",
Joiner.on(", ").join(buildTarget.getFlavors()));
ImmutableSet.Builder<SourcePath> sourcePaths = ImmutableSet.builder();
for (BuildTarget dep : args.deps) {
Optional<FrameworkDependencies> frameworks =
resolver.requireMetadata(
BuildTarget.builder(dep)
.addFlavors(AppleDescriptions.FRAMEWORK_FLAVOR)
.addFlavors(AppleDescriptions.NO_INCLUDE_FRAMEWORKS_FLAVOR)
.addFlavors(cxxPlatformFlavor.get())
.build(),
FrameworkDependencies.class);
if (frameworks.isPresent()) {
sourcePaths.addAll(frameworks.get().getSourcePaths());
}
}
// Not all parts of Buck use require yet, so require the rule here so it's available in the
// resolver for the parts that don't.
resolver.requireRule(buildTarget);
sourcePaths.add(new BuildTargetSourcePath(buildTarget));
return Optional.of(metadataClass.cast(FrameworkDependencies.of(sourcePaths.build())));
}
@Override
public ImmutableSortedSet<Flavor> addImplicitFlavors(
ImmutableSortedSet<Flavor> argDefaultFlavors) {
// Use defaults.apple_library if present, but fall back to defaults.cxx_library otherwise.
return delegate.addImplicitFlavorsForRuleTypes(
argDefaultFlavors,
TYPE,
CxxLibraryDescription.TYPE);
}
@Override
public Iterable<BuildTarget> findDepsForTargetFromConstructorArgs(
final BuildTarget buildTarget,
final CellPathResolver cellRoots,
final AppleLibraryDescription.Arg constructorArg) {
return findDepsForTargetFromConstructorArgs(
buildTarget,
cellRoots,
(AppleNativeTargetDescriptionArg) constructorArg);
}
public Iterable<BuildTarget> findDepsForTargetFromConstructorArgs(
final BuildTarget buildTarget,
final CellPathResolver cellRoots,
final AppleNativeTargetDescriptionArg constructorArg) {
return delegate.findDepsForTargetFromConstructorArgs(
buildTarget,
cellRoots,
constructorArg);
}
public static boolean isSharedLibraryTarget(BuildTarget target) {
return target.getFlavors().contains(CxxDescriptionEnhancer.SHARED_FLAVOR);
}
@SuppressFieldNotInitialized
public static class Arg extends AppleNativeTargetDescriptionArg {
public Optional<SourcePath> infoPlist;
public ImmutableMap<String, String> infoPlistSubstitutions = ImmutableMap.of();
}
}
| illicitonion/buck | src/com/facebook/buck/apple/AppleLibraryDescription.java | Java | apache-2.0 | 18,900 |
/*
* Copyright 2014-2015 See AUTHORS file.
*
* 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.kotcrab.vis.ui.widget;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.utils.FocusListener;
import com.badlogic.gdx.utils.Array;
import com.kotcrab.vis.ui.InputValidator;
import com.kotcrab.vis.ui.util.Validators;
/**
* Text field that input can be validated by custom input validators.
* @author Kotcrab
* @see InputValidator
* @see Validators
*/
public class VisValidatableTextField extends VisTextField {
private Array<InputValidator> validators = new Array<InputValidator>();
private boolean validationEnabled = true;
private LastValidFocusListener restoreFocusListener;
private boolean restoreLastValid = false;
private String lastValid;
public VisValidatableTextField () {
super();
init();
}
public VisValidatableTextField (String text) {
super(text);
init();
}
public VisValidatableTextField (String text, String styleName) {
super(text, styleName);
init();
}
public VisValidatableTextField (String text, VisTextFieldStyle style) {
super(text, style);
init();
}
public VisValidatableTextField (InputValidator validator) {
super();
addValidator(validator);
init();
}
public VisValidatableTextField (InputValidator... validators) {
super();
for (InputValidator validator : validators)
addValidator(validator);
init();
}
public VisValidatableTextField (boolean restoreLastValid, InputValidator validator) {
super();
addValidator(validator);
init();
setRestoreLastValid(restoreLastValid);
}
public VisValidatableTextField (boolean restoreLastValid, InputValidator... validators) {
super();
for (InputValidator validator : validators)
addValidator(validator);
init();
setRestoreLastValid(restoreLastValid);
}
private void init () {
setProgrammaticChangeEvents(true);
}
@Override
void beforeChangeEventFired () {
validateInput();
}
@Override
public void setText (String str) {
super.setText(str);
validateInput();
}
public void validateInput () {
if (validationEnabled) {
for (InputValidator validator : validators) {
if (validator.validateInput(getText()) == false) {
setInputValid(false);
return;
}
}
}
// validation not enabled or validators does not returned false (input was valid)
setInputValid(true);
}
public void addValidator (InputValidator validator) {
validators.add(validator);
validateInput();
}
public Array<InputValidator> getValidators () {
return validators;
}
public boolean isValidationEnabled () {
return validationEnabled;
}
/**
* Enables or disables validation, after changing this setting validateInput() is called, if validationEnabled == false then
* field is marked as valid otherwise standard validation is performed
* @param validationEnabled enable or disable validation
*/
public void setValidationEnabled (boolean validationEnabled) {
this.validationEnabled = validationEnabled;
validateInput();
}
public boolean isRestoreLastValid () {
return restoreLastValid;
}
/**
* If true this field will automatically restore text before edition stared if it loses keyboard focus while field is in invalid text.
* This can't be called while field is selected, doing so will result in IllegalStateException. Default is false.
*/
public void setRestoreLastValid (boolean restoreLastValid) {
if (hasSelection)
throw new IllegalStateException("Last valid text restore can't be changed while filed has selection");
this.restoreLastValid = restoreLastValid;
if (restoreLastValid) {
if (restoreFocusListener == null) restoreFocusListener = new LastValidFocusListener();
addListener(restoreFocusListener);
} else
removeListener(restoreFocusListener);
}
public void restoreLastValidText () {
if (restoreLastValid == false)
throw new IllegalStateException("Restore last valid is not enabled, see #setRestoreLastValid(boolean)");
//use super.setText to skip input validation and do not fire programmatic change event
VisValidatableTextField.super.setText(lastValid);
setInputValid(true);
}
private class LastValidFocusListener extends FocusListener {
@Override
public void keyboardFocusChanged (FocusEvent event, Actor actor, boolean focused) {
if (focused && restoreLastValid)
lastValid = getText();
if (focused == false && isInputValid() == false && restoreLastValid) {
restoreLastValidText();
}
}
}
}
| StQuote/VisEditor | UI/src/com/kotcrab/vis/ui/widget/VisValidatableTextField.java | Java | apache-2.0 | 5,025 |
/**
* Copyright (c) 2015 Intel Corporation
*
* 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 org.trustedanalytics.servicebroker.hdfs.integration.config;
import java.io.IOException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.trustedanalytics.servicebroker.framework.kerberos.KerberosProperties;
@Configuration
public class KerberosLocalConfiguration {
@Bean
@Profile("integration-test")
public KerberosProperties getKerberosProperties() throws IOException {
return new KerberosProperties("kdc", "realm", "cacert", false);
}
}
| trustedanalytics/hdfs-broker | src/test/java/org/trustedanalytics/servicebroker/hdfs/integration/config/KerberosLocalConfiguration.java | Java | apache-2.0 | 1,197 |
import {Injectable} from "@angular/core";
import {Http} from "@angular/http";
import {Observable} from "rxjs/Observable";
import {BaseService} from "./base-service";
import {Note} from "../classes/note";
import {Status} from "../classes/status";
@Injectable()
export class NoteService extends BaseService {
constructor(protected http: Http) {
super(http);
}
private noteUrl = "api/note/";
getAllNotes() : Observable<Note[]> {
return(this.http.get(this.noteUrl)
.map(this.extractData)
.catch(this.handleError));
}
getNoteByNoteId(noteId: number) : Observable<Note> {
return(this.http.get(this.noteUrl + noteId)
.map(this.extractData)
.catch(this.handleError));
}
getNotesByNoteApplicationId(noteApplicationId: number) : Observable<Note[]> {
return(this.http.get(this.noteUrl + "?noteApplicationId=" + noteApplicationId)
.map(this.extractData)
.catch(this.handleError));
}
getNotesByNoteProspectId(noteProspectId: number) : Observable<Note[]> {
return(this.http.get(this.noteUrl + noteProspectId)
.map(this.extractData)
.catch(this.handleError));
}
getNotesByNoteNoteTypeId(noteNoteTypeId: number) : Observable<Note[]> {
return(this.http.get(this.noteUrl + noteNoteTypeId)
.map(this.extractData)
.catch(this.handleError));
}
getNotesByBridgeStaffId(noteBridgeStaffId: string) : Observable<Note[]> {
return(this.http.get(this.noteUrl + noteBridgeStaffId)
.map(this.extractData)
.catch(this.handleError));
}
getNotesByNoteDateRange(startDate: string, endDate: string) : Observable<Note[]> {
return (this.http.get(this.noteUrl + startDate + endDate)
.map(this.extractData)
.catch(this.handleError));
}
createNote(note: Note) : Observable<Status> {
return(this.http.post(this.noteUrl, note)
.map(this.extractMessage)
.catch(this.handleError));
}
} | kdilts/aaaa-capstone | app/services/note-service.ts | TypeScript | apache-2.0 | 1,834 |
/*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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://aws.amazon.com/apache2.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.
*/
#include <aws/route53domains/model/OperationStatus.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>
using namespace Aws::Utils;
namespace Aws
{
namespace Route53Domains
{
namespace Model
{
namespace OperationStatusMapper
{
static const int SUBMITTED_HASH = HashingUtils::HashString("SUBMITTED");
static const int IN_PROGRESS_HASH = HashingUtils::HashString("IN_PROGRESS");
static const int ERROR__HASH = HashingUtils::HashString("ERROR");
static const int SUCCESSFUL_HASH = HashingUtils::HashString("SUCCESSFUL");
static const int FAILED_HASH = HashingUtils::HashString("FAILED");
OperationStatus GetOperationStatusForName(const Aws::String& name)
{
int hashCode = HashingUtils::HashString(name.c_str());
if (hashCode == SUBMITTED_HASH)
{
return OperationStatus::SUBMITTED;
}
else if (hashCode == IN_PROGRESS_HASH)
{
return OperationStatus::IN_PROGRESS;
}
else if (hashCode == ERROR__HASH)
{
return OperationStatus::ERROR_;
}
else if (hashCode == SUCCESSFUL_HASH)
{
return OperationStatus::SUCCESSFUL;
}
else if (hashCode == FAILED_HASH)
{
return OperationStatus::FAILED;
}
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
overflowContainer->StoreOverflow(hashCode, name);
return static_cast<OperationStatus>(hashCode);
}
return OperationStatus::NOT_SET;
}
Aws::String GetNameForOperationStatus(OperationStatus enumValue)
{
switch(enumValue)
{
case OperationStatus::SUBMITTED:
return "SUBMITTED";
case OperationStatus::IN_PROGRESS:
return "IN_PROGRESS";
case OperationStatus::ERROR_:
return "ERROR";
case OperationStatus::SUCCESSFUL:
return "SUCCESSFUL";
case OperationStatus::FAILED:
return "FAILED";
default:
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
}
return {};
}
}
} // namespace OperationStatusMapper
} // namespace Model
} // namespace Route53Domains
} // namespace Aws
| cedral/aws-sdk-cpp | aws-cpp-sdk-route53domains/source/model/OperationStatus.cpp | C++ | apache-2.0 | 3,277 |
/*------------------------------------------------------------------------------
* COPYRIGHT Ericsson 2015
*
* The copyright to the computer program(s) herein is the property of
* Ericsson Inc. The programs may be used and/or copied only with written
* permission from Ericsson Inc. or in accordance with the terms and
* conditions stipulated in the agreement/contract under which the
* program(s) have been supplied.
*----------------------------------------------------------------------------*/
package com.ericsson.jigsaw.redis.replication.impl;
import java.io.IOException;
import java.io.StringReader;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.Response;
import redis.clients.jedis.exceptions.JedisConnectionException;
import com.ericsson.jigsaw.redis.JedisTemplate;
import com.ericsson.jigsaw.redis.JedisTemplate.JedisAction;
import com.ericsson.jigsaw.redis.JedisTemplate.PipelineActionNoResult;
import com.ericsson.jigsaw.redis.replication.RedisOp;
import com.ericsson.jigsaw.redis.replication.ReplicationConstants;
public class ReplicaUtiils {
private static Logger logger = LoggerFactory.getLogger(ReplicaUtiils.class);
private static Map<String, Class<?>[]> pipelineParametersCache = new ConcurrentHashMap<String, Class<?>[]>();
private static Map<String, Method> pipelineMethodCache = new ConcurrentHashMap<String, Method>();
private static Object paramLock = new Object();
private static Object methodLock = new Object();
public static boolean isSyncedUp(final JedisTemplate template, HostAndPort address) {
try {
checkHealthy(template);
} catch (Exception e) {
logger.warn("check healthy fail: " + e.getMessage());
logger.debug("details:", e);
return false;
}
final Properties infoProperties = getInfoProperties(template);
final boolean isMaster = "master".equals(infoProperties.getProperty("role"));
if (isMaster) {
final HostAndPort masterAddress = template.getJedisPool().getAddress();
logger.info("[{}] is a master, check the slave[{}] syncup status.", masterAddress, address);
final long masterOffset = Long.valueOf(infoProperties.getProperty("master_repl_offset"));
final List<String> slaves = getSlaves(infoProperties);
for (String slave : slaves) {
final String[] split = slave.split(",");
final String host = split[0].split("=")[1];
final Integer port = Integer.valueOf(split[1].split("=")[1]);
if (address.getHost().equals(host) && (address.getPort() == port)) {
final String state = split[2].split("=")[1];
final long slaveOffset = Long.valueOf(split[3].split("=")[1]);
logger.info("slave[{}] state is {}", address, state);
logger.info("master[{}] offset={}, slave[{}] offset={}, gap={}", masterAddress, masterOffset,
address, slaveOffset, masterOffset - slaveOffset);
final boolean online = "online".equals(state);
final boolean aligned = masterOffset == slaveOffset;
return online && aligned;
}
}
logger.info("[{}] is not a slave of [{}] yet", address, masterAddress);
return false;
}
final String masterStatus = infoProperties.getProperty("master_link_status");
logger.info("master status: " + masterStatus);
final boolean masterUp = "up".equals(masterStatus);
final String progress = infoProperties.getProperty("master_sync_in_progress");
final boolean syncDone = "0".equals(progress);
if (masterUp) {
if (syncDone) {
logger.info("full sync up is done");
} else {
logger.info("sync up is in progress, left: " + infoProperties.getProperty("master_sync_left_bytes")
+ " byte");
}
}
final boolean syncedUp = masterUp && syncDone;
return syncedUp;
}
public static Properties getInfoProperties(final JedisTemplate template) {
final String info = template.execute(new JedisAction<String>() {
@Override
public String action(Jedis jedis) {
return jedis.info("Replication");
}
});
final Properties infoProperties = new Properties();
try {
infoProperties.load(new StringReader(info));
} catch (IOException e) {
logger.error("loading redis info got error", e);
}
return infoProperties;
}
private static List<String> getSlaves(Properties properties) {
final List<String> slaves = new ArrayList<String>();
for (String key : properties.stringPropertyNames()) {
if ((key != null) && key.startsWith("slave")) {
slaves.add(properties.getProperty(key));
}
}
return slaves;
}
public static void checkHealthy(final JedisTemplate template) {
final String status = template.ping();
if (!"PONG".equals(status)) {
throw new JedisConnectionException("cannot get PONG by PING from redis");
}
}
public static void replay(JedisTemplate template, final List<RedisOp> operations) {
final List<Response<?>> pinelineResp = new ArrayList<Response<?>>();
template.execute(new PipelineActionNoResult() {
@Override
public void action(Pipeline pipeline) {
for (RedisOp operation : operations) {
try {
final String command = operation.getCmd();
final Object[] args = operation.getArgs().toArray();
final List<String> parameterTypes = operation.getParamTypes();
Class<?>[] typeClassList = forNames(parameterTypes);
normalize(typeClassList, args);
Method method = getMethod(command, typeClassList);
method.setAccessible(true);
pinelineResp.add((Response<?>) method.invoke(pipeline, args));
} catch (Exception e) {
logger.error("replay invoke error, skip it: {}", operation);
logger.debug("details:", e);
continue;
}
}
}
});
for (Response<?> response : pinelineResp) {
response.get();
}
}
public static boolean isMaster(JedisTemplate template) {
final Properties infoProperties = getInfoProperties(template);
return "master".equals(infoProperties.getProperty("role"));
}
public static boolean isMasterOf(JedisTemplate template, HostAndPort address) {
final HostAndPort masterAddress = template.getJedisPool().getAddress();
final Properties infoProperties = getInfoProperties(template);
final List<String> slaves = getSlaves(infoProperties);
for (String slave : slaves) {
logger.info("[{}] is master of [{}]", masterAddress, slave);
final String[] split = slave.split(",");
final String host = split[0].split("=")[1];
final Integer port = Integer.valueOf(split[1].split("=")[1]);
if (address.getHost().equals(host) && (address.getPort() == port)) {
return true;
}
}
return false;
}
private static Method getMethod(String methodName, Class<?>[] typeClassList) throws SecurityException,
NoSuchMethodException {
final String methodKey = getMethodKey(methodName, typeClassList);
Method method = pipelineMethodCache.get(methodKey);
if (method == null) {
synchronized (methodLock) {
method = pipelineMethodCache.get(methodKey);
if (method == null) {
method = Pipeline.class.getMethod(methodName, typeClassList);
pipelineMethodCache.put(methodKey, method);
}
}
}
return method;
}
private static String getMethodKey(String methodName, Class<?>[] typeClassList) {
return methodName + ":" + getParametersKey(typeClassList);
}
private static String getParametersKey(Class<?>[] typeClassList) {
StringBuilder keyBuilder = new StringBuilder();
for (Class<?> type : typeClassList) {
keyBuilder.append(type.getName());
}
return keyBuilder.toString();
}
private static Class<?>[] forNames(List<String> parameterTypes) {
final String parametersKey = getParametersKey(parameterTypes);
Class<?>[] typeClassList = pipelineParametersCache.get(parametersKey);
if (typeClassList == null) {
synchronized (paramLock) {
typeClassList = pipelineParametersCache.get(parametersKey);
if (typeClassList == null) {
typeClassList = new Class<?>[parameterTypes.size()];
for (int i = 0; i < parameterTypes.size(); i++) {
try {
typeClassList[i] = Class.forName(parameterTypes.get(i));
} catch (ClassNotFoundException e) {
typeClassList[i] = ReplicationConstants.PRIMITIVE_CLASS_MAP.get(parameterTypes.get(i));
}
}
pipelineParametersCache.put(parametersKey, typeClassList);
}
}
}
return typeClassList;
}
private static String getParametersKey(List<String> parameterTypes) {
StringBuilder keyBuilder = new StringBuilder();
for (String type : parameterTypes) {
keyBuilder.append(type);
}
return keyBuilder.toString();
}
private static void normalize(Class<?>[] typeClassList, Object[] args) {
for (int i = 0; i < typeClassList.length; i++) {
if (typeClassList[i].isArray()) {
List<?> argList = (List<?>) args[i];
final Object argArray = Array.newInstance(typeClassList[i].getComponentType(), argList.size());
for (int j = 0; j < argList.size(); j++) {
Array.set(argArray, j, argList.get(j));
}
args[i] = argArray;
}
}
}
}
| supercyc/jigsaw-redis | src/main/java/com/ericsson/jigsaw/redis/replication/impl/ReplicaUtiils.java | Java | apache-2.0 | 10,969 |
/* * Copyright (c) 2012-2013, The Tor Project, Inc. */
/* See LICENSE for licensing information */
/**
* \file channeltls.c
* \brief channel_t concrete subclass using or_connection_t
**/
/*
* Define this so channel.h gives us things only channel_t subclasses
* should touch.
*/
#define TOR_CHANNEL_INTERNAL_
#include "or.h"
#include "channel.h"
#include "channeltls.h"
#include "circuitmux.h"
#include "circuitmux_ewma.h"
#include "config.h"
#include "connection.h"
#include "connection_or.h"
#include "control.h"
#include "relay.h"
#include "router.h"
#include "routerlist.h"
#define CHANNEL_CLOSE_FOR_ERROR channel_s::CHANNEL_CLOSE_FOR_ERROR
/** How many CELL_PADDING cells have we received, ever? */
uint64_t stats_n_padding_cells_processed = 0;
/** How many CELL_VERSIONS cells have we received, ever? */
uint64_t stats_n_versions_cells_processed = 0;
/** How many CELL_NETINFO cells have we received, ever? */
uint64_t stats_n_netinfo_cells_processed = 0;
/** How many CELL_VPADDING cells have we received, ever? */
uint64_t stats_n_vpadding_cells_processed = 0;
/** How many CELL_CERTS cells have we received, ever? */
uint64_t stats_n_certs_cells_processed = 0;
/** How many CELL_AUTH_CHALLENGE cells have we received, ever? */
uint64_t stats_n_auth_challenge_cells_processed = 0;
/** How many CELL_AUTHENTICATE cells have we received, ever? */
uint64_t stats_n_authenticate_cells_processed = 0;
/** How many CELL_AUTHORIZE cells have we received, ever? */
uint64_t stats_n_authorize_cells_processed = 0;
/** Active listener, if any */
channel_listener_t *channel_tls_listener = NULL;
/* Utility function declarations */
static void channel_tls_common_init(channel_tls_t *tlschan);
/* channel_tls_t method declarations */
static void channel_tls_close_method(channel_t *chan);
static const char * channel_tls_describe_transport_method(channel_t *chan);
static void channel_tls_free_method(channel_t *chan);
static int
channel_tls_get_remote_addr_method(channel_t *chan, tor_addr_t *addr_out);
static int
channel_tls_get_transport_name_method(channel_t *chan, char **transport_out);
static const char *
channel_tls_get_remote_descr_method(channel_t *chan, int flags);
static int channel_tls_has_queued_writes_method(channel_t *chan);
static int channel_tls_is_canonical_method(channel_t *chan, int req);
static int
channel_tls_matches_extend_info_method(channel_t *chan,
extend_info_t *extend_info);
static int channel_tls_matches_target_method(channel_t *chan,
const tor_addr_t *target);
static int channel_tls_write_cell_method(channel_t *chan,
cell_t *cell);
static int channel_tls_write_packed_cell_method(channel_t *chan,
packed_cell_t *packed_cell);
static int channel_tls_write_var_cell_method(channel_t *chan,
var_cell_t *var_cell);
/* channel_listener_tls_t method declarations */
static void channel_tls_listener_close_method(channel_listener_t *chan_l);
static const char *
channel_tls_listener_describe_transport_method(channel_listener_t *chan_l);
/** Handle incoming cells for the handshake stuff here rather than
* passing them on up. */
static void channel_tls_process_versions_cell(var_cell_t *cell,
channel_tls_t *tlschan);
static void channel_tls_process_netinfo_cell(cell_t *cell,
channel_tls_t *tlschan);
static void channel_tls_process_certs_cell(var_cell_t *cell,
channel_tls_t *tlschan);
static void channel_tls_process_auth_challenge_cell(var_cell_t *cell,
channel_tls_t *tlschan);
static void channel_tls_process_authenticate_cell(var_cell_t *cell,
channel_tls_t *tlschan);
static int command_allowed_before_handshake(uint8_t command);
static int enter_v3_handshake_with_cell(var_cell_t *cell,
channel_tls_t *tlschan);
/**
* Do parts of channel_tls_t initialization common to channel_tls_connect()
* and channel_tls_handle_incoming().
*/
static void
channel_tls_common_init(channel_tls_t *tlschan)
{
channel_t *chan;
tor_assert(tlschan);
chan = &(tlschan->base_);
channel_init(chan);
chan->magic = TLS_CHAN_MAGIC;
chan->state = CHANNEL_STATE_OPENING;
chan->close = channel_tls_close_method;
chan->describe_transport = channel_tls_describe_transport_method;
chan->free = channel_tls_free_method;
chan->get_remote_addr = channel_tls_get_remote_addr_method;
chan->get_remote_descr = channel_tls_get_remote_descr_method;
chan->get_transport_name = channel_tls_get_transport_name_method;
chan->has_queued_writes = channel_tls_has_queued_writes_method;
chan->is_canonical = channel_tls_is_canonical_method;
chan->matches_extend_info = channel_tls_matches_extend_info_method;
chan->matches_target = channel_tls_matches_target_method;
chan->write_cell = channel_tls_write_cell_method;
chan->write_packed_cell = channel_tls_write_packed_cell_method;
chan->write_var_cell = channel_tls_write_var_cell_method;
chan->cmux = circuitmux_alloc();
if (cell_ewma_enabled()) {
circuitmux_set_policy(chan->cmux, &ewma_policy);
}
}
/**
* Start a new TLS channel
*
* Launch a new OR connection to <b>addr</b>:<b>port</b> and expect to
* handshake with an OR with identity digest <b>id_digest</b>, and wrap
* it in a channel_tls_t.
*/
channel_t *
channel_tls_connect(const tor_addr_t *addr, uint16_t port,
const char *id_digest)
{
channel_tls_t *tlschan = (channel_tls_t *)tor_malloc_zero(sizeof(*tlschan));
channel_t *chan = &(tlschan->base_);
channel_tls_common_init(tlschan);
log_debug(LD_CHANNEL,
"In channel_tls_connect() for channel %p "
"(global id " U64_FORMAT ")",
tlschan,
U64_PRINTF_ARG(chan->global_identifier));
if (is_local_addr(addr)) {
log_debug(LD_CHANNEL,
"Marking new outgoing channel " U64_FORMAT " at %p as local",
U64_PRINTF_ARG(chan->global_identifier), chan);
channel_mark_local(chan);
} else {
log_debug(LD_CHANNEL,
"Marking new outgoing channel " U64_FORMAT " at %p as remote",
U64_PRINTF_ARG(chan->global_identifier), chan);
channel_mark_remote(chan);
}
channel_mark_outgoing(chan);
/* Set up or_connection stuff */
tlschan->conn = connection_or_connect(addr, port, id_digest, tlschan);
/* connection_or_connect() will fill in tlschan->conn */
if (!(tlschan->conn)) {
chan->reason_for_closing = CHANNEL_CLOSE_FOR_ERROR;
channel_change_state(chan, CHANNEL_STATE_ERROR);
goto err;
}
log_debug(LD_CHANNEL,
"Got orconn %p for channel with global id " U64_FORMAT,
tlschan->conn, U64_PRINTF_ARG(chan->global_identifier));
goto done;
err:
circuitmux_free(chan->cmux);
tor_free(tlschan);
chan = NULL;
done:
/* If we got one, we should register it */
if (chan) channel_register(chan);
return chan;
}
/**
* Return the current channel_tls_t listener
*
* Returns the current channel listener for incoming TLS connections, or
* NULL if none has been established
*/
channel_listener_t *
channel_tls_get_listener(void)
{
return channel_tls_listener;
}
/**
* Start a channel_tls_t listener if necessary
*
* Return the current channel_tls_t listener, or start one if we haven't yet,
* and return that.
*/
channel_listener_t *
channel_tls_start_listener(void)
{
channel_listener_t *listener;
if (!channel_tls_listener) {
listener = (channel_listener_t *)tor_malloc_zero(sizeof(*listener));
channel_init_listener(listener);
listener->state = CHANNEL_LISTENER_STATE_LISTENING;
listener->close = channel_tls_listener_close_method;
listener->describe_transport =
channel_tls_listener_describe_transport_method;
channel_tls_listener = listener;
log_debug(LD_CHANNEL,
"Starting TLS channel listener %p with global id " U64_FORMAT,
listener, U64_PRINTF_ARG(listener->global_identifier));
channel_listener_register(listener);
} else listener = channel_tls_listener;
return listener;
}
/**
* Free everything on shutdown
*
* Not much to do here, since channel_free_all() takes care of a lot, but let's
* get rid of the listener.
*/
void
channel_tls_free_all(void)
{
channel_listener_t *old_listener = NULL;
log_debug(LD_CHANNEL,
"Shutting down TLS channels...");
if (channel_tls_listener) {
/*
* When we close it, channel_tls_listener will get nulled out, so save
* a pointer so we can free it.
*/
old_listener = channel_tls_listener;
log_debug(LD_CHANNEL,
"Closing channel_tls_listener with ID " U64_FORMAT
" at %p.",
U64_PRINTF_ARG(old_listener->global_identifier),
old_listener);
channel_listener_unregister(old_listener);
channel_listener_mark_for_close(old_listener);
channel_listener_free(old_listener);
tor_assert(channel_tls_listener == NULL);
}
log_debug(LD_CHANNEL,
"Done shutting down TLS channels");
}
/**
* Create a new channel around an incoming or_connection_t
*/
channel_t *
channel_tls_handle_incoming(or_connection_t *orconn)
{
channel_tls_t *tlschan = (channel_tls_t *)tor_malloc_zero(sizeof(*tlschan));
channel_t *chan = &(tlschan->base_);
tor_assert(orconn);
tor_assert(!(orconn->chan));
channel_tls_common_init(tlschan);
/* Link the channel and orconn to each other */
tlschan->conn = orconn;
orconn->chan = tlschan;
if (is_local_addr(&(TO_CONN(orconn)->addr))) {
log_debug(LD_CHANNEL,
"Marking new incoming channel " U64_FORMAT " at %p as local",
U64_PRINTF_ARG(chan->global_identifier), chan);
channel_mark_local(chan);
} else {
log_debug(LD_CHANNEL,
"Marking new incoming channel " U64_FORMAT " at %p as remote",
U64_PRINTF_ARG(chan->global_identifier), chan);
channel_mark_remote(chan);
}
channel_mark_incoming(chan);
/* Register it */
channel_register(chan);
return chan;
}
/*********
* Casts *
********/
/**
* Cast a channel_tls_t to a channel_t.
*/
channel_t *
channel_tls_to_base(channel_tls_t *tlschan)
{
if (!tlschan) return NULL;
return &(tlschan->base_);
}
/**
* Cast a channel_t to a channel_tls_t, with appropriate type-checking
* asserts.
*/
channel_tls_t *
channel_tls_from_base(channel_t *chan)
{
if (!chan) return NULL;
// Fix me: Assertation failed
// tor_assert(chan->magic == TLS_CHAN_MAGIC);
return (channel_tls_t *)(chan);
}
/********************************************
* Method implementations for channel_tls_t *
*******************************************/
/**
* Close a channel_tls_t
*
* This implements the close method for channel_tls_t
*/
static void
channel_tls_close_method(channel_t *chan)
{
channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
tor_assert(tlschan);
if (tlschan->conn) connection_or_close_normally(tlschan->conn, 1);
else {
/* Weird - we'll have to change the state ourselves, I guess */
log_info(LD_CHANNEL,
"Tried to close channel_tls_t %p with NULL conn",
tlschan);
channel_change_state(chan, CHANNEL_STATE_ERROR);
}
}
/**
* Describe the transport for a channel_tls_t
*
* This returns the string "TLS channel on connection <id>" to the upper
* layer.
*/
static const char *
channel_tls_describe_transport_method(channel_t *chan)
{
static char *buf = NULL;
uint64_t id;
channel_tls_t *tlschan;
const char *rv = NULL;
tor_assert(chan);
tlschan = BASE_CHAN_TO_TLS(chan);
if (tlschan->conn) {
id = TO_CONN(tlschan->conn)->global_identifier;
if (buf) tor_free(buf);
tor_asprintf(&buf,
"TLS channel (connection " U64_FORMAT ")",
U64_PRINTF_ARG(id));
rv = buf;
} else {
rv = "TLS channel (no connection)";
}
return rv;
}
/**
* Free a channel_tls_t
*
* This is called by the generic channel layer when freeing a channel_tls_t;
* this happens either on a channel which has already reached
* CHANNEL_STATE_CLOSED or CHANNEL_STATE_ERROR from channel_run_cleanup() or
* on shutdown from channel_free_all(). In the latter case we might still
* have an orconn active (which connection_free_all() will get to later),
* so we should null out its channel pointer now.
*/
static void
channel_tls_free_method(channel_t *chan)
{
channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
tor_assert(tlschan);
if (tlschan->conn) {
tlschan->conn->chan = NULL;
tlschan->conn = NULL;
}
}
/**
* Get the remote address of a channel_tls_t
*
* This implements the get_remote_addr method for channel_tls_t; copy the
* remote endpoint of the channel to addr_out and return 1 (always
* succeeds for this transport).
*/
static int
channel_tls_get_remote_addr_method(channel_t *chan, tor_addr_t *addr_out)
{
int rv = 0;
channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
tor_assert(tlschan);
tor_assert(addr_out);
if (tlschan->conn) {
tor_addr_copy(addr_out, &(TO_CONN(tlschan->conn)->addr));
rv = 1;
} else tor_addr_make_unspec(addr_out);
return rv;
}
/**
* Get the name of the pluggable transport used by a channel_tls_t.
*
* This implements the get_transport_name for channel_tls_t. If the
* channel uses a pluggable transport, copy its name to
* <b>transport_out</b> and return 0. If the channel did not use a
* pluggable transport, return -1. */
static int
channel_tls_get_transport_name_method(channel_t *chan, char **transport_out)
{
channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
tor_assert(tlschan);
tor_assert(transport_out);
tor_assert(tlschan->conn);
if (!tlschan->conn->ext_or_transport)
return -1;
*transport_out = tor_strdup(tlschan->conn->ext_or_transport);
return 0;
}
/**
* Get endpoint description of a channel_tls_t
*
* This implements the get_remote_descr method for channel_tls_t; it returns
* a text description of the remote endpoint of the channel suitable for use
* in log messages. The req parameter is 0 for the canonical address or 1 for
* the actual address seen.
*/
static const char *
channel_tls_get_remote_descr_method(channel_t *chan, int flags)
{
#define MAX_DESCR_LEN 32
static char buf[MAX_DESCR_LEN + 1];
channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
connection_t *conn;
const char *answer = NULL;
char *addr_str;
tor_assert(tlschan);
if (tlschan->conn) {
conn = TO_CONN(tlschan->conn);
switch (flags) {
case 0:
/* Canonical address with port*/
tor_snprintf(buf, MAX_DESCR_LEN + 1,
"%s:%u", conn->address, conn->port);
answer = buf;
break;
case GRD_FLAG_ORIGINAL:
/* Actual address with port */
addr_str = tor_dup_addr(&(tlschan->conn->real_addr));
tor_snprintf(buf, MAX_DESCR_LEN + 1,
"%s:%u", addr_str, conn->port);
tor_free(addr_str);
answer = buf;
break;
case GRD_FLAG_ADDR_ONLY:
/* Canonical address, no port */
strlcpy(buf, conn->address, sizeof(buf));
answer = buf;
break;
case GRD_FLAG_ORIGINAL|GRD_FLAG_ADDR_ONLY:
/* Actual address, no port */
addr_str = tor_dup_addr(&(tlschan->conn->real_addr));
strlcpy(buf, addr_str, sizeof(buf));
tor_free(addr_str);
answer = buf;
break;
default:
/* Something's broken in channel.c */
tor_assert(1);
}
} else {
strlcpy(buf, "(No connection)", sizeof(buf));
answer = buf;
}
return answer;
}
/**
* Tell the upper layer if we have queued writes
*
* This implements the has_queued_writes method for channel_tls t_; it returns
* 1 iff we have queued writes on the outbuf of the underlying or_connection_t.
*/
static int
channel_tls_has_queued_writes_method(channel_t *chan)
{
size_t outbuf_len;
channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
tor_assert(tlschan);
if (!(tlschan->conn)) {
log_info(LD_CHANNEL,
"something called has_queued_writes on a tlschan "
"(%p with ID " U64_FORMAT " but no conn",
chan, U64_PRINTF_ARG(chan->global_identifier));
}
outbuf_len = (tlschan->conn != NULL) ?
connection_get_outbuf_len(TO_CONN(tlschan->conn)) :
0;
return (outbuf_len > 0);
}
/**
* Tell the upper layer if we're canonical
*
* This implements the is_canonical method for channel_tls_t; if req is zero,
* it returns whether this is a canonical channel, and if it is one it returns
* whether that can be relied upon.
*/
static int
channel_tls_is_canonical_method(channel_t *chan, int req)
{
int answer = 0;
channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
tor_assert(tlschan);
if (tlschan->conn) {
switch (req) {
case 0:
answer = tlschan->conn->is_canonical;
break;
case 1:
/*
* Is the is_canonical bit reliable? In protocols version 2 and up
* we get the canonical address from a NETINFO cell, but in older
* versions it might be based on an obsolete descriptor.
*/
answer = (tlschan->conn->link_proto >= 2);
break;
default:
/* This shouldn't happen; channel.c is broken if it does */
tor_assert(1);
}
}
/* else return 0 for tlschan->conn == NULL */
return answer;
}
/**
* Check if we match an extend_info_t
*
* This implements the matches_extend_info method for channel_tls_t; the upper
* layer wants to know if this channel matches an extend_info_t.
*/
static int
channel_tls_matches_extend_info_method(channel_t *chan,
extend_info_t *extend_info)
{
channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
tor_assert(tlschan);
tor_assert(extend_info);
/* Never match if we have no conn */
if (!(tlschan->conn)) {
log_info(LD_CHANNEL,
"something called matches_extend_info on a tlschan "
"(%p with ID " U64_FORMAT " but no conn",
chan, U64_PRINTF_ARG(chan->global_identifier));
return 0;
}
return (tor_addr_eq(&(extend_info->addr),
&(TO_CONN(tlschan->conn)->addr)) &&
(extend_info->port == TO_CONN(tlschan->conn)->port));
}
/**
* Check if we match a target address; return true iff we do.
*
* This implements the matches_target method for channel_tls t_; the upper
* layer wants to know if this channel matches a target address when extending
* a circuit.
*/
static int
channel_tls_matches_target_method(channel_t *chan,
const tor_addr_t *target)
{
channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
tor_assert(tlschan);
tor_assert(target);
/* Never match if we have no conn */
if (!(tlschan->conn)) {
log_info(LD_CHANNEL,
"something called matches_target on a tlschan "
"(%p with ID " U64_FORMAT " but no conn",
chan, U64_PRINTF_ARG(chan->global_identifier));
return 0;
}
return tor_addr_eq(&(tlschan->conn->real_addr), target);
}
/**
* Write a cell to a channel_tls_t
*
* This implements the write_cell method for channel_tls_t; given a
* channel_tls_t and a cell_t, transmit the cell_t.
*/
static int
channel_tls_write_cell_method(channel_t *chan, cell_t *cell)
{
channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
int written = 0;
tor_assert(tlschan);
tor_assert(cell);
if (tlschan->conn) {
connection_or_write_cell_to_buf(cell, tlschan->conn);
++written;
} else {
log_info(LD_CHANNEL,
"something called write_cell on a tlschan "
"(%p with ID " U64_FORMAT " but no conn",
chan, U64_PRINTF_ARG(chan->global_identifier));
}
return written;
}
/**
* Write a packed cell to a channel_tls_t
*
* This implements the write_packed_cell method for channel_tls_t; given a
* channel_tls_t and a packed_cell_t, transmit the packed_cell_t.
*/
static int
channel_tls_write_packed_cell_method(channel_t *chan,
packed_cell_t *packed_cell)
{
channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
size_t cell_network_size = get_cell_network_size(chan->wide_circ_ids);
int written = 0;
tor_assert(tlschan);
tor_assert(packed_cell);
if (tlschan->conn) {
connection_write_to_buf(packed_cell->body, cell_network_size,
TO_CONN(tlschan->conn));
/* This is where the cell is finished; used to be done from relay.c */
packed_cell_free(packed_cell);
++written;
} else {
log_info(LD_CHANNEL,
"something called write_packed_cell on a tlschan "
"(%p with ID " U64_FORMAT " but no conn",
chan, U64_PRINTF_ARG(chan->global_identifier));
}
return written;
}
/**
* Write a variable-length cell to a channel_tls_t
*
* This implements the write_var_cell method for channel_tls_t; given a
* channel_tls_t and a var_cell_t, transmit the var_cell_t.
*/
static int
channel_tls_write_var_cell_method(channel_t *chan, var_cell_t *var_cell)
{
channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
int written = 0;
tor_assert(tlschan);
tor_assert(var_cell);
if (tlschan->conn) {
connection_or_write_var_cell_to_buf(var_cell, tlschan->conn);
++written;
} else {
log_info(LD_CHANNEL,
"something called write_var_cell on a tlschan "
"(%p with ID " U64_FORMAT " but no conn",
chan, U64_PRINTF_ARG(chan->global_identifier));
}
return written;
}
/*************************************************
* Method implementations for channel_listener_t *
************************************************/
/**
* Close a channel_listener_t
*
* This implements the close method for channel_listener_t
*/
static void
channel_tls_listener_close_method(channel_listener_t *chan_l)
{
tor_assert(chan_l);
/*
* Listeners we just go ahead and change state through to CLOSED, but
* make sure to check if they're channel_tls_listener to NULL it out.
*/
if (chan_l == channel_tls_listener)
channel_tls_listener = NULL;
if (!(chan_l->state == CHANNEL_LISTENER_STATE_CLOSING ||
chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
chan_l->state == CHANNEL_LISTENER_STATE_ERROR)) {
channel_listener_change_state(chan_l, CHANNEL_LISTENER_STATE_CLOSING);
}
if (chan_l->incoming_list) {
SMARTLIST_FOREACH_BEGIN(chan_l->incoming_list,
channel_t *, ichan) {
channel_mark_for_close(ichan);
} SMARTLIST_FOREACH_END(ichan);
smartlist_free(chan_l->incoming_list);
chan_l->incoming_list = NULL;
}
if (!(chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
chan_l->state == CHANNEL_LISTENER_STATE_ERROR)) {
channel_listener_change_state(chan_l, CHANNEL_LISTENER_STATE_CLOSED);
}
}
/**
* Describe the transport for a channel_listener_t
*
* This returns the string "TLS channel (listening)" to the upper
* layer.
*/
static const char *
channel_tls_listener_describe_transport_method(channel_listener_t *chan_l)
{
tor_assert(chan_l);
return "TLS channel (listening)";
}
/*******************************************************
* Functions for handling events on an or_connection_t *
******************************************************/
/**
* Handle an orconn state change
*
* This function will be called by connection_or.c when the or_connection_t
* associated with this channel_tls_t changes state.
*/
void
channel_tls_handle_state_change_on_orconn(channel_tls_t *chan,
or_connection_t *conn,
uint8_t old_state,
uint8_t state)
{
channel_t *base_chan;
tor_assert(chan);
tor_assert(conn);
tor_assert(conn->chan == chan);
tor_assert(chan->conn == conn);
/* -Werror appeasement */
tor_assert(old_state == old_state);
base_chan = TLS_CHAN_TO_BASE(chan);
/* Make sure the base connection state makes sense - shouldn't be error,
* closed or listening. */
tor_assert(base_chan->state == CHANNEL_STATE_OPENING ||
base_chan->state == CHANNEL_STATE_OPEN ||
base_chan->state == CHANNEL_STATE_MAINT ||
base_chan->state == CHANNEL_STATE_CLOSING);
/* Did we just go to state open? */
if (state == OR_CONN_STATE_OPEN) {
/*
* We can go to CHANNEL_STATE_OPEN from CHANNEL_STATE_OPENING or
* CHANNEL_STATE_MAINT on this.
*/
channel_change_state(base_chan, CHANNEL_STATE_OPEN);
} else {
/*
* Not open, so from CHANNEL_STATE_OPEN we go to CHANNEL_STATE_MAINT,
* otherwise no change.
*/
if (base_chan->state == CHANNEL_STATE_OPEN) {
channel_change_state(base_chan, CHANNEL_STATE_MAINT);
}
}
}
/**
* Flush cells from a channel_tls_t
*
* Try to flush up to about num_cells cells, and return how many we flushed.
*/
ssize_t
channel_tls_flush_some_cells(channel_tls_t *chan, ssize_t num_cells)
{
ssize_t flushed = 0;
tor_assert(chan);
if (flushed >= num_cells) goto done;
/*
* If channel_tls_t ever buffers anything below the channel_t layer, flush
* that first here.
*/
flushed += channel_flush_some_cells(TLS_CHAN_TO_BASE(chan),
num_cells - flushed);
/*
* If channel_tls_t ever buffers anything below the channel_t layer, check
* how much we actually got and push it on down here.
*/
done:
return flushed;
}
/**
* Check if a channel_tls_t has anything to flush
*
* Return true if there is any more to flush on this channel (cells in queue
* or active circuits).
*/
int
channel_tls_more_to_flush(channel_tls_t *chan)
{
tor_assert(chan);
/*
* If channel_tls_t ever buffers anything below channel_t, the
* check for that should go here first.
*/
return channel_more_to_flush(TLS_CHAN_TO_BASE(chan));
}
#ifdef KEEP_TIMING_STATS
/**
* Timing states wrapper
*
* This is a wrapper function around the actual function that processes the
* <b>cell</b> that just arrived on <b>chan</b>. Increment <b>*time</b>
* by the number of microseconds used by the call to <b>*func(cell, chan)</b>.
*/
static void
channel_tls_time_process_cell(cell_t *cell, channel_tls_t *chan, int *time,
void (*func)(cell_t *, channel_tls_t *))
{
struct timeval start, end;
long time_passed;
tor_gettimeofday(&start);
(*func)(cell, chan);
tor_gettimeofday(&end);
time_passed = tv_udiff(&start, &end) ;
if (time_passed > 10000) { /* more than 10ms */
log_debug(LD_OR,"That call just took %ld ms.",time_passed/1000);
}
if (time_passed < 0) {
log_info(LD_GENERAL,"That call took us back in time!");
time_passed = 0;
}
*time += time_passed;
}
#endif
/**
* Handle an incoming cell on a channel_tls_t
*
* This is called from connection_or.c to handle an arriving cell; it checks
* for cell types specific to the handshake for this transport protocol and
* handles them, and queues all other cells to the channel_t layer, which
* eventually will hand them off to command.c.
*/
void
channel_tls_handle_cell(cell_t *cell, or_connection_t *conn)
{
channel_tls_t *chan;
int handshaking;
#ifdef KEEP_TIMING_STATS
#define PROCESS_CELL(tp, cl, cn) STMT_BEGIN { \
++num ## tp; \
channel_tls_time_process_cell(cl, cn, & tp ## time , \
channel_tls_process_ ## tp ## _cell); \
} STMT_END
#else
#define PROCESS_CELL(tp, cl, cn) channel_tls_process_ ## tp ## _cell(cl, cn)
#endif
tor_assert(cell);
tor_assert(conn);
chan = conn->chan;
if (!chan) {
log_warn(LD_CHANNEL,
"Got a cell_t on an OR connection with no channel");
return;
}
handshaking = (TO_CONN(conn)->state != OR_CONN_STATE_OPEN);
if (conn->base_.marked_for_close)
return;
/* Reject all but VERSIONS and NETINFO when handshaking. */
/* (VERSIONS should actually be impossible; it's variable-length.) */
if (handshaking && cell->command != CELL_VERSIONS &&
cell->command != CELL_NETINFO) {
log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
"Received unexpected cell command %d in chan state %s / "
"conn state %s; closing the connection.",
(int)cell->command,
channel_state_to_string(TLS_CHAN_TO_BASE(chan)->state),
conn_state_to_string(CONN_TYPE_OR, TO_CONN(conn)->state));
connection_or_close_for_error(conn, 0);
return;
}
if (conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3)
or_handshake_state_record_cell(conn, conn->handshake_state, cell, 1);
switch (cell->command) {
case CELL_PADDING:
++stats_n_padding_cells_processed;
/* do nothing */
break;
case CELL_VERSIONS:
tor_fragile_assert();
break;
case CELL_NETINFO:
++stats_n_netinfo_cells_processed;
PROCESS_CELL(netinfo, cell, chan);
break;
case CELL_CREATE:
case CELL_CREATE_FAST:
case CELL_CREATED:
case CELL_CREATED_FAST:
case CELL_RELAY:
case CELL_RELAY_EARLY:
case CELL_DESTROY:
case CELL_CREATE2:
case CELL_CREATED2:
/*
* These are all transport independent and we pass them up through the
* channel_t mechanism. They are ultimately handled in command.c.
*/
channel_queue_cell(TLS_CHAN_TO_BASE(chan), cell);
break;
default:
log_fn(LOG_INFO, LD_PROTOCOL,
"Cell of unknown type (%d) received in channeltls.c. "
"Dropping.",
cell->command);
break;
}
}
/**
* Handle an incoming variable-length cell on a channel_tls_t
*
* Process a <b>var_cell</b> that was just received on <b>conn</b>. Keep
* internal statistics about how many of each cell we've processed so far
* this second, and the total number of microseconds it took to
* process each type of cell. All the var_cell commands are handshake-
* related and live below the channel_t layer, so no variable-length
* cells ever get delivered in the current implementation, but I've left
* the mechanism in place for future use.
*/
void
channel_tls_handle_var_cell(var_cell_t *var_cell, or_connection_t *conn)
{
channel_tls_t *chan;
#ifdef KEEP_TIMING_STATS
/* how many of each cell have we seen so far this second? needs better
* name. */
static int num_versions = 0, num_certs = 0;
static time_t current_second = 0; /* from previous calls to time */
time_t now = time(NULL);
if (current_second == 0) current_second = now;
if (now > current_second) { /* the second has rolled over */
/* print stats */
log_info(LD_OR,
"At end of second: %d versions (%d ms), %d certs (%d ms)",
num_versions, versions_time / ((now - current_second) * 1000),
num_certs, certs_time / ((now - current_second) * 1000));
num_versions = num_certs = 0;
versions_time = certs_time = 0;
/* remember which second it is, for next time */
current_second = now;
}
#endif
tor_assert(var_cell);
tor_assert(conn);
chan = conn->chan;
if (!chan) {
log_warn(LD_CHANNEL,
"Got a var_cell_t on an OR connection with no channel");
return;
}
if (TO_CONN(conn)->marked_for_close)
return;
switch (TO_CONN(conn)->state) {
case OR_CONN_STATE_OR_HANDSHAKING_V2:
if (var_cell->command != CELL_VERSIONS) {
log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
"Received a cell with command %d in unexpected "
"orconn state \"%s\" [%d], channel state \"%s\" [%d]; "
"closing the connection.",
(int)(var_cell->command),
conn_state_to_string(CONN_TYPE_OR, TO_CONN(conn)->state),
TO_CONN(conn)->state,
channel_state_to_string(TLS_CHAN_TO_BASE(chan)->state),
(int)(TLS_CHAN_TO_BASE(chan)->state));
/*
* The code in connection_or.c will tell channel_t to close for
* error; it will go to CHANNEL_STATE_CLOSING, and then to
* CHANNEL_STATE_ERROR when conn is closed.
*/
connection_or_close_for_error(conn, 0);
return;
}
break;
case OR_CONN_STATE_TLS_HANDSHAKING:
/* If we're using bufferevents, it's entirely possible for us to
* notice "hey, data arrived!" before we notice "hey, the handshake
* finished!" And we need to be accepting both at once to handle both
* the v2 and v3 handshakes. */
/* fall through */
case OR_CONN_STATE_TLS_SERVER_RENEGOTIATING:
if (!(command_allowed_before_handshake(var_cell->command))) {
log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
"Received a cell with command %d in unexpected "
"orconn state \"%s\" [%d], channel state \"%s\" [%d]; "
"closing the connection.",
(int)(var_cell->command),
conn_state_to_string(CONN_TYPE_OR, TO_CONN(conn)->state),
(int)(TO_CONN(conn)->state),
channel_state_to_string(TLS_CHAN_TO_BASE(chan)->state),
(int)(TLS_CHAN_TO_BASE(chan)->state));
/* see above comment about CHANNEL_STATE_ERROR */
connection_or_close_for_error(conn, 0);
return;
} else {
if (enter_v3_handshake_with_cell(var_cell, chan) < 0)
return;
}
break;
case OR_CONN_STATE_OR_HANDSHAKING_V3:
if (var_cell->command != CELL_AUTHENTICATE)
or_handshake_state_record_var_cell(conn, conn->handshake_state,
var_cell, 1);
break; /* Everything is allowed */
case OR_CONN_STATE_OPEN:
if (conn->link_proto < 3) {
log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
"Received a variable-length cell with command %d in orconn "
"state %s [%d], channel state %s [%d] with link protocol %d; "
"ignoring it.",
(int)(var_cell->command),
conn_state_to_string(CONN_TYPE_OR, TO_CONN(conn)->state),
(int)(TO_CONN(conn)->state),
channel_state_to_string(TLS_CHAN_TO_BASE(chan)->state),
(int)(TLS_CHAN_TO_BASE(chan)->state),
(int)(conn->link_proto));
return;
}
break;
default:
log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
"Received var-length cell with command %d in unexpected "
"orconn state \"%s\" [%d], channel state \"%s\" [%d]; "
"ignoring it.",
(int)(var_cell->command),
conn_state_to_string(CONN_TYPE_OR, TO_CONN(conn)->state),
(int)(TO_CONN(conn)->state),
channel_state_to_string(TLS_CHAN_TO_BASE(chan)->state),
(int)(TLS_CHAN_TO_BASE(chan)->state));
return;
}
/* Now handle the cell */
switch (var_cell->command) {
case CELL_VERSIONS:
++stats_n_versions_cells_processed;
PROCESS_CELL(versions, var_cell, chan);
break;
case CELL_VPADDING:
++stats_n_vpadding_cells_processed;
/* Do nothing */
break;
case CELL_CERTS:
++stats_n_certs_cells_processed;
PROCESS_CELL(certs, var_cell, chan);
break;
case CELL_AUTH_CHALLENGE:
++stats_n_auth_challenge_cells_processed;
PROCESS_CELL(auth_challenge, var_cell, chan);
break;
case CELL_AUTHENTICATE:
++stats_n_authenticate_cells_processed;
PROCESS_CELL(authenticate, var_cell, chan);
break;
case CELL_AUTHORIZE:
++stats_n_authorize_cells_processed;
/* Ignored so far. */
break;
default:
log_fn(LOG_INFO, LD_PROTOCOL,
"Variable-length cell of unknown type (%d) received.",
(int)(var_cell->command));
break;
}
}
/**
* Update channel marks after connection_or.c has changed an address
*
* This is called from connection_or_init_conn_from_address() after the
* connection's _base.addr or real_addr fields have potentially been changed
* so we can recalculate the local mark. Notably, this happens when incoming
* connections are reverse-proxied and we only learn the real address of the
* remote router by looking it up in the consensus after we finish the
* handshake and know an authenticated identity digest.
*/
void
channel_tls_update_marks(or_connection_t *conn)
{
channel_t *chan = NULL;
tor_assert(conn);
tor_assert(conn->chan);
chan = TLS_CHAN_TO_BASE(conn->chan);
if (is_local_addr(&(TO_CONN(conn)->addr))) {
if (!channel_is_local(chan)) {
log_debug(LD_CHANNEL,
"Marking channel " U64_FORMAT " at %p as local",
U64_PRINTF_ARG(chan->global_identifier), chan);
channel_mark_local(chan);
}
} else {
if (channel_is_local(chan)) {
log_debug(LD_CHANNEL,
"Marking channel " U64_FORMAT " at %p as remote",
U64_PRINTF_ARG(chan->global_identifier), chan);
channel_mark_remote(chan);
}
}
}
/**
* Check if this cell type is allowed before the handshake is finished
*
* Return true if <b>command</b> is a cell command that's allowed to start a
* V3 handshake.
*/
static int
command_allowed_before_handshake(uint8_t command)
{
switch (command) {
case CELL_VERSIONS:
case CELL_VPADDING:
case CELL_AUTHORIZE:
return 1;
default:
return 0;
}
}
/**
* Start a V3 handshake on an incoming connection
*
* Called when we as a server receive an appropriate cell while waiting
* either for a cell or a TLS handshake. Set the connection's state to
* "handshaking_v3', initializes the or_handshake_state field as needed,
* and add the cell to the hash of incoming cells.)
*/
static int
enter_v3_handshake_with_cell(var_cell_t *cell, channel_tls_t *chan)
{
int started_here = 0;
tor_assert(cell);
tor_assert(chan);
tor_assert(chan->conn);
started_here = connection_or_nonopen_was_started_here(chan->conn);
tor_assert(TO_CONN(chan->conn)->state == OR_CONN_STATE_TLS_HANDSHAKING ||
TO_CONN(chan->conn)->state ==
OR_CONN_STATE_TLS_SERVER_RENEGOTIATING);
if (started_here) {
log_fn(LOG_PROTOCOL_WARN, LD_OR,
"Received a cell while TLS-handshaking, not in "
"OR_HANDSHAKING_V3, on a connection we originated.");
}
connection_or_block_renegotiation(chan->conn);
chan->conn->base_.state = OR_CONN_STATE_OR_HANDSHAKING_V3;
if (connection_init_or_handshake_state(chan->conn, started_here) < 0) {
connection_or_close_for_error(chan->conn, 0);
return -1;
}
or_handshake_state_record_var_cell(chan->conn,
chan->conn->handshake_state, cell, 1);
return 0;
}
/**
* Process a 'versions' cell.
*
* This function is called to handle an incoming VERSIONS cell; the current
* link protocol version must be 0 to indicate that no version has yet been
* negotiated. We compare the versions in the cell to the list of versions
* we support, pick the highest version we have in common, and continue the
* negotiation from there.
*/
static void
channel_tls_process_versions_cell(var_cell_t *cell, channel_tls_t *chan)
{
int highest_supported_version = 0;
int started_here = 0;
tor_assert(cell);
tor_assert(chan);
// FIx me: assertation failed
tor_assert(chan->conn);
if ((cell->payload_len % 2) == 1) {
log_fn(LOG_PROTOCOL_WARN, LD_OR,
"Received a VERSION cell with odd payload length %d; "
"closing connection.",cell->payload_len);
connection_or_close_for_error(chan->conn, 0);
return;
}
started_here = connection_or_nonopen_was_started_here(chan->conn);
if (chan->conn->link_proto != 0 ||
(chan->conn->handshake_state &&
chan->conn->handshake_state->received_versions)) {
log_fn(LOG_PROTOCOL_WARN, LD_OR,
"Received a VERSIONS cell on a connection with its version "
"already set to %d; dropping",
(int)(chan->conn->link_proto));
return;
}
switch (chan->conn->base_.state)
{
case OR_CONN_STATE_OR_HANDSHAKING_V2:
case OR_CONN_STATE_OR_HANDSHAKING_V3:
break;
case OR_CONN_STATE_TLS_HANDSHAKING:
case OR_CONN_STATE_TLS_SERVER_RENEGOTIATING:
default:
log_fn(LOG_PROTOCOL_WARN, LD_OR,
"VERSIONS cell while in unexpected state");
return;
}
tor_assert(chan->conn->handshake_state);
{
int i;
const uint8_t *cp = cell->payload;
for (i = 0; i < cell->payload_len / 2; ++i, cp += 2) {
uint16_t v = ntohs(get_uint16(cp));
if (is_or_protocol_version_known(v) && v > highest_supported_version)
highest_supported_version = v;
}
}
if (!highest_supported_version) {
log_fn(LOG_PROTOCOL_WARN, LD_OR,
"Couldn't find a version in common between my version list and the "
"list in the VERSIONS cell; closing connection.");
connection_or_close_for_error(chan->conn, 0);
return;
} else if (highest_supported_version == 1) {
/* Negotiating version 1 makes no sense, since version 1 has no VERSIONS
* cells. */
log_fn(LOG_PROTOCOL_WARN, LD_OR,
"Used version negotiation protocol to negotiate a v1 connection. "
"That's crazily non-compliant. Closing connection.");
connection_or_close_for_error(chan->conn, 0);
return;
} else if (highest_supported_version < 3 &&
chan->conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3) {
log_fn(LOG_PROTOCOL_WARN, LD_OR,
"Negotiated link protocol 2 or lower after doing a v3 TLS "
"handshake. Closing connection.");
connection_or_close_for_error(chan->conn, 0);
return;
} else if (highest_supported_version != 2 &&
chan->conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V2) {
/* XXXX This should eventually be a log_protocol_warn */
log_fn(LOG_WARN, LD_OR,
"Negotiated link with non-2 protocol after doing a v2 TLS "
"handshake with %s. Closing connection.",
fmt_addr(&chan->conn->base_.addr));
connection_or_close_for_error(chan->conn, 0);
return;
}
chan->conn->link_proto = highest_supported_version;
chan->conn->handshake_state->received_versions = 1;
if (chan->conn->link_proto == 2) {
log_info(LD_OR,
"Negotiated version %d with %s:%d; sending NETINFO.",
highest_supported_version,
safe_str_client(chan->conn->base_.address),
chan->conn->base_.port);
if (connection_or_send_netinfo(chan->conn) < 0) {
connection_or_close_for_error(chan->conn, 0);
return;
}
} else {
const int send_versions = !started_here;
/* If we want to authenticate, send a CERTS cell */
const int send_certs = !started_here || public_server_mode(get_options());
/* If we're a host that got a connection, ask for authentication. */
const int send_chall = !started_here;
/* If our certs cell will authenticate us, we can send a netinfo cell
* right now. */
const int send_netinfo = !started_here;
const int send_any =
send_versions || send_certs || send_chall || send_netinfo;
tor_assert(chan->conn->link_proto >= 3);
log_info(LD_OR,
"Negotiated version %d with %s:%d; %s%s%s%s%s",
highest_supported_version,
safe_str_client(chan->conn->base_.address),
chan->conn->base_.port,
send_any ? "Sending cells:" : "Waiting for CERTS cell",
send_versions ? " VERSIONS" : "",
send_certs ? " CERTS" : "",
send_chall ? " AUTH_CHALLENGE" : "",
send_netinfo ? " NETINFO" : "");
#ifdef DISABLE_V3_LINKPROTO_SERVERSIDE
if (1) {
connection_or_close_normally(chan->conn, 1);
return;
}
#endif
if (send_versions) {
if (connection_or_send_versions(chan->conn, 1) < 0) {
log_warn(LD_OR, "Couldn't send versions cell");
connection_or_close_for_error(chan->conn, 0);
return;
}
}
/* We set this after sending the verions cell. */
/*XXXXX symbolic const.*/
chan->base_.wide_circ_ids =
chan->conn->link_proto >= MIN_LINK_PROTO_FOR_WIDE_CIRC_IDS;
chan->conn->wide_circ_ids = chan->base_.wide_circ_ids;
if (send_certs) {
if (connection_or_send_certs_cell(chan->conn) < 0) {
log_warn(LD_OR, "Couldn't send certs cell");
connection_or_close_for_error(chan->conn, 0);
return;
}
}
if (send_chall) {
if (connection_or_send_auth_challenge_cell(chan->conn) < 0) {
log_warn(LD_OR, "Couldn't send auth_challenge cell");
connection_or_close_for_error(chan->conn, 0);
return;
}
}
if (send_netinfo) {
if (connection_or_send_netinfo(chan->conn) < 0) {
log_warn(LD_OR, "Couldn't send netinfo cell");
connection_or_close_for_error(chan->conn, 0);
return;
}
}
}
}
/**
* Process a 'netinfo' cell
*
* This function is called to handle an incoming NETINFO cell; read and act
* on its contents, and set the connection state to "open".
*/
static void
channel_tls_process_netinfo_cell(cell_t *cell, channel_tls_t *chan)
{
time_t timestamp;
uint8_t my_addr_type;
uint8_t my_addr_len;
const uint8_t *my_addr_ptr;
const uint8_t *cp, *end;
uint8_t n_other_addrs;
time_t now = time(NULL);
long apparent_skew = 0;
tor_addr_t my_apparent_addr = TOR_ADDR_NULL;
tor_assert(cell);
tor_assert(chan);
tor_assert(chan->conn);
if (chan->conn->link_proto < 2) {
log_fn(LOG_PROTOCOL_WARN, LD_OR,
"Received a NETINFO cell on %s connection; dropping.",
chan->conn->link_proto == 0 ? "non-versioned" : "a v1");
return;
}
if (chan->conn->base_.state != OR_CONN_STATE_OR_HANDSHAKING_V2 &&
chan->conn->base_.state != OR_CONN_STATE_OR_HANDSHAKING_V3) {
log_fn(LOG_PROTOCOL_WARN, LD_OR,
"Received a NETINFO cell on non-handshaking connection; dropping.");
return;
}
tor_assert(chan->conn->handshake_state &&
chan->conn->handshake_state->received_versions);
if (chan->conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3) {
tor_assert(chan->conn->link_proto >= 3);
if (chan->conn->handshake_state->started_here) {
if (!(chan->conn->handshake_state->authenticated)) {
log_fn(LOG_PROTOCOL_WARN, LD_OR,
"Got a NETINFO cell from server, "
"but no authentication. Closing the connection.");
connection_or_close_for_error(chan->conn, 0);
return;
}
} else {
/* we're the server. If the client never authenticated, we have
some housekeeping to do.*/
if (!(chan->conn->handshake_state->authenticated)) {
tor_assert(tor_digest_is_zero(
(const char*)(chan->conn->handshake_state->
authenticated_peer_id)));
channel_set_circid_type(TLS_CHAN_TO_BASE(chan), NULL,
chan->conn->link_proto < MIN_LINK_PROTO_FOR_WIDE_CIRC_IDS);
connection_or_init_conn_from_address(chan->conn,
&(chan->conn->base_.addr),
chan->conn->base_.port,
(const char*)(chan->conn->handshake_state->
authenticated_peer_id),
0);
}
}
}
/* Decode the cell. */
timestamp = ntohl(get_uint32(cell->payload));
if (labs(now - chan->conn->handshake_state->sent_versions_at) < 180) {
apparent_skew = now - timestamp;
}
my_addr_type = (uint8_t) cell->payload[4];
my_addr_len = (uint8_t) cell->payload[5];
my_addr_ptr = (uint8_t*) cell->payload + 6;
end = cell->payload + CELL_PAYLOAD_SIZE;
cp = cell->payload + 6 + my_addr_len;
/* We used to check:
* if (my_addr_len >= CELL_PAYLOAD_SIZE - 6) {
*
* This is actually never going to happen, since my_addr_len is at most 255,
* and CELL_PAYLOAD_LEN - 6 is 503. So we know that cp is < end. */
if (my_addr_type == RESOLVED_TYPE_IPV4 && my_addr_len == 4) {
tor_addr_from_ipv4n(&my_apparent_addr, get_uint32(my_addr_ptr));
} else if (my_addr_type == RESOLVED_TYPE_IPV6 && my_addr_len == 16) {
tor_addr_from_ipv6_bytes(&my_apparent_addr, (const char *) my_addr_ptr);
}
n_other_addrs = (uint8_t) *cp++;
while (n_other_addrs && cp < end-2) {
/* Consider all the other addresses; if any matches, this connection is
* "canonical." */
tor_addr_t addr;
const uint8_t *next =
decode_address_from_payload(&addr, cp, (int)(end-cp));
if (next == NULL) {
log_fn(LOG_PROTOCOL_WARN, LD_OR,
"Bad address in netinfo cell; closing connection.");
connection_or_close_for_error(chan->conn, 0);
return;
}
if (tor_addr_eq(&addr, &(chan->conn->real_addr))) {
connection_or_set_canonical(chan->conn, 1);
break;
}
cp = next;
--n_other_addrs;
}
/* Act on apparent skew. */
/** Warn when we get a netinfo skew with at least this value. */
#define NETINFO_NOTICE_SKEW 3600
if (labs(apparent_skew) > NETINFO_NOTICE_SKEW &&
router_get_by_id_digest(chan->conn->identity_digest)) {
char dbuf[64];
int severity;
/*XXXX be smarter about when everybody says we are skewed. */
if (router_digest_is_trusted_dir(chan->conn->identity_digest))
severity = LOG_WARN;
else
severity = LOG_INFO;
format_time_interval(dbuf, sizeof(dbuf), apparent_skew);
log_fn(severity, LD_GENERAL,
"Received NETINFO cell with skewed time from "
"server at %s:%d. It seems that our clock is %s by %s, or "
"that theirs is %s. Tor requires an accurate clock to work: "
"please check your time and date settings.",
chan->conn->base_.address,
(int)(chan->conn->base_.port),
apparent_skew > 0 ? "ahead" : "behind",
dbuf,
apparent_skew > 0 ? "behind" : "ahead");
if (severity == LOG_WARN) /* only tell the controller if an authority */
control_event_general_status(LOG_WARN,
"CLOCK_SKEW SKEW=%ld SOURCE=OR:%s:%d",
apparent_skew,
chan->conn->base_.address,
chan->conn->base_.port);
}
/* XXX maybe act on my_apparent_addr, if the source is sufficiently
* trustworthy. */
if (! chan->conn->handshake_state->sent_netinfo) {
/* If we were prepared to authenticate, but we never got an AUTH_CHALLENGE
* cell, then we would not previously have sent a NETINFO cell. Do so
* now. */
if (connection_or_send_netinfo(chan->conn) < 0) {
connection_or_close_for_error(chan->conn, 0);
return;
}
}
if (connection_or_set_state_open(chan->conn) < 0) {
log_fn(LOG_PROTOCOL_WARN, LD_OR,
"Got good NETINFO cell from %s:%d; but "
"was unable to make the OR connection become open.",
safe_str_client(chan->conn->base_.address),
chan->conn->base_.port);
connection_or_close_for_error(chan->conn, 0);
} else {
log_info(LD_OR,
"Got good NETINFO cell from %s:%d; OR connection is now "
"open, using protocol version %d. Its ID digest is %s. "
"Our address is apparently %s.",
safe_str_client(chan->conn->base_.address),
chan->conn->base_.port,
(int)(chan->conn->link_proto),
hex_str(TLS_CHAN_TO_BASE(chan)->identity_digest,
DIGEST_LEN),
tor_addr_is_null(&my_apparent_addr) ?
"<none>" : fmt_and_decorate_addr(&my_apparent_addr));
}
assert_connection_ok(TO_CONN(chan->conn),time(NULL));
}
/**
* Process a CERTS cell from a channel.
*
* This function is called to process an incoming CERTS cell on a
* channel_tls_t:
*
* If the other side should not have sent us a CERTS cell, or the cell is
* malformed, or it is supposed to authenticate the TLS key but it doesn't,
* then mark the connection.
*
* If the cell has a good cert chain and we're doing a v3 handshake, then
* store the certificates in or_handshake_state. If this is the client side
* of the connection, we then authenticate the server or mark the connection.
* If it's the server side, wait for an AUTHENTICATE cell.
*/
static void
channel_tls_process_certs_cell(var_cell_t *cell, channel_tls_t *chan)
{
tor_cert_t *link_cert = NULL;
tor_cert_t *id_cert = NULL;
tor_cert_t *auth_cert = NULL;
uint8_t *ptr;
int n_certs, i;
int send_netinfo = 0;
tor_assert(cell);
tor_assert(chan);
tor_assert(chan->conn);
#define ERR(s) \
do { \
log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, \
"Received a bad CERTS cell from %s:%d: %s", \
safe_str(chan->conn->base_.address), \
chan->conn->base_.port, (s)); \
connection_or_close_for_error(chan->conn, 0); \
goto err; \
} while (0)
if (chan->conn->base_.state != OR_CONN_STATE_OR_HANDSHAKING_V3)
ERR("We're not doing a v3 handshake!");
if (chan->conn->link_proto < 3)
ERR("We're not using link protocol >= 3");
if (chan->conn->handshake_state->received_certs_cell)
ERR("We already got one");
if (chan->conn->handshake_state->authenticated) {
/* Should be unreachable, but let's make sure. */
ERR("We're already authenticated!");
}
if (cell->payload_len < 1)
ERR("It had no body");
if (cell->circ_id)
ERR("It had a nonzero circuit ID");
n_certs = cell->payload[0];
ptr = cell->payload + 1;
for (i = 0; i < n_certs; ++i) {
uint8_t cert_type;
uint16_t cert_len;
if (cell->payload_len < 3)
goto truncated;
if (ptr > cell->payload + cell->payload_len - 3) {
goto truncated;
}
cert_type = *ptr;
cert_len = ntohs(get_uint16(ptr+1));
if (cell->payload_len < 3 + cert_len)
goto truncated;
if (ptr > cell->payload + cell->payload_len - cert_len - 3) {
goto truncated;
}
if (cert_type == OR_CERT_TYPE_TLS_LINK ||
cert_type == OR_CERT_TYPE_ID_1024 ||
cert_type == OR_CERT_TYPE_AUTH_1024) {
tor_cert_t *cert = tor_cert_decode(ptr + 3, cert_len);
if (!cert) {
log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
"Received undecodable certificate in CERTS cell from %s:%d",
safe_str(chan->conn->base_.address),
chan->conn->base_.port);
} else {
if (cert_type == OR_CERT_TYPE_TLS_LINK) {
if (link_cert) {
tor_cert_free(cert);
ERR("Too many TLS_LINK certificates");
}
link_cert = cert;
} else if (cert_type == OR_CERT_TYPE_ID_1024) {
if (id_cert) {
tor_cert_free(cert);
ERR("Too many ID_1024 certificates");
}
id_cert = cert;
} else if (cert_type == OR_CERT_TYPE_AUTH_1024) {
if (auth_cert) {
tor_cert_free(cert);
ERR("Too many AUTH_1024 certificates");
}
auth_cert = cert;
} else {
tor_cert_free(cert);
}
}
}
ptr += 3 + cert_len;
continue;
truncated:
ERR("It ends in the middle of a certificate");
}
if (chan->conn->handshake_state->started_here) {
int severity;
if (! (id_cert && link_cert))
ERR("The certs we wanted were missing");
/* Okay. We should be able to check the certificates now. */
if (! tor_tls_cert_matches_key(chan->conn->tls, link_cert)) {
ERR("The link certificate didn't match the TLS public key");
}
/* Note that this warns more loudly about time and validity if we were
* _trying_ to connect to an authority, not necessarily if we _did_ connect
* to one. */
if (router_digest_is_trusted_dir(
TLS_CHAN_TO_BASE(chan)->identity_digest))
severity = LOG_WARN;
else
severity = LOG_PROTOCOL_WARN;
if (! tor_tls_cert_is_valid(severity, link_cert, id_cert, 0))
ERR("The link certificate was not valid");
if (! tor_tls_cert_is_valid(severity, id_cert, id_cert, 1))
ERR("The ID certificate was not valid");
chan->conn->handshake_state->authenticated = 1;
{
const digests_t *id_digests = tor_cert_get_id_digests(id_cert);
crypto_pk_t *identity_rcvd;
if (!id_digests)
ERR("Couldn't compute digests for key in ID cert");
identity_rcvd = tor_tls_cert_get_key(id_cert);
if (!identity_rcvd)
ERR("Internal error: Couldn't get RSA key from ID cert.");
memcpy(chan->conn->handshake_state->authenticated_peer_id,
id_digests->d[DIGEST_SHA1], DIGEST_LEN);
channel_set_circid_type(TLS_CHAN_TO_BASE(chan), identity_rcvd,
chan->conn->link_proto < MIN_LINK_PROTO_FOR_WIDE_CIRC_IDS);
crypto_pk_free(identity_rcvd);
}
if (connection_or_client_learned_peer_id(chan->conn,
chan->conn->handshake_state->authenticated_peer_id) < 0)
ERR("Problem setting or checking peer id");
log_info(LD_OR,
"Got some good certificates from %s:%d: Authenticated it.",
safe_str(chan->conn->base_.address), chan->conn->base_.port);
chan->conn->handshake_state->id_cert = id_cert;
id_cert = NULL;
if (!public_server_mode(get_options())) {
/* If we initiated the connection and we are not a public server, we
* aren't planning to authenticate at all. At this point we know who we
* are talking to, so we can just send a netinfo now. */
send_netinfo = 1;
}
} else {
if (! (id_cert && auth_cert))
ERR("The certs we wanted were missing");
/* Remember these certificates so we can check an AUTHENTICATE cell */
if (! tor_tls_cert_is_valid(LOG_PROTOCOL_WARN, auth_cert, id_cert, 1))
ERR("The authentication certificate was not valid");
if (! tor_tls_cert_is_valid(LOG_PROTOCOL_WARN, id_cert, id_cert, 1))
ERR("The ID certificate was not valid");
log_info(LD_OR,
"Got some good certificates from %s:%d: "
"Waiting for AUTHENTICATE.",
safe_str(chan->conn->base_.address),
chan->conn->base_.port);
/* XXXX check more stuff? */
chan->conn->handshake_state->id_cert = id_cert;
chan->conn->handshake_state->auth_cert = auth_cert;
id_cert = auth_cert = NULL;
}
chan->conn->handshake_state->received_certs_cell = 1;
if (send_netinfo) {
if (connection_or_send_netinfo(chan->conn) < 0) {
log_warn(LD_OR, "Couldn't send netinfo cell");
connection_or_close_for_error(chan->conn, 0);
goto err;
}
}
err:
tor_cert_free(id_cert);
tor_cert_free(link_cert);
tor_cert_free(auth_cert);
#undef ERR
}
/**
* Process an AUTH_CHALLENGE cell from a channel_tls_t
*
* This function is called to handle an incoming AUTH_CHALLENGE cell on a
* channel_tls_t; if we weren't supposed to get one (for example, because we're
* not the originator of the channel), or it's ill-formed, or we aren't doing
* a v3 handshake, mark the channel. If the cell is well-formed but we don't
* want to authenticate, just drop it. If the cell is well-formed *and* we
* want to authenticate, send an AUTHENTICATE cell and then a NETINFO cell.
*/
static void
channel_tls_process_auth_challenge_cell(var_cell_t *cell, channel_tls_t *chan)
{
int n_types, i, use_type = -1;
uint8_t *cp;
tor_assert(cell);
tor_assert(chan);
tor_assert(chan->conn);
#define ERR(s) \
do { \
log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, \
"Received a bad AUTH_CHALLENGE cell from %s:%d: %s", \
safe_str(chan->conn->base_.address), \
chan->conn->base_.port, (s)); \
connection_or_close_for_error(chan->conn, 0); \
return; \
} while (0)
if (chan->conn->base_.state != OR_CONN_STATE_OR_HANDSHAKING_V3)
ERR("We're not currently doing a v3 handshake");
if (chan->conn->link_proto < 3)
ERR("We're not using link protocol >= 3");
if (!(chan->conn->handshake_state->started_here))
ERR("We didn't originate this connection");
if (chan->conn->handshake_state->received_auth_challenge)
ERR("We already received one");
if (!(chan->conn->handshake_state->received_certs_cell))
ERR("We haven't gotten a CERTS cell yet");
if (cell->payload_len < OR_AUTH_CHALLENGE_LEN + 2)
ERR("It was too short");
if (cell->circ_id)
ERR("It had a nonzero circuit ID");
n_types = ntohs(get_uint16(cell->payload + OR_AUTH_CHALLENGE_LEN));
if (cell->payload_len < OR_AUTH_CHALLENGE_LEN + 2 + 2*n_types)
ERR("It looks truncated");
/* Now see if there is an authentication type we can use */
cp = cell->payload+OR_AUTH_CHALLENGE_LEN + 2;
for (i = 0; i < n_types; ++i, cp += 2) {
uint16_t authtype = ntohs(get_uint16(cp));
if (authtype == AUTHTYPE_RSA_SHA256_TLSSECRET)
use_type = authtype;
}
chan->conn->handshake_state->received_auth_challenge = 1;
if (! public_server_mode(get_options())) {
/* If we're not a public server then we don't want to authenticate on a
connection we originated, and we already sent a NETINFO cell when we
got the CERTS cell. We have nothing more to do. */
return;
}
if (use_type >= 0) {
log_info(LD_OR,
"Got an AUTH_CHALLENGE cell from %s:%d: Sending "
"authentication",
safe_str(chan->conn->base_.address),
chan->conn->base_.port);
if (connection_or_send_authenticate_cell(chan->conn, use_type) < 0) {
log_warn(LD_OR,
"Couldn't send authenticate cell");
connection_or_close_for_error(chan->conn, 0);
return;
}
} else {
log_info(LD_OR,
"Got an AUTH_CHALLENGE cell from %s:%d, but we don't "
"know any of its authentication types. Not authenticating.",
safe_str(chan->conn->base_.address),
chan->conn->base_.port);
}
if (connection_or_send_netinfo(chan->conn) < 0) {
log_warn(LD_OR, "Couldn't send netinfo cell");
connection_or_close_for_error(chan->conn, 0);
return;
}
#undef ERR
}
/**
* Process an AUTHENTICATE cell from a channel_tls_t
*
* If it's ill-formed or we weren't supposed to get one or we're not doing a
* v3 handshake, then mark the connection. If it does not authenticate the
* other side of the connection successfully (because it isn't signed right,
* we didn't get a CERTS cell, etc) mark the connection. Otherwise, accept
* the identity of the router on the other side of the connection.
*/
static void
channel_tls_process_authenticate_cell(var_cell_t *cell, channel_tls_t *chan)
{
uint8_t expected[V3_AUTH_FIXED_PART_LEN];
const uint8_t *auth;
int authlen;
tor_assert(cell);
tor_assert(chan);
tor_assert(chan->conn);
#define ERR(s) \
do { \
log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, \
"Received a bad AUTHENTICATE cell from %s:%d: %s", \
safe_str(chan->conn->base_.address), \
chan->conn->base_.port, (s)); \
connection_or_close_for_error(chan->conn, 0); \
return; \
} while (0)
if (chan->conn->base_.state != OR_CONN_STATE_OR_HANDSHAKING_V3)
ERR("We're not doing a v3 handshake");
if (chan->conn->link_proto < 3)
ERR("We're not using link protocol >= 3");
if (chan->conn->handshake_state->started_here)
ERR("We originated this connection");
if (chan->conn->handshake_state->received_authenticate)
ERR("We already got one!");
if (chan->conn->handshake_state->authenticated) {
/* Should be impossible given other checks */
ERR("The peer is already authenticated");
}
if (!(chan->conn->handshake_state->received_certs_cell))
ERR("We never got a certs cell");
if (chan->conn->handshake_state->auth_cert == NULL)
ERR("We never got an authentication certificate");
if (chan->conn->handshake_state->id_cert == NULL)
ERR("We never got an identity certificate");
if (cell->payload_len < 4)
ERR("Cell was way too short");
auth = cell->payload;
{
uint16_t type = ntohs(get_uint16(auth));
uint16_t len = ntohs(get_uint16(auth+2));
if (4 + len > cell->payload_len)
ERR("Authenticator was truncated");
if (type != AUTHTYPE_RSA_SHA256_TLSSECRET)
ERR("Authenticator type was not recognized");
auth += 4;
authlen = len;
}
if (authlen < V3_AUTH_BODY_LEN + 1)
ERR("Authenticator was too short");
if (connection_or_compute_authenticate_cell_body(
chan->conn, expected, sizeof(expected), NULL, 1) < 0)
ERR("Couldn't compute expected AUTHENTICATE cell body");
if (tor_memneq(expected, auth, sizeof(expected)))
ERR("Some field in the AUTHENTICATE cell body was not as expected");
{
crypto_pk_t *pk = tor_tls_cert_get_key(
chan->conn->handshake_state->auth_cert);
char d[DIGEST256_LEN];
char *signed_data;
size_t keysize;
int signed_len;
if (!pk)
ERR("Internal error: couldn't get RSA key from AUTH cert.");
crypto_digest256(d, (char*)auth, V3_AUTH_BODY_LEN, DIGEST_SHA256);
keysize = crypto_pk_keysize(pk);
signed_data = (char *)tor_malloc(keysize);
signed_len = crypto_pk_public_checksig(pk, signed_data, keysize,
(char*)auth + V3_AUTH_BODY_LEN,
authlen - V3_AUTH_BODY_LEN);
crypto_pk_free(pk);
if (signed_len < 0) {
tor_free(signed_data);
ERR("Signature wasn't valid");
}
if (signed_len < DIGEST256_LEN) {
tor_free(signed_data);
ERR("Not enough data was signed");
}
/* Note that we deliberately allow *more* than DIGEST256_LEN bytes here,
* in case they're later used to hold a SHA3 digest or something. */
if (tor_memneq(signed_data, d, DIGEST256_LEN)) {
tor_free(signed_data);
ERR("Signature did not match data to be signed.");
}
tor_free(signed_data);
}
/* Okay, we are authenticated. */
chan->conn->handshake_state->received_authenticate = 1;
chan->conn->handshake_state->authenticated = 1;
chan->conn->handshake_state->digest_received_data = 0;
{
crypto_pk_t *identity_rcvd =
tor_tls_cert_get_key(chan->conn->handshake_state->id_cert);
const digests_t *id_digests =
tor_cert_get_id_digests(chan->conn->handshake_state->id_cert);
/* This must exist; we checked key type when reading the cert. */
tor_assert(id_digests);
memcpy(chan->conn->handshake_state->authenticated_peer_id,
id_digests->d[DIGEST_SHA1], DIGEST_LEN);
channel_set_circid_type(TLS_CHAN_TO_BASE(chan), identity_rcvd,
chan->conn->link_proto < MIN_LINK_PROTO_FOR_WIDE_CIRC_IDS);
crypto_pk_free(identity_rcvd);
connection_or_init_conn_from_address(chan->conn,
&(chan->conn->base_.addr),
chan->conn->base_.port,
(const char*)(chan->conn->handshake_state->
authenticated_peer_id),
0);
log_info(LD_OR,
"Got an AUTHENTICATE cell from %s:%d: Looks good.",
safe_str(chan->conn->base_.address),
chan->conn->base_.port);
}
#undef ERR
} | shwetasshinde24/Panoply | case-studies/tor/src/TorEnclave/or/channeltls.cpp | C++ | apache-2.0 | 68,365 |
# begin: ragel
=begin
=end
# end: ragel
require_relative '../ast/node'
require_relative '../mixin/buffer'
require_relative '../nonblocking_io_wrapper'
require_relative '../tracer'
module BELParser
module Parsers
module Common
module MultiIdentifier
class << self
MAX_LENGTH = 1024 * 128 # 128K
def parse(content)
return nil unless content
Parser.new(content).each do |obj|
yield obj
end
end
end
private
class Parser
include Enumerable
include BELParser::Parsers::Buffer
include BELParser::Parsers::AST::Sexp
include BELParser::Parsers::Tracer
def initialize(content)
@content = content
# begin: ragel
class << self
attr_accessor :_bel_trans_keys
private :_bel_trans_keys, :_bel_trans_keys=
end
self._bel_trans_keys = [
0, 0, 76, 78, 10, 78,
0
]
class << self
attr_accessor :_bel_key_spans
private :_bel_key_spans, :_bel_key_spans=
end
self._bel_key_spans = [
0, 3, 69
]
class << self
attr_accessor :_bel_index_offsets
private :_bel_index_offsets, :_bel_index_offsets=
end
self._bel_index_offsets = [
0, 0, 4
]
class << self
attr_accessor :_bel_indicies
private :_bel_indicies, :_bel_indicies=
end
self._bel_indicies = [
1, 0, 1, 0, 3, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 4, 2,
4, 2, 0
]
class << self
attr_accessor :_bel_trans_targs
private :_bel_trans_targs, :_bel_trans_targs=
end
self._bel_trans_targs = [
2, 0, 2, 2, 0
]
class << self
attr_accessor :_bel_trans_actions
private :_bel_trans_actions, :_bel_trans_actions=
end
self._bel_trans_actions = [
1, 0, 0, 3, 4
]
class << self
attr_accessor :_bel_eof_actions
private :_bel_eof_actions, :_bel_eof_actions=
end
self._bel_eof_actions = [
0, 0, 2
]
class << self
attr_accessor :bel_start
end
self.bel_start = 1;
class << self
attr_accessor :bel_first_final
end
self.bel_first_final = 2;
class << self
attr_accessor :bel_error
end
self.bel_error = 0;
class << self
attr_accessor :bel_en_multi_ident_node
end
self.bel_en_multi_ident_node = 1;
# end: ragel
end
def each
@buffers = {}
@incomplete = {}
data = @content.unpack('C*')
p = 0
id_start = 0
id_end = 0
pe = data.length
eof = data.length
identifier_started = false
# begin: ragel
begin
p ||= 0
pe ||= data.length
cs = bel_start
end
begin
testEof = false
_slen, _trans, _keys, _inds, _acts, _nacts = nil
_goto_level = 0
_resume = 10
_eof_trans = 15
_again = 20
_test_eof = 30
_out = 40
while true
if _goto_level <= 0
if p == pe
_goto_level = _test_eof
next
end
if cs == 0
_goto_level = _out
next
end
end
if _goto_level <= _resume
_keys = cs << 1
_inds = _bel_index_offsets[cs]
_slen = _bel_key_spans[cs]
_wide = data[p].ord
_trans = if ( _slen > 0 &&
_bel_trans_keys[_keys] <= _wide &&
_wide <= _bel_trans_keys[_keys + 1]
) then
_bel_indicies[ _inds + _wide - _bel_trans_keys[_keys] ]
else
_bel_indicies[ _inds + _slen ]
end
cs = _bel_trans_targs[_trans]
if _bel_trans_actions[_trans] != 0
case _bel_trans_actions[_trans]
when 1 then
begin
trace('IDENTIFIER start_multi_identifier')
@multi_identifier_started = true
multi_id_start = p;
end
when 3 then
begin
trace('IDENTIFIER end_multi_identifier')
# exclude the NL from the chars
multi_id_end = p - 1
chars = data[multi_id_start...multi_id_end]
completed = !chars.empty?
ast_node = multi_identifier(utf8_string(chars), complete: completed, character_range: [multi_id_start, multi_id_end])
@buffers[:multi_ident] = ast_node
end
when 4 then
begin
trace('IDENTIFIER multi_ident_node_err')
multi_id_end = p
chars = data[multi_id_start...multi_id_end]
ast_node = multi_identifier(utf8_string(chars), complete: false, character_range: [multi_id_start, multi_id_end])
yield ast_node
end
end
end
end
if _goto_level <= _again
if cs == 0
_goto_level = _out
next
end
p += 1
if p != pe
_goto_level = _resume
next
end
end
if _goto_level <= _test_eof
if p == eof
case _bel_eof_actions[cs]
when 2 then
begin
trace('IDENTIFIER end_multi_identifier')
# exclude the NL from the chars
multi_id_end = p - 1
chars = data[multi_id_start...multi_id_end]
completed = !chars.empty?
ast_node = multi_identifier(utf8_string(chars), complete: completed, character_range: [multi_id_start, multi_id_end])
@buffers[:multi_ident] = ast_node
end
begin
trace('IDENTIFIER yield_multi_identifier')
yield @buffers[:multi_ident]
end
end
end
end
if _goto_level <= _out
break
end
end
end
# end: ragel
end
end
end
end
end
end
if __FILE__ == $0
$stdin.each_line do |line|
BELParser::Parsers::Common::MultiIdentifier.parse(line) { |obj|
puts obj.inspect
}
end
end
# vim: ft=ruby ts=2 sw=2:
# encoding: utf-8
| OpenBEL/bel_parser | lib/bel_parser/parsers/common/multi_identifier.rb | Ruby | apache-2.0 | 5,360 |
##
# Copyright (c) 2005-2015 Apple Inc. 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.
##
from twisted.internet.defer import inlineCallbacks
from calendarserver.tools.resources import migrateResources
from twistedcaldav.test.util import StoreTestCase
from txdav.who.test.support import InMemoryDirectoryService
from twext.who.directory import DirectoryRecord
from txdav.who.idirectory import RecordType as CalRecordType
from txdav.who.directory import CalendarDirectoryRecordMixin
class TestRecord(DirectoryRecord, CalendarDirectoryRecordMixin):
pass
class MigrateResourcesTest(StoreTestCase):
@inlineCallbacks
def setUp(self):
yield super(MigrateResourcesTest, self).setUp()
self.store = self.storeUnderTest()
self.sourceService = InMemoryDirectoryService(None)
fieldName = self.sourceService.fieldName
records = (
TestRecord(
self.sourceService,
{
fieldName.uid: u"location1",
fieldName.shortNames: (u"loc1",),
fieldName.recordType: CalRecordType.location,
}
),
TestRecord(
self.sourceService,
{
fieldName.uid: u"location2",
fieldName.shortNames: (u"loc2",),
fieldName.recordType: CalRecordType.location,
}
),
TestRecord(
self.sourceService,
{
fieldName.uid: u"resource1",
fieldName.shortNames: (u"res1",),
fieldName.recordType: CalRecordType.resource,
}
),
)
yield self.sourceService.updateRecords(records, create=True)
@inlineCallbacks
def test_migrateResources(self):
# Record location1 has not been migrated
record = yield self.directory.recordWithUID(u"location1")
self.assertEquals(record, None)
# Migrate location1, location2, and resource1
yield migrateResources(self.sourceService, self.directory)
record = yield self.directory.recordWithUID(u"location1")
self.assertEquals(record.uid, u"location1")
self.assertEquals(record.shortNames[0], u"loc1")
record = yield self.directory.recordWithUID(u"location2")
self.assertEquals(record.uid, u"location2")
self.assertEquals(record.shortNames[0], u"loc2")
record = yield self.directory.recordWithUID(u"resource1")
self.assertEquals(record.uid, u"resource1")
self.assertEquals(record.shortNames[0], u"res1")
# Add a new location to the sourceService, and modify an existing
# location
fieldName = self.sourceService.fieldName
newRecords = (
TestRecord(
self.sourceService,
{
fieldName.uid: u"location1",
fieldName.shortNames: (u"newloc1",),
fieldName.recordType: CalRecordType.location,
}
),
TestRecord(
self.sourceService,
{
fieldName.uid: u"location3",
fieldName.shortNames: (u"loc3",),
fieldName.recordType: CalRecordType.location,
}
),
)
yield self.sourceService.updateRecords(newRecords, create=True)
yield migrateResources(self.sourceService, self.directory)
# Ensure an existing record does not get migrated again; verified by
# seeing if shortNames changed, which they should not:
record = yield self.directory.recordWithUID(u"location1")
self.assertEquals(record.uid, u"location1")
self.assertEquals(record.shortNames[0], u"loc1")
# Ensure new record does get migrated
record = yield self.directory.recordWithUID(u"location3")
self.assertEquals(record.uid, u"location3")
self.assertEquals(record.shortNames[0], u"loc3")
| red-hood/calendarserver | calendarserver/tools/test/test_resources.py | Python | apache-2.0 | 4,593 |
package io.dropwizard.hibernate;
import com.codahale.metrics.MetricRegistry;
import io.dropwizard.db.DataSourceFactory;
import io.dropwizard.db.ManagedPooledDataSource;
import io.dropwizard.lifecycle.setup.LifecycleEnvironment;
import io.dropwizard.logging.BootstrapLogging;
import io.dropwizard.setup.Environment;
import io.dropwizard.util.Maps;
import org.hibernate.EmptyInterceptor;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import javax.annotation.Nullable;
import java.util.Collections;
import java.util.Map;
import static java.util.Objects.requireNonNull;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class SessionFactoryFactoryTest {
static {
BootstrapLogging.bootstrap();
}
private final SessionFactoryFactory factory = new SessionFactoryFactory();
private final HibernateBundle<?> bundle = mock(HibernateBundle.class);
private final LifecycleEnvironment lifecycleEnvironment = mock(LifecycleEnvironment.class);
private final Environment environment = mock(Environment.class);
private final MetricRegistry metricRegistry = new MetricRegistry();
private DataSourceFactory config = new DataSourceFactory();
@Nullable
private SessionFactory sessionFactory;
@BeforeEach
void setUp() throws Exception {
when(environment.metrics()).thenReturn(metricRegistry);
when(environment.lifecycle()).thenReturn(lifecycleEnvironment);
config.setUrl("jdbc:h2:mem:DbTest-" + System.currentTimeMillis());
config.setUser("sa");
config.setDriverClass("org.h2.Driver");
config.setValidationQuery("SELECT 1");
final Map<String, String> properties = Maps.of(
"hibernate.show_sql", "true",
"hibernate.dialect", "org.hibernate.dialect.H2Dialect",
"hibernate.jdbc.time_zone", "UTC");
config.setProperties(properties);
}
@AfterEach
void tearDown() throws Exception {
if (sessionFactory != null) {
sessionFactory.close();
}
}
@Test
void managesTheSessionFactory() throws Exception {
build();
verify(lifecycleEnvironment).manage(any(SessionFactoryManager.class));
}
@Test
void callsBundleToConfigure() throws Exception {
build();
verify(bundle).configure(any(Configuration.class));
}
@Test
void setsPoolName() {
build();
ArgumentCaptor<SessionFactoryManager> sessionFactoryManager = ArgumentCaptor.forClass(SessionFactoryManager.class);
verify(lifecycleEnvironment).manage(sessionFactoryManager.capture());
assertThat(sessionFactoryManager.getValue().getDataSource())
.isInstanceOfSatisfying(ManagedPooledDataSource.class, dataSource ->
assertThat(dataSource.getPool().getName()).isEqualTo("hibernate"));
}
@Test
void setsACustomPoolName() {
this.sessionFactory = factory.build(bundle, environment, config,
Collections.singletonList(Person.class), "custom-hibernate-db");
ArgumentCaptor<SessionFactoryManager> sessionFactoryManager = ArgumentCaptor.forClass(SessionFactoryManager.class);
verify(lifecycleEnvironment).manage(sessionFactoryManager.capture());
assertThat(sessionFactoryManager.getValue().getDataSource())
.isInstanceOfSatisfying(ManagedPooledDataSource.class, dataSource ->
assertThat(dataSource.getPool().getName()).isEqualTo("custom-hibernate-db"));
}
@Test
void buildsAWorkingSessionFactory() throws Exception {
build();
try (Session session = requireNonNull(sessionFactory).openSession()) {
Transaction transaction = session.beginTransaction();
session.createNativeQuery("DROP TABLE people IF EXISTS").executeUpdate();
session.createNativeQuery("CREATE TABLE people (name varchar(100) primary key, email varchar(100), birthday timestamp(0))").executeUpdate();
session.createNativeQuery("INSERT INTO people VALUES ('Coda', 'coda@example.com', '1979-01-02 00:22:00')").executeUpdate();
transaction.commit();
final Person entity = session.get(Person.class, "Coda");
assertThat(entity.getName())
.isEqualTo("Coda");
assertThat(entity.getEmail())
.isEqualTo("coda@example.com");
assertThat(requireNonNull(entity.getBirthday()).toDateTime(DateTimeZone.UTC))
.isEqualTo(new DateTime(1979, 1, 2, 0, 22, DateTimeZone.UTC));
}
}
@Test
void configureRunsBeforeSessionFactoryCreation() {
final SessionFactoryFactory customFactory = new SessionFactoryFactory() {
@Override
protected void configure(Configuration configuration, ServiceRegistry registry) {
super.configure(configuration, registry);
configuration.setInterceptor(EmptyInterceptor.INSTANCE);
}
};
sessionFactory = customFactory.build(bundle,
environment,
config,
Collections.singletonList(Person.class));
assertThat(sessionFactory.getSessionFactoryOptions().getInterceptor()).isSameAs(EmptyInterceptor.INSTANCE);
}
@Test
void buildBootstrapServiceRegistryRunsBeforeSessionFactoryCreation() {
final SessionFactoryFactory customFactory = new SessionFactoryFactory() {
@Override
protected BootstrapServiceRegistryBuilder configureBootstrapServiceRegistryBuilder(BootstrapServiceRegistryBuilder builder) {
return builder;
}
};
sessionFactory = customFactory.build(bundle,
environment,
config,
Collections.singletonList(Person.class));
assertThat(sessionFactory.getSessionFactoryOptions().getInterceptor()).isSameAs(EmptyInterceptor.INSTANCE);
}
private void build() {
this.sessionFactory = factory.build(bundle,
environment,
config,
Collections.singletonList(Person.class));
}
}
| dropwizard/dropwizard | dropwizard-hibernate/src/test/java/io/dropwizard/hibernate/SessionFactoryFactoryTest.java | Java | apache-2.0 | 6,690 |
<?php
namespace spec\BlockCypher\AppWallet\Infrastructure\Persistence\Flywheel\Document;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class EncryptedWalletDocumentSpec extends ObjectBehavior
{
} | blockcypher/php-wallet-sample | spec/BlockCypher/AppWallet/Infrastructure/Persistence/Flywheel/Document/EncryptedWalletDocumentSpec.php | PHP | apache-2.0 | 203 |
#!/usr/bin/env python
import os
from glob import glob
if os.environ.get('USE_SETUPTOOLS'):
from setuptools import setup
setup_kwargs = dict(zip_safe=0)
else:
from distutils.core import setup
setup_kwargs = dict()
storage_dirs = []
for subdir in ('whisper', 'ceres', 'rrd', 'log', 'log/webapp'):
storage_dirs.append( ('storage/%s' % subdir, []) )
webapp_content = {}
for root, dirs, files in os.walk('webapp/content'):
for filename in files:
filepath = os.path.join(root, filename)
if root not in webapp_content:
webapp_content[root] = []
webapp_content[root].append(filepath)
conf_files = [ ('conf', glob('conf/*.example')) ]
examples = [ ('examples', glob('examples/example-*')) ]
setup(
name='graphite-web',
version='0.10.0-alpha',
url='https://launchpad.net/graphite',
author='Chris Davis',
author_email='chrismd@gmail.com',
license='Apache Software License 2.0',
description='Enterprise scalable realtime graphing',
package_dir={'' : 'webapp'},
packages=[
'graphite',
'graphite.account',
'graphite.browser',
'graphite.cli',
'graphite.composer',
'graphite.dashboard',
'graphite.events',
'graphite.finders',
'graphite.graphlot',
'graphite.metrics',
'graphite.render',
'graphite.version',
'graphite.whitelist',
],
package_data={'graphite' :
['templates/*', 'local_settings.py.example']},
scripts=glob('bin/*'),
data_files=webapp_content.items() + storage_dirs + conf_files + examples,
**setup_kwargs
)
| SEJeff/graphite-web | setup.py | Python | apache-2.0 | 1,530 |
/*******************************************************************************
* Copyright 2008-2013 Amazon.com, Inc. or its affiliates. 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://aws.amazon.com/apache2.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.
* *****************************************************************************
* __ _ _ ___
* ( )( \/\/ )/ __)
* /__\ \ / \__ \
* (_)(_) \/\/ (___/
*
* AWS SDK for .NET
* API Version: 2006-03-01
*
*/
using System;
using System.Security;
using System.Text;
using System.Xml.Serialization;
using System.Collections.Generic;
using System.IO;
using System.Xml;
namespace Amazon.S3.Model
{
/// <summary>
/// The parameters to request the tag set for a bucket.
/// </summary>
public class GetBucketTaggingRequest : S3Request
{
private string bucketName;
/// <summary>
/// The name of the bucket to be queried.
/// </summary>
[XmlElementAttribute(ElementName = "BucketName")]
public string BucketName
{
get { return this.bucketName; }
set { this.bucketName = value; }
}
/// <summary>
/// Sets the name of the bucket to be queried.
/// </summary>
/// <param name="bucketName">The bucket name</param>
/// <returns>the request with the BucketName set</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public GetBucketTaggingRequest WithBucketName(string bucketName)
{
this.bucketName = bucketName;
return this;
}
/// <summary>
/// Checks if BucketName property is set.
/// </summary>
/// <returns>true if BucketName property is set.</returns>
internal bool IsSetBucketName()
{
return !System.String.IsNullOrEmpty(this.bucketName);
}
}
}
| emcvipr/dataservices-sdk-dotnet | AWSSDK/Amazon.S3/Model/GetBucketTaggingRequest.cs | C# | apache-2.0 | 2,429 |
package server
import (
log "github.com/mgutz/logxi/v1"
"github.com/hashicorp/serf/serf"
)
const (
// StatusReap is used to update the status of a node if we
// are handling a EventMemberReap
StatusReap = serf.MemberStatus(-1)
)
// SerfReconciler dispatches membership changes to Raft. If IsLeader is nil,
// the server will panic.
type SerfReconciler struct {
ReconcileCh chan serf.Member
}
// Reconcile is used to reconcile Serf events with the strongly
// consistent store if we are the current leader
func (s *SerfReconciler) Reconcile(m serf.Member) {
select {
case s.ReconcileCh <- m:
default:
}
}
// SerfUserEventHandler handles both local and remote user events in Serf.
type SerfUserEventHandler struct {
Logger log.Logger
UserEventCh chan serf.UserEvent
}
// HandleUserEvent is called when a user event is received from both local and remote nodes.
func (s *SerfUserEventHandler) HandleUserEvent(event serf.UserEvent) {
s.Logger.Debug("kappa: user event: %s", event.Name)
// Send event to processing channel
s.UserEventCh <- event
}
// SerfNodeJoinHandler processes cluster Join events.
type SerfNodeJoinHandler struct {
// ClusterManager ClusterManager
Cluster NodeList
Logger log.Logger
}
// HandleMemberEvent is used to handle join events on the serf cluster.
func (s *SerfNodeJoinHandler) HandleMemberEvent(me serf.MemberEvent) {
for _, m := range me.Members {
details, err := GetKappaServer(m)
if err != nil {
s.Logger.Warn("kappa: error adding server", err)
continue
}
s.Logger.Info("kappa: adding server", details.String())
// Add to the local list as well
s.Cluster.AddNode(*details)
// // If we still expecting to bootstrap, may need to handle this
// if s.config.BootstrapExpect != 0 {
// s.maybeBootstrap()
// }
}
}
type SerfNodeUpdateHandler struct {
Cluster NodeList
Logger log.Logger
}
// nodeJoin is used to handle join events on the both serf clusters
func (s *SerfNodeUpdateHandler) HandleMemberEvent(me serf.MemberEvent) {
for _, m := range me.Members {
details, err := GetKappaServer(m)
if err != nil {
s.Logger.Warn("kappa: error updating server", err)
continue
}
s.Logger.Info("kappa: updating server", details.String())
// Add to the local list as well
s.Cluster.AddNode(*details)
// // If we still expecting to bootstrap, may need to handle this
// if s.config.BootstrapExpect != 0 {
// s.maybeBootstrap()
// }
}
}
// // maybeBootsrap is used to handle bootstrapping when a new consul server joins
// func (s *SerfNodeJoinHandler) maybeBootstrap() {
// // // TODO: Requires Raft!
// // index, err := s.raftStore.LastIndex()
// // if err != nil {
// // s.logger.Error("kappa: failed to read last raft index: %v", err)
// // return
// // }
// // // Bootstrap can only be done if there are no committed logs,
// // // remove our expectations of bootstrapping
// // if index != 0 {
// // s.config.BootstrapExpect = 0
// // return
// // }
// // Scan for all the known servers
// members := s.serf.Members()
// addrs := make([]string, 0)
// for _, member := range members {
// details, err := GetKappaServer(member)
// if err != nil {
// continue
// }
// if details.Cluster != s.config.ClusterName {
// s.Logger.Warn("kappa: Member %v has a conflicting datacenter, ignoring", member)
// continue
// }
// if details.Expect != 0 && details.Expect != s.config.BootstrapExpect {
// s.Logger.Warn("kappa: Member %v has a conflicting expect value. All nodes should expect the same number.", member)
// return
// }
// if details.Bootstrap {
// s.Logger.Warn("kappa: Member %v has bootstrap mode. Expect disabled.", member)
// return
// }
// addr := &net.TCPAddr{IP: member.Addr, Port: details.SSHPort}
// addrs = append(addrs, addr.String())
// }
// // Skip if we haven't met the minimum expect count
// if len(addrs) < s.config.BootstrapExpect {
// return
// }
// // Update the peer set
// // TODO: Requires Raft!
// // s.logger.Info("kappa: Attempting bootstrap with nodes: %v", addrs)
// // if err := s.raft.SetPeers(addrs).Error(); err != nil {
// // s.logger.Error("kappa: failed to bootstrap peers: %v", err)
// // }
// // Bootstrapping complete, don't enter this again
// s.config.BootstrapExpect = 0
// }
// SerfNodeLeaveHandler processes cluster leave events.
type SerfNodeLeaveHandler struct {
Cluster NodeList
Logger log.Logger
}
// HandleMemberEvent is used to handle fail events in the Serf cluster.
func (s *SerfNodeLeaveHandler) HandleMemberEvent(me serf.MemberEvent) {
for _, m := range me.Members {
details, err := GetKappaServer(m)
if err != nil {
continue
}
s.Logger.Info("kappa: removing server %s", details)
// Remove from the local list as well
s.Cluster.RemoveNode(*details)
}
}
| blacklabeldata/kappa | server/serf.go | GO | apache-2.0 | 4,829 |
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.querytransform;
import com.yahoo.component.chain.Chain;
import com.yahoo.prelude.Index;
import com.yahoo.prelude.IndexFacts;
import com.yahoo.prelude.IndexModel;
import com.yahoo.prelude.SearchDefinition;
import com.yahoo.prelude.query.AndItem;
import com.yahoo.prelude.query.DotProductItem;
import com.yahoo.prelude.query.Item;
import com.yahoo.prelude.query.OrItem;
import com.yahoo.prelude.query.WandItem;
import com.yahoo.prelude.query.WeakAndItem;
import com.yahoo.prelude.query.WeightedSetItem;
import com.yahoo.prelude.query.WordItem;
import com.yahoo.processing.request.ErrorMessage;
import com.yahoo.search.Query;
import com.yahoo.search.Result;
import com.yahoo.search.Searcher;
import com.yahoo.search.searchchain.Execution;
import org.junit.Before;
import org.junit.Test;
import java.util.Collections;
import java.util.ListIterator;
import static com.yahoo.container.protect.Error.INVALID_QUERY_PARAMETER;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* Testing of WandSearcher.
*/
public class WandSearcherTestCase {
private static final String VESPA_FIELD = "vespa-field";
private static final double delta = 0.0000001;
private Execution exec;
@SuppressWarnings("deprecation")
private IndexFacts buildIndexFacts() {
SearchDefinition sd = new SearchDefinition("test");
sd.addIndex(new Index(VESPA_FIELD));
return new IndexFacts(new IndexModel(sd));
}
private Execution buildExec() {
return new Execution(new Chain<Searcher>(new WandSearcher()),
Execution.Context.createContextStub(buildIndexFacts()));
}
private Query buildQuery(String wandFieldName, String wandTokens, String wandHeapSize, String wandType, String wandScoreThreshold, String wandThresholdBoostFactor) {
Query q = new Query("");
q.properties().set("wand.field", wandFieldName);
q.properties().set("wand.tokens", wandTokens);
if (wandHeapSize != null) {
q.properties().set("wand.heapSize", wandHeapSize);
}
if (wandType != null) {
q.properties().set("wand.type", wandType);
}
if (wandScoreThreshold != null) {
q.properties().set("wand.scoreThreshold", wandScoreThreshold);
}
if (wandThresholdBoostFactor != null) {
q.properties().set("wand.thresholdBoostFactor", wandThresholdBoostFactor);
}
q.setHits(9);
return q;
}
private Query buildDefaultQuery(String wandFieldName, String wandHeapSize) {
return buildQuery(wandFieldName, "{a:1,b:2,c:3}", wandHeapSize, null, null, null);
}
private Query buildDefaultQuery() {
return buildQuery(VESPA_FIELD, "{a:1,\"b\":2,c:3}", null, null, null, null);
}
private void assertWordItem(String expToken, String expField, int expWeight, Item item) {
WordItem wordItem = (WordItem) item;
assertEquals(expToken, wordItem.getWord());
assertEquals(expField, wordItem.getIndexName());
assertEquals(expWeight, wordItem.getWeight());
}
@Before
public void setUp() throws Exception {
exec = buildExec();
}
@Test
public void requireThatVespaWandCanBeSpecified() {
Query q = buildDefaultQuery();
Result r = exec.search(q);
WeakAndItem root = (WeakAndItem)TestUtils.getQueryTreeRoot(r);
assertEquals(100, root.getN());
assertEquals(3, root.getItemCount());
ListIterator<Item> itr = root.getItemIterator();
assertWordItem("a", VESPA_FIELD, 1, itr.next());
assertWordItem("b", VESPA_FIELD, 2, itr.next());
assertWordItem("c", VESPA_FIELD, 3, itr.next());
assertFalse(itr.hasNext());
}
@Test
public void requireThatVespaWandHeapSizeCanBeSpecified() {
Query q = buildDefaultQuery(VESPA_FIELD, "50");
Result r = exec.search(q);
WeakAndItem root = (WeakAndItem)TestUtils.getQueryTreeRoot(r);
assertEquals(50, root.getN());
}
@Test
public void requireThatWandCanBeSpecifiedTogetherWithNonAndQueryRoot() {
Query q = buildDefaultQuery();
q.getModel().getQueryTree().setRoot(new WordItem("foo", "otherfield"));
Result r = exec.search(q);
AndItem root = (AndItem)TestUtils.getQueryTreeRoot(r);
assertEquals(2, root.getItemCount());
ListIterator<Item> itr = root.getItemIterator();
assertTrue(itr.next() instanceof WordItem);
assertTrue(itr.next() instanceof WeakAndItem);
assertFalse(itr.hasNext());
}
@Test
public void requireThatWandCanBeSpecifiedTogetherWithAndQueryRoot() {
Query q = buildDefaultQuery();
{
AndItem root = new AndItem();
root.addItem(new WordItem("foo", "otherfield"));
root.addItem(new WordItem("bar", "otherfield"));
q.getModel().getQueryTree().setRoot(root);
}
Result r = exec.search(q);
AndItem root = (AndItem)TestUtils.getQueryTreeRoot(r);
assertEquals(3, root.getItemCount());
ListIterator<Item> itr = root.getItemIterator();
assertTrue(itr.next() instanceof WordItem);
assertTrue(itr.next() instanceof WordItem);
assertTrue(itr.next() instanceof WeakAndItem);
assertFalse(itr.hasNext());
}
@Test
public void requireThatNothingIsAddedWithoutWandPropertiesSet() {
Query foo = new Query("");
foo.getModel().getQueryTree().setRoot(new WordItem("foo", "otherfield"));
Result r = exec.search(foo);
WordItem root = (WordItem)TestUtils.getQueryTreeRoot(r);
assertEquals("foo", root.getWord());
}
@Test
public void requireThatErrorIsReturnedOnInvalidTokenList() {
Query q = buildQuery(VESPA_FIELD, "{a1,b:1}", null, null, null, null);
Result r = exec.search(q);
ErrorMessage msg = r.hits().getError();
assertNotNull(msg);
assertEquals(INVALID_QUERY_PARAMETER.code, msg.getCode());
assertEquals("'{a1,b:1}' is not a legal sparse vector string: Expected ':' starting at position 3 but was ','",msg.getDetailedMessage());
}
@Test
public void requireThatErrorIsReturnedOnUnknownField() {
Query q = buildDefaultQuery("unknown", "50");
Result r = exec.search(q);
ErrorMessage msg = r.hits().getError();
assertNotNull(msg);
assertEquals(INVALID_QUERY_PARAMETER.code, msg.getCode());
assertEquals("Field 'unknown' was not found in index facts for search definitions [test]",msg.getDetailedMessage());
}
@Test
public void requireThatVespaOrCanBeSpecified() {
Query q = buildQuery(VESPA_FIELD, "{a:1,b:2,c:3}", null, "or", null, null);
Result r = exec.search(q);
OrItem root = (OrItem)TestUtils.getQueryTreeRoot(r);
assertEquals(3, root.getItemCount());
ListIterator<Item> itr = root.getItemIterator();
assertWordItem("a", VESPA_FIELD, 1, itr.next());
assertWordItem("b", VESPA_FIELD, 2, itr.next());
assertWordItem("c", VESPA_FIELD, 3, itr.next());
assertFalse(itr.hasNext());
}
private void assertWeightedSetItem(WeightedSetItem item) {
assertEquals(3, item.getNumTokens());
assertEquals(Integer.valueOf(1), item.getTokenWeight("a"));
assertEquals(Integer.valueOf(2), item.getTokenWeight("b"));
assertEquals(Integer.valueOf(3), item.getTokenWeight("c"));
}
@Test
public void requireThatDefaultParallelWandCanBeSpecified() {
Query q = buildQuery(VESPA_FIELD, "{a:1,b:2,c:3}", null, "parallel", null, null);
Result r = exec.search(q);
WandItem root = (WandItem)TestUtils.getQueryTreeRoot(r);
assertEquals(VESPA_FIELD, root.getIndexName());
assertEquals(100, root.getTargetNumHits());
assertEquals(0.0, root.getScoreThreshold(), delta);
assertEquals(1.0, root.getThresholdBoostFactor(), delta);
assertWeightedSetItem(root);
}
@Test
public void requireThatParallelWandCanBeSpecified() {
Query q = buildQuery(VESPA_FIELD, "{a:1,b:2,c:3}", "50", "parallel", "70.5", "2.3");
Result r = exec.search(q);
WandItem root = (WandItem)TestUtils.getQueryTreeRoot(r);
assertEquals(VESPA_FIELD, root.getIndexName());
assertEquals(50, root.getTargetNumHits());
assertEquals(70.5, root.getScoreThreshold(), delta);
assertEquals(2.3, root.getThresholdBoostFactor(), delta);
assertWeightedSetItem(root);
}
@Test
public void requireThatDotProductCanBeSpecified() {
Query q = buildQuery(VESPA_FIELD, "{a:1,b:2,c:3}", null, "dotProduct", null, null);
Result r = exec.search(q);
DotProductItem root = (DotProductItem)TestUtils.getQueryTreeRoot(r);
assertEquals(VESPA_FIELD, root.getIndexName());
assertWeightedSetItem(root);
}
}
| vespa-engine/vespa | container-search/src/test/java/com/yahoo/search/querytransform/WandSearcherTestCase.java | Java | apache-2.0 | 9,211 |
// Copyright 2016 IBM Corporation
//
// 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 kubernetes
import (
"encoding/json"
// "k8s.io/client-go/pkg/api"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
// "k8s.io/client-go/pkg/api/unversioned"
"k8s.io/apimachinery/pkg/runtime/schema"
a8api "github.com/amalgam8/amalgam8/pkg/api"
)
const (
// ResourceName defines the name of the third party resource in kubernetes
ResourceName = "routing-rule"
// ResourceKind defines the kind of the third party resource in kubernetes
ResourceKind = "RoutingRule"
// ResourceGroupName defines the group name of the third party resource in kubernetes
ResourceGroupName = "amalgam8.io"
// ResourceVersion defines the version of the third party resource in kubernetes
ResourceVersion = "v1"
// ResourceDescription defines the description of the third party resource in kubernetes
ResourceDescription = "A specification of an Amalgam8 rule resource"
// RuleStateValid defines the state of a valid rule resource
RuleStateValid = "valid"
// RuleStateInvalid defines the state of an invalid rule resource
RuleStateInvalid = "invalid"
)
// StatusSpec defines third party resource status
type StatusSpec struct {
State string `json:"state,omitempty"`
Message string `json:"message,omitempty"`
}
// RoutingRule defines the third party resource spec
type RoutingRule struct {
metav1.TypeMeta `json:",inline"`
Metadata metav1.ObjectMeta `json:"metadata"`
Spec a8api.Rule `json:"spec,omitempty"`
Status StatusSpec `json:"status,omitempty"`
}
// RoutingRuleList defines list of rules
type RoutingRuleList struct {
metav1.TypeMeta `json:",inline"`
Metadata metav1.ListMeta `json:"metadata"`
Items []RoutingRule `json:"items"`
}
// GetObjectKind - Required to satisfy Object interface
func (r *RoutingRule) GetObjectKind() schema.ObjectKind {
return &r.TypeMeta
}
// GetObjectMeta - Required to satisfy ObjectMetaAccessor interface
func (r *RoutingRule) GetObjectMeta() metav1.Object {
return &r.Metadata
}
// GetObjectKind - Required to satisfy Object interface
func (rl *RoutingRuleList) GetObjectKind() schema.ObjectKind {
return &rl.TypeMeta
}
// GetListMeta - Required to satisfy ListMetaAccessor interface
func (rl *RoutingRuleList) GetListMeta() metav1.List {
return &rl.Metadata
}
// The code below is used only to work around a known problem with third-party
// resources and ugorji. If/when these issues are resolved, the code below
// should no longer be required.
// RuleListCopy defines list of rules
type RuleListCopy RoutingRuleList
// RuleCopy defines a rule resource
type RuleCopy RoutingRule
// UnmarshalJSON parses the JSON-encoded data and stores the result in the value pointed to by r
func (r *RoutingRule) UnmarshalJSON(data []byte) error {
tmp := RuleCopy{}
err := json.Unmarshal(data, &tmp)
if err != nil {
return err
}
tmp2 := RoutingRule(tmp)
*r = tmp2
return nil
}
// UnmarshalJSON parses the JSON-encoded data and stores the result in the value pointed to by rl
func (rl *RoutingRuleList) UnmarshalJSON(data []byte) error {
tmp := RuleListCopy{}
err := json.Unmarshal(data, &tmp)
if err != nil {
return err
}
tmp2 := RoutingRuleList(tmp)
*rl = tmp2
return nil
}
| kimikowang/istio_vms | pkg/adapters/rules/kubernetes/routingrule.go | GO | apache-2.0 | 3,784 |
/*
* Copyright 2018 Mikhail Shiryaev
*
* 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.
*
*
* Product : Rapid SCADA
* Module : KpModbus
* Summary : The factory for creating device templates
*
* Author : Mikhail Shiryaev
* Created : 2018
* Modified : 2018
*/
using Scada.Comm.Devices.Modbus.Protocol;
namespace Scada.Comm.Devices.Modbus
{
/// <summary>
/// The factory for creating device templates.
/// <para>Фабрика для для создания шаблонов устройства.</para>
/// </summary>
public class DeviceTemplateFactory
{
/// <summary>
/// Creates a new device template.
/// </summary>
public virtual DeviceTemplate CreateDeviceTemplate()
{
return new DeviceTemplate();
}
}
}
| RapidScada/scada | ScadaComm/OpenKPs/KpModbus/Modbus/DeviceTemplateFactory.cs | C# | apache-2.0 | 1,331 |