max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
521 | <filename>third_party/virtualbox/src/VBox/Additions/common/VBoxVideo/HGSMIBase.cpp
/* $Id: HGSMIBase.cpp $ */
/** @file
* VirtualBox Video driver, common code - HGSMI guest-to-host communication.
*/
/*
* Copyright (C) 2006-2017 Oracle Corporation
*
* 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.
*/
#include <HGSMIBase.h>
#include <VBoxVideoIPRT.h>
#include <VBoxVideoGuest.h>
#include <VBoxVideoVBE.h>
#include <HGSMIChannels.h>
#include <HGSMIChSetup.h>
/** Detect whether HGSMI is supported by the host. */
DECLHIDDEN(bool) VBoxHGSMIIsSupported(void)
{
uint16_t DispiId;
VBVO_PORT_WRITE_U16(VBE_DISPI_IOPORT_INDEX, VBE_DISPI_INDEX_ID);
VBVO_PORT_WRITE_U16(VBE_DISPI_IOPORT_DATA, VBE_DISPI_ID_HGSMI);
DispiId = VBVO_PORT_READ_U16(VBE_DISPI_IOPORT_DATA);
return (DispiId == VBE_DISPI_ID_HGSMI);
}
/**
* Inform the host of the location of the host flags in VRAM via an HGSMI command.
* @returns IPRT status value.
* @returns VERR_NOT_IMPLEMENTED if the host does not support the command.
* @returns VERR_NO_MEMORY if a heap allocation fails.
* @param pCtx the context of the guest heap to use.
* @param offLocation the offset chosen for the flags withing guest VRAM.
*/
DECLHIDDEN(int) VBoxHGSMIReportFlagsLocation(PHGSMIGUESTCOMMANDCONTEXT pCtx, HGSMIOFFSET offLocation)
{
/* Allocate the IO buffer. */
HGSMIBUFFERLOCATION RT_UNTRUSTED_VOLATILE_HOST *p =
(HGSMIBUFFERLOCATION RT_UNTRUSTED_VOLATILE_HOST *)VBoxHGSMIBufferAlloc(pCtx, sizeof(*p), HGSMI_CH_HGSMI,
HGSMI_CC_HOST_FLAGS_LOCATION);
if (!p)
return VERR_NO_MEMORY;
/* Prepare data to be sent to the host. */
p->offLocation = offLocation;
p->cbLocation = sizeof(HGSMIHOSTFLAGS);
/* No need to check that the buffer is valid as we have just allocated it. */
VBoxHGSMIBufferSubmit(pCtx, p);
/* Free the IO buffer. */
VBoxHGSMIBufferFree(pCtx, p);
return VINF_SUCCESS;
}
/**
* Notify the host of HGSMI-related guest capabilities via an HGSMI command.
* @returns IPRT status value.
* @returns VERR_NOT_IMPLEMENTED if the host does not support the command.
* @returns VERR_NO_MEMORY if a heap allocation fails.
* @param pCtx the context of the guest heap to use.
* @param fCaps the capabilities to report, see VBVACAPS.
*/
DECLHIDDEN(int) VBoxHGSMISendCapsInfo(PHGSMIGUESTCOMMANDCONTEXT pCtx, uint32_t fCaps)
{
/* Allocate the IO buffer. */
VBVACAPS RT_UNTRUSTED_VOLATILE_HOST *p =
(VBVACAPS RT_UNTRUSTED_VOLATILE_HOST *)VBoxHGSMIBufferAlloc(pCtx, sizeof(*p), HGSMI_CH_VBVA, VBVA_INFO_CAPS);
if (!p)
return VERR_NO_MEMORY;
/* Prepare data to be sent to the host. */
p->rc = VERR_NOT_IMPLEMENTED;
p->fCaps = fCaps;
/* No need to check that the buffer is valid as we have just allocated it. */
VBoxHGSMIBufferSubmit(pCtx, p);
AssertRC(p->rc);
/* Free the IO buffer. */
VBoxHGSMIBufferFree(pCtx, p);
return p->rc;
}
/**
* Get the information needed to map the basic communication structures in
* device memory into our address space. All pointer parameters are optional.
*
* @param cbVRAM how much video RAM is allocated to the device
* @param poffVRAMBaseMapping where to save the offset from the start of the
* device VRAM of the whole area to map
* @param pcbMapping where to save the mapping size
* @param poffGuestHeapMemory where to save the offset into the mapped area
* of the guest heap backing memory
* @param pcbGuestHeapMemory where to save the size of the guest heap
* backing memory
* @param poffHostFlags where to save the offset into the mapped area
* of the host flags
*/
DECLHIDDEN(void) VBoxHGSMIGetBaseMappingInfo(uint32_t cbVRAM,
uint32_t *poffVRAMBaseMapping,
uint32_t *pcbMapping,
uint32_t *poffGuestHeapMemory,
uint32_t *pcbGuestHeapMemory,
uint32_t *poffHostFlags)
{
AssertPtrNullReturnVoid(poffVRAMBaseMapping);
AssertPtrNullReturnVoid(pcbMapping);
AssertPtrNullReturnVoid(poffGuestHeapMemory);
AssertPtrNullReturnVoid(pcbGuestHeapMemory);
AssertPtrNullReturnVoid(poffHostFlags);
if (poffVRAMBaseMapping)
*poffVRAMBaseMapping = cbVRAM - VBVA_ADAPTER_INFORMATION_SIZE;
if (pcbMapping)
*pcbMapping = VBVA_ADAPTER_INFORMATION_SIZE;
if (poffGuestHeapMemory)
*poffGuestHeapMemory = 0;
if (pcbGuestHeapMemory)
*pcbGuestHeapMemory = VBVA_ADAPTER_INFORMATION_SIZE
- sizeof(HGSMIHOSTFLAGS);
if (poffHostFlags)
*poffHostFlags = VBVA_ADAPTER_INFORMATION_SIZE
- sizeof(HGSMIHOSTFLAGS);
}
/**
* Query the host for an HGSMI configuration parameter via an HGSMI command.
* @returns iprt status value
* @param pCtx the context containing the heap used
* @param u32Index the index of the parameter to query,
* @see VBVACONF32::u32Index
* @param pulValue where to store the value of the parameter on success
*/
DECLHIDDEN(int) VBoxQueryConfHGSMI(PHGSMIGUESTCOMMANDCONTEXT pCtx, uint32_t u32Index, uint32_t *pulValue)
{
VBVACONF32 *p;
/* Allocate the IO buffer. */
p = (VBVACONF32 *)VBoxHGSMIBufferAlloc(pCtx, sizeof(*p), HGSMI_CH_VBVA, VBVA_QUERY_CONF32);
if (!p)
return VERR_NO_MEMORY;
/* Prepare data to be sent to the host. */
p->u32Index = u32Index;
p->u32Value = UINT32_MAX;
/* No need to check that the buffer is valid as we have just allocated it. */
VBoxHGSMIBufferSubmit(pCtx, p);
*pulValue = p->u32Value;
/* Free the IO buffer. */
VBoxHGSMIBufferFree(pCtx, p);
return VINF_SUCCESS;
}
/**
* Pass the host a new mouse pointer shape via an HGSMI command.
*
* @returns success or failure
* @param pCtx the context containing the heap to be used
* @param fFlags cursor flags, @see VMMDevReqMousePointer::fFlags
* @param cHotX horizontal position of the hot spot
* @param cHotY vertical position of the hot spot
* @param cWidth width in pixels of the cursor
* @param cHeight height in pixels of the cursor
* @param pPixels pixel data, @see VMMDevReqMousePointer for the format
* @param cbLength size in bytes of the pixel data
*/
DECLHIDDEN(int) VBoxHGSMIUpdatePointerShape(PHGSMIGUESTCOMMANDCONTEXT pCtx, uint32_t fFlags,
uint32_t cHotX, uint32_t cHotY, uint32_t cWidth, uint32_t cHeight,
uint8_t *pPixels, uint32_t cbLength)
{
VBVAMOUSEPOINTERSHAPE *p;
uint32_t cbPixels = 0;
int rc;
if (fFlags & VBOX_MOUSE_POINTER_SHAPE)
{
/*
* Size of the pointer data:
* sizeof (AND mask) + sizeof (XOR_MASK)
*/
cbPixels = ((((cWidth + 7) / 8) * cHeight + 3) & ~3)
+ cWidth * 4 * cHeight;
if (cbPixels > cbLength)
return VERR_INVALID_PARAMETER;
/*
* If shape is supplied, then always create the pointer visible.
* See comments in 'vboxUpdatePointerShape'
*/
fFlags |= VBOX_MOUSE_POINTER_VISIBLE;
}
/* Allocate the IO buffer. */
p = (VBVAMOUSEPOINTERSHAPE *)VBoxHGSMIBufferAlloc(pCtx, sizeof(*p) + cbPixels, HGSMI_CH_VBVA,
VBVA_MOUSE_POINTER_SHAPE);
if (!p)
return VERR_NO_MEMORY;
/* Prepare data to be sent to the host. */
/* Will be updated by the host. */
p->i32Result = VINF_SUCCESS;
/* We have our custom flags in the field */
p->fu32Flags = fFlags;
p->u32HotX = cHotX;
p->u32HotY = cHotY;
p->u32Width = cWidth;
p->u32Height = cHeight;
if (cbPixels)
/* Copy the actual pointer data. */
memcpy (p->au8Data, pPixels, cbPixels);
/* No need to check that the buffer is valid as we have just allocated it. */
VBoxHGSMIBufferSubmit(pCtx, p);
rc = p->i32Result;
/* Free the IO buffer. */
VBoxHGSMIBufferFree(pCtx, p);
return rc;
}
/**
* Report the guest cursor position. The host may wish to use this information
* to re-position its own cursor (though this is currently unlikely). The
* current host cursor position is returned.
* @param pCtx The context containing the heap used.
* @param fReportPosition Are we reporting a position?
* @param x Guest cursor X position.
* @param y Guest cursor Y position.
* @param pxHost Host cursor X position is stored here. Optional.
* @param pyHost Host cursor Y position is stored here. Optional.
* @returns iprt status code.
* @returns VERR_NO_MEMORY HGSMI heap allocation failed.
*/
DECLHIDDEN(int) VBoxHGSMICursorPosition(PHGSMIGUESTCOMMANDCONTEXT pCtx, bool fReportPosition,
uint32_t x, uint32_t y, uint32_t *pxHost, uint32_t *pyHost)
{
VBVACURSORPOSITION *p;
/* Allocate the IO buffer. */
p = (VBVACURSORPOSITION *)VBoxHGSMIBufferAlloc(pCtx, sizeof(*p), HGSMI_CH_VBVA,
VBVA_CURSOR_POSITION);
if (!p)
return VERR_NO_MEMORY;
/* Prepare data to be sent to the host. */
p->fReportPosition = fReportPosition;
p->x = x;
p->y = y;
/* No need to check that the buffer is valid as we have just allocated it. */
VBoxHGSMIBufferSubmit(pCtx, p);
if (pxHost)
*pxHost = p->x;
if (pyHost)
*pyHost = p->y;
/* Free the IO buffer. */
VBoxHGSMIBufferFree(pCtx, p);
return VINF_SUCCESS;
}
/**
* @todo Mouse pointer position to be read from VMMDev memory, address of the
* memory region can be queried from VMMDev via an IOCTL. This VMMDev memory
* region will contain host information which is needed by the guest.
*
* Reading will not cause a switch to the host.
*
* Have to take into account:
* * synchronization: host must write to the memory only from EMT,
* large structures must be read under flag, which tells the host
* that the guest is currently reading the memory (OWNER flag?).
* * guest writes: may be allocate a page for the host info and make
* the page readonly for the guest.
* * the information should be available only for additions drivers.
* * VMMDev additions driver will inform the host which version of the info
* it expects, host must support all versions.
*/
| 5,097 |
3,269 | <filename>C++/maximum-length-of-a-concatenated-string-with-unique-characters.cpp
// Time: O(n) ~ O(2^n)
// Space: O(1) ~ O(2^n)
class Solution {
public:
int maxLength(vector<string>& arr) {
vector<int> dp(1);
for (const auto& x : arr) {
const auto& x_set = bitset(x);
if (!x_set) {
continue;
}
const auto curr_size = dp.size();
for (int i = 0; i < curr_size; ++i) {
if (dp[i] & x_set) {
continue;
}
dp.emplace_back(dp[i] | x_set);
}
}
return number_of_one(*max_element(dp.cbegin(), dp.cend(),
[&](const auto& lhs, const auto& rhs) {
return number_of_one(lhs) < number_of_one(rhs);
}));
}
private:
int bitset(const string& s) {
int result = 0;
for (const auto& c : s) {
if (result & (1 << (c - 'a'))) {
return 0;
}
result |= 1 << (c - 'a');
}
return result;
}
int number_of_one(int n) {
int count = 0;
for (; n; n &= n - 1) {
++count;
}
return count;
}
};
// Time: O(2^n)
// Space: O(1)
class Solution2 {
public:
int maxLength(vector<string>& arr) {
vector<int> bitsets;
for (const auto& x : arr) {
bitsets.emplace_back(bitset(x));
}
int result = 0;
for (int i = 0; i < (1 << arr.size()); ++i) {
bool skip = false;
int curr_bitset = 0, curr_len = 0;
for (int j = 0; j < arr.size(); ++j) {
if (!(i & (1 << j))) {
continue;
}
if (!bitsets[j] || (curr_bitset & bitsets[j])) {
skip = true;
break;
}
curr_bitset |= bitsets[j];
curr_len += arr[j].length();
}
if (skip) {
continue;
}
result = max(result, curr_len);
}
return result;
}
private:
int bitset(const string& s) {
int result = 0;
for (const auto& c : s) {
if (result & (1 << (c - 'a'))) {
return 0;
}
result |= 1 << (c - 'a');
}
return result;
}
};
| 1,536 |
543 | /*
* Copyright 2019 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.mirkosertic.bytecoder.complex;
import de.mirkosertic.bytecoder.unittest.BytecoderUnitTestRunner;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.luaj.vm2.Globals;
import org.luaj.vm2.LuaClosure;
import org.luaj.vm2.LuaError;
import org.luaj.vm2.LuaInteger;
import org.luaj.vm2.LuaString;
import org.luaj.vm2.LuaTable;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.Prototype;
import org.luaj.vm2.Varargs;
import org.luaj.vm2.compiler.LuaC;
import java.io.IOException;
import java.io.StringReader;
@RunWith(BytecoderUnitTestRunner.class)
public class LuaTest {
@Test
public void testLuaReturnString() {
final Globals theGlobals = new Globals();
LuaC.install(theGlobals);
final LuaValue chunk = theGlobals.load("return 'hello, world'");
final LuaString theResult = chunk.call().strvalue();
Assert.assertEquals("hello, world", theResult.tojstring());
}
@Test
public void testLuaReturnInteger() {
final Globals theGlobals = new Globals();
LuaC.install(theGlobals);
final LuaValue chunk = theGlobals.load("return 123");
final LuaString theResult = chunk.call().strvalue();
Assert.assertEquals("123", theResult.tojstring());
}
@Test
public void testLuaReturnIntegerAdd() {
final Globals theGlobals = new Globals();
LuaC.install(theGlobals);
final LuaValue chunk = theGlobals.load("return 123 + 231");
final LuaString theResult = chunk.call().strvalue();
Assert.assertEquals("354", theResult.tojstring());
}
@Test
public void testLuaFunction() {
final Globals theGlobals = new Globals();
LuaC.install(theGlobals);
final LuaValue chunk = theGlobals.load("function add(a,b)\nreturn a+b\nend\nreturn add(1,2)");
Assert.assertFalse(chunk.isnil());
Assert.assertTrue(chunk instanceof LuaClosure);
final LuaClosure luaClosure = (LuaClosure) chunk;
final LuaString theResult = luaClosure.call().strvalue();
Assert.assertEquals("3", theResult.tojstring());
}
@Test
public void testVarArgs() {
final Globals theGlobals = new Globals();
LuaC.install(theGlobals);
final Varargs theArguments = LuaValue.varargsOf(new LuaValue[]{
LuaInteger.valueOf(100),
LuaInteger.valueOf(200)
});
}
@Test
public void testCall() throws IOException {
final Globals theGlobals = new Globals();
LuaC.install(theGlobals);
final Prototype thePrototype = theGlobals.compilePrototype(new StringReader("function add(a,b) return a + b end"), "script");
new LuaClosure(thePrototype, theGlobals).call();
final LuaValue theFunction = theGlobals.get("add");
Assert.assertFalse(theFunction.isnil());
final Varargs theArguments = LuaValue.varargsOf(new LuaValue[] {
LuaInteger.valueOf(100),
LuaInteger.valueOf(200)
});
final LuaInteger theResult = (LuaInteger) theFunction.invoke(theArguments);
Assert.assertEquals("300", theResult.tojstring());
}
@Test
public void testCallStringResult() throws IOException {
final Globals theGlobals = new Globals();
LuaC.install(theGlobals);
final Prototype thePrototype = theGlobals.compilePrototype(new StringReader("function add(a,b) return 'hello' end"), "script");
new LuaClosure(thePrototype, theGlobals).call();
final Varargs theArguments = LuaValue.varargsOf(new LuaValue[] {
LuaInteger.valueOf(100),
LuaInteger.valueOf(200)
});
final LuaValue theFunction = theGlobals.get("add");
final LuaValue theValue = (LuaValue) theFunction.invoke(theArguments);
Assert.assertTrue(theValue.isstring());
Assert.assertEquals("hello", theValue.tojstring());
}
@Test
public void testLuaError() {
final LuaError error = new LuaError("Test");
Assert.assertEquals("Test", error.getMessage());
}
@Test
public void testLuaTable() {
final Globals theGlobals = new Globals();
LuaC.install(theGlobals);
final LuaTable theTable = new LuaTable();
theTable.set("20", 200);
Assert.assertEquals(200, theTable.get("20").toint(), 0);
}
@Test
public void testLuaConversion() {
final Globals theGlobals = new Globals();
LuaC.install(theGlobals);
theGlobals.set("key", 10);
Assert.assertEquals(10, theGlobals.get("key").toint());
Assert.assertEquals(10, theGlobals.get(LuaString.valueOf("key")).toint());
final LuaValue chunk = theGlobals.load("return key").call();
Assert.assertEquals(10, chunk.toint());
}
@Test
public void testGlobalSize() {
final Globals theGlobals = new Globals();
for (int i =0;i<=100;i++) {
theGlobals.set("ABC", Integer.toString(i));
}
theGlobals.presize(1000);
Assert.assertEquals(100, theGlobals.get("ABC").toint(),0);
}
} | 2,291 |
4,304 | #ifndef PASS_SERIALISERS_H
#define PASS_SERIALISERS_H
#include <platform.h>
#include "../ast/ast.h"
#include "../pass/pass.h"
PONY_EXTERN_C_BEGIN
bool pass_serialisers(ast_t* program, pass_opt_t* options);
PONY_EXTERN_C_END
#endif
| 104 |
324 | <gh_stars>100-1000
/*
* Copyright 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.css;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.collect.Iterables;
import com.google.common.primitives.Ints;
import java.util.Iterator;
import javax.annotation.Nullable;
/**
* A location in source code. A location is a sequence of adjacent characters
* that usually represent a token or a larger language construct.
*
* <p>Error messages represent the most common use of this class, as an error
* message usually relates to a source code location. The location related to
* some messages might not be known; this class has a special value that
* represents an "unknown" location.
*
* <p>Character sequences this class points to can have 0 length. If that is the
* case, the actual location is that "point" between two source code characters.
* This usually means that something happens from that point onwards, or that an
* error has been detected at that point but there is no information regarding
* the actual token that caused the error.
*
* <p>Instances of this class are immutable.
*
*/
public class SourceCodeLocation implements Comparable<SourceCodeLocation> {
/**
* This describes a point in a string. A point is the location between two
* characters and is indicated by the character index of the immediately
* following character. For example, in the string "abc", point 0 refers to
* the location immediately before the 'a' and point 2 to the location before
* the 'c'.
*
* <p>For convenience we also store the line number of the point (the line
* that contains the character following the point) and the index in that
* line. Both of these indices start at 1. The first line of a file is line 1
* and the point before its first character has index 1 on line 1.
*
* <p>The exact definition of lines depends on the language conventions and is
* best left for the parser to handle. If you want to display the text at that
* location, either use the character index or use the line number and the
* index in the line together with lines as they were split by the parser.
*
* <p>It might happen that the source code point for something is not known.
* This is modeled by a point with the special value -1 for the character
* index. The line and the index on the line must be 0 in this case.
*
* <p>Instances of this class are immutable.
*/
@VisibleForTesting
public static class SourceCodePoint implements Comparable<SourceCodePoint> {
/**
* The index of the character immediately after the source code point.
* Indices start at 0; -1 means the location is not known.
*/
private final int characterIndex;
/**
* The number of the line that contains the character at characterIndex.
* Numbers start at 1; 0 means the location is not known.
*/
private final int lineNumber;
/**
* The index in the line identified by lineNumber of the character at
* characterIndex. Numbers start at 1; 0 means the location is not known.
*/
private final int indexInLine;
SourceCodePoint(int characterIndex, int lineNumber, int indexInLine) {
this.lineNumber = lineNumber;
this.indexInLine = indexInLine;
this.characterIndex = characterIndex;
if (!hasValidKnownCoordinates()
&& !hasValidUnknownCoordinates()) {
throw new IllegalArgumentException(
String.format(
"The location passed "
+ "(lineNumber %d, indexInLine %d, characterIndex %d) "
+ "is not valid.",
lineNumber, indexInLine, characterIndex));
}
if (!hasPlausibleCoordinates()) {
throw new IllegalArgumentException(
String.format(
"The location passed "
+ "(lineNumber %d, indexInLine %d, characterIndex %d) "
+ "is not plausible.",
lineNumber, indexInLine, characterIndex));
}
}
SourceCodePoint(SourceCodePoint that) {
this(that.characterIndex, that.lineNumber, that.indexInLine);
}
boolean hasValidKnownCoordinates() {
return lineNumber >= 1 && indexInLine >= 1 && characterIndex >= 0;
}
boolean hasValidUnknownCoordinates() {
return characterIndex == -1 && lineNumber == 0 && indexInLine == 0;
}
boolean hasPlausibleCoordinates() {
return characterIndex >= lineNumber - 1 + indexInLine - 1;
}
int getCharacterIndex() {
return characterIndex;
}
int getLineNumber() {
return lineNumber;
}
int getIndexInLine() {
return indexInLine;
}
boolean isUnknown() {
return characterIndex == -1;
}
@Override
public boolean equals(@Nullable Object o) {
if (o == null) {
return false;
}
if (!(o instanceof SourceCodePoint)) {
return false;
}
SourceCodePoint other = (SourceCodePoint) o;
boolean areEqual = this.characterIndex == other.characterIndex;
if (areEqual) {
Preconditions.checkState((this.lineNumber == other.lineNumber)
&& (this.indexInLine == other.indexInLine),
"Character indexes are equal but line numbers and indexes within " +
"the line do not match.");
} else {
Preconditions.checkState((this.lineNumber != other.lineNumber)
|| (this.indexInLine != other.indexInLine),
"Line numbers and indexes within the line match but character " +
"indexes are not equal");
}
return areEqual;
}
@Override
public int hashCode() {
return characterIndex;
}
@Override
public int compareTo(SourceCodePoint o) {
Preconditions.checkNotNull(o);
return Ints.compare(this.characterIndex, o.characterIndex);
}
}
private static final SourceCode UNKNOWN_SOURCE_CODE =
new SourceCode("unknown", "");
private static final Function<Locatable, SourceCodeLocation> LOCATABLE_TO_LOCATION =
new Function<Locatable, SourceCodeLocation>() {
@Override
public SourceCodeLocation apply(Locatable locatable) {
return locatable.getSourceCodeLocation();
}
};
/**
* Returns an unknown location.
*/
public static SourceCodeLocation getUnknownLocation() {
SourceCodeLocation result = new SourceCodeLocation(
UNKNOWN_SOURCE_CODE,
-1 /* beginCharacterIndex */,
0 /* beginLineNumber */,
0 /* beginIndexInLine */,
-1 /* endCharacterindex */,
0 /* endLineNumber */,
0 /* endIndexInLine */);
Preconditions.checkState(result.isUnknown());
Preconditions.checkState(result.begin.hasValidUnknownCoordinates());
Preconditions.checkState(result.end.hasValidUnknownCoordinates());
return result;
}
/**
* Returns a new SourceCodeLocation which covers everything between the beginning of the first
* location and the end of the second location.
*/
public static SourceCodeLocation merge(
SourceCodeLocation beginLocation, SourceCodeLocation endLocation) {
Preconditions.checkNotNull(beginLocation, "Begin location can not be null");
Preconditions.checkNotNull(endLocation, "End location can not be null");
Preconditions.checkArgument(
beginLocation.sourceCode.equals(endLocation.sourceCode),
"Locations %s and %s come from different files; they cannot be merged",
beginLocation,
endLocation);
Preconditions.checkArgument(
beginLocation.compareTo(endLocation) <= 0,
"Begin location %s must be less than or equal to end location %s",
beginLocation,
endLocation);
return new SourceCodeLocation(
beginLocation.sourceCode,
beginLocation.getBeginCharacterIndex(),
beginLocation.getBeginLineNumber(),
beginLocation.getBeginIndexInLine(),
endLocation.getEndCharacterIndex(),
endLocation.getEndLineNumber(),
endLocation.getEndIndexInLine());
}
/**
* Merges the locations of all of the given locations. If the locations span {@code SourceCode}s,
* only the locations in the first {@code SourceCode} are used. If locations are out of order,
* the bounding locations are used.
*/
public static SourceCodeLocation mergeAll(Iterable<SourceCodeLocation> locations) {
Iterator<SourceCodeLocation> i = locations.iterator();
SourceCodeLocation loc = null;
while (i.hasNext() && loc == null) {
loc = i.next();
}
if (!i.hasNext()) {
return loc; // NOTE(flan): Many places assume that missing locations are null, not unknown.
}
SourceCode sourceCode = loc.sourceCode;
SourceCodePoint begin = loc.begin;
SourceCodePoint end = loc.end;
while (i.hasNext()) {
loc = i.next();
if (loc == null || loc.isUnknown() || !loc.sourceCode.equals(sourceCode)) {
continue;
}
if (loc.begin.compareTo(begin) < 0) {
begin = loc.begin;
}
if (loc.end.compareTo(end) > 0) {
end = loc.end;
}
}
return new SourceCodeLocation(sourceCode, begin, end);
}
/**
* Merges the locations of all of the given locations. If the locations span {@code SourceCode}s,
* only the locations in the first {@code SourceCode} are used.
*/
public static SourceCodeLocation merge(Iterable<? extends Locatable> locations) {
return mergeAll(Iterables.transform(locations, LOCATABLE_TO_LOCATION));
}
private final SourceCode sourceCode;
/**
* The sequence starts at the character immediately following the begin point.
*/
private final SourceCodePoint begin;
/**
* The sequence ends at the character immediately before the end point. The
* character immediately after the end point (the one indicated by the end's
* {@link SourceCodePoint#characterIndex}) is not part of the sequence. The
* empty sequence's begin point and end point are the same:
* {@code begin.equals(end)}.
*/
private final SourceCodePoint end;
@VisibleForTesting
public SourceCodeLocation(SourceCode sourceCode, SourceCodePoint begin, SourceCodePoint end) {
Preconditions.checkNotNull(sourceCode);
this.sourceCode = sourceCode;
this.begin = begin;
this.end = end;
Preconditions.checkArgument(begin.compareTo(end) <= 0,
"Beginning location must come before the end location.");
}
@VisibleForTesting
public SourceCodeLocation(
SourceCode sourceCode,
int beginCharacterIndex,
int beginLineNumber,
int beginIndexInLine,
int endCharacterIndex,
int endLineNumber,
int endIndexInLine) {
this(
sourceCode,
new SourceCodePoint(beginCharacterIndex, beginLineNumber, beginIndexInLine),
new SourceCodePoint(endCharacterIndex, endLineNumber, endIndexInLine));
}
public SourceCode getSourceCode() {
return sourceCode;
}
public boolean isUnknown() {
Preconditions.checkState(begin.isUnknown() == end.isUnknown());
return begin.isUnknown();
}
public int getBeginCharacterIndex() {
return begin.getCharacterIndex();
}
/**
* The index of the line that contains the first character of the node. Indexes start at 1; 0
* means the location is not known.
*/
public int getBeginLineNumber() {
return begin.getLineNumber();
}
/**
* The index of the column that contains the first character of the node. Indexes start at 1; 0
* means the location is not known.
*/
public int getBeginIndexInLine() {
return begin.getIndexInLine();
}
public int getEndCharacterIndex() {
return end.getCharacterIndex();
}
/**
* The index of the line that contains the last character of the node. Indexes start at 1; 0 means
* the location is not known.
*/
public int getEndLineNumber() {
return end.getLineNumber();
}
/**
* The index of the column that comes after the last character of the node. Indexes start at 1; 0
* means the location is not known.
*/
public int getEndIndexInLine() {
return end.getIndexInLine();
}
public int getCharacterIndex() {
return getBeginCharacterIndex();
}
public int getLineNumber() {
return getBeginLineNumber();
}
public int getIndexInLine() {
return getBeginIndexInLine();
}
public SourceCodePoint getBegin() {
return begin;
}
public SourceCodePoint getEnd() {
return end;
}
@Override
public boolean equals(@Nullable Object o) {
if (o == null) {
return false;
}
if (!(o instanceof SourceCodeLocation)) {
return false;
}
SourceCodeLocation other = (SourceCodeLocation) o;
return sourceCode == other.sourceCode && begin.equals(other.begin)
&& end.equals(other.end);
}
@Override
public int hashCode() {
return sourceCode.hashCode() ^ begin.hashCode() ^ (end.hashCode() << 16);
}
/**
* Comparison and ordering of locations for source code in different
* input files is supported because we don't always preserve
* locations during AST mutations and yet we still want to be able
* to sort error reports, doing the best job we can for the errors
* that have known locations. For the semantics of this method, see
* {@link Comparable#compareTo(Object)}.
*/
@Override
public int compareTo(SourceCodeLocation o) {
Preconditions.checkNotNull(o);
if (sourceCode != o.sourceCode) {
if (sourceCode == null) {
return -1;
} else if (o.sourceCode == null) {
return 1;
} else {
return sourceCode.hashCode() - o.sourceCode.hashCode();
}
}
int startPointsComparison = begin.compareTo(o.begin);
if (startPointsComparison != 0) {
return startPointsComparison;
}
return end.compareTo(o.end);
}
@Override
public String toString() {
return String.format(
"%s: [line %d, col %d -> line %d, col %d)", // half-open interval notation
sourceCode.getFileName(),
begin.getLineNumber(),
begin.getIndexInLine(),
end.getLineNumber(),
end.getIndexInLine());
}
}
| 4,956 |
6,304 | // Copyright 2020 Google LLC.
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
#include "tools/fiddle/examples.h"
REG_FIDDLE(drawarcs, 256, 256, false, 0) {
void draw(SkCanvas* canvas) {
SkPaint paint;
paint.setAntiAlias(true);
paint.setStyle(SkPaint::kStroke_Style);
paint.setStrokeWidth(8);
SkPath path;
SkRandom rand;
for (int i = 0; i < 100; ++i) {
SkScalar x = rand.nextUScalar1() * 200;
SkScalar y = rand.nextUScalar1() * 200;
path.rewind();
path.addArc(SkRect::MakeXYWH(x, y, 70, 70), rand.nextUScalar1() * 360,
rand.nextUScalar1() * 360);
paint.setColor(rand.nextU() | 0xFF000000);
canvas->drawPath(path, paint);
}
}
} // END FIDDLE
| 359 |
892 | {
"schema_version": "1.2.0",
"id": "GHSA-vfq5-wqf5-2qgg",
"modified": "2022-05-13T01:21:09Z",
"published": "2022-05-13T01:21:09Z",
"aliases": [
"CVE-2019-0101"
],
"details": "Authentication bypass in the Intel Unite(R) solution versions 3.2 through 3.3 may allow an unauthenticated user to potentially enable escalation of privilege to the Intel Unite(R) Solution administrative portal via network access.",
"severity": [
{
"type": "CVSS_V3",
"score": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H"
}
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2019-0101"
},
{
"type": "WEB",
"url": "https://www.intel.com/content/www/us/en/security-center/advisory/INTEL-SA-00214.html"
},
{
"type": "WEB",
"url": "http://www.securityfocus.com/bid/107076"
}
],
"database_specific": {
"cwe_ids": [
],
"severity": "CRITICAL",
"github_reviewed": false
}
} | 482 |
926 | <reponame>dlmarquis/dfhack
using namespace DFHack;
using namespace df::enums;
static bool inc_wear_timer (df::item_constructed *item, int amount)
{
if (item->flags.bits.artifact)
return false;
MaterialInfo mat(item->mat_type, item->mat_index);
if (mat.isInorganic() && mat.inorganic->flags.is_set(inorganic_flags::DEEP_SPECIAL))
return false;
item->wear_timer += amount;
return (item->wear_timer > 806400);
}
struct adamantine_cloth_wear_armor_hook : df::item_armorst {
typedef df::item_armorst interpose_base;
DEFINE_VMETHOD_INTERPOSE(bool, incWearTimer, (int amount))
{
return inc_wear_timer(this, amount);
}
};
IMPLEMENT_VMETHOD_INTERPOSE(adamantine_cloth_wear_armor_hook, incWearTimer);
struct adamantine_cloth_wear_helm_hook : df::item_helmst {
typedef df::item_helmst interpose_base;
DEFINE_VMETHOD_INTERPOSE(bool, incWearTimer, (int amount))
{
return inc_wear_timer(this, amount);
}
};
IMPLEMENT_VMETHOD_INTERPOSE(adamantine_cloth_wear_helm_hook, incWearTimer);
struct adamantine_cloth_wear_gloves_hook : df::item_glovesst {
typedef df::item_glovesst interpose_base;
DEFINE_VMETHOD_INTERPOSE(bool, incWearTimer, (int amount))
{
return inc_wear_timer(this, amount);
}
};
IMPLEMENT_VMETHOD_INTERPOSE(adamantine_cloth_wear_gloves_hook, incWearTimer);
struct adamantine_cloth_wear_shoes_hook : df::item_shoesst {
typedef df::item_shoesst interpose_base;
DEFINE_VMETHOD_INTERPOSE(bool, incWearTimer, (int amount))
{
return inc_wear_timer(this, amount);
}
};
IMPLEMENT_VMETHOD_INTERPOSE(adamantine_cloth_wear_shoes_hook, incWearTimer);
struct adamantine_cloth_wear_pants_hook : df::item_pantsst {
typedef df::item_pantsst interpose_base;
DEFINE_VMETHOD_INTERPOSE(bool, incWearTimer, (int amount))
{
return inc_wear_timer(this, amount);
}
};
IMPLEMENT_VMETHOD_INTERPOSE(adamantine_cloth_wear_pants_hook, incWearTimer);
| 786 |
22,688 | /******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/canbus/vehicle/lexus/protocol/dash_controls_left_rpt_20c.h"
#include "glog/logging.h"
#include "modules/drivers/canbus/common/byte.h"
#include "modules/drivers/canbus/common/canbus_consts.h"
namespace apollo {
namespace canbus {
namespace lexus {
using ::apollo::drivers::canbus::Byte;
Dashcontrolsleftrpt20c::Dashcontrolsleftrpt20c() {}
const int32_t Dashcontrolsleftrpt20c::ID = 0x20C;
void Dashcontrolsleftrpt20c::Parse(const std::uint8_t* bytes, int32_t length,
ChassisDetail* chassis) const {
chassis->mutable_lexus()
->mutable_dash_controls_left_rpt_20c()
->set_output_value(output_value(bytes, length));
chassis->mutable_lexus()
->mutable_dash_controls_left_rpt_20c()
->set_commanded_value(commanded_value(bytes, length));
chassis->mutable_lexus()
->mutable_dash_controls_left_rpt_20c()
->set_manual_input(manual_input(bytes, length));
chassis->mutable_lexus()
->mutable_dash_controls_left_rpt_20c()
->set_vehicle_fault(vehicle_fault(bytes, length));
chassis->mutable_lexus()
->mutable_dash_controls_left_rpt_20c()
->set_pacmod_fault(pacmod_fault(bytes, length));
chassis->mutable_lexus()
->mutable_dash_controls_left_rpt_20c()
->set_override_active(override_active(bytes, length));
chassis->mutable_lexus()
->mutable_dash_controls_left_rpt_20c()
->set_output_reported_fault(output_reported_fault(bytes, length));
chassis->mutable_lexus()
->mutable_dash_controls_left_rpt_20c()
->set_input_output_fault(input_output_fault(bytes, length));
chassis->mutable_lexus()->mutable_dash_controls_left_rpt_20c()->set_enabled(
enabled(bytes, length));
chassis->mutable_lexus()
->mutable_dash_controls_left_rpt_20c()
->set_command_output_fault(command_output_fault(bytes, length));
}
// config detail: {'name': 'output_value', 'enum': {0:
// 'OUTPUT_VALUE_DASH_CONTROL_NONE', 1: 'OUTPUT_VALUE_DASH_CONTROL_OK', 2:
// 'OUTPUT_VALUE_DASH_CONTROL_LEFT', 3: 'OUTPUT_VALUE_DASH_CONTROL_RIGHT', 4:
// 'OUTPUT_VALUE_DASH_CONTROL_UP', 5: 'OUTPUT_VALUE_DASH_CONTROL_DOWN'},
// 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'offset': 0.0,
// 'physical_range': '[0|255]', 'bit': 31, 'type': 'enum', 'order': 'motorola',
// 'physical_unit': ''}
Dash_controls_left_rpt_20c::Output_valueType
Dashcontrolsleftrpt20c::output_value(const std::uint8_t* bytes,
int32_t length) const {
Byte t0(bytes + 3);
int32_t x = t0.get_byte(0, 8);
Dash_controls_left_rpt_20c::Output_valueType ret =
static_cast<Dash_controls_left_rpt_20c::Output_valueType>(x);
return ret;
}
// config detail: {'name': 'commanded_value', 'enum': {0:
// 'COMMANDED_VALUE_DASH_CONTROL_NONE', 1: 'COMMANDED_VALUE_DASH_CONTROL_OK', 2:
// 'COMMANDED_VALUE_DASH_CONTROL_LEFT', 3: 'COMMANDED_VALUE_DASH_CONTROL_RIGHT',
// 4: 'COMMANDED_VALUE_DASH_CONTROL_UP', 5:
// 'COMMANDED_VALUE_DASH_CONTROL_DOWN'}, 'precision': 1.0, 'len': 8,
// 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|255]', 'bit':
// 23, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''}
Dash_controls_left_rpt_20c::Commanded_valueType
Dashcontrolsleftrpt20c::commanded_value(const std::uint8_t* bytes,
int32_t length) const {
Byte t0(bytes + 2);
int32_t x = t0.get_byte(0, 8);
Dash_controls_left_rpt_20c::Commanded_valueType ret =
static_cast<Dash_controls_left_rpt_20c::Commanded_valueType>(x);
return ret;
}
// config detail: {'name': 'manual_input', 'enum': {0:
// 'MANUAL_INPUT_DASH_CONTROL_NONE', 1: 'MANUAL_INPUT_DASH_CONTROL_OK', 2:
// 'MANUAL_INPUT_DASH_CONTROL_LEFT', 3: 'MANUAL_INPUT_DASH_CONTROL_RIGHT', 4:
// 'MANUAL_INPUT_DASH_CONTROL_UP', 5: 'MANUAL_INPUT_DASH_CONTROL_DOWN'},
// 'precision': 1.0, 'len': 8, 'is_signed_var': False, 'offset': 0.0,
// 'physical_range': '[0|255]', 'bit': 15, 'type': 'enum', 'order': 'motorola',
// 'physical_unit': ''}
Dash_controls_left_rpt_20c::Manual_inputType
Dashcontrolsleftrpt20c::manual_input(const std::uint8_t* bytes,
int32_t length) const {
Byte t0(bytes + 1);
int32_t x = t0.get_byte(0, 8);
Dash_controls_left_rpt_20c::Manual_inputType ret =
static_cast<Dash_controls_left_rpt_20c::Manual_inputType>(x);
return ret;
}
// config detail: {'name': 'vehicle_fault', 'offset': 0.0, 'precision': 1.0,
// 'len': 1, 'is_signed_var': False, 'physical_range': '[0|1]', 'bit': 6,
// 'type': 'bool', 'order': 'motorola', 'physical_unit': ''}
bool Dashcontrolsleftrpt20c::vehicle_fault(const std::uint8_t* bytes,
int32_t length) const {
Byte t0(bytes + 0);
int32_t x = t0.get_byte(6, 1);
bool ret = x;
return ret;
}
// config detail: {'name': 'pacmod_fault', 'offset': 0.0, 'precision': 1.0,
// 'len': 1, 'is_signed_var': False, 'physical_range': '[0|1]', 'bit': 5,
// 'type': 'bool', 'order': 'motorola', 'physical_unit': ''}
bool Dashcontrolsleftrpt20c::pacmod_fault(const std::uint8_t* bytes,
int32_t length) const {
Byte t0(bytes + 0);
int32_t x = t0.get_byte(5, 1);
bool ret = x;
return ret;
}
// config detail: {'name': 'override_active', 'offset': 0.0, 'precision': 1.0,
// 'len': 1, 'is_signed_var': False, 'physical_range': '[0|1]', 'bit': 1,
// 'type': 'bool', 'order': 'motorola', 'physical_unit': ''}
bool Dashcontrolsleftrpt20c::override_active(const std::uint8_t* bytes,
int32_t length) const {
Byte t0(bytes + 0);
int32_t x = t0.get_byte(1, 1);
bool ret = x;
return ret;
}
// config detail: {'name': 'output_reported_fault', 'offset': 0.0,
// 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'physical_range':
// '[0|1]', 'bit': 4, 'type': 'bool', 'order': 'motorola', 'physical_unit': ''}
bool Dashcontrolsleftrpt20c::output_reported_fault(const std::uint8_t* bytes,
int32_t length) const {
Byte t0(bytes + 0);
int32_t x = t0.get_byte(4, 1);
bool ret = x;
return ret;
}
// config detail: {'name': 'input_output_fault', 'offset': 0.0,
// 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'physical_range':
// '[0|1]', 'bit': 3, 'type': 'bool', 'order': 'motorola', 'physical_unit': ''}
bool Dashcontrolsleftrpt20c::input_output_fault(const std::uint8_t* bytes,
int32_t length) const {
Byte t0(bytes + 0);
int32_t x = t0.get_byte(3, 1);
bool ret = x;
return ret;
}
// config detail: {'name': 'enabled', 'offset': 0.0, 'precision': 1.0, 'len': 1,
// 'is_signed_var': False, 'physical_range': '[0|1]', 'bit': 0, 'type': 'bool',
// 'order': 'motorola', 'physical_unit': ''}
bool Dashcontrolsleftrpt20c::enabled(const std::uint8_t* bytes,
int32_t length) const {
Byte t0(bytes + 0);
int32_t x = t0.get_byte(0, 1);
bool ret = x;
return ret;
}
// config detail: {'name': 'command_output_fault', 'offset': 0.0,
// 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'physical_range':
// '[0|1]', 'bit': 2, 'type': 'bool', 'order': 'motorola', 'physical_unit': ''}
bool Dashcontrolsleftrpt20c::command_output_fault(const std::uint8_t* bytes,
int32_t length) const {
Byte t0(bytes + 0);
int32_t x = t0.get_byte(2, 1);
bool ret = x;
return ret;
}
} // namespace lexus
} // namespace canbus
} // namespace apollo
| 3,618 |
305 | <reponame>IntelAI/OpenVINO-model-server
/* Copyright 2017 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
//*****************************************************************************
// Copyright 2021 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#include <chrono>
#include <fstream>
#include <iostream>
#include <memory>
#include "google/protobuf/map.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/util/command_line_flags.h"
#include "tensorflow_serving/apis/prediction_service.grpc.pb.h"
#include "common.hpp"
#include "grpcpp/create_channel.h"
#include "grpcpp/security/credentials.h"
#include "opencv2/opencv.hpp"
using grpc::Channel;
using grpc::ClientContext;
using grpc::Status;
using tensorflow::serving::PredictionService;
using tensorflow::serving::PredictRequest;
using tensorflow::serving::PredictResponse;
class ServingClient {
std::unique_ptr<PredictionService::Stub> stub_;
public:
ServingClient(std::shared_ptr<Channel> channel) :
stub_(PredictionService::NewStub(channel)) {}
static tensorflow::int64 argmax(const tensorflow::Tensor& tensor) {
float topConfidence = 0;
tensorflow::int64 topLabel = -1;
for (tensorflow::int64 i = 0; i < tensor.NumElements(); i++) {
float confidence = ((float*)tensor.data())[i];
if (topLabel == -1 || topConfidence < confidence) {
topLabel = i;
topConfidence = confidence;
}
}
return topLabel;
}
// Pre-processing function for binary images.
// Images loaded from disk are packed into gRPC request proto.
bool prepareInputs(google::protobuf::Map<tensorflow::string, tensorflow::TensorProto>& inputs, const BinaryData& entry, const tensorflow::string& inputName) {
tensorflow::TensorProto proto;
proto.set_dtype(tensorflow::DataType::DT_STRING);
proto.add_string_val(entry.imageData.get(), entry.fileSize);
proto.mutable_tensor_shape()->add_dim()->set_size(1);
inputs[inputName] = proto;
return true;
}
// Pre-processing function for images in array format.
// Images loaded from disk are packed into tensor_content in plain array format (using OpenCV) either in NCHW or NHWC layout.
bool prepareInputs(google::protobuf::Map<tensorflow::string, tensorflow::TensorProto>& inputs, const CvMatData& entry, const tensorflow::string& inputName) {
tensorflow::TensorProto proto;
proto.set_dtype(tensorflow::DataType::DT_FLOAT);
size_t byteSize = entry.image.total() * entry.image.elemSize();
proto.mutable_tensor_content()->assign((char*)entry.image.data, byteSize);
proto.mutable_tensor_shape()->add_dim()->set_size(1);
if (entry.layout == "nchw") {
proto.mutable_tensor_shape()->add_dim()->set_size(entry.image.channels());
proto.mutable_tensor_shape()->add_dim()->set_size(entry.image.cols);
proto.mutable_tensor_shape()->add_dim()->set_size(entry.image.rows);
} else {
proto.mutable_tensor_shape()->add_dim()->set_size(entry.image.cols);
proto.mutable_tensor_shape()->add_dim()->set_size(entry.image.rows);
proto.mutable_tensor_shape()->add_dim()->set_size(entry.image.channels());
}
inputs[inputName] = proto;
return true;
}
// Post-processing function for classification.
// Most probable label is selected from the output.
bool interpretOutputs(google::protobuf::Map<tensorflow::string, tensorflow::TensorProto>& outputs, const tensorflow::string& outputName, tensorflow::int64& predictedLabel) {
auto it = outputs.find(outputName);
if (it == outputs.end()) {
std::cout << "cannot find output " << outputName << std::endl;
return false;
}
tensorflow::TensorProto& resultTensorProto = it->second;
if (resultTensorProto.dtype() != tensorflow::DataType::DT_FLOAT) {
std::cout << "result has non-float datatype" << std::endl;
return false;
}
tensorflow::Tensor tensor;
bool converted = tensor.FromProto(resultTensorProto);
if (!converted) {
std::cout << "the result tensor[" << it->first << "] convert failed." << std::endl;
return false;
}
predictedLabel = this->argmax(tensor);
return true;
}
template <class T>
bool predict(
const tensorflow::string& modelName,
const tensorflow::string& inputName,
const tensorflow::string& outputName,
const T& entry,
bool& isLabelCorrect) {
PredictRequest predictRequest;
PredictResponse response;
ClientContext context;
predictRequest.mutable_model_spec()->set_name(modelName);
predictRequest.mutable_model_spec()->set_signature_name("serving_default");
google::protobuf::Map<tensorflow::string, tensorflow::TensorProto>& inputs = *predictRequest.mutable_inputs();
// Pre-processing step.
// Packing image into gRPC message.
this->prepareInputs(inputs, entry, inputName);
// Actual predict request.
auto start = std::chrono::high_resolution_clock::now();
Status status = stub_->Predict(&context, predictRequest, &response);
auto duration = std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::high_resolution_clock::now() - start);
// gRPC error handling.
if (!status.ok()) {
std::cout << "gRPC call return code: " << status.error_code() << ": "
<< status.error_message() << std::endl;
return false;
}
std::cout << "call predict ok" << std::endl;
std::cout << "call predict time: " << duration.count() / 1000 << "ms" << std::endl;
std::cout << "outputs size is " << response.outputs_size() << std::endl;
// Post-processing step.
// Extracting most probable label from classification model output.
tensorflow::int64 predictedLabel = -1;
if (!this->interpretOutputs(*response.mutable_outputs(), outputName, predictedLabel)) {
return false;
}
isLabelCorrect = predictedLabel == entry.expectedLabel;
return true;
}
template <class T>
static void start(
const tensorflow::string& address,
const tensorflow::string& modelName,
const tensorflow::string& inputName,
const tensorflow::string& outputName,
const std::vector<T>& entries,
tensorflow::int64 iterations) {
auto begin = std::chrono::high_resolution_clock::now();
tensorflow::int64 correctLabels = 0;
ServingClient client(grpc::CreateChannel(address, grpc::InsecureChannelCredentials()));
for (tensorflow::int64 i = 0; i < iterations; i++) {
bool isLabelCorrect = false;
if (!client.predict(modelName, inputName, outputName, entries[i % entries.size()], isLabelCorrect)) {
return;
}
if (isLabelCorrect) {
correctLabels++;
}
}
auto duration = std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::high_resolution_clock::now() - begin);
std::cout << "Overall accuracy: " << (correctLabels * 100) / iterations << "%" << std::endl;
std::cout << "Total time divided by number of requests: " << (duration.count() / 1000) / iterations << "ms" << std::endl;
}
};
int main(int argc, char** argv) {
tensorflow::string address = "localhost";
tensorflow::string port = "9000";
tensorflow::string modelName = "resnet";
tensorflow::string inputName = "0";
tensorflow::string outputName = "1463";
tensorflow::int64 iterations = 0;
tensorflow::string imagesListPath = "input_images.txt";
tensorflow::string layout = "binary";
tensorflow::int64 width = 224;
tensorflow::int64 height = 224;
std::vector<tensorflow::Flag> flagList = {
tensorflow::Flag("grpc_address", &address, "url to grpc service"),
tensorflow::Flag("grpc_port", &port, "port to grpc service"),
tensorflow::Flag("model_name", &modelName, "model name to request"),
tensorflow::Flag("input_name", &inputName, "input tensor name with image"),
tensorflow::Flag("output_name", &outputName, "output tensor name with classification result"),
tensorflow::Flag("iterations", &iterations, "number of images per thread, by default each thread will use all images from list"),
tensorflow::Flag("images_list", &imagesListPath, "path to a file with a list of labeled images"),
tensorflow::Flag("layout", &layout, "binary, nhwc or nchw"),
tensorflow::Flag("width", &width, "input images width will be resized to this value; not applied to binary input"),
tensorflow::Flag("height", &height, "input images height will be resized to this value; not applied to binary input")};
tensorflow::string usage = tensorflow::Flags::Usage(argv[0], flagList);
const bool result = tensorflow::Flags::Parse(&argc, argv, flagList);
if (!result || imagesListPath.empty() || iterations < 0 || (layout != "binary" && layout != "nchw" && layout != "nhwc") || width <= 0 || height <= 0) {
std::cout << usage;
return -1;
}
std::vector<Entry> entries;
if (!readImagesList(imagesListPath, entries)) {
std::cout << "Error parsing images_list" << std::endl;
return -1;
}
if (entries.empty()) {
std::cout << "Empty images_list" << std::endl;
return -1;
}
std::cout
<< "Address: " << address << std::endl
<< "Port: " << port << std::endl
<< "Images list path: " << imagesListPath << std::endl
<< "Layout: " << layout << std::endl;
const tensorflow::string host = address + ":" + port;
if (iterations == 0) {
iterations = entries.size();
}
if (layout == "binary") {
std::vector<BinaryData> images;
if (!readImagesBinary(entries, images)) {
std::cout << "Error reading binary images" << std::endl;
return -1;
}
ServingClient::start(host, modelName, inputName, outputName, images, iterations);
} else {
std::vector<CvMatData> images;
if (!readImagesCvMat(entries, images, layout, width, height)) {
std::cout << "Error reading binary images" << std::endl;
return -1;
}
ServingClient::start(host, modelName, inputName, outputName, images, iterations);
}
return 0;
}
| 4,560 |
5,169 | {
"name": "TBXML",
"version": "1.4",
"license": "MIT",
"summary": "A fast XML parser.",
"homepage": "http://www.tbxml.co.uk",
"authors": {
"<NAME>": "<EMAIL>"
},
"source": {
"git": "https://github.com/steipete/TBXML.git",
"commit": "fc2db6c94e87de3d1e0fff50baf762397bc9e687"
},
"description": "\n TBXML is a light-weight XML document parser written in Objective-C \n designed for use on Apple iPad, iPhone & iPod Touch devices. TBXML \n aims to provide the fastest possible XML parsing whilst utilising \n the fewest resources. This requirement for absolute efficiency is \n achieved at the expense of XML validation and modification. It is \n not possible to modify and generate valid XML from a TBXML object \n and no validation is performed whatsoever whilst importing and \n parsing an XML document.\n ",
"platforms": {
"ios": null
},
"source_files": "*.{h,m}",
"libraries": "z",
"requires_arc": false
}
| 343 |
713 | <filename>leetcode.com/python/428_Serialize_and_Deserialize_N-ary_Tree.py<gh_stars>100-1000
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
# Idea: preorder recursive traversal; add number of children after root val, in order to know when to terminate.
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: Node
:rtype: str
"""
nodeList = []
self.serializeHelper(root, nodeList)
return ','.join(map(str, nodeList))
def serializeHelper(self, root, nodeList):
if root is None:
return
nodeList.append(root.val)
nodeList.append(len(root.children))
for child in root.children:
self.serializeHelper(child, nodeList)
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: Node
"""
if len(data) <= 0:
return None
nodeList = data.split(",")
currentNodeIndexs = [0]
deserializedData = self.deserializeHelper(nodeList, currentNodeIndexs)
return deserializedData
def deserializeHelper(self, nodeList, currentNodeIndexs):
if currentNodeIndexs[0] == len(nodeList):
return None
root = Node(int(nodeList[currentNodeIndexs[0]]), [])
currentNodeIndexs[0] += 1
childrenSize = int(nodeList[currentNodeIndexs[0]])
currentNodeIndexs[0] += 1
for index in range(childrenSize):
root.children.append(self.deserializeHelper(nodeList, currentNodeIndexs))
return root
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.serialize(root)) | 768 |
799 | import json
import io
import dateparser
import pytest
from freezegun import freeze_time
import demistomock as demisto
def util_load_json(path):
with io.open(path, mode='r', encoding='utf-8') as f:
return json.loads(f.read())
QUERY_STRING_CASES = [
(
{'query': 'chrome.exe'}, False, # case both query and params
'chrome.exe' # expected
),
(
{'hostname': 'ec2amaz-l4c2okc'}, False, # case only params
'hostname:ec2amaz-l4c2okc' # expected
),
(
{}, True, # case no params
'' # expected
)
]
@pytest.mark.parametrize('params, empty, expected_results', QUERY_STRING_CASES)
def test_create_query_string(params, empty, expected_results):
"""
Given:
- A search task's parameters
When:
- running commands using filter arguments
Then:
- validating the query string containing the params
"""
from CarbonBlackResponseV2 import _create_query_string
query_string = _create_query_string(params, allow_empty_params=empty)
assert query_string == expected_results
QUERY_STRING_ADD_CASES = [
(
'chrome.exe', # one param in query
{'test': 'example'}, # adding param
'(chrome.exe) AND test:example' # expected
),
(
'', # no query
{'test': 'example'}, # adding param
'test:example' # expected
),
(
'chrome.exe', # one param in query
{}, # adding empty param
'chrome.exe' # expected
),
]
@pytest.mark.parametrize('query, params, expected_results', QUERY_STRING_ADD_CASES)
def test_add_to_current_query(query, params, expected_results):
from CarbonBlackResponseV2 import _add_to_current_query
query_string = _add_to_current_query(query, params)
assert query_string == expected_results
QUERY_STRING_CASES_FAILS = [
(
{'hostname': 'ec2amaz-l4c2okc', 'query': 'chrome.exe'}, False, # case both query and params
'Carbon Black EDR - Searching with both query and other filters is not allowed. '
'Please provide either a search query or one of the possible filters.' # expected
),
({}, False, 'Carbon Black EDR - Search without any filter is not permitted.')]
@pytest.mark.parametrize('params, empty, expected_results', QUERY_STRING_CASES_FAILS)
def test_fail_create_query_string(params, empty, expected_results):
"""
Given:
- En empty dictionary of params
When:
- running commands using filter arguments
Then:
- validating the function fails
"""
from CarbonBlackResponseV2 import _create_query_string
from CommonServerPython import DemistoException
with pytest.raises(DemistoException) as e:
_create_query_string(params, allow_empty_params=empty)
assert str(e.value) == expected_results
PARSE_FIELD_CASES = [
('x.x.x.x,06d3d4a5ba28|', ',', 1, '|', '06d3d4a5ba28'),
('06d3d4a5ba28|', ',', 0, '|', '06d3d4a5ba28'),
('06d3d4a5ba28^&*', ',', 0, '&^*', '06d3d4a5ba28'),
]
@pytest.mark.parametrize('field, sep, index_after_split, chars_to_remove, expected', PARSE_FIELD_CASES)
def test_parse_field(field, sep, index_after_split, chars_to_remove, expected):
"""
Given:
- A field with x.x.x.x,y| format
When:
- running Endpoints command
Then:
- validate only the ip section returns
"""
from CarbonBlackResponseV2 import _parse_field
res = _parse_field(field, sep, index_after_split, chars_to_remove)
assert res == expected
@pytest.mark.parametrize('isolation_activated, is_isolated, expected',
[(0, 1, 'Pending unisolation'), (0, 0, 'No'), (1, 0, 'Pending isolation'), (1, 1, 'Yes')])
def test_get_isolation_status_field(isolation_activated, is_isolated, expected):
"""
Given:
- A sensor isolation configuration
When:
- getting/ setting isolation status for a sensor
Then:
- validate status according to API.
"""
from CarbonBlackResponseV2 import _get_isolation_status_field
status = _get_isolation_status_field(isolation_activated, is_isolated)
assert status == expected
''' ProcessEventDetail Tests'''
FILEMOD_CASES = [
(
"1|2013-09-16 07:11:58.000000|test_path.dll|||false", # case only one valid string
[{'event_time': '2013-09-16 07:11:58.000000',
'file_path': 'test_path.dll',
'file_type': '',
'flagged_as_potential_tamper_attempt': 'false',
'md5_after_last_write': '',
'operation_type': 'Created the file'}] # expected
)
]
FILEMOD_BAD_CASES = [
(
"1|2013-09-16 07:11:58.000000|test_path.dll||false", # case missing field
'Carbon Black EDR - Missing details. Ignoring entry: 1|2013-09-16 07:11:58.000000|test_path.dll||false.'
# error expected
)
]
@pytest.mark.parametrize('data_str, expected', FILEMOD_CASES)
def test_filemod(data_str, expected):
"""
Given:
- A process event data containing filemod field
When:
- formatting the data to correct format
Then:
- validating the new filemod field contains json with correctly mapped data
"""
from CarbonBlackResponseV2 import filemod_complete
res = filemod_complete(data_str).format()
assert res == expected
@pytest.mark.parametrize('data_str, expected', FILEMOD_BAD_CASES)
def test_fail_filemod(mocker, data_str, expected):
"""
Given:
- A process event data containing invalid filemod field
When:
- formatting the data to correct format
Then:
- validates when field in the response are missing, the error will show and the value be skipped.
"""
from CarbonBlackResponseV2 import filemod_complete
demisto_mocker = mocker.patch.object(demisto, 'debug')
filemod_complete(data_str)
assert demisto_mocker.call_args[0][0] == expected
MODLOAD_CASES = [
(
'2013-09-19 22:07:07.000000|f404e59db6a0f122ab26bf4f3e2fd0fa|test_path.dll', # case valid response
[{'event_time': '2013-09-19 22:07:07.000000',
'loaded_module_full_path': 'test_path.dll',
'loaded_module_md5': 'f404e59db6a0f122ab26bf4f3e2fd0fa'}] # expected
)
]
@pytest.mark.parametrize('data_str, expected', MODLOAD_CASES)
def test_modload(data_str, expected):
"""
Given:
- A process event data containing modload field
When:
- formatting the data to correct format
Then:
- validating the new modload field contains json with correctly mapped data
"""
from CarbonBlackResponseV2 import modload_complete
res = modload_complete(data_str).format()
assert res == expected
REGMOD_CASES = [
(
"2|2013-09-19 22:07:07.000000|test_path",
[{'event_time': '2013-09-19 22:07:07.000000',
'operation_type': 'First wrote to the file',
'registry_key_path': 'test_path'}]
)
]
@pytest.mark.parametrize('data_str, expected', REGMOD_CASES)
def test_regmod(data_str, expected):
"""
Given:
- A process event data containing regmod field
When:
- formatting the data to correct format
Then:
- validating the new regmod field contains json with correctly mapped data
"""
from CarbonBlackResponseV2 import regmod_complete
res = regmod_complete(data_str).format()
assert res == expected
CROSSPROC_CASES = [
(
"ProcessOpen|2014-01-23 09:19:08.331|00000177-0000-0258-01cf-c209d9f1c431|204f3f58212b3e422c90bd9691a2df28|"
"test_path.exe|1|2097151|false",
[{'ProcessOpen_sub-type': 'handle open to process',
'cross-process_access_type': 'ProcessOpen',
'event_time': '2014-01-23 09:19:08.331',
'flagged_as_potential_tamper_attempt': 'false',
'requested_access_priviledges': '2097151',
'targeted_process_md5': '204f3f58212b3e422c90bd9691a2df28',
'targeted_process_path': 'test_path.exe',
'targeted_process_unique_id': '00000177-0000-0258-01cf-c209d9f1c431'}]
)
]
@pytest.mark.parametrize('data_str, expected', CROSSPROC_CASES)
def test_crossproc(data_str, expected):
"""
Given:
- A process event data containing crossproc field
When:
- formatting the data to correct format
Then:
- validating the new crossproc field contains json with correctly mapped data
"""
from CarbonBlackResponseV2 import crossproc_complete
res = crossproc_complete(data_str).format()
assert res == expected
@freeze_time("2021-03-14T13:34:14.758295Z")
def test_fetch_incidents_first_fetch(mocker):
"""
Given
fetch incidents command running for the first time.
When
mock the Client's http_request.
Then
validate fetch incidents command using the Client gets all 3 relevant incidents
"""
from CarbonBlackResponseV2 import fetch_incidents, Client
alerts = util_load_json('test_data/commands_test_data.json').get('fetch_incident_data')
client = Client(base_url="url", apitoken="api_key", use_ssl=True, use_proxy=False)
mocker.patch.object(Client, 'get_alerts', return_value=alerts)
first_fetch_time = '7 days'
_, incidents = fetch_incidents(client, last_run={}, first_fetch_time=first_fetch_time, max_results='3')
assert len(incidents) == 3
assert incidents[0].get('name') == 'Carbon Black EDR: 1 svchost.exe'
@freeze_time("2021-03-16T13:34:14.758295Z")
def test_fetch_incidents(mocker):
"""
Given
fetch incidents command running for a second time (some incidents already been fetched).
When
mock the Client's http_request, and there are incident prior to last fetch
Then
validate fetch incidents command using the Client only returns 1 new incidents
"""
from CarbonBlackResponseV2 import fetch_incidents, Client
last_run = {'last_fetch': dateparser.parse('2021-03-12T14:13:20+00:00').timestamp()}
alerts = util_load_json('test_data/commands_test_data.json').get('fetch_incident_data')
client = Client(base_url="url", apitoken="api_key", use_ssl=True, use_proxy=False)
mocker.patch.object(Client, 'get_alerts', return_value=alerts)
first_fetch_time = '7 days'
last_fetch, incidents = fetch_incidents(client, last_run=last_run, first_fetch_time=first_fetch_time,
max_results='3')
assert len(incidents) == 1
assert incidents[0].get('name') == 'Carbon Black EDR: 2 svchost.exe'
assert last_fetch == {'last_fetch': 1615648046.79}
def test_quarantine_device_command_not_have_id(mocker):
"""
Given:
A sensor id
When:
_get_sensor_isolation_change_body in a quarantine_device_command and unquarantine_device_command
Then:
Assert the 'id' field is not in the request body.
"""
from CarbonBlackResponseV2 import _get_sensor_isolation_change_body, Client
client = Client(base_url="url", apitoken="api_key", use_ssl=True, use_proxy=False)
mocker.patch.object(Client, 'get_sensors', return_value=(1, [{"id": "some_id", "some_other_stuff": "some"}]))
sensor_data = _get_sensor_isolation_change_body(client, 5, False)
assert "id" not in sensor_data
def test_get_sensor_isolation_change_body_compatible(mocker):
"""
Given:
A sensor id
When:
Running _get_sensor_isolation_change_body in a quarantine_device_command and unquarantine_device_command
Then:
Assert the the request body is in the compatible format for version 7.5 and 6.2.
"""
from CarbonBlackResponseV2 import _get_sensor_isolation_change_body, Client
client = Client(base_url="url", apitoken="api_key", use_ssl=True, use_proxy=False)
mocker.patch.object(Client, 'get_sensors', return_value=(1, [{"id": "some_id", "group_id": "some_group_id",
"some_other_stuff": "some"}]))
sensor_data = _get_sensor_isolation_change_body(client, 5, False)
assert sensor_data == {'group_id': 'some_group_id', 'network_isolation_enabled': False}
| 5,190 |
60,067 |
import caffe2.python._import_c_extension as C
CAFFE2_NO_OPERATOR_SCHEMA = C.define_caffe2_no_operator_schema
build_options = C.get_build_options()
| 61 |
2,542 | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#pragma once
namespace ServiceModel
{
class ReplicaResourceQueryResult
: public ModelV2::ServiceReplicaDescription
{
public:
ReplicaResourceQueryResult() = default;
ReplicaResourceQueryResult(ReplicaResourceQueryResult const &) = default;
ReplicaResourceQueryResult(ReplicaResourceQueryResult && other) = default;
ReplicaResourceQueryResult(std::wstring const & replicaName)
: ModelV2::ServiceReplicaDescription(replicaName) {}
std::wstring CreateContinuationToken() const;
};
QUERY_JSON_LIST(ReplicaResourceList, ReplicaResourceQueryResult)
}
| 265 |
4,140 | <reponame>FANsZL/hive
/*
* 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.hadoop.hive.metastore;
import javax.security.sasl.AuthenticationException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hive.metastore.conf.MetastoreConf;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This authentication provider implements the {@code CONFIG} authentication. It allows a {@link
* MetaStorePasswdAuthenticationProvider} to be specified at configuration time which may
* additionally
* implement {@link org.apache.hadoop.conf.Configurable Configurable} to grab HMS's {@link
* org.apache.hadoop.conf.Configuration Configuration}.
*/
public class MetaStoreConfigAuthenticationProviderImpl implements MetaStorePasswdAuthenticationProvider {
private final String userName;
private final String password;
protected static final Logger LOG = LoggerFactory.getLogger(MetaStoreConfigAuthenticationProviderImpl.class);
@SuppressWarnings("unchecked")
MetaStoreConfigAuthenticationProviderImpl(Configuration conf) throws AuthenticationException {
userName = MetastoreConf.getVar(conf, MetastoreConf.ConfVars.THRIFT_AUTH_CONFIG_USERNAME);
password = MetastoreConf.getVar(conf, MetastoreConf.ConfVars.THRIFT_AUTH_CONFIG_PASSWORD);
if (null == userName || userName.isEmpty()) {
throw new AuthenticationException("No username specified in " +
MetastoreConf.ConfVars.THRIFT_AUTH_CONFIG_USERNAME);
}
if (null == password) {
throw new AuthenticationException("No password specified in " +
MetastoreConf.ConfVars.THRIFT_AUTH_CONFIG_PASSWORD);
}
}
@Override
public void authenticate(String authUser, String authPassword) throws AuthenticationException {
if (!userName.equals(authUser)) {
LOG.debug("Invalid user " + authUser);
throw new AuthenticationException("Invalid credentials");
}
if (!password.equals(authPassword)) {
LOG.debug("Invalid password for user " + authUser);
throw new AuthenticationException("Invalid credentials");
}
LOG.debug("User " + authUser + " successfully authenticated.");
}
}
| 865 |
360 | /*
* Copyright (c) 2020 Huawei Technologies Co.,Ltd.
*
* openGauss is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
* -------------------------------------------------------------------------
*
* column_ref_data.h
*
* IDENTIFICATION
* src\common\interfaces\libpq\client_logic_expressions\column_ref_data.h
*
* -------------------------------------------------------------------------
*/
#ifndef COLUMN_REF_DATA_H
#define COLUMN_REF_DATA_H
#include "libpq-int.h"
#include "c.h"
#include "client_logic_cache/icached_column.h"
class ICachedColumn;
class ColumnRefData {
public:
ColumnRefData();
~ColumnRefData() {}
NameData m_catalog_name;
NameData m_schema_name;
NameData m_table_name;
NameData m_column_name;
char m_alias_fqdn[NAMEDATALEN * 4]; /* this is usually col fqdn */
bool compare_with_cachecolumn(const ICachedColumn *cache_column, const char *coname_inquery = NULL) const;
};
#endif
| 455 |
1,962 | package com.bolingcavalry.springbootrediskyrodemo.config;
import com.bolingcavalry.springbootrediskyrodemo.Serializer.KryoRedisSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* @Description : Redis的配置
* @Author : <EMAIL>
* @Date : 2018-05-06 21:39
*/
@Configuration
public class RedisConfig {
/**
* redisTemplate 序列化使用的Serializeable, 存储二进制字节码, 所以自定义序列化类
* @param redisConnectionFactory
* @return
*/
@Bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
// redis value使用的序列化器
template.setValueSerializer(new KryoRedisSerializer<>(Object.class));
// redis key使用的序列化器
template.setKeySerializer(new StringRedisSerializer());
template.afterPropertiesSet();
return template;
}
}
| 536 |
340 | <reponame>gajubadge11/HackerRank-1<filename>interview-preparation-kit/largest-rectangle.py
#!/bin/python3
import sys
def largestRectangle(h):
res = 0
for i in range(len(h)):
length = 0
for j in range(i, -1, -1):
if h[j] >= h[i]:
length += 1
else:
break
for j in range(i+1, len(h)):
if h[j] >= h[i]:
length += 1
else:
break
res = max(res, length*h[i])
return res
if __name__ == "__main__":
n = int(input().strip())
h = list(map(int, input().strip().split(' ')))
result = largestRectangle(h)
print(result)
| 409 |
3,631 | /*
* Copyright 2017 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.compiler.integrationtests.drl;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.drools.compiler.compiler.DrlParser;
import org.drools.compiler.lang.descr.AttributeDescr;
import org.drools.compiler.lang.descr.PackageDescr;
import org.drools.compiler.lang.descr.RuleDescr;
import org.drools.testcoverage.common.model.Address;
import org.drools.testcoverage.common.model.Cheese;
import org.drools.testcoverage.common.model.Person;
import org.drools.testcoverage.common.model.State;
import org.drools.testcoverage.common.util.KieBaseTestConfiguration;
import org.drools.testcoverage.common.util.KieBaseUtil;
import org.drools.testcoverage.common.util.TestParametersUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.kie.api.KieBase;
import org.kie.api.runtime.KieSession;
import org.kie.internal.builder.conf.LanguageLevelOption;
import static org.junit.Assert.assertEquals;
@RunWith(Parameterized.class)
public class NestingTest {
private final KieBaseTestConfiguration kieBaseTestConfiguration;
public NestingTest(final KieBaseTestConfiguration kieBaseTestConfiguration) {
this.kieBaseTestConfiguration = kieBaseTestConfiguration;
}
@Parameterized.Parameters(name = "KieBase type={0}")
public static Collection<Object[]> getParameters() {
return TestParametersUtil.getKieBaseCloudConfigurations(true);
}
@Test
public void testNesting() throws Exception {
final String drl = "package org.drools.compiler.integrationtests.drl;\n" +
"\n" +
"dialect \"mvel\"\n" +
"\n" +
"import " + Person.class.getCanonicalName() + ";\n" +
"import " + Address.class.getCanonicalName() + ";\n" +
"\n" +
"rule \"test something\"\n" +
"\n" +
" when\n" +
" p: Person( name==\"Michael\",\n" +
" (addresses[1].street == \"Low\" &&\n" +
" addresses[0].street == \"High\" )\n" +
" )\n" +
" then\n" +
" p.name = \"goober\";\n" +
" System.out.println(p.name);\n" +
" insert(new Address(\"Latona\"));\n" +
"end";
final Person p = new Person();
p.setName("Michael");
final Address add1 = new Address();
add1.setStreet("High");
final Address add2 = new Address();
add2.setStreet("Low");
final List<Address> l = new ArrayList<>();
l.add(add1);
l.add(add2);
p.setAddresses(l);
final DrlParser parser = new DrlParser(LanguageLevelOption.DRL5);
final PackageDescr desc = parser.parse(new StringReader(drl));
final List packageAttrs = desc.getAttributes();
assertEquals(1, desc.getRules().size());
assertEquals(1, packageAttrs.size());
final RuleDescr rule = desc.getRules().get(0);
final Map<String, AttributeDescr> ruleAttrs = rule.getAttributes();
assertEquals(1, ruleAttrs.size());
assertEquals("mvel", ruleAttrs.get("dialect").getValue());
assertEquals("dialect", ruleAttrs.get("dialect").getName());
final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("nesting-test", kieBaseTestConfiguration, drl);
final KieSession ksession = kbase.newKieSession();
try {
ksession.insert(p);
ksession.fireAllRules();
} finally {
ksession.dispose();
}
}
@Test
public void testNestedConditionalElements() {
final String drl = "package org.drools.compiler.integrationtests.drl;\n" +
"import " + Person.class.getCanonicalName() + ";\n" +
"import " + Cheese.class.getCanonicalName() + ";\n" +
"import " + State.class.getCanonicalName() + ";\n" +
"global java.util.List results\n" +
"\n" +
"rule \"test nested CEs\" salience 100\n" +
" when\n" +
" not ( State( $state : state ) and\n" +
" not( Person( name == $state, $likes : likes ) and\n" +
" Cheese( type == $likes ) ) )\n" +
" then\n" +
" results.add(\"OK1\");\n" +
"end";
final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("nesting-test", kieBaseTestConfiguration, drl);
final KieSession ksession = kbase.newKieSession();
try {
final List list = new ArrayList();
ksession.setGlobal("results", list);
final State state = new State("SP");
ksession.insert(state);
final Person bob = new Person(state.getState());
bob.setLikes("stilton");
ksession.insert(bob);
ksession.fireAllRules();
assertEquals(0, list.size());
ksession.insert(new Cheese(bob.getLikes(), 10));
ksession.fireAllRules();
assertEquals(1, list.size());
} finally {
ksession.dispose();
}
}
}
| 2,760 |
1,553 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
__author__ = u'<NAME>'
__copyright__ = u'2013-2019 <NAME>'
__license__ = u'MPL-1.1 OR GPL-2.0-only OR LGPL-2.1-or-later'
__all__ = (u'Trie', u'TrieNode')
class TrieNode(object):
u'Class representing a single Trie node.'
__slots__ = (u'children', u'exception', u'leaf', u'private')
def __init__(self):
self.children = None
self.exception = None
self.leaf = False
self.private = False
class Trie(object):
u'An adhoc Trie data structure to store tlds in reverse notation order.'
def __init__(self):
self.root = TrieNode()
self.__nodes = 0
def __len__(self):
return self.__nodes
def add(self, tld, private=False):
node = self.root
for part in reversed(tld.split(u'.')):
if part.startswith(u'!'):
node.exception = part[1:]
break
if (node.children is None):
node.children = {
}
child = TrieNode()
else:
child = node.children.get(part)
if (child is None):
child = TrieNode()
node.children[part] = child
node = child
node.leaf = True
if private:
node.private = True
self.__nodes += 1
| 716 |
757 | {
"关机": "shutdown -s -t 00",
"取消关机": "shutdown -a",
"锁屏": "rundll32.exe user32.dll,LockWorkStation",
"截屏": "screenshot"
} | 78 |
319 | <reponame>AurySystem/Anodyne-1-Repo
#!/usr/bin/python
#
# www.josephlandry.com
#
# buildmap.py
#
# Builds map images from Anodyne game source files.
#
# Anodyne game: http://www.anodynegame.com/
#
# The source folder should be in ./Anodyne/src/
# The map images will be outputted to ./maps/ in PNG format.
#
import os
import csv
from PIL import Image
from xml import sax
def read_layer(filename):
f = open(filename, "rb")
map_reader = csv.reader(f, delimiter=",")
map = []
for row in map_reader:
map.append(row)
f.close()
return map
def read_tileset(filename):
tilesetimage = Image.open(filename);
tilesetimage_xblocks = tilesetimage.size[0] / 16
tilesetimage_yblocks = tilesetimage.size[1] / 16
tileset = []
for i in range(tilesetimage_yblocks):
for j in range(tilesetimage_xblocks):
tile = tilesetimage.crop((j * 16, i * 16, j * 16 + 16, i * 16 + 16))
tileset.append(tile)
return tileset
def paint_with_layer(image, layer, tileset):
y_blocks = len(layer)
x_blocks = len(layer[0])
for i in range(y_blocks):
for j in range(x_blocks):
tile_index = int(layer[i][j])
tile = tileset[tile_index]
if tile_index != 0:
image.paste(tile, (j * 16, i * 16, j * 16 + 16, i * 16 + 16), tile)
def generate_map_image(map):
layer = read_layer(map["layers"][0])
tileset = read_tileset(map["tileset"])
image = Image.new("RGB", (len(layer[0]) * 16, len(layer) * 16))
paint_with_layer(image, layer, tileset)
for layerfile in map["layers"][1:]:
layer = read_layer(layerfile)
paint_with_layer(image, layer, tileset)
return image
class RegistryHandler(sax.ContentHandler):
mapname = ""
registry = {}
def startElement(self, name, attrs):
if name == "root":
pass
elif name == "map":
self.mapname = attrs["name"]
if self.mapname not in self.registry.keys():
self.registry[self.mapname] = {}
else:
if not(name in self.registry[self.mapname].keys()):
self.registry[self.mapname][name] = []
self.registry[self.mapname][name].append({"x": attrs["x"], "y": attrs["y"], "frame": attrs["frame"]})
def endElement(self, name):
pass
def read_registry():
parser = sax.make_parser()
handler = RegistryHandler()
parser.setContentHandler( handler )
parser.parse( 'Anodyne/src/global/Registry_embedXML.dat')
return handler.registry
mapfiles = [
{
"world": "APARTMENT",
"tileset": "Anodyne/src/data/TileData__Apartment_Tiles.png",
"layers": ["Anodyne/src/data/CSV_Data_APARTMENT_BG.dat", "Anodyne/src/data/CSV_Data_APARTMENT_BG2.dat", "Anodyne/src/data/CSV_Data_APARTMENT_FG.dat"]
},
{
"world": "BEACH",
"tileset": "Anodyne/src/data/TileData__Beach_Tiles.png",
"layers": ["Anodyne/src/data/CSV_Data_BEACH_BG.dat"]
},
{
"world": "BEDROOM",
"tileset": "Anodyne/src/data/TileData__Bedroom_Tiles.png",
"layers": ["Anodyne/src/data/CSV_Data_BEDROOM_BG.dat"]
},
{
"world": "BLANK",
"tileset": "Anodyne/src/data/TileData_Blank_Tiles.png",
"layers": ["Anodyne/src/data/CSV_Data_BLANK_BG.dat"]
},
{
"world": "BLUE",
"tileset": "Anodyne/src/data/TileData_Blue_Tiles.png",
"layers": ["Anodyne/src/data/CSV_Data_BLUE_BG.dat", "Anodyne/src/data/CSV_Data_BLUE_BG2.dat"]
},
{
"world": "CELL",
"tileset": "Anodyne/src/data/TileData_Cell_Tiles.png",
"layers": ["Anodyne/src/data/CSV_Data_CELL_BG.dat"]
},
{
"world": "CIRCUS",
"tileset": "Anodyne/src/data/TileData__Circus_Tiles.png",
"layers": ["Anodyne/src/data/CSV_Data_CIRCUS_BG.dat", "Anodyne/src/data/CSV_Data_CIRCUS_FG.dat"]
},
{
"world": "CLIFF",
"tileset": "Anodyne/src/data/TileData_Cliff_Tiles.png",
"layers": ["Anodyne/src/data/CSV_Data_CLIFF_BG.dat", "Anodyne/src/data/CSV_Data_CLIFF_BG2.dat"]
},
{
"world": "CROWD",
"tileset": "Anodyne/src/data/TileData__Crowd_Tiles.png",
"layers": ["Anodyne/src/data/CSV_Data_CROWD_BG.dat", "Anodyne/src/data/CSV_Data_CROWD_BG2.dat"]
},
{
"world": "DEBUG",
"tileset": "Anodyne/src/data/TileData_Debug_Tiles.png",
"layers": ["Anodyne/src/data/CSV_Data_DEBUG_BG.dat", "Anodyne/src/data/CSV_Data_DEBUG_BG2.dat", "Anodyne/src/data/CSV_Data_DEBUG_FG.dat"]
},
{
"world": "DRAWER",
"tileset": "Anodyne/src/data/TileData_BlackWhite_Tiles.png",
"layers": ["Anodyne/src/data/CSV_Data_DRAWER_BG.dat"]
},
{
"world": "FIELDS",
"tileset": "Anodyne/src/data/TileData__Fields_Tiles.png",
"layers": ["Anodyne/src/data/CSV_Data_FIELDS_BG.dat", "Anodyne/src/data/CSV_Data_FIELDS_FG.dat"]
},
{
"world": "FOREST",
"tileset": "Anodyne/src/data/TileData_Forest_Tiles.png",
"layers": ["Anodyne/src/data/CSV_Data_FOREST_BG.dat", "Anodyne/src/data/CSV_Data_FOREST_BG2.dat", "Anodyne/src/data/CSV_Data_FOREST_FG.dat"]
},
{
"world": "GO",
"tileset": "Anodyne/src/data/TileData_Go_Tiles.png",
"layers": ["Anodyne/src/data/CSV_Data_GO_BG.dat", "Anodyne/src/data/CSV_Data_GO_BG2.dat"]
},
{
"world": "HAPPY",
"tileset": "Anodyne/src/data/TileData_Happy_Tiles.png",
"layers": ["Anodyne/src/data/CSV_Data_HAPPY_BG.dat", "Anodyne/src/data/CSV_Data_HAPPY_BG2.dat"]
},
{
"world": "HOTEL",
"tileset": "Anodyne/src/data/TileData__Hotel_Tiles.png",
"layers": ["Anodyne/src/data/CSV_Data_HOTEL_BG.dat", "Anodyne/src/data/CSV_Data_HOTEL_BG2.dat", "Anodyne/src/data/CSV_Data_HOTEL_FG.dat"]
},
{
"world": "NEXUS",
"tileset": "Anodyne/src/data/TileData__Nexus_Tiles.png",
"layers": ["Anodyne/src/data/CSV_Data_NEXUS_BG.dat", "Anodyne/src/data/CSV_Data_NEXUS_FG.dat"]
},
{
"world": "OVERWORLD",
"tileset": "Anodyne/src/data/TileData__Overworld_Tiles.png",
"layers": ["Anodyne/src/data/CSV_Data_OVERWORLD_BG.dat", "Anodyne/src/data/CSV_Data_OVERWORLD_BG2.dat"]
},
{
"world": "REDCAVE",
"tileset": "Anodyne/src/data/TileData_REDCAVE_Tiles.png",
"layers": ["Anodyne/src/data/CSV_Data_REDCAVE_BG.dat", "Anodyne/src/data/CSV_Data_REDCAVE_BG2.dat"]
},
{
"world": "REDSEA",
"tileset": "Anodyne/src/data/TileData_Red_Sea_Tiles.png",
"layers": ["Anodyne/src/data/CSV_Data_REDSEA_BG.dat", "Anodyne/src/data/CSV_Data_REDSEA_FG.dat"]
},
{
"world": "SPACE",
"tileset": "Anodyne/src/data/TileData_Space_Tiles.png",
"layers": ["Anodyne/src/data/CSV_Data_SPACE_BG.dat", "Anodyne/src/data/CSV_Data_SPACE_BG2.dat", "Anodyne/src/data/CSV_Data_SPACE_FG.dat"]
},
{
"world": "STREET",
"tileset": "Anodyne/src/data/TileData__Street_Tiles.png",
"layers": ["Anodyne/src/data/CSV_Data_STREET_BG.dat", "Anodyne/src/data/CSV_Data_STREET_BG2.dat", "Anodyne/src/data/CSV_Data_STREET_FG.dat"]
},
{
"world": "SUBURB",
"tileset": "Anodyne/src/data/TileData_Suburb_Tiles.png",
"layers": ["Anodyne/src/data/CSV_Data_SUBURB_BG.dat"]
},
{
"world": "TERMINAL",
"tileset": "Anodyne/src/data/TileData_Terminal_Tiles.png",
"layers": ["Anodyne/src/data/CSV_Data_TERMINAL_BG.dat", "Anodyne/src/data/CSV_Data_TERMINAL_BG2.dat"]
},
{
"world": "WINDMILL",
"tileset": "Anodyne/src/data/TileData__Windmill_Tiles.png",
"layers": ["Anodyne/src/data/CSV_Data_WINDMILL_BG.dat", "Anodyne/src/data/CSV_Data_WINDMILL_BG2.dat"]
}
]
entities = {
"Treasure": { "image": "Anodyne/src/entity/gadget/Treasure_S_TREASURE_SPRITE.png", "tile_index": 1}
}
# build initial map images
maps = {}
for mapfile in mapfiles:
print "Processing: " + mapfile["world"]
map = generate_map_image(mapfile)
maps[mapfile["world"]] = map
# read registry XML file that contains entity information
registry = read_registry()
treasure_tiles = read_tileset("Anodyne/src/entity/gadget/Treasure_S_TREASURE_SPRITE.png");
# draw the supported entites on the maps
for worlds in registry.keys():
print "Processing entities: " + worlds
if worlds in maps.keys():
apartment = maps[worlds]
apartment_regs = registry[worlds]
if "Treasure" in apartment_regs.keys():
treasures = apartment_regs["Treasure"]
for treasure in treasures:
x = int(treasure["x"])
y = int(treasure["y"])
apartment.paste(treasure_tiles[0], (x, y, x+16, y+16), treasure_tiles[0])
# Make map directory and save images
if not os.path.exists("maps"):
os.makedirs("maps")
for map in maps.keys():
map_image = maps[map];
print "Saving " + map
map_image.save("maps/" + map + ".png", "PNG")
| 3,752 |
21,684 | <filename>src/unittest/coroutine_utils.cc
// Copyright 2010-2015 RethinkDB, all rights reserved.
#include <stdexcept>
#include "arch/runtime/coroutines.hpp"
#include "arch/runtime/runtime.hpp"
#include "arch/timing.hpp"
#include "concurrency/cond_var.hpp"
#include "time.hpp"
#include "unittest/gtest.hpp"
#include "unittest/unittest_utils.hpp"
namespace unittest {
void run_in_coro(const std::function<void()> &fun) {
run_in_thread_pool([&]() {
// `run_in_thread_pool` already spawns a coroutine for us.
ASSERT_NE(coro_t::self(), nullptr);
fun();
});
}
TEST(CoroutineUtilsTest, WithEnoughStackNoSpawn) {
int res = 0;
run_in_coro([&]() {
// This should execute directly
ASSERT_NO_CORO_WAITING;
res = call_with_enough_stack<int>([] () {
return 5;
}, 1);
});
EXPECT_EQ(res, 5);
}
TEST(CoroutineUtilsTest, WithEnoughStackNonBlocking) {
int res = 0;
run_in_coro([&]() {
ASSERT_FINITE_CORO_WAITING;
// `COROUTINE_STACK_SIZE` forces a coroutine to be spawned
res = call_with_enough_stack<int>([] () {
return 5;
}, COROUTINE_STACK_SIZE);
});
EXPECT_EQ(res, 5);
}
TEST(CoroutineUtilsTest, WithEnoughStackBlocking) {
int res = 0;
run_in_coro([&]() {
// `COROUTINE_STACK_SIZE` forces a coroutine to be spawned
res = call_with_enough_stack<int>([] () {
nap(5);
return 5;
}, COROUTINE_STACK_SIZE);
});
EXPECT_EQ(res, 5);
}
TEST(CoroutineUtilsTest, WithEnoughStackNoCoro) {
// call_with_enough_stack should still be usable if we are not in a coroutine
// (though it doesn't do much in that case).
int res = 0;
run_in_thread_pool([&]() {
struct test_message_t : public linux_thread_message_t {
void on_thread_switch() {
ASSERT_EQ(coro_t::self(), nullptr);
*out = call_with_enough_stack<int>([] () {
return 5;
}, 1);
done_cond.pulse();
}
int *out;
cond_t done_cond;
};
test_message_t thread_msg;
thread_msg.out = &res;
call_later_on_this_thread(&thread_msg);
thread_msg.done_cond.wait();
});
EXPECT_EQ(res, 5);
}
TEST(CoroutineUtilsTest, WithEnoughStackException) {
bool got_exception = false;
run_in_coro([&]() {
try {
// `COROUTINE_STACK_SIZE` forces a coroutine to be spawned
call_with_enough_stack([] () {
throw std::runtime_error("This is a test exception");
}, COROUTINE_STACK_SIZE);
} catch (const std::exception &) {
got_exception = true;
}
});
EXPECT_TRUE(got_exception);
}
// This is not really a unit test, but a micro benchmark to test the overhead
// of call_with_enough_stack. No need to run this in debug mode.
#ifdef NDEBUG
NOINLINE int test_function() {
return 1;
}
NOINLINE int test_function_blocking() {
coro_t::yield();
return 1;
}
double nanos_to_secs(int64_t nanos) {
return ticks_to_secs(ticks_t{nanos});
}
TEST(CoroutineUtilsTest, WithEnoughStackBenchmark) {
run_in_coro([&]() {
const int NUM_REPETITIONS = 1000000;
// Get the base line first
printf("Getting base line timings.\n");
int sum = 0;
ticks_t start_ticks = get_ticks();
for(int i = 0; i < NUM_REPETITIONS; ++i) {
sum += test_function();
}
double dur_base = nanos_to_secs(get_ticks().nanos - start_ticks.nanos);
EXPECT_EQ(sum, NUM_REPETITIONS);
sum = 0;
start_ticks = get_ticks();
for(int i = 0; i < NUM_REPETITIONS; ++i) {
sum += test_function_blocking();
}
double dur_base_blocking = nanos_to_secs(get_ticks().nanos - start_ticks.nanos);
EXPECT_EQ(sum, NUM_REPETITIONS);
{
printf("Test 1: call_with_enough_stack without spawning: ");
sum = 0;
start_ticks = get_ticks();
for(int i = 0; i < NUM_REPETITIONS; ++i) {
// Use lambdas because that's what we're usually going to use in
// our code.
sum += call_with_enough_stack<int>([&] () {
return test_function();
}, 1);
}
double dur = nanos_to_secs(get_ticks().nanos - start_ticks.nanos);
EXPECT_EQ(sum, NUM_REPETITIONS);
printf("%f us overhead\n",
(dur - dur_base) / NUM_REPETITIONS * 1000000);
}
{
printf("Test 2: call_with_enough_stack with spawning: ");
sum = 0;
start_ticks = get_ticks();
for(int i = 0; i < NUM_REPETITIONS; ++i) {
// Use lambdas because that's what we're usually going to use in
// our code.
sum += call_with_enough_stack<int>([&] () {
return test_function();
}, COROUTINE_STACK_SIZE);
}
double dur = nanos_to_secs(get_ticks().nanos - start_ticks.nanos);
EXPECT_EQ(sum, NUM_REPETITIONS);
printf("%f us overhead\n",
(dur - dur_base) / NUM_REPETITIONS * 1000000);
}
{
printf("Test 3: call_with_enough_stack with blocking: ");
sum = 0;
start_ticks = get_ticks();
for(int i = 0; i < NUM_REPETITIONS; ++i) {
// Use lambdas because that's what we're usually going to use in
// our code.
sum += call_with_enough_stack<int>([&] () {
return test_function_blocking();
}, COROUTINE_STACK_SIZE);
}
double dur = nanos_to_secs(get_ticks().nanos - start_ticks.nanos);
EXPECT_EQ(sum, NUM_REPETITIONS);
printf("%f us overhead\n",
(dur - dur_base_blocking) / NUM_REPETITIONS * 1000000);
}
});
}
#endif // NDEBUG
} /* namespace unittest */
| 3,072 |
66,985 | <reponame>techAi007/spring-boot
/*
* Copyright 2012-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot;
import org.junit.jupiter.api.Test;
import org.springframework.boot.context.properties.source.ConfigurationPropertySources;
import org.springframework.core.env.AbstractEnvironment;
import org.springframework.core.env.ConfigurablePropertyResolver;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.mock.env.MockPropertySource;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Base class for {@link SpringApplication} {@link Environment} tests.
*
* @author <NAME>
*/
public abstract class AbstractApplicationEnvironmentTests {
@Test
void getActiveProfilesDoesNotResolveProperty() {
StandardEnvironment environment = createEnvironment();
new MockPropertySource().withProperty("", "");
environment.getPropertySources().addFirst(
new MockPropertySource().withProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "test"));
assertThat(environment.getActiveProfiles()).isEmpty();
}
@Test
void getDefaultProfilesDoesNotResolveProperty() {
StandardEnvironment environment = createEnvironment();
new MockPropertySource().withProperty("", "");
environment.getPropertySources().addFirst(
new MockPropertySource().withProperty(AbstractEnvironment.DEFAULT_PROFILES_PROPERTY_NAME, "test"));
assertThat(environment.getDefaultProfiles()).containsExactly("default");
}
@Test
void propertyResolverIsOptimizedForConfigurationProperties() {
StandardEnvironment environment = createEnvironment();
ConfigurablePropertyResolver expected = ConfigurationPropertySources
.createPropertyResolver(new MutablePropertySources());
assertThat(environment).extracting("propertyResolver").hasSameClassAs(expected);
}
protected abstract StandardEnvironment createEnvironment();
}
| 689 |
1,033 | <filename>models/py_utils/kp_utils.py
import torch
import torch.nn as nn
from .utils import convolution, residual
class MergeUp(nn.Module):
def forward(self, up1, up2):
return up1 + up2
def make_merge_layer(dim):
return MergeUp()
def make_tl_layer(dim):
return None
def make_br_layer(dim):
return None
def make_pool_layer(dim):
return nn.MaxPool2d(kernel_size=2, stride=2)
def make_unpool_layer(dim):
return nn.Upsample(scale_factor=2)
def make_kp_layer(cnv_dim, curr_dim, out_dim):
return nn.Sequential(
convolution(3, cnv_dim, curr_dim, with_bn=False),
nn.Conv2d(curr_dim, out_dim, (1, 1))
)
def make_inter_layer(dim):
return residual(3, dim, dim)
def make_cnv_layer(inp_dim, out_dim):
return convolution(3, inp_dim, out_dim)
def _gather_feat(feat, ind, mask=None):
dim = feat.size(2)
ind = ind.unsqueeze(2).expand(ind.size(0), ind.size(1), dim)
feat = feat.gather(1, ind)
if mask is not None:
mask = mask.unsqueeze(2).expand_as(feat)
feat = feat[mask]
feat = feat.view(-1, dim)
return feat
def _nms(heat, kernel=1):
pad = (kernel - 1) // 2
hmax = nn.functional.max_pool2d(heat, (kernel, kernel), stride=1, padding=pad)
keep = (hmax == heat).float()
return heat * keep
def _left_aggregate(heat):
'''
heat: batchsize x channels x h x w
'''
shape = heat.shape
heat = heat.reshape(-1, heat.shape[3])
ret = heat.clone()
for i in range(1, heat.shape[1]):
inds = (heat[:, i] >= heat[:, i -1])
ret[:, i] += ret[:, i - 1] * inds.float()
return (ret - heat).reshape(shape)
def _right_aggregate(heat):
'''
heat: batchsize x channels x h x w
'''
shape = heat.shape
heat = heat.reshape(-1, heat.shape[3])
ret = heat.clone()
for i in range(heat.shape[1] - 2, -1, -1):
inds = (heat[:, i] >= heat[:, i +1])
ret[:, i] += ret[:, i + 1] * inds.float()
return (ret - heat).reshape(shape)
def _top_aggregate(heat):
'''
heat: batchsize x channels x h x w
'''
heat = heat.transpose(3, 2)
shape = heat.shape
heat = heat.reshape(-1, heat.shape[3])
ret = heat.clone()
for i in range(1, heat.shape[1]):
inds = (heat[:, i] >= heat[:, i - 1])
ret[:, i] += ret[:, i - 1] * inds.float()
return (ret - heat).reshape(shape).transpose(3, 2)
def _bottom_aggregate(heat):
'''
heat: batchsize x channels x h x w
'''
heat = heat.transpose(3, 2)
shape = heat.shape
heat = heat.reshape(-1, heat.shape[3])
ret = heat.clone()
for i in range(heat.shape[1] - 2, -1, -1):
inds = (heat[:, i] >= heat[:, i + 1])
ret[:, i] += ret[:, i + 1] * inds.float()
return (ret - heat).reshape(shape).transpose(3, 2)
def _h_aggregate(heat, aggr_weight=0.1):
return aggr_weight * _left_aggregate(heat) + \
aggr_weight * _right_aggregate(heat) + heat
def _v_aggregate(heat, aggr_weight=0.1):
return aggr_weight * _top_aggregate(heat) + \
aggr_weight * _bottom_aggregate(heat) + heat
def _tranpose_and_gather_feat(feat, ind):
feat = feat.permute(0, 2, 3, 1).contiguous()
feat = feat.view(feat.size(0), -1, feat.size(3))
feat = _gather_feat(feat, ind)
return feat
def _filter(heat, direction, val=0.1):
num_channels = heat.shape[1]
if direction == 'v':
kernel = torch.zeros((num_channels, num_channels, 3, 1))
for i in range(num_channels):
kernel[i, i, 0, 0] = val
kernel[i, i, 1, 0] = 1
kernel[i, i, 2, 0] = val
padding = (1, 0)
elif direction == 'h':
kernel = torch.zeros((num_channels, num_channels, 1, 3))
for i in range(num_channels):
kernel[i, i, 0, 0] = val
kernel[i, i, 0, 1] = 1
kernel[i, i, 0, 2] = val
padding = (0, 1)
else:
assert 0, direction
heat = nn.functional.conv2d(heat, kernel.cuda(), padding=padding)
# heat[heat > 1] = 1
return heat
def _topk(scores, K=20):
batch, cat, height, width = scores.size()
topk_scores, topk_inds = torch.topk(scores.view(batch, -1), K)
topk_clses = (topk_inds / (height * width)).int()
topk_inds = topk_inds % (height * width)
topk_ys = (topk_inds / width).int().float()
topk_xs = (topk_inds % width).int().float()
return topk_scores, topk_inds, topk_clses, topk_ys, topk_xs
def _decode(
tl_heat, br_heat, tl_tag, br_tag, tl_regr, br_regr,
K=100, kernel=1, ae_threshold=1, num_dets=1000
):
batch, cat, height, width = tl_heat.size()
tl_heat = torch.sigmoid(tl_heat)
br_heat = torch.sigmoid(br_heat)
# perform nms on heatmaps
tl_heat = _nms(tl_heat, kernel=kernel)
br_heat = _nms(br_heat, kernel=kernel)
tl_scores, tl_inds, tl_clses, tl_ys, tl_xs = _topk(tl_heat, K=K)
br_scores, br_inds, br_clses, br_ys, br_xs = _topk(br_heat, K=K)
tl_ys = tl_ys.view(batch, K, 1).expand(batch, K, K)
tl_xs = tl_xs.view(batch, K, 1).expand(batch, K, K)
br_ys = br_ys.view(batch, 1, K).expand(batch, K, K)
br_xs = br_xs.view(batch, 1, K).expand(batch, K, K)
if tl_regr is not None and br_regr is not None:
tl_regr = _tranpose_and_gather_feat(tl_regr, tl_inds)
tl_regr = tl_regr.view(batch, K, 1, 2)
br_regr = _tranpose_and_gather_feat(br_regr, br_inds)
br_regr = br_regr.view(batch, 1, K, 2)
tl_xs = tl_xs + tl_regr[..., 0]
tl_ys = tl_ys + tl_regr[..., 1]
br_xs = br_xs + br_regr[..., 0]
br_ys = br_ys + br_regr[..., 1]
# all possible boxes based on top k corners (ignoring class)
bboxes = torch.stack((tl_xs, tl_ys, br_xs, br_ys), dim=3)
tl_tag = _tranpose_and_gather_feat(tl_tag, tl_inds)
tl_tag = tl_tag.view(batch, K, 1)
br_tag = _tranpose_and_gather_feat(br_tag, br_inds)
br_tag = br_tag.view(batch, 1, K)
dists = torch.abs(tl_tag - br_tag)
tl_scores = tl_scores.view(batch, K, 1).expand(batch, K, K)
br_scores = br_scores.view(batch, 1, K).expand(batch, K, K)
scores = (tl_scores + br_scores) / 2
# reject boxes based on classes
tl_clses = tl_clses.view(batch, K, 1).expand(batch, K, K)
br_clses = br_clses.view(batch, 1, K).expand(batch, K, K)
cls_inds = (tl_clses != br_clses)
# reject boxes based on distances
dist_inds = (dists > ae_threshold)
# reject boxes based on widths and heights
width_inds = (br_xs < tl_xs)
height_inds = (br_ys < tl_ys)
scores[cls_inds] = -1
scores[dist_inds] = -1
scores[width_inds] = -1
scores[height_inds] = -1
scores = scores.view(batch, -1)
scores, inds = torch.topk(scores, num_dets)
scores = scores.unsqueeze(2)
bboxes = bboxes.view(batch, -1, 4)
bboxes = _gather_feat(bboxes, inds)
clses = tl_clses.contiguous().view(batch, -1, 1)
clses = _gather_feat(clses, inds).float()
tl_scores = tl_scores.contiguous().view(batch, -1, 1)
tl_scores = _gather_feat(tl_scores, inds).float()
br_scores = br_scores.contiguous().view(batch, -1, 1)
br_scores = _gather_feat(br_scores, inds).float()
detections = torch.cat([bboxes, scores, tl_scores, br_scores, clses], dim=2)
return detections
def _exct_decode(
t_heat, l_heat, b_heat, r_heat, ct_heat,
t_regr, l_regr, b_regr, r_regr,
K=40, kernel=3,
aggr_weight=0.1, scores_thresh=0.1, center_thresh=0.1,num_dets=1000
):
batch, cat, height, width = t_heat.size()
'''
filter_kernel = 0.1
t_heat = _filter(t_heat, direction='h', val=filter_kernel)
l_heat = _filter(l_heat, direction='v', val=filter_kernel)
b_heat = _filter(b_heat, direction='h', val=filter_kernel)
r_heat = _filter(r_heat, direction='v', val=filter_kernel)
'''
t_heat = torch.sigmoid(t_heat)
l_heat = torch.sigmoid(l_heat)
b_heat = torch.sigmoid(b_heat)
r_heat = torch.sigmoid(r_heat)
ct_heat = torch.sigmoid(ct_heat)
if aggr_weight > 0:
t_heat = _h_aggregate(t_heat, aggr_weight=aggr_weight)
l_heat = _v_aggregate(l_heat, aggr_weight=aggr_weight)
b_heat = _h_aggregate(b_heat, aggr_weight=aggr_weight)
r_heat = _v_aggregate(r_heat, aggr_weight=aggr_weight)
# perform nms on heatmaps
t_heat = _nms(t_heat, kernel=kernel)
l_heat = _nms(l_heat, kernel=kernel)
b_heat = _nms(b_heat, kernel=kernel)
r_heat = _nms(r_heat, kernel=kernel)
t_heat[t_heat > 1] = 1
l_heat[l_heat > 1] = 1
b_heat[b_heat > 1] = 1
r_heat[r_heat > 1] = 1
t_scores, t_inds, t_clses, t_ys, t_xs = _topk(t_heat, K=K)
l_scores, l_inds, l_clses, l_ys, l_xs = _topk(l_heat, K=K)
b_scores, b_inds, b_clses, b_ys, b_xs = _topk(b_heat, K=K)
r_scores, r_inds, r_clses, r_ys, r_xs = _topk(r_heat, K=K)
t_ys = t_ys.view(batch, K, 1, 1, 1).expand(batch, K, K, K, K)
t_xs = t_xs.view(batch, K, 1, 1, 1).expand(batch, K, K, K, K)
l_ys = l_ys.view(batch, 1, K, 1, 1).expand(batch, K, K, K, K)
l_xs = l_xs.view(batch, 1, K, 1, 1).expand(batch, K, K, K, K)
b_ys = b_ys.view(batch, 1, 1, K, 1).expand(batch, K, K, K, K)
b_xs = b_xs.view(batch, 1, 1, K, 1).expand(batch, K, K, K, K)
r_ys = r_ys.view(batch, 1, 1, 1, K).expand(batch, K, K, K, K)
r_xs = r_xs.view(batch, 1, 1, 1, K).expand(batch, K, K, K, K)
t_clses = t_clses.view(batch, K, 1, 1, 1).expand(batch, K, K, K, K)
l_clses = l_clses.view(batch, 1, K, 1, 1).expand(batch, K, K, K, K)
b_clses = b_clses.view(batch, 1, 1, K, 1).expand(batch, K, K, K, K)
r_clses = r_clses.view(batch, 1, 1, 1, K).expand(batch, K, K, K, K)
box_ct_xs = ((l_xs + r_xs + 0.5) / 2).long()
box_ct_ys = ((t_ys + b_ys + 0.5) / 2).long()
ct_inds = t_clses.long() * (height * width) + box_ct_ys * width + box_ct_xs
ct_inds = ct_inds.view(batch, -1)
ct_heat = ct_heat.view(batch, -1, 1)
ct_scores = _gather_feat(ct_heat, ct_inds)
t_scores = t_scores.view(batch, K, 1, 1, 1).expand(batch, K, K, K, K)
l_scores = l_scores.view(batch, 1, K, 1, 1).expand(batch, K, K, K, K)
b_scores = b_scores.view(batch, 1, 1, K, 1).expand(batch, K, K, K, K)
r_scores = r_scores.view(batch, 1, 1, 1, K).expand(batch, K, K, K, K)
ct_scores = ct_scores.view(batch, K, K, K, K)
scores = (t_scores + l_scores + b_scores + r_scores + 2 * ct_scores) / 6
# reject boxes based on classes
cls_inds = (t_clses != l_clses) + (t_clses != b_clses) + \
(t_clses != r_clses)
cls_inds = (cls_inds > 0)
top_inds = (t_ys > l_ys) + (t_ys > b_ys) + (t_ys > r_ys)
top_inds = (top_inds > 0)
left_inds = (l_xs > t_xs) + (l_xs > b_xs) + (l_xs > r_xs)
left_inds = (left_inds > 0)
bottom_inds = (b_ys < t_ys) + (b_ys < l_ys) + (b_ys < r_ys)
bottom_inds = (bottom_inds > 0)
right_inds = (r_xs < t_xs) + (r_xs < l_xs) + (r_xs < b_xs)
right_inds = (right_inds > 0)
sc_inds = (t_scores < scores_thresh) + (l_scores < scores_thresh) + \
(b_scores < scores_thresh) + (r_scores < scores_thresh) + \
(ct_scores < center_thresh)
sc_inds = (sc_inds > 0)
'''
scores[sc_inds] = -1
scores[cls_inds] = -1
scores[top_inds] = -1
scores[left_inds] = -1
scores[bottom_inds] = -1
scores[right_inds] = -1
'''
scores = scores - sc_inds.float()
scores = scores - cls_inds.float()
scores = scores - top_inds.float()
scores = scores - left_inds.float()
scores = scores - bottom_inds.float()
scores = scores - right_inds.float()
scores = scores.view(batch, -1)
scores, inds = torch.topk(scores, num_dets)
scores = scores.unsqueeze(2)
if t_regr is not None and l_regr is not None \
and b_regr is not None and r_regr is not None:
t_regr = _tranpose_and_gather_feat(t_regr, t_inds)
t_regr = t_regr.view(batch, K, 1, 1, 1, 2)
l_regr = _tranpose_and_gather_feat(l_regr, l_inds)
l_regr = l_regr.view(batch, 1, K, 1, 1, 2)
b_regr = _tranpose_and_gather_feat(b_regr, b_inds)
b_regr = b_regr.view(batch, 1, 1, K, 1, 2)
r_regr = _tranpose_and_gather_feat(r_regr, r_inds)
r_regr = r_regr.view(batch, 1, 1, 1, K, 2)
t_xs = t_xs + t_regr[..., 0]
t_ys = t_ys + t_regr[..., 1]
l_xs = l_xs + l_regr[..., 0]
l_ys = l_ys + l_regr[..., 1]
b_xs = b_xs + b_regr[..., 0]
b_ys = b_ys + b_regr[..., 1]
r_xs = r_xs + r_regr[..., 0]
r_ys = r_ys + r_regr[..., 1]
else:
t_xs = t_xs + 0.5
t_ys = t_ys + 0.5
l_xs = l_xs + 0.5
l_ys = l_ys + 0.5
b_xs = b_xs + 0.5
b_ys = b_ys + 0.5
r_xs = r_xs + 0.5
r_ys = r_ys + 0.5
bboxes = torch.stack((l_xs, t_ys, r_xs, b_ys), dim=5)
bboxes = bboxes.view(batch, -1, 4)
bboxes = _gather_feat(bboxes, inds)
clses = t_clses.contiguous().view(batch, -1, 1)
clses = _gather_feat(clses, inds).float()
t_xs = t_xs.contiguous().view(batch, -1, 1)
t_xs = _gather_feat(t_xs, inds).float()
t_ys = t_ys.contiguous().view(batch, -1, 1)
t_ys = _gather_feat(t_ys, inds).float()
l_xs = l_xs.contiguous().view(batch, -1, 1)
l_xs = _gather_feat(l_xs, inds).float()
l_ys = l_ys.contiguous().view(batch, -1, 1)
l_ys = _gather_feat(l_ys, inds).float()
b_xs = b_xs.contiguous().view(batch, -1, 1)
b_xs = _gather_feat(b_xs, inds).float()
b_ys = b_ys.contiguous().view(batch, -1, 1)
b_ys = _gather_feat(b_ys, inds).float()
r_xs = r_xs.contiguous().view(batch, -1, 1)
r_xs = _gather_feat(r_xs, inds).float()
r_ys = r_ys.contiguous().view(batch, -1, 1)
r_ys = _gather_feat(r_ys, inds).float()
detections = torch.cat([bboxes, scores, t_xs, t_ys, l_xs, l_ys,
b_xs, b_ys, r_xs, r_ys, clses], dim=2)
return detections
'''
# Faster but costs more memory
def _neg_loss(preds, gt):
pos_inds = gt.eq(1).float()
neg_inds = gt.lt(1).float()
neg_weights = torch.pow(1 - gt, 4)
loss = 0
for pred in preds:
pos_loss = torch.log(pred) * torch.pow(1 - pred, 2) * pos_inds
neg_loss = torch.log(1 - pred) * torch.pow(pred, 2) * \
neg_weights * neg_inds
num_pos = pos_inds.float().sum()
pos_loss = pos_loss.sum()
neg_loss = neg_loss.sum()
if num_pos == 0:
loss = loss - neg_loss
else:
loss = loss - (pos_loss + neg_loss) / num_pos
return loss
'''
def _neg_loss(preds, gt):
pos_inds = gt.eq(1)
neg_inds = gt.lt(1)
neg_weights = torch.pow(1 - gt[neg_inds], 4)
loss = 0
for pred in preds:
pos_pred = pred[pos_inds]
neg_pred = pred[neg_inds]
pos_loss = torch.log(pos_pred) * torch.pow(1 - pos_pred, 2)
neg_loss = torch.log(1 - neg_pred) * torch.pow(neg_pred, 2) * neg_weights
num_pos = pos_inds.float().sum()
pos_loss = pos_loss.sum()
neg_loss = neg_loss.sum()
if pos_pred.nelement() == 0:
loss = loss - neg_loss
else:
loss = loss - (pos_loss + neg_loss) / num_pos
return loss
def _sigmoid(x):
x = torch.clamp(x.sigmoid_(), min=1e-4, max=1-1e-4)
return x
def _ae_loss(tag0, tag1, mask):
num = mask.sum(dim=1, keepdim=True).float()
tag0 = tag0.squeeze()
tag1 = tag1.squeeze()
tag_mean = (tag0 + tag1) / 2
tag0 = torch.pow(tag0 - tag_mean, 2) / (num + 1e-4)
tag0 = tag0[mask].sum()
tag1 = torch.pow(tag1 - tag_mean, 2) / (num + 1e-4)
tag1 = tag1[mask].sum()
pull = tag0 + tag1
mask = mask.unsqueeze(1) + mask.unsqueeze(2)
mask = mask.eq(2)
num = num.unsqueeze(2)
num2 = (num - 1) * num
dist = tag_mean.unsqueeze(1) - tag_mean.unsqueeze(2)
dist = 1 - torch.abs(dist)
dist = nn.functional.relu(dist, inplace=True)
dist = dist - 1 / (num + 1e-4)
dist = dist / (num2 + 1e-4)
dist = dist[mask]
push = dist.sum()
return pull, push
'''
def _regr_loss(regr, gt_regr, mask):
num = mask.float().sum()
mask = mask.unsqueeze(2).expand_as(gt_regr).float()
regr = regr * mask
gt_regr = gt_regr * mask
regr_loss = nn.functional.smooth_l1_loss(regr, gt_regr, size_average=False)
regr_loss = regr_loss / (num + 1e-4)
return regr_loss
'''
def _regr_loss(regr, gt_regr, mask):
num = mask.float().sum()
mask = mask.unsqueeze(2).expand_as(gt_regr)
regr = regr[mask]
gt_regr = gt_regr[mask]
regr_loss = nn.functional.smooth_l1_loss(regr, gt_regr, size_average=False)
regr_loss = regr_loss / (num + 1e-4)
return regr_loss
| 8,547 |
432 | <filename>contrib/gdb-7/gdb/python/py-auto-load.c
/* GDB routines for supporting auto-loaded scripts.
Copyright (C) 2010-2013 Free Software Foundation, Inc.
This file is part of GDB.
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 3 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, see <http://www.gnu.org/licenses/>. */
#include "defs.h"
#include "gdb_string.h"
#include "top.h"
#include "exceptions.h"
#include "gdbcmd.h"
#include "objfiles.h"
#include "python.h"
#include "cli/cli-cmds.h"
#include "auto-load.h"
#ifdef HAVE_PYTHON
#include "python-internal.h"
/* The section to look for Python auto-loaded scripts (in file formats that
support sections).
Each entry in this section is a byte of value 1, and then the nul-terminated
name of the script. The script name may include a directory.
The leading byte is to allow upward compatible extensions. */
#define GDBPY_AUTO_SECTION_NAME ".debug_gdb_scripts"
/* User-settable option to enable/disable auto-loading of Python scripts:
set auto-load python-scripts on|off
This is true if we should auto-load associated Python scripts when an
objfile is opened, false otherwise. */
static int auto_load_python_scripts = 1;
static void gdbpy_load_auto_script_for_objfile (struct objfile *objfile,
FILE *file,
const char *filename);
/* "show" command for the auto_load_python_scripts configuration variable. */
static void
show_auto_load_python_scripts (struct ui_file *file, int from_tty,
struct cmd_list_element *c, const char *value)
{
fprintf_filtered (file, _("Auto-loading of Python scripts is %s.\n"), value);
}
/* Definition of script language for Python scripts. */
static const struct script_language script_language_python
= { GDBPY_AUTO_FILE_NAME, gdbpy_load_auto_script_for_objfile };
/* Wrapper of source_python_script_for_objfile for script_language_python. */
static void
gdbpy_load_auto_script_for_objfile (struct objfile *objfile, FILE *file,
const char *filename)
{
int is_safe;
struct auto_load_pspace_info *pspace_info;
is_safe = file_is_auto_load_safe (filename,
_("auto-load: Loading Python script \"%s\" "
"by extension for objfile \"%s\".\n"),
filename, objfile->name);
/* Add this script to the hash table too so "info auto-load python-scripts"
can print it. */
pspace_info = get_auto_load_pspace_data_for_loading (current_program_space);
maybe_add_script (pspace_info, is_safe, filename, filename,
&script_language_python);
if (is_safe)
source_python_script_for_objfile (objfile, file, filename);
}
/* Load scripts specified in OBJFILE.
START,END delimit a buffer containing a list of nul-terminated
file names.
SOURCE_NAME is used in error messages.
Scripts are found per normal "source -s" command processing.
First the script is looked for in $cwd. If not found there the
source search path is used.
The section contains a list of path names of files containing
python code to load. Each path is null-terminated. */
static void
source_section_scripts (struct objfile *objfile, const char *source_name,
const char *start, const char *end)
{
const char *p;
struct auto_load_pspace_info *pspace_info;
pspace_info = get_auto_load_pspace_data_for_loading (current_program_space);
for (p = start; p < end; ++p)
{
const char *file;
FILE *stream;
char *full_path;
int opened, in_hash_table;
struct cleanup *back_to;
if (*p != 1)
{
warning (_("Invalid entry in %s section"), GDBPY_AUTO_SECTION_NAME);
/* We could try various heuristics to find the next valid entry,
but it's safer to just punt. */
break;
}
file = ++p;
while (p < end && *p != '\0')
++p;
if (p == end)
{
char *buf = alloca (p - file + 1);
memcpy (buf, file, p - file);
buf[p - file] = '\0';
warning (_("Non-null-terminated path in %s: %s"),
source_name, buf);
/* Don't load it. */
break;
}
if (p == file)
{
warning (_("Empty path in %s"), source_name);
continue;
}
opened = find_and_open_script (file, 1 /*search_path*/,
&stream, &full_path);
back_to = make_cleanup (null_cleanup, NULL);
if (opened)
{
make_cleanup_fclose (stream);
make_cleanup (xfree, full_path);
if (!file_is_auto_load_safe (full_path,
_("auto-load: Loading Python script "
"\"%s\" from section \"%s\" of "
"objfile \"%s\".\n"),
full_path, GDBPY_AUTO_SECTION_NAME,
objfile->name))
opened = 0;
}
else
{
full_path = NULL;
/* We don't throw an error, the program is still debuggable. */
if (script_not_found_warning_print (pspace_info))
warning (_("Missing auto-load scripts referenced in section %s\n\
of file %s\n\
Use `info auto-load python [REGEXP]' to list them."),
GDBPY_AUTO_SECTION_NAME, objfile->name);
}
/* If one script isn't found it's not uncommon for more to not be
found either. We don't want to print an error message for each
script, too much noise. Instead, we print the warning once and tell
the user how to find the list of scripts that weren't loaded.
IWBN if complaints.c were more general-purpose. */
in_hash_table = maybe_add_script (pspace_info, opened, file, full_path,
&script_language_python);
/* If this file is not currently loaded, load it. */
if (opened && !in_hash_table)
source_python_script_for_objfile (objfile, stream, full_path);
do_cleanups (back_to);
}
}
/* Load scripts specified in section SECTION_NAME of OBJFILE. */
static void
auto_load_section_scripts (struct objfile *objfile, const char *section_name)
{
bfd *abfd = objfile->obfd;
asection *scripts_sect;
bfd_byte *data = NULL;
scripts_sect = bfd_get_section_by_name (abfd, section_name);
if (scripts_sect == NULL)
return;
if (!bfd_get_full_section_contents (abfd, scripts_sect, &data))
warning (_("Couldn't read %s section of %s"),
section_name, bfd_get_filename (abfd));
else
{
struct cleanup *cleanups;
char *p = (char *) data;
cleanups = make_cleanup (xfree, p);
source_section_scripts (objfile, section_name, p,
p + bfd_get_section_size (scripts_sect));
do_cleanups (cleanups);
}
}
/* Load any Python auto-loaded scripts for OBJFILE. */
void
gdbpy_load_auto_scripts_for_objfile (struct objfile *objfile)
{
if (auto_load_python_scripts)
{
auto_load_objfile_script (objfile, &script_language_python);
auto_load_section_scripts (objfile, GDBPY_AUTO_SECTION_NAME);
}
}
/* Wrapper for "info auto-load python-scripts". */
static void
info_auto_load_python_scripts (char *pattern, int from_tty)
{
auto_load_info_scripts (pattern, from_tty, &script_language_python);
}
void
gdbpy_initialize_auto_load (void)
{
struct cmd_list_element *cmd;
char *cmd_name;
add_setshow_boolean_cmd ("python-scripts", class_support,
&auto_load_python_scripts, _("\
Set the debugger's behaviour regarding auto-loaded Python scripts."), _("\
Show the debugger's behaviour regarding auto-loaded Python scripts."), _("\
If enabled, auto-loaded Python scripts are loaded when the debugger reads\n\
an executable or shared library.\n\
This options has security implications for untrusted inferiors."),
NULL, show_auto_load_python_scripts,
auto_load_set_cmdlist_get (),
auto_load_show_cmdlist_get ());
add_setshow_boolean_cmd ("auto-load-scripts", class_support,
&auto_load_python_scripts, _("\
Set the debugger's behaviour regarding auto-loaded Python scripts, "
"deprecated."),
_("\
Show the debugger's behaviour regarding auto-loaded Python scripts, "
"deprecated."),
NULL, NULL, show_auto_load_python_scripts,
&setlist, &showlist);
cmd_name = "auto-load-scripts";
cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
deprecate_cmd (cmd, "set auto-load python-scripts");
/* It is needed because lookup_cmd updates the CMD_NAME pointer. */
cmd_name = "auto-load-scripts";
cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
deprecate_cmd (cmd, "show auto-load python-scripts");
add_cmd ("python-scripts", class_info, info_auto_load_python_scripts,
_("Print the list of automatically loaded Python scripts.\n\
Usage: info auto-load python-scripts [REGEXP]"),
auto_load_info_cmdlist_get ());
cmd = add_info ("auto-load-scripts", info_auto_load_python_scripts, _("\
Print the list of automatically loaded Python scripts, deprecated."));
deprecate_cmd (cmd, "info auto-load python-scripts");
}
#else /* ! HAVE_PYTHON */
void
gdbpy_load_auto_scripts_for_objfile (struct objfile *objfile)
{
}
#endif /* ! HAVE_PYTHON */
| 3,342 |
1,403 | <filename>test/fixture/python_scanner/from_import_simple_package_module1_func.py
from simple_package.module1 import somefunc # noqa: F401 | 45 |
4,538 | #include <rom_ssl_ram_map.h>
#include <section_config.h>
#ifndef SSL_RAM_MAP_SECTION
#define SSL_RAM_MAP_SECTION
#endif
#ifndef HAL_ROM_BSS_V02_SECTION
#define HAL_ROM_BSS_V02_SECTION
#endif
/* RAM table referred by SSL ROM */
SSL_RAM_MAP_SECTION
struct _rom_ssl_ram_map rom_ssl_ram_map;
SSL_RAM_MAP_SECTION
struct _rom_mbedtls_ram_map* p_rom_ssl_ram_map;
| 158 |
634 | <reponame>halotroop2288/consulo
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.diff.tools.util;
import com.intellij.diff.tools.util.DiffSplitter.Painter;
import com.intellij.diff.util.Side;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.JBUI;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import consulo.ui.annotation.RequiredUIAccess;
import javax.swing.*;
import java.awt.*;
import java.util.List;
public class ThreeDiffSplitter extends JPanel {
@Nonnull
private final List<Divider> myDividers;
@Nonnull
private final List<? extends JComponent> myContents;
public ThreeDiffSplitter(@Nonnull List<? extends JComponent> components) {
myDividers = ContainerUtil.list(new Divider(), new Divider());
myContents = components;
addAll(myContents);
addAll(myDividers);
}
@RequiredUIAccess
public void setPainter(@javax.annotation.Nullable Painter painter, @Nonnull Side side) {
getDivider(side).setPainter(painter);
}
public void repaintDividers() {
repaintDivider(Side.LEFT);
repaintDivider(Side.RIGHT);
}
public void repaintDivider(@Nonnull Side side) {
getDivider(side).repaint();
}
@Nonnull
private Divider getDivider(@Nonnull Side side) {
return myDividers.get(side.getIndex());
}
private void addAll(@Nonnull List<? extends JComponent> components) {
for (JComponent component : components) {
add(component, -1);
}
}
public void doLayout() {
int width = getWidth();
int height = getHeight();
int dividersTotalWidth = 0;
for (JComponent divider : myDividers) {
dividersTotalWidth += divider.getPreferredSize().width;
}
int panelWidth = (width - dividersTotalWidth) / 3;
int x = 0;
for (int i = 0; i < myContents.size(); i++) {
JComponent component = myContents.get(i);
component.setBounds(x, 0, panelWidth, height);
component.validate();
x += panelWidth;
if (i < myDividers.size()) {
JComponent divider = myDividers.get(i);
int dividerWidth = divider.getPreferredSize().width;
divider.setBounds(x, 0, dividerWidth, height);
divider.validate();
x += dividerWidth;
}
}
}
private static class Divider extends JComponent {
@Nullable private Painter myPainter;
public Dimension getPreferredSize() {
return JBUI.size(30, 1);
}
public void paint(Graphics g) {
super.paint(g);
if (myPainter != null) myPainter.paint(g, this);
}
@RequiredUIAccess
public void setPainter(@javax.annotation.Nullable Painter painter) {
myPainter = painter;
}
}
}
| 1,159 |
2,601 | <filename>tsconfig.json<gh_stars>1000+
{
"compilerOptions": {
"target": "es2018",
"lib": ["es2018"],
"module": "commonjs",
"resolveJsonModule": true,
"allowJs": true,
"checkJs": true,
"declaration": true,
"emitDeclarationOnly": true,
"noEmitOnError": true,
"newLine": "lf",
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
"strict": true
},
"references": [
{"path": "packages/postcss-normalize-display-values"},
{"path": "packages/postcss-normalize-timing-functions"},
{"path": "packages/postcss-normalize-string"},
{"path": "packages/postcss-discard-comments"},
{"path": "packages/postcss-discard-empty"},
{"path": "packages/postcss-minify-gradients"},
{"path": "packages/postcss-reduce-transforms"},
{"path": "packages/cssnano-utils"},
{"path": "packages/postcss-convert-values"},
{"path": "packages/postcss-colormin"},
{"path": "packages/postcss-minify-selectors"},
{"path": "packages/postcss-minify-params"},
{"path": "packages/postcss-normalize-charset"},
{"path": "packages/postcss-minify-font-values"},
{"path": "packages/postcss-discard-duplicates"},
{"path": "packages/postcss-discard-overridden"},
{"path": "packages/postcss-normalize-whitespace"},
{"path": "packages/postcss-unique-selectors"},
{"path": "packages/postcss-normalize-repeat-style"},
{"path": "packages/postcss-normalize-positions"},
{"path": "packages/postcss-normalize-unicode"},
{"path": "packages/postcss-reduce-initial"},
{"path": "packages/postcss-zindex"},
{"path": "packages/postcss-discard-unused"},
{"path": "packages/postcss-ordered-values"},
{"path": "packages/postcss-normalize-url"},
{"path": "packages/postcss-svgo"},
{"path": "packages/stylehacks"},
{"path": "packages/postcss-merge-longhand"},
{"path": "packages/postcss-merge-rules"},
{"path": "packages/postcss-merge-idents"},
{"path": "packages/postcss-reduce-idents"},
{"path": "packages/cssnano-preset-lite"},
{"path": "packages/cssnano-preset-default"},
{"path": "packages/cssnano-preset-advanced"},
{"path": "packages/cssnano"}
],
"files": []
}
| 860 |
342 | <filename>ray-rllib/explore-rllib/test_exercises.py
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
def test_chain_env_spaces(chain_env_cls):
test_env = chain_env_cls(dict(n=6))
print("Testing if spaces have been setup correctly...")
assert test_env.action_space is not None, "Action Space not implemented!"
assert test_env.observation_space is not None, "Observation Space not implemented!"
assert not test_env.action_space.contains(2), "Action Space is only [0, 1]"
assert test_env.action_space.contains(
1), "Action Space does not contain 1."
assert not test_env.observation_space.contains(
6), "Observation Space is only [0..5]"
assert test_env.observation_space.contains(
5), "Observation Space is only [0..5]"
print("Success! You've setup the spaces correctly.")
def test_chain_env_reward(chain_env_cls):
test_env = chain_env_cls(dict(n=6))
print("Testing if reward has been setup correctly...")
test_env.reset()
assert test_env.step(1)[1] == test_env.small_reward
assert test_env.state == 0
assert test_env.step(0)[1] == 0
assert test_env.state == 1
test_env.reset()
total_reward = 0
for i in range(test_env.n - 1):
total_reward += test_env.step(0)[1]
assert total_reward == 0, "Expected {} reward; got {}".format(
0, total_reward)
for i in range(3):
assert test_env.step(0)[1] == test_env.large_reward
assert test_env.step(1)[1] == test_env.small_reward
print("Success! You've setup the rewards correctly.")
def test_chain_env_behavior(chain_env_cls):
test_env = chain_env_cls(dict(n=6))
print("Testing if behavior has been changed...")
test_env.reset()
assert test_env.state == 0
test_env.step(1)
assert test_env.state == 0
test_env.step(0)
assert test_env.state == 1
test_env.reset()
assert test_env.state == 0
for i in range(1, test_env.n):
test_env.step(0)
assert test_env.state == i
test_env.step(0)
assert test_env.state == test_env.n - 1
test_env.step(1)
assert test_env.state == 0
print("Success! Behavior of environment is correct.")
| 876 |
778 | <gh_stars>100-1000
// | / |
// ' / __| _` | __| _ \ __|
// . \ | ( | | ( |\__ `
// _|\_\_| \__,_|\__|\___/ ____/
// Multi-Physics
//
// License: BSD License
// Kratos default license: kratos/license.txt
//
// Main authors: clabra
//
#if !defined(KRATOS_KD_TREE_H_INCLUDED )
#define KRATOS_KD_TREE_H_INCLUDED
// System includes
#include <string>
#include <iostream>
#include <cstddef>
#include <vector>
// External includes
// Project includes
//#include "includes/define.h"
#include "tree.h"
namespace Kratos
{
//template<std::size_t Dimension, class TPointType, class TPointsContainerType>
//class KDTree;
///@name Kratos Globals
///@{
///@}
///@name Type Definitions
///@{
///@}
///@name Enum's
///@{
///@}
///@name Functions
///@{
///@}
///@name Kratos Classes
///@{
/// Short class definition.
/** Detail class definition.
*/
template< class TLeafType >
class KDTreePartitionBase : public TreeNode< TLeafType::Dimension,
typename TLeafType::PointType,
typename TLeafType::PointerType,
typename TLeafType::IteratorType,
typename TLeafType::DistanceIteratorType >
{
public:
///@name Type Definitions
///@{
/// Pointer definition of KDTree
KRATOS_CLASS_POINTER_DEFINITION(KDTreePartitionBase);
typedef TLeafType LeafType;
typedef typename LeafType::PointType PointType;
typedef typename LeafType::ContainerType ContainerType;
typedef typename LeafType::IteratorType IteratorType;
typedef typename LeafType::DistanceIteratorType DistanceIteratorType;
typedef typename LeafType::PointerType PointerType;
typedef typename LeafType::DistanceFunction DistanceFunction;
enum { Dimension = LeafType::Dimension };
typedef TreeNode<Dimension,PointType, PointerType, IteratorType, DistanceIteratorType> TreeNodeType;
typedef typename TreeNodeType::CoordinateType CoordinateType;
typedef typename TreeNodeType::SizeType SizeType;
typedef typename TreeNodeType::IndexType IndexType;
//typedef typename TreeNodeType::SearchStructureType SearchStructureType;
typedef typename LeafType::SearchStructureType SearchStructureType;
///@}
///@name Life Cycle
///@{
/// Partition constructor.
KDTreePartitionBase(IndexType CutingDimension, CoordinateType Position,
CoordinateType LeftEnd, CoordinateType RightEnd,
TreeNodeType* pLeftChild = NULL, TreeNodeType* pRightChild = NULL)
: mCutingDimension(CutingDimension), mPosition(Position), mLeftEnd(LeftEnd), mRightEnd(RightEnd)
{
mpChilds[0] = pLeftChild;
mpChilds[1] = pRightChild;
}
void PrintData(std::ostream& rOStream, std::string const& Perfix = std::string()) const override
{
rOStream << Perfix << "Partition at ";
switch(mCutingDimension)
{
case 0:
rOStream << "X =";
break;
case 1:
rOStream << "Y =";
break;
case 2:
rOStream << "Z =";
break;
default:
rOStream << mCutingDimension << " in";
break;
}
rOStream << mPosition << " from " << mLeftEnd << " to " << mRightEnd << std::endl;
mpChilds[0]->PrintData(rOStream, Perfix + " ");
mpChilds[1]->PrintData(rOStream, Perfix + " ");
}
/// Destructor.
virtual ~KDTreePartitionBase()
{
delete mpChilds[0];
delete mpChilds[1];
}
///@}
///@name Operations
///@{
void SearchNearestPoint(PointType const& rThisPoint, PointerType& rResult, CoordinateType& rResultDistance ) override
{
SearchStructureType Auxiliar;
for(SizeType i = 0 ; i < Dimension; i++)
Auxiliar.residual_distance[i] = 0.00;
SearchNearestPoint(rThisPoint, rResult, rResultDistance, Auxiliar );
}
void SearchNearestPoint(PointType const& rThisPoint, PointerType& rResult, CoordinateType& rResultDistance, SearchStructureType& Auxiliar ) override
{
CoordinateType temp = Auxiliar.residual_distance[mCutingDimension];
CoordinateType distance_to_partition = rThisPoint[mCutingDimension] - mPosition;
if( distance_to_partition < 0.0 ) // The point is in the left partition
{
//searching in the left child
mpChilds[0]->SearchNearestPoint(rThisPoint, rResult, rResultDistance, Auxiliar );
// compare with distance to right partition
Auxiliar.residual_distance[mCutingDimension] = distance_to_partition * distance_to_partition;
Auxiliar.distance_to_partition2 = Auxiliar.residual_distance[0];
for(SizeType i = 1; i < Dimension; i++)
Auxiliar.distance_to_partition2 += Auxiliar.residual_distance[i];
if( rResultDistance > Auxiliar.distance_to_partition2 )
mpChilds[1]->SearchNearestPoint(rThisPoint, rResult, rResultDistance, Auxiliar );
}
else // The point is in the right partition
{
//Searching in the right child
mpChilds[1]->SearchNearestPoint(rThisPoint, rResult, rResultDistance, Auxiliar );
// compare with distance to left partition
Auxiliar.residual_distance[mCutingDimension] = distance_to_partition * distance_to_partition;
Auxiliar.distance_to_partition2 = Auxiliar.residual_distance[0];
for(SizeType i = 1; i < Dimension; i++)
Auxiliar.distance_to_partition2 += Auxiliar.residual_distance[i];
if( rResultDistance > Auxiliar.distance_to_partition2 )
mpChilds[0]->SearchNearestPoint( rThisPoint, rResult, rResultDistance, Auxiliar );
}
Auxiliar.residual_distance[mCutingDimension] = temp;
}
void SearchInRadius(PointType const& ThisPoint, CoordinateType const& Radius, CoordinateType const& Radius2, IteratorType& Results,
DistanceIteratorType& ResultsDistances, SizeType& NumberOfResults, SizeType const& MaxNumberOfResults) override
{
SearchStructureType Auxiliar;
for(SizeType i = 0 ; i < Dimension; i++)
Auxiliar.residual_distance[i] = 0.00;
SearchInRadius(ThisPoint, Radius, Radius2, Results, ResultsDistances, NumberOfResults, MaxNumberOfResults, Auxiliar );
}
void SearchInRadius(PointType const& ThisPoint, CoordinateType const& Radius, CoordinateType const& Radius2, IteratorType& Results,
DistanceIteratorType& ResultsDistances, SizeType& NumberOfResults, SizeType const& MaxNumberOfResults, SearchStructureType& Auxiliar ) override
{
CoordinateType temp = Auxiliar.residual_distance[mCutingDimension];
CoordinateType distance_to_partition = ThisPoint[mCutingDimension] - mPosition;
if(distance_to_partition < 0) // The point is in the left partition
{
//searching in the left child
mpChilds[0]->SearchInRadius(ThisPoint, Radius, Radius2, Results, ResultsDistances, NumberOfResults, MaxNumberOfResults, Auxiliar );
Auxiliar.residual_distance[mCutingDimension] = distance_to_partition * distance_to_partition;
Auxiliar.distance_to_partition2 = Auxiliar.residual_distance[0];
for(SizeType i = 1; i < Dimension; i++)
Auxiliar.distance_to_partition2 += Auxiliar.residual_distance[i];
// The points is too near to the wall and the other child is in the searching radius
if( Radius2 >= Auxiliar.distance_to_partition2 )
mpChilds[1]->SearchInRadius(ThisPoint, Radius, Radius2, Results, ResultsDistances, NumberOfResults, MaxNumberOfResults, Auxiliar );
}
else // The point is in the right partition
{
//searching in the left child
mpChilds[1]->SearchInRadius(ThisPoint, Radius, Radius2, Results, ResultsDistances, NumberOfResults, MaxNumberOfResults, Auxiliar );
Auxiliar.residual_distance[mCutingDimension] = distance_to_partition * distance_to_partition;
Auxiliar.distance_to_partition2 = Auxiliar.residual_distance[0];
for(SizeType i = 1; i < Dimension; i++)
Auxiliar.distance_to_partition2 += Auxiliar.residual_distance[i];
// The points is too near to the wall and the other child is in the searching radius
if( Radius2 >= Auxiliar.distance_to_partition2 )
mpChilds[0]->SearchInRadius(ThisPoint, Radius, Radius2, Results, ResultsDistances, NumberOfResults, MaxNumberOfResults, Auxiliar );
}
Auxiliar.residual_distance[mCutingDimension] = temp;
}
void SearchInRadius(PointType const& ThisPoint, CoordinateType const& Radius, CoordinateType const& Radius2, IteratorType& Results,
SizeType& NumberOfResults, SizeType const& MaxNumberOfResults) override
{
SearchStructureType Auxiliar;
for(SizeType i = 0 ; i < Dimension; i++)
Auxiliar.residual_distance[i] = 0.00;
SearchInRadius(ThisPoint, Radius, Radius2, Results, NumberOfResults, MaxNumberOfResults, Auxiliar );
}
void SearchInRadius(PointType const& ThisPoint, CoordinateType const& Radius, CoordinateType const& Radius2, IteratorType& Results,
SizeType& NumberOfResults, SizeType const& MaxNumberOfResults, SearchStructureType& Auxiliar ) override
{
CoordinateType temp = Auxiliar.residual_distance[mCutingDimension];
CoordinateType distance_to_partition = ThisPoint[mCutingDimension] - mPosition;
if(distance_to_partition < 0) // The point is in the left partition
{
//searching in the left child
mpChilds[0]->SearchInRadius(ThisPoint, Radius, Radius2, Results, NumberOfResults, MaxNumberOfResults, Auxiliar );
Auxiliar.residual_distance[mCutingDimension] = distance_to_partition * distance_to_partition;
Auxiliar.distance_to_partition2 = Auxiliar.residual_distance[0];
for(SizeType i = 1; i < Dimension; i++)
Auxiliar.distance_to_partition2 += Auxiliar.residual_distance[i];
// The points is too near to the wall and the other child is in the searching radius
if( Radius2 >= Auxiliar.distance_to_partition2 )
mpChilds[1]->SearchInRadius(ThisPoint, Radius, Radius2, Results, NumberOfResults, MaxNumberOfResults, Auxiliar );
Auxiliar.residual_distance[mCutingDimension] = temp;
}
else // The point is in the right partition
{
//searching in the left child
mpChilds[1]->SearchInRadius(ThisPoint, Radius, Radius2, Results, NumberOfResults, MaxNumberOfResults, Auxiliar );
Auxiliar.residual_distance[mCutingDimension] = distance_to_partition * distance_to_partition;
Auxiliar.distance_to_partition2 = Auxiliar.residual_distance[0];
for(SizeType i = 1; i < Dimension; i++)
Auxiliar.distance_to_partition2 += Auxiliar.residual_distance[i];
// The points is too near to the wall and the other child is in the searching radius
if( Radius2 >= Auxiliar.distance_to_partition2 )
mpChilds[0]->SearchInRadius(ThisPoint, Radius, Radius2, Results, NumberOfResults, MaxNumberOfResults, Auxiliar );
Auxiliar.residual_distance[mCutingDimension] = temp;
}
}
void SearchInBox(PointType const& SearchMinPoint, PointType const& SearchMaxPoint, IteratorType& Results, SizeType& NumberOfResults,
SizeType const& MaxNumberOfResults ) override
{
if( SearchMinPoint[mCutingDimension] <= mPosition )
mpChilds[0]->SearchInBox(SearchMinPoint,SearchMaxPoint,Results,NumberOfResults,MaxNumberOfResults);
if( SearchMaxPoint[mCutingDimension] >= mPosition )
mpChilds[1]->SearchInBox(SearchMinPoint,SearchMaxPoint,Results,NumberOfResults,MaxNumberOfResults);
}
////////////////////
/* virtual static IteratorType Partition( IteratorType PointsBegin, IteratorType PointsEnd, IndexType& rCuttingDimension, CoordinateType& rCuttingValue ) = 0; */
public:
/* virtual TreeNodeType* Construct(IteratorType PointsBegin, IteratorType PointsEnd, PointType HighPoint, PointType LowPoint, SizeType BucketSize) = 0; */
private:
IndexType mCutingDimension;
CoordinateType mPosition; // Position of partition
CoordinateType mLeftEnd; // Left extend of partition
CoordinateType mRightEnd; // Right end of partition
TreeNodeType* mpChilds[2]; // The mpChilds[0] is the left child
// and mpChilds[1] is the right child.
};
//
//
//
// Median Split KD_Tree Partition
//
//
//
//
template< class TLeafType >
class KDTreePartition : public KDTreePartitionBase<TLeafType>
{
public:
///@name Type Definitions
///@{
/// Pointer definition of KDTree
KRATOS_CLASS_POINTER_DEFINITION(KDTreePartition);
typedef KDTreePartitionBase<TLeafType> BaseType;
typedef TLeafType LeafType;
typedef typename LeafType::PointType PointType;
typedef typename LeafType::ContainerType ContainerType;
typedef typename LeafType::IteratorType IteratorType;
typedef typename LeafType::DistanceIteratorType DistanceIteratorType;
typedef typename LeafType::PointerType PointerType;
typedef typename LeafType::DistanceFunction DistanceFunction;
enum { Dimension = LeafType::Dimension };
typedef TreeNode<Dimension,PointType, PointerType, IteratorType, DistanceIteratorType> TreeNodeType;
typedef typename TreeNodeType::CoordinateType CoordinateType;
typedef typename TreeNodeType::SizeType SizeType;
typedef typename TreeNodeType::IndexType IndexType;
//typedef typename TreeNodeType::SearchStructureType SearchStructureType;
typedef typename LeafType::SearchStructureType SearchStructureType;
///@}
///@name Life Cycle
///@{
/// Partition constructor.
KDTreePartition( IndexType CutingDimension, CoordinateType Position, CoordinateType LeftEnd, CoordinateType RightEnd,
TreeNodeType* pLeftChild = NULL, TreeNodeType* pRightChild = NULL )
: BaseType(CutingDimension,Position,LeftEnd,RightEnd,pLeftChild,pRightChild) {}
/// Destructor.
~KDTreePartition() {}
///@}
///@name Operations
///@{
////////////////////
static IteratorType Partition( IteratorType PointsBegin, IteratorType PointsEnd, IndexType& rCuttingDimension, CoordinateType& rCuttingValue )
{
SizeType n = SearchUtils::PointerDistance(PointsBegin, PointsEnd);
// find dimension of maximum spread
rCuttingDimension = MaxSpread(PointsBegin, PointsEnd);
IteratorType partition = PointsBegin + n / 2;
MedianSplit(PointsBegin, partition, PointsEnd, rCuttingDimension, rCuttingValue);
return partition;
}
static SizeType MaxSpread( IteratorType PointsBegin, IteratorType PointsEnd )
{
SizeType max_dimension = 0; // dimension of max spread
CoordinateType max_spread = 0; // amount of max spread
/* if(PointsBegin == PointsEnd) // If there is no point return the first coordinate */
/* return max_dimension; */
CoordinateType min[Dimension];
CoordinateType max[Dimension];
for (SizeType d = 0; d < Dimension; d++)
{
min[d] = (**PointsBegin)[d];
max[d] = (**PointsBegin)[d];
}
for (IteratorType i_point = PointsBegin; i_point != PointsEnd; i_point++)
{
for (SizeType d = 0; d < Dimension; d++)
{
CoordinateType c = (**i_point)[d];
if (c < min[d])
min[d] = c;
else if (c > max[d])
max[d] = c;
}
}
max_dimension = 0;
max_spread = max[0] - min[0];
for (SizeType d = 1; d < Dimension; d++)
{
CoordinateType spread = max[d] - min[d];
if (spread > max_spread)
{
max_spread = spread;
max_dimension = d;
}
}
return max_dimension;
}
static void MedianSplit( IteratorType PointsBegin, IteratorType PartitionPosition, IteratorType PointsEnd,
IndexType CuttingDimension, CoordinateType& rCuttingValue )
{
IteratorType left = PointsBegin;
IteratorType right = PointsEnd - 1;
while (left < right) // Iterating to find the partition point
{
IteratorType i = left; // selecting left as pivot
if ((**i)[CuttingDimension] > (**right)[CuttingDimension])
std::swap(*i,*right);
CoordinateType value = (**i)[CuttingDimension];
IteratorType j = right;
for(;;)
{
while ((**(++i))[CuttingDimension] < value)
;
while ((**(--j))[CuttingDimension] > value)
;
if (i < j) std::swap(*i,*j);
else break;
}
std::swap(*left,*j);
if (j > PartitionPosition)
right = j - 1;
else if (j < PartitionPosition)
left = j + 1;
else break;
}
CoordinateType max = (**PointsBegin)[CuttingDimension];
IteratorType k = PointsBegin;
IteratorType last = PartitionPosition;
for(IteratorType i = PointsBegin ; i != PartitionPosition ; ++i)
if((**i)[CuttingDimension] > max)
{
max = (**i)[CuttingDimension];
k = i;
}
if(k != PointsBegin)
std::swap(--last, k);
rCuttingValue = ((**last)[CuttingDimension] + (**PartitionPosition)[CuttingDimension])/2.0;
}
//
//
public:
// static TreeNodeType* Construct(IteratorType PointsBegin, IteratorType PointsEnd, PointType HighPoint, PointType LowPoint, SizeType BucketSize)
static TreeNodeType* Construct(IteratorType PointsBegin, IteratorType PointsEnd, const PointType& HighPoint, const PointType& LowPoint, SizeType BucketSize)
{
SizeType number_of_points = SearchUtils::PointerDistance(PointsBegin,PointsEnd);
if (number_of_points == 0)
return NULL;
else if (number_of_points <= BucketSize)
{
return new LeafType(PointsBegin, PointsEnd);
}
else
{
IndexType cutting_dimension;
CoordinateType cutting_value;
IteratorType partition = Partition(PointsBegin, PointsEnd, cutting_dimension, cutting_value);
// PointType partition_high_point = HighPoint;
// PointType partition_low_point = LowPoint;
PointType partition_high_point;
partition_high_point.Coordinates() = HighPoint.Coordinates();
PointType partition_low_point;
partition_low_point.Coordinates() = LowPoint.Coordinates();
partition_high_point[cutting_dimension] = cutting_value;
partition_low_point[cutting_dimension] = cutting_value;
return new KDTreePartition( cutting_dimension, cutting_value,
HighPoint[cutting_dimension], LowPoint[cutting_dimension],
Construct(PointsBegin, partition, partition_high_point, LowPoint, BucketSize),
Construct(partition, PointsEnd, HighPoint, partition_low_point, BucketSize) );
}
}
};
//
//
//
// Average Split KD_Tree Partition
//
//
//
//
template< class TLeafType >
class KDTreePartitionAverageSplit : public KDTreePartitionBase<TLeafType>
{
public:
///@name Type Definitions
///@{
/// Pointer definition of KDTree
KRATOS_CLASS_POINTER_DEFINITION(KDTreePartitionAverageSplit);
typedef KDTreePartitionBase<TLeafType> BaseType;
typedef TLeafType LeafType;
typedef typename LeafType::PointType PointType;
typedef typename LeafType::ContainerType ContainerType;
typedef typename LeafType::IteratorType IteratorType;
typedef typename LeafType::DistanceIteratorType DistanceIteratorType;
typedef typename LeafType::PointerType PointerType;
typedef typename LeafType::DistanceFunction DistanceFunction;
enum { Dimension = LeafType::Dimension };
typedef TreeNode<Dimension,PointType, PointerType, IteratorType, DistanceIteratorType> TreeNodeType;
typedef typename TreeNodeType::CoordinateType CoordinateType;
typedef typename TreeNodeType::SizeType SizeType;
typedef typename TreeNodeType::IndexType IndexType;
//typedef typename TreeNodeType::SearchStructureType SearchStructureType;
typedef typename LeafType::SearchStructureType SearchStructureType;
///@}
///@name Life Cycle
///@{
/// Partition constructor.
KDTreePartitionAverageSplit( IndexType CutingDimension, CoordinateType Position, CoordinateType LeftEnd, CoordinateType RightEnd,
TreeNodeType* pLeftChild = NULL, TreeNodeType* pRightChild = NULL)
: BaseType(CutingDimension,Position,LeftEnd,RightEnd,pLeftChild,pRightChild) {}
/// Destructor.
virtual ~KDTreePartitionAverageSplit() {}
///@}
///@name Operations
///@{
////////////////////
static IteratorType Partition( IteratorType PointsBegin, IteratorType PointsEnd, IndexType& rCuttingDimension, CoordinateType& rCuttingValue )
{
rCuttingDimension = MaxSpread( PointsBegin, PointsEnd, rCuttingValue );
IteratorType partition;
AverageSplit(PointsBegin, partition, PointsEnd, rCuttingDimension, rCuttingValue);
return partition;
}
static SizeType MaxSpread( IteratorType PointsBegin, IteratorType PointsEnd, CoordinateType& AverageValue )
{
SizeType max_dimension = 0; // dimension of max spread
CoordinateType max_spread = 0; // amount of max spread
AverageValue = 0.0;
CoordinateType size = static_cast<CoordinateType>(SearchUtils::PointerDistance(PointsBegin,PointsEnd));
CoordinateType min[Dimension];
CoordinateType max[Dimension];
CoordinateType Average[Dimension];
for (SizeType d = 0; d < Dimension; d++)
{
Average[d] = 0.0;
min[d] = (**PointsBegin)[d];
max[d] = (**PointsBegin)[d];
}
for (IteratorType i_point = PointsBegin; i_point != PointsEnd; i_point++)
{
for (SizeType d = 0; d < Dimension; d++)
{
CoordinateType c = (**i_point)[d];
Average[d] += c;
if (c < min[d])
min[d] = c;
else if (c > max[d])
max[d] = c;
}
}
max_dimension = 0;
max_spread = max[0] - min[0];
AverageValue = Average[0] / size;
for (SizeType d = 1; d < Dimension; d++)
{
CoordinateType spread = max[d] - min[d];
if (spread > max_spread)
{
max_spread = spread;
max_dimension = d;
AverageValue = Average[d] / size;
}
}
return max_dimension;
}
static void AverageSplit( IteratorType PointsBegin, IteratorType& PartitionPosition, IteratorType PointsEnd,
IndexType& CuttingDimension, CoordinateType& rCuttingValue )
{
// reorder by cutting_dimension
IteratorType left = PointsBegin;
IteratorType right = PointsEnd - 1;
for(;;)
{
while( left < PointsEnd && (**left)[CuttingDimension] < rCuttingValue ) left++;
while( right > PointsBegin && (**right)[CuttingDimension] >= rCuttingValue ) right--;
if (left <= right) std::swap(*left,*right);
else break;
}
PartitionPosition = left;
}
//
//
public:
static TreeNodeType* Construct(IteratorType PointsBegin, IteratorType PointsEnd, PointType HighPoint, PointType LowPoint, SizeType BucketSize)
{
SizeType number_of_points = SearchUtils::PointerDistance(PointsBegin,PointsEnd);
if (number_of_points == 0)
return NULL;
else if (number_of_points <= BucketSize)
{
return new LeafType(PointsBegin, PointsEnd);
}
else
{
IndexType cutting_dimension;
CoordinateType cutting_value;
IteratorType partition = Partition(PointsBegin, PointsEnd, cutting_dimension, cutting_value);
PointType partition_high_point = HighPoint;
PointType partition_low_point = LowPoint;
partition_high_point[cutting_dimension] = cutting_value;
partition_low_point[cutting_dimension] = cutting_value;
return new KDTreePartitionAverageSplit( cutting_dimension, cutting_value,
HighPoint[cutting_dimension], LowPoint[cutting_dimension],
Construct(PointsBegin, partition, partition_high_point, LowPoint, BucketSize),
Construct(partition, PointsEnd, HighPoint, partition_low_point, BucketSize) );
}
}
};
//
//
//
// MidPoint Split KD_Tree Partition
//
//
//
//
template< class TLeafType >
class KDTreePartitionMidPointSplit : public KDTreePartitionBase<TLeafType>
{
public:
///@name Type Definitions
///@{
/// Pointer definition of KDTree
KRATOS_CLASS_POINTER_DEFINITION(KDTreePartitionMidPointSplit);
typedef KDTreePartitionBase<TLeafType> BaseType;
typedef TLeafType LeafType;
typedef typename LeafType::PointType PointType;
typedef typename LeafType::ContainerType ContainerType;
typedef typename LeafType::IteratorType IteratorType;
typedef typename LeafType::DistanceIteratorType DistanceIteratorType;
typedef typename LeafType::PointerType PointerType;
typedef typename LeafType::DistanceFunction DistanceFunction;
enum { Dimension = LeafType::Dimension };
typedef TreeNode<Dimension,PointType, PointerType, IteratorType, DistanceIteratorType> TreeNodeType;
typedef typename TreeNodeType::CoordinateType CoordinateType;
typedef typename TreeNodeType::SizeType SizeType;
typedef typename TreeNodeType::IndexType IndexType;
//typedef typename TreeNodeType::SearchStructureType SearchStructureType;
typedef typename LeafType::SearchStructureType SearchStructureType;
///@}
///@name Life Cycle
///@{
/// Partition constructor.
KDTreePartitionMidPointSplit( IndexType CutingDimension, CoordinateType Position, CoordinateType LeftEnd, CoordinateType RightEnd,
TreeNodeType* pLeftChild = NULL, TreeNodeType* pRightChild = NULL)
: BaseType(CutingDimension,Position,LeftEnd,RightEnd,pLeftChild,pRightChild) {}
/// Destructor.
virtual ~KDTreePartitionMidPointSplit() {}
///@}
///@name Operations
///@{
////////////////////
static IteratorType Partition( IteratorType PointsBegin, IteratorType PointsEnd, PointType const& HighPoint, PointType const& LowPoint, IndexType& rCuttingDimension, CoordinateType& rCuttingValue )
{
rCuttingDimension = MaxSpread( PointsBegin, PointsEnd, HighPoint, LowPoint, rCuttingValue );
/*
rCuttingDimension = 0;
double max_spread = HighPoint[0] - LowPoint[0];
double spread;
for (SizeType i = 1; i < Dimension; i++)
{
spread = HighPoint[i] - LowPoint[i];
if (spread > max_spread)
{
rCuttingDimension = i;
max_spread = spread;
}
}
rCuttingValue = (LowPoint[rCuttingDimension] + HighPoint[rCuttingDimension]) / 2.00;
*/
return Split(PointsBegin, PointsEnd, rCuttingDimension, rCuttingValue);
}
static SizeType MaxSpread( IteratorType PointsBegin, IteratorType PointsEnd, PointType const& HighPoint, PointType const& LowPoint, CoordinateType& CuttingValue )
{
//CoordinateType size = static_cast<CoordinateType>(SearchUtils::PointerDistance(PointsBegin,PointsEnd));
CoordinateType min[Dimension];
CoordinateType max[Dimension];
for (SizeType d = 0; d < Dimension; d++)
{
min[d] = (**PointsBegin)[d];
max[d] = (**PointsBegin)[d];
}
for (IteratorType i_point = PointsBegin; i_point != PointsEnd; i_point++)
for (SizeType d = 0; d < Dimension; d++)
{
CoordinateType c = (**i_point)[d];
if (c < min[d])
min[d] = c;
else if (c > max[d])
max[d] = c;
}
SizeType max_dimension = 0;
CoordinateType max_spread = max[0] - min[0];
for (SizeType d = 1; d < Dimension; d++)
{
CoordinateType spread = max[d] - min[d];
if (spread > max_spread)
{
max_spread = spread;
max_dimension = d;
}
}
CuttingValue = (max[max_dimension]+min[max_dimension]) / 2.00;
return max_dimension;
}
static IteratorType Split( IteratorType PointsBegin, IteratorType PointsEnd, IndexType& CuttingDimension, CoordinateType& rCuttingValue )
{
// reorder by cutting_dimension
IteratorType left = PointsBegin;
IteratorType right = PointsEnd - 1;
for(;;)
{
while( (**left)[CuttingDimension] < rCuttingValue ) left++;
while( (**right)[CuttingDimension] >= rCuttingValue ) right--;
if (left < right) std::swap(*left,*right);
else break;
}
return left;
}
//
//
public:
static TreeNodeType* Construct(IteratorType PointsBegin, IteratorType PointsEnd, PointType HighPoint, PointType LowPoint, SizeType BucketSize)
{
SizeType number_of_points = SearchUtils::PointerDistance(PointsBegin,PointsEnd);
if (number_of_points == 0)
return NULL;
else if (number_of_points <= BucketSize)
{
return new LeafType(PointsBegin, PointsEnd);
}
else
{
IndexType cutting_dimension;
CoordinateType cutting_value;
IteratorType partition = Partition(PointsBegin, PointsEnd, HighPoint, LowPoint, cutting_dimension, cutting_value);
PointType partition_high_point = HighPoint;
PointType partition_low_point = LowPoint;
partition_high_point[cutting_dimension] = cutting_value;
partition_low_point[cutting_dimension] = cutting_value;
return new KDTreePartitionMidPointSplit( cutting_dimension, cutting_value,
HighPoint[cutting_dimension], LowPoint[cutting_dimension],
Construct(PointsBegin, partition, partition_high_point, LowPoint, BucketSize),
Construct(partition, PointsEnd, HighPoint, partition_low_point, BucketSize) );
}
}
};
} // namespace Kratos.
#endif // KRATOS_KD_TREE_H_INCLUDED defined
| 13,152 |
796 | <gh_stars>100-1000
/*
* Copyright (c) [2020] Huawei Technologies Co.,Ltd.All rights reserved.
*
* OpenArkCompiler is licensed under the Mulan PSL v1.
* You can use this software according to the terms and conditions of the Mulan PSL v1.
* You may obtain a copy of Mulan PSL v1 at:
*
* http://license.coscl.org.cn/MulanPSL
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR
* FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v1 for more details.
* -@TestCaseID: ImmutableLocal
*- @TestCaseName: Thread_ImmutableLocal.java
*- @RequirementName: Java Thread
*- @Title/Destination: Confirm ThreadLocal.set() usage is not a side effect of get().
*- @Brief: see below
* -#step1:定义继承ThreadLocal类的抽象类ImmutableThreadLocal,定义抛出new RuntimeException的set()和私有的受保护
* initialValue()。
* -#step2:通过new得到一个私有的不可变的线程对象cache,运行initialValue(),调用getName()获取当前执行线程对象的引用。
* -#step3:在主函数中调用cache.get()获取对象引用,确认获取正确。
*- @Expect: 0\n
*- @Priority: High
*- @Source: ImmutableLocal.java
*- @ExecuteClass: ImmutableLocal
*- @ExecuteArgs:
*/
public class ImmutableLocal {
private static final ThreadLocal cache = new ImmutableThreadLocal() {
public Object initialValue() {
return Thread.currentThread().getName();
}
};
public static void main(final String[] args) {
if (cache.get().equals("main")) {
System.out.println(0);
}
}
/**
* {@link ThreadLocal} guaranteed to always return the same reference.
*/
abstract public static class ImmutableThreadLocal extends ThreadLocal {
public void set(final Object value) {
throw new RuntimeException("ImmutableThreadLocal set called");
}
// Force override
abstract protected Object initialValue();
}
}
// EXEC:%maple %f %build_option -o %n.so
// EXEC:%run %n.so %n %run_option | compare %f
// ASSERT: scan-full 0\n | 884 |
1,269 | package gc;
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
public class PermGenOOM {
//C:\Program Files (x86)\Java\jdk1.6.0_45\bin>
//java -XX:PermSize=1m -XX:MaxPermSize=9m -Xmx16m PermGenOOM
//C:\Program Files\Java\jdk1.8.0_201
//C:\Program Files (x86)\Java\jdk1.6.0_45
//-XX:MetaspaceSize=1m -XX:MaxMetaspaceSize=9m -Xmx16m
//-XX:PermSize=1m -XX:MaxPermSize=9m -Xmx16m
private static Class klass;
public static void main(String[] args) throws Exception {
List<Object> list = new ArrayList<>();
URL url = new File(".").toURI().toURL();
URL[] urls = {url};
int count = 0;
while (true) {
try {
//System.out.println(++count);
ClassLoader loader = new URLClassLoader(urls);
//classLoaderList.add(loader);
list.add(loader.loadClass("gc.GcTest"));
list.add(loader.loadClass("gc.PermGenOOM"));
//loader.loadClass("gc.StringOomMock");
//Class clazz = loader.loadClass("gc.BigClass");
//loader.loadClass("feature.method_handle.MethodHandleTest");
//loader.loadClass("feature.method_handle.Client");
// System.out.println(clazz);
// System.out.println(klass == clazz);
//klass = clazz;
list.add(loader);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
| 791 |
2,151 | <reponame>zipated/src<gh_stars>1000+
# Copyright 2014 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.
"""IDL type handling.
Classes:
IdlTypeBase
IdlType
IdlUnionType
IdlArrayOrSequenceType
IdlSequenceType
IdlFrozenArrayType
IdlNullableType
IdlTypes are picklable because we store them in interfaces_info.
"""
from collections import defaultdict
################################################################################
# IDL types
################################################################################
INTEGER_TYPES = frozenset([
# http://www.w3.org/TR/WebIDL/#dfn-integer-type
'byte',
'octet',
'short',
'unsigned short',
# int and unsigned are not IDL types
'long',
'unsigned long',
'long long',
'unsigned long long',
])
NUMERIC_TYPES = (INTEGER_TYPES | frozenset([
# http://www.w3.org/TR/WebIDL/#dfn-numeric-type
'float',
'unrestricted float',
'double',
'unrestricted double',
]))
# http://www.w3.org/TR/WebIDL/#dfn-primitive-type
PRIMITIVE_TYPES = (frozenset(['boolean']) | NUMERIC_TYPES)
BASIC_TYPES = (PRIMITIVE_TYPES | frozenset([
# Built-in, non-composite, non-object data types
# http://heycam.github.io/webidl/#idl-types
'DOMString',
'ByteString',
'USVString',
'Date',
# http://heycam.github.io/webidl/#idl-types
'void',
]))
TYPE_NAMES = {
# http://heycam.github.io/webidl/#dfn-type-name
'any': 'Any',
'boolean': 'Boolean',
'byte': 'Byte',
'octet': 'Octet',
'short': 'Short',
'unsigned short': 'UnsignedShort',
'long': 'Long',
'unsigned long': 'UnsignedLong',
'long long': 'LongLong',
'unsigned long long': 'UnsignedLongLong',
'float': 'Float',
'unrestricted float': 'UnrestrictedFloat',
'double': 'Double',
'unrestricted double': 'UnrestrictedDouble',
'DOMString': 'String',
'ByteString': 'ByteString',
'USVString': 'USVString',
'object': 'Object',
'Date': 'Date',
}
STRING_TYPES = frozenset([
# http://heycam.github.io/webidl/#es-interface-call (step 10.11)
# (Interface object [[Call]] method's string types.)
'String',
'ByteString',
'USVString',
])
STANDARD_CALLBACK_FUNCTIONS = frozenset([
# http://heycam.github.io/webidl/#common-Function
'Function',
])
################################################################################
# Inheritance
################################################################################
ancestors = defaultdict(list) # interface_name -> ancestors
def inherits_interface(interface_name, ancestor_name):
return (interface_name == ancestor_name or
ancestor_name in ancestors[interface_name])
def set_ancestors(new_ancestors):
ancestors.update(new_ancestors)
class IdlTypeBase(object):
"""Base class for IdlType, IdlUnionType, IdlArrayOrSequenceType and IdlNullableType."""
def __str__(self):
raise NotImplementedError(
'__str__() should be defined in subclasses')
def __getattr__(self, name):
# Default undefined attributes to None (analogous to Jinja variables).
# This allows us to not define default properties in the base class, and
# allows us to relay __getattr__ in IdlNullableType to the inner type.
return None
def resolve_typedefs(self, typedefs):
raise NotImplementedError(
'resolve_typedefs should be defined in subclasses')
def idl_types(self):
"""A generator which yields IdlTypes which are referenced from |self|,
including itself."""
yield self
################################################################################
# IdlType
################################################################################
class IdlType(IdlTypeBase):
# FIXME: incorporate Nullable, etc.
# to support types like short?[] vs. short[]?, instead of treating these
# as orthogonal properties (via flags).
callback_functions = {}
callback_interfaces = set()
dictionaries = set()
enums = {} # name -> values
def __init__(self, base_type, is_unrestricted=False, extended_attributes=None):
super(IdlType, self).__init__()
if is_unrestricted:
self.base_type = 'unrestricted %s' % base_type
else:
self.base_type = base_type
self.extended_attributes = extended_attributes
def __str__(self):
return self.base_type
def __getstate__(self):
return {
'base_type': self.base_type,
'extended_attributes': self.extended_attributes,
}
def __setstate__(self, state):
self.base_type = state['base_type']
self.extended_attributes = state['extended_attributes']
def set_extended_attributes(self, extended_attributes):
self.extended_attributes = extended_attributes
@property
def is_basic_type(self):
return self.base_type in BASIC_TYPES
@property
def is_callback_function(self): # pylint: disable=C0103
return self.base_type in IdlType.callback_functions or self.base_type in STANDARD_CALLBACK_FUNCTIONS
@property
def is_custom_callback_function(self):
# Treat standard callback functions as custom as they aren't generated.
if self.base_type in STANDARD_CALLBACK_FUNCTIONS:
return True
entry = IdlType.callback_functions.get(self.base_type)
callback_function = entry.get('callback_function')
if not callback_function:
return False
return 'Custom' in callback_function.extended_attributes
@property
def is_callback_interface(self):
return self.base_type in IdlType.callback_interfaces
@property
def is_dictionary(self):
return self.base_type in IdlType.dictionaries
@property
def is_enum(self):
# FIXME: add an IdlEnumType class and a resolve_enums step at end of
# IdlDefinitions constructor
return self.name in IdlType.enums
@property
def enum_values(self):
return IdlType.enums.get(self.name)
@property
def enum_type(self):
return self.name if self.is_enum else None
@property
def is_integer_type(self):
return self.base_type in INTEGER_TYPES
@property
def is_void(self):
return self.base_type == 'void'
@property
def is_numeric_type(self):
return self.base_type in NUMERIC_TYPES
@property
def is_primitive_type(self):
return self.base_type in PRIMITIVE_TYPES
@property
def is_interface_type(self):
# Anything that is not another type is an interface type.
# http://www.w3.org/TR/WebIDL/#idl-types
# http://www.w3.org/TR/WebIDL/#idl-interface
# In C++ these are RefPtr types.
return not(self.is_basic_type or
self.is_callback_function or
self.is_dictionary or
self.is_enum or
self.name == 'Any' or
self.name == 'Object' or
self.name == 'Promise') # Promise will be basic in future
@property
def is_string_type(self):
return self.name in STRING_TYPES
@property
def name(self):
"""Return type name
http://heycam.github.io/webidl/#dfn-type-name
"""
base_type = self.base_type
return TYPE_NAMES.get(base_type, base_type)
@classmethod
def set_callback_functions(cls, new_callback_functions):
cls.callback_functions.update(new_callback_functions)
@classmethod
def set_callback_interfaces(cls, new_callback_interfaces):
cls.callback_interfaces.update(new_callback_interfaces)
@classmethod
def set_dictionaries(cls, new_dictionaries):
cls.dictionaries.update(new_dictionaries)
@classmethod
def set_enums(cls, new_enums):
cls.enums.update(new_enums)
def resolve_typedefs(self, typedefs):
# This function either returns |self| or a different object.
# FIXME: Rename typedefs_resolved().
return typedefs.get(self.base_type, self)
################################################################################
# IdlUnionType
################################################################################
class IdlUnionType(IdlTypeBase):
# http://heycam.github.io/webidl/#idl-union
# IdlUnionType has __hash__() and __eq__() methods because they are stored
# in sets.
def __init__(self, member_types):
super(IdlUnionType, self).__init__()
self.member_types = member_types
def __str__(self):
return '(' + ' or '.join(str(member_type) for member_type in self.member_types) + ')'
def __hash__(self):
return hash(self.name)
def __eq__(self, rhs):
return self.name == rhs.name
def __getstate__(self):
return {
'member_types': self.member_types,
}
def __setstate__(self, state):
self.member_types = state['member_types']
@property
def flattened_member_types(self):
"""Returns the set of the union's flattened member types.
https://heycam.github.io/webidl/#dfn-flattened-union-member-types
"""
# We cannot use a set directly because each member is an IdlTypeBase-derived class, and
# comparing two objects of the same type is not the same as comparing their names. In
# other words:
# x = IdlType('ByteString')
# y = IdlType('ByteString')
# x == y # False
# x.name == y.name # True
# |flattened_members|'s keys are type names, the values are type |objects.
# We assume we can use two IDL objects of the same type interchangeably.
flattened_members = {}
for member in self.member_types:
if member.is_nullable:
member = member.inner_type
if member.is_union_type:
for inner_member in member.flattened_member_types:
flattened_members[inner_member.name] = inner_member
else:
flattened_members[member.name] = member
return set(flattened_members.values())
@property
def number_of_nullable_member_types(self):
"""Returns the union's number of nullable types.
http://heycam.github.io/webidl/#dfn-number-of-nullable-member-types
"""
count = 0
for member in self.member_types:
if member.is_nullable:
count += 1
member = member.inner_type
if member.is_union_type:
count += member.number_of_nullable_member_types
return count
@property
def is_union_type(self):
return True
def single_matching_member_type(self, predicate):
matching_types = filter(predicate, self.flattened_member_types)
if len(matching_types) > 1:
raise ValueError('%s is ambiguous.' % self.name)
return matching_types[0] if matching_types else None
@property
def string_member_type(self):
return self.single_matching_member_type(
lambda member_type: (member_type.is_string_type or
member_type.is_enum))
@property
def numeric_member_type(self):
return self.single_matching_member_type(
lambda member_type: member_type.is_numeric_type)
@property
def boolean_member_type(self):
return self.single_matching_member_type(
lambda member_type: member_type.base_type == 'boolean')
@property
def sequence_member_type(self):
return self.single_matching_member_type(
lambda member_type: member_type.is_sequence_type)
@property
def as_union_type(self):
# Note: Use this to "look through" a possible IdlNullableType wrapper.
return self
@property
def name(self):
"""Return type name (or inner type name if nullable)
http://heycam.github.io/webidl/#dfn-type-name
"""
return 'Or'.join(member_type.name for member_type in self.member_types)
def resolve_typedefs(self, typedefs):
self.member_types = [
member_type.resolve_typedefs(typedefs)
for member_type in self.member_types]
return self
def idl_types(self):
yield self
for member_type in self.member_types:
for idl_type in member_type.idl_types():
yield idl_type
################################################################################
# IdlArrayOrSequenceType, IdlSequenceType, IdlFrozenArrayType
################################################################################
# TODO(bashi): Rename this like "IdlArrayTypeBase" or something.
class IdlArrayOrSequenceType(IdlTypeBase):
"""Base class for array-like types."""
def __init__(self, element_type):
super(IdlArrayOrSequenceType, self).__init__()
self.element_type = element_type
def __getstate__(self):
return {
'element_type': self.element_type,
}
def __setstate__(self, state):
self.element_type = state['element_type']
def resolve_typedefs(self, typedefs):
self.element_type = self.element_type.resolve_typedefs(typedefs)
return self
@property
def is_array_or_sequence_type(self):
return True
@property
def is_sequence_type(self):
return False
@property
def is_frozen_array(self):
return False
@property
def enum_values(self):
return self.element_type.enum_values
@property
def enum_type(self):
return self.element_type.enum_type
def idl_types(self):
yield self
for idl_type in self.element_type.idl_types():
yield idl_type
class IdlSequenceType(IdlArrayOrSequenceType):
def __init__(self, element_type):
super(IdlSequenceType, self).__init__(element_type)
def __str__(self):
return 'sequence<%s>' % self.element_type
@property
def name(self):
return self.element_type.name + 'Sequence'
@property
def is_sequence_type(self):
return True
class IdlFrozenArrayType(IdlArrayOrSequenceType):
def __init__(self, element_type):
super(IdlFrozenArrayType, self).__init__(element_type)
def __str__(self):
return 'FrozenArray<%s>' % self.element_type
@property
def name(self):
return self.element_type.name + 'Array'
@property
def is_frozen_array(self):
return True
################################################################################
# IdlRecordType
################################################################################
class IdlRecordType(IdlTypeBase):
def __init__(self, key_type, value_type):
super(IdlRecordType, self).__init__()
self.key_type = key_type
self.value_type = value_type
def __str__(self):
return 'record<%s, %s>' % (self.key_type, self.value_type)
def __getstate__(self):
return {
'key_type': self.key_type,
'value_type': self.value_type,
}
def __setstate__(self, state):
self.key_type = state['key_type']
self.value_type = state['value_type']
def idl_types(self):
yield self
for idl_type in self.key_type.idl_types():
yield idl_type
for idl_type in self.value_type.idl_types():
yield idl_type
def resolve_typedefs(self, typedefs):
self.key_type = self.key_type.resolve_typedefs(typedefs)
self.value_type = self.value_type.resolve_typedefs(typedefs)
return self
@property
def is_record_type(self):
return True
@property
def name(self):
return self.key_type.name + self.value_type.name + 'Record'
################################################################################
# IdlNullableType
################################################################################
class IdlNullableType(IdlTypeBase):
def __init__(self, inner_type):
super(IdlNullableType, self).__init__()
self.inner_type = inner_type
def __str__(self):
# FIXME: Dictionary::ConversionContext::setConversionType can't
# handle the '?' in nullable types (passes nullability separately).
# Update that function to handle nullability from the type name,
# simplifying its signature.
# return str(self.inner_type) + '?'
return str(self.inner_type)
def __getattr__(self, name):
return getattr(self.inner_type, name)
def __getstate__(self):
return {
'inner_type': self.inner_type,
}
def __setstate__(self, state):
self.inner_type = state['inner_type']
@property
def is_nullable(self):
return True
@property
def name(self):
return self.inner_type.name + 'OrNull'
@property
def enum_values(self):
# Nullable enums are handled by preprending a None value to the list of
# enum values. This None value is converted to nullptr on the C++ side,
# which matches the JavaScript 'null' in the enum parsing code.
inner_values = self.inner_type.enum_values
if inner_values:
return [None] + inner_values
return None
def resolve_typedefs(self, typedefs):
self.inner_type = self.inner_type.resolve_typedefs(typedefs)
return self
def idl_types(self):
yield self
for idl_type in self.inner_type.idl_types():
yield idl_type
| 7,141 |
456 | <filename>YCCustomTextLib/src/main/java/com/ns/yc/yccustomtextlib/edit/model/HyperEditData.java
/*
Copyright 2017 yangchong211(github.com/yangchong211)
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.ns.yc.yccustomtextlib.edit.model;
import java.io.Serializable;
/**
* <pre>
* @author 杨充
* blog : https://github.com/yangchong211
* time : 2016/3/31
* desc : 富文本实体类
* revise: 目前就支持简单的富文本,文字+图片
* </pre>
*/
public class HyperEditData implements Serializable {
/**
* 富文本输入文字内容
*/
private String inputStr;
/**
* 富文本输入图片地址
*/
private String imagePath;
/**
* 类型:1,代表文字;2,代表图片
*/
private int type;
public String getInputStr() {
return inputStr;
}
public void setInputStr(String inputStr) {
this.inputStr = inputStr;
}
public String getImagePath() {
return imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
}
| 703 |
1,389 | #include "addsuperstakerpage.h"
#include "qt/forms/ui_addsuperstakerpage.h"
#include <qt/walletmodel.h>
#include <QMessageBox>
AddSuperStakerPage::AddSuperStakerPage(QWidget *parent) :
QDialog(parent),
ui(new Ui::AddSuperStakerPage),
m_model(nullptr)
{
ui->setupUi(this);
setWindowTitle(tr("Add super staker"));
connect(ui->lineEditStakerName, &QLineEdit::textChanged, this, &AddSuperStakerPage::on_updateAddStakerButton);
connect(ui->lineEditStakerAddress, &QComboBox::currentTextChanged, this, &AddSuperStakerPage::on_updateAddStakerButton);
}
AddSuperStakerPage::~AddSuperStakerPage()
{
delete ui;
}
void AddSuperStakerPage::setModel(WalletModel *_model)
{
m_model = _model;
if(m_model)
{
ui->lineEditStakerAddress->setWalletModel(m_model);
}
}
void AddSuperStakerPage::clearAll()
{
ui->lineEditStakerName->setText("");
ui->lineEditStakerAddress->setCurrentIndex(-1);
}
void AddSuperStakerPage::accept()
{
clearAll();
QDialog::accept();
}
void AddSuperStakerPage::reject()
{
clearAll();
QDialog::reject();
}
void AddSuperStakerPage::show()
{
ui->lineEditStakerName->setFocus();
QDialog::show();
}
void AddSuperStakerPage::on_cancelButton_clicked()
{
reject();
}
void AddSuperStakerPage::on_updateAddStakerButton()
{
bool enabled = true;
QString stakerName = ui->lineEditStakerName->text().trimmed();
QString stakerAddress = ui->lineEditStakerAddress->currentText();
if(stakerName.isEmpty())
{
enabled = false;
}
if(stakerAddress.isEmpty() || !ui->lineEditStakerAddress->isValidAddress())
{
enabled = false;
}
ui->addSuperStakerButton->setEnabled(enabled);
}
void AddSuperStakerPage::on_addSuperStakerButton_clicked()
{
if(m_model)
{
bool fSuperStake = m_model->wallet().getEnabledSuperStaking();
if(!fSuperStake)
{
QMessageBox::information(this, tr("Super staking"), tr("Enable super staking from the option menu in order to start the super staker."));
}
QString stakerAddress = ui->lineEditStakerAddress->currentText();
// Check if super staker exist in the wallet
if(m_model->wallet().existSuperStaker(stakerAddress.toStdString()))
{
QMessageBox::warning(this, tr("Super staking"), tr("The super staker address exist in the wallet list."));
return;
}
QString stakerName = ui->lineEditStakerName->text().trimmed();
interfaces::SuperStakerInfo superStaker;
superStaker.staker_address = stakerAddress.toStdString();
superStaker.staker_name = stakerName.toStdString();
m_model->wallet().addSuperStakerEntry(superStaker);
accept();
}
}
| 1,230 |
335 | # ifndef CPPAD_UTILITY_LU_SOLVE_HPP
# define CPPAD_UTILITY_LU_SOLVE_HPP
/* --------------------------------------------------------------------------
CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-17 <NAME>
CppAD is distributed under multiple licenses. This distribution is under
the terms of the
GNU General Public License Version 3.
A copy of this license is included in the COPYING file of this distribution.
Please visit http://www.coin-or.org/CppAD/ for information on other licenses.
-------------------------------------------------------------------------- */
/*
$begin LuSolve$$
$escape #$$
$spell
cppad.hpp
det
exp
Leq
typename
bool
const
namespace
std
Geq
Lu
CppAD
signdet
logdet
$$
$section Compute Determinant and Solve Linear Equations$$
$mindex LuSolve Lu$$
$pre
$$
$head Syntax$$ $codei%# include <cppad/utility/lu_solve.hpp>
%$$
$icode%signdet% = LuSolve(%n%, %m%, %A%, %B%, %X%, %logdet%)%$$
$head Description$$
Use an LU factorization of the matrix $icode A$$ to
compute its determinant
and solve for $icode X$$ in the linear of equation
$latex \[
A * X = B
\] $$
where $icode A$$ is an
$icode n$$ by $icode n$$ matrix,
$icode X$$ is an
$icode n$$ by $icode m$$ matrix, and
$icode B$$ is an $latex n x m$$ matrix.
$head Include$$
The file $code cppad/lu_solve.hpp$$ is included by $code cppad/cppad.hpp$$
but it can also be included separately with out the rest of
the $code CppAD$$ routines.
$head Factor and Invert$$
This routine is an easy to user interface to
$cref LuFactor$$ and $cref LuInvert$$ for computing determinants and
solutions of linear equations.
These separate routines should be used if
one right hand side $icode B$$
depends on the solution corresponding to another
right hand side (with the same value of $icode A$$).
In this case only one call to $code LuFactor$$ is required
but there will be multiple calls to $code LuInvert$$.
$head Matrix Storage$$
All matrices are stored in row major order.
To be specific, if $latex Y$$ is a vector
that contains a $latex p$$ by $latex q$$ matrix,
the size of $latex Y$$ must be equal to $latex p * q $$ and for
$latex i = 0 , \ldots , p-1$$,
$latex j = 0 , \ldots , q-1$$,
$latex \[
Y_{i,j} = Y[ i * q + j ]
\] $$
$head signdet$$
The return value $icode signdet$$ is a $code int$$ value
that specifies the sign factor for the determinant of $icode A$$.
This determinant of $icode A$$ is zero if and only if $icode signdet$$
is zero.
$head n$$
The argument $icode n$$ has type $code size_t$$
and specifies the number of rows in the matrices
$icode A$$,
$icode X$$,
and $icode B$$.
The number of columns in $icode A$$ is also equal to $icode n$$.
$head m$$
The argument $icode m$$ has type $code size_t$$
and specifies the number of columns in the matrices
$icode X$$
and $icode B$$.
If $icode m$$ is zero,
only the determinant of $icode A$$ is computed and
the matrices $icode X$$ and $icode B$$ are not used.
$head A$$
The argument $icode A$$ has the prototype
$codei%
const %FloatVector% &%A%
%$$
and the size of $icode A$$ must equal $latex n * n$$
(see description of $cref/FloatVector/LuSolve/FloatVector/$$ below).
This is the $latex n$$ by $icode n$$ matrix that
we are computing the determinant of
and that defines the linear equation.
$head B$$
The argument $icode B$$ has the prototype
$codei%
const %FloatVector% &%B%
%$$
and the size of $icode B$$ must equal $latex n * m$$
(see description of $cref/FloatVector/LuSolve/FloatVector/$$ below).
This is the $latex n$$ by $icode m$$ matrix that
defines the right hand side of the linear equations.
If $icode m$$ is zero, $icode B$$ is not used.
$head X$$
The argument $icode X$$ has the prototype
$codei%
%FloatVector% &%X%
%$$
and the size of $icode X$$ must equal $latex n * m$$
(see description of $cref/FloatVector/LuSolve/FloatVector/$$ below).
The input value of $icode X$$ does not matter.
On output, the elements of $icode X$$ contain the solution
of the equation we wish to solve
(unless $icode signdet$$ is equal to zero).
If $icode m$$ is zero, $icode X$$ is not used.
$head logdet$$
The argument $icode logdet$$ has prototype
$codei%
%Float% &%logdet%
%$$
On input, the value of $icode logdet$$ does not matter.
On output, it has been set to the
log of the determinant of $icode A$$
(but not quite).
To be more specific,
the determinant of $icode A$$ is given by the formula
$codei%
%det% = %signdet% * exp( %logdet% )
%$$
This enables $code LuSolve$$ to use logs of absolute values
in the case where $icode Float$$ corresponds to a real number.
$head Float$$
The type $icode Float$$ must satisfy the conditions
for a $cref NumericType$$ type.
The routine $cref CheckNumericType$$ will generate an error message
if this is not the case.
In addition, the following operations must be defined for any pair
of $icode Float$$ objects $icode x$$ and $icode y$$:
$table
$bold Operation$$ $cnext $bold Description$$ $rnext
$codei%log(%x%)%$$ $cnext
returns the logarithm of $icode x$$ as a $icode Float$$ object
$tend
$head FloatVector$$
The type $icode FloatVector$$ must be a $cref SimpleVector$$ class with
$cref/elements of type Float/SimpleVector/Elements of Specified Type/$$.
The routine $cref CheckSimpleVector$$ will generate an error message
if this is not the case.
$head LeqZero$$
Including the file $code lu_solve.hpp$$ defines the template function
$codei%
template <typename %Float%>
bool LeqZero<%Float%>(const %Float% &%x%)
%$$
in the $code CppAD$$ namespace.
This function returns true if $icode x$$ is less than or equal to zero
and false otherwise.
It is used by $code LuSolve$$ to avoid taking the log of
zero (or a negative number if $icode Float$$ corresponds to real numbers).
This template function definition assumes that the operator
$code <=$$ is defined for $icode Float$$ objects.
If this operator is not defined for your use of $icode Float$$,
you will need to specialize this template so that it works for your
use of $code LuSolve$$.
$pre
$$
Complex numbers do not have the operation or $code <=$$ defined.
In addition, in the complex case,
one can take the log of a negative number.
The specializations
$codei%
bool LeqZero< std::complex<float> > (const std::complex<float> &%x%)
bool LeqZero< std::complex<double> >(const std::complex<double> &%x%)
%$$
are defined by including $code lu_solve.hpp$$.
These return true if $icode x$$ is zero and false otherwise.
$head AbsGeq$$
Including the file $code lu_solve.hpp$$ defines the template function
$codei%
template <typename %Float%>
bool AbsGeq<%Float%>(const %Float% &%x%, const %Float% &%y%)
%$$
If the type $icode Float$$ does not support the $code <=$$ operation
and it is not $code std::complex<float>$$ or $code std::complex<double>$$,
see the documentation for $code AbsGeq$$ in $cref/LuFactor/LuFactor/AbsGeq/$$.
$children%
example/utility/lu_solve.cpp%
omh/lu_solve_hpp.omh
%$$
$head Example$$
The file
$cref lu_solve.cpp$$
contains an example and test of using this routine.
It returns true if it succeeds and false otherwise.
$head Source$$
The file $cref lu_solve.hpp$$ contains the
current source code that implements these specifications.
$end
--------------------------------------------------------------------------
*/
// BEGIN C++
# include <complex>
# include <vector>
// link exp for float and double cases
# include <cppad/base_require.hpp>
# include <cppad/core/cppad_assert.hpp>
# include <cppad/utility/check_simple_vector.hpp>
# include <cppad/utility/check_numeric_type.hpp>
# include <cppad/utility/lu_factor.hpp>
# include <cppad/utility/lu_invert.hpp>
namespace CppAD { // BEGIN CppAD namespace
// LeqZero
template <typename Float>
inline bool LeqZero(const Float &x)
{ return x <= Float(0); }
inline bool LeqZero( const std::complex<double> &x )
{ return x == std::complex<double>(0); }
inline bool LeqZero( const std::complex<float> &x )
{ return x == std::complex<float>(0); }
// LuSolve
template <typename Float, typename FloatVector>
int LuSolve(
size_t n ,
size_t m ,
const FloatVector &A ,
const FloatVector &B ,
FloatVector &X ,
Float &logdet )
{
// check numeric type specifications
CheckNumericType<Float>();
// check simple vector class specifications
CheckSimpleVector<Float, FloatVector>();
size_t p; // index of pivot element (diagonal of L)
int signdet; // sign of the determinant
Float pivot; // pivot element
// the value zero
const Float zero(0);
// pivot row and column order in the matrix
std::vector<size_t> ip(n);
std::vector<size_t> jp(n);
// -------------------------------------------------------
CPPAD_ASSERT_KNOWN(
size_t(A.size()) == n * n,
"Error in LuSolve: A must have size equal to n * n"
);
CPPAD_ASSERT_KNOWN(
size_t(B.size()) == n * m,
"Error in LuSolve: B must have size equal to n * m"
);
CPPAD_ASSERT_KNOWN(
size_t(X.size()) == n * m,
"Error in LuSolve: X must have size equal to n * m"
);
// -------------------------------------------------------
// copy A so that it does not change
FloatVector Lu(A);
// copy B so that it does not change
X = B;
// Lu factor the matrix A
signdet = LuFactor(ip, jp, Lu);
// compute the log of the determinant
logdet = Float(0);
for(p = 0; p < n; p++)
{ // pivot using the max absolute element
pivot = Lu[ ip[p] * n + jp[p] ];
// check for determinant equal to zero
if( pivot == zero )
{ // abort the mission
logdet = Float(0);
return 0;
}
// update the determinant
if( LeqZero ( pivot ) )
{ logdet += log( - pivot );
signdet = - signdet;
}
else logdet += log( pivot );
}
// solve the linear equations
LuInvert(ip, jp, Lu, X);
// return the sign factor for the determinant
return signdet;
}
} // END CppAD namespace
// END C++
# endif
| 3,394 |
5,169 | {
"name": "AACountTime",
"version": "1.0.1",
"summary": "iOS count Time lib",
"homepage": "https://github.com/CYHAI9/AACountTime",
"license": "MIT",
"authors": {
"chenyinhai": "<EMAIL>"
},
"platforms": {
"ios": "8.0"
},
"source": {
"git": "https://github.com/CYHAI9/AACountTime.git",
"tag": "1.0.1"
},
"source_files": "AACount/*.{h,m}"
}
| 183 |
535 | <gh_stars>100-1000
from sys import exit
from blessings import Terminal
from utils.settings import settings
import sys
NO_SETTINGS=False
try:
if sys.argv[1] == "--store-token" or sys.argv[1] == "--token":
NO_SETTINGS=True
except IndexError:
pass
class GlobalsContainer:
def __init__(self):
self.term = Terminal()
self.client = None
self.server_log_tree = []
self.input_buffer = []
self.user_input = ""
self.channels_entered = []
def initClient(self):
from client.client import Client
if NO_SETTINGS:
messages=100
else:
messages=settings["max_messages"]
self.client = Client(max_messages=messages)
gc = GlobalsContainer()
# kills the program and all its elements gracefully
def kill():
# attempt to cleanly close our loops
import asyncio
try: gc.client.close()
except: pass
try: asyncio.get_event_loop().close()
except: pass
try:# since we're exiting, we can be nice and try to clear the screen
from os import system
system("clear")
except: pass
exit()
# returns a "Channel" object from the given string
async def string2channel(channel):
for srv in gc.client.servers:
if srv.name == channel.server.name:
for chan in srv.channels:
if chan.name == channel:
return chan
# returns a "Channellog" object from the given string
async def get_channel_log(channel):
for srvlog in gc.server_log_tree:
if srvlog.get_name().lower() == channel.server.name.lower():
for chanlog in srvlog.get_logs():
if chanlog.get_name().lower() == channel.name.lower():
return chanlog
# returns a "Channellog" from a given "Channel"
async def chan2log(chan):
for srvlog in gc.server_log_tree:
if srvlog.get_name().lower() == chan.server.name.lower():
for clog in srvlog.get_logs():
if clog.get_name().lower() == chan.name.lower():
return clog
# returns a "Serverlog" from a given "Server"
async def serv2log(serv):
for srvlog in gc.server_log_tree:
if srvlog.get_name().lower() == serv.name.lower():
return srvlog
# takes in a string, returns the appropriate term.color
async def get_color(string):
arg = string.strip().lower()
if arg == "white": return gc.term.white
if arg == "black": return gc.term.black
if arg == "red": return gc.term.red
if arg == "blue": return gc.term.blue
if arg == "yellow": return gc.term.yellow
if arg == "cyan": return gc.term.cyan
if arg == "magenta": return gc.term.magenta
if arg == "green": return gc.term.green
if arg == "on_white": return gc.term.on_white
if arg == "on_black": return gc.term.on_black
if arg == "on_red": return gc.term.on_red
if arg == "on_blue": return gc.term.on_blue
if arg == "on_yellow": return gc.term.on_yellow
if arg == "on_cyan": return gc.term.on_cyan
if arg == "on_magenta": return gc.term.on_magenta
if arg == "on_green": return gc.term.on_green
if arg == "blink_white": return gc.term.blink_white
if arg == "blink_black": return gc.term.blink_black
if arg == "blink_red": return gc.term.blink_red
if arg == "blink_blue": return gc.term.blink_blue
if arg == "blink_yellow": return gc.term.blink_yellow
if arg == "blink_cyan": return gc.term.blink_cyan
if arg == "blink_magenta": return gc.term.blink_magenta
if arg == "blink_green": return gc.term.blink_green
# if we're here, someone has one of their settings.yaml
# colors defined wrong. We'll be nice and just return white.
return gc.term.normal + gc.term.white
| 1,633 |
777 | // Copyright 2015 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_TEST_BASE_ALWAYS_ON_TOP_WINDOW_KILLER_WIN_H_
#define CHROME_TEST_BASE_ALWAYS_ON_TOP_WINDOW_KILLER_WIN_H_
enum class RunType {
// Indicates cleanup is happening before the test run.
BEFORE_TEST,
// Indicates cleanup is happening after the test run.
AFTER_TEST,
};
// Logs if there are any always on top windows, and if one is a system dialog
// closes it.
void KillAlwaysOnTopWindows(RunType run_type);
#endif // CHROME_TEST_BASE_ALWAYS_ON_TOP_WINDOW_KILLER_WIN_H_
| 226 |
2,637 | /*
* Copyright 2019, Cypress Semiconductor Corporation or a subsidiary of
* Cypress Semiconductor Corporation. All Rights Reserved.
*
* This software, associated documentation and materials ("Software")
* is owned by Cypress Semiconductor Corporation,
* or one of its subsidiaries ("Cypress") and is protected by and subject to
* worldwide patent protection (United States and foreign),
* United States copyright laws and international treaty provisions.
* Therefore, you may use this Software only as provided in the license
* agreement accompanying the software package from which you
* obtained this Software ("EULA").
* If no EULA applies, Cypress hereby grants you a personal, non-exclusive,
* non-transferable license to copy, modify, and compile the Software
* source code solely for use in connection with Cypress's
* integrated circuit products. Any reproduction, modification, translation,
* compilation, or representation of this Software except as specified
* above is prohibited without the express written permission of Cypress.
*
* Disclaimer: THIS SOFTWARE IS PROVIDED AS-IS, WITH NO WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, NONINFRINGEMENT, IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. Cypress
* reserves the right to make changes to the Software without notice. Cypress
* does not assume any liability arising out of the application or use of the
* Software or any product or circuit described in the Software. Cypress does
* not authorize its products for use in any products where a malfunction or
* failure of the Cypress product may reasonably be expected to result in
* significant property damage, injury or death ("High Risk Product"). By
* including Cypress's product in a High Risk Product, the manufacturer
* of such system or application assumes all risk of such use and in doing
* so agrees to indemnify Cypress against all liability.
*/
#include <string.h> /* For strlen, stricmp, memcpy. memset */
#include <stddef.h>
#include "wwd_management.h"
#include "wwd_wifi.h"
#include "wwd_assert.h"
#include "wwd_wlioctl.h"
#include "wwd_debug.h"
#include "platform/wwd_platform_interface.h"
#include "network/wwd_buffer_interface.h"
#include "network/wwd_network_constants.h"
#include "RTOS/wwd_rtos_interface.h"
#include "internal/wwd_sdpcm.h"
#include "internal/wwd_bcmendian.h"
#include "internal/wwd_ap.h"
#include "internal/wwd_internal.h"
#include "wwd_bus_protocol.h"
#include "wiced_utilities.h"
#include "wiced_low_power.h"
#include "wwd_events.h"
#include "wwd_wifi_sleep.h"
#include "internal/bus_protocols/wwd_bus_protocol_interface.h"
#include "wwd_wifi_chip_common.h"
/******************************************************
* Macros
******************************************************/
//#define WWD_WIFI_SLEEP_DEBUG_OUTPUT/* uncomment for all debug output */
#ifdef WWD_WIFI_SLEEP_DEBUG_OUTPUT
#define WWD_WIFI_SLEEP_DEBUG( args ) WPRINT_APP_INFO( args )
#define WWD_WIFI_SLEEP_INFO( args ) WPRINT_APP_INFO( args )
#define WWD_WIFI_SLEEP_ERROR( args ) WPRINT_APP_INFO( args )
#else
#define WWD_WIFI_SLEEP_DEBUG( args ) WPRINT_WWD_DEBUG( args )
#define WWD_WIFI_SLEEP_INFO( args ) WPRINT_WWD_INFO( args )
#define WWD_WIFI_SLEEP_ERROR( args ) WPRINT_WWD_ERROR( args )
#endif
#define CHECK_RETURN( expr ) { wwd_result_t check_res = (expr); if ( check_res != WWD_SUCCESS ) { wiced_assert("Command failed\n", 0 == 1); return check_res; } }
/******************************************************
* Local Structures
******************************************************/
/* ULP SHM Offsets info */
typedef struct ulp_shm_info {
uint32_t m_ulp_ctrl_sdio;
uint32_t m_ulp_wakeevt_ind;
uint32_t m_ulp_wakeind;
} ulp_shm_info_t;
ulp_shm_info_t ulp_offsets;
/******************************************************
* Static Variables
******************************************************/
static const wwd_event_num_t ulp_events[] = { WLC_E_ULP, WLC_E_NONE };
static volatile wwd_ds_state_t WICED_DEEP_SLEEP_SAVED_VAR( wwd_wifi_ds1_state ) = STATE_DS_DISABLED;
static wiced_bool_t last_wake_from_fw = WICED_FALSE;
static wwd_result_t last_wake_result = WWD_SUCCESS;
static volatile wwd_ds1_state_change_callback_t WICED_DEEP_SLEEP_SAVED_VAR( ds_notify_callback ) = NULL;
static volatile void* WICED_DEEP_SLEEP_SAVED_VAR( ds_notify_callback_user_parameter ) = NULL;
/******************************************************
* Function prototypes
******************************************************/
static void ds_state_set( wwd_ds_state_t new_state );
static wwd_result_t wwd_wifi_ds1_finish_wake( wiced_bool_t wake_from_firmware );
void* wwd_wifi_event_ulp_handler( const wwd_event_header_t* event_header, const uint8_t* event_data, /*@returned@*/ void* handler_user_data );
/* enable and set up wowl patterns */
wwd_result_t wwd_wifi_wowl_enable( wwd_interface_t interface, uint32_t wowl_caps, uint32_t wowl_os,
wl_mkeep_alive_pkt_t *wowl_keepalive_data, uint8_t *pattern_data, uint32_t pattern_data_size, uint32_t *arp_host_ip_v4_address )
{
wwd_result_t wwd_result = wwd_wifi_set_iovar_value( IOVAR_STR_WOWL, wowl_caps, interface );
WWD_WIFI_SLEEP_DEBUG(("wowl\n"));
if ( WWD_SUCCESS != wwd_result )
{
WWD_WIFI_SLEEP_ERROR(("Error on wowl set %d\n", wwd_result));
return wwd_result;
}
/* Only bother setting wowl_os to a non-zero value */
if ( 0 != wowl_os )
{
WWD_WIFI_SLEEP_DEBUG(("wowl-os\n"));
CHECK_RETURN( wwd_wifi_set_iovar_value( IOVAR_STR_WOWL_OS, wowl_os, interface ) );
}
/* Set up any type of wowl requested */
if ( NULL != wowl_keepalive_data )
{
CHECK_RETURN( wwd_wifi_set_iovar_buffer( IOVAR_STR_WOWL_KEEP_ALIVE, wowl_keepalive_data, (uint16_t) ( wowl_keepalive_data->length + wowl_keepalive_data->len_bytes ), interface ) );
}
if ( NULL != pattern_data )
{
const void *buffer_pointers[2] = { IOVAR_STR_WOWL_PATTERN_ADD, (const void*)pattern_data };
uint16_t buffer_sizes[2] = { sizeof(IOVAR_STR_WOWL_PATTERN_ADD), (uint16_t)pattern_data_size };
WWD_WIFI_SLEEP_DEBUG(("pre-pattern add\n"));
wwd_result = wwd_wifi_set_iovar_buffers( IOVAR_STR_WOWL_PATTERN, buffer_pointers, buffer_sizes, 2, interface );
if ( WWD_SUCCESS != wwd_result )
{
WWD_WIFI_SLEEP_DEBUG(("add pattern result=%d\n", (int)wwd_result));
}
WWD_WIFI_SLEEP_DEBUG(("post-pattern add\n"));
}
if ( NULL != arp_host_ip_v4_address )
{
CHECK_RETURN( wwd_wifi_set_iovar_buffer( IOVAR_STR_WOWL_ARP_HOST_IP, arp_host_ip_v4_address, sizeof( *arp_host_ip_v4_address ), interface ) );
}
WWD_WIFI_SLEEP_DEBUG(("End wowl enable\n"));
return wwd_result;
}
/* called when state is changed */
static void ds_state_set( wwd_ds_state_t new_state )
{
wwd_wifi_ds1_state = new_state;
if ( NULL != ds_notify_callback )
{
ds_notify_callback( (void*)ds_notify_callback_user_parameter );
}
}
void wwd_wifi_ds1_get_status_string( uint8_t *output, uint16_t max_output_length )
{
const char *state = NULL;
switch ( wwd_wifi_ds1_get_state( ) )
{
case STATE_DS_DISABLED:
state = "STATE_DS_DISABLED";
break;
case STATE_DS_ENABLING:
state = "STATE_DS_ENABLING";
break;
case STATE_DS_ENABLED:
state = "STATE_DS_ENABLED";
break;
case STATE_DS_DISABLING:
state = "STATE_DS_DISABLING";
break;
default:
wiced_assert("Unknown DS1 state", 0 != 0 );
state = "unknown";
}
snprintf( (char*)output, max_output_length, "%s. Last %s wake result %d ", state,
( WICED_TRUE == last_wake_from_fw ) ? "FIRMWARE" : "HOST", last_wake_result );
}
/* Register a callback for deep sleep state changes; current state can then be queried */
wwd_result_t wwd_wifi_ds1_set_state_change_callback( wwd_ds1_state_change_callback_t callback, void *user_parameter )
{
ds_notify_callback = callback;
ds_notify_callback_user_parameter = user_parameter;
return WWD_SUCCESS;
}
/* Get current DS1 state */
extern wwd_ds_state_t wwd_wifi_ds1_get_state( void )
{
return wwd_wifi_ds1_state;
}
void* wwd_wifi_event_ulp_handler( const wwd_event_header_t* event_header, const uint8_t* event_data, /*@returned@*/ void* handler_user_data )
{
wl_ulp_event_t* ulp_evt = (wl_ulp_event_t *)event_data;
UNUSED_PARAMETER(event_header);
UNUSED_PARAMETER(event_data);
UNUSED_PARAMETER(handler_user_data);
WWD_WIFI_SLEEP_DEBUG(("%s : ULP event handler triggered [%d]\n", __FUNCTION__, ulp_evt->ulp_dongle_action));
switch ( ulp_evt->ulp_dongle_action )
{
case WL_ULP_ENTRY:
/* Just mark DS1 enabled flag to TRUE so that DS1 exit interrupt will be processed by WWD */
ds_state_set( STATE_DS_ENABLED );
break;
default:
break;
}
return NULL;
}
wwd_result_t wwd_wifi_ds1_disable( wwd_interface_t interface )
{
wwd_result_t wwd_result = wwd_wifi_set_iovar_value( IOVAR_STR_ULP, 0, interface );
if ( WWD_SUCCESS != wwd_result )
{
WWD_WIFI_SLEEP_ERROR(("Error %d\n", wwd_result));
return wwd_result;
}
WWD_WIFI_SLEEP_DEBUG(("disable wowl\n"));
CHECK_RETURN( wwd_wifi_wowl_disable( interface ) );
return WWD_SUCCESS;
}
/* have device go into ds1 after given wait period */
wwd_result_t wwd_wifi_enter_ds1( wwd_interface_t interface, uint32_t ulp_wait_milliseconds )
{
uint32_t ulp_enable = 1;
wwd_result_t result;
result = wwd_wifi_get_iovar_buffer( "ulp_sdioctrl", (uint8_t*)&ulp_offsets, sizeof( ulp_offsets ), WWD_STA_INTERFACE );
if ( WWD_SUCCESS != result )
{
WWD_WIFI_SLEEP_ERROR(("unable to load sdio ctl offsets\n"));
goto error;
}
WWD_WIFI_SLEEP_DEBUG(("Setting ulp evt hdlr\n"));
/* listen for ULP ready: avoid race condition by doing this first */
CHECK_RETURN( wwd_management_set_event_handler( ulp_events, wwd_wifi_event_ulp_handler, NULL, WWD_STA_INTERFACE ) );
WWD_WIFI_SLEEP_DEBUG(("ulp wait\n"));
/* then trigger ULP */
CHECK_RETURN( wwd_wifi_set_iovar_value( IOVAR_STR_ULP_WAIT, ulp_wait_milliseconds, interface ) );
WWD_WIFI_SLEEP_DEBUG(("ulp\n"));
CHECK_RETURN( wwd_wifi_set_iovar_value( IOVAR_STR_ULP, ulp_enable, interface ) );
WWD_WIFI_SLEEP_DEBUG(("ulp set to enable\n"));
/* wait for number of ulp wait milliseconds prior to setting enabled, to allow FW to settle */
ds_state_set( STATE_DS_ENABLING );
return WWD_SUCCESS;
error:
return result;
}
/* turn off wowl and clear any previously added patterns */
wwd_result_t wwd_wifi_wowl_disable( wwd_interface_t interface )
{
uint32_t val_disable = 0;
WWD_WIFI_SLEEP_DEBUG(("clear wowl\n"));
CHECK_RETURN( wwd_wifi_set_iovar_buffer( IOVAR_STR_WOWL, &val_disable, sizeof( val_disable ), interface) );
WWD_WIFI_SLEEP_DEBUG(("clear wowl os\n"));
CHECK_RETURN( wwd_wifi_set_iovar_value( IOVAR_STR_WOWL_OS, val_disable, interface ) );
WWD_WIFI_SLEEP_DEBUG(("clear pattern\n"));
CHECK_RETURN( wwd_wifi_set_iovar_buffer( IOVAR_STR_WOWL_PATTERN, (uint8_t*)IOVAR_STR_WOWL_PATTERN_CLR, sizeof( IOVAR_STR_WOWL_PATTERN_CLR ), interface ) );
return WWD_SUCCESS;
}
/* process any wake requests */
wwd_result_t wwd_wifi_ds1_wake_handle( wiced_bool_t force )
{
wiced_bool_t wake_from_firmware = WICED_FALSE;
/* Is WWD in ds1? */
if ( STATE_DS_ENABLED == wwd_wifi_ds1_state )
{
/* Wake need from host tx or forced (eg cmd line)? */
if ( WICED_TRUE == wwd_sdpcm_has_tx_packet( ) || WICED_TRUE == force )
{
WWD_WIFI_SLEEP_DEBUG(("wake due %s\n", ( WICED_TRUE == force ) ? "force" : "tx"));
wake_from_firmware = WICED_FALSE;
}
else if ( WICED_TRUE == wwd_bus_wake_interrupt_present( ) )
{
WWD_WIFI_SLEEP_DEBUG(("firmware wake need detected\n"));
wake_from_firmware = WICED_TRUE;
}
/* else no wake reason so no-op */
else
{
/* bail immediately; no more to do */
return WWD_SUCCESS;
}
/* do the actual waking */
return wwd_wifi_ds1_finish_wake( wake_from_firmware );
}
return WWD_SUCCESS;
}
static wwd_result_t wwd_wifi_ds1_finish_wake( wiced_bool_t wake_from_firmware )
{
wwd_result_t wwd_result = WWD_SUCCESS;
if ( STATE_DS_ENABLED != wwd_wifi_ds1_state )
{
WWD_WIFI_SLEEP_DEBUG(("DS1 not yet enabled; can't wake\n"));
return WWD_SUCCESS;
}
WWD_WIFI_SLEEP_DEBUG(("wake from firmware=%d\n", wake_from_firmware));
/* we are going to disable DS and return to normal mode */
ds_state_set( STATE_DS_DISABLING );
last_wake_from_fw = wake_from_firmware;
/* reinit tx and rx counters FIRST, so code is in sync */
wwd_sdpcm_bus_vars_init( );
wwd_result = wwd_wlan_bus_complete_ds_wake( wake_from_firmware, ulp_offsets.m_ulp_wakeevt_ind, ulp_offsets.m_ulp_wakeind, ulp_offsets.m_ulp_ctrl_sdio );
if ( WWD_SUCCESS != wwd_result )
{
WWD_WIFI_SLEEP_ERROR(("Error completing bus DS wake\n"));
/*@-unreachable@*/ /* Reachable after hitting assert */
goto exit;
/*@+unreachable@*/
}
wwd_result = wwd_bus_reinit( wake_from_firmware );
if ( wwd_result != WWD_SUCCESS )
{
WWD_WIFI_SLEEP_ERROR(("SDIO Reinit failed with error %d\n", wwd_result));
}
else
{
/* clear only if everything succeeded */
ds_state_set( STATE_DS_DISABLED );
}
WWD_WIFI_SLEEP_DEBUG(("Finish wake done: result %d\n", (int)wwd_result));
exit:
last_wake_result = wwd_result;
WWD_WIFI_SLEEP_DEBUG(("Wake result: %s!\n", ( WWD_SUCCESS == wwd_result ) ? "Success" : "Fail" ));
if ( WWD_SUCCESS != wwd_result )
{
ds_state_set( STATE_DS_ENABLED );
}
return wwd_result;
}
| 5,998 |
715 | <reponame>iabhimanyu/Algorithms
#include<iostream>
#include<stdlib.h>
using namespace std;
struct node{
int data;
struct node *next;
};
struct node *start = NULL;
void create(int n){
struct node *new_node, *current_node;
new_node=(struct node*)malloc(sizeof(node));
new_node->data=n;
new_node->next=NULL;
if(start==NULL){
start=new_node;
current_node=new_node;
}else{
current_node->next=new_node;
current_node=new_node;
}
}
void display(){
struct node* temp=start;
while(temp!=NULL){
cout<<temp->data<<" ";
temp=temp->next;
}
}
void reverse_linked_list(){
struct node *prev=NULL, *current=start, *next=NULL;
while(current!=NULL){
next=current->next;
current->next=prev;
prev=current;
current=next;
}
start=prev;
cout<<"\n";
display();
}
int main(){
create(2);
create(27);
create(22);
create(21);
create(25);
display();
reverse_linked_list();
}
| 485 |
338 | <reponame>zhe525069676/WeiBoLayout
package com.zheblog.weibogridview;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
import com.zheblog.weibogridview.adapter.TestAdapter;
import com.zheblog.weibogridview.model.FeedModel;
import com.zheblog.weibogridview.model.FeedPhotoModel;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
private ListView lvTest;
private TestAdapter mAdapter;
private List<FeedModel> mDatas = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initData();
}
private void initView() {
lvTest = (ListView) findViewById(R.id.lv_test);
}
private void initData() {
for (int i = 0; i < 10; i++) {
List<FeedPhotoModel> list = new ArrayList<>();
FeedModel feedModel = new FeedModel();
for (int j = 0; j < i; j++) {
list.add(new FeedPhotoModel(R.mipmap.icon_head));
}
feedModel.setContent("#秋天来了#夏天就这么静悄悄的走了~~@哲匠"+i+"\u200B,加油!!!www.zheblog.com");
feedModel.setPhotoModels(list);
mDatas.add(feedModel);
}
mAdapter = new TestAdapter(this, mDatas);
lvTest.setAdapter(mAdapter);
}
}
| 651 |
818 | /*
* Copyright 2020 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.kogito.svg;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
public abstract class ProcessSvgServiceTest {
private final static String PROCESS_ID = "travels";
public static String readFileContent(String file) throws URISyntaxException, IOException {
Path path = Paths.get(Thread.currentThread().getContextClassLoader().getResource(file).toURI());
return new String(Files.readAllBytes(path));
}
@Test
public void getProcessSvgWithoutSvgResourcePathTest() throws Exception {
String fileContent = getTravelsSVGFile();
Optional<String> svgContent = getTestedProcessSvgService().getProcessSvg(PROCESS_ID);
assertThat(svgContent).isPresent().hasValue(fileContent);
}
@Test
public void getProcessSvgFromFileSystemSuccessTest() throws Exception {
String fileContent = getTravelsSVGFile();
getTestedProcessSvgService().setSvgResourcesPath(Optional.of("./src/test/resources/META-INF/processSVG/"));
Optional<String> svgContent = getTestedProcessSvgService().getProcessSvg(PROCESS_ID);
assertThat(svgContent).isPresent().hasValue(fileContent);
}
@Test
public void getProcessSvgFromFileSystemFailTest() throws Exception {
getTestedProcessSvgService().setSvgResourcesPath(Optional.of("./src/test/resources/META-INF/processSVG/"));
assertThat(getTestedProcessSvgService().getProcessSvg("UnexistingProcessId")).isEmpty();
}
@Test
public void annotateExecutedPathTest() throws Exception {
assertThat(getTestedProcessSvgService().annotateExecutedPath(
getTravelsSVGFile(),
Arrays.asList("_1A708F87-11C0-42A0-A464-0B7E259C426F"),
Collections.emptyList())).hasValue(readFileContent("travels-expected.svg"));
assertThat(getTestedProcessSvgService().annotateExecutedPath(
null,
Arrays.asList("_1A708F87-11C0-42A0-A464-0B7E259C426F"),
Collections.emptyList())).isEmpty();
assertThat(getTestedProcessSvgService().annotateExecutedPath(
getTravelsSVGFile(),
Collections.emptyList(),
Collections.emptyList())).hasValue(getTravelsSVGFile());
}
@Test
public void readFileFromClassPathTest() throws Exception {
assertThat(getTestedProcessSvgService().readFileContentFromClassPath("undefined")).isEmpty();
assertThat(getTravelsSVGFile()).isEqualTo(getTestedProcessSvgService().readFileContentFromClassPath("travels.svg").get());
}
@Test
public void testWrongSVGContentThrowsException() {
AbstractProcessSvgService testedProcessSvgService = getTestedProcessSvgService();
List completedNodes = Arrays.asList("_1A708F87-11C0-42A0-A464-0B7E259C426F");
List activeNodes = Collections.emptyList();
try {
testedProcessSvgService.annotateExecutedPath("wrongSVGContent", completedNodes, activeNodes);
fail("Expected an ProcessSVGException to be thrown");
} catch (ProcessSVGException e) {
assertThat(e.getMessage()).isEqualTo("Failed to annotated SVG for process instance");
}
}
public String getTravelsSVGFile() throws Exception {
return readFileContent("META-INF/processSVG/travels.svg");
}
protected abstract AbstractProcessSvgService getTestedProcessSvgService();
}
| 1,615 |
735 | /**
* MVEL 2.0
* Copyright (C) 2007 The Codehaus
* <NAME>, <NAME>, <NAME>, <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mvel2.ast;
import org.mvel2.CompileException;
import org.mvel2.MVEL;
import org.mvel2.ParserContext;
import org.mvel2.integration.VariableResolverFactory;
import org.mvel2.integration.impl.ImmutableDefaultFactory;
import org.mvel2.integration.impl.StackResetResolverFactory;
import org.mvel2.util.ParseTools;
import static org.mvel2.util.ParseTools.findClassImportResolverFactory;
/**
* @author <NAME>
*/
public class ImportNode extends ASTNode {
private Class importClass;
private boolean packageImport;
private int _offset;
private static final char[] WC_TEST = new char[]{'.', '*'};
public ImportNode(char[] expr, int start, int offset, ParserContext pCtx) {
super(pCtx);
this.expr = expr;
this.start = start;
this.offset = offset;
this.pCtx = pCtx;
if (ParseTools.endsWith(expr, start, offset, WC_TEST)) {
packageImport = true;
_offset = (short) ParseTools.findLast(expr, start, offset, '.');
if (_offset == -1) {
_offset = 0;
}
}
else {
String clsName = new String(expr, start, offset);
ClassLoader classLoader = getClassLoader();
try {
this.importClass = Class.forName(clsName, true, classLoader );
}
catch (ClassNotFoundException e) {
int idx;
clsName = (clsName.substring(0, idx = clsName.lastIndexOf('.')) + "$" + clsName.substring(idx + 1)).trim();
try {
this.importClass = Class.forName(clsName, true, classLoader );
}
catch (ClassNotFoundException e2) {
throw new CompileException("class not found: " + new String(expr), expr, start);
}
}
}
}
public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) {
if (!packageImport) {
if (MVEL.COMPILER_OPT_ALLOCATE_TYPE_LITERALS_TO_SHARED_SYMBOL_TABLE) {
factory.createVariable(importClass.getSimpleName(), importClass);
return importClass;
}
return findClassImportResolverFactory(factory, pCtx).addClass(importClass);
}
// if the factory is an ImmutableDefaultFactory it means this import is unused so we can skip it safely
if (!(factory instanceof ImmutableDefaultFactory)
&& !(factory instanceof StackResetResolverFactory
&& ((StackResetResolverFactory) factory).getDelegate() instanceof ImmutableDefaultFactory)) {
findClassImportResolverFactory(factory, pCtx).addPackageImport(new String(expr, start, _offset - start));
}
return null;
}
public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) {
return getReducedValueAccelerated(ctx, thisValue, factory);
}
public Class getImportClass() {
return importClass;
}
public boolean isPackageImport() {
return packageImport;
}
public void setPackageImport(boolean packageImport) {
this.packageImport = packageImport;
}
public String getPackageImport() {
return new String(expr, start, _offset - start);
}
}
| 1,301 |
5,169 | {
"name": "IBCustomFonts",
"version": "0.0.1",
"summary": "Replace fonts in nibs.",
"description": "\t\t\t\t IBCustomFonts category allows you to use custom fonts from Interface Builder (IB) when building your iOS apps.\n\n\t\t\t\t Apps using IBCustomFonts category are approved by Apple App Store (as of September 2013).\n\n\t\t\t\t No need to use IBOutlets, subclassing of UILabels and UIButtons or change fonts in code.\n\n\t\t\t\t Tested on iOS6 and iOS7.\n",
"homepage": "https://github.com/deni2s/IBCustomFonts",
"license": "MIT",
"authors": {
"<NAME>": "<EMAIL>"
},
"platforms": {
"ios": "6.0"
},
"source": {
"git": "https://github.com/deni2s/IBCustomFonts.git",
"commit": "<PASSWORD>"
},
"source_files": "UIFont+IBCustomFonts.m",
"requires_arc": false
}
| 330 |
1,104 | /*
* 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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
* LegendPanel.java
* Copyright (C) 2000 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.visualize;
import weka.core.FastVector;
import weka.core.Instances;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JColorChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
/**
* This panel displays legends for a list of plots. If a given plot
* has a custom colour defined then this panel allows the colour to
* be changed.
*
* @author <NAME> (<EMAIL>)
* @version $Revision: 4752 $
*/
public class LegendPanel
extends JScrollPane {
/** for serialization */
private static final long serialVersionUID = -1262384440543001505L;
/** the list of plot elements */
protected FastVector m_plots;
/** the panel that contains the legend entries */
protected JPanel m_span=null;
/** a list of components that need to be repainted when a colour is
changed */
protected FastVector m_Repainters = new FastVector();
/**
* Inner class for handling legend entries
*/
protected class LegendEntry
extends JPanel {
/** for serialization */
private static final long serialVersionUID = 3879990289042935670L;
/** the data for this legend entry */
private PlotData2D m_plotData=null;
/** the index (in the list of plots) of the data for this legend---
used to draw the correct shape for this data */
private int m_dataIndex;
/** the text part of this legend */
private JLabel m_legendText;
/** displays the point shape associated with this legend entry */
private JPanel m_pointShape;
public LegendEntry(PlotData2D data, int dataIndex) {
javax.swing.ToolTipManager.sharedInstance().setDismissDelay(5000);
m_plotData = data;
m_dataIndex = dataIndex;
// this.setBackground(Color.black);
/* this.setPreferredSize(new Dimension(0, 20));
this.setMinimumSize(new Dimension(0, 20)); */
if (m_plotData.m_useCustomColour) {
this.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if ((e.getModifiers() & e.BUTTON1_MASK) == e.BUTTON1_MASK) {
Color tmp = JColorChooser.showDialog
(LegendPanel.this, "Select new Color",
m_plotData.m_customColour);
if (tmp != null) {
m_plotData.m_customColour = tmp;
m_legendText.setForeground(tmp);
if (m_Repainters.size() > 0) {
for (int i=0;i<m_Repainters.size();i++) {
((Component)(m_Repainters.elementAt(i))).repaint();
}
}
LegendPanel.this.repaint();
}
}
}
});
}
m_legendText = new JLabel(m_plotData.m_plotName);
m_legendText.setToolTipText(m_plotData.getPlotNameHTML());
if (m_plotData.m_useCustomColour) {
m_legendText.setForeground(m_plotData.m_customColour);
}
this.setLayout(new BorderLayout());
this.add(m_legendText, BorderLayout.CENTER);
/* GridBagLayout gb = new GridBagLayout();
GridBagConstraints constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridx=0;constraints.gridy=0;constraints.weightx=5; */
m_pointShape = new JPanel() {
private static final long serialVersionUID = -7048435221580488238L;
public void paintComponent(Graphics gx) {
super.paintComponent(gx);
if (!m_plotData.m_useCustomColour) {
gx.setColor(Color.black);
} else {
gx.setColor(m_plotData.m_customColour);
}
Plot2D.drawDataPoint(10,10,3,m_dataIndex,gx);
}
};
// m_pointShape.setBackground(Color.black);
m_pointShape.setPreferredSize(new Dimension(20, 20));
m_pointShape.setMinimumSize(new Dimension(20, 20));
this.add(m_pointShape, BorderLayout.WEST);
}
}
/**
* Constructor
*/
public LegendPanel() {
this.setBackground(Color.blue);
setVerticalScrollBarPolicy(VERTICAL_SCROLLBAR_ALWAYS);
}
/**
* Set the list of plots to generate legend entries for
* @param pl a list of plots
*/
public void setPlotList(FastVector pl) {
m_plots = pl;
updateLegends();
}
/**
* Adds a component that will need to be repainted if the user
* changes the colour of a label.
* @param c the component to be repainted
*/
public void addRepaintNotify(Component c) {
m_Repainters.addElement(c);
}
/**
* Redraw the panel with the legend entries
*/
private void updateLegends() {
if (m_span == null) {
m_span = new JPanel();
}
JPanel padder = new JPanel();
JPanel padd2 = new JPanel();
m_span.setPreferredSize(new Dimension(m_span.getPreferredSize().width,
(m_plots.size() + 1) * 20));
m_span.setMaximumSize(new Dimension(m_span.getPreferredSize().width,
(m_plots.size() + 1) * 20));
LegendEntry tmp;
GridBagLayout gb = new GridBagLayout();
GridBagLayout gb2 = new GridBagLayout();
GridBagConstraints constraints = new GridBagConstraints();
m_span.removeAll();
padder.setLayout(gb);
m_span.setLayout(gb2);
constraints.anchor = GridBagConstraints.CENTER;
constraints.gridx=0;constraints.gridy=0;constraints.weightx=5;
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridwidth=1;constraints.gridheight=1;
constraints.insets = new Insets(0, 0, 0, 0);
padder.add(m_span, constraints);
constraints.gridx=0;constraints.gridy=1;constraints.weightx=5;
constraints.fill = GridBagConstraints.BOTH;
constraints.gridwidth=1;constraints.gridheight=1;constraints.weighty=5;
constraints.insets = new Insets(0, 0, 0, 0);
padder.add(padd2, constraints);
constraints.weighty=0;
setViewportView(padder);
constraints.anchor = GridBagConstraints.CENTER;
constraints.gridx=0;constraints.gridy=0;constraints.weightx=5;
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridwidth=1;constraints.gridheight=1;constraints.weighty=5;
constraints.insets = new Insets(2,4,2,4);
//int numLines = ((PlotData2D)m_plots.elementAt(0)).getPlotName().split("<br>").length;
for (int i=0;i<m_plots.size();i++) {
tmp = new LegendEntry((PlotData2D)m_plots.elementAt(i),i);
constraints.gridy = i;
/* constraints.gridheight = 1;
if (numLines > 0) {
constraints.gridheight = (numLines + 2);
} */
m_span.add(tmp, constraints);
}
}
/**
* Main method for testing this class
* @param args a list of arff files
*/
public static void main(String [] args) {
try {
if (args.length < 1) {
System.err.println("Usage : weka.gui.visualize.LegendPanel "
+"<dataset> [dataset2], [dataset3],...");
System.exit(1);
}
final javax.swing.JFrame jf =
new javax.swing.JFrame("Weka Explorer: Legend");
jf.setSize(100,100);
jf.getContentPane().setLayout(new BorderLayout());
final LegendPanel p2 = new LegendPanel();
jf.getContentPane().add(p2, BorderLayout.CENTER);
jf.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent e) {
jf.dispose();
System.exit(0);
}
});
FastVector plotList = new FastVector();
for (int j=0;j<args.length;j++) {
System.err.println("Loading instances from " + args[j]);
java.io.Reader r = new java.io.BufferedReader(
new java.io.FileReader(args[j]));
Instances i = new Instances(r);
PlotData2D tmp = new PlotData2D(i);
if (j != 1) {
tmp.m_useCustomColour = true;
tmp.m_customColour = Color.red;
}
tmp.setPlotName(i.relationName());
plotList.addElement(tmp);
}
p2.setPlotList(plotList);
jf.setVisible(true);
} catch (Exception ex) {
System.err.println(ex.getMessage());
ex.printStackTrace();
}
}
}
| 3,426 |
320 | <reponame>2757571500/sdk<filename>jme3-materialeditor/src/com/jme3/gde/materialdefinition/MatDefMetaData.java
/*
* Copyright (c) 2009-2010 jMonkeyEngine
* 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 'jMonkeyEngine' 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.
*/
package com.jme3.gde.materialdefinition;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.BufferedOutputStream;
import java.io.BufferedInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.netbeans.api.project.Project;
import org.openide.filesystems.FileLock;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.loaders.DataFolder;
import org.openide.util.Exceptions;
import org.openide.util.Mutex;
import org.openide.util.Mutex.Action;
/**
* Global object to access actual jME3 data within an AssetDataObject, available
* through the Lookup of any AssetDataObject. AssetDataObjects that wish to use
*
* @author normenhansen
*/
@SuppressWarnings("unchecked")
public class MatDefMetaData {
private static final Logger logger = Logger.getLogger(MatDefMetaData.class.getName());
private final List<PropertyChangeListener> listeners = new ArrayList<PropertyChangeListener>();
private final Mutex propsMutex = new Mutex();
private final Properties props = new Properties();
private static final Properties defaultProps = new Properties();
static {
defaultProps.put("Default/position", "0,120");
defaultProps.put("Default/MatParam.Color", "438,351");
defaultProps.put("Default/Default/ColorMult", "605,372");
defaultProps.put("Default/WorldParam.WorldViewProjectionMatrix", "33,241");
defaultProps.put("Default/color", "0,478");
defaultProps.put("Default/Default/CommonVert", "211,212");
}
private MatDefDataObject file;
private String extension = "jmpdata";
private Date lastLoaded;
private FileObject folder;
private FileObject root;
// private XMLFileSystem fs;
public MatDefMetaData(MatDefDataObject file) {
try {
this.file = file;
getFolder();
FileObject primaryFile = file.getPrimaryFile();
if (primaryFile != null) {
extension = primaryFile.getExt() + "data";
}
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
}
public MatDefMetaData(MatDefDataObject file, String extension) {
this.file = file;
this.extension = extension;
}
public synchronized String getProperty(final String key) {
readProperties();
return propsMutex.readAccess(new Action<String>() {
public String run() {
String prop = props.getProperty(key);
if (prop == null) {
return defaultProps.getProperty(key);
}
return prop;
}
});
}
public synchronized String getProperty(final String key, final String defaultValue) {
readProperties();
return propsMutex.readAccess(new Action<String>() {
public String run() {
String prop = props.getProperty(key);
if (prop == null) {
return defaultProps.getProperty(key);
}
return prop;
}
});
}
public synchronized String setProperty(final String key, final String value) {
readProperties();
String ret = propsMutex.writeAccess(new Action<String>() {
public String run() {
String ret = (String) props.setProperty(key, value);
return ret;
}
});
// writeProperties();
notifyListeners(key, ret, value);
return ret;
}
private void readProperties() {
propsMutex.writeAccess(new Runnable() {
public void run() {
try {
FileObject pFile = file.getPrimaryFile();
FileObject storageFolder = getFolder();
if (storageFolder == null) {
return;
}
final FileObject myFile = storageFolder.getFileObject(getFileFullName(pFile)); //fs.findResource(fs.getRoot().getPath()+"/"+ file.getPrimaryFile().getName() + "." + extension);//
if (myFile == null) {
return;
}
final Date lastMod = myFile.lastModified();
if (!lastMod.equals(lastLoaded)) {
props.clear();
lastLoaded = lastMod;
InputStream in = null;
try {
in = new BufferedInputStream(myFile.getInputStream());
try {
props.load(in);
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
} catch (FileNotFoundException ex) {
Exceptions.printStackTrace(ex);
} finally {
try {
in.close();
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
}
logger.log(Level.FINE, "Read AssetData properties for {0}", file);
}
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
}
});
}
public void cleanup() {
propsMutex.writeAccess(new Runnable() {
public void run() {
OutputStream out = null;
FileLock lock = null;
try {
FileObject pFile = file.getPrimaryFile();
FileObject storageFolder = getFolder();
if (storageFolder == null) {
return;
}
FileObject myFile = storageFolder.getFileObject(getFileFullName(pFile));//FileUtil.findBrother(pFile, extension);//fs.findResource(fs.getRoot().getPath()+"/"+ pFile.getName() + "." + extension);//
if (myFile == null) {
return;
}
lock = myFile.lock();
myFile.delete(lock);
} catch (IOException e) {
Exceptions.printStackTrace(e);
} finally {
if (out != null) {
try {
out.close();
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
}
if (lock != null) {
lock.releaseLock();
}
}
}
});
}
public void rename(final DataFolder df, final String name) {
propsMutex.writeAccess(new Runnable() {
public void run() {
OutputStream out = null;
FileLock lock = null;
try {
FileObject pFile = file.getPrimaryFile();
FileObject storageFolder = getFolder();
if (storageFolder == null) {
return;
}
FileObject myFile = storageFolder.getFileObject(getFileFullName(pFile));//FileUtil.findBrother(pFile, extension);//fs.findResource(fs.getRoot().getPath()+"/"+ pFile.getName() + "." + extension);//
if (myFile == null) {
return;
}
lock = myFile.lock();
if (df == null) {
myFile.rename(lock, getFileFullName(pFile).replaceAll(file.getName() + "." + extension, name + "." + extension), "");
} else {
myFile.rename(lock, FileUtil.getRelativePath(root, df.getPrimaryFile()).replaceAll("/", ".") + "." + pFile.getName(), extension);
}
} catch (IOException e) {
Exceptions.printStackTrace(e);
} finally {
if (out != null) {
try {
out.close();
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
}
if (lock != null) {
lock.releaseLock();
}
}
}
});
}
public void duplicate(final DataFolder df, final String name) {
propsMutex.writeAccess(new Runnable() {
public void run() {
OutputStream out = null;
FileLock lock = null;
try {
FileObject pFile = file.getPrimaryFile();
FileObject storageFolder = getFolder();
if (storageFolder == null) {
return;
}
String newName = name;
if (newName == null) {
newName = file.getName();
}
String path = FileUtil.getRelativePath(root, df.getPrimaryFile()).replaceAll("/", ".") + "." + newName;
FileObject myFile = storageFolder.getFileObject(getFileFullName(pFile));
if (myFile == null) {
return;
}
myFile.copy(storageFolder, path, extension);
} catch (IOException e) {
Exceptions.printStackTrace(e);
} finally {
if (out != null) {
try {
out.close();
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
}
if (lock != null) {
lock.releaseLock();
}
}
}
});
}
public void save() {
if (!props.isEmpty()) {
writeProperties();
}
}
private void writeProperties() {
//writeAccess because we write lastMod date, not because we write to the file
//the mutex protects the properties object, not the file
propsMutex.writeAccess(new Runnable() {
public void run() {
OutputStream out = null;
FileLock lock = null;
try {
FileObject pFile = file.getPrimaryFile();
FileObject storageFolder = getFolder();
if (storageFolder == null) {
return;
}
FileObject myFile = storageFolder.getFileObject(getFileFullName(pFile));//FileUtil.findBrother(pFile, extension);//fs.findResource(fs.getRoot().getPath()+"/"+ pFile.getName() + "." + extension);//
if (myFile == null) {
myFile = FileUtil.createData(storageFolder, getFileFullName(pFile));
}
lock = myFile.lock();
out = new BufferedOutputStream(myFile.getOutputStream(lock));
props.store(out, "");
out.flush();
lastLoaded = myFile.lastModified();
logger.log(Level.FINE, "Written AssetData properties for {0}", file);
} catch (IOException e) {
Exceptions.printStackTrace(e);
} finally {
if (out != null) {
try {
out.close();
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
}
if (lock != null) {
lock.releaseLock();
}
}
}
});
}
private String getFileFullName(FileObject pFile) {
return FileUtil.getRelativePath(root, pFile).replaceAll("/", ".").replaceAll("j3md", extension);
}
protected void notifyListeners(String property, String before, String after) {
synchronized (listeners) {
for (Iterator<PropertyChangeListener> it = listeners.iterator(); it.hasNext();) {
PropertyChangeListener propertyChangeListener = it.next();
propertyChangeListener.propertyChange(new PropertyChangeEvent(this, property, before, after));
}
}
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
synchronized (listeners) {
listeners.add(listener);
}
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
synchronized (listeners) {
listeners.remove(listener);
}
}
private FileObject getFolder() throws IOException {
if (folder == null) {
Project p = file.getLookup().lookup(Project.class);
if (p != null) {
root = p.getProjectDirectory();
FileObject jmedataFolder = root.getFileObject("/nbproject/jme3Data");
if (jmedataFolder == null) {
jmedataFolder = root.getFileObject("/nbproject");
if(jmedataFolder!=null){
jmedataFolder = jmedataFolder.createFolder("jme3Data");
}
}
return jmedataFolder;
}
}
return folder;
}
}
| 7,910 |
5,169 | {
"name": "testsh",
"version": "0.0.1",
"summary": "testsh.",
"description": "this is testsh",
"homepage": "https://github.com/ajiao-github/testsh",
"license": {
"type": "MIT",
"file": "FILE_LICENSE"
},
"authors": "ajiao-github",
"platforms": {
"ios": "8.0"
},
"source": {
"git": "https://github.com/ajiao-github/testsh.git",
"tag": "0.0.1"
},
"source_files": "testsh/Lib/**/*"
}
| 194 |
3,012 | /** @file
Header file for boot maintenance module.
Copyright (c) 2004 - 2019, Intel Corporation. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#ifndef _BOOT_MAINT_H_
#define _BOOT_MAINT_H_
#include "FormGuid.h"
#include <Guid/TtyTerm.h>
#include <Guid/MdeModuleHii.h>
#include <Guid/FileSystemVolumeLabelInfo.h>
#include <Guid/GlobalVariable.h>
#include <Guid/HiiBootMaintenanceFormset.h>
#include <Protocol/LoadFile.h>
#include <Protocol/HiiConfigAccess.h>
#include <Protocol/SimpleFileSystem.h>
#include <Protocol/SerialIo.h>
#include <Protocol/DevicePathToText.h>
#include <Protocol/FormBrowserEx2.h>
#include <Library/PrintLib.h>
#include <Library/DebugLib.h>
#include <Library/BaseMemoryLib.h>
#include <Library/UefiBootServicesTableLib.h>
#include <Library/UefiLib.h>
#include <Library/MemoryAllocationLib.h>
#include <Library/UefiRuntimeServicesTableLib.h>
#include <Library/DevicePathLib.h>
#include <Library/HiiLib.h>
#include <Library/UefiHiiServicesLib.h>
#include <Library/UefiBootManagerLib.h>
#include <Library/FileExplorerLib.h>
#include "BootMaintenanceManagerCustomizedUi.h"
#pragma pack(1)
///
/// HII specific Vendor Device Path definition.
///
typedef struct {
VENDOR_DEVICE_PATH VendorDevicePath;
EFI_DEVICE_PATH_PROTOCOL End;
} HII_VENDOR_DEVICE_PATH;
#pragma pack()
//
// Constants which are variable names used to access variables
//
#define VAR_CON_OUT_MODE L"ConOutMode"
//
// Variable created with this flag will be "Efi:...."
//
#define VAR_FLAG EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE
extern EFI_GUID mBootMaintGuid;
extern CHAR16 mBootMaintStorageName[];
//
// These are the VFR compiler generated data representing our VFR data.
//
extern UINT8 BootMaintenanceManagerBin[];
//
// Below are the number of options in Baudrate, Databits,
// Parity and Stopbits selection for serial ports.
//
#define BM_COM_ATTR_BUADRATE 19
#define BM_COM_ATTR_DATABITS 4
#define BM_COM_ATTR_PARITY 5
#define BM_COM_ATTR_STOPBITS 3
//
// Callback function helper
//
#define BMM_CALLBACK_DATA_SIGNATURE SIGNATURE_32 ('C', 'b', 'c', 'k')
#define BMM_CALLBACK_DATA_FROM_THIS(a) CR (a, BMM_CALLBACK_DATA, BmmConfigAccess, BMM_CALLBACK_DATA_SIGNATURE)
//
// Enumeration type definition
//
typedef UINT8 BBS_TYPE;
typedef enum _TYPE_OF_TERMINAL {
TerminalTypePcAnsi = 0,
TerminalTypeVt100,
TerminalTypeVt100Plus,
TerminalTypeVtUtf8,
TerminalTypeTtyTerm,
TerminalTypeLinux,
TerminalTypeXtermR6,
TerminalTypeVt400,
TerminalTypeSCO
} TYPE_OF_TERMINAL;
//
// All of the signatures that will be used in list structure
//
#define BM_MENU_OPTION_SIGNATURE SIGNATURE_32 ('m', 'e', 'n', 'u')
#define BM_LOAD_OPTION_SIGNATURE SIGNATURE_32 ('l', 'o', 'a', 'd')
#define BM_CONSOLE_OPTION_SIGNATURE SIGNATURE_32 ('c', 'n', 's', 'l')
#define BM_FILE_OPTION_SIGNATURE SIGNATURE_32 ('f', 'i', 'l', 'e')
#define BM_HANDLE_OPTION_SIGNATURE SIGNATURE_32 ('h', 'n', 'd', 'l')
#define BM_TERMINAL_OPTION_SIGNATURE SIGNATURE_32 ('t', 'r', 'm', 'l')
#define BM_MENU_ENTRY_SIGNATURE SIGNATURE_32 ('e', 'n', 't', 'r')
#define BM_LOAD_CONTEXT_SELECT 0x0
#define BM_CONSOLE_CONTEXT_SELECT 0x1
#define BM_FILE_CONTEXT_SELECT 0x2
#define BM_HANDLE_CONTEXT_SELECT 0x3
#define BM_TERMINAL_CONTEXT_SELECT 0x5
#define BM_CONSOLE_IN_CONTEXT_SELECT 0x6
#define BM_CONSOLE_OUT_CONTEXT_SELECT 0x7
#define BM_CONSOLE_ERR_CONTEXT_SELECT 0x8
//
// Buffer size for update data
//
#define UPDATE_DATA_SIZE 0x100000
//
// Namespace of callback keys used in display and file system navigation
//
#define MAX_BBS_OFFSET 0xE000
#define NET_OPTION_OFFSET 0xD800
#define BEV_OPTION_OFFSET 0xD000
#define FD_OPTION_OFFSET 0xC000
#define HD_OPTION_OFFSET 0xB000
#define CD_OPTION_OFFSET 0xA000
#define FILE_OPTION_OFFSET 0x8000
#define FILE_OPTION_MASK 0x7FFF
#define HANDLE_OPTION_OFFSET 0x7000
#define CONSOLE_OPTION_OFFSET 0x6000
#define TERMINAL_OPTION_OFFSET 0x5000
#define CONFIG_OPTION_OFFSET 0x1200
#define KEY_VALUE_OFFSET 0x1100
#define FORM_ID_OFFSET 0x1000
//
// VarOffset that will be used to create question
// all these values are computed from the structure
// defined below
//
#define VAR_OFFSET(Field) ((UINT16) ((UINTN) &(((BMM_FAKE_NV_DATA *) 0)->Field)))
//
// Question Id of Zero is invalid, so add an offset to it
//
#define QUESTION_ID(Field) (VAR_OFFSET (Field) + CONFIG_OPTION_OFFSET)
#define BOOT_TIME_OUT_VAR_OFFSET VAR_OFFSET (BootTimeOut)
#define BOOT_NEXT_VAR_OFFSET VAR_OFFSET (BootNext)
#define COM1_BAUD_RATE_VAR_OFFSET VAR_OFFSET (COM1BaudRate)
#define COM1_DATA_RATE_VAR_OFFSET VAR_OFFSET (COM1DataRate)
#define COM1_STOP_BITS_VAR_OFFSET VAR_OFFSET (COM1StopBits)
#define COM1_PARITY_VAR_OFFSET VAR_OFFSET (COM1Parity)
#define COM1_TERMINAL_VAR_OFFSET VAR_OFFSET (COM2TerminalType)
#define COM2_BAUD_RATE_VAR_OFFSET VAR_OFFSET (COM2BaudRate)
#define COM2_DATA_RATE_VAR_OFFSET VAR_OFFSET (COM2DataRate)
#define COM2_STOP_BITS_VAR_OFFSET VAR_OFFSET (COM2StopBits)
#define COM2_PARITY_VAR_OFFSET VAR_OFFSET (COM2Parity)
#define COM2_TERMINAL_VAR_OFFSET VAR_OFFSET (COM2TerminalType)
#define DRV_ADD_HANDLE_DESC_VAR_OFFSET VAR_OFFSET (DriverAddHandleDesc)
#define DRV_ADD_ACTIVE_VAR_OFFSET VAR_OFFSET (DriverAddActive)
#define DRV_ADD_RECON_VAR_OFFSET VAR_OFFSET (DriverAddForceReconnect)
#define CON_IN_COM1_VAR_OFFSET VAR_OFFSET (ConsoleInputCOM1)
#define CON_IN_COM2_VAR_OFFSET VAR_OFFSET (ConsoleInputCOM2)
#define CON_OUT_COM1_VAR_OFFSET VAR_OFFSET (ConsoleOutputCOM1)
#define CON_OUT_COM2_VAR_OFFSET VAR_OFFSET (ConsoleOutputCOM2)
#define CON_ERR_COM1_VAR_OFFSET VAR_OFFSET (ConsoleErrorCOM1)
#define CON_ERR_COM2_VAR_OFFSET VAR_OFFSET (ConsoleErrorCOM2)
#define CON_MODE_VAR_OFFSET VAR_OFFSET (ConsoleOutMode)
#define CON_DEVICE_VAR_OFFSET VAR_OFFSET (ConsoleCheck)
#define CON_IN_DEVICE_VAR_OFFSET VAR_OFFSET (ConsoleInCheck)
#define CON_OUT_DEVICE_VAR_OFFSET VAR_OFFSET (ConsoleOutCheck)
#define CON_ERR_DEVICE_VAR_OFFSET VAR_OFFSET (ConsoleErrCheck)
#define BOOT_OPTION_ORDER_VAR_OFFSET VAR_OFFSET (BootOptionOrder)
#define DRIVER_OPTION_ORDER_VAR_OFFSET VAR_OFFSET (DriverOptionOrder)
#define BOOT_OPTION_DEL_VAR_OFFSET VAR_OFFSET (BootOptionDel)
#define DRIVER_OPTION_DEL_VAR_OFFSET VAR_OFFSET (DriverOptionDel)
#define DRIVER_ADD_OPTION_VAR_OFFSET VAR_OFFSET (DriverAddHandleOptionalData)
#define COM_BAUD_RATE_VAR_OFFSET VAR_OFFSET (COMBaudRate)
#define COM_DATA_RATE_VAR_OFFSET VAR_OFFSET (COMDataRate)
#define COM_STOP_BITS_VAR_OFFSET VAR_OFFSET (COMStopBits)
#define COM_PARITY_VAR_OFFSET VAR_OFFSET (COMParity)
#define COM_TERMINAL_VAR_OFFSET VAR_OFFSET (COMTerminalType)
#define COM_FLOWCONTROL_VAR_OFFSET VAR_OFFSET (COMFlowControl)
#define BOOT_TIME_OUT_QUESTION_ID QUESTION_ID (BootTimeOut)
#define BOOT_NEXT_QUESTION_ID QUESTION_ID (BootNext)
#define COM1_BAUD_RATE_QUESTION_ID QUESTION_ID (COM1BaudRate)
#define COM1_DATA_RATE_QUESTION_ID QUESTION_ID (COM1DataRate)
#define COM1_STOP_BITS_QUESTION_ID QUESTION_ID (COM1StopBits)
#define COM1_PARITY_QUESTION_ID QUESTION_ID (COM1Parity)
#define COM1_TERMINAL_QUESTION_ID QUESTION_ID (COM2TerminalType)
#define COM2_BAUD_RATE_QUESTION_ID QUESTION_ID (COM2BaudRate)
#define COM2_DATA_RATE_QUESTION_ID QUESTION_ID (COM2DataRate)
#define COM2_STOP_BITS_QUESTION_ID QUESTION_ID (COM2StopBits)
#define COM2_PARITY_QUESTION_ID QUESTION_ID (COM2Parity)
#define COM2_TERMINAL_QUESTION_ID QUESTION_ID (COM2TerminalType)
#define DRV_ADD_HANDLE_DESC_QUESTION_ID QUESTION_ID (DriverAddHandleDesc)
#define DRV_ADD_ACTIVE_QUESTION_ID QUESTION_ID (DriverAddActive)
#define DRV_ADD_RECON_QUESTION_ID QUESTION_ID (DriverAddForceReconnect)
#define CON_IN_COM1_QUESTION_ID QUESTION_ID (ConsoleInputCOM1)
#define CON_IN_COM2_QUESTION_ID QUESTION_ID (ConsoleInputCOM2)
#define CON_OUT_COM1_QUESTION_ID QUESTION_ID (ConsoleOutputCOM1)
#define CON_OUT_COM2_QUESTION_ID QUESTION_ID (ConsoleOutputCOM2)
#define CON_ERR_COM1_QUESTION_ID QUESTION_ID (ConsoleErrorCOM1)
#define CON_ERR_COM2_QUESTION_ID QUESTION_ID (ConsoleErrorCOM2)
#define CON_MODE_QUESTION_ID QUESTION_ID (ConsoleOutMode)
#define CON_DEVICE_QUESTION_ID QUESTION_ID (ConsoleCheck)
#define CON_IN_DEVICE_QUESTION_ID QUESTION_ID (ConsoleInCheck)
#define CON_OUT_DEVICE_QUESTION_ID QUESTION_ID (ConsoleOutCheck)
#define CON_ERR_DEVICE_QUESTION_ID QUESTION_ID (ConsoleErrCheck)
#define BOOT_OPTION_ORDER_QUESTION_ID QUESTION_ID (BootOptionOrder)
#define DRIVER_OPTION_ORDER_QUESTION_ID QUESTION_ID (DriverOptionOrder)
#define BOOT_OPTION_DEL_QUESTION_ID QUESTION_ID (BootOptionDel)
#define DRIVER_OPTION_DEL_QUESTION_ID QUESTION_ID (DriverOptionDel)
#define DRIVER_ADD_OPTION_QUESTION_ID QUESTION_ID (DriverAddHandleOptionalData)
#define COM_BAUD_RATE_QUESTION_ID QUESTION_ID (COMBaudRate)
#define COM_DATA_RATE_QUESTION_ID QUESTION_ID (COMDataRate)
#define COM_STOP_BITS_QUESTION_ID QUESTION_ID (COMStopBits)
#define COM_PARITY_QUESTION_ID QUESTION_ID (COMParity)
#define COM_TERMINAL_QUESTION_ID QUESTION_ID (COMTerminalType)
#define COM_FLOWCONTROL_QUESTION_ID QUESTION_ID (COMFlowControl)
#define STRING_DEPOSITORY_NUMBER 8
#define NONE_BOOTNEXT_VALUE (0xFFFF + 1)
///
/// Serial Ports attributes, first one is the value for
/// return from callback function, stringtoken is used to
/// display the value properly
///
typedef struct {
UINTN Value;
UINT16 StringToken;
} COM_ATTR;
typedef struct {
UINT64 BaudRate;
UINT8 DataBits;
UINT8 Parity;
UINT8 StopBits;
UINT8 BaudRateIndex;
UINT8 DataBitsIndex;
UINT8 ParityIndex;
UINT8 StopBitsIndex;
UINT8 FlowControl;
UINT8 IsConIn;
UINT8 IsConOut;
UINT8 IsStdErr;
UINT8 TerminalType;
EFI_DEVICE_PATH_PROTOCOL *DevicePath;
} BM_TERMINAL_CONTEXT;
typedef struct {
BOOLEAN IsBootNext;
BOOLEAN Deleted;
BOOLEAN IsLegacy;
UINT32 Attributes;
UINT16 FilePathListLength;
UINT16 *Description;
EFI_DEVICE_PATH_PROTOCOL *FilePathList;
UINT8 *OptionalData;
} BM_LOAD_CONTEXT;
typedef struct {
BOOLEAN IsActive;
BOOLEAN IsTerminal;
EFI_DEVICE_PATH_PROTOCOL *DevicePath;
} BM_CONSOLE_CONTEXT;
typedef struct {
UINTN Column;
UINTN Row;
} CONSOLE_OUT_MODE;
typedef struct {
EFI_HANDLE Handle;
EFI_DEVICE_PATH_PROTOCOL *DevicePath;
EFI_FILE_HANDLE FHandle;
UINT16 *FileName;
EFI_FILE_SYSTEM_VOLUME_LABEL *Info;
BOOLEAN IsRoot;
BOOLEAN IsDir;
BOOLEAN IsRemovableMedia;
BOOLEAN IsLoadFile;
BOOLEAN IsBootLegacy;
} BM_FILE_CONTEXT;
typedef struct {
EFI_HANDLE Handle;
EFI_DEVICE_PATH_PROTOCOL *DevicePath;
} BM_HANDLE_CONTEXT;
typedef struct {
UINTN Signature;
LIST_ENTRY Head;
UINTN MenuNumber;
} BM_MENU_OPTION;
typedef struct {
UINTN Signature;
LIST_ENTRY Link;
UINTN OptionNumber;
UINT16 *DisplayString;
UINT16 *HelpString;
EFI_STRING_ID DisplayStringToken;
EFI_STRING_ID HelpStringToken;
UINTN ContextSelection;
VOID *VariableContext;
} BM_MENU_ENTRY;
typedef struct {
UINTN Signature;
EFI_HII_HANDLE BmmHiiHandle;
EFI_HANDLE BmmDriverHandle;
///
/// Boot Maintenance Manager Produced protocols
///
EFI_HII_CONFIG_ACCESS_PROTOCOL BmmConfigAccess;
EFI_FORM_BROWSER2_PROTOCOL *FormBrowser2;
BM_MENU_ENTRY *MenuEntry;
BM_HANDLE_CONTEXT *HandleContext;
BM_FILE_CONTEXT *FileContext;
BM_LOAD_CONTEXT *LoadContext;
BM_TERMINAL_CONTEXT *TerminalContext;
UINTN CurrentTerminal;
BBS_TYPE BbsType;
//
// BMM main formset callback data.
//
EFI_FORM_ID BmmCurrentPageId;
EFI_FORM_ID BmmPreviousPageId;
BOOLEAN BmmAskSaveOrNot;
BMM_FAKE_NV_DATA BmmFakeNvData;
BMM_FAKE_NV_DATA BmmOldFakeNVData;
} BMM_CALLBACK_DATA;
/**
Find drivers that will be added as Driver#### variables from handles
in current system environment
All valid handles in the system except those consume SimpleFs, LoadFile
are stored in DriverMenu for future use.
@retval EFI_SUCCESS The function complets successfully.
@return Other value if failed to build the DriverMenu.
**/
EFI_STATUS
BOpt_FindDrivers (
VOID
);
/**
Build the BootOptionMenu according to BootOrder Variable.
This Routine will access the Boot#### to get EFI_LOAD_OPTION.
@param CallbackData The BMM context data.
@return The number of the Var Boot####.
**/
EFI_STATUS
BOpt_GetBootOptions (
IN BMM_CALLBACK_DATA *CallbackData
);
/**
Build up all DriverOptionMenu
@param CallbackData The BMM context data.
@return EFI_SUCESS The functin completes successfully.
@retval EFI_OUT_OF_RESOURCES Not enough memory to compete the operation.
**/
EFI_STATUS
BOpt_GetDriverOptions (
IN BMM_CALLBACK_DATA *CallbackData
);
/**
Free resources allocated in Allocate Rountine.
@param FreeMenu Menu to be freed
**/
VOID
BOpt_FreeMenu (
BM_MENU_OPTION *FreeMenu
);
/**
Get the Option Number that has not been allocated for use.
@param Type The type of Option.
@return The available Option Number.
**/
UINT16
BOpt_GetOptionNumber (
CHAR16 *Type
);
/**
Get the Option Number for Boot#### that does not used.
@return The available Option Number.
**/
UINT16
BOpt_GetBootOptionNumber (
VOID
);
/**
Get the Option Number for Driver#### that does not used.
@return The unused Option Number.
**/
UINT16
BOpt_GetDriverOptionNumber (
VOID
);
/**
Create a menu entry give a Menu type.
@param MenuType The Menu type to be created.
@retval NULL If failed to create the menu.
@return The menu.
**/
BM_MENU_ENTRY *
BOpt_CreateMenuEntry (
UINTN MenuType
);
/**
Free up all resource allocated for a BM_MENU_ENTRY.
@param MenuEntry A pointer to BM_MENU_ENTRY.
**/
VOID
BOpt_DestroyMenuEntry (
BM_MENU_ENTRY *MenuEntry
);
/**
Get the Menu Entry from the list in Menu Entry List.
If MenuNumber is great or equal to the number of Menu
Entry in the list, then ASSERT.
@param MenuOption The Menu Entry List to read the menu entry.
@param MenuNumber The index of Menu Entry.
@return The Menu Entry.
**/
BM_MENU_ENTRY *
BOpt_GetMenuEntry (
BM_MENU_OPTION *MenuOption,
UINTN MenuNumber
);
/**
Get option number according to Boot#### and BootOrder variable.
The value is saved as #### + 1.
@param CallbackData The BMM context data.
**/
VOID
GetBootOrder (
IN BMM_CALLBACK_DATA *CallbackData
);
/**
Get driver option order from globalc DriverOptionMenu.
@param CallbackData The BMM context data.
**/
VOID
GetDriverOrder (
IN BMM_CALLBACK_DATA *CallbackData
);
//
// Locate all serial io devices for console
//
/**
Build a list containing all serial devices.
@retval EFI_SUCCESS The function complete successfully.
@retval EFI_UNSUPPORTED No serial ports present.
**/
EFI_STATUS
LocateSerialIo (
VOID
);
//
// Initializing Console menu
//
/**
Build up ConsoleOutMenu, ConsoleInpMenu and ConsoleErrMenu
@retval EFI_SUCCESS The function always complete successfully.
**/
EFI_STATUS
GetAllConsoles (
VOID
);
//
// Get current mode information
//
/**
Get mode number according to column and row
@param CallbackData The BMM context data.
**/
VOID
GetConsoleOutMode (
IN BMM_CALLBACK_DATA *CallbackData
);
//
// Cleaning up console menu
//
/**
Free ConsoleOutMenu, ConsoleInpMenu and ConsoleErrMenu
@retval EFI_SUCCESS The function always complete successfully.
**/
EFI_STATUS
FreeAllConsoles (
VOID
);
/**
Update the device path that describing a terminal device
based on the new BaudRate, Data Bits, parity and Stop Bits
set.
@param DevicePath The devicepath protocol instance wanted to be updated.
**/
VOID
ChangeVariableDevicePath (
IN OUT EFI_DEVICE_PATH_PROTOCOL *DevicePath
);
/**
Update the multi-instance device path of Terminal Device based on
the global TerminalMenu. If ChangeTernimal is TRUE, the terminal
device path in the Terminal Device in TerminalMenu is also updated.
@param DevicePath The multi-instance device path.
@param ChangeTerminal TRUE, then device path in the Terminal Device
in TerminalMenu is also updated; FALSE, no update.
@return EFI_SUCCESS The function completes successfully.
**/
EFI_STATUS
ChangeTerminalDevicePath (
IN OUT EFI_DEVICE_PATH_PROTOCOL *DevicePath,
IN BOOLEAN ChangeTerminal
);
//
// Variable operation by menu selection
//
/**
This function create a currently loaded Boot Option from
the BMM. It then appends this Boot Option to the end of
the "BootOrder" list. It also append this Boot Opotion to the end
of BootOptionMenu.
@param CallbackData The BMM context data.
@retval EFI_OUT_OF_RESOURCES If not enought memory to complete the operation.
@retval EFI_SUCCESS If function completes successfully.
**/
EFI_STATUS
Var_UpdateBootOption (
IN BMM_CALLBACK_DATA *CallbackData
);
/**
Delete Boot Option that represent a Deleted state in BootOptionMenu.
@retval EFI_SUCCESS If all boot load option EFI Variables corresponding to
BM_LOAD_CONTEXT marked for deletion is deleted
@return Others If failed to update the "BootOrder" variable after deletion.
**/
EFI_STATUS
Var_DelBootOption (
VOID
);
/**
This function create a currently loaded Drive Option from
the BMM. It then appends this Driver Option to the end of
the "DriverOrder" list. It append this Driver Opotion to the end
of DriverOptionMenu.
@param CallbackData The BMM context data.
@param HiiHandle The HII handle associated with the BMM formset.
@param DescriptionData The description of this driver option.
@param OptionalData The optional load option.
@param ForceReconnect If to force reconnect.
@retval EFI_OUT_OF_RESOURCES If not enought memory to complete the operation.
@retval EFI_SUCCESS If function completes successfully.
**/
EFI_STATUS
Var_UpdateDriverOption (
IN BMM_CALLBACK_DATA *CallbackData,
IN EFI_HII_HANDLE HiiHandle,
IN UINT16 *DescriptionData,
IN UINT16 *OptionalData,
IN UINT8 ForceReconnect
);
/**
Delete Load Option that represent a Deleted state in DriverOptionMenu.
@retval EFI_SUCCESS Load Option is successfully updated.
@return Other value than EFI_SUCCESS if failed to update "Driver Order" EFI
Variable.
**/
EFI_STATUS
Var_DelDriverOption (
VOID
);
/**
This function delete and build multi-instance device path ConIn
console device.
@retval EFI_SUCCESS The function complete successfully.
@return The EFI variable can not be saved. See gRT->SetVariable for detail return information.
**/
EFI_STATUS
Var_UpdateConsoleInpOption (
VOID
);
/**
This function delete and build multi-instance device path ConOut console device.
@retval EFI_SUCCESS The function complete successfully.
@return The EFI variable can not be saved. See gRT->SetVariable for detail return information.
**/
EFI_STATUS
Var_UpdateConsoleOutOption (
VOID
);
/**
This function delete and build multi-instance device path ErrOut console device.
@retval EFI_SUCCESS The function complete successfully.
@return The EFI variable can not be saved. See gRT->SetVariable for detail return information.
**/
EFI_STATUS
Var_UpdateErrorOutOption (
VOID
);
/**
This function delete and build Out of Band console device.
@param MenuIndex Menu index which user select in the terminal menu list.
@retval EFI_SUCCESS The function complete successfully.
@return The EFI variable can not be saved. See gRT->SetVariable for detail return information.
**/
EFI_STATUS
Var_UpdateOutOfBandOption (
IN UINT16 MenuIndex
);
/**
This function update the "BootNext" EFI Variable. If there is no "BootNex" specified in BMM,
this EFI Variable is deleted.
It also update the BMM context data specified the "BootNext" value.
@param CallbackData The BMM context data.
@retval EFI_SUCCESS The function complete successfully.
@return The EFI variable can not be saved. See gRT->SetVariable for detail return information.
**/
EFI_STATUS
Var_UpdateBootNext (
IN BMM_CALLBACK_DATA *CallbackData
);
/**
This function update the "BootOrder" EFI Variable based on BMM Formset's NV map. It then refresh
BootOptionMenu with the new "BootOrder" list.
@param CallbackData The BMM context data.
@retval EFI_SUCCESS The function complete successfully.
@retval EFI_OUT_OF_RESOURCES Not enough memory to complete the function.
@return not The EFI variable can not be saved. See gRT->SetVariable for detail return information.
**/
EFI_STATUS
Var_UpdateBootOrder (
IN BMM_CALLBACK_DATA *CallbackData
);
/**
This function update the "DriverOrder" EFI Variable based on
BMM Formset's NV map. It then refresh DriverOptionMenu
with the new "DriverOrder" list.
@param CallbackData The BMM context data.
@retval EFI_SUCCESS The function complete successfully.
@retval EFI_OUT_OF_RESOURCES Not enough memory to complete the function.
@return The EFI variable can not be saved. See gRT->SetVariable for detail return information.
**/
EFI_STATUS
Var_UpdateDriverOrder (
IN BMM_CALLBACK_DATA *CallbackData
);
/**
Update the Text Mode of Console.
@param CallbackData The context data for BMM.
@retval EFI_SUCCSS If the Text Mode of Console is updated.
@return Other value if the Text Mode of Console is not updated.
**/
EFI_STATUS
Var_UpdateConMode (
IN BMM_CALLBACK_DATA *CallbackData
);
//
// Following are page create and refresh functions
//
/**
Create the global UpdateData structure.
**/
VOID
CreateUpdateData (
VOID
);
/**
Refresh the global UpdateData structure.
**/
VOID
RefreshUpdateData (
VOID
);
/**
Clean up the dynamic opcode at label and form specified by
both LabelId.
@param LabelId It is both the Form ID and Label ID for
opcode deletion.
@param CallbackData The BMM context data.
**/
VOID
CleanUpPage (
IN UINT16 LabelId,
IN BMM_CALLBACK_DATA *CallbackData
);
/**
Create a lit of boot option from global BootOptionMenu. It
allow user to delete the boot option.
@param CallbackData The BMM context data.
**/
VOID
UpdateBootDelPage (
IN BMM_CALLBACK_DATA *CallbackData
);
/**
Create a lit of driver option from global DriverMenu.
@param CallbackData The BMM context data.
**/
VOID
UpdateDrvAddHandlePage (
IN BMM_CALLBACK_DATA *CallbackData
);
/**
Create a lit of driver option from global DriverOptionMenu. It
allow user to delete the driver option.
@param CallbackData The BMM context data.
**/
VOID
UpdateDrvDelPage (
IN BMM_CALLBACK_DATA *CallbackData
);
/**
Prepare the page to allow user to add description for a Driver Option.
@param CallbackData The BMM context data.
**/
VOID
UpdateDriverAddHandleDescPage (
IN BMM_CALLBACK_DATA *CallbackData
);
/**
Dispatch the correct update page function to call based on the UpdatePageId.
@param UpdatePageId The form ID.
@param CallbackData The BMM context data.
**/
VOID
UpdatePageBody (
IN UINT16 UpdatePageId,
IN BMM_CALLBACK_DATA *CallbackData
);
/**
Create the dynamic page which allows user to set the property such as Baud Rate, Data Bits,
Parity, Stop Bits, Terminal Type.
@param CallbackData The BMM context data.
**/
VOID
UpdateTerminalPage (
IN BMM_CALLBACK_DATA *CallbackData
);
/**
Refresh the text mode page
@param CallbackData The BMM context data.
**/
VOID
UpdateConModePage (
IN BMM_CALLBACK_DATA *CallbackData
);
/**
Create a list of Goto Opcode for all terminal devices logged
by TerminaMenu. This list will be inserted to form FORM_CON_COM_SETUP_ID.
@param CallbackData The BMM context data.
**/
VOID
UpdateConCOMPage (
IN BMM_CALLBACK_DATA *CallbackData
);
/**
Update add boot/driver option page.
@param CallbackData The BMM context data.
@param FormId The form ID to be updated.
@param DevicePath Device path.
**/
VOID
UpdateOptionPage (
IN BMM_CALLBACK_DATA *CallbackData,
IN EFI_FORM_ID FormId,
IN EFI_DEVICE_PATH_PROTOCOL *DevicePath
);
/**
Function deletes the variable specified by VarName and VarGuid.
@param VarName A Null-terminated Unicode string that is
the name of the vendor's variable.
@param VarGuid A unique identifier for the vendor.
@retval EFI_SUCCESS The variable was found and removed
@retval EFI_UNSUPPORTED The variable store was inaccessible
@retval EFI_OUT_OF_RESOURCES The temporary buffer was not available
@retval EFI_NOT_FOUND The variable was not found
**/
EFI_STATUS
EfiLibDeleteVariable (
IN CHAR16 *VarName,
IN EFI_GUID *VarGuid
);
/**
Function is used to determine the number of device path instances
that exist in a device path.
@param DevicePath A pointer to a device path data structure.
@return This function counts and returns the number of device path instances
in DevicePath.
**/
UINTN
EfiDevicePathInstanceCount (
IN EFI_DEVICE_PATH_PROTOCOL *DevicePath
);
/**
Get a string from the Data Hub record based on
a device path.
@param DevPath The device Path.
@return A string located from the Data Hub records based on
the device path.
@retval NULL If failed to get the String from Data Hub.
**/
UINT16 *
EfiLibStrFromDatahub (
IN EFI_DEVICE_PATH_PROTOCOL *DevPath
);
/**
Get the index number (#### in Boot####) for the boot option pointed to a BBS legacy device type
specified by DeviceType.
@param DeviceType The legacy device type. It can be floppy, network, harddisk, cdrom,
etc.
@param OptionIndex Returns the index number (#### in Boot####).
@param OptionSize Return the size of the Boot### variable.
**/
VOID *
GetLegacyBootOptionVar (
IN UINTN DeviceType,
OUT UINTN *OptionIndex,
OUT UINTN *OptionSize
);
/**
Discard all changes done to the BMM pages such as Boot Order change,
Driver order change.
@param Private The BMM context data.
@param CurrentFakeNVMap The current Fack NV Map.
**/
VOID
DiscardChangeHandler (
IN BMM_CALLBACK_DATA *Private,
IN BMM_FAKE_NV_DATA *CurrentFakeNVMap
);
/**
This function is to clean some useless data before submit changes.
@param Private The BMM context data.
**/
VOID
CleanUselessBeforeSubmit (
IN BMM_CALLBACK_DATA *Private
);
/**
Dispatch the display to the next page based on NewPageId.
@param Private The BMM context data.
@param NewPageId The original page ID.
**/
VOID
UpdatePageId (
BMM_CALLBACK_DATA *Private,
UINT16 NewPageId
);
/**
Remove the installed BootMaint and FileExplorer HiiPackages.
**/
VOID
FreeBMPackage (
VOID
);
/**
Install BootMaint and FileExplorer HiiPackages.
**/
VOID
InitBootMaintenance (
VOID
);
/**
Initialize console input device check box to ConsoleInCheck[MAX_MENU_NUMBER]
in BMM_FAKE_NV_DATA structure.
@param CallbackData The BMM context data.
**/
VOID
GetConsoleInCheck (
IN BMM_CALLBACK_DATA *CallbackData
);
/**
Initialize console output device check box to ConsoleOutCheck[MAX_MENU_NUMBER]
in BMM_FAKE_NV_DATA structure.
@param CallbackData The BMM context data.
**/
VOID
GetConsoleOutCheck (
IN BMM_CALLBACK_DATA *CallbackData
);
/**
Initialize standard error output device check box to ConsoleErrCheck[MAX_MENU_NUMBER]
in BMM_FAKE_NV_DATA structure.
@param CallbackData The BMM context data.
**/
VOID
GetConsoleErrCheck (
IN BMM_CALLBACK_DATA *CallbackData
);
/**
Initialize terminal attributes (baudrate, data rate, stop bits, parity and terminal type)
to BMM_FAKE_NV_DATA structure.
@param CallbackData The BMM context data.
**/
VOID
GetTerminalAttribute (
IN BMM_CALLBACK_DATA *CallbackData
);
/**
This function will change video resolution and text mode
according to defined setup mode or defined boot mode
@param IsSetupMode Indicate mode is changed to setup mode or boot mode.
@retval EFI_SUCCESS Mode is changed successfully.
@retval Others Mode failed to be changed.
**/
EFI_STATUS
BmmSetConsoleMode (
BOOLEAN IsSetupMode
);
/**
This function converts an input device structure to a Unicode string.
@param DevPath A pointer to the device path structure.
@return A new allocated Unicode string that represents the device path.
**/
CHAR16 *
UiDevicePathToStr (
IN EFI_DEVICE_PATH_PROTOCOL *DevPath
);
/**
Extract filename from device path. The returned buffer is allocated using AllocateCopyPool.
The caller is responsible for freeing the allocated buffer using FreePool().
@param DevicePath Device path.
@return A new allocated string that represents the file name.
**/
CHAR16 *
ExtractFileNameFromDevicePath (
IN EFI_DEVICE_PATH_PROTOCOL *DevicePath
);
/**
This function allows a caller to extract the current configuration for one
or more named elements from the target driver.
@param This Points to the EFI_HII_CONFIG_ACCESS_PROTOCOL.
@param Request A null-terminated Unicode string in <ConfigRequest> format.
@param Progress On return, points to a character in the Request string.
Points to the string's null terminator if request was successful.
Points to the most recent '&' before the first failing name/value
pair (or the beginning of the string if the failure is in the
first name/value pair) if the request was not successful.
@param Results A null-terminated Unicode string in <ConfigAltResp> format which
has all values filled in for the names in the Request string.
String to be allocated by the called function.
@retval EFI_SUCCESS The Results is filled with the requested values.
@retval EFI_OUT_OF_RESOURCES Not enough memory to store the results.
@retval EFI_INVALID_PARAMETER Request is NULL, illegal syntax, or unknown name.
@retval EFI_NOT_FOUND Routing data doesn't match any storage in this driver.
**/
EFI_STATUS
EFIAPI
BootMaintExtractConfig (
IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This,
IN CONST EFI_STRING Request,
OUT EFI_STRING *Progress,
OUT EFI_STRING *Results
);
/**
This function applies changes in a driver's configuration.
Input is a Configuration, which has the routing data for this
driver followed by name / value configuration pairs. The driver
must apply those pairs to its configurable storage. If the
driver's configuration is stored in a linear block of data
and the driver's name / value pairs are in <BlockConfig>
format, it may use the ConfigToBlock helper function (above) to
simplify the job. Currently not implemented.
@param[in] This Points to the EFI_HII_CONFIG_ACCESS_PROTOCOL.
@param[in] Configuration A null-terminated Unicode string in
<ConfigString> format.
@param[out] Progress A pointer to a string filled in with the
offset of the most recent '&' before the
first failing name / value pair (or the
beginn ing of the string if the failure
is in the first name / value pair) or
the terminating NULL if all was
successful.
@retval EFI_SUCCESS The results have been distributed or are
awaiting distribution.
@retval EFI_OUT_OF_RESOURCES Not enough memory to store the
parts of the results that must be
stored awaiting possible future
protocols.
@retval EFI_INVALID_PARAMETERS Passing in a NULL for the
Results parameter would result
in this type of error.
@retval EFI_NOT_FOUND Target for the specified routing data
was not found.
**/
EFI_STATUS
EFIAPI
BootMaintRouteConfig (
IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This,
IN CONST EFI_STRING Configuration,
OUT EFI_STRING *Progress
);
/**
This function processes the results of changes in configuration.
@param This Points to the EFI_HII_CONFIG_ACCESS_PROTOCOL.
@param Action Specifies the type of action taken by the browser.
@param QuestionId A unique value which is sent to the original exporting driver
so that it can identify the type of data to expect.
@param Type The type of value for the question.
@param Value A pointer to the data being sent to the original exporting driver.
@param ActionRequest On return, points to the action requested by the callback function.
@retval EFI_SUCCESS The callback successfully handled the action.
@retval EFI_OUT_OF_RESOURCES Not enough storage is available to hold the variable and its data.
@retval EFI_DEVICE_ERROR The variable could not be saved.
@retval EFI_UNSUPPORTED The specified Action is not supported by the callback.
@retval EFI_INVALID_PARAMETER The parameter of Value or ActionRequest is invalid.
**/
EFI_STATUS
EFIAPI
BootMaintCallback (
IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This,
IN EFI_BROWSER_ACTION Action,
IN EFI_QUESTION_ID QuestionId,
IN UINT8 Type,
IN EFI_IFR_TYPE_VALUE *Value,
OUT EFI_BROWSER_ACTION_REQUEST *ActionRequest
);
/**
Create boot option base on the input file path info.
@param FilePath Point to the file path.
@retval TRUE Exit caller function.
@retval FALSE Not exit caller function.
**/
BOOLEAN
EFIAPI
CreateBootOptionFromFile (
IN EFI_DEVICE_PATH_PROTOCOL *FilePath
);
/**
Create driver option base on the input file path info.
@param FilePath Point to the file path.
@retval TRUE Exit caller function.
@retval FALSE Not exit caller function.
**/
BOOLEAN
EFIAPI
CreateDriverOptionFromFile (
IN EFI_DEVICE_PATH_PROTOCOL *FilePath
);
/**
Boot the file specified by the input file path info.
@param FilePath Point to the file path.
@retval TRUE Exit caller function.
@retval FALSE Not exit caller function.
**/
BOOLEAN
EFIAPI
BootFromFile (
IN EFI_DEVICE_PATH_PROTOCOL *FilePath
);
//
// Global variable in this program (defined in data.c)
//
extern BM_MENU_OPTION BootOptionMenu;
extern BM_MENU_OPTION DriverOptionMenu;
extern BM_MENU_OPTION ConsoleInpMenu;
extern BM_MENU_OPTION ConsoleOutMenu;
extern BM_MENU_OPTION ConsoleErrMenu;
extern BM_MENU_OPTION DriverMenu;
extern BM_MENU_OPTION TerminalMenu;
extern UINT16 TerminalType[9];
extern COM_ATTR BaudRateList[19];
extern COM_ATTR DataBitsList[4];
extern COM_ATTR ParityList[5];
extern COM_ATTR StopBitsList[3];
extern EFI_GUID TerminalTypeGuid[9];
extern EFI_DEVICE_PATH_PROTOCOL EndDevicePath[];
extern UINT16 mFlowControlType[2];
extern UINT32 mFlowControlValue[2];
//
// Shared IFR form update data
//
extern VOID *mStartOpCodeHandle;
extern VOID *mEndOpCodeHandle;
extern EFI_IFR_GUID_LABEL *mStartLabel;
extern EFI_IFR_GUID_LABEL *mEndLabel;
extern BMM_CALLBACK_DATA gBootMaintenancePrivate;
extern BMM_CALLBACK_DATA *mBmmCallbackInfo;
#endif
| 17,024 |
777 | // Copyright 2014 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 "ash/common/system/user/user_view.h"
#include <algorithm>
#include <utility>
#include "ash/common/material_design/material_design_controller.h"
#include "ash/common/multi_profile_uma.h"
#include "ash/common/popup_message.h"
#include "ash/common/session/session_state_delegate.h"
#include "ash/common/shell_delegate.h"
#include "ash/common/system/tray/system_tray.h"
#include "ash/common/system/tray/system_tray_controller.h"
#include "ash/common/system/tray/system_tray_delegate.h"
#include "ash/common/system/tray/tray_constants.h"
#include "ash/common/system/tray/tray_popup_item_style.h"
#include "ash/common/system/tray/tray_popup_label_button.h"
#include "ash/common/system/tray/tray_popup_label_button_border.h"
#include "ash/common/system/tray/tray_popup_utils.h"
#include "ash/common/system/user/button_from_view.h"
#include "ash/common/system/user/login_status.h"
#include "ash/common/system/user/rounded_image_view.h"
#include "ash/common/system/user/user_card_view.h"
#include "ash/common/wm_lookup.h"
#include "ash/common/wm_shell.h"
#include "ash/common/wm_window.h"
#include "ash/public/cpp/shell_window_ids.h"
#include "ash/resources/vector_icons/vector_icons.h"
#include "ash/root_window_controller.h"
#include "base/memory/ptr_util.h"
#include "components/signin/core/account_id/account_id.h"
#include "components/user_manager/user_info.h"
#include "grit/ash_resources.h"
#include "grit/ash_strings.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/geometry/insets.h"
#include "ui/gfx/paint_vector_icon.h"
#include "ui/views/controls/button/label_button.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/separator.h"
#include "ui/views/layout/fill_layout.h"
#include "ui/views/mouse_watcher_view_host.h"
#include "ui/views/painter.h"
namespace ash {
namespace tray {
namespace {
bool UseMd() {
return MaterialDesignController::IsSystemTrayMenuMaterial();
}
const int kPublicAccountLogoutButtonBorderImagesNormal[] = {
IDR_AURA_TRAY_POPUP_PUBLIC_ACCOUNT_LOGOUT_BUTTON_BORDER,
IDR_AURA_TRAY_POPUP_LABEL_BUTTON_NORMAL_BACKGROUND,
IDR_AURA_TRAY_POPUP_LABEL_BUTTON_NORMAL_BACKGROUND,
IDR_AURA_TRAY_POPUP_PUBLIC_ACCOUNT_LOGOUT_BUTTON_BORDER,
IDR_AURA_TRAY_POPUP_LABEL_BUTTON_NORMAL_BACKGROUND,
IDR_AURA_TRAY_POPUP_LABEL_BUTTON_NORMAL_BACKGROUND,
IDR_AURA_TRAY_POPUP_PUBLIC_ACCOUNT_LOGOUT_BUTTON_BORDER,
IDR_AURA_TRAY_POPUP_LABEL_BUTTON_NORMAL_BACKGROUND,
IDR_AURA_TRAY_POPUP_LABEL_BUTTON_NORMAL_BACKGROUND,
};
const int kPublicAccountLogoutButtonBorderImagesHovered[] = {
IDR_AURA_TRAY_POPUP_PUBLIC_ACCOUNT_LOGOUT_BUTTON_BORDER,
IDR_AURA_TRAY_POPUP_PUBLIC_ACCOUNT_LOGOUT_BUTTON_BORDER,
IDR_AURA_TRAY_POPUP_PUBLIC_ACCOUNT_LOGOUT_BUTTON_BORDER,
IDR_AURA_TRAY_POPUP_PUBLIC_ACCOUNT_LOGOUT_BUTTON_BORDER,
IDR_AURA_TRAY_POPUP_LABEL_BUTTON_HOVER_BACKGROUND,
IDR_AURA_TRAY_POPUP_PUBLIC_ACCOUNT_LOGOUT_BUTTON_BORDER,
IDR_AURA_TRAY_POPUP_PUBLIC_ACCOUNT_LOGOUT_BUTTON_BORDER,
IDR_AURA_TRAY_POPUP_PUBLIC_ACCOUNT_LOGOUT_BUTTON_BORDER,
IDR_AURA_TRAY_POPUP_PUBLIC_ACCOUNT_LOGOUT_BUTTON_BORDER,
};
// When a hover border is used, it is starting this many pixels before the icon
// position.
const int kTrayUserTileHoverBorderInset = 10;
// Offsetting the popup message relative to the tray menu.
const int kPopupMessageOffset = 25;
// Switch to a user with the given |user_index|.
void SwitchUser(UserIndex user_index) {
// Do not switch users when the log screen is presented.
SessionStateDelegate* delegate = WmShell::Get()->GetSessionStateDelegate();
if (delegate->IsUserSessionBlocked())
return;
DCHECK(user_index > 0);
MultiProfileUMA::RecordSwitchActiveUser(
MultiProfileUMA::SWITCH_ACTIVE_USER_BY_TRAY);
delegate->SwitchActiveUser(delegate->GetUserInfo(user_index)->GetAccountId());
}
bool IsMultiProfileSupportedAndUserActive() {
return WmShell::Get()->delegate()->IsMultiProfilesEnabled() &&
!WmShell::Get()->GetSessionStateDelegate()->IsUserSessionBlocked();
}
// Creates the view shown in the user switcher popup ("AddUserMenuOption").
views::View* CreateAddUserView(AddUserSessionPolicy policy,
views::ButtonListener* listener) {
DCHECK(UseMd());
auto view = new views::View;
const int icon_padding = (kMenuButtonSize - kMenuIconSize) / 2;
auto layout =
new views::BoxLayout(views::BoxLayout::kHorizontal, 0, 0,
kTrayPopupLabelHorizontalPadding + icon_padding);
layout->set_minimum_cross_axis_size(
GetTrayConstant(TRAY_POPUP_ITEM_MIN_HEIGHT));
view->SetLayoutManager(layout);
view->set_background(
views::Background::CreateSolidBackground(kBackgroundColor));
int message_id = 0;
switch (policy) {
case AddUserSessionPolicy::ALLOWED: {
message_id = IDS_ASH_STATUS_TRAY_SIGN_IN_ANOTHER_ACCOUNT;
auto icon = new views::ImageView();
icon->SetImage(
gfx::CreateVectorIcon(kSystemMenuNewUserIcon, kMenuIconColor));
view->AddChildView(icon);
break;
}
case AddUserSessionPolicy::ERROR_NOT_ALLOWED_PRIMARY_USER:
message_id = IDS_ASH_STATUS_TRAY_MESSAGE_NOT_ALLOWED_PRIMARY_USER;
break;
case AddUserSessionPolicy::ERROR_MAXIMUM_USERS_REACHED:
message_id = IDS_ASH_STATUS_TRAY_MESSAGE_CANNOT_ADD_USER;
break;
case AddUserSessionPolicy::ERROR_NO_ELIGIBLE_USERS:
message_id = IDS_ASH_STATUS_TRAY_MESSAGE_OUT_OF_USERS;
break;
}
auto command_label = new views::Label(l10n_util::GetStringUTF16(message_id));
command_label->SetHorizontalAlignment(gfx::ALIGN_LEFT);
command_label->SetMultiLine(true);
TrayPopupItemStyle label_style(
TrayPopupItemStyle::FontStyle::DETAILED_VIEW_LABEL);
int vertical_padding = kMenuSeparatorVerticalPadding;
if (policy != AddUserSessionPolicy::ALLOWED) {
label_style.set_font_style(TrayPopupItemStyle::FontStyle::CAPTION);
label_style.set_color_style(TrayPopupItemStyle::ColorStyle::INACTIVE);
vertical_padding += kMenuSeparatorVerticalPadding;
}
label_style.SetupLabel(command_label);
view->AddChildView(command_label);
view->SetBorder(views::CreateEmptyBorder(vertical_padding, icon_padding,
vertical_padding,
kTrayPopupLabelHorizontalPadding));
if (policy == AddUserSessionPolicy::ALLOWED) {
auto button =
new ButtonFromView(view, listener, TrayPopupInkDropStyle::INSET_BOUNDS,
false, gfx::Insets());
button->SetAccessibleName(
l10n_util::GetStringUTF16(IDS_ASH_STATUS_TRAY_SIGN_IN_ANOTHER_ACCOUNT));
return button;
}
return view;
}
class UserViewMouseWatcherHost : public views::MouseWatcherHost {
public:
explicit UserViewMouseWatcherHost(const gfx::Rect& screen_area)
: screen_area_(screen_area) {}
~UserViewMouseWatcherHost() override {}
// Implementation of MouseWatcherHost.
bool Contains(const gfx::Point& screen_point,
views::MouseWatcherHost::MouseEventType type) override {
return screen_area_.Contains(screen_point);
}
private:
gfx::Rect screen_area_;
DISALLOW_COPY_AND_ASSIGN(UserViewMouseWatcherHost);
};
// A view that acts as the contents of the widget that appears when clicking
// the active user. If the mouse exits this view or an otherwise unhandled
// click is detected, it will invoke a closure passed at construction time.
class AddUserWidgetContents : public views::View {
public:
explicit AddUserWidgetContents(const base::Closure& close_widget)
: close_widget_(close_widget) {
// Don't want to receive a mouse exit event when the cursor enters a child.
set_notify_enter_exit_on_child(true);
}
~AddUserWidgetContents() override {}
bool OnMousePressed(const ui::MouseEvent& event) override { return true; }
void OnMouseReleased(const ui::MouseEvent& event) override {
close_widget_.Run();
}
void OnMouseExited(const ui::MouseEvent& event) override {
close_widget_.Run();
}
void OnGestureEvent(ui::GestureEvent* event) override { close_widget_.Run(); }
private:
base::Closure close_widget_;
DISALLOW_COPY_AND_ASSIGN(AddUserWidgetContents);
};
// The menu item view which gets shown when the user clicks in multi profile
// mode onto the user item.
class AddUserView : public views::View {
public:
// The |owner| is the view for which this view gets created.
AddUserView(ButtonFromView* owner);
~AddUserView() override;
// Get the anchor view for a message.
views::View* anchor() { return anchor_; }
private:
// Overridden from views::View.
gfx::Size GetPreferredSize() const override;
// Create the additional client content for this item.
void AddContent();
// This is the content we create and show.
views::View* add_user_;
// This is the owner view of this item.
ButtonFromView* owner_;
// The anchor view for targetted bubble messages.
views::View* anchor_;
DISALLOW_COPY_AND_ASSIGN(AddUserView);
};
AddUserView::AddUserView(ButtonFromView* owner)
: add_user_(nullptr), owner_(owner), anchor_(nullptr) {
DCHECK(!UseMd());
AddContent();
owner_->ForceBorderVisible(true);
}
AddUserView::~AddUserView() {
owner_->ForceBorderVisible(false);
}
gfx::Size AddUserView::GetPreferredSize() const {
return owner_->bounds().size();
}
void AddUserView::AddContent() {
SetLayoutManager(new views::FillLayout());
set_background(views::Background::CreateSolidBackground(kBackgroundColor));
add_user_ = new views::View;
add_user_->SetLayoutManager(new views::BoxLayout(
views::BoxLayout::kHorizontal, 0, 0, kTrayPopupPaddingBetweenItems));
AddChildViewAt(add_user_, 0);
// Add the icon which is also the anchor for messages.
add_user_->SetBorder(
views::CreateEmptyBorder(0, kTrayUserTileHoverBorderInset, 0, 0));
RoundedImageView* icon = new RoundedImageView(kTrayRoundedBorderRadius, true);
anchor_ = icon;
icon->SetImage(*ui::ResourceBundle::GetSharedInstance()
.GetImageNamed(IDR_AURA_UBER_TRAY_ADD_MULTIPROFILE_USER)
.ToImageSkia(),
gfx::Size(kTrayItemSize, kTrayItemSize));
add_user_->AddChildView(icon);
// Add the command text.
views::Label* command_label = new views::Label(
l10n_util::GetStringUTF16(IDS_ASH_STATUS_TRAY_SIGN_IN_ANOTHER_ACCOUNT));
command_label->SetHorizontalAlignment(gfx::ALIGN_LEFT);
add_user_->AddChildView(command_label);
}
// This border reserves 4dp above and 8dp below and paints a horizontal
// separator 3dp below the host view.
class ActiveUserBorder : public views::Border {
public:
ActiveUserBorder() {}
~ActiveUserBorder() override {}
// views::Border:
void Paint(const views::View& view, gfx::Canvas* canvas) override {
canvas->FillRect(
gfx::Rect(
0, view.height() - kMenuSeparatorVerticalPadding - kSeparatorWidth,
view.width(), kSeparatorWidth),
kHorizontalSeparatorColor);
}
gfx::Insets GetInsets() const override {
return gfx::Insets(kMenuSeparatorVerticalPadding,
kMenuExtraMarginFromLeftEdge,
kMenuSeparatorVerticalPadding * 2, 0);
}
gfx::Size GetMinimumSize() const override { return gfx::Size(); }
private:
DISALLOW_COPY_AND_ASSIGN(ActiveUserBorder);
};
} // namespace
UserView::UserView(SystemTrayItem* owner, LoginStatus login, UserIndex index)
: user_index_(index),
user_card_view_(nullptr),
owner_(owner),
is_user_card_button_(false),
logout_button_(nullptr),
add_user_enabled_(true),
focus_manager_(nullptr) {
CHECK_NE(LoginStatus::NOT_LOGGED_IN, login);
if (!UseMd() && !index && login == LoginStatus::PUBLIC) {
// Public user gets a yellow bg.
set_background(views::Background::CreateSolidBackground(
kPublicAccountBackgroundColor));
}
// The logout button must be added before the user card so that the user card
// can correctly calculate the remaining available width.
// Note that only the current multiprofile user gets a button.
if (IsActiveUser())
AddLogoutButton(login);
AddUserCard(login);
if (UseMd()) {
auto layout = new views::BoxLayout(views::BoxLayout::kHorizontal, 0, 0, 0);
SetLayoutManager(layout);
layout->set_cross_axis_alignment(
views::BoxLayout::CROSS_AXIS_ALIGNMENT_CENTER);
layout->SetFlexForView(user_card_view_, 1);
if (IsActiveUser())
SetBorder(base::MakeUnique<ActiveUserBorder>());
}
}
UserView::~UserView() {
RemoveAddUserMenuOption();
}
void UserView::MouseMovedOutOfHost() {
DCHECK(!UseMd());
RemoveAddUserMenuOption();
}
TrayUser::TestState UserView::GetStateForTest() const {
if (add_menu_option_.get()) {
return add_user_enabled_ ? TrayUser::ACTIVE : TrayUser::ACTIVE_BUT_DISABLED;
}
if (!is_user_card_button_)
return TrayUser::SHOWN;
return static_cast<ButtonFromView*>(user_card_view_)->is_hovered_for_test()
? TrayUser::HOVERED
: TrayUser::SHOWN;
}
gfx::Rect UserView::GetBoundsInScreenOfUserButtonForTest() {
DCHECK(user_card_view_);
return user_card_view_->GetBoundsInScreen();
}
bool UserView::IsActiveUser() const {
return user_index_ == 0;
}
gfx::Size UserView::GetPreferredSize() const {
// MD uses a layout manager.
if (UseMd())
return View::GetPreferredSize();
// The width is more or less ignored (set by other rows in the system menu).
gfx::Size size = user_card_view_->GetPreferredSize();
if (logout_button_)
size.SetToMax(logout_button_->GetPreferredSize());
// Only the active user panel will be forced to a certain height.
if (IsActiveUser()) {
size.set_height(std::max(
size.height(),
GetTrayConstant(TRAY_POPUP_ITEM_MIN_HEIGHT) + GetInsets().height()));
}
return size;
}
int UserView::GetHeightForWidth(int width) const {
return GetPreferredSize().height();
}
void UserView::Layout() {
// MD uses a layout manager.
if (UseMd())
return views::View::Layout();
gfx::Rect contents_area(GetContentsBounds());
if (logout_button_) {
// Give the logout button the space it requests.
gfx::Rect logout_area = contents_area;
logout_area.ClampToCenteredSize(logout_button_->GetPreferredSize());
logout_area.set_x(contents_area.right() - logout_area.width());
// Give the remaining space to the user card.
gfx::Rect user_card_area = contents_area;
int remaining_width = contents_area.width() - logout_area.width();
if (IsMultiProfileSupportedAndUserActive()) {
// In multiprofile case |user_card_view_| and |logout_button_| have to
// have the same height.
int y = std::min(user_card_area.y(), logout_area.y());
int height = std::max(user_card_area.height(), logout_area.height());
logout_area.set_y(y);
logout_area.set_height(height);
user_card_area.set_y(y);
user_card_area.set_height(height);
// In multiprofile mode we have also to increase the size of the card by
// the size of the border to make it overlap with the logout button.
user_card_area.set_width(std::max(0, remaining_width + 1));
// To make the logout button symmetrical with the user card we also make
// the button longer by the same size the hover area in front of the icon
// got inset.
logout_area.set_width(logout_area.width() +
kTrayUserTileHoverBorderInset);
} else {
// In all other modes we have to make sure that there is enough spacing
// between the two.
remaining_width -= kTrayPopupPaddingBetweenItems;
}
user_card_area.set_width(remaining_width);
user_card_view_->SetBoundsRect(user_card_area);
logout_button_->SetBoundsRect(logout_area);
} else {
user_card_view_->SetBoundsRect(contents_area);
}
}
void UserView::ButtonPressed(views::Button* sender, const ui::Event& event) {
if (sender == logout_button_) {
WmShell::Get()->RecordUserMetricsAction(UMA_STATUS_AREA_SIGN_OUT);
RemoveAddUserMenuOption();
WmShell::Get()->system_tray_controller()->SignOut();
} else if (sender == user_card_view_ &&
IsMultiProfileSupportedAndUserActive()) {
if (IsActiveUser()) {
ToggleAddUserMenuOption();
} else {
RemoveAddUserMenuOption();
SwitchUser(user_index_);
// Since the user list is about to change the system menu should get
// closed.
owner_->system_tray()->CloseSystemBubble();
}
} else if (add_menu_option_.get() &&
sender->GetWidget() == add_menu_option_.get()) {
RemoveAddUserMenuOption();
// Let the user add another account to the session.
MultiProfileUMA::RecordSigninUser(MultiProfileUMA::SIGNIN_USER_BY_TRAY);
WmShell::Get()->system_tray_delegate()->ShowUserLogin();
owner_->system_tray()->CloseSystemBubble();
} else {
NOTREACHED();
}
}
void UserView::OnWillChangeFocus(View* focused_before, View* focused_now) {
if (focused_now)
RemoveAddUserMenuOption();
}
void UserView::OnDidChangeFocus(View* focused_before, View* focused_now) {
// Nothing to do here.
}
void UserView::AddLogoutButton(LoginStatus login) {
const base::string16 title =
user::GetLocalizedSignOutStringForStatus(login, true);
auto* logout_button =
TrayPopupUtils::CreateTrayPopupBorderlessButton(this, title);
logout_button->SetAccessibleName(title);
logout_button_ = logout_button;
if (UseMd()) {
AddChildView(TrayPopupUtils::CreateVerticalSeparator());
} else if (login == LoginStatus::PUBLIC) {
// In public account mode, the logout button border has a custom color.
std::unique_ptr<TrayPopupLabelButtonBorder> border(
new TrayPopupLabelButtonBorder());
border->SetPainter(false, views::Button::STATE_NORMAL,
views::Painter::CreateImageGridPainter(
kPublicAccountLogoutButtonBorderImagesNormal));
border->SetPainter(false, views::Button::STATE_HOVERED,
views::Painter::CreateImageGridPainter(
kPublicAccountLogoutButtonBorderImagesHovered));
border->SetPainter(false, views::Button::STATE_PRESSED,
views::Painter::CreateImageGridPainter(
kPublicAccountLogoutButtonBorderImagesHovered));
logout_button_->SetBorder(std::move(border));
}
AddChildView(logout_button_);
}
void UserView::AddUserCard(LoginStatus login) {
if (UseMd())
return AddUserCardMd(login);
// Add padding around the panel.
const int kSidePadding = kTrayPopupPaddingHorizontal;
SetBorder(views::CreateEmptyBorder(
kTrayPopupUserCardVerticalPadding, kSidePadding,
kTrayPopupUserCardVerticalPadding, kSidePadding));
views::TrayBubbleView* bubble_view =
owner_->system_tray()->GetSystemBubble()->bubble_view();
int max_card_width = bubble_view->GetMaximumSize().width() -
(2 * kSidePadding + kTrayPopupPaddingBetweenItems);
if (logout_button_)
max_card_width -= logout_button_->GetPreferredSize().width();
user_card_view_ = new UserCardView(login, max_card_width, user_index_);
// The entry is clickable when no system modal dialog is open and the multi
// profile option is active.
bool clickable = !WmShell::Get()->IsSystemModalWindowOpen() &&
IsMultiProfileSupportedAndUserActive();
if (clickable) {
// To allow the border to start before the icon, reduce the size before and
// add an inset to the icon to get the spacing.
if (IsActiveUser()) {
SetBorder(views::CreateEmptyBorder(
kTrayPopupUserCardVerticalPadding,
kSidePadding - kTrayUserTileHoverBorderInset,
kTrayPopupUserCardVerticalPadding, kSidePadding));
user_card_view_->SetBorder(
views::CreateEmptyBorder(0, kTrayUserTileHoverBorderInset, 0, 0));
}
gfx::Insets insets = gfx::Insets(1, 1, 1, 1);
views::View* contents_view = user_card_view_;
if (!IsActiveUser()) {
// Since the activation border needs to be drawn around the tile, we
// have to put the tile into another view which fills the menu panel,
// but keeping the offsets of the content.
contents_view = new views::View();
contents_view->SetBorder(views::CreateEmptyBorder(
kTrayPopupUserCardVerticalPadding, kSidePadding,
kTrayPopupUserCardVerticalPadding, kSidePadding));
contents_view->SetLayoutManager(new views::FillLayout());
SetBorder(nullptr);
contents_view->AddChildView(user_card_view_);
insets = gfx::Insets(1, 1, 1, 3);
}
auto* button = new ButtonFromView(contents_view, this,
// This parameter is ignored in non-md.
TrayPopupInkDropStyle::FILL_BOUNDS,
IsActiveUser(), insets);
user_card_view_ = button;
is_user_card_button_ = true;
}
AddChildViewAt(user_card_view_, 0);
// Card for supervised user can consume more space than currently
// available. In that case we should increase system bubble's width.
if (login == LoginStatus::PUBLIC)
bubble_view->SetWidth(GetPreferredSize().width());
}
void UserView::AddUserCardMd(LoginStatus login) {
user_card_view_ = new UserCardView(login, -1, user_index_);
// The entry is clickable when no system modal dialog is open and the multi
// profile option is active.
bool clickable = !WmShell::Get()->IsSystemModalWindowOpen() &&
IsMultiProfileSupportedAndUserActive();
if (clickable) {
views::View* contents_view = user_card_view_;
auto* button =
new ButtonFromView(contents_view, this,
IsActiveUser() ? TrayPopupInkDropStyle::INSET_BOUNDS
: TrayPopupInkDropStyle::FILL_BOUNDS,
false, gfx::Insets());
user_card_view_ = button;
is_user_card_button_ = true;
}
AddChildViewAt(user_card_view_, 0);
}
void UserView::ToggleAddUserMenuOption() {
if (add_menu_option_.get()) {
RemoveAddUserMenuOption();
return;
}
// Note: We do not need to install a global event handler to delete this
// item since it will destroyed automatically before the menu / user menu item
// gets destroyed..
add_menu_option_.reset(new views::Widget);
views::Widget::InitParams params;
params.type = views::Widget::InitParams::TYPE_TOOLTIP;
params.keep_on_top = true;
params.accept_events = true;
params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
if (!UseMd())
params.shadow_type = views::Widget::InitParams::SHADOW_TYPE_NONE;
params.opacity = views::Widget::InitParams::TRANSLUCENT_WINDOW;
params.name = "AddUserMenuOption";
WmLookup::Get()
->GetWindowForWidget(GetWidget())
->GetRootWindowController()
->ConfigureWidgetInitParamsForContainer(
add_menu_option_.get(), kShellWindowId_DragImageAndTooltipContainer,
¶ms);
add_menu_option_->Init(params);
const SessionStateDelegate* delegate =
WmShell::Get()->GetSessionStateDelegate();
const AddUserSessionPolicy add_user_policy =
delegate->GetAddUserSessionPolicy();
add_user_enabled_ = add_user_policy == AddUserSessionPolicy::ALLOWED;
if (UseMd()) {
// Position the widget on top of the user card view (which is still in the
// system menu). The top half of the widget will be transparent to allow
// the active user to show through.
gfx::Rect bounds = user_card_view_->GetBoundsInScreen();
bounds.set_width(bounds.width() + kSeparatorWidth);
int row_height = bounds.height();
views::View* container = new AddUserWidgetContents(
base::Bind(&UserView::RemoveAddUserMenuOption, base::Unretained(this)));
container->SetBorder(views::CreatePaddedBorder(
views::CreateSolidSidedBorder(0, 0, 0, kSeparatorWidth,
kBackgroundColor),
gfx::Insets(row_height, 0, 0, 0)));
views::View* add_user_padding = new views::View();
add_user_padding->SetBorder(views::CreateSolidSidedBorder(
kMenuSeparatorVerticalPadding, 0, 0, 0, kBackgroundColor));
views::View* add_user_view = CreateAddUserView(add_user_policy, this);
add_user_padding->AddChildView(add_user_view);
add_user_padding->SetLayoutManager(new views::FillLayout());
container->AddChildView(add_user_padding);
container->SetLayoutManager(new views::FillLayout());
add_menu_option_->SetContentsView(container);
bounds.set_height(container->GetPreferredSize().height());
add_menu_option_->SetBounds(bounds);
// Show the content.
add_menu_option_->SetAlwaysOnTop(true);
add_menu_option_->Show();
// We activate the entry automatically if invoked with focus.
if (add_user_enabled_ && user_card_view_->HasFocus()) {
add_user_view->GetFocusManager()->SetFocusedView(add_user_view);
user_card_view_->GetFocusManager()->SetFocusedView(add_user_view);
}
} else {
AddUserView* add_user_view =
new AddUserView(static_cast<ButtonFromView*>(user_card_view_));
ButtonFromView* button = new ButtonFromView(
add_user_view, add_user_enabled_ ? this : nullptr,
// Ignored in non-md.
TrayPopupInkDropStyle::INSET_BOUNDS, add_user_enabled_, gfx::Insets(1));
button->SetAccessibleName(
l10n_util::GetStringUTF16(IDS_ASH_STATUS_TRAY_SIGN_IN_ANOTHER_ACCOUNT));
button->ForceBorderVisible(true);
add_menu_option_->SetOpacity(1.f);
add_menu_option_->SetContentsView(button);
// Position it below our user card.
gfx::Rect bounds = user_card_view_->GetBoundsInScreen();
bounds.set_y(bounds.y() + bounds.height());
add_menu_option_->SetBounds(bounds);
// Show the content.
add_menu_option_->SetAlwaysOnTop(true);
add_menu_option_->Show();
if (add_user_enabled_) {
// We activate the entry automatically if invoked with focus.
if (user_card_view_->HasFocus()) {
button->GetFocusManager()->SetFocusedView(button);
user_card_view_->GetFocusManager()->SetFocusedView(button);
}
} else {
ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance();
int message_id = 0;
switch (add_user_policy) {
case AddUserSessionPolicy::ERROR_NOT_ALLOWED_PRIMARY_USER:
message_id = IDS_ASH_STATUS_TRAY_MESSAGE_NOT_ALLOWED_PRIMARY_USER;
break;
case AddUserSessionPolicy::ERROR_MAXIMUM_USERS_REACHED:
message_id = IDS_ASH_STATUS_TRAY_MESSAGE_CANNOT_ADD_USER;
break;
case AddUserSessionPolicy::ERROR_NO_ELIGIBLE_USERS:
message_id = IDS_ASH_STATUS_TRAY_MESSAGE_OUT_OF_USERS;
break;
default:
NOTREACHED() << "Unknown adding user policy "
<< static_cast<int>(add_user_policy);
}
popup_message_.reset(new PopupMessage(
bundle.GetLocalizedString(
IDS_ASH_STATUS_TRAY_CAPTION_CANNOT_ADD_USER),
bundle.GetLocalizedString(message_id), PopupMessage::ICON_WARNING,
add_user_view->anchor(), views::BubbleBorder::TOP_LEFT,
gfx::Size(parent()->bounds().width() - kPopupMessageOffset, 0),
2 * kPopupMessageOffset));
}
// Find the screen area which encloses both elements and sets then a mouse
// watcher which will close the "menu".
gfx::Rect area = user_card_view_->GetBoundsInScreen();
area.set_height(2 * area.height());
mouse_watcher_.reset(
new views::MouseWatcher(new UserViewMouseWatcherHost(area), this));
mouse_watcher_->Start();
}
// Install a listener to focus changes so that we can remove the card when
// the focus gets changed. When called through the destruction of the bubble,
// the FocusManager cannot be determined anymore and we remember it here.
focus_manager_ = user_card_view_->GetFocusManager();
focus_manager_->AddFocusChangeListener(this);
}
void UserView::RemoveAddUserMenuOption() {
if (!add_menu_option_.get())
return;
focus_manager_->RemoveFocusChangeListener(this);
focus_manager_ = nullptr;
if (user_card_view_->GetFocusManager())
user_card_view_->GetFocusManager()->ClearFocus();
popup_message_.reset();
mouse_watcher_.reset();
add_menu_option_.reset();
}
} // namespace tray
} // namespace ash
| 11,051 |
645 | # -*- coding: utf-8 -*-
"""
termcolor's documentation settings
"""
from __future__ import unicode_literals
import os
# project information
project = 'termcolor'
copyright = '2013, <NAME>'
version = '0.1'
release = '0.1'
# sphinx settings
extensions = []
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
exclude_patterns = ['_build']
pygments_style = 'sphinx'
highlight_language = 'c++'
# html output settings
html_theme = 'default'
html_static_path = ['_static']
# Unfortunately, Sphinx doesn't support code highlighting for standard
# reStructuredText `code` directive. So let's register 'code' directive
# as alias for Sphinx's own implementation.
#
# https://github.com/sphinx-doc/sphinx/issues/2155
from docutils.parsers.rst import directives
from sphinx.directives.code import CodeBlock
directives.register_directive('code', CodeBlock)
| 284 |
335 | <reponame>mrslezak/Engine<filename>QuantExt/qle/time/futureexpirycalculator.hpp
/*
Copyright (C) 2019 Quaternion Risk Management Ltd
All rights reserved.
This file is part of ORE, a free-software/open-source library
for transparent pricing and risk analysis - http://opensourcerisk.org
ORE is free software: you can redistribute it and/or modify it
under the terms of the Modified BSD License. You should have received a
copy of the license along with this program.
The license is also available online at <http://opensourcerisk.org>
This program is distributed on the basis that it will form a useful
contribution to risk analytics and model standardisation, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.
*/
/*! \file qle/time/futureexpirycalculator.hpp
\brief Base class for classes that perform date calculations for future contracts
*/
#ifndef quantext_future_expiry_calculator_hpp
#define quantext_future_expiry_calculator_hpp
#include <ql/settings.hpp>
#include <ql/time/date.hpp>
namespace QuantExt {
//! Base class for classes that perform date calculations for future contracts
class FutureExpiryCalculator {
public:
virtual ~FutureExpiryCalculator() {}
/*! Given a reference date, \p referenceDate, return the expiry date of the next futures contract relative to
the reference date.
The \p includeExpiry parameter controls what happens when the \p referenceDate is equal to the next contract's
expiry date. If \p includeExpiry is \c true, the contract's expiry date is returned. If \p includeExpiry is
\c false, the next succeeding contract's expiry is returned.
If \p forOption is \c true, the next expiry for the option contract, as opposed to the future contract, is
returned.
*/
virtual QuantLib::Date nextExpiry(bool includeExpiry = true, const QuantLib::Date& referenceDate = QuantLib::Date(),
QuantLib::Natural offset = 0, bool forOption = false) = 0;
/*! Given a reference date, \p referenceDate, return the expiry date of the first futures contract prior to
the reference date.
The \p includeExpiry parameter controls what happens when the \p referenceDate is equal to the prior contract's
expiry date. If \p includeExpiry is \c true, the contract's expiry date is returned. If \p includeExpiry is
\c false, the next preceding contract's expiry is returned.
If \p forOption is \c true, the prior expiry for the option contract, as opposed to the future contract, is
returned.
*/
virtual QuantLib::Date priorExpiry(bool includeExpiry = true,
const QuantLib::Date& referenceDate = QuantLib::Date(),
bool forOption = false) = 0;
/*! Given a date, \p contractDate, return the future expiry date associated with that date.
If the future contract has a frequency that is less than monthly, the next available future contract expiry
date will be returned. If \p forOption is \c true, the next available future option expiry is returned. For
future contracts that have a frequency that is less than monthly, the \p monthOffset parameter is ignored.
If the future contract has a frequency that is monthly or greater, the contract's month and year is taken
to be the \p contractDate month and year, and the expiry date of the future contract that is \p monthOffset
number of months from that month's future contract is returned. If \p monthOffset is zero, the expiry date of
the future contract associated with that month and year is returned. If \p forOption is \c true, the expiry
date for the option contract, as opposed to the future contract, is returned.
*/
virtual QuantLib::Date expiryDate(const QuantLib::Date& contractDate, QuantLib::Natural monthOffset = 0,
bool forOption = false) = 0;
};
} // namespace QuantExt
#endif
| 1,312 |
8,624 | /* GNU Ocrad - Optical Character Recognition program
Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011,
2012, 2013 <NAME>.
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 3 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, see <http://www.gnu.org/licenses/>.
*/
#include <algorithm>
#include <cstdio>
#include <vector>
#include <stdint.h>
#include "common.h"
#include "rectangle.h"
#include "ucs.h"
#include "bitmap.h"
#include "blob.h"
#include "character.h"
Character::Character( const Character & c )
: Rectangle( c ), blobpv( c.blobpv ), gv( c.gv )
{
for( unsigned i = 0; i < blobpv.size(); ++i )
blobpv[i] = new Blob( *c.blobpv[i] );
}
Character & Character::operator=( const Character & c )
{
if( this != &c )
{
Rectangle::operator=( c );
for( unsigned i = 0; i < blobpv.size(); ++i ) delete blobpv[i];
blobpv = c.blobpv;
for( unsigned i = 0; i < blobpv.size(); ++i )
blobpv[i] = new Blob( *c.blobpv[i] );
gv = c.gv;
}
return *this;
}
Character::~Character()
{
for( unsigned i = 0; i < blobpv.size(); ++i ) delete blobpv[i];
}
// Return the filled area of the main blobs only (no recursive)
//
int Character::area() const
{
int a = 0;
for( int i = 0; i < blobs(); ++i ) a += blobpv[i]->area();
return a;
}
const Blob & Character::blob( const int i ) const
{
if( i < 0 || i >= blobs() )
Ocrad::internal_error( "const blob, index out of bounds" );
return *blobpv[i];
}
Blob & Character::blob( const int i )
{
if( i < 0 || i >= blobs() )
Ocrad::internal_error( "blob, index out of bounds" );
return *blobpv[i];
}
Blob & Character::main_blob()
{
int imax = 0;
for( int i = 1; i < blobs(); ++i )
if( blobpv[i]->size() > blobpv[imax]->size() )
imax = i;
return *blobpv[imax];
}
void Character::shift_blobp( Blob * const p )
{
add_rectangle( *p );
int i = blobs() - 1;
for( ; i >= 0; --i )
{
Blob & bi = *blobpv[i];
if( p->vcenter() > bi.vcenter() ) break;
if( p->vcenter() == bi.vcenter() && p->hcenter() >= bi.hcenter() ) break;
}
blobpv.insert( blobpv.begin() + ( i + 1 ), p );
}
void Character::insert_guess( const int i, const int code, const int value )
{
if( i < 0 || i > guesses() )
Ocrad::internal_error( "insert_guess, index out of bounds" );
gv.insert( gv.begin() + i, Guess( code, value ) );
}
void Character::delete_guess( const int i )
{
if( i < 0 || i >= guesses() )
Ocrad::internal_error( "delete_guess, index out of bounds" );
gv.erase( gv.begin() + i );
}
bool Character::set_merged_guess( const int code1, const int right1,
const int code2, const int blob_index )
{
if( blob_index < 0 || blob_index >= blobs() ) return false;
const Blob & b = *blobpv[blob_index];
if( b.left() <= right1 && right1 < b.right() )
{
only_guess( -(blob_index + 1), left() );
add_guess( code1, right1 );
add_guess( code2, right() );
return true;
}
return false;
}
void Character::swap_guesses( const int i, const int j )
{
if( i < 0 || i >= guesses() || j < 0 || j >= guesses() )
Ocrad::internal_error( "swap_guesses, index out of bounds" );
const int code = gv[i].code;
gv[i].code = gv[j].code; gv[j].code = code;
}
const Character::Guess & Character::guess( const int i ) const
{
if( i < 0 || i >= guesses() )
Ocrad::internal_error( "guess, index out of bounds" );
return gv[i];
}
bool Character::maybe( const int code ) const
{
for( int i = 0; i < guesses(); ++i )
if( code == gv[i].code ) return true;
return false;
}
/*
bool Character::maybe_digit() const
{
for( int i = 0; i < guesses(); ++i )
if( UCS::isdigit( gv[i].code ) ) return true;
return false;
}
bool Character::maybe_letter() const
{
for( int i = 0; i < guesses(); ++i )
if( UCS::isalpha( gv[i].code ) ) return true;
return false;
}
*/
void Character::join( Character & c )
{
for( int i = 0; i < c.blobs(); ++i ) shift_blobp( c.blobpv[i] );
c.blobpv.clear();
}
unsigned char Character::byte_result() const
{
if( guesses() )
{
const unsigned char ch = UCS::map_to_byte( gv[0].code );
if( ch ) return ch;
}
return '_';
}
const char * Character::utf8_result() const
{
if( guesses() )
{
const char * s = UCS::ucs_to_utf8( gv[0].code );
if( *s ) return s;
}
return "_";
}
void Character::print( const Control & control ) const
{
if( guesses() )
{
if( !control.utf8 )
{
unsigned char ch = UCS::map_to_byte( gv[0].code );
if( ch ) std::putc( ch, control.outfile );
}
else if( gv[0].code )
std::fputs( UCS::ucs_to_utf8( gv[0].code ), control.outfile );
}
else std::putc( '_', control.outfile );
}
void Character::dprint( const Control & control, const Rectangle & charbox,
const bool graph, const bool recursive ) const
{
if( graph || recursive )
std::fprintf( control.outfile, "%d guesses ", guesses() );
for( int i = 0; i < guesses(); ++i )
{
if( !control.utf8 )
{
unsigned char ch = UCS::map_to_byte( gv[i].code );
if( ch ) std::fprintf( control.outfile, "guess '%c', confidence %d ",
ch, gv[i].value );
}
else
std::fprintf( control.outfile, "guess '%s', confidence %d ",
UCS::ucs_to_utf8( gv[i].code ), gv[i].value );
if( !graph && !recursive ) break;
}
std::fputs( "\n", control.outfile );
if( graph )
{
std::fprintf( control.outfile,
"left = %d, top = %d, right = %d, bottom = %d\n",
left(), top(), right(), bottom() );
std::fprintf( control.outfile,
"width = %d, height = %d, hcenter = %d, vcenter = %d, black area = %d%%\n\n",
width(), height(), hcenter(), vcenter(), ( area() * 100 ) / size() );
const int minrow = std::min( top(), charbox.top() );
const int maxrow = std::max( bottom(), charbox.bottom() );
for( int row = minrow; row <= maxrow; ++row )
{
bool istop = ( row == top() );
bool isvc = ( row == vcenter() );
bool isbot = ( row == bottom() );
bool iscbtop = ( row == charbox.top() );
bool iscbvc = ( row == charbox.vcenter() );
bool iscbbot = ( row == charbox.bottom() );
bool ish1top = false, ish1bot = false, ish2top = false, ish2bot = false;
if( blobs() == 1 && blobpv[0]->holes() )
{
const Blob & b = *blobpv[0];
ish1top = ( row == b.hole(0).top() );
ish1bot = ( row == b.hole(0).bottom() );
if( b.holes() > 1 )
{
ish2top = ( row == b.hole(1).top() );
ish2bot = ( row == b.hole(1).bottom() );
}
}
for( int col = left(); col <= right(); ++col )
{
char ch = ( isvc && col == hcenter() ) ? '+' : '.';
for( int i = 0; i < blobs(); ++i )
{
int id = blobpv[i]->id( row, col );
if( id != 0 )
{
if( id > 0 ) ch = (ch == '+') ? 'C' : 'O';
else ch = (ch == '+') ? '=' : '-';
break;
}
}
std::fprintf( control.outfile, " %c", ch );
}
if( istop ) std::fprintf( control.outfile, " top(%d)", row );
if( isvc ) std::fprintf( control.outfile, " vcenter(%d)", row );
if( isbot ) std::fprintf( control.outfile, " bottom(%d)", row );
if( iscbtop ) std::fprintf( control.outfile, " box.top(%d)", row );
if( iscbvc ) std::fprintf( control.outfile, " box.vcenter(%d)", row );
if( iscbbot ) std::fprintf( control.outfile, " box.bottom(%d)", row );
if( ish1top ) std::fprintf( control.outfile, " h1.top(%d)", row );
if( ish1bot ) std::fprintf( control.outfile, " h1.bottom(%d)", row );
if( ish2top ) std::fprintf( control.outfile, " h2.top(%d)", row );
if( ish2bot ) std::fprintf( control.outfile, " h2.bottom(%d)", row );
std::fputs( "\n", control.outfile );
}
std::fputs( "\n\n", control.outfile );
}
}
void Character::xprint( const Control & control ) const
{
std::fprintf( control.exportfile, "%3d %3d %2d %2d; %d",
left(), top(), width(), height(), guesses() );
for( int i = 0; i < guesses(); ++i )
if( !control.utf8 )
{
unsigned char ch = UCS::map_to_byte( gv[i].code );
if( !ch ) ch = '_';
std::fprintf( control.exportfile, ", '%c'%d", ch, gv[i].value );
}
else
std::fprintf( control.exportfile, ", '%s'%d",
UCS::ucs_to_utf8( gv[i].code ), gv[i].value );
std::fputs( "\n", control.exportfile );
}
void Character::apply_filter( const Filter & filter )
{
if( filter.type() == Filter::none ) return;
const int code = guesses() ? gv[0].code : 0;
bool remove = false;
switch( filter.type() )
{
case Filter::none: // only for completeness
break;
case Filter::letters_only:
remove = true;
case Filter::letters:
if( !UCS::isalpha( code ) && !UCS::isspace( code ) )
{
for( int i = 1; i < guesses(); ++i )
if( UCS::isalpha( gv[i].code ) ) { swap_guesses( 0, i ); break; }
if( guesses() && !UCS::isalpha( gv[0].code ) )
gv[0].code = UCS::to_nearest_letter( gv[0].code );
if( remove && ( !guesses() || !UCS::isalpha( gv[0].code ) ) )
only_guess( 0, 0 );
}
break;
case Filter::numbers_only:
remove = true;
case Filter::numbers:
if( !UCS::isdigit( code ) && !UCS::isspace( code ) )
{
for( int i = 1; i < guesses(); ++i )
if( UCS::isdigit( gv[i].code ) ) { swap_guesses( 0, i ); break; }
if( guesses() && !UCS::isdigit( gv[0].code ) )
gv[0].code = UCS::to_nearest_digit( gv[0].code );
if( remove && ( !guesses() || !UCS::isdigit( gv[0].code ) ) )
only_guess( 0, 0 );
}
break;
}
}
| 4,714 |
6,304 | /*
* Copyright 2017 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef Skottie_DEFINED
#define Skottie_DEFINED
#include "include/core/SkFontMgr.h"
#include "include/core/SkRefCnt.h"
#include "include/core/SkSize.h"
#include "include/core/SkString.h"
#include "include/core/SkTypes.h"
#include "modules/skottie/include/ExternalLayer.h"
#include "modules/skottie/include/SkottieProperty.h"
#include "modules/skresources/include/SkResources.h"
#include <memory>
#include <vector>
class SkCanvas;
struct SkRect;
class SkStream;
namespace skjson { class ObjectValue; }
namespace sksg {
class InvalidationController;
class Scene;
} // namespace sksg
namespace skottie {
namespace internal { class Animator; }
using ImageAsset = skresources::ImageAsset;
using ResourceProvider = skresources::ResourceProvider;
/**
* A Logger subclass can be used to receive Animation::Builder parsing errors and warnings.
*/
class SK_API Logger : public SkRefCnt {
public:
enum class Level {
kWarning,
kError,
};
virtual void log(Level, const char message[], const char* json = nullptr);
};
// Evaluates AE expressions.
template <class T>
class SK_API ExpressionEvaluator : public SkRefCnt {
public:
// Evaluate the expression at the current time.
virtual T evaluate(float t) = 0;
};
/**
* Creates ExpressionEvaluators to evaluate AE expressions and return the results.
*/
class SK_API ExpressionManager : public SkRefCnt {
public:
virtual sk_sp<ExpressionEvaluator<float>> createNumberExpressionEvaluator(
const char expression[]) = 0;
virtual sk_sp<ExpressionEvaluator<SkString>> createStringExpressionEvaluator(
const char expression[]) = 0;
virtual sk_sp<ExpressionEvaluator<std::vector<float>>> createArrayExpressionEvaluator(
const char expression[]) = 0;
};
/**
* Interface for receiving AE composition markers at Animation build time.
*/
class SK_API MarkerObserver : public SkRefCnt {
public:
// t0,t1 are in the Animation::seek() domain.
virtual void onMarker(const char name[], float t0, float t1) = 0;
};
class SK_API Animation : public SkNVRefCnt<Animation> {
public:
class SK_API Builder final {
public:
enum Flags : uint32_t {
kDeferImageLoading = 0x01, // Normally, all static image frames are resolved at
// load time via ImageAsset::getFrame(0). With this flag,
// frames are only resolved when needed, at seek() time.
kPreferEmbeddedFonts = 0x02, // Attempt to use the embedded fonts (glyph paths,
// normally used as fallback) over native Skia typefaces.
};
explicit Builder(uint32_t flags = 0);
~Builder();
struct Stats {
float fTotalLoadTimeMS = 0, // Total animation instantiation time.
fJsonParseTimeMS = 0, // Time spent building a JSON DOM.
fSceneParseTimeMS = 0; // Time spent constructing the animation scene graph.
size_t fJsonSize = 0, // Input JSON size.
fAnimatorCount = 0; // Number of dynamically animated properties.
};
/**
* Returns various animation build stats.
*
* @return Stats (see above).
*/
const Stats& getStats() const { return fStats; }
/**
* Specify a loader for external resources (images, etc.).
*/
Builder& setResourceProvider(sk_sp<ResourceProvider>);
/**
* Specify a font manager for loading animation fonts.
*/
Builder& setFontManager(sk_sp<SkFontMgr>);
/**
* Specify a PropertyObserver to receive callbacks during parsing.
*
* See SkottieProperty.h for more details.
*
*/
Builder& setPropertyObserver(sk_sp<PropertyObserver>);
/**
* Register a Logger with this builder.
*/
Builder& setLogger(sk_sp<Logger>);
/**
* Register a MarkerObserver with this builder.
*/
Builder& setMarkerObserver(sk_sp<MarkerObserver>);
/**
* Register a precomp layer interceptor.
* This allows substituting precomp layers with custom/externally managed content.
*/
Builder& setPrecompInterceptor(sk_sp<PrecompInterceptor>);
/**
* Registers an ExpressionManager to evaluate AE expressions.
* If unspecified, expressions in the animation JSON will be ignored.
*/
Builder& setExpressionManager(sk_sp<ExpressionManager>);
/**
* Animation factories.
*/
sk_sp<Animation> make(SkStream*);
sk_sp<Animation> make(const char* data, size_t length);
sk_sp<Animation> makeFromFile(const char path[]);
private:
const uint32_t fFlags;
sk_sp<ResourceProvider> fResourceProvider;
sk_sp<SkFontMgr> fFontMgr;
sk_sp<PropertyObserver> fPropertyObserver;
sk_sp<Logger> fLogger;
sk_sp<MarkerObserver > fMarkerObserver;
sk_sp<PrecompInterceptor> fPrecompInterceptor;
sk_sp<ExpressionManager> fExpressionManager;
Stats fStats;
};
/**
* Animation factories.
*
* Use the Builder helper above for more options/control.
*/
static sk_sp<Animation> Make(const char* data, size_t length);
static sk_sp<Animation> Make(SkStream*);
static sk_sp<Animation> MakeFromFile(const char path[]);
~Animation();
enum RenderFlag : uint32_t {
// When rendering into a known transparent buffer, clients can pass
// this flag to avoid some unnecessary compositing overhead for
// animations using layer blend modes.
kSkipTopLevelIsolation = 0x01,
// By default, content is clipped to the intrinsic animation
// bounds (as determined by its size). If this flag is set,
// then the animation can draw outside of the bounds.
kDisableTopLevelClipping = 0x02,
};
using RenderFlags = uint32_t;
/**
* Draws the current animation frame.
*
* It is undefined behavior to call render() on a newly created Animation
* before specifying an initial frame via one of the seek() variants.
*
* @param canvas destination canvas
* @param dst optional destination rect
* @param flags optional RenderFlags
*/
void render(SkCanvas* canvas, const SkRect* dst = nullptr) const;
void render(SkCanvas* canvas, const SkRect* dst, RenderFlags) const;
/**
* [Deprecated: use one of the other versions.]
*
* Updates the animation state for |t|.
*
* @param t normalized [0..1] frame selector (0 -> first frame, 1 -> final frame)
* @param ic optional invalidation controller (dirty region tracking)
*
*/
void seek(SkScalar t, sksg::InvalidationController* ic = nullptr) {
this->seekFrameTime(t * this->duration(), ic);
}
/**
* Update the animation state to match |t|, specified as a frame index
* i.e. relative to duration() * fps().
*
* Fractional values are allowed and meaningful - e.g.
*
* 0.0 -> first frame
* 1.0 -> second frame
* 0.5 -> halfway between first and second frame
*/
void seekFrame(double t, sksg::InvalidationController* ic = nullptr);
/** Update the animation state to match t, specifed in frame time
* i.e. relative to duration().
*/
void seekFrameTime(double t, sksg::InvalidationController* = nullptr);
/**
* Returns the animation duration in seconds.
*/
double duration() const { return fDuration; }
/**
* Returns the animation frame rate (frames / second).
*/
double fps() const { return fFPS; }
/**
* Animation in point, in frame index units.
*/
double inPoint() const { return fInPoint; }
/**
* Animation out point, in frame index units.
*/
double outPoint() const { return fOutPoint; }
const SkString& version() const { return fVersion; }
const SkSize& size() const { return fSize; }
private:
enum Flags : uint32_t {
kRequiresTopLevelIsolation = 1 << 0, // Needs to draw into a layer due to layer blending.
};
Animation(std::unique_ptr<sksg::Scene>,
std::vector<sk_sp<internal::Animator>>&&,
SkString ver, const SkSize& size,
double inPoint, double outPoint, double duration, double fps, uint32_t flags);
const std::unique_ptr<sksg::Scene> fScene;
const std::vector<sk_sp<internal::Animator>> fAnimators;
const SkString fVersion;
const SkSize fSize;
const double fInPoint,
fOutPoint,
fDuration,
fFPS;
const uint32_t fFlags;
using INHERITED = SkNVRefCnt<Animation>;
};
} // namespace skottie
#endif // Skottie_DEFINED
| 3,830 |
5,169 | {
"name": "LocalizationKit",
"version": "1.1.8",
"summary": "iOS Localization made easy. Localize texts and manage your translations in realtime to support multi lingual deployment.",
"description": "LocalizationKit is the easiest way to manage your texts and translations. It removes the need to recompile and redeploy an app or website to support new languages and texts. It uses a combination of sockets and rest to allow you to manage an app without resubmitting to the app store to make linguistic changes. Localize your app in one easy to use location.",
"homepage": "https://github.com/willpowell8/LocalizationKit_iOS",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"<NAME>": ""
},
"source": {
"git": "https://github.com/willpowell8/LocalizationKit_iOS.git",
"tag": "1.1.8"
},
"social_media_url": "https://twitter.com/willpowelluk",
"platforms": {
"ios": "8.0",
"osx": "10.10"
},
"source_files": "LocalizationKit/Classes/**/*",
"dependencies": {
"Socket.IO-Client-Swift": [
"~>8.3.3"
]
},
"pushed_with_swift_version": "3.0"
}
| 394 |
14,668 | <gh_stars>1000+
// Copyright 2019 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_UI_VIEWS_AUTOFILL_PAYMENTS_SAVE_UPI_OFFER_BUBBLE_VIEWS_H_
#define CHROME_BROWSER_UI_VIEWS_AUTOFILL_PAYMENTS_SAVE_UPI_OFFER_BUBBLE_VIEWS_H_
#include "base/memory/raw_ptr.h"
#include "chrome/browser/ui/autofill/payments/save_upi_bubble.h"
#include "chrome/browser/ui/autofill/payments/save_upi_bubble_controller.h"
#include "chrome/browser/ui/views/location_bar/location_bar_bubble_delegate_view.h"
namespace content {
class WebContents;
}
// This class displays the "Remember your UPI ID?" bubble that is shown when the
// user submits a form with a UPI ID that Autofill
// has not previously saved. It includes the UPI ID that is being saved and a
// [Save] button. (Non-material UIs include a [No Thanks] button).
// UPI is a payments method
// https://en.wikipedia.org/wiki/Unified_Payments_Interface
class SaveUPIOfferBubbleViews : public autofill::SaveUPIBubble,
public LocationBarBubbleDelegateView {
public:
// The bubble will be anchored to |anchor_view|.
SaveUPIOfferBubbleViews(views::View* anchor_view,
content::WebContents* web_contents,
autofill::SaveUPIBubbleController* controller);
// Displays the bubble.
void Show();
private:
// views::View:
bool Accept() override;
// autofill::SaveUPIBubble:
void Hide() override;
// LocationBarBubbleDelegateView:
void Init() override;
~SaveUPIOfferBubbleViews() override;
raw_ptr<autofill::SaveUPIBubbleController> controller_;
};
#endif // CHROME_BROWSER_UI_VIEWS_AUTOFILL_PAYMENTS_SAVE_UPI_OFFER_BUBBLE_VIEWS_H_
| 683 |
474 | <reponame>BoneyIsSpooky/Javacord
package org.javacord.api.event.channel.server.voice;
import org.javacord.api.entity.channel.ServerVoiceChannel;
import org.javacord.api.event.user.UserEvent;
import java.util.Optional;
/**
* A server voice channel member join event.
*/
public interface ServerVoiceChannelMemberJoinEvent extends ServerVoiceChannelEvent, UserEvent {
/**
* Gets the old channel of the event.
*
* @return The old channel of the event.
*/
Optional<ServerVoiceChannel> getOldChannel();
/**
* Gets whether this event is part of a move.
*
* @return whether this event is part of a move.
*/
boolean isMove();
}
| 236 |
369 | /*
* Copyright © 2021 <NAME>, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.cdap.cdap.messaging.store.leveldb;
import org.iq80.leveldb.DB;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
/**
* One partition of a MessageTable, backed by a LevelDB table.
*/
public class LevelDBPartition implements Closeable {
private final File file;
private final long startTime;
private final long endTime;
private final Supplier levelDBSupplier;
private volatile DB levelDB;
public LevelDBPartition(File file, long startTime, long endTime, Supplier levelDBSupplier) {
this.file = file;
this.startTime = startTime;
this.endTime = endTime;
this.levelDBSupplier = levelDBSupplier;
}
public File getFile() {
return file;
}
public long getStartTime() {
return startTime;
}
public long getEndTime() {
return endTime;
}
public DB getLevelDB() throws IOException {
if (levelDB != null) {
return levelDB;
}
synchronized (this) {
if (levelDB == null) {
levelDB = levelDBSupplier.get();
}
}
return levelDB;
}
@Override
public void close() throws IOException {
if (levelDB != null) {
levelDB.close();
}
}
/**
* Supplies an opened LevelDB
*/
public interface Supplier {
DB get() throws IOException;
}
}
| 620 |
3,428 | <gh_stars>1000+
{"id":"01752","group":"easy-ham-1","checksum":{"type":"MD5","value":"a672617b99187e1c4029bc33a4e8a596"},"text":"Return-Path: <EMAIL>\nDelivery-Date: Wed Sep 11 08:10:29 2002\nFrom: <EMAIL> (<NAME>)\nDate: 11 Sep 2002 00:10:29 -0700\nSubject: [Spambayes] stack.pop() ate my multipart message\nIn-Reply-To: <<EMAIL>>\nReferences: <<EMAIL>>\nMessage-ID: <<EMAIL>>\n\nSo then, <NAME> <<EMAIL>> is all like:\n\n> Maybe there's some subtle interaction between generators and lists\n> that I can't understand. Or something. Being as I'm baffled, I don't\n> imagine any theory I come up with will be anywhere close to reality.\n\nAnd then, just as I was about to fall asleep, I figured it out. The\ntokenizer now has an extra [:], and all is well. I feel like a real\nchawbacon for not realizing this earlier. :*)\n\nBlaming it on staying up past bedtime,\n\nNeale\n"} | 306 |
1,133 | /*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 1996-2003
* Sleepycat Software. All rights reserved.
*/
#include "db_config.h"
#ifndef lint
static const char revid[] = "$Id: lock_util.c,v 11.9 2003/01/08 05:22:12 bostic Exp $";
#endif /* not lint */
#ifndef NO_SYSTEM_INCLUDES
#include <sys/types.h>
#include <string.h>
#endif
#include "db_int.h"
#include "dbinc/db_page.h"
#include "dbinc/db_shash.h"
#include "dbinc/hash.h"
#include "dbinc/lock.h"
#include <crc32c.h>
/*
* __lock_cmp --
* This function is used to compare a DBT that is about to be entered
* into a hash table with an object already in the hash table. Note
* that it just returns true on equal and 0 on not-equal. Therefore
* this function cannot be used as a sort function; its purpose is to
* be used as a hash comparison function.
*
* PUBLIC: int __lock_cmp __P((const DBT *, DB_LOCKOBJ *));
*/
int
__lock_cmp(dbt, lock_obj)
const DBT *dbt;
DB_LOCKOBJ *lock_obj;
{
void *obj_data = lock_obj->lockobj.data;
return (dbt->size == lock_obj->lockobj.size &&
memcmp(dbt->data, obj_data, dbt->size) == 0);
}
/*
* PUBLIC: int __lock_locker_cmp __P((u_int32_t, DB_LOCKER *));
*/
int
__lock_locker_cmp(locker, sh_locker)
u_int32_t locker;
DB_LOCKER *sh_locker;
{
return (locker == sh_locker->id);
}
/*
* The next two functions are the hash functions used to store objects in the
* lock hash tables. They are hashing the same items, but one (__lock_ohash)
* takes a DBT (used for hashing a parameter passed from the user) and the
* other (__lock_lhash) takes a DB_LOCKOBJ (used for hashing something that is
* already in the lock manager). In both cases, we have a special check to
* fast path the case where we think we are doing a hash on a DB page/fileid
* pair. If the size is right, then we do the fast hash.
*
* We know that DB uses DB_LOCK_ILOCK types for its lock objects. The first
* four bytes are the 4-byte page number and the next DB_FILE_ID_LEN bytes
* are a unique file id, where the first 4 bytes on UNIX systems are the file
* inode number, and the first 4 bytes on Windows systems are the FileIndexLow
* bytes. So, we use the XOR of the page number and the first four bytes of
* the file id to produce a 32-bit hash value.
*
* We have no particular reason to believe that this algorithm will produce
* a good hash, but we want a fast hash more than we want a good one, when
* we're coming through this code path.
*/
#define FAST_HASH(P) { \
u_int32_t __h; \
u_int8_t *__cp, *__hp; \
__hp = (u_int8_t *)&__h; \
__cp = (u_int8_t *)(P); \
__hp[0] = __cp[0] ^ __cp[4]; \
__hp[1] = __cp[1] ^ __cp[5]; \
__hp[2] = __cp[2] ^ __cp[6]; \
__hp[3] = __cp[3] ^ __cp[7]; \
return (__h); \
}
/*
* __lock_ohash --
*
* PUBLIC: u_int32_t __lock_ohash __P((const DBT *));
*/
u_int32_t
__lock_ohash(dbt)
const DBT *dbt;
{
if (dbt->size == sizeof(DB_LOCK_ILOCK))
FAST_HASH(dbt->data);
/* crc32c offers faster runtime compared to __ham_func5 which we were using
* but it does not seem to be faster than FAST_HASH() above */
return crc32c(dbt->data, dbt->size);
}
/*
* __lock_lhash --
*
* PUBLIC: u_int32_t __lock_lhash __P((DB_LOCKOBJ *));
*/
u_int32_t
__lock_lhash(lock_obj)
DB_LOCKOBJ *lock_obj;
{
void *obj_data = lock_obj->lockobj.data;
if (lock_obj->lockobj.size == sizeof(DB_LOCK_ILOCK))
FAST_HASH(obj_data);
return (__ham_func5(NULL, obj_data, lock_obj->lockobj.size));
}
/*
* __lock_locker_hash --
* Hash function for entering lockers into the locker hash table.
* Since these are simply 32-bit unsigned integers, just return
* the locker value.
*
* PUBLIC: u_int32_t __lock_locker_hash __P((u_int32_t));
*/
u_int32_t
__lock_locker_hash(locker)
u_int32_t locker;
{
return (locker);
}
| 1,461 |
1,522 | """Settings for testing zinnia on SQLite"""
from zinnia.tests.implementations.settings import * # noqa
DATABASES = {
'default': {
'NAME': 'zinnia.db',
'ENGINE': 'django.db.backends.sqlite3'
}
}
| 98 |
721 | <filename>generated/google-apis-books_v1/.repo-metadata.json
{
"api_id": "books:v1",
"name_pretty": "Books API",
"distribution_name": "google-apis-books_v1",
"language": "ruby",
"library_type": "REST"
}
| 98 |
460 | <reponame>kohkubo/norminette
int ((*g_conv[13])(t_syntax syntax, t_buffer *buffer, va_list va));
| 44 |
450 | <filename>gum/arch-x86/gumx86backtracer.h
/*
* Copyright (C) 2008-2018 <NAME> <<EMAIL>>
*
* Licence: wxWindows Library Licence, Version 3.1
*/
#ifndef __GUM_X86_BACKTRACER_H__
#define __GUM_X86_BACKTRACER_H__
#include <glib-object.h>
#include <gum/gumbacktracer.h>
G_BEGIN_DECLS
#define GUM_TYPE_X86_BACKTRACER (gum_x86_backtracer_get_type ())
G_DECLARE_FINAL_TYPE (GumX86Backtracer, gum_x86_backtracer, GUM, X86_BACKTRACER,
GObject)
GUM_API GumBacktracer * gum_x86_backtracer_new (void);
G_END_DECLS
#endif
| 246 |
1,264 | <filename>spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/SerializationUtils.java<gh_stars>1000+
/*
* Copyright 2012-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.mongodb.core.query;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import org.bson.Document;
import org.springframework.core.convert.converter.Converter;
import org.springframework.lang.Nullable;
import org.springframework.util.ObjectUtils;
/**
* Utility methods for JSON serialization.
*
* @author <NAME>
* @author <NAME>
* @author <NAME>
*/
public abstract class SerializationUtils {
private SerializationUtils() {
}
/**
* Flattens out a given {@link Document}.
*
* <pre>
* <code>
* {
* _id : 1
* nested : { value : "conflux"}
* }
* </code>
* will result in
* <code>
* {
* _id : 1
* nested.value : "conflux"
* }
* </code>
* </pre>
*
* @param source can be {@literal null}.
* @return {@link Collections#emptyMap()} when source is {@literal null}
* @since 1.8
*/
public static Map<String, Object> flattenMap(@Nullable Document source) {
if (source == null) {
return Collections.emptyMap();
}
Map<String, Object> result = new LinkedHashMap<>();
toFlatMap("", source, result);
return result;
}
private static void toFlatMap(String currentPath, Object source, Map<String, Object> map) {
if (source instanceof Document) {
Document document = (Document) source;
Iterator<Map.Entry<String, Object>> it = document.entrySet().iterator();
String pathPrefix = currentPath.isEmpty() ? "" : currentPath + '.';
while (it.hasNext()) {
Map.Entry<String, Object> entry = it.next();
if (entry.getKey().startsWith("$")) {
if (map.containsKey(currentPath)) {
((Document) map.get(currentPath)).put(entry.getKey(), entry.getValue());
} else {
map.put(currentPath, new Document(entry.getKey(), entry.getValue()));
}
} else {
toFlatMap(pathPrefix + entry.getKey(), entry.getValue(), map);
}
}
} else {
map.put(currentPath, source);
}
}
/**
* Serializes the given object into pseudo-JSON meaning it's trying to create a JSON representation as far as possible
* but falling back to the given object's {@link Object#toString()} method if it's not serializable. Useful for
* printing raw {@link Document}s containing complex values before actually converting them into Mongo native types.
*
* @param value
* @return the serialized value or {@literal null}.
*/
@Nullable
public static String serializeToJsonSafely(@Nullable Object value) {
if (value == null) {
return null;
}
try {
String json = value instanceof Document ? ((Document) value).toJson() : serializeValue(value);
return json.replaceAll("\":", "\" :").replaceAll("\\{\"", "{ \"");
} catch (Exception e) {
if (value instanceof Collection) {
return toString((Collection<?>) value);
} else if (value instanceof Map) {
return toString((Map<?, ?>) value);
} else if (ObjectUtils.isArray(value)) {
return toString(Arrays.asList(ObjectUtils.toObjectArray(value)));
} else {
return String.format("{ \"$java\" : %s }", value.toString());
}
}
}
public static String serializeValue(@Nullable Object value) {
if (value == null) {
return "null";
}
String documentJson = new Document("toBeEncoded", value).toJson();
return documentJson.substring(documentJson.indexOf(':') + 1, documentJson.length() - 1).trim();
}
private static String toString(Map<?, ?> source) {
return iterableToDelimitedString(source.entrySet(), "{ ", " }",
entry -> String.format("\"%s\" : %s", entry.getKey(), serializeToJsonSafely(entry.getValue())));
}
private static String toString(Collection<?> source) {
return iterableToDelimitedString(source, "[ ", " ]", SerializationUtils::serializeToJsonSafely);
}
/**
* Creates a string representation from the given {@link Iterable} prepending the postfix, applying the given
* {@link Converter} to each element before adding it to the result {@link String}, concatenating each element with
* {@literal ,} and applying the postfix.
*
* @param source
* @param prefix
* @param postfix
* @param transformer
* @return
*/
private static <T> String iterableToDelimitedString(Iterable<T> source, String prefix, String postfix,
Converter<? super T, Object> transformer) {
StringBuilder builder = new StringBuilder(prefix);
Iterator<T> iterator = source.iterator();
while (iterator.hasNext()) {
builder.append(transformer.convert(iterator.next()));
if (iterator.hasNext()) {
builder.append(", ");
}
}
return builder.append(postfix).toString();
}
}
| 1,818 |
524 | <reponame>broccoliboy/LedFx<filename>ledfx/api/schema.py
import logging
from aiohttp import web
from ledfx.api import RestEndpoint
from ledfx.api.utils import convertToJsonSchema
_LOGGER = logging.getLogger(__name__)
class SchemaEndpoint(RestEndpoint):
ENDPOINT_PATH = "/api/schema"
async def get(self) -> web.Response:
response = {
"devices": {},
"effects": {},
"integrations": {},
}
# Generate all the device schema
for (
device_type,
device,
) in self._ledfx.devices.classes().items():
response["devices"][device_type] = {
"schema": convertToJsonSchema(device.schema()),
"id": device_type,
}
# Generate all the effect schema
for (
effect_type,
effect,
) in self._ledfx.effects.classes().items():
response["effects"][effect_type] = {
"schema": convertToJsonSchema(effect.schema()),
"id": effect_type,
"name": effect.NAME,
}
# Generate all the integrations schema
for (
integration_type,
integration,
) in self._ledfx.integrations.classes().items():
response["integrations"][integration_type] = {
"schema": convertToJsonSchema(integration.schema()),
"id": integration_type,
"name": integration.NAME,
"description": integration.DESCRIPTION,
}
return web.json_response(data=response, status=200)
| 798 |
2,143 | <gh_stars>1000+
package com.tngtech.archunit.example.layers.service.impl;
import com.tngtech.archunit.example.layers.MyService;
@MyService
public class WronglyNamedSvc {
}
| 65 |
660 | /*
* Copyright (c) 2021, Intel Corporation
*
* 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.
*/
//!
//! \file media_interfaces_next.cpp
//! \brief Helps with gen-specific factory creation.
//!
#include "mhw_cp_interface.h"
#ifdef IGFX_MHW_INTERFACES_NEXT_SUPPORT
#include "media_interfaces_mhw_next.h"
#include "media_interfaces_hwinfo_device.h"
template class MediaFactory<uint32_t, MhwInterfacesNext>;
typedef MediaFactory<uint32_t, MhwInterfacesNext> MhwFactoryNext;
#endif
#ifdef IGFX_MHW_INTERFACES_NEXT_SUPPORT
MhwInterfacesNext* MhwInterfacesNext::CreateFactory(
CreateParams params,
PMOS_INTERFACE osInterface)
{
if (osInterface == nullptr)
{
return nullptr;
}
PLATFORM platform = {};
osInterface->pfnGetPlatform(osInterface, &platform);
MhwInterfacesNext *mhwNext = nullptr;
mhwNext = MhwFactoryNext::Create(platform.eProductFamily + MEDIA_EXT_FLAG);
if(mhwNext == nullptr)
{
mhwNext = MhwFactoryNext::Create(platform.eProductFamily);
}
if (mhwNext == nullptr)
{
MHW_ASSERTMESSAGE("Failed to create MediaInterface on the given platform!");
return nullptr;
}
if (mhwNext->Initialize(params, osInterface) != MOS_STATUS_SUCCESS)
{
MHW_ASSERTMESSAGE("MHW interfaces were not successfully allocated!");
MOS_Delete(mhwNext);
return nullptr;
}
return mhwNext;
}
void MhwInterfacesNext::Destroy()
{
if(m_isDestroyed)
{
return;
}
Delete_MhwCpInterface(m_cpInterface);
m_cpInterface = nullptr;
MOS_Delete(m_miInterface);
MOS_Delete(m_renderInterface);
MOS_Delete(m_sfcInterface);
MOS_Delete(m_stateHeapInterface);
MOS_Delete(m_veboxInterface);
MOS_Delete(m_mfxInterface);
MOS_Delete(m_hcpInterface);
MOS_Delete(m_hucInterface);
MOS_Delete(m_vdencInterface);
MOS_Delete(m_bltInterface);
}
#endif
| 1,057 |
370 | <reponame>luoyongheng/dtslam<filename>3rdparty/suitesparse-metis-for-windows-1.2.1/SuiteSparse/UMFPACK/SourceWrappers/umf_i_malloc.o.c<gh_stars>100-1000
#define DINT
#include <../Source/umf_malloc.c>
| 90 |
879 | <filename>header/src/main/java/org/zstack/header/tag/UserTagVO_.java
package org.zstack.header.tag;
/**
*/
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;
@StaticMetamodel(UserTagVO.class)
public class UserTagVO_ extends TagAO_ {
public static volatile SingularAttribute<UserTagVO_, String> tagPatternUuid;
}
| 134 |
1,338 | /*
* Copyright 2013, Haiku, Inc. All Rights Reserved.
* Distributed under the terms of the MIT License.
*
* Authors:
* <NAME> <<EMAIL>>
*/
#include <package/solver/SolverPackageSpecifier.h>
namespace BPackageKit {
BSolverPackageSpecifier::BSolverPackageSpecifier()
:
fType(B_UNSPECIFIED),
fPackage(NULL),
fSelectString()
{
}
BSolverPackageSpecifier::BSolverPackageSpecifier(BSolverPackage* package)
:
fType(B_PACKAGE),
fPackage(package),
fSelectString()
{
}
BSolverPackageSpecifier::BSolverPackageSpecifier(const BString& selectString)
:
fType(B_SELECT_STRING),
fPackage(NULL),
fSelectString(selectString)
{
}
BSolverPackageSpecifier::BSolverPackageSpecifier(
const BSolverPackageSpecifier& other)
:
fType(other.fType),
fPackage(other.fPackage),
fSelectString(other.fSelectString)
{
}
BSolverPackageSpecifier::~BSolverPackageSpecifier()
{
}
BSolverPackageSpecifier::BType
BSolverPackageSpecifier::Type() const
{
return fType;
}
BSolverPackage*
BSolverPackageSpecifier::Package() const
{
return fPackage;
}
const BString&
BSolverPackageSpecifier::SelectString() const
{
return fSelectString;
}
BSolverPackageSpecifier&
BSolverPackageSpecifier::operator=(const BSolverPackageSpecifier& other)
{
fType = other.fType;
fPackage = other.fPackage;
fSelectString = other.fSelectString;
return *this;
}
} // namespace BPackageKit
| 469 |
361 | """GDScript-to-python converter
Experimental converter which produces syntactically correct python3 out of given
GDScript. Produced python code almost for sure will not be runnable, although its
core structure should be the same as of GDScript thus allowing usage of various
python static analysis tools like e.g. radon.
Usage:
gd2py <path> [options]
Options:
-h --help Show this screen.
--version Show version.
Examples:
gd2py file.gd # produces python file on stdout
gd2py ./addons/gut/gut.gd | radon cc -s -
"""
import sys
import pkg_resources
from docopt import docopt
from . import convert_code
def main():
sys.stdout.reconfigure(encoding="utf-8")
arguments = docopt(
__doc__,
version="gd2py {}".format(pkg_resources.get_distribution("gdtoolkit").version),
)
with open(arguments["<path>"], "r") as fh:
print(convert_code(fh.read()))
| 353 |
942 | #include <mongoc.h>
#include "mongoc-scram-private.h"
#include "TestSuite.h"
#ifdef MONGOC_ENABLE_SSL
static void
test_mongoc_scram_step_username_not_set (void)
{
mongoc_scram_t scram;
bool success;
uint8_t buf[4096] = {0};
uint32_t buflen = 0;
bson_error_t error;
_mongoc_scram_init (&scram);
_mongoc_scram_set_pass (&scram, "password");
success = _mongoc_scram_step (
&scram, buf, buflen, buf, sizeof buf, &buflen, &error);
ASSERT (!success);
ASSERT_ERROR_CONTAINS (error,
MONGOC_ERROR_SCRAM,
MONGOC_ERROR_SCRAM_PROTOCOL_ERROR,
"SCRAM Failure: username is not set");
_mongoc_scram_destroy (&scram);
}
#endif
void
test_scram_install (TestSuite *suite)
{
#ifdef MONGOC_ENABLE_SSL
TestSuite_Add (suite,
"/scram/username_not_set",
test_mongoc_scram_step_username_not_set);
#endif
}
| 475 |
2,740 | # Copyright (c) 2017, Apple Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-3-clause license that can be
# found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
import unittest
import tempfile
import os
import pandas as pd
import random
import pytest
from coremltools.models.utils import (
evaluate_classifier,
evaluate_classifier_with_probabilities,
_macos_version,
_is_macos,
)
from coremltools._deps import (
_HAS_LIBSVM,
MSG_LIBSVM_NOT_FOUND,
_HAS_SKLEARN,
MSG_SKLEARN_NOT_FOUND,
)
if _HAS_LIBSVM:
from libsvm import svm, svmutil
from svmutil import svm_train, svm_predict
from libsvm import svmutil
from coremltools.converters import libsvm
if _HAS_SKLEARN:
from sklearn.svm import NuSVC
from sklearn.preprocessing import OneHotEncoder
from coremltools.converters import sklearn as scikit_converter
@unittest.skipIf(not _HAS_SKLEARN, MSG_SKLEARN_NOT_FOUND)
class NuSvcScikitTest(unittest.TestCase):
"""
Unit test class for testing scikit-learn converter.
"""
def _evaluation_test_helper(
self,
class_labels,
use_probability_estimates,
allow_slow,
allowed_prob_delta=0.00001,
):
# Parameters to test
kernel_parameters = [
{},
{"kernel": "rbf", "gamma": 1.2},
{"kernel": "linear"},
{"kernel": "poly"},
{"kernel": "poly", "degree": 2},
{"kernel": "poly", "gamma": 0.75},
{"kernel": "poly", "degree": 0, "gamma": 0.9, "coef0": 2},
{"kernel": "sigmoid"},
{"kernel": "sigmoid", "gamma": 1.3},
{"kernel": "sigmoid", "coef0": 0.8},
{"kernel": "sigmoid", "coef0": 0.8, "gamma": 0.5},
]
non_kernel_parameters = [
{},
{"nu": 0.75},
{"nu": 0.25, "shrinking": True},
{"shrinking": False},
]
# Generate some random data
x, y = [], []
random.seed(42)
for _ in range(50):
x.append(
[random.gauss(200, 30), random.gauss(-100, 22), random.gauss(100, 42)]
)
y.append(random.choice(class_labels))
column_names = ["x1", "x2", "x3"]
# make sure first label is seen first, second is seen second, and so on.
for i, val in enumerate(class_labels):
y[i] = val
df = pd.DataFrame(x, columns=column_names)
# Test
for param1 in non_kernel_parameters:
for param2 in kernel_parameters:
cur_params = param1.copy()
cur_params.update(param2)
cur_params["probability"] = use_probability_estimates
cur_params["max_iter"] = 10 # Don't want test to take too long
# print("cur_params=" + str(cur_params))
cur_model = NuSVC(**cur_params)
cur_model.fit(x, y)
spec = scikit_converter.convert(cur_model, column_names, "target")
if _is_macos() and _macos_version() >= (10, 13):
if use_probability_estimates:
probability_lists = cur_model.predict_proba(x)
df["classProbability"] = [
dict(zip(cur_model.classes_, cur_vals))
for cur_vals in probability_lists
]
metrics = evaluate_classifier_with_probabilities(
spec, df, probabilities="classProbability"
)
self.assertEqual(metrics["num_key_mismatch"], 0)
self.assertLess(
metrics["max_probability_error"], allowed_prob_delta
)
else:
df["prediction"] = cur_model.predict(x)
metrics = evaluate_classifier(spec, df, verbose=False)
self.assertEqual(metrics["num_errors"], 0)
if not allow_slow:
break
if not allow_slow:
break
@pytest.mark.slow
def test_binary_class_int_label_without_probability_stress_test(self):
self._evaluation_test_helper([1, 3], False, allow_slow=True)
def test_binary_class_int_label_without_probability(self):
self._evaluation_test_helper([1, 3], False, allow_slow=False)
@pytest.mark.slow
def test_binary_class_string_label_with_probability_stress_test(self):
# Scikit Learn uses technique to normalize pairwise probabilities even for binary classification.
# This leads to difference in probabilities.
self._evaluation_test_helper(
["foo", "bar"], True, allow_slow=True, allowed_prob_delta=0.005
)
def test_binary_class_string_label_with_probability(self):
# Scikit Learn uses technique to normalize pairwise probabilities even for binary classification.
# This leads to difference in probabilities.
self._evaluation_test_helper(
["foo", "bar"], True, allow_slow=False, allowed_prob_delta=0.005
)
@pytest.mark.slow
def test_multi_class_int_label_without_probability_stress_test(self):
self._evaluation_test_helper([12, 33, -1, 1234], False, allow_slow=True)
def test_multi_class_int_label_without_probability(self):
self._evaluation_test_helper([12, 33, -1, 1234], False, allow_slow=False)
@pytest.mark.slow
def test_multi_class_string_label_with_probability_stress_test(self):
self._evaluation_test_helper(["X", "Y", "z"], True, allow_slow=True)
def test_multi_class_string_label_with_probability(self):
self._evaluation_test_helper(["X", "Y", "z"], True, allow_slow=False)
def test_conversion_bad_inputs(self):
from sklearn.preprocessing import OneHotEncoder
# Error on converting an untrained model
with self.assertRaises(TypeError):
model = NuSVC()
spec = scikit_converter.convert(model, "data", "out")
# Check the expected class during conversion
with self.assertRaises(TypeError):
model = OneHotEncoder()
spec = scikit_converter.convert(model, "data", "out")
@unittest.skipIf(not _HAS_LIBSVM, MSG_LIBSVM_NOT_FOUND)
@unittest.skipIf(not _HAS_SKLEARN, MSG_SKLEARN_NOT_FOUND)
class NuSVCLibSVMTest(unittest.TestCase):
# Model parameters for testing
base_param = "-s 1 -q" # model type C-SVC and quiet mode
non_kernel_parameters = ["", "-n 0.6 -p 0.5 -h 1", "-c 0.5 -p 0.5 -h 0"]
kernel_parameters = [
"-t 0", # linear kernel
"",
"-t 2 -g 1.2", # rbf kernel
"-t 1",
"-t 1 -d 2",
"-t 1 -g 0.75",
"-t 1 -d 0 -g 0.9 -r 2", # poly kernel
"-t 3",
"-t 3 -g 1.3",
"-t 3 -r 0.8",
"-t 3 -r 0.8 -g 0.5", # sigmoid kernel
]
"""
Unit test class for testing the libsvm sklearn converter.
"""
@classmethod
def setUpClass(self):
"""
Set up the unit test by loading the dataset and training a model.
"""
if not _HAS_LIBSVM:
# setUpClass is still called even if class is skipped.
return
# Generate some random data.
# This unit test should not rely on scikit learn for test data.
self.x, self.y = [], []
random.seed(42)
for _ in range(50):
self.x.append([random.gauss(200, 30), random.gauss(-100, 22)])
self.y.append(random.choice([1, 2]))
self.y[0] = 1 # Make sure 1 is always the first label it sees
self.y[1] = 2
self.column_names = ["x1", "x2"]
self.prob = svmutil.svm_problem(self.y, self.x)
param = svmutil.svm_parameter()
param.svm_type = svmutil.NU_SVC
param.kernel_type = svmutil.LINEAR
param.eps = 1
param.probability = 1
# Save the data and the model
self.libsvm_model = svmutil.svm_train(self.prob, param)
self.df = pd.DataFrame(self.x, columns=self.column_names)
def _test_prob_model(self, param1, param2):
probability_param = "-b 1"
df = self.df
param_str = " ".join([self.base_param, param1, param2, probability_param])
param = svmutil.svm_parameter(param_str)
model = svm_train(self.prob, param)
# Get predictions with probabilities as dictionaries
(df["prediction"], _, probability_lists) = svm_predict(
self.y, self.x, model, probability_param + " -q"
)
probability_dicts = [
dict(zip([1, 2], cur_vals)) for cur_vals in probability_lists
]
df["probabilities"] = probability_dicts
spec = libsvm.convert(model, self.column_names, "target", "probabilities")
if _is_macos() and _macos_version() >= (10, 13):
metrics = evaluate_classifier_with_probabilities(spec, df, verbose=False)
self.assertEqual(metrics["num_key_mismatch"], 0)
self.assertLess(metrics["max_probability_error"], 0.00001)
@pytest.mark.slow
def test_binary_classificaiton_with_probability_stress_test(self):
for param1 in self.non_kernel_parameters:
for param2 in self.kernel_parameters:
self._test_prob_model(param1, param2)
def test_binary_classificaiton_with_probability(self):
param1 = self.non_kernel_parameters[0]
param2 = self.kernel_parameters[0]
self._test_prob_model(param1, param2)
@pytest.mark.slow
@unittest.skip(
"LibSVM's Python library is broken for NuSVC without probabilities. It always segfaults during prediction time."
)
def test_multi_class_without_probability(self):
# Generate some random data.
# This unit test should not rely on scikit learn for test data.
x, y = [], []
for _ in range(50):
x.append(
[random.gauss(200, 30), random.gauss(-100, 22), random.gauss(100, 42)]
)
y.append(random.choice([1, 2, 10, 12]))
y[0], y[1], y[2], y[3] = 1, 2, 10, 12
column_names = ["x1", "x2", "x3"]
prob = svmutil.svm_problem(y, x)
df = pd.DataFrame(x, columns=column_names)
for param1 in self.non_kernel_parameters:
for param2 in self.kernel_parameters:
param_str = " ".join([self.base_param, param1, param2])
param = svmutil.svm_parameter(param_str)
model = svm_train(prob, param)
# Get predictions with probabilities as dictionaries
(df["prediction"], _, _) = svm_predict(y, x, model, " -q")
spec = libsvm.convert(model, column_names, "target")
metrics = evaluate_classifier(spec, df, verbose=False)
self.assertEqual(metrics["num_errors"], 0)
def test_conversion_from_filesystem(self):
libsvm_model_path = tempfile.mktemp(suffix="model.libsvm")
svmutil.svm_save_model(libsvm_model_path, self.libsvm_model)
spec = libsvm.convert(libsvm_model_path, "data", "target")
def test_conversion_bad_inputs(self):
# Check the expected class during covnersion.
with self.assertRaises(TypeError):
model = OneHotEncoder()
spec = libsvm.convert(model, "data", "out")
| 5,506 |
463 | <gh_stars>100-1000
package org.hive2hive.core.processes.share;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Random;
import org.hive2hive.core.H2HJUnitTest;
import org.hive2hive.core.events.framework.interfaces.file.IFileAddEvent;
import org.hive2hive.core.events.framework.interfaces.file.IFileShareEvent;
import org.hive2hive.core.exceptions.GetFailedException;
import org.hive2hive.core.exceptions.NoPeerConnectionException;
import org.hive2hive.core.exceptions.NoSessionException;
import org.hive2hive.core.model.PermissionType;
import org.hive2hive.core.network.NetworkManager;
import org.hive2hive.core.security.UserCredentials;
import org.hive2hive.core.utils.FileTestUtil;
import org.hive2hive.core.utils.H2HWaiter;
import org.hive2hive.core.utils.NetworkTestUtil;
import org.hive2hive.core.utils.TestFileEventListener;
import org.hive2hive.core.utils.UseCaseTestUtil;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* Test the share function. A folder can be shared among multiple users.
*
* @author <NAME>
*/
public class ShareFolderTest extends H2HJUnitTest {
private static List<NetworkManager> network;
private static File rootA;
private static File rootB;
private static UserCredentials userA;
private static UserCredentials userB;
private static TestFileEventListener eventB;
/**
* Setup two users with each one client, log them in
*
* @throws NoPeerConnectionException
*/
@BeforeClass
public static void initTest() throws Exception {
testClass = ShareFolderTest.class;
beforeClass();
network = NetworkTestUtil.createNetwork(Math.max(DEFAULT_NETWORK_SIZE, 3));
rootA = tempFolder.newFolder();
userA = generateRandomCredentials("userA");
UseCaseTestUtil.registerAndLogin(userA, network.get(0), rootA);
rootB = tempFolder.newFolder();
userB = generateRandomCredentials("userB");
UseCaseTestUtil.registerAndLogin(userB, network.get(1), rootB);
eventB = new TestFileEventListener();
network.get(1).getEventBus().subscribe(eventB);
}
@Test
public void shareFilledFolderTest() throws IOException, IllegalArgumentException, NoSessionException,
GetFailedException, InterruptedException, NoPeerConnectionException {
// upload an empty folder
File folderToShare = new File(rootA, "sharedFolder");
folderToShare.mkdirs();
UseCaseTestUtil.uploadNewFile(network.get(0), folderToShare);
File file1 = FileTestUtil.createFileRandomContent("file1", new Random().nextInt(5) + 1, folderToShare);
UseCaseTestUtil.uploadNewFile(network.get(0), file1);
File file2 = FileTestUtil.createFileRandomContent("file2", new Random().nextInt(5) + 1, folderToShare);
UseCaseTestUtil.uploadNewFile(network.get(0), file2);
File subfolder = new File(folderToShare, "subfolder1");
subfolder.mkdir();
UseCaseTestUtil.uploadNewFile(network.get(0), subfolder);
File file3 = FileTestUtil.createFileRandomContent("file3", new Random().nextInt(5) + 1, subfolder);
UseCaseTestUtil.uploadNewFile(network.get(0), file3);
// share the filled folder
UseCaseTestUtil.shareFolder(network.get(0), folderToShare, userB.getUserId(), PermissionType.WRITE);
// check the events at user B
File sharedFolderAtB = new File(rootB, folderToShare.getName());
IFileShareEvent shared = waitTillShared(eventB, sharedFolderAtB);
Assert.assertEquals(userA.getUserId(), shared.getInvitedBy());
Assert.assertEquals(PermissionType.WRITE, shared.getUserPermission(userB.getUserId()).getPermission());
Assert.assertEquals(2, shared.getUserPermissions().size());
IFileAddEvent added = waitTillAdded(eventB, sharedFolderAtB);
Assert.assertTrue(added.isFolder());
File file1AtB = new File(sharedFolderAtB, file1.getName());
added = waitTillAdded(eventB, file1AtB);
Assert.assertTrue(added.isFile());
File file2AtB = new File(sharedFolderAtB, file2.getName());
added = waitTillAdded(eventB, file2AtB);
Assert.assertTrue(added.isFile());
File subfolderAtB = new File(sharedFolderAtB, subfolder.getName());
added = waitTillAdded(eventB, subfolderAtB);
Assert.assertTrue(added.isFolder());
File file3AtB = new File(subfolderAtB, file3.getName());
added = waitTillAdded(eventB, file3AtB);
Assert.assertTrue(added.isFile());
}
@Test
public void shareEmptyFolder() throws IOException, IllegalArgumentException, NoSessionException, GetFailedException,
InterruptedException, NoPeerConnectionException {
// upload an empty folder
File sharedFolderAtA = new File(rootA, randomString());
sharedFolderAtA.mkdirs();
UseCaseTestUtil.uploadNewFile(network.get(0), sharedFolderAtA);
// share the empty folder
UseCaseTestUtil.shareFolder(network.get(0), sharedFolderAtA, userB.getUserId(), PermissionType.WRITE);
// wait for userB to process the user profile task
File sharedFolderAtB = new File(rootB, sharedFolderAtA.getName());
IFileShareEvent shared = waitTillShared(eventB, sharedFolderAtB);
Assert.assertEquals(userA.getUserId(), shared.getInvitedBy());
Assert.assertEquals(PermissionType.WRITE, shared.getUserPermission(userB.getUserId()).getPermission());
Assert.assertEquals(2, shared.getUserPermissions().size());
IFileAddEvent added = waitTillAdded(eventB, sharedFolderAtB);
Assert.assertTrue(added.isFolder());
}
@Test
public void shareThreeUsers() throws IOException, IllegalArgumentException, NoSessionException, GetFailedException,
InterruptedException, NoPeerConnectionException {
File rootC = tempFolder.newFolder();
UserCredentials userC = generateRandomCredentials("userC");
UseCaseTestUtil.registerAndLogin(userC, network.get(2), rootC);
TestFileEventListener eventC = new TestFileEventListener();
network.get(2).getEventBus().subscribe(eventC);
// upload an empty folder
File sharedFolderAtA = new File(rootA, randomString());
sharedFolderAtA.mkdirs();
UseCaseTestUtil.uploadNewFile(network.get(0), sharedFolderAtA);
// share the empty folder with B and C
UseCaseTestUtil.shareFolder(network.get(0), sharedFolderAtA, userB.getUserId(), PermissionType.WRITE);
UseCaseTestUtil.shareFolder(network.get(0), sharedFolderAtA, userC.getUserId(), PermissionType.WRITE);
// wait for userB to process the user profile task
File sharedFolderAtB = new File(rootB, sharedFolderAtA.getName());
IFileShareEvent sharedB = waitTillShared(eventB, sharedFolderAtB);
Assert.assertEquals(userA.getUserId(), sharedB.getInvitedBy());
Assert.assertEquals(PermissionType.WRITE, sharedB.getUserPermission(userA.getUserId()).getPermission());
Assert.assertEquals(PermissionType.WRITE, sharedB.getUserPermission(userB.getUserId()).getPermission());
Assert.assertEquals(PermissionType.WRITE, sharedB.getUserPermission(userC.getUserId()).getPermission());
Assert.assertEquals(3, sharedB.getUserPermissions().size());
// wait for userB to process the user profile task
File sharedFolderAtC = new File(rootC, sharedFolderAtA.getName());
IFileShareEvent sharedC = waitTillShared(eventC, sharedFolderAtC);
Assert.assertEquals(userA.getUserId(), sharedC.getInvitedBy());
Assert.assertEquals(PermissionType.WRITE, sharedC.getUserPermission(userA.getUserId()).getPermission());
Assert.assertEquals(PermissionType.WRITE, sharedC.getUserPermission(userB.getUserId()).getPermission());
Assert.assertEquals(PermissionType.WRITE, sharedC.getUserPermission(userC.getUserId()).getPermission());
Assert.assertEquals(3, sharedC.getUserPermissions().size());
}
private static IFileShareEvent waitTillShared(TestFileEventListener events, File sharedFolder) {
H2HWaiter waiter = new H2HWaiter(30);
do {
waiter.tickASecond();
} while (events.getShared(sharedFolder) == null);
return events.getShared(sharedFolder);
}
private static IFileAddEvent waitTillAdded(TestFileEventListener events, File addedFile) {
H2HWaiter waiter = new H2HWaiter(30);
do {
waiter.tickASecond();
} while (events.getAdded(addedFile) == null);
return events.getAdded(addedFile);
}
@AfterClass
public static void endTest() throws IOException {
NetworkTestUtil.shutdownNetwork(network);
afterClass();
}
}
| 2,772 |
1,279 | <reponame>huanjiayang-ibm/serverless-application-model
from parameterized import parameterized
from integration.helpers.base_test import BaseTest
class TestFunctionWithMq(BaseTest):
@parameterized.expand(
[
"combination/function_with_mq",
"combination/function_with_mq_using_autogen_role",
]
)
def test_function_with_mq(self, file_name):
self.create_and_verify_stack(file_name)
mq_client = self.client_provider.mq_client
mq_broker_id = self.get_physical_id_by_type("AWS::AmazonMQ::Broker")
broker_summary = get_broker_summary(mq_broker_id, mq_client)
self.assertEqual(len(broker_summary), 1, "One MQ cluster should be present")
mq_broker_arn = broker_summary[0]["BrokerArn"]
lambda_client = self.client_provider.lambda_client
function_name = self.get_physical_id_by_type("AWS::Lambda::Function")
lambda_function_arn = lambda_client.get_function_configuration(FunctionName=function_name)["FunctionArn"]
event_source_mapping_id = self.get_physical_id_by_type("AWS::Lambda::EventSourceMapping")
event_source_mapping_result = lambda_client.get_event_source_mapping(UUID=event_source_mapping_id)
event_source_mapping_function_arn = event_source_mapping_result["FunctionArn"]
event_source_mapping_mq_broker_arn = event_source_mapping_result["EventSourceArn"]
self.assertEqual(event_source_mapping_function_arn, lambda_function_arn)
self.assertEqual(event_source_mapping_mq_broker_arn, mq_broker_arn)
def get_broker_summary(mq_broker_id, mq_client):
broker_summaries = mq_client.list_brokers()["BrokerSummaries"]
return [broker_summary for broker_summary in broker_summaries if broker_summary["BrokerId"] == mq_broker_id]
| 738 |
407 | <gh_stars>100-1000
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: CellSetMessage.proto
package org.apache.hadoop.hbase.rest.protobuf.generated;
public final class CellSetMessage {
private CellSetMessage() {}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistry registry) {
}
public interface CellSetOrBuilder
extends com.google.protobuf.MessageOrBuilder {
// repeated .org.apache.hadoop.hbase.rest.protobuf.generated.CellSet.Row rows = 1;
java.util.List<org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row>
getRowsList();
org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row getRows(int index);
int getRowsCount();
java.util.List<? extends org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.RowOrBuilder>
getRowsOrBuilderList();
org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.RowOrBuilder getRowsOrBuilder(
int index);
}
public static final class CellSet extends
com.google.protobuf.GeneratedMessage
implements CellSetOrBuilder {
// Use CellSet.newBuilder() to construct.
private CellSet(Builder builder) {
super(builder);
}
private CellSet(boolean noInit) {}
private static final CellSet defaultInstance;
public static CellSet getDefaultInstance() {
return defaultInstance;
}
public CellSet getDefaultInstanceForType() {
return defaultInstance;
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.internal_static_org_apache_hadoop_hbase_rest_protobuf_generated_CellSet_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.internal_static_org_apache_hadoop_hbase_rest_protobuf_generated_CellSet_fieldAccessorTable;
}
public interface RowOrBuilder
extends com.google.protobuf.MessageOrBuilder {
// required bytes key = 1;
boolean hasKey();
com.google.protobuf.ByteString getKey();
// repeated .org.apache.hadoop.hbase.rest.protobuf.generated.Cell values = 2;
java.util.List<org.apache.hadoop.hbase.rest.protobuf.generated.CellMessage.Cell>
getValuesList();
org.apache.hadoop.hbase.rest.protobuf.generated.CellMessage.Cell getValues(int index);
int getValuesCount();
java.util.List<? extends org.apache.hadoop.hbase.rest.protobuf.generated.CellMessage.CellOrBuilder>
getValuesOrBuilderList();
org.apache.hadoop.hbase.rest.protobuf.generated.CellMessage.CellOrBuilder getValuesOrBuilder(
int index);
}
public static final class Row extends
com.google.protobuf.GeneratedMessage
implements RowOrBuilder {
// Use Row.newBuilder() to construct.
private Row(Builder builder) {
super(builder);
}
private Row(boolean noInit) {}
private static final Row defaultInstance;
public static Row getDefaultInstance() {
return defaultInstance;
}
public Row getDefaultInstanceForType() {
return defaultInstance;
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.internal_static_org_apache_hadoop_hbase_rest_protobuf_generated_CellSet_Row_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.internal_static_org_apache_hadoop_hbase_rest_protobuf_generated_CellSet_Row_fieldAccessorTable;
}
private int bitField0_;
// required bytes key = 1;
public static final int KEY_FIELD_NUMBER = 1;
private com.google.protobuf.ByteString key_;
public boolean hasKey() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
public com.google.protobuf.ByteString getKey() {
return key_;
}
// repeated .org.apache.hadoop.hbase.rest.protobuf.generated.Cell values = 2;
public static final int VALUES_FIELD_NUMBER = 2;
private java.util.List<org.apache.hadoop.hbase.rest.protobuf.generated.CellMessage.Cell> values_;
public java.util.List<org.apache.hadoop.hbase.rest.protobuf.generated.CellMessage.Cell> getValuesList() {
return values_;
}
public java.util.List<? extends org.apache.hadoop.hbase.rest.protobuf.generated.CellMessage.CellOrBuilder>
getValuesOrBuilderList() {
return values_;
}
public int getValuesCount() {
return values_.size();
}
public org.apache.hadoop.hbase.rest.protobuf.generated.CellMessage.Cell getValues(int index) {
return values_.get(index);
}
public org.apache.hadoop.hbase.rest.protobuf.generated.CellMessage.CellOrBuilder getValuesOrBuilder(
int index) {
return values_.get(index);
}
private void initFields() {
key_ = com.google.protobuf.ByteString.EMPTY;
values_ = java.util.Collections.emptyList();
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized != -1) return isInitialized == 1;
if (!hasKey()) {
memoizedIsInitialized = 0;
return false;
}
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
getSerializedSize();
if (((bitField0_ & 0x00000001) == 0x00000001)) {
output.writeBytes(1, key_);
}
for (int i = 0; i < values_.size(); i++) {
output.writeMessage(2, values_.get(i));
}
getUnknownFields().writeTo(output);
}
private int memoizedSerializedSize = -1;
public int getSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) == 0x00000001)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(1, key_);
}
for (int i = 0; i < values_.size(); i++) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(2, values_.get(i));
}
size += getUnknownFields().getSerializedSize();
memoizedSerializedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
protected java.lang.Object writeReplace()
throws java.io.ObjectStreamException {
return super.writeReplace();
}
public static org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return newBuilder().mergeFrom(data).buildParsed();
}
public static org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return newBuilder().mergeFrom(data, extensionRegistry)
.buildParsed();
}
public static org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return newBuilder().mergeFrom(data).buildParsed();
}
public static org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return newBuilder().mergeFrom(data, extensionRegistry)
.buildParsed();
}
public static org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row parseFrom(java.io.InputStream input)
throws java.io.IOException {
return newBuilder().mergeFrom(input).buildParsed();
}
public static org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return newBuilder().mergeFrom(input, extensionRegistry)
.buildParsed();
}
public static org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
Builder builder = newBuilder();
if (builder.mergeDelimitedFrom(input)) {
return builder.buildParsed();
} else {
return null;
}
}
public static org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
Builder builder = newBuilder();
if (builder.mergeDelimitedFrom(input, extensionRegistry)) {
return builder.buildParsed();
} else {
return null;
}
}
public static org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return newBuilder().mergeFrom(input).buildParsed();
}
public static org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return newBuilder().mergeFrom(input, extensionRegistry)
.buildParsed();
}
public static Builder newBuilder() { return Builder.create(); }
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder(org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row prototype) {
return newBuilder().mergeFrom(prototype);
}
public Builder toBuilder() { return newBuilder(this); }
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
public static final class Builder extends
com.google.protobuf.GeneratedMessage.Builder<Builder>
implements org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.RowOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.internal_static_org_apache_hadoop_hbase_rest_protobuf_generated_CellSet_Row_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.internal_static_org_apache_hadoop_hbase_rest_protobuf_generated_CellSet_Row_fieldAccessorTable;
}
// Construct using org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
getValuesFieldBuilder();
}
}
private static Builder create() {
return new Builder();
}
public Builder clear() {
super.clear();
key_ = com.google.protobuf.ByteString.EMPTY;
bitField0_ = (bitField0_ & ~0x00000001);
if (valuesBuilder_ == null) {
values_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000002);
} else {
valuesBuilder_.clear();
}
return this;
}
public Builder clone() {
return create().mergeFrom(buildPartial());
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row.getDescriptor();
}
public org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row getDefaultInstanceForType() {
return org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row.getDefaultInstance();
}
public org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row build() {
org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
private org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row buildParsed()
throws com.google.protobuf.InvalidProtocolBufferException {
org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(
result).asInvalidProtocolBufferException();
}
return result;
}
public org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row buildPartial() {
org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row result = new org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
to_bitField0_ |= 0x00000001;
}
result.key_ = key_;
if (valuesBuilder_ == null) {
if (((bitField0_ & 0x00000002) == 0x00000002)) {
values_ = java.util.Collections.unmodifiableList(values_);
bitField0_ = (bitField0_ & ~0x00000002);
}
result.values_ = values_;
} else {
result.values_ = valuesBuilder_.build();
}
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row) {
return mergeFrom((org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row other) {
if (other == org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row.getDefaultInstance()) return this;
if (other.hasKey()) {
setKey(other.getKey());
}
if (valuesBuilder_ == null) {
if (!other.values_.isEmpty()) {
if (values_.isEmpty()) {
values_ = other.values_;
bitField0_ = (bitField0_ & ~0x00000002);
} else {
ensureValuesIsMutable();
values_.addAll(other.values_);
}
onChanged();
}
} else {
if (!other.values_.isEmpty()) {
if (valuesBuilder_.isEmpty()) {
valuesBuilder_.dispose();
valuesBuilder_ = null;
values_ = other.values_;
bitField0_ = (bitField0_ & ~0x00000002);
valuesBuilder_ =
com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ?
getValuesFieldBuilder() : null;
} else {
valuesBuilder_.addAllMessages(other.values_);
}
}
}
this.mergeUnknownFields(other.getUnknownFields());
return this;
}
public final boolean isInitialized() {
if (!hasKey()) {
return false;
}
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder(
this.getUnknownFields());
while (true) {
int tag = input.readTag();
switch (tag) {
case 0:
this.setUnknownFields(unknownFields.build());
onChanged();
return this;
default: {
if (!parseUnknownField(input, unknownFields,
extensionRegistry, tag)) {
this.setUnknownFields(unknownFields.build());
onChanged();
return this;
}
break;
}
case 10: {
bitField0_ |= 0x00000001;
key_ = input.readBytes();
break;
}
case 18: {
org.apache.hadoop.hbase.rest.protobuf.generated.CellMessage.Cell.Builder subBuilder = org.apache.hadoop.hbase.rest.protobuf.generated.CellMessage.Cell.newBuilder();
input.readMessage(subBuilder, extensionRegistry);
addValues(subBuilder.buildPartial());
break;
}
}
}
}
private int bitField0_;
// required bytes key = 1;
private com.google.protobuf.ByteString key_ = com.google.protobuf.ByteString.EMPTY;
public boolean hasKey() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
public com.google.protobuf.ByteString getKey() {
return key_;
}
public Builder setKey(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000001;
key_ = value;
onChanged();
return this;
}
public Builder clearKey() {
bitField0_ = (bitField0_ & ~0x00000001);
key_ = getDefaultInstance().getKey();
onChanged();
return this;
}
// repeated .org.apache.hadoop.hbase.rest.protobuf.generated.Cell values = 2;
private java.util.List<org.apache.hadoop.hbase.rest.protobuf.generated.CellMessage.Cell> values_ =
java.util.Collections.emptyList();
private void ensureValuesIsMutable() {
if (!((bitField0_ & 0x00000002) == 0x00000002)) {
values_ = new java.util.ArrayList<org.apache.hadoop.hbase.rest.protobuf.generated.CellMessage.Cell>(values_);
bitField0_ |= 0x00000002;
}
}
private com.google.protobuf.RepeatedFieldBuilder<
org.apache.hadoop.hbase.rest.protobuf.generated.CellMessage.Cell, org.apache.hadoop.hbase.rest.protobuf.generated.CellMessage.Cell.Builder, org.apache.hadoop.hbase.rest.protobuf.generated.CellMessage.CellOrBuilder> valuesBuilder_;
public java.util.List<org.apache.hadoop.hbase.rest.protobuf.generated.CellMessage.Cell> getValuesList() {
if (valuesBuilder_ == null) {
return java.util.Collections.unmodifiableList(values_);
} else {
return valuesBuilder_.getMessageList();
}
}
public int getValuesCount() {
if (valuesBuilder_ == null) {
return values_.size();
} else {
return valuesBuilder_.getCount();
}
}
public org.apache.hadoop.hbase.rest.protobuf.generated.CellMessage.Cell getValues(int index) {
if (valuesBuilder_ == null) {
return values_.get(index);
} else {
return valuesBuilder_.getMessage(index);
}
}
public Builder setValues(
int index, org.apache.hadoop.hbase.rest.protobuf.generated.CellMessage.Cell value) {
if (valuesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureValuesIsMutable();
values_.set(index, value);
onChanged();
} else {
valuesBuilder_.setMessage(index, value);
}
return this;
}
public Builder setValues(
int index, org.apache.hadoop.hbase.rest.protobuf.generated.CellMessage.Cell.Builder builderForValue) {
if (valuesBuilder_ == null) {
ensureValuesIsMutable();
values_.set(index, builderForValue.build());
onChanged();
} else {
valuesBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
public Builder addValues(org.apache.hadoop.hbase.rest.protobuf.generated.CellMessage.Cell value) {
if (valuesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureValuesIsMutable();
values_.add(value);
onChanged();
} else {
valuesBuilder_.addMessage(value);
}
return this;
}
public Builder addValues(
int index, org.apache.hadoop.hbase.rest.protobuf.generated.CellMessage.Cell value) {
if (valuesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureValuesIsMutable();
values_.add(index, value);
onChanged();
} else {
valuesBuilder_.addMessage(index, value);
}
return this;
}
public Builder addValues(
org.apache.hadoop.hbase.rest.protobuf.generated.CellMessage.Cell.Builder builderForValue) {
if (valuesBuilder_ == null) {
ensureValuesIsMutable();
values_.add(builderForValue.build());
onChanged();
} else {
valuesBuilder_.addMessage(builderForValue.build());
}
return this;
}
public Builder addValues(
int index, org.apache.hadoop.hbase.rest.protobuf.generated.CellMessage.Cell.Builder builderForValue) {
if (valuesBuilder_ == null) {
ensureValuesIsMutable();
values_.add(index, builderForValue.build());
onChanged();
} else {
valuesBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
public Builder addAllValues(
java.lang.Iterable<? extends org.apache.hadoop.hbase.rest.protobuf.generated.CellMessage.Cell> values) {
if (valuesBuilder_ == null) {
ensureValuesIsMutable();
super.addAll(values, values_);
onChanged();
} else {
valuesBuilder_.addAllMessages(values);
}
return this;
}
public Builder clearValues() {
if (valuesBuilder_ == null) {
values_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
} else {
valuesBuilder_.clear();
}
return this;
}
public Builder removeValues(int index) {
if (valuesBuilder_ == null) {
ensureValuesIsMutable();
values_.remove(index);
onChanged();
} else {
valuesBuilder_.remove(index);
}
return this;
}
public org.apache.hadoop.hbase.rest.protobuf.generated.CellMessage.Cell.Builder getValuesBuilder(
int index) {
return getValuesFieldBuilder().getBuilder(index);
}
public org.apache.hadoop.hbase.rest.protobuf.generated.CellMessage.CellOrBuilder getValuesOrBuilder(
int index) {
if (valuesBuilder_ == null) {
return values_.get(index); } else {
return valuesBuilder_.getMessageOrBuilder(index);
}
}
public java.util.List<? extends org.apache.hadoop.hbase.rest.protobuf.generated.CellMessage.CellOrBuilder>
getValuesOrBuilderList() {
if (valuesBuilder_ != null) {
return valuesBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(values_);
}
}
public org.apache.hadoop.hbase.rest.protobuf.generated.CellMessage.Cell.Builder addValuesBuilder() {
return getValuesFieldBuilder().addBuilder(
org.apache.hadoop.hbase.rest.protobuf.generated.CellMessage.Cell.getDefaultInstance());
}
public org.apache.hadoop.hbase.rest.protobuf.generated.CellMessage.Cell.Builder addValuesBuilder(
int index) {
return getValuesFieldBuilder().addBuilder(
index, org.apache.hadoop.hbase.rest.protobuf.generated.CellMessage.Cell.getDefaultInstance());
}
public java.util.List<org.apache.hadoop.hbase.rest.protobuf.generated.CellMessage.Cell.Builder>
getValuesBuilderList() {
return getValuesFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilder<
org.apache.hadoop.hbase.rest.protobuf.generated.CellMessage.Cell, org.apache.hadoop.hbase.rest.protobuf.generated.CellMessage.Cell.Builder, org.apache.hadoop.hbase.rest.protobuf.generated.CellMessage.CellOrBuilder>
getValuesFieldBuilder() {
if (valuesBuilder_ == null) {
valuesBuilder_ = new com.google.protobuf.RepeatedFieldBuilder<
org.apache.hadoop.hbase.rest.protobuf.generated.CellMessage.Cell, org.apache.hadoop.hbase.rest.protobuf.generated.CellMessage.Cell.Builder, org.apache.hadoop.hbase.rest.protobuf.generated.CellMessage.CellOrBuilder>(
values_,
((bitField0_ & 0x00000002) == 0x00000002),
getParentForChildren(),
isClean());
values_ = null;
}
return valuesBuilder_;
}
// @@protoc_insertion_point(builder_scope:org.apache.hadoop.hbase.rest.protobuf.generated.CellSet.Row)
}
static {
defaultInstance = new Row(true);
defaultInstance.initFields();
}
// @@protoc_insertion_point(class_scope:org.apache.hadoop.hbase.rest.protobuf.generated.CellSet.Row)
}
// repeated .org.apache.hadoop.hbase.rest.protobuf.generated.CellSet.Row rows = 1;
public static final int ROWS_FIELD_NUMBER = 1;
private java.util.List<org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row> rows_;
public java.util.List<org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row> getRowsList() {
return rows_;
}
public java.util.List<? extends org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.RowOrBuilder>
getRowsOrBuilderList() {
return rows_;
}
public int getRowsCount() {
return rows_.size();
}
public org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row getRows(int index) {
return rows_.get(index);
}
public org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.RowOrBuilder getRowsOrBuilder(
int index) {
return rows_.get(index);
}
private void initFields() {
rows_ = java.util.Collections.emptyList();
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized != -1) return isInitialized == 1;
for (int i = 0; i < getRowsCount(); i++) {
if (!getRows(i).isInitialized()) {
memoizedIsInitialized = 0;
return false;
}
}
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
getSerializedSize();
for (int i = 0; i < rows_.size(); i++) {
output.writeMessage(1, rows_.get(i));
}
getUnknownFields().writeTo(output);
}
private int memoizedSerializedSize = -1;
public int getSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
for (int i = 0; i < rows_.size(); i++) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(1, rows_.get(i));
}
size += getUnknownFields().getSerializedSize();
memoizedSerializedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
protected java.lang.Object writeReplace()
throws java.io.ObjectStreamException {
return super.writeReplace();
}
public static org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return newBuilder().mergeFrom(data).buildParsed();
}
public static org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return newBuilder().mergeFrom(data, extensionRegistry)
.buildParsed();
}
public static org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return newBuilder().mergeFrom(data).buildParsed();
}
public static org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return newBuilder().mergeFrom(data, extensionRegistry)
.buildParsed();
}
public static org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet parseFrom(java.io.InputStream input)
throws java.io.IOException {
return newBuilder().mergeFrom(input).buildParsed();
}
public static org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return newBuilder().mergeFrom(input, extensionRegistry)
.buildParsed();
}
public static org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
Builder builder = newBuilder();
if (builder.mergeDelimitedFrom(input)) {
return builder.buildParsed();
} else {
return null;
}
}
public static org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
Builder builder = newBuilder();
if (builder.mergeDelimitedFrom(input, extensionRegistry)) {
return builder.buildParsed();
} else {
return null;
}
}
public static org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return newBuilder().mergeFrom(input).buildParsed();
}
public static org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return newBuilder().mergeFrom(input, extensionRegistry)
.buildParsed();
}
public static Builder newBuilder() { return Builder.create(); }
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder(org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet prototype) {
return newBuilder().mergeFrom(prototype);
}
public Builder toBuilder() { return newBuilder(this); }
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
public static final class Builder extends
com.google.protobuf.GeneratedMessage.Builder<Builder>
implements org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSetOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.internal_static_org_apache_hadoop_hbase_rest_protobuf_generated_CellSet_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.internal_static_org_apache_hadoop_hbase_rest_protobuf_generated_CellSet_fieldAccessorTable;
}
// Construct using org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
getRowsFieldBuilder();
}
}
private static Builder create() {
return new Builder();
}
public Builder clear() {
super.clear();
if (rowsBuilder_ == null) {
rows_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
} else {
rowsBuilder_.clear();
}
return this;
}
public Builder clone() {
return create().mergeFrom(buildPartial());
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.getDescriptor();
}
public org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet getDefaultInstanceForType() {
return org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.getDefaultInstance();
}
public org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet build() {
org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
private org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet buildParsed()
throws com.google.protobuf.InvalidProtocolBufferException {
org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(
result).asInvalidProtocolBufferException();
}
return result;
}
public org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet buildPartial() {
org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet result = new org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet(this);
int from_bitField0_ = bitField0_;
if (rowsBuilder_ == null) {
if (((bitField0_ & 0x00000001) == 0x00000001)) {
rows_ = java.util.Collections.unmodifiableList(rows_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.rows_ = rows_;
} else {
result.rows_ = rowsBuilder_.build();
}
onBuilt();
return result;
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet) {
return mergeFrom((org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet other) {
if (other == org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.getDefaultInstance()) return this;
if (rowsBuilder_ == null) {
if (!other.rows_.isEmpty()) {
if (rows_.isEmpty()) {
rows_ = other.rows_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureRowsIsMutable();
rows_.addAll(other.rows_);
}
onChanged();
}
} else {
if (!other.rows_.isEmpty()) {
if (rowsBuilder_.isEmpty()) {
rowsBuilder_.dispose();
rowsBuilder_ = null;
rows_ = other.rows_;
bitField0_ = (bitField0_ & ~0x00000001);
rowsBuilder_ =
com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ?
getRowsFieldBuilder() : null;
} else {
rowsBuilder_.addAllMessages(other.rows_);
}
}
}
this.mergeUnknownFields(other.getUnknownFields());
return this;
}
public final boolean isInitialized() {
for (int i = 0; i < getRowsCount(); i++) {
if (!getRows(i).isInitialized()) {
return false;
}
}
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder(
this.getUnknownFields());
while (true) {
int tag = input.readTag();
switch (tag) {
case 0:
this.setUnknownFields(unknownFields.build());
onChanged();
return this;
default: {
if (!parseUnknownField(input, unknownFields,
extensionRegistry, tag)) {
this.setUnknownFields(unknownFields.build());
onChanged();
return this;
}
break;
}
case 10: {
org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row.Builder subBuilder = org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row.newBuilder();
input.readMessage(subBuilder, extensionRegistry);
addRows(subBuilder.buildPartial());
break;
}
}
}
}
private int bitField0_;
// repeated .org.apache.hadoop.hbase.rest.protobuf.generated.CellSet.Row rows = 1;
private java.util.List<org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row> rows_ =
java.util.Collections.emptyList();
private void ensureRowsIsMutable() {
if (!((bitField0_ & 0x00000001) == 0x00000001)) {
rows_ = new java.util.ArrayList<org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row>(rows_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilder<
org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row, org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row.Builder, org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.RowOrBuilder> rowsBuilder_;
public java.util.List<org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row> getRowsList() {
if (rowsBuilder_ == null) {
return java.util.Collections.unmodifiableList(rows_);
} else {
return rowsBuilder_.getMessageList();
}
}
public int getRowsCount() {
if (rowsBuilder_ == null) {
return rows_.size();
} else {
return rowsBuilder_.getCount();
}
}
public org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row getRows(int index) {
if (rowsBuilder_ == null) {
return rows_.get(index);
} else {
return rowsBuilder_.getMessage(index);
}
}
public Builder setRows(
int index, org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row value) {
if (rowsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureRowsIsMutable();
rows_.set(index, value);
onChanged();
} else {
rowsBuilder_.setMessage(index, value);
}
return this;
}
public Builder setRows(
int index, org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row.Builder builderForValue) {
if (rowsBuilder_ == null) {
ensureRowsIsMutable();
rows_.set(index, builderForValue.build());
onChanged();
} else {
rowsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
public Builder addRows(org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row value) {
if (rowsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureRowsIsMutable();
rows_.add(value);
onChanged();
} else {
rowsBuilder_.addMessage(value);
}
return this;
}
public Builder addRows(
int index, org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row value) {
if (rowsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureRowsIsMutable();
rows_.add(index, value);
onChanged();
} else {
rowsBuilder_.addMessage(index, value);
}
return this;
}
public Builder addRows(
org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row.Builder builderForValue) {
if (rowsBuilder_ == null) {
ensureRowsIsMutable();
rows_.add(builderForValue.build());
onChanged();
} else {
rowsBuilder_.addMessage(builderForValue.build());
}
return this;
}
public Builder addRows(
int index, org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row.Builder builderForValue) {
if (rowsBuilder_ == null) {
ensureRowsIsMutable();
rows_.add(index, builderForValue.build());
onChanged();
} else {
rowsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
public Builder addAllRows(
java.lang.Iterable<? extends org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row> values) {
if (rowsBuilder_ == null) {
ensureRowsIsMutable();
super.addAll(values, rows_);
onChanged();
} else {
rowsBuilder_.addAllMessages(values);
}
return this;
}
public Builder clearRows() {
if (rowsBuilder_ == null) {
rows_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
rowsBuilder_.clear();
}
return this;
}
public Builder removeRows(int index) {
if (rowsBuilder_ == null) {
ensureRowsIsMutable();
rows_.remove(index);
onChanged();
} else {
rowsBuilder_.remove(index);
}
return this;
}
public org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row.Builder getRowsBuilder(
int index) {
return getRowsFieldBuilder().getBuilder(index);
}
public org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.RowOrBuilder getRowsOrBuilder(
int index) {
if (rowsBuilder_ == null) {
return rows_.get(index); } else {
return rowsBuilder_.getMessageOrBuilder(index);
}
}
public java.util.List<? extends org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.RowOrBuilder>
getRowsOrBuilderList() {
if (rowsBuilder_ != null) {
return rowsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(rows_);
}
}
public org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row.Builder addRowsBuilder() {
return getRowsFieldBuilder().addBuilder(
org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row.getDefaultInstance());
}
public org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row.Builder addRowsBuilder(
int index) {
return getRowsFieldBuilder().addBuilder(
index, org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row.getDefaultInstance());
}
public java.util.List<org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row.Builder>
getRowsBuilderList() {
return getRowsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilder<
org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row, org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row.Builder, org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.RowOrBuilder>
getRowsFieldBuilder() {
if (rowsBuilder_ == null) {
rowsBuilder_ = new com.google.protobuf.RepeatedFieldBuilder<
org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row, org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row.Builder, org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.RowOrBuilder>(
rows_,
((bitField0_ & 0x00000001) == 0x00000001),
getParentForChildren(),
isClean());
rows_ = null;
}
return rowsBuilder_;
}
// @@protoc_insertion_point(builder_scope:org.apache.hadoop.hbase.rest.protobuf.generated.CellSet)
}
static {
defaultInstance = new CellSet(true);
defaultInstance.initFields();
}
// @@protoc_insertion_point(class_scope:org.apache.hadoop.hbase.rest.protobuf.generated.CellSet)
}
private static com.google.protobuf.Descriptors.Descriptor
internal_static_org_apache_hadoop_hbase_rest_protobuf_generated_CellSet_descriptor;
private static
com.google.protobuf.GeneratedMessage.FieldAccessorTable
internal_static_org_apache_hadoop_hbase_rest_protobuf_generated_CellSet_fieldAccessorTable;
private static com.google.protobuf.Descriptors.Descriptor
internal_static_org_apache_hadoop_hbase_rest_protobuf_generated_CellSet_Row_descriptor;
private static
com.google.protobuf.GeneratedMessage.FieldAccessorTable
internal_static_org_apache_hadoop_hbase_rest_protobuf_generated_CellSet_Row_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor
descriptor;
static {
java.lang.String[] descriptorData = {
"\n\024CellSetMessage.proto\022/org.apache.hadoo" +
"p.hbase.rest.protobuf.generated\032\021CellMes" +
"sage.proto\"\260\001\n\007CellSet\022J\n\004rows\030\001 \003(\0132<.o" +
"rg.apache.hadoop.hbase.rest.protobuf.gen" +
"erated.CellSet.Row\032Y\n\003Row\022\013\n\003key\030\001 \002(\014\022E" +
"\n\006values\030\002 \003(\01325.org.apache.hadoop.hbase" +
".rest.protobuf.generated.Cell"
};
com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() {
public com.google.protobuf.ExtensionRegistry assignDescriptors(
com.google.protobuf.Descriptors.FileDescriptor root) {
descriptor = root;
internal_static_org_apache_hadoop_hbase_rest_protobuf_generated_CellSet_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_org_apache_hadoop_hbase_rest_protobuf_generated_CellSet_fieldAccessorTable = new
com.google.protobuf.GeneratedMessage.FieldAccessorTable(
internal_static_org_apache_hadoop_hbase_rest_protobuf_generated_CellSet_descriptor,
new java.lang.String[] { "Rows", },
org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.class,
org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Builder.class);
internal_static_org_apache_hadoop_hbase_rest_protobuf_generated_CellSet_Row_descriptor =
internal_static_org_apache_hadoop_hbase_rest_protobuf_generated_CellSet_descriptor.getNestedTypes().get(0);
internal_static_org_apache_hadoop_hbase_rest_protobuf_generated_CellSet_Row_fieldAccessorTable = new
com.google.protobuf.GeneratedMessage.FieldAccessorTable(
internal_static_org_apache_hadoop_hbase_rest_protobuf_generated_CellSet_Row_descriptor,
new java.lang.String[] { "Key", "Values", },
org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row.class,
org.apache.hadoop.hbase.rest.protobuf.generated.CellSetMessage.CellSet.Row.Builder.class);
return null;
}
};
com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
org.apache.hadoop.hbase.rest.protobuf.generated.CellMessage.getDescriptor(),
}, assigner);
}
// @@protoc_insertion_point(outer_class_scope)
}
| 23,646 |
634 | <reponame>gwhitehawk/zentral<gh_stars>100-1000
# Generated by Django 2.2.17 on 2020-11-29 18:33
from django.db import migrations
def set_default_manifest_names(apps, schema_editor):
Manifest = apps.get_model("monolith", "Manifest")
for manifest in Manifest.objects.select_related("meta_business_unit").all():
manifest.name = manifest.meta_business_unit.name
manifest.save()
class Migration(migrations.Migration):
dependencies = [
('monolith', '0041_auto_20201129_1756'),
]
operations = [
migrations.RunPython(set_default_manifest_names)
]
| 228 |
348 | {"nom":"Cros","circ":"3ème circonscription","dpt":"Puy-de-Dôme","inscrits":173,"abs":78,"votants":95,"blancs":11,"nuls":5,"exp":79,"res":[{"nuance":"UDI","nom":"<NAME>","voix":45},{"nuance":"MDM","nom":"<NAME>","voix":34}]} | 95 |
5,597 | package demo.soap;
import demo.TestBase;
/**
*
* @author pthomas3
*/
public class SoapRunner extends TestBase {
}
| 47 |
723 | <filename>mac/ATCommons/P2AsyncEnumeration.h
#import <Foundation/Foundation.h>
@interface NSArray (P2AsyncEnumeration)
- (void)p2_enumerateObjectsAsynchronouslyUsingBlock:(void (^)(id obj, NSUInteger idx, BOOL *stop, dispatch_block_t callback))block completionBlock:(dispatch_block_t)completionBlock;
- (void)p2_enumerateObjectsAsynchronouslyUsingBlock:(void (^)(id obj, NSUInteger idx, BOOL *stop, dispatch_block_t callback))block completionBlock:(dispatch_block_t)completionBlock usingQueue:(dispatch_queue_t)queue;
@end
| 179 |
851 | /*
* Copyright (c) 2017 The WebRTC 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 "api/video_codecs/video_encoder.h"
#include <string.h>
#include "rtc_base/checks.h"
namespace webrtc {
// TODO(mflodman): Add default complexity for VP9 and VP9.
VideoCodecVP8 VideoEncoder::GetDefaultVp8Settings() {
VideoCodecVP8 vp8_settings;
memset(&vp8_settings, 0, sizeof(vp8_settings));
vp8_settings.numberOfTemporalLayers = 1;
vp8_settings.denoisingOn = true;
vp8_settings.automaticResizeOn = false;
vp8_settings.frameDroppingOn = true;
vp8_settings.keyFrameInterval = 3000;
return vp8_settings;
}
VideoCodecVP9 VideoEncoder::GetDefaultVp9Settings() {
VideoCodecVP9 vp9_settings;
memset(&vp9_settings, 0, sizeof(vp9_settings));
vp9_settings.numberOfTemporalLayers = 1;
vp9_settings.denoisingOn = true;
vp9_settings.frameDroppingOn = true;
vp9_settings.keyFrameInterval = 3000;
vp9_settings.adaptiveQpMode = true;
vp9_settings.automaticResizeOn = true;
vp9_settings.numberOfSpatialLayers = 1;
vp9_settings.flexibleMode = false;
vp9_settings.interLayerPred = InterLayerPredMode::kOn;
return vp9_settings;
}
VideoCodecH264 VideoEncoder::GetDefaultH264Settings() {
VideoCodecH264 h264_settings;
memset(&h264_settings, 0, sizeof(h264_settings));
h264_settings.frameDroppingOn = true;
h264_settings.keyFrameInterval = 3000;
h264_settings.spsData = nullptr;
h264_settings.spsLen = 0;
h264_settings.ppsData = nullptr;
h264_settings.ppsLen = 0;
h264_settings.profile = H264::kProfileConstrainedBaseline;
return h264_settings;
}
VideoEncoder::ScalingSettings::ScalingSettings() = default;
VideoEncoder::ScalingSettings::ScalingSettings(KOff) : ScalingSettings() {}
VideoEncoder::ScalingSettings::ScalingSettings(int low, int high)
: thresholds(QpThresholds(low, high)) {}
VideoEncoder::ScalingSettings::ScalingSettings(int low,
int high,
int min_pixels)
: thresholds(QpThresholds(low, high)), min_pixels_per_frame(min_pixels) {}
VideoEncoder::ScalingSettings::ScalingSettings(const ScalingSettings&) =
default;
VideoEncoder::ScalingSettings::~ScalingSettings() {}
// static
constexpr VideoEncoder::ScalingSettings::KOff
VideoEncoder::ScalingSettings::kOff;
int32_t VideoEncoder::SetRates(uint32_t bitrate, uint32_t framerate) {
RTC_NOTREACHED() << "SetRate(uint32_t, uint32_t) is deprecated.";
return -1;
}
int32_t VideoEncoder::SetRateAllocation(
const VideoBitrateAllocation& allocation,
uint32_t framerate) {
return SetRates(allocation.get_sum_kbps(), framerate);
}
VideoEncoder::ScalingSettings VideoEncoder::GetScalingSettings() const {
return ScalingSettings::kOff;
}
bool VideoEncoder::SupportsNativeHandle() const {
return false;
}
const char* VideoEncoder::ImplementationName() const {
return "unknown";
}
} // namespace webrtc
| 1,199 |
426 | package com.richardradics.core.util;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Point;
import android.view.Display;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.ViewConfiguration;
import android.view.WindowManager;
import com.richardradics.commons.helper.TelephonyHelper;
import com.richardradics.commons.util.ConnectivityUtil;
import com.richardradics.commons.util.EmailUtil;
import com.richardradics.core.navigation.Navigator;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.EBean;
import org.androidannotations.annotations.RootContext;
import org.androidannotations.annotations.UiThread;
/**
* Created by radicsrichard on 15. 04. 28..
*/
@EBean(scope = EBean.Scope.Singleton)
public class CommonUseCases {
@RootContext
Context context;
@Bean
Navigator navigator;
@UiThread
public void sendEmail(String to, String subject, String body, String pickerTitle) {
EmailUtil.startEmailActivity(context, to, subject, body, pickerTitle);
}
@UiThread
public void callPhone(String phoneNumber) {
TelephonyHelper.startDialActivity(context, phoneNumber);
}
@UiThread
public void callPhoneWithSimCheck(String phoneNumber) {
TelephonyHelper.startDialActivityWithSimCheck(context, phoneNumber);
}
public boolean isNetworkConnected() {
return ConnectivityUtil.isConnected(context);
}
public Point getScreenSizeinActivity() {
Point size = new Point();
if (navigator.isInForeground()) {
Display display = navigator.getCurrentActivityOnScreen().getWindowManager().getDefaultDisplay(); //Activity#getWindowManager()
display.getSize(size);
}
return size;
}
public Point getScreenSize() {
Point size = new Point();
WindowManager wm = (WindowManager) context.getSystemService(context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
display.getSize(size);
return size;
}
public boolean hasNavBar() {
boolean hasMenuKey = ViewConfiguration.get(context).hasPermanentMenuKey();
boolean hasBackKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK);
if (!hasMenuKey && !hasBackKey)
return true;
else
return false;
}
public int getNavigationBarHeight() {
Resources resources = context.getResources();
int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
if (hasNavBar() && resourceId > 0 ) {
return resources.getDimensionPixelSize(resourceId);
}
return 0;
}
}
| 995 |
407 | package com.alibaba.tesla.appmanager.server.repository.mapper;
import com.alibaba.tesla.appmanager.server.repository.domain.ProductReleaseTaskAppPackageTaskRelDO;
import com.alibaba.tesla.appmanager.server.repository.domain.ProductReleaseTaskAppPackageTaskRelDOExample;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface ProductReleaseTaskAppPackageTaskRelDOMapper {
long countByExample(ProductReleaseTaskAppPackageTaskRelDOExample example);
int deleteByExample(ProductReleaseTaskAppPackageTaskRelDOExample example);
int deleteByPrimaryKey(Long id);
int insert(ProductReleaseTaskAppPackageTaskRelDO record);
int insertSelective(ProductReleaseTaskAppPackageTaskRelDO record);
List<ProductReleaseTaskAppPackageTaskRelDO> selectByExample(ProductReleaseTaskAppPackageTaskRelDOExample example);
ProductReleaseTaskAppPackageTaskRelDO selectByPrimaryKey(Long id);
int updateByExampleSelective(@Param("record") ProductReleaseTaskAppPackageTaskRelDO record, @Param("example") ProductReleaseTaskAppPackageTaskRelDOExample example);
int updateByExample(@Param("record") ProductReleaseTaskAppPackageTaskRelDO record, @Param("example") ProductReleaseTaskAppPackageTaskRelDOExample example);
int updateByPrimaryKeySelective(ProductReleaseTaskAppPackageTaskRelDO record);
int updateByPrimaryKey(ProductReleaseTaskAppPackageTaskRelDO record);
} | 404 |
5,133 | <reponame>Saljack/mapstruct<gh_stars>1000+
/*
* Copyright MapStruct Authors.
*
* Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package org.mapstruct.ap.test.java8stream;
import java.util.ArrayList;
import java.util.Collection;
/**
* @author <NAME>
*/
public class TestList<E> extends ArrayList<E> {
private static final long serialVersionUID = 1L;
private static boolean addAllCalled = false;
public static boolean isAddAllCalled() {
return addAllCalled;
}
public static void setAddAllCalled(boolean addAllCalled) {
TestList.addAllCalled = addAllCalled;
}
@Override
public boolean addAll(Collection<? extends E> c) {
addAllCalled = true;
return super.addAll( c );
}
}
| 293 |
3,428 | {"id":"01037","group":"easy-ham-2","checksum":{"type":"MD5","value":"bfe999fe03b3c6b5b7cc2360c793e5a0"},"text":"From <EMAIL> Fri Aug 16 11:27:54 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: y<EMAIL>.netnoteinc.com\nReceived: from localhost (localhost [127.0.0.1])\n\tby phobos.labs.netnoteinc.com (Postfix) with ESMTP id A4C0D441AA\n\tfor <jm@localhost>; Fri, 16 Aug 2002 06:03:30 -0400 (EDT)\nReceived: from phobos [127.0.0.1]\n\tby localhost with IMAP (fetchmail-5.9.0)\n\tfor jm@localhost (single-drop); Fri, 16 Aug 2002 11:03:30 +0100 (IST)\nReceived: from xent.com ([64.161.22.236]) by dogma.slashnull.org\n (8.11.6/8.11.6) with ESMTP id g7FM48719960 for <<EMAIL>>;\n Thu, 15 Aug 2002 23:04:08 +0100\nReceived: from lair.xent.com (localhost [127.0.0.1]) by xent.com (Postfix)\n with ESMTP id 0091B29409A; Thu, 15 Aug 2002 15:02:06 -0700 (PDT)\nDelivered-To: <EMAIL>\nReceived: from localhost.localdomain (h00045acfa2be.ne.client2.attbi.com\n [65.96.178.138]) by xent.com (Postfix) with ESMTP id 97B07294098 for\n <<EMAIL>>; Thu, 15 Aug 2002 15:01:34 -0700 (PDT)\nReceived: (from louie@localhost) by localhost.localdomain (8.11.6/8.11.6)\n id g7FM16W05669; Thu, 15 Aug 2002 18:01:06 -0400\nX-Authentication-Warning: localhost.localdomain: louie set sender to\n <EMAIL> using -f\nSubject: Re: It's a small world\nFrom: <NAME> <<EMAIL>>\nTo: Jesse <<EMAIL>>\nCc: <EMAIL>\nIn-Reply-To: <<EMAIL>>\nReferences: <<EMAIL>>\n <1029444667.<EMAIL>>\n <<EMAIL>>\n <1029448015.5<EMAIL>.5<EMAIL>>\n <<EMAIL>>\nContent-Type: text/plain\nContent-Transfer-Encoding: 7bit\nX-Mailer: Ximian Evolution 1.0.8\nMessage-Id: <<EMAIL>448866.5235.5<EMAIL>.localdomain>\nMIME-Version: 1.0\nSender: [email protected]\nErrors-To: fork-admin<EMAIL>\nX-Beenthere: <EMAIL>\nX-Mailman-Version: 2.0.11\nPrecedence: bulk\nList-Help: <mailto:<EMAIL>?subject=help>\nList-Post: <mailto:<EMAIL>>\nList-Subscribe: <http://xent.com/mailman/listinfo/fork>, <mailto:<EMAIL>?subject=subscribe>\nList-Id: Friends of <NAME> <fork.xent.com>\nList-Unsubscribe: <http://xent.com/mailman/listinfo/fork>,\n <mailto:fork-<EMAIL>?subject=unsubscribe>\nList-Archive: <http://xent.com/pipermail/fork/>\nDate: 15 Aug 2002 18:01:06 -0400\n\nOn Thu, 2002-08-15 at 17:53, Jesse wrote:\n> \n> On Thu, Aug 15, 2002 at 05:46:55PM -0400, <NAME> wrote:\n> > FWIW, slummerville actually has the internet- not just broadband, but\n> > actual broadband competition, which I gather is rare. I had ADSL and two\n> > cable options when I moved in.\n> \n> \n> Did you actually attempt to order the DSL? Large chunks of somerville have\n> advertised DSL service that can't actually be obtained. Excuses vary, from\n> \"no available copper\" to \"full DSLAM\", but the folks I know who've wanted\n> DSL around here have all failed, ending up either with ATTBB, RCN or an\n> honest-to-god T1.\n\nNo. My past experiences with DSL have generally been miserable so I went\nwith at&t digital cable[1] + cable modem. Still, even the hypothetical\noption was a lot better than what I had in the theoretically\ntech-friendly Triangle in NC.\nLuis\n\n[1]sports junkie\nhttp://xent.com/mailman/listinfo/fork\n\n"} | 1,271 |
7,482 | /*
* Copyright (c) 2012, Freescale Semiconductor, 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:
*
* o Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* o 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.
*
* o Neither the name of Freescale Semiconductor, 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 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.
*/
#include "usdhc.h"
#include "sdk.h"
#include "usdhc_host.h"
#include "usdhc_mmc.h"
#include "usdhc/usdhc_ifc.h"
#include "registers/regsusdhc.h"
#include "timer/timer.h"
static struct csd_struct csd_reg;
static uint32_t ext_csd_data[BLK_LEN / FOUR];
static uint32_t mmc_version = MMC_CARD_INV;
/********************************************* Static Function ******************************************/
/*!
* @brief Set the mmc card a RCA
*
* @param instance Instance number of the uSDHC module.
*
* @return 0 if successful; 1 otherwise
*/
static int mmc_set_rca(uint32_t instance)
{
command_t cmd;
int port, card_state, status = FAIL;
command_response_t response;
/* Check uSDHC Port */
port = card_get_port(instance);
if (port == USDHC_NUMBER_PORTS) {
printf("Base address: 0x%x not in address table.\n", REGS_USDHC_BASE(instance));
return status;
}
/* Set RCA to ONE */
usdhc_device[port].rca = ONE;
/* Configure CMD3 */
card_cmd_config(&cmd, CMD3, (usdhc_device[port].rca << RCA_SHIFT), READ, RESPONSE_48,
DATA_PRESENT_NONE, TRUE, TRUE);
usdhc_printf("Send CMD3.\n");
/* Send CMD3 */
if (host_send_cmd(instance, &cmd) == SUCCESS) {
response.format = RESPONSE_48;
host_read_response(instance, &response);
/* Check the IDENT card state */
card_state = CURR_CARD_STATE(response.cmd_rsp0);
if (card_state == IDENT) {
status = SUCCESS;
}
}
return status;
}
/*!
* @brief Check switch ability and switch function
*
* @param instance Instance number of the uSDHC module.
* @param arg Argument to command 6
*
* @return 0 if successful; 1 otherwise
*/
static int mmc_switch(uint32_t instance, uint32_t arg)
{
command_t cmd;
int status = FAIL;
/* Configure MMC Switch Command */
card_cmd_config(&cmd, CMD6, arg, READ, RESPONSE_48, DATA_PRESENT_NONE, TRUE, TRUE);
usdhc_printf("Send CMD6.\n");
/* Send CMD6 */
if (SUCCESS == host_send_cmd(instance, &cmd)) {
status = card_trans_status(instance);
}
return status;
}
/*!
* @brief Set data transfer width.
* Possible data transfer width is 1-bit, 4-bits or 8-bits
*
* @param instance Instance number of the uSDHC module.
* @param data_width Data transfer width
*/
static int mmc_set_bus_width(uint32_t instance, int bus_width)
{
return mmc_switch(instance, MMC_SWITCH_SETBW_ARG(bus_width));
}
/*!
* @brief Read card specified data (CSD)
*
* @param instance Instance number of the uSDHC module.
*
* @return 0 if successful; 1 otherwise
*/
static int mmc_read_csd(uint32_t instance)
{
command_t cmd;
command_response_t response;
int status = SUCCESS;
/* Configure read CSD command */
card_cmd_config(&cmd, CMD9, ONE << RCA_SHIFT, READ,
RESPONSE_136, DATA_PRESENT_NONE, TRUE, FALSE);
usdhc_printf("Send CMD9.\n");
/* Send CMD9 */
if (host_send_cmd(instance, &cmd) == FAIL) {
status = FAIL;
} else {
/* Read response */
response.format = RESPONSE_136;
host_read_response(instance, &response);
csd_reg.response[0] = response.cmd_rsp0;
csd_reg.response[1] = response.cmd_rsp1;
csd_reg.response[2] = response.cmd_rsp2;
csd_reg.response[3] = response.cmd_rsp3;
csd_reg.csds = (csd_reg.response[3] & 0x00C00000) >> 22;
csd_reg.ssv = (csd_reg.response[3] & 0x003C0000) >> 18;
}
return status;
}
/*!
* @brief Send CMD8 to get EXT_CSD value of MMC;
*
* @param instance Instance number of the uSDHC module.
*
* @return 0 if successful; 1 otherwise
*/
static int mmc_read_esd(uint32_t instance)
{
command_t cmd;
/* Set block length */
card_cmd_config(&cmd, CMD16, BLK_LEN, READ, RESPONSE_48, DATA_PRESENT_NONE, TRUE, TRUE);
usdhc_printf("Send CMD16.\n");
/* Send CMD16 */
if (SUCCESS == host_send_cmd(instance, &cmd)) {
/* Configure block attribute */
host_cfg_block(instance, BLK_LEN, ONE, ESDHC_BLKATTR_WML_BLOCK);
/* Read extended CSD */
card_cmd_config(&cmd, CMD8, NO_ARG, READ, RESPONSE_48, DATA_PRESENT, TRUE, TRUE);
usdhc_printf("Send CMD8.\n");
/* Send CMD8 */
if (SUCCESS == host_send_cmd(instance, &cmd)) {
return host_data_read(instance, (int *)ext_csd_data, BLK_LEN,
ESDHC_BLKATTR_WML_BLOCK);
}
}
return FAIL;
}
/*!
* @brief Read CSD and EXT_CSD value of MMC;
*
* @param instance Instance number of the uSDHC module.
*
* @return CSD value if successful; 0 otherwise
*/
static uint32_t mmc_get_spec_ver(uint32_t instance)
{
int retv = 0;
/* Read CSD */
if (SUCCESS == mmc_read_csd(instance)) {
retv = csd_reg.ssv | (csd_reg.csds << 8);
}
/* Enter transfer mode */
if (SUCCESS == card_enter_trans(instance)) {
/* Set bus width */
if (mmc_set_bus_width(instance, ONE) == SUCCESS) {
host_set_bus_width(instance, ONE);
}
/* Read Extended CSD */
if (SUCCESS == mmc_read_esd(instance)) {
retv |= (ext_csd_data[48] & 0x00FF0000) | ((ext_csd_data[57] & 0xFF) << 24);
}
}
return retv;
}
/********************************************* Global Function ******************************************/
/*!
* @brief Initialize MMC - Get Card ID, Set RCA, Frequency and bus width.
*
* @param instance Instance number of the uSDHC module.
* @param bus_width bus width to be configured.
*
* @return 0 if successful; 1 otherwise
*/
int mmc_init(uint32_t instance, int bus_width)
{
int status = FAIL;
usdhc_printf("Get CID.\n");
/* Get CID */
if (card_get_cid(instance) == SUCCESS) {
usdhc_printf("Set RCA.\n");
/* Set RCA */
if (mmc_set_rca(instance) == SUCCESS) {
/* Check Card Type here */
usdhc_printf("Set operating frequency.\n");
/* Switch to Operating Frequency */
host_cfg_clock(instance, OPERATING_FREQ);
usdhc_printf("Enter transfer state.\n");
/* Enter Transfer State */
if (card_enter_trans(instance) == SUCCESS) {
usdhc_printf("Set bus width.\n");
/* Set Card Bus Width */
if (mmc_set_bus_width(instance, bus_width) == SUCCESS) {
/* Set Host Bus Width */
host_set_bus_width(instance, bus_width);
/* Set High Speed Here */
{
status = SUCCESS;
}
}
}
}
}
return status;
}
/*!
* @brief Initialize eMMC - Get Card ID, Set RCA, Frequency and bus width.
*
* @param instance Instance number of the uSDHC module.
*
* @return 0 if successful; 1 otherwise
*/
int emmc_init(uint32_t instance)
{
uint8_t byte;
uint32_t retv;
int status = FAIL;
/* Init MMC version */
mmc_version = MMC_CARD_INV;
/* Get CID */
if (card_get_cid(instance) == SUCCESS) {
/* Set RCA */
if (mmc_set_rca(instance) == SUCCESS) {
/* Switch to Operating Frequency */
host_cfg_clock(instance, OPERATING_FREQ);
status = SUCCESS;
retv = mmc_get_spec_ver(instance);
/* Obtain CSD structure */
byte = (retv >> 8) & 0xFF;
if (byte == 3) {
/* Obtain system spec version in CSD */
byte = (retv >> 16) & 0xFF;
}
if (byte == 2) {
/* If support DDR mode */
byte = retv >> 24;
if (byte & 0x2) {
mmc_version = MMC_CARD_4_4;
printf("\teMMC 4.4 card.\n");
} else {
mmc_version = MMC_CARD_4_X;
printf("\teMMC 4.X (X<4) card.\n");
}
} else {
mmc_version = MMC_CARD_3_X;
printf("\tMMC 3.X or older cards.\n");
}
}
}
return status;
}
/*!
* @brief Print out eMMC configuration information.
*
* @param instance Instance number of the uSDHC module.
*
*/
void emmc_print_cfg_info(uint32_t instance)
{
uint8_t byte, *ptr;
/* Check if card initialized OK */
if (mmc_version == MMC_CARD_INV) {
printf("Invalid or uninitialized card.\n");
return;
}
/* Read extended CSD rigister */
if (FAIL == mmc_read_esd(instance)) {
printf("Read extended CSD failed.\n");
return;
}
/* Specify pointer */
ptr = (uint8_t *) ext_csd_data;
/* Display boot partition */
byte = ptr[MMC_ESD_OFF_PRT_CFG] & BP_MASK;
printf("\t%s enabled for boot.\n", (byte == BP_USER) ? "User Partition" :
(byte == BP_BT1) ? "Boot partition #1" :
(byte == BP_BT2) ? "Boot Partition #2" : "No partition");
/* Display boot acknowledge */
if (mmc_version == MMC_CARD_4_4) {
byte = ptr[MMC_ESD_OFF_PRT_CFG] & BT_ACK;
printf("\tFast boot acknowledgement %s\n", (byte == 0) ? "disabled" : "enabled");
}
/* Display fast boot bus width */
byte = ptr[MMC_ESD_OFF_BT_BW] & BBW_BUS_MASK;
printf("\tFast boot bus width: %s\n", (byte == BBW_1BIT) ? "1 bit" :
(byte == BBW_4BIT) ? "4 bit" : (byte == BBW_8BIT) ? "8 bit" : "unknown");
/* Display DDR mode setting */
byte = ptr[MMC_ESD_OFF_BT_BW] & BBW_DDR_MASK;
printf("\tDDR boot mode %s\n", (byte == BBW_DDR) ? "enabled" : "disabled");
/* Display boot save setting */
byte = ptr[MMC_ESD_OFF_BT_BW] & BBW_SAVE;
printf("\t%s boot bus width settings.\n\n", (byte == 0) ? "Discard" : "Retain");
}
/*!
* @brief Set bus width.
*
* @param instance Instance number of the uSDHC module.
* @param width Bus width
*
* @return 0 if successful; 1 otherwise
*/
int mmc_set_boot_bus_width(uint32_t instance, emmc_bus_width_e width)
{
int bus_width;
if (mmc_version == MMC_CARD_INV) {
printf("Invalid or uninitialized card.\n");
return FAIL;
}
bus_width = (width == EMMC_BOOT_SDR1) ? (BBW_1BIT | BBW_SAVE) :
(width == EMMC_BOOT_SDR4) ? (BBW_4BIT | BBW_SAVE) :
(width == EMMC_BOOT_SDR8) ? (BBW_8BIT | BBW_SAVE) :
(width ==
EMMC_BOOT_DDR4) ? (BBW_4BIT | BBW_SAVE | BBW_DDR) : (BBW_8BIT | BBW_SAVE | BBW_DDR);
return mmc_switch(instance,
MMC_SWITCH_SET_BOOT_BUS_WIDTH | (bus_width << MMC_SWITCH_SET_PARAM_SHIFT));
}
/*!
* @brief Set boot partition.
*
* @param instance Instance number of the uSDHC module.
* @param part Partition number
*
* @return 0 if successful; 1 otherwise
*/
int mmc_set_boot_partition(uint32_t instance, emmc_part_e part)
{
int boot_part;
uint8_t byte, *ptr;
if (mmc_version == MMC_CARD_INV) {
printf("Invalid or uninitialized card.\n");
return FAIL;
}
/* Read extended CSD rigister */
if (FAIL == mmc_read_esd(instance)) {
printf("Read extended CSD failed.\n");
return FAIL;
}
ptr = (uint8_t *) ext_csd_data;
boot_part = (part == EMMC_PART_USER) ? BP_USER : (part == EMMC_PART_BOOT1) ? BP_BT1 : BP_BT2;
byte = (ptr[MMC_ESD_OFF_PRT_CFG] & (~BP_MASK)) | boot_part;
return mmc_switch(instance,
MMC_SWITCH_SET_BOOT_PARTITION | (byte << MMC_SWITCH_SET_PARAM_SHIFT));
}
/*!
* @brief Set boot ACK.
*
* @param instance Instance number of the uSDHC module.
* @param enable 0 no ACK, otherwise set ACK
*
* @return 0 if successful; 1 otherwise
*/
int mmc_set_boot_ack(uint32_t instance, int enable)
{
uint32_t data;
/* Check emmc version */
if (mmc_version != MMC_CARD_4_4) {
printf("Fast boot acknowledge only supported for emmc4.4.\n");
return FAIL;
}
if (enable) {
data = MMC_SWITCH_SET_BOOT_ACK;
} else {
data = MMC_SWITCH_CLR_BOOT_ACK;
}
return mmc_switch(instance, data);
}
/*!
* @brief Valid the voltage.
*
* @param instance Instance number of the uSDHC module.
*
* @return 0 if successful; 1 otherwise
*/
int mmc_voltage_validation(uint32_t instance)
{
command_t cmd;
command_response_t response;
int port, count = ZERO, status = FAIL;
unsigned int ocr_val = MMC_HV_HC_OCR_VALUE;
/* Check uSDHC Port from Base Address */
port = card_get_port(instance);
if (port == USDHC_NUMBER_PORTS) {
printf("Base address: 0x%x not in address table.\n", REGS_USDHC_BASE(instance));
return status;
}
while ((count < MMC_VOLT_VALID_COUNT) && (status == FAIL)) {
/* Configure CMD1 */
card_cmd_config(&cmd, CMD1, ocr_val, READ, RESPONSE_48, DATA_PRESENT_NONE, FALSE, FALSE);
/* Send CMD1 */
if (host_send_cmd(instance, &cmd) == FAIL) {
printf("Send CMD1 failed.\n");
break;
} else {
/* Check Response */
response.format = RESPONSE_48;
host_read_response(instance, &response);
/* Check Busy Bit Cleared or NOT */
if (response.cmd_rsp0 & CARD_BUSY_BIT) {
/* Check Address Mode */
if ((response.cmd_rsp0 & MMC_OCR_HC_BIT_MASK) == MMC_OCR_HC_RESP_VAL) {
usdhc_device[port].addr_mode = SECT_MODE;
} else {
usdhc_device[port].addr_mode = BYTE_MODE;
}
status = SUCCESS;
} else {
count++;
hal_delay_us(MMC_VOLT_VALID_DELAY);
}
}
}
return status;
}
| 7,072 |
348 | <gh_stars>100-1000
{"nom":"Orchies","circ":"6ème circonscription","dpt":"Nord","inscrits":6675,"abs":4021,"votants":2654,"blancs":266,"nuls":139,"exp":2249,"res":[{"nuance":"REM","nom":"<NAME>","voix":1252},{"nuance":"LR","nom":"<NAME>","voix":997}]} | 102 |
852 | #ifndef Fireworks_Core_FWProxyBuilderTemplate_h
#define Fireworks_Core_FWProxyBuilderTemplate_h
// -*- C++ -*-
//
// Package: Core
// Class : FWProxyBuilderTemplate
//
/**\class FWProxyBuilderTemplate FWProxyBuilderTemplate.h Fireworks/Core/interface/FWProxyBuilderTemplate.h
Description: <one line class summary>
Usage:s
<usage>
*/
//
// Original Author: <NAME>
// Created: April 23 2010
//
// system include files
#include <typeinfo>
// user include files
#include "Fireworks/Core/interface/FWProxyBuilderBase.h"
#include "Fireworks/Core/interface/FWSimpleProxyHelper.h"
#include "Fireworks/Core/interface/FWEventItem.h"
template <typename T>
class FWProxyBuilderTemplate : public FWProxyBuilderBase {
public:
FWProxyBuilderTemplate() : m_helper(typeid(T)) {}
~FWProxyBuilderTemplate() override {}
// ---------- const member functions ---------------------
// ---------- static member functions --------------------
// ---------- member functions ---------------------------
protected:
const T& modelData(int index) { return *reinterpret_cast<const T*>(m_helper.offsetObject(item()->modelData(index))); }
public:
FWProxyBuilderTemplate(const FWProxyBuilderTemplate&) = delete; // stop default
const FWProxyBuilderTemplate& operator=(const FWProxyBuilderTemplate&) = delete; // stop default
private:
virtual void itemChangedImp(const FWEventItem* iItem) {
if (iItem)
m_helper.itemChanged(iItem);
}
// ---------- member data --------------------------------
FWSimpleProxyHelper m_helper;
};
#endif
| 474 |
1,607 | <gh_stars>1000+
"""Test for tmuxp workspacefreezer."""
import time
import kaptan
from tmuxp import config
from tmuxp.workspacebuilder import WorkspaceBuilder, freeze
from .fixtures._util import loadfixture
def test_freeze_config(session):
yaml_config = loadfixture("workspacefreezer/sampleconfig.yaml")
sconfig = kaptan.Kaptan(handler='yaml')
sconfig = sconfig.import_config(yaml_config).get()
builder = WorkspaceBuilder(sconf=sconfig)
builder.build(session=session)
assert session == builder.session
time.sleep(0.50)
session = session
sconf = freeze(session)
config.validate_schema(sconf)
sconf = config.inline(sconf)
kaptanconf = kaptan.Kaptan()
kaptanconf = kaptanconf.import_config(sconf)
kaptanconf.export('json', indent=2)
kaptanconf.export('yaml', indent=2, default_flow_style=False, safe=True)
| 331 |
590 | #ifndef __H3_RESET_H__
#define __H3_RESET_H__
#ifdef __cplusplus
extern "C" {
#endif
#define H3_RESET_CE (5)
#define H3_RESET_DMA (6)
#define H3_RESET_SD0 (8)
#define H3_RESET_SD1 (9)
#define H3_RESET_SD2 (10)
#define H3_RESET_NAND (13)
#define H3_RESET_SDRAM (14)
#define H3_RESET_EMAC (17)
#define H3_RESET_TS (18)
#define H3_RESET_HSTIMER (19)
#define H3_RESET_SPI0 (20)
#define H3_RESET_SPI1 (21)
#define H3_RESET_OTG_DEVICE (23)
#define H3_RESET_OTG_EHCI0 (24)
#define H3_RESET_USB_EHCI1 (25)
#define H3_RESET_USB_EHCI2 (26)
#define H3_RESET_USB_EHCI3 (27)
#define H3_RESET_OTG_OHCI0 (28)
#define H3_RESET_USB_OHCI1 (29)
#define H3_RESET_USB_OHCI2 (30)
#define H3_RESET_USB_OHCI3 (31)
#define H3_RESET_VE (32)
#define H3_RESET_TCON0 (35)
#define H3_RESET_TCON1 (36)
#define H3_RESET_DEINTERLACE (37)
#define H3_RESET_CSI (40)
#define H3_RESET_TVE (41)
#define H3_RESET_HDMI0 (42)
#define H3_RESET_HDMI1 (43)
#define H3_RESET_DE (44)
#define H3_RESET_GPU (52)
#define H3_RESET_MSGBOX (53)
#define H3_RESET_SPINLOCK (54)
#define H3_RESET_DBGSYS (63)
#define H3_RESET_EPHY (66)
#define H3_RESET_AC (96)
#define H3_RESET_OWA (97)
#define H3_RESET_THS (104)
#define H3_RESET_I2S0 (108)
#define H3_RESET_I2S1 (109)
#define H3_RESET_I2S2 (110)
#define H3_RESET_I2C0 (128)
#define H3_RESET_I2C1 (129)
#define H3_RESET_I2C2 (130)
#define H3_RESET_UART0 (144)
#define H3_RESET_UART1 (145)
#define H3_RESET_UART2 (146)
#define H3_RESET_UART3 (147)
#define H3_RESET_SCR (148)
#define H3_RESET_R_IR (161)
#define H3_RESET_R_TIMER (162)
#define H3_RESET_R_UART (164)
#define H3_RESET_R_I2C (166)
#ifdef __cplusplus
}
#endif
#endif /* __H3_RESET_H__ */
| 1,033 |
790 | <filename>lib/grizzled/grizzled/collections/dict.py
"""
``grizzled.collections.dict`` contains some useful dictionary classes
that extend the behavior of the built-in Python ``dict`` type.
"""
__docformat__ = "restructuredtext en"
# ---------------------------------------------------------------------------
# Imports
# ---------------------------------------------------------------------------
import sys
# ---------------------------------------------------------------------------
# Exports
# ---------------------------------------------------------------------------
__all__ = ['OrderedDict', 'LRUDict']
# ---------------------------------------------------------------------------
# Public Classes
# ---------------------------------------------------------------------------
##############################
# OrderedDict implementation #
##############################
class OrderedDict(dict):
"""
``OrderedDict`` is a simple ordered dictionary. The ``keys()``,
``items()``, ``__iter__()``, and other methods all return the keys in the
order they were added to the dictionary. Note that re-adding a key (i.e.,
replacing a key with a new value) does not change the original order.
An ``OrderedDict`` object is instantiated with exactly the same parameters
as a ``dict`` object. The methods it provides are identical to those in
the ``dict`` type and are not documented here.
"""
def __init__(self, *args, **kw):
dict.__init__(self, *args, **kw)
self.__orderedKeys = []
self.__keyPositions = {}
def __setitem__(self, key, value):
try:
index = self.__keyPositions[key]
except KeyError:
index = len(self.__orderedKeys)
self.__orderedKeys += [key]
self.__keyPositions[key] = index
dict.__setitem__(self, key, value)
def __delitem__(self, key):
index = self.__keyPositions[key]
del self.__orderedKeys[index]
del self.__keyPositions[key]
dict.__delitem__(self, key)
def __iter__(self):
for key in self.__orderedKeys:
yield key
def __str__(self):
s = '{'
sep = ''
for k, v in self.iteritems():
s += sep
if type(k) == str:
s += "'%s'" % k
else:
s += str(k)
s += ': '
if type(v) == str:
s += "'%s'" % v
else:
s += str(v)
sep = ', '
s += '}'
return s
def keys(self):
return self.__orderedKeys
def items(self):
return [(key, self[key]) for key in self.__orderedKeys]
def values(self):
return [self[key] for key in self.__orderedKeys]
def iteritems(self):
for key in self.__orderedKeys:
yield (key, self[key])
def iterkeys(self):
for key in self.__orderedKeys:
yield key
def update(self, d):
for key, value in d.iteritems():
self[key] = value
def pop(self, key, default=None):
try:
result = self[key]
del self[key]
except KeyError:
if not default:
raise
result = default
return result
def popitem(self):
key, value = dict.popitem(self)
del self[key]
return (key, value)
##########################
# LRUDict Implementation #
##########################
# Implementation note:
#
# Each entry in the LRUDict dictionary is an LRUListEntry. Basically,
# we maintain two structures:
#
# 1. A linked list of dictionary entries, in order of recency.
# 2. A dictionary of those linked list items.
#
# When accessing or updating an entry in the dictionary, the logic
# is more or less like the following "get" scenario:
#
# - Using the key, get the LRUListEntry from the dictionary.
# - Extract the value from the LRUListEntry, to return to the caller.
# - Move the LRUListEntry to the front of the recency queue.
class LRUListEntry(object):
def __init__(self, key, value):
self.key = key
self.value = value
self.next = None
self.prev = None
def __hash__(self):
return self.key.__hash__()
def __str__(self):
return '(%s, %s)' % (self.key, self.value)
def __repr__(self):
return str(self)
class LRUList(object):
def __init__(self):
self.head = self.tail = None
self.size = 0
def __del__(self):
self.clear()
def __str__(self):
return '[' + ', '.join([str(tup) for tup in self.items()]) + ']'
def __repr__(self):
return self.__class__.__name__ + ':' + str(self)
def __len__(self):
return self.size
def __iter__(self):
entry = self.head
while entry:
yield entry.key
entry = entry.next
def keys(self):
return [k for k in self]
def items(self):
result = []
for key, value in self.iteritems():
result.append((key, value))
return result
def values(self):
result = []
for key, value in self.iteritems():
result.append(value)
return result
def iteritems(self):
entry = self.head
while entry:
yield (entry.key, entry.value)
entry = entry.next
def iterkeys(self):
self.__iter__()
def itervalues(self):
entry = self.head
while entry:
yield entry.value
entry = entry.next
def clear(self):
while self.head:
cur = self.head
next = self.head.next
cur.next = cur.previous = cur.key = cur.value = None
self.head = next
self.tail = None
self.size = 0
def remove(self, entry):
if entry.next:
entry.next.previous = entry.previous
if entry.previous:
entry.previous.next = entry.next
if entry == self.head:
self.head = entry.next
if entry == self.tail:
self.tail = entry.previous
entry.next = entry.previous = None
self.size -= 1
assert self.size >= 0
def remove_tail(self):
result = self.tail
if result:
self.remove(result)
return result
def add_to_head(self, entry):
if type(entry) == tuple:
key, value = entry
entry = LRUListEntry(key, value)
else:
entry.next = entry.previous = None
if self.head:
assert self.tail
entry.next = self.head
self.head.previous = entry
self.head = entry
else:
assert not self.tail
self.head = self.tail = entry
self.size += 1
def move_to_head(self, entry):
self.remove(entry)
self.add_to_head(entry)
class LRUDict(dict):
"""
``LRUDict`` is a dictionary of a fixed maximum size that enforces a least
recently used discard policy. When the dictionary is full (i.e., contains
the maximum number of entries), any attempt to insert a new entry causes
one of the least recently used entries to be discarded.
**Note**:
- Setting or updating a key in the dictionary refreshes the corresponding
value, making it "new" again, even if it replaces the existing value with
itself.
- Retrieving a value from the dictionary also refreshes the entry.
- Iterating over the contents of the dictionary (via ``in`` or ``items()``
or any other similar method) does *not* affect the recency of the
dictionary's contents.
- This implementation is *not* thread-safe.
An ``LRUDict`` also supports the concept of *removal listeners*. Removal
listeners are functions that are notified when objects are removed from
the dictionary. Removal listeners can be:
- *eject only* listeners, meaning they're only notified when objects are
ejected from the cache to make room for new objects, or
- *removal* listeners, meaning they're notified whenever an object is
removed for *any* reason, including via ``del``.
This implementation is based on a Java ``LRUMap`` class in the
``org.clapper.util`` library. See http://software.clapper.org/java/util/
for details.
"""
def __init__(self, *args, **kw):
"""
Initialize an ``LRUDict`` that will hold, at most, ``max_capacity``
items. Attempts to insert more than ``max_capacity`` items in the
dictionary will cause the least-recently used entries to drop out of
the dictionary.
:Keywords:
max_capacity : int
The maximum size of the dictionary
"""
if kw.has_key('max_capacity'):
self.__max_capacity = kw['max_capacity']
del kw['max_capacity']
else:
self.__max_capacity = sys.maxint
dict.__init__(self)
self.__removal_listeners = {}
self.__lru_queue = LRUList()
def __del__(self):
self.clear()
def get_max_capacity(self):
"""
Get the maximum capacity of the dictionary.
:rtype: int
:return: the maximum capacity
"""
return self.__max_capacity
def set_max_capacity(self, new_capacity):
"""
Set or change the maximum capacity of the dictionary. Reducing
the size of a dictionary with items already in it might result
in items being evicted.
:Parameters:
new_capacity : int
the new maximum capacity
"""
self.__max_capacity = new_capacity
if len(self) > new_capacity:
self.__clear_to(new_capacity)
max_capacity = property(get_max_capacity, set_max_capacity,
doc='The maximum capacity. Can be reset at will.')
def add_ejection_listener(self, listener, *args):
"""
Add an ejection listener to the dictionary. The listener function
should take at least two parameters: the key and value being removed.
It can also take additional parameters, which are passed through
unmodified.
An ejection listener is only notified when objects are ejected from
the cache to make room for new objects; more to the point, an ejection
listener is never notified when an object is removed from the cache
manually, via use of the ``del`` operator.
:Parameters:
listener : function
Function to invoke
args : iterable
Any additional parameters to pass to the function
"""
self.__removal_listeners[listener] = (True, args)
def add_removal_listener(self, listener, *args):
"""
Add a removal listener to the dictionary. The listener function should
take at least two parameters: the key and value being removed. It can
also take additional parameters, which are passed through unmodified.
A removal listener is notified when objects are ejected from the cache
to make room for new objects *and* when objects are manually deleted
from the cache.
:Parameters:
listener : function
Function to invoke
args : iterable
Any additional parameters to pass to the function
"""
self.__removal_listeners[listener] = (False, args)
def remove_listener(self, listener):
"""
Remove the specified removal or ejection listener from the list of
listeners.
:Parameters:
listener : function
Function object to remove
:rtype: bool
:return: ``True`` if the listener was found and removed; ``False``
otherwise
"""
try:
del self.__removal_listeners[listener]
return True
except KeyError:
return False
def clear_listeners(self):
"""
Clear all removal and ejection listeners from the list of listeners.
"""
for key in self.__removal_listeners.keys():
del self.__removal_listeners[key]
def __setitem__(self, key, value):
self.__put(key, value)
def __getitem__(self, key):
lru_entry = dict.__getitem__(self, key)
self.__lru_queue.move_to_head(lru_entry)
return lru_entry.value
def __delitem__(self, key):
lru_entry = dict.__getitem__(self, key)
self.__lru_queue.remove(lru_entry)
dict.__delitem__(self, key)
self.__notify_listeners(False, [(lru_entry.key, lru_entry.value)])
def __str__(self):
s = '{'
sep = ''
for k, v in self.iteritems():
s += sep
if type(k) == str:
s += "'%s'" % k
else:
s += str(k)
s += ': '
if type(v) == str:
s += "'%s'" % v
else:
s += str(v)
sep = ', '
s += '}'
return s
def __iter__(self):
return self.__lru_queue.__iter__()
def clear(self):
self.__clear_to(0)
def get(self, key, default=None):
try:
lru_entry = self.__getitem__(key)
value = lru_entry.value
except KeyError:
value = default
return value
def keys(self):
return self.__lru_queue.keys()
def items(self):
return self.__lru_queue.items()
def values(self):
return self.__lru_queue.values()
def iteritems(self):
return self.__lru_queue.iteritems()
def iterkeys(self):
return self.__lru_queue.iterkeys()
def itervalues(self):
return self.__lru_queue.itervalues()
def update(self, d):
for key, value in d.iteritems():
self[key] = value
def pop(self, key, default=None):
try:
result = self[key]
del self[key]
except KeyError:
if not default:
raise
result = default
return result
def popitem(self):
"""
Pops the least recently used recent key/value pair from the
dictionary.
:rtype: tuple
:return: the least recent key/value pair, as a tuple
:raise KeyError: empty dictionary
"""
if len(self) == 0:
raise KeyError, 'Attempted popitem() on empty dictionary'
lru_entry = self.__lru_queue.remove_tail()
dict.__delitem__(self, lru_entry.key)
return lru_entry.key, lru_entry.value
def __put(self, key, value):
try:
lru_entry = dict.__getitem__(self, key)
# Replacing an existing value with a new one. Move the entry
# to the head of the list.
lru_entry.value = value
self.__lru_queue.move_to_head(lru_entry)
except KeyError:
# Not there. Have to add a new one. Clear out the cruft first.
# Preserve one of the entries we're clearing, to avoid
# reallocation.
lru_entry = self.__clear_to(self.max_capacity - 1)
if lru_entry:
lru_entry.key, lru_entry.value = key, value
else:
lru_entry = LRUListEntry(key, value)
self.__lru_queue.add_to_head(lru_entry)
dict.__setitem__(self, key, lru_entry)
def __clear_to(self, size):
old_tail = None
while len(self.__lru_queue) > size:
old_tail = self.__lru_queue.remove_tail()
assert old_tail
key = old_tail.key
value = dict.__delitem__(self, key)
self.__notify_listeners(True, [(key, value)])
assert len(self.__lru_queue) <= size
assert len(self) == len(self.__lru_queue)
return old_tail
def __notify_listeners(self, ejecting, key_value_pairs):
if self.__removal_listeners:
for key, value in key_value_pairs:
for func, func_data in self.__removal_listeners.items():
on_eject_only, args = func_data
if (not on_eject_only) or ejecting:
func(key, value, *args)
| 7,455 |
328 | <reponame>frkhit/SeetaFace6OpenIndex<filename>example/qt/seetaface_demo/mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "QDir"
#include "QFileDialog"
#include "QDebug"
#include "qsqlquery.h"
#include "qmessagebox.h"
#include "qsqlerror.h"
#include "qitemselectionmodel.h"
#include <QModelIndex>
//#include "faceinputdialog.h"
#include "inputfilesprocessdialog.h"
#include "resetmodelprocessdialog.h"
#include <QHBoxLayout>
#include <QWidget>
#include <QIntValidator>
#include <QDoubleValidator>
//#include "Common/CStruct.h"
#include <chrono>
using namespace std::chrono;
//////////////////////////////////
const QString gcrop_prefix("crop_");
Config_Paramter gparamters;
std::string gmodelpath;
/////////////////////////////////////
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
m_currenttab = -1;
ui->setupUi(this);
QIntValidator * vfdminfacesize = new QIntValidator(20, 1000);
ui->fdminfacesize->setValidator(vfdminfacesize);
QDoubleValidator *vfdthreshold = new QDoubleValidator(0.0,1.0, 2);
ui->fdthreshold->setValidator(vfdthreshold);
QDoubleValidator *vantispoofclarity = new QDoubleValidator(0.0,1.0, 2);
ui->antispoofclarity->setValidator(vantispoofclarity);
QDoubleValidator *vantispoofreality = new QDoubleValidator(0.0,1.0, 2);
ui->antispoofreality->setValidator(vantispoofreality);
QDoubleValidator *vyawhigh = new QDoubleValidator(0.0,90, 2);
ui->yawhighthreshold->setValidator(vyawhigh);
QDoubleValidator *vyawlow = new QDoubleValidator(0.0,90, 2);
ui->yawlowthreshold->setValidator(vyawlow);
QDoubleValidator *vpitchlow = new QDoubleValidator(0.0,90, 2);
ui->pitchlowthreshold->setValidator(vpitchlow);
QDoubleValidator *vpitchhigh = new QDoubleValidator(0.0,90, 2);
ui->pitchhighthreshold->setValidator(vpitchhigh);
QDoubleValidator *vfrthreshold = new QDoubleValidator(0.0,1.0, 2);
ui->fr_threshold->setValidator(vfrthreshold);
gparamters.MinFaceSize = 100;
gparamters.Fd_Threshold = 0.80;
gparamters.VideoWidth = 400;
gparamters.VideoHeight = 400;
gparamters.AntiSpoofClarity = 0.30;
gparamters.AntiSpoofReality = 0.80;
gparamters.PitchLowThreshold = 20;
gparamters.PitchHighThreshold = 10;
gparamters.YawLowThreshold = 20;
gparamters.YawHighThreshold = 10;
gparamters.Fr_Threshold = 0.6;
gparamters.Fr_ModelPath = "face_recognizer.csta";
m_type.type = 0;
m_type.filename = "";
m_type.title = "Open Camera 0";
ui->recognize_label->setText(m_type.title);
int width = this->width();
int height = this->height();
this->setFixedSize(width, height);
ui->db_editpicture->setStyleSheet("border-image:url(:/new/prefix1/default.png)");
ui->db_editcrop->setStyleSheet("border-image:url(:/new/prefix1/default.png)");
/////////////////////////
m_database = QSqlDatabase::addDatabase("QSQLITE");
QString exepath = QCoreApplication::applicationDirPath();
QString strdb = exepath + /*QDir::separator()*/ + "/seetaface_demo.db";
m_image_tmp_path = exepath + /*QDir::separator()*/ + "/tmp/";// + QDir::separator();
m_image_path = exepath + /*QDir::separator()*/ + "/images/";// + QDir::separator();
//m_model_path = exepath + /*QDir::separator()*/ + "/models/";// + QDir::separator();
gmodelpath = (exepath + /*QDir::separator()*/ + "/models/"/* + QDir::separator()*/).toStdString();
QDir dir;
dir.mkpath(m_image_tmp_path);
dir.mkpath(m_image_path);
m_database.setDatabaseName(strdb);
if(!m_database.open())
{
QMessageBox::critical(NULL, "critical", tr("open database failed, exited!"), QMessageBox::Yes);
exit(-1);
}
QStringList tables = m_database.tables();
m_table = "face_tab";
m_config_table = "setting_tab";//"paramter_tab";
bool bfind = false;
bool bconfigfind = false;
int i =0;
for( i=0; i<tables.length(); i++)
{
qDebug() << tables[i];
if(tables[i].compare(m_table) == 0)
{
bfind = true;
}else if(tables[i].compare(m_config_table) == 0)
{
bconfigfind = true;
}
}
if(!bfind)
{
QSqlQuery query;
if(!query.exec("create table " + m_table + " (id int primary key, name varchar(64), image_path varchar(256), feature_data blob, facex int, facey int, facewidth int, faceheight int)"))
{
qDebug() << "failed to create table:" + m_table << query.lastError();
QMessageBox::critical(NULL, "critical", "create table " + m_table + " failed, exited!", QMessageBox::Yes);
exit(-1);
}
qDebug() << "create table ok!";
}
if(!bconfigfind)
{
QSqlQuery query;
if(!query.exec("create table " + m_config_table + " (fd_minfacesize int, fd_threshold real, antispoof_clarity real, antispoof_reality real, qa_yawlow real,qa_yawhigh real,qa_pitchlow real,qa_pitchhigh real,fr_threshold real,fr_modelpath varchar(256))"))
{
qDebug() << "failed to create table:" + m_config_table << query.lastError();
QMessageBox::critical(NULL, "critical", "create table " + m_config_table + " failed, exited!", QMessageBox::Yes);
exit(-1);
}
qDebug() << query.lastQuery();
QString sql = "insert into " + m_config_table + " (fd_minfacesize, fd_threshold, antispoof_clarity, antispoof_reality, qa_yawlow, qa_yawhigh, qa_pitchlow, qa_pitchhigh,fr_threshold, fr_modelpath) values (";
sql += "%1, %2, %3, %4, %5, %6, %7, %8, %9, '%10')";
sql = QString(sql).arg(gparamters.MinFaceSize).arg(gparamters.Fd_Threshold).arg(gparamters.AntiSpoofClarity).arg(gparamters.AntiSpoofReality).
arg(gparamters.YawLowThreshold).arg(gparamters.YawHighThreshold).arg(gparamters.PitchLowThreshold).arg(gparamters.PitchHighThreshold).
arg(gparamters.Fd_Threshold).arg(gparamters.Fr_ModelPath);
qDebug() << sql;
QSqlQuery q(sql);
if(!q.exec())
{
qDebug() << "insert failed:" << q.lastError();
QMessageBox::critical(NULL, "critical", "init table " + m_config_table + " failed, exited!", QMessageBox::Yes);
exit(-1);
}
ui->fdminfacesize->setText(QString::number(gparamters.MinFaceSize));
ui->fdthreshold->setText(QString::number(gparamters.Fd_Threshold));
ui->antispoofclarity->setText(QString::number(gparamters.AntiSpoofClarity));
ui->antispoofreality->setText(QString::number(gparamters.AntiSpoofReality));
ui->yawlowthreshold->setText(QString::number(gparamters.YawLowThreshold));
ui->yawhighthreshold->setText(QString::number(gparamters.YawHighThreshold));
ui->pitchlowthreshold->setText(QString::number(gparamters.PitchLowThreshold));
ui->pitchhighthreshold->setText(QString::number(gparamters.PitchHighThreshold));
ui->fr_threshold->setText(QString::number(gparamters.Fr_Threshold));
ui->fr_modelpath->setText(gparamters.Fr_ModelPath);
qDebug() << "create config table ok!";
}
ui->dbtableview->setSelectionBehavior(QAbstractItemView::SelectRows);
ui->dbtableview->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->dbtableview->verticalHeader()->setDefaultSectionSize(80);
ui->dbtableview->verticalHeader()->hide();
connect(ui->dbtableview, SIGNAL(clicked(QModelIndex)), this, SLOT(showfaceinfo()));
m_model = new QStandardItemModel(this);
QStringList columsTitles;
columsTitles << "ID" << "Name" << "Image" << /*"edit" << */" ";
m_model->setHorizontalHeaderLabels(columsTitles);
ui->dbtableview->setModel(m_model);
ui->dbtableview->setColumnWidth(0, 120);
ui->dbtableview->setColumnWidth(1, 200);
ui->dbtableview->setColumnWidth(2, 104);
ui->dbtableview->setColumnWidth(3, 100);
//ui->dbtableview->setColumnWidth(4, 100);
getdatas();
/// ///////////////////////////
gparamters.VideoWidth = ui->previewlabel->width();
gparamters.VideoHeight = ui->previewlabel->height();
if(bconfigfind)
{
//fd_minfacesize, fd_threshold, antispoof_clarity, antispoof_reality, qa_yawlow, qa_yawhigh, qa_pitchlow, qa_pitchhigh
QSqlQuery q("select * from " + m_config_table);
while(q.next())
{
gparamters.MinFaceSize = q.value("fd_minfacesize").toInt();
ui->fdminfacesize->setText(QString::number(q.value("fd_minfacesize").toInt()));
gparamters.Fd_Threshold = q.value("fd_threshold").toFloat();
ui->fdthreshold->setText(QString::number(q.value("fd_threshold").toFloat()));
gparamters.AntiSpoofClarity = q.value("antispoof_clarity").toFloat();
ui->antispoofclarity->setText(QString::number(q.value("antispoof_clarity").toFloat()));
gparamters.AntiSpoofReality = q.value("antispoof_reality").toFloat();
ui->antispoofreality->setText(QString::number(q.value("antispoof_reality").toFloat()));
gparamters.YawLowThreshold = q.value("qa_yawlow").toFloat();
ui->yawlowthreshold ->setText(QString::number(q.value("qa_yawlow").toFloat()));
gparamters.YawHighThreshold = q.value("qa_yawhigh").toFloat();
ui->yawhighthreshold ->setText(QString::number(q.value("qa_yawhigh").toFloat()));
gparamters.PitchLowThreshold = q.value("qa_pitchlow").toFloat();
ui->pitchlowthreshold ->setText(QString::number(q.value("qa_pitchlow").toFloat()));
gparamters.PitchHighThreshold = q.value("qa_pitchhigh").toFloat();
ui->pitchhighthreshold ->setText(QString::number(q.value("qa_pitchhigh").toFloat()));
gparamters.Fr_Threshold = q.value("fr_threshold").toFloat();
gparamters.Fr_ModelPath = q.value("fr_modelpath").toString();
ui->fr_threshold->setText(QString::number(gparamters.Fr_Threshold));
ui->fr_modelpath->setText(gparamters.Fr_ModelPath);
}
}
////////////////////////////
ui->previewtableview->setSelectionBehavior(QAbstractItemView::SelectRows);
ui->previewtableview->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->previewtableview->verticalHeader()->setDefaultSectionSize(80);
ui->previewtableview->verticalHeader()->hide();
//connect(ui->tableView, SIGNAL(clicked(QModelIndex)), this, SLOT(showfaceinfo()));
m_videomodel = new QStandardItemModel(this);
columsTitles.clear();
columsTitles << "Name" << "Score" << "Gallery" << "Snapshot" << "PID";
m_videomodel->setHorizontalHeaderLabels(columsTitles);
ui->previewtableview->setModel(m_videomodel);
ui->previewtableview->setColumnWidth(0, 140);
ui->previewtableview->setColumnWidth(1, 80);
ui->previewtableview->setColumnWidth(2, 84);
ui->previewtableview->setColumnWidth(3, 84);
ui->previewtableview->setColumnWidth(4, 2);
ui->previewtableview->hideColumn(4);
/////////////////////////
m_videothread = new VideoCaptureThread(&m_datalst, ui->previewlabel->width(), ui->previewlabel->height());
m_videothread->setparamter();
//m_videothread->setMinFaceSize(ui->fdminfacesize->text().toInt());
connect(m_videothread, SIGNAL(sigUpdateUI(const QImage &)), this, SLOT(onupdateui(const QImage &)));
connect(m_videothread, SIGNAL(sigEnd(int)), this, SLOT(onvideothreadend(int)));
connect(m_videothread->m_workthread, SIGNAL(sigRecognize(int, const QString &, const QString &, float, const QImage &, const QRect &)), this,
SLOT(onrecognize(int, const QString &, const QString &, float, const QImage &, const QRect &)));
//m_videothread->start();
m_inputfilesthread = new InputFilesThread(m_videothread, m_image_path, m_image_tmp_path);
m_resetmodelthread = new ResetModelThread( m_image_path, m_image_tmp_path);
connect(m_inputfilesthread, SIGNAL(sigInputFilesUpdateUI(std::vector<DataInfo*>*)), this, SLOT(oninputfilesupdateui(std::vector<DataInfo *> *)), Qt::BlockingQueuedConnection);
ui->dbsavebtn->setEnabled(true);
ui->previewrunbtn->setEnabled(true);
ui->previewstopbtn->setEnabled(false);
//ui->pushButton_6->setEnabled(false);
///////////////////////
///////////////////////
//ui->label->setStyleSheet("QLabel{background-color:rgb(255,255,255);}");
//ui->label->setStyleSheet("border-image:url(:/new/prefix1/white.png)");
int a = ui->previewlabel->width();
int b = ui->previewlabel->height();
QImage image(":/new/prefix1/white.png");
QImage ime = image.scaled(a,b);
ui->previewlabel->setPixmap(QPixmap::fromImage(ime));
ui->tabWidget->setCurrentIndex(0);
m_currenttab = ui->tabWidget->currentIndex();
if(m_model->rowCount() > 0)
{
ui->dbtableview->scrollToBottom();
ui->dbtableview->selectRow(m_model->rowCount() - 1);
emit ui->dbtableview->clicked(m_model->index(m_model->rowCount() - 1, 1));
}
}
MainWindow::~MainWindow()
{
delete ui;
cleardata();
}
void MainWindow::cleardata()
{
std::map<int, DataInfo *>::iterator iter = m_datalst.begin();
for(; iter != m_datalst.end(); ++iter)
{
if(iter->second)
{
delete iter->second;
iter->second = NULL;
}
}
m_datalst.clear();
}
void MainWindow::getdatas()
{
int i = 0;
QSqlQuery q("select * from " + m_table + " order by id asc");
while(q.next())
{
//qDebug() << q.value("id").toInt() << "-----" << q.value("name").toString() << "----" << q.value("image_path").toString();
QByteArray data1 = q.value("feature_data").toByteArray();
float * ptr = (float *)data1.data();
//qDebug() << ptr[0] << "," << ptr[1] << "," << ptr[2] << "," << ptr[3] ;
//////////////////////////////////////////////////
m_model->setItem(i, 0, new QStandardItem(QString::number(q.value("id").toInt())));
m_model->setItem(i, 1, new QStandardItem(q.value("name").toString()));
// m_model->setItem(i, 2, new QStandardItem(q.value("image_path").toString()));
QLabel *label = new QLabel("");
label->setFixedSize(100,80);
label->setStyleSheet("border-image:url(" + m_image_path + q.value("image_path").toString() + ")");
ui->dbtableview->setIndexWidget(m_model->index(m_model->rowCount() - 1, 2), label);
/*
QPushButton *button = new QPushButton("edit");
button->setProperty("id", q.value("id").toInt());
button->setFixedSize(80, 40);
connect(button, SIGNAL(clicked()), this, SLOT(editrecord()));
ui->dbtableview->setIndexWidget(m_model->index(m_model->rowCount() - 1, 3), button);
*/
QPushButton *button2 = new QPushButton("delete");
button2->setProperty("id", q.value("id").toInt());
button2->setFixedSize(80, 40);
connect(button2, SIGNAL(clicked()), this, SLOT(deleterecord()));
QWidget *widget = new QWidget();
QHBoxLayout *layout = new QHBoxLayout;
layout->addStretch();
layout->addWidget(button2);
layout->addStretch();
widget->setLayout(layout);
ui->dbtableview->setIndexWidget(m_model->index(m_model->rowCount() - 1, 3), widget);
//ui->dbtableview->setIndexWidget(m_model->index(m_model->rowCount() - 1, 3), button2);
DataInfo * info = new DataInfo;
info->id = q.value("id").toInt();
info->name = q.value("name").toString();
info->image_path = q.value("image_path").toString();
memcpy(info->features, ptr, 1024 * sizeof(float));
info->x = q.value("facex").toInt();
info->y = q.value("facey").toInt();
info->width = q.value("facewidth").toInt();
info->height = q.value("faceheight").toInt();
m_datalst.insert(std::map<int, DataInfo *>::value_type(info->id, info));
i++;
}
}
void MainWindow::editrecord()
{
//QPushButton *button = (QPushButton *)sender();
//qDebug() << button->property("id").toInt() << ", edit";
}
void MainWindow::deleterecord()
{
QPushButton *button = (QPushButton *)sender();
qDebug() << button->property("id").toInt() << ",del";
QMessageBox::StandardButton reply = QMessageBox::question(NULL, "delete", tr("Are you sure delete this record?"), QMessageBox::Yes | QMessageBox::No);
if(reply == QMessageBox::No)
return;
QModelIndex modelindex = ui->dbtableview->indexAt(button->pos());
int id = button->property("id").toInt();
QStandardItemModel * model = (QStandardItemModel *)ui->dbtableview->model();
QSqlQuery query("delete from " + m_table + " where id=" + QString::number(id));
//qDebug() << "delete from " + m_table + " where id=" + QString::number(id);
if(!query.exec())
{
QMessageBox::warning(NULL, "warning", tr("delete this record failed!"), QMessageBox::Yes);
return;
}
int nrows = modelindex.row();
model->removeRow(modelindex.row());
std::map<int, DataInfo *>::iterator iter = m_datalst.find(id);
if(iter != m_datalst.end())
{
QFile file(m_image_path + iter->second->image_path);
file.remove();
delete iter->second;
m_datalst.erase(iter);
}
if(m_model->rowCount() > 0)
{
nrows--;
if(nrows < 0)
{
nrows = 0;
}
//qDebug() << "delete------------row:" << nrows;
ui->dbtableview->selectRow(nrows);
emit ui->dbtableview->clicked(m_model->index(nrows, 1));
}else
{
ui->db_editname->setText("");
ui->db_editid->setText("");
ui->db_editpicture->setStyleSheet("border-image:url(:/new/prefix1/default.png)");
ui->db_editcrop->setStyleSheet("border-image:url(:/new/prefix1/default.png)");
}
}
void MainWindow::showfaceinfo()
{
int row = ui->dbtableview->currentIndex().row();
//qDebug() << "showfaceinfo:" << row ;
if(row >= 0)
{
QModelIndex index = m_model->index(row, 0);
int id = ui->db_editid->text().toInt();
int curid = m_model->data(index).toInt();
if(id == curid)
return;
ui->db_editid->setText(QString::number(m_model->data(index).toInt()));
std::map<int, DataInfo *>::iterator iter = m_datalst.find(m_model->data(index).toInt());
if(iter == m_datalst.end())
return;
index = m_model->index(row, 1);
ui->db_editname->setText(m_model->data(index).toString());
QString strimage = iter->second->image_path;
//qDebug() << "showfaceinfo:" << strimage;
ui->db_editpicture->setStyleSheet("border-image:url(" + m_image_path + strimage + ")");
//qDebug() << "showfaceinfo:" << strimage;
ui->db_editcrop->setStyleSheet("border-image:url(" + m_image_path + gcrop_prefix + strimage + ")");
iter = m_datalst.find(id);
if(iter == m_datalst.end())
return;
QFile::remove(m_image_tmp_path + iter->second->image_path);
}
}
void MainWindow::onrecognize(int pid, const QString & name, const QString & imagepath, float score, const QImage &image, const QRect &rc)
{
int nrows = m_videomodel->rowCount();
if(nrows > 1000)
{
ui->previewtableview->setUpdatesEnabled(false);
m_videomodel->removeRows(0, 200);
ui->previewtableview->setUpdatesEnabled(true);
}
nrows = m_videomodel->rowCount();
int i = 0;
for(; i<nrows; i++)
{
if(m_videomodel->item(i, 4)->text().toInt() == pid)
{
break;
}
}
nrows = i;
m_videomodel->setItem(nrows, 0, new QStandardItem(name));
//m_videomodel->setItem(nrows, 1, new QStandardItem(QString::number(score, 'f', 3)));
QLabel *label = new QLabel("");
label->setFixedSize(80,80);
if(name.isEmpty())
{
m_videomodel->setItem(nrows, 1, new QStandardItem(""));
label->setText(imagepath);
}else
{
m_videomodel->setItem(nrows, 1, new QStandardItem(QString::number(score, 'f', 3)));
//QLabel *label = new QLabel("");
//qDebug() << "rows:" << nrows << ",imagepath:" << imagepath << "," << m_image_path + gcrop_prefix + imagepath ;
//label->setFixedSize(80,80);
QImage srcimage;
srcimage.load( m_image_path + imagepath);
srcimage = srcimage.copy(rc.x(),rc.y(),rc.width(),rc.height());
srcimage = srcimage.scaled(80,80);
label->setPixmap(QPixmap::fromImage(srcimage));
//label->setStyleSheet("border-image:url(" + m_image_path + gcrop_prefix + imagepath + ")");
//ui->previewtableview->setIndexWidget(m_videomodel->index(nrows, 2), label);
}
ui->previewtableview->setIndexWidget(m_videomodel->index(nrows, 2), label);
/*
QLabel *label = new QLabel("");
qDebug() << "rows:" << nrows << ",imagepath:" << imagepath << "," << m_image_path + gcrop_prefix + imagepath ;
label->setFixedSize(80,80);
QImage srcimage;
srcimage.load( m_image_path + imagepath);
srcimage = srcimage.copy(rc.x(),rc.y(),rc.width(),rc.height());
srcimage = srcimage.scaled(80,80);
label->setPixmap(QPixmap::fromImage(srcimage));
//label->setStyleSheet("border-image:url(" + m_image_path + gcrop_prefix + imagepath + ")");
ui->previewtableview->setIndexWidget(m_videomodel->index(nrows, 2), label);
*/
QLabel *label2 = new QLabel("");
label2->setFixedSize(80,80);
QImage img = image.scaled(80,80);
label2->setPixmap(QPixmap::fromImage(img));
//label2->setStyleSheet("border-image:url(" + m_image_path + gcrop_prefix + imagepath + ")");
ui->previewtableview->setIndexWidget(m_videomodel->index(nrows, 3), label2);
m_videomodel->setItem(nrows, 4, new QStandardItem(QString::number(pid)));
ui->previewtableview->scrollToBottom();
}
void MainWindow::onupdateui(const QImage & image)
{
int a = ui->previewlabel->width();
int b = ui->previewlabel->height();
QImage ime = image.scaled(a,b);
ui->previewlabel->setPixmap(QPixmap::fromImage(ime));
ui->previewlabel->show();
}
void MainWindow::onvideothreadend(int value)
{
qDebug() << "onvideothreadend:" << value;
//ui->label->setStyleSheet("border-image:url(:/new/prefix1/white.png)");
if(m_type.type != 2)
{
int a = ui->previewlabel->width();
int b = ui->previewlabel->height();
QImage image(":/new/prefix1/white.png");
QImage ime = image.scaled(a,b);
ui->previewlabel->setPixmap(QPixmap::fromImage(ime));
ui->previewlabel->show();
}
ui->previewrunbtn->setEnabled(true);
ui->previewstopbtn->setEnabled(false);
}
void MainWindow::on_dbsavebtn_clicked()
{
//input image to database
//phuckDlg *dialog = new phuckDlg(this);
//dialog->setModal(true);
//dialog->show();
//qDebug() << "----begin---update";
if(ui->db_editname->text().isEmpty())
{
QMessageBox::critical(NULL, "critical", tr("name is empty!"), QMessageBox::Yes);
return;
}
if(ui->db_editname->text().length() > 64)
{
QMessageBox::critical(NULL, "critical", tr("name length is more than 64!"), QMessageBox::Yes);
return;
}
int index = 1;
index = ui->db_editid->text().toInt();
//qDebug() << "----begin---update---index:" << index;
std::map<int, DataInfo *>::iterator iter = m_datalst.find(index);
if(iter == m_datalst.end())
{
return;
}
QString str = m_image_tmp_path + iter->second->image_path;
QFileInfo fileinfo(str);
bool imageupdate = false;
float features[1024];
SeetaRect rect;
if(fileinfo.isFile())
{
//imageupdate = true;
QString cropfile = m_image_tmp_path + gcrop_prefix + iter->second->image_path;
float features[1024];
int nret = m_videothread->checkimage(str, cropfile, features, rect);
QString strerror;
if(nret == -2)
{
strerror = "do not find face!";
}else if(nret == -1)
{
strerror = str + " is invalid!";
}else if(nret == 1)
{
strerror = "find more than one face!";
}else if(nret == 2)
{
strerror = "quality check failed!";
}
if(!strerror.isEmpty())
{
QFile::remove(str);
QMessageBox::critical(NULL,"critical", strerror, QMessageBox::Yes);
return;
}
}
//qDebug() << "---1-begin---update---index:" << index;
QSqlQuery query;
if(imageupdate)
{
query.prepare("update " + m_table + " set name = :name, feature_data=:feature_data, facex=:facex,facey=:facey,facewidth=:facewidth,faceheight=:faceheight where id=" + QString::number(index));
QByteArray bytearray;
bytearray.resize(1024 * sizeof(float));
memcpy(bytearray.data(), features, 1024 * sizeof(float));
query.bindValue(":feature_data", QVariant(bytearray));
query.bindValue(":facex", rect.x);
query.bindValue(":facey", rect.y);
query.bindValue(":facewidth", rect.width);
query.bindValue(":faceheight", rect.height);
}else
{
query.prepare("update " + m_table + " set name = :name where id=" + QString::number(index));
}
query.bindValue(":name", ui->db_editname->text());//fileinfo.fileName());//strfile);
if(!query.exec())
{
if(imageupdate)
{
QFile::remove(str);
QFile::remove(m_image_tmp_path + gcrop_prefix + iter->second->image_path);
}
//QFile::remove()
//qDebug() << "failed to update table:" << query.lastError();
QMessageBox::critical(NULL, "critical", tr("update data to database failed!"), QMessageBox::Yes);
return;
}
//qDebug() << "---ddd-begin---update---index:" << index;
iter->second->name = ui->db_editname->text();
if(imageupdate)
{
memcpy(iter->second->features, features, 1024 * sizeof(float));
//qDebug() << "---image-begin---update---index:" << index << ",image:" << str;
QFile::remove(m_image_path + iter->second->image_path);
QFile::remove(m_image_path + gcrop_prefix + iter->second->image_path);
QFile::copy(str, m_image_path + iter->second->image_path);
QFile::copy(m_image_tmp_path + gcrop_prefix + iter->second->image_path, m_image_path + gcrop_prefix + iter->second->image_path);
QFile::remove(str);
QFile::remove(m_image_tmp_path + gcrop_prefix + iter->second->image_path);
}
int row = ui->dbtableview->currentIndex().row();
//qDebug() << "showfaceinfo:" << row ;
if(row >= 0)
{
QModelIndex index = m_model->index(row, 1);
m_model->itemFromIndex(index)->setText(ui->db_editname->text());
//qDebug() << "---image-begin---update---index:" << index << ",image:" << str;
if(imageupdate)
{
index = m_model->index(row, 2);
ui->dbtableview->indexWidget(index)->setStyleSheet("border-image:url(" + m_image_path + iter->second->image_path + ")");
ui->db_editcrop->setStyleSheet("border-image:url(" + m_image_path + gcrop_prefix + iter->second->image_path + ")");
}
}
QMessageBox::information(NULL, "info", tr("update name to database success!"), QMessageBox::Yes);
}
void MainWindow::on_previewrunbtn_clicked()
{
m_videothread->m_exited = false;
m_videothread->start(m_type);
ui->previewrunbtn->setEnabled(false);
ui->previewstopbtn->setEnabled(true);
}
void MainWindow::on_previewstopbtn_clicked()
{
m_videothread->m_exited = true;
}
void MainWindow::on_settingsavebtn_clicked()
{
/*
ResetModelProcessDlg dialog(this, m_resetmodelthread);
//m_resetmodelthread->start(&m_datalst, m_table, fr);
int nret = dialog.exec();
qDebug() << "ResetModelProcessDlg:" << nret;
if(nret != QDialog::Accepted)
{
QMessageBox::critical(NULL, "critical", "reset face recognizer model failed!", QMessageBox::Yes);
return;
}
return;
*/
//////////////////////////////////
int size = ui->fdminfacesize->text().toInt();
if(size < 20 || size > 1000)
{
QMessageBox::warning(NULL, "warn", "Face Detector Min Face Size is invalid!", QMessageBox::Yes);
return;
}
float value = ui->fdthreshold->text().toFloat();
if(value >= 1.0 || value < 0.0)
{
QMessageBox::warning(NULL, "warn", "Face Detector Threshold is invalid!", QMessageBox::Yes);
return;
}
value = ui->antispoofclarity->text().toFloat();
if(value >= 1.0 || value < 0.0)
{
QMessageBox::warning(NULL, "warn", "Anti Spoofing Clarity is invalid!", QMessageBox::Yes);
return;
}
value = ui->antispoofreality->text().toFloat();
if(value >= 1.0 || value < 0.0)
{
QMessageBox::warning(NULL, "warn", "Anti Spoofing Reality is invalid!", QMessageBox::Yes);
return;
}
value = ui->yawlowthreshold->text().toFloat();
if(value >= 90 || value < 0.0)
{
QMessageBox::warning(NULL, "warn", "Quality Yaw Low Threshold is invalid!", QMessageBox::Yes);
return;
}
value = ui->yawhighthreshold->text().toFloat();
if(value >= 90 || value < 0.0)
{
QMessageBox::warning(NULL, "warn", "Quality Yaw High Threshold is invalid!", QMessageBox::Yes);
return;
}
value = ui->pitchlowthreshold->text().toFloat();
if(value >= 90 || value < 0.0)
{
QMessageBox::warning(NULL, "warn", "Quality Pitch Low Threshold is invalid!", QMessageBox::Yes);
return;
}
value = ui->pitchhighthreshold->text().toFloat();
if(value >= 90 || value < 0.0)
{
QMessageBox::warning(NULL, "warn", "Quality Pitch High Threshold is invalid!", QMessageBox::Yes);
return;
}
value = ui->fr_threshold->text().toFloat();
if(value >= 1.0 || value < 0.0)
{
QMessageBox::warning(NULL, "warn", "Face Recognizer Threshold is invalid!", QMessageBox::Yes);
return;
}
QString strmodel = ui->fr_modelpath->text().trimmed();
QFileInfo fileinfo(gmodelpath.c_str() + strmodel);
if(QString::compare(fileinfo.suffix(), "csta", Qt::CaseInsensitive) != 0)
{
QMessageBox::warning(NULL, "warn", "Face Recognizer model file is invalid!", QMessageBox::Yes);
return;
}
QMessageBox::StandardButton result;
if(QString::compare(gparamters.Fr_ModelPath, ui->fr_modelpath->text().trimmed()) != 0)
{
result = QMessageBox::warning(NULL, "warning", "Set new face recognizer model need reset features, Are you sure?", QMessageBox::Yes | QMessageBox::No);
if(result == QMessageBox::No)
{
return;
}
seeta::FaceRecognizer * fr = m_videothread->CreateFaceRecognizer(ui->fr_modelpath->text().trimmed());
ResetModelProcessDlg dialog(this, m_resetmodelthread);
m_resetmodelthread->start(&m_datalst, m_table, fr);
int nret = dialog.exec();
qDebug() << "ResetModelProcessDlg:" << nret;
if(nret != QDialog::Accepted)
{
delete fr;
QMessageBox::critical(NULL, "critical", "reset face recognizer model failed!", QMessageBox::Yes);
return;
}
m_videothread->set_fr(fr);
}
QString sql("update " + m_config_table + " set fd_minfacesize=%1, fd_threshold=%2, antispoof_clarity=%3, antispoof_reality=%4,");
sql += "qa_yawlow=%5, qa_yawhigh=%6, qa_pitchlow=%7, qa_pitchhigh=%8, fr_threshold=%9,fr_modelpath=\"%10\"";
sql = QString(sql).arg(ui->fdminfacesize->text()).arg(ui->fdthreshold->text()).arg(ui->antispoofclarity->text()).arg(ui->antispoofreality->text()).
arg(ui->yawlowthreshold->text()).arg(ui->yawhighthreshold->text()).arg(ui->pitchlowthreshold->text()).arg(ui->pitchhighthreshold->text()).
arg(ui->fr_threshold->text()).arg(ui->fr_modelpath->text().trimmed());
QSqlQuery q(sql);
//qDebug() << sql;
//QSqlQuery q("update " + m_config_table + " set min_face_size =" + ui->fdminfacesize->text() );
if(!q.exec())
{
QMessageBox::critical(NULL, "critical", "update setting failed!", QMessageBox::Yes);
return;
}
gparamters.MinFaceSize = ui->fdminfacesize->text().toInt();
gparamters.Fd_Threshold = ui->fdthreshold->text().toFloat();
gparamters.AntiSpoofClarity = ui->antispoofclarity->text().toFloat();
gparamters.AntiSpoofReality = ui->antispoofreality->text().toFloat();
gparamters.YawLowThreshold = ui->yawlowthreshold->text().toFloat();
gparamters.YawHighThreshold = ui->yawhighthreshold->text().toFloat();
gparamters.PitchLowThreshold = ui->pitchlowthreshold->text().toFloat();
gparamters.PitchHighThreshold = ui->pitchhighthreshold->text().toFloat();
gparamters.Fr_Threshold = ui->fr_threshold->text().toFloat();
gparamters.Fr_ModelPath = ui->fr_modelpath->text().trimmed();
m_videothread->setparamter();
QMessageBox::information(NULL, "info", "update setting ok!", QMessageBox::Yes);
}
void MainWindow::on_rotatebtn_clicked()
{
QMatrix matrix;
matrix.rotate(90);
int id = ui->db_editid->text().toInt();
std::map<int, DataInfo *>::iterator iter = m_datalst.find(id);
if(iter == m_datalst.end())
{
return;
}
//QFile::remove(m_image_tmp_path + iter->second->image_path);
if(!QFile::exists(m_image_tmp_path + iter->second->image_path))
{
QFile::copy(m_image_path + iter->second->image_path, m_image_tmp_path + iter->second->image_path);
}
if(!QFile::exists(m_image_tmp_path + gcrop_prefix + iter->second->image_path))
{
QFile::copy(m_image_path + gcrop_prefix + iter->second->image_path, m_image_tmp_path + gcrop_prefix + iter->second->image_path);
}
//QFile::copy(m_image_path + iter->second->image_path, m_image_tmp_path + iter->second->image_path);
QImage image(m_image_tmp_path + iter->second->image_path);
if(image.isNull())
return;
image = image.transformed(matrix, Qt::FastTransformation);
image.save(m_image_tmp_path + iter->second->image_path);
ui->db_editpicture->setStyleSheet("border-image:url(" + m_image_tmp_path + iter->second->image_path + ")");
///////////////////////
//QMatrix cropmatrix;
matrix.reset();
matrix.rotate(90);
QImage cropimage(m_image_tmp_path + gcrop_prefix + iter->second->image_path);
if(cropimage.isNull())
return;
cropimage = cropimage.transformed(matrix, Qt::FastTransformation);
cropimage.save(m_image_tmp_path + gcrop_prefix + iter->second->image_path);
ui->db_editcrop->setStyleSheet("border-image:url(" + m_image_tmp_path + gcrop_prefix + iter->second->image_path + ")");
}
void MainWindow::on_tabWidget_currentChanged(int index)
{
//qDebug() << "cur:" << ui->tabWidget->tabText(index) << ",old:" << ui->tabWidget->tabText(m_currenttab) ;
if(m_currenttab != index)
{
if(m_currenttab == 2)
{
on_previewstopbtn_clicked();
m_videothread->wait();
}
m_currenttab = index;
}
//qDebug() << "tab:" << ui->tabWidget->tabText(index) << ",cur:" << index << ",old:" << ui->tabWidget->currentIndex();
}
void MainWindow::on_addimagebtn_clicked()
{
QString fileName = QFileDialog::getOpenFileName(this, tr("open image file"),
"./" ,
"JPEG Files(*.jpg *.jpeg);;PNG Files(*.png);;BMP Files(*.bmp)");
//qDebug() << "image:" << fileName;
QImage image(fileName);
if(image.isNull())
return;
QFile file(fileName);
QFileInfo fileinfo(fileName);
//////////////////////////////
QSqlQuery query;
query.prepare("insert into " + m_table + " (id, name, image_path, feature_data, facex,facey,facewidth,faceheight) values (:id, :name, :image_path, :feature_data,:facex,:facey,:facewidth,:faceheight)");
int index = 1;
if(m_model->rowCount() > 0)
{
index = m_model->item(m_model->rowCount() - 1, 0)->text().toInt() + 1;
}
QString strfile = QString::number(index) + "_" + fileinfo.fileName();//m_image_path + QString::number(index) + "_" + m_currentimagefile;//fileinfo.fileName();
QString cropfile = m_image_path + gcrop_prefix + strfile;
float features[1024];
SeetaRect rect;
int nret = m_videothread->checkimage(fileName, cropfile, features, rect);
QString strerror;
if(nret == -2)
{
strerror = "do not find face!";
}else if(nret == -1)
{
strerror = fileName + " is invalid!";
}else if(nret == 1)
{
strerror = "find more than one face!";
}else if(nret == 2)
{
strerror = "quality check failed!";
}
if(!strerror.isEmpty())
{
QMessageBox::critical(NULL,"critical", strerror, QMessageBox::Yes);
return;
}
QString name = fileinfo.completeBaseName();//fileName();
int n = name.indexOf("_");
if(n >= 1)
{
name = name.left(n);
}
query.bindValue(0, index);
query.bindValue(1,name);
//query.bindValue(2, "/wqy/Downloads/ap.jpeg");
query.bindValue(2, strfile);//fileinfo.fileName());//strfile);
//float data[4] = {0.56,0.223,0.5671,-0.785};
QByteArray bytearray;
bytearray.resize(1024 * sizeof(float));
memcpy(bytearray.data(), features, 1024 * sizeof(float));
query.bindValue(3, QVariant(bytearray));
query.bindValue(4, rect.x);
query.bindValue(5, rect.y);
query.bindValue(6, rect.width);
query.bindValue(7, rect.height);
if(!query.exec())
{
QFile::remove(cropfile);
qDebug() << "failed to insert table:" << query.lastError();
QMessageBox::critical(NULL, "critical", tr("save face data to database failed!"), QMessageBox::Yes);
return;
}
file.copy(m_image_path + strfile);
DataInfo * info = new DataInfo();
info->id = index;
info->name = name;
info->image_path = strfile;
memcpy(info->features, features, 1024 * sizeof(float));
info->x = rect.x;
info->y = rect.y;
info->width = rect.width;
info->height = rect.height;
m_datalst.insert(std::map<int, DataInfo *>::value_type(index, info));
////////////////////////////////////////////////////////////
int rows = m_model->rowCount();
//qDebug() << "rows:" << rows;
m_model->setItem(rows, 0, new QStandardItem(QString::number(index)));
m_model->setItem(rows, 1, new QStandardItem(info->name));
QLabel *label = new QLabel("");
label->setStyleSheet("border-image:url(" + m_image_path + strfile + ")");
ui->dbtableview->setIndexWidget(m_model->index(rows, 2), label);
QPushButton *button2 = new QPushButton("delete");
button2->setProperty("id", index);
button2->setFixedSize(80, 40);
connect(button2, SIGNAL(clicked()), this, SLOT(deleterecord()));
QWidget *widget = new QWidget();
QHBoxLayout *layout = new QHBoxLayout;
layout->addStretch();
layout->addWidget(button2);
layout->addStretch();
widget->setLayout(layout);
ui->dbtableview->setIndexWidget(m_model->index(rows, 3), widget);
ui->dbtableview->scrollToBottom();
ui->dbtableview->selectRow(rows);
emit ui->dbtableview->clicked(m_model->index(rows, 1));
//QMessageBox::information(NULL, "info", tr("add face operator success!"), QMessageBox::Yes);
}
void MainWindow::on_menufacedbbtn_clicked()
{
ui->tabWidget->setCurrentIndex(1);
}
void MainWindow::on_menusettingbtn_clicked()
{
ui->tabWidget->setCurrentIndex(3);
}
void MainWindow::on_previewclearbtn_clicked()
{
ui->previewtableview->setUpdatesEnabled(false);
m_videomodel->removeRows(0, m_videomodel->rowCount());
//m_videomodel->clear();
ui->previewtableview->setUpdatesEnabled(true);
}
void MainWindow::on_menuopenvideofile_clicked()
{
QString fileName = QFileDialog::getOpenFileName(this, tr("open video file"),
"./" ,
"MP4 Files(*.mp4 *.MP4);;AVI Files(*.avi);;FLV Files(*.flv);;h265 Files(*.h265);;h263 Files(*.h263)");
//qDebug() << "image:" << fileName;
m_type.type = 1;
m_type.filename = fileName;
m_type.title = "Open Video: " + fileName;
ui->recognize_label->setText(m_type.title);
ui->tabWidget->setCurrentIndex(2);
emit ui->previewrunbtn->clicked();
}
void MainWindow::on_menuopenpicturefile_clicked()
{
QString fileName = QFileDialog::getOpenFileName(this, tr("open image file"),
"./" ,
"JPEG Files(*.jpg *.jpeg);;PNG Files(*.png);;BMP Files(*.bmp)");
//qDebug() << "image:" << fileName;
m_type.type = 2;
m_type.filename = fileName;
m_type.title = "Open Image: " + fileName;
ui->recognize_label->setText(m_type.title);
ui->tabWidget->setCurrentIndex(2);
emit ui->previewrunbtn->clicked();
}
void MainWindow::on_menuopencamera_clicked()
{
m_type.type = 0;
m_type.filename = "";
m_type.title = "Open Camera: 0";
ui->recognize_label->setText(m_type.title);
ui->tabWidget->setCurrentIndex(2);
emit ui->previewrunbtn->clicked();
}
static void FindFile(const QString & path, QStringList &files)
{
QDir dir(path);
if(!dir.exists())
return;
dir.setFilter(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot | QDir::NoSymLinks);
dir.setSorting(QDir::DirsFirst);;
QFileInfoList list = dir.entryInfoList();
int i = 0;
while(i < list.size())
{
QFileInfo info = list.at(i);
//qDebug() << info.absoluteFilePath();
if(info.isDir())
{
FindFile(info.absoluteFilePath(), files);
}else
{
QString str = info.suffix();
if(str.compare("png", Qt::CaseInsensitive) == 0 || str.compare("jpg", Qt::CaseInsensitive) == 0 || str.compare("jpeg", Qt::CaseSensitive) == 0 || str.compare("bmp", Qt::CaseInsensitive) == 0)
{
files.append(info.absoluteFilePath());
}
}
i++;
}
return;
}
void MainWindow::on_addfilesbtn_clicked()
{
QString fileName = QFileDialog::getExistingDirectory(this, tr("Select Directorky"), ".");
if(fileName.isEmpty())
{
return;
}
qDebug() << fileName;
QStringList files;
FindFile(fileName, files);
qDebug() << files.size();
if(files.size() <= 0)
return;
for(int i=0; i<files.size(); i++)
{
qDebug() << files.at(i);
}
qDebug() << files.size();
//return;
int index = 1;
if(m_model->rowCount() > 0)
{
index = m_model->item(m_model->rowCount() - 1, 0)->text().toInt();
}
InputFilesProcessDlg dialog(this, m_inputfilesthread);
m_inputfilesthread->start(&files, index, m_table);
dialog.exec();
//qDebug() << "------on_addfilesbtn_clicked---end";
}
void MainWindow::oninputfilesupdateui(std::vector<DataInfo *> * datas)
{
DataInfo * info = NULL;
//qDebug() << "----oninputfilesupdateui--" << datas->size();
if(datas->size() > 0)
{
ui->dbtableview->setUpdatesEnabled(false);
}
int rows = 0;
for(int i=0; i<datas->size(); i++)
{
rows = m_model->rowCount();
//qDebug() << "rows:" << rows;
info = (*datas)[i];
m_datalst.insert(std::map<int, DataInfo *>::value_type(info->id, info));
m_model->setItem(rows, 0, new QStandardItem(QString::number(info->id)));
m_model->setItem(rows, 1, new QStandardItem(info->name));
QLabel *label = new QLabel("");
label->setStyleSheet("border-image:url(" + m_image_path + info->image_path + ")");
ui->dbtableview->setIndexWidget(m_model->index(rows, 2), label);
QPushButton *button2 = new QPushButton("delete");
button2->setProperty("id", info->id);
button2->setFixedSize(80, 40);
connect(button2, SIGNAL(clicked()), this, SLOT(deleterecord()));
ui->dbtableview->setIndexWidget(m_model->index(rows, 3), button2);
//ui->dbtableview->scrollToBottom();
//ui->dbtableview->selectRow(rows);
}
if(datas->size() > 0)
{
ui->dbtableview->setUpdatesEnabled(true);
ui->dbtableview->scrollToBottom();
ui->dbtableview->selectRow(rows);
emit ui->dbtableview->clicked(m_model->index(rows, 1));
}
}
void MainWindow::on_settingselectmodelbtn_clicked()
{
QString fileName = QFileDialog::getOpenFileName(this, tr("open model file"),
"./" ,
"CSTA Files(*.csta)");
QFileInfo fileinfo(fileName);
QString modelfile = fileinfo.fileName();
QString str = gmodelpath.c_str() + modelfile;
qDebug() << "------str:" << str;
qDebug() << "fileName:" << fileName;
if(QString::compare(fileName, str) == 0)
{
ui->fr_modelpath->setText(modelfile);
return;
}
//QFile file(fileName);
if(!QFile::copy(fileName, str))
{
QMessageBox::critical(NULL, "critical", "Copy model file: " + fileName + " to " + gmodelpath.c_str() + " failed, file already exists!", QMessageBox::Yes);
return;
}
ui->fr_modelpath->setText(modelfile);
//m_videothread->reset_fr_model(modelfile);
//qDebug() << "image:" << fileName;
}
void MainWindow::closeEvent(QCloseEvent *event)
{
m_videothread->m_exited = true;
m_videothread->wait();
QWidget::closeEvent(event);
}
| 19,938 |
394 | <gh_stars>100-1000
from django.db import models
# Put your test models here
| 25 |
4,071 | /* Copyright (C) 2016-2018 Alibaba Group Holding Limited
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "gtest/gtest.h"
#include "xdl/core/framework/graph_def.h"
#include "xdl/core/framework/grappler.h"
using xdl::AttrValue;
using xdl::NodeDef;
using xdl::DataType;
using xdl::OutputSpec;
using xdl::TensorShape;
using xdl::Status;
using xdl::GraphDef;
using xdl::Grappler;
using xdl::GrapplerRegistry;
namespace {
GraphDef CreateDef() {
NodeDef a, b, c;
a.name = "a";
a.op = "MockConstant";
a.device.device_name = "CPU";
a.attr["dtype"].attr_type = AttrValue::kDataType;
a.attr["dtype"].type = DataType::kInt64;
a.attr["shape"].attr_type = AttrValue::kTensorShape;
a.attr["shape"].shape = TensorShape({10, 20});
b.name = "b";
b.op = "MockConstant";
b.device.device_name = "CPU";
b.attr["dtype"].attr_type = AttrValue::kDataType;
b.attr["dtype"].type = DataType::kInt64;
b.attr["shape"].attr_type = AttrValue::kTensorShape;
b.attr["shape"].shape = TensorShape({10, 20});
b.attr["value"].attr_type = AttrValue::kInt;
b.attr["value"].i = 20;
c.name = "c";
c.op = "MockMulAdd";
c.device.device_name = "CPU";
c.input.push_back("a:0");
c.input.push_back("b:0");
c.attr["dtype"].attr_type = AttrValue::kDataType;
c.attr["dtype"].type = DataType::kInt64;
c.attr["add"].attr_type = AttrValue::kInt;
c.attr["add"].i = 30;
GraphDef ret;
ret.node.push_back(a);
ret.node.push_back(b);
ret.node.push_back(c);
ret.hash = 123;
return ret;
}
OutputSpec CreateOutput() {
OutputSpec ret;
ret.output.push_back("c:0");
ret.output_device.device_name = "CPU";
return ret;
}
}
TEST(GrapplerTest, Grappler) {
xdl::GraphDef def = CreateDef();
xdl::OutputSpec output = CreateOutput();
GrapplerRegistry *registry = GrapplerRegistry::Get();
ASSERT_TRUE(registry != nullptr);
Status st = registry->Process(&def, &output);
ASSERT_EQ(st, Status::Ok());
}
| 913 |
1,162 | package io.digdag.core.queue;
import java.time.Instant;
import com.google.common.base.*;
import com.google.common.collect.*;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.immutables.value.Value;
@Value.Immutable
@JsonSerialize(as = ImmutableStoredQueueSetting.class)
@JsonDeserialize(as = ImmutableStoredQueueSetting.class)
public abstract class StoredQueueSetting
extends QueueSetting
{
public abstract long getId();
public abstract int getSiteId();
public abstract Instant getCreatedAt();
public abstract Instant getUpdatedAt();
}
| 213 |
370 | {
"displayName": "Compute Engine default service account",
"email": "<EMAIL>",
"name": "projects/k8s-infra-e2e-boskos-scale-29/serviceAccounts/<EMAIL>",
"oauth2ClientId": "116709224701301223722",
"projectId": "k8s-infra-e2e-boskos-scale-29",
"uniqueId": "116709224701301223722"
}
| 125 |
Subsets and Splits