max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
1,470
package com.guiying.module.common.http; /** * <p>在Retrofit中接口会导致泛型擦除,所以这里回调使用Class</p> * * @author 张华洋 2016/12/15 10:27 * @version V1.0.0 * @name OnResultListener */ public class OnResultListener<T> { /** * 请求成功的情况 * * @param result 需要解析的解析类 */ public void onSuccess(T result) { } /** * 响应成功,但是出错的情况 * * @param code 错误码 * @param message 错误信息 */ public void onError(int code, String message) { } /** * 请求失败的情况 * * @param message 失败信息 */ public void onFailure(String message) { } }
397
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 OOX_XLS_STYLESBUFFER_HXX #define OOX_XLS_STYLESBUFFER_HXX #include <com/sun/star/awt/FontDescriptor.hpp> #include <com/sun/star/table/CellHoriJustify.hpp> #include <com/sun/star/table/CellOrientation.hpp> #include <com/sun/star/table/CellVertJustify.hpp> #include <com/sun/star/table/TableBorder.hpp> #include <com/sun/star/util/CellProtection.hpp> #include "oox/drawingml/color.hxx" #include "oox/helper/graphichelper.hxx" #include "oox/helper/refmap.hxx" #include "oox/helper/refvector.hxx" #include "oox/xls/numberformatsbuffer.hxx" namespace com { namespace sun { namespace star { namespace awt { struct FontDescrtiptor; } } } } namespace oox { class PropertySet; } namespace oox { namespace xls { // ============================================================================ const sal_Int32 OOX_COLOR_WINDOWTEXT3 = 24; /// System window text color (BIFF3-BIFF4). const sal_Int32 OOX_COLOR_WINDOWBACK3 = 25; /// System window background color (BIFF3-BIFF4). const sal_Int32 OOX_COLOR_WINDOWTEXT = 64; /// System window text color (BIFF5+). const sal_Int32 OOX_COLOR_WINDOWBACK = 65; /// System window background color (BIFF5+). const sal_Int32 OOX_COLOR_BUTTONBACK = 67; /// System button background color (face color). const sal_Int32 OOX_COLOR_CHWINDOWTEXT = 77; /// System window text color (BIFF8 charts). const sal_Int32 OOX_COLOR_CHWINDOWBACK = 78; /// System window background color (BIFF8 charts). const sal_Int32 OOX_COLOR_CHBORDERAUTO = 79; /// Automatic frame border (BIFF8 charts). const sal_Int32 OOX_COLOR_NOTEBACK = 80; /// Note background color. const sal_Int32 OOX_COLOR_NOTETEXT = 81; /// Note text color. const sal_Int32 OOX_COLOR_FONTAUTO = 0x7FFF; /// Font auto color (system window text color). // ---------------------------------------------------------------------------- const sal_Int16 API_LINE_NONE = 0; const sal_Int16 API_LINE_HAIR = 2; const sal_Int16 API_LINE_THIN = 35; const sal_Int16 API_LINE_MEDIUM = 88; const sal_Int16 API_LINE_THICK = 141; const sal_Int16 API_ESCAPE_NONE = 0; /// No escapement. const sal_Int16 API_ESCAPE_SUPERSCRIPT = 101; /// Superscript: raise characters automatically (magic value 101). const sal_Int16 API_ESCAPE_SUBSCRIPT = -101; /// Subscript: lower characters automatically (magic value -101). const sal_Int8 API_ESCAPEHEIGHT_NONE = 100; /// Relative character height if not escaped. const sal_Int8 API_ESCAPEHEIGHT_DEFAULT = 58; /// Relative character height if escaped. // ============================================================================ /** Special implementation of the GraphicHelper for Excel palette and scheme colors. */ class ExcelGraphicHelper : public GraphicHelper, public WorkbookHelper { public: explicit ExcelGraphicHelper( const WorkbookHelper& rHelper ); /** Derived classes may implement to resolve a scheme color from the passed XML token identifier. */ virtual sal_Int32 getSchemeColor( sal_Int32 nToken ) const; /** Derived classes may implement to resolve a palette index to an RGB color. */ virtual sal_Int32 getPaletteColor( sal_Int32 nPaletteIdx ) const; }; // ============================================================================ class Color : public ::oox::drawingml::Color { public: /** Sets the color to automatic. */ void setAuto(); /** Sets the color to the passed RGB value. */ void setRgb( sal_Int32 nRgbValue, double fTint = 0.0 ); /** Sets the color to the passed theme index. */ void setTheme( sal_Int32 nThemeIdx, double fTint = 0.0 ); /** Sets the color to the passed palette index. */ void setIndexed( sal_Int32 nPaletteIdx, double fTint = 0.0 ); /** Imports the color from the passed attribute list. */ void importColor( const AttributeList& rAttribs ); /** Imports a 64-bit color from the passed binary stream. */ void importColor( SequenceInputStream& rStrm ); /** Imports a 32-bit palette color identifier from the passed BIFF12 stream. */ void importColorId( SequenceInputStream& rStrm ); /** Imports a 32-bit RGBA color value from the passed BIFF12 stream. */ void importColorRgb( SequenceInputStream& rStrm ); /** Imports an 8-bit or 16-bit palette color identifier from the passed BIFF stream. */ void importColorId( BiffInputStream& rStrm, bool b16Bit = true ); /** Imports a 32-bit RGBA color value from the passed BIFF stream. */ void importColorRgb( BiffInputStream& rStrm ); /** Returns true, if the color is set to automatic. */ inline bool isAuto() const { return isPlaceHolder(); } }; // ---------------------------------------------------------------------------- SequenceInputStream& operator>>( SequenceInputStream& rStrm, Color& orColor ); // ============================================================================ /** Stores all colors of the color palette. */ class ColorPalette : public WorkbookHelper { public: /** Constructs the color palette with predefined color values. */ explicit ColorPalette( const WorkbookHelper& rHelper ); /** Appends a new color from the passed attributes. */ void importPaletteColor( const AttributeList& rAttribs ); /** Appends a new color from the passed RGBCOLOR record. */ void importPaletteColor( SequenceInputStream& rStrm ); /** Imports the PALETTE record from the passed stream. */ void importPalette( BiffInputStream& rStrm ); /** Imports a color palette from a UNO sequence in the passed any. */ void importPalette( const ::com::sun::star::uno::Any& rPalette ); /** Rturns the RGB value of the color with the passed index. */ sal_Int32 getColor( sal_Int32 nPaletteIdx ) const; private: /** Appends the passed color. */ void appendColor( sal_Int32 nRGBValue ); private: ::std::vector< sal_Int32 > maColors; /// List of RGB values. size_t mnAppendIndex; /// Index to append a new color. }; // ============================================================================ /** Contains all XML font attributes, e.g. from a font or rPr element. */ struct FontModel { ::rtl::OUString maName; /// Font name. Color maColor; /// Font color. sal_Int32 mnScheme; /// Major/minor scheme font. sal_Int32 mnFamily; /// Font family. sal_Int32 mnCharSet; /// Windows font character set. double mfHeight; /// Font height in points. sal_Int32 mnUnderline; /// Underline style. sal_Int32 mnEscapement; /// Escapement style. bool mbBold; /// True = bold characters. bool mbItalic; /// True = italic characters. bool mbStrikeout; /// True = Strike out characters. bool mbOutline; /// True = outlined characters. bool mbShadow; /// True = shadowed chgaracters. explicit FontModel(); void setBiff12Scheme( sal_uInt8 nScheme ); void setBiffHeight( sal_uInt16 nHeight ); void setBiffWeight( sal_uInt16 nWeight ); void setBiffUnderline( sal_uInt16 nUnderline ); void setBiffEscapement( sal_uInt16 nEscapement ); }; // ---------------------------------------------------------------------------- /** Enumerates different types of API font property sets. */ enum FontPropertyType { FONT_PROPTYPE_CELL, /// Font properties in a spreadsheet cell (table::Cell service). FONT_PROPTYPE_TEXT /// Font properties in a text object (text::Text service). }; // ---------------------------------------------------------------------------- /** Contains used flags for all API font attributes. */ struct ApiFontUsedFlags { bool mbNameUsed; /// True = font name/family/char set are used. bool mbColorUsed; /// True = font color is used. bool mbSchemeUsed; /// True = font scheme is used. bool mbHeightUsed; /// True = font height is used. bool mbUnderlineUsed; /// True = underline style is used. bool mbEscapementUsed; /// True = escapement style is used. bool mbWeightUsed; /// True = font weight (boldness) is used. bool mbPostureUsed; /// True = font posture (italic) is used. bool mbStrikeoutUsed; /// True = strike out style is used. bool mbOutlineUsed; /// True = outline style is used. bool mbShadowUsed; /// True = shadow style is used. explicit ApiFontUsedFlags( bool bAllUsed ); }; // ---------------------------------------------------------------------------- /** Contains API font name, family, and charset for a script type. */ struct ApiScriptFontName { ::rtl::OUString maName; /// Font name. sal_Int16 mnFamily; /// Font family. sal_Int16 mnTextEnc; /// Font text encoding. explicit ApiScriptFontName(); }; // ---------------------------------------------------------------------------- /** Contains all API font attributes. */ struct ApiFontData { typedef ::com::sun::star::awt::FontDescriptor ApiFontDescriptor; ApiScriptFontName maLatinFont; /// Font name for latin scripts. ApiScriptFontName maAsianFont; /// Font name for east-asian scripts. ApiScriptFontName maCmplxFont; /// Font name for complex scripts. ApiFontDescriptor maDesc; /// Font descriptor (height in twips, weight in %). sal_Int32 mnColor; /// Font color. sal_Int16 mnEscapement; /// Escapement style. sal_Int8 mnEscapeHeight; /// Escapement font height. bool mbOutline; /// True = outlined characters. bool mbShadow; /// True = shadowed chgaracters. explicit ApiFontData(); }; // ============================================================================ class Font : public WorkbookHelper { public: explicit Font( const WorkbookHelper& rHelper, bool bDxf ); explicit Font( const WorkbookHelper& rHelper, const FontModel& rModel ); /** Sets font formatting attributes for the passed element. */ void importAttribs( sal_Int32 nElement, const AttributeList& rAttribs ); /** Imports the FONT record from the passed stream. */ void importFont( SequenceInputStream& rStrm ); /** Imports the font name from a DXF record. */ void importDxfName( SequenceInputStream& rStrm ); /** Imports the font color from a DXF record. */ void importDxfColor( SequenceInputStream& rStrm ); /** Imports the font scheme from a DXF record. */ void importDxfScheme( SequenceInputStream& rStrm ); /** Imports the font height from a DXF record. */ void importDxfHeight( SequenceInputStream& rStrm ); /** Imports the font weight from a DXF record. */ void importDxfWeight( SequenceInputStream& rStrm ); /** Imports the font underline style from a DXF record. */ void importDxfUnderline( SequenceInputStream& rStrm ); /** Imports the font escapement style from a DXF record. */ void importDxfEscapement( SequenceInputStream& rStrm ); /** Imports a font style flag from a DXF record. */ void importDxfFlag( sal_Int32 nElement, SequenceInputStream& rStrm ); /** Imports the FONT record from the passed stream. */ void importFont( BiffInputStream& rStrm ); /** Imports the FONTCOLOR record from the passed stream. */ void importFontColor( BiffInputStream& rStrm ); /** Sets the font attributes from the font block of a CFRULE record. */ void importCfRule( BiffInputStream& rStrm ); /** Returns the font model structure. This function can be called before finalizeImport() has been called. */ inline const FontModel& getModel() const { return maModel; } /** Returns the text encoding for strings used with this font. This function can be called before finalizeImport() has been called. */ rtl_TextEncoding getFontEncoding() const; /** Final processing after import of all style settings. */ void finalizeImport(); /** Returns an API font descriptor with own font information. */ const ::com::sun::star::awt::FontDescriptor& getFontDescriptor() const; /** Returns true, if the font requires rich text formatting in Calc. @descr Example: Font escapement is a cell attribute in Excel, but Calc needs an rich text cell for this attribute. */ bool needsRichTextFormat() const; /** Writes all font attributes to the passed property map. */ void writeToPropertyMap( PropertyMap& rPropMap, FontPropertyType ePropType ) const; /** Writes all font attributes to the passed property set. */ void writeToPropertySet( PropertySet& rPropSet, FontPropertyType ePropType ) const; private: /** Reads and sets height and flags. */ void importFontData2( BiffInputStream& rStrm ); /** Reads and sets weight, escapement, underline, family, charset (BIFF5+). */ void importFontData5( BiffInputStream& rStrm ); /** Reads and sets a byte string as font name. */ void importFontName2( BiffInputStream& rStrm ); /** Reads and sets a Unicode string as font name. */ void importFontName8( BiffInputStream& rStrm ); private: FontModel maModel; ApiFontData maApiData; ApiFontUsedFlags maUsedFlags; bool mbDxf; }; typedef ::boost::shared_ptr< Font > FontRef; // ============================================================================ /** Contains all XML cell alignment attributes, e.g. from an alignment element. */ struct AlignmentModel { sal_Int32 mnHorAlign; /// Horizontal alignment. sal_Int32 mnVerAlign; /// Vertical alignment. sal_Int32 mnTextDir; /// CTL text direction. sal_Int32 mnRotation; /// Text rotation angle. sal_Int32 mnIndent; /// Indentation. bool mbWrapText; /// True = multi-line text. bool mbShrink; /// True = shrink to fit cell size. bool mbJustLastLine; /// True = justify last line in block text. explicit AlignmentModel(); /** Sets horizontal alignment from the passed BIFF data. */ void setBiffHorAlign( sal_uInt8 nHorAlign ); /** Sets vertical alignment from the passed BIFF data. */ void setBiffVerAlign( sal_uInt8 nVerAlign ); /** Sets rotation from the passed BIFF text orientation. */ void setBiffTextOrient( sal_uInt8 nTextOrient ); }; // ---------------------------------------------------------------------------- /** Contains all API cell alignment attributes. */ struct ApiAlignmentData { typedef ::com::sun::star::table::CellHoriJustify ApiCellHoriJustify; typedef ::com::sun::star::table::CellVertJustify ApiCellVertJustify; typedef ::com::sun::star::table::CellOrientation ApiCellOrientation; ApiCellHoriJustify meHorJustify; /// Horizontal alignment. ApiCellVertJustify meVerJustify; /// Vertical alignment. ApiCellOrientation meOrientation; /// Normal or stacked text. sal_Int32 mnRotation; /// Text rotation angle. sal_Int16 mnWritingMode; /// CTL text direction. sal_Int16 mnIndent; /// Indentation. bool mbWrapText; /// True = multi-line text. bool mbShrink; /// True = shrink to fit cell size. explicit ApiAlignmentData(); }; bool operator==( const ApiAlignmentData& rLeft, const ApiAlignmentData& rRight ); // ============================================================================ class Alignment : public WorkbookHelper { public: explicit Alignment( const WorkbookHelper& rHelper ); /** Sets all attributes from the alignment element. */ void importAlignment( const AttributeList& rAttribs ); /** Sets the alignment attributes from the passed BIFF12 XF record data. */ void setBiff12Data( sal_uInt32 nFlags ); /** Sets the alignment attributes from the passed BIFF2 XF record data. */ void setBiff2Data( sal_uInt8 nFlags ); /** Sets the alignment attributes from the passed BIFF3 XF record data. */ void setBiff3Data( sal_uInt16 nAlign ); /** Sets the alignment attributes from the passed BIFF4 XF record data. */ void setBiff4Data( sal_uInt16 nAlign ); /** Sets the alignment attributes from the passed BIFF5 XF record data. */ void setBiff5Data( sal_uInt16 nAlign ); /** Sets the alignment attributes from the passed BIFF8 XF record data. */ void setBiff8Data( sal_uInt16 nAlign, sal_uInt16 nMiscAttrib ); /** Final processing after import of all style settings. */ void finalizeImport(); /** Returns the alignment model structure. */ inline const AlignmentModel& getModel() const { return maModel; } /** Returns the converted API alignment data struct. */ inline const ApiAlignmentData& getApiData() const { return maApiData; } /** Writes all alignment attributes to the passed property map. */ void writeToPropertyMap( PropertyMap& rPropMap ) const; private: AlignmentModel maModel; /// Alignment model data. ApiAlignmentData maApiData; /// Alignment data converted to API constants. }; typedef ::boost::shared_ptr< Alignment > AlignmentRef; // ============================================================================ /** Contains all XML cell protection attributes, e.g. from a protection element. */ struct ProtectionModel { bool mbLocked; /// True = locked against editing. bool mbHidden; /// True = formula is hidden. explicit ProtectionModel(); }; // ---------------------------------------------------------------------------- /** Contains all API cell protection attributes. */ struct ApiProtectionData { typedef ::com::sun::star::util::CellProtection ApiCellProtection; ApiCellProtection maCellProt; explicit ApiProtectionData(); }; bool operator==( const ApiProtectionData& rLeft, const ApiProtectionData& rRight ); // ============================================================================ class Protection : public WorkbookHelper { public: explicit Protection( const WorkbookHelper& rHelper ); /** Sets all attributes from the protection element. */ void importProtection( const AttributeList& rAttribs ); /** Sets the protection attributes from the passed BIFF12 XF record data. */ void setBiff12Data( sal_uInt32 nFlags ); /** Sets the protection attributes from the passed BIFF2 XF record data. */ void setBiff2Data( sal_uInt8 nNumFmt ); /** Sets the protection attributes from the passed BIFF3-BIFF8 XF record data. */ void setBiff3Data( sal_uInt16 nProt ); /** Final processing after import of all style settings. */ void finalizeImport(); /** Returns the protection model structure. */ inline const ProtectionModel& getModel() const { return maModel; } /** Returns the converted API protection data struct. */ inline const ApiProtectionData& getApiData() const { return maApiData; } /** Writes all protection attributes to the passed property map. */ void writeToPropertyMap( PropertyMap& rPropMap ) const; private: ProtectionModel maModel; /// Protection model data. ApiProtectionData maApiData; /// Protection data converted to API constants. }; typedef ::boost::shared_ptr< Protection > ProtectionRef; // ============================================================================ /** Contains XML attributes of a single border line. */ struct BorderLineModel { Color maColor; /// Borderline color. sal_Int32 mnStyle; /// Border line style. bool mbUsed; /// True = line format used. explicit BorderLineModel( bool bDxf ); /** Sets the passed BIFF line style. */ void setBiffStyle( sal_Int32 nLineStyle ); /** Sets line style and line color from the passed BIFF data. */ void setBiffData( sal_uInt8 nLineStyle, sal_uInt16 nLineColor ); }; // ---------------------------------------------------------------------------- /** Contains XML attributes of a complete cell border. */ struct BorderModel { BorderLineModel maLeft; /// Left line format. BorderLineModel maRight; /// Right line format. BorderLineModel maTop; /// Top line format. BorderLineModel maBottom; /// Bottom line format. BorderLineModel maDiagonal; /// Diagonal line format. bool mbDiagTLtoBR; /// True = top-left to bottom-right on. bool mbDiagBLtoTR; /// True = bottom-left to top-right on. explicit BorderModel( bool bDxf ); }; // ---------------------------------------------------------------------------- /** Contains API attributes of a complete cell border. */ struct ApiBorderData { typedef ::com::sun::star::table::TableBorder ApiTableBorder; typedef ::com::sun::star::table::BorderLine ApiBorderLine; ApiTableBorder maBorder; /// Left/right/top/bottom line format. ApiBorderLine maTLtoBR; /// Diagonal top-left to bottom-right line format. ApiBorderLine maBLtoTR; /// Diagonal bottom-left to top-right line format. bool mbBorderUsed; /// True = left/right/top/bottom line format used. bool mbDiagUsed; /// True = diagonal line format used. explicit ApiBorderData(); /** Returns true, if any of the outer border lines is visible. */ bool hasAnyOuterBorder() const; }; bool operator==( const ApiBorderData& rLeft, const ApiBorderData& rRight ); // ============================================================================ class Border : public WorkbookHelper { public: explicit Border( const WorkbookHelper& rHelper, bool bDxf ); /** Sets global border attributes from the border element. */ void importBorder( const AttributeList& rAttribs ); /** Sets border attributes for the border line with the passed element identifier. */ void importStyle( sal_Int32 nElement, const AttributeList& rAttribs ); /** Sets color attributes for the border line with the passed element identifier. */ void importColor( sal_Int32 nElement, const AttributeList& rAttribs ); /** Imports the BORDER record from the passed stream. */ void importBorder( SequenceInputStream& rStrm ); /** Imports a border from a DXF record from the passed stream. */ void importDxfBorder( sal_Int32 nElement, SequenceInputStream& rStrm ); /** Sets the border attributes from the passed BIFF2 XF record data. */ void setBiff2Data( sal_uInt8 nFlags ); /** Sets the border attributes from the passed BIFF3/BIFF4 XF record data. */ void setBiff3Data( sal_uInt32 nBorder ); /** Sets the border attributes from the passed BIFF5 XF record data. */ void setBiff5Data( sal_uInt32 nBorder, sal_uInt32 nArea ); /** Sets the border attributes from the passed BIFF8 XF record data. */ void setBiff8Data( sal_uInt32 nBorder1, sal_uInt32 nBorder2 ); /** Sets the border attributes from the border block of a CFRULE record. */ void importCfRule( BiffInputStream& rStrm, sal_uInt32 nFlags ); /** Final processing after import of all style settings. */ void finalizeImport(); /** Returns the border model structure. */ inline const BorderModel& getModel() const { return maModel; } /** Returns the converted API border data struct. */ inline const ApiBorderData& getApiData() const { return maApiData; } /** Writes all border attributes to the passed property map. */ void writeToPropertyMap( PropertyMap& rPropMap ) const; private: /** Returns the border line struct specified by the passed XML token identifier. */ BorderLineModel* getBorderLine( sal_Int32 nElement ); /** Converts border line data to an API struct, returns true, if the line is marked as used. */ bool convertBorderLine( ::com::sun::star::table::BorderLine& rBorderLine, const BorderLineModel& rModel ); private: BorderModel maModel; ApiBorderData maApiData; bool mbDxf; }; typedef ::boost::shared_ptr< Border > BorderRef; // ============================================================================ /** Contains XML pattern fill attributes from the patternFill element. */ struct PatternFillModel { Color maPatternColor; /// Pattern foreground color. Color maFillColor; /// Background fill color. sal_Int32 mnPattern; /// Pattern identifier (e.g. solid). bool mbPattColorUsed; /// True = pattern foreground color used. bool mbFillColorUsed; /// True = background fill color used. bool mbPatternUsed; /// True = pattern used. explicit PatternFillModel( bool bDxf ); /** Sets the passed BIFF pattern identifier. */ void setBiffPattern( sal_Int32 nPattern ); /** Sets the pattern and pattern colors from the passed BIFF data. */ void setBiffData( sal_uInt16 nPatternColor, sal_uInt16 nFillColor, sal_uInt8 nPattern ); }; // ---------------------------------------------------------------------------- /** Contains XML gradient fill attributes from the gradientFill element. */ struct GradientFillModel { typedef ::std::map< double, Color > ColorMap; sal_Int32 mnType; /// Gradient type, linear or path. double mfAngle; /// Rotation angle for type linear. double mfLeft; /// Left convergence for type path. double mfRight; /// Right convergence for type path. double mfTop; /// Top convergence for type path. double mfBottom; /// Bottom convergence for type path. ColorMap maColors; /// Gradient colors. explicit GradientFillModel(); /** Reads BIFF12 gradient settings from a FILL or DXF record. */ void readGradient( SequenceInputStream& rStrm ); /** Reads BIFF12 gradient stop settings from a FILL or DXF record. */ void readGradientStop( SequenceInputStream& rStrm, bool bDxf ); }; // ---------------------------------------------------------------------------- /** Contains API fill attributes. */ struct ApiSolidFillData { sal_Int32 mnColor; /// Fill color. bool mbTransparent; /// True = transparent area. bool mbUsed; /// True = fill data is valid. explicit ApiSolidFillData(); }; bool operator==( const ApiSolidFillData& rLeft, const ApiSolidFillData& rRight ); // ============================================================================ /** Contains cell fill attributes, either a pattern fill or a gradient fill. */ class Fill : public WorkbookHelper { public: explicit Fill( const WorkbookHelper& rHelper, bool bDxf ); /** Sets attributes of a patternFill element. */ void importPatternFill( const AttributeList& rAttribs ); /** Sets the pattern color from the fgColor element. */ void importFgColor( const AttributeList& rAttribs ); /** Sets the background color from the bgColor element. */ void importBgColor( const AttributeList& rAttribs ); /** Sets attributes of a gradientFill element. */ void importGradientFill( const AttributeList& rAttribs ); /** Sets a color from the color element in a gradient fill. */ void importColor( const AttributeList& rAttribs, double fPosition ); /** Imports the FILL record from the passed stream. */ void importFill( SequenceInputStream& rStrm ); /** Imports the fill pattern from a DXF record. */ void importDxfPattern( SequenceInputStream& rStrm ); /** Imports the pattern color from a DXF record. */ void importDxfFgColor( SequenceInputStream& rStrm ); /** Imports the background color from a DXF record. */ void importDxfBgColor( SequenceInputStream& rStrm ); /** Imports gradient settings from a DXF record. */ void importDxfGradient( SequenceInputStream& rStrm ); /** Imports gradient stop settings from a DXF record. */ void importDxfStop( SequenceInputStream& rStrm ); /** Sets the fill attributes from the passed BIFF2 XF record data. */ void setBiff2Data( sal_uInt8 nFlags ); /** Sets the fill attributes from the passed BIFF3/BIFF4 XF record data. */ void setBiff3Data( sal_uInt16 nArea ); /** Sets the fill attributes from the passed BIFF5 XF record data. */ void setBiff5Data( sal_uInt32 nArea ); /** Sets the fill attributes from the passed BIFF8 XF record data. */ void setBiff8Data( sal_uInt32 nBorder2, sal_uInt16 nArea ); /** Sets the fill attributes from the fill block of a CFRULE record. */ void importCfRule( BiffInputStream& rStrm, sal_uInt32 nFlags ); /** Final processing after import of all style settings. */ void finalizeImport(); /** Returns the fill pattern model structure, if extant. */ inline const PatternFillModel* getPatternModel() const { return mxPatternModel.get(); } /** Returns the fill gradient model structure, if extant. */ inline const GradientFillModel* getGradientModel() const { return mxGradientModel.get(); } /** Returns the converted API fill data struct. */ inline const ApiSolidFillData& getApiData() const { return maApiData; } /** Writes all fill attributes to the passed property map. */ void writeToPropertyMap( PropertyMap& rPropMap ) const; private: typedef ::boost::shared_ptr< PatternFillModel > PatternModelRef; typedef ::boost::shared_ptr< GradientFillModel > GradientModelRef; PatternModelRef mxPatternModel; GradientModelRef mxGradientModel; ApiSolidFillData maApiData; bool mbDxf; }; typedef ::boost::shared_ptr< Fill > FillRef; // ============================================================================ /** Contains all data for a cell format or cell style. */ struct XfModel { sal_Int32 mnStyleXfId; /// Index to parent style XF. sal_Int32 mnFontId; /// Index to font data list. sal_Int32 mnNumFmtId; /// Index to number format list. sal_Int32 mnBorderId; /// Index to list of cell borders. sal_Int32 mnFillId; /// Index to list of cell areas. bool mbCellXf; /// True = cell XF, false = style XF. bool mbFontUsed; /// True = font index used. bool mbNumFmtUsed; /// True = number format used. bool mbAlignUsed; /// True = alignment used. bool mbProtUsed; /// True = cell protection used. bool mbBorderUsed; /// True = border data used. bool mbAreaUsed; /// True = area data used. explicit XfModel(); }; // ============================================================================ /** Represents a cell format or a cell style (called XF, extended format). This class stores the type (cell/style), the index to the parent style (if it is a cell format) and all "attribute used" flags, which reflect the state of specific attribute groups (true = user has changed the attributes) and all formatting data. */ class Xf : public WorkbookHelper { public: explicit Xf( const WorkbookHelper& rHelper ); /** Sets all "attribute used" flags to the passed state. */ void setAllUsedFlags( bool bUsed ); /** Sets all attributes from the xf element. */ void importXf( const AttributeList& rAttribs, bool bCellXf ); /** Sets all attributes from the alignment element. */ void importAlignment( const AttributeList& rAttribs ); /** Sets all attributes from the protection element. */ void importProtection( const AttributeList& rAttribs ); /** Imports the XF record from the passed stream. */ void importXf( SequenceInputStream& rStrm, bool bCellXf ); /** Imports the XF record from the passed stream. */ void importXf( BiffInputStream& rStrm ); /** Final processing after import of all style settings. */ void finalizeImport(); /** Returns true, if the XF is a cell XF, and false, if it is a style XF. */ inline bool isCellXf() const { return maModel.mbCellXf; } /** Returns the referred font object. */ FontRef getFont() const; /** Returns the alignment data of this style. */ inline const Alignment& getAlignment() const { return maAlignment; } /** Returns the cell protection data of this style. */ inline const Protection& getProtection() const { return maProtection; } /** Returns true, if any "attribute used" flags are ste in this XF. */ bool hasAnyUsedFlags() const; /** Writes all formatting attributes to the passed property map. */ void writeToPropertyMap( PropertyMap& rPropMap ) const; /** Writes all formatting attributes to the passed property set. */ void writeToPropertySet( PropertySet& rPropSet ) const; /** Converts formatting information from BIFF2 cell record data directly. */ static void writeBiff2CellFormatToPropertySet( const WorkbookHelper& rHelper, PropertySet& rPropSet, sal_uInt8 nFlags1, sal_uInt8 nFlags2, sal_uInt8 nFlags3 ); private: /** Sets 'attribute used' flags from the passed BIFF bit field. */ void setBiffUsedFlags( sal_uInt8 nUsedFlags ); private: XfModel maModel; /// Cell XF or style XF model data. Alignment maAlignment; /// Cell alignment data. Protection maProtection; /// Cell protection data. ::com::sun::star::table::CellVertJustify meRotationRef; /// Rotation reference dependent on border. }; typedef ::boost::shared_ptr< Xf > XfRef; // ============================================================================ class Dxf : public WorkbookHelper { public: explicit Dxf( const WorkbookHelper& rHelper ); /** Creates a new empty font object. */ FontRef createFont( bool bAlwaysNew = true ); /** Creates a new empty border object. */ BorderRef createBorder( bool bAlwaysNew = true ); /** Creates a new empty fill object. */ FillRef createFill( bool bAlwaysNew = true ); /** Inserts a new number format code. */ void importNumFmt( const AttributeList& rAttribs ); /** Sets all attributes from the alignment element. */ void importAlignment( const AttributeList& rAttribs ); /** Sets all attributes from the protection element. */ void importProtection( const AttributeList& rAttribs ); /** Imports the DXF record from the passed stream. */ void importDxf( SequenceInputStream& rStrm ); /** Imports font, border, and fill settings from the CFRULE record. */ void importCfRule( BiffInputStream& rStrm, sal_uInt32 nFlags ); /** Final processing after import of all style settings. */ void finalizeImport(); /** Writes all formatting attributes to the passed property map. */ void writeToPropertyMap( PropertyMap& rPropMap ) const; /** Writes all formatting attributes to the passed property set. */ void writeToPropertySet( PropertySet& rPropSet ) const; private: FontRef mxFont; /// Font data. NumberFormatRef mxNumFmt; /// Number format data. AlignmentRef mxAlignment; /// Alignment data. ProtectionRef mxProtection; /// Protection data. BorderRef mxBorder; /// Border data. FillRef mxFill; /// Fill data. }; typedef ::boost::shared_ptr< Dxf > DxfRef; // ============================================================================ /** Contains attributes of a cell style, e.g. from the cellStyle element. */ struct CellStyleModel { ::rtl::OUString maName; /// Cell style name. sal_Int32 mnXfId; /// Formatting for this cell style. sal_Int32 mnBuiltinId; /// Identifier for builtin styles. sal_Int32 mnLevel; /// Level for builtin column/row styles. bool mbBuiltin; /// True = builtin style. bool mbCustom; /// True = customized builtin style. bool mbHidden; /// True = style not visible in GUI. explicit CellStyleModel(); /** Returns true, if this style is a builtin style. */ bool isBuiltin() const; /** Returns true, if this style represents the default document cell style. */ bool isDefaultStyle() const; }; // ============================================================================ class CellStyle : public WorkbookHelper { public: explicit CellStyle( const WorkbookHelper& rHelper ); /** Imports passed attributes from the cellStyle element. */ void importCellStyle( const AttributeList& rAttribs ); /** Imports style settings from a CELLSTYLE record. */ void importCellStyle( SequenceInputStream& rStrm ); /** Imports style settings from a STYLE record. */ void importStyle( BiffInputStream& rStrm ); /** Creates the style sheet in the document described by this cell style object. */ void createCellStyle(); /** Stores tha passed final style name and creates the cell style, if it is user-defined or modified built-in. */ void finalizeImport( const ::rtl::OUString& rFinalName ); /** Returns the cell style model structure. */ inline const CellStyleModel& getModel() const { return maModel; } /** Returns the final style name used in the document. */ inline const ::rtl::OUString& getFinalStyleName() const { return maFinalName; } private: CellStyleModel maModel; ::rtl::OUString maFinalName; /// Final style name used in API. bool mbCreated; /// True = style sheet created. }; typedef ::boost::shared_ptr< CellStyle > CellStyleRef; // ============================================================================ class CellStyleBuffer : public WorkbookHelper { public: explicit CellStyleBuffer( const WorkbookHelper& rHelper ); /** Appends and returns a new named cell style object. */ CellStyleRef importCellStyle( const AttributeList& rAttribs ); /** Imports the CELLSTYLE record from the passed stream. */ CellStyleRef importCellStyle( SequenceInputStream& rStrm ); /** Imports the STYLE record from the passed stream. */ CellStyleRef importStyle( BiffInputStream& rStrm ); /** Final processing after import of all style settings. */ void finalizeImport(); /** Returns the XF identifier associated to the default cell style. */ sal_Int32 getDefaultXfId() const; /** Returns the default style sheet for unused cells. */ ::rtl::OUString getDefaultStyleName() const; /** Creates the style sheet described by the style XF with the passed identifier. */ ::rtl::OUString createCellStyle( sal_Int32 nXfId ) const; private: /** Inserts the passed cell style object into the internal maps. */ void insertCellStyle( CellStyleRef xCellStyle ); /** Creates the style sheet described by the passed cell style object. */ ::rtl::OUString createCellStyle( const CellStyleRef& rxCellStyle ) const; private: typedef RefVector< CellStyle > CellStyleVector; typedef RefMap< sal_Int32, CellStyle > CellStyleXfIdMap; CellStyleVector maBuiltinStyles; /// All built-in cell styles. CellStyleVector maUserStyles; /// All user defined cell styles. CellStyleXfIdMap maStylesByXf; /// All cell styles, mapped by XF identifier. CellStyleRef mxDefStyle; /// Default cell style. }; // ============================================================================ struct AutoFormatModel { sal_Int32 mnAutoFormatId; /// Index of predefined autoformatting. bool mbApplyNumFmt; /// True = apply number format from autoformatting. bool mbApplyFont; /// True = apply font from autoformatting. bool mbApplyAlignment; /// True = apply alignment from autoformatting. bool mbApplyBorder; /// True = apply border from autoformatting. bool mbApplyFill; /// True = apply fill from autoformatting. bool mbApplyProtection; /// True = apply protection from autoformatting. explicit AutoFormatModel(); }; // ============================================================================ class StylesBuffer : public WorkbookHelper { public: explicit StylesBuffer( const WorkbookHelper& rHelper ); /** Creates a new empty font object. @param opnFontId (out-param) The identifier of the new font object. */ FontRef createFont( sal_Int32* opnFontId = 0 ); /** Creates a number format. */ NumberFormatRef createNumFmt( sal_Int32 nNumFmtId, const ::rtl::OUString& rFmtCode ); /** Creates a new empty border object. @param opnBorderId (out-param) The identifier of the new border object. */ BorderRef createBorder( sal_Int32* opnBorderId = 0 ); /** Creates a new empty fill object. @param opnFillId (out-param) The identifier of the new fill object. */ FillRef createFill( sal_Int32* opnFillId = 0 ); /** Creates a new empty cell formatting object. @param opnXfId (out-param) The identifier of the new XF object. */ XfRef createCellXf( sal_Int32* opnXfId = 0 ); /** Creates a new empty style formatting object. @param opnXfId (out-param) The identifier of the new XF object. */ XfRef createStyleXf( sal_Int32* opnXfId = 0 ); /** Creates a new empty differential formatting object. @param opnDxfId (out-param) The identifier of the new DXF object. */ DxfRef createDxf( sal_Int32* opnDxfId = 0 ); /** Appends a new color to the color palette. */ void importPaletteColor( const AttributeList& rAttribs ); /** Inserts a new number format code. */ NumberFormatRef importNumFmt( const AttributeList& rAttribs ); /** Appends and returns a new named cell style object. */ CellStyleRef importCellStyle( const AttributeList& rAttribs ); /** Appends a new color to the color palette. */ void importPaletteColor( SequenceInputStream& rStrm ); /** Imports the NUMFMT record from the passed stream. */ void importNumFmt( SequenceInputStream& rStrm ); /** Imports the CELLSTYLE record from the passed stream. */ void importCellStyle( SequenceInputStream& rStrm ); /** Imports the PALETTE record from the passed stream. */ void importPalette( BiffInputStream& rStrm ); /** Imports the FONT record from the passed stream. */ void importFont( BiffInputStream& rStrm ); /** Imports the FONTCOLOR record from the passed stream. */ void importFontColor( BiffInputStream& rStrm ); /** Imports the FORMAT record from the passed stream. */ void importFormat( BiffInputStream& rStrm ); /** Imports the XF record from the passed stream. */ void importXf( BiffInputStream& rStrm ); /** Imports the STYLE record from the passed stream. */ void importStyle( BiffInputStream& rStrm ); /** Imports a color palette from a UNO sequence in the passed any. */ void importPalette( const ::com::sun::star::uno::Any& rPalette ); /** Final processing after import of all style settings. */ void finalizeImport(); /** Returns the palette color with the specified index. */ sal_Int32 getPaletteColor( sal_Int32 nIndex ) const; /** Returns the specified font object. */ FontRef getFont( sal_Int32 nFontId ) const; /** Returns the specified border object. */ BorderRef getBorder( sal_Int32 nBorderId ) const; /** Returns the specified cell format object. */ XfRef getCellXf( sal_Int32 nXfId ) const; /** Returns the specified style format object. */ XfRef getStyleXf( sal_Int32 nXfId ) const; /** Returns the specified diferential cell format object. */ DxfRef getDxf( sal_Int32 nDxfId ) const; /** Returns the font object of the specified cell XF. */ FontRef getFontFromCellXf( sal_Int32 nXfId ) const; /** Returns the default application font (used in the "Normal" cell style). */ FontRef getDefaultFont() const; /** Returns the model of the default application font (used in the "Normal" cell style). */ const FontModel& getDefaultFontModel() const; /** Returns true, if the specified borders are equal. */ bool equalBorders( sal_Int32 nBorderId1, sal_Int32 nBorderId2 ) const; /** Returns true, if the specified fills are equal. */ bool equalFills( sal_Int32 nFillId1, sal_Int32 nFillId2 ) const; /** Returns the default style sheet for unused cells. */ ::rtl::OUString getDefaultStyleName() const; /** Creates the style sheet described by the style XF with the passed identifier. */ ::rtl::OUString createCellStyle( sal_Int32 nXfId ) const; /** Creates the style sheet described by the DXF with the passed identifier. */ ::rtl::OUString createDxfStyle( sal_Int32 nDxfId ) const; /** Writes the font attributes of the specified font data to the passed property map. */ void writeFontToPropertyMap( PropertyMap& rPropMap, sal_Int32 nFontId ) const; /** Writes the specified number format to the passed property map. */ void writeNumFmtToPropertyMap( PropertyMap& rPropMap, sal_Int32 nNumFmtId ) const; /** Writes the border attributes of the specified border data to the passed property map. */ void writeBorderToPropertyMap( PropertyMap& rPropMap, sal_Int32 nBorderId ) const; /** Writes the fill attributes of the specified fill data to the passed property map. */ void writeFillToPropertyMap( PropertyMap& rPropMap, sal_Int32 nFillId ) const; /** Writes the cell formatting attributes of the specified XF to the passed property map. */ void writeCellXfToPropertyMap( PropertyMap& rPropMap, sal_Int32 nXfId ) const; /** Writes the cell formatting attributes of the specified style XF to the passed property map. */ void writeStyleXfToPropertyMap( PropertyMap& rPropMap, sal_Int32 nXfId ) const; /** Writes the cell formatting attributes of the specified XF to the passed property set. */ void writeCellXfToPropertySet( PropertySet& rPropSet, sal_Int32 nXfId ) const; /** Writes the cell formatting attributes of the specified style XF to the passed property set. */ void writeStyleXfToPropertySet( PropertySet& rPropSet, sal_Int32 nXfId ) const; private: typedef RefVector< Font > FontVector; typedef RefVector< Border > BorderVector; typedef RefVector< Fill > FillVector; typedef RefVector< Xf > XfVector; typedef RefVector< Dxf > DxfVector; typedef ::std::map< sal_Int32, ::rtl::OUString > DxfStyleMap; ColorPalette maPalette; /// Color palette. FontVector maFonts; /// List of font objects. NumberFormatsBuffer maNumFmts; /// List of all number format codes. BorderVector maBorders; /// List of cell border objects. FillVector maFills; /// List of cell area fill objects. XfVector maCellXfs; /// List of cell formats. XfVector maStyleXfs; /// List of cell styles. CellStyleBuffer maCellStyles; /// All built-in and user defined cell styles. DxfVector maDxfs; /// List of differential cell styles. mutable DxfStyleMap maDxfStyles; /// Maps DXF identifiers to Calc style sheet names. }; // ============================================================================ } // namespace xls } // namespace oox #endif
20,346
538
<filename>plot.py import numpy as np import pandas as pd import sys from stockstats import StockDataFrame import matplotlib.pyplot as plt df = pd.DataFrame.from_csv(sys.argv[1], index_col=None) print (df.head()) df['time'] = pd.to_datetime(df['time'], unit='s') df = df.set_index('time') print (df.describe()) # plt.subplot('111') # df.plot(kind='line') # plt.subplot('122') # df.plot(kind='histogram') df.rolling('120s').mean().plot() plt.show()
177
505
from pyrep.robots.end_effectors.gripper import Gripper class BaxterGripper(Gripper): def __init__(self, count: int = 0): super().__init__(count, 'BaxterGripper', ['BaxterGripper_leftJoint', 'BaxterGripper_rightJoint'])
145
480
<filename>tests/test_phantom_style.py """Tests for `rust_phantom_style` settings.""" from rust_test_common import * class TestPhantomStyle(TestBase): def test_style_none(self): self._override_setting('rust_phantom_style', 'none') self._with_open_file('tests/error-tests/tests/cast-to-unsized-trait-object-suggestion.rs', self._test_style_none) def _test_style_none(self, view): with UiIntercept(passthrough=True) as ui: e = plugin.SyntaxCheckPlugin.RustSyntaxCheckEvent() self._cargo_clean(view) e.on_post_save(view) self._get_rust_thread().join() self.assertEqual(len(ui.phantoms), 0) regions = ui.view_regions[view.file_name()] # Extremely basic check, the number of unique regions displayed. rs = [(r.a, r.b) for r in regions] self.assertEqual(len(set(rs)), 4) def test_style_popup(self): self._override_setting('rust_phantom_style', 'popup') self._with_open_file('tests/error-tests/tests/cast-to-unsized-trait-object-suggestion.rs', self._test_style_popup) def _test_style_popup(self, view): with UiIntercept(passthrough=True) as ui: e = plugin.SyntaxCheckPlugin.RustSyntaxCheckEvent() self._cargo_clean(view) e.on_post_save(view) self._get_rust_thread().join() self.assertEqual(len(ui.phantoms), 0) regions = ui.view_regions[view.file_name()] # Extremely basic check, the number of unique regions displayed. rs = [(r.a, r.b) for r in regions] self.assertEqual(len(set(rs)), 4) # Trigger popup. self.assertEqual(len(ui.popups), 0) for region in regions: messages.message_popup(view, region.begin(), sublime.HOVER_TEXT) popups = ui.popups[view.file_name()] self.assertEqual(len(popups), 1) self.assertIn('cast to unsized type', popups[0]['content']) ui.popups.clear() # Trigger gutter hover. for lineno in (12, 16): pt = view.text_point(lineno - 1, 0) messages.message_popup(view, pt, sublime.HOVER_GUTTER) popups = ui.popups[view.file_name()] self.assertEqual(len(popups), 1) self.assertIn('cast to unsized type', popups[0]['content']) ui.popups.clear()
1,231
2,195
from aim.storage.object import CustomObject from aim.storage.types import BLOB @CustomObject.alias('aim.text') class Text(CustomObject): """Text object used to store text objects in Aim repository. Args: text (:obj:): str object used to construct `aim.Text`. """ AIM_NAME = 'aim.text' def __init__(self, text): super().__init__() if not isinstance(text, str): raise TypeError('`text` must be a string.') self.storage['data'] = BLOB(data=text) @property def data(self): return self.storage['data'].load() def __repr__(self): return self.data
266
2,670
<reponame>ghaglerSGI/vscode-cpptools /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "invalid.identifier.for.rename": "Podano nieprawidłowy identyfikator dla operacji Zmień nazwę symbolu.", "unable.to.locate.selected.symbol": "Nie można zlokalizować definicji wybranego symbolu." }
168
1,474
<reponame>billzhonggz/Transfer-Learning-Library """ @author: <NAME> @contact: <EMAIL> """ import torch.nn.functional as F import math def robust_entropy(y, ita=1.5, num_classes=19, reduction='mean'): """ Robust entropy proposed in `FDA: Fourier Domain Adaptation for Semantic Segmentation (CVPR 2020) <https://arxiv.org/abs/2004.05498>`_ Args: y (tensor): logits output of segmentation model in shape of :math:`(N, C, H, W)` ita (float, optional): parameters for robust entropy. Default: 1.5 num_classes (int, optional): number of classes. Default: 19 reduction (string, optional): Specifies the reduction to apply to the output: ``'none'`` | ``'mean'``. ``'none'``: no reduction will be applied, ``'mean'``: the sum of the output will be divided by the number of elements in the output. Default: ``'mean'`` Returns: Scalar by default. If :attr:`reduction` is ``'none'``, then :math:`(N, )`. """ P = F.softmax(y, dim=1) logP = F.log_softmax(y, dim=1) PlogP = P * logP ent = -1.0 * PlogP.sum(dim=1) ent = ent / math.log(num_classes) # compute robust entropy ent = ent ** 2.0 + 1e-8 ent = ent ** ita if reduction == 'mean': return ent.mean() else: return ent
531
3,100
package com.airbnb.airpal.api.output.persistors; import com.airbnb.airpal.api.Job; import com.airbnb.airpal.api.output.PersistentJobOutput; import com.airbnb.airpal.api.output.builders.JobOutputBuilder; import com.airbnb.airpal.core.execution.QueryExecutionAuthorizer; import com.google.common.base.Splitter; import com.google.common.collect.Iterables; import java.net.URI; import java.util.List; import static com.google.common.base.Preconditions.checkState; public class HiveTablePersistor implements Persistor { private static final Splitter TABLE_SPLITTER = Splitter.on(".").omitEmptyStrings(); private final URI jobURI; public HiveTablePersistor(PersistentJobOutput jobOutput) { this.jobURI = jobOutput.getLocation(); } @Override public boolean canPersist(QueryExecutionAuthorizer authorizer) { List<String> locationParts = TABLE_SPLITTER.splitToList(jobURI.toString()); checkState(locationParts.size() == 2, "destination hive table did not have schema and table components"); return authorizer.isAuthorizedWrite("hive", Iterables.getFirst(locationParts, ""), Iterables.getLast(locationParts)); } @Override public URI persist(JobOutputBuilder outputBuilder, Job job) { return null; } }
444
451
<gh_stars>100-1000 // File Automatically generated by eLiSe #include "StdAfx.h" class cCodeBlockCam: public cElCompiledFonc { public : cCodeBlockCam(); void ComputeVal(); void ComputeValDeriv(); void ComputeValDerivHessian(); double * AdrVarLocFromString(const std::string &); void SetGL_MK0_0_0(double); void SetGL_MK0_0_1(double); void SetGL_MK0_0_2(double); void SetGL_MK0_1_0(double); void SetGL_MK0_1_1(double); void SetGL_MK0_1_2(double); void SetGL_MK0_2_0(double); void SetGL_MK0_2_1(double); void SetGL_MK0_2_2(double); void SetGL_MK1_0_0(double); void SetGL_MK1_0_1(double); void SetGL_MK1_0_2(double); void SetGL_MK1_1_0(double); void SetGL_MK1_1_1(double); void SetGL_MK1_1_2(double); void SetGL_MK1_2_0(double); void SetGL_MK1_2_1(double); void SetGL_MK1_2_2(double); void SetGL_MK2_0_0(double); void SetGL_MK2_0_1(double); void SetGL_MK2_0_2(double); void SetGL_MK2_1_0(double); void SetGL_MK2_1_1(double); void SetGL_MK2_1_2(double); void SetGL_MK2_2_0(double); void SetGL_MK2_2_1(double); void SetGL_MK2_2_2(double); void SetGL_MK3_0_0(double); void SetGL_MK3_0_1(double); void SetGL_MK3_0_2(double); void SetGL_MK3_1_0(double); void SetGL_MK3_1_1(double); void SetGL_MK3_1_2(double); void SetGL_MK3_2_0(double); void SetGL_MK3_2_1(double); void SetGL_MK3_2_2(double); static cAutoAddEntry mTheAuto; static cElCompiledFonc * Alloc(); private : double mLocGL_MK0_0_0; double mLocGL_MK0_0_1; double mLocGL_MK0_0_2; double mLocGL_MK0_1_0; double mLocGL_MK0_1_1; double mLocGL_MK0_1_2; double mLocGL_MK0_2_0; double mLocGL_MK0_2_1; double mLocGL_MK0_2_2; double mLocGL_MK1_0_0; double mLocGL_MK1_0_1; double mLocGL_MK1_0_2; double mLocGL_MK1_1_0; double mLocGL_MK1_1_1; double mLocGL_MK1_1_2; double mLocGL_MK1_2_0; double mLocGL_MK1_2_1; double mLocGL_MK1_2_2; double mLocGL_MK2_0_0; double mLocGL_MK2_0_1; double mLocGL_MK2_0_2; double mLocGL_MK2_1_0; double mLocGL_MK2_1_1; double mLocGL_MK2_1_2; double mLocGL_MK2_2_0; double mLocGL_MK2_2_1; double mLocGL_MK2_2_2; double mLocGL_MK3_0_0; double mLocGL_MK3_0_1; double mLocGL_MK3_0_2; double mLocGL_MK3_1_0; double mLocGL_MK3_1_1; double mLocGL_MK3_1_2; double mLocGL_MK3_2_0; double mLocGL_MK3_2_1; double mLocGL_MK3_2_2; };
1,500
1,056
<filename>java/java.editor/test/unit/data/org/netbeans/modules/editor/java/TestInterface.java<gh_stars>1000+ package org.netbeans.modules.editor.java; public interface TestInterface { public void test(); }
74
918
<filename>gobblin-data-management/src/main/java/org/apache/gobblin/data/management/conversion/hive/events/EventWorkunitUtils.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.gobblin.data.management.conversion.hive.events; import java.util.List; import org.apache.hadoop.hive.ql.metadata.Partition; import org.apache.hadoop.hive.ql.metadata.Table; import org.apache.gobblin.configuration.ConfigurationKeys; import org.apache.gobblin.configuration.State; import org.apache.gobblin.configuration.WorkUnitState; import org.apache.gobblin.metrics.event.sla.SlaEventKeys; import org.apache.gobblin.source.extractor.extract.LongWatermark; import org.apache.gobblin.source.workunit.WorkUnit; /** * Utilities to set event metadata into {@link WorkUnit}s */ public class EventWorkunitUtils { public static final String IS_WATERMARK_WORKUNIT_KEY = "hive.source.watermark.isWatermarkWorkUnit"; /** * Set SLA event metadata in the workunit. The publisher will use this metadta to publish sla events */ public static void setTableSlaEventMetadata(WorkUnit state, Table table, long updateTime, long lowWatermark, long beginGetWorkunitsTime) { state.setProp(SlaEventKeys.DATASET_URN_KEY, state.getProp(ConfigurationKeys.DATASET_URN_KEY)); state.setProp(SlaEventKeys.PARTITION_KEY, table.getCompleteName()); state.setProp(SlaEventKeys.UPSTREAM_TS_IN_MILLI_SECS_KEY, String.valueOf(updateTime)); // Time when the workunit was created state.setProp(SlaEventKeys.ORIGIN_TS_IN_MILLI_SECS_KEY, System.currentTimeMillis()); state.setProp(EventConstants.WORK_UNIT_CREATE_TIME, state.getProp(SlaEventKeys.ORIGIN_TS_IN_MILLI_SECS_KEY)); state.setProp(EventConstants.BEGIN_GET_WORKUNITS_TIME, beginGetWorkunitsTime); state.setProp(SlaEventKeys.PREVIOUS_PUBLISH_TS_IN_MILLI_SECS_KEY, lowWatermark); } /** * Set SLA event metadata in the workunit. The publisher will use this metadta to publish sla events */ public static void setPartitionSlaEventMetadata(WorkUnit state, Table table, Partition partition, long updateTime, long lowWatermark, long beginGetWorkunitsTime) { state.setProp(SlaEventKeys.DATASET_URN_KEY, state.getProp(ConfigurationKeys.DATASET_URN_KEY)); state.setProp(SlaEventKeys.PARTITION_KEY, partition.getName()); state.setProp(SlaEventKeys.UPSTREAM_TS_IN_MILLI_SECS_KEY, String.valueOf(updateTime)); // Time when the workunit was created state.setProp(SlaEventKeys.ORIGIN_TS_IN_MILLI_SECS_KEY, System.currentTimeMillis()); state.setProp(EventConstants.WORK_UNIT_CREATE_TIME, state.getProp(SlaEventKeys.ORIGIN_TS_IN_MILLI_SECS_KEY)); state.setProp(SlaEventKeys.PREVIOUS_PUBLISH_TS_IN_MILLI_SECS_KEY, lowWatermark); state.setProp(EventConstants.BEGIN_GET_WORKUNITS_TIME, beginGetWorkunitsTime); state.setProp(EventConstants.SOURCE_DATA_LOCATION, partition.getDataLocation()); } /** * Set number of schema evolution DDLs as Sla event metadata */ public static void setEvolutionMetadata(State state, List<String> evolutionDDLs) { state.setProp(EventConstants.SCHEMA_EVOLUTION_DDLS_NUM, evolutionDDLs == null ? 0 : evolutionDDLs.size()); } public static void setBeginDDLBuildTimeMetadata(State state, long time) { state.setProp(EventConstants.BEGIN_DDL_BUILD_TIME, Long.toString(time)); } public static void setEndDDLBuildTimeMetadata(State state, long time) { state.setProp(EventConstants.END_DDL_BUILD_TIME, Long.toString(time)); } public static void setBeginConversionDDLExecuteTimeMetadata(State state, long time) { state.setProp(EventConstants.BEGIN_CONVERSION_DDL_EXECUTE_TIME, Long.toString(time)); } public static void setEndConversionDDLExecuteTimeMetadata(State state, long time) { state.setProp(EventConstants.END_CONVERSION_DDL_EXECUTE_TIME, Long.toString(time)); } public static void setBeginPublishDDLExecuteTimeMetadata(State state, long time) { state.setProp(EventConstants.BEGIN_PUBLISH_DDL_EXECUTE_TIME, Long.toString(time)); } public static void setEndPublishDDLExecuteTimeMetadata(State state, long time) { state.setProp(EventConstants.END_PUBLISH_DDL_EXECUTE_TIME, Long.toString(time)); } /** * Sets metadata to indicate whether this is the first time this table or partition is being published. * @param wus to set if this is first publish for this table or partition */ public static void setIsFirstPublishMetadata(WorkUnitState wus) { if (!Boolean.valueOf(wus.getPropAsBoolean(IS_WATERMARK_WORKUNIT_KEY))) { LongWatermark previousWatermark = wus.getWorkunit().getLowWatermark(LongWatermark.class); wus.setProp(SlaEventKeys.IS_FIRST_PUBLISH, (null == previousWatermark || previousWatermark.getValue() == 0)); } } }
1,860
375
/* * Copyright 2019 Nokia Solutions and Networks * Licensed under the Apache License, Version 2.0, * see license.txt file for details. */ package org.robotframework.ide.eclipse.main.plugin.views.debugshell; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.robotframework.ide.eclipse.main.plugin.tableeditor.source.assist.Assistant.createAssistant; import static org.robotframework.ide.eclipse.main.plugin.tableeditor.source.assist.Proposals.applyToDocument; import static org.robotframework.ide.eclipse.main.plugin.tableeditor.source.assist.Proposals.proposalWithImage; import static org.robotframework.red.junit.jupiter.ProjectExtension.createFile; import java.util.List; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.contentassist.ICompletionProposal; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.rf.ide.core.execution.server.response.EvaluateExpression.ExpressionType; import org.robotframework.ide.eclipse.main.plugin.RedImages; import org.robotframework.ide.eclipse.main.plugin.mockdocument.Document; import org.robotframework.ide.eclipse.main.plugin.model.RobotModel; import org.robotframework.ide.eclipse.main.plugin.model.RobotSuiteFile; import org.robotframework.red.graphics.ImagesManager; import org.robotframework.red.junit.jupiter.Project; import org.robotframework.red.junit.jupiter.ProjectExtension; @ExtendWith(ProjectExtension.class) public class KeywordCallsInShellAssistProcessorTest { @Project static IProject project; private static IFile suite; @BeforeAll public static void beforeSuite() throws Exception { createFile(project, "res.robot", "*** Keywords ***", "kw1", "kw2", " [Arguments] ${x}"); suite = createFile(project, "suite.robot", "*** Test Cases ***", "*** Settings ***", "Resource res.robot"); } @AfterAll public static void afterSuite() { suite = null; } @Test public void keywordsProcessorIsValidOnlyForDefaultSection() { final KeywordCallsInShellAssistProcessor processor = new KeywordCallsInShellAssistProcessor( createAssistant((RobotSuiteFile) null)); assertThat(processor.getApplicableContentTypes()).containsOnly(IDocument.DEFAULT_CONTENT_TYPE); } @Test public void noProposalsAreProvided_whenInVariableMode() { final RobotSuiteFile model = new RobotModel().createSuiteFile(suite); final IDocument shellDoc = new ShellDocumentSession().changeMode(ExpressionType.VARIABLE).get(); final ITextViewer viewer = mock(ITextViewer.class); when(viewer.getDocument()).thenReturn(shellDoc); final KeywordCallsInShellAssistProcessor processor = new KeywordCallsInShellAssistProcessor( createAssistant(model)); final List<? extends ICompletionProposal> proposals = processor.computeProposals(viewer, shellDoc.getLength()); assertThat(proposals).isNull(); } @Test public void noProposalsAreProvided_whenInPythonMode() { final RobotSuiteFile model = new RobotModel().createSuiteFile(suite); final IDocument shellDoc = new ShellDocumentSession().changeMode(ExpressionType.PYTHON).get(); final ITextViewer viewer = mock(ITextViewer.class); when(viewer.getDocument()).thenReturn(shellDoc); final KeywordCallsInShellAssistProcessor processor = new KeywordCallsInShellAssistProcessor( createAssistant(model)); final List<? extends ICompletionProposal> proposals = processor.computeProposals(viewer, shellDoc.getLength()); assertThat(proposals).isNull(); } @Test public void noProposalsAreProvided_whenInFirstCellOfPromptInAlreadyExecutedExpression() throws Exception { final RobotSuiteFile model = new RobotModel().createSuiteFile(suite); final ShellDocumentSession session = new ShellDocumentSession(); final int currentEndOffset = session.get().getLength(); final IDocument shellDoc = session.execute("result").get(); final ITextViewer viewer = mock(ITextViewer.class); when(viewer.getDocument()).thenReturn(shellDoc); final KeywordCallsInShellAssistProcessor processor = new KeywordCallsInShellAssistProcessor( createAssistant(model)); final List<? extends ICompletionProposal> proposals = processor.computeProposals(viewer, currentEndOffset); assertThat(proposals).isNull(); } @Test public void allProposalsAreProvided_whenNothingIsWrittenInFirstCellOfPrompt() throws Exception { final RobotSuiteFile model = new RobotModel().createSuiteFile(suite); final IDocument shellDoc = new ShellDocumentSession().get(); final ITextViewer viewer = mock(ITextViewer.class); when(viewer.getDocument()).thenReturn(shellDoc); final KeywordCallsInShellAssistProcessor processor = new KeywordCallsInShellAssistProcessor( createAssistant(model)); final List<? extends ICompletionProposal> proposals = processor.computeProposals(viewer, shellDoc.getLength()); assertThat(proposals).hasSize(2) .haveExactly(2, proposalWithImage(ImagesManager.getImage(RedImages.getUserKeywordImage()))); assertThat(proposals).extracting(proposal -> applyToDocument(shellDoc, proposal)) .containsOnly( new Document("ROBOT> kw1"), new Document("ROBOT> kw2 x")); } @Test public void allProposalsAreProvided_whenOnlySpacesAreWrittenInFirstCellOfPrompt() throws Exception { final RobotSuiteFile model = new RobotModel().createSuiteFile(suite); final IDocument shellDoc = new ShellDocumentSession().type(" ").get(); final ITextViewer viewer = mock(ITextViewer.class); when(viewer.getDocument()).thenReturn(shellDoc); final KeywordCallsInShellAssistProcessor processor = new KeywordCallsInShellAssistProcessor( createAssistant(model)); final List<? extends ICompletionProposal> proposals = processor.computeProposals(viewer, shellDoc.getLength()); assertThat(proposals).hasSize(2) .haveExactly(2, proposalWithImage(ImagesManager.getImage(RedImages.getUserKeywordImage()))); assertThat(proposals).extracting(proposal -> applyToDocument(shellDoc, proposal)) .containsOnly( new Document("ROBOT> kw1"), new Document("ROBOT> kw2 x")); } @Test public void onlyMatchingProposalsAreProvided_whenThereIsATextInFirstCellOfPrompt() throws Exception { final RobotSuiteFile model = new RobotModel().createSuiteFile(suite); final IDocument shellDoc = new ShellDocumentSession().type("1").get(); final ITextViewer viewer = mock(ITextViewer.class); when(viewer.getDocument()).thenReturn(shellDoc); final KeywordCallsInShellAssistProcessor processor = new KeywordCallsInShellAssistProcessor( createAssistant(model)); final List<? extends ICompletionProposal> proposals = processor.computeProposals(viewer, shellDoc.getLength()); assertThat(proposals).hasSize(1) .haveExactly(1, proposalWithImage(ImagesManager.getImage(RedImages.getUserKeywordImage()))); assertThat(proposals).extracting(proposal -> applyToDocument(shellDoc, proposal)) .containsOnly(new Document("ROBOT> kw1")); } @Test public void emptyProposalsAreProvided_whenNothingMatchesWithATextInFirstCellOfPrompt() throws Exception { final RobotSuiteFile model = new RobotModel().createSuiteFile(suite); final IDocument shellDoc = new ShellDocumentSession().type("3").get(); final ITextViewer viewer = mock(ITextViewer.class); when(viewer.getDocument()).thenReturn(shellDoc); final KeywordCallsInShellAssistProcessor processor = new KeywordCallsInShellAssistProcessor( createAssistant(model)); final List<? extends ICompletionProposal> proposals = processor.computeProposals(viewer, shellDoc.getLength()); assertThat(proposals).isEmpty(); } }
3,471
2,232
/* Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: <NAME> */ #pragma once #include "kernel/expr.h" #include "api/univ.h" #include "api/lean_expr.h" namespace lean { inline expr * to_expr(lean_expr n) { return reinterpret_cast<expr *>(n); } inline expr const & to_expr_ref(lean_expr n) { return *reinterpret_cast<expr *>(n); } inline lean_expr of_expr(expr * n) { return reinterpret_cast<lean_expr>(n); } void to_buffer(unsigned sz, lean_expr const * ns, buffer<expr> & r); inline list<expr> * to_list_expr(lean_list_expr n) { return reinterpret_cast<list<expr> *>(n); } inline list<expr> const & to_list_expr_ref(lean_list_expr n) { return *reinterpret_cast<list<expr> *>(n); } inline lean_list_expr of_list_expr(list<expr> * n) { return reinterpret_cast<lean_list_expr>(n); } inline macro_definition * to_macro_definition(lean_macro_def n) { return reinterpret_cast<macro_definition *>(n); } inline macro_definition const & to_macro_definition_ref(lean_macro_def n) { return *reinterpret_cast<macro_definition *>(n); } inline lean_macro_def of_macro_definition(macro_definition * n) { return reinterpret_cast<lean_macro_def>(n); } }
424
342
<reponame>hortonworks/kite<filename>kite-data/kite-data-core/src/test/java/org/kitesdk/data/spi/filesystem/TestFileSystemMetadataProviderBackwardCompatibility.java /* * Copyright 2013 Cloudera Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kitesdk.data.spi.filesystem; import com.google.common.collect.Sets; import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.kitesdk.data.DatasetDescriptor; import org.kitesdk.data.Datasets; import org.kitesdk.data.spi.MetadataProvider; public class TestFileSystemMetadataProviderBackwardCompatibility { private static final Path root = new Path("file:/tmp/tests/mixed-repository"); private static final Configuration conf = new Configuration(); private static final DatasetDescriptor descriptor = new DatasetDescriptor.Builder() .schemaLiteral("\"int\"") .build(); private static FileSystem local; private static MetadataProvider provider = null; @BeforeClass public static void createMixedLayoutRepository() throws IOException { local = FileSystem.get(conf); local.delete(root, true); // clean any old data createMetadata( local, new Path(root, new Path("old_1", ".metadata")), "old_1"); createMetadata( local, new Path(root, new Path("old_2", ".metadata")), "old_2"); provider = new FileSystemMetadataProvider(conf, root); provider.create("ns", "new_1", descriptor); provider.create("ns2", "new_2", descriptor); } public static void createMetadata(FileSystem fs, Path path, String name) throws IOException { fs.mkdirs(path); FileSystemMetadataProvider.writeDescriptor(fs, path, name, descriptor); } @Test public void testNamespaces() { Assert.assertEquals("Should report default namespace for old datasets", Sets.newHashSet("default", "ns", "ns2"), Sets.newHashSet(provider.namespaces())); } @Test public void testNamespacesWithOverlap() { // use old_1 as a new namespace provider.create("old_1", "new_3", descriptor); Assert.assertEquals("Should report default namespace for old datasets", Sets.newHashSet("old_1", "default", "ns", "ns2"), Sets.newHashSet(provider.namespaces())); provider.delete("old_1", "new_3"); } @Test public void testDatasets() throws IOException { Assert.assertEquals("Should report old datasets in default namespace", Sets.newHashSet("old_1", "old_2"), Sets.newHashSet(provider.datasets("default"))); provider.create("default", "new_3", descriptor); Assert.assertEquals("Should merge old datasets into default namespace", Sets.newHashSet("old_1", "old_2", "new_3"), Sets.newHashSet(provider.datasets("default"))); provider.delete("default", "new_3"); } @Test public void testDatasetsWithOverlap() { // use old_1 as a new namespace provider.create("old_1", "new_3", descriptor); Assert.assertEquals("Should report old datasets in default namespace", Sets.newHashSet("old_1", "old_2"), Sets.newHashSet(provider.datasets("default"))); Assert.assertEquals("Should merge old datasets into default namespace", Sets.newHashSet("new_3"), Sets.newHashSet(provider.datasets("old_1"))); provider.delete("old_1", "new_3"); } @Test public void testLoad() { DatasetDescriptor loaded = provider.load("default", "old_1"); Assert.assertNotNull("Should find old layout datasets", loaded); } @Test public void testExists() { Assert.assertTrue("Should find old layout datasets", provider.exists("default", "old_1")); } @Test public void testUpdate() throws IOException { DatasetDescriptor updated = new DatasetDescriptor.Builder(descriptor) .property("parquet.block.size", "1024") .build(); DatasetDescriptor saved = provider.update("default", "old_2", updated); Assert.assertNotNull("Should find saved metadata", saved); Assert.assertEquals("Should update old dataset successfully", updated.getProperty("parquet.block.size"), saved.getProperty("parquet.block.size")); DatasetDescriptor loaded = provider.load("default", "old_2"); Assert.assertNotNull("Should find saved metadata", loaded); Assert.assertEquals("Should make changes on disk", updated.getProperty("parquet.block.size"), loaded.getProperty("parquet.block.size")); Assert.assertFalse("Should not move metadata to new location", local.exists(new Path(root, new Path("default", "old_2")))); } }
1,794
4,335
#include "unistd.h" #include <stdio.h> #include <errno.h> #include <fcntl.h> #include "syscall.h" #include "sys/stat.h" int remove(const char *path) { struct stat sb; if (lstat(path, &sb) < 0) return -1; if (S_ISDIR(sb.st_mode)) return rmdir(path); return unlink(path); }
133
4,098
<reponame>pat2nav/Urho3D /* * Original work: Copyright (c) 2014, Oculus VR, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * RakNet License.txt file in the licenses directory of this source tree. An additional grant * of patent rights can be found in the RakNet Patents.txt file in the same directory. * * * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) * * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style * license found in the license.txt file in the root directory of this source tree. */ /// \file /// #ifndef __NETWORK_ID_MANAGER_H #define __NETWORK_ID_MANAGER_H #include "types.h" #include "Export.h" #include "memoryoverride.h" #include "NetworkIDObject.h" #include "Rand.h" namespace SLNet { /// Increase this value if you plan to have many persistent objects /// This value must match on all systems #define NETWORK_ID_MANAGER_HASH_LENGTH 1024 /// This class is simply used to generate a unique number for a group of instances of NetworkIDObject /// An instance of this class is required to use the ObjectID to pointer lookup system /// You should have one instance of this class per game instance. /// Call SetIsNetworkIDAuthority before using any functions of this class, or of NetworkIDObject class RAK_DLL_EXPORT NetworkIDManager { public: // GetInstance() and DestroyInstance(instance*) STATIC_FACTORY_DECLARATIONS(NetworkIDManager) NetworkIDManager(); virtual ~NetworkIDManager(void); /// Returns the parent object, or this instance if you don't use a parent. /// Supports NetworkIDObject anywhere in the inheritance hierarchy /// \pre You must first call SetNetworkIDManager before using this function template <class returnType> returnType GET_OBJECT_FROM_ID(NetworkID x) { NetworkIDObject *nio = GET_BASE_OBJECT_FROM_ID(x); if (nio==0) return 0; if (nio->GetParent()) return (returnType) nio->GetParent(); return (returnType) nio; } // Stop tracking all NetworkID objects void Clear(void); /// \internal NetworkIDObject *GET_BASE_OBJECT_FROM_ID(NetworkID x); protected: /// \internal void TrackNetworkIDObject(NetworkIDObject *networkIdObject); void StopTrackingNetworkIDObject(NetworkIDObject *networkIdObject); friend class NetworkIDObject; NetworkIDObject *networkIdHash[NETWORK_ID_MANAGER_HASH_LENGTH]; unsigned int NetworkIDToHashIndex(NetworkID networkId); uint64_t startingOffset; /// \internal NetworkID GetNewNetworkID(void); }; } // namespace SLNet #endif
878
2,141
""" Testing utilities """ from ploomber.testing import sql __all__ = ['sql']
25
1,350
<gh_stars>1000+ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.apimanagement.implementation; import com.azure.resourcemanager.apimanagement.fluent.models.SubscriptionKeysContractInner; import com.azure.resourcemanager.apimanagement.models.SubscriptionKeysContract; public final class SubscriptionKeysContractImpl implements SubscriptionKeysContract { private SubscriptionKeysContractInner innerObject; private final com.azure.resourcemanager.apimanagement.ApiManagementManager serviceManager; SubscriptionKeysContractImpl( SubscriptionKeysContractInner innerObject, com.azure.resourcemanager.apimanagement.ApiManagementManager serviceManager) { this.innerObject = innerObject; this.serviceManager = serviceManager; } public String primaryKey() { return this.innerModel().primaryKey(); } public String secondaryKey() { return this.innerModel().secondaryKey(); } public SubscriptionKeysContractInner innerModel() { return this.innerObject; } private com.azure.resourcemanager.apimanagement.ApiManagementManager manager() { return this.serviceManager; } }
399
381
/** * JBoss, Home of Professional Open Source * Copyright Red Hat, Inc., and individual contributors. * * 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.jboss.aerogear.unifiedpush.message.jms; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.enterprise.event.Event; import javax.inject.Inject; import org.jboss.aerogear.unifiedpush.message.holder.MessageHolderWithVariants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Consumes {@link MessageHolderWithVariants} from queue and pass them as a CDI event for further processing. * * This class serves as mediator for decoupling of JMS subsystem and services that observes these messages. */ @TransactionAttribute(TransactionAttributeType.REQUIRED) public class MessageHolderWithVariantsConsumer extends AbstractJMSMessageListener<MessageHolderWithVariants> { private static final Logger logger = LoggerFactory.getLogger(MessageHolderWithVariantsConsumer.class); @Inject @Dequeue private Event<MessageHolderWithVariants> dequeueEvent; @Override public void onMessage(MessageHolderWithVariants message) { logger.trace("receiving variant container from queue, triggering the TokenLoader class"); dequeueEvent.fire(message); } }
523
1,350
<filename>sdk/security/azure-resourcemanager-security/src/samples/java/com/azure/resourcemanager/security/IotSensorsDownloadResetPasswordSamples.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.security; import com.azure.core.util.Context; import com.azure.resourcemanager.security.models.ResetPasswordInput; /** Samples for IotSensors DownloadResetPassword. */ public final class IotSensorsDownloadResetPasswordSamples { /** * Sample code: Download file for reset password of the sensor. * * @param securityManager Entry point to SecurityManager. API spec for Microsoft.Security (Azure Security Center) * resource provider. */ public static void downloadFileForResetPasswordOfTheSensor( com.azure.resourcemanager.security.SecurityManager securityManager) { securityManager .iotSensors() .downloadResetPasswordWithResponse( "subscriptions/20<PASSWORD>-44dd-bd96-b71116dcdc23/resourceGroups/myRg/providers/Microsoft.Devices/IotHubs/myHub", "mySensor", new ResetPasswordInput().withApplianceId("3214-528AV23-D121-D3-E1"), Context.NONE); } }
484
721
package crazypants.enderio.base.machine.fuel; import javax.annotation.Nonnull; import com.enderio.core.common.util.NNList; import com.enderio.core.common.util.NullHelper; import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public class SolidFuelCenter { private SolidFuelCenter() { } private static final @Nonnull NNList<ISolidFuelHandler> HANDLERS = new NNList<>(); static { HANDLERS.add(new ISolidFuelHandler() { @Override public boolean isInGUI() { return false; } @Override public int getPowerUsePerTick() { return 0; } @Override public long getBurnTime(@Nonnull ItemStack itemstack) { return -1; } }); } private static final ISolidFuelHandler DEFAULT = new ISolidFuelHandler() { @Override public boolean isInGUI() { for (ISolidFuelHandler handler : HANDLERS) { if (handler.isInGUI()) { return true; } } return false; } @Override public int getPowerUsePerTick() { for (ISolidFuelHandler handler : HANDLERS) { int powerUsePerTick = handler.getPowerUsePerTick(); if (powerUsePerTick >= 0) { return powerUsePerTick; } } return 0; } @Override public long getBurnTime(@Nonnull ItemStack itemstack) { for (ISolidFuelHandler handler : HANDLERS) { long burnTime = handler.getBurnTime(itemstack); if (burnTime >= 0) { return burnTime; } } return -1; } }; public static void registerSolidFuelHandler(@Nonnull ISolidFuelHandler handler) { HANDLERS.add(handler); } @SideOnly(Side.CLIENT) public static ISolidFuelHandler getActiveSolidFuelHandler() { EntityPlayer player = Minecraft.getMinecraft().player; if (NullHelper.untrust(player) == null) { return DEFAULT; } if (player.openContainer instanceof ISolidFuelHandler) { return (ISolidFuelHandler) player.openContainer; } else if (player.openContainer instanceof ISolidFuelHandler.Provider) { return ((ISolidFuelHandler.Provider) player.openContainer).getSolidFuelHandler(); } return DEFAULT; } }
922
361
<reponame>vpapanchev/universal-resolver<gh_stars>100-1000 package uniresolver.examples; import uniresolver.driver.did.sov.DidSovDriver; import uniresolver.local.LocalUniResolver; import uniresolver.result.ResolveResult; import java.util.HashMap; import java.util.Map; public class TestLocalUniResolver { public static void main(String[] args) throws Exception { LocalUniResolver uniResolver = new LocalUniResolver(); uniResolver.getDrivers().add(new DidSovDriver()); uniResolver.getDriver(DidSovDriver.class).setLibIndyPath("./sovrin/lib/libindy.so"); uniResolver.getDriver(DidSovDriver.class).setPoolConfigs("_;./sovrin/mainnet.txn"); uniResolver.getDriver(DidSovDriver.class).setPoolVersions("_;2"); Map<String, Object> resolveOptions = new HashMap<>(); resolveOptions.put("accept", "application/did+ld+json"); ResolveResult resolveResult; resolveResult = uniResolver.resolve("did:sov:WRfXPg8dantKVubE3HX8pw", resolveOptions); System.out.println(resolveResult.toJson()); resolveResult = uniResolver.resolveRepresentation("did:sov:WRfXPg8dantKVubE3HX8pw", resolveOptions); System.out.println(resolveResult.toJson()); } }
416
400
<gh_stars>100-1000 package org.ofdrw.core.basicStructure.doc.vpreferences; /** * 窗口模式 * <p> * 7.5 表 9 视图首选项属性 * <p> * 默认值为 None * * @author 权观宇 * @since 2019-10-07 06:33:01 */ public enum PageMode { /** * 常规模式 */ None, /** * 开开后全文显示 */ FullScreen, /** * 同时呈现文档大纲 */ UseOutlines, /** * 同时呈现缩略图 */ UseThumbs, /** * 同时呈现语义结构 */ UseCustomTags, /** * 同时呈现图层 */ UseLayers, /** * 同时呈现附件 */ UseAttatchs, /** * 同时呈现书签 */ UseBookmarks; /** * 获取窗口模式实例 * * @param mode 模式名称 * @return 实例 */ public static PageMode getInstance(String mode) { mode = mode == null ? "" : mode.trim(); switch (mode) { case "": case "None": return None; case "FullScreen": return FullScreen; case "UseOutlines": return UseOutlines; case "UseThumbs": return UseThumbs; case "UseCustomTags": return UseCustomTags; case "UseLayers": return UseLayers; case "UseAttatchs": return UseAttatchs; case "UseBookmarks": return UseBookmarks; default: throw new IllegalArgumentException("未知的窗口模式:" + mode); } } }
982
848
/* * Copyright 2019 Xilinx Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <algorithm> #include <functional> #include <memory> #include <vart/runner.hpp> #include <vitis/ai/with_injection.hpp> namespace vart { namespace dpu { class DpuSession : public vitis::ai::WithInjection<DpuSession> { public: explicit DpuSession() = default; public: DpuSession(const DpuSession&) = delete; DpuSession& operator=(const DpuSession& other) = delete; virtual ~DpuSession() = default; public: virtual std::unique_ptr<vart::Runner> create_runner() = 0; virtual std::vector<vart::TensorBuffer*> get_inputs() = 0; virtual std::vector<vart::TensorBuffer*> get_outputs() = 0; virtual std::vector<const xir::Tensor*> get_input_tensors() const = 0; virtual std::vector<const xir::Tensor*> get_output_tensors() const = 0; }; } // namespace dpu } // namespace vart
437
334
/* Copyright (c) 2007-2015 Contributors as noted in the AUTHORS file This file is part of libzmq, the ZeroMQ core engine in C++. libzmq is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. As a special exception, the Contributors give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you must extend this exception to your version of the library. libzmq 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 this program. If not, see <http://www.gnu.org/licenses/>. */ #include "testutil.hpp" #include <zmq.h> #include <stdio.h> #include <stdlib.h> #include <vector> void test_system_max () { // Keep allocating sockets until we run out of system resources const int no_of_sockets = 2 * 65536; void *ctx = zmq_ctx_new (); zmq_ctx_set (ctx, ZMQ_MAX_SOCKETS, no_of_sockets); std::vector <void*> sockets; while (true) { void *socket = zmq_socket (ctx, ZMQ_PAIR); if (!socket) break; sockets.push_back (socket); } assert ((int) sockets.size () < no_of_sockets); // System is out of resources, further calls to zmq_socket should return NULL for (unsigned int i = 0; i < 10; ++i) { void *socket = zmq_socket (ctx, ZMQ_PAIR); assert (socket == NULL); } // Clean up. for (unsigned int i = 0; i < sockets.size (); ++i) zmq_close (sockets [i]); zmq_ctx_destroy (ctx); } void test_zmq_default_max () { // Keep allocating sockets until we hit the default limit void *ctx = zmq_ctx_new (); std::vector<void*> sockets; while (true) { void *socket = zmq_socket (ctx, ZMQ_PAIR); if (!socket) break; sockets.push_back (socket); } // We may stop sooner if system has fewer available sockets assert (sockets.size () <= ZMQ_MAX_SOCKETS_DFLT); // Further calls to zmq_socket should return NULL for (unsigned int i = 0; i < 10; ++i) { void *socket = zmq_socket (ctx, ZMQ_PAIR); assert (socket == NULL); } // Clean up for (unsigned int i = 0; i < sockets.size (); ++i) zmq_close (sockets [i]); zmq_ctx_destroy (ctx); } int main (void) { setup_test_environment (); test_system_max (); test_zmq_default_max (); return 0; }
1,162
8,572
@import XCTest; /** Runs an XCTestSuite instance containing only the given XCTestCase subclass. Use this to run QuickSpec subclasses from within a set of unit tests. Due to implicit dependencies in _XCTFailureHandler, this function raises an exception when used in Swift to run a failing test case. @param specClass The class of the spec to be run. @return An XCTestRun instance that contains information such as the number of failures, etc. */ extern XCTestRun * _Nullable qck_runSpec(Class _Nonnull specClass); /** Runs an XCTestSuite instance containing the given XCTestCase subclasses, in the order provided. See the documentation for `qck_runSpec` for more details. @param specClasses An array of QuickSpec classes, in the order they should be run. @return An XCTestRun instance that contains information such as the number of failures, etc. */ extern XCTestRun * _Nullable qck_runSpecs(NSArray * _Nonnull specClasses);
251
1,768
<reponame>zwergziege/tlaplus // Copyright (c) 2003 Compaq Corporation. All rights reserved. // Last modified on Wed Oct 17 15:25:39 PDT 2001 by yuanyu package util; import java.io.IOException; import java.io.Serializable; import java.util.Map; import tlc2.tool.Defns; import tlc2.tool.TLCState; import tlc2.tool.distributed.InternRMI; import tlc2.util.FP64; /** * For any string (state variable, operator definition) the strings are stored * only once for the entire run. This leads to a major speed-up in string comparison.<br> * * This class serves multiple purposes. * <br><br> * * The primary purpose is to use instances of this class as a wrapper or * data holder inside of the {@link InternTable}. The latter is organized that way, that it holds an * array of UniqueStrings. Each UniqueString that is created is put at most once into the table, and holds * the information of its location in the table. The member variable {@link UniqueString#s} is used to represent * the content, the member variable {@link UniqueString#tok} holds the position inside of the {@link InternTable}. * The following methods are responsible for access to content and position: * <ul> * <li>{@link UniqueString#compareTo(UniqueString)}</li> * <li>{@link UniqueString#concat(UniqueString)}</li> * <li>{@link UniqueString#equals(UniqueString)}</li> * <li>{@link UniqueString#equals(String)}</li> * <li>{@link UniqueString#getTok()}</li> * <li>{@link UniqueString#hashCode()}</li> * <li>{@link UniqueString#length()}</li> * <li>{@link UniqueString#toString()}</li> * </ul> * <br> * In addition, there exist two types of externally stored tables: the array of values of state variables * in subclasses of {@link TLCState}, and array of operator definitions in {@link Defns}. The main scheme * behind the storage of the objects in these arrays is that the value of a variable / operation * definition with name, identified by a UniqueString <code>foo</code> is stored at position, in the array, that is * stored inside of <code>foo</code>, using the instance member {@link UniqueString#loc}. Note, that multiple instances * of TLCState store values of variables on the same position in their arrays and only one Defn instance * exist. This is OK, because the state variable are global. * <br> * In order to distinguish between the index in the state variable array and index of operator definition array, * the number of state variables defined in the specification is maintained in the static member {@link UniqueString#varCount}. * The methods that are responsible for this feature are: * <ul> * <li>{@link UniqueString#getDefnLoc()}</li> * <li>{@link UniqueString#getVarLoc()}</li> * <li>{@link UniqueString#setLoc(int)}</li> * <li>{@link UniqueString#setVariableCount(int)}</li> * </ul> * <br> * Finally, there are two methods responsible for marshaling/un-marshaling and convenience methods to put and get unique * string into and out of the InternTable * * @author <NAME>, <NAME> */ public final class UniqueString implements Serializable { /** * Maps from strings to variables. */ public static InternTable internTbl = null; /** * The string content */ private String s; /** * The unique integer assigned to the string. */ private int tok; /** * If this unique string is a state variable, this is the location of this * variable in {@link TLCState}. If this string is the name of an operator * definition, this is the location of this definition in {@link Defns}. */ private int loc = -1; // SZ 10.04.2009: removed the getter method // since it is only needed in Spec#processSpec and the setter is called from there private static int varCount; /** * Call static constructor method for call not out of TLC */ static { UniqueString.initialize(); } /** * Static constructor method */ public static void initialize() { internTbl = new InternTable(1024); varCount = 0; } /** * Protected constructor, used from utility methods * @param str a string to be saved * @param tok the unique integer for this string (position in the InternalTable) */ protected UniqueString(String str, int tok) { this.s = str; this.tok = tok; } /** * Private constructor, used on marshaling/un-marshaling * @param str a string to be saved * @param tok the unique integer for this string (position in the InternalTable) * @param loc location inside of the state/definition table */ private UniqueString(String str, int tok, int loc) { this(str, tok); this.loc = loc; } /** * Sets the number of variables in the spec * @param varCount number of variables defined */ public static void setVariableCount(int varCount) { UniqueString.varCount = varCount; // SZ 10.04.2009: changed the method signature from setVariables(UniqueString[]) // to setVariableCount(int), since the method is effectively only responsible // for storing this information in the static field of this class. // SZ 10.04.2009: removed the loop that runs through the variable names // and sets the Loc field of each variable name to it's order in the list // moved it to the place where the variables are initialized } /** * Returns the location of this variable in a state, if the name is a * variable. Otherwise, returns -1. */ public int getVarLoc() { return (this.loc < varCount) ? this.loc : -1; } /** * Returns the location of this operator in defns, if it is the name * of an operator. Otherwise, returns -1. */ public int getDefnLoc() { return (this.loc < varCount) ? -1 : this.loc; } /** * Set this string's location in either the state or the defns. * This is fishy to store location outside of the storage * * @see {@link TLCState} * @see {@link Defns} */ public void setLoc(int loc) { this.loc = loc; } /** * Retrieves the unique number associated with this string * @return */ public int getTok() { return this.tok; } /** * Concatenates two unique strings */ public UniqueString concat(UniqueString uniqueString) { return uniqueStringOf(this.toString() + uniqueString.toString()); } public UniqueString concat(String string) { return uniqueStringOf(this.toString() + string); } /** * Delivers the stored string */ public String toString() { return this.s; } /** * @see {@link String#hashCode()} */ public int hashCode() { return this.s.hashCode(); } /** * @see {@link String#length()} */ public int length() { return this.s.length(); } /** * Not a compare method as usual for objects * Delivers the difference in positions inside of the table, the unique strings are stored in * @param uniqueString * @return */ public int compareTo(UniqueString uniqueString) { // SZ 10.04.2009: very strange way to compare strings // return this.s.compareTo(t.s); return this.tok - uniqueString.tok; } /** * Since uniqueness is guaranteed, the equals is a high performance reference comparison */ public boolean equals(UniqueString t) { return this.tok == t.tok; } /** * There is no performance gain to compare with a string. */ public boolean equals(String t) { return this.s.equals(t); } public long fingerPrint(long fp) { return FP64.Extend(fp, this.tok); } /** * Returns a unique object associated with string str. That is, * the first time uniqueStringOf("foo") is called, it returns a * new object o. Subsequent invocations of uniqueStringOf("foo") * return the same object o. * * This is a convenience method for a table put. */ public static UniqueString uniqueStringOf(String str) { return internTbl.put(str); } public static UniqueString of(String str) { return uniqueStringOf(str); } public static UniqueString join(String delim, UniqueString... us) { return join(delim, us.length, us); } public static UniqueString join(String delim, int n, UniqueString... us) { assert 0 < n && n <= us.length; UniqueString out = null; for (int i = 0; i < n; i++) { if (out == null) { out = us[i]; } else { out = out.concat("!"); out = out.concat(us[i]); } } return out; } /** * If there exists a UniqueString object obj such that obj.getTok() * equals tok, then uidToUniqueString(i) returns obj; otherwise, * it returns null. * * This is a convenience method for a table lookup. */ public static UniqueString uidToUniqueString(int tok) { return internTbl.get(tok); } /** * Writes current unique string to the stream * @param dos * @return * @throws IOException */ public final void write(IDataOutputStream dos) throws IOException { dos.writeInt(this.tok); dos.writeInt(this. getVarLoc()); // Above changed from dos.writeInt(this.loc); by <NAME> on 17 Mar 2010 dos.writeInt(this.s.length()); dos.writeString(this.s); } /** * Utility method for reading a unique string from the stream * @param dis * @return * @throws IOException * * The method does not change member/class variables */ public static UniqueString read(IDataInputStream dis) throws IOException { int tok1 = dis.readInt(); int loc1 = dis.readInt(); int slen = dis.readInt(); String str = dis.readString(slen); return new UniqueString(str, tok1, loc1); } public static UniqueString read(IDataInputStream dis, final Map<String, UniqueString> tbl) throws IOException { dis.readInt(); // skip, because invalid for the given internTbl dis.readInt(); // skip, because invalid for the given internTbl final int slen = dis.readInt(); final String str = dis.readString(slen); return tbl.get(str); } /** * Sets the source * @param source */ public static void setSource(InternRMI source) { internTbl.setSource(source); } }
3,896
303
/** * 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.codelibs.elasticsearch.taste.model; import java.io.Serializable; /** * Encapsulates a simple boolean "preference" for an item whose value does not matter (is fixed at 1.0). This * is appropriate in situations where users conceptually have only a general "yes" preference for items, * rather than a spectrum of preference values. */ public final class BooleanPreference implements Preference, Serializable { /** * */ private static final long serialVersionUID = 1L; private final long userID; private final long itemID; public BooleanPreference(final long userID, final long itemID) { this.userID = userID; this.itemID = itemID; } @Override public long getUserID() { return userID; } @Override public long getItemID() { return itemID; } @Override public float getValue() { return 1.0f; } @Override public void setValue(final float value) { throw new UnsupportedOperationException(); } @Override public String toString() { return "BooleanPreference[userID: " + userID + ", itemID:" + itemID + ']'; } }
626
1,210
/* (c) 2014 <NAME> glenjofe at gmail dot com Distributed under the Boost Software License, Version 1.0. http://boost.org/LICENSE_1_0.txt */ #ifndef BOOST_ALIGN_DETAIL_MAX_ALIGN_HPP #define BOOST_ALIGN_DETAIL_MAX_ALIGN_HPP #include <boost/align/detail/integral_constant.hpp> #include <cstddef> namespace boost { namespace alignment { namespace detail { template<std::size_t A, std::size_t B> struct max_align : integral_constant<std::size_t, (A > B) ? A : B> { }; } /* :detail */ } /* :alignment */ } /* :boost */ #endif
220
713
<reponame>t-gergely/infinispan package org.infinispan.commons.time; import java.time.Instant; import java.util.concurrent.TimeUnit; import org.infinispan.commons.logging.Log; import org.infinispan.commons.logging.LogFactory; /** * TimeService that allows for wall clock time to be adjust manually. */ public class ControlledTimeService extends DefaultTimeService { private static final Log log = LogFactory.getLog(ControlledTimeService.class); private final Object id; protected volatile long currentMillis; public ControlledTimeService() { this(null); } public ControlledTimeService(Object id) { this(id, 1_000_000L); } public ControlledTimeService(Object id, ControlledTimeService other) { this(id, other.currentMillis); } private ControlledTimeService(Object id, long currentMillis) { this.id = id; this.currentMillis = currentMillis; } @Override public long wallClockTime() { return currentMillis; } @Override public long time() { return TimeUnit.MILLISECONDS.toNanos(currentMillis); } @Override public Instant instant() { return Instant.ofEpochMilli(currentMillis); } public void advance(long delta, TimeUnit timeUnit) { advance(timeUnit.toMillis(delta)); } public synchronized void advance(long deltaMillis) { if (deltaMillis <= 0) { throw new IllegalArgumentException("Argument must be greater than 0"); } currentMillis += deltaMillis; log.tracef("Current time for %s is now %d", id, currentMillis); } }
550
360
import numpy as np from yt.testing import assert_almost_equal, assert_equal, fake_sph_grid_ds n_ref = 4 def test_building_tree(): """ Build an octree and make sure correct number of particles """ ds = fake_sph_grid_ds() octree = ds.octree(n_ref=n_ref) assert octree[("index", "x")].shape[0] == 17 def test_sph_interpolation_scatter(): """ Generate an octree, perform some SPH interpolation and check with some answer testing """ ds = fake_sph_grid_ds(hsml_factor=26.0) ds._sph_ptypes = ("io",) ds.use_sph_normalization = False octree = ds.octree(n_ref=n_ref) density = octree[("io", "density")] answers = np.array( [ 1.00434706, 1.00434706, 1.00434706, 1.00434706, 1.00434706, 1.00434706, 1.00434706, 0.7762907, 0.89250848, 0.89250848, 0.97039088, 0.89250848, 0.97039088, 0.97039088, 1.01156175, ] ) assert_almost_equal(density.d, answers) def test_sph_interpolation_gather(): """ Generate an octree, perform some SPH interpolation and check with some answer testing """ ds = fake_sph_grid_ds(hsml_factor=26.0) ds.index ds._sph_ptypes = ("io",) ds.sph_smoothing_style = "gather" ds.num_neighbors = 5 ds.use_sph_normalization = False octree = ds.octree(n_ref=n_ref) density = octree[("io", "density")] answers = np.array( [ 0.59240874, 0.59240874, 0.59240874, 0.59240874, 0.59240874, 0.59240874, 0.59240874, 0.10026846, 0.77014968, 0.77014968, 0.96127825, 0.77014968, 0.96127825, 0.96127825, 1.21183996, ] ) assert_almost_equal(density.d, answers) def test_octree_properties(): """ Generate an octree, and test the refinement, depth and sizes of the cells. """ ds = fake_sph_grid_ds() octree = ds.octree(n_ref=n_ref) depth = octree[("index", "depth")] depth_ans = np.array([0] + [1] * 8 + [2] * 8, dtype=np.int64) assert_equal(depth, depth_ans) size_ans = np.zeros((depth.shape[0], 3), dtype=np.float64) for i in range(size_ans.shape[0]): size_ans[i, :] = (ds.domain_right_edge - ds.domain_left_edge) / 2.0 ** depth[i] dx = octree[("index", "dx")].d assert_almost_equal(dx, size_ans[:, 0]) dy = octree[("index", "dy")].d assert_almost_equal(dy, size_ans[:, 1]) dz = octree[("index", "dz")].d assert_almost_equal(dz, size_ans[:, 2]) refined = octree[("index", "refined")] refined_ans = np.array([True] + [False] * 7 + [True] + [False] * 8, dtype=np.bool_) assert_equal(refined, refined_ans)
1,536
879
package org.zstack.header.message; /** * Created by MaJin on 2020/10/28. */ public interface ReplayableMessage { String getResourceUuid(); Class getReplayableClass(); }
60
317
#import "HCTestFailureHandler.h" @interface HCSenTestFailureHandler : NSObject <HCTestFailureHandler> @end
35
2,151
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/http/http_server_properties_manager.h" #include <utility> #include "base/bind.h" #include "base/json/json_reader.h" #include "base/json/json_writer.h" #include "base/macros.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" #include "base/threading/thread_task_runner_handle.h" #include "base/values.h" #include "net/base/ip_address.h" #include "net/http/http_network_session.h" #include "net/test/test_with_scoped_task_environment.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" namespace net { namespace { using base::StringPrintf; using ::testing::_; using ::testing::AtLeast; using ::testing::Invoke; using ::testing::Mock; using ::testing::StrictMock; class MockPrefDelegate : public net::HttpServerPropertiesManager::PrefDelegate { public: MockPrefDelegate() = default; ~MockPrefDelegate() override = default; // HttpServerPropertiesManager::PrefDelegate implementation. const base::DictionaryValue* GetServerProperties() const override { return &prefs_; } void SetServerProperties(const base::DictionaryValue& value, base::OnceClosure callback) override { prefs_.Clear(); prefs_.MergeDictionary(&value); ++num_pref_updates_; if (!prefs_changed_callback_.is_null()) prefs_changed_callback_.Run(); if (!extra_prefs_changed_callback_.is_null()) extra_prefs_changed_callback_.Run(); set_properties_callback_ = std::move(callback); } void StartListeningForUpdates(const base::Closure& callback) override { CHECK(prefs_changed_callback_.is_null()); prefs_changed_callback_ = callback; } void SetPrefs(const base::DictionaryValue& value) { // prefs_ = value; prefs_.Clear(); prefs_.MergeDictionary(&value); if (!prefs_changed_callback_.is_null()) prefs_changed_callback_.Run(); } int GetAndClearNumPrefUpdates() { int out = num_pref_updates_; num_pref_updates_ = 0; return out; } // Additional callback to call when prefs are updated, used to check prefs are // updated on destruction. void set_extra_update_prefs_callback(const base::Closure& callback) { extra_prefs_changed_callback_ = callback; } // Returns the base::OnceCallback, if any, passed to the last call to // SetServerProperties(). base::OnceClosure GetSetPropertiesCallback() { return std::move(set_properties_callback_); } private: base::DictionaryValue prefs_; base::Closure prefs_changed_callback_; base::Closure extra_prefs_changed_callback_; int num_pref_updates_ = 0; base::OnceClosure set_properties_callback_; DISALLOW_COPY_AND_ASSIGN(MockPrefDelegate); }; } // namespace // TODO(rtenneti): After we stop supporting version 3 and everyone has migrated // to version 4, delete the following code. static const int kHttpServerPropertiesVersions[] = {3, 4, 5}; class HttpServerPropertiesManagerTest : public testing::TestWithParam<int>, public WithScopedTaskEnvironment { protected: HttpServerPropertiesManagerTest() : WithScopedTaskEnvironment( base::test::ScopedTaskEnvironment::MainThreadType::MOCK_TIME) {} void SetUp() override { one_day_from_now_ = base::Time::Now() + base::TimeDelta::FromDays(1); advertised_versions_ = HttpNetworkSession::Params().quic_supported_versions; pref_delegate_ = new MockPrefDelegate; http_server_props_manager_ = std::make_unique<HttpServerPropertiesManager>( base::WrapUnique(pref_delegate_), /*net_log=*/nullptr, GetMockTickClock()); EXPECT_FALSE(http_server_props_manager_->IsInitialized()); pref_delegate_->SetPrefs(base::DictionaryValue()); EXPECT_TRUE(http_server_props_manager_->IsInitialized()); EXPECT_FALSE(MainThreadHasPendingTask()); EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates()); } void TearDown() override { // Run pending non-delayed tasks but don't FastForwardUntilNoTasksRemain() // as some delayed tasks may forever repost (e.g. because impl doesn't use a // mock clock and doesn't see timings as having expired, ref. // HttpServerPropertiesImpl:: // ScheduleBrokenAlternateProtocolMappingsExpiration()). base::RunLoop().RunUntilIdle(); http_server_props_manager_.reset(); } bool HasAlternativeService(const url::SchemeHostPort& server) { const AlternativeServiceInfoVector alternative_service_info_vector = http_server_props_manager_->GetAlternativeServiceInfos(server); return !alternative_service_info_vector.empty(); } MockPrefDelegate* pref_delegate_; // Owned by HttpServerPropertiesManager. std::unique_ptr<HttpServerPropertiesManager> http_server_props_manager_; base::Time one_day_from_now_; QuicTransportVersionVector advertised_versions_; private: DISALLOW_COPY_AND_ASSIGN(HttpServerPropertiesManagerTest); }; INSTANTIATE_TEST_CASE_P(/* no prefix */, HttpServerPropertiesManagerTest, ::testing::ValuesIn(kHttpServerPropertiesVersions)); TEST_P(HttpServerPropertiesManagerTest, SingleUpdateForTwoSpdyServerPrefChanges) { // Set up the prefs for https://www.google.com and https://mail.google.com and // then set it twice. Only expect a single cache update. auto server_pref_dict = std::make_unique<base::DictionaryValue>(); url::SchemeHostPort google_server("https", "www.google.com", 443); url::SchemeHostPort mail_server("https", "mail.google.com", 443); // Set supports_spdy for https://www.google.com:443. server_pref_dict->SetBoolean("supports_spdy", true); // Set up alternative_services for https://www.google.com. auto alternative_service_dict0 = std::make_unique<base::DictionaryValue>(); alternative_service_dict0->SetInteger("port", 443); alternative_service_dict0->SetString("protocol_str", "h2"); auto alternative_service_dict1 = std::make_unique<base::DictionaryValue>(); alternative_service_dict1->SetInteger("port", 1234); alternative_service_dict1->SetString("protocol_str", "quic"); auto alternative_service_list0 = std::make_unique<base::ListValue>(); alternative_service_list0->Append(std::move(alternative_service_dict0)); alternative_service_list0->Append(std::move(alternative_service_dict1)); server_pref_dict->SetWithoutPathExpansion( "alternative_service", std::move(alternative_service_list0)); // Set up ServerNetworkStats for https://www.google.com. auto stats = std::make_unique<base::DictionaryValue>(); stats->SetInteger("srtt", 10); server_pref_dict->SetWithoutPathExpansion("network_stats", std::move(stats)); // Set the server preference for https://www.google.com. auto servers_dict = std::make_unique<base::DictionaryValue>(); servers_dict->SetWithoutPathExpansion( GetParam() >= 5 ? "https://www.google.com" : "www.google.com:443", std::move(server_pref_dict)); std::unique_ptr<base::ListValue> servers_list; if (GetParam() >= 4) { servers_list = std::make_unique<base::ListValue>(); servers_list->Append(std::move(servers_dict)); servers_dict = std::make_unique<base::DictionaryValue>(); } // Set the preference for mail.google.com server. auto server_pref_dict1 = std::make_unique<base::DictionaryValue>(); // Set supports_spdy for https://mail.google.com. server_pref_dict1->SetBoolean("supports_spdy", true); // Set up alternative_services for https://mail.google.com. auto alternative_service_dict2 = std::make_unique<base::DictionaryValue>(); alternative_service_dict2->SetString("protocol_str", "h2"); alternative_service_dict2->SetInteger("port", 444); auto alternative_service_list1 = std::make_unique<base::ListValue>(); alternative_service_list1->Append(std::move(alternative_service_dict2)); server_pref_dict1->SetWithoutPathExpansion( "alternative_service", std::move(alternative_service_list1)); // Set up ServerNetworkStats for https://mail.google.com and it is the MRU // server. auto stats1 = std::make_unique<base::DictionaryValue>(); stats1->SetInteger("srtt", 20); server_pref_dict1->SetWithoutPathExpansion("network_stats", std::move(stats1)); // Set the server preference for https://mail.google.com. servers_dict->SetWithoutPathExpansion( GetParam() >= 5 ? "https://mail.google.com" : "mail.google.com:443", std::move(server_pref_dict1)); base::DictionaryValue http_server_properties_dict; if (GetParam() >= 4) { servers_list->AppendIfNotPresent(std::move(servers_dict)); if (GetParam() == 5) { HttpServerPropertiesManager::SetVersion(&http_server_properties_dict, -1); } else { HttpServerPropertiesManager::SetVersion(&http_server_properties_dict, GetParam()); } http_server_properties_dict.SetWithoutPathExpansion( "servers", std::move(servers_list)); } else { HttpServerPropertiesManager::SetVersion(&http_server_properties_dict, GetParam()); http_server_properties_dict.SetWithoutPathExpansion( "servers", std::move(servers_dict)); } auto supports_quic = std::make_unique<base::DictionaryValue>(); supports_quic->SetBoolean("used_quic", true); supports_quic->SetString("address", "127.0.0.1"); http_server_properties_dict.SetWithoutPathExpansion("supports_quic", std::move(supports_quic)); // Set quic_server_info for https://www.google.com, https://mail.google.com // and https://play.google.com and verify the MRU. http_server_props_manager_->SetMaxServerConfigsStoredInProperties(3); auto quic_servers_dict = std::make_unique<base::DictionaryValue>(); auto quic_server_pref_dict1 = std::make_unique<base::DictionaryValue>(); std::string quic_server_info1("quic_server_info1"); quic_server_pref_dict1->SetKey("server_info", base::Value(quic_server_info1)); auto quic_server_pref_dict2 = std::make_unique<base::DictionaryValue>(); std::string quic_server_info2("quic_server_info2"); quic_server_pref_dict2->SetKey("server_info", base::Value(quic_server_info2)); auto quic_server_pref_dict3 = std::make_unique<base::DictionaryValue>(); std::string quic_server_info3("quic_server_info3"); quic_server_pref_dict3->SetKey("server_info", base::Value(quic_server_info3)); // Set the quic_server_info1 for https://www.google.com. QuicServerId google_quic_server_id("www.google.com", 443); quic_servers_dict->SetWithoutPathExpansion(google_quic_server_id.ToString(), std::move(quic_server_pref_dict1)); // Set the quic_server_info2 for https://mail.google.com. QuicServerId mail_quic_server_id("mail.google.com", 443); quic_servers_dict->SetWithoutPathExpansion(mail_quic_server_id.ToString(), std::move(quic_server_pref_dict2)); // Set the quic_server_info3 for https://play.google.com. QuicServerId play_quic_server_id("play.google.com", 443); quic_servers_dict->SetWithoutPathExpansion(play_quic_server_id.ToString(), std::move(quic_server_pref_dict3)); http_server_properties_dict.SetWithoutPathExpansion( "quic_servers", std::move(quic_servers_dict)); // Set the same value for kHttpServerProperties multiple times. pref_delegate_->SetPrefs(http_server_properties_dict); pref_delegate_->SetPrefs(http_server_properties_dict); // Should be a delayed task to update the cache from the prefs file. EXPECT_TRUE(MainThreadHasPendingTask()); FastForwardUntilNoTasksRemain(); // Verify SupportsSpdy. EXPECT_TRUE( http_server_props_manager_->SupportsRequestPriority(google_server)); EXPECT_TRUE(http_server_props_manager_->SupportsRequestPriority(mail_server)); HostPortPair foo_host_port_pair = HostPortPair::FromString("foo.google.com:1337"); url::SchemeHostPort foo_server("http", foo_host_port_pair.host(), foo_host_port_pair.port()); EXPECT_FALSE(http_server_props_manager_->SupportsRequestPriority(foo_server)); // Verify alternative service. const AlternativeServiceMap& map = http_server_props_manager_->alternative_service_map(); ASSERT_EQ(2u, map.size()); AlternativeServiceMap::const_iterator map_it = map.begin(); EXPECT_EQ("www.google.com", map_it->first.host()); ASSERT_EQ(2u, map_it->second.size()); EXPECT_EQ(kProtoHTTP2, map_it->second[0].alternative_service().protocol); EXPECT_TRUE(map_it->second[0].alternative_service().host.empty()); EXPECT_EQ(443, map_it->second[0].alternative_service().port); EXPECT_EQ(kProtoQUIC, map_it->second[1].alternative_service().protocol); EXPECT_TRUE(map_it->second[1].alternative_service().host.empty()); EXPECT_EQ(1234, map_it->second[1].alternative_service().port); ++map_it; EXPECT_EQ("mail.google.com", map_it->first.host()); ASSERT_EQ(1u, map_it->second.size()); EXPECT_EQ(kProtoHTTP2, map_it->second[0].alternative_service().protocol); EXPECT_TRUE(map_it->second[0].alternative_service().host.empty()); EXPECT_EQ(444, map_it->second[0].alternative_service().port); // Verify SupportsQuic. IPAddress last_address; EXPECT_TRUE(http_server_props_manager_->GetSupportsQuic(&last_address)); EXPECT_EQ("127.0.0.1", last_address.ToString()); // Verify ServerNetworkStats. const ServerNetworkStats* stats2 = http_server_props_manager_->GetServerNetworkStats(google_server); EXPECT_EQ(10, stats2->srtt.ToInternalValue()); const ServerNetworkStats* stats3 = http_server_props_manager_->GetServerNetworkStats(mail_server); EXPECT_EQ(20, stats3->srtt.ToInternalValue()); // Verify QuicServerInfo. EXPECT_EQ(quic_server_info1, *http_server_props_manager_->GetQuicServerInfo( google_quic_server_id)); EXPECT_EQ(quic_server_info2, *http_server_props_manager_->GetQuicServerInfo( mail_quic_server_id)); EXPECT_EQ(quic_server_info3, *http_server_props_manager_->GetQuicServerInfo( play_quic_server_id)); // Verify the MRU order. http_server_props_manager_->SetMaxServerConfigsStoredInProperties(2); EXPECT_EQ(nullptr, http_server_props_manager_->GetQuicServerInfo( google_quic_server_id)); EXPECT_EQ(quic_server_info2, *http_server_props_manager_->GetQuicServerInfo( mail_quic_server_id)); EXPECT_EQ(quic_server_info3, *http_server_props_manager_->GetQuicServerInfo( play_quic_server_id)); } TEST_P(HttpServerPropertiesManagerTest, BadCachedHostPortPair) { auto server_pref_dict = std::make_unique<base::DictionaryValue>(); // Set supports_spdy for www.google.com:65536. server_pref_dict->SetBoolean("supports_spdy", true); // Set up alternative_service for www.google.com:65536. auto alternative_service_dict = std::make_unique<base::DictionaryValue>(); alternative_service_dict->SetString("protocol_str", "h2"); alternative_service_dict->SetInteger("port", 80); auto alternative_service_list = std::make_unique<base::ListValue>(); alternative_service_list->Append(std::move(alternative_service_dict)); server_pref_dict->SetWithoutPathExpansion( "alternative_service", std::move(alternative_service_list)); // Set up ServerNetworkStats for www.google.com:65536. auto stats = std::make_unique<base::DictionaryValue>(); stats->SetInteger("srtt", 10); server_pref_dict->SetWithoutPathExpansion("network_stats", std::move(stats)); // Set the server preference for www.google.com:65536. auto servers_dict = std::make_unique<base::DictionaryValue>(); servers_dict->SetWithoutPathExpansion("www.google.com:65536", std::move(server_pref_dict)); base::DictionaryValue http_server_properties_dict; if (GetParam() >= 4) { auto servers_list = std::make_unique<base::ListValue>(); servers_list->Append(std::move(servers_dict)); if (GetParam() == 5) { HttpServerPropertiesManager::SetVersion(&http_server_properties_dict, -1); } else { HttpServerPropertiesManager::SetVersion(&http_server_properties_dict, GetParam()); } http_server_properties_dict.SetWithoutPathExpansion( "servers", std::move(servers_list)); } else { HttpServerPropertiesManager::SetVersion(&http_server_properties_dict, GetParam()); http_server_properties_dict.SetWithoutPathExpansion( "servers", std::move(servers_dict)); } // Set quic_server_info for www.google.com:65536. auto quic_servers_dict = std::make_unique<base::DictionaryValue>(); auto quic_server_pref_dict1 = std::make_unique<base::DictionaryValue>(); quic_server_pref_dict1->SetKey("server_info", base::Value("quic_server_info1")); quic_servers_dict->SetWithoutPathExpansion("http://mail.google.com:65536", std::move(quic_server_pref_dict1)); http_server_properties_dict.SetWithoutPathExpansion( "quic_servers", std::move(quic_servers_dict)); // Set up the pref. pref_delegate_->SetPrefs(http_server_properties_dict); EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates()); EXPECT_TRUE(MainThreadHasPendingTask()); FastForwardUntilNoTasksRemain(); // Prefs should have been overwritten, due to the bad data. EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates()); // Verify that nothing is set. HostPortPair google_host_port_pair = HostPortPair::FromString("www.google.com:65536"); url::SchemeHostPort gooler_server("http", google_host_port_pair.host(), google_host_port_pair.port()); EXPECT_FALSE( http_server_props_manager_->SupportsRequestPriority(gooler_server)); EXPECT_FALSE(HasAlternativeService(gooler_server)); const ServerNetworkStats* stats1 = http_server_props_manager_->GetServerNetworkStats(gooler_server); EXPECT_EQ(nullptr, stats1); EXPECT_EQ(0u, http_server_props_manager_->quic_server_info_map().size()); } TEST_P(HttpServerPropertiesManagerTest, BadCachedAltProtocolPort) { auto server_pref_dict = std::make_unique<base::DictionaryValue>(); // Set supports_spdy for www.google.com:80. server_pref_dict->SetBoolean("supports_spdy", true); // Set up alternative_service for www.google.com:80. auto alternative_service_dict = std::make_unique<base::DictionaryValue>(); alternative_service_dict->SetString("protocol_str", "h2"); alternative_service_dict->SetInteger("port", 65536); auto alternative_service_list = std::make_unique<base::ListValue>(); alternative_service_list->Append(std::move(alternative_service_dict)); server_pref_dict->SetWithoutPathExpansion( "alternative_service", std::move(alternative_service_list)); // Set the server preference for www.google.com:80. auto servers_dict = std::make_unique<base::DictionaryValue>(); servers_dict->SetWithoutPathExpansion("www.google.com:80", std::move(server_pref_dict)); base::DictionaryValue http_server_properties_dict; if (GetParam() >= 4) { auto servers_list = std::make_unique<base::ListValue>(); servers_list->Append(std::move(servers_dict)); if (GetParam() == 5) { HttpServerPropertiesManager::SetVersion(&http_server_properties_dict, -1); } else { HttpServerPropertiesManager::SetVersion(&http_server_properties_dict, GetParam()); } http_server_properties_dict.SetWithoutPathExpansion( "servers", std::move(servers_list)); } else { HttpServerPropertiesManager::SetVersion(&http_server_properties_dict, GetParam()); http_server_properties_dict.SetWithoutPathExpansion( "servers", std::move(servers_dict)); } // Set up the pref. pref_delegate_->SetPrefs(http_server_properties_dict); EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates()); EXPECT_TRUE(MainThreadHasPendingTask()); FastForwardUntilNoTasksRemain(); // Prefs should have been overwritten, due to the bad data. EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates()); // Verify alternative service is not set. EXPECT_FALSE( HasAlternativeService(url::SchemeHostPort("http", "www.google.com", 80))); } TEST_P(HttpServerPropertiesManagerTest, SupportsSpdy) { // Add mail.google.com:443 as a supporting spdy server. url::SchemeHostPort spdy_server("https", "mail.google.com", 443); EXPECT_FALSE( http_server_props_manager_->SupportsRequestPriority(spdy_server)); http_server_props_manager_->SetSupportsSpdy(spdy_server, true); // Setting the value to the same thing again should not trigger another pref // update. http_server_props_manager_->SetSupportsSpdy(spdy_server, true); // Run the task. EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates()); EXPECT_TRUE(MainThreadHasPendingTask()); FastForwardUntilNoTasksRemain(); EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates()); // Setting the value to the same thing again should not trigger another pref // update. http_server_props_manager_->SetSupportsSpdy(spdy_server, true); EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates()); EXPECT_FALSE(MainThreadHasPendingTask()); EXPECT_TRUE(http_server_props_manager_->SupportsRequestPriority(spdy_server)); } // Regression test for crbug.com/670519. Test that there is only one pref update // scheduled if multiple updates happen in a given time period. Subsequent pref // update could also be scheduled once the previous scheduled update is // completed. TEST_P(HttpServerPropertiesManagerTest, SinglePrefUpdateForTwoSpdyServerCacheChanges) { // Post an update task. SetSupportsSpdy calls ScheduleUpdatePrefs with a delay // of 60ms. url::SchemeHostPort spdy_server("https", "mail.google.com", 443); EXPECT_FALSE( http_server_props_manager_->SupportsRequestPriority(spdy_server)); http_server_props_manager_->SetSupportsSpdy(spdy_server, true); // The pref update task should be scheduled. EXPECT_EQ(1u, GetPendingMainThreadTaskCount()); // Move forward the task runner short by 20ms. FastForwardBy(HttpServerPropertiesManager::GetUpdatePrefsDelayForTesting() - base::TimeDelta::FromMilliseconds(20)); // Set another spdy server to trigger another call to // ScheduleUpdatePrefs. There should be no new update posted. url::SchemeHostPort spdy_server2("https", "drive.google.com", 443); http_server_props_manager_->SetSupportsSpdy(spdy_server2, true); EXPECT_EQ(1u, GetPendingMainThreadTaskCount()); // Move forward the extra 20ms. The pref update should be executed. EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates()); FastForwardBy(base::TimeDelta::FromMilliseconds(20)); EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates()); EXPECT_FALSE(MainThreadHasPendingTask()); EXPECT_TRUE(http_server_props_manager_->SupportsRequestPriority(spdy_server)); EXPECT_TRUE( http_server_props_manager_->SupportsRequestPriority(spdy_server2)); // Set the third spdy server to trigger one more call to // ScheduleUpdatePrefs. A new update task should be posted now since the // previous one is completed. url::SchemeHostPort spdy_server3("https", "maps.google.com", 443); http_server_props_manager_->SetSupportsSpdy(spdy_server3, true); EXPECT_EQ(1u, GetPendingMainThreadTaskCount()); // Run the task. EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates()); FastForwardUntilNoTasksRemain(); EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates()); } TEST_P(HttpServerPropertiesManagerTest, GetAlternativeServiceInfos) { url::SchemeHostPort spdy_server_mail("http", "mail.google.com", 80); EXPECT_FALSE(HasAlternativeService(spdy_server_mail)); const AlternativeService alternative_service(kProtoHTTP2, "mail.google.com", 443); http_server_props_manager_->SetHttp2AlternativeService( spdy_server_mail, alternative_service, one_day_from_now_); // ExpectScheduleUpdatePrefs() should be called only once. http_server_props_manager_->SetHttp2AlternativeService( spdy_server_mail, alternative_service, one_day_from_now_); // Run the task. EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates()); EXPECT_TRUE(MainThreadHasPendingTask()); FastForwardUntilNoTasksRemain(); EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates()); AlternativeServiceInfoVector alternative_service_info_vector = http_server_props_manager_->GetAlternativeServiceInfos(spdy_server_mail); ASSERT_EQ(1u, alternative_service_info_vector.size()); EXPECT_EQ(alternative_service, alternative_service_info_vector[0].alternative_service()); } TEST_P(HttpServerPropertiesManagerTest, SetAlternativeServices) { url::SchemeHostPort spdy_server_mail("http", "mail.google.com", 80); EXPECT_FALSE(HasAlternativeService(spdy_server_mail)); AlternativeServiceInfoVector alternative_service_info_vector; const AlternativeService alternative_service1(kProtoHTTP2, "mail.google.com", 443); alternative_service_info_vector.push_back( AlternativeServiceInfo::CreateHttp2AlternativeServiceInfo( alternative_service1, one_day_from_now_)); const AlternativeService alternative_service2(kProtoQUIC, "mail.google.com", 1234); alternative_service_info_vector.push_back( AlternativeServiceInfo::CreateQuicAlternativeServiceInfo( alternative_service2, one_day_from_now_, advertised_versions_)); http_server_props_manager_->SetAlternativeServices( spdy_server_mail, alternative_service_info_vector); // ExpectScheduleUpdatePrefs() should be called only once. http_server_props_manager_->SetAlternativeServices( spdy_server_mail, alternative_service_info_vector); // Run the task. EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates()); FastForwardUntilNoTasksRemain(); EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates()); AlternativeServiceInfoVector alternative_service_info_vector2 = http_server_props_manager_->GetAlternativeServiceInfos(spdy_server_mail); ASSERT_EQ(2u, alternative_service_info_vector2.size()); EXPECT_EQ(alternative_service1, alternative_service_info_vector2[0].alternative_service()); EXPECT_EQ(alternative_service2, alternative_service_info_vector2[1].alternative_service()); } TEST_P(HttpServerPropertiesManagerTest, SetAlternativeServicesEmpty) { url::SchemeHostPort spdy_server_mail("http", "mail.google.com", 80); EXPECT_FALSE(HasAlternativeService(spdy_server_mail)); const AlternativeService alternative_service(kProtoHTTP2, "mail.google.com", 443); http_server_props_manager_->SetAlternativeServices( spdy_server_mail, AlternativeServiceInfoVector()); EXPECT_FALSE(MainThreadHasPendingTask()); EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates()); EXPECT_FALSE(HasAlternativeService(spdy_server_mail)); } TEST_P(HttpServerPropertiesManagerTest, ConfirmAlternativeService) { url::SchemeHostPort spdy_server_mail; AlternativeService alternative_service; spdy_server_mail = url::SchemeHostPort("http", "mail.google.com", 80); EXPECT_FALSE(HasAlternativeService(spdy_server_mail)); alternative_service = AlternativeService(kProtoHTTP2, "mail.google.com", 443); http_server_props_manager_->SetHttp2AlternativeService( spdy_server_mail, alternative_service, one_day_from_now_); EXPECT_FALSE(http_server_props_manager_->IsAlternativeServiceBroken( alternative_service)); EXPECT_FALSE(http_server_props_manager_->WasAlternativeServiceRecentlyBroken( alternative_service)); EXPECT_EQ(1u, GetPendingMainThreadTaskCount()); http_server_props_manager_->MarkAlternativeServiceBroken(alternative_service); EXPECT_TRUE(http_server_props_manager_->IsAlternativeServiceBroken( alternative_service)); EXPECT_TRUE(http_server_props_manager_->WasAlternativeServiceRecentlyBroken( alternative_service)); // In addition to the pref update task, there's now a task to mark the // alternative service as no longer broken. EXPECT_EQ(2u, GetPendingMainThreadTaskCount()); http_server_props_manager_->ConfirmAlternativeService(alternative_service); EXPECT_FALSE(http_server_props_manager_->IsAlternativeServiceBroken( alternative_service)); EXPECT_FALSE(http_server_props_manager_->WasAlternativeServiceRecentlyBroken( alternative_service)); EXPECT_EQ(2u, GetPendingMainThreadTaskCount()); // Run the task. EXPECT_TRUE(MainThreadHasPendingTask()); FastForwardUntilNoTasksRemain(); EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates()); EXPECT_FALSE(http_server_props_manager_->IsAlternativeServiceBroken( alternative_service)); EXPECT_FALSE(http_server_props_manager_->WasAlternativeServiceRecentlyBroken( alternative_service)); } TEST_P(HttpServerPropertiesManagerTest, SupportsQuic) { IPAddress address; EXPECT_FALSE(http_server_props_manager_->GetSupportsQuic(&address)); IPAddress actual_address(127, 0, 0, 1); http_server_props_manager_->SetSupportsQuic(true, actual_address); // Another task should not be scheduled. http_server_props_manager_->SetSupportsQuic(true, actual_address); // Run the task. EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates()); EXPECT_TRUE(MainThreadHasPendingTask()); FastForwardUntilNoTasksRemain(); EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates()); EXPECT_TRUE(http_server_props_manager_->GetSupportsQuic(&address)); EXPECT_EQ(actual_address, address); // Another task should not be scheduled. http_server_props_manager_->SetSupportsQuic(true, actual_address); EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates()); EXPECT_FALSE(MainThreadHasPendingTask()); } TEST_P(HttpServerPropertiesManagerTest, ServerNetworkStats) { url::SchemeHostPort mail_server("http", "mail.google.com", 80); const ServerNetworkStats* stats = http_server_props_manager_->GetServerNetworkStats(mail_server); EXPECT_EQ(nullptr, stats); ServerNetworkStats stats1; stats1.srtt = base::TimeDelta::FromMicroseconds(10); http_server_props_manager_->SetServerNetworkStats(mail_server, stats1); // Another task should not be scheduled. http_server_props_manager_->SetServerNetworkStats(mail_server, stats1); // Run the task. EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates()); EXPECT_TRUE(MainThreadHasPendingTask()); FastForwardUntilNoTasksRemain(); EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates()); // Another task should not be scheduled. http_server_props_manager_->SetServerNetworkStats(mail_server, stats1); EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates()); EXPECT_FALSE(MainThreadHasPendingTask()); const ServerNetworkStats* stats2 = http_server_props_manager_->GetServerNetworkStats(mail_server); EXPECT_EQ(10, stats2->srtt.ToInternalValue()); http_server_props_manager_->ClearServerNetworkStats(mail_server); // Run the task. EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates()); EXPECT_TRUE(MainThreadHasPendingTask()); FastForwardUntilNoTasksRemain(); EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates()); EXPECT_EQ(nullptr, http_server_props_manager_->GetServerNetworkStats(mail_server)); } TEST_P(HttpServerPropertiesManagerTest, QuicServerInfo) { QuicServerId mail_quic_server_id("mail.google.com", 80); EXPECT_EQ(nullptr, http_server_props_manager_->GetQuicServerInfo(mail_quic_server_id)); std::string quic_server_info1("quic_server_info1"); http_server_props_manager_->SetQuicServerInfo(mail_quic_server_id, quic_server_info1); // Another task should not be scheduled. http_server_props_manager_->SetQuicServerInfo(mail_quic_server_id, quic_server_info1); // Run the task. EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates()); EXPECT_TRUE(MainThreadHasPendingTask()); FastForwardUntilNoTasksRemain(); EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates()); EXPECT_EQ(quic_server_info1, *http_server_props_manager_->GetQuicServerInfo( mail_quic_server_id)); // Another task should not be scheduled. http_server_props_manager_->SetQuicServerInfo(mail_quic_server_id, quic_server_info1); EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates()); EXPECT_FALSE(MainThreadHasPendingTask()); } TEST_P(HttpServerPropertiesManagerTest, Clear) { const url::SchemeHostPort spdy_server("https", "mail.google.com", 443); const IPAddress actual_address(127, 0, 0, 1); const QuicServerId mail_quic_server_id("mail.google.com", 80); const std::string quic_server_info1("quic_server_info1"); const AlternativeService alternative_service(kProtoHTTP2, "mail.google.com", 1234); const AlternativeService broken_alternative_service( kProtoHTTP2, "broken.google.com", 1234); AlternativeServiceInfoVector alt_svc_info_vector; alt_svc_info_vector.push_back( AlternativeServiceInfo::CreateHttp2AlternativeServiceInfo( alternative_service, one_day_from_now_)); alt_svc_info_vector.push_back( AlternativeServiceInfo::CreateHttp2AlternativeServiceInfo( broken_alternative_service, one_day_from_now_)); http_server_props_manager_->SetAlternativeServices(spdy_server, alt_svc_info_vector); http_server_props_manager_->MarkAlternativeServiceBroken( broken_alternative_service); http_server_props_manager_->SetSupportsSpdy(spdy_server, true); http_server_props_manager_->SetSupportsQuic(true, actual_address); ServerNetworkStats stats; stats.srtt = base::TimeDelta::FromMicroseconds(10); http_server_props_manager_->SetServerNetworkStats(spdy_server, stats); http_server_props_manager_->SetQuicServerInfo(mail_quic_server_id, quic_server_info1); // Advance time by just enough so that the prefs update task is executed but // not the task to expire the brokenness of |broken_alternative_service|. FastForwardBy(HttpServerPropertiesManager::GetUpdatePrefsDelayForTesting()); EXPECT_TRUE(MainThreadHasPendingTask()); EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates()); EXPECT_TRUE(http_server_props_manager_->IsAlternativeServiceBroken( broken_alternative_service)); EXPECT_TRUE(http_server_props_manager_->SupportsRequestPriority(spdy_server)); EXPECT_TRUE(HasAlternativeService(spdy_server)); IPAddress address; EXPECT_TRUE(http_server_props_manager_->GetSupportsQuic(&address)); EXPECT_EQ(actual_address, address); const ServerNetworkStats* stats1 = http_server_props_manager_->GetServerNetworkStats(spdy_server); EXPECT_EQ(10, stats1->srtt.ToInternalValue()); EXPECT_EQ(quic_server_info1, *http_server_props_manager_->GetQuicServerInfo( mail_quic_server_id)); // Clear http server data, which should instantly update prefs. EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates()); bool callback_invoked_ = false; http_server_props_manager_->Clear( base::BindOnce([](bool* callback_invoked) { *callback_invoked = true; }, &callback_invoked_)); EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates()); EXPECT_FALSE(callback_invoked_); std::move(pref_delegate_->GetSetPropertiesCallback()).Run(); EXPECT_TRUE(callback_invoked_); EXPECT_FALSE(http_server_props_manager_->IsAlternativeServiceBroken( broken_alternative_service)); EXPECT_FALSE( http_server_props_manager_->SupportsRequestPriority(spdy_server)); EXPECT_FALSE(HasAlternativeService(spdy_server)); EXPECT_FALSE(http_server_props_manager_->GetSupportsQuic(&address)); const ServerNetworkStats* stats2 = http_server_props_manager_->GetServerNetworkStats(spdy_server); EXPECT_EQ(nullptr, stats2); EXPECT_EQ(nullptr, http_server_props_manager_->GetQuicServerInfo(mail_quic_server_id)); } // https://crbug.com/444956: Add 200 alternative_service servers followed by // supports_quic and verify we have read supports_quic from prefs. TEST_P(HttpServerPropertiesManagerTest, BadSupportsQuic) { auto servers_dict = std::make_unique<base::DictionaryValue>(); std::unique_ptr<base::ListValue> servers_list; if (GetParam() >= 4) servers_list = std::make_unique<base::ListValue>(); for (int i = 1; i <= 200; ++i) { // Set up alternative_service for www.google.com:i. auto alternative_service_dict = std::make_unique<base::DictionaryValue>(); alternative_service_dict->SetString("protocol_str", "quic"); alternative_service_dict->SetInteger("port", i); auto alternative_service_list = std::make_unique<base::ListValue>(); alternative_service_list->Append(std::move(alternative_service_dict)); auto server_pref_dict = std::make_unique<base::DictionaryValue>(); server_pref_dict->SetWithoutPathExpansion( "alternative_service", std::move(alternative_service_list)); if (GetParam() >= 5) { servers_dict->SetWithoutPathExpansion( StringPrintf("https://www.google.com:%d", i), std::move(server_pref_dict)); } else { servers_dict->SetWithoutPathExpansion( StringPrintf("www.google.com:%d", i), std::move(server_pref_dict)); } if (GetParam() >= 4) { servers_list->AppendIfNotPresent(std::move(servers_dict)); servers_dict = std::make_unique<base::DictionaryValue>(); } } // Set the server preference for http://mail.google.com server. auto server_pref_dict1 = std::make_unique<base::DictionaryValue>(); if (GetParam() >= 5) { servers_dict->SetWithoutPathExpansion("https://mail.google.com", std::move(server_pref_dict1)); } else { servers_dict->SetWithoutPathExpansion("mail.google.com:80", std::move(server_pref_dict1)); } base::DictionaryValue http_server_properties_dict; if (GetParam() >= 4) { servers_list->AppendIfNotPresent(std::move(servers_dict)); if (GetParam() == 5) { HttpServerPropertiesManager::SetVersion(&http_server_properties_dict, -1); } else { HttpServerPropertiesManager::SetVersion(&http_server_properties_dict, GetParam()); } http_server_properties_dict.SetWithoutPathExpansion( "servers", std::move(servers_list)); } else { HttpServerPropertiesManager::SetVersion(&http_server_properties_dict, GetParam()); http_server_properties_dict.SetWithoutPathExpansion( "servers", std::move(servers_dict)); } // Set up SupportsQuic for 127.0.0.1 auto supports_quic = std::make_unique<base::DictionaryValue>(); supports_quic->SetBoolean("used_quic", true); supports_quic->SetString("address", "127.0.0.1"); http_server_properties_dict.SetWithoutPathExpansion("supports_quic", std::move(supports_quic)); // Set up the pref. pref_delegate_->SetPrefs(http_server_properties_dict); FastForwardUntilNoTasksRemain(); // Verify alternative service. for (int i = 1; i <= 200; ++i) { GURL server_gurl; if (GetParam() >= 5) { server_gurl = GURL(StringPrintf("https://www.google.com:%d", i)); } else { server_gurl = GURL(StringPrintf("https://www.google.com:%d", i)); } url::SchemeHostPort server(server_gurl); AlternativeServiceInfoVector alternative_service_info_vector = http_server_props_manager_->GetAlternativeServiceInfos(server); ASSERT_EQ(1u, alternative_service_info_vector.size()); EXPECT_EQ( kProtoQUIC, alternative_service_info_vector[0].alternative_service().protocol); EXPECT_EQ(i, alternative_service_info_vector[0].alternative_service().port); } // Verify SupportsQuic. IPAddress address; ASSERT_TRUE(http_server_props_manager_->GetSupportsQuic(&address)); EXPECT_EQ("127.0.0.1", address.ToString()); } TEST_P(HttpServerPropertiesManagerTest, UpdatePrefsWithCache) { const url::SchemeHostPort server_www("https", "www.google.com", 80); const url::SchemeHostPort server_mail("https", "mail.google.com", 80); // #1 & #2: Set alternate protocol. AlternativeServiceInfoVector alternative_service_info_vector; AlternativeService www_alternative_service1(kProtoHTTP2, "", 443); base::Time expiration1; ASSERT_TRUE(base::Time::FromUTCString("2036-12-01 10:00:00", &expiration1)); alternative_service_info_vector.push_back( AlternativeServiceInfo::CreateHttp2AlternativeServiceInfo( www_alternative_service1, expiration1)); AlternativeService www_alternative_service2(kProtoHTTP2, "www.google.com", 1234); base::Time expiration2; ASSERT_TRUE(base::Time::FromUTCString("2036-12-31 10:00:00", &expiration2)); alternative_service_info_vector.push_back( AlternativeServiceInfo::CreateHttp2AlternativeServiceInfo( www_alternative_service2, expiration2)); ASSERT_TRUE(http_server_props_manager_->SetAlternativeServices( server_www, alternative_service_info_vector)); AlternativeService mail_alternative_service(kProtoHTTP2, "foo.google.com", 444); base::Time expiration3 = base::Time::Max(); ASSERT_TRUE(http_server_props_manager_->SetHttp2AlternativeService( server_mail, mail_alternative_service, expiration3)); http_server_props_manager_->MarkAlternativeServiceBroken( www_alternative_service2); http_server_props_manager_->MarkAlternativeServiceRecentlyBroken( mail_alternative_service); // #3: Set SPDY server map http_server_props_manager_->SetSupportsSpdy(server_www, false); http_server_props_manager_->SetSupportsSpdy(server_mail, true); http_server_props_manager_->SetSupportsSpdy( url::SchemeHostPort("http", "not_persisted.com", 80), false); // #4: Set ServerNetworkStats. ServerNetworkStats stats; stats.srtt = base::TimeDelta::FromInternalValue(42); http_server_props_manager_->SetServerNetworkStats(server_mail, stats); // #5: Set quic_server_info string. QuicServerId mail_quic_server_id("mail.google.com", 80); std::string quic_server_info1("quic_server_info1"); http_server_props_manager_->SetQuicServerInfo(mail_quic_server_id, quic_server_info1); // #6: Set SupportsQuic. IPAddress actual_address(127, 0, 0, 1); http_server_props_manager_->SetSupportsQuic(true, actual_address); base::Time time_before_prefs_update = base::Time::Now(); // Update Prefs. // The task runner has a remaining pending task to expire // |www_alternative_service2| in 5 minutes. Fast forward enough such // that the prefs update task is executed but not the task to expire // |broken_alternative_service|. EXPECT_EQ(2u, GetPendingMainThreadTaskCount()); EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates()); FastForwardBy(HttpServerPropertiesManager::GetUpdatePrefsDelayForTesting()); EXPECT_EQ(1u, GetPendingMainThreadTaskCount()); EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates()); base::Time time_after_prefs_update = base::Time::Now(); // Verify |pref_delegate_|'s server dict. // In HttpServerPropertiesManager, broken alternative services' expiration // times are converted from TimeTicks to Time before being written to JSON by // using the difference between Time::Now() and TimeTicks::Now(). // To verify these expiration times, |time_before_prefs_update| and // |time_after_prefs_update| provide lower and upper bounds for the // Time::Now() value used by the manager for this conversion. // // A copy of |pref_delegate_|'s server dict will be created, and the broken // alternative service's "broken_until" field is removed and verified // separately. The rest of the server dict copy is verified afterwards. base::Value server_value_copy = pref_delegate_->GetServerProperties()->Clone(); // Extract and remove the "broken_until" string for "www.google.com:1234". base::DictionaryValue* server_dict; ASSERT_TRUE(server_value_copy.GetAsDictionary(&server_dict)); base::ListValue* broken_alt_svc_list; ASSERT_TRUE(server_dict->GetList("broken_alternative_services", &broken_alt_svc_list)); ASSERT_EQ(2u, broken_alt_svc_list->GetSize()); base::DictionaryValue* broken_alt_svcs_list_entry; ASSERT_TRUE( broken_alt_svc_list->GetDictionary(0, &broken_alt_svcs_list_entry)); ASSERT_TRUE(broken_alt_svcs_list_entry->HasKey("broken_until")); std::string expiration_string; ASSERT_TRUE(broken_alt_svcs_list_entry->GetStringWithoutPathExpansion( "broken_until", &expiration_string)); broken_alt_svcs_list_entry->RemoveWithoutPathExpansion("broken_until", nullptr); // Expiration time of "www.google.com:1234" should be 5 minutes minus the // update-prefs-delay from when the prefs were written. int64_t expiration_int64; ASSERT_TRUE(base::StringToInt64(expiration_string, &expiration_int64)); base::TimeDelta expiration_delta = base::TimeDelta::FromMinutes(5) - HttpServerPropertiesManager::GetUpdatePrefsDelayForTesting(); time_t time_t_of_prefs_update = static_cast<time_t>(expiration_int64); EXPECT_LE((time_before_prefs_update + expiration_delta).ToTimeT(), time_t_of_prefs_update); EXPECT_GE((time_after_prefs_update + expiration_delta).ToTimeT(), time_t_of_prefs_update); // Verify all other preferences. const char expected_json[] = "{" "\"broken_alternative_services\":" "[{\"broken_count\":1,\"host\":\"www.google.com\",\"port\":1234," "\"protocol_str\":\"h2\"}," "{\"broken_count\":1,\"host\":\"foo.google.com\",\"port\":444," "\"protocol_str\":\"h2\"}]," "\"quic_servers\":" "{\"https://mail.google.com:80\":" "{\"server_info\":\"quic_server_info1\"}}," "\"servers\":[" "{\"https://www.google.com:80\":{" "\"alternative_service\":[{\"advertised_versions\":[]," "\"expiration\":\"13756212000000000\",\"port\":443," "\"protocol_str\":\"h2\"}," "{\"advertised_versions\":[],\"expiration\":\"13758804000000000\"," "\"host\":\"www.google.com\",\"port\":1234,\"protocol_str\":\"h2\"}]}}," "{\"https://mail.google.com:80\":{" "\"alternative_service\":[{\"advertised_versions\":[]," "\"expiration\":\"9223372036854775807\",\"host\":\"foo.google.com\"," "\"port\":444,\"protocol_str\":\"h2\"}]," "\"network_stats\":{\"srtt\":42}," "\"supports_spdy\":true}}]," "\"supports_quic\":{\"address\":\"127.0.0.1\",\"used_quic\":true}," "\"version\":5}"; std::string preferences_json; EXPECT_TRUE(base::JSONWriter::Write(server_value_copy, &preferences_json)); EXPECT_EQ(expected_json, preferences_json); } TEST_P(HttpServerPropertiesManagerTest, SingleCacheUpdateForMultipleUpdatesScheduled) { EXPECT_EQ(0u, GetPendingMainThreadTaskCount()); // Update cache. http_server_props_manager_->ScheduleUpdateCacheForTesting(); EXPECT_EQ(1u, GetPendingMainThreadTaskCount()); // Move forward the task runner short by 20ms. FastForwardBy(HttpServerPropertiesManager::GetUpdateCacheDelayForTesting() - base::TimeDelta::FromMilliseconds(20)); // Schedule a new cache update within the time window should be a no-op. http_server_props_manager_->ScheduleUpdateCacheForTesting(); EXPECT_EQ(1u, GetPendingMainThreadTaskCount()); // Move forward the task runner the extra 20ms, now the cache update should be // executed. FastForwardBy(base::TimeDelta::FromMilliseconds(20)); // Since this test has no pref corruption, there shouldn't be any pref update. EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates()); EXPECT_FALSE(MainThreadHasPendingTask()); // Schedule one more cache update. The task should be successfully scheduled // on the task runner. http_server_props_manager_->ScheduleUpdateCacheForTesting(); EXPECT_EQ(1u, GetPendingMainThreadTaskCount()); FastForwardUntilNoTasksRemain(); EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates()); } TEST_P(HttpServerPropertiesManagerTest, AddToAlternativeServiceMap) { std::unique_ptr<base::Value> server_value = base::JSONReader::Read( "{\"alternative_service\":[{\"port\":443,\"protocol_str\":\"h2\"}," "{\"port\":123,\"protocol_str\":\"quic\"," "\"expiration\":\"9223372036854775807\"},{\"host\":\"example.org\"," "\"port\":1234,\"protocol_str\":\"h2\"," "\"expiration\":\"13758804000000000\"}]}"); ASSERT_TRUE(server_value); base::DictionaryValue* server_dict; ASSERT_TRUE(server_value->GetAsDictionary(&server_dict)); const url::SchemeHostPort server("https", "example.com", 443); AlternativeServiceMap alternative_service_map; EXPECT_TRUE(http_server_props_manager_->AddToAlternativeServiceMap( server, *server_dict, &alternative_service_map)); AlternativeServiceMap::iterator it = alternative_service_map.Get(server); ASSERT_NE(alternative_service_map.end(), it); AlternativeServiceInfoVector alternative_service_info_vector = it->second; ASSERT_EQ(3u, alternative_service_info_vector.size()); EXPECT_EQ(kProtoHTTP2, alternative_service_info_vector[0].alternative_service().protocol); EXPECT_EQ("", alternative_service_info_vector[0].alternative_service().host); EXPECT_EQ(443, alternative_service_info_vector[0].alternative_service().port); // Expiration defaults to one day from now, testing with tolerance. const base::Time now = base::Time::Now(); const base::Time expiration = alternative_service_info_vector[0].expiration(); EXPECT_LE(now + base::TimeDelta::FromHours(23), expiration); EXPECT_GE(now + base::TimeDelta::FromDays(1), expiration); EXPECT_EQ(kProtoQUIC, alternative_service_info_vector[1].alternative_service().protocol); EXPECT_EQ("", alternative_service_info_vector[1].alternative_service().host); EXPECT_EQ(123, alternative_service_info_vector[1].alternative_service().port); // numeric_limits<int64_t>::max() represents base::Time::Max(). EXPECT_EQ(base::Time::Max(), alternative_service_info_vector[1].expiration()); EXPECT_EQ(kProtoHTTP2, alternative_service_info_vector[2].alternative_service().protocol); EXPECT_EQ("example.org", alternative_service_info_vector[2].alternative_service().host); EXPECT_EQ(1234, alternative_service_info_vector[2].alternative_service().port); base::Time expected_expiration; ASSERT_TRUE( base::Time::FromUTCString("2036-12-31 10:00:00", &expected_expiration)); EXPECT_EQ(expected_expiration, alternative_service_info_vector[2].expiration()); } // Regression test for https://crbug.com/615497. TEST_P(HttpServerPropertiesManagerTest, DoNotLoadAltSvcForInsecureOrigins) { std::unique_ptr<base::Value> server_value = base::JSONReader::Read( "{\"alternative_service\":[{\"port\":443,\"protocol_str\":\"h2\"," "\"expiration\":\"9223372036854775807\"}]}"); ASSERT_TRUE(server_value); base::DictionaryValue* server_dict; ASSERT_TRUE(server_value->GetAsDictionary(&server_dict)); const url::SchemeHostPort server("http", "example.com", 80); AlternativeServiceMap alternative_service_map; EXPECT_FALSE(http_server_props_manager_->AddToAlternativeServiceMap( server, *server_dict, &alternative_service_map)); AlternativeServiceMap::iterator it = alternative_service_map.Get(server); EXPECT_EQ(alternative_service_map.end(), it); } // Do not persist expired alternative service entries to disk. TEST_P(HttpServerPropertiesManagerTest, DoNotPersistExpiredAlternativeService) { AlternativeServiceInfoVector alternative_service_info_vector; const AlternativeService broken_alternative_service( kProtoHTTP2, "broken.example.com", 443); const base::Time time_one_day_later = base::Time::Now() + base::TimeDelta::FromDays(1); alternative_service_info_vector.push_back( AlternativeServiceInfo::CreateHttp2AlternativeServiceInfo( broken_alternative_service, time_one_day_later)); // #1: MarkAlternativeServiceBroken(). http_server_props_manager_->MarkAlternativeServiceBroken( broken_alternative_service); const AlternativeService expired_alternative_service( kProtoHTTP2, "expired.example.com", 443); const base::Time time_one_day_ago = base::Time::Now() - base::TimeDelta::FromDays(1); alternative_service_info_vector.push_back( AlternativeServiceInfo::CreateHttp2AlternativeServiceInfo( expired_alternative_service, time_one_day_ago)); const AlternativeService valid_alternative_service(kProtoHTTP2, "valid.example.com", 443); alternative_service_info_vector.push_back( AlternativeServiceInfo::CreateHttp2AlternativeServiceInfo( valid_alternative_service, time_one_day_later)); const url::SchemeHostPort server("https", "www.example.com", 443); // #2: SetAlternativeServices(). ASSERT_TRUE(http_server_props_manager_->SetAlternativeServices( server, alternative_service_info_vector)); // |net_test_task_runner_| has a remaining pending task to expire // |broken_alternative_service| at |time_one_day_later|. Fast forward enough // such that the prefs update task is executed but not the task to expire // |broken_alternative_service|. EXPECT_EQ(2U, GetPendingMainThreadTaskCount()); EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates()); FastForwardBy(HttpServerPropertiesManager::GetUpdatePrefsDelayForTesting()); EXPECT_EQ(1U, GetPendingMainThreadTaskCount()); EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates()); const base::DictionaryValue* pref_dict = pref_delegate_->GetServerProperties(); const base::ListValue* servers_list = nullptr; ASSERT_TRUE(pref_dict->GetListWithoutPathExpansion("servers", &servers_list)); base::ListValue::const_iterator it = servers_list->begin(); const base::DictionaryValue* server_pref_dict; ASSERT_TRUE(it->GetAsDictionary(&server_pref_dict)); const base::DictionaryValue* example_pref_dict; ASSERT_TRUE(server_pref_dict->GetDictionaryWithoutPathExpansion( "https://www.example.com", &example_pref_dict)); const base::ListValue* altsvc_list; ASSERT_TRUE(example_pref_dict->GetList("alternative_service", &altsvc_list)); ASSERT_EQ(2u, altsvc_list->GetSize()); const base::DictionaryValue* altsvc_entry; std::string hostname; ASSERT_TRUE(altsvc_list->GetDictionary(0, &altsvc_entry)); ASSERT_TRUE(altsvc_entry->GetString("host", &hostname)); EXPECT_EQ("broken.example.com", hostname); ASSERT_TRUE(altsvc_list->GetDictionary(1, &altsvc_entry)); ASSERT_TRUE(altsvc_entry->GetString("host", &hostname)); EXPECT_EQ("valid.example.com", hostname); } // Test that expired alternative service entries on disk are ignored. TEST_P(HttpServerPropertiesManagerTest, DoNotLoadExpiredAlternativeService) { auto alternative_service_list = std::make_unique<base::ListValue>(); auto expired_dict = std::make_unique<base::DictionaryValue>(); expired_dict->SetString("protocol_str", "h2"); expired_dict->SetString("host", "expired.example.com"); expired_dict->SetInteger("port", 443); base::Time time_one_day_ago = base::Time::Now() - base::TimeDelta::FromDays(1); expired_dict->SetString( "expiration", base::Int64ToString(time_one_day_ago.ToInternalValue())); alternative_service_list->Append(std::move(expired_dict)); auto valid_dict = std::make_unique<base::DictionaryValue>(); valid_dict->SetString("protocol_str", "h2"); valid_dict->SetString("host", "valid.example.com"); valid_dict->SetInteger("port", 443); valid_dict->SetString( "expiration", base::Int64ToString(one_day_from_now_.ToInternalValue())); alternative_service_list->Append(std::move(valid_dict)); base::DictionaryValue server_pref_dict; server_pref_dict.SetWithoutPathExpansion("alternative_service", std::move(alternative_service_list)); const url::SchemeHostPort server("https", "example.com", 443); AlternativeServiceMap alternative_service_map; ASSERT_TRUE(http_server_props_manager_->AddToAlternativeServiceMap( server, server_pref_dict, &alternative_service_map)); AlternativeServiceMap::iterator it = alternative_service_map.Get(server); ASSERT_NE(alternative_service_map.end(), it); AlternativeServiceInfoVector alternative_service_info_vector = it->second; ASSERT_EQ(1u, alternative_service_info_vector.size()); EXPECT_EQ(kProtoHTTP2, alternative_service_info_vector[0].alternative_service().protocol); EXPECT_EQ("valid.example.com", alternative_service_info_vector[0].alternative_service().host); EXPECT_EQ(443, alternative_service_info_vector[0].alternative_service().port); EXPECT_EQ(one_day_from_now_, alternative_service_info_vector[0].expiration()); } // Make sure prefs are updated on destruction. TEST_P(HttpServerPropertiesManagerTest, UpdatePrefsOnShutdown) { int pref_updates = 0; pref_delegate_->set_extra_update_prefs_callback( base::Bind([](int* updates) { (*updates)++; }, &pref_updates)); http_server_props_manager_.reset(); EXPECT_EQ(1, pref_updates); } TEST_P(HttpServerPropertiesManagerTest, PersistAdvertisedVersionsToPref) { const url::SchemeHostPort server_www("https", "www.google.com", 80); const url::SchemeHostPort server_mail("https", "mail.google.com", 80); // #1 & #2: Set alternate protocol. AlternativeServiceInfoVector alternative_service_info_vector; // Quic alternative service set with two advertised QUIC versions. AlternativeService quic_alternative_service1(kProtoQUIC, "", 443); base::Time expiration1; ASSERT_TRUE(base::Time::FromUTCString("2036-12-01 10:00:00", &expiration1)); QuicTransportVersionVector advertised_versions = {QUIC_VERSION_37, QUIC_VERSION_35}; alternative_service_info_vector.push_back( AlternativeServiceInfo::CreateQuicAlternativeServiceInfo( quic_alternative_service1, expiration1, advertised_versions)); // HTTP/2 alternative service should not set any advertised version. AlternativeService h2_alternative_service(kProtoHTTP2, "www.google.com", 1234); base::Time expiration2; ASSERT_TRUE(base::Time::FromUTCString("2036-12-31 10:00:00", &expiration2)); alternative_service_info_vector.push_back( AlternativeServiceInfo::CreateHttp2AlternativeServiceInfo( h2_alternative_service, expiration2)); ASSERT_TRUE(http_server_props_manager_->SetAlternativeServices( server_www, alternative_service_info_vector)); // Set another QUIC alternative service with a single advertised QUIC version. AlternativeService mail_alternative_service(kProtoQUIC, "foo.google.com", 444); base::Time expiration3 = base::Time::Max(); ASSERT_TRUE(http_server_props_manager_->SetQuicAlternativeService( server_mail, mail_alternative_service, expiration3, advertised_versions_)); // #3: Set ServerNetworkStats. ServerNetworkStats stats; stats.srtt = base::TimeDelta::FromInternalValue(42); http_server_props_manager_->SetServerNetworkStats(server_mail, stats); // #4: Set quic_server_info string. QuicServerId mail_quic_server_id("mail.google.com", 80); std::string quic_server_info1("quic_server_info1"); http_server_props_manager_->SetQuicServerInfo(mail_quic_server_id, quic_server_info1); // #5: Set SupportsQuic. IPAddress actual_address(127, 0, 0, 1); http_server_props_manager_->SetSupportsQuic(true, actual_address); // Update Prefs. EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates()); EXPECT_TRUE(MainThreadHasPendingTask()); FastForwardUntilNoTasksRemain(); EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates()); // Verify preferences with correct advertised version field. const char expected_json[] = "{\"quic_servers\":{\"https://mail.google.com:80\":{" "\"server_info\":\"quic_server_info1\"}},\"servers\":[" "{\"https://www.google.com:80\":{\"alternative_service\":[{" "\"advertised_versions\":[35,37],\"expiration\":\"13756212000000000\"," "\"port\":443,\"protocol_str\":\"quic\"},{\"advertised_versions\":[]," "\"expiration\":\"13758804000000000\",\"host\":\"www.google.com\"," "\"port\":1234,\"protocol_str\":\"h2\"}]}}," "{\"https://mail.google.com:80\":{\"alternative_service\":[{" "\"advertised_versions\":[43],\"expiration\":\"9223372036854775807\"," "\"host\":\"foo.google.com\",\"port\":444,\"protocol_str\":\"quic\"}]," "\"network_stats\":{\"srtt\":42}}}],\"supports_quic\":{" "\"address\":\"127.0.0.1\",\"used_quic\":true},\"version\":5}"; const base::Value* http_server_properties = pref_delegate_->GetServerProperties(); std::string preferences_json; EXPECT_TRUE( base::JSONWriter::Write(*http_server_properties, &preferences_json)); EXPECT_EQ(expected_json, preferences_json); } TEST_P(HttpServerPropertiesManagerTest, ReadAdvertisedVersionsFromPref) { std::unique_ptr<base::Value> server_value = base::JSONReader::Read( "{\"alternative_service\":[" "{\"port\":443,\"protocol_str\":\"quic\"}," "{\"port\":123,\"protocol_str\":\"quic\"," "\"expiration\":\"9223372036854775807\"," "\"advertised_versions\":[37,35]}]}"); ASSERT_TRUE(server_value); base::DictionaryValue* server_dict; ASSERT_TRUE(server_value->GetAsDictionary(&server_dict)); const url::SchemeHostPort server("https", "example.com", 443); AlternativeServiceMap alternative_service_map; EXPECT_TRUE(http_server_props_manager_->AddToAlternativeServiceMap( server, *server_dict, &alternative_service_map)); AlternativeServiceMap::iterator it = alternative_service_map.Get(server); ASSERT_NE(alternative_service_map.end(), it); AlternativeServiceInfoVector alternative_service_info_vector = it->second; ASSERT_EQ(2u, alternative_service_info_vector.size()); // Verify the first alternative service with no advertised version listed. EXPECT_EQ(kProtoQUIC, alternative_service_info_vector[0].alternative_service().protocol); EXPECT_EQ("", alternative_service_info_vector[0].alternative_service().host); EXPECT_EQ(443, alternative_service_info_vector[0].alternative_service().port); // Expiration defaults to one day from now, testing with tolerance. const base::Time now = base::Time::Now(); const base::Time expiration = alternative_service_info_vector[0].expiration(); EXPECT_LE(now + base::TimeDelta::FromHours(23), expiration); EXPECT_GE(now + base::TimeDelta::FromDays(1), expiration); EXPECT_TRUE(alternative_service_info_vector[0].advertised_versions().empty()); // Verify the second alterntaive service with two advertised versions. EXPECT_EQ(kProtoQUIC, alternative_service_info_vector[1].alternative_service().protocol); EXPECT_EQ("", alternative_service_info_vector[1].alternative_service().host); EXPECT_EQ(123, alternative_service_info_vector[1].alternative_service().port); EXPECT_EQ(base::Time::Max(), alternative_service_info_vector[1].expiration()); // Verify advertised versions. const QuicTransportVersionVector loaded_advertised_versions = alternative_service_info_vector[1].advertised_versions(); EXPECT_EQ(2u, loaded_advertised_versions.size()); EXPECT_EQ(QUIC_VERSION_35, loaded_advertised_versions[0]); EXPECT_EQ(QUIC_VERSION_37, loaded_advertised_versions[1]); } TEST_P(HttpServerPropertiesManagerTest, UpdatePrefWhenAdvertisedVersionsChange) { const url::SchemeHostPort server_www("https", "www.google.com", 80); // #1: Set alternate protocol. AlternativeServiceInfoVector alternative_service_info_vector; // Quic alternative service set with a single QUIC version: QUIC_VERSION_37. AlternativeService quic_alternative_service1(kProtoQUIC, "", 443); base::Time expiration1; ASSERT_TRUE(base::Time::FromUTCString("2036-12-01 10:00:00", &expiration1)); alternative_service_info_vector.push_back( AlternativeServiceInfo::CreateQuicAlternativeServiceInfo( quic_alternative_service1, expiration1, advertised_versions_)); ASSERT_TRUE(http_server_props_manager_->SetAlternativeServices( server_www, alternative_service_info_vector)); // Set quic_server_info string. QuicServerId mail_quic_server_id("mail.google.com", 80); std::string quic_server_info1("quic_server_info1"); http_server_props_manager_->SetQuicServerInfo(mail_quic_server_id, quic_server_info1); // Set SupportsQuic. IPAddress actual_address(127, 0, 0, 1); http_server_props_manager_->SetSupportsQuic(true, actual_address); // Update Prefs. EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates()); EXPECT_TRUE(MainThreadHasPendingTask()); FastForwardUntilNoTasksRemain(); EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates()); // Verify preferences with correct advertised version field. const char expected_json[] = "{\"quic_servers\":{\"https://mail.google.com:80\":" "{\"server_info\":\"quic_server_info1\"}},\"servers\":[" "{\"https://www.google.com:80\":" "{\"alternative_service\":[{\"advertised_versions\":[43]," "\"expiration\":\"13756212000000000\",\"port\":443," "\"protocol_str\":\"quic\"}]}}],\"supports_quic\":" "{\"address\":\"127.0.0.1\",\"used_quic\":true},\"version\":5}"; const base::Value* http_server_properties = pref_delegate_->GetServerProperties(); std::string preferences_json; EXPECT_TRUE( base::JSONWriter::Write(*http_server_properties, &preferences_json)); EXPECT_EQ(expected_json, preferences_json); // #2: Set AlternativeService with different advertised_versions for the same // AlternativeService. AlternativeServiceInfoVector alternative_service_info_vector_2; // Quic alternative service set with two advertised QUIC versions. QuicTransportVersionVector advertised_versions = {QUIC_VERSION_37, QUIC_VERSION_35}; alternative_service_info_vector_2.push_back( AlternativeServiceInfo::CreateQuicAlternativeServiceInfo( quic_alternative_service1, expiration1, advertised_versions)); ASSERT_TRUE(http_server_props_manager_->SetAlternativeServices( server_www, alternative_service_info_vector_2)); // Update Prefs. EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates()); EXPECT_TRUE(MainThreadHasPendingTask()); FastForwardUntilNoTasksRemain(); EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates()); // Verify preferences updated with new advertised versions. const char expected_json_updated[] = "{\"quic_servers\":{\"https://mail.google.com:80\":" "{\"server_info\":\"quic_server_info1\"}},\"servers\":[" "{\"https://www.google.com:80\":" "{\"alternative_service\":[{\"advertised_versions\":[35,37]," "\"expiration\":\"13756212000000000\",\"port\":443," "\"protocol_str\":\"quic\"}]}}],\"supports_quic\":" "{\"address\":\"127.0.0.1\",\"used_quic\":true},\"version\":5}"; EXPECT_TRUE( base::JSONWriter::Write(*http_server_properties, &preferences_json)); EXPECT_EQ(expected_json_updated, preferences_json); // #3: Set AlternativeService with same advertised_versions. AlternativeServiceInfoVector alternative_service_info_vector_3; // A same set of QUIC versions but listed in a different order. QuicTransportVersionVector advertised_versions_2 = {QUIC_VERSION_35, QUIC_VERSION_37}; alternative_service_info_vector_3.push_back( AlternativeServiceInfo::CreateQuicAlternativeServiceInfo( quic_alternative_service1, expiration1, advertised_versions_2)); ASSERT_FALSE(http_server_props_manager_->SetAlternativeServices( server_www, alternative_service_info_vector_3)); // No Prefs update. EXPECT_FALSE(MainThreadHasPendingTask()); EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates()); } TEST_P(HttpServerPropertiesManagerTest, UpdateCacheWithPrefs) { AlternativeService cached_broken_service(kProtoQUIC, "cached_broken", 443); AlternativeService cached_broken_service2(kProtoQUIC, "cached_broken2", 443); AlternativeService cached_recently_broken_service(kProtoQUIC, "cached_rbroken", 443); http_server_props_manager_->MarkAlternativeServiceBroken( cached_broken_service); http_server_props_manager_->MarkAlternativeServiceBroken( cached_broken_service2); http_server_props_manager_->MarkAlternativeServiceRecentlyBroken( cached_recently_broken_service); EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates()); EXPECT_TRUE(MainThreadHasPendingTask()); // Run the prefs update task but not the expiration task for // |cached_broken_service|. FastForwardBy(HttpServerPropertiesManager::GetUpdatePrefsDelayForTesting()); EXPECT_TRUE(MainThreadHasPendingTask()); EXPECT_EQ(1, pref_delegate_->GetAndClearNumPrefUpdates()); // Load the |pref_delegate_| with some JSON to verify updating the cache from // prefs. For the broken alternative services "www.google.com:1234" and // "cached_broken", the expiration time will be one day from now. std::string expiration_str = base::Int64ToString(static_cast<int64_t>(one_day_from_now_.ToTimeT())); std::unique_ptr<base::Value> server_value = base::JSONReader::Read( "{" "\"broken_alternative_services\":[" "{\"broken_until\":\"" + expiration_str + "\"," "\"host\":\"www.google.com\",\"port\":1234,\"protocol_str\":\"h2\"}," "{\"broken_count\":2,\"broken_until\":\"" + expiration_str + "\"," "\"host\":\"cached_broken\",\"port\":443,\"protocol_str\":\"quic\"}," "{\"broken_count\":3," "\"host\":\"cached_rbroken\",\"port\":443,\"protocol_str\":\"quic\"}]," "\"quic_servers\":{" "\"https://mail.google.com:80\":{" "\"server_info\":\"quic_server_info1\"}" "}," "\"servers\":[" "{\"https://www.google.com:80\":{" "\"alternative_service\":[" "{\"expiration\":\"13756212000000000\",\"port\":443," "\"protocol_str\":\"h2\"}," "{\"expiration\":\"13758804000000000\",\"host\":\"www.google.com\"," "\"port\":1234,\"protocol_str\":\"h2\"}" "]" "}}," "{\"https://mail.google.com:80\":{" "\"alternative_service\":[" "{\"expiration\":\"9223372036854775807\",\"host\":\"foo.google.com\"," "\"port\":444,\"protocol_str\":\"h2\"}" "]," "\"network_stats\":{\"srtt\":42}" "}}" "]," "\"supports_quic\":" "{\"address\":\"127.0.0.1\",\"used_quic\":true}," "\"version\":5" "}"); ASSERT_TRUE(server_value); base::DictionaryValue* server_dict; ASSERT_TRUE(server_value->GetAsDictionary(&server_dict)); pref_delegate_->SetPrefs(*server_dict); EXPECT_TRUE(MainThreadHasPendingTask()); // Run the cache update task but not the expiration task for // |cached_broken_service|. FastForwardBy(NextMainThreadPendingTaskDelay()); EXPECT_TRUE(MainThreadHasPendingTask()); // // Verify alternative service info for https://www.google.com // AlternativeServiceInfoVector alternative_service_info_vector = http_server_props_manager_->GetAlternativeServiceInfos( url::SchemeHostPort("https", "www.google.com", 80)); ASSERT_EQ(2u, alternative_service_info_vector.size()); EXPECT_EQ(kProtoHTTP2, alternative_service_info_vector[0].alternative_service().protocol); EXPECT_EQ("www.google.com", alternative_service_info_vector[0].alternative_service().host); EXPECT_EQ(443, alternative_service_info_vector[0].alternative_service().port); EXPECT_EQ( "13756212000000000", base::Int64ToString( alternative_service_info_vector[0].expiration().ToInternalValue())); EXPECT_EQ(kProtoHTTP2, alternative_service_info_vector[1].alternative_service().protocol); EXPECT_EQ("www.google.com", alternative_service_info_vector[1].alternative_service().host); EXPECT_EQ(1234, alternative_service_info_vector[1].alternative_service().port); EXPECT_EQ( "13758804000000000", base::Int64ToString( alternative_service_info_vector[1].expiration().ToInternalValue())); // // Verify alternative service info for https://mail.google.com // alternative_service_info_vector = http_server_props_manager_->GetAlternativeServiceInfos( url::SchemeHostPort("https", "mail.google.com", 80)); ASSERT_EQ(1u, alternative_service_info_vector.size()); EXPECT_EQ(kProtoHTTP2, alternative_service_info_vector[0].alternative_service().protocol); EXPECT_EQ("foo.google.com", alternative_service_info_vector[0].alternative_service().host); EXPECT_EQ(444, alternative_service_info_vector[0].alternative_service().port); EXPECT_EQ( "9223372036854775807", base::Int64ToString( alternative_service_info_vector[0].expiration().ToInternalValue())); // // Verify broken alternative services. // AlternativeService prefs_broken_service(kProtoHTTP2, "www.google.com", 1234); EXPECT_TRUE(http_server_props_manager_->IsAlternativeServiceBroken( cached_broken_service)); EXPECT_TRUE(http_server_props_manager_->IsAlternativeServiceBroken( cached_broken_service2)); EXPECT_TRUE(http_server_props_manager_->IsAlternativeServiceBroken( prefs_broken_service)); // Verify brokenness expiration times. // |cached_broken_service|'s expiration time should've been overwritten by the // prefs to be approximately 1 day from now. |cached_broken_service2|'s // expiration time should still be 5 minutes due to being marked broken. // |prefs_broken_service|'s expiration time should be approximately 1 day from // now which comes from the prefs. FastForwardBy(base::TimeDelta::FromMinutes(4)); EXPECT_TRUE(http_server_props_manager_->IsAlternativeServiceBroken( cached_broken_service)); EXPECT_FALSE(http_server_props_manager_->IsAlternativeServiceBroken( cached_broken_service2)); EXPECT_TRUE(http_server_props_manager_->IsAlternativeServiceBroken( prefs_broken_service)); FastForwardBy(base::TimeDelta::FromDays(1)); EXPECT_FALSE(http_server_props_manager_->IsAlternativeServiceBroken( cached_broken_service)); EXPECT_FALSE(http_server_props_manager_->IsAlternativeServiceBroken( cached_broken_service2)); EXPECT_FALSE(http_server_props_manager_->IsAlternativeServiceBroken( prefs_broken_service)); // Now that |prefs_broken_service|'s brokenness has expired, it should've // been removed from the alternative services info vectors of all servers. alternative_service_info_vector = http_server_props_manager_->GetAlternativeServiceInfos( url::SchemeHostPort("https", "www.google.com", 80)); ASSERT_EQ(1u, alternative_service_info_vector.size()); // // Verify recently broken alternative services. // // If an entry is already in cache, the broken count in the prefs should // overwrite the one in the cache. // |prefs_broken_service| should have broken-count 1 from prefs. // |cached_recently_broken_service| should have broken-count 3 from prefs. // |cached_broken_service| should have broken-count 2 from prefs. // |cached_broken_service2| should have broken-count 1 from being marked // broken. EXPECT_TRUE(http_server_props_manager_->WasAlternativeServiceRecentlyBroken( prefs_broken_service)); EXPECT_TRUE(http_server_props_manager_->WasAlternativeServiceRecentlyBroken( cached_recently_broken_service)); EXPECT_TRUE(http_server_props_manager_->WasAlternativeServiceRecentlyBroken( cached_broken_service)); EXPECT_TRUE(http_server_props_manager_->WasAlternativeServiceRecentlyBroken( cached_broken_service2)); // Make sure |prefs_broken_service| has the right expiration delay when marked // broken. Since |prefs_broken_service| had no broken_count specified in the // prefs, a broken_count value of 1 should have been assumed by // |http_server_props_manager_|. http_server_props_manager_->MarkAlternativeServiceBroken( prefs_broken_service); EXPECT_EQ(0, pref_delegate_->GetAndClearNumPrefUpdates()); EXPECT_TRUE(MainThreadHasPendingTask()); FastForwardBy(base::TimeDelta::FromMinutes(10) - base::TimeDelta::FromInternalValue(1)); EXPECT_TRUE(http_server_props_manager_->IsAlternativeServiceBroken( prefs_broken_service)); FastForwardBy(base::TimeDelta::FromInternalValue(1)); EXPECT_FALSE(http_server_props_manager_->IsAlternativeServiceBroken( prefs_broken_service)); // Make sure |cached_recently_broken_service| has the right expiration delay // when marked broken. http_server_props_manager_->MarkAlternativeServiceBroken( cached_recently_broken_service); EXPECT_TRUE(MainThreadHasPendingTask()); FastForwardBy(base::TimeDelta::FromMinutes(40) - base::TimeDelta::FromInternalValue(1)); EXPECT_TRUE(http_server_props_manager_->IsAlternativeServiceBroken( cached_recently_broken_service)); FastForwardBy(base::TimeDelta::FromInternalValue(1)); EXPECT_FALSE(http_server_props_manager_->IsAlternativeServiceBroken( cached_recently_broken_service)); // Make sure |cached_broken_service| has the right expiration delay when // marked broken. http_server_props_manager_->MarkAlternativeServiceBroken( cached_broken_service); EXPECT_TRUE(MainThreadHasPendingTask()); FastForwardBy(base::TimeDelta::FromMinutes(20) - base::TimeDelta::FromInternalValue(1)); EXPECT_TRUE(http_server_props_manager_->IsAlternativeServiceBroken( cached_broken_service)); FastForwardBy(base::TimeDelta::FromInternalValue(1)); EXPECT_FALSE(http_server_props_manager_->IsAlternativeServiceBroken( cached_broken_service)); // Make sure |cached_broken_service2| has the right expiration delay when // marked broken. http_server_props_manager_->MarkAlternativeServiceBroken( cached_broken_service2); EXPECT_TRUE(MainThreadHasPendingTask()); FastForwardBy(base::TimeDelta::FromMinutes(10) - base::TimeDelta::FromInternalValue(1)); EXPECT_TRUE(http_server_props_manager_->IsAlternativeServiceBroken( cached_broken_service2)); FastForwardBy(base::TimeDelta::FromInternalValue(1)); EXPECT_FALSE(http_server_props_manager_->IsAlternativeServiceBroken( cached_broken_service2)); // // Verify ServerNetworkStats. // const ServerNetworkStats* server_network_stats = http_server_props_manager_->GetServerNetworkStats( url::SchemeHostPort("https", "mail.google.com", 80)); EXPECT_TRUE(server_network_stats); EXPECT_EQ(server_network_stats->srtt, base::TimeDelta::FromInternalValue(42)); // // Verify QUIC server info. // const std::string* quic_server_info = http_server_props_manager_->GetQuicServerInfo( QuicServerId("mail.google.com", 80)); EXPECT_EQ("quic_server_info1", *quic_server_info); // // Verify supports QUIC. // IPAddress actual_address(127, 0, 0, 1); EXPECT_TRUE(http_server_props_manager_->GetSupportsQuic(&actual_address)); EXPECT_EQ(4, pref_delegate_->GetAndClearNumPrefUpdates()); } } // namespace net
29,959
2,496
/** * Copyright (c) 2006-2016 LOVE Development Team * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. **/ #include "Effect.h" #include "common/Exception.h" #include <cmath> #include <iostream> namespace love { namespace audio { namespace openal { //base class Effect::Effect() { generateEffect(); } Effect::Effect(const Effect &s) : Effect() { setParams(s.getParams()); } Effect::~Effect() { deleteEffect(); } Effect *Effect::clone() { return new Effect(*this); } bool Effect::generateEffect() { #ifdef ALC_EXT_EFX if (!alGenEffects) return false; if (effect != AL_EFFECT_NULL) return true; alGenEffects(1, &effect); if (alGetError() != AL_NO_ERROR) throw love::Exception("Failed to create sound Effect."); return true; #else return false; #endif } void Effect::deleteEffect() { #ifdef ALC_EXT_EFX if (effect != AL_EFFECT_NULL) alDeleteEffects(1, &effect); #endif effect = AL_EFFECT_NULL; } ALuint Effect::getEffect() const { return effect; } bool Effect::setParams(const std::map<Parameter, float> &params) { this->params = params; type = (Type)(int) this->params[EFFECT_TYPE]; if (!generateEffect()) return false; #ifdef ALC_EXT_EFX //parameter table without EFFECT_TYPE entry is illegal switch (type) { case TYPE_REVERB: alEffecti(effect, AL_EFFECT_TYPE, AL_EFFECT_REVERB); break; case TYPE_CHORUS: alEffecti(effect, AL_EFFECT_TYPE, AL_EFFECT_CHORUS); break; case TYPE_DISTORTION: alEffecti(effect, AL_EFFECT_TYPE, AL_EFFECT_DISTORTION); break; case TYPE_ECHO: alEffecti(effect, AL_EFFECT_TYPE, AL_EFFECT_ECHO); break; case TYPE_FLANGER: alEffecti(effect, AL_EFFECT_TYPE, AL_EFFECT_FLANGER); break; /* case TYPE_FREQSHIFTER: alEffecti(effect, AL_EFFECT_TYPE, AL_EFFECT_FREQUENCY_SHIFTER); break; case TYPE_MORPHER: alEffecti(effect, AL_EFFECT_TYPE, AL_EFFECT_VOCAL_MORPHER); break; case TYPE_PITCHSHIFTER: alEffecti(effect, AL_EFFECT_TYPE, AL_EFFECT_PITCH_SHIFTER); break; */ case TYPE_MODULATOR: alEffecti(effect, AL_EFFECT_TYPE, AL_EFFECT_RING_MODULATOR); break; /* case TYPE_AUTOWAH: alEffecti(effect, AL_EFFECT_TYPE, AL_EFFECT_AUTOWAH); break; */ case TYPE_COMPRESSOR: alEffecti(effect, AL_EFFECT_TYPE, AL_EFFECT_COMPRESSOR); break; case TYPE_EQUALIZER: alEffecti(effect, AL_EFFECT_TYPE, AL_EFFECT_EQUALIZER); break; case TYPE_BASIC: case TYPE_MAX_ENUM: break; } //failed to make effect specific type - not supported etc. if (alGetError() != AL_NO_ERROR) { deleteEffect(); return false; } #define clampf(v,l,h) fmax(fmin((v),(h)),(l)) #define PARAMSTR(i,e,v) effect,AL_##e##_##v,clampf(getValue(i,AL_##e##_DEFAULT_##v),AL_##e##_MIN_##v,AL_##e##_MAX_##v) switch (type) { case TYPE_REVERB: { alEffectf(PARAMSTR(REVERB_GAIN,REVERB,GAIN)); alEffectf(PARAMSTR(REVERB_HFGAIN,REVERB,GAINHF)); alEffectf(PARAMSTR(REVERB_DENSITY,REVERB,DENSITY)); alEffectf(PARAMSTR(REVERB_DIFFUSION,REVERB,DIFFUSION)); alEffectf(PARAMSTR(REVERB_DECAY,REVERB,DECAY_TIME)); alEffectf(PARAMSTR(REVERB_HFDECAY,REVERB,DECAY_HFRATIO)); alEffectf(PARAMSTR(REVERB_EARLYGAIN,REVERB,REFLECTIONS_GAIN)); alEffectf(PARAMSTR(REVERB_EARLYDELAY,REVERB,REFLECTIONS_DELAY)); alEffectf(PARAMSTR(REVERB_LATEGAIN,REVERB,LATE_REVERB_GAIN)); alEffectf(PARAMSTR(REVERB_LATEDELAY,REVERB,LATE_REVERB_DELAY));; alEffectf(PARAMSTR(REVERB_ROLLOFF,REVERB,ROOM_ROLLOFF_FACTOR)); alEffectf(PARAMSTR(REVERB_AIRHFGAIN,REVERB,AIR_ABSORPTION_GAINHF)); alEffecti(effect, AL_REVERB_DECAY_HFLIMIT, getValue(REVERB_HFLIMITER, 0)); break; } case TYPE_CHORUS: { Waveform wave = static_cast<Waveform>(getValue(CHORUS_WAVEFORM, static_cast<int>(WAVE_MAX_ENUM))); if (wave == WAVE_SINE) alEffecti(effect, AL_CHORUS_WAVEFORM, AL_CHORUS_WAVEFORM_SINUSOID); else if (wave == WAVE_TRIANGLE) alEffecti(effect, AL_CHORUS_WAVEFORM, AL_CHORUS_WAVEFORM_TRIANGLE); else alEffecti(effect, AL_CHORUS_WAVEFORM, AL_CHORUS_DEFAULT_WAVEFORM); alEffecti(PARAMSTR(CHORUS_PHASE,CHORUS,PHASE)); alEffectf(PARAMSTR(CHORUS_RATE,CHORUS,RATE)); alEffectf(PARAMSTR(CHORUS_DEPTH,CHORUS,DEPTH)); alEffectf(PARAMSTR(CHORUS_FEEDBACK,CHORUS,FEEDBACK)); alEffectf(PARAMSTR(CHORUS_DELAY,CHORUS,DELAY)); break; } case TYPE_DISTORTION: alEffectf(PARAMSTR(DISTORTION_GAIN,DISTORTION,GAIN)); alEffectf(PARAMSTR(DISTORTION_EDGE,DISTORTION,EDGE)); alEffectf(PARAMSTR(DISTORTION_LOWCUT,DISTORTION,LOWPASS_CUTOFF)); alEffectf(PARAMSTR(DISTORTION_EQCENTER,DISTORTION,EQCENTER)); alEffectf(PARAMSTR(DISTORTION_EQBAND,DISTORTION,EQBANDWIDTH)); break; case TYPE_ECHO: alEffectf(PARAMSTR(ECHO_DELAY,ECHO,DELAY)); alEffectf(PARAMSTR(ECHO_LRDELAY,ECHO,LRDELAY)); alEffectf(PARAMSTR(ECHO_DAMPING,ECHO,DAMPING)); alEffectf(PARAMSTR(ECHO_FEEDBACK,ECHO,FEEDBACK)); alEffectf(PARAMSTR(ECHO_SPREAD,ECHO,SPREAD)); break; case TYPE_FLANGER: { Waveform wave = static_cast<Waveform>(getValue(FLANGER_WAVEFORM, static_cast<int>(WAVE_MAX_ENUM))); if (wave == WAVE_SINE) alEffecti(effect, AL_FLANGER_WAVEFORM, AL_FLANGER_WAVEFORM_SINUSOID); else if (wave == WAVE_TRIANGLE) alEffecti(effect, AL_FLANGER_WAVEFORM, AL_FLANGER_WAVEFORM_TRIANGLE); else alEffecti(effect, AL_FLANGER_WAVEFORM, AL_FLANGER_DEFAULT_WAVEFORM); alEffecti(PARAMSTR(FLANGER_PHASE,FLANGER,PHASE)); alEffectf(PARAMSTR(FLANGER_RATE,FLANGER,RATE)); alEffectf(PARAMSTR(FLANGER_DEPTH,FLANGER,DEPTH)); alEffectf(PARAMSTR(FLANGER_FEEDBACK,FLANGER,FEEDBACK)); alEffectf(PARAMSTR(FLANGER_DELAY,FLANGER,DELAY)); break; } /* case TYPE_FREQSHIFTER: { alEffectf(PARAMSTR(FREQSHIFTER_FREQ,FREQUENCY_SHIFTER,FREQUENCY)); Direction dir = static_cast<Direction>(getValue(FREQSHIFTER_LEFTDIR, static_cast<int>(DIR_MAX_ENUM))); if (dir == DIR_NONE) alEffecti(effect, AL_FREQUENCY_SHIFTER_LEFT_DIRECTION, AL_FREQUENCY_SHIFTER_DIRECTION_OFF); else if(dir == DIR_UP) alEffecti(effect, AL_FREQUENCY_SHIFTER_LEFT_DIRECTION, AL_FREQUENCY_SHIFTER_DIRECTION_UP); else if(dir == DIR_DOWN) alEffecti(effect, AL_FREQUENCY_SHIFTER_LEFT_DIRECTION, AL_FREQUENCY_SHIFTER_DIRECTION_DOWN); else alEffecti(effect, AL_FREQUENCY_SHIFTER_LEFT_DIRECTION, AL_FREQUENCY_SHIFTER_DEFAULT_LEFT_DIRECTION); dir = static_cast<Direction>(getValue(FREQSHIFTER_RIGHTDIR, static_cast<int>(DIR_MAX_ENUM))); if (dir == DIR_NONE) alEffecti(effect, AL_FREQUENCY_SHIFTER_RIGHT_DIRECTION, AL_FREQUENCY_SHIFTER_DIRECTION_OFF); else if(dir == DIR_UP) alEffecti(effect, AL_FREQUENCY_SHIFTER_RIGHT_DIRECTION, AL_FREQUENCY_SHIFTER_DIRECTION_UP); else if(dir == DIR_DOWN) alEffecti(effect, AL_FREQUENCY_SHIFTER_RIGHT_DIRECTION, AL_FREQUENCY_SHIFTER_DIRECTION_DOWN); else alEffecti(effect, AL_FREQUENCY_SHIFTER_RIGHT_DIRECTION, AL_FREQUENCY_SHIFTER_DEFAULT_RIGHT_DIRECTION); break; } case TYPE_MORPHER: { Waveform wave = static_cast<Waveform>(getValue(MORPHER_WAVEFORM, static_cast<int>(WAVE_MAX_ENUM))); if (wave == WAVE_SINE) alEffecti(effect, AL_VOCAL_MORPHER_WAVEFORM, AL_VOCAL_MORPHER_WAVEFORM_SINUSOID); else if (wave == WAVE_TRIANGLE) alEffecti(effect, AL_VOCAL_MORPHER_WAVEFORM, AL_VOCAL_MORPHER_WAVEFORM_TRIANGLE); else if (wave == WAVE_SAWTOOTH) alEffecti(effect, AL_VOCAL_MORPHER_WAVEFORM, AL_VOCAL_MORPHER_WAVEFORM_SAWTOOTH); else alEffecti(effect, AL_VOCAL_MORPHER_WAVEFORM, AL_VOCAL_MORPHER_DEFAULT_WAVEFORM); Phoneme phoneme = static_cast<Phoneme>(getValue(MORPHER_PHONEMEA, static_cast<int>(PHONEME_MAX_ENUM))); if (phoneme == PHONEME_MAX_ENUM) alEffecti(effect, AL_VOCAL_MORPHER_PHONEMEA, AL_VOCAL_MORPHER_DEFAULT_PHONEMEA); else alEffecti(effect, AL_VOCAL_MORPHER_PHONEMEA, phonemeMap[phoneme]); phoneme = static_cast<Phoneme>(getValue(MORPHER_PHONEMEB, static_cast<int>(PHONEME_MAX_ENUM))); if (phoneme == PHONEME_MAX_ENUM) alEffecti(effect, AL_VOCAL_MORPHER_PHONEMEB, AL_VOCAL_MORPHER_DEFAULT_PHONEMEB); else alEffecti(effect, AL_VOCAL_MORPHER_PHONEMEB, phonemeMap[phoneme]); alEffectf(PARAMSTR(MORPHER_RATE,VOCAL_MORPHER,RATE)); alEffecti(PARAMSTR(MORPHER_TUNEA,VOCAL_MORPHER,PHONEMEA_COARSE_TUNING)); alEffecti(PARAMSTR(MORPHER_TUNEB,VOCAL_MORPHER,PHONEMEB_COARSE_TUNING)); break; } case TYPE_PITCHSHIFTER: { float tune = getValue(PITCHSHIFTER_PITCH, (float)AL_PITCH_SHIFTER_DEFAULT_COARSE_TUNE + (float)(AL_PITCH_SHIFTER_DEFAULT_FINE_TUNE - 50) / 100.0 ); int coarse = (int)floor(tune); int fine = (int)(fmod(tune, 1.0)*100.0); if (fine > 50) { fine -= 100; coarse += 1; } else if (fine < -50) { fine += 100; coarse -= 1; } if (coarse > AL_PITCH_SHIFTER_MAX_COARSE_TUNE) { coarse = AL_PITCH_SHIFTER_MAX_COARSE_TUNE; fine = AL_PITCH_SHIFTER_MAX_FINE_TUNE; } else if (coarse < AL_PITCH_SHIFTER_MIN_COARSE_TUNE) { coarse = AL_PITCH_SHIFTER_MIN_COARSE_TUNE; fine = AL_PITCH_SHIFTER_MIN_FINE_TUNE; } alEffecti(effect, AL_PITCH_SHIFTER_COARSE_TUNE, coarse); alEffecti(effect, AL_PITCH_SHIFTER_FINE_TUNE, fine); break; } */ case TYPE_MODULATOR: { Waveform wave = static_cast<Waveform>(getValue(MODULATOR_WAVEFORM,static_cast<int>(WAVE_MAX_ENUM))); if (wave == WAVE_SINE) alEffecti(effect, AL_RING_MODULATOR_WAVEFORM, AL_RING_MODULATOR_SINUSOID); else if (wave == WAVE_SAWTOOTH) alEffecti(effect, AL_RING_MODULATOR_WAVEFORM, AL_RING_MODULATOR_SAWTOOTH); else if (wave == WAVE_SQUARE) alEffecti(effect, AL_RING_MODULATOR_WAVEFORM, AL_RING_MODULATOR_SQUARE); else alEffecti(effect, AL_RING_MODULATOR_WAVEFORM, AL_RING_MODULATOR_DEFAULT_WAVEFORM); alEffectf(PARAMSTR(MODULATOR_FREQ,RING_MODULATOR,FREQUENCY)); alEffectf(PARAMSTR(MODULATOR_HIGHCUT,RING_MODULATOR,HIGHPASS_CUTOFF)); break; } /* case TYPE_AUTOWAH: alEffectf(PARAMSTR(AUTOWAH_ATTACK,AUTOWAH,ATTACK_TIME)); alEffectf(PARAMSTR(AUTOWAH_RELEASE,AUTOWAH,RELEASE_TIME)); alEffectf(PARAMSTR(AUTOWAH_RESONANCE,AUTOWAH,RESONANCE)); alEffectf(PARAMSTR(AUTOWAH_PEAKGAIN,AUTOWAH,PEAK_GAIN)); break; */ case TYPE_COMPRESSOR: alEffecti(effect, AL_COMPRESSOR_ONOFF, getValue(COMPRESSOR_ENABLE,static_cast<int>(AL_COMPRESSOR_DEFAULT_ONOFF))); break; case TYPE_EQUALIZER: alEffectf(PARAMSTR(EQUALIZER_LOWGAIN,EQUALIZER,LOW_GAIN)); alEffectf(PARAMSTR(EQUALIZER_LOWCUT,EQUALIZER,LOW_CUTOFF)); alEffectf(PARAMSTR(EQUALIZER_MID1GAIN,EQUALIZER,MID1_GAIN)); alEffectf(PARAMSTR(EQUALIZER_MID1FREQ,EQUALIZER,MID1_CENTER)); alEffectf(PARAMSTR(EQUALIZER_MID1BAND,EQUALIZER,MID1_WIDTH)); alEffectf(PARAMSTR(EQUALIZER_MID2GAIN,EQUALIZER,MID2_GAIN)); alEffectf(PARAMSTR(EQUALIZER_MID2FREQ,EQUALIZER,MID2_CENTER)); alEffectf(PARAMSTR(EQUALIZER_MID2BAND,EQUALIZER,MID2_WIDTH)); alEffectf(PARAMSTR(EQUALIZER_HIGHGAIN,EQUALIZER,HIGH_GAIN)); alEffectf(PARAMSTR(EQUALIZER_HIGHCUT,EQUALIZER,HIGH_CUTOFF)); break; case TYPE_BASIC: case TYPE_MAX_ENUM: break; } #undef PARAMSTR #undef clampf //alGetError(); return true; #else return false; #endif //ALC_EXT_EFX } const std::map<Effect::Parameter, float> &Effect::getParams() const { return params; } float Effect::getValue(Parameter in, float def) const { return params.find(in) == params.end() ? def : params.at(in); } int Effect::getValue(Parameter in, int def) const { return params.find(in) == params.end() ? def : static_cast<int>(params.at(in)); } /* std::map<Effect::Phoneme, ALint> Effect::phonemeMap = { {Effect::PHONEME_A, AL_VOCAL_MORPHER_PHONEME_A}, {Effect::PHONEME_E, AL_VOCAL_MORPHER_PHONEME_E}, {Effect::PHONEME_I, AL_VOCAL_MORPHER_PHONEME_I}, {Effect::PHONEME_O, AL_VOCAL_MORPHER_PHONEME_O}, {Effect::PHONEME_U, AL_VOCAL_MORPHER_PHONEME_U}, {Effect::PHONEME_AA, AL_VOCAL_MORPHER_PHONEME_AA}, {Effect::PHONEME_AE, AL_VOCAL_MORPHER_PHONEME_AE}, {Effect::PHONEME_AH, AL_VOCAL_MORPHER_PHONEME_AH}, {Effect::PHONEME_AO, AL_VOCAL_MORPHER_PHONEME_AO}, {Effect::PHONEME_EH, AL_VOCAL_MORPHER_PHONEME_EH}, {Effect::PHONEME_ER, AL_VOCAL_MORPHER_PHONEME_ER}, {Effect::PHONEME_IH, AL_VOCAL_MORPHER_PHONEME_IH}, {Effect::PHONEME_IY, AL_VOCAL_MORPHER_PHONEME_IY}, {Effect::PHONEME_UH, AL_VOCAL_MORPHER_PHONEME_UH}, {Effect::PHONEME_UW, AL_VOCAL_MORPHER_PHONEME_UW}, {Effect::PHONEME_B, AL_VOCAL_MORPHER_PHONEME_B}, {Effect::PHONEME_D, AL_VOCAL_MORPHER_PHONEME_D}, {Effect::PHONEME_F, AL_VOCAL_MORPHER_PHONEME_F}, {Effect::PHONEME_G, AL_VOCAL_MORPHER_PHONEME_G}, {Effect::PHONEME_J, AL_VOCAL_MORPHER_PHONEME_J}, {Effect::PHONEME_K, AL_VOCAL_MORPHER_PHONEME_K}, {Effect::PHONEME_L, AL_VOCAL_MORPHER_PHONEME_L}, {Effect::PHONEME_M, AL_VOCAL_MORPHER_PHONEME_M}, {Effect::PHONEME_N, AL_VOCAL_MORPHER_PHONEME_N}, {Effect::PHONEME_P, AL_VOCAL_MORPHER_PHONEME_P}, {Effect::PHONEME_R, AL_VOCAL_MORPHER_PHONEME_R}, {Effect::PHONEME_S, AL_VOCAL_MORPHER_PHONEME_S}, {Effect::PHONEME_T, AL_VOCAL_MORPHER_PHONEME_T}, {Effect::PHONEME_V, AL_VOCAL_MORPHER_PHONEME_V}, {Effect::PHONEME_Z, AL_VOCAL_MORPHER_PHONEME_Z} }; */ } //openal } //audio } //love
6,467
623
/* * Zed Attack Proxy (ZAP) and its related class files. * * ZAP is an HTTP/HTTPS proxy for assessing web application security. * * Copyright 2016 The ZAP Development Team * * 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.zaproxy.addon.commonlib; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.junit.jupiter.api.Assertions.assertThrows; import java.time.Instant; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.temporal.ChronoUnit; import java.util.stream.Stream; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; import org.zaproxy.addon.commonlib.http.HttpDateUtilsUnitTest; /** Unit test for {@link CookieUtils}. */ class CookieUtilsUnitTest { private static final String EMPTY_HEADER_VALUE = ""; private static final String EMPTY_ATTRIBUTE_NAME = ""; @Test void shouldFailToCheckNullHeaderValue() { // Given String headerValue = null; // When / Then assertThrows( IllegalArgumentException.class, () -> CookieUtils.hasAttribute(headerValue, EMPTY_ATTRIBUTE_NAME)); } @Test void shouldFailToCheckNullAttributeName() { // Given String attributeName = null; // When / Then assertThrows( IllegalArgumentException.class, () -> CookieUtils.hasAttribute(EMPTY_HEADER_VALUE, attributeName)); } @Test void shouldNotFindEmptyAttribute() { // Given String headerValue = "Name=Value; Attribute1; Attribute2=AV2; ;;"; // When boolean found = CookieUtils.hasAttribute(headerValue, EMPTY_ATTRIBUTE_NAME); // Then assertThat(found, is(equalTo(false))); } @Test void shouldNotFindAttributeInEmptyHeader() { // Given String attribute = "Attribute1"; // When boolean found = CookieUtils.hasAttribute(EMPTY_HEADER_VALUE, attribute); // Then assertThat(found, is(equalTo(false))); } @Test void shouldNotFindAttributeIfHeaderHasNoAttributes() { // Given String headerValue = "Name=Value"; String attribute = "Attribute1"; // When boolean found = CookieUtils.hasAttribute(headerValue, attribute); // Then assertThat(found, is(equalTo(false))); } @Test void shouldNotFindAttributeInNamelessCookie() { // Given String headerValue = "=Value; Attribute1; Attribute2=AV2; ;;"; String attribute = "Attribute1"; // When boolean found = CookieUtils.hasAttribute(headerValue, attribute); // Then assertThat(found, is(equalTo(false))); } @Test void shouldNotFindAttributeIfCookieHasNoNameValueSepartor() { // Given String headerValue = "Name; Attribute1; Attribute2=AV2; ;;"; String attribute = "Attribute1"; // When boolean found = CookieUtils.hasAttribute(headerValue, attribute); // Then assertThat(found, is(equalTo(false))); } @Test void shouldNotFindAttributeEvenIfCookieNameIsEqual() { // Given String headerValue = "Attribute1=Value; Attribute2=AV2"; String attribute = "Attribute1"; // When boolean found = CookieUtils.hasAttribute(headerValue, attribute); // Then assertThat(found, is(equalTo(false))); } @Test void shouldNotFindAttributeEvenIfCookieValueIsEqual() { // Given String headerValue = "Name=Attribute1; Attribute2=AV2"; String attribute = "Attribute1"; // When boolean found = CookieUtils.hasAttribute(headerValue, attribute); // Then assertThat(found, is(equalTo(false))); } @Test void shouldNotFindAttributeEvenIfAnAttributeValueIsEqual() { // Given String headerValue = "Name=Value; Attribute2=Attribute1"; String attribute = "Attribute1"; // When boolean found = CookieUtils.hasAttribute(headerValue, attribute); // Then assertThat(found, is(equalTo(false))); } @Test void shouldFindAttributeInValidCookieHeader() { // Given String headerValue = "Cookie=Value; Attribute1; Attribute2=AV2"; String attribute = "Attribute1"; // When boolean found = CookieUtils.hasAttribute(headerValue, attribute); // Then assertThat(found, is(equalTo(true))); } @Test void shouldFindAttributeEvenIfCookieHasNoValue() { // Given String headerValue = "Cookie=; Attribute1; Attribute2=AV2"; String attribute = "Attribute1"; // When boolean found = CookieUtils.hasAttribute(headerValue, attribute); // Then assertThat(found, is(equalTo(true))); } @Test void shouldFindAttributeEvenIfItHasValue() { // Given String headerValue = "Cookie=Value; Attribute1; Attribute2=AV2"; String attribute = "Attribute2"; // When boolean found = CookieUtils.hasAttribute(headerValue, attribute); // Then assertThat(found, is(equalTo(true))); } @Test void shouldFindAttributeEvenIfItHasSpacesInName() { // Given String headerValue = "Cookie=Value; Attribute1; Attribute2 =AV2"; String attribute = "Attribute2"; // When boolean found = CookieUtils.hasAttribute(headerValue, attribute); // Then assertThat(found, is(equalTo(true))); } @Test void shouldFindAttributeEvenIfItHasDifferentCase() { // Given String headerValue = "Cookie=Value; Attribute1; Attribute2=AV2"; String attribute = "aTtRiBuTe2"; // When boolean found = CookieUtils.hasAttribute(headerValue, attribute); // Then assertThat(found, is(equalTo(true))); } @Test void shouldNotFindCookiePlusNameIfNameIsNull() { // Given String fullHeader = "Set-Cookie: foo; Attribute1"; String headerValue = "foo; Attribute1"; // When String name = CookieUtils.getSetCookiePlusName(fullHeader, headerValue); // Then assertThat(name, is(equalTo(null))); } @Test void shouldKnowThatNameDoesNotIncludeSemiColon() { // Given String fullHeader = "Set-Cookie: foo; Attribute1; Attribute2=AV2"; String headerValue = "foo; Attribute1; Attribute2=AV2"; // When String name = CookieUtils.getSetCookiePlusName(fullHeader, headerValue); // Then assertThat(name, is(equalTo(null))); } @Test void shouldFindCookiePlusNameIfWellFormed() { // Given String fullHeader = "Set-Cookie: name=value; Attribute1; Attribute2=AV2"; String headerValue = "name=value; Attribute1; Attribute2=AV2"; // When String name = CookieUtils.getSetCookiePlusName(fullHeader, headerValue); // Then assertThat(name, is(equalTo("Set-Cookie: name"))); } @ParameterizedTest @ValueSource( strings = { "Sun, 06 Nov 1994 08:49:37 GMT", "Sunday, 06-Nov-94 08:49:37 GMT", "Sun Nov 6 08:49:37 1994", "Unkown Format" }) void shouldReportExpiredIfDateInThePastOrUnkownFormat(String date) { // Given String header = "name=value; expires=" + date; // When boolean expired = CookieUtils.isExpired(header); // Then assertThat(expired, is(equalTo(true))); } @ParameterizedTest @MethodSource(value = "expiresFutureProvider") void shouldReportNotExpiredIfDateInTheFuture(String date) { // Given String header = "name=value; expires=" + date; // When boolean expired = CookieUtils.isExpired(header); // Then assertThat(expired, is(equalTo(false))); } @ParameterizedTest @ValueSource(strings = {"", "a; expires=Sun, 06 Nov 1994 08:49:37 GMT", "name=value;"}) void shouldReportNotExpiredIfEmptyHeaderOrInvalidCookieOrExpiresMissing(String headerValue) { // Given String header = headerValue; // When boolean expired = CookieUtils.isExpired(header); // Then assertThat(expired, is(equalTo(false))); } static Stream<String> expiresFutureProvider() { ZonedDateTime future = ZonedDateTime.ofInstant(Instant.now().plus(1, ChronoUnit.DAYS), ZoneOffset.UTC); return HttpDateUtilsUnitTest.formatters().stream().map(e -> e.format(future)); } }
3,768
2,542
<reponame>gridgentoo/ServiceFabricAzure // ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #pragma once namespace Hosting2 { class DomainUser : public SecurityUser { DENY_COPY(DomainUser) public: DomainUser( std::wstring const& applicationId, ServiceModel::SecurityUserDescription const & userDescription); DomainUser( std::wstring const & applicationId, std::wstring const & name, std::wstring const & accountName, std::wstring const & password, bool isPasswordEncrypted, bool loadProfile, bool performInteractiveLogon, ServiceModel::SecurityPrincipalAccountType::Enum accountType, std::vector<std::wstring> parentApplicationGroups, std::vector<std::wstring> parentSystemGroups); virtual ~DomainUser(); __declspec(property(get=get_IsPasswordEncrypted)) bool const IsPasswordEncrypted; bool const get_IsPasswordEncrypted() const { return this->isPasswordEncrypted_; } virtual Common::ErrorCode CreateLogonToken(__out Common::AccessTokenSPtr & userToken); Common::ErrorCode UpdateCachedCredentials(); private: std::wstring domain_; std::wstring username_; }; }
561
749
// Copyright (c) 2015-2015 <NAME> // SPDX-License-Identifier: BSL-1.0 #include <SoapySDR/Formats.hpp> #include <cstdlib> #include <cstdio> int main(void) { #define formatCheck(formatStr, expectedSize) \ { \ size_t bytes = SoapySDR::formatToSize(formatStr); \ printf("%s -> %d bytes/element\t", formatStr, int(bytes)); \ if (bytes != expectedSize) \ { \ printf("FAIL: expected %d bytes!\n", int(expectedSize)); \ return EXIT_FAILURE; \ } \ else printf("OK\n"); \ } formatCheck(SOAPY_SDR_CF64, 16); formatCheck(SOAPY_SDR_CF32, 8); formatCheck(SOAPY_SDR_CS32, 8); formatCheck(SOAPY_SDR_CU32, 8); formatCheck(SOAPY_SDR_CS16, 4); formatCheck(SOAPY_SDR_CU16, 4); formatCheck(SOAPY_SDR_CS12, 3); formatCheck(SOAPY_SDR_CU12, 3); formatCheck(SOAPY_SDR_CS8, 2); formatCheck(SOAPY_SDR_CU8, 2); formatCheck(SOAPY_SDR_CS4, 1); formatCheck(SOAPY_SDR_CU4, 1); formatCheck(SOAPY_SDR_F64, 8); formatCheck(SOAPY_SDR_F32, 4); formatCheck(SOAPY_SDR_S32, 4); formatCheck(SOAPY_SDR_U32, 4); formatCheck(SOAPY_SDR_S16, 2); formatCheck(SOAPY_SDR_U16, 2); formatCheck(SOAPY_SDR_S8, 1); formatCheck(SOAPY_SDR_U8, 1); printf("DONE!\n"); return EXIT_SUCCESS; }
661
337
/* * 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.eventmesh.api.registry.dto; /** * EventMeshDataInfo */ public class EventMeshDataInfo { private String eventMeshClusterName; private String eventMeshName; private String endpoint; private long lastUpdateTimestamp; public EventMeshDataInfo(String eventMeshClusterName, String eventMeshName, String endpoint, long lastUpdateTimestamp) { this.eventMeshClusterName = eventMeshClusterName; this.eventMeshName = eventMeshName; this.endpoint = endpoint; this.lastUpdateTimestamp = lastUpdateTimestamp; } public String getEventMeshClusterName() { return eventMeshClusterName; } public void setEventMeshClusterName(String eventMeshClusterName) { this.eventMeshClusterName = eventMeshClusterName; } public String getEventMeshName() { return eventMeshName; } public void setEventMeshName(String eventMeshName) { this.eventMeshName = eventMeshName; } public String getEndpoint() { return endpoint; } public void setEndpoint(String endpoint) { this.endpoint = endpoint; } public long getLastUpdateTimestamp() { return lastUpdateTimestamp; } public void setLastUpdateTimestamp(long lastUpdateTimestamp) { this.lastUpdateTimestamp = lastUpdateTimestamp; } }
674
383
<filename>blender_render/image_utils.py import numpy as np from PIL import Image import cv2 import os from os.path import join, dirname, basename import shutil # Value list used to select object mask rendered by Blender value_list = [25, 39, 48, 56, 63, 69, 75, 80, 85, 89, 93, 97, 101, 105, 108, 111, 115, 118, 121, 124, 126, 129, 132, 134, 137, 139, 142, 144, 147, 149] # Transform the image containing all visible object masks into one mask per image def one_mask_per_image(mask_path, image_id, model_number): mask = np.array(Image.open(mask_path).convert('L')) mask_dir = dirname(mask_path) bbox, px = [], [] for i in range(model_number): obj_mask = (mask == value_list[i]).astype('uint8') bbox.append(cv2.boundingRect(obj_mask)) px.append(int(np.sum(obj_mask))) cv2.imwrite(join(mask_dir, '{:06d}_{:06d}.png'.format(image_id, i)), obj_mask * 255) os.remove(mask_path) return bbox, px # Transform the colored mask of Blender renderer into binary mask def binary_mask(mask_path): mask = np.array(Image.open(mask_path).convert('L')) obj_mask = (mask != 0).astype('uint8') x, y, w, h = cv2.boundingRect(obj_mask) px = int(np.sum(obj_mask)) truncated = x == 0 or x + w == mask.shape[1] or y == 0 or y + h == mask.shape[0] cv2.imwrite(mask_path, obj_mask * 255) return (x, y, w, h), px, truncated # Obtain the object center from the translation vector def obtain_obj_center(T, fx, fy, px, py, height, width): cx = int(fx * T[0] / T[2] + px) cy = int(fy * T[1] / T[2] + py) boarder = 0.1 inside = True if boarder * width <= cx <= (1 - boarder) * width and boarder * height <= cy <= ( 1 - boarder) * height else False return cx, cy, inside # Crop and Resize the image without changing the aspect ratio def resize_padding(im, desired_size): # compute the new size old_size = im.size ratio = float(desired_size) / max(old_size) new_size = tuple([int(x * ratio) for x in old_size]) im = im.resize(new_size, Image.BILINEAR) # create a new image and paste the resized on it new_im = Image.new("RGBA", (desired_size, desired_size)) new_im.paste(im, ((desired_size - new_size[0]) // 2, (desired_size - new_size[1]) // 2)) return new_im def resize_padding_v2(im, desired_size_in, desired_size_out): # compute the new size old_size = im.size ratio = float(desired_size_in)/max(old_size) new_size = tuple([int(x*ratio) for x in old_size]) im = im.resize(new_size, Image.ANTIALIAS) # create a new image and paste the resized on it new_im = Image.new("RGBA", (desired_size_out, desired_size_out)) new_im.paste(im, ((desired_size_out - new_size[0]) // 2, (desired_size_out - new_size[1]) // 2)) return new_im # Crop and resize the rendering images def clean_rendering_results(img_path, depth_path, normal_path, target_size=128): img = Image.open(img_path) depth = Image.open(depth_path) normal = Image.open(normal_path) bbox = img.getbbox() img, depth, normal = img.crop(bbox), depth.crop(bbox), normal.crop(bbox) img = resize_padding(img, target_size).convert('RGB') depth = resize_padding(depth, target_size).convert('L') normal = resize_padding(normal, target_size).convert('RGB') normal_array = np.array(normal) mask = np.array(depth) == 0 normal_array[mask, :] = 0 normal = Image.fromarray(normal_array) img.save(img_path) depth.save(depth_path) normal.save(normal_path)
1,451
664
// Classic Shell (c) 2009-2016, <NAME> // Confidential information of <NAME>. Not for disclosure or distribution without prior written consent from the author #define STRICT_TYPED_ITEMIDS #define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit #include <windows.h> #include <stdio.h> #include <atlstr.h> #include "ResourceHelper.h" #include "ComHelper.h" #include "StringUtils.h" #include "Settings.h" #include <shlobj.h> #include <wuapi.h> #include <Psapi.h> #include <propkey.h> #include <searchapi.h> #define SECURITY_WIN32 #include <Security.h> #include <set> #include <map> #include <algorithm> extern HINSTANCE g_hInstance; struct CompareStrings { bool operator()( const CString &str1, const CString &str2 ) const { return _wcsicmp(str1,str2)<0; } }; const CLSID CLSID_CSearchManager2={0x7D096C5F,0xAC08,0x4f1f,{0xBE,0xB7,0x5C,0x22,0xC5,0x17,0xCE,0x39}}; /////////////////////////////////////////////////////////////////////////////// // dummy functions void ClosingSettings( HWND hWnd, int flags, int command ) { } void SettingChangedCallback( const CSetting *pSetting ) { } void UpgradeSettings( bool bShared ) { } void UpdateSettings( void ) { } const wchar_t *GetDocRelativePath( void ) { return NULL; } /////////////////////////////////////////////////////////////////////////////// static const wchar_t *g_Tabs=L"\t\t\t\t\t\t\t\t\t\t"; static const wchar_t *GetTabs( int count ) { if (count>10) count=10; return g_Tabs+(10-count); } DWORD GetFileVersion( const wchar_t *fname, DWORD *pBuild ) { DWORD dwHandle; DWORD dwLen=GetFileVersionInfoSize(fname,&dwHandle); if (!dwLen) return 0; std::vector<char> buf(dwLen); if (!GetFileVersionInfo(fname,dwHandle,dwLen,&buf[0])) return 0; VS_FIXEDFILEINFO *pFileInfo; UINT len; if (!VerQueryValue(&buf[0],L"\\",(void**)&pFileInfo,&len)) return 0; if (pBuild) *pBuild=LOWORD(pFileInfo->dwFileVersionLS); return (HIWORD(pFileInfo->dwFileVersionMS)<<24)|(LOWORD(pFileInfo->dwFileVersionMS)<<16)|HIWORD(pFileInfo->dwFileVersionLS); } static LONG ReadRegistryValue( HKEY root, const wchar_t *keyName, const wchar_t *valName, DWORD &value ) { CRegKey regKey; LONG res=regKey.Open(root,keyName,KEY_READ|KEY_WOW64_64KEY); if (res==ERROR_SUCCESS) res=regKey.QueryDWORDValue(valName,value); return res; } static LONG ReadRegistryValue( HKEY root, const wchar_t *keyName, const wchar_t *valName, CString &value ) { value.Empty(); wchar_t text[1024]; ULONG size=_countof(text); CRegKey regKey; LONG res=regKey.Open(root,keyName,KEY_READ|KEY_WOW64_64KEY); if (res==ERROR_SUCCESS) { res=regKey.QueryStringValue(valName,text,&size); if (res==ERROR_SUCCESS) value=text; } return res; } static void WriteRegKey( FILE *f, CRegKey &key, int tabs, const wchar_t *annotations[][2]=NULL ) { std::vector<BYTE> buf(65536); for (int index=0;;index++) { wchar_t name[256]; DWORD len=_countof(name); DWORD type; DWORD size=(int)buf.size(); if (RegEnumValue(key,index,name,&len,NULL,&type,&buf[0],&size)!=ERROR_SUCCESS) break; fwprintf(f,L"%s%s: ",GetTabs(tabs),name); switch (type) { case REG_DWORD: { DWORD val=*(DWORD*)&buf[0]; fwprintf(f,L"0x%08X (%d)",val,val); } break; case REG_SZ: case REG_EXPAND_SZ: { CString val=(wchar_t*)&buf[0]; val.Replace(L"\r",L"\\r"); val.Replace(L"\n",L"\\n"); fwprintf(f,L"%s",(const wchar_t*)val); } break; case REG_MULTI_SZ: for (const wchar_t *str=(wchar_t*)&buf[0];*str;str+=Strlen(str)+1) { CString val=str; val.Replace(L"\r",L"\\r"); val.Replace(L"\n",L"\\n"); fwprintf(f,L"%s\\0",(const wchar_t*)val); } break; } if (annotations) { for (const wchar_t **a=&annotations[0][0];*a;a+=2) { if (_wcsicmp(a[0],name)==0) { fwprintf(f,L" - %s",a[1]); break; } } } fwprintf(f,L"\r\n"); } } static void WriteFolder( FILE *f, const wchar_t *path, int tabs, bool bRecursive ) { wchar_t find[_MAX_PATH]; Sprintf(find,_countof(find),L"%s\\*.*",path); std::vector<CString> folders; WIN32_FIND_DATA data; HANDLE h=FindFirstFile(find,&data); while (h!=INVALID_HANDLE_VALUE) { wchar_t fname[_MAX_PATH]; Sprintf(fname,_countof(fname),L"%s\\%s",path,data.cFileName); if (data.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY) { if (bRecursive && wcscmp(data.cFileName,L".")!=0 && wcscmp(data.cFileName,L"..")!=0) folders.push_back(fname); } else { fwprintf(f,L"%s%s",GetTabs(tabs),data.cFileName); FILETIME localTime; FileTimeToLocalFileTime(&data.ftLastWriteTime,&localTime); SYSTEMTIME sysTime; FileTimeToSystemTime(&localTime,&sysTime); fwprintf(f,L", date: %04d/%02d/%02d, time: %02d:%02d:%02d",sysTime.wYear,sysTime.wMonth,sysTime.wDay,sysTime.wHour,sysTime.wMinute,sysTime.wSecond); const wchar_t *ext=PathFindExtension(data.cFileName); if (_wcsicmp(ext,L".lnk")==0) { // find target, args and appid CComPtr<IShellItem> pItem; SHCreateItemFromParsingName(fname,NULL,IID_IShellItem,(void**)&pItem); if (pItem) { CComPtr<IShellLink> pLink; if (SUCCEEDED(pItem->BindToHandler(NULL,BHID_SFUIObject,IID_IShellLink,(void**)&pLink))) { CComPtr<IShellItem> pTarget; CComString target; CAbsolutePidl pidl; if (FAILED(pLink->GetIDList(&pidl))) fwprintf(f,L" target='no pidl'"); else if (FAILED(SHCreateItemFromIDList(pidl,IID_IShellItem,(void**)&pTarget))) fwprintf(f,L" target='no item'"); else if (FAILED(pTarget->GetDisplayName(SIGDN_DESKTOPABSOLUTEPARSING,&target))) fwprintf(f,L" target='no name'"); else fwprintf(f,L" target='%s'",(const wchar_t*)target); wchar_t args[256]; if (FAILED(pLink->GetArguments(args,_countof(args)))) args[0]=0; CComQIPtr<IPropertyStore> pStore=pLink; CString appid; if (pStore) { PROPVARIANT val; PropVariantInit(&val); if (SUCCEEDED(pStore->GetValue(PKEY_AppUserModel_ID,&val)) && val.vt==VT_BSTR && val.bstrVal) appid=val.bstrVal; PropVariantClear(&val); if (!args[0] && SUCCEEDED(pStore->GetValue(PKEY_Link_Arguments,&val)) && val.vt==VT_BSTR && val.bstrVal) Strcpy(args,_countof(args),val.bstrVal); PropVariantClear(&val); } if (args[0]) fwprintf(f,L" args='%s'",args); if (!appid.IsEmpty()) fwprintf(f,L" appid='%s'",(const wchar_t*)appid); } } } else { DWORD build; DWORD ver=GetFileVersion(fname,&build); if (ver) fwprintf(f,L", version: %d.%d.%d.%d",ver>>24,(ver>>16)&255,ver&65535,build); if (_wcsicmp(ext,L".exe")==0) { CString policy; ReadRegistryValue(HKEY_CURRENT_USER,L"Software\\Microsoft\\Windows NT\\CurrentVersion\\AppCompatFlags\\Layers",fname,policy); if (!policy.IsEmpty()) fwprintf(f,L" usercompat='%s'",(const wchar_t*)policy); ReadRegistryValue(HKEY_LOCAL_MACHINE,L"Software\\Microsoft\\Windows NT\\CurrentVersion\\AppCompatFlags\\Layers",fname,policy); if (!policy.IsEmpty()) fwprintf(f,L" compat='%s'",(const wchar_t*)policy); } } fwprintf(f,L"\r\n"); } if (!FindNextFile(h,&data)) { FindClose(h); break; } } for (std::vector<CString>::const_iterator it=folders.begin();it!=folders.end();++it) { fwprintf(f,L"%s%s\r\n",GetTabs(tabs),PathFindFileName(*it)); WriteFolder(f,*it,tabs+1,true); } } static void WriteSettings( FILE *f, TSettingsComponent component ) { CRegKey regSettings, regSettingsUser, regPolicy, regPolicyUser; bool bUpgrade=OpenSettingsKeys(component,regSettings,regSettingsUser,regPolicy,regPolicyUser); if (regSettingsUser) { fwprintf(f,L"\t\t%s:\r\n",bUpgrade?L"User settings (old)":L"User settings"); WriteRegKey(f,regSettingsUser,3); fwprintf(f,L"\r\n"); } if (regSettings) { fwprintf(f,L"\t\tCommon settings:\r\n"); WriteRegKey(f,regSettings,3); fwprintf(f,L"\r\n"); } if (regPolicyUser) { fwprintf(f,L"\t\tUser policies:\r\n"); WriteRegKey(f,regPolicyUser,3); fwprintf(f,L"\r\n"); } if (regPolicy) { fwprintf(f,L"\t\tCommon policies:\r\n"); WriteRegKey(f,regPolicy,3); fwprintf(f,L"\r\n"); } } static void WriteProcessInfo( FILE *f, HANDLE hProcess, int tabs ) { HMODULE hMods[1024]; std::set<CString,CompareStrings> names; DWORD cbNeeded; if (EnumProcessModules(hProcess,hMods,sizeof(hMods),&cbNeeded)) { int count=cbNeeded/sizeof(HMODULE); for (int i=0;i<count;i++) { wchar_t fname[_MAX_PATH]; if (GetModuleFileNameEx(hProcess,hMods[i],fname,_countof(fname))) names.insert(fname); } } for (std::set<CString,CompareStrings>::const_iterator it=names.begin();it!=names.end();++it) { DWORD ver=GetFileVersion(*it,NULL); fwprintf(f,L"%s%s (%d.%d.%d)\r\n",GetTabs(tabs),(const wchar_t*)(*it),ver>>24,(ver>>16)&255,ver&65535); } } PROPERTYKEY PKEY_ProductVersion={{0x0CEF7D53, 0xFA64, 0x11D1, {0xA2, 0x03, 0x00, 0x00, 0xF8, 0x1F, 0xED, 0xEE}}, 8}; static BOOL CALLBACK MonitorEnumProc( HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData ) { FILE *f=(FILE*)dwData; HWND taskbar=FindWindowEx(NULL,NULL,L"Shell_TrayWnd",NULL); HMONITOR mon=taskbar?MonitorFromWindow(taskbar,MONITOR_DEFAULTTONULL):NULL; if (mon!=hMonitor) { for (taskbar=FindWindowEx(NULL,NULL,L"Shell_SecondaryTrayWnd",NULL);taskbar;taskbar=FindWindowEx(NULL,taskbar,L"Shell_SecondaryTrayWnd",NULL)) { mon=MonitorFromWindow(taskbar,MONITOR_DEFAULTTONULL); if (mon==hMonitor) break; } } fwprintf(f,L"\tMonitor: %d, %d - (%d x %d)\r\n",lprcMonitor->left,lprcMonitor->top,lprcMonitor->right-lprcMonitor->left,lprcMonitor->bottom-lprcMonitor->top); if (mon==hMonitor) { RECT rc; GetWindowRect(taskbar,&rc); fwprintf(f,L"\t\tTaskbar: %d, %d - (%d x %d)\r\n",rc.left,rc.top,rc.right-rc.left,rc.bottom-rc.top); } return TRUE; } static const wchar_t *g_ExplorerRegAnnotations[][2]={ {L"Start_TrackDocs",L"track documents"}, {L"Start_TrackProgs",L"track programs"}, {L"TaskbarSizeMove",L"unlocked taskbar"}, {L"TaskbarSmallIcons",L"small icons"}, {NULL} }; struct GroupInfo { CString desc; CString group; const wchar_t *status; }; static void WriteLogFile( FILE *f ) { // windows version BOOL b64=FALSE; #ifdef _WIN64 b64=TRUE; #else IsWow64Process(GetCurrentProcess(),&b64); #endif DWORD winVer=GetVersionEx(GetModuleHandle(L"user32.dll")); fwprintf(f,L"System\r\n"); fwprintf(f,L"\tWindows version (real): %d.%02d.%d %d-bit\r\n",(winVer>>24),(winVer>>16)&255,winVer&65535,b64?64:32); DWORD ver2=GetWinVersion(); fwprintf(f,L"\tWindows version (reported): %d.%02d\r\n",(ver2>>8),ver2&255); CString strVer1, strVer2; ReadRegistryValue(HKEY_LOCAL_MACHINE,L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion",L"ProductName",strVer1); ReadRegistryValue(HKEY_LOCAL_MACHINE,L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion",L"CurrentVersion",strVer2); fwprintf(f,L"\tWindows version (registry): %s %s\r\n",(const wchar_t*)strVer1,(const wchar_t*)strVer2); wchar_t user1[256]={0}, user2[256]={0}; ULONG size=_countof(user1); GetComputerName(user1,&size); fwprintf(f,L"\tComputer: %s\r\n",user1); size=_countof(user1); GetUserName(user1,&size); size=_countof(user2); if (GetUserNameEx(NameDisplay,user2,&size)) fwprintf(f,L"\tUser: %s (%s)\r\n",user1,user2); else fwprintf(f,L"\tUser: %s (0x%08X)\r\n",user1,GetLastError()); { wchar_t languages[100]; ULONG count=0; ULONG len=_countof(languages); GetUserPreferredUILanguages(MUI_LANGUAGE_NAME,&size,languages,&len); if (len>1) { for (ULONG i=0;i<len-2;i++) if (languages[i]==0) languages[i]='|'; fwprintf(f,L"\tUser Languages: %s\r\n",languages); } count=0; len=_countof(languages); GetThreadPreferredUILanguages(MUI_LANGUAGE_NAME,&size,languages,&len); if (len>1) { for (ULONG i=0;i<len-2;i++) if (languages[i]==0) languages[i]='|'; fwprintf(f,L"\tThread Languages: %s\r\n",languages); } } EnumDisplayMonitors(NULL,NULL,MonitorEnumProc,(LPARAM)f); { int touch=GetSystemMetrics(SM_DIGITIZER); wchar_t touchCaps[256]=L""; if (touch&NID_INTEGRATED_TOUCH) Strcat(touchCaps,_countof(touchCaps),L"integrated touch, "); if (touch&NID_EXTERNAL_TOUCH) Strcat(touchCaps,_countof(touchCaps),L"external touch, "); if (touch&NID_INTEGRATED_PEN) Strcat(touchCaps,_countof(touchCaps),L"integrated pen, "); if (touch&NID_EXTERNAL_PEN) Strcat(touchCaps,_countof(touchCaps),L"external pen "); if (touch&NID_MULTI_INPUT) Strcat(touchCaps,_countof(touchCaps),L"multi input, "); if (touch&NID_READY) Strcat(touchCaps,_countof(touchCaps),L"ready, "); if (Strlen(touchCaps)>=2) touchCaps[Strlen(touchCaps)-2]=0; else Strcpy(touchCaps,_countof(touchCaps),L"None"); fwprintf(f,L"\tTouch capabilities: %s\r\n",touchCaps); } { CComString pPath; if (FAILED(SHGetKnownFolderPath(FOLDERID_StartMenu,0,NULL,&pPath))) pPath.Clear(); fwprintf(f,L"\tStart Menu folder: '%s'\r\n",pPath?pPath:L""); pPath.Clear(); if (FAILED(SHGetKnownFolderPath(FOLDERID_Programs,0,NULL,&pPath))) pPath.Clear(); fwprintf(f,L"\tPrograms folder: '%s'\r\n",pPath?pPath:L""); pPath.Clear(); if (FAILED(SHGetKnownFolderPath(FOLDERID_CommonStartMenu,0,NULL,&pPath))) pPath.Clear(); fwprintf(f,L"\tCommon Start Menu folder: '%s'\r\n",pPath?pPath:L""); pPath.Clear(); if (FAILED(SHGetKnownFolderPath(FOLDERID_CommonPrograms,0,NULL,&pPath))) pPath.Clear(); fwprintf(f,L"\tCommon Programs folder: '%s'\r\n",pPath?pPath:L""); } if (HIWORD(winVer)<WIN_VER_WIN8) { DWORD count; if (ReadRegistryValue(HKEY_LOCAL_MACHINE,L"Software\\Microsoft\\Windows\\CurrentVersion\\WindowsUpdate\\Auto Update\\UAS",L"UpdateCount",count)==ERROR_SUCCESS) fwprintf(f,L"\tPending updates: %d\r\n",count); } else { typedef HRESULT (WINAPI *FGetAutoUpdateNotification)(DWORD,DWORD*,DWORD*,DWORD*); HMODULE mod=LoadLibrary(L"wuaext.dll"); if (mod) { FGetAutoUpdateNotification fun=(FGetAutoUpdateNotification)GetProcAddress(mod,"GetAutoUpdateNotification"); if (fun) { DWORD a,b,c; HRESULT hr=fun(0,&a,&b,&c); fwprintf(f,L"\tPending updates (0x%08X): %d, %d, %d\r\n",hr,a,b,c); } FreeLibrary(mod); } } { CComPtr<ISystemInformation> pSysInfo; pSysInfo.CoCreateInstance(CLSID_SystemInformation); if (pSysInfo) { VARIANT_BOOL reboot; if (SUCCEEDED(pSysInfo->get_RebootRequired(&reboot)) && reboot) { fwprintf(f,L"\tWindows Update: Reboot required\r\n"); } } } if (HIWORD(winVer)>=WIN_VER_WIN81) { DWORD metro; if (ReadRegistryValue(HKEY_CURRENT_USER,L"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\StartPage",L"OpenAtLogon",metro)==ERROR_SUCCESS) fwprintf(f,L"\tSkip to Desktop: %d\r\n",1-metro); else fwprintf(f,L"\tSkip to Desktop: unset\r\n"); } { CRegKey regKey; const wchar_t *key=L"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Advanced"; if (regKey.Open(HKEY_CURRENT_USER,key,KEY_READ|KEY_WOW64_64KEY)==ERROR_SUCCESS) { fwprintf(f,L"\t\r\n\tHKCU\\%s:\r\n",key); WriteRegKey(f,regKey,2,g_ExplorerRegAnnotations); fwprintf(f,L"\r\n"); } } fwprintf(f,L"\tPolicies:\r\n"); fwprintf(f,L"\t\tSHRestricted(REST_HASFINDCOMPUTERS)=%d\r\n",SHRestricted(REST_HASFINDCOMPUTERS)); fwprintf(f,L"\t\tSHRestricted(REST_NOCHANGESTARMENU)=%d\r\n",SHRestricted(REST_NOCHANGESTARMENU)); fwprintf(f,L"\t\tSHRestricted(REST_NOCLOSE)=%d\r\n",SHRestricted(REST_NOCLOSE)); fwprintf(f,L"\t\tSHRestricted(REST_NOCOMMONGROUPS)=%d\r\n",SHRestricted(REST_NOCOMMONGROUPS)); fwprintf(f,L"\t\tSHRestricted(REST_NOCONTROLPANEL)=%d\r\n",SHRestricted(REST_NOCONTROLPANEL)); fwprintf(f,L"\t\tSHRestricted(REST_NODISCONNECT)=%d\r\n",SHRestricted(REST_NODISCONNECT)); fwprintf(f,L"\t\tSHRestricted(REST_NOFAVORITESMENU)=%d\r\n",SHRestricted(REST_NOFAVORITESMENU)); fwprintf(f,L"\t\tSHRestricted(REST_NOFIND)=%d\r\n",SHRestricted(REST_NOFIND)); fwprintf(f,L"\t\tSHRestricted(REST_NONETWORKCONNECTIONS)=%d\r\n",SHRestricted(REST_NONETWORKCONNECTIONS)); fwprintf(f,L"\t\tSHRestricted(REST_NORECENTDOCSMENU)=%d\r\n",SHRestricted(REST_NORECENTDOCSMENU)); fwprintf(f,L"\t\tSHRestricted(REST_NORUN)=%d\r\n",SHRestricted(REST_NORUN)); fwprintf(f,L"\t\tSHRestricted(REST_NOSETFOLDERS)=%d\r\n",SHRestricted(REST_NOSETFOLDERS)); fwprintf(f,L"\t\tSHRestricted(REST_NOSETTASKBAR)=%d\r\n",SHRestricted(REST_NOSETTASKBAR)); fwprintf(f,L"\t\tSHRestricted(REST_NOSMEJECTPC)=%d\r\n",SHRestricted(REST_NOSMEJECTPC)); fwprintf(f,L"\t\tSHRestricted(REST_NOSMHELP)=%d\r\n",SHRestricted(REST_NOSMHELP)); fwprintf(f,L"\t\tSHRestricted(REST_NOSMMYDOCS)=%d\r\n",SHRestricted(REST_NOSMMYDOCS)); fwprintf(f,L"\t\tSHRestricted(REST_NOSTRCMPLOGICAL)=%d\r\n",SHRestricted(REST_NOSTRCMPLOGICAL)); fwprintf(f,L"\t\tSHRestricted(REST_STARTMENULOGOFF)=%d\r\n",SHRestricted(REST_STARTMENULOGOFF)); fwprintf(f,L"\t\tSHRestricted(REST_FORCESTARTMENULOGOFF)=%d\r\n",SHRestricted(REST_FORCESTARTMENULOGOFF)); { CRegKey regKey; const wchar_t *key=L"Software\\Microsoft\\Windows\\CurrentVersion\\Run"; if (regKey.Open(HKEY_LOCAL_MACHINE,key,KEY_READ|KEY_WOW64_64KEY)==ERROR_SUCCESS) { fwprintf(f,L"\r\n\tHKLM\\%s:\r\n",key); WriteRegKey(f,regKey,2); fwprintf(f,L"\r\n"); } } { CRegKey regKey; const wchar_t *key=L"Software\\Microsoft\\Windows\\CurrentVersion\\Run"; if (regKey.Open(HKEY_CURRENT_USER,key,KEY_READ|KEY_WOW64_64KEY)==ERROR_SUCCESS) { fwprintf(f,L"\r\n\tHKCU\\%s:\r\n",key); WriteRegKey(f,regKey,2); fwprintf(f,L"\r\n"); } } { CComString pPath; if (SUCCEEDED(SHGetKnownFolderPath(FOLDERID_Startup,0,NULL,&pPath))) { fwprintf(f,L"\r\n\t%s:\r\n",(const wchar_t*)pPath); WriteFolder(f,pPath,2,false); fwprintf(f,L"\r\n"); } } { CComString pPath; if (SUCCEEDED(SHGetKnownFolderPath(FOLDERID_CommonStartup,0,NULL,&pPath))) { fwprintf(f,L"\r\n\t%s:\r\n",(const wchar_t*)pPath); WriteFolder(f,pPath,2,false); fwprintf(f,L"\r\n"); } } { CComPtr<ISearchManager> pSearchManager; pSearchManager.CoCreateInstance(CLSID_CSearchManager2); if (pSearchManager) { CComPtr<ISearchCatalogManager> pCatalogManager; pSearchManager->GetCatalog(L"SystemIndex",&pCatalogManager); if (pCatalogManager) { CComPtr<ISearchCrawlScopeManager> pSearchCrawlScopeManager; pCatalogManager->GetCrawlScopeManager(&pSearchCrawlScopeManager); if (pSearchCrawlScopeManager) { CComPtr<IEnumSearchRoots> pSearchRoots; pSearchCrawlScopeManager->EnumerateRoots(&pSearchRoots); if (pSearchRoots) { fwprintf(f,L"\r\nSearch Roots:\r\n"); CComPtr<ISearchRoot> pSearchRoot; while (pSearchRoots->Next(1,&pSearchRoot,NULL)==S_OK) { PWSTR pszUrl=NULL; if (SUCCEEDED(pSearchRoot->get_RootURL(&pszUrl))) { fwprintf(f,L"\t%s\r\n",pszUrl); CoTaskMemFree(pszUrl); } pSearchRoot=NULL; } fwprintf(f,L"\r\n"); } CComPtr<IEnumSearchScopeRules> pSearchRules; pSearchCrawlScopeManager->EnumerateScopeRules(&pSearchRules); if (pSearchRoots) { fwprintf(f,L"Search Rules:\r\n"); CComPtr<ISearchScopeRule> pSearchRule; while (pSearchRules->Next(1,&pSearchRule,NULL)==S_OK) { BOOL fIncluded=FALSE; pSearchRule->get_IsIncluded(&fIncluded); PWSTR pszUrl=NULL; if (SUCCEEDED(pSearchRule->get_PatternOrURL(&pszUrl))) { fwprintf(f,L"\t%s: %s\r\n",fIncluded?L"Include":L"Exclude",pszUrl); CoTaskMemFree(pszUrl); } pSearchRule=NULL; } fwprintf(f,L"\r\n"); } } } } } // programs fwprintf(f,L"\r\n\tInstalled Programs:\r\n"); std::set<CString,CompareStrings> programs; CComPtr<IShellItem> pPrograms; SHGetKnownFolderItem(FOLDERID_ChangeRemovePrograms,KF_FLAG_DEFAULT,NULL,IID_IShellItem,(void**)&pPrograms); if (pPrograms) { CComPtr<IEnumShellItems> pEnum; pPrograms->BindToHandler(NULL,BHID_EnumItems,IID_IEnumShellItems,(void**)&pEnum); CComPtr<IShellItem> pProgram; while (pEnum && (pProgram=NULL,pEnum->Next(1,&pProgram,NULL))==S_OK) { CComString pName; pProgram->GetDisplayName(SIGDN_NORMALDISPLAY,&pName); CString name=pName; CComQIPtr<IShellItem2> pProgram2=pProgram; if (pProgram2) { CComString pVersion; if (SUCCEEDED(pProgram2->GetString(PKEY_ProductVersion,&pVersion))) name+=L" ("+CString(pVersion)+L")"; } programs.insert(name); } } for (std::set<CString,CompareStrings>::const_iterator it=programs.begin();it!=programs.end();++it) fwprintf(f,L"\t\t%s\r\n",(const wchar_t*)(*it)); fwprintf(f,L"\r\nClassic Shell\r\n"); wchar_t csPath[_MAX_PATH]=L""; // classic shell version { CRegKey regKey; DWORD err=regKey.Open(HKEY_LOCAL_MACHINE,L"Software\\IvoSoft\\ClassicShell",KEY_READ|KEY_WOW64_64KEY); if (err!=ERROR_SUCCESS) { fwprintf(f,L"\tFailed to read HKLM\\Software\\IvoSoft\\ClassicShell - 0x%08X\r\n",err); } else { wchar_t language[100]=L""; ULONG size=_countof(language); if (regKey.QueryStringValue(L"DefaultLanguage",language,&size)==ERROR_SUCCESS) fwprintf(f,L"\tDefault language: '%s'\r\n",language); size=_countof(csPath); if (regKey.QueryStringValue(L"Path",csPath,&size)==ERROR_SUCCESS) { fwprintf(f,L"\tClassic Shell path: '%s'\r\n",csPath); PathRemoveBackslash(csPath); } DWORD val; if (regKey.QueryDWORDValue(L"Version",val)==ERROR_SUCCESS) fwprintf(f,L"\tClassic Shell version: %d.%d.%d\r\n",val>>24,(val>>16)&0xFF,val&0xFFFF); if (regKey.QueryDWORDValue(L"WinVersion",val)==ERROR_SUCCESS) fwprintf(f,L"\tWin version during installation: %d.%02d.%d\r\n",val>>24,(val>>16)&0xFF,val&0xFFFF); } } // language files fwprintf(f,L"\t%s:\r\n",csPath); if (csPath[0]) WriteFolder(f,csPath,2,true); { wchar_t path[_MAX_PATH]; Strcpy(path,_countof(path),L"%ALLUSERSPROFILE%\\ClassicShell"); DoEnvironmentSubst(path,_countof(path)); fwprintf(f,L"\t%s:\r\n",path); WriteFolder(f,path,2,true); } // installed components and settings wchar_t fname[_MAX_PATH]; Sprintf(fname,_countof(fname),L"%s\\ClassicExplorer32.dll",csPath); bool bClassicExplorer=GetFileAttributes(fname)!=INVALID_FILE_ATTRIBUTES; Sprintf(fname,_countof(fname),L"%s\\ClassicStartMenu.exe",csPath); bool bClassicMenu=GetFileAttributes(fname)!=INVALID_FILE_ATTRIBUTES; Sprintf(fname,_countof(fname),L"%s\\ClassicIE_32.exe",csPath); bool bClassicIE=GetFileAttributes(fname)!=INVALID_FILE_ATTRIBUTES; Sprintf(fname,_countof(fname),L"%s\\ClassicShellUpdate.exe",csPath); bool bClassicUpdate=GetFileAttributes(fname)!=INVALID_FILE_ATTRIBUTES; fwprintf(f,L"\r\nInstalled components:\r\n"); if (bClassicExplorer) { fwprintf(f,L" Classic Explorer\r\n"); WriteSettings(f,COMPONENT_EXPLORER); } if (bClassicMenu) { fwprintf(f,L" Classic Start Menu\r\n"); WriteSettings(f,COMPONENT_MENU); } if (bClassicIE) { fwprintf(f,L" Classic IE\r\n"); WriteSettings(f,COMPONENT_IE); } if (bClassicUpdate) { fwprintf(f,L" Classic Shell Update\r\n\r\n"); } fwprintf(f,L" Shared Settings\r\n"); WriteSettings(f,COMPONENT_SHARED); // check for disabled addons if (bClassicExplorer || bClassicIE) { fwprintf(f,L"Explorer addons:\r\n"); CString text; if (ReadRegistryValue(HKEY_CURRENT_USER,L"Software\\Microsoft\\Internet Explorer\\Main",L"Enable Browser Extensions",text)==ERROR_SUCCESS) fwprintf(f,L"\tEnable Browser Extensions (user): %s\r\n",(const wchar_t*)text); if (ReadRegistryValue(HKEY_LOCAL_MACHINE,L"Software\\Microsoft\\Internet Explorer\\Main",L"Enable Browser Extensions",text)==ERROR_SUCCESS) fwprintf(f,L"\tEnable Browser Extensions: %s\r\n",(const wchar_t*)text); if (ReadRegistryValue(HKEY_CURRENT_USER,L"Software\\Microsoft\\Internet Explorer\\Main",L"Isolation",text)==ERROR_SUCCESS) fwprintf(f,L"\tIsolation (user): %s\r\n",(const wchar_t*)text); if (ReadRegistryValue(HKEY_LOCAL_MACHINE,L"Software\\Microsoft\\Internet Explorer\\Main",L"Isolation",text)==ERROR_SUCCESS) fwprintf(f,L"\tIsolation: %s\r\n",(const wchar_t*)text); } if (bClassicExplorer) { DWORD flags; if (ReadRegistryValue(HKEY_CURRENT_USER,L"Software\\Microsoft\\Windows\\CurrentVersion\\Ext\\Settings\\{553891B7-A0D5-4526-BE18-D3CE461D6310}",L"Flags",flags)==ERROR_SUCCESS) fwprintf(f,L"\tExplorerBand flags: 0x%08X\r\n",flags); CString policy; if (ReadRegistryValue(HKEY_LOCAL_MACHINE,L"Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Ext\\CLSID",L"{553891B7-A0D5-4526-BE18-D3CE461D6310}",policy)==ERROR_SUCCESS) fwprintf(f,L"\tExplorerBand policy: %s\r\n",(const wchar_t*)policy); if (ReadRegistryValue(HKEY_CURRENT_USER,L"Software\\Microsoft\\Windows\\CurrentVersion\\Ext\\Settings\\{449D0D6E-2412-4E61-B68F-1CB625CD9E52}",L"Flags",flags)==ERROR_SUCCESS) fwprintf(f,L"\tExplorerBHO flags: 0x%08X\r\n",flags); if (ReadRegistryValue(HKEY_LOCAL_MACHINE,L"Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Ext\\CLSID",L"{449D0D6E-2412-4E61-B68F-1CB625CD9E52}",policy)==ERROR_SUCCESS) fwprintf(f,L"\tExplorerBHO policy: %s\r\n",(const wchar_t*)policy); } if (bClassicIE) { DWORD flags; CString policy; if (ReadRegistryValue(HKEY_CURRENT_USER,L"Software\\Microsoft\\Windows\\CurrentVersion\\Ext\\Settings\\{EA801577-E6AD-4BD5-8F71-4BE0154331A4}",L"Flags",flags)==ERROR_SUCCESS) fwprintf(f,L"\tClassicIE flags: 0x%08X\r\n",flags); if (ReadRegistryValue(HKEY_LOCAL_MACHINE,L"Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Ext\\CLSID",L"{EA801577-E6AD-4BD5-8F71-4BE0154331A4}",policy)==ERROR_SUCCESS) fwprintf(f,L"\tClassicIE policy: %s\r\n",(const wchar_t*)policy); } if (bClassicExplorer || bClassicIE) fwprintf(f,L"\r\n"); if (bClassicMenu) { if (HIWORD(winVer)>=WIN_VER_WIN8) { CString guid; LONG res=ReadRegistryValue(HKEY_CLASSES_ROOT,L"CLSID\\{ECD4FC4D-521C-11D0-B792-00A0C90312E1}\\TreatAs",NULL,guid); if (res!=ERROR_SUCCESS) fwprintf(f,L"TreatAs: 0x%08X\r\n",res); else { if (guid.IsEmpty()) guid=L"(empty)"; fwprintf(f,L"TreatAs: %s%s\r\n",(const wchar_t*)guid,_wcsicmp(guid,L"{D3214FBB-3CA1-406a-B3E8-3EB7C393A15E}")==0?L" (correct)":L" (wrong)"); } CString emulation; res=ReadRegistryValue(HKEY_CLASSES_ROOT,L"CLSID\\{D3214FBB-3CA1-406A-B3E8-3EB7C393A15E}",NULL,emulation); if (res!=ERROR_SUCCESS) fwprintf(f,L"Emulation: 0x%08X\r\n",res); else { if (emulation.IsEmpty()) emulation=L"(empty)"; fwprintf(f,L"Emulation: %s%s\r\n",(const wchar_t*)emulation,_wcsicmp(emulation,L"StartMenuEmulation")==0?L" (correct)":L" (wrong)"); } CString server; res=ReadRegistryValue(HKEY_CLASSES_ROOT,L"CLSID\\{D3214FBB-3CA1-406A-B3E8-3EB7C393A15E}\\InprocServer32",NULL,server); if (res!=ERROR_SUCCESS) fwprintf(f,L"Server: 0x%08X\r\n",res); else { const wchar_t *state=L" (wrong)"; if (server.IsEmpty()) server=L"(empty)"; else if (GetFileAttributes(server)==INVALID_FILE_ATTRIBUTES) state=L" (missing file)"; else state=L" (correct)"; fwprintf(f,L"Server: %s%s\r\n",(const wchar_t*)server,state); } } } } static void WriteLogFileAdmin( FILE *f ) { fwprintf(f,L"\r\nServices:\r\n"); { CRegKey regKey; if (regKey.Open(HKEY_LOCAL_MACHINE,L"SYSTEM\\ControlSet001\\Control\\ServiceGroupOrder",KEY_READ|KEY_WOW64_64KEY)==ERROR_SUCCESS) WriteRegKey(f,regKey,1); SC_HANDLE hManager=OpenSCManager(NULL,NULL,SC_MANAGER_ENUMERATE_SERVICE); if (hManager) { const wchar_t *status[]={ L"", L"stopped", L"start pending", L"stop pending", L"running", L"continue pending", L"pause pending", L"paused", }; std::vector<BYTE> buf(256*1024); DWORD size=0, count=0, resume=0; std::map<CString,GroupInfo,CompareStrings> services; if (EnumServicesStatusEx(hManager,SC_ENUM_PROCESS_INFO,SERVICE_DRIVER|SERVICE_WIN32,SERVICE_STATE_ALL,&buf[0],(int)buf.size(),&size,&count,&resume,NULL)) { const ENUM_SERVICE_STATUS_PROCESS *pService=(ENUM_SERVICE_STATUS_PROCESS*)&buf[0]; for (DWORD i=0;i<count;i++,pService++) { DWORD idx=pService->ServiceStatusProcess.dwCurrentState; if (idx>=_countof(status)) idx=0; GroupInfo &info=services[pService->lpServiceName]; info.desc=pService->lpDisplayName; info.status=status[idx]; CString name; name.Format(L"SYSTEM\\ControlSet001\\services\\%s",pService->lpServiceName); ReadRegistryValue(HKEY_LOCAL_MACHINE,name,L"Group",info.group); } } CloseServiceHandle(hManager); for (std::map<CString,GroupInfo,CompareStrings>::const_iterator it=services.begin();it!=services.end();++it) if (it->second.group.IsEmpty()) fwprintf(f,L"\t%s (%s): %s\r\n",(const wchar_t*)it->first,(const wchar_t*)it->second.desc,it->second.status); else fwprintf(f,L"\t%s (%s): %s (%s)\r\n",(const wchar_t*)it->first,(const wchar_t*)it->second.desc,it->second.status,(const wchar_t*)it->second.group); } } HANDLE hToken; if (OpenProcessToken(GetCurrentProcess(),TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY,&hToken)) { TOKEN_PRIVILEGES tp={1}; if (LookupPrivilegeValue(NULL,L"SeDebugPrivilege",&tp.Privileges[0].Luid)) tp.Privileges[0].Attributes=SE_PRIVILEGE_ENABLED; AdjustTokenPrivileges(hToken,FALSE,&tp,sizeof(TOKEN_PRIVILEGES),NULL,NULL); CloseHandle(hToken); } // processes fwprintf(f,L"\r\nProcesses:\r\n"); std::vector<DWORD> explorers; std::vector<DWORD> menus; { DWORD processes[1024]; DWORD cbNeeded; if (EnumProcesses(processes,sizeof(processes),&cbNeeded)) { int count=cbNeeded/sizeof(DWORD); std::sort(processes,processes+count); for (int i=0;i<count;i++) { HANDLE hProcess=OpenProcess(PROCESS_QUERY_INFORMATION,FALSE,processes[i]); if (!hProcess) hProcess=OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION,FALSE,processes[i]); if (hProcess) { wchar_t fname[_MAX_PATH]; DWORD size=_countof(fname); if (QueryFullProcessImageName(hProcess,0,fname,&size)) { const wchar_t *name=PathFindFileName(fname); if (_wcsicmp(name,L"explorer.exe")==0) { explorers.push_back(processes[i]); } else if (_wcsicmp(name,L"ClassicStartMenu.exe")==0) { menus.push_back(processes[i]); } } else fname[0]=0; fwprintf(f,L"\t%5d, %s",processes[i],fname); HANDLE hToken; const wchar_t *level=L"Unknown"; if (OpenProcessToken(hProcess,TOKEN_QUERY|TOKEN_QUERY_SOURCE,&hToken)) { DWORD dwLengthNeeded; if (!GetTokenInformation(hToken,TokenIntegrityLevel,NULL,0,&dwLengthNeeded)) { TOKEN_MANDATORY_LABEL *pTIL=(TOKEN_MANDATORY_LABEL*)malloc(dwLengthNeeded); if (pTIL) { if (GetTokenInformation(hToken,TokenIntegrityLevel,pTIL,dwLengthNeeded,&dwLengthNeeded)) { DWORD dwIntegrityLevel=*GetSidSubAuthority(pTIL->Label.Sid,(DWORD)(UCHAR)(*GetSidSubAuthorityCount(pTIL->Label.Sid)-1)); if (dwIntegrityLevel>=SECURITY_MANDATORY_SYSTEM_RID) level=L"System"; else if (dwIntegrityLevel>=SECURITY_MANDATORY_HIGH_RID) level=L"High"; else if (dwIntegrityLevel>=SECURITY_MANDATORY_MEDIUM_RID) level=L"Medium"; else level=L"Low"; } free(pTIL); } } CloseHandle(hToken); } fwprintf(f,L" (%s integrity level)\r\n",level); CloseHandle(hProcess); } } } } HWND progWin=FindWindowEx(NULL,NULL,L"Progman",NULL); DWORD desktopId=0; if (progWin) GetWindowThreadProcessId(progWin,&desktopId); // interesting processes for (std::vector<DWORD>::const_iterator it=explorers.begin();it!=explorers.end();++it) { fwprintf(f,L"\r\nExplorer process: %d%s\r\n",*it,(*it==desktopId)?L" (desktop)":L""); HANDLE hProcess=OpenProcess(PROCESS_QUERY_INFORMATION|PROCESS_VM_READ,FALSE,*it); if (hProcess) { WriteProcessInfo(f,hProcess,1); CloseHandle(hProcess); } else fwprintf(f,L"\tFailed to get modules\r\n"); } for (std::vector<DWORD>::const_iterator it=menus.begin();it!=menus.end();++it) { fwprintf(f,L"\r\nClassicStartMenu process: %d\r\n",*it); HANDLE hProcess=OpenProcess(PROCESS_QUERY_INFORMATION|PROCESS_VM_READ,FALSE,*it); if (hProcess) { WriteProcessInfo(f,hProcess,1); CloseHandle(hProcess); } else fwprintf(f,L"\tFailed to get modules\r\n"); } } int SaveLogFile( const wchar_t *fname, bool bAdmin ) { FILE *f=NULL; if (_wfopen_s(&f,fname,bAdmin?L"ab":L"wb")!=0 || !f) return 1; fseek(f,0,SEEK_END); if (ftell(f)==0) fwrite(L"\xFEFF",2,1,f); CoInitialize(NULL); if (bAdmin) WriteLogFileAdmin(f); else WriteLogFile(f); fclose(f); if (!bAdmin) { wchar_t exe[_MAX_PATH]; GetModuleFileName(NULL,exe,_countof(exe)); wchar_t cmdLine[1024]; Sprintf(cmdLine,_countof(cmdLine),L"saveloga \"%s\"",fname); if ((intptr_t)ShellExecute(NULL,L"runas",exe,cmdLine,NULL,SW_SHOWNORMAL)<=32) { f=NULL; if (_wfopen_s(&f,fname,L"ab")==0 && f) { WriteLogFileAdmin(f); fclose(f); } } } CoUninitialize(); return 0; } bool ExtractUtility64( const wchar_t *fname, wchar_t *exe ) { FILE *f=NULL; if (_wfopen_s(&f,fname,L"wb")!=0 || !f) return false; fwprintf(f,L"\xFEFF"); HRSRC hResInfo=FindResource(g_hInstance,MAKEINTRESOURCE(1),L"FILE"); if (!hResInfo) { fwprintf(f,L"Error extracting ClassicShellUtility64.exe\r\n"); fclose(f); return false; } HGLOBAL hRes=LoadResource(g_hInstance,hResInfo); void *ptr=LockResource(hRes); DWORD size=SizeofResource(g_hInstance,hResInfo); bool res=false; Strcpy(exe,_MAX_PATH,L"%TEMP%\\ClassicShellUtility64.exe"); DoEnvironmentSubst(exe,_MAX_PATH); HANDLE h=CreateFile(exe,GENERIC_WRITE,0,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL); if (h) { DWORD q; res=(WriteFile(h,ptr,size,&q,NULL) && q==size); CloseHandle(h); } if (!res) fwprintf(f,L"Error saving %s\r\n",exe); fclose(f); return res; } static void ShowSaveLogFileInternal( void ) { // save log file wchar_t fname[_MAX_PATH]; fname[0]=0; OPENFILENAME ofn={sizeof(ofn)}; ofn.lpstrFilter=L"Text files (*.txt)\0*.txt\0"; ofn.nFilterIndex=1; ofn.lpstrFile=fname; ofn.nMaxFile=_MAX_PATH; ofn.lpstrTitle=L"Save log file"; ofn.lpstrDefExt=L".txt"; ofn.Flags=OFN_ENABLESIZING|OFN_EXPLORER|OFN_PATHMUSTEXIST|OFN_OVERWRITEPROMPT|OFN_HIDEREADONLY|OFN_NOCHANGEDIR; if (GetSaveFileName(&ofn)) { wchar_t exe[_MAX_PATH]; BOOL bWow64=FALSE; IsWow64Process(GetCurrentProcess(),&bWow64); if (bWow64) { if (!ExtractUtility64(fname,exe)) return; } else GetModuleFileName(NULL,exe,_countof(exe)); STARTUPINFO startupInfo={sizeof(startupInfo)}; PROCESS_INFORMATION processInfo; memset(&processInfo,0,sizeof(processInfo)); wchar_t cmdLine[1024]; Sprintf(cmdLine,_countof(cmdLine),L"%s savelog \"%s\"",PathFindFileName(exe),fname); if (CreateProcess(exe,cmdLine,NULL,NULL,FALSE,0,NULL,NULL,&startupInfo,&processInfo)) { CloseHandle(processInfo.hThread); WaitForSingleObject(processInfo.hProcess,INFINITE); CloseHandle(processInfo.hProcess); } } } void ShowSaveLogFile( void ) { CoInitialize(NULL); ShowSaveLogFileInternal(); CoUninitialize(); }
16,828
1,144
<reponame>yodaos-project/yodaos /* * (C) Copyright 2013 * <NAME>, DENX Software Engineering, <EMAIL>. * on behalf of ifm electronic GmbH * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ #include <stdio.h> #include <sys/mount.h> #include <unistd.h> #include <fcntl.h> #include <stdlib.h> #include <errno.h> #include "swupdate.h" #include "handler.h" #include "util.h" void raw_handler(void); void raw_filecopy_handler(void); static int install_raw_image(struct img_type *img, void __attribute__ ((__unused__)) *data) { int ret; int fdout; fdout = open(img->device, O_RDWR); if (fdout < 0) { TRACE("Device %s cannot be opened: %s", img->device, strerror(errno)); return -1; } ret = copyimage(&fdout, img, NULL); close(fdout); return ret; } static int install_raw_file(struct img_type *img, void __attribute__ ((__unused__)) *data) { char path[255]; int fdout; int ret = 0; int use_mount = (strlen(img->device) && strlen(img->filesystem)) ? 1 : 0; if (strlen(img->path) == 0) { ERROR("Missing path attribute"); return -1; } if (use_mount) { ret = mount(img->device, DATADST_DIR, img->filesystem, 0, NULL); if (ret) { ERROR("Device %s with filesystem %s cannot be mounted", img->device, img->filesystem); return -1; } if (snprintf(path, sizeof(path), "%s%s", DATADST_DIR, img->path) >= (int)sizeof(path)) { ERROR("Path too long: %s%s", DATADST_DIR, img->path); return -1; } } else { if (snprintf(path, sizeof(path), "%s", img->path) >= (int)sizeof(path)) { ERROR("Path too long: %s", img->path); return -1; } } TRACE("Installing file %s on %s\n", img->fname, path); fdout = openfileoutput(path); ret = copyimage(&fdout, img, NULL); if (ret< 0) { ERROR("Error copying extracted file\n"); } close(fdout); if (use_mount) { umount(DATADST_DIR); } return ret; } __attribute__((constructor)) void raw_handler(void) { register_handler("raw", install_raw_image, NULL); } __attribute__((constructor)) void raw_filecopy_handler(void) { register_handler("rawfile", install_raw_file, NULL); }
1,027
3,285
<gh_stars>1000+ /* Copyright 2020 The OneFlow Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "oneflow/core/graph/boxing/slice_boxing_sub_task_graph_builder.h" #include "oneflow/core/register/tensor_slice_view.h" #include "oneflow/core/common/balanced_splitter.h" #include "oneflow/core/graph/slice_boxing_task_node.h" #include "oneflow/core/graph/boxing/sub_task_graph_builder_util.h" #include "oneflow/core/job/nd_sbp_util.h" #include "oneflow/core/common/id_util.h" #include "oneflow/core/graph/id_serialization.h" #include "oneflow/core/device/stream_index.h" namespace oneflow { Maybe<SubTskGphBuilderStatus> SliceBoxingSubTskGphBuilder::Build( SubTskGphBuilderCtx* ctx, const std::vector<TaskNode*>& sorted_in_tasks, std::vector<TaskNode*>* sorted_out_tasks, std::vector<std::vector<TaskNode*>>* sorted_ctrl_tasks, const ParallelDesc& in_parallel_desc, const ParallelDesc& out_parallel_desc, const LogicalBlobId& lbi, const BlobDesc& logical_blob_desc, const cfg::SbpParallel& in_sbp_parallel, const cfg::SbpParallel& out_sbp_parallel, const Shape& time_shape) const { if (SubTskGphBuilderUtil::BlobHasDynamicShape(logical_blob_desc)) { return Error::BoxingNotSupportedError(); } if (SubTskGphBuilderUtil::HasEmptySliceIfSplit(in_parallel_desc.parallel_num(), in_sbp_parallel, logical_blob_desc)) { return Error::BoxingNotSupportedError(); } if (SubTskGphBuilderUtil::HasEmptySliceIfSplit(out_parallel_desc.parallel_num(), out_sbp_parallel, logical_blob_desc)) { return Error::BoxingNotSupportedError(); } if (!(SubTskGphBuilderUtil::IsBoxingS2B(in_sbp_parallel, out_sbp_parallel) || SubTskGphBuilderUtil::IsBoxingS2S(in_sbp_parallel, out_sbp_parallel) || SubTskGphBuilderUtil::IsBoxingP2S(in_sbp_parallel, out_sbp_parallel) || SubTskGphBuilderUtil::IsBoxingP2B(in_sbp_parallel, out_sbp_parallel) || SubTskGphBuilderUtil::IsBoxingB2S(in_sbp_parallel, out_sbp_parallel))) { return Error::BoxingNotSupportedError(); } const auto NewEdge = [&ctx]() -> TaskEdge* { return ctx->task_graph()->NewEdge(); }; const auto CreateSliceBoxingNode = [&ctx, &lbi](const ParallelDesc& pd, const int64_t parallel_id, const TensorSliceView& slice, SliceBoxingTaskMode mode) -> SliceBoxingTaskNode* { SliceBoxingTaskNode* node = ctx->task_graph()->NewNode<SliceBoxingTaskNode>(); const int64_t machine_id = CHECK_JUST(pd.MachineId4ParallelId(parallel_id)); int64_t dev_id = -1; if (pd.device_type() == DeviceType::kCPU) { dev_id = DeviceId::kCPUDeviceIndex; } else { dev_id = CHECK_JUST(pd.DeviceId4ParallelId(parallel_id)); } DeviceId device_id{static_cast<DeviceId::rank_t>(machine_id), pd.device_type(), static_cast<DeviceId::device_index_t>(dev_id)}; auto* stream_index_generator = Global<IDMgr>::Get()->GetStreamIndexGeneratorManager()->GetGenerator(device_id); auto stream_index = stream_index_generator->GenerateComputeStreamIndex(); int64_t thrd_id = SerializeStreamIdToInt64(StreamId{device_id, stream_index}); node->Init(lbi, slice, mode, machine_id, thrd_id); return node; }; const auto GetSliceCopyNode = [&CreateSliceBoxingNode, &NewEdge]( TaskNode* in_node, const TensorSliceView& in_slice, const ParallelDesc& in_pd, const int64_t in_id, const TensorSliceView& intersection) -> TaskNode* { if (in_slice == intersection) { return in_node; } else { SliceBoxingTaskNode* slice_copy_node = CreateSliceBoxingNode(in_pd, in_id, intersection, kSliceBoxingTaskModeCopy); slice_copy_node->ConnectToSrcNodeWithSlice(in_node, NewEdge(), in_slice); return slice_copy_node; } }; const auto BuildSubTaskGphS2B = [&ctx, &CreateSliceBoxingNode, &NewEdge, &lbi]( const ParallelDesc& in_pd, const ParallelDesc& out_pd, const cfg::SbpParallel& in_sbp, const cfg::SbpParallel& out_sbp, const BlobDesc& blob_desc, const std::vector<TaskNode*>& in_nodes, std::vector<TaskNode*>* out_nodes) { CHECK(SubTskGphBuilderUtil::IsBoxingS2B(in_sbp, out_sbp)); const std::vector<TensorSliceView> in_slices = GetTensorSliceView(in_pd.parallel_num(), in_sbp, blob_desc); const TensorSliceView& out_slice = GetBroadcastTensorSliceView(blob_desc); FOR_RANGE(int64_t, out_id, 0, out_pd.parallel_num()) { SliceBoxingTaskNode* out_node = CreateSliceBoxingNode(out_pd, out_id, out_slice, kSliceBoxingTaskModeCopy); FOR_RANGE(int64_t, in_id, 0, in_pd.parallel_num()) { const TensorSliceView& in_slice = in_slices.at(in_id); TaskNode* in_node = in_nodes.at(in_id); TaskNode* proxy_node = ctx->task_graph()->GetProxyNode( in_node, lbi, dynamic_cast<TaskNode*>(out_node)->MemZoneId121()); out_node->ConnectToSrcNodeWithSlice(proxy_node, NewEdge(), in_slice); } out_nodes->push_back(out_node); } }; const auto BuildSubTaskGphS2S = [&ctx, &lbi, &CreateSliceBoxingNode, &GetSliceCopyNode, &NewEdge]( const ParallelDesc& in_pd, const ParallelDesc& out_pd, const cfg::SbpParallel& in_sbp, const cfg::SbpParallel& out_sbp, const BlobDesc& blob_desc, const std::vector<TaskNode*>& in_nodes, std::vector<TaskNode*>* out_nodes) { CHECK(SubTskGphBuilderUtil::IsBoxingS2S(in_sbp, out_sbp)); const std::vector<TensorSliceView> in_slices = GetTensorSliceView(in_pd.parallel_num(), in_sbp, blob_desc); const std::vector<TensorSliceView> out_slices = GetTensorSliceView(out_pd.parallel_num(), out_sbp, blob_desc); for (int64_t out_id = 0; out_id < out_pd.parallel_num(); ++out_id) { const TensorSliceView& out_slice = out_slices.at(out_id); SliceBoxingTaskNode* out_node = CreateSliceBoxingNode(out_pd, out_id, out_slice, kSliceBoxingTaskModeCopy); for (int64_t in_id = 0; in_id < in_pd.parallel_num(); ++in_id) { const TensorSliceView& in_slice = in_slices.at(in_id); const TensorSliceView& intersection = out_slice.Intersect(in_slice); if (intersection.IsEmpty()) { continue; } TaskNode* in_node = in_nodes.at(in_id); TaskNode* slice_copy_node = GetSliceCopyNode(in_node, in_slice, in_pd, in_id, intersection); TaskNode* proxy_node = ctx->task_graph()->GetProxyNode( slice_copy_node, lbi, dynamic_cast<TaskNode*>(out_node)->MemZoneId121()); out_node->ConnectToSrcNodeWithSlice(proxy_node, NewEdge(), intersection); } out_nodes->push_back(out_node); } }; const auto BuildSubTaskGphP2S = [&ctx, &lbi, &CreateSliceBoxingNode, &GetSliceCopyNode, &NewEdge]( const ParallelDesc& in_pd, const ParallelDesc& out_pd, const cfg::SbpParallel& in_sbp, const cfg::SbpParallel& out_sbp, const BlobDesc& blob_desc, const std::vector<TaskNode*>& in_nodes, std::vector<TaskNode*>* out_nodes) { CHECK(SubTskGphBuilderUtil::IsBoxingP2S(in_sbp, out_sbp)); const TensorSliceView& in_slice = GetBroadcastTensorSliceView(blob_desc); const std::vector<TensorSliceView> out_slices = GetTensorSliceView(out_pd.parallel_num(), out_sbp, blob_desc); for (int64_t out_id = 0; out_id < out_pd.parallel_num(); ++out_id) { const TensorSliceView& out_slice = out_slices.at(out_id); SliceBoxingTaskNode* out_node = CreateSliceBoxingNode(out_pd, out_id, out_slice, kSliceBoxingTaskModeAdd); for (int64_t in_id = 0; in_id < in_pd.parallel_num(); ++in_id) { const TensorSliceView& intersection = out_slice.Intersect(in_slice); if (intersection.IsEmpty()) { continue; } TaskNode* in_node = in_nodes.at(in_id); TaskNode* slice_copy_node = GetSliceCopyNode(in_node, in_slice, in_pd, in_id, intersection); TaskNode* proxy_node = ctx->task_graph()->GetProxyNode( slice_copy_node, lbi, dynamic_cast<TaskNode*>(out_node)->MemZoneId121()); out_node->ConnectToSrcNodeWithSlice(proxy_node, NewEdge(), intersection); } out_nodes->push_back(out_node); } }; const auto BuildSubTaskGphP2B = [&ctx, &lbi, &CreateSliceBoxingNode, &NewEdge]( const ParallelDesc& in_pd, const ParallelDesc& out_pd, const cfg::SbpParallel& in_sbp, const cfg::SbpParallel& out_sbp, const BlobDesc& blob_desc, const std::vector<TaskNode*>& in_nodes, std::vector<TaskNode*>* out_nodes) { CHECK(SubTskGphBuilderUtil::IsBoxingP2B(in_sbp, out_sbp)); const TensorSliceView& slice = GetBroadcastTensorSliceView(blob_desc); for (int64_t out_id = 0; out_id < out_pd.parallel_num(); ++out_id) { SliceBoxingTaskNode* out_node = CreateSliceBoxingNode(out_pd, out_id, slice, kSliceBoxingTaskModeAdd); for (int64_t in_id = 0; in_id < in_pd.parallel_num(); ++in_id) { TaskNode* in_node = in_nodes.at(in_id); TaskNode* proxy_node = ctx->task_graph()->GetProxyNode( in_node, lbi, dynamic_cast<TaskNode*>(out_node)->MemZoneId121()); out_node->ConnectToSrcNodeWithSlice(proxy_node, NewEdge(), slice); } out_nodes->push_back(out_node); } }; const auto BuildSubTaskGphB2S = [&ctx, &lbi, &CreateSliceBoxingNode, &NewEdge]( const ParallelDesc& in_pd, const ParallelDesc& out_pd, const cfg::SbpParallel& in_sbp, const cfg::SbpParallel& out_sbp, const BlobDesc& blob_desc, const std::vector<TaskNode*>& in_nodes, std::vector<TaskNode*>* out_nodes) { CHECK(SubTskGphBuilderUtil::IsBoxingB2S(in_sbp, out_sbp)); const TensorSliceView& in_slice = GetBroadcastTensorSliceView(blob_desc); const std::vector<TensorSliceView> out_slices = GetTensorSliceView(out_pd.parallel_num(), out_sbp, blob_desc); FOR_RANGE(int64_t, out_id, 0, out_pd.parallel_num()) { const TensorSliceView& out_slice = out_slices.at(out_id); const int64_t nearest_idx = SubTskGphBuilderUtil::FindNearestSrcParallelId(in_pd, out_pd, out_id); TaskNode* in_node = in_nodes.at(nearest_idx); SliceBoxingTaskNode* slice_node = CreateSliceBoxingNode(in_pd, nearest_idx, out_slice, kSliceBoxingTaskModeCopy); slice_node->ConnectToSrcNodeWithSlice(in_node, NewEdge(), in_slice); TaskNode* out_node = ctx->task_graph()->GetProxyNode(slice_node, lbi, out_pd, out_id); out_nodes->push_back(out_node); } }; std::string comment; if (SubTskGphBuilderUtil::IsBoxingS2B(in_sbp_parallel, out_sbp_parallel)) { BuildSubTaskGphS2B(in_parallel_desc, out_parallel_desc, in_sbp_parallel, out_sbp_parallel, logical_blob_desc, sorted_in_tasks, sorted_out_tasks); comment = "BuildSubTaskGphS2B"; } else if (SubTskGphBuilderUtil::IsBoxingS2S(in_sbp_parallel, out_sbp_parallel)) { BuildSubTaskGphS2S(in_parallel_desc, out_parallel_desc, in_sbp_parallel, out_sbp_parallel, logical_blob_desc, sorted_in_tasks, sorted_out_tasks); comment = "BuildSubTaskGphS2S"; } else if (SubTskGphBuilderUtil::IsBoxingP2S(in_sbp_parallel, out_sbp_parallel)) { BuildSubTaskGphP2S(in_parallel_desc, out_parallel_desc, in_sbp_parallel, out_sbp_parallel, logical_blob_desc, sorted_in_tasks, sorted_out_tasks); comment = "BuildSubTaskGphP2S"; } else if (SubTskGphBuilderUtil::IsBoxingP2B(in_sbp_parallel, out_sbp_parallel)) { if (logical_blob_desc.shape().elem_cnt() < out_parallel_desc.parallel_num()) { BuildSubTaskGphP2B(in_parallel_desc, out_parallel_desc, in_sbp_parallel, out_sbp_parallel, logical_blob_desc, sorted_in_tasks, sorted_out_tasks); comment = "BuildSubTaskGphP2B"; } else { BlobDesc flat_blob_desc(logical_blob_desc.data_type()); flat_blob_desc.mut_shape() = Shape({logical_blob_desc.shape().elem_cnt()}); std::vector<TaskNode*> middle_nodes; cfg::SbpParallel middle_sbp; middle_sbp.mutable_split_parallel()->set_axis(0); BuildSubTaskGphP2S(in_parallel_desc, out_parallel_desc, in_sbp_parallel, middle_sbp, flat_blob_desc, sorted_in_tasks, &middle_nodes); BuildSubTaskGphS2B(out_parallel_desc, out_parallel_desc, middle_sbp, out_sbp_parallel, flat_blob_desc, middle_nodes, sorted_out_tasks); comment = "BuildSubTaskGphP2S->BuildSubTaskGphS2B"; for (TaskNode* out_node : *sorted_out_tasks) { auto* slice_boxing_node = dynamic_cast<SliceBoxingTaskNode*>(out_node); CHECK_NOTNULL(slice_boxing_node); slice_boxing_node->SetOutShape(logical_blob_desc.shape()); } } } else if (SubTskGphBuilderUtil::IsBoxingB2S(in_sbp_parallel, out_sbp_parallel)) { BuildSubTaskGphB2S(in_parallel_desc, out_parallel_desc, in_sbp_parallel, out_sbp_parallel, logical_blob_desc, sorted_in_tasks, sorted_out_tasks); comment = "BuildSubTaskGphB2S"; } else { UNIMPLEMENTED(); } return TRY(BuildSubTskGphBuilderStatus("SliceBoxingSubTskGphBuilder", comment)); } } // namespace oneflow
6,624
310
{ "name": "MKH 30", "description": "A condenser microphone.", "url": "https://en-us.sennheiser.com/studio-condenser-microphone-soloists-instrument-mkh-30-p48" }
67
2,151
/* * Copyright (C) Research In Motion Limited 2010. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "third_party/blink/renderer/core/layout/svg/svg_resources_cycle_solver.h" #include "third_party/blink/renderer/core/layout/svg/layout_svg_resource_container.h" #include "third_party/blink/renderer/core/layout/svg/svg_resources.h" #include "third_party/blink/renderer/core/layout/svg/svg_resources_cache.h" namespace blink { SVGResourcesCycleSolver::SVGResourcesCycleSolver(LayoutObject& layout_object) : layout_object_(layout_object) { if (layout_object.IsSVGResourceContainer()) active_resources_.insert(ToLayoutSVGResourceContainer(&layout_object)); } SVGResourcesCycleSolver::~SVGResourcesCycleSolver() = default; class ScopedTraversalPath { public: typedef SVGResourcesCycleSolver::ResourceSet ResourceSet; ScopedTraversalPath(ResourceSet& active_set) : active_set_(active_set), resource_(nullptr) {} ~ScopedTraversalPath() { if (resource_) active_set_.erase(resource_); } bool Enter(LayoutSVGResourceContainer* resource) { if (!active_set_.insert(resource).is_new_entry) return false; resource_ = resource; return true; } private: ResourceSet& active_set_; LayoutSVGResourceContainer* resource_; }; bool SVGResourcesCycleSolver::TraverseResourceContainer( LayoutSVGResourceContainer* resource) { // If we've traversed this sub-graph before and no cycles were observed, then // reuse that result. if (dag_cache_.Contains(resource)) return false; ScopedTraversalPath scope(active_resources_); if (!scope.Enter(resource)) return true; LayoutObject* node = resource; while (node) { // Skip subtrees which are themselves resources. (They will be // processed - if needed - when they are actually referenced.) if (node != resource && node->IsSVGResourceContainer()) { node = node->NextInPreOrderAfterChildren(resource); continue; } if (TraverseResources(*node)) return true; node = node->NextInPreOrder(resource); } // No cycles found in (or from) this resource. Add it to the "DAG cache". dag_cache_.insert(resource); return false; } bool SVGResourcesCycleSolver::TraverseResources(LayoutObject& layout_object) { SVGResources* resources = SVGResourcesCache::CachedResourcesForLayoutObject(layout_object); return resources && TraverseResources(resources); } bool SVGResourcesCycleSolver::TraverseResources(SVGResources* resources) { // Fetch all the referenced resources. ResourceSet local_resources; resources->BuildSetOfResources(local_resources); // This performs a depth-first search for a back-edge in all the // (potentially disjoint) graphs formed by the referenced resources. for (auto* local_resource : local_resources) { if (TraverseResourceContainer(local_resource)) return true; } return false; } bool SVGResourcesCycleSolver::FindCycle( LayoutSVGResourceContainer* start_node) { DCHECK(active_resources_.IsEmpty() || (active_resources_.size() == 1 && active_resources_.Contains( ToLayoutSVGResourceContainer(&layout_object_)))); return TraverseResourceContainer(start_node); } } // namespace blink
1,246
398
/* * 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 io.joyrpc.util; /*- * #%L * joyrpc * %% * Copyright (C) 2019 joyrpc.io * %% * 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. * #L% */ import java.io.PrintWriter; import java.io.StringWriter; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.function.Predicate; /** * Title: 字符串操作工具类<br> */ public class StringUtils { /** * 按照逗号分号和空白字符分割 */ public static final Predicate<Character> SEMICOLON_COMMA_WHITESPACE = o -> { switch (o) { case ',': case ';': return true; default: return Character.isWhitespace(o); } }; /** * The empty String {@code ""}. * * @since 2.0 */ public static final String EMPTY = ""; // Empty checks //----------------------------------------------------------------------- /** * <p>Checks if a CharSequence is empty ("") or null.</p> * * <pre> * StringUtils.isEmpty(null) = true * StringUtils.isEmpty("") = true * StringUtils.isEmpty(" ") = false * StringUtils.isEmpty("bob") = false * StringUtils.isEmpty(" bob ") = false * </pre> * * <p>NOTE: This method changed in Lang version 2.0. * It no longer trims the CharSequence. * That functionality is available in isBlank().</p> * * @param cs the CharSequence to check, may be null * @return {@code true} if the CharSequence is empty or null * @since 3.0 Changed signature from isEmpty(String) to isEmpty(CharSequence) */ public static boolean isEmpty(CharSequence cs) { return cs == null || cs.length() == 0; } /** * <p>Checks if a CharSequence is not empty ("") and not null.</p> * * <pre> * StringUtils.isNotEmpty(null) = false * StringUtils.isNotEmpty("") = false * StringUtils.isNotEmpty(" ") = true * StringUtils.isNotEmpty("bob") = true * StringUtils.isNotEmpty(" bob ") = true * </pre> * * @param cs the CharSequence to check, may be null * @return {@code true} if the CharSequence is not empty and not null * @since 3.0 Changed signature from isNotEmpty(String) to isNotEmpty(CharSequence) */ public static boolean isNotEmpty(CharSequence cs) { return !isEmpty(cs); } /** * <p>Checks if a CharSequence is whitespace, empty ("") or null.</p> * * <pre> * StringUtils.isBlank(null) = true * StringUtils.isBlank("") = true * StringUtils.isBlank(" ") = true * StringUtils.isBlank("bob") = false * StringUtils.isBlank(" bob ") = false * </pre> * * @param cs the CharSequence to check, may be null * @return {@code true} if the CharSequence is null, empty or whitespace * @since 2.0 * @since 3.0 Changed signature from isBlank(String) to isBlank(CharSequence) */ public static boolean isBlank(CharSequence cs) { int len; if (cs == null || (len = cs.length()) == 0) { return true; } for (int i = 0; i < len; i++) { if (!Character.isWhitespace(cs.charAt(i))) { return false; } } return true; } /** * <p>Checks if a CharSequence is not empty (""), not null and not whitespace only.</p> * * <pre> * StringUtils.isNotBlank(null) = false * StringUtils.isNotBlank("") = false * StringUtils.isNotBlank(" ") = false * StringUtils.isNotBlank("bob") = true * StringUtils.isNotBlank(" bob ") = true * </pre> * * @param cs the CharSequence to check, may be null * @return {@code true} if the CharSequence is * not empty and not null and not whitespace * @since 2.0 * @since 3.0 Changed signature from isNotBlank(String) to isNotBlank(CharSequence) */ public static boolean isNotBlank(CharSequence cs) { return !isBlank(cs); } /** * <pre> * StringUtils.trim(null) = null * StringUtils.trim("") = "" * StringUtils.trim(" ") = "" * StringUtils.trim("abc") = "abc" * StringUtils.trim(" abc ") = "abc" * </pre> * * @param str the String to be trimmed, may be null * @return the trimmed string, {@code null} if null String input */ public static String trim(final String str) { return str == null ? null : str.trim(); } /** * <pre> * StringUtils.trimToNull(null) = null * StringUtils.trimToNull("") = null * StringUtils.trimToNull(" ") = null * StringUtils.trimToNull("abc") = "abc" * StringUtils.trimToNull(" abc ") = "abc" * </pre> * * @param str the String to be trimmed, may be null * @return the trimmed String, * {@code null} if only chars &lt;= 32, empty or null String input * @since 2.0 */ public static String trimToNull(final String str) { String ts = trim(str); return isEmpty(ts) ? null : ts; } /** * <pre> * StringUtils.trimToEmpty(null) = "" * StringUtils.trimToEmpty("") = "" * StringUtils.trimToEmpty(" ") = "" * StringUtils.trimToEmpty("abc") = "abc" * StringUtils.trimToEmpty(" abc ") = "abc" * </pre> * * @param str the String to be trimmed, may be null * @return the trimmed String, or an empty String if {@code null} input * @since 2.0 */ public static String trimToEmpty(final String str) { return str == null ? EMPTY : str.trim(); } /** * 分割字符 * * @param source * @param ch * @return */ public static String[] split(final String source, final char ch) { return split(source, o -> o.charValue() == ch); } /** * 分割字符 * * @param source * @param predicate * @return */ public static String[] split(final String source, final Predicate<Character> predicate) { if (source == null) { return null; } int start = -1; int end = -1; char ch; LinkedList<String> parts = new LinkedList<>(); int length = source.length(); //遍历字符 for (int i = 0; i < length; i++) { ch = source.charAt(i); //满足分割符号 if (predicate.test(ch)) { //前面有字符片段 if (start >= 0) { parts.add(source.substring(start, end + 1)); start = -1; end = -1; } } else { if (start == -1) { start = i; } end = i; } } if (start >= 0) { parts.add(source.substring(start, length)); } if (parts.isEmpty()) { return new String[0]; } return parts.toArray(new String[parts.size()]); } /** * 按照字符串分割 * * @param value * @param delimiter * @return */ public static String[] split(final String value, final String delimiter) { if (delimiter == null || delimiter.isEmpty()) { return split(value, ','); } else if (delimiter.length() == 1) { return split(value, delimiter.charAt(0)); } List<String> parts = new LinkedList<String>(); int length = value.length(); int maxPos = delimiter.length() - 1; int start = 0; int pos = 0; int end = 0; for (int i = 0; i < length; i++) { if (value.charAt(i) == delimiter.charAt(pos)) { if (pos++ == maxPos) { if (end > start) { parts.add(value.substring(start, end + 1)); } pos = 0; start = i + 1; } } else { end = i; } } if (start < length) { parts.add(value.substring(start, length)); } if (parts.isEmpty()) { return new String[0]; } return parts.toArray(new String[parts.size()]); } /** * 连接字符串数组 * * @param strings 字符串数组 * @param separator 分隔符 * @return 按分隔符分隔的字符串 */ public static String join(String[] strings, String separator) { if (strings == null || strings.length == 0) { return EMPTY; } StringBuilder sb = new StringBuilder(); for (String string : strings) { if (isNotBlank(string)) { sb.append(string).append(separator); } } return sb.length() > 0 ? sb.substring(0, sb.length() - separator.length()) : StringUtils.EMPTY; } /** * 对象转string * * @param o 对象 * @return 不为null执行toString方法 */ public static String toNullString(Object o) { return o != null ? o.toString() : null; } /** * 返回堆栈信息(e.printStackTrace()的内容) * * @param e Throwable * @return 异常堆栈信息 */ public static String toString(final Throwable e) { if (e == null) { return null; } StringWriter writer = new StringWriter(1024); PrintWriter pw = new PrintWriter(writer); e.printStackTrace(pw); pw.flush(); return writer.toString(); } public static String toSimpleString(final Throwable e) { if (e == null) { return null; } StringBuilder sb = new StringBuilder(); Throwable err = null; do { if (err == null) { err = e; } else { err = err.getCause(); sb.append(". Caused by "); } sb.append(err.getClass().getName()).append(":").append(err.getMessage()); } while (err.getCause() != null); return sb.toString(); } /** * String 数组转为Map * * @param pairs * @return */ public static Map<String, String> toMap(final String... pairs) { if (pairs != null && pairs.length > 0 && pairs.length % 2 != 0) { throw new IllegalArgumentException("the parameters must be paired."); } Map<String, String> parameters = new HashMap<String, String>(); if (pairs != null && pairs.length > 0) { for (int i = 0; i < pairs.length; i = i + 2) { parameters.put(pairs[i], pairs[i + 1]); } } return parameters; } }
5,745
446
/* ======================================== * SpatializeDither - SpatializeDither.h * Copyright (c) 2016 airwindows, All rights reserved * ======================================== */ #ifndef __SpatializeDither_H #include "SpatializeDither.h" #endif void SpatializeDither::processReplacing(float **inputs, float **outputs, VstInt32 sampleFrames) { float* in1 = inputs[0]; float* in2 = inputs[1]; float* out1 = outputs[0]; float* out2 = outputs[1]; double contingentRnd; double absSample; double contingent; double randyConstant = 1.61803398874989484820458683436563811772030917980576; double omegaConstant = 0.56714329040978387299996866221035554975381578718651; double expConstant = 0.06598803584531253707679018759684642493857704825279; int processing = (VstInt32)( A * 1.999 ); bool highres = false; if (processing == 1) highres = true; float scaleFactor; if (highres) scaleFactor = 8388608.0; else scaleFactor = 32768.0; float derez = B; if (derez > 0.0) scaleFactor *= pow(1.0-derez,6); if (scaleFactor < 0.0001) scaleFactor = 0.0001; float outScale = scaleFactor; if (outScale < 8.0) outScale = 8.0; while (--sampleFrames >= 0) { long double inputSampleL = *in1; long double inputSampleR = *in2; if (fabs(inputSampleL)<1.18e-37) inputSampleL = fpd * 1.18e-37; fpd ^= fpd << 13; fpd ^= fpd >> 17; fpd ^= fpd << 5; if (fabs(inputSampleR)<1.18e-37) inputSampleR = fpd * 1.18e-37; fpd ^= fpd << 13; fpd ^= fpd >> 17; fpd ^= fpd << 5; inputSampleL *= scaleFactor; inputSampleR *= scaleFactor; //0-1 is now one bit, now we dither if (inputSampleL > 0) inputSampleL += 0.383; if (inputSampleL < 0) inputSampleL -= 0.383; if (inputSampleR > 0) inputSampleR += 0.383; if (inputSampleR < 0) inputSampleR -= 0.383; //adjusting to permit more information drug outta the noisefloor contingentRnd = (((rand()/(double)RAND_MAX)+(rand()/(double)RAND_MAX))-1.0) * randyConstant; //produce TPDF dist, scale contingentRnd -= contingentErrL*omegaConstant; //include err absSample = fabs(inputSampleL); contingentErrL = absSample - floor(absSample); //get next err contingent = contingentErrL * 2.0; //scale of quantization levels if (contingent > 1.0) contingent = ((-contingent+2.0)*omegaConstant) + expConstant; else contingent = (contingent * omegaConstant) + expConstant; //zero is next to a quantization level, one is exactly between them if (flip) contingentRnd = (contingentRnd * (1.0-contingent)) + contingent + 0.5; else contingentRnd = (contingentRnd * (1.0-contingent)) - contingent + 0.5; inputSampleL += (contingentRnd * contingent); //Contingent Dither inputSampleL = floor(inputSampleL); contingentRnd = (((rand()/(double)RAND_MAX)+(rand()/(double)RAND_MAX))-1.0) * randyConstant; //produce TPDF dist, scale contingentRnd -= contingentErrR*omegaConstant; //include err absSample = fabs(inputSampleR); contingentErrR = absSample - floor(absSample); //get next err contingent = contingentErrR * 2.0; //scale of quantization levels if (contingent > 1.0) contingent = ((-contingent+2.0)*omegaConstant) + expConstant; else contingent = (contingent * omegaConstant) + expConstant; //zero is next to a quantization level, one is exactly between them if (flip) contingentRnd = (contingentRnd * (1.0-contingent)) + contingent + 0.5; else contingentRnd = (contingentRnd * (1.0-contingent)) - contingent + 0.5; inputSampleR += (contingentRnd * contingent); //Contingent Dither inputSampleR = floor(inputSampleR); //note: this does not dither for values exactly the same as 16 bit values- //which forces the dither to gate at 0.0. It goes to digital black, //and does a teeny parallel-compression thing when almost at digital black. flip = !flip; inputSampleL /= outScale; inputSampleR /= outScale; *out1 = inputSampleL; *out2 = inputSampleR; *in1++; *in2++; *out1++; *out2++; } } void SpatializeDither::processDoubleReplacing(double **inputs, double **outputs, VstInt32 sampleFrames) { double* in1 = inputs[0]; double* in2 = inputs[1]; double* out1 = outputs[0]; double* out2 = outputs[1]; double contingentRnd; double absSample; double contingent; double randyConstant = 1.61803398874989484820458683436563811772030917980576; double omegaConstant = 0.56714329040978387299996866221035554975381578718651; double expConstant = 0.06598803584531253707679018759684642493857704825279; int processing = (VstInt32)( A * 1.999 ); bool highres = false; if (processing == 1) highres = true; float scaleFactor; if (highres) scaleFactor = 8388608.0; else scaleFactor = 32768.0; float derez = B; if (derez > 0.0) scaleFactor *= pow(1.0-derez,6); if (scaleFactor < 0.0001) scaleFactor = 0.0001; float outScale = scaleFactor; if (outScale < 8.0) outScale = 8.0; while (--sampleFrames >= 0) { long double inputSampleL = *in1; long double inputSampleR = *in2; if (fabs(inputSampleL)<1.18e-43) inputSampleL = fpd * 1.18e-43; fpd ^= fpd << 13; fpd ^= fpd >> 17; fpd ^= fpd << 5; if (fabs(inputSampleR)<1.18e-43) inputSampleR = fpd * 1.18e-43; fpd ^= fpd << 13; fpd ^= fpd >> 17; fpd ^= fpd << 5; inputSampleL *= scaleFactor; inputSampleR *= scaleFactor; //0-1 is now one bit, now we dither if (inputSampleL > 0) inputSampleL += 0.383; if (inputSampleL < 0) inputSampleL -= 0.383; if (inputSampleR > 0) inputSampleR += 0.383; if (inputSampleR < 0) inputSampleR -= 0.383; //adjusting to permit more information drug outta the noisefloor contingentRnd = (((rand()/(double)RAND_MAX)+(rand()/(double)RAND_MAX))-1.0) * randyConstant; //produce TPDF dist, scale contingentRnd -= contingentErrL*omegaConstant; //include err absSample = fabs(inputSampleL); contingentErrL = absSample - floor(absSample); //get next err contingent = contingentErrL * 2.0; //scale of quantization levels if (contingent > 1.0) contingent = ((-contingent+2.0)*omegaConstant) + expConstant; else contingent = (contingent * omegaConstant) + expConstant; //zero is next to a quantization level, one is exactly between them if (flip) contingentRnd = (contingentRnd * (1.0-contingent)) + contingent + 0.5; else contingentRnd = (contingentRnd * (1.0-contingent)) - contingent + 0.5; inputSampleL += (contingentRnd * contingent); //Contingent Dither inputSampleL = floor(inputSampleL); contingentRnd = (((rand()/(double)RAND_MAX)+(rand()/(double)RAND_MAX))-1.0) * randyConstant; //produce TPDF dist, scale contingentRnd -= contingentErrR*omegaConstant; //include err absSample = fabs(inputSampleR); contingentErrR = absSample - floor(absSample); //get next err contingent = contingentErrR * 2.0; //scale of quantization levels if (contingent > 1.0) contingent = ((-contingent+2.0)*omegaConstant) + expConstant; else contingent = (contingent * omegaConstant) + expConstant; //zero is next to a quantization level, one is exactly between them if (flip) contingentRnd = (contingentRnd * (1.0-contingent)) + contingent + 0.5; else contingentRnd = (contingentRnd * (1.0-contingent)) - contingent + 0.5; inputSampleR += (contingentRnd * contingent); //Contingent Dither inputSampleR = floor(inputSampleR); //note: this does not dither for values exactly the same as 16 bit values- //which forces the dither to gate at 0.0. It goes to digital black, //and does a teeny parallel-compression thing when almost at digital black. flip = !flip; inputSampleL /= outScale; inputSampleR /= outScale; *out1 = inputSampleL; *out2 = inputSampleR; *in1++; *in2++; *out1++; *out2++; } }
2,976
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 _DXCANVAS_SPRITEHELPER_HXX #define _DXCANVAS_SPRITEHELPER_HXX #include <com/sun/star/rendering/XCustomSprite.hpp> #include <canvas/base/canvascustomspritehelper.hxx> #include <basegfx/point/b2dpoint.hxx> #include <basegfx/vector/b2isize.hxx> #include <basegfx/matrix/b2dhommatrix.hxx> #include "dx_spritecanvas.hxx" #include "dx_surfacebitmap.hxx" namespace dxcanvas { /* Definition of SpriteHelper class */ /** Helper class for canvas sprites. This class implements all sprite-related functionality, like that available on the XSprite interface. */ class SpriteHelper : public ::canvas::CanvasCustomSpriteHelper { public: /** Create sprite helper */ SpriteHelper(); /** Late-init the sprite helper @param rSpriteSize Size of the sprite @param rSpriteCanvas Sprite canvas this sprite is part of. Object stores ref-counted reference to it, thus, don't forget to pass on disposing()! @param rRenderModule rendermodule to use @param rSpriteSurface The surface of the sprite (not the DX texture, but the persistent target of content rendering) @param bShowSpriteBounds When true, little debug bound rects for sprites are shown */ void init( const ::com::sun::star::geometry::RealSize2D& rSpriteSize, const SpriteCanvasRef& rSpriteCanvas, const IDXRenderModuleSharedPtr& rRenderModule, const DXSurfaceBitmapSharedPtr rBitmap, bool bShowSpriteBounds ); void disposing(); /** Repaint sprite content via hardware to associated sprite canvas @param io_bSurfaceDirty Input/output parameter, whether the sprite content is dirty or not. If texture was updated, set to false */ void redraw( bool& io_bSurfaceDirty ) const; private: virtual ::basegfx::B2DPolyPolygon polyPolygonFromXPolyPolygon2D( ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XPolyPolygon2D >& xPoly ) const; /// Returns true, if the sprite _really_ needs redraw bool needRedraw() const; SpriteCanvasRef mpSpriteCanvas; DXSurfaceBitmapSharedPtr mpBitmap; mutable bool mbTextureDirty; // when true, texture needs update bool mbShowSpriteBounds; // when true, debug bound rect for sprites is shown }; } #endif /* _DXCANVAS_SPRITEHELPER_HXX */
1,449
1,489
[ "11 foot 8 Bridge", "1984 Summer Olympics", "2 + 2 = 5", "2005 NFL season", "401(k)", "4′33″", "<NAME>", "<NAME>", "Alien hand syndrome", "<NAME>", "Andromeda Galaxy", "Animals in space", "Apple Inc.", "Archipelago", "Automation", "<NAME>", "<NAME>", "Beale ciphers", "Belphegor's prime", "Bible", "Bitcoin", "Black hole", "Bloop", "Boring, Oregon", "Brave New World", "Brooklyn Nets", "Buzz Lightyear", "CNN", "Calculator spelling", "Cards Against Humanity", "Centralia, Pennsylvania", "<NAME>", "Cicada 3301", "Cleopatra", "Coca-Cola", "Coldplay", "Colors of noise", "Coral Castle", "<NAME>", "Delta Air Lines", "Denver", "<NAME>", "<NAME>", "<NAME>", "Empire State Building", "Empire State of Mind", "Exploding animal", "False memory", "Fascism", "Fasting", "Firebase", "Five-second rule", "FiveThirtyEight", "Flat Earth", "Fluid dynamics", "Gatorade", "<NAME>", "Genetics", "<NAME>", "<NAME>", "Gerrymandering", "Google", "Googleplex", "Gravity hill", "Gymnobela rotundata", "<NAME>", "<NAME>", "Hell, Norway", "<NAME>", "Homo sapiens", "Iliad", "Inception", "Internationalization", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "Jesus", "<NAME>", "Kool-Aid", "Krakatoa", "<NAME>", "<NAME>", "List of WWE personnel", "List of common misconceptions", "List of future tallest buildings", "List of lists of lists", "List of paradoxes", "Longest word in English", "Louisiana Purchase", "Lucky Charms", "<NAME>", "Manchester United F.C.", "Manifest destiny", "<NAME>", "<NAME>", "<NAME>", "McDonald's", "Megatsunami", "<NAME>", "Memento (film)", "Meta", "Metta World Peace", "Mitochondrial Eve", "Moby-Dick", "Mole Day", "Monty Hall problem", "<NAME>", "Mutual assured destruction", "Möbius strip", "Names of large numbers", "New car smell", "Nibiru cataclysm", "Nineteen Eighty-Four", "Notre Dame Fighting Irish", "Null Island", "Oh-My-God particle", "<NAME>", "Persephone", "Philadelphia Eagles", "Philanthropy", "Pittsburgh Steelers", "Placeholder name", "Porcelain", "Porsche", "Portable toilet", "Precipitation", "Rain of animals", "<NAME>", "<NAME>", "Scouting in the Antarctic", "Sex in space", "Shark Tank", "<NAME>", "Shit happens", "Signed zero", "Spaghetti sort", "Spaghettification", "St. Louis Cardinals", "Subliminal stimuli", "Superman", "Tautology (logic)", "Tesla", "Thailand", "The Hunger Games", "<NAME>oods", "Timeline of the far future", "Tinder", "Tokyo Sexwale", "Unobtainium", "Utsuro-bune", "V for Vendetta", "Vela Incident", "Venus flytrap", "WALL-E", "Waffle House Index", "Walmart", "War of 1812", "Westworld (TV series)", "Wikipedia", "<NAME>", "Winnie-the-Pooh", "Zenzizenzizenzic", "Zero-sum game", "Zeus", "xkcd" ]
1,194
575
<gh_stars>100-1000 // Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/ash/holding_space/holding_space_keyed_service.h" #include <set> #include "ash/public/cpp/holding_space/holding_space_controller.h" #include "ash/public/cpp/holding_space/holding_space_image.h" #include "ash/public/cpp/holding_space/holding_space_item.h" #include "ash/public/cpp/holding_space/holding_space_metrics.h" #include "ash/public/cpp/holding_space/holding_space_prefs.h" #include "base/callback_helpers.h" #include "base/files/file_path.h" #include "chrome/browser/ash/drive/drive_integration_service.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chromeos/file_manager/app_id.h" #include "chrome/browser/chromeos/file_manager/fileapi_util.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/ash/holding_space/holding_space_downloads_delegate.h" #include "chrome/browser/ui/ash/holding_space/holding_space_file_system_delegate.h" #include "chrome/browser/ui/ash/holding_space/holding_space_persistence_delegate.h" #include "chrome/browser/ui/ash/holding_space/holding_space_util.h" #include "components/account_id/account_id.h" #include "components/prefs/scoped_user_pref_update.h" #include "storage/browser/file_system/file_system_context.h" #include "storage/browser/file_system/file_system_url.h" #include "storage/common/file_system/file_system_types.h" namespace ash { namespace { // Helpers --------------------------------------------------------------------- // TODO(crbug.com/1131266): Track alternative type in `HoldingSpaceItem`. // Returns a holding space item other than the one provided which is backed by // the same file path in the specified `model`. base::Optional<const HoldingSpaceItem*> GetAlternativeHoldingSpaceItem( const HoldingSpaceModel& model, const HoldingSpaceItem* item) { for (const auto& candidate_item : model.items()) { if (candidate_item.get() == item) continue; if (candidate_item->file_path() == item->file_path()) return candidate_item.get(); } return base::nullopt; } // Returns the singleton profile manager for the browser process. ProfileManager* GetProfileManager() { return g_browser_process->profile_manager(); } // Records the time from the first availability of the holding space feature // to the time of the first item being added into holding space. void RecordTimeFromFirstAvailabilityToFirstAdd(Profile* profile) { base::Time time_of_first_availability = holding_space_prefs::GetTimeOfFirstAvailability(profile->GetPrefs()) .value(); base::Time time_of_first_add = holding_space_prefs::GetTimeOfFirstAdd(profile->GetPrefs()).value(); holding_space_metrics::RecordTimeFromFirstAvailabilityToFirstAdd( time_of_first_add - time_of_first_availability); } // Records the time from the first entry to the first pin into holding space. // Note that this time may be zero if the user pinned their first file before // having ever entered holding space. void RecordTimeFromFirstEntryToFirstPin(Profile* profile) { base::Time time_of_first_pin = holding_space_prefs::GetTimeOfFirstPin(profile->GetPrefs()).value(); base::Time time_of_first_entry = holding_space_prefs::GetTimeOfFirstEntry(profile->GetPrefs()) .value_or(time_of_first_pin); holding_space_metrics::RecordTimeFromFirstEntryToFirstPin( time_of_first_pin - time_of_first_entry); } } // namespace // HoldingSpaceKeyedService ---------------------------------------------------- HoldingSpaceKeyedService::HoldingSpaceKeyedService(Profile* profile, const AccountId& account_id) : profile_(profile), account_id_(account_id), holding_space_client_(profile), thumbnail_loader_(profile) { // Mark when the holding space feature first became available. If this is not // the first time that holding space became available, this will no-op. holding_space_prefs::MarkTimeOfFirstAvailability(profile_->GetPrefs()); ProfileManager* const profile_manager = GetProfileManager(); if (!profile_manager) // May be `nullptr` in tests. return; // The associated profile may not be ready yet. If it is, we can immediately // proceed with profile dependent initialization. if (profile_manager->IsValidProfile(profile)) { OnProfileReady(); return; } // Otherwise we need to wait for the profile to be added. profile_manager_observer_.Observe(profile_manager); } HoldingSpaceKeyedService::~HoldingSpaceKeyedService() { if (chromeos::PowerManagerClient::Get()) chromeos::PowerManagerClient::Get()->RemoveObserver(this); if (HoldingSpaceController::Get()) { // May be `nullptr` in tests. HoldingSpaceController::Get()->RegisterClientAndModelForUser( account_id_, /*client=*/nullptr, /*model=*/nullptr); } } // static void HoldingSpaceKeyedService::RegisterProfilePrefs( user_prefs::PrefRegistrySyncable* registry) { // TODO(crbug.com/1131266): Move to `ash::holding_space_prefs`. HoldingSpacePersistenceDelegate::RegisterProfilePrefs(registry); } void HoldingSpaceKeyedService::AddPinnedFiles( const std::vector<storage::FileSystemURL>& file_system_urls) { std::vector<std::unique_ptr<HoldingSpaceItem>> items; std::vector<const HoldingSpaceItem*> items_to_record; for (const storage::FileSystemURL& file_system_url : file_system_urls) { if (holding_space_model_.ContainsItem(HoldingSpaceItem::Type::kPinnedFile, file_system_url.path())) { continue; } items.push_back(HoldingSpaceItem::CreateFileBackedItem( HoldingSpaceItem::Type::kPinnedFile, file_system_url.path(), file_system_url.ToGURL(), base::BindOnce(&holding_space_util::ResolveImage, &thumbnail_loader_))); // When pinning an item which already exists in holding space, the pin // action should be recorded on the alternative item backed by the same file // path if such an item exists. Otherwise the only type of holding space // item pinned will be thought to be `kPinnedFile`. items_to_record.push_back( GetAlternativeHoldingSpaceItem(holding_space_model_, items.back().get()) .value_or(items.back().get())); if (file_system_url.type() == storage::kFileSystemTypeDriveFs) MakeDriveItemAvailableOffline(file_system_url); } DCHECK_EQ(items.size(), items_to_record.size()); if (items.empty()) return; // Mark when the first pin to holding space occurred. If this is not the first // pin to holding space, this will no-op. If this is the first pin, record the // amount of time from first entry to first pin into holding space. if (holding_space_prefs::MarkTimeOfFirstPin(profile_->GetPrefs())) RecordTimeFromFirstEntryToFirstPin(profile_); holding_space_metrics::RecordItemAction( items_to_record, holding_space_metrics::ItemAction::kPin); AddItems(std::move(items)); } void HoldingSpaceKeyedService::RemovePinnedFiles( const std::vector<storage::FileSystemURL>& file_system_urls) { std::set<std::string> items; std::vector<const HoldingSpaceItem*> items_to_record; for (const storage::FileSystemURL& file_system_url : file_system_urls) { const HoldingSpaceItem* item = holding_space_model_.GetItem( HoldingSpaceItem::Type::kPinnedFile, file_system_url.path()); if (!item) continue; items.emplace(item->id()); // When removing a pinned item, the unpin action should be recorded on the // alternative item backed by the same file path if such an item exists. // This will give more insight as to what types of items are being unpinned // than would otherwise be known if only `kPinnedFile` was recorded. items_to_record.push_back( GetAlternativeHoldingSpaceItem(holding_space_model_, item) .value_or(item)); } DCHECK_EQ(items.size(), items_to_record.size()); if (items.empty()) return; holding_space_metrics::RecordItemAction( items_to_record, holding_space_metrics::ItemAction::kUnpin); holding_space_model_.RemoveItems(items); } bool HoldingSpaceKeyedService::ContainsPinnedFile( const storage::FileSystemURL& file_system_url) const { return holding_space_model_.ContainsItem(HoldingSpaceItem::Type::kPinnedFile, file_system_url.path()); } std::vector<GURL> HoldingSpaceKeyedService::GetPinnedFiles() const { std::vector<GURL> pinned_files; for (const auto& item : holding_space_model_.items()) { if (item->type() == HoldingSpaceItem::Type::kPinnedFile) pinned_files.push_back(item->file_system_url()); } return pinned_files; } void HoldingSpaceKeyedService::AddScreenshot( const base::FilePath& screenshot_file) { const bool already_exists = holding_space_model_.ContainsItem( HoldingSpaceItem::Type::kScreenshot, screenshot_file); if (already_exists) return; GURL file_system_url = holding_space_util::ResolveFileSystemUrl(profile_, screenshot_file); if (file_system_url.is_empty()) return; AddItem(HoldingSpaceItem::CreateFileBackedItem( HoldingSpaceItem::Type::kScreenshot, screenshot_file, file_system_url, base::BindOnce(&holding_space_util::ResolveImage, &thumbnail_loader_))); } void HoldingSpaceKeyedService::AddDownload( const base::FilePath& download_file) { const bool already_exists = holding_space_model_.ContainsItem( HoldingSpaceItem::Type::kDownload, download_file); if (already_exists) return; GURL file_system_url = holding_space_util::ResolveFileSystemUrl(profile_, download_file); if (file_system_url.is_empty()) return; AddItem(HoldingSpaceItem::CreateFileBackedItem( HoldingSpaceItem::Type::kDownload, download_file, file_system_url, base::BindOnce(&holding_space_util::ResolveImage, &thumbnail_loader_))); } void HoldingSpaceKeyedService::AddNearbyShare( const base::FilePath& nearby_share_path) { const bool already_exists = holding_space_model_.ContainsItem( HoldingSpaceItem::Type::kNearbyShare, nearby_share_path); if (already_exists) return; GURL file_system_url = holding_space_util::ResolveFileSystemUrl(profile_, nearby_share_path); if (file_system_url.is_empty()) return; AddItem(HoldingSpaceItem::CreateFileBackedItem( HoldingSpaceItem::Type::kNearbyShare, nearby_share_path, file_system_url, base::BindOnce(&holding_space_util::ResolveImage, &thumbnail_loader_))); } void HoldingSpaceKeyedService::AddScreenRecording( const base::FilePath& screen_recording_file) { const bool already_exists = holding_space_model_.ContainsItem( HoldingSpaceItem::Type::kScreenRecording, screen_recording_file); if (already_exists) return; GURL file_system_url = holding_space_util::ResolveFileSystemUrl(profile_, screen_recording_file); if (file_system_url.is_empty()) return; AddItem(HoldingSpaceItem::CreateFileBackedItem( HoldingSpaceItem::Type::kScreenRecording, screen_recording_file, file_system_url, base::BindOnce(&holding_space_util::ResolveImage, &thumbnail_loader_))); } void HoldingSpaceKeyedService::AddItem(std::unique_ptr<HoldingSpaceItem> item) { std::vector<std::unique_ptr<HoldingSpaceItem>> items; items.push_back(std::move(item)); AddItems(std::move(items)); } void HoldingSpaceKeyedService::AddItems( std::vector<std::unique_ptr<HoldingSpaceItem>> items) { DCHECK(!items.empty()); // Mark the time when the user's first item was added to holding space. Note // that true is returned iff this is in fact the user's first add and, if so, // the time it took for the user to add their first item should be recorded. if (holding_space_prefs::MarkTimeOfFirstAdd(profile_->GetPrefs())) RecordTimeFromFirstAvailabilityToFirstAdd(profile_); holding_space_model_.AddItems(std::move(items)); } void HoldingSpaceKeyedService::Shutdown() { ShutdownDelegates(); } void HoldingSpaceKeyedService::OnProfileAdded(Profile* profile) { if (profile == profile_) { DCHECK(profile_manager_observer_.IsObserving()); profile_manager_observer_.Reset(); OnProfileReady(); } } void HoldingSpaceKeyedService::OnProfileReady() { // Observe suspend status - the delegates will be shutdown during suspend. if (chromeos::PowerManagerClient::Get()) chromeos::PowerManagerClient::Get()->AddObserver(this); InitializeDelegates(); if (HoldingSpaceController::Get()) { // May be `nullptr` in tests. HoldingSpaceController::Get()->RegisterClientAndModelForUser( account_id_, &holding_space_client_, &holding_space_model_); } } void HoldingSpaceKeyedService::SuspendImminent( power_manager::SuspendImminent::Reason reason) { // Shutdown all delegates and clear the model when device suspends - some // volumes may get unmounted during suspend, and may thus incorrectly get // detected as deleted when device suspends - shutting down delegates during // suspend avoids this issue, as it also disables file removal detection. ShutdownDelegates(); // Clear the model as it will get restored from persistence when // delegates are re-initialized after suspend. holding_space_model_.RemoveAll(); } void HoldingSpaceKeyedService::SuspendDone(base::TimeDelta sleep_duration) { InitializeDelegates(); } void HoldingSpaceKeyedService::InitializeDelegates() { // Bail out if delegates have already been initialized - delegates are // shutdown on suspend, and re-initialized once suspend completes. If // holding space keyed service starts observing suspend state after // `SuspendImminent()` is sent out, original delegates may still be around. if (!delegates_.empty()) return; // The `HoldingSpaceDownloadsDelegate` monitors the status of downloads. delegates_.push_back(std::make_unique<HoldingSpaceDownloadsDelegate>( profile_, &holding_space_model_, /*item_downloaded_callback=*/ base::BindRepeating(&HoldingSpaceKeyedService::AddDownload, weak_factory_.GetWeakPtr()))); // The `HoldingSpaceFileSystemDelegate` monitors the file system for changes. delegates_.push_back(std::make_unique<HoldingSpaceFileSystemDelegate>( profile_, &holding_space_model_)); // The `HoldingSpacePersistenceDelegate` manages holding space persistence. delegates_.push_back(std::make_unique<HoldingSpacePersistenceDelegate>( profile_, &holding_space_model_, &thumbnail_loader_, /*item_restored_callback=*/ base::BindRepeating(&HoldingSpaceKeyedService::AddItem, weak_factory_.GetWeakPtr()), /*persistence_restored_callback=*/ base::BindOnce(&HoldingSpaceKeyedService::OnPersistenceRestored, weak_factory_.GetWeakPtr()))); // Initialize all delegates only after they have been added to our collection. // Delegates should not fire their respective callbacks during construction // but once they have been initialized they are free to do so. for (auto& delegate : delegates_) delegate->Init(); } void HoldingSpaceKeyedService::ShutdownDelegates() { delegates_.clear(); } void HoldingSpaceKeyedService::OnPersistenceRestored() { for (auto& delegate : delegates_) delegate->NotifyPersistenceRestored(); } void HoldingSpaceKeyedService::MakeDriveItemAvailableOffline( const storage::FileSystemURL& file_system_url) { auto* drive_service = drive::DriveIntegrationServiceFactory::GetForProfile(profile_); bool drive_fs_mounted = drive_service && drive_service->IsMounted(); if (!drive_fs_mounted) return; if (!drive_service->GetDriveFsInterface()) return; base::FilePath path; if (drive_service->GetRelativeDrivePath(file_system_url.path(), &path)) { drive_service->GetDriveFsInterface()->SetPinned(path, true, base::DoNothing()); } } } // namespace ash
5,355
348
{"nom":"Mietesheim","circ":"8ème circonscription","dpt":"Bas-Rhin","inscrits":510,"abs":287,"votants":223,"blancs":13,"nuls":4,"exp":206,"res":[{"nuance":"LR","nom":"<NAME>","voix":104},{"nuance":"REM","nom":"<NAME>","voix":102}]}
91
13,006
<gh_stars>1000+ /******************************************************************************* * Copyright (c) 2015-2018 Skymind, Inc. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ package org.nd4j.linalg.api.blas; /** * Extra functionality for BLAS * * @author saudet */ public interface Blas { public enum Vendor { UNKNOWN, CUBLAS, OPENBLAS, MKL, } void setMaxThreads(int num); int getMaxThreads(); /** * Returns the BLAS library vendor id * * 0 - UNKNOWN, 1 - CUBLAS, 2 - OPENBLAS, 3 - MKL * * @return the BLAS library vendor id */ int getBlasVendorId(); /** * Returns the BLAS library vendor * * @return the BLAS library vendor */ public Vendor getBlasVendor(); }
422
837
package me.saket.dank.widgets.InboxUI; import android.app.Activity; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Parcel; import android.os.Parcelable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.AttributeSet; import android.view.View; import android.view.Window; import me.saket.dank.utils.Views; import me.saket.dank.widgets.InboxUI.ExpandablePageLayout.PageState; /** * Mimics the expandable layout in the Inbox app by Google. #AcheDin. */ public class InboxRecyclerView extends RecyclerView implements ExpandablePageLayout.InternalPageCallbacks { private static final String KEY_IS_EXPANDED = "isExpanded"; private static final float MAX_DIM_FACTOR = 0.2f; // [0..1] private static final int MAX_DIM = (int) (255 * MAX_DIM_FACTOR); // [0..255] private ExpandablePageLayout page; private ExpandInfo expandInfo; // Details about the currently expanded Item private Paint dimPaint; private Window activityWindow; private Drawable activityWindowOrigBackground; private boolean pendingItemsOutOfTheWindowAnimation; private boolean isFullyCoveredByPage; private boolean layoutManagerCreated; public InboxRecyclerView(Context context) { super(context); init(); } public InboxRecyclerView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public InboxRecyclerView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } private void init() { // For drawing an overlay shadow while the expandable page is fully expanded. setWillNotDraw(false); dimPaint = new Paint(Paint.ANTI_ALIAS_FLAG); dimPaint.setColor(Color.BLACK); dimPaint.setAlpha(MAX_DIM); } public LayoutManager createLayoutManager() { layoutManagerCreated = true; return new LinearLayoutManager(getContext()) { @Override public int scrollVerticallyBy(int dy, Recycler recycler, State state) { return !canScroll() ? 0 : super.scrollVerticallyBy(dy, recycler, state); } }; } public void saveExpandableState(Bundle outState) { if (page != null) { outState.putBoolean(KEY_IS_EXPANDED, page.isExpanded()); } } /** Letting Activities handle restoration manually so that the setup can happen before onRestore gets called. */ public void restoreExpandableState(Bundle savedInstance) { boolean wasExpanded = savedInstance.getBoolean(KEY_IS_EXPANDED); if (wasExpanded) { if (page == null) { throw new NullPointerException("setExpandablePage() must be called before handleOnRetainInstance()"); } page.expandImmediately(); } } /** * Sets the {@link ExpandablePageLayout} and {@link Toolbar} to be used with this list. The toolbar * gets pushed up when the page is expanding. It is also safe to call this method again and replace * the ExpandablePage or Toolbar. */ public void setExpandablePage(ExpandablePageLayout expandablePage, View toolbar) { page = expandablePage; expandablePage.setup(toolbar); expandablePage.setInternalStateCallbacksForList(this); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { super.onLayout(changed, l, t, r, b); // In case any expand() call was made before this list and its child Views were measured, perform it now. if (pendingItemsOutOfTheWindowAnimation) { pendingItemsOutOfTheWindowAnimation = false; animateItemsOutOfTheWindow(true); } } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); // Must have gotten called because the keyboard was called / hidden. The items must maintain their // positions, relative to the new bounds. Wait for Android to draw the child Views. Calling // getChildCount() right now will return old values (that is, no. of children that were present before // this height change happened. if (page == null) { return; } Views.executeOnNextLayout(this, () -> { // Fix list items. if (getPage().isExpandedOrExpanding()) { animateItemsOutOfTheWindow(getPage().isExpanded()); } else { animateItemsBackToPosition(getPage().isCollapsed()); } // Fix expandable page (or else it gets stuck in the middle since it doesn't know of the size change). if (getPage().getCurrentState() == PageState.EXPANDING) { getPage().animatePageExpandCollapse(true, getWidth(), getHeight(), getExpandInfo()); } else if (getPage().getCurrentState() == PageState.EXPANDED) { getPage().alignPageToCoverScreen(); } }); } // ======== EXPAND / COLLAPSE ======== // /** * @param itemViewPosition Item's position in the RecyclerView. This is not the same as adapter position. */ public void expandItem(int itemViewPosition, long itemId) { if (page == null) { throw new IllegalAccessError("You must call InboxRecyclerView.setup(ExpandablePage, Toolbar)"); } if (!layoutManagerCreated) { throw new IllegalAccessError("LayoutManager isn't set. #Use createLayoutManager()"); } // Ignore if already expanded. if (getPage().isExpandedOrExpanding()) { return; } View child = getChildAt(itemViewPosition); if (child == null) { // Not sure why this would happen. Maybe the View // got removed right when it was clicked to expand? return; } // Store these details so that they can be used later for restoring the original state. final Rect itemRect = new Rect( getLeft() + child.getLeft(), getTop() + child.getTop(), (getWidth() - getRight()) + child.getRight(), getTop() + child.getBottom() ); if (itemRect.width() == 0) { // Should expand from full width even when expanding from arbitrary location (that is, item to expand is null). itemRect.left = getLeft(); itemRect.right = getRight(); } expandInfo = new ExpandInfo(itemViewPosition, itemId, itemRect); // Animate all items out of the window and expand the page. animateItemsOutOfTheWindow(); // Skip animations if Android hasn't measured Views yet. if (!isLaidOut() && getVisibility() != GONE) { expandImmediately(); } else { getPage().expand(getExpandInfo()); } } /** * Expands from arbitrary location. Presently the top. * * @deprecated This will possibly crash in expandItem(). Fix before using. */ public void expandFromTop() { expandItem(-1, -1); } /** * Expands the page right away and pushes the items out of the list without animations. */ public void expandImmediately() { getPage().expandImmediately(); // This will push all the list items to the bottom, as if the item // above the 0th position was expanded animateItemsOutOfTheWindow(true); } public void collapse() { if (getPage() == null) { throw new IllegalStateException("No page attached. Cannot collapse. ListId: " + getId()); } // Ignore if already collapsed if (getPage().isCollapsedOrCollapsing()) { return; } pendingItemsOutOfTheWindowAnimation = false; // This ensures the items were present outside the window before collapse starts if (getPage().getTranslationY() == 0) { animateItemsOutOfTheWindow(true); } // Collapse the page and restore the item positions of this list if (getPage() != null) { ExpandInfo expandInfo = getExpandInfo(); getPage().collapse(expandInfo); } animateItemsBackToPosition(false); } // ======== ANIMATION ======== // /** * Animates all items out of the Window. The item at position <code>expandInfo.expandedItemPosition</code> * is moved to the top, while the items above it are animated out of the window from the top and the rest * from the bottom. */ void animateItemsOutOfTheWindow(boolean immediate) { if (!isLaidOut()) { // Neither this list has been drawn yet nor its child views. pendingItemsOutOfTheWindowAnimation = true; return; } final int anchorPosition = getExpandInfo().expandedItemPosition; final int listHeight = getHeight(); for (int i = 0; i < getChildCount(); i++) { final View view = getChildAt(i); // 1. Anchor view to the top edge // 2. Views above it out of the top edge // 3. Views below it out of the bottom edge final float moveY; final boolean above = i <= anchorPosition; if (anchorPosition == -1 || view.getHeight() <= 0) { // Item to expand not present in the list. Send all Views outside the bottom edge moveY = listHeight - getPaddingTop(); } else { final int positionOffset = i - anchorPosition; moveY = above ? -view.getTop() + positionOffset * view.getHeight() : listHeight - view.getTop() + view.getHeight() * (positionOffset - 1); } view.animate().cancel(); if (!immediate) { view.animate() .translationY(moveY) .setDuration(page.getAnimationDurationMillis()) .setInterpolator(page.getAnimationInterpolator()) .setStartDelay(getAnimationStartDelay()); if (anchorPosition == i) { view.animate().alpha(0f).withLayer(); } } else { //noinspection ResourceType view.setTranslationY(moveY); if (anchorPosition == i) { view.setAlpha(0f); } } } } void animateItemsOutOfTheWindow() { animateItemsOutOfTheWindow(false); } /** * Reverses animateItemsOutOfTheWindow() by moving all items back to their actual positions. */ protected void animateItemsBackToPosition(boolean immediate) { int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { View view = getChildAt(i); if (view == null) { continue; } // Strangely, both the sections (above and below) are getting restored at the same time even when // the animation duration is same. :O // Update: Oh god. I confused time with speed. Not deleting this so that this comment always // reminds me how stupid I can be at times. view.animate().cancel(); if (!immediate) { view.animate() .alpha(1f) .translationY(0f) .setDuration(page.getAnimationDurationMillis()) .setInterpolator(page.getAnimationInterpolator()) .setStartDelay(getAnimationStartDelay()); } else { view.setTranslationY(0f); view.setAlpha(1f); } } } // ======== PAGE CALLBACKS ======== // @Override public void onPageAboutToCollapse() { onPageBackgroundVisible(); postInvalidate(); } @Override public void onPageFullyCollapsed() { expandInfo = null; } @Override public void onPagePull(float deltaY) { for (int i = 0; i < getChildCount(); i++) { final View itemView = getChildAt(i); // Stop any ongoing animation in case the user started pulling while the list items were // still animating (out of the window). itemView.animate().cancel(); itemView.setTranslationY(itemView.getTranslationY() + deltaY); } onPageBackgroundVisible(); } @Override public void onPageRelease(boolean collapseEligible) { if (collapseEligible) { collapse(); onPageBackgroundVisible(); } else { animateItemsOutOfTheWindow(); } } @Override public void onPageFullyCovered() { final boolean invalidate = !isFullyCoveredByPage; isFullyCoveredByPage = true; // Skips draw() until visible again to the user. if (invalidate) { postInvalidate(); } if (activityWindow != null) { activityWindow.setBackgroundDrawable(null); } } public void onPageBackgroundVisible() { final boolean invalidate = isFullyCoveredByPage; isFullyCoveredByPage = false; if (invalidate) { postInvalidate(); } if (activityWindow != null) { activityWindow.setBackgroundDrawable(activityWindowOrigBackground); } } // ======== DIMMING + REDUCING OVERDRAW ======== // @Override public void draw(Canvas canvas) { // Minimize overdraw by not drawing anything while this list is totally covered by the expandable page. if (isFullyCoveredByPage) { return; } super.draw(canvas); if (page != null && page.isExpanded()) { canvas.drawRect(0, 0, getRight(), getBottom(), dimPaint); } } // ======== SCROLL ======== // private boolean canScroll() { return page == null || getPage().isCollapsed(); } @Override public void scrollToPosition(int position) { if (!canScroll()) { return; } super.scrollToPosition(position); } @Override public void smoothScrollToPosition(int position) { if (!canScroll()) { return; } super.smoothScrollToPosition(position); } @Override public void smoothScrollBy(int dx, int dy) { if (!canScroll()) { return; } super.smoothScrollBy(dx, dy); } @Override public void scrollTo(int x, int y) { if (!canScroll()) { return; } super.scrollTo(x, y); } @Override public void scrollBy(int x, int y) { if (!canScroll()) { return; } super.scrollBy(x, y); } public ExpandablePageLayout getPage() { return page; } /** * @return Details of the currently expanded item. Returns an empty ExpandInfo object * if all items are collapsed. */ public ExpandInfo getExpandInfo() { if (expandInfo == null) { expandInfo = ExpandInfo.createEmpty(); } return expandInfo; } /** * Reduce overdraw by 1 level by removing the Activity Window's background * while the {@link ExpandablePageLayout} is open. No point in drawing it when * it's not visible to the user. This way, there's no extra overdraw while the * expandable page is open. */ public void optimizeActivityBackgroundOverdraw(Activity activity) { activityWindow = activity.getWindow(); activityWindowOrigBackground = activityWindow.getDecorView().getBackground(); } public static int getAnimationStartDelay() { return 0; } /** * Contains details of the currently expanded item. */ public static class ExpandInfo implements Parcelable { // Position of the currently expanded item. public int expandedItemPosition = -1; // Adapter ID of the currently expanded item. public long expandedItemId = -1; // Original location of the currently expanded item (that is, when the user selected this item). // Can be used for restoring states after collapsing. Rect expandedItemLocationRect; public ExpandInfo(int expandedItemPosition, long expandedItemId, Rect expandedItemLocationRect) { this.expandedItemPosition = expandedItemPosition; this.expandedItemId = expandedItemId; this.expandedItemLocationRect = expandedItemLocationRect; } static ExpandInfo createEmpty() { return new ExpandInfo(-1, -1, new Rect(0, 0, 0, 0)); } boolean isEmpty() { return expandedItemPosition == -1 || expandedItemId == -1 || expandedItemLocationRect.height() == 0; } @Override public String toString() { return "ExpandInfo{" + "expandedItemPosition=" + expandedItemPosition + ", expandedItem Height=" + expandedItemLocationRect.height() + '}'; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(this.expandedItemPosition); dest.writeLong(this.expandedItemId); dest.writeParcelable(this.expandedItemLocationRect, 0); } protected ExpandInfo(Parcel in) { this.expandedItemPosition = in.readInt(); this.expandedItemId = in.readLong(); this.expandedItemLocationRect = in.readParcelable(Rect.class.getClassLoader()); } public static final Creator<ExpandInfo> CREATOR = new Creator<ExpandInfo>() { public ExpandInfo createFromParcel(Parcel source) { return new ExpandInfo(source); } public ExpandInfo[] newArray(int size) { return new ExpandInfo[size]; } }; } }
5,845
994
<filename>src/framework/shared/inc/private/common/fxpkgioshared.hpp<gh_stars>100-1000 /*++ Copyright (c) Microsoft Corporation Module Name: FxPkgIoShared.hpp Abstract: This file contains portion of FxPkgIo.hpp that is need in shared code. Author: Environment: Revision History: --*/ #ifndef _FXPKGIOSHARED_HPP_ #define _FXPKGIOSHARED_HPP_ enum FxIoStopProcessingForPowerAction { FxIoStopProcessingForPowerHold = 1, FxIoStopProcessingForPowerPurgeManaged, FxIoStopProcessingForPowerPurgeNonManaged, }; // begin_wpp config // CUSTOM_TYPE(FxIoStopProcessingForPowerAction, ItemEnum(FxIoStopProcessingForPowerAction)); // end_wpp #endif // _FXPKGIOSHARED_HPP
275
8,649
<reponame>brewswang/hsweb-framework package org.hswebframework.web.authorization.dimension; import reactor.core.publisher.Flux; import java.util.Collection; public interface DimensionUserBindProvider { Flux<DimensionUserBind> getDimensionBindInfo(Collection<String> userIdList); }
89
488
<filename>projects/MatlabTranslation/src/transformations/armadillo/ArmaOptimizer.h #ifndef _ARMA_OPTIMIZER_H #define _ARMA_OPTIMIZER_H 1 class SgProject; namespace ArmaOpt { /// runs Armadillo specific optimizations void optimize(SgProject*); } #endif /* _ARMA_OPTIMIZER_H */
111
2,577
/* * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH * under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. Camunda licenses this file to you under the Apache License, * Version 2.0; 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.camunda.bpm.client.impl; import java.net.InetAddress; import java.net.UnknownHostException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.ServiceLoader; import java.util.UUID; import org.camunda.bpm.client.ExternalTaskClient; import org.camunda.bpm.client.ExternalTaskClientBuilder; import org.camunda.bpm.client.backoff.BackoffStrategy; import org.camunda.bpm.client.backoff.ExponentialBackoffStrategy; import org.camunda.bpm.client.interceptor.ClientRequestInterceptor; import org.camunda.bpm.client.interceptor.impl.RequestInterceptorHandler; import org.camunda.bpm.client.spi.DataFormat; import org.camunda.bpm.client.spi.DataFormatConfigurator; import org.camunda.bpm.client.spi.DataFormatProvider; import org.camunda.bpm.client.topic.impl.TopicSubscriptionManager; import org.camunda.bpm.client.variable.impl.DefaultValueMappers; import org.camunda.bpm.client.variable.impl.TypedValues; import org.camunda.bpm.client.variable.impl.ValueMappers; import org.camunda.bpm.client.variable.impl.mapper.BooleanValueMapper; import org.camunda.bpm.client.variable.impl.mapper.ByteArrayValueMapper; import org.camunda.bpm.client.variable.impl.mapper.DateValueMapper; import org.camunda.bpm.client.variable.impl.mapper.DoubleValueMapper; import org.camunda.bpm.client.variable.impl.mapper.FileValueMapper; import org.camunda.bpm.client.variable.impl.mapper.IntegerValueMapper; import org.camunda.bpm.client.variable.impl.mapper.JsonValueMapper; import org.camunda.bpm.client.variable.impl.mapper.LongValueMapper; import org.camunda.bpm.client.variable.impl.mapper.NullValueMapper; import org.camunda.bpm.client.variable.impl.mapper.ObjectValueMapper; import org.camunda.bpm.client.variable.impl.mapper.ShortValueMapper; import org.camunda.bpm.client.variable.impl.mapper.StringValueMapper; import org.camunda.bpm.client.variable.impl.mapper.XmlValueMapper; import org.camunda.bpm.engine.variable.Variables; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; /** * @author <NAME> */ public class ExternalTaskClientBuilderImpl implements ExternalTaskClientBuilder { protected static final ExternalTaskClientLogger LOG = ExternalTaskClientLogger.CLIENT_LOGGER; protected String baseUrl; protected String workerId; protected int maxTasks; protected boolean usePriority; protected Long asyncResponseTimeout; protected long lockDuration; protected String defaultSerializationFormat = Variables.SerializationDataFormats.JSON.getName(); protected String dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; protected ObjectMapper objectMapper; protected ValueMappers valueMappers; protected TypedValues typedValues; protected EngineClient engineClient; protected TopicSubscriptionManager topicSubscriptionManager; protected List<ClientRequestInterceptor> interceptors; protected boolean isAutoFetchingEnabled; protected BackoffStrategy backoffStrategy; protected boolean isBackoffStrategyDisabled; public ExternalTaskClientBuilderImpl() { // default values this.maxTasks = 10; this.usePriority = true; this.asyncResponseTimeout = null; this.lockDuration = 20_000; this.interceptors = new ArrayList<>(); this.isAutoFetchingEnabled = true; this.backoffStrategy = new ExponentialBackoffStrategy(); this.isBackoffStrategyDisabled = false; } public ExternalTaskClientBuilder baseUrl(String baseUrl) { this.baseUrl = baseUrl; return this; } public ExternalTaskClientBuilder workerId(String workerId) { this.workerId = workerId; return this; } public ExternalTaskClientBuilder addInterceptor(ClientRequestInterceptor interceptor) { this.interceptors.add(interceptor); return this; } public ExternalTaskClientBuilder maxTasks(int maxTasks) { this.maxTasks = maxTasks; return this; } public ExternalTaskClientBuilder usePriority(boolean usePriority) { this.usePriority = usePriority; return this; } public ExternalTaskClientBuilder asyncResponseTimeout(long asyncResponseTimeout) { this.asyncResponseTimeout = asyncResponseTimeout; return this; } public ExternalTaskClientBuilder lockDuration(long lockDuration) { this.lockDuration = lockDuration; return this; } public ExternalTaskClientBuilder disableAutoFetching() { this.isAutoFetchingEnabled = false; return this; } public ExternalTaskClientBuilder backoffStrategy(BackoffStrategy backoffStrategy) { this.backoffStrategy = backoffStrategy; return this; } public ExternalTaskClientBuilder disableBackoffStrategy() { this.isBackoffStrategyDisabled = true; return this; } public ExternalTaskClientBuilder defaultSerializationFormat(String defaultSerializationFormat) { this.defaultSerializationFormat = defaultSerializationFormat; return this; } public ExternalTaskClientBuilder dateFormat(String dateFormat) { this.dateFormat = dateFormat; return this; } public ExternalTaskClient build() { if (maxTasks <= 0) { throw LOG.maxTasksNotGreaterThanZeroException(maxTasks); } if (asyncResponseTimeout != null && asyncResponseTimeout <= 0) { throw LOG.asyncResponseTimeoutNotGreaterThanZeroException(asyncResponseTimeout); } if (lockDuration <= 0L) { throw LOG.lockDurationIsNotGreaterThanZeroException(lockDuration); } if (baseUrl == null || baseUrl.isEmpty()) { throw LOG.baseUrlNullException(); } checkInterceptors(); initBaseUrl(); initWorkerId(); initObjectMapper(); initEngineClient(); initVariableMappers(); initTopicSubscriptionManager(); return new ExternalTaskClientImpl(topicSubscriptionManager); } protected void initBaseUrl() { baseUrl = sanitizeUrl(baseUrl); } protected String sanitizeUrl(String url) { url = url.trim(); if (url.endsWith("/")) { url = url.replaceAll("/$", ""); url = sanitizeUrl(url); } return url; } protected void initWorkerId() { if (workerId == null) { String hostname = checkHostname(); this.workerId = hostname + UUID.randomUUID(); } } protected void checkInterceptors() { interceptors.forEach(interceptor -> { if (interceptor == null) { throw LOG.interceptorNullException(); } }); } protected void initObjectMapper() { objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.configure(DeserializationFeature.FAIL_ON_UNRESOLVED_OBJECT_IDS, false); objectMapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, false); SimpleDateFormat sdf = new SimpleDateFormat(dateFormat); objectMapper.setDateFormat(sdf); objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); } @SuppressWarnings({ "rawtypes", "unchecked" }) protected void initVariableMappers() { valueMappers = new DefaultValueMappers(defaultSerializationFormat); valueMappers.addMapper(new NullValueMapper()); valueMappers.addMapper(new BooleanValueMapper()); valueMappers.addMapper(new StringValueMapper()); valueMappers.addMapper(new DateValueMapper(dateFormat)); valueMappers.addMapper(new ByteArrayValueMapper()); // number mappers valueMappers.addMapper(new IntegerValueMapper()); valueMappers.addMapper(new LongValueMapper()); valueMappers.addMapper(new ShortValueMapper()); valueMappers.addMapper(new DoubleValueMapper()); // object Map<String, DataFormat> dataFormats = lookupDataFormats(); dataFormats.forEach((key, format) -> { valueMappers.addMapper(new ObjectValueMapper(key, format)); }); // json/xml valueMappers.addMapper(new JsonValueMapper()); valueMappers.addMapper(new XmlValueMapper()); // file valueMappers.addMapper(new FileValueMapper(engineClient)); typedValues = new TypedValues(valueMappers); engineClient.setTypedValues(typedValues); } protected void initEngineClient() { RequestInterceptorHandler requestInterceptorHandler = new RequestInterceptorHandler(interceptors); RequestExecutor requestExecutor = new RequestExecutor(requestInterceptorHandler, objectMapper); engineClient = new EngineClient(workerId, maxTasks, asyncResponseTimeout, baseUrl, requestExecutor, usePriority); } protected void initTopicSubscriptionManager() { topicSubscriptionManager = new TopicSubscriptionManager(engineClient, typedValues, lockDuration); topicSubscriptionManager.setBackoffStrategy(getBackoffStrategy()); if (isBackoffStrategyDisabled) { topicSubscriptionManager.disableBackoffStrategy(); } if (isAutoFetchingEnabled()) { topicSubscriptionManager.start(); } } protected Map<String, DataFormat> lookupDataFormats() { Map<String, DataFormat> dataFormats = new HashMap<>(); lookupCustomDataFormats(dataFormats); applyConfigurators(dataFormats); return dataFormats; } protected void lookupCustomDataFormats(Map<String, DataFormat> dataFormats) { // use java.util.ServiceLoader to load custom DataFormatProvider instances on the classpath ServiceLoader<DataFormatProvider> providerLoader = ServiceLoader.load(DataFormatProvider.class); for (DataFormatProvider provider : providerLoader) { LOG.logDataFormatProvider(provider); lookupProvider(dataFormats, provider); } } protected void lookupProvider(Map<String, DataFormat> dataFormats, DataFormatProvider provider) { String dataFormatName = provider.getDataFormatName(); if(!dataFormats.containsKey(dataFormatName)) { DataFormat dataFormatInstance = provider.createInstance(); dataFormats.put(dataFormatName, dataFormatInstance); LOG.logDataFormat(dataFormatInstance); } else { throw LOG.multipleProvidersForDataformat(dataFormatName); } } @SuppressWarnings("rawtypes") protected void applyConfigurators(Map<String, DataFormat> dataFormats) { ServiceLoader<DataFormatConfigurator> configuratorLoader = ServiceLoader.load(DataFormatConfigurator.class); for (DataFormatConfigurator configurator : configuratorLoader) { LOG.logDataFormatConfigurator(configurator); applyConfigurator(dataFormats, configurator); } } @SuppressWarnings({ "rawtypes", "unchecked" }) protected void applyConfigurator(Map<String, DataFormat> dataFormats, DataFormatConfigurator configurator) { for (DataFormat dataFormat : dataFormats.values()) { if (configurator.getDataFormatClass().isAssignableFrom(dataFormat.getClass())) { configurator.configure(dataFormat); } } } public String checkHostname() { String hostname; try { hostname = getHostname(); } catch (UnknownHostException e) { throw LOG.cannotGetHostnameException(e); } return hostname; } public String getHostname() throws UnknownHostException { return InetAddress.getLocalHost().getHostName(); } public String getBaseUrl() { return baseUrl; } protected String getWorkerId() { return workerId; } protected List<ClientRequestInterceptor> getInterceptors() { return interceptors; } protected int getMaxTasks() { return maxTasks; } protected Long getAsyncResponseTimeout() { return asyncResponseTimeout; } protected long getLockDuration() { return lockDuration; } protected boolean isAutoFetchingEnabled() { return isAutoFetchingEnabled; } protected BackoffStrategy getBackoffStrategy() { return backoffStrategy; } public String getDefaultSerializationFormat() { return defaultSerializationFormat; } public String getDateFormat() { return dateFormat; } public ObjectMapper getObjectMapper() { return objectMapper; } public ValueMappers getValueMappers() { return valueMappers; } public TypedValues getTypedValues() { return typedValues; } public EngineClient getEngineClient() { return engineClient; } }
4,176
1,338
/* * \file: freecom.c * \brief: USB SCSI module extention for Freecom USB/IDE adaptor * * This file is a part of BeOS USB SCSI interface module project. * Copyright (c) 2003-2004 by <NAME> <<EMAIL>> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2, or (at your option) any * later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 675 Mass Ave, Cambridge, MA 02139, USA. * * This protocol extension module was developed using information from * "Driver for Freecom USB/IDE adaptor" in Linux usb storage driver and * "Mac OS X driver for the Freecom Traveller CD writer". * * $Source: /cvsroot/sis4be/usb_scsi/freecom/freecom.c,v $ * $Author: zharik $ * $Revision: 1.11 $ * $Date: 2005/04/01 22:39:23 $ * */ #include "usb_scsi.h" #include <malloc.h> #include "device_info.h" #include "proto_module.h" #define FREECOM_MODULE_NAME "freecom" #define FREECOM_PROTOCOL_MODULE_NAME \ MODULE_PREFIX FREECOM_MODULE_NAME PROTOCOL_SUFFIX /** \struct:fcm_command */ typedef struct { uint8 type; /* block type. */ #define FCMT_ATAPI 0x21 /* send command. low bit indicates waiting for interrupt */ #define FCMT_STATUS 0x20 /* request for status */ #define FCMT_IN 0x81 /* request read data transfer. */ #define FCMT_OUT 0x01 /* request write data transfer */ #define FCMT_REG_IN 0xC0 /* read value from IDE regsiter */ #define FCMT_REG_OUT 0x40 /* write value to IDE register */ /* to use FCMT_REG_ combine it with register */ #define FCMR_DATA 0x10 /* data register */ /* ... */ #define FCMR_CMD 0x16 /* status-command register */ #define FCMR_INT 0x17 /* interrupt-error register */ uint8 timeout; /* timeout (seconds?) */ #define FCMTO_DEF 0xfe /* default timeout */ #define FCMTO_TU 0x14 /* timeout for TEST UNIT READY command */ union{ uint8 cmd[12]; /* An ATAPI command. */ uint32 count; /* number of bytes to transfer. */ uint16 reg_val; /* Value to write to IDE register. */ uint8 pad[62]; /* Padding Data. All FREECOM commands are 64 bytes long */ }_PACKED data; }_PACKED fcm_command; /** \struct:fcm_status */ typedef struct { uint8 status; #define FCMS_BSY 0x80 /* device is busy */ #define FCMS_DRDY 0x40 /* */ #define FCMS_DMA 0x20 /* */ #define FCMS_SEEK 0x10 /* */ #define FCMS_DRQ 0x08 /* */ #define FCMS_CORR 0x04 /* */ #define FCMS_INTR 0x02 /*FREECOM specific: use obsolete bit*/ #define FCMS_CHECK 0x01 /* device is in error condition */ uint8 reason; #define FCMR_REL 0x04 /* */ #define FCMR_IO 0x02 /* */ #define FCMR_COD 0x01 /* */ uint16 count; }_PACKED fcm_status; // Timeout value (in us) for the freecom packet USB BulkRead and BulkWrite functions #define FREECOM_USB_TIMEOUT 30000000 /** \fn: \param udi: \param st: \return: */ void trace_status(usb_device_info *udi, const fcm_status *st) { char ch_status[] = "BDFSRCIE"; char ch_reason[] = ".....RIC"; int i = 0; for(; i < 8; i++){ if(!(st->status & (1 << i))) ch_status[7 - i] = '.'; if(!(st->reason & (1 << i))) ch_reason[7 - i] = '.'; } PTRACE(udi, "FCM:Status:{%s; Reason:%s; Count:%d}\n", ch_status, ch_reason, st->count); } /** \fn:freecom_initialize \param udi: device on wich we should perform initialization \return:error code if initialization failed or B_OK if it passed initialize procedure. */ status_t freecom_initialize(usb_device_info *udi) { status_t status = B_OK; #define INIT_BUFFER_SIZE 0x20 char buffer[INIT_BUFFER_SIZE + 1]; size_t len = 0; if(B_OK != (status = (*udi->usb_m->send_request)(udi->device, USB_REQTYPE_DEVICE_IN | USB_REQTYPE_VENDOR, 0x4c, 0x4346, 0x0, INIT_BUFFER_SIZE, buffer, &len))) { PTRACE_ALWAYS(udi, "FCM:init[%d]: init failed: %08x\n", udi->dev_num, status); } else { buffer[len] = 0; PTRACE(udi, "FCM:init[%d]: init '%s' OK\n", udi->dev_num, buffer); } if(B_OK != (status = (*udi->usb_m->send_request)(udi->device, USB_REQTYPE_DEVICE_OUT | USB_REQTYPE_VENDOR, 0x4d, 0x24d8, 0x0, 0, 0, &len))) { PTRACE_ALWAYS(udi, "FCM:init[%d]: reset on failed:%08x\n", udi->dev_num, status); } snooze(250000); if(B_OK != (status = (*udi->usb_m->send_request)(udi->device, USB_REQTYPE_DEVICE_OUT | USB_REQTYPE_VENDOR, 0x4d, 0x24f8, 0x0, 0, 0, &len))) { PTRACE_ALWAYS(udi, "FCM:init[%d]: reset off failed:%08x\n", udi->dev_num, status); } snooze(3 * 1000000); return status; } /** \fn:freecom_reset \param udi: device on wich we should perform reset \return:error code if reset failed or B_OK if it passed reset procedure. */ status_t freecom_reset(usb_device_info *udi) { status_t status = B_OK; /* not required ? */ return status; } /** \fn:usb_callback \param cookie:??? \param status:??? \param data:??? \param actual_len:??? \return:??? ??? */ static void usb_callback(void *cookie, uint32 status, void *data, uint32 actual_len) { if(cookie){ usb_device_info *udi = (usb_device_info *)cookie; // PTRACE(udi, "FCM:usb_callback:status:0x%08x,len:%d\n", status, actual_len); udi->status = status; udi->data = data; udi->actual_len = actual_len; if(udi->status != B_CANCELED) release_sem(udi->trans_sem); } } /** \fn:queue_bulk \param udi: device for which que_bulk request is performed \param buffer: data buffer, used in bulk i/o operation \param len: length of data buffer \param b_in: is "true" if input (device->host) data transfer, "false" otherwise \return: status of operation. performs queue_bulk USB request for corresponding pipe and handle timeout of this operation. */ static status_t queue_bulk(usb_device_info *udi, void *buffer, size_t len, bool b_in) { status_t status = B_OK; usb_pipe pipe = b_in ? udi->pipe_in : udi->pipe_out; status = (*udi->usb_m->queue_bulk)(pipe, buffer, len, usb_callback, udi); if(status != B_OK){ PTRACE_ALWAYS(udi, "FCM:queue_bulk:failed:%08x\n", status); } else { status = acquire_sem_etc(udi->trans_sem, 1, B_RELATIVE_TIMEOUT, FREECOM_USB_TIMEOUT/*udi->trans_timeout*/); if(status != B_OK){ PTRACE_ALWAYS(udi, "FCM:queue_bulk:acquire_sem_etc failed:%08x\n", status); (*udi->usb_m->cancel_queued_transfers)(pipe); } } return status; } /** \fn:write_command */ static status_t write_command(usb_device_info *udi, uint8 type, uint8 *cmd, uint8 timeout) { status_t status = B_OK; /* initialize and fill in command block*/ fcm_command fc = { .type = type, .timeout = FCMTO_DEF, }; if(0 != cmd){ memcpy(fc.data.cmd, cmd, sizeof(fc.data.cmd)); if(cmd[0] == 0x00){ fc.timeout = FCMTO_TU; } } PTRACE(udi, "FCM:FC:{Type:0x%02x; TO:%d;}\n", fc.type, fc.timeout); udi->trace_bytes("FCM:FC::Cmd:\n", fc.data.cmd, sizeof(fc.data.cmd)); udi->trace_bytes("FCM:FC::Pad:\n", fc.data.pad, sizeof(fc.data.pad)); PTRACE(udi,"sizeof:%d\n",sizeof(fc)); /* send command block to device */ status = queue_bulk(udi, &fc, sizeof(fc), false); if(status != B_OK || udi->status != B_OK){ PTRACE_ALWAYS(udi, "FCM:write_command failed:status:%08x usb status:%08x\n", status, udi->status); //(*udi->protocol_m->reset)(udi); status = B_CMD_WIRE_FAILED; } return status; } /** \fn:read_status */ static status_t read_status(usb_device_info *udi, fcm_status *fst) { status_t status = B_OK; do{ /* cleanup structure */ memset(fst, 0, sizeof(fcm_status)); /* read status */ status = queue_bulk(udi, fst, sizeof(fcm_status), true); if(status != B_OK || udi->status != B_OK){ PTRACE_ALWAYS(udi, "FCM:read_status failed:" "status:%08x usb status:%08x\n", status, udi->status); //(*udi->protocol_m->reset)(udi); status = B_CMD_WIRE_FAILED; break; } if(udi->actual_len != sizeof(fcm_status)){ PTRACE_ALWAYS(udi, "FCM:read_status failed:requested:%d, readed %d bytes\n", sizeof(fcm_status), udi->actual_len); status = B_CMD_WIRE_FAILED; break; } /* trace readed status info. if required. */ trace_status(udi, fst); if(fst->status & FCMS_BSY){ PTRACE(udi, "FCM:read_status:Timeout. Poll device with another status request.\n"); if(B_OK != (status = write_command(udi, FCMT_STATUS, 0, 0))){ PTRACE_ALWAYS(udi, "FCM:read_status failed:write_command_block failed %08x\n", status); break; } } }while(fst->status & FCMS_BSY); /* repeat until device is busy */ return status; } /** \fn:request_transfer */ static status_t request_transfer(usb_device_info *udi, uint8 type, uint32 length, uint8 timeout) { status_t status = B_OK; /* initialize and fill in Command Block */ fcm_command fc = { .type = type, .timeout = timeout, }; fc.data.count = length; PTRACE(udi, "FCM:FC:{Type:0x%02x; TO:%d; Count:%d}\n", fc.type, fc.timeout, fc.data.count); udi->trace_bytes("FCM:FC::Pad:\n", fc.data.pad, sizeof(fc.data.pad)); PTRACE(udi,"sizeof:%d\n",sizeof(fc)); /* send command block to device */ status = queue_bulk(udi, &fc, sizeof(fc), false); if(status != B_OK || udi->status != B_OK){ PTRACE_ALWAYS(udi, "FCM:request_transfer:fc send failed:" "status:%08x usb status:%08x\n", status, udi->status); status = B_CMD_WIRE_FAILED; } return status; } /** \fn:transfer_sg \param udi: corresponding device \param data_sg: io vectors array with data to transfer \param sglist_count: count of entries in io vector array \param offset: \param block_len: \param b_in: direction of data transfer) */ static status_t transfer_sg(usb_device_info *udi, iovec *data_sg, int32 sglist_count, int32 offset, int32 *block_len, bool b_in) { status_t status = B_OK; usb_pipe pipe = (b_in) ? udi->pipe_in : udi->pipe_out; int32 off = offset; int32 to_xfer = *block_len; /* iterate through SG list */ int i = 0; for(; i < sglist_count && to_xfer > 0; i++) { if(off < data_sg[i].iov_len) { int len = min(to_xfer, (data_sg[i].iov_len - off)); char *buf = ((char *)data_sg[i].iov_base) + off; /* transfer linear block of data to/from device */ if(B_OK == (status = (*udi->usb_m->queue_bulk)(pipe, buf, len, usb_callback, udi))) { status = acquire_sem_etc(udi->trans_sem, 1, B_RELATIVE_TIMEOUT, FREECOM_USB_TIMEOUT); if(status == B_OK){ status = udi->status; if(B_OK != status){ PTRACE_ALWAYS(udi, "FCM:transfer_sg:usb transfer status is not OK:%08x\n", status); } } else { PTRACE_ALWAYS(udi, "FCM:transfer_sg:acquire_sem_etc failed:%08x\n", status); goto finalize; } } else { PTRACE_ALWAYS(udi, "FCM:transfer_sg:queue_bulk failed:%08x\n", status); goto finalize; } /*check amount of transferred data*/ if(len != udi->actual_len){ PTRACE_ALWAYS(udi, "FCM:transfer_sg:WARNING!!!Length reported:%d required:%d\n", udi->actual_len, len); } /* handle offset logic */ to_xfer -= len; off = 0; } else { off -= data_sg[i].iov_len; } } finalize: *block_len -= to_xfer; return (B_OK != status) ? B_CMD_WIRE_FAILED : status; } static status_t transfer_data(usb_device_info *udi, iovec *data_sg, int32 sglist_count, int32 transfer_length, int32 *residue, fcm_status *fst, bool b_in) { status_t status = B_OK; int32 readed_len = 0; uint8 xfer_type = b_in ? FCMT_IN : FCMT_OUT; int32 block_len = (FCMR_COD == (fst->reason & FCMR_COD)) ? transfer_length : fst->count; /* Strange situation with SCSIProbe - device say about 6 bytes available for 5-bytes request. Read 5 and all is ok. Hmm... */ if(block_len > transfer_length){ PTRACE_ALWAYS(udi, "FCM:transfer_data:TRUNCATED! " "requested:%d available:%d.\n", transfer_length, block_len); block_len = transfer_length; } /* iterate until data will be transferred */ while(readed_len < transfer_length && block_len > 0){ /* send transfer block */ if(B_OK != (status = request_transfer(udi, xfer_type, block_len, 0))){ goto finalize; } /* check if data available/awaited */ if(FCMS_DRQ != (fst->status & FCMS_DRQ)){ PTRACE_ALWAYS(udi, "FCM:transfer_data:device doesn't want to transfer anything!!!\n"); status = B_CMD_FAILED; goto finalize; } /* check the device state */ if(!((fst->reason & FCMR_REL) == 0 && (fst->reason & FCMR_IO) == ((b_in) ? FCMR_IO : 0) && (fst->reason & FCMR_COD) == 0)) { PTRACE_ALWAYS(udi, "FCM:transfer_data:device doesn't ready to transfer?\n"); status = B_CMD_FAILED; goto finalize; } /* transfer scatter/gather safely only for length bytes at specified offset */ if(B_OK != (status = transfer_sg(udi, data_sg, sglist_count, readed_len, &block_len, b_in))) { goto finalize; } /* read status */ if(B_OK != (status = read_status(udi, fst))){ goto finalize; } /* check device error state */ if(fst->status & FCMS_CHECK){ PTRACE(udi, "FCM:transfer_data:data transfer failed?\n", fst->status); status = B_CMD_FAILED; goto finalize; } /* we have read block successfully */ readed_len += block_len; /* check device state and amount of data */ if((fst->reason & FCMR_COD) == FCMR_COD){ #if 0 /* too frequently reported - disabled to prevent log trashing */ if(readed_len < transfer_length){ PTRACE_ALWAYS(udi, "FCM:transfer_data:Device had LESS data that we wanted.\n"); } #endif break; /* exit iterations - device has finished the talking */ } else { if(readed_len >= transfer_length){ PTRACE_ALWAYS(udi, "FCM:transfer_data:Device had MORE data that we wanted.\n"); break; } block_len = fst->count; /* still have something to read */ } } /* calculate residue */ *residue -= readed_len; if(*residue < 0) *residue = 0; /* TODO: consistency between SG length and transfer length - in MODE_SENSE_10 converted commands f.example ... */ PTRACE(udi,"FCM:transfer_data:was requested:%d, residue:%d\n", transfer_length, *residue); finalize: return status; /* TODO: MUST return B_CMD_*** error codes !!!!! */ } /** \fn:freecom_transfer \param udi: corresponding device \param cmd: SCSI command to be performed on USB device \param cmdlen: length of SCSI command \param data_sg: io vectors array with data to transfer \param sglist_count: count of entries in io vector array \param transfer_len: overall length of data to be transferred \param dir: direction of data transfer \param ccbio: CCB_SCSIIO struct for original SCSI command \param cb: callback to handle of final stage of command performing (autosense \ request etc.) transfer procedure for bulk-only protocol. Performs SCSI command on USB device [2] */ void freecom_transfer(usb_device_info *udi, uint8 *cmd, uint8 cmdlen, iovec*sg_data, int32 sg_count, int32 transfer_len, EDirection dir, CCB_SCSIIO *ccbio, ud_transfer_callback cb) { status_t command_status = B_CMD_WIRE_FAILED; int32 residue = transfer_len; fcm_status fst = {0}; /* Current BeOS scsi_cd driver bombs us with lot of MODE_SENSE/MODE_SELECT commands. Unfortunately some of them hangs the Freecom firmware. Try to ignore translated ones */ #if 1 if((MODE_SENSE_10 == cmd[0] && 0x0e == cmd[2]) || (MODE_SELECT_10 == cmd[0] && 0x10 == cmd[1])) { uint8 *cmd_org = 0; /* set the command data pointer */ if(ccbio->cam_ch.cam_flags & CAM_CDB_POINTER){ cmd_org = ccbio->cam_cdb_io.cam_cdb_ptr; }else{ cmd_org = ccbio->cam_cdb_io.cam_cdb_bytes; } if(cmd_org[0] != cmd[0]){ if(MODE_SENSE_10 == cmd[0]){ /* emulate answer - return empty pages */ scsi_mode_param_header_10 *hdr = (scsi_mode_param_header_10*)sg_data[0].iov_base; memset(hdr, 0, sizeof(scsi_mode_param_header_10)); hdr->mode_data_len[1] = 6; PTRACE(udi, "FCM:freecom_transfer:MODE_SENSE_10 ignored %02x->02x\n", cmd_org[0], cmd[0]); } else { PTRACE(udi, "FCM:freecom_transfer:MODE_SELECT_10 ignored %02x->%02x\n", cmd_org[0], cmd[0]); } command_status = B_OK; /* just say that command processed OK */ goto finalize; } } #endif /* write command to device */ if(B_OK != (command_status = write_command(udi, FCMT_ATAPI, cmd, 0))){ PTRACE_ALWAYS(udi, "FCM:freecom_transfer:" "send command failed. Status:%08x\n", command_status); goto finalize; } /* obtain status */ if(B_OK != (command_status = read_status(udi, &fst))){ PTRACE_ALWAYS(udi, "FCM:freecom_transfer:" "read status failed. Status:%08x\n", command_status); goto finalize; } /* check device error state */ if(fst.status & FCMS_CHECK){ PTRACE_ALWAYS(udi, "FCM:freecom_transfer:FST.Status is not OK\n"); command_status = B_CMD_FAILED; goto finalize; } /* transfer data */ if(transfer_len != 0x0 && dir != eDirNone){ command_status = transfer_data(udi, sg_data, sg_count, transfer_len, &residue, &fst, (eDirIn == dir)); } finalize: /* finalize transfer */ cb(udi, ccbio, residue, command_status); } static status_t std_ops(int32 op, ...) { switch(op) { case B_MODULE_INIT: return B_OK; case B_MODULE_UNINIT: return B_OK; default: return B_ERROR; } } static protocol_module_info freecom_protocol_module = { { FREECOM_PROTOCOL_MODULE_NAME, 0, std_ops }, freecom_initialize, freecom_reset, freecom_transfer, }; _EXPORT protocol_module_info *modules[] = { &freecom_protocol_module, NULL };
8,947
567
<reponame>JackieZhai/TracKit # ------------------------------------------------------------------------------ # Copyright (c) Microsoft # Licensed under the MIT License. # Written by <NAME> (<EMAIL>) # ------------------------------------------------------------------------------ import _init_paths import os import cv2 import random import argparse import numpy as np import models.models as models from os.path import exists, join from tracker.siamfc import SiamFC from easydict import EasyDict as edict from utils.utils import load_pretrain, cxy_wh_2_rect, get_axis_aligned_bbox, load_dataset, poly_iou # for GENE tuning from lib.core.eval_otb import eval_auc_tune def parse_args(): """ args for fc testing. """ parser = argparse.ArgumentParser(description='SiamDW') parser.add_argument('--arch', dest='arch', default='SiamDW', help='backbone architecture') parser.add_argument('--resume', default='snapshot/SiamDW.pth', type=str, help='pretrained model') parser.add_argument('--dataset', default='VOT2017', help='dataset test') parser.add_argument('--epoch_test', default=False, type=bool, help='multi-gpu epoch test flag') args = parser.parse_args() return args def track(tracker, net, video, args): start_frame, toc = 0, 0 # save result to evaluate if args.epoch_test: suffix = args.resume.split('/')[-1] suffix = suffix.split('.')[0] tracker_path = os.path.join('result', args.dataset, args.arch + suffix) else: tracker_path = os.path.join('result', args.dataset, args.arch) if not os.path.exists(tracker_path): os.makedirs(tracker_path) if 'VOT' in args.dataset: baseline_path = os.path.join(tracker_path, 'baseline') video_path = os.path.join(baseline_path, video['name']) if not os.path.exists(video_path): os.makedirs(video_path) result_path = os.path.join(video_path, video['name'] + '_001.txt') else: result_path = os.path.join(tracker_path, '{:s}.txt'.format(video['name'])) if os.path.exists(result_path): return # for mult-gputesting regions = [] image_files, gt = video['image_files'], video['gt'] for f, image_file in enumerate(image_files): im = cv2.imread(image_file) if len(im.shape) == 2: im = cv2.cvtColor(im, cv2.COLOR_GRAY2BGR) # align with training tic = cv2.getTickCount() if f == start_frame: # init cx, cy, w, h = get_axis_aligned_bbox(gt[f]) target_pos = np.array([cx, cy]) target_sz = np.array([w, h]) state = tracker.init(im, target_pos, target_sz, net) # init tracker location = cxy_wh_2_rect(state['target_pos'], state['target_sz']) regions.append(1 if 'VOT' in args.dataset else gt[f]) elif f > start_frame: # tracking state = tracker.track(state, im) location = cxy_wh_2_rect(state['target_pos'], state['target_sz']) b_overlap = poly_iou(gt[f], location) if 'VOT' in args.dataset else 1 if b_overlap > 0: regions.append(location) else: regions.append(2) start_frame = f + 5 else: regions.append(0) toc += cv2.getTickCount() - tic with open(result_path, "w") as fin: if 'VOT' in args.dataset: for x in regions: if isinstance(x, int): fin.write("{:d}\n".format(x)) else: p_bbox = x.copy() fin.write(','.join([str(i) for i in p_bbox]) + '\n') else: for x in regions: p_bbox = x.copy() fin.write( ','.join([str(i + 1) if idx == 0 or idx == 1 else str(i) for idx, i in enumerate(p_bbox)]) + '\n') toc /= cv2.getTickFrequency() print('Video: {:12s} Time: {:2.1f}s Speed: {:3.1f}fps'.format(video['name'], toc, f / toc)) def main(): args = parse_args() # prepare model net = models.__dict__[args.arch]() net = load_pretrain(net, args.resume) net.eval() net = net.cuda() # prepare video dataset = load_dataset(args.dataset) video_keys = list(dataset.keys()).copy() # prepare tracker info = edict() info.arch = args.arch info.dataset = args.dataset info.epoch_test = args.epoch_test tracker = SiamFC(info) # tracking all videos in benchmark for video in video_keys: track(tracker, net, dataset[video], args) if __name__ == '__main__': main()
2,226
12,706
[ { "id": 1, "description": "", "name": "dockers", "name_with_namespace": "Library / dockers", "path": "dockers", "path_with_namespace": "library/dockers", "created_at": "2019-01-17T09:47:07.504Z", "default_branch": "master", "tag_list": [], "avatar_url": null, "star_count": 0, "forks_count": 0, "last_activity_at": "2019-06-09T15:18:10.045Z", "empty_repo": false, "archived": false, "visibility": "private", "resolve_outdated_diff_discussions": false, "container_registry_enabled": true, "issues_enabled": true, "merge_requests_enabled": true, "wiki_enabled": true, "jobs_enabled": true, "snippets_enabled": true, "shared_runners_enabled": true, "lfs_enabled": true, "creator_id": 1, "forked_from_project": {}, "import_status": "finished", "open_issues_count": 0, "ci_default_git_depth": null, "public_jobs": true, "ci_config_path": null, "shared_with_groups": [], "only_allow_merge_if_pipeline_succeeds": false, "request_access_enabled": false, "only_allow_merge_if_all_discussions_are_resolved": false, "printing_merge_request_link_enabled": true, "merge_method": "merge", "external_authorization_classification_label": "", "permissions": { "project_access": null, "group_access": null }, "mirror": false }, { "id": 5, "description": "", "name": "example-dockers", "name_with_namespace": "Library / example-dockers", "path": "example-dockers", "path_with_namespace": "library/example-dockers", "created_at": "2019-01-17T09:47:07.504Z", "default_branch": "master", "tag_list": [], "avatar_url": null, "star_count": 0, "forks_count": 0, "last_activity_at": "2019-06-09T15:18:10.045Z", "empty_repo": false, "archived": false, "visibility": "private", "resolve_outdated_diff_discussions": false, "container_registry_enabled": true, "issues_enabled": true, "merge_requests_enabled": true, "wiki_enabled": true, "jobs_enabled": true, "snippets_enabled": true, "shared_runners_enabled": true, "lfs_enabled": true, "creator_id": 1, "forked_from_project": {}, "import_status": "finished", "open_issues_count": 0, "ci_default_git_depth": null, "public_jobs": true, "ci_config_path": null, "shared_with_groups": [], "only_allow_merge_if_pipeline_succeeds": false, "request_access_enabled": false, "only_allow_merge_if_all_discussions_are_resolved": false, "printing_merge_request_link_enabled": true, "merge_method": "merge", "external_authorization_classification_label": "", "permissions": { "project_access": null, "group_access": null }, "mirror": false } ]
1,234
2,023
<gh_stars>1000+ // Copyright 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "sling/task/accumulator.h" #include "sling/base/logging.h" #include "sling/string/numbers.h" #include "sling/task/reducer.h" #include "sling/util/fingerprint.h" #include "sling/util/mutex.h" namespace sling { namespace task { void Accumulator::Init(Channel *output, int num_buckets) { output_ = output; buckets_.clear(); buckets_.resize(num_buckets); Task *task = output->producer().task(); num_slots_used_ = task->GetCounter("accumulator_slots_used"); num_collisions_ = task->GetCounter("accumulator_collisions"); } void Accumulator::Increment(Text key, int64 count) { uint64 fp = Fingerprint(key.data(), key.size()); uint32 b = (fp ^ (fp >> 32)) % buckets_.size(); MutexLock lock(&mu_); Bucket &bucket = buckets_[b]; if (fp != bucket.hash || key != bucket.key) { if (bucket.count != 0) { output_->Send(new Message(bucket.key, SimpleItoa(bucket.count))); bucket.count = 0; num_collisions_->Increment(); } else { num_slots_used_->Increment(); } bucket.hash = fp; bucket.key.assign(key.data(), key.size()); } bucket.count += count; } void Accumulator::Increment(uint64 key, int64 count) { uint64 b = (key ^ (key >> 32)) % buckets_.size(); MutexLock lock(&mu_); Bucket &bucket = buckets_[b]; if (key != bucket.hash) { if (bucket.count != 0) { output_->Send(new Message(bucket.key, SimpleItoa(bucket.count))); bucket.count = 0; num_collisions_->Increment(); } else { num_slots_used_->Increment(); } bucket.hash = key; bucket.key = SimpleItoa(key); } bucket.count += count; } void Accumulator::Flush() { MutexLock lock(&mu_); for (Bucket &bucket : buckets_) { if (bucket.count != 0) { output_->Send(new Message(bucket.key, SimpleItoa(bucket.count))); bucket.count = 0; } bucket.key.clear(); } } void SumReducer::Start(Task *task) { Reducer::Start(task); task->Fetch("threshold", &threshold_); if (threshold_ > 0) { num_keys_discarded_ = task->GetCounter("keys_discarded"); num_counts_discarded_ = task->GetCounter("counts_discarded"); } } void SumReducer::Reduce(const ReduceInput &input) { int64 sum = 0; for (Message *m : input.messages()) { int64 count; const Slice &value = m->value(); CHECK(safe_strto64_base(value.data(), value.size(), &count, 10)); sum += count; } if (sum >= threshold_) { Aggregate(input.shard(), input.key(), sum); } else { if (num_keys_discarded_) num_keys_discarded_->Increment(); if (num_counts_discarded_) num_counts_discarded_->Increment(sum); } } void SumReducer::Aggregate(int shard, const Slice &key, uint64 sum) { Output(shard, new Message(key, SimpleItoa(sum))); } REGISTER_TASK_PROCESSOR("sum-reducer", SumReducer); } // namespace task } // namespace sling
1,286
1,858
<gh_stars>1000+ /* * Tencent is pleased to support the open source community by making TENCENT SOTER available. * Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved. * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at * https://opensource.org/licenses/BSD-3-Clause * 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.tencent.soter.core.model; import android.util.Base64; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.ByteArrayInputStream; import java.security.cert.Certificate; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.ArrayList; /** * The public key model for App Secure Key and Auth Key. It consists the whole JSON that wrapper in the * TEE, and the signature of the JSON generated in TEE. Developers should upload the JSON and signature to server */ @SuppressWarnings("unused") public class SoterPubKeyModel { private static final String TAG = "Soter.SoterPubKeyModel"; public static final String JSON_KEY_PUBLIC = "pub_key"; public static final String JSON_KEY_COUNTER = "counter"; public static final String JSON_KEY_CPU_ID = "cpu_id"; public static final String JSON_KEY_UID = "uid"; public static final String JSON_KEY_CERTS = "certs"; private long counter = -1; private int uid = -1; private String cpu_id = ""; private String pub_key_in_x509 = ""; private String rawJson = ""; private ArrayList<String> certs = null; @Override public String toString() { return "SoterPubKeyModel{" + "counter=" + counter + ", uid=" + uid + ", cpu_id='" + cpu_id + '\'' + ", pub_key_in_x509='" + pub_key_in_x509 + '\'' + ", rawJson='" + rawJson + '\'' + ", signature='" + signature + '\'' + '}'; } private String signature = ""; @SuppressWarnings("unused") public SoterPubKeyModel(long counter, int uid, String cpu_id, String pub_key_in_x509, String signature) { this.counter = counter; this.uid = uid; this.cpu_id = cpu_id; this.pub_key_in_x509 = pub_key_in_x509; this.signature = signature; } public SoterPubKeyModel(String rawJson, String signature) { JSONObject jsonObj; setRawJson(rawJson); try { jsonObj = new JSONObject(rawJson); // this.rawJson = jsonObj.toString(); if(jsonObj.has(JSON_KEY_CERTS)){ JSONArray certJsonArray = jsonObj.optJSONArray(JSON_KEY_CERTS); if (certJsonArray.length() < 2) { SLogger.e(TAG,"certificates train not enough"); } SLogger.i(TAG,"certs size: [%d]", certJsonArray.length()); certs = new ArrayList<String>(); for (int i = 0; i < certJsonArray.length(); i++) { String certText = certJsonArray.getString(i); certs.add(certText); } CertificateFactory factory = CertificateFactory.getInstance("X.509"); X509Certificate askCertificate = (X509Certificate) factory.generateCertificate(new ByteArrayInputStream(certs.get(0).getBytes())); loadDeviceInfo(askCertificate); jsonObj.put(JSON_KEY_CPU_ID, cpu_id); jsonObj.put(JSON_KEY_UID, uid); jsonObj.put(JSON_KEY_COUNTER, counter); setRawJson(jsonObj.toString()); }else{ this.counter = jsonObj.optLong(JSON_KEY_COUNTER); this.uid = jsonObj.optInt(JSON_KEY_UID); this.cpu_id = jsonObj.optString(JSON_KEY_CPU_ID); this.pub_key_in_x509 = jsonObj.optString(JSON_KEY_PUBLIC); } } catch (Exception e) { SLogger.e(TAG, "soter: pub key model failed"); } this.signature = signature; } public SoterPubKeyModel(Certificate[] certificates){ try { if(certificates != null){ ArrayList<String> certTexts = new ArrayList<String>(); JSONArray jsonArray = new JSONArray(); for (int i = 0; i < certificates.length; i++) { Certificate certificate = certificates[i]; String certText = Base64.encodeToString(certificate.getEncoded(), Base64.NO_WRAP); certText = CertUtil.format(certificate); if (i == 0){ loadDeviceInfo((X509Certificate)certificate); } jsonArray.put(certText); certTexts.add(certText); } certs = certTexts; JSONObject jsonObj = new JSONObject(); jsonObj.put(JSON_KEY_CERTS, jsonArray); jsonObj.put(JSON_KEY_CPU_ID, cpu_id); jsonObj.put(JSON_KEY_UID, uid); jsonObj.put(JSON_KEY_COUNTER, counter); setRawJson(jsonObj.toString()); } }catch (Exception e){ SLogger.e(TAG, "soter: pub key model failed"); } } private void loadDeviceInfo(X509Certificate attestationCert) { try{ CertUtil.extractAttestationSequence(attestationCert,this); }catch (Exception e){ SLogger.e(TAG, "soter: loadDeviceInfo from attestationCert failed" + e.getStackTrace()); } } public void setCounter(long counter) { this.counter = counter; } public void setUid(int uid) { this.uid = uid; } public void setCpu_id(String cpu_id) { this.cpu_id = cpu_id; } public void setPub_key_in_x509(String pub_key_in_x509) { this.pub_key_in_x509 = pub_key_in_x509; } public void setSignature(String signature) { this.signature = signature; } public long getCounter() { return counter; } public int getUid() { return uid; } public String getCpu_id() { return cpu_id; } public String getPub_key_in_x509() { return pub_key_in_x509; } public String getSignature() { return signature; } public String getRawJson() { return rawJson; } public void setRawJson(String rawJson) { this.rawJson = rawJson; } }
3,071
1,960
# # Copyright (c) 2017 Intel Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import random import gym import numpy as np from gym import spaces class BitFlip(gym.Env): metadata = { 'render.modes': ['human', 'rgb_array'], 'video.frames_per_second': 30 } def __init__(self, bit_length=16, max_steps=None, mean_zero=False): super(BitFlip, self).__init__() if bit_length < 1: raise ValueError('bit_length must be >= 1, found {}'.format(bit_length)) self.bit_length = bit_length self.mean_zero = mean_zero if max_steps is None: # default to bit_length self.max_steps = bit_length elif max_steps == 0: self.max_steps = None else: self.max_steps = max_steps # spaces documentation: https://gym.openai.com/docs/ self.action_space = spaces.Discrete(bit_length) self.observation_space = spaces.Dict({ 'state': spaces.Box(low=0, high=1, shape=(bit_length, )), 'desired_goal': spaces.Box(low=0, high=1, shape=(bit_length, )), 'achieved_goal': spaces.Box(low=0, high=1, shape=(bit_length, )) }) self.reset() def _terminate(self): return (self.state == self.goal).all() or self.steps >= self.max_steps def _reward(self): return -1 if (self.state != self.goal).any() else 0 def step(self, action): # action is an int in the range [0, self.bit_length) self.state[action] = int(not self.state[action]) self.steps += 1 return (self._get_obs(), self._reward(), self._terminate(), {}) def reset(self): self.steps = 0 self.state = np.array([random.choice([1, 0]) for _ in range(self.bit_length)]) # make sure goal is not the initial state self.goal = self.state while (self.goal == self.state).all(): self.goal = np.array([random.choice([1, 0]) for _ in range(self.bit_length)]) return self._get_obs() def _mean_zero(self, x): if self.mean_zero: return (x - 0.5) / 0.5 else: return x def _get_obs(self): return { 'state': self._mean_zero(self.state), 'desired_goal': self._mean_zero(self.goal), 'achieved_goal': self._mean_zero(self.state) } def render(self, mode='human', close=False): observation = np.zeros((20, 20 * self.bit_length, 3)) for bit_idx, (state_bit, goal_bit) in enumerate(zip(self.state, self.goal)): # green if the bit matches observation[:, bit_idx * 20:(bit_idx + 1) * 20, 1] = (state_bit == goal_bit) * 255 # red if the bit doesn't match observation[:, bit_idx * 20:(bit_idx + 1) * 20, 0] = (state_bit != goal_bit) * 255 return observation
1,438
1,330
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.opensymphony.xwork2.util.classloader; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.File; import java.io.FileInputStream; /** * Reads a class from disk * class taken from Apache JCI */ public final class FileResourceStore extends AbstractResourceStore { private static final Logger LOG = LogManager.getLogger(FileResourceStore.class); public FileResourceStore(final File file) { super(file); } public byte[] read(final String pResourceName) { FileInputStream fis = null; try { File file = getFile(pResourceName); byte[] data = new byte[(int) file.length()]; fis = new FileInputStream(file); fis.read(data); return data; } catch (Exception e) { LOG.debug("Unable to read file [{}]", pResourceName, e); return null; } finally { closeQuietly(fis); } } private File getFile(final String pResourceName) { final String fileName = pResourceName.replace('/', File.separatorChar); return new File(file, fileName); } }
674
778
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Project includes #include "refinement_modeler.h" namespace Kratos { ///@name Stages ///@{ void RefinementModeler::PrepareGeometryModel() { const std::string DataFileName = mParameters.Has("refinements_file_name") ? mParameters["refinements_file_name"].GetString() : "refinements.iga.json"; KRATOS_INFO_IF("::[RefinementModeler]::", mEchoLevel > 0) << "Refining model by: " << DataFileName << std::endl; const Parameters refinements_parameters = ReadParamatersFile(DataFileName); ApplyRefinements(refinements_parameters); } void RefinementModeler::ApplyRefinements( const Parameters rParameters) const { KRATOS_ERROR_IF_NOT(rParameters.Has("refinements")) << "Parameters do not have refinements section.\n" << rParameters << std::endl; KRATOS_ERROR_IF_NOT(rParameters["refinements"].IsArray()) << "refinements section need to be of type array.\n" << rParameters << std::endl; for (IndexType i = 0; i < rParameters["refinements"].size(); ++i) { ApplyRefinement(rParameters["refinements"][i]); } } void RefinementModeler::ApplyRefinement( const Parameters rParameters) const { KRATOS_ERROR_IF_NOT(rParameters.Has("model_part_name")) << "Missing \"model_part_name\" in refinements block.\n" << rParameters << std::endl; const std::string model_part_name = rParameters["model_part_name"].GetString(); ModelPart& r_model_part = mpModel->HasModelPart(model_part_name) ? mpModel->GetModelPart(model_part_name) : mpModel->CreateModelPart(model_part_name); // Generate the list of geometries, which are needed, here. GeometriesArrayType geometry_list; GetGeometryList(geometry_list, r_model_part, rParameters); KRATOS_ERROR_IF_NOT(rParameters.Has("parameters")) << "Missing \"parameters\" in refinements block.\n" << rParameters << std::endl; KRATOS_ERROR_IF_NOT(rParameters.Has("geometry_type")) << "Missing \"geometry_type\".\n" << rParameters << std::endl; if (rParameters["geometry_type"].GetString() == "NurbsSurface") { for (IndexType n = 0; n < geometry_list.size(); ++n) { auto p_nurbs_surface = (geometry_list[n].size() > 0) ? dynamic_pointer_cast<NurbsSurfaceGeometry<3, PointerVector<Node<3>>>>(geometry_list(n)) : dynamic_pointer_cast<NurbsSurfaceGeometry<3, PointerVector<Node<3>>>>(geometry_list(n)->pGetGeometryPart(GeometryType::BACKGROUND_GEOMETRY_INDEX)); if (rParameters["parameters"].Has("insert_nb_per_span_u")) { const IndexType nb_per_span_u = rParameters["parameters"]["insert_nb_per_span_u"].GetInt(); if (nb_per_span_u > 0) { std::vector<double> spans_local_space; p_nurbs_surface->SpansLocalSpace(spans_local_space, 0); std::vector<double> knots_to_insert_u; for (IndexType i = 0; i < spans_local_space.size() - 1; ++i) { const double delta_u = (spans_local_space[i + 1] - spans_local_space[i]) / (nb_per_span_u + 1); for (IndexType j = 1; j < nb_per_span_u + 1; ++j) { knots_to_insert_u.push_back(spans_local_space[i] + delta_u * j); } } KRATOS_INFO_IF("::[RefinementModeler]::ApplyRefinement", mEchoLevel > 1) << "Refining nurbs surface #" << p_nurbs_surface->Id() << " by inserting knots in u: " << knots_to_insert_u << std::endl; PointerVector<NodeType> PointsRefined; Vector KnotsURefined; Vector WeightsRefined; NurbsSurfaceRefinementUtilities::KnotRefinementU(*(p_nurbs_surface.get()), knots_to_insert_u, PointsRefined, KnotsURefined, WeightsRefined); // Recreate nodes in model part to ensure correct assignment of dofs IndexType node_id = (r_model_part.NodesEnd() - 1)->Id() + 1; for (IndexType i = 0; i < PointsRefined.size(); ++i) { if (PointsRefined(i)->Id() == 0) { PointsRefined(i) = r_model_part.CreateNewNode(node_id, PointsRefined[i][0], PointsRefined[i][1], PointsRefined[i][2]); node_id++; } } KRATOS_INFO_IF("::[RefinementModeler]::ApplyRefinement", mEchoLevel > 1) << "New knot vector: " << KnotsURefined << ", new weights vector: " << WeightsRefined << std::endl; p_nurbs_surface->SetInternals(PointsRefined, p_nurbs_surface->PolynomialDegreeU(), p_nurbs_surface->PolynomialDegreeV(), KnotsURefined, p_nurbs_surface->KnotsV(), WeightsRefined); } else { KRATOS_INFO_IF("::[RefinementModeler]::ApplyRefinement", mEchoLevel > 1) << "Trying to refine nurbs surface #" << p_nurbs_surface->Id() << " by inserting knots in u, however insert_nb_per_span_u is set to 0." << std::endl; } } if (rParameters["parameters"].Has("insert_nb_per_span_v")) { const IndexType nb_per_span_v = rParameters["parameters"]["insert_nb_per_span_v"].GetInt(); if (nb_per_span_v > 0) { std::vector<double> spans_local_space; p_nurbs_surface->SpansLocalSpace(spans_local_space, 1); std::vector<double> knots_to_insert_v; for (IndexType i = 0; i < spans_local_space.size() - 1; ++i) { const double delta_v = (spans_local_space[i + 1] - spans_local_space[i]) / (nb_per_span_v + 1); for (IndexType j = 1; j < nb_per_span_v + 1; ++j) { knots_to_insert_v.push_back(spans_local_space[i] + delta_v * j); } } KRATOS_INFO_IF("::[RefinementModeler]::ApplyRefinement", mEchoLevel > 1) << "Refining nurbs surface #" << p_nurbs_surface->Id() << " by inserting knots in v: " << knots_to_insert_v << std::endl; PointerVector<NodeType> PointsRefined; Vector KnotsVRefined; Vector WeightsRefined; NurbsSurfaceRefinementUtilities::KnotRefinementV(*(p_nurbs_surface.get()), knots_to_insert_v, PointsRefined, KnotsVRefined, WeightsRefined); // Recreate nodes in model part to ensure correct assignment of dofs IndexType node_id = (r_model_part.NodesEnd() - 1)->Id() + 1; for (IndexType i = 0; i < PointsRefined.size(); ++i) { if (PointsRefined(i)->Id() == 0) { PointsRefined(i) = r_model_part.CreateNewNode(node_id, PointsRefined[i][0], PointsRefined[i][1], PointsRefined[i][2]); node_id++; } } KRATOS_INFO_IF("::[RefinementModeler]::ApplyRefinement", mEchoLevel > 1) << "New knot vector: " << KnotsVRefined << ", new weights vector: " << WeightsRefined << std::endl; p_nurbs_surface->SetInternals(PointsRefined, p_nurbs_surface->PolynomialDegreeU(), p_nurbs_surface->PolynomialDegreeV(), p_nurbs_surface->KnotsU(), KnotsVRefined, WeightsRefined); } else { KRATOS_INFO_IF("::[RefinementModeler]::ApplyRefinement", mEchoLevel > 1) << "Trying to refine nurbs surface #" << p_nurbs_surface->Id() << " by inserting knots in v, however insert_nb_per_span_v is set to 0." << std::endl; } } } } } void RefinementModeler::GetGeometryList( GeometriesArrayType& rGeometryList, ModelPart& rModelPart, const Parameters rParameters) const { if (rParameters.Has("brep_id")) { rGeometryList.push_back(rModelPart.pGetGeometry(rParameters["brep_id"].GetInt())); } if (rParameters.Has("brep_ids")) { for (SizeType i = 0; i < rParameters["brep_ids"].size(); ++i) { rGeometryList.push_back(rModelPart.pGetGeometry(rParameters["brep_ids"][i].GetInt())); } } if (rParameters.Has("brep_name")) { rGeometryList.push_back(rModelPart.pGetGeometry(rParameters["brep_name"].GetString())); } if (rParameters.Has("brep_names")) { for (SizeType i = 0; i < rParameters["brep_names"].size(); ++i) { rGeometryList.push_back(rModelPart.pGetGeometry(rParameters["brep_names"][i].GetString())); } } KRATOS_ERROR_IF(rGeometryList.size() == 0) << "Empty geometry list. Either \"brep_id\", \"brep_ids\", \"brep_name\" or \"brep_names\" are the possible options." << std::endl; } /// Reads in a json formatted file and returns its KratosParameters instance. Parameters RefinementModeler::ReadParamatersFile( const std::string& rDataFileName) const { // Check if rDataFileName ends with ".cad.json" and add it if needed. const std::string data_file_name = (rDataFileName.compare(rDataFileName.size() - 9, 9, ".iga.json") != 0) ? rDataFileName + ".iga.json" : rDataFileName; std::ifstream infile(data_file_name); KRATOS_ERROR_IF_NOT(infile.good()) << "Physics fil: " << data_file_name << " cannot be found." << std::endl; KRATOS_INFO_IF("ReadParamatersFile", mEchoLevel > 3) << "Reading file: \"" << data_file_name << "\"" << std::endl; std::stringstream buffer; buffer << infile.rdbuf(); return Parameters(buffer.str()); } ///@} }
5,708
314
<filename>Multiplex/IDEHeaders/IDEHeaders/IDEKit/IDEUtilityAreaDVTStackView_ML.h // // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>. // #import "CDStructures.h" #import "DVTStackView_ML-Protocol.h" @interface IDEUtilityAreaDVTStackView_ML : DVTStackView_ML { } - (void)drawRect:(struct CGRect)arg1; - (BOOL)isOpaque; @end
168
14,668
// Copyright 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 IOS_CHROME_BROWSER_WEBUI_SHOW_MAIL_COMPOSER_CONTEXT_H_ #define IOS_CHROME_BROWSER_WEBUI_SHOW_MAIL_COMPOSER_CONTEXT_H_ #import <Foundation/Foundation.h> namespace base { class FilePath; } @interface ShowMailComposerContext : NSObject // Mark inherited initializer as unavailable to prevent calling it by mistake. - (instancetype)init NS_UNAVAILABLE; // Initializes a context used to open the mail composer with pre-filled // recipients, subject, body. - (instancetype)initWithToRecipients:(NSArray<NSString*>*)toRecipients subject:(NSString*)subject body:(NSString*)body emailNotConfiguredAlertTitleId:(int)alertTitleId emailNotConfiguredAlertMessageId:(int)alertMessageId NS_DESIGNATED_INITIALIZER; // List of email recipients. @property(strong, nonatomic, readonly) NSArray<NSString*>* toRecipients; // Pre-filled default email subject. @property(copy, nonatomic, readonly) NSString* subject; // Pre-filled default email body. @property(copy, nonatomic, readonly) NSString* body; // Path to file to attach to email. @property(nonatomic, assign) const base::FilePath& textFileToAttach; // Identifier for alert if the email title is empty. @property(nonatomic, readonly) int emailNotConfiguredAlertTitleId; // Identifier for alert if the email body is empty. @property(nonatomic, readonly) int emailNotConfiguredAlertMessageId; @end #endif // IOS_CHROME_BROWSER_WEBUI_SHOW_MAIL_COMPOSER_CONTEXT_H_
580
678
<gh_stars>100-1000 /** * This header is generated by class-dump-z 0.2b. * * Source: /System/Library/PrivateFrameworks/iTunesStoreUI.framework/iTunesStoreUI */ #import <iTunesStoreUI/iTunesStoreUI-Structs.h> #import <iTunesStoreUI/NSCopying.h> #import <iTunesStoreUI/XXUnknownSuperclass.h> #import <iTunesStoreUI/NSCoding.h> @class UIColor; @interface SUShadow : XXUnknownSuperclass <NSCoding, NSCopying> { UIColor *_color; // 4 = 0x4 CGSize _offset; // 8 = 0x8 float _opacity; // 16 = 0x10 float _radius; // 20 = 0x14 } @property(assign, nonatomic) float radius; // G=0x6f745; S=0x6f755; @synthesize=_radius @property(assign, nonatomic) float opacity; // G=0x6f725; S=0x6f735; @synthesize=_opacity @property(assign, nonatomic) CGSize offset; // G=0x6f6f5; S=0x6f711; @synthesize=_offset @property(retain, nonatomic) UIColor *color; // G=0x6f6c1; S=0x6f6d1; @synthesize=_color // declared property setter: - (void)setRadius:(float)radius; // 0x6f755 // declared property getter: - (float)radius; // 0x6f745 // declared property setter: - (void)setOpacity:(float)opacity; // 0x6f735 // declared property getter: - (float)opacity; // 0x6f725 // declared property setter: - (void)setOffset:(CGSize)offset; // 0x6f711 // declared property getter: - (CGSize)offset; // 0x6f6f5 // declared property setter: - (void)setColor:(id)color; // 0x6f6d1 // declared property getter: - (id)color; // 0x6f6c1 - (void)applyToLayer:(id)layer; // 0x6f5c9 - (void)encodeWithCoder:(id)coder; // 0x6f485 - (id)copyWithZone:(NSZone *)zone; // 0x6f3d5 - (void)dealloc; // 0x6f381 - (id)initWithCoder:(id)coder; // 0x6f2a5 @end
691
511
/**************************************************************************** * * Copyright 2019 Samsung Electronics 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. * ****************************************************************************/ #ifndef __SECLINK_DRV_REQ_H__ #define __SECLINK_DRV_REQ_H__ int hd_handle_common_request(int cmd, unsigned long arg, void *lower); int hd_handle_auth_request(int cmd, unsigned long arg, void *lower); int hd_handle_key_request(int cmd, unsigned long arg, void *lower); int hd_handle_ss_request(int cmd, unsigned long arg, void *lower); int hd_handle_crypto_request(int cmd, unsigned long arg, void *lower); #endif // __SECLINK_DRV_REQ_H__
326
1,350
[{"id":"NALOSSRB","type":"radio","calc":false,"value":"NALOSSY"},{"id":"NALOSSRB","type":"radio","calc":false,"value":"NALOSSN"},{"id":"LINE27_L27CX_1_","type":"box","calc":false,"value":""},{"id":"LINE27_L27EX_1_","type":"box","calc":false,"value":""},{"id":"LINE27_L27CX_2_","type":"box","calc":false,"value":""},{"id":"LINE27_L27EX_2_","type":"box","calc":false,"value":""},{"id":"LINE27_L27CX_3_","type":"box","calc":false,"value":""},{"id":"LINE27_L27EX_3_","type":"box","calc":false,"value":""},{"id":"LINE27_L27CX_4_","type":"box","calc":false,"value":""},{"id":"LINE27_L27EX_4_","type":"box","calc":false,"value":""},{"id":"NAM2","type":"alpha","calc":true,"value":""},{"id":"SSN2","type":"ssn","calc":true,"value":""},{"id":"LINE27_L27A_1_","type":"alpha","calc":false,"value":""},{"id":"LINE27_L27B_1_","type":"alpha","calc":false,"value":""},{"id":"LINE27_L27D_1_","type":"mask","calc":false,"value":""},{"id":"LINE27_L27A_2_","type":"alpha","calc":false,"value":""},{"id":"LINE27_L27B_2_","type":"alpha","calc":false,"value":""},{"id":"LINE27_L27D_2_","type":"mask","calc":false,"value":""},{"id":"LINE27_L27A_3_","type":"alpha","calc":false,"value":""},{"id":"LINE27_L27B_3_","type":"alpha","calc":false,"value":""},{"id":"LINE27_L27D_3_","type":"mask","calc":false,"value":""},{"id":"LINE27_L27A_4_","type":"alpha","calc":false,"value":""},{"id":"LINE27_L27B_4_","type":"alpha","calc":false,"value":""},{"id":"LINE27_L27D_4_","type":"mask","calc":false,"value":""},{"id":"PSCGL_L27G_1_","type":"mask","calc":false,"value":""},{"id":"PSCGL_L27H_1_","type":"mask","calc":false,"value":""},{"id":"PSCGL_L27I_1_","type":"mask","calc":false,"value":""},{"id":"PSCGL_L27J_1_","type":"mask","calc":false,"value":""},{"id":"PSCGL_L27K_1_","type":"mask","calc":false,"value":""},{"id":"PSCGL_L27G_2_","type":"mask","calc":false,"value":""},{"id":"PSCGL_L27H_2_","type":"mask","calc":false,"value":""},{"id":"PSCGL_L27I_2_","type":"mask","calc":false,"value":""},{"id":"PSCGL_L27J_2_","type":"mask","calc":false,"value":""},{"id":"PSCGL_L27K_2_","type":"mask","calc":false,"value":""},{"id":"PSCGL_L27G_3_","type":"mask","calc":false,"value":""},{"id":"PSCGL_L27H_3_","type":"mask","calc":false,"value":""},{"id":"PSCGL_L27I_3_","type":"mask","calc":false,"value":""},{"id":"PSCGL_L27J_3_","type":"mask","calc":false,"value":""},{"id":"PSCGL_L27K_3_","type":"mask","calc":false,"value":""},{"id":"PSCGL_L27G_4_","type":"mask","calc":false,"value":""},{"id":"PSCGL_L27H_4_","type":"mask","calc":false,"value":""},{"id":"PSCGL_L27I_4_","type":"mask","calc":false,"value":""},{"id":"PSCGL_L27J_4_","type":"mask","calc":false,"value":""},{"id":"PSCGL_L27K_4_","type":"mask","calc":false,"value":""},{"id":"L28AH","type":"number","calc":true,"value":""},{"id":"L28AK","type":"number","calc":true,"value":""},{"id":"L28BG","type":"number","calc":true,"value":""},{"id":"L28BI","type":"number","calc":true,"value":""},{"id":"L28BJ","type":"number","calc":true,"value":""},{"id":"L29","type":"number","calc":true,"value":""},{"id":"L30","type":"number","calc":true,"value":""},{"id":"L31","type":"number","calc":true,"value":""},{"id":"ESTATE_L32A_1_","type":"alpha","calc":false,"value":""},{"id":"ESTATE_L32B_1_","type":"alpha","calc":false,"value":""},{"id":"ESTATE_L32A_2_","type":"alpha","calc":false,"value":""},{"id":"ESTATE_L32B_2_","type":"alpha","calc":false,"value":""},{"id":"ESGL_L32C_1_","type":"mask","calc":false,"value":""},{"id":"ESGL_L32D_1_","type":"mask","calc":false,"value":""},{"id":"ESGL_L32E_1_","type":"mask","calc":false,"value":""},{"id":"ESGL_L32F_1_","type":"mask","calc":false,"value":""},{"id":"ESGL_L32C_2_","type":"mask","calc":false,"value":""},{"id":"ESGL_L32D_2_","type":"mask","calc":false,"value":""},{"id":"ESGL_L32E_2_","type":"mask","calc":false,"value":""},{"id":"ESGL_L32F_2_","type":"mask","calc":false,"value":""},{"id":"L33AD","type":"number","calc":true,"value":""},{"id":"L33AF","type":"number","calc":true,"value":""},{"id":"L33BC","type":"number","calc":true,"value":""},{"id":"L33BE","type":"number","calc":true,"value":""},{"id":"L34","type":"number","calc":true,"value":""},{"id":"L35","type":"number","calc":true,"value":""},{"id":"L36","type":"number","calc":true,"value":""},{"id":"L37_L37A_1_","type":"alpha","calc":false,"value":""},{"id":"L37_L37B_1_","type":"mask","calc":false,"value":""},{"id":"L37_L37C_1_","type":"number","calc":false,"value":""},{"id":"L37_L37D_1_","type":"number","calc":false,"value":""},{"id":"L37_L37E_1_","type":"number","calc":false,"value":""},{"id":"L38","type":"number","calc":true,"value":""},{"id":"L39","type":"number","calc":false,"value":""},{"id":"L40","type":"number","calc":true,"value":""},{"id":"L41","type":"number","calc":false,"value":""},{"id":"L42","type":"number","calc":false,"value":""}]
1,752
820
<filename>models/trim_model.py #!/usr/bin/python # Run this script to remove the data that are only useful for training # from your model files in order to make them more compact. import os import numpy as np if __name__=='__main__': files = os.listdir('.') model_files = [f for f in files if f.endswith('.npy')] for model_file in model_files: model = np.load(model_file).item() trimmed_model = {var_name: model[var_name] for var_name in model.keys() if 'optimizer' not in var_name} os.rename(model_file, model_file[:-4]+'_old.npy') np.save(model_file, trimmed_model)
263
1,056
<filename>extide/gradle/src/org/netbeans/modules/gradle/DeleteOperationImpl.java<gh_stars>1000+ /* * 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.gradle; import java.io.File; import java.io.IOException; import java.util.Collections; import java.util.EnumSet; import java.util.LinkedList; import java.util.List; import org.netbeans.api.project.Project; import org.netbeans.modules.gradle.actions.ActionToTaskUtils; import org.netbeans.modules.gradle.api.NbGradleProject; import org.netbeans.modules.gradle.api.execute.ActionMapping; import org.netbeans.modules.gradle.api.execute.RunConfig; import org.netbeans.modules.gradle.api.execute.RunConfig.ExecFlag; import org.netbeans.modules.gradle.api.execute.RunUtils; import org.netbeans.modules.gradle.spi.GradleFiles; import org.netbeans.spi.project.DeleteOperationImplementation; import org.netbeans.spi.project.ProjectServiceProvider; import org.netbeans.spi.project.ProjectState; import org.openide.execution.ExecutorTask; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; import org.openide.util.Lookup; import org.openide.util.NbBundle.Messages; import org.openide.util.Utilities; import static org.netbeans.spi.project.ActionProvider.COMMAND_DELETE; import static org.netbeans.modules.gradle.api.execute.RunConfig.ExecFlag.REPEATABLE; /** * * @author lkishalmi */ @ProjectServiceProvider(service=DeleteOperationImplementation.class, projectType = NbGradleProject.GRADLE_PROJECT_TYPE) public class DeleteOperationImpl implements DeleteOperationImplementation { final Project project; public DeleteOperationImpl(Project project) { this.project = project; } @Override @Messages({ "# {0} - The project name", "LBL_Clean4Delete=Clean Before Delete ({0})" }) public void notifyDeleting() throws IOException { ActionMapping mapping = ActionToTaskUtils.getActiveMapping(COMMAND_DELETE, project, Lookup.EMPTY); RunConfig config = RunUtils.createRunConfig(project, COMMAND_DELETE, ActionProviderImpl.taskName(project, COMMAND_DELETE, Lookup.EMPTY), mapping.isRepeatable() ? EnumSet.of(REPEATABLE) : EnumSet.noneOf(ExecFlag.class), Utilities.parseParameters(mapping.getArgs())); ExecutorTask task = RunUtils.executeGradle(config, ""); task.result(); task.getInputOutput().getOut().close(); task.getInputOutput().getErr().close(); } @Override public void notifyDeleted() throws IOException { project.getLookup().lookup(ProjectState.class).notifyDeleted(); } @Override public List<FileObject> getMetadataFiles() { List<FileObject> ret = new LinkedList<>(); if (project instanceof NbGradleProjectImpl) { NbGradleProjectImpl prj = (NbGradleProjectImpl) project; GradleFiles gfs = prj.getGradleFiles(); List<File> meta = new LinkedList<>(); if (gfs.isRootProject()) { meta.addAll(gfs.getProjectFiles()); } else { if (!gfs.isScriptlessSubProject()) { meta.add(gfs.getBuildScript()); } } for (File file : meta) { FileObject fo = FileUtil.toFileObject(file); if (fo != null) { ret.add(fo); } } } return ret; } @Override public List<FileObject> getDataFiles() { return Collections.singletonList(project.getProjectDirectory()); } }
1,628
11,356
// Boost.Range library // // Copyright <NAME> 2003-2004. Use, modification and // distribution is subject to 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) // // For more information, see http://www.boost.org/libs/range/ // #ifndef BOOST_RANGE_DETAIL_DIFFERENCE_TYPE_HPP #define BOOST_RANGE_DETAIL_DIFFERENCE_TYPE_HPP #include <boost/range/detail/common.hpp> #include <boost/iterator/iterator_traits.hpp> ////////////////////////////////////////////////////////////////////////////// // missing partial specialization workaround. ////////////////////////////////////////////////////////////////////////////// namespace boost { namespace range_detail { template< typename T > struct range_difference_type_; template<> struct range_difference_type_<std_container_> { template< typename C > struct pts { typedef BOOST_DEDUCED_TYPENAME C::difference_type type; }; }; template<> struct range_difference_type_<std_pair_> { template< typename P > struct pts { typedef BOOST_RANGE_DEDUCED_TYPENAME boost::iterator_difference< BOOST_DEDUCED_TYPENAME P::first_type>::type type; }; }; template<> struct range_difference_type_<array_> { template< typename A > struct pts { typedef std::ptrdiff_t type; }; }; template<> struct range_difference_type_<char_array_> { template< typename A > struct pts { typedef std::ptrdiff_t type; }; }; template<> struct range_difference_type_<char_ptr_> { template< typename S > struct pts { typedef std::ptrdiff_t type; }; }; template<> struct range_difference_type_<const_char_ptr_> { template< typename S > struct pts { typedef std::ptrdiff_t type; }; }; template<> struct range_difference_type_<wchar_t_ptr_> { template< typename S > struct pts { typedef std::ptrdiff_t type; }; }; template<> struct range_difference_type_<const_wchar_t_ptr_> { template< typename S > struct pts { typedef std::ptrdiff_t type; }; }; } template< typename C > class range_difference { typedef BOOST_RANGE_DEDUCED_TYPENAME range_detail::range<C>::type c_type; public: typedef BOOST_RANGE_DEDUCED_TYPENAME range_detail::range_difference_type_<c_type>::BOOST_NESTED_TEMPLATE pts<C>::type type; }; } #endif
1,543
4,036
<filename>java/ql/test/stubs/apache-commons-lang3-3.7/org/apache/commons/lang3/text/WordUtils.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.commons.lang3.text; import java.util.regex.Matcher; import java.util.regex.Pattern; public class WordUtils { public WordUtils() { } public static String wrap(final String str, final int wrapLength) { return null; } public static String wrap(final String str, final int wrapLength, final String newLineStr, final boolean wrapLongWords) { return null; } public static String wrap(final String str, int wrapLength, String newLineStr, final boolean wrapLongWords, String wrapOn) { return null; } public static String capitalize(final String str) { return null; } public static String capitalize(final String str, final char... delimiters) { return null; } public static String capitalizeFully(final String str) { return null; } public static String capitalizeFully(String str, final char... delimiters) { return null; } public static String uncapitalize(final String str) { return null; } public static String uncapitalize(final String str, final char... delimiters) { return null; } public static String swapCase(final String str) { return null; } public static String initials(final String str) { return null; } public static String initials(final String str, final char... delimiters) { return null; } public static boolean containsAllWords(final CharSequence word, final CharSequence... words) { return false; } }
753
843
package org.zalando.nakadi.repository.db; import org.junit.After; import org.junit.Before; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DriverManagerDataSource; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; import static org.zalando.nakadi.webservice.BaseAT.POSTGRES_PWD; import static org.zalando.nakadi.webservice.BaseAT.POSTGRES_URL; import static org.zalando.nakadi.webservice.BaseAT.POSTGRES_USER; public abstract class AbstractDbRepositoryTest { protected JdbcTemplate template; protected Connection connection; @Before public void setUp() throws Exception { try { final DataSource datasource = new DriverManagerDataSource(POSTGRES_URL, POSTGRES_USER, POSTGRES_PWD); template = new JdbcTemplate(datasource); connection = datasource.getConnection(); } catch (final SQLException e) { e.printStackTrace(); } } @After public void tearDown() throws SQLException { connection.close(); } }
427
4,262
<reponame>rikvb/camel /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.dataformat.asn1; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import com.beanit.jasn1.ber.ReverseByteArrayOutputStream; import org.apache.camel.Exchange; import org.apache.camel.spi.DataFormat; import org.apache.camel.spi.DataFormatName; import org.apache.camel.spi.annotations.Dataformat; import org.apache.camel.support.service.ServiceSupport; import org.apache.camel.util.IOHelper; import org.apache.camel.util.ObjectHelper; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1Primitive; @Dataformat("asn1") public class ASN1DataFormat extends ServiceSupport implements DataFormat, DataFormatName { private boolean usingIterator; private Class<?> unmarshalType; public ASN1DataFormat() { this.usingIterator = false; } public ASN1DataFormat(Class<?> unmarshalType) { this.usingIterator = true; this.unmarshalType = unmarshalType; } @Override public String getDataFormatName() { return "asn1"; } @Override public void marshal(Exchange exchange, Object graph, OutputStream stream) throws Exception { InputStream berOut = null; if (usingIterator) { if (unmarshalType != null) { encodeGenericTypeObject(exchange, stream); return; } Object record = exchange.getIn().getBody(); if (record instanceof ASN1Primitive) { ASN1Primitive asn1Primitive = ObjectHelper.cast(ASN1Primitive.class, record); berOut = new ByteArrayInputStream(asn1Primitive.getEncoded()); } else if (record instanceof byte[]) { berOut = new ByteArrayInputStream(ObjectHelper.cast(byte[].class, record)); } } else { byte[] byteInput = exchange.getContext().getTypeConverter().mandatoryConvertTo(byte[].class, exchange, graph); berOut = new ByteArrayInputStream(byteInput); } try { IOHelper.copy(berOut, stream); } finally { IOHelper.close(berOut, stream); } } private void encodeGenericTypeObject(Exchange exchange, OutputStream stream) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, IOException { Class<?>[] paramOut = new Class<?>[1]; paramOut[0] = OutputStream.class; try (ReverseByteArrayOutputStream berOut = new ReverseByteArrayOutputStream(IOHelper.DEFAULT_BUFFER_SIZE / 256, true)) { Method encodeMethod = exchange.getIn().getBody().getClass().getDeclaredMethod("encode", paramOut); encodeMethod.invoke(exchange.getIn().getBody(), berOut); stream.write(berOut.getArray()); } } @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public Object unmarshal(Exchange exchange, InputStream stream) throws Exception { if (usingIterator) { if (unmarshalType != null) { return new ASN1GenericIterator(unmarshalType, stream); } return new ASN1MessageIterator(exchange, stream); } else { ASN1Primitive asn1Record = null; byte[] asn1Bytes; try (ASN1InputStream ais = new ASN1InputStream(stream); ByteArrayOutputStream asn1Out = new ByteArrayOutputStream();) { while (ais.available() > 0) { asn1Record = ais.readObject(); asn1Out.write(asn1Record.getEncoded()); } asn1Bytes = asn1Out.toByteArray(); } return asn1Bytes; } } public boolean isUsingIterator() { return usingIterator; } public void setUsingIterator(boolean usingIterator) { this.usingIterator = usingIterator; } public Class<?> getUnmarshalType() { return unmarshalType; } public void setUnmarshalType(Class<?> unmarshalType) { this.unmarshalType = unmarshalType; } @Override protected void doStart() throws Exception { // no op } @Override protected void doStop() throws Exception { // no op } }
2,077
302
//////////////////////////////////////////////////////////////////////////////////////////////////// // This file is part of CosmoScout VR // // and may be used under the terms of the MIT license. See the LICENSE file for details. // // Copyright: (c) 2019 German Aerospace Center (DLR) // //////////////////////////////////////////////////////////////////////////////////////////////////// #include "TestTileVisitor.hpp" namespace csp::lodbodies { //////////////////////////////////////////////////////////////////////////////////////////////////// /* explicit */ TestTileVisitor::TestTileVisitor(TileQuadTree* treeDEM, TileQuadTree* treeIMG) : TileVisitor<TestTileVisitor>(treeDEM, treeIMG) { } //////////////////////////////////////////////////////////////////////////////////////////////////// std::vector<TileId> const& TestTileVisitor::getLoadTilesDEM() const { return mLoadTilesDEM; } //////////////////////////////////////////////////////////////////////////////////////////////////// std::vector<TileId> const& TestTileVisitor::getLoadTilesIMG() const { return mLoadTilesIMG; } //////////////////////////////////////////////////////////////////////////////////////////////////// bool TestTileVisitor::preTraverse() { mLoadTilesDEM.clear(); mLoadTilesIMG.clear(); return true; } //////////////////////////////////////////////////////////////////////////////////////////////////// bool TestTileVisitor::preVisitRoot(TileId const& tileId) { bool result = true; TileNode* nodeDEM = getNodeDEM(); TileNode* nodeIMG = getNodeIMG(); if (!nodeDEM) { mLoadTilesDEM.push_back(tileId); result = false; } if (!nodeIMG) { mLoadTilesIMG.push_back(tileId); result = false; } if (result) { result = visitLevel(tileId); } return result; } //////////////////////////////////////////////////////////////////////////////////////////////////// bool TestTileVisitor::preVisit(TileId const& tileId) { return visitLevel(tileId); } //////////////////////////////////////////////////////////////////////////////////////////////////// void TestTileVisitor::postVisit(TileId const& tileId) { } //////////////////////////////////////////////////////////////////////////////////////////////////// bool TestTileVisitor::visitLevel(TileId const& tileId) { bool result = false; bool refine = refineTile(); if (refine) { for (int i = 0; i < 4; ++i) { mLoadTilesDEM.push_back(HEALPix::getChildTileId(tileId, i)); mLoadTilesIMG.push_back(HEALPix::getChildTileId(tileId, i)); } result = refine; } return result; } //////////////////////////////////////////////////////////////////////////////////////////////////// bool TestTileVisitor::refineTile() { return getLevel() < 2; } //////////////////////////////////////////////////////////////////////////////////////////////////// } // namespace csp::lodbodies
828
1,531
<filename>ngrinder-runtime/src/test/java/org/ngrinder/dns/NameStoreTest.java /* * 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.ngrinder.dns; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import java.net.InetAddress; import java.util.Set; /** * NameStore test class * * @author mavlarn * @since 3.0 */ public class NameStoreTest { @Before public void before() { NameStore.getInstance().reset(); } @Test public void testNameStoreInit() { System.setProperty("ngrinder.etc.hosts", "aaa.com:1.1.1.1,bbb.com:172.16.31.10"); NameStore.getInstance().reset(); Set<InetAddress> ips = NameStore.getInstance().get("aaa.com"); assertThat(ips.iterator().next().getHostAddress(), is("1.1.1.1")); NameStore.getInstance().remove("bbb.com"); ips = NameStore.getInstance().get("bbb.com"); assertThat(ips, nullValue()); } @Test public void testNameStoreInitInvalid() { System.setProperty("ngrinder.etc.hosts", "bbb.com:,1.1.1.1,"); NameStore.getInstance().reset(); Set<InetAddress> ips = NameStore.getInstance().get("aaa.com"); assertThat(ips, nullValue()); } @Test public void testNameStoreInitEmpty() { System.setProperty("ngrinder.etc.hosts", ""); NameStore.getInstance().reset(); Set<InetAddress> ips = NameStore.getInstance().get("bbb.com"); assertThat(ips, nullValue()); } }
680
841
/* * Copyright (c) 2014-2015 the Civetweb developers * Copyright (c) 2014 <NAME> * https://github.com/jshelley * License http://opensource.org/licenses/mit-license.php MIT License */ /* This example is superseeded by other examples, and no longer * actively maintained. * See examples/embedded_c for an up to date example. */ // Simple example program on how to use websocket client embedded C interface. #ifdef _WIN32 #include <Windows.h> #define sleep(x) Sleep(1000 * (x)) #else #include <unistd.h> #endif #include <assert.h> #include <string.h> #include "civetweb.h" #define DOCUMENT_ROOT "." #define PORT "8888" #define SSL_CERT "./ssl/server.pem" const char *websocket_welcome_msg = "websocket welcome\n"; const size_t websocket_welcome_msg_len = 18 /* strlen(websocket_welcome_msg) */; const char *websocket_acknowledge_msg = "websocket msg ok\n"; const size_t websocket_acknowledge_msg_len = 17 /* strlen(websocket_acknowledge_msg) */; const char *websocket_goodbye_msg = "websocket bye\n"; const size_t websocket_goodbye_msg_len = 14 /* strlen(websocket_goodbye_msg) */; /*************************************************************************************/ /* WEBSOCKET SERVER */ /*************************************************************************************/ #if defined(MG_LEGACY_INTERFACE) int websock_server_connect(const struct httplib_connection *conn) #else int websocket_server_connect(const struct httplib_connection *conn, void *_ignored) #endif { printf("Server: Websocket connected\n"); return 0; /* return 0 to accept every connection */ } #if defined(MG_LEGACY_INTERFACE) void websocket_server_ready(struct httplib_connection *conn) #else void websocket_server_ready(struct httplib_connection *conn, void *_ignored) #endif { printf("Server: Websocket ready\n"); /* Send websocket welcome message */ httplib_lock_connection(conn); httplib_websocket_write(conn, WEBSOCKET_OPCODE_TEXT, websocket_welcome_msg, websocket_welcome_msg_len); httplib_unlock_connection(conn); } #if defined(MG_LEGACY_INTERFACE) int websocket_server_data(struct httplib_connection *conn, int bits, char *data, size_t data_len) #else int websocket_server_data(struct httplib_connection *conn, int bits, char *data, size_t data_len, void *_ignored) #endif { printf("Server: Got %lu bytes from the client\n", (unsigned long)data_len); printf("Server received data from client: "); fwrite(data, 1, data_len, stdout); printf("\n"); if (data_len < 3 || 0 != memcmp(data, "bye", 3)) { /* Send websocket acknowledge message */ httplib_lock_connection(conn); httplib_websocket_write(conn, WEBSOCKET_OPCODE_TEXT, websocket_acknowledge_msg, websocket_acknowledge_msg_len); httplib_unlock_connection(conn); } else { /* Send websocket acknowledge message */ httplib_lock_connection(conn); httplib_websocket_write(conn, WEBSOCKET_OPCODE_TEXT, websocket_goodbye_msg, websocket_goodbye_msg_len); httplib_unlock_connection(conn); } return 1; /* return 1 to keep the connetion open */ } #if defined(MG_LEGACY_INTERFACE) void websocket_server_connection_close(const struct httplib_connection *conn) #else void websocket_server_connection_close(const struct httplib_connection *conn, void *_ignored) #endif { printf("Server: Close connection\n"); /* Can not send a websocket goodbye message here - the connection is already * closed */ } struct httplib_context * start_websocket_server() { const char *options[] = {"document_root", DOCUMENT_ROOT, "ssl_certificate", SSL_CERT, "listening_ports", PORT, "request_timeout_ms", "5000", 0}; struct httplib_callbacks callbacks; struct httplib_context *ctx; memset(&callbacks, 0, sizeof(callbacks)); #if defined(MG_LEGACY_INTERFACE) /* Obsolete: */ callbacks.websocket_connect = websock_server_connect; callbacks.websocket_ready = websocket_server_ready; callbacks.websocket_data = websocket_server_data; callbacks.connection_close = websocket_server_connection_close; ctx = httplib_start(&callbacks, 0, options); #else /* New interface: */ ctx = httplib_start(&callbacks, 0, options); httplib_set_websocket_handler(ctx, "/websocket", websocket_server_connect, websocket_server_ready, websocket_server_data, websocket_server_connection_close, NULL); #endif return ctx; } /*************************************************************************************/ /* WEBSOCKET CLIENT */ /*************************************************************************************/ struct tclient_data { void *data; size_t len; int closed; }; static int websocket_client_data_handler(struct httplib_connection *conn, int flags, char *data, size_t data_len, void *user_data) { struct httplib_context *ctx = httplib_get_context(conn); struct tclient_data *pclient_data = (struct tclient_data *)httplib_get_user_data(ctx); printf("Client received data from server: "); fwrite(data, 1, data_len, stdout); printf("\n"); pclient_data->data = malloc(data_len); assert(pclient_data->data != NULL); memcpy(pclient_data->data, data, data_len); pclient_data->len = data_len; return 1; } static void websocket_client_close_handler(const struct httplib_connection *conn, void *user_data) { struct httplib_context *ctx = httplib_get_context(conn); struct tclient_data *pclient_data = (struct tclient_data *)httplib_get_user_data(ctx); printf("Client: Close handler\n"); pclient_data->closed++; } int main(int argc, char *argv[]) { struct httplib_context *ctx = NULL; struct tclient_data client1_data = {NULL, 0, 0}; struct tclient_data client2_data = {NULL, 0, 0}; struct tclient_data client3_data = {NULL, 0, 0}; struct httplib_connection *newconn1 = NULL; struct httplib_connection *newconn2 = NULL; struct httplib_connection *newconn3 = NULL; char ebuf[100] = {0}; assert(websocket_welcome_msg_len == strlen(websocket_welcome_msg)); /* First set up a websocket server */ ctx = start_websocket_server(); assert(ctx != NULL); printf("Server init\n\n"); /* Then connect a first client */ newconn1 = httplib_connect_websocket_client("localhost", atoi(PORT), 0, ebuf, sizeof(ebuf), "/websocket", NULL, websocket_client_data_handler, websocket_client_close_handler, &client1_data); if (newconn1 == NULL) { printf("Error: %s", ebuf); return 1; } sleep(1); /* Should get the websocket welcome message */ assert(client1_data.closed == 0); assert(client2_data.closed == 0); assert(client2_data.data == NULL); assert(client2_data.len == 0); assert(client1_data.data != NULL); assert(client1_data.len == websocket_welcome_msg_len); assert(!memcmp(client1_data.data, websocket_welcome_msg, websocket_welcome_msg_len)); free(client1_data.data); client1_data.data = NULL; client1_data.len = 0; httplib_websocket_client_write(newconn1, WEBSOCKET_OPCODE_TEXT, "data1", 5); sleep(1); /* Should get the acknowledge message */ assert(client1_data.closed == 0); assert(client2_data.closed == 0); assert(client2_data.data == NULL); assert(client2_data.len == 0); assert(client1_data.data != NULL); assert(client1_data.len == websocket_acknowledge_msg_len); assert(!memcmp(client1_data.data, websocket_acknowledge_msg, websocket_acknowledge_msg_len)); free(client1_data.data); client1_data.data = NULL; client1_data.len = 0; /* Now connect a second client */ newconn2 = httplib_connect_websocket_client("localhost", atoi(PORT), 0, ebuf, sizeof(ebuf), "/websocket", NULL, websocket_client_data_handler, websocket_client_close_handler, &client2_data); if (newconn2 == NULL) { printf("Error: %s", ebuf); return 1; } sleep(1); /* Client 2 should get the websocket welcome message */ assert(client1_data.closed == 0); assert(client2_data.closed == 0); assert(client1_data.data == NULL); assert(client1_data.len == 0); assert(client2_data.data != NULL); assert(client2_data.len == websocket_welcome_msg_len); assert(!memcmp(client2_data.data, websocket_welcome_msg, websocket_welcome_msg_len)); free(client2_data.data); client2_data.data = NULL; client2_data.len = 0; httplib_websocket_client_write(newconn1, WEBSOCKET_OPCODE_TEXT, "data2", 5); sleep(1); /* Should get the acknowledge message */ assert(client1_data.closed == 0); assert(client2_data.closed == 0); assert(client2_data.data == NULL); assert(client2_data.len == 0); assert(client1_data.data != NULL); assert(client1_data.len == websocket_acknowledge_msg_len); assert(!memcmp(client1_data.data, websocket_acknowledge_msg, websocket_acknowledge_msg_len)); free(client1_data.data); client1_data.data = NULL; client1_data.len = 0; httplib_websocket_client_write(newconn1, WEBSOCKET_OPCODE_TEXT, "bye", 3); sleep(1); /* Should get the goodbye message */ assert(client1_data.closed == 0); assert(client2_data.closed == 0); assert(client2_data.data == NULL); assert(client2_data.len == 0); assert(client1_data.data != NULL); assert(client1_data.len == websocket_goodbye_msg_len); assert(!memcmp(client1_data.data, websocket_goodbye_msg, websocket_goodbye_msg_len)); free(client1_data.data); client1_data.data = NULL; client1_data.len = 0; httplib_close_connection(newconn1); sleep(1); /* Won't get any message */ assert(client1_data.closed == 1); assert(client2_data.closed == 0); assert(client1_data.data == NULL); assert(client1_data.len == 0); assert(client2_data.data == NULL); assert(client2_data.len == 0); httplib_websocket_client_write(newconn2, WEBSOCKET_OPCODE_TEXT, "bye", 3); sleep(1); /* Should get the goodbye message */ assert(client1_data.closed == 1); assert(client2_data.closed == 0); assert(client1_data.data == NULL); assert(client1_data.len == 0); assert(client2_data.data != NULL); assert(client2_data.len == websocket_goodbye_msg_len); assert(!memcmp(client2_data.data, websocket_goodbye_msg, websocket_goodbye_msg_len)); free(client2_data.data); client2_data.data = NULL; client2_data.len = 0; httplib_close_connection(newconn2); sleep(1); /* Won't get any message */ assert(client1_data.closed == 1); assert(client2_data.closed == 1); assert(client1_data.data == NULL); assert(client1_data.len == 0); assert(client2_data.data == NULL); assert(client2_data.len == 0); /* Connect client 3 */ newconn3 = httplib_connect_websocket_client("localhost", atoi(PORT), 0, ebuf, sizeof(ebuf), "/websocket", NULL, websocket_client_data_handler, websocket_client_close_handler, &client3_data); sleep(1); /* Client 3 should get the websocket welcome message */ assert(client1_data.closed == 1); assert(client2_data.closed == 1); assert(client3_data.closed == 0); assert(client1_data.data == NULL); assert(client1_data.len == 0); assert(client2_data.data == NULL); assert(client2_data.len == 0); assert(client3_data.data != NULL); assert(client3_data.len == websocket_welcome_msg_len); assert(!memcmp(client3_data.data, websocket_welcome_msg, websocket_welcome_msg_len)); free(client3_data.data); client3_data.data = NULL; client3_data.len = 0; httplib_stop(ctx); printf("Server shutdown\n"); sleep(10); assert(client3_data.closed == 1); return 0; }
6,012
302
<reponame>dbgrigsby/kafka-utils # -*- coding: utf-8 -*- # Copyright 2016 Yelp Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import import mock import pytest from kafka_utils.kafka_consumer_manager. \ commands.offset_restore import OffsetRestore from kafka_utils.util.client import KafkaToolClient from kafka_utils.util.monitoring import ConsumerPartitionOffsets class TestOffsetRestore(object): topics_partitions = { "topic1": [0, 1, 2], "topic2": [0, 1, 2, 3], "topic3": [0, 1], } consumer_offsets_metadata = { 'topic1': [ ConsumerPartitionOffsets(topic='topic1', partition=0, current=20, highmark=655, lowmark=655), ConsumerPartitionOffsets(topic='topic1', partition=1, current=10, highmark=655, lowmark=655) ] } parsed_consumer_offsets = {'groupid': 'group1', 'offsets': {'topic1': {0: 10, 1: 20}}} new_consumer_offsets = {'topic1': {0: 10, 1: 20}} kafka_consumer_offsets = {'topic1': [ ConsumerPartitionOffsets(topic='topic1', partition=0, current=30, highmark=40, lowmark=10), ConsumerPartitionOffsets(topic='topic1', partition=1, current=20, highmark=40, lowmark=10), ]} @pytest.fixture def mock_kafka_client(self): mock_kafka_client = mock.MagicMock( spec=KafkaToolClient ) mock_kafka_client.get_partition_ids_for_topic. \ side_effect = self.topics_partitions return mock_kafka_client def test_build_new_offsets(self, mock_kafka_client): new_offsets = OffsetRestore.build_new_offsets( mock_kafka_client, {'topic1': {0: 10, 1: 20}}, {'topic1': [0, 1]}, self.kafka_consumer_offsets, ) assert new_offsets == self.new_consumer_offsets
950
953
<filename>src/plugins/tools.common/http_message_parser.cpp /* * The MIT License (MIT) * * Copyright (c) 2015 Microsoft Corporation * * -=- Robust Distributed System Nucleus (rDSN) -=- * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /* * Description: * message parser for browser-generated http request * * Revision history: * Feb. 2016, <NAME>, first version * Jun. 2016, <NAME>, second version * xxxx-xx-xx, author, fix bug about xxx */ # include <dsn/utility/ports.h> # include <dsn/tool-api/rpc_message.h> # include <dsn/utility/singleton.h> # include <vector> # include <iomanip> # include "http_message_parser.h" # include <dsn/cpp/serialization.h> # ifdef __TITLE__ # undef __TITLE__ # endif # define __TITLE__ "http.message.parser" namespace dsn{ template <typename T, size_t N> char(&ArraySizeHelper(T(&array)[N]))[N]; http_message_parser::http_message_parser() { memset(&_parser_setting, 0, sizeof(_parser_setting)); _parser.data = this; _parser_setting.on_message_begin = [](http_parser* parser)->int { auto owner = static_cast<http_message_parser*>(parser->data); owner->_current_message.reset(message_ex::create_receive_message_with_standalone_header(blob())); owner->_response_parse_state = parsing_nothing; message_header* header = owner->_current_message->header; header->hdr_length = sizeof(message_header); header->hdr_crc32 = header->body_crc32 = CRC_INVALID; return 0; }; _parser_setting.on_url = [](http_parser* parser, const char *at, size_t length)->int { // see https://github.com/imzhenyu/rDSN/issues/420 // url = "/" + payload_format + "/" + thread_hash + "/" + rpc_code; // e.g., /DSF_THRIFT_JSON/0/RPC_CLI_CLI_CALL std::string url(at, length); std::vector<std::string> args; utils::split_args(url.c_str(), args, '/'); dinfo("http call %s", url.c_str()); if (args.size() != 3) { dinfo("skip url parse for %s, could be done in headers if not cross-domain", url.c_str()); return 0; } auto owner = static_cast<http_message_parser*>(parser->data); auto& hdr = owner->_current_message->header; // serialize-type dsn_msg_serialize_format fmt = enum_from_string(args[0].c_str(), DSF_INVALID); if (fmt == DSF_INVALID) { derror("invalid serialize_format in url %s", url.c_str()); return 1; } hdr->context.u.serialize_format = fmt; // thread-hash char *end; hdr->client.thread_hash = std::strtol(args[1].c_str(), &end, 10); if (end != args[1].c_str() + args[1].length()) { derror("invalid thread hash in url %s", url.c_str()); return 1; } // rpc-code if (args[2].length() > DSN_MAX_TASK_CODE_NAME_LENGTH) { derror("too long rpc code in url %s", url.c_str()); return 1; } strcpy(hdr->rpc_name, args[2].c_str()); return 0; }; _parser_setting.on_header_field = [](http_parser* parser, const char *at, size_t length)->int { #define StrLiteralLen(str) (sizeof(ArraySizeHelper(str)) - 1) #define MATCH(pat) (length >= StrLiteralLen(pat) && strncmp(at, pat, StrLiteralLen(pat)) == 0) auto owner = static_cast<http_message_parser*>(parser->data); if (MATCH("id")) { owner->_response_parse_state = parsing_id; } else if (MATCH("trace_id")) { owner->_response_parse_state = parsing_trace_id; } else if (MATCH("rpc_name")) { owner->_response_parse_state = parsing_rpc_name; } else if (MATCH("app_id")) { owner->_response_parse_state = parsing_app_id; } else if (MATCH("partition_index")) { owner->_response_parse_state = parsing_partition_index; } else if (MATCH("serialize_format")) { owner->_response_parse_state = parsing_serialize_format; } else if (MATCH("from_address")) { owner->_response_parse_state = parsing_from_address; } else if (MATCH("client_timeout")) { owner->_response_parse_state = parsing_client_timeout; } else if (MATCH("client_thread_hash")) { owner->_response_parse_state = parsing_client_thread_hash; } else if (MATCH("client_partition_hash")) { owner->_response_parse_state = parsing_client_partition_hash; } else if (MATCH("server_error")) { owner->_response_parse_state = parsing_server_error; } return 0; #undef StrLiteralLen #undef MATCH }; _parser_setting.on_header_value = [](http_parser* parser, const char *at, size_t length)->int { auto owner = static_cast<http_message_parser*>(parser->data); message_header* header = owner->_current_message->header; switch(owner->_response_parse_state) { case parsing_id: { char *end; header->id = std::strtoull(at, &end, 10); if (end != at + length) { derror("invalid header.id '%.*s'", length, at); return 1; } break; } case parsing_trace_id: { char *end; header->trace_id = std::strtoull(at, &end, 10); if (end != at + length) { derror("invalid header.trace_id '%.*s'", length, at); return 1; } break; } case parsing_rpc_name: { if (length >= DSN_MAX_TASK_CODE_NAME_LENGTH) { derror("too long header.rpc_name '%.*s'", length, at); return 1; } strncpy(header->rpc_name, at, length); header->rpc_name[length] = 0; break; } case parsing_app_id: { char *end; header->gpid.u.app_id = std::strtol(at, &end, 10); if (end != at + length) { derror("invalid header.app_id '%.*s'", length, at); return 1; } break; } case parsing_partition_index: { char *end; header->gpid.u.partition_index = std::strtol(at, &end, 10); if (end != at + length) { derror("invalid header.partition_index '%.*s'", length, at); return 1; } break; } case parsing_serialize_format: { dsn_msg_serialize_format fmt = enum_from_string(std::string(at, length).c_str(), DSF_INVALID); if (fmt == DSF_INVALID) { derror("invalid header.serialize_format '%.*s'", length, at); return 1; } header->context.u.serialize_format = fmt; break; } case parsing_from_address: { int pos = -1; int dot_count = 0; for (int i = 0; i < length; ++i) { if (at[i] == ':') { pos = i; break; } else if (at[i] == '.') { dot_count++; } } if (pos == -1 || pos == (length - 1) || dot_count != 3) { derror("invalid header.from_address '%.*s'", length, at); return 1; } char *end; unsigned long port = std::strtol(at + pos + 1, &end, 10); if (end != at + length) { derror("invalid header.from_address '%.*s'", length, at); return 1; } std::string host(at, pos); header->from_address.assign_ipv4(host.c_str(), port); break; } case parsing_client_timeout: { char *end; header->client.timeout_ms = std::strtol(at, &end, 10); if (end != at + length) { derror("invalid header.client_timeout '%.*s'", length, at); return 1; } break; } case parsing_client_thread_hash: { char *end; header->client.thread_hash = std::strtol(at, &end, 10); if (end != at + length) { derror("invalid header.client_thread_hash '%.*s'", length, at); return 1; } break; } case parsing_client_partition_hash: { char *end; header->client.partition_hash = std::strtoull(at, &end, 10); if (end != at + length) { derror("invalid header.client_partition_hash '%.*s'", length, at); return 1; } break; } case parsing_server_error: { if (length >= DSN_MAX_ERROR_CODE_NAME_LENGTH) { derror("too long header.server_error '%.*s'", length, at); return 1; } strncpy(header->server.error_name, at, length); header->server.error_name[length] = 0; break; } case parsing_nothing: ; //no default } owner->_response_parse_state = parsing_nothing; return 0; }; _parser_setting.on_headers_complete = [](http_parser* parser)->int { auto owner = static_cast<http_message_parser*>(parser->data); message_header* header = owner->_current_message->header; if (parser->type == HTTP_REQUEST && parser->method == HTTP_GET) { header->hdr_type = *(uint32_t*)"GET "; header->context.u.is_request = 1; } else if (parser->type == HTTP_REQUEST && parser->method == HTTP_POST) { header->hdr_type = *(uint32_t*)"POST"; header->context.u.is_request = 1; } else if (parser->type == HTTP_REQUEST && parser->method == HTTP_OPTIONS) { header->hdr_type = *(uint32_t*)"OPTI"; header->context.u.is_request = 1; } else if (parser->type == HTTP_RESPONSE) { header->hdr_type = *(uint32_t*)"HTTP"; header->context.u.is_request = 0; } else { derror("invalid http type %d and method %d", parser->type, parser->method); return 1; } return 0; }; _parser_setting.on_body = [](http_parser* parser, const char *at, size_t length)->int { auto owner = static_cast<http_message_parser*>(parser->data); dassert(owner->_current_buffer.buffer() != nullptr, "the read buffer is not owning"); owner->_current_message->buffers.rbegin()->assign(owner->_current_buffer.buffer(), at - owner->_current_buffer.buffer_ptr(), length); owner->_current_message->header->body_length = length; owner->_received_messages.emplace(std::move(owner->_current_message)); return 0; }; http_parser_init(&_parser, HTTP_BOTH); } void http_message_parser::reset() { http_parser_init(&_parser, HTTP_BOTH); } message_ex* http_message_parser::get_message_on_receive(message_reader* reader, /*out*/ int& read_next) { read_next = 4096; if (reader->_buffer_occupied > 0) { _current_buffer = reader->_buffer; auto nparsed = http_parser_execute(&_parser, &_parser_setting, reader->_buffer.data(), reader->_buffer_occupied); _current_buffer = blob(); reader->_buffer = reader->_buffer.range(nparsed); reader->_buffer_occupied -= nparsed; if (_parser.upgrade) { derror("unsupported http protocol"); read_next = -1; return nullptr; } } if (!_received_messages.empty()) { auto msg = std::move(_received_messages.front()); _received_messages.pop(); dinfo("rpc_name = %s, from_address = %s, seq_id = %" PRIu64 ", trace_id = %016" PRIx64, msg->header->rpc_name, msg->header->from_address.to_string(), msg->header->id, msg->header->trace_id); msg->hdr_format = NET_HDR_HTTP; return msg.release(); } else { return nullptr; } } void http_message_parser::prepare_on_send(message_ex *msg) { auto& header = msg->header; auto& buffers = msg->buffers; // construct http header blob std::string header_str; if (header->context.u.is_request) { std::stringstream ss; ss << "POST /" << header->rpc_name << " HTTP/1.1\r\n"; ss << "Content-Type: text/plain\r\n"; ss << "id: " << header->id << "\r\n"; ss << "trace_id: " << header->trace_id << "\r\n"; ss << "rpc_name: " << header->rpc_name << "\r\n"; ss << "app_id: " << header->gpid.u.app_id << "\r\n"; ss << "partition_index: " << header->gpid.u.partition_index << "\r\n"; ss << "serialize_format: " << enum_to_string((dsn_msg_serialize_format)header->context.u.serialize_format) << "\r\n"; ss << "from_address: " << header->from_address.to_string() << "\r\n"; ss << "client_timeout: " << header->client.timeout_ms << "\r\n"; ss << "client_thread_hash: " << header->client.thread_hash << "\r\n"; ss << "client_partition_hash: " << header->client.partition_hash << "\r\n"; ss << "Content-Length: " << msg->body_size() << "\r\n"; ss << "\r\n"; header_str = ss.str(); } else { std::stringstream ss; ss << "HTTP/1.1 200 OK\r\n"; ss << "Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Access-Control-Allow-Origin\r\n"; ss << "Content-Type: text/plain\r\n"; ss << "Access-Control-Allow-Origin: *\r\n"; ss << "Access-Control-Allow-Methods: POST, GET, OPTIONS\r\n"; ss << "id: " << header->id << "\r\n"; ss << "trace_id: " << header->trace_id << "\r\n"; ss << "rpc_name: " << header->rpc_name << "\r\n"; ss << "serialize_format: " << enum_to_string((dsn_msg_serialize_format)header->context.u.serialize_format) << "\r\n"; ss << "from_address: " << header->from_address.to_string() << "\r\n"; ss << "server_error: " << header->server.error_name << "\r\n"; ss << "Content-Length: " << msg->body_size() << "\r\n"; ss << "\r\n"; header_str = ss.str(); } unsigned int header_len = header_str.size(); std::shared_ptr<char> header_holder(static_cast<char*>(dsn_transient_malloc(header_len)), [](char* c) {dsn_transient_free(c);}); memcpy(header_holder.get(), header_str.data(), header_len); unsigned int dsn_size = sizeof(message_header) + header->body_length; int dsn_buf_count = 0; while (dsn_size > 0 && dsn_buf_count < buffers.size()) { blob& buf = buffers[dsn_buf_count]; dassert(dsn_size >= buf.length(), ""); dsn_size -= buf.length(); ++dsn_buf_count; } dassert(dsn_size == 0, ""); // put header_bb at the end buffers.resize(dsn_buf_count); buffers.emplace_back(blob(std::move(header_holder), header_len)); } int http_message_parser::get_buffer_count_on_send(message_ex* msg) { return (int)msg->buffers.size(); } int http_message_parser::get_buffers_on_send(message_ex* msg, send_buf* buffers) { auto& msg_header = msg->header; auto& msg_buffers = msg->buffers; // leave buffers[0] to header int i = 1; // we must skip the dsn message header unsigned int offset = sizeof(message_header); unsigned int dsn_size = sizeof(message_header) + msg_header->body_length; int dsn_buf_count = 0; while (dsn_size > 0 && dsn_buf_count < msg_buffers.size()) { blob& buf = msg_buffers[dsn_buf_count]; dassert(dsn_size >= buf.length(), ""); dsn_size -= buf.length(); ++dsn_buf_count; if (offset >= buf.length()) { offset -= buf.length(); continue; } buffers[i].buf = (void*)(buf.data() + offset); buffers[i].sz = buf.length() - offset; offset = 0; ++i; } dassert(dsn_size == 0, ""); dassert(dsn_buf_count + 1 == msg_buffers.size(), "must have 1 more blob at the end"); // set header blob& header_bb = msg_buffers[dsn_buf_count]; buffers[0].buf = (void*)header_bb.data(); buffers[0].sz = header_bb.length(); return i; } }
8,659
14,668
// Copyright 2020 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_PREFETCH_PREFETCH_PROXY_PREFETCH_PROXY_FEATURES_H_ #define CHROME_BROWSER_PREFETCH_PREFETCH_PROXY_PREFETCH_PROXY_FEATURES_H_ #include "base/feature_list.h" namespace features { extern const base::Feature kIsolatePrerenders; extern const base::Feature kIsolatePrerendersMustProbeOrigin; } // namespace features #endif // CHROME_BROWSER_PREFETCH_PREFETCH_PROXY_PREFETCH_PROXY_FEATURES_H_
214
773
<filename>cryptol-remote-api/python/tests/cryptol/test_AES.py import unittest from pathlib import Path import unittest import cryptol from cryptol.single_connection import * from cryptol.bitvector import BV class TestAES(unittest.TestCase): def test_AES(self): connect(verify=False) load_file(str(Path('tests','cryptol','test-files', 'examples','AES.cry'))) pt = BV(size=128, value=0x3243f6a8885a308d313198a2e0370734) key = BV(size=128, value=<KEY>) ct = call("aesEncrypt", (pt, key)) expected_ct = BV(size=128, value=0x3925841d02dc09fbdc118597196a0b32) self.assertEqual(ct, expected_ct) decrypted_ct = call("aesDecrypt", (ct, key)) self.assertEqual(pt, decrypted_ct) pt = BV(size=128, value=0x00112233445566778899aabbccddeeff) key = BV(size=128, value=<KEY>) ct = call("aesEncrypt", (pt, key)) expected_ct = BV(size=128, value=0x69c4e0d86a7b0430d8cdb78070b4c55a) self.assertEqual(ct, expected_ct) decrypted_ct = call("aesDecrypt", (ct, key)) self.assertEqual(pt, decrypted_ct) self.assertTrue(safe("aesEncrypt")) self.assertTrue(safe("aesDecrypt")) self.assertTrue(check("AESCorrect")) # prove("AESCorrect") # probably takes too long for this script...? if __name__ == "__main__": unittest.main()
633
3,690
#include <vector> using std::vector; using std::next; using std::prev; using std::advance; class Solution { public: int findMin(vector<int> &num) { auto beg = num.begin(); for (auto end = std::prev(num.end()); beg < end; ) { if (*beg < *end) break; auto mid = (end - beg) >> 1; *beg <= *next(beg, mid) ? advance(beg, mid+1) : advance(end, -mid); } return *beg; } };
218
1,694
<reponame>CrackerCat/iWeChat // // Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by <NAME>. // #import "NSObject-Protocol.h" @class NSArray; @protocol TXICustomPreprocessDelegate <NSObject> @optional - (void)onTextureDestoryed; - (void)onDetectFacePoints:(NSArray *)arg1; - (unsigned int)onCustomPreprocess:(unsigned int)arg1 width:(long long)arg2 height:(long long)arg3; @end
181
3,285
/* Copyright 2020 The OneFlow Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "oneflow/core/platform/include/wrapper.h" #include <dlfcn.h> #ifdef __linux__ #include <link.h> #endif // __linux__ namespace oneflow { namespace platform { namespace { void* OpenSymbol(void* handle, const char* name) { void* ret = dlsym(handle, name); if (!ret) { std::cerr << "Error in dlopen or dlsym: " << dlerror() << "\n"; abort(); } return ret; } } // namespace // original implementation is from pytorch: // https://github.com/pytorch/pytorch/blob/259d19a7335b32c4a27a018034551ca6ae997f6b/aten/src/ATen/DynamicLibrary.cpp std::unique_ptr<DynamicLibrary> DynamicLibrary::Load(const std::vector<std::string>& names) { for (const std::string& name : names) { void* handle = dlopen(name.c_str(), RTLD_LOCAL | RTLD_NOW); if (handle != nullptr) { DynamicLibrary* lib = new DynamicLibrary(handle); #ifdef __linux__ std::cerr << "loaded library: " << lib->AbsolutePath() << "\n"; #endif // __linux__ return std::unique_ptr<DynamicLibrary>(lib); } } return std::unique_ptr<DynamicLibrary>(); } void* DynamicLibrary::LoadSym(const char* name) { return OpenSymbol(handle_, name); } #ifdef __linux__ std::string DynamicLibrary::AbsolutePath() { struct link_map* map; dlinfo(handle_, RTLD_DI_LINKMAP, &map); return map->l_name; } #endif // __linux__ DynamicLibrary::~DynamicLibrary() { dlclose(handle_); } } // namespace platform } // namespace oneflow
686
2,829
/* Copyright 2020 Alibaba Group Holding 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 <sys/prctl.h> #include <signal.h> #include <unistd.h> #include <string> #include <vector> #include "gtest/gtest.h" #include "grpcpp/grpcpp.h" #include "grpcpp/impl/codegen/proto_utils.h" #include "grpcpp/generic/generic_stub.h" #include "euler/service/grpc_server.h" #include "euler/common/logging.h" #include "euler/common/server_register.h" #include "euler/common/data_types.h" #include "euler/client/query_proxy.h" #include "euler/client/query.h" #include "euler/parser/optimizer.h" #include "euler/core/framework/op_kernel.h" #include "euler/core/framework/types.pb.h" #include "euler/core/api/api.h" #include "euler/core/kernels/common.h" namespace euler { static int32_t do_abort = 0; void handle_signal(int32_t signo) { if (signo == SIGHUP) { do_abort = 1; } } class End2EndGPTest: public ::testing::Test { protected: static const char zk_path_[]; std::shared_ptr<ServerRegister> register_; pid_t pid_; void SetUp() override { EulerGraph(); pid_ = fork(); if (pid_ > 0) { // Create a grpc server and start it ServerDef server_def = {"grpc", 0, 2, {}}; server_def.options.insert({"port", "9190"}); server_def.options.insert({"data_path", "/tmp/gp_euler"}); server_def.options.insert({"load_data_type", "all"}); server_def.options.insert({"global_sampler_type", "all"}); server_def.options.insert({"zk_server", "127.0.0.1:2181"}); server_def.options.insert({"zk_path", zk_path_}); auto s = NewServer(server_def, &server_); ASSERT_TRUE(s.ok()) << s.DebugString(); s = server_->Start(); ASSERT_TRUE(s.ok()) << s; } else if (pid_ == 0) { ServerDef server_def = {"grpc", 1, 2, {}}; server_def.options.insert({"port", "9191"}); server_def.options.insert({"data_path", "/tmp/gp_euler"}); server_def.options.insert({"load_data_type", "all"}); server_def.options.insert({"global_sampler_type", "all"}); server_def.options.insert({"zk_server", "127.0.0.1:2181"}); server_def.options.insert({"zk_path", zk_path_}); auto s = NewServer(server_def, &server_); ASSERT_TRUE(s.ok()) << s.DebugString(); s = server_->Start(); ASSERT_TRUE(s.ok()) << s; } } void TearDown() override { auto s = server_->Stop(); ASSERT_TRUE(s.ok()) << s; } std::unique_ptr<ServerInterface> server_; }; const char End2EndGPTest::zk_path_[] = "/euler-2.0-test1"; TEST_F(End2EndGPTest, Execute) { if (pid_ > 0) { GraphConfig graph_config; graph_config.Add("zk_server", "127.0.0.1:2181"); graph_config.Add("zk_path", End2EndGPTest::zk_path_); graph_config.Add("num_retries", 1); graph_config.Add("shard_num", 2); graph_config.Add("mode", "remote"); QueryProxy::Init(graph_config); QueryProxy* proxy = QueryProxy::GetInstance(); /* { std::string gremlin =R"(sampleN(node_type, count).as(node).sampleNB(edge_types, count, 0).as(nb))"; Query query(gremlin); TensorShape shape({1}); TensorShape edge_types_shape({2}); Tensor* node_type_t = query.AllocInput("node_type", shape, kInt32); Tensor* count_t = query.AllocInput("count", shape, kInt32); Tensor* edge_types_t = query.AllocInput("edge_types", edge_types_shape, kInt32); int32_t node_type = 0; GetNodeType("0", &node_type); *(node_type_t->Raw<int32_t>()) = node_type; *(count_t->Raw<int32_t>()) = 3; std::vector<int32_t> edge_types = {0, 0}; GetEdgeType("0", &edge_types[0]); GetEdgeType("1", &edge_types[1]); edge_types_t->Raw<int32_t>()[0] = edge_types[0]; edge_types_t->Raw<int32_t>()[1] = edge_types[1]; std::vector<std::string> result_names = {"node:0", "nb:0", "nb:1", "nb:2"}; std::unordered_map<std::string, Tensor*> results_map = proxy->RunGremlin(&query, result_names); std::unordered_set<uint64_t> nodes = {2, 4, 6}; std::unordered_map<uint64_t, std::unordered_set<uint64_t>> node_nb_set; node_nb_set[2] = {3, 5}; node_nb_set[4] = {5}; node_nb_set[6] = {1, 3, 5}; ASSERT_EQ(3, results_map["node:0"]->NumElements()); for (int32_t i = 0; i < results_map["node:0"]->NumElements(); ++i) { auto tmp = nodes.find(results_map["node:0"]->Raw<uint64_t>()[i]); ASSERT_TRUE(tmp != nodes.end()); } for (int32_t i = 0; i < 3; ++i) { uint64_t root_id = results_map["node:0"]->Raw<uint64_t>()[i]; int32_t begin = results_map["nb:0"]->Raw<int32_t>()[i * 2]; int32_t end = results_map["nb:0"]->Raw<int32_t>()[i * 2 + 1]; for (int32_t j = begin; j < end; ++j) { auto t = results_map["nb:1"]->Raw<uint64_t>()[j]; ASSERT_TRUE(node_nb_set[root_id].find(t) != node_nb_set[root_id].end()); } } } */ { std::string gremlin = R"(v(nodes).sampleNB(edge_types, n, 0).as(n1).sampleNB(edge_types, n, 0).as(n2).v_select(n1).values(fid).as(n1_f))"; Query query(gremlin); TensorShape nodes_shape({4}); TensorShape edge_types_shape({2}); TensorShape scalar_shape({1}); TensorShape fid_shape({1}); Tensor* nodes_t = query.AllocInput("nodes", nodes_shape, kUInt64); Tensor* edge_types_t = query.AllocInput("edge_types", edge_types_shape, kInt32); Tensor* n_t = query.AllocInput("n", scalar_shape, kInt32); Tensor* fid_t = query.AllocInput("fid", fid_shape, kString); std::vector<uint64_t> nodes = {1, 0, 2, 3}; std::vector<int32_t> edge_types = {0, 1}; GetEdgeType("0", &edge_types[0]); GetEdgeType("1", &edge_types[1]); int32_t n = 3; std::copy(nodes.begin(), nodes.end(), nodes_t->Raw<uint64_t>()); std::copy(edge_types.begin(), edge_types.end(), edge_types_t->Raw<int32_t>()); n_t->Raw<int32_t>()[0] = n; std::string fid = "sparse_f1"; *(fid_t->Raw<std::string*>()[0]) = fid; std::vector<std::string> result_names = {"n1:0", "n1:1", "n2:0", "n2:1", "n1_f:1"}; std::unordered_map<std::string, Tensor*> results_map = proxy->RunGremlin(&query, result_names); std::unordered_map<uint64_t, std::unordered_set<uint64_t>> nb_sets(6); nb_sets[1] = {2, 3, 4}; nb_sets[2] = {3, 5}; nb_sets[3] = {4}; nb_sets[4] = {5}; nb_sets[5] = {2, 6}; nb_sets[6] = {1, 3, 5}; nb_sets[0] = {euler::common::DEFAULT_UINT64}; for (size_t i = 0; i < nodes.size(); ++i) { int32_t begin = results_map["n1:0"]->Raw<int32_t>()[i * 2]; int32_t end = results_map["n1:0"]->Raw<int32_t>()[i * 2 + 1]; uint64_t root_id = nodes[i]; for (int32_t j = begin; j < end; ++j) { auto t = results_map["n1:1"]->Raw<uint64_t>()[j]; ASSERT_TRUE(nb_sets[root_id].find(t) != nb_sets[root_id].end()); } } for (int32_t i = 0; i < results_map["n1:1"]->NumElements(); ++i) { int32_t begin = results_map["n2:0"]->Raw<int32_t>()[i * 2]; int32_t end = results_map["n2:0"]->Raw<int32_t>()[i * 2 + 1]; uint64_t root_id = results_map["n1:1"]->Raw<uint64_t>()[i]; for (int32_t j = begin; j < end; ++j) { auto t = results_map["n2:1"]->Raw<uint64_t>()[j]; ASSERT_TRUE(nb_sets[root_id].find(t) != nb_sets[root_id].end()); } } } } else { signal(SIGHUP, handle_signal); prctl(PR_SET_PDEATHSIG, SIGHUP); while (!do_abort) { sleep(10); } } } } // namespace euler
3,982
2,293
from test.test_support import TestFailed # A test for SF bug 422177: manifest float constants varied way too much in # precision depending on whether Python was loading a module for the first # time, or reloading it from a precompiled .pyc. The "expected" failure # mode is that when test_import imports this after all .pyc files have been # erased, it passes, but when test_import imports this from # double_const.pyc, it fails. This indicates a woeful loss of precision in # the marshal format for doubles. It's also possible that repr() doesn't # produce enough digits to get reasonable precision for this box. PI = 3.14159265358979324 TWOPI = 6.28318530717958648 PI_str = "3.14159265358979324" TWOPI_str = "6.28318530717958648" # Verify that the double x is within a few bits of eval(x_str). def check_ok(x, x_str): assert x > 0.0 x2 = eval(x_str) assert x2 > 0.0 diff = abs(x - x2) # If diff is no larger than 3 ULP (wrt x2), then diff/8 is no larger # than 0.375 ULP, so adding diff/8 to x2 should have no effect. if x2 + (diff / 8.) != x2: raise TestFailed("Manifest const %s lost too much precision " % x_str) check_ok(PI, PI_str) check_ok(TWOPI, TWOPI_str)
425
4,071
<reponame>Ru-Xiang/x-deeplearning /* * \file pruned_gemm_op.h * \desc The pruned gemm operator * * A | B x C = A x C + B x D * -- * D * * Only support 2D-Gemm */ #pragma once #include "blaze/operator/operator.h" #include "blaze/common/exception.h" #include "blaze/common/types.h" #include "blaze/math/broadcast.h" #include "blaze/math/vml.h" #include "blaze/math/gemm.h" namespace blaze { template <class Context> class PrunedGemmOp final : public Operator<Context> { public: USE_OPERATOR_FUNCTIONS(Context); PrunedGemmOp(const OperatorDef& def, Workspace* workspace) : Operator<Context>(def, workspace) { transa_ = OperatorBase::GetSingleArgument<bool>("transA", false); transb_ = OperatorBase::GetSingleArgument<bool>("transB", false); alpha_ = OperatorBase::GetSingleArgument<float>("alpha", 1.0); beta_ = OperatorBase::GetSingleArgument<float>("beta", 1.0); iblob_.reset(new Blob(this->device_option_)); } bool RunOnDevice() override { CheckValid(); Blob* x1 = this->Input(0); Blob* x2 = this->Input(1); Blob* w1 = this->Input(2); Blob* w2 = this->Input(3); Blob* bias = this->InputSize() > 4 ? this->Input(4) : nullptr; Blob* y = this->Output(0); const auto& x1_shape = x1->shape(); const auto& x2_shape = x2->shape(); const auto& w1_shape = w1->shape(); const auto& w2_shape = w2->shape(); // Reshape TIndex x1_m = x1_shape[0]; TIndex x1_k = x1_shape[1]; if (transa_) std::swap(x1_m, x1_k); TIndex x2_m = x2_shape[0]; TIndex x2_k = x2_shape[1]; if (transb_) std::swap(x2_m, x2_k); TIndex w1_n = w1_shape[1]; if (transb_) w1_n = w1_shape[0]; TIndex w2_n = w1_n; y->Reshape({ std::max(x1_m, x2_m), w1_n }); // Calculate float beta = beta_; // Step1: Y = bias if (bias == nullptr) { beta = 0; } else { TYPE_SWITCH_WITH_CTX(this->context_, y->data_type(), DType, { DimEqualBroadcastAssign<DType, Context>(y->as<DType>(), y->shape(), bias->as<DType>(), bias->shape(), &this->context_); }); } iblob_->set_data_type(static_cast<DataType>(y->data_type())); iblob_->Reshape({ w1_n }); // Step2: Y = alpha * X1 * W1 + alpha * X2 * W2 + beta * Y TYPE_SWITCH_WITH_CTX(this->context_, y->data_type(), DType, { if (x1_m == x2_m) { Gemm<DType, Context>(transa_ ? CblasTrans : CblasNoTrans, transb_ ? CblasTrans : CblasNoTrans, x1_m, w1_n, x1_k, alpha_, x1->as<DType>(), w1->as<DType>(), beta, y->as<DType>(), &this->context_); Gemm<DType, Context>(transa_ ? CblasTrans : CblasNoTrans, transb_ ? CblasTrans : CblasNoTrans, x2_m, w2_n, x2_k, alpha_, x2->as<DType>(), x2->as<DType>(), beta, y->as<DType>(), &this->context_); } else { if (x1_m == 1) { Gemm<DType, Context>(transa_ ? CblasTrans : CblasNoTrans, transb_ ? CblasTrans : CblasNoTrans, x2_m, w2_n, x2_k, alpha_, x2->as<DType>(), w2->as<DType>(), beta, y->as<DType>(), &this->context_); Gemm<DType, Context>(transa_ ? CblasTrans : CblasNoTrans, transb_ ? CblasTrans : CblasNoTrans, x1_m, w1_n, x1_k, alpha_, x1->as<DType>(), w1->as<DType>(), 0, iblob_->as<DType>(), &this->context_); } else { // x2_m == 1 Gemm<DType, Context>(transa_ ? CblasTrans : CblasNoTrans, transb_ ? CblasTrans : CblasNoTrans, x1_m, w1_n, x1_k, alpha_, x1->as<DType>(), w1->as<DType>(), beta, y->as<DType>(), &this->context_); Gemm<DType, Context>(transa_ ? CblasTrans : CblasNoTrans, transb_ ? CblasTrans : CblasNoTrans, x2_m, w2_n, x2_k, alpha_, x2->as<DType>(), w2->as<DType>(), 0, iblob_->as<DType>(), &this->context_); } // Broadcast FMA DimEqualBroadcastFMA<DType, Context>(y->as<DType>(), y->shape(), iblob_->as<DType>(), iblob_->shape(), &this->context_); } }); return true; } protected: void CheckValid() { Blob* x1 = this->Input(0); Blob* x2 = this->Input(1); Blob* w1 = this->Input(2); Blob* w2 = this->Input(3); Blob* bias = this->InputSize() > 4 ? this->Input(4) : nullptr; BLAZE_CONDITION_THROW(x1->shape().size() == 2, "x1->shape().size()=", x1->shape().size()); BLAZE_CONDITION_THROW(x2->shape().size() == 2, "x2->shape().size()=", x2->shape().size()); if (bias != nullptr) { BLAZE_CONDITION_THROW(bias->shape().size() <= 2, "bias->shape().size()=", bias->shape().size()); } const auto& x1_shape = x1->shape(); const auto& x2_shape = x2->shape(); const auto& w1_shape = w1->shape(); const auto& w2_shape = w2->shape(); // Step1: Check X1/X2 TIndex x1_m = x1_shape[0]; TIndex x1_k = x1_shape[1]; if (transa_) std::swap(x1_m, x1_k); TIndex x2_m = x2_shape[0]; TIndex x2_k = x2_shape[1]; if (transa_) std::swap(x2_m, x2_k); BLAZE_CONDITION_THROW(x1_m == x2_m || x1_m == 1 || x2_m == 1, "x1_m=", x1_m, " x2_m=", x2_m); // Step2: Check W1/W2 TIndex w1_k = w1_shape[0]; TIndex w1_n = w1_shape[1]; if (transb_) std::swap(w1_k, w1_n); TIndex w2_k = w2_shape[0]; TIndex w2_n = w2_shape[1]; if (transb_) std::swap(w2_k, w2_n); BLAZE_CONDITION_THROW(x1_k == w1_k, "x1_k=", x1_k, " w1_k=", w1_k); BLAZE_CONDITION_THROW(x2_k == w2_k, "w2_k=", x2_k, " w2_k=", w2_k); BLAZE_CONDITION_THROW(w1_n == w2_n, "w1_n=", w1_n, " w2_n=", w2_n); // Step3: Check bias if (bias) { const std::vector<TIndex>& bias_shape = bias->shape(); if (bias_shape.size() == 2) { BLAZE_CONDITION_THROW(x1_m == bias_shape[0] || x2_m == bias_shape[0], "x1_m=", x1_m, " x2_m=", x2_m, " bias_shape[0]=", bias_shape[0]); BLAZE_CONDITION_THROW(w1_n == bias_shape[1], "w1_n=", w1_n, " bias_shape[1]=", bias_shape[1]); } else { BLAZE_CONDITION_THROW(w1_n == bias_shape[0], "w1_n=", w1_n, " bias_shape[0]=", bias_shape[0]); } } } std::shared_ptr<Blob> iblob_; float alpha_; float beta_; float transa_; float transb_; }; } // namespace blaze
5,331
11,356
/* Copyright © 2017 Apple Inc. All rights reserved. * * Use of this source code is governed by a BSD-3-clause license that can * be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause */ #include <model_server/lib/toolkit_class_macros.hpp> #include <model_server/lib/toolkit_function_macros.hpp> #include <toolkits/pattern_mining/fp_growth.hpp> namespace turi { namespace pattern_mining { BEGIN_FUNCTION_REGISTRATION REGISTER_FUNCTION(_pattern_mining_create, "data", "event", "features", "min_support", "max_patterns", "min_length"); END_FUNCTION_REGISTRATION BEGIN_CLASS_REGISTRATION REGISTER_CLASS(fp_growth) END_CLASS_REGISTRATION }// pattern_mining }// turicreate
258
575
// Copyright 2020 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 THIRD_PARTY_BLINK_RENDERER_MODULES_CREDENTIALMANAGER_PAYMENT_CREDENTIAL_H_ #define THIRD_PARTY_BLINK_RENDERER_MODULES_CREDENTIALMANAGER_PAYMENT_CREDENTIAL_H_ #include "third_party/blink/renderer/core/typed_arrays/dom_array_buffer.h" #include "third_party/blink/renderer/modules/credentialmanager/authenticator_response.h" #include "third_party/blink/renderer/modules/credentialmanager/public_key_credential.h" #include "third_party/blink/renderer/modules/modules_export.h" #include "third_party/blink/renderer/platform/bindings/script_wrappable.h" namespace blink { // PaymentCredential is a special type of PublicKeyCredential that is tied // to a payment instrument. The credential is used to authenticate a user when // making a payment with SecurePaymentConfirmation. class MODULES_EXPORT PaymentCredential final : public PublicKeyCredential { DEFINE_WRAPPERTYPEINFO(); public: explicit PaymentCredential( const String& id, DOMArrayBuffer* raw_id, AuthenticatorResponse*, const AuthenticationExtensionsClientOutputs* extension_outputs); // Credential: bool IsPaymentCredential() const override; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_MODULES_CREDENTIALMANAGER_PAYMENT_CREDENTIAL_H_
487
874
<reponame>orenmnero/lambda<gh_stars>100-1000 package com.jnape.palatable.lambda.adt.hlist; import com.jnape.palatable.lambda.functions.builtin.fn1.Downcast; import java.util.Objects; /** * An immutable heterogeneous list supporting arbitrary depth type-safety via a linearly recursive type signature. Note * that due to its rapidly expanding type signature, specializations exist up to certain depths to minimize typing * overhead. * * @see SingletonHList * @see Tuple2 * @see Tuple3 * @see Tuple4 * @see Tuple5 * @see Tuple6 */ public abstract class HList { private HList() { } /** * Cons an element onto the front of this HList. * * @param newHead the new head element * @param <NewHead> the new head type * @return the updated HList */ public abstract <NewHead> HCons<NewHead, ? extends HList> cons(NewHead newHead); @Override public final String toString() { StringBuilder body = new StringBuilder("HList{"); HList next = this; while (next != HNil.INSTANCE) { HCons<?, ?> hCons = (HCons<?, ?>) next; body.append(" ").append(hCons.head).append(" "); next = hCons.tail; if (next != HNil.INSTANCE) body.append("::"); } return body.append("}").toString(); } /** * Static factory method for creating empty HLists. * * @return an empty HList */ public static HNil nil() { return HNil.INSTANCE; } /** * Static factory method for creating an HList from the given head and tail. * * @param head the head element * @param tail the tail HList * @param <Head> the head type * @param <Tail> the tail type * @return the newly created HList */ public static <Head, Tail extends HList> HCons<Head, Tail> cons(Head head, Tail tail) { return Downcast.<HCons<Head, Tail>, HCons<Head, ? extends HList>>downcast(tail.cons(head)); } /** * Static factory method for creating a singleton HList. * * @param head the head element * @param <Head> the head element type * @return the singleton HList */ public static <Head> SingletonHList<Head> singletonHList(Head head) { return new SingletonHList<>(head); } /** * Static factory method for creating a 2-element HList. * * @param _1 the head element * @param _2 the second element * @param <_1> the head element type * @param <_2> the second element type * @return the 2-element HList * @see Tuple2 */ public static <_1, _2> Tuple2<_1, _2> tuple(_1 _1, _2 _2) { return singletonHList(_2).cons(_1); } /** * Static factory method for creating a 3-element HList. * * @param _1 the head element * @param _2 the second element * @param _3 the third element * @param <_1> the head element type * @param <_2> the second element type * @param <_3> the third element type * @return the 3-element HList * @see Tuple3 */ public static <_1, _2, _3> Tuple3<_1, _2, _3> tuple(_1 _1, _2 _2, _3 _3) { return tuple(_2, _3).cons(_1); } /** * Static factory method for creating a 4-element HList. * * @param _1 the head element * @param _2 the second element * @param _3 the third element * @param _4 the fourth element * @param <_1> the head element type * @param <_2> the second element type * @param <_3> the third element type * @param <_4> the fourth element type * @return the 4-element HList * @see Tuple4 */ public static <_1, _2, _3, _4> Tuple4<_1, _2, _3, _4> tuple(_1 _1, _2 _2, _3 _3, _4 _4) { return tuple(_2, _3, _4).cons(_1); } /** * Static factory method for creating a 5-element HList. * * @param _1 the head element * @param _2 the second element * @param _3 the third element * @param _4 the fourth element * @param _5 the fifth element * @param <_1> the head element type * @param <_2> the second element type * @param <_3> the third element type * @param <_4> the fourth element type * @param <_5> the fifth element type * @return the 5-element HList * @see Tuple5 */ public static <_1, _2, _3, _4, _5> Tuple5<_1, _2, _3, _4, _5> tuple(_1 _1, _2 _2, _3 _3, _4 _4, _5 _5) { return tuple(_2, _3, _4, _5).cons(_1); } /** * Static factory method for creating a 6-element HList. * * @param _1 the head element * @param _2 the second element * @param _3 the third element * @param _4 the fourth element * @param _5 the fifth element * @param _6 the sixth element * @param <_1> the head element type * @param <_2> the second element type * @param <_3> the third element type * @param <_4> the fourth element type * @param <_5> the fifth element type * @param <_6> the sixth element type * @return the 6-element HList * @see Tuple6 */ public static <_1, _2, _3, _4, _5, _6> Tuple6<_1, _2, _3, _4, _5, _6> tuple(_1 _1, _2 _2, _3 _3, _4 _4, _5 _5, _6 _6) { return tuple(_2, _3, _4, _5, _6).cons(_1); } /** * Static factory method for creating a 7-element HList. * * @param _1 the head element * @param _2 the second element * @param _3 the third element * @param _4 the fourth element * @param _5 the fifth element * @param _6 the sixth element * @param _7 the seventh element * @param <_1> the head element type * @param <_2> the second element type * @param <_3> the third element type * @param <_4> the fourth element type * @param <_5> the fifth element type * @param <_6> the sixth element type * @param <_7> the seventh element type * @return the 7-element HList * @see Tuple7 */ public static <_1, _2, _3, _4, _5, _6, _7> Tuple7<_1, _2, _3, _4, _5, _6, _7> tuple(_1 _1, _2 _2, _3 _3, _4 _4, _5 _5, _6 _6, _7 _7) { return tuple(_2, _3, _4, _5, _6, _7).cons(_1); } /** * Static factory method for creating an 8-element HList. * * @param _1 the head element * @param _2 the second element * @param _3 the third element * @param _4 the fourth element * @param _5 the fifth element * @param _6 the sixth element * @param _7 the seventh element * @param _8 the eighth element * @param <_1> the head element type * @param <_2> the second element type * @param <_3> the third element type * @param <_4> the fourth element type * @param <_5> the fifth element type * @param <_6> the sixth element type * @param <_7> the seventh element type * @param <_8> the eighth element type * @return the 8-element HList * @see Tuple8 */ public static <_1, _2, _3, _4, _5, _6, _7, _8> Tuple8<_1, _2, _3, _4, _5, _6, _7, _8> tuple(_1 _1, _2 _2, _3 _3, _4 _4, _5 _5, _6 _6, _7 _7, _8 _8) { return tuple(_2, _3, _4, _5, _6, _7, _8).cons(_1); } /** * The consing of a head element to a tail <code>HList</code>. * * @param <Head> the head element type * @param <Tail> the HList tail type */ public static class HCons<Head, Tail extends HList> extends HList { private final Head head; private final Tail tail; HCons(Head head, Tail tail) { this.head = head; this.tail = tail; } /** * The head element of the <code>HList</code>. * * @return the head element */ public Head head() { return head; } /** * The remaining tail of the <code>HList</code>; returns an HNil if this is the last element. * * @return the tail */ public Tail tail() { return tail; } @Override public <NewHead> HCons<NewHead, ? extends HCons<Head, Tail>> cons(NewHead newHead) { return new HCons<>(newHead, this); } @Override public final boolean equals(Object other) { if (other instanceof HCons) { HCons<?, ?> that = (HCons<?, ?>) other; return this.head.equals(that.head) && this.tail.equals(that.tail); } return false; } @Override public final int hashCode() { return 31 * Objects.hashCode(head) + tail.hashCode(); } } /** * The empty <code>HList</code>. */ public static final class HNil extends HList { private static final HNil INSTANCE = new HNil(); private HNil() { } @Override public <Head> SingletonHList<Head> cons(Head head) { return new SingletonHList<>(head); } } }
4,360
3,813
<gh_stars>1000+ {"annotations":{"authorization.k8s.io/decision":"allow","authorization.k8s.io/reason":""},"auditID":"155b887c-c27c-4fdb-9667-999f74512d0a","kind":"Event","level":"RequestResponse","metadata":{"creationTimestamp":"2018-10-26T13:13:03Z"},"objectRef":{"apiVersion":"v1","name":"my-config","namespace":"default","resource":"configmaps","uid":"b4952dc3-d670-11e5-8cd0-68f728db1985"},"requestObject":{"apiVersion":"v1","data":{"ui.properties":"color.good=purple\ncolor.bad=yellow\nallow.textmode=true\n"},"kind":"ConfigMap","metadata":{"creationTimestamp":"2016-02-18T18:52:05Z","name":"my-config","namespace":"default","selfLink":"/api/v1/namespaces/default/configmaps/my-config","uid":"b4952dc3-d670-11e5-8cd0-68f728db1985"}},"requestReceivedTimestamp":"2018-10-26T13:13:03.539180Z","requestURI":"/api/v1/namespaces/default/configmaps","responseObject":{"apiVersion":"v1","data":{"ui.properties":"color.good=purple\ncolor.bad=yellow\nallow.textmode=true\n"},"kind":"ConfigMap","metadata":{"creationTimestamp":"2018-10-26T13:13:03Z","name":"my-config","namespace":"default","resourceVersion":"265142","selfLink":"/api/v1/namespaces/default/configmaps/my-config","uid":"ded3abb9-d920-11e8-a2e6-080027728ac4"}},"responseStatus":{"code":201,"metadata":{}},"sourceIPs":["192.168.99.1"],"stage":"ResponseComplete","stageTimestamp":"2018-10-26T13:13:03.544952Z","timestamp":"2018-10-26T13:13:03Z","user":{"groups":["system:masters","system:authenticated"],"username":"minikube-user"},"verb":"create"}
521
1,160
#include <Python.h> #include <err.h> #include "extapi.hpp" #ifdef __NT__ #include <windows.h> #include <psapi.h> //------------------------------------------------------------------------- bool ext_api_t::load(qstring *errbuf) { QASSERT(30602, lib_path.empty() && lib_handle == nullptr); // Inspired by https://docs.microsoft.com/en-us/windows/win32/psapi/enumerating-all-modules-for-a-process HANDLE hProcess = GetCurrentProcess(); HMODULE hMods[1024]; DWORD cbNeeded; if ( EnumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded) == 0 ) return false; const void *wanted = (const void *) Py_IsInitialized; for ( size_t i = 0; i < (cbNeeded / sizeof(HMODULE)); i++ ) { MODULEINFO module_info; if ( GetModuleInformation(hProcess, hMods[i], &module_info, sizeof(module_info)) ) { if ( wanted >= module_info.lpBaseOfDll ) { LPVOID end = (LPVOID) ((const char *) module_info.lpBaseOfDll + module_info.SizeOfImage); if ( wanted < end ) { // found module lib_handle = (void *) hMods[i]; break; } } } } if ( lib_handle == nullptr ) return false; #define BIND_SYMBOL(Name) \ do \ { \ * (FARPROC *) &Name ## _ptr = GetProcAddress( \ (HMODULE) lib_handle, TEXT(#Name)); \ if ( Name ## _ptr == nullptr ) \ { \ errbuf->sprnt("GetProcAddress(\"%s\") failed: %s", \ #Name, qstrerror(-1)); \ return false; \ } \ } while ( 0 ) BIND_SYMBOL(PyEval_SetTrace); BIND_SYMBOL(PyRun_SimpleStringFlags); BIND_SYMBOL(PyRun_StringFlags); #if PY_MAJOR_VERSION < 3 BIND_SYMBOL(Py_CompileString); #else BIND_SYMBOL(Py_CompileStringExFlags); #endif BIND_SYMBOL(PyFunction_New); BIND_SYMBOL(PyFunction_GetCode); BIND_SYMBOL(_PyLong_AsByteArray); #undef BIND_SYMBOL return true; } //------------------------------------------------------------------------- void ext_api_t::clear() { lib_handle = nullptr; } #else #include <dlfcn.h> //------------------------------------------------------------------------- bool ext_api_t::load(qstring *errbuf) { QASSERT(30603, lib_path.empty() && lib_handle == nullptr); // First, let's figure out the library to load Dl_info dl_info; memset(&dl_info, 0, sizeof(dl_info)); int rc = dladdr((void *) Py_IsInitialized, &dl_info); if ( rc == 0 ) { *errbuf = "Cannot determine path to shared object"; return false; } lib_path = dl_info.dli_fname; lib_handle = dlopen(lib_path.c_str(), RTLD_NOLOAD | RTLD_GLOBAL | RTLD_LAZY); if ( lib_handle == nullptr ) { errbuf->sprnt("dlopen(\"%s\") failed: %s", lib_path.c_str(), qstrerror(-1)); return false; } #define BIND_SYMBOL(Name) \ do \ { \ Name ## _ptr = (Name ## _t *) dlsym(lib_handle, #Name); \ if ( Name ## _ptr == nullptr ) \ { \ errbuf->sprnt("dlsym(\"%s\") failed: %s", #Name, qstrerror(-1)); \ return false; \ } \ } while ( 0 ) BIND_SYMBOL(PyEval_SetTrace); BIND_SYMBOL(PyRun_SimpleStringFlags); BIND_SYMBOL(PyRun_StringFlags); #if PY_MAJOR_VERSION < 3 BIND_SYMBOL(Py_CompileString); #else BIND_SYMBOL(Py_CompileStringExFlags); #endif BIND_SYMBOL(PyFunction_New); BIND_SYMBOL(PyFunction_GetCode); BIND_SYMBOL(_PyLong_AsByteArray); #undef BIND_SYMBOL return true; } //------------------------------------------------------------------------- void ext_api_t::clear() { if ( lib_handle != nullptr ) { dlclose(lib_handle); lib_handle = nullptr; } } #endif
2,380
892
<reponame>github/advisory-database { "schema_version": "1.2.0", "id": "GHSA-c5vw-2cfj-6qf7", "modified": "2022-05-13T01:01:04Z", "published": "2022-05-13T01:01:04Z", "aliases": [ "CVE-2016-9053" ], "details": "An exploitable out-of-bounds indexing vulnerability exists within the RW fabric message particle type of Aerospike Database Server 172.16.58.3. A specially crafted packet can cause the server to fetch a function table outside the bounds of an array resulting in remote code execution. An attacker can simply connect to the port to trigger this vulnerability.", "severity": [ { "type": "CVSS_V3", "score": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H" } ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2016-9053" }, { "type": "WEB", "url": "http://www.securityfocus.com/bid/96372" }, { "type": "WEB", "url": "http://www.talosintelligence.com/reports/TALOS-2016-0267/" } ], "database_specific": { "cwe_ids": [ "CWE-129" ], "severity": "CRITICAL", "github_reviewed": false } }
517
358
//---------------------------------------------------------- -*- Mode: C++ -*- // $Id$ // // Created 2013/07/15 // Author: <NAME> // // Copyright 2013,2016 Quantcast Corporation. All rights reserved. // // This file is part of Kosmos File System (KFS). // // 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. // // \brief Ssl socket layer unit test. // //---------------------------------------------------------------------------- #include "kfsio/SslFilter.h" #include "kfsio/Globals.h" #include "kfsio/NetConnection.h" #include "kfsio/Acceptor.h" #include "kfsio/NetManager.h" #include "qcdio/qcdebug.h" #include "common/MsgLogger.h" #include "common/Properties.h" #include "common/kfsdecls.h" #include "qcdio/QCUtils.h" #include <errno.h> #include <signal.h> #include <stdio.h> #include <fcntl.h> #include <iostream> #include <string> #include <sstream> namespace KFS { using std::cerr; using std::cout; using std::string; using std::istringstream; class SslFilterTest : private IAcceptorOwner, private SslFilterServerPsk { public: static int Run( int inArgsCount, char** inArgsPtr) { signal(SIGINT, &SslFilterTest::Shutdown); signal(SIGQUIT, &SslFilterTest::Shutdown); signal(SIGPIPE, SIG_IGN); libkfsio::InitGlobals(); SslFilter::Error theErr = SslFilter::Initialize(); int theRet; if (theErr) { cerr << "SslFilter init error: " << SslFilter::GetErrorMsg(theErr) << "\n"; theRet = 1; } else { SslFilterTest theTest; theRet = theTest.RunSelf(inArgsCount, inArgsPtr); } theErr = SslFilter::Cleanup(); if (theErr) { cerr << "SslFilter cleanup error: " << SslFilter::GetErrorMsg(theErr) << "\n"; if (theRet == 0) { theRet = 1; } } libkfsio::DestroyGlobals(); return theRet; } static void Shutdown(int /* inSignal */) { if (sInstancePtr) { sInstancePtr->ShutdownSelf(); } }; private: Properties mProperties; NetManager mNetManager; Acceptor* mAcceptorPtr; SslFilter::Ctx* mSslCtxPtr; string mPskIdentity; string mPskKey; int mMaxReadAhead; int mMaxWriteBehind; bool mUseFilterFlag; static SslFilterTest* sInstancePtr; class Responder : public KfsCallbackObj { public: Responder( SslFilter::Ctx& inCtx, SslFilter::ServerPsk& inServerPsk, NetConnectionPtr& inConnectionPtr, int inMaxReadAhead, int inMaxWriteBehind, bool inUseFilterFlag) : mConnectionPtr(inConnectionPtr), mPeerName(mConnectionPtr->GetPeerName() + " "), mSslFilter( inCtx, 0, // inPskDataPtr 0, // inPskDataLen 0, // inPskCliIdendityPtr &inServerPsk, 0, // inVerifyPeerPtr false // inDeleteOnCloseFlag ), mRecursionCount(0), mCloseConnectionFlag(false), mMaxReadAhead(inMaxReadAhead), mMaxWriteBehind(inMaxWriteBehind) { QCASSERT(mConnectionPtr); SET_HANDLER(this, &Responder::EventHandler); if (inUseFilterFlag) { string theErrMsg; const int theErr = mConnectionPtr->SetFilter( &mSslFilter, &theErrMsg); if (theErr) { if (theErrMsg.empty()) { theErrMsg = QCUtils::SysError( theErr < 0 ? -theErr : theErr); } KFS_LOG_STREAM_ERROR << mPeerName << "Responder()" << " error: " << theErrMsg << KFS_LOG_EOM; mConnectionPtr->Close(); return; } } mConnectionPtr->SetMaxReadAhead(mMaxReadAhead); KFS_LOG_STREAM_DEBUG << mPeerName << "Responder()" << KFS_LOG_EOM; } virtual ~Responder() { KFS_LOG_STREAM_DEBUG << mPeerName << "~Responder()" << KFS_LOG_EOM; } int EventHandler( int inEventCode, void* inEventDataPtr) { mRecursionCount++; QCASSERT(mRecursionCount >= 1); switch (inEventCode) { case EVENT_NET_READ: { IOBuffer& theIoBuf = mConnectionPtr->GetInBuffer(); QCASSERT(&theIoBuf == inEventDataPtr); // Simple echo. mConnectionPtr->Write(&theIoBuf); break; } case EVENT_NET_WROTE: if (mCloseConnectionFlag && ! mConnectionPtr->IsWriteReady()) { mConnectionPtr->Close(); } break; case EVENT_NET_ERROR: mConnectionPtr->SetMaxReadAhead(0); if (mConnectionPtr->IsGood() && mConnectionPtr->IsWriteReady()) { mCloseConnectionFlag = mCloseConnectionFlag || ! mConnectionPtr->HasPendingRead(); break; } // Fall through case EVENT_INACTIVITY_TIMEOUT: mConnectionPtr->Close(); mConnectionPtr->GetInBuffer().Clear(); break; default: QCASSERT(!"Unexpected event code"); break; } QCASSERT(mRecursionCount >= 1); if (mRecursionCount <= 1) { mConnectionPtr->StartFlush(); if (mConnectionPtr->IsGood()) { const int kIoTimeout = 60; const int kIdleTimeout = 600; mConnectionPtr->SetInactivityTimeout( mConnectionPtr->IsWriteReady() ? kIoTimeout : kIdleTimeout); if (mConnectionPtr->IsReadReady()) { if (IsOverWriteBehindLimit()) { // Shut down read until client unloads the data. mConnectionPtr->SetMaxReadAhead(0); } } else { if (! mCloseConnectionFlag && ! IsOverWriteBehindLimit()) { // Set read back again. mConnectionPtr->SetMaxReadAhead(mMaxReadAhead); } } } else { delete this; return 0; } } mRecursionCount--; return 0; } private: NetConnectionPtr const mConnectionPtr; string const mPeerName; SslFilter mSslFilter; int mRecursionCount; bool mCloseConnectionFlag; const int mMaxReadAhead; const int mMaxWriteBehind; bool IsOverWriteBehindLimit() const { return (mConnectionPtr->GetNumBytesToWrite() > mMaxWriteBehind); } private: Responder( const Responder& inResponder); Responder& operator=( const Responder& inResponder); }; class Initiator { public: Initiator( int inInputFd, int inOutputFd, SslFilter::Ctx& inCtx, const string& inPsk, const string& inIdentity, const ServerLocation& inServerLocation, int inMaxReadAhead, int inMaxWriteBehind, bool inShutdownFlag, bool inUserFilterFlag, NetManager& inNetManager) : mConnectionPtr(), mSslFilter( inCtx, inPsk.data(), inPsk.size(), inIdentity.c_str(), 0, // inServerPskPtr 0, // inVerifyPeerPtr false // inDeleteOnCloseFlag ), mServerLocation(inServerLocation), mRecursionCount(0), mInputSocket(inInputFd), mOutputSocket(inOutputFd), mInputConnectionPtr(), mOutputConnectionPtr(), mCloseConnectionFlag(false), mMaxReadAhead(inMaxReadAhead), mMaxWriteBehind(inMaxWriteBehind), mShutdownFlag(inShutdownFlag), mUseFilterFlag(inUserFilterFlag), mNetManager(inNetManager), mInputCB(), mOutputCB(), mNetCB() { QCASSERT(mInputSocket.IsGood()); QCASSERT(mOutputSocket.IsGood()); if (fcntl(inInputFd, F_SETFL, O_NONBLOCK)) { const int theErr = errno; KFS_LOG_STREAM_ERROR << "input set non block: " << QCUtils::SysError(theErr) << KFS_LOG_EOM; } if (fcntl(inOutputFd, F_SETFL, O_NONBLOCK)) { const int theErr = errno; KFS_LOG_STREAM_ERROR << "output set non block: " << QCUtils::SysError(theErr) << KFS_LOG_EOM; } mInputCB.SetHandler(this, &Initiator::InputHandler); mOutputCB.SetHandler(this, &Initiator::OutputHandler); mNetCB.SetHandler(this, &Initiator::NetHandler); const bool kOwnsSocketFlag = false; const bool kListenOnlyFlag = false; mInputConnectionPtr.reset(new NetConnection( &mInputSocket, &mInputCB, kListenOnlyFlag, kOwnsSocketFlag)); mOutputConnectionPtr.reset(new NetConnection( &mOutputSocket, &mOutputCB, kListenOnlyFlag, kOwnsSocketFlag)); mInputConnectionPtr->SetMaxReadAhead(mMaxReadAhead); mOutputConnectionPtr->SetMaxReadAhead(0); } ~Initiator() { mInputConnectionPtr->Close(); mOutputConnectionPtr->Close(); if (mShutdownFlag) { mNetManager.Shutdown(); } } bool Connect( string* inErrMsgPtr) { const bool theNonBlockingFlag = true; TcpSocket& theSocket = *(new TcpSocket()); const int theErr = theSocket.Connect( mServerLocation, theNonBlockingFlag); if (theErr && theErr != -EINPROGRESS) { if (inErrMsgPtr) { *inErrMsgPtr = QCUtils::SysError(-theErr); } KFS_LOG_STREAM_ERROR << "failed to connect to server " << mServerLocation.ToString() << " : " << QCUtils::SysError(-theErr) << KFS_LOG_EOM; delete &theSocket; return false; } KFS_LOG_STREAM_DEBUG << "connecting to server: " << mServerLocation.ToString() << KFS_LOG_EOM; mConnectionPtr.reset(new NetConnection(&theSocket, &mNetCB)); mConnectionPtr->EnableReadIfOverloaded(); mConnectionPtr->SetDoingNonblockingConnect(); mConnectionPtr->SetMaxReadAhead(mMaxReadAhead); const int kConnectTimeout = 120; mConnectionPtr->SetInactivityTimeout(kConnectTimeout); // Add connection to the poll vector mNetManager.AddConnection(mConnectionPtr); mNetManager.AddConnection(mInputConnectionPtr); mNetManager.AddConnection(mOutputConnectionPtr); return true; } int InputHandler( int inEventCode, void* inEventDataPtr) { mRecursionCount++; QCASSERT(mRecursionCount >= 1); switch (inEventCode) { case EVENT_NET_READ: { IOBuffer& theIoBuf = mInputConnectionPtr->GetInBuffer(); QCASSERT(&theIoBuf == inEventDataPtr); mConnectionPtr->Write(&theIoBuf); break; } case EVENT_NET_ERROR: // Fall through case EVENT_INACTIVITY_TIMEOUT: KFS_LOG_STREAM_ERROR << "input: " << (inEventCode == EVENT_INACTIVITY_TIMEOUT ? string("input timed out") : (mInputConnectionPtr->IsGood() ? string("EOF") : QCUtils::SysError(errno, "")) ) << KFS_LOG_EOM; mCloseConnectionFlag = true; mInputConnectionPtr->Close(); mInputConnectionPtr->GetInBuffer().Clear(); if (! mConnectionPtr->IsWriteReady()) { mConnectionPtr->Close(); } if (! mOutputConnectionPtr->IsWriteReady()) { mOutputConnectionPtr->Close(); } break; default: QCASSERT(!"Unexpected event code"); break; } return FlowControl(); } int OutputHandler( int inEventCode, void* inEventDataPtr) { mRecursionCount++; QCASSERT(mRecursionCount >= 1); switch (inEventCode) { case EVENT_NET_WROTE: if (mCloseConnectionFlag && ! mOutputConnectionPtr->IsWriteReady()) { mOutputConnectionPtr->Close(); } break; case EVENT_NET_ERROR: // Fall through case EVENT_INACTIVITY_TIMEOUT: KFS_LOG_STREAM_ERROR << "output: " << (inEventCode == EVENT_INACTIVITY_TIMEOUT ? string("input timed out") : QCUtils::SysError(errno, "")) << KFS_LOG_EOM; mCloseConnectionFlag = true; mOutputConnectionPtr->Close(); break; default: QCASSERT(!"Unexpected event code"); break; } return FlowControl(); } int NetHandler( int inEventCode, void* inEventDataPtr) { mRecursionCount++; QCASSERT(mRecursionCount >= 1); switch (inEventCode) { case EVENT_NET_READ: { IOBuffer& theIoBuf = mConnectionPtr->GetInBuffer(); QCASSERT(&theIoBuf == inEventDataPtr); mOutputConnectionPtr->Write(&theIoBuf); break; } case EVENT_NET_WROTE: if (mUseFilterFlag && ! mConnectionPtr->GetFilter()) { string theErrMsg; const int theErr = mConnectionPtr->SetFilter( &mSslFilter, &theErrMsg); if (theErr) { if (theErrMsg.empty()) { theErrMsg = QCUtils::SysError( theErr < 0 ? -theErr : theErr); } KFS_LOG_STREAM_ERROR << mConnectionPtr->GetPeerName() << " Initiator" << " error: " << theErrMsg << KFS_LOG_EOM; mConnectionPtr->Close(); break; } } if (mCloseConnectionFlag && ! mConnectionPtr->IsWriteReady()) { mConnectionPtr->Close(); } break; case EVENT_NET_ERROR: mConnectionPtr->SetMaxReadAhead(0); if (mConnectionPtr->IsGood() && mConnectionPtr->IsWriteReady()) { mCloseConnectionFlag = mCloseConnectionFlag || ! mConnectionPtr->HasPendingRead(); break; } // Fall through case EVENT_INACTIVITY_TIMEOUT: mConnectionPtr->Close(); mConnectionPtr->GetInBuffer().Clear(); break; default: QCASSERT(!"Unexpected event code"); break; } return FlowControl(); } private: NetConnectionPtr mConnectionPtr; SslFilter mSslFilter; ServerLocation const mServerLocation; int mRecursionCount; TcpSocket mInputSocket; TcpSocket mOutputSocket; NetConnectionPtr mInputConnectionPtr; NetConnectionPtr mOutputConnectionPtr; bool mCloseConnectionFlag; const int mMaxReadAhead; const int mMaxWriteBehind; const bool mShutdownFlag; const bool mUseFilterFlag; NetManager& mNetManager; KfsCallbackObj mInputCB; KfsCallbackObj mOutputCB; KfsCallbackObj mNetCB; bool IsOverWriteBehindLimit() const { return ( mOutputConnectionPtr->GetNumBytesToWrite() > mMaxWriteBehind); } bool IsInputOverWriteBehindLimit() const { return (mConnectionPtr->GetNumBytesToWrite() > mMaxWriteBehind); } int FlowControl() { if (mRecursionCount > 1) { mRecursionCount--; return 0; } QCASSERT(mRecursionCount >= 1); mConnectionPtr->StartFlush(); if (mConnectionPtr->IsGood()) { const int kIoTimeout = 60; const int kIdleTimeout = 600; mConnectionPtr->SetInactivityTimeout( mConnectionPtr->IsWriteReady() ? kIoTimeout : kIdleTimeout); if (mConnectionPtr->IsReadReady()) { if (IsOverWriteBehindLimit()) { // Shut down read until client unloads the data. mConnectionPtr->SetMaxReadAhead(0); } } else { if (! mCloseConnectionFlag && ! IsOverWriteBehindLimit()) { // Set read back again. mConnectionPtr->SetMaxReadAhead(mMaxReadAhead); } } if (mInputConnectionPtr->IsReadReady()) { if (IsInputOverWriteBehindLimit()) { // Shut down read until client unloads the data. mInputConnectionPtr->SetMaxReadAhead(0); } } else { if (! mCloseConnectionFlag && ! IsInputOverWriteBehindLimit()) { // Set read back again. mInputConnectionPtr->SetMaxReadAhead(mMaxReadAhead); } } } else { delete this; return 0; } QCASSERT(mRecursionCount >= 1); mRecursionCount--; return 0; } private: Initiator( const Initiator& inInitiator); Initiator& operator=( const Initiator& inInitiator); }; SslFilterTest() : IAcceptorOwner(), SslFilterServerPsk(), mProperties(), mNetManager(), mAcceptorPtr(0), mSslCtxPtr(0), mPskIdentity("testid"), mPskKey("test"), mMaxReadAhead((8 << 10) - 1), mMaxWriteBehind((8 << 10) - 1), mUseFilterFlag(true) {} virtual ~SslFilterTest() { delete mAcceptorPtr; SslFilter::FreeCtx(mSslCtxPtr); } int RunSelf( int inArgsCount, char** inArgsPtr) { delete mAcceptorPtr; mAcceptorPtr = 0; string thePropsStr; const char kDelim = '='; for (int i = 1; i < inArgsCount; ++i) { if (strcmp(inArgsPtr[i], "-c") == 0) { if (inArgsCount <= ++i) { Usage(inArgsPtr[0]); return 1; } if (mProperties.loadProperties( inArgsPtr[i], kDelim, &cout)) { cerr << "error reading properties file: " << inArgsPtr[i] << "\n"; return 1; } } else if (strcmp(inArgsPtr[i], "-D") == 0) { if (inArgsCount <= ++i) { Usage(inArgsPtr[0]); return 1; } thePropsStr += inArgsPtr[i]; thePropsStr += "\n"; } else { Usage(inArgsPtr[0]); return 1; } } if (! thePropsStr.empty()) { istringstream theInStream(thePropsStr); if (mProperties.loadProperties( theInStream, kDelim, &cout)) { cerr << "error parsing arguments\n"; return 1; } } MsgLogger::Init(mProperties, "sslFilterTest."); if (! MsgLogger::GetLogger()) { cerr << "messsage logger initialization failure\n"; return 1; } const int kCommPort = 14188; const int theAcceptPort = mProperties.getValue( "sslFilterTest.acceptor.port", kCommPort); mPskKey = mProperties.getValue( "sslFilterTest.psk.key", mPskKey); mPskIdentity = mProperties.getValue( "sslFilterTest.psk.id", mPskIdentity); mMaxReadAhead = mProperties.getValue( "sslFilterTest.maxReadAhead", mMaxReadAhead); mMaxWriteBehind = mProperties.getValue( "sslFilterTest.maxWriteBehind", mMaxWriteBehind); mUseFilterFlag = mProperties.getValue( "sslFilterTest.useFilter", mUseFilterFlag ? 0 : 1) != 0; int theRet = 0; if (0 <= theAcceptPort) { const bool kServerFlag = true; const bool kPskOnlyFlag = true; string theErrMsg; if (! (mSslCtxPtr = SslFilter::CreateCtx( kServerFlag, kPskOnlyFlag, "sslFilterTest.", mProperties, &theErrMsg ))) { KFS_LOG_STREAM_ERROR << "create server ssl context error: " << theErrMsg << KFS_LOG_EOM; theRet = 1; } else { mAcceptorPtr = new Acceptor(mNetManager, theAcceptPort, this); if (! mAcceptorPtr->IsAcceptorStarted()) { KFS_LOG_STREAM_ERROR << "listen: port: " << theAcceptPort << ": " << QCUtils::SysError(errno) << KFS_LOG_EOM; theRet = 1; } } } SslFilter::Ctx* theSslCtxPtr = 0; if (theRet == 0) { const ServerLocation theServerLocation( mProperties.getValue("sslFilterTest.connect.host", string("127.0.0.1")), mProperties.getValue("sslFilterTest.connect.port", kCommPort) ); if (theServerLocation.IsValid()) { const bool kServerFlag = false; const bool kPskOnlyFlag = true; string theErrMsg; if (! (theSslCtxPtr = SslFilter::CreateCtx( kServerFlag, kPskOnlyFlag, "sslFilterTest.", mProperties, &theErrMsg ))) { KFS_LOG_STREAM_ERROR << "create client ssl context error: " << theErrMsg << KFS_LOG_EOM; theRet = 1; } else { Initiator* const theClientPtr = new Initiator( fileno(stdin), //inInputFd, fileno(stdout), // inOutputFd, *theSslCtxPtr, mPskKey, mPskIdentity, theServerLocation, mMaxReadAhead, mMaxWriteBehind, ! mAcceptorPtr, // Shutdown if no acceptor. mUseFilterFlag, mNetManager ); if (! theClientPtr->Connect(&theErrMsg)) { KFS_LOG_STREAM_ERROR << "connect to server error: " << theErrMsg << KFS_LOG_EOM; theRet = 1; delete theClientPtr; } } } } if (theRet == 0) { sInstancePtr = this; mNetManager.MainLoop(); sInstancePtr = 0; } SslFilter::FreeCtx(theSslCtxPtr); MsgLogger::Stop(); return 0; } void ShutdownSelf() { mNetManager.Shutdown(); } void Usage( const char* inNamePtr) { cerr << "Usage " << (inNamePtr ? inNamePtr : "") << ":\n" " -c <config file name>\n" " -D config-key=config-value\n" ; } virtual KfsCallbackObj* CreateKfsCallbackObj( NetConnectionPtr& inConnPtr) { return (mSslCtxPtr ? new Responder( *mSslCtxPtr, *this, inConnPtr, mMaxReadAhead, mMaxWriteBehind, mUseFilterFlag ) : 0); } virtual unsigned long GetPsk( const char* inIdentityPtr, unsigned char* inPskBufferPtr, unsigned int inPskBufferLen, string& outAuthName) { KFS_LOG_STREAM_DEBUG << "GetPsk:" " identity: " << (inIdentityPtr ? inIdentityPtr : "null") << " buffer: " << (const void*)inPskBufferPtr << " buflen: " << inPskBufferLen << KFS_LOG_EOM; if (inPskBufferLen <= mPskKey.size()) { return 0; } if (mPskIdentity != (inIdentityPtr ? inIdentityPtr : "")) { return 0; } memcpy(inPskBufferPtr, mPskKey.data(), mPskKey.size()); outAuthName = "test"; return mPskKey.size(); } private: SslFilterTest( const SslFilterTest& inTest); SslFilterTest& operator=( const SslFilterTest& inTest); }; SslFilterTest* SslFilterTest::sInstancePtr = 0; } int main( int inArgsCount, char** inArgsPtr) { return KFS::SslFilterTest::Run(inArgsCount, inArgsPtr); }
16,514
2,787
<reponame>Son-Le-Goog/nimbus<gh_stars>1000+ // // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <UIKit/UIKit.h> #import "NimbusPagingScrollView.h" /** * A single page in a launcher view. * * This is a recyclable page view that can be used with NIPagingScrollView. * * Each launcher page contains a set of views. The page lays out each of the views in a grid based * on the given display attributes. * * Views will be laid out from left to right and then from top to bottom. * * @ingroup NimbusLauncher */ @interface NILauncherPageView : NIPagingScrollViewPage @property (nonatomic, strong) NIViewRecycler* viewRecycler; - (void)addRecyclableView:(UIView<NIRecyclableView> *)view; @property (nonatomic, readonly, strong) NSArray* recyclableViews; @property (nonatomic, assign) UIEdgeInsets contentInset; @property (nonatomic, assign) CGSize viewSize; @property (nonatomic, assign) CGSize viewMargins; @end /** @name Recyclable Views */ /** * A shared view recycler for this page's recyclable views. * * When this page view is preparing for reuse it will add each of its button views to the recycler. * This recycler should be the same recycler used by all pages in the launcher view. * * @fn NILauncherPageView::viewRecycler */ /** * Add a recyclable view to this page. * * @param view A recyclable view. * @fn NILauncherPageView::addRecyclableView: */ /** * All of the recyclable views that have been added to this page. * * @returns An array of recyclable views in the same order in which they were added. * @fn NILauncherPageView::recyclableViews */ /** @name Configuring Display Attributes */ /** * The distance that the recyclable views are inset from the enclosing view. * * Use this property to add to the area around the content. The unit of size is points. * The default value is UIEdgeInsetsZero. * * @fn NILauncherPageView::contentInset */ /** * The size of each recyclable view. * * The unit of size is points. The default value is CGSizeZero. * * @fn NILauncherPageView::viewSize */ /** * The recommended horizontal and vertical distance between each recyclable view. * * This property is only a recommended value because the page view does its best to distribute the * views in a way that visually balances them. * * Width is the horizontal distance between each view. Height is the vertical distance between each * view. The unit of size is points. The default value is CGSizeZero. * * @fn NILauncherPageView::viewMargins */
890
318
/* * This file is part of TechReborn, licensed under the MIT License (MIT). * * Copyright (c) 2020 TechReborn * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package techreborn.api.recipe; import net.minecraft.block.entity.BlockEntity; import net.minecraft.item.ItemStack; import reborncore.common.crafting.RebornRecipe; import reborncore.common.recipes.RecipeCrafter; import reborncore.common.util.RebornInventory; import techreborn.config.TechRebornConfig; import techreborn.init.ModRecipes; import java.util.List; import java.util.Objects; public class RecyclerRecipeCrafter extends RecipeCrafter { public RecyclerRecipeCrafter(BlockEntity blockEntity, RebornInventory<?> inventory, int[] inputSlots, int[] outputSlots) { super(ModRecipes.RECYCLER, blockEntity, 1, 1, inventory, inputSlots, outputSlots); } @Override public void updateCurrentRecipe() { currentTickTime = 0; List<RebornRecipe> recipeList = ModRecipes.RECYCLER.getRecipes(blockEntity.getWorld()); if (recipeList.isEmpty() || !hasAllInputs()) { setCurrentRecipe(null); currentNeededTicks = 0; setIsActive(); return; } setCurrentRecipe(recipeList.get(0)); currentNeededTicks = Math.max((int) (currentRecipe.getTime() * (1.0 - getSpeedMultiplier())), 1); setIsActive(); } @Override public boolean hasAllInputs() { boolean hasItem = false; // Check if we have at least something in input slots. Foreach input slot in case of several input slots for (int inputSlot : inputSlots) { if (inventory.getStack(inputSlot).isEmpty()) continue; hasItem = true; break; } return hasItem; } @Override public void useAllInputs() { if (currentRecipe == null) { return; } // Uses input. Foreach input slot in case of several input slots for (int inputSlot : inputSlots) { if (inventory.getStack(inputSlot).isEmpty()) continue; inventory.shrinkSlot(inputSlot, 1); break; } } @Override public void fitStack(ItemStack stack, int slot) { // Dirty hack for chance based crafting final int randomChance = Objects.requireNonNull(blockEntity.getWorld()).random.nextInt(TechRebornConfig.recyclerChance); if (randomChance == 1) { super.fitStack(stack, slot); } } }
1,011
461
<gh_stars>100-1000 /* FUNCTION <<toascii>>, <<toascii_l>>---force integers to ASCII range INDEX toascii INDEX toascii_l SYNOPSIS #include <ctype.h> int toascii(int <[c]>); #include <ctype.h> int toascii_l(int <[c]>, locale_t <[locale]>); DESCRIPTION <<toascii>> is a macro which coerces integers to the ASCII range (0--127) by zeroing any higher-order bits. <<toascii_l>> is like <<toascii>> but performs the function based on the locale specified by the locale object locale. If <[locale]> is LC_GLOBAL_LOCALE or not a valid locale object, the behaviour is undefined. You can use a compiled subroutine instead of the macro definition by undefining this macro using `<<#undef toascii>>' or `<<#undef toascii_l>>'. RETURNS <<toascii>>, <<toascii_l>> return integers between 0 and 127. PORTABILITY <<toascii>> is X/Open, BSD and POSIX-1.2001, but marked obsolete in POSIX-1.2008. <<toascii_l>> is a GNU extension. No supporting OS subroutines are required. */ #include <_ansi.h> #include <ctype.h> #undef toascii int toascii (int c) { return (c)&0177; }
421