code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
package enhancedsnapshots.dto.converter;
import com.sungardas.enhancedsnapshots.aws.dynamodb.model.TaskEntry;
import com.sungardas.enhancedsnapshots.dto.TaskDto;
import com.sungardas.enhancedsnapshots.dto.converter.TaskDtoConverter;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
public class TaskDtoConverterTest {
private String id = "Id1";
private String priority = "2";
private String status = "queued";
private String type = "backup";
private List<String> volumes = Arrays.asList("vol-c343123b", "vol-c34232");
private String schedulerManual = "false";
private String schedulerName = "everyYear";
private String schedulerTime = "00:03:82";
private String instanceId = "i-6easdads";
private String backupFileName = "someFileName";
private String cron = "0 0 1 1 *";
private String zone = "az";
private String regular = Boolean.TRUE.toString();
private String enabled = "true";
private TaskDto taskDto;
@Before
public void setUp(){
taskDto = new TaskDto();
taskDto.setId(id);
taskDto.setPriority(priority);
taskDto.setType(type);
taskDto.setStatus(status);
taskDto.setVolumes(volumes);
taskDto.setSchedulerManual(schedulerManual);
taskDto.setSchedulerTime(schedulerTime);
taskDto.setSchedulerName(schedulerName);
taskDto.setBackupFileName(backupFileName);
taskDto.setCron(cron);
taskDto.setZone(zone);
taskDto.setRegular(regular);
taskDto.setEnabled(enabled);
}
@Test
public void shouldConvertFromTaskDtoToTaskEnty(){
List<TaskEntry> taskEntries = TaskDtoConverter.convert(taskDto);
// assert there are 2 taskEntries since there are 2 volumes in the volumes list
Assert.assertTrue(taskEntries.size() == 2);
// check properties values
for(TaskEntry taskEntry: taskEntries) {
Assert.assertTrue(taskEntry.getId().equals(id));
// backup priority is 0
Assert.assertTrue(taskEntry.getPriority() == 0);
Assert.assertTrue(taskEntry.getType().equals(type));
Assert.assertTrue(taskEntry.getStatus().equals(status));
Assert.assertTrue(taskEntry.getSchedulerManual().equals(schedulerManual));
Assert.assertTrue(taskEntry.getSchedulerName().equals(schedulerName));
//TODO: find out what if instance ids were different while backup of several volumes ???
Assert.assertTrue(taskEntry.getCron().equals(cron));
Assert.assertTrue(taskEntry.getAvailabilityZone().equals(zone));
Assert.assertTrue(taskEntry.getEnabled().equals(enabled));
}
// check volume id of first taskEntry
Assert.assertTrue(taskEntries.get(0).getVolume().equals(volumes.get(0)));
// check volume id of second taskEntry
Assert.assertTrue(taskEntries.get(1).getVolume().equals(volumes.get(1)));
}
@Test
public void shouldSetPriority1ForDeleteTasks(){
taskDto.setType("delete");
List<TaskEntry> taskEntries = TaskDtoConverter.convert(taskDto);
// check priority of first taskEntry
Assert.assertTrue(taskEntries.get(0).getPriority() == 1);
// check priority of second taskEntry
Assert.assertTrue(taskEntries.get(1).getPriority() == 1);
}
}
|
SungardAS/enhanced-snapshots
|
test/com/sungardas/enhancedsnapshots/dto/converter/TaskDtoConverterTest.java
|
Java
|
apache-2.0
| 3,447
|
/*
* 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.gobblin.service;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import com.google.common.base.Suppliers;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import com.google.inject.Binder;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;
import com.linkedin.restli.server.resources.BaseResource;
import org.apache.gobblin.configuration.State;
import org.apache.gobblin.metastore.StateStore;
import org.apache.gobblin.restli.EmbeddedRestliServer;
import org.apache.gobblin.runtime.troubleshooter.MultiContextIssueRepository;
import org.apache.gobblin.service.monitoring.FlowStatusGenerator;
import org.apache.gobblin.service.monitoring.JobStatusRetriever;
import static org.mockito.Mockito.mock;
@Test(groups = { "gobblin.service" }, singleThreaded = true)
public class FlowStatusTest {
private FlowStatusClient _client;
private EmbeddedRestliServer _server;
private List<List<org.apache.gobblin.service.monitoring.JobStatus>> _listOfJobStatusLists;
class TestJobStatusRetriever extends JobStatusRetriever {
protected TestJobStatusRetriever(MultiContextIssueRepository issueRepository) {
super(issueRepository);
}
@Override
public Iterator<org.apache.gobblin.service.monitoring.JobStatus> getJobStatusesForFlowExecution(String flowName,
String flowGroup, long flowExecutionId) {
return _listOfJobStatusLists.get((int) flowExecutionId).iterator();
}
@Override
public Iterator<org.apache.gobblin.service.monitoring.JobStatus> getJobStatusesForFlowExecution(String flowName,
String flowGroup, long flowExecutionId, String jobGroup, String jobName) {
return Iterators.emptyIterator();
}
@Override
public StateStore<State> getStateStore() {
return null;
}
@Override
public List<Long> getLatestExecutionIdsForFlow(String flowName, String flowGroup, int count) {
if (_listOfJobStatusLists == null) {
return null;
}
int startIndex = (_listOfJobStatusLists.size() >= count) ? _listOfJobStatusLists.size() - count : 0;
List<Long> flowExecutionIds = IntStream.range(startIndex, _listOfJobStatusLists.size()).mapToObj(i -> (long) i)
.collect(Collectors.toList());
Collections.reverse(flowExecutionIds);
return flowExecutionIds;
}
@Override
public List<org.apache.gobblin.service.monitoring.FlowStatus> getFlowStatusesForFlowGroupExecutions(String flowGroup,
int countJobStatusesPerFlowName) {
return Lists.newArrayList(); // (as this method not exercised within `FlowStatusResource`)
}
}
@BeforeClass
public void setUp() throws Exception {
JobStatusRetriever jobStatusRetriever = new TestJobStatusRetriever(mock(MultiContextIssueRepository.class));
final FlowStatusGenerator flowStatusGenerator = new FlowStatusGenerator(jobStatusRetriever);
Injector injector = Guice.createInjector(new Module() {
@Override
public void configure(Binder binder) {
binder.bind(FlowStatusGenerator.class)
.toInstance(flowStatusGenerator);
}
});
_server = EmbeddedRestliServer.builder().resources(
Lists.<Class<? extends BaseResource>>newArrayList(FlowStatusResource.class)).injector(injector).build();
_server.startAsync();
_server.awaitRunning();
_client =
new FlowStatusClient(String.format("http://localhost:%s/", _server.getPort()));
}
/**
* Test finding the latest flow status
* @throws Exception
*/
@Test
public void testFindLatest() throws Exception {
org.apache.gobblin.service.monitoring.JobStatus js1 =
org.apache.gobblin.service.monitoring.JobStatus.builder().flowGroup("fgroup1").flowName("flow1")
.jobGroup("jgroup1").jobName("job1").startTime(1000L).endTime(5000L)
.eventName(ExecutionStatus.COMPLETE.name()).flowExecutionId(0).message("Test message 1").processedCount(100)
.jobExecutionId(1).lowWatermark("watermark:1").highWatermark("watermark:2")
.issues(Suppliers.ofInstance(Collections.emptyList())).build();
org.apache.gobblin.service.monitoring.JobStatus fs1 =
org.apache.gobblin.service.monitoring.JobStatus.builder().flowGroup("fgroup1").flowName("flow1")
.jobGroup(JobStatusRetriever.NA_KEY).jobName(JobStatusRetriever.NA_KEY).endTime(5000L)
.eventName(ExecutionStatus.COMPLETE.name()).flowExecutionId(0)
.issues(Suppliers.ofInstance(Collections.emptyList())).build();
org.apache.gobblin.service.monitoring.JobStatus js2 =
org.apache.gobblin.service.monitoring.JobStatus.builder().flowGroup("fgroup1").flowName("flow1")
.jobGroup("jgroup1").jobName("job1").jobTag("dataset1").startTime(2000L).endTime(6000L)
.eventName(ExecutionStatus.COMPLETE.name()).flowExecutionId(1).message("Test message 2").processedCount(200)
.jobExecutionId(2).lowWatermark("watermark:2").highWatermark("watermark:3")
.issues(Suppliers.ofInstance(Collections.emptyList()))
.build();
org.apache.gobblin.service.monitoring.JobStatus js3 =
org.apache.gobblin.service.monitoring.JobStatus.builder().flowGroup("fgroup1").flowName("flow1")
.jobGroup("jgroup1").jobName("job2").jobTag("dataset2").startTime(2000L).endTime(6000L)
.eventName(ExecutionStatus.COMPLETE.name()).flowExecutionId(1).message("Test message 3").processedCount(200)
.jobExecutionId(2).lowWatermark("watermark:2").highWatermark("watermark:3")
.issues(Suppliers.ofInstance(Collections.emptyList()))
.build();
org.apache.gobblin.service.monitoring.JobStatus fs2 =
org.apache.gobblin.service.monitoring.JobStatus.builder().flowGroup("fgroup1").flowName("flow1")
.jobGroup(JobStatusRetriever.NA_KEY).jobName(JobStatusRetriever.NA_KEY).endTime(7000L)
.eventName(ExecutionStatus.COMPLETE.name()).flowExecutionId(1).message("Flow message")
.issues(Suppliers.ofInstance(Collections.emptyList())).build();
List<org.apache.gobblin.service.monitoring.JobStatus> jobStatusList1 = Lists.newArrayList(js1, fs1);
List<org.apache.gobblin.service.monitoring.JobStatus> jobStatusList2 = Lists.newArrayList(js2, js3, fs2);
_listOfJobStatusLists = Lists.newArrayList();
_listOfJobStatusLists.add(jobStatusList1);
_listOfJobStatusLists.add(jobStatusList2);
FlowId flowId = new FlowId().setFlowGroup("fgroup1").setFlowName("flow1");
FlowStatus flowStatus = _client.getLatestFlowStatus(flowId);
Assert.assertEquals(flowStatus.getId().getFlowGroup(), "fgroup1");
Assert.assertEquals(flowStatus.getId().getFlowName(), "flow1");
Assert.assertEquals(flowStatus.getExecutionStatistics().getExecutionStartTime().longValue(), 1L);
Assert.assertEquals(flowStatus.getExecutionStatistics().getExecutionEndTime().longValue(), 7000L);
Assert.assertEquals(flowStatus.getMessage(), fs2.getMessage());
Assert.assertEquals(flowStatus.getExecutionStatus(), ExecutionStatus.COMPLETE);
JobStatusArray jobStatuses = flowStatus.getJobStatuses();
Assert.assertEquals(jobStatusList2.size(), jobStatuses.size() + 1);
for (int i = 0; i < jobStatuses.size(); i++) {
org.apache.gobblin.service.monitoring.JobStatus mjs = jobStatusList2.get(i);
JobStatus js = jobStatuses.get(i);
compareJobStatus(js, mjs);
}
List<FlowStatus> flowStatusList = _client.getLatestFlowStatus(flowId, 2, null);
Assert.assertEquals(flowStatusList.size(), 2);
Assert.assertEquals(flowStatusList.get(0).getId().getFlowExecutionId(), (Long) 1L);
Assert.assertEquals(flowStatusList.get(1).getId().getFlowExecutionId(), (Long) 0L);
Assert.assertEquals(flowStatusList.get(0).getJobStatuses().size(), 2);
List<FlowStatus> flowStatusList2 = _client.getLatestFlowStatus(flowId, 1, "dataset1");
Assert.assertEquals(flowStatusList2.get(0).getJobStatuses().size(), 1);
Assert.assertEquals(flowStatusList2.get(0).getJobStatuses().get(0).getJobTag(), "dataset1");
}
/**
* Test a flow that has all jobs completed
* @throws Exception
*/
@Test
public void testGetCompleted() throws Exception {
org.apache.gobblin.service.monitoring.JobStatus js1 =
org.apache.gobblin.service.monitoring.JobStatus.builder().flowGroup("fgroup1").flowName("flow1")
.jobGroup("jgroup1").jobName("job1").startTime(1000L).endTime(5000L)
.eventName(ExecutionStatus.COMPLETE.name()).flowExecutionId(0).message("Test message 1").processedCount(100)
.jobExecutionId(1).lowWatermark("watermark:1").highWatermark("watermark:2")
.issues(Suppliers.ofInstance(Collections.emptyList()))
.build();
org.apache.gobblin.service.monitoring.JobStatus js2 =
org.apache.gobblin.service.monitoring.JobStatus.builder().flowGroup("fgroup1").flowName("flow1")
.jobGroup("jgroup1").jobName("job2").startTime(2000L).endTime(6000L)
.eventName(ExecutionStatus.COMPLETE.name()).flowExecutionId(0).message("Test message 2").processedCount(200)
.jobExecutionId(2).lowWatermark("watermark:2").highWatermark("watermark:3")
.issues(Suppliers.ofInstance(Collections.emptyList()))
.build();
org.apache.gobblin.service.monitoring.JobStatus fs1 =
org.apache.gobblin.service.monitoring.JobStatus.builder().flowGroup("fgroup1").flowName("flow1")
.jobGroup(JobStatusRetriever.NA_KEY).jobName(JobStatusRetriever.NA_KEY).endTime(7000L)
.eventName(ExecutionStatus.COMPLETE.name()).flowExecutionId(0).message("Flow message")
.issues(Suppliers.ofInstance(Collections.emptyList())).build();
List<org.apache.gobblin.service.monitoring.JobStatus> jobStatusList = Lists.newArrayList(js1, js2, fs1);
_listOfJobStatusLists = Lists.newArrayList();
_listOfJobStatusLists.add(jobStatusList);
FlowStatusId flowId = new FlowStatusId().setFlowGroup("fgroup1").setFlowName("flow1").setFlowExecutionId(0);
FlowStatus flowStatus = _client.getFlowStatus(flowId);
Assert.assertEquals(flowStatus.getId().getFlowGroup(), "fgroup1");
Assert.assertEquals(flowStatus.getId().getFlowName(), "flow1");
Assert.assertEquals(flowStatus.getExecutionStatistics().getExecutionStartTime().longValue(), 0L);
Assert.assertEquals(flowStatus.getExecutionStatistics().getExecutionEndTime().longValue(), 7000L);
Assert.assertEquals(flowStatus.getMessage(), fs1.getMessage());
Assert.assertEquals(flowStatus.getExecutionStatus(), ExecutionStatus.COMPLETE);
JobStatusArray jobStatuses = flowStatus.getJobStatuses();
Assert.assertEquals(jobStatusList.size(), jobStatuses.size() + 1);
for (int i = 0; i < jobStatuses.size(); i++) {
org.apache.gobblin.service.monitoring.JobStatus mjs = jobStatusList.get(i);
JobStatus js = jobStatuses.get(i);
compareJobStatus(js, mjs);
}
}
/**
* Test a flow that has some jobs still running
* @throws Exception
*/
@Test
public void testGetRunning() throws Exception {
org.apache.gobblin.service.monitoring.JobStatus js1 =
org.apache.gobblin.service.monitoring.JobStatus.builder().flowGroup("fgroup1").flowName("flow1")
.jobGroup("jgroup1").jobName("job1").startTime(1000L).endTime(5000L)
.eventName(ExecutionStatus.RUNNING.name()).flowExecutionId(0).message("Test message 1").processedCount(100)
.jobExecutionId(1).lowWatermark("watermark:1").highWatermark("watermark:2")
.issues(Suppliers.ofInstance(Collections.emptyList()))
.build();
org.apache.gobblin.service.monitoring.JobStatus js2 =
org.apache.gobblin.service.monitoring.JobStatus.builder().flowGroup("fgroup1").flowName("flow1")
.jobGroup("jgroup1").jobName("job2").startTime(2000L).endTime(6000L)
.eventName(ExecutionStatus.COMPLETE.name()).flowExecutionId(0).message("Test message 2").processedCount(200)
.jobExecutionId(2).lowWatermark("watermark:2").highWatermark("watermark:3")
.issues(Suppliers.ofInstance(Collections.emptyList()))
.build();
org.apache.gobblin.service.monitoring.JobStatus fs1 =
org.apache.gobblin.service.monitoring.JobStatus.builder().flowGroup("fgroup1").flowName("flow1")
.jobGroup(JobStatusRetriever.NA_KEY).jobName(JobStatusRetriever.NA_KEY)
.eventName(ExecutionStatus.RUNNING.name()).flowExecutionId(0).message("Flow message")
.issues(Suppliers.ofInstance(Collections.emptyList())).build();
List<org.apache.gobblin.service.monitoring.JobStatus> jobStatusList = Lists.newArrayList(js1, js2, fs1);
_listOfJobStatusLists = Lists.newArrayList();
_listOfJobStatusLists.add(jobStatusList);
FlowStatusId flowId = new FlowStatusId().setFlowGroup("fgroup1").setFlowName("flow1").setFlowExecutionId(0);
FlowStatus flowStatus = _client.getFlowStatus(flowId);
Assert.assertEquals(flowStatus.getId().getFlowGroup(), "fgroup1");
Assert.assertEquals(flowStatus.getId().getFlowName(), "flow1");
Assert.assertEquals(flowStatus.getExecutionStatistics().getExecutionStartTime().longValue(), 0L);
Assert.assertEquals(flowStatus.getExecutionStatistics().getExecutionEndTime().longValue(), 0L);
Assert.assertEquals(flowStatus.getMessage(), fs1.getMessage());
Assert.assertEquals(flowStatus.getExecutionStatus(), ExecutionStatus.RUNNING);
JobStatusArray jobStatuses = flowStatus.getJobStatuses();
Assert.assertEquals(jobStatusList.size(), jobStatuses.size() + 1);
for (int i = 0; i < jobStatuses.size(); i++) {
org.apache.gobblin.service.monitoring.JobStatus mjs = jobStatusList.get(i);
JobStatus js = jobStatuses.get(i);
compareJobStatus(js, mjs);
}
}
/**
* Test a flow that has some failed jobs
* @throws Exception
*/
@Test
public void testGetFailed() throws Exception {
org.apache.gobblin.service.monitoring.JobStatus js1 =
org.apache.gobblin.service.monitoring.JobStatus.builder().flowGroup("fgroup1").flowName("flow1")
.jobGroup("jgroup1").jobName("job1").startTime(1000L).endTime(5000L)
.eventName(ExecutionStatus.COMPLETE.name()).flowExecutionId(0).message("Test message 1").processedCount(100)
.jobExecutionId(1).lowWatermark("watermark:1").highWatermark("watermark:2")
.issues(Suppliers.ofInstance(Collections.emptyList()))
.build();
org.apache.gobblin.service.monitoring.JobStatus js2 =
org.apache.gobblin.service.monitoring.JobStatus.builder().flowGroup("fgroup1").flowName("flow1")
.jobGroup("jgroup1").jobName("job2").startTime(2000L).endTime(6000L)
.eventName(ExecutionStatus.FAILED.name()).flowExecutionId(0).message("Test message 2").processedCount(200)
.jobExecutionId(2).lowWatermark("watermark:2").highWatermark("watermark:3")
.issues(Suppliers.ofInstance(Collections.emptyList()))
.build();
org.apache.gobblin.service.monitoring.JobStatus fs1 =
org.apache.gobblin.service.monitoring.JobStatus.builder().flowGroup("fgroup1").flowName("flow1")
.jobGroup(JobStatusRetriever.NA_KEY).jobName(JobStatusRetriever.NA_KEY).endTime(7000L)
.eventName(ExecutionStatus.FAILED.name()).flowExecutionId(0).message("Flow message")
.issues(Suppliers.ofInstance(Collections.emptyList())).build();
List<org.apache.gobblin.service.monitoring.JobStatus> jobStatusList = Lists.newArrayList(js1, js2, fs1);
_listOfJobStatusLists = Lists.newArrayList();
_listOfJobStatusLists.add(jobStatusList);
FlowStatusId flowId = new FlowStatusId().setFlowGroup("fgroup1").setFlowName("flow1").setFlowExecutionId(0);
FlowStatus flowStatus = _client.getFlowStatus(flowId);
Assert.assertEquals(flowStatus.getId().getFlowGroup(), "fgroup1");
Assert.assertEquals(flowStatus.getId().getFlowName(), "flow1");
Assert.assertEquals(flowStatus.getExecutionStatistics().getExecutionStartTime().longValue(), 0L);
Assert.assertEquals(flowStatus.getExecutionStatistics().getExecutionEndTime().longValue(), 7000L);
Assert.assertEquals(flowStatus.getMessage(), fs1.getMessage());
Assert.assertEquals(flowStatus.getExecutionStatus(), ExecutionStatus.FAILED);
JobStatusArray jobStatuses = flowStatus.getJobStatuses();
Assert.assertEquals(jobStatusList.size(), jobStatuses.size() + 1);
for (int i = 0; i < jobStatuses.size(); i++) {
org.apache.gobblin.service.monitoring.JobStatus mjs = jobStatusList.get(i);
JobStatus js = jobStatuses.get(i);
compareJobStatus(js, mjs);
}
}
@AfterClass(alwaysRun = true)
public void tearDown() throws Exception {
if (_client != null) {
_client.close();
}
if (_server != null) {
_server.stopAsync();
_server.awaitTerminated();
}
}
/**
* compare the job status objects from the REST call and monitoring service
* @param js JobStatus from REST
* @param mjs JobStatus from monitoring
*/
private void compareJobStatus(JobStatus js, org.apache.gobblin.service.monitoring.JobStatus mjs) {
Assert.assertEquals(mjs.getFlowGroup(), js.getFlowId().getFlowGroup());
Assert.assertEquals(mjs.getFlowName(), js.getFlowId().getFlowName());
Assert.assertEquals(mjs.getJobGroup(), js.getJobId().getJobGroup());
Assert.assertEquals(mjs.getJobName(), js.getJobId().getJobName());
Assert.assertEquals(mjs.getMessage(), js.getMessage());
Assert.assertEquals(mjs.getStartTime(), js.getExecutionStatistics().getExecutionStartTime().longValue());
Assert.assertEquals(mjs.getEndTime(), js.getExecutionStatistics().getExecutionEndTime().longValue());
Assert.assertEquals(mjs.getProcessedCount(), js.getExecutionStatistics().getProcessedCount().longValue());
Assert.assertEquals(mjs.getLowWatermark(), js.getJobState().getLowWatermark());
Assert.assertEquals(mjs.getHighWatermark(), js.getJobState().getHighWatermark());
}
}
|
linkedin/gobblin
|
gobblin-restli/gobblin-flow-config-service/gobblin-flow-config-service-client/src/test/java/org/apache/gobblin/service/FlowStatusTest.java
|
Java
|
apache-2.0
| 19,211
|
#!/usr/bin/env bash
# Run this script from the top level directory of this repository.
# Usage: ./ui/example/type-subtype-value/scripts/start.sh [any extra mvn command arguments, e.g -am to build all dependencies]
mvn clean install -pl :ui -Ptype-subtype-value,quick $@
|
gchq/gaffer-tools
|
ui/example/type-subtype-value/scripts/start.sh
|
Shell
|
apache-2.0
| 271
|
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.tsunami.plugins.detectors.rce.tomcat.ghostcat.ajp;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.assistedinject.FactoryModuleBuilder;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.concurrent.atomic.AtomicInteger;
import javax.inject.Inject;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
/** Unit tests for {@link AjpConnectionImpl}. */
@RunWith(JUnit4.class)
public class AjpConnectionImplTest {
private static final String REQ_URI = "/manager/xxxxx.jsp";
private static final String PATH = "/WEB-INF/web.xml";
private static final byte[] VALID_RESPONSE = {
// AJP13_END_RESPONSE (5)
'A', 'B', // magic
0, 2, // size
5, // packet prefix
1, // reuse
};
@Rule public MockitoRule rule = MockitoJUnit.rule();
@Mock Socket socketMock;
@Inject AjpConnection.Factory ajpConnectionFactory;
@Before
public void setUp() throws IOException {
Guice.createInjector(
new FactoryModuleBuilder()
.implement(AjpConnection.class, AjpConnectionImpl.class)
.build(AjpConnection.Factory.class),
new AbstractModule() {
@Override
protected void configure() {
bind(Socket.class).toInstance(socketMock);
}
})
.injectMembers(this);
when(socketMock.getOutputStream()).thenReturn(new ByteArrayOutputStream());
when(socketMock.getInputStream()).thenReturn(new ByteArrayInputStream(VALID_RESPONSE));
}
@Test
public void performGhostcat_always_establishesConnection() throws IOException {
ajpConnectionFactory.create("1.1.1.1", 80).performGhostcat(REQ_URI, PATH);
verify(socketMock, times(1)).connect(new InetSocketAddress("1.1.1.1", 80));
}
@Test
public void performGhostcat_always_writesThenReads() throws IOException {
AtomicInteger step = new AtomicInteger(0);
when(socketMock.getOutputStream())
.thenAnswer(
invocation -> {
assertThat(step.incrementAndGet()).isEqualTo(1);
return new ByteArrayOutputStream();
});
when(socketMock.getInputStream())
.thenAnswer(
invocation -> {
assertThat(step.incrementAndGet()).isEqualTo(2);
return new ByteArrayInputStream(VALID_RESPONSE);
});
ajpConnectionFactory.create("1.1.1.1", 80).performGhostcat(REQ_URI, PATH);
assertThat(step.get()).isEqualTo(2);
}
@Test
public void performGhostcat_whenSocketConnectThrows_rethrowsException() throws IOException {
IOException ioException = new IOException("failed connection");
doThrow(ioException).when(socketMock).connect(any());
IOException exception =
assertThrows(
IOException.class,
() -> ajpConnectionFactory.create("1.1.1.1", 80).performGhostcat(REQ_URI, PATH));
assertThat(exception).isSameInstanceAs(ioException);
}
}
|
google/tsunami-security-scanner-plugins
|
google/detectors/rce/tomcat/ghostcat/src/test/java/com/google/tsunami/plugins/detectors/rce/tomcat/ghostcat/ajp/AjpConnectionImplTest.java
|
Java
|
apache-2.0
| 4,208
|
//snippet-sourcedescription:[list_users.cpp demonstrates how to list IAM users.]
//snippet-keyword:[C++]
//snippet-sourcesyntax:[cpp]
//snippet-keyword:[Code Sample]
//snippet-keyword:[AWS Identity and Access Management (IAM)]
//snippet-service:[iam]
//snippet-sourcetype:[full-example]
//snippet-sourcedate:[]
//snippet-sourceauthor:[AWS]
/*
Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
This file is 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/
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.
*/
//snippet-start:[iam.cpp.list_users.inc]
#include <aws/core/Aws.h>
#include <aws/iam/IAMClient.h>
#include <aws/iam/model/ListUsersRequest.h>
#include <aws/iam/model/ListUsersResult.h>
#include <iomanip>
#include <iostream>
//snippet-end:[iam.cpp.list_users.inc]
static const char* DATE_FORMAT = "%Y-%m-%d";
/**
* Lists all iam users
*/
int main(int argc, char** argv)
{
Aws::SDKOptions options;
Aws::InitAPI(options);
{
// snippet-start:[iam.cpp.list_users.code]
Aws::IAM::IAMClient iam;
Aws::IAM::Model::ListUsersRequest request;
bool done = false;
bool header = false;
while (!done)
{
auto outcome = iam.ListUsers(request);
if (!outcome.IsSuccess())
{
std::cout << "Failed to list iam users:" <<
outcome.GetError().GetMessage() << std::endl;
break;
}
if (!header)
{
std::cout << std::left << std::setw(32) << "Name" <<
std::setw(30) << "ID" << std::setw(64) << "Arn" <<
std::setw(20) << "CreateDate" << std::endl;
header = true;
}
const auto &users = outcome.GetResult().GetUsers();
for (const auto &user : users)
{
std::cout << std::left << std::setw(32) << user.GetUserName() <<
std::setw(30) << user.GetUserId() << std::setw(64) <<
user.GetArn() << std::setw(20) <<
user.GetCreateDate().ToGmtString(DATE_FORMAT) << std::endl;
}
if (outcome.GetResult().GetIsTruncated())
{
request.SetMarker(outcome.GetResult().GetMarker());
}
else
{
done = true;
}
}
// snippet-end:[iam.cpp.list_users.code]
}
Aws::ShutdownAPI(options);
return 0;
}
|
awsdocs/aws-doc-sdk-examples
|
cpp/example_code/iam/list_users.cpp
|
C++
|
apache-2.0
| 2,863
|
/*
Copyright (c) DataStax, 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.
*/
#include "map_iterator.hpp"
using namespace datastax::internal::core;
bool MapIterator::decode_pair() {
key_ = decoder_.decode_value(map_->primary_data_type());
if (key_.data_type()) {
value_ = decoder_.decode_value(map_->secondary_data_type());
return value_.is_valid();
}
return false;
}
bool MapIterator::next() {
if (index_ + 1 >= count_) {
return false;
}
++index_;
return decode_pair();
}
|
datastax/cpp-driver
|
src/map_iterator.cpp
|
C++
|
apache-2.0
| 1,003
|
sap.ui.define([
"sap/ui/core/Control",
"sap/ui/core/HTML",
"sap/ui/core/ResizeHandler",
"sap/ui/dom/jquery/rect" // provides jQuery.fn.rect
], function(Control, HTML, ResizeHandler) {
"use strict";
return Control.extend("sap.ui.demo.toolpageapp.control.D3Chart", {
metadata: {
properties: {
type: {type: "string", defaultValue: "Radial"}
},
aggregations: {
_html: {
type: "sap.ui.core.HTML",
multiple: false,
visibility: "hidden"
},
data: {
type: "sap.ui.base.ManagedObject",
multiple: true
}
},
defaultAggregation: "data"
},
_iHeight: null,
_sContainerId: null,
_sResizeHandlerId: null,
/**
* Initialize hidden html aggregation
*/
init: function () {
this._sContainerId = this.getId() + "--container";
this._iHeight = 130;
this.setAggregation("_html", new HTML(this._sContainerId, {
content: "<svg id=\"" + this._sContainerId + "\" width=\"100%\" height=\"130px\"></svg>"
}));
},
_onResize: function (oEvent) {
this._updateSVG(oEvent.size.width);
},
onBeforeRendering: function () {
ResizeHandler.deregister(this._sResizeHandlerId);
},
onAfterRendering: function () {
this._sResizeHandlerId = ResizeHandler.register(
this,
this._onResize.bind(this));
var $control = this.$();
if ($control.length > 0) {
// jQuery Plugin "rect"
this._updateSVG($control.rect().width);
}
},
renderer: {
apiVersion: 2,
/**
* Renders the root div and the HTML aggregation
* @param {sap.ui.core.RenderManger} oRM the render manager
* @param {sap.ui.demo.toolpageapp.control.D3Chart} oControl the control to be rendered
*/
render: function (oRM, oControl) {
oRM.openStart("div", oControl);
oRM.class("customD3Chart");
oRM.openEnd();
oRM.renderControl(oControl.getAggregation("_html"));
oRM.close("div");
}
}
});
});
|
SAP/openui5
|
src/sap.tnt/test/sap/tnt/demokit/toolpageapp/webapp/control/D3Chart.js
|
JavaScript
|
apache-2.0
| 1,905
|
/* Copyright 2015-2016 Samsung Electronics Co., Ltd.
* Copyright 2016 University of Szeged.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef LIT_GLOBALS_H
#define LIT_GLOBALS_H
#include "jrt.h"
/**
* ECMAScript standard defines terms "code unit" and "character" as 16-bit unsigned value
* used to represent 16-bit unit of text, this is the same as code unit in UTF-16 (See ECMA-262 5.1 Chapter 6).
*
* The term "code point" or "Unicode character" is used to refer a single Unicode scalar value (may be longer
* than 16 bits: 0x0 - 0x10FFFFF). One code point could be represented with one ore two 16-bit code units.
*
* According to the standard all strings and source text are assumed to be a sequence of code units.
* Length of a string equals to number of code units in the string, which is not the same as number of Unicode
* characters in a string.
*
* Internally JerryScript engine uses UTF-8 representation of strings to reduce memory overhead. Unicode character
* occupies from one to four bytes in UTF-8 representation.
*
* Unicode scalar value | Bytes in UTF-8 | Bytes in UTF-16
* | (internal representation) |
* ----------------------------------------------------------------------
* 0x0 - 0x7F | 1 byte | 2 bytes
* 0x80 - 0x7FF | 2 bytes | 2 bytes
* 0x800 - 0xFFFF | 3 bytes | 2 bytes
* 0x10000 - 0x10FFFF | 4 bytes | 4 bytes
*
* Scalar values from 0xD800 to 0xDFFF are permanently reserved by Unicode standard to encode high and low
* surrogates in UTF-16 (Code points 0x10000 - 0x10FFFF are encoded via pair of surrogates in UTF-16).
* Despite that the official Unicode standard says that no UTF forms can encode these code points, we allow
* them to be encoded inside strings. The reason for that is compatibility with ECMA standard.
*
* For example, assume a string which consists one Unicode character: 0x1D700 (Mathematical Italic Small Epsilon).
* It has the following representation in UTF-16: 0xD835 0xDF00.
*
* ECMA standard allows extracting a substring from this string:
* > var str = String.fromCharCode (0xD835, 0xDF00); // Create a string containing one character: 0x1D700
* > str.length; // 2
* > var str1 = str.substring (0, 1);
* > str1.length; // 1
* > str1.charCodeAt (0); // 55349 (this equals to 0xD835)
*
* Internally original string would be represented in UTF-8 as the following byte sequence: 0xF0 0x9D 0x9C 0x80.
* After substring extraction high surrogate 0xD835 should be encoded via UTF-8: 0xED 0xA0 0xB5.
*
* Pair of low and high surrogates encoded separately should never occur in internal string representation,
* it should be encoded as any code point and occupy 4 bytes. So, when constructing a string from two surrogates,
* it should be processed gracefully;
* > var str1 = String.fromCharCode (0xD835); // 0xED 0xA0 0xB5 - internal representation
* > var str2 = String.fromCharCode (0xDF00); // 0xED 0xBC 0x80 - internal representation
* > var str = str1 + str2; // 0xF0 0x9D 0x9C 0x80 - internal representation,
* // !!! not 0xED 0xA0 0xB5 0xED 0xBC 0x80
*/
/**
* Description of an ecma-character, which represents 16-bit code unit,
* which is equal to UTF-16 character (see Chapter 6 from ECMA-262 5.1)
*/
typedef uint16_t ecma_char_t;
/**
* Description of a collection's/string's length
*/
typedef uint32_t ecma_length_t;
/**
* Description of an ecma-character pointer
*/
typedef ecma_char_t *ecma_char_ptr_t;
/**
* Max bytes needed to represent a code unit (utf-16 char) via utf-8 encoding
*/
#define LIT_UTF8_MAX_BYTES_IN_CODE_UNIT (3)
/**
* Max bytes needed to represent a code point (Unicode character) via utf-8 encoding
*/
#define LIT_UTF8_MAX_BYTES_IN_CODE_POINT (4)
/**
* Max bytes needed to represent a code unit (utf-16 char) via cesu-8 encoding
*/
#define LIT_CESU8_MAX_BYTES_IN_CODE_UNIT (3)
/**
* Max bytes needed to represent a code point (Unicode character) via cesu-8 encoding
*/
#define LIT_CESU8_MAX_BYTES_IN_CODE_POINT (6)
/**
* A byte of utf-8 string
*/
typedef uint8_t lit_utf8_byte_t;
/**
* Size of a utf-8 string in bytes
*/
typedef uint32_t lit_utf8_size_t;
/**
* Size of a magic string in bytes
*/
typedef uint8_t lit_magic_size_t;
/**
* Unicode code point
*/
typedef uint32_t lit_code_point_t;
/**
* ECMA string hash
*/
typedef uint16_t lit_string_hash_t;
/**
* Maximum value of ECMA string hash + 1
*
* Note:
* On ARM, this constant can be encoded as an immediate value
* while 0xffffu cannot be. Hence using this constant reduces
* binary size and improves performance.
*/
#define LIT_STRING_HASH_LIMIT 0x10000u
/**
* Hash of the frequently used "length" string.
*/
#define LIT_STRING_LENGTH_HASH 0x3615u
#endif /* !LIT_GLOBALS_H */
|
tilmannOSG/jerryscript
|
jerry-core/lit/lit-globals.h
|
C
|
apache-2.0
| 5,417
|
/*
* Copyright 2016 http://www.hswebframework.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 org.hswebframework.web.authorization.oauth2.client.listener;
/**
* @author zhouhao
*/
public interface OAuth2Event {
}
|
asiaon123/hsweb-framework
|
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-client/src/main/java/org/hswebframework/web/authorization/oauth2/client/listener/OAuth2Event.java
|
Java
|
apache-2.0
| 762
|
package client.js
import org.scalajs.dom.raw.CanvasRenderingContext2D
import shared.geometry._
import shared.map.{Car, Road, RoadMap}
import scala.math._
class MapViewer(context: CanvasRenderingContext2D, map: RoadMap) {
private val MapCoordinatesRange = 1000.0
private val PixelsMapRange = 800.0
private val PixelsForMargins = 100.0
private val PixelsPerMapStep = PixelsMapRange / MapCoordinatesRange
private val HalfCrossingSize = 15.0
private val HalfCarSize = 5.0
private val ColorPimpPurple = "#803CA2"
private val ColorBlack = "#000000"
def drawMap(): Unit = {
context.font = HalfCrossingSize + "px Arial"
map.crossings.foreach(crossing => {
drawCrossing(crossing.coordinates, crossing.name)
})
map.roads.foreach(drawRoad)
}
private def drawRoad(road: Road): Unit = {
if (road.bendingPoints.isEmpty) {
val roadStart = movedPoint(scaleCoordinates(road.start.coordinates), scaleCoordinates(road.end.coordinates), HalfCrossingSize)
val roadEnd = movedPoint(scaleCoordinates(road.end.coordinates), scaleCoordinates(road.start.coordinates), HalfCrossingSize)
drawArrow(roadStart, roadEnd)
} else {
val roadStart = movedPoint(scaleCoordinates(road.start.coordinates), scaleCoordinates(road.bendingPoints.head), HalfCrossingSize)
val roadEnd = movedPoint(scaleCoordinates(road.end.coordinates), scaleCoordinates(road.bendingPoints.last), HalfCrossingSize)
drawLine(roadStart, scaleCoordinates(road.bendingPoints.head))
drawArrow(scaleCoordinates(road.bendingPoints.last), roadEnd)
if (road.bendingPoints.size > 1) {
road.bendingPoints.map(scaleCoordinates).sliding(2).foreach { case List(start, end) => drawLine(start, end) }
}
}
}
private def rotatedPoint(point: Coordinates, center: Coordinates, radiansToRight: Double): Coordinates = {
val sine = sin(radiansToRight)
val cosine = cos(radiansToRight)
(point.x - center.x) * cosine - (point.y - center.y) * sine + center.x ><
(point.x - center.x) * sine + (point.y - center.y) * cosine + center.y
}
private def movedPoint(point: Coordinates, direction: Coordinates, distance: Double): Coordinates = {
val vector = direction.x - point.x >< direction.y - point.y
val vectorLength = sqrt(pow(vector.x, 2) + pow(vector.y, 2))
val normalizedVector = vector.x / vectorLength >< vector.y / vectorLength
point.x + normalizedVector.x * distance >< point.y + normalizedVector.y * distance
}
private def drawCrossing(location: Coordinates, name: String): Unit = {
val textX = scaleValue(location.x) + 1.5 * HalfCrossingSize
val textY = scaleValue(location.y) - 1.0 * HalfCrossingSize
drawCircle(scaleCoordinates(location), ColorPimpPurple, HalfCrossingSize)
context.fillText(name, textX, textY)
}
def drawCars(carsList: List[Car]): Unit = {
// FIXME ugly temporary fix
context.clearRect(0, 0, 1000, 1000)
drawMap()
carsList.foreach(car => drawCar(car.location, car.previousLocation, car.hexColor))
}
private def drawCar(location: Coordinates, previousLocation: Option[Coordinates], color: String): Unit = {
val scaledCoordinates = scaleCoordinates(location)
if (previousLocation.isEmpty) {
drawRect(scaledCoordinates, color, HalfCarSize)
} else {
val scaledPreviousLocation = scaleCoordinates(previousLocation.get)
val movingDirection = scaledCoordinates.x - scaledPreviousLocation.x >< scaledCoordinates.y - scaledPreviousLocation.y
val movingDirectionLength = sqrt(pow(movingDirection.x, 2) + pow(movingDirection.y, 2))
val unitMovingDirection = movingDirection.x / movingDirectionLength * HalfCarSize >< movingDirection.y / movingDirectionLength * HalfCarSize
val rotatedMovingDirection = -unitMovingDirection.y >< unitMovingDirection.x
val movedLocation = scaledCoordinates.x + rotatedMovingDirection.x >< scaledCoordinates.y + rotatedMovingDirection.y
drawRect(movedLocation, color, HalfCarSize)
}
}
private def drawCircle(middle: Coordinates, color: String, radius: Double): Unit = {
context.fillStyle = color
context.beginPath
context.arc(middle.x, middle.y, radius, 0, 2 * Math.PI)
context.closePath
context.fill
context.stroke
context.fillStyle = ColorBlack
}
private def drawRect(middle: Coordinates, color: String, halfRectSide: Double): Unit = {
val rectX = middle.x - halfRectSide
val rectY = middle.y - halfRectSide
val rectSide = 2 * halfRectSide
context.fillStyle = color
context.fillRect(rectX, rectY, rectSide, rectSide)
context.strokeRect(rectX, rectY, rectSide, rectSide)
context.fillStyle = ColorBlack
}
private def drawArrow(start: Coordinates, end: Coordinates): Unit = {
drawLine(start, end)
drawLine(movedPoint(end, rotatedPoint(start, end, +Pi / 6), HalfCrossingSize), end)
drawLine(movedPoint(end, rotatedPoint(start, end, -Pi / 6), HalfCrossingSize), end)
}
private def drawLine(start: Coordinates, end: Coordinates): Unit = {
context.beginPath
context.moveTo(start.x, start.y)
context.lineTo(end.x, end.y)
context.closePath
context.stroke
}
private def scaleCoordinates(coordinates: Coordinates): Coordinates = scaleValue(coordinates.x) >< scaleValue(coordinates.y)
private def scaleValue(value: Double): Double = PixelsForMargins + value * PixelsPerMapStep
}
|
tlegutko/traffic-sim
|
client/src/main/scala/client/js/MapViewer.scala
|
Scala
|
apache-2.0
| 5,435
|
package org.minimalj.repository.sql.relation;
import java.util.List;
import org.minimalj.model.Keys;
import org.minimalj.model.annotation.Size;
public class TestEntity {
public static final TestEntity $ = Keys.of(TestEntity.class);
public TestEntity() {
// needed for reflection constructor
}
public TestEntity(String name) {
this.name = name;
}
public Object id;
@Size(30)
public String name;
public List<TestElementB> list;
public List<TestElementCode> codes;
public List<TestElementCodeView> codeViews;
}
|
BrunoEberhard/minimal-j
|
src/test/java/org/minimalj/repository/sql/relation/TestEntity.java
|
Java
|
apache-2.0
| 535
|
/*******************************************************************************
* Copyright 2013 Pekka Hyvönen, pekka@vaadin.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 com.vaadin.pekka.postmessage;
import com.vaadin.ui.Component;
/**
* Represents the basic properties of a Post Message event.
*
* @author pekkahyvonen
*
*/
@SuppressWarnings("serial")
public abstract class PostMessageEvent extends Component.Event {
private final String origin;
private final String message;
private final Integer messageId;
public PostMessageEvent(final Component source, final String origin,
final String message, final Integer messageId) {
super(source);
this.origin = origin;
this.message = message;
this.messageId = messageId;
}
/**
*
* @return the origin where the message came from
*/
public String getOrigin() {
return origin;
}
/**
*
* @return the actual message
*/
public String getMessage() {
return message;
}
/**
*
* @return an id for the message, or -1 if component doesn't identify
* messages with ids
*/
public Integer getMessageId() {
return messageId;
}
// for responding to the specific message this event represents
public abstract void respond(final String message, final boolean option);
}
|
pleku/postmessageaddon
|
postmessage/src/main/java/com/vaadin/pekka/postmessage/PostMessageEvent.java
|
Java
|
apache-2.0
| 2,008
|
/**
* Copyright (c) 2014 Ernesto Posse
*
* 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.
*
* @author Ernesto Posse
* @version 0.1
*/
package org.osate.xtext.aadl2.agcl.tests;
import com.google.inject.Inject;
import org.eclipse.emf.common.util.EList;
import org.eclipse.xtext.junit4.InjectWith;
import org.eclipse.xtext.junit4.XtextRunner;
import org.eclipse.xtext.junit4.util.ParseHelper;
import org.eclipse.xtext.xbase.lib.Exceptions;
import org.eclipse.xtext.xbase.lib.InputOutput;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.osate.xtext.aadl2.agcl.AGCLInjectorProvider;
import org.osate.xtext.aadl2.agcl.agcl.AGCLAnnexLibrary;
import org.osate.xtext.aadl2.agcl.agcl.AGCLGrammarRoot;
import org.osate.xtext.aadl2.agcl.agcl.AGCLViewpoint;
@InjectWith(AGCLInjectorProvider.class)
@RunWith(XtextRunner.class)
@SuppressWarnings("all")
public class HelloUnitTesting {
@Inject
private ParseHelper<AGCLGrammarRoot> parser;
@Test
public void parseSimpleAGCLLibrary() {
try {
InputOutput.<String>println("AGCLAnnexLibrary");
final String libText = "\n library \n viewpoint v1*;\n viewpoint v2\n ";
final AGCLGrammarRoot libAST = this.parser.parse(libText);
AGCLAnnexLibrary _lib = libAST.getLib();
final EList<AGCLViewpoint> viewpoints = _lib.getViewpoints();
InputOutput.<AGCLGrammarRoot>println(libAST);
InputOutput.<EList<AGCLViewpoint>>println(viewpoints);
AGCLViewpoint _get = viewpoints.get(0);
String _name = _get.getName();
InputOutput.<String>println(_name);
AGCLViewpoint _get_1 = viewpoints.get(1);
String _name_1 = _get_1.getName();
InputOutput.<String>println(_name_1);
AGCLViewpoint _get_2 = viewpoints.get(0);
String _name_2 = _get_2.getName();
Assert.assertEquals("v1", _name_2);
AGCLViewpoint _get_3 = viewpoints.get(1);
String _name_3 = _get_3.getName();
Assert.assertEquals("v2", _name_3);
} catch (Throwable _e) {
throw Exceptions.sneakyThrow(_e);
}
}
}
|
eposse/osate2-agcl
|
org.osate.xtext.aadl2.agcl.tests/xtend-gen/org/osate/xtext/aadl2/agcl/tests/HelloUnitTesting.java
|
Java
|
apache-2.0
| 2,627
|
# AUTOGENERATED FILE
FROM balenalib/parallella-alpine:3.13-build
ENV NODE_VERSION 15.7.0
ENV YARN_VERSION 1.22.4
# Install dependencies
RUN apk add --no-cache libgcc libstdc++ libuv \
&& apk add --no-cache libssl1.0 || apk add --no-cache libssl1.1
RUN for key in \
6A010C5166006599AA17F08146C2130DFD2497F5 \
; do \
gpg --keyserver pgp.mit.edu --recv-keys "$key" || \
gpg --keyserver keyserver.pgp.com --recv-keys "$key" || \
gpg --keyserver ha.pool.sks-keyservers.net --recv-keys "$key" ; \
done \
&& curl -SLO "http://resin-packages.s3.amazonaws.com/node/v$NODE_VERSION/node-v$NODE_VERSION-linux-alpine-armv7hf.tar.gz" \
&& echo "73984242011b816117126c546702a7892b0ddd39cd51f672445b430161e2b903 node-v$NODE_VERSION-linux-alpine-armv7hf.tar.gz" | sha256sum -c - \
&& tar -xzf "node-v$NODE_VERSION-linux-alpine-armv7hf.tar.gz" -C /usr/local --strip-components=1 \
&& rm "node-v$NODE_VERSION-linux-alpine-armv7hf.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \
&& gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& mkdir -p /opt/yarn \
&& tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \
&& rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& npm config set unsafe-perm true -g --unsafe-perm \
&& rm -rf /tmp/*
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@node.sh" \
&& echo "Running test-stack@node" \
&& chmod +x test-stack@node.sh \
&& bash test-stack@node.sh \
&& rm -rf test-stack@node.sh
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Alpine Linux 3.13 \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v15.7.0, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo $'#!/bin/bash\nbalena-info\nbusybox ln -sf /bin/busybox /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& ln -f /bin/sh /bin/sh.real \
&& ln -f /bin/sh-shim /bin/sh
|
nghiant2710/base-images
|
balena-base-images/node/parallella/alpine/3.13/15.7.0/build/Dockerfile
|
Dockerfile
|
apache-2.0
| 2,955
|
-- phpMyAdmin SQL Dump
-- version 3.5.8.1deb1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Jun 21, 2015 at 11:03 PM
-- Server version: 5.5.34-0ubuntu0.13.04.1
-- PHP Version: 5.4.9-4ubuntu2.4
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Database: `traffic_collector`
--
DROP DATABASE IF EXISTS `traffic_collector`;
CREATE DATABASE `traffic_collector` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE `traffic_collector`;
-- --------------------------------------------------------
--
-- Table structure for table `journey`
--
DROP TABLE IF EXISTS `journey`;
CREATE TABLE IF NOT EXISTS `journey` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`id_user` int(11) NOT NULL,
`journey_name` text NOT NULL,
PRIMARY KEY (`id`),
KEY `id_user` (`id_user`),
KEY `id_user_2` (`id_user`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
-- --------------------------------------------------------
--
-- Table structure for table `journey_data`
--
DROP TABLE IF EXISTS `journey_data`;
CREATE TABLE IF NOT EXISTS `journey_data` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`journey_id` int(11) NOT NULL,
`latitude` float(10,6) NOT NULL,
`longitude` float(10,6) NOT NULL,
`speed` int(11) NOT NULL,
`timestamp` datetime NOT NULL,
PRIMARY KEY (`id`),
KEY `journey_id` (`journey_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
-- --------------------------------------------------------
--
-- Table structure for table `location`
--
DROP TABLE IF EXISTS `location`;
CREATE TABLE IF NOT EXISTS `location` (
`id_user` int(11) NOT NULL,
`latitude` float(10,6) NOT NULL,
`longitude` float(10,6) NOT NULL,
`speed` int(11) NOT NULL,
`timestamp` datetime NOT NULL,
PRIMARY KEY (`id_user`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `user`
--
DROP TABLE IF EXISTS `user`;
CREATE TABLE IF NOT EXISTS `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` text NOT NULL,
`password` text,
`firstname` varchar(100) NOT NULL,
`lastname` varchar(100) NOT NULL,
`phone` varchar(15) DEFAULT NULL,
`facebook_token` text,
`facebook_expires_in` int(11) DEFAULT 0,
`auth_token` text NOT NULL,
`auth_expires_in` int(11) NOT NULL,
`uuid` varchar(512) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uuid` (`uuid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
-- --------------------------------------------------------
--
-- Table structure for table `user_contact`
--
DROP TABLE IF EXISTS `user_contact`;
CREATE TABLE IF NOT EXISTS `user_contact` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`id_user` int(11) NOT NULL,
`id_friend_user` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `id_user1` (`id_user`),
KEY `id_user2` (`id_friend_user`),
KEY `id_user1_2` (`id_user`),
KEY `id_user2_2` (`id_friend_user`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `journey`
--
ALTER TABLE `journey`
ADD CONSTRAINT `journey_ibfk_1` FOREIGN KEY (`id_user`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Constraints for table `journey_data`
--
ALTER TABLE `journey_data`
ADD CONSTRAINT `journey_data_ibfk_1` FOREIGN KEY (`journey_id`) REFERENCES `journey` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Constraints for table `location`
--
ALTER TABLE `location`
ADD CONSTRAINT `location_ibfk_1` FOREIGN KEY (`id_user`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Constraints for table `user_contact`
--
ALTER TABLE `user_contact`
ADD CONSTRAINT `user_contact_ibfk_2` FOREIGN KEY (`id_friend_user`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `user_contact_ibfk_1` FOREIGN KEY (`id_user`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
cosminaionascu/trafficcollector
|
TrafficCollectorServer/sql/traffic_collector.sql
|
SQL
|
apache-2.0
| 4,364
|
# TaskInstanceUpdateItem
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**data** | [**\ProcessMaker\PMIO\Model\TaskInstance**](TaskInstance.md) | |
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
|
ProcessMaker/pmio-sdk-php
|
docs/Model/TaskInstanceUpdateItem.md
|
Markdown
|
apache-2.0
| 378
|
package com.sksamuel.elastic4s.http.search.aggs
import com.sksamuel.elastic4s.searches.aggs._
import com.sksamuel.elastic4s.searches.aggs.pipeline.MaxBucketDefinition
import org.elasticsearch.common.xcontent.{XContentBuilder, XContentFactory, XContentType}
object AggregationBuilderFn {
def apply(agg: AbstractAggregation): XContentBuilder = {
val builder = agg match {
case agg: AvgAggregationDefinition => AvgAggregationBuilder(agg)
case agg: CardinalityAggregationDefinition => CardinalityAggregationBuilder(agg)
case agg: DateHistogramAggregation => DateHistogramAggregationBuilder(agg)
case agg: FilterAggregationDefinition => FilterAggregationBuilder(agg)
case agg: MaxAggregationDefinition => MaxAggregationBuilder(agg)
case agg: MinAggregationDefinition => MinAggregationBuilder(agg)
case agg: MissingAggregationDefinition => MissingAggregationBuilder(agg)
case agg: SumAggregationDefinition => SumAggregationBuilder(agg)
case agg: TopHitsAggregationDefinition => TopHitsAggregationBuilder(agg)
case agg: TermsAggregationDefinition => TermsAggregationBuilder(agg)
case agg: ValueCountAggregationDefinition => ValueCountAggregationBuilder(agg)
// pipeline aggs
case agg: MaxBucketDefinition => MaxBucketPipelineAggBuilder(agg)
}
builder
}
}
object MaxBucketPipelineAggBuilder {
def apply(agg: MaxBucketDefinition): XContentBuilder = {
val builder = XContentFactory.jsonBuilder().startObject().startObject("max_bucket")
builder.field("buckets_path", agg.bucketsPath)
builder.endObject().endObject()
}
}
object AggMetaDataFn {
def apply(agg: AggregationDefinition, builder: XContentBuilder): Unit = {
if (agg.metadata.nonEmpty) {
builder.startObject("meta")
agg.metadata.foreach { case (key, value) => builder.field(key, value) }
builder.endObject()
}
}
}
object SubAggsBuilderFn {
def apply(agg: AggregationDefinition, builder: XContentBuilder): Unit = {
builder.startObject("aggs")
agg.subaggs.foreach { subagg =>
builder.rawField(subagg.name, AggregationBuilderFn(subagg).bytes, XContentType.JSON)
}
builder.endObject()
}
}
|
FabienPennequin/elastic4s
|
elastic4s-http/src/main/scala/com/sksamuel/elastic4s/http/search/aggs/AggregationBuilderFn.scala
|
Scala
|
apache-2.0
| 2,204
|
# Sisymbrium damascenum Boiss. SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Brassicales/Brassicaceae/Sisymbrium/Sisymbrium damascenum/README.md
|
Markdown
|
apache-2.0
| 186
|
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package storage
import (
"context"
"fmt"
"io"
"os"
"path/filepath"
"regexp"
"time"
"google.golang.org/grpc/codes" /* copybara-comment */
"google.golang.org/grpc/status" /* copybara-comment */
"github.com/golang/protobuf/jsonpb" /* copybara-comment */
"github.com/golang/protobuf/proto" /* copybara-comment */
)
const (
memStorageType = "memory"
memStorageVersion = "v0"
)
// MemoryStorage is designed as a single threading storage. Will throw exception if multiple TX request.
type MemoryStorage struct {
service string
path string
pathParts []string
cache *StorageCache
fs *FileStorage
deleted map[string]bool
wipedRealms map[string]bool
lock chan bool
lastLock time.Time
}
func NewMemoryStorage(service, path string) *MemoryStorage {
return &MemoryStorage{
service: service,
path: path,
cache: NewStorageCache(),
fs: NewFileStorage(service, path),
deleted: make(map[string]bool),
wipedRealms: make(map[string]bool),
lock: make(chan bool, 1),
lastLock: time.Unix(0, 0),
}
}
func (m *MemoryStorage) Info() map[string]string {
return map[string]string{
"type": memStorageType,
"version": memStorageVersion,
"service": m.service,
"path": m.path,
}
}
func (m *MemoryStorage) Exists(datatype, realm, user, id string, rev int64) (bool, error) {
fname := m.fname(datatype, realm, user, id, rev)
if _, ok := m.cache.GetEntity(fname); ok {
return true, nil
}
if m.deleted[fname] || m.wipedRealms[realm] {
return false, nil
}
return m.fs.Exists(datatype, realm, user, id, rev)
}
func (m *MemoryStorage) Read(datatype, realm, user, id string, rev int64, content proto.Message) error {
return m.ReadTx(datatype, realm, user, id, rev, content, nil)
}
// ReadTx reads inside a transaction.
func (m *MemoryStorage) ReadTx(datatype, realm, user, id string, rev int64, content proto.Message, tx Tx) (ferr error) {
if tx == nil {
var err error
tx, err = m.Tx(false)
if err != nil {
return err
}
defer func() {
err := tx.Finish()
if ferr == nil {
ferr = err
}
}()
}
fname := m.fname(datatype, realm, user, id, rev)
if data, ok := m.cache.GetEntity(fname); ok {
content.Reset()
proto.Merge(content, data)
return nil
}
if m.deleted[fname] || m.wipedRealms[realm] {
return fmt.Errorf("not found: %q", fname)
}
if err := m.fs.ReadTx(datatype, realm, user, id, rev, content, tx); err != nil {
return err
}
m.cache.PutEntity(fname, content)
return nil
}
// MultiReadTx reads a set of objects matching the input parameters and filters
func (m *MemoryStorage) MultiReadTx(datatype, realm, user, id string, filters [][]Filter, offset, pageSize int, typ proto.Message, tx Tx) (_ *Results, ferr error) {
if tx == nil {
var err error
tx, err = m.fs.Tx(false)
if err != nil {
return nil, fmt.Errorf("file read lock error: %v", err)
}
defer func() {
err := tx.Finish()
if ferr == nil {
ferr = err
}
}()
}
if pageSize > MaxPageSize {
pageSize = MaxPageSize
}
results := NewResults()
err := m.findPath(datatype, realm, user, id, typ, func(path, userMatch, idMatch string, p proto.Message) error {
if m.deleted[m.fname(datatype, realm, userMatch, idMatch, LatestRev)] || m.wipedRealms[realm] {
return nil
}
if id != MatchAllIDs && idMatch != id {
return nil
}
if !MatchProtoFilters(filters, p) {
return nil
}
if offset > 0 {
offset--
return nil
}
if pageSize > results.MatchCount {
results.Entries = append(results.Entries, &Entry{
Realm: realm,
GroupID: userMatch,
ItemID: idMatch,
Item: p,
})
}
results.MatchCount++
return nil
})
return results, err
}
func (m *MemoryStorage) findPath(datatype, realm, user, id string, typ proto.Message, fn func(string, string, string, proto.Message) error) error {
searchUser := user
if user == MatchAllUsers {
searchUser = "(.*)"
} else {
searchUser = "(" + user + ")"
}
searchRealm := realm
if realm == AllRealms {
searchRealm = "(.*)"
}
searchID := id
if id == MatchAllIDs {
searchID = "(.*)"
} else {
searchID = "(" + id + ")"
}
extractID := m.fs.fname(datatype, searchRealm, searchUser, searchID, LatestRev)
re, err := regexp.Compile(extractID)
if err != nil {
return fmt.Errorf("file extract ID %q regexp error: %v", extractID, err)
}
defaultUserID := m.fs.fname(datatype, realm, DefaultUser, searchID, LatestRev)
dure, err := regexp.Compile(defaultUserID)
if err != nil {
return fmt.Errorf("file extract ID %q regexp error: %v", defaultUserID, err)
}
cached := m.cache.Entities()
fileMatcher := func(path string, info os.FileInfo, err error) error {
return extractFromPath(re, dure, user, path, info, err, typ, cached, fn)
}
if err = filepath.Walk(m.fs.path, fileMatcher); err != nil {
return err
}
return extractFromCache(re, dure, user, cached, fn)
}
func extractFromPath(re, dure *regexp.Regexp, user, path string, info os.FileInfo, err error, typ proto.Message, cached map[string]proto.Message, fn func(string, string, string, proto.Message) error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil
}
if _, ok := cached[path]; ok {
return nil
}
userMatch, idMatch := extractUserAndID(re, dure, user, path)
if userMatch == "" && idMatch == "" {
return nil
}
var p proto.Message
if typ != nil {
file, err := os.Open(path)
if err != nil {
return fmt.Errorf("file %q I/O error: %v", path, err)
}
defer file.Close()
p = proto.Clone(typ)
if err := jsonpb.Unmarshal(file, p); err != nil && err != io.EOF {
return fmt.Errorf("file %q invalid JSON: %v", path, err)
}
}
return fn(path, userMatch, idMatch, p)
}
func extractUserAndID(re, dure *regexp.Regexp, user, path string) (string, string) {
matches := re.FindStringSubmatch(path)
if len(matches) == 3 {
return matches[1], matches[2]
}
if user == DefaultUser {
matches = dure.FindStringSubmatch(path)
if len(matches) == 2 {
return DefaultUser, matches[1]
}
}
return "", ""
}
func extractFromCache(re, dure *regexp.Regexp, user string, cached map[string]proto.Message, fn func(string, string, string, proto.Message) error) error {
for path, content := range cached {
if !re.MatchString(path) && !dure.MatchString(path) {
continue
}
userMatch, idMatch := extractUserAndID(re, dure, user, path)
if userMatch == "" && idMatch == "" {
continue
}
if err := fn(path, userMatch, idMatch, content); err != nil {
return err
}
}
return nil
}
func (m *MemoryStorage) ReadHistory(datatype, realm, user, id string, content *[]proto.Message) error {
return m.ReadHistoryTx(datatype, realm, user, id, content, nil)
}
// ReadHistoryTx reads history inside a transaction.
func (m *MemoryStorage) ReadHistoryTx(datatype, realm, user, id string, content *[]proto.Message, tx Tx) (ferr error) {
if tx == nil {
var err error
tx, err = m.Tx(false)
if err != nil {
return err
}
defer func() {
err := tx.Finish()
if ferr == nil {
ferr = err
}
}()
}
hfname := m.historyName(datatype, realm, user, id)
if data, ok := m.cache.GetHistory(hfname); ok {
for _, he := range data {
*content = append(*content, he)
}
return nil
}
if err := m.fs.ReadHistoryTx(datatype, realm, user, id, content, tx); err != nil {
return err
}
m.cache.PutHistory(hfname, *content)
return nil
}
func (m *MemoryStorage) Write(datatype, realm, user, id string, rev int64, content proto.Message, history proto.Message) error {
return m.WriteTx(datatype, realm, user, id, rev, content, history, nil)
}
// WriteTx writes inside a transaction.
func (m *MemoryStorage) WriteTx(datatype, realm, user, id string, rev int64, content proto.Message, history proto.Message, tx Tx) (ferr error) {
if tx == nil {
var err error
tx, err = m.Tx(true)
if err != nil {
return err
}
defer func() {
err := tx.Finish()
if ferr == nil {
ferr = err
}
}()
}
hlist := make([]proto.Message, 0)
if err := m.ReadHistoryTx(datatype, realm, user, id, &hlist, tx); err != nil && !ErrNotFound(err) {
return err
}
hlist = append(hlist, history)
hfname := m.historyName(datatype, realm, user, id)
m.cache.PutHistory(hfname, hlist)
vname := m.fname(datatype, realm, user, id, rev)
m.cache.PutEntity(vname, content)
lname := m.fname(datatype, realm, user, id, LatestRev)
m.cache.PutEntity(lname, content)
if _, ok := m.deleted[vname]; ok {
delete(m.deleted, vname)
}
if _, ok := m.deleted[lname]; ok {
delete(m.deleted, lname)
}
return nil
}
// Delete a record.
func (m *MemoryStorage) Delete(datatype, realm, user, id string, rev int64) error {
return m.DeleteTx(datatype, realm, user, id, rev, nil)
}
// DeleteTx delete a record with transaction.
func (m *MemoryStorage) DeleteTx(datatype, realm, user, id string, rev int64, tx Tx) (ferr error) {
if tx == nil {
var err error
tx, err = m.Tx(true)
if err != nil {
return err
}
defer func() {
err := tx.Finish()
if ferr == nil {
ferr = err
}
}()
}
exists, err := m.Exists(datatype, realm, user, id, rev)
if err != nil {
return err
}
lname := m.fname(datatype, realm, user, id, LatestRev)
if !exists {
return status.Errorf(codes.NotFound, "not found: %q", lname)
}
vname := m.fname(datatype, realm, user, id, rev)
m.cache.DeleteEntity(vname)
m.cache.DeleteEntity(lname)
m.deleted[vname] = true
m.deleted[lname] = true
return nil
}
// MultiDeleteTx deletes all records of a certain data type within a realm.
func (m *MemoryStorage) MultiDeleteTx(datatype, realm, user string, tx Tx) (ferr error) {
if tx == nil {
var err error
tx, err = m.fs.Tx(false)
if err != nil {
return fmt.Errorf("file read lock error: %v", err)
}
defer func() {
err := tx.Finish()
if ferr == nil {
ferr = err
}
}()
}
return m.findPath(datatype, realm, user, MatchAllIDs, nil, func(path, userMatch, idMatch string, p proto.Message) error {
return m.DeleteTx(datatype, realm, userMatch, idMatch, LatestRev, tx)
})
}
func (m *MemoryStorage) Wipe(ctx context.Context, realm string, batchNum, maxEntries int) (int, error) {
// Wipe everything, not just for the realm provided or the maxEntries.
count := len(m.cache.entityCache) + len(m.cache.historyCache)
m.cache = NewStorageCache()
m.deleted = make(map[string]bool)
m.wipedRealms[realm] = true
return count, nil
}
func (m *MemoryStorage) Tx(update bool) (Tx, error) {
select {
case m.lock <- true:
default:
panic("MAYBE BUG: Requested a new TX without the existing TX release.")
}
m.cache.Backup()
return &MemTx{
update: update,
ms: m,
}, nil
}
// LockTx returns a storage-wide lock by the given name. Only one such lock should
// be requested at a time. If Tx is provided, it must be an update Tx.
func (m *MemoryStorage) LockTx(lockName string, minFrequency time.Duration, tx Tx) Tx {
now := time.Now()
if now.Sub(m.lastLock) < minFrequency {
return nil
}
if tx == nil {
var err error
tx, err = m.Tx(true)
if err != nil {
return nil
}
}
m.lastLock = now
return tx
}
type MemTx struct {
update bool
ms *MemoryStorage
}
// Finish attempts to commit a transaction.
func (tx *MemTx) Finish() error {
select {
case <-tx.ms.lock:
default:
panic("MAYBE BUG: Releasing a released TX.")
}
return nil
}
// Rollback attempts to rollback a transaction.
func (tx *MemTx) Rollback() error {
tx.ms.cache.Restore()
tx.ms.fs = NewFileStorage(tx.ms.service, tx.ms.path)
return nil
}
// MakeUpdate will upgrade a read-only transaction to an update transaction.
func (tx *MemTx) MakeUpdate() error {
tx.update = true
return nil
}
func (tx *MemTx) IsUpdate() bool {
return tx.update
}
func (m *MemoryStorage) fname(datatype, realm, user, id string, rev int64) string {
return m.fs.fname(datatype, realm, user, id, rev)
}
func (m *MemoryStorage) historyName(datatype, realm, user, id string) string {
return m.fs.historyName(datatype, realm, user, id)
}
|
GoogleCloudPlatform/healthcare-federated-access-services
|
lib/storage/memory_storage.go
|
GO
|
apache-2.0
| 12,598
|
# Copyright 2021 The Cirq Developers
#
# 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
#
# 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.
# This is more of a placeholder for now, we can add
# official color schemes in follow-ups.
import abc
import dataclasses
from typing import Iterable, List, Optional
import cirq
from cirq.protocols.circuit_diagram_info_protocol import CircuitDiagramInfoArgs
@dataclasses.dataclass
class SymbolInfo:
"""Organizes information about a symbol."""
labels: List[str]
colors: List[str]
@staticmethod
def unknown_operation(num_qubits: int) -> 'SymbolInfo':
"""Generates a SymbolInfo object for an unknown operation.
Args:
num_qubits: the number of qubits in the operation
"""
symbol_info = SymbolInfo([], [])
for _ in range(num_qubits):
symbol_info.colors.append('gray')
symbol_info.labels.append('?')
return symbol_info
class SymbolResolver(metaclass=abc.ABCMeta):
"""Abstract class providing the interface for users to specify information
about how a particular symbol should be displayed in the 3D circuit
"""
def __call__(self, operation: cirq.Operation) -> Optional[SymbolInfo]:
return self.resolve(operation)
@abc.abstractmethod
def resolve(self, operation: cirq.Operation) -> Optional[SymbolInfo]:
"""Converts cirq.Operation objects into SymbolInfo objects for serialization."""
class DefaultResolver(SymbolResolver):
"""Default symbol resolver implementation. Takes information
from circuit_diagram_info, if unavailable, returns information representing
an unknown symbol.
"""
_SYMBOL_COLORS = {
'@': 'black',
'H': 'yellow',
'I': 'orange',
'X': 'black',
'Y': 'pink',
'Z': 'cyan',
'S': '#90EE90',
'T': '#CBC3E3',
}
def resolve(self, operation: cirq.Operation) -> Optional[SymbolInfo]:
"""Checks for the _circuit_diagram_info attribute of the operation,
and if it exists, build the symbol information from it. Otherwise,
builds symbol info for an unknown operation.
Args:
operation: the cirq.Operation object to resolve
"""
try:
info = cirq.circuit_diagram_info(operation)
except TypeError:
return SymbolInfo.unknown_operation(cirq.num_qubits(operation))
wire_symbols = info.wire_symbols
symbol_exponent = info._wire_symbols_including_formatted_exponent(
CircuitDiagramInfoArgs.UNINFORMED_DEFAULT
)
symbol_info = SymbolInfo(list(symbol_exponent), [])
for symbol in wire_symbols:
symbol_info.colors.append(DefaultResolver._SYMBOL_COLORS.get(symbol, 'gray'))
return symbol_info
DEFAULT_SYMBOL_RESOLVERS: Iterable[SymbolResolver] = tuple([DefaultResolver()])
def resolve_operation(operation: cirq.Operation, resolvers: Iterable[SymbolResolver]) -> SymbolInfo:
"""Builds a SymbolInfo object based off of a designated operation
and list of resolvers. The latest resolver takes precendent.
Args:
operation: the cirq.Operation object to resolve
resolvers: a list of SymbolResolvers which provides instructions
on how to build SymbolInfo objects.
Raises:
ValueError: if the operation cannot be resolved into a symbol.
"""
symbol_info = None
for resolver in resolvers:
info = resolver(operation)
if info is not None:
symbol_info = info
if symbol_info is None:
raise ValueError(f'Cannot resolve operation: {operation}')
return symbol_info
class Operation3DSymbol:
def __init__(self, wire_symbols, location_info, color_info, moment):
"""Gathers symbol information from an operation and builds an
object to represent it in 3D.
Args:
wire_symbols: a list of symbols taken from circuit_diagram_info()
that will be used to represent the operation in the 3D circuit.
location_info: A list of coordinates for each wire_symbol. The
index of the coordinate tuple in the location_info list must
correspond with the index of the symbol in the wire_symbols list.
color_info: a list representing the desired color of the symbol(s).
These will also correspond to index of the symbol in the
wire_symbols list.
moment: the moment where the symbol should be.
"""
self.wire_symbols = wire_symbols
self.location_info = location_info
self.color_info = color_info
self.moment = moment
def to_typescript(self):
return {
'wire_symbols': list(self.wire_symbols),
'location_info': self.location_info,
'color_info': self.color_info,
'moment': self.moment,
}
|
quantumlib/Cirq
|
cirq-web/cirq_web/circuits/symbols.py
|
Python
|
apache-2.0
| 5,383
|
package com.deepoove.poi.plugin.highlight.example;
import java.util.List;
import com.deepoove.poi.data.BookmarkTextRenderData;
import com.deepoove.poi.data.TextRenderData;
import com.deepoove.poi.plugin.highlight.HighlightRenderData;
import io.swagger.models.ExternalDocs;
import io.swagger.models.Info;
import io.swagger.models.Scheme;
public class SwaggerView {
protected String swagger = "2.0";
protected Info info;
protected String host;
protected String basePath;
protected List<Scheme> schemes;
protected ExternalDocs externalDocs;
protected List<Resource> resources;
protected List<Definition> definitions;
public String getSwagger() {
return swagger;
}
public void setSwagger(String swagger) {
this.swagger = swagger;
}
public Info getInfo() {
return info;
}
public void setInfo(Info info) {
this.info = info;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getBasePath() {
return basePath;
}
public void setBasePath(String basePath) {
this.basePath = basePath;
}
public List<Scheme> getSchemes() {
return schemes;
}
public void setSchemes(List<Scheme> schemes) {
this.schemes = schemes;
}
public ExternalDocs getExternalDocs() {
return externalDocs;
}
public void setExternalDocs(ExternalDocs externalDocs) {
this.externalDocs = externalDocs;
}
public List<Resource> getResources() {
return resources;
}
public void setResources(List<Resource> resources) {
this.resources = resources;
}
public List<Definition> getDefinitions() {
return definitions;
}
public void setDefinitions(List<Definition> definitions) {
this.definitions = definitions;
}
}
class Resource {
private String name;
private String description;
private List<Endpoint> endpoints;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<Endpoint> getEndpoints() {
return endpoints;
}
public void setEndpoints(List<Endpoint> endpoints) {
this.endpoints = endpoints;
}
}
class Endpoint {
private List<String> tag;
private String summary;
private String httpMethod;
private boolean isGet;
private boolean isPut;
private boolean isPost;
private boolean isDelete;
private String url;
private String description;
private List<Parameter> parameters;
private List<Response> responses;
private List<String> produces;
private List<String> consumes;
public List<String> getTag() {
return tag;
}
public void setTag(List<String> tag) {
this.tag = tag;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getHttpMethod() {
return httpMethod;
}
public void setHttpMethod(String httpMethod) {
this.httpMethod = httpMethod;
}
public boolean isGet() {
return isGet;
}
public void setGet(boolean isGet) {
this.isGet = isGet;
}
public boolean isPut() {
return isPut;
}
public void setPut(boolean isPut) {
this.isPut = isPut;
}
public boolean isPost() {
return isPost;
}
public void setPost(boolean isPost) {
this.isPost = isPost;
}
public boolean isDelete() {
return isDelete;
}
public void setDelete(boolean isDelete) {
this.isDelete = isDelete;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<Parameter> getParameters() {
return parameters;
}
public void setParameters(List<Parameter> parameters) {
this.parameters = parameters;
}
public List<Response> getResponses() {
return responses;
}
public void setResponses(List<Response> responses) {
this.responses = responses;
}
public List<String> getProduces() {
return produces;
}
public void setProduces(List<String> produces) {
this.produces = produces;
}
public List<String> getConsumes() {
return consumes;
}
public void setConsumes(List<String> consumes) {
this.consumes = consumes;
}
}
class Parameter {
private String in;
private String name;
private boolean required;
private String description;
private List<TextRenderData> schema;
private String defaultValue;
public String getIn() {
return in;
}
public void setIn(String in) {
this.in = in;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isRequired() {
return required;
}
public void setRequired(boolean required) {
this.required = required;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<TextRenderData> getSchema() {
return schema;
}
public void setSchema(List<TextRenderData> schema) {
this.schema = schema;
}
public String getDefaultValue() {
return defaultValue;
}
public void setDefaultValue(String defaultValue) {
this.defaultValue = defaultValue;
}
}
class Response {
private String code;
private String description;
private List<TextRenderData> schema;
private List<Header> headers;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<TextRenderData> getSchema() {
return schema;
}
public void setSchema(List<TextRenderData> schema) {
this.schema = schema;
}
public List<Header> getHeaders() {
return headers;
}
public void setHeaders(List<Header> headers) {
this.headers = headers;
}
}
class Header {
private String name;
private String type;
private String description;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
class Definition {
private BookmarkTextRenderData name;
List<Property> properties;
HighlightRenderData definitionCode;
public BookmarkTextRenderData getName() {
return name;
}
public void setName(BookmarkTextRenderData name) {
this.name = name;
}
public List<Property> getProperties() {
return properties;
}
public void setProperties(List<Property> properties) {
this.properties = properties;
}
public HighlightRenderData getDefinitionCode() {
return definitionCode;
}
public void setDefinitionCode(HighlightRenderData definitionCode) {
this.definitionCode = definitionCode;
}
}
class Property {
private String name;
private boolean required;
private List<TextRenderData> schema;
private String description;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isRequired() {
return required;
}
public void setRequired(boolean required) {
this.required = required;
}
public List<TextRenderData> getSchema() {
return schema;
}
public void setSchema(List<TextRenderData> schema) {
this.schema = schema;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
|
Sayi/poi-tl
|
poi-tl-plugin-highlight/src/test/java/com/deepoove/poi/plugin/highlight/example/SwaggerView.java
|
Java
|
apache-2.0
| 8,862
|
/* 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.activiti.idm.engine.impl.persistence.entity.data;
import java.util.List;
import java.util.Map;
import org.activiti.idm.api.Token;
import org.activiti.idm.engine.impl.Page;
import org.activiti.idm.engine.impl.TokenQueryImpl;
import org.activiti.idm.engine.impl.persistence.entity.TokenEntity;
/**
* @author Tijs Rademakers
*/
public interface TokenDataManager extends DataManager<TokenEntity> {
List<Token> findTokenByQueryCriteria(TokenQueryImpl query, Page page);
long findTokenCountByQueryCriteria(TokenQueryImpl query);
List<Token> findTokensByNativeQuery(Map<String, Object> parameterMap, int firstResult, int maxResults);
long findTokenCountByNativeQuery(Map<String, Object> parameterMap);
}
|
roberthafner/flowable-engine
|
modules/flowable-idm-engine/src/main/java/org/activiti/idm/engine/impl/persistence/entity/data/TokenDataManager.java
|
Java
|
apache-2.0
| 1,288
|
/*
* Copyright 2014 CyberVision, 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.
*/
#ifndef DEFAULTOPERATIONTCPCHANNEL_HPP_
#define DEFAULTOPERATIONTCPCHANNEL_HPP_
#include "kaa/KaaDefaults.hpp"
#include <cstdint>
#include <thread>
#include <array>
#include <boost/asio.hpp>
#include "kaa/KaaThread.hpp"
#include "kaa/security/KeyUtils.hpp"
#include "kaa/channel/IDataChannel.hpp"
#include "kaa/security/RsaEncoderDecoder.hpp"
#include "kaa/channel/IKaaChannelManager.hpp"
#include "kaa/kaatcp/KaaTcpResponseProcessor.hpp"
#include "kaa/channel/IPTransportInfo.hpp"
#include "kaa/channel/ITransportConnectionInfo.hpp"
#include "kaa/channel/TransportProtocolIdConstants.hpp"
namespace kaa {
class IKaaTcpRequest;
class KeyPair;
class DefaultOperationTcpChannel : public IDataChannel {
public:
DefaultOperationTcpChannel(IKaaChannelManager *channelManager, const KeyPair& clientKeys);
virtual ~DefaultOperationTcpChannel();
virtual void sync(TransportType type);
virtual void syncAll();
virtual void syncAck(TransportType type);
virtual const std::string& getId() const { return CHANNEL_ID; }
virtual TransportProtocolId getTransportProtocolId() const {
return TransportProtocolIdConstants::TCP_TRANSPORT_ID;
}
virtual void setMultiplexer(IKaaDataMultiplexer *multiplexer);
virtual void setDemultiplexer(IKaaDataDemultiplexer *demultiplexer);
virtual void setServer(ITransportConnectionInfoPtr server);
virtual ITransportConnectionInfoPtr getServer() {
return std::dynamic_pointer_cast<ITransportConnectionInfo, IPTransportInfo>(currentServer_);
}
virtual void shutdown();
virtual void pause();
virtual void resume();
virtual const std::map<TransportType, ChannelDirection>& getSupportedTransportTypes() const {
return SUPPORTED_TYPES;
}
virtual ServerType getServerType() const {
return ServerType::OPERATIONS;
}
virtual void setConnectivityChecker(ConnectivityCheckerPtr checker) {
connectivityChecker_= checker;
}
void onReadEvent(const boost::system::error_code& err);
void onPingTimeout(const boost::system::error_code& err);
void onConnack(const ConnackMessage& message);
void onDisconnect(const DisconnectMessage& message);
void onKaaSync(const KaaSyncResponse& message);
void onPingResponse();
void openConnection();
void closeConnection();
void onServerFailed();
private:
static const std::uint16_t PING_TIMEOUT;
static const std::uint16_t RECONNECT_TIMEOUT;
boost::system::error_code sendKaaSync(const std::map<TransportType, ChannelDirection>& transportTypes);
boost::system::error_code sendConnect();
boost::system::error_code sendDisconnect();
boost::system::error_code sendPingRequest();
boost::system::error_code sendData(const IKaaTcpRequest& request);
void readFromSocket();
void setTimer();
void createThreads();
void doShutdown();
private:
static const std::string CHANNEL_ID;
static const std::map<TransportType, ChannelDirection> SUPPORTED_TYPES;
static const std::uint16_t THREADPOOL_SIZE = 2;
static const std::uint32_t KAA_PLATFORM_PROTOCOL_AVRO_ID;
std::list<TransportType> ackTypes_;
KeyPair clientKeys_;
boost::asio::io_service io_;
boost::asio::io_service::work work_;
boost::asio::ip::tcp::socket sock_;
boost::asio::deadline_timer pingTimer_;
boost::asio::deadline_timer reconnectTimer_;
boost::asio::streambuf responseBuffer_;
std::array<std::thread, THREADPOOL_SIZE> channelThreads_;
bool firstStart_;
bool isConnected_;
bool isFirstResponseReceived_;
bool isPendingSyncRequest_;
bool isShutdown_;
bool isPaused_;
IKaaDataMultiplexer *multiplexer_;
IKaaDataDemultiplexer *demultiplexer_;
IKaaChannelManager *channelManager_;
std::shared_ptr<IPTransportInfo> currentServer_;
KaaTcpResponseProcessor responsePorcessor;
std::unique_ptr<RsaEncoderDecoder> encDec_;
KAA_MUTEX_DECLARE(channelGuard_);
ConnectivityCheckerPtr connectivityChecker_;
};
}
#endif /* DEFAULTOPERATIONTCPCHANNEL_HPP_ */
|
vzhukovskyi/kaa
|
client/client-multi/client-cpp/kaa/channel/impl/DefaultOperationTcpChannel.hpp
|
C++
|
apache-2.0
| 4,693
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<title>Uses of Class org.apache.poi.sl.draw.binding.CTGammaTransform (POI API Documentation)</title>
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.poi.sl.draw.binding.CTGammaTransform (POI API Documentation)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../org/apache/poi/sl/draw/binding/CTGammaTransform.html" title="class in org.apache.poi.sl.draw.binding">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>PREV</li>
<li>NEXT</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/apache/poi/sl/draw/binding//class-useCTGammaTransform.html" target="_top">FRAMES</a></li>
<li><a href="CTGammaTransform.html" target="_top">NO FRAMES</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.apache.poi.sl.draw.binding.CTGammaTransform" class="title">Uses of Class<br>org.apache.poi.sl.draw.binding.CTGammaTransform</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../../org/apache/poi/sl/draw/binding/CTGammaTransform.html" title="class in org.apache.poi.sl.draw.binding">CTGammaTransform</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.apache.poi.sl.draw.binding">org.apache.poi.sl.draw.binding</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.apache.poi.sl.draw.binding">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../../org/apache/poi/sl/draw/binding/CTGammaTransform.html" title="class in org.apache.poi.sl.draw.binding">CTGammaTransform</a> in <a href="../../../../../../../org/apache/poi/sl/draw/binding/package-summary.html">org.apache.poi.sl.draw.binding</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../org/apache/poi/sl/draw/binding/package-summary.html">org.apache.poi.sl.draw.binding</a> that return <a href="../../../../../../../org/apache/poi/sl/draw/binding/CTGammaTransform.html" title="class in org.apache.poi.sl.draw.binding">CTGammaTransform</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../../org/apache/poi/sl/draw/binding/CTGammaTransform.html" title="class in org.apache.poi.sl.draw.binding">CTGammaTransform</a></code></td>
<td class="colLast"><span class="strong">ObjectFactory.</span><code><strong><a href="../../../../../../../org/apache/poi/sl/draw/binding/ObjectFactory.html#createCTGammaTransform()">createCTGammaTransform</a></strong>()</code>
<div class="block">Create an instance of <a href="../../../../../../../org/apache/poi/sl/draw/binding/CTGammaTransform.html" title="class in org.apache.poi.sl.draw.binding"><code>CTGammaTransform</code></a></div>
</td>
</tr>
</tbody>
</table>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../org/apache/poi/sl/draw/binding/package-summary.html">org.apache.poi.sl.draw.binding</a> that return types with arguments of type <a href="../../../../../../../org/apache/poi/sl/draw/binding/CTGammaTransform.html" title="class in org.apache.poi.sl.draw.binding">CTGammaTransform</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>javax.xml.bind.JAXBElement<<a href="../../../../../../../org/apache/poi/sl/draw/binding/CTGammaTransform.html" title="class in org.apache.poi.sl.draw.binding">CTGammaTransform</a>></code></td>
<td class="colLast"><span class="strong">ObjectFactory.</span><code><strong><a href="../../../../../../../org/apache/poi/sl/draw/binding/ObjectFactory.html#createCTHslColorGamma(org.apache.poi.sl.draw.binding.CTGammaTransform)">createCTHslColorGamma</a></strong>(<a href="../../../../../../../org/apache/poi/sl/draw/binding/CTGammaTransform.html" title="class in org.apache.poi.sl.draw.binding">CTGammaTransform</a> value)</code>
<div class="block">Create an instance of <code>JAXBElement</code><code><</code><a href="../../../../../../../org/apache/poi/sl/draw/binding/CTGammaTransform.html" title="class in org.apache.poi.sl.draw.binding"><code>CTGammaTransform</code></a><code>></code>}</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>javax.xml.bind.JAXBElement<<a href="../../../../../../../org/apache/poi/sl/draw/binding/CTGammaTransform.html" title="class in org.apache.poi.sl.draw.binding">CTGammaTransform</a>></code></td>
<td class="colLast"><span class="strong">ObjectFactory.</span><code><strong><a href="../../../../../../../org/apache/poi/sl/draw/binding/ObjectFactory.html#createCTPresetColorGamma(org.apache.poi.sl.draw.binding.CTGammaTransform)">createCTPresetColorGamma</a></strong>(<a href="../../../../../../../org/apache/poi/sl/draw/binding/CTGammaTransform.html" title="class in org.apache.poi.sl.draw.binding">CTGammaTransform</a> value)</code>
<div class="block">Create an instance of <code>JAXBElement</code><code><</code><a href="../../../../../../../org/apache/poi/sl/draw/binding/CTGammaTransform.html" title="class in org.apache.poi.sl.draw.binding"><code>CTGammaTransform</code></a><code>></code>}</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>javax.xml.bind.JAXBElement<<a href="../../../../../../../org/apache/poi/sl/draw/binding/CTGammaTransform.html" title="class in org.apache.poi.sl.draw.binding">CTGammaTransform</a>></code></td>
<td class="colLast"><span class="strong">ObjectFactory.</span><code><strong><a href="../../../../../../../org/apache/poi/sl/draw/binding/ObjectFactory.html#createCTSchemeColorGamma(org.apache.poi.sl.draw.binding.CTGammaTransform)">createCTSchemeColorGamma</a></strong>(<a href="../../../../../../../org/apache/poi/sl/draw/binding/CTGammaTransform.html" title="class in org.apache.poi.sl.draw.binding">CTGammaTransform</a> value)</code>
<div class="block">Create an instance of <code>JAXBElement</code><code><</code><a href="../../../../../../../org/apache/poi/sl/draw/binding/CTGammaTransform.html" title="class in org.apache.poi.sl.draw.binding"><code>CTGammaTransform</code></a><code>></code>}</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>javax.xml.bind.JAXBElement<<a href="../../../../../../../org/apache/poi/sl/draw/binding/CTGammaTransform.html" title="class in org.apache.poi.sl.draw.binding">CTGammaTransform</a>></code></td>
<td class="colLast"><span class="strong">ObjectFactory.</span><code><strong><a href="../../../../../../../org/apache/poi/sl/draw/binding/ObjectFactory.html#createCTScRgbColorGamma(org.apache.poi.sl.draw.binding.CTGammaTransform)">createCTScRgbColorGamma</a></strong>(<a href="../../../../../../../org/apache/poi/sl/draw/binding/CTGammaTransform.html" title="class in org.apache.poi.sl.draw.binding">CTGammaTransform</a> value)</code>
<div class="block">Create an instance of <code>JAXBElement</code><code><</code><a href="../../../../../../../org/apache/poi/sl/draw/binding/CTGammaTransform.html" title="class in org.apache.poi.sl.draw.binding"><code>CTGammaTransform</code></a><code>></code>}</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>javax.xml.bind.JAXBElement<<a href="../../../../../../../org/apache/poi/sl/draw/binding/CTGammaTransform.html" title="class in org.apache.poi.sl.draw.binding">CTGammaTransform</a>></code></td>
<td class="colLast"><span class="strong">ObjectFactory.</span><code><strong><a href="../../../../../../../org/apache/poi/sl/draw/binding/ObjectFactory.html#createCTSRgbColorGamma(org.apache.poi.sl.draw.binding.CTGammaTransform)">createCTSRgbColorGamma</a></strong>(<a href="../../../../../../../org/apache/poi/sl/draw/binding/CTGammaTransform.html" title="class in org.apache.poi.sl.draw.binding">CTGammaTransform</a> value)</code>
<div class="block">Create an instance of <code>JAXBElement</code><code><</code><a href="../../../../../../../org/apache/poi/sl/draw/binding/CTGammaTransform.html" title="class in org.apache.poi.sl.draw.binding"><code>CTGammaTransform</code></a><code>></code>}</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>javax.xml.bind.JAXBElement<<a href="../../../../../../../org/apache/poi/sl/draw/binding/CTGammaTransform.html" title="class in org.apache.poi.sl.draw.binding">CTGammaTransform</a>></code></td>
<td class="colLast"><span class="strong">ObjectFactory.</span><code><strong><a href="../../../../../../../org/apache/poi/sl/draw/binding/ObjectFactory.html#createCTSystemColorGamma(org.apache.poi.sl.draw.binding.CTGammaTransform)">createCTSystemColorGamma</a></strong>(<a href="../../../../../../../org/apache/poi/sl/draw/binding/CTGammaTransform.html" title="class in org.apache.poi.sl.draw.binding">CTGammaTransform</a> value)</code>
<div class="block">Create an instance of <code>JAXBElement</code><code><</code><a href="../../../../../../../org/apache/poi/sl/draw/binding/CTGammaTransform.html" title="class in org.apache.poi.sl.draw.binding"><code>CTGammaTransform</code></a><code>></code>}</div>
</td>
</tr>
</tbody>
</table>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../org/apache/poi/sl/draw/binding/package-summary.html">org.apache.poi.sl.draw.binding</a> with parameters of type <a href="../../../../../../../org/apache/poi/sl/draw/binding/CTGammaTransform.html" title="class in org.apache.poi.sl.draw.binding">CTGammaTransform</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>javax.xml.bind.JAXBElement<<a href="../../../../../../../org/apache/poi/sl/draw/binding/CTGammaTransform.html" title="class in org.apache.poi.sl.draw.binding">CTGammaTransform</a>></code></td>
<td class="colLast"><span class="strong">ObjectFactory.</span><code><strong><a href="../../../../../../../org/apache/poi/sl/draw/binding/ObjectFactory.html#createCTHslColorGamma(org.apache.poi.sl.draw.binding.CTGammaTransform)">createCTHslColorGamma</a></strong>(<a href="../../../../../../../org/apache/poi/sl/draw/binding/CTGammaTransform.html" title="class in org.apache.poi.sl.draw.binding">CTGammaTransform</a> value)</code>
<div class="block">Create an instance of <code>JAXBElement</code><code><</code><a href="../../../../../../../org/apache/poi/sl/draw/binding/CTGammaTransform.html" title="class in org.apache.poi.sl.draw.binding"><code>CTGammaTransform</code></a><code>></code>}</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>javax.xml.bind.JAXBElement<<a href="../../../../../../../org/apache/poi/sl/draw/binding/CTGammaTransform.html" title="class in org.apache.poi.sl.draw.binding">CTGammaTransform</a>></code></td>
<td class="colLast"><span class="strong">ObjectFactory.</span><code><strong><a href="../../../../../../../org/apache/poi/sl/draw/binding/ObjectFactory.html#createCTPresetColorGamma(org.apache.poi.sl.draw.binding.CTGammaTransform)">createCTPresetColorGamma</a></strong>(<a href="../../../../../../../org/apache/poi/sl/draw/binding/CTGammaTransform.html" title="class in org.apache.poi.sl.draw.binding">CTGammaTransform</a> value)</code>
<div class="block">Create an instance of <code>JAXBElement</code><code><</code><a href="../../../../../../../org/apache/poi/sl/draw/binding/CTGammaTransform.html" title="class in org.apache.poi.sl.draw.binding"><code>CTGammaTransform</code></a><code>></code>}</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>javax.xml.bind.JAXBElement<<a href="../../../../../../../org/apache/poi/sl/draw/binding/CTGammaTransform.html" title="class in org.apache.poi.sl.draw.binding">CTGammaTransform</a>></code></td>
<td class="colLast"><span class="strong">ObjectFactory.</span><code><strong><a href="../../../../../../../org/apache/poi/sl/draw/binding/ObjectFactory.html#createCTSchemeColorGamma(org.apache.poi.sl.draw.binding.CTGammaTransform)">createCTSchemeColorGamma</a></strong>(<a href="../../../../../../../org/apache/poi/sl/draw/binding/CTGammaTransform.html" title="class in org.apache.poi.sl.draw.binding">CTGammaTransform</a> value)</code>
<div class="block">Create an instance of <code>JAXBElement</code><code><</code><a href="../../../../../../../org/apache/poi/sl/draw/binding/CTGammaTransform.html" title="class in org.apache.poi.sl.draw.binding"><code>CTGammaTransform</code></a><code>></code>}</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>javax.xml.bind.JAXBElement<<a href="../../../../../../../org/apache/poi/sl/draw/binding/CTGammaTransform.html" title="class in org.apache.poi.sl.draw.binding">CTGammaTransform</a>></code></td>
<td class="colLast"><span class="strong">ObjectFactory.</span><code><strong><a href="../../../../../../../org/apache/poi/sl/draw/binding/ObjectFactory.html#createCTScRgbColorGamma(org.apache.poi.sl.draw.binding.CTGammaTransform)">createCTScRgbColorGamma</a></strong>(<a href="../../../../../../../org/apache/poi/sl/draw/binding/CTGammaTransform.html" title="class in org.apache.poi.sl.draw.binding">CTGammaTransform</a> value)</code>
<div class="block">Create an instance of <code>JAXBElement</code><code><</code><a href="../../../../../../../org/apache/poi/sl/draw/binding/CTGammaTransform.html" title="class in org.apache.poi.sl.draw.binding"><code>CTGammaTransform</code></a><code>></code>}</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>javax.xml.bind.JAXBElement<<a href="../../../../../../../org/apache/poi/sl/draw/binding/CTGammaTransform.html" title="class in org.apache.poi.sl.draw.binding">CTGammaTransform</a>></code></td>
<td class="colLast"><span class="strong">ObjectFactory.</span><code><strong><a href="../../../../../../../org/apache/poi/sl/draw/binding/ObjectFactory.html#createCTSRgbColorGamma(org.apache.poi.sl.draw.binding.CTGammaTransform)">createCTSRgbColorGamma</a></strong>(<a href="../../../../../../../org/apache/poi/sl/draw/binding/CTGammaTransform.html" title="class in org.apache.poi.sl.draw.binding">CTGammaTransform</a> value)</code>
<div class="block">Create an instance of <code>JAXBElement</code><code><</code><a href="../../../../../../../org/apache/poi/sl/draw/binding/CTGammaTransform.html" title="class in org.apache.poi.sl.draw.binding"><code>CTGammaTransform</code></a><code>></code>}</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>javax.xml.bind.JAXBElement<<a href="../../../../../../../org/apache/poi/sl/draw/binding/CTGammaTransform.html" title="class in org.apache.poi.sl.draw.binding">CTGammaTransform</a>></code></td>
<td class="colLast"><span class="strong">ObjectFactory.</span><code><strong><a href="../../../../../../../org/apache/poi/sl/draw/binding/ObjectFactory.html#createCTSystemColorGamma(org.apache.poi.sl.draw.binding.CTGammaTransform)">createCTSystemColorGamma</a></strong>(<a href="../../../../../../../org/apache/poi/sl/draw/binding/CTGammaTransform.html" title="class in org.apache.poi.sl.draw.binding">CTGammaTransform</a> value)</code>
<div class="block">Create an instance of <code>JAXBElement</code><code><</code><a href="../../../../../../../org/apache/poi/sl/draw/binding/CTGammaTransform.html" title="class in org.apache.poi.sl.draw.binding"><code>CTGammaTransform</code></a><code>></code>}</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../org/apache/poi/sl/draw/binding/CTGammaTransform.html" title="class in org.apache.poi.sl.draw.binding">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>PREV</li>
<li>NEXT</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/apache/poi/sl/draw/binding//class-useCTGammaTransform.html" target="_top">FRAMES</a></li>
<li><a href="CTGammaTransform.html" target="_top">NO FRAMES</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>
<i>Copyright 2016 The Apache Software Foundation or
its licensors, as applicable.</i>
</small></p>
</body>
</html>
|
Aarhus-BSS/Aarhus-Research-Rebuilt
|
lib/poi-3.16-beta1/docs/apidocs/org/apache/poi/sl/draw/binding/class-use/CTGammaTransform.html
|
HTML
|
apache-2.0
| 19,721
|
# Uredo detenta Mains SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Uredo detenta Mains
### Remarks
null
|
mdoering/backbone
|
life/Fungi/Basidiomycota/Pucciniomycetes/Pucciniales/Uredo/Uredo detenta/README.md
|
Markdown
|
apache-2.0
| 167
|
/**
* AET
*
* Copyright (C) 2013 Cognifide Limited
*
* 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.cognifide.aet.communication.api.messages;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.Test;
public class ProgressLogTest {
@Test
public void toString_withNoFailedMessages_expectMessageWithoutFailed() {
ProgressLog progressLog = new ProgressLog("name", 105, 0, 105);
assertThat(progressLog.toString(), is("name: [success: 105, total: 105]"));
}
@Test
public void toString_withFailedMessages_expectMessageWithFailed() {
ProgressLog progressLog = new ProgressLog("name", 33, 1, 34);
assertThat(progressLog.toString(), is("name: [success: 33, failed: 1, total: 34]"));
}
}
|
Cognifide/AET
|
api/communication-api/src/test/java/com/cognifide/aet/communication/api/messages/ProgressLogTest.java
|
Java
|
apache-2.0
| 1,294
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_131) on Sat Jul 08 15:56:16 CEST 2017 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class io.klerch.alexa.state.handler.AWSDynamoStateHandler (Alexa Skills Kit States SDK for Java 1.1.0 API)</title>
<meta name="date" content="2017-07-08">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class io.klerch.alexa.state.handler.AWSDynamoStateHandler (Alexa Skills Kit States SDK for Java 1.1.0 API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../io/klerch/alexa/state/handler/AWSDynamoStateHandler.html" title="class in io.klerch.alexa.state.handler">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?io/klerch/alexa/state/handler/class-use/AWSDynamoStateHandler.html" target="_top">Frames</a></li>
<li><a href="AWSDynamoStateHandler.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class io.klerch.alexa.state.handler.AWSDynamoStateHandler" class="title">Uses of Class<br>io.klerch.alexa.state.handler.AWSDynamoStateHandler</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../io/klerch/alexa/state/handler/AWSDynamoStateHandler.html" title="class in io.klerch.alexa.state.handler">AWSDynamoStateHandler</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#io.klerch.alexa.state.handler">io.klerch.alexa.state.handler</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="io.klerch.alexa.state.handler">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../io/klerch/alexa/state/handler/AWSDynamoStateHandler.html" title="class in io.klerch.alexa.state.handler">AWSDynamoStateHandler</a> in <a href="../../../../../../io/klerch/alexa/state/handler/package-summary.html">io.klerch.alexa.state.handler</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../io/klerch/alexa/state/handler/package-summary.html">io.klerch.alexa.state.handler</a> that return <a href="../../../../../../io/klerch/alexa/state/handler/AWSDynamoStateHandler.html" title="class in io.klerch.alexa.state.handler">AWSDynamoStateHandler</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../io/klerch/alexa/state/handler/AWSDynamoStateHandler.html" title="class in io.klerch.alexa.state.handler">AWSDynamoStateHandler</a></code></td>
<td class="colLast"><span class="typeNameLabel">AWSDynamoStateHandler.</span><code><span class="memberNameLink"><a href="../../../../../../io/klerch/alexa/state/handler/AWSDynamoStateHandler.html#withUserId-java.lang.String-">withUserId</a></span>(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> userId)</code>
<div class="block">sets the userId used as a key when storing user-scoped model-state
If no userId is provided the handler will use userId coming in with the session
Note, the userId from Alexa will change when a user re-enables your skill</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../io/klerch/alexa/state/handler/AWSDynamoStateHandler.html" title="class in io.klerch.alexa.state.handler">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?io/klerch/alexa/state/handler/class-use/AWSDynamoStateHandler.html" target="_top">Frames</a></li>
<li><a href="AWSDynamoStateHandler.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2017. All rights reserved.</small></p>
</body>
</html>
|
KayLerch/alexa-skills-kit-states-java
|
docs/io/klerch/alexa/state/handler/class-use/AWSDynamoStateHandler.html
|
HTML
|
apache-2.0
| 7,442
|
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* 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.intellij.tasks.impl;
import com.intellij.notification.*;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.*;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.options.ShowSettingsUtil;
import com.intellij.openapi.progress.EmptyProgressIndicator;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.startup.StartupManager;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.AbstractVcs;
import com.intellij.openapi.vcs.ProjectLevelVcsManager;
import com.intellij.openapi.vcs.VcsTaskHandler;
import com.intellij.openapi.vcs.VcsType;
import com.intellij.openapi.vcs.changes.*;
import com.intellij.tasks.*;
import com.intellij.tasks.actions.TaskSearchSupport;
import com.intellij.tasks.config.TaskRepositoriesConfigurable;
import com.intellij.tasks.context.WorkingContextManager;
import com.intellij.ui.ColoredTreeCellRenderer;
import com.intellij.util.ArrayUtil;
import com.intellij.util.EventDispatcher;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.Convertor;
import com.intellij.util.containers.MultiMap;
import com.intellij.util.ui.UIUtil;
import com.intellij.util.xmlb.XmlSerializationException;
import com.intellij.util.xmlb.XmlSerializer;
import com.intellij.util.xmlb.XmlSerializerUtil;
import com.intellij.util.xmlb.annotations.AbstractCollection;
import com.intellij.util.xmlb.annotations.Property;
import com.intellij.util.xmlb.annotations.Tag;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import javax.swing.Timer;
import javax.swing.event.HyperlinkEvent;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* @author Dmitry Avdeev
*/
@State(
name = "TaskManager",
storages = {
@Storage(StoragePathMacros.WORKSPACE_FILE)
}
)
public class TaskManagerImpl extends TaskManager implements ProjectComponent, PersistentStateComponent<TaskManagerImpl.Config>,
ChangeListDecorator {
private static final Logger LOG = Logger.getInstance("#com.intellij.tasks.impl.TaskManagerImpl");
private static final DecimalFormat LOCAL_TASK_ID_FORMAT = new DecimalFormat("LOCAL-00000");
public static final Comparator<Task> TASK_UPDATE_COMPARATOR = (o1, o2) -> {
int i = Comparing.compare(o2.getUpdated(), o1.getUpdated());
return i == 0 ? Comparing.compare(o2.getCreated(), o1.getCreated()) : i;
};
private static final Convertor<Task, String> KEY_CONVERTOR = new Convertor<Task, String>() {
@Override
public String convert(Task o) {
return o.getId();
}
};
static final String TASKS_NOTIFICATION_GROUP = "Task Group";
private final Project myProject;
private final WorkingContextManager myContextManager;
private final Map<String, Task> myIssueCache = Collections.synchronizedMap(new LinkedHashMap<String, Task>());
private final Map<String, LocalTask> myTasks = Collections.synchronizedMap(new LinkedHashMap<String, LocalTask>() {
@Override
public LocalTask put(String key, LocalTask task) {
LocalTask result = super.put(key, task);
if (size() > myConfig.taskHistoryLength) {
ArrayList<Map.Entry<String, LocalTask>> list = new ArrayList<>(entrySet());
Collections.sort(list, (o1, o2) -> TASK_UPDATE_COMPARATOR.compare(o2.getValue(), o1.getValue()));
for (Map.Entry<String, LocalTask> oldest : list) {
if (!oldest.getValue().isDefault()) {
remove(oldest.getKey());
break;
}
}
}
return result;
}
});
@NotNull
private LocalTask myActiveTask = createDefaultTask();
private Timer myCacheRefreshTimer;
private volatile boolean myUpdating;
private final Config myConfig = new Config();
private final ChangeListAdapter myChangeListListener;
private final ChangeListManager myChangeListManager;
private final List<TaskRepository> myRepositories = new ArrayList<>();
private final EventDispatcher<TaskListener> myDispatcher = EventDispatcher.create(TaskListener.class);
private Set<TaskRepository> myBadRepositories = ContainerUtil.newConcurrentSet();
public TaskManagerImpl(Project project, WorkingContextManager contextManager, ChangeListManager changeListManager) {
myProject = project;
myContextManager = contextManager;
myChangeListManager = changeListManager;
myChangeListListener = new ChangeListAdapter() {
@Override
public void changeListRemoved(ChangeList list) {
LocalTask task = getAssociatedTask((LocalChangeList)list);
if (task != null) {
for (ChangeListInfo info : task.getChangeLists()) {
if (Comparing.equal(info.id, ((LocalChangeList)list).getId())) {
info.id = "";
}
}
}
}
@Override
public void defaultListChanged(ChangeList oldDefaultList, ChangeList newDefaultList) {
final LocalTask associatedTask = getAssociatedTask((LocalChangeList)newDefaultList);
if (associatedTask != null && !getActiveTask().equals(associatedTask)) {
ApplicationManager.getApplication().invokeLater(() -> activateTask(associatedTask, true), myProject.getDisposed());
}
}
};
}
@Override
public TaskRepository[] getAllRepositories() {
return myRepositories.toArray(new TaskRepository[myRepositories.size()]);
}
public <T extends TaskRepository> void setRepositories(List<T> repositories) {
Set<TaskRepository> set = new HashSet<>(myRepositories);
set.removeAll(repositories);
myBadRepositories.removeAll(set); // remove all changed reps
myIssueCache.clear();
myRepositories.clear();
myRepositories.addAll(repositories);
reps:
for (T repository : repositories) {
if (repository.isShared() && repository.getUrl() != null) {
List<TaskProjectConfiguration.SharedServer> servers = getProjectConfiguration().servers;
TaskRepositoryType type = repository.getRepositoryType();
for (TaskProjectConfiguration.SharedServer server : servers) {
if (repository.getUrl().equals(server.url) && type.getName().equals(server.type)) {
continue reps;
}
}
TaskProjectConfiguration.SharedServer server = new TaskProjectConfiguration.SharedServer();
server.type = type.getName();
server.url = repository.getUrl();
servers.add(server);
}
}
}
@Override
public void removeTask(LocalTask task) {
if (task.isDefault()) return;
if (myActiveTask.equals(task)) {
activateTask(myTasks.get(LocalTaskImpl.DEFAULT_TASK_ID), true);
}
myTasks.remove(task.getId());
myDispatcher.getMulticaster().taskRemoved(task);
myContextManager.removeContext(task);
}
@Override
public void addTaskListener(TaskListener listener) {
myDispatcher.addListener(listener);
}
@Override
public void addTaskListener(@NotNull TaskListener listener, @NotNull Disposable parentDisposable) {
myDispatcher.addListener(listener, parentDisposable);
}
@Override
public void removeTaskListener(TaskListener listener) {
myDispatcher.removeListener(listener);
}
@NotNull
@Override
public LocalTask getActiveTask() {
return myActiveTask;
}
@Nullable
@Override
public LocalTask findTask(String id) {
return myTasks.get(id);
}
@NotNull
@Override
public List<Task> getIssues(@Nullable final String query) {
return getIssues(query, true);
}
@Override
public List<Task> getIssues(@Nullable final String query, final boolean forceRequest) {
return getIssues(query, 0, 50, true, new EmptyProgressIndicator(), forceRequest);
}
@Override
public List<Task> getIssues(@Nullable String query,
int offset,
int limit,
final boolean withClosed,
@NotNull ProgressIndicator indicator,
boolean forceRequest) {
List<Task> tasks = getIssuesFromRepositories(query, offset, limit, withClosed, forceRequest, indicator);
if (tasks == null) {
return getCachedIssues(withClosed);
}
myIssueCache.putAll(ContainerUtil.newMapFromValues(tasks.iterator(), KEY_CONVERTOR));
return ContainerUtil.filter(tasks, task -> withClosed || !task.isClosed());
}
@Override
public List<Task> getCachedIssues() {
return getCachedIssues(true);
}
@Override
public List<Task> getCachedIssues(final boolean withClosed) {
return ContainerUtil.filter(myIssueCache.values(), task -> withClosed || !task.isClosed());
}
@Nullable
@Override
public Task updateIssue(@NotNull String id) {
for (TaskRepository repository : getAllRepositories()) {
if (repository.extractId(id) == null) {
continue;
}
try {
LOG.info("Searching for task '" + id + "' in " + repository);
Task issue = repository.findTask(id);
if (issue != null) {
LocalTask localTask = findTask(id);
if (localTask != null) {
localTask.updateFromIssue(issue);
return localTask;
}
return issue;
}
}
catch (Exception e) {
LOG.info(e);
}
}
return null;
}
@Override
public List<LocalTask> getLocalTasks() {
return getLocalTasks(true);
}
@Override
public List<LocalTask> getLocalTasks(final boolean withClosed) {
synchronized (myTasks) {
return ContainerUtil.filter(myTasks.values(), task -> withClosed || !isLocallyClosed(task));
}
}
@Override
public LocalTask addTask(Task issue) {
LocalTaskImpl task = issue instanceof LocalTaskImpl ? (LocalTaskImpl)issue : new LocalTaskImpl(issue);
addTask(task);
return task;
}
@Override
public LocalTaskImpl createLocalTask(@NotNull String summary) {
return createTask(LOCAL_TASK_ID_FORMAT.format(myConfig.localTasksCounter++), summary);
}
private static LocalTaskImpl createTask(@NotNull String id, @NotNull String summary) {
LocalTaskImpl task = new LocalTaskImpl(id, summary);
Date date = new Date();
task.setCreated(date);
task.setUpdated(date);
return task;
}
@Override
public LocalTask activateTask(@NotNull final Task origin, boolean clearContext) {
LocalTask activeTask = getActiveTask();
if (origin.equals(activeTask)) return activeTask;
saveActiveTask();
if (clearContext) {
myContextManager.clearContext();
}
myContextManager.restoreContext(origin);
final LocalTask task = doActivate(origin, true);
return restoreVcsContext(task);
}
private LocalTask restoreVcsContext(LocalTask task) {
if (!isVcsEnabled()) return task;
List<ChangeListInfo> changeLists = task.getChangeLists();
if (!changeLists.isEmpty()) {
ChangeListInfo info = changeLists.get(0);
LocalChangeList changeList = myChangeListManager.getChangeList(info.id);
if (changeList == null) {
changeList = myChangeListManager.addChangeList(info.name, info.comment);
info.id = changeList.getId();
}
myChangeListManager.setDefaultChangeList(changeList);
}
List<BranchInfo> branches = task.getBranches(false);
// we should have exactly one branch per repo
MultiMap<String, BranchInfo> multiMap = new MultiMap<>();
for (BranchInfo branch : branches) {
multiMap.putValue(branch.repository, branch);
}
for (String repo: multiMap.keySet()) {
Collection<BranchInfo> infos = multiMap.get(repo);
if (infos.size() > 1) {
// cleanup needed
List<BranchInfo> existing = getAllBranches(repo);
for (Iterator<BranchInfo> iterator = infos.iterator(); iterator.hasNext(); ) {
BranchInfo info = iterator.next();
if (!existing.contains(info)) {
iterator.remove();
if (infos.size() == 1) {
break;
}
}
}
}
}
VcsTaskHandler.TaskInfo info = fromBranches(new ArrayList<>(multiMap.values()));
switchBranch(info);
return task;
}
private List<BranchInfo> getAllBranches(final String repo) {
ArrayList<BranchInfo> infos = new ArrayList<>();
VcsTaskHandler[] handlers = VcsTaskHandler.getAllHandlers(myProject);
for (VcsTaskHandler handler : handlers) {
VcsTaskHandler.TaskInfo[] tasks = handler.getAllExistingTasks();
for (VcsTaskHandler.TaskInfo info : tasks) {
infos.addAll(ContainerUtil.filter(BranchInfo.fromTaskInfo(info, false), info1 -> Comparing.equal(info1.repository, repo)));
}
}
return infos;
}
private void switchBranch(VcsTaskHandler.TaskInfo info) {
VcsTaskHandler[] handlers = VcsTaskHandler.getAllHandlers(myProject);
for (VcsTaskHandler handler : handlers) {
handler.switchToTask(info, null);
}
}
private static VcsTaskHandler.TaskInfo fromBranches(List<BranchInfo> branches) {
if (branches.isEmpty()) return new VcsTaskHandler.TaskInfo(null, Collections.<String>emptyList());
MultiMap<String, String> map = new MultiMap<>();
for (BranchInfo branch : branches) {
map.putValue(branch.name, branch.repository);
}
Map.Entry<String, Collection<String>> next = map.entrySet().iterator().next();
return new VcsTaskHandler.TaskInfo(next.getKey(), next.getValue());
}
public void createBranch(LocalTask task, LocalTask previousActive, String name, @Nullable VcsTaskHandler.TaskInfo branchFrom) {
VcsTaskHandler[] handlers = VcsTaskHandler.getAllHandlers(myProject);
for (VcsTaskHandler handler : handlers) {
VcsTaskHandler.TaskInfo[] info = handler.getCurrentTasks();
if (previousActive != null && previousActive.getBranches(false).isEmpty()) {
addBranches(previousActive, info, false);
}
addBranches(task, info, true);
if (info.length == 0 && branchFrom != null) {
addBranches(task, new VcsTaskHandler.TaskInfo[] { branchFrom }, true);
}
addBranches(task, new VcsTaskHandler.TaskInfo[] { handler.startNewTask(name) }, false);
}
}
public void mergeBranch(LocalTask task) {
VcsTaskHandler.TaskInfo original = fromBranches(task.getBranches(true));
VcsTaskHandler.TaskInfo feature = fromBranches(task.getBranches(false));
VcsTaskHandler[] handlers = VcsTaskHandler.getAllHandlers(myProject);
for (VcsTaskHandler handler : handlers) {
handler.closeTask(feature, original);
}
}
public static void addBranches(LocalTask task, VcsTaskHandler.TaskInfo[] info, boolean original) {
for (VcsTaskHandler.TaskInfo taskInfo : info) {
List<BranchInfo> branchInfos = BranchInfo.fromTaskInfo(taskInfo, original);
for (BranchInfo branchInfo : branchInfos) {
task.addBranch(branchInfo);
}
}
}
private void saveActiveTask() {
myContextManager.saveContext(myActiveTask);
myActiveTask.setUpdated(new Date());
}
private LocalTask doActivate(Task origin, boolean explicitly) {
final LocalTaskImpl task = origin instanceof LocalTaskImpl ? (LocalTaskImpl)origin : new LocalTaskImpl(origin);
if (explicitly) {
task.setUpdated(new Date());
}
myActiveTask.setActive(false);
task.setActive(true);
addTask(task);
if (task.isIssue()) {
StartupManager.getInstance(myProject).runWhenProjectIsInitialized(
() -> ProgressManager.getInstance().run(new com.intellij.openapi.progress.Task.Backgroundable(myProject, "Updating " + task.getPresentableId()) {
public void run(@NotNull ProgressIndicator indicator) {
updateIssue(task.getId());
}
}));
}
LocalTask oldActiveTask = myActiveTask;
boolean isChanged = !task.equals(oldActiveTask);
myActiveTask = task;
if (isChanged) {
myDispatcher.getMulticaster().taskDeactivated(oldActiveTask);
myDispatcher.getMulticaster().taskActivated(task);
}
return task;
}
private void addTask(LocalTaskImpl task) {
myTasks.put(task.getId(), task);
myDispatcher.getMulticaster().taskAdded(task);
}
@Override
public boolean testConnection(final TaskRepository repository) {
TestConnectionTask task = new TestConnectionTask("Test connection") {
public void run(@NotNull ProgressIndicator indicator) {
indicator.setText("Connecting to " + repository.getUrl() + "...");
indicator.setFraction(0);
indicator.setIndeterminate(true);
try {
myConnection = repository.createCancellableConnection();
if (myConnection != null) {
Future<Exception> future = ApplicationManager.getApplication().executeOnPooledThread(myConnection);
while (true) {
try {
myException = future.get(100, TimeUnit.MILLISECONDS);
return;
}
catch (TimeoutException ignore) {
try {
indicator.checkCanceled();
}
catch (ProcessCanceledException e) {
myException = e;
myConnection.cancel();
return;
}
}
catch (Exception e) {
myException = e;
return;
}
}
}
else {
try {
repository.testConnection();
}
catch (Exception e) {
LOG.info(e);
myException = e;
}
}
}
catch (Exception e) {
myException = e;
}
}
};
ProgressManager.getInstance().run(task);
Exception e = task.myException;
if (e == null) {
myBadRepositories.remove(repository);
Messages.showMessageDialog(myProject, "Connection is successful", "Connection", Messages.getInformationIcon());
}
else if (!(e instanceof ProcessCanceledException)) {
String message = e.getMessage();
if (e instanceof UnknownHostException) {
message = "Unknown host: " + message;
}
if (message == null) {
LOG.error(e);
message = "Unknown error";
}
Messages.showErrorDialog(myProject, StringUtil.capitalize(message), "Error");
}
return e == null;
}
@NotNull
public Config getState() {
myConfig.tasks = ContainerUtil.map(myTasks.values(), new Function<Task, LocalTaskImpl>() {
public LocalTaskImpl fun(Task task) {
return new LocalTaskImpl(task);
}
});
myConfig.servers = XmlSerializer.serialize(getAllRepositories());
return myConfig;
}
public void loadState(Config config) {
XmlSerializerUtil.copyBean(config, myConfig);
myTasks.clear();
for (LocalTaskImpl task : config.tasks) {
addTask(task);
}
myRepositories.clear();
Element element = config.servers;
List<TaskRepository> repositories = loadRepositories(element);
myRepositories.addAll(repositories);
}
public static ArrayList<TaskRepository> loadRepositories(Element element) {
ArrayList<TaskRepository> repositories = new ArrayList<>();
for (TaskRepositoryType repositoryType : TaskRepositoryType.getRepositoryTypes()) {
for (Object o : element.getChildren()) {
if (((Element)o).getName().equals(repositoryType.getName())) {
try {
@SuppressWarnings({"unchecked"})
TaskRepository repository = (TaskRepository)XmlSerializer.deserialize((Element)o, repositoryType.getRepositoryClass());
if (repository != null) {
repository.setRepositoryType(repositoryType);
repositories.add(repository);
}
}
catch (XmlSerializationException e) {
LOG.error(e.getMessage(), e);
}
}
}
}
return repositories;
}
public void projectOpened() {
TaskProjectConfiguration projectConfiguration = getProjectConfiguration();
servers:
for (TaskProjectConfiguration.SharedServer server : projectConfiguration.servers) {
if (server.type == null || server.url == null) {
continue;
}
for (TaskRepositoryType<?> repositoryType : TaskRepositoryType.getRepositoryTypes()) {
if (repositoryType.getName().equals(server.type)) {
for (TaskRepository repository : myRepositories) {
if (!repositoryType.equals(repository.getRepositoryType())) {
continue;
}
if (server.url.equals(repository.getUrl())) {
continue servers;
}
}
TaskRepository repository = repositoryType.createRepository();
repository.setUrl(server.url);
repository.setShared(true);
myRepositories.add(repository);
}
}
}
myContextManager.pack(200, 50);
// make sure the task is associated with default changelist
LocalTask defaultTask = findTask(LocalTaskImpl.DEFAULT_TASK_ID);
LocalChangeList defaultList = myChangeListManager.findChangeList(LocalChangeList.DEFAULT_NAME);
if (defaultList != null && defaultTask != null) {
ChangeListInfo listInfo = new ChangeListInfo(defaultList);
if (!defaultTask.getChangeLists().contains(listInfo)) {
defaultTask.addChangelist(listInfo);
}
}
// remove already not existing changelists from tasks changelists
for (LocalTask localTask : getLocalTasks()) {
for (Iterator<ChangeListInfo> iterator = localTask.getChangeLists().iterator(); iterator.hasNext(); ) {
final ChangeListInfo changeListInfo = iterator.next();
if (myChangeListManager.getChangeList(changeListInfo.id) == null) {
iterator.remove();
}
}
}
myChangeListManager.addChangeListListener(myChangeListListener);
}
private TaskProjectConfiguration getProjectConfiguration() {
return ServiceManager.getService(myProject, TaskProjectConfiguration.class);
}
public void projectClosed() {
}
@NotNull
public String getComponentName() {
return "Task Manager";
}
public void initComponent() {
if (!ApplicationManager.getApplication().isUnitTestMode()) {
myCacheRefreshTimer = UIUtil.createNamedTimer("TaskManager refresh", myConfig.updateInterval * 60 * 1000, new ActionListener() {
public void actionPerformed(@NotNull ActionEvent e) {
if (myConfig.updateEnabled && !myUpdating) {
LOG.debug("Updating issues cache (every " + myConfig.updateInterval + " min)");
updateIssues(null);
}
}
});
myCacheRefreshTimer.setInitialDelay(0);
StartupManager.getInstance(myProject).registerPostStartupActivity(() -> myCacheRefreshTimer.start());
}
// make sure that the default task is exist
LocalTask defaultTask = findTask(LocalTaskImpl.DEFAULT_TASK_ID);
if (defaultTask == null) {
defaultTask = createDefaultTask();
addTask(defaultTask);
}
// search for active task
LocalTask activeTask = null;
final List<LocalTask> tasks = getLocalTasks();
Collections.sort(tasks, TASK_UPDATE_COMPARATOR);
for (LocalTask task : tasks) {
if (activeTask == null) {
if (task.isActive()) {
activeTask = task;
}
}
else {
task.setActive(false);
}
}
if (activeTask == null) {
activeTask = defaultTask;
}
myActiveTask = activeTask;
doActivate(myActiveTask, false);
myDispatcher.getMulticaster().taskActivated(myActiveTask);
}
private static LocalTaskImpl createDefaultTask() {
LocalTaskImpl task = new LocalTaskImpl(LocalTaskImpl.DEFAULT_TASK_ID, "Default task");
Date date = new Date();
task.setCreated(date);
task.setUpdated(date);
return task;
}
public void disposeComponent() {
if (myCacheRefreshTimer != null) {
myCacheRefreshTimer.stop();
}
myChangeListManager.removeChangeListListener(myChangeListListener);
}
public void updateIssues(final @Nullable Runnable onComplete) {
TaskRepository first = ContainerUtil.find(getAllRepositories(), repository -> repository.isConfigured());
if (first == null) {
myIssueCache.clear();
if (onComplete != null) {
onComplete.run();
}
return;
}
myUpdating = true;
if (ApplicationManager.getApplication().isUnitTestMode()) {
doUpdate(onComplete);
}
else {
ApplicationManager.getApplication().executeOnPooledThread(() -> doUpdate(onComplete));
}
}
private void doUpdate(@Nullable Runnable onComplete) {
try {
List<Task> issues = getIssuesFromRepositories(null, 0, myConfig.updateIssuesCount, false, false, new EmptyProgressIndicator());
if (issues == null) return;
synchronized (myIssueCache) {
myIssueCache.clear();
for (Task issue : issues) {
myIssueCache.put(issue.getId(), issue);
}
}
// update local tasks
synchronized (myTasks) {
for (Map.Entry<String, LocalTask> entry : myTasks.entrySet()) {
Task issue = myIssueCache.get(entry.getKey());
if (issue != null) {
entry.getValue().updateFromIssue(issue);
}
}
}
}
finally {
if (onComplete != null) {
onComplete.run();
}
myUpdating = false;
}
}
@Nullable
private List<Task> getIssuesFromRepositories(@Nullable String request,
int offset,
int limit,
boolean withClosed,
boolean forceRequest,
@NotNull final ProgressIndicator cancelled) {
List<Task> issues = null;
for (final TaskRepository repository : getAllRepositories()) {
if (!repository.isConfigured() || (!forceRequest && myBadRepositories.contains(repository))) {
continue;
}
try {
long start = System.currentTimeMillis();
Task[] tasks = repository.getIssues(request, offset, limit, withClosed, cancelled);
long timeSpent = System.currentTimeMillis() - start;
LOG.info(String.format("Total %s ms to download %d issues from '%s' (pattern '%s')",
timeSpent, tasks.length, repository.getUrl(), request));
myBadRepositories.remove(repository);
if (issues == null) issues = new ArrayList<>(tasks.length);
if (!repository.isSupported(TaskRepository.NATIVE_SEARCH) && request != null) {
List<Task> filteredTasks = TaskSearchSupport.filterTasks(request, ContainerUtil.list(tasks));
ContainerUtil.addAll(issues, filteredTasks);
}
else {
ContainerUtil.addAll(issues, tasks);
}
}
catch (ProcessCanceledException ignored) {
// OK
}
catch (Exception e) {
String reason = "";
// Fix to IDEA-111810
//noinspection InstanceofCatchParameter
if (e.getClass() == Exception.class || e instanceof RequestFailedException) {
// probably contains some message meaningful to end-user
reason = e.getMessage();
}
//noinspection InstanceofCatchParameter
if (e instanceof SocketTimeoutException) {
LOG.warn("Socket timeout from " + repository);
}
else {
LOG.warn("Cannot connect to " + repository, e);
}
myBadRepositories.add(repository);
if (forceRequest) {
notifyAboutConnectionFailure(repository, reason);
}
}
}
return issues;
}
private void notifyAboutConnectionFailure(final TaskRepository repository, String details) {
Notifications.Bus.register(TASKS_NOTIFICATION_GROUP, NotificationDisplayType.BALLOON);
String content = "<p><a href=\"\">Configure server...</a></p>";
if (!StringUtil.isEmpty(details)) {
content = "<p>" + details + "</p>" + content;
}
Notifications.Bus.notify(new Notification(TASKS_NOTIFICATION_GROUP, "Cannot connect to " + repository.getUrl(),
content, NotificationType.WARNING,
new NotificationListener() {
public void hyperlinkUpdate(@NotNull Notification notification,
@NotNull HyperlinkEvent event) {
TaskRepositoriesConfigurable configurable =
new TaskRepositoriesConfigurable(myProject);
ShowSettingsUtil.getInstance().editConfigurable(myProject, configurable);
if (!ArrayUtil.contains(repository, getAllRepositories())) {
notification.expire();
}
}
}), myProject);
}
@Override
public boolean isVcsEnabled() {
return ProjectLevelVcsManager.getInstance(myProject).getAllActiveVcss().length > 0;
}
@Override
public AbstractVcs getActiveVcs() {
AbstractVcs[] vcss = ProjectLevelVcsManager.getInstance(myProject).getAllActiveVcss();
if (vcss.length == 0) return null;
for (AbstractVcs vcs : vcss) {
if (vcs.getType() == VcsType.distributed) {
return vcs;
}
}
return vcss[0];
}
@Override
public boolean isLocallyClosed(@NotNull LocalTask localTask) {
if (isVcsEnabled()) {
List<ChangeListInfo> lists = localTask.getChangeLists();
if (lists.isEmpty()) return true;
for (ChangeListInfo list : lists) {
if (StringUtil.isEmpty(list.id)) {
return true;
}
}
}
return false;
}
@Nullable
@Override
public LocalTask getAssociatedTask(@NotNull LocalChangeList list) {
for (LocalTask task : getLocalTasks()) {
for (ChangeListInfo changeListInfo : task.getChangeLists()) {
if (changeListInfo.id.equals(list.getId())) {
return task;
}
}
}
return null;
}
@Override
public void trackContext(@NotNull LocalChangeList changeList) {
ChangeListInfo changeListInfo = new ChangeListInfo(changeList);
String changeListName = changeList.getName();
LocalTaskImpl task = createLocalTask(changeListName);
task.addChangelist(changeListInfo);
addTask(task);
if (changeList.isDefault()) {
activateTask(task, false);
}
}
@Override
public void disassociateFromTask(@NotNull LocalChangeList changeList) {
ChangeListInfo changeListInfo = new ChangeListInfo(changeList);
for (LocalTask localTask : getLocalTasks()) {
if (localTask.getChangeLists().contains(changeListInfo)) {
localTask.removeChangelist(changeListInfo);
}
}
}
public void decorateChangeList(@NotNull LocalChangeList changeList,
@NotNull ColoredTreeCellRenderer cellRenderer,
boolean selected,
boolean expanded,
boolean hasFocus) {
LocalTask task = getAssociatedTask(changeList);
if (task != null && task.isIssue()) {
cellRenderer.setIcon(task.getIcon());
}
}
public void createChangeList(@NotNull LocalTask task, String name) {
String comment = TaskUtil.getChangeListComment(task);
createChangeList(task, name, comment);
}
private void createChangeList(LocalTask task, String name, @Nullable String comment) {
LocalChangeList changeList = myChangeListManager.findChangeList(name);
if (changeList == null) {
changeList = myChangeListManager.addChangeList(name, comment);
}
else {
final LocalTask associatedTask = getAssociatedTask(changeList);
if (associatedTask != null) {
associatedTask.removeChangelist(new ChangeListInfo(changeList));
}
changeList.setComment(comment);
}
task.addChangelist(new ChangeListInfo(changeList));
myChangeListManager.setDefaultChangeList(changeList);
}
public String getChangelistName(Task task) {
String name = task.isIssue() && myConfig.changelistNameFormat != null
? TaskUtil.formatTask(task, myConfig.changelistNameFormat)
: task.getSummary();
return StringUtil.shortenTextWithEllipsis(name, 100, 0);
}
@NotNull
public String suggestBranchName(@NotNull Task task) {
String name = constructDefaultBranchName(task);
if (task.isIssue()) return name.replace(' ', '-');
List<String> words = StringUtil.getWordsIn(name);
String[] strings = ArrayUtil.toStringArray(words);
return StringUtil.join(strings, 0, Math.min(2, strings.length), "-");
}
@NotNull
public String constructDefaultBranchName(@NotNull Task task) {
return task.isIssue() ? TaskUtil.formatTask(task, myConfig.branchNameFormat) : task.getSummary();
}
@TestOnly
public ChangeListAdapter getChangeListListener() {
return myChangeListListener;
}
/**
* Reconfigure repository's HTTP clients probably to apply new connection settings.
*/
public void reconfigureRepositoryClients() {
for (TaskRepository repository : myRepositories) {
if (repository instanceof BaseRepositoryImpl) {
((BaseRepositoryImpl)repository).reconfigureClient();
}
}
}
public static class Config {
@Property(surroundWithTag = false)
@AbstractCollection(surroundWithTag = false, elementTag = "task")
public List<LocalTaskImpl> tasks = new ArrayList<>();
public int localTasksCounter = 1;
public int taskHistoryLength = 50;
public boolean updateEnabled = true;
public int updateInterval = 20;
public int updateIssuesCount = 100;
// create task options
public boolean clearContext = true;
public boolean createChangelist = true;
public boolean createBranch = true;
public boolean useBranch = false;
// close task options
public boolean commitChanges = true;
public boolean mergeBranch = true;
public boolean saveContextOnCommit = true;
public boolean trackContextForNewChangelist = false;
public String changelistNameFormat = "{id} {summary}";
public String branchNameFormat = "{id}";
public boolean searchClosedTasks = false;
@Tag("servers")
public Element servers = new Element("servers");
}
private abstract class TestConnectionTask extends com.intellij.openapi.progress.Task.Modal {
protected Exception myException;
@Nullable
protected TaskRepository.CancellableConnection myConnection;
public TestConnectionTask(String title) {
super(TaskManagerImpl.this.myProject, title, true);
}
@Override
public void onCancel() {
if (myConnection != null) {
myConnection.cancel();
}
}
}
}
|
hurricup/intellij-community
|
plugins/tasks/tasks-core/src/com/intellij/tasks/impl/TaskManagerImpl.java
|
Java
|
apache-2.0
| 36,551
|
// Copyright (C) 2015 The GoHBase Authors. All rights reserved.
// This file is part of GoHBase.
// Use of this source code is governed by the Apache License 2.0
// that can be found in the COPYING file.
package region
import (
"encoding/binary"
"errors"
"fmt"
"io"
"net"
"sync"
"sync/atomic"
"time"
log "github.com/sirupsen/logrus"
"github.com/golang/protobuf/proto"
"github.com/tsuna/gohbase/hrpc"
"github.com/tsuna/gohbase/pb"
)
// ClientType is a type alias to represent the type of this region client
type ClientType string
type canDeserializeCellBlocks interface {
// DeserializeCellBlocks populates passed protobuf message with results
// deserialized from the reader and returns number of bytes read or error.
DeserializeCellBlocks(proto.Message, []byte) (uint32, error)
}
var (
// ErrMissingCallID is used when HBase sends us a response message for a
// request that we didn't send
ErrMissingCallID = errors.New("got a response with a nonsensical call ID")
// ErrClientDead is returned to rpcs when Close() is called or when client
// died because of failed send or receive
ErrClientDead = UnrecoverableError{errors.New("client is dead")}
// javaRetryableExceptions is a map where all Java exceptions that signify
// the RPC should be sent again are listed (as keys). If a Java exception
// listed here is returned by HBase, the client should attempt to resend
// the RPC message, potentially via a different region client.
javaRetryableExceptions = map[string]struct{}{
"org.apache.hadoop.hbase.CallQueueTooBigException": struct{}{},
"org.apache.hadoop.hbase.NotServingRegionException": struct{}{},
"org.apache.hadoop.hbase.exceptions.RegionMovedException": struct{}{},
"org.apache.hadoop.hbase.exceptions.RegionOpeningException": struct{}{},
"org.apache.hadoop.hbase.ipc.ServerNotRunningYetException": struct{}{},
"org.apache.hadoop.hbase.quotas.RpcThrottlingException": struct{}{},
"org.apache.hadoop.hbase.RetryImmediatelyException": struct{}{},
}
// javaUnrecoverableExceptions is a map where all Java exceptions that signify
// the RPC should be sent again are listed (as keys). If a Java exception
// listed here is returned by HBase, the RegionClient will be closed and a new
// one should be established.
javaUnrecoverableExceptions = map[string]struct{}{
"org.apache.hadoop.hbase.regionserver.RegionServerAbortedException": struct{}{},
"org.apache.hadoop.hbase.regionserver.RegionServerStoppedException": struct{}{},
}
)
const (
//DefaultLookupTimeout is the default region lookup timeout
DefaultLookupTimeout = 30 * time.Second
//DefaultReadTimeout is the default region read timeout
DefaultReadTimeout = 30 * time.Second
// RegionClient is a ClientType that means this will be a normal client
RegionClient = ClientType("ClientService")
// MasterClient is a ClientType that means this client will talk to the
// master server
MasterClient = ClientType("MasterService")
)
var bufferPool = sync.Pool{
New: func() interface{} {
var b []byte
return b
},
}
func newBuffer(size int) []byte {
b := bufferPool.Get().([]byte)
if cap(b) < size {
doublecap := 2 * cap(b)
if doublecap > size {
return make([]byte, size, doublecap)
}
return make([]byte, size)
}
return b[:size]
}
func freeBuffer(b []byte) {
bufferPool.Put(b[:0])
}
// UnrecoverableError is an error that this region.Client can't recover from.
// The connection to the RegionServer has to be closed and all queued and
// outstanding RPCs will be failed / retried.
type UnrecoverableError struct {
error
}
func (e UnrecoverableError) Error() string {
return e.error.Error()
}
// RetryableError is an error that indicates the RPC should be retried because
// the error is transient (e.g. a region being momentarily unavailable).
type RetryableError struct {
error
}
func (e RetryableError) Error() string {
return e.error.Error()
}
// client manages a connection to a RegionServer.
type client struct {
conn net.Conn
// Address of the RegionServer.
addr string
// once used for concurrent calls to fail
once sync.Once
rpcs chan hrpc.Call
done chan struct{}
// sent contains the mapping of sent call IDs to RPC calls, so that when
// a response is received it can be tied to the correct RPC
sentM sync.Mutex // protects sent
sent map[uint32]hrpc.Call
// inFlight is number of rpcs sent to regionserver awaiting response
inFlightM sync.Mutex // protects inFlight and SetReadDeadline
inFlight uint32
id uint32
rpcQueueSize int
flushInterval time.Duration
effectiveUser string
// readTimeout is the maximum amount of time to wait for regionserver reply
readTimeout time.Duration
}
// QueueRPC will add an rpc call to the queue for processing by the writer goroutine
func (c *client) QueueRPC(rpc hrpc.Call) {
if b, ok := rpc.(hrpc.Batchable); ok && c.rpcQueueSize > 1 && !b.SkipBatch() {
// queue up the rpc
select {
case <-rpc.Context().Done():
// rpc timed out before being processed
case <-c.done:
returnResult(rpc, nil, ErrClientDead)
case c.rpcs <- rpc:
}
} else {
if err := c.trySend(rpc); err != nil {
returnResult(rpc, nil, err)
}
}
}
// Close asks this region.Client to close its connection to the RegionServer.
// All queued and outstanding RPCs, if any, will be failed as if a connection
// error had happened.
func (c *client) Close() {
c.fail(ErrClientDead)
}
// Addr returns address of the region server the client is connected to
func (c *client) Addr() string {
return c.addr
}
// String returns a string represintation of the current region client
func (c *client) String() string {
return fmt.Sprintf("RegionClient{Addr: %s}", c.addr)
}
func (c *client) inFlightUp() {
c.inFlightM.Lock()
c.inFlight++
// we expect that at least the last request can be completed within readTimeout
c.conn.SetReadDeadline(time.Now().Add(c.readTimeout))
c.inFlightM.Unlock()
}
func (c *client) inFlightDown() {
c.inFlightM.Lock()
c.inFlight--
// reset read timeout if we are not waiting for any responses
// in order to prevent from closing this client if there are no request
if c.inFlight == 0 {
c.conn.SetReadDeadline(time.Time{})
}
c.inFlightM.Unlock()
}
func (c *client) fail(err error) {
c.once.Do(func() {
log.WithFields(log.Fields{
"client": c,
"err": err,
}).Error("error occured, closing region client")
// we don't close c.rpcs channel to make it block in select of QueueRPC
// and avoid dealing with synchronization of closing it while someone
// might be sending to it. Go's GC will take care of it.
// tell goroutines to stop
close(c.done)
// close connection to the regionserver
// to let it know that we can't receive anymore
// and fail all the rpcs being sent
c.conn.Close()
c.failSentRPCs()
})
}
func (c *client) failSentRPCs() {
// channel is closed, clean up awaiting rpcs
c.sentM.Lock()
sent := c.sent
c.sent = make(map[uint32]hrpc.Call)
c.sentM.Unlock()
log.WithFields(log.Fields{
"client": c,
"count": len(sent),
}).Debug("failing awaiting RPCs")
// send error to awaiting rpcs
for _, rpc := range sent {
returnResult(rpc, nil, ErrClientDead)
}
}
func (c *client) registerRPC(rpc hrpc.Call) uint32 {
currID := atomic.AddUint32(&c.id, 1)
c.sentM.Lock()
c.sent[currID] = rpc
c.sentM.Unlock()
return currID
}
func (c *client) unregisterRPC(id uint32) hrpc.Call {
c.sentM.Lock()
rpc := c.sent[id]
delete(c.sent, id)
c.sentM.Unlock()
return rpc
}
func (c *client) processRPCs() {
// TODO: flush when the size is too large
// TODO: if multi has only one call, send that call instead
m := newMulti(c.rpcQueueSize)
defer func() {
m.returnResults(nil, ErrClientDead)
}()
flush := func() {
if log.GetLevel() == log.DebugLevel {
log.WithFields(log.Fields{
"len": m.len(),
"addr": c.Addr(),
}).Debug("flushing MultiRequest")
}
if err := c.trySend(m); err != nil {
m.returnResults(nil, err)
}
m = newMulti(c.rpcQueueSize)
}
for {
// first loop is to accomodate request heavy workload
// it will batch as long as conccurent writers are sending
// new rpcs or until multi is filled up
for {
select {
case <-c.done:
return
case rpc := <-c.rpcs:
// have things queued up, batch them
if !m.add(rpc) {
// can still put more rpcs into batch
continue
}
default:
// no more rpcs queued up
}
break
}
if l := m.len(); l == 0 {
// wait for the next batch
select {
case <-c.done:
return
case rpc := <-c.rpcs:
m.add(rpc)
}
continue
} else if l == c.rpcQueueSize || c.flushInterval == 0 {
// batch is full, flush
flush()
continue
}
// second loop is to accomodate less frequent callers
// that would like to maximize their batches at the expense
// of waiting for flushInteval
timer := time.NewTimer(c.flushInterval)
for {
select {
case <-c.done:
return
case <-timer.C:
// time to flush
case rpc := <-c.rpcs:
if !m.add(rpc) {
// can still put more rpcs into batch
continue
}
// batch is full
if !timer.Stop() {
<-timer.C
}
}
break
}
flush()
}
}
func returnResult(c hrpc.Call, msg proto.Message, err error) {
if m, ok := c.(*multi); ok {
m.returnResults(msg, err)
} else {
c.ResultChan() <- hrpc.RPCResult{Msg: msg, Error: err}
}
}
func (c *client) trySend(rpc hrpc.Call) error {
select {
case <-c.done:
// An unrecoverable error has occured,
// region client has been stopped,
// don't send rpcs
return ErrClientDead
case <-rpc.Context().Done():
// If the deadline has been exceeded, don't bother sending the
// request. The function that placed the RPC in our queue should
// stop waiting for a result and return an error.
return nil
default:
if id, err := c.send(rpc); err != nil {
if _, ok := err.(UnrecoverableError); ok {
c.fail(err)
}
if r := c.unregisterRPC(id); r != nil {
// we are the ones to unregister the rpc,
// return err to notify client of it
return err
}
}
return nil
}
}
func (c *client) receiveRPCs() {
for {
select {
case <-c.done:
return
default:
if err := c.receive(); err != nil {
switch err.(type) {
case UnrecoverableError:
c.fail(err)
return
case RetryableError:
continue
}
}
}
}
}
func (c *client) receive() (err error) {
var (
sz [4]byte
header pb.ResponseHeader
response proto.Message
)
err = c.readFully(sz[:])
if err != nil {
return UnrecoverableError{err}
}
size := binary.BigEndian.Uint32(sz[:])
b := make([]byte, size)
err = c.readFully(b)
if err != nil {
return UnrecoverableError{err}
}
buf := proto.NewBuffer(b)
if err = buf.DecodeMessage(&header); err != nil {
return fmt.Errorf("failed to decode the response header: %s", err)
}
if header.CallId == nil {
return ErrMissingCallID
}
callID := *header.CallId
rpc := c.unregisterRPC(callID)
if rpc == nil {
return fmt.Errorf("got a response with an unexpected call ID: %d", callID)
}
c.inFlightDown()
select {
case <-rpc.Context().Done():
// context has expired, don't bother deserializing
return
default:
}
// Here we know for sure that we got a response for rpc we asked.
// It's our responsibility to deliver the response or error to the
// caller as we unregistered the rpc.
defer func() { returnResult(rpc, response, err) }()
if header.Exception == nil {
response = rpc.NewResponse()
if err = buf.DecodeMessage(response); err != nil {
err = fmt.Errorf("failed to decode the response: %s", err)
return
}
var cellsLen uint32
if header.CellBlockMeta != nil {
cellsLen = header.CellBlockMeta.GetLength()
}
if d, ok := rpc.(canDeserializeCellBlocks); cellsLen > 0 && ok {
b := buf.Bytes()[size-cellsLen:]
var nread uint32
nread, err = d.DeserializeCellBlocks(response, b)
if err != nil {
err = fmt.Errorf("failed to decode the response: %s", err)
return
}
if int(nread) < len(b) {
err = fmt.Errorf("short read: buffer len %d, read %d", len(b), nread)
return
}
}
} else {
err = exceptionToError(*header.Exception.ExceptionClassName, *header.Exception.StackTrace)
}
return
}
func exceptionToError(class, stack string) error {
err := fmt.Errorf("HBase Java exception %s:\n%s", class, stack)
if _, ok := javaRetryableExceptions[class]; ok {
return RetryableError{err}
} else if _, ok := javaUnrecoverableExceptions[class]; ok {
return UnrecoverableError{err}
}
return err
}
// write sends the given buffer to the RegionServer.
func (c *client) write(buf []byte) error {
_, err := c.conn.Write(buf)
return err
}
// Tries to read enough data to fully fill up the given buffer.
func (c *client) readFully(buf []byte) error {
_, err := io.ReadFull(c.conn, buf)
return err
}
// sendHello sends the "hello" message needed when opening a new connection.
func (c *client) sendHello(ctype ClientType) error {
connHeader := &pb.ConnectionHeader{
UserInfo: &pb.UserInformation{
EffectiveUser: proto.String(c.effectiveUser),
},
ServiceName: proto.String(string(ctype)),
CellBlockCodecClass: proto.String("org.apache.hadoop.hbase.codec.KeyValueCodec"),
}
data, err := proto.Marshal(connHeader)
if err != nil {
return fmt.Errorf("failed to marshal connection header: %s", err)
}
const header = "HBas\x00\x50" // \x50 = Simple Auth.
buf := make([]byte, 0, len(header)+4+len(data))
buf = append(buf, header...)
buf = buf[:len(header)+4]
binary.BigEndian.PutUint32(buf[6:], uint32(len(data)))
buf = append(buf, data...)
return c.write(buf)
}
// send sends an RPC out to the wire.
// Returns the response (for now, as the call is synchronous).
func (c *client) send(rpc hrpc.Call) (uint32, error) {
b := newBuffer(4)
defer func() { freeBuffer(b) }()
buf := proto.NewBuffer(b[4:])
buf.Reset()
request := rpc.ToProto()
// we have to register rpc after we marhsal because
// registered rpc can fail before it was even sent
// in all the cases where c.fail() is called.
// If that happens, client can retry sending the rpc
// again potentially changing it's contents.
id := c.registerRPC(rpc)
header := &pb.RequestHeader{
CallId: &id,
MethodName: proto.String(rpc.Name()),
RequestParam: proto.Bool(true),
}
if err := buf.EncodeMessage(header); err != nil {
return id, fmt.Errorf("failed to marshal request header: %s", err)
}
if err := buf.EncodeMessage(request); err != nil {
return id, fmt.Errorf("failed to marshal request: %s", err)
}
payload := buf.Bytes()
binary.BigEndian.PutUint32(b, uint32(len(payload)))
b = append(b[:4], payload...)
if err := c.write(b); err != nil {
return id, UnrecoverableError{err}
}
c.inFlightUp()
return id, nil
}
|
LQJJ/demo
|
126-go-common-master/vendor/github.com/tsuna/gohbase/region/client.go
|
GO
|
apache-2.0
| 14,835
|
### `tf.reduce_logsumexp(input_tensor, reduction_indices=None, keep_dims=False, name=None)` {#reduce_logsumexp}
Computes log(sum(exp(elements across dimensions of a tensor))).
Reduces `input_tensor` along the dimensions given in `reduction_indices`.
Unless `keep_dims` is true, the rank of the tensor is reduced by 1 for each
entry in `reduction_indices`. If `keep_dims` is true, the reduced dimensions
are retained with length 1.
If `reduction_indices` has no entries, all dimensions are reduced, and a
tensor with a single element is returned.
This funciton is more numerically stable than log(sum(exp(input))). It avoids
overflows caused by taking the exp of large inputs and underflows caused by
taking the log of small inputs.
For example:
```python
# 'x' is [[0, 0, 0]]
# [0, 0, 0]]
tf.reduce_logsumexp(x) ==> log(6)
tf.reduce_logsumexp(x, 0) ==> [log(2), log(2), log(2)]
tf.reduce_logsumexp(x, 1) ==> [log(3), log(3)]
tf.reduce_logsumexp(x, 1, keep_dims=True) ==> [[log(3)], [log(3)]]
tf.reduce_logsumexp(x, [0, 1]) ==> log(6)
```
##### Args:
* <b>`input_tensor`</b>: The tensor to reduce. Should have numeric type.
* <b>`reduction_indices`</b>: The dimensions to reduce. If `None` (the defaut),
reduces all dimensions.
* <b>`keep_dims`</b>: If true, retains reduced dimensions with length 1.
* <b>`name`</b>: A name for the operation (optional).
##### Returns:
The reduced tensor.
|
naturali/tensorflow
|
tensorflow/g3doc/api_docs/python/functions_and_classes/shard1/tf.reduce_logsumexp.md
|
Markdown
|
apache-2.0
| 1,419
|
package com.android.coolweatherapp.gson;
import com.google.gson.annotations.SerializedName;
/**
* Created by Administrator on 2017/9/9 0009.
*/
public class Basic {
@SerializedName("city")
public String cityName;
@SerializedName("id")
public String weatherId;
public Update update;
public class Update{
@SerializedName("loc")
public String updateTime;
}
}
|
BryceCool/coolweather
|
app/src/main/java/com/android/coolweatherapp/gson/Basic.java
|
Java
|
apache-2.0
| 409
|
---
layout: post
title: CentOS系统利用yum源安装mongdb数据库
subtitle: 系统版本CentOS7
date: 2017-10-24
author: Los-GTI
header-img: img/post-bg-ios9-web.jpg
catalog: true
tags:
- CentOS
---
### CentOS系统下利用yum安装mongodb
##### 1.准备工作
打开终端输入:cd /etc/yum.repos.d/,查看自己的机器中的yum源中有没有包含mongodb的相关资源,我机器中的yum源信息如下图,没有mongodb的相关资源。

所以要在使用yum命令安装mongodb前增加yum源,也就是在 /etc/yum.repos.d/目录中增加 *.repo yum源配置文件,以下是针对centos 64位系统的MongoDB yum 源配置内容(32位系统略有不同):
我们这里就将该文件命名为:/etc/yum.repos.d/mongodb-3.4.repo
For 64-bit yum源配置:
vi /etc/yum.repos.d/mongodb-3.4.repo
```
[mongodb-org-3.4]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/3.4/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-3.4.asc
```

做好yum源的配置后,下面就可以执行相关命令安装mongodb及相关服务了。
##### 2.安装mongodb及相关服务
###### 2.1 安装mongodb
运行命令:yum -y install mongodb-org



> 出现complete说明安装成功。
###### 2.2 mongodb相关配置
运行命令:vi /etc/mongod.conf 查看修改相关配置

fork=true 允许程序在后台运行
logpath=/var/lib/mongod.log logappend=true 写日志的模式:设置为true为追加。默认是覆盖
dbpath=/var/lib/mongo数据存放目录
pidfilepath=/var/run/mongodb/mongod.pid 进程ID,没有指定则启动时候就没有PID文件。默认缺省。
port=27017,默认端口
> 存放日志和数据存放目录和端口等信息可以修改,我这边没有修改。
##### 3.运行mongodb
启动mongod :systemctl start mongod.service
>注意:外网访问需要关闭防火墙:
>
>CentOS 7.0默认使用的是firewall作为防火墙,这里改为iptables防火墙。
>
>关闭firewall:systemctl stop firewalld.service #停止firewall
>
>systemctl disable firewalld.service #禁止firewall开机启动
使用mongodb : mongo 127.0.0.1:27017


停止mongod :systemctl stop mongod,service
> 摁钉: author :Los-GTI
|
Los-GTI/Los-GTI.github.io
|
_posts/2017-10-24-CentOS系统下安装mongodb.md
|
Markdown
|
apache-2.0
| 3,048
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0-adoptopenjdk) on Tue Aug 07 14:38:46 CEST 2018 -->
<title>DefaultStepCondition (doov-core 2.1.0 API)</title>
<meta name="date" content="2018-08-07">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="DefaultStepCondition (doov-core 2.1.0 API)";
}
}
catch(err) {
}
//-->
var methods = {"i0":10,"i1":10,"i2":10,"i3":10};
var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../io/doov/core/dsl/impl/DefaultRuleRegistry.html" title="class in io.doov.core.dsl.impl"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../io/doov/core/dsl/impl/DefaultStepWhen.html" title="class in io.doov.core.dsl.impl"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?io/doov/core/dsl/impl/DefaultStepCondition.html" target="_top">Frames</a></li>
<li><a href="DefaultStepCondition.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">io.doov.core.dsl.impl</div>
<h2 title="Class DefaultStepCondition" class="title">Class DefaultStepCondition</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>io.doov.core.dsl.impl.DefaultStepCondition</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd><a href="../../../../../io/doov/core/dsl/lang/Readable.html" title="interface in io.doov.core.dsl.lang">Readable</a>, <a href="../../../../../io/doov/core/dsl/lang/StepCondition.html" title="interface in io.doov.core.dsl.lang">StepCondition</a>, <a href="../../../../../io/doov/core/dsl/meta/SyntaxTree.html" title="interface in io.doov.core.dsl.meta">SyntaxTree</a></dd>
</dl>
<hr>
<br>
<pre>public class <span class="typeNameLabel">DefaultStepCondition</span>
extends java.lang.Object</pre>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../io/doov/core/dsl/impl/DefaultStepCondition.html#DefaultStepCondition-io.doov.core.dsl.meta.PredicateMetadata-java.util.function.BiPredicate-">DefaultStepCondition</a></span>(<a href="../../../../../io/doov/core/dsl/meta/PredicateMetadata.html" title="class in io.doov.core.dsl.meta">PredicateMetadata</a> metadata,
java.util.function.BiPredicate<<a href="../../../../../io/doov/core/dsl/DslModel.html" title="interface in io.doov.core.dsl">DslModel</a>,<a href="../../../../../io/doov/core/dsl/lang/Context.html" title="interface in io.doov.core.dsl.lang">Context</a>> predicate)</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../io/doov/core/dsl/impl/DefaultStepCondition.html#accept-io.doov.core.dsl.meta.MetadataVisitor-int-">accept</a></span>(<a href="../../../../../io/doov/core/dsl/meta/MetadataVisitor.html" title="interface in io.doov.core.dsl.meta">MetadataVisitor</a> visitor,
int depth)</code> </td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code><a href="../../../../../io/doov/core/dsl/meta/Metadata.html" title="interface in io.doov.core.dsl.meta">Metadata</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../io/doov/core/dsl/impl/DefaultStepCondition.html#getMetadata--">getMetadata</a></span>()</code>
<div class="block">Returns the metadata to describe this node.</div>
</td>
</tr>
<tr id="i2" class="altColor">
<td class="colFirst"><code>java.util.function.BiPredicate<<a href="../../../../../io/doov/core/dsl/DslModel.html" title="interface in io.doov.core.dsl">DslModel</a>,<a href="../../../../../io/doov/core/dsl/lang/Context.html" title="interface in io.doov.core.dsl.lang">Context</a>></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../io/doov/core/dsl/impl/DefaultStepCondition.html#predicate--">predicate</a></span>()</code>
<div class="block">Returns the predicate for this node value.</div>
</td>
</tr>
<tr id="i3" class="rowColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../io/doov/core/dsl/impl/DefaultStepCondition.html#readable-java.util.Locale-">readable</a></span>(java.util.Locale locale)</code>
<div class="block">Returns the human readable version of this object.</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.io.doov.core.dsl.lang.StepCondition">
<!-- -->
</a>
<h3>Methods inherited from interface io.doov.core.dsl.lang.<a href="../../../../../io/doov/core/dsl/lang/StepCondition.html" title="interface in io.doov.core.dsl.lang">StepCondition</a></h3>
<code><a href="../../../../../io/doov/core/dsl/lang/StepCondition.html#and-io.doov.core.dsl.lang.StepCondition-">and</a>, <a href="../../../../../io/doov/core/dsl/lang/StepCondition.html#not--">not</a>, <a href="../../../../../io/doov/core/dsl/lang/StepCondition.html#or-io.doov.core.dsl.lang.StepCondition-">or</a></code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.io.doov.core.dsl.meta.SyntaxTree">
<!-- -->
</a>
<h3>Methods inherited from interface io.doov.core.dsl.meta.<a href="../../../../../io/doov/core/dsl/meta/SyntaxTree.html" title="interface in io.doov.core.dsl.meta">SyntaxTree</a></h3>
<code><a href="../../../../../io/doov/core/dsl/meta/SyntaxTree.html#markdown--">markdown</a>, <a href="../../../../../io/doov/core/dsl/meta/SyntaxTree.html#markdown-java.util.Locale-">markdown</a>, <a href="../../../../../io/doov/core/dsl/meta/SyntaxTree.html#readable--">readable</a></code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="DefaultStepCondition-io.doov.core.dsl.meta.PredicateMetadata-java.util.function.BiPredicate-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>DefaultStepCondition</h4>
<pre>public DefaultStepCondition(<a href="../../../../../io/doov/core/dsl/meta/PredicateMetadata.html" title="class in io.doov.core.dsl.meta">PredicateMetadata</a> metadata,
java.util.function.BiPredicate<<a href="../../../../../io/doov/core/dsl/DslModel.html" title="interface in io.doov.core.dsl">DslModel</a>,<a href="../../../../../io/doov/core/dsl/lang/Context.html" title="interface in io.doov.core.dsl.lang">Context</a>> predicate)</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="getMetadata--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getMetadata</h4>
<pre>public <a href="../../../../../io/doov/core/dsl/meta/Metadata.html" title="interface in io.doov.core.dsl.meta">Metadata</a> getMetadata()</pre>
<div class="block"><span class="descfrmTypeLabel">Description copied from interface: <code><a href="../../../../../io/doov/core/dsl/lang/StepCondition.html#getMetadata--">StepCondition</a></code></span></div>
<div class="block">Returns the metadata to describe this node.</div>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code><a href="../../../../../io/doov/core/dsl/lang/StepCondition.html#getMetadata--">getMetadata</a></code> in interface <code><a href="../../../../../io/doov/core/dsl/lang/StepCondition.html" title="interface in io.doov.core.dsl.lang">StepCondition</a></code></dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>the metadata</dd>
</dl>
</li>
</ul>
<a name="predicate--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>predicate</h4>
<pre>public java.util.function.BiPredicate<<a href="../../../../../io/doov/core/dsl/DslModel.html" title="interface in io.doov.core.dsl">DslModel</a>,<a href="../../../../../io/doov/core/dsl/lang/Context.html" title="interface in io.doov.core.dsl.lang">Context</a>> predicate()</pre>
<div class="block"><span class="descfrmTypeLabel">Description copied from interface: <code><a href="../../../../../io/doov/core/dsl/lang/StepCondition.html#predicate--">StepCondition</a></code></span></div>
<div class="block">Returns the predicate for this node value.</div>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code><a href="../../../../../io/doov/core/dsl/lang/StepCondition.html#predicate--">predicate</a></code> in interface <code><a href="../../../../../io/doov/core/dsl/lang/StepCondition.html" title="interface in io.doov.core.dsl.lang">StepCondition</a></code></dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>the predicate</dd>
</dl>
</li>
</ul>
<a name="readable-java.util.Locale-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>readable</h4>
<pre>public java.lang.String readable(java.util.Locale locale)</pre>
<div class="block"><span class="descfrmTypeLabel">Description copied from interface: <code><a href="../../../../../io/doov/core/dsl/meta/SyntaxTree.html#readable-java.util.Locale-">SyntaxTree</a></code></span></div>
<div class="block">Returns the human readable version of this object.</div>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code><a href="../../../../../io/doov/core/dsl/meta/SyntaxTree.html#readable-java.util.Locale-">readable</a></code> in interface <code><a href="../../../../../io/doov/core/dsl/meta/SyntaxTree.html" title="interface in io.doov.core.dsl.meta">SyntaxTree</a></code></dd>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>locale</code> - the locale to use</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>the readable string</dd>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="../../../../../io/doov/core/dsl/meta/SyntaxTree.html#readable--"><code>SyntaxTree.readable()</code></a></dd>
</dl>
</li>
</ul>
<a name="accept-io.doov.core.dsl.meta.MetadataVisitor-int-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>accept</h4>
<pre>public void accept(<a href="../../../../../io/doov/core/dsl/meta/MetadataVisitor.html" title="interface in io.doov.core.dsl.meta">MetadataVisitor</a> visitor,
int depth)</pre>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code><a href="../../../../../io/doov/core/dsl/meta/SyntaxTree.html#accept-io.doov.core.dsl.meta.MetadataVisitor-int-">accept</a></code> in interface <code><a href="../../../../../io/doov/core/dsl/meta/SyntaxTree.html" title="interface in io.doov.core.dsl.meta">SyntaxTree</a></code></dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../io/doov/core/dsl/impl/DefaultRuleRegistry.html" title="class in io.doov.core.dsl.impl"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../io/doov/core/dsl/impl/DefaultStepWhen.html" title="class in io.doov.core.dsl.impl"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?io/doov/core/dsl/impl/DefaultStepCondition.html" target="_top">Frames</a></li>
<li><a href="DefaultStepCondition.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
lesfurets/dOOv
|
docs/site/core/apidocs/io/doov/core/dsl/impl/DefaultStepCondition.html
|
HTML
|
apache-2.0
| 17,511
|
<?php
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/ads/googleads/v8/resources/recommendation.proto
namespace Google\Ads\GoogleAds\V8\Resources;
if (false) {
/**
* This class is deprecated. Use Google\Ads\GoogleAds\V8\Resources\Recommendation\SearchPartnersOptInRecommendation instead.
* @deprecated
*/
class Recommendation_SearchPartnersOptInRecommendation {}
}
class_exists(Recommendation\SearchPartnersOptInRecommendation::class);
@trigger_error('Google\Ads\GoogleAds\V8\Resources\Recommendation_SearchPartnersOptInRecommendation is deprecated and will be removed in the next major release. Use Google\Ads\GoogleAds\V8\Resources\Recommendation\SearchPartnersOptInRecommendation instead', E_USER_DEPRECATED);
|
googleads/google-ads-php
|
src/Google/Ads/GoogleAds/V8/Resources/Recommendation_SearchPartnersOptInRecommendation.php
|
PHP
|
apache-2.0
| 767
|
package org.ulasalle.compiler.syntax.analizer;
import org.ulasalle.compiler.util.Simbolo;
public class Temporal
{
private Simbolo simbolo;
public Simbolo getSimbolo()
{
return simbolo;
}
public void setSimbolo(Simbolo simbolo)
{
this.simbolo = simbolo;
}
}
|
rodrigomendozamelgar/compiler
|
src/main/java/org/ulasalle/compiler/syntax/analizer/Temporal.java
|
Java
|
apache-2.0
| 315
|
#!/usr/bin/env python
# Copyright 2014, Rackspace US, 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 optparse
import subprocess
from maas_common import metric
from maas_common import metric_bool
from maas_common import print_output
from maas_common import status_err
from maas_common import status_ok
import requests
OVERVIEW_URL = "http://%s:%s/api/overview"
NODES_URL = "http://%s:%s/api/nodes"
CONNECTIONS_URL = "http://%s:%s/api/connections?columns=channels"
QUEUES_URL = "http://%s:%s/api/queues"
CLUSTERED = True
CLUSTER_SIZE = 3
# {metric_category: {metric_name: metric_unit}}
OVERVIEW_METRICS = {"queue_totals": {"messages": "messages",
"messages_ready": "messages",
"messages_unacknowledged": "messages"},
"message_stats": {"get": "messages",
"ack": "messages",
"deliver_get": "messages",
"deliver": "messages",
"publish": "messages"}}
# {metric_name: metric_unit}
NODES_METRICS = {"proc_used": "processes",
"proc_total": "processes",
"fd_used": "fd",
"fd_total": "fd",
"sockets_used": "fd",
"sockets_total": "fd",
"mem_used": "bytes",
"mem_limit": "bytes",
"mem_alarm": "status",
"disk_free_alarm": "status",
"uptime": "ms"}
CONNECTIONS_METRICS = {"max_channels_per_conn": "channels"}
def hostname():
"""Return the name of the current host/node."""
return subprocess.check_output(['hostname', '-s']).strip()
def rabbit_version(node):
if ('applications' in node and 'rabbit' in node['applications']
and 'version' in node['applications']['rabbit']):
version_string = node['applications']['rabbit']['version']
return tuple(int(part) for part in version_string.split('.'))
else:
return tuple()
def parse_args():
parser = optparse.OptionParser(
usage='%prog [-h] [-H hostname] [-P port] [-u username] [-p password]'
)
parser.add_option('-H', '--host', action='store', dest='host',
default='localhost',
help='Host address to use when connecting')
parser.add_option('-P', '--port', action='store', dest='port',
default='15672',
help='Port to use when connecting')
parser.add_option('-U', '--username', action='store', dest='username',
default='guest',
help='Username to use for authentication')
parser.add_option('-p', '--password', action='store', dest='password',
default='guest',
help='Password to use for authentication')
parser.add_option('-n', '--name', action='store', dest='name',
default=None,
help=("Check a node's cluster membership using the "
'provided name'))
return parser.parse_args()
def _get_rabbit_json(session, url):
try:
response = session.get(url)
except requests.exceptions.ConnectionError as e:
status_err(str(e))
if response.ok:
return response.json()
else:
status_err('Received status {0} from RabbitMQ API'.format(
response.status_code))
def _get_connection_metrics(session, metrics, host, port):
response = _get_rabbit_json(session, CONNECTIONS_URL % (host, port))
max_chans = max(connection['channels'] for connection in response
if 'channels' in connection)
for k in CONNECTIONS_METRICS:
metrics[k] = {'value': max_chans, 'unit': CONNECTIONS_METRICS[k]}
def _get_overview_metrics(session, metrics, host, port):
response = _get_rabbit_json(session, OVERVIEW_URL % (host, port))
for k in OVERVIEW_METRICS:
if k in response:
for a, b in OVERVIEW_METRICS[k].items():
if a in response[k]:
metrics[a] = {'value': response[k][a], 'unit': b}
def _get_node_metrics(session, metrics, host, port, name):
response = _get_rabbit_json(session, NODES_URL % (host, port))
# Either use the option provided by the commandline flag or the current
# hostname
name = '@' + (name or hostname())
is_cluster_member = False
# Ensure this node is a member of the cluster
nodes_matching_name = [n for n in response
if n['name'].endswith(name)]
is_cluster_member = any(nodes_matching_name)
if CLUSTERED:
if len(response) < CLUSTER_SIZE:
status_err('cluster too small')
if not is_cluster_member:
status_err('{0} not a member of the cluster'.format(name))
for k, v in NODES_METRICS.items():
metrics[k] = {'value': nodes_matching_name[0][k], 'unit': v}
# We don't know exactly which version introduces data for all
# nodes in the cluster returned by the NODES_URL, but we know it is
# in 3.5.x at least.
if rabbit_version(nodes_matching_name[0]) > (3, 5):
# Gather the queue lengths for all nodes in the cluster
queues = [n['run_queue'] for n in response
if n.get('run_queue', None)]
# Grab the first queue length
first = queues.pop()
# Check that all other queues are equal to it
if not all(first == q for q in queues):
# If they're not, the queues are not synchronized
status_err('Cluster not replicated across all nodes')
def _get_queue_metrics(session, metrics, host, port):
response = _get_rabbit_json(session, QUEUES_URL % (host, port))
notification_messages = sum([q['messages'] for q in response
if q['name'].startswith('notifications.')])
metrics['notification_messages'] = {
'value': notification_messages,
'unit': 'messages'
}
metrics['msgs_excl_notifications'] = {
'value': metrics['messages']['value'] - notification_messages,
'unit': 'messages'
}
def main():
(options, _) = parse_args()
metrics = {}
session = requests.Session() # Make a Session to store the auth creds
session.auth = (options.username, options.password)
_get_connection_metrics(session, metrics, options.host, options.port)
_get_overview_metrics(session, metrics, options.host, options.port)
_get_node_metrics(session, metrics, options.host, options.port,
options.name)
_get_queue_metrics(session, metrics, options.host, options.port)
status_ok()
for k, v in metrics.items():
if v['value'] is True or v['value'] is False:
metric_bool('rabbitmq_%s_status' % k, not v['value'])
else:
metric('rabbitmq_%s' % k, 'int64', v['value'], v['unit'])
if __name__ == "__main__":
with print_output():
main()
|
stevelle/rpc-openstack
|
maas/plugins/rabbitmq_status.py
|
Python
|
apache-2.0
| 7,579
|
package com.google.gwt.sample.stockwatcher.uibinder.client;
import com.google.gwt.inject.client.AbstractGinModule;
import com.google.inject.Singleton;
public class StockWatcherWidgetClientModule extends AbstractGinModule {
@Override
protected void configure() {
bind(StockWatcherWidget.class).in(Singleton.class);
}
}
|
burniegu/gwtproject
|
UiBinder/StockWatcherUiBinder/src/com/google/gwt/sample/stockwatcher/uibinder/client/StockWatcherWidgetClientModule.java
|
Java
|
apache-2.0
| 326
|
/*
* Copyright 2015 agwlvssainokuni
*
* 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 cherry.foundation.testtool.invoker;
import static java.text.MessageFormat.format;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import cherry.foundation.testtool.reflect.ReflectionResolver;
import cherry.goods.util.ToMapUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
public class InvokerServiceImpl implements InvokerService {
private ReflectionResolver reflectionResolver;
private Invoker invoker;
private ObjectMapper objectMapper;
public void setReflectionResolver(ReflectionResolver reflectionResolver) {
this.reflectionResolver = reflectionResolver;
}
public void setInvoker(Invoker invoker) {
this.invoker = invoker;
}
public void setObjectMapper(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
@Override
public List<String> resolveBeanName(String className) {
try {
return reflectionResolver.resolveBeanName(className);
} catch (ClassNotFoundException ex) {
return new ArrayList<>();
}
}
@Override
public List<Method> resolveMethod(String className, String methodName) {
try {
return reflectionResolver.resolveMethod(className, methodName);
} catch (ClassNotFoundException ex) {
return new ArrayList<>();
}
}
@Override
public String invoke(String beanName, String className, String methodName, int methodIndex, String args,
String argTypes) {
try {
Class<?> beanClass = getClass().getClassLoader().loadClass(className);
List<Method> methodList = reflectionResolver.resolveMethod(beanClass, methodName);
if (methodList.isEmpty()) {
throw new NoSuchMethodException(format("{0}#{1}() not found", className, methodName));
}
Method method = (methodList.size() == 1 ? methodList.get(0) : methodList.get(methodIndex));
return invoker.invoke(beanName, beanClass, method, resolveArgs(args), resolveArgTypes(argTypes));
} catch (ClassNotFoundException | NoSuchMethodException ex) {
return fromThrowableToString(ex);
} catch (IOException ex) {
return fromThrowableToString(ex);
} catch (IllegalStateException ex) {
if (ex.getCause() instanceof InvocationTargetException || ex.getCause() instanceof IllegalAccessException
|| ex.getCause() instanceof IOException) {
return fromThrowableToString(ex.getCause());
} else {
return fromThrowableToString(ex);
}
} catch (Exception ex) {
return fromThrowableToString(ex);
}
}
private List<String> resolveArgs(String param) throws JsonProcessingException, IOException {
if (StringUtils.isEmpty(param)) {
return null;
}
List<String> list = new ArrayList<>();
for (Object value : objectMapper.readValue(param, List.class)) {
list.add(objectMapper.writeValueAsString(value));
}
return list;
}
private List<String> resolveArgTypes(String param) throws JsonProcessingException, IOException {
if (StringUtils.isEmpty(param)) {
return null;
}
return objectMapper.readValue(param, new TypeReference<List<String>>() {
});
}
private String fromThrowableToString(Throwable ex) {
Map<String, ?> map = ToMapUtil.fromThrowable(ex, Integer.MAX_VALUE);
try {
return objectMapper.writeValueAsString(map);
} catch (IOException ex2) {
return ex.getMessage();
}
}
}
|
agwlvssainokuni/springapp
|
foundation/src/main/java/cherry/foundation/testtool/invoker/InvokerServiceImpl.java
|
Java
|
apache-2.0
| 4,234
|
/*
* Copyright 2020 Hazelcast Inc.
*
* Licensed under the Hazelcast Community License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://hazelcast.com/hazelcast-community-license
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.jet.hadoop.file;
import com.hazelcast.function.ConsumerEx;
import com.hazelcast.jet.JetException;
import com.hazelcast.jet.JetInstance;
import com.hazelcast.jet.hadoop.impl.HadoopTestSupport;
import com.hazelcast.jet.pipeline.Pipeline;
import com.hazelcast.jet.pipeline.Sinks;
import com.hazelcast.jet.pipeline.file.FileSourceBuilder;
import com.hazelcast.jet.pipeline.test.Assertions;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@RunWith(Parameterized.class)
public abstract class BaseFileFormatTest extends HadoopTestSupport {
@Parameter
public boolean useHadoop;
protected String currentDir;
@Parameters(name = "{index}: useHadoop={0}")
public static Iterable<?> parameters() {
return Arrays.asList(true, false);
}
@Override
protected boolean useHadoop() {
return useHadoop;
}
@Before
public void setUp() {
currentDir = Paths.get(".").toAbsolutePath().normalize().toString();
}
@SafeVarargs
protected final <T> void assertItemsInSource(FileSourceBuilder<T> source, T... items) {
assertItemsInSource(source, collected -> assertThat(collected).containsOnly(items));
}
protected <T> void assertItemsInSource(
FileSourceBuilder<T> source, ConsumerEx<List<T>> assertion
) {
assertItemsInSource(1, source, assertion);
}
protected <T> void assertItemsInSource(
int memberCount, FileSourceBuilder<T> source, ConsumerEx<List<T>> assertion
) {
if (useHadoop) {
source.useHadoopForLocalFiles(true);
}
Pipeline p = Pipeline.create();
p.readFrom(source.build())
.apply(Assertions.assertCollected(assertion));
JetInstance[] jets = createJetMembers(memberCount);
try {
jets[0].newJob(p).join();
} finally {
for (JetInstance jet : jets) {
jet.shutdown();
}
}
}
protected void assertJobFailed(
FileSourceBuilder<?> source,
Class<? extends Throwable> expectedRootException,
String expectedMessage
) {
if (useHadoop) {
source.useHadoopForLocalFiles(true);
}
Pipeline p = Pipeline.create();
p.readFrom(source.build())
.writeTo(Sinks.logger());
JetInstance[] jets = createJetMembers(1);
try {
assertThatThrownBy(() -> jets[0].newJob(p).join())
.hasCauseInstanceOf(JetException.class)
.hasRootCauseInstanceOf(expectedRootException)
.hasMessageContaining(expectedMessage);
} finally {
for (JetInstance jet : jets) {
jet.shutdown();
}
}
}
}
|
gurbuzali/hazelcast-jet
|
extensions/hadoop/src/test/java/com/hazelcast/jet/hadoop/file/BaseFileFormatTest.java
|
Java
|
apache-2.0
| 3,734
|
using System;
using BuildAProject.BuildManagement.BuildManagers.Definitions;
using BuildAProject.BuildManagement.BuildManagers.TaskManagers;
using BuildAProject.BuildManagement.Test.TestSupport.Builders;
using Moq;
using NUnit.Framework;
using Ploeh.AutoFixture;
using Ploeh.AutoFixture.AutoMoq;
using Ploeh.AutoFixture.Idioms;
namespace BuildAProject.BuildManagement.Test.BuildManagers.TaskManagers
{
[TestFixture]
public sealed class BuildTaskProviderManagerTests
{
private readonly MockRepository mockRepository = new MockRepository(MockBehavior.Loose);
[Test]
public void BuildTaskProviderManager_AllParameters_DoNotAcceptNull()
{
// Arrange
var fixture = new Fixture()
.Customize(new AutoMoqCustomization());
var assertion = new GuardClauseAssertion(fixture);
// Act + Assert
assertion.Verify(typeof(BuildTaskProviderManager).GetConstructors());
}
[Test]
public void BuildTaskProviderManager_TaskProviderParameterIsEmpty_ThrowsError()
{
// Arrange + Act + Assert
Assert.Throws<ArgumentException>(() => new BuildTaskProviderManagerBuilder { TaskProviders = new IBuildTaskProvider[0] }.Build());
}
[Test]
public void GetTasks_FromProvidedProjects_AndReturnedWithCorrectPhases()
{
// Arrange
var fakeTask1 = mockRepository.Create<IBuildTask>();
var fakeTask2 = mockRepository.Create<IBuildTask>();
var fakeTask3 = mockRepository.Create<IBuildTask>();
var expectedResult = new[]
{
fakeTask1.Object,
fakeTask2.Object,
fakeTask3.Object
};
var projects = new[]
{
mockRepository.Create<IProject>().Object,
mockRepository.Create<IProject>().Object
};
var fakeTaskProvider1 = mockRepository.Create<IBuildTaskProvider>();
fakeTaskProvider1
.Setup(provider => provider.GetTasks(projects))
.Returns(new[] { fakeTask1.Object, fakeTask2.Object });
var fakeTaskProvider2 = mockRepository.Create<IBuildTaskProvider>();
fakeTaskProvider2
.Setup(provider => provider.GetTasks(projects))
.Returns(new[] { fakeTask3.Object });
var manager = new BuildTaskProviderManager(
new[]
{
fakeTaskProvider1.Object,
fakeTaskProvider2.Object
});
// Act
var actualResult = manager.GetTasks(projects);
// Assert
Assert.AreEqual(expectedResult, actualResult);
}
}
}
|
kristianhald/BuildAProject
|
BuildManagement.Test/BuildManagers/TaskManagers/BuildTaskProviderManagerTests.cs
|
C#
|
apache-2.0
| 2,656
|
/*
Copyright 2014 The Kubernetes Authors 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.
*/
package aws_ebs
import (
"fmt"
"os"
"path"
"testing"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/api/resource"
"k8s.io/kubernetes/pkg/client/unversioned/testclient"
"k8s.io/kubernetes/pkg/types"
"k8s.io/kubernetes/pkg/util/mount"
utiltesting "k8s.io/kubernetes/pkg/util/testing"
"k8s.io/kubernetes/pkg/volume"
)
func TestCanSupport(t *testing.T) {
tmpDir, err := utiltesting.MkTmpdir("awsebsTest")
if err != nil {
t.Fatalf("can't make a temp dir: %v", err)
}
defer os.RemoveAll(tmpDir)
plugMgr := volume.VolumePluginMgr{}
plugMgr.InitPlugins(ProbeVolumePlugins(), volume.NewFakeVolumeHost(tmpDir, nil, nil))
plug, err := plugMgr.FindPluginByName("kubernetes.io/aws-ebs")
if err != nil {
t.Errorf("Can't find the plugin by name")
}
if plug.Name() != "kubernetes.io/aws-ebs" {
t.Errorf("Wrong name: %s", plug.Name())
}
if !plug.CanSupport(&volume.Spec{Volume: &api.Volume{VolumeSource: api.VolumeSource{AWSElasticBlockStore: &api.AWSElasticBlockStoreVolumeSource{}}}}) {
t.Errorf("Expected true")
}
if !plug.CanSupport(&volume.Spec{PersistentVolume: &api.PersistentVolume{Spec: api.PersistentVolumeSpec{PersistentVolumeSource: api.PersistentVolumeSource{AWSElasticBlockStore: &api.AWSElasticBlockStoreVolumeSource{}}}}}) {
t.Errorf("Expected true")
}
}
func TestGetAccessModes(t *testing.T) {
tmpDir, err := utiltesting.MkTmpdir("awsebsTest")
if err != nil {
t.Fatalf("can't make a temp dir: %v", err)
}
defer os.RemoveAll(tmpDir)
plugMgr := volume.VolumePluginMgr{}
plugMgr.InitPlugins(ProbeVolumePlugins(), volume.NewFakeVolumeHost(tmpDir, nil, nil))
plug, err := plugMgr.FindPersistentPluginByName("kubernetes.io/aws-ebs")
if err != nil {
t.Errorf("Can't find the plugin by name")
}
if !contains(plug.GetAccessModes(), api.ReadWriteOnce) {
t.Errorf("Expected to find AccessMode: %s", api.ReadWriteOnce)
}
if len(plug.GetAccessModes()) != 1 {
t.Errorf("Expected to find exactly one AccessMode")
}
}
func contains(modes []api.PersistentVolumeAccessMode, mode api.PersistentVolumeAccessMode) bool {
for _, m := range modes {
if m == mode {
return true
}
}
return false
}
type fakePDManager struct{}
// TODO(jonesdl) To fully test this, we could create a loopback device
// and mount that instead.
func (fake *fakePDManager) AttachAndMountDisk(b *awsElasticBlockStoreBuilder, globalPDPath string) error {
globalPath := makeGlobalPDPath(b.plugin.host, b.volumeID)
err := os.MkdirAll(globalPath, 0750)
if err != nil {
return err
}
return nil
}
func (fake *fakePDManager) DetachDisk(c *awsElasticBlockStoreCleaner) error {
globalPath := makeGlobalPDPath(c.plugin.host, c.volumeID)
err := os.RemoveAll(globalPath)
if err != nil {
return err
}
return nil
}
func (fake *fakePDManager) CreateVolume(c *awsElasticBlockStoreProvisioner) (volumeID string, volumeSizeGB int, err error) {
return "test-aws-volume-name", 100, nil
}
func (fake *fakePDManager) DeleteVolume(cd *awsElasticBlockStoreDeleter) error {
if cd.volumeID != "test-aws-volume-name" {
return fmt.Errorf("Deleter got unexpected volume name: %s", cd.volumeID)
}
return nil
}
func TestPlugin(t *testing.T) {
tmpDir, err := utiltesting.MkTmpdir("awsebsTest")
if err != nil {
t.Fatalf("can't make a temp dir: %v")
}
defer os.RemoveAll(tmpDir)
plugMgr := volume.VolumePluginMgr{}
plugMgr.InitPlugins(ProbeVolumePlugins(), volume.NewFakeVolumeHost(tmpDir, nil, nil))
plug, err := plugMgr.FindPluginByName("kubernetes.io/aws-ebs")
if err != nil {
t.Errorf("Can't find the plugin by name")
}
spec := &api.Volume{
Name: "vol1",
VolumeSource: api.VolumeSource{
AWSElasticBlockStore: &api.AWSElasticBlockStoreVolumeSource{
VolumeID: "pd",
FSType: "ext4",
},
},
}
builder, err := plug.(*awsElasticBlockStorePlugin).newBuilderInternal(volume.NewSpecFromVolume(spec), types.UID("poduid"), &fakePDManager{}, &mount.FakeMounter{})
if err != nil {
t.Errorf("Failed to make a new Builder: %v", err)
}
if builder == nil {
t.Errorf("Got a nil Builder")
}
volPath := path.Join(tmpDir, "pods/poduid/volumes/kubernetes.io~aws-ebs/vol1")
path := builder.GetPath()
if path != volPath {
t.Errorf("Got unexpected path: %s", path)
}
if err := builder.SetUp(nil); err != nil {
t.Errorf("Expected success, got: %v", err)
}
if _, err := os.Stat(path); err != nil {
if os.IsNotExist(err) {
t.Errorf("SetUp() failed, volume path not created: %s", path)
} else {
t.Errorf("SetUp() failed: %v", err)
}
}
if _, err := os.Stat(path); err != nil {
if os.IsNotExist(err) {
t.Errorf("SetUp() failed, volume path not created: %s", path)
} else {
t.Errorf("SetUp() failed: %v", err)
}
}
cleaner, err := plug.(*awsElasticBlockStorePlugin).newCleanerInternal("vol1", types.UID("poduid"), &fakePDManager{}, &mount.FakeMounter{})
if err != nil {
t.Errorf("Failed to make a new Cleaner: %v", err)
}
if cleaner == nil {
t.Errorf("Got a nil Cleaner")
}
if err := cleaner.TearDown(); err != nil {
t.Errorf("Expected success, got: %v", err)
}
if _, err := os.Stat(path); err == nil {
t.Errorf("TearDown() failed, volume path still exists: %s", path)
} else if !os.IsNotExist(err) {
t.Errorf("SetUp() failed: %v", err)
}
// Test Provisioner
cap := resource.MustParse("100Gi")
options := volume.VolumeOptions{
Capacity: cap,
AccessModes: []api.PersistentVolumeAccessMode{
api.ReadWriteOnce,
},
PersistentVolumeReclaimPolicy: api.PersistentVolumeReclaimDelete,
}
provisioner, err := plug.(*awsElasticBlockStorePlugin).newProvisionerInternal(options, &fakePDManager{})
persistentSpec, err := provisioner.NewPersistentVolumeTemplate()
if err != nil {
t.Errorf("NewPersistentVolumeTemplate() failed: %v", err)
}
// get 2nd Provisioner - persistent volume controller will do the same
provisioner, err = plug.(*awsElasticBlockStorePlugin).newProvisionerInternal(options, &fakePDManager{})
err = provisioner.Provision(persistentSpec)
if err != nil {
t.Errorf("Provision() failed: %v", err)
}
if persistentSpec.Spec.PersistentVolumeSource.AWSElasticBlockStore.VolumeID != "test-aws-volume-name" {
t.Errorf("Provision() returned unexpected volume ID: %s", persistentSpec.Spec.PersistentVolumeSource.AWSElasticBlockStore.VolumeID)
}
cap = persistentSpec.Spec.Capacity[api.ResourceStorage]
size := cap.Value()
if size != 100*1024*1024*1024 {
t.Errorf("Provision() returned unexpected volume size: %v", size)
}
// Test Deleter
volSpec := &volume.Spec{
PersistentVolume: persistentSpec,
}
deleter, err := plug.(*awsElasticBlockStorePlugin).newDeleterInternal(volSpec, &fakePDManager{})
err = deleter.Delete()
if err != nil {
t.Errorf("Deleter() failed: %v", err)
}
}
func TestPersistentClaimReadOnlyFlag(t *testing.T) {
pv := &api.PersistentVolume{
ObjectMeta: api.ObjectMeta{
Name: "pvA",
},
Spec: api.PersistentVolumeSpec{
PersistentVolumeSource: api.PersistentVolumeSource{
AWSElasticBlockStore: &api.AWSElasticBlockStoreVolumeSource{},
},
ClaimRef: &api.ObjectReference{
Name: "claimA",
},
},
}
claim := &api.PersistentVolumeClaim{
ObjectMeta: api.ObjectMeta{
Name: "claimA",
Namespace: "nsA",
},
Spec: api.PersistentVolumeClaimSpec{
VolumeName: "pvA",
},
Status: api.PersistentVolumeClaimStatus{
Phase: api.ClaimBound,
},
}
client := testclient.NewSimpleFake(pv, claim)
tmpDir, err := utiltesting.MkTmpdir("awsebsTest")
if err != nil {
t.Fatalf("can't make a temp dir: %v", err)
}
defer os.RemoveAll(tmpDir)
plugMgr := volume.VolumePluginMgr{}
plugMgr.InitPlugins(ProbeVolumePlugins(), volume.NewFakeVolumeHost(tmpDir, client, nil))
plug, _ := plugMgr.FindPluginByName(awsElasticBlockStorePluginName)
// readOnly bool is supplied by persistent-claim volume source when its builder creates other volumes
spec := volume.NewSpecFromPersistentVolume(pv, true)
pod := &api.Pod{ObjectMeta: api.ObjectMeta{UID: types.UID("poduid")}}
builder, _ := plug.NewBuilder(spec, pod, volume.VolumeOptions{})
if !builder.GetAttributes().ReadOnly {
t.Errorf("Expected true for builder.IsReadOnly")
}
}
func TestBuilderAndCleanerTypeAssert(t *testing.T) {
tmpDir, err := utiltesting.MkTmpdir("awsebsTest")
if err != nil {
t.Fatalf("can't make a temp dir: %v", err)
}
defer os.RemoveAll(tmpDir)
plugMgr := volume.VolumePluginMgr{}
plugMgr.InitPlugins(ProbeVolumePlugins(), volume.NewFakeVolumeHost(tmpDir, nil, nil))
plug, err := plugMgr.FindPluginByName("kubernetes.io/aws-ebs")
if err != nil {
t.Errorf("Can't find the plugin by name")
}
spec := &api.Volume{
Name: "vol1",
VolumeSource: api.VolumeSource{
AWSElasticBlockStore: &api.AWSElasticBlockStoreVolumeSource{
VolumeID: "pd",
FSType: "ext4",
},
},
}
builder, err := plug.(*awsElasticBlockStorePlugin).newBuilderInternal(volume.NewSpecFromVolume(spec), types.UID("poduid"), &fakePDManager{}, &mount.FakeMounter{})
if _, ok := builder.(volume.Cleaner); ok {
t.Errorf("Volume Builder can be type-assert to Cleaner")
}
cleaner, err := plug.(*awsElasticBlockStorePlugin).newCleanerInternal("vol1", types.UID("poduid"), &fakePDManager{}, &mount.FakeMounter{})
if _, ok := cleaner.(volume.Builder); ok {
t.Errorf("Volume Cleaner can be type-assert to Builder")
}
}
|
WIZARD-CXY/kubernetes
|
pkg/volume/aws_ebs/aws_ebs_test.go
|
GO
|
apache-2.0
| 9,887
|
package com.caozeal;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HelloController {
/**
* 欢迎
* <p>
* 创建时间:2017年6月10日下午10:36:01
* @author writ
* @return
*/
@RequestMapping("hello")
public @ResponseBody String test() {
return "hello, world! This com from spring!";
}
@PostMapping("test")
public String testParam(@RequestParam String a){
return a;
}
// public static void main(String[] args) {
// int a = testX();
// System.out.println("0-" + a);
// }
//
// private static int testX() {
// int i = 1;
// try{
// System.out.println("1-" + i);
// System.out.println("x-" + i);
// throw new Exception();
//// return i;
// }catch (Exception e){
// ++i;
// return i;
// }
// finally {
// ++i;
// return i;
//// System.out.println("2-" + i);
// }
// }
}
|
caozeal/Utopia
|
Source/UtopiaLand/src/com/caozeal/HelloController.java
|
Java
|
apache-2.0
| 1,294
|
#pragma once
namespace gorc {
namespace flags {
enum class surface_flag {
Floor = 0x1,
CogLinked = 0x2,
Impassable = 0x4,
AiCannotWalkOnFloor = 0x8,
DoubletextureScale = 0x10,
HalftextureScale = 0x20,
EighthtextureScale = 0x40,
NoFallingDamage = 0x80,
HorizonSky = 0x200,
CeilingSky = 0x400,
Scrolling = 0x800,
Icy = 0x1000,
VeryIcy = 0x2000,
MagSealed = 0x4000,
Metal = 0x10000,
DeepWater = 0x20000,
ShallowWater = 0x40000,
Dirt = 0x80000,
VeryDeepWater = 0x100000
};
}
}
|
jdmclark/gorc
|
src/libs/libold/content/flags/surface_flag.hpp
|
C++
|
apache-2.0
| 970
|
package serf.data.io;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;
import serf.data.Attribute;
import serf.data.Record;
public abstract class ParseYahooData {
protected int recordCount = 0;
RecordFilter filter;
protected String[] dataSrcs;
public ParseYahooData(String srcs[], RecordFilter rf) throws IOException {
dataSrcs = srcs;
filter = rf;
}
public ParseYahooData(String srcs[]) throws IOException {
dataSrcs = srcs;
filter = new RecordFilter();
}
protected void parseDataSources() throws IOException {
parseDataSources(0);
}
protected int getRecords(BufferedReader br, int maxCount, int recordCount)
throws IOException {
String line;
while ((line = br.readLine()) != null
&& (maxCount == 0 || recordCount < maxCount)) {
Set<Attribute> aSet = new HashSet<Attribute>();
Pattern p = Pattern.compile("<([^:]*):([^>]*)>");
Matcher m = p.matcher(line);
while (m.find()) {
String type = line.substring(m.start(1), m.end(1));
String value = line.substring(m.start(2), m.end(2));
aSet.add(new Attribute(type, value));
}
Record r = new Record(1.0, aSet);
if (filter.includeRecord(r)) {
recordCount++;
action(r);
}
}
br.close();
return recordCount;
}
protected BufferedReader getReader(String src) throws IOException {
BufferedReader br;
// check file extension figure out if GZip file.
if (src.endsWith(".gz") || src.endsWith(".gzip"))
br =
new BufferedReader(new InputStreamReader(new GZIPInputStream(
new FileInputStream(src))));
else
br = new BufferedReader(new FileReader(src));
return br;
}
protected void parseDataSources(int[] maxPerFile) throws IOException {
parseBegin();
for (int i = 0; i < dataSrcs.length; i++) {
BufferedReader br = getReader(dataSrcs[i]);
getRecords(br, maxPerFile[i], recordCount);
}
parseEnd();
}
protected void parseDataSources(int maxRecordCount) throws IOException {
parseBegin();
for (String src : dataSrcs) {
BufferedReader br = getReader(src);
// go through file.
recordCount += getRecords(br, maxRecordCount, recordCount);
}
parseEnd();
}
protected void parseBegin() throws IOException {
}
protected void parseEnd() throws IOException {
}
protected abstract void action(Record r) throws IOException;
}
|
kevin-ww/er
|
src/serf/data/io/ParseYahooData.java
|
Java
|
apache-2.0
| 2,725
|
# -*- coding: utf-8 -*-
"""
Authors: Tim Hessels
UNESCO-IHE 2017
Contact: t.hessels@unesco-ihe.org
Repository: https://github.com/wateraccounting/wa
Module: Collect/JRC
Description:
This module downloads JRC water occurrence data from http://storage.googleapis.com/global-surface-water/downloads/.
Use the JRC.Occurrence function to
download and create a water occurrence image in Gtiff format.
The data represents the period 1984-2015.
Examples:
from wa.Collect import JRC
JRC.Occurrence(Dir='C:/Temp3/', latlim=[41, 45], lonlim=[-8, -5])
"""
from .Occurrence import main as Occurrence
__all__ = ['Occurrence']
__version__ = '0.1'
|
wateraccounting/wa
|
Collect/JRC/__init__.py
|
Python
|
apache-2.0
| 647
|
# Citharexylum ×leonis Moldenke SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Verbenaceae/Citharexylum/Citharexylum leonis/README.md
|
Markdown
|
apache-2.0
| 180
|
# Thea tenuiflora Hayata SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Ericales/Theaceae/Thea/Thea tenuiflora/README.md
|
Markdown
|
apache-2.0
| 172
|
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
class Controller extends BaseController {
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}
|
anisku11/hashtag
|
app/Http/Controllers/Controller.php
|
PHP
|
apache-2.0
| 358
|
/**
*
* @author moz4r (at) myrobotlab.org
*
* This file is part of MyRobotLab (http://myrobotlab.org).
*
* MyRobotLab is free software: you can redistribute it and/or modify
* it under the terms of the Apache License 2.0 as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version (subject to the "Classpath" exception
* as provided in the LICENSE.txt file that accompanied this code).
*
* MyRobotLab is distributed in the hope that it will be useful or fun,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Apache License 2.0 for more details.
*
* All libraries in thirdParty bundle are subject to their own license
* requirements - please refer to http://myrobotlab.org/libraries for
* details.
*
* Enjoy !
*
* */
package org.myrobotlab.swing;
import java.awt.event.ActionListener;
import java.io.IOException;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.service.SwingGui;
import org.myrobotlab.swing.abstracts.AbstractSpeechSynthesisGui;
import org.slf4j.Logger;
public class VoiceRssGui extends AbstractSpeechSynthesisGui implements ActionListener {
static final long serialVersionUID = 1L;
public final static Logger log = LoggerFactory.getLogger(VoiceRssGui.class);
public VoiceRssGui(final String boundServiceName, final SwingGui myService) throws IOException {
super(boundServiceName, myService);
}
}
|
MyRobotLab/myrobotlab
|
src/main/java/org/myrobotlab/swing/VoiceRssGui.java
|
Java
|
apache-2.0
| 1,587
|
/*
* Copyright 2012 GitHub 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.janela.mobile.ui.commit;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import com.janela.kevinsawicki.wishlist.SingleTypeAdapter;
import com.janela.mobile.R;
import com.janela.mobile.core.commit.CommitUtils;
import com.janela.mobile.ui.StyledText;
import com.janela.mobile.util.AvatarLoader;
import com.janela.mobile.util.TypefaceUtils;
import java.util.Collection;
import org.eclipse.egit.github.core.RepositoryCommit;
/**
* Adapter to display commits
*/
public class CommitListAdapter extends SingleTypeAdapter<RepositoryCommit> {
private final AvatarLoader avatars;
/**
* @param viewId
* @param inflater
* @param elements
* @param avatars
*/
public CommitListAdapter(int viewId, LayoutInflater inflater,
Collection<RepositoryCommit> elements, AvatarLoader avatars) {
super(inflater, viewId);
this.avatars = avatars;
setItems(elements);
}
@Override
public long getItemId(int position) {
String sha = getItem(position).getSha();
if (!TextUtils.isEmpty(sha))
return sha.hashCode();
else
return super.getItemId(position);
}
@Override
protected int[] getChildViewIds() {
return new int[] { R.id.tv_commit_id, R.id.tv_commit_author, R.id.iv_avatar,
R.id.tv_commit_message, R.id.tv_commit_comments };
}
@Override
protected View initialize(View view) {
view = super.initialize(view);
TextView commentIcon = (TextView) view .findViewById(R.id.tv_comment_icon);
commentIcon.setText(TypefaceUtils.ICON_COMMENT);
TypefaceUtils.setOcticons(commentIcon);
return view;
}
@Override
protected void update(int position, RepositoryCommit item) {
setText(0, CommitUtils.abbreviate(item.getSha()));
StyledText authorText = new StyledText();
authorText.bold(CommitUtils.getAuthor(item));
authorText.append(' ');
authorText.append(CommitUtils.getAuthorDate(item));
setText(1, authorText);
CommitUtils.bindAuthor(item, avatars, imageView(2));
setText(3, item.getCommit().getMessage());
setText(4, CommitUtils.getCommentCount(item));
}
}
|
DeLaSalleUniversity-Manila/forkhub-Janelaaa
|
app/src/main/java/com/janela/mobile/ui/commit/CommitListAdapter.java
|
Java
|
apache-2.0
| 2,925
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
//
// This source code was auto-generated by cf-sdk-builder
//
using CloudFoundry.CloudController.V2.Interfaces;
using Newtonsoft.Json;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
namespace CloudFoundry.CloudController.V2.Client.Data
{
/// <summary>
/// Data class used for serializing the "CloudFoundry.CloudController.V2.Client.ServicePlanVisibilitiesEndpoint.CreateServicePlanVisibility()" Request
/// <para>For usage information, see online documentation at "http://apidocs.cloudfoundry.org/195/service_plan_visibilities/creating_a_service_plan_visibility.html"</para>
/// </summary>
[GeneratedCodeAttribute("cf-sdk-builder", "1.0.0.0")]
public partial class CreateServicePlanVisibilityRequest : CloudFoundry.CloudController.V2.Client.Data.Base.AbstractCreateServicePlanVisibilityRequest
{
}
}
namespace CloudFoundry.CloudController.V2.Client.Data.Base
{
/// <summary>
/// Base abstract data class used for serializing the "CloudFoundry.CloudController.V2.Client.ServicePlanVisibilitiesEndpoint.CreateServicePlanVisibility()" Request
/// <para>For usage information, see online documentation at "http://apidocs.cloudfoundry.org/195/service_plan_visibilities/creating_a_service_plan_visibility.html"</para>
/// </summary>
[GeneratedCodeAttribute("cf-sdk-builder", "1.0.0.0")]
public abstract class AbstractCreateServicePlanVisibilityRequest
{
/// <summary>
/// <para>The guid of the plan that will be made visible</para>
/// </summary>
[JsonProperty("service_plan_guid", NullValueHandling = NullValueHandling.Ignore)]
public Guid? ServicePlanGuid
{
get;
set;
}
/// <summary>
/// <para>The guid of the organization the plan will be visible to</para>
/// </summary>
[JsonProperty("organization_guid", NullValueHandling = NullValueHandling.Ignore)]
public Guid? OrganizationGuid
{
get;
set;
}
}
}
|
adasescu/cf-dotnet-sdk
|
src/CloudFoundry.CloudController.V2.Client/Client/Data/DC_CreateServicePlanVisibilityRequest.cs
|
C#
|
apache-2.0
| 2,420
|
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _BDROID_BUILDCFG_H
#define _BDROID_BUILDCFG_H
#define BTM_DEF_LOCAL_NAME "Xperia Ion"
#define BTA_DISABLE_DELAY 1000 /* in milliseconds */
#endif
|
MrGezz/android_device_sony_aoba
|
bluetooth/bdroid_buildcfg.h
|
C
|
apache-2.0
| 779
|
package com.bruce.wechat.msg.Resp;
/**
* 视频消息
*
* @author ivhhs
* @date 2014.10.16
*/
public class VideoMessage extends BaseMessage {
// 视频
private Video video;
public Video getVideo() {
return video;
}
public void setVideo(Video video) {
this.video = video;
}
}
|
LittleLazyCat/TXEYXXK
|
2017workspace/wxqyh/src/com/bruce/wechat/msg/Resp/VideoMessage.java
|
Java
|
apache-2.0
| 293
|
import { Trans } from "@lingui/macro";
import { i18nMark, withI18n } from "@lingui/react";
import mixin from "reactjs-mixin";
import { Hooks } from "PluginSDK";
import * as React from "react";
import StoreMixin from "#SRC/js/mixins/StoreMixin";
import AuthStore from "../../stores/AuthStore";
import FormModal from "../FormModal";
import ModalHeading from "../modals/ModalHeading";
import UserStore from "../../stores/UserStore";
class UserFormModal extends mixin(StoreMixin) {
state = {
disableNewUser: false,
errorMsg: false,
errorCode: null,
};
// prettier-ignore
store_listeners = [
{name: "user", events: ["createSuccess", "createError"], suppressUpdate: true}
];
onUserStoreCreateSuccess = () => {
this.setState({
disableNewUser: false,
errorMsg: false,
errorCode: null,
});
this.props.onClose();
};
onUserStoreCreateError(errorMsg, userID, xhr) {
this.setState({
disableNewUser: false,
errorMsg,
errorCode: xhr.status,
});
}
handleClose = () => {
this.setState({
disableNewUser: false,
errorMsg: false,
errorCode: null,
});
this.props.onClose();
};
handleNewUserSubmit = (model) => {
const { i18n } = this.props;
const passwordsMessage = i18nMark("Passwords do not match.");
if (model.password !== model.confirmPassword) {
// Check if passwords match.
return this.setState({
errorMsg: i18n._(passwordsMessage),
});
}
delete model.confirmPassword; // We don't need to send this to the backend.
this.setState({ disableNewUser: true });
const userModelObject = Hooks.applyFilter("userModelObject", {
...model,
creator_uid: AuthStore.getUser().uid,
cluster_url: `${window.location.protocol}//${window.location.hostname}`,
});
UserStore.addUser(userModelObject);
};
getButtonDefinition() {
const { props, state } = this;
return Hooks.applyFilter(
"userFormModalButtonDefinition",
[
{
text: i18nMark("Cancel"),
className: "button button-primary-link",
isClose: true,
},
{
text: state.disableNewUser
? i18nMark("Adding...")
: i18nMark("Add User"),
className: "button button-primary",
isSubmit: true,
},
],
props,
state
);
}
getNewUserFormDefinition() {
const { props, state } = this;
return Hooks.applyFilter(
"userFormModalDefinition",
[
{
fieldType: "text",
name: "uid",
placeholder: "Email",
required: true,
showError: state.errorMsg,
showLabel: false,
writeType: "input",
validation() {
return true;
},
value: "",
},
],
props,
state
);
}
getHeader() {
return Hooks.applyFilter(
"userFormModalHeader",
<ModalHeading>
<Trans render="span">Add User to Cluster</Trans>
</ModalHeading>
);
}
getFooter() {
return (
<div>
{Hooks.applyFilter("userAddPolicy", null)}
{Hooks.applyFilter(
"userFormModalFooter",
<Trans
render="p"
className="form-group-without-top-label flush-bottom text-align-center"
>
<strong>Important:</strong> Because telemetry is disabled you must
manually notify users of ACL changes.
</Trans>
)}
</div>
);
}
render() {
return (
<FormModal
buttonDefinition={this.getButtonDefinition()}
definition={this.getNewUserFormDefinition()}
disabled={this.state.disableNewUser}
modalProps={{
header: this.getHeader(),
showHeader: true,
}}
onClose={this.handleClose}
onSubmit={this.handleNewUserSubmit}
open={this.props.open}
contentFooter={this.getFooter()}
/>
);
}
}
export default withI18n()(UserFormModal);
|
dcos/dcos-ui
|
src/js/components/modals/UserFormModal.tsx
|
TypeScript
|
apache-2.0
| 4,065
|
package net.sourceforge.marathon.component.jide;
import java.awt.Component;
import java.awt.Point;
import java.awt.event.MouseEvent;
import com.jidesoft.swing.JideSplitPane;
import net.sourceforge.marathon.component.RComponent;
import net.sourceforge.marathon.javarecorder.IJSONRecorder;
import net.sourceforge.marathon.javarecorder.JSONOMapConfig;
import net.sourceforge.marathon.json.JSONArray;
public class RJideSplitPaneElement extends RComponent {
private String prevLocations;
public RJideSplitPaneElement(Component source, JSONOMapConfig omapConfig, Point point, IJSONRecorder recorder) {
super(source, omapConfig, point, recorder);
}
@Override
protected void mouseButton1Pressed(MouseEvent me) {
JideSplitPane sp = (JideSplitPane) getComponent();
prevLocations = new JSONArray(sp.getDividerLocations()).toString();
}
@Override
protected void mouseReleased(MouseEvent me) {
JideSplitPane sp = (JideSplitPane) getComponent();
String currentDividerLoctions = new JSONArray(sp.getDividerLocations()).toString();
if (!currentDividerLoctions.equals(prevLocations)) {
recorder.recordSelect(this, currentDividerLoctions);
}
}
@Override
public String _getText() {
JideSplitPane sp = (JideSplitPane) getComponent();
return new JSONArray(sp.getDividerLocations()).toString();
}
@Override
public String getTagName() {
return "jide-split-pane";
}
}
|
jalian-systems/marathonv5
|
marathon-java/marathon-java-recorder/src/main/java/net/sourceforge/marathon/component/jide/RJideSplitPaneElement.java
|
Java
|
apache-2.0
| 1,506
|
package org.hswebframework.web.entity.form;
import org.hswebframework.web.commons.entity.SimpleGenericEntity;
/**
* 动态表单
*
* @author hsweb-generator-online
*/
public class SimpleDynamicFormEntity extends SimpleGenericEntity<String> implements DynamicFormEntity {
//表单名称
private String name;
//数据库表名
private String databaseTableName;
//备注
private String describe;
//版本
private Long version;
//创建人id
private String creatorId;
//创建时间
private Long createTime;
//修改时间
private Long updateTime;
//是否已发布
private Boolean deployed;
//别名
private String alias;
//触发器
private String triggers;
//表链接
private String correlations;
//数据源id,为空使用默认数据源
private String dataSourceId;
//表单类型
private String type;
/**
* @return 表单名称
*/
@Override
public String getName() {
return this.name;
}
/**
* @param name 表单名称
*/
@Override
public void setName(String name) {
this.name = name;
}
/**
* @return 数据库表名
*/
@Override
public String getDatabaseTableName() {
return this.databaseTableName;
}
/**
* @param databaseTableName 数据库表名
*/
@Override
public void setDatabaseTableName(String databaseTableName) {
this.databaseTableName = databaseTableName;
}
/**
* @return 备注
*/
@Override
public String getDescribe() {
return this.describe;
}
/**
* @param describe 备注
*/
@Override
public void setDescribe(String describe) {
this.describe = describe;
}
/**
* @return 版本
*/
@Override
public Long getVersion() {
return this.version;
}
/**
* @param version 版本
*/
@Override
public void setVersion(Long version) {
this.version = version;
}
/**
* @return 创建人id
*/
@Override
public String getCreatorId() {
return this.creatorId;
}
/**
* @param creatorId 创建人id
*/
@Override
public void setCreatorId(String creatorId) {
this.creatorId = creatorId;
}
/**
* @return 创建时间
*/
@Override
public Long getCreateTime() {
return this.createTime;
}
/**
* @param createTime 创建时间
*/
@Override
public void setCreateTime(Long createTime) {
this.createTime = createTime;
}
/**
* @return 修改时间
*/
@Override
public Long getUpdateTime() {
return this.updateTime;
}
/**
* @param updateTime 修改时间
*/
@Override
public void setUpdateTime(Long updateTime) {
this.updateTime = updateTime;
}
/**
* @return 是否已发布
*/
@Override
public Boolean getDeployed() {
return this.deployed;
}
/**
* @param deployed 是否已发布
*/
@Override
public void setDeployed(Boolean deployed) {
this.deployed = deployed;
}
/**
* @return 别名
*/
@Override
public String getAlias() {
return this.alias;
}
/**
* @param alias 别名
*/
@Override
public void setAlias(String alias) {
this.alias = alias;
}
/**
* @return 触发器
*/
@Override
public String getTriggers() {
return this.triggers;
}
/**
* @param triggers 触发器
*/
@Override
public void setTriggers(String triggers) {
this.triggers = triggers;
}
/**
* @return 表链接
*/
@Override
public String getCorrelations() {
return this.correlations;
}
/**
* @param correlations 表链接
*/
@Override
public void setCorrelations(String correlations) {
this.correlations = correlations;
}
/**
* @return 数据源id, 为空使用默认数据源
*/
@Override
public String getDataSourceId() {
return this.dataSourceId;
}
/**
* @param dataSourceId 数据源id,为空使用默认数据源
*/
@Override
public void setDataSourceId(String dataSourceId) {
this.dataSourceId = dataSourceId;
}
/**
* @return 表单类型
*/
@Override
public String getType() {
return this.type;
}
/**
* @param type 表单类型
*/
@Override
public void setType(String type) {
this.type = type;
}
}
|
asiaon123/hsweb-framework
|
hsweb-system/hsweb-system-dynamic-form/hsweb-system-dynamic-form-entity/src/main/java/org/hswebframework/web/entity/form/SimpleDynamicFormEntity.java
|
Java
|
apache-2.0
| 4,689
|
package com.tzutalin.customicon.Utils.Shape;
import android.graphics.Point;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by DEV on 2017-10-27.
*/
public class Shape {
protected Point mid;
public Point calMidPoint(Point front, Point back) {
int midX = calMid(front.x, back.x);
int midY = calMid(front.y, back.y);
mid = new Point(midX, midY);
return mid;
}
public int calMid(int x, int y) {
int tmp = x + y;
int result;
if (tmp < 0) tmp = tmp * (-1); // mark change
result = tmp / 2;
return result;
}
public double calDistance(Point a, Point b) {
int disX = a.x - b.x;
int disY = a.y - b.y;
double distance = Math.sqrt(Math.pow(disX, 2) + Math.pow(disY, 2));
return distance;
}
public double calSlope(Point a, Point b) {
double deltaX = b.y - a.y;
double deltaY = b.x - a.x;
double slope = deltaY / deltaX ;
return slope;
}
}
|
hgs6424/Customicon
|
app/src/main/java/com/tzutalin/customicon/Utils/Shape/Shape.java
|
Java
|
apache-2.0
| 1,052
|
/*
* Copyright 2015 Caleb Brose, Chris Fogerty, Rob Sheehy, Zach Taylor, Nick Miller
*
* 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.
*/
var _ = require('lodash');
function appListModel() {
'use strict';
function init() {
return {
'apps': [],
'detail': {}
};
}
return {
// State
state: init(),
handlers: {
'appDetail': 'detail',
'appList': 'list'
},
detail: function (r) {
// Sort in descending by deploy id
this.state.detail[r.id.toString()] = _.sortByOrder(r.data, ['Id'], [false]);
this.emitChange();
},
list: function (r) {
this.state.apps = r.data;
this.emitChange();
},
exports: {
apps: function () {
return this.state.apps;
},
detail: function (id) {
if (id === undefined) {
return this.state.detail;
}
var ret = this.state.detail[id.toString()];
return ret ? ret : {};
}
}
};
}
module.exports = appListModel;
|
lighthouse/harbor
|
app/js/deploy/appListModel.js
|
JavaScript
|
apache-2.0
| 1,724
|
/*
* Copyright (C) 2013 The Android Open Source Project
*
* 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.example.android.foldinglayout;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Rect;
import android.graphics.Shader.TileMode;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
/**
* The folding layout where the number of folds, the anchor point and the
* orientation of the fold can be specified. Each of these parameters can
* be modified individually and updates and resets the fold to a default
* (unfolded) state. The fold factor varies between 0 (completely unfolded
* flat image) to 1.0 (completely folded, non-visible image).
*
* This layout throws an exception if there is more than one child added to the view.
* For more complicated view hierarchy's inside the folding layout, the views should all
* be nested inside 1 parent layout.
*
* This layout folds the contents of its child in real time. By applying matrix
* transformations when drawing to canvas, the contents of the child may change as
* the fold takes place. It is important to note that there are jagged edges about
* the perimeter of the layout as a result of applying transformations to a rectangle.
* This can be avoided by having the child of this layout wrap its content inside a
* 1 pixel transparent border. This will cause an anti-aliasing like effect and smoothen
* out the edges.
*
*/
public class FoldingLayout extends ViewGroup {
public static enum Orientation {
VERTICAL,
HORIZONTAL
}
private final String FOLDING_VIEW_EXCEPTION_MESSAGE = "Folding Layout can only 1 child at " +
"most";
private final float SHADING_ALPHA = 0.8f;
private final float SHADING_FACTOR = 0.5f;
private final int DEPTH_CONSTANT = 1500;
private final int NUM_OF_POLY_POINTS = 8;
private Rect[] mFoldRectArray;
private Matrix[] mMatrix;
private Orientation mOrientation = Orientation.HORIZONTAL;
private float mAnchorFactor = 0;
private float mFoldFactor = 0;
private int mNumberOfFolds = 2;
private boolean mIsHorizontal = true;
private int mOriginalWidth = 0;
private int mOriginalHeight = 0;
private float mFoldMaxWidth = 0;
private float mFoldMaxHeight = 0;
private float mFoldDrawWidth = 0;
private float mFoldDrawHeight = 0;
private boolean mIsFoldPrepared = false;
private boolean mShouldDraw = true;
private Paint mSolidShadow;
private Paint mGradientShadow;
private LinearGradient mShadowLinearGradient;
private Matrix mShadowGradientMatrix;
private float[] mSrc;
private float[] mDst;
private OnFoldListener mFoldListener;
private float mPreviousFoldFactor = 0;
private Bitmap mFullBitmap;
private Rect mDstRect;
public FoldingLayout(Context context) {
super(context);
}
public FoldingLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public FoldingLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected boolean addViewInLayout(View child, int index, LayoutParams params,
boolean preventRequestLayout) {
throwCustomException(getChildCount());
boolean returnValue = super.addViewInLayout(child, index, params, preventRequestLayout);
return returnValue;
}
@Override
public void addView(View child, int index, LayoutParams params) {
throwCustomException(getChildCount());
super.addView(child, index, params);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
View child = getChildAt(0);
measureChild(child,widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
View child = getChildAt(0);
child.layout(0, 0, child.getMeasuredWidth(), child.getMeasuredHeight());
updateFold();
}
/**
* The custom exception to be thrown so as to limit the number of views in this
* layout to at most one.
*/
private class NumberOfFoldingLayoutChildrenException extends RuntimeException {
public NumberOfFoldingLayoutChildrenException(String message) {
super(message);
}
}
/** Throws an exception if the number of views added to this layout exceeds one.*/
private void throwCustomException (int numOfChildViews) {
if (numOfChildViews == 1) {
throw new NumberOfFoldingLayoutChildrenException(FOLDING_VIEW_EXCEPTION_MESSAGE);
}
}
public void setFoldListener(OnFoldListener foldListener) {
mFoldListener = foldListener;
}
/**
* Sets the fold factor of the folding view and updates all the corresponding
* matrices and values to account for the new fold factor. Once that is complete,
* it redraws itself with the new fold. */
public void setFoldFactor(float foldFactor) {
if (foldFactor != mFoldFactor) {
mFoldFactor = foldFactor;
calculateMatrices();
invalidate();
}
}
public void setOrientation(Orientation orientation) {
if (orientation != mOrientation) {
mOrientation = orientation;
updateFold();
}
}
public void setAnchorFactor(float anchorFactor) {
if (anchorFactor != mAnchorFactor) {
mAnchorFactor = anchorFactor;
updateFold();
}
}
public void setNumberOfFolds(int numberOfFolds) {
if (numberOfFolds != mNumberOfFolds) {
mNumberOfFolds = numberOfFolds;
updateFold();
}
}
public float getAnchorFactor() {
return mAnchorFactor;
}
public Orientation getOrientation() {
return mOrientation;
}
public float getFoldFactor() {
return mFoldFactor;
}
public int getNumberOfFolds() {
return mNumberOfFolds;
}
private void updateFold() {
prepareFold(mOrientation, mAnchorFactor, mNumberOfFolds);
calculateMatrices();
invalidate();
}
/**
* This method is called in order to update the fold's orientation, anchor
* point and number of folds. This creates the necessary setup in order to
* prepare the layout for a fold with the specified parameters. Some of the
* dimensions required for the folding transformation are also acquired here.
*
* After this method is called, it will be in a completely unfolded state by default.
*/
private void prepareFold(Orientation orientation, float anchorFactor, int numberOfFolds) {
mSrc = new float[NUM_OF_POLY_POINTS];
mDst = new float[NUM_OF_POLY_POINTS];
mDstRect = new Rect();
mFoldFactor = 0;
mPreviousFoldFactor = 0;
mIsFoldPrepared = false;
mSolidShadow = new Paint();
mGradientShadow = new Paint();
mOrientation = orientation;
mIsHorizontal = (orientation == Orientation.HORIZONTAL);
if (mIsHorizontal) {
mShadowLinearGradient = new LinearGradient(0, 0, SHADING_FACTOR, 0, Color.BLACK,
Color.TRANSPARENT, TileMode.CLAMP);
} else {
mShadowLinearGradient = new LinearGradient(0, 0, 0, SHADING_FACTOR, Color.BLACK,
Color.TRANSPARENT, TileMode.CLAMP);
}
mGradientShadow.setStyle(Style.FILL);
mGradientShadow.setShader(mShadowLinearGradient);
mShadowGradientMatrix = new Matrix();
mAnchorFactor = anchorFactor;
mNumberOfFolds = numberOfFolds;
mOriginalWidth = getMeasuredWidth();
mOriginalHeight = getMeasuredHeight();
mFoldRectArray = new Rect[mNumberOfFolds];
mMatrix = new Matrix [mNumberOfFolds];
for (int x = 0; x < mNumberOfFolds; x++) {
mMatrix[x] = new Matrix();
}
int h = mOriginalHeight;
int w = mOriginalWidth;
if (FoldingLayoutActivity.IS_JBMR2) {
mFullBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(mFullBitmap);
getChildAt(0).draw(canvas);
}
int delta = Math.round(mIsHorizontal ? ((float) w) / ((float) mNumberOfFolds) :
((float) h) /((float) mNumberOfFolds));
/* Loops through the number of folds and segments the full layout into a number
* of smaller equal components. If the number of folds is odd, then one of the
* components will be smaller than all the rest. Note that deltap below handles
* the calculation for an odd number of folds.*/
for (int x = 0; x < mNumberOfFolds; x++) {
if (mIsHorizontal) {
int deltap = (x + 1) * delta > w ? w - x * delta : delta;
mFoldRectArray[x] = new Rect(x * delta, 0, x * delta + deltap, h);
} else {
int deltap = (x + 1) * delta > h ? h - x * delta : delta;
mFoldRectArray[x] = new Rect(0, x * delta, w, x * delta + deltap);
}
}
if (mIsHorizontal) {
mFoldMaxHeight = h;
mFoldMaxWidth = delta;
} else {
mFoldMaxHeight = delta;
mFoldMaxWidth = w;
}
mIsFoldPrepared = true;
}
/*
* Calculates the transformation matrices used to draw each of the separate folding
* segments from this view.
*/
private void calculateMatrices() {
mShouldDraw = true;
if (!mIsFoldPrepared) {
return;
}
/** If the fold factor is 1 than the folding view should not be seen
* and the canvas can be left completely empty. */
if (mFoldFactor == 1) {
mShouldDraw = false;
return;
}
if (mFoldFactor == 0 && mPreviousFoldFactor > 0) {
mFoldListener.onEndFold();
}
if (mPreviousFoldFactor == 0 && mFoldFactor > 0) {
mFoldListener.onStartFold();
}
mPreviousFoldFactor = mFoldFactor;
/* Reset all the transformation matrices back to identity before computing
* the new transformation */
for (int x = 0; x < mNumberOfFolds; x++) {
mMatrix[x].reset();
}
float cTranslationFactor = 1 - mFoldFactor;
float translatedDistance = mIsHorizontal ? mOriginalWidth * cTranslationFactor :
mOriginalHeight * cTranslationFactor;
float translatedDistancePerFold = Math.round(translatedDistance / mNumberOfFolds);
/* For an odd number of folds, the rounding error may cause the
* translatedDistancePerFold to be grater than the max fold width or height. */
mFoldDrawWidth = mFoldMaxWidth < translatedDistancePerFold ?
translatedDistancePerFold : mFoldMaxWidth;
mFoldDrawHeight = mFoldMaxHeight < translatedDistancePerFold ?
translatedDistancePerFold : mFoldMaxHeight;
float translatedDistanceFoldSquared = translatedDistancePerFold * translatedDistancePerFold;
/* Calculate the depth of the fold into the screen using pythagorean theorem. */
float depth = mIsHorizontal ?
(float)Math.sqrt((double)(mFoldDrawWidth * mFoldDrawWidth -
translatedDistanceFoldSquared)) :
(float)Math.sqrt((double)(mFoldDrawHeight * mFoldDrawHeight -
translatedDistanceFoldSquared));
/* The size of some object is always inversely proportional to the distance
* it is away from the viewpoint. The constant can be varied to to affect the
* amount of perspective. */
float scaleFactor = DEPTH_CONSTANT / (DEPTH_CONSTANT + depth);
float scaledWidth, scaledHeight, bottomScaledPoint, topScaledPoint, rightScaledPoint,
leftScaledPoint;
if (mIsHorizontal) {
scaledWidth = mFoldDrawWidth * cTranslationFactor;
scaledHeight = mFoldDrawHeight * scaleFactor;
} else {
scaledWidth = mFoldDrawWidth * scaleFactor;
scaledHeight = mFoldDrawHeight * cTranslationFactor;
}
topScaledPoint = (mFoldDrawHeight - scaledHeight) / 2.0f;
bottomScaledPoint = topScaledPoint + scaledHeight;
leftScaledPoint = (mFoldDrawWidth - scaledWidth) / 2.0f;
rightScaledPoint = leftScaledPoint + scaledWidth;
float anchorPoint = mIsHorizontal ? mAnchorFactor * mOriginalWidth :
mAnchorFactor * mOriginalHeight;
/* The fold along which the anchor point is located. */
float midFold = mIsHorizontal ? (anchorPoint / mFoldDrawWidth) : anchorPoint /
mFoldDrawHeight;
mSrc[0] = 0;
mSrc[1] = 0;
mSrc[2] = 0;
mSrc[3] = mFoldDrawHeight;
mSrc[4] = mFoldDrawWidth;
mSrc[5] = 0;
mSrc[6] = mFoldDrawWidth;
mSrc[7] = mFoldDrawHeight;
/* Computes the transformation matrix for each fold using the values calculated above. */
for (int x = 0; x < mNumberOfFolds; x++) {
boolean isEven = (x % 2 == 0);
if (mIsHorizontal) {
mDst[0] = (anchorPoint > x * mFoldDrawWidth) ? anchorPoint + (x - midFold) *
scaledWidth : anchorPoint - (midFold - x) * scaledWidth;
mDst[1] = isEven ? 0 : topScaledPoint;
mDst[2] = mDst[0];
mDst[3] = isEven ? mFoldDrawHeight: bottomScaledPoint;
mDst[4] = (anchorPoint > (x + 1) * mFoldDrawWidth) ? anchorPoint + (x + 1 - midFold)
* scaledWidth : anchorPoint - (midFold - x - 1) * scaledWidth;
mDst[5] = isEven ? topScaledPoint : 0;
mDst[6] = mDst[4];
mDst[7] = isEven ? bottomScaledPoint : mFoldDrawHeight;
} else {
mDst[0] = isEven ? 0 : leftScaledPoint;
mDst[1] = (anchorPoint > x * mFoldDrawHeight) ? anchorPoint + (x - midFold) *
scaledHeight : anchorPoint - (midFold - x) * scaledHeight;
mDst[2] = isEven ? leftScaledPoint: 0;
mDst[3] = (anchorPoint > (x + 1) * mFoldDrawHeight) ? anchorPoint + (x + 1 -
midFold) * scaledHeight : anchorPoint - (midFold - x - 1) * scaledHeight;
mDst[4] = isEven ? mFoldDrawWidth : rightScaledPoint;
mDst[5] = mDst[1];
mDst[6] = isEven ? rightScaledPoint : mFoldDrawWidth;
mDst[7] = mDst[3];
}
/* Pixel fractions are present for odd number of folds which need to be
* rounded off here.*/
for (int y = 0; y < 8; y ++) {
mDst[y] = Math.round(mDst[y]);
}
/* If it so happens that any of the folds have reached a point where
* the width or height of that fold is 0, then nothing needs to be
* drawn onto the canvas because the view is essentially completely
* folded.*/
if (mIsHorizontal) {
if (mDst[4] <= mDst[0] || mDst[6] <= mDst[2]) {
mShouldDraw = false;
return;
}
} else {
if (mDst[3] <= mDst[1] || mDst[7] <= mDst[5]) {
mShouldDraw = false;
return;
}
}
/* Sets the shadow and bitmap transformation matrices.*/
mMatrix[x].setPolyToPoly(mSrc, 0, mDst, 0, NUM_OF_POLY_POINTS / 2);
}
/* The shadows on the folds are split into two parts: Solid shadows and gradients.
* Every other fold has a solid shadow which overlays the whole fold. Similarly,
* the folds in between these alternating folds also have an overlaying shadow.
* However, it is a gradient that takes up part of the fold as opposed to a solid
* shadow overlaying the whole fold.*/
/* Solid shadow paint object. */
int alpha = (int) (mFoldFactor * 255 * SHADING_ALPHA);
mSolidShadow.setColor(Color.argb(alpha, 0, 0, 0));
if (mIsHorizontal) {
mShadowGradientMatrix.setScale(mFoldDrawWidth, 1);
mShadowLinearGradient.setLocalMatrix(mShadowGradientMatrix);
} else {
mShadowGradientMatrix.setScale(1, mFoldDrawHeight);
mShadowLinearGradient.setLocalMatrix(mShadowGradientMatrix);
}
mGradientShadow.setAlpha(alpha);
}
@Override
protected void dispatchDraw(Canvas canvas) {
/** If prepareFold has not been called or if preparation has not completed yet,
* then no custom drawing will take place so only need to invoke super's
* onDraw and return. */
if (!mIsFoldPrepared || mFoldFactor == 0) {
super.dispatchDraw(canvas);
return;
}
if (!mShouldDraw) {
return;
}
Rect src;
/* Draws the bitmaps and shadows on the canvas with the appropriate transformations. */
for (int x = 0; x < mNumberOfFolds; x++) {
src = mFoldRectArray[x];
/* The canvas is saved and restored for every individual fold*/
canvas.save();
/* Concatenates the canvas with the transformation matrix for the
* the segment of the view corresponding to the actual image being
* displayed. */
canvas.concat(mMatrix[x]);
if (FoldingLayoutActivity.IS_JBMR2) {
mDstRect.set(0, 0, src.width(), src.height());
canvas.drawBitmap(mFullBitmap, src, mDstRect, null);
} else {
/* The same transformation matrix is used for both the shadow and the image
* segment. The canvas is clipped to account for the size of each fold and
* is translated so they are drawn in the right place. The shadow is then drawn on
* top of the different folds using the sametransformation matrix.*/
canvas.clipRect(0, 0, src.right - src.left, src.bottom - src.top);
if (mIsHorizontal) {
canvas.translate(-src.left, 0);
} else {
canvas.translate(0, -src.top);
}
super.dispatchDraw(canvas);
if (mIsHorizontal) {
canvas.translate(src.left, 0);
} else {
canvas.translate(0, src.top);
}
}
/* Draws the shadows corresponding to this specific fold. */
if (x % 2 == 0) {
canvas.drawRect(0, 0, mFoldDrawWidth, mFoldDrawHeight, mSolidShadow);
} else {
canvas.drawRect(0, 0, mFoldDrawWidth, mFoldDrawHeight, mGradientShadow);
}
canvas.restore();
}
}
}
|
pcqpcq/FoldingLayout
|
src/com/example/android/foldinglayout/FoldingLayout.java
|
Java
|
apache-2.0
| 20,037
|
---
layout: default
title: Up and Running with Boxupp
page-link: 3
---
##Up and Running With Boxupp
To run Boxupp on windows environment browse to the folder where you have extracted Boxupp and then move to the bin folder and run startup.bat file. It will commence with the installation. Pictorial view depicted below:
Go to bin folder double click on startup.bat ( **Windows** )
{: .img-responsive}
Installation will be shown in a command prompt window ( **Windows** )
{: .img-responsive}
**Vagrant** installation wizard will appear as a part of the boxupp’s installation process. The installation intelligence will check whether vagrant is already installed on your machine, if it is then it will skip it.
{: .img-responsive}
After the installation of Vagrant another software package which will be installed is **Oracle VM Virtualbox**. The pictorial view of the same is shown on this slide .
Similar to the vagrant installation, the installation robots will check whether Oracle VM Virtual Box is already installed on your machine, if it is then it will skip it.
After the installation of **Vagrant** and **Oracle VM Virtualbox** there will be a prompt to restart your machine.Restart it and then go to bin folder and run **startup.bat**.
It will show you the following 2 screen and **Boxupp** is all set to run on your local host at : [http://localhost:8585](http://localhost:8585/){:target="_blank"} . Port number may vary if you have changed it
{: .img-responsive}
**( Mac-OS X)**
After you have unzipped the package please execute the file “_startup.sh_” You might get a permission denied error, to resolve this error execute a command “_chmod 777 *_” and then again run “_startup.sh_” . This time Boxupp will be successfully installed on your linux or mac machine and you will be able to run that in the browser at : [http://localhost:8585](http://localhost:8585/){:target="_blank"}
{: .img-responsive}
**Now since we have successfully installed the Boxupp environment on all the platforms viz. Windows, Linux, Mac OS X. In our next sections we will take a plunge into the interactive and intuitive UI offered by the same.**
**We will also create virtualized development environment without writing a single line of code. So Lets Get Started>**
|
BoxUpp/boxupptool-docs
|
running.md
|
Markdown
|
apache-2.0
| 2,470
|
package com.simbest.cores.admin.syslog.service;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.session.RowBounds;
import com.simbest.cores.admin.syslog.model.SysLoginInfo;
import com.simbest.cores.admin.syslog.model.SysLoginInfoExample;
public interface ISysLoginInfoService {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table sys_logininfo
*
* @mbggenerated Mon Aug 18 00:48:04 CST 2014
*/
int countByExample(SysLoginInfoExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table sys_logininfo
*
* @mbggenerated Mon Aug 18 00:48:04 CST 2014
*/
int deleteByExample(SysLoginInfoExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table sys_logininfo
*
* @mbggenerated Mon Aug 18 00:48:04 CST 2014
*/
int deleteByPrimaryKey(Long id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table sys_logininfo
*
* @mbggenerated Mon Aug 18 00:48:04 CST 2014
*/
int insert(SysLoginInfo record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table sys_logininfo
*
* @mbggenerated Mon Aug 18 00:48:04 CST 2014
*/
int insertSelective(SysLoginInfo record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table sys_logininfo
*
* @mbggenerated Mon Aug 18 00:48:04 CST 2014
*/
List<SysLoginInfo> selectByExample(SysLoginInfoExample example);
List<SysLoginInfo> selectByExample(SysLoginInfoExample example, RowBounds rowBounds);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table sys_logininfo
*
* @mbggenerated Mon Aug 18 00:48:04 CST 2014
*/
SysLoginInfo selectByPrimaryKey(Long id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table sys_logininfo
*
* @mbggenerated Mon Aug 18 00:48:04 CST 2014
*/
int updateByExampleSelective(@Param("record") SysLoginInfo record, @Param("example") SysLoginInfoExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table sys_logininfo
*
* @mbggenerated Mon Aug 18 00:48:04 CST 2014
*/
int updateByExample(@Param("record") SysLoginInfo record, @Param("example") SysLoginInfoExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table sys_logininfo
*
* @mbggenerated Mon Aug 18 00:48:04 CST 2014
*/
int updateByPrimaryKeySelective(SysLoginInfo record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table sys_logininfo
*
* @mbggenerated Mon Aug 18 00:48:04 CST 2014
*/
int updateByPrimaryKey(SysLoginInfo record);
}
|
simbest/simbest-cores
|
src/main/java/com/simbest/cores/admin/syslog/service/ISysLoginInfoService.java
|
Java
|
apache-2.0
| 3,249
|
/*
* Copyright (c) 2016 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.
*/
#include <ztest.h>
#include <irq_offload.h>
#include <ring_buffer.h>
#include <logging/log.h>
LOG_MODULE_REGISTER(test);
/**
* @addtogroup t_ringbuffer
* @{
* @defgroup t_ringbuffer_api test_ringbuffer_api
* @brief TestPurpose: verify zephyr ring buffer API functionality
* - API coverage
* -# RING_BUF_ITEM_DECLARE_POW2
* -# RING_BUF_ITEM_DECLARE_SIZE
* -# ring_buf_init
* -# ring_buf_is_empty
* -# ring_buf_space_get
* -# ring_buf_item_put
* -# ring_buf_item_get
* @}
*/
RING_BUF_ITEM_DECLARE_POW2(ring_buf1, 8);
#define TYPE 1
#define VALUE 2
#define INITIAL_SIZE 2
#define RINGBUFFER_SIZE 5
#define DATA_MAX_SIZE 3
#define POW 2
void test_ring_buffer_main(void)
{
int ret, put_count, i;
u32_t getdata[6];
u8_t getsize, getval;
u16_t gettype;
int dsize = INITIAL_SIZE;
__aligned(sizeof(u32_t)) char rb_data[] = "ABCDEFGHIJKLMNOPQRSTUVWX";
put_count = 0;
while (1) {
ret = ring_buf_item_put(&ring_buf1, TYPE, VALUE,
(u32_t *)rb_data, dsize);
if (ret == -EMSGSIZE) {
LOG_DBG("ring buffer is full");
break;
}
LOG_DBG("inserted %d chunks, %d remaining", dsize,
ring_buf_space_get(&ring_buf1));
dsize = (dsize + 1) % SIZE32_OF(rb_data);
put_count++;
}
getsize = INITIAL_SIZE - 1;
ret = ring_buf_item_get(&ring_buf1, &gettype, &getval,
getdata, &getsize);
if (ret != -EMSGSIZE) {
LOG_DBG("Allowed retreival with insufficient "
"destination buffer space");
zassert_true((getsize == INITIAL_SIZE),
"Correct size wasn't reported back to the caller");
}
for (i = 0; i < put_count; i++) {
getsize = SIZE32_OF(getdata);
ret = ring_buf_item_get(&ring_buf1, &gettype, &getval, getdata,
&getsize);
zassert_true((ret == 0), "Couldn't retrieve a stored value");
LOG_DBG("got %u chunks of type %u and val %u, %u remaining",
getsize, gettype, getval,
ring_buf_space_get(&ring_buf1));
zassert_true((memcmp((char *)getdata, rb_data, getsize * sizeof(u32_t)) == 0),
"data corrupted");
zassert_true((gettype == TYPE), "type information corrupted");
zassert_true((getval == VALUE), "value information corrupted");
}
getsize = SIZE32_OF(getdata);
ret = ring_buf_item_get(&ring_buf1, &gettype, &getval, getdata,
&getsize);
zassert_true((ret == -EAGAIN), "Got data out of an empty buffer");
}
/**TESTPOINT: init via RING_BUF_ITEM_DECLARE_POW2*/
RING_BUF_ITEM_DECLARE_POW2(ringbuf_pow2, POW);
/**TESTPOINT: init via RING_BUF_ITEM_DECLARE_SIZE*/
RING_BUF_ITEM_DECLARE_SIZE(ringbuf_size, RINGBUFFER_SIZE);
RING_BUF_DECLARE(ringbuf_raw, RINGBUFFER_SIZE);
static struct ring_buf ringbuf, *pbuf;
static u32_t buffer[RINGBUFFER_SIZE];
static struct {
u8_t length;
u8_t value;
u16_t type;
u32_t buffer[DATA_MAX_SIZE];
} data[] = {
{ 0, 32, 1, {} },
{ 1, 76, 54, { 0x89ab } },
{ 3, 0xff, 0xffff, { 0x0f0f, 0xf0f0, 0xff00 } }
};
/*entry of contexts*/
static void tringbuf_put(void *p)
{
int index = (int)p;
/**TESTPOINT: ring buffer put*/
int ret = ring_buf_item_put(pbuf, data[index].type, data[index].value,
data[index].buffer, data[index].length);
zassert_equal(ret, 0, NULL);
}
static void tringbuf_get(void *p)
{
u16_t type;
u8_t value, size32 = DATA_MAX_SIZE;
u32_t rx_data[DATA_MAX_SIZE];
int ret, index = (int)p;
/**TESTPOINT: ring buffer get*/
ret = ring_buf_item_get(pbuf, &type, &value, rx_data, &size32);
zassert_equal(ret, 0, NULL);
zassert_equal(type, data[index].type, NULL);
zassert_equal(value, data[index].value, NULL);
zassert_equal(size32, data[index].length, NULL);
zassert_equal(memcmp(rx_data, data[index].buffer, size32), 0, NULL);
}
/*test cases*/
void test_ringbuffer_init(void)
{
/**TESTPOINT: init via ring_buf_init*/
ring_buf_init(&ringbuf, RINGBUFFER_SIZE, buffer);
zassert_true(ring_buf_is_empty(&ringbuf), NULL);
zassert_equal(ring_buf_space_get(&ringbuf), RINGBUFFER_SIZE - 1, NULL);
}
void test_ringbuffer_declare_pow2(void)
{
zassert_true(ring_buf_is_empty(&ringbuf_pow2), NULL);
zassert_equal(ring_buf_space_get(&ringbuf_pow2), (1 << POW) - 1, NULL);
}
void test_ringbuffer_declare_size(void)
{
zassert_true(ring_buf_is_empty(&ringbuf_size), NULL);
zassert_equal(ring_buf_space_get(&ringbuf_size), RINGBUFFER_SIZE - 1,
NULL);
}
void test_ringbuffer_put_get_thread(void)
{
pbuf = &ringbuf;
tringbuf_put((void *)0);
tringbuf_put((void *)1);
tringbuf_get((void *)0);
tringbuf_get((void *)1);
tringbuf_put((void *)2);
zassert_false(ring_buf_is_empty(pbuf), NULL);
tringbuf_get((void *)2);
zassert_true(ring_buf_is_empty(pbuf), NULL);
}
void test_ringbuffer_put_get_isr(void)
{
pbuf = &ringbuf;
irq_offload(tringbuf_put, (void *)0);
irq_offload(tringbuf_put, (void *)1);
irq_offload(tringbuf_get, (void *)0);
irq_offload(tringbuf_get, (void *)1);
irq_offload(tringbuf_put, (void *)2);
zassert_false(ring_buf_is_empty(pbuf), NULL);
irq_offload(tringbuf_get, (void *)2);
zassert_true(ring_buf_is_empty(pbuf), NULL);
}
void test_ringbuffer_put_get_thread_isr(void)
{
pbuf = &ringbuf;
tringbuf_put((void *)0);
irq_offload(tringbuf_put, (void *)1);
tringbuf_get((void *)0);
irq_offload(tringbuf_get, (void *)1);
tringbuf_put((void *)2);
irq_offload(tringbuf_get, (void *)2);
}
void test_ringbuffer_pow2_put_get_thread_isr(void)
{
pbuf = &ringbuf_pow2;
tringbuf_put((void *)0);
irq_offload(tringbuf_put, (void *)1);
tringbuf_get((void *)0);
irq_offload(tringbuf_get, (void *)1);
tringbuf_put((void *)1);
irq_offload(tringbuf_get, (void *)1);
}
void test_ringbuffer_size_put_get_thread_isr(void)
{
pbuf = &ringbuf_size;
tringbuf_put((void *)0);
irq_offload(tringbuf_put, (void *)1);
tringbuf_get((void *)0);
irq_offload(tringbuf_get, (void *)1);
tringbuf_put((void *)2);
irq_offload(tringbuf_get, (void *)2);
}
void test_ringbuffer_raw(void)
{
int i;
u8_t inbuf[RINGBUFFER_SIZE];
u8_t outbuf[RINGBUFFER_SIZE];
size_t in_size;
size_t out_size;
/* Initialize test buffer. */
for (i = 0; i < RINGBUFFER_SIZE; i++) {
inbuf[i] = i;
}
for (i = 0; i < 10; i++) {
memset(outbuf, 0, sizeof(outbuf));
in_size = ring_buf_put(&ringbuf_raw, inbuf,
RINGBUFFER_SIZE - 2);
out_size = ring_buf_get(&ringbuf_raw, outbuf,
RINGBUFFER_SIZE - 2);
zassert_true(in_size == RINGBUFFER_SIZE - 2, NULL);
zassert_true(in_size == out_size, NULL);
zassert_true(memcmp(inbuf, outbuf, RINGBUFFER_SIZE - 2) == 0,
NULL);
}
in_size = ring_buf_put(&ringbuf_raw, inbuf,
RINGBUFFER_SIZE);
zassert_equal(in_size, RINGBUFFER_SIZE - 1, NULL);
in_size = ring_buf_put(&ringbuf_raw, inbuf,
1);
zassert_equal(in_size, 0, NULL);
out_size = ring_buf_get(&ringbuf_raw, outbuf,
RINGBUFFER_SIZE);
zassert_true(out_size == RINGBUFFER_SIZE - 1, NULL);
out_size = ring_buf_get(&ringbuf_raw, outbuf,
RINGBUFFER_SIZE + 1);
zassert_true(out_size == 0, NULL);
}
void test_ringbuffer_alloc_put(void)
{
u8_t outputbuf[RINGBUFFER_SIZE];
u8_t inputbuf[] = {1, 2, 3, 4};
u32_t read_size;
u32_t allocated;
u32_t sum_allocated;
u8_t *data;
int err;
ring_buf_init(&ringbuf_raw, RINGBUFFER_SIZE, ringbuf_raw.buf.buf8);
allocated = ring_buf_put_claim(&ringbuf_raw, &data, 1);
sum_allocated = allocated;
zassert_true(allocated == 1U, NULL);
allocated = ring_buf_put_claim(&ringbuf_raw, &data,
RINGBUFFER_SIZE - 1);
sum_allocated += allocated;
zassert_true(allocated == RINGBUFFER_SIZE - 2, NULL);
/* Putting too much returns error */
err = ring_buf_put_finish(&ringbuf_raw, RINGBUFFER_SIZE);
zassert_true(err != 0, NULL);
err = ring_buf_put_finish(&ringbuf_raw, 1);
zassert_true(err == 0, NULL);
err = ring_buf_put_finish(&ringbuf_raw, RINGBUFFER_SIZE - 2);
zassert_true(err == 0, NULL);
read_size = ring_buf_get(&ringbuf_raw, outputbuf,
RINGBUFFER_SIZE - 1);
zassert_true(read_size == (RINGBUFFER_SIZE - 1), NULL);
for (int i = 0; i < 10; i++) {
allocated = ring_buf_put_claim(&ringbuf_raw, &data, 2);
if (allocated == 2U) {
data[0] = inputbuf[0];
data[1] = inputbuf[1];
} else {
data[0] = inputbuf[0];
ring_buf_put_claim(&ringbuf_raw, &data, 1);
data[0] = inputbuf[1];
}
allocated = ring_buf_put_claim(&ringbuf_raw, &data, 2);
if (allocated == 2U) {
data[0] = inputbuf[2];
data[1] = inputbuf[3];
} else {
data[0] = inputbuf[2];
ring_buf_put_claim(&ringbuf_raw, &data, 1);
data[0] = inputbuf[3];
}
err = ring_buf_put_finish(&ringbuf_raw, 4);
zassert_true(err == 0, NULL);
read_size = ring_buf_get(&ringbuf_raw,
outputbuf, 4);
zassert_true(read_size == 4U, NULL);
zassert_true(memcmp(outputbuf, inputbuf, 4) == 0, NULL);
}
}
void test_byte_put_free(void)
{
u8_t indata[] = {1, 2, 3, 4, 5};
int err;
u32_t granted;
u8_t *data;
ring_buf_init(&ringbuf_raw, RINGBUFFER_SIZE, ringbuf_raw.buf.buf8);
/* Ring buffer is empty */
granted = ring_buf_get_claim(&ringbuf_raw, &data, RINGBUFFER_SIZE);
zassert_true(granted == 0U, NULL);
for (int i = 0; i < 10; i++) {
ring_buf_put(&ringbuf_raw, indata,
RINGBUFFER_SIZE-2);
granted = ring_buf_get_claim(&ringbuf_raw, &data,
RINGBUFFER_SIZE);
if (granted == (RINGBUFFER_SIZE-2)) {
zassert_true(memcmp(indata, data, granted) == 0, NULL);
} else if (granted < (RINGBUFFER_SIZE-2)) {
/* When buffer wraps, operation is split. */
u32_t granted_1 = granted;
zassert_true(memcmp(indata, data, granted) == 0, NULL);
granted = ring_buf_get_claim(&ringbuf_raw, &data,
RINGBUFFER_SIZE);
zassert_true((granted + granted_1) ==
RINGBUFFER_SIZE - 2, NULL);
zassert_true(memcmp(&indata[granted_1], data, granted)
== 0, NULL);
} else {
zassert_true(false, NULL);
}
/* Freeing more than possible case. */
err = ring_buf_get_finish(&ringbuf_raw, RINGBUFFER_SIZE-1);
zassert_true(err != 0, NULL);
err = ring_buf_get_finish(&ringbuf_raw, RINGBUFFER_SIZE-2);
zassert_true(err == 0, NULL);
}
}
/*test case main entry*/
void test_main(void)
{
ztest_test_suite(test_ringbuffer_api,
ztest_unit_test(test_ringbuffer_init),/*keep init first!*/
ztest_unit_test(test_ringbuffer_declare_pow2),
ztest_unit_test(test_ringbuffer_declare_size),
ztest_unit_test(test_ringbuffer_put_get_thread),
ztest_unit_test(test_ringbuffer_put_get_isr),
ztest_unit_test(test_ringbuffer_put_get_thread_isr),
ztest_unit_test(test_ringbuffer_pow2_put_get_thread_isr),
ztest_unit_test(test_ringbuffer_size_put_get_thread_isr),
ztest_unit_test(test_ring_buffer_main),
ztest_unit_test(test_ringbuffer_raw),
ztest_unit_test(test_ringbuffer_alloc_put),
ztest_unit_test(test_byte_put_free)
);
ztest_run_test_suite(test_ringbuffer_api);
}
|
ldts/zephyr
|
tests/lib/ringbuffer/src/main.c
|
C
|
apache-2.0
| 11,312
|
---
title: "DL4J와 RNNs (Recurrent Neural Networks)"
layout: kr-default
redirect_from: /kr-usingrnns
---
# DL4J와 RNNs (Recurrent Neural Networks)
이 문서는 RNNs를 DL4J에서 설계/학습하는데 필요한 실용적인 내용을 다룹니다. 이 문서는 RNNs의 배경 지식을 어느 정도 갖추고 있는 독자를 대상으로 작성되었습니다. RNNs의 기본적인 내용은 [초보자를 위한 RNNs과 LSTM 가이드](kr-lstm)를 참고하십시오.
**내용**
* [기본 사항: 데이터 및 네트워크 설정](#basics)
* [RNNs의 학습](trainingfeatures)
* [단기 BPTT (Back Propagation Through Time)](#tbptt)
* [마스킹: 일대다(one-to-many), 다대일(many-to-one), 및 배열 분류](#masking)
* [RNN과 다른 층의 조합](#otherlayertypes)
* [효율적인 RNNs 사용](#rnntimestep)
* [시계열 데이터 가져오기](#data)
* [예제](#examples)
## <a name="basics">기본 사항: 데이터 및 네트워크 구성</a>
현재 DL4J는 RNNs의 여러 유형 중 LSTM(Long Short-Term Memory) 모델(클래스 이름: `GravesLSTM`)을 지원합니다. 앞으로 더 다양한 형태의 RNNs을 지원할 예정입니다.
#### RNNs과 입출력 데이터
일반적인 인공 신경망(feed-forward networks: FFNets)의 구조를 생각해봅시다 (DL4J의 `DenseLayer` 클래스). FFNets은 입력과 출력을 벡터로 표현할 수 있고, 실제 학습에서는 한 번에 여러 데이터를 읽기 때문에 2차원 데이터(데이터 개수 x 입력 벡터의 길이)를 받습니다. 이 2차원 데이터는 데이터 개수 만큼의 행과 입력 벡터의 길이와 같은 크기의 열을 갖는 행렬, 다시 말해 여러 열 벡터(column vector)의 배열(array) 입니다. 예를 들어 한번에 4개의 입력 데이터를 읽어들이고 입력 벡터가 256차원이라면 입력 데이터는 4x256 크기의 행렬입니다. 출력 데이터의 크기도 마찬가지로 계산할 수 있습니다.
RNNs은 좀 다릅니다. 기본적으로 시계열 데이터를 다루기 때문에 입력 데이터의 전체 크기는 3차원(데이터 개수 x 입력 벡터의 길이 x 전체 시간)이 되고 출력은 (데이터 개수 x 출력 벡터의 길이 x 전체 시간)이 됩니다. DL4J 문법으로 설명을 하면 `INDArray`의 `(i,j,k)` 위치의 값은 미니 배치에 있는 `i`번째 데이터에서 `k`번째 시간 단계에 있는 벡터의 `j`번째 성분입니다. 아래 그림을 참고하시기 바랍니다.

#### RnnOutputLayer
`RnnOutputLayer`는 DL4J의 RNNs에서 출력층으로 사용하는 유형입니다. `RnnOutputLayer`는 분류/회귀 작업에 모두 사용 가능하며 현재 모델의 점수를 평가하고 오차를 계산하는 기능을 가지고 있습니다. 이런 기능은 FFNets에서 사용하는 `OutputLayer`와 비슷하지만 데이터의 모양(shape)이 3차원이라는 차이가 있습니다.
`RnnOutputLayer`를 구성하는 방법은 다른 레이어와 동일합니다. 예를 들어 아래 코드는 RNNs의 세 번째 레이어를 분류 작업을 하는 출력층으로 설정합니다.
.layer(2, new RnnOutputLayer.Builder(LossFunction.MCXENT).activation("softmax")
.weightInit(WeightInit.XAVIER).nIn(prevLayerSize).nOut(nOut).build())
문서 하단에 실제 환경에서 이 클래스를 사용하는 예제를 링크해놓았습니다.
## <a name="trainingfeatures">RNNs의 학습</a>
### <a name="tbptt">단기 BPTT(Truncated Back Propagation Through Time)</a>
인공 신경망 학습은 연산량이 아주 많습니다. 그 중에서도 긴 배열로 RNNs을 학습하는 것은 많은 연산량을 소모합니다.
단기 BPTT는 RNNs 학습의 연산량을 줄이기 위해 개발되었습니다.
길이가 12인 시계열 데이터로 RNNs을 학습하는 과정을 상상해보십시오. 데이터 하나로 학습을 하는데 입력->출력으로 12단계의 연산을 거치고, 출력->입력으로 다시 12단계의 backprop 연산을 합니다. (그림 참조)

12단계는 큰 문제가 아닙니다. 그러나 입력으로 들어온 시계열 데이터가 10,000개의 샘플을 가지고 있다면 어마어마한 연산량이 필요합니다. 단 한번의 계수 업데이트에 10,000단계의 입력->출력과(출력 계산) 출력->입력 과정(backprop)을 거쳐야합니다.
이 문제를 해결하기 위해 단기 BPTT는 전체 시계열 데이터를 작게 나눠서 학습을 합니다. 예를 들어 아래 그림은 길이가 12인 시계열 데이터를 길이가 4인 작은 데이터로 나누어 학습하는 과정을 표현한 것입니다. 이 길이는 사용자가 연산량과 데이터의 크기에 따라 설정합니다.

단기 BPTT와 일반적인 BPTT의 전체 연산량은 대략 비슷합니다. 그림을 보면 단기 BPTT도 결국 12번의 출력 계산과 12번의 backprop을 수행합니다. 그러나 이렇게 하면 같은 양의 데이터로 3번의 계수 업데이트가 가능합니다.
단기 BPTT의 단점은 이렇게 잘라낸 구간으로 학습할 경우 장기적인 관계를 학습하지 못한다는 점입니다. 예를 들어 위의 그림에서 t=10인 경우에 t=0일때 정보가 필요한 상황이라면 단기 BPTT는 이 관계를 학습하지 못합니다. 즉 그라디언트가 충분히 흘러가지 못하고 중간에 잘리게 되고, 결과적으로 RNNs의 '기억력'이 짧아집니다.
DL4J에서 단기BPTT를 사용하는 방법은 아주 간단합니다. 아래의 코드를 신경망 구성(configurations)의 `.build()` 전에 입력하면 됩니다.
.backpropType(BackpropType.TruncatedBPTT)
.tBPTTForwardLength(100)
.tBPTTBackwardLength(100)
위의 코드는 RNNs을 길이 100짜리 단기BPTT로 학습하는 코드입니다.
몇 가지 참고하실 내용이 있습니다.
* DL4J의 디폴트 설정은 단기BPTT가 아닌 일반적인 BPTT입니다.
* `tBPTTForwardLength`와 `tBPTTBackwardLength` 옵션으로 단기BPTT의 길이를 설정합니다. 보통 50-200정도의 값이 적당하고 두 값을 같은 값으로 설정합니다. (경우에 따라 `tBPTTBackwardLength`가 더 짧기도 합니다.)
* `tBPTTForwardLength`와 `tBPTTBackwardLength`은 시계열 데이터의 전체 길이보다 짧아야합니다.
### <a name="masking">마스킹: 일대다(one-to-many), 다대일(many-to-one), 및 배열 분류</a>
DL4J는 RNNs 학습과 관련한 패딩(padding) 및 마스킹(masking)을 지원합니다. 패딩과 마스킹을 이용하면 일의 아이디어에 기반한 다양한 관련된 학습 기능들을 지원합니다. 패딩 및 마스킹을 이용하면 일대다/다대일이나 가변 길이 시계열 데이터 상황에서 RNNs을 학습할 수 있습니다.
예를 들어 RNNs으로 학습하려는 데이터가 매 시간 단계마다 발생하지 않는 상황을 가정해봅시다. 아래 그림이 그런 상황입니다. DL4J를 이용하면 아래 그림의 모든 상황에 대처할 수 있습니다.

마스킹과 패딩을 쓰지 않으면 RNNS은 다대다 학습만 가능합니다. 즉, 입력 데이터의 길이가 다 같고, 출력 데이터도 입력 데이터의 길이와 같은 아주 제한된 형태만 가능합니다.
패딩(padding)의 원리는 간단합니다. 한 배치에 길이가 다른 두 개의 데이터가 있는 상황을 가정하겠습니다. 예를 들어 하나는 길이가 100이고 또 하나는 길이가 70인 경우라면, 길이가 70인 데이터에 길이가 30인 행렬을 추가해서 두 데이터가 같은 길이가 되도록 해주면 됩니다. 이 경우에 출력 데이터도 마찬가지로 패딩을 해줍니다.
패딩을 했다면 반드시 마스킹(masking)을 해야합니다. 마스킹이란 데이터에서 어떤 값이 패딩을 한 값(그러므로 학습할 필요가 없는 값)인지를 알려주는 역할을 합니다. 즉, 두 개의 층(입력과 출력에 하나씩)을 추가해서 입력과 출력이 실제로 의미 있는 샘플인지 아니면 패딩이 된 샘플인지를 기록하면 됩니다.
DL4J의 미니 배치에 있는 데이터는 [배치 크기, 입력 벡터 크기, 시간축 길이(timeSeriesLength)]라고 했는데, 패딩은 이 샘플이 패딩이 된건지 아닌지만 알려주면 됩니다. 따라서 마스킹 층은 [배치 크기, 시간축 길이]의 크기를 갖는 2차원 행렬입니다. 0은 데이터가 없는, 즉 패딩이 된 상태이고 1은 반대로 패딩이 아닌 실제 존재하는 데이터 샘플입니다.
아래 그림을 보고 마스킹이 어떻게 적용하는지 이해하시기 바랍니다.

마스킹이 필요하지 않은 경우엔 마스킹 층의 값을 전부 1로 설정하면 됩니다(물론 마스킹이 전혀 필요하지 않는다면 마스킹 층을 굳이 추가하지 않아도 됩니다). 또 경우에 따라 입력층이나 출력층 중 한군데에만 마스킹을 해도 됩니다. 예를 들어 다대일 학습의 경우엔 출력층에만 마스킹을 할 수도 있습니다.
DL4J 사용시 패딩 배열은 데이터를 import하는 단계에서 생성됩니다 (`SequenceRecordReaderDatasetIterator`). 그리고 나면 데이터셋 객체에 포함됩니다. 만일 데이터셋이 마스킹 배열을 포함하고 있다면 `MultiLayerNetwork` 인스턴스는 자동으로 이 마스킹 정보를 이용해 학습합니다.
#### 마스킹을 사용한 학습 평가
학습 결과를 평가할때도 마스킹 층의 유무를 고려해야합니다. 예를 들어 다대일 분류라면 시계열 데이터를 읽고 하나를 출력하기 때문에 이 설정을 평가에 반영해야합니다.
즉, 출력 마스킹층의 값을 평가 과정에 입력해야 합니다. 아래 코드를 참고하시기 바랍니다.
Evaluation.evalTimeSeries(INDArray labels, INDArray predicted, INDArray outputMask)
입력 변수는 순서대로 정답 라벨(3차원 행렬), 예측한 값(3차원 행렬), 그리고 출력 마스킹 정보(2차원 행렬) 입니다. 입력 마스킹 정보는 필요하지 않습니다.
점수를 계산하는 `MultiLayerNetwork.score(DataSet)`는 데이터 셋을 입력으로 받는데 여기에 마스킹 정보가 포함되어 있습니다. 따라서 별도의 마스킹 정보를 입력하지 않아도 자동으로 이를 고려해 점수를 계산합니다.
### <a name="otherlayertypes">RNNs층과 다른 층의 조합</a>
DL4J에서는 RNNs층과 다른 유형의 층을 결합하는 것이 가능합니다. 예를 들어 `GravesLSTM`과 `DenseLayer`를 연결할 수 있습니다. 비디오 데이터가 들어오는 경우엔 컨볼루션 층(Convolutional layer)과 `GravesLSTM`를 결합할 수 있습니다.
이렇게 여러 층을 결합한 신경망이 잘 작동하게 하려면 데이터를 전처리해야합니다. 예를 들어 `CnnToRnnPreProcessor`, `FeedForwardToRnnPreprocessor`를 이용할 수 있습니다. 전처리기 목록은 [여기](https://github.com/deeplearning4j/deeplearning4j/tree/master/deeplearning4j-core/src/main/java/org/deeplearning4j/nn/conf/preprocessor)에 정리되어있습니다. 대부분의 경우 DL4J는 자동으로 이 전처리기를 추가합니다. 아래의 코드를 참고하면 직접 전처리기를 추가할 수 있습니다. 이 예제는 층 1과 2 사이에 전처리기를 추가하는 코드입니다.
.inputPreProcessor(2, new RnnToFeedForwardPreProcessor()).
## <a name="rnntimestep">효율적인 RNNs 사용</a>
DL4J에서 RNNs 출력은 다른 인공 신경망과 마찬가지로 `MultiLayerNetwork.output()`와 `MultiLayerNetwork.feedForward()`를 사용합니다. 주의할 점은 이 두 메서드는 늘 `시간 단계=0`에서 출발한다는 점입니다. 즉, 아무것도 없는 상태에서 새로운 시계열 데이터를 생성하는 경우에 사용하는 메서드입니다.
상황에 따라 실시간으로 데이터를 읽어오면서 결과를 출력해야 할 경우가 있습니다. 만일 그동안 누적된 데이터가 많이 있다면 이렇게 매 번 새로운 시계열 데이터를 생성하는 작업은 엄청난 연산량때문에 사실상 불가능에 가깝습니다. 매 샘플마다 전체 데이터를 다 읽어야 하기 때문입니다.
이런 경우에는 아래의 메서드를 사용합니다.
* `rnnTimeStep(INDArray)`
* `rnnClearPreviousState()`
* `rnnGetPreviousState(int layer)`
* `rnnSetPreviousState(int layer, Map<String,INDArray> state)`
`rnnTimeStep()` 메서드는 `.output()`이나 `.feedForward()`와 달리 RNNs 층의 현재 정보를 저장합니다. 매번 과거의 데이터로 다시 연산을 수행할 필요가 없이 이미 학습된 RNNs 모델에서 `rnnTimeStep()`으로 추가된 데이터에 대한 연산만 수행하며, 그 결과는 완전히 동일합니다.
즉, `MultiLayerNetwork.rnnTimeStep()` 메서드가 수행하는 작업은 아래와 같습니다.
1. 데이터를 입력받고, 만일 은닉층에 기존에 학습해놓은 값이 있다면 그 값을 이용해 결과를 출력합니다.
2. 그리고 기존의 학습 내용을 업데이트합니다.
예를 들어 그동안 100시간 분량의 날씨 예측을 했는데 101시간째 날씨를 예측하고 싶은 경우에, 1시간의 데이터만 추가적으로 공급하면 됩니다. 만일 이 방식이 없다면 시간이 바뀔때마다 100시간, 101시간, 102시간, 103시간.. 분량의 데이터로 다시 학습해야 합니다.

최초에 `rnnTimeStep`이 호출되면 학습이 끝난 뒤에 은닉층의 값이 저장됩니다. 아래 그림의 우측 도식을 보면 이렇게 저장된 값을 오렌지색으로 표시했습니다. 이제 다음 입력이 들어오면 이 값을 사용할 수 있습니다. 반면 좌측은 `output()`을 사용한 경우인데, 이 경우엔 학습이 끝난 뒤에 이 값을 저장하지 않습니다.

그 차이는 데이터가 하나 더 추가되었을 때 현격하게 벌어집니다.
1. 위 그림의 우측을 보면 단 하나의 데이터만, 즉 102시간째의 데이터만 추가된 것을 알 수 있습니다.
2. 따라서 하나의 입력만 추가적으로 학습하면 됩니다.
3. 그리고 갱신된 값은 다시 저장되기 때문에 103시간째 데이터가 추가되어도 역시 효율적인 연산을 수행할 수 있습니다.
상황에 따라 저장된 값을 지우고 완전히 새로 시작해야 할 수도 있습니다. 그런 경우엔 `MultiLayerNetwork.rnnClearPreviousState()` 메서드를 호출하면 됩니다.
만일 학습해놓은 데이터를 저장하거나 불러오길 원한다면 `rnnGetPreviousState` 및 `rnnSetPreviousState` 메서드를 이용하면 됩니다. 이 메서드는 map을 입력/반환하는데, 이 맵의 key값을 주의하시기 바랍니다. 예를 들어 LSTM 모델의 경우 출력 활성값과 메모리 셀 상태를 저장해야합니다.
그 외 참고사항:
- `rnnTimeStep()` 메서드로 동시에 여러 개의 예측을 할 수 있습니다. 예를 들어 하나의 날씨 모델을 가지고 여러 지역의 내일 날씨를 예측하는 경우가 이에 해당합니다. 이 경우엔 각 행에 (입력 데이터의 0차원에) 각 지역의 데이터를 넣으면 됩니다.
- 만일 RNNs 모델에 기존에 저장된 정보가 없다면 (즉 최초로 실행하는 경우거나 `rnnClearPreviousState()`를 실행한 직후라면) 디폴트로 설정되어있는 초기값(0)이 사용됩니다.
- `rnnTimeStep`은 꼭 하나의 시간 단계에만 적용될 필요가 없습니다. 예를 들어 100시간의 날씨 모델에 1시간이 아니라 여러 시간을 한번에 추가하는 것이 가능합니다. 다만 주의할 점이 있습니다.
- 한 개의 데이터만 추가하는 경우엔 입력은 [데이터의 개수, 입력 벡터의 길이]가 됩니다.
- 여러 시간 단계의 데이터를 추가하는 경우엔 입출력은 3차원 행렬입니다. [데이터의 개수, 입력 벡터의 길이, 시간 단계의 개수]가 됩니다.
- 만일 처음에 `rnnTimeStep()`에 3개의 시간 단계를 사용했다면, 이후에 이 메서드를 사용할 때에도 같은 식으로 3개의 시간 단계를 사용해야합니다. 이 시간 단계를 바꾸는 방법은 `rnnClearPreviousState()`로 RNNs의 학습을 초기화하는 수 밖에 없습니다.
- `rnnTimeStep`은 RNNs모델의 전체 구조에 영향을 주지 않습니다.
- `rnnTimeStep`은 RNNs모델의 은닉층의 개수와 관계 없이 작동합니다.
- `RnnOutputLayer` 층은 피드백 연결이 없기 때문에 특별히 저장할 학습 정보를 갖고있지 않습니다.
## <a name="data">시계열 데이터 가져오기</a>
일대다, 다대일 등 다양한 구성때문에 시계열 데이터도 다양한 종류가 필요합니다. 이제부터 DL4J에서 어떻게 데이터를 불러오는지 다루겠습니다.
여기에서는 DL4J의 `SequenceRecordReaderDataSetIterator`와 Canova의 `CSVSequenceRecordReader`를 사용하는 방법을 설명하려고 합니다. 이 방법은 시계열 데이터마다 별도의 파일로 저장된 CSV 포맷에서 데이터를 불러올 수 있습니다.
아래와 같은 경우에 사용이 가능합니다.
* 가변 길이 시계열 입력
* 일대다, 다대일 데이터 불러오기 (입력 데이터와 라벨이 별도의 파일에 저장된 경우)
* 라벨 값을 one-hot-vector로 변환 (예: [1,2] -> [[0,1,0], [0,0,1]])
* 데이터 파일에서 헤더에 해당하는 행의 데이터 건너 뛰기 (주석, 머릿말 등)
항상 데이터 파일의 각 줄(line)이 시간 단계 하나에 해당한다는 것을 유의하시기 바랍니다.
(아래의 예제와 별도로 [이 테스트 코드](https://github.com/deeplearning4j/deeplearning4j/blob/master/deeplearning4j-core/src/test/java/org/deeplearning4j/datasets/canova/RecordReaderDataSetiteratorTest.java)를 참고하셔도 좋습니다.)
#### 예제 1: 동일한 길이의 시계열 입력/라벨이 별도의 파일에 저장된 경우
10개의 시계열 데이터로 이루어진 학습 데이터가 있다고 가정해봅시다. 즉 입력 데이터가 10개, 출력 데이터가 10개로 총 20개의 파일이 있는 경우입니다. 그리고 각 시계열 데이터는 같은 수의 시간 단계로 이루어져 있습니다. 다시 말해 행의 수가 같습니다.
[SequenceRecordReaderDataSetIterator](https://github.com/deeplearning4j/deeplearning4j/blob/master/deeplearning4j-core/src/main/java/org/deeplearning4j/datasets/canova/SequenceRecordReaderDataSetIterator.java) 와 [CSVSequenceRecordReader](https://github.com/deeplearning4j/Canova/blob/master/canova-api/src/main/java/org/canova/api/records/reader/impl/CSVSequenceRecordReader.java)를 사용하려면 우선 입력과 출력을 위해 두 개의 `CSVSequenceRecordReader` 인스턴스를 생성합니다.
SequenceRecordReader featureReader = new CSVSequenceRecordReader(1, ",");
SequenceRecordReader labelReader = new CSVSequenceRecordReader(1, ",");
입력 변수를 보면 `1`은 데이터 파일의 맨 위 한 줄을 무시한다는 의미이고 우리가 읽어올 데이터가 콤마로 나뉘어져 있다는 것을 알려줍니다.
이제 이 두 인스턴스를 초기화해야합니다. 여기에서 초기화는 파일의 위치를 지정해주는 과정인데, `InputSplit` 객체를 사용하겠습니다.
파일의 이름 포맷이 `myInput_%d.csv`, `myLabels_%d.csv`라고 가정하겠습니다. [NumberedFileInputSplit](https://github.com/deeplearning4j/Canova/blob/master/canova-api/src/main/java/org/canova/api/split/NumberedFileInputSplit.java)를 쓰면 아래와 같습니다.
featureReader.initialize(new NumberedFileInputSplit("/path/to/data/myInput_%d.csv", 0, 9));
labelReader.initialize(new NumberedFileInputSplit(/path/to/data/myLabels_%d.csv", 0, 9));
이렇게 하면 0에서 9까지 (0과 9를 모두 포함) 사용합니다.
마지막으로, `SequenceRecordReaderdataSetIterator` 객체를 생성합니다.
DataSetIterator iter = new SequenceRecordReaderDataSetIterator(featureReader, labelReader, miniBatchSize, numPossibleLabels, regression);
이제 이 `DataSetIterator` 객체가 `MultiLayerNetwork.fit()`의 입력 변수로 전달되면 학습이 시작됩니다.
`miniBatchSize`는 미니배치의 시계열 개수를 지정합니다. 이 경우에 만일 미니 배치를 5로 지정하면 각각 5개의 시계열을 가진 미니배치 2개를 생성합니다.
아래 팁을 참고하십시오.
* 분류 문제: `numPossibleLabels`은 데이터 셋에 있는 범주의 개수입니다. `regression = false` 옵션을 지정하십시오.
* 레이블 데이터: 한 줄에 하나의 값. (one-hot-vector가 아닌 정수)
* 레이블 데이터는 자동으로 one-hot-vector로 변환됩니다.
* 회귀 문제: `numPossibleLabels`의 값은 무시됩니다(아무 것이나 설정하십시오). `regression = true`로 지정하십시오.
* 레이블 데이터: 회귀이므로 어떤 값이든지 가능합니다.
* `regression = true`인 경우엔 라벨에 추가적인 처리(예:반올림, 범주 지정)를 하지 않습니다.
#### 예제 2: 하나의 파일에서 동일한 길이의 입/출력 시계열 데이터를 포함한 경우
이번엔 입력과 출력이 하나의 파일에 들어있는 경우를 가정하겠습니다. 이 경우에도 다른 시계열은 별도의 파일에 존재합니다. 즉 10개의 시계열이 존재하되 10개의 파일에 각각의 입력/출력을 포함하는 경우입니다.
(DL4J 0.4-rc3.8 버전을 기준) 이 방법은 출력 하나의 열로 이루어져있어야 한다는 제한이 있습니다. 즉 [1,2,3,2,2,0,3,3,2..]같은 범주의 인덱스거나, 스칼라 값의 회귀 문제인 경우입니다.
이 경우에도 위와 비슷하지만 입/출력이 하나의 파일에 있으므로 입/출력 파일 리더를 별도로 열지 않고 하나를 사용합니다. 이번에도 파일명이 `myData_%d.csv` 포맷이라고 가정하겠습니다.
SequenceRecordReader reader = new CSVSequenceRecordReader(1, ",");
reader.initialize(new NumberedFileInputSplit("/path/to/data/myData_%d.csv", 0, 9));
DataSetIterator iterClassification = new SequenceRecordReaderDataSetIterator(reader, miniBatchSize, numPossibleLabels, labelIndex, false);
`miniBatchSize` 및 `numPossibleLabels`는 앞의 예제와 동일합니다. 추가되는 인수는 `labelIndex`인데, 이 값은 입력 데이터 행렬에서 몇 번째 열에 라벨이 있는지를 지정합니다(0을 기준으로 합니다). 예를 들어, 레이블이 다섯 번째 항목에 있는 경우, `labelIndex = 4`를 사용하십시오.
회귀 문제라면 아래 코드를 이용합니다.
DataSetIterator iterRegression = new SequenceRecordReaderDataSetIterator(reader, miniBatchSize, -1, labelIndex, true);
`numPossibleLabels` 인수는 회귀 분석에 사용되지 않는 것을 주의하시기 바랍니다.
#### 예제 3: 다른 길이의 시계열 (다대다)
이번엔 시계열 데이터의 길이가 다양한 경우를 보겠습니다. 이 경우에도 각 데이터의 입력/출력의 길이는 같습니다. 예를 들어 2개의 데이터가 있다면 1번 데이터는 입력과 출력 모두 100의 길이를, 2번 데이터는 입력과 출력 모두 150의 길이를 갖는 경우입니다.
이번에도 위의 예제처럼 `CSVSequenceRecordReader` 와 `SequenceRecordReaderDataSetIterator`를 사용하지만 다른 생성자를 사용합니다.
DataSetIterator variableLengthIter = new SequenceRecordReaderDataSetIterator(featureReader, labelReader, miniBatchSize, numPossibleLabels, regression, SequenceRecordReaderDataSetIterator.AlignmentMode.ALIGN_END);
인수를 잘 보면 `AlignmentMode.ALIGN_END` 추가하였고 나머지는 앞의 예제와 동일합니다. 이렇게 `AlignmentMode`를 지정해주면 `SequenceRecordReaderDataSetIterator`는 아래의 경우를 고려하여 데이터를 읽어옵니다.
1. 시계열이 다른 길이를 가질 수 있다.
2. 각 시계열의 맨 마지막 시점을 기준으로 동기화한다.
만일 `AlignmentMode.ALIGN_START`를 사용하면 각 시계열의 맨 처음 시점을 기준으로 동기화가 일어납니다.
또 하나 주의사항은, 가변 길이의 경우 항상 0부터 시간을 셉니다. (필요한 경우엔 뒤에 0이 패딩됩니다.)
예제 3은 마스킹 정보가 필요하기 때문에 `variableLengthIter` 인스턴스는 마스킹 배열을 포함합니다.
#### 예제 4: 다대일 및 다대다
예제 3에서 다룬 `AlignmentMode`를 이용해 RNN 다대일 분류기를 구현할 수 있습니다. 우선, 아래의 상황을 가정합니다.
* 입력 및 레이블은 별도의 파일에 저장
* 레이블은 (예제 2처럼) 하나의 열로 구성 (범주 인덱스 또는 스칼라 값 회귀 분석)
* 입력 길이는 데이터마다 달라질 수 있음
우선 아래의 생성자는 예제 3과 동일합니다.
DataSetIterator variableLengthIter = new SequenceRecordReaderDataSetIterator(featureReader, labelReader, miniBatchSize, numPossibleLabels, regression, SequenceRecordReaderDataSetIterator.AlignmentMode.ALIGN_END);
정렬 모드는 간단합니다. 다른 길이의 시계열을 어딜 기준으로 정렬할지를 지정합니다. 아래 그림의 좌/우를 비교하면 이해가 쉽습니다.

일대다의 경우는 위의 그림에서 네 번째 경우와 비슷합니다. `AlignmentMode.ALIGN_START`를 사용하면 됩니다.
여러 학습 시계열 데이터를 불러올 경우에 각 파일 내부적으로 정렬이 이루어집니다.

#### 다른 방법: 사용자 정의 DataSetIterator 구현하기
지금까지는 미리 구현된 클래스를 이용하는 방법을 알아봤습니다. 더 복잡한 기능이 필요한 경우엔 직접 [DataSetIterator](https://github.com/deeplearning4j/nd4j/blob/master/nd4j-api/src/main/java/org/nd4j/linalg/dataset/api/iterator/DataSetIterator.java)를 구현하는 방법이 있습니다. 간단히 말하면 `DataSetIterator`는 `DataSet` 객체를 반복 처리하는 인터페이스일 뿐 입니다.
하지만 이 방법은 상당히 로우레벨의 작업입니다. `DataSetIterator`를 구현하려면 직접 입력/레이블의 마스크 어레이를 구현하고 적합한 `INDArrays`를 생성해야합니다. 물론, 그 대신에 데이터를 정확히 어떻게 불러오고 사용하는지를 이해할 수 있고 더 다양한 학습 상황을 구현할 수 있습니다.
[tex/character 예제](https://github.com/deeplearning4j/dl4j-examples/blob/master/src/main/java/org/deeplearning4j/examples/rnn/CharacterIterator.java)와 [Word2Vec move review sentiment 예제](https://github.com/deeplearning4j/dl4j-examples/blob/master/src/main/java/org/deeplearning4j/examples/word2vec/sentiment/SentimentExampleIterator.java)에서 사용하는 iterator를 참고하시기 바랍니다.
## <a name="examples">예제</a>
DL4J는 현재 세 가지 RNNs 예제를 제공합니다.
* [글자(character) 모델링 예제](https://github.com/deeplearning4j/dl4j-examples/blob/master/src/main/java/org/deeplearning4j/examples/rnn/GravesLSTMCharModellingExample.java)로, 셰익스피어의 작품을 글자(character) 기반으로 학습하고 생성합니다.
* [간단한 비디오 프레임 분류 예제](https://github.com/deeplearning4j/dl4j-examples/blob/master/src/main/java/org/deeplearning4j/examples/video/VideoClassificationExample.java)로, 비디오 (.mp4 형식)를 불러와서 각 프레임의 객체를 분류합니다.
* [Word2vec 시퀀스 분류 예제](https://github.com/deeplearning4j/dl4j-examples/blob/master/src/main/java/org/deeplearning4j/examples/word2vec/sentiment/Word2VecSentimentRNN.java)는 영화 리뷰를 긍정적/부정적 리뷰로 분류하는 예제이며 사전에 학습된 단어 벡터와 RNNs을 사용합니다.
|
YeewenTan/YeewenTan.github.io
|
kr/kr-usingrnns.md
|
Markdown
|
apache-2.0
| 28,458
|
/*
* Copyright 2017-2022 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.mediaconvert.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.mediaconvert.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* DolbyVisionLevel6MetadataMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class DolbyVisionLevel6MetadataMarshaller {
private static final MarshallingInfo<Integer> MAXCLL_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("maxCll").build();
private static final MarshallingInfo<Integer> MAXFALL_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("maxFall").build();
private static final DolbyVisionLevel6MetadataMarshaller instance = new DolbyVisionLevel6MetadataMarshaller();
public static DolbyVisionLevel6MetadataMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(DolbyVisionLevel6Metadata dolbyVisionLevel6Metadata, ProtocolMarshaller protocolMarshaller) {
if (dolbyVisionLevel6Metadata == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(dolbyVisionLevel6Metadata.getMaxCll(), MAXCLL_BINDING);
protocolMarshaller.marshall(dolbyVisionLevel6Metadata.getMaxFall(), MAXFALL_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
|
aws/aws-sdk-java
|
aws-java-sdk-mediaconvert/src/main/java/com/amazonaws/services/mediaconvert/model/transform/DolbyVisionLevel6MetadataMarshaller.java
|
Java
|
apache-2.0
| 2,358
|
/*
* Copyright 2017-2022 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.s3control.model.transform;
import javax.xml.stream.events.XMLEvent;
import javax.annotation.Generated;
import com.amazonaws.services.s3control.model.*;
import com.amazonaws.transform.Unmarshaller;
import com.amazonaws.transform.StaxUnmarshallerContext;
import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*;
/**
* MultiRegionAccessPointRegionalResponse StAX Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class MultiRegionAccessPointRegionalResponseStaxUnmarshaller implements Unmarshaller<MultiRegionAccessPointRegionalResponse, StaxUnmarshallerContext> {
public MultiRegionAccessPointRegionalResponse unmarshall(StaxUnmarshallerContext context) throws Exception {
MultiRegionAccessPointRegionalResponse multiRegionAccessPointRegionalResponse = new MultiRegionAccessPointRegionalResponse();
int originalDepth = context.getCurrentDepth();
int targetDepth = originalDepth + 1;
if (context.isStartOfDocument())
targetDepth += 1;
while (true) {
XMLEvent xmlEvent = context.nextEvent();
if (xmlEvent.isEndDocument())
return multiRegionAccessPointRegionalResponse;
if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {
if (context.testExpression("Name", targetDepth)) {
multiRegionAccessPointRegionalResponse.setName(StringStaxUnmarshaller.getInstance().unmarshall(context));
continue;
}
if (context.testExpression("RequestStatus", targetDepth)) {
multiRegionAccessPointRegionalResponse.setRequestStatus(StringStaxUnmarshaller.getInstance().unmarshall(context));
continue;
}
} else if (xmlEvent.isEndElement()) {
if (context.getCurrentDepth() < originalDepth) {
return multiRegionAccessPointRegionalResponse;
}
}
}
}
private static MultiRegionAccessPointRegionalResponseStaxUnmarshaller instance;
public static MultiRegionAccessPointRegionalResponseStaxUnmarshaller getInstance() {
if (instance == null)
instance = new MultiRegionAccessPointRegionalResponseStaxUnmarshaller();
return instance;
}
}
|
aws/aws-sdk-java
|
aws-java-sdk-s3control/src/main/java/com/amazonaws/services/s3control/model/transform/MultiRegionAccessPointRegionalResponseStaxUnmarshaller.java
|
Java
|
apache-2.0
| 2,944
|
def handle(controller_slice):
from core.models import ControllerSlice, Slice
try:
my_status_code = int(controller_slice.backend_status[0])
try:
his_status_code = int(controller_slice.slice.backend_status[0])
except:
his_status_code = 0
if (my_status_code not in [0,his_status_code]):
controller_slice.slice.backend_status = controller_slice.backend_status
controller_slice.slice.save(update_fields = ['backend_status'])
except Exception,e:
print str(e)
pass
|
wathsalav/xos
|
xos/model_policies/model_policy_ControllerSlice.py
|
Python
|
apache-2.0
| 573
|
# Aster araucanus (Phil.) Kuntze SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Grindelia anethifolia/ Syn. Aster araucanus/README.md
|
Markdown
|
apache-2.0
| 187
|
// ProgramOptions.h
// Created by Caner Korkmaz on 20/5/2017.
// Copyright 2017 Caner Korkmaz
//
#ifndef SOCKETPLAY_PROGRAMOPTIONSPARSER_H
#define SOCKETPLAY_PROGRAMOPTIONSPARSER_H
#include <vector>
#include <string>
#include <memory>
#include <tuple>
#include <boost/program_options.hpp>
#include "ProgramMode.h"
namespace socketplay {
/**
* @brief Helper for parsing command line options, uses boost::program_options
*/
class ProgramOptionsParser {
public:
/**
* Initiates parser for command line arguments
* @param arguments Command Line Arguments
*/
explicit ProgramOptionsParser(std::vector<std::string>&& arguments);
/// Parser for stream options, checks whether the mode is true
StreamOptions parse_stream_options();
/// Parser for stream file options, checks whether the mode is true
StreamFileOptions parse_stream_file_options();
/// Parser for play options, checks whether the mode is true
PlayOptions parse_play_options();
// TODO: Add parser for config file
/// Variables map parsed from program options
const boost::program_options::variables_map &variables_map() const { return variables_map_; }
/// Checks whether an options exists
bool has(const std::string &variable) const { return variables_map_.count(variable) != 0; }
/**
* @brief Helper to get variable from variables map and convert to required type
* @pre The variable should exist and be of type T
* @tparam T Type of the requested variable
* @param variable Variable to get from the map
* @return Const ref of type T to given variable from options map
*/
template<typename T>
const T &get(const std::string &variable) const { return variables_map_[variable].as<T>(); }
/**
* @brief Helper to get variable from variables map if it exists and convert to required type,
* throws otherwise
* @tparam T Type of the requested variable
* @tparam Error Type of error to throw, defaults to std::runtime_error
* @param variable Variable to get from the map
* @param error Error message to throw if the variable doesnt exist, defaults to ""
* @throws Error if the variable doesn't exist
* @return Const ref of type T to given variable from options map
*/
template<typename T, typename Error = std::runtime_error>
const T &get_checked(const std::string &variable, const std::string &error = "") const {
if (!has(variable))
throw Error(error);
return variables_map_[variable].as<T>();
}
/**
* Gets specified mode
* @return Mode got from arguments
*/
ProgramMode mode() const { return mode_; }
/// Returns the generated help message
const std::string &help_message() const { return help_message_; }
private:
boost::program_options::options_description general_options_;
boost::program_options::positional_options_description positional_options_;
boost::program_options::options_description stream_options_;
boost::program_options::options_description stream_file_options_;
boost::program_options::options_description play_options_;
boost::program_options::options_description all_options_;
boost::program_options::variables_map variables_map_;
std::string help_message_;
std::vector<std::string> arguments_;
std::vector<std::string> unrecognized_;
ProgramMode mode_;
};
}
#endif //SOCKETPLAY_PROGRAMOPTIONS_H
|
Kausta/SocketPlay
|
include/ProgramOptionsParser.h
|
C
|
apache-2.0
| 3,431
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Subsets — SymPy 1.0.1.dev documentation</title>
<link rel="stylesheet" href="../../_static/default.css" type="text/css" />
<link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
<link rel="stylesheet" href="http://96.sympy-live-tests.appspot.com/static/live-core.css" type="text/css" />
<link rel="stylesheet" href="http://96.sympy-live-tests.appspot.com/static/live-autocomplete.css" type="text/css" />
<link rel="stylesheet" href="http://96.sympy-live-tests.appspot.com/static/live-sphinx.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: '../../',
VERSION: '1.0.1.dev',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true
};
</script>
<script type="text/javascript" src="../../_static/jquery.js"></script>
<script type="text/javascript" src="../../_static/underscore.js"></script>
<script type="text/javascript" src="../../_static/doctools.js"></script>
<script type="text/javascript" src="http://96.sympy-live-tests.appspot.com/static/utilities.js"></script>
<script type="text/javascript" src="http://96.sympy-live-tests.appspot.com/static/external/classy.js"></script>
<script type="text/javascript" src="http://96.sympy-live-tests.appspot.com/static/live-core.js"></script>
<script type="text/javascript" src="http://96.sympy-live-tests.appspot.com/static/live-autocomplete.js"></script>
<script type="text/javascript" src="http://96.sympy-live-tests.appspot.com/static/live-sphinx.js"></script>
<script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML-full"></script>
<link rel="shortcut icon" href="../../_static/sympy-notailtext-favicon.ico"/>
<link rel="top" title="SymPy 1.0.1.dev documentation" href="../../index.html" />
<link rel="up" title="Combinatorics Module" href="index.html" />
<link rel="next" title="Gray Code" href="graycode.html" />
<link rel="prev" title="Prufer Sequences" href="prufer.html" />
<meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9" />
</head>
<body role="document">
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="module-sympy.combinatorics.subsets">
<span id="subsets"></span><span id="combinatorics-subsets"></span><h1>Subsets<a class="headerlink" href="#module-sympy.combinatorics.subsets" title="Permalink to this headline">¶</a></h1>
<dl class="class">
<dt id="sympy.combinatorics.subsets.Subset">
<em class="property">class </em><code class="descclassname">sympy.combinatorics.subsets.</code><code class="descname">Subset</code><a class="reference internal" href="../../_modules/sympy/combinatorics/subsets.html#Subset"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#sympy.combinatorics.subsets.Subset" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents a basic subset object.</p>
<p>We generate subsets using essentially two techniques,
binary enumeration and lexicographic enumeration.
The Subset class takes two arguments, the first one
describes the initial subset to consider and the second
describes the superset.</p>
<p class="rubric">Examples</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">sympy.combinatorics.subsets</span> <span class="k">import</span> <span class="n">Subset</span>
<span class="gp">>>> </span><span class="n">a</span> <span class="o">=</span> <span class="n">Subset</span><span class="p">([</span><span class="s1">'c'</span><span class="p">,</span> <span class="s1">'d'</span><span class="p">],</span> <span class="p">[</span><span class="s1">'a'</span><span class="p">,</span> <span class="s1">'b'</span><span class="p">,</span> <span class="s1">'c'</span><span class="p">,</span> <span class="s1">'d'</span><span class="p">])</span>
<span class="gp">>>> </span><span class="n">a</span><span class="o">.</span><span class="n">next_binary</span><span class="p">()</span><span class="o">.</span><span class="n">subset</span>
<span class="go">['b']</span>
<span class="gp">>>> </span><span class="n">a</span><span class="o">.</span><span class="n">prev_binary</span><span class="p">()</span><span class="o">.</span><span class="n">subset</span>
<span class="go">['c']</span>
</pre></div>
</div>
<dl class="classmethod">
<dt id="sympy.combinatorics.subsets.Subset.bitlist_from_subset">
<em class="property">classmethod </em><code class="descname">bitlist_from_subset</code><span class="sig-paren">(</span><em>subset</em>, <em>superset</em><span class="sig-paren">)</span><a class="reference internal" href="../../_modules/sympy/combinatorics/subsets.html#Subset.bitlist_from_subset"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#sympy.combinatorics.subsets.Subset.bitlist_from_subset" title="Permalink to this definition">¶</a></dt>
<dd><p>Gets the bitlist corresponding to a subset.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference internal" href="#sympy.combinatorics.subsets.Subset.subset_from_bitlist" title="sympy.combinatorics.subsets.Subset.subset_from_bitlist"><code class="xref py py-obj docutils literal"><span class="pre">subset_from_bitlist</span></code></a></p>
</div>
<p class="rubric">Examples</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">sympy.combinatorics.subsets</span> <span class="k">import</span> <span class="n">Subset</span>
<span class="gp">>>> </span><span class="n">Subset</span><span class="o">.</span><span class="n">bitlist_from_subset</span><span class="p">([</span><span class="s1">'c'</span><span class="p">,</span> <span class="s1">'d'</span><span class="p">],</span> <span class="p">[</span><span class="s1">'a'</span><span class="p">,</span> <span class="s1">'b'</span><span class="p">,</span> <span class="s1">'c'</span><span class="p">,</span> <span class="s1">'d'</span><span class="p">])</span>
<span class="go">'0011'</span>
</pre></div>
</div>
</dd></dl>
<dl class="attribute">
<dt id="sympy.combinatorics.subsets.Subset.cardinality">
<code class="descname">cardinality</code><a class="headerlink" href="#sympy.combinatorics.subsets.Subset.cardinality" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the number of all possible subsets.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference internal" href="#sympy.combinatorics.subsets.Subset.subset" title="sympy.combinatorics.subsets.Subset.subset"><code class="xref py py-obj docutils literal"><span class="pre">subset</span></code></a>, <a class="reference internal" href="#sympy.combinatorics.subsets.Subset.superset" title="sympy.combinatorics.subsets.Subset.superset"><code class="xref py py-obj docutils literal"><span class="pre">superset</span></code></a>, <a class="reference internal" href="#sympy.combinatorics.subsets.Subset.size" title="sympy.combinatorics.subsets.Subset.size"><code class="xref py py-obj docutils literal"><span class="pre">size</span></code></a>, <a class="reference internal" href="#sympy.combinatorics.subsets.Subset.superset_size" title="sympy.combinatorics.subsets.Subset.superset_size"><code class="xref py py-obj docutils literal"><span class="pre">superset_size</span></code></a></p>
</div>
<p class="rubric">Examples</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">sympy.combinatorics.subsets</span> <span class="k">import</span> <span class="n">Subset</span>
<span class="gp">>>> </span><span class="n">a</span> <span class="o">=</span> <span class="n">Subset</span><span class="p">([</span><span class="s1">'c'</span><span class="p">,</span> <span class="s1">'d'</span><span class="p">],</span> <span class="p">[</span><span class="s1">'a'</span><span class="p">,</span> <span class="s1">'b'</span><span class="p">,</span> <span class="s1">'c'</span><span class="p">,</span> <span class="s1">'d'</span><span class="p">])</span>
<span class="gp">>>> </span><span class="n">a</span><span class="o">.</span><span class="n">cardinality</span>
<span class="go">16</span>
</pre></div>
</div>
</dd></dl>
<dl class="method">
<dt id="sympy.combinatorics.subsets.Subset.iterate_binary">
<code class="descname">iterate_binary</code><span class="sig-paren">(</span><em>k</em><span class="sig-paren">)</span><a class="reference internal" href="../../_modules/sympy/combinatorics/subsets.html#Subset.iterate_binary"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#sympy.combinatorics.subsets.Subset.iterate_binary" title="Permalink to this definition">¶</a></dt>
<dd><p>This is a helper function. It iterates over the
binary subsets by k steps. This variable can be
both positive or negative.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference internal" href="#sympy.combinatorics.subsets.Subset.next_binary" title="sympy.combinatorics.subsets.Subset.next_binary"><code class="xref py py-obj docutils literal"><span class="pre">next_binary</span></code></a>, <a class="reference internal" href="#sympy.combinatorics.subsets.Subset.prev_binary" title="sympy.combinatorics.subsets.Subset.prev_binary"><code class="xref py py-obj docutils literal"><span class="pre">prev_binary</span></code></a></p>
</div>
<p class="rubric">Examples</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">sympy.combinatorics.subsets</span> <span class="k">import</span> <span class="n">Subset</span>
<span class="gp">>>> </span><span class="n">a</span> <span class="o">=</span> <span class="n">Subset</span><span class="p">([</span><span class="s1">'c'</span><span class="p">,</span> <span class="s1">'d'</span><span class="p">],</span> <span class="p">[</span><span class="s1">'a'</span><span class="p">,</span> <span class="s1">'b'</span><span class="p">,</span> <span class="s1">'c'</span><span class="p">,</span> <span class="s1">'d'</span><span class="p">])</span>
<span class="gp">>>> </span><span class="n">a</span><span class="o">.</span><span class="n">iterate_binary</span><span class="p">(</span><span class="o">-</span><span class="mi">2</span><span class="p">)</span><span class="o">.</span><span class="n">subset</span>
<span class="go">['d']</span>
<span class="gp">>>> </span><span class="n">a</span> <span class="o">=</span> <span class="n">Subset</span><span class="p">([</span><span class="s1">'a'</span><span class="p">,</span> <span class="s1">'b'</span><span class="p">,</span> <span class="s1">'c'</span><span class="p">],</span> <span class="p">[</span><span class="s1">'a'</span><span class="p">,</span> <span class="s1">'b'</span><span class="p">,</span> <span class="s1">'c'</span><span class="p">,</span> <span class="s1">'d'</span><span class="p">])</span>
<span class="gp">>>> </span><span class="n">a</span><span class="o">.</span><span class="n">iterate_binary</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span><span class="o">.</span><span class="n">subset</span>
<span class="go">[]</span>
</pre></div>
</div>
</dd></dl>
<dl class="method">
<dt id="sympy.combinatorics.subsets.Subset.iterate_graycode">
<code class="descname">iterate_graycode</code><span class="sig-paren">(</span><em>k</em><span class="sig-paren">)</span><a class="reference internal" href="../../_modules/sympy/combinatorics/subsets.html#Subset.iterate_graycode"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#sympy.combinatorics.subsets.Subset.iterate_graycode" title="Permalink to this definition">¶</a></dt>
<dd><p>Helper function used for prev_gray and next_gray.
It performs k step overs to get the respective Gray codes.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference internal" href="#sympy.combinatorics.subsets.Subset.next_gray" title="sympy.combinatorics.subsets.Subset.next_gray"><code class="xref py py-obj docutils literal"><span class="pre">next_gray</span></code></a>, <a class="reference internal" href="#sympy.combinatorics.subsets.Subset.prev_gray" title="sympy.combinatorics.subsets.Subset.prev_gray"><code class="xref py py-obj docutils literal"><span class="pre">prev_gray</span></code></a></p>
</div>
<p class="rubric">Examples</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">sympy.combinatorics.subsets</span> <span class="k">import</span> <span class="n">Subset</span>
<span class="gp">>>> </span><span class="n">a</span> <span class="o">=</span> <span class="n">Subset</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">],</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">])</span>
<span class="gp">>>> </span><span class="n">a</span><span class="o">.</span><span class="n">iterate_graycode</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span><span class="o">.</span><span class="n">subset</span>
<span class="go">[1, 4]</span>
<span class="gp">>>> </span><span class="n">a</span><span class="o">.</span><span class="n">iterate_graycode</span><span class="p">(</span><span class="o">-</span><span class="mi">2</span><span class="p">)</span><span class="o">.</span><span class="n">subset</span>
<span class="go">[1, 2, 4]</span>
</pre></div>
</div>
</dd></dl>
<dl class="method">
<dt id="sympy.combinatorics.subsets.Subset.next_binary">
<code class="descname">next_binary</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="../../_modules/sympy/combinatorics/subsets.html#Subset.next_binary"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#sympy.combinatorics.subsets.Subset.next_binary" title="Permalink to this definition">¶</a></dt>
<dd><p>Generates the next binary ordered subset.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference internal" href="#sympy.combinatorics.subsets.Subset.prev_binary" title="sympy.combinatorics.subsets.Subset.prev_binary"><code class="xref py py-obj docutils literal"><span class="pre">prev_binary</span></code></a>, <a class="reference internal" href="#sympy.combinatorics.subsets.Subset.iterate_binary" title="sympy.combinatorics.subsets.Subset.iterate_binary"><code class="xref py py-obj docutils literal"><span class="pre">iterate_binary</span></code></a></p>
</div>
<p class="rubric">Examples</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">sympy.combinatorics.subsets</span> <span class="k">import</span> <span class="n">Subset</span>
<span class="gp">>>> </span><span class="n">a</span> <span class="o">=</span> <span class="n">Subset</span><span class="p">([</span><span class="s1">'c'</span><span class="p">,</span> <span class="s1">'d'</span><span class="p">],</span> <span class="p">[</span><span class="s1">'a'</span><span class="p">,</span> <span class="s1">'b'</span><span class="p">,</span> <span class="s1">'c'</span><span class="p">,</span> <span class="s1">'d'</span><span class="p">])</span>
<span class="gp">>>> </span><span class="n">a</span><span class="o">.</span><span class="n">next_binary</span><span class="p">()</span><span class="o">.</span><span class="n">subset</span>
<span class="go">['b']</span>
<span class="gp">>>> </span><span class="n">a</span> <span class="o">=</span> <span class="n">Subset</span><span class="p">([</span><span class="s1">'a'</span><span class="p">,</span> <span class="s1">'b'</span><span class="p">,</span> <span class="s1">'c'</span><span class="p">,</span> <span class="s1">'d'</span><span class="p">],</span> <span class="p">[</span><span class="s1">'a'</span><span class="p">,</span> <span class="s1">'b'</span><span class="p">,</span> <span class="s1">'c'</span><span class="p">,</span> <span class="s1">'d'</span><span class="p">])</span>
<span class="gp">>>> </span><span class="n">a</span><span class="o">.</span><span class="n">next_binary</span><span class="p">()</span><span class="o">.</span><span class="n">subset</span>
<span class="go">[]</span>
</pre></div>
</div>
</dd></dl>
<dl class="method">
<dt id="sympy.combinatorics.subsets.Subset.next_gray">
<code class="descname">next_gray</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="../../_modules/sympy/combinatorics/subsets.html#Subset.next_gray"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#sympy.combinatorics.subsets.Subset.next_gray" title="Permalink to this definition">¶</a></dt>
<dd><p>Generates the next Gray code ordered subset.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference internal" href="#sympy.combinatorics.subsets.Subset.iterate_graycode" title="sympy.combinatorics.subsets.Subset.iterate_graycode"><code class="xref py py-obj docutils literal"><span class="pre">iterate_graycode</span></code></a>, <a class="reference internal" href="#sympy.combinatorics.subsets.Subset.prev_gray" title="sympy.combinatorics.subsets.Subset.prev_gray"><code class="xref py py-obj docutils literal"><span class="pre">prev_gray</span></code></a></p>
</div>
<p class="rubric">Examples</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">sympy.combinatorics.subsets</span> <span class="k">import</span> <span class="n">Subset</span>
<span class="gp">>>> </span><span class="n">a</span> <span class="o">=</span> <span class="n">Subset</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">],</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">])</span>
<span class="gp">>>> </span><span class="n">a</span><span class="o">.</span><span class="n">next_gray</span><span class="p">()</span><span class="o">.</span><span class="n">subset</span>
<span class="go">[1, 3]</span>
</pre></div>
</div>
</dd></dl>
<dl class="method">
<dt id="sympy.combinatorics.subsets.Subset.next_lexicographic">
<code class="descname">next_lexicographic</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="../../_modules/sympy/combinatorics/subsets.html#Subset.next_lexicographic"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#sympy.combinatorics.subsets.Subset.next_lexicographic" title="Permalink to this definition">¶</a></dt>
<dd><p>Generates the next lexicographically ordered subset.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference internal" href="#sympy.combinatorics.subsets.Subset.prev_lexicographic" title="sympy.combinatorics.subsets.Subset.prev_lexicographic"><code class="xref py py-obj docutils literal"><span class="pre">prev_lexicographic</span></code></a></p>
</div>
<p class="rubric">Examples</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">sympy.combinatorics.subsets</span> <span class="k">import</span> <span class="n">Subset</span>
<span class="gp">>>> </span><span class="n">a</span> <span class="o">=</span> <span class="n">Subset</span><span class="p">([</span><span class="s1">'c'</span><span class="p">,</span> <span class="s1">'d'</span><span class="p">],</span> <span class="p">[</span><span class="s1">'a'</span><span class="p">,</span> <span class="s1">'b'</span><span class="p">,</span> <span class="s1">'c'</span><span class="p">,</span> <span class="s1">'d'</span><span class="p">])</span>
<span class="gp">>>> </span><span class="n">a</span><span class="o">.</span><span class="n">next_lexicographic</span><span class="p">()</span><span class="o">.</span><span class="n">subset</span>
<span class="go">['d']</span>
<span class="gp">>>> </span><span class="n">a</span> <span class="o">=</span> <span class="n">Subset</span><span class="p">([</span><span class="s1">'d'</span><span class="p">],</span> <span class="p">[</span><span class="s1">'a'</span><span class="p">,</span> <span class="s1">'b'</span><span class="p">,</span> <span class="s1">'c'</span><span class="p">,</span> <span class="s1">'d'</span><span class="p">])</span>
<span class="gp">>>> </span><span class="n">a</span><span class="o">.</span><span class="n">next_lexicographic</span><span class="p">()</span><span class="o">.</span><span class="n">subset</span>
<span class="go">[]</span>
</pre></div>
</div>
</dd></dl>
<dl class="method">
<dt id="sympy.combinatorics.subsets.Subset.prev_binary">
<code class="descname">prev_binary</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="../../_modules/sympy/combinatorics/subsets.html#Subset.prev_binary"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#sympy.combinatorics.subsets.Subset.prev_binary" title="Permalink to this definition">¶</a></dt>
<dd><p>Generates the previous binary ordered subset.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference internal" href="#sympy.combinatorics.subsets.Subset.next_binary" title="sympy.combinatorics.subsets.Subset.next_binary"><code class="xref py py-obj docutils literal"><span class="pre">next_binary</span></code></a>, <a class="reference internal" href="#sympy.combinatorics.subsets.Subset.iterate_binary" title="sympy.combinatorics.subsets.Subset.iterate_binary"><code class="xref py py-obj docutils literal"><span class="pre">iterate_binary</span></code></a></p>
</div>
<p class="rubric">Examples</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">sympy.combinatorics.subsets</span> <span class="k">import</span> <span class="n">Subset</span>
<span class="gp">>>> </span><span class="n">a</span> <span class="o">=</span> <span class="n">Subset</span><span class="p">([],</span> <span class="p">[</span><span class="s1">'a'</span><span class="p">,</span> <span class="s1">'b'</span><span class="p">,</span> <span class="s1">'c'</span><span class="p">,</span> <span class="s1">'d'</span><span class="p">])</span>
<span class="gp">>>> </span><span class="n">a</span><span class="o">.</span><span class="n">prev_binary</span><span class="p">()</span><span class="o">.</span><span class="n">subset</span>
<span class="go">['a', 'b', 'c', 'd']</span>
<span class="gp">>>> </span><span class="n">a</span> <span class="o">=</span> <span class="n">Subset</span><span class="p">([</span><span class="s1">'c'</span><span class="p">,</span> <span class="s1">'d'</span><span class="p">],</span> <span class="p">[</span><span class="s1">'a'</span><span class="p">,</span> <span class="s1">'b'</span><span class="p">,</span> <span class="s1">'c'</span><span class="p">,</span> <span class="s1">'d'</span><span class="p">])</span>
<span class="gp">>>> </span><span class="n">a</span><span class="o">.</span><span class="n">prev_binary</span><span class="p">()</span><span class="o">.</span><span class="n">subset</span>
<span class="go">['c']</span>
</pre></div>
</div>
</dd></dl>
<dl class="method">
<dt id="sympy.combinatorics.subsets.Subset.prev_gray">
<code class="descname">prev_gray</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="../../_modules/sympy/combinatorics/subsets.html#Subset.prev_gray"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#sympy.combinatorics.subsets.Subset.prev_gray" title="Permalink to this definition">¶</a></dt>
<dd><p>Generates the previous Gray code ordered subset.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference internal" href="#sympy.combinatorics.subsets.Subset.iterate_graycode" title="sympy.combinatorics.subsets.Subset.iterate_graycode"><code class="xref py py-obj docutils literal"><span class="pre">iterate_graycode</span></code></a>, <a class="reference internal" href="#sympy.combinatorics.subsets.Subset.next_gray" title="sympy.combinatorics.subsets.Subset.next_gray"><code class="xref py py-obj docutils literal"><span class="pre">next_gray</span></code></a></p>
</div>
<p class="rubric">Examples</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">sympy.combinatorics.subsets</span> <span class="k">import</span> <span class="n">Subset</span>
<span class="gp">>>> </span><span class="n">a</span> <span class="o">=</span> <span class="n">Subset</span><span class="p">([</span><span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">],</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">])</span>
<span class="gp">>>> </span><span class="n">a</span><span class="o">.</span><span class="n">prev_gray</span><span class="p">()</span><span class="o">.</span><span class="n">subset</span>
<span class="go">[2, 3, 4, 5]</span>
</pre></div>
</div>
</dd></dl>
<dl class="method">
<dt id="sympy.combinatorics.subsets.Subset.prev_lexicographic">
<code class="descname">prev_lexicographic</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="../../_modules/sympy/combinatorics/subsets.html#Subset.prev_lexicographic"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#sympy.combinatorics.subsets.Subset.prev_lexicographic" title="Permalink to this definition">¶</a></dt>
<dd><p>Generates the previous lexicographically ordered subset.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference internal" href="#sympy.combinatorics.subsets.Subset.next_lexicographic" title="sympy.combinatorics.subsets.Subset.next_lexicographic"><code class="xref py py-obj docutils literal"><span class="pre">next_lexicographic</span></code></a></p>
</div>
<p class="rubric">Examples</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">sympy.combinatorics.subsets</span> <span class="k">import</span> <span class="n">Subset</span>
<span class="gp">>>> </span><span class="n">a</span> <span class="o">=</span> <span class="n">Subset</span><span class="p">([],</span> <span class="p">[</span><span class="s1">'a'</span><span class="p">,</span> <span class="s1">'b'</span><span class="p">,</span> <span class="s1">'c'</span><span class="p">,</span> <span class="s1">'d'</span><span class="p">])</span>
<span class="gp">>>> </span><span class="n">a</span><span class="o">.</span><span class="n">prev_lexicographic</span><span class="p">()</span><span class="o">.</span><span class="n">subset</span>
<span class="go">['d']</span>
<span class="gp">>>> </span><span class="n">a</span> <span class="o">=</span> <span class="n">Subset</span><span class="p">([</span><span class="s1">'c'</span><span class="p">,</span><span class="s1">'d'</span><span class="p">],</span> <span class="p">[</span><span class="s1">'a'</span><span class="p">,</span> <span class="s1">'b'</span><span class="p">,</span> <span class="s1">'c'</span><span class="p">,</span> <span class="s1">'d'</span><span class="p">])</span>
<span class="gp">>>> </span><span class="n">a</span><span class="o">.</span><span class="n">prev_lexicographic</span><span class="p">()</span><span class="o">.</span><span class="n">subset</span>
<span class="go">['c']</span>
</pre></div>
</div>
</dd></dl>
<dl class="attribute">
<dt id="sympy.combinatorics.subsets.Subset.rank_binary">
<code class="descname">rank_binary</code><a class="headerlink" href="#sympy.combinatorics.subsets.Subset.rank_binary" title="Permalink to this definition">¶</a></dt>
<dd><p>Computes the binary ordered rank.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference internal" href="#sympy.combinatorics.subsets.Subset.iterate_binary" title="sympy.combinatorics.subsets.Subset.iterate_binary"><code class="xref py py-obj docutils literal"><span class="pre">iterate_binary</span></code></a>, <a class="reference internal" href="#sympy.combinatorics.subsets.Subset.unrank_binary" title="sympy.combinatorics.subsets.Subset.unrank_binary"><code class="xref py py-obj docutils literal"><span class="pre">unrank_binary</span></code></a></p>
</div>
<p class="rubric">Examples</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">sympy.combinatorics.subsets</span> <span class="k">import</span> <span class="n">Subset</span>
<span class="gp">>>> </span><span class="n">a</span> <span class="o">=</span> <span class="n">Subset</span><span class="p">([],</span> <span class="p">[</span><span class="s1">'a'</span><span class="p">,</span><span class="s1">'b'</span><span class="p">,</span><span class="s1">'c'</span><span class="p">,</span><span class="s1">'d'</span><span class="p">])</span>
<span class="gp">>>> </span><span class="n">a</span><span class="o">.</span><span class="n">rank_binary</span>
<span class="go">0</span>
<span class="gp">>>> </span><span class="n">a</span> <span class="o">=</span> <span class="n">Subset</span><span class="p">([</span><span class="s1">'c'</span><span class="p">,</span> <span class="s1">'d'</span><span class="p">],</span> <span class="p">[</span><span class="s1">'a'</span><span class="p">,</span> <span class="s1">'b'</span><span class="p">,</span> <span class="s1">'c'</span><span class="p">,</span> <span class="s1">'d'</span><span class="p">])</span>
<span class="gp">>>> </span><span class="n">a</span><span class="o">.</span><span class="n">rank_binary</span>
<span class="go">3</span>
</pre></div>
</div>
</dd></dl>
<dl class="attribute">
<dt id="sympy.combinatorics.subsets.Subset.rank_gray">
<code class="descname">rank_gray</code><a class="headerlink" href="#sympy.combinatorics.subsets.Subset.rank_gray" title="Permalink to this definition">¶</a></dt>
<dd><p>Computes the Gray code ranking of the subset.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference internal" href="#sympy.combinatorics.subsets.Subset.iterate_graycode" title="sympy.combinatorics.subsets.Subset.iterate_graycode"><code class="xref py py-obj docutils literal"><span class="pre">iterate_graycode</span></code></a>, <a class="reference internal" href="#sympy.combinatorics.subsets.Subset.unrank_gray" title="sympy.combinatorics.subsets.Subset.unrank_gray"><code class="xref py py-obj docutils literal"><span class="pre">unrank_gray</span></code></a></p>
</div>
<p class="rubric">Examples</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">sympy.combinatorics.subsets</span> <span class="k">import</span> <span class="n">Subset</span>
<span class="gp">>>> </span><span class="n">a</span> <span class="o">=</span> <span class="n">Subset</span><span class="p">([</span><span class="s1">'c'</span><span class="p">,</span><span class="s1">'d'</span><span class="p">],</span> <span class="p">[</span><span class="s1">'a'</span><span class="p">,</span><span class="s1">'b'</span><span class="p">,</span><span class="s1">'c'</span><span class="p">,</span><span class="s1">'d'</span><span class="p">])</span>
<span class="gp">>>> </span><span class="n">a</span><span class="o">.</span><span class="n">rank_gray</span>
<span class="go">2</span>
<span class="gp">>>> </span><span class="n">a</span> <span class="o">=</span> <span class="n">Subset</span><span class="p">([</span><span class="mi">2</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">],</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">6</span><span class="p">])</span>
<span class="gp">>>> </span><span class="n">a</span><span class="o">.</span><span class="n">rank_gray</span>
<span class="go">27</span>
</pre></div>
</div>
</dd></dl>
<dl class="attribute">
<dt id="sympy.combinatorics.subsets.Subset.rank_lexicographic">
<code class="descname">rank_lexicographic</code><a class="headerlink" href="#sympy.combinatorics.subsets.Subset.rank_lexicographic" title="Permalink to this definition">¶</a></dt>
<dd><p>Computes the lexicographic ranking of the subset.</p>
<p class="rubric">Examples</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">sympy.combinatorics.subsets</span> <span class="k">import</span> <span class="n">Subset</span>
<span class="gp">>>> </span><span class="n">a</span> <span class="o">=</span> <span class="n">Subset</span><span class="p">([</span><span class="s1">'c'</span><span class="p">,</span> <span class="s1">'d'</span><span class="p">],</span> <span class="p">[</span><span class="s1">'a'</span><span class="p">,</span> <span class="s1">'b'</span><span class="p">,</span> <span class="s1">'c'</span><span class="p">,</span> <span class="s1">'d'</span><span class="p">])</span>
<span class="gp">>>> </span><span class="n">a</span><span class="o">.</span><span class="n">rank_lexicographic</span>
<span class="go">14</span>
<span class="gp">>>> </span><span class="n">a</span> <span class="o">=</span> <span class="n">Subset</span><span class="p">([</span><span class="mi">2</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">],</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">6</span><span class="p">])</span>
<span class="gp">>>> </span><span class="n">a</span><span class="o">.</span><span class="n">rank_lexicographic</span>
<span class="go">43</span>
</pre></div>
</div>
</dd></dl>
<dl class="attribute">
<dt id="sympy.combinatorics.subsets.Subset.size">
<code class="descname">size</code><a class="headerlink" href="#sympy.combinatorics.subsets.Subset.size" title="Permalink to this definition">¶</a></dt>
<dd><p>Gets the size of the subset.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference internal" href="#sympy.combinatorics.subsets.Subset.subset" title="sympy.combinatorics.subsets.Subset.subset"><code class="xref py py-obj docutils literal"><span class="pre">subset</span></code></a>, <a class="reference internal" href="#sympy.combinatorics.subsets.Subset.superset" title="sympy.combinatorics.subsets.Subset.superset"><code class="xref py py-obj docutils literal"><span class="pre">superset</span></code></a>, <a class="reference internal" href="#sympy.combinatorics.subsets.Subset.superset_size" title="sympy.combinatorics.subsets.Subset.superset_size"><code class="xref py py-obj docutils literal"><span class="pre">superset_size</span></code></a>, <a class="reference internal" href="#sympy.combinatorics.subsets.Subset.cardinality" title="sympy.combinatorics.subsets.Subset.cardinality"><code class="xref py py-obj docutils literal"><span class="pre">cardinality</span></code></a></p>
</div>
<p class="rubric">Examples</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">sympy.combinatorics.subsets</span> <span class="k">import</span> <span class="n">Subset</span>
<span class="gp">>>> </span><span class="n">a</span> <span class="o">=</span> <span class="n">Subset</span><span class="p">([</span><span class="s1">'c'</span><span class="p">,</span> <span class="s1">'d'</span><span class="p">],</span> <span class="p">[</span><span class="s1">'a'</span><span class="p">,</span> <span class="s1">'b'</span><span class="p">,</span> <span class="s1">'c'</span><span class="p">,</span> <span class="s1">'d'</span><span class="p">])</span>
<span class="gp">>>> </span><span class="n">a</span><span class="o">.</span><span class="n">size</span>
<span class="go">2</span>
</pre></div>
</div>
</dd></dl>
<dl class="attribute">
<dt id="sympy.combinatorics.subsets.Subset.subset">
<code class="descname">subset</code><a class="headerlink" href="#sympy.combinatorics.subsets.Subset.subset" title="Permalink to this definition">¶</a></dt>
<dd><p>Gets the subset represented by the current instance.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference internal" href="#sympy.combinatorics.subsets.Subset.superset" title="sympy.combinatorics.subsets.Subset.superset"><code class="xref py py-obj docutils literal"><span class="pre">superset</span></code></a>, <a class="reference internal" href="#sympy.combinatorics.subsets.Subset.size" title="sympy.combinatorics.subsets.Subset.size"><code class="xref py py-obj docutils literal"><span class="pre">size</span></code></a>, <a class="reference internal" href="#sympy.combinatorics.subsets.Subset.superset_size" title="sympy.combinatorics.subsets.Subset.superset_size"><code class="xref py py-obj docutils literal"><span class="pre">superset_size</span></code></a>, <a class="reference internal" href="#sympy.combinatorics.subsets.Subset.cardinality" title="sympy.combinatorics.subsets.Subset.cardinality"><code class="xref py py-obj docutils literal"><span class="pre">cardinality</span></code></a></p>
</div>
<p class="rubric">Examples</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">sympy.combinatorics.subsets</span> <span class="k">import</span> <span class="n">Subset</span>
<span class="gp">>>> </span><span class="n">a</span> <span class="o">=</span> <span class="n">Subset</span><span class="p">([</span><span class="s1">'c'</span><span class="p">,</span> <span class="s1">'d'</span><span class="p">],</span> <span class="p">[</span><span class="s1">'a'</span><span class="p">,</span> <span class="s1">'b'</span><span class="p">,</span> <span class="s1">'c'</span><span class="p">,</span> <span class="s1">'d'</span><span class="p">])</span>
<span class="gp">>>> </span><span class="n">a</span><span class="o">.</span><span class="n">subset</span>
<span class="go">['c', 'd']</span>
</pre></div>
</div>
</dd></dl>
<dl class="classmethod">
<dt id="sympy.combinatorics.subsets.Subset.subset_from_bitlist">
<em class="property">classmethod </em><code class="descname">subset_from_bitlist</code><span class="sig-paren">(</span><em>super_set</em>, <em>bitlist</em><span class="sig-paren">)</span><a class="reference internal" href="../../_modules/sympy/combinatorics/subsets.html#Subset.subset_from_bitlist"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#sympy.combinatorics.subsets.Subset.subset_from_bitlist" title="Permalink to this definition">¶</a></dt>
<dd><p>Gets the subset defined by the bitlist.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference internal" href="#sympy.combinatorics.subsets.Subset.bitlist_from_subset" title="sympy.combinatorics.subsets.Subset.bitlist_from_subset"><code class="xref py py-obj docutils literal"><span class="pre">bitlist_from_subset</span></code></a></p>
</div>
<p class="rubric">Examples</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">sympy.combinatorics.subsets</span> <span class="k">import</span> <span class="n">Subset</span>
<span class="gp">>>> </span><span class="n">Subset</span><span class="o">.</span><span class="n">subset_from_bitlist</span><span class="p">([</span><span class="s1">'a'</span><span class="p">,</span> <span class="s1">'b'</span><span class="p">,</span> <span class="s1">'c'</span><span class="p">,</span> <span class="s1">'d'</span><span class="p">],</span> <span class="s1">'0011'</span><span class="p">)</span><span class="o">.</span><span class="n">subset</span>
<span class="go">['c', 'd']</span>
</pre></div>
</div>
</dd></dl>
<dl class="classmethod">
<dt id="sympy.combinatorics.subsets.Subset.subset_indices">
<em class="property">classmethod </em><code class="descname">subset_indices</code><span class="sig-paren">(</span><em>subset</em>, <em>superset</em><span class="sig-paren">)</span><a class="reference internal" href="../../_modules/sympy/combinatorics/subsets.html#Subset.subset_indices"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#sympy.combinatorics.subsets.Subset.subset_indices" title="Permalink to this definition">¶</a></dt>
<dd><p>Return indices of subset in superset in a list; the list is empty
if all elements of subset are not in superset.</p>
<p class="rubric">Examples</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">sympy.combinatorics</span> <span class="k">import</span> <span class="n">Subset</span>
<span class="gp">>>> </span><span class="n">superset</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">4</span><span class="p">]</span>
<span class="gp">>>> </span><span class="n">Subset</span><span class="o">.</span><span class="n">subset_indices</span><span class="p">([</span><span class="mi">3</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">1</span><span class="p">],</span> <span class="n">superset</span><span class="p">)</span>
<span class="go">[1, 2, 0]</span>
<span class="gp">>>> </span><span class="n">Subset</span><span class="o">.</span><span class="n">subset_indices</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="mi">6</span><span class="p">],</span> <span class="n">superset</span><span class="p">)</span>
<span class="go">[]</span>
<span class="gp">>>> </span><span class="n">Subset</span><span class="o">.</span><span class="n">subset_indices</span><span class="p">([],</span> <span class="n">superset</span><span class="p">)</span>
<span class="go">[]</span>
</pre></div>
</div>
</dd></dl>
<dl class="attribute">
<dt id="sympy.combinatorics.subsets.Subset.superset">
<code class="descname">superset</code><a class="headerlink" href="#sympy.combinatorics.subsets.Subset.superset" title="Permalink to this definition">¶</a></dt>
<dd><p>Gets the superset of the subset.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference internal" href="#sympy.combinatorics.subsets.Subset.subset" title="sympy.combinatorics.subsets.Subset.subset"><code class="xref py py-obj docutils literal"><span class="pre">subset</span></code></a>, <a class="reference internal" href="#sympy.combinatorics.subsets.Subset.size" title="sympy.combinatorics.subsets.Subset.size"><code class="xref py py-obj docutils literal"><span class="pre">size</span></code></a>, <a class="reference internal" href="#sympy.combinatorics.subsets.Subset.superset_size" title="sympy.combinatorics.subsets.Subset.superset_size"><code class="xref py py-obj docutils literal"><span class="pre">superset_size</span></code></a>, <a class="reference internal" href="#sympy.combinatorics.subsets.Subset.cardinality" title="sympy.combinatorics.subsets.Subset.cardinality"><code class="xref py py-obj docutils literal"><span class="pre">cardinality</span></code></a></p>
</div>
<p class="rubric">Examples</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">sympy.combinatorics.subsets</span> <span class="k">import</span> <span class="n">Subset</span>
<span class="gp">>>> </span><span class="n">a</span> <span class="o">=</span> <span class="n">Subset</span><span class="p">([</span><span class="s1">'c'</span><span class="p">,</span> <span class="s1">'d'</span><span class="p">],</span> <span class="p">[</span><span class="s1">'a'</span><span class="p">,</span> <span class="s1">'b'</span><span class="p">,</span> <span class="s1">'c'</span><span class="p">,</span> <span class="s1">'d'</span><span class="p">])</span>
<span class="gp">>>> </span><span class="n">a</span><span class="o">.</span><span class="n">superset</span>
<span class="go">['a', 'b', 'c', 'd']</span>
</pre></div>
</div>
</dd></dl>
<dl class="attribute">
<dt id="sympy.combinatorics.subsets.Subset.superset_size">
<code class="descname">superset_size</code><a class="headerlink" href="#sympy.combinatorics.subsets.Subset.superset_size" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the size of the superset.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference internal" href="#sympy.combinatorics.subsets.Subset.subset" title="sympy.combinatorics.subsets.Subset.subset"><code class="xref py py-obj docutils literal"><span class="pre">subset</span></code></a>, <a class="reference internal" href="#sympy.combinatorics.subsets.Subset.superset" title="sympy.combinatorics.subsets.Subset.superset"><code class="xref py py-obj docutils literal"><span class="pre">superset</span></code></a>, <a class="reference internal" href="#sympy.combinatorics.subsets.Subset.size" title="sympy.combinatorics.subsets.Subset.size"><code class="xref py py-obj docutils literal"><span class="pre">size</span></code></a>, <a class="reference internal" href="#sympy.combinatorics.subsets.Subset.cardinality" title="sympy.combinatorics.subsets.Subset.cardinality"><code class="xref py py-obj docutils literal"><span class="pre">cardinality</span></code></a></p>
</div>
<p class="rubric">Examples</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">sympy.combinatorics.subsets</span> <span class="k">import</span> <span class="n">Subset</span>
<span class="gp">>>> </span><span class="n">a</span> <span class="o">=</span> <span class="n">Subset</span><span class="p">([</span><span class="s1">'c'</span><span class="p">,</span> <span class="s1">'d'</span><span class="p">],</span> <span class="p">[</span><span class="s1">'a'</span><span class="p">,</span> <span class="s1">'b'</span><span class="p">,</span> <span class="s1">'c'</span><span class="p">,</span> <span class="s1">'d'</span><span class="p">])</span>
<span class="gp">>>> </span><span class="n">a</span><span class="o">.</span><span class="n">superset_size</span>
<span class="go">4</span>
</pre></div>
</div>
</dd></dl>
<dl class="classmethod">
<dt id="sympy.combinatorics.subsets.Subset.unrank_binary">
<em class="property">classmethod </em><code class="descname">unrank_binary</code><span class="sig-paren">(</span><em>rank</em>, <em>superset</em><span class="sig-paren">)</span><a class="reference internal" href="../../_modules/sympy/combinatorics/subsets.html#Subset.unrank_binary"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#sympy.combinatorics.subsets.Subset.unrank_binary" title="Permalink to this definition">¶</a></dt>
<dd><p>Gets the binary ordered subset of the specified rank.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference internal" href="#sympy.combinatorics.subsets.Subset.iterate_binary" title="sympy.combinatorics.subsets.Subset.iterate_binary"><code class="xref py py-obj docutils literal"><span class="pre">iterate_binary</span></code></a>, <a class="reference internal" href="#sympy.combinatorics.subsets.Subset.rank_binary" title="sympy.combinatorics.subsets.Subset.rank_binary"><code class="xref py py-obj docutils literal"><span class="pre">rank_binary</span></code></a></p>
</div>
<p class="rubric">Examples</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">sympy.combinatorics.subsets</span> <span class="k">import</span> <span class="n">Subset</span>
<span class="gp">>>> </span><span class="n">Subset</span><span class="o">.</span><span class="n">unrank_binary</span><span class="p">(</span><span class="mi">4</span><span class="p">,</span> <span class="p">[</span><span class="s1">'a'</span><span class="p">,</span> <span class="s1">'b'</span><span class="p">,</span> <span class="s1">'c'</span><span class="p">,</span> <span class="s1">'d'</span><span class="p">])</span><span class="o">.</span><span class="n">subset</span>
<span class="go">['b']</span>
</pre></div>
</div>
</dd></dl>
<dl class="classmethod">
<dt id="sympy.combinatorics.subsets.Subset.unrank_gray">
<em class="property">classmethod </em><code class="descname">unrank_gray</code><span class="sig-paren">(</span><em>rank</em>, <em>superset</em><span class="sig-paren">)</span><a class="reference internal" href="../../_modules/sympy/combinatorics/subsets.html#Subset.unrank_gray"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#sympy.combinatorics.subsets.Subset.unrank_gray" title="Permalink to this definition">¶</a></dt>
<dd><p>Gets the Gray code ordered subset of the specified rank.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference internal" href="#sympy.combinatorics.subsets.Subset.iterate_graycode" title="sympy.combinatorics.subsets.Subset.iterate_graycode"><code class="xref py py-obj docutils literal"><span class="pre">iterate_graycode</span></code></a>, <a class="reference internal" href="#sympy.combinatorics.subsets.Subset.rank_gray" title="sympy.combinatorics.subsets.Subset.rank_gray"><code class="xref py py-obj docutils literal"><span class="pre">rank_gray</span></code></a></p>
</div>
<p class="rubric">Examples</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">sympy.combinatorics.subsets</span> <span class="k">import</span> <span class="n">Subset</span>
<span class="gp">>>> </span><span class="n">Subset</span><span class="o">.</span><span class="n">unrank_gray</span><span class="p">(</span><span class="mi">4</span><span class="p">,</span> <span class="p">[</span><span class="s1">'a'</span><span class="p">,</span> <span class="s1">'b'</span><span class="p">,</span> <span class="s1">'c'</span><span class="p">])</span><span class="o">.</span><span class="n">subset</span>
<span class="go">['a', 'b']</span>
<span class="gp">>>> </span><span class="n">Subset</span><span class="o">.</span><span class="n">unrank_gray</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="p">[</span><span class="s1">'a'</span><span class="p">,</span> <span class="s1">'b'</span><span class="p">,</span> <span class="s1">'c'</span><span class="p">])</span><span class="o">.</span><span class="n">subset</span>
<span class="go">[]</span>
</pre></div>
</div>
</dd></dl>
</dd></dl>
<dl class="method">
<dt id="sympy.combinatorics.subsets.ksubsets">
<code class="descclassname">subsets.</code><code class="descname">ksubsets</code><span class="sig-paren">(</span><em>superset</em>, <em>k</em><span class="sig-paren">)</span><a class="headerlink" href="#sympy.combinatorics.subsets.ksubsets" title="Permalink to this definition">¶</a></dt>
<dd><p>Finds the subsets of size k in lexicographic order.</p>
<p>This uses the itertools generator.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><code class="xref py py-obj docutils literal"><span class="pre">class</span></code></dt>
<dd>Subset</dd>
</dl>
</div>
<p class="rubric">Examples</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">sympy.combinatorics.subsets</span> <span class="k">import</span> <span class="n">ksubsets</span>
<span class="gp">>>> </span><span class="nb">list</span><span class="p">(</span><span class="n">ksubsets</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">],</span> <span class="mi">2</span><span class="p">))</span>
<span class="go">[(1, 2), (1, 3), (2, 3)]</span>
<span class="gp">>>> </span><span class="nb">list</span><span class="p">(</span><span class="n">ksubsets</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">],</span> <span class="mi">2</span><span class="p">))</span>
<span class="go">[(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)]</span>
</pre></div>
</div>
</dd></dl>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper">
<p class="logo"><a href="../../index.html">
<img class="logo" src="../../_static/sympylogo.png" alt="Logo"/>
</a></p><div class="relations">
<h3>Related Topics</h3>
<ul>
<li><a href="../../index.html">Documentation overview</a><ul>
<li><a href="../index.html">SymPy Modules Reference</a><ul>
<li><a href="index.html">Combinatorics Module</a><ul>
<li>Previous: <a href="prufer.html" title="previous chapter">Prufer Sequences</a></li>
<li>Next: <a href="graycode.html" title="next chapter">Gray Code</a></li>
</ul></li>
</ul></li>
</ul></li>
</ul>
</div>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../../_sources/modules/combinatorics/subsets.txt"
rel="nofollow">Show Source</a></li>
</ul>
</div>
<div id="searchbox" style="display: none" role="search">
<h3>Quick search</h3>
<form class="search" action="../../search.html" method="get">
<input type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="footer">
©2015 SymPy Development Team.
|
Powered by <a href="http://sphinx-doc.org/">Sphinx 1.4.1</a>
& <a href="https://github.com/bitprophet/alabaster">Alabaster 0.7.7</a>
|
<a href="../../_sources/modules/combinatorics/subsets.txt"
rel="nofollow">Page source</a>
</div>
</body>
</html>
|
lidavidm/lidavidm.github.com
|
sympy/modules/combinatorics/subsets.html
|
HTML
|
apache-2.0
| 59,529
|
//
// main.c
// 3-【了解】printf函数的介绍和使用
//
// Created by 高明辉 on 15/12/24.
// Copyright © 2015年 itcast. All rights reserved.
//
#include <stdio.h>
int main(int argc, const char * argv[]) {
/*
使用printf函数,需要引入头文件stdio.h ,但是对于printf函数也可以不引入。
printf函数的一般使用形式:
1、输出一段字符:
printf("hello owrld \n");
2、输出变量的值。
printf("格式控制字符串",输出项列表);
3、输出多个变量的值
printf("%d,%d,%d",a,b,c);
注意:
格式控制字符串中的占位符要和后面的输出相的类型和次序一一对应。
注意:
%.2f 表示保留小数点后面2位小数,并且四舍五入。
域宽:
%5d
%-5d
%0d
转义字符:
在控制台打印出 :
"hello,'dog',\o/,50%"
"hello,'dog',\o/,50%"
"\"hello,\'dog',\\o/,50%%\"\n"
*/
printf("hello world...\n");
int a = 210;
// 我想打印出a的值,怎么办?
printf("a = %d\n",a);
float f = 123456.56789f;
printf("f = %5.2f\n",f);// %f默认输出6位小数。
float f1 = 1.23456789f;
printf("f1 = %.9f\n",f1);
float f2 = 123456789.0f;
printf("f2 = %f\n",f2);
double d = 1.23456789123456789;
printf("d = %.19lf\n",d);
int a1 = 10;
long b = 100000l;
float fx = 1.2f;
printf("a1 = %d,b = %ld,fx = %.2f\n",a1,b,fx);
// 打印转义字符:
printf("\"hello,\'dog',\\o/,50%%\"\n");
return 0;
}
|
MinghuiGao/C-
|
day0212月24/3-【了解】printf函数的介绍和使用/main.c
|
C
|
apache-2.0
| 1,804
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">
<html xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>SLF4J 1.7.16 Reference Package org.slf4j.dummyExt</title>
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="style" />
</head>
<body>
<div class="overview">
<ul>
<li>
<a href="../../../overview-summary.html">Overview</a>
</li>
<li class="selected">Package</li>
</ul>
</div>
<div class="framenoframe">
<ul>
<li>
<a href="../../../index.html" target="_top">FRAMES</a>
</li>
<li>
<a href="package-summary.html" target="_top">NO FRAMES</a>
</li>
</ul>
</div>
<h2>Package org.slf4j.dummyExt</h2>
<table class="summary">
<thead>
<tr>
<th>Class Summary</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<a href="EventLoggerTest.html" target="classFrame">EventLoggerTest</a>
</td>
</tr>
<tr>
<td>
<a href="ListAppender.html" target="classFrame">ListAppender</a>
</td>
</tr>
<tr>
<td>
<a href="MDCStrLookupTest.html" target="classFrame">MDCStrLookupTest</a>
</td>
</tr>
<tr>
<td>
<a href="PackageTest.html" target="classFrame">PackageTest</a>
</td>
</tr>
<tr>
<td>
<a href="XLoggerTest.html" target="classFrame">XLoggerTest</a>
</td>
</tr>
</tbody>
</table>
<div class="overview">
<ul>
<li>
<a href="../../../overview-summary.html">Overview</a>
</li>
<li class="selected">Package</li>
</ul>
</div>
<div class="framenoframe">
<ul>
<li>
<a href="../../../index.html" target="_top">FRAMES</a>
</li>
<li>
<a href="package-summary.html" target="_top">NO FRAMES</a>
</li>
</ul>
</div>
<hr />
Copyright © 2005-2016 QOS.ch. All Rights Reserved.
</body>
</html>
|
tjth/bitcoinj-lotterycoin
|
slf4j-1.7.16/site/xref-test/org/slf4j/dummyExt/package-summary.html
|
HTML
|
apache-2.0
| 2,581
|
# frozen_string_literal: true
# WARNING ABOUT GENERATED CODE
#
# This file is generated. See the contributing guide for more information:
# https://github.com/aws/aws-sdk-ruby/blob/version-3/CONTRIBUTING.md
#
# WARNING ABOUT GENERATED CODE
module Aws::Translate
# @api private
module ClientApi
include Seahorse::Model
AppliedTerminology = Shapes::StructureShape.new(name: 'AppliedTerminology')
AppliedTerminologyList = Shapes::ListShape.new(name: 'AppliedTerminologyList')
BoundedLengthString = Shapes::StringShape.new(name: 'BoundedLengthString')
ClientTokenString = Shapes::StringShape.new(name: 'ClientTokenString')
ConcurrentModificationException = Shapes::StructureShape.new(name: 'ConcurrentModificationException')
ConflictException = Shapes::StructureShape.new(name: 'ConflictException')
ContentType = Shapes::StringShape.new(name: 'ContentType')
CreateParallelDataRequest = Shapes::StructureShape.new(name: 'CreateParallelDataRequest')
CreateParallelDataResponse = Shapes::StructureShape.new(name: 'CreateParallelDataResponse')
DeleteParallelDataRequest = Shapes::StructureShape.new(name: 'DeleteParallelDataRequest')
DeleteParallelDataResponse = Shapes::StructureShape.new(name: 'DeleteParallelDataResponse')
DeleteTerminologyRequest = Shapes::StructureShape.new(name: 'DeleteTerminologyRequest')
DescribeTextTranslationJobRequest = Shapes::StructureShape.new(name: 'DescribeTextTranslationJobRequest')
DescribeTextTranslationJobResponse = Shapes::StructureShape.new(name: 'DescribeTextTranslationJobResponse')
Description = Shapes::StringShape.new(name: 'Description')
DetectedLanguageLowConfidenceException = Shapes::StructureShape.new(name: 'DetectedLanguageLowConfidenceException')
Directionality = Shapes::StringShape.new(name: 'Directionality')
EncryptionKey = Shapes::StructureShape.new(name: 'EncryptionKey')
EncryptionKeyID = Shapes::StringShape.new(name: 'EncryptionKeyID')
EncryptionKeyType = Shapes::StringShape.new(name: 'EncryptionKeyType')
Formality = Shapes::StringShape.new(name: 'Formality')
GetParallelDataRequest = Shapes::StructureShape.new(name: 'GetParallelDataRequest')
GetParallelDataResponse = Shapes::StructureShape.new(name: 'GetParallelDataResponse')
GetTerminologyRequest = Shapes::StructureShape.new(name: 'GetTerminologyRequest')
GetTerminologyResponse = Shapes::StructureShape.new(name: 'GetTerminologyResponse')
IamRoleArn = Shapes::StringShape.new(name: 'IamRoleArn')
ImportTerminologyRequest = Shapes::StructureShape.new(name: 'ImportTerminologyRequest')
ImportTerminologyResponse = Shapes::StructureShape.new(name: 'ImportTerminologyResponse')
InputDataConfig = Shapes::StructureShape.new(name: 'InputDataConfig')
Integer = Shapes::IntegerShape.new(name: 'Integer')
InternalServerException = Shapes::StructureShape.new(name: 'InternalServerException')
InvalidFilterException = Shapes::StructureShape.new(name: 'InvalidFilterException')
InvalidParameterValueException = Shapes::StructureShape.new(name: 'InvalidParameterValueException')
InvalidRequestException = Shapes::StructureShape.new(name: 'InvalidRequestException')
JobDetails = Shapes::StructureShape.new(name: 'JobDetails')
JobId = Shapes::StringShape.new(name: 'JobId')
JobName = Shapes::StringShape.new(name: 'JobName')
JobStatus = Shapes::StringShape.new(name: 'JobStatus')
LanguageCodeString = Shapes::StringShape.new(name: 'LanguageCodeString')
LanguageCodeStringList = Shapes::ListShape.new(name: 'LanguageCodeStringList')
LimitExceededException = Shapes::StructureShape.new(name: 'LimitExceededException')
ListParallelDataRequest = Shapes::StructureShape.new(name: 'ListParallelDataRequest')
ListParallelDataResponse = Shapes::StructureShape.new(name: 'ListParallelDataResponse')
ListTerminologiesRequest = Shapes::StructureShape.new(name: 'ListTerminologiesRequest')
ListTerminologiesResponse = Shapes::StructureShape.new(name: 'ListTerminologiesResponse')
ListTextTranslationJobsRequest = Shapes::StructureShape.new(name: 'ListTextTranslationJobsRequest')
ListTextTranslationJobsResponse = Shapes::StructureShape.new(name: 'ListTextTranslationJobsResponse')
Long = Shapes::IntegerShape.new(name: 'Long')
MaxResultsInteger = Shapes::IntegerShape.new(name: 'MaxResultsInteger')
MergeStrategy = Shapes::StringShape.new(name: 'MergeStrategy')
NextToken = Shapes::StringShape.new(name: 'NextToken')
OutputDataConfig = Shapes::StructureShape.new(name: 'OutputDataConfig')
ParallelDataArn = Shapes::StringShape.new(name: 'ParallelDataArn')
ParallelDataConfig = Shapes::StructureShape.new(name: 'ParallelDataConfig')
ParallelDataDataLocation = Shapes::StructureShape.new(name: 'ParallelDataDataLocation')
ParallelDataFormat = Shapes::StringShape.new(name: 'ParallelDataFormat')
ParallelDataProperties = Shapes::StructureShape.new(name: 'ParallelDataProperties')
ParallelDataPropertiesList = Shapes::ListShape.new(name: 'ParallelDataPropertiesList')
ParallelDataStatus = Shapes::StringShape.new(name: 'ParallelDataStatus')
Profanity = Shapes::StringShape.new(name: 'Profanity')
ResourceName = Shapes::StringShape.new(name: 'ResourceName')
ResourceNameList = Shapes::ListShape.new(name: 'ResourceNameList')
ResourceNotFoundException = Shapes::StructureShape.new(name: 'ResourceNotFoundException')
S3Uri = Shapes::StringShape.new(name: 'S3Uri')
ServiceUnavailableException = Shapes::StructureShape.new(name: 'ServiceUnavailableException')
StartTextTranslationJobRequest = Shapes::StructureShape.new(name: 'StartTextTranslationJobRequest')
StartTextTranslationJobResponse = Shapes::StructureShape.new(name: 'StartTextTranslationJobResponse')
StopTextTranslationJobRequest = Shapes::StructureShape.new(name: 'StopTextTranslationJobRequest')
StopTextTranslationJobResponse = Shapes::StructureShape.new(name: 'StopTextTranslationJobResponse')
String = Shapes::StringShape.new(name: 'String')
TargetLanguageCodeStringList = Shapes::ListShape.new(name: 'TargetLanguageCodeStringList')
Term = Shapes::StructureShape.new(name: 'Term')
TermList = Shapes::ListShape.new(name: 'TermList')
TerminologyArn = Shapes::StringShape.new(name: 'TerminologyArn')
TerminologyData = Shapes::StructureShape.new(name: 'TerminologyData')
TerminologyDataFormat = Shapes::StringShape.new(name: 'TerminologyDataFormat')
TerminologyDataLocation = Shapes::StructureShape.new(name: 'TerminologyDataLocation')
TerminologyFile = Shapes::BlobShape.new(name: 'TerminologyFile')
TerminologyProperties = Shapes::StructureShape.new(name: 'TerminologyProperties')
TerminologyPropertiesList = Shapes::ListShape.new(name: 'TerminologyPropertiesList')
TextSizeLimitExceededException = Shapes::StructureShape.new(name: 'TextSizeLimitExceededException')
TextTranslationJobFilter = Shapes::StructureShape.new(name: 'TextTranslationJobFilter')
TextTranslationJobProperties = Shapes::StructureShape.new(name: 'TextTranslationJobProperties')
TextTranslationJobPropertiesList = Shapes::ListShape.new(name: 'TextTranslationJobPropertiesList')
Timestamp = Shapes::TimestampShape.new(name: 'Timestamp')
TooManyRequestsException = Shapes::StructureShape.new(name: 'TooManyRequestsException')
TranslateTextRequest = Shapes::StructureShape.new(name: 'TranslateTextRequest')
TranslateTextResponse = Shapes::StructureShape.new(name: 'TranslateTextResponse')
TranslationSettings = Shapes::StructureShape.new(name: 'TranslationSettings')
UnboundedLengthString = Shapes::StringShape.new(name: 'UnboundedLengthString')
UnsupportedLanguagePairException = Shapes::StructureShape.new(name: 'UnsupportedLanguagePairException')
UpdateParallelDataRequest = Shapes::StructureShape.new(name: 'UpdateParallelDataRequest')
UpdateParallelDataResponse = Shapes::StructureShape.new(name: 'UpdateParallelDataResponse')
AppliedTerminology.add_member(:name, Shapes::ShapeRef.new(shape: ResourceName, location_name: "Name"))
AppliedTerminology.add_member(:terms, Shapes::ShapeRef.new(shape: TermList, location_name: "Terms"))
AppliedTerminology.struct_class = Types::AppliedTerminology
AppliedTerminologyList.member = Shapes::ShapeRef.new(shape: AppliedTerminology)
ConcurrentModificationException.add_member(:message, Shapes::ShapeRef.new(shape: String, location_name: "Message"))
ConcurrentModificationException.struct_class = Types::ConcurrentModificationException
ConflictException.add_member(:message, Shapes::ShapeRef.new(shape: String, location_name: "Message"))
ConflictException.struct_class = Types::ConflictException
CreateParallelDataRequest.add_member(:name, Shapes::ShapeRef.new(shape: ResourceName, required: true, location_name: "Name"))
CreateParallelDataRequest.add_member(:description, Shapes::ShapeRef.new(shape: Description, location_name: "Description"))
CreateParallelDataRequest.add_member(:parallel_data_config, Shapes::ShapeRef.new(shape: ParallelDataConfig, required: true, location_name: "ParallelDataConfig"))
CreateParallelDataRequest.add_member(:encryption_key, Shapes::ShapeRef.new(shape: EncryptionKey, location_name: "EncryptionKey"))
CreateParallelDataRequest.add_member(:client_token, Shapes::ShapeRef.new(shape: ClientTokenString, required: true, location_name: "ClientToken", metadata: {"idempotencyToken"=>true}))
CreateParallelDataRequest.struct_class = Types::CreateParallelDataRequest
CreateParallelDataResponse.add_member(:name, Shapes::ShapeRef.new(shape: ResourceName, location_name: "Name"))
CreateParallelDataResponse.add_member(:status, Shapes::ShapeRef.new(shape: ParallelDataStatus, location_name: "Status"))
CreateParallelDataResponse.struct_class = Types::CreateParallelDataResponse
DeleteParallelDataRequest.add_member(:name, Shapes::ShapeRef.new(shape: ResourceName, required: true, location_name: "Name"))
DeleteParallelDataRequest.struct_class = Types::DeleteParallelDataRequest
DeleteParallelDataResponse.add_member(:name, Shapes::ShapeRef.new(shape: ResourceName, location_name: "Name"))
DeleteParallelDataResponse.add_member(:status, Shapes::ShapeRef.new(shape: ParallelDataStatus, location_name: "Status"))
DeleteParallelDataResponse.struct_class = Types::DeleteParallelDataResponse
DeleteTerminologyRequest.add_member(:name, Shapes::ShapeRef.new(shape: ResourceName, required: true, location_name: "Name"))
DeleteTerminologyRequest.struct_class = Types::DeleteTerminologyRequest
DescribeTextTranslationJobRequest.add_member(:job_id, Shapes::ShapeRef.new(shape: JobId, required: true, location_name: "JobId"))
DescribeTextTranslationJobRequest.struct_class = Types::DescribeTextTranslationJobRequest
DescribeTextTranslationJobResponse.add_member(:text_translation_job_properties, Shapes::ShapeRef.new(shape: TextTranslationJobProperties, location_name: "TextTranslationJobProperties"))
DescribeTextTranslationJobResponse.struct_class = Types::DescribeTextTranslationJobResponse
DetectedLanguageLowConfidenceException.add_member(:message, Shapes::ShapeRef.new(shape: String, location_name: "Message"))
DetectedLanguageLowConfidenceException.add_member(:detected_language_code, Shapes::ShapeRef.new(shape: LanguageCodeString, location_name: "DetectedLanguageCode"))
DetectedLanguageLowConfidenceException.struct_class = Types::DetectedLanguageLowConfidenceException
EncryptionKey.add_member(:type, Shapes::ShapeRef.new(shape: EncryptionKeyType, required: true, location_name: "Type"))
EncryptionKey.add_member(:id, Shapes::ShapeRef.new(shape: EncryptionKeyID, required: true, location_name: "Id"))
EncryptionKey.struct_class = Types::EncryptionKey
GetParallelDataRequest.add_member(:name, Shapes::ShapeRef.new(shape: ResourceName, required: true, location_name: "Name"))
GetParallelDataRequest.struct_class = Types::GetParallelDataRequest
GetParallelDataResponse.add_member(:parallel_data_properties, Shapes::ShapeRef.new(shape: ParallelDataProperties, location_name: "ParallelDataProperties"))
GetParallelDataResponse.add_member(:data_location, Shapes::ShapeRef.new(shape: ParallelDataDataLocation, location_name: "DataLocation"))
GetParallelDataResponse.add_member(:auxiliary_data_location, Shapes::ShapeRef.new(shape: ParallelDataDataLocation, location_name: "AuxiliaryDataLocation"))
GetParallelDataResponse.add_member(:latest_update_attempt_auxiliary_data_location, Shapes::ShapeRef.new(shape: ParallelDataDataLocation, location_name: "LatestUpdateAttemptAuxiliaryDataLocation"))
GetParallelDataResponse.struct_class = Types::GetParallelDataResponse
GetTerminologyRequest.add_member(:name, Shapes::ShapeRef.new(shape: ResourceName, required: true, location_name: "Name"))
GetTerminologyRequest.add_member(:terminology_data_format, Shapes::ShapeRef.new(shape: TerminologyDataFormat, location_name: "TerminologyDataFormat"))
GetTerminologyRequest.struct_class = Types::GetTerminologyRequest
GetTerminologyResponse.add_member(:terminology_properties, Shapes::ShapeRef.new(shape: TerminologyProperties, location_name: "TerminologyProperties"))
GetTerminologyResponse.add_member(:terminology_data_location, Shapes::ShapeRef.new(shape: TerminologyDataLocation, location_name: "TerminologyDataLocation"))
GetTerminologyResponse.add_member(:auxiliary_data_location, Shapes::ShapeRef.new(shape: TerminologyDataLocation, location_name: "AuxiliaryDataLocation"))
GetTerminologyResponse.struct_class = Types::GetTerminologyResponse
ImportTerminologyRequest.add_member(:name, Shapes::ShapeRef.new(shape: ResourceName, required: true, location_name: "Name"))
ImportTerminologyRequest.add_member(:merge_strategy, Shapes::ShapeRef.new(shape: MergeStrategy, required: true, location_name: "MergeStrategy"))
ImportTerminologyRequest.add_member(:description, Shapes::ShapeRef.new(shape: Description, location_name: "Description"))
ImportTerminologyRequest.add_member(:terminology_data, Shapes::ShapeRef.new(shape: TerminologyData, required: true, location_name: "TerminologyData"))
ImportTerminologyRequest.add_member(:encryption_key, Shapes::ShapeRef.new(shape: EncryptionKey, location_name: "EncryptionKey"))
ImportTerminologyRequest.struct_class = Types::ImportTerminologyRequest
ImportTerminologyResponse.add_member(:terminology_properties, Shapes::ShapeRef.new(shape: TerminologyProperties, location_name: "TerminologyProperties"))
ImportTerminologyResponse.add_member(:auxiliary_data_location, Shapes::ShapeRef.new(shape: TerminologyDataLocation, location_name: "AuxiliaryDataLocation"))
ImportTerminologyResponse.struct_class = Types::ImportTerminologyResponse
InputDataConfig.add_member(:s3_uri, Shapes::ShapeRef.new(shape: S3Uri, required: true, location_name: "S3Uri"))
InputDataConfig.add_member(:content_type, Shapes::ShapeRef.new(shape: ContentType, required: true, location_name: "ContentType"))
InputDataConfig.struct_class = Types::InputDataConfig
InternalServerException.add_member(:message, Shapes::ShapeRef.new(shape: String, location_name: "Message"))
InternalServerException.struct_class = Types::InternalServerException
InvalidFilterException.add_member(:message, Shapes::ShapeRef.new(shape: String, location_name: "Message"))
InvalidFilterException.struct_class = Types::InvalidFilterException
InvalidParameterValueException.add_member(:message, Shapes::ShapeRef.new(shape: String, location_name: "Message"))
InvalidParameterValueException.struct_class = Types::InvalidParameterValueException
InvalidRequestException.add_member(:message, Shapes::ShapeRef.new(shape: String, location_name: "Message"))
InvalidRequestException.struct_class = Types::InvalidRequestException
JobDetails.add_member(:translated_documents_count, Shapes::ShapeRef.new(shape: Integer, location_name: "TranslatedDocumentsCount"))
JobDetails.add_member(:documents_with_errors_count, Shapes::ShapeRef.new(shape: Integer, location_name: "DocumentsWithErrorsCount"))
JobDetails.add_member(:input_documents_count, Shapes::ShapeRef.new(shape: Integer, location_name: "InputDocumentsCount"))
JobDetails.struct_class = Types::JobDetails
LanguageCodeStringList.member = Shapes::ShapeRef.new(shape: LanguageCodeString)
LimitExceededException.add_member(:message, Shapes::ShapeRef.new(shape: String, location_name: "Message"))
LimitExceededException.struct_class = Types::LimitExceededException
ListParallelDataRequest.add_member(:next_token, Shapes::ShapeRef.new(shape: NextToken, location_name: "NextToken"))
ListParallelDataRequest.add_member(:max_results, Shapes::ShapeRef.new(shape: MaxResultsInteger, location_name: "MaxResults"))
ListParallelDataRequest.struct_class = Types::ListParallelDataRequest
ListParallelDataResponse.add_member(:parallel_data_properties_list, Shapes::ShapeRef.new(shape: ParallelDataPropertiesList, location_name: "ParallelDataPropertiesList"))
ListParallelDataResponse.add_member(:next_token, Shapes::ShapeRef.new(shape: NextToken, location_name: "NextToken"))
ListParallelDataResponse.struct_class = Types::ListParallelDataResponse
ListTerminologiesRequest.add_member(:next_token, Shapes::ShapeRef.new(shape: NextToken, location_name: "NextToken"))
ListTerminologiesRequest.add_member(:max_results, Shapes::ShapeRef.new(shape: MaxResultsInteger, location_name: "MaxResults"))
ListTerminologiesRequest.struct_class = Types::ListTerminologiesRequest
ListTerminologiesResponse.add_member(:terminology_properties_list, Shapes::ShapeRef.new(shape: TerminologyPropertiesList, location_name: "TerminologyPropertiesList"))
ListTerminologiesResponse.add_member(:next_token, Shapes::ShapeRef.new(shape: NextToken, location_name: "NextToken"))
ListTerminologiesResponse.struct_class = Types::ListTerminologiesResponse
ListTextTranslationJobsRequest.add_member(:filter, Shapes::ShapeRef.new(shape: TextTranslationJobFilter, location_name: "Filter"))
ListTextTranslationJobsRequest.add_member(:next_token, Shapes::ShapeRef.new(shape: NextToken, location_name: "NextToken"))
ListTextTranslationJobsRequest.add_member(:max_results, Shapes::ShapeRef.new(shape: MaxResultsInteger, location_name: "MaxResults"))
ListTextTranslationJobsRequest.struct_class = Types::ListTextTranslationJobsRequest
ListTextTranslationJobsResponse.add_member(:text_translation_job_properties_list, Shapes::ShapeRef.new(shape: TextTranslationJobPropertiesList, location_name: "TextTranslationJobPropertiesList"))
ListTextTranslationJobsResponse.add_member(:next_token, Shapes::ShapeRef.new(shape: NextToken, location_name: "NextToken"))
ListTextTranslationJobsResponse.struct_class = Types::ListTextTranslationJobsResponse
OutputDataConfig.add_member(:s3_uri, Shapes::ShapeRef.new(shape: S3Uri, required: true, location_name: "S3Uri"))
OutputDataConfig.add_member(:encryption_key, Shapes::ShapeRef.new(shape: EncryptionKey, location_name: "EncryptionKey"))
OutputDataConfig.struct_class = Types::OutputDataConfig
ParallelDataConfig.add_member(:s3_uri, Shapes::ShapeRef.new(shape: S3Uri, required: true, location_name: "S3Uri"))
ParallelDataConfig.add_member(:format, Shapes::ShapeRef.new(shape: ParallelDataFormat, required: true, location_name: "Format"))
ParallelDataConfig.struct_class = Types::ParallelDataConfig
ParallelDataDataLocation.add_member(:repository_type, Shapes::ShapeRef.new(shape: String, required: true, location_name: "RepositoryType"))
ParallelDataDataLocation.add_member(:location, Shapes::ShapeRef.new(shape: String, required: true, location_name: "Location"))
ParallelDataDataLocation.struct_class = Types::ParallelDataDataLocation
ParallelDataProperties.add_member(:name, Shapes::ShapeRef.new(shape: ResourceName, location_name: "Name"))
ParallelDataProperties.add_member(:arn, Shapes::ShapeRef.new(shape: ParallelDataArn, location_name: "Arn"))
ParallelDataProperties.add_member(:description, Shapes::ShapeRef.new(shape: Description, location_name: "Description"))
ParallelDataProperties.add_member(:status, Shapes::ShapeRef.new(shape: ParallelDataStatus, location_name: "Status"))
ParallelDataProperties.add_member(:source_language_code, Shapes::ShapeRef.new(shape: LanguageCodeString, location_name: "SourceLanguageCode"))
ParallelDataProperties.add_member(:target_language_codes, Shapes::ShapeRef.new(shape: LanguageCodeStringList, location_name: "TargetLanguageCodes"))
ParallelDataProperties.add_member(:parallel_data_config, Shapes::ShapeRef.new(shape: ParallelDataConfig, location_name: "ParallelDataConfig"))
ParallelDataProperties.add_member(:message, Shapes::ShapeRef.new(shape: UnboundedLengthString, location_name: "Message"))
ParallelDataProperties.add_member(:imported_data_size, Shapes::ShapeRef.new(shape: Long, location_name: "ImportedDataSize"))
ParallelDataProperties.add_member(:imported_record_count, Shapes::ShapeRef.new(shape: Long, location_name: "ImportedRecordCount"))
ParallelDataProperties.add_member(:failed_record_count, Shapes::ShapeRef.new(shape: Long, location_name: "FailedRecordCount"))
ParallelDataProperties.add_member(:skipped_record_count, Shapes::ShapeRef.new(shape: Long, location_name: "SkippedRecordCount"))
ParallelDataProperties.add_member(:encryption_key, Shapes::ShapeRef.new(shape: EncryptionKey, location_name: "EncryptionKey"))
ParallelDataProperties.add_member(:created_at, Shapes::ShapeRef.new(shape: Timestamp, location_name: "CreatedAt"))
ParallelDataProperties.add_member(:last_updated_at, Shapes::ShapeRef.new(shape: Timestamp, location_name: "LastUpdatedAt"))
ParallelDataProperties.add_member(:latest_update_attempt_status, Shapes::ShapeRef.new(shape: ParallelDataStatus, location_name: "LatestUpdateAttemptStatus"))
ParallelDataProperties.add_member(:latest_update_attempt_at, Shapes::ShapeRef.new(shape: Timestamp, location_name: "LatestUpdateAttemptAt"))
ParallelDataProperties.struct_class = Types::ParallelDataProperties
ParallelDataPropertiesList.member = Shapes::ShapeRef.new(shape: ParallelDataProperties)
ResourceNameList.member = Shapes::ShapeRef.new(shape: ResourceName)
ResourceNotFoundException.add_member(:message, Shapes::ShapeRef.new(shape: String, location_name: "Message"))
ResourceNotFoundException.struct_class = Types::ResourceNotFoundException
ServiceUnavailableException.add_member(:message, Shapes::ShapeRef.new(shape: String, location_name: "Message"))
ServiceUnavailableException.struct_class = Types::ServiceUnavailableException
StartTextTranslationJobRequest.add_member(:job_name, Shapes::ShapeRef.new(shape: JobName, location_name: "JobName"))
StartTextTranslationJobRequest.add_member(:input_data_config, Shapes::ShapeRef.new(shape: InputDataConfig, required: true, location_name: "InputDataConfig"))
StartTextTranslationJobRequest.add_member(:output_data_config, Shapes::ShapeRef.new(shape: OutputDataConfig, required: true, location_name: "OutputDataConfig"))
StartTextTranslationJobRequest.add_member(:data_access_role_arn, Shapes::ShapeRef.new(shape: IamRoleArn, required: true, location_name: "DataAccessRoleArn"))
StartTextTranslationJobRequest.add_member(:source_language_code, Shapes::ShapeRef.new(shape: LanguageCodeString, required: true, location_name: "SourceLanguageCode"))
StartTextTranslationJobRequest.add_member(:target_language_codes, Shapes::ShapeRef.new(shape: TargetLanguageCodeStringList, required: true, location_name: "TargetLanguageCodes"))
StartTextTranslationJobRequest.add_member(:terminology_names, Shapes::ShapeRef.new(shape: ResourceNameList, location_name: "TerminologyNames"))
StartTextTranslationJobRequest.add_member(:parallel_data_names, Shapes::ShapeRef.new(shape: ResourceNameList, location_name: "ParallelDataNames"))
StartTextTranslationJobRequest.add_member(:client_token, Shapes::ShapeRef.new(shape: ClientTokenString, required: true, location_name: "ClientToken", metadata: {"idempotencyToken"=>true}))
StartTextTranslationJobRequest.add_member(:settings, Shapes::ShapeRef.new(shape: TranslationSettings, location_name: "Settings"))
StartTextTranslationJobRequest.struct_class = Types::StartTextTranslationJobRequest
StartTextTranslationJobResponse.add_member(:job_id, Shapes::ShapeRef.new(shape: JobId, location_name: "JobId"))
StartTextTranslationJobResponse.add_member(:job_status, Shapes::ShapeRef.new(shape: JobStatus, location_name: "JobStatus"))
StartTextTranslationJobResponse.struct_class = Types::StartTextTranslationJobResponse
StopTextTranslationJobRequest.add_member(:job_id, Shapes::ShapeRef.new(shape: JobId, required: true, location_name: "JobId"))
StopTextTranslationJobRequest.struct_class = Types::StopTextTranslationJobRequest
StopTextTranslationJobResponse.add_member(:job_id, Shapes::ShapeRef.new(shape: JobId, location_name: "JobId"))
StopTextTranslationJobResponse.add_member(:job_status, Shapes::ShapeRef.new(shape: JobStatus, location_name: "JobStatus"))
StopTextTranslationJobResponse.struct_class = Types::StopTextTranslationJobResponse
TargetLanguageCodeStringList.member = Shapes::ShapeRef.new(shape: LanguageCodeString)
Term.add_member(:source_text, Shapes::ShapeRef.new(shape: String, location_name: "SourceText"))
Term.add_member(:target_text, Shapes::ShapeRef.new(shape: String, location_name: "TargetText"))
Term.struct_class = Types::Term
TermList.member = Shapes::ShapeRef.new(shape: Term)
TerminologyData.add_member(:file, Shapes::ShapeRef.new(shape: TerminologyFile, required: true, location_name: "File"))
TerminologyData.add_member(:format, Shapes::ShapeRef.new(shape: TerminologyDataFormat, required: true, location_name: "Format"))
TerminologyData.add_member(:directionality, Shapes::ShapeRef.new(shape: Directionality, location_name: "Directionality"))
TerminologyData.struct_class = Types::TerminologyData
TerminologyDataLocation.add_member(:repository_type, Shapes::ShapeRef.new(shape: String, required: true, location_name: "RepositoryType"))
TerminologyDataLocation.add_member(:location, Shapes::ShapeRef.new(shape: String, required: true, location_name: "Location"))
TerminologyDataLocation.struct_class = Types::TerminologyDataLocation
TerminologyProperties.add_member(:name, Shapes::ShapeRef.new(shape: ResourceName, location_name: "Name"))
TerminologyProperties.add_member(:description, Shapes::ShapeRef.new(shape: Description, location_name: "Description"))
TerminologyProperties.add_member(:arn, Shapes::ShapeRef.new(shape: TerminologyArn, location_name: "Arn"))
TerminologyProperties.add_member(:source_language_code, Shapes::ShapeRef.new(shape: LanguageCodeString, location_name: "SourceLanguageCode"))
TerminologyProperties.add_member(:target_language_codes, Shapes::ShapeRef.new(shape: LanguageCodeStringList, location_name: "TargetLanguageCodes"))
TerminologyProperties.add_member(:encryption_key, Shapes::ShapeRef.new(shape: EncryptionKey, location_name: "EncryptionKey"))
TerminologyProperties.add_member(:size_bytes, Shapes::ShapeRef.new(shape: Integer, location_name: "SizeBytes"))
TerminologyProperties.add_member(:term_count, Shapes::ShapeRef.new(shape: Integer, location_name: "TermCount"))
TerminologyProperties.add_member(:created_at, Shapes::ShapeRef.new(shape: Timestamp, location_name: "CreatedAt"))
TerminologyProperties.add_member(:last_updated_at, Shapes::ShapeRef.new(shape: Timestamp, location_name: "LastUpdatedAt"))
TerminologyProperties.add_member(:directionality, Shapes::ShapeRef.new(shape: Directionality, location_name: "Directionality"))
TerminologyProperties.add_member(:message, Shapes::ShapeRef.new(shape: UnboundedLengthString, location_name: "Message"))
TerminologyProperties.add_member(:skipped_term_count, Shapes::ShapeRef.new(shape: Integer, location_name: "SkippedTermCount"))
TerminologyProperties.add_member(:format, Shapes::ShapeRef.new(shape: TerminologyDataFormat, location_name: "Format"))
TerminologyProperties.struct_class = Types::TerminologyProperties
TerminologyPropertiesList.member = Shapes::ShapeRef.new(shape: TerminologyProperties)
TextSizeLimitExceededException.add_member(:message, Shapes::ShapeRef.new(shape: String, location_name: "Message"))
TextSizeLimitExceededException.struct_class = Types::TextSizeLimitExceededException
TextTranslationJobFilter.add_member(:job_name, Shapes::ShapeRef.new(shape: JobName, location_name: "JobName"))
TextTranslationJobFilter.add_member(:job_status, Shapes::ShapeRef.new(shape: JobStatus, location_name: "JobStatus"))
TextTranslationJobFilter.add_member(:submitted_before_time, Shapes::ShapeRef.new(shape: Timestamp, location_name: "SubmittedBeforeTime"))
TextTranslationJobFilter.add_member(:submitted_after_time, Shapes::ShapeRef.new(shape: Timestamp, location_name: "SubmittedAfterTime"))
TextTranslationJobFilter.struct_class = Types::TextTranslationJobFilter
TextTranslationJobProperties.add_member(:job_id, Shapes::ShapeRef.new(shape: JobId, location_name: "JobId"))
TextTranslationJobProperties.add_member(:job_name, Shapes::ShapeRef.new(shape: JobName, location_name: "JobName"))
TextTranslationJobProperties.add_member(:job_status, Shapes::ShapeRef.new(shape: JobStatus, location_name: "JobStatus"))
TextTranslationJobProperties.add_member(:job_details, Shapes::ShapeRef.new(shape: JobDetails, location_name: "JobDetails"))
TextTranslationJobProperties.add_member(:source_language_code, Shapes::ShapeRef.new(shape: LanguageCodeString, location_name: "SourceLanguageCode"))
TextTranslationJobProperties.add_member(:target_language_codes, Shapes::ShapeRef.new(shape: TargetLanguageCodeStringList, location_name: "TargetLanguageCodes"))
TextTranslationJobProperties.add_member(:terminology_names, Shapes::ShapeRef.new(shape: ResourceNameList, location_name: "TerminologyNames"))
TextTranslationJobProperties.add_member(:parallel_data_names, Shapes::ShapeRef.new(shape: ResourceNameList, location_name: "ParallelDataNames"))
TextTranslationJobProperties.add_member(:message, Shapes::ShapeRef.new(shape: UnboundedLengthString, location_name: "Message"))
TextTranslationJobProperties.add_member(:submitted_time, Shapes::ShapeRef.new(shape: Timestamp, location_name: "SubmittedTime"))
TextTranslationJobProperties.add_member(:end_time, Shapes::ShapeRef.new(shape: Timestamp, location_name: "EndTime"))
TextTranslationJobProperties.add_member(:input_data_config, Shapes::ShapeRef.new(shape: InputDataConfig, location_name: "InputDataConfig"))
TextTranslationJobProperties.add_member(:output_data_config, Shapes::ShapeRef.new(shape: OutputDataConfig, location_name: "OutputDataConfig"))
TextTranslationJobProperties.add_member(:data_access_role_arn, Shapes::ShapeRef.new(shape: IamRoleArn, location_name: "DataAccessRoleArn"))
TextTranslationJobProperties.add_member(:settings, Shapes::ShapeRef.new(shape: TranslationSettings, location_name: "Settings"))
TextTranslationJobProperties.struct_class = Types::TextTranslationJobProperties
TextTranslationJobPropertiesList.member = Shapes::ShapeRef.new(shape: TextTranslationJobProperties)
TooManyRequestsException.add_member(:message, Shapes::ShapeRef.new(shape: String, location_name: "Message"))
TooManyRequestsException.struct_class = Types::TooManyRequestsException
TranslateTextRequest.add_member(:text, Shapes::ShapeRef.new(shape: BoundedLengthString, required: true, location_name: "Text"))
TranslateTextRequest.add_member(:terminology_names, Shapes::ShapeRef.new(shape: ResourceNameList, location_name: "TerminologyNames"))
TranslateTextRequest.add_member(:source_language_code, Shapes::ShapeRef.new(shape: LanguageCodeString, required: true, location_name: "SourceLanguageCode"))
TranslateTextRequest.add_member(:target_language_code, Shapes::ShapeRef.new(shape: LanguageCodeString, required: true, location_name: "TargetLanguageCode"))
TranslateTextRequest.add_member(:settings, Shapes::ShapeRef.new(shape: TranslationSettings, location_name: "Settings"))
TranslateTextRequest.struct_class = Types::TranslateTextRequest
TranslateTextResponse.add_member(:translated_text, Shapes::ShapeRef.new(shape: String, required: true, location_name: "TranslatedText"))
TranslateTextResponse.add_member(:source_language_code, Shapes::ShapeRef.new(shape: LanguageCodeString, required: true, location_name: "SourceLanguageCode"))
TranslateTextResponse.add_member(:target_language_code, Shapes::ShapeRef.new(shape: LanguageCodeString, required: true, location_name: "TargetLanguageCode"))
TranslateTextResponse.add_member(:applied_terminologies, Shapes::ShapeRef.new(shape: AppliedTerminologyList, location_name: "AppliedTerminologies"))
TranslateTextResponse.add_member(:applied_settings, Shapes::ShapeRef.new(shape: TranslationSettings, location_name: "AppliedSettings"))
TranslateTextResponse.struct_class = Types::TranslateTextResponse
TranslationSettings.add_member(:formality, Shapes::ShapeRef.new(shape: Formality, location_name: "Formality"))
TranslationSettings.add_member(:profanity, Shapes::ShapeRef.new(shape: Profanity, location_name: "Profanity"))
TranslationSettings.struct_class = Types::TranslationSettings
UnsupportedLanguagePairException.add_member(:message, Shapes::ShapeRef.new(shape: String, location_name: "Message"))
UnsupportedLanguagePairException.add_member(:source_language_code, Shapes::ShapeRef.new(shape: LanguageCodeString, location_name: "SourceLanguageCode"))
UnsupportedLanguagePairException.add_member(:target_language_code, Shapes::ShapeRef.new(shape: LanguageCodeString, location_name: "TargetLanguageCode"))
UnsupportedLanguagePairException.struct_class = Types::UnsupportedLanguagePairException
UpdateParallelDataRequest.add_member(:name, Shapes::ShapeRef.new(shape: ResourceName, required: true, location_name: "Name"))
UpdateParallelDataRequest.add_member(:description, Shapes::ShapeRef.new(shape: Description, location_name: "Description"))
UpdateParallelDataRequest.add_member(:parallel_data_config, Shapes::ShapeRef.new(shape: ParallelDataConfig, required: true, location_name: "ParallelDataConfig"))
UpdateParallelDataRequest.add_member(:client_token, Shapes::ShapeRef.new(shape: ClientTokenString, required: true, location_name: "ClientToken", metadata: {"idempotencyToken"=>true}))
UpdateParallelDataRequest.struct_class = Types::UpdateParallelDataRequest
UpdateParallelDataResponse.add_member(:name, Shapes::ShapeRef.new(shape: ResourceName, location_name: "Name"))
UpdateParallelDataResponse.add_member(:status, Shapes::ShapeRef.new(shape: ParallelDataStatus, location_name: "Status"))
UpdateParallelDataResponse.add_member(:latest_update_attempt_status, Shapes::ShapeRef.new(shape: ParallelDataStatus, location_name: "LatestUpdateAttemptStatus"))
UpdateParallelDataResponse.add_member(:latest_update_attempt_at, Shapes::ShapeRef.new(shape: Timestamp, location_name: "LatestUpdateAttemptAt"))
UpdateParallelDataResponse.struct_class = Types::UpdateParallelDataResponse
# @api private
API = Seahorse::Model::Api.new.tap do |api|
api.version = "2017-07-01"
api.metadata = {
"apiVersion" => "2017-07-01",
"endpointPrefix" => "translate",
"jsonVersion" => "1.1",
"protocol" => "json",
"serviceFullName" => "Amazon Translate",
"serviceId" => "Translate",
"signatureVersion" => "v4",
"signingName" => "translate",
"targetPrefix" => "AWSShineFrontendService_20170701",
"uid" => "translate-2017-07-01",
}
api.add_operation(:create_parallel_data, Seahorse::Model::Operation.new.tap do |o|
o.name = "CreateParallelData"
o.http_method = "POST"
o.http_request_uri = "/"
o.input = Shapes::ShapeRef.new(shape: CreateParallelDataRequest)
o.output = Shapes::ShapeRef.new(shape: CreateParallelDataResponse)
o.errors << Shapes::ShapeRef.new(shape: InvalidParameterValueException)
o.errors << Shapes::ShapeRef.new(shape: InvalidRequestException)
o.errors << Shapes::ShapeRef.new(shape: LimitExceededException)
o.errors << Shapes::ShapeRef.new(shape: TooManyRequestsException)
o.errors << Shapes::ShapeRef.new(shape: ConflictException)
o.errors << Shapes::ShapeRef.new(shape: InternalServerException)
end)
api.add_operation(:delete_parallel_data, Seahorse::Model::Operation.new.tap do |o|
o.name = "DeleteParallelData"
o.http_method = "POST"
o.http_request_uri = "/"
o.input = Shapes::ShapeRef.new(shape: DeleteParallelDataRequest)
o.output = Shapes::ShapeRef.new(shape: DeleteParallelDataResponse)
o.errors << Shapes::ShapeRef.new(shape: ConcurrentModificationException)
o.errors << Shapes::ShapeRef.new(shape: ResourceNotFoundException)
o.errors << Shapes::ShapeRef.new(shape: TooManyRequestsException)
o.errors << Shapes::ShapeRef.new(shape: InternalServerException)
end)
api.add_operation(:delete_terminology, Seahorse::Model::Operation.new.tap do |o|
o.name = "DeleteTerminology"
o.http_method = "POST"
o.http_request_uri = "/"
o.input = Shapes::ShapeRef.new(shape: DeleteTerminologyRequest)
o.output = Shapes::ShapeRef.new(shape: Shapes::StructureShape.new(struct_class: Aws::EmptyStructure))
o.errors << Shapes::ShapeRef.new(shape: ResourceNotFoundException)
o.errors << Shapes::ShapeRef.new(shape: TooManyRequestsException)
o.errors << Shapes::ShapeRef.new(shape: InvalidParameterValueException)
o.errors << Shapes::ShapeRef.new(shape: InternalServerException)
end)
api.add_operation(:describe_text_translation_job, Seahorse::Model::Operation.new.tap do |o|
o.name = "DescribeTextTranslationJob"
o.http_method = "POST"
o.http_request_uri = "/"
o.input = Shapes::ShapeRef.new(shape: DescribeTextTranslationJobRequest)
o.output = Shapes::ShapeRef.new(shape: DescribeTextTranslationJobResponse)
o.errors << Shapes::ShapeRef.new(shape: ResourceNotFoundException)
o.errors << Shapes::ShapeRef.new(shape: TooManyRequestsException)
o.errors << Shapes::ShapeRef.new(shape: InternalServerException)
end)
api.add_operation(:get_parallel_data, Seahorse::Model::Operation.new.tap do |o|
o.name = "GetParallelData"
o.http_method = "POST"
o.http_request_uri = "/"
o.input = Shapes::ShapeRef.new(shape: GetParallelDataRequest)
o.output = Shapes::ShapeRef.new(shape: GetParallelDataResponse)
o.errors << Shapes::ShapeRef.new(shape: ResourceNotFoundException)
o.errors << Shapes::ShapeRef.new(shape: InvalidParameterValueException)
o.errors << Shapes::ShapeRef.new(shape: TooManyRequestsException)
o.errors << Shapes::ShapeRef.new(shape: InternalServerException)
end)
api.add_operation(:get_terminology, Seahorse::Model::Operation.new.tap do |o|
o.name = "GetTerminology"
o.http_method = "POST"
o.http_request_uri = "/"
o.input = Shapes::ShapeRef.new(shape: GetTerminologyRequest)
o.output = Shapes::ShapeRef.new(shape: GetTerminologyResponse)
o.errors << Shapes::ShapeRef.new(shape: ResourceNotFoundException)
o.errors << Shapes::ShapeRef.new(shape: InvalidParameterValueException)
o.errors << Shapes::ShapeRef.new(shape: TooManyRequestsException)
o.errors << Shapes::ShapeRef.new(shape: InternalServerException)
end)
api.add_operation(:import_terminology, Seahorse::Model::Operation.new.tap do |o|
o.name = "ImportTerminology"
o.http_method = "POST"
o.http_request_uri = "/"
o.input = Shapes::ShapeRef.new(shape: ImportTerminologyRequest)
o.output = Shapes::ShapeRef.new(shape: ImportTerminologyResponse)
o.errors << Shapes::ShapeRef.new(shape: InvalidParameterValueException)
o.errors << Shapes::ShapeRef.new(shape: LimitExceededException)
o.errors << Shapes::ShapeRef.new(shape: TooManyRequestsException)
o.errors << Shapes::ShapeRef.new(shape: InternalServerException)
end)
api.add_operation(:list_parallel_data, Seahorse::Model::Operation.new.tap do |o|
o.name = "ListParallelData"
o.http_method = "POST"
o.http_request_uri = "/"
o.input = Shapes::ShapeRef.new(shape: ListParallelDataRequest)
o.output = Shapes::ShapeRef.new(shape: ListParallelDataResponse)
o.errors << Shapes::ShapeRef.new(shape: InvalidParameterValueException)
o.errors << Shapes::ShapeRef.new(shape: TooManyRequestsException)
o.errors << Shapes::ShapeRef.new(shape: InternalServerException)
o[:pager] = Aws::Pager.new(
limit_key: "max_results",
tokens: {
"next_token" => "next_token"
}
)
end)
api.add_operation(:list_terminologies, Seahorse::Model::Operation.new.tap do |o|
o.name = "ListTerminologies"
o.http_method = "POST"
o.http_request_uri = "/"
o.input = Shapes::ShapeRef.new(shape: ListTerminologiesRequest)
o.output = Shapes::ShapeRef.new(shape: ListTerminologiesResponse)
o.errors << Shapes::ShapeRef.new(shape: InvalidParameterValueException)
o.errors << Shapes::ShapeRef.new(shape: TooManyRequestsException)
o.errors << Shapes::ShapeRef.new(shape: InternalServerException)
o[:pager] = Aws::Pager.new(
limit_key: "max_results",
tokens: {
"next_token" => "next_token"
}
)
end)
api.add_operation(:list_text_translation_jobs, Seahorse::Model::Operation.new.tap do |o|
o.name = "ListTextTranslationJobs"
o.http_method = "POST"
o.http_request_uri = "/"
o.input = Shapes::ShapeRef.new(shape: ListTextTranslationJobsRequest)
o.output = Shapes::ShapeRef.new(shape: ListTextTranslationJobsResponse)
o.errors << Shapes::ShapeRef.new(shape: InvalidRequestException)
o.errors << Shapes::ShapeRef.new(shape: TooManyRequestsException)
o.errors << Shapes::ShapeRef.new(shape: InvalidFilterException)
o.errors << Shapes::ShapeRef.new(shape: InternalServerException)
o[:pager] = Aws::Pager.new(
limit_key: "max_results",
tokens: {
"next_token" => "next_token"
}
)
end)
api.add_operation(:start_text_translation_job, Seahorse::Model::Operation.new.tap do |o|
o.name = "StartTextTranslationJob"
o.http_method = "POST"
o.http_request_uri = "/"
o.input = Shapes::ShapeRef.new(shape: StartTextTranslationJobRequest)
o.output = Shapes::ShapeRef.new(shape: StartTextTranslationJobResponse)
o.errors << Shapes::ShapeRef.new(shape: TooManyRequestsException)
o.errors << Shapes::ShapeRef.new(shape: UnsupportedLanguagePairException)
o.errors << Shapes::ShapeRef.new(shape: InvalidRequestException)
o.errors << Shapes::ShapeRef.new(shape: ResourceNotFoundException)
o.errors << Shapes::ShapeRef.new(shape: InvalidParameterValueException)
o.errors << Shapes::ShapeRef.new(shape: InternalServerException)
end)
api.add_operation(:stop_text_translation_job, Seahorse::Model::Operation.new.tap do |o|
o.name = "StopTextTranslationJob"
o.http_method = "POST"
o.http_request_uri = "/"
o.input = Shapes::ShapeRef.new(shape: StopTextTranslationJobRequest)
o.output = Shapes::ShapeRef.new(shape: StopTextTranslationJobResponse)
o.errors << Shapes::ShapeRef.new(shape: ResourceNotFoundException)
o.errors << Shapes::ShapeRef.new(shape: TooManyRequestsException)
o.errors << Shapes::ShapeRef.new(shape: InternalServerException)
end)
api.add_operation(:translate_text, Seahorse::Model::Operation.new.tap do |o|
o.name = "TranslateText"
o.http_method = "POST"
o.http_request_uri = "/"
o.input = Shapes::ShapeRef.new(shape: TranslateTextRequest)
o.output = Shapes::ShapeRef.new(shape: TranslateTextResponse)
o.errors << Shapes::ShapeRef.new(shape: InvalidRequestException)
o.errors << Shapes::ShapeRef.new(shape: TextSizeLimitExceededException)
o.errors << Shapes::ShapeRef.new(shape: TooManyRequestsException)
o.errors << Shapes::ShapeRef.new(shape: UnsupportedLanguagePairException)
o.errors << Shapes::ShapeRef.new(shape: DetectedLanguageLowConfidenceException)
o.errors << Shapes::ShapeRef.new(shape: ResourceNotFoundException)
o.errors << Shapes::ShapeRef.new(shape: InternalServerException)
o.errors << Shapes::ShapeRef.new(shape: ServiceUnavailableException)
end)
api.add_operation(:update_parallel_data, Seahorse::Model::Operation.new.tap do |o|
o.name = "UpdateParallelData"
o.http_method = "POST"
o.http_request_uri = "/"
o.input = Shapes::ShapeRef.new(shape: UpdateParallelDataRequest)
o.output = Shapes::ShapeRef.new(shape: UpdateParallelDataResponse)
o.errors << Shapes::ShapeRef.new(shape: ConcurrentModificationException)
o.errors << Shapes::ShapeRef.new(shape: InvalidParameterValueException)
o.errors << Shapes::ShapeRef.new(shape: InvalidRequestException)
o.errors << Shapes::ShapeRef.new(shape: LimitExceededException)
o.errors << Shapes::ShapeRef.new(shape: TooManyRequestsException)
o.errors << Shapes::ShapeRef.new(shape: ConflictException)
o.errors << Shapes::ShapeRef.new(shape: ResourceNotFoundException)
o.errors << Shapes::ShapeRef.new(shape: InternalServerException)
end)
end
end
end
|
aws/aws-sdk-ruby
|
gems/aws-sdk-translate/lib/aws-sdk-translate/client_api.rb
|
Ruby
|
apache-2.0
| 46,279
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="zh">
<head>
<!-- Generated by javadoc (version 1.7.0_71) on Mon Nov 16 20:15:33 CST 2015 -->
<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<title>类 org.openoj.compiler.OpenCPPCompiler的使用</title>
<meta name="date" content="2015-11-16">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="\u7C7B org.openoj.compiler.OpenCPPCompiler\u7684\u4F7F\u7528";
}
//-->
</script>
<noscript>
<div>您的浏览器已禁用 JavaScript。</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="跳过导航链接"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="导航">
<li><a href="../../../../overview-summary.html">概览</a></li>
<li><a href="../package-summary.html">程序包</a></li>
<li><a href="../../../../org/openoj/compiler/OpenCPPCompiler.html" title="org.openoj.compiler中的类">类</a></li>
<li class="navBarCell1Rev">使用</li>
<li><a href="../package-tree.html">树</a></li>
<li><a href="../../../../deprecated-list.html">已过时</a></li>
<li><a href="../../../../index-files/index-1.html">索引</a></li>
<li><a href="../../../../help-doc.html">帮助</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>上一个</li>
<li>下一个</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/openoj/compiler/class-use/OpenCPPCompiler.html" target="_top">框架</a></li>
<li><a href="OpenCPPCompiler.html" target="_top">无框架</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">所有类</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="类 org.openoj.compiler.OpenCPPCompiler 的使用" class="title">类 org.openoj.compiler.OpenCPPCompiler<br>的使用</h2>
</div>
<div class="classUseContainer">没有org.openoj.compiler.OpenCPPCompiler的用法</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="跳过导航链接"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="导航">
<li><a href="../../../../overview-summary.html">概览</a></li>
<li><a href="../package-summary.html">程序包</a></li>
<li><a href="../../../../org/openoj/compiler/OpenCPPCompiler.html" title="org.openoj.compiler中的类">类</a></li>
<li class="navBarCell1Rev">使用</li>
<li><a href="../package-tree.html">树</a></li>
<li><a href="../../../../deprecated-list.html">已过时</a></li>
<li><a href="../../../../index-files/index-1.html">索引</a></li>
<li><a href="../../../../help-doc.html">帮助</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>上一个</li>
<li>下一个</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/openoj/compiler/class-use/OpenCPPCompiler.html" target="_top">框架</a></li>
<li><a href="OpenCPPCompiler.html" target="_top">无框架</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">所有类</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
trayvontang/openoj
|
openoj/doc/org/openoj/compiler/class-use/OpenCPPCompiler.html
|
HTML
|
apache-2.0
| 4,172
|
package Didi;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Scanner;
import java.util.function.IntPredicate;
import javax.security.auth.x500.X500Principal;
import Wangyi.countWays;
/**
* @author ZYJ
* @version 创建时间:2017年8月26日 下午1:23:50
* @Details
* 小青蛙有一天不小心落入了一个地下迷宫,
* 小青蛙希望用自己仅剩的体力值P跳出这个地下迷宫。
* 为了让问题简单,假设这是一个n*m的格子迷宫,
* 迷宫每个位置为0或者1,0代表这个位置有障碍物,
* 小青蛙达到不了这个位置;1代表小青蛙可以达到的位置。
* 小青蛙初始在(0,0)位置,地下迷宫的出口在(0,m-1)(保证这两个位置都是1,并且保证一定有起点到终点可达的路径),
* 小青蛙在迷宫中水平移动一个单位距离需要消耗1点体力值,
* 向上爬一个单位距离需要消耗3个单位的体力值,向下移动不消耗体力值,
* 当小青蛙的体力值等于0的时候还没有到达出口,小青蛙将无法逃离迷宫。
* 现在需要你帮助小青蛙计算出能否用仅剩的体力值跳出迷宫(即达到(0,m-1)位置)。
输入描述:
输入包括n+1行:
第一行为三个整数n,m(3 <= m,n <= 10),P(1 <= P <= 100)
接下来的n行:
每行m个0或者1,以空格分隔
输出描述:
如果能逃离迷宫,则输出一行体力消耗最小的路径,输出格式见样例所示;如果不能逃离迷宫,则输出"Can not escape!"。
测试数据保证答案唯一
输入例子1:
4 4 10
1 0 0 1
1 1 0 1
0 1 1 1
0 0 1 1
输出例子1:
[0,0],[1,0],[1,1],[2,1],[2,2],[2,3],[1,3],[0,3]
*/
public class Maze_Main {
static int[][] dir = {{1,0},{0,1},{-1,0},{0,-1}};
static int n;
static int m;
static int[][] map;
static String path = "";
static LinkedList<String> list = new LinkedList<>();
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
n = scan.nextInt();
m =scan.nextInt();
map = new int[n][m];
int P = scan.nextInt();
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[0].length; j++) {
map[i][j] = scan.nextInt();
}
}
findPath(0,0,P);
if(path != "")
System.out.println(path);
else System.out.println("Can not escape!");
}
public static void findPath(int i, int j, int p) {
// TODO Auto-generated method stub
if(i>= n || i<0 || j>= m || j<0 || p<0 || map[i][j] == 0 ) return;
list.add("["+i+","+j+"]");
map[i][j] = 0;
if(i == 0 && j == m-1) {
updatePath();
return;
}else {
findPath(i, j+1, p-1);
findPath(i, j-1, p-1);
findPath(i-1, j, p-3);
findPath(i+1, j, p);
map[i][j] = 1;
list.removeLast();
}
}
private static void updatePath() {
// TODO Auto-generated method stub
StringBuffer sb = new StringBuffer();
Iterator<String> it = list.iterator();
while(it.hasNext()) {
sb.append(it.next()+",");
}
sb.deleteCharAt(sb.length()-1);
path = sb.toString();
}
}
|
13732226055/codeBackup
|
Ali/src/Didi/Maze_Main.java
|
Java
|
apache-2.0
| 3,040
|
import Controller from '@ember/controller';
import { A } from '@ember/array';
import { computed } from '@ember/object';
import { inject as service } from '@ember/service';
import DS from 'ember-data';
import loadAll from 'ember-osf/utils/load-relationship';
import config from 'ember-get-config';
import Analytics from 'ember-osf/mixins/analytics';
import permissions from 'ember-osf/const/permissions';
import fileDownloadPath from '../../utils/file-download-path';
const { PromiseArray } = DS;
/**
* Takes an object with query parameter name as the key and value,
* or [value, maxLength] as the values.
*
* @method queryStringify
* @param queryParams {!object}
* @param queryParams.key {!array|!string}
* @param queryParams.key[0] {!string}
* @param queryParams.key[1] {int}
* @return {string}
*/
const DATE_LABEL = {
created: 'content.date_label.created_on',
submitted: 'content.date_label.submitted_on',
};
const PRE_MODERATION = 'pre-moderation';
const REJECTED = 'rejected';
const INITIAL = 'initial';
/**
* @module ember-preprints
* @submodule controllers
*/
/**
* @class Content Controller
*/
export default Controller.extend(Analytics, {
theme: service(),
currentUser: service(),
features: service(),
queryParams: {
chosenFile: 'file',
},
fullScreenMFR: false,
expandedAuthors: true,
showLicenseText: false,
primaryFile: null,
showModalClaimUser: false,
isPendingWithdrawal: false,
isWithdrawn: null,
isPlauditReady: false,
expandedAbstract: navigator.userAgent.includes('Prerender'),
hasTag: computed.bool('model.tags.length'),
relevantDate: computed.alias('model.dateCreated'),
metricsExtra: computed('model', function() {
return this.get('model.id');
}),
title: computed('model', function() {
return this.get('model.title');
}),
fullDescription: computed('model', function() {
return this.get('model.description');
}),
hyperlink: computed('model', function() {
return window.location.href;
}),
fileDownloadURL: computed('model', function() {
return fileDownloadPath(this.get('model.primaryFile'), this.get('model'));
}),
facebookAppId: computed('model', function() {
return this.get('model.provider.facebookAppId') ? this.get('model.provider.facebookAppId') : config.FB_APP_ID;
}),
supplementalMaterialDisplayLink: computed('node.links.html', function() {
const supplementalLink = this.get('node.links.html');
return supplementalLink.replace(/^https?:\/\//i, '');
}),
dateLabel: computed('model.provider.reviewsWorkflow', function() {
return this.get('model.provider.reviewsWorkflow') === PRE_MODERATION ?
DATE_LABEL.submitted :
DATE_LABEL.created;
}),
editButtonLabel: computed('model.{provider.reviewsWorkflow,reviewsState}', function () {
const editPreprint = 'content.project_button.edit_preprint';
const editResubmitPreprint = 'content.project_button.edit_resubmit_preprint';
return (
this.get('model.provider.reviewsWorkflow') === PRE_MODERATION
&& this.get('model.reviewsState') === REJECTED && this.get('isAdmin')
) ? editResubmitPreprint : editPreprint;
}),
isAdmin: computed('model', function() {
// True if the current user has admin permissions for the node that contains the preprint
return (this.get('model.currentUserPermissions') || []).includes(permissions.ADMIN);
}),
userIsContrib: computed('authors.[]', 'isAdmin', 'currentUser.currentUserId', function() {
if (this.get('isAdmin')) {
return true;
} else if (this.get('authors').length) {
const authorIds = this.get('authors').map((author) => {
return author.get('userId');
});
return this.get('currentUser.currentUserId') ? authorIds.includes(this.get('currentUser.currentUserId')) : false;
}
return false;
}),
showStatusBanner: computed('model.{public,provider.reviewsWorkflow,reviewsState}', 'userIsContrib', 'isPendingWithdrawal', function() {
return (
this.get('model.provider.reviewsWorkflow')
&& this.get('model.public')
&& this.get('userIsContrib')
&& this.get('model.reviewsState') !== INITIAL
) || this.get('isPendingWithdrawal');
}),
disciplineReduced: computed('model.subjects', function() {
// Preprint disciplines are displayed in collapsed form on content page
return this.get('model.subjects').reduce((acc, val) => acc.concat(val), []).uniqBy('id');
}),
/* eslint-disable ember/named-functions-in-promises */
authors: computed('model', function() {
// Cannot be called until node has loaded!
const model = this.get('model');
const contributors = A();
return PromiseArray.create({
promise: loadAll(model, 'contributors', contributors)
.then(() => contributors),
});
}),
/* eslint-enable ember/named-functions-in-promises */
fullLicenseText: computed('model.{license.text,licenseRecord}', function() {
const text = this.get('model.license.text') || '';
const { year = '', copyright_holders = [] } = this.get('model.licenseRecord'); /* eslint-disable-line camelcase */
return text
.replace(/({{year}})/g, year)
.replace(/({{copyrightHolders}})/g, copyright_holders.join(', '));
}),
hasShortenedDescription: computed('model.description', function() {
const description = this.get('model.description');
return description && description.length > 350;
}),
useShortenedDescription: computed('expandedAbstract', 'hasShortenedDescription', function() {
return this.get('hasShortenedDescription') && !this.get('expandedAbstract');
}),
description: computed('model.description', function() {
// Get a shortened version of the abstract, but doesn't cut in the middle of word by going
// to the last space.
return this.get('model.description')
.slice(0, 350)
.replace(/\s+\S*$/, '');
}),
emailHref: computed('model', function() {
const titleEncoded = encodeURIComponent(this.get('model.title'));
const hrefEncoded = encodeURIComponent(window.location.href);
return `mailto:?subject=${titleEncoded}&body=${hrefEncoded}`;
}),
isChronosProvider: computed('model.provider.id', function() {
const { chronosProviders } = config;
return Array.isArray(chronosProviders) && chronosProviders.includes(this.get('model.provider.id'));
}),
actions: {
toggleLicenseText() {
const licenseState = this.toggleProperty('showLicenseText') ? 'Expand' : 'Contract';
this.get('metrics')
.trackEvent({
category: 'button',
action: 'click',
label: `Content - License ${licenseState}`,
});
},
expandMFR() {
// State of fullScreenMFR before the transition (what the user perceives as the action)
const beforeState = this.toggleProperty('fullScreenMFR') ? 'Expand' : 'Contract';
this.get('metrics')
.trackEvent({
category: 'button',
action: 'click',
label: `Content - MFR ${beforeState}`,
});
},
expandAbstract() {
this.toggleProperty('expandedAbstract');
},
shareLink(href, category, action, label, extra) {
const metrics = this.get('metrics');
// TODO submit PR to ember-metrics for a trackSocial function for Google Analytics.
// For now, we'll use trackEvent.
metrics.trackEvent({
category,
action,
label,
extra,
});
if (label.includes('email')) { return; }
window.open(href, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,width=600,height=400');
return false;
},
// Sends Event to GA. Previously sent a second event to Keen to track non-contributor
// downloads, but that functionality has been removed. Stub left in place in case we want
// to double-log later.
trackNonContributors(category, label, url) {
this.send('click', category, label, url);
},
},
_returnContributors(contributors) {
return contributors;
},
});
|
CenterForOpenScience/ember-preprints
|
app/controllers/content/index.js
|
JavaScript
|
apache-2.0
| 8,707
|
// Copyright (c) 2016-2017 Nikita Pekin and the xkcd_rs contributors
// See the README.md file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
extern crate futures;
extern crate hyper;
extern crate hyper_tls;
extern crate tokio_core;
extern crate xkcd;
use hyper::Client;
use hyper_tls::HttpsConnector;
use tokio_core::reactor::Core;
fn main() {
let mut core = Core::new().unwrap();
let client = Client::configure()
.connector(HttpsConnector::new(4, &core.handle()).unwrap())
.build(&core.handle());
// Retrieve the latest comic.
let work = xkcd::comics::latest(&client);
let latest_comic = core.run(work).unwrap();
println!("Latest comic: {:?}", latest_comic);
}
|
indiv0/xkcd-rs
|
examples/latest.rs
|
Rust
|
apache-2.0
| 1,012
|
/**
* 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.apache.aurora.scheduler.updater;
import java.util.Set;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import org.apache.aurora.common.testing.easymock.EasyMockTest;
import org.apache.aurora.gen.AssignedTask;
import org.apache.aurora.gen.ExecutorConfig;
import org.apache.aurora.gen.Identity;
import org.apache.aurora.gen.Range;
import org.apache.aurora.gen.ScheduledTask;
import org.apache.aurora.gen.TaskConfig;
import org.apache.aurora.scheduler.base.JobKeys;
import org.apache.aurora.scheduler.base.Query;
import org.apache.aurora.scheduler.storage.TaskStore;
import org.apache.aurora.scheduler.storage.entities.IAssignedTask;
import org.apache.aurora.scheduler.storage.entities.IJobKey;
import org.apache.aurora.scheduler.storage.entities.IRange;
import org.apache.aurora.scheduler.storage.entities.IScheduledTask;
import org.apache.aurora.scheduler.storage.entities.ITaskConfig;
import org.easymock.IExpectationSetters;
import org.junit.Before;
import org.junit.Test;
import static org.easymock.EasyMock.expect;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
public class JobDiffTest extends EasyMockTest {
private static final IJobKey JOB = JobKeys.from("role", "env", "job");
private static final Set<IRange> NO_SCOPE = ImmutableSet.of();
private static final Set<IRange> CANARY_SCOPE = ImmutableSet.of(IRange.build(new Range(0, 0)));
private TaskStore store;
@Before
public void setUp() {
store = createMock(TaskStore.class);
}
@Test
public void testNoDiff() {
ITaskConfig task = makeTask("job", "echo");
expectFetch(instance(task, 0), instance(task, 1)).times(2);
control.replay();
assertEquals(
new JobDiff(ImmutableMap.of(), ImmutableSet.of(), ImmutableMap.of(0, task, 1, task)),
JobDiff.compute(store, JOB, JobDiff.asMap(task, 2), NO_SCOPE));
assertEquals(
new JobDiff(ImmutableMap.of(), ImmutableSet.of(), ImmutableMap.of(0, task, 1, task)),
JobDiff.compute(store, JOB, JobDiff.asMap(task, 2), CANARY_SCOPE));
}
@Test
public void testInstancesAdded() {
ITaskConfig task = makeTask("job", "echo");
expectFetch(instance(task, 0), instance(task, 1)).times(2);
control.replay();
assertEquals(
new JobDiff(ImmutableMap.of(), ImmutableSet.of(2, 3, 4), ImmutableMap.of(0, task, 1, task)),
JobDiff.compute(store, JOB, JobDiff.asMap(task, 5), NO_SCOPE));
assertEquals(
new JobDiff(ImmutableMap.of(), ImmutableSet.of(), ImmutableMap.of(0, task, 1, task)),
JobDiff.compute(store, JOB, JobDiff.asMap(task, 5), CANARY_SCOPE));
}
@Test
public void testInstancesRemoved() {
ITaskConfig task = makeTask("job", "echo");
expectFetch(instance(task, 0), instance(task, 1), instance(task, 2)).times(2);
control.replay();
assertEquals(
new JobDiff(ImmutableMap.of(1, task, 2, task), ImmutableSet.of(), ImmutableMap.of(0, task)),
JobDiff.compute(store, JOB, JobDiff.asMap(task, 1), NO_SCOPE));
assertEquals(
new JobDiff(
ImmutableMap.of(),
ImmutableSet.of(),
ImmutableMap.of(0, task, 1, task, 2, task)),
JobDiff.compute(store, JOB, JobDiff.asMap(task, 1), CANARY_SCOPE));
}
@Test
public void testFullUpdate() {
ITaskConfig oldTask = makeTask("job", "echo");
ITaskConfig newTask = makeTask("job", "echo2");
expectFetch(instance(oldTask, 0), instance(oldTask, 1), instance(oldTask, 2)).times(2);
control.replay();
assertEquals(
new JobDiff(
ImmutableMap.of(0, oldTask, 1, oldTask, 2, oldTask),
ImmutableSet.of(0, 1, 2),
ImmutableMap.of()),
JobDiff.compute(store, JOB, JobDiff.asMap(newTask, 3), NO_SCOPE));
assertEquals(
new JobDiff(
ImmutableMap.of(0, oldTask),
ImmutableSet.of(0),
ImmutableMap.of(1, oldTask, 2, oldTask)),
JobDiff.compute(store, JOB, JobDiff.asMap(newTask, 3), CANARY_SCOPE));
}
@Test
public void testMultipleConfigsAndHoles() {
ITaskConfig oldTask = makeTask("job", "echo");
ITaskConfig oldTask2 = makeTask("job", "echo1");
ITaskConfig newTask = makeTask("job", "echo2");
expectFetch(
instance(oldTask, 0), instance(newTask, 1), instance(oldTask2, 3), instance(oldTask, 4))
.times(2);
control.replay();
assertEquals(
new JobDiff(
ImmutableMap.of(0, oldTask, 3, oldTask2, 4, oldTask),
ImmutableSet.of(0, 2, 3, 4),
ImmutableMap.of(1, newTask)),
JobDiff.compute(store, JOB, JobDiff.asMap(newTask, 5), NO_SCOPE));
assertEquals(
new JobDiff(
ImmutableMap.of(0, oldTask),
ImmutableSet.of(0),
ImmutableMap.of(1, newTask, 3, oldTask2, 4, oldTask)),
JobDiff.compute(store, JOB, JobDiff.asMap(newTask, 5), CANARY_SCOPE));
}
@Test
public void testUnchangedInstances() {
ITaskConfig oldTask = makeTask("job", "echo");
ITaskConfig newTask = makeTask("job", "echo2");
expectFetch(instance(oldTask, 0), instance(newTask, 1), instance(oldTask, 2)).times(3);
control.replay();
assertEquals(
new JobDiff(
ImmutableMap.of(0, oldTask, 2, oldTask),
ImmutableSet.of(0, 2),
ImmutableMap.of(1, newTask)),
JobDiff.compute(store, JOB, JobDiff.asMap(newTask, 3), NO_SCOPE));
assertEquals(
new JobDiff(
ImmutableMap.of(0, oldTask),
ImmutableSet.of(0),
ImmutableMap.of(1, newTask, 2, oldTask)),
JobDiff.compute(store, JOB, JobDiff.asMap(newTask, 3), CANARY_SCOPE));
assertEquals(
new JobDiff(
ImmutableMap.of(0, oldTask),
ImmutableSet.of(0),
ImmutableMap.of(1, newTask, 2, oldTask)),
JobDiff.compute(store, JOB, JobDiff.asMap(newTask, 4), CANARY_SCOPE));
}
@Test
public void testObjectOverrides() {
control.replay();
JobDiff a = new JobDiff(
ImmutableMap.of(0, makeTask("job", "echo")),
ImmutableSet.of(0),
ImmutableMap.of());
JobDiff b = new JobDiff(
ImmutableMap.of(0, makeTask("job", "echo")),
ImmutableSet.of(0),
ImmutableMap.of());
JobDiff c = new JobDiff(
ImmutableMap.of(0, makeTask("job", "echo1")),
ImmutableSet.of(0),
ImmutableMap.of());
JobDiff d = new JobDiff(
ImmutableMap.of(0, makeTask("job", "echo")),
ImmutableSet.of(1),
ImmutableMap.of());
assertEquals(a, b);
assertEquals(ImmutableSet.of(a), ImmutableSet.of(a, b));
assertNotEquals(a, c);
assertNotEquals(a, "a string");
assertNotEquals(a, d);
assertEquals(a.toString(), b.toString());
}
private IExpectationSetters<?> expectFetch(IAssignedTask... results) {
ImmutableSet.Builder<IScheduledTask> tasks = ImmutableSet.builder();
for (IAssignedTask result : results) {
tasks.add(IScheduledTask.build(new ScheduledTask().setAssignedTask(result.newBuilder())));
}
return expect(store.fetchTasks(Query.jobScoped(JOB).active()))
.andReturn(tasks.build());
}
private static IAssignedTask instance(ITaskConfig config, int instance) {
return IAssignedTask.build(
new AssignedTask().setTask(config.newBuilder()).setInstanceId(instance));
}
private static ITaskConfig makeTask(String job, String config) {
return ITaskConfig.build(new TaskConfig()
.setOwner(new Identity("owner", "owner"))
.setEnvironment("test")
.setJobName(job)
.setExecutorConfig(new ExecutorConfig().setData(config)));
}
}
|
mschenck/aurora
|
src/test/java/org/apache/aurora/scheduler/updater/JobDiffTest.java
|
Java
|
apache-2.0
| 8,279
|
// Copyright (C) 2013 The Android Open Source Project
//
// 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.google.gerrit.server.project;
import com.google.common.base.Predicate;
import com.google.common.base.Strings;
import com.google.common.collect.ComparisonChain;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.Sets;
import com.google.gerrit.extensions.api.projects.BranchInfo;
import com.google.gerrit.extensions.common.ActionInfo;
import com.google.gerrit.extensions.common.WebLinkInfo;
import com.google.gerrit.extensions.registration.DynamicMap;
import com.google.gerrit.extensions.restapi.BadRequestException;
import com.google.gerrit.extensions.restapi.ResourceNotFoundException;
import com.google.gerrit.extensions.restapi.RestReadView;
import com.google.gerrit.extensions.restapi.RestView;
import com.google.gerrit.extensions.webui.UiAction;
import com.google.gerrit.reviewdb.client.RefNames;
import com.google.gerrit.server.WebLinks;
import com.google.gerrit.server.extensions.webui.UiActions;
import com.google.gerrit.server.git.GitRepositoryManager;
import com.google.inject.Inject;
import com.google.inject.util.Providers;
import dk.brics.automaton.RegExp;
import dk.brics.automaton.RunAutomaton;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.kohsuke.args4j.Option;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.TreeMap;
public class ListBranches implements RestReadView<ProjectResource> {
private final GitRepositoryManager repoManager;
private final DynamicMap<RestView<BranchResource>> branchViews;
private final WebLinks webLinks;
@Option(name = "--limit", aliases = {"-n"}, metaVar = "CNT", usage = "maximum number of branches to list")
public void setLimit(int limit) {
this.limit = limit;
}
@Option(name = "--start", aliases = {"-s"}, metaVar = "CNT", usage = "number of branches to skip")
public void setStart(int start) {
this.start = start;
}
@Option(name = "--match", aliases = {"-m"}, metaVar = "MATCH", usage = "match branches substring")
public void setMatchSubstring(String matchSubstring) {
this.matchSubstring = matchSubstring;
}
@Option(name = "--regex", aliases = {"-r"}, metaVar = "REGEX", usage = "match branches regex")
public void setMatchRegex(String matchRegex) {
this.matchRegex = matchRegex;
}
private int limit;
private int start;
private String matchSubstring;
private String matchRegex;
@Inject
public ListBranches(GitRepositoryManager repoManager,
DynamicMap<RestView<BranchResource>> branchViews,
WebLinks webLinks) {
this.repoManager = repoManager;
this.branchViews = branchViews;
this.webLinks = webLinks;
}
@Override
public List<BranchInfo> apply(ProjectResource rsrc)
throws ResourceNotFoundException, IOException, BadRequestException {
FluentIterable<BranchInfo> branches = allBranches(rsrc);
branches = filterBranches(branches);
if (start > 0) {
branches = branches.skip(start);
}
if (limit > 0) {
branches = branches.limit(limit);
}
return branches.toList();
}
private FluentIterable<BranchInfo> allBranches(ProjectResource rsrc)
throws IOException, ResourceNotFoundException {
List<Ref> refs;
try (Repository db = repoManager.openRepository(rsrc.getNameKey())) {
Collection<Ref> heads =
db.getRefDatabase().getRefs(Constants.R_HEADS).values();
refs = new ArrayList<>(heads.size() + 3);
refs.addAll(heads);
addRef(db, refs, Constants.HEAD);
addRef(db, refs, RefNames.REFS_CONFIG);
addRef(db, refs, RefNames.REFS_USERS_DEFAULT);
} catch (RepositoryNotFoundException noGitRepository) {
throw new ResourceNotFoundException();
}
Set<String> targets = Sets.newHashSetWithExpectedSize(1);
for (Ref ref : refs) {
if (ref.isSymbolic()) {
targets.add(ref.getTarget().getName());
}
}
List<BranchInfo> branches = new ArrayList<>(refs.size());
for (Ref ref : refs) {
if (ref.isSymbolic()) {
// A symbolic reference to another branch, instead of
// showing the resolved value, show the name it references.
//
String target = ref.getTarget().getName();
RefControl targetRefControl = rsrc.getControl().controlForRef(target);
if (!targetRefControl.isVisible()) {
continue;
}
if (target.startsWith(Constants.R_HEADS)) {
target = target.substring(Constants.R_HEADS.length());
}
BranchInfo b = new BranchInfo();
b.ref = ref.getName();
b.revision = target;
branches.add(b);
if (!Constants.HEAD.equals(ref.getName())) {
b.canDelete = targetRefControl.canDelete() ? true : null;
}
continue;
}
RefControl refControl = rsrc.getControl().controlForRef(ref.getName());
if (refControl.isVisible()) {
branches.add(createBranchInfo(ref, refControl, targets));
}
}
Collections.sort(branches, new BranchComparator());
return FluentIterable.from(branches);
}
private static class BranchComparator implements Comparator<BranchInfo> {
@Override
public int compare(BranchInfo a, BranchInfo b) {
return ComparisonChain.start()
.compareTrueFirst(isHead(a), isHead(b))
.compareTrueFirst(isConfig(a), isConfig(b))
.compare(a.ref, b.ref)
.result();
}
private static boolean isHead(BranchInfo i) {
return Constants.HEAD.equals(i.ref);
}
private static boolean isConfig(BranchInfo i) {
return RefNames.REFS_CONFIG.equals(i.ref);
}
}
private static void addRef(Repository db, List<Ref> refs, String name)
throws IOException {
Ref ref = db.getRef(name);
if (ref != null) {
refs.add(ref);
}
}
private FluentIterable<BranchInfo> filterBranches(
FluentIterable<BranchInfo> branches) throws BadRequestException {
if (!Strings.isNullOrEmpty(matchSubstring)) {
branches = branches.filter(new SubstringPredicate(matchSubstring));
} else if (!Strings.isNullOrEmpty(matchRegex)) {
branches = branches.filter(new RegexPredicate(matchRegex));
}
return branches;
}
private static class SubstringPredicate implements Predicate<BranchInfo> {
private final String substring;
private SubstringPredicate(String substring) {
this.substring = substring.toLowerCase(Locale.US);
}
@Override
public boolean apply(BranchInfo in) {
String ref = in.ref;
if (ref.startsWith(Constants.R_HEADS)) {
ref = ref.substring(Constants.R_HEADS.length());
}
ref = ref.toLowerCase(Locale.US);
return ref.contains(substring);
}
}
private static class RegexPredicate implements Predicate<BranchInfo> {
private final RunAutomaton a;
private RegexPredicate(String regex) throws BadRequestException {
if (regex.startsWith("^")) {
regex = regex.substring(1);
if (regex.endsWith("$") && !regex.endsWith("\\$")) {
regex = regex.substring(0, regex.length() - 1);
}
}
try {
a = new RunAutomaton(new RegExp(regex).toAutomaton());
} catch (IllegalArgumentException e) {
throw new BadRequestException(e.getMessage());
}
}
@Override
public boolean apply(BranchInfo in) {
if (!in.ref.startsWith(Constants.R_HEADS)){
return a.run(in.ref);
} else {
return a.run(in.ref.substring(Constants.R_HEADS.length()));
}
}
}
private BranchInfo createBranchInfo(Ref ref, RefControl refControl,
Set<String> targets) {
BranchInfo info = new BranchInfo();
info.ref = ref.getName();
info.revision = ref.getObjectId() != null ? ref.getObjectId().name() : null;
info.canDelete = !targets.contains(ref.getName()) && refControl.canDelete()
? true : null;
for (UiAction.Description d : UiActions.from(
branchViews,
new BranchResource(refControl.getProjectControl(), info),
Providers.of(refControl.getCurrentUser()))) {
if (info.actions == null) {
info.actions = new TreeMap<>();
}
info.actions.put(d.getId(), new ActionInfo(d));
}
FluentIterable<WebLinkInfo> links =
webLinks.getBranchLinks(
refControl.getProjectControl().getProject().getName(), ref.getName());
info.webLinks = links.isEmpty() ? null : links.toList();
return info;
}
}
|
NextGenIntelligence/gerrit
|
gerrit-server/src/main/java/com/google/gerrit/server/project/ListBranches.java
|
Java
|
apache-2.0
| 9,329
|
package com.braisgabin.couchbaseliteorm.sample;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
}
|
BraisGabin/couchbase-lite-orm
|
sample/src/androidTest/java/com/braisgabin/couchbaseliteorm/sample/ApplicationTest.java
|
Java
|
apache-2.0
| 362
|
package com.alipay.api.response;
import com.alipay.api.AlipayResponse;
/**
* ALIPAY API: alipay.eco.mycar.parking.enterinfo.sync response.
*
* @author auto create
* @since 1.0, 2017-08-25 17:10:00
*/
public class AlipayEcoMycarParkingEnterinfoSyncResponse extends AlipayResponse {
private static final long serialVersionUID = 4328627452584485732L;
}
|
wendal/alipay-sdk
|
src/main/java/com/alipay/api/response/AlipayEcoMycarParkingEnterinfoSyncResponse.java
|
Java
|
apache-2.0
| 368
|
/*******************************************************************************
* Copyright 2017-2018 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.
*******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include "self/self.hpp"
namespace self {
int bench(int argc, char **argv, bool main_bench) {
(void)argv; (void)main_bench;
SAFE(argc == 0 ? OK : FAIL, CRIT);
SAFE(bench_mode == CORR ? OK : FAIL, CRIT);
common();
conv();
bnorm();
auto &bs = benchdnn_stat;
return bs.tests == bs.passed ? OK : FAIL;
}
}
|
mlperf/training_results_v0.6
|
Fujitsu/benchmarks/resnet/implementations/mxnet/3rdparty/mkldnn/tests/benchdnn/self/self.cpp
|
C++
|
apache-2.0
| 1,129
|
<?php
// .-----------------------------------------------------------------------------------
// | WE TRY THE BEST WAY 杭州博也网络科技有限公司
// |-----------------------------------------------------------------------------------
// | Author: 贝贝 <hebiduhebi@163.com>
// | Copyright (c) 2013-2016, http://www.itboye.com. All Rights Reserved.
// |-----------------------------------------------------------------------------------
namespace Shop\Model;
use Think\Model\ViewModel;
class OrdersInfoViewModel extends ViewModel{
public $viewFields = array(
"Orders"=>array('_table'=>'__ORDERS__','_type'=>'LEFT','taxAmount','goodsAmount','id','order_code','post_price','discount_money','createtime','updatetime','uid','price','status','storeid','pay_status','order_status'),
"OrderInfo"=>array("_on"=>"Orders.order_code=OrderInfo.order_code","_table"=>"__ORDERS_CONTACTINFO__",'_type'=>'LEFT','wxno','detailinfo','contactname','country','city','province','detailinfo','area','mobile','id_card'),
"UcenterMember"=>array('_on'=>'Orders.uid=UcenterMember.id','_table'=>'__UCENTER_MEMBER__','_type'=>'LEFT','username','email'),
'Store'=>array('_on'=>'Orders.storeid=Store.id','_table'=>'__STORE__','_type'=>'LEFT','name'=>'store_name','desc'=> 'store_desc','banner'=>'store_banner','logo'=>'store_logo','service_phone'),
);
}
|
h136799711/baseItboye
|
Application/Shop/Model/OrdersInfoViewModel.class.php
|
PHP
|
apache-2.0
| 1,379
|
/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package server
import (
"fmt"
"io/ioutil"
"net"
"net/http"
"os"
goruntime "runtime"
"runtime/debug"
"sort"
"strconv"
"strings"
"sync/atomic"
"time"
jsonpatch "github.com/evanphx/json-patch"
"github.com/go-openapi/spec"
"github.com/google/uuid"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/runtime/serializer"
"k8s.io/apimachinery/pkg/util/clock"
"k8s.io/apimachinery/pkg/util/sets"
utilwaitgroup "k8s.io/apimachinery/pkg/util/waitgroup"
"k8s.io/apimachinery/pkg/version"
"k8s.io/apiserver/pkg/admission"
"k8s.io/apiserver/pkg/audit"
auditpolicy "k8s.io/apiserver/pkg/audit/policy"
"k8s.io/apiserver/pkg/authentication/authenticator"
"k8s.io/apiserver/pkg/authentication/authenticatorfactory"
authenticatorunion "k8s.io/apiserver/pkg/authentication/request/union"
"k8s.io/apiserver/pkg/authentication/user"
"k8s.io/apiserver/pkg/authorization/authorizer"
"k8s.io/apiserver/pkg/authorization/authorizerfactory"
authorizerunion "k8s.io/apiserver/pkg/authorization/union"
"k8s.io/apiserver/pkg/endpoints/discovery"
genericapifilters "k8s.io/apiserver/pkg/endpoints/filters"
apiopenapi "k8s.io/apiserver/pkg/endpoints/openapi"
apirequest "k8s.io/apiserver/pkg/endpoints/request"
"k8s.io/apiserver/pkg/features"
genericregistry "k8s.io/apiserver/pkg/registry/generic"
"k8s.io/apiserver/pkg/server/dynamiccertificates"
"k8s.io/apiserver/pkg/server/egressselector"
genericfilters "k8s.io/apiserver/pkg/server/filters"
"k8s.io/apiserver/pkg/server/healthz"
"k8s.io/apiserver/pkg/server/routes"
serverstore "k8s.io/apiserver/pkg/server/storage"
"k8s.io/apiserver/pkg/util/feature"
utilflowcontrol "k8s.io/apiserver/pkg/util/flowcontrol"
"k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes"
v1 "k8s.io/client-go/kubernetes/typed/core/v1"
restclient "k8s.io/client-go/rest"
"k8s.io/component-base/logs"
"k8s.io/klog/v2"
openapicommon "k8s.io/kube-openapi/pkg/common"
utilsnet "k8s.io/utils/net"
// install apis
_ "k8s.io/apiserver/pkg/apis/apiserver/install"
)
const (
// DefaultLegacyAPIPrefix is where the legacy APIs will be located.
DefaultLegacyAPIPrefix = "/api"
// APIGroupPrefix is where non-legacy API group will be located.
APIGroupPrefix = "/apis"
)
// Config is a structure used to configure a GenericAPIServer.
// Its members are sorted roughly in order of importance for composers.
type Config struct {
// SecureServing is required to serve https
SecureServing *SecureServingInfo
// Authentication is the configuration for authentication
Authentication AuthenticationInfo
// Authorization is the configuration for authorization
Authorization AuthorizationInfo
// LoopbackClientConfig is a config for a privileged loopback connection to the API server
// This is required for proper functioning of the PostStartHooks on a GenericAPIServer
// TODO: move into SecureServing(WithLoopback) as soon as insecure serving is gone
LoopbackClientConfig *restclient.Config
// EgressSelector provides a lookup mechanism for dialing outbound connections.
// It does so based on a EgressSelectorConfiguration which was read at startup.
EgressSelector *egressselector.EgressSelector
// RuleResolver is required to get the list of rules that apply to a given user
// in a given namespace
RuleResolver authorizer.RuleResolver
// AdmissionControl performs deep inspection of a given request (including content)
// to set values and determine whether its allowed
AdmissionControl admission.Interface
CorsAllowedOriginList []string
// FlowControl, if not nil, gives priority and fairness to request handling
FlowControl utilflowcontrol.Interface
EnableIndex bool
EnableProfiling bool
EnableDiscovery bool
// Requires generic profiling enabled
EnableContentionProfiling bool
EnableMetrics bool
DisabledPostStartHooks sets.String
// done values in this values for this map are ignored.
PostStartHooks map[string]PostStartHookConfigEntry
// Version will enable the /version endpoint if non-nil
Version *version.Info
// AuditBackend is where audit events are sent to.
AuditBackend audit.Backend
// AuditPolicyChecker makes the decision of whether and how to audit log a request.
AuditPolicyChecker auditpolicy.Checker
// ExternalAddress is the host name to use for external (public internet) facing URLs (e.g. Swagger)
// Will default to a value based on secure serving info and available ipv4 IPs.
ExternalAddress string
//===========================================================================
// Fields you probably don't care about changing
//===========================================================================
// BuildHandlerChainFunc allows you to build custom handler chains by decorating the apiHandler.
BuildHandlerChainFunc func(apiHandler http.Handler, c *Config) (secure http.Handler)
// HandlerChainWaitGroup allows you to wait for all chain handlers exit after the server shutdown.
HandlerChainWaitGroup *utilwaitgroup.SafeWaitGroup
// DiscoveryAddresses is used to build the IPs pass to discovery. If nil, the ExternalAddress is
// always reported
DiscoveryAddresses discovery.Addresses
// The default set of healthz checks. There might be more added via AddHealthChecks dynamically.
HealthzChecks []healthz.HealthChecker
// The default set of livez checks. There might be more added via AddHealthChecks dynamically.
LivezChecks []healthz.HealthChecker
// The default set of readyz-only checks. There might be more added via AddReadyzChecks dynamically.
ReadyzChecks []healthz.HealthChecker
// LegacyAPIGroupPrefixes is used to set up URL parsing for authorization and for validating requests
// to InstallLegacyAPIGroup. New API servers don't generally have legacy groups at all.
LegacyAPIGroupPrefixes sets.String
// RequestInfoResolver is used to assign attributes (used by admission and authorization) based on a request URL.
// Use-cases that are like kubelets may need to customize this.
RequestInfoResolver apirequest.RequestInfoResolver
// Serializer is required and provides the interface for serializing and converting objects to and from the wire
// The default (api.Codecs) usually works fine.
Serializer runtime.NegotiatedSerializer
// OpenAPIConfig will be used in generating OpenAPI spec. This is nil by default. Use DefaultOpenAPIConfig for "working" defaults.
OpenAPIConfig *openapicommon.Config
// RESTOptionsGetter is used to construct RESTStorage types via the generic registry.
RESTOptionsGetter genericregistry.RESTOptionsGetter
// If specified, all requests except those which match the LongRunningFunc predicate will timeout
// after this duration.
RequestTimeout time.Duration
// If specified, long running requests such as watch will be allocated a random timeout between this value, and
// twice this value. Note that it is up to the request handlers to ignore or honor this timeout. In seconds.
MinRequestTimeout int
// This represents the maximum amount of time it should take for apiserver to complete its startup
// sequence and become healthy. From apiserver's start time to when this amount of time has
// elapsed, /livez will assume that unfinished post-start hooks will complete successfully and
// therefore return true.
LivezGracePeriod time.Duration
// ShutdownDelayDuration allows to block shutdown for some time, e.g. until endpoints pointing to this API server
// have converged on all node. During this time, the API server keeps serving, /healthz will return 200,
// but /readyz will return failure.
ShutdownDelayDuration time.Duration
// The limit on the total size increase all "copy" operations in a json
// patch may cause.
// This affects all places that applies json patch in the binary.
JSONPatchMaxCopyBytes int64
// The limit on the request size that would be accepted and decoded in a write request
// 0 means no limit.
MaxRequestBodyBytes int64
// MaxRequestsInFlight is the maximum number of parallel non-long-running requests. Every further
// request has to wait. Applies only to non-mutating requests.
MaxRequestsInFlight int
// MaxMutatingRequestsInFlight is the maximum number of parallel mutating requests. Every further
// request has to wait.
MaxMutatingRequestsInFlight int
// Predicate which is true for paths of long-running http requests
LongRunningFunc apirequest.LongRunningRequestCheck
// GoawayChance is the probability that send a GOAWAY to HTTP/2 clients. When client received
// GOAWAY, the in-flight requests will not be affected and new requests will use
// a new TCP connection to triggering re-balancing to another server behind the load balance.
// Default to 0, means never send GOAWAY. Max is 0.02 to prevent break the apiserver.
GoawayChance float64
// MergedResourceConfig indicates which groupVersion enabled and its resources enabled/disabled.
// This is composed of genericapiserver defaultAPIResourceConfig and those parsed from flags.
// If not specify any in flags, then genericapiserver will only enable defaultAPIResourceConfig.
MergedResourceConfig *serverstore.ResourceConfig
// EventSink receives events about the life cycle of the API server, e.g. readiness, serving, signals and termination.
EventSink EventSink
//===========================================================================
// values below here are targets for removal
//===========================================================================
// PublicAddress is the IP address where members of the cluster (kubelet,
// kube-proxy, services, etc.) can reach the GenericAPIServer.
// If nil or 0.0.0.0, the host's default interface will be used.
PublicAddress net.IP
// EquivalentResourceRegistry provides information about resources equivalent to a given resource,
// and the kind associated with a given resource. As resources are installed, they are registered here.
EquivalentResourceRegistry runtime.EquivalentResourceRegistry
// A func that returns whether the server is terminating. This can be nil.
IsTerminating func() bool
}
// EventSink allows to create events.
type EventSink interface {
Create(event *corev1.Event) (*corev1.Event, error)
}
type RecommendedConfig struct {
Config
// SharedInformerFactory provides shared informers for Kubernetes resources. This value is set by
// RecommendedOptions.CoreAPI.ApplyTo called by RecommendedOptions.ApplyTo. It uses an in-cluster client config
// by default, or the kubeconfig given with kubeconfig command line flag.
SharedInformerFactory informers.SharedInformerFactory
// ClientConfig holds the kubernetes client configuration.
// This value is set by RecommendedOptions.CoreAPI.ApplyTo called by RecommendedOptions.ApplyTo.
// By default in-cluster client config is used.
ClientConfig *restclient.Config
}
type SecureServingInfo struct {
// Listener is the secure server network listener.
Listener net.Listener
// Cert is the main server cert which is used if SNI does not match. Cert must be non-nil and is
// allowed to be in SNICerts.
Cert dynamiccertificates.CertKeyContentProvider
// SNICerts are the TLS certificates used for SNI.
SNICerts []dynamiccertificates.SNICertKeyContentProvider
// ClientCA is the certificate bundle for all the signers that you'll recognize for incoming client certificates
ClientCA dynamiccertificates.CAContentProvider
// MinTLSVersion optionally overrides the minimum TLS version supported.
// Values are from tls package constants (https://golang.org/pkg/crypto/tls/#pkg-constants).
MinTLSVersion uint16
// CipherSuites optionally overrides the list of allowed cipher suites for the server.
// Values are from tls package constants (https://golang.org/pkg/crypto/tls/#pkg-constants).
CipherSuites []uint16
// HTTP2MaxStreamsPerConnection is the limit that the api server imposes on each client.
// A value of zero means to use the default provided by golang's HTTP/2 support.
HTTP2MaxStreamsPerConnection int
// DisableHTTP2 indicates that http2 should not be enabled.
DisableHTTP2 bool
}
type AuthenticationInfo struct {
// APIAudiences is a list of identifier that the API identifies as. This is
// used by some authenticators to validate audience bound credentials.
APIAudiences authenticator.Audiences
// Authenticator determines which subject is making the request
Authenticator authenticator.Request
}
type AuthorizationInfo struct {
// Authorizer determines whether the subject is allowed to make the request based only
// on the RequestURI
Authorizer authorizer.Authorizer
}
// NewConfig returns a Config struct with the default values
func NewConfig(codecs serializer.CodecFactory) *Config {
defaultHealthChecks := []healthz.HealthChecker{healthz.PingHealthz, healthz.LogHealthz}
return &Config{
Serializer: codecs,
BuildHandlerChainFunc: DefaultBuildHandlerChain,
HandlerChainWaitGroup: new(utilwaitgroup.SafeWaitGroup),
LegacyAPIGroupPrefixes: sets.NewString(DefaultLegacyAPIPrefix),
DisabledPostStartHooks: sets.NewString(),
PostStartHooks: map[string]PostStartHookConfigEntry{},
HealthzChecks: append([]healthz.HealthChecker{}, defaultHealthChecks...),
ReadyzChecks: append([]healthz.HealthChecker{}, defaultHealthChecks...),
LivezChecks: append([]healthz.HealthChecker{}, defaultHealthChecks...),
EnableIndex: true,
EnableDiscovery: true,
EnableProfiling: true,
EnableMetrics: true,
MaxRequestsInFlight: 400,
MaxMutatingRequestsInFlight: 200,
RequestTimeout: time.Duration(60) * time.Second,
MinRequestTimeout: 1800,
LivezGracePeriod: time.Duration(0),
ShutdownDelayDuration: time.Duration(0),
// 1.5MB is the default client request size in bytes
// the etcd server should accept. See
// https://github.com/etcd-io/etcd/blob/release-3.4/embed/config.go#L56.
// A request body might be encoded in json, and is converted to
// proto when persisted in etcd, so we allow 2x as the largest size
// increase the "copy" operations in a json patch may cause.
JSONPatchMaxCopyBytes: int64(3 * 1024 * 1024),
// 1.5MB is the recommended client request size in byte
// the etcd server should accept. See
// https://github.com/etcd-io/etcd/blob/release-3.4/embed/config.go#L56.
// A request body might be encoded in json, and is converted to
// proto when persisted in etcd, so we allow 2x as the largest request
// body size to be accepted and decoded in a write request.
MaxRequestBodyBytes: int64(3 * 1024 * 1024),
// Default to treating watch as a long-running operation
// Generic API servers have no inherent long-running subresources
LongRunningFunc: genericfilters.BasicLongRunningRequestCheck(sets.NewString("watch"), sets.NewString()),
}
}
// NewRecommendedConfig returns a RecommendedConfig struct with the default values
func NewRecommendedConfig(codecs serializer.CodecFactory) *RecommendedConfig {
return &RecommendedConfig{
Config: *NewConfig(codecs),
}
}
func DefaultOpenAPIConfig(getDefinitions openapicommon.GetOpenAPIDefinitions, defNamer *apiopenapi.DefinitionNamer) *openapicommon.Config {
return &openapicommon.Config{
ProtocolList: []string{"https"},
IgnorePrefixes: []string{},
Info: &spec.Info{
InfoProps: spec.InfoProps{
Title: "Generic API Server",
},
},
DefaultResponse: &spec.Response{
ResponseProps: spec.ResponseProps{
Description: "Default Response.",
},
},
GetOperationIDAndTags: apiopenapi.GetOperationIDAndTags,
GetDefinitionName: defNamer.GetDefinitionName,
GetDefinitions: getDefinitions,
}
}
func (c *AuthenticationInfo) ApplyClientCert(clientCA dynamiccertificates.CAContentProvider, servingInfo *SecureServingInfo) error {
if servingInfo == nil {
return nil
}
if clientCA == nil {
return nil
}
if servingInfo.ClientCA == nil {
servingInfo.ClientCA = clientCA
return nil
}
servingInfo.ClientCA = dynamiccertificates.NewUnionCAContentProvider(servingInfo.ClientCA, clientCA)
return nil
}
type completedConfig struct {
*Config
//===========================================================================
// values below here are filled in during completion
//===========================================================================
// SharedInformerFactory provides shared informers for resources
SharedInformerFactory informers.SharedInformerFactory
}
type CompletedConfig struct {
// Embed a private pointer that cannot be instantiated outside of this package.
*completedConfig
}
// AddHealthChecks adds a health check to our config to be exposed by the health endpoints
// of our configured apiserver. We should prefer this to adding healthChecks directly to
// the config unless we explicitly want to add a healthcheck only to a specific health endpoint.
func (c *Config) AddHealthChecks(healthChecks ...healthz.HealthChecker) {
for _, check := range healthChecks {
c.HealthzChecks = append(c.HealthzChecks, check)
c.LivezChecks = append(c.LivezChecks, check)
c.ReadyzChecks = append(c.ReadyzChecks, check)
}
}
// AddPostStartHook allows you to add a PostStartHook that will later be added to the server itself in a New call.
// Name conflicts will cause an error.
func (c *Config) AddPostStartHook(name string, hook PostStartHookFunc) error {
if len(name) == 0 {
return fmt.Errorf("missing name")
}
if hook == nil {
return fmt.Errorf("hook func may not be nil: %q", name)
}
if c.DisabledPostStartHooks.Has(name) {
klog.V(1).Infof("skipping %q because it was explicitly disabled", name)
return nil
}
if postStartHook, exists := c.PostStartHooks[name]; exists {
// this is programmer error, but it can be hard to debug
return fmt.Errorf("unable to add %q because it was already registered by: %s", name, postStartHook.originatingStack)
}
c.PostStartHooks[name] = PostStartHookConfigEntry{hook: hook, originatingStack: string(debug.Stack())}
return nil
}
// AddPostStartHookOrDie allows you to add a PostStartHook, but dies on failure.
func (c *Config) AddPostStartHookOrDie(name string, hook PostStartHookFunc) {
if err := c.AddPostStartHook(name, hook); err != nil {
klog.Fatalf("Error registering PostStartHook %q: %v", name, err)
}
}
// Complete fills in any fields not set that are required to have valid data and can be derived
// from other fields. If you're going to `ApplyOptions`, do that first. It's mutating the receiver.
func (c *Config) Complete(informers informers.SharedInformerFactory) CompletedConfig {
if len(c.ExternalAddress) == 0 && c.PublicAddress != nil {
c.ExternalAddress = c.PublicAddress.String()
}
// if there is no port, and we listen on one securely, use that one
if _, _, err := net.SplitHostPort(c.ExternalAddress); err != nil {
if c.SecureServing == nil {
klog.Fatalf("cannot derive external address port without listening on a secure port.")
}
_, port, err := c.SecureServing.HostPort()
if err != nil {
klog.Fatalf("cannot derive external address from the secure port: %v", err)
}
c.ExternalAddress = net.JoinHostPort(c.ExternalAddress, strconv.Itoa(port))
}
if c.OpenAPIConfig != nil {
if c.OpenAPIConfig.SecurityDefinitions != nil {
// Setup OpenAPI security: all APIs will have the same authentication for now.
c.OpenAPIConfig.DefaultSecurity = []map[string][]string{}
keys := []string{}
for k := range *c.OpenAPIConfig.SecurityDefinitions {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
c.OpenAPIConfig.DefaultSecurity = append(c.OpenAPIConfig.DefaultSecurity, map[string][]string{k: {}})
}
if c.OpenAPIConfig.CommonResponses == nil {
c.OpenAPIConfig.CommonResponses = map[int]spec.Response{}
}
if _, exists := c.OpenAPIConfig.CommonResponses[http.StatusUnauthorized]; !exists {
c.OpenAPIConfig.CommonResponses[http.StatusUnauthorized] = spec.Response{
ResponseProps: spec.ResponseProps{
Description: "Unauthorized",
},
}
}
}
// make sure we populate info, and info.version, if not manually set
if c.OpenAPIConfig.Info == nil {
c.OpenAPIConfig.Info = &spec.Info{}
}
if c.OpenAPIConfig.Info.Version == "" {
if c.Version != nil {
c.OpenAPIConfig.Info.Version = strings.Split(c.Version.String(), "-")[0]
} else {
c.OpenAPIConfig.Info.Version = "unversioned"
}
}
}
if c.DiscoveryAddresses == nil {
c.DiscoveryAddresses = discovery.DefaultAddresses{DefaultAddress: c.ExternalAddress}
}
if c.EventSink == nil {
c.EventSink = nullEventSink{}
}
AuthorizeClientBearerToken(c.LoopbackClientConfig, &c.Authentication, &c.Authorization)
if c.RequestInfoResolver == nil {
c.RequestInfoResolver = NewRequestInfoResolver(c)
}
if c.EquivalentResourceRegistry == nil {
if c.RESTOptionsGetter == nil {
c.EquivalentResourceRegistry = runtime.NewEquivalentResourceRegistry()
} else {
c.EquivalentResourceRegistry = runtime.NewEquivalentResourceRegistryWithIdentity(func(groupResource schema.GroupResource) string {
// use the storage prefix as the key if possible
if opts, err := c.RESTOptionsGetter.GetRESTOptions(groupResource); err == nil {
return opts.ResourcePrefix
}
// otherwise return "" to use the default key (parent GV name)
return ""
})
}
}
return CompletedConfig{&completedConfig{c, informers}}
}
// Complete fills in any fields not set that are required to have valid data and can be derived
// from other fields. If you're going to `ApplyOptions`, do that first. It's mutating the receiver.
func (c *RecommendedConfig) Complete() CompletedConfig {
if c.ClientConfig != nil {
ref, err := eventReference()
if err != nil {
klog.Warningf("Failed to derive event reference, won't create events: %v", err)
c.EventSink = nullEventSink{}
} else {
ns := ref.Namespace
if len(ns) == 0 {
ns = "default"
}
c.EventSink = &v1.EventSinkImpl{
Interface: kubernetes.NewForConfigOrDie(c.ClientConfig).CoreV1().Events(ns),
}
}
}
return c.Config.Complete(c.SharedInformerFactory)
}
func eventReference() (*corev1.ObjectReference, error) {
ns := os.Getenv("POD_NAMESPACE")
pod := os.Getenv("POD_NAME")
if len(ns) == 0 && len(pod) > 0 {
serviceAccountNamespaceFile := "/var/run/secrets/kubernetes.io/serviceaccount/namespace"
if _, err := os.Stat(serviceAccountNamespaceFile); err == nil {
bs, err := ioutil.ReadFile(serviceAccountNamespaceFile)
if err != nil {
return nil, err
}
ns = string(bs)
}
}
if len(ns) == 0 {
pod = ""
ns = "kube-system"
}
if len(pod) == 0 {
return &corev1.ObjectReference{
Kind: "Namespace",
Name: ns,
APIVersion: "v1",
}, nil
}
return &corev1.ObjectReference{
Kind: "Pod",
Namespace: ns,
Name: pod,
APIVersion: "v1",
}, nil
}
// New creates a new server which logically combines the handling chain with the passed server.
// name is used to differentiate for logging. The handler chain in particular can be difficult as it starts delgating.
// delegationTarget may not be nil.
func (c completedConfig) New(name string, delegationTarget DelegationTarget) (*GenericAPIServer, error) {
if c.Serializer == nil {
return nil, fmt.Errorf("Genericapiserver.New() called with config.Serializer == nil")
}
if c.LoopbackClientConfig == nil {
return nil, fmt.Errorf("Genericapiserver.New() called with config.LoopbackClientConfig == nil")
}
if c.EquivalentResourceRegistry == nil {
return nil, fmt.Errorf("Genericapiserver.New() called with config.EquivalentResourceRegistry == nil")
}
handlerChainBuilder := func(handler http.Handler) http.Handler {
return c.BuildHandlerChainFunc(handler, c.Config)
}
apiServerHandler := NewAPIServerHandler(name, c.Serializer, handlerChainBuilder, delegationTarget.UnprotectedHandler())
s := &GenericAPIServer{
discoveryAddresses: c.DiscoveryAddresses,
LoopbackClientConfig: c.LoopbackClientConfig,
legacyAPIGroupPrefixes: c.LegacyAPIGroupPrefixes,
admissionControl: c.AdmissionControl,
Serializer: c.Serializer,
AuditBackend: c.AuditBackend,
Authorizer: c.Authorization.Authorizer,
delegationTarget: delegationTarget,
EquivalentResourceRegistry: c.EquivalentResourceRegistry,
HandlerChainWaitGroup: c.HandlerChainWaitGroup,
minRequestTimeout: time.Duration(c.MinRequestTimeout) * time.Second,
ShutdownTimeout: c.RequestTimeout,
ShutdownDelayDuration: c.ShutdownDelayDuration,
SecureServingInfo: c.SecureServing,
ExternalAddress: c.ExternalAddress,
Handler: apiServerHandler,
listedPathProvider: apiServerHandler,
openAPIConfig: c.OpenAPIConfig,
postStartHooks: map[string]postStartHookEntry{},
preShutdownHooks: map[string]preShutdownHookEntry{},
disabledPostStartHooks: c.DisabledPostStartHooks,
healthzChecks: c.HealthzChecks,
livezChecks: c.LivezChecks,
readyzChecks: c.ReadyzChecks,
readinessStopCh: make(chan struct{}),
livezGracePeriod: c.LivezGracePeriod,
DiscoveryGroupManager: discovery.NewRootAPIsHandler(c.DiscoveryAddresses, c.Serializer),
maxRequestBodyBytes: c.MaxRequestBodyBytes,
livezClock: clock.RealClock{},
eventSink: c.EventSink,
}
ref, err := eventReference()
if err != nil {
klog.Warningf("Failed to derive event reference, won't create events: %v", err)
c.EventSink = nullEventSink{}
}
s.eventRef = ref
for {
if c.JSONPatchMaxCopyBytes <= 0 {
break
}
existing := atomic.LoadInt64(&jsonpatch.AccumulatedCopySizeLimit)
if existing > 0 && existing < c.JSONPatchMaxCopyBytes {
break
}
if atomic.CompareAndSwapInt64(&jsonpatch.AccumulatedCopySizeLimit, existing, c.JSONPatchMaxCopyBytes) {
break
}
}
// first add poststarthooks from delegated targets
for k, v := range delegationTarget.PostStartHooks() {
s.postStartHooks[k] = v
}
for k, v := range delegationTarget.PreShutdownHooks() {
s.preShutdownHooks[k] = v
}
// add poststarthooks that were preconfigured. Using the add method will give us an error if the same name has already been registered.
for name, preconfiguredPostStartHook := range c.PostStartHooks {
if err := s.AddPostStartHook(name, preconfiguredPostStartHook.hook); err != nil {
return nil, err
}
}
genericApiServerHookName := "generic-apiserver-start-informers"
if c.SharedInformerFactory != nil {
if !s.isPostStartHookRegistered(genericApiServerHookName) {
err := s.AddPostStartHook(genericApiServerHookName, func(context PostStartHookContext) error {
c.SharedInformerFactory.Start(context.StopCh)
return nil
})
if err != nil {
return nil, err
}
// TODO: Once we get rid of /healthz consider changing this to post-start-hook.
err = s.addReadyzChecks(healthz.NewInformerSyncHealthz(c.SharedInformerFactory))
if err != nil {
return nil, err
}
}
}
const priorityAndFairnessConfigConsumerHookName = "priority-and-fairness-config-consumer"
if s.isPostStartHookRegistered(priorityAndFairnessConfigConsumerHookName) {
} else if c.FlowControl != nil {
err := s.AddPostStartHook(priorityAndFairnessConfigConsumerHookName, func(context PostStartHookContext) error {
go c.FlowControl.Run(context.StopCh)
return nil
})
if err != nil {
return nil, err
}
// TODO(yue9944882): plumb pre-shutdown-hook for request-management system?
} else {
klog.V(3).Infof("Not requested to run hook %s", priorityAndFairnessConfigConsumerHookName)
}
for _, delegateCheck := range delegationTarget.HealthzChecks() {
skip := false
for _, existingCheck := range c.HealthzChecks {
if existingCheck.Name() == delegateCheck.Name() {
skip = true
break
}
}
if skip {
continue
}
s.AddHealthChecks(delegateCheck)
}
s.listedPathProvider = routes.ListedPathProviders{s.listedPathProvider, delegationTarget}
installAPI(s, c.Config)
// use the UnprotectedHandler from the delegation target to ensure that we don't attempt to double authenticator, authorize,
// or some other part of the filter chain in delegation cases.
if delegationTarget.UnprotectedHandler() == nil && c.EnableIndex {
s.Handler.NonGoRestfulMux.NotFoundHandler(routes.IndexLister{
StatusCode: http.StatusNotFound,
PathProvider: s.listedPathProvider,
})
}
return s, nil
}
func DefaultBuildHandlerChain(apiHandler http.Handler, c *Config) http.Handler {
handler := genericapifilters.WithAuthorization(apiHandler, c.Authorization.Authorizer, c.Serializer)
if c.FlowControl != nil {
handler = genericfilters.WithPriorityAndFairness(handler, c.LongRunningFunc, c.FlowControl)
} else {
handler = genericfilters.WithMaxInFlightLimit(handler, c.MaxRequestsInFlight, c.MaxMutatingRequestsInFlight, c.LongRunningFunc)
}
handler = genericapifilters.WithImpersonation(handler, c.Authorization.Authorizer, c.Serializer)
handler = genericapifilters.WithAudit(handler, c.AuditBackend, c.AuditPolicyChecker, c.LongRunningFunc)
failedHandler := genericapifilters.Unauthorized(c.Serializer)
failedHandler = genericapifilters.WithFailedAuthenticationAudit(failedHandler, c.AuditBackend, c.AuditPolicyChecker)
handler = genericapifilters.WithAuthentication(handler, c.Authentication.Authenticator, failedHandler, c.Authentication.APIAudiences)
handler = genericfilters.WithCORS(handler, c.CorsAllowedOriginList, nil, nil, nil, "true")
handler = genericfilters.WithTimeoutForNonLongRunningRequests(handler, c.LongRunningFunc, c.RequestTimeout)
handler = genericfilters.WithWaitGroup(handler, c.LongRunningFunc, c.HandlerChainWaitGroup)
handler = WithLateConnectionFilter(handler)
handler = genericapifilters.WithRequestInfo(handler, c.RequestInfoResolver)
if c.SecureServing != nil && !c.SecureServing.DisableHTTP2 && c.GoawayChance > 0 {
handler = genericfilters.WithProbabilisticGoaway(handler, c.GoawayChance)
}
handler = genericapifilters.WithAuditAnnotations(handler, c.AuditBackend, c.AuditPolicyChecker)
handler = genericapifilters.WithWarningRecorder(handler)
handler = genericapifilters.WithCacheControl(handler)
handler = genericfilters.WithPanicRecovery(handler, c.IsTerminating)
return handler
}
func installAPI(s *GenericAPIServer, c *Config) {
if c.EnableIndex {
routes.Index{}.Install(s.listedPathProvider, s.Handler.NonGoRestfulMux)
}
if c.EnableProfiling {
routes.Profiling{}.Install(s.Handler.NonGoRestfulMux)
if c.EnableContentionProfiling {
goruntime.SetBlockProfileRate(1)
}
// so far, only logging related endpoints are considered valid to add for these debug flags.
routes.DebugFlags{}.Install(s.Handler.NonGoRestfulMux, "v", routes.StringFlagPutHandler(logs.GlogSetter))
}
if c.EnableMetrics {
if c.EnableProfiling {
routes.MetricsWithReset{}.Install(s.Handler.NonGoRestfulMux)
} else {
routes.DefaultMetrics{}.Install(s.Handler.NonGoRestfulMux)
}
}
routes.Version{Version: c.Version}.Install(s.Handler.GoRestfulContainer)
if c.EnableDiscovery {
s.Handler.GoRestfulContainer.Add(s.DiscoveryGroupManager.WebService())
}
if feature.DefaultFeatureGate.Enabled(features.APIPriorityAndFairness) {
c.FlowControl.Install(s.Handler.NonGoRestfulMux)
}
}
func NewRequestInfoResolver(c *Config) *apirequest.RequestInfoFactory {
apiPrefixes := sets.NewString(strings.Trim(APIGroupPrefix, "/")) // all possible API prefixes
legacyAPIPrefixes := sets.String{} // APIPrefixes that won't have groups (legacy)
for legacyAPIPrefix := range c.LegacyAPIGroupPrefixes {
apiPrefixes.Insert(strings.Trim(legacyAPIPrefix, "/"))
legacyAPIPrefixes.Insert(strings.Trim(legacyAPIPrefix, "/"))
}
return &apirequest.RequestInfoFactory{
APIPrefixes: apiPrefixes,
GrouplessAPIPrefixes: legacyAPIPrefixes,
}
}
func (s *SecureServingInfo) HostPort() (string, int, error) {
if s == nil || s.Listener == nil {
return "", 0, fmt.Errorf("no listener found")
}
addr := s.Listener.Addr().String()
host, portStr, err := net.SplitHostPort(addr)
if err != nil {
return "", 0, fmt.Errorf("failed to get port from listener address %q: %v", addr, err)
}
port, err := utilsnet.ParsePort(portStr, true)
if err != nil {
return "", 0, fmt.Errorf("invalid non-numeric port %q", portStr)
}
return host, port, nil
}
// AuthorizeClientBearerToken wraps the authenticator and authorizer in loopback authentication logic
// if the loopback client config is specified AND it has a bearer token. Note that if either authn or
// authz is nil, this function won't add a token authenticator or authorizer.
func AuthorizeClientBearerToken(loopback *restclient.Config, authn *AuthenticationInfo, authz *AuthorizationInfo) {
if loopback == nil || len(loopback.BearerToken) == 0 {
return
}
if authn == nil || authz == nil {
// prevent nil pointer panic
return
}
if authn.Authenticator == nil || authz.Authorizer == nil {
// authenticator or authorizer might be nil if we want to bypass authz/authn
// and we also do nothing in this case.
return
}
privilegedLoopbackToken := loopback.BearerToken
var uid = uuid.New().String()
tokens := make(map[string]*user.DefaultInfo)
tokens[privilegedLoopbackToken] = &user.DefaultInfo{
Name: user.APIServerUser,
UID: uid,
Groups: []string{user.SystemPrivilegedGroup},
}
tokenAuthenticator := authenticatorfactory.NewFromTokens(tokens)
authn.Authenticator = authenticatorunion.New(tokenAuthenticator, authn.Authenticator)
if !skipSystemMastersAuthorizer {
tokenAuthorizer := authorizerfactory.NewPrivilegedGroups(user.SystemPrivilegedGroup)
authz.Authorizer = authorizerunion.New(tokenAuthorizer, authz.Authorizer)
}
}
type nullEventSink struct{}
func (nullEventSink) Create(event *corev1.Event) (*corev1.Event, error) {
return nil, nil
}
|
tnozicka/origin
|
vendor/k8s.io/apiserver/pkg/server/config.go
|
GO
|
apache-2.0
| 34,568
|
local kong_mlcache = require "kong.mlcache"
local type = type
local max = math.max
local ngx_log = ngx.log
local ngx_now = ngx.now
local ERR = ngx.ERR
local NOTICE = ngx.NOTICE
local DEBUG = ngx.DEBUG
local SHM_CACHE = "kong_cache"
--[[
Hypothesis
----------
Item size: 1024 bytes
Max memory limit: 500 MiBs
LRU size must be: (500 * 2^20) / 1024 = 512000
Floored: 500.000 items should be a good default
--]]
local LRU_SIZE = 5e5
local _init
local function log(lvl, ...)
return ngx_log(lvl, "[DB cache] ", ...)
end
-- Temporary fix to convert soft callback errors into hard ones.
-- FIXME: use upstream mlcache lib instead of local copy
local soft_to_hard
do
local s2h_cache = setmetatable({}, { __mode = "k" })
local function create_wrapper(cb)
s2h_cache[cb] = function(...)
local result, err = cb(...)
if err then
error(err)
end
return result
end
return s2h_cache[cb]
end
soft_to_hard = function(cb)
return s2h_cache[cb] or create_wrapper(cb)
end
end
local _M = {}
local mt = { __index = _M }
function _M.new(opts)
if _init then
return error("kong.cache was already created")
end
-- opts validation
opts = opts or {}
if not opts.cluster_events then
return error("opts.cluster_events is required")
end
if not opts.worker_events then
return error("opts.worker_events is required")
end
if opts.propagation_delay and type(opts.propagation_delay) ~= "number" then
return error("opts.propagation_delay must be a number")
end
if opts.ttl and type(opts.ttl) ~= "number" then
return error("opts.ttl must be a number")
end
if opts.neg_ttl and type(opts.neg_ttl) ~= "number" then
return error("opts.neg_ttl must be a number")
end
if opts.resty_lock_opts and type(opts.resty_lock_opts) ~= "table" then
return error("opts.resty_lock_opts must be a table")
end
local mlcache, err = kong_mlcache.new(SHM_CACHE, opts.worker_events, {
lru_size = LRU_SIZE,
ttl = max(opts.ttl or 3600, 0),
neg_ttl = max(opts.neg_ttl or 300, 0),
resty_lock_opts = opts.resty_lock_opts,
})
if not mlcache then
return nil, "failed to instantiate mlcache: " .. err
end
local self = {
propagation_delay = max(opts.propagation_delay or 0, 0),
cluster_events = opts.cluster_events,
mlcache = mlcache,
}
local ok, err = self.cluster_events:subscribe("invalidations", function(key)
log(DEBUG, "received invalidate event from cluster for key: '", key, "'")
self:invalidate_local(key)
end)
if not ok then
return nil, "failed to subscribe to invalidations cluster events " ..
"channel: " .. err
end
_init = true
return setmetatable(self, mt)
end
function _M:get(key, opts, cb, ...)
if type(key) ~= "string" then
return error("key must be a string")
end
--log(DEBUG, "get from key: ", key)
local v, err = self.mlcache:get(key, opts, soft_to_hard(cb), ...)
if err then
return nil, "failed to get from node cache: " .. err
end
return v
end
function _M:probe(key)
if type(key) ~= "string" then
return error("key must be a string")
end
local ttl, err, v = self.mlcache:probe(key)
if err then
return nil, "failed to probe from node cache: " .. err
end
return ttl, nil, v
end
function _M:invalidate_local(key)
if type(key) ~= "string" then
return error("key must be a string")
end
log(DEBUG, "invalidating (local): '", key, "'")
local ok, err = self.mlcache:delete(key)
if not ok then
log(ERR, "failed to delete entity from node cache: ", err)
end
end
function _M:invalidate(key)
if type(key) ~= "string" then
return error("key must be a string")
end
self:invalidate_local(key)
local nbf
if self.propagation_delay > 0 then
nbf = ngx_now() + self.propagation_delay
end
log(DEBUG, "broadcasting (cluster) invalidation for key: '", key, "' ",
"with nbf: '", nbf or "none", "'")
local ok, err = self.cluster_events:broadcast("invalidations", key, nbf)
if not ok then
log(ERR, "failed to broadcast cached entity invalidation: ", err)
end
end
function _M:purge()
log(NOTICE, "purging (local) cache")
local ok, err = self.mlcache:purge()
if not ok then
log(ERR, "failed to purge cache: ", err)
end
end
return _M
|
jebenexer/kong
|
kong/cache.lua
|
Lua
|
apache-2.0
| 4,412
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
// Generated from: proto/MessageInfo.proto
namespace netty
{
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"MessageInfo")]
public partial class MessageInfo : global::ProtoBuf.IExtensible
{
public MessageInfo() {}
private netty.MESSAGE_ID _messageId;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"messageId", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public netty.MESSAGE_ID messageId
{
get { return _messageId; }
set { _messageId = value; }
}
private netty.LoginReq _loginReq = null;
[global::ProtoBuf.ProtoMember(2, IsRequired = false, Name=@"loginReq", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.LoginReq loginReq
{
get { return _loginReq; }
set { _loginReq = value; }
}
private netty.LoginResp _loginResp = null;
[global::ProtoBuf.ProtoMember(3, IsRequired = false, Name=@"loginResp", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.LoginResp loginResp
{
get { return _loginResp; }
set { _loginResp = value; }
}
private netty.CreateRoomReq _createRoomReq = null;
[global::ProtoBuf.ProtoMember(4, IsRequired = false, Name=@"createRoomReq", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.CreateRoomReq createRoomReq
{
get { return _createRoomReq; }
set { _createRoomReq = value; }
}
private netty.CreateRoomResp _createRoomResp = null;
[global::ProtoBuf.ProtoMember(5, IsRequired = false, Name=@"createRoomResp", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.CreateRoomResp createRoomResp
{
get { return _createRoomResp; }
set { _createRoomResp = value; }
}
private netty.EntryRoomReq _entryRoomReq = null;
[global::ProtoBuf.ProtoMember(6, IsRequired = false, Name=@"entryRoomReq", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.EntryRoomReq entryRoomReq
{
get { return _entryRoomReq; }
set { _entryRoomReq = value; }
}
private netty.EntryRoomResp _entryRoomResp = null;
[global::ProtoBuf.ProtoMember(7, IsRequired = false, Name=@"entryRoomResp", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.EntryRoomResp entryRoomResp
{
get { return _entryRoomResp; }
set { _entryRoomResp = value; }
}
private netty.PostEntryRoom _postEntryRoom = null;
[global::ProtoBuf.ProtoMember(8, IsRequired = false, Name=@"postEntryRoom", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.PostEntryRoom postEntryRoom
{
get { return _postEntryRoom; }
set { _postEntryRoom = value; }
}
private netty.Player _player = null;
[global::ProtoBuf.ProtoMember(9, IsRequired = false, Name=@"player", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.Player player
{
get { return _player; }
set { _player = value; }
}
private netty.DisbandReq _disbandReq = null;
[global::ProtoBuf.ProtoMember(10, IsRequired = false, Name=@"disbandReq", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.DisbandReq disbandReq
{
get { return _disbandReq; }
set { _disbandReq = value; }
}
private netty.PostDisband _postDisband = null;
[global::ProtoBuf.ProtoMember(11, IsRequired = false, Name=@"postDisband", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.PostDisband postDisband
{
get { return _postDisband; }
set { _postDisband = value; }
}
private netty.DisbandCheckReq _disbandCheckReq = null;
[global::ProtoBuf.ProtoMember(12, IsRequired = false, Name=@"disbandCheckReq", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.DisbandCheckReq disbandCheckReq
{
get { return _disbandCheckReq; }
set { _disbandCheckReq = value; }
}
private netty.PostDisbandCheck _postDisbandCheck = null;
[global::ProtoBuf.ProtoMember(13, IsRequired = false, Name=@"postDisbandCheck", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.PostDisbandCheck postDisbandCheck
{
get { return _postDisbandCheck; }
set { _postDisbandCheck = value; }
}
private netty.SettlementInfo _settlementInfo = null;
[global::ProtoBuf.ProtoMember(14, IsRequired = false, Name=@"settlementInfo", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.SettlementInfo settlementInfo
{
get { return _settlementInfo; }
set { _settlementInfo = value; }
}
private netty.DiscardReq _discardReq = null;
[global::ProtoBuf.ProtoMember(15, IsRequired = false, Name=@"discardReq", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.DiscardReq discardReq
{
get { return _discardReq; }
set { _discardReq = value; }
}
private netty.PostDiscard _postDiscard = null;
[global::ProtoBuf.ProtoMember(16, IsRequired = false, Name=@"postDiscard", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.PostDiscard postDiscard
{
get { return _postDiscard; }
set { _postDiscard = value; }
}
private netty.DealReq _dealReq = null;
[global::ProtoBuf.ProtoMember(17, IsRequired = false, Name=@"dealReq", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.DealReq dealReq
{
get { return _dealReq; }
set { _dealReq = value; }
}
private netty.DealResp _dealResp = null;
[global::ProtoBuf.ProtoMember(18, IsRequired = false, Name=@"dealResp", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.DealResp dealResp
{
get { return _dealResp; }
set { _dealResp = value; }
}
private netty.GrabHostReq _grabHostReq = null;
[global::ProtoBuf.ProtoMember(19, IsRequired = false, Name=@"grabHostReq", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.GrabHostReq grabHostReq
{
get { return _grabHostReq; }
set { _grabHostReq = value; }
}
private netty.MsgInfo _msgInfo = null;
[global::ProtoBuf.ProtoMember(20, IsRequired = false, Name=@"msgInfo", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.MsgInfo msgInfo
{
get { return _msgInfo; }
set { _msgInfo = value; }
}
private netty.PostGrabHostResp _postGrabHostResp = null;
[global::ProtoBuf.ProtoMember(21, IsRequired = false, Name=@"postGrabHostResp", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.PostGrabHostResp postGrabHostResp
{
get { return _postGrabHostResp; }
set { _postGrabHostResp = value; }
}
private netty.PostDealOver _postDealOver = null;
[global::ProtoBuf.ProtoMember(22, IsRequired = false, Name=@"postDealOver", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.PostDealOver postDealOver
{
get { return _postDealOver; }
set { _postDealOver = value; }
}
private netty.CreateNNRoomReq _createNNRoomReq = null;
[global::ProtoBuf.ProtoMember(23, IsRequired = false, Name=@"createNNRoomReq", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.CreateNNRoomReq createNNRoomReq
{
get { return _createNNRoomReq; }
set { _createNNRoomReq = value; }
}
private netty.CreateNNRoomResp _createNNRoomResp = null;
[global::ProtoBuf.ProtoMember(24, IsRequired = false, Name=@"createNNRoomResp", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.CreateNNRoomResp createNNRoomResp
{
get { return _createNNRoomResp; }
set { _createNNRoomResp = value; }
}
private netty.EntryNNRoomReq _entryNNRoomReq = null;
[global::ProtoBuf.ProtoMember(25, IsRequired = false, Name=@"entryNNRoomReq", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.EntryNNRoomReq entryNNRoomReq
{
get { return _entryNNRoomReq; }
set { _entryNNRoomReq = value; }
}
private netty.EntryNNRoomResp _entryNNRoomResp = null;
[global::ProtoBuf.ProtoMember(26, IsRequired = false, Name=@"entryNNRoomResp", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.EntryNNRoomResp entryNNRoomResp
{
get { return _entryNNRoomResp; }
set { _entryNNRoomResp = value; }
}
private netty.PostNNEntryRoom _postNNEntryRoom = null;
[global::ProtoBuf.ProtoMember(27, IsRequired = false, Name=@"postNNEntryRoom", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.PostNNEntryRoom postNNEntryRoom
{
get { return _postNNEntryRoom; }
set { _postNNEntryRoom = value; }
}
private netty.StartNNGameReq _startNNGame = null;
[global::ProtoBuf.ProtoMember(28, IsRequired = false, Name=@"startNNGame", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.StartNNGameReq startNNGame
{
get { return _startNNGame; }
set { _startNNGame = value; }
}
private netty.StartNNGameResp _startNNgameResp = null;
[global::ProtoBuf.ProtoMember(29, IsRequired = false, Name=@"startNNgameResp", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.StartNNGameResp startNNgameResp
{
get { return _startNNgameResp; }
set { _startNNgameResp = value; }
}
private netty.PostStartNNGame _postStartNNGame = null;
[global::ProtoBuf.ProtoMember(30, IsRequired = false, Name=@"postStartNNGame", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.PostStartNNGame postStartNNGame
{
get { return _postStartNNGame; }
set { _postStartNNGame = value; }
}
private netty.NNPrepareReq _nnPrepareReq = null;
[global::ProtoBuf.ProtoMember(31, IsRequired = false, Name=@"nnPrepareReq", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.NNPrepareReq nnPrepareReq
{
get { return _nnPrepareReq; }
set { _nnPrepareReq = value; }
}
private netty.PostNNDealResp _nnDealResp = null;
[global::ProtoBuf.ProtoMember(32, IsRequired = false, Name=@"nnDealResp", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.PostNNDealResp nnDealResp
{
get { return _nnDealResp; }
set { _nnDealResp = value; }
}
private netty.StakeReq _stakeReq = null;
[global::ProtoBuf.ProtoMember(33, IsRequired = false, Name=@"stakeReq", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.StakeReq stakeReq
{
get { return _stakeReq; }
set { _stakeReq = value; }
}
private netty.StakeResp _stakeResp = null;
[global::ProtoBuf.ProtoMember(34, IsRequired = false, Name=@"stakeResp", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.StakeResp stakeResp
{
get { return _stakeResp; }
set { _stakeResp = value; }
}
private netty.PostStakeResp _postStakeResp = null;
[global::ProtoBuf.ProtoMember(35, IsRequired = false, Name=@"postStakeResp", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.PostStakeResp postStakeResp
{
get { return _postStakeResp; }
set { _postStakeResp = value; }
}
private netty.NNShowCardsReq _nnShowCardsReq = null;
[global::ProtoBuf.ProtoMember(36, IsRequired = false, Name=@"nnShowCardsReq", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.NNShowCardsReq nnShowCardsReq
{
get { return _nnShowCardsReq; }
set { _nnShowCardsReq = value; }
}
private netty.NNShowCardsResp _nnShowCardsResp = null;
[global::ProtoBuf.ProtoMember(37, IsRequired = false, Name=@"nnShowCardsResp", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.NNShowCardsResp nnShowCardsResp
{
get { return _nnShowCardsResp; }
set { _nnShowCardsResp = value; }
}
private netty.PostNNShowCards _postNNShowCards = null;
[global::ProtoBuf.ProtoMember(38, IsRequired = false, Name=@"postNNShowCards", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.PostNNShowCards postNNShowCards
{
get { return _postNNShowCards; }
set { _postNNShowCards = value; }
}
private netty.PostNNPrepareResp _postNNPrepareResp = null;
[global::ProtoBuf.ProtoMember(39, IsRequired = false, Name=@"postNNPrepareResp", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.PostNNPrepareResp postNNPrepareResp
{
get { return _postNNPrepareResp; }
set { _postNNPrepareResp = value; }
}
private netty.PostStakeOver _postStakeOver = null;
[global::ProtoBuf.ProtoMember(40, IsRequired = false, Name=@"postStakeOver", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.PostStakeOver postStakeOver
{
get { return _postStakeOver; }
set { _postStakeOver = value; }
}
private netty.NNDissolutionReq _nnDissolutionReq = null;
[global::ProtoBuf.ProtoMember(41, IsRequired = false, Name=@"nnDissolutionReq", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.NNDissolutionReq nnDissolutionReq
{
get { return _nnDissolutionReq; }
set { _nnDissolutionReq = value; }
}
private netty.PostDissolutionResp _postDissolutionResp = null;
[global::ProtoBuf.ProtoMember(42, IsRequired = false, Name=@"postDissolutionResp", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.PostDissolutionResp postDissolutionResp
{
get { return _postDissolutionResp; }
set { _postDissolutionResp = value; }
}
private netty.NNAnswerDissolutionReq _nnAnswerDissolutionReq = null;
[global::ProtoBuf.ProtoMember(43, IsRequired = false, Name=@"nnAnswerDissolutionReq", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.NNAnswerDissolutionReq nnAnswerDissolutionReq
{
get { return _nnAnswerDissolutionReq; }
set { _nnAnswerDissolutionReq = value; }
}
private netty.PostAnswerDissolutionResult _PostAnswerDissolutionResult = null;
[global::ProtoBuf.ProtoMember(44, IsRequired = false, Name=@"PostAnswerDissolutionResult", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.PostAnswerDissolutionResult PostAnswerDissolutionResult
{
get { return _PostAnswerDissolutionResult; }
set { _PostAnswerDissolutionResult = value; }
}
private netty.PostDissolutionResult _postDissolutionResult = null;
[global::ProtoBuf.ProtoMember(45, IsRequired = false, Name=@"postDissolutionResult", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.PostDissolutionResult postDissolutionResult
{
get { return _postDissolutionResult; }
set { _postDissolutionResult = value; }
}
private netty.SendSoundReq _sendSoundReq = null;
[global::ProtoBuf.ProtoMember(46, IsRequired = false, Name=@"sendSoundReq", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.SendSoundReq sendSoundReq
{
get { return _sendSoundReq; }
set { _sendSoundReq = value; }
}
private netty.PostSendSoundResp _postSendSoundResp = null;
[global::ProtoBuf.ProtoMember(47, IsRequired = false, Name=@"postSendSoundResp", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.PostSendSoundResp postSendSoundResp
{
get { return _postSendSoundResp; }
set { _postSendSoundResp = value; }
}
private netty.SignOutReq _signOutReq = null;
[global::ProtoBuf.ProtoMember(48, IsRequired = false, Name=@"signOutReq", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.SignOutReq signOutReq
{
get { return _signOutReq; }
set { _signOutReq = value; }
}
private netty.ReEntryNNRoomReq _reEntryNNRoomReq = null;
[global::ProtoBuf.ProtoMember(49, IsRequired = false, Name=@"reEntryNNRoomReq", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.ReEntryNNRoomReq reEntryNNRoomReq
{
get { return _reEntryNNRoomReq; }
set { _reEntryNNRoomReq = value; }
}
private netty.PostUnusualQuit _postUnusualQuit = null;
[global::ProtoBuf.ProtoMember(50, IsRequired = false, Name=@"postUnusualQuit", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.PostUnusualQuit postUnusualQuit
{
get { return _postUnusualQuit; }
set { _postUnusualQuit = value; }
}
private netty.PostPlayerOnline _postPlayerOnline = null;
[global::ProtoBuf.ProtoMember(51, IsRequired = false, Name=@"postPlayerOnline", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.PostPlayerOnline postPlayerOnline
{
get { return _postPlayerOnline; }
set { _postPlayerOnline = value; }
}
private netty.PostPlayerOffline _postPlayerOffline = null;
[global::ProtoBuf.ProtoMember(52, IsRequired = false, Name=@"postPlayerOffline", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.PostPlayerOffline postPlayerOffline
{
get { return _postPlayerOffline; }
set { _postPlayerOffline = value; }
}
private netty.ReConnectReq _reConnectReq = null;
[global::ProtoBuf.ProtoMember(53, IsRequired = false, Name=@"reConnectReq", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.ReConnectReq reConnectReq
{
get { return _reConnectReq; }
set { _reConnectReq = value; }
}
private netty.ReConnectResp _reConnectResp = null;
[global::ProtoBuf.ProtoMember(54, IsRequired = false, Name=@"reConnectResp", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.ReConnectResp reConnectResp
{
get { return _reConnectResp; }
set { _reConnectResp = value; }
}
private netty.HeartBeatReq _heartBeatReq = null;
[global::ProtoBuf.ProtoMember(55, IsRequired = false, Name=@"heartBeatReq", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.HeartBeatReq heartBeatReq
{
get { return _heartBeatReq; }
set { _heartBeatReq = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"LoginReq")]
public partial class LoginReq : global::ProtoBuf.IExtensible
{
public LoginReq() {}
private string _code;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"code", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string code
{
get { return _code; }
set { _code = value; }
}
private int _playerid = default(int);
[global::ProtoBuf.ProtoMember(2, IsRequired = false, Name=@"playerid", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
[global::System.ComponentModel.DefaultValue(default(int))]
public int playerid
{
get { return _playerid; }
set { _playerid = value; }
}
private string _clientinfos = "";
[global::ProtoBuf.ProtoMember(3, IsRequired = false, Name=@"clientinfos", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue("")]
public string clientinfos
{
get { return _clientinfos; }
set { _clientinfos = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"PlayerBaseInfo")]
public partial class PlayerBaseInfo : global::ProtoBuf.IExtensible
{
public PlayerBaseInfo() {}
private int _ID;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"ID", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int ID
{
get { return _ID; }
set { _ID = value; }
}
private string _name;
[global::ProtoBuf.ProtoMember(2, IsRequired = true, Name=@"name", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string name
{
get { return _name; }
set { _name = value; }
}
private string _imgUrl = "";
[global::ProtoBuf.ProtoMember(3, IsRequired = false, Name=@"imgUrl", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue("")]
public string imgUrl
{
get { return _imgUrl; }
set { _imgUrl = value; }
}
private int _cardNum = default(int);
[global::ProtoBuf.ProtoMember(4, IsRequired = false, Name=@"cardNum", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
[global::System.ComponentModel.DefaultValue(default(int))]
public int cardNum
{
get { return _cardNum; }
set { _cardNum = value; }
}
private string _wxopenid = "";
[global::ProtoBuf.ProtoMember(5, IsRequired = false, Name=@"wxopenid", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue("")]
public string wxopenid
{
get { return _wxopenid; }
set { _wxopenid = value; }
}
private string _token;
[global::ProtoBuf.ProtoMember(6, IsRequired = true, Name=@"token", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string token
{
get { return _token; }
set { _token = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"LoginResp")]
public partial class LoginResp : global::ProtoBuf.IExtensible
{
public LoginResp() {}
private netty.PlayerBaseInfo _playerBaseInfo;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"playerBaseInfo", DataFormat = global::ProtoBuf.DataFormat.Default)]
public netty.PlayerBaseInfo playerBaseInfo
{
get { return _playerBaseInfo; }
set { _playerBaseInfo = value; }
}
private string _shareurl = "";
[global::ProtoBuf.ProtoMember(2, IsRequired = false, Name=@"shareurl", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue("")]
public string shareurl
{
get { return _shareurl; }
set { _shareurl = value; }
}
private int _playerState;
[global::ProtoBuf.ProtoMember(3, IsRequired = true, Name=@"playerState", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int playerState
{
get { return _playerState; }
set { _playerState = value; }
}
private int _roomId = default(int);
[global::ProtoBuf.ProtoMember(4, IsRequired = false, Name=@"roomId", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
[global::System.ComponentModel.DefaultValue(default(int))]
public int roomId
{
get { return _roomId; }
set { _roomId = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"CreateRoomReq")]
public partial class CreateRoomReq : global::ProtoBuf.IExtensible
{
public CreateRoomReq() {}
private int _games;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"games", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int games
{
get { return _games; }
set { _games = value; }
}
private int _type;
[global::ProtoBuf.ProtoMember(2, IsRequired = true, Name=@"type", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int type
{
get { return _type; }
set { _type = value; }
}
private int _playerId;
[global::ProtoBuf.ProtoMember(3, IsRequired = true, Name=@"playerId", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int playerId
{
get { return _playerId; }
set { _playerId = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"CreateRoomResp")]
public partial class CreateRoomResp : global::ProtoBuf.IExtensible
{
public CreateRoomResp() {}
private int _roomId;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"roomId", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int roomId
{
get { return _roomId; }
set { _roomId = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"EntryRoomReq")]
public partial class EntryRoomReq : global::ProtoBuf.IExtensible
{
public EntryRoomReq() {}
private int _roomId;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"roomId", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int roomId
{
get { return _roomId; }
set { _roomId = value; }
}
private int _playerId;
[global::ProtoBuf.ProtoMember(2, IsRequired = true, Name=@"playerId", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int playerId
{
get { return _playerId; }
set { _playerId = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"EntryRoomResp")]
public partial class EntryRoomResp : global::ProtoBuf.IExtensible
{
public EntryRoomResp() {}
private netty.RoomInfo _roomInfo;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"roomInfo", DataFormat = global::ProtoBuf.DataFormat.Default)]
public netty.RoomInfo roomInfo
{
get { return _roomInfo; }
set { _roomInfo = value; }
}
private int _order;
[global::ProtoBuf.ProtoMember(2, IsRequired = true, Name=@"order", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int order
{
get { return _order; }
set { _order = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"PostEntryRoom")]
public partial class PostEntryRoom : global::ProtoBuf.IExtensible
{
public PostEntryRoom() {}
private netty.Player _player;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"player", DataFormat = global::ProtoBuf.DataFormat.Default)]
public netty.Player player
{
get { return _player; }
set { _player = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"RoomInfo")]
public partial class RoomInfo : global::ProtoBuf.IExtensible
{
public RoomInfo() {}
private int _roomId;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"roomId", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int roomId
{
get { return _roomId; }
set { _roomId = value; }
}
private readonly global::System.Collections.Generic.List<netty.Player> _players = new global::System.Collections.Generic.List<netty.Player>();
[global::ProtoBuf.ProtoMember(2, Name=@"players", DataFormat = global::ProtoBuf.DataFormat.Default)]
public global::System.Collections.Generic.List<netty.Player> players
{
get { return _players; }
}
private int _multiple = default(int);
[global::ProtoBuf.ProtoMember(3, IsRequired = false, Name=@"multiple", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
[global::System.ComponentModel.DefaultValue(default(int))]
public int multiple
{
get { return _multiple; }
set { _multiple = value; }
}
private int _playedGames = default(int);
[global::ProtoBuf.ProtoMember(4, IsRequired = false, Name=@"playedGames", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
[global::System.ComponentModel.DefaultValue(default(int))]
public int playedGames
{
get { return _playedGames; }
set { _playedGames = value; }
}
private int _totalGames = default(int);
[global::ProtoBuf.ProtoMember(5, IsRequired = false, Name=@"totalGames", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
[global::System.ComponentModel.DefaultValue(default(int))]
public int totalGames
{
get { return _totalGames; }
set { _totalGames = value; }
}
private int _currentPlayerId = default(int);
[global::ProtoBuf.ProtoMember(6, IsRequired = false, Name=@"currentPlayerId", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
[global::System.ComponentModel.DefaultValue(default(int))]
public int currentPlayerId
{
get { return _currentPlayerId; }
set { _currentPlayerId = value; }
}
private int _bankerId = default(int);
[global::ProtoBuf.ProtoMember(7, IsRequired = false, Name=@"bankerId", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
[global::System.ComponentModel.DefaultValue(default(int))]
public int bankerId
{
get { return _bankerId; }
set { _bankerId = value; }
}
private bool _isDisband;
[global::ProtoBuf.ProtoMember(8, IsRequired = true, Name=@"isDisband", DataFormat = global::ProtoBuf.DataFormat.Default)]
public bool isDisband
{
get { return _isDisband; }
set { _isDisband = value; }
}
private readonly global::System.Collections.Generic.List<int> _agreePlayerIds = new global::System.Collections.Generic.List<int>();
[global::ProtoBuf.ProtoMember(9, Name=@"agreePlayerIds", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public global::System.Collections.Generic.List<int> agreePlayerIds
{
get { return _agreePlayerIds; }
}
private readonly global::System.Collections.Generic.List<int> _refusePlayerIds = new global::System.Collections.Generic.List<int>();
[global::ProtoBuf.ProtoMember(10, Name=@"refusePlayerIds", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public global::System.Collections.Generic.List<int> refusePlayerIds
{
get { return _refusePlayerIds; }
}
private int _startDisbandTime = default(int);
[global::ProtoBuf.ProtoMember(11, IsRequired = false, Name=@"startDisbandTime", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
[global::System.ComponentModel.DefaultValue(default(int))]
public int startDisbandTime
{
get { return _startDisbandTime; }
set { _startDisbandTime = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"Player")]
public partial class Player : global::ProtoBuf.IExtensible
{
public Player() {}
private int _ID;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"ID", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int ID
{
get { return _ID; }
set { _ID = value; }
}
private string _name;
[global::ProtoBuf.ProtoMember(2, IsRequired = true, Name=@"name", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string name
{
get { return _name; }
set { _name = value; }
}
private string _imgUrl = "";
[global::ProtoBuf.ProtoMember(3, IsRequired = false, Name=@"imgUrl", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue("")]
public string imgUrl
{
get { return _imgUrl; }
set { _imgUrl = value; }
}
private int _score;
[global::ProtoBuf.ProtoMember(4, IsRequired = true, Name=@"score", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int score
{
get { return _score; }
set { _score = value; }
}
private bool _isDz;
[global::ProtoBuf.ProtoMember(5, IsRequired = true, Name=@"isDz", DataFormat = global::ProtoBuf.DataFormat.Default)]
public bool isDz
{
get { return _isDz; }
set { _isDz = value; }
}
private int _order = default(int);
[global::ProtoBuf.ProtoMember(6, IsRequired = false, Name=@"order", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
[global::System.ComponentModel.DefaultValue(default(int))]
public int order
{
get { return _order; }
set { _order = value; }
}
private bool _isOnline = default(bool);
[global::ProtoBuf.ProtoMember(7, IsRequired = false, Name=@"isOnline", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(default(bool))]
public bool isOnline
{
get { return _isOnline; }
set { _isOnline = value; }
}
private readonly global::System.Collections.Generic.List<int> _pokerids = new global::System.Collections.Generic.List<int>();
[global::ProtoBuf.ProtoMember(8, Name=@"pokerids", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public global::System.Collections.Generic.List<int> pokerids
{
get { return _pokerids; }
}
private netty.NNType _nntype = netty.NNType.NNT_ERROR;
[global::ProtoBuf.ProtoMember(9, IsRequired = false, Name=@"nntype", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
[global::System.ComponentModel.DefaultValue(netty.NNType.NNT_ERROR)]
public netty.NNType nntype
{
get { return _nntype; }
set { _nntype = value; }
}
private int _stakepoint = default(int);
[global::ProtoBuf.ProtoMember(10, IsRequired = false, Name=@"stakepoint", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
[global::System.ComponentModel.DefaultValue(default(int))]
public int stakepoint
{
get { return _stakepoint; }
set { _stakepoint = value; }
}
private netty.NNStatus _status = netty.NNStatus.STATUS_NONE;
[global::ProtoBuf.ProtoMember(11, IsRequired = false, Name=@"status", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
[global::System.ComponentModel.DefaultValue(netty.NNStatus.STATUS_NONE)]
public netty.NNStatus status
{
get { return _status; }
set { _status = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"Poker")]
public partial class Poker : global::ProtoBuf.IExtensible
{
public Poker() {}
private int _ID;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"ID", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int ID
{
get { return _ID; }
set { _ID = value; }
}
private bool _isOut;
[global::ProtoBuf.ProtoMember(2, IsRequired = true, Name=@"isOut", DataFormat = global::ProtoBuf.DataFormat.Default)]
public bool isOut
{
get { return _isOut; }
set { _isOut = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"DisbandReq")]
public partial class DisbandReq : global::ProtoBuf.IExtensible
{
public DisbandReq() {}
private int _groupId;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"groupId", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int groupId
{
get { return _groupId; }
set { _groupId = value; }
}
private int _playerId;
[global::ProtoBuf.ProtoMember(2, IsRequired = true, Name=@"playerId", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int playerId
{
get { return _playerId; }
set { _playerId = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"PostDisband")]
public partial class PostDisband : global::ProtoBuf.IExtensible
{
public PostDisband() {}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"DisbandCheckReq")]
public partial class DisbandCheckReq : global::ProtoBuf.IExtensible
{
public DisbandCheckReq() {}
private bool _agree;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"agree", DataFormat = global::ProtoBuf.DataFormat.Default)]
public bool agree
{
get { return _agree; }
set { _agree = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"PostDisbandCheck")]
public partial class PostDisbandCheck : global::ProtoBuf.IExtensible
{
public PostDisbandCheck() {}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"SettlementData")]
public partial class SettlementData : global::ProtoBuf.IExtensible
{
public SettlementData() {}
private int _ID;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"ID", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int ID
{
get { return _ID; }
set { _ID = value; }
}
private int _gotscore;
[global::ProtoBuf.ProtoMember(2, IsRequired = true, Name=@"gotscore", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int gotscore
{
get { return _gotscore; }
set { _gotscore = value; }
}
private int _finalscore;
[global::ProtoBuf.ProtoMember(3, IsRequired = true, Name=@"finalscore", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int finalscore
{
get { return _finalscore; }
set { _finalscore = value; }
}
private bool _isWin;
[global::ProtoBuf.ProtoMember(4, IsRequired = true, Name=@"isWin", DataFormat = global::ProtoBuf.DataFormat.Default)]
public bool isWin
{
get { return _isWin; }
set { _isWin = value; }
}
private int _leaveCardNum = default(int);
[global::ProtoBuf.ProtoMember(5, IsRequired = false, Name=@"leaveCardNum", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
[global::System.ComponentModel.DefaultValue(default(int))]
public int leaveCardNum
{
get { return _leaveCardNum; }
set { _leaveCardNum = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"SettlementInfo")]
public partial class SettlementInfo : global::ProtoBuf.IExtensible
{
public SettlementInfo() {}
private readonly global::System.Collections.Generic.List<netty.SettlementData> _players = new global::System.Collections.Generic.List<netty.SettlementData>();
[global::ProtoBuf.ProtoMember(1, Name=@"players", DataFormat = global::ProtoBuf.DataFormat.Default)]
public global::System.Collections.Generic.List<netty.SettlementData> players
{
get { return _players; }
}
private bool _isOver;
[global::ProtoBuf.ProtoMember(2, IsRequired = true, Name=@"isOver", DataFormat = global::ProtoBuf.DataFormat.Default)]
public bool isOver
{
get { return _isOver; }
set { _isOver = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"DiscardReq")]
public partial class DiscardReq : global::ProtoBuf.IExtensible
{
public DiscardReq() {}
private int _playerId;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"playerId", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int playerId
{
get { return _playerId; }
set { _playerId = value; }
}
private readonly global::System.Collections.Generic.List<int> _cardIds = new global::System.Collections.Generic.List<int>();
[global::ProtoBuf.ProtoMember(2, Name=@"cardIds", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public global::System.Collections.Generic.List<int> cardIds
{
get { return _cardIds; }
}
private readonly global::System.Collections.Generic.List<int> _variableCardIds = new global::System.Collections.Generic.List<int>();
[global::ProtoBuf.ProtoMember(3, Name=@"variableCardIds", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public global::System.Collections.Generic.List<int> variableCardIds
{
get { return _variableCardIds; }
}
private int _cardsType;
[global::ProtoBuf.ProtoMember(4, IsRequired = true, Name=@"cardsType", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int cardsType
{
get { return _cardsType; }
set { _cardsType = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"PostDiscard")]
public partial class PostDiscard : global::ProtoBuf.IExtensible
{
public PostDiscard() {}
private int _playerId;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"playerId", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int playerId
{
get { return _playerId; }
set { _playerId = value; }
}
private readonly global::System.Collections.Generic.List<int> _cardIds = new global::System.Collections.Generic.List<int>();
[global::ProtoBuf.ProtoMember(2, Name=@"cardIds", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public global::System.Collections.Generic.List<int> cardIds
{
get { return _cardIds; }
}
private readonly global::System.Collections.Generic.List<int> _variableCardIds = new global::System.Collections.Generic.List<int>();
[global::ProtoBuf.ProtoMember(3, Name=@"variableCardIds", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public global::System.Collections.Generic.List<int> variableCardIds
{
get { return _variableCardIds; }
}
private int _remainderPokersNum;
[global::ProtoBuf.ProtoMember(4, IsRequired = true, Name=@"remainderPokersNum", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int remainderPokersNum
{
get { return _remainderPokersNum; }
set { _remainderPokersNum = value; }
}
private int _nextDiscardPlayerId;
[global::ProtoBuf.ProtoMember(5, IsRequired = true, Name=@"nextDiscardPlayerId", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int nextDiscardPlayerId
{
get { return _nextDiscardPlayerId; }
set { _nextDiscardPlayerId = value; }
}
private bool _mustDiscard;
[global::ProtoBuf.ProtoMember(6, IsRequired = true, Name=@"mustDiscard", DataFormat = global::ProtoBuf.DataFormat.Default)]
public bool mustDiscard
{
get { return _mustDiscard; }
set { _mustDiscard = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"DealReq")]
public partial class DealReq : global::ProtoBuf.IExtensible
{
public DealReq() {}
private int _playerId;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"playerId", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int playerId
{
get { return _playerId; }
set { _playerId = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"DealResp")]
public partial class DealResp : global::ProtoBuf.IExtensible
{
public DealResp() {}
private int _playerId;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"playerId", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int playerId
{
get { return _playerId; }
set { _playerId = value; }
}
private readonly global::System.Collections.Generic.List<netty.Poker> _pokers = new global::System.Collections.Generic.List<netty.Poker>();
[global::ProtoBuf.ProtoMember(2, Name=@"pokers", DataFormat = global::ProtoBuf.DataFormat.Default)]
public global::System.Collections.Generic.List<netty.Poker> pokers
{
get { return _pokers; }
}
private netty.RoomInfo _roomInfo = null;
[global::ProtoBuf.ProtoMember(3, IsRequired = false, Name=@"roomInfo", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public netty.RoomInfo roomInfo
{
get { return _roomInfo; }
set { _roomInfo = value; }
}
private int _grabHost;
[global::ProtoBuf.ProtoMember(4, IsRequired = true, Name=@"grabHost", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int grabHost
{
get { return _grabHost; }
set { _grabHost = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"GrabHostReq")]
public partial class GrabHostReq : global::ProtoBuf.IExtensible
{
public GrabHostReq() {}
private int _playerId;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"playerId", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int playerId
{
get { return _playerId; }
set { _playerId = value; }
}
private int _type;
[global::ProtoBuf.ProtoMember(2, IsRequired = true, Name=@"type", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int type
{
get { return _type; }
set { _type = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"PostGrabHostResp")]
public partial class PostGrabHostResp : global::ProtoBuf.IExtensible
{
public PostGrabHostResp() {}
private int _type;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"type", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int type
{
get { return _type; }
set { _type = value; }
}
private int _playerId;
[global::ProtoBuf.ProtoMember(2, IsRequired = true, Name=@"playerId", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int playerId
{
get { return _playerId; }
set { _playerId = value; }
}
private int _hostPlayerId = default(int);
[global::ProtoBuf.ProtoMember(3, IsRequired = false, Name=@"hostPlayerId", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
[global::System.ComponentModel.DefaultValue(default(int))]
public int hostPlayerId
{
get { return _hostPlayerId; }
set { _hostPlayerId = value; }
}
private readonly global::System.Collections.Generic.List<netty.Poker> _pokers = new global::System.Collections.Generic.List<netty.Poker>();
[global::ProtoBuf.ProtoMember(4, Name=@"pokers", DataFormat = global::ProtoBuf.DataFormat.Default)]
public global::System.Collections.Generic.List<netty.Poker> pokers
{
get { return _pokers; }
}
private int _variable = default(int);
[global::ProtoBuf.ProtoMember(5, IsRequired = false, Name=@"variable", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
[global::System.ComponentModel.DefaultValue(default(int))]
public int variable
{
get { return _variable; }
set { _variable = value; }
}
private int _nextGrabPlayerId = default(int);
[global::ProtoBuf.ProtoMember(6, IsRequired = false, Name=@"nextGrabPlayerId", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
[global::System.ComponentModel.DefaultValue(default(int))]
public int nextGrabPlayerId
{
get { return _nextGrabPlayerId; }
set { _nextGrabPlayerId = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"MsgInfo")]
public partial class MsgInfo : global::ProtoBuf.IExtensible
{
public MsgInfo() {}
private int _type;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"type", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int type
{
get { return _type; }
set { _type = value; }
}
private string _message;
[global::ProtoBuf.ProtoMember(2, IsRequired = true, Name=@"message", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string message
{
get { return _message; }
set { _message = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"PostDealOver")]
public partial class PostDealOver : global::ProtoBuf.IExtensible
{
public PostDealOver() {}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"CreateNNRoomReq")]
public partial class CreateNNRoomReq : global::ProtoBuf.IExtensible
{
public CreateNNRoomReq() {}
private int _games;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"games", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int games
{
get { return _games; }
set { _games = value; }
}
private int _type;
[global::ProtoBuf.ProtoMember(2, IsRequired = true, Name=@"type", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int type
{
get { return _type; }
set { _type = value; }
}
private int _playerId;
[global::ProtoBuf.ProtoMember(3, IsRequired = true, Name=@"playerId", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int playerId
{
get { return _playerId; }
set { _playerId = value; }
}
private netty.BankerType _bankerType;
[global::ProtoBuf.ProtoMember(4, IsRequired = true, Name=@"bankerType", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public netty.BankerType bankerType
{
get { return _bankerType; }
set { _bankerType = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"CreateNNRoomResp")]
public partial class CreateNNRoomResp : global::ProtoBuf.IExtensible
{
public CreateNNRoomResp() {}
private int _roomId;
[global::ProtoBuf.ProtoMember(2, IsRequired = true, Name=@"roomId", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int roomId
{
get { return _roomId; }
set { _roomId = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"EntryNNRoomReq")]
public partial class EntryNNRoomReq : global::ProtoBuf.IExtensible
{
public EntryNNRoomReq() {}
private int _roomId;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"roomId", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int roomId
{
get { return _roomId; }
set { _roomId = value; }
}
private int _playerId;
[global::ProtoBuf.ProtoMember(2, IsRequired = true, Name=@"playerId", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int playerId
{
get { return _playerId; }
set { _playerId = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"EntryNNRoomResp")]
public partial class EntryNNRoomResp : global::ProtoBuf.IExtensible
{
public EntryNNRoomResp() {}
private netty.RoomInfo _roomInfo;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"roomInfo", DataFormat = global::ProtoBuf.DataFormat.Default)]
public netty.RoomInfo roomInfo
{
get { return _roomInfo; }
set { _roomInfo = value; }
}
private int _order;
[global::ProtoBuf.ProtoMember(2, IsRequired = true, Name=@"order", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int order
{
get { return _order; }
set { _order = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"PostNNEntryRoom")]
public partial class PostNNEntryRoom : global::ProtoBuf.IExtensible
{
public PostNNEntryRoom() {}
private netty.Player _player;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"player", DataFormat = global::ProtoBuf.DataFormat.Default)]
public netty.Player player
{
get { return _player; }
set { _player = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"StartNNGameReq")]
public partial class StartNNGameReq : global::ProtoBuf.IExtensible
{
public StartNNGameReq() {}
private int _playerid;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"playerid", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int playerid
{
get { return _playerid; }
set { _playerid = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"StartNNGameResp")]
public partial class StartNNGameResp : global::ProtoBuf.IExtensible
{
public StartNNGameResp() {}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"PostStartNNGame")]
public partial class PostStartNNGame : global::ProtoBuf.IExtensible
{
public PostStartNNGame() {}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"NNPrepareReq")]
public partial class NNPrepareReq : global::ProtoBuf.IExtensible
{
public NNPrepareReq() {}
private int _playerId;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"playerId", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int playerId
{
get { return _playerId; }
set { _playerId = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"PostNNDealResp")]
public partial class PostNNDealResp : global::ProtoBuf.IExtensible
{
public PostNNDealResp() {}
private int _playerId;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"playerId", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int playerId
{
get { return _playerId; }
set { _playerId = value; }
}
private readonly global::System.Collections.Generic.List<int> _pokers = new global::System.Collections.Generic.List<int>();
[global::ProtoBuf.ProtoMember(2, Name=@"pokers", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public global::System.Collections.Generic.List<int> pokers
{
get { return _pokers; }
}
private int _playedGames;
[global::ProtoBuf.ProtoMember(3, IsRequired = true, Name=@"playedGames", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int playedGames
{
get { return _playedGames; }
set { _playedGames = value; }
}
private int _totalGames;
[global::ProtoBuf.ProtoMember(4, IsRequired = true, Name=@"totalGames", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int totalGames
{
get { return _totalGames; }
set { _totalGames = value; }
}
private int _bankerId;
[global::ProtoBuf.ProtoMember(5, IsRequired = true, Name=@"bankerId", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int bankerId
{
get { return _bankerId; }
set { _bankerId = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"StakeReq")]
public partial class StakeReq : global::ProtoBuf.IExtensible
{
public StakeReq() {}
private int _playerid;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"playerid", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int playerid
{
get { return _playerid; }
set { _playerid = value; }
}
private int _point;
[global::ProtoBuf.ProtoMember(2, IsRequired = true, Name=@"point", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int point
{
get { return _point; }
set { _point = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"StakeResp")]
public partial class StakeResp : global::ProtoBuf.IExtensible
{
public StakeResp() {}
private int _point;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"point", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int point
{
get { return _point; }
set { _point = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"PostStakeResp")]
public partial class PostStakeResp : global::ProtoBuf.IExtensible
{
public PostStakeResp() {}
private int _playerid;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"playerid", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int playerid
{
get { return _playerid; }
set { _playerid = value; }
}
private int _point;
[global::ProtoBuf.ProtoMember(2, IsRequired = true, Name=@"point", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int point
{
get { return _point; }
set { _point = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"NNShowCardsReq")]
public partial class NNShowCardsReq : global::ProtoBuf.IExtensible
{
public NNShowCardsReq() {}
private int _playerid;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"playerid", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int playerid
{
get { return _playerid; }
set { _playerid = value; }
}
private bool _showAll;
[global::ProtoBuf.ProtoMember(2, IsRequired = true, Name=@"showAll", DataFormat = global::ProtoBuf.DataFormat.Default)]
public bool showAll
{
get { return _showAll; }
set { _showAll = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"NNShowCardsResp")]
public partial class NNShowCardsResp : global::ProtoBuf.IExtensible
{
public NNShowCardsResp() {}
private int _playerId;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"playerId", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int playerId
{
get { return _playerId; }
set { _playerId = value; }
}
private readonly global::System.Collections.Generic.List<int> _pokers = new global::System.Collections.Generic.List<int>();
[global::ProtoBuf.ProtoMember(2, Name=@"pokers", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public global::System.Collections.Generic.List<int> pokers
{
get { return _pokers; }
}
private netty.NNType _nntype;
[global::ProtoBuf.ProtoMember(3, IsRequired = true, Name=@"nntype", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public netty.NNType nntype
{
get { return _nntype; }
set { _nntype = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"PostNNShowCards")]
public partial class PostNNShowCards : global::ProtoBuf.IExtensible
{
public PostNNShowCards() {}
private int _playerId;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"playerId", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int playerId
{
get { return _playerId; }
set { _playerId = value; }
}
private readonly global::System.Collections.Generic.List<int> _pokers = new global::System.Collections.Generic.List<int>();
[global::ProtoBuf.ProtoMember(2, Name=@"pokers", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public global::System.Collections.Generic.List<int> pokers
{
get { return _pokers; }
}
private netty.NNType _nntype;
[global::ProtoBuf.ProtoMember(3, IsRequired = true, Name=@"nntype", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public netty.NNType nntype
{
get { return _nntype; }
set { _nntype = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"PostNNPrepareResp")]
public partial class PostNNPrepareResp : global::ProtoBuf.IExtensible
{
public PostNNPrepareResp() {}
private int _playerId;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"playerId", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int playerId
{
get { return _playerId; }
set { _playerId = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"PostStakeOver")]
public partial class PostStakeOver : global::ProtoBuf.IExtensible
{
public PostStakeOver() {}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"NNDissolutionReq")]
public partial class NNDissolutionReq : global::ProtoBuf.IExtensible
{
public NNDissolutionReq() {}
private int _playerId;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"playerId", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int playerId
{
get { return _playerId; }
set { _playerId = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"PostDissolutionResp")]
public partial class PostDissolutionResp : global::ProtoBuf.IExtensible
{
public PostDissolutionResp() {}
private int _playerid;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"playerid", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int playerid
{
get { return _playerid; }
set { _playerid = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"NNAnswerDissolutionReq")]
public partial class NNAnswerDissolutionReq : global::ProtoBuf.IExtensible
{
public NNAnswerDissolutionReq() {}
private int _playerId;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"playerId", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int playerId
{
get { return _playerId; }
set { _playerId = value; }
}
private bool _isAgree;
[global::ProtoBuf.ProtoMember(2, IsRequired = true, Name=@"isAgree", DataFormat = global::ProtoBuf.DataFormat.Default)]
public bool isAgree
{
get { return _isAgree; }
set { _isAgree = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"PostAnswerDissolutionResult")]
public partial class PostAnswerDissolutionResult : global::ProtoBuf.IExtensible
{
public PostAnswerDissolutionResult() {}
private int _agreeCnt;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"agreeCnt", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int agreeCnt
{
get { return _agreeCnt; }
set { _agreeCnt = value; }
}
private int _disagreeCnt;
[global::ProtoBuf.ProtoMember(2, IsRequired = true, Name=@"disagreeCnt", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int disagreeCnt
{
get { return _disagreeCnt; }
set { _disagreeCnt = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"PostDissolutionResult")]
public partial class PostDissolutionResult : global::ProtoBuf.IExtensible
{
public PostDissolutionResult() {}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"SendSoundReq")]
public partial class SendSoundReq : global::ProtoBuf.IExtensible
{
public SendSoundReq() {}
private int _playerId;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"playerId", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int playerId
{
get { return _playerId; }
set { _playerId = value; }
}
private int _soundId;
[global::ProtoBuf.ProtoMember(2, IsRequired = true, Name=@"soundId", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int soundId
{
get { return _soundId; }
set { _soundId = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"PostSendSoundResp")]
public partial class PostSendSoundResp : global::ProtoBuf.IExtensible
{
public PostSendSoundResp() {}
private int _playerId;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"playerId", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int playerId
{
get { return _playerId; }
set { _playerId = value; }
}
private int _soundId;
[global::ProtoBuf.ProtoMember(2, IsRequired = true, Name=@"soundId", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int soundId
{
get { return _soundId; }
set { _soundId = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"SignOutReq")]
public partial class SignOutReq : global::ProtoBuf.IExtensible
{
public SignOutReq() {}
private int _playerid;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"playerid", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int playerid
{
get { return _playerid; }
set { _playerid = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"ReEntryNNRoomReq")]
public partial class ReEntryNNRoomReq : global::ProtoBuf.IExtensible
{
public ReEntryNNRoomReq() {}
private int _roomId;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"roomId", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int roomId
{
get { return _roomId; }
set { _roomId = value; }
}
private int _playerId;
[global::ProtoBuf.ProtoMember(2, IsRequired = true, Name=@"playerId", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int playerId
{
get { return _playerId; }
set { _playerId = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"PostUnusualQuit")]
public partial class PostUnusualQuit : global::ProtoBuf.IExtensible
{
public PostUnusualQuit() {}
private int _playerId;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"playerId", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int playerId
{
get { return _playerId; }
set { _playerId = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"PostPlayerOnline")]
public partial class PostPlayerOnline : global::ProtoBuf.IExtensible
{
public PostPlayerOnline() {}
private int _playerId;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"playerId", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int playerId
{
get { return _playerId; }
set { _playerId = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"PostPlayerOffline")]
public partial class PostPlayerOffline : global::ProtoBuf.IExtensible
{
public PostPlayerOffline() {}
private int _playerId;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"playerId", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int playerId
{
get { return _playerId; }
set { _playerId = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"ReConnectReq")]
public partial class ReConnectReq : global::ProtoBuf.IExtensible
{
public ReConnectReq() {}
private int _playerId;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"playerId", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int playerId
{
get { return _playerId; }
set { _playerId = value; }
}
private string _token;
[global::ProtoBuf.ProtoMember(3, IsRequired = true, Name=@"token", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string token
{
get { return _token; }
set { _token = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"ReConnectResp")]
public partial class ReConnectResp : global::ProtoBuf.IExtensible
{
public ReConnectResp() {}
private bool _reLoginSuccessed;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"reLoginSuccessed", DataFormat = global::ProtoBuf.DataFormat.Default)]
public bool reLoginSuccessed
{
get { return _reLoginSuccessed; }
set { _reLoginSuccessed = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"HeartBeatReq")]
public partial class HeartBeatReq : global::ProtoBuf.IExtensible
{
public HeartBeatReq() {}
private int _playerId;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"playerId", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int playerId
{
get { return _playerId; }
set { _playerId = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::ProtoBuf.ProtoContract(Name=@"MESSAGE_ID")]
public enum MESSAGE_ID
{
[global::ProtoBuf.ProtoEnum(Name=@"msg_LoginReq", Value=1)]
msg_LoginReq = 1,
[global::ProtoBuf.ProtoEnum(Name=@"msg_LoginResp", Value=2)]
msg_LoginResp = 2,
[global::ProtoBuf.ProtoEnum(Name=@"msg_CreateRoomReq", Value=3)]
msg_CreateRoomReq = 3,
[global::ProtoBuf.ProtoEnum(Name=@"msg_CreateRoomResp", Value=4)]
msg_CreateRoomResp = 4,
[global::ProtoBuf.ProtoEnum(Name=@"msg_EntryRoomReq", Value=5)]
msg_EntryRoomReq = 5,
[global::ProtoBuf.ProtoEnum(Name=@"msg_EntryRoomResp", Value=6)]
msg_EntryRoomResp = 6,
[global::ProtoBuf.ProtoEnum(Name=@"msg_PostEntryRoom", Value=7)]
msg_PostEntryRoom = 7,
[global::ProtoBuf.ProtoEnum(Name=@"msg_Player", Value=8)]
msg_Player = 8,
[global::ProtoBuf.ProtoEnum(Name=@"msg_DisbandReq", Value=9)]
msg_DisbandReq = 9,
[global::ProtoBuf.ProtoEnum(Name=@"msg_PostDisband", Value=10)]
msg_PostDisband = 10,
[global::ProtoBuf.ProtoEnum(Name=@"msg_DisbandCheckReq", Value=11)]
msg_DisbandCheckReq = 11,
[global::ProtoBuf.ProtoEnum(Name=@"msg_PostDisbandCheck", Value=12)]
msg_PostDisbandCheck = 12,
[global::ProtoBuf.ProtoEnum(Name=@"msg_SettlementInfo", Value=13)]
msg_SettlementInfo = 13,
[global::ProtoBuf.ProtoEnum(Name=@"msg_DiscardReq", Value=14)]
msg_DiscardReq = 14,
[global::ProtoBuf.ProtoEnum(Name=@"msg_PostDiscard", Value=15)]
msg_PostDiscard = 15,
[global::ProtoBuf.ProtoEnum(Name=@"msg_DealReq", Value=16)]
msg_DealReq = 16,
[global::ProtoBuf.ProtoEnum(Name=@"msg_DealResp", Value=17)]
msg_DealResp = 17,
[global::ProtoBuf.ProtoEnum(Name=@"msg_GrabHostReq", Value=18)]
msg_GrabHostReq = 18,
[global::ProtoBuf.ProtoEnum(Name=@"msg_PostGrabHostResp", Value=19)]
msg_PostGrabHostResp = 19,
[global::ProtoBuf.ProtoEnum(Name=@"msg_MsgInfo", Value=20)]
msg_MsgInfo = 20,
[global::ProtoBuf.ProtoEnum(Name=@"msg_PostDealOver", Value=21)]
msg_PostDealOver = 21,
[global::ProtoBuf.ProtoEnum(Name=@"msg_CreateNNRoomReq", Value=22)]
msg_CreateNNRoomReq = 22,
[global::ProtoBuf.ProtoEnum(Name=@"msg_CreateNNRoomResp", Value=23)]
msg_CreateNNRoomResp = 23,
[global::ProtoBuf.ProtoEnum(Name=@"msg_EntryNNRoomReq", Value=24)]
msg_EntryNNRoomReq = 24,
[global::ProtoBuf.ProtoEnum(Name=@"msg_EntryNNRoomResp", Value=25)]
msg_EntryNNRoomResp = 25,
[global::ProtoBuf.ProtoEnum(Name=@"msg_PostNNEntryRoom", Value=26)]
msg_PostNNEntryRoom = 26,
[global::ProtoBuf.ProtoEnum(Name=@"msg_StartNNGameReq", Value=27)]
msg_StartNNGameReq = 27,
[global::ProtoBuf.ProtoEnum(Name=@"msg_StartNNGameResp", Value=28)]
msg_StartNNGameResp = 28,
[global::ProtoBuf.ProtoEnum(Name=@"msg_PostStartNNGame", Value=29)]
msg_PostStartNNGame = 29,
[global::ProtoBuf.ProtoEnum(Name=@"msg_NNPrepareReq", Value=30)]
msg_NNPrepareReq = 30,
[global::ProtoBuf.ProtoEnum(Name=@"msg_PostNNDealResp", Value=31)]
msg_PostNNDealResp = 31,
[global::ProtoBuf.ProtoEnum(Name=@"msg_StakeReq", Value=32)]
msg_StakeReq = 32,
[global::ProtoBuf.ProtoEnum(Name=@"msg_StakeResp", Value=33)]
msg_StakeResp = 33,
[global::ProtoBuf.ProtoEnum(Name=@"msg_PostStakeResp", Value=34)]
msg_PostStakeResp = 34,
[global::ProtoBuf.ProtoEnum(Name=@"msg_NNShowCardsReq", Value=35)]
msg_NNShowCardsReq = 35,
[global::ProtoBuf.ProtoEnum(Name=@"msg_NNShowCardsResp", Value=36)]
msg_NNShowCardsResp = 36,
[global::ProtoBuf.ProtoEnum(Name=@"msg_PostNNShowCards", Value=37)]
msg_PostNNShowCards = 37,
[global::ProtoBuf.ProtoEnum(Name=@"msg_PostNNPrepareResp", Value=38)]
msg_PostNNPrepareResp = 38,
[global::ProtoBuf.ProtoEnum(Name=@"msg_PostStakeOver", Value=39)]
msg_PostStakeOver = 39,
[global::ProtoBuf.ProtoEnum(Name=@"msg_NNDissolutionReq", Value=40)]
msg_NNDissolutionReq = 40,
[global::ProtoBuf.ProtoEnum(Name=@"msg_PostDissolutionResp", Value=41)]
msg_PostDissolutionResp = 41,
[global::ProtoBuf.ProtoEnum(Name=@"msg_NNAnswerDissolutionReq", Value=42)]
msg_NNAnswerDissolutionReq = 42,
[global::ProtoBuf.ProtoEnum(Name=@"msg_PostAnswerDissolutionResult", Value=43)]
msg_PostAnswerDissolutionResult = 43,
[global::ProtoBuf.ProtoEnum(Name=@"msg_PostDissolutionResult", Value=44)]
msg_PostDissolutionResult = 44,
[global::ProtoBuf.ProtoEnum(Name=@"msg_SendSoundReq", Value=45)]
msg_SendSoundReq = 45,
[global::ProtoBuf.ProtoEnum(Name=@"msg_PostSendSoundResp", Value=46)]
msg_PostSendSoundResp = 46,
[global::ProtoBuf.ProtoEnum(Name=@"msg_SignOutReq", Value=47)]
msg_SignOutReq = 47,
[global::ProtoBuf.ProtoEnum(Name=@"msg_ReEntryNNRoomReq", Value=48)]
msg_ReEntryNNRoomReq = 48,
[global::ProtoBuf.ProtoEnum(Name=@"msg_PostUnusualQuit", Value=49)]
msg_PostUnusualQuit = 49,
[global::ProtoBuf.ProtoEnum(Name=@"msg_PostPlayerOnline", Value=50)]
msg_PostPlayerOnline = 50,
[global::ProtoBuf.ProtoEnum(Name=@"msg_PostPlayerOffline", Value=51)]
msg_PostPlayerOffline = 51,
[global::ProtoBuf.ProtoEnum(Name=@"msg_HeartBeatReq", Value=52)]
msg_HeartBeatReq = 52,
[global::ProtoBuf.ProtoEnum(Name=@"msg_HeartBeatResp", Value=53)]
msg_HeartBeatResp = 53,
[global::ProtoBuf.ProtoEnum(Name=@"msg_ReConnectReq", Value=54)]
msg_ReConnectReq = 54,
[global::ProtoBuf.ProtoEnum(Name=@"msg_ReConnectResp", Value=55)]
msg_ReConnectResp = 55
}
[global::ProtoBuf.ProtoContract(Name=@"NNType")]
public enum NNType
{
[global::ProtoBuf.ProtoEnum(Name=@"NNT_ERROR", Value=0)]
NNT_ERROR = 0,
[global::ProtoBuf.ProtoEnum(Name=@"NNT_NONE", Value=1)]
NNT_NONE = 1,
[global::ProtoBuf.ProtoEnum(Name=@"NNT_SPECIAL_NIU1", Value=2)]
NNT_SPECIAL_NIU1 = 2,
[global::ProtoBuf.ProtoEnum(Name=@"NNT_SPECIAL_NIU2", Value=3)]
NNT_SPECIAL_NIU2 = 3,
[global::ProtoBuf.ProtoEnum(Name=@"NNT_SPECIAL_NIU3", Value=4)]
NNT_SPECIAL_NIU3 = 4,
[global::ProtoBuf.ProtoEnum(Name=@"NNT_SPECIAL_NIU4", Value=5)]
NNT_SPECIAL_NIU4 = 5,
[global::ProtoBuf.ProtoEnum(Name=@"NNT_SPECIAL_NIU5", Value=6)]
NNT_SPECIAL_NIU5 = 6,
[global::ProtoBuf.ProtoEnum(Name=@"NNT_SPECIAL_NIU6", Value=7)]
NNT_SPECIAL_NIU6 = 7,
[global::ProtoBuf.ProtoEnum(Name=@"NNT_SPECIAL_NIU7", Value=8)]
NNT_SPECIAL_NIU7 = 8,
[global::ProtoBuf.ProtoEnum(Name=@"NNT_SPECIAL_NIU8", Value=9)]
NNT_SPECIAL_NIU8 = 9,
[global::ProtoBuf.ProtoEnum(Name=@"NNT_SPECIAL_NIU9", Value=10)]
NNT_SPECIAL_NIU9 = 10,
[global::ProtoBuf.ProtoEnum(Name=@"NNT_SPECIAL_NIUNIU", Value=11)]
NNT_SPECIAL_NIUNIU = 11,
[global::ProtoBuf.ProtoEnum(Name=@"NNT_SPECIAL_NIUHUA", Value=12)]
NNT_SPECIAL_NIUHUA = 12,
[global::ProtoBuf.ProtoEnum(Name=@"NNT_SPECIAL_BOMEBOME", Value=13)]
NNT_SPECIAL_BOMEBOME = 13
}
[global::ProtoBuf.ProtoContract(Name=@"NNStatus")]
public enum NNStatus
{
[global::ProtoBuf.ProtoEnum(Name=@"STATUS_NONE", Value=0)]
STATUS_NONE = 0,
[global::ProtoBuf.ProtoEnum(Name=@"STATUS_CREATE_ROOM", Value=1)]
STATUS_CREATE_ROOM = 1,
[global::ProtoBuf.ProtoEnum(Name=@"STATUS_ENTER_ROOM", Value=2)]
STATUS_ENTER_ROOM = 2,
[global::ProtoBuf.ProtoEnum(Name=@"STATUS_BEGIN_PREPARE", Value=3)]
STATUS_BEGIN_PREPARE = 3,
[global::ProtoBuf.ProtoEnum(Name=@"STATUS_FINISH_PREPARE", Value=4)]
STATUS_FINISH_PREPARE = 4,
[global::ProtoBuf.ProtoEnum(Name=@"STATUS_BEGIN_STAKE", Value=5)]
STATUS_BEGIN_STAKE = 5,
[global::ProtoBuf.ProtoEnum(Name=@"STATUS_BEGIN_SHOWCARDS", Value=6)]
STATUS_BEGIN_SHOWCARDS = 6,
[global::ProtoBuf.ProtoEnum(Name=@"STATUS_PREPARE_NEXT", Value=7)]
STATUS_PREPARE_NEXT = 7
}
[global::ProtoBuf.ProtoContract(Name=@"BankerType")]
public enum BankerType
{
[global::ProtoBuf.ProtoEnum(Name=@"BT_NONE", Value=0)]
BT_NONE = 0,
[global::ProtoBuf.ProtoEnum(Name=@"BT_BAWANG", Value=1)]
BT_BAWANG = 1,
[global::ProtoBuf.ProtoEnum(Name=@"BT_LUNZHUANG", Value=2)]
BT_LUNZHUANG = 2,
[global::ProtoBuf.ProtoEnum(Name=@"BT_ZHUANZHUANG", Value=3)]
BT_ZHUANZHUANG = 3
}
}
|
inquick/rxzp
|
Assets/Scripts/Protocols/MessageInfo.cs
|
C#
|
apache-2.0
| 95,654
|
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.openqa.selenium.remote.server;
import static org.openqa.selenium.remote.server.WebDriverServlet.NEW_SESSION_PIPELINE_KEY;
import com.beust.jcommander.JCommander;
import org.openqa.grid.internal.utils.configuration.GridNodeConfiguration;
import org.openqa.grid.internal.utils.configuration.StandaloneConfiguration;
import org.openqa.grid.selenium.node.ChromeMutator;
import org.openqa.grid.selenium.node.FirefoxMutator;
import org.openqa.grid.shared.GridNodeServer;
import org.openqa.grid.web.servlet.DisplayHelpServlet;
import org.openqa.grid.web.servlet.beta.ConsoleServlet;
import org.openqa.selenium.Platform;
import org.openqa.selenium.remote.SessionId;
import org.openqa.selenium.remote.server.handler.DeleteSession;
import org.openqa.selenium.remote.server.jmx.JMXHelper;
import org.openqa.selenium.remote.server.jmx.ManagedService;
import org.seleniumhq.jetty9.security.ConstraintMapping;
import org.seleniumhq.jetty9.security.ConstraintSecurityHandler;
import org.seleniumhq.jetty9.server.Connector;
import org.seleniumhq.jetty9.server.HttpConfiguration;
import org.seleniumhq.jetty9.server.HttpConnectionFactory;
import org.seleniumhq.jetty9.server.Server;
import org.seleniumhq.jetty9.server.ServerConnector;
import org.seleniumhq.jetty9.servlet.ServletContextHandler;
import org.seleniumhq.jetty9.util.security.Constraint;
import org.seleniumhq.jetty9.util.thread.QueuedThreadPool;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
import javax.servlet.Servlet;
/**
* Provides a server that can launch and manage selenium sessions.
*/
@ManagedService(objectName = "org.seleniumhq.server:type=SeleniumServer")
public class SeleniumServer implements GridNodeServer {
private final static Logger LOG = Logger.getLogger(SeleniumServer.class.getName());
private Server server;
private DefaultDriverSessions driverSessions;
private StandaloneConfiguration configuration;
private Map<String, Class<? extends Servlet>> extraServlets;
private Thread shutDownHook;
/**
* This lock is very important to ensure that SeleniumServer and the underlying Jetty instance
* shuts down properly. It ensures that ProxyHandler does not add an SslRelay to the Jetty server
* dynamically (needed for SSL proxying) if the server has been shut down or is in the process of
* getting shut down.
*/
private final Object shutdownLock = new Object();
private static final int MAX_SHUTDOWN_RETRIES = 8;
public SeleniumServer(StandaloneConfiguration configuration) {
this.configuration = configuration;
new JMXHelper().register(this);
}
public int getRealPort() {
if (server.isStarted()) {
ServerConnector socket = (ServerConnector)server.getConnectors()[0];
return socket.getPort();
}
return configuration.port;
}
private void addRcSupport(ServletContextHandler handler) {
try {
Class<? extends Servlet> rcServlet = Class.forName(
"com.thoughtworks.selenium.webdriven.WebDriverBackedSeleniumServlet",
false,
getClass().getClassLoader())
.asSubclass(Servlet.class);
handler.addServlet(rcServlet, "/selenium-server/driver/");
LOG.info("Bound legacy RC support");
} catch (ClassNotFoundException e) {
// Do nothing.
}
}
private void addExtraServlets(ServletContextHandler handler) {
if (extraServlets != null && extraServlets.size() > 0) {
for (String path : extraServlets.keySet()) {
handler.addServlet(extraServlets.get(path), path);
}
}
}
public void setConfiguration(StandaloneConfiguration configuration) {
this.configuration = configuration;
}
public void setExtraServlets(Map<String, Class<? extends Servlet>> extraServlets) {
this.extraServlets = extraServlets;
}
public void boot() {
if (configuration.jettyMaxThreads != null && configuration.jettyMaxThreads > 0) {
server = new Server(new QueuedThreadPool(configuration.jettyMaxThreads));
} else {
server = new Server();
}
ServletContextHandler handler = new ServletContextHandler(ServletContextHandler.SECURITY);
if (configuration.browserTimeout != null && configuration.browserTimeout >= 0) {
handler.setInitParameter(DriverServlet.BROWSER_TIMEOUT_PARAMETER,
String.valueOf(configuration.browserTimeout));
}
long inactiveSessionTimeoutSeconds = configuration.timeout == null ?
Long.MAX_VALUE /1000 : configuration.timeout;
if (configuration.timeout != null && configuration.timeout >= 0) {
handler.setInitParameter(DriverServlet.SESSION_TIMEOUT_PARAMETER,
String.valueOf(configuration.timeout));
}
driverSessions = new DefaultDriverSessions(
new DefaultDriverFactory(Platform.getCurrent()),
TimeUnit.SECONDS.toMillis(inactiveSessionTimeoutSeconds));
handler.setAttribute(DriverServlet.SESSIONS_KEY, driverSessions);
NewSessionPipeline pipeline = createPipeline(configuration);
handler.setAttribute(NEW_SESSION_PIPELINE_KEY, pipeline);
handler.setContextPath("/");
if (configuration.enablePassThrough) {
LOG.info("Using the passthrough mode handler");
handler.addServlet(WebDriverServlet.class, "/wd/hub/*");
handler.addServlet(WebDriverServlet.class, "/webdriver/*");
} else {
handler.addServlet(DriverServlet.class, "/wd/hub/*");
handler.addServlet(DriverServlet.class, "/webdriver/*");
}
handler.setInitParameter(ConsoleServlet.CONSOLE_PATH_PARAMETER, "/wd/hub");
handler.setInitParameter(DisplayHelpServlet.HELPER_TYPE_PARAMETER, configuration.role);
addRcSupport(handler);
addExtraServlets(handler);
Constraint constraint = new Constraint();
constraint.setName("Disable TRACE");
constraint.setAuthenticate(true);
ConstraintMapping mapping = new ConstraintMapping();
mapping.setConstraint(constraint);
mapping.setMethod("TRACE");
mapping.setPathSpec("/");
ConstraintSecurityHandler securityHandler = (ConstraintSecurityHandler) handler.getSecurityHandler();
securityHandler.addConstraintMapping(mapping);
server.setHandler(handler);
HttpConfiguration httpConfig = new HttpConfiguration();
httpConfig.setSecureScheme("https");
ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(httpConfig));
if (configuration.port == null) {
configuration.port = 4444;
}
http.setPort(configuration.port);
http.setIdleTimeout(500000);
server.setConnectors(new Connector[]{http});
try {
server.start();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private NewSessionPipeline createPipeline(StandaloneConfiguration configuration) {
NewSessionPipeline.Builder builder = DefaultPipeline.createPipelineWithDefaultFallbacks();
if (configuration instanceof GridNodeConfiguration) {
((GridNodeConfiguration) configuration).capabilities.forEach(
caps -> {
builder.addCapabilitiesMutator(new ChromeMutator(caps));
builder.addCapabilitiesMutator(new FirefoxMutator(caps));
}
);
}
return builder.create();
}
/**
* Stops the Jetty server
*/
public void stop() {
int numTries = 0;
Exception shutDownException = null;
// this may be called by a shutdown hook, or it may be called at any time
// in case it was called as an ordinary method, try to clean up the shutdown
// hook
try {
if (shutDownHook != null) {
Runtime.getRuntime().removeShutdownHook(shutDownHook);
}
} catch (IllegalStateException ignored) {
} // thrown if we're shutting down; that's OK
// shut down the jetty server (try try again)
while (numTries <= MAX_SHUTDOWN_RETRIES) {
++numTries;
try {
// see docs for the lock object for information on this and why it is IMPORTANT!
synchronized (shutdownLock) {
server.stop();
}
// If we reached here stop didnt throw an exception.
// So we assume it was successful.
break;
} catch (Exception ex) { // org.openqa.jetty.jetty.Server.stop() throws Exception
shutDownException = ex;
// If Exception is thrown we try to stop the jetty server again
}
}
// next, stop all of the browser sessions.
stopAllBrowsers();
if (numTries > MAX_SHUTDOWN_RETRIES) { // This is bad!! Jetty didnt shutdown..
if (null != shutDownException) {
throw new RuntimeException(shutDownException);
}
}
}
private void stopAllBrowsers() {
for (SessionId sessionId : driverSessions.getSessions()) {
Session session = driverSessions.get(sessionId);
DeleteSession deleteSession = new DeleteSession(session);
try {
deleteSession.call();
driverSessions.deleteSession(sessionId);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
public static void main(String[] argv) {
StandaloneConfiguration configuration = new StandaloneConfiguration();
JCommander jCommander = new JCommander(configuration, argv);
jCommander.setProgramName("selenium-3-server");
if (configuration.help) {
StringBuilder message = new StringBuilder();
jCommander.usage(message);
System.err.println(message.toString());
return;
}
SeleniumServer server = new SeleniumServer(configuration);
server.boot();
}
public static void usage(String msg) {
if (msg != null) {
System.out.println(msg);
}
StandaloneConfiguration args = new StandaloneConfiguration();
JCommander jCommander = new JCommander(args);
jCommander.usage();
}
}
|
juangj/selenium
|
java/server/src/org/openqa/selenium/remote/server/SeleniumServer.java
|
Java
|
apache-2.0
| 10,625
|
\hypertarget{class_triton_1_1_util_1_1_language}{}\section{Triton\+:\+:Util\+:\+:Language Class Reference}
\label{class_triton_1_1_util_1_1_language}\index{Triton\+::\+Util\+::\+Language@{Triton\+::\+Util\+::\+Language}}
The language object.
{\ttfamily \#include $<$local.\+h$>$}
\subsection*{Public Member Functions}
\begin{DoxyCompactItemize}
\item
\hyperlink{namespace_triton_1_1_util_ab36ffddebe19fdd103ec60af3841d9e2}{String} \hyperlink{class_triton_1_1_util_1_1_language_a16fd4d6c079f1a6d310dafe3c0587520}{Get\+Name} ()
\item
\hyperlink{namespace_triton_1_1_util_ab36ffddebe19fdd103ec60af3841d9e2}{String} \hyperlink{class_triton_1_1_util_1_1_language_a9a2b45374aa49fa1dc9910afd92288c6}{Get\+Local} (\hyperlink{namespace_triton_1_1_util_ab36ffddebe19fdd103ec60af3841d9e2}{String} unlocalize\+Name)
\end{DoxyCompactItemize}
\subsection*{Friends}
\begin{DoxyCompactItemize}
\item
class \hyperlink{class_triton_1_1_util_1_1_language_af7a1efe82e3beafa2fa9fc62c5ce5837}{Local\+Manager}
\end{DoxyCompactItemize}
\subsection{Detailed Description}
The language object.
Definition at line 33 of file local.\+h.
\subsection{Member Function Documentation}
\hypertarget{class_triton_1_1_util_1_1_language_a9a2b45374aa49fa1dc9910afd92288c6}{}\index{Triton\+::\+Util\+::\+Language@{Triton\+::\+Util\+::\+Language}!Get\+Local@{Get\+Local}}
\index{Get\+Local@{Get\+Local}!Triton\+::\+Util\+::\+Language@{Triton\+::\+Util\+::\+Language}}
\subsubsection[{Get\+Local}]{\setlength{\rightskip}{0pt plus 5cm}{\bf String} Triton\+::\+Util\+::\+Language\+::\+Get\+Local (
\begin{DoxyParamCaption}
\item[{{\bf String}}]{unlocalize\+Name}
\end{DoxyParamCaption}
)}\label{class_triton_1_1_util_1_1_language_a9a2b45374aa49fa1dc9910afd92288c6}
\hypertarget{class_triton_1_1_util_1_1_language_a16fd4d6c079f1a6d310dafe3c0587520}{}\index{Triton\+::\+Util\+::\+Language@{Triton\+::\+Util\+::\+Language}!Get\+Name@{Get\+Name}}
\index{Get\+Name@{Get\+Name}!Triton\+::\+Util\+::\+Language@{Triton\+::\+Util\+::\+Language}}
\subsubsection[{Get\+Name}]{\setlength{\rightskip}{0pt plus 5cm}{\bf String} Triton\+::\+Util\+::\+Language\+::\+Get\+Name (
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
)}\label{class_triton_1_1_util_1_1_language_a16fd4d6c079f1a6d310dafe3c0587520}
\subsection{Friends And Related Function Documentation}
\hypertarget{class_triton_1_1_util_1_1_language_af7a1efe82e3beafa2fa9fc62c5ce5837}{}\index{Triton\+::\+Util\+::\+Language@{Triton\+::\+Util\+::\+Language}!Local\+Manager@{Local\+Manager}}
\index{Local\+Manager@{Local\+Manager}!Triton\+::\+Util\+::\+Language@{Triton\+::\+Util\+::\+Language}}
\subsubsection[{Local\+Manager}]{\setlength{\rightskip}{0pt plus 5cm}friend class {\bf Local\+Manager}\hspace{0.3cm}{\ttfamily [friend]}}\label{class_triton_1_1_util_1_1_language_af7a1efe82e3beafa2fa9fc62c5ce5837}
Definition at line 35 of file local.\+h.
The documentation for this class was generated from the following file\+:\begin{DoxyCompactItemize}
\item
util/\hyperlink{local_8h}{local.\+h}\end{DoxyCompactItemize}
|
TriantEntertainment/TritonEngine
|
docs/latex/class_triton_1_1_util_1_1_language.tex
|
TeX
|
apache-2.0
| 3,045
|
# Lepidium praetervisum Domin SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Brassicales/Brassicaceae/Lepidium/Lepidium desvauxii/ Syn. Lepidium praetervisum/README.md
|
Markdown
|
apache-2.0
| 184
|
# Saprolegnia paradoxa H.E. Petersen SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
Annls mycol. 8: 520 (1910)
#### Original name
Saprolegnia paradoxa H.E. Petersen
### Remarks
null
|
mdoering/backbone
|
life/Chromista/Oomycota/Oomycetes/Saprolegniales/Saprolegniaceae/Saprolegnia/Saprolegnia paradoxa/README.md
|
Markdown
|
apache-2.0
| 219
|
# Behuria magdalenensis (Brade) Tavares & Baumgratz SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Myrtales/Melastomataceae/Behuria/Behuria magdalenensis/README.md
|
Markdown
|
apache-2.0
| 207
|
# Nunnezharoa robusta Kuntze SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Liliopsida/Arecales/Arecaceae/Nunnezharoa/Nunnezharoa robusta/README.md
|
Markdown
|
apache-2.0
| 176
|
# Parmotrema taitae (Krog & Swinscow) Krog & Swinscow SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Lichenologist 15(2): 130 (1983)
#### Original name
Parmelia taitae Krog & Swinscow
### Remarks
null
|
mdoering/backbone
|
life/Fungi/Ascomycota/Lecanoromycetes/Lecanorales/Parmeliaceae/Parmotrema/Parmotrema taitae/README.md
|
Markdown
|
apache-2.0
| 263
|
# Leucopoa karatavica (Bunge) Krecz. & Bobrov SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
V. L. Komarov, Fl. URSS 2:496. 1934
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Liliopsida/Poales/Poaceae/Festuca/Festuca griffithiana/ Syn. Leucopoa karatavica/README.md
|
Markdown
|
apache-2.0
| 231
|
# Lecidea glauca Taylor SPECIES
#### Status
SYNONYM
#### According to
Index Fungorum
#### Published in
London J. Bot. 6: 149 (1847)
#### Original name
Lecidea glauca Taylor
### Remarks
null
|
mdoering/backbone
|
life/Fungi/Ascomycota/Lecanoromycetes/Lecanorales/Porpidiaceae/Paraporpidia/Paraporpidia glauca/ Syn. Lecidea glauca/README.md
|
Markdown
|
apache-2.0
| 194
|
#
# Cookbook Name:: blah
# Recipe:: default
#
# Copyright (c) 2015 The Authors, All Rights Reserved.
template '/etc/blah' do
source 'blah.erb'
end
|
pburkholder/cheffian-examples
|
attribute_nesting/test/fixtures/cookbooks/blah/recipes/default.rb
|
Ruby
|
apache-2.0
| 150
|
# The new stack

[On How We Found Kubernetes](https://eng.revinate.com/2015/09/11/on-how-we-found-kubernetes.html) (Bryan Stenson, Revinate, Sep 11 2015)
[Why Bother Building Cloud Native Applications?](http://engineeredweb.com/blog/2015/why-bother-with-cloud-native/?utm_content=buffer87f05&utm_medium=social&utm_source=twitter.com&utm_campaign=buffer) (Matthew Farina, HP, Sep 18 2015)
[Get ready for the new stack](http://www.infoworld.com/article/2880770/devops/get-ready-for-the-new-stack.html) (Eric Knorr, infoworld, Feb 9 2015)
[What makes a cluster a cluster?](https://coreos.com/blog/cluster-osi-model/) (Barak Michener, CoreOS, March 20 2015)
[What makes a container cluster?](http://googlecloudplatform.blogspot.tw/2015/01/what-makes-a-container-cluster.html) (Joe Beda, Google, Jan 22 2015)
[The Snooty Developer's Visual Guide to Kubernetes](http://technosophos.com/2015/09/15/a-visual-guide-to-kubernetes.html?utm_content=buffercd8ac&utm_medium=social&utm_source=twitter.com&utm_campaign=buffer) (Matt Butcher, Engine Yard, Sep 15 2015)
[A Technical Overview of Kubernetes](https://www.youtube.com/watch?v=WwBdNXt6wO4) (Brendan Burns, Google, May 4 2015)
[Patterns for Composite Containers](http://blog.kubernetes.io/2015/06/the-distributed-system-toolkit-patterns.html) , [video](https://www.youtube.com/watch?v=Ph3t8jIt894) (Brendan Burns, Google, June 29 2015)
[Stacking Up The Next Modern Platform](https://www.nextplatform.com/2015/10/16/stacking-up-a-modern-platform/) ([Joe Beda](http://www.geekwire.com/2015/joseph-beda/), 0xBEDA, Oct 16 2015)
[Kubernetes: What's New](https://speakerdeck.com/thockin) (Tim Hockin, Google, Nov 12 2015)
|
gosharplite/the-new-stack
|
README.md
|
Markdown
|
apache-2.0
| 1,711
|
// $Id: ACE.cpp 79134 2007-07-31 18:23:50Z johnnyw $
#include "ace/ACE.h"
#include "ace/Basic_Types.h"
#include "ace/Handle_Set.h"
#include "ace/Auto_Ptr.h"
#include "ace/SString.h"
#include "ace/Version.h"
#include "ace/Message_Block.h"
#include "ace/Log_Msg.h"
#include "ace/OS_NS_sys_select.h"
#include "ace/OS_NS_string.h"
#include "ace/OS_NS_strings.h"
#include "ace/OS_NS_signal.h"
#include "ace/OS_NS_stdio.h"
#include "ace/OS_NS_sys_resource.h"
#include "ace/OS_NS_sys_wait.h"
#include "ace/OS_NS_sys_time.h"
#include "ace/OS_NS_time.h"
#include "ace/OS_NS_sys_uio.h"
#include "ace/OS_NS_sys_stat.h"
#include "ace/OS_NS_ctype.h"
#include "ace/OS_TLI.h"
#if defined (ACE_VXWORKS) && (ACE_VXWORKS < 0x620)
extern "C" int maxFiles;
#endif /* ACE_VXWORKS */
#if !defined (__ACE_INLINE__)
#include "ace/ACE.inl"
#endif /* __ACE_INLINE__ */
#if defined (ACE_HAS_POLL) && defined (ACE_HAS_LIMITED_SELECT)
# include "ace/OS_NS_poll.h"
#endif /* ACE_HAS_POLL && ACE_HAS_LIMITED_SELECT */
ACE_RCSID (ace,
ACE,
"$Id: ACE.cpp 79134 2007-07-31 18:23:50Z johnnyw $")
// Open versioned namespace, if enabled by the user.
ACE_BEGIN_VERSIONED_NAMESPACE_DECL
namespace ACE
{
// private:
// Used internally so not exported.
// Size of allocation granularity.
size_t allocation_granularity_ = 0;
// Size of a VM page.
size_t pagesize_ = 0;
// Are we debugging ACE?
// Keeps track of whether we're in some global debug mode.
char debug_;
}
int
ACE::out_of_handles (int error)
{
// EMFILE is common to all platforms.
if (error == EMFILE ||
#if defined (ACE_WIN32)
// On Win32, we need to check for ENOBUFS also.
error == ENOBUFS ||
#elif defined (HPUX)
// On HPUX, we need to check for EADDRNOTAVAIL also.
error == EADDRNOTAVAIL ||
#elif defined (linux)
// On linux, we need to check for ENOENT also.
error == ENOENT ||
// For RedHat5.2, need to check for EINVAL too.
error == EINVAL ||
// Without threads check for EOPNOTSUPP
error == EOPNOTSUPP ||
#elif defined (sun)
// On sun, we need to check for ENOSR also.
error == ENOSR ||
// Without threads check for ENOTSUP
error == ENOTSUP ||
#elif defined (__FreeBSD__)
// On FreeBSD we need to check for EOPNOTSUPP (LinuxThreads) or
// ENOSYS (libc_r threads) also.
error == EOPNOTSUPP ||
error == ENOSYS ||
#elif defined (__OpenBSD__)
// OpenBSD appears to return EBADF.
error == EBADF ||
#elif defined (__sgi) // irix
error == ENOTSUP ||
#elif defined (DIGITAL_UNIX) // osf1
error == ENOTSUP ||
#endif /* ACE_WIN32 */
error == ENFILE)
return 1;
else
return 0;
}
u_int
ACE::major_version (void)
{
return ACE_MAJOR_VERSION;
}
u_int
ACE::minor_version (void)
{
return ACE_MINOR_VERSION;
}
u_int
ACE::beta_version (void)
{
return ACE_BETA_VERSION;
}
const ACE_TCHAR *
ACE::compiler_name (void)
{
#ifdef ACE_CC_NAME
return ACE_CC_NAME;
#else
return ACE_TEXT ("");
#endif
}
u_int
ACE::compiler_major_version (void)
{
#ifdef ACE_CC_MAJOR_VERSION
return ACE_CC_MAJOR_VERSION;
#else
return 0;
#endif
}
u_int
ACE::compiler_minor_version (void)
{
#ifdef ACE_CC_MINOR_VERSION
return ACE_CC_MINOR_VERSION;
#else
return 0;
#endif
}
u_int
ACE::compiler_beta_version (void)
{
#ifdef ACE_CC_BETA_VERSION
return ACE_CC_BETA_VERSION;
#else
return 0;
#endif
}
bool
ACE::debug (void)
{
static const char* debug = ACE_OS::getenv ("ACE_DEBUG");
return (ACE::debug_ != 0) ? ACE::debug_ : (debug != 0 ? (*debug != '0'): false);
}
void
ACE::debug (bool onoff)
{
ACE::debug_ = onoff;
}
int
ACE::select (int width,
ACE_Handle_Set *readfds,
ACE_Handle_Set *writefds,
ACE_Handle_Set *exceptfds,
const ACE_Time_Value *timeout)
{
int result = ACE_OS::select (width,
readfds ? readfds->fdset () : 0,
writefds ? writefds->fdset () : 0,
exceptfds ? exceptfds->fdset () : 0,
timeout);
if (result > 0)
{
# if !defined (ACE_WIN32)
// This isn't needed for Windows... it's a no-op anyway.
if (readfds)
readfds->sync ((ACE_HANDLE) width);
if (writefds)
writefds->sync ((ACE_HANDLE) width);
if (exceptfds)
exceptfds->sync ((ACE_HANDLE) width);
#endif /* ACE_WIN32 */
}
return result;
}
int
ACE::select (int width,
ACE_Handle_Set &readfds,
const ACE_Time_Value *timeout)
{
int result = ACE_OS::select (width,
readfds.fdset (),
0,
0,
timeout);
#if !defined (ACE_WIN32)
if (result > 0)
readfds.sync ((ACE_HANDLE) width);
#endif /* ACE_WIN32 */
return result;
}
int
ACE::terminate_process (pid_t pid)
{
#if defined (ACE_HAS_PHARLAP)
ACE_UNUSED_ARG (pid);
ACE_NOTSUP_RETURN (-1);
#elif defined (ACE_WIN32)
// Create a handle for the given process id.
ACE_HANDLE process_handle =
::OpenProcess (PROCESS_TERMINATE,
FALSE, // New handle is not inheritable.
pid);
if (process_handle == ACE_INVALID_HANDLE
|| process_handle == 0)
return -1;
else
{
// Kill the process associated with process_handle.
BOOL terminate_result =
::TerminateProcess (process_handle, 0);
// Free up the kernel resources.
ACE_OS::close (process_handle);
return terminate_result ? 0 : -1;
}
#else
return ACE_OS::kill (pid, 9);
#endif /* ACE_HAS_PHARLAP */
}
int
ACE::process_active (pid_t pid)
{
#if !defined(ACE_WIN32)
int retval = ACE_OS::kill (pid, 0);
if (retval == 0)
return 1;
else if (errno == ESRCH)
return 0;
else
return -1;
#else
// Create a handle for the given process id.
ACE_HANDLE process_handle =
::OpenProcess (PROCESS_QUERY_INFORMATION, FALSE, pid);
if (process_handle == ACE_INVALID_HANDLE
|| process_handle == 0)
return 0;
else
{
DWORD status;
int result = 1;
if (::GetExitCodeProcess (process_handle,
&status) == 0
|| status != STILL_ACTIVE)
result = 0;
::CloseHandle (process_handle);
return result;
}
#endif /* !ACE_WIN32 */
}
const ACE_TCHAR *
ACE::execname (const ACE_TCHAR *old_name)
{
#if defined (ACE_WIN32)
const ACE_TCHAR *suffix = ACE_OS::strrchr (old_name, ACE_TEXT ('.'));
if (suffix == 0 || ACE_OS::strcasecmp (suffix, ACE_TEXT (".exe")) != 0)
{
ACE_TCHAR *new_name;
size_t size =
ACE_OS::strlen (old_name)
+ ACE_OS::strlen (ACE_TEXT (".exe"))
+ 1;
ACE_NEW_RETURN (new_name,
ACE_TCHAR[size],
0);
ACE_TCHAR *end = new_name;
end = ACE_OS::strecpy (new_name, old_name);
// Concatenate the .exe suffix onto the end of the executable.
// end points _after_ the terminating nul.
ACE_OS::strcpy (end - 1, ACE_TEXT (".exe"));
return new_name;
}
#endif /* ACE_WIN32 */
return old_name;
}
u_long
ACE::hash_pjw (const char *str, size_t len)
{
u_long hash = 0;
for (size_t i = 0; i < len; i++)
{
const char temp = str[i];
hash = (hash << 4) + (temp * 13);
u_long g = hash & 0xf0000000;
if (g)
{
hash ^= (g >> 24);
hash ^= g;
}
}
return hash;
}
u_long
ACE::hash_pjw (const char *str)
{
return ACE::hash_pjw (str, ACE_OS::strlen (str));
}
#if defined (ACE_HAS_WCHAR)
u_long
ACE::hash_pjw (const wchar_t *str, size_t len)
{
u_long hash = 0;
for (size_t i = 0; i < len; i++)
{
// @@ UNICODE: Does this function do the correct thing with wchar's?
const wchar_t temp = str[i];
hash = (hash << 4) + (temp * 13);
u_long g = hash & 0xf0000000;
if (g)
{
hash ^= (g >> 24);
hash ^= g;
}
}
return hash;
}
u_long
ACE::hash_pjw (const wchar_t *str)
{
return ACE::hash_pjw (str, ACE_OS::strlen (str));
}
#endif /* ACE_HAS_WCHAR */
#if !defined (ACE_HAS_WINCE)
ACE_TCHAR *
ACE::strenvdup (const ACE_TCHAR *str)
{
ACE_TRACE ("ACE::strenvdup");
return ACE_OS::strenvdup (str);
}
#endif /* ACE_HAS_WINCE */
/*
Examples:
Source NT UNIX
==================================================================
netsvc netsvc.dll libnetsvc.so
(PATH will be (LD_LIBRARY_PATH
evaluated) evaluated)
libnetsvc.dll libnetsvc.dll libnetsvc.dll + warning
netsvc.so netsvc.so + warning libnetsvc.so
..\../libs/netsvc ..\..\libs\netsvc.dll ../../libs/netsvc.so
(absolute path used) (absolute path used)
*/
const ACE_TCHAR *
ACE::basename (const ACE_TCHAR *pathname, ACE_TCHAR delim)
{
ACE_TRACE ("ACE::basename");
const ACE_TCHAR *temp = ACE_OS::strrchr (pathname, delim);
if (temp == 0)
return pathname;
else
return temp + 1;
}
const ACE_TCHAR *
ACE::dirname (const ACE_TCHAR *pathname, ACE_TCHAR delim)
{
ACE_TRACE ("ACE::dirname");
static ACE_TCHAR return_dirname[MAXPATHLEN + 1];
const ACE_TCHAR *temp = ACE_OS::strrchr (pathname, delim);
if (temp == 0)
{
return_dirname[0] = '.';
return_dirname[1] = '\0';
return return_dirname;
}
else
{
// When the len is truncated, there are problems! This should
// not happen in normal circomstances
size_t len = temp - pathname + 1;
if (len > (sizeof return_dirname / sizeof (ACE_TCHAR)))
len = sizeof return_dirname / sizeof (ACE_TCHAR);
ACE_OS::strsncpy (return_dirname,
pathname,
len);
return return_dirname;
}
}
ssize_t
ACE::recv (ACE_HANDLE handle,
void *buf,
size_t len,
int flags,
const ACE_Time_Value *timeout)
{
if (timeout == 0)
return ACE_OS::recv (handle, (char *) buf, len, flags);
else
{
int val = 0;
if (ACE::enter_recv_timedwait (handle, timeout, val) ==-1)
return -1;
else
{
ssize_t bytes_transferred =
ACE_OS::recv (handle, (char *) buf, len, flags);
ACE::restore_non_blocking_mode (handle, val);
return bytes_transferred;
}
}
}
#if defined (ACE_HAS_TLI)
ssize_t
ACE::t_rcv (ACE_HANDLE handle,
void *buf,
size_t len,
int *flags,
const ACE_Time_Value *timeout)
{
if (timeout == 0)
return ACE_OS::t_rcv (handle, (char *) buf, len, flags);
else
{
int val = 0;
if (ACE::enter_recv_timedwait (handle, timeout, val) ==-1)
return -1;
else
{
ssize_t bytes_transferred =
ACE_OS::t_rcv (handle, (char *) buf, len, flags);
ACE::restore_non_blocking_mode (handle, val);
return bytes_transferred;
}
}
}
#endif /* ACE_HAS_TLI */
ssize_t
ACE::recv (ACE_HANDLE handle,
void *buf,
size_t n,
const ACE_Time_Value *timeout)
{
if (timeout == 0)
return ACE::recv_i (handle, buf, n);
else
{
int val = 0;
if (ACE::enter_recv_timedwait (handle, timeout, val) == -1)
return -1;
else
{
ssize_t bytes_transferred = ACE::recv_i (handle, buf, n);
ACE::restore_non_blocking_mode (handle, val);
return bytes_transferred;
}
}
}
ssize_t
ACE::recvmsg (ACE_HANDLE handle,
struct msghdr *msg,
int flags,
const ACE_Time_Value *timeout)
{
if (timeout == 0)
return ACE_OS::recvmsg (handle, msg, flags);
else
{
int val = 0;
if (ACE::enter_recv_timedwait (handle, timeout, val) == -1)
return -1;
else
{
ssize_t bytes_transferred = ACE_OS::recvmsg (handle, msg, flags);
ACE::restore_non_blocking_mode (handle, val);
return bytes_transferred;
}
}
}
ssize_t
ACE::recvfrom (ACE_HANDLE handle,
char *buf,
int len,
int flags,
struct sockaddr *addr,
int *addrlen,
const ACE_Time_Value *timeout)
{
if (timeout == 0)
return ACE_OS::recvfrom (handle, buf, len, flags, addr, addrlen);
else
{
int val = 0;
if (ACE::enter_recv_timedwait (handle, timeout, val) == -1)
return -1;
else
{
ssize_t bytes_transferred =
ACE_OS::recvfrom (handle, buf, len, flags, addr, addrlen);
ACE::restore_non_blocking_mode (handle, val);
return bytes_transferred;
}
}
}
ssize_t
ACE::recv_n_i (ACE_HANDLE handle,
void *buf,
size_t len,
int flags,
size_t *bt)
{
size_t temp;
size_t &bytes_transferred = bt == 0 ? temp : *bt;
ssize_t n;
for (bytes_transferred = 0;
bytes_transferred < len;
bytes_transferred += n)
{
// Try to transfer as much of the remaining data as possible.
n = ACE_OS::recv (handle,
static_cast <char *> (buf) + bytes_transferred,
len - bytes_transferred,
flags);
// Check EOF.
if (n == 0)
return 0;
// Check for other errors.
if (n == -1)
{
// Check for possible blocking.
if (errno == EWOULDBLOCK)
{
// Wait for the blocking to subside.
int result = ACE::handle_read_ready (handle,
0);
// Did select() succeed?
if (result != -1)
{
// Blocking subsided. Continue data transfer.
n = 0;
continue;
}
}
// Other data transfer or select() failures.
return -1;
}
}
return static_cast<ssize_t> (bytes_transferred);
}
ssize_t
ACE::recv_n_i (ACE_HANDLE handle,
void *buf,
size_t len,
int flags,
const ACE_Time_Value *timeout,
size_t *bt)
{
size_t temp;
size_t &bytes_transferred = bt == 0 ? temp : *bt;
ssize_t n;
ssize_t result = 0;
int error = 0;
int val = 0;
ACE::record_and_set_non_blocking_mode (handle, val);
for (bytes_transferred = 0;
bytes_transferred < len;
bytes_transferred += n)
{
// Try to transfer as much of the remaining data as possible.
// Since the socket is in non-blocking mode, this call will not
// block.
n = ACE_OS::recv (handle,
static_cast <char *> (buf) + bytes_transferred,
len - bytes_transferred,
flags);
// Check for errors.
if (n == 0 ||
n == -1)
{
// Check for possible blocking.
if (n == -1 &&
errno == EWOULDBLOCK)
{
// Wait upto <timeout> for the blocking to subside.
int rtn = ACE::handle_read_ready (handle,
timeout);
// Did select() succeed?
if (rtn != -1)
{
// Blocking subsided in <timeout> period. Continue
// data transfer.
n = 0;
continue;
}
}
// Wait in select() timed out or other data transfer or
// select() failures.
error = 1;
result = n;
break;
}
}
ACE::restore_non_blocking_mode (handle, val);
if (error)
return result;
else
return static_cast<ssize_t> (bytes_transferred);
}
#if defined (ACE_HAS_TLI)
ssize_t
ACE::t_rcv_n_i (ACE_HANDLE handle,
void *buf,
size_t len,
int *flags,
size_t *bt)
{
size_t temp;
size_t &bytes_transferred = bt == 0 ? temp : *bt;
ssize_t n;
for (bytes_transferred = 0;
bytes_transferred < len;
bytes_transferred += n)
{
// Try to transfer as much of the remaining data as possible.
n = ACE_OS::t_rcv (handle,
(char *) buf + bytes_transferred,
len - bytes_transferred,
flags);
// Check EOF.
if (n == 0)
return 0;
// Check for other errors.
if (n == -1)
{
// Check for possible blocking.
if (errno == EWOULDBLOCK)
{
// Wait for the blocking to subside.
int result = ACE::handle_read_ready (handle,
0);
// Did select() succeed?
if (result != -1)
{
// Blocking subsided. Continue data transfer.
n = 0;
continue;
}
}
// Other data transfer or select() failures.
return -1;
}
}
return bytes_transferred;
}
ssize_t
ACE::t_rcv_n_i (ACE_HANDLE handle,
void *buf,
size_t len,
int *flags,
const ACE_Time_Value *timeout,
size_t *bt)
{
size_t temp;
size_t &bytes_transferred = bt == 0 ? temp : *bt;
ssize_t n;
ssize_t result = 0;
int error = 0;
int val = 0;
ACE::record_and_set_non_blocking_mode (handle, val);
for (bytes_transferred = 0;
bytes_transferred < len;
bytes_transferred += n)
{
// Try to transfer as much of the remaining data as possible.
// Since the socket is in non-blocking mode, this call will not
// block.
n = ACE_OS::t_rcv (handle,
(char *) buf + bytes_transferred,
len - bytes_transferred,
flags);
// Check for errors.
if (n == 0 ||
n == -1)
{
// Check for possible blocking.
if (n == -1 &&
errno == EWOULDBLOCK)
{
// Wait upto <timeout> for the blocking to subside.
int rtn = ACE::handle_read_ready (handle,
timeout);
// Did select() succeed?
if (rtn != -1)
{
// Blocking subsided in <timeout> period. Continue
// data transfer.
n = 0;
continue;
}
}
// Wait in select() timed out or other data transfer or
// select() failures.
error = 1;
result = n;
break;
}
}
ACE::restore_non_blocking_mode (handle, val);
if (error)
return result;
else
return bytes_transferred;
}
#endif /* ACE_HAS_TLI */
ssize_t
ACE::recv_n_i (ACE_HANDLE handle,
void *buf,
size_t len,
size_t *bt)
{
size_t temp;
size_t &bytes_transferred = bt == 0 ? temp : *bt;
ssize_t n;
for (bytes_transferred = 0;
bytes_transferred < len;
bytes_transferred += n)
{
// Try to transfer as much of the remaining data as possible.
n = ACE::recv_i (handle,
static_cast <char *> (buf) + bytes_transferred,
len - bytes_transferred);
// Check EOF.
if (n == 0)
{
return 0;
}
// Check for other errors.
if (n == -1)
{
// Check for possible blocking.
if (errno == EWOULDBLOCK)
{
// Wait for the blocking to subside.
int result = ACE::handle_read_ready (handle,
0);
// Did select() succeed?
if (result != -1)
{
// Blocking subsided. Continue data transfer.
n = 0;
continue;
}
}
// Other data transfer or select() failures.
return -1;
}
}
return static_cast<ssize_t> (bytes_transferred);
}
ssize_t
ACE::recv_n_i (ACE_HANDLE handle,
void *buf,
size_t len,
const ACE_Time_Value *timeout,
size_t *bt)
{
size_t temp;
size_t &bytes_transferred = bt == 0 ? temp : *bt;
ssize_t n;
ssize_t result = 0;
int error = 0;
int val = 0;
ACE::record_and_set_non_blocking_mode (handle, val);
for (bytes_transferred = 0;
bytes_transferred < len;
bytes_transferred += n)
{
// Try to transfer as much of the remaining data as possible.
// Since the socket is in non-blocking mode, this call will not
// block.
n = ACE::recv_i (handle,
static_cast <char *> (buf) + bytes_transferred,
len - bytes_transferred);
// Check for errors.
if (n == 0 ||
n == -1)
{
// Check for possible blocking.
if (n == -1 &&
errno == EWOULDBLOCK)
{
// Wait upto <timeout> for the blocking to subside.
int rtn = ACE::handle_read_ready (handle,
timeout);
// Did select() succeed?
if (rtn != -1)
{
// Blocking subsided in <timeout> period. Continue
// data transfer.
n = 0;
continue;
}
}
// Wait in select() timed out or other data transfer or
// select() failures.
error = 1;
result = n;
break;
}
}
ACE::restore_non_blocking_mode (handle, val);
if (error)
return result;
else
return static_cast<ssize_t> (bytes_transferred);
}
// This is basically an interface to ACE_OS::readv, that doesn't use
// the struct iovec explicitly. The ... can be passed as an arbitrary
// number of (char *ptr, int len) tuples. However, the count N is the
// *total* number of trailing arguments, *not* a couple of the number
// of tuple pairs!
ssize_t
ACE::recv (ACE_HANDLE handle, size_t n, ...)
{
va_list argp;
int total_tuples = static_cast<int> (n / 2);
iovec *iovp;
#if defined (ACE_HAS_ALLOCA)
iovp = (iovec *) alloca (total_tuples * sizeof (iovec));
#else
ACE_NEW_RETURN (iovp,
iovec[total_tuples],
-1);
#endif /* !defined (ACE_HAS_ALLOCA) */
va_start (argp, n);
for (int i = 0; i < total_tuples; i++)
{
iovp[i].iov_base = va_arg (argp, char *);
iovp[i].iov_len = va_arg (argp, int);
}
ssize_t result = ACE_OS::recvv (handle, iovp, total_tuples);
#if !defined (ACE_HAS_ALLOCA)
delete [] iovp;
#endif /* !defined (ACE_HAS_ALLOCA) */
va_end (argp);
return result;
}
ssize_t
ACE::recvv (ACE_HANDLE handle,
iovec *iov,
int iovcnt,
const ACE_Time_Value *timeout)
{
if (timeout == 0)
return ACE_OS::recvv (handle, iov, iovcnt);
else
{
int val = 0;
if (ACE::enter_recv_timedwait (handle, timeout, val) == -1)
return -1;
else
{
ssize_t bytes_transferred = ACE_OS::recvv (handle, iov, iovcnt);
ACE::restore_non_blocking_mode (handle, val);
return bytes_transferred;
}
}
}
ssize_t
ACE::recvv_n_i (ACE_HANDLE handle,
iovec *iov,
int iovcnt,
size_t *bt)
{
size_t temp;
size_t &bytes_transferred = bt == 0 ? temp : *bt;
bytes_transferred = 0;
for (int s = 0;
s < iovcnt;
)
{
// Try to transfer as much of the remaining data as possible.
ssize_t n = ACE_OS::recvv (handle,
iov + s,
iovcnt - s);
// Check EOF.
if (n == 0)
return 0;
// Check for other errors.
if (n == -1)
{
// Check for possible blocking.
if (errno == EWOULDBLOCK)
{
// Wait for the blocking to subside.
int result = ACE::handle_read_ready (handle,
0);
// Did select() succeed?
if (result != -1)
{
// Blocking subsided. Continue data transfer.
n = 0;
continue;
}
}
// Other data transfer or select() failures.
return -1;
}
for (bytes_transferred += n;
s < iovcnt
&& n >= static_cast<ssize_t> (iov[s].iov_len);
s++)
n -= iov[s].iov_len;
if (n != 0)
{
char *base = static_cast<char *> (iov[s].iov_base);
iov[s].iov_base = base + n;
iov[s].iov_len = iov[s].iov_len - n;
}
}
return bytes_transferred;
}
ssize_t
ACE::recvv_n_i (ACE_HANDLE handle,
iovec *iov,
int iovcnt,
const ACE_Time_Value *timeout,
size_t *bt)
{
size_t temp;
size_t &bytes_transferred = bt == 0 ? temp : *bt;
bytes_transferred = 0;
ssize_t result = 0;
int error = 0;
int val = 0;
ACE::record_and_set_non_blocking_mode (handle, val);
for (int s = 0;
s < iovcnt;
)
{
// Try to transfer as much of the remaining data as possible.
// Since the socket is in non-blocking mode, this call will not
// block.
ssize_t n = ACE_OS::recvv (handle,
iov + s,
iovcnt - s);
// Check for errors.
if (n == 0 ||
n == -1)
{
// Check for possible blocking.
if (n == -1 &&
errno == EWOULDBLOCK)
{
// Wait upto <timeout> for the blocking to subside.
int rtn = ACE::handle_read_ready (handle,
timeout);
// Did select() succeed?
if (rtn != -1)
{
// Blocking subsided in <timeout> period. Continue
// data transfer.
n = 0;
continue;
}
}
// Wait in select() timed out or other data transfer or
// select() failures.
error = 1;
result = n;
break;
}
for (bytes_transferred += n;
s < iovcnt
&& n >= static_cast<ssize_t> (iov[s].iov_len);
s++)
n -= iov[s].iov_len;
if (n != 0)
{
char *base = reinterpret_cast<char *> (iov[s].iov_base);
iov[s].iov_base = base + n;
iov[s].iov_len = iov[s].iov_len - n;
}
}
ACE::restore_non_blocking_mode (handle, val);
if (error)
return result;
else
return bytes_transferred;
}
ssize_t
ACE::recv_n (ACE_HANDLE handle,
ACE_Message_Block *message_block,
const ACE_Time_Value *timeout,
size_t *bt)
{
size_t temp;
size_t &bytes_transferred = bt == 0 ? temp : *bt;
bytes_transferred = 0;
iovec iov[ACE_IOV_MAX];
int iovcnt = 0;
while (message_block != 0)
{
// Our current message block chain.
const ACE_Message_Block *current_message_block = message_block;
while (current_message_block != 0)
{
size_t current_message_block_length =
current_message_block->length ();
char *this_rd_ptr = current_message_block->rd_ptr ();
// Check if this block has any space for incoming data.
while (current_message_block_length > 0)
{
u_long this_chunk_length;
if (current_message_block_length > ULONG_MAX)
this_chunk_length = ULONG_MAX;
else
this_chunk_length =
static_cast<u_long> (current_message_block_length);
// Collect the data in the iovec.
iov[iovcnt].iov_base = this_rd_ptr;
iov[iovcnt].iov_len = this_chunk_length;
current_message_block_length -= this_chunk_length;
this_rd_ptr += this_chunk_length;
// Increment iovec counter.
++iovcnt;
// The buffer is full make a OS call. @@ TODO find a way to
// find ACE_IOV_MAX for platforms that do not define it rather
// than simply setting ACE_IOV_MAX to some arbitrary value such
// as 16.
if (iovcnt == ACE_IOV_MAX)
{
size_t current_transfer = 0;
ssize_t result = ACE::recvv_n (handle,
iov,
iovcnt,
timeout,
¤t_transfer);
// Add to total bytes transferred.
bytes_transferred += current_transfer;
// Errors.
if (result == -1 || result == 0)
return result;
// Reset iovec counter.
iovcnt = 0;
}
}
// Select the next message block in the chain.
current_message_block = current_message_block->cont ();
}
// Selection of the next message block chain.
message_block = message_block->next ();
}
// Check for remaining buffers to be sent. This will happen when
// ACE_IOV_MAX is not a multiple of the number of message blocks.
if (iovcnt != 0)
{
size_t current_transfer = 0;
ssize_t result = ACE::recvv_n (handle,
iov,
iovcnt,
timeout,
¤t_transfer);
// Add to total bytes transferred.
bytes_transferred += current_transfer;
// Errors.
if (result == -1 || result == 0)
return result;
}
// Return total bytes transferred.
return bytes_transferred;
}
ssize_t
ACE::send (ACE_HANDLE handle,
const void *buf,
size_t n,
int flags,
const ACE_Time_Value *timeout)
{
if (timeout == 0)
return ACE_OS::send (handle, (const char *) buf, n, flags);
else
{
int val = 0;
if (ACE::enter_send_timedwait (handle, timeout, val) == -1)
return -1;
else
{
ssize_t bytes_transferred = ACE_OS::send (handle, (const char *) buf, n, flags);
ACE::restore_non_blocking_mode (handle, val);
return bytes_transferred;
}
}
}
#if defined (ACE_HAS_TLI)
ssize_t
ACE::t_snd (ACE_HANDLE handle,
const void *buf,
size_t n,
int flags,
const ACE_Time_Value *timeout)
{
if (timeout == 0)
return ACE_OS::t_snd (handle, (const char *) buf, n, flags);
else
{
int val = 0;
if (ACE::enter_send_timedwait (handle, timeout, val) == -1)
return -1;
else
{
ssize_t bytes_transferred = ACE_OS::t_snd (handle, (const char *) buf, n, flags);
ACE::restore_non_blocking_mode (handle, val);
return bytes_transferred;
}
}
}
#endif /* ACE_HAS_TLI */
ssize_t
ACE::send (ACE_HANDLE handle,
const void *buf,
size_t n,
const ACE_Time_Value *timeout)
{
if (timeout == 0)
return ACE::send_i (handle, buf, n);
else
{
int val = 0;
if (ACE::enter_send_timedwait (handle, timeout, val) == -1)
return -1;
else
{
ssize_t bytes_transferred = ACE::send_i (handle, buf, n);
ACE::restore_non_blocking_mode (handle, val);
return bytes_transferred;
}
}
}
ssize_t
ACE::sendmsg (ACE_HANDLE handle,
const struct msghdr *msg,
int flags,
const ACE_Time_Value *timeout)
{
if (timeout == 0)
return ACE_OS::sendmsg (handle, msg, flags);
else
{
int val = 0;
if (ACE::enter_send_timedwait (handle, timeout, val) == -1)
return -1;
else
{
ssize_t bytes_transferred = ACE_OS::sendmsg (handle, msg, flags);
ACE::restore_non_blocking_mode (handle, val);
return bytes_transferred;
}
}
}
ssize_t
ACE::sendto (ACE_HANDLE handle,
const char *buf,
int len,
int flags,
const struct sockaddr *addr,
int addrlen,
const ACE_Time_Value *timeout)
{
if (timeout == 0)
return ACE_OS::sendto (handle, buf, len, flags, addr, addrlen);
else
{
int val = 0;
if (ACE::enter_send_timedwait (handle, timeout, val) == -1)
return -1;
else
{
ssize_t bytes_transferred =
ACE_OS::sendto (handle, buf, len, flags, addr, addrlen);
ACE::restore_non_blocking_mode (handle, val);
return bytes_transferred;
}
}
}
ssize_t
ACE::send_n_i (ACE_HANDLE handle,
const void *buf,
size_t len,
int flags,
size_t *bt)
{
size_t temp;
size_t &bytes_transferred = bt == 0 ? temp : *bt;
ssize_t n;
for (bytes_transferred = 0;
bytes_transferred < len;
bytes_transferred += n)
{
// Try to transfer as much of the remaining data as possible.
n = ACE_OS::send (handle,
(char *) buf + bytes_transferred,
len - bytes_transferred,
flags);
// Check EOF.
if (n == 0)
return 0;
// Check for other errors.
if (n == -1)
{
// Check for possible blocking.
#if defined (ACE_WIN32)
if (errno == EWOULDBLOCK) // If enobufs no need to loop
#else
if (errno == EWOULDBLOCK || errno == ENOBUFS)
#endif /* ACE_WIN32 */
{
// Wait for the blocking to subside.
int result = ACE::handle_write_ready (handle,
0);
// Did select() succeed?
if (result != -1)
{
// Blocking subsided. Continue data transfer.
n = 0;
continue;
}
}
// Other data transfer or select() failures.
return -1;
}
}
return bytes_transferred;
}
ssize_t
ACE::send_n_i (ACE_HANDLE handle,
const void *buf,
size_t len,
int flags,
const ACE_Time_Value *timeout,
size_t *bt)
{
size_t temp;
size_t &bytes_transferred = bt == 0 ? temp : *bt;
ssize_t n;
ssize_t result = 0;
int error = 0;
int val = 0;
ACE::record_and_set_non_blocking_mode (handle, val);
for (bytes_transferred = 0;
bytes_transferred < len;
bytes_transferred += n)
{
// Try to transfer as much of the remaining data as possible.
// Since the socket is in non-blocking mode, this call will not
// block.
n = ACE_OS::send (handle,
(char *) buf + bytes_transferred,
len - bytes_transferred,
flags);
// Check for errors.
if (n == 0 ||
n == -1)
{
// Check for possible blocking.
if (n == -1 &&
errno == EWOULDBLOCK || errno == ENOBUFS)
{
// Wait upto <timeout> for the blocking to subside.
int rtn = ACE::handle_write_ready (handle,
timeout);
// Did select() succeed?
if (rtn != -1)
{
// Blocking subsided in <timeout> period. Continue
// data transfer.
n = 0;
continue;
}
}
// Wait in select() timed out or other data transfer or
// select() failures.
error = 1;
result = n;
break;
}
}
ACE::restore_non_blocking_mode (handle, val);
if (error)
return result;
else
return bytes_transferred;
}
#if defined (ACE_HAS_TLI)
ssize_t
ACE::t_snd_n_i (ACE_HANDLE handle,
const void *buf,
size_t len,
int flags,
size_t *bt)
{
size_t temp;
size_t &bytes_transferred = bt == 0 ? temp : *bt;
ssize_t n;
for (bytes_transferred = 0;
bytes_transferred < len;
bytes_transferred += n)
{
// Try to transfer as much of the remaining data as possible.
n = ACE_OS::t_snd (handle,
(char *) buf + bytes_transferred,
len - bytes_transferred,
flags);
// Check EOF.
if (n == 0)
return 0;
// Check for other errors.
if (n == -1)
{
// Check for possible blocking.
if (errno == EWOULDBLOCK || errno == ENOBUFS)
{
// Wait for the blocking to subside.
int result = ACE::handle_write_ready (handle,
0);
// Did select() succeed?
if (result != -1)
{
// Blocking subsided. Continue data transfer.
n = 0;
continue;
}
}
// Other data transfer or select() failures.
return -1;
}
}
return bytes_transferred;
}
ssize_t
ACE::t_snd_n_i (ACE_HANDLE handle,
const void *buf,
size_t len,
int flags,
const ACE_Time_Value *timeout,
size_t *bt)
{
size_t temp;
size_t &bytes_transferred = bt == 0 ? temp : *bt;
ssize_t n;
ssize_t result = 0;
int error = 0;
int val = 0;
ACE::record_and_set_non_blocking_mode (handle, val);
for (bytes_transferred = 0;
bytes_transferred < len;
bytes_transferred += n)
{
// Try to transfer as much of the remaining data as possible.
// Since the socket is in non-blocking mode, this call will not
// block.
n = ACE_OS::t_snd (handle,
(char *) buf + bytes_transferred,
len - bytes_transferred,
flags);
// Check for errors.
if (n == 0 ||
n == -1)
{
// Check for possible blocking.
if (n == -1 &&
errno == EWOULDBLOCK || errno == ENOBUFS)
{
// Wait upto <timeout> for the blocking to subside.
int rtn = ACE::handle_write_ready (handle,
timeout);
// Did select() succeed?
if (rtn != -1)
{
// Blocking subsided in <timeout> period. Continue
// data transfer.
n = 0;
continue;
}
}
// Wait in select() timed out or other data transfer or
// select() failures.
error = 1;
result = n;
break;
}
}
ACE::restore_non_blocking_mode (handle, val);
if (error)
return result;
else
return bytes_transferred;
}
#endif /* ACE_HAS_TLI */
ssize_t
ACE::send_n_i (ACE_HANDLE handle,
const void *buf,
size_t len,
size_t *bt)
{
size_t temp;
size_t &bytes_transferred = bt == 0 ? temp : *bt;
ssize_t n;
for (bytes_transferred = 0;
bytes_transferred < len;
bytes_transferred += n)
{
// Try to transfer as much of the remaining data as possible.
n = ACE::send_i (handle,
(char *) buf + bytes_transferred,
len - bytes_transferred);
// Check EOF.
if (n == 0)
return 0;
// Check for other errors.
if (n == -1)
{
// Check for possible blocking.
if (errno == EWOULDBLOCK || errno == ENOBUFS)
{
// Wait for the blocking to subside.
int result = ACE::handle_write_ready (handle,
0);
// Did select() succeed?
if (result != -1)
{
// Blocking subsided. Continue data transfer.
n = 0;
continue;
}
}
// Other data transfer or select() failures.
return -1;
}
}
return bytes_transferred;
}
ssize_t
ACE::send_n_i (ACE_HANDLE handle,
const void *buf,
size_t len,
const ACE_Time_Value *timeout,
size_t *bt)
{
size_t temp;
size_t &bytes_transferred = bt == 0 ? temp : *bt;
ssize_t n;
ssize_t result = 0;
int error = 0;
int val = 0;
ACE::record_and_set_non_blocking_mode (handle, val);
for (bytes_transferred = 0;
bytes_transferred < len;
bytes_transferred += n)
{
// Try to transfer as much of the remaining data as possible.
// Since the socket is in non-blocking mode, this call will not
// block.
n = ACE::send_i (handle,
(char *) buf + bytes_transferred,
len - bytes_transferred);
// Check for errors.
if (n == 0 ||
n == -1)
{
// Check for possible blocking.
if (n == -1 &&
errno == EWOULDBLOCK || errno == ENOBUFS)
{
// Wait upto <timeout> for the blocking to subside.
int rtn = ACE::handle_write_ready (handle,
timeout);
// Did select() succeed?
if (rtn != -1)
{
// Blocking subsided in <timeout> period. Continue
// data transfer.
n = 0;
continue;
}
}
// Wait in select() timed out or other data transfer or
// select() failures.
error = 1;
result = n;
break;
}
}
ACE::restore_non_blocking_mode (handle, val);
if (error)
return result;
else
return bytes_transferred;
}
// Send N char *ptrs and int lengths. Note that the char *'s precede
// the ints (basically, an varargs version of writev). The count N is
// the *total* number of trailing arguments, *not* a couple of the
// number of tuple pairs!
ssize_t
ACE::send (ACE_HANDLE handle, size_t n, ...)
{
va_list argp;
int total_tuples = static_cast<int> (n / 2);
iovec *iovp;
#if defined (ACE_HAS_ALLOCA)
iovp = (iovec *) alloca (total_tuples * sizeof (iovec));
#else
ACE_NEW_RETURN (iovp,
iovec[total_tuples],
-1);
#endif /* !defined (ACE_HAS_ALLOCA) */
va_start (argp, n);
for (int i = 0; i < total_tuples; i++)
{
iovp[i].iov_base = va_arg (argp, char *);
iovp[i].iov_len = va_arg (argp, int);
}
ssize_t result = ACE_OS::sendv (handle, iovp, total_tuples);
#if !defined (ACE_HAS_ALLOCA)
delete [] iovp;
#endif /* !defined (ACE_HAS_ALLOCA) */
va_end (argp);
return result;
}
ssize_t
ACE::sendv (ACE_HANDLE handle,
const iovec *iov,
int iovcnt,
const ACE_Time_Value *timeout)
{
if (timeout == 0)
return ACE_OS::sendv (handle, iov, iovcnt);
else
{
int val = 0;
if (ACE::enter_send_timedwait (handle, timeout, val) == -1)
return -1;
else
{
ssize_t bytes_transferred = ACE_OS::sendv (handle, iov, iovcnt);
ACE::restore_non_blocking_mode (handle, val);
return bytes_transferred;
}
}
}
ssize_t
ACE::sendv_n_i (ACE_HANDLE handle,
const iovec *i,
int iovcnt,
size_t *bt)
{
size_t temp;
size_t &bytes_transferred = bt == 0 ? temp : *bt;
bytes_transferred = 0;
iovec *iov = const_cast<iovec *> (i);
for (int s = 0;
s < iovcnt;
)
{
// Try to transfer as much of the remaining data as possible.
ssize_t n = ACE_OS::sendv (handle,
iov + s,
iovcnt - s);
// Check EOF.
if (n == 0)
return 0;
// Check for other errors.
if (n == -1)
{
// Check for possible blocking.
if (errno == EWOULDBLOCK || errno == ENOBUFS)
{
// Wait for the blocking to subside.
int result = ACE::handle_write_ready (handle,
0);
// Did select() succeed?
if (result != -1)
{
// Blocking subsided. Continue data transfer.
n = 0;
continue;
}
}
// Other data transfer or select() failures.
return -1;
}
for (bytes_transferred += n;
s < iovcnt
&& n >= static_cast<ssize_t> (iov[s].iov_len);
s++)
n -= iov[s].iov_len;
if (n != 0)
{
char *base = reinterpret_cast<char *> (iov[s].iov_base);
iov[s].iov_base = base + n;
iov[s].iov_len = iov[s].iov_len - n;
}
}
return bytes_transferred;
}
ssize_t
ACE::sendv_n_i (ACE_HANDLE handle,
const iovec *i,
int iovcnt,
const ACE_Time_Value *timeout,
size_t *bt)
{
size_t temp;
size_t &bytes_transferred = bt == 0 ? temp : *bt;
bytes_transferred = 0;
ssize_t result = 0;
int error = 0;
int val = 0;
ACE::record_and_set_non_blocking_mode (handle, val);
iovec *iov = const_cast<iovec *> (i);
for (int s = 0;
s < iovcnt;
)
{
// Try to transfer as much of the remaining data as possible.
// Since the socket is in non-blocking mode, this call will not
// block.
ssize_t n = ACE_OS::sendv (handle,
iov + s,
iovcnt - s);
// Check for errors.
if (n == 0 ||
n == -1)
{
// Check for possible blocking.
if (n == -1 &&
errno == EWOULDBLOCK || errno == ENOBUFS)
{
// Wait upto <timeout> for the blocking to subside.
int rtn = ACE::handle_write_ready (handle,
timeout);
// Did select() succeed?
if (rtn != -1)
{
// Blocking subsided in <timeout> period. Continue
// data transfer.
n = 0;
continue;
}
}
// Wait in select() timed out or other data transfer or
// select() failures.
error = 1;
result = n;
break;
}
for (bytes_transferred += n;
s < iovcnt
&& n >= static_cast<ssize_t> (iov[s].iov_len);
s++)
n -= iov[s].iov_len;
if (n != 0)
{
char *base = reinterpret_cast<char *> (iov[s].iov_base);
iov[s].iov_base = base + n;
iov[s].iov_len = iov[s].iov_len - n;
}
}
ACE::restore_non_blocking_mode (handle, val);
if (error)
return result;
else
return bytes_transferred;
}
ssize_t
ACE::write_n (ACE_HANDLE handle,
const ACE_Message_Block *message_block,
size_t *bt)
{
size_t temp;
size_t &bytes_transferred = bt == 0 ? temp : *bt;
bytes_transferred = 0;
iovec iov[ACE_IOV_MAX];
int iovcnt = 0;
while (message_block != 0)
{
// Our current message block chain.
const ACE_Message_Block *current_message_block = message_block;
while (current_message_block != 0)
{
size_t current_message_block_length =
current_message_block->length ();
char *this_block_ptr = current_message_block->rd_ptr ();
// Check if this block has any data to be sent.
while (current_message_block_length > 0)
{
u_long this_chunk_length;
if (current_message_block_length > ULONG_MAX)
this_chunk_length = ULONG_MAX;
else
this_chunk_length =
static_cast<u_long> (current_message_block_length);
// Collect the data in the iovec.
iov[iovcnt].iov_base = this_block_ptr;
iov[iovcnt].iov_len = this_chunk_length;
current_message_block_length -= this_chunk_length;
this_block_ptr += this_chunk_length;
// Increment iovec counter.
++iovcnt;
// The buffer is full make a OS call. @@ TODO find a way to
// find ACE_IOV_MAX for platforms that do not define it rather
// than simply setting ACE_IOV_MAX to some arbitrary value such
// as 16.
if (iovcnt == ACE_IOV_MAX)
{
size_t current_transfer = 0;
ssize_t result = ACE::writev_n (handle,
iov,
iovcnt,
¤t_transfer);
// Add to total bytes transferred.
bytes_transferred += current_transfer;
// Errors.
if (result == -1 || result == 0)
return result;
// Reset iovec counter.
iovcnt = 0;
}
}
// Select the next message block in the chain.
current_message_block = current_message_block->cont ();
}
// Selection of the next message block chain.
message_block = message_block->next ();
}
// Check for remaining buffers to be sent. This will happen when
// ACE_IOV_MAX is not a multiple of the number of message blocks.
if (iovcnt != 0)
{
size_t current_transfer = 0;
ssize_t result = ACE::writev_n (handle,
iov,
iovcnt,
¤t_transfer);
// Add to total bytes transferred.
bytes_transferred += current_transfer;
// Errors.
if (result == -1 || result == 0)
return result;
}
// Return total bytes transferred.
return bytes_transferred;
}
ssize_t
ACE::send_n (ACE_HANDLE handle,
const ACE_Message_Block *message_block,
const ACE_Time_Value *timeout,
size_t *bt)
{
size_t temp;
size_t &bytes_transferred = bt == 0 ? temp : *bt;
bytes_transferred = 0;
iovec iov[ACE_IOV_MAX];
int iovcnt = 0;
while (message_block != 0)
{
// Our current message block chain.
const ACE_Message_Block *current_message_block = message_block;
while (current_message_block != 0)
{
char *this_block_ptr = current_message_block->rd_ptr ();
size_t current_message_block_length =
current_message_block->length ();
// Check if this block has any data to be sent.
while (current_message_block_length > 0)
{
u_long this_chunk_length;
if (current_message_block_length > ULONG_MAX)
this_chunk_length = ULONG_MAX;
else
this_chunk_length =
static_cast<u_long> (current_message_block_length);
// Collect the data in the iovec.
iov[iovcnt].iov_base = this_block_ptr;
iov[iovcnt].iov_len = this_chunk_length;
current_message_block_length -= this_chunk_length;
this_block_ptr += this_chunk_length;
// Increment iovec counter.
++iovcnt;
// The buffer is full make a OS call. @@ TODO find a way to
// find ACE_IOV_MAX for platforms that do not define it rather
// than simply setting ACE_IOV_MAX to some arbitrary value such
// as 16.
if (iovcnt == ACE_IOV_MAX)
{
size_t current_transfer = 0;
ssize_t result = ACE::sendv_n (handle,
iov,
iovcnt,
timeout,
¤t_transfer);
// Add to total bytes transferred.
bytes_transferred += current_transfer;
// Errors.
if (result == -1 || result == 0)
return result;
// Reset iovec counter.
iovcnt = 0;
}
}
// Select the next message block in the chain.
current_message_block = current_message_block->cont ();
}
// Selection of the next message block chain.
message_block = message_block->next ();
}
// Check for remaining buffers to be sent. This will happen when
// ACE_IOV_MAX is not a multiple of the number of message blocks.
if (iovcnt != 0)
{
size_t current_transfer = 0;
ssize_t result = ACE::sendv_n (handle,
iov,
iovcnt,
timeout,
¤t_transfer);
// Add to total bytes transferred.
bytes_transferred += current_transfer;
// Errors.
if (result == -1 || result == 0)
return result;
}
// Return total bytes transferred.
return bytes_transferred;
}
ssize_t
ACE::readv_n (ACE_HANDLE handle,
iovec *iov,
int iovcnt,
size_t *bt)
{
size_t temp;
size_t &bytes_transferred = bt == 0 ? temp : *bt;
bytes_transferred = 0;
for (int s = 0;
s < iovcnt;
)
{
ssize_t n = ACE_OS::readv (handle,
iov + s,
iovcnt - s);
if (n == -1 || n == 0)
return n;
for (bytes_transferred += n;
s < iovcnt
&& n >= static_cast<ssize_t> (iov[s].iov_len);
s++)
n -= iov[s].iov_len;
if (n != 0)
{
char *base = reinterpret_cast<char *> (iov[s].iov_base);
iov[s].iov_base = base + n;
iov[s].iov_len = iov[s].iov_len - n;
}
}
return bytes_transferred;
}
ssize_t
ACE::writev_n (ACE_HANDLE handle,
const iovec *i,
int iovcnt,
size_t *bt)
{
size_t temp;
size_t &bytes_transferred = bt == 0 ? temp : *bt;
bytes_transferred = 0;
iovec *iov = const_cast<iovec *> (i);
for (int s = 0;
s < iovcnt;
)
{
ssize_t n = ACE_OS::writev (handle,
iov + s,
iovcnt - s);
if (n == -1 || n == 0)
return n;
for (bytes_transferred += n;
s < iovcnt
&& n >= static_cast<ssize_t> (iov[s].iov_len);
s++)
n -= iov[s].iov_len;
if (n != 0)
{
char *base = reinterpret_cast<char *> (iov[s].iov_base);
iov[s].iov_base = base + n;
iov[s].iov_len = iov[s].iov_len - n;
}
}
return bytes_transferred;
}
int
ACE::handle_ready (ACE_HANDLE handle,
const ACE_Time_Value *timeout,
int read_ready,
int write_ready,
int exception_ready)
{
#if defined (ACE_HAS_POLL) && defined (ACE_HAS_LIMITED_SELECT)
ACE_UNUSED_ARG (write_ready);
ACE_UNUSED_ARG (exception_ready);
struct pollfd fds;
fds.fd = handle;
fds.events = read_ready ? POLLIN : POLLOUT;
fds.revents = 0;
int result = ACE_OS::poll (&fds, 1, timeout);
#else
ACE_Handle_Set handle_set;
handle_set.set_bit (handle);
// Wait for data or for the timeout to elapse.
int select_width;
# if defined (ACE_WIN32)
// This arg is ignored on Windows and causes pointer truncation
// warnings on 64-bit compiles.
select_width = 0;
# else
select_width = int (handle) + 1;
# endif /* ACE_WIN64 */
int result = ACE_OS::select (select_width,
read_ready ? handle_set.fdset () : 0, // read_fds.
write_ready ? handle_set.fdset () : 0, // write_fds.
exception_ready ? handle_set.fdset () : 0, // exception_fds.
timeout);
#endif /* ACE_HAS_POLL && ACE_HAS_LIMITED_SELECT */
switch (result)
{
case 0: // Timer expired.
errno = ETIME;
/* FALLTHRU */
case -1: // we got here directly - select() returned -1.
return -1;
case 1: // Handle has data.
/* FALLTHRU */
default: // default is case result > 0; return a
// ACE_ASSERT (result == 1);
return result;
}
}
int
ACE::enter_recv_timedwait (ACE_HANDLE handle,
const ACE_Time_Value *timeout,
int &val)
{
int result = ACE::handle_read_ready (handle,
timeout);
if (result == -1)
return -1;
ACE::record_and_set_non_blocking_mode (handle,
val);
return result;
}
int
ACE::enter_send_timedwait (ACE_HANDLE handle,
const ACE_Time_Value *timeout,
int &val)
{
int result = ACE::handle_write_ready (handle,
timeout);
if (result == -1)
return -1;
ACE::record_and_set_non_blocking_mode (handle,
val);
return result;
}
void
ACE::record_and_set_non_blocking_mode (ACE_HANDLE handle,
int &val)
{
// We need to record whether we are already *in* nonblocking mode,
// so that we can correctly reset the state when we're done.
val = ACE::get_flags (handle);
if (ACE_BIT_DISABLED (val, ACE_NONBLOCK))
// Set the handle into non-blocking mode if it's not already in
// it.
ACE::set_flags (handle, ACE_NONBLOCK);
}
void
ACE::restore_non_blocking_mode (ACE_HANDLE handle,
int val)
{
if (ACE_BIT_DISABLED (val,
ACE_NONBLOCK))
{
// Save/restore errno.
ACE_Errno_Guard error (errno);
// Only disable ACE_NONBLOCK if we weren't in non-blocking mode
// originally.
ACE::clr_flags (handle, ACE_NONBLOCK);
}
}
// Format buffer into printable format. This is useful for debugging.
// Portions taken from mdump by J.P. Knight (J.P.Knight@lut.ac.uk)
// Modifications by Todd Montgomery.
size_t
ACE::format_hexdump (const char *buffer,
size_t size,
ACE_TCHAR *obuf,
size_t obuf_sz)
{
ACE_TRACE ("ACE::format_hexdump");
u_char c;
ACE_TCHAR textver[16 + 1];
// We can fit 16 bytes output in text mode per line, 4 chars per byte.
size_t maxlen = (obuf_sz / 68) * 16;
if (size > maxlen)
size = maxlen;
size_t i;
size_t lines = size / 16;
for (i = 0; i < lines; i++)
{
size_t j;
for (j = 0 ; j < 16; j++)
{
c = (u_char) buffer[(i << 4) + j]; // or, buffer[i*16+j]
ACE_OS::sprintf (obuf,
ACE_TEXT ("%02x "),
c);
obuf += 3;
if (j == 7)
{
ACE_OS::sprintf (obuf,
ACE_TEXT (" "));
++obuf;
}
textver[j] = ACE_OS::ace_isprint (c) ? c : '.';
}
textver[j] = 0;
ACE_OS::sprintf (obuf,
ACE_TEXT (" %s\n"),
textver);
while (*obuf != '\0')
++obuf;
}
if (size % 16)
{
for (i = 0 ; i < size % 16; i++)
{
c = (u_char) buffer[size - size % 16 + i];
ACE_OS::sprintf (obuf,
ACE_TEXT ("%02x "),
c);
obuf += 3;
if (i == 7)
{
ACE_OS::sprintf (obuf,
ACE_TEXT (" "));
++obuf;
}
textver[i] = ACE_OS::ace_isprint (c) ? c : '.';
}
for (i = size % 16; i < 16; i++)
{
ACE_OS::sprintf (obuf,
ACE_TEXT (" "));
obuf += 3;
if (i == 7)
{
ACE_OS::sprintf (obuf,
ACE_TEXT (" "));
++obuf;
}
textver[i] = ' ';
}
textver[i] = 0;
ACE_OS::sprintf (obuf,
ACE_TEXT (" %s\n"),
textver);
}
return size;
}
// Returns the current timestamp in the form
// "hour:minute:second:microsecond." The month, day, and year are
// also stored in the beginning of the date_and_time array.
ACE_TCHAR *
ACE::timestamp (ACE_TCHAR date_and_time[],
int date_and_timelen,
int return_pointer_to_first_digit)
{
//ACE_TRACE ("ACE::timestamp");
if (date_and_timelen < 35)
{
errno = EINVAL;
return 0;
}
#if defined (WIN32)
// Emulate Unix. Win32 does NOT support all the UNIX versions
// below, so DO we need this ifdef.
static const ACE_TCHAR *day_of_week_name[] =
{
ACE_TEXT ("Sun"),
ACE_TEXT ("Mon"),
ACE_TEXT ("Tue"),
ACE_TEXT ("Wed"),
ACE_TEXT ("Thu"),
ACE_TEXT ("Fri"),
ACE_TEXT ("Sat")
};
static const ACE_TCHAR *month_name[] =
{
ACE_TEXT ("Jan"),
ACE_TEXT ("Feb"),
ACE_TEXT ("Mar"),
ACE_TEXT ("Apr"),
ACE_TEXT ("May"),
ACE_TEXT ("Jun"),
ACE_TEXT ("Jul"),
ACE_TEXT ("Aug"),
ACE_TEXT ("Sep"),
ACE_TEXT ("Oct"),
ACE_TEXT ("Nov"),
ACE_TEXT ("Dec")
};
SYSTEMTIME local;
::GetLocalTime (&local);
ACE_OS::sprintf (date_and_time,
ACE_TEXT ("%3s %3s %2d %04d %02d:%02d:%02d.%06d"),
day_of_week_name[local.wDayOfWeek],
month_name[local.wMonth - 1],
(int) local.wDay,
(int) local.wYear,
(int) local.wHour,
(int) local.wMinute,
(int) local.wSecond,
(int) (local.wMilliseconds * 1000));
return &date_and_time[15 + (return_pointer_to_first_digit != 0)];
#else /* UNIX */
ACE_TCHAR timebuf[26]; // This magic number is based on the ctime(3c) man page.
ACE_Time_Value cur_time = ACE_OS::gettimeofday ();
time_t secs = cur_time.sec ();
ACE_OS::ctime_r (&secs,
timebuf,
sizeof timebuf);
// date_and_timelen > sizeof timebuf!
ACE_OS::strsncpy (date_and_time,
timebuf,
date_and_timelen);
ACE_TCHAR yeartmp[5];
ACE_OS::strsncpy (yeartmp,
&date_and_time[20],
5);
ACE_TCHAR timetmp[9];
ACE_OS::strsncpy (timetmp,
&date_and_time[11],
9);
ACE_OS::sprintf (&date_and_time[11],
# if defined (ACE_USES_WCHAR)
ACE_TEXT ("%ls %ls.%06ld"),
# else
ACE_TEXT ("%s %s.%06ld"),
# endif /* ACE_USES_WCHAR */
yeartmp,
timetmp,
cur_time.usec ());
date_and_time[33] = '\0';
return &date_and_time[15 + (return_pointer_to_first_digit != 0)];
#endif /* WIN32 */
}
// This function rounds the request to a multiple of the page size.
size_t
ACE::round_to_pagesize (size_t len)
{
ACE_TRACE ("ACE::round_to_pagesize");
if (ACE::pagesize_ == 0)
ACE::pagesize_ = ACE_OS::getpagesize ();
return (len + (ACE::pagesize_ - 1)) & ~(ACE::pagesize_ - 1);
}
size_t
ACE::round_to_allocation_granularity (size_t len)
{
ACE_TRACE ("ACE::round_to_allocation_granularity");
if (ACE::allocation_granularity_ == 0)
ACE::allocation_granularity_ = ACE_OS::allocation_granularity ();
return (len + (ACE::allocation_granularity_ - 1)) & ~(ACE::allocation_granularity_ - 1);
}
ACE_HANDLE
ACE::handle_timed_complete (ACE_HANDLE h,
const ACE_Time_Value *timeout,
int is_tli)
{
ACE_TRACE ("ACE::handle_timed_complete");
#if !defined (ACE_WIN32) && defined (ACE_HAS_POLL) && defined (ACE_HAS_LIMITED_SELECT)
struct pollfd fds;
fds.fd = h;
fds.events = POLLIN | POLLOUT;
fds.revents = 0;
#else
ACE_Handle_Set rd_handles;
ACE_Handle_Set wr_handles;
rd_handles.set_bit (h);
wr_handles.set_bit (h);
#endif /* !ACE_WIN32 && ACE_HAS_POLL && ACE_HAS_LIMITED_SELECT */
#if defined (ACE_WIN32)
// Winsock is different - it sets the exception bit for failed connect,
// unlike other platforms, where the read bit is set.
ACE_Handle_Set ex_handles;
ex_handles.set_bit (h);
#endif /* ACE_WIN32 */
bool need_to_check = false;
bool known_failure = false;
#if defined (ACE_WIN32)
int n = ACE_OS::select (0, // Ignored on Windows: int (h) + 1,
0,
wr_handles,
ex_handles,
timeout);
#else
# if defined (ACE_HAS_POLL) && defined (ACE_HAS_LIMITED_SELECT)
int n = ACE_OS::poll (&fds, 1, timeout);
# else
int n = ACE_OS::select (int (h) + 1,
rd_handles,
wr_handles,
0,
timeout);
# endif /* ACE_HAS_POLL && ACE_HAS_LIMITED_SELECT */
#endif /* ACE_WIN32 */
// If we failed to connect within the time period allocated by the
// caller, then we fail (e.g., the remote host might have been too
// busy to accept our call).
if (n <= 0)
{
if (n == 0 && timeout != 0)
errno = ETIME;
return ACE_INVALID_HANDLE;
}
// Usually, a ready-for-write handle is successfully connected, and
// ready-for-read (exception on Win32) is a failure. On fails, we
// need to grab the error code via getsockopt. On possible success for
// any platform where we can't tell just from select() (e.g. AIX),
// we also need to check for success/fail.
#if defined (ACE_WIN32)
ACE_UNUSED_ARG (is_tli);
// On Win32, ex_handle set indicates a failure. We'll do the check
// to try and get an errno value, but the connect failed regardless of
// what getsockopt says about the error.
if (ex_handles.is_set (h))
{
need_to_check = true;
known_failure = true;
}
#elif defined (ACE_VXWORKS)
ACE_UNUSED_ARG (is_tli);
// Force the check on VxWorks. The read handle for "h" is not set,
// so "need_to_check" is false at this point. The write handle is
// set, for what it's worth.
need_to_check = true;
#else
if (is_tli)
# if defined (ACE_HAS_POLL) && defined (ACE_HAS_LIMITED_SELECT)
need_to_check = (fds.revents & POLLIN) && !(fds.revents & POLLOUT);
# else
need_to_check = rd_handles.is_set (h) && !wr_handles.is_set (h);
# endif /* ACE_HAS_POLL && ACE_HAS_LIMITED_SELECT */
else
#if defined(AIX)
// AIX is broken... both success and failed connect will set the
// write handle only, so always check.
need_to_check = true;
#else
# if defined (ACE_HAS_POLL) && defined (ACE_HAS_LIMITED_SELECT)
need_to_check = (fds.revents & POLLIN);
# else
need_to_check = rd_handles.is_set (h);
# endif /* ACE_HAS_POLL && ACE_HAS_LIMITED_SELECT */
#endif /* AIX */
#endif /* ACE_WIN32 */
if (need_to_check)
{
#if defined (SOL_SOCKET) && defined (SO_ERROR)
int sock_err = 0;
int sock_err_len = sizeof (sock_err);
int sockopt_ret = ACE_OS::getsockopt (h, SOL_SOCKET, SO_ERROR,
(char *)&sock_err, &sock_err_len);
if (sockopt_ret < 0)
{
h = ACE_INVALID_HANDLE;
}
if (sock_err != 0 || known_failure)
{
h = ACE_INVALID_HANDLE;
errno = sock_err;
}
#else
char dummy;
// The following recv() won't block provided that the
// ACE_NONBLOCK flag has not been turned off .
n = ACE::recv (h, &dummy, 1, MSG_PEEK);
// If no data was read/peeked at, check to see if it's because
// of a non-connected socket (and therefore an error) or there's
// just no data yet.
if (n <= 0)
{
if (n == 0)
{
errno = ECONNREFUSED;
h = ACE_INVALID_HANDLE;
}
else if (errno != EWOULDBLOCK && errno != EAGAIN)
h = ACE_INVALID_HANDLE;
}
#endif
}
// 1. The HANDLE is ready for writing and doesn't need to be checked or
// 2. recv() returned an indication of the state of the socket - if there is
// either data present, or a recv is legit but there's no data yet,
// the connection was successfully established.
return h;
}
// Wait up to <timeout> amount of time to accept a connection.
int
ACE::handle_timed_accept (ACE_HANDLE listener,
ACE_Time_Value *timeout,
int restart)
{
ACE_TRACE ("ACE::handle_timed_accept");
// Make sure we don't bomb out on erroneous values.
if (listener == ACE_INVALID_HANDLE)
return -1;
#if defined (ACE_HAS_POLL) && defined (ACE_HAS_LIMITED_SELECT)
struct pollfd fds;
fds.fd = listener;
fds.events = POLLIN;
fds.revents = 0;
#else
// Use the select() implementation rather than poll().
ACE_Handle_Set rd_handle;
rd_handle.set_bit (listener);
#endif /* ACE_HAS_POLL && ACE_HAS_LIMITED_SELECT */
// We need a loop here if <restart> is enabled.
for (;;)
{
#if defined (ACE_HAS_POLL) && defined (ACE_HAS_LIMITED_SELECT)
int n = ACE_OS::poll (&fds, 1, timeout);
#else
int select_width;
# if defined (ACE_WIN32)
// This arg is ignored on Windows and causes pointer truncation
// warnings on 64-bit compiles.
select_width = 0;
# else
select_width = int (listener) + 1;
# endif /* ACE_WIN32 */
int n = ACE_OS::select (select_width,
rd_handle, 0, 0,
timeout);
#endif /* ACE_HAS_POLL && ACE_HAS_LIMITED_SELECT */
switch (n)
{
case -1:
if (errno == EINTR && restart)
continue;
else
return -1;
/* NOTREACHED */
case 0:
if (timeout != 0
&& timeout->sec () == 0
&& timeout->usec () == 0)
errno = EWOULDBLOCK;
else
errno = ETIMEDOUT;
return -1;
/* NOTREACHED */
case 1:
return 0;
/* NOTREACHED */
default:
errno = EINVAL;
return -1;
/* NOTREACHED */
}
}
}
// Make the current process a UNIX daemon. This is based on Stevens
// code from APUE.
int
ACE::daemonize (const ACE_TCHAR pathname[],
bool close_all_handles,
const ACE_TCHAR program_name[])
{
ACE_TRACE ("ACE::daemonize");
#if !defined (ACE_LACKS_FORK)
pid_t pid = ACE_OS::fork ();
if (pid == -1)
return -1;
else if (pid != 0)
ACE_OS::exit (0); // Parent exits.
// 1st child continues.
ACE_OS::setsid (); // Become session leader.
ACE_OS::signal (SIGHUP, SIG_IGN);
pid = ACE_OS::fork (program_name);
if (pid != 0)
ACE_OS::exit (0); // First child terminates.
// Second child continues.
if (pathname != 0)
// change working directory.
ACE_OS::chdir (pathname);
ACE_OS::umask (0); // clear our file mode creation mask.
// Close down the I/O handles.
if (close_all_handles)
for (int i = ACE::max_handles () - 1; i >= 0; i--)
ACE_OS::close (i);
return 0;
#else
ACE_UNUSED_ARG (pathname);
ACE_UNUSED_ARG (close_all_handles);
ACE_UNUSED_ARG (program_name);
ACE_NOTSUP_RETURN (-1);
#endif /* ACE_LACKS_FORK */
}
pid_t
ACE::fork (const ACE_TCHAR *program_name,
int avoid_zombies)
{
if (avoid_zombies == 0)
return ACE_OS::fork (program_name);
else
{
// This algorithm is adapted from an example in the Stevens book
// "Advanced Programming in the Unix Environment" and an item in
// Andrew Gierth's Unix Programming FAQ. It creates an orphan
// process that's inherited by the init process; init cleans up
// when the orphan process terminates.
//
// Another way to avoid zombies is to ignore or catch the
// SIGCHLD signal; we don't use that approach here.
pid_t pid = ACE_OS::fork ();
if (pid == 0)
{
// The child process forks again to create a grandchild.
switch (ACE_OS::fork (program_name))
{
case 0: // grandchild returns 0.
return 0;
case -1: // assumes all errnos are < 256
ACE_OS::_exit (errno);
default: // child terminates, orphaning grandchild
ACE_OS::_exit (0);
}
}
// Parent process waits for child to terminate.
ACE_exitcode status;
if (pid < 0 || ACE_OS::waitpid (pid, &status, 0) < 0)
return -1;
// child terminated by calling exit()?
if (WIFEXITED ((status)))
{
// child terminated normally?
if (WEXITSTATUS ((status)) == 0)
return 1;
else
errno = WEXITSTATUS ((status));
}
else
// child didn't call exit(); perhaps it received a signal?
errno = EINTR;
return -1;
}
}
int
ACE::max_handles (void)
{
ACE_TRACE ("ACE::max_handles");
#if defined (RLIMIT_NOFILE) && !defined (ACE_LACKS_RLIMIT)
rlimit rl;
int r = ACE_OS::getrlimit (RLIMIT_NOFILE, &rl);
# if !defined (RLIM_INFINITY)
if (r == 0)
return rl.rlim_cur;
#else
if (r == 0 && rl.rlim_cur != RLIM_INFINITY)
return rl.rlim_cur;
// If == RLIM_INFINITY, fall through to the ACE_LACKS_RLIMIT sections
# endif /* RLIM_INFINITY */
#endif /* RLIMIT_NOFILE && !ACE_LACKS_RLIMIT */
#if defined (_SC_OPEN_MAX)
return ACE_OS::sysconf (_SC_OPEN_MAX);
#elif defined (ACE_VXWORKS) && (ACE_VXWORKS < 0x620)
return maxFiles;
#elif defined (FD_SETSIZE)
return FD_SETSIZE;
#else
ACE_NOTSUP_RETURN (-1);
#endif /* _SC_OPEN_MAX */
}
// Set the number of currently open handles in the process.
//
// If NEW_LIMIT == -1 set the limit to the maximum allowable.
// Otherwise, set it to be the value of NEW_LIMIT.
int
ACE::set_handle_limit (int new_limit,
int increase_limit_only)
{
ACE_TRACE ("ACE::set_handle_limit");
int cur_limit = ACE::max_handles ();
int max_limit = cur_limit;
if (cur_limit == -1)
return -1;
#if !defined (ACE_LACKS_RLIMIT) && defined (RLIMIT_NOFILE)
struct rlimit rl;
ACE_OS::memset ((void *) &rl, 0, sizeof rl);
int r = ACE_OS::getrlimit (RLIMIT_NOFILE, &rl);
if (r == 0)
max_limit = rl.rlim_max;
#endif /* ACE_LACKS_RLIMIT */
if (new_limit == -1)
new_limit = max_limit;
if (new_limit < 0)
{
errno = EINVAL;
return -1;
}
else if (new_limit > cur_limit)
{
// Increase the limit.
#if !defined (ACE_LACKS_RLIMIT) && defined (RLIMIT_NOFILE)
rl.rlim_cur = new_limit;
return ACE_OS::setrlimit (RLIMIT_NOFILE, &rl);
#else
// Must return EINVAL errno.
ACE_NOTSUP_RETURN (-1);
#endif /* ACE_LACKS_RLIMIT */
}
else if (increase_limit_only == 0)
{
// Decrease the limit.
#if !defined (ACE_LACKS_RLIMIT) && defined (RLIMIT_NOFILE)
rl.rlim_cur = new_limit;
return ACE_OS::setrlimit (RLIMIT_NOFILE, &rl);
#else
// We give a chance to platforms without RLIMIT to work.
// Instead of ACE_NOTSUP_RETURN (0), just return 0 because
// new_limit is <= cur_limit, so it's a no-op.
return 0;
#endif /* ACE_LACKS_RLIMIT */
}
return 0;
}
// Euclid's greatest common divisor algorithm.
u_long
ACE::gcd (u_long x, u_long y)
{
while (y != 0)
{
u_long r = x % y;
x = y;
y = r;
}
return x;
}
// Calculates the minimum enclosing frame size for the given values.
u_long
ACE::minimum_frame_size (u_long period1, u_long period2)
{
// if one of the periods is zero, treat it as though it as
// uninitialized and return the other period as the frame size
if (0 == period1)
{
return period2;
}
if (0 == period2)
{
return period1;
}
// if neither is zero, find the greatest common divisor of the two periods
u_long greatest_common_divisor = ACE::gcd (period1, period2);
// explicitly consider cases to reduce risk of possible overflow errors
if (greatest_common_divisor == 1)
{
// periods are relative primes: just multiply them together
return period1 * period2;
}
else if (greatest_common_divisor == period1)
{
// the first period divides the second: return the second
return period2;
}
else if (greatest_common_divisor == period2)
{
// the second period divides the first: return the first
return period1;
}
else
{
// the current frame size and the entry's effective period
// have a non-trivial greatest common divisor: return the
// product of factors divided by those in their gcd.
return (period1 * period2) / greatest_common_divisor;
}
}
u_long
ACE::is_prime (const u_long n,
const u_long min_factor,
const u_long max_factor)
{
if (n > 3)
for (u_long factor = min_factor;
factor <= max_factor;
++factor)
if (n / factor * factor == n)
return factor;
return 0;
}
const ACE_TCHAR *
ACE::sock_error (int error)
{
#if defined (ACE_WIN32)
static ACE_TCHAR unknown_msg[64];
switch (error)
{
case WSAVERNOTSUPPORTED:
return ACE_TEXT ("version of WinSock not supported");
/* NOTREACHED */
case WSASYSNOTREADY:
return ACE_TEXT ("WinSock not present or not responding");
/* NOTREACHED */
case WSAEINVAL:
return ACE_TEXT ("app version not supported by DLL");
/* NOTREACHED */
case WSAHOST_NOT_FOUND:
return ACE_TEXT ("Authoritive: Host not found");
/* NOTREACHED */
case WSATRY_AGAIN:
return ACE_TEXT ("Non-authoritive: host not found or server failure");
/* NOTREACHED */
case WSANO_RECOVERY:
return ACE_TEXT ("Non-recoverable: refused or not implemented");
/* NOTREACHED */
case WSANO_DATA:
return ACE_TEXT ("Valid name, no data record for type");
/* NOTREACHED */
/*
case WSANO_ADDRESS:
return "Valid name, no MX record";
*/
case WSANOTINITIALISED:
return ACE_TEXT ("WSA Startup not initialized");
/* NOTREACHED */
case WSAENETDOWN:
return ACE_TEXT ("Network subsystem failed");
/* NOTREACHED */
case WSAEINPROGRESS:
return ACE_TEXT ("Blocking operation in progress");
/* NOTREACHED */
case WSAEINTR:
return ACE_TEXT ("Blocking call cancelled");
/* NOTREACHED */
case WSAEAFNOSUPPORT:
return ACE_TEXT ("address family not supported");
/* NOTREACHED */
case WSAEMFILE:
return ACE_TEXT ("no file handles available");
/* NOTREACHED */
case WSAENOBUFS:
return ACE_TEXT ("no buffer space available");
/* NOTREACHED */
case WSAEPROTONOSUPPORT:
return ACE_TEXT ("specified protocol not supported");
/* NOTREACHED */
case WSAEPROTOTYPE:
return ACE_TEXT ("protocol wrong type for this socket");
/* NOTREACHED */
case WSAESOCKTNOSUPPORT:
return ACE_TEXT ("socket type not supported for address family");
/* NOTREACHED */
case WSAENOTSOCK:
return ACE_TEXT ("handle is not a socket");
/* NOTREACHED */
case WSAEWOULDBLOCK:
return ACE_TEXT ("resource temporarily unavailable");
/* NOTREACHED */
case WSAEADDRINUSE:
return ACE_TEXT ("address already in use");
/* NOTREACHED */
case WSAECONNABORTED:
return ACE_TEXT ("connection aborted");
/* NOTREACHED */
case WSAECONNRESET:
return ACE_TEXT ("connection reset");
/* NOTREACHED */
case WSAENOTCONN:
return ACE_TEXT ("not connected");
/* NOTREACHED */
case WSAETIMEDOUT:
return ACE_TEXT ("connection timed out");
/* NOTREACHED */
case WSAECONNREFUSED:
return ACE_TEXT ("connection refused");
/* NOTREACHED */
case WSAEHOSTDOWN:
return ACE_TEXT ("host down");
/* NOTREACHED */
case WSAEHOSTUNREACH:
return ACE_TEXT ("host unreachable");
/* NOTREACHED */
case WSAEADDRNOTAVAIL:
return ACE_TEXT ("address not available");
/* NOTREACHED */
case WSAEISCONN:
return ACE_TEXT ("socket is already connected");
/* NOTREACHED */
case WSAENETRESET:
return ACE_TEXT ("network dropped connection on reset");
/* NOTREACHED */
case WSAEMSGSIZE:
return ACE_TEXT ("message too long");
/* NOTREACHED */
case WSAENETUNREACH:
return ACE_TEXT ("network is unreachable");
/* NOTREACHED */
case WSAEFAULT:
return ACE_TEXT ("bad address");
/* NOTREACHED */
case WSAEDISCON:
return ACE_TEXT ("graceful shutdown in progress");
/* NOTREACHED */
case WSAEACCES:
return ACE_TEXT ("permission denied");
/* NOTREACHED */
case WSAESHUTDOWN:
return ACE_TEXT ("cannot send after socket shutdown");
/* NOTREACHED */
case WSAEPROCLIM:
return ACE_TEXT ("too many processes");
/* NOTREACHED */
case WSAEALREADY:
return ACE_TEXT ("operation already in progress");
/* NOTREACHED */
case WSAEPFNOSUPPORT:
return ACE_TEXT ("protocol family not supported");
/* NOTREACHED */
case WSAENOPROTOOPT:
return ACE_TEXT ("bad protocol option");
/* NOTREACHED */
case WSATYPE_NOT_FOUND:
return ACE_TEXT ("class type not found");
/* NOTREACHED */
case WSAEOPNOTSUPP:
return ACE_TEXT ("operation not supported");
/* NOTREACHED */
case WSAEDESTADDRREQ:
return ACE_TEXT ("destination address required");
/* NOTREACHED */
default:
ACE_OS::sprintf (unknown_msg, ACE_TEXT ("unknown error: %d"), error);
return unknown_msg;
/* NOTREACHED */
}
#else
ACE_UNUSED_ARG (error);
ACE_NOTSUP_RETURN (0);
#endif /* ACE_WIN32 */
}
bool
ACE::is_sock_error (int error)
{
#if defined (ACE_WIN32)
switch (error)
{
case WSAVERNOTSUPPORTED:
case WSASYSNOTREADY:
case WSAEINVAL:
case WSAHOST_NOT_FOUND:
case WSATRY_AGAIN:
case WSANO_RECOVERY:
case WSANO_DATA:
/*
case WSANO_ADDRESS:
*/
case WSANOTINITIALISED:
case WSAENETDOWN:
case WSAEINPROGRESS:
case WSAEINTR:
case WSAEAFNOSUPPORT:
case WSAEMFILE:
case WSAENOBUFS:
case WSAEPROTONOSUPPORT:
case WSAEPROTOTYPE:
case WSAESOCKTNOSUPPORT:
case WSAENOTSOCK:
case WSAEWOULDBLOCK:
case WSAEADDRINUSE:
case WSAECONNABORTED:
case WSAECONNRESET:
case WSAENOTCONN:
case WSAETIMEDOUT:
case WSAECONNREFUSED:
case WSAEHOSTDOWN:
case WSAEHOSTUNREACH:
case WSAEADDRNOTAVAIL:
case WSAEISCONN:
case WSAENETRESET:
case WSAEMSGSIZE:
case WSAENETUNREACH:
case WSAEFAULT:
case WSAEDISCON:
case WSAEACCES:
case WSAESHUTDOWN:
case WSAEPROCLIM:
case WSAEALREADY:
case WSAEPFNOSUPPORT:
case WSAENOPROTOOPT:
case WSATYPE_NOT_FOUND:
case WSAEOPNOTSUPP:
return true;
}
#else
ACE_UNUSED_ARG (error);
#endif /* ACE_WIN32 */
return false;
}
char *
ACE::strndup (const char *str, size_t n)
{
const char *t = str;
size_t len;
// Figure out how long this string is (remember, it might not be
// NUL-terminated).
for (len = 0;
len < n && *t++ != '\0';
len++)
continue;
char *s;
ACE_ALLOCATOR_RETURN (s,
(char *) ACE_OS::malloc (len + 1),
0);
return ACE_OS::strsncpy (s, str, len + 1);
}
#if defined (ACE_HAS_WCHAR)
wchar_t *
ACE::strndup (const wchar_t *str, size_t n)
{
const wchar_t *t = str;
size_t len;
// Figure out how long this string is (remember, it might not be
// NUL-terminated).
for (len = 0;
len < n && *t++ != '\0';
len++)
continue;
wchar_t *s;
ACE_ALLOCATOR_RETURN (s,
static_cast<wchar_t *> (
ACE_OS::malloc ((len + 1) * sizeof (wchar_t))),
0);
return ACE_OS::strsncpy (s, str, len + 1);
}
#endif /* ACE_HAS_WCHAR */
char *
ACE::strnnew (const char *str, size_t n)
{
const char *t = str;
size_t len;
// Figure out how long this string is (remember, it might not be
// NUL-terminated).
for (len = 0;
len < n && *t++ != L'\0';
len++)
continue;
char *s;
ACE_NEW_RETURN (s,
char[len + 1],
0);
return ACE_OS::strsncpy (s, str, len + 1);
}
#if defined (ACE_HAS_WCHAR)
wchar_t *
ACE::strnnew (const wchar_t *str, size_t n)
{
const wchar_t *t = str;
size_t len;
// Figure out how long this string is (remember, it might not be
// NUL-terminated).
for (len = 0;
len < n && *t++ != ACE_TEXT_WIDE ('\0');
len++)
continue;
wchar_t *s;
ACE_NEW_RETURN (s,
wchar_t[len + 1],
0);
return ACE_OS::strsncpy (s, str, len + 1);
}
#endif /* ACE_HAS_WCHAR */
const char *
ACE::strend (const char *s)
{
while (*s++ != '\0')
continue;
return s;
}
#if defined ACE_HAS_WCHAR
const wchar_t *
ACE::strend (const wchar_t *s)
{
while (*s++ != ACE_TEXT_WIDE ('\0'))
continue;
return s;
}
#endif
char *
ACE::strnew (const char *s)
{
if (s == 0)
return 0;
char *t = 0;
ACE_NEW_RETURN (t,
char [ACE_OS::strlen (s) + 1],
0);
if (t == 0)
return 0;
else
return ACE_OS::strcpy (t, s);
}
#if defined (ACE_HAS_WCHAR)
wchar_t *
ACE::strnew (const wchar_t *s)
{
if (s == 0)
return 0;
wchar_t *t = 0;
ACE_NEW_RETURN (t,
wchar_t[ACE_OS::strlen (s) + 1],
0);
if (t == 0)
return 0;
else
return ACE_OS::strcpy (t, s);
}
#endif /* ACE_HAS_WCHAR */
inline static bool equal_char(char a, char b, bool case_sensitive)
{
if (case_sensitive)
return a == b;
return ACE_OS::ace_tolower(a) == ACE_OS::ace_tolower(b);
}
bool
ACE::wild_match(const char* str, const char* pat, bool case_sensitive)
{
if (str == pat)
return true;
if (pat == 0 || str == 0)
return false;
bool star = false;
const char* s = str;
const char* p = pat;
while (*s != '\0')
{
if (*p == '*')
{
star = true;
pat = p;
while (*++pat == '*');
if (*pat == '\0')
return true;
p = pat;
}
else if (*p == '?')
{
++s;
++p;
}
else if (! equal_char(*s, *p, case_sensitive))
{
if (!star)
return false;
s = ++str;
p = pat;
}
else
{
++s;
++p;
}
}
if (*p == '*')
while (*++p == '*');
return *p == '\0';
}
// Close versioned namespace, if enabled by the user.
ACE_END_VERSIONED_NAMESPACE_DECL
|
eSDK/esdk_uc_plugin_ucservice
|
platform/HWUCSDK/windows/eSpace_Desktop_V200R001C50SPC100B091/include/ace/ACE.cpp
|
C++
|
apache-2.0
| 88,337
|
/*
Copyright (c) 2021, Craig Barnes.
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
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.
*/
#include <limits.h>
#include <stddef.h>
#include <lua.h>
#include <lauxlib.h>
#include "compat.h"
#include "../lib/ascii.h"
#include "../lib/macros.h"
static const char *do_trim(const char *str, size_t *n)
{
size_t len = *n;
while (len && ascii_isspace(*str)) {
len--;
str++;
}
const char *end = str + len - 1;
while (len && ascii_isspace(*end)) {
len--;
end--;
}
*n = len;
return str;
}
static int trim_and_collapse(lua_State *L)
{
luaL_Buffer b;
size_t len;
const char *str = luaL_checklstring(L, 1, &len);
str = do_trim(str, &len);
#if LUA_VERSION_NUM >= 502
char *out = luaL_buffinitsize(L, &b, len);
size_t pos = 0;
#else
luaL_buffinit(L, &b);
#endif
for (size_t i = 0; i < len; ) {
char ch = str[i++];
if (ascii_isspace(ch)) {
while (i < len && ascii_isspace(str[i])) {
i++;
}
ch = ' ';
}
#if LUA_VERSION_NUM >= 502
out[pos++] = ch;
#else
luaL_addchar(&b, ch);
#endif
}
#if LUA_VERSION_NUM >= 502
luaL_addsize(&b, pos);
#endif
luaL_pushresult(&b);
return 1;
}
static int trim(lua_State *L)
{
size_t len;
const char *str = luaL_checklstring(L, 1, &len);
const char *trimmed = do_trim(str, &len);
lua_pushlstring(L, trimmed, len);
return 1;
}
static int createtable(lua_State *L)
{
lua_Integer narr = luaL_checkinteger(L, 1);
lua_Integer nrec = luaL_checkinteger(L, 2);
if (unlikely(narr < 0 || narr > INT_MAX)) {
luaL_argerror(L, 1, "value outside valid range");
}
if (unlikely(nrec < 0 || nrec > INT_MAX)) {
luaL_argerror(L, 2, "value outside valid range");
}
lua_createtable(L, (int)narr, (int)nrec);
return 1;
}
static const luaL_Reg lib[] = {
{"trim", trim},
{"trimAndCollapseWhitespace", trim_and_collapse},
{"createtable", createtable},
{NULL, NULL}
};
EXPORT int luaopen_gumbo_util(lua_State *L)
{
luaL_newlib(L, lib);
return 1;
}
|
craigbarnes/lua-gumbo
|
gumbo/util.c
|
C
|
apache-2.0
| 2,695
|
/*
* Copyright 2021 HM Revenue & Customs
*
* 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 views.pages.lookup
import org.jsoup.Jsoup
import testHelpers.ViewSpecHelpers.CommonViewSpecHelper
import testHelpers.ViewSpecHelpers.lookup.ProtectionGuidanceSpecMessages
import views.html.pages.lookup.pla_protection_guidance
class PlaProtectionGuidanceViewSpec extends CommonViewSpecHelper with ProtectionGuidanceSpecMessages {
"The PLA Protection Guidance View" should {
lazy val view = application.injector.instanceOf[pla_protection_guidance]
lazy val doc = Jsoup.parse(view().body)
"have a header with the correct content" in {
doc.select("h1").text() shouldBe title
}
"have a table" which {
"has a heading row" which {
lazy val row = doc.select("tr").first()
"has the correct left column heading" in {
row.select("th").get(0).text() shouldBe tableHeadingLeft
}
"has the correct right column heading" in {
row.select("th").get(1).text() shouldBe tableHeadingRight
}
}
"has a first row" which {
lazy val row = doc.select("tr").get(1)
"has the correct left element" in {
row.select("td").get(0).text() shouldBe rowOneLeft
}
"has the correct right element" in {
row.select("td").get(1).text() shouldBe rowOneRight
}
}
"has a second row" which {
lazy val row = doc.select("tr").get(2)
"has the correct left element" in {
row.select("td").get(0).text() shouldBe rowTwoLeft
}
"has the correct right element" in {
row.select("td").get(1).text() shouldBe rowTwoRight
}
}
"has a third row" which {
lazy val row = doc.select("tr").get(3)
"has the correct left element" in {
row.select("td").get(0).text() shouldBe rowThreeLeft
}
"has the correct right element" in {
row.select("td").get(1).text() shouldBe rowThreeRight
}
}
"has a fourth row" which {
lazy val row = doc.select("tr").get(4)
"has the correct left element" in {
row.select("td").get(0).text() shouldBe rowFourLeft
}
"has the correct right element" in {
row.select("td").get(1).text() shouldBe rowFourRight
}
}
"has a fifth row" which {
lazy val row = doc.select("tr").get(5)
"has the correct left element" in {
row.select("td").get(0).text() shouldBe rowFiveLeft
}
"has the correct right element" which {
lazy val element = row.select("td").get(1)
"has the correct text" in {
element.text() shouldBe rowFiveRight
}
"has a list with the correct first element" in {
element.select("li").get(0).text() shouldBe rowFiveListOne
}
"has a list with the correct second element" in {
element.select("li").get(1).text() shouldBe rowFiveListTwo
}
}
}
"has a sixth row" which {
lazy val row = doc.select("tr").get(6)
"has the correct left element" in {
row.select("td").get(0).text() shouldBe rowSixLeft
}
"has the correct right element" which {
lazy val element = row.select("td").get(1)
"has the correct text" in {
element.text() shouldBe rowSixRight
}
"has a list with the correct first element" in {
element.select("li").get(0).text() shouldBe rowSixListOne
}
"has a list with the correct second element" in {
element.select("li").get(1).text() shouldBe rowSixListTwo
}
}
}
"has a seventh row" which {
lazy val row = doc.select("tr").get(7)
"has the correct left element" in {
row.select("td").get(0).text() shouldBe rowSevenLeft
}
"has the correct right element" in {
row.select("td").get(1).text() shouldBe rowSevenRight
}
}
}
"has a back link" which {
lazy val link = doc.select("div a.back-link")
"has the correct text" in {
link.text() shouldBe plaBaseBack
}
"has a link to the correct location" in {
link.attr("href") shouldBe controllers.routes.LookupController.displayLookupResults().url
}
}
}
}
|
hmrc/pensions-lifetime-allowance-frontend
|
test/views/pages/lookup/PlaProtectionGuidanceViewSpec.scala
|
Scala
|
apache-2.0
| 4,960
|
package jaz;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Rectangle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import javax.swing.JPanel;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
import org.fife.ui.rtextarea.RTextScrollPane;
public final class Text extends TabContent {
private final RSyntaxTextArea _textArea;
private final RTextScrollPane _scrollPane;
private final AbstractSearchField _searchField;
private final JPanel _content;
Text() {
_textArea = new RSyntaxTextArea();
_scrollPane = new RTextScrollPane(_textArea);
_searchField = new SearchField();
_content = new JPanel();
_content.setBorder(
new EmptyBorder(Window.BORDER_SIZE, Window.BORDER_SIZE, Window.BORDER_SIZE, Window.BORDER_SIZE));
_content.setLayout(new BorderLayout());
_scrollPane
.setBorder(new CompoundBorder(new EmptyBorder(0, 0, Window.BORDER_SIZE, 0), _searchField.getBorder()));
_content.add(_scrollPane, BorderLayout.CENTER);
_content.add(_searchField, BorderLayout.SOUTH);
}
@Override
Component getComponent() {
return _content;
}
public Text content(String text) {
return executeOnEventDispatchThread(() -> {
if (_textArea.getText().equals(text)) {
return;
}
int oldCaretPosition = _textArea.getCaretPosition();
_textArea.setText(text);
_textArea.setCaretPosition(Math.min(_textArea.getDocument().getLength(), oldCaretPosition));
_searchField.search(_searchField.getText());
});
}
public Text syntax(String syntax) {
return executeOnEventDispatchThread(() -> {
String styleKey = "text/" + syntax;
if (styleKey.equals(_textArea.getSyntaxEditingStyle())) {
return;
}
_textArea.setSyntaxEditingStyle(styleKey);
_textArea.setCodeFoldingEnabled(true);
});
}
public Text lineWrap() {
return executeOnEventDispatchThread(() -> {
if (_textArea.getLineWrap()) {
return;
}
_textArea.setLineWrap(true);
});
}
private final class SearchField extends AbstractSearchField {
SearchField() {
super("Search Text...");
}
@Override
void search(String text) {
_textArea.getHighlighter().removeAllHighlights();
if (text.isEmpty()) {
return;
}
try {
boolean isFirstFound = true;
Matcher matcher = Pattern.compile(text).matcher(_textArea.getText());
while (matcher.find()) {
if (isFirstFound) {
isFirstFound = false;
Rectangle viewRect = _textArea.modelToView(matcher.start());
_textArea.scrollRectToVisible(viewRect);
}
_textArea.getHighlighter().addHighlight(matcher.start(), matcher.end(), DefaultHighlighter.DefaultPainter);
}
} catch (PatternSyntaxException e) {
// ignore exception
} catch (BadLocationException e) {
new AssertionError();
}
}
}
}
|
hisano/jazcode
|
src/main/java/jaz/Text.java
|
Java
|
apache-2.0
| 3,016
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.