code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
[Spiffy UI Framework](http://www.spiffyui.org) - beautiful, fast, maintainable applications with GWT and REST ================================================== Spiffy UI is a framework for calling REST from GWT. Check out [www.spiffyui.org](http://www.spiffyui.org) for a lot more information and a sample application. Building and Running Spiffy UI -------------------------------------- Spiffy UI framework is built with [Apache Ant](http://ant.apache.org/) using [Apache Ivy](http://ant.apache.org/ivy/). Once you've installed Ant go to your Spiffy UI working copy and run this command: git clone git://github.com/spiffyui/spiffyui.git cd spiffyui <ANT HOME>/ant all run This will download the required libraries, build the Spiffy UI framework, and run it with an embedded web server. It will then provide intructions for accessing the running application. For information on all the build options run: <ANT HOME>/ant -p License -------------------------------------- The Spiffy UI Framework is available under the [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.html). Get Help -------------------------------------- If you need some help with Spiffy UI post a message on the <a href="http://groups.google.com/group/spiffy-ui">Spiffy UI Google Group</a> Get The Samples -------------------------------------- Spiffy UI hosts sample applications on the <a href="https://github.com/spiffyui/">Spiffy UI GitHub page</a>. Build Status -------------------------------------- Spiffy UI uses a continuous integration server from <a href="http://www.cloudbees.com/">CloudBees</a>. Check the status of the build on the <a href="https://spiffyui.ci.cloudbees.com/">Spiffy UI continuous integration dashboard</a>. <img src="http://web-static-cloudfront.s3.amazonaws.com/images/badges/BuiltOnDEV.png" style="float: right;" border="0">
spiffyui/spiffyui
README.md
Markdown
apache-2.0
1,916
/** * 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.camel.processor.juel; import javax.naming.Context; import org.apache.camel.ContextTestSupport; import org.apache.camel.Exchange; import org.apache.camel.InvalidPayloadException; import org.apache.camel.Message; import org.apache.camel.Processor; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.util.ExchangeHelper; import org.apache.camel.util.jndi.JndiContext; import static org.apache.camel.language.juel.JuelExpression.el; /** * @version */ public class SimulatorTest extends ContextTestSupport { protected Context createJndiContext() throws Exception { JndiContext answer = new JndiContext(); answer.bind("foo", new MyBean("foo")); answer.bind("bar", new MyBean("bar")); return answer; } public void testReceivesFooResponse() throws Exception { assertRespondsWith("foo", "Bye said foo"); } public void testReceivesBarResponse() throws Exception { assertRespondsWith("bar", "Bye said bar"); } protected void assertRespondsWith(final String value, String containedText) throws InvalidPayloadException { Exchange response = template.request("direct:a", new Processor() { public void process(Exchange exchange) throws Exception { Message in = exchange.getIn(); in.setBody("answer"); in.setHeader("cheese", value); } }); assertNotNull("Should receive a response!", response); String text = ExchangeHelper.getMandatoryOutBody(response, String.class); assertStringContains(text, containedText); } protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { // START SNIPPET: example from("direct:a"). recipientList(el("bean:${in.headers.cheese}")); // END SNIPPET: example } }; } public static class MyBean { private String value; public MyBean(String value) { this.value = value; } public String doSomething(String in) { return "Bye said " + value; } } }
everttigchelaar/camel-svn
components/camel-juel/src/test/java/org/apache/camel/processor/juel/SimulatorTest.java
Java
apache-2.0
3,124
package com.stf.bj.app.game.players; import java.util.Random; import com.stf.bj.app.game.bj.Spot; import com.stf.bj.app.game.server.Event; import com.stf.bj.app.game.server.EventType; import com.stf.bj.app.settings.AppSettings; import com.stf.bj.app.strategy.FullStrategy; public class RealisticBot extends BasicBot { private enum InsuranceStrategy { NEVER, EVEN_MONEY_ONLY, GOOD_HANDS_ONLY, RARELY, OFTEN; } private enum PlayAbility { PERFECT, NOOB, RANDOM; } private enum BetChanging { NEVER, RANDOM; } private final InsuranceStrategy insuranceStrategy; private final PlayAbility playAbility; private final Random r; private double wager = -1.0; private final BetChanging betChanging; private boolean insurancePlay = false; private boolean calculatedInsurancePlay = false; private boolean messUpNextPlay = false; public RealisticBot(AppSettings settings, FullStrategy strategy, Random r, Spot s) { super(settings, strategy, r, s); if (r == null) { r = new Random(System.currentTimeMillis()); } this.r = r; insuranceStrategy = InsuranceStrategy.values()[r.nextInt(InsuranceStrategy.values().length)]; playAbility = PlayAbility.values()[r.nextInt(PlayAbility.values().length)]; setBaseBet(); betChanging = BetChanging.RANDOM; } @Override public void sendEvent(Event e) { super.sendEvent(e); if (e.getType() == EventType.DECK_SHUFFLED) { if (betChanging == BetChanging.RANDOM && r.nextInt(2) == 0) { wager = 5; } } } @Override public double getWager() { if (delay > 0) { delay--; return -1; } return wager; } private void setBaseBet() { int rInt = r.nextInt(12); if (rInt < 6) { wager = 5.0 * (1 + rInt); } else if (rInt < 9) { wager = 10.0; } else { wager = 5.0; } } @Override public boolean getInsurancePlay() { if (insuranceStrategy == InsuranceStrategy.NEVER) { return false; } if (!calculatedInsurancePlay) { insurancePlay = calculateInsurancePlay(); calculatedInsurancePlay = true; } return insurancePlay; } private boolean calculateInsurancePlay() { switch (insuranceStrategy) { case EVEN_MONEY_ONLY: return getHandSoftTotal(0) == 21; case GOOD_HANDS_ONLY: return getHandSoftTotal(0) > 16 + r.nextInt(3); case OFTEN: return r.nextInt(2) == 0; case RARELY: return r.nextInt(5) == 0; default: throw new IllegalStateException(); } } @Override public Play getMove(int handIndex, boolean canDouble, boolean canSplit, boolean canSurrender) { if (delay > 0) { delay--; return null; } Play play = super.getMove(handIndex, canDouble, canSplit, canSurrender); if (messUpNextPlay) { if (play != Play.SPLIT && canSplit) { play = Play.SPLIT; } else if (play != Play.DOUBLEDOWN && canSplit) { play = Play.DOUBLEDOWN; } else if (play == Play.STAND) { play = Play.HIT; } else { play = Play.STAND; } } return play; } @Override protected void reset() { super.reset(); calculatedInsurancePlay = false; int random = r.nextInt(10); if (playAbility == PlayAbility.RANDOM) { messUpNextPlay = (random < 2); } if ((random == 2 || random == 3) && betChanging == BetChanging.RANDOM) { wager += 5; } else if (random == 4 && betChanging == BetChanging.RANDOM) { if (wager > 6) { wager -= 5; } } } }
Boxxy/Blackjack
core/src/com/stf/bj/app/game/players/RealisticBot.java
Java
apache-2.0
3,337
package me.marcosassuncao.servsim.job; import me.marcosassuncao.servsim.profile.RangeList; import com.google.common.base.MoreObjects; /** * {@link Reservation} represents a resource reservation request * made by a customer to reserve a given number of resources * from a provider. * * @see WorkUnit * @see DefaultWorkUnit * * @author Marcos Dias de Assuncao */ public class Reservation extends DefaultWorkUnit { private long reqStartTime = WorkUnit.TIME_NOT_SET; private RangeList rangeList; /** * Creates a reservation request to start at * <code>startTime</code> and with the given duration. * @param startTime the requested start time for the reservation * @param duration the duration of the reservation * @param numResources number of required resources */ public Reservation(long startTime, long duration, int numResources) { super(duration); super.setNumReqResources(numResources); this.reqStartTime = startTime; } /** * Creates a reservation request to start at * <code>startTime</code> and with the given duration and priority * @param startTime the requested start time for the reservation * @param duration the duration of the reservation * @param numResources the number of resources to be reserved * @param priority the reservation priority */ public Reservation(long startTime, long duration, int numResources, int priority) { super(duration, priority); super.setNumReqResources(numResources); this.reqStartTime = startTime; } /** * Returns the start time requested by this reservation * @return the requested start time */ public long getRequestedStartTime() { return reqStartTime; } /** * Sets the ranges of reserved resources * @param ranges the ranges of resources allocated for the reservation * @return <code>true</code> if the ranges have been set correctly, * <code>false</code> otherwise. */ public boolean setResourceRanges(RangeList ranges) { if (this.rangeList != null) { return false; } this.rangeList = ranges; return true; } /** * Gets the ranges of reserved resources * @return the ranges of reserved resources */ public RangeList getResourceRanges() { return rangeList; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("id", getId()) .add("submission time", getSubmitTime()) .add("start time", getStartTime()) .add("finish time", getFinishTime()) .add("duration", getDuration()) .add("priority", getPriority()) .add("status", getStatus()) .add("resources", rangeList) .toString(); } }
assuncaomarcos/servsim
src/main/java/me/marcosassuncao/servsim/job/Reservation.java
Java
apache-2.0
2,646
# AUTOGENERATED FILE FROM balenalib/photon-xavier-nx-alpine:3.12-run ENV NODE_VERSION 14.15.4 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 buildDeps='curl' \ && set -x \ && 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 \ && apk add --no-cache $buildDeps \ && curl -SLO "http://resin-packages.s3.amazonaws.com/node/v$NODE_VERSION/node-v$NODE_VERSION-linux-alpine-aarch64.tar.gz" \ && echo "93e91093748c7287665d617cca0dc2ed9c26aa95dcf9152450a7961850e6d846 node-v$NODE_VERSION-linux-alpine-aarch64.tar.gz" | sha256sum -c - \ && tar -xzf "node-v$NODE_VERSION-linux-alpine-aarch64.tar.gz" -C /usr/local --strip-components=1 \ && rm "node-v$NODE_VERSION-linux-alpine-aarch64.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/[email protected]" \ && echo "Running test-stack@node" \ && chmod +x [email protected] \ && bash [email protected] \ && rm -rf [email protected] 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 v8 \nOS: Alpine Linux 3.12 \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v14.15.4, 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/photon-xavier-nx/alpine/3.12/14.15.4/run/Dockerfile
Dockerfile
apache-2.0
3,031
# AUTOGENERATED FILE FROM balenalib/surface-pro-6-fedora:31-build ENV NODE_VERSION 14.15.4 ENV YARN_VERSION 1.22.4 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://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-x64.tar.gz" \ && echo "b51c033d40246cd26e52978125a3687df5cd02ee532e8614feff0ba6c13a774f node-v$NODE_VERSION-linux-x64.tar.gz" | sha256sum -c - \ && tar -xzf "node-v$NODE_VERSION-linux-x64.tar.gz" -C /usr/local --strip-components=1 \ && rm "node-v$NODE_VERSION-linux-x64.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/[email protected]" \ && echo "Running test-stack@node" \ && chmod +x [email protected] \ && bash [email protected] \ && rm -rf [email protected] 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: Intel 64-bit (x86-64) \nOS: Fedora 31 \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v14.15.4, 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/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
nghiant2710/base-images
balena-base-images/node/surface-pro-6/fedora/31/14.15.4/build/Dockerfile
Dockerfile
apache-2.0
2,763
/* * Copyright (c) 2016, baihw ([email protected]). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and limitations under the License. * */ package com.yoya.rdf.router; /** * Created by baihw on 16-6-13. * * 统一的服务请求处理器规范接口,此接口用于标识类文件为请求处理器实现类,无必须实现的方法。 * * 实现类中所有符合public void xxx( IRequest request, IResponse response )签名规则的方法都将被自动注册到对应的请求处理器中。 * * 如下所示: * * public void login( IRequest request, IResponse response ){}; * * public void logout( IRequest request, IResponse response ){} ; * * 上边的login, logout将被自动注册到请求处理器路径中。 * * 假如类名为LoginHnadler, 则注册的处理路径为:/Loginhandler/login, /Loginhandler/logout. * * 注意:大小写敏感。 * */ public interface IRequestHandler{ /** * 当请求中没有明确指定处理方法时,默认执行的请求处理方法。 * * @param request 请求对象 * @param response 响应对象 */ void handle( IRequest request, IResponse response ); } // end class
javakf/rdf
src/main/java/com/yoya/rdf/router/IRequestHandler.java
Java
apache-2.0
1,692
(function() { 'use strict'; angular .module('sentryApp') .controller('TimeFrameController', TimeFrameController); TimeFrameController.$inject = ['$scope', '$state', 'TimeFrame', 'ParseLinks', 'AlertService', 'paginationConstants', 'pagingParams']; function TimeFrameController ($scope, $state, TimeFrame, ParseLinks, AlertService, paginationConstants, pagingParams) { var vm = this; vm.loadPage = loadPage; vm.predicate = pagingParams.predicate; vm.reverse = pagingParams.ascending; vm.transition = transition; vm.itemsPerPage = paginationConstants.itemsPerPage; loadAll(); function loadAll () { TimeFrame.query({ page: pagingParams.page - 1, size: vm.itemsPerPage, sort: sort() }, onSuccess, onError); function sort() { var result = [vm.predicate + ',' + (vm.reverse ? 'asc' : 'desc')]; if (vm.predicate !== 'id') { result.push('id'); } return result; } function onSuccess(data, headers) { vm.links = ParseLinks.parse(headers('link')); vm.totalItems = headers('X-Total-Count'); vm.queryCount = vm.totalItems; vm.timeFrames = data; vm.page = pagingParams.page; } function onError(error) { AlertService.error(error.data.message); } } function loadPage(page) { vm.page = page; vm.transition(); } function transition() { $state.transitionTo($state.$current, { page: vm.page, sort: vm.predicate + ',' + (vm.reverse ? 'asc' : 'desc'), search: vm.currentSearch }); } } })();
quanticc/sentry
src/main/webapp/app/entities/time-frame/time-frame.controller.js
JavaScript
apache-2.0
1,937
/* * Copyright 2010-2020 Alfresco Software, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.activiti.spring.test.servicetask; import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import org.activiti.engine.impl.test.JobTestHelper; import org.activiti.engine.runtime.ProcessInstance; import org.activiti.engine.test.Deployment; import org.activiti.spring.impl.test.SpringActivitiTestCase; import org.springframework.test.context.ContextConfiguration; /** */ @ContextConfiguration("classpath:org/activiti/spring/test/servicetask/servicetaskSpringTest-context.xml") public class ServiceTaskSpringDelegationTest extends SpringActivitiTestCase { private void cleanUp() { List<org.activiti.engine.repository.Deployment> deployments = repositoryService.createDeploymentQuery().list(); for (org.activiti.engine.repository.Deployment deployment : deployments) { repositoryService.deleteDeployment(deployment.getId(), true); } } @Override public void tearDown() { cleanUp(); } @Deployment public void testDelegateExpression() { ProcessInstance procInst = runtimeService.startProcessInstanceByKey("delegateExpressionToSpringBean"); assertThat(runtimeService.getVariable(procInst.getId(), "myVar")).isEqualTo("Activiti BPMN 2.0 process engine"); assertThat(runtimeService.getVariable(procInst.getId(), "fieldInjection")).isEqualTo("fieldInjectionWorking"); } @Deployment public void testAsyncDelegateExpression() throws Exception { ProcessInstance procInst = runtimeService.startProcessInstanceByKey("delegateExpressionToSpringBean"); assertThat(JobTestHelper.areJobsAvailable(managementService)).isTrue(); waitForJobExecutorToProcessAllJobs(5000, 500); Thread.sleep(1000); assertThat(runtimeService.getVariable(procInst.getId(), "myVar")).isEqualTo("Activiti BPMN 2.0 process engine"); assertThat(runtimeService.getVariable(procInst.getId(), "fieldInjection")).isEqualTo("fieldInjectionWorking"); } @Deployment public void testMethodExpressionOnSpringBean() { ProcessInstance procInst = runtimeService.startProcessInstanceByKey("methodExpressionOnSpringBean"); assertThat(runtimeService.getVariable(procInst.getId(), "myVar")).isEqualTo("ACTIVITI BPMN 2.0 PROCESS ENGINE"); } @Deployment public void testAsyncMethodExpressionOnSpringBean() { ProcessInstance procInst = runtimeService.startProcessInstanceByKey("methodExpressionOnSpringBean"); assertThat(JobTestHelper.areJobsAvailable(managementService)).isTrue(); waitForJobExecutorToProcessAllJobs(5000, 500); assertThat(runtimeService.getVariable(procInst.getId(), "myVar")).isEqualTo("ACTIVITI BPMN 2.0 PROCESS ENGINE"); } @Deployment public void testExecutionAndTaskListenerDelegationExpression() { ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("executionAndTaskListenerDelegation"); assertThat(runtimeService.getVariable(processInstance.getId(), "executionListenerVar")).isEqualTo("working"); assertThat(runtimeService.getVariable(processInstance.getId(), "taskListenerVar")).isEqualTo("working"); assertThat(runtimeService.getVariable(processInstance.getId(), "executionListenerField")).isEqualTo("executionListenerInjection"); assertThat(runtimeService.getVariable(processInstance.getId(), "taskListenerField")).isEqualTo("taskListenerInjection"); } }
Activiti/Activiti
activiti-core/activiti-spring/src/test/java/org/activiti/spring/test/servicetask/ServiceTaskSpringDelegationTest.java
Java
apache-2.0
4,086
/** * <copyright> * </copyright> * * $Id$ */ package de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.impl; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.impl.EObjectImpl; import org.eclipse.emf.ecore.util.EcoreUtil; import de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.Cpu_usage; import de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.Sys_info_systeminfoPackage; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Cpu usage</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.impl.Cpu_usageImpl#getEContainer_cpu_usage <em>EContainer cpu usage</em>}</li> * <li>{@link de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.impl.Cpu_usageImpl#getReal <em>Real</em>}</li> * <li>{@link de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.impl.Cpu_usageImpl#getUser <em>User</em>}</li> * <li>{@link de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.impl.Cpu_usageImpl#getSys <em>Sys</em>}</li> * <li>{@link de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.impl.Cpu_usageImpl#getUnit <em>Unit</em>}</li> * </ul> * </p> * * @generated */ public class Cpu_usageImpl extends EObjectImpl implements Cpu_usage { /** * The default value of the '{@link #getReal() <em>Real</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getReal() * @generated * @ordered */ protected static final double REAL_EDEFAULT = 0.0; /** * The cached value of the '{@link #getReal() <em>Real</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getReal() * @generated * @ordered */ protected double real = REAL_EDEFAULT; /** * The default value of the '{@link #getUser() <em>User</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getUser() * @generated * @ordered */ protected static final double USER_EDEFAULT = 0.0; /** * The cached value of the '{@link #getUser() <em>User</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getUser() * @generated * @ordered */ protected double user = USER_EDEFAULT; /** * The default value of the '{@link #getSys() <em>Sys</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getSys() * @generated * @ordered */ protected static final double SYS_EDEFAULT = 0.0; /** * The cached value of the '{@link #getSys() <em>Sys</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getSys() * @generated * @ordered */ protected double sys = SYS_EDEFAULT; /** * The default value of the '{@link #getUnit() <em>Unit</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getUnit() * @generated * @ordered */ protected static final String UNIT_EDEFAULT = null; /** * The cached value of the '{@link #getUnit() <em>Unit</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getUnit() * @generated * @ordered */ protected String unit = UNIT_EDEFAULT; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected Cpu_usageImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return Sys_info_systeminfoPackage.Literals.CPU_USAGE; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.System getEContainer_cpu_usage() { if (eContainerFeatureID() != Sys_info_systeminfoPackage.CPU_USAGE__ECONTAINER_CPU_USAGE) return null; return (de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.System)eContainer(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetEContainer_cpu_usage(de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.System newEContainer_cpu_usage, NotificationChain msgs) { msgs = eBasicSetContainer((InternalEObject)newEContainer_cpu_usage, Sys_info_systeminfoPackage.CPU_USAGE__ECONTAINER_CPU_USAGE, msgs); return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setEContainer_cpu_usage(de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.System newEContainer_cpu_usage) { if (newEContainer_cpu_usage != eInternalContainer() || (eContainerFeatureID() != Sys_info_systeminfoPackage.CPU_USAGE__ECONTAINER_CPU_USAGE && newEContainer_cpu_usage != null)) { if (EcoreUtil.isAncestor(this, newEContainer_cpu_usage)) throw new IllegalArgumentException("Recursive containment not allowed for " + toString()); NotificationChain msgs = null; if (eInternalContainer() != null) msgs = eBasicRemoveFromContainer(msgs); if (newEContainer_cpu_usage != null) msgs = ((InternalEObject)newEContainer_cpu_usage).eInverseAdd(this, Sys_info_systeminfoPackage.SYSTEM__CPU_USAGE, de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.System.class, msgs); msgs = basicSetEContainer_cpu_usage(newEContainer_cpu_usage, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Sys_info_systeminfoPackage.CPU_USAGE__ECONTAINER_CPU_USAGE, newEContainer_cpu_usage, newEContainer_cpu_usage)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public double getReal() { return real; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setReal(double newReal) { double oldReal = real; real = newReal; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Sys_info_systeminfoPackage.CPU_USAGE__REAL, oldReal, real)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public double getUser() { return user; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setUser(double newUser) { double oldUser = user; user = newUser; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Sys_info_systeminfoPackage.CPU_USAGE__USER, oldUser, user)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public double getSys() { return sys; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setSys(double newSys) { double oldSys = sys; sys = newSys; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Sys_info_systeminfoPackage.CPU_USAGE__SYS, oldSys, sys)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getUnit() { return unit; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setUnit(String newUnit) { String oldUnit = unit; unit = newUnit; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Sys_info_systeminfoPackage.CPU_USAGE__UNIT, oldUnit, unit)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case Sys_info_systeminfoPackage.CPU_USAGE__ECONTAINER_CPU_USAGE: if (eInternalContainer() != null) msgs = eBasicRemoveFromContainer(msgs); return basicSetEContainer_cpu_usage((de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.System)otherEnd, msgs); } return super.eInverseAdd(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case Sys_info_systeminfoPackage.CPU_USAGE__ECONTAINER_CPU_USAGE: return basicSetEContainer_cpu_usage(null, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eBasicRemoveFromContainerFeature(NotificationChain msgs) { switch (eContainerFeatureID()) { case Sys_info_systeminfoPackage.CPU_USAGE__ECONTAINER_CPU_USAGE: return eInternalContainer().eInverseRemove(this, Sys_info_systeminfoPackage.SYSTEM__CPU_USAGE, de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.System.class, msgs); } return super.eBasicRemoveFromContainerFeature(msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case Sys_info_systeminfoPackage.CPU_USAGE__ECONTAINER_CPU_USAGE: return getEContainer_cpu_usage(); case Sys_info_systeminfoPackage.CPU_USAGE__REAL: return getReal(); case Sys_info_systeminfoPackage.CPU_USAGE__USER: return getUser(); case Sys_info_systeminfoPackage.CPU_USAGE__SYS: return getSys(); case Sys_info_systeminfoPackage.CPU_USAGE__UNIT: return getUnit(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case Sys_info_systeminfoPackage.CPU_USAGE__ECONTAINER_CPU_USAGE: setEContainer_cpu_usage((de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.System)newValue); return; case Sys_info_systeminfoPackage.CPU_USAGE__REAL: setReal((Double)newValue); return; case Sys_info_systeminfoPackage.CPU_USAGE__USER: setUser((Double)newValue); return; case Sys_info_systeminfoPackage.CPU_USAGE__SYS: setSys((Double)newValue); return; case Sys_info_systeminfoPackage.CPU_USAGE__UNIT: setUnit((String)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case Sys_info_systeminfoPackage.CPU_USAGE__ECONTAINER_CPU_USAGE: setEContainer_cpu_usage((de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.System)null); return; case Sys_info_systeminfoPackage.CPU_USAGE__REAL: setReal(REAL_EDEFAULT); return; case Sys_info_systeminfoPackage.CPU_USAGE__USER: setUser(USER_EDEFAULT); return; case Sys_info_systeminfoPackage.CPU_USAGE__SYS: setSys(SYS_EDEFAULT); return; case Sys_info_systeminfoPackage.CPU_USAGE__UNIT: setUnit(UNIT_EDEFAULT); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case Sys_info_systeminfoPackage.CPU_USAGE__ECONTAINER_CPU_USAGE: return getEContainer_cpu_usage() != null; case Sys_info_systeminfoPackage.CPU_USAGE__REAL: return real != REAL_EDEFAULT; case Sys_info_systeminfoPackage.CPU_USAGE__USER: return user != USER_EDEFAULT; case Sys_info_systeminfoPackage.CPU_USAGE__SYS: return sys != SYS_EDEFAULT; case Sys_info_systeminfoPackage.CPU_USAGE__UNIT: return UNIT_EDEFAULT == null ? unit != null : !UNIT_EDEFAULT.equals(unit); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (real: "); result.append(real); result.append(", user: "); result.append(user); result.append(", sys: "); result.append(sys); result.append(", unit: "); result.append(unit); result.append(')'); return result.toString(); } } //Cpu_usageImpl
markus1978/clickwatch
analysis/de.hub.clickwatch.specificmodels.brn/src/de/hub/clickwatch/specificmodels/brn/sys_info_systeminfo/impl/Cpu_usageImpl.java
Java
apache-2.0
14,073
<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <html> <head> <title>PHPXRef 0.7.1 : Unnamed Project : /tests/simpletest/docs/fr/web_tester_documentation.html source</title> <link rel="stylesheet" href="../../../../sample.css" type="text/css"> <link rel="stylesheet" href="../../../../sample-print.css" type="text/css" media="print"> <style id="hilight" type="text/css"></style> <meta http-equiv="content-type" content="text/html;charset=iso-8859-1"> </head> <body bgcolor="#ffffff" text="#000000" link="#801800" vlink="#300540" alink="#ffffff"> <table class="pagetitle" width="100%"> <tr> <td valign="top" class="pagetitle"> [ <a href="../../../../index.html">Index</a> ] </td> <td align="right" class="pagetitle"> <h2 style="margin-bottom: 0px">PHP Cross Reference of Unnamed Project</h2> </td> </tr> </table> <!-- Generated by PHPXref 0.7.1 at Thu Oct 23 18:57:41 2014 --> <!-- PHPXref (c) 2000-2010 Gareth Watts - [email protected] --> <!-- http://phpxref.sourceforge.net/ --> <script src="../../../../phpxref.js" type="text/javascript"></script> <script language="JavaScript" type="text/javascript"> <!-- ext='.html'; relbase='../../../../'; subdir='tests/simpletest/docs/fr'; filename='web_tester_documentation.html.source.html'; cookiekey='phpxref'; handleNavFrame(relbase, subdir, filename); // --> </script> <script language="JavaScript" type="text/javascript"> if (gwGetCookie('xrefnav')=='off') document.write('<p class="navlinks">[ <a href="javascript:navOn()">Show Explorer<\/a> ]<\/p>'); else document.write('<p class="navlinks">[ <a href="javascript:navOff()">Hide Explorer<\/a> ]<\/p>'); </script> <noscript> <p class="navlinks"> [ <a href="../../../../nav.html" target="_top">Show Explorer</a> ] [ <a href="index.html" target="_top">Hide Navbar</a> ] </p> </noscript> <script language="JavaScript" type="text/javascript"> <!-- document.writeln('<table align="right" class="searchbox-link"><tr><td><a class="searchbox-link" href="javascript:void(0)" onMouseOver="showSearchBox()">Search</a><br>'); document.writeln('<table border="0" cellspacing="0" cellpadding="0" class="searchbox" id="searchbox">'); document.writeln('<tr><td class="searchbox-title">'); document.writeln('<a class="searchbox-title" href="javascript:showSearchPopup()">Search History +</a>'); document.writeln('<\/td><\/tr>'); document.writeln('<tr><td class="searchbox-body" id="searchbox-body">'); document.writeln('<form name="search" style="margin:0px; padding:0px" onSubmit=\'return jump()\'>'); document.writeln('<a class="searchbox-body" href="../../../../_classes/index.html">Class<\/a>: '); document.writeln('<input type="text" size=10 value="" name="classname"><br>'); document.writeln('<a id="funcsearchlink" class="searchbox-body" href="../../../../_functions/index.html">Function<\/a>: '); document.writeln('<input type="text" size=10 value="" name="funcname"><br>'); document.writeln('<a class="searchbox-body" href="../../../../_variables/index.html">Variable<\/a>: '); document.writeln('<input type="text" size=10 value="" name="varname"><br>'); document.writeln('<a class="searchbox-body" href="../../../../_constants/index.html">Constant<\/a>: '); document.writeln('<input type="text" size=10 value="" name="constname"><br>'); document.writeln('<a class="searchbox-body" href="../../../../_tables/index.html">Table<\/a>: '); document.writeln('<input type="text" size=10 value="" name="tablename"><br>'); document.writeln('<input type="submit" class="searchbox-button" value="Search">'); document.writeln('<\/form>'); document.writeln('<\/td><\/tr><\/table>'); document.writeln('<\/td><\/tr><\/table>'); // --> </script> <div id="search-popup" class="searchpopup"><p id="searchpopup-title" class="searchpopup-title">title</p><div id="searchpopup-body" class="searchpopup-body">Body</div><p class="searchpopup-close"><a href="javascript:gwCloseActive()">[close]</a></p></div> <h2 class="listing-heading"><a href="./index.html">/tests/simpletest/docs/fr/</a> -> <a href="web_tester_documentation.html.html">web_tester_documentation.html</a> (source)</h2> <div class="listing"> <p class="viewlinks">[<a href="web_tester_documentation.html.html">Summary view</a>] [<a href="javascript:window.print();">Print</a>] [<a href="web_tester_documentation.html.source.txt" target="_new">Text view</a>] </p> <pre> <a name="l1"><span class="linenum"> 1</span></a> &lt;html&gt; <a name="l2"><span class="linenum"> 2</span></a> &lt;head&gt; <a name="l3"><span class="linenum"> 3</span></a> &lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=UTF-8&quot;&gt; <a name="l4"><span class="linenum"> 4</span></a> &lt;title&gt;Documentation SimpleTest : tester des scripts web&lt;/title&gt; <a name="l5"><span class="linenum"> 5</span></a> &lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;docs.css&quot; title=&quot;Styles&quot;&gt; <a name="l6"><span class="linenum"> 6</span></a> &lt;/head&gt; <a name="l7"><span class="linenum"> 7</span></a> &lt;body&gt; <a name="l8"><span class="linenum"> 8</span></a> &lt;div class=&quot;menu_back&quot;&gt;&lt;div class=&quot;menu&quot;&gt; <a name="l9"><span class="linenum"> 9</span></a> &lt;a href=&quot;index.html&quot;&gt;SimpleTest&lt;/a&gt; <a name="l10"><span class="linenum"> 10</span></a> | <a name="l11"><span class="linenum"> 11</span></a> &lt;a href=&quot;overview.html&quot;&gt;Overview&lt;/a&gt; <a name="l12"><span class="linenum"> 12</span></a> | <a name="l13"><span class="linenum"> 13</span></a> &lt;a href=&quot;unit_test_documentation.html&quot;&gt;Unit tester&lt;/a&gt; <a name="l14"><span class="linenum"> 14</span></a> | <a name="l15"><span class="linenum"> 15</span></a> &lt;a href=&quot;group_test_documentation.html&quot;&gt;Group tests&lt;/a&gt; <a name="l16"><span class="linenum"> 16</span></a> | <a name="l17"><span class="linenum"> 17</span></a> &lt;a href=&quot;mock_objects_documentation.html&quot;&gt;Mock objects&lt;/a&gt; <a name="l18"><span class="linenum"> 18</span></a> | <a name="l19"><span class="linenum"> 19</span></a> &lt;a href=&quot;partial_mocks_documentation.html&quot;&gt;Partial mocks&lt;/a&gt; <a name="l20"><span class="linenum"> 20</span></a> | <a name="l21"><span class="linenum"> 21</span></a> &lt;a href=&quot;reporter_documentation.html&quot;&gt;Reporting&lt;/a&gt; <a name="l22"><span class="linenum"> 22</span></a> | <a name="l23"><span class="linenum"> 23</span></a> &lt;a href=&quot;expectation_documentation.html&quot;&gt;Expectations&lt;/a&gt; <a name="l24"><span class="linenum"> 24</span></a> | <a name="l25"><span class="linenum"> 25</span></a> &lt;a href=&quot;web_tester_documentation.html&quot;&gt;Web tester&lt;/a&gt; <a name="l26"><span class="linenum"> 26</span></a> | <a name="l27"><span class="linenum"> 27</span></a> &lt;a href=&quot;form_testing_documentation.html&quot;&gt;Testing forms&lt;/a&gt; <a name="l28"><span class="linenum"> 28</span></a> | <a name="l29"><span class="linenum"> 29</span></a> &lt;a href=&quot;authentication_documentation.html&quot;&gt;Authentication&lt;/a&gt; <a name="l30"><span class="linenum"> 30</span></a> | <a name="l31"><span class="linenum"> 31</span></a> &lt;a href=&quot;browser_documentation.html&quot;&gt;Scriptable browser&lt;/a&gt; <a name="l32"><span class="linenum"> 32</span></a> &lt;/div&gt;&lt;/div&gt; <a name="l33"><span class="linenum"> 33</span></a> &lt;h1&gt;Documentation sur le testeur web&lt;/h1&gt; <a name="l34"><span class="linenum"> 34</span></a> This page... <a name="l35"><span class="linenum"> 35</span></a> &lt;ul&gt; <a name="l36"><span class="linenum"> 36</span></a> &lt;li&gt; <a name="l37"><span class="linenum"> 37</span></a> Réussir à &lt;a href=&quot;#telecharger&quot;&gt;télécharger une page web&lt;/a&gt; <a name="l38"><span class="linenum"> 38</span></a> &lt;/li&gt; <a name="l39"><span class="linenum"> 39</span></a> &lt;li&gt; <a name="l40"><span class="linenum"> 40</span></a> Tester le &lt;a href=&quot;#contenu&quot;&gt;contenu de la page&lt;/a&gt; <a name="l41"><span class="linenum"> 41</span></a> &lt;/li&gt; <a name="l42"><span class="linenum"> 42</span></a> &lt;li&gt; <a name="l43"><span class="linenum"> 43</span></a> &lt;a href=&quot;#navigation&quot;&gt;Naviguer sur un site web&lt;/a&gt; pendant le test <a name="l44"><span class="linenum"> 44</span></a> &lt;/li&gt; <a name="l45"><span class="linenum"> 45</span></a> &lt;li&gt; <a name="l46"><span class="linenum"> 46</span></a> Méthodes pour &lt;a href=&quot;#requete&quot;&gt;modifier une requête&lt;/a&gt; et pour déboguer <a name="l47"><span class="linenum"> 47</span></a> &lt;/li&gt; <a name="l48"><span class="linenum"> 48</span></a> &lt;/ul&gt; <a name="l49"><span class="linenum"> 49</span></a> &lt;div class=&quot;content&quot;&gt; <a name="l50"><span class="linenum"> 50</span></a> &lt;h2&gt; <a name="l51"><span class="linenum"> 51</span></a> &lt;a class=&quot;target&quot; name=&quot;telecharger&quot;&gt;&lt;/a&gt;Télécharger une page&lt;/h2&gt; <a name="l52"><span class="linenum"> 52</span></a> &lt;p&gt; <a name="l53"><span class="linenum"> 53</span></a> Tester des classes c'est très bien. <a name="l54"><span class="linenum"> 54</span></a> Reste que PHP est avant tout un langage <a name="l55"><span class="linenum"> 55</span></a> pour créer des fonctionnalités à l'intérieur de pages web. <a name="l56"><span class="linenum"> 56</span></a> Comment pouvons tester la partie de devant <a name="l57"><span class="linenum"> 57</span></a> -- celle de l'interface -- dans nos applications en PHP ? <a name="l58"><span class="linenum"> 58</span></a> Etant donné qu'une page web n'est constituée que de texte, <a name="l59"><span class="linenum"> 59</span></a> nous devrions pouvoir les examiner exactement <a name="l60"><span class="linenum"> 60</span></a> comme n'importe quelle autre donnée de test. <a name="l61"><span class="linenum"> 61</span></a> &lt;/p&gt; <a name="l62"><span class="linenum"> 62</span></a> &lt;p&gt; <a name="l63"><span class="linenum"> 63</span></a> Cela nous amène à une situation délicate. <a name="l64"><span class="linenum"> 64</span></a> Si nous testons dans un niveau trop bas, <a name="l65"><span class="linenum"> 65</span></a> vérifier des balises avec un motif ad hoc par exemple, <a name="l66"><span class="linenum"> 66</span></a> nos tests seront trop fragiles. Le moindre changement <a name="l67"><span class="linenum"> 67</span></a> dans la présentation pourrait casser un grand nombre de test. <a name="l68"><span class="linenum"> 68</span></a> Si nos tests sont situés trop haut, en utilisant <a name="l69"><span class="linenum"> 69</span></a> une version fantaisie du moteur de template pour <a name="l70"><span class="linenum"> 70</span></a> donner un cas précis, alors nous perdons complètement <a name="l71"><span class="linenum"> 71</span></a> la capacité à automatiser certaines classes de test. <a name="l72"><span class="linenum"> 72</span></a> Par exemple, l'interaction entre des formulaires <a name="l73"><span class="linenum"> 73</span></a> et la navigation devra être testé manuellement. <a name="l74"><span class="linenum"> 74</span></a> Ces types de test sont extrêmement fastidieux <a name="l75"><span class="linenum"> 75</span></a> et plutôt sensibles aux erreurs. <a name="l76"><span class="linenum"> 76</span></a> &lt;/p&gt; <a name="l77"><span class="linenum"> 77</span></a> &lt;p&gt; <a name="l78"><span class="linenum"> 78</span></a> SimpleTest comprend une forme spéciale de scénario <a name="l79"><span class="linenum"> 79</span></a> de test pour tester les actions d'une page web. <a name="l80"><span class="linenum"> 80</span></a> &lt;span class=&quot;new_code&quot;&gt;WebTestCase&lt;/span&gt; inclut des facilités pour la navigation, <a name="l81"><span class="linenum"> 81</span></a> des vérifications sur le contenu <a name="l82"><span class="linenum"> 82</span></a> et les cookies ainsi que la gestion des formulaires. <a name="l83"><span class="linenum"> 83</span></a> Utiliser ces scénarios de test ressemble <a name="l84"><span class="linenum"> 84</span></a> fortement à &lt;span class=&quot;new_code&quot;&gt;UnitTestCase&lt;/span&gt;... <a name="l85"><span class="linenum"> 85</span></a> &lt;pre&gt; <a name="l86"><span class="linenum"> 86</span></a> &lt;strong&gt;<span class="keyword">class </span><a class="class" onClick="logClass('TestOfLastcraft')" href="../../../../_classes/testoflastcraft.html" onMouseOver="classPopup(event,'testoflastcraft')">TestOfLastcraft</a> <span class="keyword">extends</span> <a class="class" onClick="logClass('WebTestCase')" href="../../../../_classes/webtestcase.html" onMouseOver="classPopup(event,'webtestcase')">WebTestCase</a> { <a name="l87"><span class="linenum"> 87</span></a> }&lt;/strong&gt; <a name="l88"><span class="linenum"> 88</span></a> &lt;/pre&gt; <a name="l89"><span class="linenum"> 89</span></a> Ici nous sommes sur le point de tester <a name="l90"><span class="linenum"> 90</span></a> le site de &lt;a href=&quot;http://www.lastcraft.com/&quot;&gt;Last Craft&lt;/a&gt;. <a name="l91"><span class="linenum"> 91</span></a> Si ce scénario de test est situé dans un fichier appelé <a name="l92"><span class="linenum"> 92</span></a> &lt;em&gt;lastcraft_test.php&lt;/em&gt; alors il peut être chargé <a name="l93"><span class="linenum"> 93</span></a> dans un script de lancement tout comme des tests unitaires... <a name="l94"><span class="linenum"> 94</span></a> &lt;pre&gt; <a name="l95"><span class="linenum"> 95</span></a> &amp;lt;?php <a name="l96"><span class="linenum"> 96</span></a> require_once('simpletest/autorun.php');&lt;strong&gt; <a name="l97"><span class="linenum"> 97</span></a> require_once('simpletest/web_tester.php');&lt;/strong&gt; <a name="l98"><span class="linenum"> 98</span></a> <a class="class" onClick="logClass('SimpleTest')" href="../../../../_classes/simpletest.html" onMouseOver="classPopup(event,'simpletest')">SimpleTest</a>::<a class="function" onClick="logFunction('prefer')" href="../../../../_functions/prefer.html" onMouseOver="funcPopup(event,'prefer')">prefer</a>(<span class="keyword">new </span><a class="class" onClick="logClass('TextReporter')" href="../../../../_classes/textreporter.html" onMouseOver="classPopup(event,'textreporter')">TextReporter</a>()); <a name="l99"><span class="linenum"> 99</span></a> <a name="l100"><span class="linenum"> 100</span></a> <span class="keyword">class </span><a class="class" onClick="logClass('WebTests')" href="../../../../_classes/webtests.html" onMouseOver="classPopup(event,'webtests')">WebTests</a> <span class="keyword">extends</span> <a class="class" onClick="logClass('TestSuite')" href="../../../../_classes/testsuite.html" onMouseOver="classPopup(event,'testsuite')">TestSuite</a> { <a name="l101"><span class="linenum"> 101</span></a> function <a class="function" onClick="logFunction('WebTests')" href="../../../../_functions/webtests.html" onMouseOver="funcPopup(event,'webtests')">WebTests</a>() { <a name="l102"><span class="linenum"> 102</span></a> <a class="var it7" onMouseOver="hilite(7)" onMouseOut="lolite()" onClick="logVariable('this')" href="../../../../_variables/this.html">$this</a>-&amp;gt;<a class="function" onClick="logFunction('TestSuite')" href="../../../../_functions/testsuite.html" onMouseOver="funcPopup(event,'testsuite')">TestSuite</a>('Web site tests');&lt;strong&gt; <a name="l103"><span class="linenum"> 103</span></a> <a class="var it7" onMouseOver="hilite(7)" onMouseOut="lolite()" onClick="logVariable('this')" href="../../../../_variables/this.html">$this</a>-&amp;gt;<a class="function" onClick="logFunction('addFile')" href="../../../../_functions/addfile.html" onMouseOver="funcPopup(event,'addfile')">addFile</a>('lastcraft_test.php');&lt;/strong&gt; <a name="l104"><span class="linenum"> 104</span></a> } <a name="l105"><span class="linenum"> 105</span></a> } <a name="l106"><span class="linenum"> 106</span></a> ?&amp;gt; <a name="l107"><span class="linenum"> 107</span></a> &lt;/pre&gt; <a name="l108"><span class="linenum"> 108</span></a> J'utilise ici le rapporteur en mode texte <a name="l109"><span class="linenum"> 109</span></a> pour mieux distinguer le contenu au format HTML <a name="l110"><span class="linenum"> 110</span></a> du résultat du test proprement dit. <a name="l111"><span class="linenum"> 111</span></a> &lt;/p&gt; <a name="l112"><span class="linenum"> 112</span></a> &lt;p&gt; <a name="l113"><span class="linenum"> 113</span></a> Rien n'est encore testé. Nous pouvons télécharger <a name="l114"><span class="linenum"> 114</span></a> la page d'accueil en utilisant la méthode &lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('get')" href="../../../../_functions/get.html" onMouseOver="funcPopup(event,'get')">get</a>()&lt;/span&gt;... <a name="l115"><span class="linenum"> 115</span></a> &lt;pre&gt; <a name="l116"><span class="linenum"> 116</span></a> <span class="keyword">class </span><a class="class" onClick="logClass('TestOfLastcraft')" href="../../../../_classes/testoflastcraft.html" onMouseOver="classPopup(event,'testoflastcraft')">TestOfLastcraft</a> <span class="keyword">extends</span> <a class="class" onClick="logClass('WebTestCase')" href="../../../../_classes/webtestcase.html" onMouseOver="classPopup(event,'webtestcase')">WebTestCase</a> { <a name="l117"><span class="linenum"> 117</span></a> &lt;strong&gt; <a name="l118"><span class="linenum"> 118</span></a> function <a class="function" onClick="logFunction('testHomepage')" href="../../../../_functions/testhomepage.html" onMouseOver="funcPopup(event,'testhomepage')">testHomepage</a>() { <a name="l119"><span class="linenum"> 119</span></a> <a class="var it7" onMouseOver="hilite(7)" onMouseOut="lolite()" onClick="logVariable('this')" href="../../../../_variables/this.html">$this</a>-&amp;gt;<a class="function" onClick="logFunction('assertTrue')" href="../../../../_functions/asserttrue.html" onMouseOver="funcPopup(event,'asserttrue')">assertTrue</a>(<a class="var it7" onMouseOver="hilite(7)" onMouseOut="lolite()" onClick="logVariable('this')" href="../../../../_variables/this.html">$this</a>-&amp;gt;<a class="function" onClick="logFunction('get')" href="../../../../_functions/get.html" onMouseOver="funcPopup(event,'get')">get</a>('http://www.lastcraft.com/')); <a name="l120"><span class="linenum"> 120</span></a> }&lt;/strong&gt; <a name="l121"><span class="linenum"> 121</span></a> } <a name="l122"><span class="linenum"> 122</span></a> &lt;/pre&gt; <a name="l123"><span class="linenum"> 123</span></a> La méthode &lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('get')" href="../../../../_functions/get.html" onMouseOver="funcPopup(event,'get')">get</a>()&lt;/span&gt; renverra &quot;true&quot; <a name="l124"><span class="linenum"> 124</span></a> uniquement si le contenu de la page a bien été téléchargé. <a name="l125"><span class="linenum"> 125</span></a> C'est un moyen simple, mais efficace pour vérifier <a name="l126"><span class="linenum"> 126</span></a> qu'une page web a bien été délivré par le serveur web. <a name="l127"><span class="linenum"> 127</span></a> Cependant le contenu peut révéler être une erreur 404 <a name="l128"><span class="linenum"> 128</span></a> et dans ce cas notre méthode &lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('get')" href="../../../../_functions/get.html" onMouseOver="funcPopup(event,'get')">get</a>()&lt;/span&gt; renverrait encore un succès. <a name="l129"><span class="linenum"> 129</span></a> &lt;/p&gt; <a name="l130"><span class="linenum"> 130</span></a> &lt;p&gt; <a name="l131"><span class="linenum"> 131</span></a> En supposant que le serveur web pour le site Last Craft <a name="l132"><span class="linenum"> 132</span></a> soit opérationnel (malheureusement ce n'est pas toujours le cas), <a name="l133"><span class="linenum"> 133</span></a> nous devrions voir... <a name="l134"><span class="linenum"> 134</span></a> &lt;pre class=&quot;shell&quot;&gt; <a name="l135"><span class="linenum"> 135</span></a> Web site tests <a name="l136"><span class="linenum"> 136</span></a> OK <a name="l137"><span class="linenum"> 137</span></a> Test cases run: 1/1, Failures: 0, Exceptions: 0 <a name="l138"><span class="linenum"> 138</span></a> &lt;/pre&gt; <a name="l139"><span class="linenum"> 139</span></a> Nous avons vérifié qu'une page, de n'importe quel type, <a name="l140"><span class="linenum"> 140</span></a> a bien été renvoyée. Nous ne savons pas encore <a name="l141"><span class="linenum"> 141</span></a> s'il s'agit de celle que nous souhaitions. <a name="l142"><span class="linenum"> 142</span></a> &lt;/p&gt; <a name="l143"><span class="linenum"> 143</span></a> <a name="l144"><span class="linenum"> 144</span></a> &lt;h2&gt; <a name="l145"><span class="linenum"> 145</span></a> &lt;a class=&quot;target&quot; name=&quot;contenu&quot;&gt;&lt;/a&gt;Tester le contenu d'une page&lt;/h2&gt; <a name="l146"><span class="linenum"> 146</span></a> &lt;p&gt; <a name="l147"><span class="linenum"> 147</span></a> Pour obtenir la confirmation que la page téléchargée <a name="l148"><span class="linenum"> 148</span></a> est bien celle que nous attendions, <a name="l149"><span class="linenum"> 149</span></a> nous devons vérifier son contenu. <a name="l150"><span class="linenum"> 150</span></a> &lt;pre&gt; <a name="l151"><span class="linenum"> 151</span></a> <span class="keyword">class </span><a class="class" onClick="logClass('TestOfLastcraft')" href="../../../../_classes/testoflastcraft.html" onMouseOver="classPopup(event,'testoflastcraft')">TestOfLastcraft</a> <span class="keyword">extends</span> <a class="class" onClick="logClass('WebTestCase')" href="../../../../_classes/webtestcase.html" onMouseOver="classPopup(event,'webtestcase')">WebTestCase</a> { <a name="l152"><span class="linenum"> 152</span></a> <a name="l153"><span class="linenum"> 153</span></a> function <a class="function" onClick="logFunction('testHomepage')" href="../../../../_functions/testhomepage.html" onMouseOver="funcPopup(event,'testhomepage')">testHomepage</a>() {&lt;strong&gt; <a name="l154"><span class="linenum"> 154</span></a> <a class="var it7" onMouseOver="hilite(7)" onMouseOut="lolite()" onClick="logVariable('this')" href="../../../../_variables/this.html">$this</a>-&amp;gt;<a class="function" onClick="logFunction('get')" href="../../../../_functions/get.html" onMouseOver="funcPopup(event,'get')">get</a>('http://www.lastcraft.com/'); <a name="l155"><span class="linenum"> 155</span></a> <a class="var it7" onMouseOver="hilite(7)" onMouseOut="lolite()" onClick="logVariable('this')" href="../../../../_variables/this.html">$this</a>-&amp;gt;assertWantedPattern('/why the last craft/i');&lt;/strong&gt; <a name="l156"><span class="linenum"> 156</span></a> } <a name="l157"><span class="linenum"> 157</span></a> } <a name="l158"><span class="linenum"> 158</span></a> &lt;/pre&gt; <a name="l159"><span class="linenum"> 159</span></a> La page obtenue par le dernier téléchargement est <a name="l160"><span class="linenum"> 160</span></a> placée dans un buffer au sein même du scénario de test. <a name="l161"><span class="linenum"> 161</span></a> Il n'est donc pas nécessaire de s'y référer directement. <a name="l162"><span class="linenum"> 162</span></a> La correspondance du motif est toujours effectuée <a name="l163"><span class="linenum"> 163</span></a> par rapport à ce buffer. <a name="l164"><span class="linenum"> 164</span></a> &lt;/p&gt; <a name="l165"><span class="linenum"> 165</span></a> &lt;p&gt; <a name="l166"><span class="linenum"> 166</span></a> Voici une liste possible d'assertions sur le contenu... <a name="l167"><span class="linenum"> 167</span></a> &lt;table&gt;&lt;tbody&gt; <a name="l168"><span class="linenum"> 168</span></a> &lt;tr&gt; <a name="l169"><span class="linenum"> 169</span></a> &lt;td&gt;&lt;span class=&quot;new_code&quot;&gt;assertWantedPattern(<a class="var it943" onMouseOver="hilite(943)" onMouseOut="lolite()" onClick="logVariable('pattern')" href="../../../../_variables/pattern.html">$pattern</a>)&lt;/span&gt;&lt;/td&gt; <a name="l170"><span class="linenum"> 170</span></a> &lt;td&gt;Vérifier une correspondance sur le contenu via une expression rationnelle Perl&lt;/td&gt; <a name="l171"><span class="linenum"> 171</span></a> &lt;/tr&gt; <a name="l172"><span class="linenum"> 172</span></a> &lt;tr&gt; <a name="l173"><span class="linenum"> 173</span></a> &lt;td&gt;&lt;span class=&quot;new_code&quot;&gt;assertNoUnwantedPattern(<a class="var it943" onMouseOver="hilite(943)" onMouseOut="lolite()" onClick="logVariable('pattern')" href="../../../../_variables/pattern.html">$pattern</a>)&lt;/span&gt;&lt;/td&gt; <a name="l174"><span class="linenum"> 174</span></a> &lt;td&gt;Une expression rationnelle Perl pour vérifier une absence&lt;/td&gt; <a name="l175"><span class="linenum"> 175</span></a> &lt;/tr&gt; <a name="l176"><span class="linenum"> 176</span></a> &lt;tr&gt; <a name="l177"><span class="linenum"> 177</span></a> &lt;td&gt;&lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('assertTitle')" href="../../../../_functions/asserttitle.html" onMouseOver="funcPopup(event,'asserttitle')">assertTitle</a>(<a class="var it756" onMouseOver="hilite(756)" onMouseOut="lolite()" onClick="logVariable('title')" href="../../../../_variables/title.html">$title</a>)&lt;/span&gt;&lt;/td&gt; <a name="l178"><span class="linenum"> 178</span></a> &lt;td&gt;Passe si le titre de la page correspond exactement&lt;/td&gt; <a name="l179"><span class="linenum"> 179</span></a> &lt;/tr&gt; <a name="l180"><span class="linenum"> 180</span></a> &lt;tr&gt; <a name="l181"><span class="linenum"> 181</span></a> &lt;td&gt;&lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('assertLink')" href="../../../../_functions/assertlink.html" onMouseOver="funcPopup(event,'assertlink')">assertLink</a>(<a class="var it106" onMouseOver="hilite(106)" onMouseOut="lolite()" onClick="logVariable('label')" href="../../../../_variables/label.html">$label</a>)&lt;/span&gt;&lt;/td&gt; <a name="l182"><span class="linenum"> 182</span></a> &lt;td&gt;Passe si un lien avec ce texte est présent&lt;/td&gt; <a name="l183"><span class="linenum"> 183</span></a> &lt;/tr&gt; <a name="l184"><span class="linenum"> 184</span></a> &lt;tr&gt; <a name="l185"><span class="linenum"> 185</span></a> &lt;td&gt;&lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('assertNoLink')" href="../../../../_functions/assertnolink.html" onMouseOver="funcPopup(event,'assertnolink')">assertNoLink</a>(<a class="var it106" onMouseOver="hilite(106)" onMouseOut="lolite()" onClick="logVariable('label')" href="../../../../_variables/label.html">$label</a>)&lt;/span&gt;&lt;/td&gt; <a name="l186"><span class="linenum"> 186</span></a> &lt;td&gt;Passe si aucun lien avec ce texte est présent&lt;/td&gt; <a name="l187"><span class="linenum"> 187</span></a> &lt;/tr&gt; <a name="l188"><span class="linenum"> 188</span></a> &lt;tr&gt; <a name="l189"><span class="linenum"> 189</span></a> &lt;td&gt;&lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('assertLinkById')" href="../../../../_functions/assertlinkbyid.html" onMouseOver="funcPopup(event,'assertlinkbyid')">assertLinkById</a>(<a class="var it36" onMouseOver="hilite(36)" onMouseOut="lolite()" onClick="logVariable('id')" href="../../../../_variables/id.html">$id</a>)&lt;/span&gt;&lt;/td&gt; <a name="l190"><span class="linenum"> 190</span></a> &lt;td&gt;Passe si un lien avec cet attribut d'identification est présent&lt;/td&gt; <a name="l191"><span class="linenum"> 191</span></a> &lt;/tr&gt; <a name="l192"><span class="linenum"> 192</span></a> &lt;tr&gt; <a name="l193"><span class="linenum"> 193</span></a> &lt;td&gt;&lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('assertField')" href="../../../../_functions/assertfield.html" onMouseOver="funcPopup(event,'assertfield')">assertField</a>(<a class="var it74" onMouseOver="hilite(74)" onMouseOut="lolite()" onClick="logVariable('name')" href="../../../../_variables/name.html">$name</a>, <a class="var it67" onMouseOver="hilite(67)" onMouseOut="lolite()" onClick="logVariable('value')" href="../../../../_variables/value.html">$value</a>)&lt;/span&gt;&lt;/td&gt; <a name="l194"><span class="linenum"> 194</span></a> &lt;td&gt;Passe si une balise input avec ce nom contient cette valeur&lt;/td&gt; <a name="l195"><span class="linenum"> 195</span></a> &lt;/tr&gt; <a name="l196"><span class="linenum"> 196</span></a> &lt;tr&gt; <a name="l197"><span class="linenum"> 197</span></a> &lt;td&gt;&lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('assertFieldById')" href="../../../../_functions/assertfieldbyid.html" onMouseOver="funcPopup(event,'assertfieldbyid')">assertFieldById</a>(<a class="var it36" onMouseOver="hilite(36)" onMouseOut="lolite()" onClick="logVariable('id')" href="../../../../_variables/id.html">$id</a>, <a class="var it67" onMouseOver="hilite(67)" onMouseOut="lolite()" onClick="logVariable('value')" href="../../../../_variables/value.html">$value</a>)&lt;/span&gt;&lt;/td&gt; <a name="l198"><span class="linenum"> 198</span></a> &lt;td&gt;Passe si une balise input avec cet identifiant contient cette valeur&lt;/td&gt; <a name="l199"><span class="linenum"> 199</span></a> &lt;/tr&gt; <a name="l200"><span class="linenum"> 200</span></a> &lt;tr&gt; <a name="l201"><span class="linenum"> 201</span></a> &lt;td&gt;&lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('assertResponse')" href="../../../../_functions/assertresponse.html" onMouseOver="funcPopup(event,'assertresponse')">assertResponse</a>(<a class="var it944" onMouseOver="hilite(944)" onMouseOut="lolite()" onClick="logVariable('codes')" href="../../../../_variables/codes.html">$codes</a>)&lt;/span&gt;&lt;/td&gt; <a name="l202"><span class="linenum"> 202</span></a> &lt;td&gt;Passe si la réponse HTTP trouve une correspondance dans la liste&lt;/td&gt; <a name="l203"><span class="linenum"> 203</span></a> &lt;/tr&gt; <a name="l204"><span class="linenum"> 204</span></a> &lt;tr&gt; <a name="l205"><span class="linenum"> 205</span></a> &lt;td&gt;&lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('assertMime')" href="../../../../_functions/assertmime.html" onMouseOver="funcPopup(event,'assertmime')">assertMime</a>(<a class="var it945" onMouseOver="hilite(945)" onMouseOut="lolite()" onClick="logVariable('types')" href="../../../../_variables/types.html">$types</a>)&lt;/span&gt;&lt;/td&gt; <a name="l206"><span class="linenum"> 206</span></a> &lt;td&gt;Passe si le type MIME se retrouve dans cette liste&lt;/td&gt; <a name="l207"><span class="linenum"> 207</span></a> &lt;/tr&gt; <a name="l208"><span class="linenum"> 208</span></a> &lt;tr&gt; <a name="l209"><span class="linenum"> 209</span></a> &lt;td&gt;&lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('assertAuthentication')" href="../../../../_functions/assertauthentication.html" onMouseOver="funcPopup(event,'assertauthentication')">assertAuthentication</a>(<a class="var it197" onMouseOver="hilite(197)" onMouseOut="lolite()" onClick="logVariable('protocol')" href="../../../../_variables/protocol.html">$protocol</a>)&lt;/span&gt;&lt;/td&gt; <a name="l210"><span class="linenum"> 210</span></a> &lt;td&gt;Passe si l'authentification provoquée est de ce type de protocole&lt;/td&gt; <a name="l211"><span class="linenum"> 211</span></a> &lt;/tr&gt; <a name="l212"><span class="linenum"> 212</span></a> &lt;tr&gt; <a name="l213"><span class="linenum"> 213</span></a> &lt;td&gt;&lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('assertNoAuthentication')" href="../../../../_functions/assertnoauthentication.html" onMouseOver="funcPopup(event,'assertnoauthentication')">assertNoAuthentication</a>()&lt;/span&gt;&lt;/td&gt; <a name="l214"><span class="linenum"> 214</span></a> &lt;td&gt;Passe s'il n'y pas d'authentification provoquée en cours&lt;/td&gt; <a name="l215"><span class="linenum"> 215</span></a> &lt;/tr&gt; <a name="l216"><span class="linenum"> 216</span></a> &lt;tr&gt; <a name="l217"><span class="linenum"> 217</span></a> &lt;td&gt;&lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('assertRealm')" href="../../../../_functions/assertrealm.html" onMouseOver="funcPopup(event,'assertrealm')">assertRealm</a>(<a class="var it74" onMouseOver="hilite(74)" onMouseOut="lolite()" onClick="logVariable('name')" href="../../../../_variables/name.html">$name</a>)&lt;/span&gt;&lt;/td&gt; <a name="l218"><span class="linenum"> 218</span></a> &lt;td&gt;Passe si le domaine provoqué correspond&lt;/td&gt; <a name="l219"><span class="linenum"> 219</span></a> &lt;/tr&gt; <a name="l220"><span class="linenum"> 220</span></a> &lt;tr&gt; <a name="l221"><span class="linenum"> 221</span></a> &lt;td&gt;&lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('assertHeader')" href="../../../../_functions/assertheader.html" onMouseOver="funcPopup(event,'assertheader')">assertHeader</a>(<a class="var it251" onMouseOver="hilite(251)" onMouseOut="lolite()" onClick="logVariable('header')" href="../../../../_variables/header.html">$header</a>, <a class="var it603" onMouseOver="hilite(603)" onMouseOut="lolite()" onClick="logVariable('content')" href="../../../../_variables/content.html">$content</a>)&lt;/span&gt;&lt;/td&gt; <a name="l222"><span class="linenum"> 222</span></a> &lt;td&gt;Passe si une entête téléchargée correspond à cette valeur&lt;/td&gt; <a name="l223"><span class="linenum"> 223</span></a> &lt;/tr&gt; <a name="l224"><span class="linenum"> 224</span></a> &lt;tr&gt; <a name="l225"><span class="linenum"> 225</span></a> &lt;td&gt;&lt;span class=&quot;new_code&quot;&gt;assertNoUnwantedHeader(<a class="var it251" onMouseOver="hilite(251)" onMouseOut="lolite()" onClick="logVariable('header')" href="../../../../_variables/header.html">$header</a>)&lt;/span&gt;&lt;/td&gt; <a name="l226"><span class="linenum"> 226</span></a> &lt;td&gt;Passe si une entête n'a pas été téléchargé&lt;/td&gt; <a name="l227"><span class="linenum"> 227</span></a> &lt;/tr&gt; <a name="l228"><span class="linenum"> 228</span></a> &lt;tr&gt; <a name="l229"><span class="linenum"> 229</span></a> &lt;td&gt;&lt;span class=&quot;new_code&quot;&gt;assertHeaderPattern(<a class="var it251" onMouseOver="hilite(251)" onMouseOut="lolite()" onClick="logVariable('header')" href="../../../../_variables/header.html">$header</a>, <a class="var it943" onMouseOver="hilite(943)" onMouseOut="lolite()" onClick="logVariable('pattern')" href="../../../../_variables/pattern.html">$pattern</a>)&lt;/span&gt;&lt;/td&gt; <a name="l230"><span class="linenum"> 230</span></a> &lt;td&gt;Passe si une entête téléchargée correspond à cette expression rationnelle Perl&lt;/td&gt; <a name="l231"><span class="linenum"> 231</span></a> &lt;/tr&gt; <a name="l232"><span class="linenum"> 232</span></a> &lt;tr&gt; <a name="l233"><span class="linenum"> 233</span></a> &lt;td&gt;&lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('assertCookie')" href="../../../../_functions/assertcookie.html" onMouseOver="funcPopup(event,'assertcookie')">assertCookie</a>(<a class="var it74" onMouseOver="hilite(74)" onMouseOut="lolite()" onClick="logVariable('name')" href="../../../../_variables/name.html">$name</a>, <a class="var it67" onMouseOver="hilite(67)" onMouseOut="lolite()" onClick="logVariable('value')" href="../../../../_variables/value.html">$value</a>)&lt;/span&gt;&lt;/td&gt; <a name="l234"><span class="linenum"> 234</span></a> &lt;td&gt;Passe s'il existe un cookie correspondant&lt;/td&gt; <a name="l235"><span class="linenum"> 235</span></a> &lt;/tr&gt; <a name="l236"><span class="linenum"> 236</span></a> &lt;tr&gt; <a name="l237"><span class="linenum"> 237</span></a> &lt;td&gt;&lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('assertNoCookie')" href="../../../../_functions/assertnocookie.html" onMouseOver="funcPopup(event,'assertnocookie')">assertNoCookie</a>(<a class="var it74" onMouseOver="hilite(74)" onMouseOut="lolite()" onClick="logVariable('name')" href="../../../../_variables/name.html">$name</a>)&lt;/span&gt;&lt;/td&gt; <a name="l238"><span class="linenum"> 238</span></a> &lt;td&gt;Passe s'il n'y a pas de cookie avec un tel nom&lt;/td&gt; <a name="l239"><span class="linenum"> 239</span></a> &lt;/tr&gt; <a name="l240"><span class="linenum"> 240</span></a> &lt;/tbody&gt;&lt;/table&gt; <a name="l241"><span class="linenum"> 241</span></a> Comme d'habitude avec les assertions de SimpleTest, <a name="l242"><span class="linenum"> 242</span></a> elles renvoient toutes &quot;false&quot; en cas d'échec <a name="l243"><span class="linenum"> 243</span></a> et &quot;true&quot; si c'est un succès. <a name="l244"><span class="linenum"> 244</span></a> Elles renvoient aussi un message de test optionnel : <a name="l245"><span class="linenum"> 245</span></a> vous pouvez l'ajouter dans votre propre message en utilisant &quot;%s&quot;. <a name="l246"><span class="linenum"> 246</span></a> &lt;/p&gt; <a name="l247"><span class="linenum"> 247</span></a> &lt;p&gt; <a name="l248"><span class="linenum"> 248</span></a> A présent nous pourrions effectué le test sur le titre uniquement... <a name="l249"><span class="linenum"> 249</span></a> &lt;pre&gt; <a name="l250"><span class="linenum"> 250</span></a> &lt;strong&gt;<a class="var it7" onMouseOver="hilite(7)" onMouseOut="lolite()" onClick="logVariable('this')" href="../../../../_variables/this.html">$this</a>-&amp;gt;<a class="function" onClick="logFunction('assertTitle')" href="../../../../_functions/asserttitle.html" onMouseOver="funcPopup(event,'asserttitle')">assertTitle</a>('The Last Craft?');&lt;/strong&gt; <a name="l251"><span class="linenum"> 251</span></a> &lt;/pre&gt; <a name="l252"><span class="linenum"> 252</span></a> En plus d'une simple vérification sur le contenu HTML, <a name="l253"><span class="linenum"> 253</span></a> nous pouvons aussi vérifier que le type MIME est bien d'un type acceptable... <a name="l254"><span class="linenum"> 254</span></a> &lt;pre&gt; <a name="l255"><span class="linenum"> 255</span></a> &lt;strong&gt;<a class="var it7" onMouseOver="hilite(7)" onMouseOut="lolite()" onClick="logVariable('this')" href="../../../../_variables/this.html">$this</a>-&amp;gt;<a class="function" onClick="logFunction('assertMime')" href="../../../../_functions/assertmime.html" onMouseOver="funcPopup(event,'assertmime')">assertMime</a>(array('text/plain', 'text/html'));&lt;/strong&gt; <a name="l256"><span class="linenum"> 256</span></a> &lt;/pre&gt; <a name="l257"><span class="linenum"> 257</span></a> Plus intéressant encore est la vérification sur <a name="l258"><span class="linenum"> 258</span></a> le code de la réponse HTTP. Pareillement au type MIME, <a name="l259"><span class="linenum"> 259</span></a> nous pouvons nous assurer que le code renvoyé se trouve <a name="l260"><span class="linenum"> 260</span></a> bien dans un liste de valeurs possibles... <a name="l261"><span class="linenum"> 261</span></a> &lt;pre&gt; <a name="l262"><span class="linenum"> 262</span></a> <span class="keyword">class </span><a class="class" onClick="logClass('TestOfLastcraft')" href="../../../../_classes/testoflastcraft.html" onMouseOver="classPopup(event,'testoflastcraft')">TestOfLastcraft</a> <span class="keyword">extends</span> <a class="class" onClick="logClass('WebTestCase')" href="../../../../_classes/webtestcase.html" onMouseOver="classPopup(event,'webtestcase')">WebTestCase</a> { <a name="l263"><span class="linenum"> 263</span></a> <a name="l264"><span class="linenum"> 264</span></a> function <a class="function" onClick="logFunction('testHomepage')" href="../../../../_functions/testhomepage.html" onMouseOver="funcPopup(event,'testhomepage')">testHomepage</a>() { <a name="l265"><span class="linenum"> 265</span></a> <a class="var it7" onMouseOver="hilite(7)" onMouseOut="lolite()" onClick="logVariable('this')" href="../../../../_variables/this.html">$this</a>-&amp;gt;<a class="function" onClick="logFunction('get')" href="../../../../_functions/get.html" onMouseOver="funcPopup(event,'get')">get</a>('http://simpletest.sourceforge.net/');&lt;strong&gt; <a name="l266"><span class="linenum"> 266</span></a> <a class="var it7" onMouseOver="hilite(7)" onMouseOut="lolite()" onClick="logVariable('this')" href="../../../../_variables/this.html">$this</a>-&amp;gt;<a class="function" onClick="logFunction('assertResponse')" href="../../../../_functions/assertresponse.html" onMouseOver="funcPopup(event,'assertresponse')">assertResponse</a>(200);&lt;/strong&gt; <a name="l267"><span class="linenum"> 267</span></a> } <a name="l268"><span class="linenum"> 268</span></a> } <a name="l269"><span class="linenum"> 269</span></a> &lt;/pre&gt; <a name="l270"><span class="linenum"> 270</span></a> Ici nous vérifions que le téléchargement s'est <a name="l271"><span class="linenum"> 271</span></a> bien terminé en ne permettant qu'une réponse HTTP 200. <a name="l272"><span class="linenum"> 272</span></a> Ce test passera, mais ce n'est pas la meilleure façon de procéder. <a name="l273"><span class="linenum"> 273</span></a> Il n'existe aucune page sur &lt;em&gt;http://simpletest.sourceforge.net/&lt;/em&gt;, <a name="l274"><span class="linenum"> 274</span></a> à la place le serveur renverra une redirection vers <a name="l275"><span class="linenum"> 275</span></a> &lt;em&gt;http://www.lastcraft.com/simple_test.php&lt;/em&gt;. <a name="l276"><span class="linenum"> 276</span></a> &lt;span class=&quot;new_code&quot;&gt;WebTestCase&lt;/span&gt; suit automatiquement trois <a name="l277"><span class="linenum"> 277</span></a> de ces redirections. Les tests sont quelque peu plus <a name="l278"><span class="linenum"> 278</span></a> robustes de la sorte. Surtout qu'on est souvent plus intéressé <a name="l279"><span class="linenum"> 279</span></a> par l'interaction entre les pages que de leur simple livraison. <a name="l280"><span class="linenum"> 280</span></a> Si les redirections se révèlent être digne d'intérêt, <a name="l281"><span class="linenum"> 281</span></a> il reste possible de les supprimer... <a name="l282"><span class="linenum"> 282</span></a> &lt;pre&gt; <a name="l283"><span class="linenum"> 283</span></a> <span class="keyword">class </span><a class="class" onClick="logClass('TestOfLastcraft')" href="../../../../_classes/testoflastcraft.html" onMouseOver="classPopup(event,'testoflastcraft')">TestOfLastcraft</a> <span class="keyword">extends</span> <a class="class" onClick="logClass('WebTestCase')" href="../../../../_classes/webtestcase.html" onMouseOver="classPopup(event,'webtestcase')">WebTestCase</a> { <a name="l284"><span class="linenum"> 284</span></a> <a name="l285"><span class="linenum"> 285</span></a> function <a class="function" onClick="logFunction('testHomepage')" href="../../../../_functions/testhomepage.html" onMouseOver="funcPopup(event,'testhomepage')">testHomepage</a>() {&lt;strong&gt; <a name="l286"><span class="linenum"> 286</span></a> <a class="var it7" onMouseOver="hilite(7)" onMouseOut="lolite()" onClick="logVariable('this')" href="../../../../_variables/this.html">$this</a>-&amp;gt;<a class="function" onClick="logFunction('setMaximumRedirects')" href="../../../../_functions/setmaximumredirects.html" onMouseOver="funcPopup(event,'setmaximumredirects')">setMaximumRedirects</a>(0);&lt;/strong&gt; <a name="l287"><span class="linenum"> 287</span></a> <a class="var it7" onMouseOver="hilite(7)" onMouseOut="lolite()" onClick="logVariable('this')" href="../../../../_variables/this.html">$this</a>-&amp;gt;<a class="function" onClick="logFunction('get')" href="../../../../_functions/get.html" onMouseOver="funcPopup(event,'get')">get</a>('http://simpletest.sourceforge.net/'); <a name="l288"><span class="linenum"> 288</span></a> <a class="var it7" onMouseOver="hilite(7)" onMouseOut="lolite()" onClick="logVariable('this')" href="../../../../_variables/this.html">$this</a>-&amp;gt;<a class="function" onClick="logFunction('assertResponse')" href="../../../../_functions/assertresponse.html" onMouseOver="funcPopup(event,'assertresponse')">assertResponse</a>(200); <a name="l289"><span class="linenum"> 289</span></a> } <a name="l290"><span class="linenum"> 290</span></a> } <a name="l291"><span class="linenum"> 291</span></a> &lt;/pre&gt; <a name="l292"><span class="linenum"> 292</span></a> Alors l'assertion échoue comme prévue... <a name="l293"><span class="linenum"> 293</span></a> &lt;pre class=&quot;shell&quot;&gt; <a name="l294"><span class="linenum"> 294</span></a> Web site tests <a name="l295"><span class="linenum"> 295</span></a> 1) Expecting response in [200] got [302] <a name="l296"><span class="linenum"> 296</span></a> in testhomepage <a name="l297"><span class="linenum"> 297</span></a> in testoflastcraft <a name="l298"><span class="linenum"> 298</span></a> in lastcraft_test.php <a name="l299"><span class="linenum"> 299</span></a> FAILURES!!! <a name="l300"><span class="linenum"> 300</span></a> Test cases run: 1/1, Failures: 1, Exceptions: 0 <a name="l301"><span class="linenum"> 301</span></a> &lt;/pre&gt; <a name="l302"><span class="linenum"> 302</span></a> Nous pouvons modifier le test pour accepter les redirections... <a name="l303"><span class="linenum"> 303</span></a> &lt;pre&gt; <a name="l304"><span class="linenum"> 304</span></a> <span class="keyword">class </span><a class="class" onClick="logClass('TestOfLastcraft')" href="../../../../_classes/testoflastcraft.html" onMouseOver="classPopup(event,'testoflastcraft')">TestOfLastcraft</a> <span class="keyword">extends</span> <a class="class" onClick="logClass('WebTestCase')" href="../../../../_classes/webtestcase.html" onMouseOver="classPopup(event,'webtestcase')">WebTestCase</a> { <a name="l305"><span class="linenum"> 305</span></a> <a name="l306"><span class="linenum"> 306</span></a> function <a class="function" onClick="logFunction('testHomepage')" href="../../../../_functions/testhomepage.html" onMouseOver="funcPopup(event,'testhomepage')">testHomepage</a>() { <a name="l307"><span class="linenum"> 307</span></a> <a class="var it7" onMouseOver="hilite(7)" onMouseOut="lolite()" onClick="logVariable('this')" href="../../../../_variables/this.html">$this</a>-&amp;gt;<a class="function" onClick="logFunction('setMaximumRedirects')" href="../../../../_functions/setmaximumredirects.html" onMouseOver="funcPopup(event,'setmaximumredirects')">setMaximumRedirects</a>(0); <a name="l308"><span class="linenum"> 308</span></a> <a class="var it7" onMouseOver="hilite(7)" onMouseOut="lolite()" onClick="logVariable('this')" href="../../../../_variables/this.html">$this</a>-&amp;gt;<a class="function" onClick="logFunction('get')" href="../../../../_functions/get.html" onMouseOver="funcPopup(event,'get')">get</a>('http://simpletest.sourceforge.net/'); <a name="l309"><span class="linenum"> 309</span></a> <a class="var it7" onMouseOver="hilite(7)" onMouseOut="lolite()" onClick="logVariable('this')" href="../../../../_variables/this.html">$this</a>-&amp;gt;<a class="function" onClick="logFunction('assertResponse')" href="../../../../_functions/assertresponse.html" onMouseOver="funcPopup(event,'assertresponse')">assertResponse</a>(&lt;strong&gt;array(301, 302, 303, 307)&lt;/strong&gt;); <a name="l310"><span class="linenum"> 310</span></a> } <a name="l311"><span class="linenum"> 311</span></a> } <a name="l312"><span class="linenum"> 312</span></a> &lt;/pre&gt; <a name="l313"><span class="linenum"> 313</span></a> Maitenant ça passe. <a name="l314"><span class="linenum"> 314</span></a> &lt;/p&gt; <a name="l315"><span class="linenum"> 315</span></a> <a name="l316"><span class="linenum"> 316</span></a> &lt;h2&gt; <a name="l317"><span class="linenum"> 317</span></a> &lt;a class=&quot;target&quot; name=&quot;navigation&quot;&gt;&lt;/a&gt;Navigeur dans un site web&lt;/h2&gt; <a name="l318"><span class="linenum"> 318</span></a> &lt;p&gt; <a name="l319"><span class="linenum"> 319</span></a> Les utilisateurs ne naviguent pas souvent en tapant les URLs, <a name="l320"><span class="linenum"> 320</span></a> mais surtout en cliquant sur des liens et des boutons. <a name="l321"><span class="linenum"> 321</span></a> Ici nous confirmons que les informations sur le contact <a name="l322"><span class="linenum"> 322</span></a> peuvent être atteintes depuis la page d'accueil... <a name="l323"><span class="linenum"> 323</span></a> &lt;pre&gt; <a name="l324"><span class="linenum"> 324</span></a> <span class="keyword">class </span><a class="class" onClick="logClass('TestOfLastcraft')" href="../../../../_classes/testoflastcraft.html" onMouseOver="classPopup(event,'testoflastcraft')">TestOfLastcraft</a> <span class="keyword">extends</span> <a class="class" onClick="logClass('WebTestCase')" href="../../../../_classes/webtestcase.html" onMouseOver="classPopup(event,'webtestcase')">WebTestCase</a> { <a name="l325"><span class="linenum"> 325</span></a> ... <a name="l326"><span class="linenum"> 326</span></a> function <a class="function" onClick="logFunction('testContact')" href="../../../../_functions/testcontact.html" onMouseOver="funcPopup(event,'testcontact')">testContact</a>() { <a name="l327"><span class="linenum"> 327</span></a> <a class="var it7" onMouseOver="hilite(7)" onMouseOut="lolite()" onClick="logVariable('this')" href="../../../../_variables/this.html">$this</a>-&amp;gt;<a class="function" onClick="logFunction('get')" href="../../../../_functions/get.html" onMouseOver="funcPopup(event,'get')">get</a>('http://www.lastcraft.com/');&lt;strong&gt; <a name="l328"><span class="linenum"> 328</span></a> <a class="var it7" onMouseOver="hilite(7)" onMouseOut="lolite()" onClick="logVariable('this')" href="../../../../_variables/this.html">$this</a>-&amp;gt;<a class="function" onClick="logFunction('clickLink')" href="../../../../_functions/clicklink.html" onMouseOver="funcPopup(event,'clicklink')">clickLink</a>('About'); <a name="l329"><span class="linenum"> 329</span></a> <a class="var it7" onMouseOver="hilite(7)" onMouseOut="lolite()" onClick="logVariable('this')" href="../../../../_variables/this.html">$this</a>-&amp;gt;<a class="function" onClick="logFunction('assertTitle')" href="../../../../_functions/asserttitle.html" onMouseOver="funcPopup(event,'asserttitle')">assertTitle</a>('About Last Craft');&lt;/strong&gt; <a name="l330"><span class="linenum"> 330</span></a> } <a name="l331"><span class="linenum"> 331</span></a> } <a name="l332"><span class="linenum"> 332</span></a> &lt;/pre&gt; <a name="l333"><span class="linenum"> 333</span></a> Le paramètre est le texte du lien. <a name="l334"><span class="linenum"> 334</span></a> &lt;/p&gt; <a name="l335"><span class="linenum"> 335</span></a> &lt;p&gt; <a name="l336"><span class="linenum"> 336</span></a> Il l'objectif est un bouton plutôt qu'une balise ancre, <a name="l337"><span class="linenum"> 337</span></a> alors &lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('clickSubmit')" href="../../../../_functions/clicksubmit.html" onMouseOver="funcPopup(event,'clicksubmit')">clickSubmit</a>()&lt;/span&gt; doit être utilisé avec <a name="l338"><span class="linenum"> 338</span></a> le titre du bouton... <a name="l339"><span class="linenum"> 339</span></a> &lt;pre&gt; <a name="l340"><span class="linenum"> 340</span></a> &lt;strong&gt;<a class="var it7" onMouseOver="hilite(7)" onMouseOut="lolite()" onClick="logVariable('this')" href="../../../../_variables/this.html">$this</a>-&amp;gt;<a class="function" onClick="logFunction('clickSubmit')" href="../../../../_functions/clicksubmit.html" onMouseOver="funcPopup(event,'clicksubmit')">clickSubmit</a>('Go!');&lt;/strong&gt; <a name="l341"><span class="linenum"> 341</span></a> &lt;/pre&gt; <a name="l342"><span class="linenum"> 342</span></a> &lt;/p&gt; <a name="l343"><span class="linenum"> 343</span></a> &lt;p&gt; <a name="l344"><span class="linenum"> 344</span></a> La liste des méthodes de navigation est... <a name="l345"><span class="linenum"> 345</span></a> &lt;table&gt;&lt;tbody&gt; <a name="l346"><span class="linenum"> 346</span></a> &lt;tr&gt; <a name="l347"><span class="linenum"> 347</span></a> &lt;td&gt;&lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('get')" href="../../../../_functions/get.html" onMouseOver="funcPopup(event,'get')">get</a>(<a class="var it333" onMouseOver="hilite(333)" onMouseOut="lolite()" onClick="logVariable('url')" href="../../../../_variables/url.html">$url</a>, <a class="var it670" onMouseOver="hilite(670)" onMouseOut="lolite()" onClick="logVariable('parameters')" href="../../../../_variables/parameters.html">$parameters</a>)&lt;/span&gt;&lt;/td&gt; <a name="l348"><span class="linenum"> 348</span></a> &lt;td&gt;Envoie une requête GET avec ces paramètres&lt;/td&gt; <a name="l349"><span class="linenum"> 349</span></a> &lt;/tr&gt; <a name="l350"><span class="linenum"> 350</span></a> &lt;tr&gt; <a name="l351"><span class="linenum"> 351</span></a> &lt;td&gt;&lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('post')" href="../../../../_functions/post.html" onMouseOver="funcPopup(event,'post')">post</a>(<a class="var it333" onMouseOver="hilite(333)" onMouseOut="lolite()" onClick="logVariable('url')" href="../../../../_variables/url.html">$url</a>, <a class="var it670" onMouseOver="hilite(670)" onMouseOut="lolite()" onClick="logVariable('parameters')" href="../../../../_variables/parameters.html">$parameters</a>)&lt;/span&gt;&lt;/td&gt; <a name="l352"><span class="linenum"> 352</span></a> &lt;td&gt;Envoie une requête POST avec ces paramètres&lt;/td&gt; <a name="l353"><span class="linenum"> 353</span></a> &lt;/tr&gt; <a name="l354"><span class="linenum"> 354</span></a> &lt;tr&gt; <a name="l355"><span class="linenum"> 355</span></a> &lt;td&gt;&lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('head')" href="../../../../_functions/head.html" onMouseOver="funcPopup(event,'head')">head</a>(<a class="var it333" onMouseOver="hilite(333)" onMouseOut="lolite()" onClick="logVariable('url')" href="../../../../_variables/url.html">$url</a>, <a class="var it670" onMouseOver="hilite(670)" onMouseOut="lolite()" onClick="logVariable('parameters')" href="../../../../_variables/parameters.html">$parameters</a>)&lt;/span&gt;&lt;/td&gt; <a name="l356"><span class="linenum"> 356</span></a> &lt;td&gt;Envoie une requête HEAD sans remplacer le contenu de la page&lt;/td&gt; <a name="l357"><span class="linenum"> 357</span></a> &lt;/tr&gt; <a name="l358"><span class="linenum"> 358</span></a> &lt;tr&gt; <a name="l359"><span class="linenum"> 359</span></a> &lt;td&gt;&lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('retry')" href="../../../../_functions/retry.html" onMouseOver="funcPopup(event,'retry')">retry</a>()&lt;/span&gt;&lt;/td&gt; <a name="l360"><span class="linenum"> 360</span></a> &lt;td&gt;Relance la dernière requête&lt;/td&gt; <a name="l361"><span class="linenum"> 361</span></a> &lt;/tr&gt; <a name="l362"><span class="linenum"> 362</span></a> &lt;tr&gt; <a name="l363"><span class="linenum"> 363</span></a> &lt;td&gt;&lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('back')" href="../../../../_functions/back.html" onMouseOver="funcPopup(event,'back')">back</a>()&lt;/span&gt;&lt;/td&gt; <a name="l364"><span class="linenum"> 364</span></a> &lt;td&gt;Identique au bouton &quot;Précédent&quot; du navigateur&lt;/td&gt; <a name="l365"><span class="linenum"> 365</span></a> &lt;/tr&gt; <a name="l366"><span class="linenum"> 366</span></a> &lt;tr&gt; <a name="l367"><span class="linenum"> 367</span></a> &lt;td&gt;&lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('forward')" href="../../../../_functions/forward.html" onMouseOver="funcPopup(event,'forward')">forward</a>()&lt;/span&gt;&lt;/td&gt; <a name="l368"><span class="linenum"> 368</span></a> &lt;td&gt;Identique au bouton &quot;Suivant&quot; du navigateur&lt;/td&gt; <a name="l369"><span class="linenum"> 369</span></a> &lt;/tr&gt; <a name="l370"><span class="linenum"> 370</span></a> &lt;tr&gt; <a name="l371"><span class="linenum"> 371</span></a> &lt;td&gt;&lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('authenticate')" href="../../../../_functions/authenticate.html" onMouseOver="funcPopup(event,'authenticate')">authenticate</a>(<a class="var it74" onMouseOver="hilite(74)" onMouseOut="lolite()" onClick="logVariable('name')" href="../../../../_variables/name.html">$name</a>, <a class="var it11" onMouseOver="hilite(11)" onMouseOut="lolite()" onClick="logVariable('password')" href="../../../../_variables/password.html">$password</a>)&lt;/span&gt;&lt;/td&gt; <a name="l372"><span class="linenum"> 372</span></a> &lt;td&gt;Re-essaye avec une tentative d'authentification&lt;/td&gt; <a name="l373"><span class="linenum"> 373</span></a> &lt;/tr&gt; <a name="l374"><span class="linenum"> 374</span></a> &lt;tr&gt; <a name="l375"><span class="linenum"> 375</span></a> &lt;td&gt;&lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('getFrameFocus')" href="../../../../_functions/getframefocus.html" onMouseOver="funcPopup(event,'getframefocus')">getFrameFocus</a>()&lt;/span&gt;&lt;/td&gt; <a name="l376"><span class="linenum"> 376</span></a> &lt;td&gt;Le nom de la fenêtre en cours d'utilisation&lt;/td&gt; <a name="l377"><span class="linenum"> 377</span></a> &lt;/tr&gt; <a name="l378"><span class="linenum"> 378</span></a> &lt;tr&gt; <a name="l379"><span class="linenum"> 379</span></a> &lt;td&gt;&lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('setFrameFocusByIndex')" href="../../../../_functions/setframefocusbyindex.html" onMouseOver="funcPopup(event,'setframefocusbyindex')">setFrameFocusByIndex</a>(<a class="var it904" onMouseOver="hilite(904)" onMouseOut="lolite()" onClick="logVariable('choice')" href="../../../../_variables/choice.html">$choice</a>)&lt;/span&gt;&lt;/td&gt; <a name="l380"><span class="linenum"> 380</span></a> &lt;td&gt;Change le focus d'une fenêtre en commençant par 1&lt;/td&gt; <a name="l381"><span class="linenum"> 381</span></a> &lt;/tr&gt; <a name="l382"><span class="linenum"> 382</span></a> &lt;tr&gt; <a name="l383"><span class="linenum"> 383</span></a> &lt;td&gt;&lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('setFrameFocus')" href="../../../../_functions/setframefocus.html" onMouseOver="funcPopup(event,'setframefocus')">setFrameFocus</a>(<a class="var it74" onMouseOver="hilite(74)" onMouseOut="lolite()" onClick="logVariable('name')" href="../../../../_variables/name.html">$name</a>)&lt;/span&gt;&lt;/td&gt; <a name="l384"><span class="linenum"> 384</span></a> &lt;td&gt;Change le focus d'une fenêtre en utilisant son nom&lt;/td&gt; <a name="l385"><span class="linenum"> 385</span></a> &lt;/tr&gt; <a name="l386"><span class="linenum"> 386</span></a> &lt;tr&gt; <a name="l387"><span class="linenum"> 387</span></a> &lt;td&gt;&lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('clearFrameFocus')" href="../../../../_functions/clearframefocus.html" onMouseOver="funcPopup(event,'clearframefocus')">clearFrameFocus</a>()&lt;/span&gt;&lt;/td&gt; <a name="l388"><span class="linenum"> 388</span></a> &lt;td&gt;Revient à un traitement de toutes les fenêtres comme une seule&lt;/td&gt; <a name="l389"><span class="linenum"> 389</span></a> &lt;/tr&gt; <a name="l390"><span class="linenum"> 390</span></a> &lt;tr&gt; <a name="l391"><span class="linenum"> 391</span></a> &lt;td&gt;&lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('clickSubmit')" href="../../../../_functions/clicksubmit.html" onMouseOver="funcPopup(event,'clicksubmit')">clickSubmit</a>(<a class="var it106" onMouseOver="hilite(106)" onMouseOut="lolite()" onClick="logVariable('label')" href="../../../../_variables/label.html">$label</a>)&lt;/span&gt;&lt;/td&gt; <a name="l392"><span class="linenum"> 392</span></a> &lt;td&gt;Clique sur le premier bouton avec cette étiquette&lt;/td&gt; <a name="l393"><span class="linenum"> 393</span></a> &lt;/tr&gt; <a name="l394"><span class="linenum"> 394</span></a> &lt;tr&gt; <a name="l395"><span class="linenum"> 395</span></a> &lt;td&gt;&lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('clickSubmitByName')" href="../../../../_functions/clicksubmitbyname.html" onMouseOver="funcPopup(event,'clicksubmitbyname')">clickSubmitByName</a>(<a class="var it74" onMouseOver="hilite(74)" onMouseOut="lolite()" onClick="logVariable('name')" href="../../../../_variables/name.html">$name</a>)&lt;/span&gt;&lt;/td&gt; <a name="l396"><span class="linenum"> 396</span></a> &lt;td&gt;Clique sur le bouton avec cet attribut de nom&lt;/td&gt; <a name="l397"><span class="linenum"> 397</span></a> &lt;/tr&gt; <a name="l398"><span class="linenum"> 398</span></a> &lt;tr&gt; <a name="l399"><span class="linenum"> 399</span></a> &lt;td&gt;&lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('clickSubmitById')" href="../../../../_functions/clicksubmitbyid.html" onMouseOver="funcPopup(event,'clicksubmitbyid')">clickSubmitById</a>(<a class="var it36" onMouseOver="hilite(36)" onMouseOut="lolite()" onClick="logVariable('id')" href="../../../../_variables/id.html">$id</a>)&lt;/span&gt;&lt;/td&gt; <a name="l400"><span class="linenum"> 400</span></a> &lt;td&gt;Clique sur le bouton avec cet attribut d'identification&lt;/td&gt; <a name="l401"><span class="linenum"> 401</span></a> &lt;/tr&gt; <a name="l402"><span class="linenum"> 402</span></a> &lt;tr&gt; <a name="l403"><span class="linenum"> 403</span></a> &lt;td&gt;&lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('clickImage')" href="../../../../_functions/clickimage.html" onMouseOver="funcPopup(event,'clickimage')">clickImage</a>(<a class="var it106" onMouseOver="hilite(106)" onMouseOut="lolite()" onClick="logVariable('label')" href="../../../../_variables/label.html">$label</a>, <a class="var it259" onMouseOver="hilite(259)" onMouseOut="lolite()" onClick="logVariable('x')" href="../../../../_variables/x.html">$x</a>, <a class="var it903" onMouseOver="hilite(903)" onMouseOut="lolite()" onClick="logVariable('y')" href="../../../../_variables/y.html">$y</a>)&lt;/span&gt;&lt;/td&gt; <a name="l404"><span class="linenum"> 404</span></a> &lt;td&gt;Clique sur une balise input de type image par son titre (title=&quot;*&quot;) our son texte alternatif (alt=&quot;*&quot;)&lt;/td&gt; <a name="l405"><span class="linenum"> 405</span></a> &lt;/tr&gt; <a name="l406"><span class="linenum"> 406</span></a> &lt;tr&gt; <a name="l407"><span class="linenum"> 407</span></a> &lt;td&gt;&lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('clickImageByName')" href="../../../../_functions/clickimagebyname.html" onMouseOver="funcPopup(event,'clickimagebyname')">clickImageByName</a>(<a class="var it74" onMouseOver="hilite(74)" onMouseOut="lolite()" onClick="logVariable('name')" href="../../../../_variables/name.html">$name</a>, <a class="var it259" onMouseOver="hilite(259)" onMouseOut="lolite()" onClick="logVariable('x')" href="../../../../_variables/x.html">$x</a>, <a class="var it903" onMouseOver="hilite(903)" onMouseOut="lolite()" onClick="logVariable('y')" href="../../../../_variables/y.html">$y</a>)&lt;/span&gt;&lt;/td&gt; <a name="l408"><span class="linenum"> 408</span></a> &lt;td&gt;Clique sur une balise input de type image par son attribut (name=&quot;*&quot;)&lt;/td&gt; <a name="l409"><span class="linenum"> 409</span></a> &lt;/tr&gt; <a name="l410"><span class="linenum"> 410</span></a> &lt;tr&gt; <a name="l411"><span class="linenum"> 411</span></a> &lt;td&gt;&lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('clickImageById')" href="../../../../_functions/clickimagebyid.html" onMouseOver="funcPopup(event,'clickimagebyid')">clickImageById</a>(<a class="var it36" onMouseOver="hilite(36)" onMouseOut="lolite()" onClick="logVariable('id')" href="../../../../_variables/id.html">$id</a>, <a class="var it259" onMouseOver="hilite(259)" onMouseOut="lolite()" onClick="logVariable('x')" href="../../../../_variables/x.html">$x</a>, <a class="var it903" onMouseOver="hilite(903)" onMouseOut="lolite()" onClick="logVariable('y')" href="../../../../_variables/y.html">$y</a>)&lt;/span&gt;&lt;/td&gt; <a name="l412"><span class="linenum"> 412</span></a> &lt;td&gt;Clique sur une balise input de type image par son identifiant (id=&quot;*&quot;)&lt;/td&gt; <a name="l413"><span class="linenum"> 413</span></a> &lt;/tr&gt; <a name="l414"><span class="linenum"> 414</span></a> &lt;tr&gt; <a name="l415"><span class="linenum"> 415</span></a> &lt;td&gt;&lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('submitFormById')" href="../../../../_functions/submitformbyid.html" onMouseOver="funcPopup(event,'submitformbyid')">submitFormById</a>(<a class="var it36" onMouseOver="hilite(36)" onMouseOut="lolite()" onClick="logVariable('id')" href="../../../../_variables/id.html">$id</a>)&lt;/span&gt;&lt;/td&gt; <a name="l416"><span class="linenum"> 416</span></a> &lt;td&gt;Soumet un formulaire sans valeur de soumission&lt;/td&gt; <a name="l417"><span class="linenum"> 417</span></a> &lt;/tr&gt; <a name="l418"><span class="linenum"> 418</span></a> &lt;tr&gt; <a name="l419"><span class="linenum"> 419</span></a> &lt;td&gt;&lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('clickLink')" href="../../../../_functions/clicklink.html" onMouseOver="funcPopup(event,'clicklink')">clickLink</a>(<a class="var it106" onMouseOver="hilite(106)" onMouseOut="lolite()" onClick="logVariable('label')" href="../../../../_variables/label.html">$label</a>, <a class="var it370" onMouseOver="hilite(370)" onMouseOut="lolite()" onClick="logVariable('index')" href="../../../../_variables/index.html">$index</a>)&lt;/span&gt;&lt;/td&gt; <a name="l420"><span class="linenum"> 420</span></a> &lt;td&gt;Clique sur une ancre avec ce texte d'étiquette visible&lt;/td&gt; <a name="l421"><span class="linenum"> 421</span></a> &lt;/tr&gt; <a name="l422"><span class="linenum"> 422</span></a> &lt;tr&gt; <a name="l423"><span class="linenum"> 423</span></a> &lt;td&gt;&lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('clickLinkById')" href="../../../../_functions/clicklinkbyid.html" onMouseOver="funcPopup(event,'clicklinkbyid')">clickLinkById</a>(<a class="var it36" onMouseOver="hilite(36)" onMouseOut="lolite()" onClick="logVariable('id')" href="../../../../_variables/id.html">$id</a>)&lt;/span&gt;&lt;/td&gt; <a name="l424"><span class="linenum"> 424</span></a> &lt;td&gt;Clique sur une ancre avec cet attribut d'identification&lt;/td&gt; <a name="l425"><span class="linenum"> 425</span></a> &lt;/tr&gt; <a name="l426"><span class="linenum"> 426</span></a> &lt;/tbody&gt;&lt;/table&gt; <a name="l427"><span class="linenum"> 427</span></a> &lt;/p&gt; <a name="l428"><span class="linenum"> 428</span></a> &lt;p&gt; <a name="l429"><span class="linenum"> 429</span></a> Les paramètres dans les méthodes &lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('get')" href="../../../../_functions/get.html" onMouseOver="funcPopup(event,'get')">get</a>()&lt;/span&gt;, <a name="l430"><span class="linenum"> 430</span></a> &lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('post')" href="../../../../_functions/post.html" onMouseOver="funcPopup(event,'post')">post</a>()&lt;/span&gt; et &lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('head')" href="../../../../_functions/head.html" onMouseOver="funcPopup(event,'head')">head</a>()&lt;/span&gt; sont optionnels. <a name="l431"><span class="linenum"> 431</span></a> Le téléchargement via HTTP HEAD ne modifie pas <a name="l432"><span class="linenum"> 432</span></a> le contexte du navigateur, il se limite au chargement des cookies. <a name="l433"><span class="linenum"> 433</span></a> Cela peut être utilise lorsqu'une image ou une feuille de style <a name="l434"><span class="linenum"> 434</span></a> initie un cookie pour bloquer un robot trop entreprenant. <a name="l435"><span class="linenum"> 435</span></a> &lt;/p&gt; <a name="l436"><span class="linenum"> 436</span></a> &lt;p&gt; <a name="l437"><span class="linenum"> 437</span></a> Les commandes &lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('retry')" href="../../../../_functions/retry.html" onMouseOver="funcPopup(event,'retry')">retry</a>()&lt;/span&gt;, &lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('back')" href="../../../../_functions/back.html" onMouseOver="funcPopup(event,'back')">back</a>()&lt;/span&gt; <a name="l438"><span class="linenum"> 438</span></a> et &lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('forward')" href="../../../../_functions/forward.html" onMouseOver="funcPopup(event,'forward')">forward</a>()&lt;/span&gt; fonctionnent exactement comme <a name="l439"><span class="linenum"> 439</span></a> dans un navigateur. Elles utilisent l'historique pour <a name="l440"><span class="linenum"> 440</span></a> relancer les pages. Une technique bien pratique pour <a name="l441"><span class="linenum"> 441</span></a> vérifier les effets d'un bouton retour sur vos formulaires. <a name="l442"><span class="linenum"> 442</span></a> &lt;/p&gt; <a name="l443"><span class="linenum"> 443</span></a> &lt;p&gt; <a name="l444"><span class="linenum"> 444</span></a> Les méthodes sur les fenêtres méritent une petite explication. <a name="l445"><span class="linenum"> 445</span></a> Par défaut, une page avec des fenêtres est traitée comme toutes <a name="l446"><span class="linenum"> 446</span></a> les autres. Le contenu sera vérifié à travers l'ensemble de <a name="l447"><span class="linenum"> 447</span></a> la &quot;frameset&quot;, par conséquent un lien fonctionnera, <a name="l448"><span class="linenum"> 448</span></a> peu importe la fenêtre qui contient la balise ancre. <a name="l449"><span class="linenum"> 449</span></a> Vous pouvez outrepassé ce comportement en exigeant <a name="l450"><span class="linenum"> 450</span></a> le focus sur une unique fenêtre. Si vous réalisez cela, <a name="l451"><span class="linenum"> 451</span></a> toutes les recherches et toutes les actions se limiteront <a name="l452"><span class="linenum"> 452</span></a> à cette unique fenêtre, y compris les demandes d'authentification. <a name="l453"><span class="linenum"> 453</span></a> Si un lien ou un bouton n'est pas dans la fenêtre en focus alors <a name="l454"><span class="linenum"> 454</span></a> il ne peut pas être cliqué. <a name="l455"><span class="linenum"> 455</span></a> &lt;/p&gt; <a name="l456"><span class="linenum"> 456</span></a> &lt;p&gt; <a name="l457"><span class="linenum"> 457</span></a> Tester la navigation sur des pages fixes ne vous alerte que <a name="l458"><span class="linenum"> 458</span></a> quand vous avez cassé un script entier. <a name="l459"><span class="linenum"> 459</span></a> Pour des pages fortement dynamiques, <a name="l460"><span class="linenum"> 460</span></a> un forum de discussion par exemple, <a name="l461"><span class="linenum"> 461</span></a> ça peut être crucial pour vérifier l'état de l'application. <a name="l462"><span class="linenum"> 462</span></a> Pour la plupart des applications cependant, <a name="l463"><span class="linenum"> 463</span></a> la logique vraiment délicate se situe dans la gestion <a name="l464"><span class="linenum"> 464</span></a> des formulaires et des sessions. <a name="l465"><span class="linenum"> 465</span></a> Heureusement SimpleTest aussi inclut <a name="l466"><span class="linenum"> 466</span></a> &lt;a href=&quot;form_testing_documentation.html&quot;&gt; <a name="l467"><span class="linenum"> 467</span></a> des outils pour tester des formulaires web&lt;/a&gt;. <a name="l468"><span class="linenum"> 468</span></a> &lt;/p&gt; <a name="l469"><span class="linenum"> 469</span></a> <a name="l470"><span class="linenum"> 470</span></a> &lt;h2&gt; <a name="l471"><span class="linenum"> 471</span></a> &lt;a class=&quot;target&quot; name=&quot;requete&quot;&gt;&lt;/a&gt;Modifier la requête&lt;/h2&gt; <a name="l472"><span class="linenum"> 472</span></a> &lt;p&gt; <a name="l473"><span class="linenum"> 473</span></a> Bien que SimpleTest n'ait pas comme objectif <a name="l474"><span class="linenum"> 474</span></a> de contrôler des erreurs réseau, il contient quand même <a name="l475"><span class="linenum"> 475</span></a> des méthodes pour modifier et déboguer les requêtes qu'il lance. <a name="l476"><span class="linenum"> 476</span></a> Voici une autre liste de méthode... <a name="l477"><span class="linenum"> 477</span></a> &lt;table&gt;&lt;tbody&gt; <a name="l478"><span class="linenum"> 478</span></a> &lt;tr&gt; <a name="l479"><span class="linenum"> 479</span></a> &lt;td&gt;&lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('getTransportError')" href="../../../../_functions/gettransporterror.html" onMouseOver="funcPopup(event,'gettransporterror')">getTransportError</a>()&lt;/span&gt;&lt;/td&gt; <a name="l480"><span class="linenum"> 480</span></a> &lt;td&gt;La dernière erreur de socket&lt;/td&gt; <a name="l481"><span class="linenum"> 481</span></a> &lt;/tr&gt; <a name="l482"><span class="linenum"> 482</span></a> &lt;tr&gt; <a name="l483"><span class="linenum"> 483</span></a> &lt;td&gt;&lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('getUrl')" href="../../../../_functions/geturl.html" onMouseOver="funcPopup(event,'geturl')">getUrl</a>()&lt;/span&gt;&lt;/td&gt; <a name="l484"><span class="linenum"> 484</span></a> &lt;td&gt;La localisation courante&lt;/td&gt; <a name="l485"><span class="linenum"> 485</span></a> &lt;/tr&gt; <a name="l486"><span class="linenum"> 486</span></a> &lt;tr&gt; <a name="l487"><span class="linenum"> 487</span></a> &lt;td&gt;&lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('showRequest')" href="../../../../_functions/showrequest.html" onMouseOver="funcPopup(event,'showrequest')">showRequest</a>()&lt;/span&gt;&lt;/td&gt; <a name="l488"><span class="linenum"> 488</span></a> &lt;td&gt;Déverse la requête sortante&lt;/td&gt; <a name="l489"><span class="linenum"> 489</span></a> &lt;/tr&gt; <a name="l490"><span class="linenum"> 490</span></a> &lt;tr&gt; <a name="l491"><span class="linenum"> 491</span></a> &lt;td&gt;&lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('showHeaders')" href="../../../../_functions/showheaders.html" onMouseOver="funcPopup(event,'showheaders')">showHeaders</a>()&lt;/span&gt;&lt;/td&gt; <a name="l492"><span class="linenum"> 492</span></a> &lt;td&gt;Déverse les entêtes d'entrée&lt;/td&gt; <a name="l493"><span class="linenum"> 493</span></a> &lt;/tr&gt; <a name="l494"><span class="linenum"> 494</span></a> &lt;tr&gt; <a name="l495"><span class="linenum"> 495</span></a> &lt;td&gt;&lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('showSource')" href="../../../../_functions/showsource.html" onMouseOver="funcPopup(event,'showsource')">showSource</a>()&lt;/span&gt;&lt;/td&gt; <a name="l496"><span class="linenum"> 496</span></a> &lt;td&gt;Déverse le contenu brut de la page HTML&lt;/td&gt; <a name="l497"><span class="linenum"> 497</span></a> &lt;/tr&gt; <a name="l498"><span class="linenum"> 498</span></a> &lt;tr&gt; <a name="l499"><span class="linenum"> 499</span></a> &lt;td&gt;&lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('ignoreFrames')" href="../../../../_functions/ignoreframes.html" onMouseOver="funcPopup(event,'ignoreframes')">ignoreFrames</a>()&lt;/span&gt;&lt;/td&gt; <a name="l500"><span class="linenum"> 500</span></a> &lt;td&gt;Ne recharge pas les framesets&lt;/td&gt; <a name="l501"><span class="linenum"> 501</span></a> &lt;/tr&gt; <a name="l502"><span class="linenum"> 502</span></a> &lt;tr&gt; <a name="l503"><span class="linenum"> 503</span></a> &lt;td&gt;&lt;span class=&quot;new_code&quot;&gt;<a class="phpfunction" onClick="logFunction('setCookie')" href="../../../../_functions/setcookie.html" onMouseOver="phpfuncPopup(event,'setcookie')">setCookie</a>(<a class="var it74" onMouseOver="hilite(74)" onMouseOut="lolite()" onClick="logVariable('name')" href="../../../../_variables/name.html">$name</a>, <a class="var it67" onMouseOver="hilite(67)" onMouseOut="lolite()" onClick="logVariable('value')" href="../../../../_variables/value.html">$value</a>)&lt;/span&gt;&lt;/td&gt; <a name="l504"><span class="linenum"> 504</span></a> &lt;td&gt;Initie un cookie à partir de maintenant&lt;/td&gt; <a name="l505"><span class="linenum"> 505</span></a> &lt;/tr&gt; <a name="l506"><span class="linenum"> 506</span></a> &lt;tr&gt; <a name="l507"><span class="linenum"> 507</span></a> &lt;td&gt;&lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('addHeader')" href="../../../../_functions/addheader.html" onMouseOver="funcPopup(event,'addheader')">addHeader</a>(<a class="var it251" onMouseOver="hilite(251)" onMouseOut="lolite()" onClick="logVariable('header')" href="../../../../_variables/header.html">$header</a>)&lt;/span&gt;&lt;/td&gt; <a name="l508"><span class="linenum"> 508</span></a> &lt;td&gt;Ajoute toujours cette entête à la requête&lt;/td&gt; <a name="l509"><span class="linenum"> 509</span></a> &lt;/tr&gt; <a name="l510"><span class="linenum"> 510</span></a> &lt;tr&gt; <a name="l511"><span class="linenum"> 511</span></a> &lt;td&gt;&lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('setMaximumRedirects')" href="../../../../_functions/setmaximumredirects.html" onMouseOver="funcPopup(event,'setmaximumredirects')">setMaximumRedirects</a>(<a class="var it905" onMouseOver="hilite(905)" onMouseOut="lolite()" onClick="logVariable('max')" href="../../../../_variables/max.html">$max</a>)&lt;/span&gt;&lt;/td&gt; <a name="l512"><span class="linenum"> 512</span></a> &lt;td&gt;S'arrête après autant de redirections&lt;/td&gt; <a name="l513"><span class="linenum"> 513</span></a> &lt;/tr&gt; <a name="l514"><span class="linenum"> 514</span></a> &lt;tr&gt; <a name="l515"><span class="linenum"> 515</span></a> &lt;td&gt;&lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('setConnectionTimeout')" href="../../../../_functions/setconnectiontimeout.html" onMouseOver="funcPopup(event,'setconnectiontimeout')">setConnectionTimeout</a>(<a class="var it786" onMouseOver="hilite(786)" onMouseOut="lolite()" onClick="logVariable('timeout')" href="../../../../_variables/timeout.html">$timeout</a>)&lt;/span&gt;&lt;/td&gt; <a name="l516"><span class="linenum"> 516</span></a> &lt;td&gt;Termine la connexion après autant de temps entre les bytes&lt;/td&gt; <a name="l517"><span class="linenum"> 517</span></a> &lt;/tr&gt; <a name="l518"><span class="linenum"> 518</span></a> &lt;tr&gt; <a name="l519"><span class="linenum"> 519</span></a> &lt;td&gt;&lt;span class=&quot;new_code&quot;&gt;<a class="function" onClick="logFunction('useProxy')" href="../../../../_functions/useproxy.html" onMouseOver="funcPopup(event,'useproxy')">useProxy</a>(<a class="var it900" onMouseOver="hilite(900)" onMouseOut="lolite()" onClick="logVariable('proxy')" href="../../../../_variables/proxy.html">$proxy</a>, <a class="var it74" onMouseOver="hilite(74)" onMouseOut="lolite()" onClick="logVariable('name')" href="../../../../_variables/name.html">$name</a>, <a class="var it11" onMouseOver="hilite(11)" onMouseOut="lolite()" onClick="logVariable('password')" href="../../../../_variables/password.html">$password</a>)&lt;/span&gt;&lt;/td&gt; <a name="l520"><span class="linenum"> 520</span></a> &lt;td&gt;Effectue les requêtes à travers ce proxy d'URL&lt;/td&gt; <a name="l521"><span class="linenum"> 521</span></a> &lt;/tr&gt; <a name="l522"><span class="linenum"> 522</span></a> &lt;/tbody&gt;&lt;/table&gt; <a name="l523"><span class="linenum"> 523</span></a> &lt;/p&gt; <a name="l524"><span class="linenum"> 524</span></a> <a name="l525"><span class="linenum"> 525</span></a> &lt;/div&gt; <a name="l526"><span class="linenum"> 526</span></a> References and related information... <a name="l527"><span class="linenum"> 527</span></a> &lt;ul&gt; <a name="l528"><span class="linenum"> 528</span></a> &lt;li&gt; <a name="l529"><span class="linenum"> 529</span></a> La page du projet SimpleTest sur <a name="l530"><span class="linenum"> 530</span></a> &lt;a href=&quot;http://sourceforge.net/projects/simpletest/&quot;&gt;SourceForge&lt;/a&gt;. <a name="l531"><span class="linenum"> 531</span></a> &lt;/li&gt; <a name="l532"><span class="linenum"> 532</span></a> &lt;li&gt; <a name="l533"><span class="linenum"> 533</span></a> La page de téléchargement de SimpleTest sur <a name="l534"><span class="linenum"> 534</span></a> &lt;a href=&quot;http://www.lastcraft.com/simple_test.php&quot;&gt;LastCraft&lt;/a&gt;. <a name="l535"><span class="linenum"> 535</span></a> &lt;/li&gt; <a name="l536"><span class="linenum"> 536</span></a> &lt;li&gt; <a name="l537"><span class="linenum"> 537</span></a> &lt;a href=&quot;http://simpletest.org/api/&quot;&gt;L'API du développeur pour SimpleTest&lt;/a&gt; <a name="l538"><span class="linenum"> 538</span></a> donne tous les détails sur les classes et les assertions disponibles. <a name="l539"><span class="linenum"> 539</span></a> &lt;/li&gt; <a name="l540"><span class="linenum"> 540</span></a> &lt;/ul&gt; <a name="l541"><span class="linenum"> 541</span></a> &lt;div class=&quot;menu_back&quot;&gt;&lt;div class=&quot;menu&quot;&gt; <a name="l542"><span class="linenum"> 542</span></a> &lt;a href=&quot;index.html&quot;&gt;SimpleTest&lt;/a&gt; <a name="l543"><span class="linenum"> 543</span></a> | <a name="l544"><span class="linenum"> 544</span></a> &lt;a href=&quot;overview.html&quot;&gt;Overview&lt;/a&gt; <a name="l545"><span class="linenum"> 545</span></a> | <a name="l546"><span class="linenum"> 546</span></a> &lt;a href=&quot;unit_test_documentation.html&quot;&gt;Unit tester&lt;/a&gt; <a name="l547"><span class="linenum"> 547</span></a> | <a name="l548"><span class="linenum"> 548</span></a> &lt;a href=&quot;group_test_documentation.html&quot;&gt;Group tests&lt;/a&gt; <a name="l549"><span class="linenum"> 549</span></a> | <a name="l550"><span class="linenum"> 550</span></a> &lt;a href=&quot;mock_objects_documentation.html&quot;&gt;Mock objects&lt;/a&gt; <a name="l551"><span class="linenum"> 551</span></a> | <a name="l552"><span class="linenum"> 552</span></a> &lt;a href=&quot;partial_mocks_documentation.html&quot;&gt;Partial mocks&lt;/a&gt; <a name="l553"><span class="linenum"> 553</span></a> | <a name="l554"><span class="linenum"> 554</span></a> &lt;a href=&quot;reporter_documentation.html&quot;&gt;Reporting&lt;/a&gt; <a name="l555"><span class="linenum"> 555</span></a> | <a name="l556"><span class="linenum"> 556</span></a> &lt;a href=&quot;expectation_documentation.html&quot;&gt;Expectations&lt;/a&gt; <a name="l557"><span class="linenum"> 557</span></a> | <a name="l558"><span class="linenum"> 558</span></a> &lt;a href=&quot;web_tester_documentation.html&quot;&gt;Web tester&lt;/a&gt; <a name="l559"><span class="linenum"> 559</span></a> | <a name="l560"><span class="linenum"> 560</span></a> &lt;a href=&quot;form_testing_documentation.html&quot;&gt;Testing forms&lt;/a&gt; <a name="l561"><span class="linenum"> 561</span></a> | <a name="l562"><span class="linenum"> 562</span></a> &lt;a href=&quot;authentication_documentation.html&quot;&gt;Authentication&lt;/a&gt; <a name="l563"><span class="linenum"> 563</span></a> | <a name="l564"><span class="linenum"> 564</span></a> &lt;a href=&quot;browser_documentation.html&quot;&gt;Scriptable browser&lt;/a&gt; <a name="l565"><span class="linenum"> 565</span></a> &lt;/div&gt;&lt;/div&gt; <a name="l566"><span class="linenum"> 566</span></a> &lt;div class=&quot;copyright&quot;&gt; <a name="l567"><span class="linenum"> 567</span></a> Copyright&lt;br&gt;Marcus Baker 2006 <a name="l568"><span class="linenum"> 568</span></a> &lt;/div&gt; <a name="l569"><span class="linenum"> 569</span></a> &lt;/body&gt; <a name="l570"><span class="linenum"> 570</span></a> &lt;/html&gt; </pre> </div> <script language="JavaScript" type="text/javascript"> FUNC_DATA={ 'assertresponse': ['assertresponse', 'Checks the response code against a list of possible values. ', [['tests/simpletest','web_tester.php',1227]], 66], 'gettransporterror': ['gettransporterror', 'Gets the last response error. ', [['tests/simpletest','web_tester.php',518],['tests/simpletest','frames.php',230],['tests/simpletest','page.php',162],['tests/simpletest','browser.php',696]], 14], 'addheader': ['addheader', 'Adds a header to every fetch. ', [['tests/simpletest','web_tester.php',642],['tests/simpletest','user_agent.php',65],['tests/simpletest','browser.php',368]], 35], 'clicksubmitbyname': ['clicksubmitbyname', 'Clicks the submit button by name attribute. The owning form will be submitted by this. ', [['tests/simpletest','web_tester.php',905],['tests/simpletest','browser.php',909]], 11], 'forward': ['forward', 'Equivalent to hitting the forward button on the browser. ', [['tests/simpletest','web_tester.php',778],['tests/simpletest','browser.php',121],['tests/simpletest','browser.php',599]], 15], 'post': ['post', 'Fetch an item from the POST array ', [['bonfire/codeigniter/core','Input.php',164],['tests/simpletest','web_tester.php',703],['tests/simpletest','browser.php',507]], 194], 'setconnectiontimeout': ['setconnectiontimeout', 'Sets the socket timeout for opening a connection and receiving at least one byte of information. ', [['tests/simpletest','web_tester.php',666],['tests/simpletest','user_agent.php',143],['tests/simpletest','browser.php',446]], 9], 'assertlink': ['assertlink', 'Tests for the presence of a link label. Match is case insensitive with normalised space. ', [['tests/simpletest','web_tester.php',1043]], 13], 'clicksubmitbyid': ['clicksubmitbyid', 'Clicks the submit button by ID attribute. The owning form will be submitted by this. ', [['tests/simpletest','web_tester.php',918],['tests/simpletest','browser.php',927]], 9], 'assertfieldbyid': ['assertfieldbyid', 'Confirms that the form element is currently set to the expected value. A missing form will always fail. If no ID is given then only the existence of the field is checked. ', [['tests/simpletest','web_tester.php',1185]], 13], 'clickimagebyname': ['clickimagebyname', 'Clicks the submit image by the name. Usually the alt tag or the nearest equivalent. The owning form will be submitted by this. Clicking outside of the boundary of the coordinates will result in a failure. ', [['tests/simpletest','web_tester.php',961],['tests/simpletest','browser.php',979]], 7], 'assertcookie': ['assertcookie', 'Checks that a cookie is set for the current page and optionally checks the value. ', [['tests/simpletest','web_tester.php',1423]], 18], 'assertheader': ['assertheader', 'Checks each header line for the required value. If no value is given then only an existence check is made. ', [['tests/simpletest','web_tester.php',1314]], 7], 'useproxy': ['useproxy', 'Sets proxy to use on all requests for when testing from behind a firewall. Set URL to false to disable. ', [['tests/simpletest','web_tester.php',676],['tests/simpletest','simpletest.php',118],['tests/simpletest','user_agent.php',162],['tests/simpletest','browser.php',455]], 9], 'showheaders': ['showheaders', 'Dumps the current HTTP headers for debugging. ', [['tests/simpletest','web_tester.php',545]], 4], 'geturl': ['geturl', 'Resource name. ', [['tests/simpletest','http.php',35],['tests/simpletest','http.php',542],['tests/simpletest','web_tester.php',527],['tests/simpletest','frames.php',254],['tests/simpletest','page.php',135],['tests/simpletest','browser.php',81],['tests/simpletest','browser.php',743]], 44], 'clickimagebyid': ['clickimagebyid', 'Clicks the submit image by ID attribute. The owning form will be submitted by this. Clicking outside of the boundary of the coordinates will result in a failure. ', [['tests/simpletest','web_tester.php',979],['tests/simpletest','browser.php',1002]], 7], 'assertnolink': ['assertnolink', 'Tests for the non-presence of a link label. Match is case insensitive with normalised space. ', [['tests/simpletest','web_tester.php',1064]], 6], 'showsource': ['showsource', 'Dumps the current HTML source for debugging. ', [['tests/simpletest','web_tester.php',553]], 2], 'testcontact': ['testcontact', '', [['tests/simpletest/docs/en','web_tester_documentation.html',329],['tests/simpletest/docs/fr','web_tester_documentation.html',326]], 0], 'assertmime': ['assertmime', 'Checks the mime type against a list of possible values. ', [['tests/simpletest','web_tester.php',1244]], 5], 'head': ['head', 'Does a HTTP HEAD fetch, fetching only the page headers. The current base URL is unchanged by this. ', [['tests/simpletest','web_tester.php',745],['tests/simpletest','browser.php',468]], 9], 'prefer': ['prefer', 'Puts the object to the global pool of \'preferred\' objects which can be retrieved with SimpleTest :: preferred() method. Instances of the same class are overwritten. ', [['tests/simpletest','simpletest.php',69]], 4], 'assertauthentication': ['assertauthentication', 'Attempt to match the authentication type within the security realm we are currently matching. ', [['tests/simpletest','web_tester.php',1260]], 7], 'testhomepage': ['testhomepage', '', [['tests/simpletest/docs/en','web_tester_documentation.html',114],['tests/simpletest/docs/en','web_tester_documentation.html',148],['tests/simpletest/docs/en','web_tester_documentation.html',288],['tests/simpletest/docs/en','web_tester_documentation.html',309],['tests/simpletest/docs/fr','overview.html',81],['tests/simpletest/docs/fr','web_tester_documentation.html',118],['tests/simpletest/docs/fr','web_tester_documentation.html',153],['tests/simpletest/docs/fr','web_tester_documentation.html',264],['tests/simpletest/docs/fr','web_tester_documentation.html',285],['tests/simpletest/docs/fr','web_tester_documentation.html',306]], 0], 'assertnocookie': ['assertnocookie', 'Checks that no cookie is present or that it has been successfully cleared. ', [['tests/simpletest','web_tester.php',1446]], 11], 'clearframefocus': ['clearframefocus', 'Clears the frame focus. All frames will be searched for content. ', [['tests/simpletest','web_tester.php',859],['tests/simpletest','frames.php',152],['tests/simpletest','page.php',251],['tests/simpletest','browser.php',687]], 18], 'setmaximumredirects': ['setmaximumredirects', 'Sets the maximum number of redirects before the web page is loaded regardless. ', [['tests/simpletest','web_tester.php',652],['tests/simpletest','user_agent.php',152],['tests/simpletest','browser.php',426]], 19], 'retry': ['retry', 'Equivalent to hitting the retry button on the browser. Will attempt to repeat the page fetch. ', [['tests/simpletest','web_tester.php',757],['tests/simpletest','browser.php',555]], 27], 'clicklink': ['clicklink', 'Follows a link by name. Will click the first link found with this link text by default, or a later one if an index is given. Match is case insensitive with normalised space. ', [['tests/simpletest','web_tester.php',1019],['tests/simpletest','browser.php',1073]], 48], 'authenticate': ['authenticate', 'Retries a request after setting the authentication for the current realm. ', [['tests/simpletest','web_tester.php',789],['tests/simpletest','browser.php',619]], 19], 'assertnoauthentication': ['assertnoauthentication', 'Checks that no authentication is necessary to view the desired page. ', [['tests/simpletest','web_tester.php',1284]], 2], 'asserttrue': ['asserttrue', 'Called from within the test methods to register passes and failures. ', [['tests/simpletest','web_tester.php',1460],['tests/simpletest','unit_tester.php',39],['tests/simpletest/extensions','pear_test_case.php',114],['tests/simpletest','shell_tester.php',131]], 495], 'webtests': ['webtests', '', [['tests/simpletest/docs/en','web_tester_documentation.html',97],['tests/simpletest/docs/fr','web_tester_documentation.html',101]], 0], 'submitformbyid': ['submitformbyid', 'Submits a form by the ID. ', [['tests/simpletest','web_tester.php',1008],['tests/simpletest','browser.php',1035]], 6], 'assertfield': ['assertfield', 'Confirms that the form element is currently set to the expected value. A missing form will always fail. If no value is given then only the existence of the field is checked. ', [['tests/simpletest','web_tester.php',1149]], 57], 'clicklinkbyid': ['clicklinkbyid', 'Follows a link by id attribute. ', [['tests/simpletest','web_tester.php',1033],['tests/simpletest','browser.php',1102]], 8], 'get': ['get', 'Fetch from cache ', [['bonfire/libraries','BF_Cache_file.php',47],['tests/simpletest/docs/fr','mock_objects_documentation.html',310],['bonfire/codeigniter/database','DB_active_rec.php',937],['bonfire/libraries','JSMin.php',187],['bonfire/libraries','template.php',648],['bonfire/codeigniter/core','Input.php',136],['bonfire/codeigniter/libraries/Cache/drivers','Cache_apc.php',30],['tests/simpletest','web_tester.php',689],['tests/_support','database.php',31],['bonfire/codeigniter/libraries/Cache/drivers','Cache_memcached.php',42],['bonfire/codeigniter/libraries/Cache/drivers','Cache_file.php',47],['bonfire/codeigniter/libraries/Cache','Cache.php',54],['bonfire/codeigniter/libraries/Cache/drivers','Cache_dummy.php',30],['tests/simpletest/docs/en','mock_objects_documentation.html',291],['tests/simpletest','simpletest.php',299],['tests/simpletest','browser.php',489]], 432], 'showrequest': ['showrequest', 'Dumps the current request for debugging. ', [['tests/simpletest','web_tester.php',537]], 3], 'clickimage': ['clickimage', 'Clicks the submit image by some kind of label. Usually the alt tag or the nearest equivalent. The owning form will be submitted by this. Clicking outside of the boundary of the coordinates will result in a failure. ', [['tests/simpletest','web_tester.php',943],['tests/simpletest','browser.php',956]], 10], 'addfile': ['addfile', 'Builds a test suite from a library of test cases. The new suite is composed into this one. ', [['tests/simpletest','test_case.php',525]], 75], 'getframefocus': ['getframefocus', 'Accessor for current frame focus. Will be false if no frame has focus. ', [['tests/simpletest','web_tester.php',827],['tests/simpletest','frames.php',77],['tests/simpletest','page.php',221],['tests/simpletest','browser.php',655]], 24], 'back': ['back', 'Equivalent to hitting the back button on the browser. ', [['tests/simpletest','web_tester.php',767],['tests/simpletest','browser.php',107],['tests/simpletest','browser.php',579]], 19], 'setframefocusbyindex': ['setframefocusbyindex', 'Sets the focus by index. The integer index starts from 1. ', [['tests/simpletest','web_tester.php',839],['tests/simpletest','frames.php',110],['tests/simpletest','page.php',231],['tests/simpletest','browser.php',667]], 27], 'assertrealm': ['assertrealm', 'Attempts to match the current security realm. ', [['tests/simpletest','web_tester.php',1297]], 10], 'setframefocus': ['setframefocus', 'Sets the focus by name. ', [['tests/simpletest','web_tester.php',849],['tests/simpletest','frames.php',131],['tests/simpletest','page.php',241],['tests/simpletest','browser.php',677]], 62], 'clicksubmit': ['clicksubmit', 'Clicks the submit button by label. The owning form will be submitted by this. ', [['tests/simpletest','web_tester.php',891],['tests/simpletest','browser.php',890]], 65], 'ignoreframes': ['ignoreframes', 'Disables frames support. Frames will not be fetched and the frameset page will be used instead. ', [['tests/simpletest','web_tester.php',597],['tests/simpletest','browser.php',227]], 8], 'assertlinkbyid': ['assertlinkbyid', 'Tests for the presence of a link id attribute. ', [['tests/simpletest','web_tester.php',1080]], 3], 'testsuite': ['testsuite', 'Sets the name of the test suite. ', [['tests/simpletest','test_case.php',481]], 25], 'asserttitle': ['asserttitle', 'Tests the text between the title tags. ', [['tests/simpletest','web_tester.php',1347]], 49], 'setcookie': ['setcookie', '', [], 44]}; CLASS_DATA={ 'simpletest': ['simpletest', 'Registry and test context. Includes a few global options that I\'m slowly getting rid of. ', [['tests/simpletest','simpletest.php',17]], 90], 'webtestcase': ['webtestcase', 'Test case for testing of web pages. Allows fetching of pages, parsing of HTML and submitting forms. ', [['tests/simpletest','web_tester.php',426]], 67], 'webtests': ['webtests', '', [['tests/simpletest/docs/en','web_tester_documentation.html',96],['tests/simpletest/docs/fr','web_tester_documentation.html',100]], 0], 'testoflastcraft': ['testoflastcraft', '', [['tests/simpletest/docs/en','web_tester_documentation.html',112],['tests/simpletest/docs/en','web_tester_documentation.html',146],['tests/simpletest/docs/en','web_tester_documentation.html',266],['tests/simpletest/docs/en','web_tester_documentation.html',286],['tests/simpletest/docs/en','web_tester_documentation.html',307],['tests/simpletest/docs/en','web_tester_documentation.html',327],['tests/simpletest/docs/fr','web_tester_documentation.html',116],['tests/simpletest/docs/fr','web_tester_documentation.html',151],['tests/simpletest/docs/fr','web_tester_documentation.html',262],['tests/simpletest/docs/fr','web_tester_documentation.html',283],['tests/simpletest/docs/fr','web_tester_documentation.html',304],['tests/simpletest/docs/fr','web_tester_documentation.html',324]], 0], 'testsuite': ['testsuite', 'This is a composite test class for combining test cases and other RunnableTest classes into a group test. ', [['tests/simpletest','test_case.php',470]], 43], 'textreporter': ['textreporter', 'Sample minimal test displayer. Generates only failure messages and a pass count. For command line use. I\'ve tried to make it look like JUnit, but I wanted to output the errors as they arrived which meant dropping the dots. ', [['tests/simpletest','reporter.php',185]], 22]}; CONST_DATA={ }; </script> <div id="func-popup" class="funcpopup"><p id="func-title" class="popup-title">title</p><p id="func-desc" class="popup-desc">Description</p><p id="func-body" class="popup-body">Body</p></div> <div id="class-popup" class="funcpopup"><p id="class-title" class="popup-title">title</p><p id="class-desc" class="popup-desc">Description</p><p id="class-body" class="popup-body">Body</p></div> <div id="const-popup" class="funcpopup"><p id="const-title" class="popup-title">title</p><p id="const-desc" class="popup-desc">Description</p><p id="const-body" class="popup-body">Body</p></div> <div id="req-popup" class="funcpopup"><p id="req-title" class="popup-title">title</p><p id="req-body" class="popup-body">Body</p></div> <!-- A link to the phpxref site in your customized footer file is appreciated ;-) --> <br><hr> <table width="100%"> <tr><td>Generated: Thu Oct 23 18:57:41 2014</td> <td align="right"><i>Cross-referenced by <a href="http://phpxref.sourceforge.net/">PHPXref 0.7.1</a></i></td> </tr> </table> </body></html>
inputx/code-ref-doc
bonfire/tests/simpletest/docs/fr/web_tester_documentation.html.source.html
HTML
apache-2.0
105,441
# AUTOGENERATED FILE FROM balenalib/up-board-ubuntu:xenial-build ENV NODE_VERSION 14.18.3 ENV YARN_VERSION 1.22.4 RUN for key in \ 6A010C5166006599AA17F08146C2130DFD2497F5 \ ; do \ gpg --keyserver pgp.mit.edu --recv-keys "$key" || \ gpg --keyserver keyserver.pgp.com --recv-keys "$key" || \ gpg --keyserver keyserver.ubuntu.com --recv-keys "$key" ; \ done \ && curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-x64.tar.gz" \ && echo "bd96f88e054801d1368787f7eaf77b49cd052b9543c56bd6bc0bfc90310e2756 node-v$NODE_VERSION-linux-x64.tar.gz" | sha256sum -c - \ && tar -xzf "node-v$NODE_VERSION-linux-x64.tar.gz" -C /usr/local --strip-components=1 \ && rm "node-v$NODE_VERSION-linux-x64.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/[email protected]" \ && echo "Running test-stack@node" \ && chmod +x [email protected] \ && bash [email protected] \ && rm -rf [email protected] 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: Intel 64-bit (x86-64) \nOS: Ubuntu xenial \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v14.18.3, 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/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
resin-io-library/base-images
balena-base-images/node/up-board/ubuntu/xenial/14.18.3/build/Dockerfile
Dockerfile
apache-2.0
2,758
#include "pmlc/dialect/pxa/analysis/affine_expr.h" namespace mlir { AffineValueExpr::AffineValueExpr(AffineExpr expr, ValueRange operands) : expr(expr), operands(operands.begin(), operands.end()) {} AffineValueExpr::AffineValueExpr(MLIRContext *ctx, int64_t v) { expr = getAffineConstantExpr(v, ctx); } AffineValueExpr::AffineValueExpr(Value v) { operands.push_back(v); expr = getAffineDimExpr(0, v.getContext()); } AffineValueExpr::AffineValueExpr(AffineValueMap map, unsigned idx) : expr(map.getResult(idx)), operands(map.getOperands().begin(), map.getOperands().end()) {} AffineValueExpr AffineValueExpr::operator*(const AffineValueExpr &rhs) const { return AffineValueExpr(AffineExprKind::Mul, *this, rhs); } AffineValueExpr AffineValueExpr::operator*(int64_t rhs) const { auto cst = AffineValueExpr(expr.getContext(), rhs); return AffineValueExpr(AffineExprKind::Mul, *this, cst); } AffineValueExpr AffineValueExpr::operator+(const AffineValueExpr &rhs) const { return AffineValueExpr(AffineExprKind::Add, *this, rhs); } AffineValueExpr AffineValueExpr::operator+(int64_t rhs) const { auto cst = AffineValueExpr(expr.getContext(), rhs); return AffineValueExpr(AffineExprKind::Add, *this, cst); } AffineValueExpr AffineValueExpr::operator-(const AffineValueExpr &rhs) const { return *this + (rhs * -1); } AffineValueExpr AffineValueExpr::operator-(int64_t rhs) const { return *this - AffineValueExpr(expr.getContext(), rhs); } AffineExpr AffineValueExpr::getExpr() const { return expr; } ArrayRef<Value> AffineValueExpr::getOperands() const { return operands; } AffineValueExpr::AffineValueExpr(AffineExprKind kind, AffineValueExpr a, AffineValueExpr b) : operands(a.operands.begin(), a.operands.end()) { SmallVector<AffineExpr, 4> repl_b; for (auto v : b.operands) { auto it = std::find(operands.begin(), operands.end(), v); unsigned idx; if (it == operands.end()) { idx = operands.size(); operands.push_back(v); } else { idx = it - operands.begin(); } repl_b.push_back(getAffineDimExpr(idx, a.expr.getContext())); } auto new_b = b.expr.replaceDimsAndSymbols(repl_b, {}); expr = getAffineBinaryOpExpr(kind, a.expr, new_b); } AffineValueMap jointValueMap(MLIRContext *ctx, ArrayRef<AffineValueExpr> exprs) { DenseMap<Value, unsigned> jointSpace; for (const auto &expr : exprs) { for (Value v : expr.getOperands()) { if (!jointSpace.count(v)) { unsigned idx = jointSpace.size(); jointSpace[v] = idx; } } } SmallVector<AffineExpr, 4> jointExprs; for (const auto &expr : exprs) { SmallVector<AffineExpr, 4> repl; for (Value v : expr.getOperands()) { repl.push_back(getAffineDimExpr(jointSpace[v], ctx)); } jointExprs.push_back(expr.getExpr().replaceDimsAndSymbols(repl, {})); } SmallVector<Value, 4> jointOperands(jointSpace.size()); for (const auto &kvp : jointSpace) { jointOperands[kvp.second] = kvp.first; } auto map = AffineMap::get(jointSpace.size(), 0, jointExprs, ctx); return AffineValueMap(map, jointOperands); } } // End namespace mlir
plaidml/plaidml
pmlc/dialect/pxa/analysis/affine_expr.cc
C++
apache-2.0
3,202
# Leptonia rodwayi Massee SPECIES #### Status ACCEPTED #### According to Index Fungorum #### Published in Bull. Misc. Inf. , Kew 124 (1898) #### Original name Leptonia rodwayi Massee ### Remarks null
mdoering/backbone
life/Fungi/Basidiomycota/Agaricomycetes/Agaricales/Entolomataceae/Leptonia/Leptonia rodwayi/README.md
Markdown
apache-2.0
204
/** * * Copyright 2016 David Strawn * * 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 strawn.longleaf.relay.util; import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; /** * * @author David Strawn * * This class loads configuration from the file system. * */ public class RelayConfigLoader { private static final String serverConfigLocation = "./resources/serverconfig.properties"; private static final String clientConfigLocation = "./resources/clientconfig.properties"; private final Properties properties; public RelayConfigLoader() { properties = new Properties(); } public void loadServerConfig() throws IOException { loadConfigFromPath(serverConfigLocation); } public void loadClientConfig() throws IOException { loadConfigFromPath(clientConfigLocation); } /** * Use this method if you want to use a different location for the configuration. * @param configFileLocation - location of the configuration file * @throws IOException */ public void loadConfigFromPath(String configFileLocation) throws IOException { FileInputStream fileInputStream = new FileInputStream(configFileLocation); properties.load(fileInputStream); fileInputStream.close(); } public int getPort() { return Integer.parseInt(properties.getProperty("port")); } public String getHost() { return properties.getProperty("host"); } }
strontian/longleaf-relay
src/main/java/strawn/longleaf/relay/util/RelayConfigLoader.java
Java
apache-2.0
2,074
/** * 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.oozie.executor.jpa; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.oozie.CoordinatorActionBean; import org.apache.oozie.CoordinatorJobBean; import org.apache.oozie.client.CoordinatorAction; import org.apache.oozie.client.CoordinatorJob; import org.apache.oozie.local.LocalOozie; import org.apache.oozie.service.JPAService; import org.apache.oozie.service.Services; import org.apache.oozie.test.XDataTestCase; import org.apache.oozie.util.XmlUtils; public class TestCoordActionGetForStartJPAExecutor extends XDataTestCase { Services services; @Override protected void setUp() throws Exception { super.setUp(); services = new Services(); services.init(); cleanUpDBTables(); } @Override protected void tearDown() throws Exception { services.destroy(); super.tearDown(); } public void testCoordActionGet() throws Exception { int actionNum = 1; String errorCode = "000"; String errorMessage = "Dummy"; String resourceXmlName = "coord-action-get.xml"; CoordinatorJobBean job = addRecordToCoordJobTable(CoordinatorJob.Status.RUNNING, false, false); CoordinatorActionBean action = createCoordAction(job.getId(), actionNum, CoordinatorAction.Status.WAITING, resourceXmlName, 0); // Add extra attributes for action action.setSlaXml(XDataTestCase.slaXml); action.setErrorCode(errorCode); action.setErrorMessage(errorMessage); // Insert the action insertRecordCoordAction(action); Path appPath = new Path(getFsTestCaseDir(), "coord"); String actionXml = getCoordActionXml(appPath, resourceXmlName); Configuration conf = getCoordConf(appPath); // Pass the expected values _testGetForStartX(action.getId(), job.getId(), CoordinatorAction.Status.WAITING, 0, action.getId() + "_E", XDataTestCase.slaXml, resourceXmlName, XmlUtils.prettyPrint(conf).toString(), actionXml, errorCode, errorMessage); } private void _testGetForStartX(String actionId, String jobId, CoordinatorAction.Status status, int pending, String extId, String slaXml, String resourceXmlName, String createdConf, String actionXml, String errorCode, String errorMessage) throws Exception { try { JPAService jpaService = Services.get().get(JPAService.class); assertNotNull(jpaService); CoordActionGetForStartJPAExecutor actionGetCmd = new CoordActionGetForStartJPAExecutor(actionId); CoordinatorActionBean action = jpaService.execute(actionGetCmd); assertNotNull(action); // Check for expected values assertEquals(actionId, action.getId()); assertEquals(jobId, action.getJobId()); assertEquals(status, action.getStatus()); assertEquals(pending, action.getPending()); assertEquals(createdConf, action.getCreatedConf()); assertEquals(slaXml, action.getSlaXml()); assertEquals(actionXml, action.getActionXml()); assertEquals(extId, action.getExternalId()); assertEquals(errorMessage, action.getErrorMessage()); assertEquals(errorCode, action.getErrorCode()); } catch (Exception ex) { ex.printStackTrace(); fail("Unable to GET a record for COORD Action By actionId =" + actionId); } } }
terrancesnyder/oozie-hadoop2
core/src/test/java/org/apache/oozie/executor/jpa/TestCoordActionGetForStartJPAExecutor.java
Java
apache-2.0
4,358
// Modifications copyright (C) 2017, Baidu.com, Inc. // Copyright 2017 The Apache Software Foundation // 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. #include "util/palo_metrics.h" #include "util/debug_util.h" namespace palo { // Naming convention: Components should be separated by '.' and words should // be separated by '-'. const char* PALO_BE_START_TIME = "palo_be.start_time"; const char* PALO_BE_VERSION = "palo_be.version"; const char* PALO_BE_READY = "palo_be.ready"; const char* PALO_BE_NUM_FRAGMENTS = "palo_be.num_fragments"; const char* TOTAL_SCAN_RANGES_PROCESSED = "palo_be.scan_ranges.total"; const char* NUM_SCAN_RANGES_MISSING_VOLUME_ID = "palo_be.scan_ranges.num_missing_volume_id"; const char* MEM_POOL_TOTAL_BYTES = "palo_be.mem_pool.total_bytes"; const char* HASH_TABLE_TOTAL_BYTES = "palo_be.hash_table.total_bytes"; const char* OLAP_LRU_CACHE_LOOKUP_COUNT = "palo_be.olap.lru_cache.lookup_count"; const char* OLAP_LRU_CACHE_HIT_COUNT = "palo_be.olap.lru_cache.hit_count"; const char* PALO_PUSH_COUNT = "palo_be.olap.push_count"; const char* PALO_FETCH_COUNT = "palo_be.olap.fetch_count"; const char* PALO_REQUEST_COUNT = "palo_be.olap.request_count"; const char* BE_MERGE_DELTA_NUM = "palo_be.olap.be_merge.delta_num"; const char* BE_MERGE_SIZE = "palo_be.olap.be_merge_size"; const char* CE_MERGE_DELTA_NUM = "palo_be.olap.ce_merge.delta_num"; const char* CE_MERGE_SIZE = "palo_be.olap.ce_merge_size"; const char* IO_MGR_NUM_BUFFERS = "palo_be.io_mgr.num_buffers"; const char* IO_MGR_NUM_OPEN_FILES = "palo_be.io_mgr.num_open_files"; const char* IO_MGR_NUM_UNUSED_BUFFERS = "palo_be.io_mgr.num_unused_buffers"; // const char* IO_MGR_NUM_CACHED_FILE_HANDLES = "palo_be.io_mgr_num_cached_file_handles"; const char* IO_MGR_NUM_FILE_HANDLES_OUTSTANDING = "palo_be.io_mgr.num_file_handles_outstanding"; // const char* IO_MGR_CACHED_FILE_HANDLES_HIT_COUNT = "palo_be.io_mgr_cached_file_handles_hit_count"; // const char* IO_MGR_CACHED_FILE_HANDLES_MISS_COUNT = "palo_be.io_mgr_cached_file_handles_miss_count"; const char* IO_MGR_TOTAL_BYTES = "palo_be.io_mgr.total_bytes"; // const char* IO_MGR_BYTES_READ = "palo_be.io_mgr_bytes_read"; // const char* IO_MGR_LOCAL_BYTES_READ = "palo_be.io_mgr_local_bytes_read"; // const char* IO_MGR_CACHED_BYTES_READ = "palo_be.io_mgr_cached_bytes_read"; // const char* IO_MGR_SHORT_CIRCUIT_BYTES_READ = "palo_be.io_mgr_short_circuit_bytes_read"; const char* IO_MGR_BYTES_WRITTEN = "palo_be.io_mgr.bytes_written"; const char* NUM_QUERIES_SPILLED = "palo_be.num_queries_spilled"; // These are created by palo_be during startup. StringProperty* PaloMetrics::_s_palo_be_start_time = NULL; StringProperty* PaloMetrics::_s_palo_be_version = NULL; BooleanProperty* PaloMetrics::_s_palo_be_ready = NULL; IntCounter* PaloMetrics::_s_palo_be_num_fragments = NULL; IntCounter* PaloMetrics::_s_num_ranges_processed = NULL; IntCounter* PaloMetrics::_s_num_ranges_missing_volume_id = NULL; IntGauge* PaloMetrics::_s_mem_pool_total_bytes = NULL; IntGauge* PaloMetrics::_s_hash_table_total_bytes = NULL; IntCounter* PaloMetrics::_s_olap_lru_cache_lookup_count = NULL; IntCounter* PaloMetrics::_s_olap_lru_cache_hit_count = NULL; IntCounter* PaloMetrics::_s_palo_push_count = NULL; IntCounter* PaloMetrics::_s_palo_fetch_count = NULL; IntCounter* PaloMetrics::_s_palo_request_count = NULL; IntCounter* PaloMetrics::_s_be_merge_delta_num = NULL; IntCounter* PaloMetrics::_s_be_merge_size = NULL; IntCounter* PaloMetrics::_s_ce_merge_delta_num = NULL; IntCounter* PaloMetrics::_s_ce_merge_size = NULL; IntGauge* PaloMetrics::_s_io_mgr_num_buffers = NULL; IntGauge* PaloMetrics::_s_io_mgr_num_open_files = NULL; IntGauge* PaloMetrics::_s_io_mgr_num_unused_buffers = NULL; // IntGauge* PaloMetrics::_s_io_mgr_num_cached_file_handles = NULL; IntGauge* PaloMetrics::_s_io_mgr_num_file_handles_outstanding = NULL; // IntGauge* PaloMetrics::_s_io_mgr_cached_file_handles_hit_count = NULL; // IntGauge* PaloMetrics::_s_io_mgr_cached_file_handles_miss_count = NULL; IntGauge* PaloMetrics::_s_io_mgr_total_bytes = NULL; // IntGauge* PaloMetrics::_s_io_mgr_bytes_read = NULL; // IntGauge* PaloMetrics::_s_io_mgr_local_bytes_read = NULL; // IntGauge* PaloMetrics::_s_io_mgr_cached_bytes_read = NULL; // IntGauge* PaloMetrics::_s_io_mgr_short_circuit_bytes_read = NULL; IntCounter* PaloMetrics::_s_io_mgr_bytes_written = NULL; IntCounter* PaloMetrics::_s_num_queries_spilled = NULL; void PaloMetrics::create_metrics(MetricGroup* m) { // Initialize impalad metrics _s_palo_be_start_time = m->AddProperty<std::string>( PALO_BE_START_TIME, ""); _s_palo_be_version = m->AddProperty<std::string>( PALO_BE_VERSION, get_version_string(true)); _s_palo_be_ready = m->AddProperty(PALO_BE_READY, false); _s_palo_be_num_fragments = m->AddCounter(PALO_BE_NUM_FRAGMENTS, 0L); // Initialize scan node metrics _s_num_ranges_processed = m->AddCounter(TOTAL_SCAN_RANGES_PROCESSED, 0L); _s_num_ranges_missing_volume_id = m->AddCounter(NUM_SCAN_RANGES_MISSING_VOLUME_ID, 0L); // Initialize memory usage metrics _s_mem_pool_total_bytes = m->AddGauge(MEM_POOL_TOTAL_BYTES, 0L); _s_hash_table_total_bytes = m->AddGauge(HASH_TABLE_TOTAL_BYTES, 0L); // Initialize olap metrics _s_olap_lru_cache_lookup_count = m->AddCounter(OLAP_LRU_CACHE_LOOKUP_COUNT, 0L); _s_olap_lru_cache_hit_count = m->AddCounter(OLAP_LRU_CACHE_HIT_COUNT, 0L); // Initialize push_count, fetch_count, request_count metrics _s_palo_push_count = m->AddCounter(PALO_PUSH_COUNT, 0L); _s_palo_fetch_count = m->AddCounter(PALO_FETCH_COUNT, 0L); _s_palo_request_count = m->AddCounter(PALO_REQUEST_COUNT, 0L); // Initialize be/ce merge metrics _s_be_merge_delta_num = m->AddCounter(BE_MERGE_DELTA_NUM, 0L); _s_be_merge_size = m->AddCounter(BE_MERGE_SIZE, 0L); _s_ce_merge_delta_num = m->AddCounter(CE_MERGE_DELTA_NUM, 0L); _s_ce_merge_size = m->AddCounter(CE_MERGE_SIZE, 0L); // Initialize metrics relate to spilling to disk // _s_io_mgr_bytes_read // = m->AddGauge(IO_MGR_BYTES_READ, 0L); // _s_io_mgr_local_bytes_read // = m->AddGauge(IO_MGR_LOCAL_BYTES_READ, 0L); // _s_io_mgr_cached_bytes_read // = m->AddGauge(IO_MGR_CACHED_BYTES_READ, 0L); // _s_io_mgr_short_circuit_bytes_read // = m->AddGauge(IO_MGR_SHORT_CIRCUIT_BYTES_READ, 0L); _s_io_mgr_bytes_written = m->AddCounter(IO_MGR_BYTES_WRITTEN, 0L); _s_io_mgr_num_buffers = m->AddGauge(IO_MGR_NUM_BUFFERS, 0L); _s_io_mgr_num_open_files = m->AddGauge(IO_MGR_NUM_OPEN_FILES, 0L); _s_io_mgr_num_unused_buffers = m->AddGauge(IO_MGR_NUM_UNUSED_BUFFERS, 0L); _s_io_mgr_num_file_handles_outstanding = m->AddGauge(IO_MGR_NUM_FILE_HANDLES_OUTSTANDING, 0L); _s_io_mgr_total_bytes = m->AddGauge(IO_MGR_TOTAL_BYTES, 0L); _s_num_queries_spilled = m->AddCounter(NUM_QUERIES_SPILLED, 0L); } }
lingbin/palo
be/src/util/palo_metrics.cpp
C++
apache-2.0
7,788
// Copyright 2015 Christina Teflioudi // // 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. /* * File: PCATree.h * Author: chteflio * * Created on February 9, 2015, 10:30 AM */ #ifndef PCATREE_H #define PCATREE_H namespace mips { comp_type GenerateID() { static comp_type nNextID = 0; return nNextID++; } /* this files are for running the PCA-tree method AFTER the transformation of the input vectors. I.e. the datasets read need to be the transformed ones. */ struct PCA_tree { double median; col_type col; bool isLeaf; comp_type leaf_counter; PCA_tree* leftChild; PCA_tree* rightChild; VectorMatrix* leafData; // if depth=2 I will have levels 2(root) 1, 0(leaves) PCA_tree(const VectorMatrix& matrix, int depth, col_type col, std::vector<row_type>& ids, int k, std::vector<VectorMatrix*>& matricesInLeaves) : col(col), isLeaf(false), leafData(0) { std::vector<row_type> idsLeft, idsRight; if (ids.size() == 0 && col == 0) { // this is the root node ids.reserve(matrix.rowNum); for (int i = k; i < matrix.rowNum; i++) ids.push_back(i); matricesInLeaves.resize(pow(2, depth)); } if (depth == 0) {// this is a leaf isLeaf = true; leaf_counter = GenerateID(); leafData = new VectorMatrix(); leafData->addVectors(matrix, ids); matricesInLeaves[leaf_counter] = leafData; } else { // internal node if (ids.size() > 0) { std::vector<double> values; values.reserve(ids.size()); for (int i = 0; i < ids.size(); i++) { double val = matrix.getMatrixRowPtr(ids[i])[col]; values.push_back(val); } std::sort(values.begin(), values.end(), std::greater<double>()); row_type pos = ids.size() / 2; median = values[pos]; if (ids.size() % 2 == 0) { median += values[pos - 1]; median /= 2; } for (int i = 0; i < ids.size(); i++) { double val = matrix.getMatrixRowPtr(ids[i])[col]; if (val <= median) { idsLeft.push_back(ids[i]); } else { idsRight.push_back(ids[i]); } } } leftChild = new PCA_tree(matrix, depth - 1, col + 1, idsLeft, k, matricesInLeaves); rightChild = new PCA_tree(matrix, depth - 1, col + 1, idsRight, k, matricesInLeaves); } } inline comp_type findBucketForQuery(const double* query) { if (isLeaf) return leaf_counter; if (query[col] <= median) { leftChild->findBucketForQuery(query); } else { rightChild->findBucketForQuery(query); } } }; class PcaTree : public Mip { PCA_tree* root; VectorMatrix probeFirstk; VectorMatrix probeMatrix; std::vector<RetrievalArguments> retrArg; std::vector<VectorMatrix*> matricesInLeaves; PcaTreeArguments args; bool isTransformed; arma::mat U; arma::vec mu; inline void transformProbeMatrix(VectorMatrix& rightMatrix) { // transform probeMatrix (transform ||p|| to less than 1 and p = [sqrt(1- ||p|| * ||p||);p]) // we need the longest vector from probeMatrix double maxLen = 0; for (row_type i = 0; i < rightMatrix.rowNum; i++) { double len = calculateLength(rightMatrix.getMatrixRowPtr(i), rightMatrix.colNum); if (len > maxLen) { maxLen = len; } } arma::mat A(rightMatrix.colNum + 1, rightMatrix.rowNum); //cols x rows mu.zeros(rightMatrix.colNum + 1); #pragma omp parallel for schedule(static,1000) for (row_type i = 0; i < rightMatrix.rowNum; i++) { double* dProbe = rightMatrix.getMatrixRowPtr(i); A(0, i) = 0; for (col_type j = 0; j < rightMatrix.colNum; ++j) { A(j + 1, i) = dProbe[j]; } double len = arma::norm(A.unsafe_col(i)); A(0, i) = maxLen * maxLen - len * len; A(0, i) = (A(0, i) < 0) ? 0 : sqrt(A(0, i)); mu += A.unsafe_col(i); } mu /= rightMatrix.rowNum; #pragma omp parallel for schedule(static,1000) for (row_type i = 0; i < rightMatrix.rowNum; i++) { A.unsafe_col(i) -= mu; } arma::vec s; arma::mat V; bool isOk = arma::svd_econ(U, s, V, A, "left"); if (!isOk) { std::cout << "[ERROR] SVD failed " << std::endl; exit(1); } arma::inplace_trans(U); A = U*A; probeMatrix.rowNum = rightMatrix.rowNum; probeMatrix.colNum = rightMatrix.colNum + 1; probeMatrix.initializeBasics(probeMatrix.colNum, probeMatrix.rowNum, false); #pragma omp parallel for schedule(static,1000) for (row_type i = 0; i < probeMatrix.rowNum; i++) { double* dProbe = probeMatrix.getMatrixRowPtr(i); for (col_type j = 0; j < probeMatrix.colNum; ++j) { dProbe[j] = A(j, i); } probeMatrix.setLengthInData(i, 1); // set to 1 by the transformation } } inline void transformQueryMatrix(const VectorMatrix& leftMatrix, VectorMatrix& queryMatrix) { // transform queryMatrix (transform ||q|| to 1 and q = [0;q]) arma::mat A(leftMatrix.colNum + 1, leftMatrix.rowNum); //cols x rows #pragma omp parallel for schedule(static,1000) for (row_type i = 0; i < leftMatrix.rowNum; i++) { double* dProbe = leftMatrix.getMatrixRowPtr(i); A(0, i) = 0; for (col_type j = 0; j < leftMatrix.colNum; ++j) { A(j + 1, i) = dProbe[j]; } A.unsafe_col(i) -= mu; } A = U * A; queryMatrix.rowNum = leftMatrix.rowNum; queryMatrix.colNum = leftMatrix.colNum + 1; queryMatrix.initializeBasics(queryMatrix.colNum, queryMatrix.rowNum, false); #pragma omp parallel for schedule(static,1000) for (row_type i = 0; i < queryMatrix.rowNum; i++) { double* dQuery = queryMatrix.getMatrixRowPtr(i); for (col_type j = 0; j < queryMatrix.colNum; ++j) { dQuery[j] = A(j, i); } queryMatrix.setLengthInData(i, 1); // ||q|| = 1 } } inline void verify(const double* query, comp_type bucket, row_type tid, double& minScore) { for (row_type j = 0; j < matricesInLeaves[bucket]->rowNum; j++) { row_type probeId = matricesInLeaves[bucket]->lengthInfo[j].id; double euclideanDistance = matricesInLeaves[bucket]->L2Distance2(j, query); // std::cout<<"checking: "<<j<<" probe id: "<<probeId<<" result: "<<euclideanDistance<<std::endl; retrArg[tid].comparisons++; if (euclideanDistance < minScore) { std::pop_heap(retrArg[tid].heap.begin(), retrArg[tid].heap.end(), std::less<QueueElement>()); retrArg[tid].heap.pop_back(); retrArg[tid].heap.push_back(QueueElement(euclideanDistance, probeId)); std::push_heap(retrArg[tid].heap.begin(), retrArg[tid].heap.end(), std::less<QueueElement>()); minScore = retrArg[tid].heap.front().data; } } } inline void printAlgoName(const VectorMatrix& leftMatrix) { logging << "PCA_TREE" << "\t" << args.threads << "\t d(" << args.depth << ")\t"; std::cout << "[ALGORITHM] PCA_TREE with " << args.threads << " thread(s) and depth " << args.depth << std::endl; logging << "P(" << probeMatrix.rowNum << "x" << (0 + probeMatrix.colNum) << ")\t"; logging << "Q^T(" << leftMatrix.rowNum << "x" << (0 + leftMatrix.colNum) << ")\t"; } inline void initializeInternal(std::vector<VectorMatrix>& queryMatrices, const VectorMatrix& leftMatrix) { std::cout << "[RETRIEVAL] QueryMatrix contains " << leftMatrix.rowNum << " vectors with dimensionality " << (0 + leftMatrix.colNum) << std::endl; row_type myNumThreads = args.threads; if (leftMatrix.rowNum < args.threads) { myNumThreads = leftMatrix.rowNum; std::cout << "[WARNING] Query matrix contains too few elements. Suboptimal running with " << myNumThreads << " thread(s)" << std::endl; } omp_set_num_threads(myNumThreads); queryMatrices.resize(myNumThreads); timer.start(); if (!isTransformed) { std::cout << "[RETRIEVAL] QueryMatrix will be transformed" << std::endl; VectorMatrix queryMatrix; transformQueryMatrix(leftMatrix, queryMatrix); splitMatrices(queryMatrix, queryMatrices); } else { splitMatrices(leftMatrix, queryMatrices); } timer.stop(); dataPreprocessingTimeLeft += timer.elapsedTime().nanos(); retrArg.resize(myNumThreads); for (row_type i = 0; i < retrArg.size(); i++) { retrArg[i].initializeBasics(queryMatrices[i], probeMatrix, LEMP_L, args.theta, args.k, args.threads, 0, 0, 0, 0); retrArg[i].clear(); } } public: inline PcaTree(InputArguments& input, int depth, bool isTransformed) : root(nullptr), isTransformed(isTransformed) { args.copyInputArguments(input); args.depth = depth; // now do the logging logging.open(args.logFile.c_str(), std::ios_base::app); if (!logging.is_open()) { std::cout << "[WARNING] No log will be created!" << std::endl; } else { std::cout << "[INFO] Logging in " << args.logFile << std::endl; } omp_set_num_threads(args.threads); } inline ~PcaTree() { logging.close(); } inline void initialize(VectorMatrix& rightMatrix) { std::cout << "[INIT] ProbeMatrix contains " << rightMatrix.rowNum << " vectors with dimensionality " << (0 + rightMatrix.colNum) << std::endl; if (!isTransformed) { std::cout << "[INIT] ProbeMatrix will be transformed" << std::endl; timer.start(); transformProbeMatrix(rightMatrix); timer.stop(); dataPreprocessingTimeRight += timer.elapsedTime().nanos(); } else { probeMatrix = rightMatrix; } //create the tree std::vector<row_type> ids; timer.start(); root = new PCA_tree(probeMatrix, args.depth, 0, ids, args.k, matricesInLeaves); ids.clear(); for (int i = 0; i < args.k; i++) { ids.push_back(i); } probeFirstk.addVectors(probeMatrix, ids); timer.stop(); dataPreprocessingTimeRight = timer.elapsedTime().nanos(); } inline void runTopK(VectorMatrix& leftMatrix, Results& results) { printAlgoName(leftMatrix); std::vector<VectorMatrix> queryMatrices; initializeInternal(queryMatrices, leftMatrix); results.resultsVector.resize(args.threads); std::cout << "[RETRIEVAL] Retrieval (k = " << args.k << ") starts ..." << std::endl; logging << "k(" << args.k << ")\t"; timer.start(); for (row_type i = 0; i < retrArg.size(); i++) retrArg[i].allocTopkResults(); comp_type comparisons = 0; #pragma omp parallel reduction(+ : comparisons) { row_type tid = omp_get_thread_num(); double minScore = 0; for (row_type i = 0; i < queryMatrices[tid].rowNum; i++) { const double* query = queryMatrices[tid].getMatrixRowPtr(i); for (row_type j = 0; j < args.k; j++) { retrArg[tid].comparisons++; double euclideanDistance = probeFirstk.L2Distance2(j, query); // std::cout<<"checking: "<<j<<" probe id: "<<0<<" result: "<<euclideanDistance<<std::endl; retrArg[tid].heap[j] = QueueElement(euclideanDistance, j); } std::make_heap(retrArg[tid].heap.begin(), retrArg[tid].heap.end(), std::less<QueueElement>()); //make the heap; minScore = retrArg[tid].heap.front().data; // find bucket of query comp_type queryBucket = root->findBucketForQuery(query); verify(query, queryBucket, tid, minScore); // now scan also buckets in hamming distance=1 for (comp_type b = 0; b < matricesInLeaves.size(); b++) { if (queryBucket == b || matricesInLeaves[b]->rowNum == 0) continue; comp_type res = b ^ queryBucket; int hammingDistance = __builtin_popcountll(res); if (hammingDistance == 1) { // these guys are candidates verify(query, b, tid, minScore); } }// for each bucket // write the results back retrArg[tid].writeHeapToTopk(i); // std::cout << retrArg[tid].heap.front().data << " " << retrArg[tid].heap.front().id << std::endl; }// for each query retrArg[tid].extendIncompleteResultItems(); results.moveAppend(retrArg[tid].results, tid); comparisons += retrArg[tid].comparisons; } timer.stop(); retrievalTime += timer.elapsedTime().nanos(); totalComparisons += comparisons; std::cout << "[RETRIEVAL] ... and is finished with " << results.getResultSize() << " results" << std::endl; logging << results.getResultSize() << "\t"; outputStats(); } }; } #endif /* PCATREE_H */
uma-pi1/LEMP
mips/algos/PcaTree.h
C
apache-2.0
15,727
package leetcode.reverse_linked_list_ii; import common.ListNode; public class Solution { public ListNode reverseBetween(ListNode head, int m, int n) { if(head == null) return null; ListNode curRight = head; for(int len = 0; len < n - m; len++){ curRight = curRight.next; } ListNode prevLeft = null; ListNode curLeft = head; for(int len = 0; len < m - 1; len++){ prevLeft = curLeft; curLeft = curLeft.next; curRight = curRight.next; } if(prevLeft == null){ head = curRight; }else{ prevLeft.next = curRight; } for(int len = 0; len < n - m; len++){ ListNode next = curLeft.next; curLeft.next = curRight.next; curRight.next = curLeft; curLeft = next; } return head; } public static void dump(ListNode node){ while(node != null){ System.err.print(node.val + "->"); node = node.next; } System.err.println("null"); } public static void main(String[] args){ final int N = 10; ListNode[] list = new ListNode[N]; for(int m = 1; m <= N; m++){ for(int n = m; n <= N; n++){ for(int i = 0; i < N; i++){ list[i] = new ListNode(i); if(i > 0) list[i - 1].next = list[i]; } dump(new Solution().reverseBetween(list[0], m, n)); } } } }
ckclark/leetcode
java/leetcode/reverse_linked_list_ii/Solution.java
Java
apache-2.0
1,378
<!DOCTYPE html> <html> <head> <base href="http://fushenghua.github.io/GetHosp"> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>涪陵博生和美妇产医院</title> <meta name="viewport" content="width=device-width"> <meta name="description" content="GetHosp"> <link rel="canonical" href="http://fushenghua.github.io/GetHosphttp://fushenghua.github.io/GetHosp/%E5%85%B6%E4%BB%96/2016/05/03/%E6%B6%AA%E9%99%B5%E5%8D%9A%E7%94%9F%E5%92%8C%E7%BE%8E%E5%A6%87%E4%BA%A7%E5%8C%BB%E9%99%A2/"> <!-- Custom CSS --> <link rel="stylesheet" href="http://fushenghua.github.io/GetHosp/css/main.css"> </head> <body> <header class="site-header"> <div class="wrap"> <a class="site-title" href="http://fushenghua.github.io/GetHosp/">GetHosp</a> <nav class="site-nav"> <a href="#" class="menu-icon"> <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 18 15" enable-background="new 0 0 18 15" xml:space="preserve"> <path fill="#505050" d="M18,1.484c0,0.82-0.665,1.484-1.484,1.484H1.484C0.665,2.969,0,2.304,0,1.484l0,0C0,0.665,0.665,0,1.484,0 h15.031C17.335,0,18,0.665,18,1.484L18,1.484z"/> <path fill="#505050" d="M18,7.516C18,8.335,17.335,9,16.516,9H1.484C0.665,9,0,8.335,0,7.516l0,0c0-0.82,0.665-1.484,1.484-1.484 h15.031C17.335,6.031,18,6.696,18,7.516L18,7.516z"/> <path fill="#505050" d="M18,13.516C18,14.335,17.335,15,16.516,15H1.484C0.665,15,0,14.335,0,13.516l0,0 c0-0.82,0.665-1.484,1.484-1.484h15.031C17.335,12.031,18,12.696,18,13.516L18,13.516z"/> </svg> </a> <div class="trigger"> <a class="page-link" href="http://fushenghua.github.io/GetHosp/about/">About</a> </div> </nav> </div> </header> <div class="page-content"> <div class="wrap"> <div class="post"> <header class="post-header"> <h1>涪陵博生和美妇产医院</h1> <p class="meta">May 3, 2016</p> </header> <article class="post-content"> <p>涪陵博生和美妇产医院</p> <p>信息</p> </article> </div> </div> </div> <footer class="site-footer"> <div class="wrap"> <h2 class="footer-heading">GetHosp</h2> <div class="footer-col-1 column"> <ul> <li>GetHosp</li> <li><a href="mailto:[email protected]">[email protected]</a></li> </ul> </div> <div class="footer-col-2 column"> <ul> <li> <a href="https://github.com/fushenghua"> <span class="icon github"> <svg version="1.1" class="github-icon-svg" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 16 16" enable-background="new 0 0 16 16" xml:space="preserve"> <path fill-rule="evenodd" clip-rule="evenodd" fill="#C2C2C2" d="M7.999,0.431c-4.285,0-7.76,3.474-7.76,7.761 c0,3.428,2.223,6.337,5.307,7.363c0.388,0.071,0.53-0.168,0.53-0.374c0-0.184-0.007-0.672-0.01-1.32 c-2.159,0.469-2.614-1.04-2.614-1.04c-0.353-0.896-0.862-1.135-0.862-1.135c-0.705-0.481,0.053-0.472,0.053-0.472 c0.779,0.055,1.189,0.8,1.189,0.8c0.692,1.186,1.816,0.843,2.258,0.645c0.071-0.502,0.271-0.843,0.493-1.037 C4.86,11.425,3.049,10.76,3.049,7.786c0-0.847,0.302-1.54,0.799-2.082C3.768,5.507,3.501,4.718,3.924,3.65 c0,0,0.652-0.209,2.134,0.796C6.677,4.273,7.34,4.187,8,4.184c0.659,0.003,1.323,0.089,1.943,0.261 c1.482-1.004,2.132-0.796,2.132-0.796c0.423,1.068,0.157,1.857,0.077,2.054c0.497,0.542,0.798,1.235,0.798,2.082 c0,2.981-1.814,3.637-3.543,3.829c0.279,0.24,0.527,0.713,0.527,1.437c0,1.037-0.01,1.874-0.01,2.129 c0,0.208,0.14,0.449,0.534,0.373c3.081-1.028,5.302-3.935,5.302-7.362C15.76,3.906,12.285,0.431,7.999,0.431z"/> </svg> </span> <span class="username">fushenghua</span> </a> </li> </ul> </div> <div class="footer-col-3 column"> <p class="text">GetHosp</p> </div> </div> </footer> </body> </html>
fushenghua/GetHosp
_site/其他/2016/05/03/涪陵博生和美妇产医院/index.html
HTML
apache-2.0
4,356
/* * 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.giraph.examples.io.formats; import com.google.common.collect.Lists; import org.apache.giraph.edge.Edge; import org.apache.giraph.edge.EdgeFactory; import org.apache.giraph.examples.utils.BrachaTouegDeadlockVertexValue; import org.apache.giraph.graph.Vertex; import org.apache.giraph.io.formats.TextVertexInputFormat; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.json.JSONArray; import org.json.JSONException; import java.io.IOException; import java.util.List; /** * VertexInputFormat for the Bracha Toueg Deadlock Detection algorithm * specified in JSON format. */ public class LongLongLongLongVertexInputFormat extends TextVertexInputFormat<LongWritable, LongWritable, LongWritable> { @Override public TextVertexReader createVertexReader(InputSplit split, TaskAttemptContext context) { return new JsonLongLongLongLongVertexReader(); } /** * VertexReader use for the Bracha Toueg Deadlock Detection Algorithm. * The files should be in the following JSON format: * JSONArray(<vertex id>, * JSONArray(JSONArray(<dest vertex id>, <edge tag>), ...)) * The tag is use for the N-out-of-M semantics. Two edges with the same tag * are considered to be combined and, hence, represent to combined requests * that need to be both satisfied to continue execution. * Here is an example with vertex id 1, and three edges (requests). * First edge has a destination vertex 2 with tag 0. * Second and third edge have a destination vertex respectively of 3 and 4 * with tag 1. * [1,[[2,0], [3,1], [4,1]]] */ class JsonLongLongLongLongVertexReader extends TextVertexReaderFromEachLineProcessedHandlingExceptions<JSONArray, JSONException> { @Override protected JSONArray preprocessLine(Text line) throws JSONException { return new JSONArray(line.toString()); } @Override protected LongWritable getId(JSONArray jsonVertex) throws JSONException, IOException { return new LongWritable(jsonVertex.getLong(0)); } @Override protected LongWritable getValue(JSONArray jsonVertex) throws JSONException, IOException { return new LongWritable(); } @Override protected Iterable<Edge<LongWritable, LongWritable>> getEdges(JSONArray jsonVertex) throws JSONException, IOException { JSONArray jsonEdgeArray = jsonVertex.getJSONArray(1); /* get the edges */ List<Edge<LongWritable, LongWritable>> edges = Lists.newArrayListWithCapacity(jsonEdgeArray.length()); for (int i = 0; i < jsonEdgeArray.length(); ++i) { LongWritable targetId; LongWritable tag; JSONArray jsonEdge = jsonEdgeArray.getJSONArray(i); targetId = new LongWritable(jsonEdge.getLong(0)); tag = new LongWritable((long) jsonEdge.getLong(1)); edges.add(EdgeFactory.create(targetId, tag)); } return edges; } @Override protected Vertex<LongWritable, LongWritable, LongWritable> handleException(Text line, JSONArray jsonVertex, JSONException e) { throw new IllegalArgumentException( "Couldn't get vertex from line " + line, e); } } }
KidEinstein/giraph
giraph-examples/src/main/java/org/apache/giraph/examples/io/formats/LongLongLongLongVertexInputFormat.java
Java
apache-2.0
4,147
/* * Copyright 2013 Google 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.google.api.client.googleapis.testing.json; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.gson.GsonFactory; import java.io.IOException; import junit.framework.TestCase; /** * Tests {@link GoogleJsonResponseExceptionFactoryTesting} * * @author Eric Mintz */ public class GoogleJsonResponseExceptionFactoryTestingTest extends TestCase { private static final JsonFactory JSON_FACTORY = new GsonFactory(); private static final int HTTP_CODE_NOT_FOUND = 404; private static final String REASON_PHRASE_NOT_FOUND = "NOT FOUND"; public void testCreateException() throws IOException { GoogleJsonResponseException exception = GoogleJsonResponseExceptionFactoryTesting.newMock( JSON_FACTORY, HTTP_CODE_NOT_FOUND, REASON_PHRASE_NOT_FOUND); assertEquals(HTTP_CODE_NOT_FOUND, exception.getStatusCode()); assertEquals(REASON_PHRASE_NOT_FOUND, exception.getStatusMessage()); } }
googleapis/google-api-java-client
google-api-client/src/test/java/com/google/api/client/googleapis/testing/json/GoogleJsonResponseExceptionFactoryTestingTest.java
Java
apache-2.0
1,619
<html> <head> <meta name="viewport" content="width=device-width, initial-scale=1" charset="UTF-8"> <title>LOWER_HALF_BLOCK</title> <link href="../../../images/logo-icon.svg" rel="icon" type="image/svg"> <script>var pathToRoot = "../../../";</script> <script type="text/javascript" src="../../../scripts/sourceset_dependencies.js" async="async"></script> <link href="../../../styles/style.css" rel="Stylesheet"> <link href="../../../styles/logo-styles.css" rel="Stylesheet"> <link href="../../../styles/jetbrains-mono.css" rel="Stylesheet"> <link href="../../../styles/main.css" rel="Stylesheet"> <script type="text/javascript" src="../../../scripts/clipboard.js" async="async"></script> <script type="text/javascript" src="../../../scripts/navigation-loader.js" async="async"></script> <script type="text/javascript" src="../../../scripts/platform-content-handler.js" async="async"></script> <script type="text/javascript" src="../../../scripts/main.js" async="async"></script> </head> <body> <div id="container"> <div id="leftColumn"> <div id="logo"></div> <div id="paneSearch"></div> <div id="sideMenu"></div> </div> <div id="main"> <div id="leftToggler"><span class="icon-toggler"></span></div> <script type="text/javascript" src="../../../scripts/pages.js"></script> <script type="text/javascript" src="../../../scripts/main.js"></script> <div class="main-content" id="content" pageIds="org.hexworks.zircon.api.graphics/Symbols/LOWER_HALF_BLOCK/#/PointingToDeclaration//-755115832"> <div class="navigation-wrapper" id="navigation-wrapper"> <div class="breadcrumbs"><a href="../../index.html">zircon.core</a>/<a href="../index.html">org.hexworks.zircon.api.graphics</a>/<a href="index.html">Symbols</a>/<a href="-l-o-w-e-r_-h-a-l-f_-b-l-o-c-k.html">LOWER_HALF_BLOCK</a></div> <div class="pull-right d-flex"> <div class="filter-section" id="filter-section"><button class="platform-tag platform-selector common-like" data-active="" data-filter=":zircon.core:dokkaHtml/commonMain">common</button></div> <div id="searchBar"></div> </div> </div> <div class="cover "> <h1 class="cover"><span>L</span><wbr></wbr><span>O</span><wbr></wbr><span>W</span><wbr></wbr><span>E</span><wbr></wbr><span>R_</span><wbr></wbr><span>H</span><wbr></wbr><span>A</span><wbr></wbr><span>L</span><wbr></wbr><span>F_</span><wbr></wbr><span>B</span><wbr></wbr><span>L</span><wbr></wbr><span>O</span><wbr></wbr><span>C</span><wbr></wbr><span>K</span></h1> </div> <div class="divergent-group" data-filterable-current=":zircon.core:dokkaHtml/commonMain" data-filterable-set=":zircon.core:dokkaHtml/commonMain"><div class="with-platform-tags"><span class="pull-right"></span></div> <div> <div class="platform-hinted " data-platform-hinted="data-platform-hinted"><div class="content sourceset-depenent-content" data-active="" data-togglable=":zircon.core:dokkaHtml/commonMain"><div class="symbol monospace">const val <a href="-l-o-w-e-r_-h-a-l-f_-b-l-o-c-k.html">LOWER_HALF_BLOCK</a>: <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-char/index.html">Char</a><span class="top-right-position"><span class="copy-icon"></span><div class="copy-popup-wrapper popup-to-left"><span class="copy-popup-icon"></span><span>Content copied to clipboard</span></div></span></div></div></div> </div> <p class="paragraph">▄</p></div> <h2 class="">Sources</h2> <div class="table" data-togglable="Sources"><a data-name="%5Borg.hexworks.zircon.api.graphics%2FSymbols%2FLOWER_HALF_BLOCK%2F%23%2FPointingToDeclaration%2F%5D%2FSource%2F-755115832" anchor-label="https://github.com/Hexworks/zircon/tree/master/zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/graphics/Symbols.kt#L474" id="%5Borg.hexworks.zircon.api.graphics%2FSymbols%2FLOWER_HALF_BLOCK%2F%23%2FPointingToDeclaration%2F%5D%2FSource%2F-755115832" data-filterable-set=":zircon.core:dokkaHtml/commonMain"></a> <div class="table-row" data-filterable-current=":zircon.core:dokkaHtml/commonMain" data-filterable-set=":zircon.core:dokkaHtml/commonMain"> <div class="main-subrow keyValue "> <div class=""><span class="inline-flex"><a href="https://github.com/Hexworks/zircon/tree/master/zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/graphics/Symbols.kt#L474">(source)</a><span class="anchor-wrapper"><span class="anchor-icon" pointing-to="%5Borg.hexworks.zircon.api.graphics%2FSymbols%2FLOWER_HALF_BLOCK%2F%23%2FPointingToDeclaration%2F%5D%2FSource%2F-755115832"></span> <div class="copy-popup-wrapper "><span class="copy-popup-icon"></span><span>Link copied to clipboard</span></div> </span></span></div> <div></div> </div> </div> </div> </div> <div class="footer"><span class="go-to-top-icon"><a href="#content"></a></span><span>© 2020 Copyright</span><span class="pull-right"><span>Sponsored and developed by dokka</span><a href="https://github.com/Kotlin/dokka"><span class="padded-icon"></span></a></span></div> </div> </div> </body> </html>
Hexworks/zircon
docs/2021.1.0-RELEASE-KOTLIN/zircon.core/zircon.core/org.hexworks.zircon.api.graphics/-symbols/-l-o-w-e-r_-h-a-l-f_-b-l-o-c-k.html
HTML
apache-2.0
5,336
//------------------------------------------------------------------------------ // <auto-generated> // このコードはツールによって生成されました。 // ランタイム バージョン:2.0.50727.8009 // // このファイルへの変更は、以下の状況下で不正な動作の原因になったり、 // コードが再生成されるときに損失したりします。 // </auto-generated> //------------------------------------------------------------------------------ namespace MsgPack.Serialization.GeneratedSerializers.MapBased { [System.CodeDom.Compiler.GeneratedCodeAttribute("MsgPack.Serialization.CodeDomSerializers.CodeDomSerializerBuilder", "0.6.0.0")] [System.Diagnostics.DebuggerNonUserCodeAttribute()] public class MsgPack_Serialization_PolymorphicMemberTypeKnownType_List_ListObjectItemPrivateSetterCollectionPropertySerializer : MsgPack.Serialization.MessagePackSerializer<MsgPack.Serialization.PolymorphicMemberTypeKnownType_List_ListObjectItemPrivateSetterCollectionProperty> { private MsgPack.Serialization.MessagePackSerializer<string> _serializer0; private MsgPack.Serialization.MessagePackSerializer<System.Collections.Generic.IList<object>> _serializer1; private System.Reflection.MethodBase _methodBasePolymorphicMemberTypeKnownType_List_ListObjectItemPrivateSetterCollectionProperty_set_ListObjectItem0; public MsgPack_Serialization_PolymorphicMemberTypeKnownType_List_ListObjectItemPrivateSetterCollectionPropertySerializer(MsgPack.Serialization.SerializationContext context) : base(context) { MsgPack.Serialization.PolymorphismSchema schema0 = default(MsgPack.Serialization.PolymorphismSchema); MsgPack.Serialization.PolymorphismSchema itemsSchema0 = default(MsgPack.Serialization.PolymorphismSchema); System.Collections.Generic.Dictionary<string, System.Type> itemsSchemaTypeMap0 = default(System.Collections.Generic.Dictionary<string, System.Type>); itemsSchemaTypeMap0 = new System.Collections.Generic.Dictionary<string, System.Type>(2); itemsSchemaTypeMap0.Add("0", typeof(MsgPack.Serialization.FileEntry)); itemsSchemaTypeMap0.Add("1", typeof(MsgPack.Serialization.DirectoryEntry)); itemsSchema0 = MsgPack.Serialization.PolymorphismSchema.ForPolymorphicObject(typeof(object), itemsSchemaTypeMap0); schema0 = MsgPack.Serialization.PolymorphismSchema.ForContextSpecifiedCollection(typeof(System.Collections.Generic.IList<object>), itemsSchema0); this._serializer0 = context.GetSerializer<string>(schema0); MsgPack.Serialization.PolymorphismSchema schema1 = default(MsgPack.Serialization.PolymorphismSchema); MsgPack.Serialization.PolymorphismSchema itemsSchema1 = default(MsgPack.Serialization.PolymorphismSchema); System.Collections.Generic.Dictionary<string, System.Type> itemsSchema1TypeMap0 = default(System.Collections.Generic.Dictionary<string, System.Type>); itemsSchema1TypeMap0 = new System.Collections.Generic.Dictionary<string, System.Type>(2); itemsSchema1TypeMap0.Add("0", typeof(MsgPack.Serialization.FileEntry)); itemsSchema1TypeMap0.Add("1", typeof(MsgPack.Serialization.DirectoryEntry)); itemsSchema1 = MsgPack.Serialization.PolymorphismSchema.ForPolymorphicObject(typeof(object), itemsSchema1TypeMap0); schema1 = MsgPack.Serialization.PolymorphismSchema.ForContextSpecifiedCollection(typeof(System.Collections.Generic.IList<object>), itemsSchema1); this._serializer1 = context.GetSerializer<System.Collections.Generic.IList<object>>(schema1); this._methodBasePolymorphicMemberTypeKnownType_List_ListObjectItemPrivateSetterCollectionProperty_set_ListObjectItem0 = typeof(MsgPack.Serialization.PolymorphicMemberTypeKnownType_List_ListObjectItemPrivateSetterCollectionProperty).GetMethod("set_ListObjectItem", (System.Reflection.BindingFlags.Instance | (System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic)), null, new System.Type[] { typeof(System.Collections.Generic.IList<object>)}, null); } protected internal override void PackToCore(MsgPack.Packer packer, MsgPack.Serialization.PolymorphicMemberTypeKnownType_List_ListObjectItemPrivateSetterCollectionProperty objectTree) { packer.PackMapHeader(1); this._serializer0.PackTo(packer, "ListObjectItem"); this._serializer1.PackTo(packer, objectTree.ListObjectItem); } protected internal override MsgPack.Serialization.PolymorphicMemberTypeKnownType_List_ListObjectItemPrivateSetterCollectionProperty UnpackFromCore(MsgPack.Unpacker unpacker) { MsgPack.Serialization.PolymorphicMemberTypeKnownType_List_ListObjectItemPrivateSetterCollectionProperty result = default(MsgPack.Serialization.PolymorphicMemberTypeKnownType_List_ListObjectItemPrivateSetterCollectionProperty); result = new MsgPack.Serialization.PolymorphicMemberTypeKnownType_List_ListObjectItemPrivateSetterCollectionProperty(); if (unpacker.IsArrayHeader) { int unpacked = default(int); int itemsCount = default(int); itemsCount = MsgPack.Serialization.UnpackHelpers.GetItemsCount(unpacker); System.Collections.Generic.IList<object> nullable = default(System.Collections.Generic.IList<object>); if ((unpacked < itemsCount)) { if ((unpacker.Read() == false)) { throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(0); } if (((unpacker.IsArrayHeader == false) && (unpacker.IsMapHeader == false))) { nullable = this._serializer1.UnpackFrom(unpacker); } else { MsgPack.Unpacker disposable = default(MsgPack.Unpacker); disposable = unpacker.ReadSubtree(); try { nullable = this._serializer1.UnpackFrom(disposable); } finally { if (((disposable == null) == false)) { disposable.Dispose(); } } } } if (((nullable == null) == false)) { if ((result.ListObjectItem == null)) { this._methodBasePolymorphicMemberTypeKnownType_List_ListObjectItemPrivateSetterCollectionProperty_set_ListObjectItem0.Invoke(result, new object[] { nullable}); } else { System.Collections.Generic.IEnumerator<object> enumerator = nullable.GetEnumerator(); object current; try { for ( ; enumerator.MoveNext(); ) { current = enumerator.Current; result.ListObjectItem.Add(current); } } finally { enumerator.Dispose(); } } } unpacked = (unpacked + 1); } else { int itemsCount0 = default(int); itemsCount0 = MsgPack.Serialization.UnpackHelpers.GetItemsCount(unpacker); for (int i = 0; (i < itemsCount0); i = (i + 1)) { string key = default(string); string nullable0 = default(string); nullable0 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, typeof(MsgPack.Serialization.PolymorphicMemberTypeKnownType_List_ListObjectItemPrivateSetterCollectionProperty), "MemberName"); if (((nullable0 == null) == false)) { key = nullable0; } else { throw MsgPack.Serialization.SerializationExceptions.NewNullIsProhibited("MemberName"); } if ((key == "ListObjectItem")) { System.Collections.Generic.IList<object> nullable1 = default(System.Collections.Generic.IList<object>); if ((unpacker.Read() == false)) { throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(i); } if (((unpacker.IsArrayHeader == false) && (unpacker.IsMapHeader == false))) { nullable1 = this._serializer1.UnpackFrom(unpacker); } else { MsgPack.Unpacker disposable0 = default(MsgPack.Unpacker); disposable0 = unpacker.ReadSubtree(); try { nullable1 = this._serializer1.UnpackFrom(disposable0); } finally { if (((disposable0 == null) == false)) { disposable0.Dispose(); } } } if (((nullable1 == null) == false)) { if ((result.ListObjectItem == null)) { this._methodBasePolymorphicMemberTypeKnownType_List_ListObjectItemPrivateSetterCollectionProperty_set_ListObjectItem0.Invoke(result, new object[] { nullable1}); } else { System.Collections.Generic.IEnumerator<object> enumerator0 = nullable1.GetEnumerator(); object current0; try { for ( ; enumerator0.MoveNext(); ) { current0 = enumerator0.Current; result.ListObjectItem.Add(current0); } } finally { enumerator0.Dispose(); } } } } else { unpacker.Skip(); } } } return result; } private static T @__Conditional<T>(bool condition, T whenTrue, T whenFalse) { if (condition) { return whenTrue; } else { return whenFalse; } } } }
luyikk/ZYSOCKET
msgpack-cli-master/test/MsgPack.UnitTest.Net35/gen/map/MsgPack_Serialization_PolymorphicMemberTypeKnownType_List_ListObjectItemPrivateSetterCollectionPropertySerializer.cs
C#
apache-2.0
11,543
# Ageratina tomentella (Schrad.) R.M.King & H.Rob. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Ageratina tomentella/README.md
Markdown
apache-2.0
198
//============================================================================ // // Copyright (C) 2006-2022 Talend Inc. - www.talend.com // // This source code is available under agreement available at // %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt // // You should have received a copy of the agreement // along with this program; if not, write to Talend SA // 9 rue Pages 92150 Suresnes, France // //============================================================================ package org.talend.components.google.drive.connection; import java.util.EnumSet; import java.util.Set; import org.talend.components.api.component.ConnectorTopology; import org.talend.components.api.component.runtime.ExecutionEngine; import org.talend.components.api.properties.ComponentProperties; import org.talend.components.google.drive.GoogleDriveComponentDefinition; import org.talend.daikon.runtime.RuntimeInfo; public class GoogleDriveConnectionDefinition extends GoogleDriveComponentDefinition { public static final String COMPONENT_NAME = "tGoogleDriveConnection"; //$NON-NLS-1$ public GoogleDriveConnectionDefinition() { super(COMPONENT_NAME); } @Override public Class<? extends ComponentProperties> getPropertyClass() { return GoogleDriveConnectionProperties.class; } @Override public Set<ConnectorTopology> getSupportedConnectorTopologies() { return EnumSet.of(ConnectorTopology.NONE); } @Override public RuntimeInfo getRuntimeInfo(ExecutionEngine engine, ComponentProperties properties, ConnectorTopology connectorTopology) { assertEngineCompatibility(engine); assertConnectorTopologyCompatibility(connectorTopology); return getRuntimeInfo(GoogleDriveConnectionDefinition.SOURCE_OR_SINK_CLASS); } @Override public boolean isStartable() { return true; } }
Talend/components
components/components-googledrive/components-googledrive-definition/src/main/java/org/talend/components/google/drive/connection/GoogleDriveConnectionDefinition.java
Java
apache-2.0
1,926
package si.majeric.smarthouse.xstream.dao; public class SmartHouseConfigReadError extends RuntimeException { private static final long serialVersionUID = 1L; public SmartHouseConfigReadError(Exception e) { super(e); } }
umajeric/smart-house
smart-house-xstream-impl/src/main/java/si/majeric/smarthouse/xstream/dao/SmartHouseConfigReadError.java
Java
apache-2.0
228
<!DOCTYPE html> <html> <meta charset="UTF-8"> <head> <title>Topic 06 -- Abstracts with Biological Entities (English) - 75 Topics / Sub-Topic Model 13 - 15 Topics</title> <style> table { font-family: "Trebuchet MS", Arial, Helvetica, sans-serif; border-collapse: collapse; width: 100%; } td, th { border: 1px solid #ddd; padding: 8px; } tr:nth-child(even){background-color: #f2f2f2;} tr:hover {background-color: #ddd;} th { padding-top: 12px; padding-bottom: 12px; text-align: left; background-color: #0099FF; color: white; } </style> </head> <body> <h2>Topic 06 -- Abstracts with Biological Entities (English) - 75 Topics / Sub-Topic Model 13 - 15 Topics</h2> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>cite ad</th> <th>title</th> <th>authors</th> <th>publish year</th> <th>publish time</th> <th>dataset</th> <th>abstract mentions covid</th> <th>pmcid</th> <th>pubmed id</th> <th>doi</th> <th>cord uid</th> <th>topic weight</th> <th>Similarity scispacy</th> <th>Similarity specter</th> </tr> </thead> <tbody> <tr> <th id="ryychtqa";>1</th> <td>Zuniga_2007</td> <td>Attenuated measles virus as a vaccine vector</td> <td>Zuniga, Armando; Wang, ZiLi; Liniger, Matthias; Hangartner, Lars; Caballero, Michael; Pavlovic, Jovan; Wild, Peter; Viret, Jean Francois; Glueck, Reinhard; Billeter, Martin A.; Naim, Hussein Y.</td> <td>2007</td> <td>2007-04-20</td> <td>None</td> <td>N</td> <td><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3707277" target="_blank">PMC3707277</a></td> <td><a href="https://www.ncbi.nlm.nih.gov/pubmed/17303293.0" target="_blank">17303293.0</a></td> <td><a href="https://doi.org/10.1016/j.vaccine.2007.01.064" target="_blank">10.1016/j.vaccine.2007.01.064</a></td> <td>ryychtqa</td> <td>0.647705</td> <td></td> <td><a href="Topic_06.html#cmbg0ty8">Mühlebach_2016</a>, <a href="Topic_01.html#3qdjmb2j">Mok_H_2012</a></td> </tr> <tr> <th id="u361oua5";>2</th> <td>Peruzzi_2009</td> <td>A novel Chimpanzee serotype-based adenoviral vector as delivery tool for cancer vaccines</td> <td>Peruzzi, Daniela; Dharmapuri, Sridhar; Cirillo, Agostino; Bruni, Bruno Ercole; Nicosia, Alfredo; Cortese, Riccardo; Colloca, Stefano; Ciliberto, Gennaro; La Monica, Nicola; Aurisicchio, Luigi</td> <td>2009</td> <td>2009-02-25</td> <td>PMC</td> <td>N</td> <td><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7115565" target="_blank">PMC7115565</a></td> <td><a href="https://www.ncbi.nlm.nih.gov/pubmed/19162112.0" target="_blank">19162112.0</a></td> <td><a href="https://doi.org/10.1016/j.vaccine.2008.12.051" target="_blank">10.1016/j.vaccine.2008.12.051</a></td> <td>u361oua5</td> <td>0.627562</td> <td><a href="Topic_06.html#hrfbygub">Singh_2016</a>, <a href="Topic_07.html#nzuq0dk7">Schwartz_2007</a>, <a href="Topic_01.html#z2u5frvq">Montefiori_2007</a></td> <td></td> </tr> <tr> <th id="ctass7hz";>3</th> <td>Bull_2019</td> <td>Recombinant vector vaccine evolution</td> <td>Bull, James J.; Nuismer, Scott L.; Antia, Rustom</td> <td>2019</td> <td>2019-07-19</td> <td>COMM-USE</td> <td>N</td> <td><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC6668849" target="_blank">PMC6668849</a></td> <td><a href="https://www.ncbi.nlm.nih.gov/pubmed/31323032.0" target="_blank">31323032.0</a></td> <td><a href="https://doi.org/10.1371/journal.pcbi.1006857" target="_blank">10.1371/journal.pcbi.1006857</a></td> <td>ctass7hz</td> <td>0.626904</td> <td><a href="Topic_01.html#z2u5frvq">Montefiori_2007</a>, <a href="Topic_07.html#neclg3gb">Tripp_2014</a></td> <td><a href="Topic_06.html#3vssgben">Bull_2019</a>, <a href="Topic_06.html#cmbg0ty8">Mühlebach_2016</a>, <a href="Topic_06.html#ryychtqa">Zuniga_2007</a>, <a href="Topic_02.html#zs8urh6c">Nuismer_2019</a></td> </tr> <tr> <th id="v5n1gupw";>4</th> <td>Bangari_2006</td> <td>Development of nonhuman adenoviruses as vaccine vectors</td> <td>Bangari, Dinesh S.; Mittal, Suresh K.</td> <td>2006</td> <td>2006-02-13</td> <td>None</td> <td>N</td> <td><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC1462960" target="_blank">PMC1462960</a></td> <td><a href="https://www.ncbi.nlm.nih.gov/pubmed/16297508.0" target="_blank">16297508.0</a></td> <td><a href="https://doi.org/10.1016/j.vaccine.2005.08.101" target="_blank">10.1016/j.vaccine.2005.08.101</a></td> <td>v5n1gupw</td> <td>0.622664</td> <td><a href="Topic_02.html#aw8p35c5">Tatsis_2004</a></td> <td><a href="Topic_02.html#aw8p35c5">Tatsis_2004</a>, <a href="Topic_06.html#mxtry60e">Mittal_2016</a></td> </tr> <tr> <th id="3vssgben";>5</th> <td>Bull_2019</td> <td>Recombinant vector vaccines and within-host evolution</td> <td>James Bull; Scott L. Nuismer; Rustom Antia</td> <td>2019</td> <td>2019-02-08</td> <td>BioRxiv</td> <td>N</td> <td></td> <td></td> <td><a href="https://doi.org/10.1101/545087" target="_blank">10.1101/545087</a></td> <td>3vssgben</td> <td>0.609826</td> <td><a href="Topic_06.html#ctass7hz">Bull_2019</a></td> <td><a href="Topic_06.html#ctass7hz">Bull_2019</a>, <a href="Topic_06.html#cmbg0ty8">Mühlebach_2016</a>, <a href="Topic_02.html#zs8urh6c">Nuismer_2019</a>, <a href="Topic_06.html#ryychtqa">Zuniga_2007</a></td> </tr> <tr> <th id="s1zl9nbb";>6</th> <td>Bishop_1988</td> <td>The release into the environment of genetically engineered viruses, vaccines and viral pesticides</td> <td>Bishop, David H.L.</td> <td>1988</td> <td>1988-04-30</td> <td>PMC</td> <td>N</td> <td></td> <td></td> <td><a href="https://doi.org/10.1016/0169-5347(88)90130-9" target="_blank">10.1016/0169-5347(88)90130-9</a></td> <td>s1zl9nbb</td> <td>0.597917</td> <td><a href="Topic_02.html#lke4y02f">Bishop_1988</a></td> <td></td> </tr> <tr> <th id="mxtry60e";>7</th> <td>Mittal_2016</td> <td>19 Xenogenic Adenoviral Vectors</td> <td>Mittal, Suresh K.; Ahi, Yadvinder S.; Vemula, Sai V.</td> <td>2016</td> <td>2016-12-31</td> <td>PMC</td> <td>N</td> <td><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7149625" target="_blank">PMC7149625</a></td> <td></td> <td><a href="https://doi.org/10.1016/b978-0-12-800276-6.00019-x" target="_blank">10.1016/b978-0-12-800276-6.00019-x</a></td> <td>mxtry60e</td> <td>0.569062</td> <td><a href="Topic_06.html#v5n1gupw">Bangari_2006</a></td> <td><a href="Topic_06.html#v5n1gupw">Bangari_2006</a>, <a href="Topic_02.html#u1xbkaq0">Ploquin_2013</a></td> </tr> <tr> <th id="uacon432";>8</th> <td>Liniger_2009</td> <td>Recombinant measles viruses expressing single or multiple antigens of human immunodeficiency virus (HIV-1) induce cellular and humoral immune responses</td> <td>Liniger, Matthias; Zuniga, Armando; Morin, Teldja Neige Azzouz; Combardiere, Behazine; Marty, Rene; Wiegand, Marian; Ilter, Orhan; Knuchel, Marlyse; Naim, Hussein Y.</td> <td>2009</td> <td>2009-05-26</td> <td>PMC</td> <td>N</td> <td><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7115622" target="_blank">PMC7115622</a></td> <td><a href="https://www.ncbi.nlm.nih.gov/pubmed/19200842.0" target="_blank">19200842.0</a></td> <td><a href="https://doi.org/10.1016/j.vaccine.2009.01.057" target="_blank">10.1016/j.vaccine.2009.01.057</a></td> <td>uacon432</td> <td>0.555529</td> <td><a href="Topic_07.html#nzuq0dk7">Schwartz_2007</a>, <a href="Topic_03.html#k785hl1r">Lv_L_2014</a></td> <td><a href="Topic_01.html#3qdjmb2j">Mok_H_2012</a>, <a href="Topic_06.html#cmbg0ty8">Mühlebach_2016</a>, <a href="Topic_01.html#vct6xakc">Jiang_2006</a>, <a href="Topic_14.html#ngms51ie">Sawada_2011</a></td> </tr> <tr> <th id="zceca4c1";>9</th> <td>Roy_S_2007</td> <td>Rescue of chimeric adenoviral vectors to expand the serotype repertoire</td> <td>Roy, Soumitra; Clawson, David S.; Lavrukhin, Oleg; Sandhu, Arbans; Miller, Jim; Wilson, James M.</td> <td>2007</td> <td>2007-04-30</td> <td>None</td> <td>N</td> <td><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC1868475" target="_blank">PMC1868475</a></td> <td><a href="https://www.ncbi.nlm.nih.gov/pubmed/17197043.0" target="_blank">17197043.0</a></td> <td><a href="https://doi.org/10.1016/j.jviromet.2006.11.022" target="_blank">10.1016/j.jviromet.2006.11.022</a></td> <td>zceca4c1</td> <td>0.541514</td> <td></td> <td><a href="Topic_06.html#mxtry60e">Mittal_2016</a>, <a href="Topic_02.html#odeksech">Ertl_2016</a>, <a href="Topic_06.html#v5n1gupw">Bangari_2006</a></td> </tr> <tr> <th id="s27bp7ft";>10</th> <td>Bolton_2012</td> <td>Priming T-cell responses with recombinant measles vaccine vector in a heterologous prime-boost setting in non-human primates</td> <td>Bolton, Diane L.; Santra, Sampa; Swett-Tapia, Cindy; Custers, Jerome; Song, Kaimei; Balachandran, Harikrishnan; Mach, Linh; Naim, Hussein; Kozlowski, Pamela A.; Lifton, Michelle; Goudsmit, Jaap; Letvin, Norman; Roederer, Mario; Radošević, Katarina</td> <td>2012</td> <td>2012-09-07</td> <td>None</td> <td>N</td> <td><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3425710" target="_blank">PMC3425710</a></td> <td><a href="https://www.ncbi.nlm.nih.gov/pubmed/22732429.0" target="_blank">22732429.0</a></td> <td><a href="https://doi.org/10.1016/j.vaccine.2012.06.029" target="_blank">10.1016/j.vaccine.2012.06.029</a></td> <td>s27bp7ft</td> <td>0.537387</td> <td><a href="Topic_01.html#z2u5frvq">Montefiori_2007</a>, <a href="Topic_07.html#nzuq0dk7">Schwartz_2007</a></td> <td><a href="Topic_01.html#f78ug0c6">Meng_2012</a>, <a href="Topic_01.html#6rcezxjx">Zakhartchouk_2005</a>, <a href="Topic_05.html#ctikde7d">Cervantes-Barragan_2010</a>, <a href="Topic_01.html#3qdjmb2j">Mok_H_2012</a></td> </tr> <tr> <th id="vr4c59hy";>11</th> <td>Xiao_2011</td> <td>A host-restricted viral vector for antigen-specific immunization against Lyme disease pathogen</td> <td>Xiao, Sa; Kumar, Manish; Yang, Xiuli; Akkoyunlu, Mustafa; Collins, Peter L.; Samal, Siba K.; Pal, Utpal</td> <td>2011</td> <td>2011-07-18</td> <td>None</td> <td>N</td> <td><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3138909" target="_blank">PMC3138909</a></td> <td><a href="https://www.ncbi.nlm.nih.gov/pubmed/21600949.0" target="_blank">21600949.0</a></td> <td><a href="https://doi.org/10.1016/j.vaccine.2011.05.010" target="_blank">10.1016/j.vaccine.2011.05.010</a></td> <td>vr4c59hy</td> <td>0.533249</td> <td><a href="Topic_07.html#nzuq0dk7">Schwartz_2007</a>, <a href="Topic_03.html#k785hl1r">Lv_L_2014</a></td> <td><a href="Topic_10.html#ovoli9dr">Keshwara_2019</a></td> </tr> <tr> <th id="xaohrtq7";>12</th> <td>Lorin_2015</td> <td>Heterologous Prime-Boost Regimens with a Recombinant Chimpanzee Adenoviral Vector and Adjuvanted F4 Protein Elicit Polyfunctional HIV-1-Specific T-Cell Responses in Macaques</td> <td>Lorin, Clarisse; Vanloubbeeck, Yannick; Baudart, Sébastien; Ska, Michaël; Bayat, Babak; Brauers, Geoffroy; Clarinval, Géraldine; Donner, Marie-Noëlle; Marchand, Martine; Koutsoukos, Marguerite; Mettens, Pascal; Cohen, Joe; Voss, Gerald</td> <td>2015</td> <td>2015-04-09</td> <td>COMM-USE</td> <td>N</td> <td><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4391709" target="_blank">PMC4391709</a></td> <td><a href="https://www.ncbi.nlm.nih.gov/pubmed/25856308.0" target="_blank">25856308.0</a></td> <td><a href="https://doi.org/10.1371/journal.pone.0122835" target="_blank">10.1371/journal.pone.0122835</a></td> <td>xaohrtq7</td> <td>0.505593</td> <td><a href="Topic_01.html#5lnehhu1">Mazeike_2012</a></td> <td><a href="Topic_06.html#s27bp7ft">Bolton_2012</a>, <a href="Topic_01.html#5hryh1ft">Azizi_2006</a>, <a href="Topic_06.html#270nzddu">Busch_2020</a></td> </tr> <tr> <th id="fie121ns";>13</th> <td>White_2018</td> <td>Development of improved therapeutic mesothelin-based vaccines for pancreatic cancer</td> <td>White, Michael; Freistaedter, Andrew; Jones, Gwendolyn J. B.; Zervos, Emmanuel; Roper, Rachel L.</td> <td>2018</td> <td>2018-02-23</td> <td>COMM-USE</td> <td>N</td> <td><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5825036" target="_blank">PMC5825036</a></td> <td><a href="https://www.ncbi.nlm.nih.gov/pubmed/29474384.0" target="_blank">29474384.0</a></td> <td><a href="https://doi.org/10.1371/journal.pone.0193131" target="_blank">10.1371/journal.pone.0193131</a></td> <td>fie121ns</td> <td>0.498469</td> <td></td> <td></td> </tr> <tr> <th id="m4sp9sjn";>14</th> <td>Matthews_2010</td> <td>HIV Antigen Incorporation within Adenovirus Hexon Hypervariable 2 for a Novel HIV Vaccine Approach</td> <td>Matthews, Qiana L.; Fatima, Aiman; Tang, Yizhe; Perry, Brian A.; Tsuruta, Yuko; Komarova, Svetlana; Timares, Laura; Zhao, Chunxia; Makarova, Natalia; Borovjagin, Anton V.; Stewart, Phoebe L.; Wu, Hongju; Blackwell, Jerry L.; Curiel, David T.</td> <td>2010</td> <td>2010-07-27</td> <td>COMM-USE</td> <td>N</td> <td><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2910733" target="_blank">PMC2910733</a></td> <td><a href="https://www.ncbi.nlm.nih.gov/pubmed/20676400.0" target="_blank">20676400.0</a></td> <td><a href="https://doi.org/10.1371/journal.pone.0011815" target="_blank">10.1371/journal.pone.0011815</a></td> <td>m4sp9sjn</td> <td>0.495758</td> <td><a href="Topic_01.html#z2u5frvq">Montefiori_2007</a>, <a href="Topic_01.html#vct6xakc">Jiang_2006</a>, <a href="Topic_06.html#hrfbygub">Singh_2016</a></td> <td><a href="Topic_06.html#p6ikd8ns">Hansra_2015</a>, <a href="Topic_06.html#u361oua5">Peruzzi_2009</a></td> </tr> <tr> <th id="4mt2v3ip";>15</th> <td>Bayer_2011</td> <td>Improved vaccine protection against retrovirus infection after co-administration of adenoviral vectors encoding viral antigens and type I interferon subtypes</td> <td>Bayer, Wibke; Lietz, Ruth; Ontikatze, Teona; Johrden, Lena; Tenbusch, Matthias; Nabi, Ghulam; Schimmer, Simone; Groitl, Peter; Wolf, Hans; Berry, Cassandra M; Überla, Klaus; Dittmer, Ulf; Wildner, Oliver</td> <td>2011</td> <td>2011-09-26</td> <td>COMM-USE</td> <td>N</td> <td><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3193818" target="_blank">PMC3193818</a></td> <td><a href="https://www.ncbi.nlm.nih.gov/pubmed/21943056.0" target="_blank">21943056.0</a></td> <td><a href="https://doi.org/10.1186/1742-4690-8-75" target="_blank">10.1186/1742-4690-8-75</a></td> <td>4mt2v3ip</td> <td>0.491964</td> <td><a href="Topic_01.html#vct6xakc">Jiang_2006</a>, <a href="Topic_01.html#z2u5frvq">Montefiori_2007</a>, <a href="Topic_06.html#hrfbygub">Singh_2016</a></td> <td><a href="Topic_01.html#3qdjmb2j">Mok_H_2012</a>, <a href="Topic_06.html#s27bp7ft">Bolton_2012</a>, <a href="Topic_01.html#f78ug0c6">Meng_2012</a></td> </tr> <tr> <th id="mu4fdrel";>16</th> <td>Meseda_2004</td> <td>DNA immunization with a herpes simplex virus 2 bacterial artificial chromosome</td> <td>Meseda, Clement A.; Schmeisser, Falko; Pedersen, Robin; Woerner, Amy; Weir, Jerry P.</td> <td>2004</td> <td>2004-01-05</td> <td>PMC</td> <td>N</td> <td></td> <td><a href="https://www.ncbi.nlm.nih.gov/pubmed/14972567.0" target="_blank">14972567.0</a></td> <td><a href="https://doi.org/10.1016/j.virol.2003.09.033" target="_blank">10.1016/j.virol.2003.09.033</a></td> <td>mu4fdrel</td> <td>0.483117</td> <td></td> <td></td> </tr> <tr> <th id="yw8gubcy";>17</th> <td>Wang_2010</td> <td>Modified H5 promoter improves stability of insert genes while maintaining immunogenicity during extended passage of genetically engineered MVA vaccines</td> <td>Wang, Zhongde; Martinez, Joy; Zhou, Wendi; La Rosa, Corinna; Srivastava, Tumul; Dasgupta, Anindya; Rawal, Ravindra; Li, Zhongqui; Britt, William J.; Diamond, Don</td> <td>2010</td> <td>2010-02-10</td> <td>PMC</td> <td>N</td> <td></td> <td><a href="https://www.ncbi.nlm.nih.gov/pubmed/19969118.0" target="_blank">19969118.0</a></td> <td><a href="https://doi.org/10.1016/j.vaccine.2009.11.056" target="_blank">10.1016/j.vaccine.2009.11.056</a></td> <td>yw8gubcy</td> <td>0.477085</td> <td></td> <td></td> </tr> <tr> <th id="3894l9qi";>18</th> <td>Fausther-Bovendo_2014</td> <td>Pre-existing immunity against Ad vectors: Humoral, cellular, and innate response, what's important?</td> <td>Fausther-Bovendo, Hugues; Kobinger, Gary P</td> <td>2014</td> <td>2014-11-01</td> <td>NONCOMM</td> <td>N</td> <td><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5443060" target="_blank">PMC5443060</a></td> <td><a href="https://www.ncbi.nlm.nih.gov/pubmed/25483662.0" target="_blank">25483662.0</a></td> <td><a href="https://doi.org/10.4161/hv.29594" target="_blank">10.4161/hv.29594</a></td> <td>3894l9qi</td> <td>0.475906</td> <td><a href="Topic_01.html#z2u5frvq">Montefiori_2007</a>, <a href="Topic_06.html#hrfbygub">Singh_2016</a></td> <td><a href="Topic_01.html#pr9i9swk">Croyle_2008</a>, <a href="Topic_01.html#eu80ccm6">Pandey_2012</a></td> </tr> <tr> <th id="270nzddu";>19</th> <td>Busch_2020</td> <td>Measles Vaccines Designed for Enhanced CD8(+) T Cell Activation</td> <td>Busch, Elena; Kubon, Kristina D.; Mayer, Johanna K. M.; Pidelaserra-Martí, Gemma; Albert, Jessica; Hoyler, Birgit; Heidbuechel, Johannes P. W.; Stephenson, Kyle B.; Lichty, Brian D.; Osen, Wolfram; Eichmüller, Stefan B.; Jäger, Dirk; Ungerechts, Guy; Engeland, Christine E.</td> <td>2020</td> <td>2020-02-21</td> <td>None</td> <td>N</td> <td><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7077255" target="_blank">PMC7077255</a></td> <td><a href="https://www.ncbi.nlm.nih.gov/pubmed/32098134.0" target="_blank">32098134.0</a></td> <td><a href="https://doi.org/10.3390/v12020242" target="_blank">10.3390/v12020242</a></td> <td>270nzddu</td> <td>0.467243</td> <td><a href="Topic_01.html#z2u5frvq">Montefiori_2007</a></td> <td><a href="Topic_01.html#lcoo85s6">Kim_S_2012</a>, <a href="Topic_05.html#ctikde7d">Cervantes-Barragan_2010</a>, <a href="Topic_01.html#3qdjmb2j">Mok_H_2012</a></td> </tr> <tr> <th id="p6ikd8ns";>20</th> <td>Hansra_2015</td> <td>Exploration of New Sites in Adenovirus Hexon for Foreign Peptides Insertion</td> <td>Hansra, Satyender; Pujhari, Sujit; Zakhartchouk, Alexander N</td> <td>2015</td> <td>2015-05-29</td> <td>NONCOMM</td> <td>N</td> <td><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4460227" target="_blank">PMC4460227</a></td> <td><a href="https://www.ncbi.nlm.nih.gov/pubmed/26069516.0" target="_blank">26069516.0</a></td> <td><a href="https://doi.org/10.2174/1874357901509010001" target="_blank">10.2174/1874357901509010001</a></td> <td>p6ikd8ns</td> <td>0.466283</td> <td></td> <td><a href="Topic_06.html#m4sp9sjn">Matthews_2010</a></td> </tr> <tr> <th id="591iufv1";>21</th> <td>Babiuk_2000</td> <td>Adenoviruses as vectors for delivering vaccines to mucosal surfaces</td> <td>Babiuk, L.A; Tikoo, S.K</td> <td>2000</td> <td>2000-09-29</td> <td>PMC</td> <td>N</td> <td><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7126179" target="_blank">PMC7126179</a></td> <td><a href="https://www.ncbi.nlm.nih.gov/pubmed/11000466.0" target="_blank">11000466.0</a></td> <td><a href="https://doi.org/10.1016/s0168-1656(00)00314-x" target="_blank">10.1016/s0168-1656(00)00314-x</a></td> <td>591iufv1</td> <td>0.447938</td> <td><a href="Topic_01.html#z2u5frvq">Montefiori_2007</a></td> <td><a href="Topic_02.html#b8mfn6o9">Tarahomjoo_2011</a>, <a href="Topic_02.html#aw8p35c5">Tatsis_2004</a>, <a href="Topic_06.html#cmbg0ty8">Mühlebach_2016</a></td> </tr> <tr> <th id="cmbg0ty8";>22</th> <td>Mühlebach_2016</td> <td>Development of Recombinant Measles Virus-Based Vaccines</td> <td>Mühlebach, Michael D.; Hutzler, Stefan</td> <td>2016</td> <td>2016-11-26</td> <td>PMC</td> <td>N</td> <td><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7121886" target="_blank">PMC7121886</a></td> <td><a href="https://www.ncbi.nlm.nih.gov/pubmed/28374248.0" target="_blank">28374248.0</a></td> <td><a href="https://doi.org/10.1007/978-1-4939-6869-5_9" target="_blank">10.1007/978-1-4939-6869-5_9</a></td> <td>cmbg0ty8</td> <td>0.447755</td> <td></td> <td><a href="Topic_06.html#ryychtqa">Zuniga_2007</a>, <a href="Topic_01.html#3qdjmb2j">Mok_H_2012</a></td> </tr> <tr> <th id="gqqzekfk";>23</th> <td>Lin_C_2012</td> <td>Enhancement of anti-murine colon cancer immunity by fusion of a SARS fragment to a low-immunogenic carcinoembryonic antigen</td> <td>Lin, Chen-Si; Kao, Shih-Han; Chen, Yu-Cheng; Li, Chi-Han; Hsieh, Yuan-Ting; Yang, Shang-Chih; Wu, Chang-Jer; Lee, Ru-Ping; Liao, Kuang-Wen</td> <td>2012</td> <td>2012-02-03</td> <td>COMM-USE</td> <td>N</td> <td><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3298716" target="_blank">PMC3298716</a></td> <td><a href="https://www.ncbi.nlm.nih.gov/pubmed/22304896.0" target="_blank">22304896.0</a></td> <td><a href="https://doi.org/10.1186/1480-9222-14-2" target="_blank">10.1186/1480-9222-14-2</a></td> <td>gqqzekfk</td> <td>0.437763</td> <td><a href="Topic_01.html#xv0esvos">Azizi_2005</a>, <a href="Topic_01.html#z2u5frvq">Montefiori_2007</a>, <a href="Topic_06.html#hrfbygub">Singh_2016</a></td> <td><a href="Topic_01.html#lbx8tqws">Li_W_2013</a></td> </tr> <tr> <th id="tzq4i5xr";>24</th> <td>Bloom_2018</td> <td>Immunization by Replication-Competent Controlled Herpesvirus Vectors</td> <td>Bloom, David C.; Tran, Robert K.; Feller, Joyce; Voellmy, Richard</td> <td>2018</td> <td>2018-07-31</td> <td>COMM-USE</td> <td>N</td> <td><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC6069180" target="_blank">PMC6069180</a></td> <td><a href="https://www.ncbi.nlm.nih.gov/pubmed/29899091.0" target="_blank">29899091.0</a></td> <td><a href="https://doi.org/10.1128/jvi.00616-18" target="_blank">10.1128/jvi.00616-18</a></td> <td>tzq4i5xr</td> <td>0.437112</td> <td></td> <td><a href="Topic_06.html#cmbg0ty8">Mühlebach_2016</a>, <a href="Topic_01.html#qk2ureql">Maunder_2015</a></td> </tr> <tr> <th id="wi7qdbc7";>25</th> <td>Lawrence_2013</td> <td>Comparison of Heterologous Prime-Boost Strategies against Human Immunodeficiency Virus Type 1 Gag Using Negative Stranded RNA Viruses</td> <td>Lawrence, Tessa M.; Wanjalla, Celestine N.; Gomme, Emily A.; Wirblich, Christoph; Gatt, Anthony; Carnero, Elena; García-Sastre, Adolfo; Lyles, Douglas S.; McGettigan, James P.; Schnell, Matthias J.</td> <td>2013</td> <td>2013-06-26</td> <td>COMM-USE</td> <td>N</td> <td><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3694142" target="_blank">PMC3694142</a></td> <td><a href="https://www.ncbi.nlm.nih.gov/pubmed/23840600.0" target="_blank">23840600.0</a></td> <td><a href="https://doi.org/10.1371/journal.pone.0067123" target="_blank">10.1371/journal.pone.0067123</a></td> <td>wi7qdbc7</td> <td>0.435406</td> <td><a href="Topic_07.html#nzuq0dk7">Schwartz_2007</a>, <a href="Topic_01.html#z2u5frvq">Montefiori_2007</a>, <a href="Topic_01.html#vct6xakc">Jiang_2006</a></td> <td><a href="Topic_06.html#s27bp7ft">Bolton_2012</a>, <a href="Topic_01.html#vct6xakc">Jiang_2006</a>, <a href="Topic_01.html#3qdjmb2j">Mok_H_2012</a></td> </tr> <tr> <th id="lke4y02f";>26</th> <td>Bishop_1988</td> <td>The release into the environment of genetically engineered viruses, vaccines and viral pesticides</td> <td>Bishop, David H.L.</td> <td>1988</td> <td>1988-04-30</td> <td>PMC</td> <td>N</td> <td></td> <td></td> <td><a href="https://doi.org/10.1016/0167-7799(88)90006-6" target="_blank">10.1016/0167-7799(88)90006-6</a></td> <td>lke4y02f</td> <td>0.428086</td> <td><a href="Topic_06.html#s1zl9nbb">Bishop_1988</a></td> <td></td> </tr> <tr> <th id="7a6q4d3h";>27</th> <td>Thacker_2009</td> <td>Strategies to overcome host immunity to adenovirus vectors in vaccine development</td> <td>Thacker, Erin E; Timares, Laura; Matthews, Qiana L</td> <td>2009</td> <td>2009-06-01</td> <td>PMC</td> <td>N</td> <td><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3700409" target="_blank">PMC3700409</a></td> <td><a href="https://www.ncbi.nlm.nih.gov/pubmed/19485756.0" target="_blank">19485756.0</a></td> <td><a href="https://doi.org/10.1586/erv.09.29" target="_blank">10.1586/erv.09.29</a></td> <td>7a6q4d3h</td> <td>0.422274</td> <td><a href="Topic_01.html#z2u5frvq">Montefiori_2007</a>, <a href="Topic_07.html#fq78593b">Mooney_2013</a></td> <td><a href="Topic_02.html#7eqpb7ge">Borovjagin_2014</a>, <a href="Topic_02.html#aw8p35c5">Tatsis_2004</a>, <a href="Topic_06.html#v5n1gupw">Bangari_2006</a></td> </tr> <tr> <th id="dgeisr8h";>28</th> <td>Folegatti_2019</td> <td>Safety and Immunogenicity of a Novel Recombinant Simian Adenovirus ChAdOx2 as a Vectored Vaccine</td> <td>Folegatti, Pedro M.; Bellamy, Duncan; Roberts, Rachel; Powlson, Jonathan; Edwards, Nick J.; Mair, Catherine F.; Bowyer, Georgina; Poulton, Ian; Mitton, Celia H.; Green, Nicky; Berrie, Eleanor; Lawrie, Alison M.; Hill, Adrian V.S.; Ewer, Katie J.; Hermon-Taylor, John; Gilbert, Sarah C.</td> <td>2019</td> <td>2019-05-15</td> <td>COMM-USE</td> <td>N</td> <td><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC6630572" target="_blank">PMC6630572</a></td> <td><a href="https://www.ncbi.nlm.nih.gov/pubmed/31096710.0" target="_blank">31096710.0</a></td> <td><a href="https://doi.org/10.3390/vaccines7020040" target="_blank">10.3390/vaccines7020040</a></td> <td>dgeisr8h</td> <td>0.420425</td> <td><a href="Topic_07.html#nzuq0dk7">Schwartz_2007</a>, <a href="Topic_01.html#z2u5frvq">Montefiori_2007</a></td> <td><a href="Topic_02.html#u1xbkaq0">Ploquin_2013</a>, <a href="Topic_12.html#5zn2vrj5">Warimwe_2013</a></td> </tr> <tr> <th id="bmrfz8pz";>29</th> <td>Lopera-Madrid_2017</td> <td>Safety and immunogenicity of mammalian cell derived and Modified Vaccinia Ankara vectored African swine fever subunit antigens in swine</td> <td>Lopera-Madrid, Jaime; Osorio, Jorge E.; He, Yongqun; Xiang, Zuoshuang; Adams, L. Garry; Laughlin, Richard C.; Mwangi, Waithaka; Subramanya, Sandesh; Neilan, John; Brake, David; Burrage, Thomas G.; Brown, William Clay; Clavijo, Alfonso; Bounpheng, Mangkey A.</td> <td>2017</td> <td>2017-03-31</td> <td>PMC</td> <td>N</td> <td><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7112906" target="_blank">PMC7112906</a></td> <td><a href="https://www.ncbi.nlm.nih.gov/pubmed/28241999.0" target="_blank">28241999.0</a></td> <td><a href="https://doi.org/10.1016/j.vetimm.2017.01.004" target="_blank">10.1016/j.vetimm.2017.01.004</a></td> <td>bmrfz8pz</td> <td>0.418540</td> <td><a href="Topic_07.html#nzuq0dk7">Schwartz_2007</a></td> <td><a href="Topic_01.html#f78ug0c6">Meng_2012</a>, <a href="Topic_14.html#ngms51ie">Sawada_2011</a>, <a href="Topic_01.html#yk0xxv16">Do_V_2020</a></td> </tr> <tr> <th id="2sg1tlrg";>30</th> <td>Clarke_2006</td> <td>Recombinant vesicular stomatitis virus as an HIV-1 vaccine vector</td> <td>Clarke, David K.; Cooper, David; Egan, Michael A.; Hendry, R. Michael; Parks, Christopher L.; Udem, Stephen A.</td> <td>2006</td> <td>2006-09-15</td> <td>PMC</td> <td>N</td> <td><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7079905" target="_blank">PMC7079905</a></td> <td><a href="https://www.ncbi.nlm.nih.gov/pubmed/16977404.0" target="_blank">16977404.0</a></td> <td><a href="https://doi.org/10.1007/s00281-006-0042-3" target="_blank">10.1007/s00281-006-0042-3</a></td> <td>2sg1tlrg</td> <td>0.409973</td> <td><a href="Topic_07.html#nzuq0dk7">Schwartz_2007</a></td> <td><a href="Topic_12.html#i8xi0h4g">Akahata_2010</a>, <a href="Topic_01.html#3qdjmb2j">Mok_H_2012</a>, <a href="Topic_01.html#vct6xakc">Jiang_2006</a>, <a href="Topic_10.html#ovoli9dr">Keshwara_2019</a></td> </tr> <tr> <th id="zfuglf2e";>31</th> <td>Wyatt_2008</td> <td>Correlation of immunogenicities and in vitro expression levels of recombinant modified vaccinia virus Ankara HIV vaccines</td> <td>Wyatt, Linda S.; Earl, Patricia L.; Vogt, Jennifer; Eller, Leigh Anne; Chandran, Dev; Liu, Jinyan; Robinson, Harriet L.; Moss, Bernard</td> <td>2008</td> <td>2008-01-01</td> <td>PMC</td> <td>N</td> <td><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2262837" target="_blank">PMC2262837</a></td> <td><a href="https://www.ncbi.nlm.nih.gov/pubmed/18155813.0" target="_blank">18155813.0</a></td> <td><a href="https://doi.org/10.1016/j.vaccine.2007.11.036" target="_blank">10.1016/j.vaccine.2007.11.036</a></td> <td>zfuglf2e</td> <td>0.383510</td> <td><a href="Topic_01.html#vct6xakc">Jiang_2006</a></td> <td><a href="Topic_01.html#8kvs0qw8">Hao_H_2008</a>, <a href="Topic_01.html#d9v2s9o4">Zhang_2011</a></td> </tr> <tr> <th id="axkdf5vu";>32</th> <td>Kim_S_2016</td> <td>Newcastle Disease Virus as a Vaccine Vector for Development of Human and Veterinary Vaccines</td> <td>Kim, Shin-Hee; Samal, Siba K.</td> <td>2016</td> <td>2016-07-04</td> <td>COMM-USE</td> <td>N</td> <td><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4974518" target="_blank">PMC4974518</a></td> <td><a href="https://www.ncbi.nlm.nih.gov/pubmed/27384578.0" target="_blank">27384578.0</a></td> <td><a href="https://doi.org/10.3390/v8070183" target="_blank">10.3390/v8070183</a></td> <td>axkdf5vu</td> <td>0.383122</td> <td><a href="Topic_07.html#nzuq0dk7">Schwartz_2007</a></td> <td><a href="Topic_10.html#ovoli9dr">Keshwara_2019</a>, <a href="Topic_12.html#i8xi0h4g">Akahata_2010</a></td> </tr> <tr> <th id="1x1bnt5j";>33</th> <td>Huang_2005</td> <td>A differential proteome in tumors suppressed by an adenovirus-based skin patch vaccine encoding human carcinoembryonic antigen</td> <td>Huang, Chun-Ming; Shi, Zhongkai; DeSilva, Tivanka S.; Yamamoto, Masato; Van Kampen, Kent R.; Elmets, Craig A.; Tang, De-chu C.</td> <td>2005</td> <td>2005-03-01</td> <td>PMC</td> <td>N</td> <td><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3035721" target="_blank">PMC3035721</a></td> <td><a href="https://www.ncbi.nlm.nih.gov/pubmed/15717328.0" target="_blank">15717328.0</a></td> <td><a href="https://doi.org/10.1002/pmic.200401114" target="_blank">10.1002/pmic.200401114</a></td> <td>1x1bnt5j</td> <td>0.381976</td> <td><a href="Topic_01.html#wxf60gww">Hu_M_2007</a>, <a href="Topic_01.html#8kvs0qw8">Hao_H_2008</a></td> <td><a href="Topic_01.html#8kvs0qw8">Hao_H_2008</a></td> </tr> <tr> <th id="vct6xakc";>34</th> <td>Jiang_2006</td> <td>Elicitation of neutralizing antibodies by intranasal administration of recombinant vesicular stomatitis virus expressing human immunodeficiency virus type 1 gp120</td> <td>Jiang, Pengfei; Liu, Yanxia; Yin, Xiaolei; Yuan, Fei; Nie, YuChun; Luo, Min; Aihua, Zheng; Liyin, Du; Ding, Mingxiao; Deng, Hongkui</td> <td>2006</td> <td>2006-01-13</td> <td>PMC</td> <td>N</td> <td><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7092882" target="_blank">PMC7092882</a></td> <td><a href="https://www.ncbi.nlm.nih.gov/pubmed/16313884.0" target="_blank">16313884.0</a></td> <td><a href="https://doi.org/10.1016/j.bbrc.2005.11.067" target="_blank">10.1016/j.bbrc.2005.11.067</a></td> <td>vct6xakc</td> <td>0.380656</td> <td><a href="Topic_07.html#nzuq0dk7">Schwartz_2007</a></td> <td><a href="Topic_01.html#3qdjmb2j">Mok_H_2012</a>, <a href="Topic_01.html#5hryh1ft">Azizi_2006</a>, <a href="Topic_06.html#2sg1tlrg">Clarke_2006</a></td> </tr> <tr> <th id="u8y47qmd";>35</th> <td>Fedosyuk_2019</td> <td>Simian adenovirus vector production for early-phase clinical trials: A simple method applicable to multiple serotypes and using entirely disposable product-contact components</td> <td>Fedosyuk, Sofiya; Merritt, Thomas; Peralta-Alvarez, Marco Polo; Morris, Susan J; Lam, Ada; Laroudie, Nicolas; Kangokar, Anilkumar; Wright, Daniel; Warimwe, George M; Angell-Manning, Phillip; Ritchie, Adam J; Gilbert, Sarah C; Xenopoulos, Alex; Boumlic, Anissa; Douglas, Alexander D</td> <td>2019</td> <td>2019-11-08</td> <td>None</td> <td>N</td> <td><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC6949866" target="_blank">PMC6949866</a></td> <td><a href="https://www.ncbi.nlm.nih.gov/pubmed/31047679.0" target="_blank">31047679.0</a></td> <td><a href="https://doi.org/10.1016/j.vaccine.2019.04.056" target="_blank">10.1016/j.vaccine.2019.04.056</a></td> <td>u8y47qmd</td> <td>0.375573</td> <td><a href="Topic_02.html#pnl1acrj">Kopecky-Bromberg_2009</a>, <a href="Topic_07.html#neclg3gb">Tripp_2014</a></td> <td><a href="Topic_06.html#v5n1gupw">Bangari_2006</a>, <a href="Topic_02.html#aw8p35c5">Tatsis_2004</a>, <a href="Topic_06.html#489dpefx">Hammond_2005</a></td> </tr> <tr> <th id="hrfbygub";>36</th> <td>Singh_2016</td> <td>Heterologous Immunity between Adenoviruses and Hepatitis C Virus: A New Paradigm in HCV Immunity and Vaccines</td> <td>Singh, Shakti; Vedi, Satish; Samrat, Subodh Kumar; Li, Wen; Kumar, Rakesh; Agrawal, Babita</td> <td>2016</td> <td>2016-01-11</td> <td>COMM-USE</td> <td>N</td> <td><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4709057" target="_blank">PMC4709057</a></td> <td><a href="https://www.ncbi.nlm.nih.gov/pubmed/26751211.0" target="_blank">26751211.0</a></td> <td><a href="https://doi.org/10.1371/journal.pone.0146404" target="_blank">10.1371/journal.pone.0146404</a></td> <td>hrfbygub</td> <td>0.359073</td> <td><a href="Topic_01.html#z2u5frvq">Montefiori_2007</a></td> <td><a href="Topic_01.html#3qdjmb2j">Mok_H_2012</a>, <a href="Topic_12.html#i8xi0h4g">Akahata_2010</a></td> </tr> <tr> <th id="aw8p35c5";>37</th> <td>Tatsis_2004</td> <td>Adenoviruses as vaccine vectors</td> <td>Tatsis, Nia; Ertl, Hildegund C.J.</td> <td>2004</td> <td>2004-10-31</td> <td>PMC</td> <td>N</td> <td><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7106330" target="_blank">PMC7106330</a></td> <td><a href="https://www.ncbi.nlm.nih.gov/pubmed/15451446.0" target="_blank">15451446.0</a></td> <td><a href="https://doi.org/10.1016/j.ymthe.2004.07.013" target="_blank">10.1016/j.ymthe.2004.07.013</a></td> <td>aw8p35c5</td> <td>0.354678</td> <td><a href="Topic_01.html#z2u5frvq">Montefiori_2007</a>, <a href="Topic_06.html#v5n1gupw">Bangari_2006</a></td> <td><a href="Topic_06.html#v5n1gupw">Bangari_2006</a>, <a href="Topic_06.html#hrfbygub">Singh_2016</a>, <a href="Topic_02.html#7eqpb7ge">Borovjagin_2014</a>, <a href="Topic_06.html#mxtry60e">Mittal_2016</a></td> </tr> <tr> <th id="489dpefx";>38</th> <td>Hammond_2005</td> <td>Porcine adenovirus as a delivery system for swine vaccines and immunotherapeutics</td> <td>Hammond, Jef M.; Johnson, Michael A.</td> <td>2005</td> <td>2005-01-31</td> <td>PMC</td> <td>N</td> <td><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7128824" target="_blank">PMC7128824</a></td> <td><a href="https://www.ncbi.nlm.nih.gov/pubmed/15683761.0" target="_blank">15683761.0</a></td> <td><a href="https://doi.org/10.1016/j.tvjl.2003.09.007" target="_blank">10.1016/j.tvjl.2003.09.007</a></td> <td>489dpefx</td> <td>0.345603</td> <td><a href="Topic_06.html#axkdf5vu">Kim_S_2016</a></td> <td></td> </tr> <tr> <th id="v812zn3r";>39</th> <td>Saxena_2013</td> <td>Pre-existing immunity against vaccine vectors – friend or foe?</td> <td>Saxena, Manvendra; Van, Thi Thu Hao; Baird, Fiona J.; Coloe, Peter J.; Smooker, Peter M.</td> <td>2013</td> <td>2013-01-23</td> <td>COMM-USE</td> <td>N</td> <td><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3542731" target="_blank">PMC3542731</a></td> <td><a href="https://www.ncbi.nlm.nih.gov/pubmed/23175507.0" target="_blank">23175507.0</a></td> <td><a href="https://doi.org/10.1099/mic.0.049601-0" target="_blank">10.1099/mic.0.049601-0</a></td> <td>v812zn3r</td> <td>0.344349</td> <td><a href="Topic_01.html#z2u5frvq">Montefiori_2007</a>, <a href="Topic_07.html#neclg3gb">Tripp_2014</a></td> <td><a href="Topic_02.html#b8mfn6o9">Tarahomjoo_2011</a>, <a href="Topic_06.html#hrfbygub">Singh_2016</a>, <a href="Topic_01.html#2gt3fwpy">Meseda_2016</a></td> </tr> <tr> <th id="de0b27nq";>40</th> <td>Anraku_2008</td> <td>Kunjin replicon-based simian immunodeficiency virus gag vaccines</td> <td>Anraku, Itaru; Mokhonov, Vladislav V.; Rattanasena, Paweena; Mokhonova, Ekaterina I.; Leung, Jason; Pijlman, Gorben; Cara, Andrea; Schroder, Wayne A.; Khromykh, Alexander A.; Suhrbier, Andreas</td> <td>2008</td> <td>2008-06-19</td> <td>PMC</td> <td>N</td> <td><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7115363" target="_blank">PMC7115363</a></td> <td><a href="https://www.ncbi.nlm.nih.gov/pubmed/18462846.0" target="_blank">18462846.0</a></td> <td><a href="https://doi.org/10.1016/j.vaccine.2008.04.001" target="_blank">10.1016/j.vaccine.2008.04.001</a></td> <td>de0b27nq</td> <td>0.340714</td> <td></td> <td><a href="Topic_09.html#0h5vgi5c">Dahiya_2012</a></td> </tr> <tr> <th id="7del8d2p";>41</th> <td>Callendret_2007</td> <td>Heterologous viral RNA export elements improve expression of severe acute respiratory syndrome (SARS) coronavirus spike protein and protective efficacy of DNA vaccines against SARS</td> <td>Callendret, Benoît; Lorin, Valérie; Charneau, Pierre; Marianneau, Philippe; Contamin, Hugues; Betton, Jean-Michel; van der Werf, Sylvie; Escriou, Nicolas</td> <td>2007</td> <td>2007-07-05</td> <td>PMC</td> <td>N</td> <td><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7103356" target="_blank">PMC7103356</a></td> <td><a href="https://www.ncbi.nlm.nih.gov/pubmed/17331558.0" target="_blank">17331558.0</a></td> <td><a href="https://doi.org/10.1016/j.virol.2007.01.012" target="_blank">10.1016/j.virol.2007.01.012</a></td> <td>7del8d2p</td> <td>0.328733</td> <td></td> <td><a href="Topic_01.html#mghgvr76">Liu_R_2005</a>, <a href="Topic_01.html#ltyqrg81">Escriou_2014</a></td> </tr> <tr> <th id="dqvgng2s";>42</th> <td>Ohtsuka_2019</td> <td>A versatile platform technology for recombinant vaccines using non-propagative human parainfluenza virus type 2 vector</td> <td>Ohtsuka, Junpei; Fukumura, Masayuki; Furuyama, Wakako; Wang, Shujie; Hara, Kenichiro; Maeda, Mitsuyo; Tsurudome, Masato; Miyamoto, Hiroko; Kaito, Aika; Tsuda, Nobuyuki; Kataoka, Yosky; Mizoguchi, Akira; Takada, Ayato; Nosaka, Tetsuya</td> <td>2019</td> <td>2019-09-09</td> <td>COMM-USE</td> <td>N</td> <td><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC6733870" target="_blank">PMC6733870</a></td> <td><a href="https://www.ncbi.nlm.nih.gov/pubmed/31501502.0" target="_blank">31501502.0</a></td> <td><a href="https://doi.org/10.1038/s41598-019-49579-y" target="_blank">10.1038/s41598-019-49579-y</a></td> <td>dqvgng2s</td> <td>0.328249</td> <td><a href="Topic_01.html#vct6xakc">Jiang_2006</a>, <a href="Topic_07.html#nzuq0dk7">Schwartz_2007</a></td> <td><a href="Topic_01.html#8kvs0qw8">Hao_H_2008</a>, <a href="Topic_04.html#0czzjeop">Chen_2007</a></td> </tr> <tr> <th id="4vkag60z";>43</th> <td>Nakayama_2016</td> <td>Recombinant measles AIK-C vaccine strain expressing heterologous virus antigens</td> <td>Nakayama, Tetsuo; Sawada, Akihito; Yamaji, Yoshiaki; Ito, Takashi</td> <td>2016</td> <td>2016-01-04</td> <td>PMC</td> <td>N</td> <td><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7115616" target="_blank">PMC7115616</a></td> <td><a href="https://www.ncbi.nlm.nih.gov/pubmed/26562316.0" target="_blank">26562316.0</a></td> <td><a href="https://doi.org/10.1016/j.vaccine.2015.10.127" target="_blank">10.1016/j.vaccine.2015.10.127</a></td> <td>4vkag60z</td> <td>0.325056</td> <td><a href="Topic_07.html#fq78593b">Mooney_2013</a></td> <td><a href="Topic_14.html#ngms51ie">Sawada_2011</a>, <a href="Topic_06.html#cmbg0ty8">Mühlebach_2016</a>, <a href="Topic_01.html#3qdjmb2j">Mok_H_2012</a></td> </tr> <tr> <th id="tjvjlyn9";>44</th> <td>Luke_2010</td> <td>Improved antibiotic-free plasmid vector design by incorporation of transient expression enhancers</td> <td>Luke, J M; Vincent, J M; Du, S X; Gerdemann, U; Leen, A M; Whalen, R G; Hodgson, C P; Williams, J A</td> <td>2010</td> <td>2010-11-25</td> <td>PMC</td> <td>N</td> <td><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7091570" target="_blank">PMC7091570</a></td> <td><a href="https://www.ncbi.nlm.nih.gov/pubmed/21107439.0" target="_blank">21107439.0</a></td> <td><a href="https://doi.org/10.1038/gt.2010.149" target="_blank">10.1038/gt.2010.149</a></td> <td>tjvjlyn9</td> <td>0.320161</td> <td></td> <td></td> </tr> <tr> <th id="a3nzj6yh";>45</th> <td>Zhang_2016</td> <td>Adenoviral vector-based strategies against infectious disease and cancer</td> <td>Zhang, Chao; Zhou, Dongming</td> <td>2016</td> <td>2016-04-22</td> <td>NONCOMM</td> <td>N</td> <td><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4994731" target="_blank">PMC4994731</a></td> <td><a href="https://www.ncbi.nlm.nih.gov/pubmed/27105067.0" target="_blank">27105067.0</a></td> <td><a href="https://doi.org/10.1080/21645515.2016.1165908" target="_blank">10.1080/21645515.2016.1165908</a></td> <td>a3nzj6yh</td> <td>0.305064</td> <td><a href="Topic_01.html#z2u5frvq">Montefiori_2007</a>, <a href="Topic_02.html#aw8p35c5">Tatsis_2004</a>, <a href="Topic_07.html#fq78593b">Mooney_2013</a></td> <td><a href="Topic_02.html#aw8p35c5">Tatsis_2004</a>, <a href="Topic_02.html#7eqpb7ge">Borovjagin_2014</a>, <a href="Topic_02.html#odeksech">Ertl_2016</a></td> </tr> <tr> <th id="l3ej1hdk";>46</th> <td>Patel_2010</td> <td>A Porcine Adenovirus with Low Human Seroprevalence Is a Promising Alternative Vaccine Vector to Human Adenovirus 5 in an H5N1 Virus Disease Model</td> <td>Patel, Ami; Tikoo, Suresh; Kobinger, Gary</td> <td>2010</td> <td>2010-12-16</td> <td>COMM-USE</td> <td>N</td> <td><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3002947" target="_blank">PMC3002947</a></td> <td><a href="https://www.ncbi.nlm.nih.gov/pubmed/21179494.0" target="_blank">21179494.0</a></td> <td><a href="https://doi.org/10.1371/journal.pone.0015301" target="_blank">10.1371/journal.pone.0015301</a></td> <td>l3ej1hdk</td> <td>0.304688</td> <td><a href="Topic_07.html#nzuq0dk7">Schwartz_2007</a></td> <td><a href="Topic_01.html#f78ug0c6">Meng_2012</a>, <a href="Topic_12.html#5zn2vrj5">Warimwe_2013</a>, <a href="Topic_07.html#xdpajuit">Wu_P_2017</a></td> </tr> <tr> <th id="7mi07qm9";>47</th> <td>Hangalapura_2012</td> <td>CD40-targeted adenoviral cancer vaccines: the long and winding road to the clinic</td> <td>Hangalapura, Basav N.; Timares, Laura; Oosterhoff, Dinja; Scheper, Rik J.; Curiel, David T.; de Gruijl, Tanja D.</td> <td>2012</td> <td>2012-06-01</td> <td>PMC</td> <td>N</td> <td><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3433169" target="_blank">PMC3433169</a></td> <td><a href="https://www.ncbi.nlm.nih.gov/pubmed/22228547.0" target="_blank">22228547.0</a></td> <td><a href="https://doi.org/10.1002/jgm.1648" target="_blank">10.1002/jgm.1648</a></td> <td>7mi07qm9</td> <td>0.304020</td> <td><a href="Topic_01.html#z2u5frvq">Montefiori_2007</a></td> <td><a href="Topic_05.html#tkzwzc57">Garu_2016</a>, <a href="Topic_05.html#ctikde7d">Cervantes-Barragan_2010</a></td> </tr> <tr> <th id="tbp3it7r";>48</th> <td>Liniger_2008</td> <td>Induction of neutralising antibodies and cellular immune responses against SARS coronavirus by recombinant measles viruses</td> <td>Liniger, Matthias; Zuniga, Armando; Tamin, Azaibi; Azzouz-Morin, Teldja N.; Knuchel, Marlyse; Marty, Rene R.; Wiegand, Marian; Weibel, Sara; Kelvin, David; Rota, Paul A.; Naim, Hussein Y.</td> <td>2008</td> <td>2008-04-16</td> <td>PMC</td> <td>N</td> <td><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7115634" target="_blank">PMC7115634</a></td> <td><a href="https://www.ncbi.nlm.nih.gov/pubmed/18346823.0" target="_blank">18346823.0</a></td> <td><a href="https://doi.org/10.1016/j.vaccine.2008.01.057" target="_blank">10.1016/j.vaccine.2008.01.057</a></td> <td>tbp3it7r</td> <td>0.300148</td> <td><a href="Topic_07.html#nzuq0dk7">Schwartz_2007</a>, <a href="Topic_03.html#k785hl1r">Lv_L_2014</a></td> <td><a href="Topic_01.html#ltyqrg81">Escriou_2014</a></td> </tr> </tbody> </table> </body> </html>
roaminsight/roamresearch
docs/CORD19_topics/cord19-2020-04-24-v9/text-ents-en-75-t13-15/Topic_06.html
HTML
apache-2.0
47,884
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" xmlns:yq="http://www.yqboots.com" xmlns="http://www.w3.org/1999/xhtml" layout:decorator="layouts/layout"> <head> <title th:text="#{FSS0001}">File Management</title> </head> <body> <div layout:fragment="breadcrumbs"> <yq:breadcrumbs menu="FSS"/> </div> <div class="content content-sm height-600" layout:fragment="content"> <div class="container"> <yq:alert level="danger" /> <form class="sky-form" action="#" th:action="@{/fss/}" th:object="${model}" method="post" enctype="multipart/form-data"> <header th:text="#{FSS0012}">FSS Form</header> <fieldset> <section> <label class="label" th:text="#{FSS0013}">Input a File</label> <label class="input input-file"> <div class="button"> <input th:field="*{file}" type="file"/> <span th:text="#{FSS0014}">Browse</span> </div> <input type="text" readonly="readonly"/> </label> <p th:if="${#fields.hasErrors('file')}" th:errors="*{file}"></p> </section> <section> <label class="label" th:text="#{FSS0015}">Destination</label> <label class="select"> <select th:field="*{path}"> <option value="" th:text="#{FSS0016}">Please Select</option> <yq:options name="FSS_AVAILABLE_DIRS"/> </select> <i></i> </label> <p th:if="${#fields.hasErrors('path')}" th:errors="*{path}"></p> </section> <section> <label class="label" th:text="#{FSS0017}">Override</label> <input th:field="*{overrideExisting}" type="checkbox"/> <label th:for="${#ids.prev('overrideExisting')}" th:text="#{FSS0018}">Override Existing?</label> </section> </fieldset> <footer> <button class="btn-u rounded" type="submit" th:text="#{FSS0019}">Submit</button> <button class="btn-u rounded" id="cancel" type="reset" th:text="#{FSS0020}">Reset</button> </footer> </form> </div> </div> </body> </html>
zhanhongbo1112/trunk
yqboots-fss/yqboots-fss-web/src/main/resources/templates/fss/form.html
HTML
apache-2.0
2,179
Osprey ====== [![Build Status](https://travis-ci.org/msmbuilder/osprey.svg?branch=master)](https://travis-ci.org/msmbuilder/osprey) [![Coverage Status](https://coveralls.io/repos/github/msmbuilder/osprey/badge.svg?branch=master)](https://coveralls.io/github/msmbuilder/osprey?branch=master) [![PyPi version](https://badge.fury.io/py/osprey.svg)](https://pypi.python.org/pypi/osprey/) [![License](https://img.shields.io/badge/license-ASLv2.0-red.svg?style=flat)](http://www.apache.org/licenses/LICENSE-2.0) [![DOI](http://joss.theoj.org/papers/10.21105/joss.00034/status.svg)](http://dx.doi.org/10.21105/joss.00034) [![Research software impact](http://depsy.org/api/package/pypi/osprey/badge.svg)](http://depsy.org/package/python/osprey) [![Documentation](https://img.shields.io/badge/docs-latest-blue.svg?style=flat)](http://msmbuilder.org/osprey) ![Logo](http://msmbuilder.org/osprey/development/_static/osprey.svg) Osprey is an easy-to-use tool for hyperparameter optimization for machine learning algorithms in python using scikit-learn (or using scikit-learn compatible APIs). Each Osprey experiment combines an dataset, an estimator, a search space (and engine), cross validation and asynchronous serialization for distributed parallel optimization of model hyperparameters. Documentation ------------ For full documentation, please visit the [Osprey homepage](http://msmbuilder.org/osprey/). Installation ------------ If you have an Anaconda Python distribution, installation is as easy as: ``` $ conda install -c omnia osprey ``` You can also install Osprey with `pip`: ``` $ pip install osprey ``` Alternatively, you can install directly from this GitHub repo: ``` $ git clone https://github.com/msmbuilder/osprey.git $ cd osprey && git checkout 1.1.0 $ python setup.py install ``` Example using [MSMBuilder](https://github.com/msmbuilder/msmbuilder) ------------------------------------------------------------- Below is an example of an osprey `config` file to cross validate Markov state models based on varying the number of clusters and dihedral angles used in a model: ```yaml estimator: eval_scope: msmbuilder eval: | Pipeline([ ('featurizer', DihedralFeaturizer(types=['phi', 'psi'])), ('cluster', MiniBatchKMeans()), ('msm', MarkovStateModel(n_timescales=5, verbose=False)), ]) search_space: cluster__n_clusters: min: 10 max: 100 type: int featurizer__types: choices: - ['phi', 'psi'] - ['phi', 'psi', 'chi1'] type: enum cv: 5 dataset_loader: name: mdtraj params: trajectories: ~/local/msmbuilder/Tutorial/XTC/*/*.xtc topology: ~/local/msmbuilder/Tutorial/native.pdb stride: 1 trials: uri: sqlite:///osprey-trials.db ``` Then run `osprey worker`. You can run multiple parallel instances of `osprey worker` simultaneously on a cluster too. ``` $ osprey worker config.yaml ... ---------------------------------------------------------------------- Beginning iteration 1 / 1 ---------------------------------------------------------------------- History contains: 0 trials Choosing next hyperparameters with random... {'cluster__n_clusters': 20, 'featurizer__types': ['phi', 'psi']} Fitting 5 folds for each of 1 candidates, totalling 5 fits [Parallel(n_jobs=1)]: Done 1 jobs | elapsed: 0.3s [Parallel(n_jobs=1)]: Done 5 out of 5 | elapsed: 1.8s finished --------------------------------- Success! Model score = 4.080646 (best score so far = 4.080646) --------------------------------- 1/1 models fit successfully. time: October 27, 2014 10:44 PM elapsed: 4 seconds. osprey worker exiting. ``` You can dump the database to JSON or CSV with `osprey dump`. Dependencies ------------ - `python>=2.7.11` - `six>=1.10.0` - `pyyaml>=3.11` - `numpy>=1.10.4` - `scipy>=0.17.0` - `scikit-learn>=0.17.0` - `sqlalchemy>=1.0.10` - `bokeh>=0.12.0` - `matplotlib>=1.5.0` - `pandas>=0.18.0` - `GPy` (optional, required for `gp` strategy) - `hyperopt` (optional, required for `hyperopt_tpe` strategy) - `nose` (optional, for testing) Contributing ------------ In case you encounter any issues with this package, please consider submitting a ticket to the [GitHub Issue Tracker](https://github.com/msmbuilder/osprey/issues). We also welcome any feature requests and highly encourage users to [submit pull requests](https://help.github.com/articles/creating-a-pull-request/) for bug fixes and improvements. For more detailed information, please refer to our [documentation](http://msmbuilder.org/osprey/development/contributing.html). Citing ------ If you use Osprey in your research, please cite: ```bibtex @misc{osprey, author = {Robert T. McGibbon and Carlos X. Hernández and Matthew P. Harrigan and Steven Kearnes and Mohammad M. Sultan and Stanislaw Jastrzebski and Brooke E. Husic and Vijay S. Pande}, title = {Osprey: Hyperparameter Optimization for Machine Learning}, month = sep, year = 2016, doi = {10.21105/joss.000341}, url = {http://dx.doi.org/10.21105/joss.00034} } ```
msultan/osprey
README.md
Markdown
apache-2.0
5,266
import { Component } from '@angular/core'; import { Platform } from 'ionic-angular'; import { InAppBrowser } from '@ionic-native/in-app-browser'; @Component({ selector: 'page-apuntes', templateUrl: 'apuntes.html' }) export class ApuntesPage { constructor(public platform: Platform, private theInAppBrowser: InAppBrowser){} launch() { this.platform.ready().then(() => { this.theInAppBrowser.create("http://apuntes.lafuenteunlp.com.ar", '_self', 'location=yes'); }); } /* ionViewDidLoad() { this.confData.getMap().subscribe((mapData: any) => { let mapEle = this.mapElement.nativeElement; let map = new google.maps.Map(mapEle, { center: mapData.find((d: any) => d.center), zoom: 16 }); mapData.forEach((markerData: any) => { let infoWindow = new google.maps.InfoWindow({ content: `<h5>${markerData.name}</h5>` }); let marker = new google.maps.Marker({ position: markerData, map: map, title: markerData.name }); marker.addListener('click', () => { infoWindow.open(map, marker); }); }); google.maps.event.addListenerOnce(map, 'idle', () => { mapEle.classList.add('show-map'); }); }); } */ }
tomibarbieri/lafuente
src/pages/apuntes/apuntes.ts
TypeScript
apache-2.0
1,350
/*price range*/ $('#sl2').slider(); var RGBChange = function() { $('#RGB').css('background', 'rgb('+r.getValue()+','+g.getValue()+','+b.getValue()+')') }; /*scroll to top*/ $(document).ready(function(){ $(function () { $.scrollUp({ scrollName: 'scrollUp', // Element ID scrollDistance: 300, // Distance from top/bottom before showing element (px) scrollFrom: 'top', // 'top' or 'bottom' scrollSpeed: 300, // Speed back to top (ms) easingType: 'linear', // Scroll to top easing (see http://easings.net/) animation: 'fade', // Fade, slide, none animationSpeed: 200, // Animation in speed (ms) scrollTrigger: false, // Set a custom triggering element. Can be an HTML string or jQuery object //scrollTarget: false, // Set a custom target element for scrolling to the top scrollText: '<i class="fa fa-angle-up"></i>', // Text for element, can contain HTML scrollTitle: false, // Set a custom <a> title if required. scrollImg: false, // Set true to use image activeOverlay: false, // Set CSS color to display scrollUp active point, e.g '#00FFFF' zIndex: 2147483647 // Z-Index for the overlay }); }); }); // Returns a random integer between min and max // Using Math.round() will give you a non-uniform distribution! function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } // Replace url parameter - WishlistItems function replaceUrlParam(url, paramName, paramValue) { var pattern = new RegExp('(' + paramName + '=).*?(&|$)') var newUrl = url if (url.search(pattern) >= 0) { newUrl = url.replace(pattern, '$1' + paramValue + '$2'); } else { newUrl = newUrl + (newUrl.indexOf('?') > 0 ? '&' : '?') + paramName + '=' + paramValue } return newUrl } // Scroll back to selected wishlist item if (window.location.hash != '') { var target = window.location.hash; //var $target = $(target); $('html, body').stop().animate({ //'scrollTop': $target.offset().top }, 900, 'swing', function () { window.location.hash = target; }); }
ReinID/ReinID
Samples/.Net/.Netproperty4u/Property4U/Scripts/main.js
JavaScript
apache-2.0
2,179
import sys sys.path.insert(1,"../../../") import h2o from tests import pyunit_utils from h2o.estimators.gbm import H2OGradientBoostingEstimator def mnist_many_cols_gbm_large(): train = h2o.import_file(path=pyunit_utils.locate("bigdata/laptop/mnist/train.csv.gz")) train.tail() gbm_mnist = H2OGradientBoostingEstimator(ntrees=1, max_depth=1, min_rows=10, learn_rate=0.01) gbm_mnist.train(x=range(784), y=784, training_frame=train) gbm_mnist.show() if __name__ == "__main__": pyunit_utils.standalone_test(mnist_many_cols_gbm_large) else: mnist_many_cols_gbm_large()
madmax983/h2o-3
h2o-py/tests/testdir_algos/gbm/pyunit_mnist_manyCols_gbm_large.py
Python
apache-2.0
712
<?php use Phalcon\DI\FactoryDefault\CLI as CliDI, Phalcon\CLI\Console as ConsoleApp; define('VERSION', '1.0.0'); //使用CLI工厂类作为默认的服务容器 $di = new CliDI(); // 定义应用目录路径 defined('APP_PATH') || define('APP_PATH', realpath(dirname(dirname(__FILE__)))); /** * * 注册类自动加载器 */ $loader = new \Phalcon\Loader(); $loader->registerDirs( array( APP_PATH . '/tasks', APP_PATH . '/apps/models', ) ); $loader->register(); //加载配置文件(如果存在) if(is_readable(APP_PATH . '/config/config.php')) { $config = include APP_PATH . '/config/config.php'; $di->set('config', $config); $di->set('db', function() use ( $config, $di) { //新建一个事件管理器 $eventsManager = new \Phalcon\Events\Manager(); $profiler = new \Phalcon\Db\Profiler(); //监听所有的db事件 $eventsManager->attach('db', function($event, $connection) use ($profiler) { //一条语句查询之前事件,profiler开始记录sql语句 if ($event->getType() == 'beforeQuery') { $profiler->startProfile($connection->getSQLStatement()); } //一条语句查询结束,结束本次记录,记录结果会保存在profiler对象中 if ($event->getType() == 'afterQuery') { $profiler->stopProfile(); } }); $connection = new \Phalcon\Db\Adapter\Pdo\Mysql( [ "host" => $config->database->host, "username" => $config->database->username, "password" => $config->database->password, "dbname" => $config->database->dbname, "charset" => $config->database->charset ] ); //将事件管理器绑定到db实例中 $connection->setEventsManager($eventsManager); return $connection; }); } // 创建console应用 $console = new ConsoleApp(); $console->setDI($di); /** * 处理console应用参数 */ $arguments = array(); foreach($argv as $k => $arg) { if($k == 1) { $arguments['task'] = $arg; } elseif($k == 2) { $arguments['action'] = $arg; } elseif($k >= 3) { $arguments['params'][] = $arg; } } // 定义全局的参数, 设定当前任务及action define('CURRENT_TASK', (isset($argv[1]) ? $argv[1] : null)); define('CURRENT_ACTION', (isset($argv[2]) ? $argv[2] : null)); try { // 处理参数 $console->handle($arguments); } catch (\Phalcon\Exception $e) { echo $e->getMessage(); exit(255); }
leisir2017/phalcon
tasks/cli.php
PHP
apache-2.0
2,843
# Flagenium petrikense Ruhsam & A.P.Davis 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/Gentianales/Rubiaceae/Flagenium/Flagenium petrikense/README.md
Markdown
apache-2.0
197
# Cephaelis dolichophylla Standl. 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/Gentianales/Rubiaceae/Carapichea/Carapichea dolichophylla/ Syn. Cephaelis dolichophylla/README.md
Markdown
apache-2.0
188
# Begonia cognata Irmsch. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in Webbia 9:477. 1953 #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Cucurbitales/Begoniaceae/Begonia/Begonia cognata/README.md
Markdown
apache-2.0
187
# Siphoneranthemum alatum Kuntze SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Acanthaceae/Siphoneranthemum/Siphoneranthemum alatum/README.md
Markdown
apache-2.0
180
# Plectranthus mysurensis Heyne ex Wall. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Lamiaceae/Plectranthus/Plectranthus mysurensis/README.md
Markdown
apache-2.0
188
# Brizopyrum boreale J.Presl 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/Liliopsida/Poales/Poaceae/Distichlis/Distichlis spicata/ Syn. Brizopyrum boreale/README.md
Markdown
apache-2.0
183
# Ziziphus cinnamomum Triana & Planch. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Rosales/Rhamnaceae/Ziziphus/Ziziphus cinnamomum/README.md
Markdown
apache-2.0
186
# Aurinia leucadea (Guss.) K. Koch SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name Alyssum leucadeum Guss. ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Brassicales/Brassicaceae/Aurinia/Aurinia leucadea/README.md
Markdown
apache-2.0
209
-- create in cinefiles_domain database, cinefiles_denorm schema CREATE OR REPLACE FUNCTION cinefiles_denorm.concat_worktitles (shortid VARCHAR) RETURNS VARCHAR AS $$ DECLARE titlestring VARCHAR(1000); preftitle VARCHAR(500); engltitle VARCHAR(500); prefcount INTEGER; englcount INTEGER; errormsg VARCHAR(500); BEGIN select into prefcount count(*) from works_common wc inner join hierarchy hwc on ( wc.id = hwc.parentid and hwc.primarytype = 'workTermGroup' and hwc.pos = 0) inner join worktermgroup wtg on (hwc.id = wtg.id) where wc.shortidentifier = $1; select into englcount count(*) from works_common wc inner join hierarchy hwc on ( wc.id = hwc.parentid and hwc.primarytype = 'workTermGroup' and hwc.pos > 0) inner join worktermgroup wtg on ( hwc.id = wtg.id and wtg.termlanguage like '%''English''%') where wc.shortidentifier = $1; IF prefcount = 0 THEN return NULL; ELSEIF prefcount > 1 THEN errormsg := 'There can be only one! But there are ' || prefcount::text || ' preferred titles!'; RAISE EXCEPTION '%', errormsg; ELSEIF prefcount = 1 THEN select into preftitle trim(wtg.termdisplayname) from works_common wc inner join hierarchy hwc on ( wc.id = hwc.parentid and hwc.primarytype = 'workTermGroup' and hwc.pos = 0) inner join worktermgroup wtg on (hwc.id = wtg.id) where wc.shortidentifier = $1; IF englcount = 0 THEN titlestring := preftitle; RETURN titlestring; ELSEIF englcount = 1 THEN select into engltitle trim(wtg.termdisplayname) from works_common wc inner join hierarchy hwc on ( wc.id = hwc.parentid and hwc.primarytype = 'workTermGroup' and hwc.pos > 0) inner join worktermgroup wtg on ( hwc.id = wtg.id and wtg.termlanguage like '%''English''%') where wc.shortidentifier = $1; titlestring := preftitle || ' (' || engltitle || ')'; RETURN titlestring; ELSEIF englcount > 1 THEN errormsg := 'There can be only one! But there are ' || englcount::text || ' non-preferred English titles!'; RAISE EXCEPTION '%', errormsg; ELSE errormsg := 'Unable to get a count of non-preferred English titles!'; RAISE EXCEPTION '%', errormsg; END IF; ELSE errormsg := 'Unable to get a count of preferred titles!'; RAISE EXCEPTION '%', errormsg; END IF; RETURN NULL; END; $$ LANGUAGE 'plpgsql' IMMUTABLE RETURNS NULL ON NULL INPUT; GRANT EXECUTE ON FUNCTION cinefiles_denorm.concat_worktitles (filmid VARCHAR) TO PUBLIC;
itsdavidbaxter/Tools
functions/cinefiles/concat_worktitles.sql
SQL
apache-2.0
2,661
--- layout: base title: 'Statistics of appos:nmod in UD_French-Spoken' udver: '2' --- ## Treebank Statistics: UD_French-Spoken: Relations: `appos:nmod` This relation is a language-specific subtype of . There are also 1 other language-specific subtypes of `appos`: <tt><a href="fr_spoken-dep-appos-conj.html">appos:conj</a></tt>. 101 nodes (0%) are attached to their parents as `appos:nmod`. 101 instances of `appos:nmod` (100%) are left-to-right (parent precedes child). Average distance between parent and child is 1.06930693069307. The following 4 pairs of parts of speech are connected with `appos:nmod`: <tt><a href="fr_spoken-pos-NOUN.html">NOUN</a></tt>-<tt><a href="fr_spoken-pos-PROPN.html">PROPN</a></tt> (95; 94% instances), <tt><a href="fr_spoken-pos-PROPN.html">PROPN</a></tt>-<tt><a href="fr_spoken-pos-PROPN.html">PROPN</a></tt> (4; 4% instances), <tt><a href="fr_spoken-pos-NOUN.html">NOUN</a></tt>-<tt><a href="fr_spoken-pos-NUM.html">NUM</a></tt> (1; 1% instances), <tt><a href="fr_spoken-pos-PRON.html">PRON</a></tt>-<tt><a href="fr_spoken-pos-PROPN.html">PROPN</a></tt> (1; 1% instances). ~~~ conllu # visual-style 7 bgColor:blue # visual-style 7 fgColor:white # visual-style 6 bgColor:blue # visual-style 6 fgColor:white # visual-style 6 7 appos:nmod color:blue 1 la le DET _ _ 2 det _ _ 2 foire foire NOUN _ _ 0 root _ _ 3 d' de ADP _ _ 4 case _ _ 4 empoigne empoigne NOUN _ _ 2 nmod _ _ 5 au à+le ADP _ _ 6 case _ _ 6 procès procès NOUN _ _ 2 nmod _ _ 7 Colonna Colonna PROPN _ _ 6 appos:nmod _ _ ~~~ ~~~ conllu # visual-style 7 bgColor:blue # visual-style 7 fgColor:white # visual-style 6 bgColor:blue # visual-style 6 fgColor:white # visual-style 6 7 appos:nmod color:blue 1 et et CCONJ _ _ 12 cc _ _ 2 puis puis ADV _ _ 1 fixed _ _ 3 après après ADP _ _ 12 obl:periph _ _ 4 rue rue NOUN _ _ 12 dislocated _ _ 5 du de+le ADP _ _ 6 case _ _ 6 Faubourg Faubourg PROPN _ _ 4 nmod _ _ 7 Saint Saint PROPN _ _ 6 appos:nmod _ _ 8 Antoine Antoine PROPN _ _ 7 flat _ _ 9 c' ce PRON _ _ 12 nsubj _ _ 10 est être AUX _ _ 12 cop _ _ 11 très très ADV _ _ 12 advmod _ _ 12 vivant vivant ADJ _ _ 0 root _ _ ~~~ ~~~ conllu # visual-style 5 bgColor:blue # visual-style 5 fgColor:white # visual-style 2 bgColor:blue # visual-style 2 fgColor:white # visual-style 2 5 appos:nmod color:blue 1 mes son DET _ _ 2 det _ _ 2 parents parent NOUN _ _ 7 nsubj _ _ 3 tous tout ADJ _ _ 5 amod _ _ 4 les le DET _ _ 5 det _ _ 5 deux deux NUM _ _ 2 appos:nmod _ _ 6 ont avoir AUX _ _ 7 aux _ _ 7 vécu vivre VERB _ _ 0 root _ _ 8 à à ADP _ _ 9 case _ _ 9 Paris Paris PROPN _ _ 7 obl:comp _ _ 10 jeunes jeune ADJ _ _ 7 advmod _ _ 11 hein hein INTJ _ _ 10 discourse _ _ ~~~
UniversalDependencies/docs
treebanks/fr_rhapsodie/fr_spoken-dep-appos-nmod.md
Markdown
apache-2.0
2,691
<!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="refresh" content="0;URL=constant.SDL_SCANCODE_LSHIFT.html"> </head> <body> <p>Redirecting to <a href="constant.SDL_SCANCODE_LSHIFT.html">constant.SDL_SCANCODE_LSHIFT.html</a>...</p> <script>location.replace("constant.SDL_SCANCODE_LSHIFT.html" + location.search + location.hash);</script> </body> </html>
nitro-devs/nitro-game-engine
docs/sdl2_sys/scancode/SDL_SCANCODE_LSHIFT.v.html
HTML
apache-2.0
373
<?php namespace Google\AdsApi\AdWords\v201809\cm; /** * This file was generated from WSDL. DO NOT EDIT. */ class IdErrorReason { const NOT_FOUND = 'NOT_FOUND'; }
googleads/googleads-php-lib
src/Google/AdsApi/AdWords/v201809/cm/IdErrorReason.php
PHP
apache-2.0
173
# Abutilon densiflorum Walp. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Malvales/Malvaceae/Abutilon/Abutilon densiflorum/README.md
Markdown
apache-2.0
176
/* * Licensed to GraphHopper GmbH under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * GraphHopper GmbH licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.graphhopper.jsprit.core.algorithm; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.Collection; import java.util.Random; import org.junit.Test; import com.graphhopper.jsprit.core.algorithm.acceptor.SolutionAcceptor; import com.graphhopper.jsprit.core.algorithm.listener.SearchStrategyModuleListener; import com.graphhopper.jsprit.core.algorithm.selector.SolutionSelector; import com.graphhopper.jsprit.core.problem.VehicleRoutingProblem; import com.graphhopper.jsprit.core.problem.solution.SolutionCostCalculator; import com.graphhopper.jsprit.core.problem.solution.VehicleRoutingProblemSolution; public class SearchStrategyTest { @Test(expected = IllegalStateException.class) public void whenANullModule_IsAdded_throwException() { SolutionSelector select = mock(SolutionSelector.class); SolutionAcceptor accept = mock(SolutionAcceptor.class); SolutionCostCalculator calc = mock(SolutionCostCalculator.class); SearchStrategy strat = new SearchStrategy("strat", select, accept, calc); strat.addModule(null); } @Test public void whenStratRunsWithOneModule_runItOnes() { SolutionSelector select = mock(SolutionSelector.class); SolutionAcceptor accept = mock(SolutionAcceptor.class); SolutionCostCalculator calc = mock(SolutionCostCalculator.class); final VehicleRoutingProblem vrp = mock(VehicleRoutingProblem.class); final VehicleRoutingProblemSolution newSol = mock(VehicleRoutingProblemSolution.class); when(select.selectSolution(null)).thenReturn(newSol); final Collection<Integer> runs = new ArrayList<Integer>(); SearchStrategy strat = new SearchStrategy("strat", select, accept, calc); SearchStrategyModule mod = new SearchStrategyModule() { @Override public VehicleRoutingProblemSolution runAndGetSolution(VehicleRoutingProblemSolution vrpSolution) { runs.add(1); return vrpSolution; } @Override public String getName() { return null; } @Override public void addModuleListener( SearchStrategyModuleListener moduleListener) { } }; strat.addModule(mod); strat.run(vrp, null); assertEquals(runs.size(), 1); } @Test public void whenStratRunsWithTwoModule_runItTwice() { SolutionSelector select = mock(SolutionSelector.class); SolutionAcceptor accept = mock(SolutionAcceptor.class); SolutionCostCalculator calc = mock(SolutionCostCalculator.class); final VehicleRoutingProblem vrp = mock(VehicleRoutingProblem.class); final VehicleRoutingProblemSolution newSol = mock(VehicleRoutingProblemSolution.class); when(select.selectSolution(null)).thenReturn(newSol); final Collection<Integer> runs = new ArrayList<Integer>(); SearchStrategy strat = new SearchStrategy("strat", select, accept, calc); SearchStrategyModule mod = new SearchStrategyModule() { @Override public VehicleRoutingProblemSolution runAndGetSolution(VehicleRoutingProblemSolution vrpSolution) { runs.add(1); return vrpSolution; } @Override public String getName() { return null; } @Override public void addModuleListener( SearchStrategyModuleListener moduleListener) { } }; SearchStrategyModule mod2 = new SearchStrategyModule() { @Override public VehicleRoutingProblemSolution runAndGetSolution(VehicleRoutingProblemSolution vrpSolution) { runs.add(1); return vrpSolution; } @Override public String getName() { return null; } @Override public void addModuleListener( SearchStrategyModuleListener moduleListener) { } }; strat.addModule(mod); strat.addModule(mod2); strat.run(vrp, null); assertEquals(runs.size(), 2); } @Test public void whenStratRunsWithNModule_runItNTimes() { SolutionSelector select = mock(SolutionSelector.class); SolutionAcceptor accept = mock(SolutionAcceptor.class); SolutionCostCalculator calc = mock(SolutionCostCalculator.class); final VehicleRoutingProblem vrp = mock(VehicleRoutingProblem.class); final VehicleRoutingProblemSolution newSol = mock(VehicleRoutingProblemSolution.class); when(select.selectSolution(null)).thenReturn(newSol); int N = new Random().nextInt(1000); final Collection<Integer> runs = new ArrayList<Integer>(); SearchStrategy strat = new SearchStrategy("strat", select, accept, calc); for (int i = 0; i < N; i++) { SearchStrategyModule mod = new SearchStrategyModule() { @Override public VehicleRoutingProblemSolution runAndGetSolution(VehicleRoutingProblemSolution vrpSolution) { runs.add(1); return vrpSolution; } @Override public String getName() { return null; } @Override public void addModuleListener( SearchStrategyModuleListener moduleListener) { } }; strat.addModule(mod); } strat.run(vrp, null); assertEquals(runs.size(), N); } @Test(expected = IllegalStateException.class) public void whenSelectorDeliversNullSolution_throwException() { SolutionSelector select = mock(SolutionSelector.class); SolutionAcceptor accept = mock(SolutionAcceptor.class); SolutionCostCalculator calc = mock(SolutionCostCalculator.class); final VehicleRoutingProblem vrp = mock(VehicleRoutingProblem.class); when(select.selectSolution(null)).thenReturn(null); int N = new Random().nextInt(1000); final Collection<Integer> runs = new ArrayList<Integer>(); SearchStrategy strat = new SearchStrategy("strat", select, accept, calc); for (int i = 0; i < N; i++) { SearchStrategyModule mod = new SearchStrategyModule() { @Override public VehicleRoutingProblemSolution runAndGetSolution(VehicleRoutingProblemSolution vrpSolution) { runs.add(1); return vrpSolution; } @Override public String getName() { return null; } @Override public void addModuleListener( SearchStrategyModuleListener moduleListener) { } }; strat.addModule(mod); } strat.run(vrp, null); assertEquals(runs.size(), N); } }
balage1551/jsprit
jsprit-core/src/test/java/com/graphhopper/jsprit/core/algorithm/SearchStrategyTest.java
Java
apache-2.0
8,039
import { extend } from 'flarum/extend'; import PermissionGrid from 'flarum/components/PermissionGrid'; export default function() { extend(PermissionGrid.prototype, 'moderateItems', items => { items.add('tag', { icon: 'fas fa-tag', label: app.translator.trans('flarum-tags.admin.permissions.tag_discussions_label'), permission: 'discussion.tag' }, 95); }); }
drthomas21/WordPress_Tutorial
community_htdocs/vendor/flarum/tags/js/src/admin/addTagPermission.js
JavaScript
apache-2.0
389
#!/Users/wuga/Documents/website/wuga/env/bin/python2.7 # # The Python Imaging Library # $Id$ # from __future__ import print_function import sys if sys.version_info[0] > 2: import tkinter else: import Tkinter as tkinter from PIL import Image, ImageTk # -------------------------------------------------------------------- # an image animation player class UI(tkinter.Label): def __init__(self, master, im): if isinstance(im, list): # list of images self.im = im[1:] im = self.im[0] else: # sequence self.im = im if im.mode == "1": self.image = ImageTk.BitmapImage(im, foreground="white") else: self.image = ImageTk.PhotoImage(im) tkinter.Label.__init__(self, master, image=self.image, bg="black", bd=0) self.update() duration = im.info.get("duration", 100) self.after(duration, self.next) def next(self): if isinstance(self.im, list): try: im = self.im[0] del self.im[0] self.image.paste(im) except IndexError: return # end of list else: try: im = self.im im.seek(im.tell() + 1) self.image.paste(im) except EOFError: return # end of file duration = im.info.get("duration", 100) self.after(duration, self.next) self.update_idletasks() # -------------------------------------------------------------------- # script interface if __name__ == "__main__": if not sys.argv[1:]: print("Syntax: python player.py imagefile(s)") sys.exit(1) filename = sys.argv[1] root = tkinter.Tk() root.title(filename) if len(sys.argv) > 2: # list of images print("loading...") im = [] for filename in sys.argv[1:]: im.append(Image.open(filename)) else: # sequence im = Image.open(filename) UI(root, im).pack() root.mainloop()
wuga214/Django-Wuga
env/bin/player.py
Python
apache-2.0
2,120
package com.apixandru.rummikub.api; /** * @author Alexandru-Constantin Bledea * @since Sep 16, 2015 */ public enum Rank { ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, ELEVEN, TWELVE, THIRTEEN; public int asNumber() { return ordinal() + 1; } @Override public String toString() { return String.format("%2d", asNumber()); } }
apixandru/rummikub-java
rummikub-model/src/main/java/com/apixandru/rummikub/api/Rank.java
Java
apache-2.0
405
/* * Copyright (c) 2008-2015, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.simulator.provisioner; import com.hazelcast.simulator.common.AgentsFile; import com.hazelcast.simulator.common.SimulatorProperties; import com.hazelcast.simulator.utils.Bash; import com.hazelcast.simulator.utils.jars.HazelcastJARs; import joptsimple.OptionParser; import joptsimple.OptionSet; import joptsimple.OptionSpec; import org.jclouds.compute.ComputeService; import static com.hazelcast.simulator.common.SimulatorProperties.PROPERTIES_FILE_NAME; import static com.hazelcast.simulator.utils.CliUtils.initOptionsWithHelp; import static com.hazelcast.simulator.utils.CliUtils.printHelpAndExit; import static com.hazelcast.simulator.utils.CloudProviderUtils.isStatic; import static com.hazelcast.simulator.utils.SimulatorUtils.loadSimulatorProperties; import static com.hazelcast.simulator.utils.jars.HazelcastJARs.isPrepareRequired; import static com.hazelcast.simulator.utils.jars.HazelcastJARs.newInstance; import static java.util.Collections.singleton; final class ProvisionerCli { private final OptionParser parser = new OptionParser(); private final OptionSpec<Integer> scaleSpec = parser.accepts("scale", "Number of Simulator machines to scale to. If the number of machines already exists, the call is ignored. If the" + " desired number of machines is smaller than the actual number of machines, machines are terminated.") .withRequiredArg().ofType(Integer.class); private final OptionSpec installSpec = parser.accepts("install", "Installs Simulator on all provisioned machines."); private final OptionSpec uploadHazelcastSpec = parser.accepts("uploadHazelcast", "If defined --install will upload the Hazelcast JARs as well."); private final OptionSpec<Boolean> enterpriseEnabledSpec = parser.accepts("enterpriseEnabled", "Use JARs of Hazelcast Enterprise Edition.") .withRequiredArg().ofType(Boolean.class).defaultsTo(false); private final OptionSpec listAgentsSpec = parser.accepts("list", "Lists the provisioned machines (from " + AgentsFile.NAME + " file)."); private final OptionSpec<String> downloadSpec = parser.accepts("download", "Download all files from the remote Worker directories. Use --clean to delete all Worker directories.") .withOptionalArg().ofType(String.class).defaultsTo("workers"); private final OptionSpec cleanSpec = parser.accepts("clean", "Cleans the remote Worker directories on the provisioned machines."); private final OptionSpec killSpec = parser.accepts("kill", "Kills the Java processes on all provisioned machines (via killall -9 java)."); private final OptionSpec terminateSpec = parser.accepts("terminate", "Terminates all provisioned machines."); private final OptionSpec<String> propertiesFileSpec = parser.accepts("propertiesFile", "The file containing the Simulator properties. If no file is explicitly configured, first the local working directory" + " is checked for a file '" + PROPERTIES_FILE_NAME + "'. All missing properties are always loaded from" + " '$SIMULATOR_HOME/conf/" + PROPERTIES_FILE_NAME + "'.") .withRequiredArg().ofType(String.class); private ProvisionerCli() { } static Provisioner init(String[] args) { ProvisionerCli cli = new ProvisionerCli(); OptionSet options = initOptionsWithHelp(cli.parser, args); SimulatorProperties properties = loadSimulatorProperties(options, cli.propertiesFileSpec); ComputeService computeService = isStatic(properties) ? null : new ComputeServiceBuilder(properties).build(); Bash bash = new Bash(properties); HazelcastJARs hazelcastJARs = null; boolean enterpriseEnabled = options.valueOf(cli.enterpriseEnabledSpec); if (options.has(cli.uploadHazelcastSpec)) { String hazelcastVersionSpec = properties.getHazelcastVersionSpec(); if (isPrepareRequired(hazelcastVersionSpec) || !enterpriseEnabled) { hazelcastJARs = newInstance(bash, properties, singleton(hazelcastVersionSpec)); } } return new Provisioner(properties, computeService, bash, hazelcastJARs, enterpriseEnabled); } static void run(String[] args, Provisioner provisioner) { ProvisionerCli cli = new ProvisionerCli(); OptionSet options = initOptionsWithHelp(cli.parser, args); try { if (options.has(cli.scaleSpec)) { int size = options.valueOf(cli.scaleSpec); provisioner.scale(size); } else if (options.has(cli.installSpec)) { provisioner.installSimulator(); } else if (options.has(cli.listAgentsSpec)) { provisioner.listMachines(); } else if (options.has(cli.downloadSpec)) { String dir = options.valueOf(cli.downloadSpec); provisioner.download(dir); } else if (options.has(cli.cleanSpec)) { provisioner.clean(); } else if (options.has(cli.killSpec)) { provisioner.killJavaProcesses(); } else if (options.has(cli.terminateSpec)) { provisioner.terminate(); } else { printHelpAndExit(cli.parser); } } finally { provisioner.shutdown(); } } }
Danny-Hazelcast/hazelcast-stabilizer
simulator/src/main/java/com/hazelcast/simulator/provisioner/ProvisionerCli.java
Java
apache-2.0
6,122
# Aster argyropholis var. niveus Y.Ling VARIETY #### 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/Aster/Aster argyropholis/ Syn. Aster argyropholis niveus/README.md
Markdown
apache-2.0
194
package OpenXPKI::Server::Workflow::Activity::Tools::SetAttribute; use strict; use base qw( OpenXPKI::Server::Workflow::Activity ); use OpenXPKI::Server::Context qw( CTX ); use OpenXPKI::Exception; use OpenXPKI::Debug; use OpenXPKI::Serialization::Simple; use Data::Dumper; sub execute { my $self = shift; my $workflow = shift; my $context = $workflow->context(); my $serializer = OpenXPKI::Serialization::Simple->new(); my $params = $self->param(); my $attrib = {}; ##! 32: 'SetAttrbute action parameters ' . Dumper $params foreach my $key (keys %{$params}) { my $val = $params->{$key}; if ($val) { ##! 16: 'Set attrib ' . $key $workflow->attrib({ $key => $val }); CTX('log')->workflow()->debug("Writing workflow attribute $key => $val"); } else { ##! 16: 'Unset attrib ' . $key # translation from empty to undef is required as the # attribute backend will write empty values $workflow->attrib({ $key => undef }); CTX('log')->workflow()->debug("Deleting workflow attribute $key"); } } return; } 1; __END__ =head1 Name OpenXPKI::Server::Workflow::Activity::Tools::SetAttribute =head1 Description Set values in the workflow attribute table. Uses the actions parameter list to determine the key/value pairs to be written. Values that result in an empty string are removed from the attribute table!
openxpki/openxpki
core/server/OpenXPKI/Server/Workflow/Activity/Tools/SetAttribute.pm
Perl
apache-2.0
1,490
package com.cognizant.cognizantits.qcconnection.qcupdation; import com4j.DISPID; import com4j.IID; import com4j.VTID; @IID("{B739B750-BFE1-43AF-8DD7-E8E8EFBBED7D}") public abstract interface IDashboardFolderFactory extends IBaseFactoryEx { @DISPID(9) @VTID(17) public abstract IList getChildPagesWithPrivateItems(IList paramIList); } /* Location: D:\Prabu\jars\QC.jar * Qualified Name: qcupdation.IDashboardFolderFactory * JD-Core Version: 0.7.0.1 */
CognizantQAHub/Cognizant-Intelligent-Test-Scripter
QcConnection/src/main/java/com/cognizant/cognizantits/qcconnection/qcupdation/IDashboardFolderFactory.java
Java
apache-2.0
482
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // 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. use collections::HashMap; use std::fmt; use std::from_str::from_str; use std::str::{MaybeOwned, Owned, Slice}; use compile::Program; use parse; use vm; use vm::{CaptureLocs, MatchKind, Exists, Location, Submatches}; /// Escapes all regular expression meta characters in `text` so that it may be /// safely used in a regular expression as a literal string. pub fn quote(text: &str) -> StrBuf { let mut quoted = StrBuf::with_capacity(text.len()); for c in text.chars() { if parse::is_punct(c) { quoted.push_char('\\') } quoted.push_char(c); } quoted } /// Tests if the given regular expression matches somewhere in the text given. /// /// If there was a problem compiling the regular expression, an error is /// returned. /// /// To find submatches, split or replace text, you'll need to compile an /// expression first. /// /// Note that you should prefer the `regex!` macro when possible. For example, /// `regex!("...").is_match("...")`. pub fn is_match(regex: &str, text: &str) -> Result<bool, parse::Error> { Regex::new(regex).map(|r| r.is_match(text)) } /// Regex is a compiled regular expression, represented as either a sequence /// of bytecode instructions (dynamic) or as a specialized Rust function /// (native). It can be used to search, split /// or replace text. All searching is done with an implicit `.*?` at the /// beginning and end of an expression. To force an expression to match the /// whole string (or a prefix or a suffix), you must use an anchor like `^` or /// `$` (or `\A` and `\z`). /// /// While this crate will handle Unicode strings (whether in the regular /// expression or in the search text), all positions returned are **byte /// indices**. Every byte index is guaranteed to be at a UTF8 codepoint /// boundary. /// /// The lifetimes `'r` and `'t` in this crate correspond to the lifetime of a /// compiled regular expression and text to search, respectively. /// /// The only methods that allocate new strings are the string replacement /// methods. All other methods (searching and splitting) return borrowed /// pointers into the string given. /// /// # Examples /// /// Find the location of a US phone number: /// /// ```rust /// # use regex::Regex; /// let re = match Regex::new("[0-9]{3}-[0-9]{3}-[0-9]{4}") { /// Ok(re) => re, /// Err(err) => fail!("{}", err), /// }; /// assert_eq!(re.find("phone: 111-222-3333"), Some((7, 19))); /// ``` /// /// You can also use the `regex!` macro to compile a regular expression when /// you compile your program: /// /// ```rust /// #![feature(phase)] /// extern crate regex; /// #[phase(syntax)] extern crate regex_macros; /// /// fn main() { /// let re = regex!(r"\d+"); /// assert_eq!(re.find("123 abc"), Some((0, 3))); /// } /// ``` /// /// Given an incorrect regular expression, `regex!` will cause the Rust /// compiler to produce a compile time error. /// Note that `regex!` will compile the expression to native Rust code, which /// makes it much faster when searching text. /// More details about the `regex!` macro can be found in the `regex` crate /// documentation. #[deriving(Clone)] #[allow(visible_private_types)] pub struct Regex { /// The representation of `Regex` is exported to support the `regex!` /// syntax extension. Do not rely on it. /// /// See the comments for the `program` module in `lib.rs` for a more /// detailed explanation for what `regex!` requires. #[doc(hidden)] pub original: StrBuf, #[doc(hidden)] pub names: Vec<Option<StrBuf>>, #[doc(hidden)] pub p: MaybeNative, } impl fmt::Show for Regex { /// Shows the original regular expression. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.original) } } pub enum MaybeNative { Dynamic(Program), Native(fn(MatchKind, &str, uint, uint) -> Vec<Option<uint>>), } impl Clone for MaybeNative { fn clone(&self) -> MaybeNative { match *self { Dynamic(ref p) => Dynamic(p.clone()), Native(fp) => Native(fp), } } } impl Regex { /// Compiles a dynamic regular expression. Once compiled, it can be /// used repeatedly to search, split or replace text in a string. /// /// When possible, you should prefer the `regex!` macro since it is /// safer and always faster. /// /// If an invalid expression is given, then an error is returned. pub fn new(re: &str) -> Result<Regex, parse::Error> { let ast = try!(parse::parse(re)); let (prog, names) = Program::new(ast); Ok(Regex { original: re.to_strbuf(), names: names, p: Dynamic(prog), }) } /// Returns true if and only if the regex matches the string given. /// /// # Example /// /// Test if some text contains at least one word with exactly 13 /// characters: /// /// ```rust /// # #![feature(phase)] /// # extern crate regex; #[phase(syntax)] extern crate regex_macros; /// # fn main() { /// let text = "I categorically deny having triskaidekaphobia."; /// let matched = regex!(r"\b\w{13}\b").is_match(text); /// assert!(matched); /// # } /// ``` pub fn is_match(&self, text: &str) -> bool { has_match(&exec(self, Exists, text)) } /// Returns the start and end byte range of the leftmost-first match in /// `text`. If no match exists, then `None` is returned. /// /// Note that this should only be used if you want to discover the position /// of the match. Testing the existence of a match is faster if you use /// `is_match`. /// /// # Example /// /// Find the start and end location of every word with exactly 13 /// characters: /// /// ```rust /// # #![feature(phase)] /// # extern crate regex; #[phase(syntax)] extern crate regex_macros; /// # fn main() { /// let text = "I categorically deny having triskaidekaphobia."; /// let pos = regex!(r"\b\w{13}\b").find(text); /// assert_eq!(pos, Some((2, 15))); /// # } /// ``` pub fn find(&self, text: &str) -> Option<(uint, uint)> { let caps = exec(self, Location, text); if has_match(&caps) { Some((caps.get(0).unwrap(), caps.get(1).unwrap())) } else { None } } /// Returns an iterator for each successive non-overlapping match in /// `text`, returning the start and end byte indices with respect to /// `text`. /// /// # Example /// /// Find the start and end location of the first word with exactly 13 /// characters: /// /// ```rust /// # #![feature(phase)] /// # extern crate regex; #[phase(syntax)] extern crate regex_macros; /// # fn main() { /// let text = "Retroactively relinquishing remunerations is reprehensible."; /// for pos in regex!(r"\b\w{13}\b").find_iter(text) { /// println!("{}", pos); /// } /// // Output: /// // (0, 13) /// // (14, 27) /// // (28, 41) /// // (45, 58) /// # } /// ``` pub fn find_iter<'r, 't>(&'r self, text: &'t str) -> FindMatches<'r, 't> { FindMatches { re: self, search: text, last_end: 0, last_match: None, } } /// Returns the capture groups corresponding to the leftmost-first /// match in `text`. Capture group `0` always corresponds to the entire /// match. If no match is found, then `None` is returned. /// /// You should only use `captures` if you need access to submatches. /// Otherwise, `find` is faster for discovering the location of the overall /// match. /// /// # Examples /// /// Say you have some text with movie names and their release years, /// like "'Citizen Kane' (1941)". It'd be nice if we could search for text /// looking like that, while also extracting the movie name and its release /// year separately. /// /// ```rust /// # #![feature(phase)] /// # extern crate regex; #[phase(syntax)] extern crate regex_macros; /// # fn main() { /// let re = regex!(r"'([^']+)'\s+\((\d{4})\)"); /// let text = "Not my favorite movie: 'Citizen Kane' (1941)."; /// let caps = re.captures(text).unwrap(); /// assert_eq!(caps.at(1), "Citizen Kane"); /// assert_eq!(caps.at(2), "1941"); /// assert_eq!(caps.at(0), "'Citizen Kane' (1941)"); /// # } /// ``` /// /// Note that the full match is at capture group `0`. Each subsequent /// capture group is indexed by the order of its opening `(`. /// /// We can make this example a bit clearer by using *named* capture groups: /// /// ```rust /// # #![feature(phase)] /// # extern crate regex; #[phase(syntax)] extern crate regex_macros; /// # fn main() { /// let re = regex!(r"'(?P<title>[^']+)'\s+\((?P<year>\d{4})\)"); /// let text = "Not my favorite movie: 'Citizen Kane' (1941)."; /// let caps = re.captures(text).unwrap(); /// assert_eq!(caps.name("title"), "Citizen Kane"); /// assert_eq!(caps.name("year"), "1941"); /// assert_eq!(caps.at(0), "'Citizen Kane' (1941)"); /// # } /// ``` /// /// Here we name the capture groups, which we can access with the `name` /// method. Note that the named capture groups are still accessible with /// `at`. /// /// The `0`th capture group is always unnamed, so it must always be /// accessed with `at(0)`. pub fn captures<'t>(&self, text: &'t str) -> Option<Captures<'t>> { let caps = exec(self, Submatches, text); Captures::new(self, text, caps) } /// Returns an iterator over all the non-overlapping capture groups matched /// in `text`. This is operationally the same as `find_iter` (except it /// yields information about submatches). /// /// # Example /// /// We can use this to find all movie titles and their release years in /// some text, where the movie is formatted like "'Title' (xxxx)": /// /// ```rust /// # #![feature(phase)] /// # extern crate regex; #[phase(syntax)] extern crate regex_macros; /// # fn main() { /// let re = regex!(r"'(?P<title>[^']+)'\s+\((?P<year>\d{4})\)"); /// let text = "'Citizen Kane' (1941), 'The Wizard of Oz' (1939), 'M' (1931)."; /// for caps in re.captures_iter(text) { /// println!("Movie: {}, Released: {}", caps.name("title"), caps.name("year")); /// } /// // Output: /// // Movie: Citizen Kane, Released: 1941 /// // Movie: The Wizard of Oz, Released: 1939 /// // Movie: M, Released: 1931 /// # } /// ``` pub fn captures_iter<'r, 't>(&'r self, text: &'t str) -> FindCaptures<'r, 't> { FindCaptures { re: self, search: text, last_match: None, last_end: 0, } } /// Returns an iterator of substrings of `text` delimited by a match /// of the regular expression. /// Namely, each element of the iterator corresponds to text that *isn't* /// matched by the regular expression. /// /// This method will *not* copy the text given. /// /// # Example /// /// To split a string delimited by arbitrary amounts of spaces or tabs: /// /// ```rust /// # #![feature(phase)] /// # extern crate regex; #[phase(syntax)] extern crate regex_macros; /// # fn main() { /// let re = regex!(r"[ \t]+"); /// let fields: Vec<&str> = re.split("a b \t c\td e").collect(); /// assert_eq!(fields, vec!("a", "b", "c", "d", "e")); /// # } /// ``` pub fn split<'r, 't>(&'r self, text: &'t str) -> RegexSplits<'r, 't> { RegexSplits { finder: self.find_iter(text), last: 0, } } /// Returns an iterator of at most `limit` substrings of `text` delimited /// by a match of the regular expression. (A `limit` of `0` will return no /// substrings.) /// Namely, each element of the iterator corresponds to text that *isn't* /// matched by the regular expression. /// The remainder of the string that is not split will be the last element /// in the iterator. /// /// This method will *not* copy the text given. /// /// # Example /// /// Get the first two words in some text: /// /// ```rust /// # #![feature(phase)] /// # extern crate regex; #[phase(syntax)] extern crate regex_macros; /// # fn main() { /// let re = regex!(r"\W+"); /// let fields: Vec<&str> = re.splitn("Hey! How are you?", 3).collect(); /// assert_eq!(fields, vec!("Hey", "How", "are you?")); /// # } /// ``` pub fn splitn<'r, 't>(&'r self, text: &'t str, limit: uint) -> RegexSplitsN<'r, 't> { RegexSplitsN { splits: self.split(text), cur: 0, limit: limit, } } /// Replaces the leftmost-first match with the replacement provided. /// The replacement can be a regular string (where `$N` and `$name` are /// expanded to match capture groups) or a function that takes the matches' /// `Captures` and returns the replaced string. /// /// If no match is found, then a copy of the string is returned unchanged. /// /// # Examples /// /// Note that this function is polymorphic with respect to the replacement. /// In typical usage, this can just be a normal string: /// /// ```rust /// # #![feature(phase)] /// # extern crate regex; #[phase(syntax)] extern crate regex_macros; /// # fn main() { /// let re = regex!("[^01]+"); /// assert_eq!(re.replace("1078910", "").as_slice(), "1010"); /// # } /// ``` /// /// But anything satisfying the `Replacer` trait will work. For example, /// a closure of type `|&Captures| -> StrBuf` provides direct access to the /// captures corresponding to a match. This allows one to access /// submatches easily: /// /// ```rust /// # #![feature(phase)] /// # extern crate regex; #[phase(syntax)] extern crate regex_macros; /// # use regex::Captures; fn main() { /// let re = regex!(r"([^,\s]+),\s+(\S+)"); /// let result = re.replace("Springsteen, Bruce", |caps: &Captures| { /// format_strbuf!("{} {}", caps.at(2), caps.at(1)) /// }); /// assert_eq!(result.as_slice(), "Bruce Springsteen"); /// # } /// ``` /// /// But this is a bit cumbersome to use all the time. Instead, a simple /// syntax is supported that expands `$name` into the corresponding capture /// group. Here's the last example, but using this expansion technique /// with named capture groups: /// /// ```rust /// # #![feature(phase)] /// # extern crate regex; #[phase(syntax)] extern crate regex_macros; /// # fn main() { /// let re = regex!(r"(?P<last>[^,\s]+),\s+(?P<first>\S+)"); /// let result = re.replace("Springsteen, Bruce", "$first $last"); /// assert_eq!(result.as_slice(), "Bruce Springsteen"); /// # } /// ``` /// /// Note that using `$2` instead of `$first` or `$1` instead of `$last` /// would produce the same result. To write a literal `$` use `$$`. /// /// Finally, sometimes you just want to replace a literal string with no /// submatch expansion. This can be done by wrapping a string with /// `NoExpand`: /// /// ```rust /// # #![feature(phase)] /// # extern crate regex; #[phase(syntax)] extern crate regex_macros; /// # fn main() { /// use regex::NoExpand; /// /// let re = regex!(r"(?P<last>[^,\s]+),\s+(\S+)"); /// let result = re.replace("Springsteen, Bruce", NoExpand("$2 $last")); /// assert_eq!(result.as_slice(), "$2 $last"); /// # } /// ``` pub fn replace<R: Replacer>(&self, text: &str, rep: R) -> StrBuf { self.replacen(text, 1, rep) } /// Replaces all non-overlapping matches in `text` with the /// replacement provided. This is the same as calling `replacen` with /// `limit` set to `0`. /// /// See the documentation for `replace` for details on how to access /// submatches in the replacement string. pub fn replace_all<R: Replacer>(&self, text: &str, rep: R) -> StrBuf { self.replacen(text, 0, rep) } /// Replaces at most `limit` non-overlapping matches in `text` with the /// replacement provided. If `limit` is 0, then all non-overlapping matches /// are replaced. /// /// See the documentation for `replace` for details on how to access /// submatches in the replacement string. pub fn replacen<R: Replacer> (&self, text: &str, limit: uint, mut rep: R) -> StrBuf { let mut new = StrBuf::with_capacity(text.len()); let mut last_match = 0u; for (i, cap) in self.captures_iter(text).enumerate() { // It'd be nicer to use the 'take' iterator instead, but it seemed // awkward given that '0' => no limit. if limit > 0 && i >= limit { break } let (s, e) = cap.pos(0).unwrap(); // captures only reports matches new.push_str(text.slice(last_match, s)); new.push_str(rep.reg_replace(&cap).as_slice()); last_match = e; } new.append(text.slice(last_match, text.len())) } } /// NoExpand indicates literal string replacement. /// /// It can be used with `replace` and `replace_all` to do a literal /// string replacement without expanding `$name` to their corresponding /// capture groups. /// /// `'r` is the lifetime of the literal text. pub struct NoExpand<'t>(pub &'t str); /// Replacer describes types that can be used to replace matches in a string. pub trait Replacer { /// Returns a possibly owned string that is used to replace the match /// corresponding the the `caps` capture group. /// /// The `'a` lifetime refers to the lifetime of a borrowed string when /// a new owned string isn't needed (e.g., for `NoExpand`). fn reg_replace<'a>(&'a mut self, caps: &Captures) -> MaybeOwned<'a>; } impl<'t> Replacer for NoExpand<'t> { fn reg_replace<'a>(&'a mut self, _: &Captures) -> MaybeOwned<'a> { let NoExpand(s) = *self; Slice(s) } } impl<'t> Replacer for &'t str { fn reg_replace<'a>(&'a mut self, caps: &Captures) -> MaybeOwned<'a> { Owned(caps.expand(*self).into_owned()) } } impl<'a> Replacer for |&Captures|: 'a -> StrBuf { fn reg_replace<'r>(&'r mut self, caps: &Captures) -> MaybeOwned<'r> { Owned((*self)(caps).into_owned()) } } /// Yields all substrings delimited by a regular expression match. /// /// `'r` is the lifetime of the compiled expression and `'t` is the lifetime /// of the string being split. pub struct RegexSplits<'r, 't> { finder: FindMatches<'r, 't>, last: uint, } impl<'r, 't> Iterator<&'t str> for RegexSplits<'r, 't> { fn next(&mut self) -> Option<&'t str> { let text = self.finder.search; match self.finder.next() { None => { if self.last >= text.len() { None } else { let s = text.slice(self.last, text.len()); self.last = text.len(); Some(s) } } Some((s, e)) => { let matched = text.slice(self.last, s); self.last = e; Some(matched) } } } } /// Yields at most `N` substrings delimited by a regular expression match. /// /// The last substring will be whatever remains after splitting. /// /// `'r` is the lifetime of the compiled expression and `'t` is the lifetime /// of the string being split. pub struct RegexSplitsN<'r, 't> { splits: RegexSplits<'r, 't>, cur: uint, limit: uint, } impl<'r, 't> Iterator<&'t str> for RegexSplitsN<'r, 't> { fn next(&mut self) -> Option<&'t str> { let text = self.splits.finder.search; if self.cur >= self.limit { None } else { self.cur += 1; if self.cur >= self.limit { Some(text.slice(self.splits.last, text.len())) } else { self.splits.next() } } } } /// Captures represents a group of captured strings for a single match. /// /// The 0th capture always corresponds to the entire match. Each subsequent /// index corresponds to the next capture group in the regex. /// If a capture group is named, then the matched string is *also* available /// via the `name` method. (Note that the 0th capture is always unnamed and so /// must be accessed with the `at` method.) /// /// Positions returned from a capture group are always byte indices. /// /// `'t` is the lifetime of the matched text. pub struct Captures<'t> { text: &'t str, locs: CaptureLocs, named: Option<HashMap<StrBuf, uint>>, } impl<'t> Captures<'t> { fn new(re: &Regex, search: &'t str, locs: CaptureLocs) -> Option<Captures<'t>> { if !has_match(&locs) { return None } let named = if re.names.len() == 0 { None } else { let mut named = HashMap::new(); for (i, name) in re.names.iter().enumerate() { match name { &None => {}, &Some(ref name) => { named.insert(name.to_strbuf(), i); } } } Some(named) }; Some(Captures { text: search, locs: locs, named: named, }) } /// Returns the start and end positions of the Nth capture group. /// Returns `None` if `i` is not a valid capture group or if the capture /// group did not match anything. /// The positions returned are *always* byte indices with respect to the /// original string matched. pub fn pos(&self, i: uint) -> Option<(uint, uint)> { let (s, e) = (i * 2, i * 2 + 1); if e >= self.locs.len() || self.locs.get(s).is_none() { // VM guarantees that each pair of locations are both Some or None. return None } Some((self.locs.get(s).unwrap(), self.locs.get(e).unwrap())) } /// Returns the matched string for the capture group `i`. /// If `i` isn't a valid capture group or didn't match anything, then the /// empty string is returned. pub fn at(&self, i: uint) -> &'t str { match self.pos(i) { None => "", Some((s, e)) => { self.text.slice(s, e) } } } /// Returns the matched string for the capture group named `name`. /// If `name` isn't a valid capture group or didn't match anything, then /// the empty string is returned. pub fn name(&self, name: &str) -> &'t str { match self.named { None => "", Some(ref h) => { match h.find_equiv(&name) { None => "", Some(i) => self.at(*i), } } } } /// Creates an iterator of all the capture groups in order of appearance /// in the regular expression. pub fn iter(&'t self) -> SubCaptures<'t> { SubCaptures { idx: 0, caps: self, } } /// Creates an iterator of all the capture group positions in order of /// appearance in the regular expression. Positions are byte indices /// in terms of the original string matched. pub fn iter_pos(&'t self) -> SubCapturesPos<'t> { SubCapturesPos { idx: 0, caps: self, } } /// Expands all instances of `$name` in `text` to the corresponding capture /// group `name`. /// /// `name` may be an integer corresponding to the index of the /// capture group (counted by order of opening parenthesis where `0` is the /// entire match) or it can be a name (consisting of letters, digits or /// underscores) corresponding to a named capture group. /// /// If `name` isn't a valid capture group (whether the name doesn't exist or /// isn't a valid index), then it is replaced with the empty string. /// /// To write a literal `$` use `$$`. pub fn expand(&self, text: &str) -> StrBuf { // How evil can you get? // FIXME: Don't use regexes for this. It's completely unnecessary. let re = Regex::new(r"(^|[^$]|\b)\$(\w+)").unwrap(); let text = re.replace_all(text, |refs: &Captures| -> StrBuf { let (pre, name) = (refs.at(1), refs.at(2)); format_strbuf!("{}{}", pre, match from_str::<uint>(name.as_slice()) { None => self.name(name).to_strbuf(), Some(i) => self.at(i).to_strbuf(), }) }); let re = Regex::new(r"\$\$").unwrap(); re.replace_all(text.as_slice(), NoExpand("$")) } } impl<'t> Container for Captures<'t> { /// Returns the number of captured groups. #[inline] fn len(&self) -> uint { self.locs.len() / 2 } } /// An iterator over capture groups for a particular match of a regular /// expression. /// /// `'t` is the lifetime of the matched text. pub struct SubCaptures<'t> { idx: uint, caps: &'t Captures<'t>, } impl<'t> Iterator<&'t str> for SubCaptures<'t> { fn next(&mut self) -> Option<&'t str> { if self.idx < self.caps.len() { self.idx += 1; Some(self.caps.at(self.idx - 1)) } else { None } } } /// An iterator over capture group positions for a particular match of a /// regular expression. /// /// Positions are byte indices in terms of the original string matched. /// /// `'t` is the lifetime of the matched text. pub struct SubCapturesPos<'t> { idx: uint, caps: &'t Captures<'t>, } impl<'t> Iterator<Option<(uint, uint)>> for SubCapturesPos<'t> { fn next(&mut self) -> Option<Option<(uint, uint)>> { if self.idx < self.caps.len() { self.idx += 1; Some(self.caps.pos(self.idx - 1)) } else { None } } } /// An iterator that yields all non-overlapping capture groups matching a /// particular regular expression. The iterator stops when no more matches can /// be found. /// /// `'r` is the lifetime of the compiled expression and `'t` is the lifetime /// of the matched string. pub struct FindCaptures<'r, 't> { re: &'r Regex, search: &'t str, last_match: Option<uint>, last_end: uint, } impl<'r, 't> Iterator<Captures<'t>> for FindCaptures<'r, 't> { fn next(&mut self) -> Option<Captures<'t>> { if self.last_end > self.search.len() { return None } let caps = exec_slice(self.re, Submatches, self.search, self.last_end, self.search.len()); let (s, e) = if !has_match(&caps) { return None } else { (caps.get(0).unwrap(), caps.get(1).unwrap()) }; // Don't accept empty matches immediately following a match. // i.e., no infinite loops please. if e == s && Some(self.last_end) == self.last_match { self.last_end += 1; return self.next() } self.last_end = e; self.last_match = Some(self.last_end); Captures::new(self.re, self.search, caps) } } /// An iterator over all non-overlapping matches for a particular string. /// /// The iterator yields a tuple of integers corresponding to the start and end /// of the match. The indices are byte offsets. The iterator stops when no more /// matches can be found. /// /// `'r` is the lifetime of the compiled expression and `'t` is the lifetime /// of the matched string. pub struct FindMatches<'r, 't> { re: &'r Regex, search: &'t str, last_match: Option<uint>, last_end: uint, } impl<'r, 't> Iterator<(uint, uint)> for FindMatches<'r, 't> { fn next(&mut self) -> Option<(uint, uint)> { if self.last_end > self.search.len() { return None } let caps = exec_slice(self.re, Location, self.search, self.last_end, self.search.len()); let (s, e) = if !has_match(&caps) { return None } else { (caps.get(0).unwrap(), caps.get(1).unwrap()) }; // Don't accept empty matches immediately following a match. // i.e., no infinite loops please. if e == s && Some(self.last_end) == self.last_match { self.last_end += 1; return self.next() } self.last_end = e; self.last_match = Some(self.last_end); Some((s, e)) } } fn exec(re: &Regex, which: MatchKind, input: &str) -> CaptureLocs { exec_slice(re, which, input, 0, input.len()) } fn exec_slice(re: &Regex, which: MatchKind, input: &str, s: uint, e: uint) -> CaptureLocs { match re.p { Dynamic(ref prog) => vm::run(which, prog, input, s, e), Native(exec) => exec(which, input, s, e), } } #[inline] fn has_match(caps: &CaptureLocs) -> bool { caps.len() >= 2 && caps.get(0).is_some() && caps.get(1).is_some() }
aturon/rust
src/libregex/re.rs
Rust
apache-2.0
30,060
@ECHO OFF SET RepoRoot=%~dp0..\..\.. %RepoRoot%\eng\build.cmd -projects %~dp0**\*.csproj /p:SkipIISNewHandlerTests=true /p:SkipIISNewShimTests=true %*
aspnet/AspNetCore
src/Servers/IIS/build.cmd
Batchfile
apache-2.0
151
<!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 (version 1.6.0_27) on Thu Jan 23 20:22:10 EST 2014 --> <meta http-equiv="Content-Type" content="text/html" charset="utf-8"> <title>Uses of Class org.apache.solr.update.processor.ParseBooleanFieldUpdateProcessorFactory (Solr 4.6.1 API)</title> <meta name="date" content="2014-01-23"> <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.solr.update.processor.ParseBooleanFieldUpdateProcessorFactory (Solr 4.6.1 API)"; } //--> </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/solr/update/processor/ParseBooleanFieldUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor">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="../../../../../../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/solr/update/processor//class-useParseBooleanFieldUpdateProcessorFactory.html" target="_top">FRAMES</a></li> <li><a href="ParseBooleanFieldUpdateProcessorFactory.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.solr.update.processor.ParseBooleanFieldUpdateProcessorFactory" class="title">Uses of Class<br>org.apache.solr.update.processor.ParseBooleanFieldUpdateProcessorFactory</h2> </div> <div class="classUseContainer">No usage of org.apache.solr.update.processor.ParseBooleanFieldUpdateProcessorFactory</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/solr/update/processor/ParseBooleanFieldUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor">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="../../../../../../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/solr/update/processor//class-useParseBooleanFieldUpdateProcessorFactory.html" target="_top">FRAMES</a></li> <li><a href="ParseBooleanFieldUpdateProcessorFactory.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 &copy; 2000-2014 Apache Software Foundation. All Rights Reserved.</i> <script src='../../../../../../prettify.js' type='text/javascript'></script> <script type='text/javascript'> (function(){ var oldonload = window.onload; if (typeof oldonload != 'function') { window.onload = prettyPrint; } else { window.onload = function() { oldonload(); prettyPrint(); } } })(); </script> </small></p> </body> </html>
arnaud71/webso-db
docs/solr-core/org/apache/solr/update/processor/class-use/ParseBooleanFieldUpdateProcessorFactory.html
HTML
apache-2.0
5,316
/* * Copyright (C) 2016 QAware GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.qaware.chronix.timeseries.dt; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import java.io.Serializable; import java.util.Arrays; import static de.qaware.chronix.timeseries.dt.ListUtil.*; /** * Implementation of a list with primitive doubles. * * @author f.lautenschlager */ public class DoubleList implements Serializable { private static final long serialVersionUID = -1275724597860546074L; /** * Shared empty array instance used for empty instances. */ private static final double[] EMPTY_ELEMENT_DATA = {}; /** * Shared empty array instance used for default sized empty instances. We * distinguish this from EMPTY_ELEMENT_DATA to know how much to inflate when * first element is added. */ private static final double[] DEFAULT_CAPACITY_EMPTY_ELEMENT_DATA = {}; private double[] doubles; private int size; /** * Constructs an empty list with the specified initial capacity. * * @param initialCapacity the initial capacity of the list * @throws IllegalArgumentException if the specified initial capacity * is negative */ public DoubleList(int initialCapacity) { if (initialCapacity > 0) { this.doubles = new double[initialCapacity]; } else if (initialCapacity == 0) { this.doubles = EMPTY_ELEMENT_DATA; } else { throw new IllegalArgumentException("Illegal Capacity: " + initialCapacity); } } /** * Constructs an empty list with an initial capacity of ten. */ public DoubleList() { this.doubles = DEFAULT_CAPACITY_EMPTY_ELEMENT_DATA; } /** * Constructs a double list from the given values by simple assigning them. * * @param longs the values of the double list. * @param size the index of the last value in the array. */ @SuppressWarnings("all") public DoubleList(double[] longs, int size) { if (longs == null) { throw new IllegalArgumentException("Illegal initial array 'null'"); } if (size < 0) { throw new IllegalArgumentException("Size if negative."); } this.doubles = longs; this.size = size; } /** * Returns the number of elements in this list. * * @return the number of elements in this list */ public int size() { return size; } /** * Returns <tt>true</tt> if this list contains no elements. * * @return <tt>true</tt> if this list contains no elements */ public boolean isEmpty() { return size == 0; } /** * Returns <tt>true</tt> if this list contains the specified element. * More formally, returns <tt>true</tt> if and only if this list contains * at least one element <tt>e</tt> such that * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>. * * @param o element whose presence in this list is to be tested * @return <tt>true</tt> if this list contains the specified element */ public boolean contains(double o) { return indexOf(o) >= 0; } /** * Returns the index of the first occurrence of the specified element * in this list, or -1 if this list does not contain the element. * More formally, returns the lowest index <tt>i</tt> such that * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>, * or -1 if there is no such index. * * @param o the double value * @return the index of the given double element */ public int indexOf(double o) { for (int i = 0; i < size; i++) { if (o == doubles[i]) { return i; } } return -1; } /** * Returns the index of the last occurrence of the specified element * in this list, or -1 if this list does not contain the element. * More formally, returns the highest index <tt>i</tt> such that * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>, * or -1 if there is no such index. * * @param o the double value * @return the last index of the given double element */ public int lastIndexOf(double o) { for (int i = size - 1; i >= 0; i--) { if (o == doubles[i]) { return i; } } return -1; } /** * Returns a shallow copy of this <tt>LongList</tt> instance. (The * elements themselves are not copied.) * * @return a clone of this <tt>LongList</tt> instance */ public DoubleList copy() { DoubleList v = new DoubleList(size); v.doubles = Arrays.copyOf(doubles, size); v.size = size; return v; } /** * Returns an array containing all of the elements in this list * in proper sequence (from first to last element). * <p> * <p>The returned array will be "safe" in that no references to it are * maintained by this list. (In other words, this method must allocate * a new array). The caller is thus free to modify the returned array. * <p> * <p>This method acts as bridge between array-based and collection-based * APIs. * * @return an array containing all of the elements in this list in * proper sequence */ public double[] toArray() { return Arrays.copyOf(doubles, size); } private void growIfNeeded(int newCapacity) { if (newCapacity != -1) { doubles = Arrays.copyOf(doubles, newCapacity); } } /** * Returns the element at the specified position in this list. * * @param index index of the element to return * @return the element at the specified position in this list * @throws IndexOutOfBoundsException */ public double get(int index) { rangeCheck(index, size); return doubles[index]; } /** * Replaces the element at the specified position in this list with * the specified element. * * @param index index of the element to replace * @param element element to be stored at the specified position * @return the element previously at the specified position * @throws IndexOutOfBoundsException */ public double set(int index, double element) { rangeCheck(index, size); double oldValue = doubles[index]; doubles[index] = element; return oldValue; } /** * Appends the specified element to the end of this list. * * @param e element to be appended to this list * @return <tt>true</tt> (as specified by Collection#add) */ public boolean add(double e) { int newCapacity = calculateNewCapacity(doubles.length, size + 1); growIfNeeded(newCapacity); doubles[size++] = e; return true; } /** * Inserts the specified element at the specified position in this * list. Shifts the element currently at that position (if any) and * any subsequent elements to the right (adds one to their indices). * * @param index index at which the specified element is to be inserted * @param element element to be inserted * @throws IndexOutOfBoundsException */ public void add(int index, double element) { rangeCheckForAdd(index, size); int newCapacity = calculateNewCapacity(doubles.length, size + 1); growIfNeeded(newCapacity); System.arraycopy(doubles, index, doubles, index + 1, size - index); doubles[index] = element; size++; } /** * Removes the element at the specified position in this list. * Shifts any subsequent elements to the left (subtracts one from their * indices). * * @param index the index of the element to be removed * @return the element that was removed from the list * @throws IndexOutOfBoundsException */ public double remove(int index) { rangeCheck(index, size); double oldValue = doubles[index]; int numMoved = size - index - 1; if (numMoved > 0) { System.arraycopy(doubles, index + 1, doubles, index, numMoved); } --size; return oldValue; } /** * Removes the first occurrence of the specified element from this list, * if it is present. If the list does not contain the element, it is * unchanged. More formally, removes the element with the lowest index * <tt>i</tt> such that * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt> * (if such an element exists). Returns <tt>true</tt> if this list * contained the specified element (or equivalently, if this list * changed as a result of the call). * * @param o element to be removed from this list, if present * @return <tt>true</tt> if this list contained the specified element */ public boolean remove(double o) { for (int index = 0; index < size; index++) { if (o == doubles[index]) { fastRemove(index); return true; } } return false; } private void fastRemove(int index) { int numMoved = size - index - 1; if (numMoved > 0) { System.arraycopy(doubles, index + 1, doubles, index, numMoved); } --size; } /** * Removes all of the elements from this list. The list will * be empty after this call returns. */ public void clear() { doubles = DEFAULT_CAPACITY_EMPTY_ELEMENT_DATA; size = 0; } /** * Appends all of the elements in the specified collection to the end of * this list, in the order that they are returned by the * specified collection's Iterator. The behavior of this operation is * undefined if the specified collection is modified while the operation * is in progress. (This implies that the behavior of this call is * undefined if the specified collection is this list, and this * list is nonempty.) * * @param c collection containing elements to be added to this list * @return <tt>true</tt> if this list changed as a result of the call * @throws NullPointerException if the specified collection is null */ public boolean addAll(DoubleList c) { double[] a = c.toArray(); int numNew = a.length; int newCapacity = calculateNewCapacity(doubles.length, size + numNew); growIfNeeded(newCapacity); System.arraycopy(a, 0, doubles, size, numNew); size += numNew; return numNew != 0; } /** * Appends the long[] at the end of this long list. * * @param otherDoubles the other double[] that is appended * @return <tt>true</tt> if this list changed as a result of the call * @throws NullPointerException if the specified array is null */ public boolean addAll(double[] otherDoubles) { int numNew = otherDoubles.length; int newCapacity = calculateNewCapacity(doubles.length, size + numNew); growIfNeeded(newCapacity); System.arraycopy(otherDoubles, 0, doubles, size, numNew); size += numNew; return numNew != 0; } /** * Inserts all of the elements in the specified collection into this * list, starting at the specified position. Shifts the element * currently at that position (if any) and any subsequent elements to * the right (increases their indices). The new elements will appear * in the list in the order that they are returned by the * specified collection's iterator. * * @param index index at which to insert the first element from the * specified collection * @param c collection containing elements to be added to this list * @return <tt>true</tt> if this list changed as a result of the call * @throws IndexOutOfBoundsException * @throws NullPointerException if the specified collection is null */ public boolean addAll(int index, DoubleList c) { rangeCheckForAdd(index, size); double[] a = c.toArray(); int numNew = a.length; int newCapacity = calculateNewCapacity(doubles.length, size + numNew); growIfNeeded(newCapacity); int numMoved = size - index; if (numMoved > 0) { System.arraycopy(doubles, index, doubles, index + numNew, numMoved); } System.arraycopy(a, 0, doubles, index, numNew); size += numNew; return numNew != 0; } /** * Removes from this list all of the elements whose index is between * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive. * Shifts any succeeding elements to the left (reduces their index). * This call shortens the list by {@code (toIndex - fromIndex)} elements. * (If {@code toIndex==fromIndex}, this operation has no effect.) * * @throws IndexOutOfBoundsException if {@code fromIndex} or * {@code toIndex} is out of range * ({@code fromIndex < 0 || * fromIndex >= size() || * toIndex > size() || * toIndex < fromIndex}) */ public void removeRange(int fromIndex, int toIndex) { int numMoved = size - toIndex; System.arraycopy(doubles, toIndex, doubles, fromIndex, numMoved); size = size - (toIndex - fromIndex); } /** * Trims the capacity of this <tt>ArrayList</tt> instance to be the * list's current size. An application can use this operation to minimize * the storage of an <tt>ArrayList</tt> instance. */ private double[] trimToSize(int size, double[] elements) { double[] copy = Arrays.copyOf(elements, elements.length); if (size < elements.length) { copy = (size == 0) ? EMPTY_ELEMENT_DATA : Arrays.copyOf(elements, size); } return copy; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (obj == this) { return true; } if (obj.getClass() != getClass()) { return false; } DoubleList rhs = (DoubleList) obj; double[] thisTrimmed = trimToSize(this.size, this.doubles); double[] otherTrimmed = trimToSize(rhs.size, rhs.doubles); return new EqualsBuilder() .append(thisTrimmed, otherTrimmed) .append(this.size, rhs.size) .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder() .append(doubles) .append(size) .toHashCode(); } @Override public String toString() { return new ToStringBuilder(this) .append("doubles", trimToSize(this.size, doubles)) .append("size", size) .toString(); } /** * @return maximum of the values of the list */ public double max() { if (size <= 0) { return Double.NaN; } double max = Double.MIN_VALUE; for (int i = 0; i < size; i++) { max = doubles[i] > max ? doubles[i] : max; } return max; } /** * @return minimum of the values of the list */ public double min() { if (size <= 0) { return Double.NaN; } double min = Double.MAX_VALUE; for (int i = 0; i < size; i++) { min = doubles[i] < min ? doubles[i] : min; } return min; } /** * @return average of the values of the list */ public double avg() { if (size <= 0) { return Double.NaN; } double current = 0; for (int i = 0; i < size; i++) { current += doubles[i]; } return current / size; } /** * @param scale to be applied to the values of this list * @return a new instance scaled with the given parameter */ public DoubleList scale(double scale) { DoubleList scaled = new DoubleList(size); for (int i = 0; i < size; i++) { scaled.add(doubles[i] * scale); } return scaled; } /** * Calculates the standard deviation * * @return the standard deviation */ public double stdDeviation() { if (isEmpty()) { return Double.NaN; } return Math.sqrt(variance()); } private double mean() { double sum = 0.0; for (int i = 0; i < size(); i++) { sum = sum + get(i); } return sum / size(); } private double variance() { double avg = mean(); double sum = 0.0; for (int i = 0; i < size(); i++) { double value = get(i); sum += (value - avg) * (value - avg); } return sum / (size() - 1); } /** * Implemented the quantile type 7 referred to * http://tolstoy.newcastle.edu.au/R/e17/help/att-1067/Quartiles_in_R.pdf * and * http://stat.ethz.ch/R-manual/R-patched/library/stats/html/quantile.html * as its the default quantile implementation * <p> * <code> * QuantileType7 = function (v, p) { * v = sort(v) * h = ((length(v)-1)*p)+1 * v[floor(h)]+((h-floor(h))*(v[floor(h)+1]- v[floor(h)])) * } * </code> * * @param percentile - the percentile (0 - 1), e.g. 0.25 * @return the value of the n-th percentile */ public double percentile(double percentile) { double[] copy = toArray(); Arrays.sort(copy);// Attention: this is only necessary because this list is not restricted to non-descending values return evaluateForDoubles(copy, percentile); } private static double evaluateForDoubles(double[] points, double percentile) { //For example: //values = [1,2,2,3,3,3,4,5,6], size = 9, percentile (e.g. 0.25) // size - 1 = 8 * 0.25 = 2 (~ 25% from 9) + 1 = 3 => values[3] => 2 double percentileIndex = ((points.length - 1) * percentile) + 1; double rawMedian = points[floor(percentileIndex - 1)]; double weight = percentileIndex - floor(percentileIndex); if (weight > 0) { double pointDistance = points[floor(percentileIndex - 1) + 1] - points[floor(percentileIndex - 1)]; return rawMedian + weight * pointDistance; } else { return rawMedian; } } /** * Wraps the Math.floor function and casts it to an integer * * @param value - the evaluatedValue * @return the floored evaluatedValue */ private static int floor(double value) { return (int) Math.floor(value); } }
0xhansdampf/chronix.kassiopeia
chronix-kassiopeia-simple/src/main/java/de/qaware/chronix/timeseries/dt/DoubleList.java
Java
apache-2.0
19,873
# Copyright 2018 Huawei Technologies Co.,LTD. # 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. import copy from oslo_log import log as logging from oslo_versionedobjects import base as object_base from cyborg.common import exception from cyborg.db import api as dbapi from cyborg.objects import base from cyborg.objects import fields as object_fields from cyborg.objects.deployable import Deployable from cyborg.objects.virtual_function import VirtualFunction LOG = logging.getLogger(__name__) @base.CyborgObjectRegistry.register class PhysicalFunction(Deployable): # Version 1.0: Initial version VERSION = '1.0' virtual_function_list = [] def create(self, context): # To ensure the creating type is PF if self.type != 'pf': raise exception.InvalidDeployType() super(PhysicalFunction, self).create(context) def save(self, context): """In addition to save the pf, it should also save the vfs associated with this pf """ # To ensure the saving type is PF if self.type != 'pf': raise exception.InvalidDeployType() for exist_vf in self.virtual_function_list: exist_vf.save(context) super(PhysicalFunction, self).save(context) def add_vf(self, vf): """add a vf object to the virtual_function_list. If the vf already exists, it will ignore, otherwise, the vf will be appended to the list """ if not isinstance(vf, VirtualFunction) or vf.type != 'vf': raise exception.InvalidDeployType() for exist_vf in self.virtual_function_list: if base.obj_equal_prims(vf, exist_vf): LOG.warning("The vf already exists") return None vf.parent_uuid = self.uuid vf.root_uuid = self.root_uuid vf_copy = copy.deepcopy(vf) self.virtual_function_list.append(vf_copy) def delete_vf(self, context, vf): """remove a vf from the virtual_function_list if the vf does not exist, ignore it """ for idx, exist_vf in self.virtual_function_list: if base.obj_equal_prims(vf, exist_vf): removed_vf = self.virtual_function_list.pop(idx) removed_vf.destroy(context) return LOG.warning("The removing vf does not exist!") def destroy(self, context): """Delete a the pf from the DB.""" del self.virtual_function_list[:] super(PhysicalFunction, self).destroy(context) @classmethod def get(cls, context, uuid): """Find a DB Physical Function and return an Obj Physical Function. In addition, it will also finds all the Virtual Functions associated with this Physical Function and place them in virtual_function_list """ db_pf = cls.dbapi.deployable_get(context, uuid) obj_pf = cls._from_db_object(cls(context), db_pf) pf_uuid = obj_pf.uuid query = {"parent_uuid": pf_uuid, "type": "vf"} db_vf_list = cls.dbapi.deployable_get_by_filters(context, query) for db_vf in db_vf_list: obj_vf = VirtualFunction.get(context, db_vf.uuid) obj_pf.virtual_function_list.append(obj_vf) return obj_pf @classmethod def get_by_filter(cls, context, filters, sort_key='created_at', sort_dir='desc', limit=None, marker=None, join=None): obj_dpl_list = [] filters['type'] = 'pf' db_dpl_list = cls.dbapi.deployable_get_by_filters(context, filters, sort_key=sort_key, sort_dir=sort_dir, limit=limit, marker=marker, join_columns=join) for db_dpl in db_dpl_list: obj_dpl = cls._from_db_object(cls(context), db_dpl) query = {"parent_uuid": obj_dpl.uuid} vf_get_list = VirtualFunction.get_by_filter(context, query) obj_dpl.virtual_function_list = vf_get_list obj_dpl_list.append(obj_dpl) return obj_dpl_list @classmethod def _from_db_object(cls, obj, db_obj): """Converts a physical function to a formal object. :param obj: An object of the class. :param db_obj: A DB model of the object :return: The object of the class with the database entity added """ obj = Deployable._from_db_object(obj, db_obj) if cls is PhysicalFunction: obj.virtual_function_list = [] return obj
openstack/nomad
cyborg/objects/physical_function.py
Python
apache-2.0
5,396
/* Copyright 2020 Gravitational, 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 events import ( "archive/tar" "bufio" "compress/gzip" "context" "encoding/binary" "fmt" "io" "io/ioutil" "os" "path/filepath" "github.com/gravitational/teleport" apievents "github.com/gravitational/teleport/api/types/events" "github.com/gravitational/teleport/lib/session" "github.com/gravitational/teleport/lib/utils" "github.com/gravitational/trace" log "github.com/sirupsen/logrus" ) // Header returns information about playback type Header struct { // Tar detected tar format Tar bool // Proto is for proto format Proto bool // ProtoVersion is a version of the format, valid if Proto is true ProtoVersion int64 } // DetectFormat detects format by reading first bytes // of the header. Callers should call Seek() // to reuse reader after calling this function. func DetectFormat(r io.ReadSeeker) (*Header, error) { version := make([]byte, Int64Size) _, err := io.ReadFull(r, version) if err != nil { return nil, trace.ConvertSystemError(err) } protocolVersion := binary.BigEndian.Uint64(version) if protocolVersion == ProtoStreamV1 { return &Header{ Proto: true, ProtoVersion: int64(protocolVersion), }, nil } _, err = r.Seek(0, 0) if err != nil { return nil, trace.ConvertSystemError(err) } tr := tar.NewReader(r) _, err = tr.Next() if err != nil { return nil, trace.ConvertSystemError(err) } return &Header{Tar: true}, nil } // Export converts session files from binary/protobuf to text/JSON. func Export(ctx context.Context, rs io.ReadSeeker, w io.Writer, exportFormat string) error { switch exportFormat { case teleport.JSON: default: return trace.BadParameter("unsupported format %q, %q is the only supported format", exportFormat, teleport.JSON) } format, err := DetectFormat(rs) if err != nil { return trace.Wrap(err) } _, err = rs.Seek(0, 0) if err != nil { return trace.ConvertSystemError(err) } switch { case format.Proto: protoReader := NewProtoReader(rs) for { event, err := protoReader.Read(ctx) if err != nil { if err == io.EOF { return nil } return trace.Wrap(err) } switch exportFormat { case teleport.JSON: data, err := utils.FastMarshal(event) if err != nil { return trace.ConvertSystemError(err) } _, err = fmt.Fprintln(w, string(data)) if err != nil { return trace.ConvertSystemError(err) } default: return trace.BadParameter("unsupported format %q, %q is the only supported format", exportFormat, teleport.JSON) } } case format.Tar: return trace.BadParameter( "to review the events in format of teleport before version 4.4, extract the tarball and look inside") default: return trace.BadParameter("unsupported format %v", format) } } // WriteForPlayback reads events from audit reader and writes them to the format optimized for playback // this function returns *PlaybackWriter and error func WriteForPlayback(ctx context.Context, sid session.ID, reader AuditReader, dir string) (*PlaybackWriter, error) { w := &PlaybackWriter{ sid: sid, reader: reader, dir: dir, eventIndex: -1, } defer func() { if err := w.Close(); err != nil { log.WithError(err).Warningf("Failed to close writer.") } }() return w, w.Write(ctx) } // SessionEvents returns slice of event fields from gzipped events file. func (w *PlaybackWriter) SessionEvents() ([]EventFields, error) { var sessionEvents []EventFields //events eventFile, err := os.Open(w.EventsPath) if err != nil { return nil, trace.Wrap(err) } defer eventFile.Close() grEvents, err := gzip.NewReader(eventFile) if err != nil { return nil, trace.Wrap(err) } defer grEvents.Close() scanner := bufio.NewScanner(grEvents) for scanner.Scan() { var f EventFields err := utils.FastUnmarshal(scanner.Bytes(), &f) if err != nil { if err == io.EOF { return sessionEvents, nil } return nil, trace.Wrap(err) } sessionEvents = append(sessionEvents, f) } if err := scanner.Err(); err != nil { return nil, trace.Wrap(err) } return sessionEvents, nil } // SessionChunks interprets the file at the given path as gzip-compressed list of session events and returns // the uncompressed contents as a result. func (w *PlaybackWriter) SessionChunks() ([]byte, error) { var stream []byte chunkFile, err := os.Open(w.ChunksPath) if err != nil { return nil, trace.Wrap(err) } defer chunkFile.Close() grChunk, err := gzip.NewReader(chunkFile) if err != nil { return nil, trace.Wrap(err) } defer grChunk.Close() stream, err = ioutil.ReadAll(grChunk) if err != nil { return nil, trace.Wrap(err) } return stream, nil } // PlaybackWriter reads messages from an AuditReader and writes them // to disk in a format suitable for SSH session playback. type PlaybackWriter struct { sid session.ID dir string reader AuditReader indexFile *os.File eventsFile *gzipWriter chunksFile *gzipWriter eventIndex int64 EventsPath string ChunksPath string } // Close closes all files func (w *PlaybackWriter) Close() error { if w.indexFile != nil { if err := w.indexFile.Close(); err != nil { log.Warningf("Failed to close index file: %v.", err) } w.indexFile = nil } if w.chunksFile != nil { if err := w.chunksFile.Flush(); err != nil { log.Warningf("Failed to flush chunks file: %v.", err) } if err := w.chunksFile.Close(); err != nil { log.Warningf("Failed closing chunks file: %v.", err) } } if w.eventsFile != nil { if err := w.eventsFile.Flush(); err != nil { log.Warningf("Failed to flush events file: %v.", err) } if err := w.eventsFile.Close(); err != nil { log.Warningf("Failed closing events file: %v.", err) } } return nil } // Write writes all events from the AuditReader and writes // files to disk in the format optimized for playback. func (w *PlaybackWriter) Write(ctx context.Context) error { if err := w.openIndexFile(); err != nil { return trace.Wrap(err) } for { event, err := w.reader.Read(ctx) if err != nil { if err == io.EOF { return nil } return trace.Wrap(err) } if err := w.writeEvent(event); err != nil { return trace.Wrap(err) } } } func (w *PlaybackWriter) writeEvent(event apievents.AuditEvent) error { switch event.GetType() { // Timing events for TTY playback go to both a chunks file (the raw bytes) as // well as well as the events file (structured events). case SessionPrintEvent: return trace.Wrap(w.writeSessionPrintEvent(event)) // Playback does not use enhanced events at the moment, // so they are skipped case SessionCommandEvent, SessionDiskEvent, SessionNetworkEvent: return nil // PlaybackWriter is not used for desktop playback, so we should never see // these events, but skip them if a user or developer somehow tries to playback // a desktop session using this TTY PlaybackWriter case DesktopRecordingEvent: return nil // All other events get put into the general events file. These are events like // session.join, session.end, etc. default: return trace.Wrap(w.writeRegularEvent(event)) } } func (w *PlaybackWriter) writeSessionPrintEvent(event apievents.AuditEvent) error { print, ok := event.(*apievents.SessionPrint) if !ok { return trace.BadParameter("expected session print event, got %T", event) } w.eventIndex++ event.SetIndex(w.eventIndex) if err := w.openEventsFile(0); err != nil { return trace.Wrap(err) } if err := w.openChunksFile(0); err != nil { return trace.Wrap(err) } data := print.Data print.Data = nil bytes, err := utils.FastMarshal(event) if err != nil { return trace.Wrap(err) } _, err = w.eventsFile.Write(append(bytes, '\n')) if err != nil { return trace.Wrap(err) } _, err = w.chunksFile.Write(data) if err != nil { return trace.Wrap(err) } return nil } func (w *PlaybackWriter) writeRegularEvent(event apievents.AuditEvent) error { w.eventIndex++ event.SetIndex(w.eventIndex) if err := w.openEventsFile(0); err != nil { return trace.Wrap(err) } bytes, err := utils.FastMarshal(event) if err != nil { return trace.Wrap(err) } _, err = w.eventsFile.Write(append(bytes, '\n')) if err != nil { return trace.Wrap(err) } return nil } func (w *PlaybackWriter) openIndexFile() error { if w.indexFile != nil { return nil } var err error w.indexFile, err = os.OpenFile( filepath.Join(w.dir, fmt.Sprintf("%v.index", w.sid.String())), os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0640) if err != nil { return trace.Wrap(err) } return nil } func (w *PlaybackWriter) openEventsFile(eventIndex int64) error { if w.eventsFile != nil { return nil } w.EventsPath = eventsFileName(w.dir, w.sid, "", eventIndex) // update the index file to write down that new events file has been created data, err := utils.FastMarshal(indexEntry{ FileName: filepath.Base(w.EventsPath), Type: fileTypeEvents, Index: eventIndex, }) if err != nil { return trace.Wrap(err) } _, err = fmt.Fprintf(w.indexFile, "%v\n", string(data)) if err != nil { return trace.Wrap(err) } // open new events file for writing file, err := os.OpenFile(w.EventsPath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0640) if err != nil { return trace.Wrap(err) } w.eventsFile = newGzipWriter(file) return nil } func (w *PlaybackWriter) openChunksFile(offset int64) error { if w.chunksFile != nil { return nil } w.ChunksPath = chunksFileName(w.dir, w.sid, offset) // Update the index file to write down that new chunks file has been created. data, err := utils.FastMarshal(indexEntry{ FileName: filepath.Base(w.ChunksPath), Type: fileTypeChunks, Offset: offset, }) if err != nil { return trace.Wrap(err) } // index file will contain file name with extension .gz (assuming it was gzipped) _, err = fmt.Fprintf(w.indexFile, "%v\n", string(data)) if err != nil { return trace.Wrap(err) } // open the chunks file for writing, but because the file is written without // compression, remove the .gz file, err := os.OpenFile(w.ChunksPath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0640) if err != nil { return trace.Wrap(err) } w.chunksFile = newGzipWriter(file) return nil }
gravitational/teleport
lib/events/playback.go
GO
apache-2.0
10,730
package de.devisnik.mine.robot.test; import de.devisnik.mine.robot.AutoPlayerTest; import de.devisnik.mine.robot.ConfigurationTest; import junit.framework.Test; import junit.framework.TestSuite; public class AllTests { public static Test suite() { TestSuite suite = new TestSuite("Tests for de.devisnik.mine.robot"); //$JUnit-BEGIN$ suite.addTestSuite(AutoPlayerTest.class); suite.addTestSuite(ConfigurationTest.class); //$JUnit-END$ return suite; } }
devisnik/mines
robot/src/test/java/de/devisnik/mine/robot/test/AllTests.java
Java
apache-2.0
470
package com.beanu.l2_shareutil.share; import androidx.annotation.IntDef; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Created by shaohui on 2016/11/18. */ public class SharePlatform { @IntDef({ DEFAULT, QQ, QZONE, WEIBO, WX, WX_TIMELINE }) @Retention(RetentionPolicy.SOURCE) public @interface Platform{} public static final int DEFAULT = 0; public static final int QQ = 1; public static final int QZONE = 2; public static final int WX = 3; public static final int WX_TIMELINE = 4; public static final int WEIBO = 5; }
beanu/smart-farmer-android
l2_shareutil/src/main/java/com/beanu/l2_shareutil/share/SharePlatform.java
Java
apache-2.0
608
<?php /** * Contains all client objects for the ExchangeRateService * service. * * PHP version 5 * * Copyright 2016, Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @package GoogleApiAdsDfp * @subpackage v201605 * @category WebServices * @copyright 2016, Google Inc. All Rights Reserved. * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, * Version 2.0 */ require_once "Google/Api/Ads/Dfp/Lib/DfpSoapClient.php"; if (!class_exists("ApiError", false)) { /** * The API error base class that provides details about an error that occurred * while processing a service request. * * <p>The OGNL field path is provided for parsers to identify the request data * element that may have caused the error.</p> * @package GoogleApiAdsDfp * @subpackage v201605 */ class ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "ApiError"; /** * @access public * @var string */ public $fieldPath; /** * @access public * @var string */ public $trigger; /** * @access public * @var string */ public $errorString; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($fieldPath = null, $trigger = null, $errorString = null) { $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; } } } if (!class_exists("ApiVersionError", false)) { /** * Errors related to the usage of API versions. * @package GoogleApiAdsDfp * @subpackage v201605 */ class ApiVersionError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "ApiVersionError"; /** * @access public * @var tnsApiVersionErrorReason */ public $reason; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; } } } if (!class_exists("ApplicationException", false)) { /** * Base class for exceptions. * @package GoogleApiAdsDfp * @subpackage v201605 */ class ApplicationException { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "ApplicationException"; /** * @access public * @var string */ public $message; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($message = null) { $this->message = $message; } } } if (!class_exists("AuthenticationError", false)) { /** * An error for an exception that occurred when authenticating. * @package GoogleApiAdsDfp * @subpackage v201605 */ class AuthenticationError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "AuthenticationError"; /** * @access public * @var tnsAuthenticationErrorReason */ public $reason; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; } } } if (!class_exists("CollectionSizeError", false)) { /** * Error for the size of the collection being too large * @package GoogleApiAdsDfp * @subpackage v201605 */ class CollectionSizeError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "CollectionSizeError"; /** * @access public * @var tnsCollectionSizeErrorReason */ public $reason; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; } } } if (!class_exists("CommonError", false)) { /** * A place for common errors that can be used across services. * @package GoogleApiAdsDfp * @subpackage v201605 */ class CommonError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "CommonError"; /** * @access public * @var tnsCommonErrorReason */ public $reason; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; } } } if (!class_exists("Date", false)) { /** * Represents a date. * @package GoogleApiAdsDfp * @subpackage v201605 */ class Date { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "Date"; /** * @access public * @var integer */ public $year; /** * @access public * @var integer */ public $month; /** * @access public * @var integer */ public $day; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($year = null, $month = null, $day = null) { $this->year = $year; $this->month = $month; $this->day = $day; } } } if (!class_exists("DfpDateTime", false)) { /** * Represents a date combined with the time of day. * @package GoogleApiAdsDfp * @subpackage v201605 */ class DfpDateTime { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "DateTime"; /** * @access public * @var Date */ public $date; /** * @access public * @var integer */ public $hour; /** * @access public * @var integer */ public $minute; /** * @access public * @var integer */ public $second; /** * @access public * @var string */ public $timeZoneID; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($date = null, $hour = null, $minute = null, $second = null, $timeZoneID = null) { $this->date = $date; $this->hour = $hour; $this->minute = $minute; $this->second = $second; $this->timeZoneID = $timeZoneID; } } } if (!class_exists("ExchangeRateAction", false)) { /** * Represents the actions that can be performed on {@link ExchangeRate} objects. * @package GoogleApiAdsDfp * @subpackage v201605 */ class ExchangeRateAction { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "ExchangeRateAction"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("ExchangeRate", false)) { /** * An {@code ExchangeRate} represents a currency which is one of the * {@link Network#secondaryCurrencyCodes}, and the latest exchange rate between this currency and * {@link Network#currencyCode}. * @package GoogleApiAdsDfp * @subpackage v201605 */ class ExchangeRate { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "ExchangeRate"; /** * @access public * @var integer */ public $id; /** * @access public * @var string */ public $currencyCode; /** * @access public * @var tnsExchangeRateRefreshRate */ public $refreshRate; /** * @access public * @var tnsExchangeRateDirection */ public $direction; /** * @access public * @var integer */ public $exchangeRate; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($id = null, $currencyCode = null, $refreshRate = null, $direction = null, $exchangeRate = null) { $this->id = $id; $this->currencyCode = $currencyCode; $this->refreshRate = $refreshRate; $this->direction = $direction; $this->exchangeRate = $exchangeRate; } } } if (!class_exists("ExchangeRateError", false)) { /** * Lists all errors associated with {@link ExchangeRate} objects. * @package GoogleApiAdsDfp * @subpackage v201605 */ class ExchangeRateError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "ExchangeRateError"; /** * @access public * @var tnsExchangeRateErrorReason */ public $reason; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; } } } if (!class_exists("ExchangeRatePage", false)) { /** * Captures a page of {@link ExchangeRate} objects. * @package GoogleApiAdsDfp * @subpackage v201605 */ class ExchangeRatePage { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "ExchangeRatePage"; /** * @access public * @var ExchangeRate[] */ public $results; /** * @access public * @var integer */ public $startIndex; /** * @access public * @var integer */ public $totalResultSetSize; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($results = null, $startIndex = null, $totalResultSetSize = null) { $this->results = $results; $this->startIndex = $startIndex; $this->totalResultSetSize = $totalResultSetSize; } } } if (!class_exists("FeatureError", false)) { /** * Errors related to feature management. If you attempt using a feature that is not available to * the current network you'll receive a FeatureError with the missing feature as the trigger. * @package GoogleApiAdsDfp * @subpackage v201605 */ class FeatureError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "FeatureError"; /** * @access public * @var tnsFeatureErrorReason */ public $reason; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; } } } if (!class_exists("InternalApiError", false)) { /** * Indicates that a server-side error has occured. {@code InternalApiError}s * are generally not the result of an invalid request or message sent by the * client. * @package GoogleApiAdsDfp * @subpackage v201605 */ class InternalApiError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "InternalApiError"; /** * @access public * @var tnsInternalApiErrorReason */ public $reason; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; } } } if (!class_exists("NotNullError", false)) { /** * Caused by supplying a null value for an attribute that cannot be null. * @package GoogleApiAdsDfp * @subpackage v201605 */ class NotNullError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "NotNullError"; /** * @access public * @var tnsNotNullErrorReason */ public $reason; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; } } } if (!class_exists("ParseError", false)) { /** * Lists errors related to parsing. * @package GoogleApiAdsDfp * @subpackage v201605 */ class ParseError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "ParseError"; /** * @access public * @var tnsParseErrorReason */ public $reason; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; } } } if (!class_exists("PermissionError", false)) { /** * Errors related to incorrect permission. * @package GoogleApiAdsDfp * @subpackage v201605 */ class PermissionError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "PermissionError"; /** * @access public * @var tnsPermissionErrorReason */ public $reason; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; } } } if (!class_exists("PublisherQueryLanguageContextError", false)) { /** * An error that occurs while executing a PQL query contained in * a {@link Statement} object. * @package GoogleApiAdsDfp * @subpackage v201605 */ class PublisherQueryLanguageContextError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "PublisherQueryLanguageContextError"; /** * @access public * @var tnsPublisherQueryLanguageContextErrorReason */ public $reason; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; } } } if (!class_exists("PublisherQueryLanguageSyntaxError", false)) { /** * An error that occurs while parsing a PQL query contained in a * {@link Statement} object. * @package GoogleApiAdsDfp * @subpackage v201605 */ class PublisherQueryLanguageSyntaxError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "PublisherQueryLanguageSyntaxError"; /** * @access public * @var tnsPublisherQueryLanguageSyntaxErrorReason */ public $reason; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; } } } if (!class_exists("QuotaError", false)) { /** * Describes a client-side error on which a user is attempting * to perform an action to which they have no quota remaining. * @package GoogleApiAdsDfp * @subpackage v201605 */ class QuotaError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "QuotaError"; /** * @access public * @var tnsQuotaErrorReason */ public $reason; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; } } } if (!class_exists("RequiredCollectionError", false)) { /** * A list of all errors to be used for validating sizes of collections. * @package GoogleApiAdsDfp * @subpackage v201605 */ class RequiredCollectionError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "RequiredCollectionError"; /** * @access public * @var tnsRequiredCollectionErrorReason */ public $reason; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; } } } if (!class_exists("RequiredError", false)) { /** * Errors due to missing required field. * @package GoogleApiAdsDfp * @subpackage v201605 */ class RequiredError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "RequiredError"; /** * @access public * @var tnsRequiredErrorReason */ public $reason; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; } } } if (!class_exists("RequiredNumberError", false)) { /** * A list of all errors to be used in conjunction with required number * validators. * @package GoogleApiAdsDfp * @subpackage v201605 */ class RequiredNumberError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "RequiredNumberError"; /** * @access public * @var tnsRequiredNumberErrorReason */ public $reason; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; } } } if (!class_exists("ServerError", false)) { /** * Errors related to the server. * @package GoogleApiAdsDfp * @subpackage v201605 */ class ServerError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "ServerError"; /** * @access public * @var tnsServerErrorReason */ public $reason; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; } } } if (!class_exists("SoapRequestHeader", false)) { /** * Represents the SOAP request header used by API requests. * @package GoogleApiAdsDfp * @subpackage v201605 */ class SoapRequestHeader { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "SoapRequestHeader"; /** * @access public * @var string */ public $networkCode; /** * @access public * @var string */ public $applicationName; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($networkCode = null, $applicationName = null) { $this->networkCode = $networkCode; $this->applicationName = $applicationName; } } } if (!class_exists("SoapResponseHeader", false)) { /** * Represents the SOAP request header used by API responses. * @package GoogleApiAdsDfp * @subpackage v201605 */ class SoapResponseHeader { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "SoapResponseHeader"; /** * @access public * @var string */ public $requestId; /** * @access public * @var integer */ public $responseTime; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($requestId = null, $responseTime = null) { $this->requestId = $requestId; $this->responseTime = $responseTime; } } } if (!class_exists("Statement", false)) { /** * Captures the {@code WHERE}, {@code ORDER BY} and {@code LIMIT} clauses of a * PQL query. Statements are typically used to retrieve objects of a predefined * domain type, which makes SELECT clause unnecessary. * <p> * An example query text might be {@code "WHERE status = 'ACTIVE' ORDER BY id * LIMIT 30"}. * </p> * <p> * Statements support bind variables. These are substitutes for literals * and can be thought of as input parameters to a PQL query. * </p> * <p> * An example of such a query might be {@code "WHERE id = :idValue"}. * </p> * <p> * Statements also support use of the LIKE keyword. This provides partial and * wildcard string matching. * </p> * <p> * An example of such a query might be {@code "WHERE name LIKE 'startswith%'"}. * </p> * The value for the variable idValue must then be set with an object of type * {@link Value}, e.g., {@link NumberValue}, {@link TextValue} or * {@link BooleanValue}. * @package GoogleApiAdsDfp * @subpackage v201605 */ class Statement { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "Statement"; /** * @access public * @var string */ public $query; /** * @access public * @var String_ValueMapEntry[] */ public $values; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($query = null, $values = null) { $this->query = $query; $this->values = $values; } } } if (!class_exists("StatementError", false)) { /** * An error that occurs while parsing {@link Statement} objects. * @package GoogleApiAdsDfp * @subpackage v201605 */ class StatementError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "StatementError"; /** * @access public * @var tnsStatementErrorReason */ public $reason; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; } } } if (!class_exists("StringLengthError", false)) { /** * Errors for Strings which do not meet given length constraints. * @package GoogleApiAdsDfp * @subpackage v201605 */ class StringLengthError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "StringLengthError"; /** * @access public * @var tnsStringLengthErrorReason */ public $reason; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; } } } if (!class_exists("String_ValueMapEntry", false)) { /** * This represents an entry in a map with a key of type String * and value of type Value. * @package GoogleApiAdsDfp * @subpackage v201605 */ class String_ValueMapEntry { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "String_ValueMapEntry"; /** * @access public * @var string */ public $key; /** * @access public * @var Value */ public $value; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($key = null, $value = null) { $this->key = $key; $this->value = $value; } } } if (!class_exists("UniqueError", false)) { /** * An error for a field which must satisfy a uniqueness constraint * @package GoogleApiAdsDfp * @subpackage v201605 */ class UniqueError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "UniqueError"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($fieldPath = null, $trigger = null, $errorString = null) { parent::__construct(); $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; } } } if (!class_exists("UpdateResult", false)) { /** * Represents the result of performing an action on objects. * @package GoogleApiAdsDfp * @subpackage v201605 */ class UpdateResult { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "UpdateResult"; /** * @access public * @var integer */ public $numChanges; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($numChanges = null) { $this->numChanges = $numChanges; } } } if (!class_exists("Value", false)) { /** * {@code Value} represents a value. * @package GoogleApiAdsDfp * @subpackage v201605 */ class Value { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "Value"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("ApiVersionErrorReason", false)) { /** * Indicates that the operation is not allowed in the version the request * was made in. * @package GoogleApiAdsDfp * @subpackage v201605 */ class ApiVersionErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "ApiVersionError.Reason"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("AuthenticationErrorReason", false)) { /** * The SOAP message contains a request header with an ambiguous definition * of the authentication header fields. This means either the {@code * authToken} and {@code oAuthToken} fields were both null or both were * specified. Exactly one value should be specified with each request. * @package GoogleApiAdsDfp * @subpackage v201605 */ class AuthenticationErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "AuthenticationError.Reason"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("CollectionSizeErrorReason", false)) { /** * The value returned if the actual value is not exposed by the requested API version. * @package GoogleApiAdsDfp * @subpackage v201605 */ class CollectionSizeErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "CollectionSizeError.Reason"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("CommonErrorReason", false)) { /** * Describes reasons for common errors * @package GoogleApiAdsDfp * @subpackage v201605 */ class CommonErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "CommonError.Reason"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("ExchangeRateDirection", false)) { /** * Determines which direction (from which currency to which currency) the exchange rate is in. * @package GoogleApiAdsDfp * @subpackage v201605 */ class ExchangeRateDirection { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "ExchangeRateDirection"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("ExchangeRateErrorReason", false)) { /** * The reasons for the target error. * @package GoogleApiAdsDfp * @subpackage v201605 */ class ExchangeRateErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "ExchangeRateError.Reason"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("ExchangeRateRefreshRate", false)) { /** * Determines at which rate the exchange rate is refreshed. * @package GoogleApiAdsDfp * @subpackage v201605 */ class ExchangeRateRefreshRate { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "ExchangeRateRefreshRate"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("FeatureErrorReason", false)) { /** * A feature is being used that is not enabled on the current network. * @package GoogleApiAdsDfp * @subpackage v201605 */ class FeatureErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "FeatureError.Reason"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("InternalApiErrorReason", false)) { /** * The single reason for the internal API error. * @package GoogleApiAdsDfp * @subpackage v201605 */ class InternalApiErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "InternalApiError.Reason"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("NotNullErrorReason", false)) { /** * The reasons for the target error. * @package GoogleApiAdsDfp * @subpackage v201605 */ class NotNullErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "NotNullError.Reason"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("ParseErrorReason", false)) { /** * The reasons for the target error. * @package GoogleApiAdsDfp * @subpackage v201605 */ class ParseErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "ParseError.Reason"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("PermissionErrorReason", false)) { /** * Describes reasons for permission errors. * @package GoogleApiAdsDfp * @subpackage v201605 */ class PermissionErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "PermissionError.Reason"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("PublisherQueryLanguageContextErrorReason", false)) { /** * The reasons for the target error. * @package GoogleApiAdsDfp * @subpackage v201605 */ class PublisherQueryLanguageContextErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "PublisherQueryLanguageContextError.Reason"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("PublisherQueryLanguageSyntaxErrorReason", false)) { /** * The reasons for the target error. * @package GoogleApiAdsDfp * @subpackage v201605 */ class PublisherQueryLanguageSyntaxErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "PublisherQueryLanguageSyntaxError.Reason"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("QuotaErrorReason", false)) { /** * The number of requests made per second is too high and has exceeded the * allowable limit. The recommended approach to handle this error is to wait * about 5 seconds and then retry the request. Note that this does not * guarantee the request will succeed. If it fails again, try increasing the * wait time. * <p> * Another way to mitigate this error is to limit requests to 2 per second for * Small Business networks, or 8 per second for Premium networks. Once again * this does not guarantee that every request will succeed, but may help * reduce the number of times you receive this error. * </p> * @package GoogleApiAdsDfp * @subpackage v201605 */ class QuotaErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "QuotaError.Reason"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("RequiredCollectionErrorReason", false)) { /** * A required collection is missing. * @package GoogleApiAdsDfp * @subpackage v201605 */ class RequiredCollectionErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "RequiredCollectionError.Reason"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("RequiredErrorReason", false)) { /** * The reasons for the target error. * @package GoogleApiAdsDfp * @subpackage v201605 */ class RequiredErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "RequiredError.Reason"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("RequiredNumberErrorReason", false)) { /** * Describes reasons for a number to be invalid. * @package GoogleApiAdsDfp * @subpackage v201605 */ class RequiredNumberErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "RequiredNumberError.Reason"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("ServerErrorReason", false)) { /** * Describes reasons for server errors * @package GoogleApiAdsDfp * @subpackage v201605 */ class ServerErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "ServerError.Reason"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("StatementErrorReason", false)) { /** * A bind variable has not been bound to a value. * @package GoogleApiAdsDfp * @subpackage v201605 */ class StatementErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "StatementError.Reason"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("StringLengthErrorReason", false)) { /** * The value returned if the actual value is not exposed by the requested API version. * @package GoogleApiAdsDfp * @subpackage v201605 */ class StringLengthErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "StringLengthError.Reason"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("CreateExchangeRates", false)) { /** * Creates new {@link ExchangeRate} objects. * * For each exchange rate, the following fields are required: * <ul> * <li>{@link ExchangeRate#currencyCode}</li> * <li>{@link ExchangeRate#exchangeRate} when {@link ExchangeRate#refreshRate} is * {@link ExchangeRateRefreshRate#FIXED}</li> * </ul> * * @param exchangeRates the exchange rates to create * @return the created exchange rates with their exchange rate values filled in * @package GoogleApiAdsDfp * @subpackage v201605 */ class CreateExchangeRates { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = ""; /** * @access public * @var ExchangeRate[] */ public $exchangeRates; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($exchangeRates = null) { $this->exchangeRates = $exchangeRates; } } } if (!class_exists("CreateExchangeRatesResponse", false)) { /** * * @package GoogleApiAdsDfp * @subpackage v201605 */ class CreateExchangeRatesResponse { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = ""; /** * @access public * @var ExchangeRate[] */ public $rval; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($rval = null) { $this->rval = $rval; } } } if (!class_exists("GetExchangeRatesByStatement", false)) { /** * Gets a {@link ExchangeRatePage} of {@link ExchangeRate} objects that satisfy the given * {@link Statement#query}. The following fields are supported for filtering: * * <table> * <tr> * <th scope="col">PQL Property</th> <th scope="col">Object Property</th> * </tr> * <tr> * <td>{@code id}</td> * <td>{@link ExchangeRate#id}</td> * </tr> * <tr> * <td>{@code currencyCode}</td> * <td>{@link ExchangeRate#currencyCode}</td> * </tr> * <tr> * <td>{@code refreshRate}</td> * <td>{@link ExchangeRate#refreshRate}</td> * </tr> * <tr> * <td>{@code direction}</td> * <td>{@link ExchangeRate#direction}</td> * </tr> * <tr> * <td>{@code exchangeRate}</td> * <td>{@link ExchangeRate#exchangeRate}</td> * </tr> * </table> * * @param filterStatement a Publisher Query Language statement used to filter * a set of exchange rates * @return the exchange rates that match the given filter * @package GoogleApiAdsDfp * @subpackage v201605 */ class GetExchangeRatesByStatement { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = ""; /** * @access public * @var Statement */ public $filterStatement; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($filterStatement = null) { $this->filterStatement = $filterStatement; } } } if (!class_exists("GetExchangeRatesByStatementResponse", false)) { /** * * @package GoogleApiAdsDfp * @subpackage v201605 */ class GetExchangeRatesByStatementResponse { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = ""; /** * @access public * @var ExchangeRatePage */ public $rval; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($rval = null) { $this->rval = $rval; } } } if (!class_exists("PerformExchangeRateAction", false)) { /** * Performs an action on {@link ExchangeRate} objects that satisfy the given * {@link Statement#query}. The following fields are supported for filtering: * * <table> * <tr> * <th scope="col">PQL Property</th> <th scope="col">Object Property</th> * </tr> * <tr> * <td>{@code id}</td> * <td>{@link ExchangeRate#id}</td> * </tr> * <tr> * <td>{@code currencyCode}</td> * <td>{@link ExchangeRate#currencyCode}</td> * </tr> * <tr> * <td>{@code refreshRate}</td> * <td>{@link ExchangeRate#refreshRate}</td> * </tr> * <tr> * <td>{@code direction}</td> * <td>{@link ExchangeRate#direction}</td> * </tr> * <tr> * <td>{@code exchangeRate}</td> * <td>{@link ExchangeRate#exchangeRate}</td> * </tr> * </table> * * @param exchangeRateAction the action to perform * @param filterStatement a Publisher Query Language statement used to filter * a set of exchange rates * @return the result of the action performed * @package GoogleApiAdsDfp * @subpackage v201605 */ class PerformExchangeRateAction { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = ""; /** * @access public * @var ExchangeRateAction */ public $exchangeRateAction; /** * @access public * @var Statement */ public $filterStatement; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($exchangeRateAction = null, $filterStatement = null) { $this->exchangeRateAction = $exchangeRateAction; $this->filterStatement = $filterStatement; } } } if (!class_exists("PerformExchangeRateActionResponse", false)) { /** * * @package GoogleApiAdsDfp * @subpackage v201605 */ class PerformExchangeRateActionResponse { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = ""; /** * @access public * @var UpdateResult */ public $rval; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($rval = null) { $this->rval = $rval; } } } if (!class_exists("UpdateExchangeRates", false)) { /** * Updates the specified {@link ExchangeRate} objects. * * @param exchangeRates the exchange rates to update * @return the updated exchange rates * @package GoogleApiAdsDfp * @subpackage v201605 */ class UpdateExchangeRates { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = ""; /** * @access public * @var ExchangeRate[] */ public $exchangeRates; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($exchangeRates = null) { $this->exchangeRates = $exchangeRates; } } } if (!class_exists("UpdateExchangeRatesResponse", false)) { /** * * @package GoogleApiAdsDfp * @subpackage v201605 */ class UpdateExchangeRatesResponse { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = ""; /** * @access public * @var ExchangeRate[] */ public $rval; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($rval = null) { $this->rval = $rval; } } } if (!class_exists("ObjectValue", false)) { /** * Contains an object value. * <p> * <b>This object is experimental! * <code>ObjectValue</code> is an experimental, innovative, and rapidly * changing new feature for DFP. Unfortunately, being on the bleeding edge means that we may make * backwards-incompatible changes to * <code>ObjectValue</code>. We will inform the community when this feature * is no longer experimental.</b> * @package GoogleApiAdsDfp * @subpackage v201605 */ class ObjectValue extends Value { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "ObjectValue"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { parent::__construct(); } } } if (!class_exists("ApiException", false)) { /** * Exception class for holding a list of service errors. * @package GoogleApiAdsDfp * @subpackage v201605 */ class ApiException extends ApplicationException { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "ApiException"; /** * @access public * @var ApiError[] */ public $errors; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($errors = null, $message = null) { parent::__construct(); $this->errors = $errors; $this->message = $message; } } } if (!class_exists("BooleanValue", false)) { /** * Contains a boolean value. * @package GoogleApiAdsDfp * @subpackage v201605 */ class BooleanValue extends Value { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "BooleanValue"; /** * @access public * @var boolean */ public $value; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($value = null) { parent::__construct(); $this->value = $value; } } } if (!class_exists("DateTimeValue", false)) { /** * Contains a date-time value. * @package GoogleApiAdsDfp * @subpackage v201605 */ class DateTimeValue extends Value { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "DateTimeValue"; /** * @access public * @var DateTime */ public $value; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($value = null) { parent::__construct(); $this->value = $value; } } } if (!class_exists("DateValue", false)) { /** * Contains a date value. * @package GoogleApiAdsDfp * @subpackage v201605 */ class DateValue extends Value { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "DateValue"; /** * @access public * @var Date */ public $value; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($value = null) { parent::__construct(); $this->value = $value; } } } if (!class_exists("DeleteExchangeRates", false)) { /** * The action used to delete {@link ExchangeRate} objects. * @package GoogleApiAdsDfp * @subpackage v201605 */ class DeleteExchangeRates extends ExchangeRateAction { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "DeleteExchangeRates"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { parent::__construct(); } } } if (!class_exists("NumberValue", false)) { /** * Contains a numeric value. * @package GoogleApiAdsDfp * @subpackage v201605 */ class NumberValue extends Value { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "NumberValue"; /** * @access public * @var string */ public $value; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($value = null) { parent::__construct(); $this->value = $value; } } } if (!class_exists("SetValue", false)) { /** * Contains a set of {@link Value Values}. May not contain duplicates. * @package GoogleApiAdsDfp * @subpackage v201605 */ class SetValue extends Value { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "SetValue"; /** * @access public * @var Value[] */ public $values; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($values = null) { parent::__construct(); $this->values = $values; } } } if (!class_exists("TextValue", false)) { /** * Contains a string value. * @package GoogleApiAdsDfp * @subpackage v201605 */ class TextValue extends Value { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "TextValue"; /** * @access public * @var string */ public $value; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($value = null) { parent::__construct(); $this->value = $value; } } } if (!class_exists("ExchangeRateService", false)) { /** * ExchangeRateService * @package GoogleApiAdsDfp * @subpackage v201605 */ class ExchangeRateService extends DfpSoapClient { const SERVICE_NAME = "ExchangeRateService"; const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const ENDPOINT = "https://ads.google.com/apis/ads/publisher/v201605/ExchangeRateService"; /** * The endpoint of the service * @var string */ public static $endpoint = "https://ads.google.com/apis/ads/publisher/v201605/ExchangeRateService"; /** * Default class map for wsdl=>php * @access private * @var array */ public static $classmap = array( "ObjectValue" => "ObjectValue", "ApiError" => "ApiError", "ApiException" => "ApiException", "ApiVersionError" => "ApiVersionError", "ApplicationException" => "ApplicationException", "AuthenticationError" => "AuthenticationError", "BooleanValue" => "BooleanValue", "CollectionSizeError" => "CollectionSizeError", "CommonError" => "CommonError", "Date" => "Date", "DateTime" => "DfpDateTime", "DateTimeValue" => "DateTimeValue", "DateValue" => "DateValue", "DeleteExchangeRates" => "DeleteExchangeRates", "ExchangeRateAction" => "ExchangeRateAction", "ExchangeRate" => "ExchangeRate", "ExchangeRateError" => "ExchangeRateError", "ExchangeRatePage" => "ExchangeRatePage", "FeatureError" => "FeatureError", "InternalApiError" => "InternalApiError", "NotNullError" => "NotNullError", "NumberValue" => "NumberValue", "ParseError" => "ParseError", "PermissionError" => "PermissionError", "PublisherQueryLanguageContextError" => "PublisherQueryLanguageContextError", "PublisherQueryLanguageSyntaxError" => "PublisherQueryLanguageSyntaxError", "QuotaError" => "QuotaError", "RequiredCollectionError" => "RequiredCollectionError", "RequiredError" => "RequiredError", "RequiredNumberError" => "RequiredNumberError", "ServerError" => "ServerError", "SetValue" => "SetValue", "SoapRequestHeader" => "SoapRequestHeader", "SoapResponseHeader" => "SoapResponseHeader", "Statement" => "Statement", "StatementError" => "StatementError", "StringLengthError" => "StringLengthError", "String_ValueMapEntry" => "String_ValueMapEntry", "TextValue" => "TextValue", "UniqueError" => "UniqueError", "UpdateResult" => "UpdateResult", "Value" => "Value", "ApiVersionError.Reason" => "ApiVersionErrorReason", "AuthenticationError.Reason" => "AuthenticationErrorReason", "CollectionSizeError.Reason" => "CollectionSizeErrorReason", "CommonError.Reason" => "CommonErrorReason", "ExchangeRateDirection" => "ExchangeRateDirection", "ExchangeRateError.Reason" => "ExchangeRateErrorReason", "ExchangeRateRefreshRate" => "ExchangeRateRefreshRate", "FeatureError.Reason" => "FeatureErrorReason", "InternalApiError.Reason" => "InternalApiErrorReason", "NotNullError.Reason" => "NotNullErrorReason", "ParseError.Reason" => "ParseErrorReason", "PermissionError.Reason" => "PermissionErrorReason", "PublisherQueryLanguageContextError.Reason" => "PublisherQueryLanguageContextErrorReason", "PublisherQueryLanguageSyntaxError.Reason" => "PublisherQueryLanguageSyntaxErrorReason", "QuotaError.Reason" => "QuotaErrorReason", "RequiredCollectionError.Reason" => "RequiredCollectionErrorReason", "RequiredError.Reason" => "RequiredErrorReason", "RequiredNumberError.Reason" => "RequiredNumberErrorReason", "ServerError.Reason" => "ServerErrorReason", "StatementError.Reason" => "StatementErrorReason", "StringLengthError.Reason" => "StringLengthErrorReason", "createExchangeRates" => "CreateExchangeRates", "createExchangeRatesResponse" => "CreateExchangeRatesResponse", "getExchangeRatesByStatement" => "GetExchangeRatesByStatement", "getExchangeRatesByStatementResponse" => "GetExchangeRatesByStatementResponse", "performExchangeRateAction" => "PerformExchangeRateAction", "performExchangeRateActionResponse" => "PerformExchangeRateActionResponse", "updateExchangeRates" => "UpdateExchangeRates", "updateExchangeRatesResponse" => "UpdateExchangeRatesResponse", ); /** * Constructor using wsdl location and options array * @param string $wsdl WSDL location for this service * @param array $options Options for the SoapClient */ public function __construct($wsdl, $options, $user) { $options["classmap"] = self::$classmap; parent::__construct($wsdl, $options, $user, self::SERVICE_NAME, self::WSDL_NAMESPACE); } /** * Creates new {@link ExchangeRate} objects. * * For each exchange rate, the following fields are required: * <ul> * <li>{@link ExchangeRate#currencyCode}</li> * <li>{@link ExchangeRate#exchangeRate} when {@link ExchangeRate#refreshRate} is * {@link ExchangeRateRefreshRate#FIXED}</li> * </ul> * * @param exchangeRates the exchange rates to create * @return the created exchange rates with their exchange rate values filled in */ public function createExchangeRates($exchangeRates) { $args = new CreateExchangeRates($exchangeRates); $result = $this->__soapCall("createExchangeRates", array($args)); return $result->rval; } /** * Gets a {@link ExchangeRatePage} of {@link ExchangeRate} objects that satisfy the given * {@link Statement#query}. The following fields are supported for filtering: * * <table> * <tr> * <th scope="col">PQL Property</th> <th scope="col">Object Property</th> * </tr> * <tr> * <td>{@code id}</td> * <td>{@link ExchangeRate#id}</td> * </tr> * <tr> * <td>{@code currencyCode}</td> * <td>{@link ExchangeRate#currencyCode}</td> * </tr> * <tr> * <td>{@code refreshRate}</td> * <td>{@link ExchangeRate#refreshRate}</td> * </tr> * <tr> * <td>{@code direction}</td> * <td>{@link ExchangeRate#direction}</td> * </tr> * <tr> * <td>{@code exchangeRate}</td> * <td>{@link ExchangeRate#exchangeRate}</td> * </tr> * </table> * * @param filterStatement a Publisher Query Language statement used to filter * a set of exchange rates * @return the exchange rates that match the given filter */ public function getExchangeRatesByStatement($filterStatement) { $args = new GetExchangeRatesByStatement($filterStatement); $result = $this->__soapCall("getExchangeRatesByStatement", array($args)); return $result->rval; } /** * Performs an action on {@link ExchangeRate} objects that satisfy the given * {@link Statement#query}. The following fields are supported for filtering: * * <table> * <tr> * <th scope="col">PQL Property</th> <th scope="col">Object Property</th> * </tr> * <tr> * <td>{@code id}</td> * <td>{@link ExchangeRate#id}</td> * </tr> * <tr> * <td>{@code currencyCode}</td> * <td>{@link ExchangeRate#currencyCode}</td> * </tr> * <tr> * <td>{@code refreshRate}</td> * <td>{@link ExchangeRate#refreshRate}</td> * </tr> * <tr> * <td>{@code direction}</td> * <td>{@link ExchangeRate#direction}</td> * </tr> * <tr> * <td>{@code exchangeRate}</td> * <td>{@link ExchangeRate#exchangeRate}</td> * </tr> * </table> * * @param exchangeRateAction the action to perform * @param filterStatement a Publisher Query Language statement used to filter * a set of exchange rates * @return the result of the action performed */ public function performExchangeRateAction($exchangeRateAction, $filterStatement) { $args = new PerformExchangeRateAction($exchangeRateAction, $filterStatement); $result = $this->__soapCall("performExchangeRateAction", array($args)); return $result->rval; } /** * Updates the specified {@link ExchangeRate} objects. * * @param exchangeRates the exchange rates to update * @return the updated exchange rates */ public function updateExchangeRates($exchangeRates) { $args = new UpdateExchangeRates($exchangeRates); $result = $this->__soapCall("updateExchangeRates", array($args)); return $result->rval; } } }
gamejolt/googleads-php-lib
src/Google/Api/Ads/Dfp/v201605/ExchangeRateService.php
PHP
apache-2.0
81,385
<!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_77) on Mon May 23 19:37:01 EDT 2016 --> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Uses of Class org.apache.lucene.spatial.prefix.NumberRangePrefixTreeStrategy (Lucene 6.0.1 API)</title> <meta name="date" content="2016-05-23"> <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 org.apache.lucene.spatial.prefix.NumberRangePrefixTreeStrategy (Lucene 6.0.1 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="../../../../../../org/apache/lucene/spatial/prefix/NumberRangePrefixTreeStrategy.html" title="class in org.apache.lucene.spatial.prefix">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="../../../../../../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/lucene/spatial/prefix/class-use/NumberRangePrefixTreeStrategy.html" target="_top">Frames</a></li> <li><a href="NumberRangePrefixTreeStrategy.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;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.lucene.spatial.prefix.NumberRangePrefixTreeStrategy" class="title">Uses of Class<br>org.apache.lucene.spatial.prefix.NumberRangePrefixTreeStrategy</h2> </div> <div class="classUseContainer">No usage of org.apache.lucene.spatial.prefix.NumberRangePrefixTreeStrategy</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="../../../../../../org/apache/lucene/spatial/prefix/NumberRangePrefixTreeStrategy.html" title="class in org.apache.lucene.spatial.prefix">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="../../../../../../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/lucene/spatial/prefix/class-use/NumberRangePrefixTreeStrategy.html" target="_top">Frames</a></li> <li><a href="NumberRangePrefixTreeStrategy.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;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 &copy; 2000-2016 Apache Software Foundation. All Rights Reserved.</i> <script src='../../../../../../prettify.js' type='text/javascript'></script> <script type='text/javascript'> (function(){ var oldonload = window.onload; if (typeof oldonload != 'function') { window.onload = prettyPrint; } else { window.onload = function() { oldonload(); prettyPrint(); } } })(); </script> </small></p> </body> </html>
YorkUIRLab/irlab
lib/lucene-6.0.1/docs/spatial-extras/org/apache/lucene/spatial/prefix/class-use/NumberRangePrefixTreeStrategy.html
HTML
apache-2.0
5,316
# This migration comes from grocer (originally 20170119220038) class CreateGrocerExports < ActiveRecord::Migration[5.0] def change create_table :grocer_exports do |t| t.string :pid t.integer :job t.string :status t.datetime :last_error t.datetime :last_success t.string :logfile t.timestamps end add_index :grocer_exports, :pid, unique: true end end
pulibrary/plum
db/migrate/20170127153850_create_grocer_exports.grocer.rb
Ruby
apache-2.0
409
const loopback = require('loopback'); const boot = require('loopback-boot'); const request = require('request-promise'); const config = require('./config.json'); const log = require('log4js').getLogger('server'); const jwt = require('jwt-simple'); var app = module.exports = loopback(); var apiUrl = config.restApiRoot + '/*'; function parseJwt (token) { var base64Url = token.split('.')[1]; var base64 = base64Url.replace('-', '+').replace('_', '/'); var json = new Buffer(base64, 'base64').toString('binary'); return JSON.parse(json); }; app.use(loopback.context()); app.use(['/api/todos'], function(req, res, next) { var accessToken = req.query.access_token || req.headers['Authorization']; if(accessToken) { app.accessTokenProvider.getUserInfo(accessToken) .then(userInfo => { log.debug('userInfo:', userInfo); loopback.getCurrentContext().set('userInfo', userInfo); next(); }).catch(error => { log.error(error); next(error); }); } else { log.debug('missing accessToken'); next({ name: 'MISSING_ACCESS_TOKEN', status: 401, message: 'tenant access token is required to access this endpoint' }); } }); app.start = () => { // start the web server return app.listen(() => { app.emit('started'); var baseUrl = app.get('url').replace(/\/$/, ''); log.info('Web server listening at: %s', baseUrl); if (app.get('loopback-component-explorer')) { var explorerPath = app.get('loopback-component-explorer').mountPath; log.info('Browse your REST API at %s%s', baseUrl, explorerPath); } }); }; // Bootstrap the application, configure models, datasources and middleware. // Sub-apps like REST API are mounted via boot scripts. boot(app, __dirname, function(err) { if (err) throw err; // start the server if `$ node server.js` if (require.main === module) app.start(); });
SaaSManager/todo-example
server/server.js
JavaScript
apache-2.0
1,921
class TreeBuilderTenants < TreeBuilder has_kids_for Tenant, [:x_get_tree_tenant_kids] def initialize(name, sandbox, build, **params) @additional_tenants = params[:additional_tenants] @selectable = params[:selectable] @ansible_playbook = params[:ansible_playbook] @catalog_bundle = params[:catalog_bundle] super(name, sandbox, build) end private def tree_init_options { :checkboxes => true, :check_url => "/catalog/#{cat_item_or_bundle}/", :open_all => false, :oncheck => @selectable ? tenant_tree_or_generic : nil, :post_check => true, :three_checks => true }.compact end def tenant_tree_or_generic if @ansible_playbook 'miqOnCheckTenantTree' else 'miqOnCheckGeneric' end end def cat_item_or_bundle if @catalog_bundle 'st_form_field_changed' else 'atomic_form_field_changed' end end def root_options text = _('All Tenants') { :text => text, :tooltip => text, :icon => 'pficon pficon-tenant', :hideCheckbox => true } end def x_get_tree_roots if ApplicationHelper.role_allows?(:feature => 'rbac_tenant_view') Tenant.with_current_tenant end end def x_get_tree_tenant_kids(object, count_only) count_only_or_objects(count_only, object.children, 'name') end def override(node, object) node.checked = @additional_tenants.try(:include?, object) node.checkable = @selectable end end
ManageIQ/manageiq-ui-classic
app/presenters/tree_builder_tenants.rb
Ruby
apache-2.0
1,530
import {NgModule} from '@angular/core'; import {TestimonialService} from "./testimonial.service"; import {TestimonialEditorComponent} from "./testimonial-editor.component"; import {TestimonialComponent} from "./testimonial-list.component"; import {TestimonialRouting} from './testimonial.route'; import {SharedModule} from '../../../shared/shared.module'; import { XhrService } from '../../../shared/services/xhr.service'; @NgModule({ imports: [SharedModule.forRoot(),TestimonialRouting], declarations: [TestimonialComponent, TestimonialEditorComponent], providers: [TestimonialService, XhrService] }) export class TestimonialModule { }
nodebeats/nodebeats
admin/src/admin-app/dashboard-app/components/testimonial/testimonial.module.ts
TypeScript
apache-2.0
655
class Solution: def isValidSerialization(self, preorder): """ :type preorder: str :rtype: bool """ arr_pre_order = preorder.split(',') stack = [] for node in arr_pre_order: stack.append(node) while len(stack) > 1 and stack[-1] == '#' and stack[-2] == '#': stack.pop() stack.pop() if len(stack) < 1: return False stack[-1] = '#' if len(stack) == 1 and stack[0] == '#': return True return False
MingfeiPan/leetcode
stack/331.py
Python
apache-2.0
615
#!/usr/bin/python # -*- coding: utf-8 -*- # Author: violinsolo # Created on 08/03/2018 import tensorflow as tf import numpy as np x_shape = [5, 3, 3, 2] x = np.arange(reduce(lambda t, s: t*s, list(x_shape), 1)) print x x = x.reshape([5, 3, 3, -1]) print x.shape X = tf.Variable(x) with tf.Session() as sess: m = tf.nn.moments(X, axes=[0]) # m = tf.nn.moments(X, axes=[0,1]) # m = tf.nn.moments(X, axes=np.arange(len(x_shape)-1)) mean, variance = m print(sess.run(m, feed_dict={X: x})) # print(sess.run(m, feed_dict={X: x}))
iViolinSolo/DeepLearning-GetStarted
TF-Persion-ReID/test/test_tf_nn_moments.py
Python
apache-2.0
557
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ #include <sys/types.h> #include <sys/event.h> #include <sys/time.h> #include <string.h> #include <unistd.h> #include <ckit/event.h> #include <ckit/debug.h> #include <ckit/time.h> int event_open(void) { return kqueue(); } void event_close(int efd) { close(efd); } static unsigned short kevent_flags(enum event_ctl ctl, struct event *ev) { unsigned short flags = 0; switch (ctl) { case EVENT_CTL_ADD: case EVENT_CTL_MOD: flags |= EV_ADD; break; case EVENT_CTL_DEL: flags |= EV_DELETE; break; } if (ev->events & EVENT_ONESHOT) flags |= EV_ONESHOT; return flags; } static void kevent_to_event(const struct kevent *kev, struct event *ev) { memset(ev, 0, sizeof(*ev)); if (kev->filter == EVFILT_READ) { //LOG_DBG("EVFILT_READ is set fd=%d\n", (int)kev->ident); ev->events |= EVENT_IN; } if (kev->filter == EVFILT_WRITE) { //LOG_DBG("EVFILT_WRITE is set fd=%d\n", (int)kev->ident); ev->events |= EVENT_OUT; } if (kev->flags & EV_EOF) { //LOG_DBG("EV_EOF set on fd=%d\n", (int)kev->ident); ev->events |= EVENT_RDHUP; } ev->data.fd = (int)kev->ident; ev->data.ptr = kev->udata; } int event_ctl(int efd, enum event_ctl ctl, int fd, struct event *ev) { struct kevent kev[2]; unsigned i = 0; if (ev->events & EVENT_IN) { //LOG_ERR("EVFILT_READ fd=%d\n", fd); EV_SET(&kev[i++], fd, EVFILT_READ, kevent_flags(ctl, ev), 0, 0, ev->data.ptr); } if (ev->events & EVENT_OUT) { //LOG_ERR("EVFILT_WRITE fd=%d\n", fd); EV_SET(&kev[i++], fd, EVFILT_WRITE, kevent_flags(ctl, ev), 0, 0, ev->data.ptr); } return kevent(efd, kev, i, NULL, 0, NULL); } int event_wait(int efd, struct event *events, int maxevents, int timeout) { struct kevent kevents[maxevents]; struct timespec ts = { 0, 0 }; struct timespec *ts_ptr = &ts; int ret; timespec_add_nsec(&ts, timeout * 1000000L); memset(kevents, 0, sizeof(kevents)); if (timeout == -1) ts_ptr = NULL; ret = kevent(efd, NULL, 0, kevents, maxevents, ts_ptr); if (ret == -1) { LOG_ERR("kevent: %s\n", strerror(errno)); } else if (ret > 0) { int i; /* Fill in events */ for (i = 0; i < ret; i++) { /* Check for error. The kevent() call may return either -1 * on error or an error event in the eventlist in case * there is room */ if (kevents[i].flags & EV_ERROR) { errno = kevents[i].data; /* NOTE/WARNING: What happens to other events returned * that aren't errors when we return -1 here? This is * not entirely clear, but since they won't be * processed by the caller of this function (as the * return value is -1) the events should still be * pending and returned in the next call to this * function. This might, however, not be true for edge * triggered events. */ return -1; } kevent_to_event(&kevents[i], &events[i]); } } return ret; }
erimatnor/libckit
src/event_kqueue.c
C
apache-2.0
3,368
package com.blp.minotaurus.utils; import com.blp.minotaurus.Minotaurus; import net.milkbowl.vault.economy.Economy; import org.bukkit.Bukkit; import org.bukkit.plugin.RegisteredServiceProvider; /** * @author TheJeterLP */ public class EconomyManager { private static Economy econ = null; public static boolean setupEconomy() { if (!Minotaurus.getInstance().getServer().getPluginManager().isPluginEnabled("Vault")) return false; RegisteredServiceProvider<Economy> rsp = Bukkit.getServicesManager().getRegistration(Economy.class); if (rsp == null || rsp.getProvider() == null) return false; econ = rsp.getProvider(); return true; } public static Economy getEcon() { return econ; } }
BossLetsPlays/Minotaurus
src/main/java/com/blp/minotaurus/utils/EconomyManager.java
Java
apache-2.0
756
package eas.com; public interface SomeInterface { String someMethod(String param1, String param2, String param3, String param4); }
xalfonso/res_java
java-reflection-method/src/main/java/eas/com/SomeInterface.java
Java
apache-2.0
137
# Pterocaulon globuliferus W.Fitzg. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Pterocaulon/Pterocaulon globuliferus/README.md
Markdown
apache-2.0
183
'use strict'; angular.module('donetexampleApp') .service('ParseLinks', function () { this.parse = function (header) { if (header.length == 0) { throw new Error("input must not be of zero length"); } // Split parts by comma var parts = header.split(','); var links = {}; // Parse each part into a named link angular.forEach(parts, function (p) { var section = p.split(';'); if (section.length != 2) { throw new Error("section could not be split on ';'"); } var url = section[0].replace(/<(.*)>/, '$1').trim(); var queryString = {}; url.replace( new RegExp("([^?=&]+)(=([^&]*))?", "g"), function($0, $1, $2, $3) { queryString[$1] = $3; } ); var page = queryString['page']; if( angular.isString(page) ) { page = parseInt(page); } var name = section[1].replace(/rel="(.*)"/, '$1').trim(); links[name] = page; }); return links; } });
CyberCastle/DoNetExample
DoNetExample.Gui/scripts/components/util/parse-links.service.js
JavaScript
apache-2.0
1,252
package com.mobisys.musicplayer.model; import android.os.Parcel; import android.os.Parcelable; /** * Created by Govinda P on 6/3/2016. */ public class MusicFile implements Parcelable { private String title; private String album; private String id; private String singer; private String path; public MusicFile() { } public MusicFile(String title, String album, String id, String singer, String path) { this.title = title; this.album = album; this.id = id; this.singer = singer; this.path = path; } protected MusicFile(Parcel in) { title = in.readString(); album = in.readString(); id = in.readString(); singer = in.readString(); path=in.readString(); } public static final Creator<MusicFile> CREATOR = new Creator<MusicFile>() { @Override public MusicFile createFromParcel(Parcel in) { return new MusicFile(in); } @Override public MusicFile[] newArray(int size) { return new MusicFile[size]; } }; public String getTitle() { return title; } public String getAlbum() { return album; } public String getId() { return id; } public String getSinger() { return singer; } public void setTitle(String title) { this.title = title; } public void setAlbum(String album) { this.album = album; } public void setId(String id) { this.id = id; } public void setSinger(String singer) { this.singer = singer; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } @Override public String toString() { return "MusicFile{" + "title='" + title + '\'' + ", album='" + album + '\'' + ", id='" + id + '\'' + ", singer='" + singer + '\'' + ", path='" + path + '\'' + '}'; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(title); dest.writeString(album); dest.writeString(id); dest.writeString(singer); dest.writeString(path); } }
GovindaPaliwal/android-constraint-Layout
app/src/main/java/com/mobisys/musicplayer/model/MusicFile.java
Java
apache-2.0
2,408
# Strobilomyces coturnix Bouriquet SPECIES #### Status ACCEPTED #### According to Index Fungorum #### Published in Bull. Acad. malgache 25: 22 (1946) #### Original name Strobilomyces coturnix Bouriquet ### Remarks null
mdoering/backbone
life/Fungi/Basidiomycota/Agaricomycetes/Boletales/Boletaceae/Strobilomyces/Strobilomyces coturnix/README.md
Markdown
apache-2.0
223
# Cirsium undulatum subsp. helleri (Small) Petr. SUBSPECIES #### 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/Cirsium/Cirsium undulatum/ Syn. Cirsium undulatum helleri/README.md
Markdown
apache-2.0
206
<?php /********************************************************************************************************************************** * * Ajax Payment System * * Author: Webbu Design * ***********************************************************************************************************************************/ add_action( 'PF_AJAX_HANDLER_pfget_itemsystem', 'pf_ajax_itemsystem' ); add_action( 'PF_AJAX_HANDLER_nopriv_pfget_itemsystem', 'pf_ajax_itemsystem' ); function pf_ajax_itemsystem(){ check_ajax_referer( 'pfget_itemsystem', 'security'); header('Content-Type: application/json; charset=UTF-8;'); /* Get form variables */ if(isset($_POST['formtype']) && $_POST['formtype']!=''){ $formtype = $processname = esc_attr($_POST['formtype']); } /* Get data*/ $vars = array(); if(isset($_POST['dt']) && $_POST['dt']!=''){ if ($formtype == 'delete') { $pid = sanitize_text_field($_POST['dt']); }else{ $vars = array(); parse_str($_POST['dt'], $vars); if (is_array($vars)) { $vars = PFCleanArrayAttr('PFCleanFilters',$vars); } else { $vars = esc_attr($vars); } } } /* WPML Fix */ $lang_c = ''; if(isset($_POST['lang']) && $_POST['lang']!=''){ $lang_c = sanitize_text_field($_POST['lang']); } if(function_exists('icl_object_id')) { global $sitepress; if (isset($sitepress) && !empty($lang_c)) { $sitepress->switch_lang($lang_c); } } $current_user = wp_get_current_user(); $user_id = $current_user->ID; $returnval = $errorval = $pfreturn_url = $msg_output = $overlay_add = $sccval = ''; $icon_processout = 62; $setup3_pointposttype_pt1 = PFSAIssetControl('setup3_pointposttype_pt1','','pfitemfinder'); if ($formtype == 'delete') { /** *Start: Delete Item for PPP/Membership **/ if($user_id != 0){ $delete_postid = (is_numeric($pid))? $pid:''; if ($delete_postid != '') { $old_status_featured = false; $setup4_membersettings_paymentsystem = PFSAIssetControl('setup4_membersettings_paymentsystem','','1'); if ($setup4_membersettings_paymentsystem == 2) { /*Check if item user s item*/ global $wpdb; $result = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_author FROM $wpdb->posts WHERE ID = %s and post_author = %s and post_type = %s", $delete_postid, $user_id, $setup3_pointposttype_pt1 ) ); if (is_array($result) && count($result)>0) { if ($result[0]->ID == $delete_postid) { $delete_item_images = get_post_meta($delete_postid, 'webbupointfinder_item_images'); if (!empty($delete_item_images)) { foreach ($delete_item_images as $item_image) { wp_delete_attachment(esc_attr($item_image),true); } } wp_delete_attachment(get_post_thumbnail_id( $delete_postid ),true); $old_status_featured = get_post_meta( $delete_postid, 'webbupointfinder_item_featuredmarker', true ); wp_delete_post($delete_postid); $membership_user_activeorder = get_user_meta( $user_id, 'membership_user_activeorder', true ); /* - Creating record for process system. */ PFCreateProcessRecord( array( 'user_id' => $user_id, 'item_post_id' => $membership_user_activeorder, 'processname' => esc_html__('Item deleted by USER.','pointfindert2d'), 'membership' => 1 ) ); /* - Create a record for payment system. */ $sccval .= esc_html__('Item successfully deleted. Refreshing...','pointfindert2d'); } }else{ $icon_processout = 485; $errorval .= esc_html__('Wrong item ID or already deleted. Item can not delete.','pointfindert2d'); } /*Membership limits for item /featured limit*/ $membership_user_item_limit = get_user_meta( $user_id, 'membership_user_item_limit', true ); $membership_user_featureditem_limit = get_user_meta( $user_id, 'membership_user_featureditem_limit', true ); $membership_user_package_id = get_user_meta( $user_id, 'membership_user_package_id', true ); $packageinfox = pointfinder_membership_package_details_get($membership_user_package_id); if ($membership_user_item_limit == -1) { /* Do nothing... */ }else{ if ($membership_user_item_limit >= 0) { $membership_user_item_limit = $membership_user_item_limit + 1; if ($membership_user_item_limit <= $packageinfox['webbupointfinder_mp_itemnumber']) { update_user_meta( $user_id, 'membership_user_item_limit', $membership_user_item_limit); } } } if($old_status_featured != false && $old_status_featured != 0){ $membership_user_featureditem_limit = $membership_user_featureditem_limit + 1; if ($membership_user_featureditem_limit <= $packageinfox['webbupointfinder_mp_fitemnumber']) { update_user_meta( $user_id, 'membership_user_featureditem_limit', $membership_user_featureditem_limit); } } } else { /*Check if item user s item*/ global $wpdb; $result = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_author FROM $wpdb->posts WHERE ID = %s and post_author = %s and post_type = %s", $delete_postid, $user_id, $setup3_pointposttype_pt1 ) ); $result_id = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key = %s and meta_value = %s", 'pointfinder_order_itemid', $delete_postid ) ); $pointfinder_order_recurring = esc_attr(get_post_meta( $result_id, 'pointfinder_order_recurring', true )); if($pointfinder_order_recurring == 1){ $pointfinder_order_recurringid = esc_attr(get_post_meta( $result_id, 'pointfinder_order_recurringid', true )); PF_Cancel_recurring_payment( array( 'user_id' => $user_id, 'profile_id' => $pointfinder_order_recurringid, 'item_post_id' => $delete_postid, 'order_post_id' => $result_id, ) ); } if (is_array($result) && count($result)>0) { if ($result[0]->ID == $delete_postid) { $delete_item_images = get_post_meta($delete_postid, 'webbupointfinder_item_images'); if (!empty($delete_item_images)) { foreach ($delete_item_images as $item_image) { wp_delete_attachment(esc_attr($item_image),true); } } wp_delete_attachment(get_post_thumbnail_id( $delete_postid ),true); wp_delete_post($delete_postid); /* - Creating record for process system. */ PFCreateProcessRecord( array( 'user_id' => $user_id, 'item_post_id' => $delete_postid, 'processname' => esc_html__('Item deleted by USER.','pointfindert2d') ) ); /* - Create a record for payment system. */ $sccval .= esc_html__('Item successfully deleted. Refreshing...','pointfindert2d'); } }else{ $icon_processout = 485; $errorval .= esc_html__('Wrong item ID (Not your item!). Item can not delete.','pointfindert2d'); } } }else{ $icon_processout = 485; $errorval .= esc_html__('Wrong item ID.','pointfindert2d'); } }else{ $icon_processout = 485; $errorval .= esc_html__('Please login again to upload/edit item (Invalid UserID).','pointfindert2d'); } if (!empty($sccval)) { $msg_output .= $sccval; $overlay_add = ' pfoverlayapprove'; }elseif (!empty($errorval)) { $msg_output .= $errorval; } /** *End: Delete Item for PPP/Membership **/ } else { /** *Start: New/Edit Item Form Request **/ if(isset($_POST) && $_POST!='' && count($_POST)>0){ if($user_id != 0){ if($vars['action'] == 'pfget_edititem'){ if (isset($vars['edit_pid']) && !empty($vars['edit_pid'])) { $edit_postid = $vars['edit_pid']; global $wpdb; $result = $wpdb->get_results( $wpdb->prepare( " SELECT ID, post_author FROM $wpdb->posts WHERE ID = %s and post_author = %s and post_type = %s ", $edit_postid, $user_id, $setup3_pointposttype_pt1 ) ); if (is_array($result) && count($result)>0) { if ($result[0]->ID == $edit_postid) { $returnval = PFU_AddorUpdateRecord( array( 'post_id' => $edit_postid, 'order_post_id' => PFU_GetOrderID($edit_postid,1), 'order_title' => PFU_GetOrderID($edit_postid,0), 'vars' => $vars, 'user_id' => $user_id ) ); }else{ $icon_processout = 485; $errorval .= esc_html__('This is not your item.','pointfindert2d'); } }else{ $icon_processout = 485; $errorval .= esc_html__('Wrong Item ID','pointfindert2d'); } }else{ $icon_processout = 485; $errorval .= esc_html__('There is no item ID to edit.','pointfindert2d'); } }elseif ($vars['action'] == 'pfget_uploaditem') { $returnval = PFU_AddorUpdateRecord( array( 'post_id' => '', 'order_post_id' => '', 'order_title' => '', 'vars' => $vars, 'user_id' => $user_id ) ); } }else{ $icon_processout = 485; $errorval .= esc_html__('Please login again to upload/edit item (Invalid UserID).','pointfindert2d'); } } if (is_array($returnval) && !empty($returnval)) { if (isset($returnval['sccval'])) { $msg_output .= $returnval['sccval']; $overlay_add = ' pfoverlayapprove'; }elseif (isset($returnval['errorval'])) { $msg_output .= $returnval['errorval']; } }else{ $msg_output .= $errorval; } /** *End: New/Edit Item Form Request **/ } $setup4_membersettings_dashboard = PFSAIssetControl('setup4_membersettings_dashboard','',''); $setup4_membersettings_dashboard_link = get_permalink($setup4_membersettings_dashboard); $pfmenu_perout = PFPermalinkCheck(); $pfreturn_url = $setup4_membersettings_dashboard_link.$pfmenu_perout.'ua=myitems'; $output_html = ''; $output_html .= '<div class="golden-forms wrapper mini" style="height:200px">'; $output_html .= '<div id="pfmdcontainer-overlay" class="pftrwcontainer-overlay">'; $output_html .= "<div class='pf-overlay-close'><i class='pfadmicon-glyph-707'></i></div>"; $output_html .= "<div class='pfrevoverlaytext".$overlay_add."'><i class='pfadmicon-glyph-".$icon_processout."'></i><span>".$msg_output."</span></div>"; $output_html .= '</div>'; $output_html .= '</div>'; if (!empty($errorval)) { echo json_encode( array( 'process'=>false, 'processname'=>$processname, 'mes'=>$output_html, 'returnurl' => $pfreturn_url ) ); }else{ echo json_encode( array( 'process'=>true, 'processname'=>$processname, 'returnval'=>$returnval, 'mes'=>$output_html, 'returnurl' => $pfreturn_url ) ); } die(); } ?>
fedebalderas/esm_wordpress
wp-content/themes/pointfinder/admin/estatemanagement/includes/ajax/ajax-itemsystem.php
PHP
apache-2.0
12,874
// // 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. // using System; using System.Collections.Generic; using System.Text; using System.Net; using System.IO; using System.Threading; using NetworkCommsDotNet.DPSBase; using NetworkCommsDotNet.Tools; #if NETFX_CORE using NetworkCommsDotNet.Tools.XPlatformHelper; #else using System.Net.Sockets; #endif #if WINDOWS_PHONE || NETFX_CORE using Windows.Networking.Sockets; using Windows.Networking; using System.Runtime.InteropServices.WindowsRuntime; #endif namespace NetworkCommsDotNet.Connections.UDP { /// <summary> /// A connection object which utilises <see href="http://en.wikipedia.org/wiki/User_Datagram_Protocol">UDP</see> to communicate between peers. /// </summary> public sealed partial class UDPConnection : IPConnection { #if WINDOWS_PHONE || NETFX_CORE internal DatagramSocket socket; #else internal UdpClientWrapper udpClient; #endif /// <summary> /// Options associated with this UDPConnection /// </summary> public UDPOptions ConnectionUDPOptions { get; private set; } /// <summary> /// An isolated UDP connection will only accept incoming packets coming from a specific RemoteEndPoint. /// </summary> bool isIsolatedUDPConnection = false; /// <summary> /// Internal constructor for UDP connections /// </summary> /// <param name="connectionInfo"></param> /// <param name="defaultSendReceiveOptions"></param> /// <param name="level"></param> /// <param name="listenForIncomingPackets"></param> /// <param name="existingConnection"></param> internal UDPConnection(ConnectionInfo connectionInfo, SendReceiveOptions defaultSendReceiveOptions, UDPOptions level, bool listenForIncomingPackets, UDPConnection existingConnection = null) : base(connectionInfo, defaultSendReceiveOptions) { if (connectionInfo.ConnectionType != ConnectionType.UDP) throw new ArgumentException("Provided connectionType must be UDP.", "connectionInfo"); if (NetworkComms.LoggingEnabled) NetworkComms.Logger.Trace("Creating new UDPConnection with " + connectionInfo); if (connectionInfo.ApplicationLayerProtocol == ApplicationLayerProtocolStatus.Disabled && level != UDPOptions.None) throw new ArgumentException("If the application layer protocol has been disabled the provided UDPOptions can only be UDPOptions.None."); ConnectionUDPOptions = level; if (listenForIncomingPackets && existingConnection != null) throw new Exception("Unable to listen for incoming packets if an existing client has been provided. This is to prevent possible multiple accidently listens on the same client."); if (existingConnection == null) { if (connectionInfo.RemoteIPEndPoint.Address.Equals(IPAddress.Any) || connectionInfo.RemoteIPEndPoint.Address.Equals(IPAddress.IPv6Any)) { #if WINDOWS_PHONE || NETFX_CORE //We are creating an unbound endPoint, this is currently the rogue UDP sender and listeners only socket = new DatagramSocket(); if (listenForIncomingPackets) socket.MessageReceived += socket_MessageReceived; socket.BindEndpointAsync(new HostName(ConnectionInfo.LocalIPEndPoint.Address.ToString()), ConnectionInfo.LocalIPEndPoint.Port.ToString()).AsTask().Wait(); #else //We are creating an unbound endPoint, this is currently the rogue UDP sender and listeners only udpClient = new UdpClientWrapper(new UdpClient(ConnectionInfo.LocalIPEndPoint)); #endif } else { //If this is a specific connection we link to a default end point here isIsolatedUDPConnection = true; #if WINDOWS_PHONE || NETFX_CORE if (ConnectionInfo.LocalEndPoint == null || (ConnectionInfo.LocalIPEndPoint.Address == IPAddress.Any && connectionInfo.LocalIPEndPoint.Port == 0) || (ConnectionInfo.LocalIPEndPoint.Address == IPAddress.IPv6Any && connectionInfo.LocalIPEndPoint.Port == 0)) { socket = new DatagramSocket(); if (listenForIncomingPackets) socket.MessageReceived += socket_MessageReceived; socket.ConnectAsync(new HostName(ConnectionInfo.RemoteIPEndPoint.Address.ToString()), ConnectionInfo.RemoteIPEndPoint.Port.ToString()).AsTask().Wait(); } else { socket = new DatagramSocket(); if (listenForIncomingPackets) socket.MessageReceived += socket_MessageReceived; EndpointPair pair = new EndpointPair(new HostName(ConnectionInfo.LocalIPEndPoint.Address.ToString()), ConnectionInfo.LocalIPEndPoint.Port.ToString(), new HostName(ConnectionInfo.RemoteIPEndPoint.Address.ToString()), ConnectionInfo.RemoteIPEndPoint.Port.ToString()); socket.ConnectAsync(pair).AsTask().Wait(); } #else if (ConnectionInfo.LocalEndPoint == null) udpClient = new UdpClientWrapper(new UdpClient(ConnectionInfo.RemoteEndPoint.AddressFamily)); else udpClient = new UdpClientWrapper(new UdpClient(ConnectionInfo.LocalIPEndPoint)); //By calling connect we discard packets from anything other then the provided remoteEndPoint on our localEndPoint udpClient.Connect(ConnectionInfo.RemoteIPEndPoint); #endif } #if !WINDOWS_PHONE && !NETFX_CORE //NAT traversal does not work in .net 2.0 //Mono does not seem to have implemented AllowNatTraversal method and attempting the below method call will throw an exception //if (Type.GetType("Mono.Runtime") == null) //Allow NAT traversal by default for all udp clients // udpClientThreadSafe.AllowNatTraversal(true); if (listenForIncomingPackets) StartIncomingDataListen(); #endif } else { if (!existingConnection.ConnectionInfo.RemoteIPEndPoint.Address.Equals(IPAddress.Any)) throw new Exception("If an existing udpClient is provided it must be unbound to a specific remoteEndPoint"); #if WINDOWS_PHONE || NETFX_CORE //Using an exiting client allows us to send from the same port as for the provided existing connection this.socket = existingConnection.socket; #else //Using an exiting client allows us to send from the same port as for the provided existing connection this.udpClient = existingConnection.udpClient; #endif } IPEndPoint localEndPoint; #if WINDOWS_PHONE || NETFX_CORE localEndPoint = new IPEndPoint(IPAddress.Parse(socket.Information.LocalAddress.DisplayName.ToString()), int.Parse(socket.Information.LocalPort)); #else localEndPoint = udpClient.LocalIPEndPoint; #endif //We can update the localEndPoint so that it is correct if (!ConnectionInfo.LocalEndPoint.Equals(localEndPoint)) { //We should now be able to set the connectionInfo localEndPoint NetworkComms.UpdateConnectionReferenceByEndPoint(this, ConnectionInfo.RemoteIPEndPoint, localEndPoint); ConnectionInfo.UpdateLocalEndPointInfo(localEndPoint); } } /// <inheritdoc /> protected override void EstablishConnectionSpecific() { //If the application layer protocol is enabled and the UDP option is set if (ConnectionInfo.ApplicationLayerProtocol == ApplicationLayerProtocolStatus.Enabled && (ConnectionUDPOptions & UDPOptions.Handshake) == UDPOptions.Handshake) ConnectionHandshake(); else { //If there is no handshake we can now consider the connection established TriggerConnectionEstablishDelegates(); //Trigger any connection setup waits connectionSetupWait.Set(); } } /// <inheritdoc /> protected override void CloseConnectionSpecific(bool closeDueToError, int logLocation = 0) { #if WINDOWS_PHONE || NETFX_CORE //We only call close on the udpClient if this is a specific UDP connection or we are calling close from the parent UDP connection if (socket != null && (isIsolatedUDPConnection || (ConnectionInfo.RemoteIPEndPoint.Address.Equals(IPAddress.Any)))) socket.Dispose(); #else //We only call close on the udpClient if this is a specific UDP connection or we are calling close from the parent UDP connection if (udpClient != null && (isIsolatedUDPConnection || (ConnectionInfo.RemoteIPEndPoint.Address.Equals(IPAddress.Any)))) udpClient.CloseClient(); #endif } /// <summary> /// Send a packet to the specified ipEndPoint. This feature is unique to UDP because of its connectionless structure. /// </summary> /// <param name="packet">Packet to send</param> /// <param name="ipEndPoint">The target ipEndPoint</param> private void SendPacketSpecific<packetObjectType>(IPacket packet, IPEndPoint ipEndPoint) { #if FREETRIAL if (ipEndPoint.Address == IPAddress.Broadcast) throw new NotSupportedException("Unable to send UDP broadcast datagram using this version of NetworkComms.Net. Please purchase a commercial license from www.networkcomms.net which supports UDP broadcast datagrams."); #endif byte[] headerBytes = new byte[0]; if (ConnectionInfo.ApplicationLayerProtocol == ApplicationLayerProtocolStatus.Enabled) { long packetSequenceNumber; lock (sendLocker) { //Set packet sequence number inside sendLocker //Increment the global counter as well to ensure future connections with the same host can not create duplicates Interlocked.Increment(ref NetworkComms.totalPacketSendCount); packetSequenceNumber = packetSequenceCounter++; packet.PacketHeader.SetOption(PacketHeaderLongItems.PacketSequenceNumber, packetSequenceNumber); } headerBytes = packet.SerialiseHeader(NetworkComms.InternalFixedSendReceiveOptions); } else { if (packet.PacketHeader.PacketType != Enum.GetName(typeof(ReservedPacketType), ReservedPacketType.Unmanaged)) throw new UnexpectedPacketTypeException("Only 'Unmanaged' packet types can be used if the NetworkComms.Net application layer protocol is disabled."); if (packet.PacketData.Length == 0) throw new NotSupportedException("Sending a zero length array if the NetworkComms.Net application layer protocol is disabled is not supported."); } //We are limited in size for the isolated send if (headerBytes.Length + packet.PacketData.Length > maximumSingleDatagramSizeBytes) throw new CommunicationException("Attempted to send a UDP packet whose serialised size was " + (headerBytes.Length + packet.PacketData.Length).ToString() + " bytes. The maximum size for a single UDP send is " + maximumSingleDatagramSizeBytes.ToString() + ". Consider using a TCP connection to send this object."); if (NetworkComms.LoggingEnabled) NetworkComms.Logger.Debug("Sending a UDP packet of type '" + packet.PacketHeader.PacketType + "' from " + ConnectionInfo.LocalIPEndPoint.Address + ":" + ConnectionInfo.LocalIPEndPoint.Port.ToString() + " to " + ipEndPoint.Address + ":" + ipEndPoint.Port.ToString() + " containing " + headerBytes.Length.ToString() + " header bytes and " + packet.PacketData.Length.ToString() + " payload bytes."); //Prepare the single byte array to send byte[] udpDatagram; if (ConnectionInfo.ApplicationLayerProtocol == ApplicationLayerProtocolStatus.Enabled) { udpDatagram = packet.PacketData.ThreadSafeStream.ToArray(headerBytes.Length); //Copy the header bytes into the datagram Buffer.BlockCopy(headerBytes, 0, udpDatagram, 0, headerBytes.Length); } else udpDatagram = packet.PacketData.ThreadSafeStream.ToArray(); #if WINDOWS_PHONE || NETFX_CORE var getStreamTask = socket.GetOutputStreamAsync(new HostName(ipEndPoint.Address.ToString()), ipEndPoint.Port.ToString()).AsTask(); getStreamTask.Wait(); var outputStream = getStreamTask.Result; outputStream.WriteAsync(WindowsRuntimeBufferExtensions.AsBuffer(udpDatagram)).AsTask().Wait(); outputStream.FlushAsync().AsTask().Wait(); #else udpClient.Send(udpDatagram, udpDatagram.Length, ipEndPoint); #endif if (NetworkComms.LoggingEnabled) NetworkComms.Logger.Trace("Completed send of a UDP packet of type '" + packet.PacketHeader.PacketType + "' from " + ConnectionInfo.LocalIPEndPoint.Address + ":" + ConnectionInfo.LocalIPEndPoint.Port.ToString() + " to " + ipEndPoint.Address + ":" + ipEndPoint.Port.ToString() + "."); } /// <inheritdoc /> protected override double[] SendStreams(StreamTools.StreamSendWrapper[] streamsToSend, double maxSendTimePerKB, long totalBytesToSend) { #if FREETRIAL if (this.ConnectionInfo.RemoteEndPoint.Address == IPAddress.Broadcast) throw new NotSupportedException("Unable to send UDP broadcast datagram using this version of NetworkComms.Net. Please purchase a commercial license from www.networkcomms.net which supports UDP broadcast datagrams."); #endif if (ConnectionInfo.RemoteIPEndPoint.Address.Equals(IPAddress.Any)) throw new CommunicationException("Unable to send packet using this method as remoteEndPoint equals IPAddress.Any"); if (totalBytesToSend > maximumSingleDatagramSizeBytes) throw new CommunicationException("Attempted to send a UDP packet whose length is " + totalBytesToSend.ToString() + " bytes. The maximum size for a single UDP send is " + maximumSingleDatagramSizeBytes.ToString() + ". Consider using a TCP connection to send this object."); byte[] udpDatagram = new byte[totalBytesToSend]; MemoryStream udpDatagramStream = new MemoryStream(udpDatagram, 0, udpDatagram.Length, true); for (int i = 0; i < streamsToSend.Length; i++) { if (streamsToSend[i].Length > 0) { //Write each stream streamsToSend[i].ThreadSafeStream.CopyTo(udpDatagramStream, streamsToSend[i].Start, streamsToSend[i].Length, NetworkComms.SendBufferSizeBytes, maxSendTimePerKB, MinSendTimeoutMS); streamsToSend[i].ThreadSafeStream.Dispose(); } } DateTime startTime = DateTime.Now; #if WINDOWS_PHONE || NETFX_CORE var getStreamTask = socket.GetOutputStreamAsync(new HostName(ConnectionInfo.RemoteIPEndPoint.Address.ToString()), ConnectionInfo.RemoteIPEndPoint.Port.ToString()).AsTask(); getStreamTask.Wait(); var outputStream = getStreamTask.Result; outputStream.WriteAsync(WindowsRuntimeBufferExtensions.AsBuffer(udpDatagram)).AsTask().Wait(); outputStream.FlushAsync().AsTask().Wait(); #else udpClient.Send(udpDatagram, udpDatagram.Length, ConnectionInfo.RemoteIPEndPoint); #endif udpDatagramStream.Dispose(); //Calculate timings based on fractional byte length double[] timings = new double[streamsToSend.Length]; double elapsedMS = (DateTime.Now - startTime).TotalMilliseconds; for (int i = 0; i < streamsToSend.Length; i++) timings[i] = elapsedMS * (streamsToSend[i].Length / (double)totalBytesToSend); return timings; } /// <inheritdoc /> protected override void StartIncomingDataListen() { #if WINDOWS_PHONE || NETFX_CORE throw new NotImplementedException("Not needed for UDP connections on Windows Phone 8"); #else if (NetworkComms.ConnectionListenModeUseSync) { if (incomingDataListenThread == null) { incomingDataListenThread = new Thread(IncomingUDPPacketWorker); incomingDataListenThread.Priority = NetworkComms.timeCriticalThreadPriority; incomingDataListenThread.Name = "UDP_IncomingDataListener"; incomingDataListenThread.IsBackground = true; incomingDataListenThread.Start(); } } else { if (asyncListenStarted) throw new ConnectionSetupException("Async listen already started. Why has this been called twice?."); udpClient.BeginReceive(new AsyncCallback(IncomingUDPPacketHandler), udpClient); asyncListenStarted = true; } #endif } #if WINDOWS_PHONE || NETFX_CORE void socket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args) { try { var stream = args.GetDataStream().AsStreamForRead(); var dataLength = args.GetDataReader().UnconsumedBufferLength; byte[] receivedBytes = new byte[dataLength]; using (MemoryStream mem = new MemoryStream(receivedBytes)) stream.CopyTo(mem); //Received data after comms shutdown initiated. We should just close the connection if (NetworkComms.commsShutdown) CloseConnection(false, -15); stream = null; if (NetworkComms.LoggingEnabled) NetworkComms.Logger.Trace("Received " + receivedBytes.Length + " bytes via UDP from " + args.RemoteAddress + ":" + args.RemotePort + "."); UDPConnection connection; HandshakeUDPDatagram possibleHandshakeUDPDatagram = new HandshakeUDPDatagram(receivedBytes); if (isIsolatedUDPConnection) //This connection was created for a specific remoteEndPoint so we can handle the data internally connection = this; else { IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse(args.RemoteAddress.DisplayName.ToString()), int.Parse(args.RemotePort)); IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse(sender.Information.LocalAddress.DisplayName.ToString()), int.Parse(sender.Information.LocalPort)); ConnectionInfo desiredConnection = new ConnectionInfo(ConnectionType.UDP, remoteEndPoint, localEndPoint, ConnectionInfo.ApplicationLayerProtocol, ConnectionInfo.ConnectionListener); try { //Look for an existing connection, if one does not exist we will create it //This ensures that all further processing knows about the correct endPoint connection = GetConnection(desiredConnection, ConnectionUDPOptions, ConnectionDefaultSendReceiveOptions, false, this, possibleHandshakeUDPDatagram); } catch (ConnectionShutdownException) { if ((ConnectionUDPOptions & UDPOptions.Handshake) == UDPOptions.Handshake) { if (NetworkComms.LoggingEnabled) NetworkComms.Logger.Trace("Attempted to get connection " + desiredConnection + " but this caused a ConnectionShutdownException. Exception caught and ignored as should only happen if the connection was closed shortly after being created."); connection = null; } else throw; } } if (connection != null && !possibleHandshakeUDPDatagram.DatagramHandled) { //We pass the data off to the specific connection //Lock on the packetbuilder locker as we may receive UDP packets in parallel from this host lock (connection.packetBuilder.Locker) { connection.packetBuilder.AddPartialPacket(receivedBytes.Length, receivedBytes); if (connection.packetBuilder.TotalBytesCached > 0) connection.IncomingPacketHandleHandOff(connection.packetBuilder); if (connection.packetBuilder.TotalPartialPacketCount > 0) LogTools.LogException(new Exception("Packet builder had " + connection.packetBuilder.TotalBytesCached + " bytes remaining after a call to IncomingPacketHandleHandOff with connection " + connection.ConnectionInfo + ". Until sequenced packets are implemented this indicates a possible error."), "UDPConnectionError"); } } } //On any error here we close the connection catch (NullReferenceException) { CloseConnection(true, 25); } catch (ArgumentNullException) { CloseConnection(true, 38); } catch (IOException) { CloseConnection(true, 26); } catch (ObjectDisposedException) { CloseConnection(true, 27); } catch (SocketException) { //Receive may throw a SocketException ErrorCode=10054 after attempting to send a datagram to an unreachable target. //We will try to get around this by ignoring the ICMP packet causing these problems on client creation CloseConnection(true, 28); } catch (InvalidOperationException) { CloseConnection(true, 29); } catch (ConnectionSetupException) { //Can occur if data is received as comms is being shutdown. //Method will attempt to create new connection which will throw ConnectionSetupException. CloseConnection(true, 50); } catch (Exception ex) { LogTools.LogException(ex, "Error_UDPConnectionIncomingPacketHandler"); CloseConnection(true, 30); } } #else /// <summary> /// Incoming data listen async method /// </summary> /// <param name="ar">Call back state data</param> private void IncomingUDPPacketHandler(IAsyncResult ar) { try { UdpClientWrapper client = (UdpClientWrapper)ar.AsyncState; IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.None, 0); byte[] receivedBytes = client.EndReceive(ar, ref remoteEndPoint); //Received data after comms shutdown initiated. We should just close the connection if (NetworkComms.commsShutdown) CloseConnection(false, -13); if (NetworkComms.LoggingEnabled) NetworkComms.Logger.Trace("Received " + receivedBytes.Length.ToString() + " bytes via UDP from " + remoteEndPoint.Address + ":" + remoteEndPoint.Port.ToString() + "."); UDPConnection connection; HandshakeUDPDatagram possibleHandshakeUDPDatagram = new HandshakeUDPDatagram(receivedBytes); if (isIsolatedUDPConnection) //This connection was created for a specific remoteEndPoint so we can handle the data internally connection = this; else { ConnectionInfo desiredConnection = new ConnectionInfo(ConnectionType.UDP, remoteEndPoint, udpClient.LocalIPEndPoint, ConnectionInfo.ApplicationLayerProtocol, ConnectionInfo.ConnectionListener); try { //Look for an existing connection, if one does not exist we will create it //This ensures that all further processing knows about the correct endPoint connection = GetConnection(desiredConnection, ConnectionUDPOptions, ConnectionDefaultSendReceiveOptions, false, this, possibleHandshakeUDPDatagram); } catch (ConnectionShutdownException) { if ((ConnectionUDPOptions & UDPOptions.Handshake) == UDPOptions.Handshake) { if (NetworkComms.LoggingEnabled) NetworkComms.Logger.Trace("Attempted to get connection " + desiredConnection + " but this caused a ConnectionShutdownException. Exception caught and ignored as should only happen if the connection was closed shortly after being created."); connection = null; } else throw; } } if (connection != null && !possibleHandshakeUDPDatagram.DatagramHandled) { //We pass the data off to the specific connection //Lock on the packetbuilder locker as we may receive UDP packets in parallel from this host lock (connection.packetBuilder.Locker) { if (NetworkComms.LoggingEnabled) NetworkComms.Logger.Trace(" ... " + receivedBytes.Length.ToString() + " bytes added to packetBuilder for " + connection.ConnectionInfo + ". Cached " + connection.packetBuilder.TotalBytesCached.ToString() + " bytes, expecting " + connection.packetBuilder.TotalBytesExpected.ToString() + " bytes."); connection.packetBuilder.AddPartialPacket(receivedBytes.Length, receivedBytes); if (connection.packetBuilder.TotalBytesCached > 0) connection.IncomingPacketHandleHandOff(connection.packetBuilder); if (connection.packetBuilder.TotalPartialPacketCount > 0) LogTools.LogException(new Exception("Packet builder had " + connection.packetBuilder.TotalBytesCached + " bytes remaining after a call to IncomingPacketHandleHandOff with connection " + connection.ConnectionInfo + ". Until sequenced packets are implemented this indicates a possible error."), "UDPConnectionError"); } } client.BeginReceive(new AsyncCallback(IncomingUDPPacketHandler), client); } //On any error here we close the connection catch (NullReferenceException) { CloseConnection(true, 25); } catch (ArgumentNullException) { CloseConnection(true, 36); } catch (IOException) { CloseConnection(true, 26); } catch (ObjectDisposedException) { CloseConnection(true, 27); } catch (SocketException) { //Receive may throw a SocketException ErrorCode=10054 after attempting to send a datagram to an unreachable target. //We will try to get around this by ignoring the ICMP packet causing these problems on client creation CloseConnection(true, 28); } catch (InvalidOperationException) { CloseConnection(true, 29); } catch (ConnectionSetupException) { //Can occur if data is received as comms is being shutdown. //Method will attempt to create new connection which will throw ConnectionSetupException. CloseConnection(true, 50); } catch (Exception ex) { LogTools.LogException(ex, "Error_UDPConnectionIncomingPacketHandler"); CloseConnection(true, 30); } } /// <summary> /// Incoming data listen sync method /// </summary> private void IncomingUDPPacketWorker() { try { while (true) { if (ConnectionInfo.ConnectionState == ConnectionState.Shutdown) break; IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.None, 0); byte[] receivedBytes = udpClient.Receive(ref remoteEndPoint); //Received data after comms shutdown initiated. We should just close the connection if (NetworkComms.commsShutdown) CloseConnection(false, -14); if (NetworkComms.LoggingEnabled) NetworkComms.Logger.Trace("Received " + receivedBytes.Length.ToString() + " bytes via UDP from " + remoteEndPoint.Address + ":" + remoteEndPoint.Port.ToString() + "."); UDPConnection connection; HandshakeUDPDatagram possibleHandshakeUDPDatagram = new HandshakeUDPDatagram(receivedBytes); if (isIsolatedUDPConnection) //This connection was created for a specific remoteEndPoint so we can handle the data internally connection = this; else { ConnectionInfo desiredConnection = new ConnectionInfo(ConnectionType.UDP, remoteEndPoint, udpClient.LocalIPEndPoint, ConnectionInfo.ApplicationLayerProtocol, ConnectionInfo.ConnectionListener); try { //Look for an existing connection, if one does not exist we will create it //This ensures that all further processing knows about the correct endPoint connection = GetConnection(desiredConnection, ConnectionUDPOptions, ConnectionDefaultSendReceiveOptions, false, this, possibleHandshakeUDPDatagram); } catch (ConnectionShutdownException) { if ((ConnectionUDPOptions & UDPOptions.Handshake) == UDPOptions.Handshake) { if (NetworkComms.LoggingEnabled) NetworkComms.Logger.Trace("Attempted to get connection " + desiredConnection + " but this caused a ConnectionShutdownException. Exception caught and ignored as should only happen if the connection was closed shortly after being created."); connection = null; } else throw; } } if (connection != null && !possibleHandshakeUDPDatagram.DatagramHandled) { //We pass the data off to the specific connection //Lock on the packetbuilder locker as we may receive UDP packets in parallel from this host lock (connection.packetBuilder.Locker) { if (NetworkComms.LoggingEnabled) NetworkComms.Logger.Trace(" ... " + receivedBytes.Length.ToString() + " bytes added to packetBuilder for " + connection.ConnectionInfo + ". Cached " + connection.packetBuilder.TotalBytesCached.ToString() + " bytes, expecting " + connection.packetBuilder.TotalBytesExpected.ToString() + " bytes."); connection.packetBuilder.AddPartialPacket(receivedBytes.Length, receivedBytes); if (connection.packetBuilder.TotalBytesCached > 0) connection.IncomingPacketHandleHandOff(connection.packetBuilder); if (connection.packetBuilder.TotalPartialPacketCount > 0) LogTools.LogException(new Exception("Packet builder had " + connection.packetBuilder.TotalBytesCached + " bytes remaining after a call to IncomingPacketHandleHandOff with connection " + connection.ConnectionInfo + ". Until sequenced packets are implemented this indicates a possible error."), "UDPConnectionError"); } } } } //On any error here we close the connection catch (NullReferenceException) { CloseConnection(true, 20); } catch (ArgumentNullException) { CloseConnection(true, 37); } catch (IOException) { CloseConnection(true, 21); } catch (ObjectDisposedException) { CloseConnection(true, 22); } catch (SocketException) { //Receive may throw a SocketException ErrorCode=10054 after attempting to send a datagram to an unreachable target. //We will try to get around this by ignoring the ICMP packet causing these problems on client creation CloseConnection(true, 23); } catch (InvalidOperationException) { CloseConnection(true, 24); } catch (ConnectionSetupException) { //Can occur if data is received as comms is being shutdown. //Method will attempt to create new connection which will throw ConnectionSetupException. CloseConnection(true, 50); } catch (Exception ex) { LogTools.LogException(ex, "Error_UDPConnectionIncomingPacketHandler"); CloseConnection(true, 41); } //Clear the listen thread object because the thread is about to end incomingDataListenThread = null; if (NetworkComms.LoggingEnabled) NetworkComms.Logger.Trace("Incoming data listen thread ending for " + ConnectionInfo); } #endif } }
MarcFletcher/NetworkComms.Net
NetworkCommsDotNet/Connection/UDP/UDPConnection.cs
C#
apache-2.0
36,508
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.cognitoidp.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.cognitoidp.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * AnalyticsMetadataType JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class AnalyticsMetadataTypeJsonUnmarshaller implements Unmarshaller<AnalyticsMetadataType, JsonUnmarshallerContext> { public AnalyticsMetadataType unmarshall(JsonUnmarshallerContext context) throws Exception { AnalyticsMetadataType analyticsMetadataType = new AnalyticsMetadataType(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return null; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("AnalyticsEndpointId", targetDepth)) { context.nextToken(); analyticsMetadataType.setAnalyticsEndpointId(context.getUnmarshaller(String.class).unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return analyticsMetadataType; } private static AnalyticsMetadataTypeJsonUnmarshaller instance; public static AnalyticsMetadataTypeJsonUnmarshaller getInstance() { if (instance == null) instance = new AnalyticsMetadataTypeJsonUnmarshaller(); return instance; } }
jentfoo/aws-sdk-java
aws-java-sdk-cognitoidp/src/main/java/com/amazonaws/services/cognitoidp/model/transform/AnalyticsMetadataTypeJsonUnmarshaller.java
Java
apache-2.0
2,836
module Serf.Event where import Serf.Member import Control.Applicative import Control.Monad.IO.Class import System.Environment import System.Exit import System.IO import Text.Parsec type SerfError = String data SerfEvent = MemberJoin Member | MemberLeave Member | MemberFailed Member | MemberUpdate Member | MemberReap Member | User | Query | Unknown String getSerfEvent :: IO (Either SerfError SerfEvent) getSerfEvent = getEnv "SERF_EVENT" >>= fromString where fromString :: String -> IO (Either SerfError SerfEvent) fromString "member-join" = readMemberEvent MemberJoin fromString "member-leave" = readMemberEvent MemberLeave fromString "member-failed" = readMemberEvent MemberFailed fromString "member-update" = readMemberEvent MemberUpdate fromString "member-reap" = readMemberEvent MemberReap fromString "user" = return $ Right User fromString "query" = return $ Right Query fromString unk = return . Right $ Unknown unk readMemberEvent :: (Member -> SerfEvent) -> IO (Either SerfError SerfEvent) readMemberEvent f = addMember f <$> readMember addMember :: (Member -> SerfEvent) -> Either ParseError Member -> Either SerfError SerfEvent addMember _ (Left err) = Left $ show err addMember f (Right m) = Right $ f m readMember :: IO (Either ParseError Member) readMember = memberFromString <$> getLine isMemberEvent :: SerfEvent -> Bool isMemberEvent (MemberJoin _) = True isMemberEvent (MemberLeave _) = True isMemberEvent (MemberFailed _) = True isMemberEvent (MemberUpdate _) = True isMemberEvent (MemberReap _) = True isMemberEvent _ = False type EventHandler m = SerfEvent -> m () handleEventWith :: MonadIO m => EventHandler m -> m () handleEventWith hdlr = do evt <- liftIO getSerfEvent case evt of Left err -> liftIO $ hPutStrLn stderr err >> exitFailure Right ev -> hdlr ev
lstephen/box
src/main/ansible/roles/serf/files/Serf/Event.hs
Haskell
apache-2.0
2,110
/* 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 kubelet import ( "bytes" "errors" "fmt" "io" "io/ioutil" "net" "net/http" "os" "path" "reflect" "sort" "strings" "testing" "time" cadvisorApi "github.com/google/cadvisor/info/v1" cadvisorApiv2 "github.com/google/cadvisor/info/v2" "k8s.io/kubernetes/pkg/api" apierrors "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/resource" "k8s.io/kubernetes/pkg/api/testapi" "k8s.io/kubernetes/pkg/capabilities" "k8s.io/kubernetes/pkg/client/unversioned/record" "k8s.io/kubernetes/pkg/client/unversioned/testclient" "k8s.io/kubernetes/pkg/kubelet/cadvisor" "k8s.io/kubernetes/pkg/kubelet/container" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" "k8s.io/kubernetes/pkg/kubelet/network" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util" "k8s.io/kubernetes/pkg/util/bandwidth" "k8s.io/kubernetes/pkg/version" "k8s.io/kubernetes/pkg/volume" _ "k8s.io/kubernetes/pkg/volume/host_path" ) func init() { api.ForTesting_ReferencesAllowBlankSelfLinks = true util.ReallyCrash = true } const testKubeletHostname = "127.0.0.1" type fakeHTTP struct { url string err error } func (f *fakeHTTP) Get(url string) (*http.Response, error) { f.url = url return nil, f.err } type TestKubelet struct { kubelet *Kubelet fakeRuntime *kubecontainer.FakeRuntime fakeCadvisor *cadvisor.Mock fakeKubeClient *testclient.Fake fakeMirrorClient *fakeMirrorClient } func newTestKubelet(t *testing.T) *TestKubelet { fakeRuntime := &kubecontainer.FakeRuntime{} fakeRuntime.VersionInfo = "1.15" fakeRecorder := &record.FakeRecorder{} fakeKubeClient := &testclient.Fake{} kubelet := &Kubelet{} kubelet.kubeClient = fakeKubeClient kubelet.os = kubecontainer.FakeOS{} kubelet.hostname = testKubeletHostname kubelet.nodeName = testKubeletHostname kubelet.runtimeUpThreshold = maxWaitForContainerRuntime kubelet.networkPlugin, _ = network.InitNetworkPlugin([]network.NetworkPlugin{}, "", network.NewFakeHost(nil)) if tempDir, err := ioutil.TempDir("/tmp", "kubelet_test."); err != nil { t.Fatalf("can't make a temp rootdir: %v", err) } else { kubelet.rootDirectory = tempDir } if err := os.MkdirAll(kubelet.rootDirectory, 0750); err != nil { t.Fatalf("can't mkdir(%q): %v", kubelet.rootDirectory, err) } kubelet.sourcesReady = func() bool { return true } kubelet.masterServiceNamespace = api.NamespaceDefault kubelet.serviceLister = testServiceLister{} kubelet.nodeLister = testNodeLister{} kubelet.readinessManager = kubecontainer.NewReadinessManager() kubelet.recorder = fakeRecorder kubelet.statusManager = newStatusManager(fakeKubeClient) if err := kubelet.setupDataDirs(); err != nil { t.Fatalf("can't initialize kubelet data dirs: %v", err) } mockCadvisor := &cadvisor.Mock{} kubelet.cadvisor = mockCadvisor podManager, fakeMirrorClient := newFakePodManager() kubelet.podManager = podManager kubelet.containerRefManager = kubecontainer.NewRefManager() diskSpaceManager, err := newDiskSpaceManager(mockCadvisor, DiskSpacePolicy{}) if err != nil { t.Fatalf("can't initialize disk space manager: %v", err) } kubelet.diskSpaceManager = diskSpaceManager kubelet.containerRuntime = fakeRuntime kubelet.runtimeCache = kubecontainer.NewFakeRuntimeCache(kubelet.containerRuntime) kubelet.podWorkers = &fakePodWorkers{ syncPodFn: kubelet.syncPod, runtimeCache: kubelet.runtimeCache, t: t, } kubelet.volumeManager = newVolumeManager() kubelet.containerManager, _ = newContainerManager(mockCadvisor, "", "", "") kubelet.networkConfigured = true fakeClock := &util.FakeClock{Time: time.Now()} kubelet.backOff = util.NewBackOff(time.Second, time.Minute) kubelet.backOff.Clock = fakeClock kubelet.podKillingCh = make(chan *kubecontainer.Pod, 20) return &TestKubelet{kubelet, fakeRuntime, mockCadvisor, fakeKubeClient, fakeMirrorClient} } func newTestPods(count int) []*api.Pod { pods := make([]*api.Pod, count) for i := 0; i < count; i++ { pods[i] = &api.Pod{ ObjectMeta: api.ObjectMeta{ Name: fmt.Sprintf("pod%d", i), }, } } return pods } func TestKubeletDirs(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet root := kubelet.rootDirectory var exp, got string got = kubelet.getPodsDir() exp = path.Join(root, "pods") if got != exp { t.Errorf("expected %q', got %q", exp, got) } got = kubelet.getPluginsDir() exp = path.Join(root, "plugins") if got != exp { t.Errorf("expected %q', got %q", exp, got) } got = kubelet.getPluginDir("foobar") exp = path.Join(root, "plugins/foobar") if got != exp { t.Errorf("expected %q', got %q", exp, got) } got = kubelet.getPodDir("abc123") exp = path.Join(root, "pods/abc123") if got != exp { t.Errorf("expected %q', got %q", exp, got) } got = kubelet.getPodVolumesDir("abc123") exp = path.Join(root, "pods/abc123/volumes") if got != exp { t.Errorf("expected %q', got %q", exp, got) } got = kubelet.getPodVolumeDir("abc123", "plugin", "foobar") exp = path.Join(root, "pods/abc123/volumes/plugin/foobar") if got != exp { t.Errorf("expected %q', got %q", exp, got) } got = kubelet.getPodPluginsDir("abc123") exp = path.Join(root, "pods/abc123/plugins") if got != exp { t.Errorf("expected %q', got %q", exp, got) } got = kubelet.getPodPluginDir("abc123", "foobar") exp = path.Join(root, "pods/abc123/plugins/foobar") if got != exp { t.Errorf("expected %q', got %q", exp, got) } got = kubelet.getPodContainerDir("abc123", "def456") exp = path.Join(root, "pods/abc123/containers/def456") if got != exp { t.Errorf("expected %q', got %q", exp, got) } } func TestKubeletDirsCompat(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet root := kubelet.rootDirectory if err := os.MkdirAll(root, 0750); err != nil { t.Fatalf("can't mkdir(%q): %s", root, err) } var exp, got string // Old-style pod dir. if err := os.MkdirAll(fmt.Sprintf("%s/oldpod", root), 0750); err != nil { t.Fatalf("can't mkdir(%q): %s", root, err) } // New-style pod dir. if err := os.MkdirAll(fmt.Sprintf("%s/pods/newpod", root), 0750); err != nil { t.Fatalf("can't mkdir(%q): %s", root, err) } // Both-style pod dir. if err := os.MkdirAll(fmt.Sprintf("%s/bothpod", root), 0750); err != nil { t.Fatalf("can't mkdir(%q): %s", root, err) } if err := os.MkdirAll(fmt.Sprintf("%s/pods/bothpod", root), 0750); err != nil { t.Fatalf("can't mkdir(%q): %s", root, err) } got = kubelet.getPodDir("oldpod") exp = path.Join(root, "oldpod") if got != exp { t.Errorf("expected %q', got %q", exp, got) } got = kubelet.getPodDir("newpod") exp = path.Join(root, "pods/newpod") if got != exp { t.Errorf("expected %q', got %q", exp, got) } got = kubelet.getPodDir("bothpod") exp = path.Join(root, "pods/bothpod") if got != exp { t.Errorf("expected %q', got %q", exp, got) } got = kubelet.getPodDir("neitherpod") exp = path.Join(root, "pods/neitherpod") if got != exp { t.Errorf("expected %q', got %q", exp, got) } root = kubelet.getPodDir("newpod") // Old-style container dir. if err := os.MkdirAll(fmt.Sprintf("%s/oldctr", root), 0750); err != nil { t.Fatalf("can't mkdir(%q): %s", root, err) } // New-style container dir. if err := os.MkdirAll(fmt.Sprintf("%s/containers/newctr", root), 0750); err != nil { t.Fatalf("can't mkdir(%q): %s", root, err) } // Both-style container dir. if err := os.MkdirAll(fmt.Sprintf("%s/bothctr", root), 0750); err != nil { t.Fatalf("can't mkdir(%q): %s", root, err) } if err := os.MkdirAll(fmt.Sprintf("%s/containers/bothctr", root), 0750); err != nil { t.Fatalf("can't mkdir(%q): %s", root, err) } got = kubelet.getPodContainerDir("newpod", "oldctr") exp = path.Join(root, "oldctr") if got != exp { t.Errorf("expected %q', got %q", exp, got) } got = kubelet.getPodContainerDir("newpod", "newctr") exp = path.Join(root, "containers/newctr") if got != exp { t.Errorf("expected %q', got %q", exp, got) } got = kubelet.getPodContainerDir("newpod", "bothctr") exp = path.Join(root, "containers/bothctr") if got != exp { t.Errorf("expected %q', got %q", exp, got) } got = kubelet.getPodContainerDir("newpod", "neitherctr") exp = path.Join(root, "containers/neitherctr") if got != exp { t.Errorf("expected %q', got %q", exp, got) } } var emptyPodUIDs map[types.UID]SyncPodType func TestSyncLoopTimeUpdate(t *testing.T) { testKubelet := newTestKubelet(t) testKubelet.fakeCadvisor.On("MachineInfo").Return(&cadvisorApi.MachineInfo{}, nil) kubelet := testKubelet.kubelet loopTime1 := kubelet.LatestLoopEntryTime() if !loopTime1.IsZero() { t.Errorf("Unexpected sync loop time: %s, expected 0", loopTime1) } kubelet.syncLoopIteration(make(chan PodUpdate), kubelet) loopTime2 := kubelet.LatestLoopEntryTime() if loopTime2.IsZero() { t.Errorf("Unexpected sync loop time: 0, expected non-zero value.") } kubelet.syncLoopIteration(make(chan PodUpdate), kubelet) loopTime3 := kubelet.LatestLoopEntryTime() if !loopTime3.After(loopTime1) { t.Errorf("Sync Loop Time was not updated correctly. Second update timestamp should be greater than first update timestamp") } } func TestSyncLoopAbort(t *testing.T) { testKubelet := newTestKubelet(t) testKubelet.fakeCadvisor.On("MachineInfo").Return(&cadvisorApi.MachineInfo{}, nil) kubelet := testKubelet.kubelet kubelet.lastTimestampRuntimeUp = time.Now() kubelet.networkConfigured = true ch := make(chan PodUpdate) close(ch) // sanity check (also prevent this test from hanging in the next step) ok := kubelet.syncLoopIteration(ch, kubelet) if ok { t.Fatalf("expected syncLoopIteration to return !ok since update chan was closed") } // this should terminate immediately; if it hangs then the syncLoopIteration isn't aborting properly kubelet.syncLoop(ch, kubelet) } func TestSyncPodsStartPod(t *testing.T) { testKubelet := newTestKubelet(t) testKubelet.fakeCadvisor.On("MachineInfo").Return(&cadvisorApi.MachineInfo{}, nil) testKubelet.fakeCadvisor.On("DockerImagesFsInfo").Return(cadvisorApiv2.FsInfo{}, nil) testKubelet.fakeCadvisor.On("RootFsInfo").Return(cadvisorApiv2.FsInfo{}, nil) kubelet := testKubelet.kubelet fakeRuntime := testKubelet.fakeRuntime pods := []*api.Pod{ { ObjectMeta: api.ObjectMeta{ UID: "12345678", Name: "foo", Namespace: "new", }, Spec: api.PodSpec{ Containers: []api.Container{ {Name: "bar"}, }, }, }, } kubelet.podManager.SetPods(pods) kubelet.HandlePodSyncs(pods) fakeRuntime.AssertStartedPods([]string{string(pods[0].UID)}) } func TestSyncPodsDeletesWhenSourcesAreReady(t *testing.T) { ready := false testKubelet := newTestKubelet(t) fakeRuntime := testKubelet.fakeRuntime testKubelet.fakeCadvisor.On("MachineInfo").Return(&cadvisorApi.MachineInfo{}, nil) testKubelet.fakeCadvisor.On("DockerImagesFsInfo").Return(cadvisorApiv2.FsInfo{}, nil) testKubelet.fakeCadvisor.On("RootFsInfo").Return(cadvisorApiv2.FsInfo{}, nil) kubelet := testKubelet.kubelet kubelet.sourcesReady = func() bool { return ready } fakeRuntime.PodList = []*kubecontainer.Pod{ { ID: "12345678", Name: "foo", Namespace: "new", Containers: []*kubecontainer.Container{ {Name: "bar"}, }, }, } kubelet.HandlePodCleanups() // Sources are not ready yet. Don't remove any pods. fakeRuntime.AssertKilledPods([]string{}) ready = true kubelet.HandlePodCleanups() // Sources are ready. Remove unwanted pods. fakeRuntime.AssertKilledPods([]string{"12345678"}) } func TestMountExternalVolumes(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet kubelet.volumePluginMgr.InitPlugins([]volume.VolumePlugin{&volume.FakeVolumePlugin{PluginName: "fake", Host: nil}}, &volumeHost{kubelet}) pod := api.Pod{ ObjectMeta: api.ObjectMeta{ UID: "12345678", Name: "foo", Namespace: "test", }, Spec: api.PodSpec{ Volumes: []api.Volume{ { Name: "vol1", VolumeSource: api.VolumeSource{}, }, }, }, } podVolumes, err := kubelet.mountExternalVolumes(&pod) if err != nil { t.Errorf("Expected success: %v", err) } expectedPodVolumes := []string{"vol1"} if len(expectedPodVolumes) != len(podVolumes) { t.Errorf("Unexpected volumes. Expected %#v got %#v. Manifest was: %#v", expectedPodVolumes, podVolumes, pod) } for _, name := range expectedPodVolumes { if _, ok := podVolumes[name]; !ok { t.Errorf("api.Pod volumes map is missing key: %s. %#v", name, podVolumes) } } } func TestGetPodVolumesFromDisk(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet plug := &volume.FakeVolumePlugin{PluginName: "fake", Host: nil} kubelet.volumePluginMgr.InitPlugins([]volume.VolumePlugin{plug}, &volumeHost{kubelet}) volsOnDisk := []struct { podUID types.UID volName string }{ {"pod1", "vol1"}, {"pod1", "vol2"}, {"pod2", "vol1"}, } expectedPaths := []string{} for i := range volsOnDisk { fv := volume.FakeVolume{PodUID: volsOnDisk[i].podUID, VolName: volsOnDisk[i].volName, Plugin: plug} fv.SetUp() expectedPaths = append(expectedPaths, fv.GetPath()) } volumesFound := kubelet.getPodVolumesFromDisk() if len(volumesFound) != len(expectedPaths) { t.Errorf("Expected to find %d cleaners, got %d", len(expectedPaths), len(volumesFound)) } for _, ep := range expectedPaths { found := false for _, cl := range volumesFound { if ep == cl.GetPath() { found = true break } } if !found { t.Errorf("Could not find a volume with path %s", ep) } } } type stubVolume struct { path string } func (f *stubVolume) GetPath() string { return f.path } func TestMakeVolumeMounts(t *testing.T) { container := api.Container{ VolumeMounts: []api.VolumeMount{ { MountPath: "/mnt/path", Name: "disk", ReadOnly: false, }, { MountPath: "/mnt/path3", Name: "disk", ReadOnly: true, }, { MountPath: "/mnt/path4", Name: "disk4", ReadOnly: false, }, { MountPath: "/mnt/path5", Name: "disk5", ReadOnly: false, }, }, } podVolumes := kubecontainer.VolumeMap{ "disk": &stubVolume{"/mnt/disk"}, "disk4": &stubVolume{"/mnt/host"}, "disk5": &stubVolume{"/var/lib/kubelet/podID/volumes/empty/disk5"}, } mounts := makeMounts(&container, podVolumes) expectedMounts := []kubecontainer.Mount{ { "disk", "/mnt/path", "/mnt/disk", false, }, { "disk", "/mnt/path3", "/mnt/disk", true, }, { "disk4", "/mnt/path4", "/mnt/host", false, }, { "disk5", "/mnt/path5", "/var/lib/kubelet/podID/volumes/empty/disk5", false, }, } if !reflect.DeepEqual(mounts, expectedMounts) { t.Errorf("Unexpected mounts: Expected %#v got %#v. Container was: %#v", expectedMounts, mounts, container) } } func TestGetContainerInfo(t *testing.T) { containerID := "ab2cdf" containerPath := fmt.Sprintf("/docker/%v", containerID) containerInfo := cadvisorApi.ContainerInfo{ ContainerReference: cadvisorApi.ContainerReference{ Name: containerPath, }, } testKubelet := newTestKubelet(t) fakeRuntime := testKubelet.fakeRuntime kubelet := testKubelet.kubelet cadvisorReq := &cadvisorApi.ContainerInfoRequest{} mockCadvisor := testKubelet.fakeCadvisor mockCadvisor.On("DockerContainer", containerID, cadvisorReq).Return(containerInfo, nil) fakeRuntime.PodList = []*kubecontainer.Pod{ { ID: "12345678", Name: "qux", Namespace: "ns", Containers: []*kubecontainer.Container{ { Name: "foo", ID: types.UID(containerID), }, }, }, } stats, err := kubelet.GetContainerInfo("qux_ns", "", "foo", cadvisorReq) if err != nil { t.Errorf("unexpected error: %v", err) } if stats == nil { t.Fatalf("stats should not be nil") } mockCadvisor.AssertExpectations(t) } func TestGetRawContainerInfoRoot(t *testing.T) { containerPath := "/" containerInfo := &cadvisorApi.ContainerInfo{ ContainerReference: cadvisorApi.ContainerReference{ Name: containerPath, }, } testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet mockCadvisor := testKubelet.fakeCadvisor cadvisorReq := &cadvisorApi.ContainerInfoRequest{} mockCadvisor.On("ContainerInfo", containerPath, cadvisorReq).Return(containerInfo, nil) _, err := kubelet.GetRawContainerInfo(containerPath, cadvisorReq, false) if err != nil { t.Errorf("unexpected error: %v", err) } mockCadvisor.AssertExpectations(t) } func TestGetRawContainerInfoSubcontainers(t *testing.T) { containerPath := "/kubelet" containerInfo := map[string]*cadvisorApi.ContainerInfo{ containerPath: { ContainerReference: cadvisorApi.ContainerReference{ Name: containerPath, }, }, "/kubelet/sub": { ContainerReference: cadvisorApi.ContainerReference{ Name: "/kubelet/sub", }, }, } testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet mockCadvisor := testKubelet.fakeCadvisor cadvisorReq := &cadvisorApi.ContainerInfoRequest{} mockCadvisor.On("SubcontainerInfo", containerPath, cadvisorReq).Return(containerInfo, nil) result, err := kubelet.GetRawContainerInfo(containerPath, cadvisorReq, true) if err != nil { t.Errorf("unexpected error: %v", err) } if len(result) != 2 { t.Errorf("Expected 2 elements, received: %+v", result) } mockCadvisor.AssertExpectations(t) } func TestGetContainerInfoWhenCadvisorFailed(t *testing.T) { containerID := "ab2cdf" testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet mockCadvisor := testKubelet.fakeCadvisor fakeRuntime := testKubelet.fakeRuntime cadvisorApiFailure := fmt.Errorf("cAdvisor failure") containerInfo := cadvisorApi.ContainerInfo{} cadvisorReq := &cadvisorApi.ContainerInfoRequest{} mockCadvisor.On("DockerContainer", containerID, cadvisorReq).Return(containerInfo, cadvisorApiFailure) fakeRuntime.PodList = []*kubecontainer.Pod{ { ID: "uuid", Name: "qux", Namespace: "ns", Containers: []*kubecontainer.Container{ {Name: "foo", ID: types.UID(containerID), }, }, }, } stats, err := kubelet.GetContainerInfo("qux_ns", "uuid", "foo", cadvisorReq) if stats != nil { t.Errorf("non-nil stats on error") } if err == nil { t.Errorf("expect error but received nil error") return } if err.Error() != cadvisorApiFailure.Error() { t.Errorf("wrong error message. expect %v, got %v", cadvisorApiFailure, err) } mockCadvisor.AssertExpectations(t) } func TestGetContainerInfoOnNonExistContainer(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet mockCadvisor := testKubelet.fakeCadvisor fakeRuntime := testKubelet.fakeRuntime fakeRuntime.PodList = []*kubecontainer.Pod{} stats, _ := kubelet.GetContainerInfo("qux", "", "foo", nil) if stats != nil { t.Errorf("non-nil stats on non exist container") } mockCadvisor.AssertExpectations(t) } func TestGetContainerInfoWhenContainerRuntimeFailed(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet mockCadvisor := testKubelet.fakeCadvisor fakeRuntime := testKubelet.fakeRuntime expectedErr := fmt.Errorf("List containers error") fakeRuntime.Err = expectedErr stats, err := kubelet.GetContainerInfo("qux", "", "foo", nil) if err == nil { t.Errorf("expected error from dockertools, got none") } if err.Error() != expectedErr.Error() { t.Errorf("expected error %v got %v", expectedErr.Error(), err.Error()) } if stats != nil { t.Errorf("non-nil stats when dockertools failed") } mockCadvisor.AssertExpectations(t) } func TestGetContainerInfoWithNoContainers(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet mockCadvisor := testKubelet.fakeCadvisor stats, err := kubelet.GetContainerInfo("qux_ns", "", "foo", nil) if err == nil { t.Errorf("expected error from cadvisor client, got none") } if err != ErrContainerNotFound { t.Errorf("expected error %v, got %v", ErrContainerNotFound.Error(), err.Error()) } if stats != nil { t.Errorf("non-nil stats when dockertools returned no containers") } mockCadvisor.AssertExpectations(t) } func TestGetContainerInfoWithNoMatchingContainers(t *testing.T) { testKubelet := newTestKubelet(t) fakeRuntime := testKubelet.fakeRuntime kubelet := testKubelet.kubelet mockCadvisor := testKubelet.fakeCadvisor fakeRuntime.PodList = []*kubecontainer.Pod{ { ID: "12345678", Name: "qux", Namespace: "ns", Containers: []*kubecontainer.Container{ {Name: "bar", ID: types.UID("fakeID"), }, }}, } stats, err := kubelet.GetContainerInfo("qux_ns", "", "foo", nil) if err == nil { t.Errorf("Expected error from cadvisor client, got none") } if err != ErrContainerNotFound { t.Errorf("Expected error %v, got %v", ErrContainerNotFound.Error(), err.Error()) } if stats != nil { t.Errorf("non-nil stats when dockertools returned no containers") } mockCadvisor.AssertExpectations(t) } type fakeContainerCommandRunner struct { Cmd []string ID string PodID types.UID E error Stdin io.Reader Stdout io.WriteCloser Stderr io.WriteCloser TTY bool Port uint16 Stream io.ReadWriteCloser } func (f *fakeContainerCommandRunner) RunInContainer(id string, cmd []string) ([]byte, error) { f.Cmd = cmd f.ID = id return []byte{}, f.E } func (f *fakeContainerCommandRunner) ExecInContainer(id string, cmd []string, in io.Reader, out, err io.WriteCloser, tty bool) error { f.Cmd = cmd f.ID = id f.Stdin = in f.Stdout = out f.Stderr = err f.TTY = tty return f.E } func (f *fakeContainerCommandRunner) PortForward(pod *kubecontainer.Pod, port uint16, stream io.ReadWriteCloser) error { f.PodID = pod.ID f.Port = port f.Stream = stream return nil } func TestRunInContainerNoSuchPod(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet fakeRuntime := testKubelet.fakeRuntime fakeRuntime.PodList = []*kubecontainer.Pod{} podName := "podFoo" podNamespace := "nsFoo" containerName := "containerFoo" output, err := kubelet.RunInContainer( kubecontainer.GetPodFullName(&api.Pod{ObjectMeta: api.ObjectMeta{Name: podName, Namespace: podNamespace}}), "", containerName, []string{"ls"}) if output != nil { t.Errorf("unexpected non-nil command: %v", output) } if err == nil { t.Error("unexpected non-error") } } func TestRunInContainer(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet fakeRuntime := testKubelet.fakeRuntime fakeCommandRunner := fakeContainerCommandRunner{} kubelet.runner = &fakeCommandRunner containerID := "abc1234" fakeRuntime.PodList = []*kubecontainer.Pod{ { ID: "12345678", Name: "podFoo", Namespace: "nsFoo", Containers: []*kubecontainer.Container{ {Name: "containerFoo", ID: types.UID(containerID), }, }, }, } cmd := []string{"ls"} _, err := kubelet.RunInContainer("podFoo_nsFoo", "", "containerFoo", cmd) if fakeCommandRunner.ID != containerID { t.Errorf("unexpected Name: %s", fakeCommandRunner.ID) } if !reflect.DeepEqual(fakeCommandRunner.Cmd, cmd) { t.Errorf("unexpected command: %s", fakeCommandRunner.Cmd) } if err != nil { t.Errorf("unexpected error: %v", err) } } func TestParseResolvConf(t *testing.T) { testCases := []struct { data string nameservers []string searches []string }{ {"", []string{}, []string{}}, {" ", []string{}, []string{}}, {"\n", []string{}, []string{}}, {"\t\n\t", []string{}, []string{}}, {"#comment\n", []string{}, []string{}}, {" #comment\n", []string{}, []string{}}, {"#comment\n#comment", []string{}, []string{}}, {"#comment\nnameserver", []string{}, []string{}}, {"#comment\nnameserver\nsearch", []string{}, []string{}}, {"nameserver 1.2.3.4", []string{"1.2.3.4"}, []string{}}, {" nameserver 1.2.3.4", []string{"1.2.3.4"}, []string{}}, {"\tnameserver 1.2.3.4", []string{"1.2.3.4"}, []string{}}, {"nameserver\t1.2.3.4", []string{"1.2.3.4"}, []string{}}, {"nameserver \t 1.2.3.4", []string{"1.2.3.4"}, []string{}}, {"nameserver 1.2.3.4\nnameserver 5.6.7.8", []string{"1.2.3.4", "5.6.7.8"}, []string{}}, {"search foo", []string{}, []string{"foo"}}, {"search foo bar", []string{}, []string{"foo", "bar"}}, {"search foo bar bat\n", []string{}, []string{"foo", "bar", "bat"}}, {"search foo\nsearch bar", []string{}, []string{"bar"}}, {"nameserver 1.2.3.4\nsearch foo bar", []string{"1.2.3.4"}, []string{"foo", "bar"}}, {"nameserver 1.2.3.4\nsearch foo\nnameserver 5.6.7.8\nsearch bar", []string{"1.2.3.4", "5.6.7.8"}, []string{"bar"}}, {"#comment\nnameserver 1.2.3.4\n#comment\nsearch foo\ncomment", []string{"1.2.3.4"}, []string{"foo"}}, } for i, tc := range testCases { ns, srch, err := parseResolvConf(strings.NewReader(tc.data)) if err != nil { t.Errorf("expected success, got %v", err) continue } if !reflect.DeepEqual(ns, tc.nameservers) { t.Errorf("[%d] expected nameservers %#v, got %#v", i, tc.nameservers, ns) } if !reflect.DeepEqual(srch, tc.searches) { t.Errorf("[%d] expected searches %#v, got %#v", i, tc.searches, srch) } } } func TestDNSConfigurationParams(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet clusterNS := "203.0.113.1" kubelet.clusterDomain = "kubernetes.io" kubelet.clusterDNS = net.ParseIP(clusterNS) pods := newTestPods(2) pods[0].Spec.DNSPolicy = api.DNSClusterFirst pods[1].Spec.DNSPolicy = api.DNSDefault options := make([]*kubecontainer.RunContainerOptions, 2) for i, pod := range pods { var err error kubelet.volumeManager.SetVolumes(pod.UID, make(kubecontainer.VolumeMap, 0)) options[i], err = kubelet.GenerateRunContainerOptions(pod, &api.Container{}) if err != nil { t.Fatalf("failed to generate container options: %v", err) } } if len(options[0].DNS) != 1 || options[0].DNS[0] != clusterNS { t.Errorf("expected nameserver %s, got %+v", clusterNS, options[0].DNS) } if len(options[0].DNSSearch) == 0 || options[0].DNSSearch[0] != ".svc."+kubelet.clusterDomain { t.Errorf("expected search %s, got %+v", ".svc."+kubelet.clusterDomain, options[0].DNSSearch) } if len(options[1].DNS) != 1 || options[1].DNS[0] != "127.0.0.1" { t.Errorf("expected nameserver 127.0.0.1, got %+v", options[1].DNS) } if len(options[1].DNSSearch) != 1 || options[1].DNSSearch[0] != "." { t.Errorf("expected search \".\", got %+v", options[1].DNSSearch) } kubelet.resolverConfig = "/etc/resolv.conf" for i, pod := range pods { var err error options[i], err = kubelet.GenerateRunContainerOptions(pod, &api.Container{}) if err != nil { t.Fatalf("failed to generate container options: %v", err) } } t.Logf("nameservers %+v", options[1].DNS) if len(options[0].DNS) != len(options[1].DNS)+1 { t.Errorf("expected prepend of cluster nameserver, got %+v", options[0].DNS) } else if options[0].DNS[0] != clusterNS { t.Errorf("expected nameserver %s, got %v", clusterNS, options[0].DNS[0]) } if len(options[0].DNSSearch) != len(options[1].DNSSearch)+3 { t.Errorf("expected prepend of cluster domain, got %+v", options[0].DNSSearch) } else if options[0].DNSSearch[0] != ".svc."+kubelet.clusterDomain { t.Errorf("expected domain %s, got %s", ".svc."+kubelet.clusterDomain, options[0].DNSSearch) } } type testServiceLister struct { services []api.Service } func (ls testServiceLister) List() (api.ServiceList, error) { return api.ServiceList{ Items: ls.services, }, nil } type testNodeLister struct { nodes []api.Node } func (ls testNodeLister) GetNodeInfo(id string) (*api.Node, error) { return nil, errors.New("not implemented") } func (ls testNodeLister) List() (api.NodeList, error) { return api.NodeList{ Items: ls.nodes, }, nil } type envs []kubecontainer.EnvVar func (e envs) Len() int { return len(e) } func (e envs) Swap(i, j int) { e[i], e[j] = e[j], e[i] } func (e envs) Less(i, j int) bool { return e[i].Name < e[j].Name } func TestMakeEnvironmentVariables(t *testing.T) { services := []api.Service{ { ObjectMeta: api.ObjectMeta{Name: "kubernetes", Namespace: api.NamespaceDefault}, Spec: api.ServiceSpec{ Ports: []api.ServicePort{{ Protocol: "TCP", Port: 8081, }}, ClusterIP: "1.2.3.1", }, }, { ObjectMeta: api.ObjectMeta{Name: "test", Namespace: "test1"}, Spec: api.ServiceSpec{ Ports: []api.ServicePort{{ Protocol: "TCP", Port: 8083, }}, ClusterIP: "1.2.3.3", }, }, { ObjectMeta: api.ObjectMeta{Name: "kubernetes", Namespace: "test2"}, Spec: api.ServiceSpec{ Ports: []api.ServicePort{{ Protocol: "TCP", Port: 8084, }}, ClusterIP: "1.2.3.4", }, }, { ObjectMeta: api.ObjectMeta{Name: "test", Namespace: "test2"}, Spec: api.ServiceSpec{ Ports: []api.ServicePort{{ Protocol: "TCP", Port: 8085, }}, ClusterIP: "1.2.3.5", }, }, { ObjectMeta: api.ObjectMeta{Name: "test", Namespace: "test2"}, Spec: api.ServiceSpec{ Ports: []api.ServicePort{{ Protocol: "TCP", Port: 8085, }}, ClusterIP: "None", }, }, { ObjectMeta: api.ObjectMeta{Name: "test", Namespace: "test2"}, Spec: api.ServiceSpec{ Ports: []api.ServicePort{{ Protocol: "TCP", Port: 8085, }}, }, }, { ObjectMeta: api.ObjectMeta{Name: "kubernetes", Namespace: "kubernetes"}, Spec: api.ServiceSpec{ Ports: []api.ServicePort{{ Protocol: "TCP", Port: 8086, }}, ClusterIP: "1.2.3.6", }, }, { ObjectMeta: api.ObjectMeta{Name: "not-special", Namespace: "kubernetes"}, Spec: api.ServiceSpec{ Ports: []api.ServicePort{{ Protocol: "TCP", Port: 8088, }}, ClusterIP: "1.2.3.8", }, }, { ObjectMeta: api.ObjectMeta{Name: "not-special", Namespace: "kubernetes"}, Spec: api.ServiceSpec{ Ports: []api.ServicePort{{ Protocol: "TCP", Port: 8088, }}, ClusterIP: "None", }, }, { ObjectMeta: api.ObjectMeta{Name: "not-special", Namespace: "kubernetes"}, Spec: api.ServiceSpec{ Ports: []api.ServicePort{{ Protocol: "TCP", Port: 8088, }}, ClusterIP: "", }, }, } testCases := []struct { name string // the name of the test case ns string // the namespace to generate environment for container *api.Container // the container to use masterServiceNs string // the namespace to read master service info from nilLister bool // whether the lister should be nil expectedEnvs []kubecontainer.EnvVar // a set of expected environment vars }{ { name: "api server = Y, kubelet = Y", ns: "test1", container: &api.Container{ Env: []api.EnvVar{ {Name: "FOO", Value: "BAR"}, {Name: "TEST_SERVICE_HOST", Value: "1.2.3.3"}, {Name: "TEST_SERVICE_PORT", Value: "8083"}, {Name: "TEST_PORT", Value: "tcp://1.2.3.3:8083"}, {Name: "TEST_PORT_8083_TCP", Value: "tcp://1.2.3.3:8083"}, {Name: "TEST_PORT_8083_TCP_PROTO", Value: "tcp"}, {Name: "TEST_PORT_8083_TCP_PORT", Value: "8083"}, {Name: "TEST_PORT_8083_TCP_ADDR", Value: "1.2.3.3"}, }, }, masterServiceNs: api.NamespaceDefault, nilLister: false, expectedEnvs: []kubecontainer.EnvVar{ {Name: "FOO", Value: "BAR"}, {Name: "TEST_SERVICE_HOST", Value: "1.2.3.3"}, {Name: "TEST_SERVICE_PORT", Value: "8083"}, {Name: "TEST_PORT", Value: "tcp://1.2.3.3:8083"}, {Name: "TEST_PORT_8083_TCP", Value: "tcp://1.2.3.3:8083"}, {Name: "TEST_PORT_8083_TCP_PROTO", Value: "tcp"}, {Name: "TEST_PORT_8083_TCP_PORT", Value: "8083"}, {Name: "TEST_PORT_8083_TCP_ADDR", Value: "1.2.3.3"}, {Name: "KUBERNETES_SERVICE_PORT", Value: "8081"}, {Name: "KUBERNETES_SERVICE_HOST", Value: "1.2.3.1"}, {Name: "KUBERNETES_PORT", Value: "tcp://1.2.3.1:8081"}, {Name: "KUBERNETES_PORT_8081_TCP", Value: "tcp://1.2.3.1:8081"}, {Name: "KUBERNETES_PORT_8081_TCP_PROTO", Value: "tcp"}, {Name: "KUBERNETES_PORT_8081_TCP_PORT", Value: "8081"}, {Name: "KUBERNETES_PORT_8081_TCP_ADDR", Value: "1.2.3.1"}, }, }, { name: "api server = Y, kubelet = N", ns: "test1", container: &api.Container{ Env: []api.EnvVar{ {Name: "FOO", Value: "BAR"}, {Name: "TEST_SERVICE_HOST", Value: "1.2.3.3"}, {Name: "TEST_SERVICE_PORT", Value: "8083"}, {Name: "TEST_PORT", Value: "tcp://1.2.3.3:8083"}, {Name: "TEST_PORT_8083_TCP", Value: "tcp://1.2.3.3:8083"}, {Name: "TEST_PORT_8083_TCP_PROTO", Value: "tcp"}, {Name: "TEST_PORT_8083_TCP_PORT", Value: "8083"}, {Name: "TEST_PORT_8083_TCP_ADDR", Value: "1.2.3.3"}, }, }, masterServiceNs: api.NamespaceDefault, nilLister: true, expectedEnvs: []kubecontainer.EnvVar{ {Name: "FOO", Value: "BAR"}, {Name: "TEST_SERVICE_HOST", Value: "1.2.3.3"}, {Name: "TEST_SERVICE_PORT", Value: "8083"}, {Name: "TEST_PORT", Value: "tcp://1.2.3.3:8083"}, {Name: "TEST_PORT_8083_TCP", Value: "tcp://1.2.3.3:8083"}, {Name: "TEST_PORT_8083_TCP_PROTO", Value: "tcp"}, {Name: "TEST_PORT_8083_TCP_PORT", Value: "8083"}, {Name: "TEST_PORT_8083_TCP_ADDR", Value: "1.2.3.3"}, }, }, { name: "api server = N; kubelet = Y", ns: "test1", container: &api.Container{ Env: []api.EnvVar{ {Name: "FOO", Value: "BAZ"}, }, }, masterServiceNs: api.NamespaceDefault, nilLister: false, expectedEnvs: []kubecontainer.EnvVar{ {Name: "FOO", Value: "BAZ"}, {Name: "TEST_SERVICE_HOST", Value: "1.2.3.3"}, {Name: "TEST_SERVICE_PORT", Value: "8083"}, {Name: "TEST_PORT", Value: "tcp://1.2.3.3:8083"}, {Name: "TEST_PORT_8083_TCP", Value: "tcp://1.2.3.3:8083"}, {Name: "TEST_PORT_8083_TCP_PROTO", Value: "tcp"}, {Name: "TEST_PORT_8083_TCP_PORT", Value: "8083"}, {Name: "TEST_PORT_8083_TCP_ADDR", Value: "1.2.3.3"}, {Name: "KUBERNETES_SERVICE_HOST", Value: "1.2.3.1"}, {Name: "KUBERNETES_SERVICE_PORT", Value: "8081"}, {Name: "KUBERNETES_PORT", Value: "tcp://1.2.3.1:8081"}, {Name: "KUBERNETES_PORT_8081_TCP", Value: "tcp://1.2.3.1:8081"}, {Name: "KUBERNETES_PORT_8081_TCP_PROTO", Value: "tcp"}, {Name: "KUBERNETES_PORT_8081_TCP_PORT", Value: "8081"}, {Name: "KUBERNETES_PORT_8081_TCP_ADDR", Value: "1.2.3.1"}, }, }, { name: "master service in pod ns", ns: "test2", container: &api.Container{ Env: []api.EnvVar{ {Name: "FOO", Value: "ZAP"}, }, }, masterServiceNs: "kubernetes", nilLister: false, expectedEnvs: []kubecontainer.EnvVar{ {Name: "FOO", Value: "ZAP"}, {Name: "TEST_SERVICE_HOST", Value: "1.2.3.5"}, {Name: "TEST_SERVICE_PORT", Value: "8085"}, {Name: "TEST_PORT", Value: "tcp://1.2.3.5:8085"}, {Name: "TEST_PORT_8085_TCP", Value: "tcp://1.2.3.5:8085"}, {Name: "TEST_PORT_8085_TCP_PROTO", Value: "tcp"}, {Name: "TEST_PORT_8085_TCP_PORT", Value: "8085"}, {Name: "TEST_PORT_8085_TCP_ADDR", Value: "1.2.3.5"}, {Name: "KUBERNETES_SERVICE_HOST", Value: "1.2.3.4"}, {Name: "KUBERNETES_SERVICE_PORT", Value: "8084"}, {Name: "KUBERNETES_PORT", Value: "tcp://1.2.3.4:8084"}, {Name: "KUBERNETES_PORT_8084_TCP", Value: "tcp://1.2.3.4:8084"}, {Name: "KUBERNETES_PORT_8084_TCP_PROTO", Value: "tcp"}, {Name: "KUBERNETES_PORT_8084_TCP_PORT", Value: "8084"}, {Name: "KUBERNETES_PORT_8084_TCP_ADDR", Value: "1.2.3.4"}, }, }, { name: "pod in master service ns", ns: "kubernetes", container: &api.Container{}, masterServiceNs: "kubernetes", nilLister: false, expectedEnvs: []kubecontainer.EnvVar{ {Name: "NOT_SPECIAL_SERVICE_HOST", Value: "1.2.3.8"}, {Name: "NOT_SPECIAL_SERVICE_PORT", Value: "8088"}, {Name: "NOT_SPECIAL_PORT", Value: "tcp://1.2.3.8:8088"}, {Name: "NOT_SPECIAL_PORT_8088_TCP", Value: "tcp://1.2.3.8:8088"}, {Name: "NOT_SPECIAL_PORT_8088_TCP_PROTO", Value: "tcp"}, {Name: "NOT_SPECIAL_PORT_8088_TCP_PORT", Value: "8088"}, {Name: "NOT_SPECIAL_PORT_8088_TCP_ADDR", Value: "1.2.3.8"}, {Name: "KUBERNETES_SERVICE_HOST", Value: "1.2.3.6"}, {Name: "KUBERNETES_SERVICE_PORT", Value: "8086"}, {Name: "KUBERNETES_PORT", Value: "tcp://1.2.3.6:8086"}, {Name: "KUBERNETES_PORT_8086_TCP", Value: "tcp://1.2.3.6:8086"}, {Name: "KUBERNETES_PORT_8086_TCP_PROTO", Value: "tcp"}, {Name: "KUBERNETES_PORT_8086_TCP_PORT", Value: "8086"}, {Name: "KUBERNETES_PORT_8086_TCP_ADDR", Value: "1.2.3.6"}, }, }, { name: "downward api pod", ns: "downward-api", container: &api.Container{ Env: []api.EnvVar{ { Name: "POD_NAME", ValueFrom: &api.EnvVarSource{ FieldRef: &api.ObjectFieldSelector{ APIVersion: testapi.Version(), FieldPath: "metadata.name", }, }, }, { Name: "POD_NAMESPACE", ValueFrom: &api.EnvVarSource{ FieldRef: &api.ObjectFieldSelector{ APIVersion: testapi.Version(), FieldPath: "metadata.namespace", }, }, }, { Name: "POD_IP", ValueFrom: &api.EnvVarSource{ FieldRef: &api.ObjectFieldSelector{ APIVersion: testapi.Version(), FieldPath: "status.podIP", }, }, }, }, }, masterServiceNs: "nothing", nilLister: true, expectedEnvs: []kubecontainer.EnvVar{ {Name: "POD_NAME", Value: "dapi-test-pod-name"}, {Name: "POD_NAMESPACE", Value: "downward-api"}, {Name: "POD_IP", Value: "1.2.3.4"}, }, }, { name: "env expansion", ns: "test1", container: &api.Container{ Env: []api.EnvVar{ { Name: "TEST_LITERAL", Value: "test-test-test", }, { Name: "POD_NAME", ValueFrom: &api.EnvVarSource{ FieldRef: &api.ObjectFieldSelector{ APIVersion: testapi.Version(), FieldPath: "metadata.name", }, }, }, { Name: "OUT_OF_ORDER_TEST", Value: "$(OUT_OF_ORDER_TARGET)", }, { Name: "OUT_OF_ORDER_TARGET", Value: "FOO", }, { Name: "EMPTY_VAR", }, { Name: "EMPTY_TEST", Value: "foo-$(EMPTY_VAR)", }, { Name: "POD_NAME_TEST2", Value: "test2-$(POD_NAME)", }, { Name: "POD_NAME_TEST3", Value: "$(POD_NAME_TEST2)-3", }, { Name: "LITERAL_TEST", Value: "literal-$(TEST_LITERAL)", }, { Name: "SERVICE_VAR_TEST", Value: "$(TEST_SERVICE_HOST):$(TEST_SERVICE_PORT)", }, { Name: "TEST_UNDEFINED", Value: "$(UNDEFINED_VAR)", }, }, }, masterServiceNs: "nothing", nilLister: false, expectedEnvs: []kubecontainer.EnvVar{ { Name: "TEST_LITERAL", Value: "test-test-test", }, { Name: "POD_NAME", Value: "dapi-test-pod-name", }, { Name: "POD_NAME_TEST2", Value: "test2-dapi-test-pod-name", }, { Name: "POD_NAME_TEST3", Value: "test2-dapi-test-pod-name-3", }, { Name: "LITERAL_TEST", Value: "literal-test-test-test", }, { Name: "TEST_SERVICE_HOST", Value: "1.2.3.3", }, { Name: "TEST_SERVICE_PORT", Value: "8083", }, { Name: "TEST_PORT", Value: "tcp://1.2.3.3:8083", }, { Name: "TEST_PORT_8083_TCP", Value: "tcp://1.2.3.3:8083", }, { Name: "TEST_PORT_8083_TCP_PROTO", Value: "tcp", }, { Name: "TEST_PORT_8083_TCP_PORT", Value: "8083", }, { Name: "TEST_PORT_8083_TCP_ADDR", Value: "1.2.3.3", }, { Name: "SERVICE_VAR_TEST", Value: "1.2.3.3:8083", }, { Name: "OUT_OF_ORDER_TEST", Value: "$(OUT_OF_ORDER_TARGET)", }, { Name: "OUT_OF_ORDER_TARGET", Value: "FOO", }, { Name: "TEST_UNDEFINED", Value: "$(UNDEFINED_VAR)", }, { Name: "EMPTY_VAR", }, { Name: "EMPTY_TEST", Value: "foo-", }, }, }, } for i, tc := range testCases { testKubelet := newTestKubelet(t) kl := testKubelet.kubelet kl.masterServiceNamespace = tc.masterServiceNs if tc.nilLister { kl.serviceLister = nil } else { kl.serviceLister = testServiceLister{services} } testPod := &api.Pod{ ObjectMeta: api.ObjectMeta{ Namespace: tc.ns, Name: "dapi-test-pod-name", }, } testPod.Status.PodIP = "1.2.3.4" result, err := kl.makeEnvironmentVariables(testPod, tc.container) if err != nil { t.Errorf("[%v] Unexpected error: %v", tc.name, err) } sort.Sort(envs(result)) sort.Sort(envs(tc.expectedEnvs)) if !reflect.DeepEqual(result, tc.expectedEnvs) { t.Errorf("%d: [%v] Unexpected env entries; expected {%v}, got {%v}", i, tc.name, tc.expectedEnvs, result) } } } func runningState(cName string) api.ContainerStatus { return api.ContainerStatus{ Name: cName, State: api.ContainerState{ Running: &api.ContainerStateRunning{}, }, } } func stoppedState(cName string) api.ContainerStatus { return api.ContainerStatus{ Name: cName, State: api.ContainerState{ Terminated: &api.ContainerStateTerminated{}, }, } } func succeededState(cName string) api.ContainerStatus { return api.ContainerStatus{ Name: cName, State: api.ContainerState{ Terminated: &api.ContainerStateTerminated{ ExitCode: 0, }, }, } } func failedState(cName string) api.ContainerStatus { return api.ContainerStatus{ Name: cName, State: api.ContainerState{ Terminated: &api.ContainerStateTerminated{ ExitCode: -1, }, }, } } func TestPodPhaseWithRestartAlways(t *testing.T) { desiredState := api.PodSpec{ NodeName: "machine", Containers: []api.Container{ {Name: "containerA"}, {Name: "containerB"}, }, RestartPolicy: api.RestartPolicyAlways, } tests := []struct { pod *api.Pod status api.PodPhase test string }{ {&api.Pod{Spec: desiredState, Status: api.PodStatus{}}, api.PodPending, "waiting"}, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ ContainerStatuses: []api.ContainerStatus{ runningState("containerA"), runningState("containerB"), }, }, }, api.PodRunning, "all running", }, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ ContainerStatuses: []api.ContainerStatus{ stoppedState("containerA"), stoppedState("containerB"), }, }, }, api.PodRunning, "all stopped with restart always", }, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ ContainerStatuses: []api.ContainerStatus{ runningState("containerA"), stoppedState("containerB"), }, }, }, api.PodRunning, "mixed state #1 with restart always", }, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ ContainerStatuses: []api.ContainerStatus{ runningState("containerA"), }, }, }, api.PodPending, "mixed state #2 with restart always", }, } for _, test := range tests { if status := GetPhase(&test.pod.Spec, test.pod.Status.ContainerStatuses); status != test.status { t.Errorf("In test %s, expected %v, got %v", test.test, test.status, status) } } } func TestPodPhaseWithRestartNever(t *testing.T) { desiredState := api.PodSpec{ NodeName: "machine", Containers: []api.Container{ {Name: "containerA"}, {Name: "containerB"}, }, RestartPolicy: api.RestartPolicyNever, } tests := []struct { pod *api.Pod status api.PodPhase test string }{ {&api.Pod{Spec: desiredState, Status: api.PodStatus{}}, api.PodPending, "waiting"}, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ ContainerStatuses: []api.ContainerStatus{ runningState("containerA"), runningState("containerB"), }, }, }, api.PodRunning, "all running with restart never", }, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ ContainerStatuses: []api.ContainerStatus{ succeededState("containerA"), succeededState("containerB"), }, }, }, api.PodSucceeded, "all succeeded with restart never", }, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ ContainerStatuses: []api.ContainerStatus{ failedState("containerA"), failedState("containerB"), }, }, }, api.PodFailed, "all failed with restart never", }, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ ContainerStatuses: []api.ContainerStatus{ runningState("containerA"), succeededState("containerB"), }, }, }, api.PodRunning, "mixed state #1 with restart never", }, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ ContainerStatuses: []api.ContainerStatus{ runningState("containerA"), }, }, }, api.PodPending, "mixed state #2 with restart never", }, } for _, test := range tests { if status := GetPhase(&test.pod.Spec, test.pod.Status.ContainerStatuses); status != test.status { t.Errorf("In test %s, expected %v, got %v", test.test, test.status, status) } } } func TestPodPhaseWithRestartOnFailure(t *testing.T) { desiredState := api.PodSpec{ NodeName: "machine", Containers: []api.Container{ {Name: "containerA"}, {Name: "containerB"}, }, RestartPolicy: api.RestartPolicyOnFailure, } tests := []struct { pod *api.Pod status api.PodPhase test string }{ {&api.Pod{Spec: desiredState, Status: api.PodStatus{}}, api.PodPending, "waiting"}, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ ContainerStatuses: []api.ContainerStatus{ runningState("containerA"), runningState("containerB"), }, }, }, api.PodRunning, "all running with restart onfailure", }, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ ContainerStatuses: []api.ContainerStatus{ succeededState("containerA"), succeededState("containerB"), }, }, }, api.PodSucceeded, "all succeeded with restart onfailure", }, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ ContainerStatuses: []api.ContainerStatus{ failedState("containerA"), failedState("containerB"), }, }, }, api.PodRunning, "all failed with restart never", }, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ ContainerStatuses: []api.ContainerStatus{ runningState("containerA"), succeededState("containerB"), }, }, }, api.PodRunning, "mixed state #1 with restart onfailure", }, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ ContainerStatuses: []api.ContainerStatus{ runningState("containerA"), }, }, }, api.PodPending, "mixed state #2 with restart onfailure", }, } for _, test := range tests { if status := GetPhase(&test.pod.Spec, test.pod.Status.ContainerStatuses); status != test.status { t.Errorf("In test %s, expected %v, got %v", test.test, test.status, status) } } } func getReadyStatus(cName string) api.ContainerStatus { return api.ContainerStatus{ Name: cName, Ready: true, } } func getNotReadyStatus(cName string) api.ContainerStatus { return api.ContainerStatus{ Name: cName, Ready: false, } } func TestGetPodReadyCondition(t *testing.T) { ready := []api.PodCondition{{ Type: api.PodReady, Status: api.ConditionTrue, }} unready := []api.PodCondition{{ Type: api.PodReady, Status: api.ConditionFalse, }} tests := []struct { spec *api.PodSpec info []api.ContainerStatus expected []api.PodCondition }{ { spec: nil, info: nil, expected: unready, }, { spec: &api.PodSpec{}, info: []api.ContainerStatus{}, expected: ready, }, { spec: &api.PodSpec{ Containers: []api.Container{ {Name: "1234"}, }, }, info: []api.ContainerStatus{}, expected: unready, }, { spec: &api.PodSpec{ Containers: []api.Container{ {Name: "1234"}, }, }, info: []api.ContainerStatus{ getReadyStatus("1234"), }, expected: ready, }, { spec: &api.PodSpec{ Containers: []api.Container{ {Name: "1234"}, {Name: "5678"}, }, }, info: []api.ContainerStatus{ getReadyStatus("1234"), getReadyStatus("5678"), }, expected: ready, }, { spec: &api.PodSpec{ Containers: []api.Container{ {Name: "1234"}, {Name: "5678"}, }, }, info: []api.ContainerStatus{ getReadyStatus("1234"), }, expected: unready, }, { spec: &api.PodSpec{ Containers: []api.Container{ {Name: "1234"}, {Name: "5678"}, }, }, info: []api.ContainerStatus{ getReadyStatus("1234"), getNotReadyStatus("5678"), }, expected: unready, }, } for i, test := range tests { condition := getPodReadyCondition(test.spec, test.info) if !reflect.DeepEqual(condition, test.expected) { t.Errorf("On test case %v, expected:\n%+v\ngot\n%+v\n", i, test.expected, condition) } } } func TestExecInContainerNoSuchPod(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet fakeRuntime := testKubelet.fakeRuntime fakeCommandRunner := fakeContainerCommandRunner{} kubelet.runner = &fakeCommandRunner fakeRuntime.PodList = []*kubecontainer.Pod{} podName := "podFoo" podNamespace := "nsFoo" containerID := "containerFoo" err := kubelet.ExecInContainer( kubecontainer.GetPodFullName(&api.Pod{ObjectMeta: api.ObjectMeta{Name: podName, Namespace: podNamespace}}), "", containerID, []string{"ls"}, nil, nil, nil, false, ) if err == nil { t.Fatal("unexpected non-error") } if fakeCommandRunner.ID != "" { t.Fatal("unexpected invocation of runner.ExecInContainer") } } func TestExecInContainerNoSuchContainer(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet fakeRuntime := testKubelet.fakeRuntime fakeCommandRunner := fakeContainerCommandRunner{} kubelet.runner = &fakeCommandRunner podName := "podFoo" podNamespace := "nsFoo" containerID := "containerFoo" fakeRuntime.PodList = []*kubecontainer.Pod{ { ID: "12345678", Name: podName, Namespace: podNamespace, Containers: []*kubecontainer.Container{ {Name: "bar", ID: "barID"}, }, }, } err := kubelet.ExecInContainer( kubecontainer.GetPodFullName(&api.Pod{ObjectMeta: api.ObjectMeta{ UID: "12345678", Name: podName, Namespace: podNamespace, }}), "", containerID, []string{"ls"}, nil, nil, nil, false, ) if err == nil { t.Fatal("unexpected non-error") } if fakeCommandRunner.ID != "" { t.Fatal("unexpected invocation of runner.ExecInContainer") } } type fakeReadWriteCloser struct{} func (f *fakeReadWriteCloser) Write(data []byte) (int, error) { return 0, nil } func (f *fakeReadWriteCloser) Read(data []byte) (int, error) { return 0, nil } func (f *fakeReadWriteCloser) Close() error { return nil } func TestExecInContainer(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet fakeRuntime := testKubelet.fakeRuntime fakeCommandRunner := fakeContainerCommandRunner{} kubelet.runner = &fakeCommandRunner podName := "podFoo" podNamespace := "nsFoo" containerID := "containerFoo" command := []string{"ls"} stdin := &bytes.Buffer{} stdout := &fakeReadWriteCloser{} stderr := &fakeReadWriteCloser{} tty := true fakeRuntime.PodList = []*kubecontainer.Pod{ { ID: "12345678", Name: podName, Namespace: podNamespace, Containers: []*kubecontainer.Container{ {Name: containerID, ID: types.UID(containerID), }, }, }, } err := kubelet.ExecInContainer( kubecontainer.GetPodFullName(&api.Pod{ObjectMeta: api.ObjectMeta{ UID: "12345678", Name: podName, Namespace: podNamespace, }}), "", containerID, []string{"ls"}, stdin, stdout, stderr, tty, ) if err != nil { t.Fatalf("unexpected error: %s", err) } if e, a := containerID, fakeCommandRunner.ID; e != a { t.Fatalf("container name: expected %q, got %q", e, a) } if e, a := command, fakeCommandRunner.Cmd; !reflect.DeepEqual(e, a) { t.Fatalf("command: expected '%v', got '%v'", e, a) } if e, a := stdin, fakeCommandRunner.Stdin; e != a { t.Fatalf("stdin: expected %#v, got %#v", e, a) } if e, a := stdout, fakeCommandRunner.Stdout; e != a { t.Fatalf("stdout: expected %#v, got %#v", e, a) } if e, a := stderr, fakeCommandRunner.Stderr; e != a { t.Fatalf("stderr: expected %#v, got %#v", e, a) } if e, a := tty, fakeCommandRunner.TTY; e != a { t.Fatalf("tty: expected %t, got %t", e, a) } } func TestPortForwardNoSuchPod(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet fakeRuntime := testKubelet.fakeRuntime fakeRuntime.PodList = []*kubecontainer.Pod{} fakeCommandRunner := fakeContainerCommandRunner{} kubelet.runner = &fakeCommandRunner podName := "podFoo" podNamespace := "nsFoo" var port uint16 = 5000 err := kubelet.PortForward( kubecontainer.GetPodFullName(&api.Pod{ObjectMeta: api.ObjectMeta{Name: podName, Namespace: podNamespace}}), "", port, nil, ) if err == nil { t.Fatal("unexpected non-error") } if fakeCommandRunner.ID != "" { t.Fatal("unexpected invocation of runner.PortForward") } } func TestPortForward(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet fakeRuntime := testKubelet.fakeRuntime podName := "podFoo" podNamespace := "nsFoo" podID := types.UID("12345678") fakeRuntime.PodList = []*kubecontainer.Pod{ { ID: podID, Name: podName, Namespace: podNamespace, Containers: []*kubecontainer.Container{ { Name: "foo", ID: "containerFoo", }, }, }, } fakeCommandRunner := fakeContainerCommandRunner{} kubelet.runner = &fakeCommandRunner var port uint16 = 5000 stream := &fakeReadWriteCloser{} err := kubelet.PortForward( kubecontainer.GetPodFullName(&api.Pod{ObjectMeta: api.ObjectMeta{ UID: "12345678", Name: podName, Namespace: podNamespace, }}), "", port, stream, ) if err != nil { t.Fatalf("unexpected error: %s", err) } if e, a := podID, fakeCommandRunner.PodID; e != a { t.Fatalf("container id: expected %q, got %q", e, a) } if e, a := port, fakeCommandRunner.Port; e != a { t.Fatalf("port: expected %v, got %v", e, a) } if e, a := stream, fakeCommandRunner.Stream; e != a { t.Fatalf("stream: expected %v, got %v", e, a) } } // Tests that identify the host port conflicts are detected correctly. func TestGetHostPortConflicts(t *testing.T) { pods := []*api.Pod{ {Spec: api.PodSpec{Containers: []api.Container{{Ports: []api.ContainerPort{{HostPort: 80}}}}}}, {Spec: api.PodSpec{Containers: []api.Container{{Ports: []api.ContainerPort{{HostPort: 81}}}}}}, {Spec: api.PodSpec{Containers: []api.Container{{Ports: []api.ContainerPort{{HostPort: 82}}}}}}, {Spec: api.PodSpec{Containers: []api.Container{{Ports: []api.ContainerPort{{HostPort: 83}}}}}}, } // Pods should not cause any conflict. if hasHostPortConflicts(pods) { t.Errorf("expected no conflicts, Got conflicts") } expected := &api.Pod{ Spec: api.PodSpec{Containers: []api.Container{{Ports: []api.ContainerPort{{HostPort: 81}}}}}, } // The new pod should cause conflict and be reported. pods = append(pods, expected) if !hasHostPortConflicts(pods) { t.Errorf("expected no conflict, Got no conflicts") } } // Tests that we handle port conflicts correctly by setting the failed status in status map. func TestHandlePortConflicts(t *testing.T) { testKubelet := newTestKubelet(t) kl := testKubelet.kubelet testKubelet.fakeCadvisor.On("MachineInfo").Return(&cadvisorApi.MachineInfo{}, nil) testKubelet.fakeCadvisor.On("DockerImagesFsInfo").Return(cadvisorApiv2.FsInfo{}, nil) testKubelet.fakeCadvisor.On("RootFsInfo").Return(cadvisorApiv2.FsInfo{}, nil) spec := api.PodSpec{Containers: []api.Container{{Ports: []api.ContainerPort{{HostPort: 80}}}}} pods := []*api.Pod{ { ObjectMeta: api.ObjectMeta{ UID: "123456789", Name: "newpod", Namespace: "foo", }, Spec: spec, }, { ObjectMeta: api.ObjectMeta{ UID: "987654321", Name: "oldpod", Namespace: "foo", }, Spec: spec, }, } // Make sure the Pods are in the reverse order of creation time. pods[1].CreationTimestamp = util.NewTime(time.Now()) pods[0].CreationTimestamp = util.NewTime(time.Now().Add(1 * time.Second)) // The newer pod should be rejected. conflictedPod := pods[0] kl.HandlePodAdditions(pods) // Check pod status stored in the status map. status, found := kl.statusManager.GetPodStatus(conflictedPod.UID) if !found { t.Fatalf("status of pod %q is not found in the status map", conflictedPod.UID) } if status.Phase != api.PodFailed { t.Fatalf("expected pod status %q. Got %q.", api.PodFailed, status.Phase) } } // Tests that we handle not matching labels selector correctly by setting the failed status in status map. func TestHandleNodeSelector(t *testing.T) { testKubelet := newTestKubelet(t) kl := testKubelet.kubelet kl.nodeLister = testNodeLister{nodes: []api.Node{ {ObjectMeta: api.ObjectMeta{Name: testKubeletHostname, Labels: map[string]string{"key": "B"}}}, }} testKubelet.fakeCadvisor.On("MachineInfo").Return(&cadvisorApi.MachineInfo{}, nil) testKubelet.fakeCadvisor.On("DockerImagesFsInfo").Return(cadvisorApiv2.FsInfo{}, nil) testKubelet.fakeCadvisor.On("RootFsInfo").Return(cadvisorApiv2.FsInfo{}, nil) pods := []*api.Pod{ { ObjectMeta: api.ObjectMeta{ UID: "123456789", Name: "podA", Namespace: "foo", }, Spec: api.PodSpec{NodeSelector: map[string]string{"key": "A"}}, }, { ObjectMeta: api.ObjectMeta{ UID: "987654321", Name: "podB", Namespace: "foo", }, Spec: api.PodSpec{NodeSelector: map[string]string{"key": "B"}}, }, } // The first pod should be rejected. notfittingPod := pods[0] kl.HandlePodAdditions(pods) // Check pod status stored in the status map. status, found := kl.statusManager.GetPodStatus(notfittingPod.UID) if !found { t.Fatalf("status of pod %q is not found in the status map", notfittingPod.UID) } if status.Phase != api.PodFailed { t.Fatalf("expected pod status %q. Got %q.", api.PodFailed, status.Phase) } } // Tests that we handle exceeded resources correctly by setting the failed status in status map. func TestHandleMemExceeded(t *testing.T) { testKubelet := newTestKubelet(t) kl := testKubelet.kubelet testKubelet.fakeCadvisor.On("MachineInfo").Return(&cadvisorApi.MachineInfo{MemoryCapacity: 100}, nil) testKubelet.fakeCadvisor.On("DockerImagesFsInfo").Return(cadvisorApiv2.FsInfo{}, nil) testKubelet.fakeCadvisor.On("RootFsInfo").Return(cadvisorApiv2.FsInfo{}, nil) spec := api.PodSpec{Containers: []api.Container{{Resources: api.ResourceRequirements{ Requests: api.ResourceList{ "memory": resource.MustParse("90"), }, }}}} pods := []*api.Pod{ { ObjectMeta: api.ObjectMeta{ UID: "123456789", Name: "newpod", Namespace: "foo", }, Spec: spec, }, { ObjectMeta: api.ObjectMeta{ UID: "987654321", Name: "oldpod", Namespace: "foo", }, Spec: spec, }, } // Make sure the Pods are in the reverse order of creation time. pods[1].CreationTimestamp = util.NewTime(time.Now()) pods[0].CreationTimestamp = util.NewTime(time.Now().Add(1 * time.Second)) // The newer pod should be rejected. notfittingPod := pods[0] kl.HandlePodAdditions(pods) // Check pod status stored in the status map. status, found := kl.statusManager.GetPodStatus(notfittingPod.UID) if !found { t.Fatalf("status of pod %q is not found in the status map", notfittingPod.UID) } if status.Phase != api.PodFailed { t.Fatalf("expected pod status %q. Got %q.", api.PodFailed, status.Phase) } } // TODO(filipg): This test should be removed once StatusSyncer can do garbage collection without external signal. func TestPurgingObsoleteStatusMapEntries(t *testing.T) { testKubelet := newTestKubelet(t) testKubelet.fakeCadvisor.On("MachineInfo").Return(&cadvisorApi.MachineInfo{}, nil) testKubelet.fakeCadvisor.On("DockerImagesFsInfo").Return(cadvisorApiv2.FsInfo{}, nil) testKubelet.fakeCadvisor.On("RootFsInfo").Return(cadvisorApiv2.FsInfo{}, nil) kl := testKubelet.kubelet pods := []*api.Pod{ {ObjectMeta: api.ObjectMeta{Name: "pod1", UID: "1234"}, Spec: api.PodSpec{Containers: []api.Container{{Ports: []api.ContainerPort{{HostPort: 80}}}}}}, {ObjectMeta: api.ObjectMeta{Name: "pod2", UID: "4567"}, Spec: api.PodSpec{Containers: []api.Container{{Ports: []api.ContainerPort{{HostPort: 80}}}}}}, } podToTest := pods[1] // Run once to populate the status map. kl.HandlePodAdditions(pods) if _, found := kl.statusManager.GetPodStatus(podToTest.UID); !found { t.Fatalf("expected to have status cached for pod2") } // Sync with empty pods so that the entry in status map will be removed. kl.podManager.SetPods([]*api.Pod{}) kl.HandlePodCleanups() if _, found := kl.statusManager.GetPodStatus(podToTest.UID); found { t.Fatalf("expected to not have status cached for pod2") } } func TestValidatePodStatus(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet testCases := []struct { podPhase api.PodPhase success bool }{ {api.PodRunning, true}, {api.PodSucceeded, true}, {api.PodFailed, true}, {api.PodPending, false}, {api.PodUnknown, false}, } for i, tc := range testCases { err := kubelet.validatePodPhase(&api.PodStatus{Phase: tc.podPhase}) if tc.success { if err != nil { t.Errorf("[case %d]: unexpected failure - %v", i, err) } } else if err == nil { t.Errorf("[case %d]: unexpected success", i) } } } func TestValidateContainerStatus(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet containerName := "x" testCases := []struct { statuses []api.ContainerStatus success bool }{ { statuses: []api.ContainerStatus{ { Name: containerName, State: api.ContainerState{ Running: &api.ContainerStateRunning{}, }, LastTerminationState: api.ContainerState{ Terminated: &api.ContainerStateTerminated{}, }, }, }, success: true, }, { statuses: []api.ContainerStatus{ { Name: containerName, State: api.ContainerState{ Terminated: &api.ContainerStateTerminated{}, }, }, }, success: true, }, { statuses: []api.ContainerStatus{ { Name: containerName, State: api.ContainerState{ Waiting: &api.ContainerStateWaiting{}, }, }, }, success: false, }, } for i, tc := range testCases { _, err := kubelet.validateContainerStatus(&api.PodStatus{ ContainerStatuses: tc.statuses, }, containerName, false) if tc.success { if err != nil { t.Errorf("[case %d]: unexpected failure - %v", i, err) } } else if err == nil { t.Errorf("[case %d]: unexpected success", i) } } if _, err := kubelet.validateContainerStatus(&api.PodStatus{ ContainerStatuses: testCases[0].statuses, }, "blah", false); err == nil { t.Errorf("expected error with invalid container name") } if _, err := kubelet.validateContainerStatus(&api.PodStatus{ ContainerStatuses: testCases[0].statuses, }, containerName, true); err != nil { t.Errorf("unexpected error with for previous terminated container - %v", err) } if _, err := kubelet.validateContainerStatus(&api.PodStatus{ ContainerStatuses: testCases[1].statuses, }, containerName, true); err == nil { t.Errorf("expected error with for previous terminated container") } } func TestUpdateNewNodeStatus(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet kubeClient := testKubelet.fakeKubeClient kubeClient.ReactionChain = testclient.NewSimpleFake(&api.NodeList{Items: []api.Node{ {ObjectMeta: api.ObjectMeta{Name: testKubeletHostname}}, }}).ReactionChain machineInfo := &cadvisorApi.MachineInfo{ MachineID: "123", SystemUUID: "abc", BootID: "1b3", NumCores: 2, MemoryCapacity: 1024, } mockCadvisor := testKubelet.fakeCadvisor mockCadvisor.On("MachineInfo").Return(machineInfo, nil) versionInfo := &cadvisorApi.VersionInfo{ KernelVersion: "3.16.0-0.bpo.4-amd64", ContainerOsVersion: "Debian GNU/Linux 7 (wheezy)", DockerVersion: "1.5.0", } mockCadvisor.On("VersionInfo").Return(versionInfo, nil) expectedNode := &api.Node{ ObjectMeta: api.ObjectMeta{Name: testKubeletHostname}, Spec: api.NodeSpec{}, Status: api.NodeStatus{ Conditions: []api.NodeCondition{ { Type: api.NodeReady, Status: api.ConditionTrue, Reason: fmt.Sprintf("kubelet is posting ready status"), LastHeartbeatTime: util.Time{}, LastTransitionTime: util.Time{}, }, }, NodeInfo: api.NodeSystemInfo{ MachineID: "123", SystemUUID: "abc", BootID: "1b3", KernelVersion: "3.16.0-0.bpo.4-amd64", OsImage: "Debian GNU/Linux 7 (wheezy)", ContainerRuntimeVersion: "docker://1.5.0", KubeletVersion: version.Get().String(), KubeProxyVersion: version.Get().String(), }, Capacity: api.ResourceList{ api.ResourceCPU: *resource.NewMilliQuantity(2000, resource.DecimalSI), api.ResourceMemory: *resource.NewQuantity(1024, resource.BinarySI), api.ResourcePods: *resource.NewQuantity(0, resource.DecimalSI), }, Addresses: []api.NodeAddress{ {Type: api.NodeLegacyHostIP, Address: "127.0.0.1"}, {Type: api.NodeInternalIP, Address: "127.0.0.1"}, }, }, } kubelet.updateRuntimeUp() if err := kubelet.updateNodeStatus(); err != nil { t.Errorf("unexpected error: %v", err) } actions := kubeClient.Actions() if len(actions) != 2 { t.Fatalf("unexpected actions: %v", actions) } if !actions[1].Matches("update", "nodes") || actions[1].GetSubresource() != "status" { t.Fatalf("unexpected actions: %v", actions) } updatedNode, ok := actions[1].(testclient.UpdateAction).GetObject().(*api.Node) if !ok { t.Errorf("unexpected object type") } if updatedNode.Status.Conditions[0].LastHeartbeatTime.IsZero() { t.Errorf("unexpected zero last probe timestamp") } if updatedNode.Status.Conditions[0].LastTransitionTime.IsZero() { t.Errorf("unexpected zero last transition timestamp") } updatedNode.Status.Conditions[0].LastHeartbeatTime = util.Time{} updatedNode.Status.Conditions[0].LastTransitionTime = util.Time{} if !reflect.DeepEqual(expectedNode, updatedNode) { t.Errorf("unexpected objects: %s", util.ObjectDiff(expectedNode, updatedNode)) } } func TestUpdateExistingNodeStatus(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet kubeClient := testKubelet.fakeKubeClient kubeClient.ReactionChain = testclient.NewSimpleFake(&api.NodeList{Items: []api.Node{ { ObjectMeta: api.ObjectMeta{Name: testKubeletHostname}, Spec: api.NodeSpec{}, Status: api.NodeStatus{ Conditions: []api.NodeCondition{ { Type: api.NodeReady, Status: api.ConditionTrue, Reason: fmt.Sprintf("kubelet is posting ready status"), LastHeartbeatTime: util.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), LastTransitionTime: util.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), }, }, Capacity: api.ResourceList{ api.ResourceCPU: *resource.NewMilliQuantity(3000, resource.DecimalSI), api.ResourceMemory: *resource.NewQuantity(2048, resource.BinarySI), api.ResourcePods: *resource.NewQuantity(0, resource.DecimalSI), }, }, }, }}).ReactionChain mockCadvisor := testKubelet.fakeCadvisor machineInfo := &cadvisorApi.MachineInfo{ MachineID: "123", SystemUUID: "abc", BootID: "1b3", NumCores: 2, MemoryCapacity: 1024, } mockCadvisor.On("MachineInfo").Return(machineInfo, nil) versionInfo := &cadvisorApi.VersionInfo{ KernelVersion: "3.16.0-0.bpo.4-amd64", ContainerOsVersion: "Debian GNU/Linux 7 (wheezy)", DockerVersion: "1.5.0", } mockCadvisor.On("VersionInfo").Return(versionInfo, nil) expectedNode := &api.Node{ ObjectMeta: api.ObjectMeta{Name: testKubeletHostname}, Spec: api.NodeSpec{}, Status: api.NodeStatus{ Conditions: []api.NodeCondition{ { Type: api.NodeReady, Status: api.ConditionTrue, Reason: fmt.Sprintf("kubelet is posting ready status"), LastHeartbeatTime: util.Time{}, // placeholder LastTransitionTime: util.Time{}, // placeholder }, }, NodeInfo: api.NodeSystemInfo{ MachineID: "123", SystemUUID: "abc", BootID: "1b3", KernelVersion: "3.16.0-0.bpo.4-amd64", OsImage: "Debian GNU/Linux 7 (wheezy)", ContainerRuntimeVersion: "docker://1.5.0", KubeletVersion: version.Get().String(), KubeProxyVersion: version.Get().String(), }, Capacity: api.ResourceList{ api.ResourceCPU: *resource.NewMilliQuantity(2000, resource.DecimalSI), api.ResourceMemory: *resource.NewQuantity(1024, resource.BinarySI), api.ResourcePods: *resource.NewQuantity(0, resource.DecimalSI), }, Addresses: []api.NodeAddress{ {Type: api.NodeLegacyHostIP, Address: "127.0.0.1"}, {Type: api.NodeInternalIP, Address: "127.0.0.1"}, }, }, } kubelet.updateRuntimeUp() if err := kubelet.updateNodeStatus(); err != nil { t.Errorf("unexpected error: %v", err) } actions := kubeClient.Actions() if len(actions) != 2 { t.Errorf("unexpected actions: %v", actions) } updateAction, ok := actions[1].(testclient.UpdateAction) if !ok { t.Errorf("unexpected action type. expected UpdateAction, got %#v", actions[1]) } updatedNode, ok := updateAction.GetObject().(*api.Node) if !ok { t.Errorf("unexpected object type") } // Expect LastProbeTime to be updated to Now, while LastTransitionTime to be the same. if reflect.DeepEqual(updatedNode.Status.Conditions[0].LastHeartbeatTime.Rfc3339Copy().UTC(), util.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC).Time) { t.Errorf("expected \n%v\n, got \n%v", util.Now(), util.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC)) } if !reflect.DeepEqual(updatedNode.Status.Conditions[0].LastTransitionTime.Rfc3339Copy().UTC(), util.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC).Time) { t.Errorf("expected \n%#v\n, got \n%#v", updatedNode.Status.Conditions[0].LastTransitionTime.Rfc3339Copy(), util.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC)) } updatedNode.Status.Conditions[0].LastHeartbeatTime = util.Time{} updatedNode.Status.Conditions[0].LastTransitionTime = util.Time{} if !reflect.DeepEqual(expectedNode, updatedNode) { t.Errorf("expected \n%v\n, got \n%v", expectedNode, updatedNode) } } func TestUpdateNodeStatusWithoutContainerRuntime(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet kubeClient := testKubelet.fakeKubeClient fakeRuntime := testKubelet.fakeRuntime // This causes returning an error from GetContainerRuntimeVersion() which // simulates that container runtime is down. fakeRuntime.VersionInfo = "" kubeClient.ReactionChain = testclient.NewSimpleFake(&api.NodeList{Items: []api.Node{ {ObjectMeta: api.ObjectMeta{Name: testKubeletHostname}}, }}).ReactionChain mockCadvisor := testKubelet.fakeCadvisor machineInfo := &cadvisorApi.MachineInfo{ MachineID: "123", SystemUUID: "abc", BootID: "1b3", NumCores: 2, MemoryCapacity: 1024, } mockCadvisor.On("MachineInfo").Return(machineInfo, nil) versionInfo := &cadvisorApi.VersionInfo{ KernelVersion: "3.16.0-0.bpo.4-amd64", ContainerOsVersion: "Debian GNU/Linux 7 (wheezy)", DockerVersion: "1.5.0", } mockCadvisor.On("VersionInfo").Return(versionInfo, nil) expectedNode := &api.Node{ ObjectMeta: api.ObjectMeta{Name: testKubeletHostname}, Spec: api.NodeSpec{}, Status: api.NodeStatus{ Conditions: []api.NodeCondition{ { Type: api.NodeReady, Status: api.ConditionFalse, Reason: fmt.Sprintf("container runtime is down"), LastHeartbeatTime: util.Time{}, LastTransitionTime: util.Time{}, }, }, NodeInfo: api.NodeSystemInfo{ MachineID: "123", SystemUUID: "abc", BootID: "1b3", KernelVersion: "3.16.0-0.bpo.4-amd64", OsImage: "Debian GNU/Linux 7 (wheezy)", ContainerRuntimeVersion: "docker://1.5.0", KubeletVersion: version.Get().String(), KubeProxyVersion: version.Get().String(), }, Capacity: api.ResourceList{ api.ResourceCPU: *resource.NewMilliQuantity(2000, resource.DecimalSI), api.ResourceMemory: *resource.NewQuantity(1024, resource.BinarySI), api.ResourcePods: *resource.NewQuantity(0, resource.DecimalSI), }, Addresses: []api.NodeAddress{ {Type: api.NodeLegacyHostIP, Address: "127.0.0.1"}, {Type: api.NodeInternalIP, Address: "127.0.0.1"}, }, }, } kubelet.runtimeUpThreshold = time.Duration(0) kubelet.updateRuntimeUp() if err := kubelet.updateNodeStatus(); err != nil { t.Errorf("unexpected error: %v", err) } actions := kubeClient.Actions() if len(actions) != 2 { t.Fatalf("unexpected actions: %v", actions) } if !actions[1].Matches("update", "nodes") || actions[1].GetSubresource() != "status" { t.Fatalf("unexpected actions: %v", actions) } updatedNode, ok := actions[1].(testclient.UpdateAction).GetObject().(*api.Node) if !ok { t.Errorf("unexpected action type. expected UpdateAction, got %#v", actions[1]) } if updatedNode.Status.Conditions[0].LastHeartbeatTime.IsZero() { t.Errorf("unexpected zero last probe timestamp") } if updatedNode.Status.Conditions[0].LastTransitionTime.IsZero() { t.Errorf("unexpected zero last transition timestamp") } updatedNode.Status.Conditions[0].LastHeartbeatTime = util.Time{} updatedNode.Status.Conditions[0].LastTransitionTime = util.Time{} if !reflect.DeepEqual(expectedNode, updatedNode) { t.Errorf("unexpected objects: %s", util.ObjectDiff(expectedNode, updatedNode)) } } func TestUpdateNodeStatusError(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet // No matching node for the kubelet testKubelet.fakeKubeClient.ReactionChain = testclient.NewSimpleFake(&api.NodeList{Items: []api.Node{}}).ReactionChain if err := kubelet.updateNodeStatus(); err == nil { t.Errorf("unexpected non error: %v", err) } if len(testKubelet.fakeKubeClient.Actions()) != nodeStatusUpdateRetry { t.Errorf("unexpected actions: %v", testKubelet.fakeKubeClient.Actions()) } } func TestCreateMirrorPod(t *testing.T) { for _, updateType := range []SyncPodType{SyncPodCreate, SyncPodUpdate} { testKubelet := newTestKubelet(t) kl := testKubelet.kubelet manager := testKubelet.fakeMirrorClient pod := &api.Pod{ ObjectMeta: api.ObjectMeta{ UID: "12345678", Name: "bar", Namespace: "foo", Annotations: map[string]string{ ConfigSourceAnnotationKey: "file", }, }, } pods := []*api.Pod{pod} kl.podManager.SetPods(pods) err := kl.syncPod(pod, nil, container.Pod{}, updateType) if err != nil { t.Errorf("unexpected error: %v", err) } podFullName := kubecontainer.GetPodFullName(pod) if !manager.HasPod(podFullName) { t.Errorf("expected mirror pod %q to be created", podFullName) } if manager.NumOfPods() != 1 || !manager.HasPod(podFullName) { t.Errorf("expected one mirror pod %q, got %v", podFullName, manager.GetPods()) } } } func TestDeleteOutdatedMirrorPod(t *testing.T) { testKubelet := newTestKubelet(t) testKubelet.fakeCadvisor.On("MachineInfo").Return(&cadvisorApi.MachineInfo{}, nil) testKubelet.fakeCadvisor.On("DockerImagesFsInfo").Return(cadvisorApiv2.FsInfo{}, nil) testKubelet.fakeCadvisor.On("RootFsInfo").Return(cadvisorApiv2.FsInfo{}, nil) kl := testKubelet.kubelet manager := testKubelet.fakeMirrorClient pod := &api.Pod{ ObjectMeta: api.ObjectMeta{ UID: "12345678", Name: "foo", Namespace: "ns", Annotations: map[string]string{ ConfigSourceAnnotationKey: "file", }, }, Spec: api.PodSpec{ Containers: []api.Container{ {Name: "1234", Image: "foo"}, }, }, } // Mirror pod has an outdated spec. mirrorPod := &api.Pod{ ObjectMeta: api.ObjectMeta{ UID: "11111111", Name: "foo", Namespace: "ns", Annotations: map[string]string{ ConfigSourceAnnotationKey: "api", ConfigMirrorAnnotationKey: "mirror", }, }, Spec: api.PodSpec{ Containers: []api.Container{ {Name: "1234", Image: "bar"}, }, }, } pods := []*api.Pod{pod, mirrorPod} kl.podManager.SetPods(pods) err := kl.syncPod(pod, mirrorPod, container.Pod{}, SyncPodUpdate) if err != nil { t.Errorf("unexpected error: %v", err) } name := kubecontainer.GetPodFullName(pod) creates, deletes := manager.GetCounts(name) if creates != 0 || deletes != 1 { t.Errorf("expected 0 creation and 1 deletion of %q, got %d, %d", name, creates, deletes) } } func TestDeleteOrphanedMirrorPods(t *testing.T) { testKubelet := newTestKubelet(t) testKubelet.fakeCadvisor.On("MachineInfo").Return(&cadvisorApi.MachineInfo{}, nil) testKubelet.fakeCadvisor.On("DockerImagesFsInfo").Return(cadvisorApiv2.FsInfo{}, nil) testKubelet.fakeCadvisor.On("RootFsInfo").Return(cadvisorApiv2.FsInfo{}, nil) kl := testKubelet.kubelet manager := testKubelet.fakeMirrorClient orphanPods := []*api.Pod{ { ObjectMeta: api.ObjectMeta{ UID: "12345678", Name: "pod1", Namespace: "ns", Annotations: map[string]string{ ConfigSourceAnnotationKey: "api", ConfigMirrorAnnotationKey: "mirror", }, }, }, { ObjectMeta: api.ObjectMeta{ UID: "12345679", Name: "pod2", Namespace: "ns", Annotations: map[string]string{ ConfigSourceAnnotationKey: "api", ConfigMirrorAnnotationKey: "mirror", }, }, }, } kl.podManager.SetPods(orphanPods) // Sync with an empty pod list to delete all mirror pods. kl.HandlePodCleanups() if manager.NumOfPods() != 0 { t.Errorf("expected zero mirror pods, got %v", manager.GetPods()) } for _, pod := range orphanPods { name := kubecontainer.GetPodFullName(pod) creates, deletes := manager.GetCounts(name) if creates != 0 || deletes != 1 { t.Errorf("expected 0 creation and one deletion of %q, got %d, %d", name, creates, deletes) } } } func TestGetContainerInfoForMirrorPods(t *testing.T) { // pods contain one static and one mirror pod with the same name but // different UIDs. pods := []*api.Pod{ { ObjectMeta: api.ObjectMeta{ UID: "1234", Name: "qux", Namespace: "ns", Annotations: map[string]string{ ConfigSourceAnnotationKey: "file", }, }, Spec: api.PodSpec{ Containers: []api.Container{ {Name: "foo"}, }, }, }, { ObjectMeta: api.ObjectMeta{ UID: "5678", Name: "qux", Namespace: "ns", Annotations: map[string]string{ ConfigSourceAnnotationKey: "api", ConfigMirrorAnnotationKey: "mirror", }, }, Spec: api.PodSpec{ Containers: []api.Container{ {Name: "foo"}, }, }, }, } containerID := "ab2cdf" containerPath := fmt.Sprintf("/docker/%v", containerID) containerInfo := cadvisorApi.ContainerInfo{ ContainerReference: cadvisorApi.ContainerReference{ Name: containerPath, }, } testKubelet := newTestKubelet(t) fakeRuntime := testKubelet.fakeRuntime mockCadvisor := testKubelet.fakeCadvisor cadvisorReq := &cadvisorApi.ContainerInfoRequest{} mockCadvisor.On("DockerContainer", containerID, cadvisorReq).Return(containerInfo, nil) kubelet := testKubelet.kubelet fakeRuntime.PodList = []*kubecontainer.Pod{ { ID: "1234", Name: "qux", Namespace: "ns", Containers: []*kubecontainer.Container{ { Name: "foo", ID: types.UID(containerID), }, }, }, } kubelet.podManager.SetPods(pods) // Use the mirror pod UID to retrieve the stats. stats, err := kubelet.GetContainerInfo("qux_ns", "5678", "foo", cadvisorReq) if err != nil { t.Errorf("unexpected error: %v", err) } if stats == nil { t.Fatalf("stats should not be nil") } mockCadvisor.AssertExpectations(t) } func TestDoNotCacheStatusForStaticPods(t *testing.T) { testKubelet := newTestKubelet(t) testKubelet.fakeCadvisor.On("MachineInfo").Return(&cadvisorApi.MachineInfo{}, nil) testKubelet.fakeCadvisor.On("DockerImagesFsInfo").Return(cadvisorApiv2.FsInfo{}, nil) testKubelet.fakeCadvisor.On("RootFsInfo").Return(cadvisorApiv2.FsInfo{}, nil) kubelet := testKubelet.kubelet pods := []*api.Pod{ { ObjectMeta: api.ObjectMeta{ UID: "12345678", Name: "staticFoo", Namespace: "new", Annotations: map[string]string{ ConfigSourceAnnotationKey: "file", }, }, Spec: api.PodSpec{ Containers: []api.Container{ {Name: "bar"}, }, }, }, } kubelet.podManager.SetPods(pods) kubelet.HandlePodSyncs(kubelet.podManager.GetPods()) status, ok := kubelet.statusManager.GetPodStatus(pods[0].UID) if ok { t.Errorf("unexpected status %#v found for static pod %q", status, pods[0].UID) } } func TestHostNetworkAllowed(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet capabilities.SetForTests(capabilities.Capabilities{ PrivilegedSources: capabilities.PrivilegedSources{ HostNetworkSources: []string{ApiserverSource, FileSource}, }, }) pod := &api.Pod{ ObjectMeta: api.ObjectMeta{ UID: "12345678", Name: "foo", Namespace: "new", Annotations: map[string]string{ ConfigSourceAnnotationKey: FileSource, }, }, Spec: api.PodSpec{ Containers: []api.Container{ {Name: "foo"}, }, HostNetwork: true, }, } kubelet.podManager.SetPods([]*api.Pod{pod}) err := kubelet.syncPod(pod, nil, container.Pod{}, SyncPodUpdate) if err != nil { t.Errorf("expected pod infra creation to succeed: %v", err) } } func TestHostNetworkDisallowed(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet capabilities.SetForTests(capabilities.Capabilities{ PrivilegedSources: capabilities.PrivilegedSources{ HostNetworkSources: []string{}, }, }) pod := &api.Pod{ ObjectMeta: api.ObjectMeta{ UID: "12345678", Name: "foo", Namespace: "new", Annotations: map[string]string{ ConfigSourceAnnotationKey: FileSource, }, }, Spec: api.PodSpec{ Containers: []api.Container{ {Name: "foo"}, }, HostNetwork: true, }, } err := kubelet.syncPod(pod, nil, container.Pod{}, SyncPodUpdate) if err == nil { t.Errorf("expected pod infra creation to fail") } } func TestPrivilegeContainerAllowed(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet capabilities.SetForTests(capabilities.Capabilities{ AllowPrivileged: true, }) privileged := true pod := &api.Pod{ ObjectMeta: api.ObjectMeta{ UID: "12345678", Name: "foo", Namespace: "new", }, Spec: api.PodSpec{ Containers: []api.Container{ {Name: "foo", SecurityContext: &api.SecurityContext{Privileged: &privileged}}, }, }, } kubelet.podManager.SetPods([]*api.Pod{pod}) err := kubelet.syncPod(pod, nil, container.Pod{}, SyncPodUpdate) if err != nil { t.Errorf("expected pod infra creation to succeed: %v", err) } } func TestPrivilegeContainerDisallowed(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet capabilities.SetForTests(capabilities.Capabilities{ AllowPrivileged: false, }) privileged := true pod := &api.Pod{ ObjectMeta: api.ObjectMeta{ UID: "12345678", Name: "foo", Namespace: "new", }, Spec: api.PodSpec{ Containers: []api.Container{ {Name: "foo", SecurityContext: &api.SecurityContext{Privileged: &privileged}}, }, }, } err := kubelet.syncPod(pod, nil, container.Pod{}, SyncPodUpdate) if err == nil { t.Errorf("expected pod infra creation to fail") } } func TestFilterOutTerminatedPods(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet pods := newTestPods(5) pods[0].Status.Phase = api.PodFailed pods[1].Status.Phase = api.PodSucceeded pods[2].Status.Phase = api.PodRunning pods[3].Status.Phase = api.PodPending expected := []*api.Pod{pods[2], pods[3], pods[4]} kubelet.podManager.SetPods(pods) actual := kubelet.filterOutTerminatedPods(pods) if !reflect.DeepEqual(expected, actual) { t.Errorf("expected %#v, got %#v", expected, actual) } } func TestRegisterExistingNodeWithApiserver(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet kubeClient := testKubelet.fakeKubeClient kubeClient.AddReactor("create", "nodes", func(action testclient.Action) (bool, runtime.Object, error) { // Return an error on create. return true, &api.Node{}, &apierrors.StatusError{ ErrStatus: api.Status{Reason: api.StatusReasonAlreadyExists}, } }) kubeClient.AddReactor("get", "nodes", func(action testclient.Action) (bool, runtime.Object, error) { // Return an existing (matching) node on get. return true, &api.Node{ ObjectMeta: api.ObjectMeta{Name: testKubeletHostname}, Spec: api.NodeSpec{ExternalID: testKubeletHostname}, }, nil }) kubeClient.AddReactor("*", "*", func(action testclient.Action) (bool, runtime.Object, error) { return true, nil, fmt.Errorf("no reaction implemented for %s", action) }) machineInfo := &cadvisorApi.MachineInfo{ MachineID: "123", SystemUUID: "abc", BootID: "1b3", NumCores: 2, MemoryCapacity: 1024, } mockCadvisor := testKubelet.fakeCadvisor mockCadvisor.On("MachineInfo").Return(machineInfo, nil) versionInfo := &cadvisorApi.VersionInfo{ KernelVersion: "3.16.0-0.bpo.4-amd64", ContainerOsVersion: "Debian GNU/Linux 7 (wheezy)", DockerVersion: "1.5.0", } mockCadvisor.On("VersionInfo").Return(versionInfo, nil) done := make(chan struct{}) go func() { kubelet.registerWithApiserver() done <- struct{}{} }() select { case <-time.After(5 * time.Second): t.Errorf("timed out waiting for registration") case <-done: return } } func TestMakePortMappings(t *testing.T) { tests := []struct { container *api.Container expectedPortMappings []kubecontainer.PortMapping }{ { &api.Container{ Name: "fooContainer", Ports: []api.ContainerPort{ { Protocol: api.ProtocolTCP, ContainerPort: 80, HostPort: 8080, HostIP: "127.0.0.1", }, { Protocol: api.ProtocolTCP, ContainerPort: 443, HostPort: 4343, HostIP: "192.168.0.1", }, { Name: "foo", Protocol: api.ProtocolUDP, ContainerPort: 555, HostPort: 5555, }, { Name: "foo", // Duplicated, should be ignored. Protocol: api.ProtocolUDP, ContainerPort: 888, HostPort: 8888, }, { Protocol: api.ProtocolTCP, // Duplicated, should be ignored. ContainerPort: 80, HostPort: 8888, }, }, }, []kubecontainer.PortMapping{ { Name: "fooContainer-TCP:80", Protocol: api.ProtocolTCP, ContainerPort: 80, HostPort: 8080, HostIP: "127.0.0.1", }, { Name: "fooContainer-TCP:443", Protocol: api.ProtocolTCP, ContainerPort: 443, HostPort: 4343, HostIP: "192.168.0.1", }, { Name: "fooContainer-foo", Protocol: api.ProtocolUDP, ContainerPort: 555, HostPort: 5555, HostIP: "", }, }, }, } for i, tt := range tests { actual := makePortMappings(tt.container) if !reflect.DeepEqual(tt.expectedPortMappings, actual) { t.Errorf("%d: Expected: %#v, saw: %#v", i, tt.expectedPortMappings, actual) } } } func TestIsPodPastActiveDeadline(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet pods := newTestPods(5) exceededActiveDeadlineSeconds := int64(30) notYetActiveDeadlineSeconds := int64(120) now := util.Now() startTime := util.NewTime(now.Time.Add(-1 * time.Minute)) pods[0].Status.StartTime = &startTime pods[0].Spec.ActiveDeadlineSeconds = &exceededActiveDeadlineSeconds pods[1].Status.StartTime = &startTime pods[1].Spec.ActiveDeadlineSeconds = &notYetActiveDeadlineSeconds tests := []struct { pod *api.Pod expected bool }{{pods[0], true}, {pods[1], false}, {pods[2], false}, {pods[3], false}, {pods[4], false}} kubelet.podManager.SetPods(pods) for i, tt := range tests { actual := kubelet.pastActiveDeadline(tt.pod) if actual != tt.expected { t.Errorf("[%d] expected %#v, got %#v", i, tt.expected, actual) } } } func TestSyncPodsSetStatusToFailedForPodsThatRunTooLong(t *testing.T) { testKubelet := newTestKubelet(t) fakeRuntime := testKubelet.fakeRuntime testKubelet.fakeCadvisor.On("MachineInfo").Return(&cadvisorApi.MachineInfo{}, nil) kubelet := testKubelet.kubelet now := util.Now() startTime := util.NewTime(now.Time.Add(-1 * time.Minute)) exceededActiveDeadlineSeconds := int64(30) pods := []*api.Pod{ { ObjectMeta: api.ObjectMeta{ UID: "12345678", Name: "bar", Namespace: "new", }, Spec: api.PodSpec{ Containers: []api.Container{ {Name: "foo"}, }, ActiveDeadlineSeconds: &exceededActiveDeadlineSeconds, }, Status: api.PodStatus{ StartTime: &startTime, }, }, } fakeRuntime.PodList = []*kubecontainer.Pod{ { ID: "12345678", Name: "bar", Namespace: "new", Containers: []*kubecontainer.Container{ {Name: "foo"}, }, }, } // Let the pod worker sets the status to fail after this sync. kubelet.HandlePodUpdates(pods) status, found := kubelet.statusManager.GetPodStatus(pods[0].UID) if !found { t.Errorf("expected to found status for pod %q", pods[0].UID) } if status.Phase != api.PodFailed { t.Fatalf("expected pod status %q, ot %q.", api.PodFailed, status.Phase) } } func TestSyncPodsDoesNotSetPodsThatDidNotRunTooLongToFailed(t *testing.T) { testKubelet := newTestKubelet(t) fakeRuntime := testKubelet.fakeRuntime testKubelet.fakeCadvisor.On("MachineInfo").Return(&cadvisorApi.MachineInfo{}, nil) kubelet := testKubelet.kubelet now := util.Now() startTime := util.NewTime(now.Time.Add(-1 * time.Minute)) exceededActiveDeadlineSeconds := int64(300) pods := []*api.Pod{ { ObjectMeta: api.ObjectMeta{ UID: "12345678", Name: "bar", Namespace: "new", }, Spec: api.PodSpec{ Containers: []api.Container{ {Name: "foo"}, }, ActiveDeadlineSeconds: &exceededActiveDeadlineSeconds, }, Status: api.PodStatus{ StartTime: &startTime, }, }, } fakeRuntime.PodList = []*kubecontainer.Pod{ { ID: "12345678", Name: "bar", Namespace: "new", Containers: []*kubecontainer.Container{ {Name: "foo"}, }, }, } kubelet.podManager.SetPods(pods) kubelet.HandlePodUpdates(pods) status, found := kubelet.statusManager.GetPodStatus(pods[0].UID) if !found { t.Errorf("expected to found status for pod %q", pods[0].UID) } if status.Phase == api.PodFailed { t.Fatalf("expected pod status to not be %q", status.Phase) } } func TestDeletePodDirsForDeletedPods(t *testing.T) { testKubelet := newTestKubelet(t) testKubelet.fakeCadvisor.On("MachineInfo").Return(&cadvisorApi.MachineInfo{}, nil) testKubelet.fakeCadvisor.On("DockerImagesFsInfo").Return(cadvisorApiv2.FsInfo{}, nil) testKubelet.fakeCadvisor.On("RootFsInfo").Return(cadvisorApiv2.FsInfo{}, nil) kl := testKubelet.kubelet pods := []*api.Pod{ { ObjectMeta: api.ObjectMeta{ UID: "12345678", Name: "pod1", Namespace: "ns", }, }, { ObjectMeta: api.ObjectMeta{ UID: "12345679", Name: "pod2", Namespace: "ns", }, }, } kl.podManager.SetPods(pods) // Sync to create pod directories. kl.HandlePodSyncs(kl.podManager.GetPods()) for i := range pods { if !dirExists(kl.getPodDir(pods[i].UID)) { t.Errorf("expected directory to exist for pod %d", i) } } // Pod 1 has been deleted and no longer exists. kl.podManager.SetPods([]*api.Pod{pods[0]}) kl.HandlePodCleanups() if !dirExists(kl.getPodDir(pods[0].UID)) { t.Errorf("expected directory to exist for pod 0") } if dirExists(kl.getPodDir(pods[1].UID)) { t.Errorf("expected directory to be deleted for pod 1") } } func syncAndVerifyPodDir(t *testing.T, testKubelet *TestKubelet, pods []*api.Pod, podsToCheck []*api.Pod, shouldExist bool) { kl := testKubelet.kubelet kl.podManager.SetPods(pods) kl.HandlePodSyncs(pods) kl.HandlePodCleanups() for i, pod := range podsToCheck { exist := dirExists(kl.getPodDir(pod.UID)) if shouldExist && !exist { t.Errorf("expected directory to exist for pod %d", i) } else if !shouldExist && exist { t.Errorf("expected directory to be removed for pod %d", i) } } } func TestDoesNotDeletePodDirsForTerminatedPods(t *testing.T) { testKubelet := newTestKubelet(t) testKubelet.fakeCadvisor.On("MachineInfo").Return(&cadvisorApi.MachineInfo{}, nil) testKubelet.fakeCadvisor.On("DockerImagesFsInfo").Return(cadvisorApiv2.FsInfo{}, nil) testKubelet.fakeCadvisor.On("RootFsInfo").Return(cadvisorApiv2.FsInfo{}, nil) kl := testKubelet.kubelet pods := []*api.Pod{ { ObjectMeta: api.ObjectMeta{ UID: "12345678", Name: "pod1", Namespace: "ns", }, }, { ObjectMeta: api.ObjectMeta{ UID: "12345679", Name: "pod2", Namespace: "ns", }, }, { ObjectMeta: api.ObjectMeta{ UID: "12345680", Name: "pod3", Namespace: "ns", }, }, } syncAndVerifyPodDir(t, testKubelet, pods, pods, true) // Pod 1 failed, and pod 2 succeeded. None of the pod directories should be // deleted. kl.statusManager.SetPodStatus(pods[1], api.PodStatus{Phase: api.PodFailed}) kl.statusManager.SetPodStatus(pods[2], api.PodStatus{Phase: api.PodSucceeded}) syncAndVerifyPodDir(t, testKubelet, pods, pods, true) } func TestDoesNotDeletePodDirsIfContainerIsRunning(t *testing.T) { testKubelet := newTestKubelet(t) testKubelet.fakeCadvisor.On("MachineInfo").Return(&cadvisorApi.MachineInfo{}, nil) testKubelet.fakeCadvisor.On("DockerImagesFsInfo").Return(cadvisorApiv2.FsInfo{}, nil) testKubelet.fakeCadvisor.On("RootFsInfo").Return(cadvisorApiv2.FsInfo{}, nil) runningPod := &kubecontainer.Pod{ ID: "12345678", Name: "pod1", Namespace: "ns", } apiPod := &api.Pod{ ObjectMeta: api.ObjectMeta{ UID: runningPod.ID, Name: runningPod.Name, Namespace: runningPod.Namespace, }, } // Sync once to create pod directory; confirm that the pod directory has // already been created. pods := []*api.Pod{apiPod} syncAndVerifyPodDir(t, testKubelet, pods, []*api.Pod{apiPod}, true) // Pretend the pod is deleted from apiserver, but is still active on the node. // The pod directory should not be removed. pods = []*api.Pod{} testKubelet.fakeRuntime.PodList = []*kubecontainer.Pod{runningPod} syncAndVerifyPodDir(t, testKubelet, pods, []*api.Pod{apiPod}, true) // The pod is deleted and also not active on the node. The pod directory // should be removed. pods = []*api.Pod{} testKubelet.fakeRuntime.PodList = []*kubecontainer.Pod{} syncAndVerifyPodDir(t, testKubelet, pods, []*api.Pod{apiPod}, false) } func TestCleanupBandwidthLimits(t *testing.T) { tests := []struct { status *api.PodStatus pods []*api.Pod inputCIDRs []string expectResetCIDRs []string cacheStatus bool expectedCalls []string name string }{ { status: &api.PodStatus{ PodIP: "1.2.3.4", Phase: api.PodRunning, }, pods: []*api.Pod{ { ObjectMeta: api.ObjectMeta{ Name: "foo", Annotations: map[string]string{ "kubernetes.io/ingress-bandwidth": "10M", }, }, }, { ObjectMeta: api.ObjectMeta{ Name: "bar", }, }, }, inputCIDRs: []string{"1.2.3.4/32", "2.3.4.5/32", "5.6.7.8/32"}, expectResetCIDRs: []string{"2.3.4.5/32", "5.6.7.8/32"}, expectedCalls: []string{"GetPodStatus"}, name: "pod running", }, { status: &api.PodStatus{ PodIP: "1.2.3.4", Phase: api.PodRunning, }, pods: []*api.Pod{ { ObjectMeta: api.ObjectMeta{ Name: "foo", Annotations: map[string]string{ "kubernetes.io/ingress-bandwidth": "10M", }, }, }, { ObjectMeta: api.ObjectMeta{ Name: "bar", }, }, }, inputCIDRs: []string{"1.2.3.4/32", "2.3.4.5/32", "5.6.7.8/32"}, expectResetCIDRs: []string{"2.3.4.5/32", "5.6.7.8/32"}, expectedCalls: []string{}, cacheStatus: true, name: "pod running with cache", }, { status: &api.PodStatus{ PodIP: "1.2.3.4", Phase: api.PodFailed, }, pods: []*api.Pod{ { ObjectMeta: api.ObjectMeta{ Name: "foo", Annotations: map[string]string{ "kubernetes.io/ingress-bandwidth": "10M", }, }, }, { ObjectMeta: api.ObjectMeta{ Name: "bar", }, }, }, inputCIDRs: []string{"1.2.3.4/32", "2.3.4.5/32", "5.6.7.8/32"}, expectResetCIDRs: []string{"1.2.3.4/32", "2.3.4.5/32", "5.6.7.8/32"}, expectedCalls: []string{"GetPodStatus"}, name: "pod not running", }, { status: &api.PodStatus{ PodIP: "1.2.3.4", Phase: api.PodFailed, }, pods: []*api.Pod{ { ObjectMeta: api.ObjectMeta{ Name: "foo", Annotations: map[string]string{ "kubernetes.io/ingress-bandwidth": "10M", }, }, }, { ObjectMeta: api.ObjectMeta{ Name: "bar", }, }, }, inputCIDRs: []string{"1.2.3.4/32", "2.3.4.5/32", "5.6.7.8/32"}, expectResetCIDRs: []string{"1.2.3.4/32", "2.3.4.5/32", "5.6.7.8/32"}, expectedCalls: []string{}, cacheStatus: true, name: "pod not running with cache", }, { status: &api.PodStatus{ PodIP: "1.2.3.4", Phase: api.PodRunning, }, pods: []*api.Pod{ { ObjectMeta: api.ObjectMeta{ Name: "foo", }, }, { ObjectMeta: api.ObjectMeta{ Name: "bar", }, }, }, inputCIDRs: []string{"1.2.3.4/32", "2.3.4.5/32", "5.6.7.8/32"}, expectResetCIDRs: []string{"1.2.3.4/32", "2.3.4.5/32", "5.6.7.8/32"}, name: "no bandwidth limits", }, } for _, test := range tests { shaper := &bandwidth.FakeShaper{ CIDRs: test.inputCIDRs, } testKube := newTestKubelet(t) testKube.kubelet.shaper = shaper testKube.fakeRuntime.PodStatus = *test.status if test.cacheStatus { for _, pod := range test.pods { testKube.kubelet.statusManager.SetPodStatus(pod, *test.status) } } err := testKube.kubelet.cleanupBandwidthLimits(test.pods) if err != nil { t.Errorf("unexpected error: %v (%s)", test.name) } if !reflect.DeepEqual(shaper.ResetCIDRs, test.expectResetCIDRs) { t.Errorf("[%s]\nexpected: %v, saw: %v", test.name, test.expectResetCIDRs, shaper.ResetCIDRs) } if test.cacheStatus { if len(testKube.fakeRuntime.CalledFunctions) != 0 { t.Errorf("unexpected function calls: %v", testKube.fakeRuntime.CalledFunctions) } } else if !reflect.DeepEqual(testKube.fakeRuntime.CalledFunctions, test.expectedCalls) { t.Errorf("[%s], expected %v, saw %v", test.name, test.expectedCalls, testKube.fakeRuntime.CalledFunctions) } } } func TestExtractBandwidthResources(t *testing.T) { four, _ := resource.ParseQuantity("4M") ten, _ := resource.ParseQuantity("10M") twenty, _ := resource.ParseQuantity("20M") tests := []struct { pod *api.Pod expectedIngress *resource.Quantity expectedEgress *resource.Quantity expectError bool }{ { pod: &api.Pod{}, }, { pod: &api.Pod{ ObjectMeta: api.ObjectMeta{ Annotations: map[string]string{ "kubernetes.io/ingress-bandwidth": "10M", }, }, }, expectedIngress: ten, }, { pod: &api.Pod{ ObjectMeta: api.ObjectMeta{ Annotations: map[string]string{ "kubernetes.io/egress-bandwidth": "10M", }, }, }, expectedEgress: ten, }, { pod: &api.Pod{ ObjectMeta: api.ObjectMeta{ Annotations: map[string]string{ "kubernetes.io/ingress-bandwidth": "4M", "kubernetes.io/egress-bandwidth": "20M", }, }, }, expectedIngress: four, expectedEgress: twenty, }, { pod: &api.Pod{ ObjectMeta: api.ObjectMeta{ Annotations: map[string]string{ "kubernetes.io/ingress-bandwidth": "foo", }, }, }, expectError: true, }, } for _, test := range tests { ingress, egress, err := extractBandwidthResources(test.pod) if test.expectError { if err == nil { t.Errorf("unexpected non-error") } continue } if err != nil { t.Errorf("unexpected error: %v", err) continue } if !reflect.DeepEqual(ingress, test.expectedIngress) { t.Errorf("expected: %v, saw: %v", ingress, test.expectedIngress) } if !reflect.DeepEqual(egress, test.expectedEgress) { t.Errorf("expected: %v, saw: %v", egress, test.expectedEgress) } } }
abdokh/kubernetes
pkg/kubelet/kubelet_test.go
GO
apache-2.0
102,547
package com.doglandia.animatingtextviewlib; 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); } }
ThomasKomarnicki/AnimatingTextView
app/src/androidTest/java/com/doglandia/animatingtextviewlib/ApplicationTest.java
Java
apache-2.0
365
# Involutinidae Butschli, 1880 FAMILY #### Status ACCEPTED #### According to Integrated Taxonomic Information System #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Protozoa/Granuloreticulosea/Foraminiferida/Involutinidae/README.md
Markdown
apache-2.0
185
/* * Copyright (C) 2017 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.seongil.mvplife.fragment; import android.os.Bundle; import android.view.View; import com.seongil.mvplife.base.MvpPresenter; import com.seongil.mvplife.base.MvpView; import com.seongil.mvplife.delegate.MvpDelegateCallback; import com.seongil.mvplife.delegate.fragment.MvpFragmentDelegate; import com.seongil.mvplife.delegate.fragment.MvpFragmentDelegateImpl; /** * Abstract class for the fragment which is holding a reference of the {@link MvpPresenter} * Also, holding a {@link MvpFragmentDelegate} which is handling the lifecycle of the fragment. * * @param <V> The type of {@link MvpView} * @param <P> The type of {@link MvpPresenter} * * @author seong-il, kim * @since 17. 1. 6 */ public abstract class BaseMvpFragment<V extends MvpView, P extends MvpPresenter<V>> extends CoreFragment implements MvpView, MvpDelegateCallback<V, P> { // ======================================================================== // Constants // ======================================================================== // ======================================================================== // Fields // ======================================================================== private MvpFragmentDelegate mFragmentDelegate; private P mPresenter; // ======================================================================== // Constructors // ======================================================================== // ======================================================================== // Getter & Setter // ======================================================================== // ======================================================================== // Methods for/from SuperClass/Interfaces // ======================================================================== @Override public abstract P createPresenter(); @Override public P getPresenter() { return mPresenter; } @Override public void setPresenter(P presenter) { mPresenter = presenter; } @Override @SuppressWarnings("unchecked") public V getMvpView() { return (V) this; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); getMvpDelegate().onViewCreated(view, savedInstanceState); } @Override public void onDestroyView() { getMvpDelegate().onDestroyView(); super.onDestroyView(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getMvpDelegate().onCreate(savedInstanceState); } @Override public void onDestroy() { super.onDestroy(); getMvpDelegate().onDestroy(); } // ======================================================================== // Methods // ======================================================================== protected MvpFragmentDelegate getMvpDelegate() { if (mFragmentDelegate == null) { mFragmentDelegate = new MvpFragmentDelegateImpl<>(this); } return mFragmentDelegate; } // ======================================================================== // Inner and Anonymous Classes // ======================================================================== }
allsoft777/MVP-with-Firebase
mvplife/src/main/java/com/seongil/mvplife/fragment/BaseMvpFragment.java
Java
apache-2.0
4,046
@media (min-width: 980px) { /*-----*/ .custom-bar-chart { margin-bottom: 40px; } } @media (min-width: 768px) and (max-width: 979px) { /*-----*/ .custom-bar-chart { margin-bottom: 40px; } /*chat room*/ } @media (max-width: 768px) { .header { position: absolute; } /*sidebar*/ #sidebar { height: auto; overflow: hidden; position: absolute; width: 100%; z-index: 1001; } /* body container */ #main-content { margin: 0px !important; position: none !important; } #sidebar > ul > li > a > span { line-height: 35px; } #sidebar > ul > li { margin: 0 10px 5px 10px; } #sidebar > ul > li > a { height: 35px; line-height: 35px; padding: 0 10px; text-align: left; } #sidebar > ul > li > a i { /*display: none !important;*/ } #sidebar ul > li > a .arrow, #sidebar > ul > li > a .arrow.open { margin-right: 10px; margin-top: 15px; } #sidebar ul > li.active > a .arrow, #sidebar ul > li > a:hover .arrow, #sidebar ul > li > a:focus .arrow, #sidebar > ul > li.active > a .arrow.open, #sidebar > ul > li > a:hover .arrow.open, #sidebar > ul > li > a:focus .arrow.open { margin-top: 15px; } #sidebar > ul > li > a, #sidebar > ul > li > ul.sub > li { width: 100%; } #sidebar > ul > li > ul.sub > li > a { background: transparent !important; } #sidebar > ul > li > ul.sub > li > a:hover { } /* sidebar */ #sidebar { margin: 0px !important; } /* sidebar collabler */ #sidebar .btn-navbar.collapsed .arrow { display: none; } #sidebar .btn-navbar .arrow { position: absolute; right: 35px; width: 0; height: 0; top: 48px; border-bottom: 15px solid #282e36; border-left: 15px solid transparent; border-right: 15px solid transparent; } /*---------*/ .modal-footer .btn { margin-bottom: 0px !important; } .btn { margin-bottom: 5px; } /* full calendar fix */ .fc-header-right { left: 25px; position: absolute; } .fc-header-left .fc-button { margin: 0px !important; top: -10px !important; } .fc-header-right .fc-button { margin: 0px !important; top: -50px !important; } .fc-state-active, .fc-state-active .fc-button-inner, .fc-state-hover, .fc-state-hover .fc-button-inner { background: none !important; color: #FFFFFF !important; } .fc-state-default, .fc-state-default .fc-button-inner { background: none !important; } .fc-button { border: none !important; margin-right: 2px; } .fc-view { top: 0px !important; } .fc-button .fc-button-inner { margin: 0px !important; padding: 2px !important; border: none !important; margin-right: 2px !important; background-color: #fafafa !important; background-image: -moz-linear-gradient(top, #fafafa, #efefef) !important; background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#fafafa), to(#efefef)) !important; background-image: -webkit-linear-gradient(top, #fafafa, #efefef) !important; background-image: -o-linear-gradient(top, #fafafa, #efefef) !important; background-image: linear-gradient(to bottom, #fafafa, #efefef) !important; filter: progid:dximagetransform.microsoft.gradient(startColorstr='#fafafa', endColorstr='#efefef', GradientType=0) !important; -webkit-box-shadow: 0 1px 0px rgba(255, 255, 255, .8) !important; -moz-box-shadow: 0 1px 0px rgba(255, 255, 255, .8) !important; box-shadow: 0 1px 0px rgba(255, 255, 255, .8) !important; -webkit-border-radius: 3px !important; -moz-border-radius: 3px !important; border-radius: 3px !important; color: #646464 !important; border: 1px solid #ddd !important; text-shadow: 0 1px 0px rgba(255, 255, 255, .6) !important; text-align: center; } .fc-button.fc-state-disabled .fc-button-inner { color: #bcbbbb !important; } .fc-button.fc-state-active .fc-button-inner { background-color: #e5e4e4 !important; background-image: -moz-linear-gradient(top, #e5e4e4, #dddcdc) !important; background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#e5e4e4), to(#dddcdc)) !important; background-image: -webkit-linear-gradient(top, #e5e4e4, #dddcdc) !important; background-image: -o-linear-gradient(top, #e5e4e4, #dddcdc) !important; background-image: linear-gradient(to bottom, #e5e4e4, #dddcdc) !important; filter: progid:dximagetransform.microsoft.gradient(startColorstr='#e5e4e4', endColorstr='#dddcdc', GradientType=0) !important; } .fc-content { margin-top: 50px; } .fc-header-title h2 { line-height: 40px !important; font-size: 12px !important; } .fc-header { margin-bottom: 0px !important; } /*--*/ /*.chart-position {*/ /*margin-top: 0px;*/ /*}*/ .stepy-titles li { margin: 10px 3px; } /*-----*/ .custom-bar-chart { margin-bottom: 40px; } /*menu icon plus minus*/ .dcjq-icon { top: 10px; } ul.sidebar-menu li ul.sub li a { padding: 0; } /*---*/ .img-responsive { width: 100%; } } @media (max-width: 480px) { .notify-row, .search, .dont-show, .inbox-head .sr-input, .inbox-head .sr-btn { display: none; } #top_menu .nav > li, ul.top-menu > li { float: right; } .hidden-phone { display: none !important; } .chart-position { margin-top: 0px; } .navbar-inverse .navbar-toggle:hover, .navbar-inverse .navbar-toggle:focus { background-color: #ccc; border-color: #ccc; } } @media (max-width: 320px) { .login-social-link a { padding: 15px 17px !important; } .notify-row, .search, .dont-show, .inbox-head .sr-input, .inbox-head .sr-btn { display: none; } #top_menu .nav > li, ul.top-menu > li { float: right; } .hidden-phone { display: none !important; } .chart-position { margin-top: 0px; } .lock-wrapper { margin: 10% auto; max-width: 310px; } .lock-input { width: 82%; } .cmt-form { display: inline-block; width: 75%; } }
theNanoSoftware/NanoWord
CMS/Admin/assets/css/style-responsive.css
CSS
apache-2.0
6,715
import React from 'react' import { StyleSheet, View, processColor } from 'react-native' import { BubbleChart } from 'react-native-charts-wrapper' class BubbleChartScreen extends React.Component<any, any> { constructor(props) { super(props) const { modeInfo } = props const temp = props.value.weekLoc.sort((a, b) => { const day = a.x - b.x return day || (a.y - b.y) }) const valueFormatter = props.value.daysMapper.slice() valueFormatter.unshift() valueFormatter.push(props.value.daysMapper[0]) const isX = item => item.x === 6 const values = [...temp.filter(isX), ...temp.filter(item => item.x !== 6)] this.state = { data: { dataSets: [{ values, label: '奖杯数比例', config: { color: processColor(modeInfo.deepColor), highlightCircleWidth: 2, drawValues: false, valueTextColor: processColor(modeInfo.titleTextColor) } }] }, legend: { enabled: true, textSize: 14, form: 'CIRCLE', wordWrapEnabled: true, textColor: processColor(props.modeInfo.standardTextColor) }, xAxis: { valueFormatter, position: 'BOTTOM', drawGridLines: false, granularityEnabled: true, granularity: 1, textColor: processColor(props.modeInfo.standardTextColor) // avoidFirstLastClipping: true // labelCountForce: true, // labelCount: 12 }, yAxis: { left: { axisMinimum: 0, axisMaximum: 23, textColor: processColor(props.modeInfo.standardTextColor) }, right: { axisMinimum: 0, axisMaximum: 23, textColor: processColor(props.modeInfo.standardTextColor) } } } } handleSelect = () => { } render() { // console.log(this.state.data.dataSets[0].values.filter(item => item.x === 6)) return ( <View style={{ height: 250 }}> <BubbleChart style={styles.chart} data={this.state.data} legend={this.state.legend} chartDescription={{text: ''}} xAxis={this.state.xAxis} yAxis={this.state.yAxis} entryLabelColor={processColor(this.props.modeInfo.titleTextColor)} onSelect={this.handleSelect} /> </View> ) } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#F5FCFF' }, chart: { flex: 1 } }) export default BubbleChartScreen
Smallpath/Psnine
psnine/container/statistics/BubbleChart.tsx
TypeScript
apache-2.0
2,584
name 'neo4j' maintainer 'YOUR_COMPANY_NAME' maintainer_email 'YOUR_EMAIL' license 'All rights reserved' description 'Installs/Configures neo4j' long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) version '0.1.0'
marpaia/chef-osx
cookbooks/neo4j/metadata.rb
Ruby
apache-2.0
274
# -*- coding: utf-8 -*- """Template shortcut & filters""" import os import datetime from jinja2 import Environment, FileSystemLoader from uwsgi_sloth.settings import ROOT from uwsgi_sloth import settings, __VERSION__ template_path = os.path.join(ROOT, 'templates') env = Environment(loader=FileSystemLoader(template_path)) # Template filters def friendly_time(msecs): secs, msecs = divmod(msecs, 1000) mins, secs = divmod(secs, 60) hours, mins = divmod(mins, 60) if hours: return '%dh%dm%ds' % (hours, mins, secs) elif mins: return '%dm%ds' % (mins, secs) elif secs: return '%ds%dms' % (secs, msecs) else: return '%.2fms' % msecs env.filters['friendly_time'] = friendly_time def render_template(template_name, context={}): template = env.get_template(template_name) context.update( SETTINGS=settings, now=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), version='.'.join(map(str, __VERSION__))) return template.render(**context)
piglei/uwsgi-sloth
uwsgi_sloth/template.py
Python
apache-2.0
1,040
# Fagopyrum odontopterum Gross SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Polygonaceae/Fagopyrum/Fagopyrum odontopterum/README.md
Markdown
apache-2.0
178
# Polemonium confertum var. mellitum A.Gray VARIETY #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Ericales/Polemoniaceae/Polemonium/Polemonium confertum/Polemonium confertum mellitum/README.md
Markdown
apache-2.0
191
package org.openstack.atlas.service.domain.exception; public class UniqueLbPortViolationException extends PersistenceServiceException { private final String message; public UniqueLbPortViolationException(final String message) { this.message = message; } @Override public String getMessage() { return message; } }
openstack-atlas/atlas-lb
core-persistence/src/main/java/org/openstack/atlas/service/domain/exception/UniqueLbPortViolationException.java
Java
apache-2.0
356
#!/bin/bash -xe # 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. source /usr/local/jenkins/slave_scripts/common_translation_update.sh setup_git setup_review setup_translation setup_horizon # Download new files that are at least 75 % translated. # Also downloads updates for existing files that are at least 75 % # translated. tx pull -a -f --minimum-perc=75 # Pull upstream translations of all downloaded files but do not # download new files. tx pull -f # Invoke run_tests.sh to update the po files # Or else, "../manage.py makemessages" can be used. ./run_tests.sh --makemessages -V # Compress downloaded po files compress_non_en_po_files "horizon" compress_non_en_po_files "openstack_dashboard" # Add all changed files to git git add horizon/locale/* openstack_dashboard/locale/* filter_commits send_patch
citrix-openstack/project-config
jenkins/scripts/propose_translation_update_horizon.sh
Shell
apache-2.0
1,316
# Eriosema ×woodii C.H.Stirt. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Eriosema/Eriosema woodii/README.md
Markdown
apache-2.0
178
<?xml version="1.0" encoding="UTF-8" ?> <!-- 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. --> <html xmlns:wicket="http://wicket.apache.org"> <body> <wicket:panel> <ul class="pagination pagination-sm"> <li><a wicket:id="first">&lt;&lt;</a></li> <li><a wicket:id="prev">&lt;</a></li> <li wicket:id="navigation"> <a wicket:id="pageLink" href="#"><wicket:container wicket:id="pageNumber"></wicket:container></a> </li> <li><a wicket:id="next">&gt;</a></li> <li><a wicket:id="last">&gt;&gt;</a></li> </ul> </wicket:panel> </body> </html>
PkayJava/pluggable
framework/src/main/resources/com/angkorteam/pluggable/framework/wicket/markup/html/navigation/paging/PagingNavigator.html
HTML
apache-2.0
1,307
// Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University // Copyright (c) 2011, 2012 Open Networking Foundation // Copyright (c) 2012, 2013 Big Switch Networks, Inc. // This library was generated by the LoxiGen Compiler. // See the file LICENSE.txt which should have been included in the source distribution // Automatically generated by LOXI from template of_class.java // Do not modify package org.projectfloodlight.openflow.protocol.ver13; import org.projectfloodlight.openflow.protocol.*; import org.projectfloodlight.openflow.protocol.action.*; import org.projectfloodlight.openflow.protocol.actionid.*; import org.projectfloodlight.openflow.protocol.bsntlv.*; import org.projectfloodlight.openflow.protocol.errormsg.*; import org.projectfloodlight.openflow.protocol.meterband.*; import org.projectfloodlight.openflow.protocol.instruction.*; import org.projectfloodlight.openflow.protocol.instructionid.*; import org.projectfloodlight.openflow.protocol.match.*; import org.projectfloodlight.openflow.protocol.oxm.*; import org.projectfloodlight.openflow.protocol.queueprop.*; import org.projectfloodlight.openflow.types.*; import org.projectfloodlight.openflow.util.*; import org.projectfloodlight.openflow.exceptions.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Set; import org.jboss.netty.buffer.ChannelBuffer; import com.google.common.hash.PrimitiveSink; import com.google.common.hash.Funnel; class OFOxmBsnUdf4MaskedVer13 implements OFOxmBsnUdf4Masked { private static final Logger logger = LoggerFactory.getLogger(OFOxmBsnUdf4MaskedVer13.class); // version: 1.3 final static byte WIRE_VERSION = 4; final static int LENGTH = 12; private final static UDF DEFAULT_VALUE = UDF.ZERO; private final static UDF DEFAULT_VALUE_MASK = UDF.ZERO; // OF message fields private final UDF value; private final UDF mask; // // Immutable default instance final static OFOxmBsnUdf4MaskedVer13 DEFAULT = new OFOxmBsnUdf4MaskedVer13( DEFAULT_VALUE, DEFAULT_VALUE_MASK ); // package private constructor - used by readers, builders, and factory OFOxmBsnUdf4MaskedVer13(UDF value, UDF mask) { if(value == null) { throw new NullPointerException("OFOxmBsnUdf4MaskedVer13: property value cannot be null"); } if(mask == null) { throw new NullPointerException("OFOxmBsnUdf4MaskedVer13: property mask cannot be null"); } this.value = value; this.mask = mask; } // Accessors for OF message fields @Override public long getTypeLen() { return 0x31908L; } @Override public UDF getValue() { return value; } @Override public UDF getMask() { return mask; } @Override public MatchField<UDF> getMatchField() { return MatchField.BSN_UDF4; } @Override public boolean isMasked() { return true; } public OFOxm<UDF> getCanonical() { if (UDF.NO_MASK.equals(mask)) { return new OFOxmBsnUdf4Ver13(value); } else if(UDF.FULL_MASK.equals(mask)) { return null; } else { return this; } } @Override public OFVersion getVersion() { return OFVersion.OF_13; } public OFOxmBsnUdf4Masked.Builder createBuilder() { return new BuilderWithParent(this); } static class BuilderWithParent implements OFOxmBsnUdf4Masked.Builder { final OFOxmBsnUdf4MaskedVer13 parentMessage; // OF message fields private boolean valueSet; private UDF value; private boolean maskSet; private UDF mask; BuilderWithParent(OFOxmBsnUdf4MaskedVer13 parentMessage) { this.parentMessage = parentMessage; } @Override public long getTypeLen() { return 0x31908L; } @Override public UDF getValue() { return value; } @Override public OFOxmBsnUdf4Masked.Builder setValue(UDF value) { this.value = value; this.valueSet = true; return this; } @Override public UDF getMask() { return mask; } @Override public OFOxmBsnUdf4Masked.Builder setMask(UDF mask) { this.mask = mask; this.maskSet = true; return this; } @Override public MatchField<UDF> getMatchField() { return MatchField.BSN_UDF4; } @Override public boolean isMasked() { return true; } @Override public OFOxm<UDF> getCanonical()throws UnsupportedOperationException { throw new UnsupportedOperationException("Property canonical not supported in version 1.3"); } @Override public OFVersion getVersion() { return OFVersion.OF_13; } @Override public OFOxmBsnUdf4Masked build() { UDF value = this.valueSet ? this.value : parentMessage.value; if(value == null) throw new NullPointerException("Property value must not be null"); UDF mask = this.maskSet ? this.mask : parentMessage.mask; if(mask == null) throw new NullPointerException("Property mask must not be null"); // return new OFOxmBsnUdf4MaskedVer13( value, mask ); } } static class Builder implements OFOxmBsnUdf4Masked.Builder { // OF message fields private boolean valueSet; private UDF value; private boolean maskSet; private UDF mask; @Override public long getTypeLen() { return 0x31908L; } @Override public UDF getValue() { return value; } @Override public OFOxmBsnUdf4Masked.Builder setValue(UDF value) { this.value = value; this.valueSet = true; return this; } @Override public UDF getMask() { return mask; } @Override public OFOxmBsnUdf4Masked.Builder setMask(UDF mask) { this.mask = mask; this.maskSet = true; return this; } @Override public MatchField<UDF> getMatchField() { return MatchField.BSN_UDF4; } @Override public boolean isMasked() { return true; } @Override public OFOxm<UDF> getCanonical()throws UnsupportedOperationException { throw new UnsupportedOperationException("Property canonical not supported in version 1.3"); } @Override public OFVersion getVersion() { return OFVersion.OF_13; } // @Override public OFOxmBsnUdf4Masked build() { UDF value = this.valueSet ? this.value : DEFAULT_VALUE; if(value == null) throw new NullPointerException("Property value must not be null"); UDF mask = this.maskSet ? this.mask : DEFAULT_VALUE_MASK; if(mask == null) throw new NullPointerException("Property mask must not be null"); return new OFOxmBsnUdf4MaskedVer13( value, mask ); } } final static Reader READER = new Reader(); static class Reader implements OFMessageReader<OFOxmBsnUdf4Masked> { @Override public OFOxmBsnUdf4Masked readFrom(ChannelBuffer bb) throws OFParseError { // fixed value property typeLen == 0x31908L int typeLen = bb.readInt(); if(typeLen != 0x31908) throw new OFParseError("Wrong typeLen: Expected=0x31908L(0x31908L), got="+typeLen); UDF value = UDF.read4Bytes(bb); UDF mask = UDF.read4Bytes(bb); OFOxmBsnUdf4MaskedVer13 oxmBsnUdf4MaskedVer13 = new OFOxmBsnUdf4MaskedVer13( value, mask ); if(logger.isTraceEnabled()) logger.trace("readFrom - read={}", oxmBsnUdf4MaskedVer13); return oxmBsnUdf4MaskedVer13; } } public void putTo(PrimitiveSink sink) { FUNNEL.funnel(this, sink); } final static OFOxmBsnUdf4MaskedVer13Funnel FUNNEL = new OFOxmBsnUdf4MaskedVer13Funnel(); static class OFOxmBsnUdf4MaskedVer13Funnel implements Funnel<OFOxmBsnUdf4MaskedVer13> { private static final long serialVersionUID = 1L; @Override public void funnel(OFOxmBsnUdf4MaskedVer13 message, PrimitiveSink sink) { // fixed value property typeLen = 0x31908L sink.putInt(0x31908); message.value.putTo(sink); message.mask.putTo(sink); } } public void writeTo(ChannelBuffer bb) { WRITER.write(bb, this); } final static Writer WRITER = new Writer(); static class Writer implements OFMessageWriter<OFOxmBsnUdf4MaskedVer13> { @Override public void write(ChannelBuffer bb, OFOxmBsnUdf4MaskedVer13 message) { // fixed value property typeLen = 0x31908L bb.writeInt(0x31908); message.value.write4Bytes(bb); message.mask.write4Bytes(bb); } } @Override public String toString() { StringBuilder b = new StringBuilder("OFOxmBsnUdf4MaskedVer13("); b.append("value=").append(value); b.append(", "); b.append("mask=").append(mask); b.append(")"); return b.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; OFOxmBsnUdf4MaskedVer13 other = (OFOxmBsnUdf4MaskedVer13) obj; if (value == null) { if (other.value != null) return false; } else if (!value.equals(other.value)) return false; if (mask == null) { if (other.mask != null) return false; } else if (!mask.equals(other.mask)) return false; return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((value == null) ? 0 : value.hashCode()); result = prime * result + ((mask == null) ? 0 : mask.hashCode()); return result; } }
o3project/openflowj-otn
src/main/java/org/projectfloodlight/openflow/protocol/ver13/OFOxmBsnUdf4MaskedVer13.java
Java
apache-2.0
10,443
# Copyright 2017,2018 IBM Corp. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import json import mock import unittest from zvmsdk.sdkwsgi.handlers import version from zvmsdk import version as sdk_version class HandlersRootTest(unittest.TestCase): def setUp(self): pass def test_version(self): req = mock.Mock() ver_str = {"rc": 0, "overallRC": 0, "errmsg": "", "modID": None, "output": {"api_version": version.APIVERSION, "min_version": version.APIVERSION, "version": sdk_version.__version__, "max_version": version.APIVERSION, }, "rs": 0} res = version.version(req) self.assertEqual('application/json', req.response.content_type) # version_json = json.dumps(ver_res) # version_str = utils.to_utf8(version_json) ver_res = json.loads(req.response.body.decode('utf-8')) self.assertEqual(ver_str, ver_res) self.assertEqual('application/json', res.content_type)
mfcloud/python-zvm-sdk
zvmsdk/tests/unit/sdkwsgi/handlers/test_version.py
Python
apache-2.0
1,674
# # Copyright (C) 2015 # Andy Warner # This file is part of the aft package. # # 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. # Simple makefile for the aft package TOP = ../../.. INCDIR = $(TOP)/src #AR = ar CC = g++ #CCFLAGS = -Wall -g -O2 -I$(TOP) -I$(INCDIR) CCFLAGS = -std=c++14 -Wall -g -fPIC -I$(TOP) -I$(INCDIR) DEPCPPFLAGS = -std=c++14 -I$(TOP) -I$(INCDIR) # OBJS := nativepluginloader.o nativethread.o OBJS := nativethread.o SRCS := $(OBJS:.o=.cpp) INCS = $(OBJS:.o=.h) LIBR = libaftnative.a .cpp.o: ; $(CC) $(CCFLAGS) -c $< all: $(LIBR) $(LIBR): $(OBJS) $(AR) rsv $@ $(OBJS) .PHONY: clean clean: rm -f $(OBJS) $(LIBR) .PHONY: depends depends: $(SRCS) $(INCS) $(CC) $(DEPCPPFLAGS) -MM $(SRCS) > .makedepends touch .mkdep-timestamp .makedepends: include .makedepends
lawarner/aft
src/osdep/native/Makefile
Makefile
apache-2.0
1,315