max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
1,473
package com.navercorp.pinpoint.common.util; import org.apache.commons.lang3.RandomUtils; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.IOException; public class IOUtilsTest { @Test public void toByteArray_small() throws IOException { assertToByteArray(0); assertToByteArray(1); assertToByteArray(32); assertToByteArray(256); assertToByteArray(512); assertToByteArray(1024); } @Test public void toByteArray_large() throws IOException { assertToByteArray(IOUtils.DEFAULT_BUFFER_SIZE - 1); assertToByteArray(IOUtils.DEFAULT_BUFFER_SIZE); assertToByteArray(IOUtils.DEFAULT_BUFFER_SIZE + 1); assertToByteArray(IOUtils.DEFAULT_BUFFER_SIZE * 4); assertToByteArray(IOUtils.DEFAULT_BUFFER_SIZE * 8); } @Test public void toByteArray_large2() throws IOException { // assertByteReadTest(IOUtils.DEFAULT_BUFFER_SIZE - 1); // assertByteReadTest(IOUtils.DEFAULT_BUFFER_SIZE); // assertByteReadTest(IOUtils.DEFAULT_BUFFER_SIZE + 1); assertToByteArray(IOUtils.DEFAULT_BUFFER_SIZE * 4); // assertByteReadTest(IOUtils.DEFAULT_BUFFER_SIZE * 4); } @Test public void toByteArray_available_unsupported() throws IOException { assertToByteArray(IOUtils.DEFAULT_BUFFER_SIZE * 2, 0); assertToByteArray(IOUtils.DEFAULT_BUFFER_SIZE * 2, 1); } @Test public void toByteArray_available_return4096() throws IOException { assertToByteArray(IOUtils.DEFAULT_BUFFER_SIZE + 1, 4096); assertToByteArray(IOUtils.DEFAULT_BUFFER_SIZE, 4096); assertToByteArray(IOUtils.DEFAULT_BUFFER_SIZE + 1, 4096); assertToByteArray(IOUtils.DEFAULT_BUFFER_SIZE * 2, 4096); assertToByteArray(IOUtils.DEFAULT_BUFFER_SIZE * 5, 4096); assertToByteArray(IOUtils.DEFAULT_BUFFER_SIZE * 10, 4096); } @Test public void toByteArray_available_os_buffer_small() throws IOException { assertToByteArray(IOUtils.DEFAULT_BUFFER_SIZE + 1, 4096, 1024); assertToByteArray(IOUtils.DEFAULT_BUFFER_SIZE, 4096); assertToByteArray(IOUtils.DEFAULT_BUFFER_SIZE + 1, 4096, 1024); assertToByteArray(IOUtils.DEFAULT_BUFFER_SIZE * 2, 4096, 1024); assertToByteArray(IOUtils.DEFAULT_BUFFER_SIZE * 5, 4096, 1024); assertToByteArray(IOUtils.DEFAULT_BUFFER_SIZE * 10, 4096, 1024); } private void assertToByteArray(final int sourceBytesSize) throws IOException { assertToByteArray(sourceBytesSize, sourceBytesSize); } private void assertToByteArray(final int sourceBytesSize, final int available) throws IOException { assertToByteArray(sourceBytesSize, available, Integer.MAX_VALUE); } private void assertToByteArray(final int sourceBytesSize, final int available, final int osBuffer) throws IOException { byte[] source = RandomUtils.nextBytes(sourceBytesSize); ByteArrayInputStream inputStream = new ByteArrayInputStream(source) { @Override public synchronized int available() { return available; } @Override public synchronized int read(byte[] b, int off, int len) { // os buffer emulation int min = Math.min(len, osBuffer); return super.read(b, off, min); } }; byte[] bytes = IOUtils.toByteArray(inputStream); org.junit.Assert.assertArrayEquals(source, bytes); } }
1,485
348
{"nom":"Croixdalle","circ":"6ème circonscription","dpt":"Seine-Maritime","inscrits":241,"abs":128,"votants":113,"blancs":1,"nuls":4,"exp":108,"res":[{"nuance":"FN","nom":"M. <NAME>","voix":39},{"nuance":"REM","nom":"M. <NAME>","voix":27},{"nuance":"COM","nom":"<NAME>","voix":16},{"nuance":"UDI","nom":"Mme <NAME>","voix":13},{"nuance":"SOC","nom":"Mme <NAME>","voix":11},{"nuance":"DVG","nom":"M. <NAME>","voix":2},{"nuance":"EXG","nom":"M. <NAME>","voix":0},{"nuance":"DIV","nom":"M. <NAME>","voix":0}]}
206
1,056
/* * 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.netbeans.modules.css.model.impl; import org.netbeans.modules.css.lib.api.Node; import org.netbeans.modules.css.lib.api.properties.Properties; import org.netbeans.modules.css.lib.api.properties.PropertyDefinition; import org.netbeans.modules.css.lib.api.properties.ResolvedProperty; import org.netbeans.modules.css.model.api.Expression; import org.netbeans.modules.css.model.api.Model; import org.netbeans.modules.css.model.api.Prio; import org.netbeans.modules.css.model.api.Property; import org.netbeans.modules.css.model.api.PropertyDeclaration; import org.netbeans.modules.css.model.api.PropertyValue; import org.openide.filesystems.FileObject; /** * * @author marekfukala */ public class PropertyDeclarationI extends ModelElement implements PropertyDeclaration { private Property property; private PropertyValue propertyValue; private Prio prio; private ResolvedProperty resolvedProperty; private final ModelElementListener elementListener = new ModelElementListener.Adapter() { @Override public void elementAdded(PropertyValue value) { propertyValue = value; } @Override public void elementAdded(Property value) { property = value; } @Override public void elementAdded(Prio value) { prio = value; } }; public PropertyDeclarationI(Model model) { super(model); //default elements addTextElement(getIndent()); //not acc. to the grammar! addEmptyElement(Property.class); addTextElement(":"); addTextElement(" "); addEmptyElement(PropertyValue.class); addEmptyElement(Prio.class); } public PropertyDeclarationI(Model model, Node node) { super(model, node); initChildrenElements(); } @Override public Property getProperty() { return property; } @Override public void setProperty(Property property) { setElement(property); } @Override public PropertyValue getPropertyValue() { return propertyValue; } @Override public void setPropertyValue(PropertyValue value) { setElement(value); } @Override public Prio getPrio() { return prio; } @Override public void setPrio(Prio prio) { setElement(prio); } @Override protected ModelElementListener getElementListener() { return elementListener; } @Override protected Class getModelClass() { return PropertyDeclaration.class; } @Override public synchronized ResolvedProperty getResolvedProperty() { FileObject file = getModel().getLookup().lookup(FileObject.class); if (resolvedProperty == null) { PropertyDefinition pmodel = Properties.getPropertyDefinition(getProperty().getContent().toString().trim()); if (pmodel != null) { Expression expression = getPropertyValue().getExpression(); CharSequence content = expression != null ? expression.getContent() : ""; resolvedProperty = ResolvedProperty.resolve(file, pmodel, content); } } return resolvedProperty; } @Override public String toString() { StringBuilder b = new StringBuilder(); b.append(getClass().getSimpleName()); b.append("("); Property p = getProperty(); b.append(p == null ? "null" : p.getContent()); PropertyValue pv = getPropertyValue(); b.append(":"); Expression e = pv == null ? null : pv.getExpression(); b.append(e == null ? "null" : e.getContent()); b.append(getPrio() == null ? "" : "!"); b.append(")"); return b.toString(); } }
1,659
337
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; class A { @Nullable public Integer foo(int i, @NotNull String s) { return null; } }
75
5,937
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //+----------------------------------------------------------------------------- // // // $TAG ENGR // $Module: win_mil_graphics_geometry // $Keywords: // $File name: PathGeometryWrapper.cpp // // $ENDTAG // //------------------------------------------------------------------------------ // Description: // // PathGeometryData implements IShapeData, an interface that abstracts away direct // knowledge of the geometry storage representation. This wrapper class understands a // linear shape data representation constructed by the managed Geometry classes. This // is necessary to bridge the gap between our managed Geometry classes and low level // computational geometry services. // // First, milcoretypes.w contains the definition of some structs, each associated with // a Geometry related class (some properties for background are in braces) // // MilPathGeometry - PathGeometry (eg, fill rule, figure count, etc.) // MilPathFigure - PathFigure (eg, IsFillable, segment count, etc.) // MilSegmentLine - LineSegment (eg, Point) // MilSegmentBezier - BezierSegment (eg, Point1, Point2, Point3) // MilSegmentQuadraticBezier - QuadraticBezierSegment (eg, Point1, Point2) // MilSegmentArc - ArcSegment (eg, Point, Size, XRotation, etc) // MilSegmentPoly - PolyLineSegment, PolyBezierSegment, PolyQuadraticBezierSegment // (eg, Count) // // This class is passed a chunk of memory formatted as follows: // // (A) (B) (C) // +----------+----------+----------+---+---------+----------+--- // | MIL_PATH | MIL_PATH | MIL_SEG_ | | MIL_PATH | MIL_SEG | // | GEOMETRY | FIGURE | LINE |...| FIGURE | LINE |... // | | | | | | | // +----------+----------+----------+---+----------+---------+--- // // 1. The header always begins with a MilPathGeometry struct. // 2. This is followed by a MilPathFigure struct // 3. This is followed by MIL_SEGMENT_* structs (the number of such segments is in // MilPathFigure) // 4. The pattern of (2) and (3) is repeated for the number of figures // (in MIL_PATHGEOMETY) // // The only twist on the above is the case of MilSegmentPoly struct, which represents // a set of points interpreted as poly line, poly bezier, or poly quadratic bezier // points. These points immediately follow the struct. The size of computed by taking // MilSegmentPoly.Count*sizeof(MilPoint2D). // // In this way, the PathGeometry object tree consisting of PathFigures, // PathFigureCollections, PathSegmentCollections, PathSegments, etc. is flattened into // an easily accessible linear representation. All content needed to resolve // animations and compute instantaneous values are contained within. // // PathGeometryData understands how to address this structure. It mains a "current // figure" state that the caller can use to traverse the figures and access properties, // etc. // // PathFigureData implements IFigureData, an interface that abstracts away direct // knowledge of the figure storage representation. This wrapper class understands how // to deal with memory formatted as between (B) and (C) above. It provides services to // query per figure properties, and enumerate the segments of the figure. It mains a // "current segment" state the caller can use to traverse the segments and access // properties, etc. // // See mil\geometry\shape.* and mil\geometry\figure.* for details on the usage pattern // of IShapeData and IFigureData. // // NOTE: To ensure we do not hit misalignment exceptions in 64-bit, all structs are // packed to be 8-byte aligned. #include "precomp.hpp" inline MilPoint2F ConvertToSingle(MilPoint2D pt) { MilPoint2F ptF; ptF.X = static_cast<FLOAT> (pt.X); ptF.Y = static_cast<FLOAT> (pt.Y); return ptF; } //+----------------------------------------------------------------------------- // // Class: // PathFigureData // // Synopsis: // Interface for access and queries on figure data // //------------------------------------------------------------------------------ //+----------------------------------------------------------------------------- // // Member: // PathFigureData::PathFigureData // // Synopsis: // Constructor for PathFigureData // //------------------------------------------------------------------------------ PathFigureData::PathFigureData() { SetFigureData(NULL, 0, NULL); } //+----------------------------------------------------------------------------- // // Member: // PathFigureData::PathFigureData // // Synopsis: // Initialize contents of PathFigureData through constructor // //------------------------------------------------------------------------------ PathFigureData::PathFigureData(MilPathFigure *pFigure, UINT nSize, const CMILMatrix *pMatrix) { SetFigureData(pFigure, nSize, pMatrix); } //+----------------------------------------------------------------------------- // // Member: // PathFigureData::SetFigureData // // Synopsis: // Initialize contents of PathFigureData // //------------------------------------------------------------------------------ VOID PathFigureData::SetFigureData(MilPathFigure *pFigure, UINT nSize, const CMILMatrix *pMatrix) { m_pFigure = pFigure; m_nSize = nSize; if (pMatrix && pMatrix->IsIdentity()) { m_pMatrix = NULL; } else { m_pMatrix = pMatrix; } m_pCurSegment = GetFirstSegment(); Assert(m_pCurSegment != NULL); m_uCurIndex = m_uStop = m_uInnerStop = UINT_MAX; m_uInnerIndex = 0; m_fEndPointValid = FALSE; m_uCurPoint = 0; } //+----------------------------------------------------------------------------- // // Member: // PathFigureData::SetInnerIndexToLast // // Synopsis: // Set the inner segment index to the last inner index // //------------------------------------------------------------------------------ void PathFigureData::SetInnerIndexToLast() const { Assert(m_pCurSegment != NULL); switch (m_pCurSegment->Type) { case MilSegmentType::None: case MilSegmentType::Line: case MilSegmentType::Bezier: case MilSegmentType::QuadraticBezier: m_uInnerIndex = 0; break; case MilSegmentType::Arc: // Arc data should have been set in SetArcData, which should have // been called before this call m_uInnerIndex = m_uLastInnerIndex; m_uCurPoint = 3 * m_uLastInnerIndex; break; case MilSegmentType::PolyLine: { const MilSegmentPoly *pPolySegment = static_cast<MilSegmentPoly*> (m_pCurSegment); Assert(pPolySegment->Count != 0); m_uInnerIndex = pPolySegment->Count - 1; break; } case MilSegmentType::PolyBezier: { const MilSegmentPoly *pPolySegment = static_cast<MilSegmentPoly*> (m_pCurSegment); Assert(pPolySegment->Count % 3 == 0); Assert(pPolySegment->Count >=3); m_uInnerIndex = pPolySegment->Count / 3 - 1; break; } case MilSegmentType::PolyQuadraticBezier: { const MilSegmentPoly *pPolySegment = static_cast<MilSegmentPoly*> (m_pCurSegment); Assert((pPolySegment->Count & 1) == 0); Assert(pPolySegment->Count >= 2); m_uInnerIndex = (pPolySegment->Count / 2) - 1; break; } default: Assert(FALSE); break; } } //+----------------------------------------------------------------------------- // // Member: // PathFigureData::IsEmpty // // Synopsis: // Returns true if figure is empty. // //------------------------------------------------------------------------------ bool PathFigureData::IsEmpty() const { // The figure is never empty because it always have at least a start point return false; } //+----------------------------------------------------------------------------- // // Member: // PathFigureData::HasNoSegments // // Synopsis: // Returns true if there are no segments beyond the start. // //------------------------------------------------------------------------------ bool PathFigureData::HasNoSegments() const { Assert(m_pFigure != NULL); return m_pFigure->Count == 0; } //+----------------------------------------------------------------------------- // // Member: // PathFigureData::IsClosed // // Synopsis: // Returns if figure is closed. // //------------------------------------------------------------------------------ bool PathFigureData::IsClosed() const { Assert(m_pFigure != NULL); return (m_pFigure->Flags & MilPathFigureFlags::IsClosed) != 0; } //+----------------------------------------------------------------------------- // // Member: // PathFigureData::IsAtASmoothJoin // // Synopsis: // Returns true if the join at the end of the current inner segment ought // to be accepted as smooth without checking. // //------------------------------------------------------------------------------ bool PathFigureData::IsAtASmoothJoin() const { Assert(m_pFigure != NULL); Assert(m_pCurSegment != NULL); return (((m_pCurSegment->Flags & MilCoreSeg::SmoothJoin) != 0) || (m_pCurSegment->Type == MilSegmentType::Arc && m_uInnerIndex < m_uLastInnerIndex)); } //+----------------------------------------------------------------------------- // // Member: // PathFigureData::HasGaps // // Synopsis: // Returns true if figure has gaps. // //------------------------------------------------------------------------------ bool PathFigureData::HasGaps() const { Assert(m_pFigure != NULL); return (m_pFigure->Flags & MilPathFigureFlags::HasGaps) != 0; } //+----------------------------------------------------------------------------- // // Member: // PathFigureData::IsAtAGap // // Synopsis: // Returns true if the current segment is a gap (not to be stroked). // //------------------------------------------------------------------------------ bool PathFigureData::IsAtAGap() const { bool fIsAtGap = false; if (m_uCurIndex >= m_pFigure->Count) { // We're at the implied closing line segment fIsAtGap = false; } else { Assert(m_pCurSegment != NULL); fIsAtGap = ((m_pCurSegment->Flags & MilCoreSeg::IsAGap) != 0); } return fIsAtGap; } //+----------------------------------------------------------------------------- // // Member: // PathFigureData::IsFillable // // Synopsis: // Returns true if figure is fillable. // //------------------------------------------------------------------------------ bool PathFigureData::IsFillable() const { Assert(m_pFigure != NULL); return (m_pFigure->Flags & MilPathFigureFlags::IsFillable) != 0; } //+----------------------------------------------------------------------------- // // Member: // PathFigureData::IsAxisAlignedRectangle // // Synopsis: // Return true if this figure is an axis aligned rectangle // //------------------------------------------------------------------------------ bool PathFigureData::IsAxisAlignedRectangle() const { bool fIsAxisAlignedRect = false; if (IsAParallelogram()) { // We can get four points that might be a rectangle MilPoint2F points[4]; GetParallelogramVertices(points); fIsAxisAlignedRect = (RectF_RBFromParallelogramPointsF(points, NULL) == TRUE); } return fIsAxisAlignedRect; } //+----------------------------------------------------------------------------- // // Member: // PathFigureData::GetAsRectangle // // Synopsis: // Gets the rectangle of an rectangle figure. // // Notes: // The rect returned may not be well ordered. // //------------------------------------------------------------------------------ VOID PathFigureData::GetAsRectangle(__out_ecount(1) MilRectF &rect) const { Assert(IsAxisAlignedRectangle()); MilPoint2F points[4]; GetParallelogramVertices(points); rect.left = points[0].X; rect.top = points[0].Y; rect.right = points[2].X; rect.bottom = points[2].Y; } //+----------------------------------------------------------------------------- // // Member: // PathFigureData::GetAsWellOrderedRectangle // // Synopsis: // Gets the rectangle of an rectangle figure. This rectangle is guaranteed // to have positive width and height. // //------------------------------------------------------------------------------ VOID PathFigureData::GetAsWellOrderedRectangle(__out_ecount(1) MilRectF &rect) const { Assert(IsAxisAlignedRectangle()); MilPoint2F points[4]; GetParallelogramVertices(points); RectF_RBFromParallelogramPointsF(points, &rect); } //+----------------------------------------------------------------------------- // // Member: // PathFigureData::GetParallelogramVertices // // Synopsis: // Get the 4 vertices of this parallelogram figure // // Synopsis: // The caller is responsible for calling it only on a figure that has been // constructed as a (possibly transformed) rectangle with a single 3-point // polyline. This assumption is guarded by assertions. // //------------------------------------------------------------------------------ VOID PathFigureData::GetParallelogramVertices( __out_ecount(4) MilPoint2F *pVertices, // 4 Rectangle's vertices __in_ecount_opt(1) const CMILMatrix *pMatrix) const // Transformation (optional) { UINT i; CMILMatrix combined; Assert(m_pFigure->Count == 1); MilSegment *pSegment = GetFirstSegment(); Assert(MilSegmentType::PolyLine == m_pCurSegment->Type); MilSegmentPoly *pPoly = static_cast<MilSegmentPoly*>(pSegment); Assert(3 == pPoly->Count); // First vertex pVertices[0] = ConvertToSingle(m_pFigure->StartPoint); // The remaining 3 vertices const MilPoint2D *pPoints = reinterpret_cast<MilPoint2D*>(pPoly+1); for (i = 1; i <= 3; i++) { pVertices[i] = ConvertToSingle(pPoints[i-1]); } if (m_pMatrix) { if (pMatrix) { combined = *m_pMatrix; combined.Multiply(*pMatrix); pMatrix = &combined; } else { pMatrix = m_pMatrix; } } if (pMatrix) { // Transform for (i = 0; i <= 3; i++) { TransformPoint(*pMatrix, pVertices[i]); } } } //+----------------------------------------------------------------------------- // // Member: // PathFigureData::GetCountsEstimate // // Synopsis: // Computes a conservative estimate of the number of segments and point // needed for this figure // // Notes: // The estimate may not be tight because an arc segment may generate 1,2,3 // or 4 segments. // //------------------------------------------------------------------------------ HRESULT PathFigureData::GetCountsEstimate( OUT UINT &cSegments, // An estimate of the nunber of segments OUT UINT &cPoints // An estimate of the number of points ) const { HRESULT hr = S_OK; Assert(m_pFigure != NULL); UINT uIndex; MilSegment *pSegment = GetFirstSegment(); cPoints = 1; // for the start point cSegments = 0; if (!pSegment) goto Cleanup; for (uIndex = 0; uIndex < m_pFigure->Count; uIndex++) { switch (pSegment->Type) { case MilSegmentType::Line: IFC(IncrementUINT(IN OUT cSegments)); IFC(IncrementUINT(IN OUT cPoints)); pSegment = reinterpret_cast<MilSegment*> (reinterpret_cast<BYTE*>(pSegment) + sizeof(MilSegmentLine)); break; case MilSegmentType::Bezier: IFC(IncrementUINT(IN OUT cSegments)); IFC(AddUINT(cPoints, 3, OUT cPoints)); pSegment = reinterpret_cast<MilSegment*> (reinterpret_cast<BYTE*>(pSegment) + sizeof(MilSegmentBezier)); break; case MilSegmentType::QuadraticBezier: IFC(IncrementUINT(IN OUT cSegments)); IFC(AddUINT(cPoints, 3, OUT cPoints)); pSegment = reinterpret_cast<MilSegment*> (reinterpret_cast<BYTE*>(pSegment) + sizeof(MilSegmentQuadraticBezier)); break; case MilSegmentType::Arc: // An arc may have up to 4 Bezier segments IFC(AddUINT(cSegments, 4, OUT cSegments)); IFC(AddUINT(cPoints, 12, OUT cPoints)); pSegment = reinterpret_cast<MilSegment*> (reinterpret_cast<BYTE*>(pSegment) + sizeof(MilSegmentArc)); break; case MilSegmentType::PolyLine: { const MilSegmentPoly *pPoly = static_cast<MilSegmentPoly*> (pSegment); IFC(AddUINT(cSegments, pPoly->Count, OUT cSegments)); IFC(AddUINT(cPoints, pPoly->Count, OUT cPoints)); pSegment = reinterpret_cast<MilSegment*> (reinterpret_cast<BYTE*>(pSegment) + sizeof(MilSegmentPoly) + sizeof(MilPoint2D)*pPoly->Count); break; } case MilSegmentType::PolyBezier: { const MilSegmentPoly *pPoly = static_cast<MilSegmentPoly*> (pSegment); IFC(AddUINT(cSegments, pPoly->Count / 3, OUT cSegments)); IFC(AddUINT(cPoints, pPoly->Count, OUT cPoints)); pSegment = reinterpret_cast<MilSegment*> (reinterpret_cast<BYTE*>(pSegment) + sizeof(MilSegmentPoly) + sizeof(MilPoint2D)*pPoly->Count); break; } case MilSegmentType::PolyQuadraticBezier: { const MilSegmentPoly *pPoly = static_cast<MilSegmentPoly*> (pSegment); UINT cInnerSegments = pPoly->Count / 2; IFC(AddUINT(cSegments, cInnerSegments, OUT cSegments)); // Quadratic segments will be converted to cubics, requiring 3 points each IFC(MultiplyUINT(cInnerSegments, 3, OUT cInnerSegments)); IFC(AddUINT(cPoints, cInnerSegments, OUT cPoints)); pSegment = reinterpret_cast<MilSegment*> (reinterpret_cast<BYTE*>(pSegment) + sizeof(MilSegmentPoly) + sizeof(MilPoint2D)*pPoly->Count); break; } default: { RIP("Invalid segment type."); break; } } if (IsClosed()) { IFC(IncrementUINT(IN OUT cSegments)); IFC(IncrementUINT(IN OUT cPoints)); } } Cleanup: RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // PathFigureData::GetCurrentSegment // // Synopsis: // Returns the type and points of the current segment. // // Returns: // true if this is the segment where a stop has been set. // // Notes: // The type is either a line or bezier. The points are either a single // point (for a line) or three points (for a cubic bezier.) // //------------------------------------------------------------------------------ bool PathFigureData::GetCurrentSegment( __out_ecount(1) BYTE &bType, // Segment type (line or Bezier) __deref_outro_xcount((bType == MilCoreSeg::TypeLine) ? 1 : 3) const MilPoint2F *&pt // Line endpoint or curve 3 last points ) const { Assert(m_pFigure != NULL); Assert(m_pCurSegment != NULL); MilPoint2F *pptPoints = static_cast<MilPoint2F*> (&m_rgPoints[0]); if (m_uCurIndex >= m_pFigure->Count) { // We're at the implied closing line segment bType = MilCoreSeg::TypeLine; pptPoints[0] = GetStartPoint(); goto Cleanup; } switch (m_pCurSegment->Type) { case MilSegmentType::Line: { const MilSegmentLine *pLine = static_cast<MilSegmentLine*> (m_pCurSegment); bType = MilCoreSeg::TypeLine; pptPoints[0] = ConvertToSingle(pLine->Point); if (m_pMatrix != NULL) { TransformPoint(*m_pMatrix, pptPoints[0]); } break; } case MilSegmentType::Bezier: { const MilSegmentBezier *pBezier = static_cast<MilSegmentBezier*> (m_pCurSegment); bType = MilCoreSeg::TypeBezier; pptPoints[0] = ConvertToSingle(pBezier->Point1); pptPoints[1] = ConvertToSingle(pBezier->Point2); pptPoints[2] = ConvertToSingle(pBezier->Point3); if (m_pMatrix != NULL) { TransformPoints(*m_pMatrix, 3, &pptPoints[0]); } break; } case MilSegmentType::QuadraticBezier: { const MilSegmentQuadraticBezier *pBezier = static_cast<MilSegmentQuadraticBezier*> (m_pCurSegment); bType = MilCoreSeg::TypeBezier; SetQuadraticBezier( *GetCurrentSegmentStartD(), pBezier->Point1, pBezier->Point2); if (m_pMatrix != NULL) { TransformPoints(*m_pMatrix, 3, &pptPoints[0]); } break; } case MilSegmentType::Arc: bType = m_bType; pptPoints += m_uCurPoint; break; case MilSegmentType::PolyLine: { MilSegmentPoly *pPoly = static_cast<MilSegmentPoly*> (m_pCurSegment); const MilPoint2D *pPoints = reinterpret_cast<MilPoint2D*>(pPoly+1); bType = MilCoreSeg::TypeLine; pptPoints[0] = ConvertToSingle(pPoints[m_uInnerIndex]); if (m_pMatrix != NULL) { TransformPoint(*m_pMatrix, pptPoints[0]); } break; } case MilSegmentType::PolyBezier: { MilSegmentPoly *pPoly = static_cast<MilSegmentPoly*> (m_pCurSegment); MilPoint2D *pPoints = reinterpret_cast<MilPoint2D*>(pPoly+1); UINT uInnerIndexTimesThree = 0; // Operation guaranteed to succeed by the marshaling code Verify(SUCCEEDED(UIntMult(m_uInnerIndex, 3, &uInnerIndexTimesThree))); pPoints = &pPoints[uInnerIndexTimesThree]; bType = MilCoreSeg::TypeBezier; pptPoints[0] = ConvertToSingle(*(pPoints++)); pptPoints[1] = ConvertToSingle(*(pPoints++)); pptPoints[2] = ConvertToSingle(*pPoints); if (m_pMatrix != NULL) { TransformPoints(*m_pMatrix, 3, &pptPoints[0]); } break; } case MilSegmentType::PolyQuadraticBezier: { MilSegmentPoly *pPoly = static_cast<MilSegmentPoly*> (m_pCurSegment); MilPoint2D *pPoints = reinterpret_cast<MilPoint2D*>(pPoly+1); UINT uInnerIndexTimesTwo = 0; // Operation guaranteed to succeed by the marshaling code Verify(SUCCEEDED((UIntMult(m_uInnerIndex, 2, &uInnerIndexTimesTwo)))); pPoints = &pPoints[uInnerIndexTimesTwo]; bType = MilCoreSeg::TypeBezier; Assert(GetCurrentSegmentStartD()); SetQuadraticBezier( m_uInnerIndex>0 ? *(pPoints-1) : *GetCurrentSegmentStartD(), *pPoints, *(pPoints+1)); if (m_pMatrix != NULL) { TransformPoints(*m_pMatrix, 3, &pptPoints[0]); } break; } default: // This case should never be hit, but the output needs to be initialized anyway RIP("Invalid segment type"); bType = MilCoreSeg::TypeLine; break; } Cleanup: pt = static_cast<const MilPoint2F *> (pptPoints); // Returning true if this is the last figure or if this is a stop return (m_uCurIndex == m_uStop) && (m_uInnerIndex == m_uInnerStop); } //+----------------------------------------------------------------------------- // // Member: // PathFigureData::GetCurrentSegmentStart // // Synopsis: // Returns the first point starting the current segment. // //------------------------------------------------------------------------------ const MilPoint2F &PathFigureData::GetCurrentSegmentStart() const { Assert(GetCurrentSegmentStartD()); m_ptStartPoint = ConvertToSingle(*GetCurrentSegmentStartD()); if (m_pMatrix != NULL) { TransformPoint(*m_pMatrix, m_ptStartPoint); } return m_ptStartPoint; } //+----------------------------------------------------------------------------- // // Member: // PathFigureData::GetStartPoint // // Synopsis: // Returns the first point in the figure, transformed // //------------------------------------------------------------------------------ const MilPoint2F &PathFigureData::GetStartPoint() const { Assert(m_pFigure != NULL); m_ptStartPoint = ConvertToSingle(m_pFigure->StartPoint); if (m_pMatrix != NULL) { TransformPoint(*m_pMatrix, m_ptStartPoint); } return m_ptStartPoint; } //+----------------------------------------------------------------------------- // // Member: // PathFigureData::GetEndPoint // // Synopsis: // Returns the last point in the figure. // //------------------------------------------------------------------------------ const MilPoint2F &PathFigureData::GetEndPoint() const { Assert(m_pFigure != NULL); if (IsClosed()) { return GetStartPoint(); } if (m_fEndPointValid) { return m_ptEndPoint; } // We should be at the last segment. Assert(GetLastSegment()); Assert(GetSegmentLastPoint(GetLastSegment())); m_ptEndPoint = ConvertToSingle(*GetSegmentLastPoint(GetLastSegment())); if (m_pMatrix != NULL) { TransformPoint(*m_pMatrix, m_ptEndPoint); } m_fEndPointValid = TRUE; return m_ptEndPoint; } //+----------------------------------------------------------------------------- // // Member: // PathFigureData::SetQuadraticBezier // // Synopsis: // Set a cubic bezier from a quadratic bezier in the scratch area // //------------------------------------------------------------------------------ VOID PathFigureData::SetQuadraticBezier( IN MilPoint2D pt0, IN MilPoint2D pt1, IN MilPoint2D pt2 // The 3 points defining a quadratic Bezier curve ) const { // By the degree-elevation formula for Bezier curves (found in any geometric // modeling textbook) the cubic Bezier points of this quadratic Bezier curve // are pt0 (not set here), (1/3)*pt0+ (2/3)*pt1, (2/3)*pt1 + (1/3)*pt2, pt2. m_rgPoints[0].X = static_cast<FLOAT> (ONE_THIRD * pt0.X + TWO_THIRDS * pt1.X); m_rgPoints[0].Y = static_cast<FLOAT> (ONE_THIRD * pt0.Y + TWO_THIRDS * pt1.Y); m_rgPoints[1].X = static_cast<FLOAT> (TWO_THIRDS * pt1.X + ONE_THIRD * pt2.X); m_rgPoints[1].Y = static_cast<FLOAT> (TWO_THIRDS * pt1.Y + ONE_THIRD * pt2.Y); m_rgPoints[2].X = static_cast<FLOAT> (pt2.X); m_rgPoints[2].Y = static_cast<FLOAT> (pt2.Y); } //+----------------------------------------------------------------------------- // // Member: // PathFigureData::SetToFirstSegment // // Synopsis: // Sets to the first "real" segment. // // Returns: // True if set // //------------------------------------------------------------------------------ bool PathFigureData::SetToFirstSegment() const { Assert(m_pFigure != NULL); bool fSet = (m_pFigure->Count > 0); if (fSet) { m_pCurSegment = GetFirstSegment(); m_uCurIndex = 0; Assert(m_pCurSegment != NULL); if (MilSegmentType::Arc == m_pCurSegment->Type) { SetArcData(); m_uCurPoint = 0; } m_uInnerIndex = 0; } return fSet; } //+----------------------------------------------------------------------------- // // Member: // PathFigureData::GetCurrentSegmentStartD // // Synopsis: // Helper function that returns the previous segment. // //------------------------------------------------------------------------------ __notnull const MilPoint2D *PathFigureData::GetCurrentSegmentStartD() const { if (0 == m_uCurIndex) { // The first segment starts at the figure's StartPoint return &m_pFigure->StartPoint; } else { MilSegment *pSegment = m_pCurSegment; Assert(pSegment != NULL); if (m_uCurIndex < m_pFigure->Count) { // Get back to the previous segment BYTE *p = reinterpret_cast<BYTE*>(pSegment); p -= pSegment->BackSize; pSegment = reinterpret_cast<MilSegment*>(p); } // // Otherwise we're at the implied closing segment, where the previous segment // is m_pCurSegment, to which pSegment has already been set // return GetSegmentLastPoint(pSegment); } } //+----------------------------------------------------------------------------- // // Member: // PathFigureData::GetSegmentLastPoint // // Synopsis: // Helper function that returns the last point of the segment. // //------------------------------------------------------------------------------ __notnull MilPoint2D *PathFigureData::GetSegmentLastPoint(MilSegment *pSegment) const { Assert(m_pFigure != NULL); Assert(pSegment != NULL); Assert(!IsEmpty()); // Should be checked by the caller switch (pSegment->Type) { case MilSegmentType::Line: { MilSegmentLine *pLine = static_cast<MilSegmentLine*>(pSegment); return &pLine->Point; } case MilSegmentType::Bezier: { MilSegmentBezier *pBezier = static_cast<MilSegmentBezier*>(pSegment); return &pBezier->Point3; } case MilSegmentType::QuadraticBezier: { MilSegmentQuadraticBezier *pBezier = static_cast<MilSegmentQuadraticBezier*>(pSegment); return &pBezier->Point2; } case MilSegmentType::Arc: { MilSegmentArc *pArc = static_cast<MilSegmentArc*>(pSegment); return &pArc->Point; } case MilSegmentType::PolyLine: case MilSegmentType::PolyBezier: case MilSegmentType::PolyQuadraticBezier: { MilSegmentPoly *pPolySegment = static_cast<MilSegmentPoly*> (pSegment); Assert(pPolySegment->Count != 0); return (reinterpret_cast<MilPoint2D*>(pPolySegment+1)) + (pPolySegment->Count-1); } default: RIP("Invalid segment type."); } return NULL; } //+----------------------------------------------------------------------------- // // Member: // PathFigureData::SetArcData // // Synopsis: // Helper function, sets the data needed for consuming an arc segment // //------------------------------------------------------------------------------ void PathFigureData::SetArcData() const { const MilSegmentArc *pArc = static_cast<MilSegmentArc*> (m_pCurSegment); Assert(pArc != NULL); Assert(m_pCurSegment->Type == MilSegmentType::Arc); INT cPieces, cPoints; const MilPoint2D *pLastPoint = GetCurrentSegmentStartD(); Assert(pLastPoint); MilPoint2F pt = ConvertToSingle(pArc->Point); MilSizeD size = pArc->Size; if (IsSizeDotEmpty(&size)) { // This way we will end up drawing nothing. size.Width = 0; size.Height = 0; } ArcToBezier( static_cast<FLOAT> (pLastPoint->X), static_cast<FLOAT> (pLastPoint->Y), static_cast<FLOAT> (size.Width), static_cast<FLOAT> (size.Height), static_cast<FLOAT> (pArc->XRotation), pArc->LargeArc, pArc->Sweep, pt.X, pt.Y, m_rgPoints, cPieces); // cPieces = -1 indicates a degenerate line, but we still treat it as a line, so-- if (cPieces <= 0) { // This is a (possibly degenerate) line m_rgPoints[0].X = static_cast<FLOAT>(pt.X); m_rgPoints[0].Y = static_cast<FLOAT>(pt.Y); m_bType = MilCoreSeg::TypeLine; cPoints = cPieces = 1; } else { m_bType = MilCoreSeg::TypeBezier; cPoints = 3 * cPieces; } if (m_pMatrix != NULL) { TransformPoints(*m_pMatrix, cPoints, m_rgPoints); } m_uLastInnerIndex = cPieces - 1; m_uCurPoint = 0; } //+----------------------------------------------------------------------------- // // Member: // PathFigureData::SetToNextSegment // // Synopsis: // Traverse to the next segment in the figure. // // Returns: // True if set // //------------------------------------------------------------------------------ bool PathFigureData::SetToNextSegment() const { Assert(m_pFigure != NULL); bool fSet = false; MilSegment *pSegment = NULL; Assert(m_pCurSegment != NULL); switch (m_pCurSegment->Type) { case MilSegmentType::Line: fSet = (m_uCurIndex < m_pFigure->Count - 1); if (fSet) { pSegment = reinterpret_cast<MilSegment*> (reinterpret_cast<BYTE*>(m_pCurSegment) + sizeof(MilSegmentLine)); } break; case MilSegmentType::Bezier: fSet = (m_uCurIndex < m_pFigure->Count - 1); if (fSet) { pSegment = reinterpret_cast<MilSegment*> (reinterpret_cast<BYTE*>(m_pCurSegment) + sizeof(MilSegmentBezier)); } break; case MilSegmentType::QuadraticBezier: fSet = (m_uCurIndex < m_pFigure->Count - 1); if (fSet) { pSegment = reinterpret_cast<MilSegment*> (reinterpret_cast<BYTE*>(m_pCurSegment) + sizeof(MilSegmentQuadraticBezier)); } break; case MilSegmentType::Arc: fSet = (m_uInnerIndex < m_uLastInnerIndex); if (fSet) { // Move to the next inner segment Assert(MilCoreSeg::TypeBezier == m_bType); // Otherwise there would be only one segment m_uCurPoint += 3; Assert(m_uCurPoint < 12); break; } fSet = (m_uCurIndex < m_pFigure->Count - 1); if (fSet) { pSegment = reinterpret_cast<MilSegment*> (reinterpret_cast<BYTE*>(m_pCurSegment) + sizeof(MilSegmentArc)); } break; case MilSegmentType::PolyLine: { const MilSegmentPoly *pPolySegment = static_cast<MilSegmentPoly*> (m_pCurSegment); UINT uLastInnerIndex = pPolySegment->Count - 1; Assert(pPolySegment->Count != 0); fSet = (m_uInnerIndex < uLastInnerIndex); if (fSet) { // We'll move to the next inner segment break; } fSet = (m_uCurIndex < m_pFigure->Count - 1); if (fSet) { pSegment = reinterpret_cast<MilSegment*> (reinterpret_cast<BYTE*>(m_pCurSegment) + sizeof(MilSegmentPoly) + sizeof(MilPoint2D)*pPolySegment->Count); } break; } case MilSegmentType::PolyBezier: { const MilSegmentPoly *pPolySegment = static_cast<MilSegmentPoly*> (m_pCurSegment); Assert((pPolySegment->Count % 3) == 0); UINT uLastInnerIndex = pPolySegment->Count / 3 - 1; Assert(pPolySegment->Count >= 3); fSet = (m_uInnerIndex < uLastInnerIndex); if (fSet) { // We'll move to the next inner segment break; } fSet = (m_uCurIndex < m_pFigure->Count - 1); if (fSet) { pSegment = reinterpret_cast<MilSegment*> (reinterpret_cast<BYTE*>(m_pCurSegment) + sizeof(MilSegmentPoly) + sizeof(MilPoint2D)*pPolySegment->Count); } break; } case MilSegmentType::PolyQuadraticBezier: { const MilSegmentPoly *pPolySegment = static_cast<MilSegmentPoly*> (m_pCurSegment); Assert((pPolySegment->Count & 1) == 0); Assert(pPolySegment->Count >= 2); UINT uLastInnerIndex = pPolySegment->Count / 2 - 1; fSet = (m_uInnerIndex < uLastInnerIndex); if (fSet) { // We'll move to the next inner segment break; } fSet = (m_uCurIndex < m_pFigure->Count - 1); if (fSet) { pSegment = reinterpret_cast<MilSegment*> (reinterpret_cast<BYTE*>(m_pCurSegment) + sizeof(MilSegmentPoly) + sizeof(MilPoint2D)*pPolySegment->Count); } break; } default: fSet = false; Assert(FALSE); break; } if (fSet) { if (pSegment) { m_pCurSegment = pSegment; m_uCurIndex++; if (MilSegmentType::Arc == pSegment->Type) { SetArcData(); m_uCurPoint = 0; } m_uInnerIndex = 0; } else { m_uInnerIndex++; } } else { // Last chance - the implied closing line segment, if not redundant if (IsClosed() && (m_uCurIndex < m_pFigure->Count)) { const MilPoint2D &ptStart = m_pFigure->StartPoint; const MilPoint2D &ptCurrent = *GetSegmentLastPoint(m_pCurSegment); fSet = ((ptStart.X != ptCurrent.X) || (ptStart.Y != ptCurrent.Y)); m_uCurIndex++; } } return fSet; } //+----------------------------------------------------------------------------- // // Member: // PathFigureData::SetToLastSegment // // Synopsis: // Sets to the last segment. // // Returns: // True if set // // Note: // This method is not tested, as there is no path code that drives it. It // will be needed once line-shapes are exposed in the public API. // //------------------------------------------------------------------------------ bool PathFigureData::SetToLastSegment() const { #ifdef LINE_SHAPES_ENABLED Assert(m_pFigure != NULL); // // This method ignores the implied closing line segment of a closed figure. // That's currently acceptable, since backward traversal is only used for // line shapes, which are only applied to open figures. // Assert(!IsClosed()); bool fSet = (m_pFigure->Count > 0); if (fSet) { Assert(m_pCurSegment != NULL); m_pCurSegment = GetLastSegment(); m_uCurIndex = m_pFigure->Count - 1; if (MilSegmentType::Arc == m_pCurSegment->Type) { SetArcData(); } SetInnerIndexToLast(); } Cleanup: return fSet; #else RIP("Invalid call"); return false; #endif // LINE_SHAPES_ENABLED } //+----------------------------------------------------------------------------- // // Member: // PathFigureData::SetToPreviousSegment // // Synopsis: // Traverse to the previous segment in the figure. // // Returns: // True if set // // Note: // This method is not tested, as there is not path code that drives it. It // will be needed once line-shapes are exposed in the public API. // //------------------------------------------------------------------------------ bool PathFigureData::SetToPreviousSegment() const { #ifdef LINE_SHAPES_ENABLED if (m_uInnerIndex > 0) { // Decrement the sub-segment m_uInnerIndex--; if (MilSegmentType::Arc == m_pCurSegment->Type) { // Move to the arc's previous Bezier segment m_uCurPoint -= 3; } return true; } if (m_uCurIndex > 0) { // Decrement the segment m_uCurIndex--; Asseret(m_pCurSegment); m_pCurSegment = reinterpret_cast<MilSegment*> (reinterpret_cast<BYTE*>(m_pCurSegment) - m_pCurSegment->BackSize); if (MilSegmentType::Arc == m_pCurSegment->Type) { // Compute the arc's Bezier segments SetArcData(); } SetInnerIndexToLast(); return true; } return false; #else RIP("Invalid call"); return false; #endif // LINE_SHAPES_ENABLED } //+----------------------------------------------------------------------------- // // Member: // PathGeometryData::PathGeometryData // // Synopsis: // Construct an empty PathGeometryData // //------------------------------------------------------------------------------ PathGeometryData::PathGeometryData() { SetPathData(NULL, 0, MilFillMode::Alternate); } //+----------------------------------------------------------------------------- // // Member: // PathGeometryData::PathGeometryData // // Synopsis: // Constructor for PathGeometryData that initializes its content. // //------------------------------------------------------------------------------ PathGeometryData::PathGeometryData( MilPathGeometry *pPathData, UINT nSize, MilFillMode::Enum fillRule, CMILMatrix *pMatrix) { SetPathData(pPathData, nSize, fillRule, pMatrix); } //+----------------------------------------------------------------------------- // // Member: // PathGeometryData::SetPathData // // Synopsis: // Initialize the path data content. // //------------------------------------------------------------------------------ void PathGeometryData::SetPathData( MilPathGeometry *pPathData, UINT nSize, MilFillMode::Enum fillRule, const CMILMatrix *pMatrix) { m_pPath = pPathData; m_nSize = nSize; m_fillRule = fillRule; m_pMatrix = pMatrix; m_uCurIndex = 0; m_pCurFigure = GetFirstFigure(); } //+----------------------------------------------------------------------------- // // Member: // PathGeometryData::HasGaps // // Synopsis: // Returns true if figure has gaps. // //------------------------------------------------------------------------------ bool PathGeometryData::HasGaps() const { Assert(m_pPath); return (m_pPath->Flags & MilPathGeometryFlags::HasGaps) != 0; } //+----------------------------------------------------------------------------- // // Member: // PathGeometryData::HasHollows // // Synopsis: // Returns true if figure has non-fillable figures. // //------------------------------------------------------------------------------ bool PathGeometryData::HasHollows() const { Assert(m_pPath != NULL); return (m_pPath->Flags & MilPathGeometryFlags::HasHollows) != 0; } //+----------------------------------------------------------------------------- // // Member: // PathGeometryData::IsEmpty // // Synopsis: // Returns if the path geomety is empty. // //------------------------------------------------------------------------------ bool PathGeometryData::IsEmpty() const { Assert(m_pPath != NULL); MilPathFigure *pFigure = GetFirstFigure(); UINT count = m_pPath->FigureCount; while (count--) { PathFigureData pathFigure(pFigure, pFigure->Size, m_pMatrix); if (!pathFigure.IsEmpty()) { return false; } pFigure = reinterpret_cast<MilPathFigure*> (reinterpret_cast<BYTE*>(pFigure) + pFigure->Size); } return true; } //+----------------------------------------------------------------------------- // // Member: // PathGeometryData::GetFigureCount // // Synopsis: // Returns the number of figures in the path geometry. // //------------------------------------------------------------------------------ UINT PathGeometryData::GetFigureCount() const { Assert(m_pPath != NULL); return m_pPath->FigureCount; } //+----------------------------------------------------------------------------- // // Member: // PathGeometryData::GetFigure // // Synopsis: // Returns the figure at the given index. // //------------------------------------------------------------------------------ const IFigureData &PathGeometryData::GetFigure(IN UINT index) const { Assert(m_pPath != NULL); Assert(index <= GetFigureCount()); if (index != m_uCurIndex) { if (index == 0) { m_pCurFigure = GetFirstFigure(); m_uCurIndex = 0; } else { while (m_uCurIndex < index) { if (!NextFigure()) return *reinterpret_cast<IFigureData*>(NULL); } while (m_uCurIndex > index) { if (!PrevFigure()) return *reinterpret_cast<IFigureData*>(NULL); } } } m_pathFigure.SetFigureData(m_pCurFigure, m_pCurFigure->Size, m_pMatrix); return m_pathFigure; } //+----------------------------------------------------------------------------- // // Member: // PathGeometryData::NextFigure // // Synopsis: // Traverse forward to the next figure. // //------------------------------------------------------------------------------ bool PathGeometryData::NextFigure() const { if (m_uCurIndex >= m_pPath->FigureCount) { return false; } m_pCurFigure = reinterpret_cast<MilPathFigure*> (reinterpret_cast<BYTE*>(m_pCurFigure) + m_pCurFigure->Size); m_uCurIndex++; return true; } //+----------------------------------------------------------------------------- // // Member: // PathGeometryData::PrevFigure // // Synopsis: // Traverse backward to the previous figure. // //------------------------------------------------------------------------------ bool PathGeometryData::PrevFigure() const { if (m_uCurIndex <= 0) { return false; } m_pCurFigure = reinterpret_cast<MilPathFigure*> (reinterpret_cast<BYTE*>(m_pCurFigure) - m_pCurFigure->BackSize); m_uCurIndex--; return true; } //+----------------------------------------------------------------------------- // // Member: // PathGeometryData::GetFillMode // // Synopsis: // Return the fill mode. // //------------------------------------------------------------------------------ MilFillMode::Enum PathGeometryData::GetFillMode() const { Assert(m_pPath != NULL); if (m_fillRule == MilFillMode::Alternate) { return MilFillMode::Alternate; } Assert(m_fillRule == MilFillMode::Winding); return MilFillMode::Winding; } bool PathGeometryData::IsAxisAlignedRectangle() const { return FALSE; } //+----------------------------------------------------------------------------- // // Member: // PathGeometryData::GetCachedBoundsCore // // Synopsis: // Get the cached bounds if they exist // // Returns: // true if bounds have previously been cached // //------------------------------------------------------------------------------ bool PathGeometryData::GetCachedBoundsCore( __out_ecount(1) MilRectF &rect) const // The cached bounds, set only if valid { Assert(m_pPath); bool fCached = ((m_pPath->Flags & MilPathGeometryFlags::BoundsValid) != 0); if (fCached) { MilRectFFromMilRectD(OUT rect, m_pPath->Bounds); } return fCached; } //+----------------------------------------------------------------------------- // // Member: // PathGeometryData::SetCachedBounds // // Synopsis: // Set the cached bounds // //------------------------------------------------------------------------------ void PathGeometryData::SetCachedBounds( __in_ecount(1) const MilRectF &rect) const // The bounding box to cache { Assert(m_pPath); MilRectDFromMilRectF(OUT m_pPath->Bounds, rect); m_pPath->Flags |= MilPathGeometryFlags::BoundsValid; }
21,376
764
{"symbol": "VRS","address": "0xAbC430136A4dE71c9998242de8c1b4B97D2b9045","overview":{"en": ""},"email": "<EMAIL>","website": "http://vedh.io/","state": "NORMAL","links": {"blog": "","twitter": "https://twitter.com/VEROSFP","telegram": "https://t.me/veros_coin","github": "https://github.com/VerosDH"}}
122
370
package com.fasterxml.jackson.datatype.jsr310.deser.key; import java.time.DateTimeException; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import com.fasterxml.jackson.core.JacksonException; import com.fasterxml.jackson.databind.DeserializationContext; public class LocalTimeKeyDeserializer extends Jsr310KeyDeserializer { public static final LocalTimeKeyDeserializer INSTANCE = new LocalTimeKeyDeserializer(); private LocalTimeKeyDeserializer() { // singleton } @Override protected LocalTime deserialize(String key, DeserializationContext ctxt) throws JacksonException { try { return LocalTime.parse(key, DateTimeFormatter.ISO_LOCAL_TIME); } catch (DateTimeException e) { return _handleDateTimeException(ctxt, LocalTime.class, e, key); } } }
316
485
<filename>network/demo_socket_udp_server.py import socket BUFSIZE = 1024 ip_port = ('0.0.0.0', 60000) server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # udp server.bind(ip_port) while True: data,client_addr = server.recvfrom(BUFSIZE) print('server recv', data) server.sendto(data.upper(),client_addr) server.close() ''' ('server recv', 'hello\n') ('server recv', 'hello\n') ('server recv', 'hello\n') ('server recv', 'hello\n') ('server recv', 'hello\n') ('server recv', 'hello\n') '''
211
511
<reponame>JojOatXGME/Grammar-Kit /* * Copyright 2011-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package org.intellij.grammar; import com.intellij.lang.ASTNode; import com.intellij.lang.folding.CustomFoldingBuilder; import com.intellij.lang.folding.FoldingDescriptor; import com.intellij.openapi.editor.Document; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.psi.util.PsiTreeUtil; import org.intellij.grammar.psi.*; import org.jetbrains.annotations.NotNull; import java.util.List; /** * @author gregsh */ public class BnfFoldingBuilder extends CustomFoldingBuilder { @Override protected void buildLanguageFoldRegions(@NotNull List<FoldingDescriptor> result, @NotNull PsiElement root, @NotNull Document document, boolean quick) { if (!(root instanceof BnfFile)) return; BnfFile file = (BnfFile)root; for (BnfAttrs attrs : file.getAttributes()) { TextRange textRange = attrs.getTextRange(); if (textRange.getLength() <= 2) continue; result.add(new FoldingDescriptor(attrs, textRange)); for (BnfAttr attr : attrs.getAttrList()) { BnfExpression attrValue = attr.getExpression(); if (attrValue instanceof BnfValueList && attrValue.getTextLength() > 2) { result.add(new FoldingDescriptor(attrValue, attrValue.getTextRange())); } } } for (BnfRule rule : file.getRules()) { //result.add(new FoldingDescriptor(rule, rule.getTextRange())); BnfAttrs attrs = rule.getAttrs(); if (attrs != null) { result.add(new FoldingDescriptor(attrs, attrs.getTextRange())); } } if (!quick) { PsiTreeUtil.processElements(file, element -> { if (element.getNode().getElementType() == BnfParserDefinition.BNF_BLOCK_COMMENT) { result.add(new FoldingDescriptor(element, element.getTextRange())); } return true; }); } } @Override protected String getLanguagePlaceholderText(@NotNull ASTNode node, @NotNull TextRange range) { PsiElement psi = node.getPsi(); if (psi instanceof BnfAttrs) return "{..}"; if (psi instanceof BnfRule) return ((BnfRule)psi).getName() + " ::= ..."; if (psi instanceof BnfValueList) return "[..]"; if (node.getElementType() == BnfParserDefinition.BNF_BLOCK_COMMENT) return "/*..*/"; return null; } @Override protected boolean isRegionCollapsedByDefault(@NotNull ASTNode node) { PsiElement psi = node.getPsi(); return psi instanceof BnfValueList || psi instanceof BnfAttrs && !(psi.getParent() instanceof BnfRule); } }
1,185
5,169
<reponame>morizotter/Specs { "name": "Reveal-iOS-SDK", "version": "0.9.1", "summary": "The Reveal SDK for iOS.", "homepage": "http://revealapp.com/", "authors": "It<EMAIL>", "source": { "http": "http://download.revealapp.com/Reveal-Framework-0.9.1.zip" }, "platforms": { "ios": null }, "source_files": "Reveal-Framework-0.9.1/Reveal.framework/Versions/A/Headers/*.h", "preserve_paths": "Reveal-Framework-0.9.1/Reveal.framework", "license": { "type": "Copyright", "file": "Reveal-Framework-0.9.1/LICENSE.html" }, "frameworks": [ "CoreGraphics", "CFNetwork", "QuartzCore", "Reveal" ], "compiler_flags": "-ObjC", "xcconfig": { "FRAMEWORK_SEARCH_PATHS": "\"${PODS_ROOT}/Reveal-iOS-SDK/Reveal-Framework-0.9.1\"" }, "requires_arc": false }
384
1,144
<reponame>dram/metasfresh<filename>backend/de.metas.adempiere.adempiere/base/src/main/java-gen/org/compiere/model/X_C_CashLine.java /****************************************************************************** * Product: Adempiere ERP & CRM Smart Business Solution * * Copyright (C) 1999-2007 ComPiere, Inc. All Rights Reserved. * * This program is free software, you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License as published * * by the Free Software Foundation. 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., * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * For the text or an alternative of this public license, you may reach us * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * or via <EMAIL> or http://www.compiere.org/license.html * *****************************************************************************/ /** Generated Model - DO NOT CHANGE */ package org.compiere.model; import java.math.BigDecimal; import java.sql.ResultSet; import java.util.Properties; import org.compiere.util.Env; /** Generated Model for C_CashLine * @author Adempiere (generated) */ @SuppressWarnings("javadoc") public class X_C_CashLine extends org.compiere.model.PO implements I_C_CashLine, org.compiere.model.I_Persistent { /** * */ private static final long serialVersionUID = -1706777201L; /** Standard Constructor */ public X_C_CashLine (Properties ctx, int C_CashLine_ID, String trxName) { super (ctx, C_CashLine_ID, trxName); /** if (C_CashLine_ID == 0) { setAmount (Env.ZERO); setCashType (null); // E setC_Cash_ID (0); setC_CashLine_ID (0); setLine (0); // @SQL=SELECT COALESCE(MAX(Line),0)+10 AS DefaultValue FROM C_CashLine WHERE C_Cash_ID=@C_Cash_ID@ setProcessed (false); } */ } /** Load Constructor */ public X_C_CashLine (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** AccessLevel * @return 3 - Client - Org */ @Override protected int get_AccessLevel() { return accessLevel.intValue(); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO (Properties ctx) { org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } @Override public String toString() { StringBuilder sb = new StringBuilder ("X_C_CashLine[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Betrag. @param Amount Amount in a defined currency */ @Override public void setAmount (java.math.BigDecimal Amount) { set_Value (COLUMNNAME_Amount, Amount); } /** Get Betrag. @return Amount in a defined currency */ @Override public java.math.BigDecimal getAmount () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Amount); if (bd == null) return Env.ZERO; return bd; } /** * CashType AD_Reference_ID=217 * Reference name: C_Cash Trx Type */ public static final int CASHTYPE_AD_Reference_ID=217; /** BankAccountTransfer = T */ public static final String CASHTYPE_BankAccountTransfer = "T"; /** Invoice = I */ public static final String CASHTYPE_Invoice = "I"; /** GeneralExpense = E */ public static final String CASHTYPE_GeneralExpense = "E"; /** GeneralReceipts = R */ public static final String CASHTYPE_GeneralReceipts = "R"; /** Charge = C */ public static final String CASHTYPE_Charge = "C"; /** Difference = D */ public static final String CASHTYPE_Difference = "D"; /** Set Kassenart. @param CashType Source of Cash */ @Override public void setCashType (java.lang.String CashType) { set_ValueNoCheck (COLUMNNAME_CashType, CashType); } /** Get Kassenart. @return Source of Cash */ @Override public java.lang.String getCashType () { return (java.lang.String)get_Value(COLUMNNAME_CashType); } @Override public org.compiere.model.I_C_BP_BankAccount getC_BP_BankAccount() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_C_BP_BankAccount_ID, org.compiere.model.I_C_BP_BankAccount.class); } @Override public void setC_BP_BankAccount(org.compiere.model.I_C_BP_BankAccount C_BP_BankAccount) { set_ValueFromPO(COLUMNNAME_C_BP_BankAccount_ID, org.compiere.model.I_C_BP_BankAccount.class, C_BP_BankAccount); } /** Set Bankverbindung. @param C_BP_BankAccount_ID Bankverbindung des Geschäftspartners */ @Override public void setC_BP_BankAccount_ID (int C_BP_BankAccount_ID) { if (C_BP_BankAccount_ID < 1) set_Value (COLUMNNAME_C_BP_BankAccount_ID, null); else set_Value (COLUMNNAME_C_BP_BankAccount_ID, Integer.valueOf(C_BP_BankAccount_ID)); } /** Get Bankverbindung. @return Bankverbindung des Geschäftspartners */ @Override public int getC_BP_BankAccount_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_BP_BankAccount_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_C_Cash getC_Cash() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_C_Cash_ID, org.compiere.model.I_C_Cash.class); } @Override public void setC_Cash(org.compiere.model.I_C_Cash C_Cash) { set_ValueFromPO(COLUMNNAME_C_Cash_ID, org.compiere.model.I_C_Cash.class, C_Cash); } /** Set Kassenjournal. @param C_Cash_ID Cash Journal */ @Override public void setC_Cash_ID (int C_Cash_ID) { if (C_Cash_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Cash_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Cash_ID, Integer.valueOf(C_Cash_ID)); } /** Get Kassenjournal. @return Cash Journal */ @Override public int getC_Cash_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Cash_ID); if (ii == null) return 0; return ii.intValue(); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public org.compiere.util.KeyNamePair getKeyNamePair() { return new org.compiere.util.KeyNamePair(get_ID(), String.valueOf(getC_Cash_ID())); } /** Set Cash Journal Line. @param C_CashLine_ID Cash Journal Line */ @Override public void setC_CashLine_ID (int C_CashLine_ID) { if (C_CashLine_ID < 1) set_ValueNoCheck (COLUMNNAME_C_CashLine_ID, null); else set_ValueNoCheck (COLUMNNAME_C_CashLine_ID, Integer.valueOf(C_CashLine_ID)); } /** Get Cash Journal Line. @return Cash Journal Line */ @Override public int getC_CashLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_CashLine_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_C_Charge getC_Charge() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_C_Charge_ID, org.compiere.model.I_C_Charge.class); } @Override public void setC_Charge(org.compiere.model.I_C_Charge C_Charge) { set_ValueFromPO(COLUMNNAME_C_Charge_ID, org.compiere.model.I_C_Charge.class, C_Charge); } /** Set Kosten. @param C_Charge_ID Additional document charges */ @Override public void setC_Charge_ID (int C_Charge_ID) { if (C_Charge_ID < 1) set_Value (COLUMNNAME_C_Charge_ID, null); else set_Value (COLUMNNAME_C_Charge_ID, Integer.valueOf(C_Charge_ID)); } /** Get Kosten. @return Additional document charges */ @Override public int getC_Charge_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Charge_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_C_Currency getC_Currency() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_C_Currency_ID, org.compiere.model.I_C_Currency.class); } @Override public void setC_Currency(org.compiere.model.I_C_Currency C_Currency) { set_ValueFromPO(COLUMNNAME_C_Currency_ID, org.compiere.model.I_C_Currency.class, C_Currency); } /** Set Währung. @param C_Currency_ID The Currency for this record */ @Override public void setC_Currency_ID (int C_Currency_ID) { if (C_Currency_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Currency_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Currency_ID, Integer.valueOf(C_Currency_ID)); } /** Get Währung. @return The Currency for this record */ @Override public int getC_Currency_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Currency_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_C_Invoice getC_Invoice() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_C_Invoice_ID, org.compiere.model.I_C_Invoice.class); } @Override public void setC_Invoice(org.compiere.model.I_C_Invoice C_Invoice) { set_ValueFromPO(COLUMNNAME_C_Invoice_ID, org.compiere.model.I_C_Invoice.class, C_Invoice); } /** Set Rechnung. @param C_Invoice_ID Invoice Identifier */ @Override public void setC_Invoice_ID (int C_Invoice_ID) { if (C_Invoice_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Invoice_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Invoice_ID, Integer.valueOf(C_Invoice_ID)); } /** Get Rechnung. @return Invoice Identifier */ @Override public int getC_Invoice_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Invoice_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_C_Payment getC_Payment() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_C_Payment_ID, org.compiere.model.I_C_Payment.class); } @Override public void setC_Payment(org.compiere.model.I_C_Payment C_Payment) { set_ValueFromPO(COLUMNNAME_C_Payment_ID, org.compiere.model.I_C_Payment.class, C_Payment); } /** Set Zahlung. @param C_Payment_ID Payment identifier */ @Override public void setC_Payment_ID (int C_Payment_ID) { if (C_Payment_ID < 1) set_Value (COLUMNNAME_C_Payment_ID, null); else set_Value (COLUMNNAME_C_Payment_ID, Integer.valueOf(C_Payment_ID)); } /** Get Zahlung. @return Payment identifier */ @Override public int getC_Payment_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Payment_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Beschreibung. @param Description Beschreibung */ @Override public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set Discount Amount. @param DiscountAmt Calculated amount of discount */ @Override public void setDiscountAmt (java.math.BigDecimal DiscountAmt) { set_Value (COLUMNNAME_DiscountAmt, DiscountAmt); } /** Get Discount Amount. @return Calculated amount of discount */ @Override public java.math.BigDecimal getDiscountAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_DiscountAmt); if (bd == null) return Env.ZERO; return bd; } /** Set Generated. @param IsGenerated This Line is generated */ @Override public void setIsGenerated (boolean IsGenerated) { set_ValueNoCheck (COLUMNNAME_IsGenerated, Boolean.valueOf(IsGenerated)); } /** Get Generated. @return This Line is generated */ @Override public boolean isGenerated () { Object oo = get_Value(COLUMNNAME_IsGenerated); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Zeile Nr.. @param Line Unique line for this document */ @Override public void setLine (int Line) { set_Value (COLUMNNAME_Line, Integer.valueOf(Line)); } /** Get Zeile Nr.. @return Unique line for this document */ @Override public int getLine () { Integer ii = (Integer)get_Value(COLUMNNAME_Line); if (ii == null) return 0; return ii.intValue(); } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Write-off Amount. @param WriteOffAmt Amount to write-off */ @Override public void setWriteOffAmt (java.math.BigDecimal WriteOffAmt) { set_Value (COLUMNNAME_WriteOffAmt, WriteOffAmt); } /** Get Write-off Amount. @return Amount to write-off */ @Override public java.math.BigDecimal getWriteOffAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_WriteOffAmt); if (bd == null) return Env.ZERO; return bd; } }
5,405
421
<gh_stars>100-1000 #pragma once class CTriangleRenderer : public CRenderer { public: static HRESULT Create(IDirect3D9 *pD3D, IDirect3D9Ex *pD3DEx, HWND hwnd, UINT uAdapter, CRenderer **ppRenderer); ~CTriangleRenderer(); HRESULT Render(); protected: HRESULT Init(IDirect3D9 *pD3D, IDirect3D9Ex *pD3DEx, HWND hwnd, UINT uAdapter); private: CTriangleRenderer(); IDirect3DVertexBuffer9 *m_pd3dVB; };
216
3,651
package com.orientechnologies.orient.object.enhancement; import com.orientechnologies.orient.core.annotation.OBeforeSerialization; /** * @author LomakiA <a href="mailto:<EMAIL>"><NAME></a> * @since 18.05.12 */ public class AbstractEntity { private boolean before1Called = false; private boolean before2Called = false; public void reset() { before1Called = false; before2Called = false; } @OBeforeSerialization public void before1() { before1Called = true; } @OBeforeSerialization public void before2() { before2Called = true; } public boolean callbackExecuted() { return before1Called && before2Called; } }
224
831
package org.jetbrains.android.refactoring; import com.intellij.psi.PsiElement; import com.intellij.util.containers.MultiMap; import org.jetbrains.annotations.TestOnly; class AndroidInlineTestConfig { private final boolean myInlineThisOnly; private MultiMap<PsiElement, String> myConflicts = null; @TestOnly AndroidInlineTestConfig(boolean inlineThisOnly) { myInlineThisOnly = inlineThisOnly; } public boolean isInlineThisOnly() { return myInlineThisOnly; } public void setConflicts(MultiMap<PsiElement, String> conflicts) { myConflicts = conflicts; } @TestOnly public MultiMap<PsiElement, String> getConflicts() { return myConflicts; } }
229
2,151
<reponame>zipated/src // Copyright 2018 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/components/shortcut_viewer/views/keyboard_shortcut_view.h" #include <set> #include "ash/components/shortcut_viewer/keyboard_shortcut_viewer_metadata.h" #include "ash/components/shortcut_viewer/views/keyboard_shortcut_item_view.h" #include "ash/components/shortcut_viewer/views/ksv_search_box_view.h" #include "ash/test/ash_test_base.h" #include "services/ui/public/cpp/input_devices/input_device_client_test_api.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/aura/window.h" #include "ui/display/display.h" #include "ui/display/screen.h" #include "ui/events/test/event_generator.h" #include "ui/views/controls/textfield/textfield.h" #include "ui/views/widget/widget.h" namespace keyboard_shortcut_viewer { class KeyboardShortcutViewTest : public ash::AshTestBase { public: KeyboardShortcutViewTest() = default; ~KeyboardShortcutViewTest() override = default; // ash::AshTestBase: void SetUp() override { ash::AshTestBase::SetUp(); // Simulate the complete listing of input devices, required by the viewer. ui::InputDeviceClientTestApi().OnDeviceListsComplete(); } protected: int GetTabCount() const { DCHECK(GetView()); return GetView()->GetTabCountForTesting(); } const std::vector<std::unique_ptr<KeyboardShortcutItemView>>& GetShortcutViews() { DCHECK(GetView()); return GetView()->GetShortcutViewsForTesting(); } KSVSearchBoxView* GetSearchBoxView() { DCHECK(GetView()); return GetView()->GetSearchBoxViewForTesting(); } void KeyPress(ui::KeyboardCode key_code, bool should_insert) { ui::KeyEvent event(ui::ET_KEY_PRESSED, key_code, ui::EF_NONE); GetSearchBoxView()->OnKeyEvent(&event); if (!should_insert) return; // Emulates the input method. if (::isalnum(static_cast<int>(key_code))) { base::char16 character = ::tolower(static_cast<int>(key_code)); GetSearchBoxView()->search_box()->InsertText( base::string16(1, character)); } } private: KeyboardShortcutView* GetView() const { return KeyboardShortcutView::GetInstanceForTesting(); } DISALLOW_COPY_AND_ASSIGN(KeyboardShortcutViewTest); }; // Shows and closes the widget for KeyboardShortcutViewer. TEST_F(KeyboardShortcutViewTest, ShowAndClose) { // Show the widget. views::Widget* widget = KeyboardShortcutView::Toggle(CurrentContext()); EXPECT_TRUE(widget); // Cleaning up. widget->CloseNow(); } // KeyboardShortcutViewer window should be centered in screen. TEST_F(KeyboardShortcutViewTest, CenterWindowInScreen) { // Show the widget. views::Widget* widget = KeyboardShortcutView::Toggle(CurrentContext()); EXPECT_TRUE(widget); gfx::Rect root_window_bounds = display::Screen::GetScreen() ->GetDisplayNearestWindow(widget->GetNativeWindow()->GetRootWindow()) .work_area(); gfx::Rect shortcuts_window_bounds = widget->GetNativeWindow()->GetBoundsInScreen(); EXPECT_EQ(root_window_bounds.CenterPoint().x(), shortcuts_window_bounds.CenterPoint().x()); EXPECT_EQ(root_window_bounds.CenterPoint().y(), shortcuts_window_bounds.CenterPoint().y()); // Cleaning up. widget->CloseNow(); } // Test that the number of side tabs equals to the number of categories. TEST_F(KeyboardShortcutViewTest, SideTabsCount) { // Show the widget. views::Widget* widget = KeyboardShortcutView::Toggle(CurrentContext()); int category_number = 0; ShortcutCategory current_category = ShortcutCategory::kUnknown; for (const auto& item_view : GetShortcutViews()) { const ShortcutCategory category = item_view->category(); if (current_category != category) { DCHECK(current_category < category); ++category_number; current_category = category; } } EXPECT_EQ(GetTabCount(), category_number); // Cleaning up. widget->CloseNow(); } // Test that the top line in two views should be center aligned. TEST_F(KeyboardShortcutViewTest, TopLineCenterAlignedInItemView) { // Show the widget. views::Widget* widget = KeyboardShortcutView::Toggle(CurrentContext()); for (const auto& item_view : GetShortcutViews()) { DCHECK(item_view->child_count() == 2); // The top lines in both |description_label_view_| and // |shortcut_label_view_| should be center aligned. Only need to check one // view in the top line, because StyledLabel always center align all the // views in a line. const views::View* description_view = item_view->child_at(0); const views::View* shortcut_view = item_view->child_at(1); const views::View* description_top_line_view = description_view->child_at(0); const views::View* shortcut_top_line_view = shortcut_view->child_at(0); EXPECT_EQ(description_top_line_view->GetBoundsInScreen().CenterPoint().y(), shortcut_top_line_view->GetBoundsInScreen().CenterPoint().y()); } // Cleaning up. widget->CloseNow(); } // Test that the focus is on search box when window inits and exits search mode. TEST_F(KeyboardShortcutViewTest, FocusOnSearchBox) { // Show the widget. views::Widget* widget = KeyboardShortcutView::Toggle(CurrentContext()); // Case 1: when window creates. The focus should be on search box. EXPECT_TRUE(GetSearchBoxView()->search_box()->HasFocus()); // Press a key should enter search mode. KeyPress(ui::VKEY_A, /*should_insert=*/true); EXPECT_TRUE(GetSearchBoxView()->back_button()->visible()); EXPECT_FALSE(GetSearchBoxView()->search_box()->text().empty()); // Case 2: Exit search mode by clicking |back_button|. The focus should be on // search box. GetSearchBoxView()->ButtonPressed( GetSearchBoxView()->back_button(), ui::MouseEvent(ui::ET_MOUSE_PRESSED, gfx::Point(), gfx::Point(), base::TimeTicks(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); EXPECT_TRUE(GetSearchBoxView()->search_box()->text().empty()); EXPECT_TRUE(GetSearchBoxView()->search_box()->HasFocus()); // Enter search mode again. KeyPress(ui::VKEY_A, /*should_insert=*/true); EXPECT_FALSE(GetSearchBoxView()->search_box()->text().empty()); // Case 3: Exit search mode by pressing |VKEY_ESCAPE|. The focus should be on // search box. KeyPress(ui::VKEY_ESCAPE, /*should_insert=*/false); EXPECT_TRUE(GetSearchBoxView()->search_box()->text().empty()); EXPECT_TRUE(GetSearchBoxView()->search_box()->HasFocus()); // Cleaning up. widget->CloseNow(); } // Test that the window can be closed by accelerator. TEST_F(KeyboardShortcutViewTest, CloseWindowByAccelerator) { // Show the widget. views::Widget* widget = KeyboardShortcutView::Toggle(CurrentContext()); EXPECT_FALSE(widget->IsClosed()); ui::test::EventGenerator& event_generator = GetEventGenerator(); event_generator.PressKey(ui::VKEY_W, ui::EF_CONTROL_DOWN); EXPECT_TRUE(widget->IsClosed()); } // Test that the window can be activated or closed by toggling. TEST_F(KeyboardShortcutViewTest, ToggleWindow) { // Show the widget. views::Widget* widget = KeyboardShortcutView::Toggle(CurrentContext()); EXPECT_FALSE(widget->IsClosed()); // Call |Toggle()| to activate the inactive widget. EXPECT_TRUE(widget->IsActive()); widget->Deactivate(); EXPECT_FALSE(widget->IsActive()); KeyboardShortcutView::Toggle(CurrentContext()); EXPECT_TRUE(widget->IsActive()); // Call |Toggle()| to close the active widget. KeyboardShortcutView::Toggle(CurrentContext()); EXPECT_TRUE(widget->IsClosed()); } } // namespace keyboard_shortcut_viewer
2,678
884
<reponame>slyoldfox/blaze-persistence /* * Copyright 2014 - 2021 Blazebit. * * 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.blazebit.persistence.view.testsuite.update.listener; import com.blazebit.persistence.testsuite.base.jpa.assertion.AssertStatementBuilder; import com.blazebit.persistence.testsuite.base.jpa.category.NoDatanucleus; import com.blazebit.persistence.testsuite.base.jpa.category.NoEclipselink; import com.blazebit.persistence.testsuite.entity.Person; import com.blazebit.persistence.view.FlushMode; import com.blazebit.persistence.view.FlushStrategy; import com.blazebit.persistence.view.change.ChangeModel; import com.blazebit.persistence.view.change.MapChangeModel; import com.blazebit.persistence.view.spi.EntityViewConfiguration; import com.blazebit.persistence.view.testsuite.update.AbstractEntityViewUpdateDocumentTest; import com.blazebit.persistence.view.testsuite.update.listener.model.PersonView; import com.blazebit.persistence.view.testsuite.update.listener.model.UpdatableDocumentWithMapsView; import com.blazebit.persistence.view.testsuite.update.listener.model.UpdatablePersonView; import org.junit.Assert; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.*; /** * * @author <NAME> * @since 1.4.0 */ @RunWith(Parameterized.class) // NOTE: No Datanucleus support yet @Category({ NoDatanucleus.class, NoEclipselink.class}) public class EntityViewUpdateListenerMapsTest extends AbstractEntityViewUpdateDocumentTest<UpdatableDocumentWithMapsView> { public EntityViewUpdateListenerMapsTest(FlushMode mode, FlushStrategy strategy, boolean version) { super(mode, strategy, version, UpdatableDocumentWithMapsView.class); } @Parameterized.Parameters(name = "{0} - {1} - VERSIONED={2}") public static Object[][] combinations() { return MODE_STRATEGY_VERSION_COMBINATIONS; } @Override protected void registerViewTypes(EntityViewConfiguration cfg) { cfg.addEntityView(PersonView.class); cfg.addEntityView(UpdatablePersonView.class); } @Override protected String[] getFetchedCollections() { return new String[] { "contacts" }; } @Test public void testUpdateReplaceCollection() { // Given final UpdatableDocumentWithMapsView docView = getDoc1View(); // When docView.setContacts(new HashMap<>(docView.getContacts())); update(docView); // Then clearPersistenceContextAndReload(); assertSubviewEquals(doc1.getContacts(), docView.getContacts()); } @Test public void testUpdateAddToCollection() { // Given final UpdatableDocumentWithMapsView docView = getDoc1View(); UpdatablePersonView newPerson = getP2View(UpdatablePersonView.class); // When docView.getContacts().put(2, newPerson); saveWith(docView, flushOperationBuilder -> { flushOperationBuilder.onPreUpdate(UpdatableDocumentWithMapsView.class, view -> { MapChangeModel<UpdatableDocumentWithMapsView, UpdatablePersonView> changeModel = (MapChangeModel<UpdatableDocumentWithMapsView, UpdatablePersonView>) (ChangeModel<?>) evm.getChangeModel(view).get("contacts"); assertEquals(newPerson, changeModel.getAddedElements().get(0).getCurrentState()); }); }); // Then clearPersistenceContextAndReload(); assertSubviewEquals(doc1.getContacts(), docView.getContacts()); } @Test public void testUpdateAddToNewCollection() { // Given final UpdatableDocumentWithMapsView docView = getDoc1View(); UpdatablePersonView newPerson = getP2View(UpdatablePersonView.class); // When docView.setContacts(new HashMap<>(docView.getContacts())); docView.getContacts().put(2, newPerson); update(docView); // Then clearPersistenceContextAndReload(); assertSubviewEquals(doc1.getContacts(), docView.getContacts()); } @Test public void testUpdateAddToCollectionAndModify() { // Given final UpdatableDocumentWithMapsView docView = getDoc1View(); UpdatablePersonView newPerson = getP2View(UpdatablePersonView.class); // When newPerson.setName("newPerson"); docView.getContacts().put(2, newPerson); update(docView); // Then clearPersistenceContextAndReload(); assertSubviewEquals(doc1.getContacts(), docView.getContacts()); assertEquals("newPerson", p2.getName()); } @Test public void testClearUpdateAddToCollectionAndModify() { // Given final UpdatableDocumentWithMapsView docView = getDoc1View(); UpdatablePersonView newPerson = getP2View(UpdatablePersonView.class); // When newPerson.setName("newPerson"); docView.getContacts().put(2, newPerson); HashMap<Integer, UpdatablePersonView> copy = new HashMap<>(docView.getContacts()); docView.getContacts().clear(); docView.getContacts().putAll(copy); update(docView); // Then clearPersistenceContextAndReload(); assertSubviewEquals(doc1.getContacts(), docView.getContacts()); assertEquals("newPerson", p2.getName()); } @Test public void testUpdateAddToCollectionCreate() { // Given final UpdatableDocumentWithMapsView docView = getDoc1View(); UpdatablePersonView newPerson = evm.create(UpdatablePersonView.class); // When newPerson.setName("newPerson"); docView.setContacts(new HashMap<>(docView.getContacts())); docView.getContacts().put(2, newPerson); saveWith(docView, flusherBuilder -> { flusherBuilder.onPrePersist(UpdatablePersonView.class, Person.class,(view, entity) -> { entity.setAge(10L); }); }); // Then clearPersistenceContextAndReload(); assertSubviewEquals(doc1.getContacts(), docView.getContacts()); assertEquals("newPerson", doc1.getContacts().get(2).getName()); assertEquals(10L, doc1.getContacts().get(2).getAge()); } public static void assertSubviewEquals(Map<Integer, Person> persons, Map<Integer, ? extends UpdatablePersonView> personSubviews) { if (persons == null) { assertNull(personSubviews); return; } assertNotNull(personSubviews); assertEquals(persons.size(), personSubviews.size()); for (Map.Entry<Integer, Person> entry : persons.entrySet()) { Person p = entry.getValue(); boolean found = false; UpdatablePersonView pSub = personSubviews.get(entry.getKey()); if (pSub != null) { if (p.getName().equals(pSub.getName())) { found = true; break; } } if (!found) { Assert.fail("Could not find a person subview instance with the name: " + p.getName()); } } } @Override protected AssertStatementBuilder fullFetch(AssertStatementBuilder builder) { return builder; } @Override protected AssertStatementBuilder versionUpdate(AssertStatementBuilder builder) { return builder; } }
3,115
1,056
<filename>enterprise/websvc.manager/src/org/netbeans/modules/websvc/manager/ui/ResultRowModel.java /* * 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.netbeans.modules.websvc.manager.ui; import org.netbeans.swing.outline.RowModel; import org.openide.util.NbBundle; import javax.swing.tree.DefaultMutableTreeNode; /** * * @author <NAME> */ public class ResultRowModel implements RowModel { /** Creates a new instance of TypeRowModel */ public ResultRowModel() { } public Class getColumnClass(int column) { switch(column) { // case 0: return String.class; case 0: return Object.class; default: return String.class; } } public int getColumnCount() { return 1; } public String getColumnName(int column) { switch(column) { case 0: return NbBundle.getMessage(this.getClass(), "PARAM_VALUE"); default: return ""; } } public Object getValueFor(Object inNode, int column) { if(null == inNode) return null; DefaultMutableTreeNode node = (DefaultMutableTreeNode)inNode; if(null == node.getUserObject()) return null; TypeNodeData data = (TypeNodeData)node.getUserObject(); switch(column) { case 0: return data.getTypeValue(); default: return ""; } } public boolean isCellEditable(Object inNode, int column) { return true; } public void setValueFor(Object inNode, int column, Object value) { return; } }
815
304
<reponame>RUI-07/yapi-to-typescript { "typescript.tsdk": "node_modules/typescript/lib", "eslint.options": { "resolvePluginsRelativeTo": "." } }
72
1,662
""" Simple example: .. UIExample:: 70 with flx.VBox(): flx.Slider(min=10, max=20, value=12) flx.RangeSlider(min=10, max=90, value=(20, 60)) Also see examples: :ref:`sine.py`, :ref:`twente.py`, :ref:`deep_event_connections.py`. """ from ... import event from .._widget import Widget, create_element class Slider(Widget): """ An input widget to select a value in a certain range. The ``node`` of this widget is a `<div> <https://developer.mozilla.org/docs/Web/HTML/Element/div>`_ containing a few HTML elements for rendering. It does not use a ``<input type='range'>`` because of its different appearance and behaviour accross browsers. """ DEFAULT_MIN_SIZE = 40, 20 CSS = """ .flx-Slider:focus { outline: none; } .flx-Slider > .gutter { box-sizing: border-box; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; margin: 0 5px; /* half width of slider */ position: absolute; top: calc(50% - 2px); height: 4px; width: calc(100% - 10px); border-radius: 6px; background: rgba(0, 0, 0, 0.2); color: rgba(0,0,0,0); text-align: center; transition: top 0.2s, height 0.2s; } .flx-Slider.flx-dragging > .gutter, .flx-Slider:focus > .gutter { top: calc(50% - 10px); height: 20px; color: rgba(0,0,0,1); } .flx-Slider .slider, .flx-Slider .range { box-sizing: border-box; text-align: center; border-radius: 3px; background: #48c; border: 2px solid #48c; transition: top 0.2s, height 0.2s, background 0.4s; position: absolute; top: calc(50% - 8px); height: 16px; width: 10px; } .flx-Slider .range { border-width: 1px 0px 1px 0px; top: calc(50% - 4px); height: 8px; width: auto; } .flx-Slider.flx-dragging .slider, .flx-Slider:focus .slider, .flx-Slider.flx-dragging .range, .flx-Slider:focus .range { background: none; top: calc(50% - 10px); height: 20px; } .flx-Slider > .gutter > .slider.disabled { background: #888; border: none; } """ step = event.FloatProp(0.01, settable=True, doc=""" The step size for the slider. """) min = event.FloatProp(0, settable=True, doc=""" The minimal slider value. """) max = event.FloatProp(1, settable=True, doc=""" The maximum slider value. """) value = event.FloatProp(0, settable=True, doc=""" The current slider value. """) text = event.StringProp('{value}', settable=True, doc=""" The label to display on the slider during dragging. Occurances of "{percent}" are replaced with the current percentage, and "{value}" with the current value. Default "{value}". """) disabled = event.BoolProp(False, settable=True, doc=""" Whether the slider is disabled. """) def init(self): self._dragging = None self._drag_target = 0 @event.emitter def user_value(self, value): """ Event emitted when the user manipulates the slider. Has ``old_value`` and ``new_value`` attributes. """ d = {'old_value': self.value, 'new_value': value} self.set_value(value) return d @event.emitter def user_done(self): """ Event emitted when the user stops manipulating the slider. Has ``old_value`` and ``new_value`` attributes (which have the same value). """ d = {'old_value': self.value, 'new_value': self.value} return d @event.action def set_value(self, value): global Math value = max(self.min, value) value = min(self.max, value) value = Math.round(value / self.step) * self.step self._mutate_value(value) @event.reaction('min', 'max', 'step') def __keep_value_constrained(self, *events): self.set_value(self.value) def _render_dom(self): global Math value = self.value mi, ma = self.min, self.max perc = 100 * (value - mi) / (ma - mi) valuestr = str(value) if '.' in valuestr and valuestr[-4:-1] == '000': valuestr = valuestr[:-1].rstrip('0') label = self.text label = label.replace('{value}', valuestr) label = label.replace('{percent}', Math.round(perc) + '%') attr = {'className': 'slider disabled' if self.disabled else 'slider', 'style__left': 'calc(' + perc + '% - 5px)' } return [create_element('div', {'className': 'gutter'}, create_element('span', {}, label), create_element('div', attr), ) ] # Use the Flexx pointer event system, so we can make use of capturing ... def _getgutter(self): return self.node.children[0] def _snap2handle(self, x): # Snap to the slider handle gutter = self._getgutter() left = gutter.getBoundingClientRect().left + gutter.children[1].offsetLeft if left <= x <= left + 10: return x else: return left + 5 # center of the slider handle @event.emitter def pointer_down(self, e): if not self.disabled: e.stopPropagation() x1 = e.changedTouches[0].clientX if e.changedTouches else e.clientX x1 = self._snap2handle(x1) self._dragging = self.value, x1 self.outernode.classList.add('flx-dragging') else: return super().pointer_down(e) @event.emitter def pointer_up(self, e): if self._dragging is not None and len(self._dragging) == 3: self.outernode.blur() self._dragging = None self._drag_target = 0 self.outernode.classList.remove('flx-dragging') self.user_done() return super().pointer_down(e) @event.emitter def pointer_move(self, e): if self._dragging is not None: e.stopPropagation() ref_value, x1 = self._dragging[0], self._dragging[1] self._dragging = ref_value, x1, True # mark as moved x2 = e.changedTouches[0].clientX if e.changedTouches else e.clientX mi, ma = self.min, self.max value_diff = (x2 - x1) / self._getgutter().clientWidth * (ma - mi) self.user_value(ref_value + value_diff) else: return super().pointer_move(e) @event.reaction('key_down') def __on_key(self, *events): for ev in events: value = self.value if ev.key == 'Escape': self.outernode.blur() self.user_done() elif ev.key == 'ArrowRight': if isinstance(value, float): self.user_value(value + self.step) else: self.user_value([v + self.step for v in value]) elif ev.key == 'ArrowLeft': if isinstance(value, float): self.user_value(value - self.step) else: self.user_value([v - self.step for v in value]) class RangeSlider(Slider): """An input widget to select a range (i.e having two handles instead of one). The ``node`` of this widget is a `<div> <https://developer.mozilla.org/docs/Web/HTML/Element/div>`_ containing a few HTML elements for rendering. """ value = event.FloatPairProp((0, 1), settable=True, doc=""" The current slider value as a two-tuple. """) @event.action def set_value(self, *value): """ Set the RangeSlider's value. Can be called using ``set_value([val1, val2])`` or ``set_value(val1, val2)``. """ global Math if len(value) == 1 and isinstance(value[0], list): value = value[0] assert len(value) == 2, 'RangeSlider value must be a 2-tuple.' value = min(value[0], value[1]), max(value[0], value[1]) for i in range(2): value[i] = max(self.min, value[i]) value[i] = min(self.max, value[i]) value[i] = Math.round(value[i] / self.step) * self.step self._mutate_value(value) def _render_dom(self): global Math value1, value2 = self.value mi, ma = self.min, self.max perc1 = 100 * (value1 - mi) / (ma - mi) perc2 = 100 * (value2 - mi) / (ma - mi) valuestr1 = str(value1) valuestr2 = str(value2) if '.' in valuestr1 and valuestr1[-4:-1] == '000': valuestr1 = valuestr1[:-1].rstrip('0') elif '.' in valuestr2 and valuestr2[-4:-1] == '000': valuestr2 = valuestr2[:-1].rstrip('0') label = self.text label = label.replace('{value}', valuestr1 + ' - ' + valuestr2) label = label.replace('{percent}', Math.round(perc1) + '% - ' + Math.round(perc2) + '%') attr0 = {'className': 'range', 'style__left': perc1 + '%', 'style__right': (100 - perc2) + '%' } attr1 = {'className': 'slider disabled' if self.disabled else 'slider', 'style__left': 'calc(' + perc1 + '% - 5px)' } attr2 = {'className': 'slider disabled' if self.disabled else 'slider', 'style__left': 'calc(' + perc2 + '% - 5px)' } return [create_element('div', {'className': 'gutter'}, create_element('span', {}, label), create_element('div', attr0), create_element('div', attr1), create_element('div', attr2), ) ] def _snap2handle(self, x): # Snap to a slider handle or the center gutter = self._getgutter() h1 = gutter.getBoundingClientRect().left + gutter.children[2].offsetLeft + 5 h2 = gutter.getBoundingClientRect().left + gutter.children[3].offsetLeft + 5 hc = 0.5 * (h1 + h2) # Distances d1, d2, dc = abs(x - h1), abs(x - h2), abs(x - hc) # Decide if dc < d1 and dc < d2: self._drag_target = 3 return x elif d1 < d2: self._drag_target = 1 return h1 else: self._drag_target = 2 return h2 @event.emitter def pointer_move(self, e): if self._dragging is not None: e.stopPropagation() ref_value, x1 = self._dragging[0], self._dragging[1] self._dragging = ref_value, x1, True # mark as moved x2 = e.changedTouches[0].clientX if e.changedTouches else e.clientX mi, ma = self.min, self.max value_diff = (x2 - x1) / self._getgutter().clientWidth * (ma - mi) value1, value2 = ref_value if 1 & self._drag_target: value1 += value_diff if 2 & self._drag_target: value2 += value_diff self.user_value((value1, value2)) else: return super().pointer_move(e)
5,561
788
<filename>stack/corepersistence/common/src/main/java/org/apache/usergrid/persistence/core/astyanax/CompositeFieldSerializer.java /* * 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.usergrid.persistence.core.astyanax; import com.netflix.astyanax.model.CompositeBuilder; import com.netflix.astyanax.model.CompositeParser; /** * This interface is for re-using multiple components in a composite. Implementing this allows many different types to * be serialized together in a single composite * * @author tnine */ public interface CompositeFieldSerializer<K> { /** * Add this to the composite */ public void toComposite( CompositeBuilder builder, K value ); /** * Create an instance from the composite */ public K fromComposite( CompositeParser composite ); }
431
819
<reponame>virdesai/stock-analysis-engine #!/usr/bin/env python """ A tool for showing how to build an algorithm and run a backtest with an algorithm config dictionary .. code-block:: python import analysis_engine.consts as ae_consts import analysis_engine.algo as base_algo import analysis_engine.run_algo as run_algo ticker = 'SPY' willr_close_path = ( 'analysis_engine/mocks/example_indicator_williamsr.py') willr_open_path = ( 'analysis_engine/mocks/example_indicator_williamsr_open.py') algo_config_dict = { 'name': 'min-runner', 'timeseries': timeseries, 'trade_horizon': 5, 'num_owned': 10, 'buy_shares': 10, 'balance': 10000.0, 'commission': 6.0, 'ticker': ticker, 'algo_module_path': None, 'algo_version': 1, 'verbose': False, # log in the algorithm 'verbose_processor': False, # log in the indicator processor 'verbose_indicators': False, # log all indicators 'verbose_trading': True, # log in the algo trading methods 'positions': { ticker: { 'shares': 10, 'buys': [], 'sells': [] } }, 'buy_rules': { 'confidence': 75, 'min_indicators': 3 }, 'sell_rules': { 'confidence': 75, 'min_indicators': 3 }, 'indicators': [ { 'name': 'willr_-70_-30', 'module_path': willr_close_path, 'category': 'technical', 'type': 'momentum', 'uses_data': 'minute', 'high': 0, 'low': 0, 'close': 0, 'open': 0, 'willr_value': 0, 'num_points': 80, 'buy_below': -70, 'sell_above': -30, 'is_buy': False, 'is_sell': False, 'verbose': False # log in just this indicator }, { 'name': 'willr_-80_-20', 'module_path': willr_close_path, 'category': 'technical', 'type': 'momentum', 'uses_data': 'minute', 'high': 0, 'low': 0, 'close': 0, 'open': 0, 'willr_value': 0, 'num_points': 30, 'buy_below': -80, 'sell_above': -20, 'is_buy': False, 'is_sell': False }, { 'name': 'willr_-90_-10', 'module_path': willr_close_path, 'category': 'technical', 'type': 'momentum', 'uses_data': 'minute', 'high': 0, 'low': 0, 'close': 0, 'open': 0, 'willr_value': 0, 'num_points': 60, 'buy_below': -90, 'sell_above': -10, 'is_buy': False, 'is_sell': False }, { 'name': 'willr_open_-80_-20', 'module_path': willr_open_path, 'category': 'technical', 'type': 'momentum', 'uses_data': 'minute', 'high': 0, 'low': 0, 'close': 0, 'open': 0, 'willr_open_value': 0, 'num_points': 80, 'buy_below': -80, 'sell_above': -20, 'is_buy': False, 'is_sell': False } ], 'slack': { 'webhook': None } } class ExampleCustomAlgo(base_algo.BaseAlgo): def process(self, algo_id, ticker, dataset): if self.verbose: print( f'process start - {self.name} ' f'date={self.backtest_date} minute={self.latest_min} ' f'close={self.latest_close} high={self.latest_high} ' f'low={self.latest_low} open={self.latest_open} ' f'volume={self.latest_volume}') # end of process # end of ExampleCustomAlgo algo_obj = ExampleCustomAlgo( ticker=algo_config_dict['ticker'], config_dict=algo_config_dict) algo_res = run_algo.run_algo( ticker=algo_config_dict['ticker'], algo=algo_obj, raise_on_err=True) if algo_res['status'] != ae_consts.SUCCESS: print( 'failed running algo backtest ' f'{algo_obj.get_name()} hit status: ' f'{ae_consts.get_status(status=algo_res['status'])} ' f'error: {algo_res["err"]}') else: print( f'backtest: {algo_obj.get_name()} ' f'{ae_consts.get_status(status=algo_res["status"])} - ' 'plotting history') # if not successful """ import os import sys import datetime import argparse import analysis_engine.consts as ae_consts import analysis_engine.algo as base_algo import analysis_engine.run_algo as run_algo import analysis_engine.plot_trading_history as plot_trading_history import analysis_engine.build_publish_request as build_publish_request import spylunking.log.setup_logging as log_utils log = log_utils.build_colorized_logger( name='bt', log_config_path=ae_consts.LOG_CONFIG_PATH) def build_example_algo_config( ticker, timeseries='minute'): """build_example_algo_config helper for building an algorithm config dictionary :returns: algorithm config dictionary """ willr_close_path = ( 'analysis_engine/mocks/example_indicator_williamsr.py') willr_open_path = ( 'analysis_engine/mocks/example_indicator_williamsr_open.py') algo_config_dict = { 'name': 'backtest', 'timeseries': timeseries, 'trade_horizon': 5, 'num_owned': 10, 'buy_shares': 10, 'balance': 10000.0, 'commission': 6.0, 'ticker': ticker, 'algo_module_path': None, 'algo_version': 1, 'verbose': False, # log in the algorithm 'verbose_processor': False, # log in the indicator processor 'verbose_indicators': False, # log all indicators 'verbose_trading': False, # log in the algo trading methods 'inspect_datasets': False, # log dataset metrics - slow 'positions': { ticker: { 'shares': 10, 'buys': [], 'sells': [] } }, 'buy_rules': { 'confidence': 75, 'min_indicators': 3 }, 'sell_rules': { 'confidence': 75, 'min_indicators': 3 }, 'indicators': [ { 'name': 'willr_-70_-30', 'module_path': willr_close_path, 'category': 'technical', 'type': 'momentum', 'uses_data': 'minute', 'high': 0, 'low': 0, 'close': 0, 'open': 0, 'willr_value': 0, 'num_points': 80, 'buy_below': -70, 'sell_above': -30, 'is_buy': False, 'is_sell': False, 'verbose': False # log in just this indicator }, { 'name': 'willr_-80_-20', 'module_path': willr_close_path, 'category': 'technical', 'type': 'momentum', 'uses_data': 'minute', 'high': 0, 'low': 0, 'close': 0, 'open': 0, 'willr_value': 0, 'num_points': 30, 'buy_below': -80, 'sell_above': -20, 'is_buy': False, 'is_sell': False }, { 'name': 'willr_-90_-10', 'module_path': willr_close_path, 'category': 'technical', 'type': 'momentum', 'uses_data': 'minute', 'high': 0, 'low': 0, 'close': 0, 'open': 0, 'willr_value': 0, 'num_points': 60, 'buy_below': -90, 'sell_above': -10, 'is_buy': False, 'is_sell': False }, { 'name': 'willr_open_-80_-20', 'module_path': willr_open_path, 'category': 'technical', 'type': 'momentum', 'uses_data': 'minute', 'high': 0, 'low': 0, 'close': 0, 'open': 0, 'willr_open_value': 0, 'num_points': 80, 'buy_below': -80, 'sell_above': -20, 'is_buy': False, 'is_sell': False } ], 'slack': { 'webhook': None } } return algo_config_dict # end of build_example_algo_config class ExampleCustomAlgo(base_algo.BaseAlgo): """ExampleCustomAlgo""" def process(self, algo_id, ticker, dataset): """process Run a custom algorithm after all the indicators from the ``algo_config_dict`` have been processed and all the number crunching is done. This allows the algorithm class to focus on the high-level trade execution problems like bid-ask spreads and opening the buy/sell trade orders. **How does it work?** The engine provides a data stream from the latest pricing updates stored in redis. Once new data is stored in redis, algorithms will be able to use each ``dataset`` as a chance to evaluate buy and sell decisions. These are your own custom logic for trading based off what the indicators find and any non-indicator data provided from within the ``dataset`` dictionary. **Dataset Dictionary Structure** Here is what the ``dataset`` variable looks like when your algorithm's ``process`` method is called (assuming you have redis running with actual pricing data too): .. code-block:: python dataset = { 'id': dataset_id, 'date': date, 'data': { 'daily': pd.DataFrame([]), 'minute': pd.DataFrame([]), 'quote': pd.DataFrame([]), 'stats': pd.DataFrame([]), 'peers': pd.DataFrame([]), 'news1': pd.DataFrame([]), 'financials': pd.DataFrame([]), 'earnings': pd.DataFrame([]), 'dividends': pd.DataFrame([]), 'calls': pd.DataFrame([]), 'puts': pd.DataFrame([]), 'pricing': pd.DataFrame([]), 'news': pd.DataFrame([]) } } .. tip:: you can also inspect these datasets by setting the algorithm's config dictionary key ``"inspect_datasets": True`` :param algo_id: string - algo identifier label for debugging datasets during specific dates :param ticker: string - ticker :param dataset: a dictionary of identifiers (for debugging) and multiple pandas ``DataFrame`` objects. """ if self.verbose: log.info( f'process start - {self.name} balance={self.balance} ' f'date={self.backtest_date} minute={self.latest_min} ' f'close={self.latest_close} high={self.latest_high} ' f'low={self.latest_low} open={self.latest_open} ' f'volume={self.latest_volume}') # end of process # end of ExampleCustomAlgo def run_backtest_and_plot_history( config_dict): """run_backtest_and_plot_history Run a derived algorithm with an algorithm config dictionary :param config_dict: algorithm config dictionary """ log.debug('start - sa') parser = argparse.ArgumentParser( description=( 'stock analysis tool')) parser.add_argument( '-t', help=( 'ticker'), required=True, dest='ticker') parser.add_argument( '-e', help=( 'file path to extract an ' 'algorithm-ready datasets from redis'), required=False, dest='algo_extract_loc') parser.add_argument( '-l', help=( 'show dataset in this file'), required=False, dest='show_from_file') parser.add_argument( '-H', help=( 'show trading history dataset in this file'), required=False, dest='show_history_from_file') parser.add_argument( '-E', help=( 'show trading performance report dataset in this file'), required=False, dest='show_report_from_file') parser.add_argument( '-L', help=( 'restore an algorithm-ready dataset file back into redis'), required=False, dest='restore_algo_file') parser.add_argument( '-f', help=( 'save the trading history dataframe ' 'to this file'), required=False, dest='history_json_file') parser.add_argument( '-J', help=( 'plot action - after preparing you can use: ' '-J show to open the image (good for debugging)'), required=False, dest='plot_action') parser.add_argument( '-b', help=( 'run a backtest using the dataset in ' 'a file path/s3 key/redis key formats: ' 'file:/opt/sa/tests/datasets/algo/SPY-latest.json or ' 's3://algoready/SPY-latest.json or ' 'redis:SPY-latest'), required=False, dest='backtest_loc') parser.add_argument( '-B', help=( 'optional - broker url for Celery'), required=False, dest='broker_url') parser.add_argument( '-C', help=( 'optional - broker url for Celery'), required=False, dest='backend_url') parser.add_argument( '-w', help=( 'optional - flag for publishing an algorithm job ' 'using Celery to the ae workers'), required=False, dest='run_on_engine', action='store_true') parser.add_argument( '-k', help=( 'optional - s3 access key'), required=False, dest='s3_access_key') parser.add_argument( '-K', help=( 'optional - s3 secret key'), required=False, dest='s3_secret_key') parser.add_argument( '-a', help=( 'optional - s3 address format: <host:port>'), required=False, dest='s3_address') parser.add_argument( '-Z', help=( 'optional - s3 secure: default False'), required=False, dest='s3_secure') parser.add_argument( '-s', help=( 'optional - start date: YYYY-MM-DD'), required=False, dest='start_date') parser.add_argument( '-n', help=( 'optional - end date: YYYY-MM-DD'), required=False, dest='end_date') parser.add_argument( '-u', help=( 'optional - s3 bucket name'), required=False, dest='s3_bucket_name') parser.add_argument( '-G', help=( 'optional - s3 region name'), required=False, dest='s3_region_name') parser.add_argument( '-g', help=( 'Path to a custom algorithm module file ' 'on disk. This module must have a single ' 'class that inherits from: ' 'https://github.com/AlgoTraders/stock-analysis-engine/' 'blob/master/' 'analysis_engine/algo.py Additionally you ' 'can find the Example-Minute-Algorithm here: ' 'https://github.com/AlgoTraders/stock-analysis-engine/' 'blob/master/analysis_engine/mocks/' 'example_algo_minute.py'), required=False, dest='run_algo_in_file') parser.add_argument( '-p', help=( 'optional - s3 bucket/file for trading history'), required=False, dest='algo_history_loc') parser.add_argument( '-o', help=( 'optional - s3 bucket/file for trading performance report'), required=False, dest='algo_report_loc') parser.add_argument( '-r', help=( 'optional - redis_address format: <host:port>'), required=False, dest='redis_address') parser.add_argument( '-R', help=( 'optional - redis and s3 key name'), required=False, dest='keyname') parser.add_argument( '-m', help=( 'optional - redis database number (0 by default)'), required=False, dest='redis_db') parser.add_argument( '-x', help=( 'optional - redis expiration in seconds'), required=False, dest='redis_expire') parser.add_argument( '-c', help=( 'optional - algorithm config_file path for setting ' 'up internal algorithm trading strategies and ' 'indicators'), required=False, dest='config_file') parser.add_argument( '-v', help=( 'set the Algorithm to verbose logging'), required=False, dest='verbose_algo', action='store_true') parser.add_argument( '-P', help=( 'set the Algorithm\'s IndicatorProcessor to verbose logging'), required=False, dest='verbose_processor', action='store_true') parser.add_argument( '-I', help=( 'set all Algorithm\'s Indicators to verbose logging ' '(note indivdual indicators support a \'verbose\' key ' 'that can be set to True to debug just one ' 'indicator)'), required=False, dest='verbose_indicators', action='store_true') parser.add_argument( '-V', help=( 'inspect the datasets an algorithm is processing - this' 'will slow down processing to show debugging'), required=False, dest='inspect_datasets', action='store_true') parser.add_argument( '-j', help=( 'run the algorithm on just this specific date in the datasets ' '- specify the date in a format: YYYY-MM-DD like: 2018-11-29'), required=False, dest='run_this_date') parser.add_argument( '-d', help=( 'debug'), required=False, dest='debug', action='store_true') args = parser.parse_args() ticker = ae_consts.TICKER use_balance = 10000.0 use_commission = 6.0 use_start_date = None use_end_date = None use_config_file = None debug = False verbose_algo = None verbose_processor = None verbose_indicators = None inspect_datasets = None history_json_file = None run_this_date = None s3_access_key = ae_consts.S3_ACCESS_KEY s3_secret_key = ae_consts.S3_SECRET_KEY s3_region_name = ae_consts.S3_REGION_NAME s3_address = ae_consts.S3_ADDRESS s3_secure = ae_consts.S3_SECURE redis_address = ae_consts.REDIS_ADDRESS redis_password = ae_<PASSWORD>.<PASSWORD> redis_db = ae_consts.REDIS_DB redis_expire = ae_consts.REDIS_EXPIRE if args.s3_access_key: s3_access_key = args.s3_access_key if args.s3_secret_key: s3_secret_key = args.s3_secret_key if args.s3_region_name: s3_region_name = args.s3_region_name if args.s3_address: s3_address = args.s3_address if args.s3_secure: s3_secure = args.s3_secure if args.redis_address: redis_address = args.redis_address if args.redis_db: redis_db = args.redis_db if args.redis_expire: redis_expire = args.redis_expire if args.history_json_file: history_json_file = args.history_json_file if args.ticker: ticker = args.ticker.upper() if args.debug: debug = True if args.verbose_algo: verbose_algo = True if args.verbose_processor: verbose_processor = True if args.verbose_indicators: verbose_indicators = True if args.inspect_datasets: inspect_datasets = True if args.run_this_date: run_this_date = args.run_this_date if args.start_date: try: use_start_date = f'{str(args.start_date)} 00:00:00' datetime.datetime.strptime( args.start_date, ae_consts.COMMON_DATE_FORMAT) except Exception as e: msg = ( 'please use a start date formatted as: ' f'{ae_consts.COMMON_DATE_FORMAT}\nerror was: {e}') log.error(msg) sys.exit(1) # end of testing for a valid date # end of args.start_date if args.end_date: try: use_end_date = f'{str(args.end_date)} 00:00:00' datetime.datetime.strptime( args.end_date, ae_consts.COMMON_DATE_FORMAT) except Exception as e: msg = ( 'please use an end date formatted as: ' f'{ae_consts.COMMON_DATE_FORMAT}\nerror was: {e}') log.error(msg) sys.exit(1) # end of testing for a valid date # end of args.end_date if args.config_file: use_config_file = args.config_file if not os.path.exists(use_config_file): log.error( f'Failed: unable to find config file: -c {use_config_file}') sys.exit(1) if args.backtest_loc: backtest_loc = args.backtest_loc if ('file:/' not in backtest_loc and 's3://' not in backtest_loc and 'redis://' not in backtest_loc): log.error( 'invalid -b <backtest dataset file> specified. ' f'{backtest_loc} ' 'please use either: ' '-b file:/opt/sa/tests/datasets/algo/SPY-latest.json or ' '-b s3://algoready/SPY-latest.json or ' '-b redis://SPY-latest') sys.exit(1) load_from_s3_bucket = None load_from_s3_key = None load_from_redis_key = None load_from_file = None if 's3://' in backtest_loc: load_from_s3_bucket = backtest_loc.split('/')[-2] load_from_s3_key = backtest_loc.split('/')[-1] elif 'redis://' in backtest_loc: load_from_redis_key = backtest_loc.split('/')[-1] elif 'file:/' in backtest_loc: load_from_file = backtest_loc.split(':')[-1] # end of parsing supported transport - loading an algo-ready load_config = build_publish_request.build_publish_request( ticker=ticker, output_file=load_from_file, s3_bucket=load_from_s3_bucket, s3_key=load_from_s3_key, redis_key=load_from_redis_key, redis_address=redis_address, redis_db=redis_db, redis_password=<PASSWORD>, redis_expire=redis_expire, s3_address=s3_address, s3_access_key=s3_access_key, s3_secret_key=s3_secret_key, s3_region_name=s3_region_name, s3_secure=s3_secure, verbose=debug, label=f'load-{backtest_loc}') if load_from_file: load_config['output_file'] = load_from_file if load_from_redis_key: load_config['redis_key'] = load_from_redis_key load_config['redis_enabled'] = True if load_from_s3_bucket and load_from_s3_key: load_config['s3_bucket'] = load_from_s3_bucket load_config['s3_key'] = load_from_s3_key load_config['s3_enabled'] = True if debug: log.info('starting algo') config_dict['ticker'] = ticker config_dict['balance'] = use_balance config_dict['commission'] = use_commission if verbose_algo: config_dict['verbose'] = verbose_algo if verbose_processor: config_dict['verbose_processor'] = verbose_processor if verbose_indicators: config_dict['verbose_indicators'] = verbose_indicators if inspect_datasets: config_dict['inspect_datasets'] = inspect_datasets if run_this_date: config_dict['run_this_date'] = run_this_date algo_obj = ExampleCustomAlgo( ticker=config_dict['ticker'], config_dict=config_dict) algo_res = run_algo.run_algo( ticker=ticker, algo=algo_obj, start_date=use_start_date, end_date=use_end_date, raise_on_err=True) if algo_res['status'] != ae_consts.SUCCESS: log.error( 'failed running algo backtest ' f'{algo_obj.get_name()} hit status: ' f'{ae_consts.get_status(status=algo_res["status"])} ' f'error: {algo_res["err"]}') return # if not successful log.info( f'backtest: {algo_obj.get_name()} ' f'{ae_consts.get_status(status=algo_res["status"])}') trading_history_dict = algo_obj.get_history_dataset() history_df = trading_history_dict[ticker] if not hasattr(history_df, 'to_json'): return if history_json_file: log.info(f'saving history to: {history_json_file}') history_df.to_json( history_json_file, orient='records', date_format='iso') log.info('plotting history') use_xcol = 'date' use_as_date_format = '%d\n%b' xlabel = f'Dates vs {trading_history_dict["algo_name"]} values' ylabel = f'Algo {trading_history_dict["algo_name"]}\nvalues' df_filter = (history_df['close'] > 0.01) first_date = history_df[df_filter]['date'].iloc[0] end_date = history_df[df_filter]['date'].iloc[-1] if config_dict['timeseries'] == 'minute': use_xcol = 'minute' use_as_date_format = '%d %H:%M:%S\n%b' first_date = history_df[df_filter]['minute'].iloc[0] end_date = history_df[df_filter]['minute'].iloc[-1] title = ( f'Trading History {ticker} for Algo ' f'{trading_history_dict["algo_name"]}\n' f'Backtest dates from {first_date} to {end_date}') # set default hloc columns: blue = None green = None orange = None red = 'close' blue = 'balance' if debug: for i, r in history_df.iterrows(): log.debug(f'{r["minute"]} - {r["close"]}') plot_trading_history.plot_trading_history( title=title, df=history_df, red=red, blue=blue, green=green, orange=orange, date_col=use_xcol, date_format=use_as_date_format, xlabel=xlabel, ylabel=ylabel, df_filter=df_filter, show_plot=True, dropna_for_all=True) # end of run_backtest_and_plot_history def start_backtest_with_plot_history(): """start_backtest_with_plot_history setup.py helper for kicking off a backtest that will plot the trading history using seaborn and matplotlib showing the algorithm's balance vs the closing price of the asset """ run_backtest_and_plot_history( config_dict=build_example_algo_config( ticker='SPY', timeseries='minute')) # end of start_backtest_with_plot_history if __name__ == '__main__': start_backtest_with_plot_history()
14,808
1,909
<reponame>state303/spring-batch package org.springframework.batch.integration.chunk; import static org.junit.Assert.assertEquals; import java.util.Collections; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobParameter; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.launch.JobLauncher; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @ContextConfiguration @RunWith(SpringJUnit4ClassRunner.class) public class RemoteChunkStepIntegrationTests { @Autowired private JobLauncher jobLauncher; @Autowired private Job job; @Test public void testSunnyDaySimpleStep() throws Exception { JobExecution jobExecution = jobLauncher.run(job, new JobParameters(Collections.singletonMap("item.three", new JobParameter("3")))); assertEquals(BatchStatus.COMPLETED, jobExecution.getStatus()); StepExecution stepExecution = jobExecution.getStepExecutions().iterator().next(); assertEquals(9, stepExecution.getReadCount()); assertEquals(9, stepExecution.getWriteCount()); } @Test public void testFailedStep() throws Exception { JobExecution jobExecution = jobLauncher.run(job, new JobParameters(Collections.singletonMap("item.three", new JobParameter("fail")))); assertEquals(BatchStatus.FAILED, jobExecution.getStatus()); StepExecution stepExecution = jobExecution.getStepExecutions().iterator().next(); assertEquals(9, stepExecution.getReadCount()); // In principle the write count could be more than 2 and less than 9... assertEquals(7, stepExecution.getWriteCount()); } }
656
679
/************************************************************** * * 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. * *************************************************************/ #ifndef _FRMPAGE_HXX #define _FRMPAGE_HXX #include <vcl/fixed.hxx> #include <vcl/button.hxx> #include <vcl/lstbox.hxx> #include <vcl/field.hxx> #include <sfx2/tabdlg.hxx> #include <svx/swframeposstrings.hxx> #include <swtypes.hxx> #include <bmpwin.hxx> #include <svx/swframeexample.hxx> #include <prcntfld.hxx> #include <globals.hrc> namespace sfx2{class FileDialogHelper;} class SwWrtShell; struct FrmMap; // OD 12.11.2003 #i22341# struct SwPosition; /*-------------------------------------------------------------------- Beschreibung: Rahmendialog --------------------------------------------------------------------*/ class SwFrmPage: public SfxTabPage { // Size FixedLine aSizeFL; FixedText aWidthFT; FixedText aWidthAutoFT; PercentField aWidthED; CheckBox aRelWidthCB; CheckBox aAutoWidthCB; FixedText aHeightFT; FixedText aHeightAutoFT; PercentField aHeightED; CheckBox aRelHeightCB; CheckBox aAutoHeightCB; CheckBox aFixedRatioCB; PushButton aRealSizeBT; // Anker FixedLine aTypeSepFL; FixedLine aTypeFL; RadioButton aAnchorAtPageRB; RadioButton aAnchorAtParaRB; RadioButton aAnchorAtCharRB; RadioButton aAnchorAsCharRB; RadioButton aAnchorAtFrameRB; // Position FixedLine aPositionFL; FixedText aHorizontalFT; ListBox aHorizontalDLB; FixedText aAtHorzPosFT; MetricField aAtHorzPosED; FixedText aHoriRelationFT; ListBox aHoriRelationLB; CheckBox aMirrorPagesCB; FixedText aVerticalFT; ListBox aVerticalDLB; FixedText aAtVertPosFT; MetricField aAtVertPosED; FixedText aVertRelationFT; ListBox aVertRelationLB; // OD 02.10.2003 #i18732# - check box for new option 'FollowTextFlow' CheckBox aFollowTextFlowCB; // Example SvxSwFrameExample aExampleWN; //'string provider' SvxSwFramePosString aFramePosString; sal_Bool bAtHorzPosModified; sal_Bool bAtVertPosModified; sal_Bool bFormat; sal_Bool bNew; sal_Bool bNoModifyHdl; sal_Bool bVerticalChanged; //check done whether frame is in vertical environment sal_Bool bIsVerticalFrame; //current frame is in vertical environment - strings are exchanged // --> OD 2009-08-31 #mongolianlayou# sal_Bool bIsVerticalL2R; // <-- sal_Bool bIsInRightToLeft; // current frame is in right-to-left environment - strings are exchanged sal_Bool bHtmlMode; sal_uInt16 nHtmlMode; sal_uInt16 nDlgType; Size aGrfSize; Size aWrap; SwTwips nUpperBorder; SwTwips nLowerBorder; double fWidthHeightRatio; //width-to-height ratio to support the KeepRatio button // OD 12.11.2003 #i22341# - keep content position of character for // to character anchored objects. const SwPosition* mpToCharCntntPos; // Die alten Ausrichtungen short nOldH; short nOldHRel; short nOldV; short nOldVRel; FrmMap* pVMap; FrmMap* pHMap; bool m_bAllowVertPositioning; bool m_bIsMathOLE; bool m_bIsMathBaselineAlignment; virtual void ActivatePage(const SfxItemSet& rSet); virtual int DeactivatePage(SfxItemSet *pSet); DECL_LINK( RangeModifyHdl, Edit * ); DECL_LINK( AnchorTypeHdl, RadioButton * ); DECL_LINK( PosHdl, ListBox * ); DECL_LINK( RelHdl, ListBox * ); void InitPos(RndStdIds eId, sal_uInt16 nH, sal_uInt16 nHRel, sal_uInt16 nV, sal_uInt16 nVRel, long nX, long nY); DECL_LINK( RealSizeHdl, Button * ); DECL_LINK( RelSizeClickHdl, CheckBox * ); DECL_LINK( MirrorHdl, CheckBox * ); DECL_LINK( AutoWidthClickHdl, void* ); DECL_LINK( AutoHeightClickHdl, void* ); // Beispiel aktualisieren void UpdateExample(); DECL_LINK( ModifyHdl, Edit * ); void Init(const SfxItemSet& rSet, sal_Bool bReset = sal_False); // OD 12.11.2003 #i22341# - adjustment to handle maps, that are ambigous // in the alignment. sal_uInt16 FillPosLB( const FrmMap* _pMap, const sal_uInt16 _nAlign, const sal_uInt16 _nRel, ListBox& _rLB ); // OD 14.11.2003 #i22341# - adjustment to handle maps, that are ambigous // in their string entries. sal_uLong FillRelLB( const FrmMap* _pMap, const sal_uInt16 _nLBSelPos, const sal_uInt16 _nAlign, sal_uInt16 _nRel, ListBox& _rLB, FixedText& _rFT ); sal_uInt16 GetMapPos( const FrmMap *pMap, ListBox &rAlignLB ); short GetAlignment(FrmMap *pMap, sal_uInt16 nMapPos, ListBox &rAlignLB, ListBox &rRelationLB); short GetRelation(FrmMap *pMap, ListBox &rRelationLB); RndStdIds GetAnchor(); void EnableGraficMode( void ); // hides auto check boxes and re-org controls for "Real Size" button SwFrmPage(Window *pParent, const SfxItemSet &rSet); ~SwFrmPage(); using SfxTabPage::ActivatePage; using SfxTabPage::DeactivatePage; public: static SfxTabPage *Create(Window *pParent, const SfxItemSet &rSet); static sal_uInt16* GetRanges(); virtual sal_Bool FillItemSet(SfxItemSet &rSet); virtual void Reset(const SfxItemSet &rSet); void SetNewFrame(sal_Bool bNewFrame) { bNew = bNewFrame; } void SetFormatUsed(sal_Bool bFmt); void SetFrmType(sal_uInt16 nType) { nDlgType = nType; } inline sal_Bool IsInGraficMode( void ) { return nDlgType == DLG_FRM_GRF || nDlgType == DLG_FRM_OLE; } void EnableVerticalPositioning( bool bEnable ); }; class SwGrfExtPage: public SfxTabPage { // Spiegeln FixedLine aMirrorFL; CheckBox aMirrorVertBox; CheckBox aMirrorHorzBox; RadioButton aAllPagesRB; RadioButton aLeftPagesRB; RadioButton aRightPagesRB; BmpWindow aBmpWin; FixedLine aConnectFL; FixedText aConnectFT; Edit aConnectED; PushButton aBrowseBT; String aFilterName; String aGrfName, aNewGrfName; ::sfx2::FileDialogHelper* pGrfDlg; sal_Bool bHtmlMode; // Handler fuer Spiegeln DECL_LINK( MirrorHdl, CheckBox * ); DECL_LINK( BrowseHdl, Button * ); virtual void ActivatePage(const SfxItemSet& rSet); SwGrfExtPage(Window *pParent, const SfxItemSet &rSet); ~SwGrfExtPage(); using SfxTabPage::ActivatePage; using SfxTabPage::DeactivatePage; public: static SfxTabPage *Create(Window *pParent, const SfxItemSet &rSet); virtual sal_Bool FillItemSet(SfxItemSet &rSet); virtual void Reset(const SfxItemSet &rSet); virtual int DeactivatePage(SfxItemSet *pSet); }; class SwFrmURLPage : public SfxTabPage { //Hyperlink FixedLine aHyperLinkFL; FixedText aURLFT; Edit aURLED; PushButton aSearchPB; FixedText aNameFT; Edit aNameED; FixedText aFrameFT; ComboBox aFrameCB; //Image map FixedLine aImageFL; CheckBox aServerCB; CheckBox aClientCB; DECL_LINK( InsertFileHdl, PushButton * ); SwFrmURLPage(Window *pParent, const SfxItemSet &rSet); ~SwFrmURLPage(); using SfxTabPage::ActivatePage; using SfxTabPage::DeactivatePage; public: static SfxTabPage *Create(Window *pParent, const SfxItemSet &rSet); virtual sal_Bool FillItemSet(SfxItemSet &rSet); virtual void Reset(const SfxItemSet &rSet); }; /*-----------------13.11.96 12.59------------------- --------------------------------------------------*/ class SwFrmAddPage : public SfxTabPage { FixedLine aNamesFL; FixedText aNameFT; Edit aNameED; FixedText aAltNameFT; Edit aAltNameED; FixedText aPrevFT; ListBox aPrevLB; FixedText aNextFT; ListBox aNextLB; FixedLine aProtectFL; CheckBox aProtectContentCB; CheckBox aProtectFrameCB; CheckBox aProtectSizeCB; FixedLine aExtFL; CheckBox aEditInReadonlyCB; CheckBox aPrintFrameCB; FixedText aTextFlowFT; ListBox aTextFlowLB; SwWrtShell* pWrtSh; sal_uInt16 nDlgType; sal_Bool bHtmlMode; sal_Bool bFormat; sal_Bool bNew; DECL_LINK(EditModifyHdl, Edit*); DECL_LINK(ChainModifyHdl, ListBox*); SwFrmAddPage(Window *pParent, const SfxItemSet &rSet); ~SwFrmAddPage(); public: static SfxTabPage* Create(Window *pParent, const SfxItemSet &rSet); static sal_uInt16* GetRanges(); virtual sal_Bool FillItemSet(SfxItemSet &rSet); virtual void Reset(const SfxItemSet &rSet); void SetFormatUsed(sal_Bool bFmt); void SetFrmType(sal_uInt16 nType) { nDlgType = nType; } void SetNewFrame(sal_Bool bNewFrame) { bNew = bNewFrame; } void SetShell(SwWrtShell* pSh) { pWrtSh = pSh; } }; #endif // _FRMPAGE_HXX
4,204
1,338
#ifndef _DEVICE_NRS_H_ #define _DEVICE_NRS_H_ // ToDo: do something nice here, perhaps reusing the new stat->st_type field #define DEV_TTY_P(stat) (0) #endif /* _DEVICE_NRS_H_ */
77
343
<gh_stars>100-1000 // Copyright 2013 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. #include "syzygy/genfilter/filter_compiler.h" #include "base/files/file_util.h" #include "gtest/gtest.h" #include "syzygy/common/unittest_util.h" #include "syzygy/core/unittest_util.h" #include "syzygy/pe/unittest_util.h" namespace genfilter { namespace { class TestFilterCompiler : public FilterCompiler { public: using FilterCompiler::Rule; using FilterCompiler::RuleMap; using FilterCompiler::RulePointers; using FilterCompiler::rule_map_; using FilterCompiler::rules_by_type_; TestFilterCompiler() { } // Returns the |index|th rule. const Rule& rule(size_t index) const { RuleMap::const_iterator it = rule_map_.find(index); return it->second; } }; class FilterCompilerTest : public testing::PELibUnitTest { public: typedef testing::PELibUnitTest Super; virtual void SetUp() override { Super::SetUp(); ASSERT_NO_FATAL_FAILURE(CreateTemporaryDir(&temp_dir_)); test_dll_ = testing::GetExeRelativePath(testing::kTestDllName); test_dll_pdb_ = testing::GetOutputRelativePath(testing::kTestDllPdbName); dummy_dll_ = testing::GetExeRelativePath(L"this-does-not-exist.dll"); dummy_pdb_ = testing::GetExeRelativePath(L"this-does-not-exist.pdb"); mismatched_test_dll_pdb_ = testing::GetSrcRelativePath(L"pe\\test_data\\test_dll.pdb"); filter_txt_ = temp_dir_.Append(L"filter.txt"); } virtual void TearDown() override { ASSERT_TRUE(base::DeleteFile(temp_dir_, true)); Super::TearDown(); } void CreateFilterDescriptionFile(const base::StringPiece& line) { base::ScopedFILE file(base::OpenFile(filter_txt_, "wb")); ::fprintf(file.get(), "%.*s\n", line.length(), line.data()); } void CreateFilterDescriptionFile() { base::ScopedFILE file(base::OpenFile(filter_txt_, "wb")); ::fprintf(file.get(), "# This is a comment.\n"); ::fprintf(file.get(), "\n"); ::fprintf(file.get(), "+function:DllMain # Another comment.\n"); ::fprintf(file.get(), " + function : ThisFunctionDoesNotExist \n"); ::fprintf(file.get(), "-public_symbol:\\?function1.*\n"); } // A temporary folder for holding filter files, etc. base::FilePath temp_dir_; // A handful of paths. base::FilePath test_dll_; base::FilePath test_dll_pdb_; base::FilePath dummy_dll_; base::FilePath dummy_pdb_; base::FilePath mismatched_test_dll_pdb_; base::FilePath filter_txt_; }; } // namespace TEST_F(FilterCompilerTest, Constructor) { TestFilterCompiler fc; EXPECT_TRUE(fc.image_path().empty()); EXPECT_TRUE(fc.pdb_path().empty()); EXPECT_TRUE(fc.rule_map_.empty()); for (size_t i = 0; i < arraysize(fc.rules_by_type_); ++i) { EXPECT_TRUE(fc.rules_by_type_[i].empty()); } } TEST_F(FilterCompilerTest, InitFailsInvalidPePath) { DisableLogging(); TestFilterCompiler fc1; EXPECT_FALSE(fc1.Init(dummy_dll_)); TestFilterCompiler fc2; EXPECT_FALSE(fc2.Init(dummy_dll_, base::FilePath())); } TEST_F(FilterCompilerTest, InitFailsInvalidPdbPath) { DisableLogging(); TestFilterCompiler fc; EXPECT_FALSE(fc.Init(test_dll_, dummy_pdb_)); } TEST_F(FilterCompilerTest, InitFailsMismatchedPeAndPdb) { DisableLogging(); TestFilterCompiler fc; EXPECT_FALSE(fc.Init(test_dll_, mismatched_test_dll_pdb_)); } TEST_F(FilterCompilerTest, InitSucceedsSpecifiedPdb) { TestFilterCompiler fc; EXPECT_TRUE(fc.Init(test_dll_, test_dll_pdb_)); EXPECT_EQ(test_dll_, fc.image_path()); EXPECT_EQ(test_dll_pdb_, fc.pdb_path()); } TEST_F(FilterCompilerTest, InitSucceedsSearchForPdb) { TestFilterCompiler fc1; EXPECT_TRUE(fc1.Init(test_dll_)); EXPECT_EQ(test_dll_, fc1.image_path()); EXPECT_SAME_FILE(test_dll_pdb_, fc1.pdb_path()); TestFilterCompiler fc2; EXPECT_TRUE(fc2.Init(test_dll_, base::FilePath())); EXPECT_EQ(test_dll_, fc2.image_path()); EXPECT_SAME_FILE(test_dll_pdb_, fc2.pdb_path()); } TEST_F(FilterCompilerTest, AddRule) { DisableLogging(); TestFilterCompiler fc; ASSERT_TRUE(fc.Init(test_dll_, test_dll_pdb_)); EXPECT_EQ(0u, fc.rule_map_.size()); EXPECT_EQ(0u, fc.rules_by_type_[FilterCompiler::kFunctionRule].size()); EXPECT_EQ(0u, fc.rules_by_type_[FilterCompiler::kPublicSymbolRule].size()); EXPECT_FALSE(fc.AddRule(FilterCompiler::kAddToFilter, FilterCompiler::kFunctionRule, "broken(regex[foo")); EXPECT_TRUE(fc.AddRule(FilterCompiler::kAddToFilter, FilterCompiler::kFunctionRule, "foo")); EXPECT_EQ(1u, fc.rule_map_.size()); EXPECT_EQ(1u, fc.rules_by_type_[FilterCompiler::kFunctionRule].size()); EXPECT_EQ(0u, fc.rules_by_type_[FilterCompiler::kPublicSymbolRule].size()); EXPECT_TRUE(fc.AddRule(FilterCompiler::kSubtractFromFilter, FilterCompiler::kPublicSymbolRule, "bar")); EXPECT_EQ(2u, fc.rule_map_.size()); EXPECT_EQ(1u, fc.rules_by_type_[FilterCompiler::kFunctionRule].size()); EXPECT_EQ(1u, fc.rules_by_type_[FilterCompiler::kPublicSymbolRule].size()); } TEST_F(FilterCompilerTest, ParseFilterDescriptionFileMissingFile) { DisableLogging(); TestFilterCompiler fc; ASSERT_TRUE(fc.Init(test_dll_, test_dll_pdb_)); EXPECT_FALSE(fc.ParseFilterDescriptionFile(filter_txt_)); } TEST_F(FilterCompilerTest, ParseFilterDescriptionFileBadModificationType) { DisableLogging(); ASSERT_NO_FATAL_FAILURE(CreateFilterDescriptionFile("?function:foo")); TestFilterCompiler fc; ASSERT_TRUE(fc.Init(test_dll_, test_dll_pdb_)); EXPECT_FALSE(fc.ParseFilterDescriptionFile(filter_txt_)); } TEST_F(FilterCompilerTest, ParseFilterDescriptionFileBadRuleType) { DisableLogging(); ASSERT_NO_FATAL_FAILURE(CreateFilterDescriptionFile( "+invalid_type:foo")); TestFilterCompiler fc; ASSERT_TRUE(fc.Init(test_dll_, test_dll_pdb_)); EXPECT_FALSE(fc.ParseFilterDescriptionFile(filter_txt_)); } TEST_F(FilterCompilerTest, ParseFilterDescriptionFileBadRegex) { DisableLogging(); ASSERT_NO_FATAL_FAILURE(CreateFilterDescriptionFile( "+function:broken(regex[ab")); TestFilterCompiler fc; ASSERT_TRUE(fc.Init(test_dll_, test_dll_pdb_)); EXPECT_FALSE(fc.ParseFilterDescriptionFile(filter_txt_)); } TEST_F(FilterCompilerTest, ParseFilterDescriptionFileSucceeds) { ASSERT_NO_FATAL_FAILURE(CreateFilterDescriptionFile()); TestFilterCompiler fc; ASSERT_TRUE(fc.Init(test_dll_, test_dll_pdb_)); ASSERT_TRUE(fc.ParseFilterDescriptionFile(filter_txt_)); EXPECT_EQ(3u, fc.rule_map_.size()); EXPECT_EQ(FilterCompiler::kFunctionRule, fc.rule(0).rule_type); EXPECT_EQ(FilterCompiler::kFunctionRule, fc.rule(1).rule_type); EXPECT_EQ(FilterCompiler::kPublicSymbolRule, fc.rule(2).rule_type); EXPECT_EQ(FilterCompiler::kAddToFilter, fc.rule(0).modification_type); EXPECT_EQ(FilterCompiler::kAddToFilter, fc.rule(1).modification_type); EXPECT_EQ(FilterCompiler::kSubtractFromFilter, fc.rule(2).modification_type); } TEST_F(FilterCompilerTest, Compile) { ASSERT_NO_FATAL_FAILURE(CreateFilterDescriptionFile()); TestFilterCompiler fc; ASSERT_TRUE(fc.Init(test_dll_, test_dll_pdb_)); ASSERT_TRUE(fc.ParseFilterDescriptionFile(filter_txt_)); ASSERT_EQ(3u, fc.rule_map_.size()); // Three rules should have been parsed. pe::ImageFilter filter; EXPECT_TRUE(fc.Compile(&filter)); // The first and last rules should have matched actual symbol info. EXPECT_EQ(1u, fc.rule(0).ranges.size()); EXPECT_EQ(0u, fc.rule(1).ranges.size()); EXPECT_EQ(1u, fc.rule(2).ranges.size()); // The image filter should be non-empty. EXPECT_LT(0u, filter.filter.size()); } } // namespace genfilter
3,273
401
package com.almasb.tutorial10; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Paths; import javafx.animation.TranslateTransition; import javafx.application.Application; import javafx.geometry.*; import javafx.scene.*; import javafx.scene.image.*; import javafx.scene.layout.*; import javafx.scene.paint.*; import javafx.scene.shape.*; import javafx.scene.text.*; import javafx.scene.input.KeyCode; import javafx.scene.effect.DropShadow; import javafx.stage.Stage; import javafx.util.Duration; public class Main extends Application { private static Font font; private MenuBox menu; private Parent createContent() { Pane root = new Pane(); root.setPrefSize(800, 600); try (InputStream is = Files.newInputStream(Paths.get("res/images/cod_bg.jpg")); InputStream fontStream = Files.newInputStream(Paths.get("res/fonts/cod_font.ttf"))) { ImageView img = new ImageView(new Image(is)); img.setFitWidth(1066); img.setFitHeight(600); root.getChildren().add(img); font = Font.loadFont(fontStream, 30); } catch (IOException e) { System.out.println("Couldn't load image or font"); } MenuItem itemQuit = new MenuItem("QUIT"); itemQuit.setOnMouseClicked(event -> System.exit(0)); menu = new MenuBox("CAMPAIGN", new MenuItem("RESUME GAME"), new MenuItem("NEW GAME"), new MenuItem("MISSION SELECT"), new MenuItem("OPTIONS"), new MenuItem("CREDITS"), new MenuItem("MAIN MENU"), itemQuit); root.getChildren().add(menu); return root; } @Override public void start(Stage primaryStage) throws Exception { Scene scene = new Scene(createContent()); scene.setOnKeyPressed(event -> { if (event.getCode() == KeyCode.ESCAPE) { if (menu.isVisible()) { menu.hide(); } else { menu.show(); } } }); primaryStage.setTitle("Tutorial"); primaryStage.setScene(scene); primaryStage.show(); } private static class MenuBox extends StackPane { public MenuBox(String title, MenuItem... items) { Rectangle bg = new Rectangle(300, 600); bg.setOpacity(0.2); DropShadow shadow = new DropShadow(7, 5, 0, Color.BLACK); shadow.setSpread(0.8); bg.setEffect(shadow); Text text = new Text(title + " "); text.setFont(font); text.setFill(Color.WHITE); Line hSep = new Line(); hSep.setEndX(250); hSep.setStroke(Color.DARKGREEN); hSep.setOpacity(0.4); Line vSep = new Line(); vSep.setStartX(300); vSep.setEndX(300); vSep.setEndY(600); vSep.setStroke(Color.DARKGREEN); vSep.setOpacity(0.4); VBox vbox = new VBox(); vbox.setAlignment(Pos.TOP_RIGHT); vbox.setPadding(new Insets(60, 0, 0, 0)); vbox.getChildren().addAll(text, hSep); vbox.getChildren().addAll(items); setAlignment(Pos.TOP_RIGHT); getChildren().addAll(bg, vSep, vbox); } public void show() { setVisible(true); TranslateTransition tt = new TranslateTransition(Duration.seconds(0.5), this); tt.setToX(0); tt.play(); } public void hide() { TranslateTransition tt = new TranslateTransition(Duration.seconds(0.5), this); tt.setToX(-300); tt.setOnFinished(event -> setVisible(false)); tt.play(); } } private static class MenuItem extends StackPane { public MenuItem(String name) { Rectangle bg = new Rectangle(300, 24); LinearGradient gradient = new LinearGradient(0, 0, 1, 0, true, CycleMethod.NO_CYCLE, new Stop[] { new Stop(0, Color.BLACK), new Stop(0.2, Color.DARKGREY) }); bg.setFill(gradient); bg.setVisible(false); bg.setEffect(new DropShadow(5, 0, 5, Color.BLACK)); Text text = new Text(name + " "); text.setFill(Color.LIGHTGREY); text.setFont(Font.font(20)); setAlignment(Pos.CENTER_RIGHT); getChildren().addAll(bg, text); setOnMouseEntered(event -> { bg.setVisible(true); text.setFill(Color.WHITE); }); setOnMouseExited(event -> { bg.setVisible(false); text.setFill(Color.LIGHTGREY); }); setOnMousePressed(event -> { bg.setFill(Color.WHITE); text.setFill(Color.BLACK); }); setOnMouseReleased(event -> { bg.setFill(gradient); text.setFill(Color.WHITE); }); } } public static void main(String[] args) { launch(args); } }
2,709
9,425
""" :codeauthor: <NAME> <<EMAIL>> """ import pytest import salt.modules.win_timezone as win_timezone from salt.exceptions import CommandExecutionError from tests.support.mock import MagicMock, patch pytestmark = [ pytest.mark.skipif(not win_timezone.HAS_PYTZ, reason="This test requires pytz"), ] @pytest.fixture def configure_loader_modules(): return { win_timezone: { "__opts__": {}, "__salt__": {}, "__utils__": {}, }, } def test_get_zone_normal(): """ Test if it get current timezone (i.e. Asia/Calcutta) """ mock_read_ok = MagicMock( return_value={ "pid": 78, "retcode": 0, "stderr": "", "stdout": "India Standard Time", } ) with patch.dict(win_timezone.__salt__, {"cmd.run_all": mock_read_ok}): assert win_timezone.get_zone() == "Asia/Calcutta" def test_get_zone_normal_dstoff(): """ Test if it gets current timezone with dst off (i.e. America/Denver) """ mock_read_ok = MagicMock( return_value={ "pid": 78, "retcode": 0, "stderr": "", "stdout": "Mountain Standard Time_dstoff", } ) with patch.dict(win_timezone.__salt__, {"cmd.run_all": mock_read_ok}): assert win_timezone.get_zone() == "America/Denver" def test_get_zone_normal_dstoff_issue(): """ Test regression with dstoff fix stripping unwanted characters """ mock_read_ok = MagicMock( return_value={ "pid": 78, "retcode": 0, "stderr": "", "stdout": "FLE Standard Time", } ) with patch.dict(win_timezone.__salt__, {"cmd.run_all": mock_read_ok}): assert win_timezone.get_zone() == "Europe/Kiev" @pytest.mark.parametrize("timezone", win_timezone.mapper.list_win()) def test_get_zone_all(timezone): """ Test all Win zones are properly resolved and none returns Unknown """ mock_read_ok = MagicMock( return_value={ "pid": 78, "retcode": 0, "stderr": "", "stdout": timezone, } ) with patch.dict(win_timezone.__salt__, {"cmd.run_all": mock_read_ok}): assert win_timezone.get_zone() != "Unknown" def test_get_zone_unknown(): """ Test get_zone with unknown timezone (i.e. Indian Standard Time) """ mock_read_error = MagicMock( return_value={ "pid": 78, "retcode": 0, "stderr": "", "stdout": "Indian Standard Time", } ) with patch.dict(win_timezone.__salt__, {"cmd.run_all": mock_read_error}): assert win_timezone.get_zone() == "Unknown" def test_get_zone_error(): """ Test get_zone when it encounters an error """ mock_read_fatal = MagicMock( return_value={"pid": 78, "retcode": 1, "stderr": "", "stdout": ""} ) with patch.dict(win_timezone.__salt__, {"cmd.run_all": mock_read_fatal}): with pytest.raises(CommandExecutionError): win_timezone.get_zone() def test_get_offset(): """ Test if it get current numeric timezone offset from UCT (i.e. +0530) """ mock_read = MagicMock( return_value={ "pid": 78, "retcode": 0, "stderr": "", "stdout": "India Standard Time", } ) with patch.dict(win_timezone.__salt__, {"cmd.run_all": mock_read}): assert win_timezone.get_offset() == "+0530" def test_get_zonecode(): """ Test if it get current timezone (i.e. PST, MDT, etc) """ mock_read = MagicMock( return_value={ "pid": 78, "retcode": 0, "stderr": "", "stdout": "India Standard Time", } ) with patch.dict(win_timezone.__salt__, {"cmd.run_all": mock_read}): assert win_timezone.get_zonecode() == "IST" def test_set_zone(): """ Test if it unlinks, then symlinks /etc/localtime to the set timezone. """ mock_write = MagicMock( return_value={"pid": 78, "retcode": 0, "stderr": "", "stdout": ""} ) mock_read = MagicMock( return_value={ "pid": 78, "retcode": 0, "stderr": "", "stdout": "India Standard Time", } ) with patch.dict(win_timezone.__salt__, {"cmd.run_all": mock_write}), patch.dict( win_timezone.__salt__, {"cmd.run_all": mock_read} ): assert win_timezone.set_zone("Asia/Calcutta") def test_zone_compare(): """ Test if it checks the md5sum between the given timezone, and the one set in /etc/localtime. Returns True if they match, and False if not. Mostly useful for running state checks. """ mock_read = MagicMock( return_value={ "pid": 78, "retcode": 0, "stderr": "", "stdout": "India Standard Time", } ) with patch.dict(win_timezone.__salt__, {"cmd.run_all": mock_read}): assert win_timezone.zone_compare("Asia/Calcutta") def test_get_hwclock(): """ Test if it get current hardware clock setting (UTC or localtime) """ assert win_timezone.get_hwclock() == "localtime" def test_set_hwclock(): """ Test if it sets the hardware clock to be either UTC or localtime """ assert not win_timezone.set_hwclock("UTC")
2,563
734
/* ,--. ,--. ,--. ,--. ,-' '-.,--.--.,--,--.,---.| |,-.,-' '-.`--' ,---. ,--,--, Copyright 2018 '-. .-'| .--' ,-. | .--'| /'-. .-',--.| .-. || \ Tracktion Software | | | | \ '-' \ `--.| \ \ | | | |' '-' '| || | Corporation `---' `--' `--`--'`---'`--'`--' `---' `--' `---' `--''--' www.tracktion.com Tracktion Engine uses a GPL/commercial licence - see LICENCE.md for details. */ namespace tracktion_engine { struct ActiveNoteList { juce::uint16 activeChannels[128] = {}; void reset() noexcept { juce::zeromem (activeChannels, sizeof (activeChannels)); } bool isNoteActive (int channel, int note) const noexcept { return isValidIndex (channel, note) && (activeChannels[note] & (1u << (channel - 1))) != 0; } void startNote (int channel, int note) noexcept { if (isValidIndex (channel, note)) activeChannels[note] |= (1u << (channel - 1)); } void clearNote (int channel, int note) noexcept { if (isValidIndex (channel, note)) activeChannels[note] &= ~(1u << (channel - 1)); } template <typename Visitor> void iterate (Visitor&& v) const noexcept { for (int note = 0; note < 128; ++note) for (int chan = 0; chan < 16; ++chan) if ((activeChannels[note] & (1u << chan)) != 0) v (chan + 1, note); } static bool isValidIndex (int channel, int note) noexcept { return juce::isPositiveAndBelow (note, 128) && channel > 0 && channel <= 16; } }; } // namespace tracktion_engine
779
347
package org.ovirt.engine.core.common.validation.group; public interface ImportClonedEntity { }
30
1,364
<gh_stars>1000+ #ifndef SSF_SERVICES_COPY_STATE_SENDER_WAIT_EOF_STATE_H_ #define SSF_SERVICES_COPY_STATE_SENDER_WAIT_EOF_STATE_H_ #include <iostream> #include <msgpack.hpp> #include <ssf/log/log.h> #include "common/error/error.h" #include "services/copy/i_copy_state.h" #include "services/copy/packet/init.h" #include "services/copy/state/on_abort.h" #include "services/copy/state/sender/abort_sender_state.h" #include "services/copy/state/sender/close_state.h" #include "services/copy/state/sender/send_integrity_check_request_state.h" namespace ssf { namespace services { namespace copy { class WaitEofState : ICopyState { public: template <typename... Args> static ICopyStateUPtr Create(Args&&... args) { return ICopyStateUPtr(new WaitEofState(std::forward<Args>(args)...)); } private: WaitEofState() : ICopyState() {} public: // ICopyState void Enter(CopyContext* context, boost::system::error_code& ec) { SSF_LOG("microservice", trace, "[copy][wait_eof] enter"); } bool FillOutboundPacket(CopyContext* context, Packet* packet, boost::system::error_code& ec) { return false; } void ProcessInboundPacket(CopyContext* context, const Packet& packet, boost::system::error_code& ec) { if (context->input.good() && context->input.is_open()) { context->input.close(); } if (packet.type() == PacketType::kAbort) { return OnSenderAbortPacket(context, packet, ec); } if (packet.type() != PacketType::kEof) { SSF_LOG("microservice", debug, "[copy][wait_eof] cannot process inbound packet"); context->SetState( AbortSenderState::Create(ErrorCode::kInboundPacketNotSupported)); return; } if (context->check_file_integrity && !context->is_stdin_input) { context->SetState(SendIntegrityCheckRequestState::Create()); } else { context->error_code = ErrorCode::kSuccess; context->SetState(CloseState::Create()); } } bool IsTerminal(CopyContext* context) { return false; } }; } // copy } // services } // ssf #endif // SSF_SERVICES_COPY_STATE_SENDER_WAIT_EOF_STATE_H_
888
2,868
<reponame>jtravee/neuvector<filename>dp/third-party/hyperscan/src/parser/Component.h /* * Copyright (c) 2015, Intel Corporation * * 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 Intel Corporation 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. */ /** \file * \brief Base class for all components. */ #ifndef _RE_COMPONENT_H_ #define _RE_COMPONENT_H_ #include "ComponentVisitor.h" #include "ConstComponentVisitor.h" #include "position.h" #include "ue2common.h" #include <set> #include <string> #include <vector> namespace ue2 { class GlushkovBuildState; class PositionInfo; enum EmptyPathType { NOT_EMPTY, /**< component must consume characters */ EPS_ONLY_PATHS, /**< eps path with no overhanging asserts */ BOUNDARY_PATHS /**< eps paths some with overhanging asserts */ }; /** \brief Base class for regular expression parse tree components. */ class Component { friend class DumpVisitor; public: /** \brief Constructor. */ Component(); /** \brief Destructor. */ virtual ~Component(); /** \brief Returns a newly-allocated deep copy of this component. */ virtual Component *clone() const = 0; /** \brief Apply the given visitor functor. */ virtual Component *accept(ComponentVisitor &v) = 0; /** \brief Apply the given const visitor functor. */ virtual void accept(ConstComponentVisitor &v) const = 0; /** \brief Glushkov construction First() function. * \return set of initial positions in this component. */ virtual std::vector<PositionInfo> first() const = 0; /** \brief Glushkov construction Last() function. * \return set of final positions in this component. */ virtual std::vector<PositionInfo> last() const = 0; /** \brief Glushkov construction Empty() function. * \return true iff the component accepts epsilon. * * Note: ^, $, etc are considered empty. */ virtual bool empty() const = 0; /** \brief True iff epsilon can pass through the component. * * Note: ^, $, etc are not vacuous everywhere. */ virtual bool vacuous_everywhere(void) const; /** \brief True iff the component is repeatable on its own, without being * encapsulated in a sequence first. * * This is true for most components, but not for repeats, anchors and word * boundaries. */ virtual bool repeatable() const; /** \brief Optimisation pass on the component tree. * * Called before \ref notePositions. May modify to the component tree. * Assumes no start of match information is required. */ virtual void optimise(bool connected_to_sds); /** \brief Informs the Glushkov build process of the positions used by this * component. */ virtual void notePositions(GlushkovBuildState &bs) = 0; /** \brief Glushkov construction Follow() function. * * Constructs (in \a bs) the set of positions in this component reachable * from the positions in \a lastPos. * * \throw ParseError on failure */ virtual void buildFollowSet(GlushkovBuildState &bs, const std::vector<PositionInfo> &lastPos) = 0; /** \brief Return value is used for chaining, throws if finds embedded * anchor. */ virtual bool checkEmbeddedStartAnchor(bool at_start) const; /* \brief Return value is used for chaining, throws if finds embedded * anchor. */ virtual bool checkEmbeddedEndAnchor(bool at_end) const; protected: /** \brief Called during \ref notePositions. */ void recordPosBounds(u32 b, u32 e); u32 pos_begin; u32 pos_end; // Protected copy ctor. Use clone instead. Component(const Component &other) : pos_begin(other.pos_begin), pos_end(other.pos_end) {} }; } // namespace ue2 #endif
1,678
365
<filename>source/blender/blenlib/BLI_vector_adaptor.hh /* * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #pragma once /** \file * \ingroup bli * * A `blender::VectorAdaptor` is a container with a fixed maximum size and does not own the * underlying memory. When an adaptor is constructed, you have to provide it with an uninitialized * array that will be filled when elements are added to the vector. The vector adaptor is not able * to grow. Therefore, it is undefined behavior to add more elements than fit into the provided * buffer. */ #include "BLI_span.hh" namespace blender { template<typename T> class VectorAdaptor { private: T *begin_; T *end_; T *capacity_end_; public: VectorAdaptor() : begin_(nullptr), end_(nullptr), capacity_end_(nullptr) { } VectorAdaptor(T *data, int64_t capacity, int64_t size = 0) : begin_(data), end_(data + size), capacity_end_(data + capacity) { } VectorAdaptor(MutableSpan<T> span) : VectorAdaptor(span.data(), span.size(), 0) { } void append(const T &value) { BLI_assert(end_ < capacity_end_); new (end_) T(value); end_++; } void append(T &&value) { BLI_assert(end_ < capacity_end_); new (end_) T(std::move(value)); end_++; } void append_n_times(const T &value, int64_t n) { BLI_assert(end_ + n <= capacity_end_); uninitialized_fill_n(end_, n, value); end_ += n; } void extend(Span<T> values) { BLI_assert(end_ + values.size() <= capacity_end_); uninitialized_copy_n(values.data(), values.size(), end_); end_ += values.size(); } int64_t capacity() const { return capacity_end_ - begin_; } int64_t size() const { return end_ - begin_; } bool is_empty() const { return begin_ == end_; } bool is_full() const { return end_ == capacity_end_; } }; } // namespace blender
867
1,246
# Generated by Django 2.2.12 on 2020-05-27 07:01 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('instances', '0001_initial'), ] operations = [ migrations.CreateModel( name='PermissionSet', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], options={ 'permissions': (('clone_instances', 'Can clone instances'),), 'managed': False, 'default_permissions': (), }, ), ]
306
973
<gh_stars>100-1000 #ifndef OPENGL_GEN_CORE_1_0_HPP #define OPENGL_GEN_CORE_1_0_HPP #include "_int_load_test.hpp" namespace gl { namespace _detail { typedef void (CODEGEN_FUNCPTR * Proc_glBlendFunc)(GLenum sfactor, GLenum dfactor); typedef void (CODEGEN_FUNCPTR * Proc_glClear)(GLbitfield mask); typedef void (CODEGEN_FUNCPTR * Proc_glClearColor)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); typedef void (CODEGEN_FUNCPTR * Proc_glClearDepth)(GLdouble depth); typedef void (CODEGEN_FUNCPTR * Proc_glClearStencil)(GLint s); typedef void (CODEGEN_FUNCPTR * Proc_glColorMask)(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha); typedef void (CODEGEN_FUNCPTR * Proc_glCullFace)(GLenum mode); typedef void (CODEGEN_FUNCPTR * Proc_glDepthFunc)(GLenum func); typedef void (CODEGEN_FUNCPTR * Proc_glDepthMask)(GLboolean flag); typedef void (CODEGEN_FUNCPTR * Proc_glDepthRange)(GLdouble ren_near, GLdouble ren_far); typedef void (CODEGEN_FUNCPTR * Proc_glDisable)(GLenum cap); typedef void (CODEGEN_FUNCPTR * Proc_glDrawBuffer)(GLenum mode); typedef void (CODEGEN_FUNCPTR * Proc_glEnable)(GLenum cap); typedef void (CODEGEN_FUNCPTR * Proc_glFinish)(); typedef void (CODEGEN_FUNCPTR * Proc_glFlush)(); typedef void (CODEGEN_FUNCPTR * Proc_glFrontFace)(GLenum mode); typedef void (CODEGEN_FUNCPTR * Proc_glGetBooleanv)(GLenum pname, GLboolean * params); typedef void (CODEGEN_FUNCPTR * Proc_glGetDoublev)(GLenum pname, GLdouble * params); typedef GLenum (CODEGEN_FUNCPTR * Proc_glGetError)(); typedef void (CODEGEN_FUNCPTR * Proc_glGetFloatv)(GLenum pname, GLfloat * params); typedef void (CODEGEN_FUNCPTR * Proc_glGetIntegerv)(GLenum pname, GLint * params); typedef const GLubyte * (CODEGEN_FUNCPTR * Proc_glGetString)(GLenum name); typedef void (CODEGEN_FUNCPTR * Proc_glGetTexImage)(GLenum target, GLint level, GLenum format, GLenum type, GLvoid * pixels); typedef void (CODEGEN_FUNCPTR * Proc_glGetTexLevelParameterfv)(GLenum target, GLint level, GLenum pname, GLfloat * params); typedef void (CODEGEN_FUNCPTR * Proc_glGetTexLevelParameteriv)(GLenum target, GLint level, GLenum pname, GLint * params); typedef void (CODEGEN_FUNCPTR * Proc_glGetTexParameterfv)(GLenum target, GLenum pname, GLfloat * params); typedef void (CODEGEN_FUNCPTR * Proc_glGetTexParameteriv)(GLenum target, GLenum pname, GLint * params); typedef void (CODEGEN_FUNCPTR * Proc_glHint)(GLenum target, GLenum mode); typedef GLboolean (CODEGEN_FUNCPTR * Proc_glIsEnabled)(GLenum cap); typedef void (CODEGEN_FUNCPTR * Proc_glLineWidth)(GLfloat width); typedef void (CODEGEN_FUNCPTR * Proc_glLogicOp)(GLenum opcode); typedef void (CODEGEN_FUNCPTR * Proc_glPixelStoref)(GLenum pname, GLfloat param); typedef void (CODEGEN_FUNCPTR * Proc_glPixelStorei)(GLenum pname, GLint param); typedef void (CODEGEN_FUNCPTR * Proc_glPointSize)(GLfloat size); typedef void (CODEGEN_FUNCPTR * Proc_glPolygonMode)(GLenum face, GLenum mode); typedef void (CODEGEN_FUNCPTR * Proc_glReadBuffer)(GLenum mode); typedef void (CODEGEN_FUNCPTR * Proc_glReadPixels)(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLvoid * pixels); typedef void (CODEGEN_FUNCPTR * Proc_glScissor)(GLint x, GLint y, GLsizei width, GLsizei height); typedef void (CODEGEN_FUNCPTR * Proc_glStencilFunc)(GLenum func, GLint ref, GLuint mask); typedef void (CODEGEN_FUNCPTR * Proc_glStencilMask)(GLuint mask); typedef void (CODEGEN_FUNCPTR * Proc_glStencilOp)(GLenum fail, GLenum zfail, GLenum zpass); typedef void (CODEGEN_FUNCPTR * Proc_glTexImage1D)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const GLvoid * pixels); typedef void (CODEGEN_FUNCPTR * Proc_glTexImage2D)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid * pixels); typedef void (CODEGEN_FUNCPTR * Proc_glTexParameterf)(GLenum target, GLenum pname, GLfloat param); typedef void (CODEGEN_FUNCPTR * Proc_glTexParameterfv)(GLenum target, GLenum pname, const GLfloat * params); typedef void (CODEGEN_FUNCPTR * Proc_glTexParameteri)(GLenum target, GLenum pname, GLint param); typedef void (CODEGEN_FUNCPTR * Proc_glTexParameteriv)(GLenum target, GLenum pname, const GLint * params); typedef void (CODEGEN_FUNCPTR * Proc_glViewport)(GLint x, GLint y, GLsizei width, GLsizei height); } extern _detail::Proc_glBlendFunc BlendFunc; extern _detail::Proc_glClear Clear; extern _detail::Proc_glClearColor ClearColor; extern _detail::Proc_glClearDepth ClearDepth; extern _detail::Proc_glClearStencil ClearStencil; extern _detail::Proc_glColorMask ColorMask; extern _detail::Proc_glCullFace CullFace; extern _detail::Proc_glDepthFunc DepthFunc; extern _detail::Proc_glDepthMask DepthMask; extern _detail::Proc_glDepthRange DepthRange; extern _detail::Proc_glDisable Disable; extern _detail::Proc_glDrawBuffer DrawBuffer; extern _detail::Proc_glEnable Enable; extern _detail::Proc_glFinish Finish; extern _detail::Proc_glFlush Flush; extern _detail::Proc_glFrontFace FrontFace; extern _detail::Proc_glGetBooleanv GetBooleanv; extern _detail::Proc_glGetDoublev GetDoublev; extern _detail::Proc_glGetError GetError; extern _detail::Proc_glGetFloatv GetFloatv; extern _detail::Proc_glGetIntegerv GetIntegerv; extern _detail::Proc_glGetString GetString; extern _detail::Proc_glGetTexImage GetTexImage; extern _detail::Proc_glGetTexLevelParameterfv GetTexLevelParameterfv; extern _detail::Proc_glGetTexLevelParameteriv GetTexLevelParameteriv; extern _detail::Proc_glGetTexParameterfv GetTexParameterfv; extern _detail::Proc_glGetTexParameteriv GetTexParameteriv; extern _detail::Proc_glHint Hint; extern _detail::Proc_glIsEnabled IsEnabled; extern _detail::Proc_glLineWidth LineWidth; extern _detail::Proc_glLogicOp LogicOp; extern _detail::Proc_glPixelStoref PixelStoref; extern _detail::Proc_glPixelStorei PixelStorei; extern _detail::Proc_glPointSize PointSize; extern _detail::Proc_glPolygonMode PolygonMode; extern _detail::Proc_glReadBuffer ReadBuffer; extern _detail::Proc_glReadPixels ReadPixels; extern _detail::Proc_glScissor Scissor; extern _detail::Proc_glStencilFunc StencilFunc; extern _detail::Proc_glStencilMask StencilMask; extern _detail::Proc_glStencilOp StencilOp; extern _detail::Proc_glTexImage1D TexImage1D; extern _detail::Proc_glTexImage2D TexImage2D; extern _detail::Proc_glTexParameterf TexParameterf; extern _detail::Proc_glTexParameterfv TexParameterfv; extern _detail::Proc_glTexParameteri TexParameteri; extern _detail::Proc_glTexParameteriv TexParameteriv; extern _detail::Proc_glViewport Viewport; } #endif /*OPENGL_GEN_CORE_1_0_HPP*/
2,624
32,544
<gh_stars>1000+ package com.baeldung.serenity.spring.steps; import io.restassured.module.mockmvc.response.MockMvcResponse; import net.thucydides.core.annotations.Step; import java.io.UnsupportedEncodingException; import static io.restassured.module.mockmvc.RestAssuredMockMvc.given; import static org.hamcrest.core.IsEqual.equalTo; /** * @author aiet */ public class AdderRestSteps { private MockMvcResponse mockMvcResponse; private int currentNum; @Step("get the current number") public void givenCurrentNumber() throws UnsupportedEncodingException { currentNum = Integer.valueOf(given().when().get("/adder/current").mvcResult().getResponse().getContentAsString()); } @Step("adding {0}") public void whenAddNumber(int num) { mockMvcResponse = given().queryParam("num", num).when().post("/adder"); currentNum += num; } @Step("got the sum") public void thenSummedUp() { mockMvcResponse.then().statusCode(200).body(equalTo(currentNum + "")); } }
375
429
from django.conf import settings from django.contrib.staticfiles.finders import get_finders from django.core.files.storage import FileSystemStorage, get_storage_class from django.utils.functional import LazyObject class SassFileStorage(LazyObject): def _setup(self): storage_path = getattr(settings, 'SASS_PROCESSOR_STORAGE', settings.STATICFILES_STORAGE) storage_options = getattr(settings, 'SASS_PROCESSOR_STORAGE_OPTIONS', {}) storage_class = get_storage_class(storage_path) if storage_path == settings.STATICFILES_STORAGE and issubclass(storage_class, FileSystemStorage): storage_options['location'] = getattr(settings, 'SASS_PROCESSOR_ROOT', settings.STATIC_ROOT) storage_options['base_url'] = settings.STATIC_URL self._wrapped = storage_class(**storage_options) def find_file(path): for finder in get_finders(): result = finder.find(path) if result: return result
371
416
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <time.h> #include <sys/time.h> #include <sys/ioctl.h> #include <sys/stat.h> #include <sys/types.h> #include "mp3_buf.h" #define SOUND_DEVICE "/dev/sb16" static int sound_fd = 0; static unsigned short MP3_Data[OUTPUT_BUFFER_SIZE]; unsigned short *get_framebuf() { return MP3_Data; } void open_sound() { sound_fd = open(SOUND_DEVICE, 0); } void close_sound() { if (sound_fd >= 0) close(sound_fd); } void submit_framebuf() { if (sound_fd >= 0) write(sound_fd, MP3_Data, OUTPUT_BUFFER_SIZE * 2); }
280
3,783
package problems.medium; import problems.utils.TreeNode; import java.util.Stack; /** * Created by sherxon on 1/4/17. */ public class BinarySearchTreeIterator { Stack<TreeNode> stack; public BinarySearchTreeIterator(TreeNode root) { stack = new Stack<>(); add(root); } /** * @return whether we have a next smallest number */ public boolean hasNext() { return stack.size() > 1; } /** * @return the next smallest number */ public int next() { TreeNode pop = stack.pop(); add(pop.right); return pop.val; } void add(TreeNode x) { while (x != null) { stack.add(x); x = x.left; } } }
326
9,717
# -*- coding: utf-8 -*- import setuptools import tokenize __file__='setup.py'; exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\\r\\n', '\\n'), __file__, 'exec'))
77
418
<filename>tests/test_files/returncode.py _, _, return_code = ~"false" assert return_code == 1 exit_code = 123 *_, return_code = ~f"exit {exit_code}" assert return_code == exit_code [_, _, return_code] = ~'echo hi' assert return_code == 0
90
964
[ { "queryName": "Global Schemes Uses HTTP", "severity": "MEDIUM", "line": 8, "filename": "positive1.json" }, { "queryName": "Global Schemes Uses HTTP", "severity": "MEDIUM", "line": 6, "filename": "positive2.yaml" } ]
117
942
<filename>src/tcriteriamongoconverter.h #pragma once #include "tsystemglobal.h" #include <QMap> #include <QMetaObject> #include <QMetaProperty> #include <QVariant> #include <TCriteria> #include <TCriteriaConverter> #include <TGlobal> template <class T> class TCriteriaMongoConverter { public: TCriteriaMongoConverter(const TCriteria &cri) : criteria(cri) { } QVariantMap toVariantMap() const; static QString propertyName(int property); protected: static QVariantMap criteriaToVariantMap(const QVariant &cri); static QVariantMap join(const QVariantMap &v1, TCriteria::LogicalOperator op, const QVariantMap &v2); private: TCriteria criteria; }; template <class T> inline QVariantMap TCriteriaMongoConverter<T>::toVariantMap() const { return criteriaToVariantMap(QVariant::fromValue(criteria)); } template <class T> inline QVariantMap TCriteriaMongoConverter<T>::criteriaToVariantMap(const QVariant &var) { QVariantMap ret; if (var.isNull()) { return ret; } if (var.canConvert<TCriteria>()) { TCriteria cri = var.value<TCriteria>(); if (!cri.isEmpty()) { ret = join(criteriaToVariantMap(cri.first()), cri.logicalOperator(), criteriaToVariantMap(cri.second())); } } else if (var.canConvert<TCriteriaData>()) { TCriteriaData cri = var.value<TCriteriaData>(); QString name = propertyName(cri.property); if (cri.isEmpty() || name.isEmpty()) { return ret; } switch (cri.op1) { case TMongo::Equal: ret.insert(name, cri.val1); break; case TMongo::NotEqual: { QVariantMap ne; ne.insert("$ne", cri.val1); ret.insert(name, QVariant(ne)); break; } case TMongo::LessThan: { QVariantMap lt; lt.insert("$lt", cri.val1); ret.insert(name, QVariant(lt)); break; } case TMongo::GreaterThan: { QVariantMap gt; gt.insert("$gt", cri.val1); ret.insert(name, QVariant(gt)); break; } case TMongo::LessEqual: { QVariantMap le; le.insert("$lte", cri.val1); ret.insert(name, QVariant(le)); break; } case TMongo::GreaterEqual: { QVariantMap ge; ge.insert("$gte", cri.val1); ret.insert(name, QVariant(ge)); break; } case TMongo::Exists: { QVariantMap ex; ex.insert("$exists", true); ret.insert(name, ex); break; } case TMongo::NotExists: { QVariantMap nex; nex.insert("$exists", false); ret.insert(name, nex); break; } case TMongo::All: { QVariantMap all; all.insert("$all", cri.val1); ret.insert(name, all); break; } case TMongo::In: { QVariantMap in; in.insert("$in", cri.val1); ret.insert(name, in); break; } case TMongo::NotIn: { QVariantMap nin; nin.insert("$nin", cri.val1); ret.insert(name, nin); break; } case TMongo::Mod: { QVariantMap mod; mod.insert("$mod", cri.val1); ret.insert(name, mod); break; } case TMongo::Size: { QVariantMap sz; sz.insert("$size", cri.val1); ret.insert(name, sz); break; } case TMongo::Type: { QVariantMap ty; ty.insert("$type", cri.val1); ret.insert(name, ty); break; } default: tWarn("error parameter: %d", cri.op1); break; } } else { tSystemError("Logic error [%s:%d]", __FILE__, __LINE__); } return ret; } template <class T> inline QString TCriteriaMongoConverter<T>::propertyName(int property) { const QMetaObject *metaObject = T().metaObject(); return (metaObject) ? metaObject->property(metaObject->propertyOffset() + property).name() : QString(); } template <class T> inline QVariantMap TCriteriaMongoConverter<T>::join(const QVariantMap &v1, TCriteria::LogicalOperator op, const QVariantMap &v2) { if (op == TCriteria::None || v2.isEmpty()) { return v1; } QVariantMap ret; if (op == TCriteria::And) { #if QT_VERSION >= 0x050f00 // 5.15.0 ret = v2; ret.insert(v1); #else ret = v1; ret.unite(v2); #endif } else if (op == TCriteria::Or) { QVariantList lst; lst << v1 << v2; ret.insert("$or", lst); } else { tSystemError("Logic error: [%s:%d]", __FILE__, __LINE__); } return ret; }
2,561
808
<gh_stars>100-1000 /* * Adapated from https://gist.github.com/cmaglie/5883185 */ #ifndef _STRING_STREAM_H_INCLUDED_ #define _STRING_STREAM_H_INCLUDED_ #include <Stream.h> class StringStream : public Stream { public: StringStream(String &s) : string(s), position(0) { } // Stream methods virtual int available() { return string.length() - position; } virtual int read() { return position < string.length() ? string[position++] : -1; } virtual int peek() { return position < string.length() ? string[position] : -1; } virtual void flush() { }; // Print methods virtual size_t write(uint8_t c) { string += (char)c; return 1; }; private: String &string; unsigned int length; unsigned int position; }; #endif // _STRING_STREAM_H_INCLUDED_
284
2,453
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 30 2020 21:18:12). // // Copyright (C) 1997-2019 <NAME>. // #import <IDEKit/NSObject-Protocol.h> @class NSArray, NSAttributedString; @protocol IDEArchiveStatusLogItemChild <NSObject> @property(readonly) NSArray *children; @property(readonly) NSAttributedString *attributedString; @property(readonly) BOOL isNotice; @property(readonly) BOOL isWarning; @property(readonly) BOOL isError; @end
162
16,989
// Copyright 2018 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.skyframe; import com.google.devtools.build.lib.events.Event; import com.google.devtools.build.lib.events.ExtendedEventHandler; /** * Suppresses {@link #post} when the provided {@link ExtendedEventHandler.Postable} is a {@link * ProgressLike}, but otherwise delegates calls to its wrapped {@link ExtendedEventHandler}. */ class ProgressSuppressingEventHandler implements ExtendedEventHandler { private final ExtendedEventHandler delegate; ProgressSuppressingEventHandler(ExtendedEventHandler listener) { this.delegate = listener; } @Override public void post(Postable obj) { if (obj instanceof ProgressLike) { return; } delegate.post(obj); } @Override public void handle(Event event) { delegate.handle(event); } }
394
856
// // Copyright © 2021 Arm Ltd and Contributors. All rights reserved. // SPDX-License-Identifier: MIT // #include <reference/workloads/Decoders.hpp> #include <fmt/format.h> #include <doctest/doctest.h> #include <chrono> template<typename T> void CompareVector(std::vector<T> vec1, std::vector<T> vec2) { CHECK(vec1.size() == vec2.size()); bool mismatch = false; for (uint32_t i = 0; i < vec1.size(); ++i) { if (vec1[i] != vec2[i]) { MESSAGE(fmt::format("Vector value mismatch: index={} {} != {}", i, vec1[i], vec2[i])); mismatch = true; } } if (mismatch) { FAIL("Error in CompareVector. Vectors don't match."); } } using namespace armnn; // Basically a per axis decoder but without any decoding/quantization class MockPerAxisIterator : public PerAxisIterator<const int8_t, Decoder<int8_t>> { public: MockPerAxisIterator(const int8_t* data, const armnn::TensorShape& tensorShape, const unsigned int axis) : PerAxisIterator(data, tensorShape, axis), m_NumElements(tensorShape.GetNumElements()) {} int8_t Get() const override { return *m_Iterator; } virtual std::vector<float> DecodeTensor(const TensorShape &tensorShape, bool isDepthwise = false) override { IgnoreUnused(tensorShape, isDepthwise); return std::vector<float>{}; }; // Iterates over data using operator[] and returns vector std::vector<int8_t> Loop() { std::vector<int8_t> vec; for (uint32_t i = 0; i < m_NumElements; ++i) { this->operator[](i); vec.emplace_back(Get()); } return vec; } unsigned int GetAxisIndex() { return m_AxisIndex; } unsigned int m_NumElements; }; TEST_SUITE("RefPerAxisIterator") { // Test Loop (Equivalent to DecodeTensor) and Axis = 0 TEST_CASE("PerAxisIteratorTest1") { std::vector<int8_t> input = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; TensorInfo tensorInfo ({3,1,2,2},DataType::QSymmS8); // test axis=0 std::vector<int8_t> expOutput = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; auto iterator = MockPerAxisIterator(input.data(), tensorInfo.GetShape(), 0); std::vector<int8_t> output = iterator.Loop(); CompareVector(output, expOutput); // Set iterator to index and check if the axis index is correct iterator[5]; CHECK(iterator.GetAxisIndex() == 1u); iterator[1]; CHECK(iterator.GetAxisIndex() == 0u); iterator[10]; CHECK(iterator.GetAxisIndex() == 2u); } // Test Axis = 1 TEST_CASE("PerAxisIteratorTest2") { std::vector<int8_t> input = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; TensorInfo tensorInfo ({3,1,2,2},DataType::QSymmS8); // test axis=1 std::vector<int8_t> expOutput = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; auto iterator = MockPerAxisIterator(input.data(), tensorInfo.GetShape(), 1); std::vector<int8_t> output = iterator.Loop(); CompareVector(output, expOutput); // Set iterator to index and check if the axis index is correct iterator[5]; CHECK(iterator.GetAxisIndex() == 0u); iterator[1]; CHECK(iterator.GetAxisIndex() == 0u); iterator[10]; CHECK(iterator.GetAxisIndex() == 0u); } // Test Axis = 2 TEST_CASE("PerAxisIteratorTest3") { std::vector<int8_t> input = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; TensorInfo tensorInfo ({3,1,2,2},DataType::QSymmS8); // test axis=2 std::vector<int8_t> expOutput = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; auto iterator = MockPerAxisIterator(input.data(), tensorInfo.GetShape(), 2); std::vector<int8_t> output = iterator.Loop(); CompareVector(output, expOutput); // Set iterator to index and check if the axis index is correct iterator[5]; CHECK(iterator.GetAxisIndex() == 0u); iterator[1]; CHECK(iterator.GetAxisIndex() == 0u); iterator[10]; CHECK(iterator.GetAxisIndex() == 1u); } // Test Axis = 3 TEST_CASE("PerAxisIteratorTest4") { std::vector<int8_t> input = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; TensorInfo tensorInfo ({3,1,2,2},DataType::QSymmS8); // test axis=3 std::vector<int8_t> expOutput = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; auto iterator = MockPerAxisIterator(input.data(), tensorInfo.GetShape(), 3); std::vector<int8_t> output = iterator.Loop(); CompareVector(output, expOutput); // Set iterator to index and check if the axis index is correct iterator[5]; CHECK(iterator.GetAxisIndex() == 1u); iterator[1]; CHECK(iterator.GetAxisIndex() == 1u); iterator[10]; CHECK(iterator.GetAxisIndex() == 0u); } // Test Axis = 1. Different tensor shape TEST_CASE("PerAxisIteratorTest5") { using namespace armnn; std::vector<int8_t> input = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; std::vector<int8_t> expOutput = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; TensorInfo tensorInfo ({2,2,2,2},DataType::QSymmS8); auto iterator = MockPerAxisIterator(input.data(), tensorInfo.GetShape(), 1); std::vector<int8_t> output = iterator.Loop(); CompareVector(output, expOutput); // Set iterator to index and check if the axis index is correct iterator[5]; CHECK(iterator.GetAxisIndex() == 1u); iterator[1]; CHECK(iterator.GetAxisIndex() == 0u); iterator[10]; CHECK(iterator.GetAxisIndex() == 0u); } // Test the increment and decrement operator TEST_CASE("PerAxisIteratorTest7") { using namespace armnn; std::vector<int8_t> input = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }; std::vector<int8_t> expOutput = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }; TensorInfo tensorInfo ({3,1,2,2},DataType::QSymmS8); auto iterator = MockPerAxisIterator(input.data(), tensorInfo.GetShape(), 2); iterator += 3; CHECK(iterator.Get() == expOutput[3]); CHECK(iterator.GetAxisIndex() == 1u); iterator += 3; CHECK(iterator.Get() == expOutput[6]); CHECK(iterator.GetAxisIndex() == 1u); iterator -= 2; CHECK(iterator.Get() == expOutput[4]); CHECK(iterator.GetAxisIndex() == 0u); iterator -= 1; CHECK(iterator.Get() == expOutput[3]); CHECK(iterator.GetAxisIndex() == 1u); } }
2,964
1,044
import logging import os import sys import time from typing import Any import multiprocessing import functools nesting_level = 0 is_start = None NCPU = multiprocessing.cpu_count() def log(entry: Any): global nesting_level space = "-" * (4 * nesting_level) logger.info("{}{}".format(space, entry)) def get_logger(verbosity_level, use_error_log=False, log_path=None): """Set logging format to something like: 2019-04-25 12:52:51,924 INFO score.py: <message> """ logger = logging.getLogger(__file__) logging_level = getattr(logging, verbosity_level) logger.setLevel(logging_level) if log_path is None: log_dir = os.path.join("..", "log") if not os.path.exists(log_dir): os.makedirs(log_dir) log_path = os.path.join(log_dir, "log.txt") else: log_path = os.path.join(log_path, "log.txt") formatter = logging.Formatter( fmt='%(asctime)s %(levelname)s %(filename)s: %(funcName)s: %(lineno)d: %(message)s') stdout_handler = logging.StreamHandler(sys.stdout) stdout_handler.setLevel(logging_level) stdout_handler.setFormatter(formatter) logger.addHandler(stdout_handler) fh = logging.FileHandler(log_path) fh.setLevel(logging_level) fh.setFormatter(formatter) logger.addHandler(fh) if use_error_log: stderr_handler = logging.StreamHandler(sys.stderr) stderr_handler.setLevel(logging.WARNING) stderr_handler.setFormatter(formatter) logger.addHandler(stderr_handler) logger.propagate = False return logger logger = get_logger('INFO') debug = logger.debug info = logger.info warning = logger.warning error = logger.error def timeit(method, start_log=None): @functools.wraps(method) def timed(*args, **kw): global is_start global nesting_level if not is_start: print() is_start = True log("Start [{}]:".format(method.__name__)+ (start_log if start_log else "")) nesting_level += 1 start_time = time.time() result = method(*args, **kw) end_time = time.time() nesting_level -= 1 log("End [{}]. Time elapsed: {} sec.".format(method.__name__, end_time - start_time)) is_start = False return result return timed
985
3,083
// Copyright 2011-2016 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.security.zynamics.zylib.gui.zygraph.proximity; import com.google.security.zynamics.zylib.gui.zygraph.edges.IViewEdge; import com.google.security.zynamics.zylib.gui.zygraph.helpers.IEdgeCallback; import com.google.security.zynamics.zylib.gui.zygraph.helpers.INodeCallback; import com.google.security.zynamics.zylib.gui.zygraph.nodes.IGroupNode; import com.google.security.zynamics.zylib.gui.zygraph.nodes.IViewNode; import com.google.security.zynamics.zylib.types.common.IterationMode; import com.google.security.zynamics.zylib.yfileswrap.gui.zygraph.AbstractZyGraph; import com.google.security.zynamics.zylib.yfileswrap.gui.zygraph.edges.ZyGraphEdge; import com.google.security.zynamics.zylib.yfileswrap.gui.zygraph.nodes.ZyGraphNode; import java.util.HashSet; /** * Class to form a single edge out of a number of edges. */ public class MultiEdgeHider { public static < NodeType extends ZyGraphNode<? extends IViewNode<?>>> void hideMultipleEdgesInternal( final AbstractZyGraph<NodeType, ?> graph) { graph.iterate(new INodeCallback<NodeType>() { @Override public IterationMode next(final NodeType node) { hideMultipleEdgesInternal(node); return IterationMode.CONTINUE; } }); } public static < NodeType extends ZyGraphNode<? extends IViewNode<?>>> void hideMultipleEdgesInternal( final NodeType node) { if (!node.isVisible() || (node.getRawNode() instanceof IGroupNode<?, ?>)) { // If the node is not visible, then none of the edges are visible. return; } final HashSet<Object> targets = new HashSet<Object>(); for (final IViewEdge<?> edge : ((IViewNode<?>) node.getRawNode()).getOutgoingEdges()) { final Object target = edge.getTarget(); if (targets.contains(target)) { edge.setVisible(false); } else { targets.add(target); } } final HashSet<Object> sources = new HashSet<Object>(); for (final IViewEdge<?> edge : ((IViewNode<?>) node.getRawNode()).getIncomingEdges()) { if (sources.contains(edge.getSource())) { edge.setVisible(false); } else { sources.add(edge.getSource()); } } } public static <NodeType extends ZyGraphNode<? extends IViewNode<?>>, EdgeType extends ZyGraphEdge<NodeType, EdgeType, ? extends IViewEdge<?>>> void unhideMultipleEdgesInternal( final AbstractZyGraph<NodeType, EdgeType> graph) { graph.iterateEdges(new IEdgeCallback<EdgeType>() { @Override public IterationMode nextEdge(final EdgeType edge) { edge.getRawEdge().setVisible(edge.getSource().isVisible() && edge.getTarget().isVisible()); return IterationMode.CONTINUE; } }); } }
1,191
381
<reponame>nanjekyejoannah/pypy<filename>rpython/rlib/test/test_rposix_environ.py from rpython.translator.c.test.test_genc import compile import os def test_environ_items(): def foo(x): if x: return len(os.environ.items()) else: return 0 f = compile(foo, [int], backendopt=False) assert f(1) > 0 def test_unset_error(): import sys def foo(x): if x: os.environ['TEST'] = 'STRING' assert os.environ['TEST'] == 'STRING' del os.environ['TEST'] try: del os.environ['key='] except (KeyError, OSError): return 1 return 2 else: return 0 f = compile(foo, [int], backendopt=False) if sys.platform.startswith('win'): # Do not open error dialog box import ctypes SEM_NOGPFAULTERRORBOX = 0x0002 # From MSDN old_err_mode = ctypes.windll.kernel32.GetErrorMode() new_err_mode = old_err_mode | SEM_NOGPFAULTERRORBOX ctypes.windll.kernel32.SetErrorMode(new_err_mode) assert f(1) == 1 if sys.platform.startswith('win'): ctypes.windll.kernel32.SetErrorMode(old_err_mode)
612
603
#pragma once #include "owl/owl.h" #include "owl/common/math/vec.h" #include <vector> #include <map> #include <stdexcept> #include <string> #include <iostream> #include <memory> #include "hdri.h" #include "mesh.h" namespace cdf { using namespace owl; using namespace owl::common; enum PixelFormat { PF_RGB32F, PF_RGBA32F }; template <typename InIt, typename OutIt> void scan(InIt first, InIt last, OutIt dest, unsigned stride = 1) { for (ptrdiff_t i = 0; i != last-first; i += stride) { *(dest + i) = i == 0 ? *first : *(dest + i - stride) + *(first + i); } } template <typename It> void normalize(It first, It last) { // Assumes that [first,last) is sorted! auto bck = *(last-1); if (bck != 0) { for (It it = first; it != last; ++it) { *it /= bck; } } } struct Point { // The column this point belongs to float x; // The row this point belongs to float y; // Data value (not used (yet?)) float f; // 1st-order forward partial derivative in x float dfdx; // 2nd-order forward partial derivative in x float d2fdx; }; struct CDF { CDF(const std::string &hdrFileName) { std::cout<<"cdf.h - constructing CDF..."<<std::endl; hdri.load(hdrFileName); // Build up luminance image std::vector<float> luminance(hdri.width * hdri.height); struct vec3 { float x, y, z; }; struct vec4 { float x, y, z, w; }; for (int y = 0; y < hdri.height; ++y) { for (int x = 0; x < hdri.width; ++x) { // That's not actually luminance, but might as well be.. if (hdri.numComponents == 3) { vec3 rgb = *((vec3*)hdri.pixel.data() + y * hdri.width + x); luminance[y * hdri.width + x] = max(rgb.x,max(rgb.y,rgb.z)); } else if (hdri.numComponents == 4) { vec4 rgba = *((vec4*)hdri.pixel.data() + y * hdri.width + x); luminance[y * hdri.width + x] = max(rgba.x,max(rgba.y,rgba.z)); } else assert(0); } } // Build up CDF cumulatedRows.resize(hdri.width * hdri.height, 0); cumulatedLastCol.resize(hdri.height); std::vector<float> lastCol(hdri.height); for (int y = 0; y < hdri.height; ++y) { // Scan each row size_t off = y * hdri.width; scan(luminance.data() + off, luminance.data() + off + hdri.width, cumulatedRows.data() + off); // Assemble the last column by filling with the last item of each row lastCol[y] = *(cumulatedRows.data() + off + hdri.width - 1); // Normalize the row normalize(cumulatedRows.data() + off, cumulatedRows.data() + off + hdri.width); } // Scan and normalize the last column scan(lastCol.begin(), lastCol.end(), cumulatedLastCol.begin()); normalize(cumulatedLastCol.begin(), cumulatedLastCol.end()); } Mesh CDF::asTriangleMesh(Mesh::Representation repr, float simplificationRate, bool dumpAsObj) { std::cout<<"cdf.h - converting to cdf geometry" << std::endl; unsigned maxControlPoints = hdri.height * hdri.width * (1.f - simplificationRate); Mesh res; std::vector<Point> controlPoints; // Sample the row CDFs, collecting first and second derivatives std::vector<Point> samples(hdri.width * hdri.height); for (int y=0; y<hdri.height; ++y) { float rowHeight = (y == 0) ? cumulatedLastCol[0] : cumulatedLastCol[y] - cumulatedLastCol[y-1]; const float *row = cumulatedRows.data() + y*hdri.width; float prevSlope = 0.f;//row[1]-row[0]; for (int x = 0; x < hdri.width - 1; ++x) { size_t index = y * hdri.width + x; float slope = row[x+1] - row[x]; samples[index].x = x + 1.f; samples[index].y = y; samples[index].f = row[x]; samples[index].dfdx = slope*rowHeight; samples[index].d2fdx = fabsf(slope-prevSlope)*rowHeight; prevSlope = slope; } } // Sort the samples by absolute differences in slope, in descending order std::sort(samples.begin(), samples.end(), [] (Point a, Point b) { return a.d2fdx > b.d2fdx; }); // Accept the N most influential samples for (int i = 0; i < min((size_t)maxControlPoints,samples.size()); ++i) { if (samples[i].dfdx < FLT_MIN || samples[i].d2fdx < FLT_MIN) continue; controlPoints.push_back(samples[i]); } // Insert starts and stops for each row, guaranteeing each row is represented. for (int y=0; y<hdri.height; ++y) { controlPoints.push_back({0, float(y), 0.f, 0, 0}); controlPoints.push_back({float(hdri.width), float(y), 1.f, 0, 0}); } // Reorder the samples into a sparse, row major order image std::sort(controlPoints.begin(),controlPoints.end(), [](Point a, Point b) { return a.x < b.x; }); std::stable_sort(controlPoints.begin(),controlPoints.end(), [](Point a, Point b) { return a.y < b.y; }); // Count the number of control points used by each row std::vector<int> counts(hdri.height + 2, 0); for (unsigned i=0; i<controlPoints.size(); ++i) counts[controlPoints[i].y+1]++; // Take the prefix sum of these counts to compute addresses into each row for (unsigned i=1; i<counts.size(); ++i) counts[i] = counts[i-1]+counts[i]; float prevRowCdf = 0.f; for (int y = 0; y < hdri.height; ++y) { // Merge any "empty" neighboring rows int rowCount = 1; int rowStart = y; while (y < (hdri.height - 1) && ((counts[y+1] - counts[y+0]) == 2) && ((counts[y+2] - counts[y+1]) == 2)) { rowCount++; y++; } float currRowCdf = cumulatedLastCol[y]; Geometry geom; geom.tag = Geometry::CDF; geom.geomPdf = (currRowCdf - prevRowCdf) / float(rowCount); geom.rowStart = rowStart; geom.rowCount = rowCount; // Generate triangle geometry to represent the CDF int o = 0; geom.vertex.push_back({prevRowCdf, 0.f, 0.f}); geom.vertex.push_back({currRowCdf, 0.f, 0.f}); for (unsigned i = counts[y] + 1; i != counts[y+1]; ++i) { // note, geometry dimensions span from 0-1 to improve traversal performance geom.vertex.push_back({prevRowCdf, controlPoints[i].f, float(controlPoints[i].x) / float(hdri.width)}); geom.vertex.push_back({currRowCdf, controlPoints[i].f, float(controlPoints[i].x) / float(hdri.width)}); geom.index.push_back({o + 0, o + 1, o + 3}); geom.index.push_back({o + 3, o + 2, o + 0}); geom.triPdfs.push_back((controlPoints[i].f - controlPoints[i-1].f) / float(controlPoints[i].x - controlPoints[i-1].x)); geom.triPdfs.push_back((controlPoints[i].f - controlPoints[i-1].f) / float(controlPoints[i].x - controlPoints[i-1].x)); o += 2; } // Add the generated geometry to our list res.geoms.push_back(geom); prevRowCdf = currRowCdf; } return res; } // Containing *normalized* prefix sums of rows std::vector<float> cumulatedRows; // The last column, cumulated and normalized std::vector<float> cumulatedLastCol; // The original environment map HDRI hdri; }; }
3,470
997
// ================================================================ // Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved // ================================================================ #ifndef PDQIO_H #define PDQIO_H // ================================================================ // CImg-dependent interface for reading files to matrices of RGB triples. // ================================================================ #include <pdq/cpp/common/pdqhashtypes.h> #define cimg_display 0 #include "CImg.h" typedef unsigned char uint8_t; namespace facebook { namespace pdq { namespace hashing { // Returns matrix as numRows x numCols in row-major order. // The caller must free the return value. // xxx check for this. float* loadFloatLumaFromCImg( cimg_library::CImg<uint8_t>& img, int& numRows, int& numCols ); void showDecoderInfo(); bool pdqHash256FromFile( const char* filename, Hash256& hash, int& quality, int& imageHeightTimesWidth, float& readSeconds, float& hashSeconds ); // Naming conventions: // * Rotate 90: counterclockwise 90 degrees // * Rotate 180: 180 degrees // * Rotate 270: counterclockwise 270 degrees (i.e. clockwise 90 degrees) // * FlipX: Left is left and right is right but top and bottom change places // * FlipY: Top is top and bottom is bottom but left and right change places // (mirror image) // * FlipPlus1: Upper left and lower right stay put; lower left and upper right // exchange places // * FlipMinus: Upper right and lower left stay put; upper left and lower right // exchange places // // Pointer semantics: // * Pass nullptr for any variants you do not want to be computed. // * Pass pointer to hashes to be stuffed with variants you do want computed. bool pdqDihedralHash256esFromFile( const char* filename, Hash256* hashptrOriginal, Hash256* hashptrRotate90, Hash256* hashptrRotate180, Hash256* hashptrRotate270, Hash256* hashptrFlipX, Hash256* hashptrFlipY, Hash256* hashptrFlipPlus1, Hash256* hashptrFlipMinus1, int& quality, int& imageHeightTimesWidth, float& readSeconds, float& hashSeconds ); // Takes matrix as numRows x numCols in row-major order void floatMatrixToCImg(float* matrix, int numRows, int numCols, const char filename[]); } // namespace hashing } // namespace pdq } // namespace facebook #endif // PDQIO_H
699
687
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved MODEL_ZOO_STORAGE_PREFIX = "https://mobile-cv.s3-us-west-2.amazonaws.com/d2go/models/" def get_launch_environment(): return "local"
87
454
{ "latent_dim":56, "max_decode_steps":278, "eps_std":0.01, "encoder_type":"cnn", "rnn_type": "gru" }
53
488
<reponame>ouankou/rose #include <stdio.h> #if defined(_OPENMP) #include <omp.h> #endif /* _OPENMP */ static double a[1000]; static void init(void) { int i=0; i=i+5; #pragma omp for for (i=0;i<1000;i++) { a[i]=(double)i/2.0; } } int main(void){ #pragma omp parallel { init(); } return 0; }
158
533
<filename>saber/funcs/impl/amd/saber_slice.cpp<gh_stars>100-1000 /* Copyright (c) 2019 Anakin Authors, 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. */ #include "include/saber_slice.h" namespace anakin { namespace saber { template <DataType OpDtype> SaberStatus SaberSlice<AMD, OpDtype>::init( const std::vector<Tensor<AMD>*>& inputs, std::vector<Tensor<AMD>*>& outputs, SliceParam<AMD>& param, Context<AMD>& ctx) { this->_ctx = &ctx; return create(inputs, outputs, param, ctx); } template <DataType OpDtype> SaberStatus SaberSlice<AMD, OpDtype>::create( const std::vector<Tensor<AMD>*>& inputs, std::vector<Tensor<AMD>*>& outputs, SliceParam<AMD>& param, Context<AMD>& ctx) { int output_size = outputs.size(); _slice_num = inputs[0]->count_valid(0, param.axis); _slice_size = inputs[0]->count_valid(param.axis + 1, inputs[0]->dims()); const int count = outputs[0]->size(); int globalsize = inputs[0]->size(); KernelInfo kernelInfo; kernelInfo.kernel_file = "Slice.cl"; kernelInfo.kernel_name = "Slice_normal_512"; kernelInfo.wk_dim = 1; for (int i = 0; i < output_size; ++i) { OpDataType* out_data = (OpDataType*)outputs[i]->mutable_data(); const int out_slice_axis_size = outputs[i]->valid_shape()[param.axis]; const int out_slice_size = out_slice_axis_size * _slice_size; const int nthreads = out_slice_size * _slice_num; kernelInfo.l_wk = {AMD_NUM_THREADS}; if (_slice_size>3 && _slice_size%4 == 0) { kernelInfo.g_wk = {(nthreads/4 + kernelInfo.l_wk[0] - 1) / kernelInfo.l_wk[-1] * kernelInfo.l_wk[0]}; kernelInfo.kernel_name = "Slice_normal_512_f4"; } else { kernelInfo.g_wk = {(nthreads + kernelInfo.l_wk[0] - 1) / kernelInfo.l_wk[0] * kernelInfo.l_wk[0]}; kernelInfo.kernel_name = "Slice_normal_512"; } AMDKernelPtr kptr = CreateKernel(inputs[0]->device_id(), &kernelInfo); if (!kptr.get()->isInit()) { LOG(ERROR) << "Failed to load program"; return SaberInvalidValue; } _kernels_ptr.push_back(kptr); } LOG_IF_S(INFO, ENABLE_AMD_DEBUG_LOG) << "COMPLETE CREATE KERNEL"; return SaberSuccess; } template <DataType OpDtype> SaberStatus SaberSlice<AMD, OpDtype>::dispatch( const std::vector<Tensor<AMD>*>& inputs, std::vector<Tensor<AMD>*>& outputs, SliceParam<AMD>& param) { bool err; AMD_API::stream_t cm = this->_ctx->get_compute_stream(); //! inputs only has one tensor Shape shape_in = inputs[0]->valid_shape(); int output_size = outputs.size(); if (output_size == 1) { outputs[0]->share_from(*inputs[0]); return SaberSuccess; } int offset_slice_axis = 0; const int in_slice_axis_size = shape_in[param.axis]; const OpDataType* in_data = (const OpDataType*)inputs[0]->data(); amd_kernel_list list; for (int i = 0; i < output_size; ++i) { OpDataType* out_data = (OpDataType*)outputs[i]->mutable_data(); const int out_slice_axis_size = outputs[i]->valid_shape()[param.axis]; const int out_slice_size = out_slice_axis_size * _slice_size; int nthreads = out_slice_size * _slice_num; if (_kernels_ptr[i] == NULL || _kernels_ptr[i].get() == NULL) { LOG(ERROR) << "Kernel is not exist"; return SaberInvalidValue; } if (_slice_size > 3 &&_slice_size % 4 == 0) { nthreads= nthreads >> 2; } _kernels_ptr[i].get()->SetKernelArgs( (int)nthreads, (PtrDtype)in_data, (int)_slice_num, (int)_slice_size, (int)in_slice_axis_size, (int)out_slice_axis_size, (int)offset_slice_axis, (PtrDtype)out_data); list.push_back(_kernels_ptr[i]); offset_slice_axis += out_slice_axis_size; } err = LaunchKernel(cm, list); if (!err) { LOG(ERROR) << "Fialed to set execution."; return SaberInvalidValue; } LOG_IF_S(INFO, ENABLE_AMD_DEBUG_LOG) << "COMPLETE EXECUTION"; return SaberSuccess; } template class SaberSlice<AMD, AK_FLOAT>; DEFINE_OP_TEMPLATE(SaberSlice, SliceParam, AMD, AK_INT8); DEFINE_OP_TEMPLATE(SaberSlice, SliceParam, AMD, AK_HALF); } // namespace saber } // namespace anakin
2,197
9,953
from scrapy.downloadermiddlewares.httpproxy import HttpProxyMiddleware class HttpProxy(HttpProxyMiddleware): @staticmethod def proxy_shadowsocks(): proxy = "http://127.0.0.1:1080" return proxy
83
679
<filename>main/dtrans/source/win32/dnd/source.hxx /************************************************************** * * 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. * *************************************************************/ #ifndef _SOURCE_HXX_ #define _SOURCE_HXX_ #include <com/sun/star/datatransfer/dnd/XDragSource.hpp> #include <com/sun/star/datatransfer/dnd/XDragSourceContext.hpp> #include <com/sun/star/lang/XInitialization.hpp> #ifndef _OSL_MUTEX_H_ #include <osl/mutex.hxx> #endif #ifndef _CPPUHELPER_COMPBASE2_HXX_ #include <cppuhelper/compbase3.hxx> #endif #include <com/sun/star/lang/XServiceInfo.hpp> #include "../../inc/DtObjFactory.hxx" #include "globals.hxx" #include <oleidl.h> #include <systools/win32/comtools.hxx> using namespace ::com::sun::star::lang; using namespace ::com::sun::star::uno; using namespace cppu; using namespace osl; using namespace rtl; using namespace ::com::sun::star::datatransfer; using namespace ::com::sun::star::datatransfer::dnd; class SourceContext; // RIGHT MOUSE BUTTON drag and drop not supported currently. // ALT modifier is considered to effect a user selection of effects class DragSource: public MutexDummy, public WeakComponentImplHelper3<XDragSource, XInitialization, XServiceInfo>, public IDropSource { Reference<XMultiServiceFactory> m_serviceFactory; HWND m_hAppWindow; // The mouse button that set off the drag and drop operation short m_MouseButton; // Converts XTransferable objects to IDataObject objects. CDTransObjFactory m_aDataConverter; DragSource(); DragSource(const DragSource&); DragSource &operator= ( const DragSource&); // First starting a new drag and drop thread if // the last one has finished void StartDragImpl( const DragGestureEvent& trigger, sal_Int8 sourceActions, sal_Int32 cursor, sal_Int32 image, const Reference<XTransferable >& trans, const Reference<XDragSourceListener >& listener); public: long m_RunningDndOperationCount; public: // only valid for one dnd operation // the thread ID of the thread which created the window DWORD m_threadIdWindow; // The context notifies the XDragSourceListener s Reference<XDragSourceContext> m_currentContext; // the wrapper for the Transferable ( startDrag) IDataObjectPtr m_spDataObject; sal_Int8 m_sourceActions; public: DragSource(const Reference<XMultiServiceFactory>& sf); virtual ~DragSource(); // XInitialization virtual void SAL_CALL initialize( const Sequence< Any >& aArguments ) throw(Exception, RuntimeException); // XDragSource virtual sal_Bool SAL_CALL isDragImageSupported( ) throw(RuntimeException); virtual sal_Int32 SAL_CALL getDefaultCursor( sal_Int8 dragAction ) throw( IllegalArgumentException, RuntimeException); virtual void SAL_CALL startDrag( const DragGestureEvent& trigger, sal_Int8 sourceActions, sal_Int32 cursor, sal_Int32 image, const Reference<XTransferable >& trans, const Reference<XDragSourceListener >& listener ) throw( RuntimeException); // XServiceInfo virtual OUString SAL_CALL getImplementationName( ) throw (RuntimeException); virtual sal_Bool SAL_CALL supportsService( const OUString& ServiceName ) throw (RuntimeException); virtual Sequence< OUString > SAL_CALL getSupportedServiceNames( ) throw (RuntimeException); virtual HRESULT STDMETHODCALLTYPE QueryInterface( /* [in] */ REFIID riid, /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject); virtual ULONG STDMETHODCALLTYPE AddRef( ); virtual ULONG STDMETHODCALLTYPE Release( ); // IDropSource virtual HRESULT STDMETHODCALLTYPE QueryContinueDrag( /* [in] */ BOOL fEscapePressed, /* [in] */ DWORD grfKeyState); virtual HRESULT STDMETHODCALLTYPE GiveFeedback( /* [in] */ DWORD dwEffect); }; #endif
1,453
479
<reponame>jeremyvdw/aurora /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aurora.scheduler.updater.strategy; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Ordering; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * An update strategy that will only add more work when the current active group is empty. * Size of the groups are picked from the supplied list. * Last element is picked multiple times if necessary. * * @param <T> Instance type. */ public class VariableBatchStrategy<T extends Comparable<T>> implements UpdateStrategy<T> { private final Ordering<T> ordering; protected final ImmutableList<Integer> groupSizes; private final boolean rollingForward; private Optional<Integer> totalModInstanceCount; private static final Logger LOG = LoggerFactory.getLogger(VariableBatchStrategy.class); /** * Creates a variable active-limited strategy that applies an upper bound to all results. * * @param maxActiveGroups List of Maximum group sizes. Each group size represents a step. * {@link #getNextGroup(Set, Set)}. */ public VariableBatchStrategy( Ordering<T> ordering, List<Integer> maxActiveGroups, boolean rollingForward) { this.ordering = Objects.requireNonNull(ordering); this.rollingForward = rollingForward; maxActiveGroups.forEach(x -> Preconditions.checkArgument(x > 0)); this.groupSizes = ImmutableList.copyOf(maxActiveGroups); this.totalModInstanceCount = Optional.empty(); } // Determine how far we're into the update based upon how many instances are waiting // to be modified. private int determineCurGroupSize(int remaining) { // Calculate which groupIndex we are in by finding out how many instances we have left to update int modified = totalModInstanceCount.get() - remaining; int finalGroupSize = Iterables.getLast(groupSizes); LOG.debug("Variable Batch Update progress: {} instances have been modified, " + "{} instances remain unmodified, and {} overall instances to be modified.", modified, remaining, totalModInstanceCount.get()); if (rollingForward) { int sum = 0; for (Integer groupSize : groupSizes) { sum += groupSize; if (sum > modified) { return groupSize; } } // Return last step when number of instances > sum of all groups return finalGroupSize; } else { // To perform the update in reverse, we use the number of remaining tasks left to update // instead of using the number of already modified instances. In a rollback, the remaining // count represents the number of instances that were already modified while rolling forward // and need to be reverted. int curGroupSize = remaining; for (Integer groupSize : groupSizes) { // This handles an in between step. i.e.: updated instances = 4, update groups = [2,3] // which results in update groups 2 and 2 rolling forward at the time of failure. if (curGroupSize <= groupSize) { return curGroupSize; } curGroupSize -= groupSize; } // Handle the case where number of instances update were // greater than the sum of all update groups // Calculate the size of the last update group size performed while rolling forward. curGroupSize = curGroupSize % finalGroupSize; if (curGroupSize == 0) { return finalGroupSize; } else { return curGroupSize; } } } @Override public final Set<T> getNextGroup(Set<T> idle, Set<T> active) { // Get the size for the idle set on the first run only. This is representative of the number // of overall instance modifications this update will trigger. if (!totalModInstanceCount.isPresent()) { totalModInstanceCount = Optional.of(idle.size()); } // Limit group size to the current size of the group minus the number of instances currently // being modified. return ordering.sortedCopy(doGetNextGroup(idle, active)).stream() .limit(Math.max(0, determineCurGroupSize(idle.size()) - active.size())) .collect(Collectors.toSet()); } /** * Return a list of instances to be updated. * Returns an empty list if the current active group has not completed. * * @param idle Idle instances, candidate for being updated. * @param active Instances currently being updated. * @return all idle instances to start updating. */ Set<T> doGetNextGroup(Set<T> idle, Set<T> active) { return active.isEmpty() ? idle : ImmutableSet.of(); } }
1,723
1,056
<filename>java/spring.beans/src/org/netbeans/modules/spring/beans/completion/completors/PNamespaceBeanRefCompletor.java /* * 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.netbeans.modules.spring.beans.completion.completors; import java.io.IOException; import java.util.List; import org.netbeans.api.lexer.Token; import org.netbeans.api.xml.lexer.XMLTokenId; import org.netbeans.modules.spring.beans.completion.CompletionContext; import org.netbeans.modules.spring.beans.completion.Completor; import org.netbeans.modules.spring.beans.completion.CompletorUtils; import org.netbeans.modules.spring.beans.completion.SpringCompletionResult; import org.netbeans.modules.spring.beans.completion.SpringXMLConfigCompletionItem; import org.netbeans.modules.spring.beans.editor.ContextUtilities; /** * * @author <NAME> (<EMAIL>) */ public class PNamespaceBeanRefCompletor extends Completor { public PNamespaceBeanRefCompletor(int invocationOffset) { super(invocationOffset); } @Override protected int initAnchorOffset(CompletionContext context) { return context.getCurrentTokenOffset() + 1; } @Override protected void compute(CompletionContext context) throws IOException { Token<XMLTokenId> attribToken = ContextUtilities.getAttributeToken(context.getDocumentContext()); if (attribToken == null) { return; } String attribName = attribToken.text().toString(); if (!ContextUtilities.isPNamespaceName(context.getDocumentContext(), attribName)) { return; } if (!attribName.endsWith("-ref")) { // NOI18N return; } // XXX: Ideally find out the property name and it's expected type // to list bean proposals intelligently BeansRefCompletor beansRefCompletor = new BeansRefCompletor(true, context.getCaretOffset()); SpringCompletionResult result = beansRefCompletor.complete(context); for (SpringXMLConfigCompletionItem item : result.getItems()) { addCacheItem(item); } } @Override public boolean canFilter(CompletionContext context) { return CompletorUtils.canFilter(context.getDocument(), getInvocationOffset(), context.getCaretOffset(), getAnchorOffset(), CompletorUtils.BEAN_NAME_ACCEPTOR); } @Override protected List<SpringXMLConfigCompletionItem> doFilter(CompletionContext context) { return CompletorUtils.filter(getCacheItems(), context.getDocument(), getInvocationOffset(), context.getCaretOffset(), getAnchorOffset()); } }
1,093
409
<filename>giraffeplayer2/src/main/java/tcking/github/com/giraffeplayer2/UIHelper.java package tcking.github.com.giraffeplayer2; import android.app.Activity; import android.content.pm.ActivityInfo; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.util.DisplayMetrics; import android.view.Surface; import android.view.WindowManager; /** * Created by tcking on 2017 */ public class UIHelper { private Activity activity; public UIHelper(Activity activity) { this.activity = activity; } public static UIHelper with(Activity activity) { return new UIHelper(activity); } public UIHelper requestedOrientation(int orientation) { if (activity == null) { return this; } activity.setRequestedOrientation(orientation); return this; } public UIHelper showActionBar(boolean show) { if (activity == null) { return this; } if (activity instanceof AppCompatActivity) { ActionBar supportActionBar = ((AppCompatActivity) activity).getSupportActionBar(); if (supportActionBar != null) { try { supportActionBar.setShowHideAnimationEnabled(false); } catch (Exception e) { } if (show) { supportActionBar.show(); } else { supportActionBar.hide(); } } } return this; } public UIHelper fullScreen(boolean fullScreen) { if (activity == null) { return this; } WindowManager.LayoutParams attrs = activity.getWindow().getAttributes(); if (fullScreen) { attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN; activity.getWindow().setAttributes(attrs); // activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS); } else { attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN); activity.getWindow().setAttributes(attrs); // activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS); } return this; } private int getScreenOrientation() { if (activity == null) { return ActivityInfo.SCREEN_ORIENTATION_PORTRAIT; } int rotation = activity.getWindowManager().getDefaultDisplay().getRotation(); DisplayMetrics dm = new DisplayMetrics(); activity.getWindowManager().getDefaultDisplay().getMetrics(dm); int width = dm.widthPixels; int height = dm.heightPixels; int orientation; // if the device's natural orientation is portrait: if ((rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180) && height > width || (rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270) && width > height) { switch (rotation) { case Surface.ROTATION_0: orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT; break; case Surface.ROTATION_90: orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE; break; case Surface.ROTATION_180: orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT; break; case Surface.ROTATION_270: orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE; break; default: orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT; break; } } // if the device's natural orientation is landscape or if the device // is square: else { switch (rotation) { case Surface.ROTATION_0: orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE; break; case Surface.ROTATION_90: orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT; break; case Surface.ROTATION_180: orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE; break; case Surface.ROTATION_270: orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT; break; default: orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE; break; } } return orientation; } }
2,412
5,169
<reponame>Gantios/Specs { "name": "NKVPhonePicker", "version": "2.1.1", "summary": "A UITextField subclass to simplify the selection of country codes.", "description": "With this pod you can easily select country codes with just making your textFields class - the NKVPhonePickerTextField. \nSupport formatting phone to a specific pattern. Can select countries from the list.", "homepage": "https://github.com/NikKovIos/NKVPhonePicker", "platforms": { "ios": "10.0" }, "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "<NAME>": "<EMAIL>" }, "source": { "git": "https://github.com/NikKovIos/NKVPhonePicker.git", "tag": "2.1.1" }, "module_name": "NKVPhonePicker", "swift_versions": "5.0", "source_files": "Sources/**/*.swift", "resources": "Sources/Bundle/*", "social_media_url": "https://vk.com/nikekov", "swift_version": "5.0" }
348
1,473
/* * Autopsy Forensic Browser * * Copyright 2013-18 Basis Technology Corp. * Contact: carrier <at> sleuthkit <dot> org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sleuthkit.autopsy.imagegallery; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.util.concurrent.UncheckedExecutionException; import java.awt.image.BufferedImage; import java.io.BufferedInputStream; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.util.Optional; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import javafx.beans.Observable; import javafx.beans.property.SimpleIntegerProperty; import javafx.concurrent.Task; import javafx.embed.swing.SwingFXUtils; import javafx.scene.image.Image; import javafx.scene.image.WritableImage; import javax.annotation.Nullable; import javax.imageio.ImageIO; import org.sleuthkit.autopsy.coreutils.ImageUtils; import org.sleuthkit.autopsy.coreutils.Logger; import org.sleuthkit.autopsy.imagegallery.datamodel.DrawableFile; import org.sleuthkit.autopsy.imagegallery.utils.TaskUtils; import org.sleuthkit.datamodel.ReadContentInputStream; import org.sleuthkit.datamodel.TskCoreException; /** * Singleton to manage creation and access of icons. Keeps a cache in memory of * most recently used icons, and a disk cache of all icons. * * TODO: this was only a singleton for convenience, convert this to * non-singleton class -jm? */ public class ThumbnailCache { private final ImageGalleryController controller; public ThumbnailCache(ImageGalleryController controller) { this.controller = controller; } private static final int MAX_THUMBNAIL_SIZE = 300; private static final Logger LOGGER = Logger.getLogger(ThumbnailCache.class.getName()); /** * in memory cache. keeps at most 1000 items each for up to 10 minutes. * items may be garbage collected if there are no strong references to them. */ private final Cache<Long, Image> cache = CacheBuilder.newBuilder() .maximumSize(1000) .softValues() .expireAfterAccess(10, TimeUnit.MINUTES).build(); /** * currently desired icon size. is bound in {@link Toolbar} */ public final SimpleIntegerProperty iconSize = new SimpleIntegerProperty(200); /** * Clear out the cache between cases */ public final void clearCache() { cache.invalidateAll(); } /** * get the cached thumbnail for the given file or generate a new one if * needed * * @param file * * @return a thumbnail for the given file, returns null if the thumbnail * could not be generated */ @Nullable public Image get(DrawableFile file) { try { return cache.get(file.getId(), () -> load(file)); } catch (UncheckedExecutionException | CacheLoader.InvalidCacheLoadException | ExecutionException ex) { LOGGER.log(Level.WARNING, "Failed to load thumbnail for file: " + file.getName(), ex.getCause()); //NON-NLS return null; } } @Nullable public Image get(Long fileID) { try { return get(controller.getFileFromID(fileID)); } catch (TskCoreException ex) { LOGGER.log(Level.WARNING, "Failed to load thumbnail for file: " + fileID, ex.getCause()); //NON-NLS return null; } } /** * load a thumbnail from the disk based cache for the given file, or * generate and save a new thumbnail if one doesn't already exist * * @param file the DrawableFile to load a thumbnail of * * @return an (possibly empty) optional containing a thumbnail */ private Image load(DrawableFile file) { if (ImageUtils.isGIF(file.getAbstractFile())) { //directly read gif to preserve potential animation, //NOTE: not saved to disk! return new Image(new BufferedInputStream(new ReadContentInputStream(file.getAbstractFile())), MAX_THUMBNAIL_SIZE, MAX_THUMBNAIL_SIZE, true, true); } BufferedImage thumbnail = getCacheFile(file).map(cachFile -> { if (cachFile.exists()) { // If a thumbnail file is already saved locally, load it try { BufferedImage cachedThumbnail = ImageIO.read(cachFile); if (cachedThumbnail.getWidth() < MAX_THUMBNAIL_SIZE) { return cachedThumbnail; } } catch (MalformedURLException ex) { LOGGER.log(Level.WARNING, "Unable to parse cache file path: " + cachFile.getPath(), ex); //NON-NLS } catch (IOException ex) { LOGGER.log(Level.WARNING, "Unable to read cache file " + cachFile.getPath(), ex); //NON-NLS } } return null; }).orElseGet(() -> { return ImageUtils.getThumbnail(file.getAbstractFile(), MAX_THUMBNAIL_SIZE); }); WritableImage jfxthumbnail; if (thumbnail == ImageUtils.getDefaultThumbnail()) { // if we go the default icon, ignore it jfxthumbnail = null; } else { jfxthumbnail = SwingFXUtils.toFXImage(thumbnail, null); } return jfxthumbnail; //return icon, or null if generation failed } /** * get a File to store the cached icon in. * * @param id the obj id of the file to get a cache file for * * @return a Optional containing a File to store the cached icon in or an * empty optional if there was a problem. */ private static Optional<File> getCacheFile(DrawableFile file) { try { return Optional.of(ImageUtils.getCachedThumbnailFile(file.getAbstractFile(), MAX_THUMBNAIL_SIZE)); } catch (Exception e) { LOGGER.log(Level.WARNING, "Failed to create cache file.{0}", e.getLocalizedMessage()); //NON-NLS return Optional.empty(); } } public Task<Image> getThumbnailTask(DrawableFile file) { final Image thumbnail = cache.getIfPresent(file.getId()); if (thumbnail != null) { return TaskUtils.taskFrom(() -> thumbnail); } final Task<Image> newGetThumbnailTask = ImageUtils.newGetThumbnailTask(file.getAbstractFile(), MAX_THUMBNAIL_SIZE, false); newGetThumbnailTask.stateProperty().addListener((Observable observable) -> { switch (newGetThumbnailTask.getState()) { case SUCCEEDED: try { cache.put(Long.MIN_VALUE, newGetThumbnailTask.get()); } catch (InterruptedException | ExecutionException ex) { LOGGER.log(Level.SEVERE, "There was an exception even though thumbnail task succedded for. This should not be possible.", ex); //NON-NLS } } }); return newGetThumbnailTask; } }
2,979
2,338
// RUN: %clang_cc1 -triple x86_64-unknown-unknown -fopenmp -verify %s namespace { // TODO this must be fixed. This warning shouldn't be generated. // expected-warning@+1{{function '(anonymous namespace)::bar' has internal linkage but is not defined}} void bar(); } // namespace #pragma omp begin declare variant match(user = {condition(1)}) void bar() { } #pragma omp end declare variant // expected-warning@+1{{function 'baz' has internal linkage but is not defined}} static void baz(); #pragma omp begin declare variant match(device = {kind(nohost)}) static void baz() {} #pragma omp end declare variant #pragma omp begin declare variant match(device = {kind(host)}) static void foo() {} #pragma omp end declare variant int main() { foo(); // expected-note@+1{{used here}} baz(); // expected-note@+1{{used here}} bar(); return 0; }
280
777
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_OMNIBOX_BROWSER_HISTORY_QUICK_PROVIDER_H_ #define COMPONENTS_OMNIBOX_BROWSER_HISTORY_QUICK_PROVIDER_H_ #include <string> #include "base/compiler_specific.h" #include "base/gtest_prod_util.h" #include "base/macros.h" #include "components/history/core/browser/history_types.h" #include "components/omnibox/browser/autocomplete_input.h" #include "components/omnibox/browser/autocomplete_match.h" #include "components/omnibox/browser/history_provider.h" #include "components/omnibox/browser/in_memory_url_index.h" struct ScoredHistoryMatch; // This class is an autocomplete provider (a pseudo-internal component of // the history system) which quickly (and synchronously) provides matching // results from recently or frequently visited sites in the profile's // history. class HistoryQuickProvider : public HistoryProvider { public: explicit HistoryQuickProvider(AutocompleteProviderClient* client); // AutocompleteProvider. |minimal_changes| is ignored since there is no asynch // completion performed. void Start(const AutocompleteInput& input, bool minimal_changes) override; // Disable this provider. For unit testing purposes only. This is required // because this provider is closely associated with the HistoryURLProvider // and in order to properly test the latter the HistoryQuickProvider must // be disabled. // TODO(mrossetti): Eliminate this once the HUP has been refactored. static void set_disabled(bool disabled) { disabled_ = disabled; } private: friend class HistoryQuickProviderTest; FRIEND_TEST_ALL_PREFIXES(HistoryQuickProviderTest, Spans); FRIEND_TEST_ALL_PREFIXES(HistoryQuickProviderTest, Relevance); ~HistoryQuickProvider() override; // Performs the autocomplete matching and scoring. void DoAutocomplete(); // Creates an AutocompleteMatch from |history_match|, assigning it // the score |score|. AutocompleteMatch QuickMatchToACMatch(const ScoredHistoryMatch& history_match, int score); AutocompleteInput autocomplete_input_; InMemoryURLIndex* in_memory_url_index_; // Not owned by this class. // This provider is disabled when true. static bool disabled_; DISALLOW_COPY_AND_ASSIGN(HistoryQuickProvider); }; #endif // COMPONENTS_OMNIBOX_BROWSER_HISTORY_QUICK_PROVIDER_H_
769
372
<reponame>VisualMine/PlaneNet import numpy as np import glob import cv2 import os from utils import * ## This class handle one scene of the scannet dataset and provide interface for dataloaders class ScanNetScene(): def __init__(self, options, scenePath, scene_id): self.options = options self.loadCached = False self.scannetVersion = 2 if not self.loadCached: self.metadata = np.zeros(10) if self.scannetVersion == 1: with open(scenePath + '/frames/_info.txt') as f: for line in f: line = line.strip() tokens = [token for token in line.split(' ') if token.strip() != ''] if tokens[0] == "m_calibrationColorIntrinsic": intrinsics = np.array([float(e) for e in tokens[2:]]) intrinsics = intrinsics.reshape((4, 4)) self.metadata[0] = intrinsics[0][0] self.metadata[1] = intrinsics[1][1] self.metadata[2] = intrinsics[0][2] self.metadata[3] = intrinsics[1][2] elif tokens[0] == "m_colorWidth": self.colorWidth = int(tokens[2]) elif tokens[0] == "m_colorHeight": self.colorHeight = int(tokens[2]) elif tokens[0] == "m_depthWidth": self.depthWidth = int(tokens[2]) elif tokens[0] == "m_depthHeight": self.depthHeight = int(tokens[2]) elif tokens[0] == "m_depthShift": self.depthShift = int(tokens[2]) elif tokens[0] == "m_frames.size": self.numImages = int(tokens[2]) pass continue pass self.imagePaths = glob.glob(scenePath + '/frames/frame-*color.jpg') else: with open(scenePath + '/' + scene_id + '.txt') as f: for line in f: line = line.strip() tokens = [token for token in line.split(' ') if token.strip() != ''] if tokens[0] == "fx_color": self.metadata[0] = float(tokens[2]) if tokens[0] == "fy_color": self.metadata[1] = float(tokens[2]) if tokens[0] == "mx_color": self.metadata[2] = float(tokens[2]) if tokens[0] == "my_color": self.metadata[3] = float(tokens[2]) elif tokens[0] == "colorWidth": self.colorWidth = int(tokens[2]) elif tokens[0] == "colorHeight": self.colorHeight = int(tokens[2]) elif tokens[0] == "depthWidth": self.depthWidth = int(tokens[2]) elif tokens[0] == "depthHeight": self.depthHeight = int(tokens[2]) elif tokens[0] == "numDepthFrames": self.numImages = int(tokens[2]) pass continue pass self.depthShift = 1000.0 self.imagePaths = glob.glob(scenePath + '/frames/color/*.jpg') pass self.metadata[4] = self.colorWidth self.metadata[5] = self.colorHeight self.planes = np.load(scenePath + '/annotation/planes.npy') #self.imagePaths = [imagePath for imagePath in self.imagePaths if os.path.exists(imagePath.replace('frames/', 'annotation/segmentation/').replace('color.jpg', 'segmentation.png')) and os.path.exists(imagePath.replace('color.jpg', 'depth.pgm')) and os.path.exists(imagePath.replace('color.jpg', 'pose.txt'))] else: self.metadata = np.load(scenePath + '/annotation_new/info.npy') self.imagePaths = glob.glob(scenePath + '/annotation_new/frame-*.segmentation.png') pass # self.imagePaths = [] # for imageIndex in xrange(self.numImages): # self.imagePaths.append('%s/frames/frame-%06d.color.jpg'%(scenePath, imageIndex)) # continue return def getItemCached(self, imageIndex): segmentationPath = self.imagePaths[imageIndex] imagePath = segmentationPath.replace('annotation_new/', 'frames/').replace('segmentation.png', 'color.jpg') image = cv2.imread(imagePath) depth = cv2.imread(imagePath.replace('color.jpg', 'depth.pgm'), -1).astype(np.float32) / self.metadata[6] extrinsics_inv = [] with open(imagePath.replace('color.jpg', 'pose.txt'), 'r') as f: for line in f: extrinsics_inv += [float(value) for value in line.strip().split(' ') if value.strip() != ''] continue pass extrinsics_inv = np.array(extrinsics_inv).reshape((4, 4)) extrinsics = np.linalg.inv(extrinsics_inv) temp = extrinsics[1].copy() extrinsics[1] = extrinsics[2] extrinsics[2] = -temp segmentation = cv2.imread(segmentationPath, -1).astype(np.int32) #segmentation = segmentation[:, :, 2] * 256 * 256 + segmentation[:, :, 1] * 256 + segmentation[:, :, 0] planes = np.load(segmentationPath.replace('segmentation.png', 'planes.npy')) info = [image, planes, segmentation, depth, self.metadata] if False: print(planes) print(depth.min(), depth.max()) cv2.imwrite('test/image.png', image) cv2.imwrite('test/depth_ori.png', drawDepthImage(depth)) cv2.imwrite('test/segmentation.png', drawSegmentationImage(segmentation)) # for index in range(segmentation.max() + 1): # print(index, newPlanes[index]) # cv2.imwrite('test/mask_' + str(index) + '.png', (segmentation == index).astype(np.uint8) * 255) # continue #planeDepths = calcPlaneDepths(planes, segmentation, 192, self.metadata) exit(1) return info def transformPlanes(self, transformation, planes): planeOffsets = np.linalg.norm(planes, axis=-1, keepdims=True) centers = planes centers = np.concatenate([centers, np.ones((planes.shape[0], 1))], axis=-1) newCenters = np.transpose(np.matmul(transformation, np.transpose(centers))) newCenters = newCenters[:, :3] / newCenters[:, 3:4] refPoints = planes - planes / np.maximum(planeOffsets, 1e-4) refPoints = np.concatenate([refPoints, np.ones((planes.shape[0], 1))], axis=-1) newRefPoints = np.transpose(np.matmul(transformation, np.transpose(refPoints))) newRefPoints = newRefPoints[:, :3] / newRefPoints[:, 3:4] planeNormals = newRefPoints - newCenters planeNormals /= np.linalg.norm(planeNormals, axis=-1, keepdims=True) planeOffsets = np.sum(newCenters * planeNormals, axis=-1, keepdims=True) newPlanes = planeNormals * planeOffsets return newPlanes def __getitem__(self, imageIndex): if self.loadCached: return self.getItemCached(imageIndex) imagePath = self.imagePaths[imageIndex] if self.scannetVersion == 1: segmentationPath = imagePath.replace('frames/', 'annotation/segmentation/').replace('color.jpg', 'segmentation.png') depthPath = imagePath.replace('color.jpg', 'depth.pgm') posePath = imagePath.replace('color.jpg', 'pose.txt') else: segmentationPath = imagePath.replace('frames/color/', 'annotation/segmentation/').replace('.jpg', '.png') depthPath = imagePath.replace('color', 'depth').replace('.jpg', '.png') posePath = imagePath.replace('color', 'pose').replace('.jpg', '.txt') pass image = cv2.imread(imagePath) depth = cv2.imread(depthPath, -1).astype(np.float32) / self.depthShift extrinsics_inv = [] with open(posePath, 'r') as f: for line in f: extrinsics_inv += [float(value) for value in line.strip().split(' ') if value.strip() != ''] continue pass extrinsics_inv = np.array(extrinsics_inv).reshape((4, 4)) extrinsics = np.linalg.inv(extrinsics_inv) segmentation = cv2.imread(segmentationPath, -1).astype(np.int32) segmentation = segmentation[:, :, 2] * 256 * 256 + segmentation[:, :, 1] * 256 + segmentation[:, :, 0] segmentation = segmentation / 100 - 1 segments, counts = np.unique(segmentation, return_counts=True) segmentList = zip(segments.tolist(), counts.tolist()) segmentList = [segment for segment in segmentList if segment[0] not in [-1, 167771]] segmentList = sorted(segmentList, key=lambda x:-x[1]) newPlanes = [] newSegmentation = np.full(segmentation.shape, fill_value=-1, dtype=np.int32) for newIndex, (oriIndex, count) in enumerate(segmentList): if count < (segmentation.shape[0] * segmentation.shape[1]) * 0.02: continue newPlanes.append(self.planes[oriIndex]) newSegmentation[segmentation == oriIndex] = newIndex continue newPlanes = np.array(newPlanes) temp = extrinsics[1].copy() extrinsics[1] = extrinsics[2] extrinsics[2] = -temp if len(newPlanes) > 0: newPlanes = self.transformPlanes(extrinsics, newPlanes) pass info = [image, newPlanes, newSegmentation, depth, self.metadata] if False: print(newPlanes) print(depth.min(), depth.max()) cv2.imwrite('test/image.png', image) cv2.imwrite('test/depth_ori.png', drawDepthImage(depth)) cv2.imwrite('test/segmentation.png', drawSegmentationImage(newSegmentation)) for index in range(newSegmentation.max() + 1): print(index, newPlanes[index]) cv2.imwrite('test/mask_' + str(index) + '.png', (newSegmentation == index).astype(np.uint8) * 255) continue #planeDepths = calcPlaneDepths(planes, segmentation, 192, self.metadata) exit(1) return info
5,554
3,787
{ "module_path": "federatedml/util", "param_class" : "federatedml/param/sample_weight_param.py/SampleWeightParam", "role": { "guest|host": { "program": "sample_weight.py/SampleWeight" } } }
126
1,738
<reponame>chriscoombs/aws-comparing-algorithms-performance-mlops-cdk # Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF # ANY KIND, either express or implied. See the License for the specific # language governing permissions and limitations under the License. import inspect import sys import os import errno import socket from botocore.compat import six if sys.platform.startswith('win'): def rename_file(current_filename, new_filename): try: os.remove(new_filename) except OSError as e: if not e.errno == errno.ENOENT: # We only want to a ignore trying to remove # a file that does not exist. If it fails # for any other reason we should be propagating # that exception. raise os.rename(current_filename, new_filename) else: rename_file = os.rename if six.PY3: def accepts_kwargs(func): # In python3.4.1, there's backwards incompatible # changes when using getargspec with functools.partials. return inspect.getfullargspec(func)[2] # In python3, socket.error is OSError, which is too general # for what we want (i.e FileNotFoundError is a subclass of OSError). # In py3 all the socket related errors are in a newly created # ConnectionError SOCKET_ERROR = ConnectionError MAXINT = None else: def accepts_kwargs(func): return inspect.getargspec(func)[2] SOCKET_ERROR = socket.error MAXINT = sys.maxint def seekable(fileobj): """Backwards compat function to determine if a fileobj is seekable :param fileobj: The file-like object to determine if seekable :returns: True, if seekable. False, otherwise. """ # If the fileobj has a seekable attr, try calling the seekable() # method on it. if hasattr(fileobj, 'seekable'): return fileobj.seekable() # If there is no seekable attr, check if the object can be seeked # or telled. If it can, try to seek to the current position. elif hasattr(fileobj, 'seek') and hasattr(fileobj, 'tell'): try: fileobj.seek(0, 1) return True except (OSError, IOError): # If an io related error was thrown then it is not seekable. return False # Else, the fileobj is not seekable return False def readable(fileobj): """Determines whether or not a file-like object is readable. :param fileobj: The file-like object to determine if readable :returns: True, if readable. False otherwise. """ if hasattr(fileobj, 'readable'): return fileobj.readable() return hasattr(fileobj, 'read') def fallocate(fileobj, size): if hasattr(os, 'posix_fallocate'): os.posix_fallocate(fileobj.fileno(), 0, size) else: fileobj.truncate(size) from multiprocessing.managers import BaseManager
1,213
502
<reponame>jackx22/fixflow package com.founder.fix.fixflow.util; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.google.gson.Gson; import com.google.gson.GsonBuilder; /** * JSON工具类 * @author hanyanwei * */ public class JSONUtil { /** * JSON中的NULL */ public static final Object NULL = org.json.JSONObject.NULL; /** 空的 {@code JSON} 数据 - <code>"{}"</code>。 */ public static final String EMPTY_JSON = "{}"; /** 空的 {@code JSON} 数组(集合)数据 - {@code "[]"}。 */ public static final String EMPTY_JSON_ARRAY = "[]"; /** 默认的 {@code JSON} 日期/时间字段的格式化模式。 */ public static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd HH:mm:ss SSS"; /** {@code Google Gson} 的 {@literal @Since} 注解常用的版本号常量 - {@code 1.0}。 */ public static final Double SINCE_VERSION_10 = 1.0d; /** {@code Google Gson} 的 {@literal @Since} 注解常用的版本号常量 - {@code 1.1}。 */ public static final Double SINCE_VERSION_11 = 1.1d; /** {@code Google Gson} 的 {@literal @Since} 注解常用的版本号常量 - {@code 1.2}。 */ public static final Double SINCE_VERSION_12 = 1.2d; private JSONUtil() { } /** * 将json数据转换为map * @param strJSON * @return map */ @SuppressWarnings("unchecked") public static Map<String, Object> parseJSON2MapFirstLevel(String strJSON) { if (strJSON!=null && isJSONObject(strJSON)) try { return (Map<String, Object>) __parseJSON(new JSONObject(strJSON),false); } catch (JSONException e) { return new HashMap<String, Object>(); } else return new HashMap<String, Object>(); } /** * 将json数据转换为map * @param strJSON * @return map */ @SuppressWarnings("unchecked") public static Map<String, Object> parseJSON2Map(String strJSON) { if (strJSON!=null && isJSONObject(strJSON)) try { return (Map<String, Object>) __parseJSON(new JSONObject(strJSON),true); } catch (JSONException e) { return new HashMap<String, Object>(); } else return new HashMap<String, Object>(); } /** * 将json数据转换为list * @param strJSON * @return list */ @SuppressWarnings("unchecked") public static List<Object> parseJSON2List(String strJSON) { if (strJSON!=null && isJSONArray(strJSON)) try { return (List<Object>) __parseJSON(new JSONArray(strJSON),true); } catch (JSONException e) { return new ArrayList<Object>(); } else return new ArrayList<Object>(); } /**通过JSON字符串转换成JAVA对象Map,List * @param strJSON * 只能是对象{a:'',b:''}或数组['a','b'] * @return JSON * @throws JSONException */ public static Object parseJSON(String strJSON) { Object obj = null; if (strJSON!=null && isJSONArray(strJSON)) { obj = parseJSON2List(strJSON); } else if (strJSON!=null && isJSONObject(strJSON)) { obj = parseJSON2Map(strJSON); } return obj; } private static Object __parseJSON(Object jsonObj,boolean doAll) throws JSONException { Object ret = null; if (jsonObj instanceof JSONArray) { JSONArray _array = (JSONArray) jsonObj; ArrayList<Object> _ret_list = new ArrayList<Object>(); for (int _i = 0; _i < _array.length(); _i++) { Object _item = _array.get(_i); if(doAll){ if (_item instanceof JSONObject || _item instanceof JSONArray) _ret_list.add(__parseJSON(_item,true)); else _ret_list.add(_item); }else{ _ret_list.add(_item.toString()); } } ret = _ret_list; } else if (jsonObj instanceof JSONObject) { JSONObject _obj = (JSONObject) jsonObj; Map<String, Object> _ret_map = new HashMap<String, Object>(); for (Iterator<?> _it = _obj.keys(); _it.hasNext();) { String _key = _it.next().toString(); Object _item = _obj.get(_key); if(doAll){ if (_item instanceof JSONObject || _item instanceof JSONArray) _ret_map.put(_key, __parseJSON(_item,true)); else _ret_map.put(_key, _item); }else{ _ret_map.put(_key,_item.toString()); } } ret = _ret_map; } return ret; } private static String toJson(Object target, Type targetType, boolean isSerializeNulls, Double version, String datePattern, boolean excludesFieldsWithoutExpose) { if (target == null) return EMPTY_JSON; GsonBuilder builder = new GsonBuilder(); if (isSerializeNulls) builder.serializeNulls(); if (version != null) builder.setVersion(version.doubleValue()); // if (StringUtil.isEmpty(datePattern)) // datePattern = DEFAULT_DATE_PATTERN; builder.setDateFormat(datePattern); if (excludesFieldsWithoutExpose) builder.excludeFieldsWithoutExposeAnnotation(); String result = null; Gson gson = builder.create(); try { if (targetType != null) { result = gson.toJson(target, targetType); } else { result = gson.toJson(target); } } catch (Exception ex) { if (target instanceof Collection || target instanceof Iterator || target instanceof Enumeration || target.getClass().isArray()) { result = EMPTY_JSON_ARRAY; } else result = EMPTY_JSON; } return result; } /**通过JAVA对象转换成JSON字符串 * @param obj * JAVA对象:bean,map,list * @return JSON字符串 */ public static String parseObject2JSON(Object obj) { return toJson(obj,null,true,null,null,false); } private static boolean isJSONArray(String strJSON) { return strJSON.matches("^\\s*\\[.*"); } private static boolean isJSONObject(String strJSON) { return strJSON.matches("^\\s*\\{.*"); } }
2,989
3,269
# Time: O(nlogn) # Space: O(1) class Solution(object): def countPairs(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: int """ for i in xrange(len(nums1)): nums1[i] -= nums2[i] nums1.sort() result = 0 left, right = 0, len(nums1)-1 while left < right: if nums1[left] > 0 or -nums1[left] < nums1[right]: result += right-left right -= 1 else: left += 1 return result
335
665
/* * 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.isis.testdomain.model.good; import java.util.List; import java.util.stream.Collectors; import org.apache.isis.applib.annotation.Action; import org.apache.isis.applib.annotation.Collection; import org.apache.isis.applib.annotation.DomainObject; import org.apache.isis.applib.annotation.Nature; import org.apache.isis.commons.internal.collections._Lists; @DomainObject(nature = Nature.VIEW_MODEL) public class ProperChoicesWhenChoicesFrom { @Collection public List<String> getCandidates() { return _Lists.of("a", "b", "c"); } // expected to pass MM validation, even though there are no member-support methods // that would provide parameter choices (for 'input'), instead @Action(choicesFrom = "candidates") // should be sufficient to derive both // 1. ActionParameterChoicesFacetFromParentedCollection // 2. ActionParameterDefaultsFacetFromAssociatedCollection @Action(choicesFrom = "candidates") public List<String> appendACharacterToCandidates(List<String> input) { return input.stream() .map(candidate->candidate + "!") .collect(Collectors.toList()); } }
617
945
/*========================================================================= * * Copyright NumFOCUS * * 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.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef itkBruker2dseqImageIO_h #define itkBruker2dseqImageIO_h #include "ITKIOBrukerExport.h" #include "itkImageIOBase.h" #include "itkVectorContainer.h" namespace itk { /** *\class Bruker2dseqImageIO * \brief Class that defines how to read Bruker file format. * * The following is a brief description of the Bruker file format. * * Within the directory representing a 'session' on the scanner, data is laid * out thus: * * session/ * 1/ <- Series/Acquisition number * method <- An important header file * acqp <- Another important header * fid <- Raw data * **other unimportant files** * pdata/ * 1/ <- Reconstruction number (may be multiple) * 2dseq <- Reconstructed data * visu_pars <- Most important header * reco <- Mostly duplicated in visu_pars * procs <- Unimportant header * id <- Unimportant header * 2/ * ... * * The minimum required data to read the image is the '2dseq' and 'visu_pars' * file. To use this reader, specify the 2dseq file as the filename. It will * check for the existence of the visu_pars file. If both these exist, the file * is opened. If the other header files exist (method, acqp, etc.) in the * correct locations then they will be read and added to the meta-data * dictionary, but they are not used to read the image data itself. * * This class supports reading only. * * This file reader has been updated for ParaVision 6 2dseq files. The original * code was written by <NAME> at Penn State in 2004. It has been * significantly changed, as Bruker also changed the format for ParaVision 6. * In particular a new header file, 'visu_pars' was introduced that means that * multiple headers no longer need to be read in order to read the '2dseq' * file. However, if the other Bruker headers are still present they are read * and added to the meta-data in case users wish to extract data from them. * * The original implementation was contributed as a paper to the Insight Journal * https://www.insight-journal.org/browse/publication/237 * * \ingroup ITKIOBruker * * \author <NAME>, King's College London 2017 */ class ITKIOBruker_EXPORT Bruker2dseqImageIO : public ImageIOBase { public: ITK_DISALLOW_COPY_AND_MOVE(Bruker2dseqImageIO); /* Standard class type aliases. */ using Self = Bruker2dseqImageIO; using Superclass = ImageIOBase; using Pointer = SmartPointer<Self>; using ConstPointer = SmartPointer<const Self>; /** New macro for creation of through a SmartPointer. */ itkNewMacro(Self); /** Run-time type information (and related methods). */ itkTypeMacro(Bruker2dseqImageIO, ImageIOBase); /** Determine if the necessary files exist to read the specified 2dseq file. * Returns true if all required files exist. */ bool CanReadFile(const char * FileNameToRead) override; /** Set the spacing and dimension information for the set filename. */ void ReadImageInformation() override; /** Reads the data from disk into the memory buffer provided. */ void Read(void * buffer) override; /** Writing files has not been implemented for Bruker 2dseq. * This function will always return false. */ bool CanWriteFile(const char * itkNotUsed(FileNameToWrite)) override { return false; } /** Not implemented. */ void WriteImageInformation() override { return; } /** Not implemented - does nothing */ void Write(const void * itkNotUsed(buffer)) override { return; } protected: Bruker2dseqImageIO(); ~Bruker2dseqImageIO() override; void PrintSelf(std::ostream & os, Indent indent) const override; private: void SwapBytesIfNecessary(void * buff, SizeValueType components); IOComponentEnum m_OnDiskComponentType{ IOComponentEnum::UCHAR }; IOByteOrderEnum m_MachineByteOrder; }; } // end namespace itk #endif // itkBruker2dseqImageIO_h
1,648
678
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>. // #import "NSObject.h" @class NSString; @interface WCRedEnvelopesOperationInfo : NSObject { _Bool m_bOpEnable; NSString *m_nsOpName; NSString *m_nsOpType; NSString *m_nsOpContent; NSString *m_nsOpShowType; id m_inSender; unsigned int m_uiOsskey; } @property(nonatomic) unsigned int m_uiOsskey; // @synthesize m_uiOsskey; @property(nonatomic) __weak id m_inSender; // @synthesize m_inSender; @property(retain, nonatomic) NSString *m_nsOpShowType; // @synthesize m_nsOpShowType; @property(retain, nonatomic) NSString *m_nsOpContent; // @synthesize m_nsOpContent; @property(retain, nonatomic) NSString *m_nsOpType; // @synthesize m_nsOpType; @property(retain, nonatomic) NSString *m_nsOpName; // @synthesize m_nsOpName; @property(nonatomic) _Bool m_bOpEnable; // @synthesize m_bOpEnable; - (void).cxx_destruct; @end
405
3,645
<reponame>huyu0415/FFmpeg<gh_stars>1000+ /* * Copyright (c) 2015 <NAME> (<EMAIL>) * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "libavutil/mips/generic_macros_msa.h" #include "h264dsp_mips.h" static void intra_predict_vert_8x8_msa(uint8_t *src, uint8_t *dst, int32_t dst_stride) { uint32_t row; uint32_t src_data1, src_data2; src_data1 = LW(src); src_data2 = LW(src + 4); for (row = 8; row--;) { SW(src_data1, dst); SW(src_data2, (dst + 4)); dst += dst_stride; } } static void intra_predict_vert_16x16_msa(uint8_t *src, uint8_t *dst, int32_t dst_stride) { uint32_t row; v16u8 src0; src0 = LD_UB(src); for (row = 16; row--;) { ST_UB(src0, dst); dst += dst_stride; } } static void intra_predict_horiz_8x8_msa(uint8_t *src, int32_t src_stride, uint8_t *dst, int32_t dst_stride) { uint64_t out0, out1, out2, out3, out4, out5, out6, out7; out0 = src[0 * src_stride] * 0x0101010101010101; out1 = src[1 * src_stride] * 0x0101010101010101; out2 = src[2 * src_stride] * 0x0101010101010101; out3 = src[3 * src_stride] * 0x0101010101010101; out4 = src[4 * src_stride] * 0x0101010101010101; out5 = src[5 * src_stride] * 0x0101010101010101; out6 = src[6 * src_stride] * 0x0101010101010101; out7 = src[7 * src_stride] * 0x0101010101010101; SD4(out0, out1, out2, out3, dst, dst_stride); dst += (4 * dst_stride); SD4(out4, out5, out6, out7, dst, dst_stride); } static void intra_predict_horiz_16x16_msa(uint8_t *src, int32_t src_stride, uint8_t *dst, int32_t dst_stride) { uint32_t row; uint8_t inp0, inp1, inp2, inp3; v16u8 src0, src1, src2, src3; for (row = 4; row--;) { inp0 = src[0]; src += src_stride; inp1 = src[0]; src += src_stride; inp2 = src[0]; src += src_stride; inp3 = src[0]; src += src_stride; src0 = (v16u8) __msa_fill_b(inp0); src1 = (v16u8) __msa_fill_b(inp1); src2 = (v16u8) __msa_fill_b(inp2); src3 = (v16u8) __msa_fill_b(inp3); ST_UB4(src0, src1, src2, src3, dst, dst_stride); dst += (4 * dst_stride); } } static void intra_predict_dc_8x8_msa(uint8_t *src_top, uint8_t *src_left, int32_t src_stride_left, uint8_t *dst, int32_t dst_stride, uint8_t is_above, uint8_t is_left) { uint32_t row; uint32_t out, addition = 0; v16u8 src_above, store; v8u16 sum_above; v4u32 sum_top; v2u64 sum; if (is_left && is_above) { src_above = LD_UB(src_top); sum_above = __msa_hadd_u_h(src_above, src_above); sum_top = __msa_hadd_u_w(sum_above, sum_above); sum = __msa_hadd_u_d(sum_top, sum_top); addition = __msa_copy_u_w((v4i32) sum, 0); for (row = 0; row < 8; row++) { addition += src_left[row * src_stride_left]; } addition = (addition + 8) >> 4; store = (v16u8) __msa_fill_b(addition); } else if (is_left) { for (row = 0; row < 8; row++) { addition += src_left[row * src_stride_left]; } addition = (addition + 4) >> 3; store = (v16u8) __msa_fill_b(addition); } else if (is_above) { src_above = LD_UB(src_top); sum_above = __msa_hadd_u_h(src_above, src_above); sum_top = __msa_hadd_u_w(sum_above, sum_above); sum = __msa_hadd_u_d(sum_top, sum_top); sum = (v2u64) __msa_srari_d((v2i64) sum, 3); store = (v16u8) __msa_splati_b((v16i8) sum, 0); } else { store = (v16u8) __msa_ldi_b(128); } out = __msa_copy_u_w((v4i32) store, 0); for (row = 8; row--;) { SW(out, dst); SW(out, (dst + 4)); dst += dst_stride; } } static void intra_predict_dc_16x16_msa(uint8_t *src_top, uint8_t *src_left, int32_t src_stride_left, uint8_t *dst, int32_t dst_stride, uint8_t is_above, uint8_t is_left) { uint32_t row; uint32_t addition = 0; v16u8 src_above, store; v8u16 sum_above; v4u32 sum_top; v2u64 sum; if (is_left && is_above) { src_above = LD_UB(src_top); sum_above = __msa_hadd_u_h(src_above, src_above); sum_top = __msa_hadd_u_w(sum_above, sum_above); sum = __msa_hadd_u_d(sum_top, sum_top); sum_top = (v4u32) __msa_pckev_w((v4i32) sum, (v4i32) sum); sum = __msa_hadd_u_d(sum_top, sum_top); addition = __msa_copy_u_w((v4i32) sum, 0); for (row = 0; row < 16; row++) { addition += src_left[row * src_stride_left]; } addition = (addition + 16) >> 5; store = (v16u8) __msa_fill_b(addition); } else if (is_left) { for (row = 0; row < 16; row++) { addition += src_left[row * src_stride_left]; } addition = (addition + 8) >> 4; store = (v16u8) __msa_fill_b(addition); } else if (is_above) { src_above = LD_UB(src_top); sum_above = __msa_hadd_u_h(src_above, src_above); sum_top = __msa_hadd_u_w(sum_above, sum_above); sum = __msa_hadd_u_d(sum_top, sum_top); sum_top = (v4u32) __msa_pckev_w((v4i32) sum, (v4i32) sum); sum = __msa_hadd_u_d(sum_top, sum_top); sum = (v2u64) __msa_srari_d((v2i64) sum, 4); store = (v16u8) __msa_splati_b((v16i8) sum, 0); } else { store = (v16u8) __msa_ldi_b(128); } for (row = 16; row--;) { ST_UB(store, dst); dst += dst_stride; } } #define INTRA_PREDICT_VALDC_8X8_MSA(val) \ static void intra_predict_##val##dc_8x8_msa(uint8_t *dst, \ int32_t dst_stride) \ { \ uint32_t row, out; \ v16i8 store; \ \ store = __msa_ldi_b(val); \ out = __msa_copy_u_w((v4i32) store, 0); \ \ for (row = 8; row--;) { \ SW(out, dst); \ SW(out, (dst + 4)); \ dst += dst_stride; \ } \ } INTRA_PREDICT_VALDC_8X8_MSA(127); INTRA_PREDICT_VALDC_8X8_MSA(129); #define INTRA_PREDICT_VALDC_16X16_MSA(val) \ static void intra_predict_##val##dc_16x16_msa(uint8_t *dst, \ int32_t dst_stride) \ { \ uint32_t row; \ v16u8 store; \ \ store = (v16u8) __msa_ldi_b(val); \ \ for (row = 16; row--;) { \ ST_UB(store, dst); \ dst += dst_stride; \ } \ } INTRA_PREDICT_VALDC_16X16_MSA(127); INTRA_PREDICT_VALDC_16X16_MSA(129); static void intra_predict_plane_8x8_msa(uint8_t *src, int32_t stride) { uint8_t lpcnt; int32_t res, res0, res1, res2, res3; uint64_t out0, out1; v16i8 shf_mask = { 3, 5, 2, 6, 1, 7, 0, 8, 3, 5, 2, 6, 1, 7, 0, 8 }; v8i16 short_multiplier = { 1, 2, 3, 4, 1, 2, 3, 4 }; v4i32 int_multiplier = { 0, 1, 2, 3 }; v16u8 src_top; v8i16 vec9, vec10, vec11; v4i32 vec0, vec1, vec2, vec3, vec4, vec5, vec6, vec7, vec8; v2i64 sum; src_top = LD_UB(src - (stride + 1)); src_top = (v16u8) __msa_vshf_b(shf_mask, (v16i8) src_top, (v16i8) src_top); vec9 = __msa_hsub_u_h(src_top, src_top); vec9 *= short_multiplier; vec8 = __msa_hadd_s_w(vec9, vec9); sum = __msa_hadd_s_d(vec8, vec8); res0 = __msa_copy_s_w((v4i32) sum, 0); res1 = (src[4 * stride - 1] - src[2 * stride - 1]) + 2 * (src[5 * stride - 1] - src[stride - 1]) + 3 * (src[6 * stride - 1] - src[-1]) + 4 * (src[7 * stride - 1] - src[-stride - 1]); res0 *= 17; res1 *= 17; res0 = (res0 + 16) >> 5; res1 = (res1 + 16) >> 5; res3 = 3 * (res0 + res1); res2 = 16 * (src[7 * stride - 1] + src[-stride + 7] + 1); res = res2 - res3; vec8 = __msa_fill_w(res0); vec4 = __msa_fill_w(res); vec2 = __msa_fill_w(res1); vec5 = vec8 * int_multiplier; vec3 = vec8 * 4; for (lpcnt = 4; lpcnt--;) { vec0 = vec5; vec0 += vec4; vec1 = vec0 + vec3; vec6 = vec5; vec4 += vec2; vec6 += vec4; vec7 = vec6 + vec3; SRA_4V(vec0, vec1, vec6, vec7, 5); PCKEV_H2_SH(vec1, vec0, vec7, vec6, vec10, vec11); CLIP_SH2_0_255(vec10, vec11); PCKEV_B2_SH(vec10, vec10, vec11, vec11, vec10, vec11); out0 = __msa_copy_s_d((v2i64) vec10, 0); out1 = __msa_copy_s_d((v2i64) vec11, 0); SD(out0, src); src += stride; SD(out1, src); src += stride; vec4 += vec2; } } static void intra_predict_plane_16x16_msa(uint8_t *src, int32_t stride) { uint8_t lpcnt; int32_t res0, res1, res2, res3; uint64_t load0, load1; v16i8 shf_mask = { 7, 8, 6, 9, 5, 10, 4, 11, 3, 12, 2, 13, 1, 14, 0, 15 }; v8i16 short_multiplier = { 1, 2, 3, 4, 5, 6, 7, 8 }; v4i32 int_multiplier = { 0, 1, 2, 3 }; v16u8 src_top = { 0 }; v8i16 vec9, vec10; v4i32 vec0, vec1, vec2, vec3, vec4, vec5, vec6, vec7, vec8, res_add; load0 = LD(src - (stride + 1)); load1 = LD(src - (stride + 1) + 9); INSERT_D2_UB(load0, load1, src_top); src_top = (v16u8) __msa_vshf_b(shf_mask, (v16i8) src_top, (v16i8) src_top); vec9 = __msa_hsub_u_h(src_top, src_top); vec9 *= short_multiplier; vec8 = __msa_hadd_s_w(vec9, vec9); res_add = (v4i32) __msa_hadd_s_d(vec8, vec8); res0 = __msa_copy_s_w(res_add, 0) + __msa_copy_s_w(res_add, 2); res1 = (src[8 * stride - 1] - src[6 * stride - 1]) + 2 * (src[9 * stride - 1] - src[5 * stride - 1]) + 3 * (src[10 * stride - 1] - src[4 * stride - 1]) + 4 * (src[11 * stride - 1] - src[3 * stride - 1]) + 5 * (src[12 * stride - 1] - src[2 * stride - 1]) + 6 * (src[13 * stride - 1] - src[stride - 1]) + 7 * (src[14 * stride - 1] - src[-1]) + 8 * (src[15 * stride - 1] - src[-1 * stride - 1]); res0 *= 5; res1 *= 5; res0 = (res0 + 32) >> 6; res1 = (res1 + 32) >> 6; res3 = 7 * (res0 + res1); res2 = 16 * (src[15 * stride - 1] + src[-stride + 15] + 1); res2 -= res3; vec8 = __msa_fill_w(res0); vec4 = __msa_fill_w(res2); vec5 = __msa_fill_w(res1); vec6 = vec8 * 4; vec7 = vec8 * int_multiplier; for (lpcnt = 16; lpcnt--;) { vec0 = vec7; vec0 += vec4; vec1 = vec0 + vec6; vec2 = vec1 + vec6; vec3 = vec2 + vec6; SRA_4V(vec0, vec1, vec2, vec3, 5); PCKEV_H2_SH(vec1, vec0, vec3, vec2, vec9, vec10); CLIP_SH2_0_255(vec9, vec10); PCKEV_ST_SB(vec9, vec10, src); src += stride; vec4 += vec5; } } static void intra_predict_dc_4blk_8x8_msa(uint8_t *src, int32_t stride) { uint8_t lp_cnt; uint32_t src0, src1, src3, src2 = 0; uint32_t out0, out1, out2, out3; v16u8 src_top; v8u16 add; v4u32 sum; src_top = LD_UB(src - stride); add = __msa_hadd_u_h((v16u8) src_top, (v16u8) src_top); sum = __msa_hadd_u_w(add, add); src0 = __msa_copy_u_w((v4i32) sum, 0); src1 = __msa_copy_u_w((v4i32) sum, 1); for (lp_cnt = 0; lp_cnt < 4; lp_cnt++) { src0 += src[lp_cnt * stride - 1]; src2 += src[(4 + lp_cnt) * stride - 1]; } src0 = (src0 + 4) >> 3; src3 = (src1 + src2 + 4) >> 3; src1 = (src1 + 2) >> 2; src2 = (src2 + 2) >> 2; out0 = src0 * 0x01010101; out1 = src1 * 0x01010101; out2 = src2 * 0x01010101; out3 = src3 * 0x01010101; for (lp_cnt = 4; lp_cnt--;) { SW(out0, src); SW(out1, (src + 4)); SW(out2, (src + 4 * stride)); SW(out3, (src + 4 * stride + 4)); src += stride; } } static void intra_predict_hor_dc_8x8_msa(uint8_t *src, int32_t stride) { uint8_t lp_cnt; uint32_t src0 = 0, src1 = 0; uint64_t out0, out1; for (lp_cnt = 0; lp_cnt < 4; lp_cnt++) { src0 += src[lp_cnt * stride - 1]; src1 += src[(4 + lp_cnt) * stride - 1]; } src0 = (src0 + 2) >> 2; src1 = (src1 + 2) >> 2; out0 = src0 * 0x0101010101010101; out1 = src1 * 0x0101010101010101; for (lp_cnt = 4; lp_cnt--;) { SD(out0, src); SD(out1, (src + 4 * stride)); src += stride; } } static void intra_predict_vert_dc_8x8_msa(uint8_t *src, int32_t stride) { uint8_t lp_cnt; uint32_t out0 = 0, out1 = 0; v16u8 src_top; v8u16 add; v4u32 sum; v4i32 res0, res1; src_top = LD_UB(src - stride); add = __msa_hadd_u_h(src_top, src_top); sum = __msa_hadd_u_w(add, add); sum = (v4u32) __msa_srari_w((v4i32) sum, 2); res0 = (v4i32) __msa_splati_b((v16i8) sum, 0); res1 = (v4i32) __msa_splati_b((v16i8) sum, 4); out0 = __msa_copy_u_w(res0, 0); out1 = __msa_copy_u_w(res1, 0); for (lp_cnt = 8; lp_cnt--;) { SW(out0, src); SW(out1, src + 4); src += stride; } } static void intra_predict_mad_cow_dc_l0t_8x8_msa(uint8_t *src, int32_t stride) { uint8_t lp_cnt; uint32_t src0, src1, src2 = 0; uint32_t out0, out1, out2; v16u8 src_top; v8u16 add; v4u32 sum; src_top = LD_UB(src - stride); add = __msa_hadd_u_h(src_top, src_top); sum = __msa_hadd_u_w(add, add); src0 = __msa_copy_u_w((v4i32) sum, 0); src1 = __msa_copy_u_w((v4i32) sum, 1); for (lp_cnt = 0; lp_cnt < 4; lp_cnt++) { src2 += src[lp_cnt * stride - 1]; } src2 = (src0 + src2 + 4) >> 3; src0 = (src0 + 2) >> 2; src1 = (src1 + 2) >> 2; out0 = src0 * 0x01010101; out1 = src1 * 0x01010101; out2 = src2 * 0x01010101; for (lp_cnt = 4; lp_cnt--;) { SW(out2, src); SW(out1, src + 4); SW(out0, src + stride * 4); SW(out1, src + stride * 4 + 4); src += stride; } } static void intra_predict_mad_cow_dc_0lt_8x8_msa(uint8_t *src, int32_t stride) { uint8_t lp_cnt; uint32_t src0, src1, src2 = 0, src3; uint32_t out0, out1, out2, out3; v16u8 src_top; v8u16 add; v4u32 sum; src_top = LD_UB(src - stride); add = __msa_hadd_u_h(src_top, src_top); sum = __msa_hadd_u_w(add, add); src0 = __msa_copy_u_w((v4i32) sum, 0); src1 = __msa_copy_u_w((v4i32) sum, 1); for (lp_cnt = 0; lp_cnt < 4; lp_cnt++) { src2 += src[(4 + lp_cnt) * stride - 1]; } src0 = (src0 + 2) >> 2; src3 = (src1 + src2 + 4) >> 3; src1 = (src1 + 2) >> 2; src2 = (src2 + 2) >> 2; out0 = src0 * 0x01010101; out1 = src1 * 0x01010101; out2 = src2 * 0x01010101; out3 = src3 * 0x01010101; for (lp_cnt = 4; lp_cnt--;) { SW(out0, src); SW(out1, src + 4); SW(out2, src + stride * 4); SW(out3, src + stride * 4 + 4); src += stride; } } static void intra_predict_mad_cow_dc_l00_8x8_msa(uint8_t *src, int32_t stride) { uint8_t lp_cnt; uint32_t src0 = 0; uint64_t out0, out1; for (lp_cnt = 0; lp_cnt < 4; lp_cnt++) { src0 += src[lp_cnt * stride - 1]; } src0 = (src0 + 2) >> 2; out0 = src0 * 0x0101010101010101; out1 = 0x8080808080808080; for (lp_cnt = 4; lp_cnt--;) { SD(out0, src); SD(out1, src + stride * 4); src += stride; } } static void intra_predict_mad_cow_dc_0l0_8x8_msa(uint8_t *src, int32_t stride) { uint8_t lp_cnt; uint32_t src0 = 0; uint64_t out0, out1; for (lp_cnt = 0; lp_cnt < 4; lp_cnt++) { src0 += src[(4 + lp_cnt) * stride - 1]; } src0 = (src0 + 2) >> 2; out0 = 0x8080808080808080; out1 = src0 * 0x0101010101010101; for (lp_cnt = 4; lp_cnt--;) { SD(out0, src); SD(out1, src + stride * 4); src += stride; } } void ff_h264_intra_predict_plane_8x8_msa(uint8_t *src, ptrdiff_t stride) { intra_predict_plane_8x8_msa(src, stride); } void ff_h264_intra_predict_dc_4blk_8x8_msa(uint8_t *src, ptrdiff_t stride) { intra_predict_dc_4blk_8x8_msa(src, stride); } void ff_h264_intra_predict_hor_dc_8x8_msa(uint8_t *src, ptrdiff_t stride) { intra_predict_hor_dc_8x8_msa(src, stride); } void ff_h264_intra_predict_vert_dc_8x8_msa(uint8_t *src, ptrdiff_t stride) { intra_predict_vert_dc_8x8_msa(src, stride); } void ff_h264_intra_predict_mad_cow_dc_l0t_8x8_msa(uint8_t *src, ptrdiff_t stride) { intra_predict_mad_cow_dc_l0t_8x8_msa(src, stride); } void ff_h264_intra_predict_mad_cow_dc_0lt_8x8_msa(uint8_t *src, ptrdiff_t stride) { intra_predict_mad_cow_dc_0lt_8x8_msa(src, stride); } void ff_h264_intra_predict_mad_cow_dc_l00_8x8_msa(uint8_t *src, ptrdiff_t stride) { intra_predict_mad_cow_dc_l00_8x8_msa(src, stride); } void ff_h264_intra_predict_mad_cow_dc_0l0_8x8_msa(uint8_t *src, ptrdiff_t stride) { intra_predict_mad_cow_dc_0l0_8x8_msa(src, stride); } void ff_h264_intra_predict_plane_16x16_msa(uint8_t *src, ptrdiff_t stride) { intra_predict_plane_16x16_msa(src, stride); } void ff_h264_intra_pred_vert_8x8_msa(uint8_t *src, ptrdiff_t stride) { uint8_t *dst = src; intra_predict_vert_8x8_msa(src - stride, dst, stride); } void ff_h264_intra_pred_horiz_8x8_msa(uint8_t *src, ptrdiff_t stride) { uint8_t *dst = src; intra_predict_horiz_8x8_msa(src - 1, stride, dst, stride); } void ff_h264_intra_pred_dc_16x16_msa(uint8_t *src, ptrdiff_t stride) { uint8_t *src_top = src - stride; uint8_t *src_left = src - 1; uint8_t *dst = src; intra_predict_dc_16x16_msa(src_top, src_left, stride, dst, stride, 1, 1); } void ff_h264_intra_pred_vert_16x16_msa(uint8_t *src, ptrdiff_t stride) { uint8_t *dst = src; intra_predict_vert_16x16_msa(src - stride, dst, stride); } void ff_h264_intra_pred_horiz_16x16_msa(uint8_t *src, ptrdiff_t stride) { uint8_t *dst = src; intra_predict_horiz_16x16_msa(src - 1, stride, dst, stride); } void ff_h264_intra_pred_dc_left_16x16_msa(uint8_t *src, ptrdiff_t stride) { uint8_t *src_top = src - stride; uint8_t *src_left = src - 1; uint8_t *dst = src; intra_predict_dc_16x16_msa(src_top, src_left, stride, dst, stride, 0, 1); } void ff_h264_intra_pred_dc_top_16x16_msa(uint8_t *src, ptrdiff_t stride) { uint8_t *src_top = src - stride; uint8_t *src_left = src - 1; uint8_t *dst = src; intra_predict_dc_16x16_msa(src_top, src_left, stride, dst, stride, 1, 0); } void ff_h264_intra_pred_dc_128_8x8_msa(uint8_t *src, ptrdiff_t stride) { uint8_t *src_top = src - stride; uint8_t *src_left = src - 1; uint8_t *dst = src; intra_predict_dc_8x8_msa(src_top, src_left, stride, dst, stride, 0, 0); } void ff_h264_intra_pred_dc_128_16x16_msa(uint8_t *src, ptrdiff_t stride) { uint8_t *src_top = src - stride; uint8_t *src_left = src - 1; uint8_t *dst = src; intra_predict_dc_16x16_msa(src_top, src_left, stride, dst, stride, 0, 0); } void ff_vp8_pred8x8_127_dc_8_msa(uint8_t *src, ptrdiff_t stride) { intra_predict_127dc_8x8_msa(src, stride); } void ff_vp8_pred8x8_129_dc_8_msa(uint8_t *src, ptrdiff_t stride) { intra_predict_129dc_8x8_msa(src, stride); } void ff_vp8_pred16x16_127_dc_8_msa(uint8_t *src, ptrdiff_t stride) { intra_predict_127dc_16x16_msa(src, stride); } void ff_vp8_pred16x16_129_dc_8_msa(uint8_t *src, ptrdiff_t stride) { intra_predict_129dc_16x16_msa(src, stride); }
12,410
938
{ "title": "Armor Upgrades", "text": [ { "text": "Armor upgrades provide ways to modify your jump, speed, and other such factors." } ] }
49
14,668
// Copyright 2017 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 "components/payments/content/android/currency_formatter_android.h" #include <memory> #include <string> #include "base/android/jni_string.h" #include "components/payments/content/android/jni_headers/CurrencyFormatter_jni.h" #include "components/payments/core/currency_formatter.h" namespace payments { namespace { using ::base::android::JavaParamRef; using ::base::android::ConvertJavaStringToUTF8; } // namespace CurrencyFormatterAndroid::CurrencyFormatterAndroid( JNIEnv* env, jobject jcaller, const JavaParamRef<jstring>& currency_code, const JavaParamRef<jstring>& locale_name) { currency_formatter_ = std::make_unique<CurrencyFormatter>( ConvertJavaStringToUTF8(env, currency_code), ConvertJavaStringToUTF8(env, locale_name)); } CurrencyFormatterAndroid::~CurrencyFormatterAndroid() {} void CurrencyFormatterAndroid::Destroy(JNIEnv* env, const JavaParamRef<jobject>& jcaller) { delete this; } void CurrencyFormatterAndroid::SetMaxFractionalDigits( JNIEnv* env, jint jmax_fractional_digits) { currency_formatter_->SetMaxFractionalDigits(jmax_fractional_digits); } base::android::ScopedJavaLocalRef<jstring> CurrencyFormatterAndroid::Format( JNIEnv* env, const JavaParamRef<jobject>& jcaller, const JavaParamRef<jstring>& amount) { std::u16string result = currency_formatter_->Format(ConvertJavaStringToUTF8(env, amount)); return base::android::ConvertUTF16ToJavaString(env, result); } base::android::ScopedJavaLocalRef<jstring> CurrencyFormatterAndroid::GetFormattedCurrencyCode( JNIEnv* env, const JavaParamRef<jobject>& unused_obj) { return base::android::ConvertUTF8ToJavaString( env, currency_formatter_->formatted_currency_code()); } static jlong JNI_CurrencyFormatter_InitCurrencyFormatterAndroid( JNIEnv* env, const JavaParamRef<jobject>& obj, const JavaParamRef<jstring>& currency_code, const JavaParamRef<jstring>& locale_name) { CurrencyFormatterAndroid* currency_formatter_android = new CurrencyFormatterAndroid(env, obj, currency_code, locale_name); return reinterpret_cast<intptr_t>(currency_formatter_android); } } // namespace payments
845
341
<gh_stars>100-1000 package admintravel.entity; import lombok.Data; import lombok.NoArgsConstructor; /** * @author fdse */ @Data @NoArgsConstructor public class AdminTrip { private Trip trip; private TrainType trainType; private Route route; }
93
679
<filename>main/svx/source/sdr/contact/viewcontactofgraphic.cxx /************************************************************** * * 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. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svx.hxx" #include <svx/sdr/contact/viewcontactofgraphic.hxx> #include <svx/sdr/contact/viewobjectcontactofgraphic.hxx> #include <svx/svdograf.hxx> #include <svx/sdr/primitive2d/sdrattributecreator.hxx> #include <svl/itemset.hxx> #ifndef ITEMID_GRF_CROP #define ITEMID_GRF_CROP 0 #endif #include <svx/sdgcpitm.hxx> #include <svx/sdr/contact/displayinfo.hxx> #include <svx/sdr/contact/viewobjectcontact.hxx> #include <svx/sdr/contact/objectcontact.hxx> #include <svx/sdr/event/eventhandler.hxx> #include <basegfx/matrix/b2dhommatrix.hxx> #include <svx/sdr/primitive2d/sdrgrafprimitive2d.hxx> #include "svx/svdstr.hrc" #include <svx/svdglob.hxx> #include <vcl/svapp.hxx> #include <basegfx/polygon/b2dpolygontools.hxx> #include <drawinglayer/primitive2d/polygonprimitive2d.hxx> #include <drawinglayer/primitive2d/bitmapprimitive2d.hxx> #include <drawinglayer/primitive2d/textprimitive2d.hxx> #include <drawinglayer/primitive2d/textlayoutdevice.hxx> #include <drawinglayer/primitive2d/maskprimitive2d.hxx> #include <svx/sdr/primitive2d/sdrtextprimitive2d.hxx> #include <editeng/eeitem.hxx> #include <editeng/colritem.hxx> #include <basegfx/matrix/b2dhommatrixtools.hxx> #include <drawinglayer/primitive2d/sdrdecompositiontools2d.hxx> ////////////////////////////////////////////////////////////////////////////// namespace sdr { namespace contact { // Create a Object-Specific ViewObjectContact, set ViewContact and // ObjectContact. Always needs to return something. ViewObjectContact& ViewContactOfGraphic::CreateObjectSpecificViewObjectContact(ObjectContact& rObjectContact) { ViewObjectContact* pRetval = new ViewObjectContactOfGraphic(rObjectContact, *this); DBG_ASSERT(pRetval, "ViewContact::CreateObjectSpecificViewObjectContact() failed (!)"); return *pRetval; } ViewContactOfGraphic::ViewContactOfGraphic(SdrGrafObj& rGrafObj) : ViewContactOfTextObj(rGrafObj) { } ViewContactOfGraphic::~ViewContactOfGraphic() { } void ViewContactOfGraphic::flushGraphicObjects() { // #i102380# The graphic is swapped out. To let that have an effect ist is necessary to // delete copies of the GraphicObject which are not swapped out and have no SwapHandler set // (this is what happnes when the GraphicObject gets copied to a SdrGrafPrimitive2D). This // is best achieved for the VC by clearing the local decomposition cache. It would be possible // to also do this for the VOC cache, but that VOCs exist exactly expresss that the object // gets visualised, so this would be wrong. flushViewIndependentPrimitive2DSequence(); } drawinglayer::primitive2d::Primitive2DSequence ViewContactOfGraphic::createVIP2DSForPresObj( const basegfx::B2DHomMatrix& rObjectMatrix, const drawinglayer::attribute::SdrLineFillShadowTextAttribute& rAttribute) const { drawinglayer::primitive2d::Primitive2DSequence xRetval; GraphicObject aEmptyGraphicObject; GraphicAttr aEmptyGraphicAttr; // SdrGrafPrimitive2D without content in original size which carries all eventual attributes and texts const drawinglayer::primitive2d::Primitive2DReference xReferenceA(new drawinglayer::primitive2d::SdrGrafPrimitive2D( rObjectMatrix, rAttribute, aEmptyGraphicObject, aEmptyGraphicAttr)); xRetval = drawinglayer::primitive2d::Primitive2DSequence(&xReferenceA, 1); // SdrGrafPrimitive2D with content (which is the preview graphic) scaled to smaller size and // without attributes basegfx::B2DHomMatrix aSmallerMatrix; // #i94431# for some reason, i forgot to take the PrefMapMode of the graphic // into account. Since EmptyPresObj's are only used in Draw/Impress, it is // safe to assume 100th mm as target. Size aPrefSize(GetGrafObject().GetGrafPrefSize()); if(MAP_PIXEL == GetGrafObject().GetGrafPrefMapMode().GetMapUnit()) { aPrefSize = Application::GetDefaultDevice()->PixelToLogic(aPrefSize, MAP_100TH_MM); } else { aPrefSize = Application::GetDefaultDevice()->LogicToLogic(aPrefSize, GetGrafObject().GetGrafPrefMapMode(), MAP_100TH_MM); } // decompose object matrix to get single values basegfx::B2DVector aScale, aTranslate; double fRotate, fShearX; rObjectMatrix.decompose(aScale, aTranslate, fRotate, fShearX); const double fOffsetX((aScale.getX() - aPrefSize.getWidth()) / 2.0); const double fOffsetY((aScale.getY() - aPrefSize.getHeight()) / 2.0); if(basegfx::fTools::moreOrEqual(fOffsetX, 0.0) && basegfx::fTools::moreOrEqual(fOffsetY, 0.0)) { // create the EmptyPresObj fallback visualisation. The fallback graphic // is already provided in rGraphicObject in this case, use it aSmallerMatrix = basegfx::tools::createScaleTranslateB2DHomMatrix(aPrefSize.getWidth(), aPrefSize.getHeight(), fOffsetX, fOffsetY); aSmallerMatrix = basegfx::tools::createShearXRotateTranslateB2DHomMatrix(fShearX, fRotate, aTranslate) * aSmallerMatrix; const GraphicObject& rGraphicObject = GetGrafObject().GetGraphicObject(false); const GraphicAttr aLocalGrafInfo; const drawinglayer::primitive2d::Primitive2DReference xReferenceB(new drawinglayer::primitive2d::SdrGrafPrimitive2D( aSmallerMatrix, drawinglayer::attribute::SdrLineFillShadowTextAttribute(), rGraphicObject, aLocalGrafInfo)); drawinglayer::primitive2d::appendPrimitive2DReferenceToPrimitive2DSequence(xRetval, xReferenceB); } return xRetval; } drawinglayer::primitive2d::Primitive2DSequence ViewContactOfGraphic::createVIP2DSForDraft( const basegfx::B2DHomMatrix& rObjectMatrix, const drawinglayer::attribute::SdrLineFillShadowTextAttribute& rAttribute) const { drawinglayer::primitive2d::Primitive2DSequence xRetval; GraphicObject aEmptyGraphicObject; GraphicAttr aEmptyGraphicAttr; // SdrGrafPrimitive2D without content in original size which carries all eventual attributes and texts const drawinglayer::primitive2d::Primitive2DReference xReferenceA(new drawinglayer::primitive2d::SdrGrafPrimitive2D( rObjectMatrix, rAttribute, aEmptyGraphicObject, aEmptyGraphicAttr)); xRetval = drawinglayer::primitive2d::Primitive2DSequence(&xReferenceA, 1); if(rAttribute.getLine().isDefault()) { // create a surrounding frame when no linestyle given const Color aColor(Application::GetSettings().GetStyleSettings().GetShadowColor()); const basegfx::BColor aBColor(aColor.getBColor()); basegfx::B2DPolygon aOutline(basegfx::tools::createUnitPolygon()); aOutline.transform(rObjectMatrix); drawinglayer::primitive2d::appendPrimitive2DReferenceToPrimitive2DSequence(xRetval, drawinglayer::primitive2d::Primitive2DReference( new drawinglayer::primitive2d::PolygonHairlinePrimitive2D( aOutline, aBColor))); } // decompose object matrix to get single values basegfx::B2DVector aScale, aTranslate; double fRotate, fShearX; rObjectMatrix.decompose(aScale, aTranslate, fRotate, fShearX); // define a distance value, used for distance from bitmap to borders and from bitmap // to text, too (2 mm) const double fDistance(200.0); // consume borders from values aScale.setX(std::max(0.0, aScale.getX() - (2.0 * fDistance))); aScale.setY(std::max(0.0, aScale.getY() - (2.0 * fDistance))); aTranslate.setX(aTranslate.getX() + fDistance); aTranslate.setY(aTranslate.getY() + fDistance); // draw a draft bitmap const Bitmap aDraftBitmap(ResId(BMAP_GrafikEi, *ImpGetResMgr())); if(!aDraftBitmap.IsEmpty()) { Size aPrefSize(aDraftBitmap.GetPrefSize()); if(MAP_PIXEL == aDraftBitmap.GetPrefMapMode().GetMapUnit()) { aPrefSize = Application::GetDefaultDevice()->PixelToLogic(aDraftBitmap.GetSizePixel(), MAP_100TH_MM); } else { aPrefSize = Application::GetDefaultDevice()->LogicToLogic(aPrefSize, aDraftBitmap.GetPrefMapMode(), MAP_100TH_MM); } const double fBitmapScaling(2.0); const double fWidth(aPrefSize.getWidth() * fBitmapScaling); const double fHeight(aPrefSize.getHeight() * fBitmapScaling); if(basegfx::fTools::more(fWidth, 1.0) && basegfx::fTools::more(fHeight, 1.0) && basegfx::fTools::lessOrEqual(fWidth, aScale.getX()) && basegfx::fTools::lessOrEqual(fHeight, aScale.getY())) { const basegfx::B2DHomMatrix aBitmapMatrix(basegfx::tools::createScaleShearXRotateTranslateB2DHomMatrix( fWidth, fHeight, fShearX, fRotate, aTranslate.getX(), aTranslate.getY())); drawinglayer::primitive2d::appendPrimitive2DReferenceToPrimitive2DSequence(xRetval, drawinglayer::primitive2d::Primitive2DReference( new drawinglayer::primitive2d::BitmapPrimitive2D( BitmapEx(aDraftBitmap), aBitmapMatrix))); // consume bitmap size in X aScale.setX(std::max(0.0, aScale.getX() - (fWidth + fDistance))); aTranslate.setX(aTranslate.getX() + fWidth + fDistance); } } // Build the text for the draft object XubString aDraftText = GetGrafObject().GetFileName(); if(!aDraftText.Len()) { aDraftText = GetGrafObject().GetName(); aDraftText.AppendAscii(" ..."); } if(aDraftText.Len() && GetGrafObject().GetModel()) { // #i103255# Goal is to produce TextPrimitives which hold the given text as // BlockText in the available space. It would be very tricky to do // an own word wrap/line layout here. // Using SdrBlockTextPrimitive2D OTOH is critical since it internally // uses the SdrObject it references. To solve this, create a temp // SdrObject with Attributes and Text, generate a SdrBlockTextPrimitive2D // directly and immediately decompose it. After that, it is no longer // needed and can be deleted. // create temp RectObj as TextObj and set needed attributes SdrRectObj aRectObj(OBJ_TEXT); aRectObj.SetModel(GetGrafObject().GetModel()); aRectObj.NbcSetText(aDraftText); aRectObj.SetMergedItem(SvxColorItem(Color(COL_LIGHTRED), EE_CHAR_COLOR)); // get SdrText and OPO SdrText* pSdrText = aRectObj.getText(0); OutlinerParaObject* pOPO = aRectObj.GetOutlinerParaObject(); if(pSdrText && pOPO) { // directly use the remaining space as TextRangeTransform const basegfx::B2DHomMatrix aTextRangeTransform(basegfx::tools::createScaleShearXRotateTranslateB2DHomMatrix( aScale, fShearX, fRotate, aTranslate)); // directly create temp SdrBlockTextPrimitive2D drawinglayer::primitive2d::SdrBlockTextPrimitive2D aBlockTextPrimitive( pSdrText, *pOPO, aTextRangeTransform, SDRTEXTHORZADJUST_LEFT, SDRTEXTVERTADJUST_TOP, false, false, false, false, false); // decompose immediately with neutral ViewInformation. This will // layout the text to more simple TextPrimitives from drawinglayer const drawinglayer::geometry::ViewInformation2D aViewInformation2D; drawinglayer::primitive2d::appendPrimitive2DSequenceToPrimitive2DSequence( xRetval, aBlockTextPrimitive.get2DDecomposition(aViewInformation2D)); } } return xRetval; } drawinglayer::primitive2d::Primitive2DSequence ViewContactOfGraphic::createViewIndependentPrimitive2DSequence() const { drawinglayer::primitive2d::Primitive2DSequence xRetval; const SfxItemSet& rItemSet = GetGrafObject().GetMergedItemSet(); // create and fill GraphicAttr GraphicAttr aLocalGrafInfo; const sal_uInt16 nTrans(((SdrGrafTransparenceItem&)rItemSet.Get(SDRATTR_GRAFTRANSPARENCE)).GetValue()); const SdrGrafCropItem& rCrop((const SdrGrafCropItem&)rItemSet.Get(SDRATTR_GRAFCROP)); aLocalGrafInfo.SetLuminance(((SdrGrafLuminanceItem&)rItemSet.Get(SDRATTR_GRAFLUMINANCE)).GetValue()); aLocalGrafInfo.SetContrast(((SdrGrafContrastItem&)rItemSet.Get(SDRATTR_GRAFCONTRAST)).GetValue()); aLocalGrafInfo.SetChannelR(((SdrGrafRedItem&)rItemSet.Get(SDRATTR_GRAFRED)).GetValue()); aLocalGrafInfo.SetChannelG(((SdrGrafGreenItem&)rItemSet.Get(SDRATTR_GRAFGREEN)).GetValue()); aLocalGrafInfo.SetChannelB(((SdrGrafBlueItem&)rItemSet.Get(SDRATTR_GRAFBLUE)).GetValue()); aLocalGrafInfo.SetGamma(((SdrGrafGamma100Item&)rItemSet.Get(SDRATTR_GRAFGAMMA)).GetValue() * 0.01); aLocalGrafInfo.SetTransparency((sal_uInt8)::basegfx::fround(Min(nTrans, (sal_uInt16)100) * 2.55)); aLocalGrafInfo.SetInvert(((SdrGrafInvertItem&)rItemSet.Get(SDRATTR_GRAFINVERT)).GetValue()); aLocalGrafInfo.SetDrawMode(((SdrGrafModeItem&)rItemSet.Get(SDRATTR_GRAFMODE)).GetValue()); aLocalGrafInfo.SetCrop(rCrop.GetLeft(), rCrop.GetTop(), rCrop.GetRight(), rCrop.GetBottom()); // we have content if graphic is not completely transparent const bool bHasContent(255L != aLocalGrafInfo.GetTransparency()); drawinglayer::attribute::SdrLineFillShadowTextAttribute aAttribute( drawinglayer::primitive2d::createNewSdrLineFillShadowTextAttribute( rItemSet, GetGrafObject().getText(0), bHasContent)); // take unrotated snap rect for position and size. Directly use model data, not getBoundRect() or getSnapRect() // which will use the primitive data we just create in the near future const Rectangle& rRectangle = GetGrafObject().GetGeoRect(); const ::basegfx::B2DRange aObjectRange( rRectangle.Left(), rRectangle.Top(), rRectangle.Right(), rRectangle.Bottom()); // look for mirroring const GeoStat& rGeoStat(GetGrafObject().GetGeoStat()); const sal_Int32 nDrehWink(rGeoStat.nDrehWink); const bool bRota180(18000 == nDrehWink); const bool bMirrored(GetGrafObject().IsMirrored()); const sal_uInt16 nMirrorCase(bRota180 ? (bMirrored ? 3 : 4) : (bMirrored ? 2 : 1)); bool bHMirr((2 == nMirrorCase ) || (4 == nMirrorCase)); bool bVMirr((3 == nMirrorCase ) || (4 == nMirrorCase)); // set mirror flags at LocalGrafInfo. Take into account that the geometry in // aObjectRange is already changed and rotated when bRota180 is used. To rebuild // that old behaviour (as long as part of the model data), correct the H/V flags // accordingly. The created bitmapPrimitive WILL use the rotation, too. if(bRota180) { // if bRota180 which is used for vertical mirroring, the graphic will already be rotated // by 180 degrees. To correct, switch off VMirror and invert HMirroring. bHMirr = !bHMirr; bVMirr = false; } if(bHMirr || bVMirr) { aLocalGrafInfo.SetMirrorFlags((bHMirr ? BMP_MIRROR_HORZ : 0)|(bVMirr ? BMP_MIRROR_VERT : 0)); } // fill object matrix const double fShearX(rGeoStat.nShearWink ? tan((36000 - rGeoStat.nShearWink) * F_PI18000) : 0.0); const double fRotate(nDrehWink ? (36000 - nDrehWink) * F_PI18000 : 0.0); const basegfx::B2DHomMatrix aObjectMatrix(basegfx::tools::createScaleShearXRotateTranslateB2DHomMatrix( aObjectRange.getWidth(), aObjectRange.getHeight(), fShearX, fRotate, aObjectRange.getMinX(), aObjectRange.getMinY())); // get the current, unchenged graphic obect from SdrGrafObj const GraphicObject& rGraphicObject = GetGrafObject().GetGraphicObject(false); if(visualisationUsesPresObj()) { // it's an EmptyPresObj, create the SdrGrafPrimitive2D without content and another scaled one // with the content which is the placeholder graphic xRetval = createVIP2DSForPresObj(aObjectMatrix, aAttribute); } else if(visualisationUsesDraft()) { // #i102380# The graphic is swapped out. To not force a swap-in here, there is a mechanism // which shows a swapped-out-visualisation (which gets created here now) and an asynchronious // visual update mechanism for swapped-out grapgics when they were loaded (see AsynchGraphicLoadingEvent // and ViewObjectContactOfGraphic implementation). Not forcing the swap-in here allows faster // (non-blocking) processing here and thus in the effect e.g. fast scrolling through pages xRetval = createVIP2DSForDraft(aObjectMatrix, aAttribute); } else { // create primitive. Info: Calling the copy-constructor of GraphicObject in this // SdrGrafPrimitive2D constructor will force a full swap-in of the graphic const drawinglayer::primitive2d::Primitive2DReference xReference( new drawinglayer::primitive2d::SdrGrafPrimitive2D( aObjectMatrix, aAttribute, rGraphicObject, aLocalGrafInfo)); xRetval = drawinglayer::primitive2d::Primitive2DSequence(&xReference, 1); } // always append an invisible outline for the cases where no visible content exists drawinglayer::primitive2d::appendPrimitive2DReferenceToPrimitive2DSequence(xRetval, drawinglayer::primitive2d::createHiddenGeometryPrimitives2D( false, aObjectMatrix)); return xRetval; } bool ViewContactOfGraphic::visualisationUsesPresObj() const { return GetGrafObject().IsEmptyPresObj(); } bool ViewContactOfGraphic::visualisationUsesDraft() const { // no draft when already PresObj if(visualisationUsesPresObj()) return false; // draft when swapped out const GraphicObject& rGraphicObject = GetGrafObject().GetGraphicObject(false); static bool bAllowReplacements(true); if(rGraphicObject.IsSwappedOut() && bAllowReplacements) return true; // draft when no graphic if(GRAPHIC_NONE == rGraphicObject.GetType() || GRAPHIC_DEFAULT == rGraphicObject.GetType()) return true; return false; } } // end of namespace contact } // end of namespace sdr ////////////////////////////////////////////////////////////////////////////// // eof
8,321
764
<gh_stars>100-1000 /* Copyright 2019 DeepMind Technologies Limited. 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 "tree.h" #include <memory> #include <string> #include <unordered_map> // logging #include "absl/memory/memory.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include <pybind11/pybind11.h> #ifdef LOG #define LOG_WARNING(w) LOG(WARNING) << w; #else #include <iostream> #define LOG_WARNING(w) std::cerr << w << "\n"; #endif #ifndef DCHECK #define DCHECK(stmt) #endif namespace py = pybind11; namespace tree { namespace { // PyObjectPtr wraps an underlying Python object and decrements the // reference count in the destructor. // // This class does not acquire the GIL in the destructor, so the GIL must be // held when the destructor is called. using PyObjectPtr = std::unique_ptr<PyObject, DecrementsPyRefcount>; const int kMaxItemsInCache = 1024; bool WarnedThatSetIsNotSequence = false; bool IsString(PyObject* o) { return PyBytes_Check(o) || PyByteArray_Check(o) || PyUnicode_Check(o); } // Equivalent to Python's 'o.__class__.__name__' // Note that '__class__' attribute is set only in new-style classes. // A lot of tensorflow code uses __class__ without checks, so it seems like // we only support new-style classes. absl::string_view GetClassName(PyObject* o) { // __class__ is equivalent to type() for new style classes. // type() is equivalent to PyObject_Type() // (https://docs.python.org/3.5/c-api/object.html#c.PyObject_Type) // PyObject_Type() is equivalent to o->ob_type except for Py_INCREF, which // we don't need here. PyTypeObject* type = o->ob_type; // __name__ is the value of `tp_name` after the last '.' // (https://docs.python.org/2/c-api/typeobj.html#c.PyTypeObject.tp_name) absl::string_view name(type->tp_name); size_t pos = name.rfind('.'); if (pos != absl::string_view::npos) { name.remove_prefix(pos + 1); } return name; } std::string PyObjectToString(PyObject* o) { if (o == nullptr) { return "<null object>"; } PyObject* str = PyObject_Str(o); if (str) { std::string s(PyUnicode_AsUTF8(str)); Py_DECREF(str); return absl::StrCat("type=", GetClassName(o), " str=", s); } else { return "<failed to execute str() on object>"; } } class CachedTypeCheck { public: explicit CachedTypeCheck(std::function<int(PyObject*)> ternary_predicate) : ternary_predicate_(std::move(ternary_predicate)) {} ~CachedTypeCheck() { for (const auto& pair : type_to_sequence_map_) { Py_DECREF(pair.first); } } // Caches successful executions of the one-argument (PyObject*) callable // "ternary_predicate" based on the type of "o". -1 from the callable // indicates an unsuccessful check (not cached), 0 indicates that "o"'s type // does not match the predicate, and 1 indicates that it does. Used to avoid // calling back into Python for expensive isinstance checks. int CachedLookup(PyObject* o) { // Try not to return to Python - see if the type has already been seen // before. auto* type = Py_TYPE(o); { auto it = type_to_sequence_map_.find(type); if (it != type_to_sequence_map_.end()) { return it->second; } } int check_result = ternary_predicate_(o); if (check_result == -1) { return -1; // Type check error, not cached. } // NOTE: This is never decref'd as long as the object lives, which is likely // forever, but we don't want the type to get deleted as long as it is in // the map. This should not be too much of a leak, as there should only be a // relatively small number of types in the map, and an even smaller number // that are eligible for decref. As a precaution, we limit the size of the // map to 1024. { if (type_to_sequence_map_.size() < kMaxItemsInCache) { Py_INCREF(type); type_to_sequence_map_.insert({type, check_result}); } } return check_result; } private: std::function<int(PyObject*)> ternary_predicate_; std::unordered_map<PyTypeObject*, bool> type_to_sequence_map_; }; py::object GetCollectionsSequenceType() { static py::object type = py::module::import("collections.abc").attr("Sequence"); return type; } py::object GetCollectionsMappingType() { static py::object type = py::module::import("collections.abc").attr("Mapping"); return type; } py::object GetCollectionsMappingViewType() { static py::object type = py::module::import("collections.abc").attr("MappingView"); return type; } py::object GetWraptObjectProxyTypeUncached() { try { return py::module::import("wrapt").attr("ObjectProxy"); } catch (const py::error_already_set& e) { if (e.matches(PyExc_ImportError)) return py::none(); throw e; } } py::object GetWraptObjectProxyType() { // TODO(gregthornton): Restore caching when deadlock issue is fixed. return GetWraptObjectProxyTypeUncached(); } // Returns 1 if `o` is considered a mapping for the purposes of Flatten(). // Returns 0 otherwise. // Returns -1 if an error occurred. int IsMappingHelper(PyObject* o) { static auto* const check_cache = new CachedTypeCheck([](PyObject* to_check) { return PyObject_IsInstance(to_check, GetCollectionsMappingType().ptr()); }); if (PyDict_Check(o)) return true; return check_cache->CachedLookup(o); } // Returns 1 if `o` is considered a mapping view for the purposes of Flatten(). // Returns 0 otherwise. // Returns -1 if an error occurred. int IsMappingViewHelper(PyObject* o) { static auto* const check_cache = new CachedTypeCheck([](PyObject* to_check) { return PyObject_IsInstance(to_check, GetCollectionsMappingViewType().ptr()); }); return check_cache->CachedLookup(o); } // Returns 1 if `o` is considered an object proxy // Returns 0 otherwise. // Returns -1 if an error occurred. int IsObjectProxy(PyObject* o) { static auto* const check_cache = new CachedTypeCheck([](PyObject* to_check) { auto type = GetWraptObjectProxyType(); return !type.is_none() && PyObject_IsInstance(to_check, type.ptr()) == 1; }); return check_cache->CachedLookup(o); } // Returns 1 if `o` is an instance of attrs-decorated class. // Returns 0 otherwise. int IsAttrsHelper(PyObject* o) { static auto* const check_cache = new CachedTypeCheck([](PyObject* to_check) { PyObjectPtr cls(PyObject_GetAttrString(to_check, "__class__")); if (cls) { return PyObject_HasAttrString(cls.get(), "__attrs_attrs__"); } // PyObject_GetAttrString returns null on error PyErr_Clear(); return 0; }); return check_cache->CachedLookup(o); } // Returns 1 if `o` is considered a sequence for the purposes of Flatten(). // Returns 0 otherwise. // Returns -1 if an error occurred. int IsSequenceHelper(PyObject* o) { static auto* const check_cache = new CachedTypeCheck([](PyObject* to_check) { int is_instance = PyObject_IsInstance(to_check, GetCollectionsSequenceType().ptr()); // Don't cache a failed is_instance check. if (is_instance == -1) return -1; return static_cast<int>(is_instance != 0 && !IsString(to_check)); }); // We treat dicts and other mappings as special cases of sequences. if (IsMappingHelper(o)) return true; if (IsMappingViewHelper(o)) return true; if (IsAttrsHelper(o)) return true; if (PySet_Check(o) && !WarnedThatSetIsNotSequence) { LOG_WARNING( "Sets are not currently considered sequences, " "but this may change in the future, " "so consider avoiding using them."); WarnedThatSetIsNotSequence = true; } return check_cache->CachedLookup(o); } using ValueIteratorPtr = std::unique_ptr<ValueIterator>; // Iterate through dictionaries in a deterministic order by sorting the // keys. Notice this means that we ignore the original order of // `OrderedDict` instances. This is intentional, to avoid potential // bugs caused by mixing ordered and plain dicts (e.g., flattening // a dict but using a corresponding `OrderedDict` to pack it back). class DictValueIterator : public ValueIterator { public: explicit DictValueIterator(PyObject* dict) : dict_(dict), keys_(PyDict_Keys(dict)) { if (PyList_Sort(keys_.get()) == -1) { invalidate(); } else { iter_.reset(PyObject_GetIter(keys_.get())); } } PyObjectPtr next() override { PyObjectPtr result; PyObjectPtr key(PyIter_Next(iter_.get())); if (key) { // PyDict_GetItem returns a borrowed reference. PyObject* elem = PyDict_GetItem(dict_, key.get()); if (elem) { Py_INCREF(elem); result.reset(elem); } else { PyErr_SetString(PyExc_RuntimeError, "Dictionary was modified during iteration over it"); } } return result; } private: PyObject* dict_; PyObjectPtr keys_; PyObjectPtr iter_; }; // Iterate over mapping objects by sorting the keys first class MappingValueIterator : public ValueIterator { public: explicit MappingValueIterator(PyObject* mapping) : mapping_(mapping), keys_(PyMapping_Keys(mapping)) { if (!keys_ || PyList_Sort(keys_.get()) == -1) { invalidate(); } else { iter_.reset(PyObject_GetIter(keys_.get())); } } PyObjectPtr next() override { PyObjectPtr result; PyObjectPtr key(PyIter_Next(iter_.get())); if (key) { // Unlike PyDict_GetItem, PyObject_GetItem returns a new reference. PyObject* elem = PyObject_GetItem(mapping_, key.get()); if (elem) { result.reset(elem); } else { PyErr_SetString(PyExc_RuntimeError, "Mapping was modified during iteration over it"); } } return result; } private: PyObject* mapping_; PyObjectPtr keys_; PyObjectPtr iter_; }; // Iterate over a sequence, by index. class SequenceValueIterator : public ValueIterator { public: explicit SequenceValueIterator(PyObject* iterable) : seq_(PySequence_Fast(iterable, "")), size_(seq_.get() ? PySequence_Fast_GET_SIZE(seq_.get()) : 0), index_(0) {} PyObjectPtr next() override { PyObjectPtr result; if (index_ < size_) { // PySequence_Fast_GET_ITEM returns a borrowed reference. PyObject* elem = PySequence_Fast_GET_ITEM(seq_.get(), index_); ++index_; if (elem) { Py_INCREF(elem); result.reset(elem); } } return result; } private: PyObjectPtr seq_; const Py_ssize_t size_; Py_ssize_t index_; }; class AttrsValueIterator : public ValueIterator { public: explicit AttrsValueIterator(PyObject* nested) : nested_(nested) { Py_INCREF(nested); cls_.reset(PyObject_GetAttrString(nested_.get(), "__class__")); if (cls_) { attrs_.reset(PyObject_GetAttrString(cls_.get(), "__attrs_attrs__")); if (attrs_) { iter_.reset(PyObject_GetIter(attrs_.get())); } } if (!iter_ || PyErr_Occurred()) invalidate(); } PyObjectPtr next() override { PyObjectPtr result; PyObjectPtr item(PyIter_Next(iter_.get())); if (item) { PyObjectPtr name(PyObject_GetAttrString(item.get(), "name")); result.reset(PyObject_GetAttr(nested_.get(), name.get())); } return result; } private: PyObjectPtr nested_; PyObjectPtr cls_; PyObjectPtr attrs_; PyObjectPtr iter_; }; bool FlattenHelper( PyObject* nested, PyObject* list, const std::function<int(PyObject*)>& is_sequence_helper, const std::function<ValueIteratorPtr(PyObject*)>& value_iterator_getter) { // if nested is not a sequence, append itself and exit int is_seq = is_sequence_helper(nested); if (is_seq == -1) return false; if (!is_seq) { return PyList_Append(list, nested) != -1; } ValueIteratorPtr iter = value_iterator_getter(nested); if (!iter->valid()) return false; for (PyObjectPtr item = iter->next(); item; item = iter->next()) { if (Py_EnterRecursiveCall(" in flatten")) { return false; } const bool success = FlattenHelper(item.get(), list, is_sequence_helper, value_iterator_getter); Py_LeaveRecursiveCall(); if (!success) { return false; } } return true; } // Sets error using keys of 'dict1' and 'dict2'. // 'dict1' and 'dict2' are assumed to be Python dictionaries. void SetDifferentKeysError(PyObject* dict1, PyObject* dict2, std::string* error_msg, bool* is_type_error) { PyObjectPtr k1(PyMapping_Keys(dict1)); if (PyErr_Occurred() || k1.get() == nullptr) { *error_msg = ("The two dictionaries don't have the same set of keys. Failed to " "fetch keys."); return; } PyObjectPtr k2(PyMapping_Keys(dict2)); if (PyErr_Occurred() || k2.get() == nullptr) { *error_msg = ("The two dictionaries don't have the same set of keys. Failed to " "fetch keys."); return; } *is_type_error = false; *error_msg = absl::StrCat( "The two dictionaries don't have the same set of keys. " "First structure has keys ", PyObjectToString(k1.get()), ", while second structure has keys ", PyObjectToString(k2.get())); } // Returns true iff there were no "internal" errors. In other words, // errors that has nothing to do with structure checking. // If an "internal" error occurred, the appropriate Python error will be // set and the caller can propage it directly to the user. // // Both `error_msg` and `is_type_error` must be non-null. `error_msg` must // be empty. // Leaves `error_msg` empty if structures matched. Else, fills `error_msg` // with appropriate error and sets `is_type_error` to true iff // the error to be raised should be TypeError. bool AssertSameStructureHelper(PyObject* o1, PyObject* o2, bool check_types, std::string* error_msg, bool* is_type_error) { DCHECK(error_msg); DCHECK(is_type_error); const bool is_seq1 = IsSequence(o1); const bool is_seq2 = IsSequence(o2); if (PyErr_Occurred()) return false; if (is_seq1 != is_seq2) { std::string seq_str = is_seq1 ? PyObjectToString(o1) : PyObjectToString(o2); std::string non_seq_str = is_seq1 ? PyObjectToString(o2) : PyObjectToString(o1); *is_type_error = false; *error_msg = absl::StrCat("Substructure \"", seq_str, "\" is a sequence, while substructure \"", non_seq_str, "\" is not"); return true; } // Got to scalars, so finished checking. Structures are the same. if (!is_seq1) return true; if (check_types) { // Unwrap wrapt.ObjectProxy if needed. PyObjectPtr o1_wrapped; if (IsObjectProxy(o1)) { o1_wrapped.reset(PyObject_GetAttrString(o1, "__wrapped__")); o1 = o1_wrapped.get(); } PyObjectPtr o2_wrapped; if (IsObjectProxy(o2)) { o2_wrapped.reset(PyObject_GetAttrString(o2, "__wrapped__")); o2 = o2_wrapped.get(); } const PyTypeObject* type1 = o1->ob_type; const PyTypeObject* type2 = o2->ob_type; // We treat two different namedtuples with identical name and fields // as having the same type. const PyObject* o1_tuple = IsNamedtuple(o1, true); if (o1_tuple == nullptr) return false; const PyObject* o2_tuple = IsNamedtuple(o2, true); if (o2_tuple == nullptr) { Py_DECREF(o1_tuple); return false; } bool both_tuples = o1_tuple == Py_True && o2_tuple == Py_True; Py_DECREF(o1_tuple); Py_DECREF(o2_tuple); if (both_tuples) { const PyObject* same_tuples = SameNamedtuples(o1, o2); if (same_tuples == nullptr) return false; bool not_same_tuples = same_tuples != Py_True; Py_DECREF(same_tuples); if (not_same_tuples) { *is_type_error = true; *error_msg = absl::StrCat( "The two namedtuples don't have the same sequence type. " "First structure ", PyObjectToString(o1), " has type ", type1->tp_name, ", while second structure ", PyObjectToString(o2), " has type ", type2->tp_name); return true; } } else if (type1 != type2 /* If both sequences are list types, don't complain. This allows one to be a list subclass (e.g. _ListWrapper used for automatic dependency tracking.) */ && !(PyList_Check(o1) && PyList_Check(o2)) /* Two mapping types will also compare equal, making _DictWrapper and dict compare equal. */ && !(IsMappingHelper(o1) && IsMappingHelper(o2))) { *is_type_error = true; *error_msg = absl::StrCat( "The two namedtuples don't have the same sequence type. " "First structure ", PyObjectToString(o1), " has type ", type1->tp_name, ", while second structure ", PyObjectToString(o2), " has type ", type2->tp_name); return true; } if (PyDict_Check(o1) && PyDict_Check(o2)) { if (PyDict_Size(o1) != PyDict_Size(o2)) { SetDifferentKeysError(o1, o2, error_msg, is_type_error); return true; } PyObject* key; Py_ssize_t pos = 0; while (PyDict_Next(o1, &pos, &key, nullptr)) { if (PyDict_GetItem(o2, key) == nullptr) { SetDifferentKeysError(o1, o2, error_msg, is_type_error); return true; } } } else if (IsMappingHelper(o1)) { // Fallback for custom mapping types. Instead of using PyDict methods // which stay in C, we call iter(o1). if (PyMapping_Size(o1) != PyMapping_Size(o2)) { SetDifferentKeysError(o1, o2, error_msg, is_type_error); return true; } PyObjectPtr iter(PyObject_GetIter(o1)); PyObject* key; while ((key = PyIter_Next(iter.get())) != nullptr) { if (!PyMapping_HasKey(o2, key)) { SetDifferentKeysError(o1, o2, error_msg, is_type_error); Py_DECREF(key); return true; } Py_DECREF(key); } } } ValueIteratorPtr iter1 = GetValueIterator(o1); ValueIteratorPtr iter2 = GetValueIterator(o2); if (!iter1->valid() || !iter2->valid()) return false; while (true) { PyObjectPtr v1 = iter1->next(); PyObjectPtr v2 = iter2->next(); if (v1 && v2) { if (Py_EnterRecursiveCall(" in assert_same_structure")) { return false; } bool no_internal_errors = AssertSameStructureHelper( v1.get(), v2.get(), check_types, error_msg, is_type_error); Py_LeaveRecursiveCall(); if (!no_internal_errors) return false; if (!error_msg->empty()) return true; } else if (!v1 && !v2) { // Done with all recursive calls. Structure matched. return true; } else { *is_type_error = false; *error_msg = absl::StrCat( "The two structures don't have the same number of elements. ", "First structure: ", PyObjectToString(o1), ". Second structure: ", PyObjectToString(o2)); return true; } } } } // namespace bool IsSequence(PyObject* o) { return IsSequenceHelper(o) == 1; } bool IsAttrs(PyObject* o) { return IsAttrsHelper(o) == 1; } PyObject* Flatten(PyObject* nested) { PyObject* list = PyList_New(0); if (FlattenHelper(nested, list, IsSequenceHelper, GetValueIterator)) { return list; } else { Py_DECREF(list); return nullptr; } } PyObject* IsNamedtuple(PyObject* o, bool strict) { // Unwrap wrapt.ObjectProxy if needed. PyObjectPtr o_wrapped; if (IsObjectProxy(o)) { o_wrapped.reset(PyObject_GetAttrString(o, "__wrapped__")); o = o_wrapped.get(); } // Must be subclass of tuple if (!PyTuple_Check(o)) { Py_RETURN_FALSE; } // If strict, o.__class__.__base__ must be tuple if (strict) { PyObject* klass = PyObject_GetAttrString(o, "__class__"); if (klass == nullptr) return nullptr; PyObject* base = PyObject_GetAttrString(klass, "__base__"); Py_DECREF(klass); if (base == nullptr) return nullptr; const PyTypeObject* base_type = reinterpret_cast<PyTypeObject*>(base); // built-in object types are singletons bool tuple_base = base_type == &PyTuple_Type; Py_DECREF(base); if (!tuple_base) { Py_RETURN_FALSE; } } // o must have attribute '_fields' and every element in // '_fields' must be a string. int has_fields = PyObject_HasAttrString(o, "_fields"); if (!has_fields) { Py_RETURN_FALSE; } PyObjectPtr fields(PyObject_GetAttrString(o, "_fields")); int is_instance = PyObject_IsInstance(fields.get(), GetCollectionsSequenceType().ptr()); if (is_instance == 0) { Py_RETURN_FALSE; } else if (is_instance == -1) { return nullptr; } PyObjectPtr seq(PySequence_Fast(fields.get(), "")); const Py_ssize_t s = PySequence_Fast_GET_SIZE(seq.get()); for (Py_ssize_t i = 0; i < s; ++i) { // PySequence_Fast_GET_ITEM returns borrowed ref PyObject* elem = PySequence_Fast_GET_ITEM(seq.get(), i); if (!IsString(elem)) { Py_RETURN_FALSE; } } Py_RETURN_TRUE; } PyObject* SameNamedtuples(PyObject* o1, PyObject* o2) { PyObject* f1 = PyObject_GetAttrString(o1, "_fields"); PyObject* f2 = PyObject_GetAttrString(o2, "_fields"); if (f1 == nullptr || f2 == nullptr) { Py_XDECREF(f1); Py_XDECREF(f2); PyErr_SetString( PyExc_RuntimeError, "Expected namedtuple-like objects (that have _fields attr)"); return nullptr; } if (PyObject_RichCompareBool(f1, f2, Py_NE)) { Py_RETURN_FALSE; } if (GetClassName(o1).compare(GetClassName(o2)) == 0) { Py_RETURN_TRUE; } else { Py_RETURN_FALSE; } } void AssertSameStructure(PyObject* o1, PyObject* o2, bool check_types) { std::string error_msg; bool is_type_error = false; AssertSameStructureHelper(o1, o2, check_types, &error_msg, &is_type_error); if (PyErr_Occurred()) { // Don't hide Python exceptions while checking (e.g. errors fetching keys // from custom mappings). return; } if (!error_msg.empty()) { PyErr_SetString( is_type_error ? PyExc_TypeError : PyExc_ValueError, absl::StrCat( "The two structures don't have the same nested structure.\n\n", "First structure: ", PyObjectToString(o1), "\n\nSecond structure: ", PyObjectToString(o2), "\n\nMore specifically: ", error_msg) .c_str()); } } ValueIteratorPtr GetValueIterator(PyObject* nested) { if (PyDict_Check(nested)) { return absl::make_unique<DictValueIterator>(nested); } else if (IsMappingHelper(nested)) { return absl::make_unique<MappingValueIterator>(nested); } else if (IsAttrsHelper(nested)) { return absl::make_unique<AttrsValueIterator>(nested); } else { return absl::make_unique<SequenceValueIterator>(nested); } } namespace { inline py::object pyo_or_throw(PyObject* ptr) { if (PyErr_Occurred() || ptr == nullptr) { throw py::error_already_set(); } return py::reinterpret_steal<py::object>(ptr); } PYBIND11_MODULE(_tree, m) { // Resolve `wrapt.ObjectProxy` at import time to avoid doing // imports during function calls. tree::GetWraptObjectProxyType(); m.def("assert_same_structure", [](py::handle& o1, py::handle& o2, bool check_types) { tree::AssertSameStructure(o1.ptr(), o2.ptr(), check_types); if (PyErr_Occurred()) { throw py::error_already_set(); } }); m.def("is_sequence", [](py::handle& o) { bool result = tree::IsSequence(o.ptr()); if (PyErr_Occurred()) { throw py::error_already_set(); } return result; }); m.def("is_namedtuple", [](py::handle& o, bool strict) { return pyo_or_throw(tree::IsNamedtuple(o.ptr(), strict)); }); m.def("is_attrs", [](py::handle& o) { bool result = tree::IsAttrs(o.ptr()); if (PyErr_Occurred()) { throw py::error_already_set(); } return result; }); m.def("same_namedtuples", [](py::handle& o1, py::handle& o2) { return pyo_or_throw(tree::SameNamedtuples(o1.ptr(), o2.ptr())); }); m.def("flatten", [](py::handle& nested) { return pyo_or_throw(tree::Flatten(nested.ptr())); }); } } // namespace } // namespace tree
9,790
1,443
<reponame>cssence/mit-license { "copyright": "<NAME>", "url": "http://rezhajulio.web.id", "email": "<EMAIL>", "format": "html", "theme": "afterdark" }
71
622
<filename>api/src/main/java/ai/djl/training/loss/SigmoidBinaryCrossEntropyLoss.java /* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.training.loss; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDArrays; import ai.djl.ndarray.NDList; import ai.djl.nn.Activation; /** * {@code SigmoidBinaryCrossEntropyLoss} is a type of {@link Loss}. * * <p>Sigmoid binary cross-entropy loss is defined by: \(L = -\sum_i {label_i * log(prob_i) * * posWeight + (1 - label_i) * log(1 - prob_i)}\) where \(prob = \frac{1}{1 + e^{-pred}}\) */ public class SigmoidBinaryCrossEntropyLoss extends Loss { private float weight; private boolean fromSigmoid; /** Performs Sigmoid cross-entropy loss for binary classification. */ public SigmoidBinaryCrossEntropyLoss() { this("SigmoidBinaryCrossEntropyLoss"); } /** * Performs Sigmoid cross-entropy loss for binary classification. * * @param name the name of the loss */ public SigmoidBinaryCrossEntropyLoss(String name) { this(name, 1, false); } /** * Performs Sigmoid cross-entropy loss for binary classification. * * @param name the name of the loss * @param weight the weight to apply on the loss value, default 1 * @param fromSigmoid whether the input is from the output of sigmoid, default false */ public SigmoidBinaryCrossEntropyLoss(String name, float weight, boolean fromSigmoid) { super(name); this.weight = weight; this.fromSigmoid = fromSigmoid; } /** {@inheritDoc} */ @Override public NDArray evaluate(NDList label, NDList prediction) { NDArray pred = prediction.singletonOrThrow(); NDArray lab = label.singletonOrThrow(); lab = lab.reshape(pred.getShape()); NDArray loss; if (!fromSigmoid) { // TODO: Add Position weight option loss = Activation.relu(pred) .sub(pred.mul(lab)) .add(Activation.softPlus(pred.abs().neg())); } else { loss = epsLog(pred) .mul(lab) .add(epsLog(NDArrays.sub(1., pred)).mul(NDArrays.sub(1., lab))); } if (weight != 1f) { loss = loss.mul(weight); } return loss.mean(); } /** * Computes a log with added epsilon to avoid errors. * * @param a the input array * @return the computed value */ private NDArray epsLog(NDArray a) { double eps = 1e-12; return a.add(eps).log(); } }
1,324
6,989
#pragma once #include <util/system/types.h> #include <util/generic/map.h> #include <util/generic/hash.h> #include <util/generic/ptr.h> #include <util/generic/guid.h> #include <util/system/spinlock.h> #include <util/system/mutex.h> //cacheable type should has GetGuid() method. this stub is default implementation for this method template <class TLock> class TGuidHolderBase { public: TGuidHolderBase() : Lock(new TLock) { } const TGUID& GetGuid() const { if (!HasGuid) { TGuard<TLock> guard(*Lock); if (!HasGuid) { CreateGuid(&Guid); HasGuid = true; } } return Guid; } private: THolder<TLock> Lock; mutable TGUID Guid; mutable bool HasGuid = false; }; using TGuidHolder = TGuidHolderBase<TFakeMutex>; using TThreadSafeGuidHolder = TGuidHolderBase<TAdaptiveLock>; class TScopedCacheHolder { private: class IScopedCache { public: virtual ~IScopedCache() { } }; template <class TKey, class TValue> class TScopedCache: public IScopedCache { public: TValue& Value(const TKey& key) { return Data.at(key); } const TValue& Value(const TKey& key) const { return Data.at(key); } void Set(const TKey& key, TValue&& value) { Data[key] = std::move(value); } bool Has(const TKey& key) const { return Data.contains(key); } private: THashMap<TKey, TValue> Data; }; template <class TScope, class TKey, class TValue> inline TScopedCache<TKey, TValue>* GetCachePtr(const TScope& scope) { using TCacheType = TScopedCache<TKey, TValue>; const ui64 typeHash = typeid(TCacheType).hash_code(); auto& ptr = ScopeCaches[scope.GetGuid()][typeHash]; if (ptr == nullptr) { ptr.Reset(new TCacheType()); } return dynamic_cast<TCacheType*>(ptr.Get()); } private: THashMap<TGUID, TMap<ui64, THolder<IScopedCache>>> ScopeCaches; public: template <class TScope, class TKey, class TBuilder> TScopedCacheHolder& CacheOnly(const TScope& scope, const TKey& key, TBuilder&& builder) { using TValue = decltype(builder()); auto cachePtr = GetCachePtr<TScope, TKey, TValue>(scope); if (!cachePtr->Has(key)) { cachePtr->Set(key, builder()); } return *this; } template <class TScope, class TKey, class TBuilder> auto Cache(const TScope& scope, const TKey& key, TBuilder&& builder) -> decltype(GetCachePtr<TScope, TKey, decltype(builder())>(scope)->Value(key)) { using TValue = decltype(builder()); CacheOnly(scope, key, std::forward<TBuilder>(builder)); return GetCachePtr<TScope, TKey, TValue>(scope)->Value(key); } };
1,404
575
<reponame>Ron423c/chromium<filename>chrome/browser/touch_to_fill/android/java/src/org/chromium/chrome/browser/touch_to_fill/data/Credential.java // 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. package org.chromium.chrome.browser.touch_to_fill.data; import org.chromium.base.annotations.CalledByNative; /** * This class holds the data used to represent a selectable credential in the Touch To Fill sheet. */ public class Credential { private final String mUsername; private final String mPassword; private final String mFormattedUsername; private final String mOriginUrl; private final boolean mIsPublicSuffixMatch; private final boolean mIsAffiliationBasedMatch; private final long mLastUsedMsSinceEpoch; /** * @param username Username shown to the user. * @param password Password shown to the user. * @param originUrl Origin URL shown to the user in case this credential is a PSL match. * @param isPublicSuffixMatch Indicating whether the credential is a PSL match. * @param isAffiliationBasedMatch Indicating whether the credential is an affiliation based * match (i.e. whether it is an Android credential). * @param lastUsedMsSinceEpoch Elapsed number of milliseconds from the unix epoch when the * credential was used the last time. */ public Credential(String username, String password, String formattedUsername, String originUrl, boolean isPublicSuffixMatch, boolean isAffiliationBasedMatch, long lastUsedMsSinceEpoch) { assert originUrl != null : "Credential origin is null! Pass an empty one instead."; mUsername = username; mPassword = password; mFormattedUsername = formattedUsername; mOriginUrl = originUrl; mIsPublicSuffixMatch = isPublicSuffixMatch; mIsAffiliationBasedMatch = isAffiliationBasedMatch; mLastUsedMsSinceEpoch = lastUsedMsSinceEpoch; } @CalledByNative public String getUsername() { return mUsername; } @CalledByNative public String getPassword() { return mPassword; } public String getFormattedUsername() { return mFormattedUsername; } @CalledByNative public String getOriginUrl() { return mOriginUrl; } @CalledByNative public boolean isPublicSuffixMatch() { return mIsPublicSuffixMatch; } @CalledByNative public boolean isAffiliationBasedMatch() { return mIsAffiliationBasedMatch; } @CalledByNative public long lastUsedMsSinceEpoch() { return mLastUsedMsSinceEpoch; } }
939
344
#include <stdint.h> #ifndef FRANKENSTEIN_EMULATION /* Patchram implementation running on the device */ #define PATCHRAM_SLOTS 255 extern int patchram_enable[]; // 0x310404 on CYW20735 extern int patchram_address_table[]; // 0x310000 on CYW20735 extern int patchram_data_table[]; // 0x270000 on CYW20735 int patchram_get_slot(int addr){ int slot; for (slot=0; slot < PATCHRAM_SLOTS; slot++){ //Reuse existing patchram slot for addr if (patchram_address_table[slot] == addr >> 2) { return slot; } //Get new patchram slot if ( !(patchram_enable[slot>>5] & (1 << (slot&0x1f)))) { return slot; } } return -1; } void write_code(uint32_t addr, uint32_t data) { uint32_t slot = patchram_get_slot(addr); if (slot != -1) { patchram_address_table[slot] = addr >> 2; patchram_data_table[slot] = data; patchram_enable[slot>>5] |= (1 << (slot&0x1f)); } } /* Not needed void write_code_undo(uint32_t addr) { uint32_t slot = patchram_get_slot(addr); if (slot != -1) patchram_enable[slot>>5] &= ~(1 << (slot&0x1f)); } */ #endif
545
526
<reponame>rychagova/egeria /* SPDX-License-Identifier: Apache-2.0 */ /* Copyright Contributors to the ODPi Egeria project. */ package org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.properties.typedefs; import com.fasterxml.jackson.databind.ObjectMapper; import org.testng.annotations.Test; import java.util.ArrayList; import java.util.List; import static org.testng.Assert.*; /** * TypeDefAttributeTest provides test of TypeDefAttribute */ public class TypeDefAttributeTest { protected String attributeName = "TestAttributeName"; protected AttributeTypeDef attributeType = new PrimitiveDef(PrimitiveDefCategory.OM_PRIMITIVE_TYPE_BOOLEAN); protected TypeDefAttributeStatus attributeStatus = TypeDefAttributeStatus.ACTIVE_ATTRIBUTE; protected String replacedByAttribute = "TestReplacementAttribute"; protected String attributeDescription = "TestAttributeDescription"; protected String attributeDescriptionGUID = "TestAttributeDescriptionGUID"; protected AttributeCardinality cardinality = AttributeCardinality.ONE_ONLY; protected int valuesMinCount = 4; protected int valuesMaxCount = 9; protected boolean isIndexable = false; protected boolean isUnique = true; protected String defaultValue = "TestDefaultValue"; protected List<ExternalStandardMapping> externalStandardMappings = new ArrayList<>(); /** * Constructor to set up complex attributes */ public TypeDefAttributeTest() { ExternalStandardMapping externalStandardMapping = new ExternalStandardMapping(); externalStandardMapping.setStandardName("TestStandardName"); externalStandardMapping.setStandardTypeName("TestStandardTypeName"); externalStandardMapping.setStandardOrganization("TestOrganizationName"); externalStandardMappings.add(externalStandardMapping); } /** * Return a filled in test object * * @return test object */ private TypeDefAttribute getTestObject() { TypeDefAttribute testObject = new TypeDefAttribute(); testObject.setAttributeName(attributeName); testObject.setAttributeType(attributeType); testObject.setAttributeStatus(attributeStatus); testObject.setReplacedByAttribute(replacedByAttribute); testObject.setAttributeDescription(attributeDescription); testObject.setAttributeDescriptionGUID(attributeDescriptionGUID); testObject.setAttributeCardinality(cardinality); testObject.setValuesMinCount(valuesMinCount); testObject.setValuesMaxCount(valuesMaxCount); testObject.setIndexable(isIndexable); testObject.setUnique(isUnique); testObject.setDefaultValue(defaultValue); testObject.setExternalStandardMappings(externalStandardMappings); return testObject; } private void validateObject(TypeDefAttribute testObject) { assertEquals(testObject.getAttributeName(), attributeName); assertEquals(testObject.getAttributeType(), attributeType); assertEquals(testObject.getAttributeStatus(), attributeStatus); assertEquals(testObject.getReplacedByAttribute(), replacedByAttribute); assertEquals(testObject.getAttributeDescription(), attributeDescription); assertEquals(testObject.getAttributeDescriptionGUID(), attributeDescriptionGUID); assertEquals(testObject.getAttributeCardinality(), AttributeCardinality.ONE_ONLY); assertEquals(testObject.getValuesMinCount(), 4); assertEquals(testObject.getValuesMaxCount(), 9); assertEquals(testObject.isIndexable(), false); assertEquals(testObject.isUnique(), true); assertEquals(testObject.getDefaultValue(), defaultValue); assertEquals(testObject.getExternalStandardMappings(), externalStandardMappings); } private void validateNullObject(TypeDefAttribute testObject) { assertNull(testObject.getAttributeName()); assertNull(testObject.getAttributeType()); assertNull(testObject.getAttributeStatus()); assertNull(testObject.getReplacedByAttribute()); assertNull(testObject.getAttributeDescription()); assertNull(testObject.getAttributeDescriptionGUID()); assertEquals(testObject.getAttributeCardinality(), AttributeCardinality.UNKNOWN); assertEquals(testObject.getValuesMinCount(), 0); assertEquals(testObject.getValuesMaxCount(), 1); assertEquals(testObject.isIndexable(), true); assertEquals(testObject.isUnique(), false); assertNull(testObject.getDefaultValue()); assertNull(testObject.getExternalStandardMappings()); } /** * Validate that the constructors set up the attributes correctly. */ @Test public void testConstructors() { validateNullObject(new TypeDefAttribute()); validateNullObject(new TypeDefAttribute(new TypeDefAttribute())); validateObject(new TypeDefAttribute(getTestObject())); TypeDefAttribute testObject = new TypeDefAttribute(); testObject.setExternalStandardMappings(new ArrayList<>()); validateNullObject(testObject); } /** * Validate that an object generated from a JSON String has the same content as the object used to * create the JSON String. */ @Test public void testJSON() { ObjectMapper objectMapper = new ObjectMapper(); String jsonString = null; try { jsonString = objectMapper.writeValueAsString(getTestObject()); } catch (Throwable exc) { fail("Exception: " + exc.getMessage()); } try { validateObject(objectMapper.readValue(jsonString, TypeDefAttribute.class)); } catch (Throwable exc) { fail("Exception: " + exc.getMessage()); } } /** * Test that toString is overridden. */ @Test public void testToString() { assertTrue(getTestObject().toString().contains("TypeDefAttribute")); } /** * Test that equals works */ @Test public void testEquals() { assertTrue(getTestObject().equals(getTestObject())); TypeDefAttribute testObject = getTestObject(); assertTrue(testObject.equals(testObject)); assertFalse(getTestObject().equals(null)); assertFalse(getTestObject().equals("AString")); assertFalse(getTestObject().equals(new CollectionDef())); } /** * Test that hashcode is consistent */ @Test public void testHash() { assertEquals(getTestObject().hashCode(), getTestObject().hashCode()); TypeDefAttribute testObject = getTestObject(); TypeDefAttribute anotherObject = getTestObject(); anotherObject.setAttributeDescriptionGUID("DifferentGUID"); assertNotEquals(testObject.hashCode(), anotherObject.hashCode()); } }
2,788
647
// Local includes #include "trick/IntegLoopScheduler.hh" #include "trick/IntegLoopManager.hh" #include "trick/IntegJobClassId.hh" // Trick includes #include "trick/exec_proto.h" #include "trick/message_proto.h" #include "trick/message_type.h" #include "trick/JobData.hh" // System includes #include <iostream> #include <iomanip> #include <cstdarg> #include <math.h> // Anonymous namespace for local functions namespace { /** * Process the enabled job in the provided job queue. * @param job_queue Job queue to be processed. */ inline void call_jobs ( Trick::ScheduledJobQueue & job_queue) { Trick::JobData * curr_job; job_queue.reset_curr_index(); while ((curr_job = job_queue.get_next_job()) != NULL) { curr_job->call(); } } } /** The singleton IntegrationManager object. It is a protected static member of the IntegLoopScheduler class. */ Trick::IntegrationManager Trick::IntegLoopScheduler::manager; /** The Integrator currently being processed. */ Trick::Integrator* trick_curr_integ = NULL; /** Non-default constructor. @param in_cycle The time interval at which the loop's integrate function is called @param in_parent_so Pointer to the parent sim object. */ Trick::IntegLoopScheduler::IntegLoopScheduler( double in_cycle, Trick::SimObject * in_parent_so) : Scheduler (), verbosity (0), last_step_deriv (false), first_step_deriv (false), integ_ptr (NULL), sim_objects (), nominal_cycle (in_cycle), next_cycle (in_cycle), parent_sim_object (in_parent_so), pre_integ_jobs (), deriv_jobs (), integ_jobs (), dynamic_event_jobs (), post_integ_jobs () { complete_construction(); } /** Default constructor */ Trick::IntegLoopScheduler::IntegLoopScheduler() : Scheduler (), verbosity (0), last_step_deriv (false), first_step_deriv (false), integ_ptr (NULL), sim_objects (), nominal_cycle (), next_cycle (), parent_sim_object (NULL), pre_integ_jobs (), deriv_jobs (), integ_jobs (), dynamic_event_jobs (), post_integ_jobs () { complete_construction(); } /** Complete the construction of an integration loop. All constructors but the copy constructor call this method. */ void Trick::IntegLoopScheduler::complete_construction() { // Create the class_name to class_id mapping. class_map["derivative"] = Trick::DerivativeJobClassId; class_to_queue[Trick::DerivativeJobClassId] = &deriv_jobs; class_map["integration"] = Trick::IntegrationJobClassId; class_to_queue[Trick::IntegrationJobClassId] = &integ_jobs; class_map["dynamic_event"] = Trick::DynamicEventJobClassId; class_to_queue[Trick::DynamicEventJobClassId] = &dynamic_event_jobs; class_map["post_integration"] = Trick::PostIntegrationJobClassId; class_to_queue[Trick::PostIntegrationJobClassId] = &post_integ_jobs; class_map["pre_integration"] = Trick::PreIntegrationJobClassId; class_to_queue[Trick::PreIntegrationJobClassId] = &pre_integ_jobs; } /** Find the specified sim object in the set of objects managed by this loop. @return Iterator pointing to the object, or to sim_objects.end() if not found. @param sim_obj Object to be found. */ Trick::IntegLoopScheduler::SimObjectVector::iterator Trick::IntegLoopScheduler::find_sim_object(Trick::SimObject & sim_obj) { return std::find (sim_objects.begin(), sim_objects.end(), &sim_obj); } /** Add jobs from specified object. @param in_obj Pointer to the sim object from which the integration jobs should be added. Deprecated! */ int Trick::IntegLoopScheduler::add_integ_jobs_from_sim_object ( Trick::SimObject * in_obj) { unsigned int ii ; std::map<std::string, int>::iterator class_id_it ; std::map<int, Trick::ScheduledJobQueue *>::iterator queue_it ; Trick::ScheduledJobQueue * curr_queue ; JobData * job ; // TODO: add check to make sure the integ job is not set to another object before adding job to queue // TODO: Check other simobjects for jobs that are to be added to this integration // TODO: check all integration schemes for integrate structures are the same // For each of the jobs in the SimObject for ( ii = 0 ; ii < in_obj->jobs.size() ; ii++ ) { job = in_obj->jobs[ii] ; // if the job's job_class_name is in the class map then set its job_class to the corresponding class_id if ( (class_id_it = class_map.find(job->job_class_name)) != class_map.end() ) { // set this integration loop frequency to all its individual jobs job->cycle = nominal_cycle; job->job_class = class_id_it->second ; if ( (queue_it = class_to_queue.find(job->job_class)) != class_to_queue.end() ) { curr_queue = queue_it->second ; curr_queue->push_ignore_sim_object( job ) ; } } } return 0; } // Overload of Scheduler::add_sim_object that does nothing. int Trick::IntegLoopScheduler::add_sim_object(Trick::SimObject * sim_obj __attribute((unused))) { return 0; } /** Add a sim object to the set of objects integrated by this integration loop. The job queues for this loop are rebuild after adding the sim object. @param sim_obj Address of the sim object that should be added to scheduler. */ int Trick::IntegLoopScheduler::add_sim_object(Trick::SimObject & sim_obj) { // Disallow duplicate objects. if (find_sim_object (sim_obj) != sim_objects.end()) { message_publish ( MSG_ERROR, "Integ Scheduler ERROR: " "SimObject '%s' is already managed by this integration loop.\n", sim_obj.name.c_str()); return 1; } // Object is not in the set. Add it. sim_objects.push_back (&sim_obj); // Rebuild jobs, but only if the manager has been initialized. // Adding jobs prior to the initial build are legal; they are addressed // by an S_define-level call to rebuild_jobs. if (! manager.is_empty()) { // If this object is already managed by a different integration loop, // remove it from that other loop to avoid integrating the object twice. IntegLoopScheduler * other = manager.get_integrated_by (&sim_obj); if (other != NULL) { other->remove_sim_object (sim_obj); } // Now rebuild our jobs. rebuild_jobs(); } return 0; } /** Remove a sim object from the objects integrated by this integration loop. The job queues for this loop are rebuilt after removing the sim object. @param sim_obj Address of sim object that should be removed from scheduler. */ int Trick::IntegLoopScheduler::remove_sim_object(Trick::SimObject & sim_obj) { // Find the object in the set of objects managed by this loop; // The object must be in that set if it is to be removed. SimObjectVector::iterator iter = find_sim_object (sim_obj); if (iter == sim_objects.end()) { message_publish ( MSG_ERROR, "Integ Scheduler ERROR: " "SimObject '%s' is not managed by this integration loop.\n", sim_obj.name.c_str()); return 1; } // Object is in the set. Remove it. sim_objects.erase (iter); // Rebuild jobs, but only if the manager has been initialized. // Calls to remove prior to the initial build are legal (but silly). if (! manager.is_empty()) { rebuild_jobs(); } return 0; } /** Prepare for a restart. */ void Trick::IntegLoopScheduler::restart_checkpoint() { manager.clear_sim_object_info(); } /** Rebuild the integration loop's job queues. This method is called internally upon adding or deleting sim objects, and is called externally (S_define level) during initialization and after a checkpoint restart. */ void Trick::IntegLoopScheduler::rebuild_jobs () { // Rebuild the manager. manager.build_sim_object_info(); // Reset the manager's notion of which objects this integrator integrates. manager.clear_integrated_by (this); for (SimObjectVector::iterator so_iter = sim_objects.begin(); so_iter != sim_objects.end(); ++so_iter) { Trick::SimObject * sim_object = *so_iter; manager.set_integrated_by (sim_object, this); } // Rebuild each of this integration loop's job queues. for (std::map<std::string, int>::iterator id_iter = class_map.begin(); id_iter != class_map.end(); ++id_iter) { const std::string & job_class_name = id_iter->first; int job_class_id = id_iter->second; Trick::ScheduledJobQueue & queue = *(class_to_queue.at(job_class_id)); // Rebuild the queue by first tearing it down to nothing // and then rebuilding from scratch. clear_queue (queue); for (SimObjectVector::iterator so_iter = sim_objects.begin(); so_iter != sim_objects.end(); ++so_iter) { Trick::SimObject * sim_object = *so_iter; manager.add_jobs_to_queue ( job_class_name, job_class_id, sim_object, queue); } } } /** Empty a job queue in anticipation of the queue being rebuilt. @param job_queue Address of job queue that should be cleared. */ void Trick::IntegLoopScheduler::clear_queue ( Trick::ScheduledJobQueue & job_queue) { if (job_queue.size() != 0) { Trick::JobData * curr_job; job_queue.reset_curr_index(); while ((curr_job = job_queue.get_next_job()) != NULL) { curr_job->set_handled (false); } job_queue.clear (); } } /** Call the enabled derivative jobs. */ void Trick::IntegLoopScheduler::call_deriv_jobs () { call_jobs (deriv_jobs); } /** Integrate objects to the current simulation time. Note that sim_time is advanced before integration, so integration has to be from sim_time-cycle to sim_time. */ int Trick::IntegLoopScheduler::integrate() { double t_end = exec_get_sim_time(); double t_start = t_end - next_cycle; // This is the time of the current state vector. int status; // Call all of the jobs in the pre-integration job queue. call_jobs (pre_integ_jobs); // Integrate sim objects to the current time. status = integrate_dt (t_start, next_cycle); if (status != 0) { return status; } // Process dynamic events, if any. if (! dynamic_event_jobs.empty()) { status = process_dynamic_events (t_start, t_end); if (status != 0) { return status; } } // Call the jobs in the derivative job queue one more time if indicated. if (get_last_step_deriv()) { call_jobs (deriv_jobs); } // Call all of the jobs in the post-integration job queue. call_jobs (post_integ_jobs); // We should now be back in sync with the nominal cycle rate. next_cycle = nominal_cycle; return 0; } /** Determine whether derivative jobs should be called on the first step. True if any integrator needs derivatives on the first step, false otherwise. */ bool Trick::IntegLoopScheduler::get_first_step_deriv_from_integrator() { // We need derivatives if the integ_ptr says so. if ((integ_ptr != NULL) && integ_ptr->first_step_deriv) { return true; } // Other integrators may be set in sup_class_data. Check them. else { Trick::JobData * curr_job; void* sup_class_data; Trick::Integrator* trick_integrator; integ_jobs.reset_curr_index(); while ((curr_job = integ_jobs.get_next_job()) != NULL) { if ((curr_job->job_class == Trick::IntegrationJobClassId) && ((sup_class_data = curr_job->sup_class_data) != NULL) && ((trick_integrator = *(static_cast<Trick::Integrator**>(sup_class_data))) != NULL) && trick_integrator->first_step_deriv) { return true; } } } return false; } /** Determine whether derivative jobs should be called prior to exiting the main integration function. True if this object's last_deriv_flag is set, or if any integrator's last_deriv_flag is set. False otherwise. */ bool Trick::IntegLoopScheduler::get_last_step_deriv() { // We need to calculate post-integration derivatives if this object // or the integ_ptr says to do so. if (last_step_deriv || ((integ_ptr != NULL) && integ_ptr->last_step_deriv)) { return true; } // Other integrators may be set in sup_class_data. Check them. else { Trick::JobData * curr_job; void* sup_class_data; Trick::Integrator* trick_integrator; integ_jobs.reset_curr_index(); while ((curr_job = integ_jobs.get_next_job()) != NULL) { if ((curr_job->job_class == Trick::IntegrationJobClassId) && ((sup_class_data = curr_job->sup_class_data) != NULL) && ((trick_integrator = *(static_cast<Trick::Integrator**>(sup_class_data))) != NULL) && trick_integrator->last_step_deriv) { return true; } } } return false; } /** Integrate over the specified time interval. */ int Trick::IntegLoopScheduler::integrate_dt ( double t_start, double dt) { int ipass = 0; int ex_pass = 0; bool need_derivs = get_first_step_deriv_from_integrator(); do { ex_pass ++; // Call all of the jobs in the derivative job queue if needed. if (need_derivs) { call_jobs (deriv_jobs); } need_derivs = true; // Call all of the jobs in the integration job queue. Trick::JobData * curr_job; integ_jobs.reset_curr_index(); while ((curr_job = integ_jobs.get_next_job()) != NULL) { void* sup_class_data = curr_job->sup_class_data; // Jobs without supplemental data use the default integrator. if (sup_class_data == NULL) { trick_curr_integ = integ_ptr; } // Non-null supplemental data: // Resolve as a pointer-to-a-pointer to a Trick::Integrator. else { trick_curr_integ = *(static_cast<Trick::Integrator**>(sup_class_data)); } if (trick_curr_integ == NULL) { message_publish ( MSG_ERROR, "Integ Scheduler ERROR: " "Integrate job has no associated Integrator.\n"); return 1; } if (ex_pass == 1) { trick_curr_integ->time = t_start; trick_curr_integ->dt = dt; } if (verbosity || trick_curr_integ->verbosity) { message_publish (MSG_DEBUG, "Job: %s, time: %f, dt: %f\n", curr_job->name.c_str(), t_start, dt); } ipass = curr_job->call(); // Trick integrators are expected to advance from step one to step // two, etc., and then back to zero to indicate completion. // All integrators are expected to march to the same beat. // FIXME, future: This restricts Trick to using only rather // simple integration techniques. if ((ipass != 0) && (ipass != ex_pass)) { message_publish ( MSG_ERROR, "Integ Scheduler ERROR: Integrators not in sync.\n"); return 1; } } } while (ipass); return 0; } int Trick::IntegLoopScheduler::process_dynamic_events ( double t_start, double t_end, unsigned int depth) { bool fired = false; double t_to = t_end; double t_from = t_start; Trick::JobData * curr_job; dynamic_event_jobs.reset_curr_index(); while ((curr_job = dynamic_event_jobs.get_next_job()) != NULL) { // Call the dynamic event job to calculate an estimated time-to-go. double tgo = curr_job->call_double(); if (tgo < 0.0) { // If there is a root in this interval ... fired = true; while (tgo != 0.0) { if (tgo > 0.0) { t_from = t_to; t_to = t_to + tgo; int status = integrate_dt( t_from, (t_to-t_from)); if (status != 0) { return status; } } else { #define FORWARD_INTEGRATION 0 #if FORWARD_INTEGRATION integ_ptr->state_reset(); // We always want to integrate forward. t_to = t_to + tgo; #else t_from = t_to; t_to = t_from + tgo; #endif int status = integrate_dt( t_from, (t_to-t_from)); if (status != 0) { return status; } } tgo = curr_job->call_double(); } } } /* Integrate to the end of the integration cycle using the updated derivatives. */ if (fired) { t_from = t_to; t_to = t_end; /* Because the derivatives have likely changed, we need to recursively check for new events in the remaining interval. */ int status = integrate_dt( t_from, (t_to-t_from)); if (status != 0) { return status; } status = process_dynamic_events(t_from, t_to, depth+1); if (status != 0) { return status; } } else { return 0; } } /** Utility function to get an integrator. @param alg The integration algorithm to use. @param state_size the total number of integration variables and derivative variables. */ Trick::Integrator * Trick::IntegLoopScheduler::getIntegrator ( Integrator_type alg, unsigned int state_size) { integ_ptr = Trick::getIntegrator (alg, state_size); trick_curr_integ = integ_ptr; return integ_ptr; } /** Set the interval at which this job is called. @param in_cycle The frequency for the integration cycle. */ int Trick::IntegLoopScheduler::set_integ_cycle ( double in_cycle) { JobData * found_job = NULL; int loops_found = 0; // Search through the parent sim object looking for integ_loop jobs. // There should be exactly one such job. for (std::vector<Trick::JobData *>::iterator vit = parent_sim_object->jobs.begin(); vit != parent_sim_object->jobs.end(); ++vit) { JobData * vit_job = *vit; if (! vit_job->job_class_name.compare("integ_loop")) { ++loops_found; found_job = vit_job; } } // Not finding exactly one integ_loop job is an error. if (loops_found != 1) { message_publish ( MSG_ERROR, "Integ Scheduler ERROR: %s\n", (loops_found == 0) ? "integ_loop job not found." : "multiple integ_loop jobs found."); return 1; } // Found exactly one integ_loop job. // Set the cycle rate for that one job and for this object. // Note: This assumes that the one found job pertains to this scheduler. else { long long prev_tics = found_job->next_tics - found_job->cycle_tics; long long curr_tics = exec_get_time_tics(); found_job->set_cycle (in_cycle); found_job->set_next_call_time (curr_tics); nominal_cycle = in_cycle; next_cycle = double((found_job->next_tics - prev_tics)) / double(found_job->time_tic_value); return 0; } } /** Write the content of the S_job_execution file. @param fp The pointer to the file to write the S_job_execution file. */ int Trick::IntegLoopScheduler::write_s_job_execution(FILE *fp) { if (fp == NULL) { return 0; } fprintf(fp, "\n===================================================================================================\n") ; fprintf(fp, "Integration Loop:\n\n") ; pre_integ_jobs.write_sched_queue(fp) ; deriv_jobs.write_sched_queue(fp) ; integ_jobs.write_sched_queue(fp) ; dynamic_event_jobs.write_sched_queue(fp) ; post_integ_jobs.write_sched_queue(fp) ; return 0; } /** Adds the incoming instrumentation job before target job if specified, or all jobs in the list. @param instrument_job Pointer to the job that should be run previously. */ int Trick::IntegLoopScheduler::instrument_job_before ( Trick::JobData * instrument_job) { int count = 0 ; /** @par Detailed Design */ count += pre_integ_jobs.instrument_before(instrument_job) ; count += deriv_jobs.instrument_before(instrument_job) ; count += integ_jobs.instrument_before(instrument_job) ; count += dynamic_event_jobs.instrument_before(instrument_job) ; count += post_integ_jobs.instrument_before(instrument_job) ; /** @li Return how many insertions were done. */ return count; } /** Adds the incoming instrumentation job after target job if specified, or all jobs in the list. @param instrument_job Pointer to the job that should be run after each job. */ int Trick::IntegLoopScheduler::instrument_job_after ( Trick::JobData * instrument_job) { int count = 0 ; count += pre_integ_jobs.instrument_after(instrument_job) ; count += deriv_jobs.instrument_after(instrument_job) ; count += integ_jobs.instrument_after(instrument_job) ; count += dynamic_event_jobs.instrument_after(instrument_job) ; count += post_integ_jobs.instrument_after(instrument_job) ; return count; } /** Removes all jobs in the list that match the name in_job. @param in_job name of the job that should be removed. */ int Trick::IntegLoopScheduler::instrument_job_remove(std::string in_job) { pre_integ_jobs.instrument_remove(in_job) ; deriv_jobs.instrument_remove(in_job) ; integ_jobs.instrument_remove(in_job) ; dynamic_event_jobs.instrument_remove(in_job) ; post_integ_jobs.instrument_remove(in_job) ; return 0; }
8,920
357
/* * Copyright © 2012-2016 VMware, 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. */ #include "includes.h" static PCSTRING IDM_CERTIFICATE_SCOPE_TYPE_ENUMS[] = { "TENANT", "EXTERNAL_IDP" }; static PCSTRING const TENANT_URI = "/idm/tenant"; static PCSTRING const TENANT_POST_URI = "/idm/post/tenant"; SSOERROR IdmCertificateGet( PCREST_CLIENT pClient, PCSTRING tenant, IDM_CERTIFICATE_SCOPE_TYPE certificateScopeType, IDM_CERTIFICATE_CHAIN_ARRAY_DATA** ppCertificateChainArrayReturn, REST_SERVER_ERROR** ppError) { SSOERROR e = SSOERROR_NONE; PSTRING resourceUri = NULL; IDM_CERTIFICATE_CHAIN_ARRAY_DATA* pCertificateChainArrayReturn = NULL; REST_SERVER_ERROR* pError = NULL; if (pClient == NULL || IS_NULL_OR_EMPTY_STRING(tenant) || ppCertificateChainArrayReturn == NULL || ppError == NULL) { e = SSOERROR_INVALID_ARGUMENT; BAIL_ON_ERROR(e); } e = RestBuildResourceUri( pClient, TENANT_URI, tenant, "certificates", NULL, NULL, &resourceUri); BAIL_ON_ERROR(e); e = RestAppendQueryStringOnResourceUri( "scope", IDM_CERTIFICATE_SCOPE_TYPE_ENUMS[certificateScopeType], true, resourceUri, &resourceUri); BAIL_ON_ERROR(e); e = RestBuildAndExecuteHttp( NULL, NULL, pClient->pAccessToken, resourceUri, REST_HTTP_METHOD_TYPE_GET, (JsonToDataObjectFunc) IdmJsonToCertificateChainArrayData, (void**) &pCertificateChainArrayReturn, pClient->tlsCAPath, &pError); BAIL_ON_ERROR(e); *ppCertificateChainArrayReturn = pCertificateChainArrayReturn; // debug if (DEBUG) { RestDebugJsonArray(*ppCertificateChainArrayReturn, (DataObjectToJsonFunc) IdmCertificateChainArrayDataToJson); } error: if (e != SSOERROR_NONE) { IdmCertificateChainArrayDataDelete(pCertificateChainArrayReturn); *ppError = pError; } // cleanup SSOStringFree(resourceUri); return e; } SSOERROR IdmCertificateDelete( PCREST_CLIENT pClient, PCSTRING tenant, PCSTRING fingerprint, REST_SERVER_ERROR** ppError) { SSOERROR e = SSOERROR_NONE; PSTRING resourceUri = NULL; REST_SERVER_ERROR* pError = NULL; if (pClient == NULL || IS_NULL_OR_EMPTY_STRING(tenant) || IS_NULL_OR_EMPTY_STRING(fingerprint) || ppError == NULL) { e = SSOERROR_INVALID_ARGUMENT; BAIL_ON_ERROR(e); } e = RestBuildResourceUri( pClient, TENANT_URI, tenant, "certificates", NULL, NULL, &resourceUri); BAIL_ON_ERROR(e); e = RestAppendQueryStringOnResourceUri("fingerprint", fingerprint, true, resourceUri, &resourceUri); BAIL_ON_ERROR(e); e = RestBuildAndExecuteHttp( NULL, NULL, pClient->pAccessToken, resourceUri, REST_HTTP_METHOD_TYPE_DELETE, NULL, NULL, pClient->tlsCAPath, &pError); BAIL_ON_ERROR(e); error: if (e != SSOERROR_NONE) { *ppError = pError; } // cleanup SSOStringFree(resourceUri); return e; } SSOERROR IdmCertificateGetPrivateKey( PCREST_CLIENT pClient, PCSTRING tenant, IDM_PRIVATE_KEY_DATA** ppPrivateKeyReturn, REST_SERVER_ERROR** ppError) { SSOERROR e = SSOERROR_NONE; PSTRING resourceUri = NULL; IDM_PRIVATE_KEY_DATA* pPrivateKeyReturn = NULL; REST_SERVER_ERROR* pError = NULL; if (pClient == NULL || IS_NULL_OR_EMPTY_STRING(tenant) || ppPrivateKeyReturn == NULL || ppError == NULL) { e = SSOERROR_INVALID_ARGUMENT; BAIL_ON_ERROR(e); } e = RestBuildResourceUri( pClient, TENANT_POST_URI, tenant, "certificates", "privatekey", NULL, &resourceUri); BAIL_ON_ERROR(e); e = RestBuildAndExecuteHttp( NULL, NULL, pClient->pAccessToken, resourceUri, REST_HTTP_METHOD_TYPE_POST, (JsonToDataObjectFunc) IdmJsonToPrivateKeyData, (void**) &pPrivateKeyReturn, pClient->tlsCAPath, &pError); BAIL_ON_ERROR(e); *ppPrivateKeyReturn = pPrivateKeyReturn; // debug if (DEBUG) { RestDebugJsonObject(*ppPrivateKeyReturn, (DataObjectToJsonFunc) IdmPrivateKeyDataToJson); } error: if (e != SSOERROR_NONE) { IdmPrivateKeyDataDelete(pPrivateKeyReturn); *ppError = pError; } // cleanup SSOStringFree(resourceUri); return e; } SSOERROR IdmCertificateSetCredentials( PCREST_CLIENT pClient, PCSTRING tenant, IDM_TENANT_CREDENTIALS_DATA* pTenantCredentials, REST_SERVER_ERROR** ppError) { SSOERROR e = SSOERROR_NONE; PSTRING resourceUri = NULL; REST_SERVER_ERROR* pError = NULL; if (pClient == NULL || IS_NULL_OR_EMPTY_STRING(tenant) || pTenantCredentials == NULL || ppError == NULL) { e = SSOERROR_INVALID_ARGUMENT; BAIL_ON_ERROR(e); } e = RestBuildResourceUri( pClient, TENANT_URI, tenant, "certificates", "privatekey", NULL, &resourceUri); BAIL_ON_ERROR(e); e = RestBuildAndExecuteHttp( pTenantCredentials, (DataObjectToJsonFunc) IdmTenantCredentialsDataToJson, pClient->pAccessToken, resourceUri, REST_HTTP_METHOD_TYPE_POST, NULL, NULL, pClient->tlsCAPath, &pError); BAIL_ON_ERROR(e); error: if (e != SSOERROR_NONE) { *ppError = pError; } // cleanup SSOStringFree(resourceUri); return e; }
2,911
14,668
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_SYNC_SYNC_UI_UTIL_H_ #define CHROME_BROWSER_SYNC_SYNC_UI_UTIL_H_ #include "build/build_config.h" #include "components/sync/driver/sync_service_utils.h" #include "third_party/abseil-cpp/absl/types/optional.h" class Browser; class GURL; class Profile; class PrefService; namespace signin { class IdentityManager; } // namespace signin namespace syncer { class SyncService; } // namespace syncer // Utility functions to gather current sync status information from the sync // service and constructs messages suitable for showing in UI. enum class SyncStatusMessageType { // User has not set up sync. kPreSynced, // We are synced and authenticated to a gmail account. kSynced, // A sync error (such as invalid credentials) has occurred. kSyncError, // Same as kSyncError but affecting passwords only. kPasswordsOnlySyncError, }; // The action associated with the sync status in settings. enum class SyncStatusActionType { // No action to take. kNoAction, // User needs to reauthenticate. kReauthenticate, // User needs to upgrade the client. kUpgradeClient, // User needs to enter their passphrase. kEnterPassphrase, // User needs to go through key retrieval. kRetrieveTrustedVaultKeys, // User needs to confirm sync settings. kConfirmSyncSettings, }; // Sync errors that should be exposed to the user through the avatar button. enum AvatarSyncErrorType { // Unrecoverable error for managed users. kManagedUserUnrecoverableError, // Unrecoverable error for regular users. kUnrecoverableError, // Authentication error. // TODO(crbug.com/1156584): Rename to SYNC_PAUSED. That's how it's treated by // the UI, and it should eventually match SyncService::TransportState::PAUSED. kAuthError, // Out-of-date client error. kUpgradeClientError, // Sync passphrase error. kPassphraseError, // Trusted vault keys missing for all sync datatypes (encrypt everything is // enabled). kTrustedVaultKeyMissingForEverythingError, // Trusted vault keys missing for always-encrypted datatypes (passwords). kTrustedVaultKeyMissingForPasswordsError, // User needs to improve recoverability of the trusted vault (encrypt // everything is enabled). kTrustedVaultRecoverabilityDegradedForEverythingError, // User needs to improve recoverability of the trusted vault (passwords). kTrustedVaultRecoverabilityDegradedForPasswordsError, // Sync settings dialog not confirmed yet. kSettingsUnconfirmedError, }; struct SyncStatusLabels { SyncStatusMessageType message_type; int status_label_string_id; int button_string_id; SyncStatusActionType action_type; }; // Returns the high-level sync status by querying |sync_service| and // |identity_manager|. SyncStatusLabels GetSyncStatusLabels(syncer::SyncService* sync_service, signin::IdentityManager* identity_manager, bool is_user_signout_allowed); // Returns the high-level sync status by querying |profile|. This is a // convenience version of GetSyncStatusLabels that use the |sync_service| and // |identity_manager| associated to |profile| via their respective factories. SyncStatusLabels GetSyncStatusLabels(Profile* profile); // Convenience version of GetSyncStatusLabels for when you're only interested in // the message type. SyncStatusMessageType GetSyncStatusMessageType(Profile* profile); // Gets the error in the sync machinery (if any) that should be exposed to the // user through the titlebar avatar button. If absl::nullopt is returned, this // does NOT mean sync-the-feature/sync-the-transport is enabled, simply that // there's no error. Furthermore, an error may be returned even if only // sync-the-transport is running. One such case is when the user wishes to run // an encrypted data type on transport mode and must first go through a reauth. absl::optional<AvatarSyncErrorType> GetAvatarSyncErrorType(Profile* profile); // When |error| is present, this returns the string to be shown both as the // tooltip of the avatar button, and in the profile menu body (the menu opened // by clicking the avatar button). std::u16string GetAvatarSyncErrorDescription(AvatarSyncErrorType error, bool is_sync_feature_enabled); // Whether sync is currently blocked from starting because the sync // confirmation dialog hasn't been shown. Note that once the dialog is // showing (i.e. IsSetupInProgress() is true), this will return false. bool ShouldRequestSyncConfirmation(const syncer::SyncService* service); // Returns whether it makes sense to show a Sync passphrase error UI, i.e. // whether a missing passphrase is preventing Sync from fully starting up. bool ShouldShowSyncPassphraseError(const syncer::SyncService* service); // Returns whether missing trusted vault keys is preventing sync from starting // up encrypted datatypes. bool ShouldShowSyncKeysMissingError(const syncer::SyncService* sync_service, const PrefService* pref_service); // Returns whether user action is required to improve the recoverability of the // trusted vault. bool ShouldShowTrustedVaultDegradedRecoverabilityError( const syncer::SyncService* sync_service, const PrefService* pref_service); // Opens a tab for the purpose of retrieving the trusted vault keys, which // usually requires a reauth. void OpenTabForSyncKeyRetrieval( Browser* browser, syncer::TrustedVaultUserActionTriggerForUMA trigger); // Opens a tab for the purpose of improving the recoverability of the trusted // vault keys, which usually requires a reauth. void OpenTabForSyncKeyRecoverabilityDegraded( Browser* browser, syncer::TrustedVaultUserActionTriggerForUMA trigger); // Testing-only variant for the two above which allows the caller to specify the // URL. void OpenTabForSyncTrustedVaultUserActionForTesting(Browser* browser, const GURL& url); #endif // CHROME_BROWSER_SYNC_SYNC_UI_UTIL_H_
1,886
2,939
<reponame>mlwilkerson/lumen #include "lumen/EIR/Conversion/BuiltinOpConversions.h" namespace lumen { namespace eir { struct IncrementReductionsOpConversion : public EIROpConversion<IncrementReductionsOp> { using EIROpConversion::EIROpConversion; LogicalResult matchAndRewrite( IncrementReductionsOp op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const override { auto ctx = getRewriteContext(op, rewriter); ModuleOp mod = ctx.getModule(); auto i32Ty = ctx.getI32Type(); auto reductionCount = ctx.getOrInsertGlobal( "CURRENT_REDUCTION_COUNT", i32Ty, nullptr, LLVM::Linkage::External, LLVM::ThreadLocalMode::LocalExec); Value increment = llvm_constant(i32Ty, ctx.getI32Attr(op.increment())); llvm_atomicrmw(i32Ty, LLVM::AtomicBinOp::add, reductionCount, increment, LLVM::AtomicOrdering::monotonic); rewriter.eraseOp(op); return success(); } }; struct IsTypeOpConversion : public EIROpConversion<IsTypeOp> { using EIROpConversion::EIROpConversion; LogicalResult matchAndRewrite( IsTypeOp op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const override { IsTypeOpAdaptor adaptor(operands); auto ctx = getRewriteContext(op, rewriter); auto termTy = ctx.getUsizeType(); auto int1Ty = ctx.getI1Type(); auto int32Ty = ctx.getI32Type(); auto matchType = op.getMatchType().cast<OpaqueTermType>(); // Boxed types and immediate types are dispatched differently if (matchType.isBox() || matchType.isBoxable(ctx.targetInfo.immediateBits())) { OpaqueTermType boxedType; if (matchType.isBox()) { boxedType = matchType.cast<BoxType>().getBoxedType(); } else { boxedType = matchType; } // Lists have a unique pointer tag, so we can avoid the function // call if (boxedType.isa<ConsType>()) { Value listTag = llvm_constant( termTy, ctx.getIntegerAttr(ctx.targetInfo.listTag())); Value listMask = llvm_constant( termTy, ctx.getIntegerAttr(ctx.targetInfo.listMask())); Value masked = llvm_and(adaptor.value(), listMask); rewriter.replaceOpWithNewOp<LLVM::ICmpOp>( op, LLVM::ICmpPredicate::eq, listTag, masked); return success(); } // For tuples we have a dedicated op if (auto tupleType = boxedType.dyn_cast_or_null<eir::TupleType>()) { if (tupleType.hasStaticShape()) { Value arity = llvm_constant( termTy, ctx.getIntegerAttr(tupleType.getArity())); rewriter.replaceOpWithNewOp<IsTupleOp>(op, adaptor.value(), arity); return success(); } else { rewriter.replaceOpWithNewOp<IsTupleOp>(op, adaptor.value(), llvm::None); return success(); } } // For functions we have a dedicated op if (auto closureType = boxedType.dyn_cast_or_null<eir::ClosureType>()) { rewriter.replaceOpWithNewOp<IsFunctionOp>(op, adaptor.value()); return success(); } StringRef symbolName("__lumen_builtin_is_boxed_type"); // If we're matching floats but the target doesn't use boxed floats, // use the correct type check function if (boxedType.isa<FloatType>() && !ctx.targetInfo.requiresPackedFloats()) symbolName = StringRef("__lumen_builtin_is_type"); // For all other boxed types, the check is performed via builtin auto matchKind = boxedType.getTypeKind().getValue(); Value matchConst = llvm_constant(int32Ty, ctx.getI32Attr(matchKind)); auto callee = ctx.getOrInsertFunction(symbolName, int1Ty, {int32Ty, termTy}); Value input = adaptor.value(); auto calleeSymbol = FlatSymbolRefAttr::get(symbolName, callee->getContext()); Operation *isType = std_call(calleeSymbol, int1Ty, ValueRange{matchConst, input}); rewriter.replaceOp(op, isType->getResults()); return success(); } // For immediates, the check is performed via builtin // // TODO: With some additional foundation-laying, we could lower // these checks to precise bit masking/shift operations, rather // than a function call auto matchKind = matchType.getTypeKind().getValue(); Value matchConst = llvm_constant(int32Ty, ctx.getI32Attr(matchKind)); StringRef symbolName("__lumen_builtin_is_type"); auto callee = ctx.getOrInsertFunction(symbolName, int1Ty, {int32Ty, termTy}); auto calleeSymbol = FlatSymbolRefAttr::get(symbolName, callee->getContext()); Operation *isType = std_call(calleeSymbol, int1Ty, ValueRange{matchConst, adaptor.value()}); rewriter.replaceOp(op, isType->getResults()); return success(); } }; struct IsTupleOpConversion : public EIROpConversion<IsTupleOp> { using EIROpConversion::EIROpConversion; LogicalResult matchAndRewrite( IsTupleOp op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const override { IsTupleOpAdaptor adaptor(operands); auto ctx = getRewriteContext(op, rewriter); Value input = adaptor.value(); Value arity = adaptor.arity(); auto termTy = ctx.getUsizeType(); auto int1Ty = ctx.getI1Type(); auto int32Ty = ctx.getI32Type(); // When an arity is given, we use a special builtin if (arity) { ArrayRef<LLVMType> argTypes({termTy, termTy}); StringRef symbolName("__lumen_builtin_is_tuple"); auto callee = ctx.getOrInsertFunction(symbolName, int1Ty, argTypes); auto calleeSymbol = FlatSymbolRefAttr::get(symbolName, callee->getContext()); Operation *isType = std_call(calleeSymbol, int1Ty, ValueRange{arity, input}); rewriter.replaceOp(op, isType->getResults()); return success(); } // Otherwise we fall back to the generic boxed type builtin Value matchConst = llvm_constant(int32Ty, ctx.getI32Attr(TypeKind::Tuple)); StringRef symbolName("__lumen_builtin_is_boxed_type"); auto callee = ctx.getOrInsertFunction(symbolName, int1Ty, {int32Ty, termTy}); auto calleeSymbol = FlatSymbolRefAttr::get(symbolName, callee->getContext()); Operation *isType = std_call(calleeSymbol, int1Ty, ValueRange{matchConst, input}); rewriter.replaceOp(op, isType->getResults()); return success(); } }; struct IsFunctionOpConversion : public EIROpConversion<IsFunctionOp> { using EIROpConversion::EIROpConversion; LogicalResult matchAndRewrite( IsFunctionOp op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const override { IsFunctionOpAdaptor adaptor(operands); auto ctx = getRewriteContext(op, rewriter); Value input = adaptor.value(); Value arity = adaptor.arity(); auto termTy = ctx.getUsizeType(); auto int1Ty = ctx.getI1Type(); auto int32Ty = ctx.getI32Type(); // When an arity is given, we use a special builtin if (arity) { ArrayRef<LLVMType> argTypes({termTy, termTy}); StringRef symbolName("__lumen_builtin_is_function"); auto callee = ctx.getOrInsertFunction(symbolName, int1Ty, argTypes); auto calleeSymbol = FlatSymbolRefAttr::get(symbolName, callee->getContext()); Operation *isType = std_call(calleeSymbol, int1Ty, ValueRange{arity, input}); rewriter.replaceOp(op, isType->getResults()); return success(); } // Otherwise we fall back to the generic boxed type builtin Value matchConst = llvm_constant(int32Ty, ctx.getI32Attr(TypeKind::Closure)); StringRef symbolName("__lumen_builtin_is_boxed_type"); auto callee = ctx.getOrInsertFunction(symbolName, int1Ty, {int32Ty, termTy}); auto calleeSymbol = FlatSymbolRefAttr::get(symbolName, callee->getContext()); Operation *isType = std_call(calleeSymbol, int1Ty, ValueRange{matchConst, input}); rewriter.replaceOp(op, isType->getResults()); return success(); } }; struct PrintOpConversion : public EIROpConversion<PrintOp> { using EIROpConversion::EIROpConversion; LogicalResult matchAndRewrite( PrintOp op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const override { auto ctx = getRewriteContext(op, rewriter); // If print is called with no operands, just remove it for now if (operands.empty()) { rewriter.eraseOp(op); return success(); } auto termTy = ctx.getUsizeType(); StringRef symbolName("__lumen_builtin_printf"); auto callee = ctx.getOrInsertFunction(symbolName, termTy, {termTy}); auto calleeSymbol = FlatSymbolRefAttr::get(symbolName, callee->getContext()); rewriter.replaceOpWithNewOp<mlir::CallOp>(op, calleeSymbol, termTy, operands); return success(); } }; struct TraceCaptureOpConversion : public EIROpConversion<TraceCaptureOp> { using EIROpConversion::EIROpConversion; LogicalResult matchAndRewrite( TraceCaptureOp op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const override { auto ctx = getRewriteContext(op, rewriter); auto termTy = ctx.getUsizeType(); auto termPtrTy = termTy.getPointerTo(); StringRef symbolName("__lumen_builtin_trace.capture"); auto callee = ctx.getOrInsertFunction(symbolName, termPtrTy, {}); auto calleeSymbol = FlatSymbolRefAttr::get(symbolName, callee->getContext()); rewriter.replaceOpWithNewOp<mlir::CallOp>(op, calleeSymbol, ArrayRef<Type>{termPtrTy}); return success(); } }; struct TracePrintOpConversion : public EIROpConversion<TracePrintOp> { using EIROpConversion::EIROpConversion; LogicalResult matchAndRewrite( TracePrintOp op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const override { auto ctx = getRewriteContext(op, rewriter); TracePrintOpAdaptor adaptor(operands); Value kind = adaptor.kind(); Value reason = adaptor.reason(); Value traceRef = adaptor.traceRef(); auto termTy = ctx.getUsizeType(); auto termPtrTy = termTy.getPointerTo(); auto voidTy = LLVMType::getVoidTy(ctx.context); StringRef symbolName("__lumen_builtin_trace.print"); auto callee = ctx.getOrInsertFunction(symbolName, voidTy, {termTy, termTy, termPtrTy}); auto calleeSymbol = FlatSymbolRefAttr::get(symbolName, callee->getContext()); rewriter.replaceOpWithNewOp<mlir::CallOp>( op, calleeSymbol, ArrayRef<Type>{}, ArrayRef<Value>{kind, reason, traceRef}); return success(); } }; struct TraceConstructOpConversion : public EIROpConversion<TraceConstructOp> { using EIROpConversion::EIROpConversion; LogicalResult matchAndRewrite( TraceConstructOp op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const override { auto ctx = getRewriteContext(op, rewriter); TraceConstructOpAdaptor adaptor(operands); Value traceRef = adaptor.traceRef(); auto termTy = ctx.getUsizeType(); auto termPtrTy = termTy.getPointerTo(); StringRef symbolName("__lumen_builtin_trace.construct"); auto callee = ctx.getOrInsertFunction(symbolName, termTy, {termPtrTy}); auto calleeSymbol = FlatSymbolRefAttr::get(symbolName, callee->getContext()); rewriter.replaceOpWithNewOp<mlir::CallOp>(op, calleeSymbol, termTy, ValueRange(traceRef)); return success(); } }; void populateBuiltinOpConversionPatterns(OwningRewritePatternList &patterns, MLIRContext *context, EirTypeConverter &converter, TargetInfo &targetInfo) { patterns.insert<IncrementReductionsOpConversion, IsTypeOpConversion, IsTupleOpConversion, IsFunctionOpConversion, PrintOpConversion, TraceCaptureOpConversion, TraceConstructOpConversion, TracePrintOpConversion>( context, converter, targetInfo); } } // namespace eir } // namespace lumen
6,218
374
#import <objc/runtime.h> struct objc_super { id receiver; Class super_class; }; OBJC_EXPORT id objc_msgSend(id self, SEL selector, ...); OBJC_EXPORT id objc_msgSendSuper(struct objc_super *super, SEL op, ...); OBJC_EXPORT void objc_msgSend_stret(id self, SEL selector, ...); OBJC_EXPORT void objc_msgSendSuper_stret(struct objc_super *super, SEL selector, ...); OBJC_EXPORT double objc_msgSend_fpret(id self, SEL selector, ...); // FIXME. TO BE CLEANED UP. OBJC_EXPORT IMP objc_msg_lookup(id self, SEL selector); OBJC_EXPORT IMP objc_msg_lookup_super(struct objc_super *super, SEL selector);
236
670
<gh_stars>100-1000 # import numpy import numpy as np # define our sigmoid function def sigmoid(x): return 1/ (1 + np.exp(-x)) # craete the AN class Neuron: def __init__(self, weights, bias): self.weights = weights self.bias = bias def feedforwards(self, inputs): total = np.dot(self.weights, inputs) + self.bias return sigmoid(total) weights = np.array([0, 1]) bias = 4 neuron = Neuron(weights, bias) x = np.array([2, 3]) forward = neuron.feedforwards(x) print(forward)
198
496
/* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. 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 co.elastic.apm.agent.matcher; import org.stagemonitor.util.StringUtils; import javax.annotation.Nullable; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import static co.elastic.apm.agent.matcher.AnnotationMatcher.annotationMatcher; import static co.elastic.apm.agent.matcher.WildcardMatcher.caseSensitiveMatcher; public class MethodMatcher { private static final String MODIFIER = "(?<modifier>public|private|protected|\\*)"; private static final String ANNOTATION = "((?<annotation>@@?[a-zA-Z\\d_$.\\*]+)\\s+)?"; private static final String CLASS_NAME = "(?<clazz>[a-zA-Z\\d_$.\\*]+)"; private static final String METHOD_NAME = "(?<method>[a-zA-Z\\d_$\\*]+)"; private static final String PARAM = "([a-zA-Z\\d_$.\\[\\]\\*]+)"; private static final String PARAMS = PARAM + "(,\\s*" + PARAM + ")*"; private static final Pattern METHOD_MATCHER_PATTERN = Pattern.compile("^(" + MODIFIER + "\\s+)?" + ANNOTATION + CLASS_NAME + "(#" + METHOD_NAME + "(?<params>\\((" + PARAMS + ")*\\))?)?$"); private final String stringRepresentation; @Nullable private final Integer modifier; private final AnnotationMatcher annotationMatcher; private final WildcardMatcher classMatcher; private final WildcardMatcher methodMatcher; @Nullable private final List<WildcardMatcher> argumentMatchers; private MethodMatcher(String stringRepresentation, @Nullable Integer modifier, AnnotationMatcher annotationMatcher, WildcardMatcher classMatcher, WildcardMatcher methodMatcher, @Nullable List<WildcardMatcher> argumentMatchers) { this.stringRepresentation = stringRepresentation; this.modifier = modifier; this.annotationMatcher = annotationMatcher; this.classMatcher = classMatcher; this.methodMatcher = methodMatcher; this.argumentMatchers = argumentMatchers; } public static MethodMatcher of(String methodMatcher) { final Matcher matcher = METHOD_MATCHER_PATTERN.matcher(methodMatcher); if (!matcher.matches()) { throw new IllegalArgumentException("'" + methodMatcher + "'" + " is not a valid method matcher"); } final String modifier = matcher.group("modifier"); final AnnotationMatcher annotationMatcher = matcher.group("annotation") != null ? annotationMatcher(matcher.group("annotation")) : AnnotationMatcher.matchAll(); final WildcardMatcher clazz = caseSensitiveMatcher(matcher.group("clazz")); final WildcardMatcher method = matcher.group("method") != null ? caseSensitiveMatcher(matcher.group("method")) : WildcardMatcher.matchAll(); final List<WildcardMatcher> args = getArgumentMatchers(matcher.group("params")); return new MethodMatcher(methodMatcher, getModifier(modifier), annotationMatcher, clazz, method, args); } @Nullable private static Integer getModifier(@Nullable String modifier) { if (modifier == null) { return null; } switch (modifier) { case "public": return Modifier.PUBLIC; case "private": return Modifier.PRIVATE; case "protected": return Modifier.PROTECTED; default: return null; } } @Nullable private static List<WildcardMatcher> getArgumentMatchers(@Nullable String arguments) { if (arguments == null) { return null; } // remove parenthesis arguments = arguments.substring(1, arguments.length() - 1); final String[] splitArguments = StringUtils.split(arguments, ','); List<WildcardMatcher> matchers = new ArrayList<>(splitArguments.length); for (String argument : splitArguments) { matchers.add(caseSensitiveMatcher(argument.trim())); } return matchers; } public AnnotationMatcher getAnnotationMatcher() { return annotationMatcher; } public WildcardMatcher getClassMatcher() { return classMatcher; } @Nullable public Integer getModifier() { return modifier; } public WildcardMatcher getMethodMatcher() { return methodMatcher; } @Nullable public List<WildcardMatcher> getArgumentMatchers() { return argumentMatchers; } @Override public String toString() { return stringRepresentation; } }
1,911
678
/** * This header is generated by class-dump-z 0.2b. * * Source: /System/Library/PrivateFrameworks/RemoteUI.framework/RemoteUI */ /* iOSOpenDev: commented-out (since already defined in SDK) typedef struct _opaque_pthread_mutex_t { long __sig; BOOL __opaque[40]; } opaque_pthread_mutex_t; */ // iOSOpenDev: wrapped with define check (since occurs in other dumped files) // iOSOpenDev: added (since definition was commented-out) #ifndef __opaque_pthread_mutex_t__ #define __opaque_pthread_mutex_t__ 1 typedef struct _opaque_pthread_mutex_t opaque_pthread_mutex_t; #endif /* iOSOpenDev: commented-out (since already defined in SDK) typedef struct _opaque_pthread_cond_t { long __sig; BOOL __opaque[24]; } opaque_pthread_cond_t; */ // iOSOpenDev: added (since definition was commented-out) // iOSOpenDev: wrapped with define check (since occurs in other dumped files) #ifndef __opaque_pthread_cond_t__ #define __opaque_pthread_cond_t__ 1 typedef struct _opaque_pthread_cond_t opaque_pthread_cond_t; #endif // iOSOpenDev: wrapped with define check (since occurs in other dumped files) #ifndef __OpaqueJSContext__ #define __OpaqueJSContext__ 1 typedef struct OpaqueJSContext OpaqueJSContext; #endif
416
517
<reponame>mlapierre/Selenium-Grid-Extras<filename>SeleniumGridExtras/src/test/java/com/groupon/seleniumgridextras/utilities/TempUtilityTest.java package com.groupon.seleniumgridextras.utilities; import org.junit.Test; import java.io.File; import static org.junit.Assert.assertEquals; public class TempUtilityTest { @Test public void testGetWindowsTempForCurrentUser() throws Exception { File expected = new File(System.getProperty("user.home"), "AppData/Local/Temp"); assertEquals(expected, TempUtility.getWindowsTempForCurrentUser()); } @Test public void testGetLinuxTempDir() throws Exception{ assertEquals(new File("/tmp"), TempUtility.getLinuxTemp()); } }
249
1,350
<filename>sdk/resourcemanager/azure-resourcemanager-cosmos/src/main/java/com/azure/resourcemanager/cosmos/models/ThroughputSettingsResource.java // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.cosmos.models; import com.azure.core.annotation.Fluent; import com.azure.core.util.logging.ClientLogger; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; /** * Cosmos DB resource throughput object. Either throughput is required or autoscaleSettings is required, but not both. */ @Fluent public class ThroughputSettingsResource { @JsonIgnore private final ClientLogger logger = new ClientLogger(ThroughputSettingsResource.class); /* * Value of the Cosmos DB resource throughput. Either throughput is * required or autoscaleSettings is required, but not both. */ @JsonProperty(value = "throughput") private Integer throughput; /* * Cosmos DB resource for autoscale settings. Either throughput is required * or autoscaleSettings is required, but not both. */ @JsonProperty(value = "autoscaleSettings") private AutoscaleSettingsResource autoscaleSettings; /* * The minimum throughput of the resource */ @JsonProperty(value = "minimumThroughput", access = JsonProperty.Access.WRITE_ONLY) private String minimumThroughput; /* * The throughput replace is pending */ @JsonProperty(value = "offerReplacePending", access = JsonProperty.Access.WRITE_ONLY) private String offerReplacePending; /** * Get the throughput property: Value of the Cosmos DB resource throughput. Either throughput is required or * autoscaleSettings is required, but not both. * * @return the throughput value. */ public Integer throughput() { return this.throughput; } /** * Set the throughput property: Value of the Cosmos DB resource throughput. Either throughput is required or * autoscaleSettings is required, but not both. * * @param throughput the throughput value to set. * @return the ThroughputSettingsResource object itself. */ public ThroughputSettingsResource withThroughput(Integer throughput) { this.throughput = throughput; return this; } /** * Get the autoscaleSettings property: Cosmos DB resource for autoscale settings. Either throughput is required or * autoscaleSettings is required, but not both. * * @return the autoscaleSettings value. */ public AutoscaleSettingsResource autoscaleSettings() { return this.autoscaleSettings; } /** * Set the autoscaleSettings property: Cosmos DB resource for autoscale settings. Either throughput is required or * autoscaleSettings is required, but not both. * * @param autoscaleSettings the autoscaleSettings value to set. * @return the ThroughputSettingsResource object itself. */ public ThroughputSettingsResource withAutoscaleSettings(AutoscaleSettingsResource autoscaleSettings) { this.autoscaleSettings = autoscaleSettings; return this; } /** * Get the minimumThroughput property: The minimum throughput of the resource. * * @return the minimumThroughput value. */ public String minimumThroughput() { return this.minimumThroughput; } /** * Get the offerReplacePending property: The throughput replace is pending. * * @return the offerReplacePending value. */ public String offerReplacePending() { return this.offerReplacePending; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { if (autoscaleSettings() != null) { autoscaleSettings().validate(); } } }
1,308
373
# BASE = "https://lingon.ladok.umu.se" BASE = "https://localhost" # If BASE is https these has to be specified SERVER_CERT = "certs/server.crt" SERVER_KEY = "certs/server.key" CA_BUNDLE = None CERT_CHAIN = None VERIFY_SSL = False # information used when registering the client, this may be the same for all OPs ME = { "application_type": "web", "application_name": "idpproxy", "contacts": ["<EMAIL>"], "redirect_uris": ["{base}authz_cb"], "post_logout_redirect_uris": ["{base}logout_success"], "response_types": ["code"], 'token_endpoint_auth_method': ['private_key_jwt'] } BEHAVIOUR = { "response_type": "code", "scope": ["openid", "profile", "email", "address", "phone"], } ACR_VALUES = ["<PASSWORD>"] # The keys in this dictionary are the OPs short userfriendly name # not the issuer (iss) name. CLIENTS = { # The ones that support webfinger, OP discovery and client registration # This is the default, any client that is not listed here is expected to # support dynamic discovery and registration. "": { "client_info": ME, "behaviour": BEHAVIOUR }, } KEY_SPECIFICATION = [ {"type": "RSA", "key": "keys/pyoidc_enc", "use": ["enc"]}, {"type": "RSA", "key": "keys/pyoidc_sig", "use": ["sig"]}, {"type": "EC", "crv": "P-256", "use": ["sig"]}, {"type": "EC", "crv": "P-256", "use": ["enc"]} ] CLIENT_TYPE = 'OAUTH2' # one of OIDC/OAUTH2 USERINFO = False
580
1,781
<reponame>yulin2/UltimateAndroid<gh_stars>1000+ package com.marshalchen.common.demoofui.flipviewpager.activity; import android.content.Context; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.marshalchen.common.demoofui.R; import com.marshalchen.common.demoofui.flipviewpager.Utils; import com.marshalchen.common.demoofui.flipviewpager.model.Friend; import com.yalantis.flipviewpager.adapter.BaseFlipAdapter; import com.yalantis.flipviewpager.utils.FlipSettings; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * @author Yalantis */ public class FlipViewPagerFriendActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.flip_view_pager_activity_friends); final ListView friends = (ListView) findViewById(R.id.friends); FlipSettings settings = new FlipSettings.Builder().defaultPage(1).build(); friends.setAdapter(new FriendsAdapter(this, Utils.friends, settings)); friends.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Friend f = (Friend) friends.getAdapter().getItem(position); Toast.makeText(FlipViewPagerFriendActivity.this, f.getNickname(), Toast.LENGTH_SHORT).show(); } }); } class FriendsAdapter extends BaseFlipAdapter<Friend> { private final int PAGES = 3; private int[] IDS_INTEREST = {R.id.interest_1, R.id.interest_2, R.id.interest_3, R.id.interest_4, R.id.interest_5}; public FriendsAdapter(Context context, List<Friend> items, FlipSettings settings) { super(context, items, settings); } @Override public View getPage(int position, View convertView, ViewGroup parent, Friend friend1, Friend friend2) { final FriendsHolder holder; if (convertView == null) { holder = new FriendsHolder(); convertView = getLayoutInflater().inflate(R.layout.flip_view_pager_friends_merge_page, parent, false); holder.leftAvatar = (ImageView) convertView.findViewById(R.id.first); holder.rightAvatar = (ImageView) convertView.findViewById(R.id.second); holder.infoPage = getLayoutInflater().inflate(R.layout.flip_view_pager_friends_info, parent, false); holder.nickName = (TextView) holder.infoPage.findViewById(R.id.nickname); for (int id : IDS_INTEREST) holder.interests.add((TextView) holder.infoPage.findViewById(id)); convertView.setTag(holder); } else { holder = (FriendsHolder) convertView.getTag(); } switch (position) { // Merged page with 2 friends case 1: holder.leftAvatar.setImageResource(friend1.getAvatar()); if (friend2 != null) holder.rightAvatar.setImageResource(friend2.getAvatar()); break; default: fillHolder(holder, position == 0 ? friend1 : friend2); holder.infoPage.setTag(holder); return holder.infoPage; } return convertView; } @Override public int getPagesCount() { return PAGES; } private void fillHolder(FriendsHolder holder, Friend friend) { if (friend == null) return; Iterator<TextView> iViews = holder.interests.iterator(); Iterator<String> iInterests = friend.getInterests().iterator(); while (iViews.hasNext() && iInterests.hasNext()) iViews.next().setText(iInterests.next()); holder.infoPage.setBackgroundColor(getResources().getColor(friend.getBackground())); holder.nickName.setText(friend.getNickname()); } class FriendsHolder { ImageView leftAvatar; ImageView rightAvatar; View infoPage; List<TextView> interests = new ArrayList<>(); TextView nickName; } } }
1,997
440
/*========================== begin_copyright_notice ============================ Copyright (C) 2021 Intel Corporation SPDX-License-Identifier: MIT ============================= end_copyright_notice ===========================*/ #include "wa_def.h" #define XE_HP_SDV_GT_REV_ID_A0 SI_REV_ID(0,0) //******************* Main Wa Initializer for Device Id ******************** // Initialize COMMON/DESKTOP/MOBILE WA using PLATFORM_STEP_APPLICABLE() macro. void InitXeHPSDVSwWaTable(PWA_TABLE pWaTable, PSKU_FEATURE_TABLE pSkuTable, PWA_INIT_PARAM pWaParam) { int StepId_XeHP_SDV = (int)pWaParam->usRevId; #ifdef __KCH // compilation issue with UTF: KCHASSERT(NULL != pWaParam); #endif //================================================================================================================= // // XeHP_SDV SW WA for all platforms // //================================================================================================================= } #ifdef __KCH void InitXeHPSDVHASWaTable(PHW_DEVICE_EXTENSION pKchContext, PWA_TABLE pWaTable, PSKU_FEATURE_TABLE pSkuTable, PWA_INIT_PARAM pWaParam) { } #endif // __KCH
382
364
// File // doc/quickbook/oglplus/quickref/enums/transform_feedback_primitive_type_class.hpp // // Automatically generated file, DO NOT modify manually. // Edit the source 'source/enums/oglplus/transform_feedback_primitive_type.txt' // or the 'source/enums/make_enum.py' script instead. // // Copyright 2010-2019 <NAME>. // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt // //[oglplus_enums_transform_feedback_primitive_type_class #if !__OGLPLUS_NO_ENUM_VALUE_CLASSES namespace enums { template < typename Base, template <__TransformFeedbackPrimitiveType> class Transform> class __EnumToClass<Base, __TransformFeedbackPrimitiveType, Transform> /*< Specialization of __EnumToClass for the __TransformFeedbackPrimitiveType enumeration. >*/ : public Base { public: EnumToClass(); EnumToClass(Base&& base); Transform<TransformFeedbackPrimitiveType::Triangles> Triangles; Transform<TransformFeedbackPrimitiveType::Lines> Lines; Transform<TransformFeedbackPrimitiveType::Points> Points; }; } // namespace enums #endif //]
384
777
{ "name": "lifecycle_unittest_app", "display_name": "Lifecycle Unittest App", "interface_provider_specs": { "service_manager:connector": { "provides": { "lifecycle_unittest:lifecycle_control": [ "service_manager::test::mojom::LifecycleControl" ] } } } }
143
22,481
<gh_stars>1000+ """SmartTub integration.""" from homeassistant.const import Platform from .const import DOMAIN, SMARTTUB_CONTROLLER from .controller import SmartTubController PLATFORMS = [ Platform.BINARY_SENSOR, Platform.CLIMATE, Platform.LIGHT, Platform.SENSOR, Platform.SWITCH, ] async def async_setup_entry(hass, entry): """Set up a smarttub config entry.""" controller = SmartTubController(hass) hass.data.setdefault(DOMAIN, {}) hass.data[DOMAIN][entry.entry_id] = { SMARTTUB_CONTROLLER: controller, } if not await controller.async_setup_entry(entry): return False hass.config_entries.async_setup_platforms(entry, PLATFORMS) return True async def async_unload_entry(hass, entry): """Remove a smarttub config entry.""" unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS) if unload_ok: hass.data[DOMAIN].pop(entry.entry_id) return unload_ok
390