code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
---|---|---|---|---|---|
"use strict";
var Metatags = require("lib/metatags/Metatags");
describe("Metatags", function() {
var metatags;
describe("instantiation", function() {
describe("when pairs are NOT provided", function() {
function instantiateMetatagsWithoutPairs() {
return new Metatags();
}
it("throws an error", function() {
expect(instantiateMetatagsWithoutPairs).toThrow();
});
});
describe("when pairs are provided", function() {
beforeEach(function() {
metatags = new Metatags({
"description": "desc",
"og:image": "a.jpg",
"canonical": "a.com/c"
});
});
it("sets html property to markup of metatags", function() {
expect(metatags.html).toEqual(
'<meta name="description" content="desc" data-ephemeral="true">' +
'<meta property="og:image" content="a.jpg" data-ephemeral="true">' +
'<link rel="canonical" href="a.com/c" data-ephemeral="true">'
);
});
});
describe("deprecation", function() {
beforeEach(function() {
spyOn(console, "warn");
});
it("logs deprecation method for open graph tags", function() {
metatags = new Metatags({
"og:image": "a.jpg"
});
expect(console.warn).toHaveBeenCalled();
});
it("logs deprecation method for canonical tags", function() {
metatags = new Metatags({
"canonical": "a.com/c"
});
expect(console.warn).toHaveBeenCalled();
});
});
});
});
// ----------------------------------------------------------------------------
// Copyright (C) 2015 Bloomberg Finance L.P.
//
// 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.
//
// ----------------------------- END-OF-FILE ----------------------------------
| sylnp0201/brisket | spec/client/metatags/MetatagsSpec.js | JavaScript | apache-2.0 | 2,630 |
java.lang.Integer[] arr = new java.lang.Integer[]{1, 2, 3};
print(new java.lang.Integer[]{1, 2, 3});
print(org.codehaus.groovy.runtime.DefaultGroovyMethods.asType("dg", java.lang.Object.class));
| consulo/consulo-groovy | testdata/refactoring/convertGroovyToJava/codeBlock/safeCast.java | Java | apache-2.0 | 195 |
/**
* 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 com.datatorrent.lib.db.jdbc;
import java.io.File;
import java.io.IOException;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.apache.apex.malhar.lib.wal.WindowDataManager;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.tuple.MutablePair;
import com.google.common.collect.Lists;
import com.datatorrent.api.Attribute;
import com.datatorrent.api.Context;
import com.datatorrent.api.DAG;
import com.datatorrent.api.Partitioner;
import com.datatorrent.lib.helper.OperatorContextTestHelper;
import com.datatorrent.lib.helper.TestPortContext;
import com.datatorrent.lib.testbench.CollectorTestSink;
import com.datatorrent.lib.util.FieldInfo;
import com.datatorrent.lib.util.KeyValPair;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class JdbcPojoPollableOpeartorTest extends JdbcOperatorTest
{
public String dir = null;
@Mock
private ScheduledExecutorService mockscheduler;
@Mock
private ScheduledFuture futureTaskMock;
@Mock
private WindowDataManager windowDataManagerMock;
@Before
public void beforeTest()
{
dir = "target/" + APP_ID + "/";
MockitoAnnotations.initMocks(this);
when(mockscheduler.scheduleWithFixedDelay(any(Runnable.class), anyLong(), anyLong(), any(TimeUnit.class)))
.thenReturn(futureTaskMock);
}
@After
public void afterTest() throws IOException
{
cleanTable();
FileUtils.deleteDirectory(new File(dir));
}
@Test
public void testDBPoller() throws InterruptedException
{
insertEvents(10, true, 0);
JdbcStore store = new JdbcStore();
store.setDatabaseDriver(DB_DRIVER);
store.setDatabaseUrl(URL);
List<FieldInfo> fieldInfos = getFieldInfos();
Attribute.AttributeMap.DefaultAttributeMap portAttributes = new Attribute.AttributeMap.DefaultAttributeMap();
portAttributes.put(Context.PortContext.TUPLE_CLASS, TestPOJOEvent.class);
TestPortContext tpc = new TestPortContext(portAttributes);
JdbcPOJOPollInputOperator inputOperator = new JdbcPOJOPollInputOperator();
inputOperator.setStore(store);
inputOperator.setTableName(TABLE_POJO_NAME);
inputOperator.setKey("id");
inputOperator.setFieldInfos(fieldInfos);
inputOperator.setFetchSize(100);
inputOperator.setBatchSize(100);
inputOperator.setPartitionCount(2);
Collection<com.datatorrent.api.Partitioner.Partition<AbstractJdbcPollInputOperator<Object>>> newPartitions = inputOperator
.definePartitions(new ArrayList<Partitioner.Partition<AbstractJdbcPollInputOperator<Object>>>(), null);
int operatorId = 0;
for (com.datatorrent.api.Partitioner.Partition<AbstractJdbcPollInputOperator<Object>> partition : newPartitions) {
Attribute.AttributeMap.DefaultAttributeMap partitionAttributeMap = new Attribute.AttributeMap.DefaultAttributeMap();
partitionAttributeMap.put(DAG.APPLICATION_ID, APP_ID);
partitionAttributeMap.put(Context.DAGContext.APPLICATION_PATH, dir);
OperatorContextTestHelper.TestIdOperatorContext partitioningContext = new OperatorContextTestHelper.TestIdOperatorContext(
operatorId++, partitionAttributeMap);
JdbcPOJOPollInputOperator parition = (JdbcPOJOPollInputOperator)partition.getPartitionedInstance();
parition.outputPort.setup(tpc);
parition.setScheduledExecutorService(mockscheduler);
parition.setup(partitioningContext);
parition.activate(partitioningContext);
}
Iterator<com.datatorrent.api.Partitioner.Partition<AbstractJdbcPollInputOperator<Object>>> itr = newPartitions
.iterator();
// First partition is for range queries,last is for polling queries
JdbcPOJOPollInputOperator firstInstance = (JdbcPOJOPollInputOperator)itr.next().getPartitionedInstance();
CollectorTestSink<Object> sink1 = new CollectorTestSink<>();
firstInstance.outputPort.setSink(sink1);
firstInstance.beginWindow(0);
firstInstance.pollRecords();
firstInstance.pollRecords();
firstInstance.emitTuples();
firstInstance.endWindow();
Assert.assertEquals("rows from db", 5, sink1.collectedTuples.size());
for (Object tuple : sink1.collectedTuples) {
TestPOJOEvent pojoEvent = (TestPOJOEvent)tuple;
Assert.assertTrue("date", pojoEvent.getStartDate() instanceof Date);
Assert.assertTrue("date", pojoEvent.getId() < 5);
}
JdbcPOJOPollInputOperator secondInstance = (JdbcPOJOPollInputOperator)itr.next().getPartitionedInstance();
CollectorTestSink<Object> sink2 = new CollectorTestSink<>();
secondInstance.outputPort.setSink(sink2);
secondInstance.beginWindow(0);
secondInstance.pollRecords();
secondInstance.emitTuples();
secondInstance.endWindow();
Assert.assertEquals("rows from db", 5, sink2.collectedTuples.size());
for (Object tuple : sink2.collectedTuples) {
TestPOJOEvent pojoEvent = (TestPOJOEvent)tuple;
Assert.assertTrue("date", pojoEvent.getId() < 10 && pojoEvent.getId() >= 5);
}
insertEvents(4, false, 10);
JdbcPOJOPollInputOperator thirdInstance = (JdbcPOJOPollInputOperator)itr.next().getPartitionedInstance();
CollectorTestSink<Object> sink3 = new CollectorTestSink<>();
thirdInstance.outputPort.setSink(sink3);
thirdInstance.beginWindow(0);
thirdInstance.pollRecords();
thirdInstance.emitTuples();
thirdInstance.endWindow();
Assert.assertEquals("rows from db", 4, sink3.collectedTuples.size());
}
@Test
public void testRecovery() throws IOException
{
int operatorId = 1;
when(windowDataManagerMock.getLargestCompletedWindow()).thenReturn(1L);
when(windowDataManagerMock.retrieve(1)).thenReturn(new MutablePair<Integer, Integer>(0, 4));
insertEvents(10, true, 0);
JdbcStore store = new JdbcStore();
store.setDatabaseDriver(DB_DRIVER);
store.setDatabaseUrl(URL);
List<FieldInfo> fieldInfos = getFieldInfos();
Attribute.AttributeMap.DefaultAttributeMap portAttributes = new Attribute.AttributeMap.DefaultAttributeMap();
portAttributes.put(Context.PortContext.TUPLE_CLASS, TestPOJOEvent.class);
TestPortContext tpc = new TestPortContext(portAttributes);
Attribute.AttributeMap.DefaultAttributeMap partitionAttributeMap = new Attribute.AttributeMap.DefaultAttributeMap();
partitionAttributeMap.put(DAG.APPLICATION_ID, APP_ID);
partitionAttributeMap.put(Context.DAGContext.APPLICATION_PATH, dir);
OperatorContextTestHelper.TestIdOperatorContext context = new OperatorContextTestHelper.TestIdOperatorContext(
operatorId, partitionAttributeMap);
JdbcPOJOPollInputOperator inputOperator = new JdbcPOJOPollInputOperator();
inputOperator.setStore(store);
inputOperator.setTableName(TABLE_POJO_NAME);
inputOperator.setKey("id");
inputOperator.setFieldInfos(fieldInfos);
inputOperator.setFetchSize(100);
inputOperator.setBatchSize(100);
inputOperator.lastEmittedRow = 0; //setting as not calling partition logic
inputOperator.rangeQueryPair = new KeyValPair<Integer, Integer>(0, 8);
inputOperator.outputPort.setup(tpc);
inputOperator.setScheduledExecutorService(mockscheduler);
inputOperator.setup(context);
inputOperator.setWindowManager(windowDataManagerMock);
inputOperator.activate(context);
CollectorTestSink<Object> sink = new CollectorTestSink<>();
inputOperator.outputPort.setSink(sink);
inputOperator.beginWindow(0);
verify(mockscheduler, times(0)).scheduleAtFixedRate(any(Runnable.class), anyLong(), anyLong(), any(TimeUnit.class));
inputOperator.emitTuples();
inputOperator.endWindow();
inputOperator.beginWindow(1);
verify(mockscheduler, times(1)).scheduleAtFixedRate(any(Runnable.class), anyLong(), anyLong(), any(TimeUnit.class));
}
private List<FieldInfo> getFieldInfos()
{
List<FieldInfo> fieldInfos = Lists.newArrayList();
fieldInfos.add(new FieldInfo("ID", "id", null));
fieldInfos.add(new FieldInfo("STARTDATE", "startDate", null));
fieldInfos.add(new FieldInfo("STARTTIME", "startTime", null));
fieldInfos.add(new FieldInfo("STARTTIMESTAMP", "startTimestamp", null));
fieldInfos.add(new FieldInfo("NAME", "name", null));
return fieldInfos;
}
}
| siyuanh/apex-malhar | library/src/test/java/com/datatorrent/lib/db/jdbc/JdbcPojoPollableOpeartorTest.java | Java | apache-2.0 | 9,540 |
package com.badlogic.gdx.tests.lwjgl3;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.Graphics.DisplayMode;
import com.badlogic.gdx.backends.lwjgl3.Lwjgl3WindowAdapter;
import com.badlogic.gdx.backends.lwjgl3.Lwjgl3Application;
import com.badlogic.gdx.backends.lwjgl3.Lwjgl3ApplicationConfiguration;
import com.badlogic.gdx.backends.lwjgl3.Lwjgl3Window;
import com.badlogic.gdx.backends.lwjgl3.Lwjgl3WindowConfiguration;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.Pixmap.Blending;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.tests.NoncontinuousRenderingTest;
import com.badlogic.gdx.tests.UITest;
import com.badlogic.gdx.tests.g3d.Basic3DSceneTest;
import com.badlogic.gdx.tests.g3d.ShaderCollectionTest;
import com.badlogic.gdx.utils.GdxRuntimeException;
public class MultiWindowTest {
static Texture sharedTexture;
static SpriteBatch sharedSpriteBatch;
public static class MainWindow extends ApplicationAdapter {
Class[] childWindowClasses = { NoncontinuousRenderingTest.class, ShaderCollectionTest.class, Basic3DSceneTest.class, UITest.class };
Lwjgl3Window latestWindow;
int index;
@Override
public void create () {
sharedSpriteBatch = new SpriteBatch();
sharedTexture = new Texture("data/badlogic.jpg");
}
@Override
public void render () {
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
sharedSpriteBatch.getProjectionMatrix().setToOrtho2D(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
sharedSpriteBatch.begin();
sharedSpriteBatch.draw(sharedTexture, Gdx.input.getX(), Gdx.graphics.getHeight() - Gdx.input.getY() - 1);
sharedSpriteBatch.end();
if(Gdx.input.justTouched()) {
Lwjgl3Application app = (Lwjgl3Application)Gdx.app;
Lwjgl3WindowConfiguration config = new Lwjgl3WindowConfiguration();
DisplayMode mode = Gdx.graphics.getDisplayMode();
config.setWindowPosition(MathUtils.random(0, mode.width - 640), MathUtils.random(0, mode.height - 480));
config.setTitle("Child window");
config.useVsync(false);
config.setWindowListener(new Lwjgl3WindowAdapter() {
@Override
public void created(Lwjgl3Window window) {
latestWindow = window;
}
});
Class clazz = childWindowClasses[index++ % childWindowClasses.length];
ApplicationListener listener = createChildWindowClass(clazz);
app.newWindow(listener, config);
}
if (Gdx.input.isKeyJustPressed(Input.Keys.SPACE) && latestWindow != null){
latestWindow.setTitle("Retitled window");
int size = 48;
Pixmap icon = new Pixmap(size, size, Pixmap.Format.RGBA8888);
icon.setBlending(Blending.None);
icon.setColor(Color.BLUE);
icon.fill();
icon.setColor(Color.CLEAR);
for (int i = 0; i < size; i += 3)
for (int j = 0; j < size; j += 3)
icon.drawPixel(i, j);
latestWindow.setIcon(icon);
icon.dispose();
}
}
public ApplicationListener createChildWindowClass(Class clazz) {
try {
return (ApplicationListener) clazz.newInstance();
} catch(Throwable t) {
throw new GdxRuntimeException("Couldn't instantiate app listener", t);
}
}
}
public static void main(String[] argv) {
Lwjgl3ApplicationConfiguration config = new Lwjgl3ApplicationConfiguration();
config.setTitle("Multi-window test");
config.useVsync(true);
new Lwjgl3Application(new MainWindow(), config);
}
}
| alex-dorokhov/libgdx | tests/gdx-tests-lwjgl3/src/com/badlogic/gdx/tests/lwjgl3/MultiWindowTest.java | Java | apache-2.0 | 3,716 |
/* -*- Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 4 -*- */
/* vi: set ts=4 sw=4 expandtab: (add to ~/.vimrc: set modeline modelines=5) */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is [Open Source Virtual Machine].
*
* The Initial Developer of the Original Code is
* Adobe System Incorporated.
* Portions created by the Initial Developer are Copyright (C) 2004-2007
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adobe AS3 Team
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "nanojit.h"
#ifdef FEATURE_NANOJIT
namespace nanojit
{
#ifdef NANOJIT_IA32
static int getCpuFeatures()
{
int features = 0;
#if defined _MSC_VER
__asm
{
pushad
mov eax, 1
cpuid
mov features, edx
popad
}
#elif defined __GNUC__
asm("xchg %%esi, %%ebx\n" /* we can't clobber ebx on gcc (PIC register) */
"mov $0x01, %%eax\n"
"cpuid\n"
"mov %%edx, %0\n"
"xchg %%esi, %%ebx\n"
: "=m" (features)
: /* We have no inputs */
: "%eax", "%esi", "%ecx", "%edx"
);
#elif defined __SUNPRO_C || defined __SUNPRO_CC
asm("push %%ebx\n"
"mov $0x01, %%eax\n"
"cpuid\n"
"pop %%ebx\n"
: "=d" (features)
: /* We have no inputs */
: "%eax", "%ecx"
);
#endif
return features;
}
#endif
Config::Config()
{
VMPI_memset(this, 0, sizeof(*this));
cseopt = true;
#ifdef NANOJIT_IA32
int const features = getCpuFeatures();
i386_sse2 = (features & (1<<26)) != 0;
i386_use_cmov = (features & (1<<15)) != 0;
i386_fixed_esp = false;
#endif
harden_function_alignment = false;
harden_nop_insertion = false;
#if defined(NANOJIT_ARM)
// XXX: temporarily disabled, see bug 547063.
//NanoStaticAssert(NJ_COMPILER_ARM_ARCH >= 5 && NJ_COMPILER_ARM_ARCH <= 7);
arm_arch = NJ_COMPILER_ARM_ARCH;
arm_vfp = (arm_arch >= 7);
#if defined(DEBUG) || defined(_DEBUG)
arm_show_stats = true;
#else
arm_show_stats = false;
#endif
soft_float = !arm_vfp;
#endif // NANOJIT_ARM
}
}
#endif /* FEATURE_NANOJIT */
| glycerine/vj | src/js-1.8.5/js/src/nanojit/njconfig.cpp | C++ | apache-2.0 | 3,724 |
/**
* 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.component.kubernetes.job.springboot;
import javax.annotation.Generated;
import org.apache.camel.spring.boot.ComponentConfigurationPropertiesCommon;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* The Kubernetes Jobs component provides a producer to execute kubernetes job
* operations
*
* Generated by camel-package-maven-plugin - do not edit this file!
*/
@Generated("org.apache.camel.maven.packaging.SpringBootAutoConfigurationMojo")
@ConfigurationProperties(prefix = "camel.component.kubernetes-job")
public class KubernetesJobComponentConfiguration
extends
ComponentConfigurationPropertiesCommon {
/**
* Whether to enable auto configuration of the kubernetes-job component.
* This is enabled by default.
*/
private Boolean enabled;
/**
* Whether the component should resolve property placeholders on itself when
* starting. Only properties which are of String type can use property
* placeholders.
*/
private Boolean resolvePropertyPlaceholders = true;
public Boolean getResolvePropertyPlaceholders() {
return resolvePropertyPlaceholders;
}
public void setResolvePropertyPlaceholders(
Boolean resolvePropertyPlaceholders) {
this.resolvePropertyPlaceholders = resolvePropertyPlaceholders;
}
} | onders86/camel | platforms/spring-boot/components-starter/camel-kubernetes-starter/src/main/java/org/apache/camel/component/kubernetes/job/springboot/KubernetesJobComponentConfiguration.java | Java | apache-2.0 | 2,184 |
/*******************************************************************************
* 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.drill.exec.expr.fn.impl.conv;
import org.apache.drill.exec.expr.DrillSimpleFunc;
import org.apache.drill.exec.expr.annotations.FunctionTemplate;
import org.apache.drill.exec.expr.annotations.FunctionTemplate.FunctionScope;
import org.apache.drill.exec.expr.annotations.FunctionTemplate.NullHandling;
import org.apache.drill.exec.expr.annotations.Output;
import org.apache.drill.exec.expr.annotations.Param;
import org.apache.drill.exec.expr.holders.Float4Holder;
import org.apache.drill.exec.expr.holders.VarBinaryHolder;
import org.apache.drill.exec.record.RecordBatch;
@FunctionTemplate(name = "convert_fromFLOAT", scope = FunctionScope.SIMPLE, nulls = NullHandling.NULL_IF_NULL)
public class FloatConvertFrom implements DrillSimpleFunc {
@Param VarBinaryHolder in;
@Output Float4Holder out;
@Override
public void setup(RecordBatch incoming) { }
@Override
public void eval() {
org.apache.drill.exec.util.ByteBufUtil.checkBufferLength(in.buffer, in.start, in.end, 4);
in.buffer.readerIndex(in.start);
out.value = in.buffer.readFloat();
}
}
| yssharma/pig-on-drill | exec/java-exec/src/main/java/org/apache/drill/exec/expr/fn/impl/conv/FloatConvertFrom.java | Java | apache-2.0 | 2,050 |
/*
* Copyright (C) 2014 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.android.systemui.statusbar.phone;
import android.util.Pools;
import android.view.MotionEvent;
import android.view.VelocityTracker;
/**
* An implementation of {@link VelocityTrackerInterface} using the platform-standard
* {@link VelocityTracker}.
*/
public class PlatformVelocityTracker implements VelocityTrackerInterface {
private static final Pools.SynchronizedPool<PlatformVelocityTracker> sPool =
new Pools.SynchronizedPool<>(2);
private VelocityTracker mTracker;
public static PlatformVelocityTracker obtain() {
PlatformVelocityTracker tracker = sPool.acquire();
if (tracker == null) {
tracker = new PlatformVelocityTracker();
}
tracker.setTracker(VelocityTracker.obtain());
return tracker;
}
public void setTracker(VelocityTracker tracker) {
mTracker = tracker;
}
@Override
public void addMovement(MotionEvent event) {
mTracker.addMovement(event);
}
@Override
public void computeCurrentVelocity(int units) {
mTracker.computeCurrentVelocity(units);
}
@Override
public float getXVelocity() {
return mTracker.getXVelocity();
}
@Override
public float getYVelocity() {
return mTracker.getYVelocity();
}
@Override
public void recycle() {
mTracker.recycle();
sPool.release(this);
}
}
| Ant-Droid/android_frameworks_base_OLD | packages/SystemUI/src/com/android/systemui/statusbar/phone/PlatformVelocityTracker.java | Java | apache-2.0 | 2,033 |
/*
* Copyright 2000-2016 Vaadin 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 com.vaadin.shared.ui.dd;
public enum DragEventType {
ENTER, LEAVE, OVER, DROP
}
| Darsstar/framework | shared/src/main/java/com/vaadin/shared/ui/dd/DragEventType.java | Java | apache-2.0 | 690 |
#!/usr/bin/env python
"""
split_file.py [-o <dir>] <path>
Take the file at <path> and write it to multiple files, switching to a new file
every time an annotation of the form "// BEGIN file1.swift" is encountered. If
<dir> is specified, place the files in <dir>; otherwise, put them in the
current directory.
"""
import getopt
import os
import re
import sys
def usage():
sys.stderr.write(__doc__.strip() + "\n")
sys.exit(1)
fp_out = None
dest_dir = '.'
try:
opts, args = getopt.getopt(sys.argv[1:], 'o:h')
for (opt, arg) in opts:
if opt == '-o':
dest_dir = arg
elif opt == '-h':
usage()
except getopt.GetoptError:
usage()
if len(args) != 1:
usage()
fp_in = open(args[0], 'r')
for line in fp_in:
m = re.match(r'^//\s*BEGIN\s+([^\s]+)\s*$', line)
if m:
if fp_out:
fp_out.close()
fp_out = open(os.path.join(dest_dir, m.group(1)), 'w')
elif fp_out:
fp_out.write(line)
fp_in.close()
if fp_out:
fp_out.close()
| khizkhiz/swift | utils/split_file.py | Python | apache-2.0 | 1,030 |
# typed: false
# frozen_string_literal: true
require "cmd/shared_examples/args_parse"
describe "brew --version" do
it "prints the Homebrew's version", :integration_test do
expect { brew_sh "--version" }
.to output(/^Homebrew #{Regexp.escape(HOMEBREW_VERSION)}\n/o).to_stdout
.and not_to_output.to_stderr
.and be_a_success
end
end
| vitorgalvao/brew | Library/Homebrew/test/cmd/--version_spec.rb | Ruby | bsd-2-clause | 358 |
/* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System;
using XenAdmin.Diagnostics.Checks;
using XenAPI;
using XenAdmin.Actions;
using System.Collections.Generic;
namespace XenAdmin.Diagnostics.Problems.PoolProblem
{
class HAEnabledProblem : PoolProblem
{
private readonly long FailuresToTolerate;
private readonly List<SR> HeartbeatSrs = new List<SR>();
public HAEnabledProblem(Check check, Pool pool)
: base(check, pool)
{
FailuresToTolerate = pool.ha_host_failures_to_tolerate;
HeartbeatSrs = pool.GetHAHeartbeatSRs();
}
protected override AsyncAction CreateAction(out bool cancelled)
{
cancelled = false;
return new DisableHAAction(Pool);
}
public override AsyncAction UnwindChanges()
{
return new EnableHAAction(Pool, null, HeartbeatSrs, FailuresToTolerate);
}
public override string Description
{
get
{
return String.Format(Messages.UPDATES_WIZARD_HA_ON_DESCRIPTION, Pool);
}
}
public override string HelpMessage
{
get
{
return Messages.TURN_HA_OFF;
}
}
}
class HAEnabledWarning : Warning
{
private readonly Pool pool;
private readonly Host host;
public HAEnabledWarning(Check check, Pool pool, Host host)
: base(check)
{
this.pool = pool;
this.host = host;
}
public override string Title
{
get { return Check.Description; }
}
public override string Description
{
get
{
return string.Format(Messages.UPDATES_WIZARD_HA_ON_WARNING, host, pool);
}
}
}
}
| GaborApatiNagy/xenadmin | XenAdmin/Diagnostics/Problems/PoolProblem/HAEnabledProblem.cs | C# | bsd-2-clause | 3,391 |
class Libdvdnav < Formula
desc "DVD navigation library"
homepage "https://www.videolan.org/developers/libdvdnav.html"
url "https://download.videolan.org/pub/videolan/libdvdnav/6.0.0/libdvdnav-6.0.0.tar.bz2"
sha256 "f0a2711b08a021759792f8eb14bb82ff8a3c929bf88c33b64ffcddaa27935618"
bottle do
cellar :any
sha256 "82f7cf986d45b13b3cc57d121dc53d7fa43d628062f978e31723d49778ea8d22" => :high_sierra
sha256 "1a2a0a5b4f2c349574f830ae5e918ee2788ceb17d2f2856ec507e62226327e28" => :sierra
sha256 "379d6e135a9e97db494376c0f35e235bced3a3052e60a0fea2a5318730c5d900" => :el_capitan
end
head do
url "https://git.videolan.org/git/libdvdnav.git"
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "libtool" => :build
end
depends_on "pkg-config" => :build
depends_on "libdvdread"
def install
system "autoreconf", "-if" if build.head?
system "./configure", "--disable-dependency-tracking",
"--prefix=#{prefix}"
system "make", "install"
end
end
| moderndeveloperllc/homebrew-core | Formula/libdvdnav.rb | Ruby | bsd-2-clause | 1,046 |
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef ASH_COMMON_SYSTEM_TRAY_THROBBER_VIEW_H_
#define ASH_COMMON_SYSTEM_TRAY_THROBBER_VIEW_H_
#include "base/macros.h"
#include "ui/gfx/geometry/size.h"
#include "ui/views/controls/throbber.h"
#include "ui/views/view.h"
namespace ash {
// A SmoothedThrobber with tooltip.
class SystemTrayThrobber : public views::SmoothedThrobber {
public:
SystemTrayThrobber();
~SystemTrayThrobber() override;
void SetTooltipText(const base::string16& tooltip_text);
// Overriden from views::View.
bool GetTooltipText(const gfx::Point& p,
base::string16* tooltip) const override;
private:
// The current tooltip text.
base::string16 tooltip_text_;
DISALLOW_COPY_AND_ASSIGN(SystemTrayThrobber);
};
// A View containing a SystemTrayThrobber with animation for starting/stopping.
class ThrobberView : public views::View {
public:
ThrobberView();
~ThrobberView() override;
void Start();
void Stop();
void SetTooltipText(const base::string16& tooltip_text);
// Overriden from views::View.
gfx::Size GetPreferredSize() const override;
void Layout() override;
bool GetTooltipText(const gfx::Point& p,
base::string16* tooltip) const override;
private:
// Schedules animation for starting/stopping throbber.
void ScheduleAnimation(bool start_throbber);
SystemTrayThrobber* throbber_;
// The current tooltip text.
base::string16 tooltip_text_;
DISALLOW_COPY_AND_ASSIGN(ThrobberView);
};
} // namespace ash
#endif // ASH_COMMON_SYSTEM_TRAY_THROBBER_VIEW_H_
| ssaroha/node-webrtc | third_party/webrtc/include/chromium/src/ash/common/system/tray/throbber_view.h | C | bsd-2-clause | 1,714 |
#!/usr/bin/env python
##
# OOIPLACEHOLDER
#
# Copyright 2014 Raytheon Co.
##
from mi.core.log import get_logger
from mi.core.versioning import version
from mi.dataset.dataset_driver import DataSetDriver
from mi.dataset.dataset_parser import DataSetDriverConfigKeys
from mi.dataset.parser.mmp_cds_base import MmpCdsParser
log = get_logger()
__author__ = 'Joe Padula'
@version("0.0.3")
def parse(unused, source_file_path, particle_data_handler):
parser_config = {
DataSetDriverConfigKeys.PARTICLE_MODULE: 'mi.dataset.parser.dosta_abcdjm_mmp_cds',
DataSetDriverConfigKeys.PARTICLE_CLASS: 'DostaAbcdjmMmpCdsParserDataParticle'
}
def exception_callback(exception):
log.debug("ERROR: %r", exception)
particle_data_handler.setParticleDataCaptureFailure()
with open(source_file_path, 'rb') as stream_handle:
parser = MmpCdsParser(parser_config, stream_handle, exception_callback)
driver = DataSetDriver(parser, particle_data_handler)
driver.processFileStream()
return particle_data_handler
| janeen666/mi-instrument | mi/dataset/driver/dosta_abcdjm/mmp_cds/dosta_abcdjm_mmp_cds_recovered_driver.py | Python | bsd-2-clause | 1,067 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JSDoc: Source: easyrtc_rates.js</title>
<script src="scripts/prettify/prettify.js"> </script>
<script src="scripts/prettify/lang-css.js"> </script>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
<link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">
</head>
<body>
<div id="main">
<h1 class="page-title">Source: easyrtc_rates.js</h1>
<section>
<article>
<pre class="prettyprint source linenums"><code>/* global define, module, require, console */
/*!
Script: easyrtc_rates.js
This code builds sdp filter functions
About: License
Copyright (c) 2016, Priologic Software Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
//RequireJS (AMD) build system
define(['easyrtc'], factory);
} else if (typeof module === 'object' && module.exports) {
//CommonJS build system
module.exports = factory(require('easyrtc'));
} else {
//Vanilla JS, ensure dependencies are loaded correctly
if (typeof window.easyrtc !== 'object' || !window.easyrtc) {
throw new Error("easyrtc_rates requires easyrtc");
}
root.easyrtc = factory(window.easyrtc);
}
}(this, function (easyrtc, undefined) {
"use strict";
/**
* Provides methods for building SDP filters. SDP filters can be used
* to control bit rates.
* @class Easyrtc_Rates
* @augments Easyrtc
*/
function buildSdpFilter(options, isLocal) {
var audioSendBitrate = options.audioSendBitrate;
var audioRecvBitrate = options.audioRecvBitrate;
var videoRecvBitrate = options.videoRecvBitrate;
var videoSendBitrate = options.videoSendBitrate;
var videoSendInitialBitrate = options.videoSendInitialBitrate;
var audioSendCodec = options.audioSendCodec || '';
var audioRecvCodec = options.audioRecvCodec || '';
var videoSendCodec = options.videoSendCodec || '';
var videoRecvCodec = options.videoRecvCodec || '';
var stereo = options.stereo;
function trace(arg) {
console.log("trace:" + arg);
}
// these functions were cribbed from the google apprtc.appspot.com demo.
function findLineInRange(sdpLines, startLine, endLine, prefix, substr) {
var realEndLine = endLine !== -1 ? endLine : sdpLines.length;
for (var i = startLine; i < realEndLine; ++i) {
if (sdpLines[i].indexOf(prefix) === 0) {
if (!substr || sdpLines[i].toLowerCase().indexOf(substr.toLowerCase()) !== -1) {
return i;
}
}
}
return null;
}
function findLine(sdpLines, prefix, substr) {
return findLineInRange(sdpLines, 0, -1, prefix, substr);
}
function preferBitRate(sdp, bitrate, mediaType) {
var sdpLines = sdp.split('\r\n');
var mLineIndex = findLine(sdpLines, 'm=', mediaType);
if (mLineIndex === null) {
trace('Failed to add bandwidth line to sdp, as no m-line found');
return sdp;
}
var nextMLineIndex = findLineInRange(sdpLines, mLineIndex + 1, -1, 'm=');
if (nextMLineIndex === null) {
nextMLineIndex = sdpLines.length;
}
var cLineIndex = findLineInRange(sdpLines, mLineIndex + 1, nextMLineIndex, 'c=');
if (cLineIndex === null) {
trace('Failed to add bandwidth line to sdp, as no c-line found');
return sdp;
}
var bLineIndex = findLineInRange(sdpLines, cLineIndex + 1, nextMLineIndex, 'b=AS');
if (bLineIndex) {
sdpLines.splice(bLineIndex, 1);
}
var bwLine = 'b=AS:' + bitrate;
sdpLines.splice(cLineIndex + 1, 0, bwLine);
sdp = sdpLines.join('\r\n');
return sdp;
}
function setDefaultCodec(mLine, payload) {
var elements = mLine.split(' ');
var newLine = [];
var index = 0;
for (var i = 0; i < elements.length; i++) {
if (index === 3) {
newLine[index++] = payload;
}
if (elements[i] !== payload) {
newLine[index++] = elements[i];
}
}
return newLine.join(' ');
}
function maybeSetAudioSendBitRate(sdp) {
if (!audioSendBitrate) {
return sdp;
}
trace('Prefer audio send bitrate: ' + audioSendBitrate);
return preferBitRate(sdp, audioSendBitrate, 'audio');
}
function maybeSetAudioReceiveBitRate(sdp) {
if (!audioRecvBitrate) {
return sdp;
}
trace('Prefer audio receive bitrate: ' + audioRecvBitrate);
return preferBitRate(sdp, audioRecvBitrate, 'audio');
}
function maybeSetVideoSendBitRate(sdp) {
if (!videoSendBitrate) {
return sdp;
}
trace('Prefer video send bitrate: ' + videoSendBitrate);
return preferBitRate(sdp, videoSendBitrate, 'video');
}
function maybeSetVideoReceiveBitRate(sdp) {
if (!videoRecvBitrate) {
return sdp;
}
trace('Prefer video receive bitrate: ' + videoRecvBitrate);
return preferBitRate(sdp, videoRecvBitrate, 'video');
}
function getCodecPayloadType(sdpLine) {
var pattern = new RegExp('a=rtpmap:(\\d+) \\w+\\/\\d+');
var result = sdpLine.match(pattern);
return (result && result.length === 2) ? result[1] : null;
}
function maybeSetVideoSendInitialBitRate(sdp) {
if (!videoSendInitialBitrate) {
return sdp;
}
var maxBitrate = videoSendInitialBitrate;
if (videoSendBitrate) {
if (videoSendInitialBitrate > videoSendBitrate) {
trace('Clamping initial bitrate to max bitrate of ' + videoSendBitrate + ' kbps.');
videoSendInitialBitrate = videoSendBitrate;
}
maxBitrate = videoSendBitrate;
}
var sdpLines = sdp.split('\r\n');
var mLineIndex = findLine(sdpLines, 'm=', 'video');
if (mLineIndex === null) {
trace('Failed to find video m-line');
return sdp;
}
var vp8RtpmapIndex = findLine(sdpLines, 'a=rtpmap', 'VP8/90000');
var vp8Payload = getCodecPayloadType(sdpLines[vp8RtpmapIndex]);
var vp8Fmtp = 'a=fmtp:' + vp8Payload + ' x-google-min-bitrate=' + videoSendInitialBitrate.toString() + '; x-google-max-bitrate=' + maxBitrate.toString();
sdpLines.splice(vp8RtpmapIndex + 1, 0, vp8Fmtp);
return sdpLines.join('\r\n');
}
function preferCodec(sdp, codec, codecType){
var sdpLines = sdp.split('\r\n');
var mLineIndex = findLine(sdpLines, 'm=', codecType);
if (mLineIndex === null) {
return sdp;
}
//
// there are two m= lines in the sdp, one for audio, one for video.
// the audio one comes first. when we search for codecs for audio, we
// want stop before we enter the section for video, hence we'll hunt
// for that subsequent m= line before we look for codecs. Otherwise,
// you could ask for a audio codec of VP9.
//
var mBottom = findLineInRange(sdpLines, mLineIndex+1, -1, "m=") || -1;
var codecIndex = findLineInRange(sdpLines, mLineIndex, mBottom, 'a=rtpmap', codec);
if (codecIndex) {
var payload = getCodecPayloadType(sdpLines[codecIndex]);
if (payload) {
sdpLines[mLineIndex] = setDefaultCodec(sdpLines[mLineIndex], payload);
}
}
sdp = sdpLines.join('\r\n');
return sdp;
}
function maybePreferVideoSendCodec(sdp) {
if (videoSendCodec === '') {
trace('No preference on video send codec.');
return sdp;
}
trace('Prefer video send codec: ' + videoSendCodec);
return preferCodec(sdp, videoSendCodec, 'video');
}
function maybePreferVideoReceiveCodec(sdp) {
if (videoRecvCodec === '') {
trace('No preference on video receive codec.');
return sdp;
}
trace('Prefer video receive codec: ' + videoRecvCodec);
return preferCodec(sdp, videoRecvCodec,'video');
}
function maybePreferAudioSendCodec(sdp) {
if (audioSendCodec === '') {
trace('No preference on audio send codec.');
return sdp;
}
trace('Prefer audio send codec: ' + audioSendCodec);
return preferCodec(sdp, audioSendCodec, 'audio');
}
function maybePreferAudioReceiveCodec(sdp) {
if (audioRecvCodec === '') {
trace('No preference on audio receive codec.');
return sdp;
}
trace('Prefer audio receive codec: ' + audioRecvCodec);
return preferCodec(sdp, audioRecvCodec, 'audio');
}
function addStereo(sdp) {
var sdpLines = sdp.split('\r\n');
var opusIndex = findLine(sdpLines, 'a=rtpmap', 'opus/48000');
var opusPayload;
if (opusIndex) {
opusPayload = getCodecPayloadType(sdpLines[opusIndex]);
}
var fmtpLineIndex = findLine(sdpLines, 'a=fmtp:' + opusPayload.toString());
if (fmtpLineIndex === null) {
return sdp;
}
sdpLines[fmtpLineIndex] = sdpLines[fmtpLineIndex].concat('; stereo=1');
sdp = sdpLines.join('\r\n');
return sdp;
}
if( isLocal ) {
return function(insdp) {
console.log("modifying local sdp");
var sdp;
sdp = maybePreferAudioReceiveCodec(insdp);
sdp = maybePreferVideoReceiveCodec(insdp);
sdp = maybeSetAudioReceiveBitRate(sdp);
sdp = maybeSetVideoReceiveBitRate(sdp);
//if( sdp != insdp ) {
// console.log("changed the sdp from \n" + insdp + "\nto\n" + sdp);
//}
return sdp;
};
}
else {
return function(insdp) {
console.log("modifying remote sdp");
var sdp = maybePreferAudioSendCodec(insdp);
var sdp = maybePreferVideoSendCodec(insdp);
sdp = maybeSetAudioSendBitRate(sdp);
sdp = maybeSetVideoSendBitRate(sdp);
sdp = maybeSetVideoSendInitialBitRate(sdp);
if (stereo) {
sdp = addStereo(sdp);
}
//if( sdp != insdp ) {
// console.log("changed the sdp from \n" + insdp + "\nto\n" + sdp);
//}
return sdp;
};
}
}
/**
* This function returns an sdp filter function.
* @param options A map that optionally includes values for the following keys: audioRecvCodec, audioRecvBitrate, videoRecvBitrate, videoRecvCodec
* @returns {Function} which takes an SDP string and returns a modified SDP string.
*/
easyrtc.buildLocalSdpFilter = function (options) {
return buildSdpFilter(options, true);
};
/**
* This function returns an sdp filter function.
* @param options A map that optionally includes values for the following keys: stereo, audioSendCodec, audioSendBitrate, videoSendBitrate, videoSendInitialBitRate,
videoRecvCodec
* @returns {Function} which takes an SDP string and returns a modified SDP string.
*/
easyrtc.buildRemoteSdpFilter = function(options) {
return buildSdpFilter(options, false);
};
return easyrtc;
}));
</code></pre>
</article>
</section>
</div>
<nav>
<h2><a href="index.html">Home</a></h2><h3>Classes</h3><ul><li><a href="Easyrtc_Rates.html">Easyrtc_Rates</a></li></ul>
</nav>
<br class="clear">
<footer>
Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.5.0-dev</a> on Tue Oct 11 2016 14:19:27 GMT-0700 (PDT)
</footer>
<script> prettyPrint(); </script>
<script src="scripts/linenumber.js"> </script>
</body>
</html>
| ash24mish/easyrtc | docs/client_html_docs/easyrtc_rates.js.html | HTML | bsd-2-clause | 14,511 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/contacts/google_contact_store.h"
#include <algorithm>
#include "base/bind.h"
#include "base/files/file_path.h"
#include "base/logging.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/contacts/contact.pb.h"
#include "chrome/browser/chromeos/contacts/contact_database.h"
#include "chrome/browser/chromeos/contacts/contact_store_observer.h"
#include "chrome/browser/chromeos/contacts/gdata_contacts_service.h"
#include "chrome/browser/google_apis/auth_service.h"
#include "chrome/browser/google_apis/time_util.h"
#include "chrome/browser/profiles/profile.h"
#include "content/public/browser/browser_thread.h"
using content::BrowserThread;
namespace contacts {
namespace {
// Name of the directory within the profile directory where the contact database
// is stored.
const base::FilePath::CharType kDatabaseDirectoryName[] =
FILE_PATH_LITERAL("Google Contacts");
// We wait this long after the last update has completed successfully before
// updating again.
// TODO(derat): Decide what this should be.
const int kUpdateIntervalSec = 600;
// https://developers.google.com/google-apps/contacts/v3/index says that deleted
// contact (groups?) will only be returned for 30 days after deletion when the
// "showdeleted" parameter is set. If it's been longer than that since the last
// successful update, we do a full refresh to make sure that we haven't missed
// any deletions. Use 29 instead to make sure that we don't run afoul of
// daylight saving time shenanigans or minor skew in the system clock.
const int kForceFullUpdateDays = 29;
// When an update fails, we initially wait this many seconds before retrying.
// The delay increases exponentially in response to repeated failures.
const int kUpdateFailureInitialRetrySec = 5;
// Amount by which |update_delay_on_next_failure_| is multiplied on failure.
const int kUpdateFailureBackoffFactor = 2;
} // namespace
GoogleContactStore::TestAPI::TestAPI(GoogleContactStore* store)
: store_(store) {
DCHECK(store);
}
GoogleContactStore::TestAPI::~TestAPI() {
store_ = NULL;
}
void GoogleContactStore::TestAPI::SetDatabase(ContactDatabaseInterface* db) {
store_->DestroyDatabase();
store_->db_ = db;
}
void GoogleContactStore::TestAPI::SetGDataService(
GDataContactsServiceInterface* service) {
store_->gdata_service_.reset(service);
}
void GoogleContactStore::TestAPI::DoUpdate() {
store_->UpdateContacts();
}
void GoogleContactStore::TestAPI::NotifyAboutNetworkStateChange(bool online) {
net::NetworkChangeNotifier::ConnectionType type =
online ?
net::NetworkChangeNotifier::CONNECTION_UNKNOWN :
net::NetworkChangeNotifier::CONNECTION_NONE;
store_->OnConnectionTypeChanged(type);
}
scoped_ptr<ContactPointers> GoogleContactStore::TestAPI::GetLoadedContacts() {
scoped_ptr<ContactPointers> contacts(new ContactPointers);
for (ContactMap::const_iterator it = store_->contacts_.begin();
it != store_->contacts_.end(); ++it) {
contacts->push_back(it->second);
}
return contacts.Pass();
}
GoogleContactStore::GoogleContactStore(
net::URLRequestContextGetter* url_request_context_getter,
Profile* profile)
: url_request_context_getter_(url_request_context_getter),
profile_(profile),
db_(new ContactDatabase),
update_delay_on_next_failure_(
base::TimeDelta::FromSeconds(kUpdateFailureInitialRetrySec)),
is_online_(true),
should_update_when_online_(false),
weak_ptr_factory_(this) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
net::NetworkChangeNotifier::AddConnectionTypeObserver(this);
is_online_ = !net::NetworkChangeNotifier::IsOffline();
}
GoogleContactStore::~GoogleContactStore() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
weak_ptr_factory_.InvalidateWeakPtrs();
net::NetworkChangeNotifier::RemoveConnectionTypeObserver(this);
DestroyDatabase();
}
void GoogleContactStore::Init() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
// Create a GData service if one hasn't already been assigned for testing.
if (!gdata_service_.get()) {
gdata_service_.reset(new GDataContactsService(
url_request_context_getter_, profile_));
gdata_service_->Initialize();
}
base::FilePath db_path = profile_->GetPath().Append(kDatabaseDirectoryName);
VLOG(1) << "Initializing contact database \"" << db_path.value() << "\" for "
<< profile_->GetProfileName();
db_->Init(db_path,
base::Bind(&GoogleContactStore::OnDatabaseInitialized,
weak_ptr_factory_.GetWeakPtr()));
}
void GoogleContactStore::AppendContacts(ContactPointers* contacts_out) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(contacts_out);
for (ContactMap::const_iterator it = contacts_.begin();
it != contacts_.end(); ++it) {
if (!it->second->deleted())
contacts_out->push_back(it->second);
}
}
const Contact* GoogleContactStore::GetContactById(
const std::string& contact_id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
return contacts_.Find(contact_id);
}
void GoogleContactStore::AddObserver(ContactStoreObserver* observer) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(observer);
observers_.AddObserver(observer);
}
void GoogleContactStore::RemoveObserver(ContactStoreObserver* observer) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(observer);
observers_.RemoveObserver(observer);
}
void GoogleContactStore::OnConnectionTypeChanged(
net::NetworkChangeNotifier::ConnectionType type) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
bool was_online = is_online_;
is_online_ = (type != net::NetworkChangeNotifier::CONNECTION_NONE);
if (!was_online && is_online_ && should_update_when_online_) {
should_update_when_online_ = false;
UpdateContacts();
}
}
base::Time GoogleContactStore::GetCurrentTime() const {
return !current_time_for_testing_.is_null() ?
current_time_for_testing_ :
base::Time::Now();
}
void GoogleContactStore::DestroyDatabase() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (db_) {
db_->DestroyOnUIThread();
db_ = NULL;
}
}
void GoogleContactStore::UpdateContacts() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
// If we're offline, defer the update.
if (!is_online_) {
VLOG(1) << "Deferring contact update due to offline state";
should_update_when_online_ = true;
return;
}
base::Time min_update_time;
base::TimeDelta time_since_last_update =
last_successful_update_start_time_.is_null() ?
base::TimeDelta() :
GetCurrentTime() - last_successful_update_start_time_;
if (!last_contact_update_time_.is_null() &&
time_since_last_update <
base::TimeDelta::FromDays(kForceFullUpdateDays)) {
// TODO(derat): I'm adding one millisecond to the last update time here as I
// don't want to re-download the same most-recently-updated contact each
// time, but what happens if within the same millisecond, contact A is
// updated, we do a sync, and then contact B is updated? I'm probably being
// overly paranoid about this.
min_update_time =
last_contact_update_time_ + base::TimeDelta::FromMilliseconds(1);
}
if (min_update_time.is_null()) {
VLOG(1) << "Downloading all contacts for " << profile_->GetProfileName();
} else {
VLOG(1) << "Downloading contacts updated since "
<< google_apis::util::FormatTimeAsString(min_update_time) << " for "
<< profile_->GetProfileName();
}
gdata_service_->DownloadContacts(
base::Bind(&GoogleContactStore::OnDownloadSuccess,
weak_ptr_factory_.GetWeakPtr(),
min_update_time.is_null(),
GetCurrentTime()),
base::Bind(&GoogleContactStore::OnDownloadFailure,
weak_ptr_factory_.GetWeakPtr()),
min_update_time);
}
void GoogleContactStore::ScheduleUpdate(bool last_update_was_successful) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
base::TimeDelta delay;
if (last_update_was_successful) {
delay = base::TimeDelta::FromSeconds(kUpdateIntervalSec);
update_delay_on_next_failure_ =
base::TimeDelta::FromSeconds(kUpdateFailureInitialRetrySec);
} else {
delay = update_delay_on_next_failure_;
update_delay_on_next_failure_ = std::min(
update_delay_on_next_failure_ * kUpdateFailureBackoffFactor,
base::TimeDelta::FromSeconds(kUpdateIntervalSec));
}
VLOG(1) << "Scheduling update of " << profile_->GetProfileName()
<< " in " << delay.InSeconds() << " second(s)";
update_timer_.Start(
FROM_HERE, delay, this, &GoogleContactStore::UpdateContacts);
}
void GoogleContactStore::MergeContacts(
bool is_full_update,
scoped_ptr<ScopedVector<Contact> > updated_contacts) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (is_full_update) {
contacts_.Clear();
last_contact_update_time_ = base::Time();
}
// Find the maximum update time from |updated_contacts| since contacts whose
// |deleted| flags are set won't be saved to |contacts_|.
for (ScopedVector<Contact>::iterator it = updated_contacts->begin();
it != updated_contacts->end(); ++it) {
last_contact_update_time_ =
std::max(last_contact_update_time_,
base::Time::FromInternalValue((*it)->update_time()));
}
VLOG(1) << "Last contact update time is "
<< google_apis::util::FormatTimeAsString(last_contact_update_time_);
contacts_.Merge(updated_contacts.Pass(), ContactMap::DROP_DELETED_CONTACTS);
}
void GoogleContactStore::OnDownloadSuccess(
bool is_full_update,
const base::Time& update_start_time,
scoped_ptr<ScopedVector<Contact> > updated_contacts) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
VLOG(1) << "Got " << updated_contacts->size() << " contact(s) for "
<< profile_->GetProfileName();
// Copy the pointers so we can update just these contacts in the database.
scoped_ptr<ContactPointers> contacts_to_save_to_db(new ContactPointers);
scoped_ptr<ContactDatabaseInterface::ContactIds>
contact_ids_to_delete_from_db(new ContactDatabaseInterface::ContactIds);
if (db_) {
for (size_t i = 0; i < updated_contacts->size(); ++i) {
Contact* contact = (*updated_contacts)[i];
if (contact->deleted())
contact_ids_to_delete_from_db->push_back(contact->contact_id());
else
contacts_to_save_to_db->push_back(contact);
}
}
bool got_updates = !updated_contacts->empty();
MergeContacts(is_full_update, updated_contacts.Pass());
last_successful_update_start_time_ = update_start_time;
if (is_full_update || got_updates) {
FOR_EACH_OBSERVER(ContactStoreObserver,
observers_,
OnContactsUpdated(this));
}
if (db_) {
// Even if this was an incremental update and we didn't get any updated
// contacts, we still want to write updated metadata containing
// |update_start_time|.
VLOG(1) << "Saving " << contacts_to_save_to_db->size() << " contact(s) to "
<< "database and deleting " << contact_ids_to_delete_from_db->size()
<< " as " << (is_full_update ? "full" : "incremental") << " update";
scoped_ptr<UpdateMetadata> metadata(new UpdateMetadata);
metadata->set_last_update_start_time(update_start_time.ToInternalValue());
metadata->set_last_contact_update_time(
last_contact_update_time_.ToInternalValue());
db_->SaveContacts(
contacts_to_save_to_db.Pass(),
contact_ids_to_delete_from_db.Pass(),
metadata.Pass(),
is_full_update,
base::Bind(&GoogleContactStore::OnDatabaseContactsSaved,
weak_ptr_factory_.GetWeakPtr()));
// We'll schedule an update from OnDatabaseContactsSaved() after we're done
// writing to the database -- we don't want to modify the contacts while
// they're being used by the database.
} else {
ScheduleUpdate(true);
}
}
void GoogleContactStore::OnDownloadFailure() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
LOG(WARNING) << "Contacts download failed for " << profile_->GetProfileName();
ScheduleUpdate(false);
}
void GoogleContactStore::OnDatabaseInitialized(bool success) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (success) {
VLOG(1) << "Contact database initialized for "
<< profile_->GetProfileName();
db_->LoadContacts(base::Bind(&GoogleContactStore::OnDatabaseContactsLoaded,
weak_ptr_factory_.GetWeakPtr()));
} else {
LOG(WARNING) << "Failed to initialize contact database for "
<< profile_->GetProfileName();
// Limp along as best as we can: throw away the database and do an update,
// which will schedule further updates.
DestroyDatabase();
UpdateContacts();
}
}
void GoogleContactStore::OnDatabaseContactsLoaded(
bool success,
scoped_ptr<ScopedVector<Contact> > contacts,
scoped_ptr<UpdateMetadata> metadata) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (success) {
VLOG(1) << "Loaded " << contacts->size() << " contact(s) from database";
MergeContacts(true, contacts.Pass());
last_successful_update_start_time_ =
base::Time::FromInternalValue(metadata->last_update_start_time());
last_contact_update_time_ = std::max(
last_contact_update_time_,
base::Time::FromInternalValue(metadata->last_contact_update_time()));
if (!contacts_.empty()) {
FOR_EACH_OBSERVER(ContactStoreObserver,
observers_,
OnContactsUpdated(this));
}
} else {
LOG(WARNING) << "Failed to load contacts from database";
}
UpdateContacts();
}
void GoogleContactStore::OnDatabaseContactsSaved(bool success) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (!success)
LOG(WARNING) << "Failed to save contacts to database";
// We only update the database when we've successfully downloaded contacts, so
// report success to ScheduleUpdate() even if the database update failed.
ScheduleUpdate(true);
}
GoogleContactStoreFactory::GoogleContactStoreFactory() {
}
GoogleContactStoreFactory::~GoogleContactStoreFactory() {
}
bool GoogleContactStoreFactory::CanCreateContactStoreForProfile(
Profile* profile) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(profile);
return google_apis::AuthService::CanAuthenticate(profile);
}
ContactStore* GoogleContactStoreFactory::CreateContactStore(Profile* profile) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(CanCreateContactStoreForProfile(profile));
return new GoogleContactStore(
g_browser_process->system_request_context(), profile);
}
} // namespace contacts
| espadrine/opera | chromium/src/chrome/browser/chromeos/contacts/google_contact_store.cc | C++ | bsd-3-clause | 15,152 |
/************************************************************************************
* configs/stm3240g-eval/src/up_selectsram.c
* arch/arm/src/board/up_selectsram.c
*
* Copyright (C) 2012 Gregory Nutt. All rights reserved.
* Author: Gregory Nutt <[email protected]>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name NuttX nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
************************************************************************************/
/************************************************************************************
* Included Files
************************************************************************************/
#include <nuttx/config.h>
#include <stdint.h>
#include <debug.h>
#include "chip.h"
#include "up_arch.h"
#include "stm32.h"
#include "stm3240g-internal.h"
#ifdef CONFIG_STM32_FSMC
/************************************************************************************
* Pre-processor Definitions
************************************************************************************/
#if STM32_NGPIO_PORTS < 6
# error "Required GPIO ports not enabled"
#endif
/* SRAM Timing */
#define SRAM_ADDRESS_SETUP_TIME 3
#define SRAM_ADDRESS_HOLD_TIME 0
#define SRAM_DATA_SETUP_TIME 6
#define SRAM_BUS_TURNAROUND_DURATION 1
#define SRAM_CLK_DIVISION 0
#define SRAM_DATA_LATENCY 0
/* SRAM pin definitions */
#define SRAM_NADDRLINES 21
#define SRAM_NDATALINES 16
/************************************************************************************
* Public Data
************************************************************************************/
/************************************************************************************
* Private Data
************************************************************************************/
/* GPIOs Configuration **************************************************************
* PD0 <-> FSMC_D2 PE0 <-> FSMC_NBL0 PF0 <-> FSMC_A0 PG0 <-> FSMC_A10
* PD1 <-> FSMC_D3 PE1 <-> FSMC_NBL1 PF1 <-> FSMC_A1 PG1 <-> FSMC_A11
* PD4 <-> FSMC_NOE PE3 <-> FSMC_A19 PF2 <-> FSMC_A2 PG2 <-> FSMC_A12
* PD5 <-> FSMC_NWE PE4 <-> FSMC_A20 PF3 <-> FSMC_A3 PG3 <-> FSMC_A13
* PD8 <-> FSMC_D13 PE7 <-> FSMC_D4 PF4 <-> FSMC_A4 PG4 <-> FSMC_A14
* PD9 <-> FSMC_D14 PE8 <-> FSMC_D5 PF5 <-> FSMC_A5 PG5 <-> FSMC_A15
* PD10 <-> FSMC_D15 PE9 <-> FSMC_D6 PF12 <-> FSMC_A6 PG9 <-> FSMC_NE2
* PD11 <-> FSMC_A16 PE10 <-> FSMC_D7 PF13 <-> FSMC_A7
* PD12 <-> FSMC_A17 PE11 <-> FSMC_D8 PF14 <-> FSMC_A8
* PD13 <-> FSMC_A18 PE12 <-> FSMC_D9 PF15 <-> FSMC_A9
* PD14 <-> FSMC_D0 PE13 <-> FSMC_D10
* PD15 <-> FSMC_D1 PE14 <-> FSMC_D11
* PE15 <-> FSMC_D12
*/
/* GPIO configurations unique to SRAM */
static const uint32_t g_sramconfig[] =
{
/* NE3, NBL0, NBL1, */
GPIO_FSMC_NOE, GPIO_FSMC_NWE, GPIO_FSMC_NBL0, GPIO_FSMC_NBL1, GPIO_FSMC_NE2
};
#define NSRAM_CONFIG (sizeof(g_sramconfig)/sizeof(uint32_t))
/************************************************************************************
* Private Functions
************************************************************************************/
/************************************************************************************
* Public Functions
************************************************************************************/
/************************************************************************************
* Name: stm32_selectsram
*
* Description:
* Initialize to access external SRAM. SRAM will be visible at the FSMC Bank
* NOR/SRAM2 base address (0x64000000)
*
* General transaction rules. The requested AHB transaction data size can be 8-,
* 16- or 32-bit wide whereas the SRAM has a fixed 16-bit data width. Some simple
* transaction rules must be followed:
*
* Case 1: AHB transaction width and SRAM data width are equal
* There is no issue in this case.
* Case 2: AHB transaction size is greater than the memory size
* In this case, the FSMC splits the AHB transaction into smaller consecutive
* memory accesses in order to meet the external data width.
* Case 3: AHB transaction size is smaller than the memory size.
* SRAM supports the byte select feature.
* a) FSMC allows write transactions accessing the right data through its
* byte lanes (NBL[1:0])
* b) Read transactions are allowed (the controller reads the entire memory
* word and uses the needed byte only). The NBL[1:0] are always kept low
* during read transactions.
*
************************************************************************************/
void stm32_selectsram(void)
{
/* Configure new GPIO pins */
stm32_extmemaddr(SRAM_NADDRLINES); /* Common address lines: A0-A20 */
stm32_extmemdata(SRAM_NDATALINES); /* Common data lines: D0-D15 */
stm32_extmemgpios(g_sramconfig, NSRAM_CONFIG); /* SRAM-specific control lines */
/* Enable AHB clocking to the FSMC */
stm32_enablefsmc();
/* Bank1 NOR/SRAM control register configuration
*
* Bank enable : Not yet
* Data address mux : Disabled
* Memory Type : PSRAM
* Data bus width : 16-bits
* Flash access : Disabled
* Burst access mode : Disabled
* Polarity : Low
* Wrapped burst mode : Disabled
* Write timing : Before state
* Write enable : Yes
* Wait signal : Disabled
* Extended mode : Disabled
* Asynchronous wait : Disabled
* Write burst : Disabled
*/
putreg32((FSMC_BCR_PSRAM | FSMC_BCR_MWID16 | FSMC_BCR_WREN), STM32_FSMC_BCR2);
/* Bank1 NOR/SRAM timing register configuration */
putreg32((FSMC_BTR_ADDSET(SRAM_ADDRESS_SETUP_TIME) | FSMC_BTR_ADDHLD(SRAM_ADDRESS_HOLD_TIME) |
FSMC_BTR_DATAST(SRAM_DATA_SETUP_TIME) | FSMC_BTR_BUSTRUN(SRAM_BUS_TURNAROUND_DURATION) |
FSMC_BTR_CLKDIV(SRAM_CLK_DIVISION) | FSMC_BTR_DATLAT(SRAM_DATA_LATENCY) |
FSMC_BTR_ACCMODA),
STM32_FSMC_BTR2);
/* Bank1 NOR/SRAM timing register for write configuration, if extended mode is used */
putreg32(0xffffffff, STM32_FSMC_BWTR2); /* Extended mode not used */
/* Enable the bank */
putreg32((FSMC_BCR_MBKEN | FSMC_BCR_PSRAM | FSMC_BCR_MWID16 | FSMC_BCR_WREN), STM32_FSMC_BCR2);
}
#endif /* CONFIG_STM32_FSMC */
| gcds/project_xxx | nuttx/configs/stm3240g-eval/src/up_selectsram.c | C | bsd-3-clause | 7,923 |
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_BROWSER_PROCESS_PLATFORM_PART_CHROMEOS_H_
#define CHROME_BROWSER_BROWSER_PROCESS_PLATFORM_PART_CHROMEOS_H_
#include "base/compiler_specific.h"
#include "base/memory/scoped_ptr.h"
#include "base/threading/non_thread_safe.h"
#include "chrome/browser/browser_process_platform_part_base.h"
namespace base {
class CommandLine;
}
namespace chromeos {
class ChromeUserManager;
class ProfileHelper;
class TimeZoneResolver;
}
namespace chromeos {
namespace system {
class AutomaticRebootManager;
class DeviceDisablingManager;
class DeviceDisablingManagerDefaultDelegate;
}
}
namespace policy {
class BrowserPolicyConnector;
class BrowserPolicyConnectorChromeOS;
}
namespace session_manager {
class SessionManager;
}
class Profile;
class BrowserProcessPlatformPart : public BrowserProcessPlatformPartBase,
public base::NonThreadSafe {
public:
BrowserProcessPlatformPart();
~BrowserProcessPlatformPart() override;
void InitializeAutomaticRebootManager();
void ShutdownAutomaticRebootManager();
void InitializeChromeUserManager();
void DestroyChromeUserManager();
void InitializeDeviceDisablingManager();
void ShutdownDeviceDisablingManager();
void InitializeSessionManager(const base::CommandLine& parsed_command_line,
Profile* profile,
bool is_running_test);
void ShutdownSessionManager();
// Disable the offline interstitial easter egg if the device is enterprise
// enrolled.
void DisableDinoEasterEggIfEnrolled();
// Returns the SessionManager instance that is used to initialize and
// start user sessions as well as responsible on launching pre-session UI like
// out-of-box or login.
virtual session_manager::SessionManager* SessionManager();
// Returns the ProfileHelper instance that is used to identify
// users and their profiles in Chrome OS multi user session.
chromeos::ProfileHelper* profile_helper();
chromeos::system::AutomaticRebootManager* automatic_reboot_manager() {
return automatic_reboot_manager_.get();
}
policy::BrowserPolicyConnectorChromeOS* browser_policy_connector_chromeos();
chromeos::ChromeUserManager* user_manager() {
return chrome_user_manager_.get();
}
chromeos::system::DeviceDisablingManager* device_disabling_manager() {
return device_disabling_manager_.get();
}
chromeos::TimeZoneResolver* GetTimezoneResolver();
// Overridden from BrowserProcessPlatformPartBase:
void StartTearDown() override;
scoped_ptr<policy::BrowserPolicyConnector> CreateBrowserPolicyConnector()
override;
private:
void CreateProfileHelper();
scoped_ptr<session_manager::SessionManager> session_manager_;
bool created_profile_helper_;
scoped_ptr<chromeos::ProfileHelper> profile_helper_;
scoped_ptr<chromeos::system::AutomaticRebootManager>
automatic_reboot_manager_;
scoped_ptr<chromeos::ChromeUserManager> chrome_user_manager_;
scoped_ptr<chromeos::system::DeviceDisablingManagerDefaultDelegate>
device_disabling_manager_delegate_;
scoped_ptr<chromeos::system::DeviceDisablingManager>
device_disabling_manager_;
scoped_ptr<chromeos::TimeZoneResolver> timezone_resolver_;
DISALLOW_COPY_AND_ASSIGN(BrowserProcessPlatformPart);
};
#endif // CHROME_BROWSER_BROWSER_PROCESS_PLATFORM_PART_CHROMEOS_H_
| SaschaMester/delicium | chrome/browser/browser_process_platform_part_chromeos.h | C | bsd-3-clause | 3,544 |
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// CRX filesystem is a filesystem that allows an extension to read its own
// package directory tree. See ppapi/examples/crxfs for example.
//
// IMPLEMENTATION
//
// The implementation involves both browser and renderer. In order to provide
// readonly access to CRX filesystem (i.e. extension directory), we create an
// "isolated filesystem" pointing to current extension directory in browser.
// Then browser grants read permission to renderer, and tells plugin the
// filesystem id, or fsid.
//
// Once the plugin receives the fsid, it creates a PPB_FileSystem and forwards
// the fsid to PepperFileSystemHost in order to construct root url.
#ifndef PPAPI_PROXY_ISOLATED_FILE_SYSTEM_PRIVATE_RESOURCE_H_
#define PPAPI_PROXY_ISOLATED_FILE_SYSTEM_PRIVATE_RESOURCE_H_
#include <stdint.h>
#include <string>
#include "base/memory/ref_counted.h"
#include "ppapi/proxy/connection.h"
#include "ppapi/proxy/plugin_resource.h"
#include "ppapi/proxy/ppapi_proxy_export.h"
#include "ppapi/thunk/ppb_isolated_file_system_private_api.h"
namespace ppapi {
class TrackedCallback;
namespace proxy {
class ResourceMessageReplyParams;
class PPAPI_PROXY_EXPORT IsolatedFileSystemPrivateResource
: public PluginResource,
public thunk::PPB_IsolatedFileSystem_Private_API {
public:
IsolatedFileSystemPrivateResource(
Connection connection, PP_Instance instance);
IsolatedFileSystemPrivateResource(const IsolatedFileSystemPrivateResource&) =
delete;
IsolatedFileSystemPrivateResource& operator=(
const IsolatedFileSystemPrivateResource&) = delete;
~IsolatedFileSystemPrivateResource() override;
// Resource overrides.
thunk::PPB_IsolatedFileSystem_Private_API*
AsPPB_IsolatedFileSystem_Private_API() override;
// PPB_IsolatedFileSystem_Private_API implementation.
int32_t Open(PP_Instance instance,
PP_IsolatedFileSystemType_Private type,
PP_Resource* file_system_resource,
scoped_refptr<TrackedCallback> callback) override;
private:
void OnBrowserOpenComplete(PP_IsolatedFileSystemType_Private type,
PP_Resource* file_system_resource,
scoped_refptr<TrackedCallback> callback,
const ResourceMessageReplyParams& params,
const std::string& fsid);
};
} // namespace proxy
} // namespace ppapi
#endif // PPAPI_PROXY_ISOLATED_FILE_SYSTEM_PRIVATE_RESOURCE_H_
| chromium/chromium | ppapi/proxy/isolated_file_system_private_resource.h | C | bsd-3-clause | 2,637 |
<?php
/**
* Copyright 2007 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.
*/
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/appengine/api/memcache/memcache_service.proto
namespace dummy {
require_once 'google/appengine/runtime/proto/ProtocolMessage.php';
}
namespace google\appengine\MemcacheServiceError {
class ErrorCode {
const OK = 0;
const UNSPECIFIED_ERROR = 1;
const NAMESPACE_NOT_SET = 2;
const PERMISSION_DENIED = 3;
const INVALID_VALUE = 6;
const UNAVAILABLE = 9;
}
}
namespace google\appengine {
class MemcacheServiceError extends \google\net\ProtocolMessage {
public function clear() {
}
public function byteSizePartial() {
$res = 0;
return $res;
}
public function outputPartial($out) {
}
public function tryMerge($d) {
while($d->avail() > 0) {
$tt = $d->getVarInt32();
switch ($tt) {
case 0:
throw new \google\net\ProtocolBufferDecodeError();
break;
default:
$d->skipData($tt);
}
};
}
public function checkInitialized() {
return null;
}
public function mergeFrom($x) {
if ($x === $this) { throw new \IllegalArgumentException('Cannot copy message to itself'); }
}
public function equals($x) {
if ($x === $this) { return true; }
return true;
}
public function shortDebugString($prefix = "") {
$res = '';
return $res;
}
}
}
namespace google\appengine {
class AppOverride extends \google\net\ProtocolMessage {
public function getAppId() {
if (!isset($this->app_id)) {
return '';
}
return $this->app_id;
}
public function setAppId($val) {
$this->app_id = $val;
return $this;
}
public function clearAppId() {
unset($this->app_id);
return $this;
}
public function hasAppId() {
return isset($this->app_id);
}
public function getNumMemcachegBackends() {
if (!isset($this->num_memcacheg_backends)) {
return 0;
}
return $this->num_memcacheg_backends;
}
public function setNumMemcachegBackends($val) {
$this->num_memcacheg_backends = $val;
return $this;
}
public function clearNumMemcachegBackends() {
unset($this->num_memcacheg_backends);
return $this;
}
public function hasNumMemcachegBackends() {
return isset($this->num_memcacheg_backends);
}
public function getIgnoreShardlock() {
if (!isset($this->ignore_shardlock)) {
return false;
}
return $this->ignore_shardlock;
}
public function setIgnoreShardlock($val) {
$this->ignore_shardlock = $val;
return $this;
}
public function clearIgnoreShardlock() {
unset($this->ignore_shardlock);
return $this;
}
public function hasIgnoreShardlock() {
return isset($this->ignore_shardlock);
}
public function getMemcachePoolHint() {
if (!isset($this->memcache_pool_hint)) {
return '';
}
return $this->memcache_pool_hint;
}
public function setMemcachePoolHint($val) {
$this->memcache_pool_hint = $val;
return $this;
}
public function clearMemcachePoolHint() {
unset($this->memcache_pool_hint);
return $this;
}
public function hasMemcachePoolHint() {
return isset($this->memcache_pool_hint);
}
public function getMemcacheShardingStrategy() {
if (!isset($this->memcache_sharding_strategy)) {
return '';
}
return $this->memcache_sharding_strategy;
}
public function setMemcacheShardingStrategy($val) {
$this->memcache_sharding_strategy = $val;
return $this;
}
public function clearMemcacheShardingStrategy() {
unset($this->memcache_sharding_strategy);
return $this;
}
public function hasMemcacheShardingStrategy() {
return isset($this->memcache_sharding_strategy);
}
public function clear() {
$this->clearAppId();
$this->clearNumMemcachegBackends();
$this->clearIgnoreShardlock();
$this->clearMemcachePoolHint();
$this->clearMemcacheShardingStrategy();
}
public function byteSizePartial() {
$res = 0;
if (isset($this->app_id)) {
$res += 1;
$res += $this->lengthString(strlen($this->app_id));
}
if (isset($this->num_memcacheg_backends)) {
$res += 1;
$res += $this->lengthVarInt64($this->num_memcacheg_backends);
}
if (isset($this->ignore_shardlock)) {
$res += 2;
}
if (isset($this->memcache_pool_hint)) {
$res += 1;
$res += $this->lengthString(strlen($this->memcache_pool_hint));
}
if (isset($this->memcache_sharding_strategy)) {
$res += 1;
$res += $this->lengthString(strlen($this->memcache_sharding_strategy));
}
return $res;
}
public function outputPartial($out) {
if (isset($this->app_id)) {
$out->putVarInt32(10);
$out->putPrefixedString($this->app_id);
}
if (isset($this->num_memcacheg_backends)) {
$out->putVarInt32(16);
$out->putVarInt32($this->num_memcacheg_backends);
}
if (isset($this->ignore_shardlock)) {
$out->putVarInt32(24);
$out->putBoolean($this->ignore_shardlock);
}
if (isset($this->memcache_pool_hint)) {
$out->putVarInt32(34);
$out->putPrefixedString($this->memcache_pool_hint);
}
if (isset($this->memcache_sharding_strategy)) {
$out->putVarInt32(42);
$out->putPrefixedString($this->memcache_sharding_strategy);
}
}
public function tryMerge($d) {
while($d->avail() > 0) {
$tt = $d->getVarInt32();
switch ($tt) {
case 10:
$length = $d->getVarInt32();
$this->setAppId(substr($d->buffer(), $d->pos(), $length));
$d->skip($length);
break;
case 16:
$this->setNumMemcachegBackends($d->getVarInt32());
break;
case 24:
$this->setIgnoreShardlock($d->getBoolean());
break;
case 34:
$length = $d->getVarInt32();
$this->setMemcachePoolHint(substr($d->buffer(), $d->pos(), $length));
$d->skip($length);
break;
case 42:
$length = $d->getVarInt32();
$this->setMemcacheShardingStrategy(substr($d->buffer(), $d->pos(), $length));
$d->skip($length);
break;
case 0:
throw new \google\net\ProtocolBufferDecodeError();
break;
default:
$d->skipData($tt);
}
};
}
public function checkInitialized() {
if (!isset($this->app_id)) return 'app_id';
return null;
}
public function mergeFrom($x) {
if ($x === $this) { throw new \IllegalArgumentException('Cannot copy message to itself'); }
if ($x->hasAppId()) {
$this->setAppId($x->getAppId());
}
if ($x->hasNumMemcachegBackends()) {
$this->setNumMemcachegBackends($x->getNumMemcachegBackends());
}
if ($x->hasIgnoreShardlock()) {
$this->setIgnoreShardlock($x->getIgnoreShardlock());
}
if ($x->hasMemcachePoolHint()) {
$this->setMemcachePoolHint($x->getMemcachePoolHint());
}
if ($x->hasMemcacheShardingStrategy()) {
$this->setMemcacheShardingStrategy($x->getMemcacheShardingStrategy());
}
}
public function equals($x) {
if ($x === $this) { return true; }
if (isset($this->app_id) !== isset($x->app_id)) return false;
if (isset($this->app_id) && $this->app_id !== $x->app_id) return false;
if (isset($this->num_memcacheg_backends) !== isset($x->num_memcacheg_backends)) return false;
if (isset($this->num_memcacheg_backends) && !$this->integerEquals($this->num_memcacheg_backends, $x->num_memcacheg_backends)) return false;
if (isset($this->ignore_shardlock) !== isset($x->ignore_shardlock)) return false;
if (isset($this->ignore_shardlock) && $this->ignore_shardlock !== $x->ignore_shardlock) return false;
if (isset($this->memcache_pool_hint) !== isset($x->memcache_pool_hint)) return false;
if (isset($this->memcache_pool_hint) && $this->memcache_pool_hint !== $x->memcache_pool_hint) return false;
if (isset($this->memcache_sharding_strategy) !== isset($x->memcache_sharding_strategy)) return false;
if (isset($this->memcache_sharding_strategy) && $this->memcache_sharding_strategy !== $x->memcache_sharding_strategy) return false;
return true;
}
public function shortDebugString($prefix = "") {
$res = '';
if (isset($this->app_id)) {
$res .= $prefix . "app_id: " . $this->debugFormatString($this->app_id) . "\n";
}
if (isset($this->num_memcacheg_backends)) {
$res .= $prefix . "num_memcacheg_backends: " . $this->debugFormatInt32($this->num_memcacheg_backends) . "\n";
}
if (isset($this->ignore_shardlock)) {
$res .= $prefix . "ignore_shardlock: " . $this->debugFormatBool($this->ignore_shardlock) . "\n";
}
if (isset($this->memcache_pool_hint)) {
$res .= $prefix . "memcache_pool_hint: " . $this->debugFormatString($this->memcache_pool_hint) . "\n";
}
if (isset($this->memcache_sharding_strategy)) {
$res .= $prefix . "memcache_sharding_strategy: " . $this->debugFormatString($this->memcache_sharding_strategy) . "\n";
}
return $res;
}
}
}
namespace google\appengine {
class MemcacheGetRequest extends \google\net\ProtocolMessage {
private $key = array();
public function getKeySize() {
return sizeof($this->key);
}
public function getKeyList() {
return $this->key;
}
public function getKey($idx) {
return $this->key[$idx];
}
public function setKey($idx, $val) {
$this->key[$idx] = $val;
return $this;
}
public function addKey($val) {
$this->key[] = $val;
return $this;
}
public function clearKey() {
$this->key = array();
}
public function getNameSpace() {
if (!isset($this->name_space)) {
return '';
}
return $this->name_space;
}
public function setNameSpace($val) {
$this->name_space = $val;
return $this;
}
public function clearNameSpace() {
unset($this->name_space);
return $this;
}
public function hasNameSpace() {
return isset($this->name_space);
}
public function getForCas() {
if (!isset($this->for_cas)) {
return false;
}
return $this->for_cas;
}
public function setForCas($val) {
$this->for_cas = $val;
return $this;
}
public function clearForCas() {
unset($this->for_cas);
return $this;
}
public function hasForCas() {
return isset($this->for_cas);
}
public function getOverride() {
if (!isset($this->override)) {
return new \google\appengine\AppOverride();
}
return $this->override;
}
public function mutableOverride() {
if (!isset($this->override)) {
$res = new \google\appengine\AppOverride();
$this->override = $res;
return $res;
}
return $this->override;
}
public function clearOverride() {
if (isset($this->override)) {
unset($this->override);
}
}
public function hasOverride() {
return isset($this->override);
}
public function clear() {
$this->clearKey();
$this->clearNameSpace();
$this->clearForCas();
$this->clearOverride();
}
public function byteSizePartial() {
$res = 0;
$this->checkProtoArray($this->key);
$res += 1 * sizeof($this->key);
foreach ($this->key as $value) {
$res += $this->lengthString(strlen($value));
}
if (isset($this->name_space)) {
$res += 1;
$res += $this->lengthString(strlen($this->name_space));
}
if (isset($this->for_cas)) {
$res += 2;
}
if (isset($this->override)) {
$res += 1;
$res += $this->lengthString($this->override->byteSizePartial());
}
return $res;
}
public function outputPartial($out) {
$this->checkProtoArray($this->key);
foreach ($this->key as $value) {
$out->putVarInt32(10);
$out->putPrefixedString($value);
}
if (isset($this->name_space)) {
$out->putVarInt32(18);
$out->putPrefixedString($this->name_space);
}
if (isset($this->for_cas)) {
$out->putVarInt32(32);
$out->putBoolean($this->for_cas);
}
if (isset($this->override)) {
$out->putVarInt32(42);
$out->putVarInt32($this->override->byteSizePartial());
$this->override->outputPartial($out);
}
}
public function tryMerge($d) {
while($d->avail() > 0) {
$tt = $d->getVarInt32();
switch ($tt) {
case 10:
$length = $d->getVarInt32();
$this->addKey(substr($d->buffer(), $d->pos(), $length));
$d->skip($length);
break;
case 18:
$length = $d->getVarInt32();
$this->setNameSpace(substr($d->buffer(), $d->pos(), $length));
$d->skip($length);
break;
case 32:
$this->setForCas($d->getBoolean());
break;
case 42:
$length = $d->getVarInt32();
$tmp = new \google\net\Decoder($d->buffer(), $d->pos(), $d->pos() + $length);
$d->skip($length);
$this->mutableOverride()->tryMerge($tmp);
break;
case 0:
throw new \google\net\ProtocolBufferDecodeError();
break;
default:
$d->skipData($tt);
}
};
}
public function checkInitialized() {
if (isset($this->override) && (!$this->override->isInitialized())) return 'override';
return null;
}
public function mergeFrom($x) {
if ($x === $this) { throw new \IllegalArgumentException('Cannot copy message to itself'); }
foreach ($x->getKeyList() as $v) {
$this->addKey($v);
}
if ($x->hasNameSpace()) {
$this->setNameSpace($x->getNameSpace());
}
if ($x->hasForCas()) {
$this->setForCas($x->getForCas());
}
if ($x->hasOverride()) {
$this->mutableOverride()->mergeFrom($x->getOverride());
}
}
public function equals($x) {
if ($x === $this) { return true; }
if (sizeof($this->key) !== sizeof($x->key)) return false;
foreach (array_map(null, $this->key, $x->key) as $v) {
if ($v[0] !== $v[1]) return false;
}
if (isset($this->name_space) !== isset($x->name_space)) return false;
if (isset($this->name_space) && $this->name_space !== $x->name_space) return false;
if (isset($this->for_cas) !== isset($x->for_cas)) return false;
if (isset($this->for_cas) && $this->for_cas !== $x->for_cas) return false;
if (isset($this->override) !== isset($x->override)) return false;
if (isset($this->override) && !$this->override->equals($x->override)) return false;
return true;
}
public function shortDebugString($prefix = "") {
$res = '';
foreach ($this->key as $value) {
$res .= $prefix . "key: " . $this->debugFormatString($value) . "\n";
}
if (isset($this->name_space)) {
$res .= $prefix . "name_space: " . $this->debugFormatString($this->name_space) . "\n";
}
if (isset($this->for_cas)) {
$res .= $prefix . "for_cas: " . $this->debugFormatBool($this->for_cas) . "\n";
}
if (isset($this->override)) {
$res .= $prefix . "override <\n" . $this->override->shortDebugString($prefix . " ") . $prefix . ">\n";
}
return $res;
}
}
}
namespace google\appengine\MemcacheGetResponse {
class Item extends \google\net\ProtocolMessage {
public function getKey() {
if (!isset($this->key)) {
return '';
}
return $this->key;
}
public function setKey($val) {
$this->key = $val;
return $this;
}
public function clearKey() {
unset($this->key);
return $this;
}
public function hasKey() {
return isset($this->key);
}
public function getValue() {
if (!isset($this->value)) {
return '';
}
return $this->value;
}
public function setValue($val) {
$this->value = $val;
return $this;
}
public function clearValue() {
unset($this->value);
return $this;
}
public function hasValue() {
return isset($this->value);
}
public function getFlags() {
if (!isset($this->flags)) {
return "0";
}
return $this->flags;
}
public function setFlags($val) {
$this->flags = $val;
return $this;
}
public function clearFlags() {
unset($this->flags);
return $this;
}
public function hasFlags() {
return isset($this->flags);
}
public function getCasId() {
if (!isset($this->cas_id)) {
return "0";
}
return $this->cas_id;
}
public function setCasId($val) {
if (is_double($val)) {
$this->cas_id = sprintf('%0.0F', $val);
} else {
$this->cas_id = $val;
}
return $this;
}
public function clearCasId() {
unset($this->cas_id);
return $this;
}
public function hasCasId() {
return isset($this->cas_id);
}
public function getExpiresInSeconds() {
if (!isset($this->expires_in_seconds)) {
return 0;
}
return $this->expires_in_seconds;
}
public function setExpiresInSeconds($val) {
$this->expires_in_seconds = $val;
return $this;
}
public function clearExpiresInSeconds() {
unset($this->expires_in_seconds);
return $this;
}
public function hasExpiresInSeconds() {
return isset($this->expires_in_seconds);
}
public function clear() {
$this->clearKey();
$this->clearValue();
$this->clearFlags();
$this->clearCasId();
$this->clearExpiresInSeconds();
}
public function byteSizePartial() {
$res = 0;
if (isset($this->key)) {
$res += 1;
$res += $this->lengthString(strlen($this->key));
}
if (isset($this->value)) {
$res += 1;
$res += $this->lengthString(strlen($this->value));
}
if (isset($this->flags)) {
$res += 5;
}
if (isset($this->cas_id)) {
$res += 9;
}
if (isset($this->expires_in_seconds)) {
$res += 1;
$res += $this->lengthVarInt64($this->expires_in_seconds);
}
return $res;
}
public function outputPartial($out) {
if (isset($this->key)) {
$out->putVarInt32(18);
$out->putPrefixedString($this->key);
}
if (isset($this->value)) {
$out->putVarInt32(26);
$out->putPrefixedString($this->value);
}
if (isset($this->flags)) {
$out->putVarInt32(37);
$out->put32($this->flags);
}
if (isset($this->cas_id)) {
$out->putVarInt32(41);
$out->put64($this->cas_id);
}
if (isset($this->expires_in_seconds)) {
$out->putVarInt32(48);
$out->putVarInt32($this->expires_in_seconds);
}
}
public function tryMerge($d) {
while($d->avail() > 0) {
$tt = $d->getVarInt32();
switch ($tt) {
case 12: return;
case 18:
$length = $d->getVarInt32();
$this->setKey(substr($d->buffer(), $d->pos(), $length));
$d->skip($length);
break;
case 26:
$length = $d->getVarInt32();
$this->setValue(substr($d->buffer(), $d->pos(), $length));
$d->skip($length);
break;
case 37:
$this->setFlags($d->getFixed32());
break;
case 41:
$this->setCasId($d->getFixed64());
break;
case 48:
$this->setExpiresInSeconds($d->getVarInt32());
break;
case 0:
throw new \google\net\ProtocolBufferDecodeError();
break;
default:
$d->skipData($tt);
}
};
}
public function checkInitialized() {
if (!isset($this->key)) return 'key';
if (!isset($this->value)) return 'value';
return null;
}
public function mergeFrom($x) {
if ($x === $this) { throw new \IllegalArgumentException('Cannot copy message to itself'); }
if ($x->hasKey()) {
$this->setKey($x->getKey());
}
if ($x->hasValue()) {
$this->setValue($x->getValue());
}
if ($x->hasFlags()) {
$this->setFlags($x->getFlags());
}
if ($x->hasCasId()) {
$this->setCasId($x->getCasId());
}
if ($x->hasExpiresInSeconds()) {
$this->setExpiresInSeconds($x->getExpiresInSeconds());
}
}
public function equals($x) {
if ($x === $this) { return true; }
if (isset($this->key) !== isset($x->key)) return false;
if (isset($this->key) && $this->key !== $x->key) return false;
if (isset($this->value) !== isset($x->value)) return false;
if (isset($this->value) && $this->value !== $x->value) return false;
if (isset($this->flags) !== isset($x->flags)) return false;
if (isset($this->flags) && !$this->integerEquals($this->flags, $x->flags)) return false;
if (isset($this->cas_id) !== isset($x->cas_id)) return false;
if (isset($this->cas_id) && !$this->integerEquals($this->cas_id, $x->cas_id)) return false;
if (isset($this->expires_in_seconds) !== isset($x->expires_in_seconds)) return false;
if (isset($this->expires_in_seconds) && !$this->integerEquals($this->expires_in_seconds, $x->expires_in_seconds)) return false;
return true;
}
public function shortDebugString($prefix = "") {
$res = '';
if (isset($this->key)) {
$res .= $prefix . "key: " . $this->debugFormatString($this->key) . "\n";
}
if (isset($this->value)) {
$res .= $prefix . "value: " . $this->debugFormatString($this->value) . "\n";
}
if (isset($this->flags)) {
$res .= $prefix . "flags: " . $this->debugFormatFixed32($this->flags) . "\n";
}
if (isset($this->cas_id)) {
$res .= $prefix . "cas_id: " . $this->debugFormatFixed64($this->cas_id) . "\n";
}
if (isset($this->expires_in_seconds)) {
$res .= $prefix . "expires_in_seconds: " . $this->debugFormatInt32($this->expires_in_seconds) . "\n";
}
return $res;
}
}
}
namespace google\appengine {
class MemcacheGetResponse extends \google\net\ProtocolMessage {
private $item = array();
public function getItemSize() {
return sizeof($this->item);
}
public function getItemList() {
return $this->item;
}
public function mutableItem($idx) {
if (!isset($this->item[$idx])) {
$val = new \google\appengine\MemcacheGetResponse\Item();
$this->item[$idx] = $val;
return $val;
}
return $this->item[$idx];
}
public function getItem($idx) {
if (isset($this->item[$idx])) {
return $this->item[$idx];
}
if ($idx >= end(array_keys($this->item))) {
throw new \OutOfRangeException('index out of range: ' + $idx);
}
return new \google\appengine\MemcacheGetResponse\Item();
}
public function addItem() {
$val = new \google\appengine\MemcacheGetResponse\Item();
$this->item[] = $val;
return $val;
}
public function clearItem() {
$this->item = array();
}
public function clear() {
$this->clearItem();
}
public function byteSizePartial() {
$res = 0;
$this->checkProtoArray($this->item);
$res += 2 * sizeof($this->item);
foreach ($this->item as $value) {
$res += $value->byteSizePartial();
}
return $res;
}
public function outputPartial($out) {
$this->checkProtoArray($this->item);
foreach ($this->item as $value) {
$out->putVarInt32(11);
$value->outputPartial($out);
$out->putVarInt32(12);
}
}
public function tryMerge($d) {
while($d->avail() > 0) {
$tt = $d->getVarInt32();
switch ($tt) {
case 11:
$this->addItem()->tryMerge($d);
break;
case 0:
throw new \google\net\ProtocolBufferDecodeError();
break;
default:
$d->skipData($tt);
}
};
}
public function checkInitialized() {
foreach ($this->item as $value) {
if (!$value->isInitialized()) return 'item';
}
return null;
}
public function mergeFrom($x) {
if ($x === $this) { throw new \IllegalArgumentException('Cannot copy message to itself'); }
foreach ($x->getItemList() as $v) {
$this->addItem()->copyFrom($v);
}
}
public function equals($x) {
if ($x === $this) { return true; }
if (sizeof($this->item) !== sizeof($x->item)) return false;
foreach (array_map(null, $this->item, $x->item) as $v) {
if (!$v[0]->equals($v[1])) return false;
}
return true;
}
public function shortDebugString($prefix = "") {
$res = '';
foreach ($this->item as $value) {
$res .= $prefix . "Item {\n" . $value->shortDebugString($prefix . " ") . $prefix . "}\n";
}
return $res;
}
}
}
namespace google\appengine\MemcacheSetRequest {
class SetPolicy {
const SET = 1;
const ADD = 2;
const REPLACE = 3;
const CAS = 4;
}
}
namespace google\appengine\MemcacheSetRequest {
class Item extends \google\net\ProtocolMessage {
public function getKey() {
if (!isset($this->key)) {
return '';
}
return $this->key;
}
public function setKey($val) {
$this->key = $val;
return $this;
}
public function clearKey() {
unset($this->key);
return $this;
}
public function hasKey() {
return isset($this->key);
}
public function getValue() {
if (!isset($this->value)) {
return '';
}
return $this->value;
}
public function setValue($val) {
$this->value = $val;
return $this;
}
public function clearValue() {
unset($this->value);
return $this;
}
public function hasValue() {
return isset($this->value);
}
public function getFlags() {
if (!isset($this->flags)) {
return "0";
}
return $this->flags;
}
public function setFlags($val) {
$this->flags = $val;
return $this;
}
public function clearFlags() {
unset($this->flags);
return $this;
}
public function hasFlags() {
return isset($this->flags);
}
public function getSetPolicy() {
if (!isset($this->set_policy)) {
return 1;
}
return $this->set_policy;
}
public function setSetPolicy($val) {
$this->set_policy = $val;
return $this;
}
public function clearSetPolicy() {
unset($this->set_policy);
return $this;
}
public function hasSetPolicy() {
return isset($this->set_policy);
}
public function getExpirationTime() {
if (!isset($this->expiration_time)) {
return '0';
}
return $this->expiration_time;
}
public function setExpirationTime($val) {
$this->expiration_time = $val;
return $this;
}
public function clearExpirationTime() {
unset($this->expiration_time);
return $this;
}
public function hasExpirationTime() {
return isset($this->expiration_time);
}
public function getCasId() {
if (!isset($this->cas_id)) {
return "0";
}
return $this->cas_id;
}
public function setCasId($val) {
if (is_double($val)) {
$this->cas_id = sprintf('%0.0F', $val);
} else {
$this->cas_id = $val;
}
return $this;
}
public function clearCasId() {
unset($this->cas_id);
return $this;
}
public function hasCasId() {
return isset($this->cas_id);
}
public function getForCas() {
if (!isset($this->for_cas)) {
return false;
}
return $this->for_cas;
}
public function setForCas($val) {
$this->for_cas = $val;
return $this;
}
public function clearForCas() {
unset($this->for_cas);
return $this;
}
public function hasForCas() {
return isset($this->for_cas);
}
public function clear() {
$this->clearKey();
$this->clearValue();
$this->clearFlags();
$this->clearSetPolicy();
$this->clearExpirationTime();
$this->clearCasId();
$this->clearForCas();
}
public function byteSizePartial() {
$res = 0;
if (isset($this->key)) {
$res += 1;
$res += $this->lengthString(strlen($this->key));
}
if (isset($this->value)) {
$res += 1;
$res += $this->lengthString(strlen($this->value));
}
if (isset($this->flags)) {
$res += 5;
}
if (isset($this->set_policy)) {
$res += 1;
$res += $this->lengthVarInt64($this->set_policy);
}
if (isset($this->expiration_time)) {
$res += 5;
}
if (isset($this->cas_id)) {
$res += 9;
}
if (isset($this->for_cas)) {
$res += 2;
}
return $res;
}
public function outputPartial($out) {
if (isset($this->key)) {
$out->putVarInt32(18);
$out->putPrefixedString($this->key);
}
if (isset($this->value)) {
$out->putVarInt32(26);
$out->putPrefixedString($this->value);
}
if (isset($this->flags)) {
$out->putVarInt32(37);
$out->put32($this->flags);
}
if (isset($this->set_policy)) {
$out->putVarInt32(40);
$out->putVarInt32($this->set_policy);
}
if (isset($this->expiration_time)) {
$out->putVarInt32(53);
$out->put32($this->expiration_time);
}
if (isset($this->cas_id)) {
$out->putVarInt32(65);
$out->put64($this->cas_id);
}
if (isset($this->for_cas)) {
$out->putVarInt32(72);
$out->putBoolean($this->for_cas);
}
}
public function tryMerge($d) {
while($d->avail() > 0) {
$tt = $d->getVarInt32();
switch ($tt) {
case 12: return;
case 18:
$length = $d->getVarInt32();
$this->setKey(substr($d->buffer(), $d->pos(), $length));
$d->skip($length);
break;
case 26:
$length = $d->getVarInt32();
$this->setValue(substr($d->buffer(), $d->pos(), $length));
$d->skip($length);
break;
case 37:
$this->setFlags($d->getFixed32());
break;
case 40:
$this->setSetPolicy($d->getVarInt32());
break;
case 53:
$this->setExpirationTime($d->getFixed32());
break;
case 65:
$this->setCasId($d->getFixed64());
break;
case 72:
$this->setForCas($d->getBoolean());
break;
case 0:
throw new \google\net\ProtocolBufferDecodeError();
break;
default:
$d->skipData($tt);
}
};
}
public function checkInitialized() {
if (!isset($this->key)) return 'key';
if (!isset($this->value)) return 'value';
return null;
}
public function mergeFrom($x) {
if ($x === $this) { throw new \IllegalArgumentException('Cannot copy message to itself'); }
if ($x->hasKey()) {
$this->setKey($x->getKey());
}
if ($x->hasValue()) {
$this->setValue($x->getValue());
}
if ($x->hasFlags()) {
$this->setFlags($x->getFlags());
}
if ($x->hasSetPolicy()) {
$this->setSetPolicy($x->getSetPolicy());
}
if ($x->hasExpirationTime()) {
$this->setExpirationTime($x->getExpirationTime());
}
if ($x->hasCasId()) {
$this->setCasId($x->getCasId());
}
if ($x->hasForCas()) {
$this->setForCas($x->getForCas());
}
}
public function equals($x) {
if ($x === $this) { return true; }
if (isset($this->key) !== isset($x->key)) return false;
if (isset($this->key) && $this->key !== $x->key) return false;
if (isset($this->value) !== isset($x->value)) return false;
if (isset($this->value) && $this->value !== $x->value) return false;
if (isset($this->flags) !== isset($x->flags)) return false;
if (isset($this->flags) && !$this->integerEquals($this->flags, $x->flags)) return false;
if (isset($this->set_policy) !== isset($x->set_policy)) return false;
if (isset($this->set_policy) && $this->set_policy !== $x->set_policy) return false;
if (isset($this->expiration_time) !== isset($x->expiration_time)) return false;
if (isset($this->expiration_time) && !$this->integerEquals($this->expiration_time, $x->expiration_time)) return false;
if (isset($this->cas_id) !== isset($x->cas_id)) return false;
if (isset($this->cas_id) && !$this->integerEquals($this->cas_id, $x->cas_id)) return false;
if (isset($this->for_cas) !== isset($x->for_cas)) return false;
if (isset($this->for_cas) && $this->for_cas !== $x->for_cas) return false;
return true;
}
public function shortDebugString($prefix = "") {
$res = '';
if (isset($this->key)) {
$res .= $prefix . "key: " . $this->debugFormatString($this->key) . "\n";
}
if (isset($this->value)) {
$res .= $prefix . "value: " . $this->debugFormatString($this->value) . "\n";
}
if (isset($this->flags)) {
$res .= $prefix . "flags: " . $this->debugFormatFixed32($this->flags) . "\n";
}
if (isset($this->set_policy)) {
$res .= $prefix . "set_policy: " . ($this->set_policy) . "\n";
}
if (isset($this->expiration_time)) {
$res .= $prefix . "expiration_time: " . $this->debugFormatFixed32($this->expiration_time) . "\n";
}
if (isset($this->cas_id)) {
$res .= $prefix . "cas_id: " . $this->debugFormatFixed64($this->cas_id) . "\n";
}
if (isset($this->for_cas)) {
$res .= $prefix . "for_cas: " . $this->debugFormatBool($this->for_cas) . "\n";
}
return $res;
}
}
}
namespace google\appengine {
class MemcacheSetRequest extends \google\net\ProtocolMessage {
private $item = array();
public function getItemSize() {
return sizeof($this->item);
}
public function getItemList() {
return $this->item;
}
public function mutableItem($idx) {
if (!isset($this->item[$idx])) {
$val = new \google\appengine\MemcacheSetRequest\Item();
$this->item[$idx] = $val;
return $val;
}
return $this->item[$idx];
}
public function getItem($idx) {
if (isset($this->item[$idx])) {
return $this->item[$idx];
}
if ($idx >= end(array_keys($this->item))) {
throw new \OutOfRangeException('index out of range: ' + $idx);
}
return new \google\appengine\MemcacheSetRequest\Item();
}
public function addItem() {
$val = new \google\appengine\MemcacheSetRequest\Item();
$this->item[] = $val;
return $val;
}
public function clearItem() {
$this->item = array();
}
public function getNameSpace() {
if (!isset($this->name_space)) {
return '';
}
return $this->name_space;
}
public function setNameSpace($val) {
$this->name_space = $val;
return $this;
}
public function clearNameSpace() {
unset($this->name_space);
return $this;
}
public function hasNameSpace() {
return isset($this->name_space);
}
public function getOverride() {
if (!isset($this->override)) {
return new \google\appengine\AppOverride();
}
return $this->override;
}
public function mutableOverride() {
if (!isset($this->override)) {
$res = new \google\appengine\AppOverride();
$this->override = $res;
return $res;
}
return $this->override;
}
public function clearOverride() {
if (isset($this->override)) {
unset($this->override);
}
}
public function hasOverride() {
return isset($this->override);
}
public function clear() {
$this->clearItem();
$this->clearNameSpace();
$this->clearOverride();
}
public function byteSizePartial() {
$res = 0;
$this->checkProtoArray($this->item);
$res += 2 * sizeof($this->item);
foreach ($this->item as $value) {
$res += $value->byteSizePartial();
}
if (isset($this->name_space)) {
$res += 1;
$res += $this->lengthString(strlen($this->name_space));
}
if (isset($this->override)) {
$res += 1;
$res += $this->lengthString($this->override->byteSizePartial());
}
return $res;
}
public function outputPartial($out) {
$this->checkProtoArray($this->item);
foreach ($this->item as $value) {
$out->putVarInt32(11);
$value->outputPartial($out);
$out->putVarInt32(12);
}
if (isset($this->name_space)) {
$out->putVarInt32(58);
$out->putPrefixedString($this->name_space);
}
if (isset($this->override)) {
$out->putVarInt32(82);
$out->putVarInt32($this->override->byteSizePartial());
$this->override->outputPartial($out);
}
}
public function tryMerge($d) {
while($d->avail() > 0) {
$tt = $d->getVarInt32();
switch ($tt) {
case 11:
$this->addItem()->tryMerge($d);
break;
case 58:
$length = $d->getVarInt32();
$this->setNameSpace(substr($d->buffer(), $d->pos(), $length));
$d->skip($length);
break;
case 82:
$length = $d->getVarInt32();
$tmp = new \google\net\Decoder($d->buffer(), $d->pos(), $d->pos() + $length);
$d->skip($length);
$this->mutableOverride()->tryMerge($tmp);
break;
case 0:
throw new \google\net\ProtocolBufferDecodeError();
break;
default:
$d->skipData($tt);
}
};
}
public function checkInitialized() {
foreach ($this->item as $value) {
if (!$value->isInitialized()) return 'item';
}
if (isset($this->override) && (!$this->override->isInitialized())) return 'override';
return null;
}
public function mergeFrom($x) {
if ($x === $this) { throw new \IllegalArgumentException('Cannot copy message to itself'); }
foreach ($x->getItemList() as $v) {
$this->addItem()->copyFrom($v);
}
if ($x->hasNameSpace()) {
$this->setNameSpace($x->getNameSpace());
}
if ($x->hasOverride()) {
$this->mutableOverride()->mergeFrom($x->getOverride());
}
}
public function equals($x) {
if ($x === $this) { return true; }
if (sizeof($this->item) !== sizeof($x->item)) return false;
foreach (array_map(null, $this->item, $x->item) as $v) {
if (!$v[0]->equals($v[1])) return false;
}
if (isset($this->name_space) !== isset($x->name_space)) return false;
if (isset($this->name_space) && $this->name_space !== $x->name_space) return false;
if (isset($this->override) !== isset($x->override)) return false;
if (isset($this->override) && !$this->override->equals($x->override)) return false;
return true;
}
public function shortDebugString($prefix = "") {
$res = '';
foreach ($this->item as $value) {
$res .= $prefix . "Item {\n" . $value->shortDebugString($prefix . " ") . $prefix . "}\n";
}
if (isset($this->name_space)) {
$res .= $prefix . "name_space: " . $this->debugFormatString($this->name_space) . "\n";
}
if (isset($this->override)) {
$res .= $prefix . "override <\n" . $this->override->shortDebugString($prefix . " ") . $prefix . ">\n";
}
return $res;
}
}
}
namespace google\appengine\MemcacheSetResponse {
class SetStatusCode {
const STORED = 1;
const NOT_STORED = 2;
const ERROR = 3;
const EXISTS = 4;
}
}
namespace google\appengine {
class MemcacheSetResponse extends \google\net\ProtocolMessage {
private $set_status = array();
public function getSetStatusSize() {
return sizeof($this->set_status);
}
public function getSetStatusList() {
return $this->set_status;
}
public function getSetStatus($idx) {
return $this->set_status[$idx];
}
public function setSetStatus($idx, $val) {
$this->set_status[$idx] = $val;
return $this;
}
public function addSetStatus($val) {
$this->set_status[] = $val;
return $this;
}
public function clearSetStatus() {
$this->set_status = array();
}
public function clear() {
$this->clearSetStatus();
}
public function byteSizePartial() {
$res = 0;
$this->checkProtoArray($this->set_status);
$res += 1 * sizeof($this->set_status);
foreach ($this->set_status as $value) {
$res += $this->lengthVarInt64($value);
}
return $res;
}
public function outputPartial($out) {
$this->checkProtoArray($this->set_status);
foreach ($this->set_status as $value) {
$out->putVarInt32(8);
$out->putVarInt32($value);
}
}
public function tryMerge($d) {
while($d->avail() > 0) {
$tt = $d->getVarInt32();
switch ($tt) {
case 8:
$this->addSetStatus($d->getVarInt32());
break;
case 0:
throw new \google\net\ProtocolBufferDecodeError();
break;
default:
$d->skipData($tt);
}
};
}
public function checkInitialized() {
return null;
}
public function mergeFrom($x) {
if ($x === $this) { throw new \IllegalArgumentException('Cannot copy message to itself'); }
foreach ($x->getSetStatusList() as $v) {
$this->addSetStatus($v);
}
}
public function equals($x) {
if ($x === $this) { return true; }
if (sizeof($this->set_status) !== sizeof($x->set_status)) return false;
foreach (array_map(null, $this->set_status, $x->set_status) as $v) {
if ($v[0] !== $v[1]) return false;
}
return true;
}
public function shortDebugString($prefix = "") {
$res = '';
foreach ($this->set_status as $value) {
$res .= $prefix . "set_status: " . ($value) . "\n";
}
return $res;
}
}
}
namespace google\appengine\MemcacheDeleteRequest {
class Item extends \google\net\ProtocolMessage {
public function getKey() {
if (!isset($this->key)) {
return '';
}
return $this->key;
}
public function setKey($val) {
$this->key = $val;
return $this;
}
public function clearKey() {
unset($this->key);
return $this;
}
public function hasKey() {
return isset($this->key);
}
public function getDeleteTime() {
if (!isset($this->delete_time)) {
return '0';
}
return $this->delete_time;
}
public function setDeleteTime($val) {
$this->delete_time = $val;
return $this;
}
public function clearDeleteTime() {
unset($this->delete_time);
return $this;
}
public function hasDeleteTime() {
return isset($this->delete_time);
}
public function clear() {
$this->clearKey();
$this->clearDeleteTime();
}
public function byteSizePartial() {
$res = 0;
if (isset($this->key)) {
$res += 1;
$res += $this->lengthString(strlen($this->key));
}
if (isset($this->delete_time)) {
$res += 5;
}
return $res;
}
public function outputPartial($out) {
if (isset($this->key)) {
$out->putVarInt32(18);
$out->putPrefixedString($this->key);
}
if (isset($this->delete_time)) {
$out->putVarInt32(29);
$out->put32($this->delete_time);
}
}
public function tryMerge($d) {
while($d->avail() > 0) {
$tt = $d->getVarInt32();
switch ($tt) {
case 12: return;
case 18:
$length = $d->getVarInt32();
$this->setKey(substr($d->buffer(), $d->pos(), $length));
$d->skip($length);
break;
case 29:
$this->setDeleteTime($d->getFixed32());
break;
case 0:
throw new \google\net\ProtocolBufferDecodeError();
break;
default:
$d->skipData($tt);
}
};
}
public function checkInitialized() {
if (!isset($this->key)) return 'key';
return null;
}
public function mergeFrom($x) {
if ($x === $this) { throw new \IllegalArgumentException('Cannot copy message to itself'); }
if ($x->hasKey()) {
$this->setKey($x->getKey());
}
if ($x->hasDeleteTime()) {
$this->setDeleteTime($x->getDeleteTime());
}
}
public function equals($x) {
if ($x === $this) { return true; }
if (isset($this->key) !== isset($x->key)) return false;
if (isset($this->key) && $this->key !== $x->key) return false;
if (isset($this->delete_time) !== isset($x->delete_time)) return false;
if (isset($this->delete_time) && !$this->integerEquals($this->delete_time, $x->delete_time)) return false;
return true;
}
public function shortDebugString($prefix = "") {
$res = '';
if (isset($this->key)) {
$res .= $prefix . "key: " . $this->debugFormatString($this->key) . "\n";
}
if (isset($this->delete_time)) {
$res .= $prefix . "delete_time: " . $this->debugFormatFixed32($this->delete_time) . "\n";
}
return $res;
}
}
}
namespace google\appengine {
class MemcacheDeleteRequest extends \google\net\ProtocolMessage {
private $item = array();
public function getItemSize() {
return sizeof($this->item);
}
public function getItemList() {
return $this->item;
}
public function mutableItem($idx) {
if (!isset($this->item[$idx])) {
$val = new \google\appengine\MemcacheDeleteRequest\Item();
$this->item[$idx] = $val;
return $val;
}
return $this->item[$idx];
}
public function getItem($idx) {
if (isset($this->item[$idx])) {
return $this->item[$idx];
}
if ($idx >= end(array_keys($this->item))) {
throw new \OutOfRangeException('index out of range: ' + $idx);
}
return new \google\appengine\MemcacheDeleteRequest\Item();
}
public function addItem() {
$val = new \google\appengine\MemcacheDeleteRequest\Item();
$this->item[] = $val;
return $val;
}
public function clearItem() {
$this->item = array();
}
public function getNameSpace() {
if (!isset($this->name_space)) {
return '';
}
return $this->name_space;
}
public function setNameSpace($val) {
$this->name_space = $val;
return $this;
}
public function clearNameSpace() {
unset($this->name_space);
return $this;
}
public function hasNameSpace() {
return isset($this->name_space);
}
public function getOverride() {
if (!isset($this->override)) {
return new \google\appengine\AppOverride();
}
return $this->override;
}
public function mutableOverride() {
if (!isset($this->override)) {
$res = new \google\appengine\AppOverride();
$this->override = $res;
return $res;
}
return $this->override;
}
public function clearOverride() {
if (isset($this->override)) {
unset($this->override);
}
}
public function hasOverride() {
return isset($this->override);
}
public function clear() {
$this->clearItem();
$this->clearNameSpace();
$this->clearOverride();
}
public function byteSizePartial() {
$res = 0;
$this->checkProtoArray($this->item);
$res += 2 * sizeof($this->item);
foreach ($this->item as $value) {
$res += $value->byteSizePartial();
}
if (isset($this->name_space)) {
$res += 1;
$res += $this->lengthString(strlen($this->name_space));
}
if (isset($this->override)) {
$res += 1;
$res += $this->lengthString($this->override->byteSizePartial());
}
return $res;
}
public function outputPartial($out) {
$this->checkProtoArray($this->item);
foreach ($this->item as $value) {
$out->putVarInt32(11);
$value->outputPartial($out);
$out->putVarInt32(12);
}
if (isset($this->name_space)) {
$out->putVarInt32(34);
$out->putPrefixedString($this->name_space);
}
if (isset($this->override)) {
$out->putVarInt32(42);
$out->putVarInt32($this->override->byteSizePartial());
$this->override->outputPartial($out);
}
}
public function tryMerge($d) {
while($d->avail() > 0) {
$tt = $d->getVarInt32();
switch ($tt) {
case 11:
$this->addItem()->tryMerge($d);
break;
case 34:
$length = $d->getVarInt32();
$this->setNameSpace(substr($d->buffer(), $d->pos(), $length));
$d->skip($length);
break;
case 42:
$length = $d->getVarInt32();
$tmp = new \google\net\Decoder($d->buffer(), $d->pos(), $d->pos() + $length);
$d->skip($length);
$this->mutableOverride()->tryMerge($tmp);
break;
case 0:
throw new \google\net\ProtocolBufferDecodeError();
break;
default:
$d->skipData($tt);
}
};
}
public function checkInitialized() {
foreach ($this->item as $value) {
if (!$value->isInitialized()) return 'item';
}
if (isset($this->override) && (!$this->override->isInitialized())) return 'override';
return null;
}
public function mergeFrom($x) {
if ($x === $this) { throw new \IllegalArgumentException('Cannot copy message to itself'); }
foreach ($x->getItemList() as $v) {
$this->addItem()->copyFrom($v);
}
if ($x->hasNameSpace()) {
$this->setNameSpace($x->getNameSpace());
}
if ($x->hasOverride()) {
$this->mutableOverride()->mergeFrom($x->getOverride());
}
}
public function equals($x) {
if ($x === $this) { return true; }
if (sizeof($this->item) !== sizeof($x->item)) return false;
foreach (array_map(null, $this->item, $x->item) as $v) {
if (!$v[0]->equals($v[1])) return false;
}
if (isset($this->name_space) !== isset($x->name_space)) return false;
if (isset($this->name_space) && $this->name_space !== $x->name_space) return false;
if (isset($this->override) !== isset($x->override)) return false;
if (isset($this->override) && !$this->override->equals($x->override)) return false;
return true;
}
public function shortDebugString($prefix = "") {
$res = '';
foreach ($this->item as $value) {
$res .= $prefix . "Item {\n" . $value->shortDebugString($prefix . " ") . $prefix . "}\n";
}
if (isset($this->name_space)) {
$res .= $prefix . "name_space: " . $this->debugFormatString($this->name_space) . "\n";
}
if (isset($this->override)) {
$res .= $prefix . "override <\n" . $this->override->shortDebugString($prefix . " ") . $prefix . ">\n";
}
return $res;
}
}
}
namespace google\appengine\MemcacheDeleteResponse {
class DeleteStatusCode {
const DELETED = 1;
const NOT_FOUND = 2;
}
}
namespace google\appengine {
class MemcacheDeleteResponse extends \google\net\ProtocolMessage {
private $delete_status = array();
public function getDeleteStatusSize() {
return sizeof($this->delete_status);
}
public function getDeleteStatusList() {
return $this->delete_status;
}
public function getDeleteStatus($idx) {
return $this->delete_status[$idx];
}
public function setDeleteStatus($idx, $val) {
$this->delete_status[$idx] = $val;
return $this;
}
public function addDeleteStatus($val) {
$this->delete_status[] = $val;
return $this;
}
public function clearDeleteStatus() {
$this->delete_status = array();
}
public function clear() {
$this->clearDeleteStatus();
}
public function byteSizePartial() {
$res = 0;
$this->checkProtoArray($this->delete_status);
$res += 1 * sizeof($this->delete_status);
foreach ($this->delete_status as $value) {
$res += $this->lengthVarInt64($value);
}
return $res;
}
public function outputPartial($out) {
$this->checkProtoArray($this->delete_status);
foreach ($this->delete_status as $value) {
$out->putVarInt32(8);
$out->putVarInt32($value);
}
}
public function tryMerge($d) {
while($d->avail() > 0) {
$tt = $d->getVarInt32();
switch ($tt) {
case 8:
$this->addDeleteStatus($d->getVarInt32());
break;
case 0:
throw new \google\net\ProtocolBufferDecodeError();
break;
default:
$d->skipData($tt);
}
};
}
public function checkInitialized() {
return null;
}
public function mergeFrom($x) {
if ($x === $this) { throw new \IllegalArgumentException('Cannot copy message to itself'); }
foreach ($x->getDeleteStatusList() as $v) {
$this->addDeleteStatus($v);
}
}
public function equals($x) {
if ($x === $this) { return true; }
if (sizeof($this->delete_status) !== sizeof($x->delete_status)) return false;
foreach (array_map(null, $this->delete_status, $x->delete_status) as $v) {
if ($v[0] !== $v[1]) return false;
}
return true;
}
public function shortDebugString($prefix = "") {
$res = '';
foreach ($this->delete_status as $value) {
$res .= $prefix . "delete_status: " . ($value) . "\n";
}
return $res;
}
}
}
namespace google\appengine\MemcacheIncrementRequest {
class Direction {
const INCREMENT = 1;
const DECREMENT = 2;
}
}
namespace google\appengine {
class MemcacheIncrementRequest extends \google\net\ProtocolMessage {
public function getKey() {
if (!isset($this->key)) {
return '';
}
return $this->key;
}
public function setKey($val) {
$this->key = $val;
return $this;
}
public function clearKey() {
unset($this->key);
return $this;
}
public function hasKey() {
return isset($this->key);
}
public function getDelta() {
if (!isset($this->delta)) {
return '1';
}
return $this->delta;
}
public function setDelta($val) {
if (is_double($val)) {
$this->delta = sprintf('%0.0F', $val);
} else {
$this->delta = $val;
}
return $this;
}
public function clearDelta() {
unset($this->delta);
return $this;
}
public function hasDelta() {
return isset($this->delta);
}
public function getDirection() {
if (!isset($this->direction)) {
return 1;
}
return $this->direction;
}
public function setDirection($val) {
$this->direction = $val;
return $this;
}
public function clearDirection() {
unset($this->direction);
return $this;
}
public function hasDirection() {
return isset($this->direction);
}
public function getNameSpace() {
if (!isset($this->name_space)) {
return '';
}
return $this->name_space;
}
public function setNameSpace($val) {
$this->name_space = $val;
return $this;
}
public function clearNameSpace() {
unset($this->name_space);
return $this;
}
public function hasNameSpace() {
return isset($this->name_space);
}
public function getInitialValue() {
if (!isset($this->initial_value)) {
return "0";
}
return $this->initial_value;
}
public function setInitialValue($val) {
if (is_double($val)) {
$this->initial_value = sprintf('%0.0F', $val);
} else {
$this->initial_value = $val;
}
return $this;
}
public function clearInitialValue() {
unset($this->initial_value);
return $this;
}
public function hasInitialValue() {
return isset($this->initial_value);
}
public function getInitialFlags() {
if (!isset($this->initial_flags)) {
return "0";
}
return $this->initial_flags;
}
public function setInitialFlags($val) {
$this->initial_flags = $val;
return $this;
}
public function clearInitialFlags() {
unset($this->initial_flags);
return $this;
}
public function hasInitialFlags() {
return isset($this->initial_flags);
}
public function getOverride() {
if (!isset($this->override)) {
return new \google\appengine\AppOverride();
}
return $this->override;
}
public function mutableOverride() {
if (!isset($this->override)) {
$res = new \google\appengine\AppOverride();
$this->override = $res;
return $res;
}
return $this->override;
}
public function clearOverride() {
if (isset($this->override)) {
unset($this->override);
}
}
public function hasOverride() {
return isset($this->override);
}
public function clear() {
$this->clearKey();
$this->clearDelta();
$this->clearDirection();
$this->clearNameSpace();
$this->clearInitialValue();
$this->clearInitialFlags();
$this->clearOverride();
}
public function byteSizePartial() {
$res = 0;
if (isset($this->key)) {
$res += 1;
$res += $this->lengthString(strlen($this->key));
}
if (isset($this->delta)) {
$res += 1;
$res += $this->lengthVarInt64($this->delta);
}
if (isset($this->direction)) {
$res += 1;
$res += $this->lengthVarInt64($this->direction);
}
if (isset($this->name_space)) {
$res += 1;
$res += $this->lengthString(strlen($this->name_space));
}
if (isset($this->initial_value)) {
$res += 1;
$res += $this->lengthVarInt64($this->initial_value);
}
if (isset($this->initial_flags)) {
$res += 5;
}
if (isset($this->override)) {
$res += 1;
$res += $this->lengthString($this->override->byteSizePartial());
}
return $res;
}
public function outputPartial($out) {
if (isset($this->key)) {
$out->putVarInt32(10);
$out->putPrefixedString($this->key);
}
if (isset($this->delta)) {
$out->putVarInt32(16);
$out->putVarUint64($this->delta);
}
if (isset($this->direction)) {
$out->putVarInt32(24);
$out->putVarInt32($this->direction);
}
if (isset($this->name_space)) {
$out->putVarInt32(34);
$out->putPrefixedString($this->name_space);
}
if (isset($this->initial_value)) {
$out->putVarInt32(40);
$out->putVarUint64($this->initial_value);
}
if (isset($this->initial_flags)) {
$out->putVarInt32(53);
$out->put32($this->initial_flags);
}
if (isset($this->override)) {
$out->putVarInt32(58);
$out->putVarInt32($this->override->byteSizePartial());
$this->override->outputPartial($out);
}
}
public function tryMerge($d) {
while($d->avail() > 0) {
$tt = $d->getVarInt32();
switch ($tt) {
case 10:
$length = $d->getVarInt32();
$this->setKey(substr($d->buffer(), $d->pos(), $length));
$d->skip($length);
break;
case 16:
$this->setDelta($d->getVarUint64());
break;
case 24:
$this->setDirection($d->getVarInt32());
break;
case 34:
$length = $d->getVarInt32();
$this->setNameSpace(substr($d->buffer(), $d->pos(), $length));
$d->skip($length);
break;
case 40:
$this->setInitialValue($d->getVarUint64());
break;
case 53:
$this->setInitialFlags($d->getFixed32());
break;
case 58:
$length = $d->getVarInt32();
$tmp = new \google\net\Decoder($d->buffer(), $d->pos(), $d->pos() + $length);
$d->skip($length);
$this->mutableOverride()->tryMerge($tmp);
break;
case 0:
throw new \google\net\ProtocolBufferDecodeError();
break;
default:
$d->skipData($tt);
}
};
}
public function checkInitialized() {
if (!isset($this->key)) return 'key';
if (isset($this->override) && (!$this->override->isInitialized())) return 'override';
return null;
}
public function mergeFrom($x) {
if ($x === $this) { throw new \IllegalArgumentException('Cannot copy message to itself'); }
if ($x->hasKey()) {
$this->setKey($x->getKey());
}
if ($x->hasDelta()) {
$this->setDelta($x->getDelta());
}
if ($x->hasDirection()) {
$this->setDirection($x->getDirection());
}
if ($x->hasNameSpace()) {
$this->setNameSpace($x->getNameSpace());
}
if ($x->hasInitialValue()) {
$this->setInitialValue($x->getInitialValue());
}
if ($x->hasInitialFlags()) {
$this->setInitialFlags($x->getInitialFlags());
}
if ($x->hasOverride()) {
$this->mutableOverride()->mergeFrom($x->getOverride());
}
}
public function equals($x) {
if ($x === $this) { return true; }
if (isset($this->key) !== isset($x->key)) return false;
if (isset($this->key) && $this->key !== $x->key) return false;
if (isset($this->delta) !== isset($x->delta)) return false;
if (isset($this->delta) && !$this->integerEquals($this->delta, $x->delta)) return false;
if (isset($this->direction) !== isset($x->direction)) return false;
if (isset($this->direction) && $this->direction !== $x->direction) return false;
if (isset($this->name_space) !== isset($x->name_space)) return false;
if (isset($this->name_space) && $this->name_space !== $x->name_space) return false;
if (isset($this->initial_value) !== isset($x->initial_value)) return false;
if (isset($this->initial_value) && !$this->integerEquals($this->initial_value, $x->initial_value)) return false;
if (isset($this->initial_flags) !== isset($x->initial_flags)) return false;
if (isset($this->initial_flags) && !$this->integerEquals($this->initial_flags, $x->initial_flags)) return false;
if (isset($this->override) !== isset($x->override)) return false;
if (isset($this->override) && !$this->override->equals($x->override)) return false;
return true;
}
public function shortDebugString($prefix = "") {
$res = '';
if (isset($this->key)) {
$res .= $prefix . "key: " . $this->debugFormatString($this->key) . "\n";
}
if (isset($this->delta)) {
$res .= $prefix . "delta: " . $this->debugFormatInt64($this->delta) . "\n";
}
if (isset($this->direction)) {
$res .= $prefix . "direction: " . ($this->direction) . "\n";
}
if (isset($this->name_space)) {
$res .= $prefix . "name_space: " . $this->debugFormatString($this->name_space) . "\n";
}
if (isset($this->initial_value)) {
$res .= $prefix . "initial_value: " . $this->debugFormatInt64($this->initial_value) . "\n";
}
if (isset($this->initial_flags)) {
$res .= $prefix . "initial_flags: " . $this->debugFormatFixed32($this->initial_flags) . "\n";
}
if (isset($this->override)) {
$res .= $prefix . "override <\n" . $this->override->shortDebugString($prefix . " ") . $prefix . ">\n";
}
return $res;
}
}
}
namespace google\appengine\MemcacheIncrementResponse {
class IncrementStatusCode {
const OK = 1;
const NOT_CHANGED = 2;
const ERROR = 3;
}
}
namespace google\appengine {
class MemcacheIncrementResponse extends \google\net\ProtocolMessage {
public function getNewValue() {
if (!isset($this->new_value)) {
return "0";
}
return $this->new_value;
}
public function setNewValue($val) {
if (is_double($val)) {
$this->new_value = sprintf('%0.0F', $val);
} else {
$this->new_value = $val;
}
return $this;
}
public function clearNewValue() {
unset($this->new_value);
return $this;
}
public function hasNewValue() {
return isset($this->new_value);
}
public function getIncrementStatus() {
if (!isset($this->increment_status)) {
return 1;
}
return $this->increment_status;
}
public function setIncrementStatus($val) {
$this->increment_status = $val;
return $this;
}
public function clearIncrementStatus() {
unset($this->increment_status);
return $this;
}
public function hasIncrementStatus() {
return isset($this->increment_status);
}
public function clear() {
$this->clearNewValue();
$this->clearIncrementStatus();
}
public function byteSizePartial() {
$res = 0;
if (isset($this->new_value)) {
$res += 1;
$res += $this->lengthVarInt64($this->new_value);
}
if (isset($this->increment_status)) {
$res += 1;
$res += $this->lengthVarInt64($this->increment_status);
}
return $res;
}
public function outputPartial($out) {
if (isset($this->new_value)) {
$out->putVarInt32(8);
$out->putVarUint64($this->new_value);
}
if (isset($this->increment_status)) {
$out->putVarInt32(16);
$out->putVarInt32($this->increment_status);
}
}
public function tryMerge($d) {
while($d->avail() > 0) {
$tt = $d->getVarInt32();
switch ($tt) {
case 8:
$this->setNewValue($d->getVarUint64());
break;
case 16:
$this->setIncrementStatus($d->getVarInt32());
break;
case 0:
throw new \google\net\ProtocolBufferDecodeError();
break;
default:
$d->skipData($tt);
}
};
}
public function checkInitialized() {
return null;
}
public function mergeFrom($x) {
if ($x === $this) { throw new \IllegalArgumentException('Cannot copy message to itself'); }
if ($x->hasNewValue()) {
$this->setNewValue($x->getNewValue());
}
if ($x->hasIncrementStatus()) {
$this->setIncrementStatus($x->getIncrementStatus());
}
}
public function equals($x) {
if ($x === $this) { return true; }
if (isset($this->new_value) !== isset($x->new_value)) return false;
if (isset($this->new_value) && !$this->integerEquals($this->new_value, $x->new_value)) return false;
if (isset($this->increment_status) !== isset($x->increment_status)) return false;
if (isset($this->increment_status) && $this->increment_status !== $x->increment_status) return false;
return true;
}
public function shortDebugString($prefix = "") {
$res = '';
if (isset($this->new_value)) {
$res .= $prefix . "new_value: " . $this->debugFormatInt64($this->new_value) . "\n";
}
if (isset($this->increment_status)) {
$res .= $prefix . "increment_status: " . ($this->increment_status) . "\n";
}
return $res;
}
}
}
namespace google\appengine {
class MemcacheBatchIncrementRequest extends \google\net\ProtocolMessage {
private $item = array();
public function getNameSpace() {
if (!isset($this->name_space)) {
return '';
}
return $this->name_space;
}
public function setNameSpace($val) {
$this->name_space = $val;
return $this;
}
public function clearNameSpace() {
unset($this->name_space);
return $this;
}
public function hasNameSpace() {
return isset($this->name_space);
}
public function getItemSize() {
return sizeof($this->item);
}
public function getItemList() {
return $this->item;
}
public function mutableItem($idx) {
if (!isset($this->item[$idx])) {
$val = new \google\appengine\MemcacheIncrementRequest();
$this->item[$idx] = $val;
return $val;
}
return $this->item[$idx];
}
public function getItem($idx) {
if (isset($this->item[$idx])) {
return $this->item[$idx];
}
if ($idx >= end(array_keys($this->item))) {
throw new \OutOfRangeException('index out of range: ' + $idx);
}
return new \google\appengine\MemcacheIncrementRequest();
}
public function addItem() {
$val = new \google\appengine\MemcacheIncrementRequest();
$this->item[] = $val;
return $val;
}
public function clearItem() {
$this->item = array();
}
public function getOverride() {
if (!isset($this->override)) {
return new \google\appengine\AppOverride();
}
return $this->override;
}
public function mutableOverride() {
if (!isset($this->override)) {
$res = new \google\appengine\AppOverride();
$this->override = $res;
return $res;
}
return $this->override;
}
public function clearOverride() {
if (isset($this->override)) {
unset($this->override);
}
}
public function hasOverride() {
return isset($this->override);
}
public function clear() {
$this->clearNameSpace();
$this->clearItem();
$this->clearOverride();
}
public function byteSizePartial() {
$res = 0;
if (isset($this->name_space)) {
$res += 1;
$res += $this->lengthString(strlen($this->name_space));
}
$this->checkProtoArray($this->item);
$res += 1 * sizeof($this->item);
foreach ($this->item as $value) {
$res += $this->lengthString($value->byteSizePartial());
}
if (isset($this->override)) {
$res += 1;
$res += $this->lengthString($this->override->byteSizePartial());
}
return $res;
}
public function outputPartial($out) {
if (isset($this->name_space)) {
$out->putVarInt32(10);
$out->putPrefixedString($this->name_space);
}
$this->checkProtoArray($this->item);
foreach ($this->item as $value) {
$out->putVarInt32(18);
$out->putVarInt32($value->byteSizePartial());
$value->outputPartial($out);
}
if (isset($this->override)) {
$out->putVarInt32(26);
$out->putVarInt32($this->override->byteSizePartial());
$this->override->outputPartial($out);
}
}
public function tryMerge($d) {
while($d->avail() > 0) {
$tt = $d->getVarInt32();
switch ($tt) {
case 10:
$length = $d->getVarInt32();
$this->setNameSpace(substr($d->buffer(), $d->pos(), $length));
$d->skip($length);
break;
case 18:
$length = $d->getVarInt32();
$tmp = new \google\net\Decoder($d->buffer(), $d->pos(), $d->pos() + $length);
$d->skip($length);
$this->addItem()->tryMerge($tmp);
break;
case 26:
$length = $d->getVarInt32();
$tmp = new \google\net\Decoder($d->buffer(), $d->pos(), $d->pos() + $length);
$d->skip($length);
$this->mutableOverride()->tryMerge($tmp);
break;
case 0:
throw new \google\net\ProtocolBufferDecodeError();
break;
default:
$d->skipData($tt);
}
};
}
public function checkInitialized() {
foreach ($this->item as $value) {
if (!$value->isInitialized()) return 'item';
}
if (isset($this->override) && (!$this->override->isInitialized())) return 'override';
return null;
}
public function mergeFrom($x) {
if ($x === $this) { throw new \IllegalArgumentException('Cannot copy message to itself'); }
if ($x->hasNameSpace()) {
$this->setNameSpace($x->getNameSpace());
}
foreach ($x->getItemList() as $v) {
$this->addItem()->copyFrom($v);
}
if ($x->hasOverride()) {
$this->mutableOverride()->mergeFrom($x->getOverride());
}
}
public function equals($x) {
if ($x === $this) { return true; }
if (isset($this->name_space) !== isset($x->name_space)) return false;
if (isset($this->name_space) && $this->name_space !== $x->name_space) return false;
if (sizeof($this->item) !== sizeof($x->item)) return false;
foreach (array_map(null, $this->item, $x->item) as $v) {
if (!$v[0]->equals($v[1])) return false;
}
if (isset($this->override) !== isset($x->override)) return false;
if (isset($this->override) && !$this->override->equals($x->override)) return false;
return true;
}
public function shortDebugString($prefix = "") {
$res = '';
if (isset($this->name_space)) {
$res .= $prefix . "name_space: " . $this->debugFormatString($this->name_space) . "\n";
}
foreach ($this->item as $value) {
$res .= $prefix . "item <\n" . $value->shortDebugString($prefix . " ") . $prefix . ">\n";
}
if (isset($this->override)) {
$res .= $prefix . "override <\n" . $this->override->shortDebugString($prefix . " ") . $prefix . ">\n";
}
return $res;
}
}
}
namespace google\appengine {
class MemcacheBatchIncrementResponse extends \google\net\ProtocolMessage {
private $item = array();
public function getItemSize() {
return sizeof($this->item);
}
public function getItemList() {
return $this->item;
}
public function mutableItem($idx) {
if (!isset($this->item[$idx])) {
$val = new \google\appengine\MemcacheIncrementResponse();
$this->item[$idx] = $val;
return $val;
}
return $this->item[$idx];
}
public function getItem($idx) {
if (isset($this->item[$idx])) {
return $this->item[$idx];
}
if ($idx >= end(array_keys($this->item))) {
throw new \OutOfRangeException('index out of range: ' + $idx);
}
return new \google\appengine\MemcacheIncrementResponse();
}
public function addItem() {
$val = new \google\appengine\MemcacheIncrementResponse();
$this->item[] = $val;
return $val;
}
public function clearItem() {
$this->item = array();
}
public function clear() {
$this->clearItem();
}
public function byteSizePartial() {
$res = 0;
$this->checkProtoArray($this->item);
$res += 1 * sizeof($this->item);
foreach ($this->item as $value) {
$res += $this->lengthString($value->byteSizePartial());
}
return $res;
}
public function outputPartial($out) {
$this->checkProtoArray($this->item);
foreach ($this->item as $value) {
$out->putVarInt32(10);
$out->putVarInt32($value->byteSizePartial());
$value->outputPartial($out);
}
}
public function tryMerge($d) {
while($d->avail() > 0) {
$tt = $d->getVarInt32();
switch ($tt) {
case 10:
$length = $d->getVarInt32();
$tmp = new \google\net\Decoder($d->buffer(), $d->pos(), $d->pos() + $length);
$d->skip($length);
$this->addItem()->tryMerge($tmp);
break;
case 0:
throw new \google\net\ProtocolBufferDecodeError();
break;
default:
$d->skipData($tt);
}
};
}
public function checkInitialized() {
foreach ($this->item as $value) {
if (!$value->isInitialized()) return 'item';
}
return null;
}
public function mergeFrom($x) {
if ($x === $this) { throw new \IllegalArgumentException('Cannot copy message to itself'); }
foreach ($x->getItemList() as $v) {
$this->addItem()->copyFrom($v);
}
}
public function equals($x) {
if ($x === $this) { return true; }
if (sizeof($this->item) !== sizeof($x->item)) return false;
foreach (array_map(null, $this->item, $x->item) as $v) {
if (!$v[0]->equals($v[1])) return false;
}
return true;
}
public function shortDebugString($prefix = "") {
$res = '';
foreach ($this->item as $value) {
$res .= $prefix . "item <\n" . $value->shortDebugString($prefix . " ") . $prefix . ">\n";
}
return $res;
}
}
}
namespace google\appengine {
class MemcacheFlushRequest extends \google\net\ProtocolMessage {
public function getOverride() {
if (!isset($this->override)) {
return new \google\appengine\AppOverride();
}
return $this->override;
}
public function mutableOverride() {
if (!isset($this->override)) {
$res = new \google\appengine\AppOverride();
$this->override = $res;
return $res;
}
return $this->override;
}
public function clearOverride() {
if (isset($this->override)) {
unset($this->override);
}
}
public function hasOverride() {
return isset($this->override);
}
public function clear() {
$this->clearOverride();
}
public function byteSizePartial() {
$res = 0;
if (isset($this->override)) {
$res += 1;
$res += $this->lengthString($this->override->byteSizePartial());
}
return $res;
}
public function outputPartial($out) {
if (isset($this->override)) {
$out->putVarInt32(10);
$out->putVarInt32($this->override->byteSizePartial());
$this->override->outputPartial($out);
}
}
public function tryMerge($d) {
while($d->avail() > 0) {
$tt = $d->getVarInt32();
switch ($tt) {
case 10:
$length = $d->getVarInt32();
$tmp = new \google\net\Decoder($d->buffer(), $d->pos(), $d->pos() + $length);
$d->skip($length);
$this->mutableOverride()->tryMerge($tmp);
break;
case 0:
throw new \google\net\ProtocolBufferDecodeError();
break;
default:
$d->skipData($tt);
}
};
}
public function checkInitialized() {
if (isset($this->override) && (!$this->override->isInitialized())) return 'override';
return null;
}
public function mergeFrom($x) {
if ($x === $this) { throw new \IllegalArgumentException('Cannot copy message to itself'); }
if ($x->hasOverride()) {
$this->mutableOverride()->mergeFrom($x->getOverride());
}
}
public function equals($x) {
if ($x === $this) { return true; }
if (isset($this->override) !== isset($x->override)) return false;
if (isset($this->override) && !$this->override->equals($x->override)) return false;
return true;
}
public function shortDebugString($prefix = "") {
$res = '';
if (isset($this->override)) {
$res .= $prefix . "override <\n" . $this->override->shortDebugString($prefix . " ") . $prefix . ">\n";
}
return $res;
}
}
}
namespace google\appengine {
class MemcacheFlushResponse extends \google\net\ProtocolMessage {
public function clear() {
}
public function byteSizePartial() {
$res = 0;
return $res;
}
public function outputPartial($out) {
}
public function tryMerge($d) {
while($d->avail() > 0) {
$tt = $d->getVarInt32();
switch ($tt) {
case 0:
throw new \google\net\ProtocolBufferDecodeError();
break;
default:
$d->skipData($tt);
}
};
}
public function checkInitialized() {
return null;
}
public function mergeFrom($x) {
if ($x === $this) { throw new \IllegalArgumentException('Cannot copy message to itself'); }
}
public function equals($x) {
if ($x === $this) { return true; }
return true;
}
public function shortDebugString($prefix = "") {
$res = '';
return $res;
}
}
}
namespace google\appengine {
class MemcacheStatsRequest extends \google\net\ProtocolMessage {
public function getOverride() {
if (!isset($this->override)) {
return new \google\appengine\AppOverride();
}
return $this->override;
}
public function mutableOverride() {
if (!isset($this->override)) {
$res = new \google\appengine\AppOverride();
$this->override = $res;
return $res;
}
return $this->override;
}
public function clearOverride() {
if (isset($this->override)) {
unset($this->override);
}
}
public function hasOverride() {
return isset($this->override);
}
public function clear() {
$this->clearOverride();
}
public function byteSizePartial() {
$res = 0;
if (isset($this->override)) {
$res += 1;
$res += $this->lengthString($this->override->byteSizePartial());
}
return $res;
}
public function outputPartial($out) {
if (isset($this->override)) {
$out->putVarInt32(10);
$out->putVarInt32($this->override->byteSizePartial());
$this->override->outputPartial($out);
}
}
public function tryMerge($d) {
while($d->avail() > 0) {
$tt = $d->getVarInt32();
switch ($tt) {
case 10:
$length = $d->getVarInt32();
$tmp = new \google\net\Decoder($d->buffer(), $d->pos(), $d->pos() + $length);
$d->skip($length);
$this->mutableOverride()->tryMerge($tmp);
break;
case 0:
throw new \google\net\ProtocolBufferDecodeError();
break;
default:
$d->skipData($tt);
}
};
}
public function checkInitialized() {
if (isset($this->override) && (!$this->override->isInitialized())) return 'override';
return null;
}
public function mergeFrom($x) {
if ($x === $this) { throw new \IllegalArgumentException('Cannot copy message to itself'); }
if ($x->hasOverride()) {
$this->mutableOverride()->mergeFrom($x->getOverride());
}
}
public function equals($x) {
if ($x === $this) { return true; }
if (isset($this->override) !== isset($x->override)) return false;
if (isset($this->override) && !$this->override->equals($x->override)) return false;
return true;
}
public function shortDebugString($prefix = "") {
$res = '';
if (isset($this->override)) {
$res .= $prefix . "override <\n" . $this->override->shortDebugString($prefix . " ") . $prefix . ">\n";
}
return $res;
}
}
}
namespace google\appengine {
class MergedNamespaceStats extends \google\net\ProtocolMessage {
public function getHits() {
if (!isset($this->hits)) {
return "0";
}
return $this->hits;
}
public function setHits($val) {
if (is_double($val)) {
$this->hits = sprintf('%0.0F', $val);
} else {
$this->hits = $val;
}
return $this;
}
public function clearHits() {
unset($this->hits);
return $this;
}
public function hasHits() {
return isset($this->hits);
}
public function getMisses() {
if (!isset($this->misses)) {
return "0";
}
return $this->misses;
}
public function setMisses($val) {
if (is_double($val)) {
$this->misses = sprintf('%0.0F', $val);
} else {
$this->misses = $val;
}
return $this;
}
public function clearMisses() {
unset($this->misses);
return $this;
}
public function hasMisses() {
return isset($this->misses);
}
public function getByteHits() {
if (!isset($this->byte_hits)) {
return "0";
}
return $this->byte_hits;
}
public function setByteHits($val) {
if (is_double($val)) {
$this->byte_hits = sprintf('%0.0F', $val);
} else {
$this->byte_hits = $val;
}
return $this;
}
public function clearByteHits() {
unset($this->byte_hits);
return $this;
}
public function hasByteHits() {
return isset($this->byte_hits);
}
public function getItems() {
if (!isset($this->items)) {
return "0";
}
return $this->items;
}
public function setItems($val) {
if (is_double($val)) {
$this->items = sprintf('%0.0F', $val);
} else {
$this->items = $val;
}
return $this;
}
public function clearItems() {
unset($this->items);
return $this;
}
public function hasItems() {
return isset($this->items);
}
public function getBytes() {
if (!isset($this->bytes)) {
return "0";
}
return $this->bytes;
}
public function setBytes($val) {
if (is_double($val)) {
$this->bytes = sprintf('%0.0F', $val);
} else {
$this->bytes = $val;
}
return $this;
}
public function clearBytes() {
unset($this->bytes);
return $this;
}
public function hasBytes() {
return isset($this->bytes);
}
public function getOldestItemAge() {
if (!isset($this->oldest_item_age)) {
return "0";
}
return $this->oldest_item_age;
}
public function setOldestItemAge($val) {
$this->oldest_item_age = $val;
return $this;
}
public function clearOldestItemAge() {
unset($this->oldest_item_age);
return $this;
}
public function hasOldestItemAge() {
return isset($this->oldest_item_age);
}
public function clear() {
$this->clearHits();
$this->clearMisses();
$this->clearByteHits();
$this->clearItems();
$this->clearBytes();
$this->clearOldestItemAge();
}
public function byteSizePartial() {
$res = 0;
if (isset($this->hits)) {
$res += 1;
$res += $this->lengthVarInt64($this->hits);
}
if (isset($this->misses)) {
$res += 1;
$res += $this->lengthVarInt64($this->misses);
}
if (isset($this->byte_hits)) {
$res += 1;
$res += $this->lengthVarInt64($this->byte_hits);
}
if (isset($this->items)) {
$res += 1;
$res += $this->lengthVarInt64($this->items);
}
if (isset($this->bytes)) {
$res += 1;
$res += $this->lengthVarInt64($this->bytes);
}
if (isset($this->oldest_item_age)) {
$res += 5;
}
return $res;
}
public function outputPartial($out) {
if (isset($this->hits)) {
$out->putVarInt32(8);
$out->putVarUint64($this->hits);
}
if (isset($this->misses)) {
$out->putVarInt32(16);
$out->putVarUint64($this->misses);
}
if (isset($this->byte_hits)) {
$out->putVarInt32(24);
$out->putVarUint64($this->byte_hits);
}
if (isset($this->items)) {
$out->putVarInt32(32);
$out->putVarUint64($this->items);
}
if (isset($this->bytes)) {
$out->putVarInt32(40);
$out->putVarUint64($this->bytes);
}
if (isset($this->oldest_item_age)) {
$out->putVarInt32(53);
$out->put32($this->oldest_item_age);
}
}
public function tryMerge($d) {
while($d->avail() > 0) {
$tt = $d->getVarInt32();
switch ($tt) {
case 8:
$this->setHits($d->getVarUint64());
break;
case 16:
$this->setMisses($d->getVarUint64());
break;
case 24:
$this->setByteHits($d->getVarUint64());
break;
case 32:
$this->setItems($d->getVarUint64());
break;
case 40:
$this->setBytes($d->getVarUint64());
break;
case 53:
$this->setOldestItemAge($d->getFixed32());
break;
case 0:
throw new \google\net\ProtocolBufferDecodeError();
break;
default:
$d->skipData($tt);
}
};
}
public function checkInitialized() {
if (!isset($this->hits)) return 'hits';
if (!isset($this->misses)) return 'misses';
if (!isset($this->byte_hits)) return 'byte_hits';
if (!isset($this->items)) return 'items';
if (!isset($this->bytes)) return 'bytes';
if (!isset($this->oldest_item_age)) return 'oldest_item_age';
return null;
}
public function mergeFrom($x) {
if ($x === $this) { throw new \IllegalArgumentException('Cannot copy message to itself'); }
if ($x->hasHits()) {
$this->setHits($x->getHits());
}
if ($x->hasMisses()) {
$this->setMisses($x->getMisses());
}
if ($x->hasByteHits()) {
$this->setByteHits($x->getByteHits());
}
if ($x->hasItems()) {
$this->setItems($x->getItems());
}
if ($x->hasBytes()) {
$this->setBytes($x->getBytes());
}
if ($x->hasOldestItemAge()) {
$this->setOldestItemAge($x->getOldestItemAge());
}
}
public function equals($x) {
if ($x === $this) { return true; }
if (isset($this->hits) !== isset($x->hits)) return false;
if (isset($this->hits) && !$this->integerEquals($this->hits, $x->hits)) return false;
if (isset($this->misses) !== isset($x->misses)) return false;
if (isset($this->misses) && !$this->integerEquals($this->misses, $x->misses)) return false;
if (isset($this->byte_hits) !== isset($x->byte_hits)) return false;
if (isset($this->byte_hits) && !$this->integerEquals($this->byte_hits, $x->byte_hits)) return false;
if (isset($this->items) !== isset($x->items)) return false;
if (isset($this->items) && !$this->integerEquals($this->items, $x->items)) return false;
if (isset($this->bytes) !== isset($x->bytes)) return false;
if (isset($this->bytes) && !$this->integerEquals($this->bytes, $x->bytes)) return false;
if (isset($this->oldest_item_age) !== isset($x->oldest_item_age)) return false;
if (isset($this->oldest_item_age) && !$this->integerEquals($this->oldest_item_age, $x->oldest_item_age)) return false;
return true;
}
public function shortDebugString($prefix = "") {
$res = '';
if (isset($this->hits)) {
$res .= $prefix . "hits: " . $this->debugFormatInt64($this->hits) . "\n";
}
if (isset($this->misses)) {
$res .= $prefix . "misses: " . $this->debugFormatInt64($this->misses) . "\n";
}
if (isset($this->byte_hits)) {
$res .= $prefix . "byte_hits: " . $this->debugFormatInt64($this->byte_hits) . "\n";
}
if (isset($this->items)) {
$res .= $prefix . "items: " . $this->debugFormatInt64($this->items) . "\n";
}
if (isset($this->bytes)) {
$res .= $prefix . "bytes: " . $this->debugFormatInt64($this->bytes) . "\n";
}
if (isset($this->oldest_item_age)) {
$res .= $prefix . "oldest_item_age: " . $this->debugFormatFixed32($this->oldest_item_age) . "\n";
}
return $res;
}
}
}
namespace google\appengine {
class MemcacheStatsResponse extends \google\net\ProtocolMessage {
public function getStats() {
if (!isset($this->stats)) {
return new \google\appengine\MergedNamespaceStats();
}
return $this->stats;
}
public function mutableStats() {
if (!isset($this->stats)) {
$res = new \google\appengine\MergedNamespaceStats();
$this->stats = $res;
return $res;
}
return $this->stats;
}
public function clearStats() {
if (isset($this->stats)) {
unset($this->stats);
}
}
public function hasStats() {
return isset($this->stats);
}
public function clear() {
$this->clearStats();
}
public function byteSizePartial() {
$res = 0;
if (isset($this->stats)) {
$res += 1;
$res += $this->lengthString($this->stats->byteSizePartial());
}
return $res;
}
public function outputPartial($out) {
if (isset($this->stats)) {
$out->putVarInt32(10);
$out->putVarInt32($this->stats->byteSizePartial());
$this->stats->outputPartial($out);
}
}
public function tryMerge($d) {
while($d->avail() > 0) {
$tt = $d->getVarInt32();
switch ($tt) {
case 10:
$length = $d->getVarInt32();
$tmp = new \google\net\Decoder($d->buffer(), $d->pos(), $d->pos() + $length);
$d->skip($length);
$this->mutableStats()->tryMerge($tmp);
break;
case 0:
throw new \google\net\ProtocolBufferDecodeError();
break;
default:
$d->skipData($tt);
}
};
}
public function checkInitialized() {
if (isset($this->stats) && (!$this->stats->isInitialized())) return 'stats';
return null;
}
public function mergeFrom($x) {
if ($x === $this) { throw new \IllegalArgumentException('Cannot copy message to itself'); }
if ($x->hasStats()) {
$this->mutableStats()->mergeFrom($x->getStats());
}
}
public function equals($x) {
if ($x === $this) { return true; }
if (isset($this->stats) !== isset($x->stats)) return false;
if (isset($this->stats) && !$this->stats->equals($x->stats)) return false;
return true;
}
public function shortDebugString($prefix = "") {
$res = '';
if (isset($this->stats)) {
$res .= $prefix . "stats <\n" . $this->stats->shortDebugString($prefix . " ") . $prefix . ">\n";
}
return $res;
}
}
}
namespace google\appengine {
class MemcacheGrabTailRequest extends \google\net\ProtocolMessage {
public function getItemCount() {
if (!isset($this->item_count)) {
return 0;
}
return $this->item_count;
}
public function setItemCount($val) {
$this->item_count = $val;
return $this;
}
public function clearItemCount() {
unset($this->item_count);
return $this;
}
public function hasItemCount() {
return isset($this->item_count);
}
public function getNameSpace() {
if (!isset($this->name_space)) {
return '';
}
return $this->name_space;
}
public function setNameSpace($val) {
$this->name_space = $val;
return $this;
}
public function clearNameSpace() {
unset($this->name_space);
return $this;
}
public function hasNameSpace() {
return isset($this->name_space);
}
public function getOverride() {
if (!isset($this->override)) {
return new \google\appengine\AppOverride();
}
return $this->override;
}
public function mutableOverride() {
if (!isset($this->override)) {
$res = new \google\appengine\AppOverride();
$this->override = $res;
return $res;
}
return $this->override;
}
public function clearOverride() {
if (isset($this->override)) {
unset($this->override);
}
}
public function hasOverride() {
return isset($this->override);
}
public function clear() {
$this->clearItemCount();
$this->clearNameSpace();
$this->clearOverride();
}
public function byteSizePartial() {
$res = 0;
if (isset($this->item_count)) {
$res += 1;
$res += $this->lengthVarInt64($this->item_count);
}
if (isset($this->name_space)) {
$res += 1;
$res += $this->lengthString(strlen($this->name_space));
}
if (isset($this->override)) {
$res += 1;
$res += $this->lengthString($this->override->byteSizePartial());
}
return $res;
}
public function outputPartial($out) {
if (isset($this->item_count)) {
$out->putVarInt32(8);
$out->putVarInt32($this->item_count);
}
if (isset($this->name_space)) {
$out->putVarInt32(18);
$out->putPrefixedString($this->name_space);
}
if (isset($this->override)) {
$out->putVarInt32(26);
$out->putVarInt32($this->override->byteSizePartial());
$this->override->outputPartial($out);
}
}
public function tryMerge($d) {
while($d->avail() > 0) {
$tt = $d->getVarInt32();
switch ($tt) {
case 8:
$this->setItemCount($d->getVarInt32());
break;
case 18:
$length = $d->getVarInt32();
$this->setNameSpace(substr($d->buffer(), $d->pos(), $length));
$d->skip($length);
break;
case 26:
$length = $d->getVarInt32();
$tmp = new \google\net\Decoder($d->buffer(), $d->pos(), $d->pos() + $length);
$d->skip($length);
$this->mutableOverride()->tryMerge($tmp);
break;
case 0:
throw new \google\net\ProtocolBufferDecodeError();
break;
default:
$d->skipData($tt);
}
};
}
public function checkInitialized() {
if (!isset($this->item_count)) return 'item_count';
if (isset($this->override) && (!$this->override->isInitialized())) return 'override';
return null;
}
public function mergeFrom($x) {
if ($x === $this) { throw new \IllegalArgumentException('Cannot copy message to itself'); }
if ($x->hasItemCount()) {
$this->setItemCount($x->getItemCount());
}
if ($x->hasNameSpace()) {
$this->setNameSpace($x->getNameSpace());
}
if ($x->hasOverride()) {
$this->mutableOverride()->mergeFrom($x->getOverride());
}
}
public function equals($x) {
if ($x === $this) { return true; }
if (isset($this->item_count) !== isset($x->item_count)) return false;
if (isset($this->item_count) && !$this->integerEquals($this->item_count, $x->item_count)) return false;
if (isset($this->name_space) !== isset($x->name_space)) return false;
if (isset($this->name_space) && $this->name_space !== $x->name_space) return false;
if (isset($this->override) !== isset($x->override)) return false;
if (isset($this->override) && !$this->override->equals($x->override)) return false;
return true;
}
public function shortDebugString($prefix = "") {
$res = '';
if (isset($this->item_count)) {
$res .= $prefix . "item_count: " . $this->debugFormatInt32($this->item_count) . "\n";
}
if (isset($this->name_space)) {
$res .= $prefix . "name_space: " . $this->debugFormatString($this->name_space) . "\n";
}
if (isset($this->override)) {
$res .= $prefix . "override <\n" . $this->override->shortDebugString($prefix . " ") . $prefix . ">\n";
}
return $res;
}
}
}
namespace google\appengine\MemcacheGrabTailResponse {
class Item extends \google\net\ProtocolMessage {
public function getValue() {
if (!isset($this->value)) {
return '';
}
return $this->value;
}
public function setValue($val) {
$this->value = $val;
return $this;
}
public function clearValue() {
unset($this->value);
return $this;
}
public function hasValue() {
return isset($this->value);
}
public function getFlags() {
if (!isset($this->flags)) {
return "0";
}
return $this->flags;
}
public function setFlags($val) {
$this->flags = $val;
return $this;
}
public function clearFlags() {
unset($this->flags);
return $this;
}
public function hasFlags() {
return isset($this->flags);
}
public function clear() {
$this->clearValue();
$this->clearFlags();
}
public function byteSizePartial() {
$res = 0;
if (isset($this->value)) {
$res += 1;
$res += $this->lengthString(strlen($this->value));
}
if (isset($this->flags)) {
$res += 5;
}
return $res;
}
public function outputPartial($out) {
if (isset($this->value)) {
$out->putVarInt32(18);
$out->putPrefixedString($this->value);
}
if (isset($this->flags)) {
$out->putVarInt32(29);
$out->put32($this->flags);
}
}
public function tryMerge($d) {
while($d->avail() > 0) {
$tt = $d->getVarInt32();
switch ($tt) {
case 12: return;
case 18:
$length = $d->getVarInt32();
$this->setValue(substr($d->buffer(), $d->pos(), $length));
$d->skip($length);
break;
case 29:
$this->setFlags($d->getFixed32());
break;
case 0:
throw new \google\net\ProtocolBufferDecodeError();
break;
default:
$d->skipData($tt);
}
};
}
public function checkInitialized() {
if (!isset($this->value)) return 'value';
return null;
}
public function mergeFrom($x) {
if ($x === $this) { throw new \IllegalArgumentException('Cannot copy message to itself'); }
if ($x->hasValue()) {
$this->setValue($x->getValue());
}
if ($x->hasFlags()) {
$this->setFlags($x->getFlags());
}
}
public function equals($x) {
if ($x === $this) { return true; }
if (isset($this->value) !== isset($x->value)) return false;
if (isset($this->value) && $this->value !== $x->value) return false;
if (isset($this->flags) !== isset($x->flags)) return false;
if (isset($this->flags) && !$this->integerEquals($this->flags, $x->flags)) return false;
return true;
}
public function shortDebugString($prefix = "") {
$res = '';
if (isset($this->value)) {
$res .= $prefix . "value: " . $this->debugFormatString($this->value) . "\n";
}
if (isset($this->flags)) {
$res .= $prefix . "flags: " . $this->debugFormatFixed32($this->flags) . "\n";
}
return $res;
}
}
}
namespace google\appengine {
class MemcacheGrabTailResponse extends \google\net\ProtocolMessage {
private $item = array();
public function getItemSize() {
return sizeof($this->item);
}
public function getItemList() {
return $this->item;
}
public function mutableItem($idx) {
if (!isset($this->item[$idx])) {
$val = new \google\appengine\MemcacheGrabTailResponse\Item();
$this->item[$idx] = $val;
return $val;
}
return $this->item[$idx];
}
public function getItem($idx) {
if (isset($this->item[$idx])) {
return $this->item[$idx];
}
if ($idx >= end(array_keys($this->item))) {
throw new \OutOfRangeException('index out of range: ' + $idx);
}
return new \google\appengine\MemcacheGrabTailResponse\Item();
}
public function addItem() {
$val = new \google\appengine\MemcacheGrabTailResponse\Item();
$this->item[] = $val;
return $val;
}
public function clearItem() {
$this->item = array();
}
public function clear() {
$this->clearItem();
}
public function byteSizePartial() {
$res = 0;
$this->checkProtoArray($this->item);
$res += 2 * sizeof($this->item);
foreach ($this->item as $value) {
$res += $value->byteSizePartial();
}
return $res;
}
public function outputPartial($out) {
$this->checkProtoArray($this->item);
foreach ($this->item as $value) {
$out->putVarInt32(11);
$value->outputPartial($out);
$out->putVarInt32(12);
}
}
public function tryMerge($d) {
while($d->avail() > 0) {
$tt = $d->getVarInt32();
switch ($tt) {
case 11:
$this->addItem()->tryMerge($d);
break;
case 0:
throw new \google\net\ProtocolBufferDecodeError();
break;
default:
$d->skipData($tt);
}
};
}
public function checkInitialized() {
foreach ($this->item as $value) {
if (!$value->isInitialized()) return 'item';
}
return null;
}
public function mergeFrom($x) {
if ($x === $this) { throw new \IllegalArgumentException('Cannot copy message to itself'); }
foreach ($x->getItemList() as $v) {
$this->addItem()->copyFrom($v);
}
}
public function equals($x) {
if ($x === $this) { return true; }
if (sizeof($this->item) !== sizeof($x->item)) return false;
foreach (array_map(null, $this->item, $x->item) as $v) {
if (!$v[0]->equals($v[1])) return false;
}
return true;
}
public function shortDebugString($prefix = "") {
$res = '';
foreach ($this->item as $value) {
$res .= $prefix . "Item {\n" . $value->shortDebugString($prefix . " ") . $prefix . "}\n";
}
return $res;
}
}
}
| ychen820/microblog | y/google-cloud-sdk/platform/google_appengine/php/sdk/google/appengine/api/memcache/memcache_service_pb.php | PHP | bsd-3-clause | 107,999 |
/* claqr0.f -- translated by f2c (version 20061008).
You must link the resulting object file with libf2c:
on Microsoft Windows system, link with libf2c.lib;
on Linux or Unix systems, link with .../path/to/libf2c.a -lm
or, if you install libf2c.a in a standard place, with -lf2c -lm
-- in that order, at the end of the command line, as in
cc *.o -lf2c -lm
Source for libf2c is in /netlib/f2c/libf2c.zip, e.g.,
http://www.netlib.org/f2c/libf2c.zip
*/
#include "f2c.h"
#include "blaswrap.h"
/* Table of constant values */
static integer c__13 = 13;
static integer c__15 = 15;
static integer c_n1 = -1;
static integer c__12 = 12;
static integer c__14 = 14;
static integer c__16 = 16;
static logical c_false = FALSE_;
static integer c__1 = 1;
static integer c__3 = 3;
/* Subroutine */ int claqr0_(logical *wantt, logical *wantz, integer *n,
integer *ilo, integer *ihi, complex *h__, integer *ldh, complex *w,
integer *iloz, integer *ihiz, complex *z__, integer *ldz, complex *
work, integer *lwork, integer *info)
{
/* System generated locals */
integer h_dim1, h_offset, z_dim1, z_offset, i__1, i__2, i__3, i__4, i__5;
real r__1, r__2, r__3, r__4, r__5, r__6, r__7, r__8;
complex q__1, q__2, q__3, q__4, q__5;
/* Builtin functions */
double r_imag(complex *);
void c_sqrt(complex *, complex *);
/* Local variables */
integer i__, k;
real s;
complex aa, bb, cc, dd;
integer ld, nh, it, ks, kt, ku, kv, ls, ns, nw;
complex tr2, det;
integer inf, kdu, nho, nve, kwh, nsr, nwr, kwv, ndec, ndfl, kbot, nmin;
complex swap;
integer ktop;
complex zdum[1] /* was [1][1] */;
integer kacc22, itmax, nsmax, nwmax, kwtop;
extern /* Subroutine */ int claqr3_(logical *, logical *, integer *,
integer *, integer *, integer *, complex *, integer *, integer *,
integer *, complex *, integer *, integer *, integer *, complex *,
complex *, integer *, integer *, complex *, integer *, integer *,
complex *, integer *, complex *, integer *), claqr4_(logical *,
logical *, integer *, integer *, integer *, complex *, integer *,
complex *, integer *, integer *, complex *, integer *, complex *,
integer *, integer *), claqr5_(logical *, logical *, integer *,
integer *, integer *, integer *, integer *, complex *, complex *,
integer *, integer *, integer *, complex *, integer *, complex *,
integer *, complex *, integer *, integer *, complex *, integer *,
integer *, complex *, integer *);
integer nibble;
extern /* Subroutine */ int clahqr_(logical *, logical *, integer *,
integer *, integer *, complex *, integer *, complex *, integer *,
integer *, complex *, integer *, integer *), clacpy_(char *,
integer *, integer *, complex *, integer *, complex *, integer *);
extern integer ilaenv_(integer *, char *, char *, integer *, integer *,
integer *, integer *);
char jbcmpz[1];
complex rtdisc;
integer nwupbd;
logical sorted;
integer lwkopt;
/* -- LAPACK auxiliary routine (version 3.2) -- */
/* Univ. of Tennessee, Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd.. */
/* November 2006 */
/* .. Scalar Arguments .. */
/* .. */
/* .. Array Arguments .. */
/* .. */
/* Purpose */
/* ======= */
/* CLAQR0 computes the eigenvalues of a Hessenberg matrix H */
/* and, optionally, the matrices T and Z from the Schur decomposition */
/* H = Z T Z**H, where T is an upper triangular matrix (the */
/* Schur form), and Z is the unitary matrix of Schur vectors. */
/* Optionally Z may be postmultiplied into an input unitary */
/* matrix Q so that this routine can give the Schur factorization */
/* of a matrix A which has been reduced to the Hessenberg form H */
/* by the unitary matrix Q: A = Q*H*Q**H = (QZ)*H*(QZ)**H. */
/* Arguments */
/* ========= */
/* WANTT (input) LOGICAL */
/* = .TRUE. : the full Schur form T is required; */
/* = .FALSE.: only eigenvalues are required. */
/* WANTZ (input) LOGICAL */
/* = .TRUE. : the matrix of Schur vectors Z is required; */
/* = .FALSE.: Schur vectors are not required. */
/* N (input) INTEGER */
/* The order of the matrix H. N .GE. 0. */
/* ILO (input) INTEGER */
/* IHI (input) INTEGER */
/* It is assumed that H is already upper triangular in rows */
/* and columns 1:ILO-1 and IHI+1:N and, if ILO.GT.1, */
/* H(ILO,ILO-1) is zero. ILO and IHI are normally set by a */
/* previous call to CGEBAL, and then passed to CGEHRD when the */
/* matrix output by CGEBAL is reduced to Hessenberg form. */
/* Otherwise, ILO and IHI should be set to 1 and N, */
/* respectively. If N.GT.0, then 1.LE.ILO.LE.IHI.LE.N. */
/* If N = 0, then ILO = 1 and IHI = 0. */
/* H (input/output) COMPLEX array, dimension (LDH,N) */
/* On entry, the upper Hessenberg matrix H. */
/* On exit, if INFO = 0 and WANTT is .TRUE., then H */
/* contains the upper triangular matrix T from the Schur */
/* decomposition (the Schur form). If INFO = 0 and WANT is */
/* .FALSE., then the contents of H are unspecified on exit. */
/* (The output value of H when INFO.GT.0 is given under the */
/* description of INFO below.) */
/* This subroutine may explicitly set H(i,j) = 0 for i.GT.j and */
/* j = 1, 2, ... ILO-1 or j = IHI+1, IHI+2, ... N. */
/* LDH (input) INTEGER */
/* The leading dimension of the array H. LDH .GE. max(1,N). */
/* W (output) COMPLEX array, dimension (N) */
/* The computed eigenvalues of H(ILO:IHI,ILO:IHI) are stored */
/* in W(ILO:IHI). If WANTT is .TRUE., then the eigenvalues are */
/* stored in the same order as on the diagonal of the Schur */
/* form returned in H, with W(i) = H(i,i). */
/* Z (input/output) COMPLEX array, dimension (LDZ,IHI) */
/* If WANTZ is .FALSE., then Z is not referenced. */
/* If WANTZ is .TRUE., then Z(ILO:IHI,ILOZ:IHIZ) is */
/* replaced by Z(ILO:IHI,ILOZ:IHIZ)*U where U is the */
/* orthogonal Schur factor of H(ILO:IHI,ILO:IHI). */
/* (The output value of Z when INFO.GT.0 is given under */
/* the description of INFO below.) */
/* LDZ (input) INTEGER */
/* The leading dimension of the array Z. if WANTZ is .TRUE. */
/* then LDZ.GE.MAX(1,IHIZ). Otherwize, LDZ.GE.1. */
/* WORK (workspace/output) COMPLEX array, dimension LWORK */
/* On exit, if LWORK = -1, WORK(1) returns an estimate of */
/* the optimal value for LWORK. */
/* LWORK (input) INTEGER */
/* The dimension of the array WORK. LWORK .GE. max(1,N) */
/* is sufficient, but LWORK typically as large as 6*N may */
/* be required for optimal performance. A workspace query */
/* to determine the optimal workspace size is recommended. */
/* If LWORK = -1, then CLAQR0 does a workspace query. */
/* In this case, CLAQR0 checks the input parameters and */
/* estimates the optimal workspace size for the given */
/* values of N, ILO and IHI. The estimate is returned */
/* in WORK(1). No error message related to LWORK is */
/* issued by XERBLA. Neither H nor Z are accessed. */
/* INFO (output) INTEGER */
/* = 0: successful exit */
/* .GT. 0: if INFO = i, CLAQR0 failed to compute all of */
/* the eigenvalues. Elements 1:ilo-1 and i+1:n of WR */
/* and WI contain those eigenvalues which have been */
/* successfully computed. (Failures are rare.) */
/* If INFO .GT. 0 and WANT is .FALSE., then on exit, */
/* the remaining unconverged eigenvalues are the eigen- */
/* values of the upper Hessenberg matrix rows and */
/* columns ILO through INFO of the final, output */
/* value of H. */
/* If INFO .GT. 0 and WANTT is .TRUE., then on exit */
/* (*) (initial value of H)*U = U*(final value of H) */
/* where U is a unitary matrix. The final */
/* value of H is upper Hessenberg and triangular in */
/* rows and columns INFO+1 through IHI. */
/* If INFO .GT. 0 and WANTZ is .TRUE., then on exit */
/* (final value of Z(ILO:IHI,ILOZ:IHIZ) */
/* = (initial value of Z(ILO:IHI,ILOZ:IHIZ)*U */
/* where U is the unitary matrix in (*) (regard- */
/* less of the value of WANTT.) */
/* If INFO .GT. 0 and WANTZ is .FALSE., then Z is not */
/* accessed. */
/* ================================================================ */
/* Based on contributions by */
/* Karen Braman and Ralph Byers, Department of Mathematics, */
/* University of Kansas, USA */
/* ================================================================ */
/* References: */
/* K. Braman, R. Byers and R. Mathias, The Multi-Shift QR */
/* Algorithm Part I: Maintaining Well Focused Shifts, and Level 3 */
/* Performance, SIAM Journal of Matrix Analysis, volume 23, pages */
/* 929--947, 2002. */
/* K. Braman, R. Byers and R. Mathias, The Multi-Shift QR */
/* Algorithm Part II: Aggressive Early Deflation, SIAM Journal */
/* of Matrix Analysis, volume 23, pages 948--973, 2002. */
/* ================================================================ */
/* .. Parameters .. */
/* ==== Matrices of order NTINY or smaller must be processed by */
/* . CLAHQR because of insufficient subdiagonal scratch space. */
/* . (This is a hard limit.) ==== */
/* ==== Exceptional deflation windows: try to cure rare */
/* . slow convergence by varying the size of the */
/* . deflation window after KEXNW iterations. ==== */
/* ==== Exceptional shifts: try to cure rare slow convergence */
/* . with ad-hoc exceptional shifts every KEXSH iterations. */
/* . ==== */
/* ==== The constant WILK1 is used to form the exceptional */
/* . shifts. ==== */
/* .. */
/* .. Local Scalars .. */
/* .. */
/* .. External Functions .. */
/* .. */
/* .. Local Arrays .. */
/* .. */
/* .. External Subroutines .. */
/* .. */
/* .. Intrinsic Functions .. */
/* .. */
/* .. Statement Functions .. */
/* .. */
/* .. Statement Function definitions .. */
/* .. */
/* .. Executable Statements .. */
/* Parameter adjustments */
h_dim1 = *ldh;
h_offset = 1 + h_dim1;
h__ -= h_offset;
--w;
z_dim1 = *ldz;
z_offset = 1 + z_dim1;
z__ -= z_offset;
--work;
/* Function Body */
*info = 0;
/* ==== Quick return for N = 0: nothing to do. ==== */
if (*n == 0) {
work[1].r = 1.f, work[1].i = 0.f;
return 0;
}
if (*n <= 11) {
/* ==== Tiny matrices must use CLAHQR. ==== */
lwkopt = 1;
if (*lwork != -1) {
clahqr_(wantt, wantz, n, ilo, ihi, &h__[h_offset], ldh, &w[1],
iloz, ihiz, &z__[z_offset], ldz, info);
}
} else {
/* ==== Use small bulge multi-shift QR with aggressive early */
/* . deflation on larger-than-tiny matrices. ==== */
/* ==== Hope for the best. ==== */
*info = 0;
/* ==== Set up job flags for ILAENV. ==== */
if (*wantt) {
*(unsigned char *)jbcmpz = 'S';
} else {
*(unsigned char *)jbcmpz = 'E';
}
if (*wantz) {
*(unsigned char *)&jbcmpz[1] = 'V';
} else {
*(unsigned char *)&jbcmpz[1] = 'N';
}
/* ==== NWR = recommended deflation window size. At this */
/* . point, N .GT. NTINY = 11, so there is enough */
/* . subdiagonal workspace for NWR.GE.2 as required. */
/* . (In fact, there is enough subdiagonal space for */
/* . NWR.GE.3.) ==== */
nwr = ilaenv_(&c__13, "CLAQR0", jbcmpz, n, ilo, ihi, lwork);
nwr = max(2,nwr);
/* Computing MIN */
i__1 = *ihi - *ilo + 1, i__2 = (*n - 1) / 3, i__1 = min(i__1,i__2);
nwr = min(i__1,nwr);
/* ==== NSR = recommended number of simultaneous shifts. */
/* . At this point N .GT. NTINY = 11, so there is at */
/* . enough subdiagonal workspace for NSR to be even */
/* . and greater than or equal to two as required. ==== */
nsr = ilaenv_(&c__15, "CLAQR0", jbcmpz, n, ilo, ihi, lwork);
/* Computing MIN */
i__1 = nsr, i__2 = (*n + 6) / 9, i__1 = min(i__1,i__2), i__2 = *ihi -
*ilo;
nsr = min(i__1,i__2);
/* Computing MAX */
i__1 = 2, i__2 = nsr - nsr % 2;
nsr = max(i__1,i__2);
/* ==== Estimate optimal workspace ==== */
/* ==== Workspace query call to CLAQR3 ==== */
i__1 = nwr + 1;
claqr3_(wantt, wantz, n, ilo, ihi, &i__1, &h__[h_offset], ldh, iloz,
ihiz, &z__[z_offset], ldz, &ls, &ld, &w[1], &h__[h_offset],
ldh, n, &h__[h_offset], ldh, n, &h__[h_offset], ldh, &work[1],
&c_n1);
/* ==== Optimal workspace = MAX(CLAQR5, CLAQR3) ==== */
/* Computing MAX */
i__1 = nsr * 3 / 2, i__2 = (integer) work[1].r;
lwkopt = max(i__1,i__2);
/* ==== Quick return in case of workspace query. ==== */
if (*lwork == -1) {
r__1 = (real) lwkopt;
q__1.r = r__1, q__1.i = 0.f;
work[1].r = q__1.r, work[1].i = q__1.i;
return 0;
}
/* ==== CLAHQR/CLAQR0 crossover point ==== */
nmin = ilaenv_(&c__12, "CLAQR0", jbcmpz, n, ilo, ihi, lwork);
nmin = max(11,nmin);
/* ==== Nibble crossover point ==== */
nibble = ilaenv_(&c__14, "CLAQR0", jbcmpz, n, ilo, ihi, lwork);
nibble = max(0,nibble);
/* ==== Accumulate reflections during ttswp? Use block */
/* . 2-by-2 structure during matrix-matrix multiply? ==== */
kacc22 = ilaenv_(&c__16, "CLAQR0", jbcmpz, n, ilo, ihi, lwork);
kacc22 = max(0,kacc22);
kacc22 = min(2,kacc22);
/* ==== NWMAX = the largest possible deflation window for */
/* . which there is sufficient workspace. ==== */
/* Computing MIN */
i__1 = (*n - 1) / 3, i__2 = *lwork / 2;
nwmax = min(i__1,i__2);
nw = nwmax;
/* ==== NSMAX = the Largest number of simultaneous shifts */
/* . for which there is sufficient workspace. ==== */
/* Computing MIN */
i__1 = (*n + 6) / 9, i__2 = (*lwork << 1) / 3;
nsmax = min(i__1,i__2);
nsmax -= nsmax % 2;
/* ==== NDFL: an iteration count restarted at deflation. ==== */
ndfl = 1;
/* ==== ITMAX = iteration limit ==== */
/* Computing MAX */
i__1 = 10, i__2 = *ihi - *ilo + 1;
itmax = max(i__1,i__2) * 30;
/* ==== Last row and column in the active block ==== */
kbot = *ihi;
/* ==== Main Loop ==== */
i__1 = itmax;
for (it = 1; it <= i__1; ++it) {
/* ==== Done when KBOT falls below ILO ==== */
if (kbot < *ilo) {
goto L80;
}
/* ==== Locate active block ==== */
i__2 = *ilo + 1;
for (k = kbot; k >= i__2; --k) {
i__3 = k + (k - 1) * h_dim1;
if (h__[i__3].r == 0.f && h__[i__3].i == 0.f) {
goto L20;
}
/* L10: */
}
k = *ilo;
L20:
ktop = k;
/* ==== Select deflation window size: */
/* . Typical Case: */
/* . If possible and advisable, nibble the entire */
/* . active block. If not, use size MIN(NWR,NWMAX) */
/* . or MIN(NWR+1,NWMAX) depending upon which has */
/* . the smaller corresponding subdiagonal entry */
/* . (a heuristic). */
/* . */
/* . Exceptional Case: */
/* . If there have been no deflations in KEXNW or */
/* . more iterations, then vary the deflation window */
/* . size. At first, because, larger windows are, */
/* . in general, more powerful than smaller ones, */
/* . rapidly increase the window to the maximum possible. */
/* . Then, gradually reduce the window size. ==== */
nh = kbot - ktop + 1;
nwupbd = min(nh,nwmax);
if (ndfl < 5) {
nw = min(nwupbd,nwr);
} else {
/* Computing MIN */
i__2 = nwupbd, i__3 = nw << 1;
nw = min(i__2,i__3);
}
if (nw < nwmax) {
if (nw >= nh - 1) {
nw = nh;
} else {
kwtop = kbot - nw + 1;
i__2 = kwtop + (kwtop - 1) * h_dim1;
i__3 = kwtop - 1 + (kwtop - 2) * h_dim1;
if ((r__1 = h__[i__2].r, dabs(r__1)) + (r__2 = r_imag(&
h__[kwtop + (kwtop - 1) * h_dim1]), dabs(r__2)) >
(r__3 = h__[i__3].r, dabs(r__3)) + (r__4 = r_imag(
&h__[kwtop - 1 + (kwtop - 2) * h_dim1]), dabs(
r__4))) {
++nw;
}
}
}
if (ndfl < 5) {
ndec = -1;
} else if (ndec >= 0 || nw >= nwupbd) {
++ndec;
if (nw - ndec < 2) {
ndec = 0;
}
nw -= ndec;
}
/* ==== Aggressive early deflation: */
/* . split workspace under the subdiagonal into */
/* . - an nw-by-nw work array V in the lower */
/* . left-hand-corner, */
/* . - an NW-by-at-least-NW-but-more-is-better */
/* . (NW-by-NHO) horizontal work array along */
/* . the bottom edge, */
/* . - an at-least-NW-but-more-is-better (NHV-by-NW) */
/* . vertical work array along the left-hand-edge. */
/* . ==== */
kv = *n - nw + 1;
kt = nw + 1;
nho = *n - nw - 1 - kt + 1;
kwv = nw + 2;
nve = *n - nw - kwv + 1;
/* ==== Aggressive early deflation ==== */
claqr3_(wantt, wantz, n, &ktop, &kbot, &nw, &h__[h_offset], ldh,
iloz, ihiz, &z__[z_offset], ldz, &ls, &ld, &w[1], &h__[kv
+ h_dim1], ldh, &nho, &h__[kv + kt * h_dim1], ldh, &nve, &
h__[kwv + h_dim1], ldh, &work[1], lwork);
/* ==== Adjust KBOT accounting for new deflations. ==== */
kbot -= ld;
/* ==== KS points to the shifts. ==== */
ks = kbot - ls + 1;
/* ==== Skip an expensive QR sweep if there is a (partly */
/* . heuristic) reason to expect that many eigenvalues */
/* . will deflate without it. Here, the QR sweep is */
/* . skipped if many eigenvalues have just been deflated */
/* . or if the remaining active block is small. */
if (ld == 0 || ld * 100 <= nw * nibble && kbot - ktop + 1 > min(
nmin,nwmax)) {
/* ==== NS = nominal number of simultaneous shifts. */
/* . This may be lowered (slightly) if CLAQR3 */
/* . did not provide that many shifts. ==== */
/* Computing MIN */
/* Computing MAX */
i__4 = 2, i__5 = kbot - ktop;
i__2 = min(nsmax,nsr), i__3 = max(i__4,i__5);
ns = min(i__2,i__3);
ns -= ns % 2;
/* ==== If there have been no deflations */
/* . in a multiple of KEXSH iterations, */
/* . then try exceptional shifts. */
/* . Otherwise use shifts provided by */
/* . CLAQR3 above or from the eigenvalues */
/* . of a trailing principal submatrix. ==== */
if (ndfl % 6 == 0) {
ks = kbot - ns + 1;
i__2 = ks + 1;
for (i__ = kbot; i__ >= i__2; i__ += -2) {
i__3 = i__;
i__4 = i__ + i__ * h_dim1;
i__5 = i__ + (i__ - 1) * h_dim1;
r__3 = ((r__1 = h__[i__5].r, dabs(r__1)) + (r__2 =
r_imag(&h__[i__ + (i__ - 1) * h_dim1]), dabs(
r__2))) * .75f;
q__1.r = h__[i__4].r + r__3, q__1.i = h__[i__4].i;
w[i__3].r = q__1.r, w[i__3].i = q__1.i;
i__3 = i__ - 1;
i__4 = i__;
w[i__3].r = w[i__4].r, w[i__3].i = w[i__4].i;
/* L30: */
}
} else {
/* ==== Got NS/2 or fewer shifts? Use CLAQR4 or */
/* . CLAHQR on a trailing principal submatrix to */
/* . get more. (Since NS.LE.NSMAX.LE.(N+6)/9, */
/* . there is enough space below the subdiagonal */
/* . to fit an NS-by-NS scratch array.) ==== */
if (kbot - ks + 1 <= ns / 2) {
ks = kbot - ns + 1;
kt = *n - ns + 1;
clacpy_("A", &ns, &ns, &h__[ks + ks * h_dim1], ldh, &
h__[kt + h_dim1], ldh);
if (ns > nmin) {
claqr4_(&c_false, &c_false, &ns, &c__1, &ns, &h__[
kt + h_dim1], ldh, &w[ks], &c__1, &c__1,
zdum, &c__1, &work[1], lwork, &inf);
} else {
clahqr_(&c_false, &c_false, &ns, &c__1, &ns, &h__[
kt + h_dim1], ldh, &w[ks], &c__1, &c__1,
zdum, &c__1, &inf);
}
ks += inf;
/* ==== In case of a rare QR failure use */
/* . eigenvalues of the trailing 2-by-2 */
/* . principal submatrix. Scale to avoid */
/* . overflows, underflows and subnormals. */
/* . (The scale factor S can not be zero, */
/* . because H(KBOT,KBOT-1) is nonzero.) ==== */
if (ks >= kbot) {
i__2 = kbot - 1 + (kbot - 1) * h_dim1;
i__3 = kbot + (kbot - 1) * h_dim1;
i__4 = kbot - 1 + kbot * h_dim1;
i__5 = kbot + kbot * h_dim1;
s = (r__1 = h__[i__2].r, dabs(r__1)) + (r__2 =
r_imag(&h__[kbot - 1 + (kbot - 1) *
h_dim1]), dabs(r__2)) + ((r__3 = h__[i__3]
.r, dabs(r__3)) + (r__4 = r_imag(&h__[
kbot + (kbot - 1) * h_dim1]), dabs(r__4)))
+ ((r__5 = h__[i__4].r, dabs(r__5)) + (
r__6 = r_imag(&h__[kbot - 1 + kbot *
h_dim1]), dabs(r__6))) + ((r__7 = h__[
i__5].r, dabs(r__7)) + (r__8 = r_imag(&
h__[kbot + kbot * h_dim1]), dabs(r__8)));
i__2 = kbot - 1 + (kbot - 1) * h_dim1;
q__1.r = h__[i__2].r / s, q__1.i = h__[i__2].i /
s;
aa.r = q__1.r, aa.i = q__1.i;
i__2 = kbot + (kbot - 1) * h_dim1;
q__1.r = h__[i__2].r / s, q__1.i = h__[i__2].i /
s;
cc.r = q__1.r, cc.i = q__1.i;
i__2 = kbot - 1 + kbot * h_dim1;
q__1.r = h__[i__2].r / s, q__1.i = h__[i__2].i /
s;
bb.r = q__1.r, bb.i = q__1.i;
i__2 = kbot + kbot * h_dim1;
q__1.r = h__[i__2].r / s, q__1.i = h__[i__2].i /
s;
dd.r = q__1.r, dd.i = q__1.i;
q__2.r = aa.r + dd.r, q__2.i = aa.i + dd.i;
q__1.r = q__2.r / 2.f, q__1.i = q__2.i / 2.f;
tr2.r = q__1.r, tr2.i = q__1.i;
q__3.r = aa.r - tr2.r, q__3.i = aa.i - tr2.i;
q__4.r = dd.r - tr2.r, q__4.i = dd.i - tr2.i;
q__2.r = q__3.r * q__4.r - q__3.i * q__4.i,
q__2.i = q__3.r * q__4.i + q__3.i *
q__4.r;
q__5.r = bb.r * cc.r - bb.i * cc.i, q__5.i = bb.r
* cc.i + bb.i * cc.r;
q__1.r = q__2.r - q__5.r, q__1.i = q__2.i -
q__5.i;
det.r = q__1.r, det.i = q__1.i;
q__2.r = -det.r, q__2.i = -det.i;
c_sqrt(&q__1, &q__2);
rtdisc.r = q__1.r, rtdisc.i = q__1.i;
i__2 = kbot - 1;
q__2.r = tr2.r + rtdisc.r, q__2.i = tr2.i +
rtdisc.i;
q__1.r = s * q__2.r, q__1.i = s * q__2.i;
w[i__2].r = q__1.r, w[i__2].i = q__1.i;
i__2 = kbot;
q__2.r = tr2.r - rtdisc.r, q__2.i = tr2.i -
rtdisc.i;
q__1.r = s * q__2.r, q__1.i = s * q__2.i;
w[i__2].r = q__1.r, w[i__2].i = q__1.i;
ks = kbot - 1;
}
}
if (kbot - ks + 1 > ns) {
/* ==== Sort the shifts (Helps a little) ==== */
sorted = FALSE_;
i__2 = ks + 1;
for (k = kbot; k >= i__2; --k) {
if (sorted) {
goto L60;
}
sorted = TRUE_;
i__3 = k - 1;
for (i__ = ks; i__ <= i__3; ++i__) {
i__4 = i__;
i__5 = i__ + 1;
if ((r__1 = w[i__4].r, dabs(r__1)) + (r__2 =
r_imag(&w[i__]), dabs(r__2)) < (r__3 =
w[i__5].r, dabs(r__3)) + (r__4 =
r_imag(&w[i__ + 1]), dabs(r__4))) {
sorted = FALSE_;
i__4 = i__;
swap.r = w[i__4].r, swap.i = w[i__4].i;
i__4 = i__;
i__5 = i__ + 1;
w[i__4].r = w[i__5].r, w[i__4].i = w[i__5]
.i;
i__4 = i__ + 1;
w[i__4].r = swap.r, w[i__4].i = swap.i;
}
/* L40: */
}
/* L50: */
}
L60:
;
}
}
/* ==== If there are only two shifts, then use */
/* . only one. ==== */
if (kbot - ks + 1 == 2) {
i__2 = kbot;
i__3 = kbot + kbot * h_dim1;
q__2.r = w[i__2].r - h__[i__3].r, q__2.i = w[i__2].i -
h__[i__3].i;
q__1.r = q__2.r, q__1.i = q__2.i;
i__4 = kbot - 1;
i__5 = kbot + kbot * h_dim1;
q__4.r = w[i__4].r - h__[i__5].r, q__4.i = w[i__4].i -
h__[i__5].i;
q__3.r = q__4.r, q__3.i = q__4.i;
if ((r__1 = q__1.r, dabs(r__1)) + (r__2 = r_imag(&q__1),
dabs(r__2)) < (r__3 = q__3.r, dabs(r__3)) + (r__4
= r_imag(&q__3), dabs(r__4))) {
i__2 = kbot - 1;
i__3 = kbot;
w[i__2].r = w[i__3].r, w[i__2].i = w[i__3].i;
} else {
i__2 = kbot;
i__3 = kbot - 1;
w[i__2].r = w[i__3].r, w[i__2].i = w[i__3].i;
}
}
/* ==== Use up to NS of the the smallest magnatiude */
/* . shifts. If there aren't NS shifts available, */
/* . then use them all, possibly dropping one to */
/* . make the number of shifts even. ==== */
/* Computing MIN */
i__2 = ns, i__3 = kbot - ks + 1;
ns = min(i__2,i__3);
ns -= ns % 2;
ks = kbot - ns + 1;
/* ==== Small-bulge multi-shift QR sweep: */
/* . split workspace under the subdiagonal into */
/* . - a KDU-by-KDU work array U in the lower */
/* . left-hand-corner, */
/* . - a KDU-by-at-least-KDU-but-more-is-better */
/* . (KDU-by-NHo) horizontal work array WH along */
/* . the bottom edge, */
/* . - and an at-least-KDU-but-more-is-better-by-KDU */
/* . (NVE-by-KDU) vertical work WV arrow along */
/* . the left-hand-edge. ==== */
kdu = ns * 3 - 3;
ku = *n - kdu + 1;
kwh = kdu + 1;
nho = *n - kdu - 3 - (kdu + 1) + 1;
kwv = kdu + 4;
nve = *n - kdu - kwv + 1;
/* ==== Small-bulge multi-shift QR sweep ==== */
claqr5_(wantt, wantz, &kacc22, n, &ktop, &kbot, &ns, &w[ks], &
h__[h_offset], ldh, iloz, ihiz, &z__[z_offset], ldz, &
work[1], &c__3, &h__[ku + h_dim1], ldh, &nve, &h__[
kwv + h_dim1], ldh, &nho, &h__[ku + kwh * h_dim1],
ldh);
}
/* ==== Note progress (or the lack of it). ==== */
if (ld > 0) {
ndfl = 1;
} else {
++ndfl;
}
/* ==== End of main loop ==== */
/* L70: */
}
/* ==== Iteration limit exceeded. Set INFO to show where */
/* . the problem occurred and exit. ==== */
*info = kbot;
L80:
;
}
/* ==== Return the optimal value of LWORK. ==== */
r__1 = (real) lwkopt;
q__1.r = r__1, q__1.i = 0.f;
work[1].r = q__1.r, work[1].i = q__1.i;
/* ==== End of CLAQR0 ==== */
return 0;
} /* claqr0_ */
| UCSantaCruzComputationalGenomicsLab/clapack | SRC/claqr0.c | C | bsd-3-clause | 27,282 |
<!--
INSTEAD OF EDITING THIS HTML FILE, USE OUR CONTROLLER GENERATOR:
http://developers.airconsole.com/tools/airconsole-controls/ctrl-generator/controller.html
!-->
<html>
<head>
<script type="text/javascript" src="../button/button.js"></script>
<script type="text/javascript" src="fake-airconsole.js"></script>
<link rel="stylesheet" href="../button/button.css">
<style type="text/css">
body {
-ms-user-select: none;
-moz-user-select: none;
-webkit-user-select: none;
user-select: none;
}
.example-container {
background-color: #3b3b3b;
text-align: center;
font-family: sans-serif;
display: inline-block;
width: 100%;
height: 100%;
max-width: 720px;
max-height: 360px;
position: relative;
}
/* You need to explicitly position your buttons */
#button-round {
position: absolute;
width: 10%;
height: 100%;
left: 10%;
top: 0px;
}
/* You need to explicitly position your buttons */
#button-rectangular {
position: absolute;
width: 40%;
height: 100%;
right: 10%;
top: 0px;
}
</style>
</head>
<body>
<div class="example-container">
<br/>
<div id=button-round class="button-80">
<div class="button-text">X</div>
</div>
<br/><br/><br/>
<div id=button-rectangular class=button-300-150>
<div class="button-text">FIRE</div>
</div>
</div>
<script type="text/javascript">
var airconsole = new AirConsole();
var round = new Button("button-round", {
"down": function() {
airconsole.message(AirConsole.SCREEN, {"round" : "down"});
},
"up": function() {
airconsole.message(AirConsole.SCREEN, {"round" : "up"});
}
});
var rectangular = new Button("button-rectangular", {
"down": function() {
airconsole.message(AirConsole.SCREEN, {"rectangular" : "down"});
},
"up": function() {
airconsole.message(AirConsole.SCREEN, {"rectangular" : "up"});
}
});
</script>
</body>
</html> | PeteE/roro | python/robot_server/airconsole-controls/examples/button.html | HTML | bsd-3-clause | 2,251 |
/**
* PANDA 3D SOFTWARE
* Copyright (c) Carnegie Mellon University. All rights reserved.
*
* All use of this software is subject to the terms of the revised BSD
* license. You should have received a copy of this license along
* with this source code in a file named "LICENSE."
*
* @file cullableObject.h
* @author drose
* @date 2002-03-04
*/
#ifndef CULLABLEOBJECT_H
#define CULLABLEOBJECT_H
#include "pandabase.h"
#include "geom.h"
#include "geomVertexData.h"
#include "renderState.h"
#include "transformState.h"
#include "pointerTo.h"
#include "geomNode.h"
#include "cullTraverserData.h"
#include "pStatCollector.h"
#include "deletedChain.h"
#include "graphicsStateGuardianBase.h"
#include "sceneSetup.h"
#include "lightMutex.h"
#include "callbackObject.h"
#include "geomDrawCallbackData.h"
class CullTraverser;
class GeomMunger;
/**
* The smallest atom of cull. This is normally just a Geom and its associated
* state, but it also contain a draw callback.
*/
class EXPCL_PANDA_PGRAPH CullableObject {
public:
INLINE CullableObject();
INLINE CullableObject(CPT(Geom) geom, CPT(RenderState) state,
CPT(TransformState) internal_transform);
INLINE CullableObject(const CullableObject ©);
INLINE void operator = (const CullableObject ©);
bool munge_geom(GraphicsStateGuardianBase *gsg, GeomMunger *munger,
const CullTraverser *traverser, bool force);
INLINE void draw(GraphicsStateGuardianBase *gsg,
bool force, Thread *current_thread);
INLINE bool request_resident() const;
INLINE static void flush_level();
INLINE void set_draw_callback(CallbackObject *draw_callback);
INLINE void draw_inline(GraphicsStateGuardianBase *gsg,
bool force, Thread *current_thread);
INLINE void draw_callback(GraphicsStateGuardianBase *gsg,
bool force, Thread *current_thread);
public:
ALLOC_DELETED_CHAIN(CullableObject);
void output(std::ostream &out) const;
public:
CPT(Geom) _geom;
CPT(GeomVertexData) _munged_data;
CPT(RenderState) _state;
CPT(TransformState) _internal_transform;
PT(CallbackObject) _draw_callback;
private:
bool munge_points_to_quads(const CullTraverser *traverser, bool force);
static CPT(RenderState) get_flash_cpu_state();
static CPT(RenderState) get_flash_hardware_state();
private:
// This class is used internally by munge_points_to_quads().
class PointData {
public:
PN_stdfloat _dist;
};
class SortPoints {
public:
INLINE SortPoints(const PointData *array);
INLINE bool operator ()(unsigned short a, unsigned short b) const;
const PointData *_array;
};
// This is a cache of converted vertex formats.
class SourceFormat {
public:
SourceFormat(const GeomVertexFormat *format, bool sprite_texcoord);
INLINE bool operator < (const SourceFormat &other) const;
CPT(GeomVertexFormat) _format;
bool _sprite_texcoord;
bool _retransform_sprites;
};
typedef pmap<SourceFormat, CPT(GeomVertexFormat) > FormatMap;
static FormatMap _format_map;
static LightMutex _format_lock;
static PStatCollector _munge_pcollector;
static PStatCollector _munge_geom_pcollector;
static PStatCollector _munge_sprites_pcollector;
static PStatCollector _munge_sprites_verts_pcollector;
static PStatCollector _munge_sprites_prims_pcollector;
static PStatCollector _sw_sprites_pcollector;
public:
static TypeHandle get_class_type() {
return _type_handle;
}
static void init_type() {
register_type(_type_handle, "CullableObject");
}
private:
static TypeHandle _type_handle;
};
INLINE std::ostream &operator << (std::ostream &out, const CullableObject &object) {
object.output(out);
return out;
}
#include "cullableObject.I"
#endif
| chandler14362/panda3d | panda/src/pgraph/cullableObject.h | C | bsd-3-clause | 3,812 |
# $Id$
from module_base import ModuleBase
from module_mixins import FilenameViewModuleMixin
import module_utils
import vtk
class stlWRT(FilenameViewModuleMixin, ModuleBase):
def __init__(self, module_manager):
# call parent constructor
ModuleBase.__init__(self, module_manager)
# need to make sure that we're all happy triangles and stuff
self._cleaner = vtk.vtkCleanPolyData()
self._tf = vtk.vtkTriangleFilter()
self._tf.SetInput(self._cleaner.GetOutput())
self._writer = vtk.vtkSTLWriter()
self._writer.SetInput(self._tf.GetOutput())
# sorry about this, but the files get REALLY big if we write them
# in ASCII - I'll make this a gui option later.
#self._writer.SetFileTypeToBinary()
# following is the standard way of connecting up the devide progress
# callback to a VTK object; you should do this for all objects in
mm = self._module_manager
for textobj in (('Cleaning data', self._cleaner),
('Converting to triangles', self._tf),
('Writing STL data', self._writer)):
module_utils.setup_vtk_object_progress(self, textobj[1],
textobj[0])
# ctor for this specific mixin
FilenameViewModuleMixin.__init__(
self,
'Select a filename',
'STL data (*.stl)|*.stl|All files (*)|*',
{'vtkSTLWriter': self._writer},
fileOpen=False)
# set up some defaults
self._config.filename = ''
self.sync_module_logic_with_config()
def close(self):
# we should disconnect all inputs
self.set_input(0, None)
del self._writer
FilenameViewModuleMixin.close(self)
def get_input_descriptions(self):
return ('vtkPolyData',)
def set_input(self, idx, input_stream):
self._cleaner.SetInput(input_stream)
def get_output_descriptions(self):
return ()
def get_output(self, idx):
raise Exception
def logic_to_config(self):
filename = self._writer.GetFileName()
if filename == None:
filename = ''
self._config.filename = filename
def config_to_logic(self):
self._writer.SetFileName(self._config.filename)
def view_to_config(self):
self._config.filename = self._getViewFrameFilename()
def config_to_view(self):
self._setViewFrameFilename(self._config.filename)
def execute_module(self):
if len(self._writer.GetFileName()):
self._writer.Write()
| nagyistoce/devide | modules/writers/stlWRT.py | Python | bsd-3-clause | 2,674 |
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: c++98, c++03, c++11
// <functional>
// boyer_moore_horspool searcher
// template<class RandomAccessIterator1,
// class Hash = hash<typename iterator_traits<RandomAccessIterator1>::value_type>,
// class BinaryPredicate = equal_to<>>
// class boyer_moore_horspool_searcher {
// public:
// boyer_moore_horspool_searcher(RandomAccessIterator1 pat_first, RandomAccessIterator1 pat_last,
// Hash hf = Hash(), BinaryPredicate pred = BinaryPredicate());
//
// template<class RandomAccessIterator2>
// pair<RandomAccessIterator2, RandomAccessIterator2>
// operator()(RandomAccessIterator2 first, RandomAccessIterator2 last) const;
//
// private:
// RandomAccessIterator1 pat_first_; // exposition only
// RandomAccessIterator1 pat_last_; // exposition only
// Hash hash_; // exposition only
// BinaryPredicate pred_; // exposition only
// };
#include <experimental/algorithm>
#include <experimental/functional>
#include <cassert>
#include "test_macros.h"
#include "test_iterators.h"
template <typename T> struct MyHash {
size_t operator () (T t) const { return static_cast<size_t>(t); }
};
struct count_equal
{
static unsigned count;
template <class T>
bool operator()(const T& x, const T& y) const
{++count; return x == y;}
};
unsigned count_equal::count = 0;
template <typename Iter1, typename Iter2>
void do_search(Iter1 b1, Iter1 e1, Iter2 b2, Iter2 e2, Iter1 result, unsigned max_count) {
std::experimental::boyer_moore_horspool_searcher<Iter2,
MyHash<typename std::remove_cv<typename std::iterator_traits<Iter2>::value_type>::type>,
count_equal>
s{b2, e2};
count_equal::count = 0;
assert(result == std::experimental::search(b1, e1, s));
assert(count_equal::count <= max_count);
}
template <class Iter1, class Iter2>
void
test()
{
int ia[] = {0, 1, 2, 3, 4, 5};
const unsigned sa = sizeof(ia)/sizeof(ia[0]);
do_search(Iter1(ia), Iter1(ia+sa), Iter2(ia), Iter2(ia), Iter1(ia), 0);
do_search(Iter1(ia), Iter1(ia+sa), Iter2(ia), Iter2(ia+1), Iter1(ia), sa);
do_search(Iter1(ia), Iter1(ia+sa), Iter2(ia+1), Iter2(ia+2), Iter1(ia+1), sa);
do_search(Iter1(ia), Iter1(ia+sa), Iter2(ia+2), Iter2(ia+2), Iter1(ia), 0);
do_search(Iter1(ia), Iter1(ia+sa), Iter2(ia+2), Iter2(ia+3), Iter1(ia+2), sa);
do_search(Iter1(ia), Iter1(ia+sa), Iter2(ia+2), Iter2(ia+3), Iter1(ia+2), sa);
do_search(Iter1(ia), Iter1(ia), Iter2(ia+2), Iter2(ia+3), Iter1(ia), 0);
do_search(Iter1(ia), Iter1(ia+sa), Iter2(ia+sa-1), Iter2(ia+sa), Iter1(ia+sa-1), sa);
do_search(Iter1(ia), Iter1(ia+sa), Iter2(ia+sa-3), Iter2(ia+sa), Iter1(ia+sa-3), 3*sa);
do_search(Iter1(ia), Iter1(ia+sa), Iter2(ia), Iter2(ia+sa), Iter1(ia), sa*sa);
do_search(Iter1(ia), Iter1(ia+sa-1), Iter2(ia), Iter2(ia+sa), Iter1(ia+sa-1), (sa-1)*sa);
do_search(Iter1(ia), Iter1(ia+1), Iter2(ia), Iter2(ia+sa), Iter1(ia+1), sa);
int ib[] = {0, 1, 2, 0, 1, 2, 3, 0, 1, 2, 3, 4};
const unsigned sb = sizeof(ib)/sizeof(ib[0]);
int ic[] = {1};
do_search(Iter1(ib), Iter1(ib+sb), Iter2(ic), Iter2(ic+1), Iter1(ib+1), sb);
int id[] = {1, 2};
do_search(Iter1(ib), Iter1(ib+sb), Iter2(id), Iter2(id+2), Iter1(ib+1), sb*2);
int ie[] = {1, 2, 3};
do_search(Iter1(ib), Iter1(ib+sb), Iter2(ie), Iter2(ie+3), Iter1(ib+4), sb*3);
int ig[] = {1, 2, 3, 4};
do_search(Iter1(ib), Iter1(ib+sb), Iter2(ig), Iter2(ig+4), Iter1(ib+8), sb*4);
int ih[] = {0, 1, 1, 1, 1, 2, 3, 0, 1, 2, 3, 4};
const unsigned sh = sizeof(ih)/sizeof(ih[0]);
int ii[] = {1, 1, 2};
do_search(Iter1(ih), Iter1(ih+sh), Iter2(ii), Iter2(ii+3), Iter1(ih+3), sh*3);
}
template <class Iter1, class Iter2>
void
test2()
{
char ia[] = {0, 1, 2, 3, 4, 5};
const unsigned sa = sizeof(ia)/sizeof(ia[0]);
do_search(Iter1(ia), Iter1(ia+sa), Iter2(ia), Iter2(ia), Iter1(ia), 0);
do_search(Iter1(ia), Iter1(ia+sa), Iter2(ia), Iter2(ia+1), Iter1(ia), sa);
do_search(Iter1(ia), Iter1(ia+sa), Iter2(ia+1), Iter2(ia+2), Iter1(ia+1), sa);
do_search(Iter1(ia), Iter1(ia+sa), Iter2(ia+2), Iter2(ia+2), Iter1(ia), 0);
do_search(Iter1(ia), Iter1(ia+sa), Iter2(ia+2), Iter2(ia+3), Iter1(ia+2), sa);
do_search(Iter1(ia), Iter1(ia+sa), Iter2(ia+2), Iter2(ia+3), Iter1(ia+2), sa);
do_search(Iter1(ia), Iter1(ia), Iter2(ia+2), Iter2(ia+3), Iter1(ia), 0);
do_search(Iter1(ia), Iter1(ia+sa), Iter2(ia+sa-1), Iter2(ia+sa), Iter1(ia+sa-1), sa);
do_search(Iter1(ia), Iter1(ia+sa), Iter2(ia+sa-3), Iter2(ia+sa), Iter1(ia+sa-3), 3*sa);
do_search(Iter1(ia), Iter1(ia+sa), Iter2(ia), Iter2(ia+sa), Iter1(ia), sa*sa);
do_search(Iter1(ia), Iter1(ia+sa-1), Iter2(ia), Iter2(ia+sa), Iter1(ia+sa-1), (sa-1)*sa);
do_search(Iter1(ia), Iter1(ia+1), Iter2(ia), Iter2(ia+sa), Iter1(ia+1), sa);
char ib[] = {0, 1, 2, 0, 1, 2, 3, 0, 1, 2, 3, 4};
const unsigned sb = sizeof(ib)/sizeof(ib[0]);
char ic[] = {1};
do_search(Iter1(ib), Iter1(ib+sb), Iter2(ic), Iter2(ic+1), Iter1(ib+1), sb);
char id[] = {1, 2};
do_search(Iter1(ib), Iter1(ib+sb), Iter2(id), Iter2(id+2), Iter1(ib+1), sb*2);
char ie[] = {1, 2, 3};
do_search(Iter1(ib), Iter1(ib+sb), Iter2(ie), Iter2(ie+3), Iter1(ib+4), sb*3);
char ig[] = {1, 2, 3, 4};
do_search(Iter1(ib), Iter1(ib+sb), Iter2(ig), Iter2(ig+4), Iter1(ib+8), sb*4);
char ih[] = {0, 1, 1, 1, 1, 2, 3, 0, 1, 2, 3, 4};
const unsigned sh = sizeof(ih)/sizeof(ih[0]);
char ii[] = {1, 1, 2};
do_search(Iter1(ih), Iter1(ih+sh), Iter2(ii), Iter2(ii+3), Iter1(ih+3), sh*3);
}
int main(int, char**) {
test<random_access_iterator<const int*>, random_access_iterator<const int*> >();
test2<random_access_iterator<const char*>, random_access_iterator<const char*> >();
return 0;
}
| endlessm/chromium-browser | third_party/llvm/libcxx/test/std/experimental/func/func.searchers/func.searchers.boyer_moore_horspool/hash.pred.pass.cpp | C++ | bsd-3-clause | 6,467 |
/*
* Copyright (c) 2015 The WebM project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "./vp9_rtcd.h"
#include "vp9/common/mips/msa/vp9_convolve_msa.h"
static void common_vt_8t_4w_msa(const uint8_t *src, int32_t src_stride,
uint8_t *dst, int32_t dst_stride,
int8_t *filter, int32_t height) {
uint32_t loop_cnt;
v16i8 src0, src1, src2, src3, src4, src5, src6, src7, src8, src9, src10;
v16i8 src10_r, src32_r, src54_r, src76_r, src98_r;
v16i8 src21_r, src43_r, src65_r, src87_r, src109_r;
v16i8 src2110, src4332, src6554, src8776, src10998;
v8i16 filt, out10, out32;
v16i8 filt0, filt1, filt2, filt3;
src -= (3 * src_stride);
filt = LOAD_SH(filter);
filt0 = (v16i8)__msa_splati_h(filt, 0);
filt1 = (v16i8)__msa_splati_h(filt, 1);
filt2 = (v16i8)__msa_splati_h(filt, 2);
filt3 = (v16i8)__msa_splati_h(filt, 3);
LOAD_7VECS_SB(src, src_stride, src0, src1, src2, src3, src4, src5, src6);
src += (7 * src_stride);
ILVR_B_6VECS_SB(src0, src2, src4, src1, src3, src5,
src1, src3, src5, src2, src4, src6,
src10_r, src32_r, src54_r, src21_r, src43_r, src65_r);
ILVR_D_3VECS_SB(src2110, src21_r, src10_r, src4332, src43_r, src32_r,
src6554, src65_r, src54_r);
XORI_B_3VECS_SB(src2110, src4332, src6554, src2110, src4332, src6554, 128);
for (loop_cnt = (height >> 2); loop_cnt--;) {
LOAD_4VECS_SB(src, src_stride, src7, src8, src9, src10);
src += (4 * src_stride);
ILVR_B_4VECS_SB(src6, src7, src8, src9, src7, src8, src9, src10,
src76_r, src87_r, src98_r, src109_r);
ILVR_D_2VECS_SB(src8776, src87_r, src76_r, src10998, src109_r, src98_r);
XORI_B_2VECS_SB(src8776, src10998, src8776, src10998, 128);
out10 = FILT_8TAP_DPADD_S_H(src2110, src4332, src6554, src8776,
filt0, filt1, filt2, filt3);
out32 = FILT_8TAP_DPADD_S_H(src4332, src6554, src8776, src10998,
filt0, filt1, filt2, filt3);
out10 = SRARI_SATURATE_SIGNED_H(out10, FILTER_BITS, 7);
out32 = SRARI_SATURATE_SIGNED_H(out32, FILTER_BITS, 7);
PCKEV_2B_XORI128_STORE_4_BYTES_4(out10, out32, dst, dst_stride);
dst += (4 * dst_stride);
src2110 = src6554;
src4332 = src8776;
src6554 = src10998;
src6 = src10;
}
}
static void common_vt_8t_8w_msa(const uint8_t *src, int32_t src_stride,
uint8_t *dst, int32_t dst_stride,
int8_t *filter, int32_t height) {
uint32_t loop_cnt;
v16i8 src0, src1, src2, src3, src4, src5, src6, src7, src8, src9, src10;
v16i8 src10_r, src32_r, src54_r, src76_r, src98_r;
v16i8 src21_r, src43_r, src65_r, src87_r, src109_r;
v16i8 filt0, filt1, filt2, filt3;
v8i16 filt, out0_r, out1_r, out2_r, out3_r;
src -= (3 * src_stride);
filt = LOAD_SH(filter);
filt0 = (v16i8)__msa_splati_h(filt, 0);
filt1 = (v16i8)__msa_splati_h(filt, 1);
filt2 = (v16i8)__msa_splati_h(filt, 2);
filt3 = (v16i8)__msa_splati_h(filt, 3);
LOAD_7VECS_SB(src, src_stride, src0, src1, src2, src3, src4, src5, src6);
src += (7 * src_stride);
XORI_B_7VECS_SB(src0, src1, src2, src3, src4, src5, src6,
src0, src1, src2, src3, src4, src5, src6, 128);
ILVR_B_6VECS_SB(src0, src2, src4, src1, src3, src5,
src1, src3, src5, src2, src4, src6,
src10_r, src32_r, src54_r, src21_r, src43_r, src65_r);
for (loop_cnt = (height >> 2); loop_cnt--;) {
LOAD_4VECS_SB(src, src_stride, src7, src8, src9, src10);
src += (4 * src_stride);
XORI_B_4VECS_SB(src7, src8, src9, src10, src7, src8, src9, src10, 128);
ILVR_B_4VECS_SB(src6, src7, src8, src9, src7, src8, src9, src10,
src76_r, src87_r, src98_r, src109_r);
out0_r = FILT_8TAP_DPADD_S_H(src10_r, src32_r, src54_r, src76_r,
filt0, filt1, filt2, filt3);
out1_r = FILT_8TAP_DPADD_S_H(src21_r, src43_r, src65_r, src87_r,
filt0, filt1, filt2, filt3);
out2_r = FILT_8TAP_DPADD_S_H(src32_r, src54_r, src76_r, src98_r,
filt0, filt1, filt2, filt3);
out3_r = FILT_8TAP_DPADD_S_H(src43_r, src65_r, src87_r, src109_r,
filt0, filt1, filt2, filt3);
out0_r = SRARI_SATURATE_SIGNED_H(out0_r, FILTER_BITS, 7);
out1_r = SRARI_SATURATE_SIGNED_H(out1_r, FILTER_BITS, 7);
out2_r = SRARI_SATURATE_SIGNED_H(out2_r, FILTER_BITS, 7);
out3_r = SRARI_SATURATE_SIGNED_H(out3_r, FILTER_BITS, 7);
PCKEV_B_4_XORI128_STORE_8_BYTES_4(out0_r, out1_r, out2_r, out3_r,
dst, dst_stride);
dst += (4 * dst_stride);
src10_r = src54_r;
src32_r = src76_r;
src54_r = src98_r;
src21_r = src65_r;
src43_r = src87_r;
src65_r = src109_r;
src6 = src10;
}
}
static void common_vt_8t_16w_mult_msa(const uint8_t *src, int32_t src_stride,
uint8_t *dst, int32_t dst_stride,
int8_t *filter, int32_t height,
int32_t width) {
const uint8_t *src_tmp;
uint8_t *dst_tmp;
uint32_t loop_cnt, cnt;
v16i8 src0, src1, src2, src3, src4, src5, src6, src7, src8, src9, src10;
v16i8 filt0, filt1, filt2, filt3;
v16i8 src10_r, src32_r, src54_r, src76_r, src98_r;
v16i8 src21_r, src43_r, src65_r, src87_r, src109_r;
v16i8 src10_l, src32_l, src54_l, src76_l, src98_l;
v16i8 src21_l, src43_l, src65_l, src87_l, src109_l;
v8i16 out0_r, out1_r, out2_r, out3_r, out0_l, out1_l, out2_l, out3_l;
v8i16 filt;
v16u8 tmp0, tmp1, tmp2, tmp3;
src -= (3 * src_stride);
filt = LOAD_SH(filter);
filt0 = (v16i8)__msa_splati_h(filt, 0);
filt1 = (v16i8)__msa_splati_h(filt, 1);
filt2 = (v16i8)__msa_splati_h(filt, 2);
filt3 = (v16i8)__msa_splati_h(filt, 3);
for (cnt = (width >> 4); cnt--;) {
src_tmp = src;
dst_tmp = dst;
LOAD_7VECS_SB(src_tmp, src_stride,
src0, src1, src2, src3, src4, src5, src6);
src_tmp += (7 * src_stride);
XORI_B_7VECS_SB(src0, src1, src2, src3, src4, src5, src6,
src0, src1, src2, src3, src4, src5, src6, 128);
ILVR_B_6VECS_SB(src0, src2, src4, src1, src3, src5,
src1, src3, src5, src2, src4, src6,
src10_r, src32_r, src54_r, src21_r, src43_r, src65_r);
ILVL_B_6VECS_SB(src0, src2, src4, src1, src3, src5,
src1, src3, src5, src2, src4, src6,
src10_l, src32_l, src54_l, src21_l, src43_l, src65_l);
for (loop_cnt = (height >> 2); loop_cnt--;) {
LOAD_4VECS_SB(src_tmp, src_stride, src7, src8, src9, src10);
src_tmp += (4 * src_stride);
XORI_B_4VECS_SB(src7, src8, src9, src10, src7, src8, src9, src10, 128);
ILVR_B_4VECS_SB(src6, src7, src8, src9, src7, src8, src9, src10,
src76_r, src87_r, src98_r, src109_r);
ILVL_B_4VECS_SB(src6, src7, src8, src9, src7, src8, src9, src10,
src76_l, src87_l, src98_l, src109_l);
out0_r = FILT_8TAP_DPADD_S_H(src10_r, src32_r, src54_r, src76_r,
filt0, filt1, filt2, filt3);
out1_r = FILT_8TAP_DPADD_S_H(src21_r, src43_r, src65_r, src87_r,
filt0, filt1, filt2, filt3);
out2_r = FILT_8TAP_DPADD_S_H(src32_r, src54_r, src76_r, src98_r,
filt0, filt1, filt2, filt3);
out3_r = FILT_8TAP_DPADD_S_H(src43_r, src65_r, src87_r, src109_r,
filt0, filt1, filt2, filt3);
out0_l = FILT_8TAP_DPADD_S_H(src10_l, src32_l, src54_l, src76_l,
filt0, filt1, filt2, filt3);
out1_l = FILT_8TAP_DPADD_S_H(src21_l, src43_l, src65_l, src87_l,
filt0, filt1, filt2, filt3);
out2_l = FILT_8TAP_DPADD_S_H(src32_l, src54_l, src76_l, src98_l,
filt0, filt1, filt2, filt3);
out3_l = FILT_8TAP_DPADD_S_H(src43_l, src65_l, src87_l, src109_l,
filt0, filt1, filt2, filt3);
out0_r = SRARI_SATURATE_SIGNED_H(out0_r, FILTER_BITS, 7);
out1_r = SRARI_SATURATE_SIGNED_H(out1_r, FILTER_BITS, 7);
out2_r = SRARI_SATURATE_SIGNED_H(out2_r, FILTER_BITS, 7);
out3_r = SRARI_SATURATE_SIGNED_H(out3_r, FILTER_BITS, 7);
out0_l = SRARI_SATURATE_SIGNED_H(out0_l, FILTER_BITS, 7);
out1_l = SRARI_SATURATE_SIGNED_H(out1_l, FILTER_BITS, 7);
out2_l = SRARI_SATURATE_SIGNED_H(out2_l, FILTER_BITS, 7);
out3_l = SRARI_SATURATE_SIGNED_H(out3_l, FILTER_BITS, 7);
out0_r = (v8i16)__msa_pckev_b((v16i8)out0_l, (v16i8)out0_r);
out1_r = (v8i16)__msa_pckev_b((v16i8)out1_l, (v16i8)out1_r);
out2_r = (v8i16)__msa_pckev_b((v16i8)out2_l, (v16i8)out2_r);
out3_r = (v8i16)__msa_pckev_b((v16i8)out3_l, (v16i8)out3_r);
XORI_B_4VECS_UB(out0_r, out1_r, out2_r, out3_r,
tmp0, tmp1, tmp2, tmp3, 128);
STORE_4VECS_UB(dst_tmp, dst_stride, tmp0, tmp1, tmp2, tmp3);
dst_tmp += (4 * dst_stride);
src10_r = src54_r;
src32_r = src76_r;
src54_r = src98_r;
src21_r = src65_r;
src43_r = src87_r;
src65_r = src109_r;
src10_l = src54_l;
src32_l = src76_l;
src54_l = src98_l;
src21_l = src65_l;
src43_l = src87_l;
src65_l = src109_l;
src6 = src10;
}
src += 16;
dst += 16;
}
}
static void common_vt_8t_16w_msa(const uint8_t *src, int32_t src_stride,
uint8_t *dst, int32_t dst_stride,
int8_t *filter, int32_t height) {
common_vt_8t_16w_mult_msa(src, src_stride, dst, dst_stride,
filter, height, 16);
}
static void common_vt_8t_32w_msa(const uint8_t *src, int32_t src_stride,
uint8_t *dst, int32_t dst_stride,
int8_t *filter, int32_t height) {
common_vt_8t_16w_mult_msa(src, src_stride, dst, dst_stride,
filter, height, 32);
}
static void common_vt_8t_64w_msa(const uint8_t *src, int32_t src_stride,
uint8_t *dst, int32_t dst_stride,
int8_t *filter, int32_t height) {
common_vt_8t_16w_mult_msa(src, src_stride, dst, dst_stride,
filter, height, 64);
}
static void common_vt_2t_4x4_msa(const uint8_t *src, int32_t src_stride,
uint8_t *dst, int32_t dst_stride,
int8_t *filter) {
uint32_t out0, out1, out2, out3;
v16i8 src0, src1, src2, src3, src4;
v16i8 src10_r, src32_r, src21_r, src43_r, src2110, src4332;
v16i8 filt0;
v8u16 filt;
filt = LOAD_UH(filter);
filt0 = (v16i8)__msa_splati_h((v8i16)filt, 0);
LOAD_5VECS_SB(src, src_stride, src0, src1, src2, src3, src4);
src += (5 * src_stride);
ILVR_B_4VECS_SB(src0, src1, src2, src3, src1, src2, src3, src4,
src10_r, src21_r, src32_r, src43_r);
ILVR_D_2VECS_SB(src2110, src21_r, src10_r, src4332, src43_r, src32_r);
src2110 = (v16i8)__msa_dotp_u_h((v16u8)src2110, (v16u8)filt0);
src4332 = (v16i8)__msa_dotp_u_h((v16u8)src4332, (v16u8)filt0);
src2110 = (v16i8)SRARI_SATURATE_UNSIGNED_H(src2110, FILTER_BITS, 7);
src4332 = (v16i8)SRARI_SATURATE_UNSIGNED_H(src4332, FILTER_BITS, 7);
src2110 = (v16i8)__msa_pckev_b((v16i8)src4332, (v16i8)src2110);
out0 = __msa_copy_u_w((v4i32)src2110, 0);
out1 = __msa_copy_u_w((v4i32)src2110, 1);
out2 = __msa_copy_u_w((v4i32)src2110, 2);
out3 = __msa_copy_u_w((v4i32)src2110, 3);
STORE_WORD(dst, out0);
dst += dst_stride;
STORE_WORD(dst, out1);
dst += dst_stride;
STORE_WORD(dst, out2);
dst += dst_stride;
STORE_WORD(dst, out3);
}
static void common_vt_2t_4x8_msa(const uint8_t *src, int32_t src_stride,
uint8_t *dst, int32_t dst_stride,
int8_t *filter) {
uint32_t out0, out1, out2, out3, out4, out5, out6, out7;
v16i8 src0, src1, src2, src3, src4, src5, src6, src7, src8;
v16i8 src10_r, src32_r, src54_r, src76_r, src21_r, src43_r;
v16i8 src65_r, src87_r, src2110, src4332, src6554, src8776;
v16i8 filt0;
v8u16 filt;
filt = LOAD_UH(filter);
filt0 = (v16i8)__msa_splati_h((v8i16)filt, 0);
LOAD_8VECS_SB(src, src_stride,
src0, src1, src2, src3, src4, src5, src6, src7);
src += (8 * src_stride);
src8 = LOAD_SB(src);
src += src_stride;
ILVR_B_8VECS_SB(src0, src1, src2, src3, src4, src5, src6, src7,
src1, src2, src3, src4, src5, src6, src7, src8,
src10_r, src21_r, src32_r, src43_r,
src54_r, src65_r, src76_r, src87_r);
ILVR_D_4VECS_SB(src2110, src21_r, src10_r, src4332, src43_r, src32_r,
src6554, src65_r, src54_r, src8776, src87_r, src76_r);
src2110 = (v16i8)__msa_dotp_u_h((v16u8)src2110, (v16u8)filt0);
src4332 = (v16i8)__msa_dotp_u_h((v16u8)src4332, (v16u8)filt0);
src6554 = (v16i8)__msa_dotp_u_h((v16u8)src6554, (v16u8)filt0);
src8776 = (v16i8)__msa_dotp_u_h((v16u8)src8776, (v16u8)filt0);
src2110 = (v16i8)SRARI_SATURATE_UNSIGNED_H(src2110, FILTER_BITS, 7);
src4332 = (v16i8)SRARI_SATURATE_UNSIGNED_H(src4332, FILTER_BITS, 7);
src6554 = (v16i8)SRARI_SATURATE_UNSIGNED_H(src6554, FILTER_BITS, 7);
src8776 = (v16i8)SRARI_SATURATE_UNSIGNED_H(src8776, FILTER_BITS, 7);
src2110 = (v16i8)__msa_pckev_b((v16i8)src4332, (v16i8)src2110);
src4332 = (v16i8)__msa_pckev_b((v16i8)src8776, (v16i8)src6554);
out0 = __msa_copy_u_w((v4i32)src2110, 0);
out1 = __msa_copy_u_w((v4i32)src2110, 1);
out2 = __msa_copy_u_w((v4i32)src2110, 2);
out3 = __msa_copy_u_w((v4i32)src2110, 3);
out4 = __msa_copy_u_w((v4i32)src4332, 0);
out5 = __msa_copy_u_w((v4i32)src4332, 1);
out6 = __msa_copy_u_w((v4i32)src4332, 2);
out7 = __msa_copy_u_w((v4i32)src4332, 3);
STORE_WORD(dst, out0);
dst += dst_stride;
STORE_WORD(dst, out1);
dst += dst_stride;
STORE_WORD(dst, out2);
dst += dst_stride;
STORE_WORD(dst, out3);
dst += dst_stride;
STORE_WORD(dst, out4);
dst += dst_stride;
STORE_WORD(dst, out5);
dst += dst_stride;
STORE_WORD(dst, out6);
dst += dst_stride;
STORE_WORD(dst, out7);
}
static void common_vt_2t_4w_msa(const uint8_t *src, int32_t src_stride,
uint8_t *dst, int32_t dst_stride,
int8_t *filter, int32_t height) {
if (4 == height) {
common_vt_2t_4x4_msa(src, src_stride, dst, dst_stride, filter);
} else if (8 == height) {
common_vt_2t_4x8_msa(src, src_stride, dst, dst_stride, filter);
}
}
static void common_vt_2t_8x4_msa(const uint8_t *src, int32_t src_stride,
uint8_t *dst, int32_t dst_stride,
int8_t *filter) {
v16u8 src0, src1, src2, src3, src4;
v16u8 vec0, vec1, vec2, vec3, filt0;
v8u16 tmp0, tmp1, tmp2, tmp3;
v8u16 filt;
/* rearranging filter_y */
filt = LOAD_UH(filter);
filt0 = (v16u8)__msa_splati_h((v8i16)filt, 0);
LOAD_5VECS_UB(src, src_stride, src0, src1, src2, src3, src4);
ILVR_B_2VECS_UB(src0, src1, src1, src2, vec0, vec1);
ILVR_B_2VECS_UB(src2, src3, src3, src4, vec2, vec3);
/* filter calc */
tmp0 = __msa_dotp_u_h(vec0, filt0);
tmp1 = __msa_dotp_u_h(vec1, filt0);
tmp2 = __msa_dotp_u_h(vec2, filt0);
tmp3 = __msa_dotp_u_h(vec3, filt0);
tmp0 = SRARI_SATURATE_UNSIGNED_H(tmp0, FILTER_BITS, 7);
tmp1 = SRARI_SATURATE_UNSIGNED_H(tmp1, FILTER_BITS, 7);
tmp2 = SRARI_SATURATE_UNSIGNED_H(tmp2, FILTER_BITS, 7);
tmp3 = SRARI_SATURATE_UNSIGNED_H(tmp3, FILTER_BITS, 7);
PCKEV_B_STORE_8_BYTES_4(tmp0, tmp1, tmp2, tmp3, dst, dst_stride);
}
static void common_vt_2t_8x8mult_msa(const uint8_t *src, int32_t src_stride,
uint8_t *dst, int32_t dst_stride,
int8_t *filter, int32_t height) {
uint32_t loop_cnt;
v16u8 src0, src1, src2, src3, src4, src5, src6, src7, src8;
v16u8 vec0, vec1, vec2, vec3, vec4, vec5, vec6, vec7, filt0;
v8u16 tmp0, tmp1, tmp2, tmp3;
v8u16 filt;
/* rearranging filter_y */
filt = LOAD_UH(filter);
filt0 = (v16u8)__msa_splati_h((v8i16)filt, 0);
src0 = LOAD_UB(src);
src += src_stride;
for (loop_cnt = (height >> 3); loop_cnt--;) {
LOAD_8VECS_UB(src, src_stride,
src1, src2, src3, src4, src5, src6, src7, src8);
src += (8 * src_stride);
ILVR_B_4VECS_UB(src0, src1, src2, src3, src1, src2, src3, src4,
vec0, vec1, vec2, vec3);
ILVR_B_4VECS_UB(src4, src5, src6, src7, src5, src6, src7, src8,
vec4, vec5, vec6, vec7);
tmp0 = __msa_dotp_u_h(vec0, filt0);
tmp1 = __msa_dotp_u_h(vec1, filt0);
tmp2 = __msa_dotp_u_h(vec2, filt0);
tmp3 = __msa_dotp_u_h(vec3, filt0);
tmp0 = SRARI_SATURATE_UNSIGNED_H(tmp0, FILTER_BITS, 7);
tmp1 = SRARI_SATURATE_UNSIGNED_H(tmp1, FILTER_BITS, 7);
tmp2 = SRARI_SATURATE_UNSIGNED_H(tmp2, FILTER_BITS, 7);
tmp3 = SRARI_SATURATE_UNSIGNED_H(tmp3, FILTER_BITS, 7);
PCKEV_B_STORE_8_BYTES_4(tmp0, tmp1, tmp2, tmp3, dst, dst_stride);
dst += (4 * dst_stride);
tmp0 = __msa_dotp_u_h(vec4, filt0);
tmp1 = __msa_dotp_u_h(vec5, filt0);
tmp2 = __msa_dotp_u_h(vec6, filt0);
tmp3 = __msa_dotp_u_h(vec7, filt0);
tmp0 = SRARI_SATURATE_UNSIGNED_H(tmp0, FILTER_BITS, 7);
tmp1 = SRARI_SATURATE_UNSIGNED_H(tmp1, FILTER_BITS, 7);
tmp2 = SRARI_SATURATE_UNSIGNED_H(tmp2, FILTER_BITS, 7);
tmp3 = SRARI_SATURATE_UNSIGNED_H(tmp3, FILTER_BITS, 7);
PCKEV_B_STORE_8_BYTES_4(tmp0, tmp1, tmp2, tmp3, dst, dst_stride);
dst += (4 * dst_stride);
src0 = src8;
}
}
static void common_vt_2t_8w_msa(const uint8_t *src, int32_t src_stride,
uint8_t *dst, int32_t dst_stride,
int8_t *filter, int32_t height) {
if (4 == height) {
common_vt_2t_8x4_msa(src, src_stride, dst, dst_stride, filter);
} else {
common_vt_2t_8x8mult_msa(src, src_stride, dst, dst_stride, filter, height);
}
}
static void common_vt_2t_16w_msa(const uint8_t *src, int32_t src_stride,
uint8_t *dst, int32_t dst_stride,
int8_t *filter, int32_t height) {
uint32_t loop_cnt;
v16u8 src0, src1, src2, src3, src4;
v16u8 vec0, vec1, vec2, vec3, vec4, vec5, vec6, vec7, filt0;
v8u16 tmp0, tmp1, tmp2, tmp3;
v8u16 filt;
/* rearranging filter_y */
filt = LOAD_UH(filter);
filt0 = (v16u8)__msa_splati_h((v8i16)filt, 0);
src0 = LOAD_UB(src);
src += src_stride;
for (loop_cnt = (height >> 2); loop_cnt--;) {
LOAD_4VECS_UB(src, src_stride, src1, src2, src3, src4);
src += (4 * src_stride);
ILV_B_LRLR_UB(src0, src1, src1, src2, vec1, vec0, vec3, vec2);
tmp0 = __msa_dotp_u_h(vec0, filt0);
tmp1 = __msa_dotp_u_h(vec1, filt0);
tmp0 = SRARI_SATURATE_UNSIGNED_H(tmp0, FILTER_BITS, 7);
tmp1 = SRARI_SATURATE_UNSIGNED_H(tmp1, FILTER_BITS, 7);
PCKEV_B_STORE_VEC(tmp1, tmp0, dst);
dst += dst_stride;
ILV_B_LRLR_UB(src2, src3, src3, src4, vec5, vec4, vec7, vec6);
tmp2 = __msa_dotp_u_h(vec2, filt0);
tmp3 = __msa_dotp_u_h(vec3, filt0);
tmp3 = SRARI_SATURATE_UNSIGNED_H(tmp3, FILTER_BITS, 7);
tmp2 = SRARI_SATURATE_UNSIGNED_H(tmp2, FILTER_BITS, 7);
PCKEV_B_STORE_VEC(tmp3, tmp2, dst);
dst += dst_stride;
tmp0 = __msa_dotp_u_h(vec4, filt0);
tmp1 = __msa_dotp_u_h(vec5, filt0);
tmp0 = SRARI_SATURATE_UNSIGNED_H(tmp0, FILTER_BITS, 7);
tmp1 = SRARI_SATURATE_UNSIGNED_H(tmp1, FILTER_BITS, 7);
PCKEV_B_STORE_VEC(tmp1, tmp0, dst);
dst += dst_stride;
tmp2 = __msa_dotp_u_h(vec6, filt0);
tmp3 = __msa_dotp_u_h(vec7, filt0);
tmp2 = SRARI_SATURATE_UNSIGNED_H(tmp2, FILTER_BITS, 7);
tmp3 = SRARI_SATURATE_UNSIGNED_H(tmp3, FILTER_BITS, 7);
PCKEV_B_STORE_VEC(tmp3, tmp2, dst);
dst += dst_stride;
src0 = src4;
}
}
static void common_vt_2t_32w_msa(const uint8_t *src, int32_t src_stride,
uint8_t *dst, int32_t dst_stride,
int8_t *filter, int32_t height) {
uint32_t loop_cnt;
v16u8 src0, src1, src2, src3, src4, src5, src6, src7, src8, src9;
v16u8 vec0, vec1, vec2, vec3, vec4, vec5, vec6, vec7, filt0;
v8u16 tmp0, tmp1, tmp2, tmp3;
v8u16 filt;
/* rearranging filter_y */
filt = LOAD_UH(filter);
filt0 = (v16u8)__msa_splati_h((v8i16)filt, 0);
src0 = LOAD_UB(src);
src5 = LOAD_UB(src + 16);
src += src_stride;
for (loop_cnt = (height >> 2); loop_cnt--;) {
LOAD_4VECS_UB(src, src_stride, src1, src2, src3, src4);
ILV_B_LRLR_UB(src0, src1, src1, src2, vec1, vec0, vec3, vec2);
LOAD_4VECS_UB(src + 16, src_stride, src6, src7, src8, src9);
src += (4 * src_stride);
tmp0 = __msa_dotp_u_h(vec0, filt0);
tmp1 = __msa_dotp_u_h(vec1, filt0);
tmp0 = SRARI_SATURATE_UNSIGNED_H(tmp0, FILTER_BITS, 7);
tmp1 = SRARI_SATURATE_UNSIGNED_H(tmp1, FILTER_BITS, 7);
PCKEV_B_STORE_VEC(tmp1, tmp0, dst);
tmp2 = __msa_dotp_u_h(vec2, filt0);
tmp3 = __msa_dotp_u_h(vec3, filt0);
tmp2 = SRARI_SATURATE_UNSIGNED_H(tmp2, FILTER_BITS, 7);
tmp3 = SRARI_SATURATE_UNSIGNED_H(tmp3, FILTER_BITS, 7);
PCKEV_B_STORE_VEC(tmp3, tmp2, dst + dst_stride);
ILV_B_LRLR_UB(src2, src3, src3, src4, vec5, vec4, vec7, vec6);
tmp0 = __msa_dotp_u_h(vec4, filt0);
tmp1 = __msa_dotp_u_h(vec5, filt0);
tmp0 = SRARI_SATURATE_UNSIGNED_H(tmp0, FILTER_BITS, 7);
tmp1 = SRARI_SATURATE_UNSIGNED_H(tmp1, FILTER_BITS, 7);
PCKEV_B_STORE_VEC(tmp1, tmp0, dst + 2 * dst_stride);
tmp2 = __msa_dotp_u_h(vec6, filt0);
tmp3 = __msa_dotp_u_h(vec7, filt0);
tmp2 = SRARI_SATURATE_UNSIGNED_H(tmp2, FILTER_BITS, 7);
tmp3 = SRARI_SATURATE_UNSIGNED_H(tmp3, FILTER_BITS, 7);
PCKEV_B_STORE_VEC(tmp3, tmp2, dst + 3 * dst_stride);
ILV_B_LRLR_UB(src5, src6, src6, src7, vec1, vec0, vec3, vec2);
tmp0 = __msa_dotp_u_h(vec0, filt0);
tmp1 = __msa_dotp_u_h(vec1, filt0);
tmp0 = SRARI_SATURATE_UNSIGNED_H(tmp0, FILTER_BITS, 7);
tmp1 = SRARI_SATURATE_UNSIGNED_H(tmp1, FILTER_BITS, 7);
PCKEV_B_STORE_VEC(tmp1, tmp0, dst + 16);
tmp2 = __msa_dotp_u_h(vec2, filt0);
tmp3 = __msa_dotp_u_h(vec3, filt0);
tmp2 = SRARI_SATURATE_UNSIGNED_H(tmp2, FILTER_BITS, 7);
tmp3 = SRARI_SATURATE_UNSIGNED_H(tmp3, FILTER_BITS, 7);
PCKEV_B_STORE_VEC(tmp3, tmp2, dst + 16 + dst_stride);
ILV_B_LRLR_UB(src7, src8, src8, src9, vec5, vec4, vec7, vec6);
tmp0 = __msa_dotp_u_h(vec4, filt0);
tmp1 = __msa_dotp_u_h(vec5, filt0);
tmp0 = SRARI_SATURATE_UNSIGNED_H(tmp0, FILTER_BITS, 7);
tmp1 = SRARI_SATURATE_UNSIGNED_H(tmp1, FILTER_BITS, 7);
PCKEV_B_STORE_VEC(tmp1, tmp0, dst + 16 + 2 * dst_stride);
tmp2 = __msa_dotp_u_h(vec6, filt0);
tmp3 = __msa_dotp_u_h(vec7, filt0);
tmp2 = SRARI_SATURATE_UNSIGNED_H(tmp2, FILTER_BITS, 7);
tmp3 = SRARI_SATURATE_UNSIGNED_H(tmp3, FILTER_BITS, 7);
PCKEV_B_STORE_VEC(tmp3, tmp2, dst + 16 + 3 * dst_stride);
dst += (4 * dst_stride);
src0 = src4;
src5 = src9;
}
}
static void common_vt_2t_64w_msa(const uint8_t *src, int32_t src_stride,
uint8_t *dst, int32_t dst_stride,
int8_t *filter, int32_t height) {
uint32_t loop_cnt;
v16u8 src0, src1, src2, src3, src4, src5, src6, src7;
v16u8 src8, src9, src10, src11;
v16u8 vec0, vec1, vec2, vec3, vec4, vec5, vec6, vec7, filt0;
v8u16 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
v8u16 filt;
/* rearranging filter_y */
filt = LOAD_UH(filter);
filt0 = (v16u8)__msa_splati_h((v8i16)filt, 0);
LOAD_4VECS_UB(src, 16, src0, src3, src6, src9);
src += src_stride;
for (loop_cnt = (height >> 1); loop_cnt--;) {
LOAD_2VECS_UB(src, src_stride, src1, src2);
LOAD_2VECS_UB(src + 16, src_stride, src4, src5);
LOAD_2VECS_UB(src + 32, src_stride, src7, src8);
LOAD_2VECS_UB(src + 48, src_stride, src10, src11);
src += (2 * src_stride);
ILV_B_LRLR_UB(src0, src1, src1, src2, vec1, vec0, vec3, vec2);
tmp0 = __msa_dotp_u_h(vec0, filt0);
tmp1 = __msa_dotp_u_h(vec1, filt0);
tmp0 = SRARI_SATURATE_UNSIGNED_H(tmp0, FILTER_BITS, 7);
tmp1 = SRARI_SATURATE_UNSIGNED_H(tmp1, FILTER_BITS, 7);
PCKEV_B_STORE_VEC(tmp1, tmp0, dst);
tmp2 = __msa_dotp_u_h(vec2, filt0);
tmp3 = __msa_dotp_u_h(vec3, filt0);
tmp3 = SRARI_SATURATE_UNSIGNED_H(tmp3, FILTER_BITS, 7);
tmp2 = SRARI_SATURATE_UNSIGNED_H(tmp2, FILTER_BITS, 7);
PCKEV_B_STORE_VEC(tmp3, tmp2, dst + dst_stride);
ILV_B_LRLR_UB(src3, src4, src4, src5, vec5, vec4, vec7, vec6);
tmp4 = __msa_dotp_u_h(vec4, filt0);
tmp5 = __msa_dotp_u_h(vec5, filt0);
tmp4 = SRARI_SATURATE_UNSIGNED_H(tmp4, FILTER_BITS, 7);
tmp5 = SRARI_SATURATE_UNSIGNED_H(tmp5, FILTER_BITS, 7);
PCKEV_B_STORE_VEC(tmp5, tmp4, dst + 16);
tmp6 = __msa_dotp_u_h(vec6, filt0);
tmp7 = __msa_dotp_u_h(vec7, filt0);
tmp6 = SRARI_SATURATE_UNSIGNED_H(tmp6, FILTER_BITS, 7);
tmp7 = SRARI_SATURATE_UNSIGNED_H(tmp7, FILTER_BITS, 7);
PCKEV_B_STORE_VEC(tmp7, tmp6, dst + 16 + dst_stride);
ILV_B_LRLR_UB(src6, src7, src7, src8, vec1, vec0, vec3, vec2);
tmp0 = __msa_dotp_u_h(vec0, filt0);
tmp1 = __msa_dotp_u_h(vec1, filt0);
tmp0 = SRARI_SATURATE_UNSIGNED_H(tmp0, FILTER_BITS, 7);
tmp1 = SRARI_SATURATE_UNSIGNED_H(tmp1, FILTER_BITS, 7);
PCKEV_B_STORE_VEC(tmp1, tmp0, dst + 32);
tmp2 = __msa_dotp_u_h(vec2, filt0);
tmp3 = __msa_dotp_u_h(vec3, filt0);
tmp2 = SRARI_SATURATE_UNSIGNED_H(tmp2, FILTER_BITS, 7);
tmp3 = SRARI_SATURATE_UNSIGNED_H(tmp3, FILTER_BITS, 7);
PCKEV_B_STORE_VEC(tmp3, tmp2, dst + 32 + dst_stride);
ILV_B_LRLR_UB(src9, src10, src10, src11, vec5, vec4, vec7, vec6);
tmp4 = __msa_dotp_u_h(vec4, filt0);
tmp5 = __msa_dotp_u_h(vec5, filt0);
tmp4 = SRARI_SATURATE_UNSIGNED_H(tmp4, FILTER_BITS, 7);
tmp5 = SRARI_SATURATE_UNSIGNED_H(tmp5, FILTER_BITS, 7);
PCKEV_B_STORE_VEC(tmp5, tmp4, dst + 48);
tmp6 = __msa_dotp_u_h(vec6, filt0);
tmp7 = __msa_dotp_u_h(vec7, filt0);
tmp6 = SRARI_SATURATE_UNSIGNED_H(tmp6, FILTER_BITS, 7);
tmp7 = SRARI_SATURATE_UNSIGNED_H(tmp7, FILTER_BITS, 7);
PCKEV_B_STORE_VEC(tmp7, tmp6, dst + 48 + dst_stride);
dst += (2 * dst_stride);
src0 = src2;
src3 = src5;
src6 = src8;
src9 = src11;
}
}
void vp9_convolve8_vert_msa(const uint8_t *src, ptrdiff_t src_stride,
uint8_t *dst, ptrdiff_t dst_stride,
const int16_t *filter_x, int x_step_q4,
const int16_t *filter_y, int y_step_q4,
int w, int h) {
int8_t cnt, filt_ver[8];
if (16 != y_step_q4) {
vp9_convolve8_vert_c(src, src_stride, dst, dst_stride,
filter_x, x_step_q4, filter_y, y_step_q4,
w, h);
return;
}
if (((const int32_t *)filter_y)[1] == 0x800000) {
vp9_convolve_copy(src, src_stride, dst, dst_stride,
filter_x, x_step_q4, filter_y, y_step_q4,
w, h);
return;
}
for (cnt = 8; cnt--;) {
filt_ver[cnt] = filter_y[cnt];
}
if (((const int32_t *)filter_y)[0] == 0) {
switch (w) {
case 4:
common_vt_2t_4w_msa(src, (int32_t)src_stride,
dst, (int32_t)dst_stride,
&filt_ver[3], h);
break;
case 8:
common_vt_2t_8w_msa(src, (int32_t)src_stride,
dst, (int32_t)dst_stride,
&filt_ver[3], h);
break;
case 16:
common_vt_2t_16w_msa(src, (int32_t)src_stride,
dst, (int32_t)dst_stride,
&filt_ver[3], h);
break;
case 32:
common_vt_2t_32w_msa(src, (int32_t)src_stride,
dst, (int32_t)dst_stride,
&filt_ver[3], h);
break;
case 64:
common_vt_2t_64w_msa(src, (int32_t)src_stride,
dst, (int32_t)dst_stride,
&filt_ver[3], h);
break;
default:
vp9_convolve8_vert_c(src, src_stride, dst, dst_stride,
filter_x, x_step_q4, filter_y, y_step_q4,
w, h);
break;
}
} else {
switch (w) {
case 4:
common_vt_8t_4w_msa(src, (int32_t)src_stride,
dst, (int32_t)dst_stride,
filt_ver, h);
break;
case 8:
common_vt_8t_8w_msa(src, (int32_t)src_stride,
dst, (int32_t)dst_stride,
filt_ver, h);
break;
case 16:
common_vt_8t_16w_msa(src, (int32_t)src_stride,
dst, (int32_t)dst_stride,
filt_ver, h);
break;
case 32:
common_vt_8t_32w_msa(src, (int32_t)src_stride,
dst, (int32_t)dst_stride,
filt_ver, h);
break;
case 64:
common_vt_8t_64w_msa(src, (int32_t)src_stride,
dst, (int32_t)dst_stride,
filt_ver, h);
break;
default:
vp9_convolve8_vert_c(src, src_stride, dst, dst_stride,
filter_x, x_step_q4, filter_y, y_step_q4,
w, h);
break;
}
}
}
| jacklicn/webm.libvpx | vp9/common/mips/msa/vp9_convolve8_vert_msa.c | C | bsd-3-clause | 30,217 |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebsitePanel.Providers.Virtualization;
using WebsitePanel.EnterpriseServer;
using WebsitePanel.Providers.Common;
namespace WebsitePanel.Portal.VPS
{
public partial class VpsDetailsNetwork : WebsitePanelModuleBase
{
VirtualMachine vm = null;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindVirtualMachine();
BindExternalAddresses();
BindPrivateAddresses();
ToggleButtons();
}
}
private void BindVirtualMachine()
{
vm = ES.Services.VPS.GetVirtualMachineItem(PanelRequest.ItemID);
// external network
if (!vm.ExternalNetworkEnabled)
{
secExternalNetwork.Visible = false;
ExternalNetworkPanel.Visible = false;
}
// private network
if (!vm.PrivateNetworkEnabled)
{
secPrivateNetwork.Visible = false;
PrivateNetworkPanel.Visible = false;
}
}
private void BindExternalAddresses()
{
// load details
NetworkAdapterDetails nic = ES.Services.VPS.GetExternalNetworkAdapterDetails(PanelRequest.ItemID);
// bind details
foreach (NetworkAdapterIPAddress ip in nic.IPAddresses)
{
if (ip.IsPrimary)
{
litExtAddress.Text = ip.IPAddress;
litExtSubnet.Text = ip.SubnetMask;
litExtGateway.Text = ip.DefaultGateway;
break;
}
}
lblTotalExternal.Text = nic.IPAddresses.Length.ToString();
// bind IP addresses
gvExternalAddresses.DataSource = nic.IPAddresses;
gvExternalAddresses.DataBind();
}
private void BindPrivateAddresses()
{
// load details
NetworkAdapterDetails nic = ES.Services.VPS.GetPrivateNetworkAdapterDetails(PanelRequest.ItemID);
// bind details
foreach (NetworkAdapterIPAddress ip in nic.IPAddresses)
{
if (ip.IsPrimary)
{
litPrivAddress.Text = ip.IPAddress;
break;
}
}
litPrivSubnet.Text = nic.SubnetMask;
litPrivFormat.Text = nic.NetworkFormat;
lblTotalPrivate.Text = nic.IPAddresses.Length.ToString();
// bind IP addresses
gvPrivateAddresses.DataSource = nic.IPAddresses;
gvPrivateAddresses.DataBind();
if (nic.IsDHCP)
{
PrivateAddressesPanel.Visible = false;
litPrivAddress.Text = GetLocalizedString("Automatic.Text");
}
}
private void ToggleButtons()
{
bool manageAllowed = VirtualMachinesHelper.IsVirtualMachineManagementAllowed(PanelSecurity.PackageId);
btnAddExternalAddress.Visible = manageAllowed;
btnSetPrimaryExternal.Visible = manageAllowed;
btnDeleteExternal.Visible = manageAllowed;
gvExternalAddresses.Columns[0].Visible = manageAllowed;
btnAddPrivateAddress.Visible = manageAllowed;
btnSetPrimaryPrivate.Visible = manageAllowed;
btnDeletePrivate.Visible = manageAllowed;
gvPrivateAddresses.Columns[0].Visible = manageAllowed;
}
protected void btnAddExternalAddress_Click(object sender, EventArgs e)
{
Response.Redirect(EditUrl("ItemID", PanelRequest.ItemID.ToString(), "vps_add_external_ip",
"SpaceID=" + PanelSecurity.PackageId.ToString()));
}
protected void btnAddPrivateAddress_Click(object sender, EventArgs e)
{
Response.Redirect(EditUrl("ItemID", PanelRequest.ItemID.ToString(), "vps_add_private_ip",
"SpaceID=" + PanelSecurity.PackageId.ToString()));
}
protected void btnSetPrimaryPrivate_Click(object sender, EventArgs e)
{
int[] addressIds = GetSelectedItems(gvPrivateAddresses);
// check if at least one is selected
if (addressIds.Length == 0)
{
messageBox.ShowWarningMessage("IP_ADDRESS_NOT_SELECTED");
return;
}
try
{
ResultObject res = ES.Services.VPS.SetVirtualMachinePrimaryPrivateIPAddress(PanelRequest.ItemID, addressIds[0]);
if (res.IsSuccess)
{
BindPrivateAddresses();
return;
}
else
{
messageBox.ShowMessage(res, "VPS_ERROR_SETTING_PRIMARY_IP", "VPS");
return;
}
}
catch (Exception ex)
{
messageBox.ShowErrorMessage("VPS_ERROR_SETTING_PRIMARY_IP", ex);
}
}
protected void btnDeletePrivate_Click(object sender, EventArgs e)
{
int[] addressIds = GetSelectedItems(gvPrivateAddresses);
// check if at least one is selected
if (addressIds.Length == 0)
{
messageBox.ShowWarningMessage("IP_ADDRESS_NOT_SELECTED");
return;
}
try
{
ResultObject res = ES.Services.VPS.DeleteVirtualMachinePrivateIPAddresses(PanelRequest.ItemID, addressIds);
if (res.IsSuccess)
{
BindPrivateAddresses();
return;
}
else
{
messageBox.ShowMessage(res, "VPS_ERROR_DELETING_IP_ADDRESS", "VPS");
return;
}
}
catch (Exception ex)
{
messageBox.ShowErrorMessage("VPS_ERROR_DELETING_IP_ADDRESS", ex);
}
}
protected void btnSetPrimaryExternal_Click(object sender, EventArgs e)
{
int[] addressIds = GetSelectedItems(gvExternalAddresses);
// check if at least one is selected
if (addressIds.Length == 0)
{
messageBox.ShowWarningMessage("IP_ADDRESS_NOT_SELECTED");
return;
}
try
{
ResultObject res = ES.Services.VPS.SetVirtualMachinePrimaryExternalIPAddress(PanelRequest.ItemID, addressIds[0]);
if (res.IsSuccess)
{
BindExternalAddresses();
return;
}
else
{
messageBox.ShowMessage(res, "VPS_ERROR_SETTING_PRIMARY_IP", "VPS");
return;
}
}
catch (Exception ex)
{
messageBox.ShowErrorMessage("VPS_ERROR_SETTING_PRIMARY_IP", ex);
}
}
protected void btnDeleteExternal_Click(object sender, EventArgs e)
{
int[] addressIds = GetSelectedItems(gvExternalAddresses);
// check if at least one is selected
if (addressIds.Length == 0)
{
messageBox.ShowWarningMessage("IP_ADDRESS_NOT_SELECTED");
return;
}
try
{
ResultObject res = ES.Services.VPS.DeleteVirtualMachineExternalIPAddresses(PanelRequest.ItemID, addressIds);
if (res.IsSuccess)
{
BindExternalAddresses();
return;
}
else
{
messageBox.ShowMessage(res, "VPS_ERROR_DELETING_IP_ADDRESS", "VPS");
return;
}
}
catch (Exception ex)
{
messageBox.ShowErrorMessage("VPS_ERROR_DELETING_IP_ADDRESS", ex);
}
}
private int[] GetSelectedItems(GridView gv)
{
List<int> items = new List<int>();
for (int i = 0; i < gv.Rows.Count; i++)
{
GridViewRow row = gv.Rows[i];
CheckBox chkSelect = (CheckBox)row.FindControl("chkSelect");
if (chkSelect.Checked)
items.Add((int)gv.DataKeys[i].Value);
}
return items.ToArray();
}
}
}
| simonegli8/Websitepanel | WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/VPS/VpsDetailsNetwork.ascx.cs | C# | bsd-3-clause | 10,694 |
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <stddef.h>
#include "base/numerics/safe_conversions.h"
#include "media/filters/h264_parser.h"
// Entry point for LibFuzzer.
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
if (!size)
return 0;
media::H264Parser parser;
parser.SetStream(data, base::checked_cast<off_t>(size));
// Parse until the end of stream/unsupported stream/error in stream is
// found.
while (true) {
media::H264NALU nalu;
media::H264Parser::Result res = parser.AdvanceToNextNALU(&nalu);
if (res != media::H264Parser::kOk)
break;
switch (nalu.nal_unit_type) {
case media::H264NALU::kIDRSlice:
case media::H264NALU::kNonIDRSlice: {
media::H264SliceHeader shdr;
res = parser.ParseSliceHeader(nalu, &shdr);
break;
}
case media::H264NALU::kSPS: {
int id;
res = parser.ParseSPS(&id);
break;
}
case media::H264NALU::kPPS: {
int id;
res = parser.ParsePPS(&id);
break;
}
case media::H264NALU::kSEIMessage: {
media::H264SEIMessage sei_msg;
res = parser.ParseSEI(&sei_msg);
break;
}
default:
// Skip any other NALU.
break;
}
if (res != media::H264Parser::kOk)
break;
}
return 0;
}
| axinging/chromium-crosswalk | media/filters/h264_parser_fuzzertest.cc | C++ | bsd-3-clause | 1,481 |
__version__=''' $Id'''
__doc__='''basic tests.'''
from reportlab.lib.testutils import setOutDir,makeSuiteForClasses, printLocation
setOutDir(__name__)
import unittest
def getrc(defns,depth=1):
from sys import getrefcount, _getframe
f = _getframe(depth)
G0 = f.f_globals
L = f.f_locals
if L is not G0:
LL = [L]
while 1:
f = f.f_back
G = f.f_globals
L = f.f_locals
if G is not G0 or G is L: break
LL.append(L)
L = {}
LL.reverse()
for l in LL:
L.update(l)
else:
L = L.copy()
G0 = G0.copy()
return ' '.join([str(getrefcount(eval(x,L,G0))-1) for x in defns.split()])
def checkrc(defns,rcv0):
rcv1 = getrc(defns,2)
return ' '.join(["%s %s-->%s" % (x,v,w) for x,v,w in zip(defns.split(),rcv0.split(),rcv1.split()) if v!=w])
class RlAccelTestCase(unittest.TestCase):
def testFpStr(self):
# should give siz decimal places if less than 1.
# if more, give up to seven sig figs
from _rl_accel import fp_str
assert fp_str(1,2,3)=='1 2 3'
assert fp_str(1) == '1'
assert fp_str(595.275574) == '595.2756'
assert fp_str(59.5275574) == '59.52756'
assert fp_str(5.95275574) == '5.952756'
def test_AsciiBase85Encode(self):
from _rl_accel import _AsciiBase85Encode
assert _AsciiBase85Encode('Dragan Andric')=='6ul^K@;[2RDIdd%@f~>'
def test_AsciiBase85Decode(self):
from _rl_accel import _AsciiBase85Decode
assert _AsciiBase85Decode('6ul^K@;[2RDIdd%@f~>')=='Dragan Andric'
def testEscapePDF(self):
from _rl_accel import escapePDF
assert escapePDF('(test)')=='\\(test\\)'
def test_instanceEscapePDF(self):
from _rl_accel import _instanceEscapePDF
assert _instanceEscapePDF('', '(test)')=='\\(test\\)'
def testCalcChecksum(self):
from _rl_accel import calcChecksum
assert calcChecksum('test')==1952805748
def test_instanceStringWidth(self):
from reportlab.pdfbase.pdfmetrics import registerFont, getFont, _fonts, unicode2T1
from reportlab.pdfbase.ttfonts import TTFont
ttfn = 'Vera'
t1fn = 'Times-Roman'
registerFont(TTFont(ttfn, "Vera.ttf"))
ttf = getFont(ttfn)
t1f = getFont(t1fn)
testCp1252 = 'copyright %s trademark %s registered %s ReportLab! Ol%s!' % (chr(169), chr(153),chr(174), chr(0xe9))
enc='cp1252'
senc = 'utf8'
ts = 'ABCDEF\xce\x91\xce\xb2G'
utext = 'ABCDEF\xce\x91\xce\xb2G'.decode(senc)
fontSize = 12
defns="ttfn t1fn ttf t1f testCp1252 enc senc ts utext fontSize ttf.face ttf.face.charWidths ttf.face.defaultWidth t1f.widths t1f.encName t1f.substitutionFonts _fonts"
rcv = getrc(defns)
def tfunc(f,ts,fontSize,enc):
w1 = f.stringWidth(ts,fontSize,enc)
w2 = f._py_stringWidth(ts,fontSize,enc)
assert abs(w1-w2)<1e-10,"f(%r).stringWidthU(%r,%s,%r)-->%r != f._py_stringWidth(...)-->%r" % (f,ts,fontSize,enc,w1,w2)
tfunc(t1f,testCp1252,fontSize,enc)
tfunc(t1f,ts,fontSize,senc)
tfunc(t1f,utext,fontSize,senc)
tfunc(ttf,ts,fontSize,senc)
tfunc(ttf,testCp1252,fontSize,enc)
tfunc(ttf,utext,fontSize,senc)
rcc = checkrc(defns,rcv)
assert not rcc, "rc diffs (%s)" % rcc
def test_unicode2T1(self):
from reportlab.pdfbase.pdfmetrics import _py_unicode2T1, getFont, _fonts
from _rl_accel import unicode2T1
t1fn = 'Times-Roman'
t1f = getFont(t1fn)
enc = 'cp1252'
senc = 'utf8'
testCp1252 = ('copyright %s trademark %s registered %s ReportLab! Ol%s!' % (chr(169), chr(153),chr(174), chr(0xe9))).decode(enc)
utext = 'This is the end of the \xce\x91\xce\xb2 world. This is the end of the \xce\x91\xce\xb2 world jap=\xe3\x83\x9b\xe3\x83\x86. This is the end of the \xce\x91\xce\xb2 world. This is the end of the \xce\x91\xce\xb2 world jap=\xe3\x83\x9b\xe3\x83\x86'.decode('utf8')
def tfunc(f,ts):
w1 = unicode2T1(ts,[f]+f.substitutionFonts)
w2 = _py_unicode2T1(ts,[f]+f.substitutionFonts)
assert w1==w2,"%r != %r" % (w1,w2)
defns="t1fn t1f testCp1252 enc senc utext t1f.widths t1f.encName t1f.substitutionFonts _fonts"
rcv = getrc(defns)
tfunc(t1f,testCp1252)
tfunc(t1f,utext)
rcc = checkrc(defns,rcv)
assert not rcc, "rc diffs (%s)" % rcc
def test_sameFrag(self):
from _rl_accel import _sameFrag
class ABag:
def __init__(self,**kwd):
self.__dict__.update(kwd)
def __str__(self):
V=['%s=%r' % v for v in self.__dict__.items()]
V.sort()
return 'ABag(%s)' % ','.join(V)
a=ABag(fontName='Helvetica',fontSize=12, textColor="red", rise=0, underline=0, strike=0, link="aaaa")
b=ABag(fontName='Helvetica',fontSize=12, textColor="red", rise=0, underline=0, strike=0, link="aaaa")
for name in ("fontName", "fontSize", "textColor", "rise", "underline", "strike", "link"):
old = getattr(a,name)
assert _sameFrag(a,b)==1, "_sameFrag(%s,%s)!=1" % (a,b)
assert _sameFrag(b,a)==1, "_sameFrag(%s,%s)!=1" % (b,a)
setattr(a,name,None)
assert _sameFrag(a,b)==0, "_sameFrag(%s,%s)!=0" % (a,b)
assert _sameFrag(b,a)==0, "_sameFrag(%s,%s)!=0" % (b,a)
delattr(a,name)
assert _sameFrag(a,b)==0, "_sameFrag(%s,%s)!=0" % (a,b)
assert _sameFrag(b,a)==0, "_sameFrag(%s,%s)!=0" % (b,a)
delattr(b,name)
assert _sameFrag(a,b)==1, "_sameFrag(%s,%s)!=1" % (a,b)
assert _sameFrag(b,a)==1, "_sameFrag(%s,%s)!=1" % (b,a)
setattr(a,name,old)
setattr(b,name,old)
def makeSuite():
# only run the tests if _rl_accel is present
try:
import _rl_accel
Klass = RlAccelTestCase
except:
class Klass(unittest.TestCase):
pass
return makeSuiteForClasses(Klass)
#noruntests
if __name__ == "__main__":
unittest.TextTestRunner().run(makeSuite())
printLocation()
| mattjmorrison/ReportLab | tests/test_rl_accel.py | Python | bsd-3-clause | 6,284 |
/* Return codes: 1 - ok, 0 - ignore, other - error. */
static int
arch_get_scno(struct tcb *tcp)
{
return upeek(tcp->pid, PT_ORIG_P0, &tcp->scno) < 0 ? -1 : 1;
}
| Distrotech/strace | linux/bfin/get_scno.c | C | bsd-3-clause | 163 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CONTENT_COMMON_INDEXED_DB_INDEXED_DB_MESSAGE_FILTER_H_
#define CONTENT_COMMON_INDEXED_DB_INDEXED_DB_MESSAGE_FILTER_H_
#include "ipc/ipc_channel_proxy.h"
namespace base {
class MessageLoopProxy;
} // namespace base
namespace content {
class IndexedDBDispatcher;
class IndexedDBMessageFilter : public IPC::ChannelProxy::MessageFilter {
public:
IndexedDBMessageFilter();
// IPC::Listener implementation.
virtual bool OnMessageReceived(const IPC::Message& msg) OVERRIDE;
protected:
virtual ~IndexedDBMessageFilter();
private:
void DispatchMessage(const IPC::Message& msg);
scoped_refptr<base::MessageLoopProxy> main_thread_loop_proxy_;
DISALLOW_COPY_AND_ASSIGN(IndexedDBMessageFilter);
};
} // namespace content
#endif // CONTENT_COMMON_INDEXED_DB_INDEXED_DB_DISPATCHER_H_
| zcbenz/cefode-chromium | content/common/indexed_db/indexed_db_message_filter.h | C | bsd-3-clause | 977 |
"""
Create SQL statements for QuerySets.
The code in here encapsulates all of the SQL construction so that QuerySets
themselves do not have to (and could be backed by things other than SQL
databases). The abstraction barrier only works one way: this module has to know
all about the internals of models in order to get the information it needs.
"""
import copy
import warnings
from collections import Iterator, Mapping, OrderedDict
from itertools import chain, count, product
from string import ascii_uppercase
from django.core.exceptions import FieldDoesNotExist, FieldError
from django.db import DEFAULT_DB_ALIAS, connections
from django.db.models.aggregates import Count
from django.db.models.constants import LOOKUP_SEP
from django.db.models.expressions import Col, Ref
from django.db.models.fields.related_lookups import MultiColSource
from django.db.models.query_utils import Q, PathInfo, refs_expression
from django.db.models.sql.constants import (
INNER, LOUTER, ORDER_DIR, ORDER_PATTERN, QUERY_TERMS, SINGLE,
)
from django.db.models.sql.datastructures import (
BaseTable, Empty, EmptyResultSet, Join, MultiJoin,
)
from django.db.models.sql.where import (
AND, OR, ExtraWhere, NothingNode, WhereNode,
)
from django.utils import six
from django.utils.deprecation import RemovedInDjango20Warning
from django.utils.encoding import force_text
from django.utils.tree import Node
__all__ = ['Query', 'RawQuery']
def get_field_names_from_opts(opts):
return set(chain.from_iterable(
(f.name, f.attname) if f.concrete else (f.name,)
for f in opts.get_fields()
))
class RawQuery(object):
"""
A single raw SQL query
"""
def __init__(self, sql, using, params=None, context=None):
self.params = params or ()
self.sql = sql
self.using = using
self.cursor = None
# Mirror some properties of a normal query so that
# the compiler can be used to process results.
self.low_mark, self.high_mark = 0, None # Used for offset/limit
self.extra_select = {}
self.annotation_select = {}
self.context = context or {}
def clone(self, using):
return RawQuery(self.sql, using, params=self.params, context=self.context.copy())
def get_columns(self):
if self.cursor is None:
self._execute_query()
converter = connections[self.using].introspection.column_name_converter
return [converter(column_meta[0])
for column_meta in self.cursor.description]
def __iter__(self):
# Always execute a new query for a new iterator.
# This could be optimized with a cache at the expense of RAM.
self._execute_query()
if not connections[self.using].features.can_use_chunked_reads:
# If the database can't use chunked reads we need to make sure we
# evaluate the entire query up front.
result = list(self.cursor)
else:
result = self.cursor
return iter(result)
def __repr__(self):
return "<RawQuery: %s>" % self
@property
def params_type(self):
return dict if isinstance(self.params, Mapping) else tuple
def __str__(self):
return self.sql % self.params_type(self.params)
def _execute_query(self):
connection = connections[self.using]
# Adapt parameters to the database, as much as possible considering
# that the target type isn't known. See #17755.
params_type = self.params_type
adapter = connection.ops.adapt_unknown_value
if params_type is tuple:
params = tuple(adapter(val) for val in self.params)
elif params_type is dict:
params = dict((key, adapter(val)) for key, val in six.iteritems(self.params))
else:
raise RuntimeError("Unexpected params type: %s" % params_type)
self.cursor = connection.cursor()
self.cursor.execute(self.sql, params)
class Query(object):
"""
A single SQL query.
"""
alias_prefix = 'T'
subq_aliases = frozenset([alias_prefix])
query_terms = QUERY_TERMS
compiler = 'SQLCompiler'
def __init__(self, model, where=WhereNode):
self.model = model
self.alias_refcount = {}
# alias_map is the most important data structure regarding joins.
# It's used for recording which joins exist in the query and what
# types they are. The key is the alias of the joined table (possibly
# the table name) and the value is a Join-like object (see
# sql.datastructures.Join for more information).
self.alias_map = {}
# Sometimes the query contains references to aliases in outer queries (as
# a result of split_exclude). Correct alias quoting needs to know these
# aliases too.
self.external_aliases = set()
self.table_map = {} # Maps table names to list of aliases.
self.default_cols = True
self.default_ordering = True
self.standard_ordering = True
self.used_aliases = set()
self.filter_is_sticky = False
# SQL-related attributes
# Select and related select clauses are expressions to use in the
# SELECT clause of the query.
# The select is used for cases where we want to set up the select
# clause to contain other than default fields (values(), subqueries...)
# Note that annotations go to annotations dictionary.
self.select = []
self.tables = [] # Aliases in the order they are created.
self.where = where()
self.where_class = where
# The group_by attribute can have one of the following forms:
# - None: no group by at all in the query
# - A list of expressions: group by (at least) those expressions.
# String refs are also allowed for now.
# - True: group by all select fields of the model
# See compiler.get_group_by() for details.
self.group_by = None
self.order_by = []
self.low_mark, self.high_mark = 0, None # Used for offset/limit
self.distinct = False
self.distinct_fields = []
self.select_for_update = False
self.select_for_update_nowait = False
self.select_related = False
# Arbitrary limit for select_related to prevents infinite recursion.
self.max_depth = 5
# Holds the selects defined by a call to values() or values_list()
# excluding annotation_select and extra_select.
self.values_select = []
# SQL annotation-related attributes
# The _annotations will be an OrderedDict when used. Due to the cost
# of creating OrderedDict this attribute is created lazily (in
# self.annotations property).
self._annotations = None # Maps alias -> Annotation Expression
self.annotation_select_mask = None
self._annotation_select_cache = None
# These are for extensions. The contents are more or less appended
# verbatim to the appropriate clause.
# The _extra attribute is an OrderedDict, lazily created similarly to
# .annotations
self._extra = None # Maps col_alias -> (col_sql, params).
self.extra_select_mask = None
self._extra_select_cache = None
self.extra_tables = ()
self.extra_order_by = ()
# A tuple that is a set of model field names and either True, if these
# are the fields to defer, or False if these are the only fields to
# load.
self.deferred_loading = (set(), True)
self.context = {}
@property
def extra(self):
if self._extra is None:
self._extra = OrderedDict()
return self._extra
@property
def annotations(self):
if self._annotations is None:
self._annotations = OrderedDict()
return self._annotations
@property
def aggregates(self):
warnings.warn(
"The aggregates property is deprecated. Use annotations instead.",
RemovedInDjango20Warning, stacklevel=2)
return self.annotations
def __str__(self):
"""
Returns the query as a string of SQL with the parameter values
substituted in (use sql_with_params() to see the unsubstituted string).
Parameter values won't necessarily be quoted correctly, since that is
done by the database interface at execution time.
"""
sql, params = self.sql_with_params()
return sql % params
def sql_with_params(self):
"""
Returns the query as an SQL string and the parameters that will be
substituted into the query.
"""
return self.get_compiler(DEFAULT_DB_ALIAS).as_sql()
def __deepcopy__(self, memo):
result = self.clone(memo=memo)
memo[id(self)] = result
return result
def _prepare(self):
return self
def get_compiler(self, using=None, connection=None):
if using is None and connection is None:
raise ValueError("Need either using or connection")
if using:
connection = connections[using]
return connection.ops.compiler(self.compiler)(self, connection, using)
def get_meta(self):
"""
Returns the Options instance (the model._meta) from which to start
processing. Normally, this is self.model._meta, but it can be changed
by subclasses.
"""
return self.model._meta
def clone(self, klass=None, memo=None, **kwargs):
"""
Creates a copy of the current instance. The 'kwargs' parameter can be
used by clients to update attributes after copying has taken place.
"""
obj = Empty()
obj.__class__ = klass or self.__class__
obj.model = self.model
obj.alias_refcount = self.alias_refcount.copy()
obj.alias_map = self.alias_map.copy()
obj.external_aliases = self.external_aliases.copy()
obj.table_map = self.table_map.copy()
obj.default_cols = self.default_cols
obj.default_ordering = self.default_ordering
obj.standard_ordering = self.standard_ordering
obj.select = self.select[:]
obj.tables = self.tables[:]
obj.where = self.where.clone()
obj.where_class = self.where_class
if self.group_by is None:
obj.group_by = None
elif self.group_by is True:
obj.group_by = True
else:
obj.group_by = self.group_by[:]
obj.order_by = self.order_by[:]
obj.low_mark, obj.high_mark = self.low_mark, self.high_mark
obj.distinct = self.distinct
obj.distinct_fields = self.distinct_fields[:]
obj.select_for_update = self.select_for_update
obj.select_for_update_nowait = self.select_for_update_nowait
obj.select_related = self.select_related
obj.values_select = self.values_select[:]
obj._annotations = self._annotations.copy() if self._annotations is not None else None
if self.annotation_select_mask is None:
obj.annotation_select_mask = None
else:
obj.annotation_select_mask = self.annotation_select_mask.copy()
# _annotation_select_cache cannot be copied, as doing so breaks the
# (necessary) state in which both annotations and
# _annotation_select_cache point to the same underlying objects.
# It will get re-populated in the cloned queryset the next time it's
# used.
obj._annotation_select_cache = None
obj.max_depth = self.max_depth
obj._extra = self._extra.copy() if self._extra is not None else None
if self.extra_select_mask is None:
obj.extra_select_mask = None
else:
obj.extra_select_mask = self.extra_select_mask.copy()
if self._extra_select_cache is None:
obj._extra_select_cache = None
else:
obj._extra_select_cache = self._extra_select_cache.copy()
obj.extra_tables = self.extra_tables
obj.extra_order_by = self.extra_order_by
obj.deferred_loading = copy.copy(self.deferred_loading[0]), self.deferred_loading[1]
if self.filter_is_sticky and self.used_aliases:
obj.used_aliases = self.used_aliases.copy()
else:
obj.used_aliases = set()
obj.filter_is_sticky = False
if 'alias_prefix' in self.__dict__:
obj.alias_prefix = self.alias_prefix
if 'subq_aliases' in self.__dict__:
obj.subq_aliases = self.subq_aliases.copy()
obj.__dict__.update(kwargs)
if hasattr(obj, '_setup_query'):
obj._setup_query()
obj.context = self.context.copy()
return obj
def add_context(self, key, value):
self.context[key] = value
def get_context(self, key, default=None):
return self.context.get(key, default)
def relabeled_clone(self, change_map):
clone = self.clone()
clone.change_aliases(change_map)
return clone
def rewrite_cols(self, annotation, col_cnt):
# We must make sure the inner query has the referred columns in it.
# If we are aggregating over an annotation, then Django uses Ref()
# instances to note this. However, if we are annotating over a column
# of a related model, then it might be that column isn't part of the
# SELECT clause of the inner query, and we must manually make sure
# the column is selected. An example case is:
# .aggregate(Sum('author__awards'))
# Resolving this expression results in a join to author, but there
# is no guarantee the awards column of author is in the select clause
# of the query. Thus we must manually add the column to the inner
# query.
orig_exprs = annotation.get_source_expressions()
new_exprs = []
for expr in orig_exprs:
if isinstance(expr, Ref):
# Its already a Ref to subquery (see resolve_ref() for
# details)
new_exprs.append(expr)
elif isinstance(expr, Col):
# Reference to column. Make sure the referenced column
# is selected.
col_cnt += 1
col_alias = '__col%d' % col_cnt
self.annotations[col_alias] = expr
self.append_annotation_mask([col_alias])
new_exprs.append(Ref(col_alias, expr))
else:
# Some other expression not referencing database values
# directly. Its subexpression might contain Cols.
new_expr, col_cnt = self.rewrite_cols(expr, col_cnt)
new_exprs.append(new_expr)
annotation.set_source_expressions(new_exprs)
return annotation, col_cnt
def get_aggregation(self, using, added_aggregate_names):
"""
Returns the dictionary with the values of the existing aggregations.
"""
if not self.annotation_select:
return {}
has_limit = self.low_mark != 0 or self.high_mark is not None
has_existing_annotations = any(
annotation for alias, annotation
in self.annotations.items()
if alias not in added_aggregate_names
)
# Decide if we need to use a subquery.
#
# Existing annotations would cause incorrect results as get_aggregation()
# must produce just one result and thus must not use GROUP BY. But we
# aren't smart enough to remove the existing annotations from the
# query, so those would force us to use GROUP BY.
#
# If the query has limit or distinct, then those operations must be
# done in a subquery so that we are aggregating on the limit and/or
# distinct results instead of applying the distinct and limit after the
# aggregation.
if (isinstance(self.group_by, list) or has_limit or has_existing_annotations or
self.distinct):
from django.db.models.sql.subqueries import AggregateQuery
outer_query = AggregateQuery(self.model)
inner_query = self.clone()
inner_query.select_for_update = False
inner_query.select_related = False
if not has_limit and not self.distinct_fields:
# Queries with distinct_fields need ordering and when a limit
# is applied we must take the slice from the ordered query.
# Otherwise no need for ordering.
inner_query.clear_ordering(True)
if not inner_query.distinct:
# If the inner query uses default select and it has some
# aggregate annotations, then we must make sure the inner
# query is grouped by the main model's primary key. However,
# clearing the select clause can alter results if distinct is
# used.
if inner_query.default_cols and has_existing_annotations:
inner_query.group_by = [self.model._meta.pk.get_col(inner_query.get_initial_alias())]
inner_query.default_cols = False
relabels = {t: 'subquery' for t in inner_query.tables}
relabels[None] = 'subquery'
# Remove any aggregates marked for reduction from the subquery
# and move them to the outer AggregateQuery.
col_cnt = 0
for alias, expression in list(inner_query.annotation_select.items()):
if expression.is_summary:
expression, col_cnt = inner_query.rewrite_cols(expression, col_cnt)
outer_query.annotations[alias] = expression.relabeled_clone(relabels)
del inner_query.annotations[alias]
# Make sure the annotation_select wont use cached results.
inner_query.set_annotation_mask(inner_query.annotation_select_mask)
if inner_query.select == [] and not inner_query.default_cols and not inner_query.annotation_select_mask:
# In case of Model.objects[0:3].count(), there would be no
# field selected in the inner query, yet we must use a subquery.
# So, make sure at least one field is selected.
inner_query.select = [self.model._meta.pk.get_col(inner_query.get_initial_alias())]
try:
outer_query.add_subquery(inner_query, using)
except EmptyResultSet:
return {
alias: None
for alias in outer_query.annotation_select
}
else:
outer_query = self
self.select = []
self.default_cols = False
self._extra = {}
outer_query.clear_ordering(True)
outer_query.clear_limits()
outer_query.select_for_update = False
outer_query.select_related = False
compiler = outer_query.get_compiler(using)
result = compiler.execute_sql(SINGLE)
if result is None:
result = [None for q in outer_query.annotation_select.items()]
converters = compiler.get_converters(outer_query.annotation_select.values())
result = compiler.apply_converters(result, converters)
return {
alias: val
for (alias, annotation), val
in zip(outer_query.annotation_select.items(), result)
}
def get_count(self, using):
"""
Performs a COUNT() query using the current filter constraints.
"""
obj = self.clone()
obj.add_annotation(Count('*'), alias='__count', is_summary=True)
number = obj.get_aggregation(using, ['__count'])['__count']
if number is None:
number = 0
return number
def has_filters(self):
return self.where
def has_results(self, using):
q = self.clone()
if not q.distinct:
if q.group_by is True:
q.add_fields((f.attname for f in self.model._meta.concrete_fields), False)
q.set_group_by()
q.clear_select_clause()
q.clear_ordering(True)
q.set_limits(high=1)
compiler = q.get_compiler(using=using)
return compiler.has_results()
def combine(self, rhs, connector):
"""
Merge the 'rhs' query into the current one (with any 'rhs' effects
being applied *after* (that is, "to the right of") anything in the
current query. 'rhs' is not modified during a call to this function.
The 'connector' parameter describes how to connect filters from the
'rhs' query.
"""
assert self.model == rhs.model, \
"Cannot combine queries on two different base models."
assert self.can_filter(), \
"Cannot combine queries once a slice has been taken."
assert self.distinct == rhs.distinct, \
"Cannot combine a unique query with a non-unique query."
assert self.distinct_fields == rhs.distinct_fields, \
"Cannot combine queries with different distinct fields."
# Work out how to relabel the rhs aliases, if necessary.
change_map = {}
conjunction = (connector == AND)
# Determine which existing joins can be reused. When combining the
# query with AND we must recreate all joins for m2m filters. When
# combining with OR we can reuse joins. The reason is that in AND
# case a single row can't fulfill a condition like:
# revrel__col=1 & revrel__col=2
# But, there might be two different related rows matching this
# condition. In OR case a single True is enough, so single row is
# enough, too.
#
# Note that we will be creating duplicate joins for non-m2m joins in
# the AND case. The results will be correct but this creates too many
# joins. This is something that could be fixed later on.
reuse = set() if conjunction else set(self.tables)
# Base table must be present in the query - this is the same
# table on both sides.
self.get_initial_alias()
joinpromoter = JoinPromoter(connector, 2, False)
joinpromoter.add_votes(
j for j in self.alias_map if self.alias_map[j].join_type == INNER)
rhs_votes = set()
# Now, add the joins from rhs query into the new query (skipping base
# table).
for alias in rhs.tables[1:]:
join = rhs.alias_map[alias]
# If the left side of the join was already relabeled, use the
# updated alias.
join = join.relabeled_clone(change_map)
new_alias = self.join(join, reuse=reuse)
if join.join_type == INNER:
rhs_votes.add(new_alias)
# We can't reuse the same join again in the query. If we have two
# distinct joins for the same connection in rhs query, then the
# combined query must have two joins, too.
reuse.discard(new_alias)
change_map[alias] = new_alias
if not rhs.alias_refcount[alias]:
# The alias was unused in the rhs query. Unref it so that it
# will be unused in the new query, too. We have to add and
# unref the alias so that join promotion has information of
# the join type for the unused alias.
self.unref_alias(new_alias)
joinpromoter.add_votes(rhs_votes)
joinpromoter.update_join_types(self)
# Now relabel a copy of the rhs where-clause and add it to the current
# one.
w = rhs.where.clone()
w.relabel_aliases(change_map)
self.where.add(w, connector)
# Selection columns and extra extensions are those provided by 'rhs'.
self.select = []
for col in rhs.select:
self.add_select(col.relabeled_clone(change_map))
if connector == OR:
# It would be nice to be able to handle this, but the queries don't
# really make sense (or return consistent value sets). Not worth
# the extra complexity when you can write a real query instead.
if self._extra and rhs._extra:
raise ValueError("When merging querysets using 'or', you "
"cannot have extra(select=...) on both sides.")
self.extra.update(rhs.extra)
extra_select_mask = set()
if self.extra_select_mask is not None:
extra_select_mask.update(self.extra_select_mask)
if rhs.extra_select_mask is not None:
extra_select_mask.update(rhs.extra_select_mask)
if extra_select_mask:
self.set_extra_mask(extra_select_mask)
self.extra_tables += rhs.extra_tables
# Ordering uses the 'rhs' ordering, unless it has none, in which case
# the current ordering is used.
self.order_by = rhs.order_by[:] if rhs.order_by else self.order_by
self.extra_order_by = rhs.extra_order_by or self.extra_order_by
def deferred_to_data(self, target, callback):
"""
Converts the self.deferred_loading data structure to an alternate data
structure, describing the field that *will* be loaded. This is used to
compute the columns to select from the database and also by the
QuerySet class to work out which fields are being initialized on each
model. Models that have all their fields included aren't mentioned in
the result, only those that have field restrictions in place.
The "target" parameter is the instance that is populated (in place).
The "callback" is a function that is called whenever a (model, field)
pair need to be added to "target". It accepts three parameters:
"target", and the model and list of fields being added for that model.
"""
field_names, defer = self.deferred_loading
if not field_names:
return
orig_opts = self.get_meta()
seen = {}
must_include = {orig_opts.concrete_model: {orig_opts.pk}}
for field_name in field_names:
parts = field_name.split(LOOKUP_SEP)
cur_model = self.model._meta.concrete_model
opts = orig_opts
for name in parts[:-1]:
old_model = cur_model
source = opts.get_field(name)
if is_reverse_o2o(source):
cur_model = source.related_model
else:
cur_model = source.remote_field.model
opts = cur_model._meta
# Even if we're "just passing through" this model, we must add
# both the current model's pk and the related reference field
# (if it's not a reverse relation) to the things we select.
if not is_reverse_o2o(source):
must_include[old_model].add(source)
add_to_dict(must_include, cur_model, opts.pk)
field = opts.get_field(parts[-1])
is_reverse_object = field.auto_created and not field.concrete
model = field.related_model if is_reverse_object else field.model
model = model._meta.concrete_model
if model == opts.model:
model = cur_model
if not is_reverse_o2o(field):
add_to_dict(seen, model, field)
if defer:
# We need to load all fields for each model, except those that
# appear in "seen" (for all models that appear in "seen"). The only
# slight complexity here is handling fields that exist on parent
# models.
workset = {}
for model, values in six.iteritems(seen):
for field in model._meta.fields:
if field in values:
continue
m = field.model._meta.concrete_model
add_to_dict(workset, m, field)
for model, values in six.iteritems(must_include):
# If we haven't included a model in workset, we don't add the
# corresponding must_include fields for that model, since an
# empty set means "include all fields". That's why there's no
# "else" branch here.
if model in workset:
workset[model].update(values)
for model, values in six.iteritems(workset):
callback(target, model, values)
else:
for model, values in six.iteritems(must_include):
if model in seen:
seen[model].update(values)
else:
# As we've passed through this model, but not explicitly
# included any fields, we have to make sure it's mentioned
# so that only the "must include" fields are pulled in.
seen[model] = values
# Now ensure that every model in the inheritance chain is mentioned
# in the parent list. Again, it must be mentioned to ensure that
# only "must include" fields are pulled in.
for model in orig_opts.get_parent_list():
if model not in seen:
seen[model] = set()
for model, values in six.iteritems(seen):
callback(target, model, values)
def table_alias(self, table_name, create=False):
"""
Returns a table alias for the given table_name and whether this is a
new alias or not.
If 'create' is true, a new alias is always created. Otherwise, the
most recently created alias for the table (if one exists) is reused.
"""
alias_list = self.table_map.get(table_name)
if not create and alias_list:
alias = alias_list[0]
self.alias_refcount[alias] += 1
return alias, False
# Create a new alias for this table.
if alias_list:
alias = '%s%d' % (self.alias_prefix, len(self.alias_map) + 1)
alias_list.append(alias)
else:
# The first occurrence of a table uses the table name directly.
alias = table_name
self.table_map[alias] = [alias]
self.alias_refcount[alias] = 1
self.tables.append(alias)
return alias, True
def ref_alias(self, alias):
""" Increases the reference count for this alias. """
self.alias_refcount[alias] += 1
def unref_alias(self, alias, amount=1):
""" Decreases the reference count for this alias. """
self.alias_refcount[alias] -= amount
def promote_joins(self, aliases):
"""
Promotes recursively the join type of given aliases and its children to
an outer join. If 'unconditional' is False, the join is only promoted if
it is nullable or the parent join is an outer join.
The children promotion is done to avoid join chains that contain a LOUTER
b INNER c. So, if we have currently a INNER b INNER c and a->b is promoted,
then we must also promote b->c automatically, or otherwise the promotion
of a->b doesn't actually change anything in the query results.
"""
aliases = list(aliases)
while aliases:
alias = aliases.pop(0)
if self.alias_map[alias].join_type is None:
# This is the base table (first FROM entry) - this table
# isn't really joined at all in the query, so we should not
# alter its join type.
continue
# Only the first alias (skipped above) should have None join_type
assert self.alias_map[alias].join_type is not None
parent_alias = self.alias_map[alias].parent_alias
parent_louter = (
parent_alias
and self.alias_map[parent_alias].join_type == LOUTER)
already_louter = self.alias_map[alias].join_type == LOUTER
if ((self.alias_map[alias].nullable or parent_louter) and
not already_louter):
self.alias_map[alias] = self.alias_map[alias].promote()
# Join type of 'alias' changed, so re-examine all aliases that
# refer to this one.
aliases.extend(
join for join in self.alias_map.keys()
if (self.alias_map[join].parent_alias == alias
and join not in aliases))
def demote_joins(self, aliases):
"""
Change join type from LOUTER to INNER for all joins in aliases.
Similarly to promote_joins(), this method must ensure no join chains
containing first an outer, then an inner join are generated. If we
are demoting b->c join in chain a LOUTER b LOUTER c then we must
demote a->b automatically, or otherwise the demotion of b->c doesn't
actually change anything in the query results. .
"""
aliases = list(aliases)
while aliases:
alias = aliases.pop(0)
if self.alias_map[alias].join_type == LOUTER:
self.alias_map[alias] = self.alias_map[alias].demote()
parent_alias = self.alias_map[alias].parent_alias
if self.alias_map[parent_alias].join_type == INNER:
aliases.append(parent_alias)
def reset_refcounts(self, to_counts):
"""
This method will reset reference counts for aliases so that they match
the value passed in :param to_counts:.
"""
for alias, cur_refcount in self.alias_refcount.copy().items():
unref_amount = cur_refcount - to_counts.get(alias, 0)
self.unref_alias(alias, unref_amount)
def change_aliases(self, change_map):
"""
Changes the aliases in change_map (which maps old-alias -> new-alias),
relabelling any references to them in select columns and the where
clause.
"""
assert set(change_map.keys()).intersection(set(change_map.values())) == set()
def relabel_column(col):
if isinstance(col, (list, tuple)):
old_alias = col[0]
return (change_map.get(old_alias, old_alias), col[1])
else:
return col.relabeled_clone(change_map)
# 1. Update references in "select" (normal columns plus aliases),
# "group by" and "where".
self.where.relabel_aliases(change_map)
if isinstance(self.group_by, list):
self.group_by = [relabel_column(col) for col in self.group_by]
self.select = [col.relabeled_clone(change_map) for col in self.select]
if self._annotations:
self._annotations = OrderedDict(
(key, relabel_column(col)) for key, col in self._annotations.items())
# 2. Rename the alias in the internal table/alias datastructures.
for old_alias, new_alias in six.iteritems(change_map):
if old_alias not in self.alias_map:
continue
alias_data = self.alias_map[old_alias].relabeled_clone(change_map)
self.alias_map[new_alias] = alias_data
self.alias_refcount[new_alias] = self.alias_refcount[old_alias]
del self.alias_refcount[old_alias]
del self.alias_map[old_alias]
table_aliases = self.table_map[alias_data.table_name]
for pos, alias in enumerate(table_aliases):
if alias == old_alias:
table_aliases[pos] = new_alias
break
for pos, alias in enumerate(self.tables):
if alias == old_alias:
self.tables[pos] = new_alias
break
self.external_aliases = {change_map.get(alias, alias)
for alias in self.external_aliases}
def bump_prefix(self, outer_query):
"""
Changes the alias prefix to the next letter in the alphabet in a way
that the outer query's aliases and this query's aliases will not
conflict. Even tables that previously had no alias will get an alias
after this call.
"""
def prefix_gen():
"""
Generates a sequence of characters in alphabetical order:
-> 'A', 'B', 'C', ...
When the alphabet is finished, the sequence will continue with the
Cartesian product:
-> 'AA', 'AB', 'AC', ...
"""
alphabet = ascii_uppercase
prefix = chr(ord(self.alias_prefix) + 1)
yield prefix
for n in count(1):
seq = alphabet[alphabet.index(prefix):] if prefix else alphabet
for s in product(seq, repeat=n):
yield ''.join(s)
prefix = None
if self.alias_prefix != outer_query.alias_prefix:
# No clashes between self and outer query should be possible.
return
local_recursion_limit = 127 # explicitly avoid infinite loop
for pos, prefix in enumerate(prefix_gen()):
if prefix not in self.subq_aliases:
self.alias_prefix = prefix
break
if pos > local_recursion_limit:
raise RuntimeError(
'Maximum recursion depth exceeded: too many subqueries.'
)
self.subq_aliases = self.subq_aliases.union([self.alias_prefix])
outer_query.subq_aliases = outer_query.subq_aliases.union(self.subq_aliases)
change_map = OrderedDict()
for pos, alias in enumerate(self.tables):
new_alias = '%s%d' % (self.alias_prefix, pos)
change_map[alias] = new_alias
self.tables[pos] = new_alias
self.change_aliases(change_map)
def get_initial_alias(self):
"""
Returns the first alias for this query, after increasing its reference
count.
"""
if self.tables:
alias = self.tables[0]
self.ref_alias(alias)
else:
alias = self.join(BaseTable(self.get_meta().db_table, None))
return alias
def count_active_tables(self):
"""
Returns the number of tables in this query with a non-zero reference
count. Note that after execution, the reference counts are zeroed, so
tables added in compiler will not be seen by this method.
"""
return len([1 for count in self.alias_refcount.values() if count])
def join(self, join, reuse=None):
"""
Returns an alias for the join in 'connection', either reusing an
existing alias for that join or creating a new one. 'connection' is a
tuple (lhs, table, join_cols) where 'lhs' is either an existing
table alias or a table name. 'join_cols' is a tuple of tuples containing
columns to join on ((l_id1, r_id1), (l_id2, r_id2)). The join corresponds
to the SQL equivalent of::
lhs.l_id1 = table.r_id1 AND lhs.l_id2 = table.r_id2
The 'reuse' parameter can be either None which means all joins
(matching the connection) are reusable, or it can be a set containing
the aliases that can be reused.
A join is always created as LOUTER if the lhs alias is LOUTER to make
sure we do not generate chains like t1 LOUTER t2 INNER t3. All new
joins are created as LOUTER if nullable is True.
If 'nullable' is True, the join can potentially involve NULL values and
is a candidate for promotion (to "left outer") when combining querysets.
The 'join_field' is the field we are joining along (if any).
"""
reuse = [a for a, j in self.alias_map.items()
if (reuse is None or a in reuse) and j == join]
if reuse:
self.ref_alias(reuse[0])
return reuse[0]
# No reuse is possible, so we need a new alias.
alias, _ = self.table_alias(join.table_name, create=True)
if join.join_type:
if self.alias_map[join.parent_alias].join_type == LOUTER or join.nullable:
join_type = LOUTER
else:
join_type = INNER
join.join_type = join_type
join.table_alias = alias
self.alias_map[alias] = join
return alias
def join_parent_model(self, opts, model, alias, seen):
"""
Makes sure the given 'model' is joined in the query. If 'model' isn't
a parent of 'opts' or if it is None this method is a no-op.
The 'alias' is the root alias for starting the join, 'seen' is a dict
of model -> alias of existing joins. It must also contain a mapping
of None -> some alias. This will be returned in the no-op case.
"""
if model in seen:
return seen[model]
chain = opts.get_base_chain(model)
if chain is None:
return alias
curr_opts = opts
for int_model in chain:
if int_model in seen:
curr_opts = int_model._meta
alias = seen[int_model]
continue
# Proxy model have elements in base chain
# with no parents, assign the new options
# object and skip to the next base in that
# case
if not curr_opts.parents[int_model]:
curr_opts = int_model._meta
continue
link_field = curr_opts.get_ancestor_link(int_model)
_, _, _, joins, _ = self.setup_joins(
[link_field.name], curr_opts, alias)
curr_opts = int_model._meta
alias = seen[int_model] = joins[-1]
return alias or seen[None]
def add_aggregate(self, aggregate, model, alias, is_summary):
warnings.warn(
"add_aggregate() is deprecated. Use add_annotation() instead.",
RemovedInDjango20Warning, stacklevel=2)
self.add_annotation(aggregate, alias, is_summary)
def add_annotation(self, annotation, alias, is_summary=False):
"""
Adds a single annotation expression to the Query
"""
annotation = annotation.resolve_expression(self, allow_joins=True, reuse=None,
summarize=is_summary)
self.append_annotation_mask([alias])
self.annotations[alias] = annotation
def prepare_lookup_value(self, value, lookups, can_reuse, allow_joins=True):
# Default lookup if none given is exact.
used_joins = []
if len(lookups) == 0:
lookups = ['exact']
# Interpret '__exact=None' as the sql 'is NULL'; otherwise, reject all
# uses of None as a query value.
if value is None:
if lookups[-1] not in ('exact', 'iexact'):
raise ValueError("Cannot use None as a query value")
lookups[-1] = 'isnull'
value = True
elif hasattr(value, 'resolve_expression'):
pre_joins = self.alias_refcount.copy()
value = value.resolve_expression(self, reuse=can_reuse, allow_joins=allow_joins)
used_joins = [k for k, v in self.alias_refcount.items() if v > pre_joins.get(k, 0)]
# Subqueries need to use a different set of aliases than the
# outer query. Call bump_prefix to change aliases of the inner
# query (the value).
if hasattr(value, 'query') and hasattr(value.query, 'bump_prefix'):
value = value._clone()
value.query.bump_prefix(self)
if hasattr(value, 'bump_prefix'):
value = value.clone()
value.bump_prefix(self)
# For Oracle '' is equivalent to null. The check needs to be done
# at this stage because join promotion can't be done at compiler
# stage. Using DEFAULT_DB_ALIAS isn't nice, but it is the best we
# can do here. Similar thing is done in is_nullable(), too.
if (connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls and
lookups[-1] == 'exact' and value == ''):
value = True
lookups[-1] = 'isnull'
return value, lookups, used_joins
def solve_lookup_type(self, lookup):
"""
Solve the lookup type from the lookup (eg: 'foobar__id__icontains')
"""
lookup_splitted = lookup.split(LOOKUP_SEP)
if self._annotations:
aggregate, aggregate_lookups = refs_expression(lookup_splitted, self.annotations)
if aggregate:
return aggregate_lookups, (), aggregate
_, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())
field_parts = lookup_splitted[0:len(lookup_splitted) - len(lookup_parts)]
if len(lookup_parts) == 0:
lookup_parts = ['exact']
elif len(lookup_parts) > 1:
if not field_parts:
raise FieldError(
'Invalid lookup "%s" for model %s".' %
(lookup, self.get_meta().model.__name__))
return lookup_parts, field_parts, False
def check_query_object_type(self, value, opts):
"""
Checks whether the object passed while querying is of the correct type.
If not, it raises a ValueError specifying the wrong object.
"""
if hasattr(value, '_meta'):
if not (value._meta.concrete_model == opts.concrete_model
or opts.concrete_model in value._meta.get_parent_list()
or value._meta.concrete_model in opts.get_parent_list()):
raise ValueError(
'Cannot query "%s": Must be "%s" instance.' %
(value, opts.object_name))
def check_related_objects(self, field, value, opts):
"""
Checks the type of object passed to query relations.
"""
if field.is_relation:
# QuerySets implement is_compatible_query_object_type() to
# determine compatibility with the given field.
if hasattr(value, 'is_compatible_query_object_type'):
if not value.is_compatible_query_object_type(opts):
raise ValueError(
'Cannot use QuerySet for "%s": Use a QuerySet for "%s".' %
(value.model._meta.model_name, opts.object_name)
)
elif hasattr(value, '_meta'):
self.check_query_object_type(value, opts)
elif hasattr(value, '__iter__'):
for v in value:
self.check_query_object_type(v, opts)
def build_lookup(self, lookups, lhs, rhs):
"""
Tries to extract transforms and lookup from given lhs.
The lhs value is something that works like SQLExpression.
The rhs value is what the lookup is going to compare against.
The lookups is a list of names to extract using get_lookup()
and get_transform().
"""
lookups = lookups[:]
while lookups:
name = lookups[0]
# If there is just one part left, try first get_lookup() so
# that if the lhs supports both transform and lookup for the
# name, then lookup will be picked.
if len(lookups) == 1:
final_lookup = lhs.get_lookup(name)
if not final_lookup:
# We didn't find a lookup. We are going to interpret
# the name as transform, and do an Exact lookup against
# it.
lhs = self.try_transform(lhs, name, lookups)
final_lookup = lhs.get_lookup('exact')
return final_lookup(lhs, rhs)
lhs = self.try_transform(lhs, name, lookups)
lookups = lookups[1:]
def try_transform(self, lhs, name, rest_of_lookups):
"""
Helper method for build_lookup. Tries to fetch and initialize
a transform for name parameter from lhs.
"""
next = lhs.get_transform(name)
if next:
return next(lhs, rest_of_lookups)
else:
raise FieldError(
"Unsupported lookup '%s' for %s or join on the field not "
"permitted." %
(name, lhs.output_field.__class__.__name__))
def build_filter(self, filter_expr, branch_negated=False, current_negated=False,
can_reuse=None, connector=AND, allow_joins=True, split_subq=True):
"""
Builds a WhereNode for a single filter clause, but doesn't add it
to this Query. Query.add_q() will then add this filter to the where
Node.
The 'branch_negated' tells us if the current branch contains any
negations. This will be used to determine if subqueries are needed.
The 'current_negated' is used to determine if the current filter is
negated or not and this will be used to determine if IS NULL filtering
is needed.
The difference between current_netageted and branch_negated is that
branch_negated is set on first negation, but current_negated is
flipped for each negation.
Note that add_filter will not do any negating itself, that is done
upper in the code by add_q().
The 'can_reuse' is a set of reusable joins for multijoins.
The method will create a filter clause that can be added to the current
query. However, if the filter isn't added to the query then the caller
is responsible for unreffing the joins used.
"""
if isinstance(filter_expr, dict):
raise FieldError("Cannot parse keyword query as dict")
arg, value = filter_expr
if not arg:
raise FieldError("Cannot parse keyword query %r" % arg)
lookups, parts, reffed_aggregate = self.solve_lookup_type(arg)
if not allow_joins and len(parts) > 1:
raise FieldError("Joined field references are not permitted in this query")
# Work out the lookup type and remove it from the end of 'parts',
# if necessary.
value, lookups, used_joins = self.prepare_lookup_value(value, lookups, can_reuse, allow_joins)
clause = self.where_class()
if reffed_aggregate:
condition = self.build_lookup(lookups, reffed_aggregate, value)
clause.add(condition, AND)
return clause, []
opts = self.get_meta()
alias = self.get_initial_alias()
allow_many = not branch_negated or not split_subq
try:
field, sources, opts, join_list, path = self.setup_joins(
parts, opts, alias, can_reuse=can_reuse, allow_many=allow_many)
# Prevent iterator from being consumed by check_related_objects()
if isinstance(value, Iterator):
value = list(value)
self.check_related_objects(field, value, opts)
# split_exclude() needs to know which joins were generated for the
# lookup parts
self._lookup_joins = join_list
except MultiJoin as e:
return self.split_exclude(filter_expr, LOOKUP_SEP.join(parts[:e.level]),
can_reuse, e.names_with_path)
if can_reuse is not None:
can_reuse.update(join_list)
used_joins = set(used_joins).union(set(join_list))
targets, alias, join_list = self.trim_joins(sources, join_list, path)
if field.is_relation:
# No support for transforms for relational fields
assert len(lookups) == 1
lookup_class = field.get_lookup(lookups[0])
if len(targets) == 1:
lhs = targets[0].get_col(alias, field)
else:
lhs = MultiColSource(alias, targets, sources, field)
condition = lookup_class(lhs, value)
lookup_type = lookup_class.lookup_name
else:
col = targets[0].get_col(alias, field)
condition = self.build_lookup(lookups, col, value)
lookup_type = condition.lookup_name
clause.add(condition, AND)
require_outer = lookup_type == 'isnull' and value is True and not current_negated
if current_negated and (lookup_type != 'isnull' or value is False):
require_outer = True
if (lookup_type != 'isnull' and (
self.is_nullable(targets[0]) or
self.alias_map[join_list[-1]].join_type == LOUTER)):
# The condition added here will be SQL like this:
# NOT (col IS NOT NULL), where the first NOT is added in
# upper layers of code. The reason for addition is that if col
# is null, then col != someval will result in SQL "unknown"
# which isn't the same as in Python. The Python None handling
# is wanted, and it can be gotten by
# (col IS NULL OR col != someval)
# <=>
# NOT (col IS NOT NULL AND col = someval).
lookup_class = targets[0].get_lookup('isnull')
clause.add(lookup_class(targets[0].get_col(alias, sources[0]), False), AND)
return clause, used_joins if not require_outer else ()
def add_filter(self, filter_clause):
self.add_q(Q(**{filter_clause[0]: filter_clause[1]}))
def add_q(self, q_object):
"""
A preprocessor for the internal _add_q(). Responsible for doing final
join promotion.
"""
# For join promotion this case is doing an AND for the added q_object
# and existing conditions. So, any existing inner join forces the join
# type to remain inner. Existing outer joins can however be demoted.
# (Consider case where rel_a is LOUTER and rel_a__col=1 is added - if
# rel_a doesn't produce any rows, then the whole condition must fail.
# So, demotion is OK.
existing_inner = set(
(a for a in self.alias_map if self.alias_map[a].join_type == INNER))
clause, _ = self._add_q(q_object, self.used_aliases)
if clause:
self.where.add(clause, AND)
self.demote_joins(existing_inner)
def _add_q(self, q_object, used_aliases, branch_negated=False,
current_negated=False, allow_joins=True, split_subq=True):
"""
Adds a Q-object to the current filter.
"""
connector = q_object.connector
current_negated = current_negated ^ q_object.negated
branch_negated = branch_negated or q_object.negated
target_clause = self.where_class(connector=connector,
negated=q_object.negated)
joinpromoter = JoinPromoter(q_object.connector, len(q_object.children), current_negated)
for child in q_object.children:
if isinstance(child, Node):
child_clause, needed_inner = self._add_q(
child, used_aliases, branch_negated,
current_negated, allow_joins, split_subq)
joinpromoter.add_votes(needed_inner)
else:
child_clause, needed_inner = self.build_filter(
child, can_reuse=used_aliases, branch_negated=branch_negated,
current_negated=current_negated, connector=connector,
allow_joins=allow_joins, split_subq=split_subq,
)
joinpromoter.add_votes(needed_inner)
if child_clause:
target_clause.add(child_clause, connector)
needed_inner = joinpromoter.update_join_types(self)
return target_clause, needed_inner
def names_to_path(self, names, opts, allow_many=True, fail_on_missing=False):
"""
Walks the list of names and turns them into PathInfo tuples. Note that
a single name in 'names' can generate multiple PathInfos (m2m for
example).
'names' is the path of names to travel, 'opts' is the model Options we
start the name resolving from, 'allow_many' is as for setup_joins().
If fail_on_missing is set to True, then a name that can't be resolved
will generate a FieldError.
Returns a list of PathInfo tuples. In addition returns the final field
(the last used join field), and target (which is a field guaranteed to
contain the same value as the final field). Finally, the method returns
those names that weren't found (which are likely transforms and the
final lookup).
"""
path, names_with_path = [], []
for pos, name in enumerate(names):
cur_names_with_path = (name, [])
if name == 'pk':
name = opts.pk.name
try:
field = opts.get_field(name)
# Fields that contain one-to-many relations with a generic
# model (like a GenericForeignKey) cannot generate reverse
# relations and therefore cannot be used for reverse querying.
if field.is_relation and not field.related_model:
raise FieldError(
"Field %r does not generate an automatic reverse "
"relation and therefore cannot be used for reverse "
"querying. If it is a GenericForeignKey, consider "
"adding a GenericRelation." % name
)
model = field.model._meta.concrete_model
except FieldDoesNotExist:
# We didn't find the current field, so move position back
# one step.
pos -= 1
if pos == -1 or fail_on_missing:
field_names = list(get_field_names_from_opts(opts))
available = sorted(field_names + list(self.annotation_select))
raise FieldError("Cannot resolve keyword %r into field. "
"Choices are: %s" % (name, ", ".join(available)))
break
# Check if we need any joins for concrete inheritance cases (the
# field lives in parent, but we are currently in one of its
# children)
if model is not opts.model:
# The field lives on a base class of the current model.
# Skip the chain of proxy to the concrete proxied model
proxied_model = opts.concrete_model
for int_model in opts.get_base_chain(model):
if int_model is proxied_model:
opts = int_model._meta
else:
final_field = opts.parents[int_model]
targets = (final_field.remote_field.get_related_field(),)
opts = int_model._meta
path.append(PathInfo(final_field.model._meta, opts, targets, final_field, False, True))
cur_names_with_path[1].append(
PathInfo(final_field.model._meta, opts, targets, final_field, False, True)
)
if hasattr(field, 'get_path_info'):
pathinfos = field.get_path_info()
if not allow_many:
for inner_pos, p in enumerate(pathinfos):
if p.m2m:
cur_names_with_path[1].extend(pathinfos[0:inner_pos + 1])
names_with_path.append(cur_names_with_path)
raise MultiJoin(pos + 1, names_with_path)
last = pathinfos[-1]
path.extend(pathinfos)
final_field = last.join_field
opts = last.to_opts
targets = last.target_fields
cur_names_with_path[1].extend(pathinfos)
names_with_path.append(cur_names_with_path)
else:
# Local non-relational field.
final_field = field
targets = (field,)
if fail_on_missing and pos + 1 != len(names):
raise FieldError(
"Cannot resolve keyword %r into field. Join on '%s'"
" not permitted." % (names[pos + 1], name))
break
return path, final_field, targets, names[pos + 1:]
def setup_joins(self, names, opts, alias, can_reuse=None, allow_many=True):
"""
Compute the necessary table joins for the passage through the fields
given in 'names'. 'opts' is the Options class for the current model
(which gives the table we are starting from), 'alias' is the alias for
the table to start the joining from.
The 'can_reuse' defines the reverse foreign key joins we can reuse. It
can be None in which case all joins are reusable or a set of aliases
that can be reused. Note that non-reverse foreign keys are always
reusable when using setup_joins().
If 'allow_many' is False, then any reverse foreign key seen will
generate a MultiJoin exception.
Returns the final field involved in the joins, the target field (used
for any 'where' constraint), the final 'opts' value, the joins and the
field path travelled to generate the joins.
The target field is the field containing the concrete value. Final
field can be something different, for example foreign key pointing to
that value. Final field is needed for example in some value
conversions (convert 'obj' in fk__id=obj to pk val using the foreign
key field for example).
"""
joins = [alias]
# First, generate the path for the names
path, final_field, targets, rest = self.names_to_path(
names, opts, allow_many, fail_on_missing=True)
# Then, add the path to the query's joins. Note that we can't trim
# joins at this stage - we will need the information about join type
# of the trimmed joins.
for join in path:
opts = join.to_opts
if join.direct:
nullable = self.is_nullable(join.join_field)
else:
nullable = True
connection = Join(opts.db_table, alias, None, INNER, join.join_field, nullable)
reuse = can_reuse if join.m2m else None
alias = self.join(connection, reuse=reuse)
joins.append(alias)
return final_field, targets, opts, joins, path
def trim_joins(self, targets, joins, path):
"""
The 'target' parameter is the final field being joined to, 'joins'
is the full list of join aliases. The 'path' contain the PathInfos
used to create the joins.
Returns the final target field and table alias and the new active
joins.
We will always trim any direct join if we have the target column
available already in the previous table. Reverse joins can't be
trimmed as we don't know if there is anything on the other side of
the join.
"""
joins = joins[:]
for pos, info in enumerate(reversed(path)):
if len(joins) == 1 or not info.direct:
break
join_targets = set(t.column for t in info.join_field.foreign_related_fields)
cur_targets = set(t.column for t in targets)
if not cur_targets.issubset(join_targets):
break
targets = tuple(r[0] for r in info.join_field.related_fields if r[1].column in cur_targets)
self.unref_alias(joins.pop())
return targets, joins[-1], joins
def resolve_ref(self, name, allow_joins=True, reuse=None, summarize=False):
if not allow_joins and LOOKUP_SEP in name:
raise FieldError("Joined field references are not permitted in this query")
if name in self.annotations:
if summarize:
# Summarize currently means we are doing an aggregate() query
# which is executed as a wrapped subquery if any of the
# aggregate() elements reference an existing annotation. In
# that case we need to return a Ref to the subquery's annotation.
return Ref(name, self.annotation_select[name])
else:
return self.annotation_select[name]
else:
field_list = name.split(LOOKUP_SEP)
field, sources, opts, join_list, path = self.setup_joins(
field_list, self.get_meta(),
self.get_initial_alias(), reuse)
targets, _, join_list = self.trim_joins(sources, join_list, path)
if len(targets) > 1:
raise FieldError("Referencing multicolumn fields with F() objects "
"isn't supported")
if reuse is not None:
reuse.update(join_list)
col = targets[0].get_col(join_list[-1], sources[0])
return col
def split_exclude(self, filter_expr, prefix, can_reuse, names_with_path):
"""
When doing an exclude against any kind of N-to-many relation, we need
to use a subquery. This method constructs the nested query, given the
original exclude filter (filter_expr) and the portion up to the first
N-to-many relation field.
As an example we could have original filter ~Q(child__name='foo').
We would get here with filter_expr = child__name, prefix = child and
can_reuse is a set of joins usable for filters in the original query.
We will turn this into equivalent of:
WHERE NOT (pk IN (SELECT parent_id FROM thetable
WHERE name = 'foo' AND parent_id IS NOT NULL))
It might be worth it to consider using WHERE NOT EXISTS as that has
saner null handling, and is easier for the backend's optimizer to
handle.
"""
# Generate the inner query.
query = Query(self.model)
query.add_filter(filter_expr)
query.clear_ordering(True)
# Try to have as simple as possible subquery -> trim leading joins from
# the subquery.
trimmed_prefix, contains_louter = query.trim_start(names_with_path)
# Add extra check to make sure the selected field will not be null
# since we are adding an IN <subquery> clause. This prevents the
# database from tripping over IN (...,NULL,...) selects and returning
# nothing
col = query.select[0]
select_field = col.target
alias = col.alias
if self.is_nullable(select_field):
lookup_class = select_field.get_lookup('isnull')
lookup = lookup_class(select_field.get_col(alias), False)
query.where.add(lookup, AND)
if alias in can_reuse:
pk = select_field.model._meta.pk
# Need to add a restriction so that outer query's filters are in effect for
# the subquery, too.
query.bump_prefix(self)
lookup_class = select_field.get_lookup('exact')
# Note that the query.select[0].alias is different from alias
# due to bump_prefix above.
lookup = lookup_class(pk.get_col(query.select[0].alias),
pk.get_col(alias))
query.where.add(lookup, AND)
query.external_aliases.add(alias)
condition, needed_inner = self.build_filter(
('%s__in' % trimmed_prefix, query),
current_negated=True, branch_negated=True, can_reuse=can_reuse)
if contains_louter:
or_null_condition, _ = self.build_filter(
('%s__isnull' % trimmed_prefix, True),
current_negated=True, branch_negated=True, can_reuse=can_reuse)
condition.add(or_null_condition, OR)
# Note that the end result will be:
# (outercol NOT IN innerq AND outercol IS NOT NULL) OR outercol IS NULL.
# This might look crazy but due to how IN works, this seems to be
# correct. If the IS NOT NULL check is removed then outercol NOT
# IN will return UNKNOWN. If the IS NULL check is removed, then if
# outercol IS NULL we will not match the row.
return condition, needed_inner
def set_empty(self):
self.where.add(NothingNode(), AND)
def is_empty(self):
return any(isinstance(c, NothingNode) for c in self.where.children)
def set_limits(self, low=None, high=None):
"""
Adjusts the limits on the rows retrieved. We use low/high to set these,
as it makes it more Pythonic to read and write. When the SQL query is
created, they are converted to the appropriate offset and limit values.
Any limits passed in here are applied relative to the existing
constraints. So low is added to the current low value and both will be
clamped to any existing high value.
"""
if high is not None:
if self.high_mark is not None:
self.high_mark = min(self.high_mark, self.low_mark + high)
else:
self.high_mark = self.low_mark + high
if low is not None:
if self.high_mark is not None:
self.low_mark = min(self.high_mark, self.low_mark + low)
else:
self.low_mark = self.low_mark + low
def clear_limits(self):
"""
Clears any existing limits.
"""
self.low_mark, self.high_mark = 0, None
def can_filter(self):
"""
Returns True if adding filters to this instance is still possible.
Typically, this means no limits or offsets have been put on the results.
"""
return not self.low_mark and self.high_mark is None
def clear_select_clause(self):
"""
Removes all fields from SELECT clause.
"""
self.select = []
self.default_cols = False
self.select_related = False
self.set_extra_mask(())
self.set_annotation_mask(())
def clear_select_fields(self):
"""
Clears the list of fields to select (but not extra_select columns).
Some queryset types completely replace any existing list of select
columns.
"""
self.select = []
self.values_select = []
def add_select(self, col):
self.default_cols = False
self.select.append(col)
def set_select(self, cols):
self.default_cols = False
self.select = cols
def add_distinct_fields(self, *field_names):
"""
Adds and resolves the given fields to the query's "distinct on" clause.
"""
self.distinct_fields = field_names
self.distinct = True
def add_fields(self, field_names, allow_m2m=True):
"""
Adds the given (model) fields to the select set. The field names are
added in the order specified.
"""
alias = self.get_initial_alias()
opts = self.get_meta()
try:
for name in field_names:
# Join promotion note - we must not remove any rows here, so
# if there is no existing joins, use outer join.
_, targets, _, joins, path = self.setup_joins(
name.split(LOOKUP_SEP), opts, alias, allow_many=allow_m2m)
targets, final_alias, joins = self.trim_joins(targets, joins, path)
for target in targets:
self.add_select(target.get_col(final_alias))
except MultiJoin:
raise FieldError("Invalid field name: '%s'" % name)
except FieldError:
if LOOKUP_SEP in name:
# For lookups spanning over relationships, show the error
# from the model on which the lookup failed.
raise
else:
names = sorted(list(get_field_names_from_opts(opts)) + list(self.extra)
+ list(self.annotation_select))
raise FieldError("Cannot resolve keyword %r into field. "
"Choices are: %s" % (name, ", ".join(names)))
def add_ordering(self, *ordering):
"""
Adds items from the 'ordering' sequence to the query's "order by"
clause. These items are either field names (not column names) --
possibly with a direction prefix ('-' or '?') -- or OrderBy
expressions.
If 'ordering' is empty, all ordering is cleared from the query.
"""
errors = []
for item in ordering:
if not hasattr(item, 'resolve_expression') and not ORDER_PATTERN.match(item):
errors.append(item)
if errors:
raise FieldError('Invalid order_by arguments: %s' % errors)
if ordering:
self.order_by.extend(ordering)
else:
self.default_ordering = False
def clear_ordering(self, force_empty):
"""
Removes any ordering settings. If 'force_empty' is True, there will be
no ordering in the resulting query (not even the model's default).
"""
self.order_by = []
self.extra_order_by = ()
if force_empty:
self.default_ordering = False
def set_group_by(self):
"""
Expands the GROUP BY clause required by the query.
This will usually be the set of all non-aggregate fields in the
return data. If the database backend supports grouping by the
primary key, and the query would be equivalent, the optimization
will be made automatically.
"""
self.group_by = []
for col in self.select:
self.group_by.append(col)
if self._annotations:
for alias, annotation in six.iteritems(self.annotations):
for col in annotation.get_group_by_cols():
self.group_by.append(col)
def add_select_related(self, fields):
"""
Sets up the select_related data structure so that we only select
certain related models (as opposed to all models, when
self.select_related=True).
"""
if isinstance(self.select_related, bool):
field_dict = {}
else:
field_dict = self.select_related
for field in fields:
d = field_dict
for part in field.split(LOOKUP_SEP):
d = d.setdefault(part, {})
self.select_related = field_dict
def add_extra(self, select, select_params, where, params, tables, order_by):
"""
Adds data to the various extra_* attributes for user-created additions
to the query.
"""
if select:
# We need to pair any placeholder markers in the 'select'
# dictionary with their parameters in 'select_params' so that
# subsequent updates to the select dictionary also adjust the
# parameters appropriately.
select_pairs = OrderedDict()
if select_params:
param_iter = iter(select_params)
else:
param_iter = iter([])
for name, entry in select.items():
entry = force_text(entry)
entry_params = []
pos = entry.find("%s")
while pos != -1:
if pos == 0 or entry[pos - 1] != '%':
entry_params.append(next(param_iter))
pos = entry.find("%s", pos + 2)
select_pairs[name] = (entry, entry_params)
# This is order preserving, since self.extra_select is an OrderedDict.
self.extra.update(select_pairs)
if where or params:
self.where.add(ExtraWhere(where, params), AND)
if tables:
self.extra_tables += tuple(tables)
if order_by:
self.extra_order_by = order_by
def clear_deferred_loading(self):
"""
Remove any fields from the deferred loading set.
"""
self.deferred_loading = (set(), True)
def add_deferred_loading(self, field_names):
"""
Add the given list of model field names to the set of fields to
exclude from loading from the database when automatic column selection
is done. The new field names are added to any existing field names that
are deferred (or removed from any existing field names that are marked
as the only ones for immediate loading).
"""
# Fields on related models are stored in the literal double-underscore
# format, so that we can use a set datastructure. We do the foo__bar
# splitting and handling when computing the SQL column names (as part of
# get_columns()).
existing, defer = self.deferred_loading
if defer:
# Add to existing deferred names.
self.deferred_loading = existing.union(field_names), True
else:
# Remove names from the set of any existing "immediate load" names.
self.deferred_loading = existing.difference(field_names), False
def add_immediate_loading(self, field_names):
"""
Add the given list of model field names to the set of fields to
retrieve when the SQL is executed ("immediate loading" fields). The
field names replace any existing immediate loading field names. If
there are field names already specified for deferred loading, those
names are removed from the new field_names before storing the new names
for immediate loading. (That is, immediate loading overrides any
existing immediate values, but respects existing deferrals.)
"""
existing, defer = self.deferred_loading
field_names = set(field_names)
if 'pk' in field_names:
field_names.remove('pk')
field_names.add(self.get_meta().pk.name)
if defer:
# Remove any existing deferred names from the current set before
# setting the new names.
self.deferred_loading = field_names.difference(existing), False
else:
# Replace any existing "immediate load" field names.
self.deferred_loading = field_names, False
def get_loaded_field_names(self):
"""
If any fields are marked to be deferred, returns a dictionary mapping
models to a set of names in those fields that will be loaded. If a
model is not in the returned dictionary, none of its fields are
deferred.
If no fields are marked for deferral, returns an empty dictionary.
"""
# We cache this because we call this function multiple times
# (compiler.fill_related_selections, query.iterator)
try:
return self._loaded_field_names_cache
except AttributeError:
collection = {}
self.deferred_to_data(collection, self.get_loaded_field_names_cb)
self._loaded_field_names_cache = collection
return collection
def get_loaded_field_names_cb(self, target, model, fields):
"""
Callback used by get_deferred_field_names().
"""
target[model] = {f.attname for f in fields}
def set_aggregate_mask(self, names):
warnings.warn(
"set_aggregate_mask() is deprecated. Use set_annotation_mask() instead.",
RemovedInDjango20Warning, stacklevel=2)
self.set_annotation_mask(names)
def set_annotation_mask(self, names):
"Set the mask of annotations that will actually be returned by the SELECT"
if names is None:
self.annotation_select_mask = None
else:
self.annotation_select_mask = set(names)
self._annotation_select_cache = None
def append_aggregate_mask(self, names):
warnings.warn(
"append_aggregate_mask() is deprecated. Use append_annotation_mask() instead.",
RemovedInDjango20Warning, stacklevel=2)
self.append_annotation_mask(names)
def append_annotation_mask(self, names):
if self.annotation_select_mask is not None:
self.set_annotation_mask(set(names).union(self.annotation_select_mask))
def set_extra_mask(self, names):
"""
Set the mask of extra select items that will be returned by SELECT,
we don't actually remove them from the Query since they might be used
later
"""
if names is None:
self.extra_select_mask = None
else:
self.extra_select_mask = set(names)
self._extra_select_cache = None
@property
def annotation_select(self):
"""The OrderedDict of aggregate columns that are not masked, and should
be used in the SELECT clause.
This result is cached for optimization purposes.
"""
if self._annotation_select_cache is not None:
return self._annotation_select_cache
elif not self._annotations:
return {}
elif self.annotation_select_mask is not None:
self._annotation_select_cache = OrderedDict(
(k, v) for k, v in self.annotations.items()
if k in self.annotation_select_mask
)
return self._annotation_select_cache
else:
return self.annotations
@property
def aggregate_select(self):
warnings.warn(
"aggregate_select() is deprecated. Use annotation_select() instead.",
RemovedInDjango20Warning, stacklevel=2)
return self.annotation_select
@property
def extra_select(self):
if self._extra_select_cache is not None:
return self._extra_select_cache
if not self._extra:
return {}
elif self.extra_select_mask is not None:
self._extra_select_cache = OrderedDict(
(k, v) for k, v in self.extra.items()
if k in self.extra_select_mask
)
return self._extra_select_cache
else:
return self.extra
def trim_start(self, names_with_path):
"""
Trims joins from the start of the join path. The candidates for trim
are the PathInfos in names_with_path structure that are m2m joins.
Also sets the select column so the start matches the join.
This method is meant to be used for generating the subquery joins &
cols in split_exclude().
Returns a lookup usable for doing outerq.filter(lookup=self). Returns
also if the joins in the prefix contain a LEFT OUTER join.
_"""
all_paths = []
for _, paths in names_with_path:
all_paths.extend(paths)
contains_louter = False
# Trim and operate only on tables that were generated for
# the lookup part of the query. That is, avoid trimming
# joins generated for F() expressions.
lookup_tables = [t for t in self.tables if t in self._lookup_joins or t == self.tables[0]]
for trimmed_paths, path in enumerate(all_paths):
if path.m2m:
break
if self.alias_map[lookup_tables[trimmed_paths + 1]].join_type == LOUTER:
contains_louter = True
alias = lookup_tables[trimmed_paths]
self.unref_alias(alias)
# The path.join_field is a Rel, lets get the other side's field
join_field = path.join_field.field
# Build the filter prefix.
paths_in_prefix = trimmed_paths
trimmed_prefix = []
for name, path in names_with_path:
if paths_in_prefix - len(path) < 0:
break
trimmed_prefix.append(name)
paths_in_prefix -= len(path)
trimmed_prefix.append(
join_field.foreign_related_fields[0].name)
trimmed_prefix = LOOKUP_SEP.join(trimmed_prefix)
# Lets still see if we can trim the first join from the inner query
# (that is, self). We can't do this for LEFT JOINs because we would
# miss those rows that have nothing on the outer side.
if self.alias_map[lookup_tables[trimmed_paths + 1]].join_type != LOUTER:
select_fields = [r[0] for r in join_field.related_fields]
select_alias = lookup_tables[trimmed_paths + 1]
self.unref_alias(lookup_tables[trimmed_paths])
extra_restriction = join_field.get_extra_restriction(
self.where_class, None, lookup_tables[trimmed_paths + 1])
if extra_restriction:
self.where.add(extra_restriction, AND)
else:
# TODO: It might be possible to trim more joins from the start of the
# inner query if it happens to have a longer join chain containing the
# values in select_fields. Lets punt this one for now.
select_fields = [r[1] for r in join_field.related_fields]
select_alias = lookup_tables[trimmed_paths]
# The found starting point is likely a Join instead of a BaseTable reference.
# But the first entry in the query's FROM clause must not be a JOIN.
for table in self.tables:
if self.alias_refcount[table] > 0:
self.alias_map[table] = BaseTable(self.alias_map[table].table_name, table)
break
self.set_select([f.get_col(select_alias) for f in select_fields])
return trimmed_prefix, contains_louter
def is_nullable(self, field):
"""
A helper to check if the given field should be treated as nullable.
Some backends treat '' as null and Django treats such fields as
nullable for those backends. In such situations field.null can be
False even if we should treat the field as nullable.
"""
# We need to use DEFAULT_DB_ALIAS here, as QuerySet does not have
# (nor should it have) knowledge of which connection is going to be
# used. The proper fix would be to defer all decisions where
# is_nullable() is needed to the compiler stage, but that is not easy
# to do currently.
if ((connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls)
and field.empty_strings_allowed):
return True
else:
return field.null
def get_order_dir(field, default='ASC'):
"""
Returns the field name and direction for an order specification. For
example, '-foo' is returned as ('foo', 'DESC').
The 'default' param is used to indicate which way no prefix (or a '+'
prefix) should sort. The '-' prefix always sorts the opposite way.
"""
dirn = ORDER_DIR[default]
if field[0] == '-':
return field[1:], dirn[1]
return field, dirn[0]
def add_to_dict(data, key, value):
"""
A helper function to add "value" to the set of values for "key", whether or
not "key" already exists.
"""
if key in data:
data[key].add(value)
else:
data[key] = {value}
def is_reverse_o2o(field):
"""
A little helper to check if the given field is reverse-o2o. The field is
expected to be some sort of relation field or related object.
"""
return field.is_relation and field.one_to_one and not field.concrete
class JoinPromoter(object):
"""
A class to abstract away join promotion problems for complex filter
conditions.
"""
def __init__(self, connector, num_children, negated):
self.connector = connector
self.negated = negated
if self.negated:
if connector == AND:
self.effective_connector = OR
else:
self.effective_connector = AND
else:
self.effective_connector = self.connector
self.num_children = num_children
# Maps of table alias to how many times it is seen as required for
# inner and/or outer joins.
self.outer_votes = {}
self.inner_votes = {}
def add_votes(self, inner_votes):
"""
Add single vote per item to self.inner_votes. Parameter can be any
iterable.
"""
for voted in inner_votes:
self.inner_votes[voted] = self.inner_votes.get(voted, 0) + 1
def update_join_types(self, query):
"""
Change join types so that the generated query is as efficient as
possible, but still correct. So, change as many joins as possible
to INNER, but don't make OUTER joins INNER if that could remove
results from the query.
"""
to_promote = set()
to_demote = set()
# The effective_connector is used so that NOT (a AND b) is treated
# similarly to (a OR b) for join promotion.
for table, votes in self.inner_votes.items():
# We must use outer joins in OR case when the join isn't contained
# in all of the joins. Otherwise the INNER JOIN itself could remove
# valid results. Consider the case where a model with rel_a and
# rel_b relations is queried with rel_a__col=1 | rel_b__col=2. Now,
# if rel_a join doesn't produce any results is null (for example
# reverse foreign key or null value in direct foreign key), and
# there is a matching row in rel_b with col=2, then an INNER join
# to rel_a would remove a valid match from the query. So, we need
# to promote any existing INNER to LOUTER (it is possible this
# promotion in turn will be demoted later on).
if self.effective_connector == 'OR' and votes < self.num_children:
to_promote.add(table)
# If connector is AND and there is a filter that can match only
# when there is a joinable row, then use INNER. For example, in
# rel_a__col=1 & rel_b__col=2, if either of the rels produce NULL
# as join output, then the col=1 or col=2 can't match (as
# NULL=anything is always false).
# For the OR case, if all children voted for a join to be inner,
# then we can use INNER for the join. For example:
# (rel_a__col__icontains=Alex | rel_a__col__icontains=Russell)
# then if rel_a doesn't produce any rows, the whole condition
# can't match. Hence we can safely use INNER join.
if self.effective_connector == 'AND' or (
self.effective_connector == 'OR' and votes == self.num_children):
to_demote.add(table)
# Finally, what happens in cases where we have:
# (rel_a__col=1|rel_b__col=2) & rel_a__col__gte=0
# Now, we first generate the OR clause, and promote joins for it
# in the first if branch above. Both rel_a and rel_b are promoted
# to LOUTER joins. After that we do the AND case. The OR case
# voted no inner joins but the rel_a__col__gte=0 votes inner join
# for rel_a. We demote it back to INNER join (in AND case a single
# vote is enough). The demotion is OK, if rel_a doesn't produce
# rows, then the rel_a__col__gte=0 clause can't be true, and thus
# the whole clause must be false. So, it is safe to use INNER
# join.
# Note that in this example we could just as well have the __gte
# clause and the OR clause swapped. Or we could replace the __gte
# clause with an OR clause containing rel_a__col=1|rel_a__col=2,
# and again we could safely demote to INNER.
query.promote_joins(to_promote)
query.demote_joins(to_demote)
return to_demote
| gannetson/django | django/db/models/sql/query.py | Python | bsd-3-clause | 92,461 |
/* ISO C9x compliant stdint.h for Microsoft Visual Studio
* Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124
*
* Copyright (c) 2006-2008 Alexander Chemeris
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. The name of the author may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef _MSC_VER
#ifndef _MSC_STDINT_H_
#define _MSC_STDINT_H_
#if _MSC_VER > 1000
#pragma once
#endif
#include <limits.h>
/* For Visual Studio 6 in C++ mode and for many Visual Studio versions when
* compiling for ARM we should wrap <wchar.h> include with 'extern "C++" {}'
* or compiler give many errors like this:
* error C2733: second C linkage of overloaded function 'wmemchr' not allowed
*/
#ifdef __cplusplus
extern "C" {
#endif
#include <wchar.h>
#ifdef __cplusplus
}
#endif
/* Define _W64 macros to mark types changing their size, like intptr_t. */
#ifndef _W64
#if !defined(__midl) && (defined(_X86_) || defined(_M_IX86)) && _MSC_VER >= 1300
#define _W64 __w64
#else
#define _W64
#endif
#endif
/* 7.18.1 Integer types */
/* 7.18.1.1 Exact-width integer types */
/* Visual Studio 6 and Embedded Visual C++ 4 doesn't
* realize that, e.g. char has the same size as __int8
* so we give up on __intX for them. */
#if (_MSC_VER < 1300)
typedef signed char int8_t;
typedef signed short int16_t;
typedef signed int int32_t;
typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
typedef unsigned int uint32_t;
#else
typedef signed __int8 int8_t;
typedef signed __int16 int16_t;
typedef signed __int32 int32_t;
typedef unsigned __int8 uint8_t;
typedef unsigned __int16 uint16_t;
typedef unsigned __int32 uint32_t;
#endif
typedef signed __int64 int64_t;
typedef unsigned __int64 uint64_t;
/* 7.18.1.2 Minimum-width integer types */
typedef int8_t int_least8_t;
typedef int16_t int_least16_t;
typedef int32_t int_least32_t;
typedef int64_t int_least64_t;
typedef uint8_t uint_least8_t;
typedef uint16_t uint_least16_t;
typedef uint32_t uint_least32_t;
typedef uint64_t uint_least64_t;
/* 7.18.1.3 Fastest minimum-width integer types */
typedef int8_t int_fast8_t;
typedef int16_t int_fast16_t;
typedef int32_t int_fast32_t;
typedef int64_t int_fast64_t;
typedef uint8_t uint_fast8_t;
typedef uint16_t uint_fast16_t;
typedef uint32_t uint_fast32_t;
typedef uint64_t uint_fast64_t;
/* 7.18.1.4 Integer types capable of holding object pointers */
#ifdef _WIN64
typedef signed __int64 intptr_t;
typedef unsigned __int64 uintptr_t;
#else /*_WIN64 */
typedef _W64 signed int intptr_t;
typedef _W64 unsigned int uintptr_t;
#endif /* _WIN64 */
/* 7.18.1.5 Greatest-width integer types */
typedef int64_t intmax_t;
typedef uint64_t uintmax_t;
/* 7.18.2 Limits of specified-width integer types */
#if !defined(__cplusplus) || defined(__STDC_LIMIT_MACROS)
/* See footnote 220 at page 257 and footnote 221 at page 259 */
/* 7.18.2.1 Limits of exact-width integer types */
#define INT8_MIN ((int8_t)_I8_MIN)
#define INT8_MAX _I8_MAX
#define INT16_MIN ((int16_t)_I16_MIN)
#define INT16_MAX _I16_MAX
#define INT32_MIN ((int32_t)_I32_MIN)
#define INT32_MAX _I32_MAX
#define INT64_MIN ((int64_t)_I64_MIN)
#define INT64_MAX _I64_MAX
#define UINT8_MAX _UI8_MAX
#define UINT16_MAX _UI16_MAX
#define UINT32_MAX _UI32_MAX
#define UINT64_MAX _UI64_MAX
/* 7.18.2.2 Limits of minimum-width integer types */
#define INT_LEAST8_MIN INT8_MIN
#define INT_LEAST8_MAX INT8_MAX
#define INT_LEAST16_MIN INT16_MIN
#define INT_LEAST16_MAX INT16_MAX
#define INT_LEAST32_MIN INT32_MIN
#define INT_LEAST32_MAX INT32_MAX
#define INT_LEAST64_MIN INT64_MIN
#define INT_LEAST64_MAX INT64_MAX
#define UINT_LEAST8_MAX UINT8_MAX
#define UINT_LEAST16_MAX UINT16_MAX
#define UINT_LEAST32_MAX UINT32_MAX
#define UINT_LEAST64_MAX UINT64_MAX
/* 7.18.2.3 Limits of fastest minimum-width integer types */
#define INT_FAST8_MIN INT8_MIN
#define INT_FAST8_MAX INT8_MAX
#define INT_FAST16_MIN INT16_MIN
#define INT_FAST16_MAX INT16_MAX
#define INT_FAST32_MIN INT32_MIN
#define INT_FAST32_MAX INT32_MAX
#define INT_FAST64_MIN INT64_MIN
#define INT_FAST64_MAX INT64_MAX
#define UINT_FAST8_MAX UINT8_MAX
#define UINT_FAST16_MAX UINT16_MAX
#define UINT_FAST32_MAX UINT32_MAX
#define UINT_FAST64_MAX UINT64_MAX
/* 7.18.2.4 Limits of integer types capable of holding object pointers */
#ifdef _WIN64
#define INTPTR_MIN INT64_MIN
#define INTPTR_MAX INT64_MAX
#define UINTPTR_MAX UINT64_MAX
#else /* _WIN64 */
#define INTPTR_MIN INT32_MIN
#define INTPTR_MAX INT32_MAX
#define UINTPTR_MAX UINT32_MAX
#endif /* _WIN64 */
/* 7.18.2.5 Limits of greatest-width integer types */
#define INTMAX_MIN INT64_MIN
#define INTMAX_MAX INT64_MAX
#define UINTMAX_MAX UINT64_MAX
/* 7.18.3 Limits of other integer types */
#ifdef _WIN64
#define PTRDIFF_MIN _I64_MIN
#define PTRDIFF_MAX _I64_MAX
#else /* _WIN64 */
#define PTRDIFF_MIN _I32_MIN
#define PTRDIFF_MAX _I32_MAX
#endif /* _WIN64 */
#define SIG_ATOMIC_MIN INT_MIN
#define SIG_ATOMIC_MAX INT_MAX
#ifndef SIZE_MAX
#ifdef _WIN64
#define SIZE_MAX _UI64_MAX
#else /* _WIN64 */
#define SIZE_MAX _UI32_MAX
#endif /* _WIN64 */
#endif /* SIZE_MAX */
/* WCHAR_MIN and WCHAR_MAX are also defined in <wchar.h> */
#ifndef WCHAR_MIN
#define WCHAR_MIN 0
#endif /* WCHAR_MIN */
#ifndef WCHAR_MAX
#define WCHAR_MAX _UI16_MAX
#endif /* WCHAR_MAX */
#define WINT_MIN 0
#define WINT_MAX _UI16_MAX
#endif /* __STDC_LIMIT_MACROS */
/* 7.18.4 Limits of other integer types */
#if !defined(__cplusplus) || defined(__STDC_CONSTANT_MACROS)
/* See footnote 224 at page 260 */
/* 7.18.4.1 Macros for minimum-width integer constants */
#define INT8_C(val) val##i8
#define INT16_C(val) val##i16
#define INT32_C(val) val##i32
#define INT64_C(val) val##i64
#define UINT8_C(val) val##ui8
#define UINT16_C(val) val##ui16
#define UINT32_C(val) val##ui32
#define UINT64_C(val) val##ui64
/* 7.18.4.2 Macros for greatest-width integer constants */
#define INTMAX_C INT64_C
#define UINTMAX_C UINT64_C
#endif /* __STDC_CONSTANT_MACROS */
#endif /* _MSC_STDINT_H_ */
#endif /* _MSC_VER */
| sswen/ntirpc | ntirpc/misc/stdint.h | C | bsd-3-clause | 7,457 |
badnode
=======
Report if the node version we're using is bad.
| keybase/node-client | node_modules/keybase-installer/node_modules/badnode/README.md | Markdown | bsd-3-clause | 64 |
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <sstream>
#include <google/protobuf/compiler/code_generator.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/io/zero_copy_stream.h>
#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/compiler/csharp/csharp_doc_comment.h>
#include <google/protobuf/compiler/csharp/csharp_helpers.h>
#include <google/protobuf/compiler/csharp/csharp_options.h>
#include <google/protobuf/compiler/csharp/csharp_primitive_field.h>
namespace google {
namespace protobuf {
namespace compiler {
namespace csharp {
PrimitiveFieldGenerator::PrimitiveFieldGenerator(
const FieldDescriptor* descriptor, int presenceIndex, const Options *options)
: FieldGeneratorBase(descriptor, presenceIndex, options) {
// TODO(jonskeet): Make this cleaner...
is_value_type = descriptor->type() != FieldDescriptor::TYPE_STRING
&& descriptor->type() != FieldDescriptor::TYPE_BYTES;
if (!is_value_type && !IsProto2(descriptor_->file())) {
variables_["has_property_check"] = variables_["property_name"] + ".Length != 0";
variables_["other_has_property_check"] = "other." + variables_["property_name"] + ".Length != 0";
}
}
PrimitiveFieldGenerator::~PrimitiveFieldGenerator() {
}
void PrimitiveFieldGenerator::GenerateMembers(io::Printer* printer) {
// TODO(jonskeet): Work out whether we want to prevent the fields from ever being
// null, or whether we just handle it, in the cases of bytes and string.
// (Basically, should null-handling code be in the getter or the setter?)
if (IsProto2(descriptor_->file())) {
printer->Print(
variables_,
"private readonly static $type_name$ $property_name$DefaultValue = $default_value$;\n\n");
}
printer->Print(
variables_,
"private $type_name$ $name_def_message$;\n");
WritePropertyDocComment(printer, descriptor_);
AddPublicMemberAttributes(printer);
if (IsProto2(descriptor_->file())) {
if (presenceIndex_ == -1) {
printer->Print(
variables_,
"$access_level$ $type_name$ $property_name$ {\n"
" get { return $name$_ ?? $property_name$DefaultValue; }\n"
" set {\n");
} else {
printer->Print(
variables_,
"$access_level$ $type_name$ $property_name$ {\n"
" get { if ($has_field_check$) { return $name$_; } else { return $property_name$DefaultValue; } }\n"
" set {\n");
}
} else {
printer->Print(
variables_,
"$access_level$ $type_name$ $property_name$ {\n"
" get { return $name$_; }\n"
" set {\n");
}
if (presenceIndex_ != -1) {
printer->Print(
variables_,
" $set_has_field$;\n");
}
if (is_value_type) {
printer->Print(
variables_,
" $name$_ = value;\n");
} else {
printer->Print(
variables_,
" $name$_ = pb::ProtoPreconditions.CheckNotNull(value, \"value\");\n");
}
printer->Print(
" }\n"
"}\n");
if (IsProto2(descriptor_->file())) {
printer->Print(variables_, "/// <summary>Gets whether the \"$descriptor_name$\" field is set</summary>\n");
AddPublicMemberAttributes(printer);
printer->Print(
variables_,
"$access_level$ bool Has$property_name$ {\n"
" get { return ");
if (IsNullable(descriptor_)) {
printer->Print(
variables_,
"$name$_ != null; }\n}\n");
} else {
printer->Print(
variables_,
"$has_field_check$; }\n}\n");
}
}
if (IsProto2(descriptor_->file())) {
printer->Print(variables_, "/// <summary>Clears the value of the \"$descriptor_name$\" field</summary>\n");
AddPublicMemberAttributes(printer);
printer->Print(
variables_,
"$access_level$ void Clear$property_name$() {\n");
if (IsNullable(descriptor_)) {
printer->Print(variables_, " $name$_ = null;\n");
} else {
printer->Print(variables_, " $clear_has_field$;\n");
}
printer->Print("}\n");
}
}
void PrimitiveFieldGenerator::GenerateMergingCode(io::Printer* printer) {
printer->Print(
variables_,
"if ($other_has_property_check$) {\n"
" $property_name$ = other.$property_name$;\n"
"}\n");
}
void PrimitiveFieldGenerator::GenerateParsingCode(io::Printer* printer) {
// Note: invoke the property setter rather than writing straight to the field,
// so that we can normalize "null to empty" for strings and bytes.
printer->Print(
variables_,
"$property_name$ = input.Read$capitalized_type_name$();\n");
}
void PrimitiveFieldGenerator::GenerateSerializationCode(io::Printer* printer) {
printer->Print(
variables_,
"if ($has_property_check$) {\n"
" output.WriteRawTag($tag_bytes$);\n"
" output.Write$capitalized_type_name$($property_name$);\n"
"}\n");
}
void PrimitiveFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer) {
printer->Print(
variables_,
"if ($has_property_check$) {\n");
printer->Indent();
int fixedSize = GetFixedSize(descriptor_->type());
if (fixedSize == -1) {
printer->Print(
variables_,
"size += $tag_size$ + pb::CodedOutputStream.Compute$capitalized_type_name$Size($property_name$);\n");
} else {
printer->Print(
"size += $tag_size$ + $fixed_size$;\n",
"fixed_size", StrCat(fixedSize),
"tag_size", variables_["tag_size"]);
}
printer->Outdent();
printer->Print("}\n");
}
void PrimitiveFieldGenerator::WriteHash(io::Printer* printer) {
const char *text = "if ($has_property_check$) hash ^= $property_name$.GetHashCode();\n";
if (descriptor_->type() == FieldDescriptor::TYPE_FLOAT) {
text = "if ($has_property_check$) hash ^= pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.GetHashCode($property_name$);\n";
} else if (descriptor_->type() == FieldDescriptor::TYPE_DOUBLE) {
text = "if ($has_property_check$) hash ^= pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.GetHashCode($property_name$);\n";
}
printer->Print(variables_, text);
}
void PrimitiveFieldGenerator::WriteEquals(io::Printer* printer) {
const char *text = "if ($property_name$ != other.$property_name$) return false;\n";
if (descriptor_->type() == FieldDescriptor::TYPE_FLOAT) {
text = "if (!pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.Equals($property_name$, other.$property_name$)) return false;\n";
} else if (descriptor_->type() == FieldDescriptor::TYPE_DOUBLE) {
text = "if (!pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.Equals($property_name$, other.$property_name$)) return false;\n";
}
printer->Print(variables_, text);
}
void PrimitiveFieldGenerator::WriteToString(io::Printer* printer) {
printer->Print(
variables_,
"PrintField(\"$descriptor_name$\", $has_property_check$, $property_name$, writer);\n");
}
void PrimitiveFieldGenerator::GenerateCloningCode(io::Printer* printer) {
printer->Print(variables_,
"$name$_ = other.$name$_;\n");
}
void PrimitiveFieldGenerator::GenerateCodecCode(io::Printer* printer) {
printer->Print(
variables_,
"pb::FieldCodec.For$capitalized_type_name$($tag$, $default_value$)");
}
void PrimitiveFieldGenerator::GenerateExtensionCode(io::Printer* printer) {
WritePropertyDocComment(printer, descriptor_);
AddDeprecatedFlag(printer);
printer->Print(
variables_,
"$access_level$ static readonly pb::Extension<$extended_type$, $type_name$> $property_name$ =\n"
" new pb::Extension<$extended_type$, $type_name$>($number$, ");
GenerateCodecCode(printer);
printer->Print(");\n");
}
PrimitiveOneofFieldGenerator::PrimitiveOneofFieldGenerator(
const FieldDescriptor* descriptor, int presenceIndex, const Options *options)
: PrimitiveFieldGenerator(descriptor, presenceIndex, options) {
SetCommonOneofFieldVariables(&variables_);
}
PrimitiveOneofFieldGenerator::~PrimitiveOneofFieldGenerator() {
}
void PrimitiveOneofFieldGenerator::GenerateMembers(io::Printer* printer) {
WritePropertyDocComment(printer, descriptor_);
AddPublicMemberAttributes(printer);
printer->Print(
variables_,
"$access_level$ $type_name$ $property_name$ {\n"
" get { return $has_property_check$ ? ($type_name$) $oneof_name$_ : $default_value$; }\n"
" set {\n");
if (is_value_type) {
printer->Print(
variables_,
" $oneof_name$_ = value;\n");
} else {
printer->Print(
variables_,
" $oneof_name$_ = pb::ProtoPreconditions.CheckNotNull(value, \"value\");\n");
}
printer->Print(
variables_,
" $oneof_name$Case_ = $oneof_property_name$OneofCase.$property_name$;\n"
" }\n"
"}\n");
if (IsProto2(descriptor_->file())) {
printer->Print(
variables_,
"/// <summary>Gets whether the \"$descriptor_name$\" field is set</summary>\n");
AddPublicMemberAttributes(printer);
printer->Print(
variables_,
"$access_level$ bool Has$property_name$ {\n"
" get { return $oneof_name$Case_ == $oneof_property_name$OneofCase.$property_name$; }\n"
"}\n");
printer->Print(
variables_,
"/// <summary> Clears the value of the oneof if it's currently set to \"$descriptor_name$\" </summary>\n");
AddPublicMemberAttributes(printer);
printer->Print(
variables_,
"$access_level$ void Clear$property_name$() {\n"
" if ($has_property_check$) {\n"
" Clear$oneof_property_name$();\n"
" }\n"
"}\n");
}
}
void PrimitiveOneofFieldGenerator::GenerateMergingCode(io::Printer* printer) {
printer->Print(variables_, "$property_name$ = other.$property_name$;\n");
}
void PrimitiveOneofFieldGenerator::WriteToString(io::Printer* printer) {
printer->Print(variables_,
"PrintField(\"$descriptor_name$\", $has_property_check$, $oneof_name$_, writer);\n");
}
void PrimitiveOneofFieldGenerator::GenerateParsingCode(io::Printer* printer) {
printer->Print(
variables_,
"$property_name$ = input.Read$capitalized_type_name$();\n");
}
void PrimitiveOneofFieldGenerator::GenerateCloningCode(io::Printer* printer) {
printer->Print(variables_,
"$property_name$ = other.$property_name$;\n");
}
} // namespace csharp
} // namespace compiler
} // namespace protobuf
} // namespace google
| endlessm/chromium-browser | third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc | C++ | bsd-3-clause | 11,927 |
<?php
namespace React\Tests\ChildProcess;
use React\ChildProcess\Process;
use React\EventLoop\Timer\Timer;
abstract class AbstractProcessTest extends \PHPUnit_Framework_TestCase
{
abstract public function createLoop();
public function testGetEnhanceSigchildCompatibility()
{
$process = new Process('echo foo');
$this->assertSame($process, $process->setEnhanceSigchildCompatibility(true));
$this->assertTrue($process->getEnhanceSigchildCompatibility());
$this->assertSame($process, $process->setEnhanceSigchildCompatibility(false));
$this->assertFalse($process->getEnhanceSigchildCompatibility());
}
/**
* @expectedException RuntimeException
*/
public function testSetEnhanceSigchildCompatibilityCannotBeCalledIfProcessIsRunning()
{
$process = new Process('sleep 1');
$process->start($this->createLoop());
$process->setEnhanceSigchildCompatibility(false);
}
public function testGetCommand()
{
$process = new Process('echo foo');
$this->assertSame('echo foo', $process->getCommand());
}
public function testIsRunning()
{
$process = new Process('sleep 1');
$this->assertFalse($process->isRunning());
$process->start($this->createLoop());
$this->assertTrue($process->isRunning());
return $process;
}
/**
* @depends testIsRunning
*/
public function testGetExitCodeWhenRunning($process)
{
$this->assertNull($process->getExitCode());
}
/**
* @depends testIsRunning
*/
public function testGetTermSignalWhenRunning($process)
{
$this->assertNull($process->getTermSignal());
}
public function testProcessWithDefaultCwdAndEnv()
{
$cmd = 'php -r ' . escapeshellarg('echo getcwd(), PHP_EOL, count($_ENV), PHP_EOL;');
$loop = $this->createLoop();
$process = new Process($cmd);
$output = '';
$loop->addTimer(0.001, function(Timer $timer) use ($process, &$output) {
$process->start($timer->getLoop());
$process->stdout->on('data', function () use (&$output) {
$output .= func_get_arg(0);
});
});
$loop->run();
$expectedOutput = sprintf('%s%s%d%s', getcwd(), PHP_EOL, count($_ENV), PHP_EOL);
$this->assertSame($expectedOutput, $output);
}
public function testProcessWithCwd()
{
$cmd = 'php -r ' . escapeshellarg('echo getcwd(), PHP_EOL;');
$loop = $this->createLoop();
$process = new Process($cmd, '/');
$output = '';
$loop->addTimer(0.001, function(Timer $timer) use ($process, &$output) {
$process->start($timer->getLoop());
$process->stdout->on('data', function () use (&$output) {
$output .= func_get_arg(0);
});
});
$loop->run();
$this->assertSame('/' . PHP_EOL, $output);
}
public function testProcessWithEnv()
{
if (getenv('TRAVIS')) {
$this->markTestSkipped('Cannot execute PHP processes with custom environments on Travis CI.');
}
$cmd = 'php -r ' . escapeshellarg('echo getenv("foo"), PHP_EOL;');
$loop = $this->createLoop();
$process = new Process($cmd, null, array('foo' => 'bar'));
$output = '';
$loop->addTimer(0.001, function(Timer $timer) use ($process, &$output) {
$process->start($timer->getLoop());
$process->stdout->on('data', function () use (&$output) {
$output .= func_get_arg(0);
});
});
$loop->run();
$this->assertSame('bar' . PHP_EOL, $output);
}
public function testStartAndAllowProcessToExitSuccessfullyUsingEventLoop()
{
$loop = $this->createLoop();
$process = new Process('exit 0');
$called = false;
$exitCode = 'initial';
$termSignal = 'initial';
$process->on('exit', function () use (&$called, &$exitCode, &$termSignal) {
$called = true;
$exitCode = func_get_arg(0);
$termSignal = func_get_arg(1);
});
$loop->addTimer(0.001, function(Timer $timer) use ($process) {
$process->start($timer->getLoop());
});
$loop->run();
$this->assertTrue($called);
$this->assertSame(0, $exitCode);
$this->assertNull($termSignal);
$this->assertFalse($process->isRunning());
$this->assertSame(0, $process->getExitCode());
$this->assertNull($process->getTermSignal());
$this->assertFalse($process->isTerminated());
}
public function testStartInvalidProcess()
{
$cmd = tempnam(sys_get_temp_dir(), 'react');
$loop = $this->createLoop();
$process = new Process($cmd);
$output = '';
$loop->addTimer(0.001, function(Timer $timer) use ($process, &$output) {
$process->start($timer->getLoop());
$process->stderr->on('data', function () use (&$output) {
$output .= func_get_arg(0);
});
});
$loop->run();
unlink($cmd);
$this->assertNotEmpty($output);
}
/**
* @expectedException RuntimeException
*/
public function testStartAlreadyRunningProcess()
{
$process = new Process('sleep 1');
$process->start($this->createLoop());
$process->start($this->createLoop());
}
public function testTerminateWithDefaultTermSignalUsingEventLoop()
{
if (defined('PHP_WINDOWS_VERSION_BUILD')) {
$this->markTestSkipped('Windows does not report signals via proc_get_status()');
}
if (!defined('SIGTERM')) {
$this->markTestSkipped('SIGTERM is not defined');
}
$loop = $this->createloop();
$process = new Process('sleep 1; exit 0');
$called = false;
$exitCode = 'initial';
$termSignal = 'initial';
$process->on('exit', function () use (&$called, &$exitCode, &$termSignal) {
$called = true;
$exitCode = func_get_arg(0);
$termSignal = func_get_arg(1);
});
$loop->addTimer(0.001, function(Timer $timer) use ($process) {
$process->start($timer->getLoop());
$process->terminate();
});
$loop->run();
$this->assertTrue($called);
$this->assertNull($exitCode);
$this->assertEquals(SIGTERM, $termSignal);
$this->assertFalse($process->isRunning());
$this->assertNull($process->getExitCode());
$this->assertEquals(SIGTERM, $process->getTermSignal());
$this->assertTrue($process->isTerminated());
}
public function testTerminateWithStopAndContinueSignalsUsingEventLoop()
{
if (defined('PHP_WINDOWS_VERSION_BUILD')) {
$this->markTestSkipped('Windows does not report signals via proc_get_status()');
}
if (!defined('SIGSTOP') && !defined('SIGCONT')) {
$this->markTestSkipped('SIGSTOP and/or SIGCONT is not defined');
}
$loop = $this->createloop();
$process = new Process('sleep 1; exit 0');
$called = false;
$exitCode = 'initial';
$termSignal = 'initial';
$process->on('exit', function () use (&$called, &$exitCode, &$termSignal) {
$called = true;
$exitCode = func_get_arg(0);
$termSignal = func_get_arg(1);
});
$loop->addTimer(0.001, function(Timer $timer) use ($process) {
$process->start($timer->getLoop());
$process->terminate(SIGSTOP);
$this->assertSoon(function() use ($process) {
$this->assertTrue($process->isStopped());
$this->assertTrue($process->isRunning());
$this->assertEquals(SIGSTOP, $process->getStopSignal());
});
$process->terminate(SIGCONT);
$this->assertSoon(function() use ($process) {
$this->assertFalse($process->isStopped());
$this->assertEquals(SIGSTOP, $process->getStopSignal());
});
});
$loop->run();
$this->assertTrue($called);
$this->assertSame(0, $exitCode);
$this->assertNull($termSignal);
$this->assertFalse($process->isRunning());
$this->assertSame(0, $process->getExitCode());
$this->assertNull($process->getTermSignal());
$this->assertFalse($process->isTerminated());
}
/**
* Execute a callback at regular intervals until it returns successfully or
* a timeout is reached.
*
* @param Closure $callback Callback with one or more assertions
* @param integer $timeout Time limit for callback to succeed (milliseconds)
* @param integer $interval Interval for retrying the callback (milliseconds)
* @throws PHPUnit_Framework_ExpectationFailedException Last exception raised by the callback
*/
public function assertSoon(\Closure $callback, $timeout = 20000, $interval = 200)
{
$start = microtime(true);
$timeout /= 1000; // convert to seconds
$interval *= 1000; // convert to microseconds
while (1) {
try {
call_user_func($callback);
return;
} catch (\PHPUnit_Framework_ExpectationFailedException $e) {}
if ((microtime(true) - $start) > $timeout) {
throw $e;
}
usleep($interval);
}
}
}
| handsomegyr/ent | vendor/react/react/tests/ChildProcess/AbstractProcessTest.php | PHP | bsd-3-clause | 9,667 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Terminology test: default</title>
</head>
<body its-annotators-ref="text-analysis|file:///tools.xml#T1" >
<p>We need a new <span its-annotators-ref="terminology|http://example.com/term-tool#T2" its-term="YeS" its-term-info-ref="#TDPV" its-term-confidence="0.5">motherboard</span>
</p>
</body>
</html>
| cr/fxos-certsuite | web-platform-tests/tests/conformance-checkers/html-its/terminology/html/terminology5html.html | HTML | mpl-2.0 | 388 |
/************************************************************************************[SimpSolver.h]
Copyright (c) 2006, Niklas Een, Niklas Sorensson
Copyright (c) 2007-2010, Niklas Sorensson
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**************************************************************************************************/
#ifndef Minisat_SimpSolver_h
#define Minisat_SimpSolver_h
#include "Queue.h"
#include "Solver.h"
namespace Minisat {
//=================================================================================================
class SimpSolver : public Solver {
public:
// Constructor/Destructor:
//
SimpSolver();
~SimpSolver();
// Problem specification:
//
Var newVar (lbool upol = l_Undef, bool dvar = true);
void releaseVar(Lit l);
bool addClause (const vec<Lit>& ps);
bool addEmptyClause(); // Add the empty clause to the solver.
bool addClause (Lit p); // Add a unit clause to the solver.
bool addClause (Lit p, Lit q); // Add a binary clause to the solver.
bool addClause (Lit p, Lit q, Lit r); // Add a ternary clause to the solver.
bool addClause (Lit p, Lit q, Lit r, Lit s); // Add a quaternary clause to the solver.
bool addClause_( vec<Lit>& ps);
bool substitute(Var v, Lit x); // Replace all occurences of v with x (may cause a contradiction).
// Variable mode:
//
void setFrozen (Var v, bool b); // If a variable is frozen it will not be eliminated.
bool isEliminated(Var v) const;
// Alternative freeze interface (may replace 'setFrozen()'):
void freezeVar (Var v); // Freeze one variable so it will not be eliminated.
void thaw (); // Thaw all frozen variables.
// Solving:
//
bool solve (const vec<Lit>& assumps, bool do_simp = true, bool turn_off_simp = false);
lbool solveLimited(const vec<Lit>& assumps, bool do_simp = true, bool turn_off_simp = false);
bool solve ( bool do_simp = true, bool turn_off_simp = false);
bool solve (Lit p , bool do_simp = true, bool turn_off_simp = false);
bool solve (Lit p, Lit q, bool do_simp = true, bool turn_off_simp = false);
bool solve (Lit p, Lit q, Lit r, bool do_simp = true, bool turn_off_simp = false);
bool eliminate (bool turn_off_elim = false); // Perform variable elimination based simplification.
// Memory managment:
//
virtual void garbageCollect();
// Generate a (possibly simplified) DIMACS file:
//
#if 0
void toDimacs (const char* file, const vec<Lit>& assumps);
void toDimacs (const char* file);
void toDimacs (const char* file, Lit p);
void toDimacs (const char* file, Lit p, Lit q);
void toDimacs (const char* file, Lit p, Lit q, Lit r);
#endif
// Mode of operation:
//
int grow; // Allow a variable elimination step to grow by a number of clauses (default to zero).
int clause_lim; // Variables are not eliminated if it produces a resolvent with a length above this limit.
// -1 means no limit.
int subsumption_lim; // Do not check if subsumption against a clause larger than this. -1 means no limit.
double simp_garbage_frac; // A different limit for when to issue a GC during simplification (Also see 'garbage_frac').
bool use_asymm; // Shrink clauses by asymmetric branching.
bool use_rcheck; // Check if a clause is already implied. Prett costly, and subsumes subsumptions :)
bool use_elim; // Perform variable elimination.
bool extend_model; // Flag to indicate whether the user needs to look at the full model.
// Statistics:
//
int merges;
int asymm_lits;
int eliminated_vars;
protected:
// Helper structures:
//
struct ElimLt {
const LMap<int>& n_occ;
explicit ElimLt(const LMap<int>& no) : n_occ(no) {}
// TODO: are 64-bit operations here noticably bad on 32-bit platforms? Could use a saturating
// 32-bit implementation instead then, but this will have to do for now.
uint64_t cost (Var x) const { return (uint64_t)n_occ[mkLit(x)] * (uint64_t)n_occ[~mkLit(x)]; }
bool operator()(Var x, Var y) const { return cost(x) < cost(y); }
// TODO: investigate this order alternative more.
// bool operator()(Var x, Var y) const {
// int c_x = cost(x);
// int c_y = cost(y);
// return c_x < c_y || c_x == c_y && x < y; }
};
struct ClauseDeleted {
const ClauseAllocator& ca;
explicit ClauseDeleted(const ClauseAllocator& _ca) : ca(_ca) {}
bool operator()(const CRef& cr) const { return ca[cr].mark() == 1; } };
// Solver state:
//
int elimorder;
bool use_simplification;
Var max_simp_var; // Max variable at the point simplification was turned off.
vec<uint32_t> elimclauses;
VMap<char> touched;
OccLists<Var, vec<CRef>, ClauseDeleted>
occurs;
LMap<int> n_occ;
Heap<Var,ElimLt> elim_heap;
Queue<CRef> subsumption_queue;
VMap<char> frozen;
vec<Var> frozen_vars;
VMap<char> eliminated;
int bwdsub_assigns;
int n_touched;
// Temporaries:
//
CRef bwdsub_tmpunit;
// Main internal methods:
//
lbool solve_ (bool do_simp = true, bool turn_off_simp = false);
bool asymm (Var v, CRef cr);
bool asymmVar (Var v);
void updateElimHeap (Var v);
void gatherTouchedClauses ();
bool merge (const Clause& _ps, const Clause& _qs, Var v, vec<Lit>& out_clause);
bool merge (const Clause& _ps, const Clause& _qs, Var v, int& size);
bool backwardSubsumptionCheck (bool verbose = false);
bool eliminateVar (Var v);
void extendModel ();
void removeClause (CRef cr);
bool strengthenClause (CRef cr, Lit l);
bool implied (const vec<Lit>& c);
void relocAll (ClauseAllocator& to);
};
//=================================================================================================
// Implementation of inline methods:
inline bool SimpSolver::isEliminated (Var v) const { return eliminated[v]; }
inline void SimpSolver::updateElimHeap(Var v) {
assert(use_simplification);
// if (!frozen[v] && !isEliminated(v) && value(v) == l_Undef)
if (elim_heap.inHeap(v) || (!frozen[v] && !isEliminated(v) && value(v) == l_Undef))
elim_heap.update(v); }
inline bool SimpSolver::addClause (const vec<Lit>& ps) { ps.copyTo(add_tmp); return addClause_(add_tmp); }
inline bool SimpSolver::addEmptyClause() { add_tmp.clear(); return addClause_(add_tmp); }
inline bool SimpSolver::addClause (Lit p) { add_tmp.clear(); add_tmp.push(p); return addClause_(add_tmp); }
inline bool SimpSolver::addClause (Lit p, Lit q) { add_tmp.clear(); add_tmp.push(p); add_tmp.push(q); return addClause_(add_tmp); }
inline bool SimpSolver::addClause (Lit p, Lit q, Lit r) { add_tmp.clear(); add_tmp.push(p); add_tmp.push(q); add_tmp.push(r); return addClause_(add_tmp); }
inline bool SimpSolver::addClause (Lit p, Lit q, Lit r, Lit s){ add_tmp.clear(); add_tmp.push(p); add_tmp.push(q); add_tmp.push(r); add_tmp.push(s); return addClause_(add_tmp); }
inline void SimpSolver::setFrozen (Var v, bool b) { frozen[v] = (char)b; if (use_simplification && !b) { updateElimHeap(v); } }
inline void SimpSolver::freezeVar(Var v){
if (!frozen[v]){
frozen[v] = 1;
frozen_vars.push(v);
} }
inline void SimpSolver::thaw(){
for (int i = 0; i < frozen_vars.size(); i++){
Var v = frozen_vars[i];
frozen[v] = 0;
if (use_simplification)
updateElimHeap(v);
}
frozen_vars.clear(); }
inline bool SimpSolver::solve ( bool do_simp, bool turn_off_simp) { budgetOff(); assumptions.clear(); return solve_(do_simp, turn_off_simp) == l_True; }
inline bool SimpSolver::solve (Lit p , bool do_simp, bool turn_off_simp) { budgetOff(); assumptions.clear(); assumptions.push(p); return solve_(do_simp, turn_off_simp) == l_True; }
inline bool SimpSolver::solve (Lit p, Lit q, bool do_simp, bool turn_off_simp) { budgetOff(); assumptions.clear(); assumptions.push(p); assumptions.push(q); return solve_(do_simp, turn_off_simp) == l_True; }
inline bool SimpSolver::solve (Lit p, Lit q, Lit r, bool do_simp, bool turn_off_simp) { budgetOff(); assumptions.clear(); assumptions.push(p); assumptions.push(q); assumptions.push(r); return solve_(do_simp, turn_off_simp) == l_True; }
inline bool SimpSolver::solve (const vec<Lit>& assumps, bool do_simp, bool turn_off_simp){
budgetOff(); assumps.copyTo(assumptions); return solve_(do_simp, turn_off_simp) == l_True; }
inline lbool SimpSolver::solveLimited (const vec<Lit>& assumps, bool do_simp, bool turn_off_simp){
assumps.copyTo(assumptions); return solve_(do_simp, turn_off_simp); }
//=================================================================================================
}
#endif
| YosysHQ/yosys | libs/minisat/SimpSolver.h | C | isc | 10,801 |
<?php
/**
* this file is part of magerun
*
* @author Tom Klingenberg <https://github.com/ktomk>
*/
namespace N98\Util\Console\Helper\Table\Renderer;
use DOMDocument;
use DOMElement;
use DOMException;
use RuntimeException;
use Symfony\Component\Console\Output\OutputInterface;
/**
* Class XmlRenderer
*
* @package N98\Util\Console\Helper\Table\Renderer
*/
class XmlRenderer implements RendererInterface
{
const NAME_ROOT = 'table';
const NAME_ROW = 'row';
private $headers;
/**
* {@inheritdoc}
*/
public function render(OutputInterface $output, array $rows)
{
$dom = new DOMDocument('1.0', 'UTF-8');
$dom->formatOutput = true;
$rows && $this->setHeadersFrom($rows);
$table = $dom->createElement(self::NAME_ROOT);
/** @var DOMElement $table */
$table = $dom->appendChild($table);
$this->appendHeaders($table, $this->headers);
$this->appendRows($table, $rows);
/** @var $output \Symfony\Component\Console\Output\StreamOutput */
$output->write($dom->saveXML($dom, LIBXML_NOEMPTYTAG), false, $output::OUTPUT_RAW);
}
private function appendRows(DOMElement $parent, array $rows)
{
$doc = $parent->ownerDocument;
if (!$rows) {
$parent->appendChild($doc->createComment('intentionally left blank, the table is empty'));
return;
}
foreach ($rows as $fields) {
/** @var DOMElement $row */
$row = $parent->appendChild($doc->createElement(self::NAME_ROW));
$this->appendRowFields($row, $fields);
}
}
/**
* @param DOMElement $row
* @param array $fields
*/
private function appendRowFields(DOMElement $row, array $fields)
{
$index = 0;
foreach ($fields as $key => $value) {
$header = $this->getHeader($index++, $key);
$element = $this->createField($row->ownerDocument, $header, $value);
$row->appendChild($element);
}
}
/**
* @param DOMElement $parent
* @param array $headers
*/
private function appendHeaders(DOMElement $parent, array $headers = null)
{
if (!$headers) {
return;
}
$doc = $parent->ownerDocument;
$parent = $parent->appendChild($doc->createElement('headers'));
foreach ($headers as $header) {
$parent->appendChild($doc->createElement('header', $header));
}
}
/**
* create a DOMElement containing the data
*
* @param DOMDocument $doc
* @param string $key
* @param string $value
*
* @return DOMElement
*/
private function createField(DOMDocument $doc, $key, $value)
{
$name = $this->getName($key);
$base64 = !preg_match('//u', $value) || preg_match('/[\x0-\x8\xB-\xC\xE-\x1F]/', $value);
$node = $doc->createElement($name, $base64 ? base64_encode($value) : $value);
if ($base64) {
$node->setAttribute('encoding', 'base64');
}
return $node;
}
/**
* @param string $string
*
* @return string valid XML element name
*
* @throws DOMException if no valid XML Name can be generated
* @throws RuntimeException if character encoding is not US-ASCII or UTF-8
*/
private function getName($string)
{
$name = preg_replace("/[^a-z0-9]/ui", '_', $string);
if (null === $name) {
throw new RuntimeException(
sprintf(
'Encoding error, only US-ASCII and UTF-8 supported, can not process %s',
var_export($string, true)
)
);
}
try {
new DOMElement("$name");
} catch (DOMException $e) {
throw new DOMException(sprintf('Invalid name %s', var_export($name, true)));
}
return $name;
}
/**
* @param int $index zero-based
* @param mixed $default
*
* @return string
*/
private function getHeader($index, $default = null)
{
if (!isset($this->headers[$index])) {
return $default;
}
return $this->headers[$index];
}
/**
* @param array $rows
*
* @return void
*/
private function setHeadersFrom(array $rows)
{
$first = reset($rows);
if (is_array($first)) {
$this->headers = array_keys($first);
}
}
}
| tkn98/n98-magerun | src/N98/Util/Console/Helper/Table/Renderer/XmlRenderer.php | PHP | mit | 4,542 |
const fs = require('fs');
const _ = require('lodash');
const cache = require('./state/cache');
const broadcast = cache.get('broadcast');
const apiKeysFile = __dirname + '/../SECRET-api-keys.json';
// on init:
const noApiKeysFile = !fs.existsSync(apiKeysFile);
if(noApiKeysFile)
fs.writeFileSync(
apiKeysFile,
JSON.stringify({})
);
const apiKeys = JSON.parse( fs.readFileSync(apiKeysFile, 'utf8') );
module.exports = {
get: () => _.keys(apiKeys),
// note: overwrites if exists
add: (exchange, props) => {
apiKeys[exchange] = props;
fs.writeFileSync(apiKeysFile, JSON.stringify(apiKeys));
broadcast({
type: 'apiKeys',
exchanges: _.keys(apiKeys)
});
},
remove: exchange => {
if(!apiKeys[exchange])
return;
delete apiKeys[exchange];
fs.writeFileSync(apiKeysFile, JSON.stringify(apiKeys));
broadcast({
type: 'apiKeys',
exchanges: _.keys(apiKeys)
});
},
// retrieve api keys
// this cannot touch the frontend for security reaons.
_getApiKeyPair: key => apiKeys[key]
} | WXLWEB/gekko | web/apiKeyManager.js | JavaScript | mit | 1,067 |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>
Class: Concurrent::ErlangActor::EnvironmentConstants::Or
— Concurrent Ruby
</title>
<link rel="stylesheet" href="../../../css/style.css" type="text/css" />
<link rel="stylesheet" href="../../../css/common.css" type="text/css" />
<script type="text/javascript">
pathId = "Concurrent::ErlangActor::EnvironmentConstants::Or";
relpath = '../../../';
</script>
<script type="text/javascript" charset="utf-8" src="../../../js/jquery.js"></script>
<script type="text/javascript" charset="utf-8" src="../../../js/app.js"></script>
</head>
<body>
<div class="nav_wrap">
<iframe id="nav" src="../../../class_list.html?1"></iframe>
<div id="resizer"></div>
</div>
<div id="main" tabindex="-1">
<div id="header">
<div id="menu">
<a href="../../../_index.html">Index (O)</a> »
<span class='title'><span class='object_link'><a href="../../../Concurrent.html" title="Concurrent (module)">Concurrent</a></span></span> » <span class='title'><span class='object_link'><a href="../../ErlangActor.html" title="Concurrent::ErlangActor (module)">ErlangActor</a></span></span> » <span class='title'><span class='object_link'><a href="../EnvironmentConstants.html" title="Concurrent::ErlangActor::EnvironmentConstants (module)">EnvironmentConstants</a></span></span>
»
<span class="title">Or</span>
</div>
<div id="search">
<a class="full_list_link" id="class_list_link"
href="../../../class_list.html">
<svg width="24" height="24">
<rect x="0" y="4" width="24" height="4" rx="1" ry="1"></rect>
<rect x="0" y="12" width="24" height="4" rx="1" ry="1"></rect>
<rect x="0" y="20" width="24" height="4" rx="1" ry="1"></rect>
</svg>
</a>
</div>
<div class="clear"></div>
</div>
<div id="content"><h1>Class: Concurrent::ErlangActor::EnvironmentConstants::Or
</h1>
<div class="box_info">
<dl>
<dt>Inherits:</dt>
<dd>
<span class="inheritName"><span class='object_link'><a href="AbstractLogicOperationMatcher.html" title="Concurrent::ErlangActor::EnvironmentConstants::AbstractLogicOperationMatcher (class)">AbstractLogicOperationMatcher</a></span></span>
<ul class="fullTree">
<li>Object</li>
<li class="next"><span class='object_link'><a href="AbstractLogicOperationMatcher.html" title="Concurrent::ErlangActor::EnvironmentConstants::AbstractLogicOperationMatcher (class)">AbstractLogicOperationMatcher</a></span></li>
<li class="next">Concurrent::ErlangActor::EnvironmentConstants::Or</li>
</ul>
<a href="#" class="inheritanceTree">show all</a>
</dd>
</dl>
<dl>
<dt>Defined in:</dt>
<dd>lib/concurrent-ruby-edge/concurrent/edge/erlang_actor.rb</dd>
</dl>
</div>
<h2>Overview</h2><div class="docstring">
<div class="discussion">
<p>Combines matchers into one which matches if any matches.</p>
</div>
</div>
<div class="tags">
<div class="examples">
<p class="tag_title">Examples:</p>
<pre class="example code"><code><span class='const'>Or</span><span class='lbracket'>[</span><span class='const'>Symbol</span><span class='comma'>,</span> <span class='const'>String</span><span class='rbracket'>]</span> <span class='op'>===</span> <span class='symbol'>:v</span> <span class='comment'># => true
</span><span class='const'>Or</span><span class='lbracket'>[</span><span class='const'>Symbol</span><span class='comma'>,</span> <span class='const'>String</span><span class='rbracket'>]</span> <span class='op'>===</span> <span class='tstring'><span class='tstring_beg'>'</span><span class='tstring_content'>v</span><span class='tstring_end'>'</span></span> <span class='comment'># => true
</span><span class='const'>Or</span><span class='lbracket'>[</span><span class='const'>Symbol</span><span class='comma'>,</span> <span class='const'>String</span><span class='rbracket'>]</span> <span class='op'>===</span> <span class='int'>1</span> <span class='comment'># => false</span></code></pre>
</div>
</div>
<h2>
Instance Method Summary
<small><a href="#" class="summary_toggle">collapse</a></small>
</h2>
<ul class="summary">
<li class="public ">
<span class="summary_signature">
<a href="#===-instance_method" title="#=== (instance method)">#<strong>===</strong>(v) ⇒ true, false </a>
</span>
<span class="summary_desc"><div class='inline'></div></span>
</li>
</ul>
<div id="constructor_details" class="method_details_list">
<h2>Constructor Details</h2>
<p class="notice">This class inherits a constructor from <span class='object_link'><a href="AbstractLogicOperationMatcher.html#initialize-instance_method" title="Concurrent::ErlangActor::EnvironmentConstants::AbstractLogicOperationMatcher#initialize (method)">Concurrent::ErlangActor::EnvironmentConstants::AbstractLogicOperationMatcher</a></span></p>
</div>
<div id="instance_method_details" class="method_details_list">
<h2>Instance Method Details</h2>
<div class="method_details first">
<h3 class="signature first" id="===-instance_method">
#<strong>===</strong>(v) ⇒ <tt>true</tt>, <tt>false</tt>
</h3><div class="docstring">
<div class="discussion">
</div>
</div>
<div class="tags">
<p class="tag_title">Returns:</p>
<ul class="return">
<li>
<span class='type'>(<tt>true</tt>, <tt>false</tt>)</span>
</li>
</ul>
</div><table class="source_code">
<tr>
<td>
<pre class="lines">
618
619
620</pre>
</td>
<td>
<pre class="code"><span class="info file"># File 'lib/concurrent-ruby-edge/concurrent/edge/erlang_actor.rb', line 618</span>
<span class='kw'>def</span> <span class='op'>===</span><span class='lparen'>(</span><span class='id identifier rubyid_v'>v</span><span class='rparen'>)</span>
<span class='ivar'>@matchers</span><span class='period'>.</span><span class='id identifier rubyid_any?'>any?</span> <span class='lbrace'>{</span> <span class='op'>|</span><span class='id identifier rubyid_m'>m</span><span class='op'>|</span> <span class='id identifier rubyid_m'>m</span> <span class='op'>===</span> <span class='id identifier rubyid_v'>v</span> <span class='rbrace'>}</span>
<span class='kw'>end</span></pre>
</td>
</tr>
</table>
</div>
</div>
</div>
<div id="footer">
Generated by <a href="http://yardoc.org" title="Yay! A Ruby Documentation Tool" target="_blank">yard</a>.
</div>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-57940973-1', 'auto');
ga('send', 'pageview');
</script>
</div>
</body>
</html> | lucasallan/concurrent-ruby | docs/master/Concurrent/ErlangActor/EnvironmentConstants/Or.html | HTML | mit | 7,397 |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var locale = {
placeholder: 'Zeit auswählen'
};
exports['default'] = locale;
module.exports = exports['default']; | yhx0634/foodshopfront | node_modules/antd/lib/time-picker/locale/de_DE.js | JavaScript | mit | 200 |
import { ServerActions } from './ServerActions';
import { AuthTokenProvider } from './AuthTokenProvider';
import { RepoInfo } from './RepoInfo';
import { Query } from '../api/Query';
/**
* Firebase connection. Abstracts wire protocol and handles reconnecting.
*
* NOTE: All JSON objects sent to the realtime connection must have property names enclosed
* in quotes to make sure the closure compiler does not minify them.
*/
export declare class PersistentConnection extends ServerActions {
private repoInfo_;
private onDataUpdate_;
private onConnectStatus_;
private onServerInfoUpdate_;
private authTokenProvider_;
private authOverride_;
id: number;
private log_;
/** @private {Object} */
private interruptReasons_;
private listens_;
private outstandingPuts_;
private outstandingPutCount_;
private onDisconnectRequestQueue_;
private connected_;
private reconnectDelay_;
private maxReconnectDelay_;
private securityDebugCallback_;
lastSessionId: string | null;
/** @private {number|null} */
private establishConnectionTimer_;
/** @private {boolean} */
private visible_;
private requestCBHash_;
private requestNumber_;
/** @private {?{
* sendRequest(Object),
* close()
* }} */
private realtime_;
/** @private {string|null} */
private authToken_;
private forceTokenRefresh_;
private invalidAuthTokenCount_;
private firstConnection_;
private lastConnectionAttemptTime_;
private lastConnectionEstablishedTime_;
/**
* @private
*/
private static nextPersistentConnectionId_;
/**
* Counter for number of connections created. Mainly used for tagging in the logs
* @type {number}
* @private
*/
private static nextConnectionId_;
/**
* @implements {ServerActions}
* @param {!RepoInfo} repoInfo_ Data about the namespace we are connecting to
* @param {function(string, *, boolean, ?number)} onDataUpdate_ A callback for new data from the server
* @param onConnectStatus_
* @param onServerInfoUpdate_
* @param authTokenProvider_
* @param authOverride_
*/
constructor(repoInfo_: RepoInfo, onDataUpdate_: (a: string, b: any, c: boolean, d: number | null) => void, onConnectStatus_: (a: boolean) => void, onServerInfoUpdate_: (a: any) => void, authTokenProvider_: AuthTokenProvider, authOverride_?: Object | null);
/**
* @param {!string} action
* @param {*} body
* @param {function(*)=} onResponse
* @protected
*/
protected sendRequest(action: string, body: any, onResponse?: (a: any) => void): void;
/**
* @inheritDoc
*/
listen(query: Query, currentHashFn: () => string, tag: number | null, onComplete: (a: string, b: any) => void): void;
/**
* @param {!{onComplete(),
* hashFn():!string,
* query: !Query,
* tag: ?number}} listenSpec
* @private
*/
private sendListen_(listenSpec);
/**
* @param {*} payload
* @param {!Query} query
* @private
*/
private static warnOnListenWarnings_(payload, query);
/**
* @inheritDoc
*/
refreshAuthToken(token: string): void;
/**
* @param {!string} credential
* @private
*/
private reduceReconnectDelayIfAdminCredential_(credential);
/**
* Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like
* a auth revoked (the connection is closed).
*/
tryAuth(): void;
/**
* @inheritDoc
*/
unlisten(query: Query, tag: number | null): void;
private sendUnlisten_(pathString, queryId, queryObj, tag);
/**
* @inheritDoc
*/
onDisconnectPut(pathString: string, data: any, onComplete?: (a: string, b: string) => void): void;
/**
* @inheritDoc
*/
onDisconnectMerge(pathString: string, data: any, onComplete?: (a: string, b: string) => void): void;
/**
* @inheritDoc
*/
onDisconnectCancel(pathString: string, onComplete?: (a: string, b: string) => void): void;
private sendOnDisconnect_(action, pathString, data, onComplete);
/**
* @inheritDoc
*/
put(pathString: string, data: any, onComplete?: (a: string, b: string) => void, hash?: string): void;
/**
* @inheritDoc
*/
merge(pathString: string, data: any, onComplete: (a: string, b: string | null) => void, hash?: string): void;
putInternal(action: string, pathString: string, data: any, onComplete: (a: string, b: string | null) => void, hash?: string): void;
private sendPut_(index);
/**
* @inheritDoc
*/
reportStats(stats: {
[k: string]: any;
}): void;
/**
* @param {*} message
* @private
*/
private onDataMessage_(message);
private onDataPush_(action, body);
private onReady_(timestamp, sessionId);
private scheduleConnect_(timeout);
/**
* @param {boolean} visible
* @private
*/
private onVisible_(visible);
private onOnline_(online);
private onRealtimeDisconnect_();
private establishConnection_();
/**
* @param {string} reason
*/
interrupt(reason: string): void;
/**
* @param {string} reason
*/
resume(reason: string): void;
private handleTimestamp_(timestamp);
private cancelSentTransactions_();
/**
* @param {!string} pathString
* @param {Array.<*>=} query
* @private
*/
private onListenRevoked_(pathString, query?);
/**
* @param {!string} pathString
* @param {!string} queryId
* @return {{queries:Array.<Query>, onComplete:function(string)}}
* @private
*/
private removeListen_(pathString, queryId);
private onAuthRevoked_(statusCode, explanation);
private onSecurityDebugPacket_(body);
private restoreState_();
/**
* Sends client stats for first connection
* @private
*/
private sendConnectStats_();
/**
* @return {boolean}
* @private
*/
private shouldReconnect_();
}
| tipographo/tipographo.github.io | node_modules/@firebase/database/dist/src/core/PersistentConnection.d.ts | TypeScript | mit | 6,330 |
<!DOCTYPE html>
<html class="minimal">
<title>Canvas test: 2d.fillStyle.parse.invalid.name-3</title>
<script src="../tests.js"></script>
<link rel="stylesheet" href="../tests.css">
<link rel="prev" href="minimal.2d.fillStyle.parse.invalid.name-2.html" title="2d.fillStyle.parse.invalid.name-2">
<link rel="next" href="minimal.2d.fillStyle.parse.system.html" title="2d.fillStyle.parse.system">
<body>
<p id="passtext">Pass</p>
<p id="failtext">Fail</p>
<!-- TODO: handle "script did not run" case -->
<p class="output">These images should be identical:</p>
<canvas id="c" class="output" width="100" height="50"><p class="fallback">FAIL (fallback content)</p></canvas>
<p class="output expectedtext">Expected output:<p><img src="green-100x50.png" class="output expected" id="expected" alt="">
<ul id="d"></ul>
<script>
_addTest(function(canvas, ctx) {
ctx.fillStyle = '#0f0';
try { ctx.fillStyle = 'red blue'; } catch (e) { } // this shouldn't throw, but it shouldn't matter here if it does
ctx.fillRect(0, 0, 100, 50);
_assertPixel(canvas, 50,25, 0,255,0,255, "50,25", "0,255,0,255");
});
</script>
| corbanbrook/webgl-2d | test/philip.html5.org/tests/minimal.2d.fillStyle.parse.invalid.name-3.html | HTML | mit | 1,103 |
--TEST--
Bug #60227 (header() cannot detect the multi-line header with CR), \0 before \n
--FILE--
<?php
header("X-foo: e\n foo");
header("X-Foo6: e\0Set-Cookie: ID=\n123\n d");
echo 'foo';
?>
--EXPECTF--
Warning: Header may not contain NUL bytes in %s on line %d
foo
--EXPECTHEADERS--
X-foo: e
foo
| xhava/hippyvm | test_phpt/ext/standard/general_functions/bug60227_3.phpt | PHP | mit | 298 |
/*
* Copyright (C) 2014 MediaSift Ltd.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef SERVED_REQUEST_PARSER_IMPL_HPP
#define SERVED_REQUEST_PARSER_IMPL_HPP
#include <served/request_parser.hpp>
#include <served/request.hpp>
#include <sstream>
namespace served {
/*
* An implementation of a request parser.
*
* Responsible for moving sections of an incoming HTTP request to a served request object, and uses
* the headers and HTTP verb of the request to parse a body if one is expected.
*
* Call parse for each chunk of TCP data received, the parser will return a state that declares its
* current position through the HTTP response. If the state is EXPECT_CONTINUE then the client
* should be waiting for a 100 CONTINUE response before it will send its body.
*/
class request_parser_impl : public served::request_parser {
public:
enum status_type
{
ERROR = 0,
READ_HEADER,
EXPECT_CONTINUE,
READ_BODY,
FINISHED,
REJECTED_REQUEST_SIZE
};
private:
request & _request;
status_type _status;
size_t _body_expected;
std::stringstream _body_stream;
size_t _max_req_size_bytes;
size_t _bytes_parsed;
public:
/*
* Constructs a parser by giving it a reference to a request object to be modified.
*
* @param req the request object to be modified
* @param max_header_size_bytes the max size of an acceptable request, a value of 0 is ignored
*/
explicit request_parser_impl(request & req, size_t max_req_size_bytes = 0)
: served::request_parser()
, _request(req)
, _status(status_type::READ_HEADER)
, _body_expected(0)
, _body_stream()
, _max_req_size_bytes(max_req_size_bytes)
, _bytes_parsed(0)
{}
/*
* Parses a chunk of data into the request object and returns the current status of the parser.
*
* The status determines whether the parsing is complete, an error has occurred, the body is
* being read, or whether the client has requested a 100 CONTINUE response and is waiting.
*
* @return the new state of the parser
*/
status_type parse(const char *data, size_t len);
protected:
/*
* Converts a block of data into an HTTP request header and stores it in the request object.
*/
virtual void http_field(const char *data, const char *field, size_t flen,
const char *value, size_t vlen) override;
/*
* Converts a block of data into an HTTP method and stores it in the request object.
*/
virtual void request_method(const char *data, const char *at,
size_t length) override;
/*
* Converts a block of data into an HTTP request URI and stores it in the request object.
*/
virtual void request_uri(const char *data, const char *at,
size_t length) override;
/*
* Converts a block of data into a URL fragment and stores it in the request object.
*/
virtual void fragment(const char *data, const char *at,
size_t length) override;
/*
* Converts a block of data into a URL request path and stores it in the request object.
*/
virtual void request_path(const char *data, const char *at,
size_t length) override;
/*
* Converts a block of data into a URL query string and stores it in the request object.
*/
virtual void query_string(const char *data, const char *at,
size_t length) override;
/*
* Converts a block of data into an HTTP protocol and stores it in the request object.
*/
virtual void http_version(const char *data, const char *at,
size_t length) override;
/*
* Called when the parser has completed reading the HEADER of the request.
*
* Currently not used.
*/
virtual void header_done(const char *data, const char *at,
size_t length) override;
private:
/*
* Checks whether the request has sent an Expect: 100-continue header.
*
* Scans the HTTP verb and headers of the request object to find out if a body is possible
* and whether a 100-continue has been requested.
*
* Should be used after the HTTP header is fully parsed to determine whether to send a
* 100 CONTINUE response before waiting for more data.
*/
bool requested_continue();
/*
* Checks whether the request is sending a body.
*
* Scans the HTTP verb and headers of the request object to find out if a header should be
* expected, and how long the body will be.
*
* Should be used after the HTTP header is fully parsed to determine whether to wait for more
* data.
*
* @return the size of the expected body, or 0 if a body is not expected
*/
size_t expecting_body();
/*
* Parse a chunk of body.
*
* Continues to read the body of a request and returns the status of the parser.
*
* @return status_type of request_parser_impl, FINISHED indicates the body is fully read
*/
status_type parse_body(const char *data, size_t len);
};
} // served namespace
#endif // SERVED_REQUEST_PARSER_IMPL_HPP
| marekjm/served | src/served/request_parser_impl.hpp | C++ | mit | 5,847 |
package pluginerror
import "fmt"
// SSLValidationHostnameError replaces x509.HostnameError when the server has
// SSL certificate that does not match the hostname.
type SSLValidationHostnameError struct {
Message string
}
func (e SSLValidationHostnameError) Error() string {
return fmt.Sprintf("Hostname does not match SSL Certificate (%s)", e.Message)
}
| odlp/antifreeze | vendor/github.com/cloudfoundry/cli/api/plugin/pluginerror/ssl_validation_hostname_error.go | GO | mit | 360 |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.Zelig.CodeGeneration.IR
{
using System;
using System.Collections.Generic;
using Microsoft.Zelig.MetaData;
using Microsoft.Zelig.MetaData.Normalized;
using Microsoft.Zelig.Runtime.TypeSystem;
/////////////////////////////////////////////////////////////////////////////////////////////
//
// Method analysis:
//
// 1) Discover basic blocks (starting points: exception handlers and first bytecode).
// 2) Operators to zero-out all local variables.
// 3) Build state of evaluation stack, inferring types of every slot.
// 4) Convert the evaluation stack to variables.
// 5) Convert every bytecode to a set of operators (input: set of variables, output: a variable).
// 6) Optimize.
// 7) Code-generation.
//
public sealed partial class ByteCodeConverter
{
//
// State
//
private readonly TypeSystemForIR m_typeSystem;
private readonly ConversionContext m_context;
private readonly MethodRepresentation m_md;
private readonly MetaData.Normalized.SignatureType[] m_mdLocals;
private readonly Debugging.MethodDebugInfo m_mdDebugInfo;
private readonly Instruction[] m_instructions;
private readonly EHClause[] m_ehTable;
private List< ByteCodeBlock > m_byteCodeBlocks;
private ByteCodeBlock[] m_instructionToByteCodeBlock;
private object[] m_byteCodeArguments;
private TypeRepresentation[] m_localsTypes;
//
// Constructor Methods
//
public ByteCodeConverter( TypeSystemForIR typeSystem ,
ref ConversionContext context ,
MethodRepresentation md ,
MetaData.Normalized.SignatureType[] mdLocals ,
Debugging.MethodDebugInfo mdDebugInfo )
{
MetaDataMethodBase metadata = typeSystem.GetAssociatedMetaData( md );
m_typeSystem = typeSystem;
m_context = context;
m_md = md;
m_mdLocals = mdLocals;
m_mdDebugInfo = mdDebugInfo;
m_instructions = metadata.Instructions;
m_ehTable = metadata.EHTable;
}
//--//
public void PerformDelayedByteCodeAnalysis()
{
m_typeSystem.Report( "Converting byte code for {0}...", m_md );
BuildByteCodeBlocks( AnalyzeControlFlow() );
SetExceptionHandlingDomains();
PopulateBasicBlocks();
}
//--//
#region ExpandByteCodeArguments
public void ExpandByteCodeArguments()
{
int numInstructions = m_instructions.Length;
m_byteCodeArguments = new object[numInstructions];
for(int i = 0; i < numInstructions; i++)
{
object o = m_instructions[i].Argument;
if(o is MetaDataTypeDefinitionAbstract)
{
o = m_typeSystem.ConvertToIR( (MetaDataTypeDefinitionAbstract)o, m_context );
}
else if(o is MetaDataMethodAbstract)
{
o = m_typeSystem.ConvertToIR( (MetaDataMethodAbstract)o, m_context );
}
else if(o is MetaDataFieldAbstract)
{
o = m_typeSystem.ConvertToIR( null, (MetaDataFieldAbstract)o, m_context );
}
else if(o is MetaDataObject)
{
throw TypeConsistencyErrorException.Create( "Found unexpected metadata object {0} in method {1}", o, m_md );
}
m_byteCodeArguments[i] = o;
}
if(m_mdLocals != null)
{
m_localsTypes = new TypeRepresentation[m_mdLocals.Length];
//
// We need to convert the types of the local variables here, even if we don't keep the result around.
// The ByteCodeConverter will actually pass the values to the FlowGraphState object.
//
for(int i = 0; i < m_mdLocals.Length; i++)
{
m_localsTypes[i] = m_typeSystem.ConvertToIR( m_mdLocals[i].Type, m_context );
}
}
else
{
m_localsTypes = TypeRepresentation.SharedEmptyArray;
}
}
#endregion ExpandByteCodeArguments
//--//
#region AnalyzeControlFlow
private ByteCodeBlock.Flags[] AnalyzeControlFlow()
{
int numInstructions = m_instructions.Length;
ByteCodeBlock.Flags[] byteCodeBlockKinds = new ByteCodeBlock.Flags[numInstructions];
try
{
//
// The first instruction is for sure the start of a new basic block.
//
byteCodeBlockKinds[0] |= ByteCodeBlock.Flags.NormalEntryPoint;
for(int i = 0; i < m_ehTable.Length; i++)
{
byteCodeBlockKinds[ m_ehTable[i].HandlerOffset ] |= ByteCodeBlock.Flags.ExceptionHandlerEntryPoint;
//
// Force a basic block boundary on entry to a try block.
//
byteCodeBlockKinds[ m_ehTable[i].TryOffset ] |= ByteCodeBlock.Flags.JoinNode;
}
for(int outerIndex = 0; outerIndex < numInstructions; outerIndex++)
{
if(byteCodeBlockKinds[outerIndex] != 0 && (byteCodeBlockKinds[outerIndex] & ByteCodeBlock.Flags.Reached) == 0)
{
for(int innerIndex = outerIndex; (byteCodeBlockKinds[innerIndex] & ByteCodeBlock.Flags.Reached) == 0; innerIndex++)
{
byteCodeBlockKinds[innerIndex] |= ByteCodeBlock.Flags.Reached;
Instruction instr = m_instructions[innerIndex];
Instruction.OpcodeInfo oi = instr.Operator;
Instruction.OpcodeFlowControl ctrl = oi.Control;
if(ctrl != Instruction.OpcodeFlowControl.None)
{
switch(oi.OperandFormat)
{
case Instruction.OpcodeOperand.Branch:
{
int target = (int)instr.Argument;
byteCodeBlockKinds[innerIndex] |= ByteCodeBlock.Flags.BranchNode;
outerIndex = AnalyzeControlFlow_ProcessBranch( byteCodeBlockKinds, target, innerIndex, outerIndex );
}
break;
case Instruction.OpcodeOperand.Switch:
{
byteCodeBlockKinds[innerIndex] |= ByteCodeBlock.Flags.BranchNode;
foreach(int target in (int[])instr.Argument)
{
outerIndex = AnalyzeControlFlow_ProcessBranch( byteCodeBlockKinds, target, innerIndex, outerIndex );
}
}
break;
}
if(ctrl != Instruction.OpcodeFlowControl.ConditionalControl)
{
break;
}
}
}
}
}
for(int outerIndex = 0; outerIndex < numInstructions; outerIndex++)
{
if(byteCodeBlockKinds[outerIndex] == 0)
{
m_typeSystem.Report( "Unreachable bytecode {0} for {1}", m_instructions[outerIndex], m_md );
}
}
}
catch
{
throw TypeConsistencyErrorException.Create( "Invalid byte code for '{0}'", m_md );
}
return byteCodeBlockKinds;
}
private static int AnalyzeControlFlow_ProcessBranch( ByteCodeBlock.Flags[] byteCodeBlockKinds ,
int target ,
int innerIndex ,
int outerIndex )
{
byteCodeBlockKinds[target] |= ByteCodeBlock.Flags.JoinNode;
if(target < innerIndex)
{
byteCodeBlockKinds[target] |= ByteCodeBlock.Flags.BackEdge;
}
//
// Backtrack external loop.
//
if((byteCodeBlockKinds[target] & ByteCodeBlock.Flags.Reached) == 0 && outerIndex > target)
{
outerIndex = target - 1;
}
return outerIndex;
}
#endregion AnalyzeControlFlow
//--//
#region BuildByteCodeBlocks
private void BuildByteCodeBlocks( ByteCodeBlock.Flags[] byteCodeBlockKinds )
{
int numInstructions = m_instructions.Length;
ByteCodeBlock currentBCB = null;
m_byteCodeBlocks = new List<ByteCodeBlock>();
m_instructionToByteCodeBlock = new ByteCodeBlock[numInstructions];
for(int i = 0; i < numInstructions; i++)
{
if((byteCodeBlockKinds[i] & ByteCodeBlock.Flags.JoinNode) != 0)
{
currentBCB = null;
}
if(currentBCB == null)
{
currentBCB = BuildByteCodeBlocks_Fetch( i, byteCodeBlockKinds );
}
else
{
m_instructionToByteCodeBlock[i] = currentBCB;
}
Instruction instr = m_instructions[i];
bool fJoinWithNext = false;
currentBCB.IncrementInstructionCount();
switch(instr.Operator.OperandFormat)
{
case Instruction.OpcodeOperand.Branch:
{
int target = (int)instr.Argument;
BuildByteCodeBlocks_Link( currentBCB, target, byteCodeBlockKinds );
fJoinWithNext = (instr.Operator.Control == Instruction.OpcodeFlowControl.ConditionalControl);
}
break;
case Instruction.OpcodeOperand.Switch:
{
foreach(int target in (int[])instr.Argument)
{
BuildByteCodeBlocks_Link( currentBCB, target, byteCodeBlockKinds );
}
fJoinWithNext = (instr.Operator.Control == Instruction.OpcodeFlowControl.ConditionalControl);
}
break;
default:
{
if(instr.Operator.Control == Instruction.OpcodeFlowControl.None)
{
int target = i + 1;
if(target < numInstructions && (byteCodeBlockKinds[target] & ByteCodeBlock.Flags.JoinNode) != 0)
{
fJoinWithNext = true;
}
}
}
break;
}
if(fJoinWithNext)
{
BuildByteCodeBlocks_Link( currentBCB, i+1, byteCodeBlockKinds );
}
if((byteCodeBlockKinds[i] & ByteCodeBlock.Flags.BranchNode) != 0)
{
currentBCB = null;
}
}
}
private ByteCodeBlock BuildByteCodeBlocks_Fetch( int i ,
ByteCodeBlock.Flags[] byteCodeBlockKinds )
{
ByteCodeBlock current = m_instructionToByteCodeBlock[i];
if(current == null)
{
current = new ByteCodeBlock( byteCodeBlockKinds[i], i );
m_byteCodeBlocks.Add( current );
m_instructionToByteCodeBlock[i] = current;
}
return current;
}
private void BuildByteCodeBlocks_Link( ByteCodeBlock currentBCB ,
int target ,
ByteCodeBlock.Flags[] byteCodeBlockKinds )
{
ByteCodeBlock targetBCB = BuildByteCodeBlocks_Fetch( target, byteCodeBlockKinds );
targetBCB .SetPredecessor( currentBCB );
currentBCB.SetSuccessor ( targetBCB );
}
#endregion BuildByteCodeBlocks
//--//
#region SetExceptionHandlingDomains
private void SetExceptionHandlingDomains()
{
for(int i = 0; i < m_ehTable.Length; i++)
{
EHClause eh = m_ehTable[i];
ByteCodeBlock bcbLast = null;
ByteCodeBlock bcbHandler = m_instructionToByteCodeBlock[eh.HandlerOffset];
bcbHandler.SetAsHandlerFor( eh );
for(int j = eh.TryOffset; j < eh.TryEnd; j++)
{
ByteCodeBlock bcb = m_instructionToByteCodeBlock[j];
if(bcb != bcbLast)
{
bcb.SetProtectedBy( bcbHandler );
bcbLast = bcb;
}
}
}
}
#endregion SetExceptionHandlingDomains
//--//
//
// Access Methods
//
//--//
//
// Debug Methods
//
}
}
| smaillet-ms/llilum | Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/ByteCode/ByteCodeConverter.cs | C# | mit | 15,055 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Microsoft.Cci.Extensions.CSharp;
namespace Microsoft.Cci.Writers.CSharp
{
public partial class CSDeclarationWriter
{
private void WritePropertyDefinition(IPropertyDefinition property)
{
bool isInterfaceProp = property.ContainingTypeDefinition.IsInterface;
IMethodDefinition accessor = null;
IMethodDefinition getter = null;
IMethodDefinition setter = null;
if (property.Getter != null)
{
getter = property.Getter.ResolvedMethod;
if (!_filter.Include(getter))
getter = null;
accessor = getter;
}
if (property.Setter != null)
{
setter = property.Setter.ResolvedMethod;
if (!_filter.Include(setter))
setter = null;
if (accessor == null)
accessor = setter;
}
if (accessor == null)
return;
bool isIndexer = accessor.ParameterCount > (accessor == setter ? 1 : 0);
if (isIndexer)
{
string id = property.Name.Value;
int index = id.LastIndexOf(".");
if (index >= 0)
id = id.Substring(index + 1);
if (id != "Item")
{
WriteFakeAttribute("System.Runtime.CompilerServices.IndexerName", "\"" + id + "\"");
}
}
WriteAttributes(property.Attributes);
if (!isInterfaceProp)
{
if (!accessor.IsExplicitInterfaceMethod())
WriteVisibility(property.Visibility);
// Getter and Setter modifiers should be the same
WriteMethodModifiers(accessor);
}
if (property.GetHiddenBaseProperty(_filter) != Dummy.Property)
WriteKeyword("new");
if (property.ReturnValueIsByRef)
{
WriteKeyword("ref");
if (property.Attributes.HasIsReadOnlyAttribute())
WriteKeyword("readonly");
}
WriteTypeName(property.Type, isDynamic: IsDynamic(property.Attributes));
if (property.IsExplicitInterfaceProperty() && _forCompilationIncludeGlobalprefix)
Write("global::");
if (isIndexer)
{
int index = property.Name.Value.LastIndexOf(".");
if (index >= 0)
WriteIdentifier(property.Name.Value.Substring(0, index + 1) + "this", false); // +1 to include the '.'
else
WriteIdentifier("this", false);
var parameters = new List<IParameterDefinition>(accessor.Parameters);
if (accessor == setter) // If setter remove value parameter.
parameters.RemoveAt(parameters.Count - 1);
WriteParameters(parameters, property.ContainingType, true);
}
else
{
WriteIdentifier(property.Name);
}
WriteSpace();
WriteSymbol("{");
//get
if (getter != null)
{
WriteAccessorDefinition(property, getter, "get");
}
//set
if (setter != null)
{
WriteAccessorDefinition(property, setter, "set");
}
WriteSpace();
WriteSymbol("}");
}
private void WriteAccessorDefinition(IPropertyDefinition property, IMethodDefinition accessor, string accessorType)
{
WriteSpace();
WriteAttributes(accessor.Attributes, writeInline: true);
WriteAttributes(accessor.SecurityAttributes, writeInline: true);
// If the accessor is an internal call (or a PInvoke) we should put those attributes here as well
WriteMethodPseudoCustomAttributes(accessor);
if (accessor.Visibility != property.Visibility)
WriteVisibility(accessor.Visibility);
WriteKeyword(accessorType, noSpace: true);
WriteMethodBody(accessor);
}
}
}
| mmitche/buildtools | src/Microsoft.Cci.Extensions/Writers/CSharp/CSDeclarationWriter.Properties.cs | C# | mit | 4,516 |
#!/bin/sh
set -e
set -x
dd if=/dev/zero of=EMPTY bs=1M || :
rm EMPTY
| d-adler/packer-templates | scripts/vyos/minimize.sh | Shell | mit | 71 |
// Type definitions for babyparse
// Project: https://github.com/Rich-Harris/BabyParse
// Definitions by: Charles Parker <https://github.com/cdiddy77>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module BabyParse {
interface Static {
/**
* Parse a csv string or a csv file
*/
parse(csvString: string, config?: ParseConfig): ParseResult;
/**
* Unparses javascript data objects and returns a csv string
*/
unparse(data: Array<Object>, config?: UnparseConfig): string;
unparse(data: Array<Array<any>>, config?: UnparseConfig): string;
unparse(data: UnparseObject, config?: UnparseConfig): string;
/**
* Read-Only Properties
*/
// An array of characters that are not allowed as delimiters.
BAD_DELIMETERS: Array<string>;
// The true delimiter. Invisible. ASCII code 30. Should be doing the job we strangely rely upon commas and tabs for.
RECORD_SEP: string;
// Also sometimes used as a delimiting character. ASCII code 31.
UNIT_SEP: string;
// Whether or not the browser supports HTML5 Web Workers. If false, worker: true will have no effect.
WORKERS_SUPPORTED: boolean;
// The relative path to Papa Parse. This is automatically detected when Papa Parse is loaded synchronously.
SCRIPT_PATH: string;
/**
* Configurable Properties
*/
// The size in bytes of each file chunk. Used when streaming files obtained from the DOM that exist on the local computer. Default 10 MB.
LocalChunkSize: string;
// Same as LocalChunkSize, but for downloading files from remote locations. Default 5 MB.
RemoteChunkSize: string;
// The delimiter used when it is left unspecified and cannot be detected automatically. Default is comma.
DefaultDelimiter: string;
/**
* On Papa there are actually more classes exposed
* but none of them are officially documented
* Since we can interact with the Parser from one of the callbacks
* I have included the API for this class.
*/
Parser: ParserConstructor;
}
interface ParseConfig {
delimiter?: string; // default: ""
newline?: string; // default: ""
header?: boolean; // default: false
dynamicTyping?: boolean; // default: false
preview?: number; // default: 0
encoding?: string; // default: ""
worker?: boolean; // default: false
comments?: boolean; // default: false
download?: boolean; // default: false
skipEmptyLines?: boolean; // default: false
fastMode?: boolean; // default: undefined
// Callbacks
step?(results: ParseResult, parser: Parser): void; // default: undefined
complete?(results: ParseResult): void; // default: undefined
}
interface UnparseConfig {
quotes?: boolean|boolean[]; // default: false
delimiter?: string; // default: ","
newline?: string; // default: "\r\n"
}
interface UnparseObject {
fields: Array<any>;
data: string | Array<any>;
}
interface ParseError {
type: string; // A generalization of the error
code: string; // Standardized error code
message: string; // Human-readable details
row: number; // Row index of parsed data where error is
}
interface ParseMeta {
delimiter: string; // Delimiter used
linebreak: string; // Line break sequence used
aborted: boolean; // Whether process was aborted
fields: Array<string>; // Array of field names
truncated: boolean; // Whether preview consumed all input
}
/**
* @interface ParseResult
*
* data: is an array of rows. If header is false, rows are arrays; otherwise they are objects of data keyed by the field name.
* errors: is an array of errors
* meta: contains extra information about the parse, such as delimiter used, the newline sequence, whether the process was aborted, etc. Properties in this object are not guaranteed to exist in all situations
*/
interface ParseResult {
data: Array<any>;
errors: Array<ParseError>;
meta: ParseMeta;
}
interface ParserConstructor { new (config: ParseConfig): Parser; }
interface Parser {
// Parses the input
parse(input: string): any;
// Sets the abort flag
abort(): void;
// Gets the cursor position
getCharIndex(): number;
}
}
declare var Baby:BabyParse.Static;
declare module "babyparse"{
var Baby:BabyParse.Static;
export = Baby;
} | UzEE/DefinitelyTyped | babyparse/babyparse.d.ts | TypeScript | mit | 5,026 |
module Sass
# An exception class that keeps track of
# the line of the Sass template it was raised on
# and the Sass file that was being parsed (if applicable).
#
# All Sass errors are raised as {Sass::SyntaxError}s.
#
# When dealing with SyntaxErrors,
# it's important to provide filename and line number information.
# This will be used in various error reports to users, including backtraces;
# see \{#sass\_backtrace} for details.
#
# Some of this information is usually provided as part of the constructor.
# New backtrace entries can be added with \{#add\_backtrace},
# which is called when an exception is raised between files (e.g. with `@import`).
#
# Often, a chunk of code will all have similar backtrace information -
# the same filename or even line.
# It may also be useful to have a default line number set.
# In those situations, the default values can be used
# by omitting the information on the original exception,
# and then calling \{#modify\_backtrace} in a wrapper `rescue`.
# When doing this, be sure that all exceptions ultimately end up
# with the information filled in.
class SyntaxError < StandardError
# The backtrace of the error within Sass files.
# This is an array of hashes containing information for a single entry.
# The hashes have the following keys:
#
# `:filename`
# : The name of the file in which the exception was raised,
# or `nil` if no filename is available.
#
# `:mixin`
# : The name of the mixin in which the exception was raised,
# or `nil` if it wasn't raised in a mixin.
#
# `:line`
# : The line of the file on which the error occurred. Never nil.
#
# This information is also included in standard backtrace format
# in the output of \{#backtrace}.
#
# @return [Aray<{Symbol => Object>}]
attr_accessor :sass_backtrace
# The text of the template where this error was raised.
#
# @return [String]
attr_accessor :sass_template
# @param msg [String] The error message
# @param attrs [{Symbol => Object}] The information in the backtrace entry.
# See \{#sass\_backtrace}
def initialize(msg, attrs = {})
@message = msg
@sass_backtrace = []
add_backtrace(attrs)
end
# The name of the file in which the exception was raised.
# This could be `nil` if no filename is available.
#
# @return [String, nil]
def sass_filename
sass_backtrace.first[:filename]
end
# The name of the mixin in which the error occurred.
# This could be `nil` if the error occurred outside a mixin.
#
# @return [String]
def sass_mixin
sass_backtrace.first[:mixin]
end
# The line of the Sass template on which the error occurred.
#
# @return [Integer]
def sass_line
sass_backtrace.first[:line]
end
# Adds an entry to the exception's Sass backtrace.
#
# @param attrs [{Symbol => Object}] The information in the backtrace entry.
# See \{#sass\_backtrace}
def add_backtrace(attrs)
sass_backtrace << attrs.reject {|_k, v| v.nil?}
end
# Modify the top Sass backtrace entries
# (that is, the most deeply nested ones)
# to have the given attributes.
#
# Specifically, this goes through the backtrace entries
# from most deeply nested to least,
# setting the given attributes for each entry.
# If an entry already has one of the given attributes set,
# the pre-existing attribute takes precedence
# and is not used for less deeply-nested entries
# (even if they don't have that attribute set).
#
# @param attrs [{Symbol => Object}] The information to add to the backtrace entry.
# See \{#sass\_backtrace}
def modify_backtrace(attrs)
attrs = attrs.reject {|_k, v| v.nil?}
# Move backwards through the backtrace
(0...sass_backtrace.size).to_a.reverse_each do |i|
entry = sass_backtrace[i]
sass_backtrace[i] = attrs.merge(entry)
attrs.reject! {|k, _v| entry.include?(k)}
break if attrs.empty?
end
end
# @return [String] The error message
def to_s
@message
end
# Returns the standard exception backtrace,
# including the Sass backtrace.
#
# @return [Array<String>]
def backtrace
return nil if super.nil?
return super if sass_backtrace.all? {|h| h.empty?}
sass_backtrace.map do |h|
"#{h[:filename] || '(sass)'}:#{h[:line]}" +
(h[:mixin] ? ":in `#{h[:mixin]}'" : "")
end + super
end
# Returns a string representation of the Sass backtrace.
#
# @param default_filename [String] The filename to use for unknown files
# @see #sass_backtrace
# @return [String]
def sass_backtrace_str(default_filename = "an unknown file")
lines = message.split("\n")
msg = lines[0] + lines[1..-1].
map {|l| "\n" + (" " * "Error: ".size) + l}.join
"Error: #{msg}" +
Sass::Util.enum_with_index(sass_backtrace).map do |entry, i|
"\n #{i == 0 ? 'on' : 'from'} line #{entry[:line]}" +
" of #{entry[:filename] || default_filename}" +
(entry[:mixin] ? ", in `#{entry[:mixin]}'" : "")
end.join
end
class << self
# Returns an error report for an exception in CSS format.
#
# @param e [Exception]
# @param line_offset [Integer] The number of the first line of the Sass template.
# @return [String] The error report
# @raise [Exception] `e`, if the
# {file:SASS_REFERENCE.md#full_exception-option `:full_exception`} option
# is set to false.
def exception_to_css(e, line_offset = 1)
header = header_string(e, line_offset)
<<END
/*
#{header.gsub('*/', '*\\/')}
Backtrace:\n#{e.backtrace.join("\n").gsub('*/', '*\\/')}
*/
body:before {
white-space: pre;
font-family: monospace;
content: "#{header.gsub('"', '\"').gsub("\n", '\\A ')}"; }
END
end
private
def header_string(e, line_offset)
unless e.is_a?(Sass::SyntaxError) && e.sass_line && e.sass_template
return "#{e.class}: #{e.message}"
end
line_num = e.sass_line + 1 - line_offset
min = [line_num - 6, 0].max
section = e.sass_template.rstrip.split("\n")[min...line_num + 5]
return e.sass_backtrace_str if section.nil? || section.empty?
e.sass_backtrace_str + "\n\n" + Sass::Util.enum_with_index(section).
map {|line, i| "#{line_offset + min + i}: #{line}"}.join("\n")
end
end
end
# The class for Sass errors that are raised due to invalid unit conversions
# in SassScript.
class UnitConversionError < SyntaxError; end
end
| xvhfeng/blog-source | vendor/cache/ruby/2.4.0/gems/sass-3.4.24/lib/sass/error.rb | Ruby | mit | 6,777 |
$(document).ready(function() {
$('#servicio_ingreso').select2({
width: '60%',
placeholder:'Seleccione...',
allowClear:true
});
$("#fecha_inicio").datepicker().mask("99-99-9999");
$("#fecha_fin").datepicker().mask("99-99-9999");
$("#emitir_informe").click(function() {
if ($("#fecha_inicio").val() == '' || $("#fecha_fin").val() == '') {
($('#error')) ? $('#error').remove() : '';
var elem = $("<div id='error' title='Error de llenado'><center>" +
"Debe de seleccionar ambas fechas para generar el reporte."
+ "</center></div>");
elem.insertAfter($("#pacientesIngresados"));
$("#error").dialog({
close: function() {
if ($("#fecha_inicio").val() == '')
$("#fecha_inicio").focus();
else
$("#fecha_fin").focus();
}
});
} else if( $("#fecha_inicio").datepicker("getDate") > $("#fecha_fin").datepicker("getDate")){
($('#error')) ? $('#error').remove() : '';
var elem = $("<div id='error' title='Error de llenado'><center>" +
"La fecha de inicio debe de ser menor que la fecha fin."
+ "</center></div>");
elem.insertAfter($("#pacientesIngresados"));
$("#error").dialog({
close: function() {
$("#fecha_inicio").val('');
$("#fecha_fin").val('');
$("#fecha_inicio").focus();
}
});
} else {
$('#resultado').load(Routing.generate('buscar_ingresos_pacientes'), {'datos': $('#pacientesIngresados').serialize()});
}
return false;
});
$.getJSON(Routing.generate('get_servicios_hospitalarios_todos'),
function(data) {
$.each(data.especialidades, function(indice, aux) {
$('#servicio_ingreso').append('<option value="' + aux.id + '">' + aux.nombre + '</option>');
});
});
});
| jishisv/sipernes | web/bundles/minsalseguimiento/js/SecIngreso/reporte_list.js | JavaScript | mit | 2,150 |
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-error-$rootScope-inprog-production</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-app="app">
<button ng-click="focusInput = true">Focus</button>
<input ng-focus="count = count + 1" set-focus-if="focusInput" />
</body>
</html> | viral810/ngSimpleCMS | web/bundles/sunraangular/js/angular/angular-1.3.16/docs/examples/example-error-$rootScope-inprog/index-production.html | HTML | mit | 431 |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
/**
*
* Take a screenshot of the current viewport. To get the screenshot of the whole page
* use the action command `saveScreenshot`
*
* @returns {String} screenshot The screenshot as a base64 encoded PNG.
*
* @see https://w3c.github.io/webdriver/webdriver-spec.html#dfn-take-screenshot
* @type protocol
*
*/
var screenshot = function screenshot() {
return this.requestHandler.create('/session/:sessionId/screenshot');
};
exports.default = screenshot;
module.exports = exports['default'];
| deep0892/jitendrachatbot | node_modules/webdriverio/build/lib/protocol/screenshot.js | JavaScript | mit | 586 |
//---------------------------------------------------------------------------//
// Copyright (c) 2013 Kyle Lutz <[email protected]>
//
// Distributed under the Boost Software License, Version 1.0
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
// See http://boostorg.github.com/compute for more information.
//---------------------------------------------------------------------------//
#ifndef BOOST_COMPUTE_ALGORITHM_PARTITION_COPY_HPP
#define BOOST_COMPUTE_ALGORITHM_PARTITION_COPY_HPP
#include <boost/compute/system.hpp>
#include <boost/compute/functional.hpp>
#include <boost/compute/command_queue.hpp>
#include <boost/compute/algorithm/copy_if.hpp>
namespace boost {
namespace compute {
/// Copies all of the elements in the range [\p first, \p last) for which
/// \p predicate returns \c true to the range beginning at \p first_true
/// and all of the elements for which \p predicate returns \c false to
/// the range beginning at \p first_false.
///
/// \see partition()
template<class InputIterator,
class OutputIterator1,
class OutputIterator2,
class UnaryPredicate>
inline std::pair<OutputIterator1, OutputIterator2>
partition_copy(InputIterator first,
InputIterator last,
OutputIterator1 first_true,
OutputIterator2 first_false,
UnaryPredicate predicate,
command_queue &queue = system::default_queue())
{
// copy true values
OutputIterator1 last_true =
::boost::compute::copy_if(first,
last,
first_true,
predicate,
queue);
// copy false values
OutputIterator2 last_false =
::boost::compute::copy_if(first,
last,
first_false,
not1(predicate),
queue);
// return iterators to the end of the true and the false ranges
return std::make_pair(last_true, last_false);
}
} // end compute namespace
} // end boost namespace
#endif // BOOST_COMPUTE_ALGORITHM_PARTITION_COPY_HPP
| nginnever/zogminer | tests/deps/boost/compute/algorithm/partition_copy.hpp | C++ | mit | 2,316 |
/*
This file is part of Ext JS 4.2
Copyright (c) 2011-2013 Sencha Inc
Contact: http://www.sencha.com/contact
Commercial Usage
Licensees holding valid commercial licenses may use this file in accordance with the Commercial
Software License Agreement provided with the Software or, alternatively, in accordance with the
terms contained in a written agreement between you and Sencha.
If you are unsure which license is appropriate for your use, please contact the sales department
at http://www.sencha.com/contact.
Build date: 2013-09-18 17:18:59 (940c324ac822b840618a3a8b2b4b873f83a1a9b1)
*/
/**
* @class Ext.fx.Animator
*
* This class is used to run keyframe based animations, which follows the CSS3 based animation structure.
* Keyframe animations differ from typical from/to animations in that they offer the ability to specify values
* at various points throughout the animation.
*
* ## Using Keyframes
*
* The {@link #keyframes} option is the most important part of specifying an animation when using this
* class. A key frame is a point in a particular animation. We represent this as a percentage of the
* total animation duration. At each key frame, we can specify the target values at that time. Note that
* you *must* specify the values at 0% and 100%, the start and ending values. There is also a {@link #keyframe}
* event that fires after each key frame is reached.
*
* ## Example
*
* In the example below, we modify the values of the element at each fifth throughout the animation.
*
* @example
* Ext.create('Ext.fx.Animator', {
* target: Ext.getBody().createChild({
* style: {
* width: '100px',
* height: '100px',
* 'background-color': 'red'
* }
* }),
* duration: 10000, // 10 seconds
* keyframes: {
* 0: {
* opacity: 1,
* backgroundColor: 'FF0000'
* },
* 20: {
* x: 30,
* opacity: 0.5
* },
* 40: {
* x: 130,
* backgroundColor: '0000FF'
* },
* 60: {
* y: 80,
* opacity: 0.3
* },
* 80: {
* width: 200,
* y: 200
* },
* 100: {
* opacity: 1,
* backgroundColor: '00FF00'
* }
* }
* });
*/
Ext.define('Ext.fx.Animator', {
/* Begin Definitions */
mixins: {
observable: 'Ext.util.Observable'
},
requires: ['Ext.fx.Manager'],
/* End Definitions */
/**
* @property {Boolean} isAnimator
* `true` in this class to identify an object as an instantiated Animator, or subclass thereof.
*/
isAnimator: true,
/**
* @cfg {Number} duration
* Time in milliseconds for the animation to last. Defaults to 250.
*/
duration: 250,
/**
* @cfg {Number} delay
* Time to delay before starting the animation. Defaults to 0.
*/
delay: 0,
/* private used to track a delayed starting time */
delayStart: 0,
/**
* @cfg {Boolean} dynamic
* Currently only for Component Animation: Only set a component's outer element size bypassing layouts. Set to true to do full layouts for every frame of the animation. Defaults to false.
*/
dynamic: false,
/**
* @cfg {String} easing
*
* This describes how the intermediate values used during a transition will be calculated. It allows for a transition to change
* speed over its duration.
*
* - backIn
* - backOut
* - bounceIn
* - bounceOut
* - ease
* - easeIn
* - easeOut
* - easeInOut
* - elasticIn
* - elasticOut
* - cubic-bezier(x1, y1, x2, y2)
*
* Note that cubic-bezier will create a custom easing curve following the CSS3 [transition-timing-function][0]
* specification. The four values specify points P1 and P2 of the curve as (x1, y1, x2, y2). All values must
* be in the range [0, 1] or the definition is invalid.
*
* [0]: http://www.w3.org/TR/css3-transitions/#transition-timing-function_tag
*/
easing: 'ease',
/**
* Flag to determine if the animation has started
* @property running
* @type Boolean
*/
running: false,
/**
* Flag to determine if the animation is paused. Only set this to true if you need to
* keep the Anim instance around to be unpaused later; otherwise call {@link #end}.
* @property paused
* @type Boolean
*/
paused: false,
/**
* @private
*/
damper: 1,
/**
* @cfg {Number} iterations
* Number of times to execute the animation. Defaults to 1.
*/
iterations: 1,
/**
* Current iteration the animation is running.
* @property currentIteration
* @type Number
*/
currentIteration: 0,
/**
* Current keyframe step of the animation.
* @property keyframeStep
* @type Number
*/
keyframeStep: 0,
/**
* @private
*/
animKeyFramesRE: /^(from|to|\d+%?)$/,
/**
* @cfg {Ext.fx.target.Target} target
* The Ext.fx.target to apply the animation to. If not specified during initialization, this can be passed to the applyAnimator
* method to apply the same animation to many targets.
*/
/**
* @cfg {Object} keyframes
* Animation keyframes follow the CSS3 Animation configuration pattern. 'from' is always considered '0%' and 'to'
* is considered '100%'.<b>Every keyframe declaration must have a keyframe rule for 0% and 100%, possibly defined using
* "from" or "to"</b>. A keyframe declaration without these keyframe selectors is invalid and will not be available for
* animation. The keyframe declaration for a keyframe rule consists of properties and values. Properties that are unable to
* be animated are ignored in these rules, with the exception of 'easing' which can be changed at each keyframe. For example:
<pre><code>
keyframes : {
'0%': {
left: 100
},
'40%': {
left: 150
},
'60%': {
left: 75
},
'100%': {
left: 100
}
}
</code></pre>
*/
constructor: function(config) {
var me = this;
config = Ext.apply(me, config || {});
me.config = config;
me.id = Ext.id(null, 'ext-animator-');
me.addEvents(
/**
* @event beforeanimate
* Fires before the animation starts. A handler can return false to cancel the animation.
* @param {Ext.fx.Animator} this
*/
'beforeanimate',
/**
* @event keyframe
* Fires at each keyframe.
* @param {Ext.fx.Animator} this
* @param {Number} keyframe step number
*/
'keyframe',
/**
* @event afteranimate
* Fires when the animation is complete.
* @param {Ext.fx.Animator} this
* @param {Date} startTime
*/
'afteranimate'
);
me.mixins.observable.constructor.call(me, config);
me.timeline = [];
me.createTimeline(me.keyframes);
if (me.target) {
me.applyAnimator(me.target);
Ext.fx.Manager.addAnim(me);
}
},
/**
* @private
*/
sorter: function (a, b) {
return a.pct - b.pct;
},
/**
* @private
* Takes the given keyframe configuration object and converts it into an ordered array with the passed attributes per keyframe
* or applying the 'to' configuration to all keyframes. Also calculates the proper animation duration per keyframe.
*/
createTimeline: function(keyframes) {
var me = this,
attrs = [],
to = me.to || {},
duration = me.duration,
prevMs, ms, i, ln, pct, attr;
for (pct in keyframes) {
if (keyframes.hasOwnProperty(pct) && me.animKeyFramesRE.test(pct)) {
attr = {attrs: Ext.apply(keyframes[pct], to)};
// CSS3 spec allow for from/to to be specified.
if (pct == "from") {
pct = 0;
}
else if (pct == "to") {
pct = 100;
}
// convert % values into integers
attr.pct = parseInt(pct, 10);
attrs.push(attr);
}
}
// Sort by pct property
Ext.Array.sort(attrs, me.sorter);
// Only an end
//if (attrs[0].pct) {
// attrs.unshift({pct: 0, attrs: element.attrs});
//}
ln = attrs.length;
for (i = 0; i < ln; i++) {
prevMs = (attrs[i - 1]) ? duration * (attrs[i - 1].pct / 100) : 0;
ms = duration * (attrs[i].pct / 100);
me.timeline.push({
duration: ms - prevMs,
attrs: attrs[i].attrs
});
}
},
/**
* Applies animation to the Ext.fx.target
* @private
* @param target
* @type String/Object
*/
applyAnimator: function(target) {
var me = this,
anims = [],
timeline = me.timeline,
ln = timeline.length,
anim, easing, damper, attrs, i;
if (me.fireEvent('beforeanimate', me) !== false) {
for (i = 0; i < ln; i++) {
anim = timeline[i];
attrs = anim.attrs;
easing = attrs.easing || me.easing;
damper = attrs.damper || me.damper;
delete attrs.easing;
delete attrs.damper;
anim = new Ext.fx.Anim({
target: target,
easing: easing,
damper: damper,
duration: anim.duration,
paused: true,
to: attrs
});
anims.push(anim);
}
me.animations = anims;
me.target = anim.target;
for (i = 0; i < ln - 1; i++) {
anim = anims[i];
anim.nextAnim = anims[i + 1];
anim.on('afteranimate', function() {
this.nextAnim.paused = false;
});
anim.on('afteranimate', function() {
this.fireEvent('keyframe', this, ++this.keyframeStep);
}, me);
}
anims[ln - 1].on('afteranimate', function() {
this.lastFrame();
}, me);
}
},
/**
* @private
* Fires beforeanimate and sets the running flag.
*/
start: function(startTime) {
var me = this,
delay = me.delay,
delayStart = me.delayStart,
delayDelta;
if (delay) {
if (!delayStart) {
me.delayStart = startTime;
return;
}
else {
delayDelta = startTime - delayStart;
if (delayDelta < delay) {
return;
}
else {
// Compensate for frame delay;
startTime = new Date(delayStart.getTime() + delay);
}
}
}
if (me.fireEvent('beforeanimate', me) !== false) {
me.startTime = startTime;
me.running = true;
me.animations[me.keyframeStep].paused = false;
}
},
/**
* @private
* Perform lastFrame cleanup and handle iterations
* @returns a hash of the new attributes.
*/
lastFrame: function() {
var me = this,
iter = me.iterations,
iterCount = me.currentIteration;
iterCount++;
if (iterCount < iter) {
me.startTime = new Date();
me.currentIteration = iterCount;
me.keyframeStep = 0;
me.applyAnimator(me.target);
me.animations[me.keyframeStep].paused = false;
}
else {
me.currentIteration = 0;
me.end();
}
},
/**
* Fire afteranimate event and end the animation. Usually called automatically when the
* animation reaches its final frame, but can also be called manually to pre-emptively
* stop and destroy the running animation.
*/
end: function() {
var me = this;
me.fireEvent('afteranimate', me, me.startTime, new Date() - me.startTime);
},
isReady: function() {
return this.paused === false && this.running === false && this.iterations > 0;
},
isRunning: function() {
// Explicitly return false, we don't want to be run continuously by the manager
return false;
}
}); | rch/flask-openshift | wsgi/container/pkgs/sencha/static/ext-4.2.2.1144/src/fx/Animator.js | JavaScript | mit | 13,072 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Batch.Protocol.Models
{
using System.Linq;
/// <summary>
/// Specifies details of a Job Manager task.
/// </summary>
public partial class JobManagerTask
{
/// <summary>
/// Initializes a new instance of the JobManagerTask class.
/// </summary>
public JobManagerTask() { }
/// <summary>
/// Initializes a new instance of the JobManagerTask class.
/// </summary>
/// <param name="id">A string that uniquely identifies the Job Manager
/// taskwithin the job.</param>
/// <param name="commandLine">The command line of the Job Manager
/// task.</param>
/// <param name="displayName">The display name of the Job Manager
/// task.</param>
/// <param name="resourceFiles">A list of files that the Batch service
/// will download to the compute node before running the command
/// line.</param>
/// <param name="environmentSettings">A list of environment variable
/// settings for the Job Manager task.</param>
/// <param name="constraints">Constraints that apply to the Job Manager
/// task.</param>
/// <param name="killJobOnCompletion">Whether completion of the Job
/// Manager task signifies completion of the entire job.</param>
/// <param name="userIdentity">The user identity under which the Job
/// Manager task runs.</param>
/// <param name="runExclusive">Whether the Job Manager task requires
/// exclusive use of the compute node where it runs.</param>
/// <param name="applicationPackageReferences">A list of application
/// packages that the Batch service will deploy to the compute node
/// before running the command line.</param>
/// <param name="authenticationTokenSettings">The settings for an
/// authentication token that the task can use to perform Batch service
/// operations.</param>
public JobManagerTask(string id, string commandLine, string displayName = default(string), System.Collections.Generic.IList<ResourceFile> resourceFiles = default(System.Collections.Generic.IList<ResourceFile>), System.Collections.Generic.IList<EnvironmentSetting> environmentSettings = default(System.Collections.Generic.IList<EnvironmentSetting>), TaskConstraints constraints = default(TaskConstraints), bool? killJobOnCompletion = default(bool?), UserIdentity userIdentity = default(UserIdentity), bool? runExclusive = default(bool?), System.Collections.Generic.IList<ApplicationPackageReference> applicationPackageReferences = default(System.Collections.Generic.IList<ApplicationPackageReference>), AuthenticationTokenSettings authenticationTokenSettings = default(AuthenticationTokenSettings))
{
Id = id;
DisplayName = displayName;
CommandLine = commandLine;
ResourceFiles = resourceFiles;
EnvironmentSettings = environmentSettings;
Constraints = constraints;
KillJobOnCompletion = killJobOnCompletion;
UserIdentity = userIdentity;
RunExclusive = runExclusive;
ApplicationPackageReferences = applicationPackageReferences;
AuthenticationTokenSettings = authenticationTokenSettings;
}
/// <summary>
/// Gets or sets a string that uniquely identifies the Job Manager
/// taskwithin the job.
/// </summary>
/// <remarks>
/// The id can contain any combination of alphanumeric characters
/// including hyphens and underscores and cannot contain more than 64
/// characters.
/// </remarks>
[Newtonsoft.Json.JsonProperty(PropertyName = "id")]
public string Id { get; set; }
/// <summary>
/// Gets or sets the display name of the Job Manager task.
/// </summary>
/// <remarks>
/// It need not be unique and can contain any Unicode characters up to
/// a maximum length of 1024.
/// </remarks>
[Newtonsoft.Json.JsonProperty(PropertyName = "displayName")]
public string DisplayName { get; set; }
/// <summary>
/// Gets or sets the command line of the Job Manager task.
/// </summary>
/// <remarks>
/// The command line does not run under a shell, and therefore cannot
/// take advantage of shell features such as environment variable
/// expansion. If you want to take advantage of such features, you
/// should invoke the shell in the command line, for example using "cmd
/// /c MyCommand" in Windows or "/bin/sh -c MyCommand" in Linux.
/// </remarks>
[Newtonsoft.Json.JsonProperty(PropertyName = "commandLine")]
public string CommandLine { get; set; }
/// <summary>
/// Gets or sets a list of files that the Batch service will download
/// to the compute node before running the command line.
/// </summary>
/// <remarks>
/// Files listed under this element are located in the task's working
/// directory.
/// </remarks>
[Newtonsoft.Json.JsonProperty(PropertyName = "resourceFiles")]
public System.Collections.Generic.IList<ResourceFile> ResourceFiles { get; set; }
/// <summary>
/// Gets or sets a list of environment variable settings for the Job
/// Manager task.
/// </summary>
[Newtonsoft.Json.JsonProperty(PropertyName = "environmentSettings")]
public System.Collections.Generic.IList<EnvironmentSetting> EnvironmentSettings { get; set; }
/// <summary>
/// Gets or sets constraints that apply to the Job Manager task.
/// </summary>
[Newtonsoft.Json.JsonProperty(PropertyName = "constraints")]
public TaskConstraints Constraints { get; set; }
/// <summary>
/// Gets or sets whether completion of the Job Manager task signifies
/// completion of the entire job.
/// </summary>
/// <remarks>
/// If true, when the Job Manager task completes, the Batch service
/// marks the job as complete. If any tasks are still running at this
/// time (other than Job Release), those tasks are terminated. If
/// false, the completion of the Job Manager task does not affect the
/// job status. In this case, you should either use the
/// onAllTasksComplete attribute to terminate the job, or have a client
/// or user terminate the job explicitly. An example of this is if the
/// Job Manager creates a set of tasks but then takes no further role
/// in their execution. The default value is true. If you are using the
/// onAllTasksComplete and onTaskFailure attributes to control job
/// lifetime, and using the Job Manager task only to create the tasks
/// for the job (not to monitor progress), then it is important to set
/// killJobOnCompletion to false.
/// </remarks>
[Newtonsoft.Json.JsonProperty(PropertyName = "killJobOnCompletion")]
public bool? KillJobOnCompletion { get; set; }
/// <summary>
/// Gets or sets the user identity under which the Job Manager task
/// runs.
/// </summary>
/// <remarks>
/// If omitted, the task runs as a non-administrative user unique to
/// the task.
/// </remarks>
[Newtonsoft.Json.JsonProperty(PropertyName = "userIdentity")]
public UserIdentity UserIdentity { get; set; }
/// <summary>
/// Gets or sets whether the Job Manager task requires exclusive use of
/// the compute node where it runs.
/// </summary>
/// <remarks>
/// If true, no other tasks will run on the same compute node for as
/// long as the Job Manager is running. If false, other tasks can run
/// simultaneously with the Job Manager on a compute node. The Job
/// Manager task counts normally against the node's concurrent task
/// limit, so this is only relevant if the node allows multiple
/// concurrent tasks. The default value is true.
/// </remarks>
[Newtonsoft.Json.JsonProperty(PropertyName = "runExclusive")]
public bool? RunExclusive { get; set; }
/// <summary>
/// Gets or sets a list of application packages that the Batch service
/// will deploy to the compute node before running the command line.
/// </summary>
/// <remarks>
/// Application packages are downloaded and deployed to a shared
/// directory, not the task directory. Therefore, if a referenced
/// package is already on the compute node, and is up to date, then it
/// is not re-downloaded; the existing copy on the compute node is
/// used. If a referenced application package cannot be installed, for
/// example because the package has been deleted or because download
/// failed, the task fails with a scheduling error. This property is
/// currently not supported on jobs running on pools created using the
/// virtualMachineConfiguration (IaaS) property. If a task specifying
/// applicationPackageReferences runs on such a pool, it fails with a
/// scheduling error with code TaskSchedulingConstraintFailed.
/// </remarks>
[Newtonsoft.Json.JsonProperty(PropertyName = "applicationPackageReferences")]
public System.Collections.Generic.IList<ApplicationPackageReference> ApplicationPackageReferences { get; set; }
/// <summary>
/// Gets or sets the settings for an authentication token that the task
/// can use to perform Batch service operations.
/// </summary>
/// <remarks>
/// If this property is set, the Batch service provides the task with
/// an authentication token which can be used to authenticate Batch
/// service operations without requiring an account access key. The
/// token is provided via the AZ_BATCH_AUTHENTICATION_TOKEN environment
/// variable. The operations that the task can carry out using the
/// token depend on the settings. For example, a task can request job
/// permissions in order to add other tasks to the job, or check the
/// status of the job or of other tasks under the job.
/// </remarks>
[Newtonsoft.Json.JsonProperty(PropertyName = "authenticationTokenSettings")]
public AuthenticationTokenSettings AuthenticationTokenSettings { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (Id == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "Id");
}
if (CommandLine == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "CommandLine");
}
if (this.ResourceFiles != null)
{
foreach (var element in this.ResourceFiles)
{
if (element != null)
{
element.Validate();
}
}
}
if (this.EnvironmentSettings != null)
{
foreach (var element1 in this.EnvironmentSettings)
{
if (element1 != null)
{
element1.Validate();
}
}
}
if (this.ApplicationPackageReferences != null)
{
foreach (var element2 in this.ApplicationPackageReferences)
{
if (element2 != null)
{
element2.Validate();
}
}
}
}
}
}
| JasonYang-MSFT/azure-sdk-for-net | src/SDKs/Batch/dataPlane/Client/Src/Azure.Batch/GeneratedProtocol/Models/JobManagerTask.cs | C# | mit | 12,597 |
/*!
* OOUI v0.27.2
* https://www.mediawiki.org/wiki/OOUI
*
* Copyright 2011–2018 OOUI Team and other contributors.
* Released under the MIT license
* http://oojs.mit-license.org
*
* Date: 2018-06-06T16:16:14Z
*/
/**
* WikimediaUI Base v0.10.0
* Wikimedia Foundation user interface base variables
*/
.oo-ui-element-hidden {
display: none !important;
}
.oo-ui-buttonElement {
display: inline-block;
line-height: normal;
vertical-align: middle;
}
.oo-ui-buttonElement > .oo-ui-buttonElement-button {
cursor: pointer;
display: inline-block;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
vertical-align: middle;
font-family: inherit;
font-size: inherit;
white-space: nowrap;
-webkit-touch-callout: none;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.oo-ui-buttonElement > .oo-ui-buttonElement-button::-moz-focus-inner {
border-color: transparent;
padding: 0;
}
.oo-ui-buttonElement.oo-ui-widget-disabled > .oo-ui-buttonElement-button {
cursor: default;
}
.oo-ui-buttonElement-frameless {
position: relative;
}
.oo-ui-buttonElement-framed > .oo-ui-buttonElement-button {
vertical-align: top;
text-align: center;
}
.oo-ui-buttonElement > .oo-ui-buttonElement-button {
position: relative;
border-radius: 2px;
padding-top: 2.14285714em;
font-weight: bold;
text-decoration: none;
}
.oo-ui-buttonElement > .oo-ui-buttonElement-button:focus {
outline: 0;
}
.oo-ui-buttonElement > input.oo-ui-buttonElement-button {
-webkit-appearance: none;
}
.oo-ui-buttonElement.oo-ui-labelElement > .oo-ui-buttonElement-button {
line-height: 1;
}
.oo-ui-buttonElement.oo-ui-labelElement > input.oo-ui-buttonElement-button,
.oo-ui-buttonElement.oo-ui-labelElement > .oo-ui-buttonElement-button > .oo-ui-labelElement-label {
line-height: 1.07142857em;
}
.oo-ui-buttonElement.oo-ui-labelElement.oo-ui-indicatorElement > .oo-ui-buttonElement-button {
padding-right: 2.28571429em;
}
.oo-ui-buttonElement.oo-ui-iconElement .oo-ui-iconElement-icon,
.oo-ui-buttonElement.oo-ui-indicatorElement .oo-ui-indicatorElement-indicator {
-webkit-transform: translateZ(0);
transform: translateZ(0);
}
.oo-ui-buttonElement.oo-ui-indicatorElement.oo-ui-labelElement > .oo-ui-buttonElement-button > .oo-ui-indicatorElement-indicator,
.oo-ui-buttonElement.oo-ui-indicatorElement.oo-ui-iconElement > .oo-ui-buttonElement-button > .oo-ui-indicatorElement-indicator {
right: 0.85714286em;
}
.oo-ui-buttonElement.oo-ui-widget-enabled > .oo-ui-buttonElement-button {
-webkit-transition: background-color 100ms, color 100ms, border-color 100ms, box-shadow 100ms;
-moz-transition: background-color 100ms, color 100ms, border-color 100ms, box-shadow 100ms;
transition: background-color 100ms, color 100ms, border-color 100ms, box-shadow 100ms;
}
.oo-ui-buttonElement.oo-ui-widget-enabled > .oo-ui-buttonElement-button > .oo-ui-iconElement-icon,
.oo-ui-buttonElement.oo-ui-widget-enabled > .oo-ui-buttonElement-button > .oo-ui-indicatorElement-indicator {
opacity: 0.87;
-webkit-transition: opacity 100ms;
-moz-transition: opacity 100ms;
transition: opacity 100ms;
}
.oo-ui-buttonElement.oo-ui-widget-enabled > .oo-ui-buttonElement-button > .oo-ui-iconElement-icon.oo-ui-image-invert,
.oo-ui-buttonElement.oo-ui-widget-enabled > .oo-ui-buttonElement-button > .oo-ui-indicatorElement-indicator.oo-ui-image-invert {
opacity: 1;
}
.oo-ui-buttonElement.oo-ui-widget-enabled > .oo-ui-buttonElement-button:hover > .oo-ui-iconElement-icon,
.oo-ui-buttonElement.oo-ui-widget-enabled > .oo-ui-buttonElement-button:hover > .oo-ui-indicatorElement-indicator {
opacity: 0.73;
}
.oo-ui-buttonElement.oo-ui-widget-enabled > .oo-ui-buttonElement-button:hover > .oo-ui-iconElement-icon.oo-ui-image-invert,
.oo-ui-buttonElement.oo-ui-widget-enabled > .oo-ui-buttonElement-button:hover > .oo-ui-indicatorElement-indicator.oo-ui-image-invert {
opacity: 1;
}
.oo-ui-buttonElement.oo-ui-widget-enabled.oo-ui-buttonElement-pressed > .oo-ui-buttonElement-button > .oo-ui-iconElement-icon,
.oo-ui-buttonElement.oo-ui-widget-enabled.oo-ui-buttonElement-pressed > .oo-ui-buttonElement-button > .oo-ui-indicatorElement-indicator {
opacity: 1;
}
.oo-ui-buttonElement-frameless.oo-ui-iconElement:first-child {
margin-left: -0.42857143em;
}
.oo-ui-buttonElement-frameless.oo-ui-iconElement > .oo-ui-buttonElement-button {
min-width: 1.42857143em;
min-height: 1.42857143em;
border-color: #fff;
border-color: transparent;
border-style: solid;
border-width: 1px;
padding-top: 2.14285714em;
padding-left: 2.14285714em;
}
.oo-ui-buttonElement-frameless.oo-ui-iconElement > .oo-ui-buttonElement-button > .oo-ui-iconElement-icon {
left: 0.35714286em;
}
.oo-ui-buttonElement-frameless.oo-ui-labelElement:first-child {
margin-left: -0.14285714em;
}
.oo-ui-buttonElement-frameless.oo-ui-labelElement.oo-ui-iconElement:first-child {
margin-left: -0.42857143em;
}
.oo-ui-buttonElement-frameless.oo-ui-labelElement > .oo-ui-buttonElement-button {
border-color: #fff;
border-color: transparent;
border-style: solid;
border-width: 1px;
padding: 0.57142857em 0.14285714em 0.5em;
}
.oo-ui-buttonElement-frameless.oo-ui-labelElement.oo-ui-iconElement > .oo-ui-buttonElement-button {
padding-left: 2.14285714em;
}
.oo-ui-buttonElement-frameless.oo-ui-indicatorElement > .oo-ui-buttonElement-button {
min-width: 12px;
min-height: 12px;
padding-top: 0;
}
.oo-ui-buttonElement-frameless.oo-ui-indicatorElement.oo-ui-iconElement > .oo-ui-buttonElement-button {
padding-left: 3.85714286em;
padding-top: 2.14285714em;
}
.oo-ui-buttonElement-frameless.oo-ui-indicatorElement.oo-ui-labelElement > .oo-ui-buttonElement-button {
padding-left: 0.14285714em;
padding-top: 0.57142857em;
}
.oo-ui-buttonElement-frameless.oo-ui-indicatorElement.oo-ui-iconElement.oo-ui-labelElement > .oo-ui-buttonElement-button {
padding-left: 2.14285714em;
}
.oo-ui-buttonElement-frameless.oo-ui-widget-enabled > .oo-ui-buttonElement-button {
color: #222;
}
.oo-ui-buttonElement-frameless.oo-ui-widget-enabled > .oo-ui-buttonElement-button:hover {
color: #444;
}
.oo-ui-buttonElement-frameless.oo-ui-widget-enabled.oo-ui-iconElement > .oo-ui-buttonElement-button:focus,
.oo-ui-buttonElement-frameless.oo-ui-widget-enabled.oo-ui-labelElement > .oo-ui-buttonElement-button:focus {
border-color: #36c;
box-shadow: inset 0 0 0 1px #36c;
}
.oo-ui-buttonElement-frameless.oo-ui-widget-enabled.oo-ui-iconElement > .oo-ui-buttonElement-button:focus:active,
.oo-ui-buttonElement-frameless.oo-ui-widget-enabled.oo-ui-labelElement > .oo-ui-buttonElement-button:focus:active {
border-color: #fff;
border-color: transparent;
box-shadow: none;
}
.oo-ui-buttonElement-frameless.oo-ui-widget-enabled.oo-ui-indicatorElement:not( .oo-ui-iconElement ):not( .oo-ui-labelElement ) > .oo-ui-buttonElement-button {
border-radius: 1px;
}
.oo-ui-buttonElement-frameless.oo-ui-widget-enabled.oo-ui-indicatorElement:not( .oo-ui-iconElement ):not( .oo-ui-labelElement ) > .oo-ui-buttonElement-button:focus {
box-shadow: 0 0 0 2px #36c;
}
.oo-ui-buttonElement-frameless.oo-ui-widget-enabled.oo-ui-indicatorElement:not( .oo-ui-iconElement ):not( .oo-ui-labelElement ) > .oo-ui-buttonElement-button:focus:active {
box-shadow: none;
}
.oo-ui-buttonElement-frameless.oo-ui-widget-enabled.oo-ui-buttonElement-pressed > input.oo-ui-buttonElement-button,
.oo-ui-buttonElement-frameless.oo-ui-widget-enabled > .oo-ui-buttonElement-button:active {
color: #000;
border-color: #fff;
border-color: transparent;
box-shadow: none;
}
.oo-ui-buttonElement-frameless.oo-ui-widget-enabled.oo-ui-flaggedElement-progressive > .oo-ui-buttonElement-button {
color: #36c;
}
.oo-ui-buttonElement-frameless.oo-ui-widget-enabled.oo-ui-flaggedElement-progressive > .oo-ui-buttonElement-button:hover {
color: #447ff5;
}
.oo-ui-buttonElement-frameless.oo-ui-widget-enabled.oo-ui-flaggedElement-progressive > .oo-ui-buttonElement-button:active,
.oo-ui-buttonElement-frameless.oo-ui-widget-enabled.oo-ui-flaggedElement-progressive > .oo-ui-buttonElement-button:active:focus,
.oo-ui-buttonElement-frameless.oo-ui-widget-enabled.oo-ui-flaggedElement-progressive.oo-ui-buttonElement-pressed > .oo-ui-buttonElement-button {
color: #2a4b8d;
box-shadow: none;
}
.oo-ui-buttonElement-frameless.oo-ui-widget-enabled.oo-ui-flaggedElement-destructive > .oo-ui-buttonElement-button {
color: #d33;
}
.oo-ui-buttonElement-frameless.oo-ui-widget-enabled.oo-ui-flaggedElement-destructive > .oo-ui-buttonElement-button:hover {
color: #ff4242;
}
.oo-ui-buttonElement-frameless.oo-ui-widget-enabled.oo-ui-flaggedElement-destructive > .oo-ui-buttonElement-button:active,
.oo-ui-buttonElement-frameless.oo-ui-widget-enabled.oo-ui-flaggedElement-destructive > .oo-ui-buttonElement-button:active:focus,
.oo-ui-buttonElement-frameless.oo-ui-widget-enabled.oo-ui-flaggedElement-destructive.oo-ui-buttonElement-pressed > .oo-ui-buttonElement-button {
color: #b32424;
box-shadow: none;
}
.oo-ui-buttonElement-frameless.oo-ui-widget-enabled[class*='oo-ui-flaggedElement'] > .oo-ui-buttonElement-button > .oo-ui-iconElement-icon,
.oo-ui-buttonElement-frameless.oo-ui-widget-enabled[class*='oo-ui-flaggedElement'] > .oo-ui-buttonElement-button > .oo-ui-indicatorElement-indicator {
opacity: 1;
}
.oo-ui-buttonElement-frameless.oo-ui-widget-enabled[class*='oo-ui-flaggedElement'] > .oo-ui-buttonElement-button:hover > .oo-ui-iconElement-icon,
.oo-ui-buttonElement-frameless.oo-ui-widget-enabled[class*='oo-ui-flaggedElement'] > .oo-ui-buttonElement-button:hover > .oo-ui-indicatorElement-indicator {
opacity: 0.73;
}
.oo-ui-buttonElement-frameless.oo-ui-widget-disabled > .oo-ui-buttonElement-button {
color: #72777d;
}
.oo-ui-buttonElement-frameless.oo-ui-widget-disabled > .oo-ui-buttonElement-button > .oo-ui-iconElement-icon,
.oo-ui-buttonElement-frameless.oo-ui-widget-disabled > .oo-ui-buttonElement-button > .oo-ui-indicatorElement-indicator {
opacity: 0.51;
}
.oo-ui-buttonElement-framed > .oo-ui-buttonElement-button {
border-style: solid;
border-width: 1px;
border-radius: 2px;
padding-left: 0.85714286em;
padding-right: 0.85714286em;
}
.oo-ui-buttonElement-framed.oo-ui-iconElement > .oo-ui-buttonElement-button {
padding-top: 2.14285714em;
padding-bottom: 0;
padding-left: 2.14285714em;
}
.oo-ui-buttonElement-framed.oo-ui-iconElement > .oo-ui-buttonElement-button > .oo-ui-iconElement-icon {
left: 0.78571429em;
}
.oo-ui-buttonElement-framed.oo-ui-iconElement.oo-ui-labelElement > .oo-ui-buttonElement-button,
.oo-ui-buttonElement-framed.oo-ui-iconElement.oo-ui-indicatorElement > .oo-ui-buttonElement-button {
padding-left: 2.64285714em;
}
.oo-ui-buttonElement-framed.oo-ui-indicatorElement > .oo-ui-buttonElement-button {
padding-top: 2.14285714em;
padding-right: 2.14285714em;
padding-bottom: 0;
}
.oo-ui-buttonElement-framed.oo-ui-indicatorElement > .oo-ui-buttonElement-button > .oo-ui-indicatorElement-indicator {
right: 1.07142857em;
}
.oo-ui-buttonElement-framed.oo-ui-indicatorElement.oo-ui-labelElement > .oo-ui-buttonElement-button {
padding-right: 2.28571429em;
}
.oo-ui-buttonElement-framed.oo-ui-labelElement > .oo-ui-buttonElement-button {
padding-top: 0.57142857em;
padding-bottom: 0.5em;
}
.oo-ui-buttonElement-framed.oo-ui-widget-disabled > .oo-ui-buttonElement-button {
background-color: #c8ccd1;
color: #fff;
border-color: #c8ccd1;
}
.oo-ui-buttonElement-framed.oo-ui-widget-enabled > .oo-ui-buttonElement-button {
background-color: #f8f9fa;
color: #222;
border-color: #a2a9b1;
}
.oo-ui-buttonElement-framed.oo-ui-widget-enabled > .oo-ui-buttonElement-button:hover {
background-color: #fff;
color: #444;
border-color: #a2a9b1;
}
.oo-ui-buttonElement-framed.oo-ui-widget-enabled > .oo-ui-buttonElement-button:focus {
border-color: #36c;
box-shadow: inset 0 0 0 1px #36c;
}
.oo-ui-buttonElement-framed.oo-ui-widget-enabled > .oo-ui-buttonElement-button:active,
.oo-ui-buttonElement-framed.oo-ui-widget-enabled > .oo-ui-buttonElement-button:active:focus,
.oo-ui-buttonElement-framed.oo-ui-widget-enabled.oo-ui-buttonElement-pressed > .oo-ui-buttonElement-button {
background-color: #c8ccd1;
color: #000;
border-color: #72777d;
box-shadow: none;
}
.oo-ui-buttonElement-framed.oo-ui-widget-enabled.oo-ui-buttonElement-active > .oo-ui-buttonElement-button {
background-color: #2a4b8d;
color: #fff;
border-color: #2a4b8d;
}
.oo-ui-buttonElement-framed.oo-ui-widget-enabled.oo-ui-buttonElement-active > .oo-ui-buttonElement-button:focus {
border-color: #36c;
box-shadow: inset 0 0 0 1px #36c, inset 0 0 0 2px #fff;
}
.oo-ui-buttonElement-framed.oo-ui-widget-enabled.oo-ui-flaggedElement-progressive > .oo-ui-buttonElement-button {
color: #36c;
}
.oo-ui-buttonElement-framed.oo-ui-widget-enabled.oo-ui-flaggedElement-progressive > .oo-ui-buttonElement-button:hover {
background-color: #fff;
border-color: #447ff5;
}
.oo-ui-buttonElement-framed.oo-ui-widget-enabled.oo-ui-flaggedElement-progressive > .oo-ui-buttonElement-button:active,
.oo-ui-buttonElement-framed.oo-ui-widget-enabled.oo-ui-flaggedElement-progressive > .oo-ui-buttonElement-button:active:focus,
.oo-ui-buttonElement-framed.oo-ui-widget-enabled.oo-ui-flaggedElement-progressive.oo-ui-buttonElement-pressed > .oo-ui-buttonElement-button,
.oo-ui-buttonElement-framed.oo-ui-widget-enabled.oo-ui-flaggedElement-progressive.oo-ui-buttonElement-active > .oo-ui-buttonElement-button,
.oo-ui-buttonElement-framed.oo-ui-widget-enabled.oo-ui-flaggedElement-progressive.oo-ui-popupToolGroup-active > .oo-ui-buttonElement-button {
background-color: #eff3fa;
color: #2a4b8d;
border-color: #2a4b8d;
box-shadow: none;
}
.oo-ui-buttonElement-framed.oo-ui-widget-enabled.oo-ui-flaggedElement-progressive > .oo-ui-buttonElement-button:focus {
border-color: #36c;
box-shadow: inset 0 0 0 1px #36c;
}
.oo-ui-buttonElement-framed.oo-ui-widget-enabled.oo-ui-flaggedElement-destructive > .oo-ui-buttonElement-button {
color: #d73333;
}
.oo-ui-buttonElement-framed.oo-ui-widget-enabled.oo-ui-flaggedElement-destructive > .oo-ui-buttonElement-button:hover {
background-color: #fff;
border-color: #ff4242;
}
.oo-ui-buttonElement-framed.oo-ui-widget-enabled.oo-ui-flaggedElement-destructive > .oo-ui-buttonElement-button:active,
.oo-ui-buttonElement-framed.oo-ui-widget-enabled.oo-ui-flaggedElement-destructive > .oo-ui-buttonElement-button:active:focus,
.oo-ui-buttonElement-framed.oo-ui-widget-enabled.oo-ui-flaggedElement-destructive.oo-ui-buttonElement-pressed > .oo-ui-buttonElement-button,
.oo-ui-buttonElement-framed.oo-ui-widget-enabled.oo-ui-flaggedElement-destructive.oo-ui-buttonElement-active > .oo-ui-buttonElement-button,
.oo-ui-buttonElement-framed.oo-ui-widget-enabled.oo-ui-flaggedElement-destructive.oo-ui-popupToolGroup-active > .oo-ui-buttonElement-button {
background-color: #ffffff;
color: #b32424;
border-color: #b32424;
box-shadow: none;
}
.oo-ui-buttonElement-framed.oo-ui-widget-enabled.oo-ui-flaggedElement-destructive > .oo-ui-buttonElement-button:focus {
border-color: #d33;
box-shadow: inset 0 0 0 1px #d33;
}
.oo-ui-buttonElement-framed.oo-ui-widget-enabled.oo-ui-flaggedElement-primary.oo-ui-flaggedElement-progressive > .oo-ui-buttonElement-button {
color: #fff;
background-color: #36c;
border-color: #36c;
}
.oo-ui-buttonElement-framed.oo-ui-widget-enabled.oo-ui-flaggedElement-primary.oo-ui-flaggedElement-progressive > .oo-ui-buttonElement-button:hover {
background-color: #447ff5;
border-color: #447ff5;
}
.oo-ui-buttonElement-framed.oo-ui-widget-enabled.oo-ui-flaggedElement-primary.oo-ui-flaggedElement-progressive > .oo-ui-buttonElement-button:active,
.oo-ui-buttonElement-framed.oo-ui-widget-enabled.oo-ui-flaggedElement-primary.oo-ui-flaggedElement-progressive > .oo-ui-buttonElement-button:active:focus,
.oo-ui-buttonElement-framed.oo-ui-widget-enabled.oo-ui-flaggedElement-primary.oo-ui-flaggedElement-progressive.oo-ui-buttonElement-pressed > .oo-ui-buttonElement-button,
.oo-ui-buttonElement-framed.oo-ui-widget-enabled.oo-ui-flaggedElement-primary.oo-ui-flaggedElement-progressive.oo-ui-buttonElement-active > .oo-ui-buttonElement-button,
.oo-ui-buttonElement-framed.oo-ui-widget-enabled.oo-ui-flaggedElement-primary.oo-ui-flaggedElement-progressive.oo-ui-popupToolGroup-active > .oo-ui-buttonElement-button {
color: #fff;
background-color: #2a4b8d;
border-color: #2a4b8d;
box-shadow: none;
}
.oo-ui-buttonElement-framed.oo-ui-widget-enabled.oo-ui-flaggedElement-primary.oo-ui-flaggedElement-progressive > .oo-ui-buttonElement-button:focus {
border-color: #36c;
box-shadow: inset 0 0 0 1px #36c, inset 0 0 0 2px #fff;
}
.oo-ui-buttonElement-framed.oo-ui-widget-enabled.oo-ui-flaggedElement-primary.oo-ui-flaggedElement-destructive > .oo-ui-buttonElement-button {
color: #fff;
background-color: #d33;
border-color: #d33;
}
.oo-ui-buttonElement-framed.oo-ui-widget-enabled.oo-ui-flaggedElement-primary.oo-ui-flaggedElement-destructive > .oo-ui-buttonElement-button:hover {
background-color: #ff4242;
border-color: #ff4242;
}
.oo-ui-buttonElement-framed.oo-ui-widget-enabled.oo-ui-flaggedElement-primary.oo-ui-flaggedElement-destructive > .oo-ui-buttonElement-button:active,
.oo-ui-buttonElement-framed.oo-ui-widget-enabled.oo-ui-flaggedElement-primary.oo-ui-flaggedElement-destructive > .oo-ui-buttonElement-button:active:focus,
.oo-ui-buttonElement-framed.oo-ui-widget-enabled.oo-ui-flaggedElement-primary.oo-ui-flaggedElement-destructive.oo-ui-buttonElement-pressed > .oo-ui-buttonElement-button,
.oo-ui-buttonElement-framed.oo-ui-widget-enabled.oo-ui-flaggedElement-primary.oo-ui-flaggedElement-destructive.oo-ui-buttonElement-active > .oo-ui-buttonElement-button,
.oo-ui-buttonElement-framed.oo-ui-widget-enabled.oo-ui-flaggedElement-primary.oo-ui-flaggedElement-destructive.oo-ui-popupToolGroup-active > .oo-ui-buttonElement-button {
color: #fff;
background-color: #b32424;
border-color: #b32424;
box-shadow: none;
}
.oo-ui-buttonElement-framed.oo-ui-widget-enabled.oo-ui-flaggedElement-primary.oo-ui-flaggedElement-destructive > .oo-ui-buttonElement-button:focus {
border-color: #d33;
box-shadow: inset 0 0 0 1px #d33, inset 0 0 0 2px #fff;
}
.oo-ui-buttonElement-framed.oo-ui-widget-enabled.oo-ui-flaggedElement-primary > .oo-ui-buttonElement-button > .oo-ui-iconElement-icon,
.oo-ui-buttonElement-framed.oo-ui-widget-enabled.oo-ui-flaggedElement-primary > .oo-ui-buttonElement-button > .oo-ui-indicatorElement-indicator {
opacity: 1;
}
.oo-ui-clippableElement-clippable {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
min-height: 3.125em;
}
.oo-ui-floatableElement {
position: absolute;
}
.oo-ui-iconElement .oo-ui-iconElement-icon,
.oo-ui-iconElement.oo-ui-iconElement-icon {
background-size: contain;
background-position: center center;
background-repeat: no-repeat;
position: absolute;
top: 0;
min-width: 20px;
width: 1.42857143em;
min-height: 20px;
height: 100%;
}
.oo-ui-indicatorElement .oo-ui-indicatorElement-indicator,
.oo-ui-indicatorElement.oo-ui-indicatorElement-indicator {
background-size: contain;
background-position: center center;
background-repeat: no-repeat;
position: absolute;
top: 0;
min-width: 12px;
width: 0.85714286em;
min-height: 12px;
height: 100%;
}
.oo-ui-labelElement .oo-ui-labelElement-label,
.oo-ui-labelElement.oo-ui-labelElement-label {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.oo-ui-labelElement .oo-ui-labelElement-label {
line-height: 1.42857143em;
}
.oo-ui-labelElement .oo-ui-labelElement-label-highlight {
font-weight: bold;
}
.oo-ui-pendingElement-pending {
background-image: /* @embed */ url(themes/wikimediaui/images/textures/pending.gif);
}
.oo-ui-fieldLayout {
display: block;
margin-top: 1.14285714em;
}
.oo-ui-fieldLayout:before,
.oo-ui-fieldLayout:after {
content: ' ';
display: table;
}
.oo-ui-fieldLayout:after {
clear: both;
}
.oo-ui-fieldLayout.oo-ui-fieldLayout-align-left > .oo-ui-fieldLayout-body > .oo-ui-fieldLayout-header,
.oo-ui-fieldLayout.oo-ui-fieldLayout-align-right > .oo-ui-fieldLayout-body > .oo-ui-fieldLayout-header,
.oo-ui-fieldLayout.oo-ui-fieldLayout-align-left > .oo-ui-fieldLayout-body > .oo-ui-fieldLayout-help,
.oo-ui-fieldLayout.oo-ui-fieldLayout-align-right > .oo-ui-fieldLayout-body > .oo-ui-fieldLayout-help,
.oo-ui-fieldLayout.oo-ui-fieldLayout-align-left > .oo-ui-fieldLayout-body > .oo-ui-fieldLayout-field,
.oo-ui-fieldLayout.oo-ui-fieldLayout-align-right > .oo-ui-fieldLayout-body > .oo-ui-fieldLayout-field {
display: block;
float: left;
}
.oo-ui-fieldLayout.oo-ui-fieldLayout-align-right > .oo-ui-fieldLayout-body > .oo-ui-fieldLayout-header {
text-align: right;
}
.oo-ui-fieldLayout.oo-ui-fieldLayout-align-inline > .oo-ui-fieldLayout-body {
display: table;
width: 100%;
}
.oo-ui-fieldLayout.oo-ui-fieldLayout-align-inline > .oo-ui-fieldLayout-body > .oo-ui-fieldLayout-header,
.oo-ui-fieldLayout.oo-ui-fieldLayout-align-inline > .oo-ui-fieldLayout-body > .oo-ui-fieldLayout-field {
display: table-cell;
}
.oo-ui-fieldLayout.oo-ui-fieldLayout-align-inline > .oo-ui-fieldLayout-body > .oo-ui-fieldLayout-header {
vertical-align: middle;
}
.oo-ui-fieldLayout.oo-ui-fieldLayout-align-inline > .oo-ui-fieldLayout-body > .oo-ui-fieldLayout-field {
width: 1px;
vertical-align: top;
}
.oo-ui-fieldLayout.oo-ui-fieldLayout-align-top > .oo-ui-fieldLayout-body > .oo-ui-fieldLayout-header,
.oo-ui-fieldLayout.oo-ui-fieldLayout-align-top > .oo-ui-fieldLayout-body > .oo-ui-fieldLayout-field {
display: block;
}
.oo-ui-fieldLayout .oo-ui-fieldLayout-help {
float: right;
}
.oo-ui-fieldLayout .oo-ui-fieldLayout-help > .oo-ui-buttonElement-button > .oo-ui-labelElement-label {
display: block;
position: absolute !important;
/* stylelint-disable-line declaration-no-important */
clip: rect(1px, 1px, 1px, 1px);
width: 1px;
height: 1px;
margin: -1px;
border: 0;
padding: 0;
overflow: hidden;
}
.oo-ui-fieldLayout .oo-ui-fieldLayout-help > .oo-ui-popupWidget > .oo-ui-popupWidget-popup {
z-index: 1;
}
.oo-ui-fieldLayout.oo-ui-labelElement,
.oo-ui-fieldLayout.oo-ui-fieldLayout-align-inline {
margin-top: 0.85714286em;
}
.oo-ui-fieldLayout:first-child,
.oo-ui-fieldLayout.oo-ui-labelElement:first-child,
.oo-ui-fieldLayout.oo-ui-fieldLayout-align-inline:first-child {
margin-top: 0;
}
.oo-ui-fieldLayout.oo-ui-labelElement > .oo-ui-fieldLayout-body > .oo-ui-fieldLayout-header {
padding-bottom: 0.28571429em;
}
.oo-ui-fieldLayout.oo-ui-labelElement.oo-ui-fieldLayout-align-top > .oo-ui-fieldLayout-body > .oo-ui-fieldLayout-header,
.oo-ui-fieldLayout.oo-ui-labelElement.oo-ui-fieldLayout-align-inline > .oo-ui-fieldLayout-body {
max-width: 50em;
}
.oo-ui-fieldLayout.oo-ui-labelElement.oo-ui-fieldLayout-align-left > .oo-ui-fieldLayout-body > .oo-ui-fieldLayout-header,
.oo-ui-fieldLayout.oo-ui-labelElement.oo-ui-fieldLayout-align-right > .oo-ui-fieldLayout-body > .oo-ui-fieldLayout-header {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
width: 40%;
padding-right: 2.64285714em;
}
.oo-ui-fieldLayout.oo-ui-labelElement.oo-ui-fieldLayout-align-left > .oo-ui-fieldLayout-body > .oo-ui-fieldLayout-header > .oo-ui-labelElement-label,
.oo-ui-fieldLayout.oo-ui-labelElement.oo-ui-fieldLayout-align-right > .oo-ui-fieldLayout-body > .oo-ui-fieldLayout-header > .oo-ui-labelElement-label {
display: block;
padding-top: 0.28571429em;
}
.oo-ui-fieldLayout.oo-ui-labelElement.oo-ui-fieldLayout-align-left > .oo-ui-fieldLayout-body > .oo-ui-fieldLayout-help,
.oo-ui-fieldLayout.oo-ui-labelElement.oo-ui-fieldLayout-align-right > .oo-ui-fieldLayout-body > .oo-ui-fieldLayout-help {
margin-right: 0;
margin-left: -2.35714286em;
}
.oo-ui-fieldLayout.oo-ui-labelElement.oo-ui-fieldLayout-align-left > .oo-ui-fieldLayout-body > .oo-ui-fieldLayout-field,
.oo-ui-fieldLayout.oo-ui-labelElement.oo-ui-fieldLayout-align-right > .oo-ui-fieldLayout-body > .oo-ui-fieldLayout-field {
width: 60%;
}
.oo-ui-fieldLayout.oo-ui-labelElement.oo-ui-fieldLayout-align-inline > .oo-ui-fieldLayout-body > .oo-ui-fieldLayout-header {
padding-top: 0;
padding-bottom: 0;
padding-left: 0.42857143em;
}
.oo-ui-fieldLayout .oo-ui-fieldLayout-help {
margin-right: 0;
}
.oo-ui-fieldLayout .oo-ui-fieldLayout-help:last-child {
margin-right: 0;
}
.oo-ui-fieldLayout .oo-ui-fieldLayout-help .oo-ui-buttonElement-button {
padding-top: 1.42857143em;
padding-right: 0;
}
.oo-ui-fieldLayout.oo-ui-fieldLayout-align-top .oo-ui-fieldLayout-help,
.oo-ui-fieldLayout.oo-ui-fieldLayout-align-inline .oo-ui-fieldLayout-help {
margin-top: -0.42857143em;
margin-right: -0.57142857em;
margin-left: 0;
}
.oo-ui-fieldLayout-messages {
list-style: none none;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
max-width: 50em;
margin: 0;
padding: 0.28571429em 0.85714286em;
}
.oo-ui-fieldLayout-messages > li {
display: table;
margin: 0.28571429em 0 0;
padding: 0;
}
.oo-ui-fieldLayout-messages .oo-ui-iconElement.oo-ui-iconElement-icon {
display: table-cell;
position: static;
top: auto;
height: 1.42857143em;
}
.oo-ui-fieldLayout-messages .oo-ui-labelWidget {
display: table-cell;
padding-left: 0.42857143em;
vertical-align: middle;
}
.oo-ui-fieldLayout-disabled > .oo-ui-fieldLayout-body > .oo-ui-fieldLayout-header > .oo-ui-labelElement-label {
color: #72777d;
}
.oo-ui-actionFieldLayout-input,
.oo-ui-actionFieldLayout-button {
display: table-cell;
vertical-align: middle;
}
.oo-ui-actionFieldLayout-button {
width: 1%;
white-space: nowrap;
}
.oo-ui-actionFieldLayout.oo-ui-fieldLayout-align-top {
max-width: 50em;
}
.oo-ui-actionFieldLayout .oo-ui-actionFieldLayout-input .oo-ui-widget:not( .oo-ui-textInputWidget ) {
margin-right: 0.57142857em;
}
.oo-ui-actionFieldLayout .oo-ui-actionFieldLayout-input .oo-ui-widget.oo-ui-textInputWidget input {
border-radius: 2px 0 0 2px;
}
.oo-ui-actionFieldLayout .oo-ui-actionFieldLayout-input .oo-ui-widget.oo-ui-textInputWidget input:hover,
.oo-ui-actionFieldLayout .oo-ui-actionFieldLayout-input .oo-ui-widget.oo-ui-textInputWidget input:focus {
position: relative;
z-index: 1;
}
.oo-ui-actionFieldLayout .oo-ui-actionFieldLayout-button .oo-ui-buttonElement-framed {
border-radius: 0 2px 2px 0;
}
.oo-ui-actionFieldLayout .oo-ui-actionFieldLayout-button .oo-ui-buttonElement-framed > .oo-ui-buttonElement-button {
margin-left: -1px;
}
.oo-ui-actionFieldLayout .oo-ui-actionFieldLayout-button .oo-ui-buttonElement-frameless {
margin-left: 0.14285714em;
}
.oo-ui-fieldsetLayout {
position: relative;
min-width: 0;
margin: 0;
border: 0;
padding: 0.01px 0 0 0;
}
body:not( :-moz-handler-blocked ) .oo-ui-fieldsetLayout {
display: table-cell;
}
.oo-ui-fieldsetLayout > .oo-ui-fieldsetLayout-header {
display: none;
}
.oo-ui-fieldsetLayout.oo-ui-iconElement > .oo-ui-fieldsetLayout-header,
.oo-ui-fieldsetLayout.oo-ui-labelElement > .oo-ui-fieldsetLayout-header {
color: inherit;
display: inline-table;
box-sizing: border-box;
padding: 0;
white-space: normal;
float: left;
width: 100%;
}
.oo-ui-fieldsetLayout-group {
clear: both;
}
.oo-ui-fieldsetLayout .oo-ui-fieldsetLayout-help {
float: right;
}
.oo-ui-fieldsetLayout .oo-ui-fieldsetLayout-help > .oo-ui-buttonElement-button > .oo-ui-labelElement-label {
display: block;
position: absolute !important;
/* stylelint-disable-line declaration-no-important */
clip: rect(1px, 1px, 1px, 1px);
width: 1px;
height: 1px;
margin: -1px;
border: 0;
padding: 0;
overflow: hidden;
}
.oo-ui-fieldsetLayout .oo-ui-fieldsetLayout-help > .oo-ui-popupWidget > .oo-ui-popupWidget-popup {
z-index: 1;
}
.oo-ui-fieldsetLayout .oo-ui-fieldsetLayout-header {
max-width: 50em;
}
.oo-ui-fieldsetLayout .oo-ui-fieldsetLayout-header .oo-ui-iconElement-icon {
height: 1.42857143em;
}
.oo-ui-fieldsetLayout.oo-ui-iconElement > .oo-ui-fieldsetLayout-header .oo-ui-iconElement-icon {
display: block;
}
.oo-ui-fieldsetLayout + .oo-ui-fieldsetLayout,
.oo-ui-fieldsetLayout + .oo-ui-formLayout {
margin-top: 1.71428571em;
}
.oo-ui-fieldsetLayout.oo-ui-labelElement > .oo-ui-fieldsetLayout-header > .oo-ui-labelElement-label {
display: inline-block;
margin-bottom: 0.5em;
font-size: 1.14285714em;
font-weight: bold;
}
.oo-ui-fieldsetLayout.oo-ui-iconElement > .oo-ui-fieldsetLayout-header > .oo-ui-labelElement-label {
padding-left: 1.625em;
}
.oo-ui-fieldsetLayout .oo-ui-fieldsetLayout-help {
margin-right: 0;
margin-right: -0.57142857em;
}
.oo-ui-fieldsetLayout .oo-ui-fieldsetLayout-help:last-child {
margin-right: 0;
}
.oo-ui-fieldsetLayout .oo-ui-fieldsetLayout-help:last-child {
margin-right: -0.57142857em;
}
.oo-ui-fieldsetLayout .oo-ui-fieldsetLayout-help .oo-ui-buttonElement-button {
padding-top: 1.42857143em;
padding-right: 0;
}
.oo-ui-formLayout + .oo-ui-fieldsetLayout,
.oo-ui-formLayout + .oo-ui-formLayout {
margin-top: 1.71428571em;
}
.oo-ui-panelLayout {
position: relative;
}
.oo-ui-panelLayout-scrollable {
overflow: auto;
}
.oo-ui-panelLayout-expanded {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
.oo-ui-panelLayout-padded {
padding: 1.14285714em;
}
.oo-ui-panelLayout-padded.oo-ui-formLayout > .oo-ui-fieldsetLayout .oo-ui-labelElement-label,
.oo-ui-panelLayout-padded.oo-ui-formLayout > .oo-ui-fieldsetLayout .oo-ui-iconElement-icon {
margin-top: -0.42857143em;
}
.oo-ui-panelLayout-framed {
border: 1px solid #a2a9b1;
border-radius: 2px;
}
.oo-ui-panelLayout-padded.oo-ui-panelLayout-framed {
margin: 0.85714286em 0;
}
.oo-ui-horizontalLayout > .oo-ui-widget {
display: inline-block;
vertical-align: middle;
}
.oo-ui-horizontalLayout > .oo-ui-layout {
display: inline-block;
}
.oo-ui-horizontalLayout > .oo-ui-layout,
.oo-ui-horizontalLayout > .oo-ui-widget {
margin-right: 0.5em;
}
.oo-ui-horizontalLayout > .oo-ui-layout:last-child,
.oo-ui-horizontalLayout > .oo-ui-widget:last-child {
margin-right: 0;
}
.oo-ui-horizontalLayout > .oo-ui-layout {
margin-top: 0;
}
.oo-ui-horizontalLayout > .oo-ui-widget {
margin-bottom: 0.5em;
}
.oo-ui-widget .oo-ui-iconElement-icon,
.oo-ui-widget .oo-ui-indicatorElement-indicator,
.oo-ui-widget.oo-ui-iconElement .oo-ui-widget .oo-ui-iconElement-icon,
.oo-ui-widget.oo-ui-indicatorElement .oo-ui-widget .oo-ui-indicatorElement-indicator {
display: none;
}
.oo-ui-widget.oo-ui-iconElement .oo-ui-iconElement-icon,
.oo-ui-widget.oo-ui-iconElement > * > .oo-ui-iconElement-icon,
.oo-ui-widget.oo-ui-iconElement .oo-ui-iconElement .oo-ui-iconElement-icon,
.oo-ui-widget.oo-ui-indicatorElement > .oo-ui-indicatorElement-indicator,
.oo-ui-widget.oo-ui-indicatorElement > * > .oo-ui-indicatorElement-indicator,
.oo-ui-widget.oo-ui-indicatorElement .oo-ui-indicatorElement .oo-ui-indicatorElement-indicator {
display: block;
}
.oo-ui-optionWidget {
position: relative;
display: block;
}
.oo-ui-optionWidget.oo-ui-widget-enabled {
cursor: pointer;
}
.oo-ui-optionWidget.oo-ui-widget-disabled {
cursor: default;
}
.oo-ui-optionWidget.oo-ui-labelElement > .oo-ui-labelElement-label {
display: block;
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
}
.oo-ui-optionWidget-selected .oo-ui-buttonElement-button > .oo-ui-iconElement-icon {
opacity: 1;
}
.oo-ui-optionWidget.oo-ui-widget-disabled {
color: #72777d;
}
.oo-ui-decoratedOptionWidget {
padding: 0.64285714em 0.85714286em 0.57142857em;
line-height: 1;
}
.oo-ui-decoratedOptionWidget.oo-ui-iconElement {
padding-left: 2.64285714em;
}
.oo-ui-decoratedOptionWidget.oo-ui-iconElement .oo-ui-iconElement-icon {
left: 0.78571429em;
}
.oo-ui-decoratedOptionWidget .oo-ui-labelElement-label {
line-height: 1.07142857em;
}
.oo-ui-decoratedOptionWidget.oo-ui-indicatorElement {
padding-right: 2.28571429em;
}
.oo-ui-decoratedOptionWidget.oo-ui-indicatorElement .oo-ui-indicatorElement-indicator {
right: 0.85714286em;
}
.oo-ui-decoratedOptionWidget.oo-ui-widget-enabled:hover .oo-ui-iconElement-icon,
.oo-ui-decoratedOptionWidget.oo-ui-widget-enabled:hover .oo-ui-indicatorElement-indicator {
opacity: 0.73;
}
.oo-ui-decoratedOptionWidget.oo-ui-widget-enabled .oo-ui-iconElement-icon,
.oo-ui-decoratedOptionWidget.oo-ui-widget-enabled .oo-ui-indicatorElement-indicator {
opacity: 0.87;
-webkit-transition: opacity 100ms;
-moz-transition: opacity 100ms;
transition: opacity 100ms;
}
.oo-ui-decoratedOptionWidget.oo-ui-widget-disabled .oo-ui-iconElement-icon,
.oo-ui-decoratedOptionWidget.oo-ui-widget-disabled .oo-ui-indicatorElement-indicator {
opacity: 0.51;
}
.oo-ui-radioSelectWidget:focus {
outline: 0;
}
.oo-ui-radioSelectWidget:focus [type='radio']:checked + span:before {
border-color: #fff;
}
.oo-ui-radioOptionWidget {
display: table;
width: 100%;
padding: 0.28571429em 0;
}
.oo-ui-radioOptionWidget .oo-ui-radioInputWidget,
.oo-ui-radioOptionWidget.oo-ui-labelElement > .oo-ui-labelElement-label {
display: table-cell;
vertical-align: top;
}
.oo-ui-radioOptionWidget .oo-ui-radioInputWidget {
width: 1px;
}
.oo-ui-radioOptionWidget.oo-ui-labelElement > .oo-ui-labelElement-label {
white-space: normal;
}
.oo-ui-radioOptionWidget.oo-ui-labelElement .oo-ui-labelElement-label {
padding-left: 0.42857143em;
}
.oo-ui-radioOptionWidget .oo-ui-radioInputWidget {
margin-right: 0;
}
.oo-ui-labelWidget {
display: inline-block;
}
.oo-ui-labelWidget.oo-ui-inline-help {
display: block;
color: #54595d;
font-size: 0.92857143em;
}
.oo-ui-iconWidget {
display: inline-block;
vertical-align: middle;
line-height: 2.5;
}
.oo-ui-iconWidget.oo-ui-iconElement.oo-ui-iconElement-icon {
display: inline-block;
position: static;
top: auto;
height: 1.42857143em;
}
.oo-ui-iconWidget.oo-ui-widget-disabled {
opacity: 0.51;
}
.oo-ui-indicatorWidget {
display: inline-block;
vertical-align: middle;
line-height: 2.5;
margin: 0.42857143em;
}
.oo-ui-indicatorWidget.oo-ui-indicatorElement.oo-ui-indicatorElement-indicator {
display: inline-block;
position: static;
top: auto;
height: 0.85714286em;
}
.oo-ui-indicatorWidget.oo-ui-widget-disabled {
opacity: 0.51;
}
.oo-ui-buttonWidget {
margin-right: 0.5em;
}
.oo-ui-buttonWidget:last-child {
margin-right: 0;
}
.oo-ui-buttonGroupWidget {
display: inline-block;
white-space: nowrap;
border-radius: 2px;
margin-right: 0.5em;
z-index: 0;
position: relative;
}
.oo-ui-buttonGroupWidget .oo-ui-buttonWidget.oo-ui-buttonElement-active .oo-ui-buttonElement-button {
cursor: default;
}
.oo-ui-buttonGroupWidget:last-child {
margin-right: 0;
}
.oo-ui-buttonGroupWidget .oo-ui-buttonElement {
margin-right: 0;
z-index: 0;
}
.oo-ui-buttonGroupWidget .oo-ui-buttonElement:last-child {
margin-right: 0;
}
.oo-ui-buttonGroupWidget .oo-ui-buttonElement-framed .oo-ui-buttonElement-button {
margin-left: -1px;
border-radius: 0;
}
.oo-ui-buttonGroupWidget .oo-ui-buttonElement-framed:first-child .oo-ui-buttonElement-button {
margin-left: 0;
border-bottom-left-radius: 2px;
border-top-left-radius: 2px;
}
.oo-ui-buttonGroupWidget .oo-ui-buttonElement-framed:last-child .oo-ui-buttonElement-button {
border-bottom-right-radius: 2px;
border-top-right-radius: 2px;
}
.oo-ui-buttonGroupWidget .oo-ui-buttonElement-framed.oo-ui-widget-disabled + .oo-ui-widget-disabled > .oo-ui-buttonElement-button {
border-left-color: #fff;
}
.oo-ui-buttonGroupWidget.oo-ui-widget-enabled .oo-ui-buttonElement.oo-ui-widget-enabled > .oo-ui-buttonElement-button:active {
z-index: 1;
}
.oo-ui-buttonGroupWidget.oo-ui-widget-enabled .oo-ui-buttonElement.oo-ui-widget-enabled > .oo-ui-buttonElement-button:focus {
z-index: 2;
}
.oo-ui-buttonGroupWidget.oo-ui-widget-enabled .oo-ui-buttonElement.oo-ui-buttonElement-active > .oo-ui-buttonElement-button {
z-index: 3;
}
.oo-ui-buttonGroupWidget.oo-ui-widget-enabled .oo-ui-buttonElement.oo-ui-widget-disabled > .oo-ui-buttonElement-button {
z-index: -1;
}
.oo-ui-buttonGroupWidget.oo-ui-widget-enabled .oo-ui-buttonElement.oo-ui-toggleWidget-on + .oo-ui-toggleWidget-on > .oo-ui-buttonElement-button,
.oo-ui-buttonGroupWidget.oo-ui-widget-enabled .oo-ui-buttonElement.oo-ui-toggleWidget-on + .oo-ui-toggleWidget-on > .oo-ui-buttonElement-button:active {
border-left-color: #a2a9b1;
z-index: 3;
}
.oo-ui-popupWidget {
position: absolute;
}
.oo-ui-popupWidget-popup {
position: relative;
overflow: hidden;
z-index: 1;
}
.oo-ui-popupWidget-anchor {
display: none;
z-index: 1;
}
.oo-ui-popupWidget-anchored .oo-ui-popupWidget-anchor {
display: block;
position: absolute;
background-repeat: no-repeat;
}
.oo-ui-popupWidget-anchored .oo-ui-popupWidget-anchor:before,
.oo-ui-popupWidget-anchored .oo-ui-popupWidget-anchor:after {
content: '';
position: absolute;
width: 0;
height: 0;
border-style: solid;
border-color: transparent;
}
.oo-ui-popupWidget-anchored-top .oo-ui-popupWidget-anchor {
left: 0;
}
.oo-ui-popupWidget-anchored-top .oo-ui-popupWidget-anchor:before,
.oo-ui-popupWidget-anchored-top .oo-ui-popupWidget-anchor:after {
border-top: 0;
}
.oo-ui-popupWidget-anchored-bottom .oo-ui-popupWidget-anchor {
left: 0;
}
.oo-ui-popupWidget-anchored-bottom .oo-ui-popupWidget-anchor:before,
.oo-ui-popupWidget-anchored-bottom .oo-ui-popupWidget-anchor:after {
border-bottom: 0;
}
.oo-ui-popupWidget-anchored-start .oo-ui-popupWidget-anchor {
top: 0;
}
.oo-ui-popupWidget-anchored-start .oo-ui-popupWidget-anchor:before,
.oo-ui-popupWidget-anchored-start .oo-ui-popupWidget-anchor:after {
border-left: 0;
}
.oo-ui-popupWidget-anchored-end .oo-ui-popupWidget-anchor {
top: 0;
}
.oo-ui-popupWidget-anchored-end .oo-ui-popupWidget-anchor:before,
.oo-ui-popupWidget-anchored-end .oo-ui-popupWidget-anchor:after {
border-right: 0;
}
.oo-ui-popupWidget-head {
-webkit-touch-callout: none;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.oo-ui-popupWidget-head > .oo-ui-buttonWidget {
position: absolute;
}
.oo-ui-popupWidget-head > .oo-ui-labelElement-label {
float: left;
cursor: default;
}
.oo-ui-popupWidget-body {
clear: both;
}
.oo-ui-popupWidget-body.oo-ui-clippableElement-clippable {
min-height: 1em;
}
.oo-ui-popupWidget-popup {
background-color: #fff;
border: 1px solid #a2a9b1;
border-radius: 2px;
box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.25);
}
.oo-ui-popupWidget-anchored-top {
margin-top: 9px;
}
.oo-ui-popupWidget-anchored-top .oo-ui-popupWidget-anchor {
top: -9px;
}
.oo-ui-popupWidget-anchored-top .oo-ui-popupWidget-anchor:before {
bottom: -10px;
left: -9px;
border-bottom-color: #a2a9b1;
border-width: 10px;
}
.oo-ui-popupWidget-anchored-top .oo-ui-popupWidget-anchor:after {
bottom: -10px;
left: -8px;
border-bottom-color: #fff;
border-width: 9px;
}
.oo-ui-popupWidget-anchored-bottom {
margin-bottom: 9px;
}
.oo-ui-popupWidget-anchored-bottom .oo-ui-popupWidget-anchor {
bottom: -9px;
}
.oo-ui-popupWidget-anchored-bottom .oo-ui-popupWidget-anchor:before {
top: -10px;
left: -9px;
border-top-color: #a2a9b1;
border-width: 10px;
}
.oo-ui-popupWidget-anchored-bottom .oo-ui-popupWidget-anchor:after {
top: -10px;
left: -8px;
border-top-color: #fff;
border-width: 9px;
}
.oo-ui-popupWidget-anchored-start {
margin-left: 9px;
}
.oo-ui-popupWidget-anchored-start .oo-ui-popupWidget-anchor {
left: -9px;
}
.oo-ui-popupWidget-anchored-start .oo-ui-popupWidget-anchor:before {
right: -10px;
top: -9px;
border-right-color: #a2a9b1;
border-width: 10px;
}
.oo-ui-popupWidget-anchored-start .oo-ui-popupWidget-anchor:after {
right: -10px;
top: -8px;
border-right-color: #fff;
border-width: 9px;
}
.oo-ui-popupWidget-anchored-end {
margin-right: 9px;
}
.oo-ui-popupWidget-anchored-end .oo-ui-popupWidget-anchor {
right: -9px;
}
.oo-ui-popupWidget-anchored-end .oo-ui-popupWidget-anchor:before {
left: -10px;
top: -9px;
border-left-color: #a2a9b1;
border-width: 10px;
}
.oo-ui-popupWidget-anchored-end .oo-ui-popupWidget-anchor:after {
left: -10px;
top: -8px;
border-left-color: #fff;
border-width: 9px;
}
.oo-ui-popupWidget-transitioning .oo-ui-popupWidget-popup {
-webkit-transition: width 100ms, height 100ms, left 100ms;
-moz-transition: width 100ms, height 100ms, left 100ms;
transition: width 100ms, height 100ms, left 100ms;
}
.oo-ui-popupWidget-head > .oo-ui-labelElement-label {
margin: 0.64285714em 2.64285714em 0.57142857em 0.85714286em;
line-height: 1.07142857em;
}
.oo-ui-popupWidget-head > .oo-ui-buttonWidget {
right: 0;
}
.oo-ui-popupWidget-body {
line-height: 1.42857143em;
}
.oo-ui-popupWidget-body-padded {
margin: 0.64285714em 0.85714286em 0.57142857em;
}
.oo-ui-popupWidget-body-padded > :first-child {
margin-top: 0;
}
.oo-ui-popupWidget-footer {
margin: 0.64285714em 0.85714286em 0.57142857em;
}
.oo-ui-popupButtonWidget {
position: relative;
}
.oo-ui-popupButtonWidget .oo-ui-popupWidget {
cursor: auto;
}
.oo-ui-inputWidget {
margin-right: 0.5em;
}
.oo-ui-inputWidget:last-child {
margin-right: 0;
}
.oo-ui-buttonInputWidget > button,
.oo-ui-buttonInputWidget > input {
background-color: transparent;
margin: 0;
border: 0;
padding: 0;
}
.oo-ui-checkboxInputWidget {
position: relative;
line-height: 1.42857143em;
white-space: nowrap;
display: inline-block;
}
.oo-ui-checkboxInputWidget * {
font: inherit;
vertical-align: middle;
}
.oo-ui-checkboxInputWidget [type='checkbox'] {
position: relative;
max-width: none;
width: 1.42857143em;
height: 1.42857143em;
margin: 0;
opacity: 0;
z-index: 1;
}
.oo-ui-checkboxInputWidget [type='checkbox'] + span {
background-color: #fff;
background-size: 0 0;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
left: 0;
width: 1.42857143em;
height: 1.42857143em;
border: 1px solid #72777d;
border-radius: 2px;
}
.oo-ui-checkboxInputWidget [type='checkbox'] + span.oo-ui-iconWidget.oo-ui-iconElement.oo-ui-iconElement-icon {
position: absolute;
}
.oo-ui-checkboxInputWidget [type='checkbox']:checked + span {
background-size: 1em 1em;
}
.oo-ui-checkboxInputWidget [type='checkbox']:disabled + span {
background-color: #c8ccd1;
border-color: #c8ccd1;
}
.oo-ui-checkboxInputWidget.oo-ui-widget-enabled [type='checkbox'] {
cursor: pointer;
}
.oo-ui-checkboxInputWidget.oo-ui-widget-enabled [type='checkbox'] + span {
cursor: pointer;
-webkit-transition: background-color 100ms, border-color 100ms, box-shadow 100ms;
-moz-transition: background-color 100ms, border-color 100ms, box-shadow 100ms;
transition: background-color 100ms, border-color 100ms, box-shadow 100ms;
}
.oo-ui-checkboxInputWidget.oo-ui-widget-enabled [type='checkbox']:focus + span {
border-color: #36c;
box-shadow: inset 0 0 0 1px #36c;
}
.oo-ui-checkboxInputWidget.oo-ui-widget-enabled [type='checkbox']:hover + span {
border-color: #36c;
}
.oo-ui-checkboxInputWidget.oo-ui-widget-enabled [type='checkbox']:active + span {
background-color: #2a4b8d;
border-color: #2a4b8d;
box-shadow: inset 0 0 0 1px #2a4b8d;
}
.oo-ui-checkboxInputWidget.oo-ui-widget-enabled [type='checkbox']:checked + span {
background-color: #36c;
border-color: #36c;
}
.oo-ui-checkboxInputWidget.oo-ui-widget-enabled [type='checkbox']:checked:focus + span {
background-color: #36c;
border-color: #36c;
box-shadow: inset 0 0 0 1px #36c, inset 0 0 0 2px #fff;
}
.oo-ui-checkboxInputWidget.oo-ui-widget-enabled [type='checkbox']:checked:hover + span {
background-color: #447ff5;
border-color: #447ff5;
}
.oo-ui-checkboxInputWidget.oo-ui-widget-enabled [type='checkbox']:checked:active + span {
background-color: #2a4b8d;
border-color: #2a4b8d;
box-shadow: inset 0 0 0 1px #2a4b8d;
}
.oo-ui-checkboxMultiselectInputWidget .oo-ui-fieldLayout {
margin-top: 0.28571429em;
}
.oo-ui-dropdownInputWidget {
position: relative;
vertical-align: middle;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
width: 100%;
max-width: 50em;
}
.oo-ui-dropdownInputWidget .oo-ui-dropdownWidget,
.oo-ui-dropdownInputWidget.oo-ui-dropdownInputWidget-php select {
display: block;
}
.oo-ui-dropdownInputWidget select {
display: none;
background-position: -9999em 0;
background-repeat: no-repeat;
width: 100%;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.oo-ui-dropdownInputWidget.oo-ui-widget-enabled select {
cursor: pointer;
}
.oo-ui-dropdownInputWidget-php {
border-right: 1px solid #a2a9b1;
border-radius: 2px;
overflow-x: hidden;
}
.oo-ui-dropdownInputWidget select {
-webkit-appearance: none;
-moz-appearance: none;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
border: 1px solid #a2a9b1;
border-radius: 2px;
padding: 0.57142857em 0.85714286em 0.5em;
font-size: inherit;
font-family: inherit;
vertical-align: middle;
}
.oo-ui-dropdownInputWidget select::-ms-expand {
display: none;
}
.oo-ui-dropdownInputWidget select:not( [no-ie] ) {
background-position: right 1.75em center;
width: calc( 100% + 1em );
height: 2.28571429em;
padding: 0 0 0 0.85714286em;
}
.oo-ui-dropdownInputWidget option {
font-size: inherit;
font-family: inherit;
height: 1.5em;
padding: 0.57142857em 0.85714286em;
}
.oo-ui-dropdownInputWidget.oo-ui-widget-enabled select {
background-color: #f8f9fa;
color: #222;
-webkit-transition: background-color 100ms, border-color 100ms, box-shadow 100ms;
-moz-transition: background-color 100ms, border-color 100ms, box-shadow 100ms;
transition: background-color 100ms, border-color 100ms, box-shadow 100ms;
}
.oo-ui-dropdownInputWidget.oo-ui-widget-enabled select:hover {
background-color: #fff;
color: #444;
border-color: #a2a9b1;
}
.oo-ui-dropdownInputWidget.oo-ui-widget-enabled select:active {
color: #000;
border-color: #72777d;
}
.oo-ui-dropdownInputWidget.oo-ui-widget-enabled select:focus {
border-color: #36c;
outline: 0;
box-shadow: inset 0 0 0 1px #36c;
}
.oo-ui-dropdownInputWidget.oo-ui-widget-disabled select {
background-color: #eaecf0;
color: #72777d;
border-color: #c8ccd1;
}
.oo-ui-radioInputWidget {
position: relative;
line-height: 1.42857143em;
white-space: nowrap;
display: inline-block;
}
.oo-ui-radioInputWidget * {
font: inherit;
vertical-align: middle;
}
.oo-ui-radioInputWidget [type='radio'] {
position: relative;
max-width: none;
width: 1.42857143em;
height: 1.42857143em;
margin: 0;
opacity: 0;
z-index: 1;
}
.oo-ui-radioInputWidget [type='radio'] + span {
background-color: #fff;
position: absolute;
left: 0;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
width: 1.42857143em;
height: 1.42857143em;
border: 1px solid #72777d;
border-radius: 100%;
}
.oo-ui-radioInputWidget [type='radio'] + span:before {
content: ' ';
position: absolute;
top: -4px;
left: -4px;
right: -4px;
bottom: -4px;
border: 1px solid transparent;
border-radius: 100%;
}
.oo-ui-radioInputWidget [type='radio']:checked + span,
.oo-ui-radioInputWidget [type='radio']:checked:hover + span,
.oo-ui-radioInputWidget [type='radio']:checked:focus:hover + span {
border-width: 0.42857143em;
}
.oo-ui-radioInputWidget [type='radio']:disabled + span {
background-color: #c8ccd1;
border-color: #c8ccd1;
}
.oo-ui-radioInputWidget [type='radio']:disabled:checked + span {
background-color: #fff;
}
.oo-ui-radioInputWidget.oo-ui-widget-enabled [type='radio'] {
cursor: pointer;
}
.oo-ui-radioInputWidget.oo-ui-widget-enabled [type='radio'] + span {
cursor: pointer;
-webkit-transition: background-color 100ms, border-color 100ms, border-width 100ms;
-moz-transition: background-color 100ms, border-color 100ms, border-width 100ms;
transition: background-color 100ms, border-color 100ms, border-width 100ms;
}
.oo-ui-radioInputWidget.oo-ui-widget-enabled [type='radio']:hover + span {
border-color: #36c;
}
.oo-ui-radioInputWidget.oo-ui-widget-enabled [type='radio']:active + span {
background-color: #2a4b8d;
border-color: #2a4b8d;
}
.oo-ui-radioInputWidget.oo-ui-widget-enabled [type='radio']:checked + span {
border-color: #36c;
}
.oo-ui-radioInputWidget.oo-ui-widget-enabled [type='radio']:checked:focus + span:before {
border-color: #fff;
}
.oo-ui-radioInputWidget.oo-ui-widget-enabled [type='radio']:checked:hover + span {
border-color: #447ff5;
}
.oo-ui-radioInputWidget.oo-ui-widget-enabled [type='radio']:checked:active + span {
border-color: #2a4b8d;
box-shadow: inset 0 0 0 1px #2a4b8d;
}
.oo-ui-radioInputWidget.oo-ui-widget-enabled [type='radio']:checked:active + span:before {
border-color: #2a4b8d;
}
.oo-ui-radioSelectInputWidget .oo-ui-fieldLayout {
margin-top: 0.28571429em;
}
.oo-ui-textInputWidget {
position: relative;
vertical-align: middle;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
width: 100%;
max-width: 50em;
}
.oo-ui-textInputWidget input,
.oo-ui-textInputWidget textarea {
display: block;
width: 100%;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.oo-ui-textInputWidget textarea {
overflow: auto;
}
.oo-ui-textInputWidget textarea.oo-ui-textInputWidget-autosized {
resize: none;
}
.oo-ui-textInputWidget [type='number'] {
-moz-appearance: textfield;
}
.oo-ui-textInputWidget [type='number']::-webkit-outer-spin-button,
.oo-ui-textInputWidget [type='number']::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
.oo-ui-textInputWidget [type='search'] {
-webkit-appearance: none;
}
.oo-ui-textInputWidget [type='search']::-ms-clear {
display: none;
}
.oo-ui-textInputWidget [type='search']::-webkit-search-decoration,
.oo-ui-textInputWidget [type='search']::-webkit-search-cancel-button {
display: none;
}
.oo-ui-textInputWidget.oo-ui-widget-enabled > .oo-ui-iconElement-icon,
.oo-ui-textInputWidget.oo-ui-widget-enabled > .oo-ui-indicatorElement-indicator {
cursor: text;
}
.oo-ui-textInputWidget.oo-ui-widget-enabled.oo-ui-textInputWidget-type-search > .oo-ui-indicatorElement-indicator {
cursor: pointer;
}
.oo-ui-textInputWidget.oo-ui-widget-disabled > * {
-webkit-touch-callout: none;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.oo-ui-textInputWidget.oo-ui-labelElement > .oo-ui-labelElement-label {
display: block;
}
.oo-ui-textInputWidget > .oo-ui-iconElement-icon,
.oo-ui-textInputWidget-labelPosition-before > .oo-ui-labelElement-label {
left: 0;
}
.oo-ui-textInputWidget > .oo-ui-indicatorElement-indicator,
.oo-ui-textInputWidget-labelPosition-after > .oo-ui-labelElement-label {
right: 0;
}
.oo-ui-textInputWidget-labelPosition-after.oo-ui-labelElement ::-ms-clear {
display: none;
}
.oo-ui-textInputWidget > .oo-ui-labelElement-label {
position: absolute;
top: 0;
}
.oo-ui-textInputWidget-php > .oo-ui-iconElement-icon,
.oo-ui-textInputWidget-php > .oo-ui-indicatorElement-indicator,
.oo-ui-textInputWidget-php > .oo-ui-labelElement-label {
pointer-events: none;
}
.oo-ui-textInputWidget input,
.oo-ui-textInputWidget textarea {
-webkit-appearance: none;
margin: 0;
font-size: inherit;
font-family: inherit;
background-color: #fff;
color: #000;
border: 1px solid #a2a9b1;
border-radius: 2px;
padding: 0.57142857em 0.57142857em 0.5em;
}
.oo-ui-textInputWidget input {
line-height: 1.07142857em;
}
.oo-ui-textInputWidget textarea {
line-height: 1.286;
}
.oo-ui-textInputWidget .oo-ui-pendingElement-pending {
background-color: transparent;
}
.oo-ui-textInputWidget.oo-ui-widget-enabled input,
.oo-ui-textInputWidget.oo-ui-widget-enabled textarea {
box-shadow: inset 0 0 0 1px transparent;
-webkit-transition: border-color 200ms cubic-bezier(0.4, 0.55, 0.55, 1), box-shadow 200ms cubic-bezier(0.4, 0.55, 0.55, 1);
-moz-transition: border-color 200ms cubic-bezier(0.4, 0.55, 0.55, 1), box-shadow 200ms cubic-bezier(0.4, 0.55, 0.55, 1);
transition: border-color 200ms cubic-bezier(0.4, 0.55, 0.55, 1), box-shadow 200ms cubic-bezier(0.4, 0.55, 0.55, 1);
}
.oo-ui-textInputWidget.oo-ui-widget-enabled input::-webkit-input-placeholder,
.oo-ui-textInputWidget.oo-ui-widget-enabled textarea::-webkit-input-placeholder {
color: #72777d;
opacity: 1;
}
.oo-ui-textInputWidget.oo-ui-widget-enabled input:-ms-input-placeholder,
.oo-ui-textInputWidget.oo-ui-widget-enabled textarea:-ms-input-placeholder {
color: #72777d;
opacity: 1;
}
.oo-ui-textInputWidget.oo-ui-widget-enabled input::-moz-placeholder,
.oo-ui-textInputWidget.oo-ui-widget-enabled textarea::-moz-placeholder {
color: #72777d;
opacity: 1;
}
.oo-ui-textInputWidget.oo-ui-widget-enabled input:-moz-placeholder,
.oo-ui-textInputWidget.oo-ui-widget-enabled textarea:-moz-placeholder {
color: #72777d;
opacity: 1;
}
.oo-ui-textInputWidget.oo-ui-widget-enabled input::placeholder,
.oo-ui-textInputWidget.oo-ui-widget-enabled textarea::placeholder {
color: #72777d;
opacity: 1;
}
.oo-ui-textInputWidget.oo-ui-widget-enabled input:focus,
.oo-ui-textInputWidget.oo-ui-widget-enabled textarea:focus {
outline: 0;
border-color: #36c;
box-shadow: inset 0 0 0 1px #36c;
}
.oo-ui-textInputWidget.oo-ui-widget-enabled input[readonly],
.oo-ui-textInputWidget.oo-ui-widget-enabled textarea[readonly] {
background-color: #f8f9fa;
}
.oo-ui-textInputWidget.oo-ui-widget-enabled:hover input,
.oo-ui-textInputWidget.oo-ui-widget-enabled:hover textarea {
border-color: #72777d;
}
.oo-ui-textInputWidget.oo-ui-widget-enabled:hover input:focus,
.oo-ui-textInputWidget.oo-ui-widget-enabled:hover textarea:focus {
border-color: #36c;
}
@media screen and (min-width: 0) {
.oo-ui-textInputWidget.oo-ui-widget-enabled textarea:focus {
outline: 1px solid #36c;
outline-offset: -2px;
}
}
.oo-ui-textInputWidget.oo-ui-widget-enabled.oo-ui-flaggedElement-invalid input,
.oo-ui-textInputWidget.oo-ui-widget-enabled.oo-ui-flaggedElement-invalid textarea {
border-color: #d33;
}
.oo-ui-textInputWidget.oo-ui-widget-enabled.oo-ui-flaggedElement-invalid input:hover,
.oo-ui-textInputWidget.oo-ui-widget-enabled.oo-ui-flaggedElement-invalid textarea:hover {
border-color: #d33;
}
.oo-ui-textInputWidget.oo-ui-widget-enabled.oo-ui-flaggedElement-invalid input:focus,
.oo-ui-textInputWidget.oo-ui-widget-enabled.oo-ui-flaggedElement-invalid textarea:focus {
border-color: #d33;
box-shadow: inset 0 0 0 1px #d33;
}
.oo-ui-textInputWidget.oo-ui-widget-disabled input,
.oo-ui-textInputWidget.oo-ui-widget-disabled textarea {
background-color: #eaecf0;
-webkit-text-fill-color: #72777d;
color: #72777d;
text-shadow: 0 1px 1px #fff;
border-color: #c8ccd1;
}
.oo-ui-textInputWidget.oo-ui-widget-disabled > .oo-ui-iconElement-icon,
.oo-ui-textInputWidget.oo-ui-widget-disabled > .oo-ui-indicatorElement-indicator {
opacity: 0.51;
}
.oo-ui-textInputWidget.oo-ui-widget-disabled > .oo-ui-labelElement-label {
color: #72777d;
text-shadow: 0 1px 1px #fff;
}
.oo-ui-textInputWidget.oo-ui-iconElement input,
.oo-ui-textInputWidget.oo-ui-iconElement textarea {
padding-left: 2.64285714em;
}
.oo-ui-textInputWidget.oo-ui-iconElement > .oo-ui-iconElement-icon {
left: 0.57142857em;
}
.oo-ui-textInputWidget.oo-ui-iconElement textarea + .oo-ui-iconElement-icon {
max-height: 2.28571429em;
}
.oo-ui-textInputWidget > .oo-ui-labelElement-label {
color: #72777d;
margin-top: 1px;
padding: 0.57142857em 0.85714286em 0.5em 0.57142857em;
line-height: 1.07142857em;
}
.oo-ui-textInputWidget.oo-ui-indicatorElement input,
.oo-ui-textInputWidget.oo-ui-indicatorElement textarea {
padding-right: 2em;
}
.oo-ui-textInputWidget.oo-ui-indicatorElement.oo-ui-textInputWidget-labelPosition-after > .oo-ui-labelElement-label {
padding-right: 0;
}
.oo-ui-textInputWidget.oo-ui-indicatorElement > .oo-ui-indicatorElement-indicator {
max-height: 2.28571429em;
margin-right: 0.85714286em;
}
.oo-ui-textInputWidget-labelPosition-after.oo-ui-indicatorElement > .oo-ui-labelElement-label {
margin-right: 2.28571429em;
}
.oo-ui-textInputWidget-labelPosition-before.oo-ui-iconElement > .oo-ui-labelElement-label {
padding-left: 2.64285714em;
}
.oo-ui-menuSelectWidget {
position: absolute;
width: 100%;
z-index: 4;
background-color: #fff;
margin-top: -1px;
margin-bottom: -1px;
border: 1px solid #a2a9b1;
border-radius: 0 0 2px 2px;
box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.25);
}
.oo-ui-menuSelectWidget.oo-ui-clippableElement-clippable {
min-height: 2.6em;
}
.oo-ui-menuSelectWidget-invisible {
display: none;
}
.oo-ui-menuOptionWidget {
-webkit-transition: background-color 100ms, color 100ms;
-moz-transition: background-color 100ms, color 100ms;
transition: background-color 100ms, color 100ms;
}
.oo-ui-menuOptionWidget.oo-ui-optionWidget .oo-ui-iconElement-icon.oo-ui-menuOptionWidget-checkIcon {
display: none;
}
.oo-ui-menuOptionWidget.oo-ui-optionWidget-highlighted {
background-color: #eaecf0;
color: #000;
}
.oo-ui-menuOptionWidget.oo-ui-optionWidget-selected {
background-color: #eaf3ff;
color: #36c;
}
.oo-ui-menuOptionWidget.oo-ui-optionWidget-selected.oo-ui-menuOptionWidget.oo-ui-optionWidget-highlighted,
.oo-ui-menuOptionWidget.oo-ui-optionWidget-pressed.oo-ui-menuOptionWidget.oo-ui-optionWidget-highlighted {
background-color: rgba(41, 98, 204, 0.1);
color: #36c;
}
.oo-ui-menuSectionOptionWidget {
color: #72777d;
padding: 0.64285714em 0.85714286em 0.28571429em;
font-weight: bold;
}
.oo-ui-menuSectionOptionWidget.oo-ui-widget-enabled {
cursor: default;
}
.oo-ui-menuSectionOptionWidget ~ .oo-ui-menuOptionWidget {
padding-left: 1.71428571em;
}
.oo-ui-menuSectionOptionWidget ~ .oo-ui-menuOptionWidget.oo-ui-iconElement {
padding-left: 3.5em;
}
.oo-ui-menuSectionOptionWidget ~ .oo-ui-menuOptionWidget.oo-ui-iconElement .oo-ui-iconElement-icon {
left: 1.71428571em;
}
.oo-ui-dropdownWidget {
display: inline-block;
position: relative;
width: 100%;
max-width: 50em;
margin-right: 0.5em;
}
.oo-ui-dropdownWidget-handle {
position: relative;
width: 100%;
display: block;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
cursor: default;
-webkit-touch-callout: none;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.oo-ui-dropdownWidget.oo-ui-widget-enabled .oo-ui-dropdownWidget-handle {
cursor: pointer;
}
.oo-ui-dropdownWidget:last-child {
margin-right: 0;
}
.oo-ui-dropdownWidget-handle {
min-height: 2.28571429em;
border: 1px solid #a2a9b1;
border-radius: 2px;
padding: 0.57142857em 0.85714286em 0.5em;
line-height: 1;
}
.oo-ui-dropdownWidget-handle .oo-ui-iconElement-icon {
left: 0.85714286em;
}
.oo-ui-dropdownWidget-handle .oo-ui-indicatorElement-indicator {
right: 0.85714286em;
}
.oo-ui-dropdownWidget-handle .oo-ui-labelElement-label {
line-height: 1.07142857em;
}
.oo-ui-dropdownWidget.oo-ui-iconElement .oo-ui-dropdownWidget-handle {
padding-left: 2.64285714em;
}
.oo-ui-dropdownWidget.oo-ui-indicatorElement .oo-ui-dropdownWidget-handle {
padding-right: 1.71428571em;
}
.oo-ui-dropdownWidget.oo-ui-widget-enabled .oo-ui-dropdownWidget-handle {
background-color: #f8f9fa;
color: #222;
-webkit-transition: background-color 100ms, border-color 100ms, box-shadow 100ms;
-moz-transition: background-color 100ms, border-color 100ms, box-shadow 100ms;
transition: background-color 100ms, border-color 100ms, box-shadow 100ms;
}
.oo-ui-dropdownWidget.oo-ui-widget-enabled .oo-ui-dropdownWidget-handle:hover {
background-color: #fff;
color: #444;
border-color: #a2a9b1;
}
.oo-ui-dropdownWidget.oo-ui-widget-enabled .oo-ui-dropdownWidget-handle:hover .oo-ui-iconElement-icon,
.oo-ui-dropdownWidget.oo-ui-widget-enabled .oo-ui-dropdownWidget-handle:hover .oo-ui-indicatorElement-indicator {
opacity: 0.73;
}
.oo-ui-dropdownWidget.oo-ui-widget-enabled .oo-ui-dropdownWidget-handle:active {
color: #000;
border-color: #72777d;
}
.oo-ui-dropdownWidget.oo-ui-widget-enabled .oo-ui-dropdownWidget-handle:focus {
border-color: #36c;
outline: 0;
box-shadow: inset 0 0 0 1px #36c;
}
.oo-ui-dropdownWidget.oo-ui-widget-enabled .oo-ui-dropdownWidget-handle .oo-ui-iconElement-icon,
.oo-ui-dropdownWidget.oo-ui-widget-enabled .oo-ui-dropdownWidget-handle .oo-ui-indicatorElement-indicator {
opacity: 0.87;
-webkit-transition: opacity 100ms;
-moz-transition: opacity 100ms;
transition: opacity 100ms;
}
.oo-ui-dropdownWidget.oo-ui-widget-enabled.oo-ui-dropdownWidget-open .oo-ui-dropdownWidget-handle {
background-color: #fff;
}
.oo-ui-dropdownWidget.oo-ui-widget-enabled.oo-ui-dropdownWidget-open .oo-ui-dropdownWidget-handle .oo-ui-iconElement-icon,
.oo-ui-dropdownWidget.oo-ui-widget-enabled.oo-ui-dropdownWidget-open .oo-ui-dropdownWidget-handle .oo-ui-indicatorElement-indicator {
opacity: 1;
}
.oo-ui-dropdownWidget.oo-ui-widget-disabled .oo-ui-dropdownWidget-handle {
color: #72777d;
text-shadow: 0 1px 1px #fff;
border-color: #c8ccd1;
background-color: #eaecf0;
}
.oo-ui-dropdownWidget.oo-ui-widget-disabled .oo-ui-dropdownWidget-handle:focus {
outline: 0;
}
.oo-ui-dropdownWidget.oo-ui-widget-disabled .oo-ui-dropdownWidget-handle .oo-ui-indicatorElement-indicator {
opacity: 0.15;
}
.oo-ui-comboBoxInputWidget {
display: inline-block;
position: relative;
}
.oo-ui-comboBoxInputWidget-field {
display: table;
width: 100%;
table-layout: fixed;
}
.oo-ui-comboBoxInputWidget .oo-ui-inputWidget-input {
display: table-cell;
vertical-align: middle;
position: relative;
overflow: hidden;
}
.oo-ui-comboBoxInputWidget-dropdownButton {
display: table-cell;
}
.oo-ui-comboBoxInputWidget-dropdownButton > .oo-ui-buttonElement-button {
display: block;
overflow: hidden;
}
.oo-ui-comboBoxInputWidget.oo-ui-comboBoxInputWidget-empty .oo-ui-comboBoxInputWidget-dropdownButton {
display: none;
}
.oo-ui-comboBoxInputWidget-php ::-webkit-calendar-picker-indicator {
opacity: 0;
position: absolute;
right: 0;
top: 0;
width: 2.5em;
height: 2.5em;
padding: 0;
}
.oo-ui-comboBoxInputWidget-php > .oo-ui-indicatorWidget {
display: block;
position: absolute;
top: 0;
height: 100%;
pointer-events: none;
}
.oo-ui-comboBoxInputWidget input {
height: 2.28571429em;
border-top-right-radius: 0;
border-bottom-right-radius: 0;
border-right-width: 0;
}
.oo-ui-comboBoxInputWidget.oo-ui-comboBoxInputWidget-empty input,
.oo-ui-comboBoxInputWidget-php input {
border-top-right-radius: 2px;
border-bottom-right-radius: 2px;
border-right-width: 1px;
}
.oo-ui-comboBoxInputWidget-dropdownButton.oo-ui-indicatorElement {
width: 2.64285714em;
}
.oo-ui-comboBoxInputWidget-dropdownButton.oo-ui-indicatorElement .oo-ui-buttonElement-button {
min-width: 37px;
min-height: 2.28571429em;
padding-left: 0;
}
.oo-ui-comboBoxInputWidget-dropdownButton.oo-ui-indicatorElement .oo-ui-buttonElement-button > .oo-ui-indicatorElement-indicator {
right: 0.85714286em;
}
.oo-ui-comboBoxInputWidget-dropdownButton.oo-ui-indicatorElement .oo-ui-buttonElement-button,
.oo-ui-comboBoxInputWidget-dropdownButton.oo-ui-indicatorElement .oo-ui-buttonElement-button:focus {
border-top-left-radius: 0;
border-bottom-left-radius: 0;
}
.oo-ui-comboBoxInputWidget-php .oo-ui-indicatorWidget.oo-ui-indicatorElement.oo-ui-indicatorElement-indicator {
display: block;
position: absolute;
top: 0;
height: 100%;
right: 0.85714286em;
margin: 0;
}
.oo-ui-comboBoxInputWidget-open .oo-ui-comboBoxInputWidget-dropdownButton > .oo-ui-buttonElement-button {
background-color: #fff;
}
.oo-ui-comboBoxInputWidget-open .oo-ui-comboBoxInputWidget-dropdownButton > .oo-ui-buttonElement-button .oo-ui-indicatorElement-indicator {
opacity: 1;
}
.oo-ui-comboBoxInputWidget.oo-ui-widget-disabled .oo-ui-indicatorElement-indicator {
opacity: 1;
}
.oo-ui-multioptionWidget {
position: relative;
display: block;
}
.oo-ui-multioptionWidget.oo-ui-widget-enabled {
cursor: pointer;
}
.oo-ui-multioptionWidget.oo-ui-widget-disabled {
cursor: default;
}
.oo-ui-multioptionWidget.oo-ui-labelElement .oo-ui-labelElement-label {
display: block;
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
}
.oo-ui-multioptionWidget.oo-ui-widget-disabled {
color: #72777d;
}
.oo-ui-checkboxMultioptionWidget {
display: table;
width: 100%;
padding: 0.28571429em 0;
}
.oo-ui-checkboxMultioptionWidget .oo-ui-checkboxInputWidget,
.oo-ui-checkboxMultioptionWidget.oo-ui-labelElement > .oo-ui-labelElement-label {
display: table-cell;
vertical-align: top;
}
.oo-ui-checkboxMultioptionWidget .oo-ui-checkboxInputWidget {
width: 1px;
}
.oo-ui-checkboxMultioptionWidget.oo-ui-labelElement > .oo-ui-labelElement-label {
white-space: normal;
}
.oo-ui-checkboxMultioptionWidget.oo-ui-labelElement .oo-ui-labelElement-label {
padding-left: 0.42857143em;
}
.oo-ui-checkboxMultioptionWidget .oo-ui-checkboxInputWidget {
margin-right: 0;
}
.oo-ui-progressBarWidget {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
max-width: 50em;
background-color: #fff;
border: 1px solid #a2a9b1;
border-radius: 2px;
overflow: hidden;
}
.oo-ui-progressBarWidget-bar {
height: 1em;
-webkit-transition: width 200ms;
-moz-transition: width 200ms;
transition: width 200ms;
}
.oo-ui-progressBarWidget-indeterminate .oo-ui-progressBarWidget-bar {
-webkit-animation: oo-ui-progressBarWidget-slide 2s infinite linear;
-moz-animation: oo-ui-progressBarWidget-slide 2s infinite linear;
animation: oo-ui-progressBarWidget-slide 2s infinite linear;
width: 40%;
-webkit-transform: translate(-25%);
-moz-transform: translate(-25%);
-ms-transform: translate(-25%);
transform: translate(-25%);
border-left-width: 1px;
}
.oo-ui-progressBarWidget.oo-ui-widget-enabled .oo-ui-progressBarWidget-bar {
background-color: #36c;
}
.oo-ui-progressBarWidget.oo-ui-widget-disabled .oo-ui-progressBarWidget-bar {
background-color: #c8ccd1;
}
@-webkit-keyframes oo-ui-progressBarWidget-slide {
from {
-webkit-transform: translate(-100%);
-moz-transform: translate(-100%);
-ms-transform: translate(-100%);
transform: translate(-100%);
}
to {
-webkit-transform: translate(350%);
-moz-transform: translate(350%);
-ms-transform: translate(350%);
transform: translate(350%);
}
}
@-moz-keyframes oo-ui-progressBarWidget-slide {
from {
-webkit-transform: translate(-100%);
-moz-transform: translate(-100%);
-ms-transform: translate(-100%);
transform: translate(-100%);
}
to {
-webkit-transform: translate(350%);
-moz-transform: translate(350%);
-ms-transform: translate(350%);
transform: translate(350%);
}
}
@keyframes oo-ui-progressBarWidget-slide {
from {
-webkit-transform: translate(-100%);
-moz-transform: translate(-100%);
-ms-transform: translate(-100%);
transform: translate(-100%);
}
to {
-webkit-transform: translate(350%);
-moz-transform: translate(350%);
-ms-transform: translate(350%);
transform: translate(350%);
}
}
.oo-ui-numberInputWidget {
display: inline-block;
position: relative;
max-width: 50em;
}
.oo-ui-numberInputWidget-buttoned .oo-ui-buttonWidget,
.oo-ui-numberInputWidget-buttoned .oo-ui-inputWidget-input {
display: table-cell;
height: 100%;
}
.oo-ui-numberInputWidget-field {
display: table;
table-layout: fixed;
width: 100%;
}
.oo-ui-numberInputWidget-buttoned .oo-ui-buttonWidget {
width: 2.64285714em;
}
.oo-ui-numberInputWidget-buttoned .oo-ui-buttonWidget .oo-ui-buttonElement-button {
display: block;
min-width: 37px;
min-height: 2.28571429em;
padding-left: 0;
padding-right: 0;
}
.oo-ui-numberInputWidget-buttoned .oo-ui-buttonWidget .oo-ui-buttonElement-button .oo-ui-iconElement-icon {
left: 0.57142857em;
}
.oo-ui-numberInputWidget-buttoned .oo-ui-inputWidget-input {
border-radius: 0;
max-height: 2.28571429em;
}
.oo-ui-numberInputWidget-minusButton > .oo-ui-buttonElement-button {
border-top-right-radius: 0;
border-bottom-right-radius: 0;
border-right-width: 0;
}
.oo-ui-numberInputWidget-plusButton > .oo-ui-buttonElement-button {
border-top-left-radius: 0;
border-bottom-left-radius: 0;
border-left-width: 0;
}
.oo-ui-numberInputWidget.oo-ui-widget-disabled.oo-ui-numberInputWidget-buttoned .oo-ui-iconElement-icon {
opacity: 1;
}
.oo-ui-defaultOverlay {
position: absolute;
top: 0;
/* @noflip */
left: 0;
}
| joeyparrish/cdnjs | ajax/libs/oojs-ui/0.27.2/oojs-ui-core-wikimediaui.css | CSS | mit | 68,761 |
%include "asm/vesa.inc"
[section .text]
[BITS 16]
vesa:
.getcardinfo:
mov ax, 0x4F00
mov di, VBECardInfo
int 0x10
cmp ax, 0x4F
je .edid
mov eax, 1
ret
.edid:
cmp dword [.required], 0 ;if both required x and required y are set, forget this
jne near .findmode
mov ax, 0x4F15
mov bl, 1
mov di, VBEEDID
int 0x10
cmp ax, 0x4F
jne near .noedid
xor di, di
.lp:
xor cx, cx
mov cl, [di+VBEEDID.standardtiming]
shl cx, 3
add cx, 248
push ecx
call decshowrm
mov al, 'x'
call charrm
pop ecx
mov bx, cx
inc di
mov al, [di+VBEEDID.standardtiming]
and al, 11000000b
cmp al, VBEEDID.aspect.4.3
jne .not43
mov ax, 3
mul cx
mov cx, ax
shr cx, 2
jmp .gotres
.not43:
cmp al, VBEEDID.aspect.5.4
jne .not54
shl cx, 2
mov ax, cx
mov cx, 5
xor dx, dx
div cx
mov cx, ax
jmp .gotres
.not54:
cmp al, VBEEDID.aspect.16.10
jne .not1610
mov ax, 10
mul cx
mov cx, ax
shr cx, 4
jmp .gotres
.not1610:
mov ax, 9
mul cx
mov cx, ax
shr cx, 4
.gotres:
call decshowrm
mov si, .edidmsg
call printrm
inc di
cmp di, 8
jb .lp
jmp .findmode
.noedid:
mov si, .noedidmsg
call printrm
jmp .findmode
.resetlist:
;if needed, reset mins/maxes/stuff
xor cx, cx
mov [.minx], cx
mov [.miny], cx
mov [.requiredx], cx
mov [.requiredy], cx
mov [.requiredmode], cx
.findmode:
mov si, [VBECardInfo.videomodeptr]
mov ax, [VBECardInfo.videomodeptr+2]
mov fs, ax
sub si, 2
mov cx, [.requiredmode]
test cx, cx
jnz .getmodeinfo
.searchmodes:
add si, 2
mov cx, [fs:si]
cmp cx, 0xFFFF
jne .getmodeinfo
cmp word [.goodmode], 0
je .resetlist
jmp .findmode
.getmodeinfo:
push esi
;or cx, 1 << 14
mov [.currentmode], cx
mov ax, 0x4F01
mov di, VBEModeInfo
int 0x10
pop esi
cmp ax, 0x4F
je .foundmode
mov eax, 1
ret
.foundmode:
;check minimum values, really not minimums from an OS perspective but ugly for users
cmp byte [VBEModeInfo.bitsperpixel], 32
jb .searchmodes
.testx:
mov cx, [VBEModeInfo.xresolution]
cmp word [.requiredx], 0
je .notrequiredx
cmp cx, [.requiredx]
je .testy
jmp .searchmodes
.notrequiredx:
cmp cx, [.minx]
jb .searchmodes
.testy:
mov cx, [VBEModeInfo.yresolution]
cmp word [.requiredy], 0
je .notrequiredy
cmp cx, [.requiredy]
jne .searchmodes ;as if there weren't enough warnings, USE WITH CAUTION
cmp word [.requiredx], 0
jnz .setmode
jmp .testgood
.notrequiredy:
cmp cx, [.miny]
jb .searchmodes
.testgood:
mov cx, [.currentmode]
mov [.goodmode], cx
push esi
mov cx, [VBEModeInfo.xresolution]
call decshowrm
mov al, 'x'
call charrm
mov cx, [VBEModeInfo.yresolution]
call decshowrm
mov al, '@'
call charrm
xor ch, ch
mov cl, [VBEModeInfo.bitsperpixel]
call decshowrm
mov si, .modeok
call printrm
xor ax, ax
int 0x16
pop esi
cmp al, 'y'
jne .searchmodes
.setmode:
mov bx, [.currentmode]
cmp bx, 0
je .nomode
or bx, 0x4000
mov ax, 0x4F02
int 0x10
.nomode:
cmp ax, 0x4F
je .returngood
mov eax, 1
ret
.returngood:
xor eax, eax
ret
.minx dw 1024
.miny dw 768
.required:
.requiredx dw 1024 ;USE THESE WITH CAUTION
.requiredy dw 768
.requiredmode dw 0
.noedidmsg db "EDID not supported.",10,13,0
.edidmsg db " is supported.",10,13,0
.modeok db 10,13,"Is this OK?(y/n)",10,13,0
.goodmode dw 0
.currentmode dw 0
;useful functions
decshowrm:
mov si, .number
.clear:
mov al, "0"
mov [si], al
inc si
cmp si, .numberend
jb .clear
dec si
call convertrm
mov si, .number
.lp:
lodsb
cmp si, .numberend
jae .end
cmp al, "0"
jbe .lp
.end:
dec si
call printrm
ret
.number times 7 db 0
.numberend db 0
convertrm:
dec si
mov bx, si ;place to convert into must be in si, number to convert must be in cx
.cnvrt:
mov si, bx
sub si, 4
.ten4: inc si
cmp cx, 10000
jb .ten3
sub cx, 10000
inc byte [si]
jmp .cnvrt
.ten3: inc si
cmp cx, 1000
jb .ten2
sub cx, 1000
inc byte [si]
jmp .cnvrt
.ten2: inc si
cmp cx, 100
jb .ten1
sub cx, 100
inc byte [si]
jmp .cnvrt
.ten1: inc si
cmp cx, 10
jb .ten0
sub cx, 10
inc byte [si]
jmp .cnvrt
.ten0: inc si
cmp cx, 1
jb .return
sub cx, 1
inc byte [si]
jmp .cnvrt
.return:
ret
printrm:
mov al, [si]
test al, al
jz .return
call charrm
inc si
jmp printrm
.return:
ret
charrm: ;char must be in al
mov bx, 7
mov ah, 0xE
int 10h
ret
; .bestmode: ;preference is width > height > color
; mov bx, [VBEModeInfo.xresolution]
; cmp bx, [.width]
; ja .switchmode
; jb .searchmodes
; mov bx, [VBEModeInfo.yresolution]
; cmp bx, [.height]
; ja .switchmode
; jb .searchmodes
; mov bl, [VBEModeInfo.bitsperpixel]
; cmp bl, [.color]
; jb .searchmodes
; .switchmode:
; mov cx, [.currentmode]
; mov [.mode], cx
; mov bx, [VBEModeInfo.xresolution]
; mov [.width], bx
; mov bx, [VBEModeInfo.yresolution]
; mov [.height], bx
; mov bl, [VBEModeInfo.bitsperpixel]
; mov [.color], bl
; jmp .searchmodes
; .mode dw 0
; .color db 0
; .height dw 0
; .width dw 0
| alexzhang2015/redox | src/asm/vesa.asm | Assembly | mit | 4,846 |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//
// Originally based on the Bartok code base.
//
using System;
using System.Collections.Generic;
using System.Text;
namespace Microsoft.Zelig.MetaData.Importer
{
public sealed class MetaDataMethodImpl : MetaDataObject,
IMetaDataNormalize
{
//
// State
//
private MetaDataTypeDefinition m_classObject;
private IMetaDataMethodDefOrRef m_body;
private IMetaDataMethodDefOrRef m_declaration;
//
// Constructor Methods
//
private MetaDataMethodImpl( int index ) : base( TokenType.MethodImpl, index )
{
}
// Helper methods to work around limitations in generics, see Parser.InitializeTable<T>
internal static MetaDataObject.CreateInstance GetCreator()
{
return new MetaDataObject.CreateInstance( Creator );
}
private static MetaDataObject Creator( int index )
{
return new MetaDataMethodImpl( index );
}
//--//
internal override void Parse( Parser parser ,
Parser.TableSchema ts ,
ArrayReader reader )
{
Parser.IndexReader classReader = ts.m_columns[0].m_reader;
Parser.IndexReader bodyReader = ts.m_columns[1].m_reader;
Parser.IndexReader declarationReader = ts.m_columns[2].m_reader;
int classIndex = classReader ( reader );
int bodyIndex = bodyReader ( reader );
int declarationIndex = declarationReader( reader );
m_classObject = parser.getTypeDef ( classIndex );
m_body = parser.getMethodDefOrRef( bodyIndex );
m_declaration = parser.getMethodDefOrRef( declarationIndex );
}
//
// IMetaDataNormalize methods
//
Normalized.MetaDataObject IMetaDataNormalize.AllocateNormalizedObject( MetaDataNormalizationContext context )
{
switch(context.Phase)
{
case MetaDataNormalizationPhase.CreationOfMethodImplDefinitions:
{
Normalized.MetaDataMethodImpl miNew = new Normalized.MetaDataMethodImpl( m_token );
context.GetNormalizedObject( m_classObject, out miNew.m_classObject, MetaDataNormalizationMode.LookupExisting );
context.GetNormalizedObject( m_body , out miNew.m_body , MetaDataNormalizationMode.LookupExisting );
context.GetNormalizedObject( m_declaration, out miNew.m_declaration, MetaDataNormalizationMode.Default );
return miNew;
}
}
throw context.InvalidPhase( this );
}
void IMetaDataNormalize.ExecuteNormalizationPhase( Normalized.IMetaDataObject obj ,
MetaDataNormalizationContext context )
{
Normalized.MetaDataMethodImpl mi = (Normalized.MetaDataMethodImpl)obj;
context = context.Push( obj );
switch(context.Phase)
{
case MetaDataNormalizationPhase.CompletionOfMethodImplNormalization:
{
Normalized.MetaDataTypeDefinitionBase td = (Normalized.MetaDataTypeDefinitionBase)mi.Body.Owner;
td.m_methodImpls = ArrayUtility.AppendToArray( td.m_methodImpls, mi );
}
return;
}
throw context.InvalidPhase( this );
}
//
// Access Methods
//
public MetaDataTypeDefinition Class
{
get
{
return m_classObject;
}
}
public IMetaDataMethodDefOrRef Body
{
get
{
return m_body;
}
}
public IMetaDataMethodDefOrRef Declaration
{
get
{
return m_declaration;
}
}
//
// Debug Methods
//
public override String ToString()
{
return "MetaDataMethodImpl(" + m_classObject + "," + m_body + "," + m_declaration + ")";
}
}
}
| jkotas/llilum | Zelig/Zelig/CompileTime/MetaData/Importer/MetaDataMethodImpl.cs | C# | mit | 4,489 |
/*++
Copyright (c) 2011 Microsoft Corporation
Module Name:
sat_elim_eqs.h
Abstract:
Helper class for eliminating eqs.
Author:
Leonardo de Moura (leonardo) 2011-05-27.
Revision History:
--*/
#ifndef SAT_ELIM_EQS_H_
#define SAT_ELIM_EQS_H_
#include"sat_types.h"
namespace sat {
class solver;
class elim_eqs {
solver & m_solver;
void save_elim(literal_vector const & roots, bool_var_vector const & to_elim);
void cleanup_clauses(literal_vector const & roots, clause_vector & cs);
void cleanup_bin_watches(literal_vector const & roots);
bool check_clauses(literal_vector const & roots) const;
public:
elim_eqs(solver & s);
void operator()(literal_vector const & roots, bool_var_vector const & to_elim);
};
};
#endif
| seahorn/z3 | src/sat/sat_elim_eqs.h | C | mit | 813 |
#
# Author:: Adam Jacob (<[email protected]>)
# Copyright:: Copyright (c) 2009 Opscode, Inc.
# License:: Apache License, Version 2.0
#
# 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.
#
require 'chef/knife'
class Chef
class Knife
class ClientReregister < Knife
deps do
require 'chef/api_client'
require 'chef/json_compat'
end
banner "knife client reregister CLIENT (options)"
option :file,
:short => "-f FILE",
:long => "--file FILE",
:description => "Write the key to a file"
def run
@client_name = @name_args[0]
if @client_name.nil?
show_usage
ui.fatal("You must specify a client name")
exit 1
end
client = Chef::ApiClient.load(@client_name)
key = client.save(new_key=true)
if config[:file]
File.open(config[:file], "w") do |f|
f.print(key['private_key'])
end
else
ui.msg key['private_key']
end
end
end
end
end
| higanworks/chef-with-ruby_precise-x86_64 | lib/ruby/gems/1.9.1/gems/chef-10.16.0/lib/chef/knife/client_reregister.rb | Ruby | mit | 1,540 |
require "spec_helper"
describe Mongoid::Relations::AutoSave do
describe ".auto_save" do
before(:all) do
Person.autosave(Person.relations["account"].merge!(autosave: true))
end
after(:all) do
Person.reset_callbacks(:save)
end
let(:person) do
Person.new
end
context "when the option is not provided" do
let(:game) do
Game.new(name: "Tekken")
end
before do
person.game = game
end
context "when saving the parent document" do
before do
person.save
end
it "does not save the relation" do
expect(game).to_not be_persisted
end
end
end
context "when the option is true" do
context "when the relation has already had the autosave callback added" do
let(:metadata) do
Person.relations["drugs"].merge!(autosave: true)
end
before do
Person.autosave(metadata)
Person.autosave(metadata)
end
let(:drug) do
Drug.new(name: "Percocet")
end
it "does not add the autosave callback twice" do
expect(drug).to receive(:save).once
person.drugs.push(drug)
person.save
end
end
context "when the relation is a references many" do
let(:drug) do
Drug.new(name: "Percocet")
end
context "when saving a new parent document" do
before do
person.drugs << drug
person.save
end
it "saves the relation" do
expect(drug).to be_persisted
end
end
context "when saving an existing parent document" do
before do
person.save
person.drugs << drug
person.save
end
it "saves the relation" do
expect(drug).to be_persisted
end
end
context "when not updating the document" do
let(:from_db) do
Person.find person.id
end
before do
person.drugs << drug
person.save
end
it 'does not load the association' do
from_db.save
expect(from_db.ivar(:drugs)).to be false
end
end
end
context "when the relation is a references one" do
let(:account) do
Account.new(name: "Testing")
end
context "when saving a new parent document" do
before do
person.account = account
person.save
end
it "saves the relation" do
expect(account).to be_persisted
end
it "persists on the database" do
expect(account.reload).to_not be_nil
end
end
context "when saving an existing parent document" do
before do
person.save
person.account = account
person.save
end
it "saves the relation" do
expect(account).to be_persisted
end
it "persists on the database" do
expect(account.reload).to_not be_nil
end
end
pending "when updating the child" do
before do
person.account = account
person.save
end
it "sends one insert" do
account.name = "account"
expect_query(1) do
person.with(write: {w:0}).save
end
end
end
context "when not updating the document" do
let(:from_db) do
Person.find person.id
end
before do
person.account = account
person.save
end
it 'does not load the association' do
from_db.save
expect(from_db.ivar(:account)).to be false
end
end
end
context "when the relation is a referenced in" do
let(:ghost) do
Ghost.new(name: "Slimer")
end
let(:movie) do
Movie.new(title: "Ghostbusters")
end
context "when saving a new parent document" do
before do
ghost.movie = movie
ghost.save
end
it "saves the relation" do
expect(movie).to be_persisted
end
end
context "when saving an existing parent document" do
before do
ghost.save
ghost.movie = movie
ghost.save
end
it "saves the relation" do
expect(movie).to be_persisted
end
end
end
context "when it has two relations with autosaves" do
before do
Person.autosave(Person.relations["drugs"].merge!(autosave: true))
end
let!(:person) do
Person.create(drugs: [percocet], account: account)
end
let(:from_db) do
Person.find person.id
end
let(:percocet) do
Drug.new(name: "Percocet")
end
let(:account) do
Account.new(name: "Testing")
end
context "when updating one document" do
let(:placebo) do
Drug.new(name: "Placebo")
end
before do
from_db.drugs = [placebo]
from_db.save
end
it 'loads the updated association' do
expect(from_db.ivar(:drugs)).to eq([placebo])
end
it 'doest not load the other association' do
expect(from_db.ivar(:account)).to be false
end
end
context "when updating none document" do
before do
from_db.save
end
it 'doest not load drugs association' do
expect(from_db.ivar(:drugs)).to be false
end
it 'doest not load account association' do
expect(from_db.ivar(:account)).to be false
end
end
end
end
end
end
| bjori/mongoid | spec/mongoid/relations/auto_save_spec.rb | Ruby | mit | 6,065 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Interface org.apache.commons.math3.util.IntegerSequence.Incrementor.MaxCountExceededCallback (Apache Commons Math 3.6.1 API)</title>
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Interface org.apache.commons.math3.util.IntegerSequence.Incrementor.MaxCountExceededCallback (Apache Commons Math 3.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/commons/math3/util/IntegerSequence.Incrementor.MaxCountExceededCallback.html" title="interface in org.apache.commons.math3.util">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><em><script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script></em></div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/commons/math3/util/class-use/IntegerSequence.Incrementor.MaxCountExceededCallback.html" target="_top">Frames</a></li>
<li><a href="IntegerSequence.Incrementor.MaxCountExceededCallback.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 Interface org.apache.commons.math3.util.IntegerSequence.Incrementor.MaxCountExceededCallback" class="title">Uses of Interface<br>org.apache.commons.math3.util.IntegerSequence.Incrementor.MaxCountExceededCallback</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../org/apache/commons/math3/util/IntegerSequence.Incrementor.MaxCountExceededCallback.html" title="interface in org.apache.commons.math3.util">IntegerSequence.Incrementor.MaxCountExceededCallback</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.apache.commons.math3.util">org.apache.commons.math3.util</a></td>
<td class="colLast">
<div class="block">Convenience routines and common data structures used throughout the commons-math library.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.apache.commons.math3.util">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../org/apache/commons/math3/util/IntegerSequence.Incrementor.MaxCountExceededCallback.html" title="interface in org.apache.commons.math3.util">IntegerSequence.Incrementor.MaxCountExceededCallback</a> in <a href="../../../../../../org/apache/commons/math3/util/package-summary.html">org.apache.commons.math3.util</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../org/apache/commons/math3/util/package-summary.html">org.apache.commons.math3.util</a> with parameters of type <a href="../../../../../../org/apache/commons/math3/util/IntegerSequence.Incrementor.MaxCountExceededCallback.html" title="interface in org.apache.commons.math3.util">IntegerSequence.Incrementor.MaxCountExceededCallback</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../org/apache/commons/math3/util/IntegerSequence.Incrementor.html" title="class in org.apache.commons.math3.util">IntegerSequence.Incrementor</a></code></td>
<td class="colLast"><span class="strong">IntegerSequence.Incrementor.</span><code><strong><a href="../../../../../../org/apache/commons/math3/util/IntegerSequence.Incrementor.html#withCallback(org.apache.commons.math3.util.IntegerSequence.Incrementor.MaxCountExceededCallback)">withCallback</a></strong>(<a href="../../../../../../org/apache/commons/math3/util/IntegerSequence.Incrementor.MaxCountExceededCallback.html" title="interface in org.apache.commons.math3.util">IntegerSequence.Incrementor.MaxCountExceededCallback</a> cb)</code>
<div class="block">Creates a new instance with a given callback.</div>
</td>
</tr>
</tbody>
</table>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing constructors, and an explanation">
<caption><span>Constructors in <a href="../../../../../../org/apache/commons/math3/util/package-summary.html">org.apache.commons.math3.util</a> with parameters of type <a href="../../../../../../org/apache/commons/math3/util/IntegerSequence.Incrementor.MaxCountExceededCallback.html" title="interface in org.apache.commons.math3.util">IntegerSequence.Incrementor.MaxCountExceededCallback</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colLast"><code><strong><a href="../../../../../../org/apache/commons/math3/util/IterationManager.html#IterationManager(int,%20org.apache.commons.math3.util.IntegerSequence.Incrementor.MaxCountExceededCallback)">IterationManager</a></strong>(int maxIterations,
<a href="../../../../../../org/apache/commons/math3/util/IntegerSequence.Incrementor.MaxCountExceededCallback.html" title="interface in org.apache.commons.math3.util">IntegerSequence.Incrementor.MaxCountExceededCallback</a> callBack)</code>
<div class="block">Creates a new instance of this class.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../org/apache/commons/math3/util/IntegerSequence.Incrementor.MaxCountExceededCallback.html" title="interface in org.apache.commons.math3.util">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><em><script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script></em></div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/commons/math3/util/class-use/IntegerSequence.Incrementor.MaxCountExceededCallback.html" target="_top">Frames</a></li>
<li><a href="IntegerSequence.Incrementor.MaxCountExceededCallback.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2003–2016 <a href="http://www.apache.org/">The Apache Software Foundation</a>. All rights reserved.</small></p>
</body>
</html>
| asampley/FactorioRatioAssistant | src/commons-math3-3.6.1/docs/apidocs/org/apache/commons/math3/util/class-use/IntegerSequence.Incrementor.MaxCountExceededCallback.html | HTML | mit | 9,339 |
/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockitousage.matchers;
import static org.mockito.AdditionalMatchers.*;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Matchers;
import org.mockito.Mockito;
import org.mockito.exceptions.verification.WantedButNotInvoked;
import org.mockito.exceptions.verification.junit.ArgumentsAreDifferent;
import org.mockitousage.IMethods;
import org.mockitoutil.TestBase;
@SuppressWarnings("unchecked")
public class MatchersTest extends TestBase {
private IMethods mock;
@Before
public void setUp() {
mock = Mockito.mock(IMethods.class);
}
@Test
public void andOverloaded() {
when(mock.oneArg(and(eq(false), eq(false)))).thenReturn("0");
when(mock.oneArg(and(eq((byte) 1), eq((byte) 1)))).thenReturn("1");
when(mock.oneArg(and(eq('a'), eq('a')))).thenReturn("2");
when(mock.oneArg(and(eq((double) 1), eq((double) 1)))).thenReturn("3");
when(mock.oneArg(and(eq((float) 1), eq((float) 1)))).thenReturn("4");
when(mock.oneArg(and(eq((int) 1), eq((int) 1)))).thenReturn("5");
when(mock.oneArg(and(eq((long) 1), eq((long) 1)))).thenReturn("6");
when(mock.oneArg(and(eq((short) 1), eq((short) 1)))).thenReturn("7");
when(mock.oneArg(and(Matchers.contains("a"), Matchers.contains("d")))).thenReturn("8");
when(mock.oneArg(and(isA(Class.class), eq(Object.class)))).thenReturn("9");
assertEquals("0", mock.oneArg(false));
assertEquals(null, mock.oneArg(true));
assertEquals("1", mock.oneArg((byte) 1));
assertEquals("2", mock.oneArg('a'));
assertEquals("3", mock.oneArg((double) 1));
assertEquals("4", mock.oneArg((float) 1));
assertEquals("5", mock.oneArg((int) 1));
assertEquals("6", mock.oneArg((long) 1));
assertEquals("7", mock.oneArg((short) 1));
assertEquals("8", mock.oneArg("abcde"));
assertEquals(null, mock.oneArg("aaaaa"));
assertEquals("9", mock.oneArg(Object.class));
}
@Test
public void orOverloaded() {
when(mock.oneArg(or(eq(false), eq(true)))).thenReturn("0");
when(mock.oneArg(or(eq((byte) 1), eq((byte) 2)))).thenReturn("1");
when(mock.oneArg(or(eq((char) 1), eq((char) 2)))).thenReturn("2");
when(mock.oneArg(or(eq((double) 1), eq((double) 2)))).thenReturn("3");
when(mock.oneArg(or(eq((float) 1), eq((float) 2)))).thenReturn("4");
when(mock.oneArg(or(eq((int) 1), eq((int) 2)))).thenReturn("5");
when(mock.oneArg(or(eq((long) 1), eq((long) 2)))).thenReturn("6");
when(mock.oneArg(or(eq((short) 1), eq((short) 2)))).thenReturn("7");
when(mock.oneArg(or(eq("asd"), eq("jkl")))).thenReturn("8");
when(mock.oneArg(or(eq(this.getClass()), eq(Object.class)))).thenReturn("9");
assertEquals("0", mock.oneArg(true));
assertEquals("0", mock.oneArg(false));
assertEquals("1", mock.oneArg((byte) 2));
assertEquals("2", mock.oneArg((char) 1));
assertEquals("3", mock.oneArg((double) 2));
assertEquals("4", mock.oneArg((float) 1));
assertEquals("5", mock.oneArg((int) 2));
assertEquals("6", mock.oneArg((long) 1));
assertEquals("7", mock.oneArg((short) 1));
assertEquals("8", mock.oneArg("jkl"));
assertEquals("8", mock.oneArg("asd"));
assertEquals(null, mock.oneArg("asdjkl"));
assertEquals("9", mock.oneArg(Object.class));
assertEquals(null, mock.oneArg(String.class));
}
@Test
public void notOverloaded() {
when(mock.oneArg(not(eq(false)))).thenReturn("0");
when(mock.oneArg(not(eq((byte) 1)))).thenReturn("1");
when(mock.oneArg(not(eq('a')))).thenReturn("2");
when(mock.oneArg(not(eq((double) 1)))).thenReturn("3");
when(mock.oneArg(not(eq((float) 1)))).thenReturn("4");
when(mock.oneArg(not(eq((int) 1)))).thenReturn("5");
when(mock.oneArg(not(eq((long) 1)))).thenReturn("6");
when(mock.oneArg(not(eq((short) 1)))).thenReturn("7");
when(mock.oneArg(not(Matchers.contains("a")))).thenReturn("8");
when(mock.oneArg(not(isA(Class.class)))).thenReturn("9");
assertEquals("0", mock.oneArg(true));
assertEquals(null, mock.oneArg(false));
assertEquals("1", mock.oneArg((byte) 2));
assertEquals("2", mock.oneArg('b'));
assertEquals("3", mock.oneArg((double) 2));
assertEquals("4", mock.oneArg((float) 2));
assertEquals("5", mock.oneArg((int) 2));
assertEquals("6", mock.oneArg((long) 2));
assertEquals("7", mock.oneArg((short) 2));
assertEquals("8", mock.oneArg("bcde"));
assertEquals("9", mock.oneArg(new Object()));
assertEquals(null, mock.oneArg(Class.class));
}
@Test
public void lessOrEqualOverloaded() {
when(mock.oneArg(leq((byte) 1))).thenReturn("1");
when(mock.oneArg(leq((double) 1))).thenReturn("3");
when(mock.oneArg(leq((float) 1))).thenReturn("4");
when(mock.oneArg(leq((int) 1))).thenReturn("5");
when(mock.oneArg(leq((long) 1))).thenReturn("6");
when(mock.oneArg(leq((short) 1))).thenReturn("7");
when(mock.oneArg(leq(new BigDecimal("1")))).thenReturn("8");
assertEquals("1", mock.oneArg((byte) 1));
assertEquals(null, mock.oneArg((byte) 2));
assertEquals("3", mock.oneArg((double) 1));
assertEquals("7", mock.oneArg((short) 0));
assertEquals("4", mock.oneArg((float) -5));
assertEquals("5", mock.oneArg((int) -2));
assertEquals("6", mock.oneArg((long) -3));
assertEquals("8", mock.oneArg(new BigDecimal("0.5")));
assertEquals(null, mock.oneArg(new BigDecimal("1.1")));
}
@Test
public void lessThanOverloaded() {
when(mock.oneArg(lt((byte) 1))).thenReturn("1");
when(mock.oneArg(lt((double) 1))).thenReturn("3");
when(mock.oneArg(lt((float) 1))).thenReturn("4");
when(mock.oneArg(lt((int) 1))).thenReturn("5");
when(mock.oneArg(lt((long) 1))).thenReturn("6");
when(mock.oneArg(lt((short) 1))).thenReturn("7");
when(mock.oneArg(lt(new BigDecimal("1")))).thenReturn("8");
assertEquals("1", mock.oneArg((byte) 0));
assertEquals(null, mock.oneArg((byte) 1));
assertEquals("3", mock.oneArg((double) 0));
assertEquals("7", mock.oneArg((short) 0));
assertEquals("4", mock.oneArg((float) -4));
assertEquals("5", mock.oneArg((int) -34));
assertEquals("6", mock.oneArg((long) -6));
assertEquals("8", mock.oneArg(new BigDecimal("0.5")));
assertEquals(null, mock.oneArg(new BigDecimal("23")));
}
@Test
public void greaterOrEqualMatcherOverloaded() {
when(mock.oneArg(geq((byte) 1))).thenReturn("1");
when(mock.oneArg(geq((double) 1))).thenReturn("3");
when(mock.oneArg(geq((float) 1))).thenReturn("4");
when(mock.oneArg(geq((int) 1))).thenReturn("5");
when(mock.oneArg(geq((long) 1))).thenReturn("6");
when(mock.oneArg(geq((short) 1))).thenReturn("7");
when(mock.oneArg(geq(new BigDecimal("1")))).thenReturn("8");
assertEquals("1", mock.oneArg((byte) 2));
assertEquals(null, mock.oneArg((byte) 0));
assertEquals("3", mock.oneArg((double) 1));
assertEquals("7", mock.oneArg((short) 2));
assertEquals("4", mock.oneArg((float) 3));
assertEquals("5", mock.oneArg((int) 4));
assertEquals("6", mock.oneArg((long) 5));
assertEquals("8", mock.oneArg(new BigDecimal("1.00")));
assertEquals(null, mock.oneArg(new BigDecimal("0.9")));
}
@Test
public void greaterThanMatcherOverloaded() {
when(mock.oneArg(gt((byte) 1))).thenReturn("1");
when(mock.oneArg(gt((double) 1))).thenReturn("3");
when(mock.oneArg(gt((float) 1))).thenReturn("4");
when(mock.oneArg(gt((int) 1))).thenReturn("5");
when(mock.oneArg(gt((long) 1))).thenReturn("6");
when(mock.oneArg(gt((short) 1))).thenReturn("7");
when(mock.oneArg(gt(new BigDecimal("1")))).thenReturn("8");
assertEquals("1", mock.oneArg((byte) 2));
assertEquals(null, mock.oneArg((byte) 1));
assertEquals("3", mock.oneArg((double) 2));
assertEquals("7", mock.oneArg((short) 2));
assertEquals("4", mock.oneArg((float) 3));
assertEquals("5", mock.oneArg((int) 2));
assertEquals("6", mock.oneArg((long) 5));
assertEquals("8", mock.oneArg(new BigDecimal("1.5")));
assertEquals(null, mock.oneArg(new BigDecimal("0.9")));
}
@Test
public void compareToMatcher() {
when(mock.oneArg(cmpEq(new BigDecimal("1.5")))).thenReturn("0");
assertEquals("0", mock.oneArg(new BigDecimal("1.50")));
assertEquals(null, mock.oneArg(new BigDecimal("1.51")));
}
@Test
public void anyStringMatcher() {
when(mock.oneArg(anyString())).thenReturn("matched");
assertEquals("matched", mock.oneArg(""));
assertEquals("matched", mock.oneArg("any string"));
assertEquals(null, mock.oneArg((String) null));
}
@Test
public void anyMatcher() {
when(mock.forObject(any())).thenReturn("matched");
assertEquals("matched", mock.forObject(123));
assertEquals("matched", mock.forObject("any string"));
assertEquals("matched", mock.forObject("any string"));
assertEquals("matched", mock.forObject((Object) null));
}
@Test
public void anyXMatcher() {
when(mock.oneArg(anyBoolean())).thenReturn("0");
when(mock.oneArg(anyByte())).thenReturn("1");
when(mock.oneArg(anyChar())).thenReturn("2");
when(mock.oneArg(anyDouble())).thenReturn("3");
when(mock.oneArg(anyFloat())).thenReturn("4");
when(mock.oneArg(anyInt())).thenReturn("5");
when(mock.oneArg(anyLong())).thenReturn("6");
when(mock.oneArg(anyShort())).thenReturn("7");
when(mock.oneArg((String) anyObject())).thenReturn("8");
when(mock.oneArg(anyObject())).thenReturn("9");
assertEquals("0", mock.oneArg(true));
assertEquals("0", mock.oneArg(false));
assertEquals("1", mock.oneArg((byte) 1));
assertEquals("2", mock.oneArg((char) 1));
assertEquals("3", mock.oneArg((double) 1));
assertEquals("4", mock.oneArg((float) 889));
assertEquals("5", mock.oneArg((int) 1));
assertEquals("6", mock.oneArg((long) 1));
assertEquals("7", mock.oneArg((short) 1));
assertEquals("8", mock.oneArg("Test"));
assertEquals("9", mock.oneArg(new Object()));
assertEquals("9", mock.oneArg(new HashMap()));
}
@Test
public void shouldArrayEqualsDealWithNullArray() throws Exception {
Object[] nullArray = null;
when(mock.oneArray(aryEq(nullArray))).thenReturn("null");
assertEquals("null", mock.oneArray(nullArray));
mock = mock(IMethods.class);
try {
verify(mock).oneArray(aryEq(nullArray));
fail();
} catch (WantedButNotInvoked e) {
assertContains("oneArray(null)", e.getMessage());
}
}
@Test
public void shouldUseSmartEqualsForArrays() throws Exception {
//issue 143
mock.arrayMethod(new String[] {"one"});
verify(mock).arrayMethod(eq(new String[] {"one"}));
verify(mock).arrayMethod(new String[] {"one"});
}
@Test
public void shouldUseSmartEqualsForPrimitiveArrays() throws Exception {
//issue 143
mock.objectArgMethod(new int[] {1, 2});
verify(mock).objectArgMethod(eq(new int[] {1, 2}));
verify(mock).objectArgMethod(new int[] {1, 2});
}
@Test(expected=ArgumentsAreDifferent.class)
public void arrayEqualsShouldThrowArgumentsAreDifferentExceptionForNonMatchingArguments() {
List list = Mockito.mock(List.class);
list.add("test"); // testing fix for issue 20
list.contains(new Object[] {"1"});
Mockito.verify(list).contains(new Object[] {"1", "2", "3"});
}
@Test
public void arrayEqualsMatcher() {
when(mock.oneArray(aryEq(new boolean[] { true, false, false }))).thenReturn("0");
when(mock.oneArray(aryEq(new byte[] { 1 }))).thenReturn("1");
when(mock.oneArray(aryEq(new char[] { 1 }))).thenReturn("2");
when(mock.oneArray(aryEq(new double[] { 1 }))).thenReturn("3");
when(mock.oneArray(aryEq(new float[] { 1 }))).thenReturn("4");
when(mock.oneArray(aryEq(new int[] { 1 }))).thenReturn("5");
when(mock.oneArray(aryEq(new long[] { 1 }))).thenReturn("6");
when(mock.oneArray(aryEq(new short[] { 1 }))).thenReturn("7");
when(mock.oneArray(aryEq(new String[] { "Test" }))).thenReturn("8");
when(mock.oneArray(aryEq(new Object[] { "Test", new Integer(4) }))).thenReturn("9");
assertEquals("0", mock.oneArray(new boolean[] { true, false, false }));
assertEquals("1", mock.oneArray(new byte[] { 1 }));
assertEquals("2", mock.oneArray(new char[] { 1 }));
assertEquals("3", mock.oneArray(new double[] { 1 }));
assertEquals("4", mock.oneArray(new float[] { 1 }));
assertEquals("5", mock.oneArray(new int[] { 1 }));
assertEquals("6", mock.oneArray(new long[] { 1 }));
assertEquals("7", mock.oneArray(new short[] { 1 }));
assertEquals("8", mock.oneArray(new String[] { "Test" }));
assertEquals("9", mock.oneArray(new Object[] { "Test", new Integer(4) }));
assertEquals(null, mock.oneArray(new Object[] { "Test", new Integer(999) }));
assertEquals(null, mock.oneArray(new Object[] { "Test", new Integer(4), "x" }));
assertEquals(null, mock.oneArray(new boolean[] { true, false }));
assertEquals(null, mock.oneArray(new boolean[] { true, true, false }));
}
@Test
public void greaterOrEqualMatcher() {
when(mock.oneArg(geq(7))).thenReturn(">= 7");
when(mock.oneArg(lt(7))).thenReturn("< 7");
assertEquals(">= 7", mock.oneArg(7));
assertEquals(">= 7", mock.oneArg(8));
assertEquals(">= 7", mock.oneArg(9));
assertEquals("< 7", mock.oneArg(6));
assertEquals("< 7", mock.oneArg(6));
}
@Test
public void greaterThanMatcher() {
when(mock.oneArg(gt(7))).thenReturn("> 7");
when(mock.oneArg(leq(7))).thenReturn("<= 7");
assertEquals("> 7", mock.oneArg(8));
assertEquals("> 7", mock.oneArg(9));
assertEquals("> 7", mock.oneArg(10));
assertEquals("<= 7", mock.oneArg(7));
assertEquals("<= 7", mock.oneArg(6));
}
@Test
public void lessOrEqualMatcher() {
when(mock.oneArg(leq(7))).thenReturn("<= 7");
when(mock.oneArg(gt(7))).thenReturn("> 7");
assertEquals("<= 7", mock.oneArg(7));
assertEquals("<= 7", mock.oneArg(6));
assertEquals("<= 7", mock.oneArg(5));
assertEquals("> 7", mock.oneArg(8));
assertEquals("> 7", mock.oneArg(9));
}
@Test
public void lessThanMatcher() {
when(mock.oneArg(lt(7))).thenReturn("< 7");
when(mock.oneArg(geq(7))).thenReturn(">= 7");
assertEquals("< 7", mock.oneArg(5));
assertEquals("< 7", mock.oneArg(6));
assertEquals("< 7", mock.oneArg(4));
assertEquals(">= 7", mock.oneArg(7));
assertEquals(">= 7", mock.oneArg(8));
}
@Test
public void orMatcher() {
when(mock.oneArg(anyInt())).thenReturn("other");
when(mock.oneArg(or(eq(7), eq(9)))).thenReturn("7 or 9");
assertEquals("other", mock.oneArg(10));
assertEquals("7 or 9", mock.oneArg(7));
assertEquals("7 or 9", mock.oneArg(9));
}
@Test
public void nullMatcher() {
when(mock.threeArgumentMethod(eq(1), isNull(), eq(""))).thenReturn("1");
when(mock.threeArgumentMethod(eq(1), not(isNull()), eq(""))).thenReturn("2");
assertEquals("1", mock.threeArgumentMethod(1, null, ""));
assertEquals("2", mock.threeArgumentMethod(1, new Object(), ""));
}
@Test
public void notNullMatcher() {
when(mock.threeArgumentMethod(eq(1), notNull(), eq(""))).thenReturn("1");
when(mock.threeArgumentMethod(eq(1), not(isNotNull()), eq(""))).thenReturn("2");
assertEquals("1", mock.threeArgumentMethod(1, new Object(), ""));
assertEquals("2", mock.threeArgumentMethod(1, null, ""));
}
@Test
public void findMatcher() {
when(mock.oneArg(find("([a-z]+)\\d"))).thenReturn("1");
assertEquals("1", mock.oneArg("ab12"));
assertEquals(null, mock.oneArg("12345"));
assertEquals(null, mock.oneArg((Object) null));
}
@Test
public void matchesMatcher() {
when(mock.oneArg(matches("[a-z]+\\d\\d"))).thenReturn("1");
when(mock.oneArg(matches("\\d\\d\\d"))).thenReturn("2");
assertEquals("1", mock.oneArg("a12"));
assertEquals("2", mock.oneArg("131"));
assertEquals(null, mock.oneArg("blah"));
}
@Test
public void containsMatcher() {
when(mock.oneArg(Matchers.contains("ell"))).thenReturn("1");
when(mock.oneArg(Matchers.contains("ld"))).thenReturn("2");
assertEquals("1", mock.oneArg("hello"));
assertEquals("2", mock.oneArg("world"));
assertEquals(null, mock.oneArg("xlx"));
}
@Test
public void startsWithMatcher() {
when(mock.oneArg(startsWith("ab"))).thenReturn("1");
when(mock.oneArg(startsWith("bc"))).thenReturn("2");
assertEquals("1", mock.oneArg("ab quake"));
assertEquals("2", mock.oneArg("bc quake"));
assertEquals(null, mock.oneArg("ba quake"));
}
@Test
public void endsWithMatcher() {
when(mock.oneArg(Matchers.endsWith("ab"))).thenReturn("1");
when(mock.oneArg(Matchers.endsWith("bc"))).thenReturn("2");
assertEquals("1", mock.oneArg("xab"));
assertEquals("2", mock.oneArg("xbc"));
assertEquals(null, mock.oneArg("ac"));
}
@Test
public void deltaMatcher() {
when(mock.oneArg(eq(1.0D, 0.1D))).thenReturn("1");
when(mock.oneArg(eq(2.0D, 0.1D))).thenReturn("2");
when(mock.oneArg(eq(1.0F, 0.1F))).thenReturn("3");
when(mock.oneArg(eq(2.0F, 0.1F))).thenReturn("4");
when(mock.oneArg(eq(2.0F, 0.1F))).thenReturn("4");
assertEquals("1", mock.oneArg(1.0));
assertEquals("1", mock.oneArg(0.91));
assertEquals("1", mock.oneArg(1.09));
assertEquals("2", mock.oneArg(2.0));
assertEquals("3", mock.oneArg(1.0F));
assertEquals("3", mock.oneArg(0.91F));
assertEquals("3", mock.oneArg(1.09F));
assertEquals("4", mock.oneArg(2.1F));
assertEquals(null, mock.oneArg(2.2F));
}
@Test
public void deltaMatcherPrintsItself() {
try {
verify(mock).oneArg(eq(1.0D, 0.1D));
fail();
} catch (WantedButNotInvoked e) {
assertContains("eq(1.0, 0.1)", e.getMessage());
}
}
@Test
public void sameMatcher() {
Object one = new String("1243");
Object two = new String("1243");
Object three = new String("1243");
assertNotSame(one, two);
assertEquals(one, two);
assertEquals(two, three);
when(mock.oneArg(same(one))).thenReturn("1");
when(mock.oneArg(same(two))).thenReturn("2");
assertEquals("1", mock.oneArg(one));
assertEquals("2", mock.oneArg(two));
assertEquals(null, mock.oneArg(three));
}
@Test
public void eqMatcherAndNulls() {
mock.simpleMethod((Object) null);
verify(mock).simpleMethod((Object) eq(null));
}
@Test
public void sameMatcherAndNulls() {
mock.simpleMethod((Object) null);
verify(mock).simpleMethod(same(null));
}
} | GeeChao/mockito | test/org/mockitousage/matchers/MatchersTest.java | Java | mit | 20,347 |
function substr(str, start, len) {
// discuss at: http://phpjs.org/functions/substr/
// version: 909.322
// original by: Martijn Wieringa
// bugfixed by: T.Wild
// improved by: Onno Marsman
// improved by: Brett Zamir (http://brett-zamir.me)
// revised by: Theriault
// note: Handles rare Unicode characters if 'unicode.semantics' ini (PHP6) is set to 'on'
// example 1: substr('abcdef', 0, -1);
// returns 1: 'abcde'
// example 2: substr(2, 0, -6);
// returns 2: false
// example 3: ini_set('unicode.semantics', 'on');
// example 3: substr('a\uD801\uDC00', 0, -1);
// returns 3: 'a'
// example 4: ini_set('unicode.semantics', 'on');
// example 4: substr('a\uD801\uDC00', 0, 2);
// returns 4: 'a\uD801\uDC00'
// example 5: ini_set('unicode.semantics', 'on');
// example 5: substr('a\uD801\uDC00', -1, 1);
// returns 5: '\uD801\uDC00'
// example 6: ini_set('unicode.semantics', 'on');
// example 6: substr('a\uD801\uDC00z\uD801\uDC00', -3, 2);
// returns 6: '\uD801\uDC00z'
// example 7: ini_set('unicode.semantics', 'on');
// example 7: substr('a\uD801\uDC00z\uD801\uDC00', -3, -1)
// returns 7: '\uD801\uDC00z'
var i = 0,
allBMP = true,
es = 0,
el = 0,
se = 0,
ret = '';
str += '';
var end = str.length;
// BEGIN REDUNDANT
this.php_js = this.php_js || {};
this.php_js.ini = this.php_js.ini || {};
// END REDUNDANT
switch ((this.php_js.ini['unicode.semantics'] && this.php_js.ini['unicode.semantics'].local_value.toLowerCase())) {
case 'on':
// Full-blown Unicode including non-Basic-Multilingual-Plane characters
// strlen()
for (i = 0; i < str.length; i++) {
if (/[\uD800-\uDBFF]/.test(str.charAt(i)) && /[\uDC00-\uDFFF]/.test(str.charAt(i + 1))) {
allBMP = false;
break;
}
}
if (!allBMP) {
if (start < 0) {
for (i = end - 1, es = (start += end); i >= es; i--) {
if (/[\uDC00-\uDFFF]/.test(str.charAt(i)) && /[\uD800-\uDBFF]/.test(str.charAt(i - 1))) {
start--;
es--;
}
}
} else {
var surrogatePairs = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
while ((surrogatePairs.exec(str)) != null) {
var li = surrogatePairs.lastIndex;
if (li - 2 < start) {
start++;
} else {
break;
}
}
}
if (start >= end || start < 0) {
return false;
}
if (len < 0) {
for (i = end - 1, el = (end += len); i >= el; i--) {
if (/[\uDC00-\uDFFF]/.test(str.charAt(i)) && /[\uD800-\uDBFF]/.test(str.charAt(i - 1))) {
end--;
el--;
}
}
if (start > end) {
return false;
}
return str.slice(start, end);
} else {
se = start + len;
for (i = start; i < se; i++) {
ret += str.charAt(i);
if (/[\uD800-\uDBFF]/.test(str.charAt(i)) && /[\uDC00-\uDFFF]/.test(str.charAt(i + 1))) {
se++; // Go one further, since one of the "characters" is part of a surrogate pair
}
}
return ret;
}
break;
}
// Fall-through
case 'off':
// assumes there are no non-BMP characters;
// if there may be such characters, then it is best to turn it on (critical in true XHTML/XML)
default:
if (start < 0) {
start += end;
}
end = typeof len === 'undefined' ? end : (len < 0 ? len + end : len + start);
// PHP returns false if start does not fall within the string.
// PHP returns false if the calculated end comes before the calculated start.
// PHP returns an empty string if start and end are the same.
// Otherwise, PHP returns the portion of the string from start to end.
return start >= str.length || start < 0 || start > end ? !1 : str.slice(start, end);
}
return undefined; // Please Netbeans
} | grshane/monthofmud | web/themes/custom/mom/node_modules/phpjs/functions/strings/substr.js | JavaScript | mit | 4,106 |
#include "Variant.h"
#include "split.h"
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
using namespace vcflib;
int main(int argc, char** argv) {
if (argc != 2) {
cerr << "usage: " << argv[0] << " <vcf file>" << endl
<< "outputs a VCF stream in which 'long' non-complex"
<< "alleles have their position corrected." << endl
<< "assumes that VCF records can't overlap 5'->3'" << endl;
return 1;
}
string filename = argv[1];
VariantCallFile variantFile;
if (filename == "-") {
variantFile.open(std::cin);
} else {
variantFile.open(filename);
}
if (!variantFile.is_open()) {
cerr << "could not open " << filename << endl;
return 1;
}
Variant var(variantFile);
// write the new header
cout << variantFile.header << endl;
// print the records, filtering is done via the setting of varA's output sample names
while (variantFile.getNextVariant(var)) {
// if we just have one parsed alternate (non-complex case)
map<string, vector<VariantAllele> > parsedAlts = var.parsedAlternates(true, true); // use mnps, and previous for indels
// but the alt string is long
//cerr << var.alt.size() << " " << parsedAlts.size() << endl;
if (var.alt.size() == 1 && parsedAlts.size() > 1) {
string& alternate = var.alt.front();
vector<VariantAllele>& vs = parsedAlts[alternate];
vector<VariantAllele> valleles;
for (vector<VariantAllele>::iterator a = vs.begin(); a != vs.end(); ++a) {
if (a->ref != a->alt) {
valleles.push_back(*a);
}
}
if (valleles.size() == 1) {
// do we have extra sequence hanging around?
VariantAllele& varallele = valleles.front();
if (vs.front().ref == vs.front().alt) {
var.position = varallele.position;
var.ref = var.ref.substr(vs.front().ref.size(), varallele.ref.size());
var.alt.front() = varallele.alt;
}
}
}
cout << var << endl;
}
return 0;
}
| benranco/SNPpipeline | tools/vcflib/src/vcfcleancomplex.cpp | C++ | mit | 2,263 |
.domainDetailLogoContainer {width:20%; float:left;}
.domainDetailTabsContainer {width:75%; float:right;}
.logoWhiteness {margin:2px; background:#fff;} /* solid white behind logo, but a margin of 1 so 'edited' creates a border around the image */
.domainList th {text-align:left;}
.domainList th.alignRight {text-align:right;}
.domainList {border-spacing:0 1px;}
.domainList th, .domainList tf {padding:2px 12px 2px 2px; vertical-align:top;}
td.domainDetailRow {border-bottom:1px solid #efefef;}
.hostChooser {max-height:200px; overflow:auto;}
.hostChooserHostList {margin:.2 0 .5em .2em; padding:0; list-style:none;}
.hostChooserHostListItem {margin-bottom:.1em; padding:.2em .5em; cursor:pointer;}
@media only screen and (min-height: 500px) {
.hostChooser {max-height:450px;}
} | speedaddictcycles/speedaddictcycles | extensions/admin/sites.css | CSS | mit | 787 |
// stdafx.cpp : source file that includes just the standard includes
// NETGeographic.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
| JanEicken/MA | libs/GeographicLib-1.43/dotnet/NETGeographicLib/stdafx.cpp | C++ | mit | 204 |
/*
* Copyright (c) 2014 The FreeBSD Foundation.
* All rights reserved.
*
* Portions of this software were developed by Konstantin Belousov
* under sponsorship from the FreeBSD Foundation.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice(s), this list of conditions and the following disclaimer as
* the first lines of this file unmodified other than the possible
* addition of one or more copyright notices.
* 2. Redistributions in binary form must reproduce the above copyright
* notice(s), this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");
#include <sys/types.h>
#include <signal.h>
#include "libc_private.h"
__weak_reference(__sys_sigtimedwait, __sigtimedwait);
#pragma weak sigtimedwait
int
sigtimedwait(const sigset_t * __restrict set, siginfo_t * __restrict info,
const struct timespec * __restrict t)
{
return (((int (*)(const sigset_t *, siginfo_t *,
const struct timespec *))
__libc_interposing[INTERPOS_sigtimedwait])(set, info, t));
}
| kishoredbn/barrelfish | lib/libc/sys/sigtimedwait.c | C | mit | 2,080 |
module Jekyll
class PluginManager
attr_reader :site
# Create an instance of this class.
#
# site - the instance of Jekyll::Site we're concerned with
#
# Returns nothing
def initialize(site)
@site = site
end
# Require all the plugins which are allowed.
#
# Returns nothing
def conscientious_require
require_plugin_files
require_gems
deprecation_checks
end
# Require each of the gem plugins specified.
#
# Returns nothing.
def require_gems
Jekyll::External.require_with_graceful_fail(site.gems.select { |gem| plugin_allowed?(gem) })
end
def self.require_from_bundler
if !ENV["JEKYLL_NO_BUNDLER_REQUIRE"] && File.file?("Gemfile")
require "bundler"
Bundler.setup # puts all groups on the load path
required_gems = Bundler.require(:jekyll_plugins) # requires the gems in this group only
Jekyll.logger.debug("PluginManager:", "Required #{required_gems.map(&:name).join(', ')}")
ENV["JEKYLL_NO_BUNDLER_REQUIRE"] = "true"
true
else
false
end
rescue LoadError, Bundler::GemfileNotFound
false
end
# Check whether a gem plugin is allowed to be used during this build.
#
# gem_name - the name of the gem
#
# Returns true if the gem name is in the whitelist or if the site is not
# in safe mode.
def plugin_allowed?(gem_name)
!site.safe || whitelist.include?(gem_name)
end
# Build an array of allowed plugin gem names.
#
# Returns an array of strings, each string being the name of a gem name
# that is allowed to be used.
def whitelist
@whitelist ||= Array[site.config['whitelist']].flatten
end
# Require all .rb files if safe mode is off
#
# Returns nothing.
def require_plugin_files
unless site.safe
plugins_path.each do |plugin_search_path|
plugin_files = Utils.safe_glob(plugin_search_path, File.join("**", "*.rb"))
Jekyll::External.require_with_graceful_fail(plugin_files)
end
end
end
# Public: Setup the plugin search path
#
# Returns an Array of plugin search paths
def plugins_path
if site.config['plugins_dir'] == Jekyll::Configuration::DEFAULTS['plugins_dir']
[site.in_source_dir(site.config['plugins_dir'])]
else
Array(site.config['plugins_dir']).map { |d| File.expand_path(d) }
end
end
def deprecation_checks
pagination_included = (site.config['gems'] || []).include?('jekyll-paginate') || defined?(Jekyll::Paginate)
if site.config['paginate'] && !pagination_included
Jekyll::Deprecator.deprecation_message "You appear to have pagination " \
"turned on, but you haven't included the `jekyll-paginate` gem. " \
"Ensure you have `gems: [jekyll-paginate]` in your configuration file."
end
end
end
end
| yanz67/yanz67.github.io | vendor/cache/ruby/2.0.0/gems/jekyll-3.1.1/lib/jekyll/plugin_manager.rb | Ruby | mit | 2,953 |
{% extends "blog/blog_post_list.html" %}
{% load mezzanine_tags comment_tags keyword_tags rating_tags i18n disqus_tags %}
{% block meta_title %}{{ blog_post.meta_title }}{% endblock %}
{% block meta_keywords %}{% metablock %}
{% keywords_for blog_post as tags %}
{% for tag in tags %}{% if not forloop.first %}, {% endif %}{{ tag }}{% endfor %}
{% endmetablock %}{% endblock %}
{% block meta_description %}{% metablock %}
{{ blog_post.description }}
{% endmetablock %}{% endblock %}
{% block title %}
{% editable blog_post.title %}{{ blog_post.title }}{% endeditable %}
{% endblock %}
{% block breadcrumb_menu %}
{{ block.super }}
<li class="active">{{ blog_post.title }}</li>
{% endblock %}
{% block main %}
{% block blog_post_detail_postedby %}
{% editable blog_post.publish_date %}
<h6 class="post-meta">
{% trans "Posted by" %}:
{% with blog_post.user as author %}
<a href="{% url "blog_post_list_author" author %}">{{ author.get_full_name|default:author.username }}</a>
{% endwith %}
{% blocktrans with sometime=blog_post.publish_date|timesince %}{{ sometime }} ago{% endblocktrans %}
</h6>
{% endeditable %}
{% endblock %}
{% block blog_post_detail_commentlink %}
<p>
{% if blog_post.allow_comments %}
{% if settings.COMMENTS_DISQUS_SHORTNAME %}
(<a href="{{ blog_post.get_absolute_url }}#disqus_thread"
data-disqus-identifier="{% disqus_id_for blog_post %}">{% spaceless %}
{% trans "Comments" %}
{% endspaceless %}</a>)
{% else %}(<a href="#comments">{% spaceless %}
{% blocktrans count comments_count=blog_post.comments_count %}{{ comments_count }} comment{% plural %}{{ comments_count }} comments{% endblocktrans %}
{% endspaceless %}</a>)
{% endif %}
{% endif %}
</p>
{% endblock %}
{% block blog_post_detail_featured_image %}
{% if settings.BLOG_USE_FEATURED_IMAGE and blog_post.featured_image %}
<p><img class="img-responsive" src="{{ MEDIA_URL }}{% thumbnail blog_post.featured_image 600 0 %}"></p>
{% endif %}
{% endblock %}
{% if settings.COMMENTS_DISQUS_SHORTNAME %}
{% include "generic/includes/disqus_counts.html" %}
{% endif %}
{% block blog_post_detail_content %}
{% editable blog_post.content %}
{{ blog_post.content|richtext_filters|safe }}
{% endeditable %}
{% endblock %}
{% block blog_post_detail_keywords %}
{% keywords_for blog_post as tags %}
{% if tags %}
{% spaceless %}
<ul class="list-inline tags">
<li>{% trans "Tags" %}:</li>
{% for tag in tags %}
<li><a href="{% url "blog_post_list_tag" tag.slug %}">{{ tag }}</a>{% if not forloop.last %}, {% endif %}</li>
{% endfor %}
</ul>
{% endspaceless %}
{% endif %}
{% endblock %}
{% block blog_post_detail_rating %}
<div class="panel panel-default rating">
<div class="panel-body">
{% rating_for blog_post %}
</div>
</div>
{% endblock %}
{% block blog_post_detail_sharebuttons %}
{% set_short_url_for blog_post %}
<a class="btn btn-sm share-twitter" target="_blank" href="https://twitter.com/intent/tweet?url={{ blog_post.short_url|urlencode }}&text={{ blog_post.title|urlencode }}">{% trans "Share on Twitter" %}</a>
<a class="btn btn-sm share-facebook" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u={{ request.build_absolute_uri }}">{% trans "Share on Facebook" %}</a>
{% endblock %}
{% block blog_post_previous_next %}
<ul class="pager">
{% with blog_post.get_previous_by_publish_date as previous %}
{% if previous %}
<li class="previous">
<a href="{{ previous.get_absolute_url }}">← {{ previous }}</a>
</li>
{% endif %}
{% endwith %}
{% with blog_post.get_next_by_publish_date as next %}
{% if next %}
<li class="next">
<a href="{{ next.get_absolute_url }}">{{ next }} →</a>
</li>
{% endif %}
{% endwith %}
</ul>
{% endblock %}
{% block blog_post_detail_related_posts %}
{% if related_posts %}
<div id="related-posts">
<h3>{% trans 'Related posts' %}</h3>
<ul class="list-unstyled">
{% for post in related_posts %}
<li><a href="{{ post.get_absolute_url }}">{{ post.title }}</a></li>
{% endfor %}
</ul>
</div>
{% endif %}
{% endblock %}
{% block blog_post_detail_comments %}
{% if blog_post.allow_comments %}{% comments_for blog_post %}{% endif %}
{% endblock %}
{% endblock %}
| Sikilabs/sikilabs | pages/templates/blog/blog_post_detail.html | HTML | mit | 4,285 |
//
// NSDictionary+Stripe.h
// Stripe
//
// Created by Jack Flintermann on 10/15/15.
// Copyright © 2015 Stripe, Inc. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSDictionary (Stripe)
- (nullable NSDictionary *)stp_dictionaryByRemovingNullsValidatingRequiredFields:(nonnull NSArray *)requiredFields;
@end
void linkNSDictionaryCategory(void);
| thrifty-p2p/thrifty-client | ios/Pods/Stripe/Stripe/NSDictionary+Stripe.h | C | mit | 377 |
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
(function (factory) {
if (typeof module === 'object' && typeof module.exports === 'object') {
var v = factory(require, exports); if (v !== undefined) module.exports = v;
}
else if (typeof define === 'function' && define.amd) {
define(["require", "exports", '../animations/animation', '../util/util', './page-transition'], factory);
}
})(function (require, exports) {
"use strict";
var animation_1 = require('../animations/animation');
var util_1 = require('../util/util');
var page_transition_1 = require('./page-transition');
var DURATION = 500;
var EASING = 'cubic-bezier(0.36,0.66,0.04,1)';
var OPACITY = 'opacity';
var TRANSFORM = 'transform';
var TRANSLATEX = 'translateX';
var OFF_RIGHT = '99.5%';
var OFF_LEFT = '-33%';
var CENTER = '0%';
var OFF_OPACITY = 0.8;
var SHOW_BACK_BTN_CSS = 'show-back-button';
var IOSTransition = (function (_super) {
__extends(IOSTransition, _super);
function IOSTransition() {
_super.apply(this, arguments);
}
IOSTransition.prototype.init = function () {
_super.prototype.init.call(this);
var plt = this.plt;
var enteringView = this.enteringView;
var leavingView = this.leavingView;
var opts = this.opts;
this.duration(util_1.isPresent(opts.duration) ? opts.duration : DURATION);
this.easing(util_1.isPresent(opts.easing) ? opts.easing : EASING);
var backDirection = (opts.direction === 'back');
var enteringHasNavbar = (enteringView && enteringView.hasNavbar());
var leavingHasNavbar = (leavingView && leavingView.hasNavbar());
if (enteringView) {
// get the native element for the entering page
var enteringPageEle = enteringView.pageRef().nativeElement;
// entering content
var enteringContent = new animation_1.Animation(plt, enteringView.contentRef());
enteringContent.element(enteringPageEle.querySelectorAll('ion-header > *:not(ion-navbar),ion-footer > *'));
this.add(enteringContent);
if (backDirection) {
// entering content, back direction
enteringContent
.fromTo(TRANSLATEX, OFF_LEFT, CENTER, true)
.fromTo(OPACITY, OFF_OPACITY, 1, true);
}
else {
// entering content, forward direction
enteringContent
.beforeClearStyles([OPACITY])
.fromTo(TRANSLATEX, OFF_RIGHT, CENTER, true);
}
if (enteringHasNavbar) {
// entering page has a navbar
var enteringNavbarEle = enteringPageEle.querySelector('ion-navbar');
var enteringNavBar = new animation_1.Animation(plt, enteringNavbarEle);
this.add(enteringNavBar);
var enteringTitle = new animation_1.Animation(plt, enteringNavbarEle.querySelector('ion-title'));
var enteringNavbarItems = new animation_1.Animation(plt, enteringNavbarEle.querySelectorAll('ion-buttons,[menuToggle]'));
var enteringNavbarBg = new animation_1.Animation(plt, enteringNavbarEle.querySelector('.toolbar-background'));
var enteringBackButton = new animation_1.Animation(plt, enteringNavbarEle.querySelector('.back-button'));
enteringNavBar
.add(enteringTitle)
.add(enteringNavbarItems)
.add(enteringNavbarBg)
.add(enteringBackButton);
enteringTitle.fromTo(OPACITY, 0.01, 1, true);
enteringNavbarItems.fromTo(OPACITY, 0.01, 1, true);
// set properties depending on direction
if (backDirection) {
// entering navbar, back direction
enteringTitle.fromTo(TRANSLATEX, OFF_LEFT, CENTER, true);
if (enteringView.enableBack()) {
// back direction, entering page has a back button
enteringBackButton
.beforeAddClass(SHOW_BACK_BTN_CSS)
.fromTo(OPACITY, 0.01, 1, true);
}
}
else {
// entering navbar, forward direction
enteringTitle.fromTo(TRANSLATEX, OFF_RIGHT, CENTER, true);
enteringNavbarBg
.beforeClearStyles([OPACITY])
.fromTo(TRANSLATEX, OFF_RIGHT, CENTER, true);
if (enteringView.enableBack()) {
// forward direction, entering page has a back button
enteringBackButton
.beforeAddClass(SHOW_BACK_BTN_CSS)
.fromTo(OPACITY, 0.01, 1, true);
var enteringBackBtnText = new animation_1.Animation(plt, enteringNavbarEle.querySelector('.back-button-text'));
enteringBackBtnText.fromTo(TRANSLATEX, '100px', '0px');
enteringNavBar.add(enteringBackBtnText);
}
else {
enteringBackButton.beforeRemoveClass(SHOW_BACK_BTN_CSS);
}
}
}
}
// setup leaving view
if (leavingView && leavingView.pageRef()) {
// leaving content
var leavingPageEle = leavingView.pageRef().nativeElement;
var leavingContent = new animation_1.Animation(plt, leavingView.contentRef());
leavingContent.element(leavingPageEle.querySelectorAll('ion-header > *:not(ion-navbar),ion-footer > *'));
this.add(leavingContent);
if (backDirection) {
// leaving content, back direction
leavingContent
.beforeClearStyles([OPACITY])
.fromTo(TRANSLATEX, CENTER, '100%');
}
else {
// leaving content, forward direction
leavingContent
.fromTo(TRANSLATEX, CENTER, OFF_LEFT)
.fromTo(OPACITY, 1, OFF_OPACITY)
.afterClearStyles([TRANSFORM, OPACITY]);
}
if (leavingHasNavbar) {
// leaving page has a navbar
var leavingNavbarEle = leavingPageEle.querySelector('ion-navbar');
var leavingNavBar = new animation_1.Animation(plt, leavingNavbarEle);
var leavingTitle = new animation_1.Animation(plt, leavingNavbarEle.querySelector('ion-title'));
var leavingNavbarItems = new animation_1.Animation(plt, leavingNavbarEle.querySelectorAll('ion-buttons,[menuToggle]'));
var leavingNavbarBg = new animation_1.Animation(plt, leavingNavbarEle.querySelector('.toolbar-background'));
var leavingBackButton = new animation_1.Animation(plt, leavingNavbarEle.querySelector('.back-button'));
leavingNavBar
.add(leavingTitle)
.add(leavingNavbarItems)
.add(leavingBackButton)
.add(leavingNavbarBg);
this.add(leavingNavBar);
// fade out leaving navbar items
leavingBackButton.fromTo(OPACITY, 0.99, 0);
leavingTitle.fromTo(OPACITY, 0.99, 0);
leavingNavbarItems.fromTo(OPACITY, 0.99, 0);
if (backDirection) {
// leaving navbar, back direction
leavingTitle.fromTo(TRANSLATEX, CENTER, '100%');
// leaving navbar, back direction, and there's no entering navbar
// should just slide out, no fading out
leavingNavbarBg
.beforeClearStyles([OPACITY])
.fromTo(TRANSLATEX, CENTER, '100%');
var leavingBackBtnText = new animation_1.Animation(plt, leavingNavbarEle.querySelector('.back-button-text'));
leavingBackBtnText.fromTo(TRANSLATEX, CENTER, (300) + 'px');
leavingNavBar.add(leavingBackBtnText);
}
else {
// leaving navbar, forward direction
leavingTitle
.fromTo(TRANSLATEX, CENTER, OFF_LEFT)
.afterClearStyles([TRANSFORM]);
leavingBackButton.afterClearStyles([OPACITY]);
leavingTitle.afterClearStyles([OPACITY]);
leavingNavbarItems.afterClearStyles([OPACITY]);
}
}
}
};
return IOSTransition;
}(page_transition_1.PageTransition));
exports.IOSTransition = IOSTransition;
});
//# sourceMappingURL=transition-ios.js.map | Spect-AR/Spect-AR | node_modules/node_modules/ionic-angular/umd/transitions/transition-ios.js | JavaScript | mit | 9,772 |
/* Copyright (c) 2006-2015 by OpenLayers Contributors (see authors.txt for
* full list of contributors). Published under the 2-clause BSD license.
* See license.txt in the OpenLayers distribution or repository for the
* full text of the license. */
/**
* @requires OpenLayers/Format/XML/VersionedOGC.js
*/
/**
* Class: OpenLayers.Format.OWSCommon
* Read OWSCommon. Create a new instance with the <OpenLayers.Format.OWSCommon>
* constructor.
*
* Inherits from:
* - <OpenLayers.Format.XML.VersionedOGC>
*/
OpenLayers.Format.OWSCommon = OpenLayers.Class(OpenLayers.Format.XML.VersionedOGC, {
/**
* APIProperty: defaultVersion
* {String} Version number to assume if none found. Default is "1.0.0".
*/
defaultVersion: "1.0.0",
/**
* Constructor: OpenLayers.Format.OWSCommon
* Create a new parser for OWSCommon.
*
* Parameters:
* options - {Object} An optional object whose properties will be set on
* this instance.
*/
/**
* Method: getVersion
* Returns the version to use. Subclasses can override this function
* if a different version detection is needed.
*
* Parameters:
* root - {DOMElement}
* options - {Object} Optional configuration object.
*
* Returns:
* {String} The version to use.
*/
getVersion: function(root, options) {
var version = this.version;
if(!version) {
// remember version does not correspond to the OWS version
// it corresponds to the WMS/WFS/WCS etc. request version
var uri = root.getAttribute("xmlns:ows");
// the above will fail if the namespace prefix is different than
// ows and if the namespace is declared on a different element
if (uri && uri.substring(uri.lastIndexOf("/")+1) === "1.1") {
version ="1.1.0";
}
if(!version) {
version = this.defaultVersion;
}
}
return version;
},
/**
* APIMethod: read
* Read an OWSCommon document and return an object.
*
* Parameters:
* data - {String | DOMElement} Data to read.
* options - {Object} Options for the reader.
*
* Returns:
* {Object} An object representing the structure of the document.
*/
CLASS_NAME: "OpenLayers.Format.OWSCommon"
});
| usgin/NGDSDataExplorer | static/lib/ol2-master/lib/OpenLayers/Format/OWSCommon.js | JavaScript | mit | 2,414 |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Tests\Component\HttpFoundation\File;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesser;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
class FileTest extends \PHPUnit_Framework_TestCase
{
protected $file;
public function testGetMimeTypeUsesMimeTypeGuessers()
{
$file = new File(__DIR__.'/Fixtures/test.gif');
$guesser = $this->createMockGuesser($file->getPathname(), 'image/gif');
MimeTypeGuesser::getInstance()->register($guesser);
$this->assertEquals('image/gif', $file->getMimeType());
}
public function testGuessExtensionWithoutGuesser()
{
$file = new File(__DIR__.'/Fixtures/directory/.empty');
$this->assertEquals(null, $file->guessExtension());
}
public function testGuessExtensionIsBasedOnMimeType()
{
$file = new File(__DIR__.'/Fixtures/test');
$guesser = $this->createMockGuesser($file->getPathname(), 'image/gif');
MimeTypeGuesser::getInstance()->register($guesser);
$this->assertEquals('gif', $file->guessExtension());
}
public function testConstructWhenFileNotExists()
{
$this->setExpectedException('Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException');
new File(__DIR__.'/Fixtures/not_here');
}
public function testMove()
{
$path = __DIR__.'/Fixtures/test.copy.gif';
$targetDir = __DIR__.'/Fixtures/directory';
$targetPath = $targetDir.'/test.copy.gif';
@unlink($path);
@unlink($targetPath);
copy(__DIR__.'/Fixtures/test.gif', $path);
$file = new File($path);
$movedFile = $file->move($targetDir);
$this->assertInstanceOf('Symfony\Component\HttpFoundation\File\File', $movedFile);
$this->assertTrue(file_exists($targetPath));
$this->assertFalse(file_exists($path));
$this->assertEquals(realpath($targetPath), $movedFile->getRealPath());
@unlink($targetPath);
}
public function testMoveWithNewName()
{
$path = __DIR__.'/Fixtures/test.copy.gif';
$targetDir = __DIR__.'/Fixtures/directory';
$targetPath = $targetDir.'/test.newname.gif';
@unlink($path);
@unlink($targetPath);
copy(__DIR__.'/Fixtures/test.gif', $path);
$file = new File($path);
$movedFile = $file->move($targetDir, 'test.newname.gif');
$this->assertTrue(file_exists($targetPath));
$this->assertFalse(file_exists($path));
$this->assertEquals(realpath($targetPath), $movedFile->getRealPath());
@unlink($targetPath);
}
public function testMoveToAnUnexistentDirectory()
{
$sourcePath = __DIR__.'/Fixtures/test.copy.gif';
$targetDir = __DIR__.'/Fixtures/directory/sub';
$targetPath = $targetDir.'/test.copy.gif';
@unlink($sourcePath);
@unlink($targetPath);
@rmdir($targetDir);
copy(__DIR__.'/Fixtures/test.gif', $sourcePath);
$file = new File($sourcePath);
$movedFile = $file->move($targetDir);
$this->assertFileExists($targetPath);
$this->assertFileNotExists($sourcePath);
$this->assertEquals(realpath($targetPath), $movedFile->getRealPath());
@unlink($sourcePath);
@unlink($targetPath);
@rmdir($targetDir);
}
public function testGetExtension()
{
$file = new File(__DIR__.'/Fixtures/test.gif');
$this->assertEquals('gif', $file->getExtension());
}
protected function createMockGuesser($path, $mimeType)
{
$guesser = $this->getMock('Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesserInterface');
$guesser
->expects($this->once())
->method('guess')
->with($this->equalTo($path))
->will($this->returnValue($mimeType))
;
return $guesser;
}
}
| gaetanHautecoeur/Welcomebac | vendor/symfony/tests/Symfony/Tests/Component/HttpFoundation/File/FileTest.php | PHP | mit | 4,233 |
// Copyright (c) 2011-2014 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_QT_MACNOTIFICATIONHANDLER_H
#define BITCOIN_QT_MACNOTIFICATIONHANDLER_H
#include <QObject>
/** Macintosh-specific notification handler (supports UserNotificationCenter).
*/
class MacNotificationHandler : public QObject
{
Q_OBJECT
public:
/** shows a macOS 10.8+ UserNotification in the UserNotificationCenter
*/
void showNotification(const QString &title, const QString &text);
/** check if OS can handle UserNotifications */
bool hasUserNotificationCenterSupport(void);
static MacNotificationHandler *instance();
};
#endif // BITCOIN_QT_MACNOTIFICATIONHANDLER_H
| UdjinM6/dash | src/qt/macnotificationhandler.h | C | mit | 810 |
.p-multiselect {
display: inline-flex;
cursor: pointer;
position: relative;
user-select: none;
}
.p-multiselect-trigger {
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
.p-multiselect-label-container {
overflow: hidden;
flex: 1 1 auto;
cursor: pointer;
}
.p-multiselect-label {
display: block;
white-space: nowrap;
cursor: pointer;
overflow: hidden;
text-overflow: ellipsis;
}
.p-multiselect-label-empty {
overflow: hidden;
visibility: hidden;
}
.p-multiselect .p-multiselect-panel {
min-width: 100%;
}
.p-multiselect-panel {
position: absolute;
}
.p-multiselect-items-wrapper {
overflow: auto;
}
.p-multiselect-items {
margin: 0;
padding: 0;
list-style-type: none;
}
.p-multiselect-item {
cursor: pointer;
display: flex;
align-items: center;
font-weight: normal;
white-space: nowrap;
position: relative;
overflow: hidden;
}
.p-multiselect-header {
display: flex;
align-items: center;
justify-content: space-between;
}
.p-multiselect-filter-container {
position: relative;
flex: 1 1 auto;
}
.p-multiselect-filter-icon {
position: absolute;
top: 50%;
margin-top: -.5rem;
}
.p-multiselect-filter-container .p-inputtext {
width: 100%;
}
.p-multiselect-close {
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
overflow: hidden;
position: relative;
}
.p-fluid .p-multiselect {
display: flex;
} | cdnjs/cdnjs | ajax/libs/primeng/10.0.3/resources/components/multiselect/multiselect.css | CSS | mit | 1,552 |
/*
Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'div', 'km', {
IdInputLabel: 'Id',
advisoryTitleInputLabel: 'ចំណងជើងប្រឹក្សា',
cssClassInputLabel: 'Stylesheet Classes',
edit: 'កែ Div',
inlineStyleInputLabel: 'ស្ទីលក្នុងបន្ទាត់',
langDirLTRLabel: 'ពីឆ្វេងទៅស្តាំ(LTR)',
langDirLabel: 'ទិសដៅភាសា',
langDirRTLLabel: 'ពីស្តាំទៅឆ្វេង(RTL)',
languageCodeInputLabel: 'កូដភាសា',
remove: 'ដក Div ចេញ',
styleSelectLabel: 'ស្ទីល',
title: 'បង្កើតអ្នកផ្ទុក Div',
toolbar: 'បង្កើតអ្នកផ្ទុក Div'
} );
| braverokmc79/macaronics-spring-one | web04/src/main/webapp/WEB-INF/views/ckeditor/plugins/div/lang/km.js | JavaScript | epl-1.0 | 883 |
/**
* Copyright (c) 2014,2019 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.smarthome.binding.astro.internal.job;
import static org.eclipse.smarthome.binding.astro.AstroBindingConstants.*;
import static org.eclipse.smarthome.binding.astro.internal.job.Job.*;
import static org.eclipse.smarthome.binding.astro.internal.model.SunPhaseName.*;
import org.eclipse.smarthome.binding.astro.handler.AstroThingHandler;
import org.eclipse.smarthome.binding.astro.internal.model.Planet;
import org.eclipse.smarthome.binding.astro.internal.model.Sun;
import org.eclipse.smarthome.binding.astro.internal.model.SunEclipse;
/**
* Daily scheduled jobs For Sun planet
*
* @author Gerhard Riegler - Initial contribution
* @author Amit Kumar Mondal - Implementation to be compliant with ESH Scheduler
*/
public final class DailyJobSun extends AbstractJob {
private final AstroThingHandler handler;
/**
* Constructor
*
* @param thingUID the Thing UID
* @param handler the {@link AstroThingHandler} instance
* @throws IllegalArgumentException
* if {@code thingUID} or {@code handler} is {@code null}
*/
public DailyJobSun(String thingUID, AstroThingHandler handler) {
super(thingUID);
checkArgument(handler != null, "The handler must not be null");
this.handler = handler;
}
@Override
public void run() {
handler.publishDailyInfo();
String thingUID = getThingUID();
LOGGER.info("Scheduled Astro event-jobs for thing {}", thingUID);
Planet planet = handler.getPlanet();
if (planet == null) {
LOGGER.error("Planet not instantiated");
return;
}
Sun sun = (Sun) planet;
scheduleRange(thingUID, handler, sun.getRise(), EVENT_CHANNEL_ID_RISE);
scheduleRange(thingUID, handler, sun.getSet(), EVENT_CHANNEL_ID_SET);
scheduleRange(thingUID, handler, sun.getNoon(), EVENT_CHANNEL_ID_NOON);
scheduleRange(thingUID, handler, sun.getNight(), EVENT_CHANNEL_ID_NIGHT);
scheduleRange(thingUID, handler, sun.getMorningNight(), EVENT_CHANNEL_ID_MORNING_NIGHT);
scheduleRange(thingUID, handler, sun.getAstroDawn(), EVENT_CHANNEL_ID_ASTRO_DAWN);
scheduleRange(thingUID, handler, sun.getNauticDawn(), EVENT_CHANNEL_ID_NAUTIC_DAWN);
scheduleRange(thingUID, handler, sun.getCivilDawn(), EVENT_CHANNEL_ID_CIVIL_DAWN);
scheduleRange(thingUID, handler, sun.getAstroDusk(), EVENT_CHANNEL_ID_ASTRO_DUSK);
scheduleRange(thingUID, handler, sun.getNauticDusk(), EVENT_CHANNEL_ID_NAUTIC_DUSK);
scheduleRange(thingUID, handler, sun.getCivilDusk(), EVENT_CHANNEL_ID_CIVIL_DUSK);
scheduleRange(thingUID, handler, sun.getEveningNight(), EVENT_CHANNEL_ID_EVENING_NIGHT);
scheduleRange(thingUID, handler, sun.getDaylight(), EVENT_CHANNEL_ID_DAYLIGHT);
SunEclipse eclipse = sun.getEclipse();
scheduleEvent(thingUID, handler, eclipse.getPartial(), EVENT_ECLIPSE_PARTIAL, EVENT_CHANNEL_ID_ECLIPSE, false);
scheduleEvent(thingUID, handler, eclipse.getTotal(), EVENT_ECLIPSE_TOTAL, EVENT_CHANNEL_ID_ECLIPSE, false);
scheduleEvent(thingUID, handler, eclipse.getRing(), EVENT_ECLIPSE_RING, EVENT_CHANNEL_ID_ECLIPSE, false);
// schedule republish jobs
schedulePublishPlanet(thingUID, handler, sun.getZodiac().getEnd());
schedulePublishPlanet(thingUID, handler, sun.getSeason().getNextSeason());
// schedule phase jobs
scheduleSunPhase(thingUID, handler, SUN_RISE, sun.getRise().getStart());
scheduleSunPhase(thingUID, handler, SUN_SET, sun.getSet().getStart());
scheduleSunPhase(thingUID, handler, NIGHT, sun.getNight().getStart());
scheduleSunPhase(thingUID, handler, DAYLIGHT, sun.getDaylight().getStart());
scheduleSunPhase(thingUID, handler, ASTRO_DAWN, sun.getAstroDawn().getStart());
scheduleSunPhase(thingUID, handler, NAUTIC_DAWN, sun.getNauticDawn().getStart());
scheduleSunPhase(thingUID, handler, CIVIL_DAWN, sun.getCivilDawn().getStart());
scheduleSunPhase(thingUID, handler, ASTRO_DUSK, sun.getAstroDusk().getStart());
scheduleSunPhase(thingUID, handler, NAUTIC_DUSK, sun.getNauticDusk().getStart());
scheduleSunPhase(thingUID, handler, CIVIL_DUSK, sun.getCivilDusk().getStart());
}
@Override
public String toString() {
return "Daily job sun " + getThingUID();
}
}
| Snickermicker/smarthome | extensions/binding/org.eclipse.smarthome.binding.astro/src/main/java/org/eclipse/smarthome/binding/astro/internal/job/DailyJobSun.java | Java | epl-1.0 | 4,833 |
<?php //$Id: upgradelib.php,v 1.9.2.10 2010/01/25 00:59:22 mjollnir_ Exp $
/*
* This file is used for special upgrade functions - for example groups and gradebook.
* These functions must use SQL and database related functions only- no other Moodle API,
* because it might depend on db structures that are not yet present during upgrade.
* (Do not use functions from accesslib.php, grades classes or group functions at all!)
*/
/**
* Migrates the grade_letter data to grade_letters
*/
function upgrade_18_letters() {
global $CFG;
$table = new XMLDBTable('grade_letters');
if (table_exists($table)) {
// already converted or development site
return true;
}
$result = true;
/// Rename field grade_low on table grade_letter to lowerboundary
$table = new XMLDBTable('grade_letter');
$field = new XMLDBField('grade_low');
$field->setAttributes(XMLDB_TYPE_NUMBER, '5, 2', null, XMLDB_NOTNULL, null, null, null, '0.00', 'grade_high');
/// Launch rename field grade_low
$result = $result && rename_field($table, $field, 'lowerboundary');
/// Define field grade_high to be dropped from grade_letter
$table = new XMLDBTable('grade_letter');
$field = new XMLDBField('grade_high');
/// Launch drop field grade_high
$result = $result && drop_field($table, $field);
/// Define index courseid (not unique) to be dropped form grade_letter
$table = new XMLDBTable('grade_letter');
$index = new XMLDBIndex('courseid');
$index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('courseid'));
/// Launch drop index courseid
$result = $result && drop_index($table, $index);
/// Rename field courseid on table grade_letter to contextid
$table = new XMLDBTable('grade_letter');
$field = new XMLDBField('courseid');
$field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'id');
/// Launch rename field courseid
$result = $result && rename_field($table, $field, 'contextid');
$sql = "UPDATE {$CFG->prefix}grade_letter
SET contextid=COALESCE((SELECT c.id
FROM {$CFG->prefix}context c
WHERE c.instanceid={$CFG->prefix}grade_letter.contextid AND c.contextlevel=".CONTEXT_COURSE."), 0)";
execute_sql($sql);
/// remove broken records
execute_sql("DELETE FROM {$CFG->prefix}grade_letter WHERE contextid=0");
/// Define table grade_letter to be renamed to grade_letters
$table = new XMLDBTable('grade_letter');
/// Launch rename table for grade_letter
$result = $result && rename_table($table, 'grade_letters');
/// Changing type of field lowerboundary on table grade_letters to number
$table = new XMLDBTable('grade_letters');
$field = new XMLDBField('lowerboundary');
$field->setAttributes(XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, null, 'contextid');
/// Launch change of type for field lowerboundary
$result = $result && change_field_precision($table, $field);
$result = $result && change_field_default($table, $field);
/// Changing the default of field letter on table grade_letters to drop it
$table = new XMLDBTable('grade_letters');
$field = new XMLDBField('letter');
$field->setAttributes(XMLDB_TYPE_CHAR, '255', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null, 'lowerboundary');
/// Launch change of default for field letter
$result = $result && change_field_precision($table, $field);
$result = $result && change_field_default($table, $field);
/// Define index contextidlowerboundary (not unique) to be added to grade_letters
$table = new XMLDBTable('grade_letters');
$index = new XMLDBIndex('contextid-lowerboundary');
$index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('contextid', 'lowerboundary'));
/// Launch add index contextidlowerboundary
$result = $result && add_index($table, $index);
return $result;
}
/**
* This function is used to migrade old data and settings from old gradebook into new grading system.
* It is executed only once for each course during upgrade to 1.9, all grade tables must be empty initially.
* @param int $courseid
*/
function upgrade_18_gradebook($courseid) {
global $CFG;
require_once($CFG->libdir.'/gradelib.php'); // we need constants only
// get all grade items with mod details and categories
$sql = "SELECT gi.*, cm.idnumber as cmidnumber, m.name as modname
FROM {$CFG->prefix}grade_item gi, {$CFG->prefix}course_modules cm, {$CFG->prefix}modules m
WHERE gi.courseid=$courseid AND m.id=gi.modid AND cm.instance=gi.cminstance
ORDER BY gi.sort_order ASC";
if (!$olditems = get_records_sql($sql)) {
//nothing to do - no items present in old gradebook
return true;
}
if (!$oldcats = get_records('grade_category', 'courseid', $courseid, 'id')) {
//there should be at least uncategorised category - hmm, nothing to do
return true;
}
$order = 1;
// create course category
$course_category = new object();
$course_category->courseid = $courseid;
$course_category->fullname = '?';
$course_category->parent = null;
$course_category->aggregation = GRADE_AGGREGATE_WEIGHTED_MEAN2;
$course_category->timemodified = $course_category->timecreated = time();
$course_category->aggregateonlygraded = 0;
if (!$course_category->id = insert_record('grade_categories', $course_category)) {
return false;
}
$course_category->depth = 1;
$course_category->path = '/'.$course_category->id;
if (!update_record('grade_categories', $course_category)) {
return false;
}
// create course item
$course_item = new object();
$course_item->courseid = $courseid;
$course_item->itemtype = 'course';
$course_item->iteminstance = $course_category->id;
$course_item->gradetype = GRADE_TYPE_VALUE;
$course_item->display = GRADE_DISPLAY_TYPE_PERCENTAGE;
$course_item->sortorder = $order++;
$course_item->timemodified = $course_item->timecreated = $course_category->timemodified;
$course_item->needsupdate = 1;
if (!insert_record('grade_items', $course_item)) {
return false;
}
// existing categories
$categories = array();
$hiddenoldcats = array();
if (count($oldcats) == 1) {
$oldcat = reset($oldcats);
if ($oldcat->drop_x_lowest) {
$course_category->droplow = $oldcat->drop_x_lowest;
update_record('grade_categories', $course_category);
}
$categories[$oldcat->id] = $course_category;
} else {
foreach ($oldcats as $oldcat) {
$category = new object();
$category->courseid = $courseid;
$category->fullname = addslashes($oldcat->name);
$category->parent = $course_category->id;
$category->droplow = $oldcat->drop_x_lowest;
$category->aggregation = GRADE_AGGREGATE_WEIGHTED_MEAN2;
$category->timemodified = $category->timecreated = time();
$category->aggregateonlygraded = 0;
if (!$category->id = insert_record('grade_categories', $category)) {
return false;
}
$category->depth = 2;
$category->path = '/'.$course_category->id.'/'.$category->id;
if (!update_record('grade_categories', $category)) {
return false;
}
$categories[$oldcat->id] = $category;
$item = new object();
$item->courseid = $courseid;
$item->itemtype = 'category';
$item->iteminstance = $category->id;
$item->gradetype = GRADE_TYPE_VALUE;
$item->display = GRADE_DISPLAY_TYPE_PERCENTAGE;
$item->plusfactor = $oldcat->bonus_points;
$item->hidden = $oldcat->hidden;
$item->aggregationcoef = $oldcat->weight;
$item->sortorder = $order++;
$item->timemodified = $item->timecreated = $category->timemodified;
$item->needsupdate = 1;
if (!insert_record('grade_items', $item)) {
return false;
}
if ($item->hidden) {
$hiddenoldcats[] = $oldcat->id;
}
}
$course_category->aggregation = GRADE_AGGREGATE_WEIGHTED_MEAN2;
update_record('grade_categories', $course_category);
}
unset($oldcats);
// existing items
$newitems = array();
foreach ($olditems as $olditem) {
if (empty($categories[$olditem->category])) {
continue; // faulty record
}
// proper data are set during activity upgrade or legacy grade fetching
$item = new object();
$item->courseid = $courseid;
$item->itemtype = 'mod';
$item->itemmodule = $olditem->modname;
$item->iteminstance = $olditem->cminstance;
$item->idnumber = $olditem->cmidnumber;
$item->itemname = NULL;
$item->itemnumber = 0;
$item->gradetype = GRADE_TYPE_VALUE;
$item->multfactor = $olditem->scale_grade;
$item->hidden = (int)in_array($olditem->category, $hiddenoldcats);
$item->aggregationcoef = $olditem->extra_credit;
$item->sortorder = $order++;
$item->timemodified = $item->timecreated = time();
$item->needsupdate = 1;
$item->categoryid = $categories[$olditem->category]->id;
if (!$item->id = insert_record('grade_items', $item)) {
return false;
}
$newitems[$olditem->id] = $item;
}
unset($olditems);
// setup up exception handling - exclude grade from aggregation
if ($exceptions = get_records('grade_exceptions', 'courseid', $courseid)) {
foreach ($exceptions as $exception) {
if (!array_key_exists($exception->grade_itemid, $newitems)) {
continue; // broken record
}
$grade = new object();
$grade->excluded = time();
$grade->itemid = $newitems[$exception->grade_itemid]->id;
$grade->userid = $exception->userid;
$grade->timemodified = $grade->timecreated = $grade->excluded;
insert_record('grade_grades', $grade);
}
}
// flag indicating new 1.9.5 upgrade routine
set_config('gradebook_latest195_upgrade', 1);
return true;
}
/**
* Create new groupings tables for upgrade from 1.7.*|1.6.* and so on.
*/
function upgrade_17_groups() {
global $CFG;
$result = true;
/// Define table groupings to be created
$table = new XMLDBTable('groupings');
/// Adding fields to table groupings
$table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
$table->addFieldInfo('courseid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
$table->addFieldInfo('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
$table->addFieldInfo('description', XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null);
$table->addFieldInfo('configdata', XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null);
$table->addFieldInfo('timecreated', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
$table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
/// Adding keys to table groupings
$table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
$table->addKeyInfo('courseid', XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id'));
/// Launch create table for groupings
$result = $result && create_table($table);
// ==========================================
/// Define table groupings_groups to be created
$table = new XMLDBTable('groupings_groups');
/// Adding fields to table groupings_groups
$table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
$table->addFieldInfo('groupingid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
$table->addFieldInfo('groupid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
$table->addFieldInfo('timeadded', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
/// Adding keys to table groupings_groups
$table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
$table->addKeyInfo('groupingid', XMLDB_KEY_FOREIGN, array('groupingid'), 'groupings', array('id'));
$table->addKeyInfo('groupid', XMLDB_KEY_FOREIGN, array('groupid'), 'groups', array('id'));
/// Launch create table for groupings_groups
$result = $result && create_table($table);
/// fix not null constrain
$table = new XMLDBTable('groups');
$field = new XMLDBField('password');
$field->setAttributes(XMLDB_TYPE_CHAR, '50', null, null, null, null, null, null, 'description');
$result = $result && change_field_notnull($table, $field);
/// Rename field password in table groups to enrolmentkey
$table = new XMLDBTable('groups');
$field = new XMLDBField('password');
$field->setAttributes(XMLDB_TYPE_CHAR, '50', null, null, null, null, null, null, 'description');
$result = $result && rename_field($table, $field, 'enrolmentkey');
return $result;
}
/**
* Try to fix broken groups from 1.8 - at least partially
*/
function upgrade_18_broken_groups() {
global $db;
/// Undo password -> enrolmentkey
$table = new XMLDBTable('groups');
$field = new XMLDBField('enrolmentkey');
$field->setAttributes(XMLDB_TYPE_CHAR, '50', null, XMLDB_NOTNULL, null, null, null, null, 'description');
rename_field($table, $field, 'password');
/// Readd courseid field
$table = new XMLDBTable('groups');
$field = new XMLDBField('courseid');
$field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'id');
add_field($table, $field);
/// and courseid key
$table = new XMLDBTable('groups');
$key = new XMLDBKey('courseid');
$key->setAttributes(XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id'));
add_key($table, $key);
}
/**
* Drop, add fields and rename tables for groups upgrade from 1.8.*
* @param XMLDBTable $table 'groups_groupings' table object.
*/
function upgrade_18_groups() {
global $CFG, $db;
$result = upgrade_18_groups_drop_keys_indexes();
/// Delete not used columns
$fields_r = array('viewowngroup', 'viewallgroupsmembers', 'viewallgroupsactivities',
'teachersgroupmark', 'teachersgroupview', 'teachersoverride', 'teacherdeletable');
foreach ($fields_r as $fname) {
$table = new XMLDBTable('groups_groupings');
$field = new XMLDBField($fname);
if (field_exists($table, $field)) {
$result = $result && drop_field($table, $field);
}
}
/// Rename 'groups_groupings' to 'groupings'
$table = new XMLDBTable('groups_groupings');
$result = $result && rename_table($table, 'groupings');
/// Add columns/key 'courseid', exclusivegroups, maxgroupsize, timemodified.
$table = new XMLDBTable('groupings');
$field = new XMLDBField('courseid');
$field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'id');
$result = $result && add_field($table, $field);
$table = new XMLDBTable('groupings');
$key = new XMLDBKey('courseid');
$key->setAttributes(XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id'));
$result = $result && add_key($table, $key);
$table = new XMLDBTable('groupings');
$field = new XMLDBField('configdata');
$field->setAttributes(XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null, 'description');
$result = $result && add_field($table, $field);
$table = new XMLDBTable('groupings');
$field = new XMLDBField('timemodified');
$field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'timecreated');
$result = $result && add_field($table, $field);
//==================
/// Add columns/key 'courseid' into groups table
$table = new XMLDBTable('groups');
$field = new XMLDBField('courseid');
$field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'id');
$result = $result && add_field($table, $field);
$table = new XMLDBTable('groups');
$key = new XMLDBKey('courseid');
$key->setAttributes(XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id'));
$result = $result && add_key($table, $key);
/// Changing nullability of field enrolmentkey on table groups to null
$table = new XMLDBTable('groups');
$field = new XMLDBField('enrolmentkey');
$field->setAttributes(XMLDB_TYPE_CHAR, '50', null, null, null, null, null, null, 'description');
$result = $result && change_field_notnull($table, $field);
//==================
/// Now, rename 'groups_groupings_groups' to 'groupings_groups' and add keys
$table = new XMLDBTable('groups_groupings_groups');
$result = $result && rename_table($table, 'groupings_groups');
$table = new XMLDBTable('groupings_groups');
$key = new XMLDBKey('groupingid');
$key->setAttributes(XMLDB_KEY_FOREIGN, array('groupingid'), 'groupings', array('id'));
$result = $result && add_key($table, $key);
$table = new XMLDBTable('groupings_groups');
$key = new XMLDBKey('groupid');
$key->setAttributes(XMLDB_KEY_FOREIGN, array('groupid'), 'groups', array('id'));
$result = $result && add_key($table, $key);
///=================
/// Transfer courseid from 'mdl_groups_courses_groups' to 'mdl_groups'.
if ($result) {
$sql = "UPDATE {$CFG->prefix}groups
SET courseid = (
SELECT MAX(courseid)
FROM {$CFG->prefix}groups_courses_groups gcg
WHERE gcg.groupid = {$CFG->prefix}groups.id)";
execute_sql($sql);
}
/// Transfer courseid from 'groups_courses_groupings' to 'mdl_groupings'.
if ($result) {
$sql = "UPDATE {$CFG->prefix}groupings
SET courseid = (
SELECT MAX(courseid)
FROM {$CFG->prefix}groups_courses_groupings gcg
WHERE gcg.groupingid = {$CFG->prefix}groupings.id)";
execute_sql($sql);
}
/// Drop the old tables
if ($result) {
drop_table(new XMLDBTable('groups_courses_groups'));
drop_table(new XMLDBTable('groups_courses_groupings'));
drop_table(new XMLDBTable('groups_temp'));
drop_table(new XMLDBTable('groups_members_temp'));
unset_config('group_version');
}
return $result;
}
/**
* Drop keys & indexes for groups upgrade from 1.8.*
*/
function upgrade_18_groups_drop_keys_indexes() {
$result = true;
/// Define index groupid-courseid (unique) to be added to groups_members
$table = new XMLDBTable('groups_members');
$index = new XMLDBIndex('groupid-courseid');
$index->setAttributes(XMLDB_INDEX_UNIQUE, array('groupid', 'userid'));
$result = $result && drop_index($table, $index);
/// Define key courseid (foreign) to be added to groups_courses_groups
$table = new XMLDBTable('groups_courses_groups');
$key = new XMLDBKey('courseid');
$key->setAttributes(XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id'));
$result = $result && drop_key($table, $key);
/// Define key groupid (foreign) to be added to groups_courses_groups
$table = new XMLDBTable('groups_courses_groups');
$key = new XMLDBKey('groupid');
$key->setAttributes(XMLDB_KEY_FOREIGN, array('groupid'), 'groups', array('id'));
$result = $result && drop_key($table, $key);
/// Define index courseid-groupid (unique) to be added to groups_courses_groups
$table = new XMLDBTable('groups_courses_groups');
$index = new XMLDBIndex('courseid-groupid');
$index->setAttributes(XMLDB_INDEX_UNIQUE, array('courseid', 'groupid'));
$result = $result && drop_index($table, $index);
/// Define key courseid (foreign) to be added to groups_courses_groupings
$table = new XMLDBTable('groups_courses_groupings');
$key = new XMLDBKey('courseid');
$key->setAttributes(XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id'));
$result = $result && drop_key($table, $key);
/// Define key groupingid (foreign) to be added to groups_courses_groupings
$table = new XMLDBTable('groups_courses_groupings');
$key = new XMLDBKey('groupingid');
$key->setAttributes(XMLDB_KEY_FOREIGN, array('groupingid'), 'groups_groupings', array('id'));
$result = $result && drop_key($table, $key);
/// Define index courseid-groupingid (unique) to be added to groups_courses_groupings
$table = new XMLDBTable('groups_courses_groupings');
$index = new XMLDBIndex('courseid-groupingid');
$index->setAttributes(XMLDB_INDEX_UNIQUE, array('courseid', 'groupingid'));
$result = $result && drop_index($table, $index);
/// Define key groupingid (foreign) to be added to groups_groupings_groups
$table = new XMLDBTable('groups_groupings_groups');
$key = new XMLDBKey('groupingid');
$key->setAttributes(XMLDB_KEY_FOREIGN, array('groupingid'), 'groups_groupings', array('id'));
$result = $result && drop_key($table, $key);
/// Define key groupid (foreign) to be added to groups_groupings_groups
$table = new XMLDBTable('groups_groupings_groups');
$key = new XMLDBKey('groupid');
$key->setAttributes(XMLDB_KEY_FOREIGN, array('groupid'), 'groups', array('id'));
$result = $result && drop_key($table, $key);
/// Define index groupingid-groupid (unique) to be added to groups_groupings_groups
$table = new XMLDBTable('groups_groupings_groups');
$index = new XMLDBIndex('groupingid-groupid');
$index->setAttributes(XMLDB_INDEX_UNIQUE, array('groupingid', 'groupid'));
$result = $result && drop_index($table, $index);
return $result;
}
function upgrade_fix_category_depths() {
global $CFG, $db;
// first fix incorrect parents
$sql = "SELECT c.id
FROM {$CFG->prefix}course_categories c
WHERE c.parent > 0 AND c.parent NOT IN (SELECT pc.id FROM {$CFG->prefix}course_categories pc)";
if ($rs = get_recordset_sql($sql)) {
while ($cat = rs_fetch_next_record($rs)) {
$cat->depth = 1;
$cat->path = '/'.$cat->id;
$cat->parent = 0;
update_record('course_categories', $cat);
}
rs_close($rs);
}
// now add path and depth to top level categories
$sql = "UPDATE {$CFG->prefix}course_categories
SET depth = 1, path = ".sql_concat("'/'", "id")."
WHERE parent = 0";
execute_sql($sql);
// now fix all other levels - slow but works in all supported dbs
$parentdepth = 1;
$db->debug = true;
while (record_exists('course_categories', 'depth', 0)) {
$sql = "SELECT c.id, pc.path
FROM {$CFG->prefix}course_categories c, {$CFG->prefix}course_categories pc
WHERE c.parent=pc.id AND c.depth=0 AND pc.depth=$parentdepth";
if ($rs = get_recordset_sql($sql)) {
while ($cat = rs_fetch_next_record($rs)) {
$cat->depth = $parentdepth+1;
$cat->path = $cat->path.'/'.$cat->id;
update_record('course_categories', $cat);
}
rs_close($rs);
}
$parentdepth++;
if ($parentdepth > 100) {
//something must have gone wrong - nobody can have more than 100 levels of categories, right?
debugging('Unknown error fixing category depths');
break;
}
}
$db->debug = true;
}
/**
* This function will fix the status of the localhost/all records in the mnet_host table
* checking they exist and adding them if missing + redefine CFG->mnet_localhost_id and
* CFG->mnet_all_hosts_id if needed + update all the users having non-existent mnethostid
* to correct CFG->mnet_localhost_id
*
* Implemented because, at some point, specially in old installations upgraded along
* multiple versions, sometimes the stuff above has ended being inconsistent, causing
* problems here and there (noticeablely in backup/restore). MDL-16879
*/
function upgrade_fix_incorrect_mnethostids() {
global $CFG;
/// Get current $CFG/mnet_host records
$old_mnet_localhost_id = !empty($CFG->mnet_localhost_id) ? $CFG->mnet_localhost_id : 0;
$old_mnet_all_hosts_id = !empty($CFG->mnet_all_hosts_id) ? $CFG->mnet_all_hosts_id : 0;
$current_mnet_localhost_host = get_record('mnet_host', 'wwwroot', addslashes($CFG->wwwroot)); /// By wwwroot
$current_mnet_all_hosts_host = get_record_select('mnet_host', sql_isempty('mnet_host', 'wwwroot', false, false)); /// By empty wwwroot
if (!$moodleapplicationid = get_field('mnet_application', 'id', 'name', 'moodle')) {
$m = (object)array(
'name' => 'moodle',
'display_name' => 'Moodle',
'xmlrpc_server_url' => '/mnet/xmlrpc/server.php',
'sso_land_url' => '/auth/mnet/land.php',
'sso_jump_url' => '/auth/mnet/land.php',
);
$moodleapplicationid = insert_record('mnet_application', $m);
}
/// Create localhost_host if necessary (pretty improbable but better to be 100% in the safe side)
/// Code stolen from mnet_environment->init
if (!$current_mnet_localhost_host) {
$current_mnet_localhost_host = new stdClass();
$current_mnet_localhost_host->wwwroot = $CFG->wwwroot;
$current_mnet_localhost_host->ip_address = '';
$current_mnet_localhost_host->public_key = '';
$current_mnet_localhost_host->public_key_expires = 0;
$current_mnet_localhost_host->last_connect_time = 0;
$current_mnet_localhost_host->last_log_id = 0;
$current_mnet_localhost_host->deleted = 0;
$current_mnet_localhost_host->name = '';
$current_mnet_localhost_host->applicationid = $moodleapplicationid;
/// Get the ip of the server
if (empty($_SERVER['SERVER_ADDR'])) {
/// SERVER_ADDR is only returned by Apache-like webservers
$count = preg_match("@^(?:http[s]?://)?([A-Z0-9\-\.]+).*@i", $current_mnet_localhost_host->wwwroot, $matches);
$my_hostname = $count > 0 ? $matches[1] : false;
$my_ip = gethostbyname($my_hostname); // Returns unmodified hostname on failure. DOH!
if ($my_ip == $my_hostname) {
$current_mnet_localhost_host->ip_address = 'UNKNOWN';
} else {
$current_mnet_localhost_host->ip_address = $my_ip;
}
} else {
$current_mnet_localhost_host->ip_address = $_SERVER['SERVER_ADDR'];
}
$current_mnet_localhost_host->id = insert_record('mnet_host', $current_mnet_localhost_host, true);
}
/// Create all_hosts_host if necessary (pretty improbable but better to be 100% in the safe side)
/// Code stolen from mnet_environment->init
if (!$current_mnet_all_hosts_host) {
$current_mnet_all_hosts_host = new stdClass();
$current_mnet_all_hosts_host->wwwroot = '';
$current_mnet_all_hosts_host->ip_address = '';
$current_mnet_all_hosts_host->public_key = '';
$current_mnet_all_hosts_host->public_key_expires = 0;
$current_mnet_all_hosts_host->last_connect_time = 0;
$current_mnet_all_hosts_host->last_log_id = 0;
$current_mnet_all_hosts_host->deleted = 0;
$current_mnet_all_hosts_host->name = 'All Hosts';
$current_mnet_all_hosts_host->applicationid = $moodleapplicationid;
$current_mnet_all_hosts_host->id = insert_record('mnet_host', $current_mnet_all_hosts_host, true);
}
/// Compare old_mnet_localhost_id and current_mnet_localhost_host
if ($old_mnet_localhost_id != $current_mnet_localhost_host->id) { /// Different = problems
/// Update $CFG->mnet_localhost_id to correct value
set_config('mnet_localhost_id', $current_mnet_localhost_host->id);
/// Delete $old_mnet_localhost_id if exists (users will be assigned to new one below)
delete_records('mnet_host', 'id', $old_mnet_localhost_id);
}
/// Compare old_mnet_all_hosts_id and current_mnet_all_hosts_host
if ($old_mnet_all_hosts_id != $current_mnet_all_hosts_host->id) { /// Different = problems
/// Update $CFG->mnet_localhost_id to correct value
set_config('mnet_all_hosts_id', $current_mnet_all_hosts_host->id);
/// Delete $old_mnet_all_hosts_id if exists
delete_records('mnet_host', 'id', $old_mnet_all_hosts_id);
}
/// Finally, update all the incorrect user->mnethostid to the correct CFG->mnet_localhost_id, preventing UIX dupes
$hosts = get_records_menu('mnet_host', '', '', '', 'id, id AS id2');
$hosts_str = implode(', ', $hosts);
$sql = "SELECT id
FROM {$CFG->prefix}user u1
WHERE u1.mnethostid NOT IN ($hosts_str)
AND NOT EXISTS (
SELECT 'x'
FROM {$CFG->prefix}user u2
WHERE u2.username = u1.username
AND u2.mnethostid = $current_mnet_localhost_host->id)";
$rs = get_recordset_sql($sql);
while ($rec = rs_fetch_next_record($rs)) {
set_field('user', 'mnethostid', $current_mnet_localhost_host->id, 'id', $rec->id);
}
rs_close($rs);
// fix up any host records that have incorrect ids
set_field_select('mnet_host', 'applicationid', $moodleapplicationid, "id = $current_mnet_localhost_host->id or id = $current_mnet_all_hosts_host->id");
}
?>
| nagyistoce/moodle-Teach-Pilot | lib/db/upgradelib.php | PHP | gpl-2.0 | 30,325 |
/*
Copyright (c) 1998 Red Hat Software
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Except as contained in this notice, the name of the X Consortium shall not be
used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from the X Consortium.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#ifdef HAVE_ALLOCA_H
# include <alloca.h>
#else
# ifdef _AIX
# pragma alloca
# endif
#endif
#ifdef HAVE_MALLOC_H
# include <malloc.h>
#endif
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "popt.h"
#include "poptint.h"
#ifdef _WIN32
#define SLASH '\\'
#else
#define SLASH '/'
#endif
static void displayArgs(poptContext con, enum poptCallbackReason foo,
struct poptOption * key,
const char * arg, void * data) {
if (key->shortName== '?')
poptPrintHelp(con, stdout, 0);
else
poptPrintUsage(con, stdout, 0);
exit(0);
}
struct poptOption poptHelpOptions[] = {
{ NULL, '\0', POPT_ARG_CALLBACK, &displayArgs, '\0', NULL },
{ "help", '?', 0, NULL, '?', N_("Show this help message") },
{ "usage", '\0', 0, NULL, 'u', N_("Display brief usage message") },
{ NULL, '\0', 0, NULL, 0 }
} ;
static const char * getArgDescrip(const struct poptOption * opt) {
if (!(opt->argInfo & POPT_ARG_MASK)) return NULL;
if (opt == (poptHelpOptions + 1) || opt == (poptHelpOptions + 2))
if (opt->argDescrip) return POPT_(opt->argDescrip);
if (opt->argDescrip) return _(opt->argDescrip);
return POPT_("ARG");
}
static void singleOptionHelp(FILE * f, int maxLeftCol,
const struct poptOption * opt) {
int indentLength = maxLeftCol + 5;
int lineLength = 79 - indentLength;
const char * help = _(opt->descrip);
int helpLength;
const char * ch;
char * left = alloca(maxLeftCol + 1);
const char * argDescrip = getArgDescrip(opt);
*left = '\0';
if (opt->longName && opt->shortName)
sprintf(left, "-%c, --%s", opt->shortName, opt->longName);
else if (opt->shortName)
sprintf(left, "-%c", opt->shortName);
else if (opt->longName)
sprintf(left, "--%s", opt->longName);
if (!*left) return ;
if (argDescrip) {
strcat(left, "=");
strcat(left, argDescrip);
}
if (help)
fprintf(f," %-*s ", maxLeftCol, left);
else {
fprintf(f," %s\n", left);
return;
}
helpLength = strlen(help);
while (helpLength > lineLength) {
ch = help + lineLength - 1;
while (ch > help && !isspace(*ch)) ch--;
if (ch == help) break; /* give up */
while (ch > (help + 1) && isspace(*ch)) ch--;
ch++;
fprintf(f, "%.*s\n%*s", (int) (ch - help), help, indentLength, " ");
help = ch;
while (isspace(*help) && *help) help++;
helpLength = strlen(help);
}
if (helpLength) fprintf(f, "%s\n", help);
}
static int maxArgWidth(const struct poptOption * opt) {
int max = 0;
int this;
const char * s;
while (opt->longName || opt->shortName || opt->arg) {
if ((opt->argInfo & POPT_ARG_MASK) == POPT_ARG_INCLUDE_TABLE) {
this = maxArgWidth(opt->arg);
if (this > max) max = this;
} else if (!(opt->argInfo & POPT_ARGFLAG_DOC_HIDDEN)) {
this = opt->shortName ? 2 : 0;
if (opt->longName) {
if (this) this += 2;
this += strlen(opt->longName) + 2;
}
s = getArgDescrip(opt);
if (s)
this += strlen(s) + 1;
if (this > max) max = this;
}
opt++;
}
return max;
}
static void singleTableHelp(FILE * f, const struct poptOption * table,
int left) {
const struct poptOption * opt;
opt = table;
while (opt->longName || opt->shortName || opt->arg) {
if ((opt->longName || opt->shortName) &&
!(opt->argInfo & POPT_ARGFLAG_DOC_HIDDEN))
singleOptionHelp(f, left, opt);
opt++;
}
opt = table;
while (opt->longName || opt->shortName || opt->arg) {
if ((opt->argInfo & POPT_ARG_MASK) == POPT_ARG_INCLUDE_TABLE) {
if (opt->descrip)
fprintf(f, "\n%s\n", _(opt->descrip));
singleTableHelp(f, opt->arg, left);
}
opt++;
}
}
static int showHelpIntro(poptContext con, FILE * f) {
int len = 6;
char * fn;
fprintf(f, POPT_("Usage:"));
if (!(con->flags & POPT_CONTEXT_KEEP_FIRST)) {
fn = con->optionStack->argv[0];
if (strchr(fn, SLASH)) fn = strchr(fn, SLASH) + 1;
fprintf(f, " %s", fn);
len += strlen(fn) + 1;
}
return len;
}
void poptPrintHelp(poptContext con, FILE * f, int flags) {
int leftColWidth;
showHelpIntro(con, f);
if (con->otherHelp)
fprintf(f, " %s", con->otherHelp);
else
fprintf(f, " %s", POPT_("[OPTION...]"));
fprintf(f, " [LIBRARIES]\n");
leftColWidth = maxArgWidth(con->options);
singleTableHelp(f, con->options, leftColWidth);
}
static int singleOptionUsage(FILE * f, int cursor,
const struct poptOption * opt) {
int len = 3;
char shortStr[2];
const char * item = shortStr;
const char * argDescrip = getArgDescrip(opt);
if (opt->shortName) {
if (!(opt->argInfo & POPT_ARG_MASK))
return cursor; /* we did these already */
len++;
*shortStr = opt->shortName;
shortStr[1] = '\0';
} else if (opt->longName) {
len += 1 + strlen(opt->longName);
item = opt->longName;
}
if (len == 3) return cursor;
if (argDescrip)
len += strlen(argDescrip) + 1;
if ((cursor + len) > 79) {
fprintf(f, "\n ");
cursor = 7;
}
fprintf(f, " [-%s%s%s%s]", opt->shortName ? "" : "-", item,
argDescrip ? (opt->shortName ? " " : "=") : "",
argDescrip ? argDescrip : "");
return cursor + len + 1;
}
int singleTableUsage(FILE * f, int cursor, const struct poptOption * table) {
const struct poptOption * opt;
opt = table;
while (opt->longName || opt->shortName || opt->arg) {
if ((opt->longName || opt->shortName) &&
!(opt->argInfo & POPT_ARGFLAG_DOC_HIDDEN))
cursor = singleOptionUsage(f, cursor, opt);
else if ((opt->argInfo & POPT_ARG_MASK) == POPT_ARG_INCLUDE_TABLE)
cursor = singleTableUsage(f, cursor, opt->arg);
opt++;
}
return cursor;
}
static int showShortOptions(const struct poptOption * opt, FILE * f,
char * str) {
char s[300]; /* this is larger then the ascii set, so
it should do just fine */
if (!str) {
str = s;
memset(str, 0, sizeof(str));
}
while (opt->longName || opt->shortName || opt->arg) {
if (opt->shortName && !(opt->argInfo & POPT_ARG_MASK))
str[strlen(str)] = opt->shortName;
else if ((opt->argInfo & POPT_ARG_MASK) == POPT_ARG_INCLUDE_TABLE)
showShortOptions(opt->arg, f, str);
opt++;
}
if (s != str || !*s)
return 0;
fprintf(f, " [-%s]", s);
return strlen(s) + 4;
}
void poptPrintUsage(poptContext con, FILE * f, int flags) {
int cursor;
cursor = showHelpIntro(con, f);
cursor += showShortOptions(con->options, f, NULL);
singleTableUsage(f, cursor, con->options);
if (con->otherHelp) {
cursor += strlen(con->otherHelp) + 1;
if (cursor > 79) fprintf(f, "\n ");
fprintf(f, " %s", con->otherHelp);
}
fprintf(f, "\n [LIBRARIES]\n");
}
void poptSetOtherOptionHelp(poptContext con, const char * text) {
if (con->otherHelp) free(con->otherHelp);
con->otherHelp = strdup(text);
}
| bennoleslie/pkg-config | popt/popthelp.c | C | gpl-2.0 | 8,226 |
/* Copyright (C) 2013 Maxim Zakharov. All rights reserved.
Copyright (C) 2003-2012 DataPark Ltd. All rights reserved.
Copyright (C) 2000-2002 Lavtech.com corp. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "dps_common.h"
#include "dps_utils.h"
#include "dps_db.h"
#include "dps_sqldbms.h"
#include "dps_agent.h"
#include "dps_env.h"
#include "dps_conf.h"
#include "dps_services.h"
#include "dps_sdp.h"
#include "dps_log.h"
#include "dps_xmalloc.h"
#include "dps_doc.h"
#include "dps_result.h"
#include "dps_searchtool.h"
#include "dps_vars.h"
#include "dps_match.h"
#include "dps_spell.h"
#include "dps_mutex.h"
#include "dps_signals.h"
#include "dps_socket.h"
#include "dps_store.h"
#include "dps_hash.h"
#include "dps_charsetutils.h"
#include "dps_searchcache.h"
#include "dps_url.h"
#include "dps_template.h"
#include "dps_proto.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#ifdef HAVE_SYS_WAIT_H
#include <sys/wait.h>
#endif
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#ifdef HAVE_SYS_UN_H
#include <sys/un.h>
#endif
#include <errno.h>
#include <locale.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <signal.h>
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#include <fcntl.h>
#ifdef HAVE_NETDB_H
#include <netdb.h>
#endif
#ifdef HAVE_GETOPT_H
#include <getopt.h>
#endif
#ifdef HAVE_SYS_MSG_H
#include <sys/msg.h>
#endif
#ifdef HAVE_SYS_IPC_H
#include <sys/ipc.h>
#endif
/* This should be last include */
#ifdef DMALLOC
#include "dmalloc.h"
#endif
#ifndef INADDR_NONE
#define INADDR_NONE ((unsigned long)-1)
#endif
#ifdef O_BINARY
#define DPS_BINARY O_BINARY
#else
#define DPS_BINARY 0
#endif
#define DEBUG_SEARCH 1
static fd_set mask;
static DPS_CHILD Children[DPS_CHILDREN_LIMIT];
/*static*/ int clt_sock, sockfd;
static pid_t parent_pid = 0;
static size_t MaxClients = 1;
/********************* SIG Handlers ****************/
static void sighandler(int sign);
static void TrackSighandler(int sign);
static void init_signals(void){
/* Set up signals handler*/
DpsSignal(SIGPIPE, sighandler);
DpsSignal(SIGCHLD, sighandler);
DpsSignal(SIGALRM, sighandler);
DpsSignal(SIGUSR1, sighandler);
DpsSignal(SIGUSR2, sighandler);
DpsSignal(SIGHUP, sighandler);
DpsSignal(SIGINT, sighandler);
DpsSignal(SIGTERM, sighandler);
}
static void sighandler(int sign){
pid_t chpid;
#ifdef UNIONWAIT
union wait status;
#else
int status;
#endif
switch(sign){
case SIGPIPE:
have_sigpipe = 1;
break;
case SIGCHLD:
while ((chpid = waitpid(-1, &status, WNOHANG)) > 0) {
register size_t i;
for (i = 0; i < MaxClients; i++) {
if (chpid == Children[i].pid) Children[i].pid = 0;
}
}
break;
case SIGHUP:
have_sighup=1;
break;
case SIGINT:
have_sigint=1;
break;
case SIGTERM:
have_sigterm=1;
break;
case SIGALRM:
_exit(0);
break;
case SIGUSR1:
have_sigusr1 = 1;
break;
case SIGUSR2:
have_sigusr2 = 1;
break;
default:
break;
}
init_signals();
}
static void init_TrackSignals(void){
/* Set up signals handler*/
DpsSignal(SIGPIPE, TrackSighandler);
DpsSignal(SIGCHLD, TrackSighandler);
DpsSignal(SIGALRM, TrackSighandler);
DpsSignal(SIGUSR1, TrackSighandler);
DpsSignal(SIGUSR2, TrackSighandler);
DpsSignal(SIGHUP, TrackSighandler);
DpsSignal(SIGINT, TrackSighandler);
DpsSignal(SIGTERM, TrackSighandler);
}
static void TrackSighandler(int sign){
#ifdef UNIONWAIT
union wait status;
#else
int status;
#endif
switch(sign){
case SIGPIPE:
have_sigpipe = 1;
break;
case SIGCHLD:
while (waitpid(-1, &status, WNOHANG) > 0);
break;
case SIGHUP:
have_sighup=1;
break;
case SIGINT:
have_sigint=1;
break;
case SIGTERM:
have_sigterm=1;
break;
case SIGALRM:
_exit(0);
break;
case SIGUSR1:
have_sigusr1 = 1;
break;
case SIGUSR2:
have_sigusr2 = 1;
break;
default:
break;
}
init_TrackSignals();
}
/*************************************************************/
#define REST_REQ_SIZE 4096
#define MAX_PS 1000
static int do_RESTful(DPS_AGENT *Agent, int client, const DPS_SEARCHD_PACKET_HEADER *hdr) {
char template_name[PATH_MAX+6]="";
DPS_VARLIST query_vars;
DPS_ENV *Env = Agent->Conf;
DPS_RESULT *Res;
const char *p = (const char*)hdr;
const char *conf_dir;
const char *ResultContentType;
char *query_string, *pp;
char *self;
char *template_filename = NULL;
char *nav = NULL;
char *url = NULL;
char *searchwords = NULL;
char *storedstr = NULL;
char *bcharset, *lcharset;
size_t len;
ssize_t nrecv;
int res = DPS_OK;
size_t catcolumns = 0;
ssize_t page1,page2,npages,ppp=10;
int page_size, page_number, have_p = 1, not_first_fl = 0;
size_t i, swlen = 0, nav_len, storedlen;
#ifdef WITH_GOOGLEGRP
int site_id, prev_site_id = 0;
#endif
while (*p != '\0' && *p != ' ') p++; /* skip command name, it's only GET implemented */
if (*p == ' ') p++;
if ((pp = strchr(p, (int)'?')) != NULL) p = pp + 1;
if (*p == '\0') return DPS_ERROR;
query_string = (char*)DpsMalloc(REST_REQ_SIZE);
if (query_string == NULL) return DPS_ERROR;
len = sizeof(*hdr) - (p - (const char*)hdr);
dps_memcpy(query_string, p, len);
nrecv = DpsRecvstr(client, query_string + len, REST_REQ_SIZE - len, 600);
if (nrecv < 0) {
DpsLog(Agent, DPS_ERROR, "RESTful command rceiving error nrecv=%d", (int)nrecv);
DPS_FREE(query_string);
return DPS_ERROR;
}
query_string[nrecv + len] = '\0';
for(pp = query_string; *pp != '\0'; pp++) if (' ' == *pp) { *pp = '\0'; break; }
DpsLog(Agent, DPS_LOG_EXTRA, "RESTful query: %s", query_string);
conf_dir = DpsVarListFindStr(&Env->Vars, "EtcDir", DPS_CONF_DIR);
DpsVarListInit(&query_vars);
DpsParseQStringUnescaped(&query_vars, query_string);
DpsParseQueryString(Agent, &Env->Vars, query_string);
template_filename = (char*)DpsStrdup(DpsVarListFindStr(&Env->Vars, "tmplt", "search.htm"));
dps_snprintf(template_name, sizeof(template_name), "%s/%s", conf_dir,
(p = strrchr(template_filename, DPSSLASH)) ? (p+1) : template_filename);
self = DpsVarListFindStr(&Env->Vars, "PATH_INFO", "");
DpsVarListReplaceStr(&Agent->Conf->Vars, "tmplt", template_filename);
DPS_FREE(template_filename);
Agent->tmpl.Env_Vars = &Env->Vars;
DpsURLNormalizePath(template_name);
#define RESTexit(rc) res = rc; goto farend;
#define RESTstatus(status) DpsSockPrintf(&client, "HTTP/1.0 %d %s\r\nServer: %s\r\nConnection: close\r\n", status, DpsHTTPStatusStr(status), PACKAGE)
if ( (strncmp(template_name, conf_dir, dps_strlen(conf_dir)) || (res = DpsTemplateLoad(Agent, Env, &Agent->tmpl, template_name)))) {
DpsLog(Agent, DPS_LOG_ERROR, "Can't load template: '%s' %s\n", template_name, Env->errstr);
if (strcmp(template_name, "search.htm")) { /* trying load default template */
DPS_FREE(template_filename);
template_filename = (char*)DpsStrdup("search.htm");
dps_snprintf(template_name, sizeof(template_name), "%s/%s", conf_dir, template_filename);
if ((res = DpsTemplateLoad(Agent, Env, &Agent->tmpl, template_name))) {
DpsLog(Agent, DPS_LOG_ERROR, "Can't load default template: '%s' %s\n", template_name, Env->errstr);
DpsSockPrintf(&client, "%s\n", Env->errstr);
RESTexit(DPS_ERROR);
}
} else {
DpsSockPrintf(&client, "%s\n", Env->errstr);
RESTexit(DPS_ERROR);
}
}
/* set locale if specified */
if ((url = DpsVarListFindStr(&Env->Vars, "Locale", NULL)) != NULL) {
setlocale(LC_COLLATE, url);
setlocale(LC_CTYPE, url);
setlocale(LC_ALL, url);
{ char *p;
if ((p = strchr(url, '.')) != NULL) {
*p = '\0';
DpsVarListReplaceStr(&Env->Vars, "g-lc", url);
*p = '.';
}
}
url = NULL;
}
/* set TZ if specified */
if ((url = DpsVarListFindStr(&Env->Vars, "TZ", NULL)) != NULL) {
setenv("TZ", url, 1);
tzset();
url = NULL;
}
/* Call again to load search Limits if need */
DpsParseQueryString(Agent, &Env->Vars, query_string);
DpsVarListAddLst(&Agent->Vars, &Env->Vars, NULL, "*");
Agent->tmpl.Env_Vars = &Agent->Vars;
/* This is for query tracking */
DpsVarListAddStr(&Agent->Vars, "QUERY_STRING", query_string);
DpsVarListAddStr(&Agent->Vars, "self", self);
bcharset = DpsVarListFindStr(&Agent->Vars, "BrowserCharset", "iso-8859-1");
Env->bcs = DpsGetCharSet(bcharset);
lcharset = DpsVarListFindStr(&Agent->Vars, "LocalCharset", "iso-8859-1");
Env->lcs = DpsGetCharSet(lcharset);
if(!Env->bcs) {
RESTstatus(DPS_HTTP_STATUS_INTERNAL_SERVER_ERROR);
DpsSockPrintf(&client, "Unknown BrowserCharset '%s' in template '%s'\n", bcharset, template_name);
RESTexit(DPS_ERROR);
}
if(!Env->lcs) {
RESTstatus(DPS_HTTP_STATUS_INTERNAL_SERVER_ERROR);
DpsSockPrintf(&client, "Unknown LocalCharset '%s' in template '%s'\n", lcharset, template_name);
RESTexit(DPS_ERROR);
}
ppp = DpsVarListFindInt(&Agent->Vars, "PagesPerScreen", 10);
ResultContentType = DpsVarListFindStr(&Agent->Vars, "ResultContentType", "text/html");
RESTstatus(DPS_HTTP_STATUS_OK);
/* Date: header */
{
char buf[64];
DpsTime_t2HttpStr(Agent->now, buf);
DpsSockPrintf(&client, "Date: %s\r\n", buf);
}
/* Add user defined headers */
/*
for(i = 0; i < Agent->tmpl.Env_Vars->Root[(size_t)'r'].nvars; i++) {
DPS_VAR *Hdr = &Agent->tmpl.Env_Vars->Root[(size_t)'r'].Var[i];
if (strncmp(DPS_NULL2EMPTY(Hdr->name), "Request.", 8)) continue;
DpsSockPrintf(&client, "%s: %s\r\n", Hdr->name + 8, Hdr->val);
}
*/
DpsSockPrintf(&client, "Content-Type: %s; charset=%s\r\n\r\n", ResultContentType, bcharset);
res = DpsVarListFindInt(&Agent->Vars, "ps", DPS_DEFAULT_PS);
page_size = dps_min(res, MAX_PS);
page_number = DpsVarListFindInt(&Agent->Vars, "p", 0);
if (page_number == 0) {
page_number = DpsVarListFindInt(&Agent->Vars, "np", 0);
DpsVarListReplaceInt(&Agent->Vars, "p", page_number + 1);
have_p = 0;
} else page_number--;
res = DpsVarListFindInt(&Agent->Vars, "np", 0) * page_size;
DpsVarListAddInt(&Agent->Vars, "pn", res);
catcolumns = (size_t)atoi(DpsVarListFindStr(&Agent->Vars, "CatColumns", ""));
if(NULL == (Res = DpsFind(Agent))) {
DpsVarListAddStr(&Agent->Vars, "E", DpsEnvErrMsg(Agent->Conf));
DpsTemplatePrint(Agent, (DPS_OUTPUTFUNCTION)&DpsSockPrintf, &client, NULL, 0, &Agent->tmpl, "top");
DpsTemplatePrint(Agent, (DPS_OUTPUTFUNCTION)&DpsSockPrintf, &client, NULL, 0, &Agent->tmpl, "error");
TRACE_LINE(Agent);
goto end;
}
DpsVarListAddInt(&Agent->Vars, "first", (int)Res->first);
DpsVarListAddInt(&Agent->Vars, "last", (int)Res->last);
DpsVarListAddInt(&Agent->Vars, "total", (int)Res->total_found);
DpsVarListAddInt(&Agent->Vars, "grand_total", (int)Res->grand_total);
#ifdef HAVE_ASPELL
{ const char *q_save;
if (Res->Suggest != NULL) {
q_save = DpsStrdup(DpsVarListFindStr(&query_vars, "q", ""));
DpsVarListReplaceStr(&query_vars, "q", Res->Suggest);
DpsBuildPageURL(&query_vars, &url);
DpsVarListReplaceStr(&Agent->Vars, "Suggest_q", Res->Suggest);
DpsVarListReplaceStr(&Agent->Vars, "Suggest_url", url);
DpsVarListReplaceStr(&query_vars, "q", q_save);
DPS_FREE(q_save);
}
}
#endif
TRACE_LINE(Agent);
{
const char *s_save = DpsStrdup(DpsVarListFindStr(&query_vars, "s", ""));
int p_save = DpsVarListFindInt(&query_vars, "p", 0);
int np_save = DpsVarListFindInt(&query_vars, "np", 0);
if (p_save == 0) {
DpsVarListReplaceInt(&query_vars, "np", 0);
} else {
DpsVarListReplaceInt(&query_vars, "p", 1);
DpsVarListDel(&query_vars, "np");
}
DpsVarListDel(&query_vars, "s");
DpsBuildPageURL(&query_vars, &url);
DpsVarListReplaceStr(&Agent->Vars, "FirstPage", url);
if (*s_save != '\0') DpsVarListReplaceStr(&query_vars, "s", s_save);
if (np_save) DpsVarListReplaceInt(&query_vars, "np", np_save);
if (p_save) DpsVarListReplaceInt(&query_vars, "p", p_save);
DPS_FREE(s_save);
}
DpsTemplatePrint(Agent, (DPS_OUTPUTFUNCTION)&DpsSockPrintf, &client, NULL, 0, &Agent->tmpl, "top");
if((Res->WWList.nwords == 0) && (Res->nitems - Res->ncmds == 0) && (Res->num_rows == 0)){
DpsTemplatePrint(Agent, (DPS_OUTPUTFUNCTION)&DpsSockPrintf, &client, NULL, 0, &Agent->tmpl, "noquery");
TRACE_LINE(Agent);
goto freeres;
}
if(Res->num_rows == 0) {
DpsTemplatePrint(Agent, (DPS_OUTPUTFUNCTION)&DpsSockPrintf, &client, NULL, 0, &Agent->tmpl, "notfound");
TRACE_LINE(Agent);
goto freeres;
}
for (i = 0; i < Res->WWList.nwords; i++) {
swlen += (8 * Res->WWList.Word[i].len) + 2;
}
if ((searchwords = DpsXmalloc(swlen + 1)) != NULL) {
int z=0;
for (i = 0; i < Res->WWList.nwords; i++) {
if (Res->WWList.Word[i].count > 0) {
sprintf(DPS_STREND(searchwords), (z)?"+%s":"%s", Res->WWList.Word[i].word);
z++;
}
}
}
storedstr = DpsRealloc(storedstr, storedlen = (1024 + 10 * swlen) );
if (storedstr == NULL) {
DpsSockPrintf(&client, "Can't realloc storedstr\n");
res = DPS_ERROR;
goto freeres;
}
npages = (Res->total_found/(page_size?page_size:20)) + ((Res->total_found % (page_size?page_size:20) != 0 ) ? 1 : 0);
page1 = page_number-ppp/2;
page2 = page_number+ppp/2;
if(page1 < 0) {
page2 -= page1;
page1 = 0;
} else if(page2 > npages) {
page1 -= (page2 - npages);
page2 = npages;
}
if(page1 < 0) page1 = page1 = 0;
if(page2 > npages) page2 = npages;
nav = (char *)DpsRealloc(nav, nav_len = (size_t)(page2 - page1 + 2) * (1024 + 1024));
/* !!! 1024 - limit for navbar0/navbar1 template size */
if (nav == NULL) {
DpsSockPrintf(&client, "Can't realloc nav\n");
res = DPS_ERROR;
goto freeres;
}
nav[0] = '\0';
TRACE_LINE(Agent);
/* build NL NB NR */
for(i = (size_t)page1; i < (size_t)page2; i++){
DpsVarListReplaceInt(&query_vars, (have_p) ? "p" : "np", (int)i + have_p);
DpsBuildPageURL(&query_vars, &url);
DpsVarListReplaceStr(&Agent->Vars, "NH", url);
DpsVarListReplaceInt(&Agent->Vars, "NP", (int)(i+1));
DpsTemplatePrint(Agent, (DPS_OUTPUTFUNCTION)&DpsSockPrintf, NULL, DPS_STREND(nav), nav_len - strlen(nav),
&Agent->tmpl, (i == (size_t)page_number)?"navbar0":"navbar1");
}
DpsVarListAddStr(&Agent->Vars, "NB", nav);
DpsVarListReplaceInt(&query_vars, (have_p) ? "p" : "np", page_number - 1 + have_p);
DpsBuildPageURL(&query_vars, &url);
DpsVarListReplaceStr(&Agent->Vars, "NH", url);
if(Res->first == 1) {/* First page */
DpsTemplatePrint(Agent, (DPS_OUTPUTFUNCTION)&DpsSockPrintf, NULL, nav, nav_len, &Agent->tmpl, "navleft_nop");
DpsVarListReplaceStr(&Agent->Vars, "NL", nav);
}else{
DpsTemplatePrint(Agent, (DPS_OUTPUTFUNCTION)&DpsSockPrintf, NULL, nav, nav_len, &Agent->tmpl, "navleft");
DpsVarListReplaceStr(&Agent->Vars, "NL", nav);
}
DpsVarListReplaceInt(&query_vars, (have_p) ? "p" : "np", page_number + 1 + have_p);
DpsBuildPageURL(&query_vars, &url);
DpsVarListReplaceStr(&Agent->Vars, "NH", url);
if(Res->last >= Res->total_found) {/* Last page */
DpsTemplatePrint(Agent, (DPS_OUTPUTFUNCTION)&DpsSockPrintf, NULL, nav, nav_len, &Agent->tmpl, "navright_nop");
DpsVarListReplaceStr(&Agent->Vars, "NR", nav);
} else {
DpsTemplatePrint(Agent, (DPS_OUTPUTFUNCTION)&DpsSockPrintf, NULL, nav, nav_len, &Agent->tmpl, "navright");
DpsVarListReplaceStr(&Agent->Vars, "NR", nav);
}
DpsTemplatePrint(Agent, (DPS_OUTPUTFUNCTION)&DpsSockPrintf, &client, NULL, 0, &Agent->tmpl, "restop");
for(i = 0; i < Res->num_rows; i++) {
DPS_DOCUMENT *Doc = &Res->Doc[i];
DPS_CATEGORY C;
char *clist;
const char *u, *dm;
char *eu, *edm;
char *ct, *ctu;
size_t cl, sc, r, clistsize;
urlid_t dc_url_id = (urlid_t)DpsVarListFindInt(&Doc->Sections, "DP_ID", 0);
urlid_t dc_origin_id = (urlid_t)DpsVarListFindInt(&Doc->Sections, "Origin-ID", 0);
/* Skip clones */
if(dc_origin_id) continue;
if (not_first_fl) {
DpsTemplatePrint(Agent, (DPS_OUTPUTFUNCTION)&DpsSockPrintf, &client, NULL, 0, &Agent->tmpl, "betweenres");
} else not_first_fl = 1;
clist = (char*)DpsMalloc(2048);
if (clist == NULL) {
DpsSockPrintf(&client, "Can't alloc clist\n");
res = DPS_ERROR;
goto freeres;
}
clist[0] = '\0';
clistsize = 0;
for(cl = 0; cl < Res->num_rows; cl++) {
DPS_DOCUMENT *Clone = &Res->Doc[cl];
urlid_t cl_origin_id = (urlid_t)DpsVarListFindInt(&Clone->Sections, "Origin-ID", 0);
if ((dc_url_id == cl_origin_id) && cl_origin_id){
DPS_VARLIST CloneVars;
DpsVarListInit(&CloneVars);
DpsVarListAddLst(&CloneVars, &Agent->Vars, NULL, "*");
DpsVarListReplaceLst(&CloneVars, &Doc->Sections, NULL, "*");
DpsVarListReplaceLst(&CloneVars, &Clone->Sections, NULL, "*");
clist = (char*)DpsRealloc(clist, (clistsize = dps_strlen(clist)) + 2048);
if (clist == NULL) {
DpsSockPrintf(&client, "Can't realloc clist\n");
res = DPS_ERROR;
goto freeres;
}
Agent->tmpl.Env_Vars = &CloneVars;
DpsTemplatePrint(Agent, (DPS_OUTPUTFUNCTION)&DpsSockPrintf, NULL, clist + clistsize, 2048, &Agent->tmpl, "clone");
DpsVarListFree(&CloneVars);
}
}
Agent->tmpl.Env_Vars = &Agent->Vars;
clistsize += 2048;
DpsVarListReplaceStr(&Agent->Vars, "CL", clist);
DpsVarListReplaceInt(&Agent->Vars, "DP_ID", dc_url_id);
DpsVarListReplace(&Agent->Vars, DpsVarListFind(&Doc->Sections, "Alias"));
DpsVarListReplaceStr(&Agent->Vars, "title", "[no title]");
/* Pass all found user-defined sections */
for (r = 0; r < 256; r++)
for (sc = 0; sc < Doc->Sections.Root[r].nvars; sc++) {
DPS_VAR *S = &Doc->Sections.Root[r].Var[sc];
DpsVarListReplace(&Agent->Vars, S);
}
bzero((void*)&C, sizeof(C));
dps_strncpy(C.addr, DpsVarListFindStr(&Doc->Sections, "Category", "0"), sizeof(C.addr));
if(catcolumns && !DpsCatAction(Agent, &C, DPS_CAT_ACTION_PATH)){
char *catpath = NULL, *pp;
size_t c, l = 2;
for(c = (catcolumns > C.ncategories) ? (C.ncategories - catcolumns) : 0; c < C.ncategories; c++)
l += 32 + dps_strlen(C.Category[c].path) + dps_strlen(C.Category[c].name);
pp = catpath = (char*)DpsMalloc(l);
if (catpath != NULL) {
*catpath = '\0';
for(c = (catcolumns > C.ncategories) ? (C.ncategories - catcolumns) : 0; c < C.ncategories; c++) {
sprintf(pp, " > <a href=\"?c=%s\">%s</a> ", C.Category[c].path, C.Category[c].name);
pp += dps_strlen(pp);
}
DpsVarListReplaceStr(&Agent->Vars, "DY", catpath);
DPS_FREE(catpath);
}
}
DPS_FREE(C.Category);
u = DpsVarListFindStrTxt(&Agent->Vars, "URL", "");
eu = (char*)DpsMalloc(dps_strlen(u)*10 + 64);
if (eu == NULL) {
DpsSockPrintf(&client, "Can't alloc eu\n");
res = DPS_ERROR;
goto freeres;
}
DpsEscapeURL(eu, u);
dm = DpsVarListFindStr(&Agent->Vars, "Last-Modified", "");
edm = (char*)DpsMalloc(dps_strlen(dm)*10 + 10);
if (edm == NULL) {
DpsSockPrintf(&client, "Can't alloc edm\n");
res = DPS_ERROR;
goto freeres;
}
DpsEscapeURL(edm, dm);
ct = DpsVarListFindStr(&Agent->Vars, "Content-Type", "");
ctu = (char*)DpsMalloc(dps_strlen(ct) * 10 + 10);
if (ctu == NULL) {
DpsSockPrintf(&client, "Can't alloc ctu\n");
res = DPS_ERROR;
goto freeres;
}
DpsEscapeURL(ctu, ct);
dps_snprintf(storedstr, storedlen, "%s?rec_id=%d&label=%s&DM=%s&DS=%d&L=%s&CS=%s&DU=%s&CT=%s&q=%s",
DpsVarListFindStr(&Agent->Vars, "StoredocURL", "/cgi-bin/storedoc.cgi"),
DpsURL_ID(Doc, NULL),
DpsVarListFindStr(&Agent->Vars, "label", ""),
edm, /* Last-Modified escaped */
sc = DpsVarListFindInt(&Agent->Vars, "Content-Length", 0),
DpsVarListFindStr(&Agent->Vars, "Content-Language", ""),
DpsVarListFindStr(&Agent->Vars, "Charset", ""),
eu, /* URL escaped */
ctu, /* Content-Type escaped */
searchwords
);
if (sc >= 10485760) {
dps_snprintf(eu, 64, "%dM", sc / 1048576);
} else if (sc >= 1048576) {
dps_snprintf(eu, 64, "%.1fM", (double)sc / 1048576);
} else if (sc >= 10240) {
dps_snprintf(eu, 64, "%dK", sc / 1024);
} else if (sc >= 1024) {
dps_snprintf(eu, 64, "%.1fK", (double)sc / 1024);
} else {
dps_snprintf(eu, 64, "%d", sc);
}
DpsVarListReplaceStr(&Agent->Vars, "FancySize", eu);
DpsFree(eu);
DpsFree(edm);
DpsFree(ctu);
if ((DpsVarListFindStr(&Doc->Sections, "Z", NULL) == NULL)) {
DpsVarListReplaceInt(&Agent->Vars, "ST", 1);
DpsVarListReplaceStr(&Agent->Vars, "stored_href", storedstr);
} else {
DpsVarListReplaceInt(&Agent->Vars, "ST", 0);
DpsVarListReplaceStr(&Agent->Vars, "stored_href", "");
}
if (Res->PerSite) {
DpsVarListReplaceUnsigned(&Agent->Vars, "PerSite", Res->PerSite[i + Res->offset * (Res->first - 1)]);
}
/* put Xres sections if any */
for (r = 2; r <= Res->num_rows; r++) {
if ((i + 1) % r == 0) {
dps_snprintf(template_name, sizeof(template_name), "%dres", r);
DpsTemplatePrint(Agent, (DPS_OUTPUTFUNCTION)&DpsSockPrintf, &client, NULL, 0, &Agent->tmpl, template_name);
}
}
if ( (sc = DpsVarListFindInt(&Agent->Vars, "site", 0)) == 0) {
DpsVarListReplaceInt(&query_vars, (have_p) ? "p" : "np", have_p);
DpsVarListReplaceInt(&query_vars, "site",
#ifdef WITH_GOOGLEGRP
site_id =
#endif
DpsVarListFindInt(&Doc->Sections, "Site_id", 0));
DpsBuildPageURL(&query_vars, &url);
DpsVarListReplaceStr(&Agent->Vars, "sitelimit_href", url);
#ifdef WITH_GOOGLEGRP
if (site_id == prev_site_id) {
DpsVarListAddStr(&Agent->Vars, "grouped", "yes");
DpsSockPrintf(&client, "%s", Agent->tmpl.GrBeg);
}
#endif
}
DpsTemplatePrint(Agent, (DPS_OUTPUTFUNCTION)&DpsSockPrintf, &client, NULL, 0, &Agent->tmpl, "res");
#ifdef WITH_GOOGLEGRP
if ((sc == 0) && (site_id == prev_site_id)) {
DpsVarListDel(&Agent->Vars, "grouped");
DpsSockPrintf(&client, "%s", Agent->tmpl.GrEnd);
}
prev_site_id = site_id;
#endif
/* put resX sections if any */
for (r = 2; r <= Res->num_rows; r++) {
if ((i + 1) % r == 0) {
dps_snprintf(template_name, sizeof(template_name), "res%d", r);
DpsTemplatePrint(Agent, (DPS_OUTPUTFUNCTION)&DpsSockPrintf, &client, NULL, 0, &Agent->tmpl, template_name);
}
}
/* Revoke all found user-defined sections */
for (r = 0; r < 256; r++)
for(sc = 0; sc < Doc->Sections.Root[r].nvars; sc++){
DPS_VAR *S = &Doc->Sections.Root[r].Var[sc];
DpsVarListDel(&Agent->Vars, S->name);
}
DpsVarListDel(&Agent->Vars, "body"); /* remoke "body" if it's not in doc's info and made from Excerpt */
DpsFree(clist);
}
TRACE_LINE(Agent);
DpsVarListReplaceInt(&Agent->Vars, (have_p) ? "p" : "np", page_number + have_p);
DpsTemplatePrint(Agent, (DPS_OUTPUTFUNCTION)&DpsSockPrintf, &client, NULL, 0, &Agent->tmpl, "resbot");
DPS_FREE(searchwords);
DPS_FREE(storedstr);
res = DPS_OK;
freeres:
end:
DpsTemplatePrint(Agent, (DPS_OUTPUTFUNCTION)&DpsSockPrintf, &client, NULL, 0, &Agent->tmpl, "bottom");
DpsResultFree(Res);
dps_closesocket(client); /* Too early closure ? */
#ifdef HAVE_ASPELL
if (Agent->Flags.use_aspellext && Agent->naspell > 0) {
register size_t i;
#ifdef UNIONWAIT
union wait status;
#else
int status;
#endif
for (i = 0; i < Agent->naspell; i++) {
if (Agent->aspell_pid[i]) {
kill(Agent->aspell_pid[i], SIGTERM);
Agent->aspell_pid[i] = 0;
}
}
while(waitpid(-1, &status, WNOHANG) > 0);
Agent->naspell = 0;
}
#endif /* HAVE_ASPELL*/
farend:
(void)DpsVarListDelLst(&Env->Vars, &query_vars, NULL, "*");
DpsVarListFree(&query_vars);
DPS_FREE(template_filename);
DPS_FREE(query_string);
DPS_FREE(url);
DPS_FREE(nav);
return res;
}
/*************************************************************/
static int do_client(DPS_AGENT *Agent, int client){
char buf[1024]="";
DPS_SEARCHD_PACKET_HEADER hdr;
DPS_RESULT *Res;
struct sockaddr_in server_addr;
struct sockaddr_in his_addr;
struct in_addr bind_address;
char port_str[16];
char *words = NULL;
ssize_t nrecv,nsent;
int verb = DPS_LOG_EXTRA;
int done=0;
int page_number;
int page_size;
int pre_server, server;
const char *bcharset;
size_t ExcerptSize, ExcerptPadding;
#if defined HAVE_PTHREAD
pthread_t *threads;
DPS_EXCERPT_CFG *Cfg;
pthread_attr_t attr;
#else
DPS_EXCERPT_CFG Cfg;
#endif
#ifdef __irix__
int addrlen;
#else
socklen_t addrlen;
#endif
#ifdef DEBUG_SEARCH
unsigned long ticks = DpsStartTimer();
unsigned long total_ticks;
#else
unsigned long ticks = DpsStartTimer();
#endif
Res=DpsResultInit(NULL);
if (Res == NULL) return DPS_ERROR;
server = client;
while(!done){
size_t dlen = 0, ndocs, i, last_cmd;
int * doc_id=NULL;
char * dinfo=NULL;
char * tok, * lt;
DpsLog(Agent,verb,"Waiting for command header");
nrecv = DpsRecvall(client, &hdr, sizeof(hdr), 5);
if(nrecv != sizeof(hdr)){
DpsLog(Agent,verb,"Received incomplete header nrecv=%d", (int)nrecv);
if (!strncasecmp((char*)&hdr, "GET ", 4)) do_RESTful(Agent, client, &hdr);
break;
}else{
if (!strncasecmp((char*)&hdr, "GET ", 4)) {
do_RESTful(Agent, client, &hdr);
break;
}
DpsLog(Agent,verb,"Received header cmd=%d len=%d", hdr.cmd, hdr.len);
}
switch(last_cmd = hdr.cmd){
case DPS_SEARCHD_CMD_DOCINFO:
dinfo = (char*)DpsRealloc(dinfo, hdr.len + 1);
if (dinfo == NULL) {
DPS_FREE(doc_id);
done=1;
break;
}
nrecv = DpsRecvall(client, dinfo, hdr.len, 360);
if((size_t)nrecv != hdr.len){
DpsLog(Agent,verb,"Received incomplete data nbytes=%d nrecv=%d",hdr.len,(int)nrecv);
DPS_FREE(doc_id);
done=1;
break;
}
dinfo[hdr.len]='\0';
ndocs = 0;
tok = dps_strtok_r(dinfo, "\r\n", <, NULL);
while(tok){
Res->Doc = (DPS_DOCUMENT*)DpsRealloc(Res->Doc, sizeof(DPS_DOCUMENT) * (ndocs + 1));
if (Res->Doc == NULL) {
DPS_FREE(doc_id);
done=1;
break;
}
DpsDocInit(&Res->Doc[ndocs]);
DpsVarListReplaceLst(&Res->Doc[ndocs].Sections, &Agent->Conf->Sections, NULL, "*");
Res->Doc[ndocs].method = DPS_METHOD_GET;
DpsDocFromTextBuf(&Res->Doc[ndocs], tok);
#ifdef WITH_MULTIDBADDR
if ((Agent->flags & DPS_FLAG_UNOCON) ? (Agent->Conf->dbl.nitems > 1) : (Agent->dbl.nitems > 1)) {
char *dbstr = DpsVarListFindStr(&Res->Doc[ndocs].Sections, "dbnum", NULL);
if (dbstr != NULL) {
Res->Doc[ndocs].dbnum = DPS_ATOI(dbstr);
}
}
#endif
tok = dps_strtok_r(NULL, "\r\n", <, NULL);
ndocs++;
}
Res->num_rows = ndocs;
DpsLog(Agent,verb,"Received DOCINFO command len=%d ndocs=%d",hdr.len,ndocs);
#ifdef DEBUG_SEARCH
total_ticks = DpsStartTimer();
#endif
if(DPS_OK != DpsResAction(Agent, Res, DPS_RES_ACTION_DOCINFO)){
/* DpsResultFree(Res); must not be here */
dps_snprintf(buf,sizeof(buf)-1,"%s",DpsEnvErrMsg(Agent->Conf));
DpsLog(Agent, DPS_LOG_ERROR, "ResAction Error: %s", DpsEnvErrMsg(Agent->Conf));
hdr.cmd=DPS_SEARCHD_CMD_ERROR;
hdr.len=dps_strlen(buf);
nsent = DpsSearchdSendPacket(server, &hdr, buf);
done=1;
break;
}
#ifdef DEBUG_SEARCH
total_ticks = DpsStartTimer() - total_ticks;
DpsLog(Agent, DPS_LOG_EXTRA, "ResAction in %.2f sec.", (float)total_ticks / 1000);
#endif
dlen=0;
#ifdef DEBUG_SEARCH
total_ticks = DpsStartTimer();
#endif
DpsAgentStoredConnect(Agent);
ExcerptSize = (size_t)DpsVarListFindInt(&Agent->Vars, "ExcerptSize", 256);
ExcerptPadding = (size_t)DpsVarListFindInt(&Agent->Vars, "ExcerptPadding", 40);
#if defined HAVE_PTHREAD
#ifdef HAVE_PTHREAD_SETCONCURRENCY_PROT
if (pthread_setconcurrency(Res->num_rows + 1) != 0) {
DpsLog(A, DPS_LOG_ERROR, "Can't set %d concurrency threads", Res->num_rows + 1);
}
#elif HAVE_THR_SETCONCURRENCY_PROT
if (thr_setconcurrency(Res->num_rows + 1) != NULL) {
DpsLog(A, DPS_LOG_ERROR, "Can't set %d concurrency threads", Res->num_rows + 1);
}
#endif
threads = (pthread_t*)DpsMalloc((Res->num_rows + 1) * sizeof(pthread_t));
Cfg = (DPS_EXCERPT_CFG*)DpsMalloc((Res->num_rows + 1) * sizeof(DPS_EXCERPT_CFG));
if (threads != NULL && Cfg != NULL) {
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for(i = 0; i < Res->num_rows; i++) {
Cfg[i].query = Agent;
Cfg[i].Res = Res;
Cfg[i].size = ExcerptSize;
Cfg[i].padding = ExcerptPadding;
Cfg[i].Doc = &Res->Doc[i];
if (pthread_create(&threads[i], &attr, &DpsExcerptDoc, Cfg + i) == 0) {
}
}
pthread_attr_destroy(&attr);
}
#else /* HAVE_PTHREAD */
Cfg.query = Agent;
Cfg.Res = Res;
Cfg.size = ExcerptSize;
Cfg.padding = ExcerptPadding;
#endif /* HAVE_PTHREAD */
for(i=0;i<Res->num_rows;i++){
size_t ulen;
size_t olen;
char *textbuf;
size_t nsec, r;
DPS_DOCUMENT *D=&Res->Doc[i];
#if defined(HAVE_PTHREAD)
if (threads != NULL && Cfg != NULL) {
if (pthread_join(threads[i], NULL) != 0) {
}
}
#else
char *al;
al = DpsVarListFindStrTxt(&D->Sections, "URL", "");
DpsLog(Agent, DPS_LOG_DEBUG, "Start excerpts for %s [dbnum:%d]", al, D->dbnum);
if (Agent->Flags.do_excerpt) {
Cfg.Doc = D;
DpsExcerptDoc(&Cfg);
}
#endif
if (DpsVarListFindStr(&D->Sections, "Z", NULL) != NULL) {
DpsVarListReplaceStr(&D->Sections, "ST", "0");
}
textbuf = DpsDocToTextBuf(D, 1, 0);
if (textbuf == NULL) break;
/*
fprintf(stderr, "%s\n\n", textbuf);
*/
ulen=dps_strlen(textbuf)+2;
olen=dlen;
dlen=dlen+ulen;
dinfo=(char*)DpsRealloc(dinfo,dlen+1);
if (dinfo == NULL) {
DPS_FREE(doc_id);
done=1;
break;
}
dinfo[olen]='\0';
sprintf(dinfo+olen,"%s\r\n",textbuf);
DpsFree(textbuf);
}
#if defined HAVE_PTHREAD
DPS_FREE(Cfg);
DPS_FREE(threads);
#endif
#ifdef DEBUG_SEARCH
total_ticks = DpsStartTimer() - total_ticks;
DpsLog(Agent, DPS_LOG_EXTRA, "Excerpts in %.2f sec.", (float)total_ticks / 1000);
#endif
if(!dinfo) dinfo = (char*)DpsStrdup("nodocinfo");
hdr.cmd=DPS_SEARCHD_CMD_DOCINFO;
hdr.len=dps_strlen(dinfo);
nsent = DpsSearchdSendPacket(server, &hdr, dinfo);
DpsLog(Agent, verb, "Sent doc_info packet %d bytes", (int)nsent);
DPS_FREE(dinfo);
break;
case DPS_SEARCHD_CMD_CLONES:
{
DPS_RESULT *Cl;
DPS_DOCUMENT *D;
int origin_id;
char cl_buf[128];
if (hdr.len > 128) {
DpsLog(Agent, verb, "Received too many data bytes=%d", hdr.len);
done = 1;
break;
}
nrecv = DpsRecvall(client, cl_buf, hdr.len, 360);
if((size_t)nrecv != hdr.len){
DpsLog(Agent, verb, "Received incomplete data nbytes=%d nrecv=%d", hdr.len, (int)nrecv);
done = 1;
break;
}
cl_buf[nrecv] = '\0';
sscanf(cl_buf, "%d", &origin_id);
D = DpsDocInit(NULL);
DpsVarListReplaceLst(&D->Sections, &Agent->Conf->Sections, NULL, "*");
D->method = DPS_METHOD_GET;
DpsVarListAddInt(&D->Sections, "DP_ID", origin_id);
Cl = DpsCloneList(Agent, &Agent->Vars, D);
DpsDocFree(D);
dlen=0;
if (Cl) for(i = 0; i < Cl->num_rows; i++) {
size_t ulen;
size_t olen;
char *textbuf;
size_t nsec, r;
D = &Cl->Doc[i];
for (r = 0; r < 256; r++)
for (nsec = 0; nsec < D->Sections.Root[r].nvars; nsec++)
D->Sections.Root[r].Var[nsec].section = 1;
textbuf = DpsDocToTextBuf(D, 1, 0);
if (textbuf == NULL) break;
ulen=dps_strlen(textbuf)+2;
olen=dlen;
dlen=dlen+ulen;
dinfo=(char*)DpsRealloc(dinfo,dlen+1);
if (dinfo == NULL) {
DPS_FREE(doc_id);
done=1;
break;
}
dinfo[olen]='\0';
sprintf(dinfo+olen,"%s\r\n",textbuf);
DpsFree(textbuf);
}
if (!dinfo) dinfo = (char*)DpsStrdup("nocloneinfo");
hdr.cmd = DPS_SEARCHD_CMD_DOCINFO;
hdr.len = dps_strlen(dinfo);
nsent = DpsSearchdSendPacket(server, &hdr, dinfo);
DpsLog(Agent, verb, "Sent clone_info packet %d bytes", (int)nsent);
DPS_FREE(dinfo);
DpsResultFree(Cl);
}
break;
case DPS_SEARCHD_CMD_CATINFO:
{
DPS_CATEGORY Cat;
int cmd;
bzero((void*)&Cat, sizeof(DPS_CATEGORY));
nrecv = DpsRecvall(client, &cmd, sizeof(int), 360);
nrecv = DpsRecvall(client, Cat.addr, hdr.len - sizeof(int), 360);
Cat.addr[hdr.len - sizeof(int)] = '\0';
DpsLog(Agent,verb,"Received CATINFO command len=%d, cmd=%d, addr='%s'", hdr.len, cmd, Cat.addr);
DpsCatAction(Agent, &Cat, cmd);
dlen = Cat.ncategories * 1024;
dinfo = (char*)DpsMalloc(dlen + 1);
if (dinfo == NULL) {
DPS_FREE(doc_id);
done=1;
break;
}
DpsCatToTextBuf(&Cat, dinfo, dlen);
hdr.cmd = DPS_SEARCHD_CMD_CATINFO;
hdr.len = dps_strlen(dinfo);
nsent = DpsSearchdSendPacket(server, &hdr, dinfo);
DpsLog(Agent,verb,"Sent cat_info packet %d bytes",(int)nsent);
DPS_FREE(dinfo);
DPS_FREE(Cat.Category);
}
break;
case DPS_SEARCHD_CMD_URLACTION:
{
int cmd;
DpsLog(Agent,verb,"Received URLACTION command len=%d", hdr.len);
nrecv = DpsRecvall(client, &cmd, sizeof(int), 360);
DpsURLAction(Agent, NULL, cmd);
DpsLog(Agent,verb,"Received URLACTION command len=%d", hdr.len);
hdr.cmd = DPS_SEARCHD_CMD_DOCCOUNT;
hdr.len = sizeof(Agent->doccount);
nsent = DpsSearchdSendPacket(server, &hdr, (char*)&Agent->doccount);
DpsLog(Agent,verb,"Sent doccount packet %d bytes",(int)nsent);
}
break;
case DPS_SEARCHD_CMD_WORDS:
case DPS_SEARCHD_CMD_WORDS_ALL:
words = (char*)DpsRealloc(words, hdr.len + 1);
if (words == NULL) {
dps_snprintf(buf, sizeof(buf)-1, "Can't alloc memory for query");
DpsLog(Agent, verb, "Can't alloc memory for query");
hdr.cmd=DPS_SEARCHD_CMD_ERROR;
hdr.len=dps_strlen(buf);
DpsSearchdSendPacket(server, &hdr, buf);
done=1;
break;
}
nrecv=DpsRecvall(client, words, hdr.len, 360); /* FIXME: check */
words[nrecv]='\0';
DpsLog(Agent, verb, "Received words len=%d words='%s'", nrecv, words);
DpsParseQueryString(Agent, &Agent->Vars, words);
bcharset = DpsVarListFindStr(&Agent->Vars, "BrowserCharset", "iso-8859-1");
if (!(Agent->Conf->bcs = DpsGetCharSet(bcharset))) {
dps_snprintf(buf,sizeof(buf)-1,"Unknown BrowserCharset: %s", bcharset);
DpsLog(Agent,verb,"Unknown BrowserCharset: %s", bcharset);
hdr.cmd=DPS_SEARCHD_CMD_ERROR;
hdr.len=dps_strlen(buf);
DpsSearchdSendPacket(server, &hdr, buf);
done=1;
break;
}
DpsLog(Agent, DPS_LOG_INFO, "Query: [%s:%s:%s:%s] %s ", DpsVarListFindStr(&Agent->Vars, "IP", "localhost"),
DpsVarListFindStr(&Agent->Vars, "tmplt", "search.htm"),
bcharset,
DpsVarListFindStr(&Agent->Vars, "label", ""),
DpsVarListFindStr(&Agent->Vars, "q", ""));
DpsPrepare(Agent, Res); /* Prepare search query */
if(DPS_OK != DpsFindWords(Agent, Res)) {
dps_snprintf(buf,sizeof(buf)-1,"%s",DpsEnvErrMsg(Agent->Conf));
DpsLog(Agent,verb,"%s",DpsEnvErrMsg(Agent->Conf));
hdr.cmd=DPS_SEARCHD_CMD_ERROR;
hdr.len = dps_strlen(buf) + 1;
DpsSearchdSendPacket(server, &hdr, buf);
done=1;
break;
}
dps_snprintf(buf,sizeof(buf)-1,"Total_found=%d %d", Res->total_found, Res->grand_total);
hdr.cmd=DPS_SEARCHD_CMD_MESSAGE;
hdr.len = dps_strlen(buf) + 1;
nsent=DpsSearchdSendPacket(server, &hdr, buf);
DpsLog(Agent,verb,"Sent total_found packet %d bytes buf='%s'",(int)nsent,buf);
/* if (Res->offset) {
hdr.cmd = DPS_SEARCHD_CMD_WITHOFFSET;
hdr.len = 0;
nsent = DpsSearchdSendPacket(server, &hdr, buf);
DpsLog(Agent,verb,"Sent withoffset packet %d bytes",(int)nsent);
}*/
{
char *wbuf, *p;
p = DpsVarListFindStr(&Agent->Vars, "q", "");
hdr.cmd = DPS_SEARCHD_CMD_QLC;
hdr.len = dps_strlen(p);
nsent = DpsSearchdSendPacket(server, &hdr, p);
if (nsent != sizeof(hdr) + hdr.len) {
DpsLog(Agent, DPS_LOG_ERROR, "Error sending cmd_qlc packet, %d of %d bytes sent", nsent, sizeof(hdr) + hdr.len);
}
hdr.cmd = DPS_SEARCHD_CMD_WWL;
hdr.len = sizeof(DPS_WIDEWORDLIST_EX);
for (i = 0; i < Res->WWList.nwords; i++) {
hdr.len += sizeof(DPS_WIDEWORD_EX)
+ sizeof(char) * (Res->WWList.Word[i].len + 1)
+ sizeof(dpsunicode_t) * (Res->WWList.Word[i].ulen + 1)
+ sizeof(int);
}
if (hdr.len & 1) hdr.len++;
p = wbuf = (char *)DpsXmalloc(hdr.len + 1); /* need DpsXmalloc */
if (p == NULL) {
done=1;
break;
}
dps_memcpy(p, &(Res->WWList), sizeof(DPS_WIDEWORDLIST_EX));
p += sizeof(DPS_WIDEWORDLIST_EX);
for (i = 0; i < Res->WWList.nwords; i++) {
dps_memcpy(p, &(Res->WWList.Word[i]), sizeof(DPS_WIDEWORD_EX));
p += sizeof(DPS_WIDEWORD_EX);
dps_memcpy(p, Res->WWList.Word[i].word, Res->WWList.Word[i].len + 1);
p += Res->WWList.Word[i].len + 1;
p += sizeof(dpsunicode_t) - ((SDPALIGN)p % sizeof(dpsunicode_t));
dps_memcpy(p, Res->WWList.Word[i].uword, sizeof(dpsunicode_t) * (Res->WWList.Word[i].ulen + 1));
p += sizeof(dpsunicode_t) * (Res->WWList.Word[i].ulen + 1);
}
nsent = DpsSearchdSendPacket(server, &hdr, wbuf);
DpsLog(Agent, verb, "Sent WWL packet %d bytes cmd=%d len=%d nwords=%d",
(int)nsent, hdr.cmd, hdr.len, Res->WWList.nwords);
DPS_FREE(wbuf);
}
#define MAX_PS 1000
if (last_cmd == DPS_SEARCHD_CMD_WORDS_ALL) {
Res->num_rows = Res->total_found;
Res->first = 0;
} else {
page_size = DpsVarListFindInt(&Agent->Vars, "ps", DPS_DEFAULT_PS);
page_size = dps_min(page_size, MAX_PS);
page_number = DpsVarListFindInt(&Agent->Vars, "p", 0);
if (page_number == 0) {
page_number = DpsVarListFindInt(&Agent->Vars, "np", 0);
} else page_number--;
Res->first = page_number * page_size;
if(Res->first >= Res->total_found) Res->first = (Res->total_found)? (Res->total_found - 1) : 0;
if((Res->first + page_size) > Res->total_found){
Res->num_rows = Res->total_found - Res->first;
}else{
Res->num_rows = page_size;
}
}
Res->last = Res->first + Res->num_rows - 1;
if (Res->PerSite) {
hdr.cmd = DPS_SEARCHD_CMD_PERSITE;
hdr.len = /*Res->CoordList.ncoords*/ Res->num_rows * sizeof(*Res->PerSite);
nsent = DpsSearchdSendPacket(server, &hdr, &Res->PerSite[Res->first]);
DpsLog(Agent, verb, "Sent PerSite packet %u bytes cmd=%d len=%d", nsent, hdr.cmd, hdr.len);
}
hdr.cmd = DPS_SEARCHD_CMD_DATA;
hdr.len = /*Res->CoordList.ncoords*/ Res->num_rows * sizeof(*Res->CoordList.Data);
nsent = DpsSearchdSendPacket(server, &hdr, &Res->CoordList.Data[Res->first]);
DpsLog(Agent, verb, "Sent URLDATA packet %u bytes cmd=%d len=%d", nsent, hdr.cmd, hdr.len);
#ifdef WITH_REL_TRACK
hdr.cmd = DPS_SEARCHD_CMD_TRACKDATA;
hdr.len = /*Res->CoordList.ncoords*/ Res->num_rows * sizeof(*Res->CoordList.Track);
nsent = DpsSearchdSendPacket(server, &hdr, &Res->CoordList.Track[Res->first]);
DpsLog(Agent, verb, "Sent TRACKDATA packet %u bytes cmd=%d len=%d", nsent, hdr.cmd, hdr.len);
#endif
#if HAVE_ASPELL
if (Res->Suggest != NULL) {
hdr.cmd = DPS_SEARCHD_CMD_SUGGEST;
hdr.len = dps_strlen(Res->Suggest) + 1;
nsent = DpsSearchdSendPacket(server, &hdr, Res->Suggest);
DpsLog(Agent, verb, "Sent Suggest packet %d bytes cmd=%d len=%d", (int)nsent, hdr.cmd, hdr.len);
}
#endif
hdr.cmd=DPS_SEARCHD_CMD_WORDS;
hdr.len = /*Res->CoordList.ncoords*/ Res->num_rows * sizeof(DPS_URL_CRD_DB);
nsent=DpsSearchdSendPacket(server, &hdr, &Res->CoordList.Coords[Res->first]);
DpsLog(Agent,verb,"Sent words packet %d bytes cmd=%d len=%d nwords=%d",(int)nsent,hdr.cmd,hdr.len,Res->num_rows/*Res->CoordList.ncoords*/);
#ifdef HAVE_ASPELL
if (Agent->Flags.use_aspellext && Agent->naspell > 0) {
register size_t z;
/*#ifdef UNIONWAIT
union wait status;
#else
int status;
#endif*/
for (z = 0; z < Agent->naspell; z++) {
if (Agent->aspell_pid[z]) {
kill(Agent->aspell_pid[z], SIGALRM);
Agent->aspell_pid[z] = 0;
}
}
/* while(waitpid(Agent->aspell_pid, &status, WNOHANG) > 0); we catch it by signal */
Agent->naspell = 0;
}
#endif /* HAVE_ASPELL */
/*
for(i=0;i<Agent->total_found;i++){
dps_snprintf(buf,sizeof(buf)-1,"u=%08X c=%08X",wrd[i].url_id,wrd[i].coord);
DpsLog(Agent,verb,"%s",buf);
}
*/
break;
case DPS_SEARCHD_CMD_GOODBYE:
Res->work_time = DpsStartTimer() - ticks;
DpsTrackSearchd(Agent, Res);
/* DpsTrack(Agent, &Agent->Conf->Vars, Res);*/
DpsLog(Agent,verb,"Received goodbye command. Work time: %.3f sec.", (float)Res->work_time / 1000);
done=1;
break;
default:
DpsLog(Agent,verb,"Unknown command %d",hdr.cmd);
done=1;
break;
}
}
close(server);
close(client);
client=0;
DpsLog(Agent,verb,"Quit");
DpsResultFree(Res);
DPS_FREE(words);
return DPS_OK;
}
/*************************************************************/
static void usage(void){
fprintf(stderr, "\nsearchd from %s-%s-%s\n(C)1998-2003, LavTech Corp.\n(C)2003-2011, DataPark Ltd.\n\n\
Usage: searchd [OPTIONS]\n\
\n\
Options are:\n\
-l do not log to stderr\n\
-v n verbose level, 0-5\n\
-s n sleep n seconds before starting\n\
-w /path choose alternative working /var directory\n\
-f run foreground, don't demonize\n\
"
#ifdef HAVE_PTHREAD
" -U use one connection to DB for all threads\n"
#endif
"\
-h,-? print this help page and exit\n\
\n\
\n", PACKAGE,VERSION,DPS_DBTYPE);
return;
}
#define SEARCHD_EXIT 0
#define SEARCHD_RELOAD 1
static int client_main(DPS_ENV *Env, size_t handle) {
struct timeval tval;
int ns;
struct sockaddr_in client_addr;
socklen_t addrlen=sizeof(client_addr);
char addr[128]="";
int method;
DPS_MATCH *M;
DPS_MATCH_PART P[10];
int mdone=0;
int res=SEARCHD_EXIT;
DPS_AGENT *Agent = DpsAgentInit(NULL, Env, 300 + (int)handle);
MaxClients = DpsVarListFindInt(&Env->Vars, "MaxClients", 1);
if (MaxClients > DPS_CHILDREN_LIMIT) MaxClients = DPS_CHILDREN_LIMIT;
if (Agent == NULL) {
DpsLog_noagent(Env, DPS_LOG_ERROR, "Can't alloc Agent at %s:%d", __FILE__, __LINE__);
exit(1);
}
/* (re)setup signals here ?*/
init_signals();
while (!mdone) {
fd_set msk;
int sel;
alarm(2400); /* 40 min. - maximum time of child execution */
DpsVarListFree(&Agent->Vars);
DpsVarListInit(&Agent->Vars);
DpsVarListAddLst(&Agent->Vars, &Env->Vars, NULL, "*");
/*
DpsVarListDel(&Agent->Vars, "q");
DpsVarListDel(&Agent->Vars, "np");
DpsVarListDel(&Agent->Vars, "p");
DpsVarListDel(&Agent->Vars, "E");
DpsVarListDel(&Agent->Vars, "CS");
DpsVarListDel(&Agent->Vars, "CP");
*Env->errstr = '\0';
*/
tval.tv_sec = 2;
tval.tv_usec = 0;
DpsAcceptMutexLock(Agent);
msk = mask;
sel = select(FD_SETSIZE, &msk, 0, 0, &tval);
if(have_sighup){
DpsLog(Agent, DPS_LOG_WARN, "SIGHUP arrived");
have_sighup = 0;
res = SEARCHD_RELOAD;
if (parent_pid > 0) kill(parent_pid, SIGHUP);
mdone = 1;
}
if(have_sigint){
DpsLog(Agent, DPS_LOG_ERROR, "SIGINT arrived");
have_sigint = 0;
mdone = 1;
}
if(have_sigterm){
DpsLog(Agent, DPS_LOG_ERROR, "SIGTERM arrived");
have_sigterm = 0;
mdone = 1;
}
if(have_sigpipe){
DpsLog(Agent, DPS_LOG_ERROR, "SIGPIPE arrived. Broken pipe!");
have_sigpipe = 0;
mdone = 1;
}
if (have_sigusr1) {
DpsIncLogLevel(Agent);
have_sigusr1 = 0;
}
if (have_sigusr2) {
DpsDecLogLevel(Agent);
have_sigusr2 = 0;
}
if(mdone) {
DpsAcceptMutexUnlock(Agent);
break;
}
if(sel == 0) {
DpsAcceptMutexUnlock(Agent);
continue;
}
if(sel == -1) {
switch(errno){
case EINTR: /* Child */
break;
default:
dps_strerror(Agent, DPS_LOG_WARN, "FIXME select error");
}
DpsAcceptMutexUnlock(Agent);
continue;
}
if (FD_ISSET(sockfd, &msk)) {
if ((ns = accept(sockfd, (struct sockaddr *) &client_addr, &addrlen)) == -1) {
DpsAcceptMutexUnlock(Agent);
dps_strerror(Agent, DPS_LOG_ERROR, "accept() error");
DpsEnvFree(Agent->Conf);
DpsAgentFree(Agent);
exit(1);
}
} else if (FD_ISSET(clt_sock, &msk)) {
if ((ns = accept(clt_sock, (struct sockaddr *) &client_addr, &addrlen)) == -1) {
DpsAcceptMutexUnlock(Agent);
dps_strerror(Agent, DPS_LOG_ERROR, "accept() error");
DpsEnvFree(Agent->Conf);
DpsAgentFree(Agent);
exit(1);
}
} else {
DpsAcceptMutexUnlock(Agent);
continue;
}
DpsAcceptMutexUnlock(Agent);
DpsLog(Agent, DPS_LOG_EXTRA, "Connect %s", inet_ntoa(client_addr.sin_addr));
dps_snprintf(addr, sizeof(addr)-1, inet_ntoa(client_addr.sin_addr));
M = DpsMatchListFind(&Agent->Conf->Filters,addr,10,P);
method = M ? DpsMethod(M->arg) : DPS_METHOD_GET;
DpsLog(Agent, DPS_LOG_EXTRA, "%s %s %s%s", M?M->arg:"",addr,M?M->pattern:"",M?"":"Allow by default");
if(method == DPS_METHOD_DISALLOW) {
DpsLog(Agent, DPS_LOG_ERROR, "Reject client");
close(ns);
continue;
}
do_client(Agent, ns);
close(ns);
}
if (clt_sock > 0) dps_closesocket(clt_sock);
if (sockfd > 0) dps_closesocket(sockfd);
return res;
}
#define MAXMSG (4096 + sizeof(long))
static void SearchdTrack(DPS_AGENT *Agent) {
DPS_SQLRES sqlRes;
DPS_DBLIST dbl;
DPS_DB *db, *tr_db;
DPS_DBLIST *DBL, *TrL = NULL;
DIR * dir;
struct dirent * item;
int fd, rec_id, res = DPS_OK;
ssize_t n;
char query[MAXMSG];
char *lt;
char qbuf[4096 + MAXMSG];
char fullname[PATH_MAX]="";
char *IP, *qwords, *qtime, *total_found, *wtime, *var, *val;
size_t i, dbfrom = 0, dbto;
const char *TrackDBAddr = DpsVarListFindStr(&Agent->Vars, "TrackDBAddr", NULL);
size_t to_sleep = 0, to_delete, trdone;
init_TrackSignals();
DpsSQLResInit(&sqlRes);
if (TrackDBAddr) {
TrL = &dbl;
bzero((void*)TrL, sizeof(dbl));
if(DPS_OK != DpsDBListAdd(TrL, TrackDBAddr, DPS_OPEN_MODE_WRITE)) {
DpsLog(Agent, DPS_LOG_ERROR, "Invalid TrackDBAddr: '%s'", TrackDBAddr);
return;
}
}
DBL = (Agent->flags & DPS_FLAG_UNOCON) ? &Agent->Conf->dbl : &Agent->dbl;
dbto = DBL->nitems;
/* To see the URL being indexed in "ps" output on xBSD */
dps_setproctitle("Query Tracker");
for (i = dbfrom; i < dbto; i++) {
db = DBL->db[i];
db->connected = 0;
}
while(1) {
if(have_sigint){
DpsLog(Agent, DPS_LOG_ERROR, "Query Tracker: SIGINT arrived");
have_sigint = 0;
break;
}
if(have_sigterm){
DpsLog(Agent, DPS_LOG_ERROR, "Query Tracker: SIGTERM arrived");
have_sigterm = 0;
break;
}
if(have_sigpipe){
DpsLog(Agent, DPS_LOG_ERROR, "Query Tracker: SIGPIPE arrived. Broken pipe !");
have_sigpipe = 0;
break;
}
if (have_sigusr1) {
DpsIncLogLevel(Agent);
have_sigusr1 = 0;
}
if (have_sigusr2) {
DpsDecLogLevel(Agent);
have_sigusr2 = 0;
}
DpsLog(Agent, DPS_LOG_DEBUG, "Query Track: starting directory reading");
trdone = 0;
for (i = dbfrom; (i < dbto); i++) {
db = DBL->db[i];
tr_db = (TrackDBAddr!=NULL) ? TrL->db[0] : db;
/* fprintf(stderr, " -- %d TrackDBAddr:%s TrackQuery:%d\n", i, DPS_NULL2EMPTY(TrackDBAddr), db->TrackQuery);*/
#ifdef HAVE_SQL
if(TrackDBAddr || db->TrackQuery) {
const char *qu = (tr_db->DBType == DPS_DB_PGSQL) ? "'" : "";
const char *vardir = (db->vardir != NULL) ? db->vardir : DpsVarListFindStr(&Agent->Vars, "VarDir", DPS_VAR_DIR);
dir = opendir(vardir);
/* fprintf(stderr, " -- opendir: %s\n", dir);*/
if (dir) {
while((item = readdir(dir))) {
if (strncmp(item->d_name, "track.", 6) && strncmp(item->d_name, "query.", 6)) continue;
to_delete = 0;
dps_snprintf(fullname, sizeof(fullname), "%s%s%s", vardir, DPSSLASHSTR, item->d_name);
if ((fd = DpsOpen2(fullname, O_RDONLY | DPS_BINARY)) > 0) {
n = read(fd, query, sizeof(query) - 1);
DpsClose(fd);
if (n > 0) {
query[n] = '\0';
to_delete = 1;
if (strncmp(item->d_name, "track.", 6)) {
DpsLog(Agent, DPS_LOG_EXTRA, "Query Track: track[%d]: %s", dps_strlen(query + sizeof(long)), query + sizeof(long) );
res = DpsSQLAsyncQuery(tr_db, NULL, query);
if (res != DPS_OK) {to_delete = 0; continue; }
trdone = 1;
} else {
char *cmd_escaped;
char *text_escaped;
DpsLog(Agent, DPS_LOG_EXTRA, "Query Track: query[%d]: %s", dps_strlen(query), query);
trdone = 1;
IP = dps_strtok_r(query + sizeof(long), "\2", <, NULL);
/* DpsLog(Agent, DPS_LOG_EXTRA, "Query Track: IP: %s", IP);*/
qwords = dps_strtok_r(NULL, "\2", <, NULL);
/* DpsLog(Agent, DPS_LOG_EXTRA, "Query Track: qwords: %s", qwords);*/
qtime = dps_strtok_r(NULL, "\2", <, NULL);
/* DpsLog(Agent, DPS_LOG_EXTRA, "Query Track: qtime: %s", qtime);*/
total_found = dps_strtok_r(NULL, "\2", <, NULL);
/* DpsLog(Agent, DPS_LOG_EXTRA, "Query Track: total: %s", total_found);*/
wtime = dps_strtok_r(NULL, "\2", <, NULL);
/* DpsLog(Agent, DPS_LOG_EXTRA, "Query Track: wtime: %s", wtime);*/
dps_snprintf(qbuf, sizeof(qbuf), "INSERT INTO qtrack (ip,qwords,qtime,found,wtime) VALUES ('%s','%s',%s,%s,%s)",
IP, qwords, qtime, total_found, wtime );
DpsLog(Agent, DPS_LOG_EXTRA, "%s", qbuf);
res = DpsSQLAsyncQuery(tr_db, NULL, qbuf);
if (res != DPS_OK) {to_delete = tr_db->connected; goto tr_loop_continue; }
dps_snprintf(qbuf, sizeof(qbuf), "SELECT rec_id FROM qtrack WHERE ip='%s' AND qtime=%s", IP, qtime);
DpsLog(Agent, DPS_LOG_EXTRA, "%s", qbuf);
res = DpsSQLQuery(tr_db, &sqlRes, qbuf);
if (res != DPS_OK) { to_delete = 0; DpsSQLFree(&sqlRes); goto tr_loop_continue; }
if (DpsSQLNumRows(&sqlRes) == 0) { DpsSQLFree(&sqlRes); res = DPS_ERROR; goto tr_loop_continue; }
rec_id = DPS_ATOI(DpsSQLValue(&sqlRes, 0, 0));
DpsSQLFree(&sqlRes);
do {
var = dps_strtok_r(NULL, "\2", <, NULL);
if (var != NULL) {
val = dps_strtok_r(NULL, "\2", <, NULL);
cmd_escaped = DpsDBEscStr(db, NULL, DPS_NULL2EMPTY(var), dps_strlen(DPS_NULL2EMPTY(var))); /* Escape parameter name */
text_escaped = DpsDBEscStr(db, NULL, DPS_NULL2EMPTY(val), dps_strlen(DPS_NULL2EMPTY(val))); /* Escape parameter value */
dps_snprintf(qbuf, sizeof(qbuf), "INSERT INTO qinfo (q_id,name,value) VALUES (%s%i%s,'%s','%s')",
qu, rec_id, qu, cmd_escaped, text_escaped);
DpsLog(Agent, DPS_LOG_EXTRA, "%s", qbuf);
res = DpsSQLAsyncQuery(tr_db, NULL, qbuf);
DPS_FREE(text_escaped);
DPS_FREE(cmd_escaped);
if (res != DPS_OK) continue;
}
} while (var != NULL);
}
}
tr_loop_continue:
if (to_delete) unlink(fullname);
}
}
closedir(dir);
if (trdone) {
to_sleep = 0;
}
} else {
dps_strerror(Agent, DPS_LOG_ERROR, "Can't open directory: %s", vardir);
}
}
#endif
}
if (to_sleep < 3600) {
to_sleep += 10;
}
DpsLog(Agent, DPS_LOG_DEBUG, "Query Track: sleeping %d", to_sleep);
DPSSLEEP(to_sleep);
}
}
int main(int argc, char **argv, char **envp) {
struct sockaddr_in old_server_addr;
dps_uint8 flags = DPS_FLAG_SPELL | DPS_FLAG_ADD_SERV;
int done = 0, demonize = 1;
int ch=0, pid_fd;
int nport=DPS_SEARCHD_PORT;
const char * config_name = DPS_CONF_DIR "/searchd.conf";
int debug_level = DPS_LOG_INFO;
char pidbuf[64];
const char *var_dir = NULL, *pvar_dir = DPS_VAR_DIR;
pid_t track_pid = 0;
size_t i;
log2stderr = 1;
DpsInit(argc, argv, envp); /* Initialize library */
DpsInitMutexes();
parent_pid = getpid();
while ((ch = getopt(argc, argv, "Ufhl?v:w:s:")) != -1){
switch (ch) {
case 'l':
log2stderr=0;
break;
case 'v': debug_level = atoi(optarg); break;
case 'w':
pvar_dir = optarg;
break;
case 's':
sleep((unsigned int)atoi(optarg));
break;
case 'f':
demonize = 0;
break;
case 'U':
flags |= DPS_FLAG_UNOCON;
break;
case 'h':
case '?':
default:
usage();
return 1;
break;
}
}
argc -= optind;argv += optind;
if(argc==1)config_name=argv[0];
dps_snprintf(dps_pid_name, PATH_MAX, "%s%s%s", pvar_dir, DPSSLASHSTR, "searchd.pid");
pid_fd = DpsOpen3(dps_pid_name, O_CREAT|O_EXCL|O_WRONLY, 0644);
if(pid_fd < 0) {
dps_strerror(NULL, 0, "Can't create '%s'", dps_pid_name);
if(errno == EEXIST){
int pid = 0, kill_rc;
pid_fd = DpsOpen3(dps_pid_name, O_RDWR, 0644);
if (pid_fd < 0) {
dps_strerror(NULL, 0, "Can't open '%s'", dps_pid_name);
return DPS_ERROR;
}
(void)read(pid_fd, pidbuf, sizeof(pidbuf));
if (1 > sscanf(pidbuf, "%d", &pid)) {
dps_strerror(NULL, 0, "Can't read pid from '%s'", dps_pid_name);
close(pid_fd);
return DPS_ERROR;
}
kill_rc = kill((pid_t)pid, 0);
if (kill_rc == 0) {
fprintf(stderr, "It seems that another indexer is already running!\n");
fprintf(stderr, "Remove '%s' if it is not true.\n", dps_pid_name);
close(pid_fd);
return DPS_ERROR;
}
if (errno == EPERM) {
fprintf(stderr, "Can't check if another indexer is already running!\n");
fprintf(stderr, "Remove '%s' if it is not true.\n", dps_pid_name);
close(pid_fd);
return DPS_ERROR;
}
dps_strerror(NULL, 0, "Process %d seems to be dead. Flushing '%s'", pid, dps_pid_name);
lseek(pid_fd, 0L, SEEK_SET);
ftruncate(pid_fd, 0L);
}
}
if (demonize) {
if (dps_demonize() != 0) {
fprintf(stderr, "Can't demonize\n");
DpsClose(pid_fd);
exit(1);
}
}
sprintf(pidbuf, "%d\n", (int)getpid());
(void)write(pid_fd, &pidbuf, dps_strlen(pidbuf));
DpsClose(pid_fd);
bzero(Children, DPS_CHILDREN_LIMIT * sizeof(DPS_CHILD));
bzero(&old_server_addr, sizeof(old_server_addr));
while(!done){
struct sockaddr_in server_addr;
struct sockaddr_un unix_addr;
int on = 1;
DPS_AGENT * Agent;
DPS_ENV * Conf=NULL;
int verb = DPS_LOG_EXTRA;
int res = 0, internaldone = 0;
const char *lstn, *unix_socket;
if (track_pid != 0) {
kill(track_pid, SIGTERM);
}
Conf = DpsEnvInit(NULL);
if (Conf == NULL) {
fprintf(stderr, "Can't alloc Env at %s:%d", __FILE__, __LINE__);
return DPS_ERROR;
}
Agent=DpsAgentInit(NULL,Conf,0);
if (Agent == NULL) {
fprintf(stderr, "Can't alloc Agent at %s:%d", __FILE__, __LINE__);
return DPS_ERROR;
}
Agent->flags = Conf->flags = flags; /*DPS_FLAG_UNOCON | DPS_FLAG_ADD_SERV;*/
res = DpsEnvLoad(Agent, config_name, flags);
if ((NULL == DpsAgentDBLSet(Agent, Conf))) {
fprintf(stderr, "Can't set DBList at %s:%d", __FILE__, __LINE__);
DpsAgentFree(Agent);
DpsEnvFree(Conf);
unlink(dps_pid_name);
exit(2);
}
if (pvar_dir == NULL) var_dir = DpsVarListFindStr(&Conf->Vars, "VarDir", DPS_VAR_DIR);
else var_dir = pvar_dir;
DpsAcceptMutexInit(var_dir, "searchd");
DpsUniRegCompileAll(Conf);
DpsOpenLog("searchd", Conf, log2stderr);
DpsSetLogLevel(Agent, debug_level);
Agent->flags = Conf->flags = flags;
Agent->Flags = Conf->Flags;
if(res!=DPS_OK){
DpsLog(Agent,verb,"%s",DpsEnvErrMsg(Conf));
DpsAgentFree(Agent);
DpsEnvFree(Conf);
unlink(dps_pid_name);
exit(1);
}
if (Conf->Flags.PreloadURLData) {
DpsLog(Agent, verb, "Preloading url data");
DpsURLDataPreload(Agent);
}
MaxClients = DpsVarListFindInt(&Agent->Conf->Vars, "MaxClients", 1);
if (MaxClients > DPS_CHILDREN_LIMIT) MaxClients = DPS_CHILDREN_LIMIT;
unix_socket = DpsVarListFindStr(&Agent->Conf->Vars, "Socket", NULL);
DpsLog(Agent, verb, "searchd started with '%s'", config_name);
DpsLog(Agent, verb, "VarDir: '%s'", DpsVarListFindStr(&Agent->Conf->Vars, "VarDir", DPS_VAR_DIR));
DpsLog(Agent, verb, "MaxClients: %d", MaxClients);
if (unix_socket != NULL) DpsLog(Agent, verb, "Unix socket: '%s'", unix_socket);
DpsLog(Agent, verb, "Affixes: %d, Spells: %d, Synonyms: %d, Acronyms: %d, Stopwords: %d",
Conf->Affixes.naffixes,Conf->Spells.nspell,
Conf->Synonyms.nsynonyms,
Conf->Acronyms.nacronyms,
Conf->StopWords.nstopwords);
DpsLog(Agent,verb,"Chinese dictionary with %d entries", Conf->Chi.nwords);
DpsLog(Agent,verb,"Korean dictionary with %d entries", Conf->Korean.nwords);
DpsLog(Agent,verb,"Thai dictionary with %d entries", Conf->Thai.nwords);
for (i = 0; i < DPS_CHILDREN_LIMIT; i++) {
if (Children[i].pid) kill(Children[i].pid, SIGTERM);
/* Children[i].pid = 0;*/
}
if ((track_pid = fork() ) == -1) {
dps_strerror(Agent, DPS_LOG_ERROR, "fork() error");
DpsAgentFree(Agent);
DpsEnvFree(Conf);
unlink(dps_pid_name);
exit(1);
}
if (track_pid == 0) { /* child process */
DpsVarListAddLst(&Agent->Vars, &Agent->Conf->Vars, NULL, "*");
SearchdTrack(Agent);
DpsAgentFree(Agent);
DpsEnvFree(Conf);
exit(0);
}
DpsLog(Agent,verb,"Query tracker child started.");
#if defined(HAVE_PTHREAD) && defined(HAVE_THR_SETCONCURRENCY_PROT)
if (thr_setconcurrency(16) != NULL) { /* FIXME: Does 16 is enough ? */
DpsLog(A, DPS_LOG_ERROR, "Can't set %d concurrency threads", maxthreads);
return DPS_ERROR;
}
#endif
bzero((void*)&server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
if((lstn=DpsVarListFindStr(&Agent->Conf->Vars,"Listen",NULL))){
char * cport;
if((cport=strchr(lstn, ':'))) {
*cport = '\0';
server_addr.sin_addr.s_addr = inet_addr(lstn);
nport=atoi(cport+1);
}else if (strchr(lstn, '.')) {
server_addr.sin_addr.s_addr = inet_addr(lstn);
}else{
nport = atoi(lstn);
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
}
DpsLog(Agent, verb, "Listening port %d", nport);
}else{
DpsLog(Agent,verb,"Listening port %d",nport);
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
}
server_addr.sin_port = htons((u_short)nport);
for (i = 0; i < DPS_CHILDREN_LIMIT; i++) {
if (Children[i].pid) kill(Children[i].pid, SIGKILL);
/* Children[i].pid = 0;*/
}
FD_ZERO(&mask);
if (memcmp(&old_server_addr, &server_addr, sizeof(server_addr)) != 0) {
if (clt_sock > 0) dps_closesocket(clt_sock);
if ((clt_sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
DpsLog(Agent, DPS_LOG_ERROR, "socket() error %d", errno);
DpsAgentFree(Agent);
DpsEnvFree(Conf);
unlink(dps_pid_name);
exit(1);
}
if (setsockopt(clt_sock, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof(on)) != 0){
DpsLog(Agent, DPS_LOG_ERROR, "setsockopt() error %d", errno);
DpsAgentFree(Agent);
DpsEnvFree(Conf);
unlink(dps_pid_name);
exit(1);
}
#ifdef SO_REUSEPORT
if (setsockopt(clt_sock, SOL_SOCKET, SO_REUSEPORT, (char *)&on, sizeof(on)) != 0){
dps_strerror(Agent, DPS_LOG_ERROR, "setsockopt() error");
DpsAgentFree(Agent);
DpsEnvFree(Conf);
unlink(dps_pid_name);
exit(1);
}
#endif
DpsSockOpt(Agent, clt_sock);
for (i = 0; ;i++) {
if (bind(clt_sock, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
dps_strerror(Agent, DPS_LOG_ERROR, "Can't bind: error");
if (i < 15) {
DPSSLEEP(1 + i * 3);
continue;
}
DpsAgentFree(Agent);
DpsEnvFree(Conf);
unlink(dps_pid_name);
exit(1);
}
break;
}
/* Backlog 64 is enough? */
if (listen(clt_sock, 64) == -1) {
dps_strerror(Agent, DPS_LOG_ERROR, "listen() error");
DpsAgentFree(Agent);
DpsEnvFree(Conf);
unlink(dps_pid_name);
exit(1);
}
dps_memcpy(&old_server_addr, &server_addr, sizeof(server_addr));
}
FD_SET(clt_sock, &mask);
if (unix_socket != NULL) {
char unix_path[128];
int saddrlen;
int old_umask;
if (DpsRelVarName(Conf, unix_path, sizeof(unix_path), unix_socket) < 105) {
} else {
DpsLog(Agent, DPS_LOG_ERROR, "Unix socket name '%s' is too large", unix_path);
DpsAgentFree(Agent);
DpsEnvFree(Conf);
unlink(dps_pid_name);
exit(1);
}
if ((sockfd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
DpsLog(Agent, DPS_LOG_ERROR, "unix socket() error %d", errno);
DpsAgentFree(Agent);
DpsEnvFree(Conf);
unlink(dps_pid_name);
exit(1);
}
DpsSockOpt(Agent, sockfd);
unlink(unix_path);
bzero((void*)&unix_addr, sizeof(unix_addr));
unix_addr.sun_family = AF_UNIX;
dps_strncpy(unix_addr.sun_path, unix_path, sizeof(unix_addr.sun_path));
saddrlen = sizeof(unix_addr.sun_family) + dps_strlen(unix_addr.sun_path);
old_umask = umask( ~((S_IRWXU | S_IRWXG | S_IRWXO) & 0777));
if (bind(sockfd, (struct sockaddr *)&unix_addr, saddrlen) == -1) {
dps_strerror(Agent, DPS_LOG_ERROR, "Can't bind unix socket: error");
umask(old_umask);
DpsAgentFree(Agent);
DpsEnvFree(Conf);
unlink(dps_pid_name);
exit(1);
}
umask(old_umask);
/* Backlog 64 is enough? */
if (listen(sockfd, 64) == -1) {
dps_strerror(Agent, DPS_LOG_ERROR, "listen() unix socket error");
DpsAgentFree(Agent);
DpsEnvFree(Conf);
unlink(dps_pid_name);
exit(1);
}
chmod(unix_path, S_IRWXU | S_IRWXG | S_IRWXO);
FD_SET(sockfd, &mask);
}
DpsLog(Agent, DPS_LOG_WARN, "Ready");
init_signals();
if(DpsSearchCacheClean(Agent) != DPS_OK) {
DpsLog(Agent, DPS_LOG_ERROR, "Error in search cache cleaning");
DpsAgentFree(Agent);
DpsEnvFree(Conf);
unlink(dps_pid_name);
DpsDestroyMutexes();
exit(1);
}
for (i = 0; i < MaxClients; i++) {
pid_t pid;
if (Children[i].pid) continue;
/* if (Children[i].pid) kill(Children[i].pid, SIGTERM);*/
pid = fork();
if(pid == 0){
client_main(Agent->Conf, i);
DpsEnvFree(Agent->Conf);
DpsAgentFree(Agent);
exit(0);
} else {
if (pid > 0) {
Children[i].pid = pid;
} else {
Children[i].pid = 0;
DpsLog(Agent, DPS_LOG_ERROR, "fork() error %d", pid);
}
}
}
while(!internaldone) {
DPSSLEEP(1);
if(have_sighup){
DpsLog(Agent,verb,"SIGHUP arrived");
have_sighup=0;
res = SEARCHD_RELOAD;
internaldone = 1;
}
if(have_sigint){
DpsLog(Agent,verb,"SIGINT arrived");
have_sigint=0;
res = SEARCHD_EXIT;
internaldone = 1;
}
if(have_sigterm){
DpsLog(Agent,verb,"SIGTERM arrived");
have_sigterm=0;
res = SEARCHD_EXIT;
internaldone = 1;
}
if(have_sigpipe){ /* FIXME: why this may happens and what to do with it */
DpsLog(Agent, verb, "SIGPIPE arrived. Broken pipe!");
have_sigpipe = 0;
/* mdone = 1;*/
}
if (have_sigusr1) {
DpsIncLogLevel(Agent);
have_sigusr1 = 0;
}
if (have_sigusr2) {
DpsDecLogLevel(Agent);
have_sigusr2 = 0;
}
for (i = 0; i < MaxClients; i++) {
if (Children[i].pid == 0) {
pid_t pid = fork();
if(pid == 0){
client_main(Agent->Conf, i);
DpsEnvFree(Agent->Conf);
DpsAgentFree(Agent);
exit(0);
} else {
if (pid > 0) {
Children[i].pid = pid;
} else {
Children[i].pid = 0;
DpsLog(Agent, DPS_LOG_ERROR, "fork() error %d", pid);
}
}
}
}
}
if(res != SEARCHD_RELOAD){
done = 1;
DpsLog(Agent,verb,"Shutdown");
}else{
DpsLog(Agent,verb,"Reloading conf");
}
if (Conf->Flags.PreloadURLData) {
DpsURLDataDePreload(Agent);
}
DpsAgentFree(Agent);
DpsEnvFree(Conf);
DpsAcceptMutexCleanup();
}
for (i = 0; i < MaxClients; i++) {
if (Children[i].pid) kill(Children[i].pid, SIGTERM);
}
if (track_pid != 0) {
kill(track_pid, SIGTERM);
}
unlink(dps_pid_name);
DpsDestroyMutexes();
#ifdef EFENCE
fprintf(stderr, "Memory leaks checking\n");
DpsEfenceCheckLeaks();
#endif
#ifdef FILENCE
fprintf(stderr, "FD leaks checking\n");
DpsFilenceCheckLeaks(NULL);
#endif
#ifdef BOEHMGC
CHECK_LEAKS();
#endif
return DPS_OK;
}
| Letractively/dataparksearch | src/searchd.c | C | gpl-2.0 | 66,076 |
/* linux/spi/ads7846.h */
/* Touchscreen characteristics vary between boards and models. The
* platform_data for the device's "struct device" holds this information.
*
* It's OK if the min/max values are zero.
*/
#define MAX_12BIT ((1<<12)-1)
enum ads7846_filter {
ADS7846_FILTER_OK,
ADS7846_FILTER_REPEAT,
ADS7846_FILTER_IGNORE,
};
enum ads7846_invertion_flags {
XY_SWAP = 1 << 1,
X_INV = 1 << 2,
Y_INV = 1 << 3,
};
struct ads7846_platform_data {
u16 model; /* 7843, 7845, 7846. */
u16 vref_delay_usecs; /* 0 for external vref; etc */
u16 vref_mv; /* external vref value, milliVolts */
bool keep_vref_on; /* set to keep vref on for differential
* measurements as well */
/* Settling time of the analog signals; a function of Vcc and the
* capacitance on the X/Y drivers. If set to non-zero, two samples
* are taken with settle_delay us apart, and the second one is used.
* ~150 uSec with 0.01uF caps.
*/
u16 settle_delay_usecs;
/* If set to non-zero, after samples are taken this delay is applied
* and penirq is rechecked, to help avoid false events. This value
* is affected by the material used to build the touch layer.
*/
u16 penirq_recheck_delay_usecs;
u16 x_plate_ohms;
u16 y_plate_ohms;
u16 x_min, x_max;
u16 y_min, y_max;
u16 pressure_min, pressure_max;
u16 debounce_max; /* max number of additional readings
* per sample */
u16 debounce_tol; /* tolerance used for filtering */
u16 debounce_rep; /* additional consecutive good readings
* required after the first two */
int gpio_pendown; /* the GPIO used to decide the pendown
* state if get_pendown_state == NULL
*/
int inversion_flags; /* X/Y channels inversion / swap flags
*/
int (*get_pendown_state)(void);
int (*filter_init) (struct ads7846_platform_data *pdata,
void **filter_data);
int (*filter) (void *filter_data, int data_idx, int *val);
void (*filter_cleanup)(void *filter_data);
void (*filter_flush)(void *filter_data);
/* controls enabling/disabling*/
int (*vaux_control)(int vaux_cntrl);
#define VAUX_ENABLE 1
#define VAUX_DISABLE 0
};
| gilou811/Archos_OPENAOS_Kernel_ICS | include/linux/spi/ads7846.h | C | gpl-2.0 | 2,125 |
/* @(#)clnt_simple.c 2.2 88/08/01 4.0 RPCSRC */
/*
* Sun RPC is a product of Sun Microsystems, Inc. and is provided for
* unrestricted use provided that this legend is included on all tape
* media and as a part of the software program in whole or part. Users
* may copy or modify Sun RPC without charge, but are not authorized
* to license or distribute it to anyone else except as part of a product or
* program developed by the user.
*
* SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
* WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
* PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
*
* Sun RPC is provided with no support and without any obligation on the
* part of Sun Microsystems, Inc. to assist in its use, correction,
* modification or enhancement.
*
* SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
* INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
* OR ANY PART THEREOF.
*
* In no event will Sun Microsystems, Inc. be liable for any lost revenue
* or profits or other special, indirect and consequential damages, even if
* Sun has been advised of the possibility of such damages.
*
* Sun Microsystems, Inc.
* 2550 Garcia Avenue
* Mountain View, California 94043
*/
#if 0
static char sccsid[] = "@(#)clnt_simple.c 1.35 87/08/11 Copyr 1984 Sun Micro";
#endif
/*
* clnt_simple.c
* Simplified front end to rpc.
*
* Copyright (C) 1984, Sun Microsystems, Inc.
*/
#define __FORCE_GLIBC
#include <features.h>
#include <alloca.h>
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include "rpc_private.h"
#include <sys/socket.h>
#include <netdb.h>
#include <string.h>
libc_hidden_proto(memcpy)
libc_hidden_proto(strcmp)
libc_hidden_proto(strncpy)
libc_hidden_proto(close)
libc_hidden_proto(clntudp_create)
libc_hidden_proto(gethostbyname_r)
struct callrpc_private_s
{
CLIENT *client;
int socket;
u_long oldprognum, oldversnum, valid;
char *oldhost;
};
#ifdef __UCLIBC_HAS_THREADS__
#define callrpc_private (*(struct callrpc_private_s **)&RPC_THREAD_VARIABLE(callrpc_private_s))
#else
static struct callrpc_private_s *callrpc_private;
#endif
int
callrpc (const char *host, u_long prognum, u_long versnum, u_long procnum,
xdrproc_t inproc, const char *in, xdrproc_t outproc, char *out)
{
struct callrpc_private_s *crp = callrpc_private;
struct sockaddr_in server_addr;
enum clnt_stat clnt_stat;
struct hostent hostbuf, *hp;
struct timeval timeout, tottimeout;
if (crp == 0)
{
crp = (struct callrpc_private_s *) calloc (1, sizeof (*crp));
if (crp == 0)
return 0;
callrpc_private = crp;
}
if (crp->oldhost == NULL)
{
crp->oldhost = malloc (256);
crp->oldhost[0] = 0;
crp->socket = RPC_ANYSOCK;
}
if (crp->valid && crp->oldprognum == prognum && crp->oldversnum == versnum
&& strcmp (crp->oldhost, host) == 0)
{
/* reuse old client */
}
else
{
size_t buflen;
char *buffer;
int herr;
crp->valid = 0;
if (crp->socket != RPC_ANYSOCK)
{
(void) close (crp->socket);
crp->socket = RPC_ANYSOCK;
}
if (crp->client)
{
clnt_destroy (crp->client);
crp->client = NULL;
}
buflen = 1024;
buffer = alloca (buflen);
while (gethostbyname_r (host, &hostbuf, buffer, buflen,
&hp, &herr) != 0
|| hp == NULL)
if (herr != NETDB_INTERNAL || errno != ERANGE)
return (int) RPC_UNKNOWNHOST;
else
{
/* Enlarge the buffer. */
buflen *= 2;
buffer = alloca (buflen);
}
timeout.tv_usec = 0;
timeout.tv_sec = 5;
memcpy ((char *) &server_addr.sin_addr, hp->h_addr, hp->h_length);
server_addr.sin_family = AF_INET;
server_addr.sin_port = 0;
if ((crp->client = clntudp_create (&server_addr, (u_long) prognum,
(u_long) versnum, timeout, &crp->socket)) == NULL)
return (int) get_rpc_createerr().cf_stat;
crp->valid = 1;
crp->oldprognum = prognum;
crp->oldversnum = versnum;
(void) strncpy (crp->oldhost, host, 255);
crp->oldhost[255] = '\0';
}
tottimeout.tv_sec = 25;
tottimeout.tv_usec = 0;
clnt_stat = clnt_call (crp->client, procnum, inproc, (char *) in,
outproc, out, tottimeout);
/*
* if call failed, empty cache
*/
if (clnt_stat != RPC_SUCCESS)
crp->valid = 0;
return (int) clnt_stat;
}
#ifdef __UCLIBC_HAS_THREADS__
void attribute_hidden __rpc_thread_clnt_cleanup (void)
{
struct callrpc_private_s *rcp = RPC_THREAD_VARIABLE(callrpc_private_s);
if (rcp) {
if (rcp->client)
CLNT_DESTROY (rcp->client);
free (rcp);
}
}
#endif /* __UCLIBC_HAS_THREADS__ */
| rhuitl/uClinux | uClibc/libc/inet/rpc/clnt_simple.c | C | gpl-2.0 | 4,716 |
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Qtopia - 4.1.2 Release Notes</title>
<link href="classic.css" rel="stylesheet" type="text/css" />
</head>
<body>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td align="left" valign="top" width="32"><img src="images/qtlogo.png" align="left" border="0" /></td>
<td width="1"> </td><td class="postheader" valign="center"><a href="index.html"><font color="#004faf">Home</font></a> · <a href="namespaces.html"><font color="#004faf">All Namespaces</font></a> · <a href="classes.html"><font color="#004faf">All Classes</font></a> · <a href="groups.html"><font color="#004faf">Grouped Classes</font></a> · <a href="modules-index.html"><font color="#004faf">Modules</font></a> · <a href="functions.html"><font color="#004faf">Functions</font></a></td>
<td align="right" valign="center"><img src="images/codeless.png" border="0" alt="codeless banner"></td></tr></table><h1 class="title">Qtopia - 4.1.2 Release Notes<br /><span class="subtitle"></span>
</h1>
<ul><li><a href="#introduction">Introduction</a></li>
<li><a href="#enhancements">Enhancements</a></li>
<li><a href="#bug-fixes">Bug Fixes</a></li>
</ul>
<a name="introduction"></a>
<h2>Introduction</h2>
<p>The Qtopia 4.1.2 release is a patch release that provides:</p>
<ul>
<li>improved performance.</li>
<li>fixes for a number of bugs</li>
</ul>
<a name="enhancements"></a>
<h2>Enhancements</h2>
<ol type="1">
<li><b>Performance</b><ul>
<li>Multitasking has been improved by a significant reduction of memory usage per application.</li>
<li>Both Qt and Qtopia code have been further optimized for speed.</li>
<li><b>Qtopia server</b>: startup time has been reduced from 35 seconds to 6 seconds.</li>
<li><b>Qtopia applications</b>: startup times have been improved with, on average, 10-20%. Average starting time for most applications is now close to or less than 2 seconds.</li>
</ul>
</li>
</ol>
<p>Substantial improvements have been achieved for the following applications (values in seconds are given for the previous 4.1.1 release and the current 4.1.2 release):</p>
<p><table align="center" cellpadding="2" cellspacing="1" border="0">
<thead><tr valign="top" class="qt-style"><th>Application</th><th>4.1.1</th><th>4.1.2</th></tr></thead>
<tr valign="top" class="odd"><td>calculator</td><td>01.23</td><td>0.768</td></tr>
<tr valign="top" class="even"><td>calender</td><td>02.40</td><td>2.174</td></tr>
<tr valign="top" class="odd"><td>camera</td><td>02.44</td><td>0.918</td></tr>
<tr valign="top" class="even"><td>clock</td><td>00.71</td><td>0.568</td></tr>
<tr valign="top" class="odd"><td>contacts</td><td>02.36</td><td>1.602</td></tr>
<tr valign="top" class="even"><td>update_userhelp</td><td>00.70</td><td>0.567</td></tr>
<tr valign="top" class="odd"><td>messages</td><td>03.73</td><td>3.766</td></tr>
<tr valign="top" class="even"><td>notes</td><td>02.17</td><td>0.967</td></tr>
<tr valign="top" class="odd"><td>pictures</td><td>01.15</td><td>0.937</td></tr>
<tr valign="top" class="even"><td>sim applications</td><td>00.96</td><td>0.644</td></tr>
<tr valign="top" class="odd"><td>system info</td><td>01.44</td><td>1.247</td></tr>
<tr valign="top" class="even"><td>tasks</td><td>01.84</td><td>1.471</td></tr>
<tr valign="top" class="odd"><td>voice notes</td><td>02.70</td><td>0.879</td></tr>
<tr valign="top" class="even"><td>world time</td><td>02.66</td><td>1.708</td></tr>
<tr valign="top" class="odd"><td>beaming</td><td>02.12</td><td>1.282</td></tr>
<tr valign="top" class="even"><td>call forwarding</td><td>03.08</td><td>1.924</td></tr>
<tr valign="top" class="odd"><td>call networks</td><td>02.11</td><td>1.540</td></tr>
<tr valign="top" class="even"><td>call options</td><td>02.23</td><td>1.460</td></tr>
<tr valign="top" class="odd"><td>internet</td><td>03.01</td><td>1.853</td></tr>
<tr valign="top" class="even"><td>language</td><td>02.02</td><td>1.345</td></tr>
<tr valign="top" class="odd"><td>power management</td><td>02.02</td><td>1.808</td></tr>
<tr valign="top" class="even"><td>speed dial</td><td>04.67</td><td>1.878</td></tr>
<tr valign="top" class="odd"><td>words</td><td>02.26</td><td>1.343</td></tr>
</table></p>
<a name="bug-fixes"></a>
<h2>Bug Fixes</h2>
<ol type="1">
<li><b>Datebook</b><ul>
<li>BUG 4818: Couldn't edit an event twice in succession.</li>
</ul>
</li>
<li><b>Calendar</b><ul>
<li>BUG 5146: Calendar crashed when pressing OK with nothing selected under certain circumstances.</li>
<li>BUG 4973: Gray out days from other months in calendar month-view</li>
<li>BUG 113560: Calendar views where inconsistent between datebook and addresspicker</li>
</ul>
</li>
<li><b>Categories</b><ul>
<li>Fix no entry being added to category->content mapping table</li>
</ul>
</li>
<li><b>SXE</b><ul>
<li>BUG 113291: properly handle expired keys and out-of-date-ness</li>
</ul>
</li>
<li><b>Dialer</b><ul>
<li>Fix crash when entering numbers while a dialing call is in progress.</li>
</ul>
</li>
<li><b>QtMail</b><ul>
<li>BUG 113018: Restore ability to send emails and messages through qtmail from other apps by adding some missing qcop permissions to msg profile.</li>
</ul>
</li>
<li><b>Contacts</b><ul>
<li>BUG 114066: Clicking 'done' on the new contact dialog without entering any details created an empty contact.</li>
<li>BUG 113362: Entering a new contact name behaved oddly when using the phone keypads, worked fine when using the keyboard.</li>
<li>BUG 5038: When two contacts shared a number, calling one contact sometimes showed the other contact's name</li>
<li>BUG 4711: Updating icons in Contacts after selecting a category</li>
<li>BUG 4816: Show correct icon for select button after deleting a contact</li>
<li>BUG 4702: Allow a user to unselect a contact as the business card</li>
<li>BUG 5140: Contact name didn't show up in some cases</li>
</ul>
</li>
<li><b>Network</b><ul>
<li>BUG 11339: allow specific selection of non encrypted wifi network</li>
<li>BUG 4919: added IPv6 address validation</li>
</ul>
</li>
<li><b>WAP</b><ul>
<li>BUG 114260: Extended the maximum amount of data that can be read into WspParts to stop reading of large MMS attachments from failing.</li>
</ul>
</li>
<li><b>Qtopia</b><ul>
<li>BUG: Fixed server crash with transformed display</li>
<li>BUG 5099: cache cell location info to display immediately when turned on</li>
</ul>
</li>
<li><b>CallForwarding</b><ul>
<li>BUG 5145: Unset callforwarding correctly without restarting the app</li>
</ul>
</li>
<li><b>VOIP</b><ul>
<li>Redesigned Voip</li>
<li>BUG: fixed not sending SIP invite message</li>
<li>BUG: fixed VoIP registration state not coming through correctly</li>
</ul>
</li>
<li><b>PhotoEdit</b><ul>
<li>BUG 4948: Allow pictures to be edited, deleted, etc from thumbnail view</li>
</ul>
</li>
<li><b>WorldTime</b><ul>
<li>BUG 4759: Fixed city selection when scrolling zoomed zonemap</li>
<li>BUG 4759: Fixed scrolling of worldtime zonemap at edges.</li>
<li>BUG 4759: Allow the keypad to scoll the zoomed world map</li>
</ul>
</li>
<li><b>Todo</b><ul>
<li>BUG 4897: Fixed display issues with new/edit task dialog on touchscreen</li>
</ul>
</li>
<li><b>Calibrate</b><ul>
<li>BUG 5076: Added calibrate support in QVFb</li>
</ul>
</li>
</ol>
<p /><address><hr /><div align="center">
<table width="100%" cellspacing="0" border="0"><tr class="address">
<td align="left">Copyright © 2009 Trolltech</td>
<td align="center"><a href="trademarks.html">Trademarks</a></td>
<td align="right"><div align="right">Qt Extended 4.4.3</div></td>
</tr></table></div></address></body>
</html>
| liuyanghejerry/qtextended | doc/html/release-4-1-2.html | HTML | gpl-2.0 | 7,821 |
using System;
using Server;
using Server.Items;
namespace Server.Mobiles
{
[CorpseName( "a hydra corpse" )]
public class Hydra : BaseCreature
{
[Constructable]
public Hydra()
: base( AIType.AI_Melee, FightMode.Closest, 10, 1, 0.2, 0.4 )
{
Name = "a hydra";
Body = 0x109;
BaseSoundID = 0x16A;
SetStr( 801, 828 );
SetDex( 102, 118 );
SetInt( 102, 120 );
SetHits( 1480, 1500 );
SetDamage( 21, 26 );
SetDamageType( ResistanceType.Physical, 60 );
SetDamageType( ResistanceType.Fire, 10 );
SetDamageType( ResistanceType.Cold, 10 );
SetDamageType( ResistanceType.Poison, 10 );
SetDamageType( ResistanceType.Energy, 10 );
SetResistance( ResistanceType.Physical, 65, 75 );
SetResistance( ResistanceType.Fire, 70, 85 );
SetResistance( ResistanceType.Cold, 25, 35 );
SetResistance( ResistanceType.Poison, 35, 43 );
SetResistance( ResistanceType.Energy, 36, 45 );
SetSkill( SkillName.Wrestling, 103.5, 117.4 );
SetSkill( SkillName.Tactics, 100.1, 109.8 );
SetSkill( SkillName.MagicResist, 85.5, 98.5 );
SetSkill( SkillName.Anatomy, 75.4, 79.8 );
// TODO: Fame/Karma
}
public override void GenerateLoot()
{
AddLoot( LootPack.UltraRich, 3 );
}
public override void OnDeath( Container c )
{
base.OnDeath( c );
c.DropItem( new HydraScale() );
/*
// TODO: uncomment once added
if ( Utility.RandomDouble() < 0.2 )
c.DropItem( new ParrotItem() );
if ( Utility.RandomDouble() < 0.05 )
c.DropItem( new ThorvaldsMedallion() );
*/
}
public override bool HasBreath { get { return true; } }
public override int Hides { get { return 40; } }
public override int Meat { get { return 19; } }
public override int TreasureMapLevel { get { return 5; } }
public Hydra( Serial serial )
: base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
}
}
| jackuoll/Pre-AOS-RunUO | Scripts/Mobiles/Monsters/ML/Blighted Grove/Hydra.cs | C# | gpl-2.0 | 2,107 |
/*
* pcic.c: MicroSPARC-IIep PCI controller support
*
* Copyright (C) 1998 V. Roganov and G. Raiko
*
* Code is derived from Ultra/PCI PSYCHO controller support, see that
* for author info.
*
* Support for diverse IIep based platforms by Pete Zaitcev.
* CP-1200 by Eric Brower.
*/
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/init.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/jiffies.h>
#include <asm/swift.h> /* */
#include <asm/io.h>
#include <linux/ctype.h>
#include <linux/pci.h>
#include <linux/time.h>
#include <linux/timex.h>
#include <linux/interrupt.h>
#include <linux/export.h>
#include <asm/irq.h>
#include <asm/oplib.h>
#include <asm/prom.h>
#include <asm/pcic.h>
#include <asm/timex.h>
#include <asm/timer.h>
#include <asm/uaccess.h>
#include <asm/irq_regs.h>
#include "irq.h"
/*
*/
struct pcic_ca2irq {
unsigned char busno; /* */
unsigned char devfn; /* */
unsigned char pin; /* */
unsigned char irq; /* */
unsigned int force; /* */
};
struct pcic_sn2list {
char *sysname;
struct pcic_ca2irq *intmap;
int mapdim;
};
/*
*/
static struct pcic_ca2irq pcic_i_je1a[] = { /* */
{ 0, 0x00, 2, 12, 0 }, /* */
{ 0, 0x01, 1, 6, 1 }, /* */
{ 0, 0x80, 0, 7, 0 }, /* */
};
/* */
static struct pcic_ca2irq pcic_i_jse[] = {
{ 0, 0x00, 0, 13, 0 }, /* */
{ 0, 0x01, 1, 6, 0 }, /* */
{ 0, 0x08, 2, 9, 0 }, /* */
{ 0, 0x10, 6, 8, 0 }, /* */
{ 0, 0x18, 7, 12, 0 }, /* */
{ 0, 0x38, 4, 9, 0 }, /* */
{ 0, 0x80, 5, 11, 0 }, /* */
/* */
{ 0, 0xA0, 4, 9, 0 }, /* */
/*
*/
};
/*
*/
static struct pcic_ca2irq pcic_i_se6[] = {
{ 0, 0x08, 0, 2, 0 }, /* */
{ 0, 0x01, 1, 6, 0 }, /* */
{ 0, 0x00, 3, 13, 0 }, /* */
};
/*
*/
static struct pcic_ca2irq pcic_i_jk[] = {
{ 0, 0x00, 0, 13, 0 }, /* */
{ 0, 0x01, 1, 6, 0 }, /* */
};
/*
*/
#define SN2L_INIT(name, map) \
{ name, map, ARRAY_SIZE(map) }
static struct pcic_sn2list pcic_known_sysnames[] = {
SN2L_INIT("SUNW,JavaEngine1", pcic_i_je1a), /* */
SN2L_INIT("SUNW,JS-E", pcic_i_jse), /* */
SN2L_INIT("SUNW,SPARCengine-6", pcic_i_se6), /* */
SN2L_INIT("SUNW,JS-NC", pcic_i_jk), /* */
SN2L_INIT("SUNW,JSIIep", pcic_i_jk), /* */
{ NULL, NULL, 0 }
};
/*
*/
static int pcic0_up;
static struct linux_pcic pcic0;
void __iomem *pcic_regs;
volatile int pcic_speculative;
volatile int pcic_trapped;
/* */
unsigned int pcic_build_device_irq(struct platform_device *op,
unsigned int real_irq);
#define CONFIG_CMD(bus, device_fn, where) (0x80000000 | (((unsigned int)bus) << 16) | (((unsigned int)device_fn) << 8) | (where & ~3))
static int pcic_read_config_dword(unsigned int busno, unsigned int devfn,
int where, u32 *value)
{
struct linux_pcic *pcic;
unsigned long flags;
pcic = &pcic0;
local_irq_save(flags);
#if 0 /* */
pcic_speculative = 1;
pcic_trapped = 0;
#endif
writel(CONFIG_CMD(busno, devfn, where), pcic->pcic_config_space_addr);
#if 0 /* */
nop();
if (pcic_trapped) {
local_irq_restore(flags);
*value = ~0;
return 0;
}
#endif
pcic_speculative = 2;
pcic_trapped = 0;
*value = readl(pcic->pcic_config_space_data + (where&4));
nop();
if (pcic_trapped) {
pcic_speculative = 0;
local_irq_restore(flags);
*value = ~0;
return 0;
}
pcic_speculative = 0;
local_irq_restore(flags);
return 0;
}
static int pcic_read_config(struct pci_bus *bus, unsigned int devfn,
int where, int size, u32 *val)
{
unsigned int v;
if (bus->number != 0) return -EINVAL;
switch (size) {
case 1:
pcic_read_config_dword(bus->number, devfn, where&~3, &v);
*val = 0xff & (v >> (8*(where & 3)));
return 0;
case 2:
if (where&1) return -EINVAL;
pcic_read_config_dword(bus->number, devfn, where&~3, &v);
*val = 0xffff & (v >> (8*(where & 3)));
return 0;
case 4:
if (where&3) return -EINVAL;
pcic_read_config_dword(bus->number, devfn, where&~3, val);
return 0;
}
return -EINVAL;
}
static int pcic_write_config_dword(unsigned int busno, unsigned int devfn,
int where, u32 value)
{
struct linux_pcic *pcic;
unsigned long flags;
pcic = &pcic0;
local_irq_save(flags);
writel(CONFIG_CMD(busno, devfn, where), pcic->pcic_config_space_addr);
writel(value, pcic->pcic_config_space_data + (where&4));
local_irq_restore(flags);
return 0;
}
static int pcic_write_config(struct pci_bus *bus, unsigned int devfn,
int where, int size, u32 val)
{
unsigned int v;
if (bus->number != 0) return -EINVAL;
switch (size) {
case 1:
pcic_read_config_dword(bus->number, devfn, where&~3, &v);
v = (v & ~(0xff << (8*(where&3)))) |
((0xff&val) << (8*(where&3)));
return pcic_write_config_dword(bus->number, devfn, where&~3, v);
case 2:
if (where&1) return -EINVAL;
pcic_read_config_dword(bus->number, devfn, where&~3, &v);
v = (v & ~(0xffff << (8*(where&3)))) |
((0xffff&val) << (8*(where&3)));
return pcic_write_config_dword(bus->number, devfn, where&~3, v);
case 4:
if (where&3) return -EINVAL;
return pcic_write_config_dword(bus->number, devfn, where, val);
}
return -EINVAL;
}
static struct pci_ops pcic_ops = {
.read = pcic_read_config,
.write = pcic_write_config,
};
/*
*/
int __init pcic_probe(void)
{
struct linux_pcic *pcic;
struct linux_prom_registers regs[PROMREG_MAX];
struct linux_pbm_info* pbm;
char namebuf[64];
phandle node;
int err;
if (pcic0_up) {
prom_printf("PCIC: called twice!\n");
prom_halt();
}
pcic = &pcic0;
node = prom_getchild (prom_root_node);
node = prom_searchsiblings (node, "pci");
if (node == 0)
return -ENODEV;
/*
*/
err = prom_getproperty(node, "reg", (char*)regs, sizeof(regs));
if (err == 0 || err == -1) {
prom_printf("PCIC: Error, cannot get PCIC registers "
"from PROM.\n");
prom_halt();
}
pcic0_up = 1;
pcic->pcic_res_regs.name = "pcic_registers";
pcic->pcic_regs = ioremap(regs[0].phys_addr, regs[0].reg_size);
if (!pcic->pcic_regs) {
prom_printf("PCIC: Error, cannot map PCIC registers.\n");
prom_halt();
}
pcic->pcic_res_io.name = "pcic_io";
if ((pcic->pcic_io = (unsigned long)
ioremap(regs[1].phys_addr, 0x10000)) == 0) {
prom_printf("PCIC: Error, cannot map PCIC IO Base.\n");
prom_halt();
}
pcic->pcic_res_cfg_addr.name = "pcic_cfg_addr";
if ((pcic->pcic_config_space_addr =
ioremap(regs[2].phys_addr, regs[2].reg_size * 2)) == 0) {
prom_printf("PCIC: Error, cannot map "
"PCI Configuration Space Address.\n");
prom_halt();
}
/*
*/
pcic->pcic_res_cfg_data.name = "pcic_cfg_data";
if ((pcic->pcic_config_space_data =
ioremap(regs[3].phys_addr, regs[3].reg_size * 2)) == 0) {
prom_printf("PCIC: Error, cannot map "
"PCI Configuration Space Data.\n");
prom_halt();
}
pbm = &pcic->pbm;
pbm->prom_node = node;
prom_getstring(node, "name", namebuf, 63); namebuf[63] = 0;
strcpy(pbm->prom_name, namebuf);
{
extern volatile int t_nmi[4];
extern int pcic_nmi_trap_patch[4];
t_nmi[0] = pcic_nmi_trap_patch[0];
t_nmi[1] = pcic_nmi_trap_patch[1];
t_nmi[2] = pcic_nmi_trap_patch[2];
t_nmi[3] = pcic_nmi_trap_patch[3];
swift_flush_dcache();
pcic_regs = pcic->pcic_regs;
}
prom_getstring(prom_root_node, "name", namebuf, 63); namebuf[63] = 0;
{
struct pcic_sn2list *p;
for (p = pcic_known_sysnames; p->sysname != NULL; p++) {
if (strcmp(namebuf, p->sysname) == 0)
break;
}
pcic->pcic_imap = p->intmap;
pcic->pcic_imdim = p->mapdim;
}
if (pcic->pcic_imap == NULL) {
/*
*/
printk("PCIC: System %s is unknown, cannot route interrupts\n",
namebuf);
}
return 0;
}
static void __init pcic_pbm_scan_bus(struct linux_pcic *pcic)
{
struct linux_pbm_info *pbm = &pcic->pbm;
pbm->pci_bus = pci_scan_bus(pbm->pci_first_busno, &pcic_ops, pbm);
#if 0 /* */
pci_fill_in_pbm_cookies(pbm->pci_bus, pbm, pbm->prom_node);
pci_record_assignments(pbm, pbm->pci_bus);
pci_assign_unassigned(pbm, pbm->pci_bus);
pci_fixup_irq(pbm, pbm->pci_bus);
#endif
}
/*
*/
static int __init pcic_init(void)
{
struct linux_pcic *pcic;
/*
*/
if(!pcic0_up)
return 0;
pcic = &pcic0;
/*
*/
writeb(PCI_DVMA_CONTROL_IOTLB_DISABLE,
pcic->pcic_regs+PCI_DVMA_CONTROL);
/*
*/
writel(0xF0000000UL, pcic->pcic_regs+PCI_SIZE_0);
writel(0+PCI_BASE_ADDRESS_SPACE_MEMORY,
pcic->pcic_regs+PCI_BASE_ADDRESS_0);
pcic_pbm_scan_bus(pcic);
return 0;
}
int pcic_present(void)
{
return pcic0_up;
}
static int __devinit pdev_to_pnode(struct linux_pbm_info *pbm,
struct pci_dev *pdev)
{
struct linux_prom_pci_registers regs[PROMREG_MAX];
int err;
phandle node = prom_getchild(pbm->prom_node);
while(node) {
err = prom_getproperty(node, "reg",
(char *)®s[0], sizeof(regs));
if(err != 0 && err != -1) {
unsigned long devfn = (regs[0].which_io >> 8) & 0xff;
if(devfn == pdev->devfn)
return node;
}
node = prom_getsibling(node);
}
return 0;
}
static inline struct pcidev_cookie *pci_devcookie_alloc(void)
{
return kmalloc(sizeof(struct pcidev_cookie), GFP_ATOMIC);
}
static void pcic_map_pci_device(struct linux_pcic *pcic,
struct pci_dev *dev, int node)
{
char namebuf[64];
unsigned long address;
unsigned long flags;
int j;
if (node == 0 || node == -1) {
strcpy(namebuf, "???");
} else {
prom_getstring(node, "name", namebuf, 63); namebuf[63] = 0;
}
for (j = 0; j < 6; j++) {
address = dev->resource[j].start;
if (address == 0) break; /* */
flags = dev->resource[j].flags;
if ((flags & IORESOURCE_IO) != 0) {
if (address < 0x10000) {
/*
*/
dev->resource[j].start =
pcic->pcic_io + address;
dev->resource[j].end = 1; /* */
dev->resource[j].flags =
(flags & ~IORESOURCE_IO) | IORESOURCE_MEM;
} else {
/*
*/
printk("PCIC: Skipping I/O space at 0x%lx, "
"this will Oops if a driver attaches "
"device '%s' at %02x:%02x)\n", address,
namebuf, dev->bus->number, dev->devfn);
}
}
}
}
static void
pcic_fill_irq(struct linux_pcic *pcic, struct pci_dev *dev, int node)
{
struct pcic_ca2irq *p;
unsigned int real_irq;
int i, ivec;
char namebuf[64];
if (node == 0 || node == -1) {
strcpy(namebuf, "???");
} else {
prom_getstring(node, "name", namebuf, sizeof(namebuf));
}
if ((p = pcic->pcic_imap) == 0) {
dev->irq = 0;
return;
}
for (i = 0; i < pcic->pcic_imdim; i++) {
if (p->busno == dev->bus->number && p->devfn == dev->devfn)
break;
p++;
}
if (i >= pcic->pcic_imdim) {
printk("PCIC: device %s devfn %02x:%02x not found in %d\n",
namebuf, dev->bus->number, dev->devfn, pcic->pcic_imdim);
dev->irq = 0;
return;
}
i = p->pin;
if (i >= 0 && i < 4) {
ivec = readw(pcic->pcic_regs+PCI_INT_SELECT_LO);
real_irq = ivec >> (i << 2) & 0xF;
} else if (i >= 4 && i < 8) {
ivec = readw(pcic->pcic_regs+PCI_INT_SELECT_HI);
real_irq = ivec >> ((i-4) << 2) & 0xF;
} else { /* */
printk("PCIC: BAD PIN %d\n", i); for (;;) {}
}
/* */ /* */
/*
*/
if (real_irq == 0 || p->force) {
if (p->irq == 0 || p->irq >= 15) { /* */
printk("PCIC: BAD IRQ %d\n", p->irq); for (;;) {}
}
printk("PCIC: setting irq %d at pin %d for device %02x:%02x\n",
p->irq, p->pin, dev->bus->number, dev->devfn);
real_irq = p->irq;
i = p->pin;
if (i >= 4) {
ivec = readw(pcic->pcic_regs+PCI_INT_SELECT_HI);
ivec &= ~(0xF << ((i - 4) << 2));
ivec |= p->irq << ((i - 4) << 2);
writew(ivec, pcic->pcic_regs+PCI_INT_SELECT_HI);
} else {
ivec = readw(pcic->pcic_regs+PCI_INT_SELECT_LO);
ivec &= ~(0xF << (i << 2));
ivec |= p->irq << (i << 2);
writew(ivec, pcic->pcic_regs+PCI_INT_SELECT_LO);
}
}
dev->irq = pcic_build_device_irq(NULL, real_irq);
}
/*
*/
void __devinit pcibios_fixup_bus(struct pci_bus *bus)
{
struct pci_dev *dev;
int i, has_io, has_mem;
unsigned int cmd;
struct linux_pcic *pcic;
/* */
int node;
struct pcidev_cookie *pcp;
if (!pcic0_up) {
printk("pcibios_fixup_bus: no PCIC\n");
return;
}
pcic = &pcic0;
/*
*/
if (bus->number != 0) {
printk("pcibios_fixup_bus: nonzero bus 0x%x\n", bus->number);
return;
}
list_for_each_entry(dev, &bus->devices, bus_list) {
/*
*/
has_io = has_mem = 0;
for(i=0; i<6; i++) {
unsigned long f = dev->resource[i].flags;
if (f & IORESOURCE_IO) {
has_io = 1;
} else if (f & IORESOURCE_MEM)
has_mem = 1;
}
pcic_read_config(dev->bus, dev->devfn, PCI_COMMAND, 2, &cmd);
if (has_io && !(cmd & PCI_COMMAND_IO)) {
printk("PCIC: Enabling I/O for device %02x:%02x\n",
dev->bus->number, dev->devfn);
cmd |= PCI_COMMAND_IO;
pcic_write_config(dev->bus, dev->devfn,
PCI_COMMAND, 2, cmd);
}
if (has_mem && !(cmd & PCI_COMMAND_MEMORY)) {
printk("PCIC: Enabling memory for device %02x:%02x\n",
dev->bus->number, dev->devfn);
cmd |= PCI_COMMAND_MEMORY;
pcic_write_config(dev->bus, dev->devfn,
PCI_COMMAND, 2, cmd);
}
node = pdev_to_pnode(&pcic->pbm, dev);
if(node == 0)
node = -1;
/* */
pcp = pci_devcookie_alloc();
pcp->pbm = &pcic->pbm;
pcp->prom_node = of_find_node_by_phandle(node);
dev->sysdata = pcp;
/* */
if ((dev->class>>16) != PCI_BASE_CLASS_BRIDGE)
pcic_map_pci_device(pcic, dev, node);
pcic_fill_irq(pcic, dev, node);
}
}
/*
*/
unsigned int
pcic_pin_to_irq(unsigned int pin, const char *name)
{
struct linux_pcic *pcic = &pcic0;
unsigned int irq;
unsigned int ivec;
if (pin < 4) {
ivec = readw(pcic->pcic_regs+PCI_INT_SELECT_LO);
irq = ivec >> (pin << 2) & 0xF;
} else if (pin < 8) {
ivec = readw(pcic->pcic_regs+PCI_INT_SELECT_HI);
irq = ivec >> ((pin-4) << 2) & 0xF;
} else { /* */
printk("PCIC: BAD PIN %d FOR %s\n", pin, name);
for (;;) {} /* */
}
/* */ /* */
return irq;
}
/* */
static volatile int pcic_timer_dummy;
static void pcic_clear_clock_irq(void)
{
pcic_timer_dummy = readl(pcic0.pcic_regs+PCI_SYS_LIMIT);
}
static irqreturn_t pcic_timer_handler (int irq, void *h)
{
pcic_clear_clock_irq();
xtime_update(1);
#ifndef CONFIG_SMP
update_process_times(user_mode(get_irq_regs()));
#endif
return IRQ_HANDLED;
}
#define USECS_PER_JIFFY 10000 /* */
#define TICK_TIMER_LIMIT ((100*1000000/4)/100)
u32 pci_gettimeoffset(void)
{
/*
*/
unsigned long count =
readl(pcic0.pcic_regs+PCI_SYS_COUNTER) & ~PCI_SYS_COUNTER_OVERFLOW;
count = ((count/100)*USECS_PER_JIFFY) / (TICK_TIMER_LIMIT/100);
return count * 1000;
}
void __init pci_time_init(void)
{
struct linux_pcic *pcic = &pcic0;
unsigned long v;
int timer_irq, irq;
int err;
do_arch_gettimeoffset = pci_gettimeoffset;
btfixup();
writel (TICK_TIMER_LIMIT, pcic->pcic_regs+PCI_SYS_LIMIT);
/* */
v = readb(pcic->pcic_regs+PCI_COUNTER_IRQ);
timer_irq = PCI_COUNTER_IRQ_SYS(v);
writel (PCI_COUNTER_IRQ_SET(timer_irq, 0),
pcic->pcic_regs+PCI_COUNTER_IRQ);
irq = pcic_build_device_irq(NULL, timer_irq);
err = request_irq(irq, pcic_timer_handler,
IRQF_TIMER, "timer", NULL);
if (err) {
prom_printf("time_init: unable to attach IRQ%d\n", timer_irq);
prom_halt();
}
local_irq_enable();
}
#if 0
static void watchdog_reset() {
writeb(0, pcic->pcic_regs+PCI_SYS_STATUS);
}
#endif
/*
*/
char * __devinit pcibios_setup(char *str)
{
return str;
}
resource_size_t pcibios_align_resource(void *data, const struct resource *res,
resource_size_t size, resource_size_t align)
{
return res->start;
}
int pcibios_enable_device(struct pci_dev *pdev, int mask)
{
return 0;
}
/*
*/
void pcic_nmi(unsigned int pend, struct pt_regs *regs)
{
pend = flip_dword(pend);
if (!pcic_speculative || (pend & PCI_SYS_INT_PENDING_PIO) == 0) {
/*
*/
printk("Aiee, NMI pend 0x%x pc 0x%x spec %d, hanging\n",
pend, (int)regs->pc, pcic_speculative);
for (;;) { }
}
pcic_speculative = 0;
pcic_trapped = 1;
regs->pc = regs->npc;
regs->npc += 4;
}
static inline unsigned long get_irqmask(int irq_nr)
{
return 1 << irq_nr;
}
static void pcic_mask_irq(struct irq_data *data)
{
unsigned long mask, flags;
mask = (unsigned long)data->chip_data;
local_irq_save(flags);
writel(mask, pcic0.pcic_regs+PCI_SYS_INT_TARGET_MASK_SET);
local_irq_restore(flags);
}
static void pcic_unmask_irq(struct irq_data *data)
{
unsigned long mask, flags;
mask = (unsigned long)data->chip_data;
local_irq_save(flags);
writel(mask, pcic0.pcic_regs+PCI_SYS_INT_TARGET_MASK_CLEAR);
local_irq_restore(flags);
}
static unsigned int pcic_startup_irq(struct irq_data *data)
{
irq_link(data->irq);
pcic_unmask_irq(data);
return 0;
}
static struct irq_chip pcic_irq = {
.name = "pcic",
.irq_startup = pcic_startup_irq,
.irq_mask = pcic_mask_irq,
.irq_unmask = pcic_unmask_irq,
};
unsigned int pcic_build_device_irq(struct platform_device *op,
unsigned int real_irq)
{
unsigned int irq;
unsigned long mask;
irq = 0;
mask = get_irqmask(real_irq);
if (mask == 0)
goto out;
irq = irq_alloc(real_irq, real_irq);
if (irq == 0)
goto out;
irq_set_chip_and_handler_name(irq, &pcic_irq,
handle_level_irq, "PCIC");
irq_set_chip_data(irq, (void *)mask);
out:
return irq;
}
static void pcic_load_profile_irq(int cpu, unsigned int limit)
{
printk("PCIC: unimplemented code: FILE=%s LINE=%d", __FILE__, __LINE__);
}
void __init sun4m_pci_init_IRQ(void)
{
sparc_irq_config.build_device_irq = pcic_build_device_irq;
BTFIXUPSET_CALL(clear_clock_irq, pcic_clear_clock_irq, BTFIXUPCALL_NORM);
BTFIXUPSET_CALL(load_profile_irq, pcic_load_profile_irq, BTFIXUPCALL_NORM);
}
int pcibios_assign_resource(struct pci_dev *pdev, int resource)
{
return -ENXIO;
}
/*
*/
void outsb(unsigned long addr, const void *src, unsigned long count)
{
while (count) {
count -= 1;
outb(*(const char *)src, addr);
src += 1;
/* */
}
}
EXPORT_SYMBOL(outsb);
void outsw(unsigned long addr, const void *src, unsigned long count)
{
while (count) {
count -= 2;
outw(*(const short *)src, addr);
src += 2;
/* */
}
}
EXPORT_SYMBOL(outsw);
void outsl(unsigned long addr, const void *src, unsigned long count)
{
while (count) {
count -= 4;
outl(*(const long *)src, addr);
src += 4;
/* */
}
}
EXPORT_SYMBOL(outsl);
void insb(unsigned long addr, void *dst, unsigned long count)
{
while (count) {
count -= 1;
*(unsigned char *)dst = inb(addr);
dst += 1;
/* */
}
}
EXPORT_SYMBOL(insb);
void insw(unsigned long addr, void *dst, unsigned long count)
{
while (count) {
count -= 2;
*(unsigned short *)dst = inw(addr);
dst += 2;
/* */
}
}
EXPORT_SYMBOL(insw);
void insl(unsigned long addr, void *dst, unsigned long count)
{
while (count) {
count -= 4;
/*
*/
*(unsigned long *)dst = inl(addr);
dst += 4;
/* */
}
}
EXPORT_SYMBOL(insl);
subsys_initcall(pcic_init);
| holyangel/LGE_G3 | arch/sparc/kernel/pcic.c | C | gpl-2.0 | 24,782 |
// 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.cloudstack.acl;
import org.apache.cloudstack.api.ServerApiException;
import com.cloud.user.Account;
import com.cloud.utils.component.Adapter;
/**
* APILimitChecker checks if we should block an API request based on pre-set account based api limit.
*/
public interface APILimitChecker extends Adapter {
// Interface for checking if the account is over its api limit
void checkLimit(Account account) throws ServerApiException;
}
| ikoula/cloudstack | api/src/org/apache/cloudstack/acl/APILimitChecker.java | Java | gpl-2.0 | 1,259 |
/* Support for opening stores named in URL syntax.
Copyright (C) 2001,02 Free Software Foundation, Inc.
This file is part of the GNU Hurd.
The GNU Hurd is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2, or (at
your option) any later version.
The GNU Hurd is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111, USA. */
#include "store.h"
#include <string.h>
#include <stdlib.h>
/* Similar to store_typed_open, but NAME must be in URL format,
i.e. a class name followed by a ':' and any type-specific name.
Store classes opened this way must strip off the "class:" prefix.
A leading ':' or no ':' at all is invalid syntax. */
error_t
store_url_open (const char *name, int flags,
const struct store_class *const *classes,
struct store **store)
{
if (name == 0 || name[0] == ':' || strchr (name, ':') == 0)
return EINVAL;
return store_typed_open (name, flags, classes, store);
}
error_t
store_url_decode (struct store_enc *enc,
const struct store_class *const *classes,
struct store **store)
{
const struct store_class *cl;
/* This is pretty bogus. We use decode.c's code just to validate
the generic format and extract the name from the data. */
struct store dummy, *dummyptr;
error_t dummy_create (mach_port_t port, int flags, size_t block_size,
const struct store_run *runs, size_t num_runs,
struct store **store)
{
*store = &dummy;
return 0;
}
struct store_enc dummy_enc = *enc;
error_t err = store_std_leaf_decode (&dummy_enc, &dummy_create, &dummyptr);
if (err)
return err;
/* Find the class matching this name. */
cl = store_find_class (dummy.name, strchr (dummy.name, ':'), classes);
# pragma weak store_module_find_class
if (cl == 0 && store_module_find_class)
err = store_module_find_class (dummy.name, strchr (dummy.name, ':'),
&cl);
free (dummy.name);
free (dummy.misc);
if (cl == 0)
return EINVAL;
/* Now that we have the class, we just punt to its own decode hook. */
return (!cl->decode ? EOPNOTSUPP : (*cl->decode) (enc, classes, store));
}
/* This class is only trivially different from the "typed" class when used
by name. Its real purpose is to decode file_get_storage_info results
that use the STORAGE_NETWORK type, for which the convention is that the
name be in URL format (i.e. "type:something"). */
const struct store_class store_url_open_class =
{
STORAGE_NETWORK, "url",
open: store_url_open,
decode: store_url_decode
};
STORE_STD_CLASS (url_open);
| joshumax/hurd | libstore/url.c | C | gpl-2.0 | 3,038 |
/*
bParse
Copyright (c) 2006-2009 Charlie C & Erwin Coumans http://gamekit.googlecode.com
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "bChunk.h"
#include "bDefines.h"
#include "bFile.h"
#if !defined( __CELLOS_LV2__) && !defined(__MWERKS__)
#include <memory.h>
#endif
#include <string.h>
using namespace bParse;
// ----------------------------------------------------- //
short ChunkUtils::swapShort(short sht)
{
SWITCH_SHORT(sht);
return sht;
}
// ----------------------------------------------------- //
int ChunkUtils::swapInt(int inte)
{
SWITCH_INT(inte);
return inte;
}
// ----------------------------------------------------- //
long64 ChunkUtils::swapLong64(long64 lng)
{
SWITCH_LONGINT(lng);
return lng;
}
// ----------------------------------------------------- //
int ChunkUtils::getOffset(int flags)
{
// if the file is saved in a
// different format, get the
// file's chunk size
int res = CHUNK_HEADER_LEN;
if (VOID_IS_8)
{
if (flags &FD_BITS_VARIES)
res = sizeof(bChunkPtr4);
}
else
{
if (flags &FD_BITS_VARIES)
res = sizeof(bChunkPtr8);
}
return res;
}
//eof
| liquidmetal/bananaman | jni/gfx/bullet/bChunk.cpp | C++ | gpl-2.0 | 1,965 |
/* Measure bzero functions.
Copyright (C) 2013 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
#define TEST_BZERO
#include "bench-memset.c"
| SanDisk-Open-Source/SSD_Dashboard | uefi/userspace/glibc/benchtests/bench-bzero.c | C | gpl-2.0 | 856 |
#if !defined(_AMDGPU_TRACE_H) || defined(TRACE_HEADER_MULTI_READ)
#define _AMDGPU_TRACE_H_
#include <linux/stringify.h>
#include <linux/types.h>
#include <linux/tracepoint.h>
#include <drm/drmP.h>
#undef TRACE_SYSTEM
#define TRACE_SYSTEM amdgpu
#define TRACE_INCLUDE_FILE amdgpu_trace
TRACE_EVENT(amdgpu_bo_create,
TP_PROTO(struct amdgpu_bo *bo),
TP_ARGS(bo),
TP_STRUCT__entry(
__field(struct amdgpu_bo *, bo)
__field(u32, pages)
),
TP_fast_assign(
__entry->bo = bo;
__entry->pages = bo->tbo.num_pages;
),
TP_printk("bo=%p, pages=%u", __entry->bo, __entry->pages)
);
TRACE_EVENT(amdgpu_cs,
TP_PROTO(struct amdgpu_cs_parser *p, int i),
TP_ARGS(p, i),
TP_STRUCT__entry(
__field(u32, ring)
__field(u32, dw)
__field(u32, fences)
),
TP_fast_assign(
__entry->ring = p->ibs[i].ring->idx;
__entry->dw = p->ibs[i].length_dw;
__entry->fences = amdgpu_fence_count_emitted(
p->ibs[i].ring);
),
TP_printk("ring=%u, dw=%u, fences=%u",
__entry->ring, __entry->dw,
__entry->fences)
);
TRACE_EVENT(amdgpu_vm_grab_id,
TP_PROTO(unsigned vmid, int ring),
TP_ARGS(vmid, ring),
TP_STRUCT__entry(
__field(u32, vmid)
__field(u32, ring)
),
TP_fast_assign(
__entry->vmid = vmid;
__entry->ring = ring;
),
TP_printk("vmid=%u, ring=%u", __entry->vmid, __entry->ring)
);
TRACE_EVENT(amdgpu_vm_bo_update,
TP_PROTO(struct amdgpu_bo_va_mapping *mapping),
TP_ARGS(mapping),
TP_STRUCT__entry(
__field(u64, soffset)
__field(u64, eoffset)
__field(u32, flags)
),
TP_fast_assign(
__entry->soffset = mapping->it.start;
__entry->eoffset = mapping->it.last + 1;
__entry->flags = mapping->flags;
),
TP_printk("soffs=%010llx, eoffs=%010llx, flags=%08x",
__entry->soffset, __entry->eoffset, __entry->flags)
);
TRACE_EVENT(amdgpu_vm_set_page,
TP_PROTO(uint64_t pe, uint64_t addr, unsigned count,
uint32_t incr, uint32_t flags),
TP_ARGS(pe, addr, count, incr, flags),
TP_STRUCT__entry(
__field(u64, pe)
__field(u64, addr)
__field(u32, count)
__field(u32, incr)
__field(u32, flags)
),
TP_fast_assign(
__entry->pe = pe;
__entry->addr = addr;
__entry->count = count;
__entry->incr = incr;
__entry->flags = flags;
),
TP_printk("pe=%010Lx, addr=%010Lx, incr=%u, flags=%08x, count=%u",
__entry->pe, __entry->addr, __entry->incr,
__entry->flags, __entry->count)
);
TRACE_EVENT(amdgpu_vm_flush,
TP_PROTO(uint64_t pd_addr, unsigned ring, unsigned id),
TP_ARGS(pd_addr, ring, id),
TP_STRUCT__entry(
__field(u64, pd_addr)
__field(u32, ring)
__field(u32, id)
),
TP_fast_assign(
__entry->pd_addr = pd_addr;
__entry->ring = ring;
__entry->id = id;
),
TP_printk("pd_addr=%010Lx, ring=%u, id=%u",
__entry->pd_addr, __entry->ring, __entry->id)
);
DECLARE_EVENT_CLASS(amdgpu_fence_request,
TP_PROTO(struct drm_device *dev, int ring, u32 seqno),
TP_ARGS(dev, ring, seqno),
TP_STRUCT__entry(
__field(u32, dev)
__field(int, ring)
__field(u32, seqno)
),
TP_fast_assign(
__entry->dev = dev->primary->index;
__entry->ring = ring;
__entry->seqno = seqno;
),
TP_printk("dev=%u, ring=%d, seqno=%u",
__entry->dev, __entry->ring, __entry->seqno)
);
DEFINE_EVENT(amdgpu_fence_request, amdgpu_fence_emit,
TP_PROTO(struct drm_device *dev, int ring, u32 seqno),
TP_ARGS(dev, ring, seqno)
);
DEFINE_EVENT(amdgpu_fence_request, amdgpu_fence_wait_begin,
TP_PROTO(struct drm_device *dev, int ring, u32 seqno),
TP_ARGS(dev, ring, seqno)
);
DEFINE_EVENT(amdgpu_fence_request, amdgpu_fence_wait_end,
TP_PROTO(struct drm_device *dev, int ring, u32 seqno),
TP_ARGS(dev, ring, seqno)
);
DECLARE_EVENT_CLASS(amdgpu_semaphore_request,
TP_PROTO(int ring, struct amdgpu_semaphore *sem),
TP_ARGS(ring, sem),
TP_STRUCT__entry(
__field(int, ring)
__field(signed, waiters)
__field(uint64_t, gpu_addr)
),
TP_fast_assign(
__entry->ring = ring;
__entry->waiters = sem->waiters;
__entry->gpu_addr = sem->gpu_addr;
),
TP_printk("ring=%u, waiters=%d, addr=%010Lx", __entry->ring,
__entry->waiters, __entry->gpu_addr)
);
DEFINE_EVENT(amdgpu_semaphore_request, amdgpu_semaphore_signale,
TP_PROTO(int ring, struct amdgpu_semaphore *sem),
TP_ARGS(ring, sem)
);
DEFINE_EVENT(amdgpu_semaphore_request, amdgpu_semaphore_wait,
TP_PROTO(int ring, struct amdgpu_semaphore *sem),
TP_ARGS(ring, sem)
);
#endif
/* This part must be outside protection */
#undef TRACE_INCLUDE_PATH
#define TRACE_INCLUDE_PATH .
#include <trace/define_trace.h>
| zhjwpku/gsoc | drivers/gpu/drm/amd/amdgpu/amdgpu_trace.h | C | gpl-2.0 | 5,041 |
<?php
require_once dirname(__FILE__) . '/config.php';
require_once dirname(__FILE__) . '/views/header.tpl.php';
?>
<pre>
<?php
$CDCService = new QuickBooks_IPP_Service_ChangeDataCapture();
// What types of objects do you want to get?
$objects = array(
'Customer',
'Invoice',
);
// The date they should have been updated after
$timestamp = QuickBooks_Utilities::datetime('-5 years');
$cdc = $CDCService->cdc($Context, $realm,
$objects,
$timestamp);
print('<h2>Here are the ' . implode(', ', $objects) . ' that have changed since ' . $timestamp . '</h2>');
foreach ($cdc as $object_type => $list)
{
print('<h3>Now showing ' . $object_type . 's</h3>');
foreach ($list as $Object)
{
switch ($object_type)
{
case 'Customer':
print(' ' . $Object->getFullyQualifiedName() . '<br>');
break;
case 'Invoice':
print(' ' . $Object->getDocNumber() . '<br>');
break;
default:
print(' ' . $Object->getId() . '<br>');
break;
}
}
}
/*
print("\n\n\n\n");
print('Request [' . $IPP->lastRequest() . ']');
print("\n\n\n\n");
print('Response [' . $IPP->lastResponse() . ']');
print("\n\n\n\n");
*/
?>
</pre>
<?php
require_once dirname(__FILE__) . '/views/footer.tpl.php';
?> | kuldeep89/160515 | testapp/docs/partner_platform/app_ipp_v3/example_cdc.php | PHP | gpl-2.0 | 1,245 |
/*
* Copyright (c) 2012-2013, The Linux Foundation. All rights reserved.
*
* Previously licensed under the ISC license by Qualcomm Atheros, Inc.
*
*
* Permission to use, copy, modify, and/or distribute this software for
* any purpose with or without fee is hereby granted, provided that the
* above copyright notice and this permission notice appear in all
* copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
* WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
* AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
* PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
/*
* Copyright (c) 2012, The Linux Foundation. All rights reserved.
*
* Previously licensed under the ISC license by Qualcomm Atheros, Inc.
*
*
* Permission to use, copy, modify, and/or distribute this software for
* any purpose with or without fee is hereby granted, provided that the
* above copyright notice and this permission notice appear in all
* copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
* WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
* AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
* PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
/******************************************************************************
*
* Name: pmc.c
*
* Description:
Power Management Control (PMC) processing routines.
*
* Copyright 2008 (c) Qualcomm Technologies, Inc. All Rights Reserved.
* Qualcomm Technologies Confidential and Proprietary.
*
*
******************************************************************************/
#include "palTypes.h"
#include "aniGlobal.h"
#include "csrLinkList.h"
#include "csrApi.h"
#include "smeInside.h"
#include "sme_Api.h"
#include "smsDebug.h"
#include "pmc.h"
#include "wlan_qct_wda.h"
#include "wlan_ps_wow_diag.h"
#include <vos_power.h>
#include "csrInsideApi.h"
static void pmcProcessDeferredMsg( tpAniSirGlobal pMac );
/******************************************************************************
*
* Name: pmcEnterLowPowerState
*
* Description:
* Have the device enter Low Power State.
*
* Parameters:
* hHal - HAL handle for device
*
* Returns:
* eHAL_STATUS_SUCCESS - changing state successful
* eHAL_STATUS_FAILURE - changing state not successful
*
******************************************************************************/
eHalStatus pmcEnterLowPowerState (tHalHandle hHal)
{
tpAniSirGlobal pMac = PMAC_STRUCT(hHal);
pmcLog(pMac, LOG2, FL("Entering pmcEnterLowPowerState"));
/* If already in Low Power State, just return. */
if (pMac->pmc.pmcState == LOW_POWER)
return eHAL_STATUS_SUCCESS;
/* Cancel any running timers. */
if (vos_timer_stop(&pMac->pmc.hImpsTimer) != VOS_STATUS_SUCCESS)
{
pmcLog(pMac, LOGE, FL("Cannot cancel IMPS timer"));
return eHAL_STATUS_FAILURE;
}
pmcStopTrafficTimer(hHal);
if (vos_timer_stop(&pMac->pmc.hExitPowerSaveTimer) != VOS_STATUS_SUCCESS)
{
pmcLog(pMac, LOGE, FL("Cannot cancel exit power save mode timer"));
return eHAL_STATUS_FAILURE;
}
/* Do all the callbacks. */
pmcDoCallbacks(hHal, eHAL_STATUS_FAILURE);
/* Change state. */
pMac->pmc.pmcState = LOW_POWER;
return eHAL_STATUS_SUCCESS;
}
/******************************************************************************
*
* Name: pmcExitLowPowerState
*
* Description:
* Have the device exit the Low Power State.
*
* Parameters:
* hHal - HAL handle for device
*
* Returns:
* eHAL_STATUS_SUCCESS - changing state successful
* eHAL_STATUS_FAILURE - changing state not successful
*
******************************************************************************/
eHalStatus pmcExitLowPowerState (tHalHandle hHal)
{
tpAniSirGlobal pMac = PMAC_STRUCT(hHal);
pmcLog(pMac, LOG2, FL("Entering pmcExitLowPowerState"));
/* Must be in Low Power State if we are going to exit that state. */
if (pMac->pmc.pmcState != LOW_POWER)
{
pmcLog(pMac, LOGE, FL("Cannot exit Low Power State if not in that state"));
return eHAL_STATUS_FAILURE;
}
/* Both WLAN switches much be on to exit Low Power State. */
if ((pMac->pmc.hwWlanSwitchState == ePMC_SWITCH_OFF) || (pMac->pmc.swWlanSwitchState == ePMC_SWITCH_OFF))
return eHAL_STATUS_SUCCESS;
/* Change state. */
pMac->pmc.pmcState = FULL_POWER;
if(pmcShouldBmpsTimerRun(pMac))
{
if (pmcStartTrafficTimer(hHal, pMac->pmc.bmpsConfig.trafficMeasurePeriod) != eHAL_STATUS_SUCCESS)
return eHAL_STATUS_FAILURE;
}
return eHAL_STATUS_SUCCESS;
}
/******************************************************************************
*
* Name: pmcEnterFullPowerState
*
* Description:
* Have the device enter the Full Power State.
*
* Parameters:
* hHal - HAL handle for device
*
* Returns:
* eHAL_STATUS_SUCCESS - changing state successful
* eHAL_STATUS_FAILURE - changing state not successful
*
******************************************************************************/
eHalStatus pmcEnterFullPowerState (tHalHandle hHal)
{
tpAniSirGlobal pMac = PMAC_STRUCT(hHal);
pmcLog(pMac, LOG2, FL("Entering pmcEnterFullPowerState"));
/* Take action based on the current state. */
switch (pMac->pmc.pmcState)
{
/* Already in Full Power State. */
case FULL_POWER:
break;
/* Notify everyone that we are going to full power.
Change to Full Power State. */
case REQUEST_FULL_POWER:
case REQUEST_IMPS:
case REQUEST_BMPS:
case REQUEST_STANDBY:
/* Change state. */
pMac->pmc.pmcState = FULL_POWER;
pMac->pmc.requestFullPowerPending = FALSE;
if(pmcShouldBmpsTimerRun(pMac))
(void)pmcStartTrafficTimer(hHal, pMac->pmc.bmpsConfig.trafficMeasurePeriod);
pmcProcessDeferredMsg( pMac );
/* Do all the callbacks. */
pmcDoCallbacks(hHal, eHAL_STATUS_SUCCESS);
/* Update registerd modules that we are entering Full Power. This is
only way to inform modules if PMC exited a power save mode because
of error conditions or if som other module requested full power */
pmcDoDeviceStateUpdateCallbacks(hHal, FULL_POWER);
break;
/* Cannot go directly to Full Power State from these states. */
default:
pmcLog(pMac, LOGE, FL("Trying to enter Full Power State from state %d"), pMac->pmc.pmcState);
PMC_ABORT;
return eHAL_STATUS_FAILURE;
}
pmcLog(pMac, LOG1, "PMC: Enter full power done: Cancel XO Core ON vote");
if (vos_chipVoteXOCore(NULL, NULL, NULL, VOS_FALSE) != VOS_STATUS_SUCCESS)
{
pmcLog(pMac, LOGE, "Could not cancel XO Core ON vote. Not returning failure. "
"Power consumed will be high");
}
return eHAL_STATUS_SUCCESS;
}
/******************************************************************************
*
* Name: pmcEnterRequestFullPowerState
*
* Description:
* Have the device enter the Request Full Power State.
*
* Parameters:
* hHal - HAL handle for device
* fullPowerReason - Reason code for requesting full power
*
* Returns:
* eHAL_STATUS_SUCCESS - changing state successful
* eHAL_STATUS_FAILURE - changing state not successful
*
******************************************************************************/
eHalStatus pmcEnterRequestFullPowerState (tHalHandle hHal, tRequestFullPowerReason fullPowerReason)
{
tpAniSirGlobal pMac = PMAC_STRUCT(hHal);
vos_call_status_type callType;
VOS_STATUS status;
pmcLog(pMac, LOG2, FL("Entering pmcEnterRequestFullPowerState"));
/* Take action based on the current state of the device. */
switch (pMac->pmc.pmcState)
{
/* Should not request full power if already there. */
case FULL_POWER:
pmcLog(pMac, LOGE, FL("Requesting Full Power State when already there"));
return eHAL_STATUS_FAILURE;
/* Only power events can take device out of Low Power State. */
case LOW_POWER:
pmcLog(pMac, LOGE, FL("Cannot request exit from Low Power State"));
return eHAL_STATUS_FAILURE;
/* Cannot go directly to Request Full Power state from these states.
Record that this is pending and take care of it later. */
case REQUEST_IMPS:
case REQUEST_START_UAPSD:
case REQUEST_STOP_UAPSD:
case REQUEST_STANDBY:
case REQUEST_BMPS:
case REQUEST_ENTER_WOWL:
case REQUEST_EXIT_WOWL:
pmcLog(pMac, LOGW, FL("Request for full power is being buffered. "
"Current state is %d"), pMac->pmc.pmcState);
//Ignore the new reason if request for full power is already pending
if( !pMac->pmc.requestFullPowerPending )
{
pMac->pmc.requestFullPowerPending = TRUE;
pMac->pmc.requestFullPowerReason = fullPowerReason;
}
return eHAL_STATUS_SUCCESS;
/* Tell MAC to have device enter full power mode. */
case IMPS:
if ( pMac->pmc.rfSuppliesVotedOff )
{
status = vos_chipVoteOnRFSupply(&callType, NULL, NULL);
VOS_ASSERT( VOS_IS_STATUS_SUCCESS( status ) );
status = vos_chipVoteOnXOBuffer(&callType, NULL, NULL);
VOS_ASSERT( VOS_IS_STATUS_SUCCESS( status ) );
pMac->pmc.rfSuppliesVotedOff = FALSE;
}
if (pmcIssueCommand( pMac, eSmeCommandExitImps, NULL, 0, FALSE ) != eHAL_STATUS_SUCCESS)
{
return eHAL_STATUS_FAILURE;
}
return eHAL_STATUS_SUCCESS;
/* Tell MAC to have device enter full power mode. */
case BMPS:
{
tExitBmpsInfo exitBmpsInfo;
exitBmpsInfo.exitBmpsReason = fullPowerReason;
if (pmcIssueCommand(hHal, eSmeCommandExitBmps, &exitBmpsInfo, sizeof(tExitBmpsInfo), FALSE)
!= eHAL_STATUS_SUCCESS)
{
return eHAL_STATUS_FAILURE;
}
return eHAL_STATUS_SUCCESS;
}
/* Already in Request Full Power State. */
case REQUEST_FULL_POWER:
return eHAL_STATUS_SUCCESS;
/* Tell MAC to have device enter full power mode. */
case STANDBY:
if ( pMac->pmc.rfSuppliesVotedOff )
{
status = vos_chipVoteOnXOBuffer(&callType, NULL, NULL);
if(VOS_STATUS_SUCCESS != status)
{
return eHAL_STATUS_FAILURE;
}
status = vos_chipVoteOnRFSupply(&callType, NULL, NULL);
if(VOS_STATUS_SUCCESS != status)
{
return eHAL_STATUS_FAILURE;
}
pMac->pmc.rfSuppliesVotedOff = FALSE;
}
if (pmcIssueCommand(hHal, eSmeCommandExitImps, NULL, 0, FALSE) !=
eHAL_STATUS_SUCCESS)
{
pmcLog(pMac, LOGE, "PMC: failure to send message "
"eWNI_PMC_EXIT_IMPS_REQ");
return eHAL_STATUS_FAILURE;
}
return eHAL_STATUS_SUCCESS;
/* Tell MAC to have device exit UAPSD mode first */
case UAPSD:
//Need to save the reason code here in case later on we need to exit BMPS as well
if (pmcIssueCommand(hHal, eSmeCommandExitUapsd, &fullPowerReason, sizeof(tRequestFullPowerReason), FALSE) !=
eHAL_STATUS_SUCCESS)
{
pmcLog(pMac, LOGE, "PMC: failure to send message "
"eWNI_PMC_EXIT_UAPSD_REQ");
return eHAL_STATUS_FAILURE;
}
return eHAL_STATUS_SUCCESS;
/* Tell MAC to have device exit WOWL mode first */
case WOWL:
if (pmcIssueCommand(hHal, eSmeCommandExitWowl, &fullPowerReason, sizeof(tRequestFullPowerReason), FALSE) !=
eHAL_STATUS_SUCCESS)
{
pmcLog(pMac, LOGP, "PMC: failure to send message "
"eWNI_PMC_EXIT_WOWL_REQ");
return eHAL_STATUS_FAILURE;
}
return eHAL_STATUS_SUCCESS;
/* Cannot go directly to Request Full Power State from these states. */
default:
pmcLog(pMac, LOGE,
FL("Trying to enter Request Full Power State from state %d"), pMac->pmc.pmcState);
PMC_ABORT;
return eHAL_STATUS_FAILURE;
}
}
/******************************************************************************
*
* Name: pmcEnterRequestImpsState
*
* Description:
* Have the device enter the Request IMPS State.
*
* Parameters:
* hHal - HAL handle for device
*
* Returns:
* eHAL_STATUS_SUCCESS - changing state successful
* eHAL_STATUS_FAILURE - changing state not successful
*
******************************************************************************/
eHalStatus pmcEnterRequestImpsState (tHalHandle hHal)
{
tpAniSirGlobal pMac = PMAC_STRUCT(hHal);
pmcLog(pMac, LOG2, FL("Entering pmcEnterRequestImpsState"));
/* Can enter Request IMPS State only from Full Power State. */
if (pMac->pmc.pmcState != FULL_POWER)
{
pmcLog(pMac, LOGE, FL("Trying to enter Request IMPS State from state %d"), pMac->pmc.pmcState);
return eHAL_STATUS_FAILURE;
}
/* Make sure traffic timer that triggers bmps entry is not running */
pmcStopTrafficTimer(hHal);
/* Tell MAC to have device enter IMPS mode. */
if (pmcIssueCommand(hHal, eSmeCommandEnterImps, NULL, 0, FALSE) != eHAL_STATUS_SUCCESS)
{
pmcLog(pMac, LOGE, "PMC: failure to send message eWNI_PMC_ENTER_IMPS_REQ");
pMac->pmc.pmcState = FULL_POWER;
if(pmcShouldBmpsTimerRun(pMac))
(void)pmcStartTrafficTimer(hHal, pMac->pmc.bmpsConfig.trafficMeasurePeriod);
return eHAL_STATUS_FAILURE;
}
pmcLog(pMac, LOG2, FL("eWNI_PMC_ENTER_IMPS_REQ sent to PE"));
return eHAL_STATUS_SUCCESS;
}
/******************************************************************************
*
* Name: pmcEnterImpsState
*
* Description:
* Have the device enter the IMPS State.
*
* Parameters:
* hHal - HAL handle for device
*
* Returns:
* eHAL_STATUS_SUCCESS - changing state successful
* eHAL_STATUS_FAILURE - changing state not successful
*
******************************************************************************/
eHalStatus pmcEnterImpsState (tHalHandle hHal)
{
tpAniSirGlobal pMac = PMAC_STRUCT(hHal);
vos_call_status_type callType;
VOS_STATUS status;
pmcLog(pMac, LOG2, FL("Entering pmcEnterImpsState"));
/* Can enter IMPS State only from Request IMPS State. */
if (pMac->pmc.pmcState != REQUEST_IMPS)
{
pmcLog(pMac, LOGE, FL("Trying to enter IMPS State from state %d"), pMac->pmc.pmcState);
return eHAL_STATUS_FAILURE;
}
/* Change state. */
pMac->pmc.pmcState = IMPS;
/* If we have a reqeust for full power pending then we have to go
directly into full power. */
if (pMac->pmc.requestFullPowerPending)
{
/* Start exit IMPS sequence now. */
return pmcEnterRequestFullPowerState(hHal, pMac->pmc.requestFullPowerReason);
}
/* Set timer to come out of IMPS.only if impsPeriod is non-Zero*/
if(0 != pMac->pmc.impsPeriod)
{
if (vos_timer_start(&pMac->pmc.hImpsTimer, pMac->pmc.impsPeriod) != VOS_STATUS_SUCCESS)
{
PMC_ABORT;
pMac->pmc.ImpsReqTimerFailed = VOS_TRUE;
if (!(pMac->pmc.ImpsReqTimerfailCnt & 0xF))
{
pMac->pmc.ImpsReqTimerfailCnt++;
pmcLog(pMac, LOGE,
FL("Cannot start IMPS timer, FailCnt - %d"), pMac->pmc.ImpsReqTimerfailCnt);
}
pmcEnterRequestFullPowerState(hHal, eSME_REASON_OTHER);
return eHAL_STATUS_FAILURE;
}
if (pMac->pmc.ImpsReqTimerfailCnt)
{
pmcLog(pMac, LOGE,
FL("Start IMPS timer was failed %d times before success"), pMac->pmc.ImpsReqTimerfailCnt);
}
pMac->pmc.ImpsReqTimerfailCnt = 0;
}
//Vote off RF supplies. Note RF supllies are not voted off if there is a
//pending request for full power already
status = vos_chipVoteOffRFSupply(&callType, NULL, NULL);
VOS_ASSERT( VOS_IS_STATUS_SUCCESS( status ) );
status = vos_chipVoteOffXOBuffer(&callType, NULL, NULL);
VOS_ASSERT( VOS_IS_STATUS_SUCCESS( status ) );
pMac->pmc.rfSuppliesVotedOff= TRUE;
return eHAL_STATUS_SUCCESS;
}
/******************************************************************************
*
* Name: pmcEnterRequestBmpsState
*
* Description:
* Have the device enter the Request BMPS State.
*
* Parameters:
* hHal - HAL handle for device
*
* Returns:
* eHAL_STATUS_SUCCESS - changing state successful
* eHAL_STATUS_FAILURE - changing state not successful
*
******************************************************************************/
eHalStatus pmcEnterRequestBmpsState (tHalHandle hHal)
{
tpAniSirGlobal pMac = PMAC_STRUCT(hHal);
pmcLog(pMac, LOG2, FL("Entering pmcEnterRequestBmpsState"));
/* Can enter Request BMPS State only from Full Power State. */
if (pMac->pmc.pmcState != FULL_POWER)
{
pmcLog(pMac, LOGE,
FL("Trying to enter Request BMPS State from state %d"), pMac->pmc.pmcState);
return eHAL_STATUS_FAILURE;
}
/* Stop Traffic timer if running. Note: timer could have expired because of possible
race conditions. So no need to check for errors. Just make sure timer is not running */
pmcStopTrafficTimer(hHal);
/* Tell MAC to have device enter BMPS mode. */
if ( !pMac->pmc.bmpsRequestQueued )
{
pMac->pmc.bmpsRequestQueued = eANI_BOOLEAN_TRUE;
if(pmcIssueCommand(hHal, eSmeCommandEnterBmps, NULL, 0, FALSE) != eHAL_STATUS_SUCCESS)
{
pmcLog(pMac, LOGE, "PMC: failure to send message eWNI_PMC_ENTER_BMPS_REQ");
pMac->pmc.bmpsRequestQueued = eANI_BOOLEAN_FALSE;
pMac->pmc.pmcState = FULL_POWER;
if(pmcShouldBmpsTimerRun(pMac))
{
(void)pmcStartTrafficTimer(hHal, pMac->pmc.bmpsConfig.trafficMeasurePeriod);
}
return eHAL_STATUS_FAILURE;
}
}
else
{
pmcLog(pMac, LOGE, "PMC: enter BMPS command already queued");
//restart the timer if needed
if(pmcShouldBmpsTimerRun(pMac))
{
(void)pmcStartTrafficTimer(hHal, pMac->pmc.bmpsConfig.trafficMeasurePeriod);
}
return eHAL_STATUS_SUCCESS;
}
pmcLog(pMac, LOGW, FL("eWNI_PMC_ENTER_BMPS_REQ sent to PE"));
return eHAL_STATUS_SUCCESS;
}
/******************************************************************************
*
* Name: pmcEnterBmpsState
*
* Description:
* Have the device enter the BMPS State.
*
* Parameters:
* hHal - HAL handle for device
*
* Returns:
* eHAL_STATUS_SUCCESS - changing state successful
* eHAL_STATUS_FAILURE - changing state not successful
*
******************************************************************************/
eHalStatus pmcEnterBmpsState (tHalHandle hHal)
{
tpAniSirGlobal pMac = PMAC_STRUCT(hHal);
pmcLog(pMac, LOG2, FL("Entering pmcEnterBmpsState"));
/* Can enter BMPS State only from 5 states. */
if (pMac->pmc.pmcState != REQUEST_BMPS &&
pMac->pmc.pmcState != REQUEST_START_UAPSD &&
pMac->pmc.pmcState != REQUEST_STOP_UAPSD &&
pMac->pmc.pmcState != REQUEST_ENTER_WOWL &&
pMac->pmc.pmcState != REQUEST_EXIT_WOWL)
{
pmcLog(pMac, LOGE, FL("Trying to enter BMPS State from state %d"), pMac->pmc.pmcState);
return eHAL_STATUS_FAILURE;
}
/* Change state. */
pMac->pmc.pmcState = BMPS;
/* Update registerd modules that we are entering BMPS. This is
only way to inform modules if PMC entered BMPS power save mode
on its own because of traffic timer */
pmcDoDeviceStateUpdateCallbacks(hHal, BMPS);
/* If we have a reqeust for full power pending then we have to go directly into full power. */
if (pMac->pmc.requestFullPowerPending)
{
/* Start exit BMPS sequence now. */
pmcLog(pMac, LOGW, FL("Pending Full Power request found on entering BMPS mode. "
"Start exit BMPS exit sequence"));
//Note: Reason must have been set when requestFullPowerPending flag was set.
pmcEnterRequestFullPowerState(hHal, pMac->pmc.requestFullPowerReason);
return eHAL_STATUS_SUCCESS;
}
/*This should never happen ideally. WOWL and UAPSD not supported at the same time */
if (pMac->pmc.wowlModeRequired && pMac->pmc.uapsdSessionRequired)
{
pmcLog(pMac, LOGW, FL("Both UAPSD and WOWL is required on entering BMPS mode. "
"UAPSD will be prioritized over WOWL"));
}
/* Do we need Uapsd?*/
if (pMac->pmc.uapsdSessionRequired)
{
pmcLog(pMac, LOGW, FL("UAPSD session is required on entering BMPS mode. "
"Start UAPSD entry sequence"));
pmcEnterRequestStartUapsdState(hHal);
return eHAL_STATUS_SUCCESS;
}
/* Do we need WOWL?*/
if (pMac->pmc.wowlModeRequired)
{
pmcLog(pMac, LOGW, FL("WOWL is required on entering BMPS mode. "
"Start WOWL entry sequence"));
pmcRequestEnterWowlState(hHal, &(pMac->pmc.wowlEnterParams));
}
return eHAL_STATUS_SUCCESS;
}
/******************************************************************************
*
* Name: pmcPowerSaveCheck
*
* Description:
* Check if device is allowed to enter a power save mode.
*
* Parameters:
* hHal - HAL handle for device
*
* Returns:
* TRUE - entry is allowed
* FALSE - entry is not allowed at this time
*
******************************************************************************/
tANI_BOOLEAN pmcPowerSaveCheck (tHalHandle hHal)
{
tpAniSirGlobal pMac = PMAC_STRUCT(hHal);
tListElem *pEntry;
tpPowerSaveCheckEntry pPowerSaveCheckEntry;
tANI_BOOLEAN (*checkRoutine) (void *checkContext);
tANI_BOOLEAN bResult=FALSE;
pmcLog(pMac, LOG2, FL("Entering pmcPowerSaveCheck"));
/* Call the routines in the power save check routine list. If any
return FALSE, then we cannot go into power save mode. */
pEntry = csrLLPeekHead(&pMac->pmc.powerSaveCheckList, FALSE);
while (pEntry != NULL)
{
pPowerSaveCheckEntry = GET_BASE_ADDR(pEntry, tPowerSaveCheckEntry, link);
checkRoutine = pPowerSaveCheckEntry->checkRoutine;
/* If the checkRoutine is NULL for a paricular entry, proceed with other entries
* in the list */
if (NULL != checkRoutine)
{
if (!checkRoutine(pPowerSaveCheckEntry->checkContext))
{
pmcLog(pMac, LOGE, FL("pmcPowerSaveCheck fail!"));
bResult = FALSE;
break;
}
else
{
bResult = TRUE;
}
}
pEntry = csrLLNext(&pMac->pmc.powerSaveCheckList, pEntry, FALSE);
}
return bResult;
}
/******************************************************************************
*
* Name: pmcSendPowerSaveConfigMessage
*
* Description:
* Send a message to PE/MAC to configure the power saving modes.
*
* Parameters:
* hHal - HAL handle for device
*
* Returns:
* eHAL_STATUS_SUCCESS - message successfuly sent
* eHAL_STATUS_FAILURE - error while sending message
*
******************************************************************************/
eHalStatus pmcSendPowerSaveConfigMessage (tHalHandle hHal)
{
tpAniSirGlobal pMac = PMAC_STRUCT(hHal);
tSirPowerSaveCfg powerSaveConfig;
pmcLog(pMac, LOG2, FL("Entering pmcSendPowerSaveConfigMessage"));
palZeroMemory(pMac->hHdd, &(powerSaveConfig), sizeof(tSirPowerSaveCfg));
switch (pMac->pmc.bmpsConfig.forwardBeacons)
{
case ePMC_NO_BEACONS:
powerSaveConfig.beaconFwd = ePM_BEACON_FWD_NONE;
break;
case ePMC_BEACONS_WITH_TIM_SET:
powerSaveConfig.beaconFwd = ePM_BEACON_FWD_TIM;
break;
case ePMC_BEACONS_WITH_DTIM_SET:
powerSaveConfig.beaconFwd = ePM_BEACON_FWD_DTIM;
break;
case ePMC_NTH_BEACON:
powerSaveConfig.beaconFwd = ePM_BEACON_FWD_NTH;
powerSaveConfig.nthBeaconFwd = (tANI_U16)pMac->pmc.bmpsConfig.valueOfN;
break;
case ePMC_ALL_BEACONS:
powerSaveConfig.beaconFwd = ePM_BEACON_FWD_NTH;
powerSaveConfig.nthBeaconFwd = 1;
break;
}
powerSaveConfig.fEnablePwrSaveImmediately = pMac->pmc.bmpsConfig.setPmOnLastFrame;
powerSaveConfig.fPSPoll = pMac->pmc.bmpsConfig.usePsPoll;
powerSaveConfig.fEnableBeaconEarlyTermination =
pMac->pmc.bmpsConfig.enableBeaconEarlyTermination;
powerSaveConfig.bcnEarlyTermWakeInterval =
pMac->pmc.bmpsConfig.bcnEarlyTermWakeInterval;
/* setcfg for listenInterval. Make sure CFG is updated because PE reads this
from CFG at the time of assoc or reassoc */
ccmCfgSetInt(pMac, WNI_CFG_LISTEN_INTERVAL, pMac->pmc.bmpsConfig.bmpsPeriod,
NULL, eANI_BOOLEAN_FALSE);
if( pMac->pmc.pmcState == IMPS || pMac->pmc.pmcState == REQUEST_IMPS )
{
//Wake up the chip first
eHalStatus status = pmcDeferMsg( pMac, eWNI_PMC_PWR_SAVE_CFG,
&powerSaveConfig, sizeof(tSirPowerSaveCfg) );
if( eHAL_STATUS_PMC_PENDING == status )
{
return eHAL_STATUS_SUCCESS;
}
else
{
//either fail or already in full power
if( !HAL_STATUS_SUCCESS( status ) )
{
return ( status );
}
//else let it through because it is in full power state
}
}
/* Send a message so that FW System config is also updated and is in sync with
the CFG.*/
if (pmcSendMessage(hHal, eWNI_PMC_PWR_SAVE_CFG, &powerSaveConfig, sizeof(tSirPowerSaveCfg))
!= eHAL_STATUS_SUCCESS)
{
pmcLog(pMac, LOGE, FL("Send of eWNI_PMC_PWR_SAVE_CFG to PE failed"));
return eHAL_STATUS_FAILURE;
}
return eHAL_STATUS_SUCCESS;
}
/******************************************************************************
*
* Name: pmcSendMessage
*
* Description:
* Send a message to PE/MAC.
*
* Parameters:
* hHal - HAL handle for device
* messageType - message type to send
* pMessageData - pointer to message data
* messageSize - Size of the message data
*
* Returns:
* eHAL_STATUS_SUCCESS - message successfuly sent
* eHAL_STATUS_FAILURE - error while sending message
*
******************************************************************************/
eHalStatus pmcSendMessage (tpAniSirGlobal pMac, tANI_U16 messageType, void *pMessageData, tANI_U32 messageSize)
{
tSirMbMsg *pMsg;
pmcLog(pMac, LOG2, FL("Entering pmcSendMessage, message type %d"), messageType);
/* Allocate and fill in message. */
if (palAllocateMemory(pMac->hHdd, (void **)&pMsg, WNI_CFG_MB_HDR_LEN + messageSize) != eHAL_STATUS_SUCCESS)
{
pmcLog(pMac, LOGE, FL("Cannot allocate memory for message"));
PMC_ABORT;
return eHAL_STATUS_FAILURE;
}
pMsg->type = messageType;
pMsg->msgLen = (tANI_U16) (WNI_CFG_MB_HDR_LEN + messageSize);
if (messageSize > 0)
{
if (palCopyMemory(pMac->hHdd, pMsg->data, pMessageData, messageSize) != eHAL_STATUS_SUCCESS)
{
pmcLog(pMac, LOGE, FL("Cannot copy message data"));
PMC_ABORT;
return eHAL_STATUS_FAILURE;
}
}
/* Send message. */
if (palSendMBMessage(pMac->hHdd, pMsg) != eHAL_STATUS_SUCCESS)
{
pmcLog(pMac, LOGE, FL("Cannot send message"));
PMC_ABORT;
return eHAL_STATUS_FAILURE;
}
return eHAL_STATUS_SUCCESS;
}
/******************************************************************************
*
* Name: pmcDoCallbacks
*
* Description:
* Call the IMPS callback routine and the routines in the request full
* power callback routine list.
*
* Parameters:
* hHal - HAL handle for device
* callbackStatus - status to pass to the callback routines
*
* Returns:
* nothing
*
******************************************************************************/
void pmcDoCallbacks (tHalHandle hHal, eHalStatus callbackStatus)
{
tpAniSirGlobal pMac = PMAC_STRUCT(hHal);
tListElem *pEntry;
tpRequestFullPowerEntry pRequestFullPowerEntry;
pmcLog(pMac, LOG2, FL("Entering pmcDoCallbacks"));
/* Call IMPS callback routine. */
if (pMac->pmc.impsCallbackRoutine != NULL)
{
pMac->pmc.impsCallbackRoutine(pMac->pmc.impsCallbackContext, callbackStatus);
pMac->pmc.impsCallbackRoutine = NULL;
}
/* Call the routines in the request full power callback routine list. */
while (NULL != (pEntry = csrLLRemoveHead(&pMac->pmc.requestFullPowerList, TRUE)))
{
pRequestFullPowerEntry = GET_BASE_ADDR(pEntry, tRequestFullPowerEntry, link);
if (pRequestFullPowerEntry->callbackRoutine)
pRequestFullPowerEntry->callbackRoutine(pRequestFullPowerEntry->callbackContext, callbackStatus);
if (palFreeMemory(pMac->hHdd, pRequestFullPowerEntry) != eHAL_STATUS_SUCCESS)
{
pmcLog(pMac, LOGE, FL("Cannot free request full power routine list entry"));
PMC_ABORT;
}
}
}
/******************************************************************************
*
* Name: pmcStartTrafficTimer
*
* Description:
* Start the timer used in Full Power State to measure traffic
* levels and determine when to enter BMPS.
*
* Parameters:
* hHal - HAL handle for device
*
* Returns:
* eHAL_STATUS_SUCCESS - timer successfuly started
* eHAL_STATUS_FAILURE - error while starting timer
*
******************************************************************************/
eHalStatus pmcStartTrafficTimer (tHalHandle hHal, tANI_U32 expirationTime)
{
tpAniSirGlobal pMac = PMAC_STRUCT(hHal);
VOS_STATUS vosStatus;
pmcLog(pMac, LOG2, FL("Entering pmcStartTrafficTimer"));
vosStatus = vos_timer_start(&pMac->pmc.hTrafficTimer, expirationTime);
if ( !VOS_IS_STATUS_SUCCESS(vosStatus) )
{
if( VOS_STATUS_E_ALREADY == vosStatus )
{
//Consider this ok since the timer is already started.
pmcLog(pMac, LOGW, FL(" traffic timer is already started"));
}
else
{
pmcLog(pMac, LOGP, FL("Cannot start traffic timer"));
return eHAL_STATUS_FAILURE;
}
}
return eHAL_STATUS_SUCCESS;
}
/******************************************************************************
*
* Name: pmcStopTrafficTimer
*
* Description:
* Cancels the timer (if running) used in Full Power State to measure traffic
* levels and determine when to enter BMPS.
*
* Parameters:
* hHal - HAL handle for device
*
*
******************************************************************************/
void pmcStopTrafficTimer (tHalHandle hHal)
{
tpAniSirGlobal pMac = PMAC_STRUCT(hHal);
pmcLog(pMac, LOG2, FL("Entering pmcStopTrafficTimer"));
vos_timer_stop(&pMac->pmc.hTrafficTimer);
}
/******************************************************************************
*
* Name: pmcImpsTimerExpired
*
* Description:
* Called when IMPS timer expires.
*
* Parameters:
* hHal - HAL handle for device
*
* Returns:
* nothing
*
******************************************************************************/
void pmcImpsTimerExpired (tHalHandle hHal)
{
tpAniSirGlobal pMac = PMAC_STRUCT(hHal);
pmcLog(pMac, LOG2, FL("Entering pmcImpsTimerExpired"));
/* If timer expires and we are in a state other than IMPS State then something is wrong. */
if (pMac->pmc.pmcState != IMPS)
{
pmcLog(pMac, LOGE, FL("Got IMPS timer expiration in state %d"), pMac->pmc.pmcState);
PMC_ABORT;
return;
}
/* Start on the path of going back to full power. */
pmcEnterRequestFullPowerState(hHal, eSME_REASON_OTHER);
}
/******************************************************************************
*
* Name: pmcTrafficTimerExpired
*
* Description:
* Called when traffic measurement timer expires.
*
* Parameters:
* hHal - HAL handle for device
*
* Returns:
* nothing
*
******************************************************************************/
void pmcTrafficTimerExpired (tHalHandle hHal)
{
tpAniSirGlobal pMac = PMAC_STRUCT(hHal);
VOS_STATUS vosStatus;
pmcLog(pMac, LOG2, FL("BMPS Traffic timer expired"));
/* If timer expires and we are in a state other than Full Power State then something is wrong. */
if (pMac->pmc.pmcState != FULL_POWER)
{
pmcLog(pMac, LOGE, FL("Got traffic timer expiration in state %d"), pMac->pmc.pmcState);
return;
}
/* Untill DHCP is not completed remain in power active */
if(pMac->pmc.remainInPowerActiveTillDHCP)
{
pmcLog(pMac, LOG2, FL("BMPS Traffic Timer expired before DHCP completion ignore enter BMPS"));
pMac->pmc.remainInPowerActiveThreshold++;
if( pMac->pmc.remainInPowerActiveThreshold >= DHCP_REMAIN_POWER_ACTIVE_THRESHOLD)
{
pmcLog(pMac, LOGE,
FL("Remain in power active DHCP threshold reached FALLBACK to enable enter BMPS"));
/*FALLBACK: reset the flag to make BMPS entry possible*/
pMac->pmc.remainInPowerActiveTillDHCP = FALSE;
pMac->pmc.remainInPowerActiveThreshold = 0;
}
//Activate the Traffic Timer again for entering into BMPS
vosStatus = vos_timer_start(&pMac->pmc.hTrafficTimer, pMac->pmc.bmpsConfig.trafficMeasurePeriod);
if ( !VOS_IS_STATUS_SUCCESS(vosStatus) && (VOS_STATUS_E_ALREADY != vosStatus) )
{
pmcLog(pMac, LOGP, FL("Cannot re-start traffic timer"));
}
return;
}
/* Clear remain in power active threshold */
pMac->pmc.remainInPowerActiveThreshold = 0;
/* Check if the timer should be running */
if (!pmcShouldBmpsTimerRun(pMac))
{
pmcLog(pMac, LOGE, FL("BMPS timer should not be running"));
return;
}
#ifdef FEATURE_WLAN_TDLS
if (pMac->isTdlsPowerSaveProhibited)
{
pmcLog(pMac, LOGE, FL("TDLS peer(s) connected/discovery sent. Dont enter BMPS"));
return;
}
#endif
if (pmcPowerSaveCheck(hHal))
{
pmcLog(pMac, LOGW, FL("BMPS entry criteria satisfied. Requesting BMPS state"));
(void)pmcEnterRequestBmpsState(hHal);
}
else
{
/*Some module voted against Power Save. So timer should be restarted again to retry BMPS */
pmcLog(pMac, LOGE, FL("Power Save check failed. Retry BMPS again later"));
//Since hTrafficTimer is a vos_timer now, we need to restart the timer here
vosStatus = vos_timer_start(&pMac->pmc.hTrafficTimer, pMac->pmc.bmpsConfig.trafficMeasurePeriod);
if ( !VOS_IS_STATUS_SUCCESS(vosStatus) && (VOS_STATUS_E_ALREADY != vosStatus) )
{
pmcLog(pMac, LOGP, FL("Cannot start traffic timer"));
return;
}
}
}
/******************************************************************************
*
* Name: pmcExitPowerSaveTimerExpired
*
* Description:
* Called when timer used to schedule a deferred power save mode exit expires.
*
* Parameters:
* hHal - HAL handle for device
*
* Returns:
* nothing
*
******************************************************************************/
void pmcExitPowerSaveTimerExpired (tHalHandle hHal)
{
tpAniSirGlobal pMac = PMAC_STRUCT(hHal);
pmcLog(pMac, LOG2, FL("Entering pmcExitPowerSaveTimerExpired"));
/* Make sure process of exiting power save mode might hasn't already been started due to another trigger. */
if (pMac->pmc.requestFullPowerPending)
/* Start on the path of going back to full power. */
pmcEnterRequestFullPowerState(hHal, pMac->pmc.requestFullPowerReason);
}
/******************************************************************************
*
* Name: pmcDoBmpsCallbacks
*
* Description:
* Call the registered BMPS callback routines because device is unable to
* enter BMPS state
*
* Parameters:
* hHal - HAL handle for device
* callbackStatus - Success or Failure.
*
* Returns:
* nothing
*
******************************************************************************/
void pmcDoBmpsCallbacks (tHalHandle hHal, eHalStatus callbackStatus)
{
tpAniSirGlobal pMac = PMAC_STRUCT(hHal);
tListElem *pEntry;
tpRequestBmpsEntry pRequestBmpsEntry;
pmcLog(pMac, LOG2, "PMC: entering pmcDoBmpsCallbacks");
/* Call the routines in the request BMPS callback routine list. */
csrLLLock(&pMac->pmc.requestBmpsList);
pEntry = csrLLRemoveHead(&pMac->pmc.requestBmpsList, FALSE);
while (pEntry != NULL)
{
pRequestBmpsEntry = GET_BASE_ADDR(pEntry, tRequestBmpsEntry, link);
if (pRequestBmpsEntry->callbackRoutine)
pRequestBmpsEntry->callbackRoutine(pRequestBmpsEntry->callbackContext,
callbackStatus);
palFreeMemory(pMac->hHdd, pRequestBmpsEntry);
pEntry = csrLLRemoveHead(&pMac->pmc.requestBmpsList, FALSE);
}
csrLLUnlock(&pMac->pmc.requestBmpsList);
}
/******************************************************************************
*
* Name: pmcDoStartUapsdCallbacks
*
* Description:
* Call the registered UAPSD callback routines because device is unable to
* start UAPSD state
*
* Parameters:
* hHal - HAL handle for device
* callbackStatus - Success or Failure.
*
* Returns:
* nothing
*
******************************************************************************/
void pmcDoStartUapsdCallbacks (tHalHandle hHal, eHalStatus callbackStatus)
{
tpAniSirGlobal pMac = PMAC_STRUCT(hHal);
tListElem *pEntry;
tpStartUapsdEntry pStartUapsdEntry;
pmcLog(pMac, LOG2, "PMC: entering pmcDoStartUapsdCallbacks");
csrLLLock(&pMac->pmc.requestStartUapsdList);
/* Call the routines in the request start UAPSD callback routine list. */
pEntry = csrLLRemoveHead(&pMac->pmc.requestStartUapsdList, FALSE);
while (pEntry != NULL)
{
pStartUapsdEntry = GET_BASE_ADDR(pEntry, tStartUapsdEntry, link);
pStartUapsdEntry->callbackRoutine(pStartUapsdEntry->callbackContext,
callbackStatus);
palFreeMemory(pMac->hHdd, pStartUapsdEntry);
pEntry = csrLLRemoveHead(&pMac->pmc.requestStartUapsdList, FALSE);
}
csrLLUnlock(&pMac->pmc.requestStartUapsdList);
}
/******************************************************************************
*
* Name: pmcEnterRequestStartUapsdState
*
* Description:
* Have the device enter the UAPSD State.
*
* Parameters:
* hHal - HAL handle for device
*
* Returns:
* eHAL_STATUS_SUCCESS - changing state successful
* eHAL_STATUS_FAILURE - changing state not successful
*
******************************************************************************/
eHalStatus pmcEnterRequestStartUapsdState (tHalHandle hHal)
{
tpAniSirGlobal pMac = PMAC_STRUCT(hHal);
v_BOOL_t fFullPower = VOS_FALSE; //need to get back to full power state
pmcLog(pMac, LOG2, "PMC: entering pmcEnterRequestStartUapsdState");
/* Can enter UAPSD State only from FULL_POWER or BMPS State. */
switch (pMac->pmc.pmcState)
{
case FULL_POWER:
/* Check that entry into a power save mode is allowed at this time. */
if (!pmcPowerSaveCheck(hHal))
{
pmcLog(pMac, LOGW, "PMC: Power save check failed. UAPSD request "
"will be accepted and buffered");
/* UAPSD mode will be attempted when we enter BMPS later */
pMac->pmc.uapsdSessionRequired = TRUE;
/* Make sure the BMPS retry timer is running */
if(pmcShouldBmpsTimerRun(pMac))
(void)pmcStartTrafficTimer(hHal, pMac->pmc.bmpsConfig.trafficMeasurePeriod);
break;
}
else
{
pMac->pmc.uapsdSessionRequired = TRUE;
//Check BTC state
#ifndef WLAN_MDM_CODE_REDUCTION_OPT
if( btcIsReadyForUapsd( pMac ) )
#endif /* WLAN_MDM_CODE_REDUCTION_OPT*/
{
/* Put device in BMPS mode first. This step should NEVER fail.
That is why no need to buffer the UAPSD request*/
if(pmcEnterRequestBmpsState(hHal) != eHAL_STATUS_SUCCESS)
{
pmcLog(pMac, LOGE, "PMC: Device in Full Power. Enter Request Bmps failed. "
"UAPSD request will be dropped ");
return eHAL_STATUS_FAILURE;
}
}
#ifndef WLAN_MDM_CODE_REDUCTION_OPT
else
{
(void)pmcStartTrafficTimer(hHal, pMac->pmc.bmpsConfig.trafficMeasurePeriod);
}
#endif /* WLAN_MDM_CODE_REDUCTION_OPT*/
}
break;
case BMPS:
//It is already in BMPS mode, check BTC state
#ifndef WLAN_MDM_CODE_REDUCTION_OPT
if( btcIsReadyForUapsd(pMac) )
#endif /* WLAN_MDM_CODE_REDUCTION_OPT*/
{
/* Tell MAC to have device enter UAPSD mode. */
if (pmcIssueCommand(hHal, eSmeCommandEnterUapsd, NULL, 0, FALSE) !=
eHAL_STATUS_SUCCESS)
{
pmcLog(pMac, LOGE, "PMC: failure to send message "
"eWNI_PMC_ENTER_BMPS_REQ");
return eHAL_STATUS_FAILURE;
}
}
#ifndef WLAN_MDM_CODE_REDUCTION_OPT
else
{
//Not ready for UAPSD at this time, save it first and wake up the chip
pmcLog(pMac, LOGE, " PMC state = %d",pMac->pmc.pmcState);
pMac->pmc.uapsdSessionRequired = TRUE;
/* While BTC traffic is going on, STA can be in BMPS
* and need not go to Full Power */
//fFullPower = VOS_TRUE;
}
#endif /* WLAN_MDM_CODE_REDUCTION_OPT*/
break;
case REQUEST_START_UAPSD:
#ifndef WLAN_MDM_CODE_REDUCTION_OPT
if( !btcIsReadyForUapsd(pMac) )
{
//BTC rejects UAPSD, bring it back to full power
fFullPower = VOS_TRUE;
}
#endif
break;
case REQUEST_BMPS:
/* Buffer request for UAPSD mode. */
pMac->pmc.uapsdSessionRequired = TRUE;
#ifndef WLAN_MDM_CODE_REDUCTION_OPT
if( !btcIsReadyForUapsd(pMac) )
{
//BTC rejects UAPSD, bring it back to full power
fFullPower = VOS_TRUE;
}
#endif /* WLAN_MDM_CODE_REDUCTION_OPT*/
break;
default:
pmcLog(pMac, LOGE, "PMC: trying to enter UAPSD State from state %d",
pMac->pmc.pmcState);
return eHAL_STATUS_FAILURE;
}
if(fFullPower)
{
if( eHAL_STATUS_PMC_PENDING != pmcRequestFullPower( pMac, NULL, NULL, eSME_REASON_OTHER ) )
{
//This is an error
pmcLog(pMac, LOGE, FL(" fail to request full power because BTC"));
}
}
return eHAL_STATUS_SUCCESS;
}
/******************************************************************************
*
* Name: pmcEnterUapsdState
*
* Description:
* Have the device enter the UAPSD State.
*
* Parameters:
* hHal - HAL handle for device
*
* Returns:
* eHAL_STATUS_SUCCESS - changing state successful
* eHAL_STATUS_FAILURE - changing state not successful
*
******************************************************************************/
eHalStatus pmcEnterUapsdState (tHalHandle hHal)
{
tpAniSirGlobal pMac = PMAC_STRUCT(hHal);
pmcLog(pMac, LOG2, "PMC: entering pmcEnterUapsdState");
/* Can enter UAPSD State only from Request UAPSD State. */
if (pMac->pmc.pmcState != REQUEST_START_UAPSD )
{
pmcLog(pMac, LOGE, "PMC: trying to enter UAPSD State from state %d",
pMac->pmc.pmcState);
return eHAL_STATUS_FAILURE;
}
/* Change state. */
pMac->pmc.pmcState = UAPSD;
/* Update registerd modules that we are entering UAPSD. This is
only way to inform modules if PMC resumed UAPSD power save mode
on its own after full power mode */
pmcDoDeviceStateUpdateCallbacks(hHal, UAPSD);
/* If we have a reqeust for full power pending then we have to go
directly into full power. */
if (pMac->pmc.requestFullPowerPending)
{
/* Start exit UAPSD sequence now. */
return pmcEnterRequestFullPowerState(hHal, pMac->pmc.requestFullPowerReason);
}
return eHAL_STATUS_SUCCESS;
}
/******************************************************************************
*
* Name: pmcEnterRequestStopUapsdState
*
* Description:
* Have the device Stop the UAPSD State.
*
* Parameters:
* hHal - HAL handle for device
*
* Returns:
* eHAL_STATUS_SUCCESS - changing state successful
* eHAL_STATUS_FAILURE - changing state not successful
*
******************************************************************************/
eHalStatus pmcEnterRequestStopUapsdState (tHalHandle hHal)
{
tpAniSirGlobal pMac = PMAC_STRUCT(hHal);
pmcLog(pMac, LOG2, "PMC: entering pmcEnterRequestStopUapsdState");
/* If already in REQUEST_STOP_UAPSD, simply return */
if (pMac->pmc.pmcState == REQUEST_STOP_UAPSD)
{
return eHAL_STATUS_SUCCESS;
}
/* Can enter Request Stop UAPSD State only from UAPSD */
if (pMac->pmc.pmcState != UAPSD)
{
pmcLog(pMac, LOGE, "PMC: trying to enter Request Stop UAPSD State from "
"state %d", pMac->pmc.pmcState);
return eHAL_STATUS_FAILURE;
}
/* Tell MAC to have device exit UAPSD mode. */
if (pmcIssueCommand(hHal, eSmeCommandExitUapsd, NULL, 0, FALSE) !=
eHAL_STATUS_SUCCESS)
{
pmcLog(pMac, LOGE, "PMC: failure to send message "
"eWNI_PMC_EXIT_UAPSD_REQ");
return eHAL_STATUS_FAILURE;
}
return eHAL_STATUS_SUCCESS;
}
/******************************************************************************
*
* Name: pmcEnterRequestStandbyState
*
* Description:
* Have the device enter the Request STANDBY State.
*
* Parameters:
* hHal - HAL handle for device
*
* Returns:
* eHAL_STATUS_SUCCESS - changing state successful
* eHAL_STATUS_FAILURE - changing state not successful
*
******************************************************************************/
eHalStatus pmcEnterRequestStandbyState (tHalHandle hHal)
{
tpAniSirGlobal pMac = PMAC_STRUCT(hHal);
pmcLog(pMac, LOG2, "PMC: entering pmcEnterRequestStandbyState");
/* Can enter Standby State only from Full Power State. */
if (pMac->pmc.pmcState != FULL_POWER)
{
pmcLog(pMac, LOGE, "PMC: trying to enter Standby State from "
"state %d", pMac->pmc.pmcState);
return eHAL_STATUS_FAILURE;
}
// Stop traffic timer. Just making sure timer is not running
pmcStopTrafficTimer(hHal);
/* Tell MAC to have device enter STANDBY mode. We are using the same message
as IMPS mode to avoid code changes in layer below (PE/HAL)*/
if (pmcIssueCommand(hHal, eSmeCommandEnterStandby, NULL, 0, FALSE) !=
eHAL_STATUS_SUCCESS)
{
pmcLog(pMac, LOGE, "PMC: failure to send message "
"eWNI_PMC_ENTER_IMPS_REQ");
pMac->pmc.pmcState = FULL_POWER;
if(pmcShouldBmpsTimerRun(pMac))
(void)pmcStartTrafficTimer(hHal, pMac->pmc.bmpsConfig.trafficMeasurePeriod);
return eHAL_STATUS_FAILURE;
}
return eHAL_STATUS_SUCCESS;
}
/******************************************************************************
*
* Name: pmcEnterStandbyState
*
* Description:
* Have the device enter the STANDBY State.
*
* Parameters:
* hHal - HAL handle for device
*
* Returns:
* eHAL_STATUS_SUCCESS - changing state successful
* eHAL_STATUS_FAILURE - changing state not successful
*
******************************************************************************/
eHalStatus pmcEnterStandbyState (tHalHandle hHal)
{
tpAniSirGlobal pMac = PMAC_STRUCT(hHal);
vos_call_status_type callType;
VOS_STATUS status;
pmcLog(pMac, LOG2, "PMC: entering pmcEnterStandbyState");
/* Can enter STANDBY State only from REQUEST_STANDBY State. */
if (pMac->pmc.pmcState != REQUEST_STANDBY)
{
pmcLog(pMac, LOGE, "PMC: trying to enter STANDBY State from state %d",
pMac->pmc.pmcState);
return eHAL_STATUS_FAILURE;
}
/* Change state. */
pMac->pmc.pmcState = STANDBY;
/* If we have a reqeust for full power pending then we have to go
directly into full power. */
if (pMac->pmc.requestFullPowerPending)
{
/* Start exit STANDBY sequence now. */
return pmcEnterRequestFullPowerState(hHal, pMac->pmc.requestFullPowerReason);
}
//Note that RF supplies are not voted off if there is already a pending request
//for full power
status = vos_chipVoteOffRFSupply(&callType, NULL, NULL);
VOS_ASSERT( VOS_IS_STATUS_SUCCESS( status ) );
status = vos_chipVoteOffXOBuffer(&callType, NULL, NULL);
VOS_ASSERT( VOS_IS_STATUS_SUCCESS( status ) );
pMac->pmc.rfSuppliesVotedOff= TRUE;
return eHAL_STATUS_SUCCESS;
}
/******************************************************************************
*
* Name: pmcDoStandbyCallbacks
*
* Description:
* Call the registered Standby callback routines
*
* Parameters:
* hHal - HAL handle for device
* callbackStatus - Success or Failure.
*
* Returns:
* nothing
*
******************************************************************************/
void pmcDoStandbyCallbacks (tHalHandle hHal, eHalStatus callbackStatus)
{
tpAniSirGlobal pMac = PMAC_STRUCT(hHal);
pmcLog(pMac, LOG2, "PMC: entering pmcDoStandbyCallbacks");
/* Call Standby callback routine. */
if (pMac->pmc.standbyCallbackRoutine != NULL)
pMac->pmc.standbyCallbackRoutine(pMac->pmc.standbyCallbackContext, callbackStatus);
pMac->pmc.standbyCallbackRoutine = NULL;
pMac->pmc.standbyCallbackContext = NULL;
}
/******************************************************************************
*
* Name: pmcGetPmcState
*
* Description:
* Return the PMC state
*
* Parameters:
* hHal - HAL handle for device
*
* Returns:
* tPmcState (one of IMPS, REQUEST_IMPS, BMPS, REQUEST_BMPS etc)
*
******************************************************************************/
tPmcState pmcGetPmcState (tHalHandle hHal)
{
tpAniSirGlobal pMac = PMAC_STRUCT(hHal);
return pMac->pmc.pmcState;
}
const char* pmcGetPmcStateStr(tPmcState state)
{
switch(state)
{
case STOPPED:
return "STOPPED";
case FULL_POWER:
return "FULL_POWER";
case LOW_POWER:
return "LOW_POWER";
case IMPS:
return "IMPS";
case BMPS:
return "BMPS";
case UAPSD:
return "UAPSD";
case STANDBY:
return "STANDBY";
case REQUEST_IMPS:
return "REQUEST_IMPS";
case REQUEST_BMPS:
return "REQUEST_BMPS";
case REQUEST_START_UAPSD:
return "REQUEST_START_UAPSD";
case REQUEST_STOP_UAPSD:
return "REQUEST_STOP_UAPSD";
case REQUEST_FULL_POWER:
return "REQUEST_FULL_POWER";
case REQUEST_STANDBY:
return "REQUEST_STANDBY";
case REQUEST_ENTER_WOWL:
return "REQUEST_ENTER_WOWL";
case REQUEST_EXIT_WOWL:
return "REQUEST_EXIT_WOWL";
case WOWL:
return "WOWL";
default:
break;
}
return "UNKNOWN";
}
void pmcDoDeviceStateUpdateCallbacks (tHalHandle hHal, tPmcState state)
{
tpAniSirGlobal pMac = PMAC_STRUCT(hHal);
tListElem *pEntry;
tpDeviceStateUpdateIndEntry pDeviceStateUpdateIndEntry;
void (*callbackRoutine) (void *callbackContext, tPmcState pmcState);
pmcLog(pMac, LOG2, FL("PMC - Update registered modules of new device "
"state: %s"), pmcGetPmcStateStr(state));
/* Call the routines in the update device state routine list. */
pEntry = csrLLPeekHead(&pMac->pmc.deviceStateUpdateIndList, FALSE);
while (pEntry != NULL)
{
pDeviceStateUpdateIndEntry = GET_BASE_ADDR(pEntry, tDeviceStateUpdateIndEntry, link);
callbackRoutine = pDeviceStateUpdateIndEntry->callbackRoutine;
callbackRoutine(pDeviceStateUpdateIndEntry->callbackContext, state);
pEntry = csrLLNext(&pMac->pmc.deviceStateUpdateIndList, pEntry, FALSE);
}
}
/******************************************************************************
*
* Name: pmcRequestEnterWowlState
*
* Description:
* Have the device enter the WOWL State.
*
* Parameters:
* hHal - HAL handle for device
*
* Returns:
* eHAL_STATUS_SUCCESS - WOWL mode will be entered
* eHAL_STATUS_FAILURE - WOWL mode cannot be entered
*
******************************************************************************/
eHalStatus pmcRequestEnterWowlState(tHalHandle hHal, tpSirSmeWowlEnterParams wowlEnterParams)
{
tpAniSirGlobal pMac = PMAC_STRUCT(hHal);
pmcLog(pMac, LOG2, "PMC: entering pmcRequestEnterWowlState");
switch (pMac->pmc.pmcState)
{
case FULL_POWER:
/* Put device in BMPS mode first. This step should NEVER fail. */
if(pmcEnterRequestBmpsState(hHal) != eHAL_STATUS_SUCCESS)
{
pmcLog(pMac, LOGE, "PMC: Device in Full Power. pmcEnterRequestBmpsState failed. "
"Cannot enter WOWL");
return eHAL_STATUS_FAILURE;
}
break;
case REQUEST_BMPS:
pmcLog(pMac, LOGW, "PMC: BMPS transaction going on. WOWL request "
"will be buffered");
break;
case BMPS:
case WOWL:
/* Tell MAC to have device enter WOWL mode. Note: We accept WOWL request
when we are in WOWL mode. This allows HDD to change WOWL configuration
without having to exit WOWL mode */
if (pmcIssueCommand(hHal, eSmeCommandEnterWowl, wowlEnterParams, sizeof(tSirSmeWowlEnterParams), FALSE) !=
eHAL_STATUS_SUCCESS)
{
pmcLog(pMac, LOGE, "PMC: failure to send message eWNI_PMC_ENTER_WOWL_REQ");
return eHAL_STATUS_FAILURE;
}
break;
case REQUEST_ENTER_WOWL:
//Multiple enter WOWL requests at the same time are not accepted
pmcLog(pMac, LOGE, "PMC: Enter WOWL transaction already going on. New WOWL request "
"will be rejected");
return eHAL_STATUS_FAILURE;
case REQUEST_EXIT_WOWL:
pmcLog(pMac, LOGW, "PMC: Exit WOWL transaction going on. New WOWL request "
"will be buffered");
break;
default:
pmcLog(pMac, LOGE, "PMC: Trying to enter WOWL State from state %s",
pmcGetPmcStateStr(pMac->pmc.pmcState));
return eHAL_STATUS_FAILURE;
}
return eHAL_STATUS_SUCCESS;
}
/******************************************************************************
*
* Name: pmcEnterWowlState
*
* Description:
* Have the device enter the WOWL State.
*
* Parameters:
* hHal - HAL handle for device
*
* Returns:
* eHAL_STATUS_SUCCESS - changing state successful
* eHAL_STATUS_FAILURE - changing state not successful
*
******************************************************************************/
eHalStatus pmcEnterWowlState (tHalHandle hHal)
{
tpAniSirGlobal pMac = PMAC_STRUCT(hHal);
pmcLog(pMac, LOG2, "PMC: entering pmcEnterWowlState");
/* Can enter WOWL State only from Request WOWL State. */
if (pMac->pmc.pmcState != REQUEST_ENTER_WOWL )
{
pmcLog(pMac, LOGP, "PMC: trying to enter WOWL State from state %d",
pMac->pmc.pmcState);
return eHAL_STATUS_FAILURE;
}
/* Change state. */
pMac->pmc.pmcState = WOWL;
/* Clear the buffered command for WOWL */
pMac->pmc.wowlModeRequired = FALSE;
/* If we have a reqeust for full power pending then we have to go
directly into full power. */
if (pMac->pmc.requestFullPowerPending)
{
/* Start exit Wowl sequence now. */
return pmcEnterRequestFullPowerState(hHal, pMac->pmc.requestFullPowerReason);
}
return eHAL_STATUS_SUCCESS;
}
/******************************************************************************
*
* Name: pmcRequestExitWowlState
*
* Description:
* Have the device exit WOWL State.
*
* Parameters:
* hHal - HAL handle for device
*
* Returns:
* eHAL_STATUS_SUCCESS - Exit WOWL successful
* eHAL_STATUS_FAILURE - Exit WOWL unsuccessful
*
******************************************************************************/
eHalStatus pmcRequestExitWowlState(tHalHandle hHal)
{
tpAniSirGlobal pMac = PMAC_STRUCT(hHal);
pmcLog(pMac, LOG2, "PMC: entering pmcRequestExitWowlState");
switch (pMac->pmc.pmcState)
{
case WOWL:
/* Tell MAC to have device exit WOWL mode. */
if (pmcIssueCommand(hHal, eSmeCommandExitWowl, NULL, 0, FALSE) !=
eHAL_STATUS_SUCCESS)
{
pmcLog(pMac, LOGP, "PMC: failure to send message eWNI_PMC_EXIT_WOWL_REQ");
return eHAL_STATUS_FAILURE;
}
break;
case REQUEST_ENTER_WOWL:
pmcLog(pMac, LOGP, "PMC: Rcvd exit WOWL even before enter WOWL was completed");
return eHAL_STATUS_FAILURE;
default:
pmcLog(pMac, LOGW, "PMC: Got exit WOWL in state %s. Nothing to do as already out of WOWL",
pmcGetPmcStateStr(pMac->pmc.pmcState));
break;
}
return eHAL_STATUS_SUCCESS;
}
/******************************************************************************
*
* Name: pmcDoEnterWowlCallbacks
*
* Description:
* Invoke Enter WOWL callbacks
*
* Parameters:
* hHal - HAL handle for device
*
* Returns: None
*
******************************************************************************/
void pmcDoEnterWowlCallbacks (tHalHandle hHal, eHalStatus callbackStatus)
{
tpAniSirGlobal pMac = PMAC_STRUCT(hHal);
pmcLog(pMac, LOG2, "PMC: entering pmcDoWowlCallbacks");
/* Call Wowl callback routine. */
if (pMac->pmc.enterWowlCallbackRoutine != NULL)
pMac->pmc.enterWowlCallbackRoutine(pMac->pmc.enterWowlCallbackContext, callbackStatus);
pMac->pmc.enterWowlCallbackRoutine = NULL;
pMac->pmc.enterWowlCallbackContext = NULL;
}
static void pmcProcessDeferredMsg( tpAniSirGlobal pMac )
{
tPmcDeferredMsg *pDeferredMsg;
tListElem *pEntry;
while( NULL != ( pEntry = csrLLRemoveHead( &pMac->pmc.deferredMsgList, eANI_BOOLEAN_TRUE ) ) )
{
pDeferredMsg = GET_BASE_ADDR( pEntry, tPmcDeferredMsg, link );
switch (pDeferredMsg->messageType)
{
case eWNI_PMC_WOWL_ADD_BCAST_PTRN:
VOS_ASSERT( pDeferredMsg->size == sizeof(tSirWowlAddBcastPtrn) );
if (pmcSendMessage(pMac, eWNI_PMC_WOWL_ADD_BCAST_PTRN,
&pDeferredMsg->u.wowlAddPattern, sizeof(tSirWowlAddBcastPtrn))
!= eHAL_STATUS_SUCCESS)
{
pmcLog(pMac, LOGE, FL("Send of eWNI_PMC_WOWL_ADD_BCAST_PTRN to PE failed"));
}
break;
case eWNI_PMC_WOWL_DEL_BCAST_PTRN:
VOS_ASSERT( pDeferredMsg->size == sizeof(tSirWowlDelBcastPtrn) );
if (pmcSendMessage(pMac, eWNI_PMC_WOWL_DEL_BCAST_PTRN,
&pDeferredMsg->u.wowlDelPattern, sizeof(tSirWowlDelBcastPtrn))
!= eHAL_STATUS_SUCCESS)
{
pmcLog(pMac, LOGE, FL("Send of eWNI_PMC_WOWL_ADD_BCAST_PTRN to PE failed"));
}
break;
case eWNI_PMC_PWR_SAVE_CFG:
VOS_ASSERT( pDeferredMsg->size == sizeof(tSirPowerSaveCfg) );
if (pmcSendMessage(pMac, eWNI_PMC_PWR_SAVE_CFG,
&pDeferredMsg->u.powerSaveConfig, sizeof(tSirPowerSaveCfg))
!= eHAL_STATUS_SUCCESS)
{
pmcLog(pMac, LOGE, FL("Send of eWNI_PMC_PWR_SAVE_CFG to PE failed"));
}
break;
default:
pmcLog(pMac, LOGE, FL("unknown message (%d)"), pDeferredMsg->messageType);
break;
}
//Need to free the memory here
palFreeMemory( pMac->hHdd, pDeferredMsg );
} //while
}
eHalStatus pmcDeferMsg( tpAniSirGlobal pMac, tANI_U16 messageType, void *pData, tANI_U32 size)
{
tPmcDeferredMsg *pDeferredMsg;
eHalStatus status;
if( !HAL_STATUS_SUCCESS( palAllocateMemory( pMac->hHdd, (void **)&pDeferredMsg, sizeof(tPmcDeferredMsg) ) ) )
{
pmcLog(pMac, LOGE, FL("Cannot allocate memory for callback context"));
return eHAL_STATUS_RESOURCES;
}
palZeroMemory( pMac->hHdd, pDeferredMsg, sizeof(tPmcDeferredMsg) );
pDeferredMsg->messageType = messageType;
pDeferredMsg->size = (tANI_U16)size;
if( pData )
{
if( !HAL_STATUS_SUCCESS( palCopyMemory( pMac->hHdd, &pDeferredMsg->u.data,
pData, size ) ) )
{
pmcLog(pMac, LOGE, FL("Cannot copy pattern for callback context"));
palFreeMemory( pMac->hHdd, pDeferredMsg );
return eHAL_STATUS_FAILURE;
}
}
csrLLInsertTail( &pMac->pmc.deferredMsgList, &pDeferredMsg->link, eANI_BOOLEAN_TRUE );
//No callback is needed. The messages are put into deferred queue and be processed first
//when enter full power is complete.
status = pmcRequestFullPower( pMac, NULL, NULL, eSME_REASON_OTHER );
if( eHAL_STATUS_PMC_PENDING != status )
{
//either fail or already in full power
if( csrLLRemoveEntry( &pMac->pmc.deferredMsgList, &pDeferredMsg->link, eANI_BOOLEAN_TRUE ) )
{
palFreeMemory( pMac->hHdd, pDeferredMsg );
}
if( !HAL_STATUS_SUCCESS( status ) )
{
pmcLog(pMac, LOGE, FL("failed to request full power status = %d"), status);
}
}
return (status);
}
void pmcReleaseCommand( tpAniSirGlobal pMac, tSmeCmd *pCommand )
{
if(!pCommand->u.pmcCmd.fReleaseWhenDone)
{
//This is a normal command, put it back to the free lsit
pCommand->u.pmcCmd.size = 0;
smeReleaseCommand( pMac, pCommand );
}
else
{
//this is a specially allocated comamnd due to out of command buffer. free it.
palFreeMemory(pMac->hHdd, pCommand);
}
}
//this function is used to abort a command where the normal processing of the command
//is terminated without going through the normal path. it is here to take care of callbacks for
//the command, if applicable.
void pmcAbortCommand( tpAniSirGlobal pMac, tSmeCmd *pCommand, tANI_BOOLEAN fStopping )
{
if( eSmePmcCommandMask & pCommand->command )
{
if( !fStopping )
{
switch( pCommand->command )
{
case eSmeCommandEnterImps:
pmcLog(pMac, LOGE, FL("aborting request to enter IMPS"));
pmcEnterFullPowerState(pMac);
break;
case eSmeCommandExitImps:
pmcLog(pMac, LOGE, FL("aborting request to exit IMPS "));
pmcEnterFullPowerState(pMac);
break;
case eSmeCommandEnterBmps:
pmcLog(pMac, LOGE, FL("aborting request to enter BMPS "));
pMac->pmc.bmpsRequestQueued = eANI_BOOLEAN_FALSE;
pmcEnterFullPowerState(pMac);
pmcDoBmpsCallbacks(pMac, eHAL_STATUS_FAILURE);
break;
case eSmeCommandExitBmps:
pmcLog(pMac, LOGE, FL("aborting request to exit BMPS "));
pmcEnterFullPowerState(pMac);
break;
case eSmeCommandEnterUapsd:
pmcLog(pMac, LOGE, FL("aborting request to enter UAPSD "));
//Since there is no retry for UAPSD, tell the requester here we are done with failure
pMac->pmc.uapsdSessionRequired = FALSE;
pmcDoStartUapsdCallbacks(pMac, eHAL_STATUS_FAILURE);
break;
case eSmeCommandExitUapsd:
pmcLog(pMac, LOGE, FL("aborting request to exit UAPSD "));
break;
case eSmeCommandEnterWowl:
pmcLog(pMac, LOGE, FL("aborting request to enter WOWL "));
pmcDoEnterWowlCallbacks(pMac, eHAL_STATUS_FAILURE);
break;
case eSmeCommandExitWowl:
pmcLog(pMac, LOGE, FL("aborting request to exit WOWL "));
break;
case eSmeCommandEnterStandby:
pmcLog(pMac, LOGE, FL("aborting request to enter Standby "));
pmcDoStandbyCallbacks(pMac, eHAL_STATUS_FAILURE);
break;
default:
pmcLog(pMac, LOGE, FL("Request for PMC command (%d) is dropped"), pCommand->command);
break;
}
}// !stopping
pmcReleaseCommand( pMac, pCommand );
}
}
//These commands are not supposed to fail due to out of command buffer,
//otherwise other commands are not executed and no command is released. It will be deadlock.
#define PMC_IS_COMMAND_CANNOT_FAIL(cmdType)\
( (eSmeCommandEnterStandby == (cmdType )) ||\
(eSmeCommandExitImps == (cmdType )) ||\
(eSmeCommandExitBmps == (cmdType )) ||\
(eSmeCommandExitUapsd == (cmdType )) ||\
(eSmeCommandExitWowl == (cmdType )) )
eHalStatus pmcPrepareCommand( tpAniSirGlobal pMac, eSmeCommandType cmdType, void *pvParam,
tANI_U32 size, tSmeCmd **ppCmd )
{
eHalStatus status = eHAL_STATUS_RESOURCES;
tSmeCmd *pCommand = NULL;
VOS_ASSERT( ppCmd );
do
{
pCommand = smeGetCommandBuffer( pMac );
if ( pCommand )
{
//Make sure it will be put back to the list
pCommand->u.pmcCmd.fReleaseWhenDone = FALSE;
}
else
{
pmcLog( pMac, LOGE,
FL(" fail to get command buffer for command 0x%X curState = %d"), cmdType, pMac->pmc.pmcState );
//For certain PMC command, we cannot fail
if( PMC_IS_COMMAND_CANNOT_FAIL(cmdType) )
{
pmcLog( pMac, LOGE,
FL(" command 0x%X cannot fail try allocating memory for it"), cmdType );
status = palAllocateMemory(pMac->hHdd, (void **)&pCommand, sizeof(tSmeCmd));
if(!HAL_STATUS_SUCCESS(status))
{
VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_FATAL, "%s fail to allocate memory for command (0x%X)",
__func__, cmdType);
pCommand = NULL;
break;
}
palZeroMemory(pMac->hHdd, pCommand, sizeof(tSmeCmd));
//Make sure it will be free when it is done
pCommand->u.pmcCmd.fReleaseWhenDone = TRUE;
}
else
{
break;
}
}
pCommand->command = cmdType;
pCommand->u.pmcCmd.size = size;
//Initialize the reason code here. It may be overwritten later when
//a particular reason is needed.
pCommand->u.pmcCmd.fullPowerReason = eSME_REASON_OTHER;
switch ( cmdType )
{
case eSmeCommandEnterImps:
case eSmeCommandExitImps:
case eSmeCommandEnterBmps:
case eSmeCommandEnterUapsd:
case eSmeCommandEnterStandby:
status = eHAL_STATUS_SUCCESS;
break;
case eSmeCommandExitUapsd:
case eSmeCommandExitWowl:
status = eHAL_STATUS_SUCCESS;
if( pvParam )
{
pCommand->u.pmcCmd.fullPowerReason = *( (tRequestFullPowerReason *)pvParam );
}
break;
case eSmeCommandExitBmps:
status = eHAL_STATUS_SUCCESS;
if( pvParam )
{
pCommand->u.pmcCmd.u.exitBmpsInfo = *( (tExitBmpsInfo *)pvParam );
pCommand->u.pmcCmd.fullPowerReason = pCommand->u.pmcCmd.u.exitBmpsInfo.exitBmpsReason;
}
else
{
pmcLog( pMac, LOGE, (" exit BMPS must have a reason code") );
}
break;
case eSmeCommandEnterWowl:
status = eHAL_STATUS_SUCCESS;
if( pvParam )
{
pCommand->u.pmcCmd.u.enterWowlInfo = *( ( tSirSmeWowlEnterParams * )pvParam );
}
break;
default:
pmcLog( pMac, LOGE, FL(" invalid command type %d"), cmdType );
status = eHAL_STATUS_INVALID_PARAMETER;
break;
}
} while( 0 );
if( HAL_STATUS_SUCCESS( status ) && pCommand )
{
*ppCmd = pCommand;
}
else if( pCommand )
{
pmcReleaseCommand( pMac, pCommand );
}
return (status);
}
eHalStatus pmcIssueCommand( tpAniSirGlobal pMac, eSmeCommandType cmdType, void *pvParam,
tANI_U32 size, tANI_BOOLEAN fPutToListHead )
{
eHalStatus status = eHAL_STATUS_RESOURCES;
tSmeCmd *pCommand = NULL;
status = pmcPrepareCommand( pMac, cmdType, pvParam, size, &pCommand );
if( HAL_STATUS_SUCCESS( status ) && pCommand )
{
smePushCommand( pMac, pCommand, fPutToListHead );
}
else if( pCommand )
{
pmcReleaseCommand( pMac, pCommand );
}
return( status );
}
tANI_BOOLEAN pmcProcessCommand( tpAniSirGlobal pMac, tSmeCmd *pCommand )
{
eHalStatus status = eHAL_STATUS_SUCCESS;
VOS_STATUS vstatus;
tANI_BOOLEAN fRemoveCmd = eANI_BOOLEAN_TRUE;
do
{
switch ( pCommand->command )
{
case eSmeCommandEnterImps:
if( FULL_POWER == pMac->pmc.pmcState )
{
status = pmcEnterImpsCheck( pMac );
if( HAL_STATUS_SUCCESS( status ) )
{
/* Change state. */
pMac->pmc.pmcState = REQUEST_IMPS;
status = pmcSendMessage(pMac, eWNI_PMC_ENTER_IMPS_REQ, NULL, 0);
if( HAL_STATUS_SUCCESS( status ) )
{
/* If we already went back Full Power State (meaning that request did not
get as far as the device) then we are not successfull. */
if ( FULL_POWER != pMac->pmc.pmcState )
{
fRemoveCmd = eANI_BOOLEAN_FALSE;
}
}
}
if( !HAL_STATUS_SUCCESS( status ) )
{
pmcLog(pMac, LOGE,
"PMC: failure to send message eWNI_PMC_ENTER_IMPS_REQ or pmcEnterImpsCheck failed");
pmcEnterFullPowerState( pMac );
if(pmcShouldBmpsTimerRun(pMac))
(void)pmcStartTrafficTimer(pMac, pMac->pmc.bmpsConfig.trafficMeasurePeriod);
}
}//full_power
break;
case eSmeCommandExitImps:
pMac->pmc.requestFullPowerPending = FALSE;
if( ( IMPS == pMac->pmc.pmcState ) || ( STANDBY == pMac->pmc.pmcState ) )
{
//Check state before sending message. The state may change after that
if( STANDBY == pMac->pmc.pmcState )
{
//Enable Idle scan in CSR
csrScanResumeIMPS(pMac);
}
status = pmcSendMessage(pMac, eWNI_PMC_EXIT_IMPS_REQ, NULL, 0);
if ( HAL_STATUS_SUCCESS( status ) )
{
pMac->pmc.pmcState = REQUEST_FULL_POWER;
pmcLog(pMac, LOG2, FL("eWNI_PMC_EXIT_IMPS_REQ sent to PE"));
fRemoveCmd = eANI_BOOLEAN_FALSE;
}
else
{
pmcLog(pMac, LOGE,
FL("eWNI_PMC_EXIT_IMPS_REQ fail to be sent to PE status %d"), status);
//Callbacks are called with success srarus, do we need to pass in real status??
pmcEnterFullPowerState(pMac);
}
}
break;
case eSmeCommandEnterBmps:
#ifdef CUSTOMER_LGE_DEBUG_LOG
pmcLog(pMac, LOGE, "Request EnterBMPS, PMC Status = %d", pMac->pmc.pmcState);
#endif
if( FULL_POWER == pMac->pmc.pmcState )
{
//This function will not return success because the pmc state is not BMPS
status = pmcEnterBmpsCheck( pMac );
if( HAL_STATUS_SUCCESS( status ) )
{
/* Change PMC state */
pMac->pmc.pmcState = REQUEST_BMPS;
pmcLog(pMac, LOG2, "PMC: Enter BMPS req done: Force XO Core ON");
vstatus = vos_chipVoteXOCore(NULL, NULL, NULL, VOS_TRUE);
if ( !VOS_IS_STATUS_SUCCESS(vstatus) )
{
pmcLog(pMac, LOGE, "Could not turn XO Core ON. Can't go to BMPS");
}
else /* XO Core turn ON was successful */
{
/* Tell MAC to have device enter BMPS mode. */
status = pmcSendMessage(pMac, eWNI_PMC_ENTER_BMPS_REQ, NULL, 0);
if ( HAL_STATUS_SUCCESS( status ) )
{
fRemoveCmd = eANI_BOOLEAN_FALSE;
}
else
{
pmcLog(pMac, LOGE, "Fail to send enter BMPS msg to PE");
/* Cancel the vote for XO Core */
pmcLog(pMac, LOGW, "In module init: Cancel the vote for XO CORE ON "
"since send enter bmps failed");
if (vos_chipVoteXOCore(NULL, NULL, NULL, VOS_FALSE) != VOS_STATUS_SUCCESS)
{
pmcLog(pMac, LOGE, "Could not cancel XO Core ON vote."
"Not returning failure."
"Power consumed will be high");
}
}
}
}
if( !HAL_STATUS_SUCCESS( status ) )
{
pmcLog(pMac, LOGE,
"PMC: failure to send message eWNI_PMC_ENTER_BMPS_REQ status %d", status);
pMac->pmc.bmpsRequestQueued = eANI_BOOLEAN_FALSE;
pmcEnterFullPowerState(pMac);
//Do not call UAPSD callback here since it may be retried
pmcDoBmpsCallbacks(pMac, eHAL_STATUS_FAILURE);
if(pmcShouldBmpsTimerRun(pMac))
(void)pmcStartTrafficTimer(pMac, pMac->pmc.bmpsConfig.trafficMeasurePeriod);
}
}
break;
case eSmeCommandExitBmps:
#ifdef CUSTOMER_LGE_DEBUG_LOG
pmcLog(pMac, LOGE, "Request ExitBMPS, PMC Status = %d", pMac->pmc.pmcState);
#endif
if( BMPS == pMac->pmc.pmcState )
{
pMac->pmc.requestFullPowerPending = FALSE;
status = pmcSendMessage( pMac, eWNI_PMC_EXIT_BMPS_REQ,
&pCommand->u.pmcCmd.u.exitBmpsInfo, sizeof(tExitBmpsInfo) );
if ( HAL_STATUS_SUCCESS( status ) )
{
pMac->pmc.pmcState = REQUEST_FULL_POWER;
fRemoveCmd = eANI_BOOLEAN_FALSE;
pmcLog(pMac, LOG2, FL("eWNI_PMC_EXIT_BMPS_REQ sent to PE"));
}
else
{
pmcLog(pMac, LOGE, FL("eWNI_PMC_EXIT_BMPS_REQ fail to be sent to PE status %d"), status);
pmcEnterFullPowerState(pMac);
}
}
break;
case eSmeCommandEnterUapsd:
if( BMPS == pMac->pmc.pmcState )
{
pMac->pmc.uapsdSessionRequired = TRUE;
status = pmcSendMessage(pMac, eWNI_PMC_ENTER_UAPSD_REQ, NULL, 0);
if ( HAL_STATUS_SUCCESS( status ) )
{
pMac->pmc.pmcState = REQUEST_START_UAPSD;
fRemoveCmd = eANI_BOOLEAN_FALSE;
}
else
{
pmcLog(pMac, LOGE, "PMC: failure to send message "
"eWNI_PMC_ENTER_BMPS_REQ");
//there is no retry for re-entering UAPSD so tell the requester we are done witgh failure.
pMac->pmc.uapsdSessionRequired = FALSE;
pmcDoStartUapsdCallbacks(pMac, eHAL_STATUS_FAILURE);
}
}
break;
case eSmeCommandExitUapsd:
if( UAPSD == pMac->pmc.pmcState )
{
pMac->pmc.requestFullPowerPending = FALSE;
/* If already in REQUEST_STOP_UAPSD, simply return */
if (pMac->pmc.pmcState == REQUEST_STOP_UAPSD)
{
break;
}
/* Tell MAC to have device exit UAPSD mode. */
status = pmcSendMessage(pMac, eWNI_PMC_EXIT_UAPSD_REQ, NULL, 0);
if ( HAL_STATUS_SUCCESS( status ) )
{
/* Change state. Note that device will be put in BMPS state at the
end of REQUEST_STOP_UAPSD state even if response is a failure*/
pMac->pmc.pmcState = REQUEST_STOP_UAPSD;
pMac->pmc.requestFullPowerPending = TRUE;
pMac->pmc.requestFullPowerReason = pCommand->u.pmcCmd.fullPowerReason;
fRemoveCmd = eANI_BOOLEAN_FALSE;
}
else
{
pmcLog(pMac, LOGE, "PMC: failure to send message "
"eWNI_PMC_EXIT_UAPSD_REQ");
pmcEnterBmpsState(pMac);
}
}
break;
case eSmeCommandEnterWowl:
if( ( BMPS == pMac->pmc.pmcState ) || ( WOWL == pMac->pmc.pmcState ) )
{
status = pmcSendMessage(pMac, eWNI_PMC_ENTER_WOWL_REQ,
&pCommand->u.pmcCmd.u.enterWowlInfo, sizeof(tSirSmeWowlEnterParams));
if ( HAL_STATUS_SUCCESS( status ) )
{
pMac->pmc.pmcState = REQUEST_ENTER_WOWL;
fRemoveCmd = eANI_BOOLEAN_FALSE;
}
else
{
pmcLog(pMac, LOGE, "PMC: failure to send message eWNI_PMC_ENTER_WOWL_REQ");
pmcDoEnterWowlCallbacks(pMac, eHAL_STATUS_FAILURE);
}
}
else
{
fRemoveCmd = eANI_BOOLEAN_TRUE;
}
break;
case eSmeCommandExitWowl:
if( WOWL == pMac->pmc.pmcState )
{
pMac->pmc.requestFullPowerPending = FALSE;
pMac->pmc.pmcState = REQUEST_EXIT_WOWL;
status = pmcSendMessage(pMac, eWNI_PMC_EXIT_WOWL_REQ, NULL, 0);
if ( HAL_STATUS_SUCCESS( status ) )
{
fRemoveCmd = eANI_BOOLEAN_FALSE;
pMac->pmc.requestFullPowerPending = TRUE;
pMac->pmc.requestFullPowerReason = pCommand->u.pmcCmd.fullPowerReason;
}
else
{
pmcLog(pMac, LOGP, "PMC: failure to send message eWNI_PMC_EXIT_WOWL_REQ");
pmcEnterBmpsState(pMac);
}
}
break;
case eSmeCommandEnterStandby:
if( FULL_POWER == pMac->pmc.pmcState )
{
//Disallow standby if concurrent sessions are present. Note that CSR would have
//caused the STA to disconnect the Infra session (if not already disconnected) because of
//standby request. But we are now failing the standby request because of concurrent session.
//So was the tearing of infra session wasteful if we were going to fail the standby request ?
//Not really. This is beacuse if and when BT-AMP etc sessions are torn down we will transition
//to IMPS/standby and still save power.
if (csrIsIBSSStarted(pMac) || csrIsBTAMPStarted(pMac))
{
VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_FATAL,
"WLAN: IBSS or BT-AMP session present. Cannot honor standby request");
pmcDoStandbyCallbacks(pMac, eHAL_STATUS_PMC_NOT_NOW);
if(pmcShouldBmpsTimerRun(pMac))
(void)pmcStartTrafficTimer(pMac, pMac->pmc.bmpsConfig.trafficMeasurePeriod);
break;
}
// Stop traffic timer. Just making sure timer is not running
pmcStopTrafficTimer(pMac);
/* Change state. */
pMac->pmc.pmcState = REQUEST_STANDBY;
/* Tell MAC to have device enter STANDBY mode. We are using the same message
as IMPS mode to avoid code changes in layer below (PE/HAL)*/
status = pmcSendMessage(pMac, eWNI_PMC_ENTER_IMPS_REQ, NULL, 0);
if ( HAL_STATUS_SUCCESS( status ) )
{
//Disable Idle scan in CSR
csrScanSuspendIMPS(pMac);
fRemoveCmd = eANI_BOOLEAN_FALSE;
}
else
{
pmcLog(pMac, LOGE, "PMC: failure to send message "
"eWNI_PMC_ENTER_IMPS_REQ");
pmcEnterFullPowerState(pMac);
pmcDoStandbyCallbacks(pMac, eHAL_STATUS_FAILURE);
/* Start the timer only if Auto BMPS feature is enabled or an UAPSD session is
required */
if(pmcShouldBmpsTimerRun(pMac))
(void)pmcStartTrafficTimer(pMac, pMac->pmc.bmpsConfig.trafficMeasurePeriod);
}
}
break;
default:
pmcLog( pMac, LOGE, FL(" invalid command type %d"), pCommand->command );
break;
}
} while( 0 );
return( fRemoveCmd );
}
eHalStatus pmcEnterImpsCheck( tpAniSirGlobal pMac )
{
if( !PMC_IS_READY(pMac) )
{
pmcLog(pMac, LOGE, FL("Requesting IMPS when PMC not ready"));
pmcLog(pMac, LOGE, FL("pmcReady = %d pmcState = %s"),
pMac->pmc.pmcReady, pmcGetPmcStateStr(pMac->pmc.pmcState));
return eHAL_STATUS_FAILURE;
}
/* Check if IMPS is enabled. */
if (!pMac->pmc.impsEnabled)
{
pmcLog(pMac, LOG2, FL("IMPS is disabled"));
return eHAL_STATUS_PMC_DISABLED;
}
/* Check if IMPS enabled for current power source. */
if ((pMac->pmc.powerSource == AC_POWER) && !pMac->pmc.impsConfig.enterOnAc)
{
pmcLog(pMac, LOG2, FL("IMPS is disabled when operating on AC power"));
return eHAL_STATUS_PMC_AC_POWER;
}
/* Check that entry into a power save mode is allowed at this time. */
if (!pmcPowerSaveCheck(pMac))
{
pmcLog(pMac, LOG2, FL("IMPS cannot be entered now"));
return eHAL_STATUS_PMC_NOT_NOW;
}
/* Check that entry into a power save mode is allowed at this time if all
running sessions agree. */
if (!pmcAllowImps(pMac))
{
pmcLog(pMac, LOG2, FL("IMPS cannot be entered now"));
return eHAL_STATUS_PMC_NOT_NOW;
}
/* Check if already in IMPS. */
if ((pMac->pmc.pmcState == REQUEST_IMPS) || (pMac->pmc.pmcState == IMPS) ||
(pMac->pmc.pmcState == REQUEST_FULL_POWER))
{
pmcLog(pMac, LOG2, FL("Already in IMPS"));
return eHAL_STATUS_PMC_ALREADY_IN_IMPS;
}
/* Check whether driver load unload is in progress */
if(vos_is_load_unload_in_progress( VOS_MODULE_ID_VOSS, NULL))
{
pmcLog(pMac, LOGW, FL("Driver load/unload is in progress"));
return eHAL_STATUS_PMC_NOT_NOW;
}
return ( eHAL_STATUS_SUCCESS );
}
/* This API detrmines if it is ok to proceed with a Enter BMPS Request or not . Note when
device is in BMPS/UAPSD states, this API returns failure because it is not ok to issue
a BMPS request */
eHalStatus pmcEnterBmpsCheck( tpAniSirGlobal pMac )
{
/* Check if BMPS is enabled. */
if (!pMac->pmc.bmpsEnabled)
{
pmcLog(pMac, LOGE, "PMC: Cannot initiate BMPS. BMPS is disabled");
return eHAL_STATUS_PMC_DISABLED;
}
if( !PMC_IS_READY(pMac) )
{
pmcLog(pMac, LOGE, FL("Requesting BMPS when PMC not ready"));
pmcLog(pMac, LOGE, FL("pmcReady = %d pmcState = %s"),
pMac->pmc.pmcReady, pmcGetPmcStateStr(pMac->pmc.pmcState));
return eHAL_STATUS_FAILURE;
}
/* Check that we are associated with a single active session. */
if (!pmcValidateConnectState( pMac ))
{
pmcLog(pMac, LOGE, "PMC: STA not associated with an AP with single active session. BMPS cannot be entered");
return eHAL_STATUS_FAILURE;
}
/* BMPS can only be requested when device is in Full Power */
if (pMac->pmc.pmcState != FULL_POWER)
{
pmcLog(pMac, LOGE,
"PMC: Device not in full power. Cannot request BMPS. pmcState %d", pMac->pmc.pmcState);
return eHAL_STATUS_FAILURE;
}
/* Check that entry into a power save mode is allowed at this time. */
if (!pmcPowerSaveCheck(pMac))
{
pmcLog(pMac, LOGE, "PMC: Power save check failed. BMPS cannot be entered now");
return eHAL_STATUS_PMC_NOT_NOW;
}
//Remove this code once SLM_Sessionization is supported
//BMPS_WORKAROUND_NOT_NEEDED
if(!IS_FEATURE_SUPPORTED_BY_FW(SLM_SESSIONIZATION))
{
pmcLog(pMac, LOG1, FL("doBMPSWorkaround %u"), pMac->roam.configParam.doBMPSWorkaround);
if (pMac->roam.configParam.doBMPSWorkaround)
{
pMac->roam.configParam.doBMPSWorkaround = 0;
pmcLog(pMac, LOG1,
FL("reset doBMPSWorkaround to disabled %u"), pMac->roam.configParam.doBMPSWorkaround);
csrDisconnectAllActiveSessions(pMac);
pmcLog(pMac, LOGE,
"PMC: doBMPSWorkaround was enabled. First Disconnect all sessions. pmcState %d", pMac->pmc.pmcState);
return eHAL_STATUS_FAILURE;
}
}
return ( eHAL_STATUS_SUCCESS );
}
tANI_BOOLEAN pmcShouldBmpsTimerRun( tpAniSirGlobal pMac )
{
/* Check if BMPS is enabled and if Auto BMPS Feature is still enabled
* or there is a pending Uapsd request or HDD requested BMPS or there
* is a pending request for WoWL. In all these cases BMPS is required.
* Otherwise just stop the timer and return.
*/
if (!(pMac->pmc.bmpsEnabled && (pMac->pmc.autoBmpsEntryEnabled ||
pMac->pmc.uapsdSessionRequired || pMac->pmc.bmpsRequestedByHdd ||
pMac->pmc.wowlModeRequired )))
{
pmcLog(pMac, LOG1, FL("BMPS is not enabled or not required"));
return eANI_BOOLEAN_FALSE;
}
if(pMac->pmc.isHostPsEn && pMac->pmc.remainInPowerActiveTillDHCP)
{
pmcLog(pMac, LOG1,
FL("Host controlled ps enabled and host wants active mode, so dont allow BMPS"));
return eANI_BOOLEAN_FALSE;
}
if ((vos_concurrent_sessions_running()) &&
((csrIsConcurrentInfraConnected( pMac ) ||
(vos_get_concurrency_mode()& VOS_SAP) ||
(vos_get_concurrency_mode()& VOS_P2P_GO))))
{
pmcLog(pMac, LOG1, FL("Multiple Sessions/GO/SAP sessions . BMPS should not be started"));
return eANI_BOOLEAN_FALSE;
}
/* Check if there is an Infra session. BMPS is possible only if there is
* an Infra session */
if (!csrIsInfraConnected(pMac))
{
pmcLog(pMac, LOG1, FL("No Infra Session or multiple sessions. BMPS should not be started"));
return eANI_BOOLEAN_FALSE;
}
return eANI_BOOLEAN_TRUE;
}
#ifdef FEATURE_WLAN_DIAG_SUPPORT
#define PMC_DIAG_EVT_TIMER_INTERVAL ( 5000 )
void pmcDiagEvtTimerExpired (tHalHandle hHal)
{
tpAniSirGlobal pMac = PMAC_STRUCT(hHal);
WLAN_VOS_DIAG_EVENT_DEF(psRequest, vos_event_wlan_powersave_payload_type);
vos_mem_zero(&psRequest, sizeof(vos_event_wlan_powersave_payload_type));
psRequest.event_subtype = WLAN_PMC_CURRENT_STATE;
psRequest.pmc_current_state = pMac->pmc.pmcState;
WLAN_VOS_DIAG_EVENT_REPORT(&psRequest, EVENT_WLAN_POWERSAVE_GENERIC);
pmcLog(pMac, LOGW, FL("DIAG event timer expired"));
/* re-arm timer */
if (pmcStartDiagEvtTimer(hHal) != eHAL_STATUS_SUCCESS)
{
pmcLog(pMac, LOGP, FL("Cannot re-arm DIAG evt timer"));
}
vos_timer_start(&pMac->pmc.hDiagEvtTimer, PMC_DIAG_EVT_TIMER_INTERVAL);
}
eHalStatus pmcStartDiagEvtTimer (tHalHandle hHal)
{
tpAniSirGlobal pMac = PMAC_STRUCT(hHal);
pmcLog(pMac, LOG2, FL("Entering pmcStartDiagEvtTimer"));
if ( vos_timer_start(&pMac->pmc.hDiagEvtTimer, PMC_DIAG_EVT_TIMER_INTERVAL) != VOS_STATUS_SUCCESS)
{
pmcLog(pMac, LOGP, FL("Cannot start DIAG evt timer"));
return eHAL_STATUS_FAILURE;
}
return eHAL_STATUS_SUCCESS;
}
void pmcStopDiagEvtTimer (tHalHandle hHal)
{
tpAniSirGlobal pMac = PMAC_STRUCT(hHal);
pmcLog(pMac, LOG2, FL("Entering pmcStopDiagEvtTimer"));
(void)vos_timer_stop(&pMac->pmc.hDiagEvtTimer);
}
#endif
| VentureROM-Legacy/android_kernel_lge_d85x | drivers/staging/prima/CORE/SME/src/pmc/pmc.c | C | gpl-2.0 | 90,050 |
/********************************************************************************
* Nepenthes
* - finest collection -
*
*
*
* Copyright (C) 2005 Paul Baecher & Markus Koetter
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*
* contact [email protected]
*
*******************************************************************************/
/* $Id$ */
| jrwren/nepenthes | nepenthes-core/src/Responder.cpp | C++ | gpl-2.0 | 1,124 |
/*
* Copyright (C) 2015 Team XBMC
* http://kodi.tv
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include <algorithm>
extern "C" {
#include "libswscale/swscale.h"
}
#include "PictureScalingAlgorithm.h"
#include "utils/StringUtils.h"
CPictureScalingAlgorithm::Algorithm CPictureScalingAlgorithm::Default = CPictureScalingAlgorithm::Bicubic;
CPictureScalingAlgorithm::AlgorithmMap CPictureScalingAlgorithm::m_algorithms = {
{ FastBilinear, { "fast_bilinear", SWS_FAST_BILINEAR } },
{ Bilinear, { "bilinear", SWS_BILINEAR } },
{ Bicubic, { "bicubic", SWS_BICUBIC } },
{ Experimental, { "experimental", SWS_X } },
{ NearestNeighbor, { "nearest_neighbor", SWS_POINT } },
{ AveragingArea, { "averaging_area", SWS_AREA } },
{ Bicublin, { "bicublin", SWS_BICUBLIN } },
{ Gaussian, { "gaussian", SWS_GAUSS } },
{ Sinc, { "sinc", SWS_SINC } },
{ Lanczos, { "lanczos", SWS_LANCZOS } },
{ BicubicSpline, { "bicubic_spline", SWS_SPLINE } },
};
CPictureScalingAlgorithm::Algorithm CPictureScalingAlgorithm::FromString(const std::string& scalingAlgorithm)
{
const auto& algorithm = std::find_if(m_algorithms.begin(), m_algorithms.end(),
[&scalingAlgorithm](const std::pair<Algorithm, ScalingAlgorithm>& algo) { return StringUtils::EqualsNoCase(algo.second.name, scalingAlgorithm); });
if (algorithm != m_algorithms.end())
return algorithm->first;
return NoAlgorithm;
}
std::string CPictureScalingAlgorithm::ToString(Algorithm scalingAlgorithm)
{
const auto& algorithm = m_algorithms.find(scalingAlgorithm);
if (algorithm != m_algorithms.end())
return algorithm->second.name;
return "";
}
int CPictureScalingAlgorithm::ToSwscale(const std::string& scalingAlgorithm)
{
return ToSwscale(FromString(scalingAlgorithm));
}
int CPictureScalingAlgorithm::ToSwscale(Algorithm scalingAlgorithm)
{
const auto& algorithm = m_algorithms.find(scalingAlgorithm);
if (algorithm != m_algorithms.end())
return algorithm->second.swscale;
return ToSwscale(Default);
}
| ironman771/xbmc | xbmc/pictures/PictureScalingAlgorithm.cpp | C++ | gpl-2.0 | 2,771 |
/*
* This file is part of the coreboot project.
*
* Copyright 2015 Google Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc.
*/
#include <delay.h>
#include <soc/addressmap.h>
#include <device/i2c.h>
#include <soc/clock.h>
#include <soc/funitcfg.h>
#include <soc/nvidia/tegra/i2c.h>
#include <soc/padconfig.h>
#include <soc/romstage.h>
#include "gpio.h"
#include "pmic.h"
static const struct pad_config padcfgs[] = {
/* AP_SYS_RESET_L - active low*/
PAD_CFG_GPIO_OUT1(SDMMC1_DAT0, PINMUX_PULL_UP),
/* WP_L - active low */
PAD_CFG_GPIO_INPUT(GPIO_PK2, PINMUX_PULL_NONE),
/* BTN_AP_PWR_L - active low */
PAD_CFG_GPIO_INPUT(BUTTON_POWER_ON, PINMUX_PULL_UP),
/* BTN_AP_VOLD_L - active low */
PAD_CFG_GPIO_INPUT(BUTTON_VOL_DOWN, PINMUX_PULL_UP),
/* BTN_AP_VOLU_L - active low */
PAD_CFG_GPIO_INPUT(SDMMC1_DAT1, PINMUX_PULL_UP),
};
void romstage_mainboard_init(void)
{
soc_configure_pads(padcfgs, ARRAY_SIZE(padcfgs));
}
void mainboard_configure_pmc(void)
{
}
void mainboard_enable_vdd_cpu(void)
{
/* VDD_CPU is already enabled in bootblock. */
}
| BTDC/coreboot | src/mainboard/google/smaug/romstage.c | C | gpl-2.0 | 1,626 |